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
//! Everything the engineering build showed: the field table, and the record beside it.
//!
//! Nothing here is a control but the table. The rest is the record: what the container
//! says, what the bytes did, and — for something read off the instrument — what the
//! instrument says about the slot it came from.

use eframe::egui;
use nord_format::fields::Field;
use nord_usb::{Location, ObjectClass};

use super::controls::{self, Sets};
use super::field;
use crate::app;
use crate::device::{Device, DeviceCmd};
use crate::fields::{byte_diff, DiffRow};
use crate::icon::{icon, Glyph};
use crate::strings;
use crate::workspace::LocalEntity;

/// A read the Meta face asked the instrument for.
pub struct SlotDetails {
    pub class: ObjectClass,
    pub at: Location,
}

/// The table's columns, left to right. Wide enough for the longest of each in an ne5
/// body, and fixed rather than reflowing: a path is long, a body has hundreds of them,
/// and a column that moves per row cannot be read down.
const COLUMNS: [(&str, f32); 6] = [
    ("Path", 250.0),
    ("Bits", 74.0),
    ("Control", 110.0),
    ("Raw", 150.0),
    ("Writes · editable", 140.0),
    ("", 20.0),
];

/// One row of it, and the page's own left margin.
const ROW: f32 = 22.0;
const PAD: f32 = 12.0;
const MONO: f32 = 10.5;
const HEAD: f32 = 9.0;

/// A cell being typed into, and what the library said about it last.
#[derive(Default)]
struct Cell {
    path: String,
    text: String,
    /// The first frame the cell is open, so focus is taken once.
    fresh: bool,
    /// The library's refusal. While it is set the cell stays in edit.
    error: Option<String>,
}

#[derive(Default)]
pub struct Advanced {
    /// Narrows the table by path or label. A body has ninety fields.
    filter: String,
    cell: Cell,
    /// The id and the [`LocalEntity::stamp`] the cached dump was laid out from.
    ///
    /// ⚠️ `{:#?}` over an undecoded body prints every byte, and a piano library is
    /// hundreds of megabytes — it is rendered once per set of bytes, never per frame.
    dump_for: Option<(u64, u64)>,
    dump: String,
    /// The asset and the two sets of bytes the cached diff is a comparison of.
    ///
    /// ⚠️ `byte_diff` walks both bodies. The Metadata face asks for it on every frame
    /// it is up, and a piano library is hundreds of megabytes — it is walked once per
    /// pair of bodies.
    diff_for: Option<(u64, u64, u64)>,
    diff: Vec<DiffRow>,
}

impl Advanced {
    /// What the file says about itself: the same facts the document was built from,
    /// read here and never written differently.
    pub fn about(ui: &mut egui::Ui, rows: &[(&'static str, String, String)]) {
        let quiet = app::caption(ui.visuals());
        controls::heading(
            ui,
            "About this file",
            "what the file says about itself",
            None,
        );
        for (label, value, note) in rows {
            ui.horizontal(|ui| {
                ui.add_space(PAD);
                ui.spacing_mut().item_spacing.x = 10.0;
                ui.add_sized(
                    [110.0, ROW],
                    egui::Label::new(
                        egui::RichText::new(*label)
                            .font(egui::FontId::proportional(11.0))
                            .color(ui.visuals().weak_text_color()),
                    )
                    .halign(egui::Align::LEFT),
                );
                ui.label(
                    egui::RichText::new(value)
                        .font(egui::FontId::monospace(11.0))
                        .color(ui.visuals().text_color()),
                );
                if !note.is_empty() {
                    ui.add(
                        egui::Label::new(
                            egui::RichText::new(note)
                                .font(egui::FontId::proportional(10.0))
                                .color(quiet),
                        )
                        .truncate(),
                    );
                }
            });
        }
    }

    /// The whole body as a table: every field the library declares, engineering-only
    /// ones included, each value editable by the spelling `set_field` takes.
    ///
    /// This is the engineer's view, so nothing is hidden and nothing is prettied up: an
    /// unrecognised value is spelled `unknown (9)` here and that spelling is accepted
    /// back, and a field the Edit face does not draw is a row like any other, flagged
    /// for what it is.
    pub fn table(&mut self, ui: &mut egui::Ui, table: &Table<'_>, sets: &mut Sets) {
        let quiet = app::caption(ui.visuals());
        let rows: Vec<&Field> = table
            .fields
            .iter()
            .filter(|field| self.matches(field))
            .collect();
        let unseen = rows
            .iter()
            .filter(|field| !table.shows(&field.path))
            .count();
        controls::heading(
            ui,
            "Every field",
            "registry order · raw is what was read; type in Writes to change it — the value \
             is taken as spelled, refused if the field cannot hold it",
            Some((
                &format!(
                    "{} of {} rows · {unseen} hidden from Edit",
                    rows.len(),
                    table.fields.len()
                ),
                quiet,
            )),
        );
        ui.horizontal(|ui| {
            ui.add_space(PAD);
            ui.label(egui::RichText::new("Filter").small().color(quiet));
            ui.add(
                egui::TextEdit::singleline(&mut self.filter)
                    .desired_width(200.0)
                    .hint_text("path or name"),
            );
        });
        ui.add_space(4.0);

        ui.horizontal(|ui| {
            ui.add_space(PAD);
            ui.spacing_mut().item_spacing.x = 10.0;
            for (head, width) in COLUMNS {
                ui.add_sized(
                    [width, 14.0],
                    egui::Label::new(
                        egui::RichText::new(head.to_uppercase())
                            .font(egui::FontId::proportional(HEAD))
                            .color(quiet),
                    )
                    .halign(egui::Align::LEFT),
                );
            }
        });
        ui.separator();

        // Declaration order, which is the order the body is laid out in.
        for field in rows {
            self.row(ui, field, table, sets);
        }
    }

    fn row(&mut self, ui: &mut egui::Ui, field: &Field, table: &Table<'_>, sets: &mut Sets) {
        let visuals = ui.visuals().clone();
        let changed = table.changed.contains(&field.path);
        let hidden = !table.shows(&field.path);
        let labelled = strings::known(&field.path);
        let (rect, response) =
            ui.allocate_exact_size(egui::vec2(ui.available_width(), ROW), egui::Sense::hover());
        if changed {
            ui.painter()
                .rect_filled(rect, 0.0, visuals.selection.bg_fill);
        }
        let mut row = ui.new_child(
            egui::UiBuilder::new()
                .max_rect(rect)
                .layout(egui::Layout::left_to_right(egui::Align::Center)),
        );
        row.spacing_mut().item_spacing.x = 10.0;
        row.add_space(PAD);
        let ink = match hidden {
            true => app::caption(&visuals),
            false => visuals.weak_text_color(),
        };
        cell(&mut row, &field.path, COLUMNS[0].1, ink);
        cell(
            &mut row,
            field.spec.placement,
            COLUMNS[1].1,
            app::caption(&visuals),
        );
        row.add_sized(
            [COLUMNS[2].1, ROW],
            egui::Label::new(
                egui::RichText::new(field::kind_word(field))
                    .font(egui::FontId::proportional(MONO))
                    .color(app::caption(&visuals)),
            )
            .truncate()
            .halign(egui::Align::LEFT),
        );
        cell(&mut row, table.raw(&field.path), COLUMNS[3].1, ink);
        self.writes(&mut row, field, sets);
        if let Some((glyph, tint)) = flag(changed, hidden, labelled, &visuals) {
            icon(&mut row, glyph, 11.0, tint);
        }

        // ⚠️ Asked only of the row under the pointer. Enumerating a field walks every
        // bit pattern it can hold, and a body has hundreds of fields in one table.
        if !response.hovered() {
            return;
        }
        let accepts = match (field.spec.legal)() {
            legal if legal.is_empty() => "its stored bits, as spelled".to_string(),
            legal if legal.len() > 12 => format!("{} .. {}", legal[0], legal[legal.len() - 1]),
            legal => legal.join(", "),
        };
        response.on_hover_text(format!(
            "{} · accepts {accepts}",
            match (hidden, labelled) {
                (true, _) => "not relevant: the instrument is not using this for the state the \
                              file holds — stored, valid, writable"
                    .to_string(),
                (false, true) => strings::label(&field.path),
                (false, false) => "no label in this app's table yet".to_string(),
            }
        ));
    }

    /// The one editable column. A box opens where the value is clicked, commits when it
    /// gives up the focus, and stays open holding what was typed while the library is
    /// refusing it.
    fn writes(&mut self, ui: &mut egui::Ui, field: &Field, sets: &mut Sets) {
        let width = COLUMNS[4].1;
        if self.cell.path != field.path {
            let drawn = ui.add_sized(
                [width, ROW - 4.0],
                egui::Button::new(
                    egui::RichText::new(&field.value)
                        .font(egui::FontId::monospace(MONO))
                        .color(ui.visuals().text_color()),
                )
                .fill(egui::Color32::TRANSPARENT)
                .stroke(egui::Stroke::new(
                    1.0_f32,
                    ui.visuals().widgets.noninteractive.bg_stroke.color,
                )),
            );
            if drawn.on_hover_text("click to type a value").clicked() {
                self.cell = Cell {
                    path: field.path.clone(),
                    text: field.value.clone(),
                    fresh: true,
                    error: None,
                };
            }
            return;
        }

        let response = ui.add_sized(
            [width, ROW - 4.0],
            egui::TextEdit::singleline(&mut self.cell.text).font(egui::FontId::monospace(MONO)),
        );
        // ⚠️ Taken once. Asking for focus every frame would mean the cell could never be
        // left by clicking anything else.
        if self.cell.fresh {
            self.cell.fresh = false;
            response.request_focus();
            // Selected, so typing replaces the value rather than growing it.
            let all = egui::text::CCursorRange::two(
                egui::text::CCursor::new(0),
                egui::text::CCursor::new(self.cell.text.chars().count()),
            );
            if let Some(mut state) = egui::TextEdit::load_state(ui.ctx(), response.id) {
                state.cursor.set_char_range(Some(all));
                state.store(ui.ctx(), response.id);
            }
        }
        if let Some(why) = &self.cell.error {
            ui.label(
                egui::RichText::new(why)
                    .small()
                    .color(crate::app::bad(ui.visuals())),
            );
        }
        // ⚠️ The cell's own keys, which a `TextEdit` gives up the focus on. Read from
        // the window, an Enter pressed anywhere submitted every cell left open on
        // screen — including one the library had already refused, which went back to
        // it and into the log on every press.
        if !response.lost_focus() {
            return;
        }
        let (escaped, entered) = ui.input(|i| {
            (
                i.key_pressed(egui::Key::Escape),
                i.key_pressed(egui::Key::Enter),
            )
        });
        if escaped {
            self.cell = Cell::default();
            return;
        }
        // Losing focus while a refusal is showing keeps the cell open: the typed value
        // is the only copy of what the operator meant, and Enter is what tries again.
        if self.cell.error.is_some() && !entered {
            return;
        }
        let typed = self.cell.text.trim().to_string();
        if typed == field.value {
            self.cell = Cell::default();
            return;
        }
        sets.push((field.path.clone(), typed));
    }

    fn matches(&self, field: &Field) -> bool {
        let wanted = self.filter.trim().to_ascii_lowercase();
        if wanted.is_empty() {
            return true;
        }
        field.path.to_ascii_lowercase().contains(&wanted)
            || strings::label(&field.path)
                .to_ascii_lowercase()
                .contains(&wanted)
    }

    /// Forget the cell being typed into.
    ///
    /// ⚠️ One table serves every tab, and a cell is remembered by the **path** it sits on
    /// — which two documents of the same format both declare. Left standing, a half-typed
    /// value follows the operator into the next document and lands there on Enter.
    pub(super) fn leave(&mut self) {
        self.cell = Cell::default();
    }

    /// The path of the cell being typed into, if any.
    #[cfg(test)]
    pub(super) fn editing(&self) -> Option<&str> {
        (!self.cell.path.is_empty()).then_some(self.cell.path.as_str())
    }

    /// Open a cell as a click would, for a test that cannot click.
    #[cfg(test)]
    pub(super) fn pretend_editing(&mut self, path: &str, typed: &str) {
        self.cell = Cell {
            path: path.to_string(),
            text: typed.to_string(),
            fresh: true,
            error: None,
        };
    }

    /// Report what the library said about the last cell edit.
    ///
    /// `Ok` closes the cell; a refusal leaves it open with the message under the table.
    pub fn settled(&mut self, outcome: Result<(), String>) {
        match outcome {
            Ok(()) => self.cell = Cell::default(),
            Err(why) => {
                self.cell.error = Some(why);
                // Back into the cell: what was typed is the only copy of what was meant.
                self.cell.fresh = true;
            }
        }
    }

    /// The record, section by section: where it came from and what it is, what the bytes
    /// have done since it was last saved, what the instrument says about its slot, and
    /// the decode in full.
    pub fn meta(
        &mut self,
        ui: &mut egui::Ui,
        entity: &LocalEntity,
        device: &Device,
    ) -> Option<SlotDetails> {
        let mut asked = None;
        controls::section(ui, "Container", |ui| {
            verify(ui, entity);
            container(ui, entity);
        });
        let rows = self.changes(entity);
        let title = match rows.len() {
            0 => "Changes".to_string(),
            n => format!("Changes ({n} bytes)"),
        };
        controls::section(ui, &title, |ui| diff(ui, entity, rows));
        if entity.origin.slot().is_some() {
            controls::section(ui, "On the instrument", |ui| {
                asked = slot(ui, entity, device);
            });
        }
        if entity.entity.is_some() {
            controls::section(ui, "Raw", |ui| self.dump(ui, entity));
        }
        asked
    }

    /// The bytes that moved since the asset was last saved.
    fn changes(&mut self, entity: &LocalEntity) -> &[DiffRow] {
        let against = (entity.id, entity.stamp, entity.saved.stamp);
        if self.diff_for != Some(against) {
            self.diff = byte_diff(&entity.saved.bytes, &entity.bytes);
            self.diff_for = Some(against);
        }
        &self.diff
    }

    fn dump(&mut self, ui: &mut egui::Ui, entity: &LocalEntity) {
        if entity.entity.is_none() {
            return;
        }
        // ⚠️ Formatting is synchronous; keep large library bodies folded until requested.
        egui::CollapsingHeader::new("Show the decode")
            .id_salt("raw_debug")
            .show(ui, |ui| {
                let dump = self.decoded(entity);
                egui::ScrollArea::both()
                    .max_height(360.0)
                    .auto_shrink([false, true])
                    .show(ui, |ui| {
                        ui.label(egui::RichText::new(dump).monospace().small());
                    });
            });
    }

    /// The decode as text, laid out once per set of bytes: an edit is a new set of
    /// bytes and a dump of the old ones is a dump of something nothing holds.
    fn decoded(&mut self, entity: &LocalEntity) -> &str {
        let laid = (entity.id, entity.stamp);
        if self.dump_for != Some(laid) {
            self.dump = match &entity.entity {
                Some(decoded) => format!("{decoded:#?}"),
                None => String::new(),
            };
            self.dump_for = Some(laid);
        }
        &self.dump
    }
}

/// What the Advanced table reads besides the working fields: the decode of the bytes
/// this document was last saved as, the paths the two spell differently, and which
/// fields the Edit face draws at all.
pub struct Table<'a> {
    pub fields: &'a [Field],
    pub saved: &'a [Field],
    pub changed: &'a [String],
    pub doc: Option<&'a field::Doc<'a>>,
}

impl Table<'_> {
    /// The value this path held in the bytes the document was last saved as. A field the
    /// saved decode does not carry reads as what is in front of the operator.
    fn raw(&self, path: &str) -> &str {
        self.saved
            .iter()
            .chain(self.fields)
            .find(|field| field.path == path)
            .map_or("", |field| field.value.as_str())
    }

    fn shows(&self, path: &str) -> bool {
        self.doc.is_none_or(|doc| doc.shows(path))
    }
}

/// One mono column of a row.
fn cell(ui: &mut egui::Ui, text: &str, width: f32, ink: egui::Color32) {
    ui.add_sized(
        [width, ROW],
        egui::Label::new(
            egui::RichText::new(text)
                .font(egui::FontId::monospace(MONO))
                .color(ink),
        )
        .truncate()
        .halign(egui::Align::LEFT),
    );
}

/// The one mark at the end of a row, in the order that decides which it wears: what the
/// operator changed, then what the Edit face does not draw, then what this app has no
/// name for.
fn flag(
    changed: bool,
    hidden: bool,
    labelled: bool,
    visuals: &egui::Visuals,
) -> Option<(Glyph, egui::Color32)> {
    match (changed, hidden, labelled) {
        (true, _, _) => Some((Glyph::Pencil, app::warn(visuals))),
        (false, true, _) => Some((Glyph::EyeOff, app::caption(visuals))),
        (false, false, false) => Some((Glyph::Tag, app::caption(visuals))),
        (false, false, true) => None,
    }
}

fn verify(ui: &mut egui::Ui, entity: &LocalEntity) {
    ui.horizontal_wrapped(|ui| {
        ui.label(egui::RichText::new("verify").weak());
        ui.label(
            egui::RichText::new(entity.verify.badge())
                .strong()
                .color(entity.verify.color(ui.visuals())),
        );
        ui.label(egui::RichText::new(entity.verify.detail()).weak());
    });
    if let Some(e) = &entity.parse_error {
        ui.label(egui::RichText::new(e).color(crate::app::bad(ui.visuals())));
    }
}

fn row(ui: &mut egui::Ui, label: &str, value: impl Into<String>) {
    ui.label(egui::RichText::new(label).weak());
    ui.label(egui::RichText::new(value.into()).monospace());
    ui.end_row();
}

fn container(ui: &mut egui::Ui, entity: &LocalEntity) {
    let Some(container) = &entity.container else {
        ui.label(
            egui::RichText::new("these bytes carry no CBIN header, so there is nothing to read")
                .weak()
                .small(),
        );
        return;
    };
    egui::Grid::new("cbin_grid").num_columns(2).show(ui, |ui| {
        row(
            ui,
            "generation",
            format!("{:?}", container.header.generation),
        );
        row(ui, "format", container.tag());
        row(ui, "version", container.header.version.to_string());
        row(ui, "slot", stored_slot(container.header.slot()));
        row(ui, "body", format!("{} bytes", container.body_len()));
        row(ui, "file", format!("{} bytes", entity.bytes.len()));
        row(
            ui,
            container.checksum_label.trim_end_matches(':'),
            match container.checksum_ok {
                true => container.checksum.clone(),
                false => format!("{} (does not match the bytes)", container.checksum),
            },
        );
    });
}

/// What a stored half carries where it names no position.
const NO_SLOT: u16 = 0xffff;

/// The stored slot, one-indexed as `BANK:SLOT`.
///
/// Library files carry `0xffff:0xffff` where slot files keep a bank/slot pair — a
/// library object has no slot until an instrument gives it one.
fn stored_slot(slot: (u16, u16)) -> String {
    match slot {
        (NO_SLOT, NO_SLOT) => "none (a library file, not a slot save)".into(),
        (bank, slot) => format!("{}:{}", counted(bank), counted(slot)),
    }
}

/// One half of a stored slot, counted from one. A half holding the none marker names no
/// position, so there is nothing to count from — and `0xffff + 1` does not fit a `u16`.
fn counted(half: u16) -> String {
    match half {
        NO_SLOT => "none".to_string(),
        half => (u32::from(half) + 1).to_string(),
    }
}

fn diff(ui: &mut egui::Ui, entity: &LocalEntity, rows: &[DiffRow]) {
    if rows.is_empty() {
        ui.label(
            egui::RichText::new(match entity.saved.bytes.len() == entity.bytes.len() {
                true => "nothing moved",
                // Nothing here can pair the bytes up across a length change.
                false => "the length changed, so there is nothing to line up",
            })
            .weak()
            .small(),
        );
        return;
    }
    egui::ScrollArea::vertical()
        .id_salt("bytediff")
        .max_height(220.0)
        .auto_shrink([false, true])
        .show(ui, |ui| {
            for row in rows {
                ui.label(
                    egui::RichText::new(format!(
                        "byte {:#06x}  {:#04x} -> {:#04x}{}",
                        row.at, row.before, row.after, row.note,
                    ))
                    .monospace()
                    .small()
                    .weak(),
                );
            }
        });
}

/// What the instrument says about the slot this came off.
fn slot(ui: &mut egui::Ui, entity: &LocalEntity, device: &Device) -> Option<SlotDetails> {
    let (class, at) = entity.origin.slot()?;
    let mut asked = None;
    ui.label(
        egui::RichText::new(strings::place(class, at))
            .monospace()
            .small(),
    );
    let busy = device.state.in_flight.is_some();
    if ui
        .add_enabled(
            device.state.connected() && !busy,
            egui::Button::new("Read slot details"),
        )
        .on_disabled_hover_text("needs the instrument attached and idle")
        .clicked()
    {
        asked = Some(SlotDetails { class, at });
    }
    if device.state.detail.at != Some((class, at)) {
        return asked;
    }
    match &device.state.detail.info {
        Some(Some(info)) => {
            egui::Grid::new("slot_detail")
                .num_columns(2)
                .show(ui, |ui| {
                    row(ui, "name", format!("{:?}", info.name));
                    row(ui, "format", info.format.clone());
                    row(ui, "version", info.version.to_string());
                    row(ui, "body", format!("{} bytes", info.body_len));
                    row(
                        ui,
                        "crc32",
                        match info.crc32 {
                            Some(crc) => format!("{crc:#010x}"),
                            // Library content reports 0xffffffff: no checksum is kept for
                            // objects this large.
                            None => "none (not checksummed for this class)".into(),
                        },
                    );
                });
        }
        Some(None) => {
            ui.label(egui::RichText::new("the slot is empty").weak());
        }
        None => {}
    }
    if let Some(deps) = &device.state.detail.deps {
        ui.separator();
        if deps.is_empty() {
            ui.label(egui::RichText::new("no dependencies").weak());
        }
        egui::Grid::new("deps").num_columns(3).show(ui, |ui| {
            for dep in deps {
                ui.label(egui::RichText::new(dep.class.label()).small().weak());
                ui.label(egui::RichText::new(format!("{:08x}", dep.id)).monospace());
                // The names come from the device; a file stores ids only.
                ui.label(dep.name.trim());
                ui.end_row();
            }
        });
    }
    asked
}

/// The two reads the Meta face asks for, in the order the CLI asks them.
pub fn commands(details: SlotDetails) -> [DeviceCmd; 2] {
    let SlotDetails { class, at } = details;
    [
        DeviceCmd::SlotInfo { class, at },
        DeviceCmd::Deps { class, at },
    ]
}

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

    /// The Raw section shows the decode of the bytes the document holds. An edit is a
    /// new set of bytes, and a dump kept by id alone would go on describing the old
    /// ones for as long as the tab stayed open.
    #[test]
    fn the_raw_decode_follows_an_edit_to_the_bytes() {
        let ctx = eframe::egui::Context::default();
        let mut workspace = Workspace::new(ctx);
        let mut log = crate::log::Log::default();
        let id = workspace.create(Fresh::Program, &mut log).expect("a fresh");
        let mut advanced = Advanced::default();

        let before = advanced
            .decoded(workspace.get(id).expect("it is open"))
            .to_string();
        assert!(
            before.contains("organ_type"),
            "it is the decode: {before:.200}"
        );

        let bytes = workspace.get(id).expect("it is open").bytes.clone();
        let (_, edited) = crate::fields::apply(
            &bytes,
            &[("center_panel.organ_type".to_string(), "Vox".to_string())],
        )
        .expect("the set is legal");
        workspace.replace_bytes(id, edited, &mut log);

        let after = advanced.decoded(workspace.get(id).expect("it is open"));
        assert_ne!(
            before, after,
            "the dump is of the bytes in front of the reader"
        );
    }

    /// The Changes section is what the asset holds against what it was last saved as,
    /// and it follows both ends of that: an edit moves the bytes, and saving moves the
    /// baseline onto them.
    #[test]
    fn the_changes_rows_follow_the_bytes_and_the_baseline() {
        let ctx = eframe::egui::Context::default();
        let mut workspace = Workspace::new(ctx);
        let mut log = crate::log::Log::default();
        let id = workspace.create(Fresh::Program, &mut log).expect("a fresh");
        let mut advanced = Advanced::default();
        assert!(
            advanced
                .changes(workspace.get(id).expect("it is open"))
                .is_empty(),
            "nothing has moved yet"
        );

        let bytes = workspace.get(id).expect("it is open").bytes.clone();
        let (_, edited) = crate::fields::apply(
            &bytes,
            &[("center_panel.gain".to_string(), "96".to_string())],
        )
        .expect("the set is legal");
        workspace.replace_bytes(id, edited, &mut log);
        assert!(
            !advanced
                .changes(workspace.get(id).expect("it is open"))
                .is_empty(),
            "the edit is in the section"
        );

        workspace.mark_saved(id);
        assert!(
            advanced
                .changes(workspace.get(id).expect("it is open"))
                .is_empty(),
            "the baseline moved onto the bytes"
        );
    }

    /// A pair is counted from one, and a half holding the none marker is spelled as one
    /// rather than counted from: `0xffff + 1` is not a slot and does not fit a `u16`.
    #[test]
    fn a_stored_slot_counts_from_one_and_names_a_half_that_holds_no_position() {
        assert_eq!(stored_slot((0, 0)), "1:1");
        assert_eq!(stored_slot((6, 3)), "7:4");
        assert_eq!(
            stored_slot((NO_SLOT, NO_SLOT)),
            "none (a library file, not a slot save)"
        );
        assert_eq!(stored_slot((NO_SLOT, 5)), "none:6");
        assert_eq!(stored_slot((5, NO_SLOT)), "6:none");
        assert_eq!(stored_slot((0xfffe, 0xfffe)), "65535:65535");
    }
}