playr 0.4.0

A minimal TUI music player that plays local files and contacts nothing
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
//! Rendering tests against a headless backend. No audio device involved.

use playr::audio::{Spec, State, Status};
use playr::db::query::Playlist;
use playr::db::Track;
use playr::ui::action::Keymap;
use playr::ui::render::{self, scroll_offset};
use playr::ui::{Input, Screen, Snapshot, View};
use ratatui::backend::TestBackend;
use ratatui::widgets::ListState;
use ratatui::Terminal;
use std::time::Duration;

fn track(title: &str, artist: &str, album: &str, secs: i64) -> Track {
    Track {
        id: 1,
        path: format!("/m/{title}.flac"),
        title: Some(title.into()),
        artist: Some(artist.into()),
        album: Some(album.into()),
        duration_ms: Some(secs * 1000),
        ..Default::default()
    }
}

/// One frame to draw. Defaults to an idle, empty player.
struct Case<'a> {
    view: View,
    snapshot: &'a Snapshot,
    all: &'a [Track],
    results: Option<&'a [Track]>,
    playing: &'a [Track],
    selection: &'a [Track],
    playlists: &'a [Playlist],
    input: &'a Input,
    message: Option<&'a str>,
    width: u16,
    height: u16,
    /// Cursor row in the library and selection views; the first row when unset.
    selected: Option<usize>,
    help_scroll: usize,
    /// The key map; the defaults when unset.
    keys: Option<&'a Keymap>,
}

impl<'a> Case<'a> {
    fn new(view: View, snapshot: &'a Snapshot) -> Self {
        Case {
            view,
            snapshot,
            all: &[],
            results: None,
            playing: &[],
            selection: &[],
            playlists: &[],
            input: &Input::None,
            message: None,
            width: 100,
            height: 20,
            selected: None,
            help_scroll: 0,
            keys: None,
        }
    }

    fn all(mut self, v: &'a [Track]) -> Self {
        self.all = v;
        self
    }

    fn results(mut self, v: &'a [Track]) -> Self {
        self.results = Some(v);
        self
    }

    fn playing(mut self, v: &'a [Track]) -> Self {
        self.playing = v;
        self
    }

    fn selection(mut self, v: &'a [Track]) -> Self {
        self.selection = v;
        self
    }

    fn playlists(mut self, v: &'a [Playlist]) -> Self {
        self.playlists = v;
        self
    }

    fn input(mut self, v: &'a Input) -> Self {
        self.input = v;
        self
    }

    fn message(mut self, v: &'a str) -> Self {
        self.message = Some(v);
        self
    }

    fn selected(mut self, i: usize) -> Self {
        self.selected = Some(i);
        self
    }

    fn keys(mut self, keys: &'a Keymap) -> Self {
        self.keys = Some(keys);
        self
    }

    fn help_scroll(mut self, rows: usize) -> Self {
        self.help_scroll = rows;
        self
    }

    fn size(mut self, width: u16, height: u16) -> Self {
        self.width = width;
        self.height = height;
        self
    }

    /// Draws one frame and returns it as plain text lines.
    fn render(self) -> Vec<String> {
        let buf = self.buffer();
        (0..buf.area.height)
            .map(|y| {
                (0..buf.area.width)
                    .map(|x| buf[(x, y)].symbol())
                    .collect::<String>()
                    .trim_end()
                    .to_string()
            })
            .collect()
    }

    /// Draws one frame and returns the cells.
    fn buffer(mut self) -> ratatui::buffer::Buffer {
        let mut terminal = Terminal::new(TestBackend::new(self.width, self.height)).unwrap();
        let default_keys = Keymap::default();
        let keys = self.keys.unwrap_or(&default_keys);
        let mut ls = ListState::default();
        let cursor = self.selected.unwrap_or(0);
        ls.select(if self.all.is_empty() {
            None
        } else {
            Some(cursor)
        });
        let mut qs = ListState::default();
        qs.select(if self.selection.is_empty() {
            None
        } else {
            Some(cursor)
        });
        let mut ps = ListState::default();
        ps.select(if self.playlists.is_empty() {
            None
        } else {
            Some(0)
        });

        terminal
            .draw(|f| {
                let mut screen = Screen {
                    view: self.view,
                    snapshot: self.snapshot,
                    all: self.all,
                    results: self.results,
                    playing: self.playing,
                    selection: self.selection,
                    playlists: self.playlists,
                    input: self.input,
                    keys,
                    help_scroll: &mut self.help_scroll,
                    message: self.message,
                    library_state: &mut ls,
                    selection_state: &mut qs,
                    playlist_state: &mut ps,
                };
                render::draw(&mut screen, f);
            })
            .unwrap();

        terminal.backend().buffer().clone()
    }

    /// Draws one frame and joins it for substring assertions.
    fn text(self) -> String {
        self.render().join("\n")
    }
}

fn stopped() -> Snapshot {
    Snapshot {
        status: Status::default(),
        position: Duration::ZERO,
        volume: 0.8,
        ..Default::default()
    }
}

/// Returns cells on `row` whose foreground equals their background.
///
/// Such a cell renders as a blank: the text is there but cannot be read.
fn invisible_cells(
    view: View,
    all: &[Track],
    selection: &[Track],
    playlists: &[Playlist],
    row: u16,
) -> Vec<String> {
    let snapshot = stopped();
    let mut terminal = Terminal::new(TestBackend::new(100, 20)).unwrap();
    let sel = |v: &[Track]| {
        let mut st = ListState::default();
        st.select((!v.is_empty()).then_some(0));
        st
    };
    let mut ls = sel(all);
    let mut qs = sel(selection);
    let mut ps = ListState::default();
    ps.select((!playlists.is_empty()).then_some(0));

    terminal
        .draw(|f| {
            let mut screen = Screen {
                view,
                snapshot: &snapshot,
                all,
                results: None,
                playing: &[],
                selection,
                playlists,
                input: &Input::None,
                keys: &Keymap::default(),
                help_scroll: &mut 0,
                message: None,
                library_state: &mut ls,
                selection_state: &mut qs,
                playlist_state: &mut ps,
            };
            render::draw(&mut screen, f);
        })
        .unwrap();

    let buf = terminal.backend().buffer().clone();
    (0..buf.area.width)
        .filter_map(|x| {
            let cell = &buf[(x, row)];
            let sym = cell.symbol().to_string();
            (cell.fg == cell.bg && !sym.trim().is_empty()).then_some(sym)
        })
        .collect()
}

#[test]
fn the_selected_row_stays_readable_in_every_view() {
    // The selected row gets a background colour. Any column drawn in that same
    // colour vanishes: the text is present but unreadable. This caught the
    // album and duration disappearing from the highlighted track.
    let tracks = [track(
        "Prophecy At 1420 MHz",
        "Boards of Canada",
        "Inferno",
        304,
    )];
    let playlists = [Playlist {
        id: 1,
        name: "late night".into(),
        len: 27,
    }];

    for (view, all, selection, pls) in [
        (View::Library, &tracks[..], &[][..], &[][..]),
        (View::Selection, &[][..], &tracks[..], &[][..]),
        (View::Playlists, &[][..], &[][..], &playlists[..]),
    ] {
        let hidden = invisible_cells(view, all, selection, pls, 2);
        assert!(
            hidden.is_empty(),
            "{view:?}: {} cells on the selected row have fg == bg: {:?}",
            hidden.len(),
            hidden.concat()
        );
    }
}

#[test]
fn library_lists_tracks_with_artist_album_and_duration() {
    let all = vec![track("Waltz for Debby", "Bill Evans", "Sunday", 396)];
    let joined = Case::new(View::Library, &stopped()).all(&all).text();
    assert!(joined.contains("Bill Evans"), "artist missing:\n{joined}");
    assert!(
        joined.contains("Waltz for Debby"),
        "title missing:\n{joined}"
    );
    assert!(joined.contains("Sunday"), "album missing:\n{joined}");
    assert!(joined.contains("6:36"), "duration missing:\n{joined}");
}

#[test]
fn empty_library_explains_how_to_fill_it() {
    let joined = Case::new(View::Library, &stopped()).text();
    assert!(
        joined.contains("playr scan"),
        "no guidance for an empty library:\n{joined}"
    );
}

#[test]
fn now_playing_shows_title_position_and_source_format() {
    let playing = vec![track("So What", "Miles Davis", "Kind of Blue", 545)];
    let snapshot = Snapshot {
        status: Status {
            state: State::Playing,
            queue: vec![std::path::PathBuf::from("/m/So What.flac")].into(),
            index: 0,
            duration: Some(Duration::from_secs(545)),
            source: Some(Spec {
                rate: 44100,
                channels: 2,
            }),
            output_rate: 44100,
            resampling: false,
            error: None,
            error_seq: 0,
            semitones: 0,
            mode: Default::default(),
        },
        position: Duration::from_secs(151),
        volume: 0.75,
        ..Default::default()
    };
    let joined = Case::new(View::Selection, &snapshot)
        .playing(&playing)
        .text();
    assert!(joined.contains("So What"), "title missing:\n{joined}");
    assert!(joined.contains("Miles Davis"), "artist missing:\n{joined}");
    assert!(joined.contains("2:31"), "position missing:\n{joined}");
    assert!(joined.contains("9:05"), "duration missing:\n{joined}");
    assert!(joined.contains("44.1kHz"), "source rate missing:\n{joined}");
    assert!(joined.contains("75%"), "volume missing:\n{joined}");
}

#[test]
fn resampling_is_shown_when_the_device_forces_it() {
    let mut snapshot = stopped();
    snapshot.status.source = Some(Spec {
        rate: 44100,
        channels: 2,
    });
    snapshot.status.output_rate = 48000;
    snapshot.status.resampling = true;
    let joined = Case::new(View::Selection, &snapshot).text();
    assert!(joined.contains("44.1kHz"), "source rate missing:\n{joined}");
    assert!(joined.contains("48.0kHz"), "device rate missing:\n{joined}");
}

#[test]
fn playback_errors_reach_the_status_line() {
    // The engine reports errors; the app promotes them to a timed message.
    let msg = "bad.opus: unsupported format";
    let joined = Case::new(View::Library, &stopped()).message(msg).text();
    assert!(
        joined.contains("unsupported format"),
        "error not shown:\n{joined}"
    );
}

#[test]
fn search_prompt_replaces_the_library_title() {
    let input = Input::Search("evans".into());
    let joined = Case::new(View::Library, &stopped()).input(&input).text();
    assert!(
        joined.contains("Search: evans"),
        "search prompt missing:\n{joined}"
    );
}

#[test]
fn playlists_show_their_track_counts() {
    let pls = vec![Playlist {
        id: 1,
        name: "late night".into(),
        len: 27,
    }];
    let joined = Case::new(View::Playlists, &stopped())
        .playlists(&pls)
        .text();
    assert!(joined.contains("late night"), "name missing:\n{joined}");
    assert!(joined.contains("27"), "count missing:\n{joined}");
}

#[test]
fn track_rows_never_truncate_the_duration_column() {
    // The duration sits at the right edge; if the column arithmetic is off by
    // even one, it is the first thing to be cut.
    let all = vec![track(
        "A Fairly Long Track Title Here",
        "An Artist Name",
        "An Album Name",
        396,
    )];
    for width in [40u16, 55, 80, 120, 200] {
        let joined = Case::new(View::Library, &stopped())
            .all(&all)
            .size(width, 10)
            .text();
        assert!(
            joined.contains("6:36"),
            "duration truncated at width {width}:\n{joined}"
        );
    }
}

#[test]
fn layout_survives_a_narrow_terminal() {
    let all = vec![track(
        "A Very Long Track Title Indeed",
        "Some Artist",
        "Some Album",
        200,
    )];
    for width in [40u16, 60, 80, 200] {
        let lines = Case::new(View::Library, &stopped())
            .all(&all)
            .size(width, 12)
            .render();
        assert_eq!(lines.len(), 12, "height wrong at width {width}");
        for line in &lines {
            assert!(
                line.chars().count() <= width as usize,
                "line overflows at width {width}: {line:?}"
            );
        }
    }
}

#[test]
fn varispeed_is_shown_but_not_as_a_rate_conversion() {
    // Varispeed engages the resampler at the same rate. Reporting that as
    // "44.1kHz -> 44.1kHz" reads as a fault instead of a speed change.
    let mut snapshot = stopped();
    snapshot.status.source = Some(Spec {
        rate: 44100,
        channels: 2,
    });
    snapshot.status.output_rate = 44100;
    snapshot.status.resampling = true;
    snapshot.status.semitones = 3;

    let joined = Case::new(View::Selection, &snapshot).text();
    assert!(
        joined.contains("1.19x (+3 st)"),
        "speed not shown:\n{joined}"
    );
    assert!(
        !joined.contains("->"),
        "spurious rate conversion shown:\n{joined}"
    );
}

#[test]
fn normal_speed_is_not_announced() {
    let mut snapshot = stopped();
    snapshot.status.source = Some(Spec {
        rate: 44100,
        channels: 2,
    });
    snapshot.status.output_rate = 44100;
    let joined = Case::new(View::Selection, &snapshot).text();
    assert!(
        !joined.contains(" st)"),
        "speed shown when normal:\n{joined}"
    );
}

// --- scrolling long lists ---

#[test]
fn a_cursor_far_down_a_long_library_is_on_screen() {
    let all: Vec<Track> = (0..10_000)
        .map(|i| track(&format!("Song {i:05}"), "A", "B", 60))
        .collect();
    let snapshot = stopped();
    for view in [View::Library, View::Selection] {
        let joined = Case::new(view, &snapshot)
            .all(&all)
            .selection(&all)
            .selected(9_500)
            .text();
        assert!(
            joined.contains("Song 09500"),
            "cursor row not drawn:\n{joined}"
        );
        // Had the list not scrolled, its second row would show.
        assert!(
            !joined.contains("Song 00001"),
            "list did not scroll:\n{joined}"
        );
    }
}

#[test]
fn moving_within_the_view_does_not_scroll() {
    assert_eq!(scroll_offset(100, Some(105), 10, 1_000), 100);
    assert_eq!(scroll_offset(100, Some(100), 10, 1_000), 100);
    assert_eq!(scroll_offset(100, Some(109), 10, 1_000), 100);
}

#[test]
fn leaving_the_view_scrolls_by_the_least_amount() {
    assert_eq!(scroll_offset(100, Some(110), 10, 1_000), 101);
    assert_eq!(scroll_offset(100, Some(99), 10, 1_000), 99);
}

#[test]
fn a_list_that_shrank_is_pulled_back_into_view() {
    // Scrolled to 500 in the library, then a search leaves 3 results.
    assert_eq!(scroll_offset(500, Some(0), 10, 3), 0);
    assert_eq!(scroll_offset(500, None, 10, 30), 20);
}

#[test]
fn an_empty_list_or_area_scrolls_nowhere() {
    assert_eq!(scroll_offset(7, Some(3), 0, 100), 0);
    assert_eq!(scroll_offset(7, None, 10, 0), 0);
}

#[test]
fn a_pending_confirmation_is_shown_in_place_of_the_hints() {
    use playr::ui::Confirm;
    let input = Input::Confirm(Confirm::ReplacePlaylist("late".into()));
    let joined = Case::new(View::Selection, &stopped()).input(&input).text();
    assert!(
        joined.contains("replace playlist \"late\" with the selection? (y/n)"),
        "prompt not shown:\n{joined}"
    );
}

#[test]
fn wide_characters_do_not_push_the_duration_off_the_row() {
    // CJK characters take two cells each. Padding by character count made
    // such a row twice as wide as its columns.
    let all = [
        track("Plain", "Artist", "Album", 599),
        track(
            "\u{6771}\u{4eac}\u{306e}\u{591c}".repeat(12).as_str(),
            "\u{5742}\u{672c}\u{9f8d}\u{4e00}".repeat(4).as_str(),
            "\u{97f3}\u{697d}\u{56f3}\u{9451}".repeat(4).as_str(),
            599,
        ),
    ];
    let width = 100;
    let buf = Case::new(View::Library, &stopped()).all(&all).buffer();
    for y in [2, 3] {
        let tail: String = (width - 5..width - 1)
            .map(|x| buf[(x, y)].symbol())
            .collect();
        assert_eq!(tail, "9:59", "row {y} lost its duration");
    }
}

// --- bottom line and help ---

#[test]
fn the_bottom_line_shows_a_volume_meter_and_the_help_key() {
    let joined = Case::new(View::Library, &stopped()).text();
    assert!(
        joined.contains("vol [########--]  80%"),
        "no volume meter:\n{joined}"
    );
    assert!(joined.contains("? help"), "no help key:\n{joined}");
}

#[test]
fn a_message_shares_the_bottom_line_with_the_indicators() {
    let joined = Case::new(View::Library, &stopped())
        .message("added to selection")
        .text();
    let last = joined
        .lines()
        .rev()
        .find(|l| !l.trim().is_empty())
        .unwrap_or("");
    assert!(
        last.contains("added to selection"),
        "message missing: {last:?}"
    );
    assert!(last.contains("? help"), "indicators missing: {last:?}");
}

#[test]
fn help_lists_every_key_with_its_command_by_view() {
    let input = Input::Help;
    let joined = Case::new(View::Library, &stopped())
        .input(&input)
        .size(100, 80)
        .text();
    let keys = Keymap::default();
    for b in keys.bindings() {
        let command = playr::ui::command::line(b.action.as_ref().unwrap(), b.view);
        let row = joined
            .lines()
            // The command ends its row, so `:down` does not match `:down 10`.
            .find(|l| {
                l.split('\u{2502}')
                    .any(|cell| cell.trim_end().ends_with(&format!(" :{command}")))
            })
            .unwrap_or_else(|| panic!(":{command} missing from key help:\n{joined}"));
        assert!(
            row.split_whitespace().any(|w| w == b.key.to_string()),
            "{} not on the row for :{command}: {row:?}",
            b.key
        );
    }
    // Keys that run the same command share its row.
    assert!(joined.contains(" j down shift-down "), "{joined}");

    // The key list is narrower than its title; the popup widens to show it.
    let short = Case::new(View::Library, &stopped())
        .input(&input)
        .size(80, 24)
        .text();
    assert!(
        short.contains("Keys: j k scroll, any other key closes"),
        "{short}"
    );
}

#[test]
fn the_help_hint_names_the_key_bound_to_the_key_list() {
    use playr::ui::action::{Action, Key};
    let hint = |keys: &Keymap| {
        Case::new(View::Library, &stopped())
            .keys(keys)
            .render()
            .into_iter()
            .rev()
            .find(|l| !l.trim().is_empty())
            .unwrap()
    };
    assert!(hint(&Keymap::default()).ends_with("? help"));
    let mut keys = Keymap::default();
    keys.unbind(None, Key::parse("?").unwrap());
    keys.bind(None, Key::parse("f1").unwrap(), Some(Action::Help));
    assert!(hint(&keys).ends_with("f1 help"), "{}", hint(&keys));
    keys.unbind(None, Key::parse("f1").unwrap());
    assert!(!hint(&keys).contains("help"), "{}", hint(&keys));
}

#[test]
fn help_command_lists_every_command_with_its_arguments_by_view() {
    let input = Input::CommandHelp;
    // Tall enough for the whole list; 80 columns, the smallest common width.
    let joined = Case::new(View::Library, &stopped())
        .input(&input)
        .size(80, 60)
        .text();
    for c in playr::ui::command::COMMANDS {
        let usage = format!(":{} {}", c.name, c.args);
        assert!(
            joined.contains(usage.trim_end()) && joined.contains(c.help),
            ":{} missing from command help:\n{joined}",
            c.name
        );
    }
    // Row numbers, by a row's text inside the border.
    let row = |text: &str| {
        joined
            .lines()
            .position(|l| {
                let inner = l.trim().trim_matches('\u{2502}').trim();
                inner == text || inner.starts_with(&format!("{text} "))
            })
            .unwrap_or_else(|| panic!("no row {text:?}:\n{joined}"))
    };
    let order = [
        "in every view",
        ":quit",
        "library",
        ":toggle",
        "selection",
        ":remove",
        "playlists",
        ":delete",
    ];
    let rows: Vec<usize> = order.iter().map(|t| row(t)).collect();
    assert!(rows.is_sorted(), "out of order: {order:?} at rows {rows:?}");
}

#[test]
fn a_long_help_list_scrolls_and_stops_at_its_end() {
    let input = Input::CommandHelp;
    let snapshot = stopped();
    let case = || {
        Case::new(View::Library, &snapshot)
            .input(&input)
            .size(80, 24)
    };
    let top = case().text();
    assert!(top.contains(":help") && !top.contains(":rename"), "{top}");
    assert!(top.contains("j k scroll"), "no scroll hint:\n{top}");
    let bottom = case().help_scroll(1000).text();
    assert!(
        bottom.contains(":rename") && !bottom.contains(":help"),
        "{bottom}"
    );
}

#[test]
fn a_command_being_typed_is_shown_in_place_of_the_hints() {
    let mut line = playr::ui::command::CommandLine::default();
    "seek 1:23".chars().for_each(|c| line.push(c));
    let input = Input::Command(line);
    let joined = Case::new(View::Library, &stopped()).input(&input).text();
    let last = joined.lines().rev().find(|l| !l.trim().is_empty()).unwrap();
    assert_eq!(last.trim(), ":seek 1:23_");
}

// --- level meter ---

fn playing(loudness: Option<f32>, peak: Option<f32>) -> Snapshot {
    let mut snapshot = stopped();
    snapshot.status.state = State::Playing;
    snapshot.loudness = loudness;
    snapshot.peak = peak;
    snapshot
}

/// The last non-blank line of a frame `width` wide.
fn bottom_line(snapshot: &Snapshot, width: u16, message: Option<&str>) -> String {
    let mut case = Case::new(View::Library, snapshot).size(width, 12);
    if let Some(m) = message {
        case = case.message(m);
    }
    case.render()
        .into_iter()
        .rev()
        .find(|l| !l.trim().is_empty())
        .unwrap_or_default()
}

/// The loudness bar's cells, between the first `[` and `]` on `line`.
fn bar_of(line: &str) -> &str {
    let open = line.find('[').expect("no bar");
    let close = line[open..].find(']').expect("no bar end") + open;
    &line[open + 1..close]
}

#[test]
fn the_loudness_bar_fills_the_free_space_on_the_bottom_line() {
    let snapshot = playing(Some(-18.2), Some(-3.1));
    let narrow = bottom_line(&snapshot, 100, None);
    let wide = bottom_line(&snapshot, 160, None);
    let (narrow_cells, wide_cells) = (bar_of(&narrow).len(), bar_of(&wide).len());
    assert!(
        narrow_cells > 40,
        "{narrow_cells} cells at 100 columns: {narrow:?}"
    );
    assert_eq!(
        wide_cells,
        narrow_cells + 60,
        "the bar did not grow with the line"
    );
    assert!(
        narrow.contains("] -18.2 LUFS  pk  -3.1"),
        "readout not beside the bar: {narrow:?}"
    );
    assert!(
        narrow.contains("vol [########--]"),
        "volume missing: {narrow:?}"
    );
}

#[test]
fn the_bar_fill_and_peak_marker_follow_the_level() {
    let line = bottom_line(&playing(Some(-18.2), Some(-3.1)), 120, None);
    let bar = bar_of(&line);
    let cells = bar.len() as f32;
    // -40 dB to 0 across the bar: -18.2 LUFS fills 54.5%, the -3.1 peak sits at 92.25%.
    let filled = bar.chars().filter(|c| *c == '#').count();
    assert_eq!(filled, (0.545 * cells).round() as usize, "{bar}");
    assert_eq!(
        bar.find('|'),
        Some((0.9225 * cells).round() as usize - 1),
        "{bar}"
    );
}

#[test]
fn the_meter_is_hidden_unless_playing() {
    let joined = Case::new(View::Library, &stopped()).text();
    assert!(
        !joined.contains("LUFS"),
        "meter shown while stopped:\n{joined}"
    );
}

#[test]
fn silence_shows_an_empty_meter() {
    let line = bottom_line(&playing(None, None), 100, None);
    assert!(bar_of(&line).chars().all(|c| c == '-'), "{line:?}");
    assert!(line.contains("]    -- LUFS  pk    --"), "{line:?}");
}

#[test]
fn a_message_takes_the_bars_place_and_the_readout_stays() {
    let line = bottom_line(
        &playing(Some(-18.2), Some(-3.1)),
        100,
        Some("added to selection"),
    );
    assert!(line.contains("added to selection"), "{line:?}");
    assert!(line.contains("-18.2 LUFS"), "readout hidden: {line:?}");
    // The volume bar is the only bracketed bar left.
    assert_eq!(line.matches('[').count(), 1, "bar still drawn: {line:?}");
}

#[test]
fn the_meter_never_overflows_a_narrow_terminal() {
    let snapshot = playing(Some(-18.2), Some(-3.1));
    for width in [30u16, 50, 70] {
        let lines = Case::new(View::Library, &snapshot).size(width, 12).render();
        for line in lines {
            assert!(
                line.chars().count() <= width as usize,
                "overflow at {width}: {line:?}"
            );
        }
    }
}

#[test]
fn a_peak_is_held_then_released() {
    use playr::ui::{hold_peak, PEAK_HOLD};
    use std::time::Instant;
    let start = Instant::now();
    let held = hold_peak(None, 0.9, start);
    assert_eq!(held, Some((0.9, start)));
    // A lower reading inside the hold keeps the peak.
    let soon = start + PEAK_HOLD / 2;
    assert_eq!(hold_peak(held, 0.2, soon), held);
    // A higher one replaces it at once.
    assert_eq!(hold_peak(held, 0.95, soon), Some((0.95, soon)));
    // Once the hold has passed, the current reading shows.
    let later = start + PEAK_HOLD;
    assert_eq!(hold_peak(held, 0.2, later), Some((0.2, later)));
    assert_eq!(hold_peak(held, 0.0, later), None);
}

// --- pane titles ---

#[test]
fn panes_do_not_repeat_the_tabs() {
    let tracks = vec![track("So What", "Miles Davis", "Kind of Blue", 545)];
    let playlists = vec![Playlist {
        id: 1,
        name: "late".into(),
        len: 1,
    }];
    for view in [View::Library, View::Selection, View::Playlists] {
        let lines = Case::new(view, &stopped())
            .all(&tracks)
            .selection(&tracks)
            .playlists(&playlists)
            .render();
        // Row 0 is the tabs; row 1 is the pane's top border.
        assert!(
            lines[0].contains("Library 1"),
            "tabs lost their counts: {:?}",
            lines[0]
        );
        assert!(
            lines[1].chars().all(|c| !c.is_alphanumeric()),
            "{view:?} pane is titled: {:?}",
            lines[1]
        );
    }
}

#[test]
fn search_results_say_how_to_leave_them() {
    let tracks = vec![track("So What", "Miles Davis", "Kind of Blue", 545)];
    let lines = Case::new(View::Library, &stopped())
        .all(&tracks)
        .results(&tracks)
        .render();
    assert!(
        lines[1].contains("Search results (esc clears)"),
        "{:?}",
        lines[1]
    );
}

/// Symbol and foreground colour of each loudness bar cell, drawn `width` wide.
fn bar_cells(snapshot: &Snapshot, width: u16) -> Vec<(String, ratatui::style::Color)> {
    let buf = Case::new(View::Library, snapshot).size(width, 12).buffer();
    let row = (0..buf.area.height)
        .find(|&y| {
            let line: String = (0..width).map(|x| buf[(x, y)].symbol()).collect();
            line.contains("LUFS")
        })
        .expect("no meter row");
    let symbols: Vec<(String, ratatui::style::Color)> = (0..width)
        .map(|x| (buf[(x, row)].symbol().to_string(), buf[(x, row)].fg))
        .collect();
    let open = symbols.iter().position(|(s, _)| s == "[").unwrap();
    let close = symbols[open..].iter().position(|(s, _)| s == "]").unwrap() + open;
    symbols[open + 1..close].to_vec()
}

/// The zone a cell's centre falls in: green below -18 dB, yellow to -6, red above.
fn expected_zone(i: usize, cells: usize) -> ratatui::style::Color {
    use ratatui::style::Color;
    let db = -40.0 * (1.0 - (i as f32 + 0.5) / cells as f32);
    match db {
        _ if db >= -6.0 => Color::Red,
        _ if db >= -18.0 => Color::Yellow,
        _ => Color::Green,
    }
}

#[test]
fn the_bar_is_green_then_yellow_then_red_by_position() {
    use ratatui::style::Color;
    let cells = bar_cells(&playing(Some(-2.0), Some(-1.0)), 120);
    let n = cells.len();
    let mut zones = Vec::new();
    for (i, (symbol, fg)) in cells.iter().enumerate() {
        match symbol.as_str() {
            "#" | "|" => {
                assert_eq!(*fg, expected_zone(i, n), "cell {i} of {n} ({symbol})");
                if zones.last() != Some(fg) {
                    zones.push(*fg);
                }
            }
            "-" => assert_eq!(*fg, Color::DarkGray, "empty cell {i} is coloured"),
            other => panic!("unexpected {other:?} in the bar"),
        }
    }
    assert_eq!(zones, [Color::Green, Color::Yellow, Color::Red]);
    let marker = cells
        .iter()
        .find(|(s, _)| s == "|")
        .expect("no peak marker");
    assert_eq!(marker.1, Color::Red, "a -1 dBFS peak is in the red zone");
}

#[test]
fn a_quiet_signal_stays_green() {
    use ratatui::style::Color;
    let cells = bar_cells(&playing(Some(-30.0), Some(-24.0)), 120);
    for (symbol, fg) in &cells {
        if symbol == "#" || symbol == "|" {
            assert_eq!(*fg, Color::Green, "{symbol} is {fg:?} at -30 LUFS");
        }
    }
}

// --- selection marker ---

#[test]
fn selected_tracks_are_marked_in_the_library_but_not_in_the_selection() {
    let all = vec![
        track("Alpha", "A", "X", 60),
        track("Bravo", "A", "X", 60),
        track("Charlie", "A", "X", 60),
    ];
    let selection = vec![all[0].clone(), all[2].clone()];
    let mut snapshot = stopped();
    snapshot.status.state = State::Playing;
    snapshot.status.queue = vec![std::path::PathBuf::from(&all[0].path)].into();

    let lines = Case::new(View::Library, &snapshot)
        .all(&all)
        .selection(&selection)
        .render();
    // Row 2 onwards are the tracks; the gutter is the two cells after the border.
    let gutter = |row: usize| lines[row].chars().skip(1).take(2).collect::<String>();
    assert_eq!(gutter(2), ">+", "playing and selected: {:?}", lines[2]);
    assert_eq!(gutter(3), "  ", "neither: {:?}", lines[3]);
    assert_eq!(gutter(4), " +", "selected: {:?}", lines[4]);

    let lines = Case::new(View::Selection, &snapshot)
        .selection(&selection)
        .render();
    for row in [2, 3] {
        assert!(
            !lines[row].contains('+'),
            "marked in the selection: {:?}",
            lines[row]
        );
    }
}

#[test]
fn the_mode_shows_on_the_bottom_line_unless_normal() {
    use playr::audio::Mode;
    let normal = Case::new(View::Library, &stopped()).text();
    assert!(
        !normal.contains("normal"),
        "normal mode announced:\n{normal}"
    );
    for mode in [Mode::Shuffle, Mode::Repeat, Mode::RepeatOne] {
        let mut snapshot = stopped();
        snapshot.status.mode = mode;
        let joined = Case::new(View::Library, &snapshot).text();
        assert!(
            joined.contains(mode.name()),
            "{mode:?} not shown:\n{joined}"
        );
    }
}

#[test]
fn the_rename_prompt_names_the_playlist() {
    let input = Input::RenamePlaylist {
        from: Playlist {
            id: 1,
            name: "late".into(),
            len: 3,
        },
        name: "night".into(),
    };
    let joined = Case::new(View::Playlists, &stopped()).input(&input).text();
    assert!(joined.contains("rename \"late\" to: night_"), "{joined}");
}

// --- marks ---

#[test]
fn marks_show_under_the_progress_bar_where_they_fall() {
    let mut snapshot = stopped();
    snapshot.status.state = State::Playing;
    snapshot.status.duration = Some(Duration::from_secs(100));
    snapshot.marks = vec![
        Duration::ZERO,
        Duration::from_secs(50),
        Duration::from_secs(100),
    ];
    let lines = Case::new(View::Library, &snapshot).size(100, 12).render();
    let bar = lines
        .iter()
        .position(|l| l.contains("0:00 / 1:40"))
        .expect("no progress bar");
    let ticks = &lines[bar + 1];
    let columns: Vec<usize> = ticks.match_indices('^').map(|(i, _)| i).collect();
    // The bar is inset one cell either side: 98 cells from column 1.
    let at = |fraction: f64| 1 + (fraction * 97.0).round() as usize;
    assert_eq!(columns, [at(0.0), at(0.5), at(1.0)], "ticks row: {ticks:?}");

    snapshot.status.duration = None;
    let lines = Case::new(View::Library, &snapshot).size(100, 12).render();
    assert!(
        !lines.iter().any(|l| l.contains('^')),
        "marks drawn without a duration"
    );
}