nord-cli 0.6.0

Your Nord from the terminal: inspect, edit and move the sounds in Nord files and on a connected instrument
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
//! The human rendering of a decoded entity.
//!
//! Everything here is *data*, so it goes to stdout: `nord inspect x.ne5p | grep transpose`
//! has to work.

use nord_format::cbin::Cbin;
use nord_format::formats::ne5;
use nord_format::formats::ne5::{Instrument, OrganModel};
use nord_format::formats::nsmp::zone::VelocityWindow;
use nord_format::formats::nsmp::{codec, stroke, Chain, Sample};
use nord_format::formats::nsmpproj;
use nord_format::note;
use nord_format::{Entity, Live, Program, Settings, Song};

use crate::slot::shown_at;
use crate::ui::Ui;

/// The Stage 2/3 program category, or the `aux` word that names none.
fn category(header: &nord_format::cbin::Header) -> String {
    match nord_format::components::ProgramCategory::of(header) {
        Some(category) => format!("{category:?}"),
        None => format!("none ({:#010x})", header.aux),
    }
}

fn yn(b: bool) -> &'static str {
    if b {
        "yes"
    } else {
        "no"
    }
}

/// A library dependency id as hex: the one spelling every verb that prints an id
/// uses, so an id read here can be matched against one `deps` reports.
pub(crate) fn dep_id(id: u32) -> String {
    match id {
        0 => "none".to_string(),
        id => format!("{id:#010x}"),
    }
}

/// Column the values line up in, counting the two-space indent.
const LABEL_WIDTH: usize = 11;
/// Same, for the effect-name column, whose longest entry is `reverb`.
const FX_WIDTH: usize = 7;
/// Same, for a setting's name, whose longest entry is `rotary rotor acceleration`.
const SETTING_WIDTH: usize = 27;

/// A version stored ×100, as the instrument prints it: `530` is `5.30`.
pub(crate) fn version_label(v: u32) -> String {
    format!("{}.{:02}", v / 100, v % 100)
}

/// `label:     value`, label dimmed so the eye runs down the values. `indent` is 2 for
/// the file's own identity and 4 for anything sitting under a section heading.
fn field(ui: &Ui, indent: usize, label: &str, value: impl std::fmt::Display) -> String {
    let label = format!("{label}:");
    format!(
        "{:indent$}{}{value}",
        "",
        ui.dim(format!("{label:<LABEL_WIDTH$}"))
    )
}

/// Start a group: a blank line, then the heading.
fn section(ui: &Ui, name: &str) {
    ui.out("");
    ui.out(format!("  {}", ui.heading(name)));
}

/// A drawbar position as a block whose height is how far the bar is pulled out.
///
/// `0` is a dot rather than the shortest block: a registration is read by which bars are
/// *out*, and an eighth-block reads as a small value instead of none.
fn level(position: u8) -> char {
    const LEVELS: [char; 9] = ['·', '', '', '', '', '', '', '', ''];
    LEVELS[(position as usize).min(8)]
}

fn digits(positions: &[u8]) -> String {
    positions.iter().map(u8::to_string).collect()
}

/// Nine drawbars as a chart, with the digits — the data — kept alongside it.
///
/// ⚠️ Without unicode this must return exactly the digits and nothing else: a pipe
/// carries them in that form.
fn drawbars(ui: &Ui, positions: &[u8]) -> String {
    let digits = digits(positions);
    if !ui.unicode() {
        return digits;
    }
    let chart: String = positions.iter().map(|&p| level(p)).collect();
    format!("{chart}  {}", ui.dim(digits))
}

/// The panel printout, shared by `.ne5p` programs and `.ne5l` live slots.
///
/// The live buffer is the program body under another tag, so it is the same panel and
/// gets the same rendering; only the `kind` line and the slot space differ. `at` is the
/// header's own `(bank, slot)`, whichever space the caller reads it in.
fn panels(ui: &Ui, kind: &str, at: (u16, u16), p: &ne5::Program) {
    ui.out(field(ui, 2, "type", kind));
    ui.out(field(ui, 2, "location", shown_at(at.0, at.1)));
    keyboard(ui, p);
    voices(ui, p);
    effects(ui, p);
    organ(ui, p);
}

fn keyboard(ui: &Ui, p: &ne5::Program) {
    let split = if p.center_panel.split {
        format!("yes @ {:?}", p.center_panel.split_point)
    } else {
        "no".to_string()
    };

    section(ui, "Keyboard");
    for (name, part, octave, sustain, control) in [
        (
            "lower",
            p.center_panel.lower_part,
            p.center_panel.lower_octave_shift.inner(),
            p.center_panel.lower_sustain,
            p.center_panel.lower_control,
        ),
        (
            "upper",
            p.center_panel.upper_part,
            p.center_panel.upper_octave_shift.inner(),
            p.center_panel.upper_sustain,
            p.center_panel.upper_control,
        ),
    ] {
        ui.out(field(
            ui,
            4,
            name,
            format!(
                "{part:?}  {} {octave:+}  {} {}  {} {}",
                ui.dim("octave"),
                ui.dim("sustain"),
                yn(sustain),
                ui.dim("control"),
                yn(control),
            ),
        ));
    }
    ui.out(field(ui, 4, "split", split));
    // The enable is a separate field from the value, so it is shown as the panel
    // shows it — a light that is on or off, not a yes/no answer to "transpose".
    let transpose = format!("{:+}", p.center_panel.transpose.inner());
    ui.out(field(
        ui,
        4,
        "transpose",
        if p.center_panel.transpose_enabled {
            format!("{transpose}  {}", ui.dim("(on)"))
        } else {
            ui.dim(format!("{transpose}  (off)"))
        },
    ));
    ui.out(field(
        ui,
        4,
        "part mix",
        format!("{} {}", p.center_panel.part_mix, ui.dim("(lower/upper %)")),
    ));
    ui.out(field(ui, 4, "gain", p.center_panel.gain));
}

fn voices(ui: &Ui, p: &ne5::Program) {
    section(ui, "Voices");
    let (piano, sample) = (&p.piano_panel, &p.sample_panel);
    ui.out(field(
        ui,
        4,
        "piano",
        format!(
            "{}  {} {}  {} {}  {} {}  {} {}  {} {}",
            piano.category,
            ui.dim("model"),
            piano.piano_model.as_u8(),
            ui.dim("clav"),
            piano.clav_model.as_u8(),
            ui.dim("acoustics"),
            piano.acoustics.as_u8(),
            ui.dim("touch"),
            piano.touch.as_u8(),
            ui.dim("mono"),
            yn(piano.mono),
        ),
    ));
    ui.out(field(
        ui,
        4,
        "sample",
        format!(
            "{} {}  {} {}  {} {}  {} {}  {} {}",
            ui.dim("number"),
            sample.number,
            ui.dim("attack"),
            sample.attack,
            ui.dim("decay/rel"),
            sample.decay_release,
            ui.dim("dynamics"),
            sample.dynamics.as_u8(),
            ui.dim("filter"),
            yn(sample.filter),
        ),
    ));
    // The file stores only the ids. `nord program deps` reports the same ids for
    // this program with names attached, which is the only way to resolve them.
    ui.out(field(
        ui,
        4,
        "depends",
        format!(
            "{} {}  {} {}",
            ui.dim("piano"),
            dep_id(piano.id.id()),
            ui.dim("sample"),
            dep_id(sample.id.id()),
        ),
    ));
}

fn effects(ui: &Ui, p: &ne5::Program) {
    let fx = &p.effects_panel;
    section(ui, "Effects");
    ui.out(format!(
        "    {}",
        ui.dim("stored value, with the panel's reading where the scale is known")
    ));
    let off = |name: &str, value: &dyn std::fmt::Display| {
        ui.out(ui.dim(format!("    {name:<FX_WIDTH$}{value}")))
    };
    match fx.fx1.part() {
        Some(part) => ui.out(format!(
            "    {:<FX_WIDTH$}{part:<5}  {:<9}  {} {}  {} {}",
            "fx1",
            fx.fx1_type,
            ui.dim("rate"),
            fx.fx1_rate,
            ui.dim("control"),
            yn(fx.fx1_control),
        )),
        None => off("fx1", &fx.fx1),
    }
    match fx.fx2.part() {
        Some(part) => ui.out(format!(
            "    {:<FX_WIDTH$}{part:<5}  {:<9}  {} {}  {} {}",
            "fx2",
            fx.fx2_type,
            ui.dim("rate"),
            fx.fx2_rate,
            ui.dim("deep"),
            yn(fx.fx2_deep),
        )),
        None => off("fx2", &fx.fx2),
    }
    match fx.fx3.part() {
        Some(part) => ui.out(format!(
            "    {:<FX_WIDTH$}{part:<5}  {:<9}  {} {}",
            "fx3",
            fx.fx3_type,
            ui.dim("compression"),
            fx.fx3_compression,
        )),
        None => off("fx3", &fx.fx3),
    }
    match fx.fx4.part() {
        Some(part) => ui.out(format!(
            "    {:<FX_WIDTH$}{part:<5}  {} {}  {} {}  {} {}  {} {}",
            "delay",
            ui.dim("feedback"),
            fx.fx4_feedback.as_u8(),
            ui.dim("tempo"),
            fx.fx4_tempo,
            ui.dim("wet"),
            fx.fx4_moisture,
            ui.dim("ping-pong"),
            yn(fx.fx4_ping_pong),
        )),
        None => off("delay", &fx.fx4),
    }
    // `fx5` set means reverb on. Inferred from specimens; not confirmed on hardware.
    if fx.fx5 {
        ui.out(format!(
            "    {:<FX_WIDTH$}{:<15}  {} {}",
            "reverb",
            fx.fx5_type,
            ui.dim("wet"),
            fx.fx5_moisture,
        ));
    } else {
        off("reverb", &"off");
    }
    // `equalizer_part` says which part, never whether: `0` is lower, and the enable
    // is the separate bit `equalizer_on`.
    if fx.equalizer_on {
        let part = fx.equalizer_part;
        ui.out(format!(
            "    {:<FX_WIDTH$}{part:<11}  {} {}  {} {}  {} {}  {} {}",
            "eq",
            ui.dim("bass"),
            fx.equalizer_bass,
            ui.dim("freq"),
            fx.equalizer_freq,
            ui.dim("gain"),
            fx.equalizer_freq_gain,
            ui.dim("treble"),
            fx.equalizer_treble,
        ));
    } else {
        off("eq", &"off");
    }
    ui.out(format!(
        "    {:<FX_WIDTH$}{} {}  {} {}",
        "rotary",
        ui.dim("speed"),
        fx.rotary_speed,
        ui.dim("stop"),
        if fx.rotary_stop { "on" } else { "off" },
    ));
}

fn organ(ui: &Ui, p: &ne5::Program) {
    // The file keeps the full state of all four models, and b3+bass cannot be
    // read without preset 1 and preset 2 side by side, so every row is printed.
    if p.center_panel.lower_part == Instrument::Organ
        || p.center_panel.upper_part == Instrument::Organ
    {
        let o = &p.organ_panel;
        let selected = p.center_panel.organ_type;
        // b3+bass shares the B3's storage, so it marks the B3 rows.
        let sel_model = selected.storage();
        section(ui, "Organ");
        ui.out(format!(
            "    {}",
            ui.dim(format!(
                "{selected} selected (*), active preset (<), drawbar positions 0-8"
            ))
        ));
        for (model, label) in [
            (OrganModel::B3, "b3"),
            (OrganModel::Vox, "vox"),
            (OrganModel::Farfisa, "farf"),
            (OrganModel::Pipe, "pipe"),
        ] {
            for preset in [ne5::Preset::One, ne5::Preset::Two] {
                let mark = if Some(model) == sel_model { "*" } else { " " };
                let live = if o.preset(model) == preset { "<" } else { " " };

                // The bass manual's two bars live outside the block, and the nine
                // nibbles are stale there: `OrganPanel::b3_bass_drawbars`.
                let bars = if selected.is_b3_bass()
                    && model == OrganModel::B3
                    && preset == ne5::Preset::One
                {
                    // Dots align the two-bar bass manual without inventing seven bars.
                    let b = o.b3_bass_drawbars();
                    let plain = format!("{}{}.......", b[0], b[1]);
                    if ui.unicode() {
                        format!("{}{}·······  {}", level(b[0]), level(b[1]), ui.dim(plain))
                    } else {
                        plain
                    }
                } else if model == OrganModel::Farfisa {
                    // On/off tabs rather than positions, with the stored nibble kept
                    // beside them: `OrganPanel::farfisa_tabs`.
                    let (on, off) = if ui.unicode() {
                        ('', '·')
                    } else {
                        ('|', '.')
                    };
                    let tabs: String = o
                        .farfisa_tabs(preset)
                        .iter()
                        .map(|t| if *t { on } else { off })
                        .collect();
                    let pos = digits(&o.drawbars(model, preset)[..]);
                    if ui.unicode() {
                        format!("{tabs}  {}", ui.dim(format!("({pos})")))
                    } else {
                        format!("{tabs} ({pos})")
                    }
                } else {
                    drawbars(ui, &o.drawbars(model, preset)[..])
                };

                let vib = match o.vib_type(model) {
                    Some(v) if o.vib_on(model, preset) => format!("  vib {v:?}"),
                    Some(_) => "  vib off".to_string(),
                    None => String::new(),
                };
                let perc = if model == OrganModel::B3 {
                    if o.b3_perc_on(preset) {
                        let third = if o.b3_perc_third() { " +3rd" } else { "" };
                        format!("  perc {:?}{third}", o.b3_perc_speed())
                    } else {
                        "  perc off".to_string()
                    }
                } else {
                    String::new()
                };
                // Padded before styling: an escape sequence inside a width spec
                // is counted as characters and the column stops lining up.
                let name = format!("{label:<5}");
                let name = if Some(model) == sel_model {
                    ui.bold(name)
                } else {
                    name
                };
                ui.out(format!("   {mark}{name} p{preset}{live} {bars}{vib}{perc}"));
            }
        }
    }
}

/// The v3/v4 sample-instrument printout: identity and section inventory — the
/// zone map is not decoded for this generation yet.
fn sample_v3(ui: &Ui, s: &Cbin<nord_format::formats::nsmp::SampleV3>) {
    ui.out(field(ui, 2, "type", "sample instrument (nsmp3/nsmp4)"));
    match (s.name(), s.sub_name()) {
        (Ok(name), Ok(sub)) if !sub.is_empty() => {
            ui.out(field(ui, 2, "name", format!("{name}_{sub}")))
        }
        (Ok(name), _) => ui.out(field(ui, 2, "name", name)),
        (Err(e), _) => ui.warn(format!("name unreadable: {e}")),
    }
    let v = s.header.version;
    ui.out(field(ui, 2, "version", version_label(v)));
    ui.out(field(ui, 2, "strokes", s.stroke_count().to_string()));

    section(ui, "Zones");
    match s.zones() {
        Err(e) => ui.warn(format!("zone table unreadable: {e}")),
        Ok(zones) => {
            for z in zones {
                let range = match z.low_note {
                    Some(low) => format!("{}..={}", low, z.top_note),
                    None => format!("..={}", z.top_note),
                };
                let mut says = format!("root {} (stroke {})", z.root_key, z.stroke_gid);
                // Silent unless it is not the whole range: a narrow window is
                // the difference between a zone that sounds and one that does not.
                if let Some(w) = z.velocity.filter(|w| *w != VelocityWindow::FULL) {
                    says.push_str(&format!(" velocity {}..={}", w.low, w.high));
                }
                ui.out(field(ui, 2, &range, says));
            }
        }
    }
}

/// The Sample Editor project printout: identity, the audio files, the zone map.
fn sample_project(ui: &Ui, p: &nsmpproj::Project) {
    ui.out(field(ui, 2, "type", "Sample Editor project (nsmpproj)"));
    match p.name() {
        Ok(name) => ui.out(field(ui, 2, "name", name)),
        Err(e) => ui.warn(format!("name unreadable: {e}")),
    }
    if let Ok((product, version)) = p.created_by() {
        ui.out(field(ui, 2, "editor", format!("{product} {version}")));
    }
    if let Ok(v) = p.file_format_version() {
        ui.out(field(ui, 2, "version", v));
    }

    section(ui, "Audio files");
    match p.audio_files() {
        Err(e) => ui.warn(format!("audio files unreadable: {e}")),
        Ok(files) => {
            for f in files {
                ui.out(field(
                    ui,
                    4,
                    &format!("file {}", f.id),
                    format!("{}  {} {}", f.path, ui.dim("Hz"), f.sample_rate),
                ));
            }
        }
    }

    section(ui, "Zones");
    let (zones, strokes) = match (p.zones(), p.strokes()) {
        (Ok(z), Ok(s)) => (z, s),
        (Err(e), _) | (_, Err(e)) => {
            ui.warn(format!("zone table unreadable: {e}"));
            return;
        }
    };
    ui.out(format!("    {}", ui.dim("high to low")));
    for zone in &zones {
        let range = format!(
            "{}..{}",
            note::name(zone.bottom_note),
            note::name(zone.top_note)
        );
        let files: Vec<String> = zone
            .strokes
            .iter()
            .map(|zs| {
                strokes
                    .iter()
                    .find(|s| s.global_id == zs.global_id)
                    .map_or_else(
                        || format!("stroke {}?", zs.global_id),
                        |s| format!("file {}", s.file_id),
                    )
            })
            .collect();
        ui.out(field(
            ui,
            4,
            &format!("zone {}", zone.zone_id),
            format!(
                "{range:<10} {} {} ({})  {}{}",
                ui.dim("root"),
                note::name(zone.root_key),
                zone.root_key,
                files.join(", "),
                if zone.enabled { "" } else { "  (disabled)" }
            ),
        ));
    }
}

/// The sample-instrument printout: identity, then the zone map.
fn sample(ui: &Ui, s: &Cbin<Sample>) {
    ui.out(field(ui, 2, "type", "sample instrument (nsmp)"));
    let named = s.chain().is_ok_and(Chain::names_instrument);
    match s.name() {
        Ok(_) if !named => ui.out(field(ui, 2, "name", "(this library carries none)")),
        Ok(name) => ui.out(field(ui, 2, "name", name)),
        Err(e) => ui.warn(format!("name unreadable: {e}")),
    }
    // Content version, `format * 100 + revision`: 200 reads back as 2.0.
    let v = s.header.version;
    ui.out(field(ui, 2, "version", version_label(v)));
    let categories = s.categories();
    if !categories.is_empty() {
        ui.out(field(ui, 2, "category", categories.join(" / ")));
    }

    section(ui, "Zones");
    let (zones, strokes) = match (s.zones(), s.strokes()) {
        (Ok(z), Ok(st)) => (z, st),
        (Err(e), _) | (_, Err(e)) => {
            ui.warn(format!("zone table unreadable: {e}"));
            return;
        }
    };
    if zones.len() != strokes.len() {
        ui.warn(format!(
            "{} zones but {} strokes; showing what pairs up",
            zones.len(),
            strokes.len()
        ));
    }
    ui.out(format!(
        "    {}",
        ui.dim("high to low; the last zone reaches the bottom of the keyboard")
    ));
    for (i, (zone, stroke)) in zones.iter().zip(&strokes).enumerate() {
        // Zones tile, so a zone's bottom is one above the next record's top note:
        // `Sample::set_zone_low_note`.
        let range = match zones.get(i + 1) {
            Some(below) => format!(
                "{}..{}",
                note::name(below.top_note.saturating_add(1)),
                note::name(zone.top_note)
            ),
            None => format!("..{}", note::name(zone.top_note)),
        };
        ui.out(field(
            ui,
            4,
            &format!("zone {}", i + 1),
            format!(
                "{range:<10} {} {} ({})  {} {}",
                ui.dim("root"),
                note::name(stroke.root_key),
                stroke.root_key,
                ui.dim("packets"),
                match stroke.packets {
                    Some(n) => n.to_string(),
                    None => "?".into(),
                },
            ),
        ));
    }
    match s.key_table() {
        Ok(table) => {
            let level = table.instrument;
            ui.out(field(
                ui,
                4,
                "keyboard",
                format!(
                    "{} {:.3} ({:+.1} dB)  {} {:+.2} st  {} {}",
                    ui.dim("gain"),
                    level.ratio(),
                    20.0 * level.ratio().log10(),
                    ui.dim("detune"),
                    level.semitones(),
                    ui.dim("keys adjusted"),
                    table.adjusted().count(),
                ),
            ));
        }
        Err(e) => ui.warn(format!("keyboard map unreadable: {e}")),
    }
    // Do not present a partial packet count as a complete measurement.
    let counted: usize = strokes.iter().filter_map(|s| s.packets).sum();
    let unknown = strokes.iter().filter(|s| s.packets.is_none()).count();
    ui.out(field(
        ui,
        4,
        "audio",
        format!(
            "{} {counted}{}  {} {}",
            ui.dim("packets"),
            if unknown > 0 {
                format!(" (+{unknown} stroke(s) whose header length is unknown)")
            } else {
                String::new()
            },
            ui.dim("encoded bytes"),
            counted * stroke::packet_len(codec::Layout::V2),
        ),
    ));
}

pub fn print(ui: &Ui, entity: &Entity) {
    match entity {
        Entity::Program(Program::Electro5(p)) => {
            panels(ui, "Electro 5 program (ne5p)", p.header.slot(), p)
        }
        Entity::Live(Live::Electro5(p)) => {
            panels(ui, "Electro 5 live slot (ne5l)", p.header.slot(), p)
        }
        Entity::Song(Song::Electro5(s)) => {
            let (bank, slot) = s.header.slot();
            ui.out(field(ui, 2, "type", "Electro 5 song / set (ne5t)"));
            ui.out(field(ui, 2, "location", shown_at(bank, slot)));
            section(ui, "Programs");
            for (n, slot) in ne5::song::Slot::ALL.into_iter().enumerate() {
                let p = s.get(slot);
                ui.out(field(
                    ui,
                    4,
                    &format!("slot {}", n + 1),
                    shown_at(p.x(), p.y()),
                ));
            }
        }
        Entity::Settings(Settings::Electro5(s)) => {
            ui.out(field(ui, 2, "type", "Electro 5 settings (ne5s)"));

            // Startup retains both program and live locations regardless of active mode.
            let boot = &s.body;
            section(ui, "Startup");
            for (name, value) in [
                (
                    "program",
                    shown_at(boot.startup_program.x(), boot.startup_program.y()),
                ),
                ("live mode", yn(boot.startup_live_mode).to_string()),
                ("live slot", boot.startup_live_slot.to_string()),
                ("set list mode", yn(boot.startup_set_list_mode).to_string()),
                // A `song::Location`: a set list and a song inside it, not a bank
                // and a slot.
                (
                    "set list song",
                    format!(
                        "list {} song {}",
                        boot.startup_song.x() + 1,
                        boot.startup_song.y() + 1
                    ),
                ),
            ] {
                ui.out(format!(
                    "    {}{}",
                    ui.dim(format!("{name:<SETTING_WIDTH$}")),
                    value,
                ));
            }

            // Grouped and ordered by the instrument's own menus, which is not the order
            // the fields sit in the file.
            for (menu, fields) in s.by_menu() {
                section(ui, menu.title());
                for f in fields {
                    ui.out(format!(
                        "    {}{}",
                        ui.dim(format!("{:<SETTING_WIDTH$}", f.name.replace('_', " "))),
                        f.value,
                    ));
                }
            }
        }
        Entity::Piano(p) => {
            ui.out(field(ui, 2, "type", "piano library (npno)"));
            match p.name() {
                Ok((name, variant)) if variant.is_empty() => ui.out(field(ui, 2, "name", name)),
                Ok((name, variant)) => ui.out(field(ui, 2, "name", format!("{name} ({variant})"))),
                Err(e) => ui.warn(format!("name unreadable: {e}")),
            }
            ui.out(field(
                ui,
                2,
                "version",
                version_label(p.file.header.version),
            ));
            if let Ok(map) = p.key_map() {
                let covered = map.iter().filter(|&&b| b != 0xFF).count();
                ui.out(field(ui, 2, "notes", format!("{covered} covered")));
            }
            if let Ok(library) = p.library() {
                ui.out(field(
                    ui,
                    2,
                    "strokes",
                    format!(
                        "{} over {} root(s), {} channel(s)",
                        library.strokes().len(),
                        library.roots().len(),
                        library.channels(),
                    ),
                ));
            }
        }
        Entity::Sample(nord_format::Sample::V2(s)) => sample(ui, s),
        Entity::Sample(nord_format::Sample::V3(s)) => sample_v3(ui, s),
        Entity::SampleProject(p) => sample_project(ui, p),
        Entity::Bundle(nord_format::Bundle::Electro5(b)) => {
            ui.out(field(ui, 2, "type", "backup bundle (zip)"));
            ui.out(field(
                ui,
                2,
                "note",
                ui.dim("use --raw to list contained programs/songs"),
            ));
            // Chatter, not data: a partial read is something the operator should see,
            // but a pipe consuming the summary should not.
            for (name, why) in b.skipped() {
                ui.warn(format!("bundle entry skipped: {name}: {why}"));
            }
        }
        Entity::Program(Program::Stage2(p)) => ns2_globals(ui, "Stage 2 program (ns2p)", p),
        Entity::Live(Live::Stage2(p)) => ns2_globals(ui, "Stage 2 live slot (ns2l)", p),
        Entity::Program(Program::Stage3(p)) => ns3_globals(ui, "Stage 3 program (ns3f)", p),
        Entity::Live(Live::Stage3(p)) => ns3_globals(ui, "Stage 3 live slot (ns3l)", p),
        Entity::Program(Program::Stage4(p)) => ns4_globals(ui, "Stage 4 program (ns4p)", p),
        Entity::Live(Live::Stage4(p)) => ns4_globals(ui, "Stage 4 live slot (ns4l)", p),
        Entity::Synth(nord_format::Synth::Stage4(y)) => {
            ns4_head(ui, "Stage 4 synth preset (ns4y)", &y.header);
            section(ui, "Layers");
            ui.out(field(
                ui,
                4,
                "on",
                layers(&[
                    ("A", y.synth_a_layer_enabled),
                    ("B", y.synth_b_layer_enabled),
                    ("C", y.synth_c_layer_enabled),
                ]),
            ));
            ns4_note(ui);
        }
        Entity::PianoPreset(nord_format::PianoPreset::Stage4(n)) => {
            ns4_head(ui, "Stage 4 piano preset (ns4n)", &n.header);
            section(ui, "Layers");
            ui.out(field(
                ui,
                4,
                "on",
                layers(&[
                    ("A", n.piano_a_layer_enabled),
                    ("B", n.piano_b_layer_enabled),
                ]),
            ));
            ns4_note(ui);
        }
        Entity::OrganPreset(nord_format::OrganPreset::Stage4(o)) => {
            ns4_head(ui, "Stage 4 organ preset (ns4o)", &o.header);
            section(ui, "Layers");
            ui.out(field(
                ui,
                4,
                "on",
                layers(&[
                    ("A", o.organ_a_layer_enabled),
                    ("B", o.organ_b_layer_enabled),
                ]),
            ));
            ns4_note(ui);
        }
        Entity::Bundle(nord_format::Bundle::Drum2Bank(b)) => {
            ui.out(field(ui, 2, "type", "Drum 2 bank (zip)"));
            ui.out(field(ui, 2, "programs", b.programs.len().to_string()));
        }
        Entity::Bundle(nord_format::Bundle::Drum3KitBank(b)) => {
            ui.out(field(ui, 2, "type", "Drum 3P kit bank (zip)"));
            ui.out(field(ui, 2, "kits", b.kits.len().to_string()));
        }
        Entity::Bundle(nord_format::Bundle::Members(members)) => {
            ui.out(field(ui, 2, "type", "bundle (zip)"));
            let mut by_tag: std::collections::BTreeMap<String, usize> = Default::default();
            for (_, m) in members {
                *by_tag
                    .entry(String::from_utf8_lossy(&m.header.tag).replace('\0', ""))
                    .or_default() += 1;
            }
            let counts = by_tag
                .iter()
                .map(|(tag, n)| format!("{n} {tag}"))
                .collect::<Vec<_>>()
                .join(", ");
            ui.out(field(ui, 2, "members", counts));
        }
        other => raw_summary(ui, other),
    }
}

/// The Stage 2 program-wide globals — the decoded slice of a mostly-raw body.
fn ns2_globals(ui: &Ui, kind: &str, p: &Cbin<nord_format::formats::ns2::Program>) {
    ui.out(field(ui, 2, "type", kind));
    let (bank, slot) = p.header.slot();
    ui.out(field(ui, 2, "location", shown_at(bank, slot)));
    ui.out(field(ui, 2, "category", category(&p.header)));
    ui.out(field(ui, 2, "version", p.header.version.to_string()));

    section(ui, "Globals");
    ui.out(field(
        ui,
        4,
        "transpose",
        transpose(p.transpose_enabled, p.transpose),
    ));
    let split = if p.split_three_zones {
        format!("{:?} / {:?}", p.split_low_note, p.split_high_note)
    } else if p.split_two_zones {
        format!("{:?}", p.split_low_note)
    } else {
        "off".to_string()
    };
    ui.out(field(ui, 4, "split", split));
    ui.out(field(
        ui,
        4,
        "clock",
        format!("{} bpm", p.master_clock.bpm()),
    ));
    ui.out(field(ui, 4, "dual kb", yn(p.dual_keyboard)));
    ui.out(field(ui, 4, "note", ui.dim("slots and effects unmapped")));
}

/// The Stage 3 program-wide globals.
fn ns3_globals(ui: &Ui, kind: &str, p: &Cbin<nord_format::formats::ns3::Program>) {
    ui.out(field(ui, 2, "type", kind));
    let (bank, slot) = p.header.slot();
    ui.out(field(ui, 2, "location", shown_at(bank, slot)));
    ui.out(field(ui, 2, "category", category(&p.header)));
    ui.out(field(ui, 2, "version", version_label(p.header.version)));

    section(ui, "Globals");
    ui.out(field(ui, 4, "panels", format!("{:?}", p.panel_enable)));
    ui.out(field(
        ui,
        4,
        "transpose",
        transpose(p.transpose_enabled, p.transpose),
    ));
    let split = if p.split_enabled {
        let mut zones = Vec::new();
        for (on, note, width) in [
            (p.split_low_enabled, p.split_low_note, p.split_low_width),
            (p.split_mid_enabled, p.split_mid_note, p.split_mid_width),
            (p.split_high_enabled, p.split_high_note, p.split_high_width),
        ] {
            if on {
                // `width` Displays as its semitone label (1/6/12), not the
                // variant name.
                zones.push(format!("{note:?} (width {width})"));
            }
        }
        zones.join(" / ")
    } else {
        "off".to_string()
    };
    ui.out(field(ui, 4, "split", split));
    ui.out(field(
        ui,
        4,
        "clock",
        format!("{} bpm", p.master_clock.bpm()),
    ));
    let dual = if p.dual_keyboard {
        format!("on ({:?})", p.dual_keyboard_style)
    } else {
        "off".to_string()
    };
    ui.out(field(ui, 4, "dual kb", dual));
    ui.out(field(ui, 4, "note", ui.dim("panels and effects unmapped")));
}

/// `A+B` / `A` / `—` — which of a section's layers are switched on.
fn layers(on: &[(&str, bool)]) -> String {
    let live: Vec<&str> = on.iter().filter(|(_, on)| *on).map(|(n, _)| *n).collect();
    if live.is_empty() {
        "".to_string()
    } else {
        live.join("+")
    }
}

/// The container facts every Stage 4 file carries. The category is shown as its
/// stored id: what the ids name on this model is not decoded.
fn ns4_head(ui: &Ui, kind: &str, header: &nord_format::cbin::Header) {
    ui.out(field(ui, 2, "type", kind));
    let (bank, slot) = header.slot();
    ui.out(field(ui, 2, "location", shown_at(bank, slot)));
    if let Some(id) = header.category() {
        ui.out(field(ui, 2, "category", format!("id {id}")));
    }
    ui.out(field(ui, 2, "version", version_label(header.version)));
}

fn ns4_note(ui: &Ui) {
    ui.out(field(
        ui,
        4,
        "note",
        ui.dim("every parameter decodes; values are raw, use --raw to read them"),
    ));
}

/// The Stage 4 program-wide globals.
///
/// Only the parameters that carry their own meaning are shown. The rest decode to
/// the number the file stores, which reads as noise in a summary — `--raw` is
/// where those belong until there is something to name them with.
fn ns4_globals(ui: &Ui, kind: &str, p: &Cbin<nord_format::formats::ns4::Program>) {
    ns4_head(ui, kind, &p.header);

    section(ui, "Globals");
    ui.out(field(
        ui,
        4,
        "sections",
        format!(
            "organ {}, piano {}, synth {}",
            yn(p.organ_section_enabled),
            yn(p.piano_section_enabled),
            yn(p.synth_section_enabled),
        ),
    ));
    ui.out(field(
        ui,
        4,
        "layers",
        format!(
            "organ {}, piano {}, synth {}",
            layers(&[
                ("A", p.organ_a_layer_enabled),
                ("B", p.organ_b_layer_enabled)
            ]),
            layers(&[
                ("A", p.piano_a_layer_enabled),
                ("B", p.piano_b_layer_enabled)
            ]),
            layers(&[
                ("A", p.synth_a_layer_enabled),
                ("B", p.synth_b_layer_enabled),
                ("C", p.synth_c_layer_enabled),
            ]),
        ),
    ));
    let split = if p.split_enabled {
        layers(&[
            ("1-2", p.kb_zones_1_2_split_point_enabled),
            ("2-3", p.kb_zones_2_3_split_point_enabled),
            ("3-4", p.kb_zones_3_4_split_point_enabled),
        ])
    } else {
        "off".to_string()
    };
    ui.out(field(ui, 4, "split", split));
    ui.out(field(
        ui,
        4,
        "transpose",
        if p.program_transpose_enabled {
            format!("on (stored {})", p.program_transpose_amount)
        } else {
            "off".to_string()
        },
    ));
    ui.out(field(
        ui,
        4,
        "global fx",
        format!(
            "comp {}, delay {}, reverb {}",
            yn(p.fx_comp_global_enabled),
            yn(p.fx_delay_global_enabled),
            yn(p.fx_reverb_global_enabled),
        ),
    ));
    ns4_note(ui);
}

/// `off (stored -2)` vs `+3` — the enable bit means touched-at-least-once, so the
/// stored value is shown either way. An out-of-table pattern (an untouched live
/// buffer) reads as plain `off`.
fn transpose(enabled: bool, t: nord_format::components::StageTranspose) -> String {
    match (enabled, t.semitones()) {
        (true, Some(s)) => format!("{s:+}"),
        (true, None) => format!("unknown ({})", t.raw()),
        (false, Some(0)) | (false, None) => "off".to_string(),
        (false, Some(s)) => format!("off (stored {s:+})"),
    }
}

/// Everything without a decoded body: identity, then the container's facts.
fn raw_summary(ui: &Ui, entity: &Entity) {
    let id = entity.identity();
    // The three-character tags carry a trailing NUL; it is data, not display.
    let tag = id.format.trim_end_matches('\0');
    ui.out(field(ui, 2, "type", format!("{} ({tag})", id.kind)));

    if let Some(f) = entity.raw() {
        let header = &f.header;
        // A location word with its high bits set is not a bank/slot pair; show it
        // the way a hex dump would rather than as an absurd bank number.
        if header.location & 0xff00_ff00 == 0 {
            let (bank, slot) = header.slot();
            ui.out(field(ui, 2, "location", shown_at(bank, slot)));
        } else {
            ui.out(field(
                ui,
                2,
                "location",
                format!("{:#010x}", header.location),
            ));
        }
        ui.out(field(ui, 2, "version", header.version.to_string()));
        ui.out(field(ui, 2, "body", format!("{} bytes", f.body.0.len())));
        ui.out(field(
            ui,
            2,
            "note",
            ui.dim("body unmapped; container verified"),
        ));
        return;
    }

    match entity {
        Entity::Sysex(s) => {
            ui.out(field(ui, 2, "family", format!("{:?}", s.family())));
            ui.out(field(ui, 2, "messages", s.messages().count().to_string()));
            ui.out(field(ui, 2, "bytes", s.data.len().to_string()));
        }
        Entity::Midi(m) => ui.out(field(ui, 2, "bytes", m.data.len().to_string())),
        Entity::Cne3(c) => ui.out(field(ui, 2, "bytes", c.data.len().to_string())),
        _ => {}
    }
}