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
use iced::widget::operation;

use super::{Message, MusicPlayer, Task, Track, TrackListKind, TrackPos, ViewData};
use crate::app::{
    interaction::{ContextMenuFocus, HoverTarget},
    ui::SEARCH_HISTORY_LIST_ID,
    view_data::ViewKind,
    TrackListSearch,
};

impl MusicPlayer {
    /// Arrow-key navigation and Enter activation while the context menu is
    /// open. Mirrors track-list nav: Up/Down move within the focused pane and
    /// wrap at the edges; Left/Right switch between the menu and its submenu.
    pub fn handle_context_menu_key(
        &mut self,
        key: iced::keyboard::key::Physical,
        modifiers: iced::keyboard::Modifiers,
    ) -> Task<Message> {
        use iced::keyboard::key::{Code, Physical};
        if matches!(key, Physical::Code(Code::Escape)) && !modifiers.control() {
            self.close_context_menu();
            return Task::none();
        }
        if self.context_menu.is_none() {
            return Task::none();
        }
        match key {
            Physical::Code(Code::ArrowUp) => self.step_context_menu_focus(-1),
            Physical::Code(Code::ArrowDown) => self.step_context_menu_focus(1),
            Physical::Code(Code::ArrowLeft | Code::ArrowRight) => self.context_menu_horizontal(),
            Physical::Code(Code::Enter) => {
                let menu = self.context_menu.as_ref().expect("checked above");
                let message = match menu.hovered {
                    Some(ContextMenuFocus::Item(i)) => {
                        menu.actions().get(i).map(|a| a.to_message(menu))
                    }
                    Some(ContextMenuFocus::Sub(kind, i)) => kind
                        .providers(&menu.track)
                        .get(i)
                        .map(|p| kind.entry_message(*p, menu)),
                    None => None,
                };
                match message {
                    Some(m) => iced::Task::done(m),
                    None => Task::none(),
                }
            }
            _ => Task::none(),
        }
    }

    fn step_context_menu_focus(&mut self, dir: isize) -> Task<Message> {
        // Move within whichever pane focus is currently in; an unfocused menu
        // starts in the main list.
        let focus = {
            let Some(menu) = self.context_menu.as_ref() else {
                return Task::none();
            };
            let (kind, count, current) = match menu.hovered {
                Some(ContextMenuFocus::Sub(kind, i)) => {
                    (Some(kind), kind.providers(&menu.track).len(), Some(i))
                }
                other => {
                    let i = match other {
                        Some(ContextMenuFocus::Item(i)) => Some(i),
                        _ => None,
                    };
                    (None, menu.actions().len(), i)
                }
            };
            if count == 0 {
                return Task::none();
            }
            let next = current.map_or(if dir < 0 { count - 1 } else { 0 }, |i| {
                (i.cast_signed() + dir).rem_euclid(count.cast_signed()) as usize
            });
            match kind {
                Some(kind) => ContextMenuFocus::Sub(kind, next),
                None => ContextMenuFocus::Item(next),
            }
        };
        if let Some(m) = self.context_menu.as_mut() {
            m.hovered = Some(focus);
        }
        Task::none()
    }

    fn context_menu_horizontal(&mut self) -> Task<Message> {
        let focus = {
            let Some(menu) = self.context_menu.as_ref() else {
                return Task::none();
            };
            match menu.hovered {
                // Enter the open submenu from its parent row.
                Some(ContextMenuFocus::Item(i)) => {
                    let Some(kind) = menu.actions().get(i).and_then(|a| a.submenu()) else {
                        return Task::none();
                    };
                    ContextMenuFocus::Sub(kind, 0)
                }
                // Leave the submenu back to its parent row.
                Some(ContextMenuFocus::Sub(kind, _)) => {
                    let i = menu
                        .actions()
                        .iter()
                        .position(|a| a.submenu() == Some(kind))
                        .unwrap_or(0);
                    ContextMenuFocus::Item(i)
                }
                _ => return Task::none(),
            }
        };
        if let Some(m) = self.context_menu.as_mut() {
            m.hovered = Some(focus);
        }
        Task::none()
    }

    pub fn handle_cursor_moved(&mut self, pos: iced::Point) -> Task<Message> {
        self.drag.is_hover_controlled = false;
        self.drag.cursor_pos = pos;
        if self.drag.drag_active {
            return self.handle_drag_update();
        }
        if let Some(origin) = self.drag.pressed.as_ref().map(|pd| pd.origin) {
            let dx = (pos.x - origin.x).abs();
            let dy = (pos.y - origin.y).abs();
            if dx > crate::theme::DRAG_THRESHOLD || dy > crate::theme::DRAG_THRESHOLD {
                self.drag.drag_active = true;
                // Reveal the library so it can receive drops.
                if self.drag.is_pressed_card() {
                    self.library_expanded = true;
                }
                return Task::batch([
                    super::operation::CaptureBounds::new().into(),
                    self.handle_drag_update(),
                ]);
            }
        }
        Task::none()
    }

    #[allow(clippy::too_many_lines)]
    pub fn handle_key_press(
        &mut self,
        key: iced::keyboard::key::Physical,
        modifiers: iced::keyboard::Modifiers,
    ) -> Task<Message> {
        use iced::keyboard::key::{Code, Physical};
        if self.context_menu.is_some() {
            return self.handle_context_menu_key(key, modifiers);
        }
        let task = match key {
            Physical::Code(Code::KeyF) if modifiers.control() || modifiers.logo() => {
                self.open_track_list_search()
            }
            Physical::Code(Code::Slash)
                if !modifiers.control() && !modifiers.logo() && !modifiers.alt() =>
            {
                Task::batch([
                    operation::focus::<Message>(crate::app::ui::SEARCH_INPUT_ID),
                    self.activate_search_input(),
                ])
            }
            Physical::Code(Code::Space) => {
                self.toggle_play_pause();
                Task::none()
            }
            Physical::Code(Code::ContextMenu) => self.open_context_menu_for_hovered_track(),
            Physical::Code(Code::F10)
                if modifiers.shift() && !modifiers.control() && !modifiers.logo() =>
            {
                self.open_context_menu_for_hovered_track()
            }
            Physical::Code(Code::Enter) if modifiers.control() || modifiers.logo() => {
                self.open_context_menu_for_hovered_track()
            }
            Physical::Code(Code::Escape) => {
                if self.track_list_search.is_some() {
                    self.track_list_search = None;
                } else if self.show_search_history {
                    self.show_search_history = false;
                    self.drag.clear_hovered_search_history();
                } else if let Some(hovered) = self.drag.hovered_track() {
                    self.clear_selection_for(hovered.list);
                } else if self.has_selection() {
                    self.clear_selection();
                } else {
                    return self.handle_navigate_to(ViewData::new_search(
                        String::new(),
                        self.search_provider,
                        self.search_scope,
                    ));
                }
                Task::none()
            }
            Physical::Code(Code::Delete) => {
                if matches!(&self.view_data().kind, ViewKind::Playlist(_)) {
                    self.handle_delete_selected();
                }
                Task::none()
            }
            Physical::Code(Code::ArrowLeft | Code::ArrowRight) => self.toggle_keyboard_list(),
            Physical::Code(Code::ArrowUp) => {
                if self.track_list_search.is_some() {
                    return self.handle_track_list_search_step(-1);
                }
                if self.show_search_history {
                    return self.step_search_history_hover(-1);
                }
                self.step_hovered_track(-1)
            }
            Physical::Code(Code::ArrowDown) => {
                if self.track_list_search.is_some() {
                    return self.handle_track_list_search_step(1);
                }
                if self.show_search_history {
                    return self.step_search_history_hover(1);
                }
                self.step_hovered_track(1)
            }
            Physical::Code(Code::Enter) => {
                if let Some(i) = self.drag.hovered_search_history() {
                    return self.handle_search_history_select(i);
                } else if let Some(hovered) = self.drag.hovered_track() {
                    self.handle_play_track(hovered);
                }
                Task::none()
            }
            Physical::Code(Code::KeyA) if modifiers.control() || modifiers.logo() => {
                self.handle_select_all();
                Task::none()
            }
            Physical::Code(Code::KeyC) if modifiers.control() || modifiers.logo() => {
                self.handle_copy_selected();
                Task::none()
            }
            Physical::Code(Code::KeyV) if modifiers.control() || modifiers.logo() => {
                self.handle_paste_clipboard();
                Task::none()
            }
            _ => Task::none(),
        };
        task
    }

    fn toggle_keyboard_list(&mut self) -> Task<Message> {
        if !self.show_queue {
            return Task::none();
        }

        let target = if self.hovered_list().is_main() {
            self.queue.queue_tab.into()
        } else {
            TrackListKind::Active
        };
        if self.track_count(target) == 0
            || self.drag.hovered_track().is_some_and(|p| p.list == target)
        {
            return Task::none();
        }
        let index = self
            .drag
            .recall_focus(target)
            .clamp(target.first_index(), self.track_count(target) - 1);
        self.move_hovered(TrackPos::new(index, target))
    }

    /// Scroll `pos` into view of its list. `center` forces the row to the
    /// middle of the viewport; otherwise the list only scrolls when `pos` is
    /// outside the visible viewport (reveal).
    fn scroll_track_into_view(&self, pos: TrackPos) -> Task<Message> {
        let TrackPos { index, list } = pos;

        let bounds = if list.is_main() {
            self.bounds.track.as_ref().map(|g| g.bounds)
        } else {
            self.bounds.queue.as_ref().map(|g| g.bounds)
        };

        let Some(bounds) = bounds else {
            return Task::none();
        };

        // The queue's now-playing track renders in its own header, so the
        // scrollable's rows are shifted down by `first_index`.
        let visual_index = index - list.first_index().min(index);
        let row_y = visual_index as f32 * crate::theme::ROW_HEIGHT;

        // `scroll_to` with `AbsoluteOffset` sets the scroll position
        // directly, so center the row within the viewport height.
        let absolute = (row_y + crate::theme::ROW_HEIGHT / 2.0 - bounds.height / 2.0).max(0.0);
        operation::scroll_to::<Message>(
            list,
            operation::AbsoluteOffset {
                x: 0.0,
                y: absolute,
            },
        )
    }

    /// Move the hovered track by `dir` (-1 up, +1 down) within its list, looping
    /// at both edges, and center it. Starts from the first row when nothing is
    /// hovered yet.
    fn step_hovered_track(&mut self, dir: isize) -> Task<Message> {
        let list = self.hovered_list();
        let count = self.track_count(list);
        if count == 0 {
            return Task::none();
        }
        let first = list.first_index();
        let new_idx = match self.drag.hovered_track() {
            Some(pos) if pos.list == list => {
                let span = count - first;
                ((pos.index - first).cast_signed() + dir).rem_euclid(span.cast_signed()) as usize
                    + first
            }
            _ => self.drag.recall_focus(list).clamp(first, count - 1),
        };
        self.move_hovered(TrackPos::new(new_idx, list))
    }

    /// Set the hovered track and center it in its list.
    pub(crate) fn move_hovered(&mut self, pos: TrackPos) -> Task<Message> {
        self.drag.is_hover_controlled = true;
        self.drag.set_hovered(HoverTarget::Track(pos));
        self.scroll_track_into_view(pos)
    }

    /// Move the hovered search-history entry by `dir` (-1 up, +1 down),
    /// looping at both edges (last+1 → first, first-1 → last), and center it
    /// in the dropdown viewport — mirroring track-list keyboard nav. Starts
    /// from the first entry when nothing is hovered yet.
    fn step_search_history_hover(&mut self, dir: isize) -> Task<Message> {
        let count = self.last_filtered_history.len();
        if count == 0 {
            return Task::none();
        }
        let new_idx = match self.drag.hovered_search_history() {
            Some(i) => (i.cast_signed() + dir).rem_euclid(count.cast_signed()) as usize,
            None => 0,
        };
        self.drag.is_hover_controlled = true;
        self.drag.set_hovered_search_history(new_idx);
        let y = self
            .bounds
            .search_history
            .as_ref()
            .and_then(|g| g.rows.get(new_idx).map(|row| (g, row)))
            .map_or(0.0, |(g, row)| {
                // Center the row in the viewport, like `scroll_track_into_view`.
                let row_center = row.y + row.height / 2.0;
                (row_center - g.bounds.y + g.translation_y - g.bounds.height / 2.0).max(0.0)
            });
        operation::scroll_to::<Message>(
            SEARCH_HISTORY_LIST_ID,
            iced::widget::operation::AbsoluteOffset { x: 0.0, y },
        )
    }

    fn hovered_list(&self) -> TrackListKind {
        self.drag
            .hovered_track()
            .map_or(TrackListKind::Active, |h| h.list)
    }

    pub(crate) fn open_track_list_search(&mut self) -> Task<Message> {
        let Some(pos) = self.drag.hovered_track() else {
            return Task::none();
        };
        let list = pos.list;
        let matches: Vec<usize> = (0..self.track_count(list)).collect();
        self.track_list_search = Some(TrackListSearch {
            list,
            query: String::new(),
            matches,
        });
        // Anchor the hovered track to the closest match so there is a current
        // occurrence immediately (and scroll it into view).
        let from = pos.index;
        let anchored = self.closest_match(from).unwrap_or(from);
        Task::batch([
            self.move_hovered(TrackPos::new(anchored, list)),
            operation::focus::<Message>(crate::app::ui::track_list_search::TRACK_LIST_SEARCH_ID),
        ])
    }

    /// The matched track index nearest to `from` (by absolute row distance,
    /// ties resolved to the smaller index), or `None` when there are no
    /// matches.
    fn closest_match(&self, from: usize) -> Option<usize> {
        let fs = self.track_list_search.as_ref()?;
        let mut best: Option<(usize, usize)> = None;
        for &m in &fs.matches {
            let dist = m.abs_diff(from);
            match best {
                Some((b_dist, b_idx)) if b_dist < dist || (b_dist == dist && b_idx < m) => {}
                _ => best = Some((dist, m)),
            }
        }
        best.map(|(_, idx)| idx)
    }

    /// Recompute the match set for the active track list search against the
    /// live query. The hovered track is re-anchored to the closest match
    /// (kept as-is when it still matches) so the current occurrence follows
    /// the query, and the new current is scrolled into view.
    pub(crate) fn handle_track_list_search_input(&mut self, query: &str) -> Task<Message> {
        let list = match &self.track_list_search {
            Some(fs) => fs.list,
            None => return Task::none(),
        };
        let tracks: &[Track] = match list {
            TrackListKind::Queue => &self.queue.tracks,
            TrackListKind::Active => self.view_tracks(),
            TrackListKind::Recent => self.queue.recently_played.as_slices().0,
        };
        let matches: Vec<usize> = tracks
            .iter()
            .enumerate()
            .filter(|(_, t)| {
                crate::util::fuzzy_match(query, &t.title)
                    || crate::util::fuzzy_match(query, &t.artist)
            })
            .map(|(i, _)| i)
            .collect();
        let fs = self.track_list_search.as_mut().expect("checked above");
        fs.query = query.to_string();
        fs.matches = matches;
        let from = match self.drag.hovered_track() {
            Some(h) if h.list == list => h.index,
            _ => 0,
        };
        let anchored = self.closest_match(from).unwrap_or(from);
        self.move_hovered(TrackPos::new(anchored, list))
    }

    /// Move the hovered track to the next (`dir = 1`) or previous (`dir = -1`)
    /// match relative to its current row, wrapping around the match list.
    /// The hovered track is the current occurrence, so this is how the user
    /// walks between matches; the new current is scrolled into view.
    pub(crate) fn handle_track_list_search_step(&mut self, dir: isize) -> Task<Message> {
        let Some(fs) = self.track_list_search.as_ref() else {
            return Task::none();
        };
        if fs.matches.len() <= 1 {
            return Task::none();
        }
        let from = match self.drag.hovered_track() {
            Some(h) if h.list == fs.list => h.index,
            _ => 0,
        };
        let target = {
            let back = dir < 0;
            let mut lo = 0usize;
            let mut hi = fs.matches.len();
            while lo < hi {
                let mid = lo + (hi - lo) / 2;
                // forward: skip the exact match; backward: keep it (step back)
                if fs.matches[mid] < from || (!back && fs.matches[mid] == from) {
                    lo = mid + 1; // match is at or before `from`
                } else {
                    hi = mid; // match is after `from`
                }
            }
            if dir < 0 {
                // previous match; wrap to last past the start
                *fs.matches
                    .get(lo.wrapping_sub(1))
                    .unwrap_or_else(|| fs.matches.last().unwrap())
            } else {
                // next match; wrap to first past the end
                fs.matches.get(lo).copied().unwrap_or(fs.matches[0])
            }
        };
        self.move_hovered(TrackPos::new(target, fs.list))
    }
}