duat-core 0.10.0

The core of Duat, a highly customizable text editor.
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
//! Utilities for stylizing the text of Duat.
use std::sync::{RwLock, RwLockReadGuard};

use FormKind::*;
use crossterm::style::{Attribute, Attributes, ContentStyle};
pub use crossterm::{cursor::SetCursorStyle as CursorShape, style::Color};

pub use self::global::*;
pub(crate) use self::global::{colorscheme_exists, exists};
use crate::{
    context::{self, sender},
    hook::{self, FormSet},
    session::DuatEvent,
    text::FormTag,
};

static BASE_FORMS: &[(&str, Form)] = &[
    ("default", Form::new()),
    ("accent", Form::new().bold()),
    ("caret.main", Form::new().reverse()),
    ("caret.extra", Form {
        kind: Ref(2, default_style()),
        ..Form::new().reverse()
    }),
    ("selection.main", Form::new().white().on_dark_grey()),
    ("selection.extra", Form::new().white().on_grey()),
    ("cloak", Form::new().grey().on_black()),
    ("character.control", Form::new().grey()),
    ("param.path", Form::new().yellow()),
    ("param.path.exists", Form {
        kind: Ref(8, ContentStyle {
            attributes: Attributes::none().with(Attribute::Underlined),
            ..default_style()
        }),
        ..Form::new().yellow().underlined()
    }),
    ("replace", Form::new().grey()),
];

/// The functions that will be exposed for public use.
mod global {
    use std::{
        any::TypeId,
        collections::HashMap,
        sync::{Arc, LazyLock, Mutex},
    };

    use super::{CursorShape, Form, FormId, Painter, Palette};
    #[doc(inline)]
    pub use crate::__id_of__ as id_of;
    use crate::{
        context,
        form::{FormKind, MaskId},
        hook::{self, ColorschemeSet},
    };

    static PALETTE: LazyLock<Palette> = LazyLock::new(Palette::new);
    static COLORSCHEMES: LazyLock<Mutex<HashMap<Arc<str>, ColorschemeFn>>> =
        LazyLock::new(Mutex::default);

    /// Sets the [`Form`] by the name of `name`.
    ///
    /// This will create a new form or replace one that already
    /// exists, and you can either set it to a [`Form`] directly, or
    /// reference another form by its name:
    ///
    /// ```rust
    /// # use duat_core::form::{self, Form};
    /// // Creates a regular form
    /// let reg_id = form::set("my_regular_form", Form::new().red());
    /// // Creates a form that references the first
    /// let ref_id = form::set("my_ref_form", Form::mimic("my_regular_form"));
    /// // Sets both "MyRegularForm" and "MyRefForm" to blue
    /// form::set("my_regular_form", Form::new().blue());
    /// ```
    ///
    /// If you are creating a plugin, or another kind of tool for
    /// others using Duat, use [`form::set_weak`] instead of this
    /// function.
    ///
    /// [`form::set_weak`]: set_weak
    pub fn set(name: impl ToString, form: Form) -> FormId {
        let name = name.to_string();
        let cloned_name = name.clone();

        match form.kind {
            FormKind::Normal => PALETTE.set_form(cloned_name, form),
            FormKind::Ref(refed, style) => PALETTE.set_ref(cloned_name, refed, style),
            _ => unreachable!(),
        }
    }

    /// Sets a form, "weakly".
    ///
    /// The difference between this function and [`form::set`] is
    /// that this function will only trigger if the form didn't
    /// already exist/was previously onle set with [`set_weak`].
    ///
    /// This is useful for plugins, since it prioritizes the user's
    /// preferences, no matter in what order this function and
    /// [`form::set`] are called:
    ///
    /// ```rust
    /// use duat_core::form::{self, Form};
    ///
    /// // Creates a form "weakly"
    /// form::set_weak("weak_form", Form::new().blue().on_white());
    ///
    /// // Sets that form "strongly"
    /// form::set("weak_form", Form::new().red().on_grey());
    ///
    /// // Even if setting the form weakly afterwards, it won't change again.
    /// form::set_weak("weak_form", Form::new().blue().underlined());
    /// ```
    ///
    /// [`form::set`]: set
    pub fn set_weak(name: impl ToString, form: Form) -> FormId {
        let name = name.to_string();
        let cloned_name = name.clone();

        match form.kind {
            FormKind::Normal => PALETTE.set_weak_form(cloned_name, form),
            FormKind::Ref(refed, style) => PALETTE.set_weak_ref(cloned_name, refed, style),
            _ => unreachable!(),
        }
    }

    /// Returns a [`Form`], given a [`FormId`].
    pub fn from_id(id: FormId) -> Form {
        PALETTE.form_from_id(id).unwrap_or_default()
    }

    /// The current main cursor, with the `"caret.main"` [`Form`].
    pub fn main_cursor() -> (Form, Option<CursorShape>) {
        PALETTE.main_cursor()
    }

    /// The current extra cursor, with the `"caret.extra"` [`Form`].
    pub fn extra_cursor() -> (Form, Option<CursorShape>) {
        PALETTE.extra_cursor()
    }

    /// Sets the main cursor's [shape].
    ///
    /// Cursors in Duat can either be a distinct [shape], or can be
    /// defined as a [`Form`], just like the rest of the styling.
    ///
    /// This is done because some UIs (like a terminal) lack the
    /// ability to show multiple cursors, so extra cursors are usually
    /// printed as solid blocks with a background color.
    ///
    /// If you want to set the cursor's color, do something like this:
    ///
    /// ```rust
    /// # use duat_core::form::{self, Form};
    /// form::set("caret.main", Form::new().black().on("#456321"));
    /// ```
    ///
    /// However, if possible, Duat will still try to use the main
    /// cursor's [shape]. If you don't want that to happen, see
    /// [`form::unset_main_cursor`].
    ///
    /// [shape]: CursorShape
    /// [`form::unset_main_cursor`]: unset_main_cursor
    pub fn set_main_cursor(shape: CursorShape) {
        PALETTE.set_main_cursor(shape);
    }

    /// Sets extra cursors's [shape]s.
    ///
    /// Cursors in Duat can either be a distinct [shape], or can be
    /// defined as a [`Form`], just like the rest of the styling.
    ///
    /// This is done because some UIs (like a terminal) lack the
    /// ability to show multiple cursors, so extra cursors are usually
    /// printed as solid blocks with a background color.
    ///
    /// If you want to set the cursor's color, do something like this:
    ///
    /// ```rust
    /// # use duat_core::form::{self, Form};
    /// form::set("caret.extra", Form::new().black().on_cyan());
    /// ```
    ///
    /// However, if possible, Duat will still try to use the main
    /// cursor's [shape]. If you don't want that to happen, see
    /// [`form::unset_extra_cursor`].
    ///
    /// [shape]: CursorShape
    /// [`form::unset_extra_cursor`]: unset_extra_cursor
    pub fn set_extra_cursor(shape: CursorShape) {
        PALETTE.set_extra_cursor(shape);
    }

    /// Removes the main cursor's [shape].
    ///
    /// By doing this, you will force Duat to draw the main cursor by
    /// use of the `"caret.main"` form.
    ///
    /// If you want to set the [shape] instead, see
    /// [`form::set_main_cursor`].
    ///
    /// [shape]: CursorShape
    /// [`form::set_main_cursor`]: set_main_cursor
    pub fn unset_main_cursor() {
        PALETTE.unset_main_cursor();
    }

    /// Removes extra cursors's [shape]s.
    ///
    /// By doing this, you will force Duat to draw the extra cursor by
    /// use of the `"caret.main"` form. Do note however that, in
    /// something like a terminal, extra cursors would never be
    /// printed as a [shape] anyways, since terminals can only
    /// print one cursor at a time.
    ///
    /// If you want to set the [shape] instead, see
    /// [`form::set_extra_cursor`].
    ///
    /// [shape]: CursorShape
    /// [`form::set_extra_cursor`]: set_extra_cursor
    pub fn unset_extra_cursor() {
        PALETTE.unset_extra_cursor();
    }

    /// Removes all cursors's [shape]s.
    ///
    /// Is the equivalent of calling [`unset_main_cursor`] and
    /// [`unset_extra_cursor`].
    ///
    /// [shape]: CursorShape
    pub fn unset_cursors() {
        PALETTE.unset_main_cursor();
        PALETTE.unset_extra_cursor();
    }

    /// Creates a [`Painter`].
    ///
    /// # Warning
    ///
    /// Only [`RawUi`] implementors should ever make use of this
    /// function, since it reads from the [`RwLock`] that is used for
    /// [`Form`] setting. If you try to set `Form`s while holding a
    /// `Painter`, you _will_ deadlock Duat, so be careful with this
    /// function. Getting `Form`s is _also_ going to cause deadlocks,
    /// since you might need to mutably borrow in order to set a
    /// default value for a form.
    ///
    /// [`RawUi`]: crate::ui::traits::RawUi
    /// [`RwLock`]: std::sync::RwLock
    pub fn painter() -> Painter {
        PALETTE.painter(super::DEFAULT_ID)
    }

    /// Creates a [`Painter`] with a widget.
    pub(crate) fn painter_with_widget<W: ?Sized + 'static>() -> Painter {
        PALETTE.painter(default_id(
            TypeId::of::<W>(),
            crate::utils::duat_name::<W>(),
        ))
    }

    /// Enables the use of this mask.
    ///
    /// A mask is essentially a remapping of [`Form`]s based on
    /// suffix, this remapping doesn't take place outside of a
    /// [`Painter`] (i.e. [`form::from_id`] won't be altered), here's
    /// how it works:
    ///
    /// ```rust
    /// # duat_core::doc_duat!(duat);
    /// use duat::prelude::*;
    ///
    /// let mut text = Text::new();
    ///
    /// // Assume that a Form with the given name exists
    /// form::set("my_form", Form::new().red().on_blue());
    ///
    /// // If I create a second Form like this one, they are separate
    /// form::set("my_form.suffix", Form::new().undercurled());
    ///
    /// text = txt!("[my_form]This text is red on blue[], [my_form.suffix]undercurled");
    ///
    /// // But if I enable the "suffix" mask that's at the end of the second Form
    /// form::enable_mask("suffix");
    ///
    /// // After calling `handle.set_mask("suffix")` on the Handle that owns this
    /// // Text, it will be equivalent to this:
    ///
    /// text = txt!("[my_form.suffix]This text is red on blue[], [my_form.suffix]undercurled");
    /// ```
    ///
    /// Masks can serve a myriad of different purposes, but here's a
    /// few:
    ///
    /// - When you want to temporarily change the [`Form`]s on a
    ///   single [`Widget`]. This is, for example, used in the
    ///   [`Notifications`] [`Widget`], which maps [`Form`]s in order
    ///   to correspond to the [`Level`] of their severity.
    /// - When you want to have [`Widget`]s change [`Form`] based on
    ///   [hooks], so you could have, for example, an `"inactive"`
    ///   mask for your [`Buffer`]s
    /// - If you want to quickly cycle through [`Form`]s in a
    ///   [`Text`], this is the most efficient way of doing that,
    ///   since it relies on static remaps, not on changing the
    ///   [`Form`]s themselves.
    ///
    /// When Duat first starts, the only available masks are
    /// `"error"`, `"warn"` and `"info"`, but you can use this
    /// function to add more of them.
    ///
    /// [`form::from_id`]: from_id
    /// [`Widget`]: crate::ui::Widget
    /// [`Notifications`]: https://docs.rs/duat/latest/duat
    /// [`Level`]: crate::context::Level
    /// [hooks]: crate::hook
    /// [`Buffer`]: crate::buffer::Buffer
    /// [`Text`]: crate::text::Text
    pub fn enable_mask(mask: impl AsRef<str> + Send + Sync + 'static) {
        let mask = mask.as_ref();
        let mut inner = PALETTE.0.write().unwrap();
        if !inner.masks.iter().any(|(m, _)| *m == mask) {
            let mut remaps: Vec<u16> = (0..inner.forms.len() as u16).collect();

            for (i, (name, ..)) in inner.forms.iter().enumerate() {
                if let Some((pref, suf)) = name.rsplit_once('.')
                    && suf == mask
                    && let Some(j) = inner.forms.iter().position(|(name, ..)| *name == pref)
                {
                    remaps[j] = i as u16;
                }
            }

            inner.masks.push((mask.to_string().leak(), remaps));
        }
    }

    /// Returns the [`MaskId`] for a given mask.
    pub(crate) fn mask_id_for(mask: &'static str) -> Option<MaskId> {
        let inner = PALETTE.0.read().unwrap();
        Some(MaskId(
            inner.masks.iter().position(|(m, _)| *m == mask)? as u32
        ))
    }

    /// Returns the [`FormId`] from the name of a [`Form`].
    ///
    /// If there is no [`Form`] with the given name, a new one is
    /// created, which will behave according to the following
    /// priority:
    ///
    /// - If the name contains a `'.'` character, it will reference
    ///   the [`Form`] whose name is a suffix up to the last `'.'`.
    ///   For example, `"Prefix.Middle.Suffix"` will reference
    ///   `"Prefix.Middle"`;
    /// - If the name does not contain a `'.'`, it will not reference
    ///   anything, having the [default `Form`];
    ///
    /// If a referenced [`Form`] does not exist, it will be added,
    /// following the same rules.
    ///
    /// # Note
    ///
    /// This is a macro because, in order to be as efficient as
    /// possible, it is better to store this value inside of a
    /// static variable, since it is guaranteed to not change. This
    /// way, you only have to figure it out once, and it is much
    /// faster than with a [`HashMap`] (how this is usually done).
    ///
    /// [`HashMap`]: std::collections::HashMap
    /// [default `Form`]: Form::new
    // SAFETY: Since _set_many always resolves to the same value, then the
    // static muts should eventually be set to their correct values, after
    // which no problems can occurr.
    // Before that point, the absolute worst thing that could happen is
    // DEFAULT_ID will be returned instead of the correct id (if the two
    // unsafe setting statements are in the wrong order for some reason),
    // but this should pretty much never happen.
    #[macro_export]
    #[doc(hidden)]
    macro_rules! __id_of__ {
        ($form:expr) => {{
            use $crate::form::{DEFAULT_ID, FormId, set_many};

            static mut WAS_SET: bool = false;
            static mut ID: FormId = DEFAULT_ID;
            if unsafe { WAS_SET } {
                unsafe { ID }
            } else {
                let name = $form.to_string();
                let id = set_many([(name, None)])[0];
                unsafe {
                    ID = id;
                    WAS_SET = true;
                }
                id
            }
        }};
    }

    /// Non static version of [`id_of!`].
    ///
    /// You should only use this if the names of the [`Form`]s in
    /// question are not known at compile time. And if that is the
    /// case, you should try to find a way to memoize around this
    /// issue (usually with something like a [`HashMap`]).
    pub fn id_of_non_static(name: impl ToString) -> FormId {
        let name = name.to_string();
        set_many([(name, None)])[0]
    }

    /// Non static version of [`id_of!`], for many [`Form`]s.
    ///
    /// You should only use this if the names of the [`Form`]s in
    /// question are not known at compile time. And if that is the
    /// case, you should try to find a way to memoize around this
    /// issue (usually with something like a [`HashMap`]).
    pub fn ids_of_non_static(names: impl IntoIterator<Item = impl ToString>) -> Vec<FormId> {
        set_many(names.into_iter().map(|n| (n.to_string(), None)))
    }

    /// Sets a bunch of [`Form`]s.
    #[doc(hidden)]
    pub fn set_many<S: AsRef<str>>(
        sets: impl IntoIterator<Item = (S, Option<Form>)>,
    ) -> Vec<FormId> {
        PALETTE.set_many(&Vec::from_iter(sets))
    }

    /// Adds a colorscheme to the list of colorschemes.
    ///
    /// A colorscheme is just a name in the form of a `&'static str`,
    /// and a list of name/[`Form`] pairs.
    ///
    /// This colorscheme can then be applied by calling
    /// [`colorscheme::set`].
    ///
    /// When you call this function, you will replace any previous
    /// colorscheme with the same name.
    ///
    /// [`colorscheme::set`]: set_colorscheme
    pub fn add_colorscheme(
        name: impl ToString,
        pairs: impl FnMut() -> Vec<(String, Form)> + Send + 'static,
    ) {
        let name = name.to_string();
        COLORSCHEMES
            .lock()
            .unwrap()
            .insert(Arc::from(name), Box::new(pairs));
    }

    /// Applies a colorscheme by its name.
    ///
    /// This colorscheme must've first been added via
    /// [`colorscheme::add`].
    ///
    /// [`colorscheme::add`]: add_colorscheme
    pub fn set_colorscheme(name: &str) {
        let name = name.to_string();
        let mut colorschemes = COLORSCHEMES.lock().unwrap();
        if let Some(pairs_fn) = colorschemes.get_mut(name.as_str()) {
            let Some(pairs) = crate::utils::catch_panic(pairs_fn) else {
                context::error!("Failed to set [a]{name}[] colorscheme");
                return;
            };

            set_many(pairs.iter().cloned().map(|(name, form)| (name, Some(form))));
            context::queue(move |pa| {
                _ = hook::trigger(pa, ColorschemeSet((name.to_string(), pairs)))
            });
        } else {
            context::error!("The colorscheme [a]{name}[] was not found");
        }
    }

    /// Gets all available colorscheme names.
    pub fn colorscheme_list() -> Vec<String> {
        let mut list = Vec::from_iter(
            COLORSCHEMES
                .lock()
                .unwrap()
                .keys()
                .map(|name| name.to_string()),
        );
        list.sort_unstable();
        list
    }

    /// Wether or not a specific [`Form`] has been set.
    pub(crate) fn exists(name: &str) -> bool {
        let palette = PALETTE.0.read().unwrap();
        palette.forms.iter().any(|(n, _)| *n == name)
    }

    /// Wether or not a specific `colorscheme` was added.
    pub(crate) fn colorscheme_exists(name: &str) -> bool {
        COLORSCHEMES.lock().unwrap().contains_key(name)
    }

    /// The name of a form, given a [`FormId`].
    pub(super) fn name_of_form(id: FormId) -> &'static str {
        PALETTE.0.read().unwrap().forms[id.0 as usize].0
    }

    /// The name of a mask, given a [`MaskId`].
    pub(super) fn name_of_mask(id: MaskId) -> &'static str {
        PALETTE.0.read().unwrap().masks[id.0 as usize].0
    }

    /// The default [`FormId`] of a `Widget`.
    fn default_id(type_id: TypeId, type_name: &'static str) -> FormId {
        static IDS: LazyLock<Mutex<HashMap<TypeId, FormId>>> = LazyLock::new(Mutex::default);
        let mut ids = IDS.lock().unwrap();

        if let Some(id) = ids.get(&type_id) {
            *id
        } else {
            let name = format!("default.{type_name}");
            let id = set_many(vec![(name, None)])[0];
            ids.insert(type_id, id);
            id
        }
    }

    type ColorschemeFn = Box<dyn FnMut() -> Vec<(String, Form)> + Send>;
}

/// An identifier of a [`Form`].
///
/// [`Builder`] part: Applies the [`Form`] destructively.
///
/// This struct is always going to point to the same form, since those
/// cannot be destroyed.
///
/// The main use for keeping these things directly is in order to
/// modify a buffer's text in an efficient manner, by adding tags
/// directly, instead of using a macro like [`txt!`]
///
/// [`txt!`]: crate::text::txt
/// [`Builder`]: crate::text::Builder
#[derive(Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct FormId(u16);

impl FormId {
    /// Creates a [`Tag`] out of this [`FormId`].
    ///
    /// In order to push a [`Form`] to the [`Text`], it needs a
    /// priority value, in order to properly sort the [`Form`]s within
    /// the same byte.
    ///
    /// [`Tag`]: crate::text::Tag
    /// [`Text`]: crate::text::Text
    pub const fn to_tag(self, prio: u8) -> FormTag {
        FormTag { id: self, priority: prio }
    }

    /// The internal id of the [`FormId`].
    ///
    /// This may be useful in certain situations.
    pub const fn to_u16(self) -> u16 {
        self.0
    }

    /// The name of this [`FormId`].
    pub fn name(self) -> &'static str {
        name_of_form(self)
    }
}

impl std::fmt::Debug for FormId {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "FormId({}: {})", self.0, name_of_form(*self))
    }
}

/// Mimics [`ContentStyle`] methods for the [`Form`] type.
macro_rules! mimic_method {
    (#[$attr:meta] $method:ident $attrib:expr) => {
        /// New [`Form`] with the
        #[$attr]
        /// attribute.
        pub const fn $method(mut self) -> Form {
            self.style.attributes = self.style.attributes.with($attrib);
            self
        }
    };
    (#[$attr:meta] $fg:ident $bg:ident $ul:ident $color:expr) => {
        /// New [`Form`] with a
        #[$attr]
        /// foreground.
        pub const fn $fg(mut self) -> Form {
            self.style.foreground_color = Some($color);
            self
        }

        /// New [`Form`] with a
        #[$attr]
        /// background.
        pub const fn $bg(mut self) -> Form {
            self.style.background_color = Some($color);
            self
        }

        /// New [`Form`] with a
        #[$attr]
        /// underlining.
        ///
        /// Do note that this feature may not be supported in all `Ui`s,
        /// for example, various terminals don't support this feature,
        /// since it is a part of the kitty protocol, and hasn't been
        /// universally accepted yet.
        ///
        /// `Ui`: crate::ui::traits::RawUi
        pub const fn $ul(mut self) -> Form {
            self.style.underline_color = Some($color);
            self
        }
    };
}

/// A style for text.
#[derive(Default, Clone, Copy)]
pub struct Form {
    /// The actual [style](ContentStyle) that is applied.
    pub style: ContentStyle,
    kind: FormKind,
}

#[rustfmt::skip]
impl Form {
    mimic_method!(/**bold*/ bold Attribute::Bold);
    mimic_method!(/**dim*/ dim Attribute::Dim);
    mimic_method!(/**italic*/ italic Attribute::Italic);
    mimic_method!(/**underlined*/ underlined Attribute::Underlined);
    mimic_method!(/**double_underlined*/ double_underlined Attribute::DoubleUnderlined);
    mimic_method!(/**undercurled*/ undercurled Attribute::Undercurled);
    mimic_method!(/**underdashed*/ underdashed Attribute::Underdashed);
    mimic_method!(/**reverse*/ reverse Attribute::Reverse);
    mimic_method!(/**crossed_out*/ crossed_out Attribute::CrossedOut);
    mimic_method!(/**black*/ black on_black underline_black Color::Black);
    mimic_method!(/**dark_grey*/ dark_grey on_dark_grey underline_dark_grey Color::DarkGrey);
    mimic_method!(/**red*/ red on_red underline_red Color::Red);
    mimic_method!(/**dark_red*/ dark_red on_dark_red underline_dark_red Color::DarkRed);
    mimic_method!(/**green*/ green on_green underline_green Color::Green);
    mimic_method!(
        /**dark_green*/ dark_green on_dark_green underline_dark_green Color::DarkGreen
    );
    mimic_method!(/**yellow*/ yellow on_yellow underline_yellow Color::Yellow);
    mimic_method!(
        /**dark_yellow*/ dark_yellow on_dark_yellow underline_dark_yellow Color::DarkYellow
    );
    mimic_method!(/**blue*/ blue on_blue underline_blue Color::Blue);
    mimic_method!(/**dark_blue*/ dark_blue on_dark_blue underline_dark_blue Color::DarkBlue);
    mimic_method!(/**magenta*/ magenta on_magenta underline_magenta Color::Magenta);
    mimic_method!(
        /**dark_magenta*/ dark_magenta on_dark_magenta underline_dark_magenta Color::DarkMagenta
    );
    mimic_method!(/**cyan*/ cyan on_cyan underline_cyan Color::Cyan);
    mimic_method!(/**dark_cyan*/ dark_cyan on_dark_cyan underline_dark_cyan Color::DarkCyan);
    mimic_method!(/**white*/ white on_white underline_white Color::White);
    mimic_method!(/**grey*/ grey on_grey underline_grey Color::Grey);
}

impl Form {
    /// Returns a new `Form` with a default style.
    pub const fn new() -> Form {
        Self {
            style: default_style(),
            kind: FormKind::Normal,
        }
    }

    /// A `Form` value, from the name of the form.
    pub fn of(form_name: impl AsRef<str>) -> Self {
        let mut form = from_id(id_of_non_static(form_name.as_ref()));
        form.kind = FormKind::Normal;
        form
    }

    /// A `Form` that mimics another.
    ///
    /// This is useful if you want `Form`s to automatically change if
    /// the mimicked one does.
    ///
    /// Normally, this is done automatically. For example, if you
    /// define a `Form` "foo.bar.baz" through [`form::id_of!`], or
    /// within the [`txt!`] macro, then that `Form` will be set to
    /// "mimic" "foo.bar". That is, if "foo.bar" changes, so will
    /// "foo.bar.baz".
    ///
    /// This function lets you manually do that.
    ///
    /// [`form::id_of!`]: id_of
    /// [`txt!`]: crate::txt
    pub fn mimic(form_name: impl AsRef<str>) -> Self {
        let id = id_of_non_static(form_name.as_ref());
        let mut form = from_id(id);
        form.kind = FormKind::Ref(id.0, default_style());
        form
    }

    /// Sets the [`Reset`] attribute.
    ///
    /// In Duat, the [`Reset`] attribute should remove only other
    /// [`Attribute`]s, not any of the colors in use.
    ///
    /// [`Reset`]: Attribute::Reset
    pub const fn reset(mut self) -> Self {
        self.style.attributes = self.style.attributes.with(Attribute::Reset);

        if let FormKind::Ref(_, style) = &mut self.kind {
            style.attributes = style.attributes.with(Attribute::Reset);
        }

        self
    }

    /// Sets the color of the foreground.
    ///
    /// This function accepts two color formats:
    ///
    /// - A hexcode, like `"#abcdef"`, capitalization is ignored;
    /// - Three hsl values, like `"hsl {hue} {sat} {lit}"`, where
    ///   {hue}, {sat} and {lit} can either be a number from `0..255`,
    ///   or a percentage, followed by `'%'`, e.g. `"hsl 234 50% 42"`.
    ///
    /// If this `Form` was created via [`Form::mimic`], then the other
    /// attributes will change as the mimicked color does, but the
    /// foreground won't.
    #[track_caller]
    pub const fn with(mut self, color: &str) -> Self {
        self.style.foreground_color = match str_to_color(color) {
            Ok(color) => Some(color),
            Err(_) => panic!("Ill-formed color"),
        };

        if let FormKind::Ref(_, style) = &mut self.kind {
            style.foreground_color = self.style.foreground_color;
        }

        self
    }

    /// Sets the color of the background.
    ///
    /// This function accepts two color formats:
    ///
    /// - A hexcode, like `"#abcdef"`, capitalization is ignored;
    /// - Three hsl values, like `"hsl {hue} {sat} {lit}"`, where
    ///   {hue}, {sat} and {lit} can either be a number from `0..255`,
    ///   or a percentage, followed by `'%'`, e.g. `"hsl 234 50% 42"`.
    ///
    /// If this `Form` was created via [`Form::mimic`], then the other
    /// attributes will change as the mimicked color does, but the
    /// background won't.
    #[track_caller]
    pub const fn on(mut self, color: &str) -> Self {
        self.style.background_color = match str_to_color(color) {
            Ok(color) => Some(color),
            Err(_) => panic!("Ill-formed color"),
        };

        if let FormKind::Ref(_, style) = &mut self.kind {
            style.background_color = self.style.background_color;
        }

        self
    }

    /// Sets the color of the foreground and background.
    ///
    /// You can use this if you want to "hide" the text as if it were
    /// just one solid block of one color.
    ///
    /// This function accepts two color formats:
    ///
    /// - A hexcode, like `"#abcdef"`, capitalization is ignored;
    /// - Three hsl values, like `"hsl {hue} {sat} {lit}"`, where
    ///   {hue}, {sat} and {lit} can either be a number from `0..255`,
    ///   or a percentage, followed by `'%'`, e.g. `"hsl 234 50% 42"`.
    ///
    /// If this `Form` was created via [`Form::mimic`], then the other
    /// attributes will change as the mimicked color does, but the
    /// background and foreground won't.
    #[track_caller]
    pub const fn with_on(mut self, color: &str) -> Self {
        let color = match str_to_color(color) {
            Ok(color) => color,
            Err(_) => panic!("Ill-formed color"),
        };

        self.style.background_color = Some(color);
        self.style.foreground_color = Some(color);

        if let FormKind::Ref(_, style) = &mut self.kind {
            style.background_color = self.style.background_color;
            style.foreground_color = self.style.foreground_color;
        }

        self
    }

    /// Sets the color of underlines.
    ///
    /// Note that this doesn't actually make the underline show up, it
    /// merely colors one that is set via a command like
    /// [`Form::underlined`].
    ///
    /// This function accepts two color formats:
    ///
    /// - A hexcode, like `"#abcdef"`, capitalization is ignored;
    /// - Three hsl values, like `"hsl {hue} {sat} {lit}"`, where
    ///   {hue}, {sat} and {lit} can either be a number from `0..255`,
    ///   or a percentage, followed by `'%'`, e.g. `"hsl 234 50% 42"`.
    ///
    /// If this `Form` was created via [`Form::mimic`], then the other
    /// attributes will change as the mimicked color does, but the
    /// underline color won't.
    #[track_caller]
    pub fn underline(mut self, color: &str) -> Self {
        self.style.underline_color = match str_to_color(color) {
            Ok(color) => Some(color),
            Err(_) => panic!("Ill-formed color"),
        };

        if let FormKind::Ref(_, style) = &mut self.kind {
            style.underline_color = self.style.underline_color;
        }

        self
    }

    /// Interpolate the foreground, background, and underline colors
    /// of this `Form` with those of another.
    ///
    /// The `factor` argument is a percentage bias towards this form,
    /// that is, a final color would be calculated like this:
    ///
    /// ```
    /// # let (mut fg_final, fg_self, fg_other, factor) = (None::<usize>, None, None::<usize>, 50);
    /// fg_final = if let Some(fg_other) = fg_other
    ///     && let Some(fg_self) = fg_self
    /// {
    ///     Some((fg_self * factor + fg_other * (100 - factor)) / 100)
    /// } else {
    ///     fg_self
    /// };
    /// ```
    ///
    /// If any of the attributes was set to a terminal color (i.e.,
    /// not RGB), then it will be ignored for the purposes of this
    /// function.
    ///
    /// If this `Form` was created via [`Form::mimic`], then the other
    /// attributes will change as the mimicked color does, but the
    /// underline color won't.
    #[track_caller]
    pub const fn interpolate(mut self, other: Self, factor: u8) -> Self {
        const fn interpolate(color: Color, other: Color, factor: u8) -> Color {
            if let (Color::Rgb { r, g, b }, Color::Rgb { r: or, g: og, b: ob }) = (color, other) {
                let factor = factor as usize;
                Color::Rgb {
                    r: ((r as usize * factor + or as usize * (100 - factor)) / 100) as u8,
                    g: ((g as usize * factor + og as usize * (100 - factor)) / 100) as u8,
                    b: ((b as usize * factor + ob as usize * (100 - factor)) / 100) as u8,
                }
            } else {
                color
            }
        }

        assert!(factor <= 100, "factor must be between 0 and 100");

        if let (Some(other_fg), Some(self_fg)) = (other.fg(), &mut self.style.foreground_color) {
            *self_fg = interpolate(*self_fg, other_fg, factor);
            if let FormKind::Ref(_, style) = &mut self.kind {
                style.foreground_color = self.style.foreground_color;
            }
        }
        if let (Some(other_bg), Some(self_bg)) = (other.bg(), &mut self.style.background_color) {
            *self_bg = interpolate(*self_bg, other_bg, factor);
            if let FormKind::Ref(_, style) = &mut self.kind {
                style.background_color = self.style.background_color;
            }
        }
        if let (Some(other_ul), Some(self_ul)) = (other.ul(), &mut self.style.underline_color) {
            *self_ul = interpolate(*self_ul, other_ul, factor);
            if let FormKind::Ref(_, style) = &mut self.kind {
                style.underline_color = self.style.underline_color;
            }
        }

        self
    }

    /// The foreground color.
    const fn fg(&self) -> Option<Color> {
        self.style.foreground_color
    }

    /// The background color.
    const fn bg(&self) -> Option<Color> {
        self.style.background_color
    }

    /// The foreground color.
    const fn ul(&self) -> Option<Color> {
        self.style.underline_color
    }

    /// The attributes.
    const fn attrs(&self) -> Attributes {
        self.style.attributes
    }
}

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

impl Eq for Form {}

/// The list of forms to be used when rendering.
///
/// ONLY MEANT TO BE ACCESSED BY DUAT AND DUAT-CORE.
#[derive(Debug)]
#[doc(hidden)]
pub struct Palette(RwLock<InnerPalette>);

impl Palette {
    /// Returns a new instance of [`Palette`].
    fn new() -> Self {
        let main_cursor = Some(CursorShape::DefaultUserShape);
        Self(RwLock::new(InnerPalette {
            main_cursor,
            extra_cursor: main_cursor,
            forms: BASE_FORMS.iter().map(|(str, form)| (*str, *form)).collect(),
            masks: vec![("", (0..BASE_FORMS.len() as u16).collect())],
        }))
    }

    /// Sets a [`Form`].
    fn set_form(&self, name: impl AsRef<str>, form: Form) -> FormId {
        let name = name.as_ref();
        self.0.write().unwrap().set_form(name, form)
    }

    /// Sets a [`Form`] "weakly".
    fn set_weak_form(&self, name: impl AsRef<str>, form: Form) -> FormId {
        let name = name.as_ref();
        self.0.write().unwrap().set_weak_form(name, form)
    }

    /// Makes a [`Form`] reference another.
    fn set_ref(&self, name: impl AsRef<str>, refed: u16, override_style: ContentStyle) -> FormId {
        let name = name.as_ref();
        self.0.write().unwrap().set_ref(name, refed, override_style)
    }

    /// Makes a [`Form`] reference another "weakly".
    fn set_weak_ref(
        &self,
        name: impl AsRef<str>,
        refed: u16,
        override_style: ContentStyle,
    ) -> FormId {
        let name = name.as_ref();
        let mut inner_palette = self.0.write().unwrap();
        inner_palette.set_weak_ref(name, refed, override_style)
    }

    /// Sets many [`Form`]s.
    fn set_many<S: AsRef<str>>(&self, sets: &[(S, Option<Form>)]) -> Vec<FormId> {
        let mut inner = self.0.write().unwrap();
        let mut ids = Vec::new();

        for (name, form) in sets {
            let Some(form) = *form else {
                let (idx, _) = position_and_form(&mut inner.forms, name);
                ids.push(FormId(idx as u16));
                continue;
            };

            ids.push(match form.kind {
                FormKind::Normal => inner.set_form(name.as_ref(), form),
                FormKind::Ref(refed, style) => inner.set_ref(name.as_ref(), refed, style),
                FormKind::Weakest => inner.set_weak_form(name.as_ref(), form),
                FormKind::WeakestRef(refed, style) => {
                    inner.set_weak_ref(name.as_ref(), refed, style)
                }
            });
        }

        ids
    }

    /// Returns a form, given a [`FormId`].
    fn form_from_id(&self, id: FormId) -> Option<Form> {
        let inner = self.0.read().unwrap();
        inner.forms.get(id.0 as usize).map(|(_, form)| *form)
    }

    /// The [`Form`] and [`CursorShape`] of the main cursor.
    fn main_cursor(&self) -> (Form, Option<CursorShape>) {
        let form = self.form_from_id(M_CAR_ID).unwrap();
        (form, self.0.read().unwrap().main_cursor)
    }

    /// The [`Form`] and [`CursorShape`] of extra cursors.
    fn extra_cursor(&self) -> (Form, Option<CursorShape>) {
        let form = self.form_from_id(E_CAR_ID).unwrap();
        (form, self.0.read().unwrap().extra_cursor)
    }

    /// Sets the [`CursorShape`] of the main cursor.
    fn set_main_cursor(&self, shape: CursorShape) {
        self.0.write().unwrap().main_cursor = Some(shape);
        sender().send(DuatEvent::FormChange);
    }

    /// Sets the [`CursorShape`] of extra cursors.
    fn set_extra_cursor(&self, shape: CursorShape) {
        self.0.write().unwrap().extra_cursor = Some(shape);
        sender().send(DuatEvent::FormChange);
    }

    /// Unsets the [`CursorShape`] of the main cursor.
    fn unset_main_cursor(&self) {
        self.0.write().unwrap().main_cursor = None;
        sender().send(DuatEvent::FormChange);
    }

    /// Unsets the [`CursorShape`] of the extra cursors.
    fn unset_extra_cursor(&self) {
        self.0.write().unwrap().extra_cursor = None;
        sender().send(DuatEvent::FormChange);
    }

    /// Returns a [`Painter`].
    fn painter(&'static self, default_id: FormId) -> Painter {
        let inner = self.0.read().unwrap();

        let default = inner
            .forms
            .get(default_id.0 as usize)
            .map(|(_, f)| *f)
            .unwrap_or_default();

        Painter {
            inner,
            applied_masks: vec![0],
            default: (default, default_id),
            forms: Vec::new(),
            set_fg: true,
            set_bg: true,
            set_ul: true,
            reset_attrs: true,
            prev_style: None,
        }
    }
}

struct InnerPalette {
    main_cursor: Option<CursorShape>,
    extra_cursor: Option<CursorShape>,
    forms: Vec<(&'static str, Form)>,
    masks: Vec<(&'static str, Vec<u16>)>,
}

impl InnerPalette {
    /// Sets a [`Form`].
    fn set_form(&mut self, name: &str, form: Form) -> FormId {
        let (idx, _) = position_and_form(&mut self.forms, name);

        self.forms[idx].1 = form;

        for (referee, override_style) in refs_of(self, idx) {
            mimic_form_to_referee(&mut self.forms[referee].1, form, override_style);
        }

        sender().send(DuatEvent::FormChange);

        mask_form(name, idx, self);

        let form_set = FormSet((self.forms[idx].0, FormId(idx as u16), form));
        context::queue(move |pa| _ = hook::trigger(pa, form_set));

        FormId(idx as u16)
    }

    /// Sets a [`Form`] "weakly".
    fn set_weak_form(&mut self, name: &str, form: Form) -> FormId {
        let (idx, _) = position_and_form(&mut self.forms, name);

        let (_, f) = &mut self.forms[idx];
        if let FormKind::Weakest | FormKind::WeakestRef(..) = f.kind {
            *f = form;
            f.kind = FormKind::Normal;

            sender().send(DuatEvent::FormChange);
            for (referee, override_style) in refs_of(self, idx) {
                mimic_form_to_referee(&mut self.forms[referee].1, form, override_style);
            }

            mask_form(name, idx, self);
        }

        FormId(idx as u16)
    }

    /// Makes a [`Form`] reference another.
    fn set_ref(&mut self, name: &str, refed: u16, override_style: ContentStyle) -> FormId {
        let (_, form) = self.forms[refed as usize];
        let (idx, _) = position_and_form(&mut self.forms, name);

        self.forms[idx].1 = form;
        for (referee, override_style) in refs_of(self, idx) {
            mimic_form_to_referee(&mut self.forms[referee].1, form, override_style);
        }

        // If it would be circular, we just don't reference anything.
        if would_be_circular(self, idx, refed as usize) {
            self.forms[idx].1.kind = FormKind::Normal;
        } else {
            self.forms[idx].1.kind = FormKind::Ref(refed, override_style);
        }

        sender().send(DuatEvent::FormChange);

        mask_form(name, idx, self);
        let form_set = FormSet((self.forms[idx].0, FormId(idx as u16), form));
        context::queue(move |pa| _ = hook::trigger(pa, form_set));

        FormId(idx as u16)
    }

    /// Makes a [`Form`] reference another "weakly".
    fn set_weak_ref(&mut self, name: &str, refed: u16, override_style: ContentStyle) -> FormId {
        let (_, form) = self.forms[refed as usize];
        let (idx, _) = position_and_form(&mut self.forms, name);

        let (_, f) = &mut self.forms[idx];
        if let FormKind::Weakest | FormKind::WeakestRef(..) = f.kind {
            *f = form;
            f.kind = FormKind::WeakestRef(refed, override_style);

            sender().send(DuatEvent::FormChange);

            for (referee, override_style) in refs_of(self, idx) {
                mimic_form_to_referee(&mut self.forms[referee].1, form, override_style);
            }

            mask_form(name, idx, self);
        }

        FormId(idx as u16)
    }
}

fn mimic_form_to_referee(referee: &mut Form, form: Form, override_style: ContentStyle) {
    referee.style = form.style;
    referee.style.attributes.extend(override_style.attributes);
    if let Some(color) = override_style.foreground_color {
        referee.style.foreground_color = Some(color);
    }
    if let Some(color) = override_style.background_color {
        referee.style.background_color = Some(color);
    }
    if let Some(color) = override_style.underline_color {
        referee.style.underline_color = Some(color);
    }
}

/// If setting a form with an existing mask suffix, mask its prefix
fn mask_form(name: &str, form_i: usize, inner: &mut InnerPalette) {
    if inner.masks[0].1.len() < inner.forms.len() {
        for (_, remaps) in inner.masks.iter_mut() {
            remaps.extend(remaps.len() as u16..inner.forms.len() as u16);
        }
    }

    if let Some((pref, mask)) = name.rsplit_once(".")
        && let Some((_, remaps)) = inner.masks.iter_mut().find(|(m, _)| *m == mask)
        && let Some(j) = inner.forms.iter().position(|(name, ..)| *name == pref)
    {
        remaps[j] = form_i as u16;
    }
}

/// A struct to create [`Form`]s from [`RawTag`] in a [`Text`].
///
/// This [`Painter`] not only prints the [`Form`]s in the [`Text`],
/// but within it there is also a "mask". This mask will remap
/// [`Form`]s based on suffix, like in the following example:
///
/// ```rust
/// # duat_core::doc_duat!(duat);
/// use duat::prelude::*;
///
/// let mut text = Text::new();
///
/// // Assume that a Form with the given name exists
/// form::set("my_form", Form::new().red().on_blue());
///
/// // If I create a second Form like this one, they are separate
/// form::set("my_form.suffix", Form::new().undercurled());
///
/// text = txt!("[my_form]This text is red on blue[], [my_form.suffix]undercurled");
///
/// // But if I enable the "suffix" mask that's at the end of the second Form
/// form::enable_mask("suffix");
///
/// // After calling `handle.set_mask("suffix")` on the Handle that owns this
/// // Text, it will be equivalent to this:
///
/// text = txt!("[my_form.suffix]This text is red on blue[], [my_form.suffix]undercurled");
/// ```
///
/// Masks can serve a myriad of different purposes, but here's a
/// few:
///
/// - When you want to temporarily change the [`Form`]s on a single
///   [`Widget`]. This is, for example, used in the [`Notifications`]
///   [`Widget`], which maps [`Form`]s in order to correspond to the
///   [`Level`] of their severity.
/// - When you want to have [`Widget`]s change [`Form`] based on
///   [hooks], so you could have, for example, an `"inactive"` mask
///   for your [`Buffer`]s
/// - If you want to quickly cycle through [`Form`]s in a [`Text`],
///   this is the most efficient way of doing that, since it relies on
///   static remaps, not on changing the [`Form`]s themselves.
///
/// Do note that no suffix, except `"error"`, `"warn"` and
/// `"info"` is a mask when Duat starts. In order to enable more
/// masks, see [`enable_mask`].
///
/// [`Widget`]: crate::ui::Widget
/// [`Notifications`]: https://docs.rs/duat/latest/duat
/// [`Level`]: crate::context::Level
/// [hooks]: crate::hook
/// [`Buffer`]: crate::buffer::Buffer
/// [`Text`]: crate::text::Text
///
/// [`RawTag`]: crate::text::RawTag
/// [`Text`]: crate::text::Text
pub struct Painter {
    inner: RwLockReadGuard<'static, InnerPalette>,
    applied_masks: Vec<usize>,
    default: (Form, FormId),
    forms: Vec<(Form, FormId, u8)>,
    set_fg: bool,
    set_bg: bool,
    set_ul: bool,
    reset_attrs: bool,
    prev_style: Option<ContentStyle>,
}

impl Painter {
    /// Applies the `Form` with the given `id` and returns the result,
    /// given previous triggers.
    ///
    /// Will return a [`Form`] _relative_ to what the previous
    /// [`Form`] was, that is, if the new [`Form`] doesn't include a
    /// background, its combination with the other [`Form`]s also
    /// won't, since it wasn't changed.
    #[inline(always)]
    pub fn apply(&mut self, id: FormId, prio: u8) {
        let forms = &self.inner.forms;

        let form = get_form_for(id, &self.applied_masks, forms, &self.inner.masks);

        let gt = |(.., p): &&(_, _, u8)| *p > prio;
        let i = self.forms.len() - self.forms.iter().rev().take_while(gt).count();
        self.forms.insert(i, (form, id, prio));

        self.set_fg |= form.fg().is_some();
        self.set_bg |= form.bg().is_some();
        self.set_ul |= form.ul().is_some();
        self.reset_attrs |= form.attrs().has(Attribute::Reset);
    }

    /// Removes the [`Form`] with the given `id` and returns the
    /// result, given previous triggers.
    #[inline(always)]
    pub fn remove(&mut self, id: FormId) {
        let mut applied_forms = self.forms.iter().enumerate();
        if let Some((i, &(form, ..))) = applied_forms.rfind(|(_, (_, lhs, _))| *lhs == id) {
            self.forms.remove(i);

            self.set_fg |= form.fg().is_some();
            self.set_bg |= form.bg().is_some();
            self.set_ul |= form.ul().is_some();
            self.reset_attrs |= !form.attrs().is_empty();
        };
    }

    /// Removes all [`Form`]s except the default one.
    ///
    /// Should be used when a [`ResetState`] part is printed.
    ///
    /// [`ResetState`]: crate::text::TextPart::ResetState
    #[inline(always)]
    pub fn reset(&mut self) -> ContentStyle {
        self.forms.clear();
        self.absolute_style()
    }

    /// Generates the absolute [`ContentStyle`] to be set.
    ///
    /// This function assumes that all previous styling is not being
    /// carried over, i.e., we're styling from scratch.
    #[inline(always)]
    pub fn absolute_style(&self) -> ContentStyle {
        let mut style = self.default.0.style;

        for &(form, ..) in &self.forms {
            style.foreground_color = form.fg().or(style.foreground_color);
            style.background_color = form.bg().or(style.background_color);
            style.underline_color = form.ul().or(style.underline_color);
            style.attributes = if form.attrs().has(Attribute::Reset) {
                form.attrs()
            } else {
                form.attrs() | style.attributes
            }
        }

        style
    }

    /// Generates the relative [`ContentStyle`] to be set.
    ///
    /// This function assumes that previously printed styles are being
    /// carried over, influencing this one.
    ///
    /// You should strive to use this function more than
    /// [`absolute_style`], since it "theoretically" should be less
    /// work to change just one aspect of the style, rather than
    /// replacing the whole thing.
    ///
    /// [`absolute_style`]: Painter::absolute_style
    #[inline(always)]
    pub fn relative_style(&mut self) -> Option<ContentStyle> {
        let abs_style = self.absolute_style();
        let mut style = abs_style;

        if style.attributes.has(Attribute::Reset) || self.reset_attrs {
            style.attributes.set(Attribute::Reset);
        // Only when we are certain that all forms have been
        // printed, can we cull unnecessary colors for efficiency
        // (this happens most of the time).
        } else {
            style.foreground_color = self
                .set_fg
                .then_some(style.foreground_color.unwrap_or(Color::Reset))
                .filter(|fg| Some(*fg) != self.prev_style.and_then(|s| s.foreground_color));
            style.background_color = self
                .set_bg
                .then_some(style.background_color.unwrap_or(Color::Reset))
                .filter(|bg| Some(*bg) != self.prev_style.and_then(|s| s.background_color));
            style.underline_color = self
                .set_ul
                .then_some(style.underline_color.unwrap_or(Color::Reset))
                .filter(|ul| Some(*ul) != self.prev_style.and_then(|s| s.underline_color));
        }

        self.set_fg = false;
        self.set_bg = false;
        self.set_ul = false;
        self.reset_attrs = false;

        if let Some(prev_style) = self.prev_style.replace(abs_style) {
            (style != prev_style && style != Default::default()).then_some(style)
        } else {
            Some(style)
        }
    }

    /// Makes it so the next call to [`relative_style`] returns the
    /// same thing as a call to [`absolute_style`].
    ///
    /// [`relative_style`]: Self::relative_style
    /// [`absolute_style`]: Self::absolute_style
    pub fn reset_prev_style(&mut self) {
        self.prev_style = None;
        self.set_fg = true;
        self.set_bg = true;
        self.set_ul = true;
        self.reset_attrs = true;
    }

    /// Applies the `"caret.main"` [`Form`].
    #[inline(always)]
    pub fn apply_main_selection(&mut self, is_caret: bool, start_range: bool) {
        if is_caret {
            self.apply(M_CAR_ID, 150);
        }
        if start_range {
            self.apply(M_SEL_ID, 145);
        }
    }

    /// Removes the `"caret.main"` [`Form`].
    #[inline(always)]
    pub fn remove_main_selection(&mut self, is_caret: bool, end_range: bool) {
        if is_caret {
            self.remove(M_CAR_ID);
        }
        if end_range {
            self.remove(M_SEL_ID);
        }
    }

    /// Applies the `"caret.extra"` [`Form`].
    #[inline(always)]
    pub fn apply_extra_selection(&mut self, is_caret: bool, start_range: bool) {
        if is_caret {
            self.apply(E_CAR_ID, 149);
        }
        if start_range {
            self.apply(E_SEL_ID, 144);
        }
    }

    /// Removes the `"caret.extra"` [`Form`].
    #[inline(always)]
    pub fn remove_extra_selection(&mut self, is_caret: bool, end_range: bool) {
        if is_caret {
            self.remove(E_CAR_ID);
        }
        if end_range {
            self.remove(E_SEL_ID);
        }
    }

    /// Applies a given mask, mapping all [`Form`]s.
    ///
    /// This will also remap all currently applied `Form`s, so you
    /// should reprint the style.
    pub fn apply_mask(&mut self, id: MaskId) {
        self.reset_prev_style();
        self.applied_masks.push(id.0 as usize);

        let forms = &self.inner.forms;

        for (form, id) in std::iter::once((&mut self.default.0, &mut self.default.1))
            .chain(self.forms.iter_mut().map(|(form, id, _)| (form, id)))
        {
            *form = get_form_for(*id, &self.applied_masks, forms, &self.inner.masks);
        }
    }

    /// Removes a given mask, unmapping all [`Form`]s.
    ///
    /// This will also remap all currently applied `Form`s, so you
    /// should reprint the style.
    pub fn remove_mask(&mut self, id: MaskId) {
        self.reset_prev_style();
        self.applied_masks.retain(|idx| *idx != id.0 as usize);

        let forms = &self.inner.forms;

        for (form, id) in std::iter::once((&mut self.default.0, &mut self.default.1))
            .chain(self.forms.iter_mut().map(|(form, id, _)| (form, id)))
        {
            *form = get_form_for(*id, &self.applied_masks, forms, &self.inner.masks);
        }
    }

    /// The [`Form`] "caret.extra", and its shape.
    pub fn main_cursor(&self) -> Option<CursorShape> {
        self.inner.main_cursor
    }

    /// The [`Form`] "caret.extra", and its shape.
    pub fn extra_cursor(&self) -> Option<CursorShape> {
        self.inner.extra_cursor
    }

    /// The `"default"` form's [`Form`].
    pub fn get_default(&self) -> Form {
        self.default.0
    }
}

/// An enum that helps in the modification of forms.
#[derive(Default, Clone, Copy)]
enum FormKind {
    #[default]
    Normal,
    Ref(u16, ContentStyle),
    Weakest,
    WeakestRef(u16, ContentStyle),
}

fn get_form_for(
    id: FormId,
    applied_masks: &[usize],
    forms: &[(&str, Form)],
    masks: &[(&'static str, Vec<u16>)],
) -> Form {
    // SAFETY: When you create a form, it gets indexed, and never becomes
    // unindexed, so this should be fine.
    unsafe {
        applied_masks
            .iter()
            .rev()
            .find_map(|mask_id| {
                let (_, mask) = masks.get(*mask_id).unwrap_unchecked();
                let idx = mask
                    .get(id.0 as usize)
                    .copied()
                    .filter(|idx| *idx != id.0)?;
                Some(forms.get(idx as usize).unwrap_unchecked().1)
            })
            .unwrap_or(forms.get(id.0 as usize).unwrap_unchecked().1)
    }
}

/// The position of each form that eventually references the `n`th.
fn refs_of(inner: &InnerPalette, refed: usize) -> Vec<(usize, ContentStyle)> {
    let mut refs = Vec::new();
    for (i, (_, form)) in inner.forms.iter().enumerate() {
        if let FormKind::Ref(id, style) | FormKind::WeakestRef(id, style) = form.kind
            && id as usize == refed
        {
            refs.push((i, style));
            refs.extend(refs_of(inner, i));
        }
    }
    refs
}

/// If form references would eventually lead to a loop.
fn would_be_circular(inner: &InnerPalette, referee: usize, refed: usize) -> bool {
    if let FormKind::Ref(id, _) | FormKind::WeakestRef(id, _) = inner.forms[refed].1.kind {
        match id as usize == referee {
            true => true,
            false => would_be_circular(inner, referee, id as usize),
        }
    } else {
        false
    }
}

fn position_and_form(
    forms: &mut Vec<(&'static str, Form)>,
    name: impl AsRef<str>,
) -> (usize, Form) {
    let name = name.as_ref();
    if let Some((i, (_, form))) = forms.iter().enumerate().find(|(_, (lhs, _))| *lhs == name) {
        (i, *form)
    } else if let Some((refed, _)) = name.rsplit_once('.') {
        let (i, mut form) = position_and_form(forms, refed);
        form.kind = FormKind::WeakestRef(i as u16, default_style());
        forms.push((name.to_string().leak(), form));
        (forms.len() - 1, form)
    } else {
        let mut form = Form::new();
        form.kind = FormKind::Weakest;
        forms.push((name.to_string().leak(), form));
        (forms.len() - 1, form)
    }
}

/// Converts a string to a color, supporst hex, RGB and HSL.
const fn str_to_color(str: &str) -> std::result::Result<Color, &'static str> {
    const fn strip_prefix<'a>(prefix: &str, str: &'a str) -> Option<&'a str> {
        let prefix = prefix.as_bytes();

        let mut i = 0;
        while i < prefix.len() {
            if str.as_bytes()[i] != prefix[i] {
                return None;
            }
            i += 1;
        }

        Some(str.split_at(prefix.len()).1)
    }
    const fn strip_suffix<'a>(suffix: &str, str: &'a str) -> Option<&'a str> {
        let prefix = suffix.as_bytes();

        let mut i = str.len() - 1;
        while i >= str.len() - prefix.len() {
            if str.as_bytes()[i] != prefix[i - (str.len() - prefix.len())] {
                return None;
            }
            i += 1;
        }

        Some(str.split_at(str.len() - suffix.len()).0)
    }
    const fn split_space(str: &str) -> Option<(&str, &str)> {
        if str.is_empty() {
            return None;
        }

        let mut i = 0;
        while i < str.len() {
            if str.as_bytes()[i] == b' ' {
                break;
            }
            i += 1;
        }

        let (cut, rest) = str.split_at(i);
        let (_, rest) = rest.split_at(if rest.is_empty() { 0 } else { 1 });
        Some((cut, rest))
    }
    const fn hue_to_rgb(p: f32, q: f32, mut t: f32) -> f32 {
        t = if t < 0.0 { t + 1.0 } else { t };
        t = if t > 1.0 { t - 1.0 } else { t };
        if t < 1.0 / 6.0 {
            p + (q - p) * 6.0 * t
        } else if t < 1.0 / 2.0 {
            q
        } else if t < 2.0 / 3.0 {
            p + (q - p) * (2.0 / 3.0 - t) * 6.0
        } else {
            p
        }
    }

    // Expects "#{red:x}{green:x}{blue:x}"
    if let Some(hex) = strip_prefix("#", str) {
        let total = match u32::from_str_radix(hex, 16) {
            Ok(total) if hex.len() == 6 => total,
            _ => return Err("Hexcode does not contain 6 hex values"),
        };
        let r = (total >> 16) as u8;
        let g = (total >> 8) as u8;
        let b = total as u8;

        Ok(Color::Rgb { r, g, b })
    // Expects "hsl {hue%?} {saturation%?} {lightness%?}"
    } else if let Some(mut hsl) = strip_prefix("hsl ", str) {
        let mut values = [0.0, 0.0, 0.0];
        let mut i = 0;
        while i < values.len() {
            if let Some((cut, rest)) = split_space(hsl) {
                hsl = rest;
                let (num, div) = match strip_suffix("%", cut) {
                    Some(perc) => (perc, 100),
                    None => (cut, 255),
                };
                values[i] = match u8::from_str_radix(num, 10) {
                    Ok(value) if value <= div => value as f32 / div as f32,
                    _ => return Err("Hsl format property could not be parsed"),
                }
            } else {
                return Err("Missing value in hsl format");
            }
            i += 1;
        }
        let [hue, sat, lit] = values;

        let (r, g, b) = if sat == 0.0 {
            (lit, lit, lit)
        } else {
            let q = if lit < 0.5 {
                lit * (1.0 + sat)
            } else {
                lit + sat - lit * sat
            };
            let p = 2.0 * lit - q;
            let r = hue_to_rgb(p, q, hue + 1.0 / 3.0);
            let g = hue_to_rgb(p, q, hue);
            let b = hue_to_rgb(p, q, hue - 1.0 / 3.0);
            (r, g, b)
        };

        // + 0.5 because `as` rounds floats down.
        let r = (0.5 + r * 255.0) as u8;
        let g = (0.5 + g * 255.0) as u8;
        let b = (0.5 + b * 255.0) as u8;
        Ok(Color::Rgb { r, g, b })
    } else {
        Err("Color format was not recognized")
    }
}

/// Returns the default [`ContentStyle`]..
const fn default_style() -> ContentStyle {
    ContentStyle {
        foreground_color: None,
        background_color: None,
        underline_color: None,
        attributes: Attributes::none(),
    }
}

impl std::fmt::Debug for Form {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        struct DebugColor(Option<Color>);
        impl std::fmt::Debug for DebugColor {
            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
                match self.0 {
                    Some(Color::Rgb { r, g, b }) => write!(f, "Some(Rgb({r}, {g}, {b}))"),
                    Some(Color::AnsiValue(ansi)) => write!(f, "Some(Ansi({ansi}))"),
                    Some(color) => write!(f, "Some({color:?})"),
                    None => f.write_str("None"),
                }
            }
        }

        struct DebugAttributes(Attributes);
        impl std::fmt::Debug for DebugAttributes {
            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
                if self.0.is_empty() {
                    f.write_str("None")
                } else {
                    let mut is_first = true;
                    for attr in Attribute::iterator() {
                        if self.0.has(attr) {
                            if !is_first {
                                f.write_str(" | ")?;
                            }
                            is_first = false;
                            write!(f, "{attr:?}")?;
                        }
                    }
                    Ok(())
                }
            }
        }

        f.debug_struct("Form")
            .field("fg", &DebugColor(self.style.foreground_color))
            .field("bg", &DebugColor(self.style.background_color))
            .field("ul", &DebugColor(self.style.underline_color))
            .field("attr", &DebugAttributes(self.style.attributes))
            .finish()
    }
}

impl std::fmt::Debug for InnerPalette {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        struct DebugForms<'a>(&'a [(&'static str, Form)]);
        impl std::fmt::Debug for DebugForms<'_> {
            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
                if f.alternate() {
                    f.write_str("[\n")?;
                    let max = self.0.len().ilog10() as usize + 3;
                    for (n, (name, form)) in self.0.iter().enumerate() {
                        let num = format!("{n}:");
                        writeln!(f, "{num:<max$}({name}, {form:#?})")?;
                    }
                    f.write_str("]")
                } else {
                    write!(f, "{:?}", self.0)
                }
            }
        }

        struct DebugCursorShape(CursorShape);
        impl std::fmt::Debug for DebugCursorShape {
            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
                match self.0 {
                    CursorShape::DefaultUserShape => f.write_str("DefaultUserShape"),
                    CursorShape::BlinkingBlock => f.write_str("BlinkingBlock"),
                    CursorShape::SteadyBlock => f.write_str("SteadyBlock"),
                    CursorShape::BlinkingUnderScore => f.write_str("BlinkingUnderScore"),
                    CursorShape::SteadyUnderScore => f.write_str("SteadyUnderScore"),
                    CursorShape::BlinkingBar => f.write_str("BlinkingBar"),
                    CursorShape::SteadyBar => f.write_str("SteadyBar"),
                }
            }
        }

        f.debug_struct("InnerPalette")
            .field("main_cursor", &self.main_cursor.map(DebugCursorShape))
            .field("extra_cursor", &self.extra_cursor.map(DebugCursorShape))
            .field("forms", &DebugForms(&self.forms))
            .field("masks", &self.masks)
            .finish()
    }
}

impl std::fmt::Debug for FormKind {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Normal => write!(f, "Normal"),
            Self::Ref(refed, _) => write!(f, "Ref({refed})"),
            Self::Weakest => write!(f, "Weakest"),
            Self::WeakestRef(refed, _) => write!(f, "WeakestRef({refed})"),
        }
    }
}

/// The [`FormId`] of `"default"`.
pub const DEFAULT_ID: FormId = FormId(0);
/// The [`FormId`] of `"accent"`.
pub const ACCENT_ID: FormId = FormId(1);
/// The [`FormId`] of `"caret.main"`.
pub const M_CAR_ID: FormId = FormId(2);
/// The [`FormId`] of `"caret.extra"`.
pub const E_CAR_ID: FormId = FormId(3);
/// The [`FormId`] of `"slection.main"`.
pub const M_SEL_ID: FormId = FormId(4);
/// The [`FormId`] of `"selection.extra"`.
pub const E_SEL_ID: FormId = FormId(5);
/// The [`FormId`] of `"character.control"`.
pub const CONTROL_CHAR_ID: FormId = FormId(7);

/// An identifier for a mask, which maps [`Form`]s, given a suffix.
#[derive(Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct MaskId(u32);

impl MaskId {
    /// The name of the mask.
    pub fn name(&self) -> &'static str {
        name_of_mask(*self)
    }
}

impl std::fmt::Debug for MaskId {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "MaskId({:?})", name_of_mask(*self))
    }
}