Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
768ef0f919 | ||
|
|
26d8bc417c | ||
|
|
0200e73ba3 | ||
|
|
e11d95daa5 | ||
|
|
3d91739447 | ||
|
|
7b2fe7c84e | ||
|
|
10710c1755 | ||
|
|
bce0d68442 | ||
|
|
d77316b5b7 |
@@ -2,6 +2,26 @@
|
||||
|
||||
One section per version, newest first.
|
||||
|
||||
## v0.9.0 (2026-11-05)
|
||||
|
||||
### Features
|
||||
|
||||
- The queue can be shuffled from the now-playing screen. The queue button, or S on the keyboard, cycles through shuffling by track, shuffling by album and off. Album shuffle finishes the playing album first. Off goes back to the order the tracks were queued in and carries on after the playing track. Tracks queued while shuffled go to random places among those still to play. The mode shows beside the queue and comes back after a restart.
|
||||
- Holding the activate button on an album, artist or playlist, or pressing Shift+S, plays it shuffled. On a track it shuffles the page the track is on. The activate button now acts when it is released.
|
||||
- Shuffle all, the first tile in Random, plays random tracks from the whole library and keeps fetching more. Tracks queued meanwhile play next, ahead of the random ones.
|
||||
|
||||
## v0.8.7 (2026-11-04)
|
||||
|
||||
### Features
|
||||
|
||||
- On an album page, a track whose cover is a different picture from the album's shows its cover instead of its track number. Only servers that give tracks their own art, such as Navidrome, can show this; Nextcloud Music gives every track the album's cover.
|
||||
|
||||
## v0.8.6 (2026-11-04)
|
||||
|
||||
### Bug fixes
|
||||
|
||||
- Covers cached by versions before 0.8.0 are deleted on start. They were no longer used but stayed on disk.
|
||||
|
||||
## v0.8.5 (2026-11-04)
|
||||
|
||||
### Bug fixes
|
||||
|
||||
Generated
+2
-1
@@ -4385,11 +4385,12 @@ checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4"
|
||||
|
||||
[[package]]
|
||||
name = "remus"
|
||||
version = "0.8.5"
|
||||
version = "0.9.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"directories",
|
||||
"env_logger",
|
||||
"fastrand",
|
||||
"fontique",
|
||||
"gilrs",
|
||||
"gstreamer",
|
||||
|
||||
+2
-1
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "remus"
|
||||
version = "0.8.5"
|
||||
version = "0.9.0"
|
||||
edition = "2024"
|
||||
license = "MIT"
|
||||
|
||||
@@ -8,6 +8,7 @@ license = "MIT"
|
||||
anyhow = "1.0.104"
|
||||
directories = "6.0.0"
|
||||
env_logger = "0.11.11"
|
||||
fastrand = "2.5.0"
|
||||
fontique = { version = "0.11", default-features = false, features = ["fontconfig-dlopen"] }
|
||||
gilrs = "0.11.2"
|
||||
gstreamer = "0.25.4"
|
||||
|
||||
@@ -20,6 +20,9 @@
|
||||
</supports>
|
||||
<content_rating type="oars-1.1"/>
|
||||
<releases>
|
||||
<release version="0.9.0" date="2026-11-05"/>
|
||||
<release version="0.8.7" date="2026-11-04"/>
|
||||
<release version="0.8.6" date="2026-11-04"/>
|
||||
<release version="0.8.5" date="2026-11-04"/>
|
||||
<release version="0.8.4" date="2026-11-04"/>
|
||||
<release version="0.8.3" date="2026-11-04"/>
|
||||
|
||||
+422
-12
@@ -5,7 +5,7 @@ use std::cell::RefCell;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::future::Future;
|
||||
use std::num::NonZeroUsize;
|
||||
use std::path::PathBuf;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::rc::Rc;
|
||||
use std::sync::Arc;
|
||||
use std::time::{Duration, Instant};
|
||||
@@ -23,6 +23,7 @@ use crate::palette::{Lab, Palette, Role, Tone};
|
||||
use crate::player::{Player, PlayerEvent};
|
||||
use crate::prompts::{self, Control, Family, Prompts};
|
||||
use crate::saved_queue::{self, SavedQueue, SavedQueues};
|
||||
use crate::shuffle::{self, Library, Mode};
|
||||
use crate::subsonic::{self, Album, Artist, Client, Playlist, SearchResult, Song};
|
||||
use crate::{Action, AppWindow, Area, Header, Hint, Item, Screen, Theme};
|
||||
|
||||
@@ -125,6 +126,8 @@ enum Target {
|
||||
Playlist(String),
|
||||
/// Index into the page's `songs`.
|
||||
Song(usize),
|
||||
/// Starts library shuffle.
|
||||
ShuffleAll,
|
||||
Setting(Setting),
|
||||
}
|
||||
|
||||
@@ -264,7 +267,19 @@ pub struct App {
|
||||
queue_items: Rc<VecModel<Item>>,
|
||||
queue_range: (usize, usize),
|
||||
covers: Covers,
|
||||
/// In the order it plays, which the player's list matches.
|
||||
queue: Vec<Song>,
|
||||
/// Each queued track's position in the order it was queued, which
|
||||
/// turning shuffle off goes back to.
|
||||
order: Vec<usize>,
|
||||
shuffle: Mode,
|
||||
library: Option<Library>,
|
||||
/// A batch of random tracks is on its way for library shuffle.
|
||||
library_fetching: bool,
|
||||
/// The player's queue generation as of the last reorder. A track index
|
||||
/// from an earlier one points at the wrong song.
|
||||
queue_generation: u64,
|
||||
rng: fastrand::Rng,
|
||||
current: Option<usize>,
|
||||
queue_sel: usize,
|
||||
position: f64,
|
||||
@@ -330,6 +345,9 @@ impl App {
|
||||
{
|
||||
log::warn!("cover cache disabled, cannot create {}: {e}", d.display());
|
||||
}
|
||||
if let Some(d) = dir.clone() {
|
||||
rt.spawn_blocking(move || remove_unkeyed_covers(&d));
|
||||
}
|
||||
let inhibitor = Inhibitor::spawn(&rt);
|
||||
let mpris = Mpris::spawn(&rt, |c| {
|
||||
let _ = slint::invoke_from_event_loop(move || with_app(move |app| app.mpris_command(c)));
|
||||
@@ -366,6 +384,12 @@ impl App {
|
||||
generation: 0,
|
||||
},
|
||||
queue: Vec::new(),
|
||||
order: Vec::new(),
|
||||
shuffle: Mode::Off,
|
||||
library: None,
|
||||
library_fetching: false,
|
||||
queue_generation: 0,
|
||||
rng: fastrand::Rng::new(),
|
||||
current: None,
|
||||
queue_sel: 0,
|
||||
position: 0.0,
|
||||
@@ -601,8 +625,7 @@ impl App {
|
||||
if self.client.is_some() {
|
||||
self.save_queue();
|
||||
self.stop_player();
|
||||
self.queue.clear();
|
||||
self.current = None;
|
||||
self.clear_queue();
|
||||
self.queue_sel = 0;
|
||||
self.position = 0.0;
|
||||
self.duration = 0.0;
|
||||
@@ -622,6 +645,14 @@ impl App {
|
||||
self.sync_inhibit();
|
||||
}
|
||||
|
||||
fn clear_queue(&mut self) {
|
||||
self.queue.clear();
|
||||
self.order.clear();
|
||||
self.shuffle = Mode::Off;
|
||||
self.library = None;
|
||||
self.current = None;
|
||||
}
|
||||
|
||||
/// Stops playback for good, dropping whatever the player still has on
|
||||
/// its way about the old queue.
|
||||
fn stop_player(&self) {
|
||||
@@ -678,8 +709,7 @@ impl App {
|
||||
// Nothing left to browse: stop, keep the queue on disk.
|
||||
self.save_queue();
|
||||
self.stop_player();
|
||||
self.queue.clear();
|
||||
self.current = None;
|
||||
self.clear_queue();
|
||||
self.client = None;
|
||||
self.render_player();
|
||||
self.add_server();
|
||||
@@ -742,6 +772,13 @@ impl App {
|
||||
}
|
||||
|
||||
pub fn action(&mut self, a: Action) {
|
||||
// A long press of the controller's activate button shuffles what is
|
||||
// selected, and activates wherever there is nothing to shuffle.
|
||||
let a = match a {
|
||||
Action::HoldActivate if self.selected_shuffle_target().is_some() => Action::Shuffle,
|
||||
Action::HoldActivate => Action::Activate,
|
||||
a => a,
|
||||
};
|
||||
match a {
|
||||
Action::Quit => {
|
||||
let _ = slint::quit_event_loop();
|
||||
@@ -802,6 +839,7 @@ impl App {
|
||||
}
|
||||
}
|
||||
Action::Search => self.open_search(),
|
||||
Action::CycleShuffle => self.cycle_shuffle(),
|
||||
_ => return false,
|
||||
}
|
||||
true
|
||||
@@ -840,6 +878,7 @@ impl App {
|
||||
self.move_sel(a)
|
||||
}
|
||||
Action::Activate => self.activate(),
|
||||
Action::Shuffle => self.shuffle_selected(),
|
||||
Action::Back => self.back(),
|
||||
Action::Queue => match self.selected_setting() {
|
||||
Some(Setting::Server(i)) => self.remove_server(i),
|
||||
@@ -1130,6 +1169,7 @@ impl App {
|
||||
let songs = page.songs.clone();
|
||||
self.play_songs(songs, index);
|
||||
}
|
||||
Target::ShuffleAll => self.start_library_shuffle(),
|
||||
Target::Setting(s) => self.toggle_setting(s),
|
||||
}
|
||||
}
|
||||
@@ -1392,7 +1432,23 @@ impl App {
|
||||
move |app, r| app.page_loaded(page_id, r, true),
|
||||
),
|
||||
Source::Section(Section::Random) => self.spawn(
|
||||
async move { Ok(albums_data(client.album_list("random", 120, 0).await?)) },
|
||||
async move {
|
||||
let mut data = albums_data(client.album_list("random", 120, 0).await?);
|
||||
data.entries.insert(
|
||||
0,
|
||||
Entry {
|
||||
title: "Shuffle all".to_string(),
|
||||
subtitle: "Random tracks from the whole library".to_string(),
|
||||
detail: String::new(),
|
||||
number: String::new(),
|
||||
cover: None,
|
||||
round: false,
|
||||
show_art: true,
|
||||
target: Target::ShuffleAll,
|
||||
},
|
||||
);
|
||||
Ok(data)
|
||||
},
|
||||
move |app, r| app.page_loaded(page_id, r, true),
|
||||
),
|
||||
Source::Section(Section::Albums) => {
|
||||
@@ -1661,6 +1717,33 @@ impl App {
|
||||
self.items_range = (lo, hi);
|
||||
}
|
||||
|
||||
/// The album's cover id, on an album page.
|
||||
fn album_cover_id(&self) -> Option<String> {
|
||||
let page = self.current_page()?;
|
||||
if !page.list || !matches!(page.source, Source::Album(_)) {
|
||||
return None;
|
||||
}
|
||||
page.header.as_ref()?.cover.clone()
|
||||
}
|
||||
|
||||
/// Whether a track's cover is a different picture from its album's, so its
|
||||
/// row shows the cover instead of the track number. Compared by picture:
|
||||
/// Navidrome gives every track its own cover id even when it is the album's
|
||||
/// image. False until both are decoded at this size; the load of either
|
||||
/// redraws the row.
|
||||
fn own_picture(&mut self, track: Option<&str>, album: &str, px: u32) -> bool {
|
||||
let Some(track) = track.filter(|t| *t != album) else {
|
||||
return false;
|
||||
};
|
||||
// Starts the album cover's load at row size, which the header does not.
|
||||
self.cover(album, px);
|
||||
let print = |app: &mut App, id: &str| app.covers.prints.get(&(id.to_string(), px)).copied();
|
||||
match (print(self, track), print(self, album)) {
|
||||
(Some(t), Some(a)) => t != a,
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
fn playing_id(&self) -> Option<&str> {
|
||||
self.current.and_then(|i| self.queue.get(i)).map(|s| s.id.as_str())
|
||||
}
|
||||
@@ -1672,7 +1755,11 @@ impl App {
|
||||
Target::Song(i) => page.songs.get(i).map(|s| s.id.as_str()) == self.playing_id(),
|
||||
_ => false,
|
||||
};
|
||||
let album_cover = self.album_cover_id();
|
||||
let cover = entry.cover.as_deref().and_then(|id| self.cover(id, px));
|
||||
let show_art = entry.show_art
|
||||
|| matches!(entry.target, Target::Song(_))
|
||||
&& album_cover.is_some_and(|album| self.own_picture(entry.cover.as_deref(), &album, px));
|
||||
let level = match entry.target {
|
||||
Target::Setting(Setting::CoverBackdrop) => Some(self.settings.cover_backdrop as f32 / 100.0),
|
||||
_ => None,
|
||||
@@ -1688,14 +1775,25 @@ impl App {
|
||||
has_cover: cover.is_some(),
|
||||
cover: cover.unwrap_or_default(),
|
||||
round: entry.round,
|
||||
show_art: entry.show_art,
|
||||
show_art,
|
||||
playing,
|
||||
slider: level.is_some(),
|
||||
level: level.unwrap_or_default(),
|
||||
})
|
||||
}
|
||||
|
||||
fn render_shuffle(&self) {
|
||||
let label = match self.shuffle {
|
||||
_ if self.library.is_some() => "Shuffling the whole library",
|
||||
Mode::Off => "",
|
||||
Mode::Tracks => "Shuffled by track",
|
||||
Mode::Albums => "Shuffled by album",
|
||||
};
|
||||
self.ui.set_np_shuffle(label.into());
|
||||
}
|
||||
|
||||
fn render_hints(&self) {
|
||||
self.render_shuffle();
|
||||
let mut hints = Vec::new();
|
||||
let mut h = |c: Control, l: &str| {
|
||||
let icons = self.hint_icons(c);
|
||||
@@ -1743,7 +1841,7 @@ impl App {
|
||||
.and_then(|p| p.entries.get(p.sel))
|
||||
.map(|e| &e.target);
|
||||
match target {
|
||||
Some(Target::Song(_)) => h(Control::Activate, "Play"),
|
||||
Some(Target::Song(_) | Target::ShuffleAll) => h(Control::Activate, "Play"),
|
||||
Some(Target::Setting(Setting::CoverBackdrop)) => h(Control::Seek, "Adjust"),
|
||||
Some(Target::Setting(Setting::Version)) => {}
|
||||
Some(Target::Setting(Setting::Server(i))) => {
|
||||
@@ -1764,6 +1862,18 @@ impl App {
|
||||
if matches!(target, Some(Target::Song(_) | Target::Album(_) | Target::Playlist(_))) {
|
||||
h(Control::Queue, "Add to queue");
|
||||
}
|
||||
if matches!(
|
||||
target,
|
||||
Some(Target::Song(_) | Target::Album(_) | Target::Artist(_) | Target::Playlist(_))
|
||||
) {
|
||||
h(
|
||||
Control::ShufflePlay,
|
||||
match self.prompts {
|
||||
Prompts::Keyboard => "Shuffle",
|
||||
Prompts::Pad(_) => "Hold: Shuffle",
|
||||
},
|
||||
);
|
||||
}
|
||||
h(Control::PlayPause, "Play / Pause");
|
||||
h(Control::Sections, "Sections");
|
||||
h(Control::NowPlaying, "Now playing");
|
||||
@@ -1774,6 +1884,15 @@ impl App {
|
||||
h(Control::Back, "Back");
|
||||
h(Control::PlayPause, "Play / Pause");
|
||||
h(Control::Skip, "Skip");
|
||||
h(
|
||||
Control::Shuffle,
|
||||
match self.shuffle {
|
||||
_ if self.library.is_some() => "Shuffle: library",
|
||||
Mode::Off => "Shuffle: off",
|
||||
Mode::Tracks => "Shuffle: tracks",
|
||||
Mode::Albums => "Shuffle: albums",
|
||||
},
|
||||
);
|
||||
h(Control::Seek, "Seek");
|
||||
h(Control::Volume, "Volume");
|
||||
h(Control::Mute, "Mute");
|
||||
@@ -1923,9 +2042,11 @@ impl App {
|
||||
|
||||
// Refresh whatever shows this cover.
|
||||
let (lo, hi) = self.items_range;
|
||||
// Every track row of an album compares its picture with the album's.
|
||||
let album = self.album_cover_id().as_deref() == Some(id);
|
||||
let rows: Vec<usize> = match self.current_page() {
|
||||
Some(p) => (lo..hi.min(p.entries.len()))
|
||||
.filter(|&i| p.entries[i].cover.as_deref() == Some(id))
|
||||
.filter(|&i| album || p.entries[i].cover.as_deref() == Some(id))
|
||||
.collect(),
|
||||
None => Vec::new(),
|
||||
};
|
||||
@@ -1985,7 +2106,10 @@ impl App {
|
||||
};
|
||||
let urls: Vec<String> = songs.iter().map(|s| client.stream_url(&s.id)).collect();
|
||||
player.play_list(&urls, start);
|
||||
self.order = (0..songs.len()).collect();
|
||||
self.queue = songs;
|
||||
self.shuffle = Mode::Off;
|
||||
self.library = None;
|
||||
self.current = None;
|
||||
self.queue_sel = start;
|
||||
self.sync_queue(true);
|
||||
@@ -2004,7 +2128,25 @@ impl App {
|
||||
player.append(&client.stream_url(&s.id));
|
||||
}
|
||||
let n = songs.len();
|
||||
let added = self.queue.len();
|
||||
let next = self.order.iter().max().map_or(0, |m| m + 1);
|
||||
self.order.extend(next..next + n);
|
||||
self.queue.extend(songs);
|
||||
if let Some(lib) = self.library {
|
||||
// After the playing track and what was queued before, ahead of the random tracks.
|
||||
let perm = self.rearrange(|songs, _, current, pending| {
|
||||
let at = lib.added_end.max(fixed(current, pending)).min(added);
|
||||
(0..at).chain(added..songs.len()).chain(at..added).collect()
|
||||
});
|
||||
if let Some(at) = perm.iter().position(|&p| p == added) {
|
||||
self.library = Some(Library { added_end: at + n });
|
||||
}
|
||||
} else if self.shuffle != Mode::Off {
|
||||
let (mode, mut rng) = (self.shuffle, fastrand::Rng::with_seed(self.rng.u64(..)));
|
||||
self.rearrange(|songs, order, current, pending| {
|
||||
shuffle::insert(&mut rng, mode, songs, order, fixed(current, pending), added)
|
||||
});
|
||||
}
|
||||
self.sync_queue(true);
|
||||
self.save_queue();
|
||||
self.toast(if n == 1 {
|
||||
@@ -2014,6 +2156,70 @@ impl App {
|
||||
});
|
||||
}
|
||||
|
||||
/// What shuffle play would play from the selected row, if anything.
|
||||
fn selected_shuffle_target(&self) -> Option<Target> {
|
||||
if self.screen != Screen::Browse || self.area != Area::Content {
|
||||
return None;
|
||||
}
|
||||
let page = self.current_page()?;
|
||||
let target = &page.entries.get(page.sel)?.target;
|
||||
matches!(
|
||||
target,
|
||||
Target::Song(_) | Target::Album(_) | Target::Artist(_) | Target::Playlist(_)
|
||||
)
|
||||
.then(|| target.clone())
|
||||
}
|
||||
|
||||
/// Plays the selected album, artist or playlist shuffled, or the page a
|
||||
/// selected song is on.
|
||||
fn shuffle_selected(&mut self) {
|
||||
let (Some(target), Some(client)) = (self.selected_shuffle_target(), self.client.clone()) else {
|
||||
return;
|
||||
};
|
||||
let failed = |app: &mut App, e: anyhow::Error| app.toast(format!("Could not shuffle: {e:#}"));
|
||||
match target {
|
||||
Target::Song(_) => {
|
||||
let songs = self.current_page().map(|p| p.songs.clone()).unwrap_or_default();
|
||||
self.shuffle_play(songs);
|
||||
}
|
||||
Target::Album(id) => self.spawn(
|
||||
async move { Ok(client.album(&id).await?.song) },
|
||||
move |app, r| match r {
|
||||
Ok(songs) => app.shuffle_play(songs),
|
||||
Err(e) => failed(app, e),
|
||||
},
|
||||
),
|
||||
Target::Playlist(id) => {
|
||||
self.spawn(
|
||||
async move { Ok(client.playlist(&id).await?.entry) },
|
||||
move |app, r| match r {
|
||||
Ok(songs) => app.shuffle_play(songs),
|
||||
Err(e) => failed(app, e),
|
||||
},
|
||||
)
|
||||
}
|
||||
Target::Artist(id) => self.spawn(async move { client.artist_songs(&id).await }, move |app, r| match r {
|
||||
Ok(songs) => app.shuffle_play(songs),
|
||||
Err(e) => failed(app, e),
|
||||
}),
|
||||
Target::ShuffleAll | Target::Setting(_) => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// Replaces the queue with `songs` in random order, with track shuffle on
|
||||
/// so turning it off goes back to their own order.
|
||||
fn shuffle_play(&mut self, songs: Vec<Song>) {
|
||||
if songs.is_empty() {
|
||||
self.toast("Nothing to shuffle".into());
|
||||
return;
|
||||
}
|
||||
let perm = shuffle::tracks(&mut self.rng, songs.len(), 0);
|
||||
self.play_songs(shuffle::apply(&songs, &perm), 0);
|
||||
self.order = perm;
|
||||
self.shuffle = Mode::Tracks;
|
||||
self.render_hints();
|
||||
}
|
||||
|
||||
fn enqueue_selected(&mut self) {
|
||||
let Some(page) = self.current_page() else { return };
|
||||
let Some(entry) = page.entries.get(page.sel) else {
|
||||
@@ -2044,7 +2250,7 @@ impl App {
|
||||
)
|
||||
}
|
||||
Target::Artist(_) => self.toast("Open the artist to queue one of their albums".into()),
|
||||
Target::Setting(_) => {}
|
||||
Target::ShuffleAll | Target::Setting(_) => {}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2074,7 +2280,12 @@ impl App {
|
||||
}
|
||||
}
|
||||
}
|
||||
PlayerEvent::Track(t) => {
|
||||
PlayerEvent::Track { generation, .. } | PlayerEvent::Art { generation, .. }
|
||||
if generation < self.queue_generation =>
|
||||
{
|
||||
return;
|
||||
}
|
||||
PlayerEvent::Track { index: t, .. } => {
|
||||
// Reported once per track started, so the same index again is a
|
||||
// new play: another queue started there, or the track replayed.
|
||||
let t = t.filter(|&i| i < self.queue.len());
|
||||
@@ -2103,8 +2314,13 @@ impl App {
|
||||
self.sync_items(true);
|
||||
self.sync_queue(true);
|
||||
self.save_queue();
|
||||
self.maintain_library();
|
||||
}
|
||||
PlayerEvent::Art(i, bytes) => {
|
||||
PlayerEvent::Art {
|
||||
index: i,
|
||||
picture: bytes,
|
||||
..
|
||||
} => {
|
||||
if self.current != Some(i) {
|
||||
return;
|
||||
}
|
||||
@@ -2220,7 +2436,16 @@ impl App {
|
||||
);
|
||||
let urls: Vec<String> = saved.songs.iter().map(|s| client.stream_url(&s.id)).collect();
|
||||
player.load_paused(&urls, current, saved.position);
|
||||
// An older file has no order: it was saved unshuffled.
|
||||
let (order, mode) = if saved.order.len() == saved.songs.len() {
|
||||
(saved.order, saved.shuffle)
|
||||
} else {
|
||||
((0..saved.songs.len()).collect(), Mode::Off)
|
||||
};
|
||||
self.queue = saved.songs;
|
||||
self.order = order;
|
||||
self.shuffle = mode;
|
||||
self.library = saved.library;
|
||||
self.current = None;
|
||||
self.queue_sel = current.unwrap_or(0);
|
||||
self.held = current.is_some();
|
||||
@@ -2241,6 +2466,9 @@ impl App {
|
||||
};
|
||||
let queue = SavedQueue {
|
||||
songs: self.queue.clone(),
|
||||
order: self.order.clone(),
|
||||
shuffle: self.shuffle,
|
||||
library: self.library,
|
||||
current,
|
||||
position,
|
||||
};
|
||||
@@ -2287,6 +2515,7 @@ impl App {
|
||||
}
|
||||
|
||||
fn render_player(&mut self) {
|
||||
self.render_shuffle();
|
||||
let song = self.current.and_then(|i| self.queue.get(i)).cloned();
|
||||
self.ui.set_np_has_track(song.is_some());
|
||||
self.ui.set_np_paused(self.paused);
|
||||
@@ -2449,6 +2678,7 @@ impl App {
|
||||
Action::PageDown => self.move_queue_sel(8),
|
||||
Action::Left => self.seek(-10.0),
|
||||
Action::Right => self.seek(10.0),
|
||||
Action::Queue => self.cycle_shuffle(),
|
||||
Action::Activate => {
|
||||
if self.queue_sel < self.queue.len()
|
||||
&& let Some(p) = &self.player
|
||||
@@ -2460,6 +2690,141 @@ impl App {
|
||||
}
|
||||
}
|
||||
|
||||
fn cycle_shuffle(&mut self) {
|
||||
if self.library.is_some() {
|
||||
self.toast("Playing the whole library shuffled".into());
|
||||
return;
|
||||
}
|
||||
if self.queue.is_empty() {
|
||||
self.toast("Nothing to shuffle".into());
|
||||
return;
|
||||
}
|
||||
let mode = self.shuffle.next();
|
||||
self.set_shuffle(mode);
|
||||
self.toast(
|
||||
match mode {
|
||||
Mode::Off => "Shuffle off",
|
||||
Mode::Tracks => "Shuffling tracks",
|
||||
Mode::Albums => "Shuffling albums",
|
||||
}
|
||||
.into(),
|
||||
);
|
||||
}
|
||||
|
||||
/// Reorders what has not played yet. Turning shuffle off goes back to
|
||||
/// the original order, carrying on after the playing track.
|
||||
fn set_shuffle(&mut self, mode: Mode) {
|
||||
self.shuffle = mode;
|
||||
let mut rng = fastrand::Rng::with_seed(self.rng.u64(..));
|
||||
self.rearrange(|songs, order, current, pending| match mode {
|
||||
// The handed-over track plays next whatever the order says.
|
||||
Mode::Off => shuffle::unshuffle(order, current.or(pending), current.and(pending)),
|
||||
Mode::Tracks => shuffle::tracks(&mut rng, songs.len(), fixed(current, pending)),
|
||||
Mode::Albums => shuffle::albums(&mut rng, songs, order, current.or(pending), fixed(current, pending)),
|
||||
});
|
||||
self.render_hints();
|
||||
}
|
||||
|
||||
/// Reorders the queue through the player, which keeps the playing track
|
||||
/// going, and moves the songs and their original positions to match.
|
||||
/// `arrange` gets the songs, their original positions, and the playing
|
||||
/// and handed-over positions, and returns a `shuffle` permutation.
|
||||
fn rearrange(
|
||||
&mut self,
|
||||
arrange: impl FnOnce(&[Song], &[usize], Option<usize>, Option<usize>) -> Vec<usize>,
|
||||
) -> Vec<usize> {
|
||||
let Some(player) = &self.player else { return Vec::new() };
|
||||
let (songs, order) = (&self.queue, &self.order);
|
||||
let r = player.reorder(|current, pending| arrange(songs, order, current, pending));
|
||||
let moved = |i: usize| r.perm.iter().position(|&p| p == i);
|
||||
self.queue = shuffle::apply(&self.queue, &r.perm);
|
||||
self.order = shuffle::apply(&self.order, &r.perm);
|
||||
self.queue_generation = r.generation;
|
||||
self.queue_sel = moved(self.queue_sel).or(r.current).unwrap_or(0);
|
||||
self.restoring = self.restoring.and_then(|(i, pos)| moved(i).map(|i| (i, pos)));
|
||||
let seen = self.current.and_then(moved);
|
||||
if seen == r.current {
|
||||
self.current = seen;
|
||||
self.sync_queue(true);
|
||||
self.save_queue();
|
||||
} else {
|
||||
// A track started that its report, now stale, has not told us of.
|
||||
self.player_event(PlayerEvent::Track {
|
||||
index: r.current,
|
||||
generation: r.generation,
|
||||
});
|
||||
}
|
||||
r.perm
|
||||
}
|
||||
|
||||
fn start_library_shuffle(&mut self) {
|
||||
let Some(client) = self.client.clone() else { return };
|
||||
self.spawn(
|
||||
async move { client.random_songs(LIBRARY_BATCH).await },
|
||||
|app, r| match r {
|
||||
Ok(songs) if songs.is_empty() => app.toast("The library has no tracks".into()),
|
||||
Ok(songs) => {
|
||||
app.play_songs(songs, 0);
|
||||
app.library = Some(Library::default());
|
||||
app.render_hints();
|
||||
app.toast("Shuffling the whole library".into());
|
||||
}
|
||||
Err(e) => app.toast(format!("Could not shuffle the library: {e:#}")),
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
/// Under library shuffle, drops tracks played long ago and fetches more
|
||||
/// random ones as the queue runs low.
|
||||
fn maintain_library(&mut self) {
|
||||
let (Some(lib), Some(current)) = (self.library, self.current) else {
|
||||
return;
|
||||
};
|
||||
if current > LIBRARY_KEEP_PLAYED {
|
||||
let perm = self.rearrange(|songs, _, current, pending| {
|
||||
let first = current.into_iter().chain(pending).min().unwrap_or(0);
|
||||
(first.saturating_sub(LIBRARY_KEEP_PLAYED)..songs.len()).collect()
|
||||
});
|
||||
let added_end = perm.iter().position(|&p| p >= lib.added_end).unwrap_or(perm.len());
|
||||
self.library = Some(Library { added_end });
|
||||
}
|
||||
let left = self.current.map_or(0, |c| self.queue.len().saturating_sub(c + 1));
|
||||
if left >= LIBRARY_LOW || self.library_fetching {
|
||||
return;
|
||||
}
|
||||
let Some(client) = self.client.clone() else { return };
|
||||
self.library_fetching = true;
|
||||
let epoch = self.player_epoch.load(std::sync::atomic::Ordering::Relaxed);
|
||||
self.spawn(
|
||||
async move { client.random_songs(LIBRARY_BATCH).await },
|
||||
move |app, r| {
|
||||
app.library_fetching = false;
|
||||
// Library shuffle ended, or another server is playing.
|
||||
if app.library.is_none() || app.player_epoch.load(std::sync::atomic::Ordering::Relaxed) != epoch {
|
||||
return;
|
||||
}
|
||||
match r {
|
||||
Ok(songs) => app.append_random(songs),
|
||||
Err(e) => log::warn!("could not fetch random tracks: {e:#}"),
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
fn append_random(&mut self, songs: Vec<Song>) {
|
||||
let (Some(client), Some(player)) = (&self.client, &self.player) else {
|
||||
return;
|
||||
};
|
||||
for s in &songs {
|
||||
player.append(&client.stream_url(&s.id));
|
||||
}
|
||||
let next = self.order.iter().max().map_or(0, |m| m + 1);
|
||||
self.order.extend(next..next + songs.len());
|
||||
self.queue.extend(songs);
|
||||
self.sync_queue(true);
|
||||
self.save_queue();
|
||||
}
|
||||
|
||||
fn queue_clicked(&mut self, index: usize) {
|
||||
self.queue_sel = index;
|
||||
self.ui.set_queue_selected(index as i32);
|
||||
@@ -2795,6 +3160,22 @@ fn color(lab: Lab) -> Color {
|
||||
Color::from_rgb_u8(r, g, b)
|
||||
}
|
||||
|
||||
/// Deletes the covers that versions before 0.8.0 cached straight under
|
||||
/// `root`. Covers now live in a directory per server, so files directly in
|
||||
/// `root` are never read again.
|
||||
fn remove_unkeyed_covers(root: &Path) {
|
||||
let Ok(entries) = std::fs::read_dir(root) else { return };
|
||||
let mut removed = 0;
|
||||
for entry in entries.flatten() {
|
||||
if entry.file_type().is_ok_and(|t| t.is_file()) && std::fs::remove_file(entry.path()).is_ok() {
|
||||
removed += 1;
|
||||
}
|
||||
}
|
||||
if removed > 0 {
|
||||
log::info!("removed {removed} covers cached before covers were kept per server");
|
||||
}
|
||||
}
|
||||
|
||||
fn sanitize(id: &str) -> String {
|
||||
id.chars()
|
||||
.map(|c| {
|
||||
@@ -2892,10 +3273,39 @@ fn join_dot<I: IntoIterator<Item = Option<String>>>(parts: I) -> String {
|
||||
.join(" · ")
|
||||
}
|
||||
|
||||
/// Random tracks fetched at a time for library shuffle.
|
||||
const LIBRARY_BATCH: u32 = 50;
|
||||
/// Library shuffle fetches more once fewer than this are left to play.
|
||||
const LIBRARY_LOW: usize = 5;
|
||||
/// Played tracks library shuffle keeps for going back to.
|
||||
const LIBRARY_KEEP_PLAYED: usize = 50;
|
||||
|
||||
/// How many tracks at the head of the queue a reorder leaves in place: up to
|
||||
/// the one playing, and the one already handed to the player after it.
|
||||
fn fixed(current: Option<usize>, pending: Option<usize>) -> usize {
|
||||
current.max(pending).map_or(0, |i| i + 1)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn unkeyed_covers_go_and_server_directories_stay() {
|
||||
let root = std::env::temp_dir().join(format!("remus-covers-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
let server = root.join("u_https___host");
|
||||
std::fs::create_dir_all(&server).unwrap();
|
||||
std::fs::write(root.join("al-1_600"), b"old").unwrap();
|
||||
std::fs::write(server.join("al-1_600"), b"new").unwrap();
|
||||
|
||||
remove_unkeyed_covers(&root);
|
||||
|
||||
assert!(!root.join("al-1_600").exists());
|
||||
assert!(server.join("al-1_600").exists());
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
}
|
||||
|
||||
fn png(pixel: [u8; 3]) -> Vec<u8> {
|
||||
let img = image::RgbImage::from_pixel(8, 8, image::Rgb(pixel));
|
||||
let mut out = std::io::Cursor::new(Vec::new());
|
||||
|
||||
@@ -95,6 +95,9 @@ fn step(ui: slint::Weak<AppWindow>, steps: Vec<String>, i: usize) {
|
||||
"volume-up" => Action::VolumeUp,
|
||||
"volume-down" => Action::VolumeDown,
|
||||
"mute" => Action::ToggleMute,
|
||||
"cycle-shuffle" => Action::CycleShuffle,
|
||||
"shuffle" => Action::Shuffle,
|
||||
"hold-activate" => Action::HoldActivate,
|
||||
other => {
|
||||
log::warn!("unknown dev script step {other}");
|
||||
Action::None
|
||||
|
||||
+36
-2
@@ -27,6 +27,8 @@ const REPEAT_DELAY: Duration = Duration::from_millis(380);
|
||||
const REPEAT_SLOW: Duration = Duration::from_millis(110);
|
||||
const REPEAT_FAST: Duration = Duration::from_millis(45);
|
||||
const FAST_AFTER: Duration = Duration::from_millis(1500);
|
||||
/// How long South is held before it counts as a long press.
|
||||
const LONG_PRESS: Duration = Duration::from_millis(500);
|
||||
const STICK_ON: f32 = 0.55;
|
||||
const STICK_OFF: f32 = 0.35;
|
||||
|
||||
@@ -37,6 +39,14 @@ enum Source {
|
||||
RightStick,
|
||||
}
|
||||
|
||||
/// South acts on release, so a long press can mean something else.
|
||||
struct SouthPress {
|
||||
family: Family,
|
||||
since: Instant,
|
||||
/// Sent as a long press already, so the release sends nothing.
|
||||
long: bool,
|
||||
}
|
||||
|
||||
struct Held {
|
||||
source: Source,
|
||||
action: Action,
|
||||
@@ -66,6 +76,7 @@ pub fn spawn_gamepad(emit: impl Fn(PadEvent) + Send + 'static) {
|
||||
}
|
||||
emit(PadEvent::Present(present(&gilrs, &mut families)));
|
||||
let mut held: Option<Held> = None;
|
||||
let mut south: Option<SouthPress> = None;
|
||||
loop {
|
||||
while let Some(ev) = gilrs.next_event_blocking(Some(Duration::from_millis(15))) {
|
||||
if matches!(ev.event, EventType::Connected | EventType::Disconnected) {
|
||||
@@ -77,6 +88,20 @@ pub fn spawn_gamepad(emit: impl Fn(PadEvent) + Send + 'static) {
|
||||
}
|
||||
let family = families.family(&gilrs, ev.id);
|
||||
match ev.event {
|
||||
EventType::ButtonPressed(Button::South, _) => {
|
||||
south = Some(SouthPress {
|
||||
family,
|
||||
since: Instant::now(),
|
||||
long: false,
|
||||
});
|
||||
}
|
||||
EventType::ButtonReleased(Button::South, _) => {
|
||||
if let Some(p) = south.take()
|
||||
&& !p.long
|
||||
{
|
||||
emit(PadEvent::Action(Action::Activate, p.family));
|
||||
}
|
||||
}
|
||||
EventType::ButtonPressed(b, _) => {
|
||||
if let Some(a) = dpad_action(b) {
|
||||
held = Some(start_hold(Source::DPad, a, family));
|
||||
@@ -108,10 +133,20 @@ pub fn spawn_gamepad(emit: impl Fn(PadEvent) + Send + 'static) {
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
EventType::Disconnected => held = None,
|
||||
EventType::Disconnected => {
|
||||
held = None;
|
||||
south = None;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
if let Some(p) = south.as_mut()
|
||||
&& !p.long
|
||||
&& p.since.elapsed() >= LONG_PRESS
|
||||
{
|
||||
p.long = true;
|
||||
emit(PadEvent::Action(Action::HoldActivate, p.family));
|
||||
}
|
||||
if let Some(h) = held.as_mut() {
|
||||
let now = Instant::now();
|
||||
if now >= h.next {
|
||||
@@ -216,7 +251,6 @@ fn dpad_action(b: Button) -> Option<Action> {
|
||||
|
||||
fn button_action(b: Button) -> Option<Action> {
|
||||
Some(match b {
|
||||
Button::South => Action::Activate,
|
||||
Button::East => Action::Back,
|
||||
Button::West => Action::PlayPause,
|
||||
Button::North => Action::Queue,
|
||||
|
||||
@@ -10,6 +10,7 @@ mod palette;
|
||||
mod player;
|
||||
mod prompts;
|
||||
mod saved_queue;
|
||||
mod shuffle;
|
||||
mod subsonic;
|
||||
|
||||
use std::time::Duration;
|
||||
|
||||
+179
-36
@@ -17,12 +17,30 @@ pub enum PlayerEvent {
|
||||
Position(f64),
|
||||
Duration(f64),
|
||||
Paused(bool),
|
||||
/// Index into the queue, None when playback has stopped.
|
||||
Track(Option<usize>),
|
||||
/// The picture embedded in a track's file, or None once it is clear the
|
||||
/// file has none. Sent once per track started, after its `Track`. A
|
||||
/// picture that turns up late is still sent, after the None.
|
||||
Art(usize, Option<Vec<u8>>),
|
||||
/// Index into the queue, None when playback has stopped. An index is
|
||||
/// only valid for the queue `generation` it was sent from: see `reorder`.
|
||||
Track {
|
||||
index: Option<usize>,
|
||||
generation: u64,
|
||||
},
|
||||
/// The picture embedded in the playing track's file, or None once it is
|
||||
/// clear the file has none. Sent once per track started, after its
|
||||
/// `Track`. A picture that turns up late is still sent, after the None.
|
||||
Art {
|
||||
index: usize,
|
||||
generation: u64,
|
||||
picture: Option<Vec<u8>>,
|
||||
},
|
||||
}
|
||||
|
||||
/// The queue after `reorder`.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct Reordered {
|
||||
/// The new order, as positions in the old one.
|
||||
pub perm: Vec<usize>,
|
||||
pub current: Option<usize>,
|
||||
pub pending: Option<usize>,
|
||||
pub generation: u64,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
@@ -36,6 +54,8 @@ struct Queue {
|
||||
hold: bool,
|
||||
/// Seconds to seek to once the paused track has prerolled.
|
||||
seek_to: Option<f64>,
|
||||
/// Bumped by every reorder, so an index sent before one is recognised.
|
||||
generation: u64,
|
||||
}
|
||||
|
||||
/// Pictures found in the files being decoded, by URI.
|
||||
@@ -112,6 +132,28 @@ impl Player {
|
||||
self.play_index(start);
|
||||
}
|
||||
|
||||
/// Reorders the queue without interrupting the playing track. `arrange`
|
||||
/// gets the playing position and the one already handed to playbin, and
|
||||
/// returns the new order as positions in the old one; a position it
|
||||
/// leaves out is dropped. It runs under the queue lock, so no track
|
||||
/// starts in between: keep the handed-over track right after the playing
|
||||
/// one, or the queue jumps to wherever it went once it starts.
|
||||
pub fn reorder(&self, arrange: impl FnOnce(Option<usize>, Option<usize>) -> Vec<usize>) -> Reordered {
|
||||
let mut q = lock(&self.queue);
|
||||
let perm = arrange(q.current, q.pending);
|
||||
let moved = |i: Option<usize>| i.and_then(|i| perm.iter().position(|&p| p == i));
|
||||
q.current = moved(q.current);
|
||||
q.pending = moved(q.pending);
|
||||
q.urls = perm.iter().filter_map(|&p| q.urls.get(p).cloned()).collect();
|
||||
q.generation += 1;
|
||||
Reordered {
|
||||
current: q.current,
|
||||
pending: q.pending,
|
||||
generation: q.generation,
|
||||
perm,
|
||||
}
|
||||
}
|
||||
|
||||
/// Adds to the end of the queue, starting playback if it had stopped.
|
||||
pub fn append(&self, url: &str) {
|
||||
let start = {
|
||||
@@ -162,7 +204,12 @@ impl Player {
|
||||
/// Stops playback and forgets the queue, as when switching server. Going
|
||||
/// to Null flushes the bus, so nothing from the old track reports later.
|
||||
pub fn stop(&self) {
|
||||
*lock(&self.queue) = Queue::default();
|
||||
let mut q = lock(&self.queue);
|
||||
*q = Queue {
|
||||
generation: q.generation,
|
||||
..Queue::default()
|
||||
};
|
||||
drop(q);
|
||||
lock(&self.pictures).clear();
|
||||
let _ = self.playbin.set_state(gst::State::Null);
|
||||
}
|
||||
@@ -273,7 +320,7 @@ fn watch_pictures(playbin: &gst::Element, pictures: &Pictures) {
|
||||
|
||||
/// The track whose picture is still being looked for.
|
||||
struct ArtWait {
|
||||
index: usize,
|
||||
url: String,
|
||||
since: Instant,
|
||||
/// Already reported as without a picture; one turning up later is still sent.
|
||||
told_none: bool,
|
||||
@@ -320,12 +367,13 @@ fn watch_bus(
|
||||
let mut duration = 0.0;
|
||||
// playbin can post stream-start more than once for one track, so a repeat
|
||||
// of the last report is dropped. A track that was just started is always
|
||||
// reported, even at the same index: a new queue, or the same track again.
|
||||
let mut last_track: Option<Option<usize>> = None;
|
||||
let mut report_track = |t: Option<usize>, started: bool| {
|
||||
if started || last_track != Some(t) {
|
||||
last_track = Some(t);
|
||||
emit(PlayerEvent::Track(t));
|
||||
// reported, even the same one: a new queue, or the same track again. By
|
||||
// URL, since a reorder moves the track without restarting it.
|
||||
let mut last_track: Option<Option<String>> = None;
|
||||
let mut report_track = |index: Option<usize>, url: Option<String>, generation: u64, started: bool| {
|
||||
if started || last_track.as_ref() != Some(&url) {
|
||||
last_track = Some(url);
|
||||
emit(PlayerEvent::Track { index, generation });
|
||||
emit(PlayerEvent::Position(0.0));
|
||||
true
|
||||
} else {
|
||||
@@ -338,7 +386,7 @@ fn watch_bus(
|
||||
use gst::MessageView;
|
||||
match msg.view() {
|
||||
MessageView::StreamStart(_) => {
|
||||
let (current, started) = {
|
||||
let (current, url, generation, started) = {
|
||||
let mut q = lock(queue);
|
||||
let started = match q.pending.take() {
|
||||
Some(p) => {
|
||||
@@ -347,12 +395,13 @@ fn watch_bus(
|
||||
}
|
||||
None => false,
|
||||
};
|
||||
(q.current, started)
|
||||
let url = q.current.and_then(|i| q.urls.get(i).cloned());
|
||||
(q.current, url, q.generation, started)
|
||||
};
|
||||
duration = 0.0;
|
||||
if report_track(current, started) {
|
||||
art_wait = current.map(|index| ArtWait {
|
||||
index,
|
||||
if report_track(current, url.clone(), generation, started) {
|
||||
art_wait = url.map(|url| ArtWait {
|
||||
url,
|
||||
since: Instant::now(),
|
||||
told_none: false,
|
||||
});
|
||||
@@ -390,8 +439,9 @@ fn watch_bus(
|
||||
q.current = None;
|
||||
q.pending = None;
|
||||
}
|
||||
let generation = lock(queue).generation;
|
||||
let _ = playbin.set_state(gst::State::Ready);
|
||||
report_track(None, false);
|
||||
report_track(None, None, generation, false);
|
||||
art_wait = None;
|
||||
}
|
||||
// A failing source posts several errors. Once the first has moved
|
||||
@@ -424,8 +474,9 @@ fn watch_bus(
|
||||
start(playbin, &url);
|
||||
}
|
||||
} else {
|
||||
let generation = lock(queue).generation;
|
||||
let _ = playbin.set_state(gst::State::Ready);
|
||||
report_track(None, false);
|
||||
report_track(None, None, generation, false);
|
||||
art_wait = None;
|
||||
}
|
||||
}
|
||||
@@ -433,14 +484,32 @@ fn watch_bus(
|
||||
}
|
||||
}
|
||||
if let Some(w) = &mut art_wait {
|
||||
let url = lock(queue).urls.get(w.index).cloned();
|
||||
let picture = url.and_then(|u| lock(pictures).get(&u).cloned());
|
||||
if picture.is_some() {
|
||||
emit(PlayerEvent::Art(w.index, picture));
|
||||
art_wait = None;
|
||||
} else if !w.told_none && w.since.elapsed() >= ART_WAIT {
|
||||
w.told_none = true;
|
||||
emit(PlayerEvent::Art(w.index, None));
|
||||
// Where the track is now, since a reorder may have moved it.
|
||||
let (index, generation) = {
|
||||
let q = lock(queue);
|
||||
let index = q.current.filter(|&i| q.urls.get(i) == Some(&w.url));
|
||||
(index, q.generation)
|
||||
};
|
||||
let picture = lock(pictures).get(&w.url).cloned();
|
||||
match index {
|
||||
None => art_wait = None,
|
||||
Some(index) if picture.is_some() => {
|
||||
emit(PlayerEvent::Art {
|
||||
index,
|
||||
generation,
|
||||
picture,
|
||||
});
|
||||
art_wait = None;
|
||||
}
|
||||
Some(index) if !w.told_none && w.since.elapsed() >= ART_WAIT => {
|
||||
w.told_none = true;
|
||||
emit(PlayerEvent::Art {
|
||||
index,
|
||||
generation,
|
||||
picture: None,
|
||||
});
|
||||
}
|
||||
Some(_) => {}
|
||||
}
|
||||
}
|
||||
if last_tick.elapsed() >= TICK {
|
||||
@@ -580,8 +649,8 @@ mod tests {
|
||||
|
||||
let (tx, rx) = mpsc::channel();
|
||||
let player = Player::spawn(move |ev| {
|
||||
if let PlayerEvent::Art(i, bytes) = ev {
|
||||
let _ = tx.send((i, bytes));
|
||||
if let PlayerEvent::Art { index, picture, .. } = ev {
|
||||
let _ = tx.send((index, picture));
|
||||
}
|
||||
})
|
||||
.unwrap();
|
||||
@@ -604,8 +673,8 @@ mod tests {
|
||||
|
||||
let (tx, rx) = mpsc::channel();
|
||||
let player = Player::spawn(move |ev| {
|
||||
if let PlayerEvent::Track(t) = ev {
|
||||
let _ = tx.send(t);
|
||||
if let PlayerEvent::Track { index, .. } = ev {
|
||||
let _ = tx.send(index);
|
||||
}
|
||||
})
|
||||
.unwrap();
|
||||
@@ -635,8 +704,8 @@ mod tests {
|
||||
|
||||
let (tx, rx) = mpsc::channel();
|
||||
let player = Player::spawn(move |ev| {
|
||||
if let PlayerEvent::Track(t) = ev {
|
||||
let _ = tx.send(t);
|
||||
if let PlayerEvent::Track { index, .. } = ev {
|
||||
let _ = tx.send(index);
|
||||
}
|
||||
})
|
||||
.unwrap();
|
||||
@@ -681,7 +750,7 @@ mod tests {
|
||||
let deadline = Instant::now() + Duration::from_secs(2);
|
||||
while let Some(left) = deadline.checked_duration_since(Instant::now()) {
|
||||
match rx.recv_timeout(left) {
|
||||
Ok(PlayerEvent::Track(t)) => track = t,
|
||||
Ok(PlayerEvent::Track { index, .. }) => track = index,
|
||||
Ok(PlayerEvent::Paused(false)) => started = true,
|
||||
Ok(PlayerEvent::Position(p)) if p > 0.0 => started = true,
|
||||
Ok(_) => {}
|
||||
@@ -722,4 +791,78 @@ mod tests {
|
||||
drop(player);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_reorder_keeps_the_track_playing_and_plays_the_new_order() {
|
||||
// SAFETY: set before any thread reads the environment in this test.
|
||||
unsafe { std::env::set_var("REMUS_AUDIO_SINK", "fakesink") };
|
||||
let dir = std::env::temp_dir().join(format!("remus-player-reorder-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let urls = vec![
|
||||
silent_wav(&dir, "a.wav", 0.8),
|
||||
silent_wav(&dir, "b.wav", 0.6),
|
||||
silent_wav(&dir, "c.wav", 0.6),
|
||||
];
|
||||
|
||||
let (tx, rx) = mpsc::channel();
|
||||
let player = Player::spawn(move |ev| {
|
||||
if let PlayerEvent::Track { index, generation } = ev {
|
||||
let _ = tx.send((index, generation));
|
||||
}
|
||||
})
|
||||
.unwrap();
|
||||
player.play_list(&urls, 0);
|
||||
assert_eq!(rx.recv_timeout(Duration::from_secs(5)), Ok((Some(0), 0)));
|
||||
|
||||
let r = player.reorder(|current, pending| {
|
||||
assert_eq!((current, pending), (Some(0), None));
|
||||
vec![0, 2, 1]
|
||||
});
|
||||
assert_eq!((r.current, r.pending, r.generation), (Some(0), None, 1));
|
||||
|
||||
let mut tracks = Vec::new();
|
||||
let mut played = Vec::new();
|
||||
while let Ok((t, generation)) = rx.recv_timeout(Duration::from_secs(5)) {
|
||||
assert_eq!(generation, 1);
|
||||
tracks.push(t);
|
||||
played.extend(t.map(|i| lock(&player.queue).urls[i].clone()));
|
||||
if t.is_none() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
drop(player);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
assert_eq!(tracks, vec![Some(1), Some(2), None], "a did not start again");
|
||||
assert_eq!(played, vec![urls[2].clone(), urls[1].clone()]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_reorder_can_drop_tracks_before_the_playing_one() {
|
||||
// SAFETY: set before any thread reads the environment in this test.
|
||||
unsafe { std::env::set_var("REMUS_AUDIO_SINK", "fakesink") };
|
||||
let dir = std::env::temp_dir().join(format!("remus-player-trim-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let urls: Vec<String> = ["a", "b", "c"]
|
||||
.iter()
|
||||
.map(|n| silent_wav(&dir, &format!("{n}.wav"), 10.0))
|
||||
.collect();
|
||||
|
||||
let (tx, rx) = mpsc::channel();
|
||||
let player = Player::spawn(move |ev| {
|
||||
if let PlayerEvent::Track { index, .. } = ev {
|
||||
let _ = tx.send(index);
|
||||
}
|
||||
})
|
||||
.unwrap();
|
||||
player.play_list(&urls, 1);
|
||||
assert_eq!(rx.recv_timeout(Duration::from_secs(3)), Ok(Some(1)));
|
||||
let r = player.reorder(|_, _| vec![1, 2]);
|
||||
assert_eq!(r.current, Some(0));
|
||||
player.next();
|
||||
assert_eq!(rx.recv_timeout(Duration::from_secs(3)), Ok(Some(1)));
|
||||
assert_eq!(lock(&player.queue).urls, urls[1..]);
|
||||
|
||||
drop(player);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
}
|
||||
|
||||
+18
-1
@@ -35,6 +35,11 @@ pub enum Control {
|
||||
Seek,
|
||||
Volume,
|
||||
Mute,
|
||||
/// Cycles the shuffle mode on now playing: the queue button on a
|
||||
/// controller, a key of its own on the keyboard.
|
||||
Shuffle,
|
||||
/// Shuffle play on a row: a long press of activate on a controller.
|
||||
ShufflePlay,
|
||||
/// Steam + X brings up Steam's on-screen keyboard. Nothing to show for a
|
||||
/// real keyboard.
|
||||
OnScreenKeyboard,
|
||||
@@ -42,7 +47,7 @@ pub enum Control {
|
||||
|
||||
#[cfg(test)]
|
||||
impl Control {
|
||||
pub const ALL: [Control; 12] = [
|
||||
pub const ALL: [Control; 14] = [
|
||||
Control::Activate,
|
||||
Control::Back,
|
||||
Control::PlayPause,
|
||||
@@ -54,6 +59,8 @@ impl Control {
|
||||
Control::Seek,
|
||||
Control::Volume,
|
||||
Control::Mute,
|
||||
Control::Shuffle,
|
||||
Control::ShufflePlay,
|
||||
Control::OnScreenKeyboard,
|
||||
];
|
||||
}
|
||||
@@ -81,13 +88,17 @@ pub fn icons(prompts: Prompts, control: Control) -> &'static [&'static [u8]] {
|
||||
Seek => &[icon!("keyboard", "keyboard_arrows_horizontal")],
|
||||
Volume => &[icon!("keyboard", "keyboard_minus"), icon!("keyboard", "keyboard_plus")],
|
||||
Mute => &[icon!("keyboard", "keyboard_m")],
|
||||
Shuffle => &[icon!("keyboard", "keyboard_s")],
|
||||
ShufflePlay => &[icon!("keyboard", "keyboard_shift"), icon!("keyboard", "keyboard_s")],
|
||||
OnScreenKeyboard => &[],
|
||||
},
|
||||
Prompts::Pad(Family::Xbox) => match control {
|
||||
Activate => &[icon!("xbox", "xbox_button_color_a")],
|
||||
ShufflePlay => &[icon!("xbox", "xbox_button_color_a")],
|
||||
Back => &[icon!("xbox", "xbox_button_color_b")],
|
||||
PlayPause => &[icon!("xbox", "xbox_button_color_x")],
|
||||
Queue => &[icon!("xbox", "xbox_button_color_y")],
|
||||
Shuffle => &[icon!("xbox", "xbox_button_color_y")],
|
||||
Skip => &[icon!("xbox", "xbox_lb"), icon!("xbox", "xbox_rb")],
|
||||
Sections => &[icon!("xbox", "xbox_lt"), icon!("xbox", "xbox_rt")],
|
||||
Search => &[icon!("xbox", "xbox_button_view")],
|
||||
@@ -99,9 +110,11 @@ pub fn icons(prompts: Prompts, control: Control) -> &'static [&'static [u8]] {
|
||||
},
|
||||
Prompts::Pad(Family::PlayStation) => match control {
|
||||
Activate => &[icon!("playstation", "playstation_button_color_cross")],
|
||||
ShufflePlay => &[icon!("playstation", "playstation_button_color_cross")],
|
||||
Back => &[icon!("playstation", "playstation_button_color_circle")],
|
||||
PlayPause => &[icon!("playstation", "playstation_button_color_square")],
|
||||
Queue => &[icon!("playstation", "playstation_button_color_triangle")],
|
||||
Shuffle => &[icon!("playstation", "playstation_button_color_triangle")],
|
||||
Skip => &[
|
||||
icon!("playstation", "playstation_trigger_l1"),
|
||||
icon!("playstation", "playstation_trigger_r1"),
|
||||
@@ -124,9 +137,11 @@ pub fn icons(prompts: Prompts, control: Control) -> &'static [&'static [u8]] {
|
||||
// By position, as gilrs reports buttons: the bottom face button is B on a Switch.
|
||||
Prompts::Pad(Family::Switch) => match control {
|
||||
Activate => &[icon!("switch", "switch_button_b")],
|
||||
ShufflePlay => &[icon!("switch", "switch_button_b")],
|
||||
Back => &[icon!("switch", "switch_button_a")],
|
||||
PlayPause => &[icon!("switch", "switch_button_y")],
|
||||
Queue => &[icon!("switch", "switch_button_x")],
|
||||
Shuffle => &[icon!("switch", "switch_button_x")],
|
||||
Skip => &[icon!("switch", "switch_button_l"), icon!("switch", "switch_button_r")],
|
||||
Sections => &[icon!("switch", "switch_button_zl"), icon!("switch", "switch_button_zr")],
|
||||
Search => &[icon!("switch", "switch_button_minus")],
|
||||
@@ -141,9 +156,11 @@ pub fn icons(prompts: Prompts, control: Control) -> &'static [&'static [u8]] {
|
||||
},
|
||||
Prompts::Pad(Family::SteamDeck) => match control {
|
||||
Activate => &[icon!("steamdeck", "steamdeck_button_a")],
|
||||
ShufflePlay => &[icon!("steamdeck", "steamdeck_button_a")],
|
||||
Back => &[icon!("steamdeck", "steamdeck_button_b")],
|
||||
PlayPause => &[icon!("steamdeck", "steamdeck_button_x")],
|
||||
Queue => &[icon!("steamdeck", "steamdeck_button_y")],
|
||||
Shuffle => &[icon!("steamdeck", "steamdeck_button_y")],
|
||||
Skip => &[
|
||||
icon!("steamdeck", "steamdeck_button_l1"),
|
||||
icon!("steamdeck", "steamdeck_button_r1"),
|
||||
|
||||
@@ -12,13 +12,23 @@ use anyhow::Result;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::config;
|
||||
use crate::shuffle::{Library, Mode};
|
||||
use crate::subsonic::{Client, Song};
|
||||
|
||||
const VERSION: u32 = 1;
|
||||
|
||||
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
|
||||
pub struct SavedQueue {
|
||||
/// In the order they play.
|
||||
pub songs: Vec<Song>,
|
||||
/// Each song's position in the order it was queued. Empty in files from
|
||||
/// before shuffle, which were saved in that order.
|
||||
#[serde(default)]
|
||||
pub order: Vec<usize>,
|
||||
#[serde(default)]
|
||||
pub shuffle: Mode,
|
||||
#[serde(default)]
|
||||
pub library: Option<Library>,
|
||||
pub current: Option<usize>,
|
||||
/// Seconds into the current song.
|
||||
pub position: f64,
|
||||
@@ -121,6 +131,9 @@ mod tests {
|
||||
let mut queues = SavedQueues::default();
|
||||
let a = SavedQueue {
|
||||
songs: vec![song("1"), song("2")],
|
||||
order: vec![1, 0],
|
||||
shuffle: Mode::Tracks,
|
||||
library: Some(Library { added_end: 1 }),
|
||||
current: Some(1),
|
||||
position: 93.5,
|
||||
};
|
||||
@@ -128,6 +141,7 @@ mod tests {
|
||||
songs: vec![song("9")],
|
||||
current: None,
|
||||
position: 0.0,
|
||||
..SavedQueue::default()
|
||||
};
|
||||
queues.set(&home, a.clone());
|
||||
queues.set(&other, b.clone());
|
||||
@@ -142,6 +156,23 @@ mod tests {
|
||||
let _ = fs::remove_dir_all(path.parent().unwrap());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_queue_saved_before_shuffle_loads_unshuffled() {
|
||||
let path = temp("before-shuffle");
|
||||
fs::create_dir_all(path.parent().unwrap()).unwrap();
|
||||
let client = Client::new("https://h", "u", Auth::Password("p".into()));
|
||||
let text = r#"{"version": 1, "servers": {"u@https://h": {
|
||||
"songs": [{"id": "1", "title": "One"}], "current": 0, "position": 12.0}}}"#;
|
||||
fs::write(&path, text).unwrap();
|
||||
let q = load(&path).get(&client).cloned().expect("the queue");
|
||||
assert_eq!(
|
||||
(q.songs.len(), q.order, q.shuffle, q.library),
|
||||
(1, vec![], Mode::Off, None)
|
||||
);
|
||||
assert_eq!(q.songs[0].album_id, None);
|
||||
let _ = fs::remove_dir_all(path.parent().unwrap());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unreadable_file_loads_as_empty() {
|
||||
let path = temp("unreadable");
|
||||
|
||||
+348
@@ -0,0 +1,348 @@
|
||||
//! Shuffled play orders. Every function returns a permutation: positions into
|
||||
//! the queue as it plays now, in the order it should play next. The caller
|
||||
//! applies the same permutation to the songs, to their original positions and
|
||||
//! to the player's URLs, so the three never disagree.
|
||||
//!
|
||||
//! `fixed` is how many tracks at the head of the queue stay where they are:
|
||||
//! those played, the one playing and one already handed to playbin.
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
use fastrand::Rng;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::subsonic::Song;
|
||||
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum Mode {
|
||||
#[default]
|
||||
Off,
|
||||
Tracks,
|
||||
Albums,
|
||||
}
|
||||
|
||||
impl Mode {
|
||||
pub fn next(self) -> Mode {
|
||||
match self {
|
||||
Mode::Off => Mode::Tracks,
|
||||
Mode::Tracks => Mode::Albums,
|
||||
Mode::Albums => Mode::Off,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Library shuffle: the queue is topped up with random tracks from the
|
||||
/// server as it runs low.
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct Library {
|
||||
/// Where the random tracks carry on after those queued by hand, which go
|
||||
/// after the playing track and after any queued before them.
|
||||
pub added_end: usize,
|
||||
}
|
||||
|
||||
/// Which album a song belongs to. The album name alone would merge different
|
||||
/// albums of the same title, so it is only the fallback for songs saved
|
||||
/// without an album id. A song with neither is an album of its own.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
|
||||
enum AlbumKey<'a> {
|
||||
Id(&'a str),
|
||||
Name(&'a str, Option<&'a str>),
|
||||
Alone(usize),
|
||||
}
|
||||
|
||||
fn album_key(song: &Song, pos: usize) -> AlbumKey<'_> {
|
||||
match (&song.album_id, &song.album) {
|
||||
(Some(id), _) => AlbumKey::Id(id),
|
||||
(None, Some(name)) if !name.is_empty() => AlbumKey::Name(name, song.artist.as_deref()),
|
||||
_ => AlbumKey::Alone(pos),
|
||||
}
|
||||
}
|
||||
|
||||
/// Keeps the first `fixed` tracks and shuffles the rest.
|
||||
pub fn tracks(rng: &mut Rng, len: usize, fixed: usize) -> Vec<usize> {
|
||||
let fixed = fixed.min(len);
|
||||
let mut perm: Vec<usize> = (0..len).collect();
|
||||
rng.shuffle(&mut perm[fixed..]);
|
||||
perm
|
||||
}
|
||||
|
||||
/// Keeps the first `fixed` tracks, then plays the rest of the playing track's
|
||||
/// album, then the other albums in random order. Each album plays in disc and
|
||||
/// track order, and tracks without numbers keep their original order.
|
||||
/// `original` holds each track's position in the original order.
|
||||
pub fn albums(rng: &mut Rng, songs: &[Song], original: &[usize], playing: Option<usize>, fixed: usize) -> Vec<usize> {
|
||||
let fixed = fixed.min(songs.len());
|
||||
let mut groups = album_groups(songs, original, fixed..songs.len());
|
||||
let first = playing
|
||||
.and_then(|p| songs.get(p).map(|s| album_key(s, p)))
|
||||
.and_then(|key| groups.iter().position(|(k, _)| *k == key))
|
||||
.map(|i| groups.remove(i));
|
||||
rng.shuffle(&mut groups);
|
||||
(0..fixed)
|
||||
.chain(first.into_iter().chain(groups).flat_map(|(_, g)| g))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The tracks in `range` grouped by album, in the order each album first
|
||||
/// appears, each sorted by disc and track.
|
||||
fn album_groups<'a>(
|
||||
songs: &'a [Song],
|
||||
original: &[usize],
|
||||
range: std::ops::Range<usize>,
|
||||
) -> Vec<(AlbumKey<'a>, Vec<usize>)> {
|
||||
let mut groups: Vec<(AlbumKey<'a>, Vec<usize>)> = Vec::new();
|
||||
let mut index: HashMap<AlbumKey<'a>, usize> = HashMap::new();
|
||||
for pos in range {
|
||||
let key = album_key(&songs[pos], pos);
|
||||
let i = *index.entry(key.clone()).or_insert_with(|| {
|
||||
groups.push((key, Vec::new()));
|
||||
groups.len() - 1
|
||||
});
|
||||
groups[i].1.push(pos);
|
||||
}
|
||||
for (_, g) in &mut groups {
|
||||
g.sort_by_key(|&p| {
|
||||
let s = &songs[p];
|
||||
(
|
||||
s.disc_number.unwrap_or(0),
|
||||
s.track.unwrap_or(0),
|
||||
original.get(p).copied().unwrap_or(p),
|
||||
)
|
||||
});
|
||||
}
|
||||
groups
|
||||
}
|
||||
|
||||
/// Places the tracks from `added` on (just appended to the queue) at random
|
||||
/// positions after the first `fixed`. Under album shuffle each added album
|
||||
/// goes in as one block, and only between albums, never inside one.
|
||||
pub fn insert(rng: &mut Rng, mode: Mode, songs: &[Song], original: &[usize], fixed: usize, added: usize) -> Vec<usize> {
|
||||
let added = added.min(songs.len());
|
||||
let fixed = fixed.min(added);
|
||||
let mut tail: Vec<usize> = (fixed..added).collect();
|
||||
if mode == Mode::Albums {
|
||||
let mut blocks: Vec<Vec<usize>> = Vec::new();
|
||||
for pos in tail {
|
||||
let key = album_key(&songs[pos], pos);
|
||||
match blocks.last_mut() {
|
||||
Some(b) if album_key(&songs[b[0]], b[0]) == key => b.push(pos),
|
||||
_ => blocks.push(vec![pos]),
|
||||
}
|
||||
}
|
||||
// The rest of the album playing now still plays first.
|
||||
let lo = match (fixed.checked_sub(1), blocks.first()) {
|
||||
(Some(last), Some(b)) if album_key(&songs[last], last) == album_key(&songs[b[0]], b[0]) => 1,
|
||||
_ => 0,
|
||||
};
|
||||
for (_, g) in album_groups(songs, original, added..songs.len()) {
|
||||
let at = rng.usize(lo..=blocks.len());
|
||||
blocks.insert(at, g);
|
||||
}
|
||||
tail = blocks.concat();
|
||||
} else {
|
||||
for pos in added..songs.len() {
|
||||
let at = rng.usize(..=tail.len());
|
||||
tail.insert(at, pos);
|
||||
}
|
||||
}
|
||||
(0..fixed).chain(tail).collect()
|
||||
}
|
||||
|
||||
/// Back to the original order, given each track's original position. A
|
||||
/// `pinned` track (handed to playbin already) is moved to play right after
|
||||
/// `playing`, so the track that plays next is the one the player expects.
|
||||
pub fn unshuffle(original: &[usize], playing: Option<usize>, pinned: Option<usize>) -> Vec<usize> {
|
||||
let mut perm: Vec<usize> = (0..original.len()).collect();
|
||||
perm.sort_by_key(|&p| original[p]);
|
||||
if let (Some(playing), Some(pinned)) = (playing, pinned)
|
||||
&& playing != pinned
|
||||
&& let Some(from) = perm.iter().position(|&p| p == pinned)
|
||||
{
|
||||
perm.remove(from);
|
||||
let at = perm.iter().position(|&p| p == playing).map_or(perm.len(), |i| i + 1);
|
||||
perm.insert(at, pinned);
|
||||
}
|
||||
perm
|
||||
}
|
||||
|
||||
/// `items` reordered by `perm`.
|
||||
pub fn apply<T: Clone>(items: &[T], perm: &[usize]) -> Vec<T> {
|
||||
perm.iter().map(|&p| items[p].clone()).collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn song(id: &str, album: Option<&str>, track: u32) -> Song {
|
||||
serde_json::from_value(serde_json::json!({
|
||||
"id": id, "title": id, "album": album.map(|a| format!("Album {a}")),
|
||||
"albumId": album, "artist": "A", "track": track,
|
||||
}))
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
fn is_permutation(perm: &[usize], len: usize) -> bool {
|
||||
let mut sorted = perm.to_vec();
|
||||
sorted.sort();
|
||||
sorted == (0..len).collect::<Vec<_>>()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tracks_keeps_the_fixed_head_and_plays_the_rest_once() {
|
||||
let mut rng = Rng::with_seed(1);
|
||||
for fixed in [0, 1, 3, 10, 12] {
|
||||
let perm = tracks(&mut rng, 10, fixed);
|
||||
assert!(is_permutation(&perm, 10));
|
||||
let fixed = fixed.min(10);
|
||||
assert_eq!(perm[..fixed], (0..fixed).collect::<Vec<_>>()[..]);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tracks_actually_shuffles() {
|
||||
let mut rng = Rng::with_seed(7);
|
||||
let perm = tracks(&mut rng, 50, 1);
|
||||
assert_ne!(perm, (0..50).collect::<Vec<_>>());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn albums_finish_the_playing_album_then_play_whole_albums_in_track_order() {
|
||||
// Track shuffled already: b2, a1, b1 | a2, c1, b3, a3, c2.
|
||||
let songs = vec![
|
||||
song("b2", Some("b"), 2),
|
||||
song("a1", Some("a"), 1),
|
||||
song("b1", Some("b"), 1),
|
||||
song("a2", Some("a"), 2),
|
||||
song("c2", Some("c"), 2),
|
||||
song("b3", Some("b"), 3),
|
||||
song("a3", Some("a"), 3),
|
||||
song("c1", Some("c"), 1),
|
||||
];
|
||||
let original: Vec<usize> = (0..songs.len()).collect();
|
||||
for seed in 0..20 {
|
||||
let mut rng = Rng::with_seed(seed);
|
||||
let perm = albums(&mut rng, &songs, &original, Some(0), 3);
|
||||
assert!(is_permutation(&perm, songs.len()));
|
||||
let ids: Vec<&str> = perm.iter().map(|&p| songs[p].id.as_str()).collect();
|
||||
assert_eq!(ids[..3], ["b2", "a1", "b1"]);
|
||||
assert_eq!(ids[3], "b3", "the playing album goes on first");
|
||||
let rest = &ids[4..];
|
||||
assert!(
|
||||
rest == ["a2", "a3", "c1", "c2"] || rest == ["c1", "c2", "a2", "a3"],
|
||||
"seed {seed}: {rest:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn albums_with_the_same_name_stay_apart_and_saved_songs_fall_back_to_the_name() {
|
||||
let mut same_name = song("x1", Some("x"), 1);
|
||||
same_name.album = Some("Album y".into());
|
||||
let mut saved = song("y2", None, 2);
|
||||
saved.album = Some("Album y".into());
|
||||
let mut saved1 = song("y1", None, 1);
|
||||
saved1.album = Some("Album y".into());
|
||||
let songs = vec![song("p", Some("p"), 1), saved, same_name, saved1];
|
||||
let original: Vec<usize> = (0..songs.len()).collect();
|
||||
let mut rng = Rng::with_seed(3);
|
||||
let perm = albums(&mut rng, &songs, &original, Some(0), 1);
|
||||
let ids: Vec<&str> = perm.iter().map(|&p| songs[p].id.as_str()).collect();
|
||||
let y = ids.iter().position(|&i| i == "y1").unwrap();
|
||||
assert_eq!(ids[y + 1], "y2", "{ids:?}");
|
||||
assert!(ids.contains(&"x1"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tracks_without_numbers_keep_their_original_order() {
|
||||
let mut songs: Vec<Song> = ["a", "b", "c"].iter().map(|id| song(id, Some("al"), 0)).collect();
|
||||
for s in &mut songs {
|
||||
s.track = None;
|
||||
}
|
||||
// Played as c, a, b; originally a, b, c.
|
||||
let songs = vec![songs[2].clone(), songs[0].clone(), songs[1].clone()];
|
||||
let original = vec![2, 0, 1];
|
||||
let mut rng = Rng::with_seed(0);
|
||||
let perm = albums(&mut rng, &songs, &original, None, 0);
|
||||
let ids: Vec<&str> = perm.iter().map(|&p| songs[p].id.as_str()).collect();
|
||||
assert_eq!(ids, ["a", "b", "c"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn insert_scatters_added_tracks_after_the_fixed_head() {
|
||||
let songs: Vec<Song> = (0..20).map(|i| song(&i.to_string(), None, 0)).collect();
|
||||
let original: Vec<usize> = (0..20).collect();
|
||||
let mut rng = Rng::with_seed(5);
|
||||
let perm = insert(&mut rng, Mode::Tracks, &songs, &original, 2, 15);
|
||||
assert!(is_permutation(&perm, 20));
|
||||
assert_eq!(perm[..2], [0, 1]);
|
||||
let old: Vec<usize> = perm.iter().copied().filter(|&p| p < 15).collect();
|
||||
assert_eq!(old, (0..15).collect::<Vec<_>>(), "the queued tracks keep their order");
|
||||
assert_ne!(perm[15..], [15, 16, 17, 18, 19], "added tracks are not all at the end");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn insert_under_album_shuffle_adds_whole_albums_between_albums() {
|
||||
let songs = vec![
|
||||
song("p1", Some("p"), 1),
|
||||
song("q1", Some("q"), 1),
|
||||
song("q2", Some("q"), 2),
|
||||
song("r1", Some("r"), 1),
|
||||
song("r2", Some("r"), 2),
|
||||
song("n2", Some("n"), 2),
|
||||
song("n1", Some("n"), 1),
|
||||
];
|
||||
let original: Vec<usize> = (0..songs.len()).collect();
|
||||
for seed in 0..20 {
|
||||
let mut rng = Rng::with_seed(seed);
|
||||
let perm = insert(&mut rng, Mode::Albums, &songs, &original, 1, 5);
|
||||
let ids: Vec<&str> = perm.iter().map(|&p| songs[p].id.as_str()).collect();
|
||||
let n = ids.iter().position(|&i| i == "n1").unwrap();
|
||||
assert_eq!(ids[n + 1], "n2", "seed {seed}: {ids:?}");
|
||||
assert!(
|
||||
n >= 1 && ids[n - 1] != "q1" && ids[n - 1] != "r1",
|
||||
"seed {seed}: {ids:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn insert_under_album_shuffle_leaves_the_playing_album_first() {
|
||||
let songs = vec![
|
||||
song("p1", Some("p"), 1),
|
||||
song("p2", Some("p"), 2),
|
||||
song("q1", Some("q"), 1),
|
||||
song("n1", Some("n"), 1),
|
||||
];
|
||||
let original: Vec<usize> = (0..songs.len()).collect();
|
||||
for seed in 0..20 {
|
||||
let mut rng = Rng::with_seed(seed);
|
||||
let perm = insert(&mut rng, Mode::Albums, &songs, &original, 1, 3);
|
||||
assert_eq!(perm[1], 1, "seed {seed}: {perm:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unshuffle_restores_the_original_order() {
|
||||
let original = vec![3, 0, 4, 1, 2];
|
||||
let perm = unshuffle(&original, Some(0), None);
|
||||
assert_eq!(apply(&original, &perm), [0, 1, 2, 3, 4]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unshuffle_plays_the_pinned_track_next() {
|
||||
// Playing original 3, playbin already has original 0.
|
||||
let original = vec![1, 3, 0, 4, 2];
|
||||
let perm = unshuffle(&original, Some(1), Some(2));
|
||||
assert_eq!(apply(&original, &perm), [1, 2, 3, 0, 4]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn modes_cycle_off_tracks_albums() {
|
||||
assert_eq!(Mode::Off.next(), Mode::Tracks);
|
||||
assert_eq!(Mode::Tracks.next(), Mode::Albums);
|
||||
assert_eq!(Mode::Albums.next(), Mode::Off);
|
||||
}
|
||||
}
|
||||
+100
@@ -212,6 +212,28 @@ impl Client {
|
||||
Ok(r.artist)
|
||||
}
|
||||
|
||||
/// Every song on the artist's albums, album by album. A few albums are
|
||||
/// fetched at a time, so an artist with dozens does not flood the server.
|
||||
pub async fn artist_songs(&self, id: &str) -> Result<Vec<Song>> {
|
||||
let albums = self.artist(id).await?.album;
|
||||
let limit = std::sync::Arc::new(tokio::sync::Semaphore::new(4));
|
||||
let tasks: Vec<_> = albums
|
||||
.into_iter()
|
||||
.map(|a| {
|
||||
let (client, limit) = (self.clone(), limit.clone());
|
||||
tokio::spawn(async move {
|
||||
let _permit = limit.acquire_owned().await?;
|
||||
anyhow::Ok(client.album(&a.id).await?.song)
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
let mut songs = Vec::new();
|
||||
for t in tasks {
|
||||
songs.extend(t.await??);
|
||||
}
|
||||
Ok(songs)
|
||||
}
|
||||
|
||||
pub async fn album(&self, id: &str) -> Result<AlbumDetail> {
|
||||
#[derive(Deserialize)]
|
||||
struct R {
|
||||
@@ -265,6 +287,23 @@ impl Client {
|
||||
Ok(r.result)
|
||||
}
|
||||
|
||||
/// Up to `size` random songs from the whole library. Servers cap `size`
|
||||
/// at 500.
|
||||
pub async fn random_songs(&self, size: u32) -> Result<Vec<Song>> {
|
||||
#[derive(Deserialize)]
|
||||
struct R {
|
||||
#[serde(rename = "randomSongs", default)]
|
||||
list: Songs,
|
||||
}
|
||||
#[derive(Deserialize, Default)]
|
||||
struct Songs {
|
||||
#[serde(default)]
|
||||
song: Vec<Song>,
|
||||
}
|
||||
let r: R = self.call("getRandomSongs", &[("size", size.to_string())]).await?;
|
||||
Ok(r.list.song)
|
||||
}
|
||||
|
||||
pub async fn scrobble(&self, id: &str, submission: bool) -> Result<()> {
|
||||
let _: serde_json::Value = self
|
||||
.call("scrobble", &[("id", id.into()), ("submission", submission.to_string())])
|
||||
@@ -426,6 +465,9 @@ pub struct Song {
|
||||
pub artist: Option<String>,
|
||||
#[serde(default)]
|
||||
pub album: Option<String>,
|
||||
/// None in queues saved before it was kept, and from servers that leave it out.
|
||||
#[serde(default, deserialize_with = "de_opt_id")]
|
||||
pub album_id: Option<String>,
|
||||
#[serde(default, deserialize_with = "de_opt_id")]
|
||||
pub cover_art: Option<String>,
|
||||
#[serde(default)]
|
||||
@@ -489,6 +531,56 @@ mod tests {
|
||||
let a: Album = serde_json::from_str(r#"{"id": 42, "name": "X", "coverArt": 7}"#).unwrap();
|
||||
assert_eq!(a.id, "42");
|
||||
assert_eq!(a.cover_art.as_deref(), Some("7"));
|
||||
let s: Song = serde_json::from_str(r#"{"id": 1, "albumId": 42}"#).unwrap();
|
||||
assert_eq!(s.album_id.as_deref(), Some("42"));
|
||||
let s: Song = serde_json::from_str(r#"{"id": 1}"#).unwrap();
|
||||
assert_eq!(s.album_id, None);
|
||||
}
|
||||
|
||||
/// A loopback HTTP server that answers every request with `body` and
|
||||
/// sends each request line back.
|
||||
fn fake_server(body: &'static str) -> (String, std::sync::mpsc::Receiver<String>) {
|
||||
use std::io::{BufRead, BufReader, Write};
|
||||
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
let addr = listener.local_addr().unwrap();
|
||||
let (tx, rx) = std::sync::mpsc::channel();
|
||||
std::thread::spawn(move || {
|
||||
for stream in listener.incoming() {
|
||||
let Ok(mut stream) = stream else { continue };
|
||||
let mut line = String::new();
|
||||
let _ = BufReader::new(stream.try_clone().unwrap()).read_line(&mut line);
|
||||
let _ = tx.send(line);
|
||||
let _ = write!(
|
||||
stream,
|
||||
"HTTP/1.1 200 OK\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{body}",
|
||||
body.len()
|
||||
);
|
||||
}
|
||||
});
|
||||
(format!("http://{addr}"), rx)
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn random_songs_asks_for_the_size_and_reads_the_songs() {
|
||||
let (base, requests) = fake_server(
|
||||
r#"{"subsonic-response":{"status":"ok","randomSongs":{"song":[
|
||||
{"id":"s1","title":"One","albumId":"al-1"},{"id":"s2","title":"Two"}]}}}"#,
|
||||
);
|
||||
let c = Client::new(&base, "u", Auth::Password("sesame".into()));
|
||||
let songs = c.random_songs(50).await.unwrap();
|
||||
let ids: Vec<_> = songs.iter().map(|s| s.id.as_str()).collect();
|
||||
assert_eq!(ids, ["s1", "s2"]);
|
||||
assert_eq!(songs[0].album_id.as_deref(), Some("al-1"));
|
||||
let line = requests.recv().unwrap();
|
||||
assert!(line.contains("/rest/getRandomSongs?"), "{line}");
|
||||
assert!(line.contains("size=50"), "{line}");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn random_songs_from_an_empty_library_is_empty() {
|
||||
let (base, _) = fake_server(r#"{"subsonic-response":{"status":"ok","randomSongs":{}}}"#);
|
||||
let c = Client::new(&base, "u", Auth::Password("sesame".into()));
|
||||
assert!(c.random_songs(50).await.unwrap().is_empty());
|
||||
}
|
||||
|
||||
/// Exercises every endpoint against a real server:
|
||||
@@ -514,6 +606,7 @@ mod tests {
|
||||
assert!(!albums.is_empty(), "no albums");
|
||||
let album = c.album(&albums[0].id).await.unwrap();
|
||||
assert!(!album.song.is_empty(), "album has no songs");
|
||||
assert_eq!(album.song[0].album_id.as_deref(), Some(albums[0].id.as_str()));
|
||||
println!(
|
||||
"album: {} by {:?}, {} songs",
|
||||
album.name,
|
||||
@@ -530,6 +623,9 @@ mod tests {
|
||||
assert!(!artists.is_empty(), "no artists");
|
||||
let artist = c.artist(&artists[0].id).await.unwrap();
|
||||
println!("artist: {} with {} albums", artist.name, artist.album.len());
|
||||
let songs = c.artist_songs(&artists[0].id).await.unwrap();
|
||||
assert!(!songs.is_empty(), "artist has no songs");
|
||||
println!("artist songs: {}", songs.len());
|
||||
|
||||
let playlists = c.playlists().await.unwrap();
|
||||
if let Some(p) = playlists.first() {
|
||||
@@ -537,6 +633,10 @@ mod tests {
|
||||
println!("playlist: {} with {} entries", p.name, p.entry.len());
|
||||
}
|
||||
|
||||
let random = c.random_songs(20).await.unwrap();
|
||||
assert!(!random.is_empty(), "no random songs");
|
||||
println!("random: {} songs", random.len());
|
||||
|
||||
let found = c.search(&album.name).await.unwrap();
|
||||
assert!(!found.album.is_empty(), "search found nothing for {}", album.name);
|
||||
|
||||
|
||||
+27
-8
@@ -9,7 +9,7 @@ export enum Action {
|
||||
none, up, down, left, right, page-up, page-down, activate, back,
|
||||
play-pause, next, prev, queue, section-next, section-prev,
|
||||
now-playing, search, seek-forward, seek-back, toggle-fullscreen, quit,
|
||||
volume-up, volume-down, toggle-mute,
|
||||
volume-up, volume-down, toggle-mute, cycle-shuffle, shuffle, hold-activate,
|
||||
}
|
||||
|
||||
export enum Screen { login, browse, now-playing }
|
||||
@@ -213,8 +213,10 @@ component Row inherits Rectangle {
|
||||
round: root.item.round;
|
||||
}
|
||||
}
|
||||
// As wide as the art, so a row with a cover and a row with a number
|
||||
// line up, as on an album where some tracks have their own cover.
|
||||
if !root.item.show-art: Text {
|
||||
width: 34px * Theme.s;
|
||||
width: 46px * Theme.s;
|
||||
text: root.item.playing ? "▶" : root.item.number;
|
||||
font-size: 15px * Theme.s;
|
||||
color: root.item.playing ? Theme.highlight : Theme.faint;
|
||||
@@ -1021,6 +1023,8 @@ component NowPlayingView inherits Rectangle {
|
||||
in property <[Item]> queue;
|
||||
in property <int> queue-count;
|
||||
in property <int> queue-selected;
|
||||
// How the queue is shuffled, empty when it plays in order.
|
||||
in property <string> shuffle;
|
||||
callback queue-clicked(int);
|
||||
callback queue-wheel(int);
|
||||
// From the scale, not our own size: a layout child sized from its parent loops.
|
||||
@@ -1132,12 +1136,23 @@ component NowPlayingView inherits Rectangle {
|
||||
VerticalLayout {
|
||||
spacing: 14px * Theme.s;
|
||||
horizontal-stretch: 1;
|
||||
Text {
|
||||
text: "Queue";
|
||||
font-size: 28px * Theme.s;
|
||||
font-family: Theme.serif;
|
||||
font-weight: 600;
|
||||
color: Theme.text;
|
||||
HorizontalLayout {
|
||||
spacing: 16px * Theme.s;
|
||||
Text {
|
||||
text: "Queue";
|
||||
font-size: 28px * Theme.s;
|
||||
font-family: Theme.serif;
|
||||
font-weight: 600;
|
||||
color: Theme.text;
|
||||
}
|
||||
Text {
|
||||
horizontal-stretch: 1;
|
||||
text: root.shuffle;
|
||||
font-size: 16px * Theme.s;
|
||||
color: Theme.muted;
|
||||
vertical-alignment: center;
|
||||
overflow: elide;
|
||||
}
|
||||
}
|
||||
ItemView {
|
||||
vertical-stretch: 1;
|
||||
@@ -1230,6 +1245,7 @@ export component AppWindow inherits Window {
|
||||
in property <string> np-position;
|
||||
in property <string> np-duration;
|
||||
in property <bool> np-paused;
|
||||
in property <string> np-shuffle;
|
||||
in property <bool> np-flip-out;
|
||||
in property <float> np-backdrop-opacity: 0.16;
|
||||
in property <float> np-backdrop-left: 0.67;
|
||||
@@ -1303,6 +1319,8 @@ export component AppWindow inherits Window {
|
||||
if (e.text == "+" || e.text == "=") { root.action(Action.volume-up); return accept; }
|
||||
if (e.text == "-") { root.action(Action.volume-down); return accept; }
|
||||
if (e.text == "m") { root.action(Action.toggle-mute); return accept; }
|
||||
if (e.text == "s") { root.action(Action.cycle-shuffle); return accept; }
|
||||
if (e.text == "S") { root.action(Action.shuffle); return accept; }
|
||||
reject
|
||||
}
|
||||
|
||||
@@ -1415,6 +1433,7 @@ export component AppWindow inherits Window {
|
||||
queue: root.queue-items;
|
||||
queue-count: root.queue-count;
|
||||
queue-selected: root.queue-selected;
|
||||
shuffle: root.np-shuffle;
|
||||
queue-clicked(i) => { root.queue-clicked(i); }
|
||||
queue-wheel(d) => { root.queue-wheel(d); }
|
||||
}
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
<svg width="64" height="64" xmlns="http://www.w3.org/2000/svg">
|
||||
<defs>
|
||||
<mask id="letter">
|
||||
<rect width="64" height="64" fill="#FFFFFF"/>
|
||||
<path fill="none" stroke="#000000" stroke-width="4" stroke-linecap="square" d="M38 25.5 Q36.5 24 32 24 Q26 24 26 28 Q26 32 32 32 Q38 32 38 36 Q38 40 32 40 Q27.5 40 26 38.5"/>
|
||||
</mask>
|
||||
</defs>
|
||||
<path stroke="none" fill="#FFFFFF" mask="url(#letter)" d="M16 8 L48 8 Q56 8 56 16 L56 48 Q56 56 48 56 L16 56 Q8 56 8 48 L8 16 Q8 8 16 8"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 499 B |
@@ -0,0 +1,9 @@
|
||||
<svg width="64" height="64" xmlns="http://www.w3.org/2000/svg">
|
||||
<defs>
|
||||
<mask id="glyph">
|
||||
<rect width="64" height="64" fill="#FFFFFF"/>
|
||||
<path fill="none" stroke="#000000" stroke-width="3.5" stroke-linejoin="round" d="M32 21 L42 32 L36.5 32 L36.5 42 L27.5 42 L27.5 32 L22 32 Z"/>
|
||||
</mask>
|
||||
</defs>
|
||||
<path stroke="none" fill="#FFFFFF" mask="url(#glyph)" d="M16 8 L48 8 Q56 8 56 16 L56 48 Q56 56 48 56 L16 56 Q8 56 8 48 L8 16 Q8 8 16 8"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 465 B |
Reference in New Issue
Block a user