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
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
// Copyright (c) 2025 - present
// Author: prjctimg <prjctimg@outlook.com>
// Application state machine: input handling, IPC dispatch, crossfade
//
// This is free software released under the GPL-3.0 license.
use std::path::Path;
use std::time::Duration;
use crossterm::event::{self, Event, KeyCode, KeyEventKind, KeyModifiers};
use gtm_core::client::DaemonClient;
use gtm_core::ipc::DaemonRes;
use gtm_core::spotify::{SpotifyPlaylist, SpotifyStatus, SpotifyTrack};
use gtm_core::state::{DaemonState, Easing, PlaybackStatus, RepeatMode, Tab};
use gtm_core::track::{Playlist, TrackInfo, YTSearchResult};
use ratatui::layout::Alignment;
use ratatui::widgets::Paragraph;
use ratatui::Terminal;
use ratatui_image::picker::Picker;
use ratatui_image::protocol::StatefulProtocol;
use tachyonfx::EffectManager;
use tokio::sync::mpsc;
use base64::Engine;
use crate::footer;
use crate::keymap::{default_keybindings, KeyContext, KeyboardAction};
use crate::picker::{PickerId, PickerManager};
use crate::theme::{AppTheme, ThemeEntry};
use crate::ui;
fn prefs_path() -> std::path::PathBuf {
let config = std::env::var("XDG_CONFIG_HOME")
.map(std::path::PathBuf::from)
.unwrap_or_else(|_| {
let home = std::env::var("HOME").unwrap_or_else(|_| "/tmp".into());
std::path::PathBuf::from(home).join(".config")
});
let dir = config.join("gtm");
let _ = std::fs::create_dir_all(&dir);
dir.join("config.toml")
}
/// Return the config file path, creating the config directory and a
/// default (pretty-printed) `config.toml` if it does not exist yet. Used by
/// the `gtm config` CLI command to give the editor a valid starting point.
pub(crate) fn ensure_prefs_file() -> std::path::PathBuf {
let path = prefs_path();
if !path.exists() {
if let Ok(toml_s) = toml::to_string_pretty(&Prefs::default()) {
let _ = std::fs::write(&path, format!("{toml_s}\n"));
}
}
path
}
#[derive(serde::Serialize, serde::Deserialize, Clone)]
struct Prefs {
#[serde(default = "default_theme_name")]
theme_name: String,
#[serde(default)]
transparent_bg: bool,
#[serde(default = "default_footer_preset_name")]
footer_preset_name: String,
#[serde(default)]
progress_style: crate::progress::ProgressStyle,
#[serde(default)]
design: Design,
#[serde(default)]
visualizer_preset: crate::visualizer::VisualizerPreset,
}
fn default_theme_name() -> String {
"Chadrula".into()
}
fn default_footer_preset_name() -> String {
"Default".into()
}
#[derive(Clone, Copy, PartialEq, Eq, serde::Deserialize, serde::Serialize, Default)]
#[serde(rename_all = "lowercase")]
pub enum Design {
#[default]
Modern,
Classic,
}
impl Design {
pub fn all() -> &'static [Design] {
&[Design::Modern, Design::Classic]
}
pub fn name(&self) -> &'static str {
match self {
Design::Modern => "Modern",
Design::Classic => "Classic",
}
}
}
impl Default for Prefs {
fn default() -> Self {
Self {
theme_name: default_theme_name(),
transparent_bg: false,
footer_preset_name: default_footer_preset_name(),
progress_style: crate::progress::ProgressStyle::default(),
design: Design::default(),
visualizer_preset: crate::visualizer::VisualizerPreset::default(),
}
}
}
fn load_prefs() -> Prefs {
let path = prefs_path();
let Ok(s) = std::fs::read_to_string(&path) else {
return Prefs::default();
};
toml::from_str::<Prefs>(&s).unwrap_or_default()
}
fn save_prefs(prefs: &Prefs) {
if let Ok(s) = toml::to_string(prefs) {
let _ = std::fs::write(prefs_path(), s);
}
}
pub const NUM_SETTINGS_CATEGORIES: usize = 6;
pub const LIBRARY_CATEGORIES: &[&str] = &[
"All Tracks",
"Liked",
"Albums",
"Artists",
"Playlists",
"Spotify",
"YouTube",
];
/// Returns true if the terminal doesn't support image protocols (Neovim, Zellij, etc.).
pub fn no_image_protocol() -> bool {
std::env::var("NVIM").is_ok() || std::env::var("ZELLIJ").is_ok()
}
pub enum InputMode {
Normal,
Searching,
}
#[derive(Debug, Clone)]
pub enum NotificationKind {
Info,
Success,
Warning,
Error,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SlideDirection {
Left,
Right,
}
#[derive(Debug, Clone)]
pub struct Notification {
pub message: String,
pub kind: NotificationKind,
pub expires_at: std::time::Instant,
/// Direction the notification slides in from.
pub slide_direction: SlideDirection,
/// Whether this is a volume-change notification (vertical bar).
pub is_volume: bool,
/// Volume level (0–100) for volume notifications.
pub volume_value: u8,
/// Animation progress: 0.0 = just appeared, 1.0 = fully settled.
/// Managed by the animation system; not user-set.
pub animation_progress: f32,
}
pub struct App {
pub theme: AppTheme,
pub themes: Vec<ThemeEntry>,
pub client: DaemonClient,
pub state: DaemonState,
pub display_position: f64,
last_display_position: f64,
pub frame_count: u64,
pub current_tab: Tab,
pub input_mode: InputMode,
pub search_query: String,
pub scroll_offset: usize,
pub library_category: usize,
pub library_pane_focus: bool,
pub settings_category: usize,
pub settings_pane_focus: bool,
pub settings_option: usize,
pub tracks_cache: Vec<TrackInfo>,
pub queue_cache: Vec<TrackInfo>,
pub queue_cursor: usize,
pub browse_detail: Option<String>,
pub yt_results_cache: Vec<gtm_core::track::YTSearchResult>,
pub playlist_cache: Vec<gtm_core::track::Playlist>,
pub playlist_tracks_cache: Vec<TrackInfo>,
pub spotify_status: Option<SpotifyStatus>,
pub spotify_playlists: Vec<SpotifyPlaylist>,
pub spotify_playlist_tracks_cache: Vec<SpotifyTrack>,
pub spotify_token_input: String,
pub cookie_file: Option<String>,
pub notifications: Vec<Notification>,
pub crossfade_duration: u8,
pub yt_search_loading: bool,
pub yt_search_debounce: Option<std::time::Instant>,
pub yt_search_poll_deadline: Option<std::time::Instant>,
pub pending_delete: Option<(i64, String)>,
pub pickers: PickerManager,
pub sleep_timer_remaining: Option<u64>,
pub sleep_timer_minutes: u32,
pub sleep_timer_input_mode: bool,
pub sleep_timer_input_buf: String,
pub playback_speed: f64,
pub current_cover: Option<Vec<u8>>,
pub last_cover_track_id: Option<i64>,
pub cover_picker: Option<Picker>,
pub cover_stateful: Option<StatefulProtocol>,
pub terminal_cols: u16,
pub terminal_rows: u16,
pub cmd_rx: mpsc::Receiver<TuiCommand>,
cmd_tx: mpsc::Sender<TuiCommand>,
high_pri_cmd_rx: mpsc::UnboundedReceiver<TuiCommand>,
high_pri_cmd_tx: mpsc::UnboundedSender<TuiCommand>,
ipc_rx: mpsc::UnboundedReceiver<IpcResult>,
ipc_tx: mpsc::UnboundedSender<IpcResult>,
keybindings: crate::keymap::Keybindings,
pub theme_index: usize,
pub list_scroll: usize,
pub viewport_items: usize,
pub transparent_bg: bool,
pub last_action_name: Option<(String, std::time::Instant)>,
pub footer_presets: Vec<footer::FooterPreset>,
pub footer_preset: usize,
pub footer_title_scroll: usize,
pub is_ready: bool,
last_queue_cursor: u64,
last_track_path_display: Option<String>,
prev_tab: Tab,
prev_track_id: Option<i64>,
prev_status: gtm_core::state::PlaybackStatus,
prev_volume: u8,
prev_cover_id: Option<i64>,
cover_art_dirty: bool,
pub footer_cache: crate::footer::FooterCache,
last_event_time: std::time::Instant,
pub multiselect_mode: bool,
pub progress_style: crate::progress::ProgressStyle,
pub design: Design,
pub visualizer: crate::visualizer::AudioVisualizer,
pub selected_indices: std::collections::HashSet<usize>,
pending_motion: Option<char>,
pub pending_playlist_track_ids: Vec<i64>,
pub metadata_edit_track_id: Option<i64>,
pub metadata_fields: [String; 7],
pub metadata_field_idx: usize,
/// Cover art preview shown in the Edit Metadata floating window.
pub metadata_cover: Option<Vec<u8>>,
pub metadata_cover_stateful: Option<StatefulProtocol>,
pub metadata_cover_dirty: bool,
pub pending_quit: bool,
pub np_title_scroll: usize,
/// Set on the first frame and on each track change; the render layer
/// (re)starts the library/Now-Playing evolve animation once per trigger.
pub track_anim_trigger: bool,
/// Tachyonfx effect manager carrying the running evolve animation; kept
/// alive across refresh frames until the effect completes.
pub anim_fx: EffectManager<&'static str>,
pub track_popup_visible: bool,
pub track_popup_track_id: Option<i64>,
pub track_popup_cover: Option<Vec<u8>>,
pub popup_cover_stateful: Option<StatefulProtocol>,
last_popup_cover_fetch_id: Option<i64>,
pub current_lyrics: Option<gtm_core::track::LrcData>,
pub lyrics_scroll: usize,
pub lyrics_fetching: bool,
pub show_lyrics: bool,
/// Whether the lyrics pane holds focus (B7). While true, MoveUp/Down,
/// PageUp/Down, Top/Bottom scroll the lyrics and take over from the
/// time-sync driver until focus is released.
pub lyrics_pane_focus: bool,
pub show_health_panel: bool,
pub health_report: Option<gtm_core::ipc::HealthReport>,
pub hide_help_bar: bool,
pub lyrics_manual_scroll: bool,
}
enum IpcResult {
RefreshDone(Box<DaemonState>, Option<Vec<u8>>, Option<i64>),
CoverArt(Option<Vec<u8>>, Option<i64>),
PopupCoverArt(Option<Vec<u8>>, i64),
MetadataCoverArt(Option<Vec<u8>>, i64),
CoverPicker(Option<Picker>),
Lyrics(Option<gtm_core::track::LrcData>),
LibraryTracks(Vec<TrackInfo>),
PlaylistTracks(Vec<TrackInfo>),
Playlists(Vec<Playlist>),
Queue(Vec<TrackInfo>, usize),
YtResults(String, Vec<YTSearchResult>),
Notification(String, NotificationKind),
Error(String),
HealthReport(gtm_core::ipc::HealthReport),
SpotifyStatus(SpotifyStatus),
SpotifyPlaylists(Vec<SpotifyPlaylist>),
SpotifyTracks(Vec<SpotifyTrack>),
}
fn spawn_sync_and_wait(
c: DaemonClient,
kind: gtm_core::ipc::SyncKind,
label: &'static str,
ipc_tx: mpsc::UnboundedSender<IpcResult>,
) {
tokio::spawn(async move {
let kick = match kind {
gtm_core::ipc::SyncKind::Covers => c.library_sync_covers().await,
gtm_core::ipc::SyncKind::Lyrics => c.library_sync_lyrics().await,
gtm_core::ipc::SyncKind::Metadata => c.library_sync_metadata(None).await,
};
if let Err(e) = kick {
let _ = ipc_tx.send(IpcResult::Error(format!("{label} sync failed: {e}")));
return;
}
let deadline = std::time::Instant::now() + Duration::from_secs(1800);
loop {
tokio::time::sleep(Duration::from_millis(400)).await;
match c.library_sync_status().await {
Ok(st) if !st.running => {
let msg = format!("{label} synced: {}/{} tracks", st.synced, st.total);
let _ = ipc_tx.send(IpcResult::Notification(msg, NotificationKind::Info));
if let Ok(DaemonRes::Tracks { tracks, .. }) =
c.library_get_tracks(None, None).await
{
let _ = ipc_tx.send(IpcResult::LibraryTracks(tracks));
}
break;
}
Ok(_) if std::time::Instant::now() >= deadline => {
let _ = ipc_tx.send(IpcResult::Error(format!("{label} sync timed out")));
break;
}
Ok(_) => {}
Err(e) => {
let _ = ipc_tx.send(IpcResult::Error(e.to_string()));
break;
}
}
}
});
}
pub enum TuiCommand {
Play(String),
PlayPause,
Pause,
Stop,
Next,
Prev,
Seek(f64),
SetVolume(u8),
SetMasterVolume(u8),
ToggleShuffle,
CycleRepeat(RepeatMode),
ToggleMute,
Crossfade(bool, u8),
SetCrossfadeEasing(gtm_core::state::Easing),
QueueAdd(String),
QueueMove(u64, u64),
QueueClear,
YtSearch(String),
YtDownload(String),
YtResolve(String),
SetEqPreset(gtm_core::state::EqPreset),
Search(String),
AddFavourite(i64),
Refresh,
RefreshLibrary,
RefreshYt,
RemoveTrack(i64),
RemoveFromPlaylist(i64, i64),
FetchLyrics,
SetSleepTimer(u32),
CancelSleepTimer,
CheckHealth,
}
impl App {
pub async fn new(socket_path: &Path) -> Result<Self, Box<dyn std::error::Error>> {
let client = DaemonClient::connect(socket_path).await?;
let state = DaemonState::new();
let (cmd_tx, cmd_rx) = mpsc::channel(64);
let (high_pri_cmd_tx, high_pri_cmd_rx) = mpsc::unbounded_channel();
let (ipc_tx, ipc_rx) = mpsc::unbounded_channel();
let keybindings = default_keybindings();
let prefs = tokio::task::spawn_blocking(load_prefs)
.await
.unwrap_or_else(|_| Prefs::default());
let initial_cursor = state.queue_cursor;
// Build the merged theme + footer preset tables (built-ins overridden
// by user-supplied files under ~/.config/gtm/). Resolve the persisted
// prefs by name so adding/removing a built-in never shifts the saved
// theme off its slot.
let themes = crate::theme::merged_themes();
let theme_index = themes
.iter()
.position(|t| t.name == prefs.theme_name)
.unwrap_or(0);
let theme = themes[theme_index].theme;
let footer_presets = footer::merged_presets();
let footer_preset = footer_presets
.iter()
.position(|p| p.name == prefs.footer_preset_name)
.unwrap_or(0);
Ok(Self {
theme,
themes,
client,
state,
display_position: 0.0,
last_display_position: 0.0,
frame_count: 0,
current_tab: Tab::Library,
input_mode: InputMode::Normal,
search_query: String::new(),
scroll_offset: 0,
library_category: 0,
library_pane_focus: false,
settings_category: 0,
settings_pane_focus: false,
settings_option: 0,
tracks_cache: Vec::new(),
queue_cache: Vec::new(),
queue_cursor: 0,
browse_detail: None,
yt_results_cache: Vec::new(),
playlist_cache: Vec::new(),
playlist_tracks_cache: Vec::new(),
spotify_status: None,
spotify_playlists: Vec::new(),
spotify_playlist_tracks_cache: Vec::new(),
spotify_token_input: String::new(),
cookie_file: None,
notifications: Vec::new(),
crossfade_duration: 7,
pending_delete: None,
yt_search_loading: false,
yt_search_debounce: None,
yt_search_poll_deadline: None,
pickers: PickerManager::new(),
sleep_timer_remaining: None,
sleep_timer_minutes: 30,
sleep_timer_input_mode: false,
sleep_timer_input_buf: String::new(),
playback_speed: 1.0,
current_cover: None,
last_cover_track_id: None,
cover_picker: None,
cover_stateful: None,
terminal_cols: 80,
terminal_rows: 24,
cmd_rx,
cmd_tx,
high_pri_cmd_rx,
high_pri_cmd_tx,
ipc_rx,
ipc_tx,
keybindings,
theme_index,
list_scroll: 0,
viewport_items: 20,
transparent_bg: prefs.transparent_bg,
last_action_name: None,
footer_presets,
footer_preset,
footer_title_scroll: 0,
is_ready: false,
last_queue_cursor: initial_cursor,
last_track_path_display: None,
prev_tab: Tab::Library,
prev_track_id: None,
prev_status: gtm_core::state::PlaybackStatus::Stopped,
prev_volume: 100,
prev_cover_id: None,
cover_art_dirty: false,
footer_cache: crate::footer::FooterCache::default(),
last_event_time: std::time::Instant::now(),
multiselect_mode: false,
progress_style: prefs.progress_style,
design: prefs.design,
visualizer: {
let mut v = crate::visualizer::AudioVisualizer::new();
v.preset = prefs.visualizer_preset;
v
},
selected_indices: std::collections::HashSet::new(),
pending_motion: None,
pending_playlist_track_ids: Vec::new(),
metadata_edit_track_id: None,
metadata_fields: Default::default(),
metadata_field_idx: 0,
metadata_cover: None,
metadata_cover_stateful: None,
metadata_cover_dirty: false,
pending_quit: false,
np_title_scroll: 0,
track_anim_trigger: false,
anim_fx: EffectManager::default(),
track_popup_visible: false,
track_popup_track_id: None,
track_popup_cover: None,
popup_cover_stateful: None,
last_popup_cover_fetch_id: None,
current_lyrics: None,
lyrics_scroll: 0,
lyrics_fetching: false,
show_lyrics: false,
lyrics_pane_focus: false,
show_health_panel: false,
health_report: None,
hide_help_bar: false,
lyrics_manual_scroll: false,
})
}
pub fn cmd_tx(&self) -> mpsc::Sender<TuiCommand> {
self.cmd_tx.clone()
}
pub fn send_high(&self, cmd: TuiCommand) {
let _ = self.high_pri_cmd_tx.send(cmd);
}
/// Snapshot of the user-facing preferences resolved from current indices.
/// Stored by name (not index) so adding/removing built-in themes or
/// footer presets doesn't shift what was saved.
fn current_prefs(&self) -> Prefs {
Prefs {
theme_name: self
.themes
.get(self.theme_index)
.map(|t| t.name.to_string())
.unwrap_or_else(default_theme_name),
transparent_bg: self.transparent_bg,
footer_preset_name: self
.footer_presets
.get(self.footer_preset)
.map(|p| p.name.to_string())
.unwrap_or_else(default_footer_preset_name),
progress_style: self.progress_style,
design: self.design,
visualizer_preset: self.visualizer.preset,
}
}
/// Cycle footer preset, persist, and announce the new name.
fn cycle_footer_preset(&mut self) {
let n = self.footer_presets.len().max(1);
self.footer_preset = (self.footer_preset + 1) % n;
if let Some(p) = self.footer_presets.get(self.footer_preset) {
self.set_last_action(&format!("Footer: {}", p.name));
}
save_prefs(&self.current_prefs());
}
/// Apply a theme picker selection by index, persist by name, and refresh
/// the live `theme` field.
fn apply_theme_index(&mut self, idx: usize) {
let idx = idx.min(self.themes.len().saturating_sub(1));
self.theme = self.themes[idx].theme;
self.theme_index = idx;
save_prefs(&self.current_prefs());
}
/// Cycle the design and auto-switch the theme to match, then persist.
fn cycle_design(&mut self) {
let all = Design::all();
let idx = all.iter().position(|d| *d == self.design).unwrap_or(0);
self.design = all[(idx + 1) % all.len()];
let target_theme = match self.design {
Design::Classic => "Classic",
Design::Modern => "Chadrula",
};
if let Some(idx) = self.themes.iter().position(|t| t.name == target_theme) {
self.theme_index = idx;
}
self.notify(
format!("Design: {}", self.design.name()),
NotificationKind::Info,
);
save_prefs(&self.current_prefs());
}
/// Cycle to the next theme in the list, persist, and refresh.
fn toggle_theme(&mut self) {
let next = (self.theme_index + 1) % self.themes.len();
self.apply_theme_index(next);
let name = &self.themes[next].name;
let light = if self.themes[next].light {
" (light)"
} else {
""
};
self.notify(format!("Theme: {}{}", name, light), NotificationKind::Info);
}
/// Toggle crossfade on/off and persist.
#[allow(dead_code)]
fn cycle_crossfade_type(&mut self) {
let currently_enabled = self.state.crossfade.as_ref().is_some_and(|c| c.enabled);
let new_enabled = !currently_enabled;
let duration = self
.state
.crossfade
.as_ref()
.map_or(7u8, |c| c.duration_secs);
let tx = self.cmd_tx();
tokio::spawn(async move {
let _ = tx.send(TuiCommand::Crossfade(new_enabled, duration)).await;
});
let label = if new_enabled { "ON" } else { "OFF" };
self.notify(format!("Crossfade: {}", label), NotificationKind::Info);
save_prefs(&self.current_prefs());
}
pub async fn run(
mut self,
terminal: &mut Terminal<ratatui::backend::CrosstermBackend<std::io::Stdout>>,
) -> Result<(), Box<dyn std::error::Error>> {
// All initial IPC is done in background tasks so the TUI renders
// immediately with an empty state. Results arrive via ipc_rx and
// are applied on the next loop iteration.
{
let c = self.client.clone();
let ipc_tx = self.ipc_tx.clone();
tokio::spawn(async move {
if let Ok(state) = c.get_status().await {
let _ = ipc_tx.send(IpcResult::RefreshDone(Box::new(state), None, None));
}
});
}
{
let c = self.client.clone();
let ipc_tx = self.ipc_tx.clone();
tokio::spawn(async move {
if let Ok(DaemonRes::QueueState {
queue: tracks,
cursor,
..
}) = c.queue_list().await
{
let _ = ipc_tx.send(IpcResult::Queue(tracks, cursor as usize));
}
});
}
{
let c = self.client.clone();
let ipc_tx = self.ipc_tx.clone();
tokio::spawn(async move {
if let Ok(DaemonRes::Tracks { tracks, .. }) = c.library_get_tracks(None, None).await
{
if !tracks.is_empty() {
let _ = ipc_tx.send(IpcResult::LibraryTracks(tracks));
}
}
});
}
{
let c = self.client.clone();
let ipc_tx = self.ipc_tx.clone();
tokio::spawn(async move {
if let Ok(status) = c.spotify_status().await {
let _ = ipc_tx.send(IpcResult::SpotifyStatus(status));
}
if let Ok(playlists) = c.spotify_playlists().await {
let _ = ipc_tx.send(IpcResult::SpotifyPlaylists(playlists));
}
});
}
// Initialize cover image picker in background (blocking terminal query).
{
let ipc_tx = self.ipc_tx.clone();
tokio::spawn(async move {
let picker = tokio::task::spawn_blocking(|| Picker::from_query_stdio().ok())
.await
.unwrap_or(None);
let _ = ipc_tx.send(IpcResult::CoverPicker(picker));
});
}
self.is_ready = true;
// Animate the initial frame so the library list and Now Playing pane
// evolve into view on startup.
self.track_anim_trigger = true;
// Render the initial frame immediately, before the main loop, so
// the user never sees a blank alternate screen on startup.
let _ = terminal.draw(|f| ui::render(f, &mut self));
let cmd_tx = self.cmd_tx();
tokio::spawn(async move {
loop {
tokio::time::sleep(Duration::from_millis(1000)).await;
let _ = cmd_tx.try_send(TuiCommand::Refresh);
}
});
loop {
let mut events_received = false;
let mut had_track_change = false;
let mut had_sleep_expired = false;
for ev in self.client.drain().await {
if matches!(ev, gtm_core::ipc::DaemonEvent::PlaybackStarted { .. }) {
had_track_change = true;
}
if matches!(ev, gtm_core::ipc::DaemonEvent::SleepTimerExpired) {
had_sleep_expired = true;
}
self.state.apply_event(&ev);
events_received = true;
}
if events_received {
self.last_event_time = std::time::Instant::now();
}
if had_sleep_expired {
self.sleep_timer_remaining = None;
self.notify(
"Sleep timer expired — shutting down",
NotificationKind::Info,
);
// Draw a final frame so the user sees the shutdown message
// before the terminal restores.
let _ = terminal.draw(|f| ui::render(f, &mut self));
tokio::time::sleep(Duration::from_millis(1200)).await;
// Await the daemon's reply so the quit request is actually
// delivered before the TUI exits. The daemon replies Ok then
// shuts down ~200ms later.
let c = self.client.clone();
let _ = tokio::time::timeout(Duration::from_millis(1500), c.quit()).await;
break;
}
// Sync sleep_timer_remaining from daemon state
if let Some(secs) = self.state.sleep_timer {
self.sleep_timer_remaining = Some(secs as u64);
} else if self.sleep_timer_remaining.is_some() && self.state.sleep_timer.is_none() {
self.sleep_timer_remaining = None;
}
// Re-seed clock from state after track change events so the
// local position estimate stays in sync with the daemon.
if had_track_change {
self.client.seed_clock_from_state(&self.state).await;
}
// Force a state refresh if no events received for 8s to prevent
// stale state from broadcast lag. Works in all playback states,
// not just Playing, to catch lag when paused/stopped too.
if self.last_event_time.elapsed() > Duration::from_secs(8) && self.client.is_connected()
{
let c = self.client.clone();
let ipc_tx2 = self.ipc_tx.clone();
tokio::spawn(async move {
if let Ok(state) = c.get_status().await {
let _ = ipc_tx2.send(IpcResult::RefreshDone(Box::new(state), None, None));
}
});
self.last_event_time = std::time::Instant::now();
}
self.last_queue_cursor = self.state.queue_cursor;
// Track-change detection keyed on path. Queued/foreign tracks
// share `id == 0`, so id-based detection misses auto-advance
// between them (stale elapsed, cover art and lyrics).
let current_tid = self.state.current_track.as_ref().map(|t| t.id);
let current_path = self.state.current_track.as_ref().map(|t| t.path.clone());
let track_changed = current_path.as_deref() != self.last_track_path_display.as_deref();
if track_changed {
self.last_track_path_display = current_path;
let raw = self.client.estimated_position().await;
self.display_position = raw;
self.last_display_position = raw;
self.track_anim_trigger = true;
// Re-enable auto-sync for the new track; a manual lyric scroll
// on a previous track must not stick across track changes.
self.lyrics_manual_scroll = false;
}
// Clear stale cover immediately so we don't show old art on the
// new track, then trigger a cover fetch + lyrics auto-fetch.
if track_changed {
self.current_cover = None;
self.cover_stateful = None;
// Skip cover art in Neovim terminal (no image protocol passthrough)
if !no_image_protocol() {
if let Some(tid) = current_tid {
if Some(tid) != self.last_cover_track_id {
self.last_cover_track_id = Some(tid);
let client2 = self.client.clone();
let ipc_tx2 = self.ipc_tx.clone();
tokio::spawn(async move {
if let Ok(Some(b64)) = client2.get_cover_art(tid).await {
if let Ok(bytes) =
base64::engine::general_purpose::STANDARD.decode(&b64)
{
let _ = ipc_tx2
.send(IpcResult::CoverArt(Some(bytes), Some(tid)));
}
}
});
}
}
}
// Auto-fetch lyrics if lyrics pane is visible
if self.show_lyrics {
let client3 = self.client.clone();
let ipc_tx3 = self.ipc_tx.clone();
let tpath = self.state.current_track.as_ref().map(|t| t.path.clone());
self.current_lyrics = None;
self.lyrics_fetching = true;
self.lyrics_scroll = 0;
tokio::spawn(async move {
let result = client3
.get_lyrics(current_tid.unwrap_or(0), tpath.as_deref())
.await;
let _ = ipc_tx3.send(IpcResult::Lyrics(result.unwrap_or(None)));
});
}
}
while let Ok(result) = self.ipc_rx.try_recv() {
match result {
IpcResult::RefreshDone(state, cover, cover_tid) => {
// Only apply if the new state is at least as recent as ours.
// A stale get_status() response can arrive after a PlaybackStarted
// event and overwrite the newer state if we don't guard this.
//
// Exception: a large backward version jump means the daemon
// restarted (its counter resets to 0). The fresh snapshot is
// authoritative even though its version is lower than the local
// mirror, so it must not be dropped forever.
let restarted = state.version < self.state.version
&& self.state.version.saturating_sub(state.version) > 1000;
if state.version >= self.state.version || restarted {
self.state = *state;
self.client.seed_clock_from_state(&self.state).await;
// Cover art is fetched on track-change events only.
// Do not clear last_cover_track_id when a periodic
// RefreshDone carries no cover, or the track-change
// guard would re-download art (and re-fetch lyrics)
// every second.
if !no_image_protocol() {
if let Some(c) = cover {
self.current_cover = Some(c);
self.last_cover_track_id = cover_tid;
self.sync_cover_stateful();
}
}
}
}
IpcResult::CoverArt(cover, cover_tid) => {
if !no_image_protocol() {
self.current_cover = cover;
self.last_cover_track_id = cover_tid;
self.sync_cover_stateful();
self.cover_art_dirty = true;
}
}
IpcResult::LibraryTracks(tracks) => self.tracks_cache = tracks,
IpcResult::Playlists(playlists) => self.playlist_cache = playlists,
IpcResult::PlaylistTracks(tracks) => self.playlist_tracks_cache = tracks,
IpcResult::Queue(tracks, cursor) => {
self.queue_cache = tracks.clone();
self.queue_cursor = cursor;
if self.queue_cache.is_empty() && self.state.current_track.is_none() {
self.browse_detail = None;
}
}
IpcResult::YtResults(query, results) => {
// Apply results only when they belong to the query the
// picker currently shows; stale results from a
// superseded search are dropped.
let current = self
.pickers
.top()
.filter(|t| t.id == PickerId::YTSearch)
.map(|t| t.query.clone());
if current.as_deref() == Some(query.as_str()) {
// Interleave: 1 playlist for every 3 tracks
self.yt_results_cache = Self::interleave_yt_results(results);
self.yt_search_loading = false;
}
}
IpcResult::Notification(msg, kind) => {
self.notifications.push(Notification {
message: msg,
kind,
expires_at: std::time::Instant::now() + Duration::from_secs(5),
slide_direction: SlideDirection::Right,
is_volume: false,
volume_value: 0,
animation_progress: 0.0,
});
}
IpcResult::Error(e) => {
self.notify(e, NotificationKind::Error);
}
IpcResult::PopupCoverArt(cover, track_id) => {
if !no_image_protocol() && self.track_popup_track_id == Some(track_id) {
self.track_popup_cover = cover;
self.sync_popup_cover_stateful();
}
}
IpcResult::MetadataCoverArt(cover, track_id) => {
if !no_image_protocol() && self.metadata_edit_track_id == Some(track_id) {
self.metadata_cover = cover;
self.sync_metadata_cover_stateful();
self.metadata_cover_dirty = true;
}
}
IpcResult::CoverPicker(picker) => {
self.cover_picker = picker;
}
IpcResult::Lyrics(lyrics) => {
self.current_lyrics = lyrics;
self.lyrics_fetching = false;
// Snap to the lyric line matching the current playback
// position so opening lyrics mid-track doesn't start
// with the first line highlighted.
self.lyrics_scroll = self.current_lyric_index();
}
IpcResult::HealthReport(report) => {
self.health_report = Some(report);
self.show_health_panel = true;
}
IpcResult::SpotifyStatus(s) => self.spotify_status = Some(s),
IpcResult::SpotifyPlaylists(p) => self.spotify_playlists = p,
IpcResult::SpotifyTracks(t) => self.spotify_playlist_tracks_cache = t,
}
}
while let Ok(cmd) = self.high_pri_cmd_rx.try_recv() {
self.handle_command(cmd);
}
while let Ok(cmd) = self.cmd_rx.try_recv() {
self.handle_command(cmd);
}
// YT search debounce: auto-search 500ms after last keystroke
let now = std::time::Instant::now();
if let Some(deadline) = self.yt_search_debounce {
if now >= deadline {
self.yt_search_debounce = None;
if let Some(top) = self.pickers.top() {
if top.id == PickerId::YTSearch && !top.query.is_empty() {
let q = top.query.clone();
let tx = self.cmd_tx();
let _ = tx.send(TuiCommand::YtSearch(q)).await;
}
}
}
}
// YT search polling: while a search is in flight, poll for results
// so the picker populates without requiring an extra Enter. The
// daemon runs the search on a background task; polls return the
// results once it completes.
if self.yt_search_loading
&& self
.pickers
.top()
.is_some_and(|t| t.id == PickerId::YTSearch)
{
if self.yt_search_poll_deadline.is_none() {
self.yt_search_poll_deadline = Some(now + Duration::from_millis(500));
}
if now >= self.yt_search_poll_deadline.unwrap_or(now) {
self.yt_search_poll_deadline = Some(now + Duration::from_millis(700));
let tx = self.cmd_tx();
let _ = tx.send(TuiCommand::RefreshYt).await;
}
} else {
self.yt_search_poll_deadline = None;
}
// Detect state changes
if self.current_tab != self.prev_tab {
self.prev_tab = self.current_tab;
}
let current_tid = self.state.current_track.as_ref().map(|t| t.id);
if current_tid != self.prev_track_id {
self.prev_track_id = current_tid;
}
if self.state.status != self.prev_status {
self.prev_status = self.state.status;
}
// Volume changes: update the previous volume tracker without triggering an animation.
if self.state.volume != self.prev_volume {
self.prev_volume = self.state.volume;
}
if self.last_cover_track_id != self.prev_cover_id {
self.prev_cover_id = self.last_cover_track_id;
}
let raw_pos = self.client.estimated_position().await;
// Monotonic guard: prevent large backward jumps from clock skew.
// Allow at most 0.5s of regression to avoid visible stutter.
let raw_pos = raw_pos.max(self.display_position - 0.5);
// EMA smoothing
self.display_position = self.display_position * 0.85 + raw_pos * 0.15;
// Auto-resume lyric auto-follow: after a manual scroll, once
// playback reaches the line the user scrolled to, re-enable
// auto-follow so the highlight can't stay frozen for the rest of
// the track. Reading ahead still holds until the audio catches up.
if self.lyrics_manual_scroll
&& self.show_lyrics
&& self.current_lyrics.is_some()
&& self.current_lyric_index() >= self.lyrics_scroll
{
self.lyrics_manual_scroll = false;
}
// Auto-scroll lyrics to current playback position. Not gated on
// `status == Playing` so a mirrored-status desync (e.g. after a
// daemon restart) can't freeze the highlight at the first line.
if !self.lyrics_manual_scroll && self.show_lyrics && self.current_lyrics.is_some() {
self.lyrics_scroll = self.current_lyric_index();
}
// Dirty-render: skip redraw if position hasn't changed meaningfully
// to reduce CPU usage. Always render every 10th frame as a safety net.
let frame_count = self.frame_count.wrapping_add(1);
self.frame_count = frame_count;
let pos_changed = (self.display_position - self.last_display_position).abs() >= 0.1;
// Advance title scroll animations (every 3rd frame)
if frame_count.is_multiple_of(3) {
self.footer_title_scroll = self.footer_title_scroll.wrapping_add(1);
self.np_title_scroll = self.np_title_scroll.wrapping_add(1);
}
let force_render = pos_changed
|| !self.notifications.is_empty()
|| frame_count.is_multiple_of(10)
|| self.cover_art_dirty
|| self.metadata_cover_dirty
|| self.track_anim_trigger
|| self.anim_fx.is_running();
self.cover_art_dirty = false;
self.metadata_cover_dirty = false;
self.last_display_position = self.display_position;
if force_render {
let (cols, rows) = crossterm::terminal::size().unwrap_or((80, 24));
self.terminal_cols = cols;
self.terminal_rows = rows;
if cols < 20 || rows < 6 {
let _ = terminal.draw(|f| {
let msg = Paragraph::new("Terminal too small (min 20x6)")
.alignment(Alignment::Center);
f.render_widget(msg, f.area());
});
} else if terminal.draw(|f| ui::render(f, &mut self)).is_ok() {
self.footer_cache.suppress_refresh = false;
}
}
if event::poll(Duration::from_millis(16)).unwrap_or(false) {
if let Ok(Event::Key(key)) = event::read() {
if key.kind == KeyEventKind::Press
&& (!self.handle_key(key).await || self.pending_quit)
{
break;
}
}
}
}
Ok(())
}
/// Index of the time-synced lyric line for the current playback position.
/// Untimed lines (timestamp < 0) are skipped for matching but keep their
/// index so the highlight tracks timed lines correctly.
pub fn current_lyric_index(&self) -> usize {
let Some(ref lyrics) = self.current_lyrics else {
return 0;
};
lyric_index_at(&lyrics.lines, self.display_position)
}
/// Cycle pane focus with Tab/Shift-Tab. On the Library tab with lyrics
/// open this walks left pane → right pane → lyrics pane (or the reverse
/// for Shift-Tab); otherwise it toggles the left/right panes. Leaving
/// the lyrics pane re-enables lyric auto-follow.
fn cycle_pane_focus(&mut self, forward: bool) {
match self.current_tab {
Tab::Library => {
if self.show_lyrics {
let (lib, lyr) = cycle_library_focus(
self.library_pane_focus,
self.lyrics_pane_focus,
forward,
);
self.library_pane_focus = lib;
self.lyrics_pane_focus = lyr;
if !lyr {
self.lyrics_manual_scroll = false;
}
} else {
self.library_pane_focus = !self.library_pane_focus;
}
}
Tab::Settings => {
self.settings_pane_focus = !self.settings_pane_focus;
}
}
}
pub fn notify(&mut self, message: impl Into<String>, kind: NotificationKind) {
let expires_at = std::time::Instant::now() + std::time::Duration::from_secs(4);
self.notifications.push(Notification {
message: message.into(),
kind,
expires_at,
slide_direction: SlideDirection::Right,
is_volume: false,
volume_value: 0,
animation_progress: 0.0,
});
}
/// Show a volume-change notification (vertical floating bar).
pub fn notify_volume(&mut self, volume: u8) {
let expires_at = std::time::Instant::now() + std::time::Duration::from_secs(2);
// Replace any existing volume notification
self.notifications
.retain(|n| !(n.is_volume && n.expires_at > std::time::Instant::now()));
self.notifications.push(Notification {
message: format!("Vol {}", volume),
kind: NotificationKind::Info,
expires_at,
slide_direction: SlideDirection::Right,
is_volume: true,
volume_value: volume,
animation_progress: 0.0,
});
}
/// Update the track popup to show the currently selected track in the library list.
pub fn update_track_popup(&mut self) {
let maybe_track = {
let filtered = self.filtered_tracks();
if self.scroll_offset < filtered.len() {
let t = filtered[self.scroll_offset];
Some((t.id, t.path.clone()))
} else {
None
}
};
if let Some((tid, path)) = maybe_track {
self.track_popup_track_id = Some(tid);
self.track_popup_visible = true;
let current_is_selected = self
.state
.current_track
.as_ref()
.is_some_and(|t| t.path == path);
if current_is_selected {
self.track_popup_cover = self.current_cover.clone();
self.sync_popup_cover_stateful();
self.last_popup_cover_fetch_id = None;
} else if self.last_popup_cover_fetch_id != Some(tid) && !no_image_protocol() {
self.last_popup_cover_fetch_id = Some(tid);
self.track_popup_cover = None;
let client2 = self.client.clone();
let ipc_tx2 = self.ipc_tx.clone();
tokio::spawn(async move {
if let Ok(Some(b64)) = client2.get_cover_art(tid).await {
if let Ok(bytes) = base64::engine::general_purpose::STANDARD.decode(&b64) {
let _ = ipc_tx2.send(IpcResult::PopupCoverArt(Some(bytes), tid));
}
}
});
}
} else {
self.track_popup_visible = false;
self.track_popup_track_id = None;
self.track_popup_cover = None;
self.last_popup_cover_fetch_id = None;
}
}
/// Dismiss the track popup.
pub fn dismiss_track_popup(&mut self) {
self.track_popup_visible = false;
self.track_popup_track_id = None;
self.track_popup_cover = None;
self.popup_cover_stateful = None;
self.last_popup_cover_fetch_id = None;
}
/// Filtered tracks for the current library view, respecting search query, browse_detail, and category.
pub fn filtered_tracks(&self) -> Vec<&TrackInfo> {
if self.library_category == 4 && self.browse_detail.is_some() {
return self.playlist_tracks_cache.iter().collect();
}
let mut tracks: Vec<&TrackInfo> = self.tracks_cache.iter().collect();
if !self.search_query.is_empty() {
let q = self.search_query.to_lowercase();
tracks.retain(|t| {
t.title.to_lowercase().contains(&q)
|| t.artist.to_lowercase().contains(&q)
|| t.album.to_lowercase().contains(&q)
});
}
if let Some(ref detail) = self.browse_detail {
// Drill-down must match the browse key exactly — a substring OR
// across album/artist/title pulls in unrelated tracks (e.g. an
// album name that appears in another track's title) and misses
// empty-field keys that `unique_albums`/`unique_artists` render
// as "Unknown Album"/"Unknown Artist".
tracks.retain(|t| match self.library_category {
2 => {
let album: &str = if t.album.is_empty() {
"Unknown Album"
} else {
&t.album
};
album.eq_ignore_ascii_case(detail)
}
3 => {
let artist: &str = if t.artist.is_empty() {
"Unknown Artist"
} else {
&t.artist
};
artist.eq_ignore_ascii_case(detail)
}
_ => {
t.album.eq_ignore_ascii_case(detail)
|| t.artist.eq_ignore_ascii_case(detail)
|| t.title.eq_ignore_ascii_case(detail)
}
});
}
if self.library_category == 1 {
tracks.retain(|t| t.favourite);
} else if self.library_category == 5 {
// Spotify: category renders the synced playlist browser, not a flat
// TrackInfo list — resolve/play goes through the daemon.
tracks.clear();
} else if self.library_category == 6 {
// YouTube: tracks from the youtube audio subdirectory
tracks.retain(|t| {
t.path.contains("/audio/youtube") || t.path.contains("\\audio\\youtube")
});
}
tracks
}
/// Play the track highlighted in the current library view, replacing the
/// queue with the filtered list and starting at that row.
fn play_filtered_highlighted(&self) {
let filtered = self.filtered_tracks();
if self.scroll_offset >= filtered.len() {
return;
}
let idx = self.scroll_offset;
let paths: Vec<String> = filtered.iter().map(|t| t.path.clone()).collect();
let path = paths[idx].clone();
let c = self.client.clone();
tokio::spawn(async move {
let _ = c.queue_set(paths, idx as u64).await;
let _ = c.play(&path, 0.0).await;
});
}
/// Unique album names with track counts, sorted by album.
pub fn unique_albums(&self) -> Vec<(String, usize)> {
let mut albums: std::collections::BTreeMap<String, usize> =
std::collections::BTreeMap::new();
for t in &self.tracks_cache {
let key = if t.album.is_empty() {
"Unknown Album".into()
} else {
t.album.clone()
};
*albums.entry(key).or_insert(0) += 1;
}
albums.into_iter().collect()
}
/// Length of the list currently visible in the library right pane,
/// depending on the active category and drill-down state.
pub fn library_list_len(&self) -> usize {
if self.browse_detail.is_some() {
if self.library_category == 5 {
return self.spotify_playlist_tracks_cache.len();
}
return self.filtered_tracks().len();
}
match self.library_category {
2 => self.unique_albums().len(),
3 => self.unique_artists().len(),
4 => self.playlist_cache.len(),
5 => self.spotify_playlists.len(),
_ => self.filtered_tracks().len(),
}
}
/// Unique artist names with track counts, sorted by artist.
pub fn unique_artists(&self) -> Vec<(String, usize)> {
let mut artists: std::collections::BTreeMap<String, usize> =
std::collections::BTreeMap::new();
for t in &self.tracks_cache {
let key = if t.artist.is_empty() {
"Unknown Artist".into()
} else {
t.artist.clone()
};
*artists.entry(key).or_insert(0) += 1;
}
artists.into_iter().collect()
}
fn sync_cover_stateful(&mut self) {
match (&self.current_cover, &self.cover_picker) {
(Some(bytes), Some(picker)) => {
if let Ok(img) = image::load_from_memory(bytes) {
self.cover_stateful = Some(picker.new_resize_protocol(img));
} else {
self.cover_stateful = None;
}
}
_ => self.cover_stateful = None,
}
}
fn sync_popup_cover_stateful(&mut self) {
match (&self.track_popup_cover, &self.cover_picker) {
(Some(bytes), Some(picker)) => {
if let Ok(img) = image::load_from_memory(bytes) {
self.popup_cover_stateful = Some(picker.new_resize_protocol(img));
} else {
self.popup_cover_stateful = None;
}
}
_ => self.popup_cover_stateful = None,
}
}
/// (Re)build the stateful cover protocol for the Edit Metadata preview.
fn sync_metadata_cover_stateful(&mut self) {
match (&self.metadata_cover, &self.cover_picker) {
(Some(bytes), Some(picker)) => {
if let Ok(img) = image::load_from_memory(bytes) {
self.metadata_cover_stateful = Some(picker.new_resize_protocol(img));
} else {
self.metadata_cover_stateful = None;
}
}
_ => self.metadata_cover_stateful = None,
}
}
/// Fetch the cover art for the track currently being edited and stream it
/// to the `MetadataCoverArt` IPC channel so the preview can refresh.
fn fetch_metadata_cover(&self) {
let Some(track_id) = self.metadata_edit_track_id else {
return;
};
if no_image_protocol() {
return;
}
let client = self.client.clone();
let ipc_tx = self.ipc_tx.clone();
tokio::spawn(async move {
if let Ok(Some(b64)) = client.get_cover_art(track_id).await {
if let Ok(bytes) = base64::engine::general_purpose::STANDARD.decode(&b64) {
let _ = ipc_tx.send(IpcResult::MetadataCoverArt(Some(bytes), track_id));
}
}
});
}
fn settings_options_for_category(&self) -> usize {
match self.settings_category {
0 => 3, // Audio: Master Volume, Volume, Mute
1 => 8, // YouTube
2 => 4, // Playback: Repeat, Shuffle, Crossfade, Easing
3 => 7, // System: Theme, Transparent BG, Sync Covers, Sync Lyrics, Sync Metadata, Footer Preset, Visualizer Preset
4 => 6, // Spotify: Status, Account, Playlists, Link, Sync, Unlink
_ => 0,
}
}
async fn fetch_queue(&mut self) {
if let Ok(DaemonRes::QueueState {
queue: tracks,
cursor,
..
}) = self.client.queue_list().await
{
self.queue_cache = tracks;
self.queue_cursor = cursor as usize;
}
}
fn handle_command(&mut self, cmd: TuiCommand) {
// All IPC calls are spawned as background tasks to avoid blocking the UI loop.
let client = self.client.clone();
let ipc_tx = self.ipc_tx.clone();
let err_tx = ipc_tx.clone();
let error_handler = move |e: gtm_core::CoreError| {
let _ = err_tx.send(IpcResult::Error(e.to_string()));
};
let err_tx2 = ipc_tx.clone();
let error_handler2 = move |e: gtm_core::CoreError| {
let _ = err_tx2.send(IpcResult::Error(e.to_string()));
};
match cmd {
TuiCommand::Play(path) => {
tokio::spawn(async move {
if let Err(e) = client.play(&path, 0.0).await {
error_handler(e);
}
});
}
TuiCommand::PlayPause => {
tokio::spawn(async move {
if let Err(e) = client.play_pause().await {
error_handler(e);
}
});
}
TuiCommand::Pause => {
tokio::spawn(async move {
if let Err(e) = client.pause().await {
error_handler(e);
}
});
}
TuiCommand::Stop => {
tokio::spawn(async move {
if let Err(e) = client.stop().await {
error_handler(e);
}
});
}
TuiCommand::Next => {
tokio::spawn(async move {
if let Err(e) = client.next().await {
error_handler(e);
}
});
}
TuiCommand::Prev => {
tokio::spawn(async move {
if let Err(e) = client.prev().await {
error_handler(e);
}
});
}
TuiCommand::Seek(pos) => {
tokio::spawn(async move {
if let Err(e) = client.seek(pos).await {
error_handler(e);
}
});
}
TuiCommand::SetVolume(v) => {
tokio::spawn(async move {
if let Err(e) = client.set_volume(v).await {
error_handler(e);
}
});
}
TuiCommand::SetMasterVolume(v) => {
tokio::spawn(async move {
if let Err(e) = client.set_master_volume(v).await {
error_handler(e);
}
});
}
TuiCommand::ToggleShuffle => {
tokio::spawn(async move {
if let Err(e) = client.toggle_shuffle().await {
error_handler(e);
}
});
}
TuiCommand::CycleRepeat(m) => {
tokio::spawn(async move {
if let Err(e) = client.cycle_repeat(m).await {
error_handler(e);
}
});
}
TuiCommand::ToggleMute => {
tokio::spawn(async move {
if let Err(e) = client.toggle_mute().await {
error_handler(e);
}
});
}
TuiCommand::Crossfade(en, dur) => {
tokio::spawn(async move {
if let Err(e) = client.crossfade(en, dur, None).await {
error_handler(e);
}
});
}
TuiCommand::SetCrossfadeEasing(_easing) => {
// TODO: pass easing through crossfade command
}
TuiCommand::QueueAdd(p) => {
tokio::spawn(async move {
if let Err(e) = client.queue_add(&p, None).await {
error_handler2(e);
}
});
}
TuiCommand::QueueMove(from, to) => {
tokio::spawn(async move {
if let Err(e) = client.queue_move(from, to).await {
error_handler(e);
}
});
}
TuiCommand::QueueClear => {
tokio::spawn(async move {
if let Err(e) = client.queue_clear().await {
error_handler(e);
}
});
}
TuiCommand::YtSearch(q) => {
self.yt_search_loading = true;
self.yt_results_cache.clear();
let c = client.clone();
tokio::spawn(async move {
if let Err(e) = c.yt_search(&q, None).await {
error_handler2(e);
}
});
}
TuiCommand::YtDownload(url) => {
self.notify("Download started…", NotificationKind::Info);
let ipc = ipc_tx.clone();
let client2 = self.client.clone();
tokio::spawn(async move {
let audio_dir = std::env::var("XDG_DATA_HOME")
.map(|d| std::path::PathBuf::from(d).join("gtm").join("audio"))
.unwrap_or_else(|_| {
let home = std::env::var("HOME").unwrap_or_else(|_| "/tmp".into());
std::path::PathBuf::from(home).join(".local/share/gtm/audio")
});
std::fs::create_dir_all(&audio_dir).ok();
let template = audio_dir.join("%(title)s.%(ext)s");
let output = tokio::process::Command::new("yt-dlp")
.arg("--extract-audio")
.arg("--audio-format")
.arg("mp3")
.arg("--restrict-filenames")
.arg("-o")
.arg(template.to_string_lossy().as_ref())
.arg(&url)
.output()
.await;
let msg = match output {
Ok(o) if o.status.success() => {
let _ = client2
.library_scan(audio_dir.to_string_lossy().as_ref())
.await;
// Also refresh the track cache
if let Ok(DaemonRes::Tracks { tracks, .. }) =
client2.library_get_tracks(None, None).await
{
let _ = ipc.send(IpcResult::LibraryTracks(tracks));
}
// Try to fetch lyrics for the newly downloaded track
let stdout_text = String::from_utf8_lossy(&o.stdout).to_string();
let filename = stdout_text.lines().next().unwrap_or(&url).to_string();
// Find the track by filename substring match in library
if let Ok(DaemonRes::Tracks { tracks, .. }) =
client2.library_get_tracks(None, None).await
{
if let Some(track) = tracks
.iter()
.find(|t| {
filename.contains(&t.title)
|| t.path.contains(filename.trim_end_matches(".mp3"))
})
.or_else(|| tracks.last())
{
if let Ok(Some(lyrics_data)) =
client2.get_lyrics(track.id, Some(&track.path)).await
{
if !lyrics_data.lines.is_empty() {
// Write .lrc sidecar next to the audio file
let lrc_path = {
let p = std::path::PathBuf::from(&track.path);
p.with_extension("lrc")
};
let mut lrc_content = String::new();
if let Some(ref ar) = lyrics_data.artist {
lrc_content.push_str(&format!("[ar:{}]\n", ar));
}
if let Some(ref al) = lyrics_data.album {
lrc_content.push_str(&format!("[al:{}]\n", al));
}
if let Some(ref ti) = lyrics_data.title {
lrc_content.push_str(&format!("[ti:{}]\n", ti));
}
for line in &lyrics_data.lines {
if line.timestamp < 0.0 {
lrc_content.push_str(&line.text);
lrc_content.push('\n');
continue;
}
let mins = (line.timestamp / 60.0) as u64;
let secs = line.timestamp - (mins as f64 * 60.0);
lrc_content.push_str(&format!(
"[{:02}:{:05.2}]{}\n",
mins, secs, line.text
));
}
let _ = std::fs::write(&lrc_path, lrc_content);
}
}
}
}
format!("Downloaded: {}", filename)
}
Ok(o) => format!(
"Download failed: {}",
String::from_utf8_lossy(&o.stderr)
.lines()
.last()
.unwrap_or("unknown error")
),
Err(e) => format!("Download error: {e}"),
};
let kind = if msg.starts_with("Downloaded") {
crate::app::NotificationKind::Success
} else {
crate::app::NotificationKind::Error
};
let _ = ipc.send(IpcResult::Notification(msg, kind));
});
}
TuiCommand::YtResolve(u) => {
tokio::spawn(async move {
if let Err(e) = client.yt_resolve_stream(&u).await {
error_handler2(e);
}
});
}
TuiCommand::SetEqPreset(preset) => {
tokio::spawn(async move {
if let Err(e) = client.set_eq_preset(preset).await {
error_handler(e);
}
});
}
TuiCommand::Search(q) => {
tokio::spawn(async move {
if let Err(e) = client.search(&q).await {
error_handler2(e);
}
});
}
TuiCommand::AddFavourite(id) => {
tokio::spawn(async move {
if let Err(e) = client.add_favourite(id).await {
error_handler(e);
}
});
}
TuiCommand::Refresh => {
let client2 = self.client.clone();
let ipc_tx2 = self.ipc_tx.clone();
tokio::spawn(async move {
if let Ok(state) = client2.get_status().await {
// Cover art is fetched on track-change events, not
// here, to avoid an extra IPC call every second.
let _ = ipc_tx2.send(IpcResult::RefreshDone(Box::new(state), None, None));
}
// Also refresh queue to recover from initial background
// spawn failures that leave queue_cache empty.
if let Ok(DaemonRes::QueueState {
queue: tracks,
cursor,
..
}) = client2.queue_list().await
{
let _ = ipc_tx2.send(IpcResult::Queue(tracks, cursor as usize));
}
});
}
TuiCommand::RefreshLibrary => {
tokio::spawn(async move {
if let Ok(DaemonRes::Tracks { tracks, .. }) =
client.library_get_tracks(None, None).await
{
let _ = ipc_tx.send(IpcResult::LibraryTracks(tracks));
}
});
}
TuiCommand::RefreshYt => {
tokio::spawn(async move {
if let Ok(DaemonRes::YtSearchResults { query, results }) =
client.yt_search_poll().await
{
let _ = ipc_tx.send(IpcResult::YtResults(query, results));
}
});
}
TuiCommand::RemoveTrack(track_id) => {
tokio::spawn(async move {
if let Err(e) = client.library_remove_track(track_id).await {
error_handler(e);
} else {
let _ = ipc_tx.send(IpcResult::Notification(
"Track deleted".to_string(),
NotificationKind::Success,
));
if let Ok(DaemonRes::Tracks { tracks, .. }) =
client.library_get_tracks(None, None).await
{
let _ = ipc_tx.send(IpcResult::LibraryTracks(tracks));
}
}
});
}
TuiCommand::RemoveFromPlaylist(playlist_id, track_id) => {
tokio::spawn(async move {
if let Err(e) = client
.library_remove_from_playlist(playlist_id, track_id)
.await
{
error_handler(e);
} else {
let _ = ipc_tx.send(IpcResult::Notification(
"Removed from playlist".to_string(),
NotificationKind::Success,
));
if let Ok(DaemonRes::Playlists { playlists, .. }) =
client.library_get_playlists().await
{
let _ = ipc_tx.send(IpcResult::Playlists(playlists));
}
}
});
}
TuiCommand::FetchLyrics => {
let track_path = self.state.current_track.as_ref().map(|t| t.path.clone());
let track_id = self.state.current_track.as_ref().map(|t| t.id).unwrap_or(0);
let client2 = self.client.clone();
let ipc_tx2 = self.ipc_tx.clone();
tokio::spawn(async move {
let result = tokio::time::timeout(
Duration::from_secs(5),
client2.get_lyrics(track_id, track_path.as_deref()),
)
.await;
let _ = ipc_tx2.send(IpcResult::Lyrics(match result {
Ok(r) => r.unwrap_or(None),
Err(_) => None,
}));
});
}
TuiCommand::SetSleepTimer(minutes) => {
let client = self.client.clone();
let ipc_tx = self.ipc_tx.clone();
tokio::spawn(async move {
if let Err(e) = client.set_sleep_timer(minutes).await {
let _ = ipc_tx.send(IpcResult::Error(e.to_string()));
}
});
}
TuiCommand::CancelSleepTimer => {
let client = self.client.clone();
let ipc_tx = self.ipc_tx.clone();
tokio::spawn(async move {
if let Err(e) = client.cancel_sleep_timer().await {
let _ = ipc_tx.send(IpcResult::Error(e.to_string()));
}
});
}
TuiCommand::CheckHealth => {
let client = self.client.clone();
let ipc_tx = self.ipc_tx.clone();
tokio::spawn(async move {
match client.check_health().await {
Ok(report) => {
let _ = ipc_tx.send(IpcResult::HealthReport(report));
}
Err(e) => {
let _ = ipc_tx.send(IpcResult::Error(e.to_string()));
}
}
});
}
};
}
fn set_last_action(&mut self, name: &str) {
self.last_action_name = Some((
name.to_string(),
std::time::Instant::now() + std::time::Duration::from_secs(3),
));
}
fn clamp_picker_selection(&mut self) {
if let Some(top) = self.pickers.top_mut() {
let max = match top.id {
PickerId::Queue => self.queue_cache.len().saturating_sub(1),
PickerId::YTSearch => self.yt_results_cache.len().saturating_sub(1),
PickerId::SearchLibrary => {
let q = top.query.to_lowercase();
if q.is_empty() {
self.tracks_cache.len()
} else {
self.tracks_cache
.iter()
.filter(|t| {
t.title.to_lowercase().contains(&q)
|| t.artist.to_lowercase().contains(&q)
})
.count()
}
.saturating_sub(1)
}
PickerId::Equalizer => {
let presets = [
gtm_core::state::EqPreset::Flat,
gtm_core::state::EqPreset::Normal,
gtm_core::state::EqPreset::Pop,
gtm_core::state::EqPreset::Rock,
gtm_core::state::EqPreset::Jazz,
gtm_core::state::EqPreset::Classical,
gtm_core::state::EqPreset::Bass,
gtm_core::state::EqPreset::Vocal,
gtm_core::state::EqPreset::Electronic,
gtm_core::state::EqPreset::HipHop,
gtm_core::state::EqPreset::Latin,
gtm_core::state::EqPreset::Acoustic,
gtm_core::state::EqPreset::Podcast,
gtm_core::state::EqPreset::Dance,
gtm_core::state::EqPreset::Headphones,
gtm_core::state::EqPreset::Speaker,
];
presets.len().saturating_sub(1)
}
PickerId::SleepTimer => 4,
PickerId::ThemePicker => {
let q = top.query.to_lowercase();
if q.is_empty() {
self.themes.len()
} else {
self.themes
.iter()
.filter(|entry| {
let lower = entry.name.to_lowercase();
let mut qi = 0usize;
for ch in lower.chars() {
if qi < q.len() && ch == q.as_bytes()[qi] as char {
qi += 1;
}
}
qi == q.len()
})
.count()
}
.saturating_sub(1)
}
PickerId::CommandPalette => {
let commands = crate::ui::COMMAND_PALETTE_COMMANDS;
let q = top.query.to_lowercase();
if q.is_empty() {
commands.len()
} else {
commands
.iter()
.filter(|c| {
let lower = c.0.to_lowercase();
let mut qi = 0usize;
for ch in lower.chars() {
if qi < q.len() && ch == q.as_bytes()[qi] as char {
qi += 1;
}
}
qi == q.len()
})
.count()
}
.saturating_sub(1)
}
_ => usize::MAX,
};
top.selected = top.selected.min(max);
}
}
fn help_picker_total(&self) -> usize {
let help_lines = [
("topic", "Playback"),
("key", " Space Play / Pause"),
("key", " n / Ctrl+N Next track"),
("key", " p / Ctrl+P Previous track"),
("key", " s Stop"),
("key", " . / , Seek forward / back"),
("", ""),
("topic", "Volume"),
("key", " + / = Volume up"),
("key", " - Volume down"),
("key", " m Toggle mute"),
("", ""),
("topic", "Queue & Library"),
("key", " Enter Play selected / drill-down"),
("key", " d / Del Remove item"),
("key", " F Toggle favourite"),
("key", " D Clear queue"),
("key", " / Filter mode"),
("", ""),
("topic", "Navigation"),
("key", " Tab Toggle left/right pane focus"),
("key", " j/k / arrows Move up/down"),
("key", " h/l Focus left/right pane"),
("key", " ? Toggle this help"),
("", ""),
("topic", "Overlays (Alt+key)"),
("key", " Alt+Q Queue"),
("key", " Alt+Y YouTube Search"),
("key", " Alt+F Search Library"),
("key", " Alt+A About"),
("key", " Alt+C Theme Picker"),
("key", " Alt+E Equalizer"),
("key", " Alt+P Command Palette"),
("key", " Alt+Z Sleep Timer"),
("key", " Alt+X Sound Effects"),
("key", " Alt+S Spotify Search"),
("", ""),
("topic", "Other"),
("key", " q Quit"),
("key", " Q / Ctrl+Q Quit & stop daemon"),
("key", " S Toggle shuffle"),
("key", " r / R Cycle repeat"),
("key", " : Command palette"),
("", ""),
("topic", "Help"),
("key", " ? Toggle this help"),
("key", " gg / G Jump to top / bottom"),
("key", " 0 / $ Jump to first / last line"),
("key", " / Search"),
("key", " n / N Next / previous match"),
("key", " Esc / q Close"),
];
if let Some(top) = self.pickers.top() {
if top.id == PickerId::Help {
let q = top.query.to_lowercase();
if q.is_empty() {
help_lines.len()
} else {
help_lines
.iter()
.filter(|(_, l)| l.to_lowercase().contains(&q))
.count()
}
} else {
0
}
} else {
0
}
}
async fn handle_key(&mut self, key: event::KeyEvent) -> bool {
// Reset pending_motion if the key is not 'g'
if key.code != KeyCode::Char('g') {
self.pending_motion = None;
}
// If an picker is open, Esc closes it; keys pass through to picker
if self.pickers.is_open() {
return match key.code {
KeyCode::Esc => {
self.pickers.close_top();
true
}
_ => {
// Pass key to picker handler
self.handle_picker_key(key).await;
true
}
};
}
match self.input_mode {
InputMode::Searching => match key.code {
KeyCode::Esc => {
self.input_mode = InputMode::Normal;
self.search_query.clear();
}
KeyCode::Enter => {
let q = self.search_query.clone();
self.input_mode = InputMode::Normal;
match self.current_tab {
Tab::Library => {
// Commit the filter without clearing it and play
// the highlighted row in the filtered list.
self.play_filtered_highlighted();
}
_ => {
let tx = self.cmd_tx();
let _ = tx.send(TuiCommand::Search(q)).await;
self.search_query.clear();
}
}
}
KeyCode::Char(c) => {
self.search_query.push(c);
}
KeyCode::Backspace => {
self.search_query.pop();
}
_ => {}
},
InputMode::Normal => {
// If a delete confirmation is pending, intercept Enter/Esc
if self.pending_delete.is_some() {
match key.code {
KeyCode::Enter => {
if let Some((track_id, track_name)) = self.pending_delete.take() {
let tx = self.cmd_tx();
let _ = tx.send(TuiCommand::RemoveTrack(track_id)).await;
self.notify(
format!("Deleted: {track_name}"),
NotificationKind::Success,
);
}
}
KeyCode::Esc => {
self.pending_delete = None;
}
_ => {}
}
return true;
}
// Health panel: Esc closes it
if self.show_health_panel && key.code == KeyCode::Esc {
self.show_health_panel = false;
return true;
}
// Handle gg (vim-style double-press) for jump to start
if key.code == KeyCode::Char('g')
&& self.current_tab == Tab::Library
&& !self.library_pane_focus
{
if self.pending_motion == Some('g') {
// Second 'g' — execute jump to start
self.pending_motion = None;
self.scroll_offset = 0;
return true;
} else {
// First 'g' — wait for second press
self.pending_motion = Some('g');
return true;
}
}
// In multiselect mode, Tab toggles selection and advances
if key.code == KeyCode::Tab
&& self.multiselect_mode
&& self.current_tab == Tab::Library
&& !self.library_pane_focus
{
if self.selected_indices.contains(&self.scroll_offset) {
self.selected_indices.remove(&self.scroll_offset);
} else {
self.selected_indices.insert(self.scroll_offset);
}
let max = self.filtered_tracks().len().saturating_sub(1);
self.scroll_offset = (self.scroll_offset + 1).min(max);
let count = self.selected_indices.len();
self.notify(format!("{count} selected"), NotificationKind::Info);
return true;
}
match self.keybindings.dispatch(key, KeyContext::Normal) {
Some(KeyboardAction::Quit) => {
if self.browse_detail.is_some() {
self.browse_detail = None;
self.scroll_offset = 0;
if self.library_category == 5 {
self.spotify_playlist_tracks_cache.clear();
}
} else {
return false;
}
}
Some(KeyboardAction::QuitDaemon) => {
let c = self.client.clone();
// Await the daemon's reply so the quit request is
// actually delivered before the TUI exits. The daemon
// replies Ok then shuts down ~200ms later.
let _ = tokio::time::timeout(Duration::from_millis(1500), c.quit()).await;
return false;
}
Some(KeyboardAction::NextTab) => {
self.cycle_pane_focus(true);
self.dismiss_track_popup();
}
Some(KeyboardAction::PrevTab) => {
self.cycle_pane_focus(false);
self.dismiss_track_popup();
}
Some(KeyboardAction::SwitchTab(tab)) => {
if self.current_tab != tab {
self.current_tab = tab;
self.library_pane_focus = false;
self.settings_pane_focus = false;
self.lyrics_pane_focus = false;
self.lyrics_manual_scroll = false;
self.browse_detail = None;
self.scroll_offset = 0;
}
self.dismiss_track_popup();
}
Some(KeyboardAction::OpenOverlay(id)) => {
self.pickers.open(id);
self.dismiss_track_popup();
}
Some(KeyboardAction::ToggleHelp) => {
if self.pickers.top().is_some_and(|o| o.id == PickerId::Help) {
self.pickers.close_top();
} else {
self.pickers.open(PickerId::Help);
self.dismiss_track_popup();
}
}
Some(KeyboardAction::HideHelpBar) => {
self.hide_help_bar = !self.hide_help_bar;
}
Some(KeyboardAction::PlayPause) => {
self.set_last_action("Play/Pause");
match self.state.status {
PlaybackStatus::Playing => {
self.send_high(TuiCommand::Pause);
}
PlaybackStatus::Paused => {
self.send_high(TuiCommand::PlayPause);
}
PlaybackStatus::Stopped => {
if !self.queue_cache.is_empty() {
let idx = self.queue_cursor.min(self.queue_cache.len() - 1);
let path = self.queue_cache[idx].path.clone();
self.send_high(TuiCommand::Play(path));
}
}
}
}
Some(KeyboardAction::Next) => {
self.set_last_action("Next");
self.send_high(TuiCommand::Next);
}
Some(KeyboardAction::Prev) => {
self.set_last_action("Previous");
self.send_high(TuiCommand::Prev);
}
Some(KeyboardAction::Stop) => {
self.set_last_action("Stop");
self.send_high(TuiCommand::Stop);
}
Some(KeyboardAction::VolumeUp) => {
let new_vol = (self.state.volume + 5).min(100);
self.send_high(TuiCommand::SetVolume(new_vol));
self.notify_volume(new_vol);
}
Some(KeyboardAction::VolumeDown) => {
self.set_last_action("Volume Down");
let new_vol = self.state.volume.saturating_sub(5);
self.send_high(TuiCommand::SetVolume(new_vol));
self.notify_volume(new_vol);
}
Some(KeyboardAction::SeekForward) => {
self.set_last_action("Seek Forward");
let pos = (self.display_position + 5.0).min(self.state.duration);
self.send_high(TuiCommand::Seek(pos));
}
Some(KeyboardAction::SeekBackward) => {
self.set_last_action("SeekBackward");
let pos = (self.display_position - 5.0).max(0.0);
self.send_high(TuiCommand::Seek(pos));
}
Some(KeyboardAction::ToggleMute) => {
self.set_last_action("Toggle Mute");
self.send_high(TuiCommand::ToggleMute);
if self.state.mute {
self.notify("Unmuted", NotificationKind::Info);
} else {
self.notify("Muted", NotificationKind::Warning);
}
}
Some(KeyboardAction::CycleRepeat) => {
self.set_last_action("Cycle Repeat");
let new_mode = match self.state.repeat {
RepeatMode::Off => RepeatMode::One,
RepeatMode::One => RepeatMode::All,
RepeatMode::All => RepeatMode::Off,
};
self.send_high(TuiCommand::CycleRepeat(new_mode));
self.notify(format!("Repeat: {:?}", new_mode), NotificationKind::Info);
}
Some(KeyboardAction::ToggleShuffle) => {
self.set_last_action("Toggle Shuffle");
self.send_high(TuiCommand::ToggleShuffle);
if self.state.shuffle {
self.notify("Shuffle OFF", NotificationKind::Info);
} else {
self.notify("Shuffle ON", NotificationKind::Info);
}
}
Some(KeyboardAction::ToggleFavourite) => {
self.set_last_action("Toggle Favourite");
if let Some(ref track) = self.state.current_track {
let track_id = track.id;
let new_fav = !track.favourite;
if let Some(ref mut ct) = self.state.current_track {
ct.favourite = new_fav;
}
for t in &mut self.tracks_cache {
if t.id == track_id {
t.favourite = new_fav;
break;
}
}
let tx = self.cmd_tx();
let _ = tx.send(TuiCommand::AddFavourite(track_id)).await;
self.notify("Favourite toggled", NotificationKind::Info);
}
}
Some(KeyboardAction::ClearQueue) => {
self.set_last_action("Clear Queue");
let tx = self.cmd_tx();
let _ = tx.send(TuiCommand::QueueClear).await;
self.notify("Queue cleared", NotificationKind::Info);
}
Some(KeyboardAction::ToggleVisualizer) => {
self.visualizer.toggle();
let state = if self.visualizer.is_enabled() {
"ON"
} else {
"OFF"
};
self.notify(format!("Visualizer: {}", state), NotificationKind::Info);
}
Some(KeyboardAction::ToggleTheme) => {
self.toggle_theme();
}
Some(KeyboardAction::CheckHealth) => {
self.send_high(TuiCommand::CheckHealth);
}
Some(KeyboardAction::FocusLeft) => {
if self.show_lyrics && self.current_tab == Tab::Library {
if self.lyrics_pane_focus {
// lyrics → right (track) pane
self.lyrics_pane_focus = false;
self.lyrics_manual_scroll = false;
self.library_pane_focus = false;
} else {
self.library_pane_focus = true;
}
} else {
match self.current_tab {
Tab::Library => self.library_pane_focus = true,
Tab::Settings => self.settings_pane_focus = true,
}
}
}
Some(KeyboardAction::FocusRight) => {
if self.show_lyrics && self.current_tab == Tab::Library {
if self.library_pane_focus {
// left → right (track) pane
self.library_pane_focus = false;
} else {
// right pane → lyrics pane
self.lyrics_pane_focus = true;
}
} else {
match self.current_tab {
Tab::Library => self.library_pane_focus = false,
Tab::Settings => self.settings_pane_focus = false,
}
}
}
Some(KeyboardAction::Back) => {
if self.lyrics_pane_focus {
// Exit lyrics focus back to the track pane.
self.lyrics_pane_focus = false;
self.lyrics_manual_scroll = false;
} else {
let is_narrow = self.terminal_cols < 60;
if is_narrow && self.show_lyrics {
self.show_lyrics = false;
} else if self.browse_detail.is_some() {
self.browse_detail = None;
self.scroll_offset = 0;
if self.library_category == 5 {
self.spotify_playlist_tracks_cache.clear();
}
} else if !self.library_pane_focus && self.current_tab == Tab::Library {
self.library_pane_focus = true;
}
}
}
Some(KeyboardAction::FetchLyrics) => {
self.show_lyrics = !self.show_lyrics;
if !self.show_lyrics {
self.lyrics_pane_focus = false;
self.lyrics_manual_scroll = false;
}
if self.show_lyrics && self.current_lyrics.is_none() {
self.lyrics_fetching = true;
self.send_high(TuiCommand::FetchLyrics);
}
self.dismiss_track_popup();
}
Some(KeyboardAction::EnterFilter) => {
self.input_mode = InputMode::Searching;
self.dismiss_track_popup();
}
Some(KeyboardAction::MoveUp) => {
if self.lyrics_pane_focus && self.show_lyrics {
self.lyrics_manual_scroll = true;
self.lyrics_scroll = self.lyrics_scroll.saturating_sub(1);
} else {
match self.current_tab {
Tab::Library if self.library_pane_focus => {
let new_cat = self.library_category.saturating_sub(1);
if new_cat != self.library_category {
self.browse_detail = None;
self.scroll_offset = 0;
}
self.library_category = new_cat;
}
Tab::Settings if self.settings_pane_focus => {
self.settings_category =
self.settings_category.saturating_sub(1);
self.settings_option = 0;
}
Tab::Settings => {
self.settings_option = self.settings_option.saturating_sub(1);
}
Tab::Library => {
self.scroll_offset = self.scroll_offset.saturating_sub(1);
self.update_track_popup();
}
}
}
}
Some(KeyboardAction::MoveDown) => {
if self.lyrics_pane_focus && self.show_lyrics {
self.lyrics_manual_scroll = true;
let max = self
.current_lyrics
.as_ref()
.map(|l| l.lines.len().saturating_sub(1))
.unwrap_or(0);
self.lyrics_scroll = (self.lyrics_scroll + 1).min(max);
} else {
match self.current_tab {
Tab::Library if self.library_pane_focus => {
let new_cat = (self.library_category + 1)
.min(LIBRARY_CATEGORIES.len() - 1);
if new_cat != self.library_category {
self.browse_detail = None;
self.scroll_offset = 0;
}
self.library_category = new_cat;
}
Tab::Settings if self.settings_pane_focus => {
self.settings_category = (self.settings_category + 1)
.min(NUM_SETTINGS_CATEGORIES.saturating_sub(1));
self.settings_option = 0;
}
Tab::Settings => {
let max =
self.settings_options_for_category().saturating_sub(1);
self.settings_option = (self.settings_option + 1).min(max);
}
Tab::Library => {
let max_list = self.library_list_len().saturating_sub(1);
self.scroll_offset = (self.scroll_offset + 1).min(max_list);
self.update_track_popup();
}
}
}
}
Some(KeyboardAction::PageUp) => {
if self.lyrics_pane_focus && self.show_lyrics {
self.lyrics_manual_scroll = true;
let page = self.viewport_items.max(1);
self.lyrics_scroll = self.lyrics_scroll.saturating_sub(page);
} else if self.current_tab == Tab::Library && !self.library_pane_focus {
let page = self.viewport_items.max(1);
self.scroll_offset = self.scroll_offset.saturating_sub(page);
self.update_track_popup();
}
}
Some(KeyboardAction::PageDown) => {
if self.lyrics_pane_focus && self.show_lyrics {
self.lyrics_manual_scroll = true;
let page = self.viewport_items.max(1);
let max = self
.current_lyrics
.as_ref()
.map(|l| l.lines.len().saturating_sub(1))
.unwrap_or(0);
self.lyrics_scroll = (self.lyrics_scroll + page).min(max);
} else if self.current_tab == Tab::Library && !self.library_pane_focus {
let page = self.viewport_items.max(1);
let max_list = self.library_list_len().saturating_sub(1);
self.scroll_offset = (self.scroll_offset + page).min(max_list);
self.update_track_popup();
}
}
Some(KeyboardAction::Top) => {
if self.lyrics_pane_focus && self.show_lyrics {
self.lyrics_manual_scroll = true;
self.lyrics_scroll = 0;
} else if self.current_tab == Tab::Library && !self.library_pane_focus {
self.scroll_offset = 0;
}
}
Some(KeyboardAction::Bottom) => {
if self.lyrics_pane_focus && self.show_lyrics {
self.lyrics_manual_scroll = true;
let max = self
.current_lyrics
.as_ref()
.map(|l| l.lines.len().saturating_sub(1))
.unwrap_or(0);
self.lyrics_scroll = max;
} else if self.current_tab == Tab::Library && !self.library_pane_focus {
let max_list = self.library_list_len().saturating_sub(1);
self.scroll_offset = max_list;
}
}
Some(KeyboardAction::Select) => {
if self.current_tab == Tab::Library {
if self.library_pane_focus {
self.library_pane_focus = false;
} else if self.browse_detail.is_some() {
// In detail view: play the selected track
if self.library_category == 5 {
// Spotify playlist: resolve track to a playable
// local stream (via YouTube) and enqueue it.
if self.scroll_offset < self.spotify_playlist_tracks_cache.len()
{
let playlist_id =
self.browse_detail.clone().unwrap_or_default();
let track_index = self.spotify_playlist_tracks_cache
[self.scroll_offset]
.index;
let c = self.client.clone();
let ipc_tx2 = self.ipc_tx.clone();
tokio::spawn(async move {
match c.spotify_resolve(&playlist_id, track_index).await
{
Ok(()) => {
let _ = ipc_tx2.send(IpcResult::Notification(
"Spotify track resolved & queued"
.to_string(),
NotificationKind::Success,
));
}
Err(e) => {
let _ = ipc_tx2.send(IpcResult::Error(
format!("Spotify resolve failed: {e}"),
));
}
}
});
}
} else {
self.play_filtered_highlighted();
}
} else if self.library_category == 2 {
// Albums: select album → show its tracks
let albums = self.unique_albums();
if self.scroll_offset < albums.len() {
self.browse_detail = Some(albums[self.scroll_offset].0.clone());
self.scroll_offset = 0;
}
} else if self.library_category == 3 {
// Artists: select artist → show its tracks
let artists = self.unique_artists();
if self.scroll_offset < artists.len() {
self.browse_detail =
Some(artists[self.scroll_offset].0.clone());
self.scroll_offset = 0;
}
} else if self.library_category == 4 {
// Playlists: select playlist → show its tracks
if self.scroll_offset < self.playlist_cache.len() {
let playlist = self.playlist_cache[self.scroll_offset].clone();
self.browse_detail = Some(playlist.name.clone());
self.scroll_offset = 0;
self.playlist_tracks_cache.clear();
let c = self.client.clone();
let ipc_tx2 = self.ipc_tx.clone();
let pid = playlist.id;
tokio::spawn(async move {
if let Ok(DaemonRes::Tracks { tracks }) =
c.library_get_playlist_tracks(pid).await
{
let _ = ipc_tx2.send(IpcResult::PlaylistTracks(tracks));
}
});
}
} else if self.library_category == 5 {
// Spotify: select playlist → show its cached tracks
if self.scroll_offset < self.spotify_playlists.len() {
let playlist =
self.spotify_playlists[self.scroll_offset].clone();
self.browse_detail = Some(playlist.id.clone());
self.scroll_offset = 0;
self.spotify_playlist_tracks_cache.clear();
let c = self.client.clone();
let ipc_tx2 = self.ipc_tx.clone();
let pid = playlist.id;
tokio::spawn(async move {
match c.spotify_playlist_tracks(&pid).await {
Ok(tracks) => {
let _ =
ipc_tx2.send(IpcResult::SpotifyTracks(tracks));
}
Err(e) => {
let _ = ipc_tx2.send(IpcResult::Error(format!(
"Spotify playlist load failed: {e}"
)));
}
}
});
}
} else {
// Default: play track from flat list
self.play_filtered_highlighted();
}
} else if self.current_tab == Tab::Settings && !self.settings_pane_focus {
let tx = self.cmd_tx();
let opt = self.settings_option;
match self.settings_category {
0 => match opt {
0 => {
// Master Volume: cycle in 10% increments
let current = self.state.master_volume;
let new_vol = if current >= 100 {
50
} else {
(current + 10).min(100)
};
self.send_high(TuiCommand::SetMasterVolume(new_vol));
self.notify(
format!("Master Volume: {}%", new_vol),
NotificationKind::Info,
);
}
1 => {
// Mute toggle
let muted = !self.state.mute;
self.send_high(TuiCommand::SetVolume(if muted {
0
} else {
self.state.volume
}));
self.state.mute = muted;
}
_ => {}
},
1 => {
if opt == 1 {
// Cookie File: set directory
let c = self.client.clone();
let current = self.cookie_file.clone();
let new_path = if current.is_some() {
None
} else {
// Default to common cookie path
let home = std::env::var("HOME").unwrap_or_default();
Some(format!("{home}/.cookies/youtube.txt"))
};
let display = new_path
.clone()
.unwrap_or_else(|| "(none)".to_string());
self.cookie_file = new_path.clone();
let cf = new_path.clone();
tokio::spawn(async move {
let _ =
c.yt_set_config(None, cf, None, None, None).await;
});
self.notify(
format!("Cookie file: {display}"),
crate::app::NotificationKind::Info,
);
}
}
2 => match opt {
0 => {
// Repeat cycle
let next = match self.state.repeat {
gtm_core::state::RepeatMode::Off => {
gtm_core::state::RepeatMode::One
}
gtm_core::state::RepeatMode::One => {
gtm_core::state::RepeatMode::All
}
gtm_core::state::RepeatMode::All => {
gtm_core::state::RepeatMode::Off
}
};
let c = self.client.clone();
tokio::spawn(async move {
let _ = c.cycle_repeat(next).await;
});
self.state.repeat = next;
}
1 => {
// Shuffle toggle
let c = self.client.clone();
tokio::spawn(async move {
let _ = c.toggle_shuffle().await;
});
self.state.shuffle = !self.state.shuffle;
}
2 => {
// Crossfade toggle
let enabled = !self
.state
.crossfade
.as_ref()
.map(|c| c.enabled)
.unwrap_or(false);
let dur = self
.state
.crossfade
.as_ref()
.map(|c| c.duration_secs)
.unwrap_or(self.crossfade_duration);
let _ = tx.send(TuiCommand::Crossfade(enabled, dur)).await;
}
3 => {
// Easing cycle
let current = self
.state
.crossfade
.as_ref()
.map(|c| c.easing)
.unwrap_or(Easing::Linear);
let next = match current {
Easing::Linear => Easing::Smoothstep,
Easing::Smoothstep => Easing::Logarithmic,
Easing::Logarithmic => Easing::SlowFadeInFastFadeOut,
Easing::SlowFadeInFastFadeOut => {
Easing::FastFadeInSlowFadeOut
}
Easing::FastFadeInSlowFadeOut => Easing::EqualPower,
Easing::EqualPower => Easing::Exponential,
Easing::Exponential => Easing::Linear,
};
let _ = tx.send(TuiCommand::SetCrossfadeEasing(next)).await;
if let Some(ref mut cf) = self.state.crossfade {
cf.easing = next;
}
}
4 => {
// EQ Enabled toggle
let new_enabled = !self.state.eq_enabled;
self.state.eq_enabled = new_enabled;
let c = self.client.clone();
tokio::spawn(async move {
let _ = c.set_eq_enabled(new_enabled).await;
});
}
_ => {}
},
3 => match opt {
1 => {
// Transparent BG toggle
self.transparent_bg = !self.transparent_bg;
save_prefs(&self.current_prefs());
}
2 => {
// Sync Covers
spawn_sync_and_wait(
self.client.clone(),
gtm_core::ipc::SyncKind::Covers,
"Covers",
self.ipc_tx.clone(),
);
}
3 => {
// Sync Lyrics
spawn_sync_and_wait(
self.client.clone(),
gtm_core::ipc::SyncKind::Lyrics,
"Lyrics",
self.ipc_tx.clone(),
);
}
4 => {
// Sync Metadata
spawn_sync_and_wait(
self.client.clone(),
gtm_core::ipc::SyncKind::Metadata,
"Metadata",
self.ipc_tx.clone(),
);
}
5 => {
// Footer Preset cycle
self.cycle_footer_preset();
if let Some(p) = self.footer_presets.get(self.footer_preset)
{
self.notify(
format!("Footer: {}", p.name),
NotificationKind::Info,
);
}
}
6 => {
// Visualizer Preset cycle
self.visualizer.cycle_preset();
save_prefs(&self.current_prefs());
self.notify(
format!(
"Visualizer: {}",
self.visualizer.preset.name()
),
NotificationKind::Info,
);
}
_ => {}
},
4 => match opt {
3 => {
// Link Spotify account: open token input picker
self.spotify_token_input.clear();
self.pickers.open(PickerId::SpotifySearch);
}
4 => {
// Sync playlists now
let c = self.client.clone();
let ipc_tx = self.ipc_tx.clone();
tokio::spawn(async move {
match c.spotify_sync().await {
Ok(()) => {
let _ = ipc_tx.send(IpcResult::Notification(
"Spotify sync complete".to_string(),
NotificationKind::Success,
));
}
Err(e) => {
let _ = ipc_tx.send(IpcResult::Error(format!(
"Spotify sync failed: {e}"
)));
}
}
if let Ok(status) = c.spotify_status().await {
let _ =
ipc_tx.send(IpcResult::SpotifyStatus(status));
}
if let Ok(playlists) = c.spotify_playlists().await {
let _ = ipc_tx
.send(IpcResult::SpotifyPlaylists(playlists));
}
});
}
5 => {
// Unlink account
let c = self.client.clone();
let ipc_tx = self.ipc_tx.clone();
tokio::spawn(async move {
match c.spotify_clear().await {
Ok(status) => {
let _ = ipc_tx
.send(IpcResult::SpotifyStatus(status));
let _ = ipc_tx.send(IpcResult::Notification(
"Spotify account unlinked".to_string(),
NotificationKind::Info,
));
}
Err(e) => {
let _ = ipc_tx.send(IpcResult::Error(format!(
"Spotify unlink failed: {e}"
)));
}
}
});
}
_ => {}
},
5 if opt == 0 => {
// Design cycle
self.cycle_design();
}
_ => {}
}
}
}
Some(KeyboardAction::Delete) => {
if self.current_tab == Tab::Library && !self.library_pane_focus {
let track_data = self
.filtered_tracks()
.get(self.scroll_offset)
.map(|t| (t.id, t.title.clone()));
if let Some((track_id, track_name)) = track_data {
self.pending_delete = Some((track_id, track_name.clone()));
self.notify(
format!(
"Delete \"{track_name}\"? Enter to confirm, Esc to cancel"
),
NotificationKind::Info,
);
}
}
}
Some(KeyboardAction::ToggleMultiselect) => {
if self.current_tab == Tab::Library && !self.library_pane_focus {
self.multiselect_mode = !self.multiselect_mode;
if !self.multiselect_mode {
self.selected_indices.clear();
}
let msg = if self.multiselect_mode {
"Multiselect ON"
} else {
"Multiselect OFF"
};
self.notify(msg, NotificationKind::Info);
}
}
Some(KeyboardAction::AddToQueue) => {
if self.current_tab == Tab::Library && !self.library_pane_focus {
let tracks = self.filtered_tracks();
let indices: Vec<usize> =
if self.multiselect_mode && !self.selected_indices.is_empty() {
self.selected_indices.iter().copied().collect()
} else {
vec![self.scroll_offset]
};
let mut added = 0;
for idx in indices {
if let Some(track) = tracks.get(idx) {
let c = self.client.clone();
let path = track.path.clone();
tokio::spawn(async move {
let _ = c.queue_add(&path, None).await;
});
added += 1;
}
}
self.fetch_queue().await;
self.notify(
format!("Added {added} track(s) to queue"),
NotificationKind::Info,
);
}
}
Some(KeyboardAction::AddToPlaylist) => {
if self.current_tab == Tab::Library && !self.library_pane_focus {
let tracks = self.filtered_tracks();
let indices: Vec<i64> =
if self.multiselect_mode && !self.selected_indices.is_empty() {
self.selected_indices
.iter()
.filter_map(|i| tracks.get(*i).map(|t| t.id))
.collect()
} else {
tracks
.get(self.scroll_offset)
.map(|t| vec![t.id])
.unwrap_or_default()
};
if !indices.is_empty() {
self.pending_playlist_track_ids = indices;
self.pickers.open(PickerId::PlaylistSelect);
}
}
}
Some(KeyboardAction::DeleteFromList) => {
if self.current_tab == Tab::Library && !self.library_pane_focus {
if self.library_category == 4 && self.browse_detail.is_some() {
// In playlist view — remove selected track from playlist
let filtered = self.filtered_tracks();
if let Some(track) = filtered.get(self.scroll_offset) {
let track_id = track.id;
if let Some(pl) = self
.playlist_cache
.iter()
.find(|p| self.browse_detail.as_deref() == Some(&p.name))
{
let playlist_id = pl.id;
let tx = self.cmd_tx();
let _ = tx
.send(TuiCommand::RemoveFromPlaylist(
playlist_id,
track_id,
))
.await;
self.notify(
"Removed from playlist",
NotificationKind::Info,
);
}
}
} else {
self.notify(
"Remove from list only available in playlist view",
NotificationKind::Info,
);
}
}
}
Some(KeyboardAction::JumpToEnd) => {
if self.current_tab == Tab::Library && !self.library_pane_focus {
let max = self.library_list_len().saturating_sub(1);
self.scroll_offset = max;
}
}
Some(KeyboardAction::EditMetadata) => {
if self.current_tab == Tab::Library && !self.library_pane_focus {
let track_data = {
let tracks = self.filtered_tracks();
tracks.get(self.scroll_offset).map(|t| {
(
t.id,
t.title.clone(),
t.artist.clone(),
t.album.clone(),
t.genre.clone(),
t.year,
t.track_number,
)
})
};
if let Some((id, title, artist, album, genre, year, track_num)) =
track_data
{
self.metadata_edit_track_id = Some(id);
self.metadata_fields = [
title,
artist,
album,
String::new(),
genre,
year.map_or(String::new(), |y| y.to_string()),
track_num.map_or(String::new(), |n| n.to_string()),
];
self.metadata_field_idx = 0;
self.pickers.open(PickerId::EditMetadata);
self.fetch_metadata_cover();
}
}
}
None => {
match key.code {
KeyCode::Char('q') => {
if self.browse_detail.is_some() {
self.browse_detail = None;
self.scroll_offset = 0;
} else {
return false;
}
}
KeyCode::Esc => {
if self.browse_detail.is_some() {
self.browse_detail = None;
self.scroll_offset = 0;
}
}
KeyCode::Char('c') if self.current_tab == Tab::Settings => {
// Toggle crossfade in Settings tab
let enabled = !self
.state
.crossfade
.as_ref()
.map(|c| c.enabled)
.unwrap_or(false);
let dur = self
.state
.crossfade
.as_ref()
.map(|c| c.duration_secs)
.unwrap_or(self.crossfade_duration);
let tx = self.cmd_tx();
let _ = tx.send(TuiCommand::Crossfade(enabled, dur)).await;
}
KeyCode::Char('C') if self.current_tab == Tab::Settings => {
// Cycle crossfade duration (3, 5, 7, 10, 15, 30)
let dur = self
.state
.crossfade
.as_ref()
.map(|c| c.duration_secs)
.unwrap_or(self.crossfade_duration);
let new_dur = match dur {
0..=3 => 5,
4..=7 => 10,
8..=14 => 15,
15..=29 => 30,
_ => 3,
};
let enabled = self
.state
.crossfade
.as_ref()
.map(|c| c.enabled)
.unwrap_or(true);
let tx = self.cmd_tx();
let _ = tx.send(TuiCommand::Crossfade(enabled, new_dur)).await;
}
KeyCode::Char('S') => {
// Sync covers for tracks missing cover art
self.notify("Syncing covers...", NotificationKind::Info);
spawn_sync_and_wait(
self.client.clone(),
gtm_core::ipc::SyncKind::Covers,
"Covers",
self.ipc_tx.clone(),
);
}
_ => {}
}
}
}
}
}
true
}
async fn handle_picker_key(&mut self, key: event::KeyEvent) {
let tx = self.cmd_tx();
if matches!(self.pickers.top().map(|o| o.id), Some(PickerId::SleepTimer)) {
if self.sleep_timer_input_mode {
match key.code {
KeyCode::Esc => {
self.sleep_timer_input_mode = false;
self.sleep_timer_input_buf.clear();
}
KeyCode::Enter => {
if let Ok(m) = self.sleep_timer_input_buf.parse::<u32>() {
self.sleep_timer_minutes = m.min(180);
}
self.sleep_timer_input_mode = false;
self.sleep_timer_input_buf.clear();
}
KeyCode::Backspace => {
self.sleep_timer_input_buf.pop();
}
KeyCode::Char(c) if c.is_ascii_digit() => {
self.sleep_timer_input_buf.push(c);
}
_ => {}
}
return;
}
match key.code {
KeyCode::Esc => {
self.sleep_timer_remaining = None;
self.sleep_timer_minutes = 30;
self.sleep_timer_input_mode = false;
self.sleep_timer_input_buf.clear();
self.pickers.close_top();
return;
}
KeyCode::Char('h') | KeyCode::Left => {
self.sleep_timer_minutes = self.sleep_timer_minutes.saturating_sub(5);
return;
}
KeyCode::Char('l') | KeyCode::Right => {
self.sleep_timer_minutes = (self.sleep_timer_minutes + 5).min(180);
return;
}
KeyCode::Char('-') => {
self.sleep_timer_minutes = self.sleep_timer_minutes.saturating_sub(1);
return;
}
KeyCode::Char('+') | KeyCode::Char('=') => {
self.sleep_timer_minutes = (self.sleep_timer_minutes + 1).min(180);
return;
}
KeyCode::Enter => {
let mins = self.sleep_timer_minutes;
self.sleep_timer_remaining = Some(mins as u64);
self.send_high(TuiCommand::SetSleepTimer(mins));
self.notify(
format!("Sleep timer set: {} min", mins),
NotificationKind::Info,
);
self.pickers.close_top();
return;
}
KeyCode::Char('i') => {
self.sleep_timer_input_mode = true;
self.sleep_timer_input_buf.clear();
return;
}
KeyCode::Char('c') => {
self.sleep_timer_remaining = None;
self.send_high(TuiCommand::CancelSleepTimer);
self.notify("Sleep timer cancelled", NotificationKind::Info);
return;
}
KeyCode::Up | KeyCode::Char('j') => {
let quick_opts = [5u32, 10, 15, 30, 60, 90, 120];
if let Some(top) = self.pickers.top_mut() {
top.selected = (top.selected + 1) % quick_opts.len();
self.sleep_timer_minutes = quick_opts[top.selected];
}
return;
}
KeyCode::Down | KeyCode::Char('k') => {
let quick_opts = [5u32, 10, 15, 30, 60, 90, 120];
if let Some(top) = self.pickers.top_mut() {
top.selected = if top.selected == 0 {
quick_opts.len() - 1
} else {
top.selected - 1
};
self.sleep_timer_minutes = quick_opts[top.selected];
}
return;
}
_ => {}
}
return;
}
let top_id = self.pickers.top().map(|o| o.id);
let is_help = top_id == Some(PickerId::Help);
let ctrl_or_alt = key
.modifiers
.intersects(KeyModifiers::CONTROL | KeyModifiers::ALT);
match key.code {
KeyCode::Esc => {
if let Some(top) = self.pickers.top() {
match top.id {
PickerId::SleepTimer => self.sleep_timer_remaining = None,
PickerId::SpotifySearch => self.spotify_token_input.clear(),
PickerId::EditMetadata => {
self.metadata_cover = None;
self.metadata_cover_stateful = None;
self.metadata_edit_track_id = None;
}
_ => {}
}
}
self.pickers.close_top();
}
// Help picker vim motions
KeyCode::Char('g') if key.modifiers == KeyModifiers::CONTROL && is_help => {
if let Some(top) = self.pickers.top_mut() {
top.selected = 0;
}
}
KeyCode::Char('G') if is_help && !ctrl_or_alt => {
let total = self.help_picker_total();
if let Some(top) = self.pickers.top_mut() {
top.selected = total.saturating_sub(1);
}
}
KeyCode::Char('0') if is_help && !ctrl_or_alt => {
if let Some(top) = self.pickers.top_mut() {
top.selected = 0;
}
}
KeyCode::Char('$') if is_help && !ctrl_or_alt => {
let total = self.help_picker_total();
if let Some(top) = self.pickers.top_mut() {
top.selected = total.saturating_sub(1);
}
}
KeyCode::Char('/') if is_help && !ctrl_or_alt => {
if let Some(top) = self.pickers.top_mut() {
top.query.clear();
}
}
KeyCode::Char('n') if is_help && !ctrl_or_alt => {
let total = self.help_picker_total();
if let Some(top) = self.pickers.top_mut() {
if total > 0 {
top.selected = (top.selected + 1).min(total - 1);
}
}
}
KeyCode::Char('N') if is_help && !ctrl_or_alt => {
if let Some(top) = self.pickers.top_mut() {
top.selected = top.selected.saturating_sub(1);
}
}
// Queue move up/down (Ctrl+K/J) must come before plain k/j
KeyCode::Char('k') if key.modifiers == KeyModifiers::CONTROL => {
if let Some(top) = self.pickers.top() {
if top.id == PickerId::Queue && !self.queue_cache.is_empty() {
let idx = top.selected.min(self.queue_cache.len() - 1);
if idx > 0 {
let _ = tx
.send(TuiCommand::QueueMove(
idx as u64,
idx.saturating_sub(1) as u64,
))
.await;
self.fetch_queue().await;
}
}
}
}
KeyCode::Char('j') if key.modifiers == KeyModifiers::CONTROL => {
if let Some(top) = self.pickers.top() {
if top.id == PickerId::Queue && !self.queue_cache.is_empty() {
let idx = top.selected.min(self.queue_cache.len() - 1);
if idx < self.queue_cache.len() - 1 {
let _ = tx
.send(TuiCommand::QueueMove(idx as u64, (idx + 1) as u64))
.await;
self.fetch_queue().await;
}
}
}
}
KeyCode::Up | KeyCode::Char('k') => {
let has_input = matches!(
self.pickers.top().map(|o| o.id),
Some(PickerId::YTSearch)
| Some(PickerId::SearchLibrary)
| Some(PickerId::CommandPalette)
| Some(PickerId::ThemePicker)
);
let is_metadata = matches!(
self.pickers.top().map(|o| o.id),
Some(PickerId::EditMetadata)
);
if is_metadata {
if self.metadata_field_idx > 0 {
self.metadata_field_idx -= 1;
}
return;
}
if has_input && key.code != KeyCode::Up {
// Add 'k' to the query instead of navigating
if let Some(top) = self.pickers.top_mut() {
top.query.push('k');
}
return;
}
if let Some(top) = self.pickers.top_mut() {
top.selected = top.selected.saturating_sub(1);
let is_theme = top.id == PickerId::ThemePicker;
let selected = top.selected;
if is_theme {
self.apply_theme_index(selected);
}
}
self.clamp_picker_selection();
self.apply_eq_on_navigation().await;
}
KeyCode::Down | KeyCode::Char('j') => {
let has_input = matches!(
self.pickers.top().map(|o| o.id),
Some(PickerId::YTSearch)
| Some(PickerId::SearchLibrary)
| Some(PickerId::CommandPalette)
| Some(PickerId::ThemePicker)
);
let is_metadata = matches!(
self.pickers.top().map(|o| o.id),
Some(PickerId::EditMetadata)
);
if is_metadata {
if self.metadata_field_idx < 6 {
self.metadata_field_idx += 1;
}
return;
}
if has_input && key.code != KeyCode::Down {
// Add 'j' to the query instead of navigating
if let Some(top) = self.pickers.top_mut() {
top.query.push('j');
}
return;
}
if let Some(top) = self.pickers.top_mut() {
top.selected += 1;
let is_theme = top.id == PickerId::ThemePicker;
let selected = top.selected;
if is_theme {
self.apply_theme_index(selected);
}
}
self.clamp_picker_selection();
self.apply_eq_on_navigation().await;
}
KeyCode::Enter if key.modifiers.contains(KeyModifiers::CONTROL) => {
if matches!(
self.pickers.top().map(|o| o.id),
Some(PickerId::EditMetadata)
) {
if let Some(track_id) = self.metadata_edit_track_id {
let title = self.metadata_fields[0].clone();
let artist = self.metadata_fields[1].clone();
let album = self.metadata_fields[2].clone();
let genre = self.metadata_fields[4].clone();
let year = self.metadata_fields[5].parse::<i32>().ok();
let track_number = self.metadata_fields[6].parse::<i32>().ok();
let client = self.client.clone();
let ipc_tx = self.ipc_tx.clone();
tokio::spawn(async move {
let patch = gtm_core::MetadataPatch {
title: Some(title),
artist: Some(artist),
album: Some(album),
genre: Some(genre),
year,
track_number,
};
let _ = client.library_update_metadata(track_id, patch).await;
let _ = ipc_tx.send(IpcResult::Notification(
"Metadata saved".to_string(),
NotificationKind::Success,
));
});
self.metadata_cover = None;
self.metadata_cover_stateful = None;
self.metadata_edit_track_id = None;
}
self.pickers.close_top();
}
}
KeyCode::Enter => {
// Dispatch based on picker type
if let Some(top) = self.pickers.top() {
match top.id {
PickerId::SpotifySearch => {
let token = self.spotify_token_input.clone();
if token.trim().is_empty() {
self.notify(
"Enter a Spotify access token to link your account",
NotificationKind::Info,
);
} else {
let c = self.client.clone();
let ipc_tx = self.ipc_tx.clone();
tokio::spawn(async move {
match c.spotify_set_token(&token).await {
Ok(status) => {
let _ = ipc_tx.send(IpcResult::SpotifyStatus(status));
let _ = ipc_tx.send(IpcResult::Notification(
"Spotify account linked".to_string(),
NotificationKind::Success,
));
}
Err(e) => {
let _ = ipc_tx.send(IpcResult::Error(format!(
"Spotify link failed: {e}"
)));
}
}
});
self.spotify_token_input.clear();
self.pickers.close_top();
}
}
PickerId::Queue => {
if !self.queue_cache.is_empty() {
let idx = top.selected.min(self.queue_cache.len() - 1);
let path = self.queue_cache[idx].path.clone();
self.send_high(TuiCommand::Play(path));
}
}
PickerId::YTSearch => {
if top.query.is_empty() {
// Start search
} else if !self.yt_results_cache.is_empty() {
let idx = top.selected.min(self.yt_results_cache.len() - 1);
if self.yt_results_cache[idx].is_playlist {
// Playlist drill-down: search using the playlist URL
let url = self.yt_results_cache[idx].url.clone();
if let Some(top) = self.pickers.top_mut() {
top.query = url;
}
let query = self.yt_results_cache[idx].url.clone();
let _ = tx.send(TuiCommand::YtSearch(query)).await;
} else {
let url = self.yt_results_cache[idx].url.clone();
let _ = tx.send(TuiCommand::YtResolve(url)).await;
}
} else {
// Initiate a new search
let query = top.query.clone();
let _ = tx.send(TuiCommand::YtSearch(query)).await;
let _ = tx.send(TuiCommand::RefreshYt).await;
}
}
PickerId::SleepTimer => {
// Handled by early return above
}
PickerId::CommandPalette => {
let commands = crate::ui::COMMAND_PALETTE_COMMANDS;
let query = top.query.to_lowercase();
let filtered: Vec<&(&str, &str)> = if query.is_empty() {
commands.iter().collect()
} else {
commands
.iter()
.filter(|c| {
let lower = c.0.to_lowercase();
let mut qi = 0usize;
for ch in lower.chars() {
if qi < query.len()
&& ch == query.as_bytes()[qi] as char
{
qi += 1;
}
}
qi == query.len()
})
.collect()
};
let idx = top.selected.min(filtered.len().saturating_sub(1));
if let Some(cmd) = filtered.get(idx) {
let raw = cmd.0.to_lowercase();
// Strip leading icon (skip to first ASCII letter)
let label = raw
.chars()
.skip_while(|c| !c.is_ascii_alphabetic())
.collect::<String>();
if label.starts_with("play/pause") {
self.send_high(TuiCommand::PlayPause);
} else if label.starts_with("next track") {
self.send_high(TuiCommand::Next);
} else if label.starts_with("prev track") {
self.send_high(TuiCommand::Prev);
} else if label.starts_with("volume up") {
let new_vol = (self.state.volume + 5).min(100);
self.send_high(TuiCommand::SetVolume(new_vol));
} else if label.starts_with("volume down") {
let new_vol = self.state.volume.saturating_sub(5);
self.send_high(TuiCommand::SetVolume(new_vol));
} else if label.starts_with("mute") {
self.send_high(TuiCommand::ToggleMute);
} else if label.starts_with("repeat") {
let new_mode = match self.state.repeat {
RepeatMode::Off => RepeatMode::One,
RepeatMode::One => RepeatMode::All,
RepeatMode::All => RepeatMode::Off,
};
self.send_high(TuiCommand::CycleRepeat(new_mode));
} else if label.starts_with("shuffle") {
self.send_high(TuiCommand::ToggleShuffle);
} else if label.starts_with("quit daemon") {
let c = self.client.clone();
let _ =
tokio::time::timeout(Duration::from_millis(1500), c.quit())
.await;
self.pending_quit = true;
} else if label.starts_with("quit") {
self.pending_quit = true;
} else if label.starts_with("tab cycle") {
self.current_tab = match self.current_tab {
Tab::Library => Tab::Settings,
Tab::Settings => Tab::Library,
};
} else if label.starts_with("library") {
self.current_tab = Tab::Library;
} else if label.starts_with("settings") {
self.current_tab = Tab::Settings;
} else if label.starts_with("queue") {
self.pickers.open(PickerId::Queue);
} else if label.starts_with("youtube") {
self.pickers.open(PickerId::YTSearch);
} else if label.starts_with("search lib") {
self.pickers.open(PickerId::SearchLibrary);
} else if label.starts_with("eq") {
self.pickers.open(PickerId::Equalizer);
} else if label.starts_with("sleeptimer") {
self.pickers.open(PickerId::SleepTimer);
} else if label.starts_with("themepicker") {
self.pickers.open_with_selection(
PickerId::ThemePicker,
self.theme_index,
);
} else if label.starts_with("sound fx") {
self.pickers.open(PickerId::SoundEffects);
} else if label.starts_with("about") {
self.pickers.open(PickerId::About);
} else if label.starts_with("search") {
self.pickers.open(PickerId::SearchLibrary);
} else if label.starts_with("spotify") {
self.pickers.open(PickerId::SpotifySearch);
} else if label.starts_with("fetch lyrics") {
self.show_lyrics = true;
self.send_high(TuiCommand::FetchLyrics);
} else if label.starts_with("progress style") {
self.progress_style = self.progress_style.next();
self.notify(
format!("Progress: {}", self.progress_style.name()),
crate::app::NotificationKind::Info,
);
} else if label.starts_with("visualizer preset") {
self.visualizer.cycle_preset();
save_prefs(&self.current_prefs());
self.notify(
format!("Visualizer: {}", self.visualizer.preset.name()),
crate::app::NotificationKind::Info,
);
} else if label.starts_with("visualizer") {
self.visualizer.toggle();
let state = if self.visualizer.is_enabled() {
"ON"
} else {
"OFF"
};
self.notify(
format!("Visualizer: {}", state),
crate::app::NotificationKind::Info,
);
} else if label.starts_with("stop") {
self.send_high(TuiCommand::Stop);
} else if label.starts_with("seek forward") {
let pos =
(self.display_position + 5.0).min(self.state.duration);
self.send_high(TuiCommand::Seek(pos));
} else if label.starts_with("seek backward") {
let pos = (self.display_position - 5.0).max(0.0);
self.send_high(TuiCommand::Seek(pos));
} else if label.starts_with("toggle favourite") {
if let Some(ref track) = self.state.current_track {
let track_id = track.id;
let new_fav = !track.favourite;
if let Some(ref mut ct) = self.state.current_track {
ct.favourite = new_fav;
}
for t in &mut self.tracks_cache {
if t.id == track_id {
t.favourite = new_fav;
break;
}
}
let tx = self.cmd_tx();
let _ = tx.send(TuiCommand::AddFavourite(track_id)).await;
self.notify("Favourite toggled", NotificationKind::Info);
}
} else if label.starts_with("clear queue") {
let tx = self.cmd_tx();
let _ = tx.send(TuiCommand::QueueClear).await;
self.notify("Queue cleared", NotificationKind::Info);
} else if label.starts_with("prev tab") {
self.current_tab = match self.current_tab {
Tab::Library => Tab::Settings,
Tab::Settings => Tab::Library,
};
} else if label.starts_with("multiselect") {
if self.current_tab == Tab::Library && !self.library_pane_focus
{
self.multiselect_mode = !self.multiselect_mode;
if !self.multiselect_mode {
self.selected_indices.clear();
}
let msg = if self.multiselect_mode {
"Multiselect ON — use v/a/x to queue"
} else {
"Multiselect OFF"
};
self.notify(msg, NotificationKind::Info);
}
} else if label.starts_with("add to queue") {
if self.current_tab == Tab::Library && !self.library_pane_focus
{
let tracks = self.filtered_tracks();
let indices: Vec<usize> = if self.multiselect_mode
&& !self.selected_indices.is_empty()
{
self.selected_indices.iter().copied().collect()
} else {
vec![self.scroll_offset]
};
let mut added = 0;
for idx in indices {
if let Some(track) = tracks.get(idx) {
let c = self.client.clone();
let path = track.path.clone();
tokio::spawn(async move {
let _ = c.queue_add(&path, None).await;
});
added += 1;
}
}
self.fetch_queue().await;
self.notify(
format!("Added {added} track(s) to queue"),
NotificationKind::Info,
);
}
} else if label.starts_with("add to playlist") {
if self.current_tab == Tab::Library && !self.library_pane_focus
{
let tracks = self.filtered_tracks();
let indices: Vec<i64> = if self.multiselect_mode
&& !self.selected_indices.is_empty()
{
self.selected_indices
.iter()
.filter_map(|i| tracks.get(*i).map(|t| t.id))
.collect()
} else {
tracks
.get(self.scroll_offset)
.map(|t| vec![t.id])
.unwrap_or_default()
};
if !indices.is_empty() {
self.pending_playlist_track_ids = indices;
self.pickers.open(PickerId::PlaylistSelect);
}
}
} else if label.starts_with("delete from list") {
if self.current_tab == Tab::Library && !self.library_pane_focus
{
if self.library_category == 4
&& self.browse_detail.is_some()
{
let filtered = self.filtered_tracks();
if let Some(track) = filtered.get(self.scroll_offset) {
let track_id = track.id;
if let Some(pl) =
self.playlist_cache.iter().find(|p| {
self.browse_detail.as_deref()
== Some(&p.name)
})
{
let playlist_id = pl.id;
let tx = self.cmd_tx();
let _ = tx
.send(TuiCommand::RemoveFromPlaylist(
playlist_id,
track_id,
))
.await;
self.notify(
"Removed from playlist",
NotificationKind::Info,
);
}
}
} else {
self.notify(
"Remove from list only available in playlist view",
NotificationKind::Info,
);
}
}
} else if label.starts_with("jump to end") {
if self.current_tab == Tab::Library && !self.library_pane_focus
{
let max = self.library_list_len().saturating_sub(1);
self.scroll_offset = max;
}
} else if label.starts_with("edit metadata") {
if self.current_tab == Tab::Library && !self.library_pane_focus
{
let track_data = {
let tracks = self.filtered_tracks();
tracks.get(self.scroll_offset).map(|t| {
(
t.id,
t.title.clone(),
t.artist.clone(),
t.album.clone(),
t.genre.clone(),
t.year,
t.track_number,
)
})
};
if let Some((
id,
title,
artist,
album,
genre,
year,
track_num,
)) = track_data
{
self.metadata_edit_track_id = Some(id);
self.metadata_fields = [
title,
artist,
album,
String::new(),
genre,
year.map_or(String::new(), |y| y.to_string()),
track_num.map_or(String::new(), |n| n.to_string()),
];
self.metadata_field_idx = 0;
self.pickers.open(PickerId::EditMetadata);
self.fetch_metadata_cover();
}
}
} else if label.starts_with("toggle help") {
if self.pickers.top().is_some_and(|o| o.id == PickerId::Help) {
self.pickers.close_top();
} else {
self.pickers.open(PickerId::Help);
}
} else if label.starts_with("hide help bar") {
self.hide_help_bar = !self.hide_help_bar;
} else if label.starts_with("footer preset") {
self.cycle_footer_preset();
} else if label.starts_with("cycle design") {
self.cycle_design();
} else if label.starts_with("health check") {
self.send_high(TuiCommand::CheckHealth);
}
}
self.pickers.close_top();
}
PickerId::Equalizer => {
// Apply selected EQ preset
let presets = [
gtm_core::state::EqPreset::Flat,
gtm_core::state::EqPreset::Normal,
gtm_core::state::EqPreset::Pop,
gtm_core::state::EqPreset::Rock,
gtm_core::state::EqPreset::Jazz,
gtm_core::state::EqPreset::Classical,
gtm_core::state::EqPreset::Bass,
gtm_core::state::EqPreset::Vocal,
gtm_core::state::EqPreset::Electronic,
gtm_core::state::EqPreset::HipHop,
gtm_core::state::EqPreset::Latin,
gtm_core::state::EqPreset::Acoustic,
gtm_core::state::EqPreset::Podcast,
gtm_core::state::EqPreset::Dance,
gtm_core::state::EqPreset::Headphones,
gtm_core::state::EqPreset::Speaker,
];
let idx = top.selected.min(presets.len() - 1);
let c = self.client.clone();
tokio::spawn(async move {
let _ = c.set_eq_preset(presets[idx]).await;
});
self.pickers.close_top();
}
PickerId::ThemePicker => {
let idx = top.selected;
self.apply_theme_index(idx);
self.pickers.close_top();
}
PickerId::SearchLibrary => {
let q = top.query.to_lowercase();
let filtered: Vec<>m_core::track::TrackInfo> = if q.is_empty() {
self.tracks_cache.iter().collect()
} else {
self.tracks_cache
.iter()
.filter(|t| {
t.title.to_lowercase().contains(&q)
|| t.artist.to_lowercase().contains(&q)
})
.collect()
};
if !filtered.is_empty() {
let idx = top.selected.min(filtered.len() - 1);
let path = filtered[idx].path.clone();
self.send_high(TuiCommand::Play(path));
}
self.pickers.close_top();
}
PickerId::SoundEffects => {
let sel = top.selected;
match sel {
1 => {
// Reverb toggle
let new_enabled = !self.state.reverb.enabled;
let room_size = self.state.reverb.room_size;
self.state.reverb.enabled = new_enabled;
let c = self.client.clone();
tokio::spawn(async move {
let _ = c.set_reverb(new_enabled, room_size).await;
});
self.pickers.close_top();
}
_ => {
self.pickers.close_top();
}
}
}
PickerId::EditMetadata => {
if self.metadata_field_idx < 6 {
self.metadata_field_idx += 1;
} else {
if let Some(track_id) = self.metadata_edit_track_id {
let title = self.metadata_fields[0].clone();
let artist = self.metadata_fields[1].clone();
let album = self.metadata_fields[2].clone();
let genre = self.metadata_fields[4].clone();
let year = self.metadata_fields[5].parse::<i32>().ok();
let track_number = self.metadata_fields[6].parse::<i32>().ok();
let client = self.client.clone();
let ipc_tx = self.ipc_tx.clone();
tokio::spawn(async move {
let patch = gtm_core::MetadataPatch {
title: Some(title),
artist: Some(artist),
album: Some(album),
genre: Some(genre),
year,
track_number,
};
let _ =
client.library_update_metadata(track_id, patch).await;
let _ = ipc_tx.send(IpcResult::Notification(
"Metadata saved".to_string(),
NotificationKind::Success,
));
});
self.metadata_cover = None;
self.metadata_cover_stateful = None;
self.metadata_edit_track_id = None;
}
self.pickers.close_top();
}
}
_ => {}
}
}
}
KeyCode::Char('d') if key.modifiers == KeyModifiers::CONTROL => {
// YT search: download selected result
let idx = self.pickers.top().map_or(0, |o| {
o.selected
.min(self.yt_results_cache.len().saturating_sub(1))
});
if !self.yt_results_cache.is_empty() {
let url = self.yt_results_cache[idx].url.clone();
let _ = tx.send(TuiCommand::YtDownload(url)).await;
}
}
KeyCode::Char('a') if key.modifiers == KeyModifiers::CONTROL => {
// YT search: add selected result to queue
let idx = self.pickers.top().map_or(0, |o| {
o.selected
.min(self.yt_results_cache.len().saturating_sub(1))
});
if !self.yt_results_cache.is_empty() {
let url = self.yt_results_cache[idx].url.clone();
if self.yt_results_cache[idx].is_playlist {
let _ = tx.send(TuiCommand::YtResolve(url)).await;
} else {
let _ = tx.send(TuiCommand::QueueAdd(url)).await;
}
}
}
KeyCode::Char('s') if key.modifiers == KeyModifiers::CONTROL => {
// Edit Metadata: sync cover using the currently-entered metadata.
if top_id == Some(PickerId::EditMetadata) {
if let Some(track_id) = self.metadata_edit_track_id {
let title = self.metadata_fields[0].clone();
let artist = self.metadata_fields[1].clone();
let album = self.metadata_fields[2].clone();
let genre = self.metadata_fields[4].clone();
let year = self.metadata_fields[5].parse::<i32>().ok();
let track_number = self.metadata_fields[6].parse::<i32>().ok();
let client = self.client.clone();
let ipc_tx = self.ipc_tx.clone();
tokio::spawn(async move {
let patch = gtm_core::MetadataPatch {
title: Some(title),
artist: Some(artist),
album: Some(album),
genre: Some(genre),
year,
track_number,
};
// Persist edited metadata first so the cover lookup
// uses the updated artist/album/title.
let _ = client.library_update_metadata(track_id, patch).await;
if let Ok(Some(b64)) = client.get_cover_art(track_id).await {
if let Ok(bytes) =
base64::engine::general_purpose::STANDARD.decode(&b64)
{
let _ = ipc_tx
.send(IpcResult::MetadataCoverArt(Some(bytes), track_id));
}
}
});
self.metadata_cover_dirty = true;
self.notify("Syncing cover…", NotificationKind::Info);
}
}
}
KeyCode::Char(c) if !ctrl_or_alt => {
if let Some(top) = self.pickers.top_mut() {
match top.id {
PickerId::YTSearch
| PickerId::SearchLibrary
| PickerId::CommandPalette
| PickerId::ThemePicker
| PickerId::Help => {
top.query.push(c);
if top.id == PickerId::YTSearch {
// Invalidate stale results immediately so the
// picker never shows results from an older query.
self.yt_results_cache.clear();
self.yt_search_loading = false;
self.yt_search_debounce =
Some(std::time::Instant::now() + Duration::from_millis(500));
}
}
PickerId::EditMetadata => {
self.metadata_fields[self.metadata_field_idx].push(c);
}
PickerId::SpotifySearch => {
self.spotify_token_input.push(c);
}
_ => {}
}
}
}
KeyCode::Tab => {
if let Some(top) = self.pickers.top() {
if top.id == PickerId::EditMetadata {
self.metadata_field_idx = (self.metadata_field_idx + 1) % 7;
}
}
}
KeyCode::Backspace => {
if let Some(top) = self.pickers.top_mut() {
match top.id {
PickerId::EditMetadata => {
self.metadata_fields[self.metadata_field_idx].pop();
}
PickerId::SpotifySearch => {
self.spotify_token_input.pop();
}
_ => {
top.query.pop();
if top.id == PickerId::YTSearch {
self.yt_results_cache.clear();
self.yt_search_loading = false;
self.yt_search_debounce =
Some(std::time::Instant::now() + Duration::from_millis(500));
}
}
}
}
}
_ => {}
}
}
async fn apply_eq_on_navigation(&mut self) {
if let Some(top) = self.pickers.top() {
if top.id == PickerId::Equalizer {
let presets = [
gtm_core::state::EqPreset::Flat,
gtm_core::state::EqPreset::Normal,
gtm_core::state::EqPreset::Pop,
gtm_core::state::EqPreset::Rock,
gtm_core::state::EqPreset::Jazz,
gtm_core::state::EqPreset::Classical,
gtm_core::state::EqPreset::Bass,
gtm_core::state::EqPreset::Vocal,
gtm_core::state::EqPreset::Electronic,
gtm_core::state::EqPreset::HipHop,
gtm_core::state::EqPreset::Latin,
gtm_core::state::EqPreset::Acoustic,
gtm_core::state::EqPreset::Podcast,
gtm_core::state::EqPreset::Dance,
gtm_core::state::EqPreset::Headphones,
gtm_core::state::EqPreset::Speaker,
];
let idx = top.selected.min(presets.len() - 1);
self.send_high(TuiCommand::SetEqPreset(presets[idx]));
self.state.eq_preset = presets[idx];
}
}
}
/// Interleave YT search results: insert one playlist entry after every 3 track entries.
fn interleave_yt_results(
mut results: Vec<gtm_core::track::YTSearchResult>,
) -> Vec<gtm_core::track::YTSearchResult> {
let tracks: Vec<_> = results.drain(..).filter(|r| !r.is_playlist).collect();
let playlists: Vec<_> = results; // remaining are playlists
let mut out = Vec::with_capacity(tracks.len() + playlists.len());
let mut pl_idx = 0;
for (i, track) in tracks.into_iter().enumerate() {
out.push(track);
if (i + 1) % 3 == 0 && pl_idx < playlists.len() {
out.push(playlists[pl_idx].clone());
pl_idx += 1;
}
}
// Append remaining playlists
while pl_idx < playlists.len() {
out.push(playlists[pl_idx].clone());
pl_idx += 1;
}
out
}
}
/// Index of the active time-synced lyric line for a playback position.
/// Untimed lines (timestamp < 0) are skipped for matching but keep their
/// index so the highlight tracks timed lines correctly.
fn lyric_index_at(lines: &[gtm_core::track::LrcLine], position: f64) -> usize {
if lines.is_empty() {
return 0;
}
let mut current_idx = 0;
for (i, line) in lines.iter().enumerate() {
if line.timestamp < 0.0 {
continue;
}
if line.timestamp <= position {
current_idx = i;
} else {
break;
}
}
current_idx
}
/// Pure focus-state transition for Tab/Shift-Tab pane cycling on the Library
/// tab with lyrics open. States are `(library_focus, lyrics_focus)`:
/// left `(true, false)`, right `(false, false)`, lyrics `(false, true)`.
/// Returns the next `(library_focus, lyrics_focus)` moving forward (Tab) or
/// backward (Shift-Tab) around the three-pane cycle.
fn cycle_library_focus(library_focus: bool, lyrics_focus: bool, forward: bool) -> (bool, bool) {
if lyrics_focus {
// lyrics → left (Tab) or right (Shift-Tab)
(forward, false)
} else if library_focus {
// left → right (Tab) or lyrics (Shift-Tab)
if forward {
(false, false)
} else {
(false, true)
}
} else if forward {
// right → lyrics
(false, true)
} else {
// right → left
(true, false)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn lyric_index_tracks_position_through_timed_lines() {
let lines = vec![
gtm_core::track::LrcLine {
timestamp: -1.0,
text: "intro (untimed)".into(),
},
gtm_core::track::LrcLine {
timestamp: 0.0,
text: "first".into(),
},
gtm_core::track::LrcLine {
timestamp: 5.0,
text: "second".into(),
},
gtm_core::track::LrcLine {
timestamp: 10.0,
text: "third".into(),
},
];
assert_eq!(lyric_index_at(&lines, -1.0), 0);
assert_eq!(lyric_index_at(&lines, 0.0), 1);
assert_eq!(lyric_index_at(&lines, 4.9), 1);
assert_eq!(lyric_index_at(&lines, 5.0), 2);
assert_eq!(lyric_index_at(&lines, 999.0), 3);
}
#[test]
fn lyric_index_empty_returns_zero() {
assert_eq!(lyric_index_at(&[], 42.0), 0);
}
#[test]
fn cycle_library_focus_advances_forward() {
let (lib, lyr) = cycle_library_focus(true, false, true);
assert_eq!((lib, lyr), (false, false));
let (lib, lyr) = cycle_library_focus(false, false, true);
assert_eq!((lib, lyr), (false, true));
let (lib, lyr) = cycle_library_focus(false, true, true);
assert_eq!((lib, lyr), (true, false));
}
#[test]
fn cycle_library_focus_advances_backward() {
let (lib, lyr) = cycle_library_focus(true, false, false);
assert_eq!((lib, lyr), (false, true));
let (lib, lyr) = cycle_library_focus(false, false, false);
assert_eq!((lib, lyr), (true, false));
let (lib, lyr) = cycle_library_focus(false, true, false);
assert_eq!((lib, lyr), (false, false));
}
}