mecomp_core/state/
mod.rs

1#![allow(clippy::module_name_repetitions)]
2pub mod library;
3use std::{fmt::Display, time::Duration};
4
5use mecomp_storage::db::schemas::song::Song;
6use serde::{Deserialize, Serialize};
7
8use crate::format_duration;
9
10#[derive(Clone, Copy, Debug, PartialEq, Eq, Deserialize, Serialize)]
11pub enum SeekType {
12    Absolute,
13    RelativeForwards,
14    RelativeBackwards,
15}
16
17impl Display for SeekType {
18    #[inline]
19    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
20        match self {
21            Self::Absolute => write!(f, "Absolute"),
22            Self::RelativeForwards => write!(f, "Forwards"),
23            Self::RelativeBackwards => write!(f, "Backwards"),
24        }
25    }
26}
27
28#[derive(Clone, Copy, Debug, PartialEq, Eq, Deserialize, Serialize, Default)]
29pub enum RepeatMode {
30    /// No repeat: after the queue is finished the player stops
31    #[default]
32    None,
33    /// Repeat the current Song: Repeats the current song, otherwise behaves like `RepeatMode::None`
34    One,
35    /// Repeat the queue Continuously: after going through the queue, the player goes back to the beginning and continues
36    All,
37}
38
39impl Display for RepeatMode {
40    #[inline]
41    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
42        match self {
43            Self::None => write!(f, "None"),
44            Self::One => write!(f, "One"),
45            Self::All => write!(f, "All"),
46        }
47    }
48}
49
50impl RepeatMode {
51    #[must_use]
52    #[inline]
53    pub const fn is_none(&self) -> bool {
54        matches!(self, Self::None)
55    }
56
57    #[must_use]
58    #[inline]
59    pub const fn is_one(&self) -> bool {
60        matches!(self, Self::One)
61    }
62
63    #[must_use]
64    #[inline]
65    pub const fn is_all(&self) -> bool {
66        matches!(self, Self::All)
67    }
68}
69
70#[derive(Copy, Clone, Debug, PartialEq, Deserialize, Serialize, Default)]
71pub struct Percent(f32);
72
73impl Percent {
74    #[must_use]
75    #[inline]
76    pub const fn new(value: f32) -> Self {
77        Self(if value.is_finite() {
78            value.clamp(0.0, 100.0)
79        } else {
80            0.0
81        })
82    }
83
84    #[must_use]
85    #[inline]
86    pub const fn into_inner(self) -> f32 {
87        self.0
88    }
89}
90
91impl Display for Percent {
92    #[inline]
93    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
94        write!(f, "{:.2}%", self.into_inner())
95    }
96}
97
98/// Information about the runtime of the song song
99#[derive(Clone, Copy, Debug, Deserialize, Serialize, PartialEq, Default)]
100pub struct StateRuntime {
101    pub seek_position: Duration,
102    pub seek_percent: Percent,
103    pub duration: Duration,
104}
105
106impl Display for StateRuntime {
107    #[inline]
108    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
109        write!(
110            f,
111            "StateRuntime {{ seek_position: {}, seek_percent: {}, duration: {} }}",
112            format_duration(&self.seek_position),
113            self.seek_percent,
114            format_duration(&self.duration)
115        )
116    }
117}
118
119#[derive(
120    Debug, Deserialize, Serialize, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default,
121)]
122pub enum Status {
123    #[default]
124    Stopped,
125    Paused,
126    Playing,
127}
128
129impl Display for Status {
130    #[inline]
131    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
132        match self {
133            Self::Paused => write!(f, "Paused"),
134            Self::Playing => write!(f, "Playing"),
135            Self::Stopped => write!(f, "Stopped"),
136        }
137    }
138}
139
140#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
141pub struct StateAudio {
142    pub queue: Box<[Song]>,
143    pub queue_position: Option<usize>,
144    pub current_song: Option<Song>,
145    pub repeat_mode: RepeatMode,
146    pub runtime: Option<StateRuntime>,
147    pub status: Status,
148    pub muted: bool,
149    pub volume: f32,
150}
151
152impl Display for StateAudio {
153    #[inline]
154    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
155        write!(
156            f,
157            "StateAudio {{ queue: {:?}, queue_position: {}, current_song: {}, repeat_mode: {}, runtime: {}, status: {}, muted: {}, volume: {:.0}% }}",
158            self.queue
159                .iter()
160                .map(|song| song.title.to_string())
161                .collect::<Vec<_>>(),
162            self.queue_position.map_or_else(|| "None".to_string(), |pos| pos.to_string()),
163            self.current_song.as_ref().map_or_else(|| "None".to_string(),|song| format!("\"{}\"",song.title)),
164            self.repeat_mode,
165            self.runtime.as_ref().map_or_else(|| "None".to_string(),std::string::ToString::to_string),
166            self.status,
167            self.muted,
168            self.volume * 100.0,
169        )
170    }
171}
172
173impl Default for StateAudio {
174    /// Should match the defaults assigned to the [`AudioKernel`]
175    #[inline]
176    fn default() -> Self {
177        Self {
178            queue: Box::default(),
179            queue_position: None,
180            current_song: None,
181            repeat_mode: RepeatMode::default(),
182            runtime: None,
183            status: Status::default(),
184            muted: false,
185            volume: 1.0,
186        }
187    }
188}
189
190impl StateAudio {
191    #[must_use]
192    #[inline]
193    pub const fn paused(&self) -> bool {
194        !matches!(self.status, Status::Playing)
195    }
196}
197
198#[cfg(test)]
199mod tests {
200    use std::time::Duration;
201
202    use super::*;
203    use one_or_many::OneOrMany;
204    use pretty_assertions::{assert_eq, assert_str_eq};
205    use rstest::rstest;
206
207    #[test]
208    fn test_state_audio_default() {
209        let state = StateAudio::default();
210        assert_eq!(state.queue.as_ref(), &[]);
211        assert_eq!(state.queue_position, None);
212        assert_eq!(state.current_song, None);
213        assert_eq!(state.repeat_mode, RepeatMode::None);
214        assert_eq!(state.runtime, None);
215        assert_eq!(state.status, Status::Stopped);
216        assert_eq!(state.muted, false);
217        assert_eq!(state.volume, 1.0);
218    }
219
220    #[rstest]
221    #[case::none(RepeatMode::None, [true, false, false])]
222    #[case::one(RepeatMode::One, [false, true, false])]
223    #[case::all(RepeatMode::All, [false, false, true])]
224    fn test_repeat_mode(#[case] mode: RepeatMode, #[case] expected: [bool; 3]) {
225        assert_eq!(mode.is_none(), expected[0]);
226        assert_eq!(mode.is_one(), expected[1]);
227        assert_eq!(mode.is_all(), expected[2]);
228    }
229
230    #[rstest]
231    #[case::seek_type(SeekType::Absolute, "Absolute")]
232    #[case::seek_type(SeekType::RelativeForwards, "Forwards")]
233    #[case::seek_type(SeekType::RelativeBackwards, "Backwards")]
234    #[case::repeat_mode(RepeatMode::None, "None")]
235    #[case::repeat_mode(RepeatMode::One, "One")]
236    #[case::repeat_mode(RepeatMode::All, "All")]
237    #[case::percent(Percent::new(50.0), "50.00%")]
238    #[case::state_runtimme(
239        StateRuntime {
240            seek_position: Duration::from_secs(3),
241            seek_percent: Percent::new(50.0),
242            duration: Duration::from_secs(6),
243        },
244        "StateRuntime { seek_position: 00:00:03.00, seek_percent: 50.00%, duration: 00:00:06.00 }"
245    )]
246    #[case::state_audio_empty(
247        StateAudio {
248            queue: Box::new([]),
249            queue_position: None,
250            current_song: None,
251            repeat_mode: RepeatMode::None,
252            runtime: None,
253            status: Status::Paused,
254            muted: false,
255            volume: 1.0,
256        },
257        "StateAudio { queue: [], queue_position: None, current_song: None, repeat_mode: None, runtime: None, status: Paused, muted: false, volume: 100% }"
258    )]
259    #[case::state_audio_empty(
260        StateAudio {
261            queue: Box::new([]),
262            queue_position: None,
263            current_song: None,
264            repeat_mode: RepeatMode::None,
265            runtime: None,
266            status: Status::Paused,
267            muted: false,
268            volume: 1.0,
269        },
270        "StateAudio { queue: [], queue_position: None, current_song: None, repeat_mode: None, runtime: None, status: Paused, muted: false, volume: 100% }"
271    )]
272    #[case::state_audio(
273        StateAudio {
274            queue: Box::new([
275                Song {
276                    id: Song::generate_id(),
277                    title: "Song 1".into(),
278                    artist: OneOrMany::None,
279                    album_artist: OneOrMany::None,
280                    album: "album".into(),
281                    genre: OneOrMany::None,
282                    runtime: Duration::from_secs(100),
283                    track: None,
284                    disc: None,
285                    release_year: None,
286                    extension: "mp3".into(),
287                    path: "foo/bar.mp3".into(),
288                }
289            ]),
290            queue_position: Some(1),
291            current_song: Some(
292                Song {
293                    id: Song::generate_id(),
294                    title: "Song 1".into(),
295                    artist: OneOrMany::None,
296                    album_artist: OneOrMany::None,
297                    album: "album".into(),
298                    genre: OneOrMany::None,
299                    runtime: Duration::from_secs(100),
300                    track: None,
301                    disc: None,
302                    release_year: None,
303                    extension: "mp3".into(),
304                    path: "foo/bar.mp3".into(),
305                }
306            ),
307            repeat_mode: RepeatMode::None,
308            runtime: Some(StateRuntime {
309                seek_position: Duration::from_secs(20),
310                seek_percent: Percent::new(20.0),
311                duration: Duration::from_secs(100),
312            }),
313            status: Status::Playing,
314            muted: false,
315            volume: 1.0,
316        },
317        "StateAudio { queue: [\"Song 1\"], queue_position: 1, current_song: \"Song 1\", repeat_mode: None, runtime: StateRuntime { seek_position: 00:00:20.00, seek_percent: 20.00%, duration: 00:01:40.00 }, status: Playing, muted: false, volume: 100% }"
318    )]
319    fn test_display_impls<T: Display>(#[case] input: T, #[case] expected: &str) {
320        assert_str_eq!(input.to_string(), expected);
321    }
322}