drawbar 0.6.0

Your Nord's sounds, in a window: browse, edit and send programs, samples and pianos, in the browser or on the desktop
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
//! The one strip every document wears.
//!
//! What it is, what it is called, where it lives, how big it is, what state it is in,
//! which face is showing, and the one thing this kind of document is for — in that
//! order, left to right. A kind with nothing to put in one of those parts leaves the
//! part out rather than showing an empty one.
//!
//! The strip is full bleed on the window fill with a hairline under it; the body below
//! it is the only thing given a margin.

use eframe::egui;
use nord_format::accept::Family;
use nord_usb::{Location, ObjectClass};

use super::controls::{self, Sets};
use super::{encode, piano, project, sample, setlist, SendBack, Shape};
use crate::app::{accent, caption, good, warn};
use crate::browser::Kind;
use crate::device::{read_only, DeviceState};
use crate::icon::{icon, painted, Glyph};
use crate::library::{keyboard_mark, mark_words, Mark};
use crate::panel::caps;
use crate::queue::Queue;
use crate::room;
use crate::strings::{carries_tag, display_name, folder, kind_word, place, shown};
use crate::tags::Tags;
use crate::workspace::{LocalEntity, Origin};

/// The strip's own room: how tall it is at least, what it keeps at each end, and the gap
/// between two of its parts.
const HEIGHT: f32 = 38.0;
const PAD: i8 = 12;
const GAP: f32 = 10.0;

/// Every control on the strip is this tall, and corners are cut to this.
const CONTROL: f32 = 20.0;
const RADIUS: f32 = 2.0;

/// The glyph sizes: the kind, a face or a quiet action, the loud action, a tag chip.
const KIND: f32 = 15.0;
const SMALL: f32 = 11.0;
const LOUD: f32 = 12.0;
const TAG: f32 = 10.0;

/// The state dot's box, which holds a 6 px dot — see [`claim`].
const DOT: f32 = 8.0;

/// The room between a glyph and the word after it.
const INSET: f32 = 5.0;

/// The words a control carries, and the mono the badge, the place and the size are set
/// in.
const WORD: f32 = 10.5;
const MONO: f32 = 10.5;

/// A read-only value on the identity row, which stands where a text box would.
const READ: f32 = 11.5;

/// The name box, the piano's shorter one, and the variant beside it.
const NAME: f32 = 190.0;
const PIANO_NAME: f32 = 150.0;
const VARIANT: f32 = 84.0;

/// The name the instrument owns, which is text rather than a box.
const FIXED: f32 = 12.5;

/// The identity row's indent, measured from the strip's outer edge, and its own height.
const INDENT: f32 = 37.0;
const CHIP: f32 = 18.0;

/// Which face of a document is showing.
///
/// Three files rather than three modes: Edit is the sound, Metadata is what the file
/// says about itself, and Advanced is the engineering. Which of them a document has is
/// [`super::faces`].
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum Face {
    /// The panel, in the instrument's own words. Happy-path edits.
    #[default]
    Edit,
    /// The record: the container, the bytes that moved, and what the instrument says
    /// about the slot. Nothing here is a control.
    Metadata,
    /// The whole body as a table. Nothing hidden.
    Advanced,
}

impl Face {
    pub fn label(self) -> &'static str {
        match self {
            Face::Edit => "Edit",
            Face::Metadata => "Metadata",
            Face::Advanced => "Advanced",
        }
    }

    fn glyph(self) -> Glyph {
        match self {
            Face::Edit => Glyph::Pencil,
            Face::Metadata => Glyph::Info,
            Face::Advanced => Glyph::Wrench,
        }
    }

    fn hint(self) -> &'static str {
        match self {
            Face::Edit => "the fields that change the sound",
            Face::Metadata => "what the file says about itself — read only",
            Face::Advanced => "capabilities, offsets, raw values — engineering",
        }
    }
}

/// How much of the header fits, measured on the header's own width.
///
/// The collapse order, widest first: the quiet actions lose their words, then the faces
/// lose theirs, then the loud action keeps only its number. The identity row wraps after
/// all three.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Stage {
    Full,
    Quiet,
    Faces,
    Narrow,
}

/// The three widths the strip changes shape at.
const BREAKPOINTS: [f32; 3] = [1000.0, 860.0, 720.0];

pub fn stage(width: f32) -> Stage {
    match width {
        width if width >= BREAKPOINTS[0] => Stage::Full,
        width if width >= BREAKPOINTS[1] => Stage::Quiet,
        width if width >= BREAKPOINTS[2] => Stage::Faces,
        _ => Stage::Narrow,
    }
}

/// The ink a header phrase or stroke may wear.
///
/// ⚠️ There is no `bad` here. Red is for the hatches in a key map, and a header that
/// has already shouted has nothing louder left to say.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Ink {
    Good,
    Warn,
    /// The caption ink: a figure rather than a claim.
    Quiet,
}

impl Ink {
    pub(super) fn color(self, visuals: &egui::Visuals) -> egui::Color32 {
        match self {
            Ink::Good => good(visuals),
            Ink::Warn => warn(visuals),
            Ink::Quiet => caption(visuals),
        }
    }
}

/// The size line: what it reads, whether it is a warning, and the sentence behind it.
pub struct SizeLine {
    pub text: String,
    pub warn: bool,
    pub hint: String,
}

/// The dot and the phrase beside it: one claim about this document.
#[derive(Clone)]
pub struct StateLine {
    pub words: String,
    pub ink: Ink,
    pub hint: String,
}

/// How the loud action is dressed.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Tone {
    /// It can happen.
    Ready,
    /// It cannot yet, and the label carries the reason.
    Blocked,
    /// There is nothing to do it to.
    Idle,
}

/// The one loud action a document has, in whichever of its three states it is in.
pub struct Loud {
    pub label: String,
    /// What it is called where there is no room for the whole label.
    pub short: String,
    pub glyph: Glyph,
    pub tone: Tone,
    pub hint: String,
    /// The slot a click would queue a write for. `None` is an action nothing happens on.
    pub send: Option<(ObjectClass, Location)>,
}

/// What an editor adds to the header that the asset alone does not say.
///
/// Each field is what the strip shows *instead* of what it works out for itself: the
/// piano's `188 of 194 MB`, its `trimmed`, and its refusal to queue a library that does
/// not fit.
#[derive(Default)]
pub struct Extras {
    pub size: Option<SizeLine>,
    /// The claim an unsaved document makes, where the editor has a better one than
    /// `edited` — the field document's `N pending`.
    ///
    /// ⚠️ Its ink is the strip's, not the editor's: an unsaved document is a warning
    /// whatever counted it.
    pub edited: Option<StateLine>,
    /// What a saved document claims instead of what the strip works out — a set list
    /// naming programs the instrument does not have where it says.
    pub state: Option<StateLine>,
    pub loud: Option<Loud>,
}

/// One cell of the identity row: a MICRO-caps label and what the document wears under
/// it.
pub struct Cell {
    pub label: &'static str,
    pub body: Body,
    /// The one note that is shown rather than hovered: a constraint the field enforces.
    pub note: Option<String>,
    pub hint: &'static str,
}

/// What a cell wears beside its label.
///
/// There is no third kind yet because no header-level field of any format has a setter:
/// the sample's category and sub name are stated by the file and read here.
pub enum Body {
    /// One chip per label the list puts on this asset.
    Chips(Vec<String>),
    /// A value the file states and nothing here writes.
    Read(String),
}

/// Everything the strip draws from besides the asset itself.
pub(super) struct Facts<'a> {
    pub faces: &'a [Face],
    pub showing: Face,
    pub device: &'a DeviceState,
    pub queue: &'a Queue,
    pub tags: &'a Tags,
    /// Whether this is a view of the instrument's own copy rather than an asset held
    /// here.
    pub view: bool,
    /// What a piano library's plan will save its name and its variant as, from
    /// [`piano::State::renaming`]: the box holds what a save writes.
    pub renaming: (Option<String>, Option<String>),
    /// What the document is, which is what decides where its name is kept.
    pub shape: Shape,
    pub extras: Extras,
}

/// What the header was asked for this frame.
#[derive(Default)]
pub(super) struct Clicked {
    pub revert: bool,
    pub export: bool,
    pub send: Option<SendBack>,
    /// The face picked, where one was.
    pub face: Option<Face>,
    /// The name the asset is to be called, where a rename settled. Applied once nothing
    /// is borrowing the asset.
    pub rename: Option<String>,
}

/// Draw the strip, and the identity row under it where the kind has one.
pub(super) fn ui(
    ui: &mut egui::Ui,
    entity: &LocalEntity,
    facts: &Facts<'_>,
    boxes: (&mut String, &mut String),
    sets: &mut Sets,
) -> Clicked {
    let stage = stage(ui.available_width());
    let cells = identity(entity, facts.tags);
    let visuals = ui.visuals().clone();
    let mut act = Clicked::default();

    let drawn = egui::Frame::new()
        .fill(visuals.window_fill)
        .inner_margin(egui::Margin {
            left: PAD,
            right: PAD,
            top: 4,
            bottom: match cells.is_empty() {
                true => 4,
                false => 8,
            },
        })
        .show(ui, |ui| {
            ui.spacing_mut().item_spacing.x = GAP;
            ui.spacing_mut().interact_size.y = CONTROL;
            strip(
                ui,
                &mut act,
                |rhs, act| right(rhs, entity, facts, stage, act),
                |lhs, act| left(lhs, entity, facts, boxes, sets, act),
            );
            if !cells.is_empty() {
                row(ui, &cells, stage);
            }
        });

    let hairline = egui::Stroke::new(1.0_f32, visuals.widgets.noninteractive.bg_stroke.color);
    let rect = drawn.response.rect;
    ui.painter()
        .hline(ui.max_rect().x_range(), rect.bottom() - 0.5, hairline);
    act
}

/// One row of the strip: the right-hand group takes the width it needs at the right
/// edge, and the left-hand group has the rest, wrapping onto a second line when the
/// words run out of room rather than running under the controls.
///
/// The right group is laid out first because its width is what decides the left
/// group's room.
fn strip<T>(
    ui: &mut egui::Ui,
    state: &mut T,
    right: impl FnOnce(&mut egui::Ui, &mut T),
    left: impl FnOnce(&mut egui::Ui, &mut T),
) {
    let row = egui::Rect::from_min_size(
        ui.cursor().min,
        egui::vec2(ui.available_width(), HEIGHT - 8.0),
    );
    let mut rhs = ui.new_child(
        egui::UiBuilder::new()
            .max_rect(row)
            .layout(egui::Layout::right_to_left(egui::Align::Center)),
    );
    rhs.spacing_mut().item_spacing.x = GAP;
    right(&mut rhs, state);
    let taken = rhs.min_rect();
    let room = egui::Rect::from_min_max(row.min, egui::pos2(taken.left() - GAP, row.max.y));
    let mut lhs = ui.new_child(
        egui::UiBuilder::new()
            .max_rect(room)
            .layout(egui::Layout::left_to_right(egui::Align::Center).with_main_wrap(true)),
    );
    lhs.spacing_mut().item_spacing = egui::vec2(GAP, 4.0);
    left(&mut lhs, state);
    ui.advance_cursor_after_rect(lhs.min_rect().union(taken).union(row));
}

/// The kind, the name, the format, the place, the size and the state.
fn left(
    ui: &mut egui::Ui,
    entity: &LocalEntity,
    facts: &Facts<'_>,
    boxes: (&mut String, &mut String),
    sets: &mut Sets,
    act: &mut Clicked,
) {
    let visuals = ui.visuals().clone();
    let quiet = caption(&visuals);
    let glyph = Kind::of(entity.entity.as_ref()).glyph();
    icon(ui, glyph, KIND, accent(&visuals));

    let (held, stored) = named(entity, facts.shape, facts.view, facts.renaming.clone());
    act.rename = name(ui, entity, &held, &stored, boxes, sets);

    let (badge, hint) = badge(entity);
    let drawn = pill(
        ui,
        Pill {
            glyph: None,
            label: Some(&badge),
            ink: visuals
                .widgets
                .inactive
                .fg_stroke
                .color
                .gamma_multiply(0.85),
            mono: true,
            stroke: Some(visuals.widgets.noninteractive.bg_stroke.color),
            dashed: false,
            pad: 6.0,
            height: CONTROL,
            live: false,
        },
    );
    if !hint.is_empty() {
        drawn.on_hover_text(hint);
    }

    mono(ui, &lives(entity), quiet).on_hover_text(entity.origin.label());

    let own = sized(entity);
    if let Some(size) = facts.extras.size.as_ref().or(own.as_ref()) {
        rule(ui);
        let ink = match size.warn {
            true => warn(&visuals),
            false => quiet,
        };
        let drawn = mono(ui, &size.text, ink);
        if !size.hint.is_empty() {
            drawn.on_hover_text(&size.hint);
        }
    }

    if let Some(state) = state(entity, facts) {
        let ink = state.ink.color(&visuals);
        claim(ui, &state.words, ink).on_hover_text(&state.hint);
    }
}

/// The state as one widget, a dot and its phrase, so a wrapping row moves the two
/// together rather than leaving the dot on one line and the words on the next.
fn claim(ui: &mut egui::Ui, words: &str, ink: egui::Color32) -> egui::Response {
    let galley =
        ui.painter()
            .layout_no_wrap(words.to_owned(), egui::FontId::proportional(WORD), ink);
    let size = egui::vec2(DOT + INSET + galley.size().x, CONTROL);
    let (rect, response) = ui.allocate_exact_size(size, egui::Sense::hover());
    let painter = ui.painter();
    painter.circle_filled(
        egui::pos2(rect.left() + DOT / 2.0, rect.center().y),
        DOT / 2.0 - 1.0,
        ink,
    );
    painter.galley(
        egui::pos2(
            rect.left() + DOT + INSET,
            rect.center().y - galley.size().y / 2.0,
        ),
        galley,
        ink,
    );
    response
}

/// The faces, the quiet actions and the loud one, in that order left to right — which
/// in a right-to-left layout is this order backwards.
fn right(
    ui: &mut egui::Ui,
    entity: &LocalEntity,
    facts: &Facts<'_>,
    stage: Stage,
    act: &mut Clicked,
) {
    let visuals = ui.visuals().clone();
    let quiet = caption(&visuals);
    let own = action(entity, facts.device);
    let loud = facts.extras.loud.as_ref().unwrap_or(&own);
    let label = match stage {
        Stage::Narrow => &loud.short,
        _ => &loud.label,
    };
    let (stroke, mark, ink) = match loud.tone {
        Tone::Ready => (accent(&visuals), accent(&visuals), visuals.text_color()),
        Tone::Blocked => (warn(&visuals), warn(&visuals), visuals.text_color()),
        Tone::Idle => (visuals.widgets.noninteractive.bg_stroke.color, quiet, quiet),
    };
    let clicked = pill(
        ui,
        Pill {
            glyph: Some((loud.glyph, LOUD, mark)),
            label: Some(label),
            ink,
            mono: false,
            stroke: Some(stroke),
            dashed: loud.tone == Tone::Idle,
            pad: 8.0,
            height: CONTROL,
            live: loud.tone == Tone::Ready,
        },
    )
    .on_hover_text(&loud.hint)
    .clicked();
    if let (true, Some((class, at))) = (clicked, loud.send) {
        act.send = Some(SendBack {
            id: entity.id,
            class,
            at,
        });
    }

    // Right to left: Export is drawn before Revert so the two read the other way round.
    let words = stage == Stage::Full;
    let quiet_pill = |ui: &mut egui::Ui, glyph, label: &str, live| {
        pill(
            ui,
            Pill {
                glyph: Some((glyph, SMALL, quiet)),
                label: words.then_some(label),
                ink: quiet,
                mono: false,
                stroke: Some(visuals.widgets.noninteractive.bg_stroke.color),
                dashed: false,
                pad: match words {
                    true => 7.0,
                    false => 5.0,
                },
                height: CONTROL,
                live,
            },
        )
    };
    act.export = quiet_pill(ui, Glyph::ArrowDownToLine, "Export…", true)
        .on_hover_text(hint(
            "Export…",
            "a copy on this computer, under a name you pick",
            words,
        ))
        .clicked();
    let unsaved = entity.is_unsaved();
    let revert = quiet_pill(ui, Glyph::RotateCcw, "Revert", unsaved);
    act.revert = match unsaved {
        true => revert
            .on_hover_text(hint(
                "Revert",
                "back to the bytes it was last saved as",
                words,
            ))
            .clicked(),
        false => {
            revert.on_hover_text(hint(
                "Revert",
                "nothing has changed since it was saved",
                words,
            ));
            false
        }
    };

    rule(ui);
    act.face = segments(ui, facts, stage);
}

/// A hover that names the control as well as explaining it, once the stage has taken the
/// word off its face.
fn hint(label: &str, why: &str, words: bool) -> String {
    match words {
        true => why.to_string(),
        false => format!("{why} ({label})"),
    }
}

/// The faces as one control: one stroke round the group, a rule between two of them, and
/// the showing one filled. Only the faces this document has are in it.
fn segments(ui: &mut egui::Ui, facts: &Facts<'_>, stage: Stage) -> Option<Face> {
    let visuals = ui.visuals().clone();
    let painter = ui.painter().clone();
    let words = matches!(stage, Stage::Full | Stage::Quiet);
    let pad = match words {
        true => 8.0,
        false => 6.0,
    };
    let ink = |face: Face| match face == facts.showing {
        true => visuals.text_color(),
        false => caption(&visuals),
    };
    let laid: Vec<(Face, Option<std::sync::Arc<egui::Galley>>, f32)> = facts
        .faces
        .iter()
        .map(|face| {
            let word = words.then(|| {
                painter.layout_no_wrap(
                    face.label().to_string(),
                    egui::FontId::proportional(WORD),
                    ink(*face),
                )
            });
            let width = pad * 2.0 + SMALL + word.as_ref().map_or(0.0, |laid| INSET + laid.size().x);
            (*face, word, width)
        })
        .collect();

    let total: f32 = laid.iter().map(|(_, _, width)| width).sum();
    let (rect, _) = ui.allocate_exact_size(egui::vec2(total, CONTROL), egui::Sense::hover());
    let border = egui::Stroke::new(1.0_f32, visuals.widgets.noninteractive.bg_stroke.color);
    let mut picked = None;
    let mut x = rect.left();
    let last = laid.len().saturating_sub(1);
    for (nth, (face, word, width)) in laid.into_iter().enumerate() {
        let cell = egui::Rect::from_min_size(egui::pos2(x, rect.top()), egui::vec2(width, CONTROL));
        let response = ui.interact(
            cell,
            ui.id().with(("face", face.label())),
            egui::Sense::click(),
        );
        let fill = match (face == facts.showing, response.hovered()) {
            (true, _) => Some(visuals.widgets.active.weak_bg_fill),
            (false, true) => Some(visuals.widgets.hovered.weak_bg_fill),
            (false, false) => None,
        };
        if let Some(fill) = fill {
            painter.rect_filled(cell, 0.0, fill);
        }
        if nth < last {
            painter.vline(cell.right() - 0.5, cell.y_range(), border);
        }
        painted(
            ui,
            face.glyph(),
            egui::Rect::from_center_size(
                egui::pos2(cell.left() + pad + SMALL / 2.0, cell.center().y),
                egui::Vec2::splat(SMALL),
            ),
            ink(face),
        );
        if let Some(word) = word {
            let at = egui::pos2(
                cell.left() + pad + SMALL + INSET,
                cell.center().y - word.size().y / 2.0,
            );
            painter.galley(at, word, ink(face));
        }
        if response.clicked() {
            picked = Some(face);
        }
        response.on_hover_text(hint(face.label(), face.hint(), words));
        x = cell.right();
    }
    painter.rect_stroke(rect, RADIUS, border, egui::StrokeKind::Inside);
    picked
}

/// The identity row: a MICRO-caps label and what the document wears under it, one cell
/// after another under the name.
fn row(ui: &mut egui::Ui, cells: &[Cell], stage: Stage) {
    let indent = INDENT - f32::from(PAD);
    let draw = |ui: &mut egui::Ui| {
        ui.spacing_mut().item_spacing = egui::vec2(18.0, 4.0);
        ui.add_space(indent);
        for cell in cells {
            let response = ui
                .horizontal(|ui| {
                    ui.spacing_mut().item_spacing.x = 7.0;
                    ui.label(caps(cell.label).color(caption(ui.visuals())));
                    ui.spacing_mut().item_spacing.x = 4.0;
                    match &cell.body {
                        Body::Chips(chips) => {
                            for text in chips {
                                chip(ui, text);
                            }
                        }
                        Body::Read(value) => read(ui, value),
                    }
                    if let Some(note) = &cell.note {
                        ui.label(
                            egui::RichText::new(note)
                                .size(10.0)
                                .color(caption(ui.visuals())),
                        );
                    }
                })
                .response;
            if !cell.hint.is_empty() {
                response.on_hover_text(cell.hint);
            }
        }
    };
    match stage {
        Stage::Narrow => ui.horizontal_wrapped(draw),
        _ => ui.horizontal(draw),
    };
}

/// A value the file states: the eye that says nothing writes it, and the value in mono.
fn read(ui: &mut egui::Ui, value: &str) {
    ui.spacing_mut().item_spacing.x = INSET;
    icon(ui, Glyph::Eye, SMALL, caption(ui.visuals()));
    ui.label(
        egui::RichText::new(value)
            .font(egui::FontId::monospace(READ))
            .color(ui.visuals().weak_text_color()),
    );
}

/// One tag chip: the accent stroke and ink the inspector's own chips wear, in a box
/// shorter than the strip's own controls.
fn chip(ui: &mut egui::Ui, text: &str) -> egui::Response {
    let ink = accent(ui.visuals());
    pill(
        ui,
        Pill {
            glyph: Some((Glyph::Tag, TAG, ink)),
            label: Some(text),
            ink,
            mono: false,
            stroke: Some(ink),
            dashed: false,
            pad: 6.0,
            height: CHIP,
            live: false,
        },
    )
}

/// What one button on the strip is made of.
struct Pill<'a> {
    /// The glyph, its box and its ink. The badge carries none.
    glyph: Option<(Glyph, f32, egui::Color32)>,
    /// The word beside it, or nothing where the stage has taken it.
    label: Option<&'a str>,
    ink: egui::Color32,
    mono: bool,
    stroke: Option<egui::Color32>,
    dashed: bool,
    pad: f32,
    height: f32,
    /// Whether the pointer lifts it and a click of it means anything.
    live: bool,
}

fn pill(ui: &mut egui::Ui, held: Pill<'_>) -> egui::Response {
    let visuals = ui.visuals().clone();
    let painter = ui.painter().clone();
    let font = match held.mono {
        true => egui::FontId::monospace(MONO),
        false => egui::FontId::proportional(WORD),
    };
    let word = held
        .label
        .map(|label| painter.layout_no_wrap(label.to_string(), font, held.ink));
    let marked = held.glyph.map_or(0.0, |(_, size, _)| size);
    let gap = match (held.glyph.is_some(), word.is_some()) {
        (true, true) => INSET,
        _ => 0.0,
    };
    let width = held.pad * 2.0 + marked + gap + word.as_ref().map_or(0.0, |laid| laid.size().x);
    let sense = match held.live {
        true => egui::Sense::click(),
        false => egui::Sense::hover(),
    };
    let (rect, response) = ui.allocate_exact_size(egui::vec2(width, held.height), sense);

    if held.live && response.hovered() {
        painter.rect_filled(rect, RADIUS, visuals.widgets.hovered.weak_bg_fill);
    }
    if let Some(color) = held.stroke {
        let stroke = egui::Stroke::new(1.0_f32, color);
        match held.dashed {
            true => crate::panel::dashed_rect(&painter, rect.shrink(0.5), stroke),
            false => {
                painter.rect_stroke(rect, RADIUS, stroke, egui::StrokeKind::Inside);
            }
        }
    }
    let mut x = rect.left() + held.pad;
    if let Some((glyph, size, mark)) = held.glyph {
        painted(
            ui,
            glyph,
            egui::Rect::from_center_size(
                egui::pos2(x + size / 2.0, rect.center().y),
                egui::Vec2::splat(size),
            ),
            mark,
        );
        x += size + gap;
    }
    if let Some(word) = word {
        let at = egui::pos2(x, rect.center().y - word.size().y / 2.0);
        painter.galley(at, word, held.ink);
    }
    response
}

/// A mono readout: the place and the size, which are figures rather than controls.
fn mono(ui: &mut egui::Ui, text: &str, ink: egui::Color32) -> egui::Response {
    // Never broken inside: a figure that does not fit moves to the next line whole.
    ui.add(
        egui::Label::new(
            egui::RichText::new(text)
                .font(egui::FontId::monospace(MONO))
                .color(ink),
        )
        .wrap_mode(egui::TextWrapMode::Extend),
    )
}

/// The 1 px rule that parts one group of the strip from the next.
fn rule(ui: &mut egui::Ui) {
    let (rect, _) = ui.allocate_exact_size(egui::vec2(1.0, 12.0), egui::Sense::hover());
    let color = ui.visuals().widgets.noninteractive.bg_stroke.color;
    ui.painter().rect_filled(rect, 0.0, color);
}

/// Where a document's name is kept, which decides what typing in the box does.
enum Named {
    /// The file stores it, under the `name` its editor already spells. `variant` is the
    /// piano's second half, which is a box of its own.
    Stored {
        limit: Option<usize>,
        variant: Option<String>,
        width: f32,
    },
    /// The asset's own name on this computer: a rename, not an edit to the file.
    Asset,
    /// The instrument's own, and there is one of it.
    Device,
}

/// The name the file itself stores, where this shape keeps one, and how its box is
/// dressed. `renaming` is what a piano library's plan will save each half as, where it
/// renames it.
fn stored_name(
    entity: &LocalEntity,
    shape: Shape,
    renaming: (Option<String>, Option<String>),
) -> Option<(Named, String)> {
    let decoded = entity.entity.as_ref()?;
    match shape {
        Shape::Sample => {
            let held = sample::snapshot(decoded)?.ok()?;
            Some((
                Named::Stored {
                    limit: Some(held.max_name_len),
                    variant: None,
                    width: NAME,
                },
                held.name,
            ))
        }
        Shape::Project => {
            let held = project::snapshot(decoded)?.ok()?;
            Some((
                Named::Stored {
                    limit: None,
                    variant: None,
                    width: NAME,
                },
                held.name,
            ))
        }
        Shape::Piano => {
            let held = piano::snapshot(decoded)?.ok()?;
            let (name, variant) = renaming;
            Some((
                Named::Stored {
                    limit: None,
                    variant: Some(variant.unwrap_or(held.variant)),
                    width: PIANO_NAME,
                },
                name.unwrap_or(held.name),
            ))
        }
        Shape::Fields | Shape::SetList | Shape::Verbatim | Shape::Wav | Shape::Undecoded => None,
    }
}

/// What the name box holds, and what typing in it does.
fn named(
    entity: &LocalEntity,
    shape: Shape,
    view: bool,
    renaming: (Option<String>, Option<String>),
) -> (Named, String) {
    if let Some(held) = stored_name(entity, shape, renaming) {
        return held;
    }
    let settings = Kind::of(entity.entity.as_ref()) == Kind::Settings;
    match view && settings {
        true => (Named::Device, display_name(&entity.name).to_string()),
        false => (Named::Asset, display_name(&entity.name).to_string()),
    }
}

/// What the name boxes hold when a document opens.
pub(super) fn boxes(
    entity: &LocalEntity,
    shape: Shape,
    view: bool,
    renaming: (Option<String>, Option<String>),
) -> (String, String) {
    let (held, stored) = named(entity, shape, view, renaming);
    let variant = match held {
        Named::Stored { variant, .. } => variant.unwrap_or_default(),
        Named::Asset | Named::Device => String::new(),
    };
    (stored, variant)
}

/// The name, as a box where something here can change it and as text where it is the
/// instrument's. Returns the name the asset is to be called, where a rename settled.
fn name(
    ui: &mut egui::Ui,
    entity: &LocalEntity,
    held: &Named,
    stored: &str,
    boxes: (&mut String, &mut String),
    sets: &mut Sets,
) -> Option<String> {
    let (typed, variant_box) = boxes;
    match held {
        Named::Device => {
            ui.label(
                egui::RichText::new(stored)
                    .size(FIXED)
                    .strong()
                    .color(ui.visuals().text_color()),
            )
            .on_hover_text("a keyboard has one settings block; it is not renamed");
            None
        }
        Named::Stored {
            limit,
            variant,
            width,
        } => {
            if settled(ui, typed, *width, *limit, false) && typed != stored {
                sets.push(("name".to_string(), typed.clone()));
            }
            if let Some(stored) = variant {
                ui.label(
                    egui::RichText::new("#")
                        .font(egui::FontId::monospace(12.0))
                        .color(caption(ui.visuals())),
                );
                if settled(ui, variant_box, VARIANT, None, true) && variant_box != stored {
                    sets.push(("variant".to_string(), variant_box.clone()));
                }
            }
            None
        }
        Named::Asset => {
            let done = settled(ui, typed, NAME, None, false);
            let wanted = tagged(&entity.name, typed);
            (done && !typed.trim().is_empty() && wanted != entity.name).then_some(wanted)
        }
    }
}

/// A single-line name box that commits when it is done rather than per keystroke: half a
/// name is a name the format would take.
///
/// ⚠️ Done is this box giving up the focus, which a single-line `TextEdit` does on Enter.
/// An Enter read from the window would settle every name box on screen, so a value the
/// format had already refused went back to it on every Enter the operator pressed.
fn settled(
    ui: &mut egui::Ui,
    text: &mut String,
    width: f32,
    limit: Option<usize>,
    mono: bool,
) -> bool {
    let mut edit = egui::TextEdit::singleline(text)
        .desired_width(width)
        .margin(egui::Margin::symmetric(4, 1));
    if mono {
        edit = edit.font(egui::FontId::monospace(MONO));
    }
    let response = ui.add(edit);
    if let Some(limit) = limit {
        controls::fits(text, limit);
    }
    response.lost_focus()
}

/// What a typed name is stored as: the words that were typed, under the format tag the
/// stored name carries.
///
/// The glyph beside the box already says what kind of file it is, so the tag is never in
/// the box — and it must not be lost by typing in one.
fn tagged(stored: &str, typed: &str) -> String {
    match carries_tag(stored) {
        true => match stored.rsplit_once('.') {
            Some((_, tag)) => format!("{typed}.{tag}"),
            None => typed.to_string(),
        },
        false => typed.to_string(),
    }
}

/// The mono badge over a document, and the sentence behind it.
///
/// ⚠️ Exhaustive over [`Kind`], so a kind the browser learns is a badge decided here
/// rather than a blank one.
pub(super) fn badge(entity: &LocalEntity) -> (String, String) {
    let tag = entity.tag();
    let kind = Kind::of(entity.entity.as_ref());
    let word = kind_word(kind, Family::of_tag(&tag));
    let version = entity.container.as_ref().map(|held| held.header.version);
    let sentence = match version {
        Some(version) => format!("{word}, content version {version}"),
        None => word,
    };
    match kind {
        Kind::Sample => {
            let generation = entity
                .entity
                .as_ref()
                .and_then(sample::snapshot)
                .and_then(Result::ok)
                .map_or_else(String::new, |held| format!(" {}", held.generation));
            (
                format!("nsmp{generation}"),
                match version {
                    Some(version) => format!("content version {version}"),
                    None => sentence,
                },
            )
        }
        Kind::Piano => match stream_version(entity) {
            Some(stream) => (
                format!("npno {stream:#05x}"),
                format!("stream version {stream:#05x}"),
            ),
            None => (tag, sentence),
        },
        Kind::Project => (
            "project".to_string(),
            "a Nord Sample Editor project, which builds an nsmp".to_string(),
        ),
        Kind::Program => (format!("program v{}", version.unwrap_or(0)), sentence),
        Kind::SetList => ("set list".to_string(), sentence),
        Kind::Settings => ("settings".to_string(), sentence),
        Kind::Other => match encode::is_wav(&entity.bytes) {
            true => (
                "wav".to_string(),
                "audio this app can make an instrument out of".to_string(),
            ),
            false => (tag, "these bytes did not decode".to_string()),
        },
        Kind::Live
        | Kind::Synth
        | Kind::OrganPreset
        | Kind::PianoPreset
        | Kind::Performance
        | Kind::LeadBank
        | Kind::SampleLibrary
        | Kind::PipeLibrary
        | Kind::Bundle => (tag, sentence),
    }
}

/// The stream version a piano library states, which is not the container's.
fn stream_version(entity: &LocalEntity) -> Option<u16> {
    match entity.entity.as_ref()? {
        nord_format::Entity::Piano(piano) => piano.stream_version().ok(),
        _ => None,
    }
}

/// Where the document lives: a slot on the instrument, a folder on this computer, or the
/// computer itself.
pub(super) fn lives(entity: &LocalEntity) -> String {
    if let Some((class, at)) = entity.spot() {
        return place(class, at);
    }
    match &entity.origin {
        Origin::File(path) => folder_of(path, home()),
        Origin::Rescued { at } => shown(*at),
        // ⚠️ Unreachable: a device origin is a slot, and `spot` answered for it.
        Origin::Device { class, at } => place(*class, *at),
        Origin::Fresh => "This computer".to_string(),
    }
}

/// The home directory, where the host has one to compare a path against.
fn home() -> Option<String> {
    std::env::var("HOME").ok().filter(|home| !home.is_empty())
}

/// The folder a path is in, with the home directory written `~`.
///
/// A name with no folder in it — what a drop and the file picker hand over — is on this
/// computer and nothing more can be said about where.
fn folder_of(path: &str, home: Option<String>) -> String {
    let parent = match path.rsplit_once('/') {
        Some(("", _)) => "/".to_string(),
        Some((parent, _)) => parent.to_string(),
        None => return "This computer".to_string(),
    };
    match home.filter(|home| parent == *home || parent.starts_with(&format!("{home}/"))) {
        Some(home) => format!("~{}", &parent[home.len()..]),
        None => parent,
    }
}

/// How big the document is, in whatever it is that a document of this kind has: bytes,
/// or the entries a set list orders. Settings are one block and there is nothing to say.
fn sized(entity: &LocalEntity) -> Option<SizeLine> {
    let kind = Kind::of(entity.entity.as_ref());
    if kind == Kind::Settings {
        return None;
    }
    if kind == Kind::SetList {
        let entries = setlist::entries(entity.entity.as_ref()?)?;
        return Some(SizeLine {
            text: match entries {
                1 => "1 entry".to_string(),
                entries => format!("{entries} entries"),
            },
            warn: false,
            hint: "the programs this set list orders".to_string(),
        });
    }
    let bytes = entity.bytes.len() as u64;
    Some(SizeLine {
        text: room::measure(bytes),
        warn: false,
        hint: format!("{bytes} bytes"),
    })
}

/// The one claim the header makes about this document: what it holds that is not what it
/// was saved as, or what the attached instrument holds where this document stands.
///
/// ⚠️ Ordered, unsaved first: a slot that agrees with the *saved* bytes says nothing
/// about the ones in front of the reader.
fn state(entity: &LocalEntity, facts: &Facts<'_>) -> Option<StateLine> {
    let waiting = facts.queue.holds(entity.id);
    if entity.is_unsaved() {
        return Some(match &facts.extras.edited {
            Some(line) => StateLine {
                words: line.words.clone(),
                ink: Ink::Warn,
                hint: line.hint.clone(),
            },
            None => phrase(Mark::Unsaved, waiting),
        });
    }
    if let Some(claim) = &facts.extras.state {
        return Some(claim.clone());
    }
    let mark = keyboard_mark(entity, facts.device, facts.queue)?;
    Some(phrase(mark, waiting))
}

/// What a mark says in the strip, in the strip's own shorter words — and never in red.
///
/// ⚠️ Exhaustive over [`Mark`], and every arm's ink is an [`Ink`]: there is no spelling
/// of this that reaches `bad`.
fn phrase(mark: Mark, waiting: bool) -> StateLine {
    let hint = mark_words(mark).to_string();
    match mark {
        Mark::Unsaved => StateLine {
            words: "edited".to_string(),
            ink: Ink::Warn,
            hint,
        },
        Mark::Agrees => StateLine {
            words: "matches keyboard".to_string(),
            ink: Ink::Good,
            hint,
        },
        Mark::Differs => StateLine {
            words: match waiting {
                true => "waiting to send".to_string(),
                false => "differs from keyboard".to_string(),
            },
            ink: Ink::Warn,
            hint,
        },
        Mark::Unknown => StateLine {
            words: "on the keyboard".to_string(),
            ink: Ink::Quiet,
            hint,
        },
    }
}

/// The one loud action, and which of its three states it is in.
///
/// ⚠️ Ordered, and the order is what makes the label honest: a project has nothing to
/// send whatever is attached, an unattached instrument cannot be written to whatever the
/// asset is, and a class this app does not write into is never a question of room.
pub(super) fn action(entity: &LocalEntity, device: &DeviceState) -> Loud {
    let send = |hint: String| Loud {
        label: "Queue send".to_string(),
        short: "Send".to_string(),
        glyph: Glyph::Upload,
        tone: Tone::Ready,
        hint,
        send: entity.spot(),
    };
    let idle = |hint: String| Loud {
        send: None,
        tone: Tone::Idle,
        ..send(hint)
    };

    if Kind::of(entity.entity.as_ref()) == Kind::Project {
        return Loud {
            label: "Build → .nsmp".to_string(),
            short: "Build".to_string(),
            glyph: Glyph::CircleAlert,
            tone: Tone::Blocked,
            hint: "the codec is not understood yet".to_string(),
            send: None,
        };
    }
    if !device.connected() {
        return idle("no instrument attached — nothing to send to".to_string());
    }
    let Some((class, at)) = entity.spot() else {
        return idle("this stands on no slot — there is nothing to replace".to_string());
    };
    if read_only(class) {
        return idle(format!(
            "nothing here knows what {} holds, so nothing is written there",
            folder(class)
        ));
    }
    if let Some((over, free)) = over(entity, class, device) {
        return Loud {
            label: format!("Won't fit · {} over", room::measure(over)),
            short: format!("{} over", room::measure(over)),
            glyph: Glyph::CircleAlert,
            tone: Tone::Blocked,
            hint: format!(
                "{} is free in {}, and this is {}",
                room::measure(free),
                folder(class),
                room::measure(entity.bytes.len() as u64)
            ),
            send: None,
        };
    }
    send(format!("replaces {}", place(class, at)))
}

/// How much larger the document is than the room left in its folder, and how much that
/// room is — where the folder counts in bytes and the document is the larger.
fn over(entity: &LocalEntity, class: ObjectClass, device: &DeviceState) -> Option<(u64, u64)> {
    let free = room::free_bytes(class, device)?;
    let bytes = entity.bytes.len() as u64;
    bytes
        .checked_sub(free)
        .filter(|over| *over > 0)
        .map(|over| (over, free))
}

/// The identity cells this kind has: the header-level fields the strip cannot carry.
///
/// ⚠️ A cell with nothing in it is left out, and a kind with no cell at all has no row —
/// an indented empty line under the name reads as a field that failed to draw.
fn identity(entity: &LocalEntity, tags: &Tags) -> Vec<Cell> {
    let mut cells = Vec::new();
    if Kind::of(entity.entity.as_ref()) == Kind::Program {
        let worn: Vec<String> = tags
            .worn(entity.id)
            .iter()
            .filter_map(|tag| tags.name_of(*tag))
            .map(str::to_string)
            .collect();
        if !worn.is_empty() {
            cells.push(Cell {
                label: "Tags",
                body: Body::Chips(worn),
                note: None,
                hint: "what this computer's list labels it with",
            });
        }
    }
    if let Some(stated) = entity.entity.as_ref().and_then(sample::stated) {
        cells.push(stated);
    }
    cells
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::log::Log;
    use crate::workspace::{Fresh, Workspace};

    fn workspace() -> (Workspace, Log) {
        let ctx = egui::Context::default();
        (Workspace::new(ctx), Log::default())
    }

    /// A workspace holding one file, and its id.
    fn opened(name: &str, bytes: Vec<u8>) -> (Workspace, u64) {
        let (mut workspace, mut log) = workspace();
        let id = workspace.ingest(
            name.to_string(),
            Origin::File(name.to_string()),
            bytes,
            &mut log,
        );
        (workspace, id)
    }

    /// ⚠️ A name box settles on its own Enter. Read from the window, every box on
    /// screen settled together, so a name the format had refused went back to it — and
    /// into the log — on every Enter the operator pressed anywhere.
    #[test]
    fn a_name_box_settles_on_its_own_enter_rather_than_the_windows() {
        let ctx = egui::Context::default();
        ctx.set_fonts(crate::app::fonts());
        let mut text = "Marimba".to_string();
        let key = |key| egui::Event::Key {
            key,
            physical_key: None,
            pressed: true,
            repeat: false,
            modifiers: egui::Modifiers::NONE,
        };
        let at = |pos| egui::Event::PointerButton {
            pos,
            button: egui::PointerButton::Primary,
            pressed: true,
            modifiers: egui::Modifiers::NONE,
        };
        let frame = |events: Vec<egui::Event>, text: &mut String| {
            let mut done = false;
            let input = egui::RawInput {
                events,
                screen_rect: Some(egui::Rect::from_min_size(
                    egui::Pos2::ZERO,
                    egui::vec2(400.0, 100.0),
                )),
                ..Default::default()
            };
            let _ = ctx.run(input, |ctx| {
                egui::CentralPanel::default().show(ctx, |ui| {
                    done = settled(ui, text, NAME, None, false);
                });
            });
            done
        };

        assert!(!frame(Vec::new(), &mut text), "nothing has happened");
        assert!(
            !frame(vec![key(egui::Key::Enter)], &mut text),
            "the box never had the focus"
        );
        let _ = frame(vec![at(egui::pos2(40.0, 20.0))], &mut text);
        assert!(
            frame(vec![key(egui::Key::Enter)], &mut text),
            "an Enter typed in the box is the box being done with"
        );
    }

    /// The collapse order is decided on three widths, and a width exactly on one is
    /// still the wider stage.
    #[test]
    fn each_breakpoint_belongs_to_the_stage_above_it() {
        assert_eq!(stage(1600.0), Stage::Full);
        assert_eq!(stage(1000.0), Stage::Full);
        assert_eq!(stage(999.0), Stage::Quiet);
        assert_eq!(stage(860.0), Stage::Quiet);
        assert_eq!(stage(859.0), Stage::Faces);
        assert_eq!(stage(720.0), Stage::Faces);
        assert_eq!(stage(719.0), Stage::Narrow);
        assert_eq!(stage(0.0), Stage::Narrow);
    }

    /// A path's folder, with the home directory written the way a person writes it.
    #[test]
    fn a_path_reads_as_the_folder_it_is_in() {
        let home = || Some("/Users/x".to_string());
        assert_eq!(
            folder_of("/Users/x/Nord/projects/a.nsmpproj", home()),
            "~/Nord/projects"
        );
        assert_eq!(folder_of("/Users/x/a.nsmp", home()), "~");
        assert_eq!(folder_of("/opt/nord/a.nsmp", home()), "/opt/nord");
        assert_eq!(folder_of("/a.nsmp", home()), "/");
        // Another account's home is not this one's, however it begins.
        assert_eq!(folder_of("/Users/xavier/a.nsmp", home()), "/Users/xavier");
        // A drop hands over a bare name, and a name says nothing about a folder.
        assert_eq!(folder_of("a.nsmp", home()), "This computer");
        assert_eq!(folder_of("/opt/a.nsmp", None), "/opt");
    }

    /// A slot beats a path: an asset matched to the instrument is where the instrument
    /// has it.
    #[test]
    fn the_place_is_the_slot_where_there_is_one() {
        let (mut workspace, mut log) = workspace();
        let fresh = workspace.create(Fresh::Program, &mut log).unwrap();
        assert_eq!(lives(workspace.get(fresh).unwrap()), "This computer");

        let bytes = workspace.get(fresh).unwrap().bytes.clone();
        let copied = workspace.ingest(
            "Africa.ne5p".to_string(),
            Origin::Device {
                class: ObjectClass::Program,
                at: Location { bank: 6, slot: 3 },
            },
            bytes,
            &mut log,
        );
        assert_eq!(lives(workspace.get(copied).unwrap()), "Programs 7:4");
    }

    /// One badge per kind, and the version behind it: the generation or kind in the
    /// badge, the content or stream version in the hover.
    #[test]
    fn every_kind_says_what_format_it_is() {
        let (mut workspace, mut log) = workspace();
        let program = workspace.create(Fresh::Program, &mut log).unwrap();
        assert_eq!(
            badge(workspace.get(program).unwrap()),
            (
                "program v4".to_string(),
                "Electro 5 program, content version 4".to_string()
            )
        );

        let settings = workspace.create(Fresh::Settings, &mut log).unwrap();
        assert_eq!(
            badge(workspace.get(settings).unwrap()),
            (
                "settings".to_string(),
                "Electro 5 settings, content version 0".to_string()
            )
        );

        let (held, id) = opened("blank.ne5t", Fresh::SetList.bytes().unwrap());
        assert_eq!(
            badge(held.get(id).unwrap()),
            (
                "set list".to_string(),
                "Electro 5 set list, content version 1".to_string()
            )
        );

        let (held, id) = opened("junk.bin", b"not a nord file".to_vec());
        assert_eq!(
            badge(held.get(id).unwrap()),
            ("?".to_string(), "these bytes did not decode".to_string())
        );

        let (held, id) = opened("Marimba.nsmp", sample_bytes());
        assert_eq!(
            badge(held.get(id).unwrap()),
            ("nsmp v2".to_string(), "content version 200".to_string())
        );

        let (held, id) = opened("clarinet.nsmpproj", project_bytes());
        let (text, hint) = badge(held.get(id).unwrap());
        assert_eq!(text, "project");
        assert!(hint.contains("Sample Editor project"), "{hint}");

        let (held, id) = opened("Marimba hit.wav", wav_bytes());
        assert_eq!(badge(held.get(id).unwrap()).0, "wav");
    }

    /// A set list is an order, so its size is the count of what it orders; settings are
    /// one block and say nothing; everything else is its bytes.
    #[test]
    fn the_size_is_whatever_this_kind_measures_in() {
        let (mut workspace, mut log) = workspace();
        let settings = workspace.create(Fresh::Settings, &mut log).unwrap();
        assert!(sized(workspace.get(settings).unwrap()).is_none());

        let (held, id) = opened("blank.ne5t", Fresh::SetList.bytes().unwrap());
        assert_eq!(sized(held.get(id).unwrap()).unwrap().text, "4 entries");

        let program = workspace.create(Fresh::Program, &mut log).unwrap();
        let held = workspace.get(program).unwrap();
        assert_eq!(
            sized(held).unwrap().text,
            room::measure(held.bytes.len() as u64)
        );
    }

    /// A typed name keeps the tag the stored one carries, because the glyph beside the
    /// box says what kind of file it is and the box never shows the tag.
    #[test]
    fn a_renamed_asset_keeps_the_tag_its_stored_name_carries() {
        assert_eq!(
            tagged("Africa-Split.ne5p", "Kenya Split"),
            "Kenya Split.ne5p"
        );
        assert_eq!(tagged("Africa Split", "Kenya Split"), "Kenya Split");
        assert_eq!(tagged("notes.txt", "list"), "list.txt");
    }

    /// One phrase per mark, the queue's own word where a write is waiting, and never red
    /// — whatever the mark and whatever the editor calls an edit.
    #[test]
    fn every_mark_has_one_phrase_and_none_of_them_is_red() {
        let marks = [Mark::Unsaved, Mark::Agrees, Mark::Differs, Mark::Unknown];
        for mark in marks {
            for waiting in [false, true] {
                let held = phrase(mark, waiting);
                assert!(!held.words.is_empty(), "{mark:?} says something");
                assert_eq!(held.hint, mark_words(mark), "{mark:?} explains itself");
                // Only `dark_mode` decides an ink, so egui's own two faces answer.
                for visuals in [egui::Visuals::dark(), egui::Visuals::light()] {
                    assert_ne!(
                        held.ink.color(&visuals),
                        crate::app::bad(&visuals),
                        "{mark:?} in the header"
                    );
                }
            }
        }
        assert_eq!(phrase(Mark::Unsaved, false).words, "edited");
        assert_eq!(phrase(Mark::Agrees, false).words, "matches keyboard");
        assert_eq!(phrase(Mark::Differs, false).words, "differs from keyboard");
        assert_eq!(phrase(Mark::Differs, true).words, "waiting to send");
        assert_eq!(phrase(Mark::Unknown, false).words, "on the keyboard");
    }

    fn facts<'a>(device: &'a DeviceState, queue: &'a Queue, tags: &'a Tags) -> Facts<'a> {
        Facts {
            faces: &[Face::Edit],
            showing: Face::Edit,
            device,
            queue,
            tags,
            view: false,
            renaming: (None, None),
            shape: Shape::Fields,
            extras: Extras::default(),
        }
    }

    /// An editor's own word for an unsaved document stands in the strip, and it is warn
    /// ink whatever the editor called it — the header has no red to reach for.
    #[test]
    fn an_editors_own_state_phrase_keeps_the_strips_ink() {
        let (queue, tags) = (Queue::default(), Tags::default());
        let device = crate::device::Device::new(egui::Context::default());
        let (mut workspace, mut log) = workspace();
        let id = workspace.create(Fresh::Program, &mut log).unwrap();
        let mut edited = workspace.get(id).unwrap().bytes.clone();
        *edited.last_mut().expect("a byte to move") ^= 0xff;
        workspace.replace_bytes(id, edited, &mut log);

        let mut facts = facts(&device.state, &queue, &tags);
        let held = state(workspace.get(id).unwrap(), &facts).expect("an unsaved document");
        assert_eq!(held.words, "edited");

        facts.extras.edited = Some(StateLine {
            words: "6 pending".to_string(),
            ink: Ink::Good,
            hint: "raw ≠ bits on 6 fields".to_string(),
        });
        let held = state(workspace.get(id).unwrap(), &facts).expect("an unsaved document");
        assert_eq!(held.words, "6 pending");
        assert_eq!(held.hint, "raw ≠ bits on 6 fields");
        assert_eq!(
            held.ink,
            Ink::Warn,
            "the strip decides the ink, not the editor"
        );
    }

    /// The loud action's three states: a send that can happen, a folder with no room
    /// for it, and an instrument that is not there.
    #[test]
    fn the_loud_action_says_which_of_its_three_states_it_is_in() {
        use crate::device::Device;
        use nord_usb::wire::Status;

        let (mut workspace, mut log) = workspace();
        let at = Location { bank: 6, slot: 3 };
        let bytes = Fresh::SetList.bytes().unwrap();

        let unattached = Device::new(egui::Context::default());
        let id = workspace.ingest(
            "Blue Room.ne5t".into(),
            Origin::Device {
                class: ObjectClass::SetList,
                at,
            },
            bytes.clone(),
            &mut log,
        );
        let held = action(workspace.get(id).unwrap(), &unattached.state);
        assert_eq!(held.tone, Tone::Idle, "{}", held.hint);
        assert_eq!(held.send, None, "a dashed action asks for nothing");
        assert!(
            held.hint.contains("no instrument attached"),
            "{}",
            held.hint
        );

        let mut attached = Device::new(egui::Context::default());
        attached.pretend_scanned(ObjectClass::SetList, 7, &["Blue Room"]);
        let held = action(workspace.get(id).unwrap(), &attached.state);
        assert_eq!(held.tone, Tone::Ready);
        assert_eq!(held.send, Some((ObjectClass::SetList, at)));
        assert_eq!(held.label, "Queue send");
        assert_eq!(held.short, "Send");
        assert_eq!(held.hint, "replaces Set lists 7:4");

        // A piano is sent like anything else that stands on a slot. Nothing has reported
        // what the Pianos partition has free, and nothing that has not been said is a
        // reason to refuse.
        let in_pianos = Location { bank: 0, slot: 3 };
        let library = workspace.ingest(
            "Grand.npno".into(),
            Origin::Device {
                class: ObjectClass::Piano,
                at: in_pianos,
            },
            bytes.clone(),
            &mut log,
        );
        let held = action(workspace.get(library).unwrap(), &attached.state);
        assert_eq!(held.tone, Tone::Ready, "{}", held.hint);
        assert_eq!(held.send, Some((ObjectClass::Piano, in_pianos)));
        assert_eq!(held.hint, "replaces Pianos 1:4");

        // The same library against a Pianos partition with nothing left in it.
        let mut full = Device::new(egui::Context::default());
        full.pretend_scanned(ObjectClass::Piano, 1, &["Royal Grand 3D"]);
        full.pretend_partitions(&crate::device::ELECTRO5);
        full.state.inventory.push(Status {
            class: ObjectClass::Piano,
            count: 1,
            free: 0,
            used: 1072,
            dirty: 0,
            spare: 0,
        });
        let held = action(workspace.get(library).unwrap(), &full.state);
        assert_eq!(held.tone, Tone::Blocked);
        assert_eq!(
            held.label,
            format!("Won't fit · {} over", room::measure(bytes.len() as u64))
        );
        assert_eq!(held.send, None, "a blocked action asks for nothing");
        assert!(held.hint.contains("free in Pianos"), "{}", held.hint);
    }

    /// A project lives on this computer, so its loud action is a build — and the build
    /// refuses, because nothing here writes an nsmp from one yet.
    #[test]
    fn a_project_offers_a_build_that_refuses_rather_than_a_send() {
        let device = crate::device::Device::new(egui::Context::default());
        let (held, id) = opened("clarinet.nsmpproj", project_bytes());
        let loud = action(held.get(id).unwrap(), &device.state);
        assert_eq!(loud.tone, Tone::Blocked);
        assert_eq!(loud.label, "Build → .nsmp");
        assert_eq!(loud.short, "Build");
        assert_eq!(loud.send, None);
    }

    fn wav_bytes() -> Vec<u8> {
        use nord_format::formats::nsmp::codec;
        let samples: Vec<i16> = (0..codec::SOURCE_RATE as usize)
            .map(|i| ((i as f64 / 40.0).sin() * 12_000.0) as i16)
            .collect();
        nord_format::wav::mono_pcm16(&samples, codec::SOURCE_RATE).unwrap()
    }

    fn sample_bytes() -> Vec<u8> {
        let source = nord_format::wav::read_pcm16(&wav_bytes()).unwrap();
        let options = nord_format::formats::nsmp::encode::Options::new("Marimba");
        nord_format::formats::nsmp::encode::instrument(&source.samples, &options)
            .unwrap()
            .to_bytes()
            .unwrap()
    }

    fn project_bytes() -> Vec<u8> {
        use nord_format::formats::nsmpproj::{NewZone, Project};
        let project = Project::new(
            "clarinet",
            &[NewZone {
                path: "low.wav".into(),
                sample_rate: 44100,
                frames: 44100,
                root_key: 48,
            }],
            0,
        )
        .unwrap();
        nord_format::to_bytes(&nord_format::Entity::SampleProject(project)).unwrap()
    }
}