playr-app 0.7.0

What playr's Rust frontends share: actions, : commands, key bindings, settings and dispatch
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
//! The shared model, driven with no drawing and no key events: what the
//! terminal does with a key, and a GUI with a control, arrives as these calls.

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

use std::path::Path;
use std::time::{Duration, Instant};

use playr_app::action::Action;
use playr_app::command::CommandLine;
use playr_app::config::Config;
use playr_app::dispatch::{Confirm, Frontend};
use playr_app::message::Message;
use playr_app::model::{hold_peak, Input, Model, PEAK_HOLD};
use playr_app::View;
use playr_core::audio::Mode;
use playr_core::db::{self, query, Track};
use playr_core::notice::{Notice, Outcome, Task};

fn track(path: &str) -> Track {
    Track {
        path: path.into(),
        mtime: 1,
        size: 1,
        ..Default::default()
    }
}

/// A model over a library file of tracks a, b and c and playlists "early"
/// and "late", with its directory.
fn model() -> (Model, 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(|p| db::upsert(&conn, &track(p)).unwrap())
        .collect();
    query::save_playlist(&mut conn, "late", &ids[..2]).unwrap();
    query::save_playlist(&mut conn, "early", &ids[2..]).unwrap();
    let player = common::fake_player().0;
    (Model::new(conn, player, Vec::new(), Config::default()), dir)
}

#[test]
fn tracks_handed_over_are_selected_played_and_shown() {
    let tracks = vec![track("/x/one.wav"), track("/x/two.wav")];
    let conn = db::open_memory().unwrap();
    let model = Model::new(
        conn,
        common::fake_player().0,
        tracks.clone(),
        Config::default(),
    );
    assert_eq!(model.view(), View::Selection);
    assert_eq!(model.session().selection(), &tracks[..]);
    assert_eq!(model.playing(), &tracks[..]);
    assert_eq!(model.cursors().selection, Some(0));
}

#[test]
fn a_question_waits_for_its_answer() {
    let (mut model, _dir) = model();
    model.perform(Action::ShowView(View::Playlists));
    model.perform(Action::DeletePlaylist);
    assert!(matches!(
        model.input(),
        Input::Confirm(Confirm::DeletePlaylist(p)) if p.name == "early"
    ));

    model.answer(false);
    assert_eq!(model.input(), &Input::None);
    assert_eq!(model.message(), Some(&Message::Cancelled));
    assert_eq!(model.session().playlists().len(), 2);

    model.perform(Action::DeletePlaylist);
    model.answer(true);
    assert_eq!(
        model.message(),
        Some(&Message::Core(Notice::Done(Outcome::Deleted {
            name: "early".into()
        })))
    );
    assert_eq!(model.session().playlists().len(), 1);

    // With no question open, an answer does nothing.
    model.answer(true);
    assert_eq!(model.session().playlists().len(), 1);
}

#[test]
fn the_theme_starts_from_the_settings_and_changes_by_command() {
    use playr_app::Theme;
    let config = Config::parse("theme = \"light\"").unwrap();
    let conn = db::open_memory().unwrap();
    let mut model = Model::new(conn, common::fake_player().0, Vec::new(), config);
    assert_eq!(model.theme(), Theme::Light);
    model.run_command("theme dark");
    assert_eq!(model.theme(), Theme::Dark);
    assert_eq!(model.message(), Some(&Message::Theme(Theme::Dark)));
}

#[test]
fn the_sampler_snaps_ranges_marks_and_nudges_and_slices_the_range() {
    use playr_app::action::{Nudge, Slicing};
    use playr_app::sampler::{frame_of, Scale, Wave};

    // Four seconds at 8 kHz changing sign every half second: crossings at
    // frames 4,000, 8,000 ... 28,000. A snap reaches 80 frames either side.
    let dir = tempfile::tempdir().unwrap();
    let file = dir.path().join("steps.wav");
    let parts: Vec<(f32, f32)> = (0..8)
        .map(|i| (0.5, if i % 2 == 0 { 0.25 } else { -0.25 }))
        .collect();
    common::levels(&file, 8000, &parts);
    let mut model = Model::new(
        db::open(&dir.path().join("library.db")).unwrap(),
        common::fake_player().0,
        vec![track(&file.to_string_lossy())],
        Config::default(),
    );
    model.perform(Action::ShowView(View::Sampler));
    let deadline = Instant::now() + Duration::from_secs(5);
    while !matches!(model.sampler().wave, Wave::Ready { .. }) {
        assert!(Instant::now() < deadline, "no waveform");
        model.refresh();
        std::thread::sleep(Duration::from_millis(10));
    }
    let ms = Duration::from_millis;
    let current = Some(file.clone());

    model.perform(Action::Nudge(Nudge::Columns(1)));
    assert_eq!(
        model.message(),
        Some(&Message::NoWaveform),
        "no columns drawn yet"
    );

    model.perform(Action::Snap(None));
    assert_eq!(model.message(), Some(&Message::Snap(true)));
    model.perform(Action::SetRange(Some((ms(1_005), ms(2_995)))));
    assert_eq!(
        model.sampler().range(current.as_ref()),
        Some((8_000, 24_000))
    );

    // 1.508 s snaps to 1.5 s; 1.6 s has no crossing near. They are 100 ms
    // apart, which only the sampler view allows.
    model.perform(Action::MarkAt(ms(1_508)));
    model.perform(Action::MarkAt(ms(1_600)));
    let marks: Vec<u64> = model
        .session_mut()
        .marks_for(current.as_ref())
        .iter()
        .map(|m| m.frame)
        .collect();
    assert_eq!(marks, [12_000, 12_800]);

    model.perform(Action::Slice(Slicing::Region));
    let deadline = Instant::now() + Duration::from_secs(5);
    while model.sampler().pending.is_none() {
        assert!(
            Instant::now() < deadline,
            "nothing planned: {:?}",
            model.message()
        );
        model.refresh();
        std::thread::sleep(Duration::from_millis(10));
    }
    let plan = model.sampler().pending.as_ref().unwrap();
    assert_eq!(plan.job.range, Some((8_000, 24_000)));
    assert_eq!(plan.spans, [(8_000, Some(24_000))]);

    // Paused, so the position is where each seek put it.
    model.perform(Action::TogglePause);
    model.set_scale(Scale {
        start: 0,
        per_column: 64,
        per_frame: 1,
        columns: 100,
    });
    let at = |model: &Model, frame: u64| {
        let deadline = Instant::now() + Duration::from_secs(5);
        while frame_of(model.session().player().position(), 8000) != frame {
            assert!(
                Instant::now() < deadline,
                "at {:?}, not frame {frame}",
                model.session().player().position()
            );
            std::thread::sleep(Duration::from_millis(10));
        }
    };
    model.perform(Action::SeekTo(ms(990)));
    at(&model, 8_000);
    model.perform(Action::Nudge(Nudge::Columns(1)));
    at(&model, 8_064);
    model.perform(Action::Nudge(Nudge::Columns(-1)));
    at(&model, 8_000);
    model.perform(Action::Nudge(Nudge::Percent(-10)));
    at(&model, 7_360);
}

#[test]
fn the_range_loops_follows_its_changes_and_escape_clears_it() {
    use playr_app::sampler::Wave;
    use playr_core::audio::State;

    let dir = tempfile::tempdir().unwrap();
    let file = dir.path().join("long.wav");
    common::silence(&file, 8000, 10.0);
    let mut model = Model::new(
        db::open(&dir.path().join("library.db")).unwrap(),
        common::fake_player().0,
        vec![track(&file.to_string_lossy())],
        Config::default(),
    );
    model.perform(Action::ShowView(View::Sampler));
    let deadline = Instant::now() + Duration::from_secs(5);
    while !matches!(model.sampler().wave, Wave::Ready { .. }) {
        assert!(Instant::now() < deadline, "no waveform");
        model.refresh();
        std::thread::sleep(Duration::from_millis(10));
    }
    let status = |model: &Model| model.session().player().status();
    let settle = |model: &Model, done: &dyn Fn(&playr_core::audio::Status) -> bool| {
        let deadline = Instant::now() + Duration::from_secs(5);
        while !done(&status(model)) {
            assert!(Instant::now() < deadline, "{:?}", status(model).looping);
            std::thread::sleep(Duration::from_millis(10));
        }
    };
    let ms = Duration::from_millis;

    model.perform(Action::Loop(None));
    assert_eq!(model.message(), Some(&Message::NoRangeToLoop));

    // A paused track plays once it loops.
    model.perform(Action::TogglePause);
    settle(&model, &|s| s.state == State::Paused);
    model.perform(Action::SetRange(Some((ms(2_000), ms(3_000)))));
    model.perform(Action::Loop(None));
    assert_eq!(model.message(), Some(&Message::Loop(true)));
    settle(&model, &|s| {
        s.looping == Some((16_000, 24_000)) && s.state == State::Playing
    });

    // A new end moves the loop with it.
    model.perform(Action::SetRange(Some((ms(2_000), ms(2_500)))));
    settle(&model, &|s| s.looping == Some((16_000, 20_000)));

    // So does moving an end, which stops a frame short of the other.
    use playr_app::action::Nudge;
    use playr_app::sampler::{Edge, Scale};
    model.set_scale(Scale {
        start: 0,
        per_column: 64,
        per_frame: 1,
        columns: 100,
    });
    model.perform(Action::PickEdge(Edge::End));
    model.perform(Action::MoveEdge(Nudge::Columns(-2)));
    let current = model.snapshot().status.current().cloned();
    assert_eq!(
        model.sampler().range(current.as_ref()),
        Some((16_000, 19_872))
    );
    settle(&model, &|s| s.looping == Some((16_000, 19_872)));
    model.perform(Action::PickEdge(Edge::Start));
    model.perform(Action::MoveEdge(Nudge::Percent(100)));
    assert_eq!(
        model.sampler().range(current.as_ref()),
        Some((19_871, 19_872))
    );
    settle(&model, &|s| s.looping == Some((19_871, 19_872)));
    model.perform(Action::SetRange(Some((ms(2_000), ms(2_500)))));

    // Escape, with no slices planned, clears the range, which ends the loop.
    model.perform(Action::DiscardSlices);
    assert_eq!(model.sampler().range, None);
    settle(&model, &|s| s.looping.is_none());
    model.perform(Action::DiscardSlices);
    assert_eq!(model.message(), Some(&Message::NoSlicesPlanned));
}

#[test]
fn a_close_view_reads_its_frames_and_again_once_it_leaves_them() {
    use playr_app::sampler::{DetailRead, Scale, Wave};

    let dir = tempfile::tempdir().unwrap();
    let file = dir.path().join("steps.wav");
    let parts: Vec<(f32, f32)> = (0..8)
        .map(|i| (0.5, if i % 2 == 0 { 0.25 } else { -0.25 }))
        .collect();
    common::levels(&file, 8000, &parts);
    let mut model = Model::new(
        db::open(&dir.path().join("library.db")).unwrap(),
        common::fake_player().0,
        vec![track(&file.to_string_lossy())],
        Config::default(),
    );
    model.perform(Action::ShowView(View::Sampler));
    let until = |model: &mut Model, done: &dyn Fn(&Model) -> bool| {
        let deadline = Instant::now() + Duration::from_secs(5);
        while !done(model) {
            assert!(Instant::now() < deadline, "{:?}", model.sampler().detail);
            model.refresh();
            std::thread::sleep(Duration::from_millis(10));
        }
    };
    until(&mut model, &|m| {
        matches!(m.sampler().wave, Wave::Ready { .. })
    });
    let current = Some(file.clone());

    // Columns of 64 frames draw from the peaks: nothing is read.
    let coarse = Scale {
        start: 8_000,
        per_column: 64,
        per_frame: 1,
        columns: 1_000,
    };
    model.set_scale(coarse);
    model.refresh();
    assert!(matches!(model.sampler().detail, DetailRead::None));

    // 16 columns a frame: 63 frames in view, and 2 s, 16,000 frames, either side.
    let close = Scale {
        per_column: 1,
        per_frame: 16,
        ..coarse
    };
    model.set_scale(close);
    model.refresh();
    assert!(matches!(
        model.sampler().detail,
        DetailRead::Reading {
            start: 0,
            end: 24_063,
            ..
        }
    ));
    until(&mut model, &|m| m.sampler().detail(Some(&file)).is_some());
    let detail = model.sampler().detail(current.as_ref()).unwrap();
    assert!(detail.covers(8_000, 8_063));
    assert!(detail.mean(8_000).unwrap() > 0.0 && detail.mean(7_999).unwrap() < 0.0);

    // Inside what was read, no new read; past it, another.
    model.set_scale(Scale {
        start: 20_000,
        ..close
    });
    model.refresh();
    assert!(matches!(model.sampler().detail, DetailRead::Ready { .. }));
    model.set_scale(Scale {
        start: 30_000,
        ..close
    });
    model.refresh();
    assert!(matches!(
        model.sampler().detail,
        DetailRead::Reading {
            start: 14_000,
            end: 32_000,
            ..
        }
    ));
}

#[test]
fn command_lines_run_and_are_remembered_even_when_they_fail() {
    let (mut model, _dir) = model();
    model.set_input(Input::Command(CommandLine::default()));
    model.run_command("mode shuffle");
    assert_eq!(model.input(), &Input::None);
    assert_eq!(
        model.message(),
        Some(&Message::Core(Notice::Done(Outcome::Mode(Mode::Shuffle))))
    );
    model.run_command("frob");
    assert!(matches!(model.message(), Some(Message::Command(_))));
    model.run_command("   ");

    let mut line = CommandLine::default();
    line.recall(true, model.history());
    assert_eq!(line.text, "frob");
    line.recall(true, model.history());
    assert_eq!(line.text, "mode shuffle", "a blank line was remembered");
}

#[test]
fn a_search_shows_results_as_typed_and_ends_kept_or_cleared() {
    let (mut model, _dir) = model();
    model.search_as_typed("b".into());
    assert_eq!(model.input(), &Input::Search("b".into()));
    assert_eq!(model.results().map(<[Track]>::len), Some(1));

    model.end_search(true);
    assert_eq!(model.input(), &Input::None);
    assert_eq!(model.results().map(<[Track]>::len), Some(1));
    assert_eq!(model.message(), None);

    model.search_as_typed("zzz".into());
    model.end_search(true);
    assert_eq!(model.message(), Some(&Message::NoMatches));

    model.end_search(false);
    assert_eq!(model.results(), None);
    assert_eq!(model.listed().len(), 3);
}

/// Refreshes until the message showing matches `done`, or five seconds pass.
fn refresh_until(model: &mut Model, done: impl Fn(&Message) -> bool) {
    let deadline = Instant::now() + Duration::from_secs(5);
    loop {
        model.refresh();
        if model.message().is_some_and(&done) {
            return;
        }
        assert!(Instant::now() < deadline, "saw {:?}", model.message());
        std::thread::sleep(Duration::from_millis(10));
    }
}

/// Three short WAV files in `dir`.
fn music(dir: &Path) {
    std::fs::create_dir_all(dir).unwrap();
    for name in ["a.wav", "b.wav", "c.wav"] {
        common::silence(&dir.join(name), 8000, 0.05);
    }
}

#[test]
fn a_scan_fills_a_library_that_started_empty() {
    let dir = tempfile::tempdir().unwrap();
    let songs = dir.path().join("music");
    music(&songs);
    let conn = db::open_memory().unwrap();
    let mut model = Model::new(conn, common::fake_player().0, Vec::new(), Config::default());
    model
        .session_mut()
        .set_library_path(dir.path().join("library.db"));

    model.perform(Action::Scan(songs.clone()));
    assert_eq!(
        model.message(),
        Some(&Message::Core(Notice::Done(Outcome::ScanStarted {
            dir: songs.clone()
        })))
    );
    refresh_until(&mut model, |m| {
        matches!(m, Message::Core(Notice::Done(Outcome::Scanned { .. })))
    });
    assert_eq!(model.session().tracks().len(), 3);
    assert!(model.session().has_library_file());
    assert_eq!(
        model.cursors().library,
        Some(0),
        "no cursor on the new rows"
    );
}

#[test]
fn opened_files_are_added_to_the_selection_and_played() {
    let dir = tempfile::tempdir().unwrap();
    let songs = dir.path().join("music");
    music(&songs);
    let (mut model, _library) = model();
    model.perform(Action::Add);
    assert_eq!(model.session().selection().len(), 1);

    model.perform(Action::Open(vec![songs.clone()]));
    refresh_until(&mut model, |m| {
        matches!(m, Message::Core(Notice::Done(Outcome::Opened { .. })))
    });
    assert_eq!(
        model.message(),
        Some(&Message::Core(Notice::Done(Outcome::Opened {
            tracks: 3,
            skipped: 0
        })))
    );
    assert_eq!(model.view(), View::Selection);
    assert_eq!(model.session().selection().len(), 4);
    assert_eq!(
        model.cursors().selection,
        Some(1),
        "not on the first opened"
    );
    let playing: Vec<&str> = model.playing().iter().map(|t| t.path.as_str()).collect();
    assert_eq!(playing.len(), 3);
    assert!(playing[0].ends_with("a.wav"), "{playing:?}");

    model.perform(Action::Open(vec![dir.path().join("gone")]));
    refresh_until(&mut model, |m| {
        matches!(m, Message::Core(Notice::Failed { .. }))
    });
    assert!(matches!(
        model.message(),
        Some(Message::Core(Notice::Failed {
            task: Task::Open,
            ..
        }))
    ));
    assert_eq!(
        model.session().selection().len(),
        4,
        "a failed open changed the selection"
    );
}

#[test]
fn a_peak_is_held_then_released() {
    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);
}

/// Waits until `count` passes `seen`, or five seconds pass.
fn wait_past(count: &std::sync::atomic::AtomicUsize, seen: usize) -> usize {
    let deadline = Instant::now() + Duration::from_secs(5);
    loop {
        let now = count.load(std::sync::atomic::Ordering::SeqCst);
        if now > seen {
            return now;
        }
        assert!(Instant::now() < deadline, "no event arrived");
        std::thread::sleep(Duration::from_millis(10));
    }
}

#[cfg(unix)]
#[test]
fn only_the_latest_slicing_is_shown() {
    use playr_app::action::Slicing;
    use playr_app::sampler::{plan_text, Wave};
    use playr_core::samples::Cut;
    use std::sync::atomic::{AtomicUsize, Ordering};
    use std::sync::Arc;

    let dir = tempfile::tempdir().unwrap();
    let file = dir.path().join("long.wav");
    common::silence(&file, 8000, 60.0);
    let events = Arc::new(AtomicUsize::new(0));
    let counted = events.clone();
    let mut model = Model::waking(
        db::open(&dir.path().join("library.db")).unwrap(),
        common::fake_player().0,
        vec![track(&file.to_string_lossy())],
        Config::default(),
        move || {
            counted.fetch_add(1, Ordering::SeqCst);
        },
    );
    model.perform(Action::ShowView(View::Sampler));
    let deadline = Instant::now() + Duration::from_secs(5);
    while !matches!(model.sampler().wave, Wave::Ready { .. }) {
        assert!(Instant::now() < deadline, "no waveform");
        model.refresh();
        std::thread::sleep(Duration::from_millis(10));
    }

    // The engine keeps its open file. Planning opens the path again, and
    // finds a pipe that blocks until the test writes the track into it.
    let moved = dir.path().join("moved.wav");
    std::fs::rename(&file, &moved).unwrap();
    let made = std::process::Command::new("mkfifo")
        .arg(&file)
        .status()
        .unwrap();
    assert!(made.success());

    let seen = events.load(Ordering::SeqCst);
    model.perform(Action::Slice(Slicing::Region));
    let seen = wait_past(&events, seen);
    // The region's plan waits in the channel while a newer slicing starts.
    model.perform(Action::Slice(Slicing::Onsets(None)));
    model.refresh();
    assert!(model.sampler().pending.is_none(), "an older plan was shown");
    assert_eq!(plan_text(model.sampler()), "planning slices");

    let mut pipe = std::fs::OpenOptions::new().write(true).open(&file).unwrap();
    std::io::copy(&mut std::fs::File::open(&moved).unwrap(), &mut pipe).unwrap();
    drop(pipe);
    wait_past(&events, seen);
    model.refresh();
    let pending = model.sampler().pending.as_ref().map(|p| p.job.cut);
    assert!(
        matches!(pending, Some(Cut::Onsets(_))),
        "{pending:?}, {:?}",
        model.message()
    );
    assert!(!plan_text(model.sampler()).contains("planning"));
}