playr 0.2.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
//! Terminal interface.
//!
//! One thread: it renders, reads keys, and talks to the player over a channel.
//! Nothing here blocks on audio.

pub mod render;

use std::path::PathBuf;
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, Playlist};
use crate::db::Track;

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

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

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

/// What typed input is currently being collected.
pub enum Input {
    None,
    Search(String),
    SavePlaylist(String),
    /// Waiting for `y` before an action that cannot be undone.
    Confirm(Confirm),
}

/// A destructive action held until the listener confirms it.
pub enum Confirm {
    DeletePlaylist(Playlist),
    /// Overwrite the playlist of this name with the queue.
    ReplacePlaylist(String),
}

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 queue? (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,

    queue: Vec<Track>,
    queue_state: ListState,

    playlists: Vec<Playlist>,
    playlist_state: ListState,

    input: Input,
    message: Option<(String, Instant)>,
    quit: bool,

    /// Last error sequence shown, so each new one is surfaced exactly once.
    seen_error: u64,
    /// Playing index the queue cursor was last moved to.
    followed: Option<usize>,

    /// 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]>,
    pub queue: &'a [Track],
    pub playlists: &'a [Playlist],
    pub input: &'a Input,
    pub message: Option<&'a str>,
    pub library_state: &'a mut ListState,
    pub queue_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,
}

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

    /// Builds the app with an initial queue, as handed over by the CLI.
    pub fn with_queue(conn: Connection, player: Player, queue: Vec<Track>) -> Self {
        let mut app = App {
            conn,
            player,
            view: View::Library,
            all: Vec::new(),
            results: None,
            library_state: ListState::default(),
            queue,
            queue_state: ListState::default(),
            playlists: Vec::new(),
            playlist_state: ListState::default(),
            input: Input::None,
            message: None,
            quit: false,
            seen_error: 0,
            followed: None,
            snapshot: Snapshot::default(),
        };
        if !app.queue.is_empty() {
            app.queue_state.select(Some(0));
            app.view = View::Queue;
        }
        app.reload();
        app
    }

    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(),
            queue: &self.queue,
            playlists: &self.playlists,
            input: &self.input,
            message: self.message.as_ref().map(|(m, _)| m.as_str()),
            library_state: &mut self.library_state,
            queue_state: &mut self.queue_state,
            playlist_state: &mut self.playlist_state,
        }
    }

    pub fn run(mut self, terminal: &mut ratatui::DefaultTerminal) -> std::io::Result<()> {
        while !self.quit {
            self.snapshot = Snapshot {
                status: self.player.status(),
                position: self.player.position(),
                volume: self.player.volume(),
            };
            // Show a skipped or unplayable track once, then let it expire.
            if self.snapshot.status.error_seq > self.seen_error {
                self.seen_error = self.snapshot.status.error_seq;
                if let Some(e) = self.snapshot.status.error.clone() {
                    self.notify(e);
                }
            }
            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);
                    }
                }
            }
            self.sync_queue();
            if let Some((_, at)) = &self.message {
                if at.elapsed() > Duration::from_secs(4) {
                    self.message = None;
                }
            }
        }
        Ok(())
    }

    /// Keeps the displayed queue aligned with the engine's.
    fn sync_queue(&mut self) {
        let status = &self.snapshot.status;
        if status.queue.len() != self.queue.len() || self.queue.is_empty() {
            return;
        }
        let playing = match status.state {
            State::Playing | State::Paused => Some(status.index),
            State::Stopped => None,
        };

        if let Some(target) = follow_target(self.followed, playing, self.queue_state.selected()) {
            self.followed = Some(target);
            self.queue_state.select(Some(target));
        }
    }

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

    /// Handles one key press.
    pub fn on_key(&mut self, key: KeyEvent) {
        // 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 key.code == KeyCode::Char('y') {
                    self.confirm(action);
                } else {
                    self.notify("cancelled");
                }
                return;
            }
            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::None => {}
        }

        if key.modifiers.contains(KeyModifiers::CONTROL) && key.code == KeyCode::Char('c') {
            self.quit = true;
            return;
        }

        match key.code {
            KeyCode::Char('q') => self.quit = true,
            KeyCode::Tab => self.view = self.view.next(),
            KeyCode::Char('1') => self.view = View::Library,
            KeyCode::Char('2') => self.view = View::Queue,
            KeyCode::Char('3') => self.view = View::Playlists,

            KeyCode::Char('j') | KeyCode::Down => self.move_selection(1),
            KeyCode::Char('k') | KeyCode::Up => self.move_selection(-1),
            KeyCode::PageDown => self.move_selection(10),
            KeyCode::PageUp => self.move_selection(-10),
            KeyCode::Char('g') | KeyCode::Home => self.select(0),
            KeyCode::Char('G') | KeyCode::End => self.select(self.len().saturating_sub(1)),

            KeyCode::Char(' ') => self.player.send(Cmd::TogglePause),
            KeyCode::Char('n') => self.player.send(Cmd::Next),
            KeyCode::Char('p') => self.player.send(Cmd::Prev),
            KeyCode::Char('x') => self.player.send(Cmd::Stop),
            KeyCode::Char('+') | KeyCode::Char('=') => self.nudge_volume(0.05),
            KeyCode::Char('-') | KeyCode::Char('_') => self.nudge_volume(-0.05),
            KeyCode::Right => self.player.send(Cmd::SeekBy(5)),
            KeyCode::Left => self.player.send(Cmd::SeekBy(-5)),
            // Varispeed: one semitone per press, pitch moving with tempo.
            KeyCode::Char(']') => self.player.send(Cmd::SpeedBy(1)),
            KeyCode::Char('[') => self.player.send(Cmd::SpeedBy(-1)),
            KeyCode::Char('\\') => self.player.send(Cmd::SpeedReset),

            KeyCode::Char('/') => self.input = Input::Search(String::new()),
            KeyCode::Esc => {
                if self.results.take().is_some() {
                    self.library_state.select(Some(0));
                }
            }
            KeyCode::Enter => self.activate(),
            KeyCode::Char('a') => self.append_selection(),
            KeyCode::Char('s') => {
                if self.queue.is_empty() {
                    self.notify("queue is empty");
                } 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");
                } else {
                    self.input = Input::SavePlaylist(String::new());
                }
            }
            KeyCode::Char('d') => self.delete_playlist(),
            _ => {}
        }
    }

    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) => {
                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;
                let name = buf.trim().to_string();
                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));
                } else {
                    self.save_queue(&name);
                }
            }
            KeyCode::Backspace => {
                buf.pop();
                self.input = Input::SavePlaylist(buf);
            }
            KeyCode::Char(c) => {
                buf.push(c);
                self.input = Input::SavePlaylist(buf);
            }
            _ => self.input = Input::SavePlaylist(buf),
        }
    }

    fn save_queue(&mut self, name: &str) {
        let ids: Vec<i64> = self
            .queue
            .iter()
            .map(|t| t.id)
            .filter(|id| *id != 0)
            .collect();
        match query::save_playlist(&mut self.conn, name, &ids) {
            Ok(_) => {
                self.notify(format!("saved \"{name}\" ({} tracks)", 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_queue(&name),
            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::Queue => self.queue.len(),
            View::Playlists => self.playlists.len(),
        }
    }

    fn state_mut(&mut self) -> &mut ListState {
        match self.view {
            View::Library => &mut self.library_state,
            View::Queue => &mut self.queue_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 from here in the library, jump within the queue, or load 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::Queue => {
                if let Some(i) = self.queue_state.selected() {
                    let paths = self.queue_paths();
                    self.player.send(Cmd::Play(paths, 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}\""));
            }
        }
    }

    fn play(&mut self, tracks: Vec<Track>, index: usize) {
        self.queue = tracks;
        self.queue_state.select(Some(index));
        let paths = self.queue_paths();
        self.player.send(Cmd::Play(paths, index));
    }

    fn queue_paths(&self) -> Vec<PathBuf> {
        self.queue.iter().map(|t| PathBuf::from(&t.path)).collect()
    }

    fn append_selection(&mut self) {
        let added: Vec<Track> = match self.view {
            View::Library => self
                .library_state
                .selected()
                .and_then(|i| self.visible().get(i).cloned())
                .into_iter()
                .collect(),
            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::Queue => return,
        };
        if added.is_empty() {
            return;
        }
        let paths: Vec<PathBuf> = added.iter().map(|t| PathBuf::from(&t.path)).collect();
        self.queue.extend(added);
        self.player.send(Cmd::Enqueue(paths.clone()));
        self.notify(format!("queued {} track(s)", paths.len()));
    }

    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));
    }

    fn nudge_volume(&mut self, delta: f32) {
        let v = (self.snapshot.volume + delta).clamp(0.0, 1.0);
        self.player.send(Cmd::SetVolume(v));
    }
}

/// Where the queue cursor belongs after a status update, or `None` to leave it.
///
/// The cursor follows playback so the playing track stays on screen in a long
/// queue: without it, a track change scrolls the current song out of view and
/// it has to be hunted for.
///
/// It moves only when the track actually changes, not on every frame, so
/// scrolling with `j`/`k` is not fought for as long as the track keeps playing.
pub fn follow_target(
    last_seen: Option<usize>,
    playing: Option<usize>,
    selected: Option<usize>,
) -> Option<usize> {
    match playing {
        // Nothing is playing: leave the cursor wherever the listener put it.
        None => None,
        // First status after a queue is loaded.
        Some(now) if selected.is_none() => Some(now),
        // The track changed, so follow it.
        Some(now) if last_seen != Some(now) => Some(now),
        _ => None,
    }
}

/// `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 => "#",
    }
}