diff --git a/src/app.rs b/src/app.rs index a7fbc51..fed4903 100644 --- a/src/app.rs +++ b/src/app.rs @@ -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, Mode}; use crate::subsonic::{self, Album, Artist, Client, Playlist, SearchResult, Song}; use crate::{Action, AppWindow, Area, Header, Hint, Item, Screen, Theme}; @@ -264,7 +265,16 @@ pub struct App { queue_items: Rc>, queue_range: (usize, usize), covers: Covers, + /// In the order it plays, which the player's list matches. queue: Vec, + /// Each queued track's position in the order it was queued, which + /// turning shuffle off goes back to. + order: Vec, + shuffle: Mode, + /// 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, queue_sel: usize, position: f64, @@ -369,6 +379,10 @@ impl App { generation: 0, }, queue: Vec::new(), + order: Vec::new(), + shuffle: Mode::Off, + queue_generation: 0, + rng: fastrand::Rng::new(), current: None, queue_sel: 0, position: 0.0, @@ -604,8 +618,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; @@ -625,6 +638,13 @@ impl App { self.sync_inhibit(); } + fn clear_queue(&mut self) { + self.queue.clear(); + self.order.clear(); + self.shuffle = Mode::Off; + self.current = None; + } + /// Stops playback for good, dropping whatever the player still has on /// its way about the old queue. fn stop_player(&self) { @@ -681,8 +701,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(); @@ -805,6 +824,7 @@ impl App { } } Action::Search => self.open_search(), + Action::CycleShuffle => self.cycle_shuffle(), _ => return false, } true @@ -1808,6 +1828,14 @@ impl App { h(Control::Back, "Back"); h(Control::PlayPause, "Play / Pause"); h(Control::Skip, "Skip"); + h( + Control::Shuffle, + match self.shuffle { + Mode::Off => "Shuffle: off", + Mode::Tracks => "Shuffle: tracks", + Mode::Albums => "Shuffle: albums", + }, + ); h(Control::Seek, "Seek"); h(Control::Volume, "Volume"); h(Control::Mute, "Mute"); @@ -2021,7 +2049,9 @@ impl App { }; let urls: Vec = 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.current = None; self.queue_sel = start; self.sync_queue(true); @@ -2040,7 +2070,16 @@ 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 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 { @@ -2110,7 +2149,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()); @@ -2140,7 +2184,11 @@ impl App { self.sync_queue(true); self.save_queue(); } - PlayerEvent::Art(i, bytes) => { + PlayerEvent::Art { + index: i, + picture: bytes, + .. + } => { if self.current != Some(i) { return; } @@ -2256,7 +2304,15 @@ impl App { ); let urls: Vec = 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.current = None; self.queue_sel = current.unwrap_or(0); self.held = current.is_some(); @@ -2277,6 +2333,8 @@ impl App { }; let queue = SavedQueue { songs: self.queue.clone(), + order: self.order.clone(), + shuffle: self.shuffle, current, position, }; @@ -2485,6 +2543,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 @@ -2496,6 +2555,65 @@ impl App { } } + fn cycle_shuffle(&mut self) { + 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, Option) -> Vec) { + let Some(player) = &self.player else { return }; + 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, + }); + } + } + fn queue_clicked(&mut self, index: usize) { self.queue_sel = index; self.ui.set_queue_selected(index as i32); @@ -2944,6 +3062,12 @@ fn join_dot>>(parts: I) -> String { .join(" ยท ") } +/// 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, pending: Option) -> usize { + current.max(pending).map_or(0, |i| i + 1) +} + #[cfg(test)] mod tests { use super::*; diff --git a/src/devscript.rs b/src/devscript.rs index 3f76ed0..363b053 100644 --- a/src/devscript.rs +++ b/src/devscript.rs @@ -95,6 +95,7 @@ fn step(ui: slint::Weak, steps: Vec, i: usize) { "volume-up" => Action::VolumeUp, "volume-down" => Action::VolumeDown, "mute" => Action::ToggleMute, + "cycle-shuffle" => Action::CycleShuffle, other => { log::warn!("unknown dev script step {other}"); Action::None diff --git a/src/main.rs b/src/main.rs index f7cb097..e68e67c 100644 --- a/src/main.rs +++ b/src/main.rs @@ -10,7 +10,6 @@ mod palette; mod player; mod prompts; mod saved_queue; -#[cfg_attr(not(test), expect(dead_code, reason = "wired into the queue by 7ff72a1"))] mod shuffle; mod subsonic; diff --git a/src/player.rs b/src/player.rs index 29ad384..1fb5a29 100644 --- a/src/player.rs +++ b/src/player.rs @@ -17,12 +17,30 @@ pub enum PlayerEvent { Position(f64), Duration(f64), Paused(bool), - /// Index into the queue, None when playback has stopped. - Track(Option), - /// 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>), + /// 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, + 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>, + }, +} + +/// The queue after `reorder`. +#[derive(Debug, Clone, PartialEq)] +pub struct Reordered { + /// The new order, as positions in the old one. + pub perm: Vec, + pub current: Option, + pub pending: Option, + 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, + /// 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, Option) -> Vec) -> Reordered { + let mut q = lock(&self.queue); + let perm = arrange(q.current, q.pending); + let moved = |i: Option| 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> = None; - let mut report_track = |t: Option, 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> = None; + let mut report_track = |index: Option, url: Option, 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 = ["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); + } } diff --git a/src/prompts.rs b/src/prompts.rs index 9672378..d90b9b3 100644 --- a/src/prompts.rs +++ b/src/prompts.rs @@ -35,6 +35,9 @@ 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, /// Steam + X brings up Steam's on-screen keyboard. Nothing to show for a /// real keyboard. OnScreenKeyboard, @@ -42,7 +45,7 @@ pub enum Control { #[cfg(test)] impl Control { - pub const ALL: [Control; 12] = [ + pub const ALL: [Control; 13] = [ Control::Activate, Control::Back, Control::PlayPause, @@ -54,6 +57,7 @@ impl Control { Control::Seek, Control::Volume, Control::Mute, + Control::Shuffle, Control::OnScreenKeyboard, ]; } @@ -81,6 +85,7 @@ 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")], OnScreenKeyboard => &[], }, Prompts::Pad(Family::Xbox) => match control { @@ -88,6 +93,7 @@ pub fn icons(prompts: Prompts, control: Control) -> &'static [&'static [u8]] { 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")], @@ -102,6 +108,7 @@ pub fn icons(prompts: Prompts, control: Control) -> &'static [&'static [u8]] { 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"), @@ -127,6 +134,7 @@ pub fn icons(prompts: Prompts, control: Control) -> &'static [&'static [u8]] { 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")], @@ -144,6 +152,7 @@ pub fn icons(prompts: Prompts, control: Control) -> &'static [&'static [u8]] { 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"), diff --git a/src/saved_queue.rs b/src/saved_queue.rs index a8295e1..1cd6b2c 100644 --- a/src/saved_queue.rs +++ b/src/saved_queue.rs @@ -12,13 +12,21 @@ use anyhow::Result; use serde::{Deserialize, Serialize}; use crate::config; +use crate::shuffle::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, + /// 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, + #[serde(default)] + pub shuffle: Mode, pub current: Option, /// Seconds into the current song. pub position: f64, @@ -121,6 +129,8 @@ mod tests { let mut queues = SavedQueues::default(); let a = SavedQueue { songs: vec![song("1"), song("2")], + order: vec![1, 0], + shuffle: Mode::Tracks, current: Some(1), position: 93.5, }; @@ -128,6 +138,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 +153,20 @@ 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), (1, vec![], Mode::Off)); + 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"); diff --git a/ui/app.slint b/ui/app.slint index e95c3a2..b743b41 100644 --- a/ui/app.slint +++ b/ui/app.slint @@ -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, } export enum Screen { login, browse, now-playing } @@ -1305,6 +1305,7 @@ 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; } reject } diff --git a/ui/prompts/keyboard/keyboard_s.svg b/ui/prompts/keyboard/keyboard_s.svg new file mode 100644 index 0000000..5e4c072 --- /dev/null +++ b/ui/prompts/keyboard/keyboard_s.svg @@ -0,0 +1,9 @@ + + + + + + + + +