« get me outta code hell

ui.js - mtui - Music Text User Interface - user-friendly command line music player
about summary refs log tree commit diff
path: root/ui.js
blob: 81108aaa0effbd4836d9235c5ffe0cc4e1c818d9 (plain)
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
// The UI in MTUI! Interfaces with the backend to form the complete mtui app.

'use strict'

const { getAllCrawlersForArg } = require('./crawlers')
const processSmartPlaylist = require('./smart-playlist')
const UndoManager = require('./undo-manager')

const {
  shuffleArray,
  getTimeStringsFromSec
} = require('./general-util')

const {
  cloneGrouplike,
  countTotalTracks,
  flattenGrouplike,
  getCorrespondingFileForItem,
  getCorrespondingPlayableForFile,
  getItemPath,
  getNameWithoutTrackNumber,
  isGroup,
  isOpenable,
  isPlayable,
  isTrack,
  parentSymbol,
  reverseOrderOfGroups,
  searchForItem,
  shuffleOrderOfGroups
} = require('./playlist-utils')

const {
  ui: {
    Dialog,
    DisplayElement,
    Label,
    Pane,
    WrapLabel,
    form: {
      Button,
      FocusElement,
      Form,
      ListScrollForm,
      TextInput,
    }
  },
  util: {
    ansi,
    telchars: telc,
    unichars: unic,
  }
} = require('tui-lib')

const TuiTextEditor = require('tui-text-editor')

const { promisify } = require('util')
const fs = require('fs')
const open = require('open')
const path = require('path')
const url = require('url')
const readFile = promisify(fs.readFile)
const writeFile = promisify(fs.writeFile)

const input = {}

const keyBindings = [
  ['isUp', telc.isUp],
  ['isDown', telc.isDown],
  ['isLeft', telc.isLeft],
  ['isRight', telc.isRight],
  ['isSelect', telc.isSelect],
  ['isBackspace', telc.isBackspace],
  ['isMenu', 'm'],
  ['isMenu', 'f'],
  ['isScrollToStart', 'g', {caseless: false}],
  ['isScrollToEnd', 'G', {caseless: false}],
  ['isScrollToStart', telc.isHome],
  ['isScrollToEnd', telc.isEnd],
  ['isTogglePause', telc.isSpace],
  ['isToggleLoop', 'l', {caseless: false}],
  ['isStop', telc.isEscape],
  ['isVolumeUp', 'v', {caseless: false}],
  ['isVolumeDown', 'V', {caseless: false}],
  ['isSkipBack', telc.isControlUp],
  ['isSkipAhead', telc.isControlDown],
  ['isSkipBack', 'p'],
  ['isSkipAhead', 'n'],
  ['isFocusTabber', '['],
  ['isFocusQueue', ']'],
  ['isFocusPlaybackInfo', '|'],
  ['isNextTab', 't', {caseless: false}],
  ['isPreviousTab', 'T', {caseless: false}],
  ['isDownload', 'd'],
  ['isRemove', 'x'],
  ['isQueueAfterSelectedTrack', 'q'],
  ['isOpenThroughSystem', 'o'],
  ['isShuffleQueue', 's'],
  ['isClearQueue', 'c'],
  ['isFocusMenubar', ';'],
  ['isFocusLabels', 'L', {caseless: false}], // todo: better key? to let isToggleLoop be caseless again
  ['isSelectUp', telc.isShiftUp],
  ['isSelectDown', telc.isShiftDown],

  ['isPreviousPlayer', telc.isMetaUp],
  ['isPreviousPlayer', [0x1b, 'p']],
  ['isNextPlayer', telc.isMetaDown],
  ['isNextPlayer', [0x1b, 'n']],
  ['isNewPlayer', [0x1b, 'c']],
  ['isRemovePlayer', [0x1b, 'x']],
  ['isActOnPlayer', [0x1b, 'a']],
  ['isActOnPlayer', [0x1b, '!']],

  ['isFocusTextEditor', [0x05]], // ^E
  ['isSaveTextEditor', [0x13]], // ^S
  ['isDeselectTextEditor', [0x18]], // ^X
  ['isDeselectTextEditor', telc.isEscape],

  // Number pad
  ['isUp', '8'],
  ['isDown', '2'],
  ['isLeft', '4'],
  ['isRight', '6'],
  ['isSpace', '5'],
  ['isTogglePause', '5'],
  ['isBackspace', '.'],
  ['isMenu', '+'],
  ['isSkipBack', '1'],
  ['isSkipAhead', '3'],
  // Disabled because this is the jump key! Oops.
  // ['isVolumeDown', '/'],
  // ['isVolumeUp', '*'],
  ['isFocusTabber', '7'],
  ['isFocusQueue', '9'],
  ['isFocusMenubar', '*'],

  // HJKL
  ['isDown', 'j'],
  ['isUp', 'k'],
  // Don't use these for now... currently L is used for toggling loop.
  // May want to look into changing that (so we can re-enable these).
  // ['isLeft', 'h'],
  // ['isRight', 'l'],
]

const addKey = (prop, keyOrFunc, {caseless = true} = {}) => {
  const oldFunc = input[prop] || (() => false)
  let newFunc
  if (typeof keyOrFunc === 'function') {
    newFunc = keyOrFunc
  } else if (typeof keyOrFunc === 'string') {
    const key = keyOrFunc
    if (caseless) {
      newFunc = input => input.toString().toLowerCase() === key.toLowerCase()
    } else {
      newFunc = input => input.toString() === key
    }
  } else if (Array.isArray(keyOrFunc)) {
    const buf = Buffer.from(keyOrFunc.map(k => typeof k === 'string' ? k.charCodeAt(0) : k))
    newFunc = keyBuf => keyBuf.equals(buf)
  }
  input[prop] = keyBuf => newFunc(keyBuf) || oldFunc(keyBuf)
}

for (const entry of keyBindings) {
  addKey(...entry)
}

// Some things just need to be overridden in order for the rest of tui-lib to
// recognize our new keys.
telc.isUp = input.isUp
telc.isDown = input.isDown
telc.isLeft = input.isLeft
telc.isRight = input.isRight
telc.isSelect = input.isSelect
telc.isBackspace = input.isBackspace

class AppElement extends FocusElement {
  constructor(backend, config = {}) {
    super()

    this.backend = backend
    this.telnetServer = null
    this.isPartyHost = false

    this.config = Object.assign({
      canControlPlayback: true,
      canControlQueue: true,
      canControlQueuePlayers: true,
      canProcessMetadata: true,
      canSuspend: true,
      menubarColor: 4, // blue
      showTabberPane: true,
      stopPlayingUponQuit: true
    }, config)

    // TODO: Move edit mode stuff to the backend!
    this.undoManager = new UndoManager()
    this.markGrouplike = {name: 'Selected Items', items: []}
    this.editMode = false

    // We add this is a child later (so that it's on top of every element).
    this.menuLayer = new DisplayElement()
    this.menuLayer.clickThrough = true
    this.showContextMenu = this.showContextMenu.bind(this)

    this.menubar = new Menubar(this.showContextMenu)
    this.addChild(this.menubar)

    this.menubar.color = this.config.menubarColor

    this.tabberPane = new Pane()
    this.addChild(this.tabberPane)

    this.queuePane = new Pane()
    this.addChild(this.queuePane)

    this.textInfoPane = new Pane()
    this.addChild(this.textInfoPane)

    this.textEditor = new NotesTextEditor()
    this.textInfoPane.addChild(this.textEditor)
    this.textInfoPane.visible = false

    this.textEditor.on('deselect', () => {
      this.root.select(this.tabber)
      this.fixLayout()
    })

    if (!this.config.showTabberPane) {
      this.tabberPane.visible = false
    }

    this.tabber = new Tabber()
    this.tabberPane.addChild(this.tabber)

    this.metadataStatusLabel = new Label()
    this.metadataStatusLabel.visible = false
    this.tabberPane.addChild(this.metadataStatusLabel)

    this.newGrouplikeListing()

    this.queueListingElement = new QueueListingElement(this)
    this.setupCommonGrouplikeListingEvents(this.queueListingElement)
    this.queuePane.addChild(this.queueListingElement)

    this.queueLengthLabel = new Label('')
    this.queuePane.addChild(this.queueLengthLabel)

    this.queueTimeLabel = new Label('')
    this.queuePane.addChild(this.queueTimeLabel)

    this.queueListingElement.on('open', item => this.openSpecialOrThroughSystem(item))
    this.queueListingElement.on('queue', item => this.play(item))
    this.queueListingElement.on('remove', item => this.unqueue(item))
    this.queueListingElement.on('shuffle', () => this.shuffleQueue())
    this.queueListingElement.on('clear', () => this.clearQueue())
    this.queueListingElement.on('select main listing',
      () => this.selected())

    this.playbackPane = new Pane()
    this.addChild(this.playbackPane)

    this.playbackForm = new ListScrollForm()
    this.playbackPane.addChild(this.playbackForm)

    this.playbackInfoElements = []

    this.partyTop = new DisplayElement()
    this.partyBottom = new DisplayElement()
    this.addChild(this.partyTop)
    this.addChild(this.partyBottom)
    this.partyTop.visible = false
    this.partyBottom.visible = false

    this.partyTopBanner = new PartyBanner(1)
    this.partyBottomBanner = new PartyBanner(-1)
    this.partyTop.addChild(this.partyTopBanner)
    this.partyBottom.addChild(this.partyBottomBanner)

    this.partyLabel = new Label('')
    this.partyTop.addChild(this.partyLabel)

    // Dialogs

    this.openPlaylistDialog = new OpenPlaylistDialog()
    this.setupDialog(this.openPlaylistDialog)

    this.openPlaylistDialog.on('source selected', source => this.handlePlaylistSource(source))
    this.openPlaylistDialog.on('source selected (new tab)', source => this.handlePlaylistSource(source, true))

    this.alertDialog = new AlertDialog()
    this.setupDialog(this.alertDialog)

    // Should be placed on top of everything else!
    this.addChild(this.menuLayer)

    this.whereControl = new InlineListPickerElement('Where?', [
      {value: 'next-selected', label: 'After selected song'},
      {value: 'next', label: 'After current song'},
      {value: 'end', label: 'At end of queue'},
      {value: 'distribute-evenly', label: 'Distributed across queue evenly'},
      {value: 'distribute-randomly', label: 'Distributed across queue randomly'}
    ], this.showContextMenu)

    this.orderControl = new InlineListPickerElement('Order?', [
      {value: 'shuffle', label: 'Shuffle all'},
      {value: 'shuffle-groups', label: 'Shuffle order of groups'},
      {value: 'reverse', label: 'Reverse all'},
      {value: 'reverse-groups', label: 'Reverse order of groups'},
      {value: 'normal', label: 'In order'}
    ], this.showContextMenu)

    this.menubar.buildItems([
      {text: 'mtui', menuItems: [
        {label: 'mtui (perpetual development)'},
        {divider: true},
        {label: 'Quit', action: () => this.shutdown()},
        this.config.canSuspend && {label: 'Suspend', action: () => this.suspend()}
      ]},
      {text: 'Playback', menuFn: () => {
        const { playingTrack } = this.SQP
        const { items } = this.SQP.queueGrouplike
        const curIndex = items.indexOf(playingTrack)
        const next = (curIndex >= 0) && items[curIndex + 1]
        const previous = (curIndex >= 0) && items[curIndex - 1]

        return [
          {label: playingTrack ? `("${playingTrack.name}")` : '(No track playing.)'},
          {divider: true},
          playingTrack && {element: this.playingControl},
          {element: this.loopingControl},
          {element: this.pauseNextControl},
          {element: this.volumeSlider},
          {divider: true},
          previous && {label: `Previous (${previous.name})`, action: () => this.SQP.playPrevious(playingTrack)},
          next && {label: `Next (${next.name})`, action: () => this.SQP.playNext(playingTrack)},
          next && {label: '- Play later', action: () => this.playLater(next)}
        ]
      }},
      {text: 'Queue', menuFn: () => {
        const { items } = this.SQP.queueGrouplike
        const curIndex = items.indexOf(this.playingTrack)

        return [
          {label: `(Queue - ${curIndex >= 0 ? `${curIndex + 1}/` : ''}${items.length} items.)`},
          {divider: true},
          items.length && {label: 'Shuffle', action: () => this.shuffleQueue()},
          items.length && {label: 'Clear', action: () => this.clearQueue()}
        ]
      }},
      {text: 'Multi', menuFn: () => {
        const { queuePlayers } = this.backend
        return [
          {label: `(Multi-players - ${queuePlayers.length})`},
          {divider: true},
          ...queuePlayers.map((queuePlayer, index) => {
            const PIE = new PlaybackInfoElement(queuePlayer, this)
            PIE.displayMode = 'collapsed'
            PIE.updateTrack()
            return {element: PIE}
          })
        ]
      }}
    ])

    this.playingControl = new ToggleControl('Pause?', {
      setValue: val => this.SQP.setPause(val),
      getValue: () => this.SQP.player.isPaused,
      getEnabled: () => this.config.canControlPlayback
    })

    this.loopingControl = new ToggleControl('Loop current track?', {
      setValue: val => this.SQP.setLoop(val),
      getValue: () => this.SQP.player.isLooping,
      getEnabled: () => this.config.canControlPlayback
    })

    this.pauseNextControl = new ToggleControl('Pause when this track ends?', {
      setValue: val => this.SQP.setPauseNextTrack(val),
      getValue: () => this.SQP.pauseNextTrack,
      getEnabled: () => this.config.canControlPlayback
    })

    this.volumeSlider = new SliderElement('Volume', {
      setValue: val => this.SQP.setVolume(val),
      getValue: () => this.SQP.player.volume,
      getEnabled: () => this.config.canControlPlayback
    })

    this.bindListeners()
    this.initialAttachListeners()

    // Also handy to be bound to the app.
    this.showContextMenu = this.showContextMenu.bind(this)

    this.queuePlayersToActOn = []
    this.selectQueuePlayer(this.backend.queuePlayers[0])
  }

  bindListeners() {
    for (const key of [
      'handlePlaying',
      'handleReceivedTimeData',
      'handleProcessMetadataProgress',
      'handleQueueUpdated',
      'handleAddedQueuePlayer',
      'handleRemovedQueuePlayer'
    ]) {
      this[key] = this[key].bind(this)
    }
  }

  initialAttachListeners() {
    this.attachBackendListeners()
    for (const queuePlayer of this.backend.queuePlayers) {
      this.attachQueuePlayerListenersAndUI(queuePlayer)
    }
  }

  removeListeners() {
    this.removeBackendListeners()
    for (const queuePlayer of this.backend.queuePlayers) {
      // Don't update the UI - removeListeners is only called just before the
      // AppElement is done being used.
      this.removeQueuePlayerListenersAndUI(queuePlayer, false)
    }
  }

  attachQueuePlayerListenersAndUI(queuePlayer) {
    const PIE = new PlaybackInfoElement(queuePlayer, this)
    this.playbackInfoElements.push(PIE)
    this.playbackForm.addInput(PIE)
    this.fixLayout()

    PIE.on('seek back', () => PIE.queuePlayer.seekBack(5))
    PIE.on('seek ahead', () => PIE.queuePlayer.seekAhead(5))
    PIE.on('toggle pause', () => PIE.queuePlayer.togglePause())

    queuePlayer.on('received time data', this.handleReceivedTimeData)
    queuePlayer.on('playing', this.handlePlaying)
    queuePlayer.on('queue updated', this.handleQueueUpdated)
  }

  removeQueuePlayerListenersAndUI(queuePlayer, updateUI = true) {
    if (updateUI) {
      const PIE = this.getPlaybackInfoElementForQueuePlayer(queuePlayer)
      if (PIE) {
        const PIEs = this.playbackInfoElements
        const oldIndex = PIEs.indexOf(PIE)
        if (this.playbackForm.curIndex > oldIndex) {
          this.playbackForm.curIndex--
        }
        PIEs.splice(oldIndex, 1)
        this.playbackForm.removeInput(PIE)
        if (this.SQP === queuePlayer) {
          const { queuePlayer } = PIEs[Math.min(oldIndex, PIEs.length - 1)]
          this.selectQueuePlayer(queuePlayer)
        }
        this.fixLayout()
      }
    }

    const index = this.queuePlayersToActOn.indexOf(queuePlayer)
    if (index >= 0) {
      this.queuePlayersToActOn.splice(index, 1)
    }

    queuePlayer.removeListener('receivedTimeData', this.handleReceivedTimeData)
    queuePlayer.removeListener('playing', this.handlePlaying)
    queuePlayer.removeListener('queue updated', this.handleQueueUpdated)
    queuePlayer.stopPlaying()
  }

  attachBackendListeners() {
    this.backend.on('processMetadata progress', this.handleProcessMetadataProgress)
    this.backend.on('added queue player', this.handleAddedQueuePlayer)
    this.backend.on('removed queue player', this.handleRemovedQueuePlayer)
  }

  removeBackendListeners() {
    this.backend.removeListener('processMetadata progress', this.handleProcessMetadataProgress)
    this.backend.removeListener('added queue player', this.handleAddedQueuePlayer)
    this.backend.removeListener('removed queue player', this.handleRemovedQueuePlayer)
  }

  handleAddedQueuePlayer(queuePlayer) {
    this.attachQueuePlayerListenersAndUI(queuePlayer)
  }

  handleRemovedQueuePlayer(queuePlayer) {
    this.removeQueuePlayerListenersAndUI(queuePlayer)
  }

  handlePlaying(track, oldTrack, queuePlayer) {
    const PIE = this.getPlaybackInfoElementForQueuePlayer(queuePlayer)
    if (PIE) {
      PIE.updateTrack()
    }

    if (queuePlayer === this.SQP) {
      this.updateQueueLengthLabel()
      if (track && this.queueListingElement.currentItem === oldTrack) {
        this.queueListingElement.selectAndShow(track)
      }
    }
  }

  handleReceivedTimeData(data, queuePlayer) {
    const PIE = this.getPlaybackInfoElementForQueuePlayer(queuePlayer)
    if (PIE) {
      PIE.updateProgress()
    }

    if (queuePlayer === this.SQP) {
      this.updateQueueLengthLabel()
    }
  }

  handleProcessMetadataProgress(remaining) {
    this.metadataStatusLabel.text = `Processing metadata - ${remaining} to go.`
  }

  handleQueueUpdated() {
    this.queueListingElement.buildItems()
  }

  selectQueuePlayer(queuePlayer) {
    // You can use this.SQP as a shorthand to get this.
    this.selectedQueuePlayer = queuePlayer

    this.queueListingElement.loadGrouplike(queuePlayer.queueGrouplike)

    this.playbackForm.curIndex = this.playbackForm.inputs
      .findIndex(el => el.queuePlayer === queuePlayer)
    this.playbackForm.scrollSelectedElementIntoView()
  }

  selectNextQueuePlayer() {
    const { queuePlayers } = this.backend
    let index = queuePlayers.indexOf(this.SQP) + 1
    if (index >= queuePlayers.length) {
      index = 0
    }
    this.selectQueuePlayer(queuePlayers[index])
  }

  selectPreviousQueuePlayer() {
    const { queuePlayers } = this.backend
    let index = queuePlayers.indexOf(this.SQP) - 1
    if (index <= -1) {
      index = queuePlayers.length - 1
    }
    this.selectQueuePlayer(queuePlayers[index])
  }

  async addQueuePlayer() {
    if (!this.config.canControlQueuePlayers) {
      return false
    }

    const queuePlayer = await this.backend.addQueuePlayer()
    this.selectQueuePlayer(queuePlayer)
  }

  removeQueuePlayer(queuePlayer) {
    if (!this.config.canControlQueuePlayers) {
      return false
    }

    this.backend.removeQueuePlayer(queuePlayer)
  }

  toggleActOnQueuePlayer(queuePlayer) {
    const index = this.queuePlayersToActOn.indexOf(queuePlayer)
    if (index >= 0) {
      this.queuePlayersToActOn.splice(index, 1)
    } else {
      this.queuePlayersToActOn.push(queuePlayer)
    }

    for (const PIE of this.playbackInfoElements) {
      PIE.fixLayout()
    }
  }

  getPlaybackInfoElementForQueuePlayer(queuePlayer) {
    return this.playbackInfoElements
      .find(el => el.queuePlayer === queuePlayer)
  }

  selected() {
    if (this.tabberPane.visible) {
      this.root.select(this.tabber)
    } else {
      if (this.queueListingElement.selectable) {
        this.root.select(this.queueListingElement)
      } else {
        this.menubar.select()
      }
    }
  }

  newGrouplikeListing() {
    const grouplikeListing = new GrouplikeListingElement(this)
    this.tabber.addTab(grouplikeListing)
    this.tabber.selectTab(grouplikeListing)

    grouplikeListing.on('browse', item => grouplikeListing.loadGrouplike(item))
    grouplikeListing.on('download', item => this.SQP.download(item))
    grouplikeListing.on('open', item => this.openSpecialOrThroughSystem(item))
    grouplikeListing.on('queue', (item, opts) => this.handleQueueOptions(item, opts))

    const updateListingsFor = item => {
      for (const grouplikeListing of this.tabber.tabberElements) {
        if (grouplikeListing.grouplike === item) {
          grouplikeListing.loadGrouplike(item, false)
        }
      }
    }

    grouplikeListing.on('remove', item => {
      if (this.editMode) {
        const parent = item[parentSymbol]
        const index = parent.items.indexOf(item)

        this.undoManager.pushAction({
          activate: () => {
            parent.items.splice(index, 1)
            delete item[parentSymbol]
            updateListingsFor(item)
            updateListingsFor(parent)
          },
          undo: () => {
            parent.items.splice(index, 0, item)
            item[parentSymbol] = parent
            updateListingsFor(item)
            updateListingsFor(parent)
          }
        })
      }
    })

    grouplikeListing.on('mark', item => {
      if (this.editMode) {
        if (!this.markGrouplike.items.includes(item)) {
          this.undoManager.pushAction({
            activate: () => {
              this.markGrouplike.items.push(item)
            },
            undo: () => {
              this.markGrouplike.items.pop()
            }
          })
        } else {
          const index = this.markGrouplike.items.indexOf(item)
          this.undoManager.pushAction({
            activate: () => {
              this.markGrouplike.items.splice(index, 1)
            },
            undo: () => {
              this.markGrouplike.items.splice(index, 0, item)
            }
          })
        }
      }
    })

    grouplikeListing.on('paste', (item, {where = 'below'} = {}) => {
      if (this.editMode && this.markGrouplike.items.length) {
        let parent, index

        if (where === 'above') {
          parent = item[parentSymbol]
          index = parent.items.indexOf(item)
        } else if (where === 'below') {
          parent = item[parentSymbol]
          index = parent.items.indexOf(item) + 1
        }

        this.undoManager.pushAction({
          activate: () => {
            parent.items.splice(index, 0, ...cloneGrouplike(this.markGrouplike).items.map(
              item => Object.assign({}, item, {[parentSymbol]: parent})
            ))
            updateListingsFor(parent)
          },
          undo: () => {
            parent.items.splice(index, this.markGrouplike.items.length)
            updateListingsFor(parent)
          }
        })
      }
    })

    this.setupCommonGrouplikeListingEvents(grouplikeListing)

    return grouplikeListing
  }

  setupCommonGrouplikeListingEvents(grouplikeListing) {
    // Sets up event listeners that are common to ordinary grouplike listings
    // (made by newGrouplikeListing) as well as the queue grouplike listing.

    grouplikeListing.pathElement.on('select', item => this.reveal(item))
    grouplikeListing.on('menu', (item, el) => this.showMenuForItemElement(el, grouplikeListing))
    grouplikeListing.on('selected', item => this.editNotesFile(item, false))
    grouplikeListing.on('edit-notes', item => {
      this.reveal(item)
      this.editNotesFile(item, true)
    })
  }

  showContextMenu(opts) {
    const menu = new ContextMenu(this.showContextMenu)
    this.menuLayer.addChild(menu)
    if (opts.beforeShowing) {
      opts.beforeShowing(menu)
    }
    menu.show(opts)
    return menu
  }

  reveal(item) {
    if (!this.tabberPane.visible) {
      return
    }

    const tabberListing = this.tabber.currentElement
    this.root.select(tabberListing)

    const parent = item[parentSymbol]
    if (isGroup(item)) {
      tabberListing.loadGrouplike(item)
    } else if (parent) {
      if (tabberListing.grouplike !== parent) {
        tabberListing.loadGrouplike(parent)
      }
      tabberListing.selectAndShow(item)
    }
  }

  play(item) {
    if (!this.config.canControlQueue) {
      return
    }

    this.SQP.play(item)
  }

  unqueue(item) {
    if (!this.config.canControlQueue) {
      return
    }

    let focusItem = this.queueListingElement.currentItem
    focusItem = this.SQP.unqueue(item, focusItem)

    this.queueListingElement.buildItems()
    this.updateQueueLengthLabel()

    if (focusItem) {
      this.queueListingElement.selectAndShow(focusItem)
    }
  }

  playSooner(item) {
    if (!this.config.canControlQueue) {
      return
    }

    this.SQP.playSooner(item)
    // It may not have queued as soon as the user wants; in that case, they'll
    // want to queue it sooner again. Automatically reselect the track so that
    // this they don't have to navigate back to it by hand.
    this.queueListingElement.selectAndShow(item)
  }

  playLater(item) {
    if (!this.config.canControlQueue) {
      return
    }

    this.SQP.playLater(item)
    // Just for consistency with playSooner (you can press ^-L to quickly get
    // back to the current track).
    this.queueListingElement.selectAndShow(item)
  }

  clearQueuePast(item) {
    if (!this.config.canControlQueue) {
      return
    }

    this.SQP.clearQueuePast(item)
    this.queueListingElement.selectAndShow(item)
  }

  clearQueueUpTo(item) {
    if (!this.config.canControlQueue) {
      return
    }

    this.SQP.clearQueueUpTo(item)
    this.queueListingElement.selectAndShow(item)
  }

  deselectAll() {
    this.markGrouplike.items.splice(0)
  }

  pauseAll() {
    if (!this.config.canControlPlayback) {
      return
    }

    for (const queuePlayer of this.backend.queuePlayers) {
      queuePlayer.setPause(true)
    }
  }

  resumeAll() {
    if (!this.config.canControlPlayback) {
      return
    }

    for (const queuePlayer of this.backend.queuePlayers) {
      queuePlayer.setPause(false)
    }
  }

  async createNotesFile(item) {
    if (!item[parentSymbol]) {
      return
    }

    if (!item.url) {
      return
    }

    if (getCorrespondingFileForItem(item, '.txt')) {
      return
    }

    let itemPath
    try {
      itemPath = url.fileURLToPath(item.url)
    } catch (error) {
      return
    }

    const dirname = path.dirname(itemPath)
    const extname = path.extname(itemPath)
    const basename = path.basename(itemPath, extname)
    const name = basename + '.txt'
    const filePath = path.join(dirname, name)
    const fileURL = url.pathToFileURL(filePath).toString()
    const file = {name, url: fileURL}
    await writeFile(filePath, '\n')

    const { items } = item[parentSymbol]
    items.splice(items.indexOf(item), 0, file)
  }

  async editNotesFile(item, focus) {
    if (!item) {
      return
    }

    // Creates it, if it doesn't exist.
    // We only do this when we're manually selecting the file (and expect to
    // focus it). Otherwise we'd create a notes file for every track hovered
    // over!
    if (focus) {
      await this.createNotesFile(item)
    }

    const doubleCheckItem = () => {
      const listing = this.root.selectedElement.directAncestors.find(el => el instanceof GrouplikeListingElement)
      return listing && listing.currentItem === item
    }

    if (!doubleCheckItem()) {
      return
    }

    const status = await this.textEditor.openItem(item, {doubleCheckItem})

    let fixLayout
    if (status === true) {
      this.textInfoPane.visible = true
      fixLayout = true
    } else if (status === false) {
      this.textInfoPane.visible = false
      fixLayout = true
    }

    if (focus && (status === true || status === null) && doubleCheckItem()) {
      this.root.select(this.textEditor)
      fixLayout = true
    }

    if (fixLayout) {
      this.fixLayout()
    }
  }

  openSpecialOrThroughSystem(item) {
    if (item.url.endsWith('.json')) {
      return this.handlePlaylistSource(item.url, true)
    } else if (item.url.endsWith('.txt')) {
      if (this.textInfoPane.visible) {
        this.root.select(this.textEditor)
      }
    } else {
      return this.openThroughSystem(item)
    }
  }

  openThroughSystem(item) {
    if (!isOpenable(item)) {
      return
    }

    open(item.url)
  }

  set actOnAllPlayers(val) {
    if (val) {
      this.queuePlayersToActOn = this.backend.queuePlayers.slice()
    } else {
      this.queuePlayersToActOn = []
    }
  }

  get actOnAllPlayers() {
    return this.queuePlayersToActOn.length === this.backend.queuePlayers.length
  }

  willActOnQueuePlayer(queuePlayer) {
    if (this.queuePlayersToActOn.length) {
      if (this.queuePlayersToActOn.includes(queuePlayer)) {
        return 'marked'
      }
    } else if (queuePlayer === this.SQP) {
      return '=SQP'
    }
  }

  actOnQueuePlayers(fn) {
    const actOn = this.queuePlayersToActOn.length ? this.queuePlayersToActOn : [this.SQP]
    for (const queuePlayer of actOn) {
      fn(queuePlayer)
      const PIE = this.getPlaybackInfoElementForQueuePlayer(queuePlayer)
      if (PIE) {
        PIE.updateProgress()
      }
    }
  }

  showMenuForItemElement(el, listing) {
    const emitControls = play => () => {
      this.handleQueueOptions(item, {
        where: this.whereControl.curValue,
        order: this.orderControl.curValue,
        play: play
      })
    }

    let item
    if (this.markGrouplike.items.length) {
      item = this.markGrouplike
    } else {
      item = el.item
    }

    // TODO: Implement this! :P
    const isMarked = false

    const { editMode } = this
    const { canControlQueue, canProcessMetadata } = this.config
    const anyMarked = editMode && this.markGrouplike.items.length > 0
    const hasNotesFile = !!getCorrespondingFileForItem(item, '.txt')

    let items;
    if (listing.grouplike.isTheQueue && isTrack(item)) {
      items = [
        this.tabberPane.visible && {label: 'Reveal', action: () => this.reveal(item)},
        {divider: true},
        canControlQueue && {label: 'Play later', action: () => this.playLater(item)},
        canControlQueue && {label: 'Play sooner', action: () => this.playSooner(item)},
        {divider: true},
        canControlQueue && {label: 'Clear past this track', action: () => this.clearQueuePast(item)},
        canControlQueue && {label: 'Clear up to this track', action: () => this.clearQueueUpTo(item)},
        {divider: true},
        canControlQueue && {label: 'Remove from queue', action: () => this.unqueue(item)}
      ]
    } else {
      const numTracks = countTotalTracks(item)
      const { string: durationString } = this.backend.getDuration(item)
      items = [
        // A label that just shows some brief information about the item.
        {label:
          `(${item.name ? `"${item.name}"` : 'Unnamed'}` +
          (isGroup(item) ? (
            ' -' +
            ` ${numTracks} track${numTracks === 1 ? '' : 's'}` +
            `, ${durationString}`)
          : '') + ')',
          keyboardIdentifier: item.name
        },

        // The actual controls!
        {divider: true},

        // TODO: Don't emit these on the element (and hence receive them from
        // the listing) - instead, handle their behavior directly. We'll want
        // to move the "mark"/"paste" (etc) code into separate functions,
        // instead of just defining their behavior inside the listing event
        // handlers.
        /*
        editMode && {label: isMarked ? 'Unmark' : 'Mark', action: () => el.emit('mark')},
        anyMarked && {label: 'Paste (above)', action: () => el.emit('paste', {where: 'above'})},
        anyMarked && {label: 'Paste (below)', action: () => el.emit('paste', {where: 'below'})},
        // anyMarked && !this.isReal && {label: 'Paste', action: () => this.emit('paste')}, // No "above" or "elow" in the label because the "fake" item/row will be replaced (it'll disappear, since there'll be an item in the group)
        {divider: true},
        */

        canControlQueue && isPlayable(item) && {element: this.whereControl},
        canControlQueue && isGroup(item) && {element: this.orderControl},
        canControlQueue && isPlayable(item) && {label: 'Play!', action: emitControls(true)},
        canControlQueue && isPlayable(item) && {label: 'Queue!', action: emitControls(false)},
        {divider: true},

        canProcessMetadata && isGroup(item) && {label: 'Process metadata (new entries)', action: () => this.processMetadata(item, false)},
        canProcessMetadata && isGroup(item) && {label: 'Process metadata (reprocess)', action: () => this.processMetadata(item, true)},
        canProcessMetadata && isTrack(item) && {label: 'Process metadata', action: () => this.processMetadata(item, true)},
        isOpenable(item) && item.url.endsWith('.json') && {label: 'Open (JSON Playlist)', action: () => this.openSpecialOrThroughSystem(item)},
        isOpenable(item) && {label: 'Open (System)', action: () => this.openThroughSystem(item)},
        !hasNotesFile && isPlayable(item) && {label: 'Create notes file', action: () => this.editNotesFile(item, true)},
        hasNotesFile && isPlayable(item) && {label: 'Edit notes file', action: () => this.editNotesFile(item, true)},
        canControlQueue && isPlayable(item) && {label: 'Remove from queue', action: () => this.unqueue(item)},
        {divider: true},

        item === this.markGrouplike && {label: 'Deselect', action: () => this.deselectAll()}
      ]
    }

    this.showContextMenu({
      x: el.absLeft,
      y: el.absTop + 1,
      items
    })
  }

  async handlePlaylistSource(source, newTab = false) {
    if (this.openPlaylistDialog.visible) {
      this.openPlaylistDialog.close()
    }

    this.alertDialog.showMessage('Opening playlist...', false)

    let grouplike
    try {
      grouplike = await this.openPlaylist(source)
    } catch (error) {
      if (error === 'unknown argument') {
        this.alertDialog.showMessage('Could not figure out how to load a playlist from: ' + source)
      } else if (typeof error === 'string') {
        this.alertDialog.showMessage(error)
      } else {
        throw error
      }

      return
    }

    this.alertDialog.close()

    grouplike = await processSmartPlaylist(grouplike)

    if (newTab || !this.tabber.currentElement) {
      const grouplikeListing = this.newGrouplikeListing()
      grouplikeListing.loadGrouplike(grouplike)
    } else {
      this.tabber.currentElement.loadGrouplike(grouplike)
    }
  }

  openPlaylist(arg) {
    const crawlers = getAllCrawlersForArg(arg)

    if (crawlers.length === 0) {
      throw 'unknown argument'
    }

    const crawler = crawlers[0]

    return crawler(arg)
  }

  setupDialog(dialog) {
    dialog.visible = false
    this.addChild(dialog)

    dialog.on('cancelled', () => {
      dialog.close()
    })
  }

  async shutdown() {
    if (this.config.stopPlayingUponQuit) {
      await this.backend.stopPlayingAll()
    }

    await this.textEditor.save()
    this.emit('quitRequested')
  }

  suspend() {
    if (this.config.canSuspend) {
      this.emit('suspendRequested')
    }
  }

  fixLayout() {
    if (this.parent) {
      this.fillParent()
    }

    this.menubar.fixLayout()

    let topY = this.contentH

    if (this.partyBottom.visible) {
      this.partyBottom.w = this.contentW
      this.partyBottom.h = 1
      this.partyBottom.x = 0
      this.partyBottom.y = topY - this.partyBottom.h
      topY = this.partyBottom.top
      this.partyBottomBanner.w = this.partyBottom.w
    }

    this.playbackPane.w = this.contentW
    this.playbackPane.h = 5
    this.playbackPane.x = 0
    this.playbackPane.y = topY - this.playbackPane.h
    topY = this.playbackPane.top

    for (const PIE of this.playbackInfoElements) {
      if (this.playbackInfoElements.length === 1) {
        PIE.displayMode = 'expanded'
      } else {
        PIE.displayMode = 'collapsed'
      }
    }
    this.playbackForm.fillParent()
    this.playbackForm.fixLayout()

    let bottomY = 1

    if (this.partyTop.visible) {
      this.partyTop.w = this.contentW
      this.partyTop.h = 1
      this.partyTop.x = 0
      this.partyTop.y = 1
      bottomY = this.partyTop.bottom

      this.partyTopBanner.w = this.partyTop.w
      this.partyTopBanner.y = this.partyTop.contentH - 1

      this.alignPartyLabel()
    }

    const leftWidth = Math.max(Math.floor(0.8 * this.contentW), this.contentW - 80)

    if (this.textInfoPane.visible) {
      this.textInfoPane.w = leftWidth
      if (this.textEditor.isSelected) {
        this.textInfoPane.h = 8
      } else {
        this.textEditor.w = this.textInfoPane.contentW
        this.textEditor.rebuildUiLines()
        this.textInfoPane.h = Math.min(8, this.textEditor.getOptimalHeight() + 2)
      }

      this.textEditor.fillParent()
      this.textEditor.fixLayout()
    }

    if (this.tabberPane.visible) {
      this.tabberPane.w = leftWidth
      this.tabberPane.y = bottomY
      this.tabberPane.h = topY - this.tabberPane.y
      if (this.textInfoPane.visible) {
        this.tabberPane.h -= this.textInfoPane.h
        this.textInfoPane.y = this.tabberPane.bottom
      }
      this.queuePane.x = this.tabberPane.right
      this.queuePane.w = this.contentW - this.tabberPane.right
    } else {
      this.queuePane.x = 0
      this.queuePane.w = this.contentW
      if (this.textInfoPane.visible) {
        this.textInfoPane.y = bottomY
      }
    }

    this.queuePane.y = bottomY
    this.queuePane.h = topY - this.queuePane.y
    topY = this.queuePane.y

    this.tabber.fillParent()

    if (this.metadataStatusLabel.visible) {
      this.tabber.h--
      this.metadataStatusLabel.y = this.tabberPane.contentH - 1
    }

    this.tabber.fixLayout()

    this.queueListingElement.fillParent()
    this.queueListingElement.h -= 2

    this.updateQueueLengthLabel()

    this.menuLayer.fillParent()
  }

  alignPartyLabel() {
    this.partyLabel.centerInParent()
    this.partyLabel.y = 0
  }

  attachAsServerHost(telnetServer) {
    this.isPartyHost = true
    this.attachAsServer(telnetServer)
  }

  attachAsServerClient(telnetServer) {
    this.isPartyHost = false
    this.attachAsServer(telnetServer)
  }

  attachAsServer(telnetServer) {
    this.telnetServer = telnetServer
    this.updatePartyLabel()

    this.telnetServer.on('joined', () => this.updatePartyLabel())
    this.telnetServer.on('left', () => this.updatePartyLabel())

    this.partyTop.visible = true
    this.partyBottom.visible = true
    this.fixLayout()
  }

  updatePartyLabel() {
    const clients = this.telnetServer.sockets.length
    const clientsMsg = clients === 1 ? '1-ish connection' : `${clients}-ish connections`
    let msg = `${process.env.USER} playing for ${clientsMsg}`

    this.partyLabel.text = `  ${msg}  `
    this.alignPartyLabel()
  }

  keyPressed(keyBuf) {
    if (keyBuf[0] === 0x03) { // Ctrl-C
      this.shutdown()
      return
    } else if (keyBuf[0] === 0x1a) { // Ctrl-Z
      this.suspend()
      return
    }

    if ((telc.isEscape(keyBuf) || telc.isBackspace(keyBuf)) && this.menubar.isSelected) {
      this.menubar.restoreSelection()
      return
    }

    if (this.config.canControlPlayback) {
      if ((telc.isLeft(keyBuf) || telc.isRight(keyBuf)) && this.menubar.isSelected) {
        return // le sigh
      } else if (input.isRight(keyBuf)) {
        this.actOnQueuePlayers(qp => qp.seekAhead(10))
      } else if (input.isLeft(keyBuf)) {
        this.actOnQueuePlayers(qp => qp.seekBack(10))
      } else if (input.isTogglePause(keyBuf)) {
        this.actOnQueuePlayers(qp => qp.togglePause())
      } else if (input.isToggleLoop(keyBuf)) {
        this.actOnQueuePlayers(qp => qp.toggleLoop())
      } else if (input.isVolumeUp(keyBuf)) {
        this.actOnQueuePlayers(qp => qp.volUp())
      } else if (input.isVolumeDown(keyBuf)) {
        this.actOnQueuePlayers(qp => qp.volDown())
      } else if (input.isStop(keyBuf)) {
        this.actOnQueuePlayers(qp => qp.stopPlaying())
      } else if (input.isSkipBack(keyBuf)) {
        this.actOnQueuePlayers(qp => qp.playPrevious(qp.playingTrack, true))
      } else if (input.isSkipAhead(keyBuf)) {
        this.actOnQueuePlayers(qp => qp.playNext(qp.playingTrack, true))
      }
    }

    if (input.isFocusTabber(keyBuf) && this.tabberPane.visible && this.tabber.selectable) {
      this.root.select(this.tabber)
    } else if (input.isFocusQueue(keyBuf) && this.queueListingElement.selectable) {
      this.root.select(this.queueListingElement)
    } else if (input.isFocusPlaybackInfo(keyBuf) && this.backend.queuePlayers.length > 1) {
      this.root.select(this.playbackForm)
    } else if (input.isFocusMenubar(keyBuf)) {
      if (this.menubar.isSelected) {
        this.menubar.restoreSelection()
      } else {
        // If we've got a menu open, close it, restoring selection to the
        // element selected before the menu was opened, so the menubar will
        // see that as the previously selected element (instead of the context
        // menu - which will be closed irregardless and gone when the menubar
        // tries to restore the selection).
        if (this.menuLayer.children[0]) {
          this.menuLayer.children[0].close()
        }
        this.menubar.select()
      }
    } else if (this.editMode && keyBuf.equals(Buffer.from([14]))) { // ctrl-N
      this.newEmptyTab()
    } else if (keyBuf.equals(Buffer.from([15]))) { // ctrl-O
      this.openPlaylistDialog.open()
    } else if (this.tabber.isSelected && keyBuf.equals(Buffer.from([20]))) { // ctrl-T
      this.cloneCurrentTab()
    } else if (this.tabber.isSelected && keyBuf.equals(Buffer.from([23]))) { // ctrl-W
      if (this.tabber.tabberElements.length > 1) {
        this.closeCurrentTab()
      }
    } else if (telc.isCharacter(keyBuf, 'u')) {
      this.undoManager.undoLastAction()
    } else if (telc.isCharacter(keyBuf, 'U')) {
      this.undoManager.redoLastUndoneAction()
    } else if (this.tabber.isSelected && keyBuf.equals(Buffer.from(['t'.charCodeAt(0)]))) {
      this.tabber.nextTab()
    } else if (this.tabber.isSelected && keyBuf.equals(Buffer.from(['T'.charCodeAt(0)]))) {
      this.tabber.previousTab()
    } else if (input.isPreviousPlayer(keyBuf)) {
      this.selectPreviousQueuePlayer()
    } else if (input.isNextPlayer(keyBuf)) {
      this.selectNextQueuePlayer()
    } else if (input.isNewPlayer(keyBuf)) {
      this.addQueuePlayer()
    } else if (input.isRemovePlayer(keyBuf)) {
      this.removeQueuePlayer(this.SQP)
    } else if (input.isActOnPlayer(keyBuf)) {
      this.toggleActOnQueuePlayer(this.SQP)
    } else {
      super.keyPressed(keyBuf)
    }
  }

  newEmptyTab() {
    const listing = this.newGrouplikeListing()
    listing.loadGrouplike({
      name: 'New Playlist',
      items: []
    })
  }

  cloneCurrentTab() {
    const grouplike = this.tabber.currentElement.grouplike
    const listing = this.newGrouplikeListing()
    listing.loadGrouplike(grouplike)
  }

  closeCurrentTab() {
    const listing = this.tabber.currentElement
    let index
    this.undoManager.pushAction({
      activate: () => {
        index = this.tabber.currentElementIndex
        this.tabber.closeTab(this.tabber.currentElement)
      },
      undo: () => {
        this.tabber.addTab(listing, index)
        this.tabber.selectTab(listing)
      }
    })
  }

  shuffleQueue() {
    this.SQP.shuffleQueue()
  }

  clearQueue() {
    this.SQP.clearQueue()
    this.queueListingElement.selectNone()
    this.updateQueueLengthLabel()

    if (this.queueListingElement.isSelected && !this.queueListingElement.selectable) {
      this.root.select(this.tabber)
    }
  }

  // TODO: I'd like to name/incorporate this function better.. for now it's
  // just directly moved from the old event listener on grouplikeListings for
  // 'queue'.
  handleQueueOptions(item, {where = 'end', order = 'normal', play = false, skip = false} = {}) {
    if (!this.config.canControlQueue) {
      return
    }

    const passedItem = item

    let { playingTrack } = this.SQP

    if (skip && playingTrack === item) {
      this.SQP.playNext(playingTrack)
    }

    if (isGroup(item)) {
      if (order === 'shuffle') {
        item = {items: shuffleArray(flattenGrouplike(item).items)}
      } else if (order === 'shuffle-groups') {
        item = shuffleOrderOfGroups(item)
      } else if (order === 'reverse') {
        item = {items: flattenGrouplike(item).items.reverse()}
      } else if (order === 'reverse-groups') {
        item = reverseOrderOfGroups(item)
      }
    } else {
      // Make it into a grouplike that just contains itself.
      item = {items: [item]}
    }

    if (where === 'next' || where === 'next-selected' || where === 'end') {
      let afterItem = null
      if (where === 'next') {
        afterItem = playingTrack
      } else if (where === 'next-selected') {
        afterItem = this.queueListingElement.currentItem
      }

      this.SQP.queue(item, afterItem, {
        movePlayingTrack: order === 'normal'
      })

      if (isTrack(passedItem)) {
        this.queueListingElement.selectAndShow(passedItem)
      }
    } else if (where.startsWith('distribute-')) {
      this.SQP.distributeQueue(item, {
        how: where.slice('distribute-'.length)
      })
    }

    this.updateQueueLengthLabel()

    if (play) {
      this.play(item)
    }
  }

  async processMetadata(item, reprocess = false) {
    if (!this.config.canProcessMetadata) {
      return
    }

    if (this.clearMetadataStatusTimeout) {
      clearTimeout(this.clearMetadataStatusTimeout)
    }

    this.metadataStatusLabel.text = 'Processing metadata...'
    this.metadataStatusLabel.visible = true
    this.fixLayout()

    const counter = await this.backend.processMetadata(item, reprocess)

    const tracksMsg = (counter === 1) ? '1 track' : `${counter} tracks`
    this.metadataStatusLabel.text = `Done processing metadata of ${tracksMsg}!`

    this.clearMetadataStatusTimeout = setTimeout(() => {
      this.clearMetadataStatusTimeout = null
      this.metadataStatusLabel.text = ''
      this.metadataStatusLabel.visible = false
      this.fixLayout()
    }, 3000)
  }

  updateQueueLengthLabel() {
    if (!this.SQP) {
      this.queueTimeLabel.text = ''
      return
    }

    const { playingTrack, timeData } = this.SQP
    const { items } = this.SQP.queueGrouplike

    let trackRemainSec = 0

    if (timeData) {
      const { curSecTotal = 0, lenSecTotal = 0 } = timeData
      trackRemainSec = lenSecTotal - curSecTotal
    }

    // Index of tracks "ahead" of the current track. All tracks before this
    // index are accounted for by either being behind the current track (and
    // thus ignorable) or being the current track (and thus having its
    // remaining duration be counted by the time data stored on the playback
    // info element).
    let index = 0

    if (playingTrack) {
      index = items.indexOf(playingTrack)
      // If it's NOT counted by the playback info element's time data yet,
      // we skip this - the current track is counted as "ahead" and its
      // duration will be tallied like the rest of the "ahead" tracks.
      if (timeData) {
        index++
      }
    }

    const { seconds: aheadRemainSec, approxSymbol } = this.backend.getDuration({items: items.slice(index)})
    const totalRemainSec = trackRemainSec + aheadRemainSec

    const { duration } = getTimeStringsFromSec(0, totalRemainSec)

    this.queueLengthLabel.text = (playingTrack && items.includes(playingTrack)
      ? `(${this.SQP.playSymbol} ${index} / ${items.length})`
      : `(${items.length})`)

    this.queueTimeLabel.text = `(${duration + approxSymbol})`

    this.queueLengthLabel.centerInParent()
    this.queueTimeLabel.centerInParent()
    this.queueLengthLabel.y = this.queuePane.contentH - 2
    this.queueTimeLabel.y = this.queuePane.contentH - 1
  }

  get SQP() {
    // Just a convenient shorthand.
    return this.selectedQueuePlayer
  }

  get selectedQueuePlayer() { return this.getDep('selectedQueuePlayer') }
  set selectedQueuePlayer(v) { return this.setDep('selectedQueuePlayer', v) }
}

class GrouplikeListingElement extends Form {
  // TODO: This is a Form, which means that it captures the tab key. The result
  // of this is that you cannot use Tab to navigate the top-level application.
  // Accordingly, I've made AppElement a FocusElement and not a Form and re-
  // factored calls of addInput to addChild. However, I'm not sure that this is
  // the "correct" or most intuitive behavior. Should the tab key be usable to
  // navigate the entire interface? I don't know. I've gone with the current
  // behavior (GrouplikeListingElement as a Form) because it feels right at the
  // moment, but we'll see, I suppose.
  //
  // In order to let tab navigate through all UI elements (or rather, the top-
  // level application as well as GrouplikeListingElements, which are a sort of
  // nested Form), the AppElement would have to be changed to be a Form again
  // (replacing addChild with addInput where appropriate). Furthermore, while
  // the GrouplikeListingElement should stay as a Form subclass, it should be
  // modified so that it does not capture tab if there is no next element to
  // select, and vice versa for shift-tab and the previous element. This should
  // probably be implemented in tui-lib as a flag on Form (captureTabOnEnds,
  // or something).
  //
  // (PS AppElement apparently used a "this.form" property, instead of directly
  // inheriting from Form, apparently. That's more or less adjacent to the
  // point. It's removed now. You'll have to add it back, if wanted.)
  //
  // August 15th, 2018

  constructor(app) {
    super()

    this.grouplike = null
    this.app = app

    this.form = this.getNewForm()
    this.addInput(this.form)

    this.form.on('selected', input => {
      if (input && this.pathElement) {
        this.pathElement.showItem(input.item)
        this.emit('selected', input.item)
      }
    })

    this.jumpElement = new ListingJumpElement()
    this.addChild(this.jumpElement)
    this.jumpElement.visible = false
    this.oldFocusedIndex = null // To restore to, if a jump is canceled.
    this.previousJumpValue = '' // To default to, if the user doesn't enter anything.

    this.jumpElement.on('cancel', () => this.hideJumpElement(true))
    this.jumpElement.on('change', value => this.handleJumpValue(value, false))
    this.jumpElement.on('confirm', value => this.handleJumpValue(value, true))

    this.pathElement = new PathElement()
    this.addInput(this.pathElement)

    this.commentLabel = new WrapLabel()
    this.addChild(this.commentLabel)
  }

  getNewForm() {
    return new GrouplikeListingForm(this.app)
  }

  fixLayout() {
    this.commentLabel.w = this.contentW

    this.form.w = this.contentW
    this.form.h = this.contentH
    this.form.y = this.commentLabel.bottom
    this.form.h -= this.commentLabel.h
    this.form.h -= 1 // For the path element
    if (this.jumpElement.visible) this.form.h -= 1

    this.form.fixLayout() // Respond to being resized
    this.form.scrollSelectedElementIntoView()

    this.pathElement.y = this.contentH - 1
    this.pathElement.w = this.contentW

    this.jumpElement.y = this.pathElement.y - 1
    this.jumpElement.w = this.contentW
  }

  selected() {
    this.curIndex = 0
    this.root.select(this.form)
    this.emit('selected', this.currentItem)
  }

  clicked(button) {
    if (button === 'left') {
      this.selected()
      return false
    }
  }

  get selectable() {
    return this.form.selectable
  }

  keyPressed(keyBuf) {
    // Just about everything here depends on the grouplike existing, so let's
    // not continue if it doesn't!
    if (!this.grouplike) {
      return
    }

    if (telc.isBackspace(keyBuf)) {
      this.loadParentGrouplike()
    } else if (telc.isCharacter(keyBuf, '/') || keyBuf[0] === 6) { // '/', ctrl-F
      this.showJumpElement()
    } else if (input.isScrollToStart(keyBuf)) {
      this.form.selectAndShow(this.grouplike.items[0])
      this.form.scrollToBeginning()
    } else if (input.isScrollToEnd(keyBuf)) {
      this.form.selectAndShow(this.grouplike.items[this.grouplike.items.length - 1])
    } else if (keyBuf[0] === 12) { // ctrl-L
      if (this.grouplike.isTheQueue) {
        this.form.selectAndShow(this.app.SQP.playingTrack)
      } else {
        this.toggleExpandLabels()
      }
    } else if (keyBuf[0] === 1) { // ctrl-A
      this.toggleSelectAll()
    } else {
      return super.keyPressed(keyBuf)
    }
  }

  loadGrouplike(grouplike, resetIndex = true) {
    this.grouplike = grouplike
    this.buildItems(resetIndex)
    if (this.root.select) this.hideJumpElement()
  }

  selectNone() {
    // nb: this is unrelated to the actual track selection system!
    // just clears the form selection
    this.pathElement.showItem(null)
    this.form.curIndex = 0
    this.form.scrollItems = 0
  }

  toggleSelectAll() {
    const { items } = this.grouplike
    if (items.every(item => this.app.markGrouplike.items.includes(item))) {
      this.app.markGrouplike.items = []
    } else {
      this.app.markGrouplike.items = items.slice(0) // Don't share the array! :)
    }
  }

  toggleExpandLabels() {
    this.expandLabels = !this.expandLabels
    for (const input of this.form.inputs) {
      if (!(input instanceof InteractiveGrouplikeItemElement)) {
        continue
      }
      if (!input.labelsSelected) {
        input.expandLabels = this.expandLabels
        input.computeText()
      }
    }
  }

  buildItems(resetIndex = false) {
    if (!this.grouplike) {
      throw new Error('Attempted to call buildItems before a grouplike was loaded')
    }

    this.commentLabel.text = this.grouplike.comment || ''

    const wasSelected = this.isSelected
    const form = this.form

    // Just outright scrap the old items - don't deal with any selection stuff
    // (as a result of removeInput) yet.
    form.children = form.children.filter(child => !form.inputs.includes(child));
    form.inputs = []

    const parent = this.grouplike[parentSymbol]
    if (parent) {
      const upButton = new BasicGrouplikeItemElement(`Up (to ${parent.name || 'unnamed group'})`)
      upButton.on('pressed', () => this.loadParentGrouplike())
      form.addInput(upButton)
    }

    if (this.grouplike.items.length) {
      // Add an element for controlling this whole group. Particularly handy
      // for operating on the top-level group, which itself is not contained
      // within any groups (so you can't bworse a parent and access its menu
      // from there).
      if (!this.grouplike.isTheQueue) {
        const ownElement = new BasicGrouplikeItemElement(`This group: ${this.grouplike.name || '(Unnamed group)'}`)
        ownElement.item = this.grouplike
        ownElement.app = this.app
        ownElement.isGroup = true
        ownElement.on('pressed', () => {
          ownElement.emit('menu', ownElement)
        })
        this.addEventListeners(ownElement)
        form.addInput(ownElement)
      }

      // Add the elements for all the actual items within this playlist.
      for (const item of this.grouplike.items) {
        if (!isPlayable(item) && getCorrespondingPlayableForFile(item)) {
          continue
        }

        const itemElement = new InteractiveGrouplikeItemElement(item, this.app)
        this.addEventListeners(itemElement)
        form.addInput(itemElement)

        if (this.grouplike.isTheQueue) {
          itemElement.hideMetadata = true
          itemElement.text = getNameWithoutTrackNumber(item)
        }
      }
    } else if (!this.grouplike.isTheQueue) {
      form.addInput(new BasicGrouplikeItemElement('(This group is empty)'))
    }

    if (wasSelected) {
      if (resetIndex) {
        form.scrollItems = 0
        form.selectInput(form.inputs[form.firstItemIndex])
      } else {
        this.root.select(form)
      }
    }

    // Just to make the selected-track-info bar fill right away (if it wasn't
    // already filled by a previous this.curIndex set).
    form.curIndex = form.curIndex

    this.fixAllLayout()
  }

  addEventListeners(itemElement) {
    for (const evtName of [
      'browse',
      'download',
      'edit-notes',
      'mark',
      'menu',
      'open',
      'paste',
      'queue',
      'remove',
      'unqueue'
    ]) {
      itemElement.on(evtName, (...data) => this.emit(evtName, itemElement.item, ...data))
    }

    itemElement.on('unselected labels', () => {
      if (!this.expandLabels) {
        itemElement.expandLabels = false
        itemElement.computeText()
      }
    })
  }

  loadParentGrouplike() {
    if (!this.grouplike) {
      return
    }

    const parent = this.grouplike[parentSymbol]
    if (parent) {
      const oldGrouplike = this.grouplike
      this.loadGrouplike(parent)

      const form = this.form
      const index = form.inputs.findIndex(inp => inp.item === oldGrouplike)
      if (typeof index === 'number') {
        form.curIndex = index
      } else {
        form.curIndex = form.firstItemIndex
      }
      form.updateSelectedElement()
      form.scrollSelectedElementIntoView()
    }
  }

  selectAndShow(item) {
    return this.form.selectAndShow(item)
  }

  handleJumpValue(value, isConfirm) {
    // If the user doesn't enter anything, we won't perform a search -- unless
    // the user just pressed enter. If that's the case, we'll search for
    // whatever was previously entered into the form. This is to strike a
    // balance between keeping the jump form simple and unsurprising but also
    // powerful, i.e. to support easy "repeated" searches (see the below
    // cmoment about search match prioritization).
    if (!value.length && isConfirm && this.previousJumpValue) {
      value = this.previousJumpValue
    }

    const grouplike = {items: this.form.inputs.map(inp => inp.item)}

    // We prioritize searching past the index that the user opened the jump
    // element from (oldFocusedIndex). This is so that it's more practical
    // to do a "repeated" search, wherein the user searches for the same
    // value over and over, each time jumping to the next match, until they
    // have found the one they're looking for.
    const preferredStartIndex = this.oldFocusedIndex

    const item = searchForItem(grouplike, value, preferredStartIndex)

    if (item) {
      this.form.curIndex = this.form.inputs.findIndex(inp => inp.item === item)
      this.form.scrollSelectedElementIntoView()
    } else {
      // TODO: Feedback that the search failed.. right now we just close the
      // jump-to menu, which might not be right.
    }

    if (isConfirm) {
      this.previousJumpValue = value
      this.hideJumpElement()
    }
  }

  showJumpElement() {
    this.oldFocusedIndex = this.form.curIndex
    this.jumpElement.visible = true
    this.root.select(this.jumpElement)
    this.fixLayout()
  }

  hideJumpElement(isCancel) {
    if (isCancel) {
      this.form.curIndex = this.oldFocusedIndex
      this.form.scrollSelectedElementIntoView()
    }
    this.jumpElement.visible = false
    if (this.jumpElement.isSelected) {
      this.root.select(this)
    }
    this.fixLayout()
  }

  get tabberLabel() {
    if (this.grouplike) {
      return this.grouplike.name || 'Unnamed group'
    } else {
      return 'No group open'
    }
  }

  get currentItem() {
    const element = this.form.inputs[this.form.curIndex] || null
    return element && element.item
  }
}

class GrouplikeListingForm extends ListScrollForm {
  constructor(app) {
    super('vertical')

    this.app = app
    this.dragInputs = []
    this.selectMode = null
    this.keyboardDragDirection = null
    this.captureTab = false
  }

  keyPressed(keyBuf) {
    if (input.isSelectUp(keyBuf)) {
      this.selectUp()
    } else if (input.isSelectDown(keyBuf)) {
      this.selectDown()
    } else {
      if (telc.isUp(keyBuf) || telc.isDown(keyBuf)) {
        this.keyboardDragDirection = null
      }
      return super.keyPressed(keyBuf)
    }
  }

  set curIndex(newIndex) {
    this.setDep('curIndex', newIndex)
    this.emit('selected', this.inputs[this.curIndex])
    return newIndex
  }

  get curIndex() {
    return this.getDep('curIndex')
  }

  get firstItemIndex() {
    return Math.max(0, this.inputs.findIndex(el => el instanceof InteractiveGrouplikeItemElement))
  }

  selectAndShow(item) {
    const index = this.inputs.findIndex(inp => inp.item === item)
    if (index >= 0) {
      this.curIndex = index
      if (this.isSelected) {
        this.updateSelectedElement()
      }
      this.scrollSelectedElementIntoView()
      return true
    }
    return false
  }

  clicked(button, allData) {
    const { line, ctrl } = allData
    if (button === 'left') {
      this.dragStartLine = line - this.absTop + this.scrollItems
      this.dragStartIndex = this.inputs.findIndex(inp => inp.absTop === line - 1)
      if (this.dragStartIndex >= 0) {
        const input = this.inputs[this.dragStartIndex]
        if (!(input instanceof InteractiveGrouplikeItemElement)) {
          this.dragStartIndex = -1
          return
        }
        const { item } = input
        if (this.app.markGrouplike.items.includes(item)) {
          this.selectMode = 'deselect'
        } else {
          if (!ctrl) {
            this.app.markGrouplike.items = []
          }
          this.selectMode = 'select'
        }
        if (ctrl) {
          this.dragInputs = [item]
          this.dragEnteredRange(item)
        } else {
          this.dragInputs = []
        }
        this.oldMarkedItems = this.app.markGrouplike.items.slice()
      }
    } else if (button === 'drag-left' && this.dragStartIndex >= 0) {
      const offset = (line - this.absTop + this.scrollItems) - this.dragStartLine
      const rangeA = this.dragStartIndex
      const rangeB = this.dragStartIndex + offset
      const inputs = ((rangeA < rangeB)
        ? this.inputs.slice(rangeA, rangeB + 1)
        : this.inputs.slice(rangeB, rangeA + 1))
      let enteredRange = inputs.filter(inp => !this.dragInputs.includes(inp))
      let leftRange = this.dragInputs.filter(inp => !inputs.includes(inp))
      for (const { item } of enteredRange) {
        this.dragEnteredRange(item)
      }
      for (const { item } of leftRange) {
        this.dragLeftRange(item)
      }
      if (this.inputs[rangeB]) {
        this.root.select(this.inputs[rangeB])
      }
      this.dragInputs = inputs
    } else if (button === 'release') {
      this.dragStartIndex = -1
    } else {
      return super.clicked(button, allData)
    }
  }

  dragEnteredRange(item) {
    const { items } = this.app.markGrouplike
    if (this.selectMode === 'select') {
      if (!items.includes(item)) {
        items.push(item)
      }
    } else if (this.selectMode === 'deselect') {
      if (items.includes(item)) {
        items.splice(items.indexOf(item), 1)
      }
    }
  }

  dragLeftRange(item) {
    const { items } = this.app.markGrouplike
    if (this.selectMode === 'select') {
      if (items.includes(item) && !this.oldMarkedItems.includes(item)) {
        items.splice(items.indexOf(item), 1)
      }
    } else if (this.selectMode === 'deselect') {
      if (!items.includes(item) && this.oldMarkedItems.includes(item)) {
        items.push(item)
      }
    }
  }

  selectUp() {
    this.handleKeyboardSelect(-1)
  }

  selectDown() {
    this.handleKeyboardSelect(+1)
  }

  handleKeyboardSelect(direction) {
    const move = () => {
      if (direction === +1) {
        this.nextInput()
      } else {
        this.previousInput()
      }
      this.scrollSelectedElementIntoView()
    }

    const getItem = () => {
      const input = this.inputs[this.curIndex]
      if (input instanceof InteractiveGrouplikeItemElement) {
        return input.item
      } else {
        return null
      }
    }

    if (!this.keyboardDragDirection) {
      const item = getItem()
      if (!item) {
        move()
        return
      }
      this.keyboardDragDirection = direction
      this.oldMarkedItems = this.app.markGrouplike.items.slice()
      if (this.app.markGrouplike.items.includes(item)) {
        this.selectMode = 'deselect'
      } else {
        this.selectMode = 'select'
      }
      this.dragEnteredRange(item)
    }

    if (direction === this.keyboardDragDirection) {
      move()
      const item = getItem()
      if (!item) {
        return
      }
      this.dragEnteredRange(item)
    } else {
      const item = getItem()
      if (!item) {
        move()
        return
      }
      this.dragLeftRange(item)
      move()
    }
  }
}

class BasicGrouplikeItemElement extends Button {
  constructor(text) {
    super()

    this._text = this._rightText = ''

    this.text = text
    this.rightText = ''
    this.drawText = ''
  }

  fixLayout() {
    this.w = this.parent.contentW
    this.h = 1

    this.computeText()
  }

  set text(val) {
    if (this._text !== val) {
      this._text = val
      this.computeText()
    }
  }

  get text() {
    return this._text
  }

  set rightText(val) {
    if (this._rightText !== val) {
      this._rightText = val
      this.computeText()
    }
  }

  get rightText() {
    return this._rightText
  }

  getFormattedRightText() {
    return this.rightText
  }

  getRightTextColumns() {
    return ansi.measureColumns(this.rightText)
  }

  getMinLeftTextColumns() {
    return 12
  }

  getLeftPadding() {
    return 2
  }

  getSelfSelected() {
    return this.isSelected
  }

  computeText() {
    let w = this.w - this.x - this.getLeftPadding()

    // Also make space for the right text - if we choose to show it.
    const rightTextCols = this.getRightTextColumns()
    const showRightText = (w - rightTextCols > this.getMinLeftTextColumns())
    if (showRightText) {
      w -= rightTextCols
    }

    let text = ansi.trimToColumns(this.text, w)

    const width = ansi.measureColumns(this.text)
    if (width < w) {
      text += ' '.repeat(w - width)
    }

    if (showRightText) {
      text += this.getFormattedRightText()
    }

    text += ansi.resetAttributes()

    this.drawText = text
  }

  drawTo(writable) {
    const isCurrentInput = this.parent.inputs[this.parent.curIndex] === this
    // This line's commented out for now, so it'll show as selected (but
    // dimmed) even if you don't have the listing selected. To change that,
    // uncomment this and add it to the isCurrentInput line.
    // const isListingSelected = this.parent.parent.isSelected
    const isSelfSelected = this.getSelfSelected()

    if (isSelfSelected) {
      writable.write(ansi.invert())
    } else if (isCurrentInput) {
      // technically cheating - isPlayable is defined on InteractiveGrouplikeElement
      if (this.isPlayable === false) {
        writable.write(ansi.setAttributes([ansi.A_INVERT, ansi.C_BLACK, ansi.A_BRIGHT]))
      } else {
        writable.write(ansi.setAttributes([ansi.A_INVERT, ansi.A_DIM]))
      }
    }

    writable.write(ansi.moveCursor(this.absTop, this.absLeft))
    this.writeStatus(writable)
    writable.write(this.drawText)
  }

  writeStatus(writable) {
    // Add a couple spaces. This is less than the padding of the status text
    // of elements which represent real playlist items; that's to distinguish
    // "fake" rows from actual playlist items.
    writable.write('  ')
    this.drawX += 2
  }

  keyPressed(keyBuf) {
    // This function is overridden by InteractiveGrouplikeItemElement, but
    // it's still specified here that only enter counts as an action key.
    // By default for buttons, the space key also works, but since in this app
    // space is generally bound to mean "pause" instead of "select", we don't
    // check if space is pressed here.
    if (telc.isEnter(keyBuf) || input.isMenu(keyBuf)) {
      this.emit('pressed')
    }
  }

  clicked(button) {
    super.clicked(button)
  }
}

class InlineListPickerElement extends FocusElement {
  // And you thought my class names couldn't get any worse...
  // This is an element that looks something like the following:
  //    Fruit?  [Apple]
  // (Imagine that "[Apple]" just looks like "Apple" written in blue text.)
  // If you press the element (like a button), it'll pick the next item in its
  // list of options, like "Banana" or "Canteloupe" in this example. The arrow
  // keys also work to move through the list. You typically don't want to put
  // too many items in the list, since there's no visual way of telling what's
  // next or previous. (That's the point, it's inline.) This element is mainly
  // useful in forms or ContextMenus.

  constructor(labelText, options, showContextMenu = null) {
    super()
    this.labelText = labelText
    this.options = options
    this.showContextMenu = showContextMenu
    this.curIndex = 0
    this.keyboardIdentifier = this.labelText
  }

  fixLayout() {
    // We want to fill the parent's width, but also fit ourselves, so we need
    // to determine the ideal width which would fit us but not leave extra
    // space.
    const longestOptionLength = this.options.reduce(
      (soFar, { label }) => Math.max(soFar, ansi.measureColumns(label)), 0)
    const idealWidth = (
      ansi.measureColumns(this.labelText) + longestOptionLength + 4)

    // Then we use whichever is greater - our ideal width or the width of the
    // parent - as our own width. The parent should respect our needs by
    // growing if necessary. :)  (ContextMenu does this, which is where you'd
    // typically embed this element.)
    // I shall fill you, parent, even beyond your own bounds!!!
    this.w = Math.max(this.parent.contentW, idealWidth)

    // Height is always just 1.
    this.h = 1
  }

  drawTo(writable) {
    if (this.isSelected) {
      writable.write(ansi.invert())
    }

    const curOption = this.options[this.curIndex].label.toString()
    let drawX = 0
    writable.write(ansi.moveCursor(this.absTop, this.absLeft))

    writable.write(this.labelText + ' ')
    drawX += ansi.measureColumns(this.labelText) + 1

    writable.write(ansi.setAttributes([ansi.A_BRIGHT, ansi.C_BLUE]))
    writable.write(' ' + curOption + ' ')
    drawX += ansi.measureColumns(curOption) + 2

    writable.write(ansi.setForeground(ansi.C_RESET))
    writable.write(' '.repeat(Math.max(0, this.w - drawX)))

    writable.write(ansi.resetAttributes())
  }

  keyPressed(keyBuf) {
    if (telc.isSelect(keyBuf) || telc.isRight(keyBuf)) {
      this.nextOption()
    } else if (telc.isLeft(keyBuf)) {
      this.previousOption()
    } else if (input.isMenu(keyBuf) && this.showContextMenu) {
      this.showContextMenu({
        x: this.absLeft + ansi.measureColumns(this.labelText) + 1,
        y: this.absTop + 1,
        items: this.options.map(({ value, label }, index) => ({
          label: label,
          action: () => {
            this.curIndex = index
          },
          isDefault: index === this.curIndex
        }))
      })
    } else {
      return true
    }
    return false
  }

  clicked(button) {
    if (button === 'left') {
      if (this.isSelected) {
        this.nextOption()
      } else {
        this.root.select(this)
      }
    } else if (button === 'scroll-up') {
      this.previousOption()
    } else if (button === 'scroll-down') {
      this.nextOption()
    } else {
      return true
    }
    return false
  }

  nextOption() {
    this.curIndex++
    if (this.curIndex === this.options.length) {
      this.curIndex = 0
    }
  }

  previousOption() {
    this.curIndex--
    if (this.curIndex < 0) {
      this.curIndex = this.options.length - 1
    }
  }

  get curValue() {
    return this.options[this.curIndex].value
  }

  get curIndex() { return this.getDep('curIndex') }
  set curIndex(v) { return this.setDep('curIndex', v) }
}

// Quite hacky, but ATM I can't think of any way to neatly tie getDep/setDep
// into the slider and toggle elements.
const drawAfter = (fn, thisObj) => (...args) => {
  const ret = fn(...args)
  thisObj.scheduleDrawWithoutPropertyChange()
  return ret
}

class SliderElement extends FocusElement {
  // Same general principle and usage as InlineListPickerElement, but for
  // changing a numeric value.

  constructor(labelText, {setValue, getValue, maxValue = 100, percent = true, getEnabled = () => true}) {
    super()
    this.labelText = labelText
    this.setValue = drawAfter(setValue, this)
    this.getValue = getValue
    this.getEnabled = getEnabled
    this.maxValue = maxValue
    this.percent = percent
    this.keyboardIdentifier = this.labelText
  }

  fixLayout() {
    const idealWidth = ansi.measureColumns(
      this.labelText +
      '  ' + this.getValueString(this.maxValue) +
      ' ' + this.getNumString(this.maxValue) +
      '  '
    )

    this.w = Math.max(this.parent.contentW, idealWidth)
    this.h = 1
  }

  drawTo(writable) {
    const enabled = this.getEnabled()

    if (this.isSelected) {
      writable.write(ansi.invert())
    }

    let drawX = 0
    writable.write(ansi.moveCursor(this.absTop, this.absLeft))

    if (!enabled) {
      writable.write(ansi.setAttributes([ansi.A_DIM, ansi.C_WHITE]))
    }

    writable.write(this.labelText + ' ')
    drawX += ansi.measureColumns(this.labelText) + 1

    if (enabled) {
      writable.write(ansi.setAttributes([ansi.A_BRIGHT, ansi.C_BLUE]))
    }
    writable.write(' ')
    drawX += 1

    const valueString = this.getValueString(this.getValue())
    writable.write(valueString)
    drawX += valueString.length

    const numString = this.getNumString(this.getValue())
    writable.write(' ' + numString + ' ')
    drawX += numString.length + 2

    if (enabled) {
      writable.write(ansi.setForeground(ansi.C_RESET))
    }

    writable.write(' '.repeat(Math.max(0, this.w - drawX)))

    writable.write(ansi.resetAttributes())
  }

  getValueString(value) {
    const maxLength = 10

    let length = Math.round(value / this.maxValue * maxLength)

    if (value < this.maxValue && length === maxLength) {
      length--
    }

    if (value > 0 && length === 0) {
      length++
    }

    return (
      '[' +
      '-'.repeat(length) +
      ' '.repeat(maxLength - length) +
      ']'
    )
  }

  getNumString(value) {
    const maxValueString = Math.round(this.maxValue).toString()
    const valueString = Math.round(value).toString()
    const paddedString = valueString.padStart(maxValueString.length)

    return paddedString + (this.percent ? '%' : '')
  }

  keyPressed(keyBuf) {
    const enabled = this.getEnabled()
    if (enabled && telc.isRight(keyBuf)) {
      this.increment()
    } else if (enabled && telc.isLeft(keyBuf)) {
      this.decrement()
    } else {
      return true
    }
    return false
  }

  clicked(button) {
    if (!this.getEnabled()) {
      return
    }

    if (button === 'left') {
      if (this.isSelected) {
        if (this.getValue() === this.maxValue) {
          this.setValue(0)
        } else {
          this.increment()
        }
      } else {
        this.root.select(this)
      }
    } else if (button === 'scroll-up') {
      this.increment()
    } else if (button === 'scroll-down') {
      this.decrement()
    }
  }

  increment() {
    this.setValue(this.getValue() + this.step)
  }

  decrement() {
    this.setValue(this.getValue() - this.step)
  }

  get step() {
    return this.maxValue / 10
  }
}

class ToggleControl extends FocusElement {
  constructor(labelText, {setValue, getValue, getEnabled = () => true}) {
    super()
    this.labelText = labelText
    this.setValue = drawAfter(setValue, this)
    this.getValue = getValue
    this.getEnabled = getEnabled
    this.keyboardIdentifier = this.labelText
  }

  keyPressed(keyBuf) {
    if (input.isSelect(keyBuf) && this.getEnabled()) {
      this.toggle()
    }
  }

  clicked(button) {
    if (!this.getEnabled()) {
      return
    }

    if (button === 'left') {
      if (this.isSelected) {
        this.toggle()
      } else {
        this.root.select(this)
      }
    } else if (button === 'scroll-up' || button === 'scroll-down') {
      this.toggle()
    } else {
      return true
    }
    return false
  }


  toggle() {
    this.setValue(!this.getValue())
  }

  fixLayout() {
    // Same general principle as ToggleControl - fill the parent, but always
    // fit ourselves!
    this.w = Math.max(this.parent.contentW, this.labelText.length + 5)
    this.h = 1
  }

  drawTo(writable) {
    if (this.isSelected) {
      writable.write(ansi.invert())
    }

    if (!this.getEnabled()) {
      writable.write(ansi.setAttributes([ansi.C_WHITE, ansi.A_DIM]))
    }

    writable.write(ansi.moveCursor(this.absTop, this.absLeft))

    writable.write(this.getValue() ? '[X] ' : '[.] ')
    writable.write(this.labelText)
    writable.write(' '.repeat(this.w - (this.labelText.length + 4)))

    writable.write(ansi.resetAttributes())
  }
}

class InteractiveGrouplikeItemElement extends BasicGrouplikeItemElement {
  constructor(item, app) {
    super(item.name)
    this.item = item
    this.app = app
    this.hideMetadata = false
    this.expandLabels = false
    this.labelsSelected = false
    this.selectedLabelIndex = 0
  }

  drawTo(writable) {
    this.rightText = ''
    if (!this.hideMetadata) {
      const metadata = this.app.backend.getMetadataFor(this.item)
      if (metadata) {
        const durationString = getTimeStringsFromSec(0, metadata.duration).duration
        this.rightText = `(${durationString}) `
      }
    }

    super.drawTo(writable)
  }

  selected() {
    this.computeText()
  }

  unselected() {
    this.unselectLabels()
  }

  getLabelTexts() {
    const separator = this.isSelected ? '' : ''
    let labels = []
    // let labels = ['Voice', 'Woof']
    if (this.expandLabels && this.labelsSelected) {
      labels = ['+', ...labels]
    }
    return labels.map((label, i) => {
      return [
        label,
        separator + (this.expandLabels
          ? (this.labelsSelected && i === this.selectedLabelIndex
            ? `<${label}>`
            : ` ${label} `)
          : label[0])
      ]
    })
  }

  getLabelColor(label) {
    if (label === '+') {
      return ansi.C_BLACK
    } else {
      return 30 + (label.charCodeAt(0) % 7)
    }
  }

  getFormattedRightText() {
    const labelTexts = this.getLabelTexts()

    if (labelTexts.length) {
      const lastColor = this.getLabelColor(labelTexts[labelTexts.length - 1][0])
      return (this.isSelected ? ' ' : '') +
        ansi.resetAttributes() +
        (this.isSelected ? '' : ' ') +
        ansi.setAttributes(this.isSelected ? [ansi.A_BRIGHT, 7] : []) +
        labelTexts.map(([ label, labelText ], i, arr) => {
          let text = ''

          if (this.isSelected) {
            text += ansi.setBackground(this.getLabelColor(label))
          } else {
            text += ansi.setForeground(this.getLabelColor(label))
          }

          text += labelText[0]

          // text += ansi.resetAttributes()
          text += ansi.setForeground(ansi.C_RESET)
          text += ansi.setBackground(this.getLabelColor(label))

          text += labelText.slice(1)

          return text
        }).join('') +
        ansi.setAttributes([ansi.A_RESET, this.isSelected ? 0 : lastColor]) +
        '▎' +
        ansi.resetAttributes() +
        super.getFormattedRightText()
    } else {
      return super.getFormattedRightText()
    }
  }

  getRightTextColumns() {
    const labelTexts = this.getLabelTexts()

    return labelTexts
      .reduce((acc, [l, lt]) => acc + lt.length, 0) +
      (labelTexts.length ? 2 : 0) +
      super.getRightTextColumns()
  }

  getMinLeftTextColumns() {
    return this.expandLabels ? 0 : super.getMinLeftTextColumns()
  }

  getLeftPadding() {
    return 3
  }

  getSelfSelected() {
    return !this.labelsSelected && super.getSelfSelected()
  }

  keyPressed(keyBuf) {
    if (this.labelsSelected) {
      if (input.isRight(keyBuf)) {
        this.selectNextLabel()
      } else if (input.isLeft(keyBuf)) {
        this.selectPreviousLabel()
      } else if (telc.isEscape(keyBuf) || input.isFocusLabels(keyBuf)) {
        this.unselectLabels()
        return false
      }
    } else if (input.isDownload(keyBuf)) {
      this.emit('download')
    } else if (input.isQueueAfterSelectedTrack(keyBuf)) {
      this.emit('queue', {where: 'next-selected'})
    } else if (input.isOpenThroughSystem(keyBuf)) {
      this.emit('open')
    } else if (telc.isEnter(keyBuf)) {
      if (isGroup(this.item)) {
        this.emit('browse')
      } else if (isTrack(this.item)) {
        this.emit('queue', {where: 'next', play: true})
      } else if (!this.isPlayable) {
        this.emit('open')
      }
    } else if (input.isRemove(keyBuf)) {
      this.emit('remove')
    } else if (input.isMenu(keyBuf)) {
      this.emit('menu', this)
    } else if (input.isFocusTextEditor(keyBuf)) {
      this.emit('edit-notes')
    } else if (input.isFocusLabels(keyBuf)) {
      this.labelsSelected = true
      this.expandLabels = true
      this.selectedLabelIndex = 0
    }
  }

  unselectLabels() {
    this.labelsSelected = false
    this.emit('unselected labels')
    this.computeText()
  }

  selectNextLabel() {
    this.selectedLabelIndex++
    if (this.selectedLabelIndex >= this.getLabelTexts().length) {
      this.selectedLabelIndex = 0
    }
    this.computeText()
  }

  selectPreviousLabel() {
    this.selectedLabelIndex--
    if (this.selectedLabelIndex < 0) {
      this.selectedLabelIndex = this.getLabelTexts().length - 1
    }
    this.computeText()
  }

  clicked(button, {ctrl}) {
    if (button === 'left') {
      if (this.isSelected) {
        if (ctrl) {
          return
        }
        if (this.isGroup) {
          this.emit('browse')
        } else if (this.isTrack) {
          this.emit('queue', {where: 'next', play: true})
        } else if (!this.isPlayable) {
          this.emit('open')
        }
        return false
      } else {
        this.parent.selectInput(this)
      }
    } else if (button === 'right') {
      this.parent.selectInput(this)
      this.emit('menu', this)
      return false
    }
  }

  writeStatus(writable) {
    if (this.isGroup) {
      // The ANSI attributes here will apply to the rest of the line, too.
      // (We don't reset the active attributes until after drawing the rest of
      // the line.)
      if (this.isMarked) {
        writable.write(ansi.setAttributes([ansi.C_BLUE + 10]))
      } else {
        writable.write(ansi.setAttributes([ansi.C_BLUE, ansi.A_BRIGHT]))
      }
    } else if (this.isTrack) {
      if (this.isMarked) {
        writable.write(ansi.setAttributes([ansi.C_WHITE + 10, ansi.C_BLACK, ansi.A_BRIGHT]))
      }
    } else if (!this.isPlayable) {
      if (this.isMarked) {
        writable.write(ansi.setAttributes([ansi.C_WHITE + 10, ansi.C_BLACK, ansi.A_BRIGHT]))
      } else {
        writable.write(ansi.setAttributes([ansi.A_DIM]))
      }
    }

    this.drawX += 3

    const braille = '⠈⠐⠠⠄⠂⠁'
    const brailleChar = braille[Math.floor(Date.now() / 250) % 6]

    const record = this.app.backend.getRecordFor(this.item)

    if (this.isMarked) {
      writable.write('>')
    } else {
      writable.write(' ')
    }

    if (this.isGroup) {
      writable.write('G')
    } else if (!this.isPlayable) {
      writable.write('F')
    } else if (record.downloading) {
      writable.write(braille[Math.floor(Date.now() / 250) % 6])
    } else if (this.app.SQP.playingTrack === this.item) {
      writable.write('\u25B6')
    } else {
      writable.write(' ')
    }

    writable.write(' ')
  }

  get isMarked() {
    return this.app.markGrouplike.items.includes(this.item)
  }

  get isGroup() {
    return isGroup(this.item)
  }

  get isTrack() {
    return isTrack(this.item)
  }

  get isPlayable() {
    return isPlayable(this.item)
  }
}

class ListingJumpElement extends Form {
  constructor() {
    super()

    this.label = new Label('Jump to: ')
    this.addChild(this.label)

    this.input = new TextInput()
    this.addInput(this.input)

    this.input.on('confirm', value => this.emit('confirm', value))
    this.input.on('change', value => this.emit('change', value))
    this.input.on('cancel', () => this.emit('cancel'))
  }

  selected() {
    this.input.value = ''
    this.input.keepCursorInRange()
    this.root.select(this.input)
  }

  fixLayout() {
    this.input.x = this.label.right
    this.input.w = this.contentW - this.input.x
  }

  keyPressed(keyBuf) {
    const val = super.keyPressed(keyBuf)
    if (typeof val !== 'undefined') {
      return val
    }

    // Don't bubble escape.
    if (telc.isEscape(keyBuf)) {
      return false
    }
  }
}

class PathElement extends ListScrollForm {
  constructor() {
    // TODO: Once we've got the horizontal scrollbar draw working, perhaps
    // enable this? Well probably not. This is more a TODO to just, well,
    // implement that horizontal scrollbar drawing anyway.
    super('horizontal', false)
    this.captureTab = false
  }

  showItem(item) {
    while (this.inputs.length) {
      this.removeInput(this.inputs[0])
    }

    if (!item) {
      return
    }

    const itemPath = getItemPath(item)
    const parentPath = itemPath.slice(0, -1)

    for (const pathItem of parentPath) {
      const isFirst = pathItem === parentPath[0]
      const element = new PathItemElement(pathItem, isFirst)
      element.on('select', () => this.emit('select', pathItem))
      element.fixLayout()
      this.addInput(element)
    }

    this.curIndex = this.inputs.length - 1

    this.scrollToEnd()
    this.fixLayout()
  }
}

class PathItemElement extends FocusElement {
  constructor(item, isFirst) {
    super()

    this.item = item
    this.isFirst = isFirst

    this.arrowLabel = new Label(isFirst ? 'In: ' : ' > ')
    this.addChild(this.arrowLabel)

    this.button = new Button(item.name || '(Unnamed)')
    this.addChild(this.button)

    this.button.on('pressed', () => {
      this.emit('select')
    })
  }

  selected() {
    this.root.select(this.button)
  }

  clicked(button) {
    if (button === 'left') {
      this.emit('select')
    }
  }

  fixLayout() {
    const text = this.item.name || '(Unnamed)'

    const maxWidth = this.parent ? this.parent.contentW : Infinity
    this.arrowLabel.fixLayout()

    const maxButtonWidth = maxWidth - this.arrowLabel.w

    if (text.length > maxButtonWidth) {
      this.button.text = unic.ELLIPSIS + text.slice(-(maxButtonWidth - 1))
    } else {
      this.button.text = text
    }

    this.button.fixLayout()

    this.w = this.button.w + this.arrowLabel.w
    this.button.x = this.arrowLabel.right
    this.h = 1
  }
}

class QueueListingElement extends GrouplikeListingElement {
  getNewForm() {
    return new QueueListingForm(this.app)
  }

  keyPressed(keyBuf) {
    if (input.isShuffleQueue(keyBuf)) {
      this.emit('shuffle')
    } else if (input.isClearQueue(keyBuf)) {
      this.emit('clear')
    } else {
      return super.keyPressed(keyBuf)
    }
  }
}

class QueueListingForm extends GrouplikeListingForm {
  updateSelectedElement() {
    if (this.inputs.length) {
      super.updateSelectedElement()
    } else {
      this.emit('select main listing')
    }
  }
}

class PlaybackInfoElement extends FocusElement {
  constructor(queuePlayer, app) {
    super()

    this.queuePlayer = queuePlayer
    this.app = app

    this.displayMode = 'expanded'
    this.timeData = {}

    this.queuePlayerIndex = 0
    this.queuePlayerSelected = false

    this.progressBarLabel = new Label('')
    this.addChild(this.progressBarLabel)

    this.progressTextLabel = new Label('')
    this.addChild(this.progressTextLabel)

    this.trackNameLabel = new Label('')
    this.addChild(this.trackNameLabel)

    this.downloadLabel = new Label('')
    this.addChild(this.downloadLabel)

    this.queuePlayerIndexLabel = new Label('')
    this.addChild(this.queuePlayerIndexLabel)

    this.updateTrack()
    this.updateProgress()
  }

  fixLayout() {
    this.refreshProgressText()
    if (this.displayMode === 'expanded') {
      this.fixLayoutExpanded()
    } else if (this.displayMode === 'collapsed') {
      this.fixLayoutCollapsed()
    }
  }

  fixLayoutExpanded() {
    if (this.parent) {
      this.fillParent()
    }

    this.queuePlayerIndexLabel.visible = false
    this.downloadLabel.visible = true

    this.trackNameLabel.y = 0
    this.progressBarLabel.y = 1
    this.progressTextLabel.y = this.progressBarLabel.y
    this.downloadLabel.y = 2

    if (this.currentTrack) {
      const dl = this.currentTrack.downloaderArg
      let dlText = dl.slice(Math.max(dl.length - this.w + 20, 0))
      if (dlText !== dl) {
        dlText = unic.ELLIPSIS + dlText
      }
      this.downloadLabel.text = `(From: ${dlText})`
    }

    for (const el of [
      this.progressTextLabel,
      this.trackNameLabel,
      this.downloadLabel
    ]) {
      el.x = Math.round((this.w - el.w) / 2)
    }
  }

  fixLayoutCollapsed() {
    if (this.parent) {
      this.w = Math.max(30, this.parent.contentW)
    }
    this.h = 1

    this.queuePlayerIndexLabel.visible = true
    this.downloadLabel.visible = false

    const why = this.app.willActOnQueuePlayer(this.queuePlayer)
    const index = this.app.backend.queuePlayers.indexOf(this.queuePlayer)
    const msg = (why ? '!' : ' ') + index

    this.queuePlayerIndexLabel.text = (this.app.SQP === this.queuePlayer
      ? `<${msg}>`
      : ` ${msg} `)

    if (why === 'marked') {
      this.queuePlayerIndexLabel.textAttributes = [ansi.A_BRIGHT]
    } else {
      this.queuePlayerIndexLabel.textAttributes = []
    }

    this.queuePlayerIndexLabel.x = 1
    this.queuePlayerIndexLabel.y = 0

    this.trackNameLabel.x = this.queuePlayerIndexLabel.right + 1
    this.trackNameLabel.y = 0

    this.progressBarLabel.y = 0
    this.progressBarLabel.x = 0

    this.progressTextLabel.x = this.contentW - this.progressTextLabel.w - 1
    this.progressTextLabel.y = 0

    this.refreshTrackText(this.progressTextLabel.x - 2 - this.trackNameLabel.x)
    this.refreshProgressText()
  }

  clicked(button) {
    if (button === 'scroll-up') {
      this.emit('seek back')
    } else if (button === 'scroll-down') {
      this.emit('seek ahead')
    } else if (button === 'left') {
      if (this.displayMode === 'expanded') {
        this.emit('toggle pause')
      } else if (this.isSelected) {
        this.showMenu()
      } else {
        this.root.select(this)
      }
    }
  }

  keyPressed(keyBuf) {
    if (input.isSelect(keyBuf)) {
      this.showMenu()
      return false
    }
  }

  showMenu() {
    const fn = this.showContextMenu || this.app.showContextMenu
    fn({
      x: this.absLeft,
      y: this.absTop + 1,
      items: [
        {
          label: 'Select',
          action: () => {
            this.app.selectQueuePlayer(this.queuePlayer)
            this.parent.fixLayout()
          }
        },
        {
          label: (this.app.willActOnQueuePlayer(this.queuePlayer) === 'marked'
            ? 'Remove from multiple-player selection'
            : 'Add to multiple-player selection'),
          action: () => {
            this.app.toggleActOnQueuePlayer(this.queuePlayer)
            this.parent.fixLayout()
          }
        },
        this.app.backend.queuePlayers.length > 1 && {
          label: 'Delete',
          action: () => {
            const { parent } = this
            this.app.removeQueuePlayer(this.queuePlayer)
            if (parent) {
              parent.removeInput(this)
              parent.fixLayout()
              // uhhh for some reason this selects the app instead of the form
              // for all the PIEs? not sure why but it probably has to do with
              // context menu shenanigans. it's currently 29:50 and i am really
              // definitely not going to try to figure that out right now!
              parent.root.select(parent)
            }
          }
        }
      ]
    })
  }

  refreshProgressText() {
    const { player, timeData } = this.queuePlayer
    if (!timeData) {
      return
    }

    const { timeDone, duration, lenSecTotal, curSecTotal } = timeData
    this.timeData = timeData
    this.curSecTotal = curSecTotal
    this.lenSecTotal = lenSecTotal
    this.volume = player.volume
    this.isLooping = player.isLooping
    this.isPaused = player.isPaused

    this.progressBarLabel.text = '-'.repeat(Math.floor(this.w / lenSecTotal * curSecTotal))
    this.progressTextLabel.text = timeDone + ' / ' + duration
    if (player.isLooping) {
      this.progressTextLabel.text += ' [Looping]'
    }
    if (player.volume !== 100) {
      this.progressTextLabel.text += ` [Volume: ${Math.round(player.volume)}%]`
    }
  }

  refreshTrackText(maxNameWidth = Infinity) {
    const { playingTrack } = this.queuePlayer
    if (playingTrack) {
      this.currentTrack = playingTrack
      const { name } = playingTrack
      if (ansi.measureColumns(name) > maxNameWidth) {
        this.trackNameLabel.text = ansi.trimToColumns(name, maxNameWidth) + unic.ELLIPSIS
      } else {
        this.trackNameLabel.text = playingTrack.name
      }
      this.progressBarLabel.text = ''
      this.progressTextLabel.text = '(Starting..)'
      this.timeData = {}
    } else {
      this.clearInfoText()
    }
  }

  clearInfoText() {
    this.currentTrack = null
    this.progressBarLabel.text = ''
    this.progressTextLabel.text = ''
    this.trackNameLabel.text = ''
    this.downloadLabel.text = ''
    this.timeData = {}
  }

  updateProgress() {
    this.refreshProgressText()
    this.fixLayout()
  }

  updateTrack() {
    this.refreshTrackText()
    this.fixLayout()
  }

  clearInfo() {
    this.clearInfoText()
    this.fixLayout()
  }

  drawTo(writable) {
    if (this.isSelected) {
      this.progressBarLabel.textAttributes = [ansi.A_INVERT]
    } else {
      this.progressBarLabel.textAttributes = []
    }

    if (this.isSelected) {
      writable.write(ansi.invert())
      writable.write(ansi.moveCursor(this.absTop, this.absLeft))
      writable.write(' '.repeat(this.w))
    }
  }

  get curSecTotal() { return this.getDep('curSecTotal') }
  set curSecTotal(v) { return this.setDep('curSecTotal', v) }
  get lenSecTotal() { return this.getDep('lenSecTotal') }
  set lenSecTotal(v) { return this.setDep('lenSecTotal', v) }
  get volume() { return this.getDep('volume') }
  set volume(v) { return this.setDep('volume', v) }
  get isLooping() { return this.getDep('isLooping') }
  set isLooping(v) { return this.setDep('isLooping', v) }
  get isPaused() { return this.getDep('isPaused') }
  set isPaused(v) { return this.setDep('isPaused', v) }
  get currentTrack() { return this.getDep('currentTrack') }
  set currentTrack(v) { return this.setDep('currentTrack', v) }
}

class OpenPlaylistDialog extends Dialog {
  constructor() {
    super()

    this.label = new Label('Enter a playlist source:')
    this.pane.addChild(this.label)

    this.form = new Form()
    this.pane.addChild(this.form)

    this.input = new TextInput()
    this.form.addInput(this.input)

    this.button = new Button('Open')
    this.form.addInput(this.button)

    this.buttonNewTab = new Button('..in New Tab')
    this.form.addInput(this.buttonNewTab)

    this.button.on('pressed', () => {
      if (this.input.value) {
        this.emit('source selected', this.input.value)
      }
    })

    this.buttonNewTab.on('pressed', () => {
      if (this.input.value) {
        this.emit('source selected (new tab)', this.input.value)
      }
    })
  }

  opened() {
    this.input.setValue('')
    this.form.curIndex = 0
    this.form.updateSelectedElement()
  }

  fixLayout() {
    super.fixLayout()

    this.pane.w = Math.min(60, this.contentW)
    this.pane.h = 6
    this.pane.centerInParent()

    this.label.centerInParent()
    this.label.y = 0

    this.form.w = this.pane.contentW
    this.form.h = 2
    this.form.y = 1

    this.input.w = this.form.contentW

    this.button.centerInParent()
    this.button.y = 1

    this.buttonNewTab.centerInParent()
    this.buttonNewTab.y = 2
  }

  selected() {
    this.root.select(this.form)
  }
}

class AlertDialog extends Dialog {
  constructor() {
    super()

    this.label = new Label()
    this.pane.addChild(this.label)

    this.button = new Button('Close')
    this.button.on('pressed', () => {
      if (this.canClose) {
        this.emit('cancelled')
      }
    })
    this.pane.addChild(this.button)
  }

  selected() {
    this.root.select(this.button)
  }

  showMessage(message, canClose = true) {
    this.canClose = canClose
    this.label.text = message
    this.button.text = canClose ? 'Close' : '(Hold on...)'
    this.open()
  }

  fixLayout() {
    super.fixLayout()

    this.pane.w = Math.min(this.label.w + 4, this.contentW)
    this.pane.h = 4
    this.pane.centerInParent()

    this.label.centerInParent()
    this.label.y = 0

    this.button.fixLayout()
    this.button.centerInParent()
    this.button.y = 1
  }

  keyPressed() {
    // Don't handle the escape key.
  }
}

class Tabber extends FocusElement {
  constructor() {
    super()

    this.tabberElements = []
    this.currentElementIndex = 0

    this.listElement = new TabberList(this)
    this.addChild(this.listElement)

    this.listElement.on('selected', item => this.selectTab(item))
    this.listElement.on('next tab', () => this.nextTab())
    this.listElement.on('previous tab', () => this.previousTab())
  }

  fixLayout() {
    const el = this.currentElement
    if (el) {
      // Only make space for the tab list if there's more than one tab visible.
      // (The tab list isn't shown if there's only one.)
      if (this.tabberElements.length > 1) {
        el.w = this.contentW
        el.h = this.contentH - 1
        el.x = 0
        el.y = 1
      } else {
        el.fillParent()
        el.x = 0
        el.y = 0
      }
      el.fixLayout()
    }

    if (this.tabberElements.length > 1) {
      this.listElement.visible = true
      this.listElement.w = this.contentW
      this.listElement.h = 1
      this.listElement.fixLayout()
    } else {
      this.listElement.visible = false
    }
  }

  addTab(element, index = this.currentElementIndex) {
    element.visible = false
    this.tabberElements.splice(index + 1, 0, element)
    this.addChild(element, index + 1)
    this.listElement.buildItems()
  }

  nextTab() {
    this.currentElementIndex++
    if (this.currentElementIndex >= this.tabberElements.length) {
      this.currentElementIndex = 0
    }
    this.updateVisibleElement()
  }

  previousTab() {
    this.currentElementIndex--
    if (this.currentElementIndex < 0) {
      this.currentElementIndex = this.tabberElements.length - 1
    }
    this.updateVisibleElement()
  }

  selectTab(element) {
    if (!this.tabberElements.includes(element)) {
      throw new Error('That tab does not exist! (Perhaps it was removed, somehow, or was never added?)')
    }

    this.currentElementIndex = this.tabberElements.indexOf(element)
    this.updateVisibleElement()
  }

  closeTab(element) {
    if (!this.tabberElements.includes(element)) {
      return
    }

    const index = this.tabberElements.indexOf(element)
    this.tabberElements.splice(index, 1)
    if (index <= this.currentElementIndex) {
      this.currentElementIndex--
    }

    // Deliberately update the visible element before removing the child. If we
    // remove the child first, the isSelected in updateVisibleElement will be
    // false, so the new currentElement won't actually be root.select()'ed.
    this.updateVisibleElement()
    this.removeChild(element)
    this.listElement.buildItems()
  }

  updateVisibleElement() {
    const len = this.tabberElements.length - 1
    this.currentElementIndex = Math.min(len, Math.max(0, this.currentElementIndex))

    this.tabberElements.forEach((el, i) => {
      el.visible = (i === this.currentElementIndex)
    })

    if (this.isSelected) {
      if (this.currentElement) {
        this.root.select(this.currentElement)
      } else {
        this.root.select(this)
      }
    }

    this.fixLayout()
  }

  selected() {
    if (this.currentElement) {
      this.root.select(this.currentElement)
    }
  }

  get selectable() {
    return this.currentElement && this.currentElement.selectable
  }

  get currentElement() {
    return this.tabberElements[this.currentElementIndex] || null
  }
}

class TabberList extends ListScrollForm {
  constructor(tabber) {
    super('horizontal')
    this.tabber = tabber
    this.captureTab = false
  }

  buildItems() {
    while (this.inputs.length) {
      this.removeInput(this.inputs[0])
    }

    for (const item of this.tabber.tabberElements) {
      const element = new TabberListItem(item, this.tabber)
      this.addInput(element)
      element.fixLayout()
      element.on('selected', () => this.emit('selected', item))
    }

    this.scrollToEnd()
    this.fixLayout()
  }

  fixLayout() {
    this.w = this.parent.contentW
    this.h = 1
    this.x = 0
    this.y = 0
    this.scrollElementIntoEndOfView(this.inputs[this.curIndex])
    super.fixLayout()
  }

  drawTo() {
    let changed = false
    for (const input of this.inputs) {
      input.fixLayout()
      if (input._oldW !== input.w) {
        input._oldW = input.w
        changed = true
      }
    }
    if (changed) {
      this.fixLayout()
    }
  }

  clicked(button) {
    if (button === 'scroll-up') {
      this.emit('previous tab')
      return false
    } else if (button === 'scroll-down') {
      this.emit('next tab')
      return false
    }
  }

  // TODO: Be less hacky about these! Right now the tabber list is totally not
  // interactive.
  get curIndex() { return this.tabber.currentElementIndex }
  set curIndex(newVal) {}
}

class TabberListItem extends FocusElement {
  constructor(tab, tabber) {
    super()

    this.tab = tab
    this.tabber = tabber
  }

  fixLayout() {
    this.w = ansi.measureColumns(this.text) + 3
    this.h = 1
  }

  drawTo(writable) {
    if (this.tabber.currentElement === this.tab) {
      writable.write(ansi.setAttributes([ansi.A_BRIGHT]))
      writable.write(ansi.moveCursor(this.absTop, this.absLeft))
      writable.write('<' + this.text + '>')
      writable.write(ansi.resetAttributes())
    } else {
      writable.write(ansi.moveCursor(this.absTop, this.absLeft + 1))
      writable.write(this.text)
    }
  }

  clicked(button) {
    if (button === 'left') {
      this.emit('selected')
      return false
    }
  }

  get text() {
    return this.tab.tabberLabel || 'a(n) ' + this.tab.constructor.name
  }
}

class ContextMenu extends FocusElement {
  constructor(showContextMenu) {
    super()

    this.pane = new Pane()
    this.addChild(this.pane)

    this.form = new ListScrollForm()
    this.pane.addChild(this.form)

    this.keyboardSelector = new KeyboardSelector(this.form)

    this.visible = false

    this.showContextMenu = showContextMenu
    this.showSubmenu = this.showSubmenu.bind(this)
    this.submenu = null
  }

  show({x = 0, y = 0, items}) {
    items = items.filter(Boolean)
    if (!items.length) {
      return
    }

    if (!this.root.selectedElement.directAncestors.includes(this)) {
      this.selectedBefore = this.root.selectedElement
    }

    this.clearItems()

    this.x = x
    this.y = y
    this.visible = true

    // This code is so that we don't show two dividers beside each other, or
    // end a menu with a divider!
    let wantDivider = false
    const addDividerIfWanted = () => {
      if (wantDivider) {
        const element = new HorizontalRule()
        this.form.addInput(element)
        wantDivider = false
      }
    }

    for (const item of items.filter(Boolean)) {
      if (item.element) {
        addDividerIfWanted()
        this.form.addInput(item.element)
        item.element.showContextMenu = this.showSubmenu
        if (item.isDefault) {
          this.root.select(item.element)
        }
      } else if (item.divider) {
        wantDivider = true
      } else {
        addDividerIfWanted()
        const button = new Button(item.label)
        button.keyboardIdentifier = item.keyboardIdentifier || item.label
        if (item.action) {
          button.on('pressed', () => {
            this.close()
            item.action()
          })
        }
        this.form.addInput(button)
        if (item.isDefault) {
          this.root.select(button)
        }
      }
    }

    this.fixLayout()

    if (!items.some(item => item.isDefault)) {
      this.form.firstInput()
    }

    this.keyboardSelector.reset()
  }

  showSubmenu(opts) {
    this.showContextMenu(Object.assign({}, opts, {
      // We need to get a reference to the submenu before it is shown, or else
      // the parent menu will be closed (from being unselected and not knowing
      // that a submenu was just opened).
      beforeShowing: menu => {
        this.submenu = menu
      }
    }))

    this.submenu.on('close', () => {
      this.submenu = null
    })
  }

  keyPressed(keyBuf) {
    if (telc.isEscape(keyBuf) || telc.isBackspace(keyBuf)) {
      this.close()
      return false
    } else if (this.keyboardSelector.keyPressed(keyBuf)) {
      return false
    } else if (input.isScrollToStart(keyBuf)) {
      this.form.firstInput()
      this.form.scrollToBeginning()
    } else if (input.isScrollToEnd(keyBuf)) {
      this.form.lastInput()
    } else {
      return super.keyPressed(keyBuf)
    }
  }

  unselected() {
    // Don't close if we just opened a submenu!
    const newEl = this.root.selectedElement
    if (this.submenu && newEl.directAncestors.includes(this.submenu)) {
      return
    }

    if (this.visible) {
      const newlySelected = this.root.selectedElement
      this.close()
      this.selectedBefore.root.select(newlySelected)
    }
  }

  close() {
    this.clearItems()
    this.visible = false
    this.selectedBefore.root.select(this.selectedBefore)
    this.parent.removeChild(this)
    this.emit('closed')
  }

  clearItems() {
    // Abhorrent hack - just erases children from memory. Leaves children
    // thinking they've still got a parent, though. (Necessary to avoid crazy
    // select() loops that probably explode the world... speaking of things
    // to forget, that one time when I was figuring out menus in the queue.
    // This makes them work.)
    this.form.children = this.form.children.filter(
      child => !this.form.inputs.includes(child))
    this.form.inputs = []
  }

  fixLayout() {
    // Do an initial pass to determine the width of this menu (or in particular
    // the form), which is the greatest width of all the inputs.
    let width = 10

    // Some elements resize to fill their parent (the menu)'s width. Since we
    // want to know what their *minimum* width is, we'll immediately change the
    // parent width that they see.
    this.form.w = width

    for (const input of this.form.inputs) {
      input.fixLayout()
      width = Math.max(width, input.w)
    }

    let height = Math.min(14, this.form.inputs.length)

    width += 2 // Space for the pane border
    height += 2 // Space for the pane border
    if (this.form.scrollBarShown) width++
    this.w = width
    this.h = height

    this.fitToParent()

    this.pane.fillParent()
    this.form.fillParent()
    this.form.fixLayout()

    // After everything else, do a second pass to apply the decided width
    // to every element, so that they expand to all be the same width.
    // In order to change the width of a button (which is what these elements
    // are), we need to append space characters.
    for (const input of this.form.inputs) {
      input.fixLayout()
      if (input.text) {
        const inputWidth = ansi.measureColumns(input.text)
        if (inputWidth < this.form.contentW) {
          input.text += ' '.repeat(this.form.contentW - inputWidth)
        }
      }
    }
  }

  selected() {
    this.root.select(this.form)
  }
}

class HorizontalRule extends FocusElement {
  // It's just a horizontal rule. Y'know..
  // --------------------------------------------------------------------------
  // You get the idea. :)

  get selectable() {
    // Just return false. A HorizontalRule is technically a FocusElement,
    // but that's just so that it can be used in place of other inputs
    // (e.g. in a ContextMenu).
    return false
  }

  fixLayout() {
    this.w = this.parent.contentW
    this.h = 1
  }

  drawTo(writable) {
    // For the character we draw with, we use an ordinary dash instead of
    // an actual box-drawing horizontal line. That's so that the rule is
    // distinguishable from the edge of a Pane.
    writable.write(ansi.moveCursor(this.absTop, this.absLeft))
    writable.write('-'.repeat(this.w))
  }
}

class KeyboardSelector {
  // Class used to select things when you type out their name. Specify strings
  // used to access each element of a form in the keyboardIdentifier property.
  // (Elements without a keyboardIdentifier, or which are !selectable, will be
  // skipped.)

  constructor(form) {
    this.value = ''
    this.form = form
  }

  reset() {
    this.value = ''
  }

  keyPressed(keyBuf) {
    // Don't do anything if the input isn't a single keyboard character.
    if (keyBuf.length !== 1 || keyBuf[0] <= 31 || keyBuf[0] >= 127) {
      return
    }

    // First see if a result is found when we append the typed character to our
    // recorded input.
    const char = keyBuf.toString()
    this.value += char
    if (!KeyboardSelector.find(this.value, this.form)) {
      // If we don't find a result, replace our recorded input with the single
      // character entered, then do a search. Start from the input after the
      // current-selected one, so that we don't just end up re-selecting the
      // element that was selected before, if there's another option that would
      // match this key ahead. (This is so that you can easily type a string or
      // character over and over to navigate through options that all start
      // with the same string/character.)
      this.value = char
      return KeyboardSelector.find(this.value, this.form, this.form.curIndex + 1)
    }
    return true
  }

  static find(text, form, fromIndex = form.curIndex) {
    // Most of this code is just stolen from AppElement's code for handling
    // input from JumpElement!

    const lower = text.toLowerCase()
    const getName = inp => inp.keyboardIdentifier ? inp.keyboardIdentifier.toLowerCase().trim() : ''

    const testStartsWith = inp => getName(inp).startsWith(lower)

    const searchPastCurrentIndex = test => {
      const start = fromIndex
      const match = form.inputs.slice(start).findIndex(test)
      if (match === -1) {
        return -1
      } else {
        return start + match
      }
    }

    const allIndexes = [
      searchPastCurrentIndex(testStartsWith),
      form.inputs.findIndex(testStartsWith),
    ]

    const matchedIndex = allIndexes.find(value => value >= 0)

    if (typeof matchedIndex !== 'undefined') {
      form.selectInput(form.inputs[matchedIndex])
      return true
    } else {
      return false
    }
  }
}

class Menubar extends ListScrollForm {
  constructor(showContextMenu) {
    super('horizontal')

    this.showContextMenu = showContextMenu
    this.contextMenu = null
    this.color = 4 // blue
    this.attribute = 2 // dim

    this.keyboardSelector = new KeyboardSelector(this)
  }

  select() {
    // When the menubar is selected from the menubar's context menu, the UI
    // looks like it's "popping" a state, so don't reset the selected index to
    // the start - something we only do when we "newly" select the menubar.
    if (this.contextMenu && this.contextMenu.isSelected) {
      this.root.select(this)
    } else {
      this.selectedBefore = this.root.selectedElement
      this.firstInput()
    }

    this.keyboardSelector.reset()
  }

  keyPressed(keyBuf) {
    super.keyPressed(keyBuf)

    // Don't pause the music from the menubar!
    if (telc.isSpace(keyBuf)) {
      return false
    }

    if (this.keyboardSelector.keyPressed(keyBuf)) {
      return false
    } else if (telc.isCaselessLetter(keyBuf, 'c')) {
      // For fun :)
      this.color = (this.color % 8) + 1
      return false
    } else if (telc.isCaselessLetter(keyBuf, 'a')) {
      this.attribute = (this.attribute % 3) + 1
      return false
    }
  }

  restoreSelection() {
    if (this.selectedBefore) {
      this.root.select(this.selectedBefore)
      this.selectedBefore = null
    }
  }

  buildItems(array) {
    for (const {text, menuItems, menuFn} of array) {
      const button = new Button(` ${text} `)

      const container = new FocusElement()
      container.addChild(button)
      button.x = 1
      container.w = button.w + 2
      container.h = 1
      container.selected = () => this.root.select(button)
      container.keyboardIdentifier = text

      button.on('pressed', () => {
        this.contextMenu = this.showContextMenu({
          x: container.absLeft, y: container.absY + 1,
          items: menuFn ? menuFn() : menuItems
        })
        this.contextMenu.on('closed', () => {
          this.contextMenu = null
        })
      })

      this.addInput(container)
    }
  }

  fixLayout() {
    this.x = 0
    this.y = 0
    this.w = this.parent.contentW
    this.h = 1
    super.fixLayout()
  }

  drawTo(writable) {
    writable.write(ansi.moveCursor(this.absTop, this.absLeft))
    writable.write(ansi.setAttributes([this.attribute, 30 + this.color, ansi.A_INVERT, ansi.C_WHITE + 10]))
    writable.write(' '.repeat(this.w))
    writable.write(ansi.resetAttributes())
  }

  get color() { return this.getDep('color') }
  set color(v) { return this.setDep('color', v) }
  get attribute() { return this.getDep('attribute') }
  set attribute(v) { return this.setDep('attribute', v) }
}

class PartyBanner extends DisplayElement {
  constructor(direction) {
    super()

    this.direction = direction
  }

  drawTo(writable) {
    writable.write(ansi.moveCursor(this.absTop, this.absLeft))

    // TODO: Figure out how to connect this to the draw dependency system.
    // Currently the party banner doesn't schedule any renders itself (meaning
    // if you have nothing playing or otherwise rendering, it'll just stay
    // still).
    const timerNum = Date.now() / 2000 * this.direction
    let lastAttribute = ''
    const updateAttribute = offsetNum => {
      const attr = (Math.cos(offsetNum - timerNum) < 0 ? '\x1b[0;1m' : '\x1b[0;2m')
      if (attr === lastAttribute) {
        return ''
      } else {
        lastAttribute = attr
        return attr
      }
    }
    let str = new Array(this.w).fill('0').map((_, i) => {
      const offsetNum = i / this.w * 2 * Math.PI
      return (
        updateAttribute(offsetNum) +
        (Math.sin(offsetNum + timerNum) < 0 ? '-' : '*')
      )
    }).join('')

    writable.write(str)
    writable.write(ansi.resetAttributes())
  }
}

class NotesTextEditor extends TuiTextEditor {
  constructor() {
    super()

    this.openedItem = null
  }

  keyPressed(keyBuf) {
    if (input.isDeselectTextEditor(keyBuf)) {
      this.emit('deselect')
      return false
    } else if (input.isSaveTextEditor(keyBuf)) {
      this.saveManually()
      return false
    } else {
      return super.keyPressed(keyBuf)
    }
  }

  async openItem(item, {doubleCheckItem}) {
    if (this.hasBeenEdited) {
      // Save in the background.
      this.save()
    }

    const textFile = getCorrespondingFileForItem(item, '.txt')
    if (!textFile) {
      this.openedItem = null
      return false
    }

    if (textFile === this.openedItem) {
      // This file is already open - don't do anything.
      return null
    }

    let filePath
    try {
      filePath = url.fileURLToPath(new URL(textFile.url))
    } catch (error) {
      this.openedItem = null
      return false
    }

    let buffer
    try {
      buffer = await readFile(filePath)
    } catch (error) {
      this.openedItem = null
      return false
    }

    if (!doubleCheckItem(item)) {
      return null
    }

    this.openedItem = textFile
    this.openedPath = filePath
    this.clearSourceAndLoadText(buffer.toString())
    return true
  }

  async saveManually() {
    if (!this.openedItem || !this.openedPath) {
      return
    }

    const item = this.openedItem

    if (await this.save()) {
      if (item === this.openedItem) {
        this.showStatusMessage('Saved manually.')
      }
    }
  }

  async save() {
    if (!this.openedItem || !this.openedPath) {
      return
    }

    const text = this.getSourceText()
    try {
      await writeFile(this.openedPath, text)
      this.clearEditStatus()
      return true
    } catch (error) {
      this.showStatusMessage(`Failed to save (${path.basename(this.openedPath)}: ${error.code}).`)
      return false
    }
  }
}

module.exports = AppElement