flaccy 1.5.0

Lossless music player for Linux
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
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
use crate::events::AppEvent;
use crate::library::{format_time, Album, Track};
use crate::ui::{context, Ui};
use adw::prelude::*;
use gtk::glib::BoxedAnyObject;
use gtk::{gdk, gio, glib, pango};
use std::cell::{Cell, RefCell};
use std::collections::HashMap;
use std::rc::Rc;

pub fn build(ui: &Rc<Ui>) -> gtk::Widget {
    let store = gio::ListStore::new::<BoxedAnyObject>();

    let filter = {
        let query = Rc::clone(&ui.query);
        gtk::CustomFilter::new(move |obj| {
            let Some(boxed) = obj.downcast_ref::<BoxedAnyObject>() else {
                return true;
            };
            let query = query.borrow();
            if query.is_empty() {
                return true;
            }
            let needle = query.to_lowercase();
            let album = boxed.borrow::<Album>();
            album.title.to_lowercase().contains(&needle)
                || album.artist.to_lowercase().contains(&needle)
        })
    };
    let filter_model = gtk::FilterListModel::new(Some(store.clone()), Some(filter.clone()));
    let selection = gtk::NoSelection::new(Some(filter_model));

    let bound: Rc<RefCell<HashMap<String, glib::WeakRef<gtk::Picture>>>> =
        Rc::new(RefCell::new(HashMap::new()));

    let factory = gtk::SignalListItemFactory::new();
    factory.connect_setup(move |_, item| {
        let Some(item) = item.downcast_ref::<gtk::ListItem>() else {
            return;
        };
        let cell = build_album_cell();
        let gesture = gtk::GestureClick::builder().button(gdk::BUTTON_SECONDARY).build();
        let item_weak = item.downgrade();
        let anchor = cell.clone();
        gesture.connect_pressed(move |_, _, x, y| {
            let Some(item) = item_weak.upgrade() else { return };
            let Some(boxed) = item.item().and_downcast::<BoxedAnyObject>() else {
                return;
            };
            let key = boxed.borrow::<Album>().key();
            context::popup_menu_at(&anchor, &context::album_menu(&key), x, y);
        });
        cell.add_controller(gesture);
        item.set_child(Some(&cell));
    });
    {
        let ui = Rc::clone(ui);
        let bound = Rc::clone(&bound);
        factory.connect_bind(move |_, item| {
            let Some(item) = item.downcast_ref::<gtk::ListItem>() else {
                return;
            };
            let Some(cell) = item.child() else { return };
            let Some(boxed) = item.item().and_downcast::<BoxedAnyObject>() else {
                return;
            };
            let album = boxed.borrow::<Album>();
            let Some(picture) = cell.first_child().and_downcast::<gtk::Picture>() else {
                return;
            };
            let Some(title) = picture.next_sibling().and_downcast::<gtk::Label>() else {
                return;
            };
            let Some(subtitle) = title.next_sibling().and_downcast::<gtk::Label>() else {
                return;
            };
            title.set_label(&album.title);
            title.set_tooltip_text(Some(&album.title));
            subtitle.set_label(&subtitle_text(&album));
            picture.set_paintable(Some(&ui.core.artwork.placeholder(&album.key())));
            let expected = album.key();
            let item_weak = item.downgrade();
            let weak = picture.downgrade();
            ui.core.artwork.request(&album.title, &album.artist, 168, move |texture, _| {
                if let (Some(picture), Some(texture)) = (weak.upgrade(), texture) {
                    if still_bound_album(&item_weak, &expected) {
                        picture.set_paintable(Some(texture));
                    }
                }
            });
            bound.borrow_mut().insert(album.key(), picture.downgrade());
        });
    }
    {
        let bound = Rc::clone(&bound);
        factory.connect_unbind(move |_, item| {
            let Some(item) = item.downcast_ref::<gtk::ListItem>() else {
                return;
            };
            if let Some(boxed) = item.item().and_downcast::<BoxedAnyObject>() {
                bound.borrow_mut().remove(&boxed.borrow::<Album>().key());
            }
        });
    }

    let grid = gtk::GridView::builder()
        .model(&selection)
        .factory(&factory)
        .min_columns(2)
        .max_columns(10)
        .single_click_activate(true)
        .margin_top(24)
        .margin_bottom(24)
        .margin_start(24)
        .margin_end(24)
        .build();
    grid.add_css_class("album-grid");
    {
        let ui = Rc::clone(ui);
        grid.connect_activate(move |grid, position| {
            let Some(boxed) = grid
                .model()
                .and_then(|model| model.item(position))
                .and_downcast::<BoxedAnyObject>()
            else {
                return;
            };
            let album = boxed.borrow::<Album>().clone();
            push_album_detail(&ui, &album);
        });
    }

    let scroll = gtk::ScrolledWindow::builder()
        .hscrollbar_policy(gtk::PolicyType::Never)
        .vexpand(true)
        .child(&grid)
        .build();
    let grid_content = gtk::Box::new(gtk::Orientation::Vertical, 0);
    grid_content.append(&crate::ui::suggested_shelf::build(ui));
    grid_content.append(&scroll);

    let empty = adw::StatusPage::builder()
        .icon_name("audio-x-generic-symbolic")
        .title("No Music Found")
        .description("Drop FLAC or MP3 files into your music folder, then rescan.\nChoose a different folder in Preferences.")
        .build();
    let empty_actions = gtk::Box::builder()
        .orientation(gtk::Orientation::Vertical)
        .spacing(10)
        .halign(gtk::Align::Center)
        .build();
    let empty_button = gtk::Button::with_label("Choose Music Folder");
    empty_button.add_css_class("pill");
    empty_button.add_css_class("suggested-action");
    empty_button.set_action_name(Some("app.preferences"));
    empty_actions.append(&empty_button);
    let sample_button = gtk::Button::with_label("Download Sample Album");
    sample_button.add_css_class("pill");
    {
        let ui = Rc::clone(ui);
        sample_button.connect_clicked(move |_| crate::samples::download(&ui.core));
    }
    empty_actions.append(&sample_button);
    let sample_progress = gtk::Label::new(None);
    sample_progress.add_css_class("dim");
    sample_progress.add_css_class("caption");
    sample_progress.set_visible(false);
    empty_actions.append(&sample_progress);
    {
        let sample_button = sample_button.clone();
        let sample_progress_ref = sample_progress.clone();
        ui.core
            .hub
            .subscribe_widget(&empty_actions, move |_, event| {
                if let AppEvent::SampleDownload { text, done, failed } = event {
                    sample_progress_ref.set_visible(true);
                    sample_progress_ref.set_label(text);
                    sample_button.set_sensitive(*done);
                    if *done && !failed {
                        sample_button.set_label("Sample Album Added");
                    }
                }
            });
    }
    empty.set_child(Some(&empty_actions));

    let stack = gtk::Stack::new();
    stack.add_named(&empty, Some("empty"));
    stack.add_named(&grid_content, Some("grid"));

    let rebuild = {
        let store = store.clone();
        let stack = stack.clone();
        let scroll = scroll.clone();
        let ui = Rc::clone(ui);
        let applied = Cell::new(0u64);
        move || {
            let library = ui.core.library.borrow().clone();
            let fingerprint = albums_fingerprint(&library.albums);
            if applied.replace(fingerprint) != fingerprint {
                let saved = scroll.vadjustment().value();
                let items: Vec<BoxedAnyObject> = library
                    .albums
                    .iter()
                    .map(|album| BoxedAnyObject::new(album.clone()))
                    .collect();
                store.splice(0, store.n_items(), &items);
                if saved > 0.0 {
                    let adj = scroll.vadjustment();
                    glib::idle_add_local_once(move || adj.set_value(saved));
                }
            }
            stack.set_visible_child_name(if library.albums.is_empty() {
                "empty"
            } else {
                "grid"
            });
        }
    };
    rebuild();

    {
        let rebuild = rebuild.clone();
        let filter = filter.clone();
        ui.core.hub.subscribe_widget(&stack, move |_, event| match event {
            AppEvent::LibraryReloaded => rebuild(),
            AppEvent::SearchChanged(_) => filter.changed(gtk::FilterChange::Different),
            _ => {}
        });
    }

    {
        let ui = Rc::clone(ui);
        let bound = Rc::clone(&bound);
        ui.core.hub.clone().subscribe_widget(&stack, move |_, event| {
            if let AppEvent::AlbumEnriched { title, artist } = event {
                ui.core.artwork.invalidate(title, artist);
                let key = format!("{title}|{artist}");
                let picture = bound.borrow().get(&key).and_then(|w| w.upgrade());
                if let Some(picture) = picture {
                    let weak = picture.downgrade();
                    let bound = Rc::clone(&bound);
                    ui.core.artwork.request(title, artist, 168, move |texture, _| {
                        if let (Some(picture), Some(texture)) = (weak.upgrade(), texture) {
                            let still = bound
                                .borrow()
                                .get(&key)
                                .and_then(|w| w.upgrade())
                                .is_some_and(|current| current == picture);
                            if still {
                                picture.set_paintable(Some(texture));
                            }
                        }
                    });
                }
            }
        });
    }

    stack.upcast()
}

/// Digest of the album set plus the metadata the grid renders; any add,
/// removal, reorder, or enriched year/genre changes it, triggering a model
/// splice (the virtualized GridView only rebinds the handful of visible cells).
fn albums_fingerprint(albums: &[Album]) -> u64 {
    let mut hash = 0xcbf2_9ce4_8422_2325u64;
    for album in albums {
        let row = format!("{}|{}|{:?}|{:?}", album.title, album.artist, album.year, album.genre);
        hash = hash.rotate_left(5) ^ crate::palette::fnv1a_64(&row);
    }
    hash
}

fn subtitle_text(album: &Album) -> String {
    match &album.year {
        Some(year) if !year.is_empty() => format!("{} · {}", album.artist, year),
        _ => album.artist.clone(),
    }
}

/// Guards an async artwork callback against GridView cell recycling: the shared
/// tile widget may have been rebound to a different album by the time a queued
/// cover decode lands, so only paint if the list item still holds this album.
fn still_bound_album(item: &glib::WeakRef<gtk::ListItem>, expected: &str) -> bool {
    item.upgrade()
        .and_then(|item| item.item())
        .and_downcast::<BoxedAnyObject>()
        .is_some_and(|boxed| boxed.borrow::<Album>().key() == expected)
}

/// Empty tile shell reused by the GridView factory: cover picture, title, and
/// subtitle in fixed order (the bind step fills them and requests artwork).
fn build_album_cell() -> gtk::Box {
    let cell = gtk::Box::builder()
        .orientation(gtk::Orientation::Vertical)
        .spacing(8)
        .width_request(168)
        .halign(gtk::Align::Center)
        .valign(gtk::Align::Start)
        .build();
    cell.add_css_class("album-tile");

    let picture = gtk::Picture::builder()
        .width_request(168)
        .height_request(168)
        .content_fit(gtk::ContentFit::Cover)
        .build();
    picture.set_overflow(gtk::Overflow::Hidden);
    picture.add_css_class("cover");
    cell.append(&picture);

    let title = gtk::Label::builder()
        .xalign(0.0)
        .ellipsize(pango::EllipsizeMode::End)
        .max_width_chars(18)
        .build();
    title.add_css_class("album-title");
    cell.append(&title);

    let subtitle = gtk::Label::builder()
        .xalign(0.0)
        .ellipsize(pango::EllipsizeMode::End)
        .max_width_chars(20)
        .build();
    subtitle.add_css_class("dim");
    subtitle.add_css_class("caption");
    cell.append(&subtitle);

    cell
}

/// A section header announcing a physical disc or vinyl side, e.g.
/// "Side A · 4 songs · 18 min", evoking the divider between records in a set.
fn disc_header(label: &str, count: usize, duration: f64) -> gtk::Box {
    let row = gtk::Box::builder()
        .orientation(gtk::Orientation::Horizontal)
        .spacing(8)
        .margin_top(10)
        .margin_start(4)
        .margin_end(6)
        .build();
    row.add_css_class("disc-header");
    let icon = gtk::Image::from_icon_name("media-optical-symbolic");
    icon.add_css_class("disc-header-icon");
    row.append(&icon);
    let name = gtk::Label::builder().label(label).xalign(0.0).build();
    name.add_css_class("disc-header-label");
    row.append(&name);
    let songs = if count == 1 {
        "1 song".to_string()
    } else {
        format!("{count} songs")
    };
    let meta = gtk::Label::builder()
        .label(format!(
            "{songs} · {} min",
            (duration / 60.0).round().max(1.0) as i64
        ))
        .hexpand(true)
        .xalign(1.0)
        .build();
    meta.add_css_class("disc-header-meta");
    row.append(&meta);
    row
}

/// Builds one boxed track list for a slice of an album's tracks. `base` is the
/// slice's offset within `all_tracks` so activating a row queues the whole
/// album from the correct position regardless of which disc section it sits in.
fn build_track_list(
    ui: &Rc<Ui>,
    all_tracks: &Rc<Vec<Track>>,
    base: usize,
    tracks: &[Track],
) -> gtk::ListBox {
    let list = gtk::ListBox::builder()
        .selection_mode(gtk::SelectionMode::None)
        .build();
    list.add_css_class("boxed-list");
    for track in tracks {
        let row_box = gtk::Box::builder()
            .orientation(gtk::Orientation::Horizontal)
            .spacing(12)
            .margin_top(10)
            .margin_bottom(10)
            .margin_start(12)
            .margin_end(12)
            .build();
        let number = gtk::Label::builder()
            .label(if track.track_number > 0 {
                track.track_number.to_string()
            } else {
                "·".to_string()
            })
            .width_chars(3)
            .xalign(1.0)
            .build();
        number.add_css_class("track-number");
        row_box.append(&number);
        let track_title = gtk::Label::builder()
            .label(&track.title)
            .xalign(0.0)
            .hexpand(true)
            .ellipsize(pango::EllipsizeMode::End)
            .tooltip_text(&track.title)
            .build();
        row_box.append(&track_title);
        let heart = gtk::Image::from_icon_name("emote-love-symbolic");
        heart.add_css_class("loved-heart");
        heart.set_visible(track.loved);
        row_box.append(&heart);
        if let Some(badge_text) = track.quality_badge() {
            let badge = gtk::Label::new(Some(&badge_text));
            badge.add_css_class("quality-badge");
            row_box.append(&badge);
        }
        let duration = gtk::Label::new(Some(&format_time(track.duration)));
        duration.add_css_class("duration-label");
        row_box.append(&duration);

        let row = gtk::ListBoxRow::builder().child(&row_box).build();
        context::attach_track_context_menu(&row, &ui.core, track.rel_path.clone());
        {
            let rel = track.rel_path.clone();
            ui.core.hub.subscribe_widget(&heart, move |heart, event| {
                if let AppEvent::LovedChanged { rel_path, loved } = event {
                    if rel_path == &rel {
                        heart.set_visible(*loved);
                    }
                }
            });
        }
        list.append(&row);
    }
    {
        let all_tracks = Rc::clone(all_tracks);
        let ui = Rc::clone(ui);
        list.connect_row_activated(move |_, row| {
            let index = base + row.index().max(0) as usize;
            ui.core.play_tracks((*all_tracks).clone(), index);
        });
    }
    list
}

pub fn push_album_detail(ui: &Rc<Ui>, album: &Album) {
    let dominant: Rc<RefCell<Option<(u8, u8, u8)>>> = Rc::new(RefCell::new(None));

    let backdrop = gtk::DrawingArea::new();
    backdrop.set_hexpand(true);
    backdrop.set_vexpand(true);
    {
        let dominant = Rc::clone(&dominant);
        backdrop.set_draw_func(move |_, cr, width, height| {
            let Some((r, g, b)) = *dominant.borrow() else { return };
            let dark = adw::StyleManager::default().is_dark();
            let blend = |channel: u8| {
                let value = channel as f64 / 255.0;
                if dark {
                    value * 0.55
                } else {
                    value * 0.45 + 0.98 * 0.55
                }
            };
            let (r, g, b) = (blend(r), blend(g), blend(b));
            let gradient = gtk::cairo::LinearGradient::new(0.0, 0.0, 0.0, height as f64);
            gradient.add_color_stop_rgba(0.0, r, g, b, 0.85);
            gradient.add_color_stop_rgba(0.7, r, g, b, 0.0);
            let _ = cr.set_source(&gradient);
            cr.rectangle(0.0, 0.0, width as f64, height as f64);
            let _ = cr.fill();
        });
    }
    {
        let weak = backdrop.downgrade();
        adw::StyleManager::default().connect_dark_notify(move |_| {
            if let Some(backdrop) = weak.upgrade() {
                backdrop.queue_draw();
            }
        });
    }

    let header = gtk::Box::builder()
        .orientation(gtk::Orientation::Horizontal)
        .spacing(24)
        .build();

    let picture = gtk::Picture::builder()
        .width_request(232)
        .height_request(232)
        .content_fit(gtk::ContentFit::Cover)
        .valign(gtk::Align::Start)
        .build();
    picture.set_overflow(gtk::Overflow::Hidden);
    picture.add_css_class("cover-large");
    picture.set_paintable(Some(&ui.core.artwork.placeholder(&album.key())));
    {
        let weak = picture.downgrade();
        let backdrop_weak = backdrop.downgrade();
        let dominant = Rc::clone(&dominant);
        ui.core
            .artwork
            .request(&album.title, &album.artist, 232, move |texture, color| {
                if let (Some(picture), Some(texture)) = (weak.upgrade(), texture) {
                    picture.set_paintable(Some(texture));
                }
                if let Some(color) = color {
                    *dominant.borrow_mut() = Some(color);
                    if let Some(backdrop) = backdrop_weak.upgrade() {
                        backdrop.queue_draw();
                    }
                }
            });
    }
    header.append(&picture);

    let meta = gtk::Box::builder()
        .orientation(gtk::Orientation::Vertical)
        .spacing(6)
        .valign(gtk::Align::Center)
        .build();
    let title = gtk::Label::builder()
        .label(&album.title)
        .xalign(0.0)
        .wrap(true)
        .build();
    title.add_css_class("title-1");
    meta.append(&title);
    let artist = gtk::Label::builder().label(&album.artist).xalign(0.0).build();
    artist.add_css_class("title-4");
    artist.add_css_class("dim");
    meta.append(&artist);

    let info_text = |year: Option<&String>, genre: Option<&String>| {
        let mut info_parts: Vec<String> = Vec::new();
        if let Some(year) = year.filter(|y| !y.is_empty()) {
            info_parts.push(year.clone());
        }
        if let Some(genre) = genre.filter(|g| !g.is_empty()) {
            info_parts.push(genre.clone());
        }
        info_parts.push(format!(
            "{} songs · {} min",
            album.tracks.len(),
            (album.total_duration() / 60.0).round() as i64
        ));
        info_parts.join(" · ")
    };
    let info = gtk::Label::builder()
        .label(info_text(album.year.as_ref(), album.genre.as_ref()))
        .xalign(0.0)
        .build();
    info.add_css_class("dim");
    info.add_css_class("caption");
    meta.append(&info);

    let playcount = gtk::Label::builder().xalign(0.0).visible(false).build();
    playcount.add_css_class("dim");
    playcount.add_css_class("caption");
    meta.append(&playcount);
    load_user_playcount(ui, album, &playcount);

    crate::enrichment::request_album(&ui.core, &album.title, &album.artist);
    {
        let ui_ref = Rc::clone(ui);
        let album_title = album.title.clone();
        let album_artist = album.artist.clone();
        let picture_weak = picture.downgrade();
        let backdrop_weak = backdrop.downgrade();
        let dominant_ref = Rc::clone(&dominant);
        let info_for = {
            let album = album.clone();
            move |year: Option<&String>, genre: Option<&String>| {
                let mut info_parts: Vec<String> = Vec::new();
                if let Some(year) = year.filter(|y| !y.is_empty()) {
                    info_parts.push(year.clone());
                }
                if let Some(genre) = genre.filter(|g| !g.is_empty()) {
                    info_parts.push(genre.clone());
                }
                info_parts.push(format!(
                    "{} songs · {} min",
                    album.tracks.len(),
                    (album.total_duration() / 60.0).round() as i64
                ));
                info_parts.join(" · ")
            }
        };
        ui.core.hub.subscribe_widget(&info, move |info, event| {
            let AppEvent::AlbumEnriched { title, artist } = event else { return };
            if title != &album_title || artist != &album_artist {
                return;
            }
            if let Some(status) = ui_ref.core.db.album_info_status(title, artist) {
                info.set_label(&info_for(status.year.as_ref(), status.genre.as_ref()));
            }
            let picture_weak = picture_weak.clone();
            let backdrop_weak = backdrop_weak.clone();
            let dominant_ref = Rc::clone(&dominant_ref);
            ui_ref
                .core
                .artwork
                .request(title, artist, 232, move |texture, color| {
                    if let (Some(picture), Some(texture)) = (picture_weak.upgrade(), texture) {
                        picture.set_paintable(Some(texture));
                    }
                    if let Some(color) = color {
                        *dominant_ref.borrow_mut() = Some(color);
                        if let Some(backdrop) = backdrop_weak.upgrade() {
                            backdrop.queue_draw();
                        }
                    }
                });
        });
    }

    if let Some(badge_text) = album_quality_summary(album) {
        let badge = gtk::Label::new(Some(&badge_text));
        badge.add_css_class("quality-badge");
        badge.set_halign(gtk::Align::Start);
        badge.set_margin_top(4);
        meta.append(&badge);
    }

    let buttons = gtk::Box::builder()
        .orientation(gtk::Orientation::Horizontal)
        .spacing(10)
        .margin_top(12)
        .build();
    let play = gtk::Button::builder().label("Play").build();
    play.add_css_class("pill");
    play.add_css_class("suggested-action");
    play.set_action_name(Some("win.play-album"));
    play.set_action_target_value(Some(&album.key().to_variant()));
    let shuffle = gtk::Button::builder().label("Shuffle").build();
    shuffle.add_css_class("pill");
    shuffle.set_action_name(Some("win.shuffle-album"));
    shuffle.set_action_target_value(Some(&album.key().to_variant()));
    buttons.append(&play);
    buttons.append(&shuffle);
    meta.append(&buttons);
    header.append(&meta);

    let content = gtk::Box::builder()
        .orientation(gtk::Orientation::Vertical)
        .spacing(24)
        .margin_top(32)
        .margin_bottom(32)
        .margin_start(32)
        .margin_end(32)
        .build();
    content.append(&header);

    let all_tracks = Rc::new(album.tracks.clone());
    match crate::library::disc_sections(&album.tracks) {
        Some(sections) => {
            let mut base = 0usize;
            for section in &sections {
                content.append(&disc_header(
                    &section.label,
                    section.tracks.len(),
                    section.duration(),
                ));
                content.append(&build_track_list(ui, &all_tracks, base, &section.tracks));
                base += section.tracks.len();
            }
        }
        None => content.append(&build_track_list(ui, &all_tracks, 0, &album.tracks)),
    }

    let clamp = adw::Clamp::builder()
        .maximum_size(920)
        .child(&content)
        .build();
    let scroll = gtk::ScrolledWindow::builder()
        .hscrollbar_policy(gtk::PolicyType::Never)
        .child(&clamp)
        .build();

    let overlay = gtk::Overlay::new();
    overlay.set_child(Some(&backdrop));
    overlay.add_overlay(&scroll);

    let page = adw::NavigationPage::builder()
        .title(album.title.clone())
        .child(&overlay)
        .build();
    ui.nav.push(&page);
}

/// Personal Last.fm play count for this album ("You've played this N times"),
/// fetched via album.getInfo with the username param when authenticated.
fn load_user_playcount(ui: &Rc<Ui>, album: &Album, label: &gtk::Label) {
    let Some(session) = ui.core.session.borrow().clone() else { return };
    let Some(client) = crate::lastfm::LastFmClient::new(Some(session.key.clone())) else {
        return;
    };
    let artist = album.artist.clone();
    let title = album.title.clone();
    let (tx, rx) = async_channel::bounded::<Option<i64>>(1);
    std::thread::Builder::new()
        .name("flaccy-album-plays".into())
        .spawn(move || {
            let count = client
                .fetch_album_user_playcount(&artist, &title, &session.username)
                .unwrap_or(None);
            let _ = tx.send_blocking(count);
        })
        .ok();
    let weak = label.downgrade();
    gtk::glib::spawn_future_local(async move {
        let Ok(Some(count)) = rx.recv().await else { return };
        if count <= 0 {
            return;
        }
        if let Some(label) = weak.upgrade() {
            label.set_label(&format!(
                "You've played this {count} time{} on Last.fm",
                if count == 1 { "" } else { "s" }
            ));
            label.set_visible(true);
        }
    });
}

fn album_quality_summary(album: &Album) -> Option<String> {
    let badges: Vec<String> = album.tracks.iter().filter_map(|t| t.quality_badge()).collect();
    if badges.is_empty() {
        return None;
    }
    let first = &badges[0];
    if badges.iter().all(|b| b == first) {
        Some(first.clone())
    } else {
        Some("Mixed Quality".to_string())
    }
}