nsh-js 0.6.1

QuickJS host: runtime setup, host APIs, op decoding and bytecode.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
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
//! `nsh/desktop`'s hand-written exports (with the registry's
//! `Application`): `isAvailable`, `displays()` (the environment's
//! accessor), the windows (`crate::window`) and `Menu`, `Tray` and
//! `GlobalShortcut`, whose items call the app's functions: the menus are decoded natively
//! into [`MenuItem`]s with an id per item, the functions kept by id, and
//! the platform's [`EventKind::Menu`] calls the chosen item's.

use std::{
    cell::{Cell, RefCell},
    ffi::{CStr, c_int},
    ptr,
    sync::Arc,
};

use nsh_core::{
    Command, EventKind, HeaderItem, HeaderItemContent, HeaderSystemItem, ImageSource, Op, Prop,
    ROOT_ID, ScreenProp,
    desktop::{
        DesktopCommand, MenuAction, MenuBarMode, MenuItem, MenuRole, Shortcut, Tray,
        TrayTitlePlacement, TrayTitleRun,
    },
    geometry::{Points, point},
    keymap::When,
    platform::Os,
};
use rquickjs::{Ctx, Value, qjs};

use crate::{
    dom,
    modules::{Export, Item, Ts},
    reactive::{self, arg},
};

type JsValue = qjs::JSValue;
type JsContext = qjs::JSContext;

const UNDEFINED: JsValue = qjs::JS_UNDEFINED;

/// Menu items' functions: (id, owned function).
type Functions = Vec<(u32, JsValue)>;

/// The menus' part of a context's state.
pub(crate) struct Menus {
    /// The application menu's functions (id, owned function).
    app: RefCell<Vec<(u32, JsValue)>>,
    /// The last context menu's functions.
    popup: RefCell<Vec<(u32, JsValue)>>,
    /// Trailing iOS header bar button functions, by screen node id.
    header: RefCell<std::collections::HashMap<u32, Vec<(u32, JsValue)>>>,
    /// Resolves the promise of the context menu shown (owned), once the
    /// platform reports it closed.
    closed: Cell<JsValue>,
    /// The tray's functions: its menu's and its click's.
    tray: RefCell<Vec<(u32, JsValue)>>,
    /// The id of the tray's click among them (0: none), whose function gets
    /// the click's event.
    tray_click: Cell<u32>,
    /// The global shortcuts registered.
    globals: RefCell<Vec<Global>>,
    /// The root's `onMenu` handler is set.
    listening: Cell<bool>,
    next: Cell<u32>,
}

impl Default for Menus {
    fn default() -> Self {
        Menus {
            app: RefCell::default(),
            popup: RefCell::default(),
            header: RefCell::default(),
            tray: RefCell::default(),
            tray_click: Cell::new(0),
            globals: RefCell::default(),
            closed: Cell::new(UNDEFINED),
            listening: Cell::new(false),
            next: Cell::new(0),
        }
    }
}

/// Resolves the promise of the context menu shown, if there is one.
fn resolve_closed(cx: *mut JsContext) {
    let resolve = menus(cx).closed.replace(UNDEFINED);
    if !nullish(resolve) {
        // SAFETY: an owned resolving function, called then freed.
        unsafe {
            let r = qjs::JS_Call(cx, resolve, UNDEFINED, 0, ptr::null_mut());
            qjs::JS_FreeValue(cx, r);
            qjs::JS_FreeValue(cx, resolve);
        }
    }
}

/// A global shortcut (`GlobalShortcut.register`).
struct Global {
    id: u32,
    shortcut: Shortcut,
    /// Called at each press (owned).
    on_press: JsValue,
    /// Resolves `register`'s promise once the platform answers (owned;
    /// `undefined` once it did).
    resolve: JsValue,
}

impl Global {
    /// Frees its functions, settling `register`'s promise with `false` when
    /// the platform has not answered yet.
    fn free(self, cx: *mut JsContext) {
        settle(cx, self.resolve, false);
        free(cx, self.on_press);
    }
}

/// Calls the owned resolving function `resolve` (if any) with `value`, then
/// frees it.
fn settle(cx: *mut JsContext, resolve: JsValue, value: bool) {
    if nullish(resolve) {
        return;
    }
    let mut arg = if value { qjs::JS_TRUE } else { qjs::JS_FALSE };
    // SAFETY: an owned resolving function, called then freed.
    unsafe {
        let r = qjs::JS_Call(cx, resolve, UNDEFINED, 1, &mut arg);
        qjs::JS_FreeValue(cx, r);
        qjs::JS_FreeValue(cx, resolve);
    }
}

impl Menus {
    /// Frees the values held (the state is unregistered).
    pub(crate) fn free_all(&mut self, raw: *mut JsContext) {
        for g in self.globals.get_mut().drain(..) {
            // SAFETY: owned values; no JS runs from here on.
            unsafe {
                qjs::JS_FreeValue(raw, g.on_press);
                qjs::JS_FreeValue(raw, g.resolve);
            }
        }
        // SAFETY: owned; no JS runs from here on.
        unsafe { qjs::JS_FreeValue(raw, self.closed.replace(UNDEFINED)) };
        for (_, f) in self
            .app
            .get_mut()
            .drain(..)
            .chain(self.popup.get_mut().drain(..))
            .chain(self.tray.get_mut().drain(..))
            .chain(
                self.header
                    .get_mut()
                    .drain()
                    .flat_map(|(_, handlers)| handlers),
            )
        {
            // SAFETY: owned values; no JS runs from here on.
            unsafe { qjs::JS_FreeValue(raw, f) };
        }
    }
}

fn menus<'a>(cx: *mut JsContext) -> &'a Menus {
    // SAFETY: a projection of the state's field, by shared reference.
    unsafe { &(*crate::state::state(cx)).menus }
}

fn os(cx: *mut JsContext) -> Os {
    // SAFETY: the state's renderer, by shared reference.
    unsafe { &(*crate::state::state(cx)).dom }.os()
}

fn throw(cx: *mut JsContext, message: &str) -> JsValue {
    let message = std::ffi::CString::new(message).unwrap_or_default();
    // SAFETY: throws on a live context; `%s` keeps the message literal.
    unsafe { qjs::JS_ThrowTypeError(cx, c"%s".as_ptr(), message.as_ptr()) }
}

/// `undefined` or `null`.
fn nullish(v: JsValue) -> bool {
    // SAFETY: inline tag checks.
    unsafe { qjs::JS_IsUndefined(v) || qjs::JS_IsNull(v) }
}

fn is_object(v: JsValue) -> bool {
    // SAFETY: an inline tag check.
    unsafe { qjs::JS_IsObject(v) }
}

/// Property `key` of `object` (owned).
fn get(cx: *mut JsContext, object: JsValue, key: &CStr) -> JsValue {
    // SAFETY: a read of a live object.
    unsafe { qjs::JS_GetPropertyStr(cx, object, key.as_ptr()) }
}

fn free(cx: *mut JsContext, v: JsValue) {
    // SAFETY: an owned value.
    unsafe { qjs::JS_FreeValue(cx, v) };
}

/// String property `key`, if it is set.
fn string(cx: *mut JsContext, object: JsValue, key: &CStr) -> Option<String> {
    let v = get(cx, object, key);
    let s = if nullish(v) {
        None
    } else {
        dom::string_arg(cx, v)
    };
    free(cx, v);
    s
}

/// The role named `name`, as `MenuRole`'s conversion reads it.
fn menu_role(cx: *mut JsContext, name: &str) -> Option<MenuRole> {
    let host = crate::classes::host_outside_calls(cx);
    let value = nsh_core::element::JsHost::new_string(&host, name).ok()?;
    let value = nsh_core::element::JsOwned::new(&host, value);
    let role = <MenuRole as nsh_core::element::JsValue>::from_js(value.get()).ok();
    host.clear_pending();
    role
}

/// Boolean property `key`, if it is set.
fn flag(cx: *mut JsContext, object: JsValue, key: &CStr) -> Option<bool> {
    let v = get(cx, object, key);
    let b = if nullish(v) {
        None
    } else {
        // SAFETY: `ToBoolean` of a live value.
        Some(unsafe { qjs::JS_ToBool(cx, v) } == 1)
    };
    free(cx, v);
    b
}

/// The source of item `v`'s `icon`, as `<Image>`'s `src` takes it (a `blob:`
/// URL's bytes, in this VM, go with it); `None` when it has none. Anything
/// else throws, as a menu's other wrong values do: a failed load only
/// warns, on the platform.
fn icon(cx: *mut JsContext, v: JsValue) -> Result<Option<ImageSource>, String> {
    let icon = get(cx, v, c"icon");
    if nullish(icon) {
        return Ok(None);
    }
    // SAFETY: a context reference for the decoder, which reads a live
    // value it owns (its reference given to `Value`).
    let value =
        unsafe { Value::from_raw(Ctx::from_raw(std::ptr::NonNull::new_unchecked(cx)), icon) };
    let empty = value.as_string().is_some_and(|s| {
        // A string that cannot be read is no empty one.
        s.to_string().is_ok_and(|s| s.is_empty())
    });
    let Some(mut source) = crate::protocol::image_source(value) else {
        return match empty {
            true => Ok(None),
            false => Err("an item's `icon` is a URL or an imported image".into()),
        };
    };
    if let Some((uri, data)) = crate::web::blob::resolve_image_url(cx, &source.uri) {
        source.uri = uri;
        source.data = Some(data);
    }
    Ok(Some(source.inline()))
}

/// [`dom::take_len`] with its error as the message: arrays read here are
/// read natively, where the time budget cannot interrupt, and a sparse
/// array is as long as it says.
fn take_len(cx: *mut JsContext, list: JsValue, budget: &mut u32) -> Result<u32, String> {
    dom::take_len(cx, list, budget).ok_or_else(|| {
        // SAFETY: the pending exception (owned), freed after; its message
        // says why.
        unsafe {
            let e = qjs::JS_GetException(cx);
            let message = dom::string_arg(cx, e).unwrap_or_default();
            qjs::JS_FreeValue(cx, e);
            message
        }
    })
}

/// Decodes menus, keeping their functions.
struct Decoder {
    cx: *mut JsContext,
    mac: bool,
    /// The items' functions (id, owned function).
    functions: Vec<(u32, JsValue)>,
    /// The submenus the item being read is in.
    depth: u32,
    /// The items left to read of [`dom::MAX_ARRAY_ITEMS`], submenus counted
    /// together: a menu that is its own submenu multiplies its length at
    /// each level.
    budget: u32,
}

impl Decoder {
    /// The items of array `list`.
    fn items(&mut self, list: JsValue) -> Result<Vec<MenuItem>, String> {
        let cx = self.cx;
        // SAFETY: an inline tag check.
        if !unsafe { qjs::JS_IsArray(list) } {
            return Err("a menu is an array of items".into());
        }
        // Read natively, where neither the time budget nor the interpreter's
        // stack limit applies: a menu that is its own submenu would recurse
        // until the thread's stack overflows.
        if self.depth > dom::MAX_DEPTH {
            return Err("submenus nested too deeply".into());
        }
        let len = take_len(cx, list, &mut self.budget)?;
        let mut out = Vec::with_capacity(len.min(1 << 10) as usize);
        self.depth += 1;
        for i in 0..len {
            // SAFETY: an element of a live array (owned).
            let v = unsafe { qjs::JS_GetPropertyUint32(cx, list, i) };
            let item = self.item(v);
            free(cx, v);
            match item {
                Ok(Some(item)) => out.push(item),
                Ok(None) => {}
                Err(e) => {
                    self.depth -= 1;
                    return Err(e);
                }
            }
        }
        self.depth -= 1;
        Ok(out)
    }

    /// One item; `None` for items that are nothing (`null`, `false`: a
    /// condition left them out).
    fn item(&mut self, v: JsValue) -> Result<Option<MenuItem>, String> {
        let cx = self.cx;
        if !is_object(v) {
            // SAFETY: `ToBoolean` of a live value.
            return if unsafe { qjs::JS_ToBool(cx, v) } == 0 {
                Ok(None)
            } else {
                Err("a menu item is an object".into())
            };
        }
        if string(cx, v, c"type").as_deref() == Some("separator") {
            return Ok(Some(MenuItem::Separator));
        }
        let label = string(cx, v, c"label");
        let enabled = !flag(cx, v, c"disabled").unwrap_or(false);
        let icon = icon(cx, v)?;
        let symbol = string(cx, v, c"symbol");
        let submenu = get(cx, v, c"submenu");
        if !nullish(submenu) {
            let items = self.items(submenu);
            free(cx, submenu);
            return Ok(Some(MenuItem::Submenu {
                label: label.ok_or("a submenu needs a label")?,
                enabled,
                items: items?,
                icon,
                symbol,
                inline: flag(cx, v, c"inline").unwrap_or(false),
            }));
        }
        let role = match string(cx, v, c"role") {
            Some(name) => {
                Some(menu_role(cx, &name).ok_or_else(|| format!("unknown menu role `{name}`"))?)
            }
            None => None,
        };
        if label.is_none() && role.is_none() {
            return Err("a menu item needs a label or a role".into());
        }
        let shortcut = match string(cx, v, c"shortcut") {
            Some(text) => Some(Shortcut::parse(&text, self.mac).map_err(|e| e.to_string())?),
            None => role.and_then(|r| r.shortcut(self.mac)),
        };
        let when = match string(cx, v, c"when").as_deref() {
            None | Some("always") => When::Always,
            Some("auto") => When::Auto,
            Some("notEditing") => When::NotEditing,
            Some(other) => {
                return Err(format!(
                    "when must be \"always\", \"auto\" or \"notEditing\", not {other:?}"
                ));
            }
        };
        let on_select = get(cx, v, c"onSelect");
        // SAFETY: an inline check.
        let id = if unsafe { qjs::JS_IsFunction(cx, on_select) } {
            let id = next_id(cx);
            self.functions.push((id, on_select));
            id
        } else {
            free(cx, on_select);
            0
        };
        Ok(Some(MenuItem::Action(MenuAction {
            id,
            label: label.unwrap_or_default(),
            shortcut,
            enabled,
            checked: flag(cx, v, c"checked"),
            role,
            when,
            icon,
            symbol,
            destructive: flag(cx, v, c"destructive").unwrap_or(false),
        })))
    }

    fn free(self) {
        for (_, f) in self.functions {
            free(self.cx, f);
        }
    }
}

/// Decodes `list` into items and their functions; throws on a bad menu.
fn decode(cx: *mut JsContext, list: JsValue) -> Result<(Arc<[MenuItem]>, Functions), JsValue> {
    let mut decoder = Decoder {
        cx,
        mac: os(cx) == Os::MacOs,
        functions: Vec::new(),
        depth: 0,
        budget: dom::MAX_ARRAY_ITEMS,
    };
    match decoder.items(list) {
        Ok(items) => Ok((items.into(), std::mem::take(&mut decoder.functions))),
        Err(message) => {
            decoder.free();
            Err(throw(cx, &format!("nsh/desktop: {message}")))
        }
    }
}

/// Keeps `functions` in `slot`, freeing the ones they replace.
fn keep(cx: *mut JsContext, slot: &RefCell<Vec<(u32, JsValue)>>, functions: Vec<(u32, JsValue)>) {
    let old = slot.replace(functions);
    for (_, f) in old {
        free(cx, f);
    }
}

fn send(cx: *mut JsContext, command: DesktopCommand) -> Result<(), JsValue> {
    dom::push_op(
        cx,
        Op::Command {
            id: ROOT_ID,
            command: Command::Desktop(Box::new(command)),
        },
    )
}

/// Sets the root's `onMenu` handler, once.
fn listen(cx: *mut JsContext) -> Result<(), JsValue> {
    let m = menus(cx);
    if m.listening.get() {
        return Ok(());
    }
    let on = reactive::new_function(cx, c"onMenu", on_menu, 1);
    let r = dom::set_handler(cx, ROOT_ID, EventKind::Menu, on);
    free(cx, on);
    r?;
    m.listening.set(true);
    Ok(())
}

/// `Menu.setApplicationMenu(items | null)`.
unsafe extern "C" fn set_application_menu(
    cx: *mut JsContext,
    _this: JsValue,
    argc: c_int,
    argv: *mut JsValue,
) -> JsValue {
    if !os(cx).is_desktop() {
        return UNDEFINED;
    }
    let list = arg(argc, argv, 0);
    let result = if nullish(list) {
        keep(cx, &menus(cx).app, Vec::new());
        send(cx, DesktopCommand::SetMenu(None))
    } else {
        match decode(cx, list) {
            Ok((items, functions)) => {
                keep(cx, &menus(cx).app, functions);
                let items = MenuItem::with_inline_expanded(&items).into();
                listen(cx).and_then(|()| send(cx, DesktopCommand::SetMenu(Some(items))))
            }
            Err(e) => Err(e),
        }
    };
    result.err().unwrap_or(UNDEFINED)
}

/// `Menu.popup(items, at?)`: a promise, which a wrong item rejects.
unsafe extern "C" fn popup(
    cx: *mut JsContext,
    this: JsValue,
    argc: c_int,
    argv: *mut JsValue,
) -> JsValue {
    // SAFETY: QuickJS's arguments, passed on.
    crate::web::js::rejecting(cx, unsafe { popup_menu(cx, this, argc, argv) })
}

/// [`popup`]'s work: its promise, or the exception of what it refuses.
unsafe fn popup_menu(
    cx: *mut JsContext,
    _this: JsValue,
    argc: c_int,
    argv: *mut JsValue,
) -> JsValue {
    let mut funcs = [UNDEFINED; 2];
    // SAFETY: a new promise and its resolving functions (owned).
    let promise = unsafe { qjs::JS_NewPromiseCapability(cx, funcs.as_mut_ptr()) };
    free(cx, funcs[1]);
    if !os(cx).is_desktop() {
        // Nothing shows: settled at once.
        // SAFETY: an owned resolving function, called then freed.
        unsafe {
            let r = qjs::JS_Call(cx, funcs[0], UNDEFINED, 0, ptr::null_mut());
            qjs::JS_FreeValue(cx, r);
        }
        free(cx, funcs[0]);
        return promise;
    }
    let (items, functions) = match decode(cx, arg(argc, argv, 0)) {
        Ok(decoded) => decoded,
        Err(e) => {
            free(cx, funcs[0]);
            free(cx, promise);
            return e;
        }
    };
    keep(cx, &menus(cx).popup, functions);
    let items = MenuItem::with_inline_expanded(&items).into();
    // One context menu at a time: one shown before is closed by now.
    resolve_closed(cx);
    menus(cx).closed.set(funcs[0]);
    let at = arg(argc, argv, 1);
    let at = if is_object(at) {
        let number = |key: &CStr| {
            let v = get(cx, at, key);
            let mut n = 0f64;
            // SAFETY: `ToNumber` of a live value.
            unsafe { qjs::JS_ToFloat64(cx, &mut n, v) };
            free(cx, v);
            n as f32
        };
        Some(point(Points(number(c"x")), Points(number(c"y"))))
    } else {
        None
    };
    match listen(cx).and_then(|()| send(cx, DesktopCommand::PopupMenu { items, at })) {
        Ok(()) => promise,
        Err(e) => {
            free(cx, promise);
            e
        }
    }
}

/// The root's `onMenu`: calls the chosen item's function.
unsafe extern "C" fn on_menu(
    cx: *mut JsContext,
    _this: JsValue,
    argc: c_int,
    argv: *mut JsValue,
) -> JsValue {
    let e = arg(argc, argv, 0);
    let v = get(cx, e, c"id");
    let mut id = 0f64;
    // SAFETY: `ToNumber` of a live value.
    unsafe { qjs::JS_ToFloat64(cx, &mut id, v) };
    free(cx, v);
    let id = id as u32;
    // The platform's answer to a global shortcut's registration.
    if let Some(registered) = flag(cx, e, c"registered") {
        let m = menus(cx);
        let resolve = m
            .globals
            .borrow_mut()
            .iter_mut()
            .find(|g| g.id == id)
            .map(|g| std::mem::replace(&mut g.resolve, UNDEFINED));
        if !registered {
            m.globals.borrow_mut().retain(|g| {
                if g.id == id {
                    free(cx, g.on_press);
                }
                g.id != id
            });
        }
        if let Some(resolve) = resolve {
            settle(cx, resolve, registered);
        }
        return UNDEFINED;
    }
    // A context menu closed (after its chosen item was reported).
    if flag(cx, e, c"closed") == Some(true) {
        resolve_closed(cx);
        return UNDEFINED;
    }
    let m = menus(cx);
    let f = [&m.app, &m.popup, &m.tray]
        .into_iter()
        .find_map(|slot| {
            slot.borrow()
                .iter()
                .find(|(i, _)| *i == id)
                // SAFETY: a dup for the call.
                .map(|&(_, f)| unsafe { qjs::JS_DupValue(cx, f) })
        })
        .or_else(|| {
            m.header.borrow().values().find_map(|handlers| {
                handlers.iter().find(|(i, _)| *i == id).map(|&(_, f)| {
                    // SAFETY: a dup for the call.
                    unsafe { qjs::JS_DupValue(cx, f) }
                })
            })
        })
        .or_else(|| {
            m.globals
                .borrow()
                .iter()
                .find(|g| g.id == id)
                // SAFETY: a dup for the call.
                .map(|g| unsafe { qjs::JS_DupValue(cx, g.on_press) })
        });
    let Some(f) = f else { return UNDEFINED };
    // The tray's click gets `{ bounds }`: the icon's frame, `null` where
    // the platform does not report one.
    let mut event = (id != 0 && id == m.tray_click.get()).then(|| tray_click_event(cx, e));
    let (argc, argv) = match &mut event {
        Some(event) => (1, event as *mut JsValue),
        None => (0, ptr::null_mut()),
    };
    // SAFETY: a call of an owned function, freed after it, with its owned
    // argument.
    unsafe {
        let r = qjs::JS_Call(cx, f, UNDEFINED, argc, argv);
        qjs::JS_FreeValue(cx, f);
        if let Some(event) = event {
            qjs::JS_FreeValue(cx, event);
        }
        if qjs::JS_IsException(r) {
            return r;
        }
        qjs::JS_FreeValue(cx, r);
    }
    UNDEFINED
}

/// The tray click's event (owned): `{ bounds }`, from the platform's report
/// `e`.
fn tray_click_event(cx: *mut JsContext, e: JsValue) -> JsValue {
    let bounds = get(cx, e, c"bounds");
    let bounds = if nullish(bounds) {
        free(cx, bounds);
        qjs::JS_NULL
    } else {
        bounds
    };
    // SAFETY: a new object taking the owned value.
    unsafe {
        let o = qjs::JS_NewObject(cx);
        qjs::JS_SetPropertyStr(cx, o, c"bounds".as_ptr(), bounds);
        o
    }
}

/// The next id of a menu item, a tray's click or a global shortcut.
fn next_id(cx: *mut JsContext) -> u32 {
    let m = menus(cx);
    let id = m.next.get() + 1;
    m.next.set(id);
    id
}

/// Decodes `ios.headerRightItems` for screen `screen`: assigns menu /
/// press ids, keeps their functions by screen id, and returns the
/// platform items (or an error to throw).
pub(crate) fn decode_header_right_items(
    cx: *mut JsContext,
    screen: u32,
    list: JsValue,
) -> Result<Vec<HeaderItem>, JsValue> {
    listen(cx)?;
    if nullish(list) {
        clear_header(cx, screen);
        return Ok(Vec::new());
    }
    // SAFETY: an inline tag check.
    if !unsafe { qjs::JS_IsArray(list) } {
        return Err(throw(cx, "nsh: ios.headerRightItems is an array of items"));
    }
    let mut len: i64 = 0;
    // SAFETY: the length of a live array.
    unsafe { qjs::JS_GetLength(cx, list, &mut len) };
    let mut items = Vec::with_capacity(len.max(0) as usize);
    let mut functions = Vec::new();
    for i in 0..len.max(0) {
        // SAFETY: an element of a live array (owned).
        let v = unsafe { qjs::JS_GetPropertyInt64(cx, list, i) };
        let item = decode_header_item(cx, v, &mut functions);
        free(cx, v);
        match item {
            Ok(Some(item)) => items.push(item),
            Ok(None) => {}
            Err(message) => {
                for (_, f) in functions {
                    free(cx, f);
                }
                return Err(throw(cx, &format!("nsh: ios.headerRightItems: {message}")));
            }
        }
    }
    keep_header(cx, screen, functions);
    Ok(items)
}

/// Drops the header handlers of screen `screen` (the prop was cleared).
pub(crate) fn clear_header(cx: *mut JsContext, screen: u32) {
    if let Some(old) = menus(cx).header.borrow_mut().remove(&screen) {
        for (_, f) in old {
            free(cx, f);
        }
    }
}

/// As [`clear_header`], from a finalizer (no live context).
pub(crate) fn clear_header_rt(rt: *mut qjs::JSRuntime, screen: u32) {
    let Some(state) = crate::state::of_runtime(rt) else {
        return;
    };
    // SAFETY: the state's menus, while the runtime lives.
    let menus = unsafe { &(*state).menus };
    if let Some(old) = menus.header.borrow_mut().remove(&screen) {
        for (_, f) in old {
            // SAFETY: owned values; no JS runs from a finalizer.
            unsafe { qjs::JS_FreeValueRT(rt, f) };
        }
    }
}

fn keep_header(cx: *mut JsContext, screen: u32, functions: Vec<(u32, JsValue)>) {
    let old = menus(cx)
        .header
        .borrow_mut()
        .insert(screen, functions)
        .unwrap_or_default();
    for (_, f) in old {
        free(cx, f);
    }
}

fn decode_header_item(
    cx: *mut JsContext,
    v: JsValue,
    functions: &mut Functions,
) -> Result<Option<HeaderItem>, String> {
    if !is_object(v) {
        // SAFETY: `ToBoolean` of a live value.
        return if unsafe { qjs::JS_ToBool(cx, v) } == 0 {
            Ok(None)
        } else {
            Err("a header item is an object".into())
        };
    }
    let system = string(cx, v, c"systemItem")
        .map(|name| header_system_item(&name).ok_or_else(|| format!("unknown systemItem `{name}`")))
        .transpose()?;
    let symbol = string(cx, v, c"symbol").map(Into::into);
    let label_field = string(cx, v, c"label").map(Into::into);
    let content = match (system, symbol, label_field.clone()) {
        (Some(item), None, _) => HeaderItemContent::SystemItem(item),
        (None, Some(name), _) => HeaderItemContent::Symbol(name),
        (None, None, Some(text)) => HeaderItemContent::Label(text),
        _ => {
            return Err("a header item needs exactly one of systemItem, symbol, or label".into());
        }
    };
    let label = match &content {
        HeaderItemContent::Label(_) => None,
        _ => label_field,
    };
    let menu_val = get(cx, v, c"menu");
    let menu = if nullish(menu_val) {
        free(cx, menu_val);
        None
    } else {
        let mut decoder = Decoder {
            cx,
            mac: os(cx) == Os::MacOs,
            functions: Vec::new(),
            depth: 0,
            budget: dom::MAX_ARRAY_ITEMS,
        };
        let items = decoder.items(menu_val);
        free(cx, menu_val);
        match items {
            Ok(items) => {
                functions.extend(std::mem::take(&mut decoder.functions));
                Some(items)
            }
            Err(message) => {
                decoder.free();
                return Err(message);
            }
        }
    };
    let on_press = get(cx, v, c"onPress");
    // SAFETY: an inline check.
    let press_id = if menu.is_none() && unsafe { qjs::JS_IsFunction(cx, on_press) } {
        let id = next_id(cx);
        functions.push((id, on_press));
        id
    } else {
        free(cx, on_press);
        0
    };
    Ok(Some(HeaderItem::from_parts(
        string(cx, v, c"key").map(Into::into),
        content,
        label,
        flag(cx, v, c"disabled").unwrap_or(false),
        press_id,
        menu,
    )))
}

fn header_system_item(name: &str) -> Option<HeaderSystemItem> {
    Some(match name {
        "add" => HeaderSystemItem::Add,
        "done" => HeaderSystemItem::Done,
        "close" => HeaderSystemItem::Close,
        "edit" => HeaderSystemItem::Edit,
        "compose" => HeaderSystemItem::Compose,
        "search" => HeaderSystemItem::Search,
        "share" => HeaderSystemItem::Share,
        "trash" => HeaderSystemItem::Trash,
        "save" => HeaderSystemItem::Save,
        "cancel" => HeaderSystemItem::Cancel,
        _ => return None,
    })
}

/// Sets `ios.headerRightItems` on screen `id` from JS value `value`.
pub(crate) fn set_header_right_items(
    cx: *mut JsContext,
    id: u32,
    value: JsValue,
) -> Result<(), JsValue> {
    let items = decode_header_right_items(cx, id, value)?;
    dom::push_op(
        cx,
        Op::SetProp {
            id,
            prop: Prop::Screen(ScreenProp::HeaderRightItems(items)),
        },
    )
}

/// Sets `selectionMenu` on view `id` from JS value `value`: assigns the
/// items' ids and keeps their `onSelect` functions by the view's id (in
/// the slot header items use), freed when the prop changes or the view
/// goes.
pub(crate) fn set_selection_menu(
    cx: *mut JsContext,
    id: u32,
    value: JsValue,
) -> Result<(), JsValue> {
    listen(cx)?;
    let items = if nullish(value) {
        clear_header(cx, id);
        Vec::new()
    } else {
        let mut decoder = Decoder {
            cx,
            mac: os(cx) == Os::MacOs,
            functions: Vec::new(),
            depth: 0,
            budget: dom::MAX_ARRAY_ITEMS,
        };
        match decoder.items(value) {
            Ok(items) => {
                keep_header(cx, id, std::mem::take(&mut decoder.functions));
                items
            }
            Err(message) => {
                decoder.free();
                return Err(throw(cx, &format!("nsh: selectionMenu: {message}")));
            }
        }
    };
    dom::push_op(
        cx,
        Op::SetProp {
            id,
            prop: Prop::SelectionMenu(items),
        },
    )
}

/// `Tray.set(options | null)`.
unsafe extern "C" fn set_tray(
    cx: *mut JsContext,
    _this: JsValue,
    argc: c_int,
    argv: *mut JsValue,
) -> JsValue {
    if !os(cx).is_desktop() {
        return UNDEFINED;
    }
    let options = arg(argc, argv, 0);
    if nullish(options) {
        keep(cx, &menus(cx).tray, Vec::new());
        menus(cx).tray_click.set(0);
        return send(cx, DesktopCommand::SetTray(None))
            .err()
            .unwrap_or(UNDEFINED);
    }
    if !is_object(options) {
        return throw(cx, "nsh/desktop: Tray.set takes an object or null");
    }
    let icon = match icon(cx, options) {
        Ok(icon) => icon,
        Err(_) => {
            return throw(
                cx,
                "nsh/desktop: the tray's `icon` is a URL or an imported image",
            );
        }
    };
    // Before the menu and the click: a bad title must leave the tray shown,
    // and its functions, as they are.
    let title = match tray_title(cx, options) {
        Ok(title) => title,
        Err(message) => return throw(cx, &message),
    };
    let title_placement = match string(cx, options, c"titlePlacement").as_deref() {
        None | Some("right") => TrayTitlePlacement::Right,
        Some("left") => TrayTitlePlacement::Left,
        Some(_) => {
            return throw(
                cx,
                "nsh/desktop: the tray's `titlePlacement` is \"right\" or \"left\"",
            );
        }
    };
    let menu = get(cx, options, c"menu");
    let (items, mut functions) = if nullish(menu) {
        free(cx, menu);
        (Arc::from([]), Vec::new())
    } else {
        let decoded = decode(cx, menu);
        free(cx, menu);
        match decoded {
            Ok(decoded) => decoded,
            Err(e) => return e,
        }
    };
    let on_click = get(cx, options, c"onClick");
    // SAFETY: an inline check.
    let click = if unsafe { qjs::JS_IsFunction(cx, on_click) } {
        let id = next_id(cx);
        functions.push((id, on_click));
        id
    } else {
        free(cx, on_click);
        0
    };
    keep(cx, &menus(cx).tray, functions);
    menus(cx).tray_click.set(click);
    let mut tray = Tray::default();
    tray.icon = icon;
    tray.tooltip = string(cx, options, c"tooltip").unwrap_or_default();
    tray.title = title;
    tray.title_placement = title_placement;
    tray.menu = MenuItem::with_inline_expanded(&items).into();
    tray.click = click;
    listen(cx)
        .and_then(|()| send(cx, DesktopCommand::SetTray(Some(tray))))
        .err()
        .unwrap_or(UNDEFINED)
}

/// The tray's `title`: an array of `{ text, color? }`, `text` a string and
/// `color` a CSS color.
fn tray_title(cx: *mut JsContext, options: JsValue) -> Result<Vec<TrayTitleRun>, String> {
    let list = get(cx, options, c"title");
    let runs = tray_title_runs(cx, list);
    free(cx, list);
    runs
}

fn tray_title_runs(cx: *mut JsContext, list: JsValue) -> Result<Vec<TrayTitleRun>, String> {
    const SHAPE: &str =
        "nsh/desktop: the tray's `title` is an array of `{ text, color? }`, `text` a string";
    if nullish(list) {
        return Ok(Vec::new());
    }
    // SAFETY: an inline tag check.
    if !unsafe { qjs::JS_IsArray(list) } {
        return Err(SHAPE.into());
    }
    let len = take_len(cx, list, &mut { dom::MAX_ARRAY_ITEMS })?;
    // Not sized by `len`: the app sets an array's length, holes and all; the
    // first hole ends the decoding with an error.
    let mut runs = Vec::new();
    for i in 0..len {
        // SAFETY: an element of a live array (owned).
        let v = unsafe { qjs::JS_GetPropertyUint32(cx, list, i) };
        let fields = is_object(v).then(|| (text_string(cx, v), string(cx, v, c"color")));
        free(cx, v);
        let Some((Some(text), color)) = fields else {
            return Err(SHAPE.into());
        };
        let mut run = TrayTitleRun::default();
        run.text = text;
        run.color = match color {
            None => None,
            Some(color) => Some(color.parse().map_err(|_| {
                format!("nsh/desktop: the tray's title color `{color}` is not a CSS color")
            })?),
        };
        runs.push(run);
    }
    Ok(runs)
}

/// Property `text` when it is a string (no other value is converted).
fn text_string(cx: *mut JsContext, object: JsValue) -> Option<String> {
    let v = get(cx, object, c"text");
    // SAFETY: an inline tag check.
    let s = if unsafe { qjs::JS_IsString(v) } {
        dom::string_arg(cx, v)
    } else {
        None
    };
    free(cx, v);
    s
}

/// `Tray`: an object of its functions.
fn tray(cx: *mut JsContext) -> JsValue {
    // SAFETY: a new object taking the function.
    unsafe {
        let o = qjs::JS_NewObject(cx);
        let set = reactive::new_function(cx, c"set", set_tray, 1);
        qjs::JS_SetPropertyStr(cx, o, c"set".as_ptr(), set);
        o
    }
}

/// The keystroke of argument `i`, or the exception of a wrong one.
fn global_shortcut_arg(
    cx: *mut JsContext,
    argc: c_int,
    argv: *mut JsValue,
    name: &str,
) -> Result<Shortcut, JsValue> {
    let v = arg(argc, argv, 0);
    let text = (!nullish(v)).then(|| dom::string_arg(cx, v)).flatten();
    let Some(text) = text else {
        return Err(throw(
            cx,
            &format!(
                "nsh/desktop: GlobalShortcut.{name} takes a keystroke such as \"mod+shift+k\""
            ),
        ));
    };
    Shortcut::parse(&text, os(cx) == Os::MacOs)
        .map_err(|e| throw(cx, &format!("nsh/desktop: GlobalShortcut.{name}: {e}")))
}

/// Gives back the global shortcuts `remove` picks.
fn unregister_where(cx: *mut JsContext, remove: impl Fn(&Global) -> bool) -> Result<(), JsValue> {
    let removed: Vec<Global> = {
        let mut globals = menus(cx).globals.borrow_mut();
        let (removed, kept) = std::mem::take(&mut *globals).into_iter().partition(&remove);
        *globals = kept;
        removed
    };
    let mut result = Ok(());
    for g in removed {
        result = result.and(send(cx, DesktopCommand::UnregisterGlobalShortcut(g.id)));
        g.free(cx);
    }
    result
}

/// `GlobalShortcut.register(shortcut, onPress)`: a promise of whether the
/// system took it.
unsafe extern "C" fn register_global(
    cx: *mut JsContext,
    _this: JsValue,
    argc: c_int,
    argv: *mut JsValue,
) -> JsValue {
    let shortcut = match global_shortcut_arg(cx, argc, argv, "register") {
        Ok(s) => s,
        Err(e) => return e,
    };
    let on_press = arg(argc, argv, 1);
    // SAFETY: an inline check.
    if !unsafe { qjs::JS_IsFunction(cx, on_press) } {
        return throw(
            cx,
            "nsh/desktop: GlobalShortcut.register takes a function to call at each press",
        );
    }
    let mut funcs = [UNDEFINED; 2];
    // SAFETY: a new promise and its resolving functions (owned).
    let promise = unsafe { qjs::JS_NewPromiseCapability(cx, funcs.as_mut_ptr()) };
    free(cx, funcs[1]);
    if !os(cx).is_desktop() {
        settle(cx, funcs[0], false);
        return promise;
    }
    // Registering a keystroke again replaces its function.
    if let Err(e) = unregister_where(cx, |g| g.shortcut == shortcut) {
        settle(cx, funcs[0], false);
        free(cx, promise);
        return e;
    }
    let id = next_id(cx);
    menus(cx).globals.borrow_mut().push(Global {
        id,
        shortcut,
        // SAFETY: a dup kept with the shortcut.
        on_press: unsafe { qjs::JS_DupValue(cx, on_press) },
        resolve: funcs[0],
    });
    match listen(cx)
        .and_then(|()| send(cx, DesktopCommand::RegisterGlobalShortcut { id, shortcut }))
    {
        Ok(()) => promise,
        Err(e) => {
            let _ = unregister_where(cx, |g| g.id == id);
            free(cx, promise);
            e
        }
    }
}

/// `GlobalShortcut.unregister(shortcut)`.
unsafe extern "C" fn unregister_global(
    cx: *mut JsContext,
    _this: JsValue,
    argc: c_int,
    argv: *mut JsValue,
) -> JsValue {
    let shortcut = match global_shortcut_arg(cx, argc, argv, "unregister") {
        Ok(s) => s,
        Err(e) => return e,
    };
    unregister_where(cx, |g| g.shortcut == shortcut)
        .err()
        .unwrap_or(UNDEFINED)
}

/// `GlobalShortcut.unregisterAll()`.
unsafe extern "C" fn unregister_all_globals(
    cx: *mut JsContext,
    _this: JsValue,
    _argc: c_int,
    _argv: *mut JsValue,
) -> JsValue {
    unregister_where(cx, |_| true).err().unwrap_or(UNDEFINED)
}

/// `GlobalShortcut`: an object of its functions.
fn global_shortcut(cx: *mut JsContext) -> JsValue {
    // SAFETY: a new object taking the functions.
    unsafe {
        let o = qjs::JS_NewObject(cx);
        let f = reactive::new_function(cx, c"register", register_global, 2);
        qjs::JS_SetPropertyStr(cx, o, c"register".as_ptr(), f);
        let f = reactive::new_function(cx, c"unregister", unregister_global, 1);
        qjs::JS_SetPropertyStr(cx, o, c"unregister".as_ptr(), f);
        let f = reactive::new_function(cx, c"unregisterAll", unregister_all_globals, 0);
        qjs::JS_SetPropertyStr(cx, o, c"unregisterAll".as_ptr(), f);
        o
    }
}

/// `Menu`: an object of its functions.
fn menu(cx: *mut JsContext) -> JsValue {
    // SAFETY: a new object taking the functions.
    unsafe {
        let o = qjs::JS_NewObject(cx);
        let set = reactive::new_function(cx, c"setApplicationMenu", set_application_menu, 1);
        qjs::JS_SetPropertyStr(cx, o, c"setApplicationMenu".as_ptr(), set);
        let pop = reactive::new_function(cx, c"popup", popup, 2);
        qjs::JS_SetPropertyStr(cx, o, c"popup".as_ptr(), pop);
        let bar = reactive::new_function(cx, c"setMenuBar", set_menu_bar, 1);
        qjs::JS_SetPropertyStr(cx, o, c"setMenuBar".as_ptr(), bar);
        o
    }
}

/// `Menu.setMenuBar(mode)`: when the window's menu bar shows, where the
/// app's window draws one.
unsafe extern "C" fn set_menu_bar(
    cx: *mut JsContext,
    _this: JsValue,
    argc: c_int,
    argv: *mut JsValue,
) -> JsValue {
    let mode = crate::dom::string_arg(cx, arg(argc, argv, 0));
    let host = crate::classes::host_outside_calls(cx);
    let mode = mode.and_then(|m| {
        let value = nsh_core::element::JsHost::new_string(&host, &m).ok()?;
        let value = nsh_core::element::JsOwned::new(&host, value);
        <MenuBarMode as nsh_core::element::JsValue>::from_js(value.get()).ok()
    });
    host.clear_pending();
    let Some(mode) = mode else {
        return throw(cx, "Menu.setMenuBar: the mode is \"shown\" or \"autoHide\"");
    };
    match send(cx, DesktopCommand::SetMenuBar(mode)) {
        Ok(()) => UNDEFINED,
        Err(e) => e,
    }
}

/// The hand-written exports of `nsh/desktop` (with the registry's
/// `Application`).
pub(crate) const EXPORTS: &[Item] = &[
    (
        "isAvailable",
        Export::Value(|cx| {
            if os(cx).is_desktop() {
                qjs::JS_TRUE
            } else {
                qjs::JS_FALSE
            }
        }),
        Ts::value(
            "True where this module's window and menu APIs work: macOS, Windows and\nLinux. `platform.desktop` (desktop behavior) also holds in browsers in the\ndesktop idiom, where the browser keeps its own window and menus.",
            "boolean",
        ),
    ),
    (
        "displays",
        Export::Value(crate::env::displays),
        Ts::value(
            "The displays (reactive): their bounds and the parts of them windows\nuse, in points, in screen coordinates. Plugging in a display, unplugging\none or arranging them again changes them. Empty off desktops.",
            "Accessor<Display[]>",
        ),
    ),
    (
        "Window",
        Export::Value(crate::window::window_export),
        Ts::value(
            "A window of the app's own (desktops), rendered from the app's one engine:\nit shares the app's signals, context and theme. Open while `open` is not\nfalse and the user has not closed it (`onOpenChange` tells the app); it\ncloses when it unmounts. `Window.open` is the same imperatively;\n`Window.get` finds an open window by id. Off the desktops `<Window>`\nrenders nothing and `Window.open` throws `ERR_FEATURE_UNAVAILABLE_ON_PLATFORM`.",
            "WindowComponent",
        ),
    ),
    (
        "currentWindow",
        Export::Function(crate::window::current_window, 0),
        Ts::function(
            "The window the calling component renders in: the nearest `<Window>` (or\n`Window.open`'s) around it, else the main window. Call it while\nrendering and keep the `WindowRef`: outside a component (an event\nhandler, a timer, after an `await`) it throws a `TypeError`.",
            &["(): WindowRef"],
        ),
    ),
    (
        "windows",
        Export::Function(crate::window::all_windows, 0),
        Ts::function(
            "The open windows (reactive): the main window, then the app's own in\nthe order they opened.",
            &["(): WindowRef[]"],
        ),
    ),
    (
        "focusedWindow",
        Export::Function(crate::window::focused_window, 0),
        Ts::function(
            "The window with the keyboard focus, or `null` while another app has it\n(reactive).",
            &["(): WindowRef | null"],
        ),
    ),
    (
        "windowState",
        Export::Function(crate::window::window_state, 0),
        Ts::function(
            "The current window's state (reactive): `currentWindow().state()`.\n`null` off desktops.",
            &["(): WindowState | null"],
        ),
    ),
    (
        "titleBar",
        Export::Function(crate::window::title_bar, 0),
        Ts::function(
            "The current window's hidden title bar area, in points (reactive):\n`currentWindow().titleBar()`. All 0 while the system shows its title\nbar, and off desktops.",
            &["(): TitleBarArea"],
        ),
    ),
    (
        "Menu",
        Export::Value(menu),
        Ts::value(
            "The application menu and context menus (desktops; nothing happens\nelsewhere).",
            "MenuModule",
        ),
    ),
    (
        "Tray",
        Export::Value(tray),
        Ts::value(
            "The app's icon in the system tray (desktops; nothing happens elsewhere).",
            "TrayModule",
        ),
    ),
    (
        "GlobalShortcut",
        Export::Value(global_shortcut),
        Ts::value(
            "Keystrokes the app hears whichever app has the keyboard (desktops;\n`register` resolves `false` elsewhere).",
            "GlobalShortcutModule",
        ),
    ),
];

/// `nsh/desktop`'s types (with the registry's).
pub(crate) const TYPES: &str = r#"/** `<Window>`'s props: the window's options and attributes, whether it is
 * open, its content and its events. */
export interface WindowProps extends WindowOptions {
  /** Whether it is open (controlled). Without it, open from the start
   * unless `defaultOpen` is false. */
  open?: boolean;
  /** Whether it is open at first while `open` is not given (default true). */
  defaultOpen?: boolean;
  /** It closed while `open` held: the user's close press (with
   * `closeOnPress`), Escape (`closeOnEscape`), losing the focus
   * (`closeOnBlur`), its parent closing, or the app's `WindowRef.close()`
   * (`"close"`), so a controlled `open` follows. */
  onOpenChange?: (event: { open: boolean; reason: WindowCloseCause }) => void;
  /** The user asked to close it, whether or not `closeOnPress` lets it close. */
  onClosePress?: (event: { reason: CloseReason }) => void;
  /** It gained or lost the keyboard focus. */
  onFocusChange?: (event: { focused: boolean }) => void;
  /** Its mode changed, or it was minimized or restored. */
  onModeChange?: (event: { mode: WindowMode; minimized: boolean }) => void;
  /** It moved or was resized (once the move or resize settles). */
  onBoundsChange?: (event: { bounds: Bounds }) => void;
  /** It moved to another display. */
  onDisplayChange?: (event: { display: Display }) => void;
  /** What it shows; `currentWindow()` in it is this window. */
  children?: JSX.Element;
  /** Takes the window's `WindowRef` once it opens (a variable, a signal or a
   * function); each opening gives a new one. */
  ref?: WindowRef | ((node: WindowRef) => void);
}

/** `Window`: the component, and opening and finding windows imperatively. */
export interface WindowComponent {
  (props: WindowProps): JSX.Element;
  /** Renders `component` in a window of its own and returns it, or returns
   * the open window of the same `id`. Throws `ERR_ACCESS_DENIED`
   * (`permission: "windows"`) when the app's capabilities do not grant
   * the window, and `ERR_FEATURE_UNAVAILABLE_ON_PLATFORM` off the
   * desktops. */
  open(component: () => JSX.Element, options: WindowOptions): WindowRef;
  /** The open window with `id` (`"main"`: the main window), or `null`
   * (reactive). */
  get(id: string): WindowRef | null;
}

/** A window: the main window or one of the app's own. Requests return
 * nothing: the platform may decline or adjust them, and `state()` reports
 * what happened. A closed window's requests do nothing. */
export interface WindowRef {
  /** The app's id for it (`"main"`: the main window). */
  readonly id: string;
  /** It is the main window. */
  readonly main: boolean;
  /** The window that owns it, or `null`. */
  readonly parent: WindowRef | null;
  /** What the platform reports of it (reactive); `null` off desktops,
   * before it shows and once it closed. */
  state(): WindowState | null;
  /** Its hidden title bar's area, in points (reactive). */
  titleBar(): TitleBarArea;
  /** Changes the attributes `attributes` sets; the others keep their
   * values. An attribute the app's capabilities do not grant is left as it
   * is, with a warning. */
  set(attributes: Partial<WindowAttributes>): void;
  /** Shows it, restoring it when minimized. */
  show(): void;
  /** Hides it. */
  hide(): void;
  /** Shows it, brings it to the front of its level and focuses it. */
  focus(): void;
  /** Closes it, whatever `closeOnPress` says. */
  close(): void;
  /** Minimizes it. */
  minimize(): void;
  /** Brings it back from being minimized, in the mode it had. */
  restore(): void;
  /** Puts it in `mode`; doing it again changes nothing. */
  setMode(mode: WindowMode): void;
  /** Moves and sizes it, in points, in screen coordinates; fields left out
   * keep their values. */
  setBounds(bounds: { origin?: Partial<Point>; size?: Partial<Size>; animated?: boolean }): void;
  /** Restores a placement saved from `state().placement`, fitted on the
   * displays there are now. */
  setPlacement(placement: WindowPlacement): void;
  /** Centers it on `display` (its own without it). */
  center(options?: { display?: DisplayId }): void;
  /** Asks for the user's attention (the Dock's icon bounces, the taskbar
   * button flashes); `critical` until the user activates the app. */
  requestAttention(options?: { critical?: boolean }): void;
  /** Listens to it; returns a function that stops. A listener registered
   * while a component renders goes with the component. */
  on(event: "closePress", listener: (event: { reason: CloseReason }) => void): () => void;
  on(event: "close", listener: () => void): () => void;
  on(event: "focusChange", listener: (event: { focused: boolean }) => void): () => void;
  on(event: "modeChange", listener: (event: { mode: WindowMode; minimized: boolean }) => void): () => void;
  on(event: "boundsChange", listener: (event: { bounds: Bounds }) => void): () => void;
  on(event: "displayChange", listener: (event: { display: Display }) => void): () => void;
}

/** What the platform reports of a window. Rectangles are in points, in
 * screen coordinates: from the primary display's top left corner, `y`
 * growing down. */
export interface WindowState {
  /** Its mode (minimized apart). */
  mode: WindowMode;
  /** It is minimized (in the Dock, the taskbar). */
  minimized: boolean;
  /** It is on the screen (not hidden, not minimized). */
  visible: boolean;
  /** It has the keyboard focus. */
  focused: boolean;
  /** Its outer frame now, window decorations included. */
  bounds: Bounds;
  /** Its content area now. */
  contentBounds: Bounds;
  /** Its mode and windowed bounds: what to save, and give to
   * `setPlacement`, to open it the same way next time. */
  placement: WindowPlacement;
  /** The display it is on (the one with most of it). */
  display: Display | null;
  /** Device pixels per point. */
  scaleFactor: number;
}

/** A hidden title bar's area, in points. */
export interface TitleBarArea {
  /** Its height. */
  height: number;
  /** The width the window controls take at its left end (macOS). */
  left: number;
  /** The width the window controls take at its right end (Windows, GTK). */
  right: number;
}

/** A standard menu item: the platform carries it out, and labels it when the
 * item has no label (macOS adds the app's name to `about`, `hide` and
 * `quit`). The editing roles act on the focused text field and keep its own
 * shortcuts. `about`, `hide`, `hideOthers` and `showAll` are macOS's: left
 * out elsewhere. */
export type MenuRole =
  | "about"
  | "hide"
  | "hideOthers"
  | "showAll"
  | "quit"
  | "undo"
  | "redo"
  | "cut"
  | "copy"
  | "paste"
  | "selectAll"
  | "minimize"
  | "zoom"
  | "toggleFullScreen"
  | "close";

/** An item of a menu: a separator, a submenu, or an item that calls
 * `onSelect` (or carries out its `role`). `null`, `undefined` and `false`
 * items are left out (`cond && { … }`). */
export type MenuItem =
  | { type: "separator" }
  | {
      /** What it shows (a role's own label without it). */
      label?: string;
      /** A standard item. */
      role?: MenuRole;
      /** Its shortcut: modifiers and a key joined by `+`, in any case
       * (lowercase is the recommended style; a capital letter is the same
       * key, not Shift):
       * `"mod+n"`, `"mod+shift+z"`, `"alt+f4"`, `"f11"`. `mod` (`cmdorctrl`)
       * is Command on macOS and Control elsewhere; `cmd` (`command`,
       * `meta`, `super`, `win`), `ctrl` (`control`), `alt` (`option`,
       * `opt`), `shift`. Keys: the character a key types on the US layout
       * without Shift (`n`, `1`, `,`, `/`; `"shift+/"` for `?`), `plus`
       * (`=`), `minus` (`-`), `space`, `enter`, `escape`, `tab`,
       * `backspace`, `delete`, `insert`, `up`, `down`, `left`, `right`,
       * `home`, `end`, `pageup`, `pagedown`, `f1`–`f24`: the keystrokes of
       * `nsh/keymap`. A role has its platform's by default. */
      shortcut?: string;
      /** When its shortcut chooses it while a text field has the keyboard
       * focus: `"always"` (the default), `"auto"` (unless the field uses
       * the keystroke itself: keys that type, move the caret or delete,
       * and the editing shortcuts, as `nsh/keymap`'s bindings) or
       * `"notEditing"` (never). A key the item leaves goes to the field.
       * On the GPUI backend. */
      when?: "always" | "auto" | "notEditing";
      /** It cannot be chosen: shown dimmed (default false). */
      disabled?: boolean;
      /** A check mark: set (true or false) for a checkable item. */
      checked?: boolean;
      /** Called when it is chosen (by a click or its shortcut). */
      onSelect?: () => void;
      /** The image beside its label, as `<Image>`'s `src` takes it (an
       * imported file, or a URL such as a `data:` one), so that an app's menus
       * show its own icon set on every platform. It is fitted in the menu's
       * icon size (16 points on macOS, the small icon size at the window's
       * DPI on Windows) and drawn for the screen. An SVG is a template: only
       * its shape counts, in the color of the menu's text, whatever that is
       * (dark mode, a selected or disabled item); a bitmap keeps its colors.
       * It loads off the main thread, so a menu never blocks on it and the
       * icon shows once it has loaded (a context menu on Windows gives it
       * up to 100ms before opening); one that fails to load leaves the item
       * without an icon and logs a warning. The top-level menus of a
       * menu bar show their titles alone, and so do GPUI's native menus on
       * macOS. GTK's menus show no icon beside a label: GTK draws a menu
       * item's icon only when it has no text. A terminal shows no images.
       * For an SF Symbol name in iOS header menus, use `symbol` instead. */
      icon?: ImageAsset | string;
      /** An SF Symbol name beside its label in iOS header menus; ignored
       * elsewhere (including macOS). Takes the place of `icon` when both
       * are set. */
      symbol?: string;
      /** Destructive: iOS draws it red; the desktops ignore it. */
      destructive?: boolean;
      /** Its items: makes it a submenu (`label` is required). With
       * `inline: true`, an inline section: on iOS,
       * `UIMenuOptions.displayInline` with `label` as the section title;
       * on the desktops, its items between separators, its label not
       * shown. */
      submenu?: readonly (MenuItem | null | undefined | false)[];
      /** An inline section when `submenu` is set (see `submenu`). */
      inline?: boolean;
    };

/** The application menu and context menus. */
export interface MenuModule {
  /** Sets the application menu, a submenu per top-level item (`File`,
   * `Edit`, …): macOS's menu bar, whose first menu is the app menu (titled
   * with the app's name), or the window's menu bar on Windows and Linux,
   * which is not shown while the title bar is hidden (its shortcuts still
   * work: show its menus with `Menu.popup` from a title bar of the app's
   * own). Call it again to change it (in an `effect`, it follows the
   * signals it reads); `null` restores the platform's default menu. */
  setApplicationMenu(items: readonly (MenuItem | null | undefined | false)[] | null): void;
  /** When the window's menu bar shows on Windows and Linux where the app's
   * window draws the application menu as a bar (the GPUI backend):
   * `"shown"` (the default) always; `"autoHide"` only after Alt is pressed
   * and released alone, until Alt alone hides it again. F10 and Alt with a
   * menu's initial open a menu either way. macOS's menu bar is the
   * system's. */
  setMenuBar(mode: "shown" | "autoHide"): void;
  /** Shows a context menu with its top left corner at `at` (the window's
   * coordinates, points: `Menu.popup(items, e.pagePosition)` in an
   * `onContextMenu`), else at the pointer. The promise resolves once
   * the menu closes, chosen or dismissed: a button that opened it can look
   * pressed until then. */
  popup(items: readonly (MenuItem | null | undefined | false)[], at?: Point): Promise<void>;
}

/** A click on the tray's icon. */
export interface TrayClickEvent {
  /** The icon's frame on the screen, in points, in the coordinates of
   * `displays()` and `setBounds` (from the primary display's top left,
   * `y` growing down): where to place a popup window beside it. `null`
   * when the system does not say where the icon is (always on Linux). */
  bounds: Bounds | null;
}

/** A run of the tray's `title`: text in one color. */
export interface TrayTitleRun {
  /** The text. */
  text: string;
  /** Its color, a CSS color (`#d92d20`, or a theme token's color from
   * `token`); without one, the
   * menu bar's text color, which follows its appearance. */
  color?: string;
}

/** The app's icon in the system tray. */
export interface TrayOptions {
  /** The icon, as `<Image>`'s `src` takes it (an imported file, or a URL).
   * Keep it simple and square: panels draw it at 16 to 24 pixels. An SVG is
   * a template on macOS, drawn in the menu bar's text color; elsewhere it
   * keeps its colors. Without one, the app's icon where the system has
   * one. */
  icon?: ImageAsset | string;
  /** Shown when the pointer rests on the icon (the app's name without it). */
  tooltip?: string;
  /** Text beside the icon, in runs each of its own color: what the app
   * keeps in sight, such as a price. macOS's menu bar shows it in its
   * colors; Linux's panels that show AppIndicator labels show its text;
   * Windows' notification area shows the icon alone. */
  title?: readonly TrayTitleRun[];
  /** Which side of the icon the title shows on: `"right"` (the default) or
   * `"left"`. macOS only: Linux's panels draw the title right of the icon. */
  titlePlacement?: "right" | "left";
  /** Its menu, opened by a secondary click (and a primary one without
   * `onClick`). */
  menu?: readonly (MenuItem | null | undefined | false)[];
  /** Called when the icon is clicked with the primary button (on Windows,
   * Enter or Space on the icon too), with where the icon is. */
  onClick?: (event: TrayClickEvent) => void;
}

/** The app's icon in the system tray: the notification area on Windows, the
 * menu bar's right side on macOS, a StatusNotifierItem on Linux (Plasma,
 * Waybar and most panels; GNOME needs the AppIndicator extension). */
export interface TrayModule {
  /** Shows the icon, or changes it (in an `effect`, it follows the signals
   * it reads); `null` removes it. One per app. */
  set(options: TrayOptions | null): void;
}

/** Keystrokes the app hears whichever app has the keyboard. */
export interface GlobalShortcutModule {
  /** Registers `shortcut` (a keystroke as a menu item's `shortcut`:
   * `"mod+shift+k"`) and calls `onPress` at each press. Resolves with
   * whether the system took it: `false` when another app holds it, or off
   * desktops. On Linux it goes through the desktop portal
   * (`org.freedesktop.portal.GlobalShortcuts`): the desktop may ask the user
   * to confirm it or let them pick another keystroke, and Hyprland binds it
   * in its own configuration (`bind = …, global, <app id>:<shortcut>`).
   * Registering a keystroke again replaces its function. */
  register(shortcut: string, onPress: () => void): Promise<boolean>;
  /** Gives back `shortcut`. */
  unregister(shortcut: string): void;
  /** Gives back every shortcut the app registered. */
  unregisterAll(): void;
}
"#;

#[cfg(test)]
mod tests {
    use nsh_core::{desktop::MenuRole, element::JsValue as _};

    /// `MenuRole`'s declaration (written here, with the docs of each role)
    /// names the roles the Rust type reads.
    #[test]
    fn menu_roles_are_declared() {
        let declared = super::TYPES
            .split("export type MenuRole =")
            .nth(1)
            .and_then(|rest| rest.split(';').next())
            .expect("MenuRole's declaration");
        let mut names: Vec<String> = declared
            .split('|')
            .map(|n| n.trim().trim_matches('"').to_owned())
            .filter(|n| !n.is_empty())
            .collect();
        let host = crate::Host::new().unwrap();
        let mut roles: Vec<String> = host.with_raw(|cx| {
            let js = crate::classes::host_outside_calls(cx);
            MenuRole::ALL
                .iter()
                .map(|r| r.to_js(&js).unwrap().get().as_string().unwrap())
                .collect()
        });
        names.sort();
        roles.sort();
        assert_eq!(names, roles);
    }
}