playr-app 0.14.0

What playr's Rust frontends share: actions, : commands, key bindings, settings and dispatch
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
//! Actions dispatched through a frontend that is not a terminal: plain fields
//! for cursors and a log of what it was asked to show. What passes here holds
//! for any frontend that implements `Frontend` the same way.

#[path = "../../playr-core/tests/common/mod.rs"]
mod common;

use std::path::PathBuf;

use playr_app::action::{Action, Key, Keymap};
use playr_app::command;
use playr_app::dispatch::{confirmed, dispatch, Confirm, Frontend, Presentation, Prompt};
use playr_app::message::Message;
use playr_app::View::{self, Library, Playlists, Sampler, Selection};
use playr_core::db::query::{self, Playlist};
use playr_core::db::{self, Track};
use playr_core::event::{self, JobId};
use playr_core::notice::{Notice, Outcome, Refusal};
use playr_core::samples::Plan;
use playr_core::session::Session;

/// A frontend with no drawing: state in fields, output in logs.
struct Headless {
    session: Session,
    keys: Keymap,
    view: View,
    cursors: [Option<usize>; 4],
    results: Option<Vec<Track>>,
    messages: Vec<Message>,
    asked: Option<Confirm>,
    prompts: Vec<Prompt>,
    shown: Vec<Presentation>,
    plan: Option<Plan>,
    planning: bool,
    sampler: playr_app::sampler::Sampler,
}

fn slot(view: View) -> Option<usize> {
    match view {
        Library => Some(0),
        Selection => Some(1),
        Playlists => Some(2),
        View::Queue => Some(3),
        Sampler => None,
    }
}

impl Frontend for Headless {
    fn session(&self) -> &Session {
        &self.session
    }

    fn session_mut(&mut self) -> &mut Session {
        &mut self.session
    }
    fn keys(&mut self) -> &mut Keymap {
        &mut self.keys
    }
    fn view(&self) -> View {
        self.view
    }
    fn set_view(&mut self, view: View) {
        self.view = view;
    }
    fn cursor(&self, view: View) -> Option<usize> {
        slot(view).and_then(|i| self.cursors[i])
    }
    fn set_cursor(&mut self, view: View, row: Option<usize>) {
        if let Some(i) = slot(view) {
            self.cursors[i] = row;
        }
    }
    fn listed(&self) -> &[Track] {
        self.results.as_deref().unwrap_or(self.session.tracks())
    }
    fn set_results(&mut self, results: Option<Vec<Track>>) -> Option<Vec<Track>> {
        std::mem::replace(&mut self.results, results)
    }
    fn searching(&self) -> bool {
        self.results.is_some()
    }
    fn onset_sensitivity(&self) -> f32 {
        0.5
    }
    fn notify(&mut self, message: Message) {
        self.messages.push(message);
    }
    fn confirm(&mut self, question: Confirm) {
        self.asked = Some(question);
    }
    fn prompt(&mut self, prompt: Prompt) {
        self.prompts.push(prompt);
    }
    fn present(&mut self, presentation: Presentation) {
        self.shown.push(presentation);
    }
    fn sampler(&self) -> &playr_app::sampler::Sampler {
        &self.sampler
    }
    fn sampler_mut(&mut self) -> &mut playr_app::sampler::Sampler {
        &mut self.sampler
    }
    fn planning(&mut self, _job: JobId) {
        self.planning = true;
    }
    fn take_plan(&mut self) -> Option<Plan> {
        self.plan.take()
    }
    fn sql_started(&mut self, _: JobId, _: playr_app::dispatch::SqlThen) {}
}

/// A headless frontend over a library file of tracks a, b and c, and
/// playlists "early" (c) and "late" (a, b), with its directory.
fn headless() -> (Headless, tempfile::TempDir) {
    let dir = tempfile::tempdir().unwrap();
    let mut conn = db::open(&dir.path().join("library.db")).unwrap();
    let ids: Vec<i64> = ["/m/a.flac", "/m/b.flac", "/m/c.flac"]
        .iter()
        .map(|path| {
            let t = Track {
                path: path.to_string(),
                mtime: 1,
                size: 1,
                ..Default::default()
            };
            db::upsert(&conn, &t).unwrap()
        })
        .collect();
    query::save_playlist(&mut conn, "late", &ids[..2]).unwrap();
    query::save_playlist(&mut conn, "early", &ids[2..]).unwrap();
    let session = Session::new(conn, common::fake_player().0, event::ignore());
    let frontend = Headless {
        session,
        keys: Keymap::default(),
        view: Library,
        cursors: [Some(0), None, Some(0), None],
        results: None,
        messages: Vec::new(),
        asked: None,
        prompts: Vec::new(),
        shown: Vec::new(),
        plan: None,
        planning: false,
        sampler: Default::default(),
    };
    (frontend, dir)
}

fn last(f: &Headless) -> Option<&Message> {
    f.messages.last()
}

fn selection(f: &Headless) -> Vec<String> {
    f.session
        .selection()
        .iter()
        .map(|t| t.path.clone())
        .collect()
}

fn queue(f: &Headless) -> Vec<PathBuf> {
    f.session.player().queue().to_vec()
}

#[test]
fn adding_moves_the_cursor_and_playing_starts_from_it() {
    let (mut f, _dir) = headless();
    dispatch(Action::Add, &mut f);
    dispatch(Action::Add, &mut f);
    assert_eq!(selection(&f), ["/m/a.flac", "/m/b.flac"]);
    assert_eq!(f.cursor(Library), Some(2));
    assert_eq!(
        f.cursor(Selection),
        Some(0),
        "the selection cursor was not placed"
    );
    assert_eq!(last(&f), Some(&Outcome::AddedToSelection.into()));

    // On c, the last row, the cursor stays: the first add selects c and the
    // second unselects it.
    dispatch(Action::Add, &mut f);
    dispatch(Action::Add, &mut f);
    assert_eq!(selection(&f), ["/m/a.flac", "/m/b.flac"]);
    assert_eq!(last(&f), Some(&Outcome::RemovedFromSelection.into()));

    dispatch(Action::CursorFirst, &mut f);
    dispatch(Action::Cursor(1), &mut f);
    dispatch(Action::Activate, &mut f);
    assert_eq!(queue(&f).len(), 3);
    assert_eq!(f.session.player().status().queue.len(), 3);

    // In the selection, the cursor names the track to move and remove.
    dispatch(Action::ShowView(Selection), &mut f);
    dispatch(Action::MoveTrack(1), &mut f);
    assert_eq!(selection(&f), ["/m/b.flac", "/m/a.flac"]);
    assert_eq!(f.cursor(Selection), Some(1));
    dispatch(Action::Remove, &mut f);
    assert_eq!(selection(&f), ["/m/b.flac"]);
    assert_eq!(f.cursor(Selection), Some(0));
}

#[test]
fn enqueueing_adds_the_row_under_the_cursor_and_moves_on() {
    let (mut f, _dir) = headless();
    // Nothing playing: the track queued is the whole queue.
    f.set_cursor(Library, Some(1));
    dispatch(Action::Enqueue(true), &mut f);
    assert_eq!(queued(&f), [PathBuf::from("/m/b.flac")]);
    assert_eq!(
        last(&f),
        Some(
            &Outcome::Queued {
                tracks: 1,
                next: true
            }
            .into()
        )
    );
    assert_eq!(f.cursor(Library), Some(2), "the cursor did not move on");

    // On a playlist, its tracks; the playlists are listed by name.
    dispatch(Action::ShowView(Playlists), &mut f);
    f.set_cursor(Playlists, Some(1));
    dispatch(Action::Enqueue(false), &mut f);
    assert_eq!(
        last(&f),
        Some(
            &Outcome::Queued {
                tracks: 2,
                next: false
            }
            .into()
        )
    );

    // The sampler and the queue list no rows to queue.
    let before = f.messages.len();
    for view in [Sampler, View::Queue] {
        dispatch(Action::ShowView(view), &mut f);
        dispatch(Action::Enqueue(false), &mut f);
    }
    assert_eq!(f.messages.len(), before);

    // `:enqueue all` takes search results or the selection, not the library.
    dispatch(Action::ShowView(Library), &mut f);
    dispatch(Action::EnqueueAll, &mut f);
    assert_eq!(last(&f), Some(&Message::NothingToQueue));
}

/// The tracks the player holds as queued, in order.
fn queued(f: &Headless) -> Vec<PathBuf> {
    let status = f.session.player().status();
    status
        .queue
        .iter()
        .zip(status.queued.iter())
        .filter(|(_, q)| **q)
        .map(|(p, _)| p.clone())
        .collect()
}

#[test]
fn the_queue_view_takes_tracks_out_and_keeps_the_one_playing_first() {
    // Real files, so the queue holds still while it plays.
    let dir = tempfile::tempdir().unwrap();
    let conn = db::open(&dir.path().join("library.db")).unwrap();
    for name in ["a", "b", "c"] {
        let path = dir.path().join(format!("{name}.wav"));
        common::silence(&path, 8000, 5.0);
        let t = Track {
            path: path.to_string_lossy().into_owned(),
            mtime: 1,
            size: 1,
            ..Default::default()
        };
        db::upsert(&conn, &t).unwrap();
    }
    let (mut f, _other) = headless();
    f.session = Session::new(conn, common::fake_player().0, event::ignore());
    let name = |f: &Headless, row: usize| {
        let rows = f.session.queue_rows();
        let path = f.session.player().queue()[rows[row]].clone();
        path.file_stem().unwrap().to_string_lossy().into_owned()
    };
    let wait = |f: &Headless, done: &dyn Fn(&Headless) -> bool| {
        let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
        while !done(f) {
            assert!(std::time::Instant::now() < deadline);
            std::thread::sleep(std::time::Duration::from_millis(10));
        }
    };

    f.set_cursor(Library, Some(0));
    dispatch(Action::Activate, &mut f);
    wait(&f, &|f| {
        f.session.player().status().state == playr_core::audio::State::Playing
    });
    assert!(
        f.session.queue_rows().is_empty(),
        "the library filled the queue"
    );
    // b interrupts the library; c waits behind it.
    f.set_cursor(Library, Some(1));
    dispatch(Action::Enqueue(false), &mut f);
    wait(&f, &|f| {
        let status = f.session.player().status();
        f.session.queue_rows().first() == Some(&status.index) && name(f, 0) == "b"
    });
    dispatch(Action::Enqueue(false), &mut f);
    assert_eq!((name(&f, 0), name(&f, 1)), ("b".into(), "c".into()));

    dispatch(Action::ShowView(View::Queue), &mut f);
    f.set_cursor(View::Queue, Some(1));
    dispatch(Action::MoveTrack(-1), &mut f);
    assert_eq!(
        name(&f, 0),
        "b",
        "a waiting track moved above the one playing"
    );
    dispatch(Action::Remove, &mut f);
    assert_eq!(f.session.queue_rows().len(), 1);
    assert!(matches!(
        last(&f),
        Some(Message::Core(Notice::Done(Outcome::RemovedTrack { .. })))
    ));
    // Only b, playing, is left; clearing takes it out of the queue, and it
    // plays on.
    dispatch(Action::ClearQueue, &mut f);
    assert_eq!(f.asked, Some(Confirm::ClearQueue(1)));
    confirmed(Confirm::ClearQueue(1), &mut f);
    assert!(f.session.queue_rows().is_empty());
    let status = f.session.player().status();
    assert_eq!(status.current().unwrap().file_stem().unwrap(), "b");
    dispatch(Action::ClearQueue, &mut f);
    assert_eq!(last(&f), Some(&Message::QueueEmpty));
}

#[test]
fn enter_in_the_queue_jumps_without_replacing_it() {
    let (mut f, _dir) = headless();
    dispatch(Action::Activate, &mut f);
    let playing = f.session.player().queue();
    dispatch(Action::ShowView(View::Queue), &mut f);
    f.set_cursor(View::Queue, Some(2));
    dispatch(Action::Activate, &mut f);
    assert!(
        std::sync::Arc::ptr_eq(&playing, &f.session.player().queue()),
        "the queue was replaced"
    );
}

#[test]
fn searching_lists_results_and_clearing_lists_the_library() {
    let (mut f, _dir) = headless();
    dispatch(Action::ShowView(Playlists), &mut f);
    dispatch(Action::Search("b".into()), &mut f);
    assert_eq!(f.view, Library);
    assert_eq!(f.listed().len(), 1);
    assert_eq!(f.cursor(Library), Some(0));
    dispatch(Action::Search("zzz".into()), &mut f);
    assert_eq!(last(&f), Some(&Message::NoMatches));
    assert_eq!(f.cursor(Library), None);
    dispatch(Action::ClearSearch, &mut f);
    assert_eq!(f.listed().len(), 3);
    assert_eq!(f.cursor(Library), Some(0));
}

#[test]
fn playlists_are_renamed_deleted_and_replaced_through_confirmation() {
    let (mut f, _dir) = headless();
    let names = |f: &Headless| -> Vec<String> {
        f.session
            .playlists()
            .iter()
            .map(|p| p.name.clone())
            .collect()
    };
    dispatch(Action::RenameTo("x".into()), &mut f);
    assert_eq!(last(&f), Some(&Message::NoPlaylistUnderCursor));

    dispatch(Action::ShowView(Playlists), &mut f);
    dispatch(Action::StartRename, &mut f);
    let early: Playlist = f.session.playlists()[0].clone();
    assert_eq!(f.prompts.last(), Some(&Prompt::Rename(early)));
    // "early" sorts first; renamed "zzz", it sorts last and the cursor follows.
    dispatch(Action::RenameTo("zzz".into()), &mut f);
    assert_eq!(names(&f), ["late", "zzz"]);
    assert_eq!(f.cursor(Playlists), Some(1));

    dispatch(Action::DeletePlaylist, &mut f);
    let question = f.asked.take().unwrap();
    assert!(matches!(&question, Confirm::DeletePlaylist(p) if p.name == "zzz"));
    assert_eq!(names(&f), ["late", "zzz"], "deleted before a yes");
    confirmed(question, &mut f);
    assert_eq!(names(&f), ["late"]);
    assert_eq!(f.cursor(Playlists), Some(0));

    // Saving over "late" asks first.
    dispatch(Action::SaveAs("late".into()), &mut f);
    assert_eq!(last(&f), Some(&Refusal::SelectionEmpty.into()));
    dispatch(Action::Add, &mut f);
    dispatch(Action::SaveAs("late".into()), &mut f);
    assert_eq!(
        f.asked,
        Some(Confirm::ReplacePlaylist {
            name: "late".into(),
            queue: false
        })
    );
    confirmed(f.asked.take().unwrap(), &mut f);
    assert!(matches!(
        last(&f),
        Some(Message::Core(Notice::Done(Outcome::Saved {
            tracks: 2,
            ..
        })))
    ));
}

#[test]
fn commands_parse_and_dispatch_in_the_frontend_s_view() {
    let (mut f, _dir) = headless();
    let run = |f: &mut Headless, line: &str| {
        let action = command::parse(line, f.view).unwrap();
        dispatch(action, f);
    };
    run(&mut f, "view sampler");
    run(&mut f, "zoom +");
    run(&mut f, "display braille");
    run(&mut f, "theme light");
    run(&mut f, "keys");
    assert_eq!(
        f.shown,
        [
            Presentation::Zoom(playr_app::action::Zoom::In),
            Presentation::Display(Some(playr_app::Display::Braille)),
            Presentation::Theme(playr_app::Theme::Light),
            Presentation::KeyList
        ]
    );
    // No rows in the sampler: cursor commands change nothing.
    run(&mut f, "down");
    assert_eq!(f.cursors, [Some(0), None, Some(0), None]);
    run(&mut f, "slice 4");
    assert_eq!(last(&f), Some(&Refusal::NothingPlaying.into()));
    assert!(!f.planning);
    run(&mut f, "write");
    assert_eq!(last(&f), Some(&Message::NoSlicesPlanned));

    run(&mut f, "map sampler ctrl-q quit");
    let ctrl_q = Key::parse("ctrl-q").unwrap();
    assert_eq!(f.keys.lookup(ctrl_q, Sampler), Some(&Action::Quit));
    run(&mut f, "unmap ctrl-q");
    assert_eq!(
        last(&f),
        Some(&Message::NotBound {
            key: ctrl_q,
            view: None
        })
    );
    run(&mut f, "next-view");
    assert_eq!(f.view, Library);
    run(&mut f, "search");
    // `command` names the prompt only as a key binding's target.
    dispatch(Action::StartCommand, &mut f);
    assert_eq!(
        f.prompts,
        [
            Prompt::Search(String::new()),
            Prompt::Command(String::new())
        ]
    );
}

/// Plays `track` alone, waits until it plays, and marks it at `secs`.
fn play_and_mark(f: &mut Headless, track: &Track, secs: &[u64]) {
    f.session.play(std::slice::from_ref(track), 0);
    let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
    while f.session.playing_track().map(|(p, _)| p) != Ok(PathBuf::from(&track.path)) {
        assert!(
            std::time::Instant::now() < deadline,
            "never started playing"
        );
        std::thread::sleep(std::time::Duration::from_millis(10));
    }
    for s in secs {
        f.session.add_mark(Some(std::time::Duration::from_secs(*s)));
    }
}

#[test]
fn clearing_marks_clears_the_track_asked_about_after_the_track_changes() {
    let (mut f, dir) = headless();
    let wav = |name: &str| {
        let path = dir.path().join(name);
        common::silence(&path, 8000, 20.0);
        Track {
            path: path.to_string_lossy().into_owned(),
            mtime: 1,
            size: 1,
            ..Default::default()
        }
    };
    let (a, b) = (wav("a.wav"), wav("b.wav"));
    let marks =
        |f: &mut Headless, t: &Track| f.session.marks_for(Some(&PathBuf::from(&t.path))).len();

    play_and_mark(&mut f, &a, &[5, 10]);
    dispatch(Action::ClearMarks, &mut f);
    let question = f.asked.take().unwrap();
    assert!(matches!(&question, Confirm::ClearMarks { count: 2, .. }));
    // The track changes while the question is open, and the frontend reads
    // the new track's marks, as `Model::refresh` does each frame.
    play_and_mark(&mut f, &b, &[5, 10, 15]);
    confirmed(question, &mut f);

    assert_eq!(marks(&mut f, &a), 0, "the track asked about kept its marks");
    assert_eq!(
        marks(&mut f, &b),
        3,
        "a track not asked about lost its marks"
    );
}

#[test]
fn pruning_asks_first_and_starts_on_a_yes() {
    let (mut f, dir) = headless();
    let nowhere = dir.path().join("nowhere");
    dispatch(Action::Prune(Some(nowhere.clone())), &mut f);
    assert_eq!(last(&f), Some(&Refusal::NotADirectory(nowhere).into()));
    assert_eq!(f.asked, None, "asked about a directory that is not there");

    let music = dir.path().to_path_buf();
    dispatch(Action::Prune(Some(music.clone())), &mut f);
    let question = f.asked.take().unwrap();
    assert_eq!(question, Confirm::Prune(Some(music.clone())));
    assert_ne!(
        last(&f),
        Some(
            &Outcome::PruneStarted {
                dir: Some(music.clone())
            }
            .into()
        ),
        "pruned before a yes"
    );
    confirmed(question, &mut f);
    assert_eq!(
        last(&f),
        Some(&Outcome::PruneStarted { dir: Some(music) }.into())
    );
}

#[test]
fn the_new_questions_say_what_they_will_do() {
    assert_eq!(
        Confirm::ForgetRoot("/mnt/music".into()).question(),
        "forget /mnt/music, and every track and mark under it?"
    );
    assert_eq!(
        Confirm::Resume {
            path: "/mnt/music/amen.flac".into(),
            at: std::time::Duration::from_secs(95),
            queue: Default::default(),
        }
        .question(),
        "take up amen.flac again at 1:35?"
    );
    let queue = playr_core::db::SavedQueue {
        played: vec!["/mnt/music/a.flac".into()],
        playing: true,
        waiting: vec!["/mnt/music/b.flac".into()],
    };
    assert_eq!(
        Confirm::Resume {
            path: "/mnt/music/amen.flac".into(),
            at: std::time::Duration::from_secs(95),
            queue,
        }
        .question(),
        "take up amen.flac again at 1:35, with its queue of 3 tracks?"
    );
}