zng-app 0.22.11

Part of the zng project.
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
use std::{
    any::{Any, TypeId},
    collections::{HashMap, hash_map},
    fmt, mem,
    ops::{self, ControlFlow},
    thread::ThreadId,
};

use crate::{
    APP,
    handler::{Handler, HandlerExt},
    shortcut::CommandShortcutExt,
    widget::info::{WidgetInfo, WidgetPath},
    window::{WINDOWS_APP, WindowId},
};

use super::*;

/// <span data-del-macro-root></span> Declares new [`Command`] static items.
///
/// Command static items represent widget or service actions. Command items are also events, that is they dereference
/// to [`Event<A>`] and *override* some event methods to enable communication from the command subscribers to the command
/// notifier. Command static items also host metadata about the command.
///
/// [`Event<A>`]: crate::event::Event
///
/// # Conventions
///
/// Command events have the `_CMD` suffix, for example a command for the clipboard *copy* action is called `COPY_CMD`.
/// Public and user facing commands also set the [`CommandNameExt`] and [`CommandInfoExt`] with localized display text.
///
/// # Shortcuts
///
/// You can give commands one or more shortcuts using the [`CommandShortcutExt`], the `GestureManager` notifies commands
/// that match a pressed shortcut automatically.
///
/// # Properties
///
/// If the command implementation is not specific you can use `command_property!` to declare properties that setup command handlers
/// for the command.
///
/// # Examples
///
/// Declare two commands:
///
/// ```
/// use zng_app::event::command;
///
/// command! {
///     static FOO_CMD;
///
///     /// Command docs.
///     pub(crate) static BAR_CMD;
/// }
/// ```
///
/// You can also initialize metadata:
///
/// ```
/// use zng_app::{
///     event::{CommandInfoExt, CommandNameExt, command},
///     shortcut::{CommandShortcutExt, shortcut},
/// };
///
/// command! {
///     /// Represents the **foo** action.
///     pub static FOO_CMD {
///         name: "Foo!",
///         info: "Does the foo thing",
///         shortcut: shortcut![CTRL + 'F'],
///     };
/// }
/// ```
///
/// The initialization uses the [command extensions] pattern and runs once for each app.
///
/// Or you the special `init: |cmd| { }` to run an arbitrary closure on init:
///
/// ```
/// use zng_app::{
///     event::{CommandInfoExt, CommandNameExt, command},
///     shortcut::{CommandShortcutExt, shortcut},
/// };
///
/// command! {
///     /// Represents the **foo** action.
///     pub static FOO_CMD {
///         init: |cmd| {
///             cmd.init_name("Foo!");
///             cmd.init_info("Does the foo thing.");
///             cmd.init_shortcut(shortcut![CTRL + 'F']);
///         },
///     };
/// }
/// ```
///
/// A documentation section is also generated with a table of metadata for each inited metadata.
///
/// # Localization
///
/// If the first metadata is `l10n!:` the command init will attempt to localize the other string metadata. The `cargo zng l10n`
/// command line tool scraps commands that set this special metadata.
///
/// ```
/// # use zng_app::{event::{command, CommandNameExt, CommandInfoExt}, shortcut::{CommandShortcutExt, shortcut}};
/// command! {
///     pub static FOO_CMD {
///         l10n!: true,
///         name: "Foo!",
///         info: "Does the foo thing",
///     };
/// }
/// ```
///
/// The example above will be scrapped as:
///
/// ```ftl
/// FOO_CMD =
///     .name = Foo!
///     .info = Does the foo thing.
/// ```
///
/// The `l10n!:` meta can also be set to a localization file name:
///
/// ```
/// # use zng_app::{event::{command, CommandNameExt, CommandInfoExt}, shortcut::{CommandShortcutExt, shortcut}};
/// command! {
///     pub static FOO_CMD {
///         l10n!: "file",
///         name: "Foo!",
///     };
/// }
/// ```
///
/// The example above is scrapped to `{l10n-dir}/{lang}/file.ftl` files.
///
/// ## Limitations
///
/// Interpolation is not supported in command localization strings.
///
/// The `l10n!:` value must be a *textual* literal, that is, it can be only a string literal or a `bool` literal, and it cannot be
/// inside a macro expansion.
///
/// [`Command`]: crate::event::Command
/// [`CommandArgs`]: crate::event::CommandArgs
/// [`CommandNameExt`]: crate::event::CommandNameExt
/// [`CommandInfoExt`]: crate::event::CommandInfoExt
/// [`Event`]: crate::event::Event
/// [command extensions]: crate::event::Command#extensions
/// [`CommandShortcutExt`]: crate::shortcut::CommandShortcutExt
#[macro_export]
macro_rules! command {
    ($(
        $(#[$attr:meta])*
        $vis:vis static $COMMAND:ident $({ $($meta_ident:ident $(!)? : $meta_init:expr),* $(,)? };)? $(;)?
    )+) => {
        $(
            $crate::__command! {
                $(#[$attr])*
                $vis static $COMMAND $({
                    $($meta_ident: $meta_init,)+
                })? ;
            }
        )+
    }
}
#[doc(inline)]
pub use command;

use parking_lot::Mutex;
use zng_state_map::{OwnedStateMap, StateId, StateMapMut, StateValue};
use zng_txt::Txt;
use zng_unique_id::{static_id, unique_id_64};
use zng_var::{Var, VarHandles, VarValue, const_var, impl_from_and_into_var, var};

#[doc(hidden)]
pub use zng_app_context::app_local;

#[doc(hidden)]
pub use pastey::paste;

#[doc(hidden)]
#[macro_export]
macro_rules! __command {
    (
        $(#[$attr:meta])*
        $vis:vis static $COMMAND:ident { l10n: $l10n_arg:expr, $($meta_ident:ident : $meta_init:expr),* $(,)? };
    ) => {
        $(#[$attr])*
        ///
        /// # Metadata
        ///
        /// This command has the following default metadata:
        ///
        $(#[doc = concat!("* `", stringify!($meta_ident), "`")])+
        ///
        /// Text metadata is localized.
        $vis static $COMMAND: $crate::event::Command = {
            fn __meta_init__(cmd: $crate::event::Command) {
                let __l10n_arg = $l10n_arg;
                $crate::event::paste! {$(
                    cmd.[<init_ $meta_ident>]($meta_init);
                    $crate::event::init_meta_l10n(std::env!("CARGO_PKG_NAME"), std::env!("CARGO_PKG_VERSION"), &__l10n_arg, cmd, stringify!($meta_ident), &cmd.$meta_ident());
                )*}
            }
            $crate::event::app_local! {
                static EVENT: $crate::event::EventData = $crate::event::EventData::new::<$crate::event::CommandArgs>();
                static DATA: $crate::event::CommandData = $crate::event::CommandData::new(__meta_init__, stringify!($COMMAND));
            }
            $crate::event::Command::new(&EVENT, &DATA)
        };
    };
    (
        $(#[$attr:meta])*
        $vis:vis static $COMMAND:ident { $($meta_ident:ident : $meta_init:expr),* $(,)? };
    ) => {
        $(#[$attr])*
        ///
        /// # Metadata
        ///
        /// This command has the following default metadata:
        ///
        $(#[doc = concat!("* `", stringify!($meta_ident), "`")])+
        $vis static $COMMAND: $crate::event::Command = {
            fn __meta_init__(cmd: $crate::event::Command) {
                $crate::event::paste! {$(
                    cmd.[<init_ $meta_ident>]($meta_init);
                )*}
            }
            $crate::event::app_local! {
                static EVENT: $crate::event::EventData = $crate::event::EventData::new::<$crate::event::CommandArgs>();
                static DATA: $crate::event::CommandData = $crate::event::CommandData::new(__meta_init__, stringify!($COMMAND));
            }
            $crate::event::Command::new(&EVENT, &DATA)
        };
    };
    (
        $(#[$attr:meta])*
        $vis:vis static $COMMAND:ident;
    ) => {
        $(#[$attr])*
        $vis static $COMMAND: $crate::event::Command = {
            fn __meta_init__(_: $crate::event::Command) {
            }
            $crate::event::app_local! {
                static EVENT: $crate::event::EventData = $crate::event::EventData::new::<$crate::event::CommandArgs>();
                static DATA: $crate::event::CommandData = $crate::event::CommandData::new(__meta_init__, stringify!($COMMAND));
            }
            $crate::event::Command::new(&EVENT, &DATA)
        };
    };
}

#[doc(hidden)]
pub fn init_meta_l10n(
    pkg_name: &'static str,
    pkg_version: &'static str,
    l10n_arg: &dyn Any,
    cmd: Command,
    meta_name: &'static str,
    meta_value: &dyn Any,
) {
    if let Some(txt) = meta_value.downcast_ref::<CommandMetaVar<Txt>>() {
        let mut l10n_file = "";

        if let Some(&enabled) = l10n_arg.downcast_ref::<bool>() {
            if !enabled {
                return;
            }
        } else if let Some(&file) = l10n_arg.downcast_ref::<&'static str>() {
            l10n_file = file;
        } else {
            tracing::error!("unknown l10n value in {:?}", cmd.event());
            return;
        }

        EVENTS_L10N.init_meta_l10n([pkg_name, pkg_version, l10n_file], cmd, meta_name, txt.clone());
    }
}

/// Identifies a command event.
///
/// Use the [`command!`] to declare commands, it declares command static items with optional
/// [metadata](#metadata) initialization.
///
/// ```
/// # use zng_app::event::*;
/// # pub trait CommandFooBarExt: Sized { fn init_foo(self, foo: bool) -> Self { self } fn init_bar(self, bar: bool) -> Self { self } }
/// # impl CommandFooBarExt for Command { }
/// command! {
///     /// Foo-bar command.
///     pub static FOO_BAR_CMD { foo: true, bar: false };
/// }
/// ```
///
/// # Metadata
///
/// Commands can have associated metadata, this metadata is extendable and can be used to enable
/// command features such as command shortcuts. The metadata can be accessed using [`with_meta`], metadata
/// extensions traits can use this metadata to store state. See [`CommandMeta`] for more details.
///
/// # Handles
///
/// Unlike other events, commands only notify if it has at least one handler, handlers
/// must call [`subscribe`] to indicate that the command is relevant to the current app state and
/// set the subscription handle [`enabled`] flag to indicate that the handler can fulfill command requests.
///
/// # Scopes
///
/// Commands are *global* by default, meaning an enabled handle anywhere in the app enables it everywhere.
/// You can use [`scoped`] to declare *sub-commands* that are the same command event, but filtered to a scope, metadata
/// of scoped commands inherit from the app scope metadata, but can be overridden just for the scope.
///
/// [`command!`]: macro@crate::event::command
/// [`subscribe`]: Command::subscribe
/// [`with_meta`]: Command::with_meta
/// [`scoped`]: Command::scoped
/// [`enabled`]: CommandHandle::enabled
#[derive(Clone, Copy)]
pub struct Command {
    event: Event<CommandArgs>,
    local: &'static AppLocal<CommandData>,
    scope: CommandScope,
}
struct CommandDbg {
    static_name: &'static str,
    scope: CommandScope,
    state: Option<[usize; 2]>,
}
impl CommandDbg {
    fn new(static_name: &'static str, scope: CommandScope) -> Self {
        Self {
            static_name,
            scope,
            state: None,
        }
    }
}
impl fmt::Debug for CommandDbg {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if f.alternate() {
            let mut d = f.debug_struct("Command");
            d.field("static_name", &self.static_name).field("scope", &self.scope);
            if let Some([has, enabled]) = &self.state {
                d.field("handle_count", has);
                d.field("enabled_count", enabled);
            }

            d.finish_non_exhaustive()
        } else {
            write!(f, "{}", self.static_name)?;
            match self.scope {
                CommandScope::App => Ok(()),
                CommandScope::Window(id) => write!(f, "({id})"),
                CommandScope::Widget(id) => write!(f, "({id})"),
            }
        }
    }
}
impl fmt::Debug for Command {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let dbg = if let Some(d) = self.local.try_read() {
            let mut dbg = CommandDbg::new(d.static_name, self.scope);
            dbg.state = Some([d.handle_count, d.enabled_count]);
            dbg
        } else {
            CommandDbg::new("<locked>", self.scope)
        };
        fmt::Debug::fmt(&dbg, f)
    }
}
impl Command {
    #[doc(hidden)]
    pub const fn new(event_local: &'static AppLocal<EventData>, command_local: &'static AppLocal<CommandData>) -> Self {
        Command {
            event: Event::new(event_local),
            local: command_local,
            scope: CommandScope::App,
        }
    }

    /// Create a new handle to this command.
    ///
    /// A handle indicates that command handlers are present in the current app, the `enabled` flag
    /// indicates the handler is ready to fulfill command requests.
    ///
    /// If the command is scoped on a window or widget if it is added to the command event subscribers.
    pub fn subscribe(&self, enabled: bool) -> CommandHandle {
        self.local.write().subscribe(*self, enabled, None)
    }

    /// Create a new handle for this command for a handler in the `target` widget.
    ///
    /// The handle behaves like [`subscribe`], but include the `target` on the delivery list for app scoped commands.
    /// Note this only works for global commands (app scope), window and widget scoped commands only notify the scope
    /// so the `target` is ignored for scoped commands.
    ///
    /// [`subscribe`]: Command::subscribe
    pub fn subscribe_wgt(&self, enabled: bool, target: WidgetId) -> CommandHandle {
        self.local.write().subscribe(*self, enabled, Some(target))
    }

    /// Underlying event that represents this command in any scope.
    pub fn event(&self) -> Event<CommandArgs> {
        self.event
    }

    /// Command scope.
    pub fn scope(&self) -> CommandScope {
        self.scope
    }

    /// Gets the command in a new `scope`.
    pub fn scoped(mut self, scope: impl Into<CommandScope>) -> Command {
        self.scope = scope.into();
        self
    }

    /// Visit the command custom metadata of the current scope.
    ///
    /// Metadata for [`CommandScope::App`] is retained for the duration of the app, metadata scoped
    /// on window or widgets is dropped after an update cycle with no handler and no strong references
    /// to [`has_handlers`] and [`is_enabled`].
    ///
    /// [`has_handlers`]: Self::has_handlers
    /// [`is_enabled`]: Self::is_enabled
    pub fn with_meta<R>(&self, visit: impl FnOnce(&mut CommandMeta) -> R) -> R {
        // code that runs before  calling `visit`, removed from the generics function
        fn init_meta(self_: &Command) -> parking_lot::MappedRwLockReadGuard<'static, CommandData> {
            {
                let mut write = self_.local.write();
                match write.meta_init.clone() {
                    MetaInit::Init(init) => {
                        let lock = Arc::new((std::thread::current().id(), Mutex::new(())));
                        write.meta_init = MetaInit::Initing(lock.clone());
                        let _init_guard = lock.1.lock();
                        drop(write);
                        init(*self_);
                        self_.local.write().meta_init = MetaInit::Inited;
                    }
                    MetaInit::Initing(l) => {
                        drop(write);
                        if l.0 != std::thread::current().id() {
                            let _wait = l.1.lock();
                        }
                    }
                    MetaInit::Inited => {}
                }
            }

            if !matches!(self_.scope, CommandScope::App) {
                let mut write = self_.local.write();
                write.scopes.entry(self_.scope).or_default();
            }
            self_.local.read()
        }
        let local_read = init_meta(self);
        let mut meta_lock = local_read.meta.lock();

        match self.scope {
            CommandScope::App => visit(&mut CommandMeta {
                meta: meta_lock.borrow_mut(),
                scope: None,
            }),
            scope => {
                let scope = local_read.scopes.get(&scope).unwrap();
                visit(&mut CommandMeta {
                    meta: meta_lock.borrow_mut(),
                    scope: Some(scope.meta.lock().borrow_mut()),
                })
            }
        }
    }

    /// Gets a variable that tracks if this command has any handlers.
    pub fn has_handlers(&self) -> Var<bool> {
        match self.scope {
            CommandScope::App => self.local.read().has_handlers.read_only(),
            scope => {
                // scoped data is retained only if there are handlers or observers (has_handlers, is_enabled)

                // get or insert entry
                let mut write = self.local.write();
                let entry = write.scopes.entry(scope).or_default();

                // create observer
                entry.observer_count += 1;
                let observer = var(entry.has_handlers.get());
                entry.has_handlers.set_bind(&observer).perm();

                // setup observer cleanup
                let command = *self;
                observer
                    .hook_drop(move || {
                        if !APP.is_started() {
                            return;
                        }
                        let mut write = command.local.write();
                        let mut entry = match write.scopes.entry(scope) {
                            hash_map::Entry::Occupied(e) => e,
                            hash_map::Entry::Vacant(_) => unreachable!(),
                        };
                        entry.get_mut().observer_count -= 1;
                        if entry.get().observer_count == 0 && entry.get().handle_count == 0 {
                            entry.remove();
                            EVENTS.unregister_command(command);
                        }
                    })
                    .perm();

                observer.read_only()
            }
        }
    }

    /// Gets a variable that tracks if this command has any enabled handlers.
    pub fn is_enabled(&self) -> Var<bool> {
        match self.scope {
            CommandScope::App => self.local.read().is_enabled.read_only(),
            scope => {
                let mut write = self.local.write();
                let entry = write.scopes.entry(scope).or_default();

                entry.observer_count += 1;
                let observer = var(entry.is_enabled.get());
                entry.is_enabled.set_bind(&observer).perm();

                let command = *self;
                observer
                    .hook_drop(move || {
                        if !APP.is_started() {
                            return;
                        }

                        let mut write = command.local.write();
                        let mut entry = match write.scopes.entry(scope) {
                            hash_map::Entry::Occupied(e) => e,
                            hash_map::Entry::Vacant(_) => unreachable!(),
                        };
                        entry.get_mut().observer_count -= 1;
                        if entry.get().observer_count == 0 && entry.get().handle_count == 0 {
                            entry.remove();
                            EVENTS.unregister_command(command);
                        }
                    })
                    .perm();

                observer.read_only()
            }
        }
    }

    /// Calls `visitor` for each scope of this command.
    ///
    /// Note that scoped commands are removed if unused, see [`with_meta`](Self::with_meta) for more details.
    pub fn visit_scopes<T>(&self, mut visitor: impl FnMut(Command) -> ControlFlow<T>) -> Option<T> {
        let read = self.local.read();
        for &scope in read.scopes.keys() {
            match visitor(self.scoped(scope)) {
                ControlFlow::Continue(_) => continue,
                ControlFlow::Break(r) => return Some(r),
            }
        }
        None
    }

    /// Schedule a command update without param.
    pub fn notify(&self) {
        self.event.notify(CommandArgs::now(
            None,
            self.scope,
            self.scope.search_target(),
            self.is_enabled().get(),
        ))
    }

    /// Schedule a command update without param for all scopes inside `parent`.
    pub fn notify_descendants(&self, parent: &WidgetInfo) {
        self.visit_scopes::<()>(|parse_cmd| {
            if let CommandScope::Widget(id) = parse_cmd.scope()
                && let Some(scope) = parent.tree().get(id)
                && scope.is_descendant(parent)
            {
                parse_cmd.notify();
            }
            ControlFlow::Continue(())
        });
    }

    /// Schedule a command update with custom `param`.
    pub fn notify_param(&self, param: impl Any + Send + Sync) {
        self.event.notify(CommandArgs::now(
            CommandParam::new(param),
            self.scope,
            self.scope.search_target(),
            self.is_enabled().get(),
        ));
    }

    /// Schedule a command update linked with an external event `propagation`.
    pub fn notify_linked(&self, propagation: EventPropagationHandle, param: Option<CommandParam>) {
        self.event.notify(CommandArgs::new(
            crate::INSTANT.now(),
            propagation,
            param,
            self.scope,
            self.scope.search_target(),
            self.is_enabled().get(),
        ))
    }

    /// Visit each new update, oldest first, that target the context widget.
    ///
    /// This is similar to [`Event::each_update`], but with extra filtering. If `direct_scope_only` is enabled
    /// only handle exact command scope matches, otherwise the app scope matches all events, the window scope matches all events for the window
    /// or widgets in the window and the widget scope matches the widget and all descendants.
    pub fn each_update(&self, direct_scope_only: bool, ignore_propagation: bool, mut handler: impl FnMut(&CommandArgs)) {
        self.event.each_update(ignore_propagation, move |args| {
            if args.scope_matches(direct_scope_only, self.scope) {
                handler(args);
            }
        });
    }

    /// Visit the latest update that targets the context widget.
    ///
    /// This is similar to [`Event::latest_update`], but with extra filtering.
    pub fn latest_update<O>(
        &self,
        direct_scope_only: bool,
        ignore_propagation: bool,
        handler: impl FnOnce(&CommandArgs) -> O,
    ) -> Option<O> {
        let mut r = None;
        self.event.latest_update(ignore_propagation, |args| {
            if args.scope_matches(direct_scope_only, self.scope) {
                r = Some(handler(args));
            }
        });
        r
    }

    /// Visit the latest update that targets the context widget.
    ///
    /// This is similar to [`Event::has_update`], but with extra filtering.
    pub fn has_update(&self, direct_scope_only: bool, ignore_propagation: bool) -> bool {
        self.latest_update(direct_scope_only, ignore_propagation, |_| true).unwrap_or(false)
    }

    /// Creates a preview event handler for the command.
    ///
    /// This is similar to [`Event::on_pre_event`], but with extra filtering. The `handler` is only called if
    /// handle is [`enabled`] and if the scope matches. if `direct_scope_only` is enabled only handles exact
    /// matches, otherwise the app scope matches all events, the window scope matches all events for the window
    /// or widgets in the window and the widget scope matches the widget and all descendants.
    ///
    /// The `init_enabled` value defines the handle initial state.
    ///
    /// [`enabled`]: CommandHandle::enabled
    pub fn on_pre_event(
        &self,
        init_enabled: bool,
        direct_scope_only: bool,
        ignore_propagation: bool,
        handler: Handler<CommandArgs>,
    ) -> CommandHandle {
        let (mut handle, handler) = self.event_handler(init_enabled, direct_scope_only, handler);
        handle._handles.push(self.event().on_pre_event(ignore_propagation, handler));
        handle
    }

    /// Creates an event handler for the command.
    ///
    /// This is similar to [`Event::on_event`], but with extra filtering. The `handler` is only called if
    /// the command handle is [`enabled`] and if the scope matches. if `direct_scope_only` is enabled only handles exact
    /// matches, otherwise the app scope matches all events, the window scope matches all events for the window
    /// or widgets in the window and the widget scope matches the widget and all descendants.
    ///
    /// The `init_enabled` value defines the handle initial state.
    ///
    /// [`enabled`]: CommandHandle::enabled
    pub fn on_event(
        &self,
        init_enabled: bool,
        direct_scope_only: bool,
        ignore_propagation: bool,
        handler: Handler<CommandArgs>,
    ) -> CommandHandle {
        let (mut handle, handler) = self.event_handler(init_enabled, direct_scope_only, handler);
        handle._handles.push(self.event().on_event(ignore_propagation, handler));
        handle
    }

    fn event_handler(
        &self,
        init_enabled: bool,
        direct_scope_only: bool,
        handler: Handler<CommandArgs>,
    ) -> (CommandHandle, Handler<CommandArgs>) {
        let handle = self.subscribe(init_enabled);
        let local_enabled = handle.enabled().clone();
        let handler = if direct_scope_only {
            let scope = self.scope();
            handler.filtered(move |a| a.scope == scope && local_enabled.get())
        } else {
            match self.scope() {
                CommandScope::App => handler.filtered(move |_| local_enabled.get()),
                CommandScope::Window(id) => {
                    handler.filtered(move |a| a.target.as_ref().map(|t| t.window_id() == id).unwrap_or(false) && local_enabled.get())
                }
                CommandScope::Widget(id) => {
                    handler.filtered(move |a| a.target.as_ref().map(|t| t.contains(id)).unwrap_or(false) && local_enabled.get())
                }
            }
        };
        (handle, handler)
    }

    /// Sets a handler like [`Command::on_pre_event`], but the args include the handle [`enabled`] and the handler
    /// is called when the handle is disabled as well.
    ///
    /// [`enabled`]: CommandHandle::enabled
    pub fn on_pre_event_with_enabled(
        &self,
        init_enabled: bool,
        direct_scope_only: bool,
        ignore_propagation: bool,
        handler: Handler<(CommandArgs, Var<bool>)>,
    ) -> CommandHandle {
        let (mut handle, handler) = self.event_handler_with_enabled(init_enabled, direct_scope_only, handler);
        handle._handles.push(self.event().on_pre_event(ignore_propagation, handler));
        handle
    }

    /// Sets a handler like [`Command::on_event`], but the args include the handle [`enabled`] and the handler
    /// is called when the handle is disabled as well.
    ///
    /// [`enabled`]: CommandHandle::enabled
    pub fn on_event_with_enabled(
        &self,
        init_enabled: bool,
        direct_scope_only: bool,
        ignore_propagation: bool,
        handler: Handler<(CommandArgs, Var<bool>)>,
    ) -> CommandHandle {
        let (mut handle, handler) = self.event_handler_with_enabled(init_enabled, direct_scope_only, handler);
        handle._handles.push(self.event().on_event(ignore_propagation, handler));
        handle
    }

    fn event_handler_with_enabled(
        &self,
        init_enabled: bool,
        direct_scope_only: bool,
        mut handler: Handler<(CommandArgs, Var<bool>)>,
    ) -> (CommandHandle, Handler<CommandArgs>) {
        let handle = self.subscribe(init_enabled);
        let local_enabled = handle.enabled().clone();

        let r: Handler<CommandArgs>;
        if direct_scope_only {
            let scope = self.scope();
            r = Box::new(move |a: &CommandArgs| {
                if a.scope == scope {
                    handler(&(a.clone(), local_enabled.clone()))
                } else {
                    HandlerResult::Done
                }
            });
        } else {
            match self.scope() {
                CommandScope::App => r = Box::new(move |a: &CommandArgs| handler(&(a.clone(), local_enabled.clone()))),
                CommandScope::Window(id) => {
                    r = Box::new(move |a: &CommandArgs| {
                        if a.target.as_ref().map(|t| t.window_id() == id).unwrap_or(false) {
                            handler(&(a.clone(), local_enabled.clone()))
                        } else {
                            HandlerResult::Done
                        }
                    })
                }
                CommandScope::Widget(id) => {
                    r = Box::new(move |a: &CommandArgs| {
                        if a.target.as_ref().map(|t| t.contains(id)).unwrap_or(false) {
                            handler(&(a.clone(), local_enabled.clone()))
                        } else {
                            HandlerResult::Done
                        }
                    })
                }
            }
        };
        (handle, r)
    }

    /// Name of the `static` item that defines this command.
    pub fn static_name(&self) -> &'static str {
        self.local.read().static_name
    }
}
impl ops::Deref for Command {
    type Target = Event<CommandArgs>;

    fn deref(&self) -> &Self::Target {
        &self.event
    }
}
impl PartialEq for Command {
    fn eq(&self, other: &Self) -> bool {
        self.event == other.event && self.scope == other.scope
    }
}
impl Eq for Command {}
impl std::hash::Hash for Command {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        std::hash::Hash::hash(&self.event.as_any(), state);
        std::hash::Hash::hash(&self.scope, state);
    }
}

/// Represents the scope of a [`Command`].
///
/// The command scope defines the targets of its event and the context of its metadata.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub enum CommandScope {
    /// Default scope, this is the scope of command types declared using [`command!`].
    App,
    /// Scope of a window.
    ///
    /// Note that the window scope is different from the window root widget scope, the metadata store and command
    /// handles are different, but subscribers set on the window root should probably also subscribe to the window scope.
    Window(WindowId),
    /// Scope of a widget.
    Widget(WidgetId),
}
impl CommandScope {
    /// Search for the widget scope, or the window root widget for window scope.
    pub fn search_target(self) -> Option<WidgetPath> {
        match self {
            CommandScope::App => None,
            CommandScope::Window(id) => WINDOWS_APP.widget_tree(id).map(|t| t.root().path()),
            CommandScope::Widget(id) => WINDOWS_APP.widget_info(id).map(|w| w.path()),
        }
    }
}
impl_from_and_into_var! {
    fn from(id: WidgetId) -> CommandScope {
        CommandScope::Widget(id)
    }
    fn from(id: WindowId) -> CommandScope {
        CommandScope::Window(id)
    }
    /// Widget scope.
    fn from(widget_name: &'static str) -> CommandScope {
        WidgetId::named(widget_name).into()
    }
    /// Widget scope.
    fn from(widget_name: Txt) -> CommandScope {
        WidgetId::named(widget_name).into()
    }
}

event_args! {
    /// Event args for command events.
    pub struct CommandArgs {
        /// Optional parameter for the command handler.
        pub param: Option<CommandParam>,

        /// Scope of command that notified.
        pub scope: CommandScope,

        /// Target widget.
        ///
        /// * If the scope is `App` this is `None`.
        /// * If the scope is `Window` this is the window root widget, if the window was found.
        /// * If the scope is `Widget` this is the widget, if it was found.
        pub target: Option<WidgetPath>,

        /// If the command was enabled when the command notified.
        ///
        /// If `false` the command primary action must not run, but a secondary "disabled interaction"
        /// that indicates what conditions enable the command is recommended.
        ///
        /// Note that this is the [`Command::is_enabled`] value, it is `true` id any handle is enabled,
        /// the local handler might still be disabled.
        pub enabled: bool,

        ..

        /// Broadcast to all if the scope is `App`, otherwise if is in `target`.
        fn is_in_target(&self, id: WidgetId) -> bool {
            match self.scope {
                CommandScope::App => true,
                _ => match &self.target {
                    Some(t) => t.contains(id),
                    None => false,
                },
            }
        }

        /// Validates if the target matches the scope.
        fn validate(&self) -> Result<(), Txt> {
            if let Some(t) = &self.target {
                match self.scope {
                    CommandScope::App => return Err("args for app scope cannot have a `target`".into()),
                    CommandScope::Window(id) => {
                        if id != t.window_id() || t.widgets_path().len() > 1 {
                            return Err("args for window scope must only `target` that window root widget".into());
                        }
                    }
                    CommandScope::Widget(id) => {
                        if id != t.widget_id() {
                            return Err("args for widget scope must only `target` that widget".into());
                        }
                    }
                }
            }
            Ok(())
        }
    }
}
impl CommandArgs {
    /// Returns a reference to a parameter of `T` if [`parameter`](#structfield.parameter) is set to a value of `T`.
    pub fn param<T: Any>(&self) -> Option<&T> {
        self.param.as_ref().and_then(|p| p.downcast_ref::<T>())
    }

    /// Returns [`param`] if is [`enabled`].
    ///
    /// [`param`]: Self::param()
    /// [`enabled`]: Self::enabled
    pub fn enabled_param<T: Any>(&self) -> Option<&T> {
        if self.enabled { self.param::<T>() } else { None }
    }

    /// Returns [`param`] if is not [`enabled`].
    ///
    /// [`param`]: Self::param()
    /// [`enabled`]: Self::enabled
    pub fn disabled_param<T: Any>(&self) -> Option<&T> {
        if !self.enabled { self.param::<T>() } else { None }
    }

    /// If `direct_only` is enabled only matches exact command scope matches,
    /// otherwise the app `scope` matches all args, the window `scope` matches all events for the window
    /// or widgets in the window and the widget `scope` matches the widget and all descendants.
    pub fn scope_matches(&self, direct_only: bool, scope: CommandScope) -> bool {
        if direct_only {
            self.scope == scope
        } else {
            match (scope, self.scope) {
                (CommandScope::App, _) => true,
                (CommandScope::Window(scope_id), CommandScope::Window(args_id)) => scope_id == args_id,
                (CommandScope::Window(scope_id), CommandScope::Widget(args_id)) => {
                    // if window contains widget
                    if let Some(t) = &self.target {
                        t.window_id() == scope_id && t.contains(args_id)
                    } else if let Some(info) = WINDOWS_APP.widget_tree(scope_id) {
                        info.contains(args_id)
                    } else {
                        false
                    }
                }
                (CommandScope::Widget(scope_id), CommandScope::Widget(args_id)) => {
                    // if scope widget contains args scope widget
                    if let Some(t) = &self.target {
                        t.widgets_path().iter().position(|i| *i == scope_id).unwrap_or(usize::MAX)
                            < t.widgets_path().iter().position(|i| *i == args_id).unwrap_or(usize::MAX)
                    } else {
                        todo!()
                    }
                }
                _ => false,
            }
        }
    }
}

/// A handle to a [`Command`] subscription.
///
/// Holding the command handle indicates that the command is relevant in the current app state.
/// The handle also needs to be enabled to indicate that the command primary action can be executed.
///
/// You can use the [`Command::subscribe`] method in a command type to create a handle.
pub struct CommandHandle {
    command: Option<Command>,
    local_enabled: Var<bool>,
    // event subscription handle in `subscribe` or event handle in `on_(pre_)event`
    _handles: VarHandles,
}
/// Clone the handle.
///
/// Note that the cloned handle will have its own enabled state, disconnected from this handle.
impl Clone for CommandHandle {
    fn clone(&self) -> Self {
        match self.command {
            Some(c) => c.subscribe(self.local_enabled.get()),
            None => Self::dummy(),
        }
    }
}
impl CommandHandle {
    /// The command.
    pub fn command(&self) -> Option<Command> {
        self.command
    }

    /// Variable that gets and sets if this specific handle is enabled.
    ///
    /// The [`Command::is_enabled`] is `true` if any handle is enabled.
    pub fn enabled(&self) -> &Var<bool> {
        &self.local_enabled
    }

    /// New handle not connected to any command.
    pub fn dummy() -> Self {
        CommandHandle {
            command: None,
            local_enabled: const_var(false),
            _handles: VarHandles::dummy(),
        }
    }

    fn new(cmd: Command, event_handle: VarHandle, enabled: bool) -> Self {
        let mut r = Self {
            command: Some(cmd),
            local_enabled: var(enabled),
            _handles: VarHandles::dummy(),
        };

        // var explicit update can call hook without changing value
        let mut last_applied = enabled;
        r._handles.push(r.local_enabled.hook(move |args| {
            let _hold = &event_handle;
            let enabled = *args.value();
            if last_applied != enabled {
                Self::update_enabled(cmd, enabled);
                last_applied = enabled;
            }
            true
        }));

        r
    }

    fn update_enabled(command: Command, enabled: bool) {
        let mut write = command.local.write();
        match command.scope {
            CommandScope::App => {
                if enabled {
                    write.enabled_count += 1;
                    if write.enabled_count == 1 {
                        write.is_enabled.set(true);
                    }
                    tracing::trace!(
                        "command handle {:?} enabled, count: {:?}",
                        CommandDbg::new(write.static_name, command.scope),
                        write.enabled_count
                    );
                } else {
                    write.enabled_count = match write.enabled_count.checked_sub(1) {
                        Some(c) => c,
                        None => {
                            #[cfg(debug_assertions)]
                            panic!("handle for {} was disabled when enabled_count was already zero", write.static_name);
                            #[cfg(not(debug_assertions))]
                            0
                        }
                    };
                    if write.enabled_count == 0 {
                        write.is_enabled.set(false);
                    }
                    tracing::trace!(
                        "command handle {:?} disabled, count: {:?}",
                        CommandDbg::new(write.static_name, command.scope),
                        write.enabled_count
                    );
                }
            }
            scope => {
                let write = &mut *write;
                if let Some(data) = write.scopes.get_mut(&scope) {
                    if enabled {
                        data.enabled_count += 1;
                        if data.enabled_count == 1 {
                            data.is_enabled.set(true);
                        }
                        tracing::trace!(
                            "command handle {:?} enabled, count: {:?}",
                            CommandDbg::new(write.static_name, command.scope),
                            data.enabled_count
                        );
                    } else {
                        data.enabled_count = match data.enabled_count.checked_sub(1) {
                            Some(c) => c,
                            None => {
                                #[cfg(debug_assertions)]
                                panic!(
                                    "handle for {:?} was disabled when enabled_count was already zero",
                                    CommandDbg::new(write.static_name, scope)
                                );
                                #[cfg(not(debug_assertions))]
                                0
                            }
                        };
                        if data.enabled_count == 0 {
                            data.is_enabled.set(false);
                        }
                        tracing::trace!(
                            "command handle {:?} enabled, count: {:?}",
                            CommandDbg::new(write.static_name, command.scope),
                            data.enabled_count
                        );
                    }
                }
            }
        }
    }

    /// If the handle is not connected to any command.
    pub fn is_dummy(&self) -> bool {
        self.command.is_none()
    }

    /// Drop the handle removing its effect.
    ///
    /// The command will be stuck indicating that it has handlers and if this handle is enabled, it will
    /// continue indicating it is enabled until the app exit.
    pub fn perm(mut self) {
        // perm the handle
        mem::replace(&mut self._handles, VarHandles::dummy()).perm();
        // pretend we are dummy to avoid Drop code
        self.command = None;
    }
}
impl fmt::Debug for CommandHandle {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("CommandHandle")
            .field("command", &self.command)
            .field("enabled", &self.local_enabled.get())
            .finish_non_exhaustive()
    }
}
impl Drop for CommandHandle {
    fn drop(&mut self) {
        if let Some(command) = self.command.take()
            && APP.is_started()
        {
            let mut write = command.local.write();
            match command.scope {
                CommandScope::App => {
                    write.handle_count = match write.handle_count.checked_sub(1) {
                        Some(c) => c,
                        None => {
                            #[cfg(debug_assertions)]
                            panic!("handle for {} was dropped when handle_count was already zero", write.static_name);
                            #[cfg(not(debug_assertions))]
                            0
                        }
                    };
                    if write.handle_count == 0 {
                        write.has_handlers.set(false);
                    }

                    if self.local_enabled.get() {
                        write.enabled_count = match write.enabled_count.checked_sub(1) {
                            Some(c) => c,
                            None => {
                                #[cfg(debug_assertions)]
                                panic!(
                                    "handle for enabled {} was dropped when enabled_count was already zero",
                                    write.static_name
                                );
                                #[cfg(not(debug_assertions))]
                                0
                            }
                        };

                        if write.enabled_count == 0 {
                            write.is_enabled.set(false);
                        }
                    }

                    tracing::trace!(
                        "unsubscribe to {:?}, handle_count: {:?}, enabled_count: {:?}",
                        CommandDbg::new(write.static_name, command.scope),
                        write.handle_count,
                        write.enabled_count
                    );
                }
                scope => {
                    let write = &mut *write;
                    if let hash_map::Entry::Occupied(mut entry) = write.scopes.entry(scope) {
                        let data = entry.get_mut();

                        data.handle_count = match data.handle_count.checked_sub(1) {
                            Some(c) => c,
                            None => {
                                #[cfg(debug_assertions)]
                                panic!(
                                    "handle for {:?} was dropped when handle_count was already zero",
                                    CommandDbg::new(write.static_name, scope)
                                );
                                #[cfg(not(debug_assertions))]
                                0
                            }
                        };

                        if self.local_enabled.get() {
                            data.enabled_count = match data.enabled_count.checked_sub(1) {
                                Some(c) => c,
                                None => {
                                    #[cfg(debug_assertions)]
                                    panic!(
                                        "handle for enabled {:?} was dropped when enabled_count was already zero",
                                        CommandDbg::new(write.static_name, scope)
                                    );
                                    #[cfg(not(debug_assertions))]
                                    0
                                }
                            };

                            if data.enabled_count == 0 {
                                data.is_enabled.set(false);
                            }
                        }

                        tracing::trace!(
                            "unsubscribe to {:?}, handle_count: {:?}, enabled_count: {:?}",
                            CommandDbg::new(write.static_name, command.scope),
                            data.handle_count,
                            data.enabled_count
                        );

                        if data.handle_count == 0 {
                            data.has_handlers.set(false);
                            if data.observer_count == 0 {
                                entry.remove();
                                EVENTS.unregister_command(command);
                            }
                        }
                    }
                }
            }
        }
    }
}
impl Default for CommandHandle {
    fn default() -> Self {
        Self::dummy()
    }
}

/// Represents a reference counted `dyn Any` object parameter for a command request.
#[derive(Clone)]
#[non_exhaustive]
pub struct CommandParam(pub Arc<dyn Any + Send + Sync>);
impl PartialEq for CommandParam {
    fn eq(&self, other: &Self) -> bool {
        Arc::ptr_eq(&self.0, &other.0)
    }
}
impl Eq for CommandParam {}
impl CommandParam {
    /// New param.
    ///
    /// If `param` is already a [`CommandParam`] or `Arc<dyn Any + Send + Sync>` returns a clone.
    pub fn new(param: impl Any + Send + Sync + 'static) -> Self {
        let p: &dyn Any = &param;
        if let Some(p) = p.downcast_ref::<Self>() {
            p.clone()
        } else if let Some(p) = p.downcast_ref::<Arc<dyn Any + Send + Sync>>() {
            CommandParam(p.clone())
        } else {
            CommandParam(Arc::new(param))
        }
    }

    /// Gets the [`TypeId`] of the parameter.
    pub fn type_id(&self) -> TypeId {
        self.0.type_id()
    }

    /// Gets a typed reference to the parameter if it is of type `T`.
    pub fn downcast_ref<T: Any>(&self) -> Option<&T> {
        self.0.downcast_ref()
    }

    /// Returns `true` if the parameter type is `T`.
    pub fn is<T: Any>(&self) -> bool {
        self.0.is::<T>()
    }
}
impl fmt::Debug for CommandParam {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_tuple("CommandParam").field(&self.0.type_id()).finish()
    }
}
zng_var::impl_from_and_into_var! {
    fn from(param: CommandParam) -> Option<CommandParam>;
}

#[rustfmt::skip] // for zng fmt
unique_id_64! {
    /// Unique identifier of a command metadata state variable.
    ///
    /// This type is very similar to [`StateId`], but `T` is the value type of the metadata variable.
    ///
    /// [`StateId`]: zng_state_map::StateId
    pub struct CommandMetaVarId<T: (StateValue + VarValue)>: StateId;
}
zng_unique_id::impl_unique_id_bytemuck!(CommandMetaVarId<T: (StateValue + VarValue)>);
impl<T: StateValue + VarValue> CommandMetaVarId<T> {
    fn app(self) -> StateId<Var<T>> {
        let id = self.get();
        StateId::from_raw(id)
    }

    fn scope(self) -> StateId<Var<T>> {
        let id = self.get();
        StateId::from_raw(id)
    }
}

impl<T: StateValue + VarValue> fmt::Debug for CommandMetaVarId<T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        #[cfg(debug_assertions)]
        let t = pretty_type_name::pretty_type_name::<T>();
        #[cfg(not(debug_assertions))]
        let t = "$T";

        if f.alternate() {
            writeln!(f, "CommandMetaVarId<{t} {{")?;
            writeln!(f, "   id: {},", self.get())?;
            writeln!(f, "   sequential: {}", self.sequential())?;
            writeln!(f, "}}")
        } else {
            write!(f, "CommandMetaVarId<{t}>({})", self.sequential())
        }
    }
}

/// Access to metadata of a command.
///
/// The metadata storage can be accessed using the [`Command::with_meta`]
/// method, implementers must declare and extension trait that adds methods that return [`CommandMetaVar`] or
/// [`ReadOnlyCommandMetaVar`] that are stored in the [`CommandMeta`]. An initialization builder method for
/// each value also must be provided to integrate with the [`command!`] macro.
///
/// # Examples
///
/// The [`command!`] initialization transforms `foo: true,` to `command.init_foo(true);`, to support that, the command extension trait
/// must have a `foo` and `init_foo` methods.
///
/// ```
/// use zng_app::{event::*, static_id, var::*};
///
/// static_id! {
///     static ref COMMAND_FOO_ID: CommandMetaVarId<bool>;
///     static ref COMMAND_BAR_ID: CommandMetaVarId<bool>;
/// }
///
/// /// FooBar command values.
/// pub trait CommandFooBarExt {
///     /// Gets read/write *foo*.
///     fn foo(self) -> CommandMetaVar<bool>;
///
///     /// Gets read-only *bar*.
///     fn bar(self) -> ReadOnlyCommandMetaVar<bool>;
///
///     /// Gets a read-only var derived from other metadata.
///     fn foo_and_bar(self) -> Var<bool>;
///
///     /// Init *foo*.
///     fn init_foo(self, foo: bool) -> Self;
///
///     /// Init *bar*.
///     fn init_bar(self, bar: bool) -> Self;
/// }
///
/// impl CommandFooBarExt for Command {
///     fn foo(self) -> CommandMetaVar<bool> {
///         self.with_meta(|m| m.get_var_or_default(*COMMAND_FOO_ID))
///     }
///
///     fn bar(self) -> ReadOnlyCommandMetaVar<bool> {
///         self.with_meta(|m| m.get_var_or_insert(*COMMAND_BAR_ID, || true)).read_only()
///     }
///
///     fn foo_and_bar(self) -> Var<bool> {
///         merge_var!(self.foo(), self.bar(), |f, b| *f && *b)
///     }
///
///     fn init_foo(self, foo: bool) -> Self {
///         self.with_meta(|m| m.init_var(*COMMAND_FOO_ID, foo));
///         self
///     }
///
///     fn init_bar(self, bar: bool) -> Self {
///         self.with_meta(|m| m.init_var(*COMMAND_BAR_ID, bar));
///         self
///     }
/// }
/// ```
///
/// [`command!`]: macro@crate::event::command
pub struct CommandMeta<'a> {
    meta: StateMapMut<'a, CommandMetaState>,
    scope: Option<StateMapMut<'a, CommandMetaState>>,
}
impl CommandMeta<'_> {
    /// Clone a meta value identified by a [`StateId`].
    ///
    /// If the key is not set in the app, insert it using `init` to produce a value.
    ///
    /// [`StateId`]: zng_state_map::StateId
    pub fn get_or_insert<T, F>(&mut self, id: impl Into<StateId<T>>, init: F) -> T
    where
        T: StateValue + Clone,
        F: FnOnce() -> T,
    {
        let id = id.into();
        if let Some(scope) = &mut self.scope {
            if let Some(value) = scope.get(id) {
                value.clone()
            } else if let Some(value) = self.meta.get(id) {
                value.clone()
            } else {
                let value = init();
                let r = value.clone();
                scope.set(id, value);
                r
            }
        } else {
            self.meta.entry(id).or_insert_with(init).clone()
        }
    }

    /// Clone a meta value identified by a [`StateId`].
    ///
    /// If the key is not set, insert the default value and returns a clone of it.
    ///
    /// [`StateId`]: zng_state_map::StateId
    pub fn get_or_default<T>(&mut self, id: impl Into<StateId<T>>) -> T
    where
        T: StateValue + Clone + Default,
    {
        self.get_or_insert(id, Default::default)
    }

    /// Clone a meta value identified by a [`StateId`] if it is set.
    ///
    /// [`StateId`]: zng_state_map::StateId
    pub fn get<T>(&self, id: impl Into<StateId<T>>) -> Option<T>
    where
        T: StateValue + Clone,
    {
        let id = id.into();
        if let Some(scope) = &self.scope {
            scope.get(id).or_else(|| self.meta.get(id))
        } else {
            self.meta.get(id)
        }
        .cloned()
    }

    /// Set the meta value associated with the [`StateId`].
    ///
    /// [`StateId`]: zng_state_map::StateId
    pub fn set<T>(&mut self, id: impl Into<StateId<T>>, value: impl Into<T>)
    where
        T: StateValue + Clone,
    {
        if let Some(scope) = &mut self.scope {
            scope.set(id, value);
        } else {
            self.meta.set(id, value);
        }
    }

    /// Set the metadata value only if it is not set.
    ///
    /// This does not set the scoped override, only the command type metadata.
    pub fn init<T>(&mut self, id: impl Into<StateId<T>>, value: impl Into<T>)
    where
        T: StateValue + Clone,
    {
        self.meta.entry(id).or_insert(value);
    }

    /// Clone a meta variable identified by a [`CommandMetaVarId`].
    ///
    /// The variable is read-write and is clone-on-write if the command is scoped.
    ///
    /// [`read_only`]: Var::read_only
    pub fn get_var_or_insert<T, F>(&mut self, id: impl Into<CommandMetaVarId<T>>, init: F) -> CommandMetaVar<T>
    where
        T: StateValue + VarValue,
        F: FnOnce() -> T,
    {
        let id = id.into();
        if let Some(scope) = &mut self.scope {
            let meta = &mut self.meta;
            scope
                .entry(id.scope())
                .or_insert_with(|| {
                    let var = meta.entry(id.app()).or_insert_with(|| var(init())).clone();
                    var.cow()
                })
                .clone()
        } else {
            self.meta.entry(id.app()).or_insert_with(|| var(init())).clone()
        }
    }

    /// Clone a meta variable identified by a [`CommandMetaVarId`], if it is set.
    pub fn get_var<T>(&self, id: impl Into<CommandMetaVarId<T>>) -> Option<CommandMetaVar<T>>
    where
        T: StateValue + VarValue,
    {
        let id = id.into();
        if let Some(scope) = &self.scope {
            let meta = &self.meta;
            scope.get(id.scope()).cloned().or_else(|| meta.get(id.app()).cloned())
        } else {
            self.meta.get(id.app()).cloned()
        }
    }

    /// Clone a meta variable identified by a [`CommandMetaVarId`].
    ///
    /// Inserts a variable with the default value if no variable is in the metadata.
    pub fn get_var_or_default<T>(&mut self, id: impl Into<CommandMetaVarId<T>>) -> CommandMetaVar<T>
    where
        T: StateValue + VarValue + Default,
    {
        self.get_var_or_insert(id, Default::default)
    }

    /// Set the metadata variable if it was not set.
    ///
    /// This does not set the scoped override, only the command type metadata.
    pub fn init_var<T>(&mut self, id: impl Into<CommandMetaVarId<T>>, value: impl Into<T>)
    where
        T: StateValue + VarValue,
    {
        self.meta.entry(id.into().app()).or_insert_with(|| var(value.into()));
    }
}

/// Read-write command metadata variable.
///
/// This is a simple [`var`] for *app* scope, or a [`Var::cow`] for scoped commands.
/// If you get this variable from an app scoped command it sets
/// the value for all scopes. If you get this variable using a scoped command,
/// it is a clone-on-write variable that overrides only the value for the scope.
pub type CommandMetaVar<T> = Var<T>;

/// Read-only command metadata variable.
///
/// To convert a [`CommandMetaVar<T>`] into this var call [`read_only`].
///
/// [`read_only`]: Var::read_only
pub type ReadOnlyCommandMetaVar<T> = Var<T>;

/// Adds the [`name`](CommandNameExt) command metadata.
pub trait CommandNameExt {
    /// Gets a read-write variable that is the display name for the command.
    fn name(self) -> CommandMetaVar<Txt>;

    /// Sets the initial name if it is not set.
    fn init_name(self, name: impl Into<Txt>) -> Self;

    /// Gets a read-only variable that formats the name and first shortcut formatted as `"name (first_shortcut)"`
    ///
    /// Note that if no shortcut is set for the command this method returns the same as [`name`](Self::name).
    ///
    /// Note that the shortcut keys are not localized, consider using `ShortcutText!` instead.
    fn name_with_shortcut(self) -> Var<Txt>
    where
        Self: crate::shortcut::CommandShortcutExt;
}
static_id! {
    static ref COMMAND_NAME_ID: CommandMetaVarId<Txt>;
}
impl CommandNameExt for Command {
    fn name(self) -> CommandMetaVar<Txt> {
        self.with_meta(|m| {
            m.get_var_or_insert(*COMMAND_NAME_ID, || {
                let name = self.static_name();
                let name = name.strip_suffix("_CMD").unwrap_or(name);
                let mut title = String::with_capacity(name.len());
                let mut lower = false;
                for c in name.chars() {
                    if c == '_' {
                        if !title.ends_with(' ') {
                            title.push(' ');
                        }
                        lower = false;
                    } else if lower {
                        for l in c.to_lowercase() {
                            title.push(l);
                        }
                    } else {
                        title.push(c);
                        lower = true;
                    }
                }
                Txt::from(title)
            })
        })
    }

    fn init_name(self, name: impl Into<Txt>) -> Self {
        self.with_meta(|m| m.init_var(*COMMAND_NAME_ID, name.into()));
        self
    }

    fn name_with_shortcut(self) -> Var<Txt>
    where
        Self: crate::shortcut::CommandShortcutExt,
    {
        crate::var::merge_var!(self.name(), self.shortcut(), |name, shortcut| {
            if shortcut.is_empty() {
                name.clone()
            } else {
                zng_txt::formatx!("{name} ({})", shortcut[0])
            }
        })
    }
}

// support `init: |cmd| { }` in `command!`
impl Command {
    #[doc(hidden)]
    pub fn init_init(self, init: impl FnOnce(Self)) {
        init(self)
    }
    #[doc(hidden)]
    pub fn init(self) {}
}

/// Adds the [`info`](CommandInfoExt) command metadata.
pub trait CommandInfoExt {
    /// Gets a read-write variable that is a short informational string about the command.
    fn info(self) -> CommandMetaVar<Txt>;

    /// Sets the initial info if it is not set.
    fn init_info(self, info: impl Into<Txt>) -> Self;
}
static_id! {
    static ref COMMAND_INFO_ID: CommandMetaVarId<Txt>;
}
impl CommandInfoExt for Command {
    fn info(self) -> CommandMetaVar<Txt> {
        self.with_meta(|m| m.get_var_or_insert(*COMMAND_INFO_ID, Txt::default))
    }

    fn init_info(self, info: impl Into<Txt>) -> Self {
        self.with_meta(|m| m.init_var(*COMMAND_INFO_ID, info.into()));
        self
    }
}

enum CommandMetaState {}

#[derive(Clone)]
enum MetaInit {
    Init(fn(Command)),
    /// Initing in a thread, lock is for other threads.
    Initing(Arc<(ThreadId, Mutex<()>)>),
    Inited,
}

#[doc(hidden)]
pub struct CommandData {
    static_name: &'static str,

    meta_init: MetaInit,
    meta: Mutex<OwnedStateMap<CommandMetaState>>,

    handle_count: usize,
    enabled_count: usize,
    registered: bool,

    has_handlers: Var<bool>,
    is_enabled: Var<bool>,

    scopes: HashMap<CommandScope, ScopedValue>,
}
impl CommandData {
    pub fn new(meta_init: fn(Command), static_name: &'static str) -> Self {
        CommandData {
            static_name,
            meta_init: MetaInit::Init(meta_init),
            meta: Mutex::new(OwnedStateMap::new()),

            handle_count: 0,
            enabled_count: 0,
            registered: false,

            has_handlers: var(false),
            is_enabled: var(false),

            scopes: HashMap::default(),
        }
    }

    fn subscribe(&mut self, command: Command, enabled: bool, mut target: Option<WidgetId>) -> CommandHandle {
        match command.scope {
            CommandScope::App => {
                if !mem::replace(&mut self.registered, true) {
                    EVENTS.register_command(command);
                }

                self.handle_count += 1;
                if enabled {
                    self.enabled_count += 1;
                }

                if self.handle_count == 1 {
                    self.has_handlers.set(true);
                }
                if self.enabled_count == 1 {
                    self.is_enabled.set(true);
                }

                tracing::trace!(
                    "subscribe to {:?}, handle_count: {:?}, enabled_count: {:?}",
                    CommandDbg::new(self.static_name, command.scope),
                    self.handle_count,
                    self.enabled_count
                );
            }
            scope => {
                let data = self.scopes.entry(scope).or_default();

                if !mem::replace(&mut data.registered, true) {
                    EVENTS.register_command(command);
                }

                data.handle_count += 1;
                if enabled {
                    data.enabled_count += 1;
                }

                if data.handle_count == 1 {
                    data.has_handlers.set(true);
                }
                if data.enabled_count == 1 {
                    data.is_enabled.set(true);
                }

                tracing::trace!(
                    "subscribe to {:?}, handle_count: {:?}, enabled_count: {:?}",
                    CommandDbg::new(self.static_name, command.scope),
                    data.handle_count,
                    data.enabled_count
                );

                if let CommandScope::Widget(id) = scope {
                    target = Some(id);
                }
            }
        };

        CommandHandle::new(
            command,
            target
                .map(|t| command.event.subscribe(UpdateOp::Update, t))
                .unwrap_or_else(VarHandle::dummy),
            enabled,
        )
    }
}

struct ScopedValue {
    observer_count: usize,
    handle_count: usize,
    enabled_count: usize,
    is_enabled: Var<bool>,
    has_handlers: Var<bool>,
    meta: Mutex<OwnedStateMap<CommandMetaState>>,
    registered: bool,
}
impl Default for ScopedValue {
    fn default() -> Self {
        ScopedValue {
            observer_count: 0,
            is_enabled: var(false),
            has_handlers: var(false),
            handle_count: 0,
            enabled_count: 0,
            meta: Mutex::new(OwnedStateMap::default()),
            registered: false,
        }
    }
}

#[cfg(test)]
mod tests {
    use crate::APP;

    use super::*;

    command! {
        static FOO_CMD;
    }

    #[test]
    fn parameter_none() {
        let _ = CommandArgs::now(None, CommandScope::App, None, true);
    }

    #[test]
    fn enabled_not_scoped() {
        let mut app = APP.minimal().run_headless(false);

        assert!(!FOO_CMD.has_handlers().get());

        let handle = FOO_CMD.subscribe(true);
        app.update(false).assert_wait();
        assert!(FOO_CMD.is_enabled().get());

        handle.enabled().set(false);
        app.update(false).assert_wait();

        assert!(FOO_CMD.has_handlers().get());
        assert!(!FOO_CMD.is_enabled().get());

        handle.enabled().set(true);
        app.update(false).assert_wait();

        assert!(FOO_CMD.is_enabled().get());

        drop(handle);
        app.update(false).assert_wait();

        assert!(!FOO_CMD.has_handlers().get());
        assert!(!FOO_CMD.is_enabled().get());
    }

    #[test]
    fn enabled_scoped() {
        let mut app = APP.minimal().run_headless(false);

        let cmd = FOO_CMD;
        let cmd_scoped = FOO_CMD.scoped(WindowId::named("enabled_scoped"));
        app.update(false).assert_wait();
        assert!(!cmd.has_handlers().get());
        assert!(!cmd_scoped.has_handlers().get());

        let handle_scoped = cmd_scoped.subscribe(true);
        app.update(false).assert_wait();

        assert!(!cmd.has_handlers().get());
        assert!(cmd_scoped.is_enabled().get());

        handle_scoped.enabled().set(false);
        app.update(false).assert_wait();

        assert!(!cmd.has_handlers().get());
        assert!(!cmd_scoped.is_enabled().get());
        assert!(cmd_scoped.has_handlers().get());

        handle_scoped.enabled().set(true);
        app.update(false).assert_wait();

        assert!(!cmd.has_handlers().get());
        assert!(cmd_scoped.is_enabled().get());

        drop(handle_scoped);
        app.update(false).assert_wait();

        assert!(!cmd.has_handlers().get());
        assert!(!cmd_scoped.has_handlers().get());
    }

    #[test]
    fn has_handlers_not_scoped() {
        let mut app = APP.minimal().run_headless(false);

        assert!(!FOO_CMD.has_handlers().get());

        let handle = FOO_CMD.subscribe(false);
        app.update(false).assert_wait();

        assert!(FOO_CMD.has_handlers().get());

        drop(handle);
        app.update(false).assert_wait();

        assert!(!FOO_CMD.has_handlers().get());
    }

    #[test]
    fn has_handlers_scoped() {
        let mut app = APP.minimal().run_headless(false);

        let cmd = FOO_CMD;
        let cmd_scoped = FOO_CMD.scoped(WindowId::named("has_handlers_scoped"));
        app.update(false).assert_wait();

        assert!(!cmd.has_handlers().get());
        assert!(!cmd_scoped.has_handlers().get());

        let handle = cmd_scoped.subscribe(false);
        app.update(false).assert_wait();

        assert!(!cmd.has_handlers().get());
        assert!(cmd_scoped.has_handlers().get());

        drop(handle);
        app.update(false).assert_wait();

        assert!(!cmd.has_handlers().get());
        assert!(!cmd_scoped.has_handlers().get());
    }

    // there are also integration tests in tests/command.rs
}