trill 0.7.3

Lean terminal Spotify client: Spotify's own player, small and quiet when idle
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
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
//! Application state, key handling and playback queue logic.

mod extras;

pub use extras::{Art, Chooser, LyricsSlot, LyricsState};

use std::{
    collections::{HashMap, HashSet, VecDeque},
    sync::Arc,
    time::{Duration, Instant, SystemTime},
};

use crossterm::event::{KeyCode, KeyEvent, KeyEventKind, KeyModifiers, MouseButton, MouseEvent, MouseEventKind};
use librespot_core::Session;
use ratatui::{
    layout::{Position, Rect},
    widgets::{ListState, TableState},
};
use tokio::sync::{Mutex, mpsc::UnboundedSender};

use crate::{
    api::{self, Kind, Row, Rows},
    audio::{AudioSettings, BANDS, Eq},
    auth::WebToken,
    engine::{Engine, EngineEvent},
    discover::{self, FOR_YOU},
    mpris::Remote,
};

pub enum Msg {
    Playlists(Result<Vec<(String, String, bool, bool)>, String>),
    Rows { uri: String, title: String, rows: Result<Vec<Row>, String> },
    Search { query: String, rows: Result<(Vec<Row>, &'static str), String> },
    /// Every liked track, saved album and followed artist (for the โ™ฅ markers and `f`).
    Liked(Result<HashSet<String>, String>),
    /// `P`: every track in the open list, ready to play.
    PlayAll(Result<Vec<Row>, String>),
    LikeDone { row: Row, liked: bool, res: Result<(), String> },
    Lyrics { uri: String, res: Result<Option<crate::library::Lyrics>, String> },
    /// `header`: the picture over an album or artist (else the now-playing cover).
    Art { url: String, size: (u16, u16), header: bool, res: Result<(ratatui_image::protocol::Protocol, bytes::Bytes), String> },
    /// The header details of an album or artist page.
    Info { uri: String, res: Result<api::Info, String> },
    NextArt { url: String, bytes: bytes::Bytes },
    Private { on: bool, was: u64, res: Result<(), String> },
    /// `u` / `U`: the album or artist to open (uri, title).
    Home(Result<(String, String), String>),
    /// The pause around `I` has had time to reach Discord; `apply`: switch private on now.
    PrivateGo { apply: bool },
    /// Accent colour picked from a cover (`None`: black-and-white cover).
    Tint { url: String, tint: Option<[u8; 3]> },
    /// A newer trill release is out (its tag).
    Update(String),
    PlaylistEdit { playlist: String, name: String, row: Row, add: bool, res: Result<(), String> },
    /// Smart-shuffle recommendations for the list `list`.
    Recs { list: String, rows: Vec<Row> },
    /// The playlists (not already loaded) that hold the song "Add to playlist" is open for.
    Holding { track: String, playlists: Vec<String> },
}

/// Put one of `recs` after every 3 entries of `order[from..]`; leftovers aren't used.
fn weave(order: &mut Vec<usize>, from: usize, mut recs: std::ops::Range<usize>) {
    let tail = order.split_off(from.min(order.len()));
    for (i, t) in tail.into_iter().enumerate() {
        order.push(t);
        if i % 3 == 2
            && let Some(r) = recs.next()
        {
            order.push(r);
        }
    }
}

/// Sidebar entries above the playlists: Liked Songs, Albums, Artists, For You, Queue, Search.
const FIXED_SIDE: usize = 6;
/// For You is worked out again when it's opened this long after the last time (or on `R`).
const FOR_YOU_FRESH: Duration = Duration::from_secs(12 * 3600);

#[derive(Clone, Copy, PartialEq, Eq)]
pub enum Focus {
    Side,
    Main,
    Input,
}

/// What the bottom-line input box is for.
#[derive(Clone, Copy, PartialEq, Eq)]
pub enum InputMode {
    /// `/`: search Spotify.
    Search,
    /// `F`: narrow the open list as you type.
    Find,
}

/// Sleep timer steps for `z`; after the last comes "end of this song", then off.
const SLEEP_MINUTES: [u64; 5] = [15, 30, 45, 60, 90];
/// How long the volume takes to fade out before the sleep timer pauses.
const SLEEP_FADE: Duration = Duration::from_secs(8);

/// `z`: pause after a while, fading out first.
pub struct SleepTimer {
    /// Index into [`SLEEP_MINUTES`], or its length for "end of this song".
    step: usize,
    /// When to pause; None: at the end of the song playing.
    pub until: Option<Instant>,
}

#[derive(Clone, Copy, PartialEq, Eq)]
pub enum Repeat {
    Off,
    All,
    One,
}

/// How playlists / liked songs are ordered on screen (and therefore played).
/// Same order as [`crate::audio::SORTS`], which names them in the settings file.
#[derive(Clone, Copy, PartialEq, Eq)]
pub enum Sort {
    /// Most recently added first (default).
    Added,
    /// The playlist's own order.
    Original,
    Title,
    Artist,
    Album,
    Duration,
}

impl Sort {
    const ALL: [Sort; 6] = [Sort::Added, Sort::Original, Sort::Title, Sort::Artist, Sort::Album, Sort::Duration];

    fn label(self) -> &'static str {
        match self {
            Sort::Added => "newest first",
            Sort::Original => "playlist order",
            Sort::Title => "by title",
            Sort::Artist => "by artist",
            Sort::Album => "by album",
            Sort::Duration => "by length",
        }
    }
}

/// Apply the sort mode to playlists and liked songs (albums/artists keep their order).
/// Sorts are stable, so ties keep the playlist's order.
/// "10 tracks ยท 7 albums" for the status line.
pub fn unix_now() -> u64 {
    SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0)
}

/// Same songs in the same order, added at the same times.
fn same_rows(a: &[Row], b: &[Row]) -> bool {
    a.len() == b.len() && a.iter().zip(b).all(|(x, y)| x.uri == y.uri && x.added_at == y.added_at)
}

fn count(rows: &[Row]) -> String {
    let parts: Vec<String> = [(Kind::Track, "track"), (Kind::Album, "album"), (Kind::Playlist, "playlist"), (Kind::Artist, "artist")]
        .into_iter()
        .filter_map(|(k, name)| {
            let n = rows.iter().filter(|r| r.kind == k).count();
            (n > 0).then(|| format!("{n} {name}{}", if n == 1 { "" } else { "s" }))
        })
        .collect();
    if parts.is_empty() { "empty".into() } else { parts.join(" ยท ") }
}

/// Playlists and the library sets can be re-sorted; albums, artist pages and search keep their order.
fn sortable(uri: &str) -> bool {
    uri.starts_with("spotify:playlist:") || uri.contains(":collection")
}

/// The rows of `all` that match `find` (case-insensitive, in title, artist or album).
fn found(all: &Rows, find: &str) -> Rows {
    if find.is_empty() {
        return all.clone();
    }
    let q = find.to_lowercase();
    Arc::new(all.iter().filter(|r| [&r.title, &r.artist, &r.album].iter().any(|f| f.to_lowercase().contains(&q))).cloned().collect())
}

fn sorted(sort: Sort, uri: &str, rows: Rows) -> (Rows, Option<&'static str>) {
    let label = Some(sort.label());
    match sort {
        _ if !sortable(uri) => (rows, None),
        Sort::Original => (rows, None),
        Sort::Added if !rows.iter().any(|r| r.added_at > 0) => (rows, None),
        // already newest-first (liked songs): no copy
        Sort::Added if rows.windows(2).all(|w| w[0].added_at >= w[1].added_at) => (rows, label),
        sort => {
            let mut v = (*rows).clone();
            let low = |s: &str| s.to_lowercase();
            match sort {
                Sort::Title => v.sort_by_cached_key(|r| low(&r.title)),
                Sort::Artist => v.sort_by_cached_key(|r| (low(&r.artist), low(&r.album))),
                Sort::Album => v.sort_by_cached_key(|r| (low(&r.album), low(&r.artist))),
                Sort::Duration => v.sort_by_key(|r| r.duration_ms),
                _ => v.sort_by_key(|r| std::cmp::Reverse(r.added_at)),
            }
            (Arc::new(v), label)
        }
    }
}

#[derive(Clone, Copy, PartialEq, Eq)]
pub enum SideKind {
    Liked,
    ForYou,
    Queue,
    Search,
    Playlist,
}

pub struct SideItem {
    pub name: String,
    pub uri: String,
    pub kind: SideKind,
    /// Playlist we can add songs to / remove songs from.
    pub editable: bool,
    /// Pinned to the top of Your Library.
    pub pinned: bool,
}

/// What a row in the Queue view refers to, so Enter can act on it.
#[derive(Clone, Copy)]
enum QSrc {
    Now,
    Manual(usize),
    Upcoming(usize), // position in `order`
}

pub struct View {
    pub uri: String,
    pub title: String,
    /// The rows shown: `all`, narrowed by `find`.
    pub rows: Rows,
    /// Every row of the list, sorted.
    pub all: Rows,
    /// `F`: only rows matching this are shown.
    pub find: String,
    pub state: TableState,
    /// The sort applied to the rows, for the header (None: their own order).
    pub sort: Option<&'static str>,
}

impl View {
    fn empty(uri: String, title: String) -> Self {
        View { uri, title, rows: Arc::default(), all: Arc::default(), find: String::new(), state: TableState::default(), sort: None }
    }
}

impl View {
    /// Select row `sel` again after the rows changed, or the last one if the list got shorter.
    fn reselect(&mut self, sel: Option<usize>) {
        let len = self.rows.len();
        self.state.select(sel.map(|i| i.min(len.saturating_sub(1))).filter(|_| len > 0));
    }
}

pub struct App {
    pub session: Session,
    pub engine: Engine,
    pub web: Option<Arc<Mutex<WebToken>>>,
    tx: UnboundedSender<Msg>,

    pub side: Vec<SideItem>,
    pub side_state: ListState,
    pub view: View,
    back: Vec<View>,
    queue_src: Vec<QSrc>,
    cache: HashMap<String, Rows>,
    pending: Option<String>,
    search_rows: Rows,
    pub search_title: String,

    pub sort: Sort,
    pub audio: AudioSettings,
    pub eq: Option<Eq>,
    /// `eq = off` in config disables the EQ entirely.
    pub eq_allowed: bool,
    /// Why trill fell back to librespot instead of Soloist (auto backend), if it did.
    pub soloist_missing: Option<String>,
    /// Where the playlist list is cached so the sidebar fills instantly on start.
    pub cache_dir: Option<std::path::PathBuf>,
    /// Where settings, the play log and "not interested" live.
    pub data_dir: Option<std::path::PathBuf>,
    /// Songs never to suggest again (`X`).
    pub not_interested: HashSet<String>,
    /// The song whose play is already in the log (it's logged once it has played 30 s).
    logged: Option<String>,
    /// Tag of a newer trill release, shown in the title bar.
    pub update: Option<String>,
    /// EQ panel open, with this band selected.
    pub eq_panel: Option<usize>,
    /// `?`: the key help pane is open; any key closes it.
    pub help_open: bool,
    /// When to restart Soloist to apply a crossfade change (debounced).
    pub restart_at: Option<Instant>,
    /// End of the private session (unix seconds), shared with the relay that hides Soloist.
    pub private_shared: Arc<std::sync::atomic::AtomicU64>,
    /// Soloist runs through the relay; `want_relay` asks the main loop to start it.
    pub relay_on: bool,
    pub want_relay: bool,
    /// `I` paused playback and waits for `Msg::PrivateGo` to resume it.
    going_private: bool,
    /// After a restart: the position to resume at, and until when to keep correcting
    /// Soloist if it reports playing well before it (a fresh Soloist can start the track
    /// from 0 after accepting our seek). A track change or seek by the user cancels it.
    pending_seek: Option<(u32, Instant, Instant)>, // (position, keep correcting until, last seek)
    /// After a restart while paused: reload this position on the next play.
    reload_at: Option<u32>,
    /// Ignore stale "Soloist stopped" messages from the old process.
    quiet_until: Instant,
    /// When Soloist last died on its own and was started again (at most once a minute).
    revived_at: Option<Instant>,
    pub focus: Focus,
    pub input: String,
    pub input_mode: InputMode,
    /// Which past search โ†‘/โ†“ brought back into the search box.
    history_at: Option<usize>,
    pub sleep: Option<SleepTimer>,
    pub status: String,
    pub loading: bool,
    pub quit: bool,

    // playback
    /// The list playing. `order` indexes `ctx` and then `recs` (see [`App::at`]).
    ctx: Rows,
    /// Smart-shuffle recommendations, kept apart so a big list isn't copied to add them.
    recs: Vec<Row>,
    /// The list the playing context came from (uri, title), for `w`.
    ctx_src: (String, String),
    /// `w` opened that list: select the playing song once it's shown.
    jump: bool,
    order: Vec<usize>,
    cursor: usize,
    pub queue: VecDeque<Row>,
    pub now: Option<Row>,
    pub playing: bool,
    pos_ms: u32,
    pos_at: Instant,
    /// The last seek (target, when): Soloist's report for an earlier seek can arrive after it.
    seeked: Option<(u32, Instant)>,
    /// Soloist: the uri we asked for and when; transitional events are ignored until it starts.
    awaiting: Option<(String, Instant)>,
    /// Soloist: the next track we already put in Soloist's own queue (so it switches
    /// gaplessly instead of autoplaying). Soloist can't un-queue, so we track it to consume it.
    ahead: Option<String>,
    vol: u32,
    vol_set_at: Instant,
    skips: u32,
    pub shuffle: bool,
    /// Smart shuffle: a recommendation after every few songs (only with `shuffle`).
    pub smart: bool,
    pub repeat: Repeat,
    rng: u64,

    // library, lyrics, art
    pub liked: HashSet<String>,
    pub lyrics_open: bool,
    pub lyrics: Option<LyricsSlot>,
    /// Terminal image support (None = art disabled).
    pub img_picker: Option<ratatui_image::picker::Picker>,
    pub art_on: bool,
    pub theme: usize,
    /// (cover url, its colour) for the `cover` theme.
    pub tint: Option<(String, Option<[u8; 3]>)>,
    pub art: Option<Art>,
    /// The next song's cover (url, bytes), fetched while this one ends so it shows at once.
    next_art: Option<(String, bytes::Bytes)>,
    /// Cell size the UI has room for (set while drawing).
    pub art_want: Option<(u16, u16)>,
    /// Album and artist page headers, by uri (an empty one while it loads).
    pub infos: HashMap<String, api::Info>,
    /// The header's picture, and the cell size the UI has room for it.
    pub info_art: Option<Art>,
    pub info_want: Option<(u16, u16)>,
    /// The lyrics lines last drawn and the first one's index (for clicks).
    pub lyrics_rows: (Rect, usize),
    /// Where the last frame drew the sidebar list, the track table and the progress bar (for clicks).
    pub side_area: Rect,
    pub main_area: Rect,
    pub bar_area: Rect,
    /// The โ‡„ โ†ป โŠ˜ icons on the now-playing line, clicked like their keys.
    pub flag_areas: [Rect; 3],
    /// The open EQ panel or playlist picker: its whole box, and its list rows with their scroll.
    pub popup_area: Rect,
    pub popup_rows: (Rect, usize),
    /// Last click on a table row (when, row), to spot a double-click.
    last_click: Option<(Instant, usize)>,
    /// "Add to playlist" popup.
    pub chooser: Option<Chooser>,
    /// From `remap =` in the config: in the lists, this key acts as that one.
    pub remap: HashMap<KeyCode, KeyCode>,
    /// First `D` press: (track uri, when) โ€” the second press within a few seconds removes.
    confirm_remove: Option<(String, Instant)>,
}

const SEEK_MS: u32 = 10_000;

fn for_you_status(n: usize) -> String {
    format!("For You: {n} songs from what you play, worked out here. X: not interested ยท R: new picks")
}

fn playlists_status(n: usize) -> String {
    format!("{n} playlists. Tab to switch panes, / to search, ? for keys.")
}
const VOL_STEP: u32 = 5; // percent

impl App {
    pub fn new(
        session: Session,
        engine: Engine,
        vol: u32,
        web: Option<Arc<Mutex<WebToken>>>,
        tx: UnboundedSender<Msg>,
        audio: AudioSettings,
        eq: Option<Eq>,
    ) -> Self {
        let user = session.username();
        let (shuffle, smart, sort) = (audio.shuffle, audio.smart, Sort::ALL[(audio.sort as usize).min(Sort::ALL.len() - 1)]);
        let repeat = [Repeat::Off, Repeat::All, Repeat::One][audio.repeat.min(2) as usize];
        engine.set_repeat_track(repeat == Repeat::One);
        let (theme, tint) = (audio.theme, audio.tint.map(|c| (String::new(), Some(c))));
        let side = vec![
            SideItem { name: "โ™ฅ Liked Songs".into(), uri: format!("spotify:user:{user}:collection"), kind: SideKind::Liked, editable: false, pinned: false },
            SideItem { name: "โ—‰ Albums".into(), uri: api::SAVED_ALBUMS.into(), kind: SideKind::Liked, editable: false, pinned: false },
            SideItem { name: "โ—ˆ Artists".into(), uri: api::FOLLOWED_ARTISTS.into(), kind: SideKind::Liked, editable: false, pinned: false },
            SideItem { name: "โœฆ For You".into(), uri: FOR_YOU.into(), kind: SideKind::ForYou, editable: false, pinned: false },
            SideItem { name: "โ‰ก Queue".into(), uri: "trill:queue".into(), kind: SideKind::Queue, editable: false, pinned: false },
            SideItem { name: "โŒ• Search".into(), uri: "trill:search".into(), kind: SideKind::Search, editable: false, pinned: false },
        ];
        let seed = SystemTime::now()
            .duration_since(SystemTime::UNIX_EPOCH)
            .map(|d| d.as_nanos() as u64)
            .unwrap_or(0x9E37_79B9_7F4A_7C15)
            | 1;
        
        App {
            session,
            engine,
            web,
            tx,
            side,
            side_state: ListState::default().with_selected(Some(0)),
            view: View::empty(String::new(), "trill".into()),
            back: Vec::new(),
            queue_src: Vec::new(),
            cache: HashMap::new(),
            pending: None,
            search_rows: Arc::new(Vec::new()),
            search_title: "Search".into(),
            sort,
            audio,
            eq,
            eq_allowed: true,
            cache_dir: None,
            data_dir: None,
            not_interested: HashSet::new(),
            logged: None,
            update: None,
            eq_panel: None,
            help_open: false,
            soloist_missing: None,
            restart_at: None,
            private_shared: Arc::default(),
            relay_on: false,
            want_relay: false,
            going_private: false,
            pending_seek: None,
            reload_at: None,
            quiet_until: Instant::now(),
            revived_at: None,
            focus: Focus::Side,
            input: String::new(),
            input_mode: InputMode::Search,
            history_at: None,
            sleep: None,
            status: "Loading playlistsโ€ฆ".into(),
            loading: false,
            quit: false,
            ctx: Arc::new(Vec::new()),
            recs: Vec::new(),
            ctx_src: (String::new(), String::new()),
            jump: false,
            order: Vec::new(),
            cursor: 0,
            queue: VecDeque::new(),
            now: None,
            playing: false,
            pos_ms: 0,
            pos_at: Instant::now(),
            seeked: None,
            awaiting: None,
            ahead: None,
            vol,
            vol_set_at: Instant::now().checked_sub(std::time::Duration::from_secs(10)).unwrap_or_else(Instant::now),
            skips: 0,
            shuffle,
            smart: shuffle && smart,
            repeat,
            rng: seed,
            liked: HashSet::new(),
            lyrics_open: false,
            lyrics: None,
            img_picker: None,
            art_on: true,
            theme,
            tint,
            art: None,
            next_art: None,
            art_want: None,
            infos: HashMap::new(),
            info_art: None,
            info_want: None,
            lyrics_rows: (Rect::default(), 0),
            side_area: Rect::default(),
            main_area: Rect::default(),
            bar_area: Rect::default(),
            flag_areas: [Rect::default(); 3],
            popup_area: Rect::default(),
            popup_rows: (Rect::default(), 0),
            last_click: None,
            chooser: None,
            remap: HashMap::new(),
            confirm_remove: None,
        }
    }

    // ---------------------------------------------------------------- data loading

    /// Shows the cached playlist list right away (if any), then refreshes it.
    pub fn load_playlists(&mut self) {
        if self.side.len() <= FIXED_SIDE
            && let Some(list) = self.cache_dir.as_deref().and_then(api::read_playlist_cache)
        {
            self.set_playlists(list);
            self.status = playlists_status(self.side.len() - FIXED_SIDE);
        }
        let (s, tx) = (self.session.clone(), self.tx.clone());
        tokio::spawn(async move {
            let _ = tx.send(Msg::Playlists(api::playlists(&s).await));
        });
    }

    /// Replace the playlists in the sidebar, keeping the selected item selected.
    fn set_playlists(&mut self, list: Vec<(String, String, bool, bool)>) {
        let sel = self.side_state.selected().and_then(|i| self.side.get(i)).map(|s| s.uri.clone());
        self.side.truncate(FIXED_SIDE);
        self.side.extend(list.into_iter().map(|(uri, name, editable, pinned)| SideItem { name, uri, kind: SideKind::Playlist, editable, pinned }));
        let i = sel.and_then(|u| self.side.iter().position(|s| s.uri == u)).unwrap_or(0);
        self.side_state.select(Some(i.min(self.side.len() - 1)));
    }

    pub(crate) fn open(&mut self, uri: String, title: String, push_back: bool, force: bool) {
        self.lyrics_open = false; // the lyrics view would hide the list being opened
        if push_back && !self.view.uri.is_empty() {
            let prev = std::mem::replace(&mut self.view, View::empty(String::new(), String::new()));
            self.back.push(prev);
            if self.back.len() > 20 {
                self.back.remove(0);
            }
        }
        if !force && uri != FOR_YOU && let Some(rows) = self.cache.get(&uri).cloned() {
            self.show(uri, title, rows);
            return;
        }
        // For You from disk, as it was last worked out, unless that was a while ago
        if !force
            && uri == FOR_YOU
            && let Some(dir) = self.cache_dir.as_deref()
            && api::list_age(dir, &uri).is_some_and(|a| a < FOR_YOU_FRESH)
            && let Some(rows) = api::read_list_cache(dir, &uri)
        {
            let rows: Rows = Arc::new(rows);
            self.cache.insert(uri.clone(), rows.clone()); // so `X` can take songs out of it
            self.status = for_you_status(rows.len());
            self.show(uri, title, rows);
            return;
        }
        // Loaded in an earlier run: show that copy now; a fresh one replaces it if it changed.
        if !force && let Some(rows) = self.cache_dir.as_deref().and_then(|d| api::read_list_cache(d, &uri)) {
            let rows: Rows = Arc::new(rows);
            if rows.len() > 500 {
                crate::trim_heap();
            }
            self.cache.insert(uri.clone(), rows.clone());
            self.status = format!("{title}: {}", count(&rows));
            self.show(uri.clone(), title.clone(), rows.clone());
            self.fetch_rows(uri, title, rows);
            return;
        }
        let known = self.cache.get(&uri).cloned().unwrap_or_default();
        self.view.uri = uri.clone();
        self.view.title = title.clone();
        self.view.rows = Arc::new(Vec::new());
        self.view.all = Arc::new(Vec::new());
        self.view.find = String::new();
        self.view.state = TableState::default();
        self.loading = true;
        self.status = format!("Loading {title}โ€ฆ");
        self.pending = Some(uri.clone());
        self.fetch_rows(uri, title, known);
    }

    /// Load a list; `known` rows (an older copy) spare re-fetching their songs' details.
    fn fetch_rows(&self, uri: String, title: String, known: Rows) {
        let (s, tx) = (self.session.clone(), self.tx.clone());
        if uri == FOR_YOU {
            let Some(dir) = self.data_dir.clone() else { return };
            let liked = self.cache.get(&self.liked_uri()).cloned().or_else(|| {
                self.cache_dir.as_deref().and_then(|d| api::read_list_cache(d, &self.liked_uri())).map(Arc::new)
            });
            let exclude: HashSet<String> = self.liked.iter().chain(&self.not_interested).cloned().collect();
            tokio::spawn(async move {
                let rows = discover::for_you(&s, &dir, liked.unwrap_or_default(), exclude).await;
                let _ = tx.send(Msg::Rows { uri, title, rows });
            });
            return;
        }
        tokio::spawn(async move {
            let rows = api::context_rows(&s, &uri, &known).await;
            let _ = tx.send(Msg::Rows { uri, title, rows });
        });
    }

    fn show(&mut self, uri: String, title: String, rows: Rows) {
        // another list still loading mustn't replace this one when it arrives
        if self.pending.as_deref() != Some(uri.as_str()) {
            self.pending = None;
            self.loading = false;
        }
        let (all, sort) = sorted(self.sort_for(&uri), &uri, rows);
        // a fresh copy of the list on screen keeps what it's narrowed to
        let find = if self.view.uri == uri { std::mem::take(&mut self.view.find) } else { String::new() };
        let rows = found(&all, &find);
        let sel = if rows.is_empty() { None } else { Some(0) };
        self.view = View { uri, title, rows, all, find, state: TableState::default().with_selected(sel), sort };
        // `w` opened the list, but the song has since left it
        if std::mem::take(&mut self.jump) && !self.select_now() {
            self.show_now_in_queue();
        }
    }

    /// `w`: show the playing song in the list it's playing from.
    fn jump_to_now(&mut self) {
        if self.now.is_none() {
            self.status = "Nothing is playing.".into();
            return;
        }
        self.lyrics_open = false;
        self.focus = Focus::Main;
        if self.select_now() {
            return;
        }
        let (uri, title) = self.ctx_src.clone();
        if !self.now.as_ref().is_some_and(|n| self.ctx.iter().any(|r| r.uri == n.uri)) {
            // A recommendation, or a song started elsewhere: it's in no list we know of.
            self.show_now_in_queue();
            return;
        }
        match uri.as_str() {
            "trill:search" => {
                let rows = self.search_rows.clone();
                self.jump = true;
                self.show(uri, title, rows);
            }
            _ => {
                self.jump = true;
                self.open(uri, title, true, false);
            }
        }
    }

    /// The playing song isn't in a list: show it atop the queue, where `f` and `A` act on it.
    fn show_now_in_queue(&mut self) {
        let Some(uri) = self.now.as_ref().map(|r| r.uri.clone()) else { return };
        self.show_queue();
        self.status = match self.ctx_src.1.as_str() {
            _ if !self.is_rec(&uri) => "This song isn't in a list you're playing. f likes it, A adds it to a playlist.".into(),
            "" => "โœฆ a recommendation. f likes it, A adds it to a playlist.".into(),
            list => format!("โœฆ recommended while playing {list}. f likes it, A adds it."),
        };
    }

    /// Select the playing song if the open list has it.
    fn select_now(&mut self) -> bool {
        let Some(now) = self.now.as_ref() else { return false };
        let Some(i) = self.view.rows.iter().position(|r| r.uri == now.uri) else { return false };
        self.view.state.select(Some(i));
        true
    }

    /// The order list `uri` is shown in: its own, else the default.
    fn sort_for(&self, uri: &str) -> Sort {
        self.audio.sorts.get(uri).map_or(self.sort, |&i| Sort::ALL[(i as usize).min(Sort::ALL.len() - 1)])
    }

    /// Step through the sort modes for the open list (`back`: the other way round); each list
    /// remembers its own.
    fn cycle_sort(&mut self, back: bool) {
        let uri = self.view.uri.clone();
        if !sortable(&uri) {
            self.status = "This list keeps its own order (playlists and your library can be sorted).".into();
            return;
        }
        let n = Sort::ALL.len();
        let sort = Sort::ALL[(self.sort_for(&uri) as usize + if back { n - 1 } else { 1 }) % n];
        if sort == self.sort {
            self.audio.sorts.remove(&uri);
        } else {
            self.audio.sorts.insert(uri.clone(), sort as u8);
        }
        self.save_prefs();
        self.status = format!("Sort: {}", sort.label());
        let Some(orig) = self.cache.get(&self.view.uri).cloned() else { return };
        let keep = self.view.state.selected().and_then(|i| self.view.rows.get(i)).map(|r| r.uri.clone());
        let (uri, title) = (self.view.uri.clone(), self.view.title.clone());
        self.show(uri, title, orig);
        if let Some(k) = keep
            && let Some(i) = self.view.rows.iter().position(|r| r.uri == k)
        {
            self.view.state.select(Some(i));
        }
    }

    fn open_side(&mut self) {
        let Some(i) = self.side_state.selected() else { return };
        let item = &self.side[i];
        let (uri, name, kind) = (item.uri.clone(), item.name.clone(), item.kind);
        self.back.clear();
        self.lyrics_open = false;
        match kind {
            SideKind::Queue => self.show_queue(),
            SideKind::Search => {
                let rows = self.search_rows.clone();
                self.show("trill:search".into(), self.search_title.clone(), rows);
            }
            SideKind::Liked | SideKind::Playlist | SideKind::ForYou => self.open(uri, name, false, false),
        }
        // Picking "Search" means "I want to search": open the search box right away.
        self.focus = if kind == SideKind::Search { Focus::Input } else { Focus::Main };
    }

    /// The play order changed: rebuild the Queue view if it's open, so its rows still match.
    pub(super) fn refresh_queue_view(&mut self) {
        if self.view.uri == "trill:queue" {
            let sel = self.view.state.selected();
            self.show_queue();
            self.view.reselect(sel);
        }
    }

    fn show_queue(&mut self) {
        let mut rows = Vec::new();
        self.queue_src.clear();
        if let Some(now) = &self.now {
            rows.push(now.clone());
            self.queue_src.push(QSrc::Now);
        }
        for (i, r) in self.queue.iter().enumerate() {
            rows.push(r.clone());
            self.queue_src.push(QSrc::Manual(i));
        }
        let start = if self.now.is_some() { self.cursor + 1 } else { self.cursor };
        for p in start..(start + 100).min(self.order.len()) {
            rows.push(self.at(self.order[p]).clone());
            self.queue_src.push(QSrc::Upcoming(p));
        }
        self.show("trill:queue".into(), format!("Queue โ€” {} manual, {} upcoming", self.queue.len(), rows.len().saturating_sub(self.queue.len() + self.now.is_some() as usize)), Arc::new(rows));
    }

    pub fn on_msg(&mut self, msg: Msg) {
        match msg {
            Msg::Playlists(Ok(list)) => {
                if let Some(d) = &self.cache_dir {
                    api::write_playlist_cache(d, &list);
                }
                let had_cached = self.side.len() > FIXED_SIDE;
                let n = list.len();
                self.set_playlists(list);
                if !had_cached {
                    self.status = playlists_status(n);
                }
            }
            Msg::Playlists(Err(e)) => self.status = format!("Couldn't load playlists: {e}  (R to retry)"),
            Msg::Rows { uri, title, rows } => {
                let is_current = self.pending.as_deref() == Some(uri.as_str());
                match rows {
                    Ok(rows) => {
                        let big = rows.len() > 500;
                        let rows: Rows = Arc::new(rows);
                        if uri == self.liked_uri() {
                            self.liked = rows.iter().map(|r| r.uri.clone()).collect();
                        }
                        let old = self.cache.insert(uri.clone(), rows.clone());
                        let changed = !old.as_deref().is_some_and(|o| same_rows(o, &rows));
                        if changed && let Some(d) = self.cache_dir.as_deref() {
                            api::write_list_cache(d, &uri, &rows);
                        }
                        if big {
                            // Loading a big list decodes megabytes of protobuf that is freed
                            // right away; hand those pages back to the OS instead of keeping them.
                            crate::trim_heap();
                        }
                        if is_current {
                            self.status = if uri == FOR_YOU { for_you_status(rows.len()) } else { format!("{title}: {}", count(&rows)) };
                            self.show(uri, title, rows);
                        } else if changed && self.view.uri == uri {
                            // The copy on screen came from disk; this is the fresh one.
                            self.status = format!("{title}: {} (updated)", count(&rows));
                            self.replace_view_rows(rows);
                        }
                    }
                    Err(e) if is_current => self.status = format!("Couldn't load {title}: {e}  (R to retry)"),
                    // the copy on screen came from disk and stays
                    Err(e) if self.view.uri == uri => self.status = format!("{title}: saved copy, couldn't refresh it: {e}"),
                    Err(_) => {}
                }
                if is_current {
                    self.loading = false;
                    self.pending = None;
                }
            }
            Msg::Search { query, rows } => {
                self.loading = false;
                match rows {
                    Ok((rows, via)) => {
                        self.lyrics_open = false; // results replace whatever covers the list
                        let via = if via == "basic" { "no playlists: set client_id for those" } else { via };
                        self.status = format!("{} results for โ€œ{query}โ€ ({via})", rows.len());
                        self.search_title = format!("Search: {query}");
                        self.search_rows = Arc::new(rows);
                        self.back.clear();
                        self.show("trill:search".into(), self.search_title.clone(), self.search_rows.clone());
                        self.focus = Focus::Main;
                        if let Some(i) = self.side.iter().position(|s| s.kind == SideKind::Search) {
                            self.side_state.select(Some(i));
                        }
                    }
                    Err(e) => self.status = format!("Search failed: {e}"),
                }
            }
            other => self.on_extra_msg(other),
        }
    }

    fn search(&mut self, q: String) {
        if q.trim().is_empty() {
            return;
        }
        self.audio.searches.retain(|s| *s != q);
        self.audio.searches.insert(0, q.clone());
        self.audio.searches.truncate(crate::audio::SEARCHES);
        self.audio.save();
        self.loading = true;
        self.status = format!("Searching โ€œ{q}โ€โ€ฆ");
        let (s, tx, web) = (self.session.clone(), self.tx.clone(), self.web.clone());
        tokio::spawn(async move {
            let rows = api::search(&s, web, &q).await;
            let _ = tx.send(Msg::Search { query: q, rows });
        });
    }

    // ---------------------------------------------------------------- playback

    pub fn position_ms(&self) -> u32 {
        if self.playing {
            self.pos_ms.saturating_add(self.pos_at.elapsed().as_millis() as u32)
        } else {
            self.pos_ms
        }
    }

    fn rand(&mut self) -> u64 {
        // xorshift64*: plenty for shuffling a playlist
        self.rng ^= self.rng >> 12;
        self.rng ^= self.rng << 25;
        self.rng ^= self.rng >> 27;
        self.rng.wrapping_mul(0x2545_F491_4F6C_DD1D)
    }

    /// Rebuild `order`, keeping the current track at the cursor.
    fn reorder(&mut self, keep: Option<usize>) {
        self.order = (0..self.ctx.len()).collect();
        if self.shuffle {
            for i in (1..self.order.len()).rev() {
                let j = (self.rand() % (i as u64 + 1)) as usize;
                self.order.swap(i, j);
            }
            if let Some(k) = keep
                && let Some(p) = self.order.iter().position(|&x| x == k)
            {
                self.order.swap(0, p);
            }
            self.cursor = 0;
        } else {
            self.cursor = keep.unwrap_or(0);
        }
    }

    /// Smart shuffle: one recommendation after every 3 songs still to come.
    fn weave(&mut self) {
        if self.smart {
            let n = self.ctx.len();
            weave(&mut self.order, self.cursor + 1, n..n + self.recs.len());
        }
    }

    /// Whether `uri` is playing as a smart-shuffle recommendation (shown with โœฆ).
    pub fn is_rec(&self, uri: &str) -> bool {
        self.recs.iter().any(|r| r.uri == uri)
    }

    /// Entry `i` of the play order's index space: the list, then the recommendations.
    fn at(&self, i: usize) -> &Row {
        self.ctx.get(i).unwrap_or_else(|| &self.recs[i - self.ctx.len()])
    }

    fn fetch_recs(&self) {
        let (s, tx, list) = (self.session.clone(), self.tx.clone(), self.ctx_src.0.clone());
        let Some(track) = self.now.as_ref().or(self.ctx.first()).map(|r| r.uri.clone()) else { return };
        tokio::spawn(async move {
            let rows = api::recommendations(&s, &list, &track).await;
            let _ = tx.send(Msg::Recs { list, rows });
        });
    }

    fn load(&mut self, row: Row) {
        self.pending_seek = None; // a resume belongs to the track it was set for
        self.reload_at = None;
        self.seeked = None;
        if self.engine.is_soloist() && self.ahead.take().is_some() {
            // Burn the pre-queued track so it can't play later; `play` follows immediately.
            self.engine.skip_next();
        }
        self.engine.load(&row.uri);
        if self.engine.is_soloist() {
            self.awaiting = Some((row.uri.clone(), Instant::now()));
        }
        self.pos_ms = 0;
        self.pos_at = Instant::now();
        self.now = Some(row);
    }

    /// Play `rows[idx]`, making the track rows of that list the playback context.
    fn play_list(&mut self, rows: &Rows, idx: usize) {
        let tracks: Vec<Row> = rows.iter().filter(|r| r.kind == Kind::Track).cloned().collect();
        let target = &rows[idx].uri;
        let before = rows[..idx].iter().filter(|r| r.kind == Kind::Track).count();
        let pos = if tracks.get(before).map(|r| &r.uri) == Some(target) { before } else { 0 };
        self.ctx = if tracks.len() == rows.len() { rows.clone() } else { Arc::new(tracks) };
        self.ctx_src = (self.view.uri.clone(), self.view.title.clone());
        self.recs.clear();
        self.reorder(Some(pos));
        self.skips = 0;
        let row = self.at(self.order[self.cursor]).clone();
        self.load(row);
        if self.smart {
            self.fetch_recs();
        }
    }

    fn peek_next(&self) -> Option<Row> {
        if self.repeat == Repeat::One {
            return self.now.clone();
        }
        if let Some(r) = self.queue.front() {
            return Some(r.clone());
        }
        let p = self.cursor + 1;
        if p < self.order.len() {
            Some(self.at(self.order[p]).clone())
        } else if self.repeat == Repeat::All && !self.order.is_empty() {
            Some(self.at(self.order[0]).clone())
        } else {
            None
        }
    }

    /// Move cursor/queue to the next track and return it (None = end of list).
    /// `auto` = track ended naturally (respects repeat-one).
    fn advance(&mut self, auto: bool) -> Option<Row> {
        if auto && self.repeat == Repeat::One {
            return self.now.clone();
        }
        if let Some(r) = self.queue.pop_front() {
            return Some(r);
        }
        if self.order.is_empty() {
            return None;
        }
        if self.cursor + 1 < self.order.len() {
            self.cursor += 1;
        } else if self.repeat == Repeat::All {
            self.cursor = 0;
        } else {
            self.status = "End of list".into();
            return None;
        }
        Some(self.at(self.order[self.cursor]).clone())
    }

    fn next(&mut self, auto: bool) {
        if auto && self.sleep.as_ref().is_some_and(|s| s.until.is_none()) {
            // ended before the timer caught it: stop whatever Soloist moved on to
            self.stop();
            self.finish_sleep();
            return;
        }
        match self.advance(auto) {
            // Soloist already has it queued: skip to it rather than queue a duplicate.
            Some(r) if self.ahead.as_deref() == Some(r.uri.as_str()) => {
                self.ahead = None;
                self.engine.skip_next();
                self.awaiting = Some((r.uri.clone(), Instant::now()));
                self.pos_ms = 0;
                self.pos_at = Instant::now();
                self.now = Some(r);
            }
            Some(r) => self.load(r),
            None if auto => self.stop(),
            None => {}
        }
    }

    fn prev(&mut self) {
        if self.position_ms() > 3000 || self.order.is_empty() {
            self.seek_to(0);
            return;
        }
        if self.cursor > 0 {
            self.cursor -= 1;
        } else if self.repeat == Repeat::All {
            self.cursor = self.order.len() - 1;
        }
        let row = self.at(self.order[self.cursor]).clone();
        self.load(row);
    }

    fn stop(&mut self) {
        self.engine.stop();
        self.playing = false;
        self.pos_ms = 0;
        if self.engine.is_soloist() {
            // Soloist has moved on (autoplay at the end of the list): play ours again on Space.
            self.reload_at = Some(0);
        }
    }

    fn toggle(&mut self) {
        if let Some(pos) = self.reload_at.take()
            && let Some(row) = self.now.clone()
        {
            // Player was restarted while paused: bring the track back where it was.
            self.load(row);
            self.resume_at(pos);
            return;
        }
        if self.now.is_none() {
            // nothing loaded: play whatever is selected
            self.activate();
        } else if self.playing {
            self.engine.pause();
        } else {
            self.engine.resume();
        }
    }

    /// Seek to `pos` once the reloaded track plays (see `pending_seek`).
    fn resume_at(&mut self, pos: u32) {
        if pos > 1000 {
            let now = Instant::now();
            // "last seek" a second ago: the first report of playing from the start seeks at once
            let ago = now.checked_sub(std::time::Duration::from_secs(1)).unwrap_or(now);
            self.pending_seek = Some((pos, now + std::time::Duration::from_secs(10), ago));
        }
    }

    /// Seek again while Soloist plays well before the resume point (see `pending_seek`).
    /// Runs on each position report and each second: after a restart Soloist first sends
    /// the old session's snapshot, then starts our track from 0 and may report nothing more.
    /// Log the song playing once it has played 30 s (again after it starts over), for For You.
    pub fn note_play(&mut self) {
        let Some(now) = self.now.as_ref() else { return };
        let pos = self.position_ms();
        if pos >= 30_000 && self.logged.as_deref() != Some(now.uri.as_str()) {
            if let Some(dir) = self.data_dir.as_deref() {
                discover::log_play(dir, now);
            }
            self.logged = Some(now.uri.clone());
        } else if pos < 5_000 && self.logged.as_deref() == Some(now.uri.as_str()) {
            self.logged = None; // repeat one, or played again: counts again after 30 s
        }
    }

    pub fn check_resume(&mut self) {
        let Some((want, until, last)) = self.pending_seek else { return };
        if Instant::now() > until {
            self.pending_seek = None;
        } else if self.awaiting.is_none() && self.playing && self.position_ms() + 2500 < want && last.elapsed().as_millis() >= 1000 {
            log::debug!("resume: at {} ms, seeking to {want} ms", self.position_ms());
            self.engine.seek(want);
            self.pending_seek = Some((want, until, Instant::now()));
        }
    }

    fn seek_to(&mut self, ms: u32) {
        self.pending_seek = None;
        if self.now.is_some() {
            self.engine.seek(ms);
            self.pos_ms = ms;
            self.pos_at = Instant::now();
            self.seeked = Some((ms, self.pos_at));
        }
    }

    /// A position report that belongs to an earlier seek than the last one (pressing `.`
    /// quickly would otherwise lose every other seek).
    fn stale_position(&self, pos_ms: u32) -> bool {
        self.seeked.is_some_and(|(want, at)| at.elapsed() < Duration::from_secs(1) && pos_ms.abs_diff(want) > 1500)
    }

    fn seek_by(&mut self, delta: i64) {
        let dur = self.now.as_ref().map(|r| r.duration_ms).unwrap_or(0) as i64;
        let to = (self.position_ms() as i64 + delta).clamp(0, (dur - 1000).max(0));
        self.seek_to(to as u32);
    }

    pub fn volume_pct(&self) -> u32 {
        self.vol
    }

    fn change_volume(&mut self, up: bool) {
        self.set_volume(if up { self.vol + VOL_STEP } else { self.vol.saturating_sub(VOL_STEP) });
    }

    fn set_volume(&mut self, pct: u32) {
        self.vol = pct.min(100);
        self.vol_set_at = Instant::now();
        self.engine.set_volume(self.vol);
        self.save_volume();
    }

    fn save_volume(&self) {
        if let Some(c) = self.session.cache() {
            c.save_volume((self.vol * u16::MAX as u32 / 100) as u16);
        }
    }

    /// Write the keyboard toggles (shuffle, repeat, sort, art) next to the EQ settings.
    pub(crate) fn save_prefs(&mut self) {
        self.audio.shuffle = self.shuffle;
        self.audio.smart = self.smart;
        self.audio.repeat = self.repeat as u8;
        self.audio.sort = self.sort as u8;
        self.audio.art = self.art_on;
        self.audio.theme = self.theme;
        self.audio.tint = self.tint.as_ref().and_then(|t| t.1).or(self.audio.tint);
        self.audio.save();
    }

    /// Soloist autoplays a radio track the moment ours ends. To avoid that, we hand it our
    /// next track via its own queue ~8 s before the end; it then switches gaplessly.
    /// Returns when that should happen (None = nothing to do).
    pub fn end_deadline(&self) -> Option<Instant> {
        let lead_ms = 8_000 + self.audio.crossfade_s * 1000; // crossfade starts earlier
        if !self.engine.is_soloist()
            || !self.playing
            || self.awaiting.is_some()
            || self.ahead.is_some()
            || self.repeat == Repeat::One
            || self.sleep.as_ref().is_some_and(|s| s.until.is_none())
        {
            return None;
        }
        let dur = self.now.as_ref()?.duration_ms;
        self.peek_next()?;
        let remaining = dur.saturating_sub(lead_ms).saturating_sub(self.position_ms());
        Some(Instant::now() + std::time::Duration::from_millis(remaining as u64))
    }

    pub fn on_end_deadline(&mut self) {
        if self.end_deadline().is_some_and(|d| d <= Instant::now() + std::time::Duration::from_millis(50))
            && let Some(r) = self.peek_next()
        {
            self.engine.add_to_queue(&r.uri);
            self.prefetch_art(&r);
            self.ahead = Some(r.uri);
        }
    }

    /// True when the current track is (about) finished โ€” used to tell a natural end apart
    /// from the user changing tracks on another device.
    fn near_end(&self) -> bool {
        let dur = self.now.as_ref().map(|r| r.duration_ms).unwrap_or(0);
        // with crossfade, Soloist moves on that much earlier
        dur > 0 && self.position_ms() + 5000 + self.audio.crossfade_s * 1000 >= dur
    }

    /// Returns true if the UI needs a redraw.
    pub fn on_engine(&mut self, ev: EngineEvent) -> bool {
        if let Some((_, at)) = &self.awaiting
            && at.elapsed().as_secs() >= 10
        {
            self.awaiting = None; // never got confirmation; stop waiting
        }
        match ev {
            EngineEvent::Position { pos_ms, playing } => {
                if self.awaiting.is_some() {
                    return false; // belongs to the previous track
                }
                if let Some(p) = playing {
                    if p {
                        self.skips = 0;
                    }
                    self.playing = p;
                }
                if self.stale_position(pos_ms) {
                    return true;
                }
                self.pos_ms = pos_ms;
                self.pos_at = Instant::now();
                self.check_resume();
            }
            EngineEvent::TrackChanged(row) => {
                if self.reload_at.is_some() {
                    return false; // not ours (autoplay or a stale snapshot); Space reloads ours
                }
                if let Some((want, _)) = &self.awaiting {
                    if *want == row.uri {
                        // No seek here: after a restart this is often the new Soloist's stale
                        // snapshot, and a seek before it starts our track is lost. check_resume
                        // seeks once it reports playing.
                        if let Some(now) = self.now.as_mut()
                            && now.art.is_none()
                        {
                            now.art = row.art;
                        }
                        self.awaiting = None;
                        self.pos_ms = 0;
                        self.pos_at = Instant::now();
                    }
                    return false;
                }
                if let Some(now) = self.now.as_mut()
                    && now.uri == row.uri
                {
                    if now.art.is_none() && row.art.is_some() {
                        now.art = row.art;
                        return true;
                    }
                    return false;
                }
                if self.ahead.as_deref() == Some(row.uri.as_str()) {
                    // Soloist moved to the track we pre-queued: catch our state up.
                    self.ahead = None;
                    match self.advance(true) {
                        Some(r) if r.uri == row.uri => {
                            self.now = Some(r);
                            self.pos_ms = 0;
                            self.pos_at = Instant::now();
                        }
                        Some(r) => self.load(r), // plan changed since we queued it
                        None => self.stop(),
                    }
                } else if self.now.is_some() && self.near_end() {
                    // Soloist moved on by itself (autoplay) at the end of our track: play our next.
                    self.next(true);
                } else {
                    // Changed from another device (phone etc.): follow it.
                    self.now = Some(row);
                    self.pos_ms = 0;
                    self.pos_at = Instant::now();
                }
            }
            EngineEvent::Idle => {
                if self.awaiting.is_some() {
                    return false;
                }
                if self.now.is_some() && self.near_end() {
                    self.next(true);
                } else {
                    self.playing = false;
                }
            }
            EngineEvent::Stopped => self.playing = false,
            EngineEvent::PreloadNext => {
                if let Some(r) = self.peek_next() {
                    self.engine.preload(&r.uri);
                }
                return false;
            }
            EngineEvent::Ended => self.next(true),
            EngineEvent::Unavailable => {
                self.skips += 1;
                if self.skips > 15 {
                    self.stop();
                    self.status = "Too many unavailable tracks in a row; stopped. (TRILL_LOG=debug to see why)".into();
                } else {
                    let title = self.now.as_ref().map_or_else(|| "track".into(), |r| r.title.clone());
                    // Spotify refuses librespot on many accounts; say what Soloist still needs.
                    self.status = match &self.soloist_missing {
                        Some(why) => format!("Unavailable: {title}, skipping. Playing through librespot because {why}"),
                        None => format!("Unavailable: {title}, skipping"),
                    };
                    // repeat-one would retry the same track forever
                    if self.repeat == Repeat::One {
                        self.stop();
                        self.status = format!("Unavailable: {title}");
                    } else {
                        self.next(true);
                    }
                }
            }
            EngineEvent::Volume(v) => {
                // Soloist echoes volume changes late; don't let an old echo undo a keypress.
                if self.vol_set_at.elapsed().as_millis() < 1500 || v.min(100) == self.vol {
                    return false;
                }
                self.vol = v.min(100); // changed from the phone / another Connect device
                self.save_volume();
            }
            // Soloist crashed or was killed: start it again and carry on where it was.
            EngineEvent::Exited(m)
                if self.engine.is_soloist()
                    && Instant::now() >= self.quiet_until
                    && self.restart_at.is_none()
                    && !m.contains("expired")
                    && self.revived_at.is_none_or(|t| t.elapsed().as_secs() >= 60) =>
            {
                log::warn!("{m} Restarting it.");
                self.revived_at = Some(Instant::now());
                self.restart_at = Some(Instant::now() + std::time::Duration::from_secs(1));
                self.status = format!("{m} Restarting itโ€ฆ");
            }
            EngineEvent::Exited(_) if self.restart_at.is_some() => return false, // already restarting
            EngineEvent::Status(m) | EngineEvent::Exited(m) => {
                if Instant::now() < self.quiet_until {
                    return false;
                }
                self.status = m;
            }
            EngineEvent::Deactivated => return false, // only awaited while quitting
        }
        true
    }

    // ---------------------------------------------------------------- audio settings

    fn apply_eq(&mut self) {
        self.audio.save();
        match &self.eq {
            Some(eq) => {
                eq.apply(&self.audio.gains());
                self.status = format!("EQ: {}", self.audio.preset_name());
            }
            None if self.audio.is_flat() => self.status = format!("EQ: {}", self.audio.preset_name()),
            None if !self.eq_allowed => self.status = if cfg!(target_os = "linux") { "EQ is disabled (eq = off in config)" } else { "EQ needs PipeWire, which is Linux-only" }.into(),
            None if self.engine.is_soloist() => {
                // First non-flat setting: start the EQ and reroute the player (short restart).
                self.restart_at = Some(Instant::now() + std::time::Duration::from_millis(900));
                self.status = format!("EQ: {} (starting EQโ€ฆ)", self.audio.preset_name());
            }
            None => self.status = format!("EQ: {} โ€” restart trill to apply", self.audio.preset_name()),
        }
    }

    /// The main loop should start the EQ process before the next player restart.
    pub fn eq_wanted(&self) -> bool {
        self.eq.is_none() && self.eq_allowed && !self.audio.is_flat()
    }

    fn cycle_crossfade(&mut self) {
        if !self.engine.is_soloist() {
            self.status = "Crossfade needs the Soloist engine".into();
            return;
        }
        self.audio.cycle_crossfade();
        self.audio.save();
        // debounce: tapping x a few times only restarts once
        self.restart_at = Some(Instant::now() + std::time::Duration::from_millis(1200));
        self.status = match self.audio.crossfade_s {
            0 => "Crossfade off (applyingโ€ฆ)".into(),
            s => format!("Crossfade {s} s (applyingโ€ฆ)"),
        };
    }

    pub fn restart_due(&self) -> bool {
        self.restart_at.is_some_and(|t| t <= Instant::now())
    }

    /// Returns what to resume after the player restarts.
    pub fn begin_restart(&mut self) -> Option<(Row, u32, bool)> {
        self.restart_at = None;
        self.awaiting = None;
        self.ahead = None; // the new process has an empty queue
        self.quiet_until = Instant::now() + std::time::Duration::from_secs(4);
        self.now.clone().map(|r| (r, self.position_ms(), self.playing))
    }

    pub fn finish_restart(&mut self, engine: Engine, resume: Option<(Row, u32, bool)>) {
        self.engine = engine;
        self.engine.set_repeat_track(self.repeat == Repeat::One);
        self.quiet_until = Instant::now() + std::time::Duration::from_secs(2);
        match resume {
            Some((row, pos, true)) => {
                self.load(row);
                self.resume_at(pos);
            }
            Some((_, pos, false)) => {
                self.reload_at = Some(pos);
                self.playing = false;
            }
            None => {}
        }
        let xfade = match self.audio.crossfade_s {
            0 => "crossfade off".to_string(),
            s => format!("crossfade {s} s"),
        };
        self.status = if self.revived_at.is_some_and(|t| t.elapsed().as_secs() < 30) {
            "Soloist restarted.".into()
        } else {
            format!("EQ: {} ยท {xfade}", self.audio.preset_name())
        };
    }

    fn on_eq_key(&mut self, band: usize, k: KeyEvent) {
        let n = BANDS.len();
        match k.code {
            KeyCode::Esc | KeyCode::Char('E') | KeyCode::Char('q') => {
                self.eq_panel = None;
            }
            KeyCode::Up | KeyCode::Char('k') => self.eq_panel = Some((band + n - 1) % n),
            KeyCode::Down | KeyCode::Char('j') => self.eq_panel = Some((band + 1) % n),
            KeyCode::Left | KeyCode::Char('h') => {
                self.audio.nudge(band, -1.0);
                self.apply_eq();
            }
            KeyCode::Right | KeyCode::Char('l') => {
                self.audio.nudge(band, 1.0);
                self.apply_eq();
            }
            KeyCode::Char('0') => {
                self.audio.set_band(band, 0.0);
                self.apply_eq();
            }
            KeyCode::Char('p') | KeyCode::Char('e') | KeyCode::Tab => {
                self.audio.cycle_preset(false);
                self.apply_eq();
            }
            KeyCode::Char('P') | KeyCode::BackTab => {
                self.audio.cycle_preset(true);
                self.apply_eq();
            }
            KeyCode::Char('f') => {
                self.audio.preset = 0;
                self.apply_eq();
            }
            KeyCode::Char('x') => self.cycle_crossfade(),
            KeyCode::Char(' ') => self.toggle(),
            _ => {}
        }
    }

    // ---------------------------------------------------------------- desktop (MPRIS)

    pub fn on_remote(&mut self, cmd: Remote) {
        match cmd {
            Remote::PlayPause => self.toggle(),
            Remote::Play => {
                if !self.playing {
                    self.toggle()
                }
            }
            Remote::Pause | Remote::Stop => {
                if self.playing {
                    self.engine.pause()
                }
            }
            Remote::Next => self.next(false),
            Remote::Prev => self.prev(),
            Remote::Seek(ms) => self.seek_by(ms),
            Remote::SetPosition(ms) => self.seek_to(ms),
            Remote::Volume(v) => self.set_volume(v),
            Remote::Shuffle(on) => {
                if on != self.shuffle {
                    self.set_shuffle(on, false)
                }
            }
            Remote::Loop(r) => {
                self.repeat = r;
                self.save_prefs();
                self.engine.set_repeat_track(r == Repeat::One);
            }
        }
    }

    /// `s`: shuffle off โ†’ on โ†’ smart โ†’ off.
    fn toggle_shuffle(&mut self) {
        match (self.shuffle, self.smart) {
            (false, _) => self.set_shuffle(true, false),
            (true, false) => self.set_shuffle(true, true),
            (true, true) => self.set_shuffle(false, false),
        }
    }

    fn set_shuffle(&mut self, on: bool, smart: bool) {
        (self.shuffle, self.smart) = (on, on && smart);
        self.save_prefs();
        // A playing recommendation isn't in the list's order: carry on after the list song before it.
        let cur = self.order.get(..=self.cursor).and_then(|o| o.iter().rev().find(|&&c| c < self.ctx.len()).copied());
        self.reorder(cur);
        self.weave();
        if self.smart && self.recs.is_empty() && !self.ctx.is_empty() {
            self.fetch_recs();
        }
        self.refresh_queue_view();
        self.status = match (self.shuffle, self.smart) {
            (true, true) => "Smart shuffle: a recommendation (โœฆ) after every 3 songs".into(),
            (true, false) => "Shuffle on".into(),
            _ => "Shuffle off".into(),
        };
    }

    // ---------------------------------------------------------------- keys

    fn activate(&mut self) {
        let Some(i) = self.view.state.selected() else { return };
        let rows = self.view.rows.clone();
        let Some(row) = rows.get(i) else { return };
        if self.view.uri == "trill:queue" {
            match self.queue_src.get(i).copied() {
                Some(QSrc::Now) => self.seek_to(0),
                Some(QSrc::Manual(q)) => {
                    if let Some(r) = self.queue.remove(q) {
                        self.load(r);
                    }
                }
                Some(QSrc::Upcoming(p)) if p < self.order.len() => {
                    self.cursor = p;
                    let r = self.at(self.order[p]).clone();
                    self.load(r);
                }
                _ => {}
            }
            self.show_queue();
            return;
        }
        match row.kind {
            Kind::Track => self.play_list(&rows, i),
            Kind::Album | Kind::Playlist | Kind::Artist => {
                let title = if row.artist.is_empty() { row.title.clone() } else { format!("{} โ€” {}", row.title, row.artist) };
                self.open(row.uri.clone(), title, true, false);
            }
        }
    }

    fn enqueue(&mut self) {
        let Some(i) = self.view.state.selected() else { return };
        if let Some(r) = self.view.rows.get(i)
            && r.kind == Kind::Track
        {
            self.queue.push_back(r.clone());
            self.status = format!("Queued: {} ({} in queue)", r.title, self.queue.len());
            self.view.state.select(Some((i + 1).min(self.view.rows.len().saturating_sub(1))));
        }
    }

    fn move_sel(&mut self, delta: isize) {
        let (len, sel) = match self.focus {
            Focus::Side => (self.side.len(), self.side_state.selected()),
            _ => (self.view.rows.len(), self.view.state.selected()),
        };
        if len == 0 {
            return;
        }
        let cur = sel.unwrap_or(0) as isize;
        let next = (cur + delta).clamp(0, len as isize - 1) as usize;
        match self.focus {
            Focus::Side => self.side_state.select(Some(next)),
            _ => self.view.state.select(Some(next)),
        }
    }

    /// Click a sidebar entry to open it, a row to select it (double-click plays), the progress
    /// bar to seek; the wheel scrolls the pane under the pointer. Returns whether to redraw,
    /// so pointer moves (sent on every motion while mouse capture is on) cost no frame.
    pub fn on_mouse(&mut self, m: MouseEvent) -> bool {
        let pos = (m.column, m.row);
        let modal = self.help_open || self.eq_panel.is_some() || self.chooser.is_some();
        match m.kind {
            MouseEventKind::ScrollDown | MouseEventKind::ScrollUp => {
                if self.help_open {
                    return false;
                }
                if !modal && self.focus != Focus::Input {
                    if self.side_area.contains(pos.into()) {
                        self.focus = Focus::Side;
                    } else if self.main_area.contains(pos.into()) {
                        self.focus = Focus::Main;
                    }
                }
                // as arrow keys, so popups and the lyrics view scroll the way they already do
                let code = if m.kind == MouseEventKind::ScrollDown { KeyCode::Down } else { KeyCode::Up };
                self.on_key(KeyEvent::new(code, KeyModifiers::NONE));
            }
            MouseEventKind::Down(MouseButton::Left) => {
                if self.help_open {
                    self.help_open = false;
                } else if modal && !self.popup_area.contains(pos.into()) {
                    // a click outside the EQ panel or playlist picker closes it, like Esc
                    self.on_key(KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE));
                } else if modal {
                    let len = match &self.chooser {
                        Some(c) => c.matches(self).len(),
                        None => BANDS.len(),
                    };
                    let Some(i) = popup_row(self.popup_rows, len, pos) else { return false };
                    if self.eq_panel.is_some() {
                        self.eq_panel = Some(i);
                    } else {
                        if let Some(c) = self.chooser.as_mut() {
                            c.sel = i;
                        }
                        if self.double_click(i) {
                            self.on_key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE));
                        }
                    }
                } else if self.focus == Focus::Input {
                    return false;
                } else if let Some(i) = row_at(self.side_area, 1, self.side_state.offset(), self.side.len(), pos) {
                    self.side_state.select(Some(i));
                    self.open_side();
                } else if self.lyrics_open && let Some(ms) = self.lyric_at(pos) {
                    self.seek_to(ms);
                } else if let Some(i) = row_at(self.main_area, 2, self.view.state.offset(), self.view.rows.len(), pos)
                    && !self.lyrics_open
                {
                    self.focus = Focus::Main;
                    self.view.state.select(Some(i));
                    if self.double_click(i) {
                        self.activate();
                    }
                } else if let Some(len) = self.now.as_ref().map(|r| r.duration_ms)
                    && self.bar_area.contains(Position::from(pos))
                {
                    let ms = (pos.0 - self.bar_area.x) as u64 * len as u64 / self.bar_area.width as u64;
                    self.seek_to(ms as u32);
                } else if let Some(i) = self.flag_areas.iter().position(|r| r.contains(pos.into())) {
                    self.on_key(KeyEvent::new(KeyCode::Char(['s', 'r', 'I'][i]), KeyModifiers::NONE));
                } else {
                    return false;
                }
            }
            _ => return false,
        }
        true
    }

    /// Whether this click on row `i` follows one on the same row moments ago.
    fn double_click(&mut self, i: usize) -> bool {
        let double = self.last_click.is_some_and(|(t, j)| j == i && t.elapsed() < Duration::from_millis(400));
        self.last_click = (!double).then(|| (Instant::now(), i));
        double
    }

    /// Keys while the bottom-line box is open: `/` search (โ†‘โ†“ past searches) or `F` find in
    /// the list (narrows it as you type; โ†‘โ†“ move in it).
    fn on_input_key(&mut self, k: KeyEvent) {
        let find = self.input_mode == InputMode::Find;
        match k.code {
            KeyCode::Esc => {
                self.focus = Focus::Main;
                self.input.clear();
                if find {
                    self.set_find(String::new());
                }
            }
            KeyCode::Enter => {
                let q = std::mem::take(&mut self.input);
                self.focus = Focus::Main;
                if !find {
                    self.search(q);
                }
            }
            KeyCode::Up | KeyCode::Down if find => self.move_sel(if k.code == KeyCode::Up { -1 } else { 1 }),
            KeyCode::Up | KeyCode::Down => {
                // โ†‘ goes back in time, โ†“ forward; past the newest is an empty box again
                let n = self.audio.searches.len();
                self.history_at = match (k.code, self.history_at) {
                    (KeyCode::Up, None) if n > 0 => Some(0),
                    (KeyCode::Up, Some(i)) => Some((i + 1).min(n.saturating_sub(1))),
                    (KeyCode::Down, Some(0)) | (_, None) => None,
                    (_, Some(i)) => Some(i - 1),
                };
                self.input = self.history_at.and_then(|i| self.audio.searches.get(i)).cloned().unwrap_or_default();
            }
            KeyCode::Backspace => {
                self.input.pop();
                if find {
                    self.set_find(self.input.clone());
                }
            }
            KeyCode::Char(c) => {
                self.input.push(c);
                if find {
                    self.set_find(self.input.clone());
                }
            }
            _ => {}
        }
    }

    /// Narrow the open list to the rows matching `find` (empty: show it all again).
    fn set_find(&mut self, find: String) {
        let keep = self.view.state.selected().and_then(|i| self.view.rows.get(i)).map(|r| r.uri.clone());
        self.view.rows = found(&self.view.all, &find);
        self.view.find = find;
        let i = keep.and_then(|k| self.view.rows.iter().position(|r| r.uri == k)).unwrap_or(0);
        self.view.state.select((!self.view.rows.is_empty()).then_some(i));
    }

    /// `z`: sleep timer 15 โ†’ 30 โ†’ 45 โ†’ 60 โ†’ 90 min โ†’ end of this song โ†’ off.
    fn cycle_sleep(&mut self) {
        let step = self.sleep.as_ref().map_or(0, |s| s.step + 1);
        if self.sleep_end().is_some_and(|e| e <= Instant::now() + SLEEP_FADE) {
            self.engine.set_volume(self.vol); // it was fading
            self.vol_set_at = Instant::now();
        }
        self.sleep = None;
        self.status = match SLEEP_MINUTES.get(step) {
            Some(&m) => {
                self.sleep = Some(SleepTimer { step, until: Some(Instant::now() + Duration::from_secs(m * 60)) });
                format!("Sleep timer: pausing in {m} min (z for longer)")
            }
            None if step == SLEEP_MINUTES.len() => {
                self.sleep = Some(SleepTimer { step, until: None });
                "Sleep timer: pausing at the end of this song".into()
            }
            None => "Sleep timer off".into(),
        };
    }

    /// When the sleep timer pauses (None: off, or "end of song" while nothing plays).
    fn sleep_end(&self) -> Option<Instant> {
        let s = self.sleep.as_ref()?;
        match s.until {
            Some(t) => Some(t),
            // a little early: our position runs a moment behind Soloist's, and once the song
            // ends Soloist starts its own autoplay pick
            None if self.playing => {
                let left = self.now.as_ref()?.duration_ms.saturating_sub(self.position_ms()).saturating_sub(1500);
                Some(Instant::now() + Duration::from_millis(left as u64))
            }
            None => None,
        }
    }

    /// When the sleep timer next needs to act: start fading, the next fade step, or pause.
    pub fn sleep_deadline(&self) -> Option<Instant> {
        let end = self.sleep_end()?;
        let now = Instant::now();
        if !self.playing || now + SLEEP_FADE < end {
            return Some(if self.playing { end - SLEEP_FADE } else { end });
        }
        Some(end.min(now + Duration::from_millis(500)))
    }

    /// Fade the volume over the last seconds, then pause and put the volume back.
    pub fn on_sleep_deadline(&mut self) {
        let Some(end) = self.sleep_end() else { return };
        let now = Instant::now();
        self.vol_set_at = now; // Soloist echoes the fade; that's not the user changing the volume
        if now + Duration::from_millis(20) >= end {
            self.finish_sleep();
        } else if self.playing && now + SLEEP_FADE >= end {
            let left = (end - now).as_secs_f32() / SLEEP_FADE.as_secs_f32();
            self.engine.set_volume((self.vol as f32 * left).round() as u32);
        }
    }

    fn finish_sleep(&mut self) {
        self.sleep = None;
        if self.playing {
            self.engine.pause();
        }
        self.engine.set_volume(self.vol);
        self.vol_set_at = Instant::now();
        self.status = "Sleep timer: paused.".into();
    }

    pub fn on_key(&mut self, k: KeyEvent) {
        if k.kind == KeyEventKind::Release {
            return;
        }
        if k.modifiers.contains(KeyModifiers::CONTROL) && k.code == KeyCode::Char('c') {
            self.quit = true;
            return;
        }
        if self.help_open {
            self.help_open = false;
            return;
        }
        if let Some(band) = self.eq_panel {
            self.on_eq_key(band, k);
            return;
        }
        if self.chooser.is_some() {
            self.on_chooser_key(k);
            return;
        }
        if self.lyrics_open && self.focus != Focus::Input && self.on_lyrics_key(k) {
            return;
        }
        if self.focus == Focus::Input {
            self.on_input_key(k);
            return;
        }
        // Only here, so typing in search and the EQ/chooser/lyrics panels keep their own keys.
        let k = KeyEvent { code: self.remap.get(&k.code).copied().unwrap_or(k.code), ..k };
        match k.code {
            KeyCode::Char('q') => self.quit = true,
            KeyCode::Tab | KeyCode::BackTab => {
                self.focus = if self.focus == Focus::Side { Focus::Main } else { Focus::Side }
            }
            KeyCode::Char('h') => self.focus = Focus::Side,
            KeyCode::Char('l') => self.focus = Focus::Main,
            KeyCode::Down | KeyCode::Char('j') => self.move_sel(1),
            KeyCode::Up | KeyCode::Char('k') => self.move_sel(-1),
            KeyCode::PageDown => self.move_sel(20),
            KeyCode::PageUp => self.move_sel(-20),
            KeyCode::Home | KeyCode::Char('g') => self.move_sel(isize::MIN / 2),
            KeyCode::End | KeyCode::Char('G') => self.move_sel(isize::MAX / 2),
            KeyCode::Enter => {
                if self.focus == Focus::Side {
                    self.open_side()
                } else {
                    self.activate()
                }
            }
            KeyCode::Esc | KeyCode::Backspace if !self.view.find.is_empty() && self.focus == Focus::Main => self.set_find(String::new()),
            KeyCode::Esc | KeyCode::Backspace => {
                if let Some(v) = self.back.pop() {
                    self.view = v;
                    self.pending = None;
                    self.loading = false;
                } else {
                    self.focus = Focus::Side;
                }
            }
            KeyCode::Char('/') => {
                self.focus = Focus::Input;
                self.input_mode = InputMode::Search;
                self.input.clear();
                self.history_at = None;
            }
            KeyCode::Char('F') if self.view.uri == "trill:queue" || self.view.uri.is_empty() => {
                self.status = "Open a list to find songs in it.".into();
            }
            KeyCode::Char('F') => {
                self.lyrics_open = false;
                self.focus = Focus::Input;
                self.input_mode = InputMode::Find;
                self.input = self.view.find.clone();
            }
            KeyCode::Char('z') => self.cycle_sleep(),
            KeyCode::Char('X') => self.mark_not_interested(),
            KeyCode::Char(' ') => self.toggle(),
            KeyCode::Char('n') => self.next(false),
            KeyCode::Char('p') => self.prev(),
            KeyCode::Right | KeyCode::Char('.') => self.seek_by(SEEK_MS as i64),
            KeyCode::Left | KeyCode::Char(',') => self.seek_by(-(SEEK_MS as i64)),
            KeyCode::Char('+') | KeyCode::Char('=') => self.change_volume(true),
            KeyCode::Char('-') | KeyCode::Char('_') => self.change_volume(false),
            KeyCode::Char('a') => self.enqueue(),
            KeyCode::Char('s') => self.toggle_shuffle(),
            KeyCode::Char('o') => self.cycle_sort(false),
            KeyCode::Char('O') => self.cycle_sort(true),
            KeyCode::Char('t') => {
                self.theme = (self.theme + 1) % (crate::theme::COVER + 1);
                self.save_prefs();
                self.status = match self.theme {
                    crate::theme::COVER => "Theme: from the album art".into(),
                    i => format!("Theme: {}", crate::theme::name(i)),
                };
            }
            KeyCode::Char('e') => {
                self.audio.cycle_preset(false);
                self.apply_eq();
            }
            KeyCode::Char('E') => self.eq_panel = Some(0),
            KeyCode::Char('x') => self.cycle_crossfade(),
            KeyCode::Char('r') => {
                self.repeat = match self.repeat {
                    Repeat::Off => Repeat::All,
                    Repeat::All => Repeat::One,
                    Repeat::One => Repeat::Off,
                };
                self.save_prefs();
                self.engine.set_repeat_track(self.repeat == Repeat::One);
            }
            KeyCode::Char('c') => {
                // jump to the queue / now playing
                self.lyrics_open = false;
                if let Some(i) = self.side.iter().position(|s| s.kind == SideKind::Queue) {
                    self.side_state.select(Some(i));
                    self.back.clear();
                    self.show_queue();
                    self.focus = Focus::Main;
                }
            }
            KeyCode::Char('R') => {
                if self.focus == Focus::Side || self.view.uri.is_empty() {
                    self.status = "Reloading playlistsโ€ฆ".into();
                    self.load_playlists();
                } else if !self.view.uri.starts_with("trill:") || self.view.uri.starts_with("trill:collection:") || self.view.uri == FOR_YOU {
                    let (u, t) = (self.view.uri.clone(), self.view.title.clone());
                    self.open(u, t, false, true);
                }
            }
            KeyCode::Char('f') => self.toggle_like(),
            KeyCode::Char('P') => self.play_all(),
            KeyCode::Char('w') => self.jump_to_now(),
            KeyCode::Char('A') => self.open_chooser(),
            KeyCode::Char('I') => self.toggle_private(),
            KeyCode::Char('y') => self.copy_link(false),
            KeyCode::Char('Y') => self.copy_link(true),
            KeyCode::Char('u') => self.open_home(false),
            KeyCode::Char('U') => self.open_home(true),
            KeyCode::Char('D') => self.remove_from_playlist(),
            KeyCode::Char('L') => self.toggle_lyrics(),
            KeyCode::Char('i') => self.toggle_art(),
            KeyCode::Char('?') => self.help_open = true,
            _ => {}
        }
    }
}

/// The list row under `pos` in a bordered pane whose rows start `top` lines down, scrolled by `offset`.
fn row_at(area: Rect, top: u16, offset: usize, len: usize, (x, y): (u16, u16)) -> Option<usize> {
    if x <= area.x || x + 1 >= area.right() || y < area.y + top || y + 1 >= area.bottom() {
        return None;
    }
    let i = offset + (y - area.y - top) as usize;
    (i < len).then_some(i)
}

/// The row under `pos` in a popup's list (no border), given its area and scroll offset.
fn popup_row((area, offset): (Rect, usize), len: usize, pos: (u16, u16)) -> Option<usize> {
    let i = offset + pos.1.checked_sub(area.y)? as usize;
    (area.contains(pos.into()) && i < len).then_some(i)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn popup_clicks_map_to_rows() {
        let rows = (Rect::new(20, 8, 30, 5), 4); // 5 visible rows, scrolled by 4
        assert_eq!(popup_row(rows, 20, (25, 8)), Some(4));
        assert_eq!(popup_row(rows, 20, (25, 12)), Some(8));
        assert_eq!(popup_row(rows, 20, (25, 13)), None, "below the list");
        assert_eq!(popup_row(rows, 20, (25, 7)), None, "above the list");
        assert_eq!(popup_row(rows, 20, (19, 9)), None, "left of it");
        assert_eq!(popup_row(rows, 6, (25, 11)), None, "past the last match");
        assert_eq!(popup_row((Rect::default(), 0), 5, (0, 0)), None, "nothing drawn");
    }

    #[test]
    fn clicks_map_to_rows() {
        let area = Rect::new(10, 5, 20, 10); // rows at y 7..14, x 11..29
        assert_eq!(row_at(area, 2, 0, 50, (15, 7)), Some(0));
        assert_eq!(row_at(area, 2, 30, 50, (15, 13)), Some(36));
        assert_eq!(row_at(area, 2, 0, 50, (15, 6)), None, "header");
        assert_eq!(row_at(area, 2, 0, 50, (15, 14)), None, "bottom border");
        assert_eq!(row_at(area, 2, 0, 50, (10, 8)), None, "left border");
        assert_eq!(row_at(area, 2, 0, 3, (15, 10)), None, "past the last row");
        assert_eq!(row_at(Rect::default(), 1, 0, 5, (0, 1)), None, "hidden pane");
    }

    #[test]
    fn smart_shuffle_mixes_after_the_cursor() {
        // 8 songs (0..8) with 2 recommendations (8, 9); song at position 1 is playing.
        let mut order: Vec<usize> = (0..8).collect();
        weave(&mut order, 2, 8..10);
        assert_eq!(order, [0, 1, 2, 3, 4, 8, 5, 6, 7, 9]);
        let mut short = vec![0, 1];
        weave(&mut short, 5, 2..4);
        assert_eq!(short, [0, 1]);
    }

    fn row(title: &str, artist: &str, album: &str, ms: u32, added: u64) -> api::Row {
        api::Row {
            uri: format!("spotify:track:{title}"),
            title: title.into(),
            artist: artist.into(),
            album: album.into(),
            duration_ms: ms,
            kind: api::Kind::Track,
            art: None,
            added_at: added,
            members: String::new(),
            plays: 0,
        }
    }

    #[test]
    fn counts_each_kind() {
        let mut a = row("a", "x", "y", 1, 0);
        a.kind = Kind::Album;
        assert_eq!(count(&[row("t", "x", "y", 1, 0), row("u", "x", "y", 1, 0), a]), "2 tracks ยท 1 album");
        assert_eq!(count(&[]), "empty");
    }

    #[test]
    fn sorts_playlists_every_way() {
        let rows: Rows = Arc::new(vec![row("b", "Zed", "x", 300, 1), row("C", "amy", "Y", 100, 3), row("a", "Amy", "y", 200, 2)]);
        let order = |s: Sort, uri: &str| sorted(s, uri, rows.clone()).0.iter().map(|r| r.title.clone()).collect::<String>();
        let pl = "spotify:playlist:1";
        assert_eq!(order(Sort::Added, pl), "Cab");
        assert_eq!(order(Sort::Original, pl), "bCa");
        assert_eq!(order(Sort::Title, pl), "abC");
        assert_eq!(order(Sort::Artist, pl), "Cab"); // amy == Amy, ties keep playlist order
        assert_eq!(order(Sort::Album, pl), "bCa");
        assert_eq!(order(Sort::Duration, pl), "Cab");
        assert_eq!(order(Sort::Title, "spotify:album:1"), "bCa"); // albums keep their order
        assert_eq!(sorted(Sort::Original, pl, rows.clone()).1, None);
        assert_eq!(sorted(Sort::Album, pl, rows.clone()).1, Some("by album"));
    }
}