nsh-cli 0.3.0

The nsh command line tool: build, package and run apps.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
use std::{
    fs,
    path::{Path, PathBuf},
    process::{Command, Stdio},
};

use anyhow::{Context as _, bail};
use nsh_core::js::HostLimits;
use serde::Deserialize;

use crate::{dev::DevSession, runtime::Platform, ui};

const APP_NAME: &str = "NshDev";
pub(crate) const BUNDLE_ID: &str = "com.longbridge.nsh.host";

/// Where `nsh dev` and `nsh run` run the app.
#[derive(Debug, Clone, Copy, PartialEq, Eq, clap::ValueEnum)]
pub(crate) enum Target {
    /// The Mac Catalyst development host (an iPhone-sized window).
    Catalyst,
    /// The development host in an iOS simulator.
    Ios,
    /// The development host on an Android device or emulator.
    Android,
    /// The Linux (GTK) development host, in a window on this machine.
    Linux,
    /// The macOS (AppKit) development host, in a window on this machine.
    Macos,
    /// The Windows development host, in a window on this machine.
    Windows,
    /// The web development host, in the browser (the dev server serves its
    /// page).
    Web,
    /// The GPUI development host, in a window on this machine (macOS,
    /// Windows or Linux): the app as GPUI apps that embed it show it.
    Gpui,
}

impl Target {
    /// The default: this system’s native desktop host (AppKit on macOS,
    /// GTK on Linux, Win32 on Windows; the browser elsewhere).
    pub(crate) fn native() -> Target {
        if cfg!(target_os = "macos") {
            Target::Macos
        } else if cfg!(target_os = "linux") {
            Target::Linux
        } else if cfg!(windows) {
            Target::Windows
        } else {
            Target::Web
        }
    }

    pub(crate) fn platform(self) -> crate::runtime::Platform {
        match self {
            Target::Catalyst => crate::runtime::Platform::MacCatalyst,
            Target::Linux => crate::runtime::Platform::Linux,
            Target::Macos => crate::runtime::Platform::MacOs,
            Target::Windows => crate::runtime::Platform::Windows,
            Target::Gpui => crate::runtime::Platform::Gpui,
            Target::Ios | Target::Android | Target::Web => {
                crate::runtime::Platform::IphoneSimulator
            }
        }
    }
}

/// How the development host runs the app and what it shows besides it.
#[derive(Debug, Clone, Copy)]
pub(crate) struct HostFlags {
    /// The VM limits an embedding app would set (`--limits`); `None`: none,
    /// as an app on its own.
    pub(crate) limits: Option<HostLimits>,
    /// Log per-commit timings.
    pub(crate) trace: bool,
    /// The performance monitor (the macOS host's).
    pub(crate) fps: bool,
}

/// The host window's own options: the desktop hosts take the size
/// ([`HostWindow::check`]), the macOS host the name too.
#[derive(Debug, Clone, Copy, Default)]
pub(crate) struct HostWindow<'a> {
    /// The app's name in the host (the menu bar, the window title).
    pub(crate) name: Option<&'a str>,
    /// The window's initial size, `WxH` in points.
    pub(crate) size: Option<&'a str>,
}

impl HostWindow<'_> {
    /// Refuses the options `target`'s host does not take. An app of Rust
    /// only (`rust_root`) runs in its runner on macOS, Linux and Windows;
    /// GPUI has no runner (it is the backend for embedding in GPUI apps),
    /// so such an app does not run there at all.
    fn check(&self, target: Target, rust_root: bool) -> anyhow::Result<()> {
        if rust_root && target == Target::Gpui {
            bail!(
                "a Rust app runs on this OS's own backend (--target macos, linux or windows); \
                 GPUI apps embed its root with AppView"
            );
        }
        let desktop = matches!(
            target,
            Target::Macos | Target::Linux | Target::Windows | Target::Gpui
        );
        if self.name.is_some() && (target != Target::Macos || rust_root) {
            bail!(
                "--name needs --target macos and a TSX entry (the other hosts do not take it yet)"
            );
        }
        if self.size.is_some() && (!desktop || rust_root) {
            bail!(
                "--window-size needs a desktop host (--target macos, linux, windows or gpui) and a TSX entry"
            );
        }
        Ok(())
    }

    /// The arguments of the size, for a desktop host.
    fn args(&self) -> Vec<&str> {
        let mut args = Vec::new();
        if let Some(size) = self.size {
            // `WxH` in points; the host opens the window at this size.
            args.extend(["--window-size", size]);
        }
        args
    }
}

/// Starts a dev session and runs the app in a development host, which
/// loads bundles from the dev server and reloads on change.
pub(crate) fn run(
    entry: &Path,
    port: u16,
    release: bool,
    flags: HostFlags,
    target: Target,
    device: Option<&str>,
    window: HostWindow<'_>,
) -> anyhow::Result<()> {
    let HostFlags { limits, trace, fps } = flags;
    if fps
        && !matches!(
            target,
            Target::Macos | Target::Linux | Target::Ios | Target::Windows
        )
    {
        bail!(
            "--fps needs --target macos, linux, windows or ios (the other hosts have no performance monitor yet)"
        );
    }
    window.check(target, crate::rust_app::is_root(entry))?;
    let work = dunce::canonicalize(entry)?
        .parent()
        .context("entry has no directory")?
        .join(".nsh");
    if crate::rust_app::is_root(entry) {
        return run_rust_app(entry, port, target, device, &work);
    }
    if target == Target::Android {
        return run_android(entry, port, release, limits, &work, trace);
    }
    if target == Target::Web {
        return run_web(entry, port, release, limits);
    }
    // The host a previous session left running would connect to this one
    // until it is replaced.
    let udid = match target {
        Target::Ios => {
            let udid = simulator(device)?;
            let _ = simctl(&["terminate", &udid, BUNDLE_ID]);
            Some(udid)
        }
        Target::Catalyst
        | Target::Android
        | Target::Linux
        | Target::Macos
        | Target::Windows
        | Target::Web
        | Target::Gpui => None,
    };
    // The host it starts connects by itself: no addresses to show.
    let session = DevSession::start(entry, port, release, limits)?;
    let host = crate::runtime::file(target.platform(), false)?;
    let mut args = vec!["--dev-server".to_owned(), session.local_url()];
    if trace {
        args.push("--trace".to_owned());
    }
    if fps {
        args.push("--fps".to_owned());
    }
    match target {
        Target::Catalyst => {
            let app = package_catalyst(&work, &host)?;
            let exe = app.join("Contents/MacOS/nsh-ios-host");
            // Its own output (AppKit's notes) is kept for when it fails.
            let mut command = Command::new(&exe);
            command.env("NSH_DEV_APP_DIR", work.parent().expect("source directory"));
            command
                .args(&args)
                // A host that crashed must not ask to reopen its windows
                // next time (a modal dialog that blocks the window).
                .args(["-ApplePersistenceIgnoreState", "YES"]);
            run_local(&session, &mut command, "the Mac Catalyst host")
        }
        // Run in place: unlike Catalyst's, the GTK host needs no app
        // bundle around it.
        Target::Linux => {
            let mut command = Command::new(&host);
            command.env("NSH_DEV_APP_DIR", work.parent().expect("source directory"));
            command
                .args(&args)
                .args(["--app-id", &crate::package::app_id(entry)?])
                .args(window.args());
            run_local(&session, &mut command, "the Linux host")
        }
        // In place too: the AppKit host makes itself a regular app (menu
        // bar, Dock icon) without an app bundle around it.
        Target::Macos => {
            // The menu bar and the window show the app's name; `--name`
            // overrides it (a host run for one of the app's windows can
            // name itself).
            let entry = entry.canonicalize()?;
            let config = crate::package::read_config(&entry).unwrap_or_default();
            let (app_name, id) = crate::package::name_and_id(&entry, &config);
            let name = window.name.unwrap_or(&app_name);
            let mut command = Command::new(&host);
            command.env("NSH_DEV_APP_DIR", work.parent().expect("source directory"));
            command
                .args(&args)
                .args(["--name", name, "--app-id", &id])
                .args(["-ApplePersistenceIgnoreState", "YES"])
                .args(window.args());
            run_local(&session, &mut command, "the macOS host")
        }
        Target::Windows => {
            let mut command = Command::new(&host);
            command.env("NSH_DEV_APP_DIR", work.parent().expect("source directory"));
            command
                .args(&args)
                .args(["--app-id", &crate::package::app_id(entry)?])
                .args(window.args());
            run_local(&session, &mut command, "the Windows host")
        }
        // In place on every OS: GPUI makes the process a regular app (on
        // macOS too) without an app bundle around it.
        Target::Gpui => {
            let mut command = Command::new(&host);
            command.env("NSH_DEV_APP_DIR", work.parent().expect("source directory"));
            command
                .args(&args)
                .args(["--app-id", &crate::package::app_id(entry)?])
                .args(window.args());
            run_local(&session, &mut command, "the GPUI host")
        }
        Target::Ios => {
            let app = package_ios(&work, &host)?;
            let udid = udid.expect("the simulator is picked before the session");
            let step = ui::Step::start("installing the development host in the simulator");
            simctl(&["install", &udid, &app.to_string_lossy()])?;
            step.finish();
            let mut launch = vec!["launch", "--terminate-running-process", &udid, BUNDLE_ID];
            launch.extend(args.iter().map(String::as_str));
            let step = ui::Step::start("launching the development host");
            simctl(&launch)?;
            step.finish();
            // The simulator shares the Mac's network: 127.0.0.1 is the dev
            // server, so a host left running would join the next session
            // of any app: Ctrl-C stops it too.
            let stoppable = ui::Stoppable::new();
            let result = session.watch(|| Ok(false));
            let _ = simctl(&["terminate", &udid, BUNDLE_ID]);
            drop(stoppable);
            result
        }
        Target::Android | Target::Web => unreachable!("handled above"),
    }
}

/// Starts a dev session that serves the web host and prints its address;
/// every browser that opens the page (on this machine or, at the LAN
/// address, on a phone) runs the app until the session ends. The browser
/// is the user's to open: a session that starts again (the app's Rust code
/// changed) finds its page still open, and it reloads by itself.
fn run_web(
    entry: &Path,
    port: u16,
    release: bool,
    limits: Option<HostLimits>,
) -> anyhow::Result<()> {
    // Built first in a checkout: the session serves the runtime it finds.
    crate::runtime::web(crate::runtime::WebKind::Dev, true)?.context("no web runtime")?;
    let session = DevSession::start(entry, port, release, limits)?;
    session.print_web_url();
    session.watch(|| Ok(false))
}

/// Runs a Rust app (`nsh.json` `"root"`): its own runner, with no JS
/// runtime, mounts its root. Desktops run the debug runner in place (its
/// output in this terminal), Catalyst in an app bundle, the iOS simulator
/// and Android a package of it, the web the dev server's page. A change to
/// the app's Rust code ends the command with [`crate::rust_app::Restart`]:
/// `nsh` builds it again and runs it anew.
fn run_rust_app(
    entry: &Path,
    port: u16,
    target: Target,
    device: Option<&str>,
    work: &Path,
) -> anyhow::Result<()> {
    let app =
        crate::rust_app::current().context("nsh.json: \"root\" needs \"rust\", the app's crate")?;
    let entry = dunce::canonicalize(entry)?;
    let config = crate::package::read_config(&entry)?;
    let (name, id) = crate::package::name_and_id(&entry, &config);
    let built = crate::build::rust_root();
    // The package's `nsh` directory for the runners that run in place:
    // the crates' assets and the window's name, id and appearance.
    let resources = |dir: &Path| -> anyhow::Result<()> {
        if dir.exists() {
            fs::remove_dir_all(dir)?;
        }
        for asset in &built.assets {
            let dest = dir.join("assets").join(&asset.path);
            fs::create_dir_all(dest.parent().context("asset dir")?)?;
            fs::copy(&asset.source, &dest).with_context(|| format!("copy {}", asset.path))?;
        }
        fs::create_dir_all(dir)?;
        let mut info = serde_json::json!({ "name": name, "id": id });
        if let Some(appearance) = &config.appearance {
            info["appearance"] = appearance.as_str().into();
        }
        fs::write(dir.join("app.json"), info.to_string())?;
        Ok(())
    };
    let run = work.join("rust");
    match target {
        Target::Linux | Target::Macos | Target::Windows => {
            let runner = crate::runtime::file(target.platform(), false)?;
            let dir = run.join("run/nsh");
            resources(&dir)?;
            let mut command = Command::new(&runner);
            command.env("NSH_APP_DIR", &dir);
            if cfg!(target_os = "macos") {
                // A runner that crashed must not ask to reopen its windows.
                command.args(["-ApplePersistenceIgnoreState", "YES"]);
            }
            ui::done(format!(
                "running {name} ({})",
                ui::dim("Rust, no JS runtime")
            ));
            run_rust_local(&app, &mut command)
        }
        Target::Catalyst => {
            let runner = crate::runtime::file(Platform::MacCatalyst, false)?;
            let bundle = package_catalyst(&run.join("catalyst"), &runner)?;
            let macos = bundle.join("Contents/MacOS");
            // The iOS runner looks next to itself.
            resources(&macos.join("nsh"))?;
            let mut command = Command::new(macos.join("nsh-ios-host"));
            command
                .env("NSH_DEVELOPMENT", "1")
                .args(["-ApplePersistenceIgnoreState", "YES"]);
            ui::done(format!(
                "running {name} ({})",
                ui::dim("Rust, no JS runtime")
            ));
            run_rust_local(&app, &mut command)
        }
        Target::Ios => {
            let udid = simulator(device)?;
            let out = run.join("ios");
            package_for_run(
                &entry,
                crate::package::PackageTarget::IosSimulator,
                &out,
                config,
            )?;
            let bundle = out.join(format!("{name}.app"));
            let step = ui::Step::start(format!("installing {id} in the simulator"));
            simctl(&["install", &udid, &bundle.to_string_lossy()])?;
            step.finish();
            // Its output (the app's logs) in this terminal while it runs.
            let mut command = Command::new("xcrun");
            command
                .args([
                    "simctl",
                    "launch",
                    "--console-pty",
                    "--terminate-running-process",
                ])
                .args([&udid, &id])
                .env("SIMCTL_CHILD_NSH_DEVELOPMENT", "1");
            let result = run_rust_local(&app, &mut command);
            let _ = simctl(&["terminate", &udid, &id]);
            result
        }
        Target::Android => {
            use crate::android;
            let sdk = android::Sdk::find()?;
            let serial = android::device(&sdk)?;
            let out = run.join("android");
            package_for_run(&entry, crate::package::PackageTarget::Android, &out, config)?;
            let apk = out.join(format!("{name}.apk"));
            let step = ui::Step::start(format!("installing {id} on {serial}"));
            android::adb(&sdk, &serial, &["install", "-r", &apk.to_string_lossy()])?;
            android::adb(
                &sdk,
                &serial,
                &[
                    "shell",
                    "am",
                    "start",
                    "-S",
                    "-n",
                    &format!("{id}/com.longbridge.nsh.AppActivity"),
                ],
            )?;
            step.done(format!("launched {id} on {serial}"));
            let _stoppable = ui::Stoppable::new();
            let result = app.watch(|| Ok(false));
            let _ = android::adb(&sdk, &serial, &["shell", "am", "force-stop", &id]);
            result
        }
        Target::Web => {
            crate::runtime::web(crate::runtime::WebKind::Dev, true)?.context("no web runtime")?;
            let session = DevSession::start(&entry, port, false, None)?;
            session.print_web_url();
            session.watch(|| Ok(false))
        }
        Target::Gpui => unreachable!("refused by HostWindow::check"),
    }
}

/// Packages the Rust app at `entry` for `target` into `out` (as `nsh
/// package` does), for `nsh run` to install.
fn package_for_run(
    entry: &Path,
    target: crate::package::PackageTarget,
    out: &Path,
    config: crate::package::AppConfig,
) -> anyhow::Result<()> {
    crate::package::package(crate::package::PackageOptions {
        entry,
        target,
        out,
        config,
        sign: None,
        profile: None,
        keystore: None,
        run: false,
    })
}

/// Runs `command` (a Rust app's runner, its output in this terminal) until
/// it ends or the app's Rust code changes.
fn run_rust_local(app: &crate::rust_app::RustApp, command: &mut Command) -> anyhow::Result<()> {
    #[cfg(windows)]
    {
        use std::os::windows::process::CommandExt as _;
        command.creation_flags(windows_sys::Win32::System::Threading::CREATE_NEW_PROCESS_GROUP);
    }
    let mut child = command
        .stdin(Stdio::null())
        .spawn()
        .with_context(|| format!("launch {}", command.get_program().to_string_lossy()))?;
    #[cfg(windows)]
    let _job = KillOnClose::assign(&child);
    let stoppable = ui::Stoppable::new();
    let result = app.watch(|| match child.try_wait()? {
        Some(status) if status.success() => Ok(true),
        Some(status) => bail!("the app exited with {status}"),
        None => Ok(false),
    });
    let _ = child.kill();
    let _ = child.wait();
    drop(stoppable);
    result
}

/// Runs `command`, a host in a window on this machine, until its window
/// closes or the session ends; `what` names it when it fails.
fn run_local(session: &DevSession, command: &mut Command, what: &str) -> anyhow::Result<()> {
    #[cfg(windows)]
    {
        use std::os::windows::process::CommandExt as _;
        // Out of the console's Ctrl-C: this command stops the host itself,
        // so that a stop is not taken for the host failing.
        command.creation_flags(windows_sys::Win32::System::Threading::CREATE_NEW_PROCESS_GROUP);
    }
    // Its own output is kept for when it fails.
    let (mut child, output) = ui::quiet(command)
        .with_context(|| format!("launch {}", command.get_program().to_string_lossy()))?;
    // Windows ends a child with its parent only in a job: the host goes
    // with this command however it ends (closed console, killed).
    #[cfg(windows)]
    let _job = KillOnClose::assign(&child);
    // A host left running would open a second window next time: Ctrl-C and
    // SIGTERM close it too.
    let stoppable = ui::Stoppable::new();
    let result = session.watch(|| match child.try_wait()? {
        Some(status) if status.success() => Ok(true),
        Some(status) => Err(ui::failure(
            format!("{what} exited with {status}"),
            output.text(),
        )),
        None => Ok(false),
    });
    let _ = child.kill();
    let _ = child.wait();
    drop(stoppable);
    result
}

/// A job object that ends its processes when it closes: when dropped, or
/// with this process, however it ends.
#[cfg(windows)]
pub(crate) struct KillOnClose(windows_sys::Win32::Foundation::HANDLE);

#[cfg(windows)]
impl KillOnClose {
    /// Puts `child` in a new such job; `None` (the child then outlives a
    /// killed parent, as without it) if Windows refuses.
    pub(crate) fn assign(child: &std::process::Child) -> Option<KillOnClose> {
        use std::os::windows::io::AsRawHandle as _;

        use windows_sys::Win32::System::JobObjects::{
            AssignProcessToJobObject, CreateJobObjectW, JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE,
            JOBOBJECT_EXTENDED_LIMIT_INFORMATION, JobObjectExtendedLimitInformation,
            SetInformationJobObject,
        };

        // SAFETY: an unnamed job with default security; the handle is
        // owned by the returned value, which closes it.
        let job = unsafe { CreateJobObjectW(std::ptr::null(), std::ptr::null()) };
        if job.is_null() {
            return None;
        }
        let job = KillOnClose(job);
        // SAFETY: zeroed is a valid "no limits" value of this plain C
        // structure.
        let mut info: JOBOBJECT_EXTENDED_LIMIT_INFORMATION = unsafe { std::mem::zeroed() };
        info.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;
        // SAFETY: `info` is the structure the information class names, with
        // its size; `child`'s handle is open while it is borrowed.
        let ok = unsafe {
            SetInformationJobObject(
                job.0,
                JobObjectExtendedLimitInformation,
                (&raw const info).cast(),
                std::mem::size_of_val(&info) as u32,
            ) != 0
                && AssignProcessToJobObject(job.0, child.as_raw_handle()) != 0
        };
        ok.then_some(job)
    }
}

#[cfg(windows)]
impl Drop for KillOnClose {
    fn drop(&mut self) {
        // SAFETY: the job handle this value owns, closed once.
        unsafe { windows_sys::Win32::Foundation::CloseHandle(self.0) };
    }
}

/// Starts a dev session, builds and installs the Android dev host (when
/// it changed), forwards the dev server port to the device and starts the
/// host.
fn run_android(
    entry: &Path,
    port: u16,
    release: bool,
    limits: Option<HostLimits>,
    work: &Path,
    trace: bool,
) -> anyhow::Result<()> {
    use crate::android;
    let sdk = android::Sdk::find()?;
    let serial = android::device(&sdk)?;
    // As on iOS: the host of a previous session must not connect first.
    let _ = android::adb(&sdk, &serial, &["shell", "am", "force-stop", BUNDLE_ID]);
    let session = DevSession::start(entry, port, release, limits)?;
    install_android_host(&sdk, &serial, work, &crate::runtime::android(true)?)?;
    // The device reaches the dev server on its own 127.0.0.1, until the
    // run ends.
    let _reverse = android::Reverse::add(&sdk, &serial, session.port())?;
    let url = session.local_url();
    let mut start = vec![
        "shell",
        "am",
        "start",
        "-S",
        "-n",
        "com.longbridge.nsh.host/com.longbridge.nsh.DevActivity",
        "--es",
        "url",
        &url,
    ];
    if trace {
        start.extend(["--ez", "trace", "true"]);
    }
    let step = ui::Step::start("launching the development host");
    android::adb(&sdk, &serial, &start)?;
    step.finish();
    let result = session.watch(|| Ok(false));
    let _ = android::adb(&sdk, &serial, &["shell", "am", "force-stop", BUNDLE_ID]);
    result
}

/// Builds the Android development host (when its runtime changed) into
/// `work` and installs it on device `serial` (when the device does not have
/// this build).
pub(crate) fn install_android_host(
    sdk: &crate::android::Sdk,
    serial: &str,
    work: &Path,
    runtime: &Path,
) -> anyhow::Result<()> {
    use crate::android::{self, Apk, Signing};
    let apk_path = work.join("android/NshDev.apk");
    fs::create_dir_all(apk_path.parent().context("apk dir")?)?;
    let stamp = work.join("android/runtime.stamp");
    // Every app's development host is the same package: another app's run
    // (an app with its own Rust crate has its own runtime) or another
    // device replaces what this app installed. The device's install time
    // tells whether the host there is still the one this app installed.
    let installed = work.join("android/installed");
    let version = runtime_version(runtime)?;
    let built =
        apk_path.exists() && fs::read_to_string(&stamp).ok().as_deref() == Some(version.as_str());
    if !built {
        let step = ui::Step::start("building the Android development host");
        android::build_apk(
            sdk,
            &Apk {
                package: BUNDLE_ID,
                label: APP_NAME,
                version_name: "0.1.0",
                version_code: 1,
                activity: "com.longbridge.nsh.DevActivity",
                dev: true,
                rust: false,
                dark: false,
                runtime,
                icon: None,
                assets: Vec::new(),
                signing: Signing::Debug,
            },
            &apk_path,
        )?;
        step.done("built the Android development host");
        // Until it is installed, no device has this build.
        let _ = fs::remove_file(&installed);
        fs::write(&stamp, &version)?;
    }
    let on_device =
        |sdk: &android::Sdk| installed_host(sdk, serial).map(|time| format!("{serial} {time}"));
    let current = fs::read_to_string(&installed).ok();
    if current.is_none() || current != on_device(sdk) {
        let step = ui::Step::start(format!("installing it on {serial}"));
        android::adb(
            sdk,
            serial,
            &["install", "-r", "-t", &apk_path.to_string_lossy()],
        )?;
        step.done(format!(
            "installed the Android development host on {serial}"
        ));
        match on_device(sdk) {
            Some(record) => fs::write(&installed, record)?,
            None => {
                let _ = fs::remove_file(&installed);
            }
        }
    }
    Ok(())
}

/// When the development host on device `serial` was installed or last
/// updated (`dumpsys package`), if it is there.
fn installed_host(sdk: &crate::android::Sdk, serial: &str) -> Option<String> {
    let text =
        crate::android::adb(sdk, serial, &["shell", "dumpsys", "package", BUNDLE_ID]).ok()?;
    text.lines()
        .find_map(|line| line.trim().strip_prefix("lastUpdateTime="))
        .map(str::to_owned)
}

/// Identifies a runtime build: the sizes and times of its files.
fn runtime_version(runtime: &Path) -> anyhow::Result<String> {
    let mut parts = Vec::new();
    let mut files = vec![runtime.join("classes.dex")];
    for entry in fs::read_dir(runtime.join("lib"))? {
        files.push(entry?.path().join("libnsh.so"));
    }
    for file in files {
        if let Ok(meta) = fs::metadata(&file) {
            let modified = meta
                .modified()?
                .duration_since(std::time::UNIX_EPOCH)
                .map(|d| d.as_secs())
                .unwrap_or(0);
            parts.push(format!("{}:{}:{modified}", file.display(), meta.len()));
        }
    }
    Ok(parts.join("\n"))
}

/// Creates (or refreshes) `<work>/NshDev.app` around the host binary.
fn package_catalyst(work: &Path, host: &Path) -> anyhow::Result<PathBuf> {
    let app = work.join(format!("{APP_NAME}.app"));
    let contents = app.join("Contents");
    let macos = contents.join("MacOS");
    fs::create_dir_all(&macos)?;
    fs::write(contents.join("Info.plist"), info_plist(Target::Catalyst))?;
    install_binary(host, &macos.join("nsh-ios-host"))?;
    Ok(app)
}

/// Creates (or refreshes) `<work>/ios/NshDev.app`, a flat iOS app bundle,
/// signed ad hoc (the simulator requires a signature).
pub(crate) fn package_ios(work: &Path, host: &Path) -> anyhow::Result<PathBuf> {
    let app = work.join("ios").join(format!("{APP_NAME}.app"));
    fs::create_dir_all(&app)?;
    fs::write(app.join("Info.plist"), info_plist(Target::Ios))?;
    if install_binary(host, &app.join("nsh-ios-host"))? || !app.join("_CodeSignature").exists() {
        let status = Command::new("codesign")
            .args(["--force", "--sign", "-", "--timestamp=none"])
            .arg(&app)
            .stdout(Stdio::null())
            .stderr(Stdio::null())
            .status()
            .context("run codesign")?;
        if !status.success() {
            bail!("codesign failed for {}", app.display());
        }
    }
    Ok(app)
}

/// Copies the host binary if it changed. Returns true if it did.
fn install_binary(host: &Path, dest: &Path) -> anyhow::Result<bool> {
    if !is_stale(host, dest)? {
        return Ok(false);
    }
    // Copy then rename: overwriting in place would modify the file a
    // running host (another session) maps, and the kernel kills processes
    // whose code no longer matches its cached signature.
    let tmp = dest.with_extension("tmp");
    fs::copy(host, &tmp).with_context(|| format!("copy {}", host.display()))?;
    fs::rename(&tmp, dest)?;
    Ok(true)
}

fn is_stale(src: &Path, dest: &Path) -> anyhow::Result<bool> {
    let Ok(dest_meta) = fs::metadata(dest) else {
        return Ok(true);
    };
    let src_meta = fs::metadata(src)?;
    Ok(src_meta.len() != dest_meta.len() || src_meta.modified()? > dest_meta.modified()?)
}

pub(crate) fn simctl(args: &[&str]) -> anyhow::Result<String> {
    let output = Command::new("xcrun")
        .arg("simctl")
        .args(args)
        .output()
        .context("run xcrun simctl (is Xcode installed?)")?;
    if !output.status.success() {
        bail!(
            "simctl {} failed: {}",
            args.first().unwrap_or(&""),
            String::from_utf8_lossy(&output.stderr).trim()
        );
    }
    Ok(String::from_utf8_lossy(&output.stdout).into_owned())
}

#[derive(Deserialize)]
struct DeviceList {
    devices: std::collections::BTreeMap<String, Vec<Device>>,
}

#[derive(Deserialize)]
struct Device {
    udid: String,
    name: String,
    state: String,
    #[serde(rename = "isAvailable", default)]
    available: bool,
}

/// Picks a simulator (`wanted` by name or UDID; else a booted one; else the
/// newest iPhone), boots it and shows the Simulator app.
pub(crate) fn simulator(wanted: Option<&str>) -> anyhow::Result<String> {
    let list: DeviceList =
        serde_json::from_str(&simctl(&["list", "devices", "available", "--json"])?)?;
    // Runtimes sort by version within a platform; newest last.
    let mut devices: Vec<&Device> = list
        .devices
        .iter()
        .filter(|(runtime, _)| runtime.contains("SimRuntime.iOS"))
        .flat_map(|(_, devices)| devices)
        .filter(|d| d.available)
        .collect();
    devices.reverse();
    let device = match wanted {
        Some(w) => devices
            .iter()
            .find(|d| d.udid == w || d.name == w)
            .with_context(|| format!("no available simulator named {w}"))?,
        None => devices
            .iter()
            .find(|d| d.state == "Booted")
            .or_else(|| {
                devices
                    .iter()
                    .find(|d| d.name.starts_with("iPhone") && d.name.contains("Pro"))
            })
            .or_else(|| devices.iter().find(|d| d.name.starts_with("iPhone")))
            .context(
                "no iOS simulator available: install one with `xcodebuild -downloadPlatform iOS`",
            )?,
    };
    let booting =
        (device.state != "Booted").then(|| ui::Step::start(format!("booting {}", device.name)));
    if booting.is_some() {
        simctl(&["boot", &device.udid])?;
    }
    // Apps launched before the boot completes are sent to the background
    // when SpringBoard comes up.
    simctl(&["bootstatus", &device.udid, "-b"])?;
    if let Some(step) = booting {
        step.done(format!("booted {}", device.name));
    }
    show_simulators();
    Ok(device.udid.clone())
}

/// Brings up the simulators' window: Simulator.app, or DeviceHub.app in
/// Xcode versions that replaced it.
fn show_simulators() {
    let quiet = |cmd: &mut Command| {
        cmd.stdout(Stdio::null())
            .stderr(Stdio::null())
            .status()
            .is_ok_and(|s| s.success())
    };
    if quiet(Command::new("open").args(["-b", "com.apple.iphonesimulator"])) {
        return;
    }
    let developer = Command::new("xcode-select").arg("-p").output();
    if let Ok(out) = developer {
        let developer = String::from_utf8_lossy(&out.stdout);
        let hub = Path::new(developer.trim()).join("../Applications/DeviceHub.app");
        if hub.exists() && quiet(Command::new("open").arg(&hub)) {
            return;
        }
    }
    ui::warn("no Simulator or DeviceHub app found: the simulator runs without a window");
}

fn info_plist(target: Target) -> String {
    let platform = match target {
        // 6 = Mac idiom ("Optimize for Mac"): 1:1 points instead of the 77%
        // iPad scaling.
        Target::Catalyst => {
            "<key>UIDeviceFamily</key><array><integer>6</integer></array>\n    \
             <key>LSMinimumSystemVersion</key><string>11.0</string>"
        }
        // A launch screen entry opts into the full screen (no letterboxing).
        Target::Ios
        | Target::Android
        | Target::Linux
        | Target::Macos
        | Target::Windows
        | Target::Web
        | Target::Gpui => {
            "<key>UIDeviceFamily</key><array><integer>1</integer><integer>2</integer></array>\n    \
             <key>MinimumOSVersion</key><string>15.0</string>\n    \
             <key>CFBundleSupportedPlatforms</key><array><string>iPhoneSimulator</string></array>\n    \
             <key>UILaunchScreen</key><dict/>\n    \
             <key>CADisableMinimumFrameDurationOnPhone</key><true/>\n    \
             <key>NSAppTransportSecurity</key><dict><key>NSAllowsLocalNetworking</key><true/></dict>"
        }
    };
    format!(
        r#"<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>CFBundleExecutable</key><string>nsh-ios-host</string>
    <key>CFBundleIdentifier</key><string>{BUNDLE_ID}</string>
    <key>CFBundleName</key><string>{APP_NAME}</string>
    <key>CFBundlePackageType</key><string>APPL</string>
    <key>CFBundleShortVersionString</key><string>0.1.0</string>
    <key>CFBundleVersion</key><string>1</string>
    <key>UIApplicationSupportsMultipleScenes</key><false/>
    {platform}
</dict>
</plist>
"#
    )
}

#[cfg(test)]
mod tests {
    use clap::ValueEnum as _;

    use super::{HostWindow, Target};

    /// `--window-size` reaches every desktop host; GPUI runs no app of
    /// Rust only.
    #[test]
    fn the_desktop_hosts_take_a_size() {
        for target in [Target::Macos, Target::Linux, Target::Windows] {
            assert!(
                HostWindow::default().check(target, true).is_ok(),
                "Rust app, {target:?}"
            );
        }
        assert!(HostWindow::default().check(Target::Gpui, true).is_err());
        let sized = HostWindow {
            size: Some("700x500"),
            ..HostWindow::default()
        };
        for target in [Target::Macos, Target::Linux, Target::Windows, Target::Gpui] {
            assert!(sized.check(target, false).is_ok(), "{target:?}");
        }
        for target in [Target::Catalyst, Target::Ios, Target::Android, Target::Web] {
            assert!(sized.check(target, false).is_err(), "{target:?}");
        }
        assert_eq!(sized.args(), ["--window-size", "700x500"]);
        let named = HostWindow {
            name: Some("Orders"),
            ..HostWindow::default()
        };
        assert!(named.check(Target::Macos, false).is_ok());
        assert!(named.check(Target::Linux, false).is_err());
    }

    /// The desktop hosts get each app's own id, so each keeps its own data.
    #[test]
    fn hosts_get_the_apps_id() {
        let dir = std::env::temp_dir().join(format!("nsh-run-app-id-{}", std::process::id()));
        let (named, unnamed) = (dir.join("named"), dir.join("Notes"));
        for app in [&named, &unnamed] {
            std::fs::create_dir_all(app).unwrap();
            std::fs::write(app.join("App.tsx"), "").unwrap();
        }
        std::fs::write(named.join("nsh.json"), r#"{ "id": "com.acme.orders" }"#).unwrap();
        assert_eq!(
            crate::package::app_id(&named.join("App.tsx")).unwrap(),
            "com.acme.orders"
        );
        assert_eq!(
            crate::package::app_id(&unnamed.join("App.tsx")).unwrap(),
            "com.example.notes"
        );
        std::fs::remove_dir_all(&dir).unwrap();
    }

    #[test]
    fn gpui_is_a_target_with_its_own_host() {
        let target = Target::from_str("gpui", false).unwrap();
        assert_eq!(target, Target::Gpui);
        assert_eq!(target.platform().binary(false), "nsh-gpui-host");
    }
}