nsh-cli 0.7.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
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
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,
    /// The development host in this terminal.
    Tui,
}

impl Target {
    /// Whether the dev server listens on every interface for this target,
    /// or on loopback only. Phones open the web page at the LAN address
    /// and a device's host may be on the network; a desktop window, the
    /// terminal and Catalyst connect on this machine.
    pub(crate) fn uses_network(self) -> bool {
        matches!(self, Target::Ios | Target::Android | Target::Web)
    }

    /// 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::Tui => crate::runtime::Platform::Tui,
            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)]
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 selected host's performance monitor.
    pub(crate) fps: bool,
    /// Terminal Cell dimensions, overriding nsh.json.
    pub(crate) points_per_cell: Option<String>,
}

/// The host window's own options: the desktop hosts take the size
/// ([`HostWindow::check`]), the macOS host the name and the display 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>,
    /// The display the window opens on, from 1 (the primary display).
    pub(crate) display: Option<usize>,
    /// Never the active app (`--background`): the window shows, the
    /// keyboard stays with the app the user types in, as `nsh test` runs
    /// its apps.
    pub(crate) background: bool,
}

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.display.is_some() && (target != Target::Macos || rust_root) {
            bail!(
                "--display 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"
            );
        }
        if self.background && (!crate::test_host::runs_in_background(target) || rust_root) {
            bail!(
                "--background needs a desktop host (--target macos, linux, windows or gpui) and a TSX entry"
            );
        }
        Ok(())
    }

    /// The arguments of the size, the display and the background, for a
    /// desktop host.
    fn args(&self) -> Vec<String> {
        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".to_owned(), size.to_owned()]);
        }
        if let Some(display) = self.display {
            // One-based, as the host counts them.
            args.extend(["--display".to_owned(), display.to_string()]);
        }
        if self.background {
            // The host the tests run in takes it too (`test_host.rs`).
            args.push("--background".to_owned());
        }
        args
    }
}

fn validate_listen(listen: crate::dev::Listen, target: Target) -> anyhow::Result<()> {
    if target == Target::Android
        && !matches!(
            listen.host,
            std::net::Ipv4Addr::UNSPECIFIED | std::net::Ipv4Addr::LOCALHOST
        )
    {
        bail!(
            "--host {} is not supported with --target android: adb reverse forwards the device's 127.0.0.1 to this machine's 127.0.0.1, so use 127.0.0.1 or 0.0.0.0",
            listen.host
        );
    }
    Ok(())
}

/// 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,
    listen: crate::dev::Listen,
    release: bool,
    flags: HostFlags,
    target: Target,
    device: Option<&str>,
    window: HostWindow<'_>,
) -> anyhow::Result<()> {
    let HostFlags {
        limits,
        trace,
        fps,
        points_per_cell,
    } = flags;
    if points_per_cell.is_some() && target != Target::Tui {
        bail!("--points-per-cell needs --target tui");
    }
    if fps
        && !matches!(
            target,
            Target::Macos | Target::Linux | Target::Ios | Target::Windows | Target::Tui
        )
    {
        bail!(
            "--fps needs --target macos, linux, windows, ios or tui (the other hosts have no performance monitor yet)"
        );
    }
    window.check(target, crate::rust_app::is_root(entry))?;
    validate_listen(listen, target)?;
    if matches!(
        target,
        Target::Macos | Target::Linux | Target::Windows | Target::Gpui
    ) {
        crate::package::note_hidden_main_window(entry);
    }
    if release {
        // The app's crates and NSH's in the host, optimized as in a
        // package: a debug host measures debug code.
        crate::rust_app::set_release_hosts();
    }
    // The app's directory: its `nsh.json`'s, which may be above the entry
    // (`"entry"`).
    let work = nsh_bundler::app_dir::app_dir_of(&dunce::canonicalize(entry)?).join(".nsh");
    if target == Target::Tui {
        return run_tui(
            entry,
            listen,
            release,
            HostFlags {
                limits,
                trace,
                fps,
                points_per_cell,
            },
            &work,
        );
    }
    if crate::rust_app::is_root(entry) {
        return run_rust_app(entry, listen, target, device, &work);
    }
    if target == Target::Android {
        return run_android(entry, listen, release, limits, &work, trace, device);
    }
    if target == Target::Web {
        return run_web(entry, listen, 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, SimulatorWindow::Front)?;
            let _ = simctl(&["terminate", &udid, BUNDLE_ID]);
            Some(udid)
        }
        Target::Catalyst
        | Target::Android
        | Target::Linux
        | Target::Macos
        | Target::Windows
        | Target::Web
        | Target::Gpui
        | Target::Tui => None,
    };
    // The host it starts connects by itself: no addresses to show.
    let session = DevSession::start(entry, listen, 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 config = crate::package::read_config(entry)?;
            let app = package_catalyst(&work, &host, &config)?;
            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());
            let schemes = crate::package::read_config(entry)?.schemes;
            if !schemes.is_empty() {
                command.args(["--schemes", &schemes.join(",")]);
            }
            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, or the menu bar
        // app `nsh.json` `macos.activationPolicy` says, from the start.
        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(config.macos_host_args())
                .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(crate::windows::host_args(entry, &work))
                .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 config = crate::package::read_config(entry)?;
            let app = package_ios(&work, &host, &config)?;
            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 env = simctl_app_env(&config);
            let step = ui::Step::start("launching the development host");
            simctl_with_env(&launch, &env)?;
            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 | Target::Tui => 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,
    listen: crate::dev::Listen,
    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, listen, 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,
    listen: crate::dev::Listen,
    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, appearance and
    // activation policy.
    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();
        }
        // A menu bar app on macOS (the other runners leave it).
        config.macos.add_to_app_json(&mut info);
        // The runner runs in place, outside an app bundle: the Dock shows
        // the app's icon only when the runner is given it.
        if target == Target::Macos
            && let Some(icon) = config.icon(crate::package::PackageTarget::Macos)
        {
            info["icon"] = icon.to_string_lossy().as_ref().into();
        }
        config.add_file_types_to_app_json(&mut info);
        // The main window's launch options, as a package's `app.json`.
        if let Some(window) = &config.window {
            info["window"] = window.clone();
        }
        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, &config)?;
            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, SimulatorWindow::Front)?;
            let env = simctl_app_env(&config);
            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])
                .envs(env)
                .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, device)?;
            let env = android_app_env(&config);
            let out = run.join("android");
            // The device's ABI alone: each one is a build of the app's crate.
            let abi = android::preferred_abi(&serial, &android::device_abis(&sdk, &serial)?)?;
            package_for_run(
                &entry,
                crate::package::PackageTarget::Android,
                &out,
                config,
                std::slice::from_ref(&abi),
            )?;
            let apk = out.join(format!("{name}.apk"));
            let step = ui::Step::start(format!("installing {id} on {serial}"));
            android::install(&sdk, &serial, &apk, &id, &["-r"], android::AppData::Kept)?;
            let activity = format!("{id}/com.longbridge.nsh.AppActivity");
            let mut start = android::dev_start(&activity);
            start.extend(env.iter().map(String::as_str));
            android::adb(&sdk, &serial, &start)?;
            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, listen, false, None)?;
            session.print_web_url();
            session.watch(|| Ok(false))
        }
        Target::Gpui | Target::Tui => unreachable!("handled before Rust runner selection"),
    }
}

/// Packages the Rust app at `entry` for `target` into `out` (as `nsh
/// package` does), for `nsh run` to install; Android: for `abis`.
fn package_for_run(
    entry: &Path,
    target: crate::package::PackageTarget,
    out: &Path,
    config: crate::package::AppConfig,
    abis: &[String],
) -> anyhow::Result<()> {
    crate::package::package(crate::package::PackageOptions {
        entry,
        target,
        out,
        config,
        sign: None,
        profiles: &[],
        keystore: None,
        abis,
        format: crate::android::Format::Apk,
        arch: None,
        run: false,
        device: None,
        asset_url: None,
        development: true,
    })
}

/// 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
}

/// Checks the terminal scale at the CLI/configuration boundary.
pub(crate) fn parse_points_per_cell(value: &str) -> Result<String, String> {
    let valid = value.split_once('x').is_some_and(|(width, height)| {
        [width, height]
            .into_iter()
            .all(|part| part.parse::<f32>().is_ok_and(|n| n.is_finite() && n > 0.0))
    });
    if !valid {
        return Err("points per Cell must be WIDTHxHEIGHT with finite, positive dimensions".into());
    }
    Ok(value.to_owned())
}

fn run_tui(
    entry: &Path,
    listen: crate::dev::Listen,
    release: bool,
    flags: HostFlags,
    work: &Path,
) -> anyhow::Result<()> {
    let HostFlags {
        limits,
        trace,
        fps,
        points_per_cell,
    } = flags;
    let config = crate::package::read_config(entry)?;
    let cells = points_per_cell
        .as_deref()
        .or(config.tui.points_per_cell.as_deref())
        .unwrap_or("8x16");
    parse_points_per_cell(cells).map_err(anyhow::Error::msg)?;
    fs::create_dir_all(work)?;
    let path = work.join("tui.log");
    let building = ui::Step::start(format!("building {}", ui::path(entry)));
    let session = DevSession::start(entry, listen, release, limits)?;
    building.finish();
    // A Rust root also uses the development host, which receives the Root event.
    let host = crate::runtime::test_host(Platform::Tui)?;
    // Preparation stays visible until the host takes over the terminal. From
    // here, diagnostics belong in the panel so they cannot overwrite its UI.
    let _terminal_logs = ui::LogFile::open(&path)?;
    let diagnostics = fs::OpenOptions::new()
        .create(true)
        .append(true)
        .open(&path)?;
    let mut command = Command::new(host);
    command
        .env("NSH_DEV_APP_DIR", work.parent().context("app directory")?)
        .args([
            "--dev-server",
            &session.local_url(),
            "--points-per-cell",
            cells,
        ])
        .arg("--log-file")
        .arg(&path)
        .stdin(Stdio::inherit())
        .stdout(Stdio::inherit())
        .stderr(diagnostics);
    if fps {
        command.arg("--fps");
    }
    if trace {
        command.arg("--trace");
    }
    #[cfg(windows)]
    {
        use std::os::windows::process::CommandExt as _;
        command.creation_flags(windows_sys::Win32::System::Threading::CREATE_NEW_PROCESS_GROUP);
    }
    let _stoppable = ui::Stoppable::new();
    let mut child = command
        .spawn()
        .context("launch the terminal development host")?;
    #[cfg(windows)]
    let _job = KillOnClose::assign(&child);
    let result = session.watch(|| match child.try_wait()? {
        Some(status) if status.success() => Ok(true),
        Some(status) => bail!(
            "the terminal host exited with {status}; see {}",
            path.display()
        ),
        None => Ok(false),
    });
    if !matches!(child.try_wait(), Ok(Some(_))) {
        // Let the host leave raw mode and the alternate screen before ending it.
        #[cfg(unix)]
        // SAFETY: this is the live child owned by this invocation.
        unsafe {
            libc::kill(child.id() as libc::pid_t, libc::SIGTERM);
        }
        #[cfg(windows)]
        // SAFETY: the child was started in its own console process group.
        unsafe {
            windows_sys::Win32::System::Console::GenerateConsoleCtrlEvent(
                windows_sys::Win32::System::Console::CTRL_BREAK_EVENT,
                child.id(),
            );
        }
        let deadline = std::time::Instant::now() + std::time::Duration::from_secs(2);
        while matches!(child.try_wait(), Ok(None)) && std::time::Instant::now() < deadline {
            std::thread::sleep(std::time::Duration::from_millis(10));
        }
        if !matches!(child.try_wait(), Ok(Some(_))) {
            let _ = child.kill();
        }
    }
    let _ = child.wait();
    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) on `device` ([`crate::android::device`]), forwards the dev
/// server port to the device and starts the host.
fn run_android(
    entry: &Path,
    listen: crate::dev::Listen,
    release: bool,
    limits: Option<HostLimits>,
    work: &Path,
    trace: bool,
    device: Option<&str>,
) -> anyhow::Result<()> {
    use crate::android;
    let sdk = android::Sdk::find()?;
    let serial = android::device(&sdk, device)?;
    // 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, listen, release, limits)?;
    let abis = android::dev_abis(&sdk, &serial)?;
    let runtime = crate::runtime::android(true, &abis)?;
    let config = crate::package::read_config(entry)?.android;
    install_android_host(
        &sdk,
        &serial,
        work,
        &runtime,
        &abis,
        Some(&AppLibraries {
            libraries: &config.libraries,
            placeholders: &config.manifest_placeholders,
            target_sdk: config.target_sdk()?,
        }),
    )?;
    // The device reaches the dev server on its own 127.0.0.1 through
    // `adb reverse`, until the run ends.
    let _reverse = android::Reverse::add(&sdk, &serial, session.port())?;
    let url = session.loopback_url();
    let mut start = android::dev_start("com.longbridge.nsh.host/com.longbridge.nsh.DevActivity");
    start.extend(["--es", "url", &url]);
    if trace {
        start.extend(["--ez", "trace", "true"]);
    }
    let env = android_app_env(&crate::package::read_config(entry)?);
    start.extend(env.iter().map(String::as_str));
    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
}

/// What one app gives the Android development host it runs in.
pub(crate) struct AppLibraries<'a> {
    /// `nsh.json` `android.libraries`, which go before its crates'.
    pub(crate) libraries: &'a [crate::android::Library],
    /// `nsh.json` `android.manifestPlaceholders`.
    pub(crate) placeholders: &'a std::collections::BTreeMap<String, String>,
    /// `nsh.json` `android.targetSdk`: the host compiles against it when it
    /// is newer than its own.
    pub(crate) target_sdk: u32,
}

/// 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). It takes the runtime's libraries for `abis` (empty: every
/// one the runtime has), the Java libraries of the app's `nsh.json`
/// (`app`; `None` for the shared test host, which runs many apps) before
/// its crates'.
pub(crate) fn install_android_host(
    sdk: &crate::android::Sdk,
    serial: &str,
    work: &Path,
    runtime: &Path,
    abis: &[String],
    app: Option<&AppLibraries<'_>>,
) -> 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");
    // What the app's crates declare for the manifest (the apps they start,
    // their components) and the Java libraries they list: part of the
    // build, as the runtime is.
    let meta = crate::module_meta::for_dev_host(
        "aarch64-linux-android",
        crate::module_meta::Platform::Android,
    );
    let mut version = runtime_version(runtime, abis)?;
    for line in meta
        .android_permissions
        .iter()
        .chain(&meta.android_queries)
        .chain(&meta.android_application)
    {
        version.push('\n');
        version.push_str(line);
    }
    // A library's contents, not its time: a rebuilt jar that is the same
    // keeps the host. Their order and crates settle which of two AARs'
    // resources of one name the host takes.
    let mut libraries = app.map(|app| app.libraries.to_vec()).unwrap_or_default();
    for library in &meta.android_libraries {
        if !libraries.iter().any(|have| have.path == library.path) {
            libraries.push(library.clone());
        }
    }
    for library in &libraries {
        let sha256 = android::file_sha256(&library.path).unwrap_or_default();
        version.push_str(&format!("\n{} {sha256}", library.path.display()));
        if let Some(owner) = &library.owner {
            version.push_str(&format!(" ({owner})"));
        }
    }
    // The platform the host compiles against: the app's, when newer, which
    // its libraries may need (`minCompileSdk`).
    let target_sdk = app.map_or(android::DEFAULT_TARGET_SDK, |app| {
        app.target_sdk.max(android::DEFAULT_TARGET_SDK)
    });
    if target_sdk != android::DEFAULT_TARGET_SDK {
        version.push_str(&format!("\ntargetSdk {target_sdk}"));
    }
    let placeholders = app.map(|app| app.placeholders);
    for (name, value) in placeholders.into_iter().flatten() {
        version.push_str(&format!("\n${{{name}}}={value}"));
    }
    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,
                target_sdk,
                activity: "com.longbridge.nsh.DevActivity",
                dev: true,
                cleartext: true,
                notifications: true,
                // The host runs any app: its pages may capture media.
                microphone: true,
                camera: true,
                libraries: &libraries,
                library_cache: &work.join("android/libraries"),
                manifest_placeholders: placeholders,
                permissions: &meta.android_permissions,
                queries: &meta.android_queries,
                application: &meta.android_application,
                schemes: &[],
                share_mime_types: &[],
                links: &[],
                rust: false,
                dark: false,
                fixed_appearance: false,
                runtime,
                abis,
                icon: None,
                launch_screen: None,
                assets: Vec::new(),
                sounds: Vec::new(),
                res: None,
                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}"));
        // The host keeps only what apps under test and in development
        // write, which they start without again.
        android::install(
            sdk,
            serial,
            &apk_path,
            BUNDLE_ID,
            &["-r", "-t"],
            android::AppData::Disposable,
        )?;
        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, abis: &[String]) -> 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"))? {
        let dir = entry?.path();
        // Libraries of other ABIs left from earlier runs are not in the APK.
        if !abis.is_empty()
            && !dir
                .file_name()
                .is_some_and(|abi| abis.iter().any(|a| a.as_str() == abi))
        {
            continue;
        }
        files.push(dir.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, with
/// the languages of the app whose `nsh.json` is `config` (`locales`,
/// `ios.infoPlistStrings`).
fn package_catalyst(
    work: &Path,
    host: &Path,
    config: &crate::package::AppConfig,
) -> 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)?;
    let meta = crate::module_meta::for_dev_host(
        "aarch64-apple-ios-macabi",
        crate::module_meta::Platform::Ios,
    );
    let strings = dev_host_strings(config, &meta)?;
    let localized = localized_files(&strings);
    fs::write(
        contents.join("Info.plist"),
        with_crates_info(info_plist(Target::Catalyst), &meta, config, &strings)?,
    )?;
    crate::apple::write_localized_info(&contents.join("Resources"), &localized)?;
    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), with the languages
/// of the app whose `nsh.json` is `config`, as [`package_catalyst`], and its
/// `ios.entitlements` and `ios.extensions`.
pub(crate) fn package_ios(
    work: &Path,
    host: &Path,
    config: &crate::package::AppConfig,
) -> anyhow::Result<PathBuf> {
    let app = work.join("ios").join(format!("{APP_NAME}.app"));
    fs::create_dir_all(&app)?;
    // The signature seals the Info.plist and the other languages' strings
    // too: one changed (the app's crates declare other keys, the app
    // translates them anew) is signed again, as a new binary is.
    let plist = app.join("Info.plist");
    let meta = crate::module_meta::for_dev_host(
        "aarch64-apple-ios-sim",
        crate::module_meta::Platform::Ios,
    );
    let strings = dev_host_strings(config, &meta)?;
    let localized = localized_files(&strings);
    let info = with_crates_info(info_plist(Target::Ios), &meta, config, &strings)?;
    let info_changed = fs::read_to_string(&plist).ok().as_deref() != Some(info.as_str());
    if info_changed {
        fs::write(&plist, &info)?;
    }
    let strings_changed = crate::apple::write_localized_info(&app, &localized)?;
    let installed = install_binary(host, &app.join("nsh-ios-host"))?;
    let (extensions, extensions_changed) = dev_host_extensions(config, &app, &info)?;
    // The app's entitlements, as its simulator package has them: an app
    // group the host shares with the app's extensions, for one.
    let entitlements = config.ios.entitlements(crate::apple::ApplePlatform::Ios)?;
    let entitlements_file = work.join("ios").join(format!("{APP_NAME}.entitlements"));
    let entitlements_changed = if entitlements.is_empty() {
        fs::remove_file(&entitlements_file).is_ok()
    } else {
        let mut xml = Vec::new();
        plist::Value::Dictionary(entitlements).to_writer_xml(&mut xml)?;
        let changed = fs::read(&entitlements_file).ok() != Some(xml.clone());
        if changed {
            fs::write(&entitlements_file, &xml)?;
        }
        changed
    };
    if installed
        || info_changed
        || strings_changed
        || extensions_changed
        || entitlements_changed
        || !app.join("_CodeSignature").exists()
    {
        // The app's signature seals its extensions': they
        // are signed first.
        crate::app_extensions::sign_ad_hoc(&extensions, &work.join("ios"))?;
        let mut codesign = Command::new("codesign");
        codesign.args(["--force", "--sign", "-", "--timestamp=none"]);
        if entitlements_file.exists() {
            codesign.arg("--entitlements").arg(&entitlements_file);
        }
        let status = codesign
            .arg(&app)
            .stdout(Stdio::null())
            .stderr(Stdio::null())
            .status()
            .context("run codesign")?;
        if !status.success() {
            bail!("codesign failed for {}", app.display());
        }
    }
    Ok(app)
}

/// The app's extensions (`nsh.json` `ios.extensions`, `config`) copied into
/// the development host `app` (whose `Info.plist` is `info`) afresh, under
/// the host's identifier: iOS installs an extension only under its
/// containing app's, and the host runs any app. Returns them, to sign, and
/// whether `PlugIns/` changed (it had or has some).
fn dev_host_extensions(
    config: &crate::package::AppConfig,
    app: &Path,
    info: &str,
) -> anyhow::Result<(Vec<crate::app_extensions::Embedded>, bool)> {
    let plugins = app.join("PlugIns");
    let had = plugins.exists();
    if had {
        fs::remove_dir_all(&plugins).with_context(|| format!("remove {}", plugins.display()))?;
    }
    if config.ios.extensions.is_empty() {
        return Ok((Vec::new(), had));
    }
    let app_id = config.id.as_deref().context(
        "nsh.json ios.extensions need the app's \"id\", which their identifiers start with",
    )?;
    let mut info = plist::Value::from_reader_xml(info.as_bytes())?
        .into_dictionary()
        .context("the host's Info.plist is a dictionary")?;
    info.insert("CFBundleIdentifier".to_owned(), app_id.into());
    let extensions =
        crate::app_extensions::embed(&config.ios.extensions, app, &info, true, Some(BUNDLE_ID))?;
    Ok((extensions, true))
}

/// 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> {
    simctl_with_env(args, &[])
}

/// [`simctl`] with variables in its environment: `launch` passes those
/// named `SIMCTL_CHILD_<name>` to the app as `<name>` ([`simctl_app_env`]).
pub(crate) fn simctl_with_env(
    args: &[&str],
    env: &[(String, std::ffi::OsString)],
) -> anyhow::Result<String> {
    let output = Command::new("xcrun")
        .arg("simctl")
        .args(args)
        .envs(env.iter().map(|(name, value)| (name, value)))
        .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())
}

/// The variables of this environment that the app's `nsh.json` declares in
/// `capabilities.process.env`, named for `xcrun simctl launch`, which
/// passes the app only its caller's `SIMCTL_CHILD_<name>` variables: the
/// app in the simulator reads them in `process.env` as the desktops' hosts,
/// the CLI's children, do. Only declared names, never the whole
/// environment: the declaration is what the app may read.
pub(crate) fn simctl_app_env(
    config: &crate::package::AppConfig,
) -> Vec<(String, std::ffi::OsString)> {
    simctl_child_env(&declared_env(config), |name| std::env::var_os(name))
}

/// The variable names the app's `nsh.json` declares in
/// `capabilities.process.env`: the only ones a development host is given
/// from this environment.
fn declared_env(config: &crate::package::AppConfig) -> Vec<String> {
    config
        .capabilities
        .as_ref()
        .and_then(|c| nsh_core::access::Capabilities::from_json_lenient(c).ok())
        .map(|(caps, _)| caps.process.env)
        .unwrap_or_default()
}

/// What the simulator sets for each app it launches: its container's paths
/// and the simulated runtime's. The app reads the simulator's values; the
/// Mac's would point it outside its container.
const SIMULATOR_ENV: [&str; 4] = ["HOME", "CFFIXED_USER_HOME", "TMPDIR", "PATH"];

/// [`simctl_app_env`] over the environment `var` reads. Each name is looked
/// up as the OS matches names, as the runtime's `process.env` does
/// (exactly on macOS, where the simulator runs).
fn simctl_child_env(
    declared: &[String],
    var: impl Fn(&str) -> Option<std::ffi::OsString>,
) -> Vec<(String, std::ffi::OsString)> {
    let mut env: Vec<(String, std::ffi::OsString)> = Vec::new();
    for name in declared {
        let child = format!("SIMCTL_CHILD_{name}");
        let simulators = SIMULATOR_ENV.contains(&name.as_str())
            || name.starts_with("DYLD_")
            || name.starts_with("SIMULATOR_");
        if simulators || env.iter().any(|(n, _)| *n == child) {
            continue;
        }
        if let Some(value) = var(name) {
            env.push((child, value));
        }
    }
    env
}

/// The variables of this environment that the app's `nsh.json` declares in
/// `capabilities.process.env`, as `adb shell am start` arguments for the
/// Android development host and a Rust app's development build: `am start`
/// starts the app in a process the system makes, so each one goes as a
/// string extra `nsh.env.<name>`, which `DevActivity` (or a debuggable
/// build's `AppActivity`) sets in its process's environment before the app
/// starts.
/// The app reads them in `process.env` as the desktops' hosts, the CLI's
/// children, do.
pub(crate) fn android_app_env(config: &crate::package::AppConfig) -> Vec<String> {
    android_env_extras(&declared_env(config), |name| std::env::var_os(name))
}

/// What Android sets for each app process: its paths and the runtime's
/// (`PATH`, `ANDROID_ROOT`, `BOOTCLASSPATH`, ...). The app reads the
/// device's values; the computer's would point it at files the device does
/// not have.
fn android_system_env(name: &str) -> bool {
    ["PATH", "HOME", "TMPDIR", "EXTERNAL_STORAGE"].contains(&name)
        || name.starts_with("LD_")
        || name.starts_with("ANDROID_")
        || name.ends_with("CLASSPATH")
}

/// [`android_app_env`] over the environment `var` reads: `--es
/// nsh.env.<name> <value>` for each declared name with a value, once. Only
/// names of letters, digits and `_` (the extra's key is a word of the
/// command line) and UTF-8 values (an extra is a Java string) go.
fn android_env_extras(
    declared: &[String],
    var: impl Fn(&str) -> Option<std::ffi::OsString>,
) -> Vec<String> {
    let mut extras = Vec::new();
    let mut passed: Vec<&str> = Vec::new();
    for name in declared {
        let plain =
            !name.is_empty() && name.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_');
        if !plain || android_system_env(name) || passed.contains(&name.as_str()) {
            continue;
        }
        let Some(value) = var(name).and_then(|v| v.into_string().ok()) else {
            continue;
        };
        passed.push(name);
        extras.extend([
            "--es".to_owned(),
            format!("nsh.env.{name}"),
            shell_quote(&value),
        ]);
    }
    extras
}

/// `text` as one word of a POSIX shell's command line: `adb shell` joins its
/// arguments into a line the device's shell parses again.
fn shell_quote(text: &str) -> String {
    format!("'{}'", text.replace('\'', r"'\''"))
}

#[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,
}

/// How [`simulator`] shows the simulators' window.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum SimulatorWindow {
    /// In front, active: `nsh run`, where the user works with the app.
    Front,
    /// Opened, or left where it is, without becoming the active app: `nsh
    /// test`, whose input goes to the app in the simulator directly, so the
    /// keyboard stays with the app the user types in.
    Behind,
}

/// Picks a simulator (`wanted` by name or UDID; else a booted one; else the
/// newest iPhone), boots it and shows the Simulator app (`window`).
pub(crate) fn simulator(wanted: Option<&str>, window: SimulatorWindow) -> 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(window);
    Ok(device.udid.clone())
}

/// `open`'s arguments before what it opens: `-g` keeps a window opened
/// [`SimulatorWindow::Behind`] from activating the app.
fn open_args(window: SimulatorWindow) -> &'static [&'static str] {
    match window {
        SimulatorWindow::Front => &[],
        SimulatorWindow::Behind => &["-g"],
    }
}

/// Brings up the simulators' window: Simulator.app, or DeviceHub.app in
/// Xcode versions that replaced it.
fn show_simulators(window: SimulatorWindow) {
    let quiet = |cmd: &mut Command| {
        cmd.stdout(Stdio::null())
            .stderr(Stdio::null())
            .status()
            .is_ok_and(|s| s.success())
    };
    let open = || {
        let mut open = Command::new("open");
        open.args(open_args(window));
        open
    };
    if quiet(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(open().arg(&hub)) {
            return;
        }
    }
    ui::warn("no Simulator or DeviceHub app found: the simulator runs without a window");
}

/// The development host's `Info.plist` strings, by language: the app's
/// (`config`'s `ios.infoPlistStrings`) over those its crates declare
/// (`meta`) for the app's languages, as packages take them
/// ([`crate::module_meta::ModuleMeta::crate_strings`]). The host is not the
/// app's package: its `Info.plist` is its own, so a translated key it has
/// no value of is left to the package to refuse
/// ([`crate::apple::localized_info`]).
fn dev_host_strings(
    config: &crate::package::AppConfig,
    meta: &crate::module_meta::ModuleMeta,
) -> anyhow::Result<serde_json::Map<String, serde_json::Value>> {
    let mut strings = config.ios.info_plist_strings.clone();
    crate::module_meta::add_strings(
        &mut strings,
        &meta.crate_strings(config, crate::apple::ApplePlatform::Ios),
    );
    // Checked as `nsh.json`'s are.
    crate::apple::AppleConfig {
        info_plist_strings: strings.clone(),
        ..Default::default()
    }
    .info_plist_strings(crate::apple::ApplePlatform::Ios)?;
    Ok(strings)
}

/// The `InfoPlist.strings` files of `strings` (checked by
/// [`dev_host_strings`]), by language: none of a language without text.
fn localized_files(
    strings: &serde_json::Map<String, serde_json::Value>,
) -> std::collections::BTreeMap<String, String> {
    strings
        .iter()
        .filter_map(|(language, texts)| {
            let texts: std::collections::BTreeMap<String, String> = texts
                .as_object()?
                .iter()
                .filter_map(|(key, text)| Some((key.clone(), text.as_str()?.to_owned())))
                .collect();
            (!texts.is_empty()).then(|| (language.clone(), crate::apple::strings_file(&texts)))
        })
        .collect()
}

/// The development host's `Info.plist` with the keys the app's crates
/// declare (`meta`, [`crate::module_meta`]) that it does not set, and the
/// app's languages declared as its packages declare them: its `locales`
/// (`config`) and those its `Info.plist` strings (`strings`) have text in
/// ([`crate::package::bundle_languages`]).
fn with_crates_info(
    plist: String,
    meta: &crate::module_meta::ModuleMeta,
    config: &crate::package::AppConfig,
    strings: &serde_json::Map<String, serde_json::Value>,
) -> anyhow::Result<String> {
    let languages = crate::package::bundle_languages(&config.localizations, strings);
    if meta.ios_info.is_empty() && languages.is_empty() {
        return Ok(plist);
    }
    let crates = crate::apple::AppleConfig {
        info_plist: meta.ios_info.clone(),
        ..Default::default()
    }
    .info_plist(crate::apple::ApplePlatform::Ios)?;
    let mut value = plist::Value::from_reader_xml(plist.as_bytes())?;
    let dict = value
        .as_dictionary_mut()
        .context("the host's Info.plist is a dictionary")?;
    for (key, value) in crates {
        if !dict.contains_key(&key) {
            dict.insert(key, value);
        }
    }
    if !languages.is_empty() {
        dict.insert("CFBundleDevelopmentRegion".into(), "en".into());
        dict.insert(
            "CFBundleLocalizations".into(),
            plist::Value::Array(languages.into_iter().map(plist::Value::String).collect()),
        );
    }
    let mut out = Vec::new();
    value.to_writer_xml(&mut out)?;
    Ok(String::from_utf8(out)?)
}

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
        | Target::Tui => {
            "<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>"
        }
    };
    // The host runs any app: its pages may capture media. What the app's
    // crates use (`nsh-extra`'s `speech`) they declare
    // (`with_crates_info`).
    let usage = crate::package::WEB_MEDIA_USAGE_DESCRIPTIONS
        .iter()
        .map(|(_, key, text)| format!("<key>{key}</key><string>{text}</string>"))
        .collect::<Vec<_>>()
        .join("\n    ");
    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/>
    {usage}
    {platform}
</dict>
</plist>
"#
    )
}

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

    use super::{
        HostWindow, SimulatorWindow, Target, android_app_env, android_env_extras, open_args,
        shell_quote, simctl_app_env, simctl_child_env,
    };

    /// `nsh run` brings the simulators' window to the front; `nsh test`
    /// opens it without activating it (`open -g`), so the keyboard stays
    /// with the app the user types in.
    #[test]
    fn only_a_run_brings_the_simulator_to_the_front() {
        assert!(open_args(SimulatorWindow::Front).is_empty());
        assert_eq!(open_args(SimulatorWindow::Behind), ["-g"]);
    }

    /// The simulator's app gets the declared variables this environment
    /// has, prefixed for simctl, each once; undeclared ones stay behind,
    /// and so do those the simulator sets for its apps (`HOME`).
    #[test]
    fn simctl_passes_only_declared_variables() {
        let vars = |name: &str| {
            ["NSH_GALLERY_DEMO", "API_TOKEN", "HOME", "DYLD_LIBRARY_PATH"]
                .contains(&name)
                .then(|| format!("{name} value").into())
        };
        let declared = [
            "NSH_GALLERY_DEMO",
            "NSH_GALLERY_SECTION",
            "NSH_GALLERY_DEMO",
            "API_TOKEN",
            "HOME",
            "DYLD_LIBRARY_PATH",
        ]
        .map(String::from);
        assert_eq!(
            simctl_child_env(&declared, vars),
            [
                (
                    "SIMCTL_CHILD_NSH_GALLERY_DEMO".to_owned(),
                    "NSH_GALLERY_DEMO value".into()
                ),
                (
                    "SIMCTL_CHILD_API_TOKEN".to_owned(),
                    "API_TOKEN value".into()
                ),
            ]
        );
        assert!(simctl_child_env(&[], vars).is_empty());
    }

    /// An app without a declaration of `process.env`, or none at all, gets
    /// nothing from this environment; one that declares a name gets it
    /// (`cargo test` sets `CARGO_PKG_NAME`).
    #[test]
    fn simctl_passes_nothing_undeclared() {
        let config = |json: &str| {
            let mut config = crate::package::AppConfig::default();
            config.capabilities = Some(serde_json::from_str(json).unwrap());
            config
        };
        assert!(simctl_app_env(&crate::package::AppConfig::default()).is_empty());
        assert!(simctl_app_env(&config(r#"{ "clipboard": true }"#)).is_empty());
        assert_eq!(
            simctl_app_env(&config(r#"{ "process": { "env": ["CARGO_PKG_NAME"] } }"#))
                .into_iter()
                .map(|(name, _)| name)
                .collect::<Vec<_>>(),
            ["SIMCTL_CHILD_CARGO_PKG_NAME"]
        );
    }

    /// The Android host gets the declared variables this environment has,
    /// each once, as string extras with quoted values; undeclared ones stay
    /// behind, and so do those Android sets for its apps, names that are
    /// not plain and values that are not UTF-8.
    #[test]
    fn android_passes_only_declared_variables() {
        let vars = |name: &str| -> Option<std::ffi::OsString> {
            match name {
                "NSH_GALLERY_DEMO" => Some("accordion".into()),
                "API_TOKEN" => Some("it's $HOME".into()),
                "EMPTY" => Some("".into()),
                #[cfg(unix)]
                "BINARY" => Some(
                    <std::ffi::OsStr as std::os::unix::ffi::OsStrExt>::from_bytes(b"\xff").into(),
                ),
                "PATH" | "HOME" | "TMPDIR" | "LD_PRELOAD" | "ANDROID_ROOT" | "BOOTCLASSPATH"
                | "EXTERNAL_STORAGE" | "A-B" | "A B" => Some("system".into()),
                _ => None,
            }
        };
        let declared = [
            "NSH_GALLERY_DEMO",
            "NSH_GALLERY_SECTION",
            "NSH_GALLERY_DEMO",
            "API_TOKEN",
            "EMPTY",
            "BINARY",
            "PATH",
            "HOME",
            "TMPDIR",
            "LD_PRELOAD",
            "ANDROID_ROOT",
            "BOOTCLASSPATH",
            "EXTERNAL_STORAGE",
            "A-B",
            "A B",
            "",
        ]
        .map(String::from);
        assert_eq!(
            android_env_extras(&declared, vars),
            [
                "--es",
                "nsh.env.NSH_GALLERY_DEMO",
                "'accordion'",
                "--es",
                "nsh.env.API_TOKEN",
                r"'it'\''s $HOME'",
                "--es",
                "nsh.env.EMPTY",
                "''",
            ]
        );
        assert!(android_env_extras(&[], vars).is_empty());
    }

    /// An app without a declaration of `process.env` gets nothing on
    /// Android either; one that declares a name gets it (`cargo test` sets
    /// `CARGO_PKG_NAME`).
    #[test]
    fn android_passes_nothing_undeclared() {
        let mut config = crate::package::AppConfig::default();
        assert!(android_app_env(&config).is_empty());
        config.capabilities = Some(serde_json::json!({ "process": { "env": ["CARGO_PKG_NAME"] } }));
        assert_eq!(
            android_app_env(&config),
            ["--es", "nsh.env.CARGO_PKG_NAME", "'nsh-cli'"]
        );
    }

    /// A value is one word for the device's shell, whatever it holds.
    #[test]
    fn shell_quote_keeps_one_word() {
        assert_eq!(shell_quote(""), "''");
        assert_eq!(shell_quote("a b"), "'a b'");
        assert_eq!(shell_quote(r#"$HOME `x` "q""#), r#"'$HOME `x` "q"'"#);
        assert_eq!(shell_quote("it's"), r"'it'\''s'");
        assert_eq!(shell_quote("''"), r"''\'''\'''");
    }

    /// Only phones and browsers that may be on the network get a dev
    /// server listening on every interface; hosts on this machine get
    /// loopback.
    #[test]
    fn only_targets_that_may_be_other_machines_listen_on_the_network() {
        let network: Vec<_> = Target::value_variants()
            .iter()
            .filter(|target| target.uses_network())
            .copied()
            .collect();
        assert_eq!(network, [Target::Ios, Target::Android, Target::Web]);
    }

    #[test]
    fn android_rejects_bind_hosts_that_adb_reverse_cannot_reach() {
        use std::net::Ipv4Addr;

        let listen = |host| crate::dev::Listen { port: 8790, host };
        assert!(super::validate_listen(listen(Ipv4Addr::UNSPECIFIED), Target::Android).is_ok());
        assert!(super::validate_listen(listen(Ipv4Addr::LOCALHOST), Target::Android).is_ok());
        assert!(
            super::validate_listen(listen(Ipv4Addr::new(192, 168, 1, 20)), Target::Android)
                .is_err()
        );
        assert!(
            super::validate_listen(listen(Ipv4Addr::new(127, 0, 0, 2)), Target::Android).is_err()
        );
        assert!(
            super::validate_listen(listen(Ipv4Addr::new(192, 168, 1, 20)), Target::Web).is_ok()
        );
    }

    /// `--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());
    }

    /// `--display` reaches the macOS host only, for a TSX entry.
    #[test]
    fn the_macos_host_takes_a_display() {
        let placed = HostWindow {
            display: Some(2),
            ..HostWindow::default()
        };
        assert!(placed.check(Target::Macos, false).is_ok());
        assert!(placed.check(Target::Macos, true).is_err());
        for target in [Target::Linux, Target::Windows, Target::Gpui, Target::Ios] {
            assert!(placed.check(target, false).is_err(), "{target:?}");
        }
        assert_eq!(placed.args(), ["--display", "2"]);
    }

    /// `--background` reaches the desktop hosts that run tests in the
    /// background, for a TSX entry.
    #[test]
    fn the_desktop_hosts_run_in_the_background() {
        let background = HostWindow {
            background: true,
            ..HostWindow::default()
        };
        for target in [Target::Macos, Target::Linux, Target::Windows, Target::Gpui] {
            assert!(background.check(target, false).is_ok(), "{target:?}");
        }
        assert!(background.check(Target::Macos, true).is_err());
        for target in [Target::Catalyst, Target::Ios, Target::Android, Target::Web] {
            assert!(background.check(target, false).is_err(), "{target:?}");
        }
        assert_eq!(background.args(), ["--background"]);
    }

    /// 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");
    }

    /// The development host declares the app's languages as its packages
    /// do (`locales` and those its strings have text in), and takes the
    /// crates' translations for those languages only.
    #[test]
    fn dev_hosts_declare_the_apps_languages() {
        let mut config: crate::package::AppConfig = serde_json::from_value(serde_json::json!({
            "ios": { "infoPlistStrings": {
                "zh-Hans": { "NSCameraUsageDescription": "用相机拍照。" },
                "ko": {}
            } }
        }))
        .unwrap();
        config.localizations = vec!["ja".into()];
        let mut meta = crate::module_meta::ModuleMeta::default();
        for (language, text) in [("ja", "カメラ。"), ("de", "Kamera."), ("zh-Hans", "相机。")]
        {
            meta.ios_strings.insert(
                language.into(),
                serde_json::json!({ "NSCameraUsageDescription": text }),
            );
        }
        let strings = super::dev_host_strings(&config, &meta).unwrap();
        let files = super::localized_files(&strings);
        assert_eq!(
            files.keys().map(String::as_str).collect::<Vec<_>>(),
            ["ja", "zh-Hans"]
        );
        // The app's own text wins over the crate's.
        assert_eq!(
            files["zh-Hans"],
            "\"NSCameraUsageDescription\" = \"用相机拍照。\";\n"
        );
        let info =
            super::with_crates_info(super::info_plist(Target::Ios), &meta, &config, &strings)
                .unwrap();
        let info = plist::Value::from_reader_xml(info.as_bytes()).unwrap();
        let languages: Vec<&str> = info.as_dictionary().unwrap()["CFBundleLocalizations"]
            .as_array()
            .unwrap()
            .iter()
            .filter_map(plist::Value::as_string)
            .collect();
        assert_eq!(languages, ["en", "ja", "zh-Hans"]);
        // An app without languages leaves the host's Info.plist as it is.
        let plain = crate::package::AppConfig::default();
        let none = crate::module_meta::ModuleMeta::default();
        assert_eq!(
            super::with_crates_info(
                super::info_plist(Target::Ios),
                &none,
                &plain,
                &Default::default()
            )
            .unwrap(),
            super::info_plist(Target::Ios)
        );
    }
}