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
//! The browser's one tree: the places a sound can live, the kinds there are, and the
//! tags on the list on this computer.
//!
//! Every row is [`super::row::row`], and the tree computes its own indents rather than
//! nesting `Ui`s — a leaf skips the triangle's box so its glyph lines up under the glyph
//! of the branch beside it.

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

use super::act::{will_write, Act, Bulk};
use super::drag::{kinds_present, qualifier, Item, Kind, Onto};
use super::row::{row, Cells, Drawn, STEP};
use super::{Ask, Browser, Click};
use crate::device::{occupancy, read_only, Connection, Device, DeviceState};
use crate::filter::{Filter, Narrow, Place, State};
use crate::icon::Glyph;
use crate::newproject::Making;
use crate::panel::panel_header;
use crate::queue::{Queue, Queued};
use crate::shell::marked;
use crate::strings::{place, shown};
use crate::tabs::Spot;
use crate::workspace::{Fresh, LocalEntity, Workspace};

/// The New menu: every kind this app can build from nothing, the project that is laid
/// out from audio files rather than started from a default, and the folder that groups
/// them once they exist.
///
/// ⚠️ Written once and offered whole. The tree's context menu, the File menu, the toolbar
/// and the tab strip all say "New", and four menus of that name holding different things
/// is four things to learn. Connecting an instrument is not one of them — it makes
/// nothing on this computer — and lives on the tree's own instrument row.
pub fn new_menu(ui: &mut egui::Ui, acts: &mut Vec<Act>) {
    for family in &Fresh::FAMILIES {
        ui.menu_button(family.label, |ui| {
            for kind in family.kinds {
                let mut entry = ui.button(kind.label());
                if let Some(note) = kind.note() {
                    entry = entry.on_hover_text(note);
                }
                if entry.clicked() {
                    acts.push(Act::New(*kind));
                    ui.close();
                }
            }
        });
    }
    ui.separator();
    // Not families: each is laid out from audio files rather than started from a
    // default, so they ask for the files before they exist.
    for making in Making::FROM_WAVS {
        let (item, hint) = making.item();
        if ui.button(item).on_hover_text(hint).clicked() {
            acts.push(Act::NewFromWavs(making));
            ui.close();
        }
    }
    if ui
        .button("New folder")
        .on_hover_text("a way of grouping the list on this computer; the instrument never sees one")
        .clicked()
    {
        acts.push(Act::NewFolder);
        ui.close();
    }
}

/// A row of the tree with something under it.
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub(super) enum Branch {
    Computer,
    Folder(u64),
    Instrument,
    Class(u32),
    /// ⚠️ The bank as the panel counts it, which is the numbering the scan cache is keyed
    /// by — never a [`Location`]'s own zero-indexed one.
    Bank(u32, u64),
}

/// Which of the three sections are showing.
#[derive(Clone, Copy)]
pub(super) struct Sections {
    places: bool,
    kinds: bool,
    tags: bool,
}

impl Default for Sections {
    fn default() -> Sections {
        Sections {
            places: true,
            kinds: true,
            tags: true,
        }
    }
}

/// Where a row's contents start.
///
/// A branch at the top is 8 px in, a leaf beside it 26, and a leaf one level down 40:
/// a leaf skips the triangle's box, which is what lines its glyph up under the glyph of
/// a branch at the same depth.
fn indent(depth: usize, branch: bool) -> f32 {
    const FIRST: f32 = 8.0;
    const DOWN: f32 = 14.0;
    let past_the_triangle = match branch {
        true => 0.0,
        false => STEP,
    };
    FIRST + DOWN * depth as f32 + past_the_triangle
}

/// A section's header, and whether its body should be drawn.
fn section(ui: &mut egui::Ui, title: &str, open: &mut bool) -> bool {
    panel_header(ui, title, Some(open), None);
    *open
}

/// Whether a click landed on the triangle, which opens the branch rather than picking
/// the row.
fn on_triangle(drawn: &Drawn) -> bool {
    let (Some(box_), Some(at)) = (drawn.chevron, drawn.response.interact_pointer_pos()) else {
        return false;
    };
    box_.expand(3.0).contains(at)
}

/// Turn one of the library's filters, and bring the library forward to show what it
/// left. A narrowing nobody can see is a narrowing that will surprise whoever finds it.
fn narrow(acts: &mut Vec<Act>, narrow: Narrow) {
    acts.push(Act::ShowTab(Spot::Library));
    acts.push(Act::Narrow(narrow));
}

/// A line where a branch has nothing to show.
fn nothing(ui: &mut egui::Ui, depth: usize, said: &str) {
    row(
        ui,
        false,
        &Cells {
            indent: indent(depth, false),
            name: said,
            faint: true,
            child: true,
            ..Cells::default()
        },
    );
}

/// Whether the kinds section is worth a section at all.
///
/// One kind is what everything in both places is, so there is nothing to choose between
/// and the rows would only narrow the library to what it already shows.
fn worth_choosing(kinds: &[Kind]) -> bool {
    kinds.len() > 1
}

/// The open-set key for one bank's rows.
pub(super) fn bank_branch(class: ObjectClass, bank: u64) -> Branch {
    Branch::Bank(class.to_raw(), bank)
}

/// What a local row's kind word needs from beyond the row: the families the list on this
/// computer spans, and the attached instrument's own.
///
/// Read once a frame rather than per row — every row asks the same question of the whole
/// list.
struct Naming {
    kept: Vec<Family>,
    instrument: Option<Family>,
}

/// Where a duplicate of a slot lands: the first slot of its own folder that a walk found
/// free and nothing is already waiting for.
///
/// ⚠️ The same exclusion a queued asset is placed by. Two writes handed one address are
/// one write.
fn spare_slot(device: &DeviceState, class: ObjectClass, queue: &Queue) -> Option<Location> {
    device.first_free(class, &queue.waiting_in(class))
}

/// Where a drop onto a row of the local list lands: the folder that row is drawn under,
/// or the loose part of the list.
pub(super) fn onto_list(folder: Option<u64>) -> Onto {
    match folder {
        Some(id) => Onto::Group(id),
        None => Onto::Computer,
    }
}

/// Whether a bank's own name says anything the number beside every row does not.
///
/// Programs come back called "Bank 1", "Bank 2" — a caption repeating the number the
/// location column already carries is a line of furniture. Pianos come back called
/// "Grand" and "Upright", which is the whole reason to show a caption at all.
fn worth_captioning(bank: u32, name: &str) -> bool {
    let name = name.trim();
    !name.is_empty()
        && name != bank.to_string()
        && !name.eq_ignore_ascii_case(&format!("bank {bank}"))
}

impl Browser {
    pub(super) fn tree(
        &mut self,
        ui: &mut egui::Ui,
        workspace: &Workspace,
        device: &Device,
        queue: &Queue,
        filter: &Filter,
        acts: &mut Vec<Act>,
    ) {
        egui::ScrollArea::vertical()
            .id_salt("browser_tree")
            .auto_shrink([false; 2])
            .show(ui, |ui| {
                let mut sections = self.sections;
                if section(ui, "places", &mut sections.places) {
                    self.places(ui, workspace, device, queue, filter, acts);
                }
                let kinds = kinds_present(workspace, &device.state);
                if worth_choosing(&kinds) && section(ui, "kinds", &mut sections.kinds) {
                    self.kinds(ui, &kinds, workspace, device, filter, acts);
                }
                if section(ui, "tags", &mut sections.tags) {
                    self.tag_rows(ui, workspace, device, filter, acts);
                }
                self.sections = sections;
                self.empty_below(ui);
            });
    }

    /// The room under the last row: a click there is a click on no row, which lets go of
    /// everything picked.
    fn empty_below(&mut self, ui: &mut egui::Ui) {
        let rest = ui.available_rect_before_wrap();
        if rest.height() <= 0.0 {
            return;
        }
        if ui
            .interact(rest, ui.id().with("tree_empty"), egui::Sense::click())
            .clicked()
        {
            self.selection.clear();
        }
    }

    fn twist(&mut self, branch: Branch) {
        if !self.open.remove(&branch) {
            self.open.insert(branch);
        }
    }

    /// Right-clicking a row nothing has picked picks it; right-clicking one that is
    /// already picked leaves the rest alone, so a menu acts on the whole selection.
    fn aim(&mut self, item: Item) {
        if !self.selection.holds(item) {
            self.select(item);
        }
    }

    #[allow(clippy::too_many_arguments)]
    fn places(
        &mut self,
        ui: &mut egui::Ui,
        workspace: &Workspace,
        device: &Device,
        queue: &Queue,
        filter: &Filter,
        acts: &mut Vec<Act>,
    ) {
        self.computer_row(ui, workspace, device, filter, acts);
        if self.open.contains(&Branch::Computer) {
            let naming = Naming {
                kept: super::families_present(workspace),
                instrument: device.state.product().and_then(Family::from_product),
            };
            for id in self.folder_ids() {
                self.folder_row(ui, id, workspace, device, queue, &naming, acts);
            }
            let loose: Vec<Item> = workspace
                .listed()
                .filter(|entity| self.folders.holding(entity.id).is_none())
                .map(|entity| Item::Local(entity.id))
                .collect();
            for entity in workspace.listed() {
                if self.folders.holding(entity.id).is_none() {
                    self.local_row(
                        ui, entity, None, &loose, workspace, device, queue, &naming, acts,
                    );
                }
            }
            if loose.is_empty() && self.folders.all().is_empty() {
                nothing(ui, 1, "Drop Nord files here, or use Open…");
            }
        }

        match device.state.connected() {
            true => self.instrument_rows(ui, workspace, device, queue, filter, acts),
            false => self.connect_row(ui, device, acts),
        }

        let counts = [
            queue.len(),
            crate::library::differing(workspace, &device.state, queue),
        ];
        let states = [
            (
                State::Waiting,
                Glyph::Upload,
                crate::app::warn(ui.visuals()),
            ),
            (
                State::Differs,
                Glyph::CircleAlert,
                crate::app::bad(ui.visuals()),
            ),
        ];
        for ((state, glyph, dot), count) in states.into_iter().zip(counts) {
            // A row that has gone to nothing stays while it is the one narrowing, so
            // there is always something left to click to widen the library again.
            let asked = Narrow::State(state);
            if count == 0 && !filter.on(asked) {
                continue;
            }
            let drawn = row(
                ui,
                filter.on(asked),
                &Cells {
                    indent: indent(0, false),
                    glyph: Some(glyph),
                    name: state.title(),
                    dot: Some((dot, state.sentence())),
                    count: Some(count.to_string()),
                    ..Cells::default()
                },
            );
            if drawn.response.on_hover_text(state.sentence()).clicked() {
                narrow(acts, asked);
            }
        }
    }

    fn computer_row(
        &mut self,
        ui: &mut egui::Ui,
        workspace: &Workspace,
        device: &Device,
        filter: &Filter,
        acts: &mut Vec<Act>,
    ) {
        let here = Narrow::Place(Place::Computer);
        let drawn = row(
            ui,
            filter.on(here),
            &Cells {
                indent: indent(0, true),
                open: Some(self.open.contains(&Branch::Computer)),
                glyph: Some(Glyph::LibraryBig),
                name: "This computer",
                count: Some(workspace.listed().count().to_string()),
                ..Cells::default()
            },
        );
        // The head of the branch takes a drop, so there is one target that is never
        // also a place a drag could have started from.
        self.drop_zone(ui, &drawn.response, Onto::Computer, acts);
        if drawn.response.clicked() {
            match on_triangle(&drawn) {
                true => self.twist(Branch::Computer),
                false => narrow(acts, here),
            }
        }
        let listed = Browser::standing_for(workspace, |_| true);
        drawn.response.context_menu(|ui| {
            self.set_menu(ui, &listed, workspace, device, acts, |_, ui, acts| {
                if ui.button("Open…").clicked() {
                    acts.push(Act::OpenFiles);
                    ui.close();
                }
                ui.menu_button("New", |ui| new_menu(ui, acts));
            });
        });
    }

    /// The row that stands in for an instrument until there is one.
    ///
    /// ⚠️ The click reaches `requestDevice()` inside the frame it landed in, which is
    /// what keeps the browser's transient user activation alive for it.
    fn connect_row(&mut self, ui: &mut egui::Ui, device: &Device, acts: &mut Vec<Act>) {
        if matches!(device.state.connection, Connection::Connecting) {
            nothing(ui, 0, "Looking for an instrument…");
            return;
        }
        let drawn = row(
            ui,
            false,
            &Cells {
                indent: indent(0, false),
                glyph: Some(Glyph::Keyboard),
                name: "Connect an instrument…",
                faint: true,
                ..Cells::default()
            },
        );
        if drawn
            .response
            .on_hover_text(
                "Close Nord Sound Manager first — it holds the instrument on its own, and \
                 nothing else can reach it alongside.\n\nIn a browser: Chrome or Edge only.",
            )
            .clicked()
        {
            acts.push(Act::Connect);
        }
    }

    /// The folders in the order they were made. Taken as ids so a row can change the
    /// list it is drawn from.
    fn folder_ids(&self) -> Vec<u64> {
        self.folders.all().iter().map(|folder| folder.id).collect()
    }

    #[allow(clippy::too_many_arguments)]
    fn folder_row(
        &mut self,
        ui: &mut egui::Ui,
        id: u64,
        workspace: &Workspace,
        device: &Device,
        queue: &Queue,
        naming: &Naming,
        acts: &mut Vec<Act>,
    ) {
        let item = Item::Folder(id);
        let Some(name) = self.folders.name_of(id).map(str::to_string) else {
            return;
        };
        let members: Vec<u64> = self
            .folders
            .members(id, workspace)
            .iter()
            .map(|entity| entity.id)
            .collect();
        let inside: Vec<Item> = members.iter().copied().map(Item::Local).collect();
        let mut open = self.open.contains(&Branch::Folder(id));

        if self.rename.as_ref().is_some_and(|r| r.what == item) {
            if let Some(name) = self.rename_row(ui, indent(1, true), &name) {
                acts.push(Act::RenameFolder { id, name });
            }
            // A folder is renamed with its contents in view: what is in it is what the
            // name is about.
            open = true;
        } else {
            let drawn = row(
                ui,
                self.selection.holds(item),
                &Cells {
                    indent: indent(1, true),
                    open: Some(open),
                    glyph: Some(Glyph::Folder),
                    name: &name,
                    count: Some(members.len().to_string()),
                    child: true,
                    ..Cells::default()
                },
            );
            self.drop_zone(ui, &drawn.response, Onto::Group(id), acts);
            if drawn.response.clicked() {
                match on_triangle(&drawn) {
                    true => self.twist(Branch::Folder(id)),
                    false => {
                        let list: Vec<Item> =
                            self.folder_ids().into_iter().map(Item::Folder).collect();
                        self.clicked(ui, Click { item, list: &list });
                    }
                }
            }
            drawn.response.context_menu(|ui| {
                self.aim(item);
                self.set_menu(ui, &inside, workspace, device, acts, |browser, ui, acts| {
                    if ui.button("Rename").clicked() {
                        browser.start_rename(item, &name);
                        ui.close();
                    }
                    if ui
                        .button("Remove folder")
                        .on_hover_text("what is in it goes back to the list; nothing is deleted")
                        .clicked()
                    {
                        acts.push(Act::RemoveFolder(id));
                        ui.close();
                    }
                });
            });
        }

        if !open {
            return;
        }
        if members.is_empty() {
            nothing(ui, 2, "empty — drag sounds in");
        }
        for entity in members.iter().filter_map(|id| workspace.get(*id)) {
            self.local_row(
                ui,
                entity,
                Some(id),
                &inside,
                workspace,
                device,
                queue,
                naming,
                acts,
            );
        }
    }

    #[allow(clippy::too_many_arguments)]
    fn local_row(
        &mut self,
        ui: &mut egui::Ui,
        entity: &LocalEntity,
        folder: Option<u64>,
        list: &[Item],
        workspace: &Workspace,
        device: &Device,
        queue: &Queue,
        naming: &Naming,
        acts: &mut Vec<Act>,
    ) {
        let item = Item::Local(entity.id);
        let kind = Kind::of(entity.entity.as_ref());
        let selected = self.selection.holds(item);
        let depth = match folder {
            Some(_) => 2,
            None => 1,
        };

        // While a name is being typed the row stops sensing anything: a drag sense over
        // the field would take the clicks that place the cursor in it.
        if self.rename.as_ref().is_some_and(|r| r.what == item) {
            if let Some(name) = self.rename_row(ui, indent(depth, false), &entity.name) {
                acts.push(Act::RenameLocal {
                    id: entity.id,
                    name,
                });
            }
            return;
        }

        let owed = queue.entry(entity.id).map(destination);
        let wears = self.tags.worn(entity.id).len();
        let word =
            crate::strings::kind_word(kind, qualifier(entity, &naming.kept, naming.instrument));
        let drawn = row(
            ui,
            selected,
            &Cells {
                indent: indent(depth, false),
                glyph: Some(kind.glyph()),
                name: &entity.name,
                note: owed.as_deref().or(Some(word.as_str())),
                unsaved: entity.is_unsaved(),
                dot: mark(entity, &device.state, queue, ui.visuals()),
                tags: wears,
                child: true,
                ..Cells::default()
            },
        );
        // ⚠️ The whole name is the row's own hover, where the row had to cut it. A second
        // one here shows it twice.
        let response = drawn.response;

        if response.dragged() {
            if let Some(head) = self.held(item, workspace, &device.state) {
                let carried = self.carrying(head, &entity.name, workspace, &device.state);
                egui::DragAndDrop::set_payload(ui.ctx(), carried);
            }
        }
        // A drop onto a row lands where that row is drawn, and is taken here so the
        // branch's own zone does not act on it a second time.
        self.drop_zone(ui, &response, onto_list(folder), acts);

        if response.double_clicked() {
            acts.push(Act::Open(item));
        } else if response.clicked() {
            self.clicked(ui, Click { item, list });
        }
        if self.sole_is(item) && ui.input(|i| i.key_pressed(egui::Key::F2)) {
            self.start_rename(item, &entity.name);
        }

        response.context_menu(|ui| self.menu(ui, item, workspace, device, queue, acts));
    }

    /// The menu a row standing for a set of assets offers: what can be asked of the
    /// whole set, then whatever can be asked of the row itself.
    ///
    /// One builder for the folder, tag, kind, place and class rows. They differ in which
    /// assets they stand for and in what the row itself can be told to do; between those
    /// two they offer the same things, dead for the same reasons and labelled the same
    /// way.
    fn set_menu(
        &mut self,
        ui: &mut egui::Ui,
        members: &[Item],
        workspace: &Workspace,
        device: &Device,
        acts: &mut Vec<Act>,
        own: impl FnOnce(&mut Browser, &mut egui::Ui, &mut Vec<Act>),
    ) {
        for action in [Bulk::Queue, Bulk::Export] {
            self.bulk_item(ui, action, members, workspace, &device.state, acts);
        }
        ui.separator();
        own(self, ui, acts);
    }

    /// The assets on this computer a row stands for, in the order the list holds them.
    fn standing_for(workspace: &Workspace, keep: impl Fn(&LocalEntity) -> bool) -> Vec<Item> {
        workspace
            .listed()
            .filter(|entity| keep(entity))
            .map(|entity| Item::Local(entity.id))
            .collect()
    }

    /// The menu a row offers, wherever it is drawn — the tree, or the library table.
    ///
    /// A row inside a checked set of several offers what the library's footer offers,
    /// because the menu is about the set rather than about the row under the pointer.
    ///
    /// A folder and a tag are rows of the tree alone; their menus stay with the rows
    /// that draw them.
    pub fn menu(
        &mut self,
        ui: &mut egui::Ui,
        item: Item,
        workspace: &Workspace,
        device: &Device,
        queue: &Queue,
        acts: &mut Vec<Act>,
    ) {
        self.aim(item);
        let checked: Vec<Item> = self.selection.items().collect();
        if checked.len() > 1 && self.selection.holds(item) {
            for action in Bulk::ALL {
                self.bulk_item(ui, action, &checked, workspace, &device.state, acts);
            }
            return;
        }
        match item {
            Item::Local(id) => self.local_menu(ui, id, workspace, device, acts),
            Item::Slot { class, at } => self.slot_menu(ui, class, at, device, queue, acts),
            Item::Folder(_) | Item::Tag(_) => {}
        }
    }

    fn local_menu(
        &mut self,
        ui: &mut egui::Ui,
        id: u64,
        workspace: &Workspace,
        device: &Device,
        acts: &mut Vec<Act>,
    ) {
        let Some(entity) = workspace.get(id) else {
            return;
        };
        let item = Item::Local(id);
        let picked = self.selection.locals();
        if ui.button("Open").clicked() {
            acts.push(Act::Open(item));
            ui.close();
        }
        self.bulk_item(ui, Bulk::Queue, &[item], workspace, &device.state, acts);
        if ui.button("Export…").clicked() {
            acts.push(Act::Export(id));
            ui.close();
        }
        if ui.button("Rename").clicked() {
            self.start_rename(item, &entity.name);
            ui.close();
        }
        if ui.button("Duplicate").clicked() {
            acts.push(Act::DuplicateLocal(id));
            ui.close();
        }
        self.filing_menu(ui, id, self.folders.holding(id), acts);
        ui.menu_button("Tag", |ui| self.tag_items(ui, &picked, acts));
        if ui
            .button("Save as gig…")
            .on_hover_text("what is picked, under a tag of its own")
            .clicked()
        {
            acts.push(Act::SaveAsGig);
            ui.close();
        }
        ui.separator();
        if ui.button("Remove from list").clicked() {
            acts.push(Act::Remove(id));
            ui.close();
        }
    }

    /// Where an asset can be put, for the operators who would rather pick than drag.
    fn filing_menu(&self, ui: &mut egui::Ui, id: u64, filed: Option<u64>, acts: &mut Vec<Act>) {
        if self.folders.all().is_empty() {
            return;
        }
        ui.menu_button("Move to folder", |ui| {
            for folder in self.folders.all() {
                if marked(ui, &folder.name, filed == Some(folder.id), None) {
                    acts.push(Act::File {
                        id,
                        folder: Some(folder.id),
                    });
                }
            }
            ui.separator();
            if ui
                .add_enabled(filed.is_some(), egui::Button::new("Out of any folder"))
                .clicked()
            {
                acts.push(Act::File { id, folder: None });
                ui.close();
            }
        });
    }

    /// Every tag, checked where it is on everything picked, and one more.
    ///
    /// The items alone, so the row's own menu and the library's footer can each put
    /// their own label over them.
    pub fn tag_items(&self, ui: &mut egui::Ui, picked: &[u64], acts: &mut Vec<Act>) {
        for tag in self.tags.all() {
            let on = self.tags.on_all(picked, tag.id);
            if marked(ui, &tag.name, on, None) {
                let ids = picked.to_vec();
                acts.push(match on {
                    true => Act::Untag { ids, tag: tag.id },
                    false => Act::Tag { ids, tag: tag.id },
                });
            }
        }
        if !self.tags.all().is_empty() {
            ui.separator();
        }
        if ui.button("New tag…").clicked() {
            acts.push(Act::SaveAsGig);
            ui.close();
        }
    }

    #[allow(clippy::too_many_arguments)]
    fn instrument_rows(
        &mut self,
        ui: &mut egui::Ui,
        workspace: &Workspace,
        device: &Device,
        queue: &Queue,
        filter: &Filter,
        acts: &mut Vec<Act>,
    ) {
        let Some(product) = device.state.product().map(str::to_string) else {
            return;
        };
        let held = occupancy(
            ObjectClass::Program,
            &device.state.inventory,
            device.state.allocation_unit(ObjectClass::Program),
        );
        let drawn = row(
            ui,
            filter.on(Narrow::Place(Place::Keyboard)),
            &Cells {
                indent: indent(0, true),
                open: Some(self.open.contains(&Branch::Instrument)),
                glyph: Some(Glyph::Keyboard),
                name: &product,
                dot: Some((crate::app::good(ui.visuals()), "attached")),
                count: held,
                ..Cells::default()
            },
        );
        let response = drawn
            .response
            .clone()
            .on_hover_text("attached; the count is its programs");
        if response.clicked() {
            match on_triangle(&drawn) {
                true => self.twist(Branch::Instrument),
                // ⚠️ Not [`narrow`]: the instrument's own tab is what this row opens, so
                // the narrowing it asks for is already in front.
                false => {
                    acts.push(Act::ShowTab(Spot::Keyboard));
                    acts.push(Act::Narrow(Narrow::Place(Place::Keyboard)));
                }
            }
        }
        let reading = device
            .state
            .classes()
            .into_iter()
            .filter_map(|class| device.state.scan.progress(class))
            .any(|progress| progress.running);
        // The label states what the batch would do, so it counts what the batch takes:
        // an entry this instrument has already refused is not one of them.
        let waiting = will_write(queue).count();
        // What this row stands for on this computer: everything that came off a slot of
        // the instrument it names.
        let off_it = Browser::standing_for(workspace, |entity| entity.spot().is_some());
        drawn.response.context_menu(|ui| {
            self.set_menu(ui, &off_it, workspace, device, acts, |_, ui, acts| {
                if ui
                    .add_enabled(!reading, egui::Button::new("Read everything again"))
                    .on_disabled_hover_text("already reading")
                    .clicked()
                {
                    acts.push(Act::Resync);
                    ui.close();
                }
                if waiting > 0 && ui.button(format!("Send all ({waiting})")).clicked() {
                    acts.push(Act::AskSendAll);
                    ui.close();
                }
                ui.separator();
                if ui.button("Disconnect").clicked() {
                    acts.push(Act::Disconnect);
                    ui.close();
                }
            });
        });

        if !self.open.contains(&Branch::Instrument) {
            return;
        }
        // The slots something is looking at right now, which the list on this computer
        // deliberately does not show.
        let viewed: Vec<(ObjectClass, Location)> = workspace
            .entities()
            .iter()
            .filter(|entity| !entity.kept)
            .filter_map(|entity| entity.origin.slot())
            .collect();
        for class in device.state.classes() {
            self.class_row(ui, device, class, &viewed, workspace, queue, acts);
        }
    }

    #[allow(clippy::too_many_arguments)]
    fn class_row(
        &mut self,
        ui: &mut egui::Ui,
        device: &Device,
        class: ObjectClass,
        viewed: &[(ObjectClass, Location)],
        workspace: &Workspace,
        queue: &Queue,
        acts: &mut Vec<Act>,
    ) {
        // A jump wins over whatever the branch was left in: the point of it is to reach
        // a slot that is inside something closed.
        if let Some((held, at)) = self.jump.filter(|(held, _)| *held == class) {
            self.open.insert(Branch::Class(class.to_raw()));
            self.open.insert(bank_branch(held, at.user_bank()));
        }
        let open = self.open.contains(&Branch::Class(class.to_raw()));
        let progress = device.state.scan.progress(class);
        let count = match progress {
            Some(p) if p.running => Some(match p.total {
                Some(total) => format!("{} of {total}", p.done + 1),
                None => "reading…".to_string(),
            }),
            _ => occupancy(
                class,
                &device.state.inventory,
                device.state.allocation_unit(class),
            ),
        };
        let drawn = row(
            ui,
            false,
            &Cells {
                indent: indent(1, true),
                open: Some(open),
                glyph: Some(Kind::from_class(class).glyph()),
                name: device.state.folder_name(class),
                note: read_only(class).then_some("read only"),
                count,
                child: true,
                ..Cells::default()
            },
        );
        if drawn.response.clicked() {
            match on_triangle(&drawn) {
                true => self.twist(Branch::Class(class.to_raw())),
                false => acts.push(Act::ShowClass(class)),
            }
        }
        let focus = device.state.focused(class);
        let off_it = Browser::standing_for(workspace, |entity| {
            entity.spot().is_some_and(|(held, _)| held == class)
        });
        drawn.response.context_menu(|ui| {
            self.set_menu(ui, &off_it, workspace, device, acts, |browser, ui, acts| {
                if ui
                    .button("Read this folder again")
                    .on_hover_text(
                        "Read everything reads the whole instrument; this reads one folder",
                    )
                    .clicked()
                {
                    acts.push(Act::ReadAgain(class));
                    ui.close();
                }
                if let Some(at) = focus {
                    if ui
                        .button("Go to loaded")
                        .on_hover_text(format!("the panel is on {}", shown(at)))
                        .clicked()
                    {
                        browser.jump = Some((class, at));
                        ui.close();
                    }
                }
            });
        });

        // ⚠️ A jump at a slot the walk has never reached would hold the branch open for
        // as long as the instrument stays attached: nothing draws the row that clears it.
        if self
            .jump
            .is_some_and(|(held, at)| held == class && device.state.slot(class, at).is_none())
        {
            self.jump = None;
        }
        if !open {
            return;
        }
        let banks = device.state.banks_of(class);
        if banks.is_empty() {
            nothing(ui, 2, "nothing read yet");
        }
        // The live buffer and the settings singleton divide into one bank.
        let cut = banks.len() > 1;
        for bank in banks {
            self.bank_rows(ui, device, class, bank, cut, viewed, workspace, queue, acts);
        }
    }

    /// One bank, as a branch over its own slots.
    ///
    /// ⚠️ A container in the browser and a numbering everywhere else. The instrument has
    /// no folders inside a class — a location is a bank and a slot and that is all — but
    /// four hundred rows in one run is a tree nobody can navigate, so the numbering is
    /// what the list is cut on. A bank the device named says so in its row; for pianos
    /// those names are the panel's categories.
    #[allow(clippy::too_many_arguments)]
    fn bank_rows(
        &mut self,
        ui: &mut egui::Ui,
        device: &Device,
        class: ObjectClass,
        bank: u32,
        cut: bool,
        viewed: &[(ObjectClass, Location)],
        workspace: &Workspace,
        queue: &Queue,
        acts: &mut Vec<Act>,
    ) {
        let Some(slots) = device.state.bank(class, bank) else {
            return;
        };
        let count = slots.len();
        let held = slots.iter().filter(|slot| slot.is_some()).count();
        let list: Vec<Item> = device
            .state
            .slots_of(class, bank)
            .map(|(at, _)| Item::Slot { class, at })
            .collect();

        let depth = match cut {
            true => 3,
            false => 2,
        };
        if cut {
            let name = device
                .state
                .bank_name(class, bank)
                .filter(|name| worth_captioning(bank, name))
                .map(|name| format!("{bank} · {name}"))
                .unwrap_or_else(|| format!("Bank {bank}"));
            let drawn = row(
                ui,
                false,
                &Cells {
                    indent: indent(2, true),
                    open: Some(self.open.contains(&bank_branch(class, u64::from(bank)))),
                    glyph: Some(Glyph::Folder),
                    name: &name,
                    count: Some(format!("{held}/{count}")),
                    child: true,
                    ..Cells::default()
                },
            );
            if drawn.response.clicked() {
                self.twist(bank_branch(class, u64::from(bank)));
            }
            if !self.open.contains(&bank_branch(class, u64::from(bank))) {
                return;
            }
        }
        for item in &list {
            let Item::Slot { at, .. } = item else {
                continue;
            };
            self.slot_row(
                ui, device, class, *at, depth, &list, viewed, workspace, queue, acts,
            );
        }
    }

    #[allow(clippy::too_many_arguments)]
    fn slot_row(
        &mut self,
        ui: &mut egui::Ui,
        device: &Device,
        class: ObjectClass,
        at: Location,
        depth: usize,
        list: &[Item],
        viewed: &[(ObjectClass, Location)],
        workspace: &Workspace,
        queue: &Queue,
        acts: &mut Vec<Act>,
    ) {
        let held = device
            .state
            .slot(class, at)
            .flatten()
            .map(|info| info.name.trim().to_string());
        let item = Item::Slot { class, at };
        let selected = self.selection.holds(item);

        // While a name is being typed the row stops sensing anything: a drag sense over
        // the field would take the clicks that place the cursor in it.
        if self.rename.as_ref().is_some_and(|r| r.what == item) {
            let was = held.clone().unwrap_or_default();
            if let Some(name) = self.rename_row(ui, indent(depth, false), &was) {
                acts.push(Act::RenameSlot { class, at, name });
            }
            return;
        }

        let loaded = device.state.focused(class) == Some(at);
        // A slot open as a view says so here, because the tab strip cannot: what a tab
        // shows is the document's name, and a view's name is the slot's own.
        let viewing = viewed.contains(&(class, at));
        let drawn = row(
            ui,
            selected,
            &Cells {
                indent: indent(depth, false),
                glyph: Some(Kind::from_class(class).glyph()),
                at: Some(shown(at)),
                name: held.as_deref().unwrap_or("empty"),
                note: viewing.then_some("open"),
                faint: held.is_none(),
                loaded,
                child: true,
                ..Cells::default()
            },
        );
        let mut response = drawn.response;
        if loaded {
            response = response.on_hover_text("on the instrument's panel now");
        }
        if viewing {
            response = response
                .on_hover_text("open in a tab as a view of this slot — it is not on this computer");
        }
        // A jump can scroll only after the branches holding this row have opened.
        if self.jump == Some((class, at)) {
            self.jump = None;
            self.selection.only(item);
            response.scroll_to_me(Some(egui::Align::Center));
        }

        // ⚠️ A partition this app cannot name is listed and nothing more.
        let fetchable = !read_only(class);

        if let Some(name) = &held {
            if response.dragged() {
                if let Some(head) = self.held(item, workspace, &device.state) {
                    let carried = self.carrying(head, name, workspace, &device.state);
                    egui::DragAndDrop::set_payload(ui.ctx(), carried);
                }
            }
        }
        self.drop_zone(ui, &response, Onto::Slot { class, at }, acts);

        if response.double_clicked() {
            if held.is_some() && fetchable {
                acts.push(Act::Open(item));
            }
        } else if response.clicked() {
            self.clicked(ui, Click { item, list });
        }
        if let Some(name) = &held {
            if fetchable && self.sole_is(item) && ui.input(|i| i.key_pressed(egui::Key::F2)) {
                self.start_rename(item, name);
            }
        }

        if held.is_none() {
            return;
        }
        response.context_menu(|ui| self.menu(ui, item, workspace, device, queue, acts));
    }

    /// What a slot offers. A vacant one offers nothing, so nothing is drawn for it.
    fn slot_menu(
        &mut self,
        ui: &mut egui::Ui,
        class: ObjectClass,
        at: Location,
        device: &Device,
        queue: &Queue,
        acts: &mut Vec<Act>,
    ) {
        let Some(name) = device
            .state
            .slot(class, at)
            .flatten()
            .map(|info| info.name.trim().to_string())
        else {
            return;
        };
        // ⚠️ A partition this app cannot name is listed and nothing more.
        if read_only(class) {
            ui.label(egui::RichText::new("Nothing here knows what this folder holds.").weak());
            return;
        }
        let item = Item::Slot { class, at };
        let free = spare_slot(&device.state, class, queue);
        if ui
            .button("Open")
            .on_hover_text("a view of this slot; nothing joins the list on this computer")
            .clicked()
        {
            acts.push(Act::Open(item));
            ui.close();
        }
        if ui.button("Copy to this computer").clicked() {
            acts.push(Act::Copy { class, at });
            ui.close();
        }
        if ui.button("Load on instrument").clicked() {
            acts.push(Act::LoadOnInstrument { class, at });
            ui.close();
        }
        ui.separator();
        if ui.button("Rename").clicked() {
            self.start_rename(item, &name);
            ui.close();
        }
        if ui
            .add_enabled(free.is_some(), egui::Button::new("Duplicate"))
            .on_disabled_hover_text("every slot read so far is taken or already spoken for")
            .clicked()
        {
            if let Some(to) = free {
                acts.push(Act::DuplicateSlot {
                    class,
                    from: at,
                    to,
                });
            }
            ui.close();
        }
        ui.separator();
        if ui.button("Delete…").clicked() {
            self.ask = Some(Ask {
                title: format!("Delete “{name}” from {}?", place(class, at)),
                note: Some("It is removed from the instrument. There is no undo.".into()),
                verb: "Delete",
                acts: vec![Act::DeleteSlot { class, at }],
            });
            ui.close();
        }
    }

    fn kinds(
        &mut self,
        ui: &mut egui::Ui,
        kinds: &[Kind],
        workspace: &Workspace,
        device: &Device,
        filter: &Filter,
        acts: &mut Vec<Act>,
    ) {
        for kind in kinds.iter().copied() {
            let asked = Narrow::Kind(kind);
            let drawn = row(
                ui,
                filter.on(asked),
                &Cells {
                    indent: indent(0, false),
                    glyph: Some(kind.glyph()),
                    name: kind.plural(),
                    ..Cells::default()
                },
            );
            if drawn.response.clicked() {
                narrow(acts, asked);
            }
            let of_it =
                Browser::standing_for(workspace, |entity| Kind::of(entity.entity.as_ref()) == kind);
            drawn.response.context_menu(|ui| {
                self.set_menu(ui, &of_it, workspace, device, acts, |_, _, _| {});
            });
        }
    }

    fn tag_rows(
        &mut self,
        ui: &mut egui::Ui,
        workspace: &Workspace,
        device: &Device,
        filter: &Filter,
        acts: &mut Vec<Act>,
    ) {
        for id in self.tag_ids() {
            let item = Item::Tag(id);
            let Some(name) = self.tags.name_of(id).map(str::to_string) else {
                continue;
            };
            if self.rename.as_ref().is_some_and(|r| r.what == item) {
                if let Some(name) = self.rename_row(ui, indent(0, false), &name) {
                    acts.push(Act::RenameTag { id, name });
                }
                continue;
            }
            let asked = Narrow::Tag(id);
            let drawn = row(
                ui,
                filter.on(asked),
                &Cells {
                    indent: indent(0, false),
                    glyph: Some(Glyph::Tag),
                    name: &name,
                    count: Some(self.tags.count(id).to_string()),
                    ..Cells::default()
                },
            );
            if drawn.response.clicked() {
                narrow(acts, asked);
            }
            let wearing =
                Browser::standing_for(workspace, |entity| self.tags.worn(entity.id).contains(&id));
            drawn.response.context_menu(|ui| {
                self.aim(item);
                self.set_menu(
                    ui,
                    &wearing,
                    workspace,
                    device,
                    acts,
                    |browser, ui, acts| {
                        if ui.button("Rename").clicked() {
                            browser.start_rename(item, &name);
                            ui.close();
                        }
                        if ui
                            .button("Remove tag")
                            .on_hover_text("it comes off everything wearing it; nothing is deleted")
                            .clicked()
                        {
                            acts.push(Act::RemoveTag(id));
                            ui.close();
                        }
                    },
                );
            });
        }
        let drawn = row(
            ui,
            false,
            &Cells {
                indent: indent(0, false),
                glyph: Some(Glyph::Plus),
                name: "new tag",
                faint: true,
                ..Cells::default()
            },
        );
        if drawn.response.clicked() {
            acts.push(Act::NewTag("New tag".into()));
        }
    }

    fn tag_ids(&self) -> Vec<u64> {
        self.tags.all().iter().map(|tag| tag.id).collect()
    }
}

/// The dot a local row wears, in its own ink and its own words.
fn mark(
    entity: &LocalEntity,
    device: &DeviceState,
    queue: &Queue,
    visuals: &egui::Visuals,
) -> Option<(egui::Color32, &'static str)> {
    let mark = crate::library::keyboard_mark(entity, device, queue)?;
    Some((
        crate::library::mark_ink(mark, visuals),
        crate::library::mark_words(mark),
    ))
}

/// Where a queued asset is going, for the note that says so.
fn destination(held: &Queued) -> String {
    format!("{}", place(held.class, held.at))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::browser::act::apply;
    use crate::browser::bench::{bench, context, words};
    use crate::shell::Shell;

    /// ⚠️ Everything laid out from audio is on the one New menu. A pick of WAVs makes
    /// any of them, and a menu offering only some hides what the dialog does.
    #[test]
    fn the_new_menu_offers_everything_a_pick_of_wavs_makes() {
        let ctx = context();
        let output = ctx.run(egui::RawInput::default(), |ctx| {
            egui::CentralPanel::default().show(ctx, |ui| new_menu(ui, &mut Vec::new()));
        });
        let said = words(&output);
        for making in Making::FROM_WAVS {
            let item = making.item().0;
            assert!(said.iter().any(|word| word == item), "{item} is missing");
        }
        assert!(said.iter().any(|word| word == "New folder"));
    }

    /// ⚠️ A row says what a sound is called, not what file it is in. The name the
    /// workspace holds keeps its format tag; only the paint drops it.
    #[test]
    fn a_row_paints_its_name_without_the_format_tag() {
        let (mut browser, mut workspace, device, _tabs, queue, mut log) = bench();
        let id = workspace.create(Fresh::Program, &mut log).unwrap();
        workspace.rename(id, "Africa Split.ne5p".into());

        let ctx = workspace.ctx().clone();
        let output = ctx.run(egui::RawInput::default(), |ctx| {
            egui::SidePanel::left("browser")
                .exact_width(crate::shell::BROWSER)
                .show(ctx, |ui| {
                    browser.ui(ui, &workspace, &device, &queue, &Filter::default());
                });
        });

        let said = words(&output);
        assert!(said.iter().any(|word| word == "Africa Split"), "{said:?}");
        assert!(!said.iter().any(|word| word.contains(".ne5p")), "{said:?}");
        assert_eq!(workspace.get(id).unwrap().name, "Africa Split.ne5p");
    }

    /// ⚠️ A filter turned while a document is in front narrows a table nobody is looking
    /// at. Every row of the tree that narrows brings the library forward with it.
    #[test]
    fn narrowing_the_library_brings_it_forward() {
        for asked in [
            Narrow::Kind(Kind::Program),
            Narrow::Tag(1),
            Narrow::Place(Place::Computer),
            Narrow::State(State::Waiting),
            Narrow::State(State::Differs),
        ] {
            let (mut browser, mut workspace, mut device, mut tabs, mut queue, mut log) = bench();
            let mut shell = Shell::default();
            let id = workspace.create(Fresh::Program, &mut log).unwrap();
            tabs.open(id);

            let mut acts = Vec::new();
            narrow(&mut acts, asked);
            apply(
                &mut browser,
                &mut shell,
                acts,
                &mut workspace,
                &mut device,
                &mut tabs,
                &mut queue,
                &mut log,
            );
            assert!(shell.filter.on(asked), "{asked:?}");
            assert_eq!(tabs.showing(), Some(Spot::Library), "{asked:?}");
        }
    }

    /// ⚠️ A place row narrows the library like a kind or a tag row, so it reads as on
    /// like one. Without it nothing in the window says where the narrowing came from.
    #[test]
    fn the_place_row_reads_as_on_while_the_library_is_over_that_place() {
        fn selections(shape: &egui::Shape, want: egui::Color32) -> usize {
            match shape {
                egui::Shape::Rect(drawn) => usize::from(drawn.fill == want),
                egui::Shape::Vec(shapes) => {
                    shapes.iter().map(|shape| selections(shape, want)).sum()
                }
                _ => 0,
            }
        }

        let ctx = context();
        let (mut browser, workspace, device, _tabs, queue, _log) = bench();
        let lit = ctx.style().visuals.selection.bg_fill;
        let mut on = |filter: &Filter| -> usize {
            let output = ctx.run(egui::RawInput::default(), |ctx| {
                egui::SidePanel::left("places")
                    .exact_width(crate::shell::BROWSER)
                    .show(ctx, |ui| {
                        browser.ui(ui, &workspace, &device, &queue, filter);
                    });
            });
            output
                .shapes
                .iter()
                .map(|clipped| selections(&clipped.shape, lit))
                .sum()
        };

        assert_eq!(on(&Filter::default()), 0, "nothing is narrowed to a place");
        let mut filter = Filter::default();
        filter.narrow(Narrow::Place(Place::Computer));
        assert_eq!(on(&filter), 1, "This computer is the one row lit");
    }

    /// The kinds row list is what the two places actually hold, in one order. A row for
    /// a kind neither place holds narrows the library to nothing.
    #[test]
    fn the_kinds_section_lists_the_union_of_the_two_places() {
        let (_browser, mut workspace, mut device, _tabs, _queue, mut log) = bench();
        workspace.create(Fresh::Program, &mut log).unwrap();
        let alone = kinds_present(&workspace, &device.state);
        assert_eq!(alone, [Kind::Program]);
        assert!(!worth_choosing(&alone), "nothing to choose between");

        device.pretend_partitions(&crate::device::ELECTRO5);
        workspace.create(Fresh::Stage4Synth, &mut log).unwrap();
        assert_eq!(
            kinds_present(&workspace, &device.state),
            [
                Kind::Program,
                Kind::SetList,
                Kind::Sample,
                Kind::Piano,
                Kind::Live,
                Kind::Settings,
                Kind::Synth,
            ],
            "the instrument's six folders and what is on this computer, in one order"
        );
        assert!(worth_choosing(&kinds_present(&workspace, &device.state)));
    }

    /// ⚠️ The row that turns a narrowing off goes with the kind. A filter left pointing
    /// at a kind that is nowhere shows an empty table with nothing to click to refill it.
    #[test]
    fn a_kind_that_leaves_the_union_stops_narrowing() {
        let (_browser, workspace, mut device, _tabs, _queue, _log) = bench();
        let mut filter = Filter::default();
        device.pretend_partitions(&crate::device::ELECTRO5);
        filter.narrow(Narrow::Kind(Kind::Piano));
        filter.keep_kinds(&kinds_present(&workspace, &device.state));
        assert_eq!(filter.kind, Some(Kind::Piano));

        device.pretend(crate::device::DeviceEvent::Disconnected { lost: false });
        device.poll(
            &mut crate::log::Log::default(),
            &mut Workspace::new(context()),
            &mut crate::tabs::Tabs::default(),
            &mut Queue::default(),
        );
        filter.keep_kinds(&kinds_present(&workspace, &device.state));
        assert_eq!(filter.kind, None, "the instrument took its folders with it");
    }

    /// ⚠️ A duplicate goes where nothing else is going. A slot something in the queue is
    /// already bound for is spoken for, and two writes handed one address are one write.
    #[test]
    fn a_duplicate_lands_past_the_slot_the_queue_is_bound_for() {
        let (_browser, mut workspace, mut device, _tabs, mut queue, mut log) = bench();
        let class = ObjectClass::Program;
        device.pretend_scanned(class, 7, &["Africa Split", "", ""]);
        let id = workspace.create(Fresh::Program, &mut log).unwrap();
        assert_eq!(
            spare_slot(&device.state, class, &queue),
            Some(Location::from_user(7, 2))
        );

        crate::queue::enqueue(
            &workspace,
            &mut device,
            &mut queue,
            &mut log,
            id,
            class,
            Location::from_user(7, 2),
        );
        assert_eq!(
            spare_slot(&device.state, class, &queue),
            Some(Location::from_user(7, 3)),
            "7:2 is already waiting for something"
        );
    }

    /// A caption earns its line by saying something the location column does not. The
    /// piano categories do; "Bank 1" over the rows already labelled `1:…` does not.
    #[test]
    fn a_bank_caption_only_shows_what_the_number_does_not_say() {
        assert!(worth_captioning(1, "Grand"));
        assert!(worth_captioning(2, "Upright"));
        for furniture in ["Bank 1", "bank 1", "BANK 1", "1", " ", ""] {
            assert!(!worth_captioning(1, furniture), "{furniture:?}");
        }
        // The number has to match to be redundant — "Bank 2" over bank 1 is worth saying,
        // because one of the two is wrong and hiding it would hide that.
        assert!(worth_captioning(1, "Bank 2"));
    }

    /// ⚠️ A leaf's glyph lines up under the glyph of the branch beside it, because a
    /// leaf's indent already carries the triangle's box that a branch's does not.
    #[test]
    fn a_leaf_starts_where_the_branch_beside_it_puts_its_glyph() {
        assert_eq!(indent(0, true), 8.0);
        assert_eq!(indent(0, false), 26.0);
        assert_eq!(indent(1, false), 40.0);
        for depth in 0..4 {
            assert_eq!(
                indent(depth, false),
                indent(depth, true) + STEP,
                "depth {depth}"
            );
            assert!(indent(depth + 1, true) > indent(depth, true));
        }
    }
}