Skip to main content

euv_cli/builder/apple/
fn.rs

1use super::*;
2
3/// Renders the universal iOS and iPadOS `Info.plist` with dynamic version and bundle identifier.
4///
5/// # Arguments
6///
7/// - `&str` - Semantic version written to `CFBundleShortVersionString`.
8/// - `&str` - Monotonic build number written to `CFBundleVersion`.
9/// - `&str` - Application `CFBundleIdentifier` (for example `vip.ltpp.euv.showcase`).
10///
11/// # Returns
12///
13/// - `String` - Complete XML `Info.plist` contents.
14#[must_use]
15pub fn render_ios_info_plist(version: &str, build_number: &str, bundle_id: &str) -> String {
16    format!(
17        "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n\
18<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n\
19<plist version=\"1.0\">\n\
20<dict>\n\
21    <key>CFBundleDevelopmentRegion</key><string>en</string>\n\
22    <key>CFBundleDisplayName</key><string>Euv Studio</string>\n\
23    <key>CFBundleExecutable</key><string>EuvShowcase</string>\n\
24    <key>CFBundleIconFiles</key>\n\
25    <array>\n\
26        <string>AppIcon60x60@2x.png</string>\n\
27        <string>AppIcon60x60@3x.png</string>\n\
28        <string>AppIcon.png</string>\n\
29    </array>\n\
30    <key>CFBundleIcons</key>\n\
31    <dict>\n\
32        <key>CFBundlePrimaryIcon</key>\n\
33        <dict>\n\
34            <key>CFBundleIconFiles</key>\n\
35            <array>\n\
36                <string>AppIcon60x60</string>\n\
37            </array>\n\
38        </dict>\n\
39    </dict>\n\
40    <key>CFBundleIdentifier</key><string>{bundle_id}</string>\n\
41    <key>CFBundleInfoDictionaryVersion</key><string>6.0</string>\n\
42    <key>CFBundleName</key><string>Euv Studio</string>\n\
43    <key>CFBundlePackageType</key><string>APPL</string>\n\
44    <key>CFBundleShortVersionString</key><string>{version}</string>\n\
45    <key>CFBundleVersion</key><string>{build_number}</string>\n\
46    <key>CFBundleURLTypes</key>\n\
47    <array>\n\
48        <dict>\n\
49            <key>CFBundleURLName</key><string>{bundle_id}</string>\n\
50            <key>CFBundleURLSchemes</key>\n\
51            <array>\n\
52                <string>euv</string>\n\
53            </array>\n\
54        </dict>\n\
55    </array>\n\
56    <key>CADisableMinimumFrameDurationOnPhone</key><true/>\n\
57    <key>LSRequiresIPhoneOS</key><true/>\n\
58    <key>NSAppTransportSecurity</key>\n\
59    <dict>\n\
60        <key>NSAllowsArbitraryLoads</key><true/>\n\
61        <key>NSAllowsLocalNetworking</key><true/>\n\
62    </dict>\n\
63    <key>UIApplicationSceneManifest</key>\n\
64    <dict>\n\
65        <key>UIApplicationSupportsMultipleScenes</key><true/>\n\
66        <key>UISceneConfigurations</key>\n\
67        <dict>\n\
68            <key>UIWindowSceneSessionRoleApplication</key>\n\
69            <array>\n\
70                <dict>\n\
71                    <key>UISceneConfigurationName</key><string>Default Configuration</string>\n\
72                    <key>UISceneDelegateClassName</key><string>EuvSceneDelegate</string>\n\
73                </dict>\n\
74            </array>\n\
75        </dict>\n\
76    </dict>\n\
77    <key>UIApplicationSupportsIndirectInputEvents</key><true/>\n\
78    <key>NSMotionUsageDescription</key><string>Motion sensors drive physically accurate liquid water gravity and sloshing simulation.</string>\n\
79    <key>UIDeviceFamily</key>\n\
80    <array>\n\
81        <integer>1</integer>\n\
82        <integer>2</integer>\n\
83    </array>\n\
84    <key>UIRequiresFullScreen</key><false/>\n\
85    <key>UILaunchScreen</key><dict/>\n\
86    <key>UISupportedInterfaceOrientations</key>\n\
87    <array>\n\
88        <string>UIInterfaceOrientationPortrait</string>\n\
89        <string>UIInterfaceOrientationLandscapeLeft</string>\n\
90        <string>UIInterfaceOrientationLandscapeRight</string>\n\
91    </array>\n\
92    <key>UISupportedInterfaceOrientations~ipad</key>\n\
93    <array>\n\
94        <string>UIInterfaceOrientationPortrait</string>\n\
95        <string>UIInterfaceOrientationPortraitUpsideDown</string>\n\
96        <string>UIInterfaceOrientationLandscapeLeft</string>\n\
97        <string>UIInterfaceOrientationLandscapeRight</string>\n\
98    </array>\n\
99</dict>\n\
100</plist>\n"
101    )
102}
103
104/// Renders the standalone Apple watchOS `Info.plist` with dynamic version and bundle identifier.
105///
106/// # Arguments
107///
108/// - `&str` - Semantic version written to `CFBundleShortVersionString`.
109/// - `&str` - Monotonic build number written to `CFBundleVersion`.
110/// - `&str` - Application `CFBundleIdentifier`.
111///
112/// # Returns
113///
114/// - `String` - Complete XML `Info.plist` contents for watchOS.
115#[must_use]
116pub fn render_watchos_info_plist(version: &str, build_number: &str, bundle_id: &str) -> String {
117    format!(
118        "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n\
119<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n\
120<plist version=\"1.0\">\n\
121<dict>\n\
122  <key>CFBundleExecutable</key>\n\
123  <string>EuvWatch</string>\n\
124  <key>CFBundleIdentifier</key>\n\
125  <string>{bundle_id}</string>\n\
126  <key>CFBundleDisplayName</key>\n\
127  <string>Euv Watch</string>\n\
128  <key>CFBundleShortVersionString</key>\n\
129  <string>{version}</string>\n\
130  <key>CFBundleVersion</key>\n\
131  <string>{build_number}</string>\n\
132  <key>WKApplication</key>\n\
133  <true/>\n\
134  <key>WKRunsIndependentlyOfCompanionApp</key>\n\
135  <true/>\n\
136</dict>\n\
137</plist>\n"
138    )
139}
140
141/// Generates the standalone Apple host crate (`staticlib`), Objective-C/Swift entry files, `Info.plist`, and icons.
142///
143/// # Arguments
144///
145/// - `&AppleBuildConfig` - Apple build configuration specifying target kind, workspace root, and output paths.
146/// - `Option<&MobileIconWriter<'_>>` - Optional callback writing PNG app icons.
147///
148/// # Returns
149///
150/// - `io::Result<AppleBuildReport>` - Summary of generated host files and bundle destination.
151pub fn generate_apple_host_project(
152    config: &AppleBuildConfig,
153    icon_writer: Option<&MobileIconWriter<'_>>,
154) -> io::Result<AppleBuildReport> {
155    let workspace_root: PathBuf = resolve_absolute_path(config.get_workspace_root());
156    let target_kind: AppleTargetKind = config.get_target_kind();
157    let version: String = config
158        .try_get_app_version()
159        .clone()
160        .unwrap_or_else(|| resolve_workspace_semver(&workspace_root));
161    let build_num: u32 = config
162        .try_get_build_number()
163        .unwrap_or_else(|| compute_semver_version_code(&version));
164    let build_number: String = build_num.to_string();
165    let bundle_id: String = config
166        .try_get_bundle_id()
167        .clone()
168        .unwrap_or_else(|| target_kind.default_bundle_id().to_string());
169    let build_dir: PathBuf = config.try_get_build_dir().clone().unwrap_or_else(|| {
170        workspace_root
171            .join(MOBILE_HOSTS_SUBDIR)
172            .join(target_kind.host_dir_name())
173    });
174    let out_dir: PathBuf = config.try_get_out_dir().clone().unwrap_or_else(|| {
175        workspace_root
176            .join(MOBILE_DIST_DIR_NAME)
177            .join(target_kind.default_out_subdir())
178    });
179    let app_bundle: PathBuf = out_dir.join(target_kind.default_bundle_name());
180    fs::create_dir_all(build_dir.join(MOBILE_DIR_SRC))?;
181    fs::create_dir_all(&out_dir)?;
182    let report: AppleBuildReport = AppleBuildReport {
183        target_kind: target_kind.as_label().to_string(),
184        rust_triple: target_kind.rust_triple().to_string(),
185        version,
186        build_number,
187        build_dir,
188        app_bundle_path: app_bundle,
189        archive_path: config.try_get_archive_path().clone(),
190        binary_bytes: 0,
191        ai_schema_clean: true,
192        launched: false,
193    };
194    if target_kind.is_watchos() {
195        generate_watchos_host_files(&workspace_root, &out_dir, &bundle_id, &report, icon_writer)?;
196    } else {
197        generate_ios_host_files(
198            &workspace_root,
199            config.get_render_mode(),
200            &bundle_id,
201            &report,
202            icon_writer,
203        )?;
204    }
205    Ok(report)
206}
207
208/// Builds, strips, signs, verifies, optionally archives, and optionally launches an Apple `.app` bundle.
209///
210/// # Arguments
211///
212/// - `&AppleBuildConfig` - Complete Apple build, signing, archiving, and Simulator launch config.
213/// - `Option<&MobileIconWriter<'_>>` - Optional callback writing PNG app icons.
214///
215/// # Returns
216///
217/// - `io::Result<AppleBuildReport>` - Detailed build report including compiled binary size and archive path.
218pub fn build_apple_bundle(
219    config: &AppleBuildConfig,
220    icon_writer: Option<&MobileIconWriter<'_>>,
221) -> io::Result<AppleBuildReport> {
222    let generated: AppleBuildReport = generate_apple_host_project(config, icon_writer)?;
223    if config.get_shell_only() {
224        return Ok(generated);
225    }
226    if consts::OS != MOBILE_HOST_OS_MACOS {
227        return Err(Error::new(ErrorKind::Unsupported, ERR_APPLE_REQUIRES_MACOS));
228    }
229    let target_kind: AppleTargetKind = config.get_target_kind();
230    let sdk_path: String = resolve_xcode_sdk_path(target_kind.xcode_sdk())?;
231    let build_dir: &Path = generated.get_build_dir();
232    let app_bundle: &Path = generated.get_app_bundle_path();
233    let exec_path: PathBuf = app_bundle.join(target_kind.default_executable_name());
234    if target_kind.is_watchos() {
235        compile_and_link_watchos(config, &sdk_path, build_dir, app_bundle, &exec_path)?;
236    } else {
237        compile_and_link_ios(config, &sdk_path, build_dir, app_bundle, &exec_path)?;
238    }
239    if config.get_release() {
240        assert_release_binary_ai_schema_clean(&exec_path)?;
241    }
242    let binary_bytes: u64 = fs::metadata(&exec_path)?.len();
243    let archive_path: Option<PathBuf> = config.try_get_archive_path().clone();
244    if let Some(archive_dst) = archive_path.as_deref() {
245        archive_apple_bundle_tar_gz(app_bundle, archive_dst)?;
246    }
247    let skip_env: bool = env::var(ENV_EUV_IOS_SKIP_LAUNCH)
248        .map(|val: String| val.trim() == "1")
249        .unwrap_or(false);
250    let launched: bool = if !config.get_no_launch()
251        && !skip_env
252        && target_kind.is_simulator()
253        && !target_kind.is_watchos()
254    {
255        let bundle_id: String = config
256            .try_get_bundle_id()
257            .clone()
258            .unwrap_or_else(|| target_kind.default_bundle_id().to_string());
259        launch_ios_simulator_bundle(config, app_bundle, &bundle_id)?;
260        true
261    } else {
262        false
263    };
264    Ok(AppleBuildReport {
265        target_kind: generated.get_target_kind().clone(),
266        rust_triple: generated.get_rust_triple().clone(),
267        version: generated.get_version().clone(),
268        build_number: generated.get_build_number().clone(),
269        build_dir: generated.get_build_dir().clone(),
270        app_bundle_path: app_bundle.to_path_buf(),
271        archive_path,
272        binary_bytes,
273        ai_schema_clean: true,
274        launched,
275    })
276}
277
278/// Writes the standalone iOS/iPadOS host crate, `main.m`, `Info.plist`, and bundle icons.
279///
280/// # Arguments
281///
282/// - `&Path` - Absolute workspace root path.
283/// - `RenderArg` - Selected default render pipeline mode.
284/// - `&str` - Bundle identifier string.
285/// - `&AppleBuildReport` - Resolved build directories, version, and build number metadata.
286/// - `Option<&MobileIconWriter<'_>>` - Optional icon writer callback.
287///
288/// # Returns
289///
290/// - `io::Result<()>` - Host generation outcome.
291fn generate_ios_host_files(
292    workspace_root: &Path,
293    render_mode: RenderArg,
294    bundle_id: &str,
295    report: &AppleBuildReport,
296    icon_writer: Option<&MobileIconWriter<'_>>,
297) -> io::Result<()> {
298    let build_dir: &Path = report.get_build_dir();
299    let app_bundle: &Path = report.get_app_bundle_path();
300    let version: &str = report.get_version();
301    let build_number: &str = report.get_build_number();
302    let render_expr: &str = render_mode_const_expr(render_mode);
303    let host_config: String = format!(
304        "use euv::RenderMode;\n\n\
305pub const HOST_RENDER_MODE: RenderMode = {render_expr};\n"
306    );
307    let root_escaped: String = escape_toml_path(workspace_root);
308    let example_escaped: String = escape_toml_path(&workspace_root.join(MOBILE_DIR_EXAMPLE));
309    let cargo_toml: String = format!(
310        "[workspace]\n\n\
311[package]\n\
312name = \"euv-ios-host\"\n\
313version = \"{version}\"\n\
314edition = \"2024\"\n\n\
315[lib]\n\
316crate-type = [\"staticlib\"]\n\n\
317[dependencies]\n\
318euv = {{ path = \"{root_escaped}\" }}\n\
319euv-example = {{ path = \"{example_escaped}\" }}\n\n\
320[profile.release]\n\
321opt-level = 3\n\
322lto = \"thin\"\n\
323codegen-units = 1\n\
324panic = \"abort\"\n"
325    );
326    let info_plist: String = render_ios_info_plist(version, build_number, bundle_id);
327    fs::write(
328        build_dir
329            .join(MOBILE_DIR_SRC)
330            .join(MOBILE_FILE_HOST_CONFIG_RS),
331        host_config,
332    )?;
333    fs::write(build_dir.join(MOBILE_FILE_CARGO_TOML), cargo_toml)?;
334    fs::write(
335        build_dir.join(MOBILE_DIR_SRC).join(MOBILE_FILE_LIB_RS),
336        APPLE_IOS_HOST_LIB_RS_TEMPLATE,
337    )?;
338    fs::write(
339        build_dir.join(APPLE_IOS_MAIN_M_FILE),
340        APPLE_IOS_MAIN_M_TEMPLATE,
341    )?;
342    fs::write(build_dir.join(APPLE_INFO_PLIST_FILE), &info_plist)?;
343    if app_bundle.exists() {
344        fs::remove_dir_all(app_bundle)?;
345    }
346    fs::create_dir_all(app_bundle)?;
347    fs::write(app_bundle.join(APPLE_INFO_PLIST_FILE), info_plist)?;
348    for (icon_name, size_px) in APPLE_IOS_ICON_FILES.iter().copied() {
349        let icon_path: PathBuf = app_bundle.join(icon_name);
350        write_icon_or_fallback(icon_writer, &icon_path, size_px)?;
351    }
352    Ok(())
353}
354
355/// Writes the standalone Apple watchOS host crate, SwiftUI app, bridging header, `Info.plist`, and AppIcon.
356///
357/// # Arguments
358///
359/// - `&Path` - Absolute workspace root path.
360/// - `&Path` - Destination watchOS project output directory.
361/// - `&str` - Bundle identifier string.
362/// - `&AppleBuildReport` - Resolved build directories, version, and build number metadata.
363/// - `Option<&MobileIconWriter<'_>>` - Optional icon writer callback.
364///
365/// # Returns
366///
367/// - `io::Result<()>` - Host generation outcome.
368fn generate_watchos_host_files(
369    workspace_root: &Path,
370    out_dir: &Path,
371    bundle_id: &str,
372    report: &AppleBuildReport,
373    icon_writer: Option<&MobileIconWriter<'_>>,
374) -> io::Result<()> {
375    let build_dir: &Path = report.get_build_dir();
376    let version: &str = report.get_version();
377    let build_number: &str = report.get_build_number();
378    let app_src_dir: PathBuf = out_dir.join(APPLE_WATCHOS_APP_SRC_DIR);
379    let iconset_dir: PathBuf = out_dir.join(APPLE_WATCHOS_ICONSET_REL);
380    fs::create_dir_all(&app_src_dir)?;
381    fs::create_dir_all(&iconset_dir)?;
382    fs::create_dir_all(out_dir.join(APPLE_LIBS_DIR_NAME))?;
383    let root_escaped: String = escape_toml_path(workspace_root);
384    let example_escaped: String = escape_toml_path(&workspace_root.join(MOBILE_DIR_EXAMPLE));
385    let cargo_toml: String = format!(
386        "[package]\n\
387name = \"euv-watchos-host\"\n\
388version = \"{version}\"\n\
389edition = \"2024\"\n\n\
390[workspace]\n\n\
391[lib]\n\
392crate-type = [\"staticlib\"]\n\n\
393[dependencies]\n\
394euv = {{ path = \"{root_escaped}\" }}\n\
395euv-example = {{ path = \"{example_escaped}\" }}\n\n\
396[profile.release]\n\
397opt-level = \"s\"\n\
398lto = \"thin\"\n\
399codegen-units = 1\n\
400panic = \"abort\"\n"
401    );
402    let info_plist: String = render_watchos_info_plist(version, build_number, bundle_id);
403    fs::write(build_dir.join(MOBILE_FILE_CARGO_TOML), cargo_toml)?;
404    fs::write(
405        build_dir.join(MOBILE_DIR_SRC).join(MOBILE_FILE_LIB_RS),
406        APPLE_WATCHOS_HOST_LIB_RS_TEMPLATE,
407    )?;
408    fs::write(
409        app_src_dir.join(APPLE_WATCHOS_BRIDGE_H_FILE),
410        APPLE_WATCHOS_BRIDGE_H_TEMPLATE,
411    )?;
412    fs::write(
413        app_src_dir.join(APPLE_WATCHOS_SWIFT_FILE),
414        APPLE_WATCHOS_APP_SWIFT_TEMPLATE,
415    )?;
416    fs::write(app_src_dir.join(APPLE_INFO_PLIST_FILE), info_plist)?;
417    fs::write(
418        iconset_dir.join(APPLE_CONTENTS_JSON_FILE),
419        APPLE_WATCHOS_ICONSET_JSON,
420    )?;
421    write_icon_or_fallback(
422        icon_writer,
423        &iconset_dir.join(APPLE_APP_ICON_PNG_FILE),
424        APPLE_WATCHOS_ICON_SIZE,
425    )
426}
427
428/// Compiles the iOS Rust staticlib, links Objective-C `main.m` with all 10 frameworks, strips, and signs.
429///
430/// # Arguments
431///
432/// - `&AppleBuildConfig` - Apple build configuration.
433/// - `&str` - Resolved Xcode SDK path.
434/// - `&Path` - iOS host build directory.
435/// - `&Path` - Destination `.app` bundle directory.
436/// - `&Path` - Destination executable path inside `app_bundle`.
437///
438/// # Returns
439///
440/// - `io::Result<()>` - Compilation, linking, and signing outcome.
441fn compile_and_link_ios(
442    config: &AppleBuildConfig,
443    sdk_path: &str,
444    build_dir: &Path,
445    app_bundle: &Path,
446    exec_path: &Path,
447) -> io::Result<()> {
448    let target_kind: AppleTargetKind = config.get_target_kind();
449    let triple: &str = target_kind.rust_triple();
450    let mut cargo_args: Vec<&OsStr> = vec![OsStr::new(MOBILE_ARG_BUILD)];
451    if config.get_release() {
452        cargo_args.push(OsStr::new(MOBILE_ARG_RELEASE));
453    }
454    cargo_args.push(OsStr::new(MOBILE_ARG_TARGET));
455    cargo_args.push(OsStr::new(triple));
456    run_checked_command(
457        Path::new(MOBILE_CMD_CARGO),
458        &cargo_args,
459        Some(build_dir),
460        &[],
461    )?;
462    let profile_dir: &str = if config.get_release() {
463        MOBILE_DIR_RELEASE
464    } else {
465        MOBILE_DIR_DEBUG
466    };
467    let static_lib: PathBuf = build_dir
468        .join(MOBILE_DIR_TARGET)
469        .join(triple)
470        .join(profile_dir)
471        .join(APPLE_IOS_STATICLIB_NAME);
472    let clang_out: Output = run_checked_command(
473        Path::new(CMD_XCRUN),
474        &[
475            OsStr::new(ARG_XCRUN_SDK),
476            OsStr::new(target_kind.xcode_sdk()),
477            OsStr::new(ARG_XCRUN_FIND),
478            OsStr::new(TOOL_CLANG),
479        ],
480        None,
481        &[],
482    )?;
483    let clang_bin: PathBuf = PathBuf::from(String::from_utf8_lossy(&clang_out.stdout).trim());
484    let min_ver_flag: &str = if target_kind.is_simulator() {
485        ARG_MIN_IOS_SIM
486    } else {
487        ARG_MIN_IOS_DEVICE
488    };
489    let main_m: PathBuf = build_dir.join(APPLE_IOS_MAIN_M_FILE);
490    let mut link_args: Vec<&OsStr> = vec![
491        OsStr::new(ARG_ARCH),
492        OsStr::new(ARG_ARM64),
493        OsStr::new(ARG_ISYSROOT),
494        OsStr::new(sdk_path),
495        OsStr::new(min_ver_flag),
496        OsStr::new(ARG_FOBJC_ARC),
497        main_m.as_os_str(),
498        static_lib.as_os_str(),
499    ];
500    for framework in APPLE_IOS_FRAMEWORKS.iter().copied() {
501        link_args.push(OsStr::new(ARG_FRAMEWORK));
502        link_args.push(OsStr::new(framework));
503    }
504    link_args.push(OsStr::new("-o"));
505    link_args.push(exec_path.as_os_str());
506    run_checked_command(&clang_bin, &link_args, None, &[])?;
507    run_checked_command(
508        Path::new(CMD_STRIP),
509        &[OsStr::new("-x"), exec_path.as_os_str()],
510        None,
511        &[],
512    )?;
513    let identity: &str = config.try_get_codesign_identity().as_deref().unwrap_or("-");
514    run_checked_command(
515        Path::new(CMD_CODESIGN),
516        &[
517            OsStr::new(ARG_CODESIGN_FORCE),
518            OsStr::new(ARG_CODESIGN_SIGN),
519            OsStr::new(identity),
520            app_bundle.as_os_str(),
521        ],
522        None,
523        &[],
524    )?;
525    Ok(())
526}
527
528/// Compiles the watchOS Rust staticlib and links the SwiftUI host binary via `xcrun swiftc`.
529///
530/// # Arguments
531///
532/// - `&AppleBuildConfig` - Apple build configuration.
533/// - `&str` - Resolved watchOS Xcode SDK path.
534/// - `&Path` - watchOS host build directory.
535/// - `&Path` - Destination `EuvWatch.app` bundle directory.
536/// - `&Path` - Destination `EuvWatch` executable path.
537///
538/// # Returns
539///
540/// - `io::Result<()>` - Compilation, linking, and signing outcome.
541fn compile_and_link_watchos(
542    config: &AppleBuildConfig,
543    sdk_path: &str,
544    build_dir: &Path,
545    app_bundle: &Path,
546    exec_path: &Path,
547) -> io::Result<()> {
548    let target_kind: AppleTargetKind = config.get_target_kind();
549    let triple: &str = target_kind.rust_triple();
550    let mut cargo_args: Vec<&OsStr> = vec![OsStr::new(MOBILE_ARG_BUILD)];
551    if config.get_release() {
552        cargo_args.push(OsStr::new(MOBILE_ARG_RELEASE));
553    }
554    cargo_args.push(OsStr::new(MOBILE_ARG_TARGET));
555    cargo_args.push(OsStr::new(triple));
556    let envs: [(&str, &OsStr); 1] = [(ENV_SDKROOT, OsStr::new(sdk_path))];
557    run_checked_command(
558        Path::new(MOBILE_CMD_CARGO),
559        &cargo_args,
560        Some(build_dir),
561        &envs,
562    )?;
563    let profile_dir: &str = if config.get_release() {
564        MOBILE_DIR_RELEASE
565    } else {
566        MOBILE_DIR_DEBUG
567    };
568    let static_lib: PathBuf = build_dir
569        .join(MOBILE_DIR_TARGET)
570        .join(triple)
571        .join(profile_dir)
572        .join(APPLE_WATCHOS_STATICLIB_NAME);
573    let out_dir: PathBuf = app_bundle
574        .parent()
575        .map(Path::to_path_buf)
576        .unwrap_or_else(|| PathBuf::from("."));
577    let lib_dest_dir: PathBuf = out_dir.join(APPLE_LIBS_DIR_NAME).join(triple);
578    fs::create_dir_all(&lib_dest_dir)?;
579    fs::create_dir_all(app_bundle)?;
580    let _: u64 = fs::copy(&static_lib, lib_dest_dir.join(APPLE_WATCHOS_STATICLIB_NAME))?;
581    let app_src_dir: PathBuf = out_dir.join(APPLE_WATCHOS_APP_SRC_DIR);
582    let _: u64 = fs::copy(
583        app_src_dir.join(APPLE_INFO_PLIST_FILE),
584        app_bundle.join(APPLE_INFO_PLIST_FILE),
585    )?;
586    let swift_target: &str = if target_kind.is_simulator() {
587        ARG_WATCHOS_SIM_TRIPLE
588    } else {
589        ARG_WATCHOS_DEVICE_TRIPLE
590    };
591    let bridge_h: PathBuf = app_src_dir.join(APPLE_WATCHOS_BRIDGE_H_FILE);
592    let swift_src: PathBuf = app_src_dir.join(APPLE_WATCHOS_SWIFT_FILE);
593    let mut swift_args: Vec<&OsStr> = vec![
594        OsStr::new(ARG_XCRUN_SDK),
595        OsStr::new(target_kind.xcode_sdk()),
596        OsStr::new(TOOL_SWIFTC),
597        OsStr::new(ARG_PARSE_AS_LIBRARY),
598        OsStr::new(ARG_SWIFTC_TARGET),
599        OsStr::new(swift_target),
600        OsStr::new(ARG_SWIFTC_SDK),
601        OsStr::new(sdk_path),
602        OsStr::new("-O"),
603        OsStr::new(ARG_IMPORT_OBJC_HEADER),
604        bridge_h.as_os_str(),
605        swift_src.as_os_str(),
606        static_lib.as_os_str(),
607    ];
608    for framework in APPLE_WATCHOS_FRAMEWORKS.iter().copied() {
609        swift_args.push(OsStr::new(ARG_FRAMEWORK));
610        swift_args.push(OsStr::new(framework));
611    }
612    swift_args.push(OsStr::new("-o"));
613    swift_args.push(exec_path.as_os_str());
614    run_checked_command(Path::new(CMD_XCRUN), &swift_args, None, &[])?;
615    let identity: &str = config.try_get_codesign_identity().as_deref().unwrap_or("-");
616    run_checked_command(
617        Path::new(CMD_CODESIGN),
618        &[
619            OsStr::new(ARG_CODESIGN_FORCE),
620            OsStr::new(ARG_CODESIGN_SIGN),
621            OsStr::new(identity),
622            app_bundle.as_os_str(),
623        ],
624        None,
625        &[],
626    )?;
627    Ok(())
628}
629
630/// Resolves the Xcode SDK filesystem path for the given SDK name via `xcrun`.
631///
632/// # Arguments
633///
634/// - `&str` - Xcode SDK identifier such as `iphonesimulator` or `watchsimulator`.
635///
636/// # Returns
637///
638/// - `io::Result<String>` - Trimmed SDK directory path.
639fn resolve_xcode_sdk_path(sdk_name: &str) -> io::Result<String> {
640    let output: Output = run_checked_command(
641        Path::new(CMD_XCRUN),
642        &[
643            OsStr::new(ARG_XCRUN_SDK),
644            OsStr::new(sdk_name),
645            OsStr::new(ARG_XCRUN_SHOW_SDK_PATH),
646        ],
647        None,
648        &[],
649    )?;
650    let path_str: String = String::from_utf8_lossy(&output.stdout).trim().to_string();
651    if path_str.is_empty() {
652        return Err(Error::new(
653            ErrorKind::NotFound,
654            format!("xcrun returned empty SDK path for '{sdk_name}'"),
655        ));
656    }
657    Ok(path_str)
658}
659
660/// Archives a compiled Apple `.app` bundle into a compressed `.tar.gz` file.
661///
662/// # Arguments
663///
664/// - `&Path` - Source `.app` bundle directory.
665/// - `&Path` - Destination `.tar.gz` file path.
666///
667/// # Returns
668///
669/// - `io::Result<()>` - Archiving outcome.
670fn archive_apple_bundle_tar_gz(app_bundle: &Path, archive_dst: &Path) -> io::Result<()> {
671    if let Some(archive_parent) = archive_dst.parent() {
672        fs::create_dir_all(archive_parent)?;
673    }
674    let bundle_parent: &Path = app_bundle.parent().unwrap_or_else(|| Path::new("."));
675    let bundle_name: &OsStr = app_bundle
676        .file_name()
677        .unwrap_or_else(|| OsStr::new(APPLE_IOS_BUNDLE_NAME));
678    run_checked_command(
679        Path::new(APPLE_CMD_TAR),
680        &[
681            OsStr::new(ARG_TAR_CZF),
682            archive_dst.as_os_str(),
683            OsStr::new("-C"),
684            bundle_parent.as_os_str(),
685            bundle_name,
686        ],
687        None,
688        &[],
689    )?;
690    Ok(())
691}
692
693/// Boots, installs, and launches the `.app` bundle in an iOS/iPadOS Simulator while forwarding OTA env vars.
694///
695/// # Arguments
696///
697/// - `&AppleBuildConfig` - Apple build configuration.
698/// - `&Path` - Compiled and signed `.app` bundle path.
699/// - `&str` - Bundle identifier launched via `xcrun simctl launch`.
700///
701/// # Returns
702///
703/// - `io::Result<()>` - Simulator install and launch outcome.
704fn launch_ios_simulator_bundle(
705    config: &AppleBuildConfig,
706    app_bundle: &Path,
707    bundle_id: &str,
708) -> io::Result<()> {
709    let sim_udid: String = resolve_ios_simulator_udid(config)?;
710    let _: io::Result<Output> = Command::new(CMD_XCRUN)
711        .args([TOOL_SIMCTL, ARG_SIMCTL_BOOT, &sim_udid])
712        .output();
713    let _: io::Result<Output> = Command::new(CMD_XCRUN)
714        .args([TOOL_SIMCTL, ARG_SIMCTL_TERMINATE, &sim_udid, bundle_id])
715        .output();
716    run_checked_command(
717        Path::new(CMD_XCRUN),
718        &[
719            OsStr::new(TOOL_SIMCTL),
720            OsStr::new(ARG_SIMCTL_INSTALL),
721            OsStr::new(&sim_udid),
722            app_bundle.as_os_str(),
723        ],
724        None,
725        &[],
726    )?;
727    let mut forwarded_owned: Vec<(String, OsString)> = Vec::new();
728    for env_key in [
729        ENV_EUV_UPDATE_URL,
730        ENV_EUV_PROXY_URL,
731        ENV_EUV_UPDATE_CHANNEL,
732    ] {
733        if let Ok(env_val) = env::var(env_key)
734            && !env_val.trim().is_empty()
735        {
736            forwarded_owned.push((
737                format!("{ENV_SIMCTL_CHILD_PREFIX}{env_key}"),
738                OsString::from(env_val),
739            ));
740        }
741    }
742    let forwarded_refs: Vec<(&str, &OsStr)> = forwarded_owned
743        .iter()
744        .map(|(env_k, env_v): &(String, OsString)| (env_k.as_str(), env_v.as_os_str()))
745        .collect();
746    run_checked_command(
747        Path::new(CMD_XCRUN),
748        &[
749            OsStr::new(TOOL_SIMCTL),
750            OsStr::new(ARG_SIMCTL_LAUNCH),
751            OsStr::new(&sim_udid),
752            OsStr::new(bundle_id),
753        ],
754        None,
755        &forwarded_refs,
756    )?;
757    Ok(())
758}
759
760/// Resolves an active or available iOS/iPadOS Simulator UDID from config, env, or `xcrun simctl`.
761///
762/// # Arguments
763///
764/// - `&AppleBuildConfig` - Apple build configuration.
765///
766/// # Returns
767///
768/// - `io::Result<String>` - Resolved 36-character Simulator UUID.
769fn resolve_ios_simulator_udid(config: &AppleBuildConfig) -> io::Result<String> {
770    if let Some(custom) = config.try_get_sim_udid() {
771        return Ok(custom.clone());
772    }
773    if let Ok(env_udid) = env::var(ENV_EUV_IOS_SIM_UDID) {
774        let trimmed: &str = env_udid.trim();
775        if !trimmed.is_empty() {
776            return Ok(trimmed.to_string());
777        }
778    }
779    let booted_out: Output = Command::new(CMD_XCRUN)
780        .args([
781            TOOL_SIMCTL,
782            ARG_SIMCTL_LIST,
783            ARG_SIMCTL_DEVICES,
784            ARG_SIMCTL_BOOTED,
785        ])
786        .output()?;
787    let booted_text: Cow<'_, str> = String::from_utf8_lossy(&booted_out.stdout);
788    if let Some(udid) = extract_first_sim_uuid(&booted_text, None) {
789        return Ok(udid);
790    }
791    let avail_out: Output = Command::new(CMD_XCRUN)
792        .args([
793            TOOL_SIMCTL,
794            ARG_SIMCTL_LIST,
795            ARG_SIMCTL_DEVICES,
796            ARG_SIMCTL_AVAILABLE,
797        ])
798        .output()?;
799    let avail_text: Cow<'_, str> = String::from_utf8_lossy(&avail_out.stdout);
800    let device_filter: &str = if config.get_target_kind().is_ipad() {
801        SIM_DEVICE_IPAD
802    } else {
803        SIM_DEVICE_IPHONE
804    };
805    if let Some(udid) = extract_first_sim_uuid(&avail_text, Some(device_filter)) {
806        return Ok(udid);
807    }
808    Err(Error::new(ErrorKind::NotFound, ERR_APPLE_NO_SIMULATOR))
809}
810
811/// Extracts the first 36-character uppercase UUID from `xcrun simctl list devices` output.
812///
813/// # Arguments
814///
815/// - `&str` - Multiline `simctl` text output.
816/// - `Option<&str>` - Optional device label substring filter such as `"iPhone"` or `"iPad"`.
817///
818/// # Returns
819///
820/// - `Option<String>` - First matching UUID string when found.
821fn extract_first_sim_uuid(simctl_output: &str, line_filter: Option<&str>) -> Option<String> {
822    for raw_line in simctl_output.lines() {
823        if let Some(filter) = line_filter
824            && !raw_line.contains(filter)
825        {
826            continue;
827        }
828        let mut search_from: usize = 0;
829        while let Some(open_rel) = raw_line[search_from..].find('(') {
830            let start_idx: usize = search_from + open_rel + 1;
831            let Some(close_rel) = raw_line[start_idx..].find(')') else {
832                break;
833            };
834            let candidate: &str = &raw_line[start_idx..start_idx + close_rel];
835            if is_sim_uuid(candidate) {
836                return Some(candidate.to_string());
837            }
838            search_from = start_idx + close_rel + 1;
839        }
840    }
841    None
842}
843
844/// Validates whether a candidate string matches the 36-character `8-4-4-4-12` Simulator UUID format.
845///
846/// # Arguments
847///
848/// - `&str` - Candidate token inside parentheses.
849///
850/// # Returns
851///
852/// - `bool` - `true` when `candidate` is a valid uppercase/hex UUID.
853fn is_sim_uuid(candidate: &str) -> bool {
854    if candidate.len() != APPLE_UUID_LEN {
855        return false;
856    }
857    for (idx, byte_val) in candidate.bytes().enumerate() {
858        let expect_dash: bool = idx == 8 || idx == 13 || idx == 18 || idx == 23;
859        if expect_dash {
860            if byte_val != b'-' {
861                return false;
862            }
863        } else if !byte_val.is_ascii_hexdigit() {
864            return false;
865        }
866    }
867    true
868}