goosemusic 1.2.0

A music player with YouTube search, local playback, and OS media controls
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
//! Mouse, drag, and context-menu interaction state.

use iced::{widget::Id, Point};

use crate::{
    data::library::LibraryItem,
    types::{QueueTab, Track},
};

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum TrackListKind {
    Queue,
    Active,
    Recent,
}

impl From<TrackListKind> for Id {
    fn from(list: TrackListKind) -> Self {
        match list {
            TrackListKind::Queue => crate::app::ui::QUEUE_LIST_ID,
            TrackListKind::Active => crate::app::ui::TRACK_LIST_ID,
            TrackListKind::Recent => crate::app::ui::QUEUE_RECENT_LIST_ID,
        }
    }
}

impl TrackListKind {
    pub const fn first_index(self) -> usize {
        match self {
            TrackListKind::Queue => 1,
            _ => 0,
        }
    }

    /// Slot into `DragState::last_focus` for this list.
    pub const fn slot(self) -> usize {
        match self {
            TrackListKind::Queue => 0,
            TrackListKind::Active => 1,
            TrackListKind::Recent => 2,
        }
    }

    pub const fn is_main(self) -> bool {
        matches!(self, TrackListKind::Active)
    }
}

/// Stable `Id` for a track-list row `Container`, used to capture its measured
/// geometry via the bounds `Operation`. The tag distinguishes lists so ids
/// never collide across the tree. Cards (artists/albums/playlists) are not
/// track-list rows and intentionally carry no geometry-capturing id.
pub fn row_id(list: TrackListKind, index: usize) -> Id {
    let tag = match list {
        TrackListKind::Queue => "queue",
        TrackListKind::Active => "active",
        TrackListKind::Recent => "recent",
    };
    Id::from(format!("row:{tag}:{index}"))
}

impl From<QueueTab> for TrackListKind {
    fn from(tab: QueueTab) -> Self {
        match tab {
            QueueTab::Queue => TrackListKind::Queue,
            QueueTab::RecentlyPlayed => TrackListKind::Recent,
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct TrackPos {
    pub index: usize,
    pub list: TrackListKind,
}

impl TrackPos {
    pub const fn new(index: usize, list: TrackListKind) -> Self {
        Self { index, list }
    }
}

#[derive(Debug, Clone)]
pub struct TrackListSearch {
    pub list: TrackListKind,
    pub query: String,
    pub matches: Vec<usize>,
}

/// Which submenu of the context menu is currently expanded by hover.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SubmenuKind {
    Play,
    Download,
    SongRadio,
    ArtistRadio,
    GoToArtist,
}

impl SubmenuKind {
    /// Message produced by activating the entry for `provider` in this
    /// submenu.
    pub fn entry_message(
        self,
        provider: crate::providers::ProviderId,
        menu: &ContextMenuState,
    ) -> super::message::Message {
        use super::message::Message;
        match self {
            SubmenuKind::Play => Message::ContextMenuPlayViaProvider(provider, menu.pos),
            SubmenuKind::Download => Message::ContextMenuDownloadViaProvider(provider),
            SubmenuKind::SongRadio => Message::ContextMenuSongRadioProvider(provider),
            SubmenuKind::ArtistRadio => Message::ContextMenuArtistRadioProvider(provider),
            SubmenuKind::GoToArtist => Message::ContextMenuGoToArtistProvider(provider),
        }
    }

    /// Providers listed in this submenu, in display order.
    pub fn providers(self, track: &Track) -> Vec<crate::providers::ProviderId> {
        use crate::providers::ProviderId;
        match self {
            SubmenuKind::Play => {
                let mut v: Vec<ProviderId> = ProviderId::searchable()
                    .iter()
                    .copied()
                    .filter(|p| p.capabilities().stream)
                    .collect();
                // A local file (imported or downloaded) is playable directly,
                // so it appears in the "Play" submenu alongside the stream
                // providers when one is available.
                if track.local_path().is_some() {
                    v.push(ProviderId::Local);
                }
                v
            }
            SubmenuKind::Download => ProviderId::defaultable()
                .iter()
                .copied()
                .filter(|p| p.capabilities().download)
                .collect(),
            SubmenuKind::SongRadio | SubmenuKind::ArtistRadio => ProviderId::searchable()
                .iter()
                .copied()
                .filter(|p| p.capabilities().radio)
                .collect(),
            SubmenuKind::GoToArtist => ProviderId::searchable()
                .iter()
                .copied()
                .filter(|p| p.capabilities().search)
                .collect(),
        }
    }

    /// Cheap capability probe so building the main-menu action list does not
    /// allocate a provider vec just to check that one is non-empty.
    pub fn available(self) -> bool {
        use crate::providers::ProviderId;
        let any = |list: &'static [ProviderId], cap: fn(ProviderId) -> bool| {
            list.iter().copied().any(cap)
        };
        match self {
            SubmenuKind::Play => any(ProviderId::searchable(), |p| p.capabilities().stream),
            SubmenuKind::Download => any(ProviderId::defaultable(), |p| p.capabilities().download),
            SubmenuKind::SongRadio | SubmenuKind::ArtistRadio => {
                any(ProviderId::searchable(), |p| p.capabilities().radio)
            }
            SubmenuKind::GoToArtist => !ProviderId::searchable().is_empty(),
        }
    }
}

/// Actions whose direct activation (clicking the submenu's parent row) needs
/// a default provider resolved from the track and config. A dedicated enum
/// keeps [`Message::ContextMenuDefault`] exhaustive over real cases.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DefaultCtxAction {
    Download,
    SongRadio,
    ArtistRadio,
}

/// A context-menu entry. The menu's contents are derived from this list so
/// the view and keyboard navigation always agree on indices.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CtxAction {
    Play,
    Edit,
    GoToArtist,
    AddToPlaylist,
    Download,
    SongRadio,
    ArtistRadio,
    RemoveFromQueue,
    RemoveFromPlaylist,
}

impl CtxAction {
    pub fn submenu(self) -> Option<SubmenuKind> {
        match self {
            CtxAction::Play => Some(SubmenuKind::Play),
            CtxAction::Download => Some(SubmenuKind::Download),
            CtxAction::SongRadio => Some(SubmenuKind::SongRadio),
            CtxAction::ArtistRadio => Some(SubmenuKind::ArtistRadio),
            CtxAction::GoToArtist => Some(SubmenuKind::GoToArtist),
            CtxAction::Edit
            | CtxAction::AddToPlaylist
            | CtxAction::RemoveFromQueue
            | CtxAction::RemoveFromPlaylist => None,
        }
    }

    pub fn to_message(self, menu: &ContextMenuState) -> super::message::Message {
        use super::message::Message;
        match self {
            CtxAction::Play => Message::ContextMenuPlayTrack(menu.pos),
            CtxAction::Edit => Message::ContextMenuEditTrack,
            CtxAction::GoToArtist => Message::ContextMenuGoToArtist,
            CtxAction::AddToPlaylist => Message::TogglePicker(menu.target_indices.clone()),
            CtxAction::Download => Message::ContextMenuDefault(DefaultCtxAction::Download),
            CtxAction::SongRadio => Message::ContextMenuDefault(DefaultCtxAction::SongRadio),
            CtxAction::ArtistRadio => Message::ContextMenuDefault(DefaultCtxAction::ArtistRadio),
            CtxAction::RemoveFromQueue => {
                Message::ContextMenuRemoveFromQueue(menu.target_indices.clone())
            }
            CtxAction::RemoveFromPlaylist => {
                Message::ContextMenuRemoveFromPlaylist(menu.target_indices.clone())
            }
        }
    }
}

/// Where keyboard/mouse focus currently sits inside the open context menu.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ContextMenuFocus {
    /// An entry of the main menu (index into [`ContextMenuState::actions`]).
    Item(usize),
    /// An entry of the open submenu (index into `SubmenuKind::providers`).
    Sub(SubmenuKind, usize),
}

#[derive(Debug, Clone)]
#[allow(clippy::struct_excessive_bools)]
pub struct ContextMenuState {
    pub pos: TrackPos,
    pub position: (f32, f32),
    /// Original cursor point; `position` may be flipped away from it, but
    /// every re-measure recomputes the flip relative to this.
    pub cursor: (f32, f32),
    pub in_playlist: bool,
    pub track: Track,
    pub target_indices: Vec<usize>,
    pub hovered: Option<ContextMenuFocus>,
}

impl ContextMenuState {
    /// The visible entries of the main menu, in order. The view renders one
    /// row per entry; keyboard navigation indexes into this list.
    pub fn actions(&self) -> Vec<CtxAction> {
        let mut v = vec![CtxAction::Play, CtxAction::Edit];
        if !self.track.artist.is_empty() {
            v.push(CtxAction::GoToArtist);
        }
        v.push(CtxAction::AddToPlaylist);
        v.push(CtxAction::Download);
        if SubmenuKind::SongRadio.available() {
            v.push(CtxAction::SongRadio);
            v.push(CtxAction::ArtistRadio);
        }
        if self.pos.list == TrackListKind::Queue {
            v.push(CtxAction::RemoveFromQueue);
        } else if self.in_playlist && self.pos.list != TrackListKind::Recent {
            v.push(CtxAction::RemoveFromPlaylist);
        }
        v
    }

    /// The submenu currently visible, derived from the hovered element: a
    /// main-menu parent opens its own submenu; hovering a submenu entry keeps
    /// that submenu open.
    pub fn open_submenu_kind(&self) -> Option<SubmenuKind> {
        match self.hovered? {
            ContextMenuFocus::Item(i) => self.actions().get(i).and_then(|a| a.submenu()),
            ContextMenuFocus::Sub(kind, _) => Some(kind),
        }
    }

    /// Provider used when a submenu-parent action is clicked directly: the
    /// track's source provider when capable of `action`, else the first
    /// capable search provider, else `fallback` (the configured default).
    pub fn default_provider(
        &self,
        action: DefaultCtxAction,
        fallback: crate::providers::ProviderId,
    ) -> crate::providers::ProviderId {
        use crate::providers::ProviderId;
        let capable = |p: ProviderId| match action {
            DefaultCtxAction::Download => p.capabilities().download,
            DefaultCtxAction::SongRadio | DefaultCtxAction::ArtistRadio => p.capabilities().radio,
        };
        if capable(self.track.source) {
            return self.track.source;
        }
        ProviderId::searchable()
            .iter()
            .copied()
            .find(|&p| action != DefaultCtxAction::Download && capable(p))
            .unwrap_or(fallback)
    }

    /// Provider used when "Go to artist" is clicked directly: the track's
    /// source provider when it carries that artist id, else `fallback`.
    pub fn default_go_to_artist_provider(
        &self,
        fallback: crate::providers::ProviderId,
    ) -> crate::providers::ProviderId {
        if self.track.provider_artist_id(self.track.source).is_some() {
            self.track.source
        } else {
            fallback
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DropTarget {
    Track(TrackPos),
    Playlist(usize),
    Library(usize),
    PlaylistAdd(usize),
    PlaylistReorder { from: usize, to: usize },
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum HoverTarget {
    Track(TrackPos),
    Card(LibraryItem),
    LibraryCard(LibraryItem),
    Playlist(usize),
    SearchHistory(usize),
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Pressed {
    Track(TrackPos),
    Card(LibraryItem),
    Playlist(usize),
}

#[derive(Debug, Clone, PartialEq)]
pub struct PressedDrag {
    pub what: Pressed,
    pub origin: Point,
}

/// Mouse and drag interaction state
#[derive(Debug, Clone, Default)]
pub struct DragState {
    pub cursor_pos: Point,
    pub pressed: Option<PressedDrag>,
    pub drag_active: bool,
    pub drop_target: Option<DropTarget>,
    /// Track indices carried by the current drag, resolved at press time:
    /// the whole selection if the pressed track is selected, else just it.
    /// The list is stored alongside because `pressed` is taken before the
    /// drop handler runs.
    pub dragged: Option<(TrackListKind, Vec<usize>)>,
    pub is_hover_controlled: bool,
    pub hovered: Option<HoverTarget>,
    /// Last focused row per list, so returning to a list restores focus.
    pub last_focus: [usize; 3],
}

impl DragState {
    pub fn stop(&mut self) {
        self.drag_active = false;
        self.pressed = None;
        self.drop_target = None;
        self.dragged = None;
    }

    pub(crate) fn cleanup(&mut self) {
        self.stop();
        self.hovered = None;
    }

    /// The hovered track, if any — also the keyboard-navigation focus.
    pub fn hovered_track(&self) -> Option<TrackPos> {
        match self.hovered {
            Some(HoverTarget::Track(pos)) => Some(pos),
            _ => None,
        }
    }

    /// Set the hovered target, remembering track rows as the list's last
    /// focused row.
    pub fn set_hovered(&mut self, target: HoverTarget) {
        if let HoverTarget::Track(pos) = &target {
            self.last_focus[pos.list.slot()] = pos.index;
        }
        self.hovered = Some(target);
    }

    /// The last focused row index of `list`, if still meaningful-ish.
    pub fn recall_focus(&self, list: TrackListKind) -> usize {
        self.last_focus[list.slot()]
    }

    /// Clear a hovered track without disturbing an unrelated card hover.
    pub fn clear_hovered_track(&mut self) {
        if matches!(self.hovered, Some(HoverTarget::Track(_))) {
            self.hovered = None;
        }
    }

    /// The hovered search-history entry index, if any — the keyboard-
    /// navigation focus while the search-history dropdown is open.
    pub fn hovered_search_history(&self) -> Option<usize> {
        match self.hovered {
            Some(HoverTarget::SearchHistory(i)) => Some(i),
            _ => None,
        }
    }

    /// Set the hovered search-history entry (keyboard-navigation focus).
    pub fn set_hovered_search_history(&mut self, index: usize) {
        self.hovered = Some(HoverTarget::SearchHistory(index));
    }

    /// Clear a hovered search-history entry without disturbing another hover.
    pub fn clear_hovered_search_history(&mut self) {
        if matches!(self.hovered, Some(HoverTarget::SearchHistory(_))) {
            self.hovered = None;
        }
    }

    /// Whether the given search card is the hovered one.
    pub fn is_hovered_card(&self, item: &LibraryItem) -> bool {
        matches!(self.hovered, Some(HoverTarget::Card(ref c)) if c == item)
    }

    /// Whether the given library card is the hovered one.
    pub fn is_hovered_library_card(&self, item: &LibraryItem) -> bool {
        matches!(self.hovered, Some(HoverTarget::LibraryCard(ref c)) if c == item)
    }

    /// Whether a card (vs track) drag is active.
    pub fn is_pressed_card(&self) -> bool {
        matches!(
            self.pressed,
            Some(PressedDrag {
                what: Pressed::Card(_),
                ..
            })
        )
    }

    /// The hovered playlist row index, if any.
    pub fn hovered_playlist(&self) -> Option<usize> {
        match self.hovered {
            Some(HoverTarget::Playlist(i)) => Some(i),
            _ => None,
        }
    }

    pub fn cursor_interaction(&self) -> Option<iced::mouse::Interaction> {
        if self.drag_active && self.pressed.is_some() {
            Some(iced::mouse::Interaction::Grabbing)
        } else {
            None
        }
    }

    pub fn clickable_cursor_interaction(&self) -> iced::mouse::Interaction {
        self.cursor_interaction()
            .unwrap_or(iced::mouse::Interaction::Pointer)
    }
}

#[cfg(test)]
mod tests {
    use iced::widget::Id;

    use super::TrackListKind::{Active, Queue, Recent};
    use crate::app::ui::{QUEUE_LIST_ID, QUEUE_RECENT_LIST_ID, TRACK_LIST_ID};

    #[test]
    fn each_list_targets_a_distinct_scrollable() {
        assert_eq!(Id::from(Queue), QUEUE_LIST_ID);
        assert_eq!(Id::from(Active), TRACK_LIST_ID);
        assert_eq!(Id::from(Recent), QUEUE_RECENT_LIST_ID);
        assert_ne!(Id::from(Queue), Id::from(Recent));
    }

    #[test]
    fn only_queue_offsets_its_first_row() {
        assert_eq!(Queue.first_index(), 1);
        assert_eq!(Active.first_index(), 0);
        assert_eq!(Recent.first_index(), 0);
    }
}