nsh-core 0.7.1

Platform-independent core: shadow tree, styles, layout and mount instructions.
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
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
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
//! Desktop windows and menus for Rust components, using the platform's
//! native chrome (TS: `nsh/desktop`'s `Window`, `currentWindow()` and
//! `Menu`).
//!
//! Every window of the app renders from its one engine. [`window`] declares
//! a window of the app's own in the tree, controlled as a dialog is: open
//! while [`Window::open`] holds, its content in the same reactive graph as
//! the rest of the app. [`current_window`] is the window the calling code
//! renders in (the app root's ref outside a window): a [`WindowRef`]
//! whose [`WindowRef::set`] changes its attributes and whose requests
//! ([`WindowRef::set_mode`], [`WindowRef::minimize`], ...) the
//! platform carries out, reporting what happened in
//! [`WindowRef::state`]. [`quit`], [`restart`], [`launch_at_login`] and
//! [`set_launch_at_login`] are `Application`'s.
//!
//! A custom title bar hides the system's (`TitleBarOptions` with
//! [`TitleBarStyle::Hidden`](crate::desktop::TitleBarStyle::Hidden)),
//! marks its background with [`Interactive::window_drag`], and reserves the
//! left and right edges reported by [`title_bar`]. The application menu
//! ([`set_application_menu`]) and context menus ([`popup_menu`]) are
//! [`MenuItem`]s whose [`MenuItem::on_select`] runs when the user chooses
//! the item, by a click or its shortcut.
//!
//! An app that opens its window as the user left it saves
//! [`WindowState::placement`] when it changes and gives it back to
//! [`WindowRef::set_placement`], which fits it on the displays there
//! are now; a [`window`] with [`Window::restore_bounds`] has the core do
//! both.
//!
//! ```ignore
//! let window = current_window(); // in a window's content
//! if let Some(saved) = Storage::get_item("window")
//!     .and_then(|json| serde_json::from_str::<WindowPlacement>(&json).ok())
//! {
//!     window.set_placement(saved);
//! }
//! effect(move || {
//!     if let Some(state) = window.state() {
//!         let json = serde_json::to_string(&state.placement).unwrap();
//!         let _ = Storage::set_item("window", json);
//!     }
//! });
//! ```
//!
//! On platforms without desktop windows these have no effect.
//!
//! [`Interactive::window_drag`]: super::Interactive::window_drag

use std::{cell::RefCell, fmt, rc::Rc};

use super::{
    AnyElement, Element, ElementRef, ImageSrc, IntoElement, IntoElements, IntoReactive, Owner,
    ParentElement, Signal, cleanup, menus::MenuHandler, task::Answer,
};
use crate::{
    Command, EventKind, EventPayload,
    desktop::{
        self, CloseReason, DesktopCommand, Display, DisplayId, LaunchAtLoginError, MenuAction,
        MenuBarMode, MenuRole, Shortcut, TrayTitlePlacement, TrayTitleRun, WindowAttributes,
        WindowCloseCause, WindowEvent, WindowFrame, WindowKind, WindowMode, WindowOptions,
        WindowPlacement, WindowPosition, WindowRequest, WindowState,
    },
    geometry::{Bounds, Edges, Point, Points, Size},
    keymap::When,
    platform::Os,
};

/// The current window's ([`current_window`]) custom title bar: its height
/// (`top`) and the widths its native window controls occupy (`left` and
/// `right`), in points (TS: `titleBar()`). Reading subscribes to changes,
/// including entering and leaving full screen. These are zero with a
/// system title bar and on platforms without desktop windows.
pub fn title_bar() -> Edges<Points> {
    if !super::os().is_desktop() || super::idiom() == crate::platform::Idiom::Terminal {
        return Edges::default();
    }
    current_window().title_bar()
}

/// When the menu bar shows on Windows and Linux where the window draws the
/// application menu as a bar above the app (the GPUI backend):
/// [`MenuBarMode::Shown`] (the default) always; [`MenuBarMode::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, and the
/// bar shows while it is open. macOS's menu bar is the system's (TS:
/// `Menu.setMenuBar`).
pub fn set_menu_bar(mode: MenuBarMode) {
    super::desktop_command(DesktopCommand::SetMenuBar(mode));
}

/// The current window's state (TS: `windowState()`):
/// [`WindowRef::state`] of [`current_window`]; `None` off the desktops,
/// where there is no window.
pub fn window_state() -> Option<WindowState> {
    if !super::os().is_desktop() || super::idiom() == crate::platform::Idiom::Terminal {
        return None;
    }
    current_window().state()
}

/// The displays (TS: `displays()`): their bounds and the parts of them
/// windows use, in screen coordinates. Reading subscribes: plugging in a
/// display, unplugging one or arranging them again changes them. Empty
/// off desktops.
pub fn displays() -> Vec<Display> {
    super::ambient::displays()
}

/// The display with `id`, of [`displays`] (reading subscribes).
pub fn display(id: DisplayId) -> Option<Display> {
    displays().into_iter().find(|d| d.id == id)
}

// --- Windows ---------------------------------------------------------------------------

/// Where a [`WindowRef`]'s commands go.
#[derive(Clone, Copy)]
enum Target {
    /// The app root (the invisible host's ref), not a user window.
    Main,
    /// A window of the app's own: the dialog root carrying the ref.
    Own(ElementRef),
}

/// A window (TS: `WindowRef`): the app root's ref ([`main_window`], the
/// invisible host, not a user window) or a window of the app's own
/// ([`window`]), as [`current_window`] gives it. Setting its attributes and
/// its requests are commands that go out with the commit; the platform may
/// decline or adjust a request, and [`Self::state`] reports what happened.
/// Commands to a closed window do nothing.
#[derive(Clone)]
pub struct WindowRef {
    id: Rc<str>,
    target: Target,
    /// The state of a window of the app's own (the app root's is the
    /// environment's).
    state: Option<Signal<Option<WindowState>>>,
    /// The hidden title bar's area of a window of the app's own (the app
    /// root's is the environment's).
    title_bar: Option<Signal<Edges<Points>>>,
    /// Closes a window of the app's own as its element does
    /// ([`WindowRef::close`]).
    close: Option<Rc<dyn Fn(WindowCloseCause)>>,
    /// The close presses of a window of the app's own: how many, and the
    /// last one's reason (the app root's are the environment's).
    close_press: Option<Signal<(u64, CloseReason)>>,
    /// What a window of the app's own was set to and asked for before its
    /// element was mounted (its content's first render): opened with it.
    early: Option<Signal<Early>>,
}

/// What a window's ref was given before its element was mounted.
#[derive(Clone, Default, PartialEq)]
struct Early {
    /// Joins the options it opens with.
    attributes: WindowAttributes,
    /// Sent after it opens, in order (`focus()`, `set_mode()`, ...).
    commands: Vec<DesktopCommand>,
    /// It closed: nothing more is kept.
    closed: bool,
}

impl fmt::Debug for WindowRef {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("WindowRef")
            .field("id", &self.id)
            .finish_non_exhaustive()
    }
}

impl PartialEq for WindowRef {
    fn eq(&self, other: &Self) -> bool {
        self.id == other.id
    }
}

/// The app root's ref, for commands about the application host: it is not a
/// user window and has no visible window in window model v2. A desktop app
/// declares its UI with [`window`]; off the desktops [`window`] shows its
/// content in the app's one surface. Its window requests (`show`, `hide`,
/// `focus`, `close`, `minimize`, `restore`, modes and bounds) do nothing: the
/// host never shows and is not a window to close; [`WindowRef::request_attention`]
/// still reaches the platform: the app's Dock icon bounces or its launcher
/// entry turns urgent (the hidden host has no taskbar button on Windows). Use
/// [`quit`] (or `Application.quit`) to end the app.
pub fn main_window() -> WindowRef {
    WindowRef {
        id: Rc::from("main"),
        target: Target::Main,
        state: None,
        title_bar: None,
        close: None,
        close_press: None,
        early: None,
    }
}

/// The window the calling code renders in (TS: `currentWindow()`): the
/// nearest [`window`] around it. Never the focused window. Call it while
/// rendering and keep the handle: listeners and tasks find no window
/// around them. Outside every window it is [`main_window`]: the app root's
/// ref, which a released app's plain root renders in (not a user window on
/// the desktops).
pub fn current_window() -> WindowRef {
    super::use_context::<WindowRef>().unwrap_or_else(main_window)
}

/// The ref of a window JS opened (`<Window>` of `nsh/desktop`) at node
/// `node`, under its own owner, for the Rust components rendered inside it:
/// [`current_window`] finds it as it finds a [`window`]'s, with the state
/// and title bar area `reported` gives and [`WindowRef::report`] keeps.
/// Commands go to the node; JS keeps its own handle of the window.
pub(crate) fn js_window(
    id: &str,
    node: crate::NodeId,
    executor: &Rc<super::Executor>,
    reported: (Option<WindowState>, Edges<Points>),
) -> (Owner, WindowRef) {
    Owner::detached().run(|| {
        super::create_root(|| {
            let element = ElementRef::new(executor);
            if let Some(target) = element.target() {
                target.attach(node);
            }
            let this = WindowRef {
                id: Rc::from(id),
                target: Target::Own(element),
                state: Some(super::signal(reported.0)),
                title_bar: Some(super::signal(reported.1)),
                close: None,
                close_press: None,
                early: None,
            };
            super::provide_context(this.clone());
            this
        })
    })
}

impl WindowRef {
    /// Its id: the app's (`"main"` is a conventional first-window id, with
    /// no special behavior).
    pub fn id(&self) -> &str {
        &self.id
    }

    /// Whether its id is `"main"` (a conventional first-window id; there
    /// is no privileged window).
    pub fn is_main(&self) -> bool {
        self.id.as_ref() == "main"
    }

    /// The ref on a window of the app's own's dialog root (its node is the
    /// window's root node); `None` for the app root's ref.
    pub(crate) fn dialog_root(&self) -> Option<super::ElementRef> {
        match &self.target {
            Target::Main => None,
            Target::Own(element) => Some(*element),
        }
    }

    fn command(&self, command: DesktopCommand) {
        match self.target {
            Target::Main => {
                // The host is not a user window: a request would act on the
                // hidden host, and minimize/restore/mode can present it on
                // Linux or Windows. Attributes keep the app-root defaults.
                // Attention is the app's (its Dock icon or launcher entry),
                // so it passes like the attributes do.
                if matches!(
                    command,
                    DesktopCommand::SetAttributes(_)
                        | DesktopCommand::Request(WindowRequest::RequestAttention { .. })
                ) {
                    super::ambient::desktop_command(command);
                }
            }
            // Not mounted yet (`open_window`, or set while it first
            // renders): the attributes join the options it opens with, and
            // the other commands follow its opening, in order.
            Target::Own(element) => match self.early {
                Some(early) if element.node().is_none() => {
                    if !early.is_live() {
                        return;
                    }
                    early.update(|e| match command {
                        _ if e.closed => {}
                        DesktopCommand::SetAttributes(attributes) => {
                            e.attributes.merge(&attributes)
                        }
                        command => e.commands.push(command),
                    });
                }
                _ => element.send(Command::Desktop(Box::new(command))),
            },
        }
    }

    /// What the platform reports of it (reading subscribes): its mode,
    /// bounds, display, whether it is focused, minimized or visible.
    /// `None` off desktops, while it is not open, and once it closed.
    pub fn state(&self) -> Option<WindowState> {
        match self.state {
            None => super::ambient::window_state(),
            Some(state) => state.try_get().flatten(),
        }
    }

    /// Changes the attributes `attributes` sets (TS: `set(partial)`); the
    /// others keep their values. One command per window and commit carries
    /// what changed. An attribute the app's capabilities do not grant is
    /// left as it is, with a warning.
    pub fn set(&self, attributes: WindowAttributes) {
        if attributes.is_empty() {
            return;
        }
        self.command(DesktopCommand::SetAttributes(Box::new(attributes)));
    }

    /// Shows it, restoring it when minimized. The app root's ref never
    /// shows: the host is invisible in window model v2.
    pub fn show(&self) {
        if matches!(self.target, Target::Main) {
            return;
        }
        self.command(DesktopCommand::Request(WindowRequest::Show));
    }

    /// Hides it.
    pub fn hide(&self) {
        self.command(DesktopCommand::Request(WindowRequest::Hide));
    }

    /// Shows it, brings it to the front of its level and focuses it. The app
    /// root's ref never shows or takes focus.
    pub fn focus(&self) {
        if matches!(self.target, Target::Main) {
            return;
        }
        self.command(DesktopCommand::Request(WindowRequest::Focus));
    }

    /// Closes it, whatever `close_on_press` says. A [`window`] reports it
    /// to [`Window::on_open_change`] with [`WindowCloseCause::Close`], so
    /// the app's `open` state follows. Only this window closes; the app's
    /// last-window policy decides whether the app ends (an embedding host
    /// decides).
    pub fn close(&self) {
        match &self.close {
            Some(close) => close(WindowCloseCause::Close),
            None => self.command(DesktopCommand::Request(WindowRequest::Close)),
        }
    }

    /// What the platform reported of a window JS opened
    /// ([`js_window`]): its state and title bar area follow.
    pub(crate) fn report(&self, event: &WindowEvent) {
        match event {
            WindowEvent::State(next) => {
                if let Some(state) = self.state {
                    state.try_set(Some(**next));
                }
            }
            WindowEvent::TitleBar(area) => {
                if let Some(title_bar) = self.title_bar {
                    title_bar.try_set(*area);
                }
            }
            _ => {}
        }
    }

    /// Its hidden title bar's area (reading subscribes): the bar's height
    /// (`top`) and the widths its window controls take (`left`, `right`),
    /// as [`title_bar`] gives the main window's.
    pub fn title_bar(&self) -> Edges<Points> {
        match self.title_bar {
            Some(area) => area.try_get().unwrap_or_default(),
            None => super::title_bar(),
        }
    }

    /// Minimizes it.
    pub fn minimize(&self) {
        self.command(DesktopCommand::Request(WindowRequest::Minimize));
    }

    /// Brings it back from being minimized, in the mode it had.
    pub fn restore(&self) {
        self.command(DesktopCommand::Request(WindowRequest::Restore));
    }

    /// Puts it in `mode`; doing it again changes nothing.
    pub fn set_mode(&self, mode: WindowMode) {
        self.command(DesktopCommand::Request(WindowRequest::SetMode(mode)));
    }

    /// Moves and sizes it in points, in screen coordinates; fields left out
    /// keep their values. Widths and heights take positive finite numbers,
    /// `x` and `y` finite ones: other values keep the field's value.
    pub fn set_bounds(&self, frame: WindowFrame) {
        self.command(DesktopCommand::Request(WindowRequest::SetBounds(
            WindowFrame {
                x: frame.x.filter(|v| v.is_finite()),
                y: frame.y.filter(|v| v.is_finite()),
                width: frame.width.filter(|v| v.is_finite() && v.0 > 0.0),
                height: frame.height.filter(|v| v.is_finite() && v.0 > 0.0),
                animated: frame.animated,
            },
        )));
    }

    /// Restores a placement saved earlier ([`WindowState::placement`]):
    /// restored to its bounds, then maximized or in full screen when its
    /// mode says so. The bounds are first fitted on the displays there are
    /// now: unchanged when at least 100 × 20 points of the window's top 40
    /// points are on a display's visible bounds, where the user can take
    /// it by its title bar; otherwise centered on the primary display's
    /// visible bounds, no larger than them.
    pub fn set_placement(&self, placement: WindowPlacement) {
        self.command(DesktopCommand::Request(WindowRequest::SetPlacement(
            placement,
        )));
    }

    /// Centers it on `display` (its own with `None`).
    pub fn center(&self, display: Option<DisplayId>) {
        self.command(DesktopCommand::Request(WindowRequest::Center { display }));
    }

    /// Asks for the user's attention: the Dock's icon bounces, the taskbar
    /// button flashes; `critical` until the user activates the app.
    pub fn request_attention(&self, critical: bool) {
        self.command(DesktopCommand::Request(WindowRequest::RequestAttention {
            critical,
        }));
    }

    /// Runs `f` with what changed whenever `changed` finds a change between
    /// two states, under the current owner.
    fn on_change<T: 'static>(
        &self,
        changed: impl Fn(Option<&WindowState>, &WindowState) -> Option<T> + 'static,
        f: impl Fn(T) + 'static,
    ) {
        let this = self.clone();
        let last = super::stored(None::<WindowState>);
        super::effect(move || {
            let Some(next) = this.state() else { return };
            let previous = last.replace(Some(next));
            if let Some(change) = changed(previous.as_ref(), &next) {
                super::untracked(|| f(change));
            }
        });
    }

    /// Runs `f` with the reason each time the user asks to close it (its
    /// close button, a shortcut, a menu, the taskbar, the system), under
    /// the current owner (TS: `on("closePress", …)`). With
    /// `close_on_press: false` it stays open: save or ask, then
    /// [`Self::close`].
    pub fn on_close_press(&self, f: impl Fn(CloseReason) + 'static) {
        let signal = self
            .close_press
            .unwrap_or_else(super::ambient::main_close_press_signal);
        let seen = super::stored(signal.with_untracked(|(count, _)| *count));
        super::effect(move || {
            let (count, reason) = signal.get();
            if seen.replace(count) != count {
                super::untracked(|| f(reason));
            }
        });
    }

    /// Runs `f` with `focused` when it gains or loses the focus.
    pub fn on_focus_change(&self, f: impl Fn(bool) + 'static) {
        self.on_change(
            |old, new| (old.is_some_and(|o| o.focused != new.focused)).then_some(new.focused),
            f,
        );
    }

    /// Runs `f` with its mode and whether it is minimized when either
    /// changes.
    pub fn on_mode_change(&self, f: impl Fn(WindowMode, bool) + 'static) {
        self.on_change(
            |old, new| {
                old.is_some_and(|o| o.mode != new.mode || o.minimized != new.minimized)
                    .then_some((new.mode, new.minimized))
            },
            move |(mode, minimized)| f(mode, minimized),
        );
    }

    /// Runs `f` with its bounds once a move or a resize settles.
    pub fn on_bounds_change(&self, f: impl Fn(Bounds<Points>) + 'static) {
        self.on_change(
            |old, new| (old.is_some_and(|o| o.bounds != new.bounds)).then_some(new.bounds),
            f,
        );
    }

    /// Runs `f` with the display it moved to.
    pub fn on_display_change(&self, f: impl Fn(DisplayId) + 'static) {
        self.on_change(
            |old, new| {
                (old.is_some_and(|o| o.display != new.display))
                    .then_some(new.display)
                    .flatten()
            },
            f,
        );
    }
}

/// Why a [`window`] closed ([`Window::on_open_change`]).
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Default)]
pub struct OpenChange {
    /// Whether it is open now (always `false`: the app opens windows).
    pub open: bool,
    /// What closed it.
    pub reason: WindowCloseCause,
}

type OpenChangeFn = Rc<dyn Fn(&OpenChange)>;
type ClosePressFn = Rc<dyn Fn(CloseReason)>;
type BindFn = Rc<dyn Fn(&mut WindowAttributes)>;
type ContentFn = Rc<dyn Fn() -> Vec<AnyElement>>;

/// A window of the app's own in the tree (TS: `<Window>`), made by
/// [`window`]: open while [`Self::open`] holds and the user has not closed
/// it, its content made each time it opens.
pub struct Window {
    options: WindowOptions,
    bound: Vec<BindFn>,
    reactive: Vec<super::Reactive<WindowAttributes>>,
    open: Option<super::Reactive<bool>>,
    content: Option<ContentFn>,
    on_open_change: Option<OpenChangeFn>,
    on_close_press: Option<ClosePressFn>,
    /// Its ref, made before it opens ([`open_window`]).
    opened: Option<WindowRef>,
}

/// A window of the app's own (TS: `<Window>`): a window the platform shows
/// its content in, rendered from the app's one engine, so it shares the
/// app's signals, context and theme. Give it an [`Window::id`] (one window
/// per id), its [`Window::kind`] and its content; it opens while
/// [`Window::open`] holds (always, without it) and closes when it leaves
/// the tree.
///
/// ```ignore
/// window()
///     .id("inspector")
///     .kind(WindowKind::Panel)
///     .title("Inspector")
///     .default_size(size(px(320.), px(560.)))
///     .open(inspector)
///     .on_open_change(move |e| inspector.set(e.open))
///     .content(inspector_panel)
/// ```
///
/// Off the desktops it shows its content in the app's one surface.
pub fn window() -> Window {
    Window {
        options: WindowOptions::default(),
        bound: Vec::new(),
        reactive: Vec::new(),
        open: None,
        content: None,
        on_open_change: None,
        on_close_press: None,
        opened: None,
    }
}

impl Window {
    /// The app's id for it: one window per id, and the key of its kept
    /// placement ([`Self::restore_bounds`]).
    pub fn id(mut self, id: impl Into<String>) -> Self {
        self.options.id = id.into();
        self
    }

    /// What it is for: its attributes' defaults.
    pub fn kind(mut self, kind: WindowKind) -> Self {
        self.options.kind = kind;
        self
    }

    /// The id of the window that owns it (`"main"` is a conventional id).
    pub fn parent(mut self, id: impl Into<String>) -> Self {
        self.options.parent = Some(id.into());
        self
    }

    /// Its parent takes no input while it is open (dialogs).
    pub fn modal(mut self, modal: bool) -> Self {
        self.options.modal = modal;
        self
    }

    /// Its content size when it opens.
    pub fn default_size(mut self, size: Size<Points>) -> Self {
        self.options.default_size = Some(size);
        self
    }

    /// Where it opens.
    pub fn default_position(mut self, position: WindowPosition) -> Self {
        self.options.default_position = Some(position);
        self
    }

    /// The display it opens on.
    pub fn display(mut self, display: DisplayId) -> Self {
        self.options.display = Some(display);
        self
    }

    /// The mode it opens in.
    pub fn default_mode(mut self, mode: WindowMode) -> Self {
        self.options.default_mode = Some(mode);
        self
    }

    /// Opens where the user left it: the core keeps its placement under its
    /// id and fits it on the displays there are when it opens again.
    pub fn restore_bounds(mut self, restore: bool) -> Self {
        self.options.restore_bounds = restore;
        self
    }

    /// Its title (a value, a signal or a closure).
    pub fn title(mut self, title: impl IntoReactive<String>) -> Self {
        match title.into_reactive() {
            super::Reactive::Static(title) => self.options.attributes.title = Some(title),
            reactive => {
                let reactive = Rc::new(reactive);
                self.bound.push(Rc::new(move |a: &mut WindowAttributes| {
                    a.title = Some(reactive.get());
                }));
            }
        }
        self
    }

    /// Any of its attributes (a value, a signal or a closure): the fields
    /// set, over its kind's defaults; given again, the later fields win.
    pub fn attributes(mut self, attributes: impl IntoReactive<WindowAttributes>) -> Self {
        match attributes.into_reactive() {
            super::Reactive::Static(a) => self.options.attributes.merge(&a),
            reactive => self.reactive.push(reactive),
        }
        self
    }

    /// Whether it is open (a value, a signal or a closure).
    pub fn open(mut self, open: impl IntoReactive<bool>) -> Self {
        self.open = Some(open.into_reactive());
        self
    }

    /// Runs `f` when the window closed while `open` held (the user's close
    /// press with `close_on_press`, Escape, losing the focus, its parent
    /// closing, [`WindowRef::close`]): the app sets its `open` state
    /// from it.
    pub fn on_open_change(mut self, f: impl Fn(&OpenChange) + 'static) -> Self {
        self.on_open_change = Some(Rc::new(f));
        self
    }

    /// Runs `f` when the user asks to close it (its close button, the
    /// close key), whether or not `close_on_press` lets it close.
    pub fn on_close_press(mut self, f: impl Fn(CloseReason) + 'static) -> Self {
        self.on_close_press = Some(Rc::new(f));
        self
    }

    /// What it shows, made each time it opens; [`current_window`] in it is
    /// this window.
    pub fn content<E: IntoElements>(mut self, content: impl Fn() -> E + 'static) -> Self {
        self.content = Some(Rc::new(move || content().into_elements()));
        self
    }
}

impl IntoElement for Window {
    fn into_element(self) -> AnyElement {
        // Off the desktops, and in a terminal, the app has one surface: the
        // window's content is the app's screen while `open`, as TSX's
        // `<Window>` does.
        if !super::os().is_desktop() || super::idiom() == crate::platform::Idiom::Terminal {
            let open = self.open.unwrap_or(super::Reactive::Static(true));
            return match self.content {
                Some(content) => super::when(move || open.get(), move || content()).into_element(),
                None => super::when(false, Vec::<AnyElement>::new).into_element(),
            };
        }
        let Window {
            options,
            bound,
            reactive,
            open,
            content,
            on_open_change,
            on_close_press,
            opened,
        } = self;
        let open = open.unwrap_or(super::Reactive::Static(true));
        // Closed by the user while `open` stayed true: hidden until the app
        // follows (then `open` opens it again).
        let closed = super::signal(false);
        let open = Rc::new(open);
        let is_open = {
            let open = open.clone();
            move || {
                let open = open.get();
                if !open {
                    super::untracked(|| closed.set(false));
                }
                open && !closed.get()
            }
        };
        let options = Rc::new(options);
        let bound = Rc::new(bound);
        let reactive = Rc::new(reactive);
        super::when(is_open, move || {
            let (element, state, title_bar, close_press, early) = match &opened {
                Some(WindowRef {
                    target: Target::Own(element),
                    state: Some(state),
                    title_bar: Some(title_bar),
                    close_press: Some(close_press),
                    early: Some(early),
                    ..
                }) => (*element, *state, *title_bar, *close_press, *early),
                _ => (
                    super::element_ref(),
                    super::signal(None::<WindowState>),
                    super::signal(Edges::<Points>::default()),
                    super::signal((0u64, CloseReason::default())),
                    super::signal(Early::default()),
                ),
            };
            // Closed, its ref reaches nothing: what it is asked for then is
            // not kept for a later opening.
            super::cleanup(move || {
                early.try_set(Early {
                    closed: true,
                    ..Early::default()
                });
            });
            let close: Rc<dyn Fn(WindowCloseCause)> = {
                let on_open_change = on_open_change.clone();
                Rc::new(move |cause: WindowCloseCause| {
                    closed.set(true);
                    if let Some(f) = &on_open_change {
                        f(&OpenChange {
                            open: false,
                            reason: cause,
                        });
                    }
                })
            };
            let this = WindowRef {
                id: Rc::from(options.id.as_str()),
                target: Target::Own(element),
                state: Some(state),
                title_bar: Some(title_bar),
                close: Some(close.clone()),
                close_press: Some(close_press),
                early: Some(early),
            };
            LiveWindows::add(this.clone());
            super::provide_context(this);
            let mut modal = super::modal().element_ref(&element);
            {
                let node = modal.node();
                let options = options.clone();
                let bound = bound.clone();
                let reactive = reactive.clone();
                let resolve = move || {
                    let mut o = (*options).clone();
                    for b in bound.iter() {
                        b(&mut o.attributes);
                    }
                    for r in reactive.iter() {
                        o.attributes.merge(&r.get());
                    }
                    let commands = early.with(|e| {
                        o.attributes.merge(&e.attributes);
                        e.commands.clone()
                    });
                    (o, commands)
                };
                let apply = |attrs: &mut super::Attrs, (o, commands): (WindowOptions, _)| {
                    let rare = attrs.rare_mut();
                    rare.window = Some(Box::new(o));
                    rare.window_commands = commands;
                };
                // Bound even with static options: what its content sets
                // while it first renders (`early`) joins them.
                node.bind_attr(super::Reactive::Bound(Rc::new(resolve)), apply);
                let on_close_press = on_close_press.clone();
                let close_on_dismiss = close.clone();
                node.handlers.push((
                    EventKind::Window,
                    super::Listener::from(move |payload: &EventPayload| {
                        let EventPayload::Window(event) = payload else {
                            return;
                        };
                        match event.as_ref() {
                            WindowEvent::State(next) => {
                                state.try_set(Some(**next));
                            }
                            WindowEvent::TitleBar(area) => {
                                title_bar.try_set(*area);
                            }
                            WindowEvent::ClosePress { reason } => {
                                if let Some(f) = &on_close_press {
                                    f(*reason);
                                }
                                if close_press.is_live() {
                                    close_press.update(|(count, last)| {
                                        *count += 1;
                                        *last = *reason;
                                    });
                                }
                            }
                            WindowEvent::Closed { cause } => close(*cause),
                            // The root's ([`Core`](crate::Core) hears them).
                            WindowEvent::QuitRequest | WindowEvent::Reopen => {}
                        }
                    }),
                ));
                // The platforms that close windows themselves report it so.
                node.handlers.push((
                    EventKind::Dismiss,
                    super::Listener::from(move |_: &EventPayload| {
                        close_on_dismiss(WindowCloseCause::ClosePress)
                    }),
                ));
            }
            if let Some(content) = &content {
                modal = modal.children(content());
            }
            modal
        })
        .into_element()
    }
}

/// Every window of the app's own that is open now (the app root's ref
/// aside), however it opened: a [`window`] in the tree or [`open_window`].
#[derive(Default, Clone)]
struct LiveWindows(Vec<WindowRef>);

impl LiveWindows {
    /// Lists `window` until the owner rendering it is disposed (it closes).
    fn add(window: WindowRef) {
        let live = super::global::<Self>();
        let id = window.id.clone();
        live.update(|l| l.0.push(window));
        super::cleanup(move || {
            if live.is_live() {
                live.update(|l| l.0.retain(|w| !Rc::ptr_eq(&w.id, &id)));
            }
        });
    }

    /// The open window with `id`.
    fn get(id: &str) -> Option<WindowRef> {
        super::global::<Self>().with_untracked(|l| l.0.iter().find(|w| &*w.id == id).cloned())
    }

    fn count() -> usize {
        super::global::<Self>().with_untracked(|l| l.0.len())
    }
}

/// What the app may open, as the core checks it ([`crate::Core::set_access`]).
#[derive(Default, Clone)]
pub(crate) struct WindowAccess(pub(crate) Option<std::sync::Arc<crate::access::Access>>);

/// The windows [`open_window`] opened, in the order they opened.
#[derive(Default, Clone)]
struct OpenedWindows(Vec<Opened>);

/// A window [`open_window`] opened: its id, its [`Window`] until it
/// renders, and the owner of its ref's signals (disposed once it closes).
#[derive(Clone)]
struct Opened {
    id: Rc<str>,
    window: Rc<RefCell<Option<Window>>>,
    owner: Owner,
}

impl PartialEq for Opened {
    fn eq(&self, other: &Self) -> bool {
        Rc::ptr_eq(&self.window, &other.window)
    }
}

/// Opens `window` (made with [`window`]) from anywhere: an event handler, a
/// menu item, a task (TS: `Window.open`; GPUI: `cx.open_window`). It
/// renders from the app's one engine, so it shares the app's signals,
/// context and theme, and stays open until it closes (the user, its
/// [`WindowRef::close`]). One window per id: with the id of a window that
/// is open, however it opened, it focuses that window and returns its ref
/// (a document window per document: `.id(format!("doc:{id}"))`). Without
/// an id it gets a new one.
///
/// `None`, with a warning in the log, where TS `Window.open` throws: off
/// the desktops (`ERR_FEATURE_UNAVAILABLE_ON_PLATFORM`) and when the app's
/// capabilities do not grant the window (`ERR_ACCESS_DENIED`).
/// [`Window::open`] does not apply here: the window opens now.
///
/// ```ignore
/// let Some(inspector) = open_window(
///     window()
///         .id("inspector")
///         .kind(WindowKind::Panel)
///         .title("Inspector")
///         .content(inspector_panel),
/// ) else {
///     return;
/// };
/// inspector.set_mode(WindowMode::Normal);
/// ```
pub fn open_window(mut window: Window) -> Option<WindowRef> {
    if !super::os().is_desktop() || super::idiom() == crate::platform::Idiom::Terminal {
        log::warn!("open_window: windows of the app's own open on the desktops only");
        return None;
    }
    if window.open.is_some() {
        log::warn!("open_window: `Window::open` is ignored, the window opens now");
    }
    let opened = super::global::<OpenedWindows>();
    if window.options.id.is_empty() {
        thread_local!(static NEXT: std::cell::Cell<u64> = const { std::cell::Cell::new(0) });
        let n = NEXT.with(|n| {
            n.set(n.get() + 1);
            n.get()
        });
        window.options.id = format!("window-{n}");
    }
    let id: Rc<str> = Rc::from(window.options.id.as_str());
    // Open already: rendered (any way in), or opened and not yet rendered.
    let open = LiveWindows::get(&id).or_else(|| {
        opened.with_untracked(|o| {
            o.0.iter()
                .find(|w| w.id == id)
                .and_then(|w| w.window.borrow().as_ref().and_then(|w| w.opened.clone()))
        })
    });
    if let Some(open) = open {
        open.focus();
        return Some(open);
    }
    let access = super::global::<WindowAccess>().get_untracked().0;
    if let Some(access) = access {
        let pending = opened.with_untracked(|o| {
            o.0.iter()
                .filter(|w| LiveWindows::get(&w.id).is_none())
                .count()
        });
        if let Err(message) = access.check_window(
            window.options.kind,
            &window.options.attributes,
            LiveWindows::count() + pending,
        ) {
            log::warn!("open_window: {message}: the window does not open");
            return None;
        }
    }
    let user = window.on_open_change.take();
    let on_open_change: OpenChangeFn = {
        let id = id.clone();
        Rc::new(move |change: &OpenChange| {
            opened.update(|o| o.0.retain(|w| w.id != id));
            if let Some(f) = &user {
                f(change);
            }
        })
    };
    let (owner, this) = Owner::detached().run(|| {
        super::create_root(|| WindowRef {
            id: id.clone(),
            target: Target::Own(super::element_ref()),
            state: Some(super::signal(None)),
            title_bar: Some(super::signal(Edges::default())),
            close: Some({
                let on_open_change = on_open_change.clone();
                Rc::new(move |reason| {
                    on_open_change(&OpenChange {
                        open: false,
                        reason,
                    })
                })
            }),
            close_press: Some(super::signal((0, CloseReason::default()))),
            early: Some(super::signal(Early::default())),
        })
    });
    window.on_open_change = Some(on_open_change);
    window.open = None;
    window.opened = Some(this.clone());
    opened.update(|o| {
        o.0.push(Opened {
            id,
            window: Rc::new(RefCell::new(Some(window))),
            owner,
        })
    });
    Some(this)
}

/// The windows [`open_window`] opened: the core renders it beside the
/// app's root.
pub(crate) struct OpenedWindowsHost;

impl super::Component for OpenedWindowsHost {
    type Props = ();
    type Event = super::NoEvent;

    fn view(_: (), _: super::Scope<super::NoEvent>) -> impl IntoElement {
        super::each(
            move || super::global::<OpenedWindows>().get().0,
            |w: &Opened| w.id.clone(),
            |w, _| {
                let w = w.get_untracked();
                // The ref's signals go once the window closes (its row goes).
                let owner = w.owner;
                super::cleanup(move || owner.dispose());
                let window = w.window.borrow().as_ref().map(|w| Window {
                    options: w.options.clone(),
                    bound: w.bound.clone(),
                    reactive: Vec::new(),
                    open: None,
                    content: w.content.clone(),
                    on_open_change: w.on_open_change.clone(),
                    on_close_press: w.on_close_press.clone(),
                    opened: w.opened.clone(),
                });
                let reactive = w
                    .window
                    .borrow_mut()
                    .as_mut()
                    .map(|w| std::mem::take(&mut w.reactive))
                    .unwrap_or_default();
                window.map(|mut window| {
                    window.reactive = reactive;
                    window
                })
            },
        )
    }
}

/// Quits the app, as the application menu's Quit item
/// ([`MenuRole::Quit`]) and the platform's quit key do (TS: `Application.quit`):
/// the engine stops as when the last window closes (an embedding app's close
/// handling runs as it does for the Quit item), then the app's run ends, also
/// when closing the window alone would leave it running (a window kept hidden
/// for the Dock, a tray icon). It is not a per-window close path: windows'
/// `on_open_change` may not run. It quits
/// whether or not the app listens to quit requests ([`on_quit_request`]):
/// that is how an app that asks first quits once it is ready; a GPUI host
/// that owns the window is asked first and quits when it is ready. For a
/// menu item or a button of
/// the app's own that quits, and for restarting after an update. A view
/// embedded in another app leaves the app's lifecycle to that app. On the
/// web, called while a quit request listener runs, it lets the page leave
/// without a question ([`on_quit_request`]); the app ends as the page goes.
/// On platforms without desktop windows this has no effect.
pub fn quit() {
    super::desktop_command(DesktopCommand::Quit);
}

/// Sets when closing the app's last window quits it (TS:
/// `Application.setQuitMode`; nsh.json's `application.quitMode`):
/// [`desktop::QuitMode::Platform`] (the default) follows the platform
/// (macOS stays in the Dock; Windows and Linux quit),
/// [`desktop::QuitMode::LastWindowClosed`] quits on every platform, and
/// [`desktop::QuitMode::Explicit`] leaves the app running so it can open
/// another window, show a tray menu or call [`quit`]. The app root stays
/// alive while no window is open. A view embedded in another app leaves
/// the app's lifecycle to that app; on platforms without desktop windows
/// this has no effect.
pub fn set_quit_mode(mode: desktop::QuitMode) {
    super::desktop_command(DesktopCommand::SetQuitMode(mode));
}

/// Sets which additional requests go to [`on_quit_request`] on standalone
/// macOS apps (TS: `Application.setQuitRequestOptions`). Both options
/// default to false; each call replaces them. Without a listener the app
/// still quits as before. Changing the options cancels a pending request.
/// Replacing the app cancels its request and restores the default options.
/// Other platforms and embedded views ignore it.
pub fn set_quit_request_options(options: desktop::QuitRequestOptions) {
    super::desktop_command(DesktopCommand::SetQuitRequestOptions(options));
}

/// Cancels the pending quit request on standalone macOS apps (TS:
/// `Application.cancelQuitRequest`). For an intercepted system request,
/// this cancels logout or shutdown too. Call [`quit`] to approve instead.
/// Repeated requests share the pending confirmation until answered.
/// System requests left unanswered are cancelled after 110 seconds, before
/// AppKit's logout timeout. Removing the last listener also cancels them.
/// Nothing happens without a pending request or on other platforms.
pub fn cancel_quit_request() {
    super::desktop_command(DesktopCommand::CancelQuitRequest);
}

pub use super::quit::QUIT_TIMEOUT;

/// Runs `f` as the app quits, for its cleanup (TS: `Application.on("quit",
/// …)`), as GPUI's `App::on_app_quit`: saving what it keeps, closing a
/// connection. It cannot keep the app running; an app that asks first
/// listens to quit requests ([`on_quit_request`]). It runs when the app
/// stops: its Quit
/// item and [`quit`], its last window closing, the system ending it
/// (logging out), a host app removing its view, on the web the page going
/// (its tab closed, a reload, another site), once, however the user left
/// it; a page the browser keeps to come back to keeps the app running.
/// The engine waits for the
/// futures it returns [`QUIT_TIMEOUT`] at most, together, and while it
/// waits the platform does: keep it short. Removed with the current owner.
///
/// ```ignore
/// on_app_quit(move || {
///     let draft = draft.get_untracked();
///     async move { save_draft(draft).await }
/// });
/// ```
pub fn on_app_quit<F>(f: impl FnMut() -> F + 'static)
where
    F: std::future::Future<Output = ()> + 'static,
{
    let owner = Owner::current();
    let f = RefCell::new(f);
    let listener: super::quit::QuitListener = Rc::new(move || {
        let future = owner.run(|| (f.borrow_mut())());
        super::ambient::owned(owner, future)
    });
    let subscription = add_quit_listener(listener);
    cleanup(move || drop(subscription));
}

/// Runs `f` each time the user asks to quit the app (TS:
/// `Application.on("quitRequest", …)`), as AppKit's
/// `applicationShouldTerminate:`: while one is registered, the app's Quit
/// item and the platform's quit key (Command-Q, Ctrl+Q) no longer quit, and
/// the app decides: it asks the user, saves, or waits for work to finish,
/// then calls [`quit`]. Without one they quit as before. The system ending
/// the app (logging out, shutting down) runs [`on_app_quit`] without asking
/// by default. On macOS, [`set_quit_request_options`] can include system
/// requests and main-window closes; answer with [`quit`] or
/// [`cancel_quit_request`]. Standalone apps on macOS, Windows and Linux;
/// a view embedded in another app leaves the app's lifecycle to that app. On the web, the
/// user leaving the page (closing its tab, reloading) is the request: `f`
/// runs then, and a [`quit`] it calls at once lets the page go without a
/// question; otherwise the browser asks the user whether to leave. The
/// [`on_app_quit`] listeners run once the page is gone. Removed with the
/// current owner.
///
/// ```ignore
/// on_quit_request(move || {
///     if busy.get_untracked() {
///         confirm_quit.set(true);
///     } else {
///         quit();
///     }
/// });
/// ```
pub fn on_quit_request(f: impl Fn() + 'static) {
    let owner = Owner::current();
    let listener: super::quit::QuitRequestListener = Rc::new(move || owner.run(&f));
    let subscription = add_quit_request_listener(listener);
    cleanup(move || drop(subscription));
}

/// Runs `f` each time the OS asks the app to show itself (TS:
/// `Application.on("reopen", …)`): a macOS Dock or Finder reopen, or a
/// later launch on Windows and Linux. The app opens or focuses the window
/// it wants; nothing shows implicitly. Removed with the current owner.
pub fn on_reopen(f: impl Fn() + 'static) {
    let owner = Owner::current();
    let listener: super::quit::ReopenListener = Rc::new(move || owner.run(&f));
    let subscription = add_reopen_listener(listener);
    cleanup(move || drop(subscription));
}

/// Runs `f` when the app's last window closes (TS:
/// `Application.on("lastWindowClosed", …)`), after the window's own close
/// path. The quit mode is decided at that close; a JS listener runs in a
/// later commit, after the decision, so an app that stays alive with no
/// windows sets `quitMode: "explicit"` before the last close.
/// Removed with the current owner.
pub fn on_last_window_closed(f: impl Fn() + 'static) {
    let owner = Owner::current();
    let listener: super::quit::LastWindowClosedListener = Rc::new(move || owner.run(&f));
    let subscription = add_last_window_closed_listener(listener);
    cleanup(move || drop(subscription));
}

/// Adds `listener` to what hears the user ask to quit, until the
/// subscription drops (`Application.on("quitRequest")` keeps one per JS
/// listener).
pub(crate) fn add_quit_request_listener(
    listener: super::quit::QuitRequestListener,
) -> super::quit::Subscription<super::quit::QuitRequestListener> {
    let requests = &super::ambient::executor().quit_requests;
    let id = requests.borrow_mut().add(listener);
    super::quit::Subscription::new(requests, id)
}

/// Adds `listener` to what hears the OS ask the app to show itself
/// (`Application.on("reopen")` keeps one per JS listener).
pub(crate) fn add_reopen_listener(
    listener: super::quit::ReopenListener,
) -> super::quit::Subscription<super::quit::ReopenListener> {
    let reopens = &super::ambient::executor().reopens;
    let id = reopens.borrow_mut().add(listener);
    super::quit::Subscription::new(reopens, id)
}

/// Adds `listener` to what hears the app's last window close
/// (`Application.on("lastWindowClosed")` keeps one per JS listener).
pub(crate) fn add_last_window_closed_listener(
    listener: super::quit::LastWindowClosedListener,
) -> super::quit::Subscription<super::quit::LastWindowClosedListener> {
    let closed = &super::ambient::executor().last_window_closed;
    let id = closed.borrow_mut().add(listener);
    super::quit::Subscription::new(closed, id)
}

/// Adds `listener` to what runs as the app quits, until the subscription
/// drops (`Application.on("quit")` keeps one while the VM lasts).
pub(crate) fn add_quit_listener(
    listener: super::quit::QuitListener,
) -> super::quit::QuitSubscription {
    let quit = &super::ambient::executor().quit;
    let id = quit.borrow_mut().add(listener);
    super::quit::QuitSubscription::new(quit, id)
}

/// Restarts the app (TS: `Application.restart`): it quits as [`quit`]
/// does, and once this process has exited the platform starts the same
/// program again with the arguments it was started with. For a setting
/// that takes effect at the next start (the app's language, say): the app
/// asks the user first, then calls this. Standalone apps on macOS, Windows
/// and Linux; a view embedded in another app leaves the app's lifecycle to
/// that app, and on other platforms this has no effect.
pub fn restart() {
    super::desktop_command(DesktopCommand::Restart);
}

/// Whether the system opens the app when the user logs in (TS:
/// `Application.launchAtLogin()`), as the system has it now: ask again when
/// the app shows it, as the user may change it in the system's settings.
/// To await in a task. `false` wherever the app cannot launch at login (a
/// view embedded in another app, `nsh run`, iOS, Android, the web), while
/// macOS waits for the user to approve it in Login Items, and when the
/// system cannot be read (logged). On macOS it is the app's bundle id's, the
/// same for every copy of the app; on Windows and Linux it is this copy's.
pub fn launch_at_login() -> impl Future<Output = bool> + 'static {
    let answer = super::login_item_request(None);
    async move {
        answer.await.unwrap_or_else(|error| {
            log::warn!("{error}");
            false
        })
    }
}

/// Turns launching at login on or off (TS:
/// `Application.setLaunchAtLogin(enabled)`): turning on what is on and off
/// what is off succeed. Call it when the user turns the app's own setting on
/// or off, never on the app's own (at every start, say): what the user
/// chose in the system's settings stands. The changes run in the order the
/// app makes them. On macOS the system may then wait for the user's
/// approval, and [`launch_at_login`] reads `false` until they give it.
/// Fails with [`LaunchAtLoginError::Unavailable`] where the app cannot
/// launch at login and with the system's error when it refuses.
pub fn set_launch_at_login(
    enabled: bool,
) -> impl Future<Output = Result<(), LaunchAtLoginError>> + 'static {
    // Asked now, so the changes keep the order of the calls.
    let answer = super::login_item_request(Some(enabled));
    async move { answer.await.map(|_| ()) }
}

/// An item of a menu (TS: `nsh/desktop`'s `MenuItem`): an item that runs
/// its [`on_select`](Self::on_select) or carries out its
/// [`role`](Self::role), a separator, or a submenu.
///
/// ```ignore
/// MenuItem::submenu("File", [
///     MenuItem::new("New").shortcut("mod+n").on_select(new_document),
///     MenuItem::separator(),
///     MenuItem::role(MenuRole::Quit),
/// ])
/// ```
#[derive(Clone)]
pub struct MenuItem {
    kind: Kind,
    label: String,
    role: Option<MenuRole>,
    /// The keystroke as written, checked.
    shortcut: Option<Rc<str>>,
    when: When,
    enabled: bool,
    checked: Option<bool>,
    icon: Option<ImageSrc>,
    /// An SF Symbol name for iOS header menus; see [`Self::symbol`].
    symbol: Option<String>,
    /// Destructive on iOS; ignored on the desktops; see [`Self::destructive`].
    destructive: bool,
    /// Inline section when this is a submenu; see [`Self::inline`].
    inline: bool,
    on_select: Option<MenuHandler>,
}

#[derive(Clone)]
enum Kind {
    Action,
    Separator,
    Submenu(Vec<MenuItem>),
}

impl MenuItem {
    fn of(kind: Kind, label: String) -> Self {
        MenuItem {
            kind,
            label,
            role: None,
            shortcut: None,
            when: When::Always,
            enabled: true,
            checked: None,
            icon: None,
            symbol: None,
            destructive: false,
            inline: false,
            on_select: None,
        }
    }

    /// An item showing `label`.
    pub fn new(label: impl Into<String>) -> Self {
        Self::of(Kind::Action, label.into())
    }

    /// A standard item the platform carries out, with the platform's label
    /// and shortcut unless it is given its own.
    pub fn role(role: MenuRole) -> Self {
        MenuItem {
            role: Some(role),
            ..Self::of(Kind::Action, String::new())
        }
    }

    /// A line between groups of items.
    pub fn separator() -> Self {
        Self::of(Kind::Separator, String::new())
    }

    /// An item opening a menu of `items` (the top-level menus of the
    /// application menu: `File`, `Edit`, ...).
    pub fn submenu(label: impl Into<String>, items: impl IntoIterator<Item = MenuItem>) -> Self {
        Self::of(Kind::Submenu(items.into_iter().collect()), label.into())
    }

    /// What it shows, in place of its role's label.
    pub fn label(mut self, label: impl Into<String>) -> Self {
        self.label = label.into();
        self
    }

    /// Its keyboard shortcut, as `nsh/keymap` writes keystrokes: `"mod+n"`,
    /// `"mod+shift+z"`, `"alt+f4"`, `"f11"` (`mod` is Command on macOS and
    /// Control elsewhere; [`Shortcut::parse`]).
    ///
    /// # Panics
    ///
    /// On a keystroke that is not one, as TS's menus throw.
    #[track_caller]
    pub fn shortcut(mut self, keystroke: &str) -> Self {
        if let Err(e) = Shortcut::parse(keystroke, false) {
            panic!("MenuItem::shortcut: {e}");
        }
        self.shortcut = Some(keystroke.into());
        self
    }

    /// When its shortcut chooses it while a text field has the keyboard
    /// focus ([`When::Always`] by default), on the GPUI backend.
    pub fn shortcut_when(mut self, when: When) -> Self {
        self.when = when;
        self
    }

    /// It cannot be chosen (or opened): shown dimmed.
    pub fn disabled(mut self, disabled: bool) -> Self {
        self.enabled = !disabled;
        self
    }

    /// A check mark: makes it a checkable item, checked or not.
    pub fn checked(mut self, checked: bool) -> Self {
        self.checked = Some(checked);
        self
    }

    /// The image beside its label, or beside a submenu's (the top-level
    /// menus of a menu bar show their titles alone): a URL or an
    /// [`asset!`](crate::asset)'s image, as [`image`](crate::element::image)
    /// takes, fitted in the menu's icon size for the screen. An SVG takes
    /// the color of the menu's text; a bitmap keeps its colors. It loads
    /// off the main thread and shows once it has (one that fails to load
    /// leaves the item without an icon, with a warning). GTK's menus show
    /// no icons beside labels, and a terminal shows no images. For an SF
    /// Symbol name for iOS header menus, use [`Self::symbol`] instead.
    pub fn icon(mut self, src: impl Into<ImageSrc>) -> Self {
        self.icon = Some(src.into());
        self
    }

    /// An SF Symbol name beside its label in iOS header menus; ignored
    /// elsewhere (including macOS). Takes the place of [`Self::icon`] when
    /// both are set.
    pub fn symbol(mut self, name: impl Into<String>) -> Self {
        self.symbol = Some(name.into());
        self
    }

    /// Marks the action destructive: iOS draws it red; the desktops ignore
    /// it.
    pub fn destructive(mut self, destructive: bool) -> Self {
        self.destructive = destructive;
        self
    }

    /// An inline section when this is a submenu ([`Self::submenu`]): on
    /// iOS, `UIMenuOptions.displayInline` with the label as the section
    /// title; on the desktops, its items between separators, its label
    /// not shown.
    pub fn inline(mut self, inline: bool) -> Self {
        self.inline = inline;
        self
    }

    /// Runs `f` when it is chosen, by a click or its shortcut, under the
    /// owner that showed the menu.
    pub fn on_select(mut self, f: impl Fn() + 'static) -> Self {
        self.on_select = Some(Rc::new(f));
        self
    }
}

impl fmt::Debug for MenuItem {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match &self.kind {
            Kind::Separator => f.write_str("Separator"),
            Kind::Submenu(items) => f
                .debug_struct("Submenu")
                .field("label", &self.label)
                .field("items", items)
                .finish_non_exhaustive(),
            Kind::Action => f
                .debug_struct("MenuItem")
                .field("label", &self.label)
                .field("role", &self.role)
                .field("shortcut", &self.shortcut)
                .finish_non_exhaustive(),
        }
    }
}

/// Makes the platform's items of `items`, keeping their handlers (run
/// under `owner`) in `handlers` with the ids it gives them.
pub(crate) fn decode_for_header(
    items: Vec<MenuItem>,
    mac: bool,
    owner: &Owner,
    handlers: &mut Vec<(u32, MenuHandler)>,
) -> Vec<desktop::MenuItem> {
    decode(items, mac, owner, handlers)
}

/// Makes the platform's items of `items`, keeping their handlers (run
/// under `owner`) in `handlers` with the ids it gives them.
fn decode(
    items: Vec<MenuItem>,
    mac: bool,
    owner: &Owner,
    handlers: &mut Vec<(u32, MenuHandler)>,
) -> Vec<desktop::MenuItem> {
    let menus = super::view_menus();
    items
        .into_iter()
        .map(|item| match item.kind {
            Kind::Separator => desktop::MenuItem::Separator,
            Kind::Submenu(items) => desktop::MenuItem::Submenu {
                label: item.label,
                enabled: item.enabled,
                items: decode(items, mac, owner, handlers),
                icon: item.icon.as_ref().and_then(ImageSrc::menu_icon),
                symbol: item.symbol,
                inline: item.inline,
            },
            Kind::Action => {
                let id = match item.on_select {
                    Some(f) => {
                        let id = menus.borrow_mut().next_id();
                        let owner = *owner;
                        handlers.push((id, Rc::new(move || owner.run(&*f))));
                        id
                    }
                    None => 0,
                };
                let shortcut = match item.shortcut {
                    // Checked when it was given.
                    Some(text) => Shortcut::parse(&text, mac).ok(),
                    None => item.role.and_then(|r| r.shortcut(mac)),
                };
                desktop::MenuItem::Action(MenuAction {
                    id,
                    label: item.label,
                    shortcut,
                    enabled: item.enabled,
                    checked: item.checked,
                    role: item.role,
                    when: item.when,
                    icon: item.icon.as_ref().and_then(ImageSrc::menu_icon),
                    symbol: item.symbol,
                    destructive: item.destructive,
                })
            }
        })
        .collect()
}

/// Decodes the items of a selectable view's selection menu
/// ([`super::Element::selection_menu`]), keeping their handlers under a
/// generation that a cleanup drops when the binding is replaced or the
/// owner goes. Shown on every OS, not the desktops alone.
pub(crate) fn register_selection_menu(items: Vec<MenuItem>) -> Vec<desktop::MenuItem> {
    let menus = super::view_menus();
    let owner = Owner::current();
    let mut handlers = Vec::new();
    let items = decode(items, super::os() == Os::MacOs, &owner, &mut handlers);
    let generation = menus.borrow_mut().push_header(handlers);
    let weak = Rc::downgrade(&menus);
    cleanup(move || {
        if let Some(menus) = weak.upgrade() {
            menus.borrow_mut().take_header(generation);
        }
    });
    items
}

/// Whether the app runs on a desktop OS, where menus show (as TS's).
fn desktop_os() -> bool {
    super::os().is_desktop()
}

/// Sets the application menu, a submenu per top-level item (`File`,
/// `Edit`, ...), or with `None` restores the platform's default (TS:
/// `Menu.setApplicationMenu`). On macOS it is the menu bar, whose first
/// menu is the app menu (titled with the app's name); on Windows and Linux
/// the window's menu bar, not shown while the title bar is hidden (its
/// shortcuts still work: a title bar of the app's own shows its menus with
/// [`popup_menu`]). Call it again to change it; in an [`effect`] it follows
/// the signals it reads. The items' handlers run while the current owner
/// lives: the menu stays after it, inert, until it is set again.
///
/// [`effect`]: super::effect
pub fn set_application_menu(items: impl Into<Option<Vec<MenuItem>>>) {
    if !desktop_os() {
        return;
    }
    let menus = super::view_menus();
    let Some(items) = items.into() else {
        let mut m = menus.borrow_mut();
        m.app_generation += 1;
        let old = std::mem::take(&mut m.app);
        drop(m);
        drop(old);
        super::desktop_command(DesktopCommand::SetMenu(None));
        return;
    };
    let owner = Owner::current();
    let mut handlers = Vec::new();
    let items = desktop::MenuItem::with_inline_expanded(&decode(
        items,
        super::os() == Os::MacOs,
        &owner,
        &mut handlers,
    ));
    let generation = {
        let mut m = menus.borrow_mut();
        m.app_generation += 1;
        let old = std::mem::replace(&mut m.app, handlers);
        let generation = m.app_generation;
        drop(m);
        drop(old);
        generation
    };
    let weak = Rc::downgrade(&menus);
    cleanup(move || {
        if let Some(menus) = weak.upgrade() {
            let mut m = menus.borrow_mut();
            if m.app_generation == generation {
                let old = std::mem::take(&mut m.app);
                drop(m);
                drop(old);
            }
        }
    });
    super::desktop_command(DesktopCommand::SetMenu(Some(items.into())));
}

/// Shows a context menu of `items` at the pointer (TS: `Menu.popup`). The
/// chosen item's [`MenuItem::on_select`] runs under the current owner. The
/// answer comes once the menu closes, chosen or dismissed (at once off
/// desktops), so a button that opened it can look pressed until then; it
/// need not be awaited.
pub fn popup_menu(items: Vec<MenuItem>) -> Answer<()> {
    popup(items, None)
}

/// As [`popup_menu`], with the menu's top left corner at `at` (the
/// window's coordinates, in points: an
/// [`on_context_menu`](super::Interactive::on_context_menu)'s
/// `page_position`; TS: `Menu.popup(items, at)`).
pub fn popup_menu_at(items: Vec<MenuItem>, at: Point<Points>) -> Answer<()> {
    popup(items, Some(at))
}

fn popup(items: Vec<MenuItem>, at: Option<Point<Points>>) -> Answer<()> {
    let (answer, slot) = Answer::new();
    if !desktop_os() {
        slot.borrow_mut().deliver(());
        return answer;
    }
    let menus = super::view_menus();
    let owner = Owner::current();
    let mut handlers = Vec::new();
    let items = desktop::MenuItem::with_inline_expanded(&decode(
        items,
        super::os() == Os::MacOs,
        &owner,
        &mut handlers,
    ));
    let generation = {
        let mut m = menus.borrow_mut();
        // One context menu at a time: one shown before is closed by now.
        m.settle_popup();
        m.closed = Some(slot);
        m.popup_generation += 1;
        let old = std::mem::replace(&mut m.popup, handlers);
        let generation = m.popup_generation;
        drop(m);
        drop(old);
        generation
    };
    let weak = Rc::downgrade(&menus);
    cleanup(move || {
        if let Some(menus) = weak.upgrade() {
            let mut m = menus.borrow_mut();
            if m.popup_generation == generation {
                let old = std::mem::take(&mut m.popup);
                drop(m);
                drop(old);
            }
        }
    });
    super::desktop_command(DesktopCommand::PopupMenu {
        items: items.into(),
        at,
    });
    answer
}

/// A click on the tray's icon ([`Tray::on_click`]; TS: `TrayClickEvent`).
#[derive(Debug, Clone, Copy, PartialEq)]
#[non_exhaustive]
pub struct TrayClickEvent {
    /// The icon's frame on the screen, in points, in the coordinates of
    /// [`displays`] and [`WindowRef::set_bounds`]: where to place a window
    /// beside it. `None` when the system does not say where the icon is
    /// (always on Linux).
    pub bounds: Option<Bounds<Points>>,
}

/// The app's icon in the system tray, for [`set_tray`] (TS:
/// `TrayOptions`): the notification area on Windows, the menu bar's right
/// side on macOS, a StatusNotifierItem on Linux.
#[derive(Default)]
#[must_use = "a tray shows nothing until given to set_tray"]
pub struct Tray {
    icon: Option<ImageSrc>,
    tooltip: String,
    title: Vec<TrayTitleRun>,
    title_placement: TrayTitlePlacement,
    menu: Vec<MenuItem>,
    on_click: Option<TrayClick>,
}

type TrayClick = Rc<dyn Fn(&TrayClickEvent)>;

/// A tray icon to give to [`set_tray`]: the app's icon, its name as the
/// tooltip, no menu.
pub fn tray() -> Tray {
    Tray::default()
}

impl Tray {
    /// The icon (as [`Image`](super::Image)'s source). 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.
    pub fn icon(mut self, src: impl Into<ImageSrc>) -> Self {
        self.icon = Some(src.into());
        self
    }

    /// Shown when the pointer rests on the icon (the app's name without
    /// it).
    pub fn tooltip(mut self, tooltip: impl Into<String>) -> Self {
        self.tooltip = tooltip.into();
        self
    }

    /// Text beside the icon, in runs each of its own color: what the app
    /// keeps in sight (a price, a count). macOS's menu bar shows it in its
    /// font; Linux's panels that show AppIndicator labels show its text
    /// right of the icon; Windows' notification area shows the icon alone.
    ///
    /// ```ignore
    /// tray().title([
    ///     TrayTitleRun::new("AAPL 228.00 "),
    ///     TrayTitleRun::new("+1.33%").color(rgb(0xd92d20)),
    /// ])
    /// ```
    pub fn title(mut self, runs: impl IntoIterator<Item = TrayTitleRun>) -> Self {
        self.title = runs.into_iter().collect();
        self
    }

    /// Which side of the icon the title shows on (macOS; Linux's panels
    /// draw it right of the icon).
    pub fn title_placement(mut self, placement: TrayTitlePlacement) -> Self {
        self.title_placement = placement;
        self
    }

    /// Its menu, opened by a secondary click (and a primary one without
    /// [`Tray::on_click`]).
    pub fn menu(mut self, items: impl IntoIterator<Item = MenuItem>) -> Self {
        self.menu = items.into_iter().collect();
        self
    }

    /// Runs when the icon is clicked with the primary button (on Windows,
    /// Enter or Space on the icon too), with where the icon is.
    pub fn on_click(mut self, f: impl Fn(&TrayClickEvent) + 'static) -> Self {
        self.on_click = Some(Rc::new(f));
        self
    }
}

impl fmt::Debug for Tray {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Tray")
            .field("tooltip", &self.tooltip)
            .field("title", &self.title)
            .field("title_placement", &self.title_placement)
            .field("menu", &self.menu)
            .field("on_click", &self.on_click.is_some())
            .finish_non_exhaustive()
    }
}

/// Shows the app's icon in the system tray, or changes it; `None` removes
/// it (TS: `Tray.set`). One per app, shared with TS: the last set wins.
/// Call it again to change it; in an [`effect`] it follows the signals it
/// reads. Its menu's and click's handlers run while the current owner
/// lives: the icon stays after it, inert, until it is set again. Nothing
/// happens off desktops.
///
/// ```ignore
/// set_tray(
///     tray()
///         .icon("tray.svg")
///         .tooltip("Player")
///         .menu([MenuItem::new("Quit").on_select(quit)])
///         .on_click(|e| show_popover(e.bounds)),
/// );
/// ```
///
/// [`effect`]: super::effect
pub fn set_tray(tray: impl Into<Option<Tray>>) {
    if !desktop_os() {
        return;
    }
    let menus = super::view_menus();
    let Some(tray) = tray.into() else {
        let mut m = menus.borrow_mut();
        m.tray_generation += 1;
        let old = (std::mem::take(&mut m.tray), m.tray_click.take());
        drop(m);
        drop(old);
        super::desktop_command(DesktopCommand::SetTray(None));
        return;
    };
    let owner = Owner::current();
    let mut handlers = Vec::new();
    let items = decode(tray.menu, super::os() == Os::MacOs, &owner, &mut handlers);
    let click = tray.on_click.map(|f| {
        let id = menus.borrow_mut().next_id();
        let handler: super::menus::TrayClickHandler =
            Rc::new(move |bounds| owner.run(|| f(&TrayClickEvent { bounds })));
        (id, handler)
    });
    let command = desktop::Tray {
        icon: tray.icon.as_ref().and_then(ImageSrc::menu_icon),
        tooltip: tray.tooltip,
        title: tray.title,
        title_placement: tray.title_placement,
        menu: items.into(),
        click: click.as_ref().map_or(0, |(id, _)| *id),
    };
    let generation = {
        let mut m = menus.borrow_mut();
        m.tray_generation += 1;
        let old = (
            std::mem::replace(&mut m.tray, handlers),
            std::mem::replace(&mut m.tray_click, click),
        );
        let generation = m.tray_generation;
        drop(m);
        drop(old);
        generation
    };
    let weak = Rc::downgrade(&menus);
    cleanup(move || {
        if let Some(menus) = weak.upgrade() {
            let mut m = menus.borrow_mut();
            if m.tray_generation == generation {
                let old = (std::mem::take(&mut m.tray), m.tray_click.take());
                drop(m);
                drop(old);
            }
        }
    });
    super::desktop_command(DesktopCommand::SetTray(Some(command)));
}

/// Registers `keystroke` system-wide, heard whichever app has the keyboard
/// (TS: `GlobalShortcut.register`): `on_press` runs at each press, under
/// the current owner, until [`unregister_global_shortcut`] or the owner
/// goes. The keystroke is written as a [`MenuItem::shortcut`]'s
/// (`"mod+shift+k"`). The answer is whether the system took it: `false`
/// when another app holds it, when the keystroke is not one (a warning
/// names why in the log, and the component goes on — keystrokes often
/// come from user settings, where a typo must not end it), or off
/// desktops; it need not be awaited. Registering a keystroke again
/// replaces its function.
///
/// 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>`).
pub fn register_global_shortcut(keystroke: &str, on_press: impl Fn() + 'static) -> Answer<bool> {
    let shortcut = match Shortcut::parse(keystroke, super::os() == Os::MacOs) {
        Ok(shortcut) => shortcut,
        Err(e) => {
            log::warn!("register_global_shortcut: {e}");
            let (answer, slot) = Answer::new();
            slot.borrow_mut().deliver(false);
            return answer;
        }
    };
    let (answer, slot) = Answer::new();
    if !desktop_os() {
        slot.borrow_mut().deliver(false);
        return answer;
    }
    unregister_where(|g| g.shortcut == shortcut);
    let menus = super::view_menus();
    let owner = Owner::current();
    let id = {
        let mut m = menus.borrow_mut();
        let id = m.next_id();
        m.globals.push(super::menus::Global {
            id,
            shortcut,
            on_press: Rc::new(move || owner.run(&on_press)),
            registered: Some(slot),
        });
        id
    };
    cleanup(move || unregister_where(|g| g.id == id));
    super::desktop_command(DesktopCommand::RegisterGlobalShortcut { id, shortcut });
    answer
}

/// Gives back `keystroke`, registered with [`register_global_shortcut`]
/// (TS: `GlobalShortcut.unregister`). A keystroke that is not one, or not
/// registered, does nothing.
pub fn unregister_global_shortcut(keystroke: &str) {
    if let Ok(shortcut) = Shortcut::parse(keystroke, super::os() == Os::MacOs) {
        unregister_where(|g| g.shortcut == shortcut);
    }
}

/// Gives back every shortcut registered with [`register_global_shortcut`]
/// (TS: `GlobalShortcut.unregisterAll`).
pub fn unregister_all_global_shortcuts() {
    unregister_where(|_| true);
}

fn unregister_where(remove: impl Fn(&super::menus::Global) -> bool) {
    let menus = super::view_menus();
    let removed: Vec<super::menus::Global> = {
        let mut m = menus.borrow_mut();
        let (removed, kept) = std::mem::take(&mut m.globals)
            .into_iter()
            .partition(&remove);
        m.globals = kept;
        removed
    };
    for g in removed {
        if let Some(slot) = g.registered {
            slot.borrow_mut().deliver(false);
        }
        super::desktop_command(DesktopCommand::UnregisterGlobalShortcut(g.id));
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    /// A keystroke that is not one answers `false` where the call was
    /// made, instead of ending the component that took it from user
    /// settings (#2758): the answer is already there to poll.
    #[test]
    fn a_keystroke_that_is_not_one_answers_false() {
        let runtime = crate::element::Runtime::default();
        runtime.set_environment(crate::element::Environment::default());
        let _entered = runtime.enter();
        let answer = register_global_shortcut("ctrl+alt+notakey", || {});
        let waker = std::task::Waker::noop();
        let mut cx = std::task::Context::from_waker(waker);
        match std::pin::pin!(answer).poll(&mut cx) {
            std::task::Poll::Ready(taken) => assert!(!taken),
            std::task::Poll::Pending => panic!("the answer was to be delivered at once"),
        }
    }
}