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
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
//! Terminal interface.
//!
//! One thread: it renders, reads keys, and talks to the player over a channel.
//! Nothing here blocks on audio.

pub mod action;
pub mod command;
pub mod config;
pub mod render;

use std::collections::{HashMap, HashSet};
use std::path::PathBuf;
use std::sync::Arc;
use std::time::{Duration, Instant};

use ratatui::crossterm::event::{self, Event, KeyCode, KeyEvent, KeyEventKind, KeyModifiers};
use ratatui::widgets::ListState;
use rusqlite::Connection;

use crate::audio::{Cmd, Player, State, Status};
use crate::db::query::{self, Mark, Playlist};
use crate::db::Track;
use action::{Action, Keymap};
use command::{CommandLine, History};
use config::Config;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum View {
    Library,
    Selection,
    Playlists,
}

impl View {
    fn next(self) -> Self {
        match self {
            View::Library => View::Selection,
            View::Selection => View::Playlists,
            View::Playlists => View::Library,
        }
    }

    fn title(self) -> &'static str {
        match self {
            View::Library => "Library",
            View::Selection => "Selection",
            View::Playlists => "Playlists",
        }
    }
}

/// What typed input is currently being collected.
pub enum Input {
    None,
    Search(String),
    SavePlaylist(String),
    /// A new name for the playlist `from`, being typed.
    RenamePlaylist {
        from: Playlist,
        name: String,
    },
    /// Waiting for `y` before an action that cannot be undone.
    Confirm(Confirm),
    /// The key list is open; the next key closes it.
    Help,
    /// The command list is open; the next key closes it.
    CommandHelp,
    /// A `:` command being typed.
    Command(CommandLine),
}

/// A destructive action held until the listener confirms it.
pub enum Confirm {
    DeletePlaylist(Playlist),
    /// Overwrite the playlist of this name with the selection.
    ReplacePlaylist(String),
    /// Empty the selection, which holds this many tracks.
    ClearSelection(usize),
    /// Remove this many marks from the playing track.
    ClearMarks(usize),
}

impl Confirm {
    pub fn prompt(&self) -> String {
        match self {
            Confirm::DeletePlaylist(p) => format!("delete playlist \"{}\"? (y/n)", p.name),
            Confirm::ReplacePlaylist(name) => {
                format!("replace playlist \"{name}\" with the selection? (y/n)")
            }
            Confirm::ClearSelection(n) => format!("clear all {n} tracks from the selection? (y/n)"),
            Confirm::ClearMarks(n) => format!("clear all {n} marks from this track? (y/n)"),
        }
    }
}

pub struct App {
    conn: Connection,
    player: Player,
    view: View,

    /// Every track in the library, loaded once.
    all: Vec<Track>,
    /// Search results; when set, the library view shows these instead.
    results: Option<Vec<Track>>,
    library_state: ListState,

    /// Rows for the list the player is playing from.
    playing: Vec<Track>,
    /// The player list `playing` was built from, compared by identity.
    playing_source: Arc<[PathBuf]>,

    /// Tracks collected with `a`, to edit and save as a playlist. It does not
    /// change what plays unless it is played itself.
    selection: Vec<Track>,
    selection_state: ListState,

    playlists: Vec<Playlist>,
    playlist_state: ListState,

    input: Input,
    /// `:` command lines entered this session.
    history: History,
    keys: Keymap,
    /// Rows the key or command list is scrolled by.
    help_scroll: usize,
    message: Option<(String, Instant)>,
    quit: bool,

    /// Last error sequence shown, so each new one is surfaced exactly once.
    seen_error: u64,
    /// The peak shown, as a sample magnitude, and when it was reached.
    peak_hold: Option<(f32, Instant)>,
    /// Marks in the track `marks_for`, earliest first.
    marks: Vec<Mark>,
    marks_for: Option<PathBuf>,

    /// One snapshot of the player per frame.
    ///
    /// Taken once and shared by every widget: reading the player separately in
    /// each one can mix three different instants into a single frame, showing a
    /// track title from before a change next to a position from after it.
    snapshot: Snapshot,
}

/// Everything the drawing code reads.
///
/// Rendering takes this rather than the whole `App` so it can be exercised
/// against a `TestBackend` without an audio device.
pub struct Screen<'a> {
    pub view: View,
    pub snapshot: &'a Snapshot,
    pub all: &'a [Track],
    pub results: Option<&'a [Track]>,
    /// Rows for the list the player is playing from.
    pub playing: &'a [Track],
    pub selection: &'a [Track],
    pub playlists: &'a [Playlist],
    pub input: &'a Input,
    pub keys: &'a Keymap,
    /// Rows the key or command list is scrolled by; drawing clamps it.
    pub help_scroll: &'a mut usize,
    pub message: Option<&'a str>,
    pub library_state: &'a mut ListState,
    pub selection_state: &'a mut ListState,
    pub playlist_state: &'a mut ListState,
}

impl Screen<'_> {
    /// The track list the library pane is showing.
    pub fn visible(&self) -> &[Track] {
        self.results.unwrap_or(self.all)
    }
}

/// What the widgets need to know about playback, sampled once per frame.
#[derive(Debug, Clone, Default)]
pub struct Snapshot {
    pub status: Status,
    pub position: Duration,
    pub volume: f32,
    /// Momentary loudness in LUFS; `None` for silence.
    pub loudness: Option<f32>,
    /// The highest recent sample peak in dBFS, held for [`PEAK_HOLD`].
    pub peak: Option<f32>,
    /// Marks in the playing track, as times into it, earliest first.
    pub marks: Vec<Duration>,
}

impl App {
    pub fn new(conn: Connection, player: Player) -> Self {
        Self::with_selection(conn, player, Vec::new())
    }

    /// Builds the app with `tracks` selected and playing, as the CLI hands
    /// them over, so the files played are also listed.
    pub fn with_selection(conn: Connection, player: Player, tracks: Vec<Track>) -> Self {
        Self::configured(conn, player, tracks, Config::default())
    }

    /// As [`App::with_selection`], with the keys, volume, mode and speed of
    /// `config`. They apply before `tracks` start, so a shuffle covers them.
    pub fn configured(
        conn: Connection,
        player: Player,
        tracks: Vec<Track>,
        config: Config,
    ) -> Self {
        let mut app = App {
            conn,
            player,
            view: View::Library,
            all: Vec::new(),
            results: None,
            library_state: ListState::default(),
            playing: Vec::new(),
            playing_source: Arc::default(),
            selection: Vec::new(),
            selection_state: ListState::default(),
            playlists: Vec::new(),
            playlist_state: ListState::default(),
            input: Input::None,
            history: History::default(),
            keys: config.keys,
            help_scroll: 0,
            message: None,
            quit: false,
            seen_error: 0,
            peak_hold: None,
            marks: Vec::new(),
            marks_for: None,
            snapshot: Snapshot::default(),
        };
        app.player.send(Cmd::SetVolume(config.volume));
        app.player.send(Cmd::SetMode(config.mode));
        app.player.send(Cmd::SetSpeed(config.speed));
        if !tracks.is_empty() {
            app.selection = tracks.clone();
            app.selection_state.select(Some(0));
            app.play(tracks, 0);
            app.view = View::Selection;
        }
        app.reload();
        app
    }

    /// Rebuilds `playing` if the player's list is no longer the one it shows.
    ///
    /// Playing from here updates `playing` directly; this catches any other change.
    fn follow_player(&mut self) {
        let current = self.player.queue();
        if Arc::ptr_eq(&current, &self.playing_source) {
            return;
        }
        let known: HashMap<&str, &Track> = self
            .playing
            .iter()
            .chain(&self.selection)
            .chain(&self.all)
            .map(|t| (t.path.as_str(), t))
            .collect();
        self.playing = current
            .iter()
            .map(|p| {
                let path = p.to_string_lossy();
                known
                    .get(path.as_ref())
                    .map(|t| (*t).clone())
                    .unwrap_or(Track {
                        path: path.into_owned(),
                        ..Default::default()
                    })
            })
            .collect();
        self.playing_source = current;
    }

    fn reload(&mut self) {
        self.all = query::all(&self.conn).unwrap_or_default();
        self.playlists = query::playlists(&self.conn).unwrap_or_default();
        if !self.all.is_empty() && self.library_state.selected().is_none() {
            self.library_state.select(Some(0));
        }
        if !self.playlists.is_empty() && self.playlist_state.selected().is_none() {
            self.playlist_state.select(Some(0));
        }
    }

    /// The track list the library view is currently showing.
    fn visible(&self) -> &[Track] {
        self.results.as_deref().unwrap_or(&self.all)
    }

    /// Borrows the state the renderer needs.
    pub fn screen(&mut self) -> Screen<'_> {
        Screen {
            view: self.view,
            snapshot: &self.snapshot,
            all: &self.all,
            results: self.results.as_deref(),
            playing: &self.playing,
            selection: &self.selection,
            playlists: &self.playlists,
            input: &self.input,
            keys: &self.keys,
            help_scroll: &mut self.help_scroll,
            message: self.message.as_ref().map(|(m, _)| m.as_str()),
            library_state: &mut self.library_state,
            selection_state: &mut self.selection_state,
            playlist_state: &mut self.playlist_state,
        }
    }

    pub fn run(mut self, terminal: &mut ratatui::DefaultTerminal) -> std::io::Result<()> {
        while !self.quit {
            self.refresh();
            terminal.draw(|f| render::draw(&mut self.screen(), f))?;

            // A short poll keeps the progress bar moving without busy-waiting.
            if event::poll(Duration::from_millis(200))? {
                if let Event::Key(key) = event::read()? {
                    if key.kind == KeyEventKind::Press {
                        self.on_key(key);
                    }
                }
            }
            if let Some((_, at)) = &self.message {
                if at.elapsed() > Duration::from_secs(4) {
                    self.message = None;
                }
            }
        }
        Ok(())
    }

    /// Samples the player for the next frame, and shows any new error once.
    pub fn refresh(&mut self) {
        self.follow_player();
        self.peak_hold = hold_peak(self.peak_hold, self.player.take_peak(), Instant::now());
        self.snapshot = Snapshot {
            status: self.player.status(),
            position: self.player.position(),
            volume: self.player.volume(),
            loudness: self.player.loudness(),
            peak: self.peak_hold.map(|(p, _)| 20.0 * p.log10()),
            marks: Vec::new(),
        };
        let current = self.snapshot.status.current().cloned();
        self.follow_marks(current.as_ref());
        self.snapshot.marks = self.marks.iter().map(Mark::time).collect();
        let seq = self.snapshot.status.error_seq;
        if seq > self.seen_error {
            let missed = seq - self.seen_error - 1;
            self.seen_error = seq;
            if let Some(e) = self.snapshot.status.error.clone() {
                // Only the latest error is kept, so a run of bad files would
                // otherwise show one name and hide the rest.
                if missed > 0 {
                    self.notify(format!("{e} (and {missed} more)"));
                } else {
                    self.notify(e);
                }
            }
        }
    }

    fn notify(&mut self, msg: impl Into<String>) {
        self.message = Some((msg.into(), Instant::now()));
    }

    /// Whether a key has asked the interface to exit.
    pub fn quitting(&self) -> bool {
        self.quit
    }

    /// Handles one key press.
    pub fn on_key(&mut self, key: KeyEvent) {
        self.follow_player();
        // Before text entry, which would otherwise type it as `c`.
        if key.modifiers.contains(KeyModifiers::CONTROL) && key.code == KeyCode::Char('c') {
            self.quit = true;
            return;
        }

        // Text entry swallows most keys.
        match &self.input {
            Input::Confirm(_) => {
                let Input::Confirm(action) = std::mem::replace(&mut self.input, Input::None) else {
                    unreachable!()
                };
                // Anything but `y` cancels, so a stray key cannot confirm.
                if typed(&key) == Some('y') {
                    self.confirm(action);
                } else {
                    self.notify("cancelled");
                }
                return;
            }
            Input::Help | Input::CommandHelp => {
                // The lists can be longer than the screen.
                match key.code {
                    KeyCode::Char('j') | KeyCode::Down => self.help_scroll += 1,
                    KeyCode::Char('k') | KeyCode::Up => {
                        self.help_scroll = self.help_scroll.saturating_sub(1)
                    }
                    KeyCode::PageDown => self.help_scroll += 10,
                    KeyCode::PageUp => self.help_scroll = self.help_scroll.saturating_sub(10),
                    _ => self.input = Input::None,
                }
                return;
            }
            Input::Command(line) => {
                let line = line.clone();
                return self.command_key(key, line);
            }
            Input::Search(buf) => {
                let buf = buf.clone();
                return self.search_key(key, buf);
            }
            Input::SavePlaylist(buf) => {
                let buf = buf.clone();
                return self.save_key(key, buf);
            }
            Input::RenamePlaylist { from, name } => {
                let (from, name) = (from.clone(), name.clone());
                return self.rename_key(key, from, name);
            }
            Input::None => {}
        }

        if let Some(action) = self.keys.lookup((&key).into(), self.view).cloned() {
            self.perform(action);
        }
    }

    /// Does `action`. Keys and `:` commands both arrive here.
    pub fn perform(&mut self, action: Action) {
        self.follow_player();
        match action {
            Action::Quit => self.quit = true,
            Action::Help => {
                self.help_scroll = 0;
                self.input = Input::Help;
            }
            Action::CommandHelp => {
                self.help_scroll = 0;
                self.input = Input::CommandHelp;
            }
            Action::ShowView(view) => self.view = view,
            Action::NextView => self.view = self.view.next(),
            Action::Cursor(rows) => self.move_selection(rows),
            Action::CursorFirst => self.select(0),
            Action::CursorLast => self.select(self.len().saturating_sub(1)),
            Action::StartSearch => self.input = Input::Search(String::new()),
            Action::Search(query) => {
                self.apply_search(&query);
                if self.visible().is_empty() {
                    self.notify("no matches");
                }
            }
            Action::ClearSearch => {
                if self.results.take().is_some() {
                    self.library_state.select(Some(0));
                }
            }
            Action::StartCommand => self.input = Input::Command(CommandLine::default()),
            Action::Activate => self.activate(),

            Action::Add => self.append_selection(),
            Action::Remove => self.remove_from_selection(),
            Action::MoveTrack(delta) => self.move_in_selection(delta),
            Action::ClearSelection => {
                if self.selection.is_empty() {
                    self.notify("selection is empty");
                } else {
                    self.input = Input::Confirm(Confirm::ClearSelection(self.selection.len()));
                }
            }
            Action::StartSave => {
                if self.can_save() {
                    self.input = Input::SavePlaylist(String::new());
                }
            }
            Action::SaveAs(name) => {
                if self.can_save() {
                    self.save_as(&name);
                }
            }
            Action::DeletePlaylist => self.delete_playlist(),
            Action::StartRename => self.start_rename(),
            Action::RenameTo(name) => match self.playlist_under_cursor() {
                Some(from) => self.rename_to(&from, &name),
                None => self.notify("no playlist under the cursor in the playlists view"),
            },
            Action::PlayPlaylist(name) => self.play_playlist_named(&name),

            Action::TogglePause => self.player.send(Cmd::TogglePause),
            Action::Next => self.player.send(Cmd::Next),
            Action::Prev => self.player.send(Cmd::Prev),
            Action::Stop => self.player.send(Cmd::Stop),
            Action::SeekBy(seconds) => self.player.send(Cmd::SeekBy(seconds)),
            Action::SeekTo(at) => self.player.send(Cmd::Seek(at)),
            Action::VolumeBy(delta) => self.nudge_volume(delta),
            Action::SetVolume(v) => self.player.send(Cmd::SetVolume(v)),
            Action::SpeedBy(semitones) => self.player.send(Cmd::SpeedBy(semitones)),
            Action::SetSpeed(semitones) => self.player.send(Cmd::SetSpeed(semitones)),
            Action::CycleMode(forward) => self.cycle_mode(forward),
            Action::SetMode(mode) => {
                self.player.send(Cmd::SetMode(mode));
                self.notify(format!("mode: {}", mode.name()));
            }

            Action::Mark => self.add_mark(None),
            Action::MarkAt(at) => self.add_mark(Some(at)),
            Action::UndoMark => self.undo_mark(),
            Action::ClearMarks => self.ask_to_clear_marks(),
            Action::NextMark => self.jump_to_mark(true),
            Action::PrevMark => self.jump_to_mark(false),

            Action::Map { view, key, action } => {
                let shown = command::line(
                    &Action::Map {
                        view,
                        key,
                        action: action.clone(),
                    },
                    None,
                );
                self.keys.bind(view, key, action.map(|a| *a));
                self.notify(shown);
            }
            Action::Unmap { view, key } => {
                if self.keys.unbind(view, key) {
                    self.notify(format!("unmapped {key}"));
                } else {
                    self.notify(format!("{key} has no binding {}", command::scope(view)));
                }
            }
        }
    }

    /// Whether the selection can be saved, saying why not when it cannot.
    fn can_save(&mut self) -> bool {
        if self.selection.is_empty() {
            self.notify("selection is empty");
            false
        } else if self.conn.path().is_none_or(str::is_empty) {
            // In memory, the playlist would be lost on exit.
            self.notify("no library to save to; `playr scan <dir>` creates one");
            false
        } else {
            true
        }
    }

    /// Saves the selection as `name`, asking first if that replaces a playlist.
    fn save_as(&mut self, name: &str) {
        let name = name.trim();
        if name.is_empty() {
            self.notify("playlist name cannot be empty");
        } else if self.playlists.iter().any(|p| p.name == name) {
            self.input = Input::Confirm(Confirm::ReplacePlaylist(name.to_string()));
        } else {
            self.save_selection(name);
        }
    }

    fn playlist_under_cursor(&self) -> Option<Playlist> {
        if self.view != View::Playlists {
            return None;
        }
        self.playlist_state
            .selected()
            .and_then(|i| self.playlists.get(i))
            .cloned()
    }

    fn play_playlist_named(&mut self, name: &str) {
        let Some(pl) = query::find_playlist(&self.playlists, name.trim()).cloned() else {
            return self.notify(format!("no single playlist named \"{}\"", name.trim()));
        };
        let tracks = query::playlist_tracks(&self.conn, pl.id).unwrap_or_default();
        if tracks.is_empty() {
            return self.notify("playlist is empty");
        }
        self.play(tracks, 0);
        self.notify(format!("playing \"{}\"", pl.name));
    }

    fn command_key(&mut self, key: KeyEvent, mut line: CommandLine) {
        match key.code {
            KeyCode::Esc => return self.input = Input::None,
            KeyCode::Enter => {
                self.input = Input::None;
                if line.text.trim().is_empty() {
                    return;
                }
                // Recorded even when it fails, so a typo can be recalled and fixed.
                self.history.push(&line.text);
                match command::parse(&line.text, self.view) {
                    Ok(action) => self.perform(action),
                    Err(e) => self.notify(e),
                }
                return;
            }
            // Deleting past the colon closes the prompt, as in vim.
            KeyCode::Backspace if !line.pop() => return self.input = Input::None,
            KeyCode::Tab | KeyCode::BackTab => {
                let names: Vec<String> = self.playlists.iter().map(|p| p.name.clone()).collect();
                line.complete(key.code == KeyCode::Tab, self.view, &names);
            }
            KeyCode::Up => line.recall(true, &self.history),
            KeyCode::Down => line.recall(false, &self.history),
            _ => {
                if let Some(c) = typed(&key) {
                    line.push(c);
                }
            }
        }
        self.input = Input::Command(line);
    }

    fn search_key(&mut self, key: KeyEvent, mut buf: String) {
        match key.code {
            KeyCode::Esc => {
                self.input = Input::None;
                self.results = None;
            }
            KeyCode::Enter => {
                self.input = Input::None;
                if self.visible().is_empty() {
                    self.notify("no matches");
                }
            }
            KeyCode::Backspace => {
                buf.pop();
                self.apply_search(&buf);
                self.input = Input::Search(buf);
            }
            KeyCode::Char(c) if typed(&key).is_some() => {
                buf.push(c);
                self.apply_search(&buf);
                self.input = Input::Search(buf);
            }
            _ => self.input = Input::Search(buf),
        }
    }

    fn apply_search(&mut self, term: &str) {
        self.view = View::Library;
        if term.is_empty() {
            self.results = None;
        } else {
            self.results = Some(query::search(&self.conn, term).unwrap_or_default());
        }
        self.library_state.select(if self.visible().is_empty() {
            None
        } else {
            Some(0)
        });
    }

    fn save_key(&mut self, key: KeyEvent, mut buf: String) {
        match key.code {
            KeyCode::Esc => self.input = Input::None,
            KeyCode::Enter => {
                self.input = Input::None;
                self.save_as(&buf);
            }
            KeyCode::Backspace => {
                buf.pop();
                self.input = Input::SavePlaylist(buf);
            }
            KeyCode::Char(c) if typed(&key).is_some() => {
                buf.push(c);
                self.input = Input::SavePlaylist(buf);
            }
            _ => self.input = Input::SavePlaylist(buf),
        }
    }

    fn start_rename(&mut self) {
        let Some(from) = self.playlist_under_cursor() else {
            return self.notify("no playlist under the cursor in the playlists view");
        };
        // Starts from the current name, which is usually a small edit away.
        let name = from.name.clone();
        self.input = Input::RenamePlaylist { from, name };
    }

    fn rename_key(&mut self, key: KeyEvent, from: Playlist, mut name: String) {
        match key.code {
            KeyCode::Esc => self.input = Input::None,
            KeyCode::Enter => {
                self.input = Input::None;
                self.rename_to(&from, &name);
            }
            KeyCode::Backspace => {
                name.pop();
                self.input = Input::RenamePlaylist { from, name };
            }
            KeyCode::Char(c) if typed(&key).is_some() => {
                name.push(c);
                self.input = Input::RenamePlaylist { from, name };
            }
            _ => self.input = Input::RenamePlaylist { from, name },
        }
    }

    /// Renames `from` to `name`, unless the name is empty, unchanged or taken.
    fn rename_to(&mut self, from: &Playlist, name: &str) {
        let name = name.trim();
        if name.is_empty() {
            self.notify("playlist name cannot be empty");
        } else if name == from.name {
            self.notify("name unchanged");
        } else if self.playlists.iter().any(|p| p.name == name) {
            // Renaming onto it would have to merge or replace two playlists.
            self.notify(format!("a playlist named \"{name}\" already exists"));
        } else {
            self.rename_playlist(from, name);
        }
    }

    fn rename_playlist(&mut self, from: &Playlist, name: &str) {
        if let Err(e) = query::rename_playlist(&self.conn, from.id, name) {
            return self.notify(format!("could not rename: {e}"));
        }
        self.playlists = query::playlists(&self.conn).unwrap_or_default();
        // The list is sorted by name, so the renamed playlist may have moved.
        let at = self.playlists.iter().position(|p| p.id == from.id);
        self.playlist_state.select(at);
        self.notify(format!("renamed \"{}\" to \"{name}\"", from.name));
    }

    fn save_selection(&mut self, name: &str) {
        let ids: Vec<i64> = self
            .selection
            .iter()
            .map(|t| t.id)
            .filter(|id| *id != 0)
            .collect();
        match query::save_playlist(&mut self.conn, name, &ids) {
            Ok(_) => {
                // A playlist can only hold library tracks; `playr <path>` selects others.
                let left_out = self.selection.len() - ids.len();
                let note = if left_out > 0 {
                    format!(", {left_out} not in the library left out")
                } else {
                    String::new()
                };
                self.notify(format!("saved \"{name}\" ({} tracks{note})", ids.len()));
                self.playlists = query::playlists(&self.conn).unwrap_or_default();
            }
            Err(e) => self.notify(format!("could not save: {e}")),
        }
    }

    fn confirm(&mut self, action: Confirm) {
        match action {
            Confirm::ReplacePlaylist(name) => self.save_selection(&name),
            Confirm::ClearMarks(_) => {
                let Some(path) = self.marks_for.clone() else {
                    return;
                };
                match query::clear_marks(&self.conn, &path.to_string_lossy()) {
                    Ok(_) => {
                        self.marks.clear();
                        self.notify("marks cleared");
                    }
                    Err(e) => self.notify(format!("could not clear marks: {e}")),
                }
            }
            Confirm::ClearSelection(_) => {
                self.selection.clear();
                self.selection_state.select(None);
                self.notify("selection cleared");
            }
            Confirm::DeletePlaylist(pl) => {
                if query::delete_playlist(&self.conn, pl.id).is_ok() {
                    self.playlists = query::playlists(&self.conn).unwrap_or_default();
                    self.view = View::Playlists;
                    self.select(self.playlist_state.selected().unwrap_or(0));
                    self.notify(format!("deleted \"{}\"", pl.name));
                }
            }
        }
    }

    fn len(&self) -> usize {
        match self.view {
            View::Library => self.visible().len(),
            View::Selection => self.selection.len(),
            View::Playlists => self.playlists.len(),
        }
    }

    fn state_mut(&mut self) -> &mut ListState {
        match self.view {
            View::Library => &mut self.library_state,
            View::Selection => &mut self.selection_state,
            View::Playlists => &mut self.playlist_state,
        }
    }

    fn select(&mut self, i: usize) {
        let len = self.len();
        if len == 0 {
            self.state_mut().select(None);
        } else {
            self.state_mut().select(Some(i.min(len - 1)));
        }
    }

    fn move_selection(&mut self, delta: i64) {
        let len = self.len();
        if len == 0 {
            return;
        }
        let cur = self.state_mut().selected().unwrap_or(0) as i64;
        let next = (cur + delta).clamp(0, len as i64 - 1) as usize;
        self.state_mut().select(Some(next));
    }

    /// Enter: play the list in view from the selected track, or play a playlist.
    fn activate(&mut self) {
        match self.view {
            View::Library => {
                let Some(i) = self.library_state.selected() else {
                    return;
                };
                let tracks = self.visible().to_vec();
                if tracks.is_empty() {
                    return;
                }
                self.play(tracks, i);
            }
            View::Selection => {
                if let Some(i) = self.selection_state.selected() {
                    self.play(self.selection.clone(), i);
                }
            }
            View::Playlists => {
                let Some(i) = self.playlist_state.selected() else {
                    return;
                };
                let Some(pl) = self.playlists.get(i) else {
                    return;
                };
                let tracks = query::playlist_tracks(&self.conn, pl.id).unwrap_or_default();
                if tracks.is_empty() {
                    self.notify("playlist is empty");
                    return;
                }
                let name = pl.name.clone();
                self.play(tracks, 0);
                self.notify(format!("playing \"{name}\""));
            }
        }
    }

    /// Plays `tracks` from `index`. The selection is not touched.
    fn play(&mut self, tracks: Vec<Track>, index: usize) {
        let paths = tracks.iter().map(|t| PathBuf::from(&t.path)).collect();
        self.player.send(Cmd::Play(paths, index));
        self.playing = tracks;
        self.playing_source = self.player.queue();
    }

    /// `a`: in the library, selects the track or unselects it if it was
    /// selected; on a playlist, adds its tracks. Either way the cursor moves on.
    fn append_selection(&mut self) {
        if self.view == View::Library {
            return self.toggle_selected_track();
        }
        let added: Vec<Track> = match self.view {
            View::Playlists => self
                .playlist_state
                .selected()
                .and_then(|i| self.playlists.get(i))
                .map(|pl| query::playlist_tracks(&self.conn, pl.id).unwrap_or_default())
                .unwrap_or_default(),
            View::Library | View::Selection => return,
        };
        if added.is_empty() {
            return;
        }
        // Skip what is already selected. Repeats within `added` stay, so a
        // playlist that repeats a track on purpose keeps doing so.
        let selected: HashSet<&str> = self.selection.iter().map(|t| t.path.as_str()).collect();
        let new: Vec<Track> = added
            .into_iter()
            .filter(|t| !selected.contains(t.path.as_str()))
            .collect();
        // On to the next row either way, so a run of tracks takes one key each.
        self.move_selection(1);
        if new.is_empty() {
            self.notify("already in selection");
            return;
        }
        self.selection.extend(new);
        if self.selection_state.selected().is_none() {
            self.selection_state.select(Some(0));
        }
        // The tab already shows the total.
        self.notify("added to selection");
    }

    fn toggle_selected_track(&mut self) {
        let Some(track) = self
            .library_state
            .selected()
            .and_then(|i| self.visible().get(i).cloned())
        else {
            return;
        };
        if self.selection.iter().any(|t| t.path == track.path) {
            // Every copy, so the track's marker goes with it.
            self.selection.retain(|t| t.path != track.path);
            let len = self.selection.len();
            let cursor = self
                .selection_state
                .selected()
                .map(|i| i.min(len.saturating_sub(1)));
            self.selection_state
                .select(if len == 0 { None } else { cursor });
            self.notify("removed from selection");
        } else {
            self.selection.push(track);
            if self.selection_state.selected().is_none() {
                self.selection_state.select(Some(0));
            }
            self.notify("added to selection");
        }
        // On to the next row, so a run of tracks takes one key each.
        self.move_selection(1);
    }

    fn remove_from_selection(&mut self) {
        let Some(i) = self
            .selection_state
            .selected()
            .filter(|i| *i < self.selection.len())
        else {
            return;
        };
        let removed = self.selection.remove(i);
        self.select(i);
        self.notify(format!("removed \"{}\"", removed.display_title()));
    }

    /// Moves the selected track in the selection `delta` places, keeping it selected.
    fn move_in_selection(&mut self, delta: i64) {
        let Some(i) = self
            .selection_state
            .selected()
            .filter(|i| *i < self.selection.len())
        else {
            return;
        };
        let j = i as i64 + delta;
        if j < 0 || j >= self.selection.len() as i64 {
            return;
        }
        self.selection.swap(i, j as usize);
        self.selection_state.select(Some(j as usize));
    }

    fn delete_playlist(&mut self) {
        if self.view != View::Playlists {
            return;
        }
        let Some(i) = self.playlist_state.selected() else {
            return;
        };
        let Some(pl) = self.playlists.get(i).cloned() else {
            return;
        };
        self.input = Input::Confirm(Confirm::DeletePlaylist(pl));
    }

    /// Loads the marks for `path` if they are not the ones held.
    fn follow_marks(&mut self, path: Option<&PathBuf>) {
        if self.marks_for.as_ref() == path {
            return;
        }
        self.marks = path
            .and_then(|p| query::marks(&self.conn, &p.to_string_lossy()).ok())
            .unwrap_or_default();
        self.marks_for = path.cloned();
    }

    /// The playing track's path and source rate, read fresh rather than from
    /// the snapshot, or a message saying nothing is playing.
    fn playing_track(&mut self) -> Option<(PathBuf, u32)> {
        let status = self.player.status();
        let track = match (status.state, status.current(), status.source) {
            (State::Playing | State::Paused, Some(path), Some(source)) => {
                Some((path.clone(), source.rate))
            }
            _ => None,
        };
        if track.is_none() {
            self.notify("nothing is playing");
        }
        track
    }

    /// Marks `at`, or the playing position, unless a mark is already within [`MARK_NEAR`].
    fn add_mark(&mut self, at: Option<Duration>) {
        let Some((path, rate)) = self.playing_track() else {
            return;
        };
        self.follow_marks(Some(&path));
        let at = at.unwrap_or_else(|| self.player.position());
        if let Some(near) = self
            .marks
            .iter()
            .find(|m| m.time().abs_diff(at) < MARK_NEAR)
        {
            return self.notify(format!("already marked at {}", fmt_time(near.time())));
        }
        let mark = Mark::at_time(at, rate);
        if let Err(e) = query::add_mark(&self.conn, &path.to_string_lossy(), mark) {
            return self.notify(format!("could not mark: {e}"));
        }
        self.marks.push(mark);
        self.marks.sort_by_key(|m| m.frame);
        // As with playlists: in memory, the mark is gone when playr exits.
        let kept = if self.conn.path().is_none_or(str::is_empty) {
            " (not kept: no library file)"
        } else {
            ""
        };
        self.notify(format!("marked {}{kept}", fmt_time(at)));
    }

    /// Removes the most recently added mark in the playing track: marks are a
    /// chain, and `B` takes off the last link.
    fn undo_mark(&mut self) {
        let Some((path, _)) = self.playing_track() else {
            return;
        };
        self.follow_marks(Some(&path));
        match query::remove_last_mark(&self.conn, &path.to_string_lossy()) {
            Ok(Some(mark)) => {
                self.marks.retain(|m| m.frame != mark.frame);
                self.notify(format!("removed mark at {}", fmt_time(mark.time())));
            }
            Ok(None) => self.notify("no marks in this track"),
            Err(e) => self.notify(format!("could not remove mark: {e}")),
        }
    }

    fn ask_to_clear_marks(&mut self) {
        let Some((path, _)) = self.playing_track() else {
            return;
        };
        self.follow_marks(Some(&path));
        if self.marks.is_empty() {
            return self.notify("no marks in this track");
        }
        self.input = Input::Confirm(Confirm::ClearMarks(self.marks.len()));
    }

    /// Seeks to the next mark, or back to the previous one.
    ///
    /// Back skips a mark less than [`MARK_BACK`] behind, as `p` restarts a
    /// track rather than leaving it, so pressing it twice steps back twice.
    fn jump_to_mark(&mut self, forward: bool) {
        let Some((path, _)) = self.playing_track() else {
            return;
        };
        self.follow_marks(Some(&path));
        let at = self.player.position();
        let mut times = self.marks.iter().map(Mark::time);
        let target = if forward {
            times.find(|t| *t > at + MARK_NEAR / 2)
        } else {
            times.rev().find(|t| *t + MARK_BACK < at)
        };
        match target {
            Some(t) => {
                self.player.send(Cmd::Seek(t));
                self.notify(format!("mark at {}", fmt_time(t)));
            }
            None if forward => self.notify("no later mark"),
            None => self.notify("no earlier mark"),
        }
    }

    /// Moves to the next playback mode, or the previous one.
    fn cycle_mode(&mut self, forward: bool) {
        // Not the snapshot: it is a frame old, so quick presses would repeat a step.
        let current = self.player.mode();
        let mode = if forward {
            current.next()
        } else {
            current.prev()
        };
        self.player.send(Cmd::SetMode(mode));
        self.notify(format!("mode: {}", mode.name()));
    }

    fn nudge_volume(&mut self, delta: f32) {
        // Not the snapshot: it is a frame old, so quick presses would repeat a step.
        let v = (self.player.volume() + delta).clamp(0.0, 1.0);
        self.player.send(Cmd::SetVolume(v));
    }
}

/// Marks closer than this to one another are the same mark.
const MARK_NEAR: Duration = Duration::from_millis(500);
/// How far past a mark playback must be before `,` returns to it rather than
/// the one before.
const MARK_BACK: Duration = Duration::from_secs(1);

/// The character `key` types, or `None` for any other key and for a Ctrl or
/// Alt chord, which is a command rather than text.
fn typed(key: &KeyEvent) -> Option<char> {
    match key.code {
        KeyCode::Char(c)
            if !key
                .modifiers
                .intersects(KeyModifiers::CONTROL | KeyModifiers::ALT) =>
        {
            Some(c)
        }
        _ => None,
    }
}

/// How long the meter keeps showing a peak after it passes.
pub const PEAK_HOLD: Duration = Duration::from_millis(1500);

/// The peak to show, given the one `held` and a new `reading`, both as sample
/// magnitudes. A higher reading replaces the held peak at once; a lower one
/// only once the held peak is [`PEAK_HOLD`] old.
pub fn hold_peak(
    held: Option<(f32, Instant)>,
    reading: f32,
    now: Instant,
) -> Option<(f32, Instant)> {
    match held {
        Some((level, at)) if level >= reading && now.duration_since(at) < PEAK_HOLD => held,
        _ => (reading > 0.0).then_some((reading, now)),
    }
}

/// `m:ss`, or `h:mm:ss` past an hour.
pub fn fmt_time(d: Duration) -> String {
    let total = d.as_secs();
    let (h, m, s) = (total / 3600, (total % 3600) / 60, total % 60);
    if h > 0 {
        format!("{h}:{m:02}:{s:02}")
    } else {
        format!("{m}:{s:02}")
    }
}

/// Short label for the playback state.
pub fn state_glyph(s: State) -> &'static str {
    match s {
        State::Playing => ">",
        State::Paused => "||",
        State::Stopped => "#",
    }
}