aboutsummaryrefslogtreecommitdiffstats
path: root/source/player/player_ui.cpp
blob: 02d970dc7610e8c839abd2b5fc2b14abf990812d (plain) (blame)
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
//- small helpers

internal b32 ui_hovered(PlatformInput *input, Rect rect)
{
	return input->mouse_in_window && rect_contains(rect, input->mouse_x, input->mouse_y);
}

internal b32 ui_clicked(PlatformInput *input, Rect rect)
{
	return ButtonPressed(input->mouse[0]) && ui_hovered(input, rect);
}

internal f32 ui_baseline(App *app, FontKind kind, f32 size, f32 y0, f32 height)
{
	f32 line   = font_line_height(&app->fonts, kind, size);
	f32 ascent = font_ascent(&app->fonts, kind, size);
	return floorf(y0 + (height - line) * 0.5f + ascent + 0.5f);
}

// NOTE: the integer cells (surah #, ayat, counts) are on every visible row every frame, and
// vsnprintf is a few hundred cycles of format parsing for them. these just emit the digits.
internal u32 ui_digits(u8 *out, u32 value)
{
	u8  buffer[10];
	u32 size = 0;
	do {
		buffer[size++] = (u8)('0' + value % 10);
		value /= 10;
	} while(value);
	for(u32 index = 0; index < size; ++index) out[index] = buffer[size - 1 - index];
	return size;
}

internal String8 ui_u32(Arena *arena, u32 value)
{
	u8 *out = PushArray(arena, u8, 10);
	return ToString8Size(out, ui_digits(out, value));
}

// "a<separator>b", like "18/114"
internal String8 ui_u32_pair(Arena *arena, u32 a, char separator, u32 b)
{
	u8 *out  = PushArray(arena, u8, 21);
	u32 size = ui_digits(out, a);
	out[size++] = (u8)separator;
	size += ui_digits(out + size, b);
	return ToString8Size(out, size);
}

internal String8 ui_format(Arena *arena, const char *format, ...)
{
	va_list args;
	va_start(args, format);
	char buffer[256];
	int  length = vsnprintf(buffer, sizeof(buffer), format, args);
	va_end(args);
	length  = Clamp(length, 0, (int)sizeof(buffer) - 1);
	u8 *out = PushArray(arena, u8, (u64)Max(length, 1));
	MemCpy(out, buffer, (u64)length);
	return ToString8Size(out, (u64)length);
}

internal void format_duration(char *out, u32 size, f64 seconds)
{
	u32 total = (u32)Max(seconds, 0.0);
	if(total >= 3600) {
		snprintf(out, size, "%u:%02u:%02u", total / 3600, (total / 60) % 60, total % 60);
	} else {
		snprintf(out, size, "%u:%02u", total / 60, total % 60);
	}
}

internal void app_message(App *app, const char *format, ...)
{
	va_list args;
	va_start(args, format);
	vsnprintf(app->message, sizeof(app->message), format, args);
	va_end(args);
	app->message_ns = time_now_ns();
}

internal b32 str8_contains_nocase(String8 haystack, const char *needle, u32 needle_size)
{
	if(needle_size == 0) return true;
	for(u64 start = 0; start + needle_size <= haystack.size; ++start) {
		u32 index = 0;
		for(; index < needle_size; ++index) {
			u8 a = haystack.data[start + index], b = (u8)needle[index];
			if(a >= 'A' && a <= 'Z') a += 32;
			if(b >= 'A' && b <= 'Z') b += 32;
			if(a != b) break;
		}
		if(index == needle_size) return true;
	}
	return false;
}

internal void scroll_update(ScrollList *scroll, f32 content, f32 view, f32 dt, b32 *animating)
{
	f32 max_offset = Max(content - view, 0.0f);
	scroll->target = Clamp(scroll->target, 0.0f, max_offset);
	f32 speed = ui_theme.scroll_speed;
	scroll->offset += (scroll->target - scroll->offset) * (speed > 0 ? 1.0f - expf(-dt * speed) : 1.0f);
	if(fabsf(scroll->target - scroll->offset) < 0.25f) {
		scroll->offset = scroll->target;
	}
	scroll->offset = Clamp(scroll->offset, 0.0f, max_offset);
	if(scroll->offset != scroll->target) *animating = true;
}

//- playback queries

internal u32 app_current_key(App *app)
{
	if(app->position.flags & PLAYBACK_HAS_TRACK) {
		return app->position.track_key;
	}
	u32 status = AtomicLoadRelaxed(&app->decoder->status);
	if(status == DECODER_BUFFERING || status == DECODER_DECODING) {
		return app->requested_key;
	}
	return TRACK_NONE;
}

internal u64 app_track_total(App *app)
{
	if(app->position.total_frames) {
		return app->position.total_frames;
	}
	if(AtomicLoadRelaxed(&app->decoder->status_key) == app_current_key(app)) {
		return AtomicLoadRelaxed(&app->decoder->published_total);
	}
	return 0;
}

internal u32 app_selected_key(App *app)
{
	if(app->qari < 0 || (u32)app->qari >= app->catalog->qari_count) return TRACK_NONE;
	return TrackKey(app->qari, app->surah);
}

//- disk summary

//- actions

internal s32  queue_find(App *app, u32 key);
internal void app_play_in_queue(App *app, u32 key);

internal void app_play(App *app, u32 key, u64 frame)
{
	if(!app->audio_ok || key == TRACK_NONE) {
		return;
	}
	app->requested_key = key;
	app->paused        = false;
	app->resume_frame  = 0;
	audio_output_set_paused(app->output, false);
	// NOTE: a plain single play ends any queue a multi selection started
	if(app->queue_count) {
		app->queue_count = 0;
		decoder_command(app->decoder, DECODER_QUEUE_CLEAR, 0, 0);
	}
	decoder_command(app->decoder, DECODER_SET_AUTOPLAY, 0, app->settings.autoplay);
	decoder_command(app->decoder, DECODER_PLAY, key, frame);

	TrackEntry *entry = store_entry(app->store, key);
	if(entry && AtomicLoadRelaxed(TrackStatePtr(app->store, entry)) != TRACK_DONE) {
		app_message(app, "streaming %u. " Str8Fmt, TrackSurah(key) + 1, Str8Arg(app->catalog->surahs[TrackSurah(key)].name));
	}
}

internal void app_toggle_pause(App *app)
{
	if(!app->audio_ok) {
		return;
	}
	if(app_current_key(app) == TRACK_NONE) {
		app_play(app, app_selected_key(app), app->resume_frame);
		return;
	}
	app->paused = !app->paused;
	if(app->paused) {
		app->paused_since_ns = time_now_ns();
	}
	audio_output_set_paused(app->output, app->paused);
}

internal void app_step_track(App *app, s32 delta)
{
	u32 key = app_current_key(app);
	if(key == TRACK_NONE) key = app_selected_key(app);
	if(key == TRACK_NONE) return;

	// NOTE: inside a queue, < and > move through the queue
	s32 at = queue_find(app, key);
	if(at >= 0) {
		s32 next = at + delta;
		if(next >= 0 && next < (s32)app->queue_count) app_play_in_queue(app, app->queue[next]);
		return;
	}

	s32 surah = (s32)TrackSurah(key);
	for(;;) {
		surah += delta;
		if(surah < 0 || surah >= SURAH_COUNT) return;
		// NOTE: when listening offline, skip what isn't on disk
		if(app->settings.autoplay != AUTOPLAY_NEXT_DOWNLOADED || store_on_disk(app->store, TrackKey(TrackQari(key), surah))) break;
	}
	app_play(app, TrackKey(TrackQari(key), surah), 0);
}

internal void app_seek_seconds(App *app, f64 delta)
{
	if(app_current_key(app) == TRACK_NONE || app->position.rate == 0) {
		return;
	}
	s64 frame = (s64)app->position.frame + (s64)(delta * app->position.rate);
	decoder_command(app->decoder, DECODER_SEEK, 0, (u64)Max(frame, (s64)0));
}

internal void app_apply_settings(App *app)
{
	settings_clamp(&app->settings);
	if(app->audio_ok) {
		audio_output_set_volume(app->output, app->settings.volume);
		decoder_command(app->decoder, DECODER_SET_AUTOPLAY, 0, app->settings.autoplay);
	}
	// NOTE: extra download workers are started by the host (player.cpp), never from here: this
	// code may live in the hot reloaded .so, and a thread running in it would crash on unload
}

internal void app_set_volume(App *app, f32 volume)
{
	app->settings.volume = Clamp(volume, 0.0f, 1.0f);
	app_apply_settings(app);
}

internal const char *autoplay_name(u32 mode)
{
	switch(mode) {
		case AUTOPLAY_OFF: return "off";
		case AUTOPLAY_NEXT: return "next surah";
		case AUTOPLAY_NEXT_DOWNLOADED: return "next downloaded";
	}
	return "?";
}

internal void app_download(App *app, u32 key)
{
	if(key == TRACK_NONE) return;
	if(store_on_disk(app->store, key)) {
		app_message(app, "already on disk");
		return;
	}
	store_request(app->store, key, true);
	app_message(app, "downloading %u. " Str8Fmt, TrackSurah(key) + 1, Str8Arg(app->catalog->surahs[TrackSurah(key)].name));
}

internal void app_delete(App *app, u32 key)
{
	if(key == TRACK_NONE) return;
	if(key == app_current_key(app)) {
		decoder_command(app->decoder, DECODER_STOP, 0, 0);
		app->requested_key = TRACK_NONE;
	}
	if(store_delete(app->store, key)) {
		app_message(app, "deleted %u. " Str8Fmt " from disk", TrackSurah(key) + 1, Str8Arg(app->catalog->surahs[TrackSurah(key)].name));
	} else {
		app_message(app, "busy downloading, try again when it's done");
	}
}

internal void app_delete_qari(App *app, u32 qari)
{
	u32 deleted = 0;
	for(u32 surah = 0; surah < SURAH_COUNT; ++surah) {
		u32 key = TrackKey(qari, surah);
		if(store_on_disk(app->store, key)) {
			if(key == app_current_key(app)) decoder_command(app->decoder, DECODER_STOP, 0, 0);
			deleted += store_delete(app->store, key);
		}
	}
	app_message(app, "deleted %u surahs of " Str8Fmt, deleted, Str8Arg(app->catalog->qaris[qari].name));
}

internal UIPlace app_place(App *app)
{
	UIPlace place = {};
	if(app->qari >= 0) {
		place.qari_id = app->catalog->qaris[app->qari].id;
		place.surah   = (u32)app->surah;
	}
	return place;
}

internal void app_goto_place(App *app, UIPlace place)
{
	s32 qari = catalog_find_qari_by_id(app->catalog, place.qari_id);
	if(qari < 0) {
		app_message(app, "mark not set");
		return;
	}
	app->jump_back              = app_place(app);
	app->qari                   = qari;
	app->surah                  = (s32)Min(place.surah, (u32)SURAH_COUNT - 1);
	app->keep_selection_visible = true;
}

//- layout pool

internal s32 layout_alloc_panel(Layout *layout)
{
	for(s32 index = 0; index < UI_MAX_PANELS; ++index) {
		if(layout->panels[index].kind == PANEL_FREE) {
			MemSetZero(&layout->panels[index], sizeof(Panel));
			layout->panels[index].kind   = PANEL_LEAF; // reserved right away, callers retype it
			layout->panels[index].parent = -1;
			return index;
		}
	}
	return -1;
}

internal s32 layout_alloc_view(Layout *layout, ViewKind kind)
{
	for(s32 index = 0; index < UI_MAX_VIEWS; ++index) {
		if(layout->views[index].kind == VIEW_NONE) {
			MemSetZero(&layout->views[index], sizeof(View));
			layout->views[index].kind = (u32)kind;
			return index;
		}
	}
	return -1;
}

internal s32 layout_leaf(Layout *layout, s32 parent, ViewKind *kinds, u32 count)
{
	s32    panel = layout_alloc_panel(layout);
	Panel *p     = &layout->panels[panel];
	p->kind      = PANEL_LEAF;
	p->parent    = parent;
	for(u32 index = 0; index < count && p->tab_count < UI_MAX_TABS; ++index) {
		s32 view = layout_alloc_view(layout, kinds[index]);
		if(view >= 0) p->tabs[p->tab_count++] = (u8)view;
	}
	return panel;
}

internal s32 layout_split(Layout *layout, s32 parent, u32 axis, f32 ratio)
{
	s32    panel = layout_alloc_panel(layout);
	Panel *p     = &layout->panels[panel];
	p->kind      = PANEL_SPLIT;
	p->parent    = parent;
	p->axis      = axis;
	p->ratio     = ratio;
	return panel;
}

// NOTE: the footer: the whole tree goes above a one line bar holding the status view
internal void layout_add_status_bar(Layout *layout)
{
	u32 free_panels = 0, free_views = 0;
	for(u32 index = 0; index < UI_MAX_PANELS; ++index) free_panels += (layout->panels[index].kind == PANEL_FREE);
	for(u32 index = 0; index < UI_MAX_VIEWS; ++index) free_views += (layout->views[index].kind == VIEW_NONE);
	if(free_panels < 2 || free_views < 1) return;

	ViewKind kinds[] = {VIEW_STATUS};
	s32 old_root     = layout->root;
	s32 split        = layout_split(layout, -1, 1, -1.0f);
	s32 bar          = layout_leaf(layout, split, kinds, 1);
	layout->panels[split].children[0] = old_root;
	layout->panels[split].children[1] = bar;
	layout->panels[old_root].parent   = split;
	layout->root                      = split;
}

// NOTE: version 2 layouts had the footer drawn outside the tree: keep the arrangement, add the bar
internal void layout_migrate(Layout *layout)
{
	if(layout->version != 2 || layout->root < 0 || layout->root >= UI_MAX_PANELS) return;
	layout->version = UI_LAYOUT_VERSION;
	layout_add_status_bar(layout);
}

internal void ui_layout_default(Layout *layout)
{
	MemSetZero(layout, sizeof(*layout));
	layout->version = UI_LAYOUT_VERSION;

	// [ reciters | offline ] | [ surahs ] / [ playing | downloads | settings ]
	ViewKind left_kinds[]   = {VIEW_RECITERS, VIEW_OFFLINE};
	ViewKind top_kinds[]    = {VIEW_SURAHS};
	ViewKind bottom_kinds[] = {VIEW_PLAYING, VIEW_QUEUE, VIEW_DOWNLOADS, VIEW_VIEWS};

	s32 root   = layout_split(layout, -1, 0, 0.32f);
	s32 left   = layout_leaf(layout, root, left_kinds, ArrayCount(left_kinds));
	s32 right  = layout_split(layout, root, 1, 0.68f);
	s32 top    = layout_leaf(layout, right, top_kinds, ArrayCount(top_kinds));
	s32 bottom = layout_leaf(layout, right, bottom_kinds, ArrayCount(bottom_kinds));

	layout->panels[root].children[0]  = left;
	layout->panels[root].children[1]  = right;
	layout->panels[right].children[0] = top;
	layout->panels[right].children[1] = bottom;
	layout->root                      = root;
	layout->focused                   = left;
	layout_add_status_bar(layout);
}

// NOTE: a saved layout is trusted only if every index it holds is in range and consistent
internal b32 layout_valid(Layout *layout)
{
	if(layout->version != UI_LAYOUT_VERSION || layout->root < 0 || layout->root >= UI_MAX_PANELS) return false;
	if(layout->panels[layout->root].kind == PANEL_FREE) return false;
	for(s32 index = 0; index < UI_MAX_PANELS; ++index) {
		Panel *p = &layout->panels[index];
		if(p->kind == PANEL_SPLIT) {
			for(u32 c = 0; c < 2; ++c) {
				s32 child = p->children[c];
				if(child < 0 || child >= UI_MAX_PANELS || layout->panels[child].kind == PANEL_FREE || layout->panels[child].parent != index) return false;
			}
		} else if(p->kind == PANEL_LEAF) {
			if(p->tab_count > UI_MAX_TABS) return false;
			for(u32 t = 0; t < p->tab_count; ++t) {
				if(p->tabs[t] >= UI_MAX_VIEWS || layout->views[p->tabs[t]].kind == VIEW_NONE || layout->views[p->tabs[t]].kind >= VIEW_KIND_COUNT) return false;
			}
		} else if(p->kind != PANEL_FREE) {
			return false;
		}
	}
	return layout->focused >= 0 && layout->focused < UI_MAX_PANELS && layout->panels[layout->focused].kind == PANEL_LEAF;
}

internal s32 layout_first_leaf(Layout *layout, s32 panel)
{
	while(layout->panels[panel].kind == PANEL_SPLIT) panel = layout->panels[panel].children[0];
	return panel;
}

internal s32 panel_active_view(Layout *layout, s32 panel)
{
	Panel *p = &layout->panels[panel];
	if(p->kind != PANEL_LEAF || p->tab_count == 0) return -1;
	return p->tabs[Min(p->active_tab, p->tab_count - 1)];
}

// NOTE: an empty leaf disappears: its sibling takes the parent's place in the tree
internal void layout_collapse(Layout *layout, s32 leaf)
{
	Panel *p = &layout->panels[leaf];
	if(p->kind != PANEL_LEAF || p->tab_count > 0 || p->parent < 0) {
		return;
	}
	s32    parent  = p->parent;
	Panel *pp      = &layout->panels[parent];
	s32    sibling = (pp->children[0] == leaf) ? pp->children[1] : pp->children[0];
	s32    grand   = pp->parent;

	// move the sibling into the parent's slot so the grandparent's child index stays valid
	Panel moved  = layout->panels[sibling];
	moved.parent = grand;
	*pp          = moved;
	if(pp->kind == PANEL_SPLIT) {
		layout->panels[pp->children[0]].parent = parent;
		layout->panels[pp->children[1]].parent = parent;
	}
	layout->panels[sibling].kind = PANEL_FREE;
	layout->panels[leaf].kind    = PANEL_FREE;

	if(layout->focused == leaf || layout->focused == sibling || layout->panels[layout->focused].kind != PANEL_LEAF) {
		layout->focused = layout_first_leaf(layout, parent);
	}
}

internal void layout_remove_tab(Layout *layout, s32 panel, u32 tab)
{
	Panel *p = &layout->panels[panel];
	for(u32 index = tab; index + 1 < p->tab_count; ++index) p->tabs[index] = p->tabs[index + 1];
	--p->tab_count;
	if(p->active_tab >= p->tab_count && p->active_tab > 0) --p->active_tab;
}

internal void layout_close_view(Layout *layout, s32 panel, u32 tab)
{
	Panel *p = &layout->panels[panel];
	if(tab >= p->tab_count) return;
	layout->views[p->tabs[tab]].kind = VIEW_NONE;
	layout_remove_tab(layout, panel, tab);
	layout_collapse(layout, panel);
}

typedef enum DropZone {
	DROP_NONE,
	DROP_CENTER,
	DROP_LEFT,
	DROP_RIGHT,
	DROP_TOP,
	DROP_BOTTOM,
} DropZone;

// NOTE: move a view into a panel. center joins its tabs, an edge splits the panel and puts the
// view on that side. the source panel collapses if this was its last tab.
internal void layout_move_view(Layout *layout, s32 from_panel, s32 view, s32 to_panel, DropZone zone)
{
	Panel *source = &layout->panels[from_panel];
	u32    tab    = 0;
	for(; tab < source->tab_count && source->tabs[tab] != view; ++tab) {}
	if(tab == source->tab_count) return;
	if(from_panel == to_panel && (zone == DROP_CENTER || source->tab_count == 1)) return;

	if(zone == DROP_CENTER) {
		Panel *target = &layout->panels[to_panel];
		if(target->tab_count >= UI_MAX_TABS) return;
		layout_remove_tab(layout, from_panel, tab);
		target->tabs[target->tab_count] = (u8)view;
		target->active_tab              = target->tab_count++;
		layout->focused                 = to_panel;
		layout_collapse(layout, from_panel);
		return;
	}

	// NOTE: split: the target leaf's content moves into a new child, the target slot becomes the split
	s32 keep  = layout_alloc_panel(layout);
	s32 fresh = (keep >= 0) ? layout_alloc_panel(layout) : -1;
	if(keep < 0 || fresh < 0) {
		if(keep >= 0) layout->panels[keep].kind = PANEL_FREE;
		return;
	}
	layout_remove_tab(layout, from_panel, tab);

	Panel *target               = &layout->panels[to_panel];
	layout->panels[keep]        = *target;
	layout->panels[keep].parent = to_panel;

	Panel *fresh_panel     = &layout->panels[fresh];
	fresh_panel->kind      = PANEL_LEAF;
	fresh_panel->parent    = to_panel;
	fresh_panel->tabs[0]   = (u8)view;
	fresh_panel->tab_count = 1;

	b32 fresh_first     = (zone == DROP_LEFT || zone == DROP_TOP);
	target->kind        = PANEL_SPLIT;
	target->axis        = (zone == DROP_LEFT || zone == DROP_RIGHT) ? 0 : 1;
	target->ratio       = 0.5f;
	target->children[0] = fresh_first ? fresh : keep;
	target->children[1] = fresh_first ? keep : fresh;
	target->tab_count   = 0;

	// NOTE: the source may have been the target leaf, which now lives in `keep`
	s32 source_now  = (from_panel == to_panel) ? keep : from_panel;
	layout->focused = fresh;
	layout_collapse(layout, source_now);
	// collapsing can move panels around, find the new view's leaf again
	for(s32 index = 0; index < UI_MAX_PANELS; ++index) {
		Panel *p = &layout->panels[index];
		if(p->kind != PANEL_LEAF) continue;
		for(u32 t = 0; t < p->tab_count; ++t) {
			if(p->tabs[t] == view) {
				layout->focused = index;
				p->active_tab   = t;
			}
		}
	}
}

internal void layout_compute(Layout *layout, s32 panel, Rect rect)
{
	Panel *p = &layout->panels[panel];
	p->rect  = rect;
	if(p->kind != PANEL_SPLIT) return;
	f32 half = UI_GAP * 0.5f;
	if(p->axis == 0) {
		f32 split = rect.x0 + rect_w(rect) * p->ratio;
		layout_compute(layout, p->children[0], Rect{rect.x0, rect.y0, split - half, rect.y1});
		layout_compute(layout, p->children[1], Rect{split + half, rect.y0, rect.x1, rect.y1});
	} else {
		f32 split = (p->ratio < 0) ? Max(rect.y1 - half + p->ratio * UI_STATUS_H, rect.y0 + half) // bar: -ratio lines
		                           : rect.y0 + rect_h(rect) * p->ratio;
		layout_compute(layout, p->children[0], Rect{rect.x0, rect.y0, rect.x1, split - half});
		layout_compute(layout, p->children[1], Rect{rect.x0, split + half, rect.x1, rect.y1});
	}
}

internal s32 layout_find_kind(Layout *layout, ViewKind kind, s32 *out_panel, u32 group = 0)
{
	for(s32 index = 0; index < UI_MAX_PANELS; ++index) {
		Panel *p = &layout->panels[index];
		if(p->kind != PANEL_LEAF) continue;
		for(u32 t = 0; t < p->tab_count; ++t) {
			if(layout->views[p->tabs[t]].kind == (u32)kind && layout->views[p->tabs[t]].group == group) {
				if(out_panel) *out_panel = index;
				return p->tabs[t];
			}
		}
	}
	return -1;
}

// NOTE: show a view of this kind: focus an existing tab, or open a new one in the focused panel
internal void layout_open(Layout *layout, ViewKind kind, u32 group = 0)
{
	s32 panel = -1;
	s32 view  = layout_find_kind(layout, kind, &panel, group);
	if(view >= 0) {
		Panel *p = &layout->panels[panel];
		for(u32 t = 0; t < p->tab_count; ++t) if(p->tabs[t] == view) p->active_tab = t;
		layout->focused = panel;
		return;
	}
	Panel *p = &layout->panels[layout->focused];
	view     = layout_alloc_view(layout, kind);
	if(view < 0) return;
	layout->views[view].group = group;
	if(p->tab_count >= UI_MAX_TABS) { layout->views[view].kind = VIEW_NONE; return; }
	p->tabs[p->tab_count] = (u8)view;
	p->active_tab         = p->tab_count++;
}

internal void layout_split_with(Layout *layout, ViewKind kind, u32 axis, u32 group = 0)
{
	s32 copy = layout_alloc_view(layout, kind);
	if(copy < 0) return;
	layout->views[copy].group = group;
	Panel *p = &layout->panels[layout->focused];
	if(p->tab_count >= UI_MAX_TABS) { layout->views[copy].kind = VIEW_NONE; return; }
	p->tabs[p->tab_count++] = (u8)copy;
	layout_move_view(layout, layout->focused, copy, layout->focused, axis == 0 ? DROP_RIGHT : DROP_BOTTOM);
}

internal void layout_split_focused(Layout *layout, u32 axis)
{
	s32 view = panel_active_view(layout, layout->focused);
	if(view < 0) return;
	layout_split_with(layout, (ViewKind)layout->views[view].kind, axis, layout->views[view].group);
}

// NOTE: ctrl-w h j k l: the nearest leaf on that side that overlaps us on the other axis
// NOTE: a leaf drawn as a one line bar (the footer): shown, but keyboard focus passes over it
internal b32 panel_is_bar(Layout *layout, s32 panel)
{
	return rect_h(layout->panels[panel].rect) < UI_TAB_H + UI_COLUMN_H + UI_ROW_H;
}

internal void layout_focus_direction(Layout *layout, s32 dx, s32 dy)
{
	Rect current = layout->panels[layout->focused].rect;
	s32  best    = -1;
	f32  best_d  = 1e9f;
	for(s32 index = 0; index < UI_MAX_PANELS; ++index) {
		Panel *p = &layout->panels[index];
		if(p->kind != PANEL_LEAF || index == layout->focused || panel_is_bar(layout, index)) continue;
		Rect r = p->rect;
		f32  d = -1;
		if(dx > 0 && r.x0 >= current.x1 - 1 && r.y0 < current.y1 && r.y1 > current.y0) d = r.x0 - current.x1;
		if(dx < 0 && r.x1 <= current.x0 + 1 && r.y0 < current.y1 && r.y1 > current.y0) d = current.x0 - r.x1;
		if(dy > 0 && r.y0 >= current.y1 - 1 && r.x0 < current.x1 && r.x1 > current.x0) d = r.y0 - current.y1;
		if(dy < 0 && r.y1 <= current.y0 + 1 && r.x0 < current.x1 && r.x1 > current.x0) d = current.y0 - r.y1;
		if(d >= 0 && d < best_d) { best_d = d; best = index; }
	}
	if(best >= 0) layout->focused = best;
}

internal void layout_focus_next(Layout *layout)
{
	for(s32 step = 1; step <= UI_MAX_PANELS; ++step) {
		s32 index = (layout->focused + step) % UI_MAX_PANELS;
		if(layout->panels[index].kind == PANEL_LEAF && !panel_is_bar(layout, index)) { layout->focused = index; return; }
	}
}

// NOTE: leaves in reading order: depth first, first child (left / top) before the second
internal void layout_leaves(Layout *layout, s32 panel, s32 *out, u32 *count)
{
	Panel *p = &layout->panels[panel];
	if(p->kind == PANEL_SPLIT) {
		layout_leaves(layout, p->children[0], out, count);
		layout_leaves(layout, p->children[1], out, count);
	} else if(p->kind == PANEL_LEAF && *count < UI_MAX_PANELS) {
		out[(*count)++] = panel;
	}
}

// NOTE: ctrl-tab: every tab of every panel as one ring, in reading order. focuses the panel and
// makes the tab active. bars are skipped, they aren't something to type into.
internal void layout_cycle_views(Layout *layout, s32 direction)
{
	s32 leaves[UI_MAX_PANELS];
	u32 leaf_count = 0;
	layout_leaves(layout, layout->root, leaves, &leaf_count);

	// flatten to (panel, tab) and find where we are
	s32 panels[UI_MAX_PANELS * UI_MAX_TABS];
	u32 tabs[UI_MAX_PANELS * UI_MAX_TABS];
	u32 count = 0;
	s32 at    = -1;
	for(u32 leaf = 0; leaf < leaf_count; ++leaf) {
		s32    panel = leaves[leaf];
		Panel *p     = &layout->panels[panel];
		if(panel_is_bar(layout, panel)) continue;
		for(u32 t = 0; t < p->tab_count; ++t) {
			if(panel == layout->focused && t == p->active_tab) at = (s32)count;
			panels[count] = panel;
			tabs[count]   = t;
			++count;
		}
	}
	if(count == 0) return;
	s32 next = (at < 0) ? 0 : (at + direction + (s32)count) % (s32)count;
	layout->focused                         = panels[next];
	layout->panels[panels[next]].active_tab = tabs[next];
}

//- rows
// NOTE: every view produces rows of small ids. cell text is only formatted for rows that are on
// screen, so a 114 row table costs ~20 formatted rows per frame.

typedef enum RowKind {
	ROW_QARI,
	ROW_SURAH,
	ROW_FIELD,
	ROW_SETTING, // a = index into the settings table
} RowKind;

typedef struct Row Row;
struct Row {
	u32 a;      // qari index / field id / setting id
	u32 b;      // surah index
	u8  kind;   // RowKind
	u8  depth;  // tree indent
	u8  expandable;
	u8  expanded;
};

#define UI_MAX_ROWS 4096

typedef enum PlayingField {
	FIELD_SURAH,
	FIELD_RECITER,
	FIELD_STATE,
	FIELD_POSITION,
	FIELD_VOLUME,
	FIELD_AUTOPLAY,
	FIELD_FORMAT,
	FIELD_COUNT,
} PlayingField;


//- profiler rows
// NOTE: a fixed list of metrics in sections, two of them (arenas, threads) expand to one row per
// registered entry. only the rows on screen get formatted, everything comes from counters and the
// 2hz sample, nothing here touches the os.

typedef enum ProfileMetric {
	PM_SECTION_FRAME, PM_FPS, PM_FRAME_CPU, PM_FRAME_SPLIT, PM_UI_SPLIT, PM_RENDER_SPLIT, PM_IDLE, PM_DRAW,
	PM_SECTION_MEMORY, PM_RSS, PM_RSS_KIND, PM_VIRTUAL, PM_STACK_MAIN,
	PM_SECTION_HEAP, PM_HEAP_LIVE, PM_HEAP_ALLOCS, PM_HEAP_FREES, PM_HEAP_BLOCKS, PM_HEAP_TOTAL, PM_HEAP_GLIBC,
	PM_SECTION_ARENAS, PM_ARENA,
	PM_SECTION_THREADS, PM_THREAD,
	PM_SECTION_PROCESS, PM_CPU, PM_FAULTS, PM_SWITCHES,
	PM_SECTION_AUDIO, PM_AUDIO_QUANTUM, PM_AUDIO_CALLBACK, PM_AUDIO_RING, PM_AUDIO_DECODER, PM_AUDIO_UNDERRUNS,
	PM_SECTION_GPU, PM_GPU_MEMORY, PM_GPU_SWAPCHAIN,
	PM_SECTION_FONTS, PM_FONT_GLYPHS, PM_FONT_RUNS, PM_FONT_ATLAS,
	PM_SECTION_DATA, PM_DATA_TRACKS, PM_DATA_NETWORK,
	PM_COUNT,
} ProfileMetric;

global_variable const char *profile_labels[PM_COUNT] = {
	"frame", "frame rate", "frame cpu", "frame split", "ui split", "render split", "between frames", "draw",
	"memory", "resident", "resident by kind", "virtual", "main thread stack",
	"heap (malloc, whole process)", "live", "allocations", "frees", "blocks alive", "handed out", "glibc arenas",
	"arenas", "",
	"threads and stacks", "",
	"process", "cpu", "page faults", "context switches",
	"audio", "pipewire quantum", "realtime callback", "ring", "decoder", "underruns",
	"gpu", "allocated by us", "swapchain",
	"fonts", "glyph cache", "shaped text cache", "atlas",
	"data", "track table", "network",
};

// NOTE: the sections of the metric list are separate views (Frame, Memory, Heap, ...). the
// section markers stay in the enum as the boundaries between groups.
global_variable const char *profile_group_names[] = {"frame", "memory", "heap", "arenas", "threads", "process", "audio", "gpu", "fonts", "data"};

internal b32 profile_is_section(u32 metric)
{
	return metric == PM_SECTION_FRAME || metric == PM_SECTION_MEMORY || metric == PM_SECTION_HEAP || metric == PM_SECTION_ARENAS ||
	       metric == PM_SECTION_THREADS || metric == PM_SECTION_PROCESS || metric == PM_SECTION_AUDIO || metric == PM_SECTION_GPU ||
	       metric == PM_SECTION_FONTS || metric == PM_SECTION_DATA;
}

//- the view registry
// NOTE: everything that can be opened: the plain kinds, every settings group and every profiler
// group. :view, its completion, --open, tab titles and the Views view all come from here.

typedef struct ViewType ViewType;
struct ViewType {
	u32         kind;
	u32         group;
	const char *name;
};

#define UI_MAX_VIEW_TYPES 48

typedef struct BaseView BaseView;
struct BaseView {
	u32         kind;
	const char *name;
	const char *title;
};

global_variable const BaseView ui_base_views[] = {
	{VIEW_RECITERS, "reciters", "Reciters"},
	{VIEW_SURAHS, "surahs", "Surahs"},
	{VIEW_OFFLINE, "offline", "Offline"},
	{VIEW_PLAYING, "playing", "Now Playing"},
	{VIEW_QUEUE, "queue", "Queue"},
	{VIEW_DOWNLOADS, "downloads", "Downloads"},
	{VIEW_VIEWS, "views", "Views"},
	{VIEW_STATUS, "status", "Status"},
};

internal u32 view_types(ViewType *out)
{
	u32 count = 0;
	for(u32 index = 0; index < ArrayCount(ui_base_views); ++index) out[count++] = ViewType{ui_base_views[index].kind, 0, ui_base_views[index].name};
	u32 group = 0;
	for(u32 index = 0; index < settings_desc_count() && count < UI_MAX_VIEW_TYPES; ++index) {
		if(settings_desc(index)->kind == SETTING_KIND_SECTION) out[count++] = ViewType{VIEW_SETTINGS, group++, settings_desc(index)->name};
	}
	for(u32 index = 0; index < ArrayCount(profile_group_names) && count < UI_MAX_VIEW_TYPES; ++index) out[count++] = ViewType{VIEW_PROFILER, index, profile_group_names[index]};
	return count;
}

internal const char *view_type_name(u32 kind, u32 group)
{
	ViewType types[UI_MAX_VIEW_TYPES];
	u32      count = view_types(types);
	for(u32 index = 0; index < count; ++index) if(types[index].kind == kind && types[index].group == group) return types[index].name;
	return "?";
}

// NOTE: the tab title: the base views have their own, groups show their name capitalized
internal String8 view_title(Arena *arena, View *view)
{
	for(u32 index = 0; index < ArrayCount(ui_base_views); ++index) {
		if(ui_base_views[index].kind == view->kind) return str8((char *)ui_base_views[index].title);
	}
	String8 name  = ui_format(arena, "%s", view_type_name(view->kind, view->group));
	if(name.size && name.data[0] >= 'a' && name.data[0] <= 'z') name.data[0] -= 32;
	return name;
}

// NOTE: exact name first, then a unique prefix ("prof" is no view, "pro" is process)
internal b32 view_resolve(const char *name, ViewType *out)
{
	ViewType types[UI_MAX_VIEW_TYPES];
	u32      count = view_types(types);
	u32      size  = (u32)strlen(name), hits = 0;
	if(size == 0) return false;
	for(u32 index = 0; index < count; ++index) {
		if(!strcasecmp(types[index].name, name)) { *out = types[index]; return true; }
		if(!strncasecmp(types[index].name, name, size)) { *out = types[index]; ++hits; }
	}
	return hits == 1;
}

// NOTE: the host asks this to decide whether to sample at all
internal b32 layout_view_visible(Layout *layout, ViewKind kind)
{
	for(s32 index = 0; index < UI_MAX_PANELS; ++index) {
		s32 view = panel_active_view(layout, index);
		if(view >= 0 && layout->views[view].kind == (u32)kind) return true;
	}
	return false;
}
global_variable const char *field_labels[FIELD_COUNT]    = {"surah", "reciter", "state", "position", "volume", "autoplay", "format"};

// NOTE: the status view's rows. as a bar: mode and message from the left, the rest from the right
typedef enum StatusItem {
	STATUS_MODE,
	STATUS_MESSAGE,
	STATUS_PLAYING,
	STATUS_DOWNLOADS,
	STATUS_SELECTION,
	STATUS_KEYS,
	STATUS_COUNT,
} StatusItem;
global_variable const char *status_labels[STATUS_COUNT] = {"mode", "message", "playing", "downloads", "selection", "pending keys"};

typedef struct Column Column;
struct Column {
	const char *title;
	f32         width; // fraction of the table
	b32         mono;
};

internal u32 view_columns(ViewKind kind, Column *out)
{
	switch(kind) {
		case VIEW_RECITERS:  out[0] = {"Reciter", 0.58f, 0}; out[1] = {"Style", 0.20f, 0}; out[2] = {"On disk", 0.22f, 1}; return 3;
		case VIEW_SURAHS:    out[0] = {"#", 0.07f, 1}; out[1] = {"Surah", 0.30f, 0}; out[2] = {"Meaning", 0.33f, 0}; out[3] = {"Ayat", 0.09f, 1}; out[4] = {"State", 0.21f, 1}; return 5;
		case VIEW_OFFLINE:   out[0] = {"Name", 0.58f, 0}; out[1] = {"Size", 0.17f, 1}; out[2] = {"Files", 0.25f, 0}; return 3;
		case VIEW_PLAYING:   out[0] = {"Field", 0.24f, 0}; out[1] = {"Value", 0.76f, 1}; return 2;
		case VIEW_DOWNLOADS: out[0] = {"Track", 0.55f, 0}; out[1] = {"Progress", 0.27f, 1}; out[2] = {"Size", 0.18f, 1}; return 3;
		case VIEW_SETTINGS:  out[0] = {"Setting", 0.28f, 0}; out[1] = {"Value", 0.30f, 1}; out[2] = {"Note", 0.42f, 0}; return 3;
		case VIEW_QUEUE:     out[0] = {"#", 0.07f, 1}; out[1] = {"Surah", 0.33f, 0}; out[2] = {"Reciter", 0.40f, 0}; out[3] = {"State", 0.20f, 1}; return 4;
		case VIEW_PROFILER:  out[0] = {"Metric", 0.26f, 0}; out[1] = {"Value", 0.30f, 1}; out[2] = {"Detail", 0.44f, 1}; return 3;
		case VIEW_VIEWS:     out[0] = {"View", 0.30f, 0}; out[1] = {"Command", 0.36f, 1}; out[2] = {"Shown", 0.34f, 0}; return 3;
		case VIEW_STATUS:    out[0] = {"Item", 0.24f, 0}; out[1] = {"Value", 0.76f, 1}; return 2;
		default: return 0;
	}
}

internal b32 view_expanded(View *view, u32 qari)
{
	return qari < VIEW_EXPANDED_WORDS * 64 && ((view->expanded[qari >> 6] >> (qari & 63)) & 1);
}

internal void view_set_expanded(View *view, u32 qari, b32 on)
{
	if(qari >= VIEW_EXPANDED_WORDS * 64) return;
	if(on) view->expanded[qari >> 6] |= (1ull << (qari & 63));
	else view->expanded[qari >> 6] &= ~(1ull << (qari & 63));
}

internal u32 view_rows(App *app, View *view, Row *rows, u32 capacity)
{
	u32 count = 0;
	switch(view->kind) {
		case VIEW_RECITERS: {
			for(u32 qari = 0; qari < app->catalog->qari_count && count < capacity; ++qari) {
				rows[count++] = Row{qari, 0, ROW_QARI, 0, 0, 0};
			}
		} break;
		case VIEW_SURAHS: {
			if(app->qari < 0) break;
			for(u32 surah = 0; surah < SURAH_COUNT && count < capacity; ++surah) {
				rows[count++] = Row{(u32)app->qari, surah, ROW_SURAH, 0, 0, 0};
			}
		} break;
		case VIEW_OFFLINE: {
			for(u32 qari = 0; qari < app->catalog->qari_count && count < capacity; ++qari) {
				if(store_disk_count(app->store, qari) == 0) continue;
				b32 open      = view_expanded(view, qari);
				rows[count++] = Row{qari, 0, ROW_QARI, 0, 1, (u8)open};
				if(!open) continue;
				for(u32 surah = 0; surah < SURAH_COUNT && count < capacity; ++surah) {
					if(store_on_disk(app->store, TrackKey(qari, surah))) rows[count++] = Row{qari, surah, ROW_SURAH, 1, 0, 0};
				}
			}
		} break;
		case VIEW_PLAYING: {
			for(u32 field = 0; field < FIELD_COUNT && count < capacity; ++field) rows[count++] = Row{field, 0, ROW_FIELD, 0, 0, 0};
		} break;
		case VIEW_DOWNLOADS: {
			for(u32 index = 0; index < app->store->worker_count && count < capacity; ++index) {
				u32 key = AtomicLoadRelaxed(&app->store->workers[index].current_key);
				if(key != TRACK_NONE) rows[count++] = Row{TrackQari(key), TrackSurah(key), ROW_SURAH, 0, 0, 0};
			}
			// NOTE: peek at the queue, a few dozen is all that fits on screen anyway
			JobQueue *queue = &app->store->queue;
			spin_lock(&queue->lock);
			for(u32 index = 0; index < queue->count && index < 64 && count < capacity; ++index) {
				u32 key = queue->items[(queue->head + index) & queue->mask];
				if(AtomicLoadRelaxed(&app->store->states[key]) == TRACK_QUEUED) rows[count++] = Row{TrackQari(key), TrackSurah(key), ROW_SURAH, 0, 0, 0};
			}
			spin_unlock(&queue->lock);
		} break;
		case VIEW_PROFILER: {
			// NOTE: the metrics between this group's section marker and the next one
			Profiler *profiler = app->profiler;
			s32       group    = -1;
			for(u32 metric = 0; metric < PM_COUNT && count < capacity; ++metric) {
				if(profile_is_section(metric)) { ++group; continue; }
				if(group != (s32)view->group) continue;
				if(metric == PM_ARENA) {
					for(u32 index = 0; index < profiler->arena_count && count < capacity; ++index) rows[count++] = Row{metric, index, ROW_FIELD, 0, 0, 0};
				} else if(metric == PM_THREAD) {
					for(u32 index = 0; index < profiler->thread_count && count < capacity; ++index) rows[count++] = Row{metric, index, ROW_FIELD, 0, 0, 0};
				} else {
					rows[count++] = Row{metric, 0, ROW_FIELD, 0, 0, 0};
				}
			}
		} break;
		case VIEW_VIEWS: {
			ViewType types[UI_MAX_VIEW_TYPES];
			u32      types_count = view_types(types);
			for(u32 index = 0; index < types_count && count < capacity; ++index) rows[count++] = Row{index, 0, ROW_FIELD, 0, 0, 0};
		} break;
		case VIEW_STATUS: {
			for(u32 index = 0; index < STATUS_COUNT && count < capacity; ++index) rows[count++] = Row{index, 0, ROW_FIELD, 0, 0, 0};
		} break;
		case VIEW_QUEUE: {
			for(u32 index = 0; index < app->queue_count && count < capacity; ++index) {
				u32 key       = app->queue[index];
				rows[count++] = Row{TrackQari(key), TrackSurah(key), ROW_SURAH, 0, 0, 0};
			}
		} break;
		case VIEW_SETTINGS: {
			// NOTE: the settings between this group's section entry and the next one
			s32 group = -1;
			for(u32 index = 0; index < settings_desc_count() && count < capacity; ++index) {
				if(settings_desc(index)->kind == SETTING_KIND_SECTION) { ++group; continue; }
				if(group == (s32)view->group) rows[count++] = Row{index, 0, ROW_SETTING, 0, 0, 0};
			}
		} break;
	}
	return count;
}

// NOTE: reciters and surahs show the shared selection (rad style: views follow the selected
// entity), every other view keeps its own cursor
internal s32 view_cursor(App *app, View *view, Row *rows, u32 count)
{
	if(view->kind == VIEW_RECITERS) return app->qari;
	if(view->kind == VIEW_SURAHS) return app->surah;
	return (count == 0) ? 0 : Clamp(view->cursor, 0, (s32)count - 1);
}

internal void view_set_cursor(App *app, View *view, Row *rows, u32 count, s32 cursor)
{
	if(count == 0) return;
	cursor       = Clamp(cursor, 0, (s32)count - 1);
	view->cursor = cursor;
	Row *row     = &rows[cursor];
	if(view->kind == VIEW_RECITERS) {
		app->qari = (s32)row->a;
	} else if(view->kind == VIEW_SURAHS) {
		app->surah = (s32)row->b;
	} else if(view->kind == VIEW_OFFLINE) {
		app->qari = (s32)row->a;
		if(row->kind == ROW_SURAH) app->surah = (s32)row->b;
	}
	app->keep_selection_visible = true;
}

internal u32 row_track_key(Row *row)
{
	return (row->kind == ROW_SURAH) ? TrackKey(row->a, row->b) : TRACK_NONE;
}

typedef struct Cells Cells;
struct Cells {
	u32     swatch;     // color settings: a sample square before the value
	b32     has_swatch;
	String8 text[5];
	f32     progress; // >= 0 and an empty last column: draw a bar there
	b32     bright;   // the playing track. in a bar: drawn as a highlighted block
	b32     dim;
	b32     right;    // in a bar: placed from the right edge
};

internal String8 track_state_text(App *app, u32 key, f32 *progress)
{
	TrackEntry *entry = store_entry(app->store, key);
	u32         state = AtomicLoadRelaxed(TrackStatePtr(app->store, entry));
	switch(state) {
		case TRACK_DONE: return str8("on disk");
		case TRACK_QUEUED: return str8("queued");
		case TRACK_DOWNLOADING: {
			u64 total = AtomicLoadRelaxed(&entry->bytes_total);
			*progress = total ? (f32)((f64)AtomicLoadRelaxed(&entry->bytes_done) / (f64)total) : 0.0f;
			return str8_zero();
		}
		case TRACK_PARTIAL: return str8("partial");
		case TRACK_FAILED: return str8(AtomicLoadRelaxed(&entry->http_status) == 0 ? "no connection" : "unavailable");
	}
	return str8_zero();
}

internal void view_cells(App *app, View *view, Row *row, Cells *cells, Arena *arena)
{
	MemSetZero(cells, sizeof(*cells));
	cells->progress  = -1.0f;
	Catalog *catalog = app->catalog;
	u32      playing = app_current_key(app);
	char     a[32], b[32];

	switch(view->kind) {
		case VIEW_RECITERS: {
			Qari *qari = &catalog->qaris[row->a];
			u32 on_disk    = store_disk_count(app->store, row->a);
			cells->text[0] = qari->name;
			cells->text[1] = catalog_section_name(qari->section_id);
			cells->text[2] = on_disk ? ui_u32_pair(arena, on_disk, '/', SURAH_COUNT) : str8("-");
			cells->bright  = (playing != TRACK_NONE && TrackQari(playing) == row->a);
		} break;
		case VIEW_SURAHS: {
			Surah *surah   = &catalog->surahs[row->b];
			u32    key     = row_track_key(row);
			cells->text[0] = ui_u32(arena, row->b + 1);
			cells->text[1] = surah->name;
			cells->text[2] = surah->english;
			cells->text[3] = ui_u32(arena, surah->ayah_count);
			cells->text[4] = track_state_text(app, key, &cells->progress);
			cells->bright  = (key == playing);
			cells->dim     = !store_on_disk(app->store, key) && cells->progress < 0;
		} break;
		case VIEW_DOWNLOADS: {
			Surah      *surah = &catalog->surahs[row->b];
			u32         key   = row_track_key(row);
			TrackEntry *entry = store_entry(app->store, key);
			cells->text[0]    = ui_format(arena, Str8Fmt " · %u. " Str8Fmt, Str8Arg(catalog->qaris[row->a].name), row->b + 1, Str8Arg(surah->name));
			cells->text[1]    = track_state_text(app, key, &cells->progress);
			if(cells->progress >= 0) cells->text[1] = ui_format(arena, "%3.0f%%", cells->progress * 100.0f);
			u64 total = AtomicLoadRelaxed(&entry->bytes_total);
			format_bytes(a, sizeof(a), (f64)total);
			cells->text[2] = total ? ui_format(arena, "%s", a) : str8("-");
			cells->bright  = (key == playing);
		} break;
		case VIEW_PROFILER: {
			Profiler *p = app->profiler;
			char      x[32], y[32], z[32];
			cells->text[0] = str8((char *)profile_labels[row->a]);
			switch(row->a) {
				case PM_FPS: {
					cells->text[1] = ui_format(arena, "%.0f fps", app->fps);
					cells->text[2] = app->settings.fps_cap ? ui_format(arena, "cap %u, renders only while something moves", app->settings.fps_cap) : str8("paced by the compositor");
				} break;
				case PM_FRAME_CPU: {
					cells->text[1] = ui_format(arena, "%.3f ms", p->average);
					cells->text[2] = ui_format(arena, "p50 %.3f  p99 %.3f  worst %.3f  (%u frames)", p->p50, p->p99, p->worst, p->frames_total);
				} break;
				case PM_FRAME_SPLIT: {
					cells->text[1] = ui_format(arena, "ui %.3f ms", p->ui_ms);
					cells->text[2] = ui_format(arena, "render %.3f ms (p99 ui %.3f render %.3f), ~%.0f fps of headroom", p->render_ms, p->ui_p99, p->render_p99, p->average > 0 ? 1000.0f / p->average : 0.0f);
				} break;
				case PM_UI_SPLIT: {
					f32 *us = p->ui_phase_us;
					cells->text[1] = ui_format(arena, "panels %.0f us", us[PROFILE_UI_PANELS]);
					cells->text[2] = ui_format(arena, "keys %.1f  overlay %.1f us (averaged, panels include the status bar)", us[PROFILE_UI_KEYBOARD], us[PROFILE_UI_OVERLAY]);
				} break;
				case PM_RENDER_SPLIT: {
					VulkanRenderer *r = &app->renderer;
					cells->text[1] = ui_format(arena, "record %.3f ms", r->record_ms);
					cells->text[2] = ui_format(arena, "gpu wait %.3f  acquire %.3f  submit+present %.3f", r->wait_ms, r->acquire_ms, r->submit_ms);
				} break;
				case PM_IDLE: cells->text[1] = ui_format(arena, "%.2f ms", p->idle_ms); cells->text[2] = str8("asleep in poll() waiting for input or the next frame slot"); break;
				case PM_DRAW: {
					cells->text[1] = ui_format(arena, "%u quads", app->draw.count);
					cells->text[2] = ui_format(arena, "%u draw calls, peak %u of %u quads", app->renderer.batches, app->draw.peak, (u32)DRAW_MAX_INSTANCES);
				} break;
				case PM_RSS: {
					format_bytes(x, sizeof(x), (f64)p->rss); format_bytes(y, sizeof(y), (f64)p->rss_peak);
					cells->text[1] = ui_format(arena, "%s", x);
					cells->text[2] = ui_format(arena, "peak %s", y);
				} break;
				case PM_RSS_KIND: {
					format_bytes(x, sizeof(x), (f64)p->rss_anon); format_bytes(y, sizeof(y), (f64)p->rss_file); format_bytes(z, sizeof(z), (f64)p->rss_shmem);
					cells->text[1] = ui_format(arena, "anon %s", x);
					cells->text[2] = ui_format(arena, "file %s (library code, shared)  shmem %s", y, z);
				} break;
				case PM_VIRTUAL: {
					format_bytes(x, sizeof(x), (f64)p->vm_size); format_bytes(y, sizeof(y), (f64)p->vm_data); format_bytes(z, sizeof(z), (f64)p->vm_lib);
					cells->text[1] = ui_format(arena, "%s", x);
					cells->text[2] = ui_format(arena, "data %s  libraries %s (reserved, mostly untouched)", y, z);
				} break;
				case PM_STACK_MAIN: {
					format_bytes(x, sizeof(x), (f64)p->vm_stack);
					cells->text[1] = ui_format(arena, "%s", x);
					cells->text[2] = str8("touched so far (VmStk)");
				} break;
				case PM_HEAP_LIVE: {
					format_bytes(x, sizeof(x), (f64)Max(AtomicLoadRelaxed(&p->heap_live), (s64)0)); format_bytes(y, sizeof(y), (f64)AtomicLoadRelaxed(&p->heap_peak));
					cells->text[1] = ui_format(arena, "%s", x);
					cells->text[2] = ui_format(arena, "peak %s, counted at every malloc / free", y);
				} break;
				case PM_HEAP_ALLOCS: cells->text[1] = ui_format(arena, "%llu", (unsigned long long)AtomicLoadRelaxed(&p->malloc_count)); cells->text[2] = ui_format(arena, "%.0f / s", p->mallocs_per_s); break;
				case PM_HEAP_FREES:  cells->text[1] = ui_format(arena, "%llu", (unsigned long long)AtomicLoadRelaxed(&p->free_count)); cells->text[2] = ui_format(arena, "%.0f / s", p->frees_per_s); break;
				case PM_HEAP_BLOCKS: cells->text[1] = ui_format(arena, "%lld", (long long)(AtomicLoadRelaxed(&p->malloc_count) - AtomicLoadRelaxed(&p->free_count))); cells->text[2] = str8("allocations not freed yet"); break;
				case PM_HEAP_TOTAL: format_bytes(x, sizeof(x), (f64)AtomicLoadRelaxed(&p->heap_total)); cells->text[1] = ui_format(arena, "%s", x); cells->text[2] = str8("every byte malloc ever returned"); break;
				case PM_HEAP_GLIBC: {
					format_bytes(x, sizeof(x), (f64)p->heap_arena); format_bytes(y, sizeof(y), (f64)p->heap_free); format_bytes(z, sizeof(z), (f64)p->heap_mmapped);
					cells->text[1] = ui_format(arena, "%s", x);
					cells->text[2] = ui_format(arena, "free in arenas %s  mmapped chunks %s", y, z);
				} break;
				case PM_ARENA: {
					ProfileArena *entry = &p->arenas[row->b];
					Arena        *a     = entry->arena;
					u64 used = arena_position(a), reserved = 0, blocks = 0;
					for(Arena *block = a->current; block; block = block->previous) { reserved += block->capacity; ++blocks; }
					format_bytes(x, sizeof(x), (f64)used); format_bytes(y, sizeof(y), (f64)a->peak_position); format_bytes(z, sizeof(z), (f64)reserved);
					cells->text[0] = ui_format(arena, "%s", entry->name);
					cells->text[1] = ui_format(arena, "%s", x);
					cells->text[2] = ui_format(arena, "peak %s of %s, %llu allocs (%.0f/s), %llu blocks", y, z, (unsigned long long)a->alloc_count, entry->allocs_per_s, (unsigned long long)blocks);
				} break;
				case PM_THREAD: {
					ProfileThread *t = &p->threads[row->b];
					format_bytes(x, sizeof(x), (f64)t->stack_touched); format_bytes(y, sizeof(y), (f64)t->stack_size);
					cells->text[0] = ui_format(arena, "%s (%d)", t->name, t->tid);
					cells->text[1] = ui_format(arena, "cpu %5.1f%%", t->cpu * 100.0f);
					cells->text[2] = ui_format(arena, "stack %s / %s  faults %.0f/s  switches %.0f/s", x, t->stack_size ? y : "rlimit", t->minflt_per_s, t->csw_per_s);
				} break;
				case PM_CPU: cells->text[1] = ui_format(arena, "%.1f%%", p->cpu_process * 100.0f); cells->text[2] = str8("of one core, every thread together"); break;
				case PM_FAULTS: cells->text[1] = ui_format(arena, "%.0f / s", p->minflt_per_s); cells->text[2] = ui_format(arena, "major %.1f / s, %llu minor total", p->majflt_per_s, (unsigned long long)p->minflt); break;
				case PM_SWITCHES: cells->text[1] = ui_format(arena, "%.0f / s", p->csw_per_s); cells->text[2] = ui_format(arena, "%llu voluntary, %llu involuntary", (unsigned long long)p->vcsw, (unsigned long long)p->ivcsw); break;
				case PM_AUDIO_QUANTUM: {
					AudioOutput *o = app->output;
					u32 rate = Max(o->rate, 1u);
					cells->text[1] = ui_format(arena, "%u frames", o->callback_frames);
					cells->text[2] = ui_format(arena, "%.2f ms at %u hz, %llu callbacks", 1000.0 * o->callback_frames / rate, rate, (unsigned long long)o->callbacks);
				} break;
				case PM_AUDIO_CALLBACK: {
					AudioOutput *o       = app->output;
					f64          average = o->callbacks ? (f64)o->callback_ns_total / (f64)o->callbacks / 1000.0 : 0.0;
					f64          budget  = o->rate ? 1e6 * o->callback_frames / o->rate : 0.0;
					cells->text[1] = ui_format(arena, "%.1f us", average);
					cells->text[2] = ui_format(arena, "worst %.1f us, %.3f%% of its budget", (f64)o->callback_ns_max / 1000.0, budget > 0 ? 100.0 * average / budget : 0.0);
				} break;
				case PM_AUDIO_RING: {
					AudioRing *ring = app->ring;
					u64 fill = AtomicLoadRelaxed(&ring->write_frame) - AtomicLoadRelaxed(&ring->read_frame);
					format_bytes(x, sizeof(x), (f64)(ring->capacity_frames * AUDIO_CHANNELS * sizeof(f32)));
					cells->text[1] = ui_format(arena, "%3.0f%% full", 100.0 * (f64)fill / (f64)ring->capacity_frames);
					cells->text[2] = ui_format(arena, "%.2f s buffered of %.2f s, %s", (f64)fill / Max(app->output->rate, 1u), (f64)ring->capacity_frames / Max(app->output->rate, 1u), x);
				} break;
				case PM_AUDIO_DECODER: {
					Decoder *dec    = app->decoder;
					u64      frames = AtomicLoadRelaxed(&dec->decoded_frames), ns = AtomicLoadRelaxed(&dec->decode_ns);
					f64      speed  = ns ? ((f64)frames / Max(app->output->rate, 1u)) / ((f64)ns / 1e9) : 0.0;
					cells->text[1] = ui_format(arena, "%.0fx realtime", speed);
					cells->text[2] = ui_format(arena, "%.1f s of audio decoded in %.1f ms, mpg123 %s", (f64)frames / Max(app->output->rate, 1u), (f64)ns / 1e6, dec->decoder_name ? dec->decoder_name : "-");
				} break;
				case PM_AUDIO_UNDERRUNS: cells->text[1] = ui_u32(arena, app->output->underruns); cells->text[2] = ui_format(arena, "audio missing mid track; %u waits for a new track's first samples", app->output->switch_gaps); break;
				case PM_GPU_MEMORY: {
					format_bytes(x, sizeof(x), (f64)app->renderer.gpu_bytes);
					cells->text[1] = ui_format(arena, "%s", x);
					cells->text[2] = str8("instance + staging buffers, glyph atlas (driver swapchain not included)");
				} break;
				case PM_GPU_SWAPCHAIN: {
					VulkanRenderer *r = &app->renderer;
					cells->text[1] = ui_format(arena, "%ux%u", r->extent.width, r->extent.height);
					cells->text[2] = ui_format(arena, "%u images, %s", r->image_count, r->present_mode == VK_PRESENT_MODE_MAILBOX_KHR ? "mailbox" : "fifo");
				} break;
				case PM_FONT_GLYPHS: {
					FontSystem *f = &app->fonts;
					cells->text[1] = ui_format(arena, "%u / %u", f->glyph_count, (u32)FONT_GLYPH_SLOTS);
					cells->text[2] = ui_format(arena, "%u faces loaded (font x size)", f->face_count);
				} break;
				case PM_FONT_RUNS: {
					FontSystem *f = &app->fonts;
					cells->text[1] = ui_format(arena, "%u / %u", f->run_count, (u32)FONT_RUN_SLOTS);
					cells->text[2] = str8("strings shaped once, then reused every frame");
				} break;
				case PM_FONT_ATLAS: {
					FontSystem *f = &app->fonts;
					cells->text[1] = ui_format(arena, "%.0f%%", 100.0f * (f32)(f->shelf_y + f->shelf_h) / FONT_ATLAS_SIZE);
					cells->text[2] = ui_format(arena, "%ux%u single channel, rows filled", (u32)FONT_ATLAS_SIZE, (u32)FONT_ATLAS_SIZE);
				} break;
				case PM_DATA_TRACKS: {
					format_bytes(x, sizeof(x), (f64)(sizeof(TrackEntry) * app->store->entry_count));
					cells->text[1] = ui_format(arena, "%s", x);
					cells->text[2] = ui_format(arena, "%u tracks x %u bytes, flat array", app->store->entry_count, (u32)sizeof(TrackEntry));
				} break;
				case PM_DATA_NETWORK: {
					format_bytes(x, sizeof(x), (f64)AtomicLoadRelaxed(&app->store->bytes_downloaded));
					format_bytes(y, sizeof(y), app->speed);
					cells->text[1] = ui_format(arena, "%s", x);
					cells->text[2] = ui_format(arena, "this session, %s/s now, %u active, %u queued", y, AtomicLoadRelaxed(&app->store->active), job_queue_count(&app->store->queue));
				} break;
			}
		} break;
		case VIEW_STATUS: {
			cells->text[0] = str8((char *)status_labels[row->a]);
			cells->right   = (row->a >= STATUS_PLAYING);
			switch(row->a) {
				case STATUS_MODE: {
					const char *mode = "NORMAL";
					if(app->overlay == UI_OVERLAY_SEARCH) mode = "SEARCH";
					if(app->overlay == UI_OVERLAY_COMMAND) mode = "COMMAND";
					if(app->overlay == UI_OVERLAY_EDIT) mode = "EDIT";
					if(app->drag_view >= 0 && app->drag_active) mode = "MOVE";
					if(app->visual) mode = "VISUAL";
					cells->text[1] = str8((char *)mode);
					cells->bright  = true;
				} break;
				case STATUS_MESSAGE: {
					if(app->message[0] && time_now_ns() - app->message_ns < (u64)(ui_theme.message_seconds * 1e9f)) {
						cells->text[1] = str8(app->message);
						app->ticking   = true; // so it disappears on time
					}
				} break;
				case STATUS_PLAYING: {
					u32 key = app_current_key(app);
					if(key == TRACK_NONE) break;
					char a[32], b[32];
					u32  rate  = Max(app->position.rate, 1u);
					u64  total = app_track_total(app);
					format_duration(a, sizeof(a), (f64)app->position.frame / rate);
					format_duration(b, sizeof(b), (f64)total / rate);
					cells->text[1] = ui_format(arena, "%s  %u. " Str8Fmt "  %s / %s", app->paused ? "paused" : "playing", TrackSurah(key) + 1,
					                           Str8Arg(app->catalog->surahs[TrackSurah(key)].name), a, total ? b : "--:--");
				} break;
				case STATUS_DOWNLOADS: {
					u32 active = AtomicLoadRelaxed(&app->store->active);
					u32 queued = job_queue_count(&app->store->queue);
					if(active + queued == 0) break;
					char speed[32];
					format_bytes(speed, sizeof(speed), app->speed);
					cells->text[1] = ui_format(arena, "dl %u+%u  %s/s", active, queued, speed);
					cells->dim     = true;
					app->ticking   = true;
				} break;
				case STATUS_SELECTION: {
					if(app->visual) cells->text[1] = str8("selecting");
					else if(app->selected_count) cells->text[1] = ui_format(arena, "%u selected", app->selected_count);
				} break;
				case STATUS_KEYS: {
					if(!app->count && !app->pending) break;
					char buffer[32];
					int  length = 0;
					if(app->count) length = snprintf(buffer, sizeof(buffer), "%u", app->count);
					if(app->pending == 'w') snprintf(buffer + length, sizeof(buffer) - (u32)length, "^W");
					else if(app->pending) snprintf(buffer + length, sizeof(buffer) - (u32)length, "%c", (char)app->pending);
					cells->text[1] = ui_format(arena, "%s", buffer);
				} break;
			}
		} break;
		case VIEW_VIEWS: {
			ViewType types[UI_MAX_VIEW_TYPES];
			view_types(types);
			ViewType *type  = &types[row->a];
			View      probe = {};
			probe.kind      = type->kind;
			probe.group     = type->group;
			s32 panel       = -1;
			s32 shown       = layout_find_kind(&app->layout, (ViewKind)type->kind, &panel, type->group);
			cells->text[0]  = view_title(arena, &probe);
			cells->text[1]  = ui_format(arena, ":view %s", type->name);
			cells->text[2]  = (shown < 0) ? str8_zero() : str8(panel_active_view(&app->layout, panel) == shown ? "on screen" : "in a tab");
			cells->dim      = (shown < 0);
		} break;
		case VIEW_QUEUE: {
			u32 key        = row_track_key(row);
			cells->text[0] = ui_u32(arena, row->b + 1);
			cells->text[1] = catalog->surahs[row->b].name;
			cells->text[2] = catalog->qaris[row->a].name;
			cells->text[3] = track_state_text(app, key, &cells->progress);
			cells->bright  = (key == playing);
		} break;
		case VIEW_OFFLINE: {
			if(row->kind == ROW_QARI) {
				cells->text[0] = catalog->qaris[row->a].name;
				format_bytes(a, sizeof(a), (f64)AtomicLoadRelaxed(&app->store->qari_done_bytes[row->a]));
				cells->text[1] = ui_format(arena, "%s", a);
				cells->text[2] = ui_format(arena, "%u surahs", store_disk_count(app->store, row->a));
				cells->bright  = (playing != TRACK_NONE && TrackQari(playing) == row->a);
			} else {
				u32 key        = row_track_key(row);
				cells->text[0] = ui_format(arena, "%u. " Str8Fmt, row->b + 1, Str8Arg(catalog->surahs[row->b].name));
				format_bytes(a, sizeof(a), (f64)AtomicLoadRelaxed(&store_entry(app->store, key)->bytes_total));
				cells->text[1] = ui_format(arena, "%s", a);
				cells->text[2] = catalog->surahs[row->b].english;
				cells->bright  = (key == playing);
			}
		} break;
		case VIEW_PLAYING: {
			cells->text[0] = str8((char *)field_labels[row->a]);
			u32 key        = (playing != TRACK_NONE) ? playing : app_selected_key(app);
			cells->dim     = (playing == TRACK_NONE);
			if(key == TRACK_NONE) break;
			Surah *surah = &catalog->surahs[TrackSurah(key)];
			u32    rate  = Max(app->position.rate, 1u);
			switch(row->a) {
				case FIELD_SURAH: cells->text[1] = ui_format(arena, "%u. " Str8Fmt " (" Str8Fmt ")", surah->number, Str8Arg(surah->name), Str8Arg(surah->english)); break;
				case FIELD_RECITER: cells->text[1] = catalog->qaris[TrackQari(key)].name; break;
				case FIELD_STATE: {
					u32         status = AtomicLoadRelaxed(&app->decoder->status);
					const char *text   = "stopped";
					if(playing != TRACK_NONE) text = app->paused ? "paused" : "playing";
					if(playing != TRACK_NONE && (status == DECODER_BUFFERING || (app->position.flags & PLAYBACK_STARVED))) text = "buffering";
					if(status == DECODER_ERROR) {
						TrackEntry *entry = store_entry(app->store, app->requested_key);
						text = (entry && AtomicLoadRelaxed(TrackStatePtr(app->store, entry)) == TRACK_FAILED && entry->http_status == 0) ? "offline, and not downloaded" : "error, could not play";
					}
					cells->text[1] = str8((char *)text);
				} break;
				case FIELD_POSITION: {
					u64 total = app_track_total(app);
					format_duration(a, sizeof(a), playing != TRACK_NONE ? (f64)app->position.frame / rate : 0.0);
					format_duration(b, sizeof(b), (f64)total / rate);
					cells->text[1]  = ui_format(arena, "%s / %s", a, total ? b : "--:--");
					cells->progress = (total && playing != TRACK_NONE) ? (f32)((f64)app->position.frame / (f64)total) : 0.0f;
				} break;
				case FIELD_VOLUME: cells->text[1] = ui_format(arena, "%.0f%%", app->settings.volume * 100.0f); break;
				case FIELD_AUTOPLAY: cells->text[1] = str8((char *)autoplay_name(app->settings.autoplay)); break;
				case FIELD_FORMAT: cells->text[1] = app->position.rate ? ui_format(arena, "%.1f kHz, f32 stereo, pipewire", app->position.rate / 1000.0f) : str8("-"); break;
			}
		} break;
		case VIEW_SETTINGS: {
			SettingDesc *desc = settings_desc(row->a);
			cells->text[0]    = str8((char *)desc->name);
			cells->text[2]    = desc->note ? str8((char *)desc->note) : str8_zero();
			if(desc->kind == SETTING_KIND_COLOR) {
				cells->has_swatch = true;
				cells->swatch     = *(u32 *)((u8 *)&app->settings + desc->offset);
			}
			if(desc->kind == SETTING_KIND_ACTION) {
				cells->text[1] = str8("run");
			} else if(desc->kind == SETTING_KIND_INFO) {
				cells->dim = true;
				switch(desc->action) {
					case SETTING_INFO_FRAME: {
						cells->text[1] = ui_format(arena, "%.2f ms", app->frame_ms);
						cells->text[2] = ui_format(arena, "%.0f fps now, %u quads, ~%.0f fps possible", app->fps, app->draw.peak, app->frame_ms > 0 ? 1000.0f / app->frame_ms : 0.0f);
					} break;
					case SETTING_INFO_ON_DISK: {
						u64 bytes = 0;
						u32 files = 0;
						for(u32 qari = 0; qari < catalog->qari_count; ++qari) {
							bytes += AtomicLoadRelaxed(&app->store->qari_done_bytes[qari]);
							files += store_disk_count(app->store, qari);
						}
						format_bytes(a, sizeof(a), (f64)bytes);
						cells->text[1] = ui_format(arena, "%s", a);
						cells->text[2] = ui_format(arena, "%u surahs", files);
					} break;
					case SETTING_INFO_DATA_DIR: cells->text[1] = app->data_dir; break;
					case SETTING_INFO_RELOADS: cells->text[1] = ui_u32(arena, app->ui_generation); cells->text[2] = str8("hot reloaded ui builds this session"); break;
				}
			} else {
				cells->text[1] = settings_format(arena, &app->settings, desc);
			}
		} break;
	}
}

//- row actions

internal void overlay_open(App *app, UIOverlay overlay);

internal void view_adjust(App *app, View *view, Row *row, s32 direction)
{
	if(view->kind == VIEW_PLAYING) {
		switch(row->a) {
			case FIELD_POSITION: app_seek_seconds(app, direction * (f64)app->settings.seek_seconds); break;
			case FIELD_VOLUME: app_set_volume(app, app->settings.volume + 0.05f * direction); break;
			case FIELD_AUTOPLAY: app->settings.autoplay = (app->settings.autoplay + 3 + direction) % 3; app_apply_settings(app); break;
			case FIELD_STATE: app_toggle_pause(app); break;
		}
	} else if(view->kind == VIEW_SETTINGS && row->kind == ROW_SETTING) {
		settings_adjust(&app->settings, settings_desc(row->a), direction);
		app_apply_settings(app);
	}
}

internal void edit_begin(App *app, View *view, u32 field)
{
	app->edit_view  = (u32)(view - app->layout.views);
	app->edit_field = field;
	overlay_open(app, UI_OVERLAY_EDIT);
}

internal void view_activate(App *app, View *view, Row *row)
{
	switch(view->kind) {
		case VIEW_RECITERS: {
			app->qari = (s32)row->a;
			if(layout_find_kind(&app->layout, VIEW_SURAHS, NULL) >= 0) layout_open(&app->layout, VIEW_SURAHS);
		} break;
		case VIEW_VIEWS: {
			ViewType types[UI_MAX_VIEW_TYPES];
			view_types(types);
			layout_open(&app->layout, (ViewKind)types[row->a].kind, types[row->a].group);
		} break;
		case VIEW_QUEUE: {
			u32 key = row_track_key(row);
			if(key == app_current_key(app)) app_toggle_pause(app);
			else app_play_in_queue(app, key);
		} break;
		case VIEW_SURAHS:
		case VIEW_DOWNLOADS: {
			u32 key = row_track_key(row);
			if(key == app_current_key(app)) app_toggle_pause(app);
			else app_play(app, key, 0);
		} break;
		case VIEW_OFFLINE: {
			if(row->kind == ROW_QARI) {
				view_set_expanded(view, row->a, !view_expanded(view, row->a));
			} else {
				// NOTE: playing from the offline library keeps you offline
				if(app->settings.autoplay == AUTOPLAY_NEXT) app->settings.autoplay = AUTOPLAY_NEXT_DOWNLOADED;
				u32 key = row_track_key(row);
				if(key == app_current_key(app)) app_toggle_pause(app);
				else app_play(app, key, 0);
			}
		} break;
		case VIEW_PLAYING: {
			u32 key = app_current_key(app);
			if(row->a == FIELD_SURAH || row->a == FIELD_RECITER) {
				if(key != TRACK_NONE) {
					app->jump_back              = app_place(app);
					app->qari                   = (s32)TrackQari(key);
					app->surah                  = (s32)TrackSurah(key);
					app->keep_selection_visible = true;
				}
			} else if(row->a == FIELD_STATE) {
				app_toggle_pause(app);
			} else if(row->a == FIELD_POSITION || row->a == FIELD_VOLUME) {
				edit_begin(app, view, row->a);
			} else {
				view_adjust(app, view, row, 1);
			}
		} break;
		case VIEW_SETTINGS: {
			SettingDesc *desc = settings_desc(row->a);
			if(desc->kind == SETTING_KIND_ACTION) {
				if(desc->action == SETTING_ACTION_RESET_LAYOUT) {
					ui_layout_default(&app->layout);
					app_message(app, "layout reset");
				} else if(desc->action == SETTING_ACTION_RESET_COLORS) {
					settings_apply_scheme(&app->settings, app->settings.scheme == UI_SCHEME_CUSTOM ? 0 : app->settings.scheme);
					app_message(app, "colors reset");
				} else if(desc->action == SETTING_ACTION_RESET_SETTINGS) {
					settings_default(&app->settings);
					app_apply_settings(app);
					app_message(app, "settings reset to defaults");
				}
			} else if(desc->kind == SETTING_KIND_F32 || desc->kind == SETTING_KIND_U32 || desc->kind == SETTING_KIND_COLOR) {
				edit_begin(app, view, row->a);
			} else if(desc->kind != SETTING_KIND_INFO) {
				view_adjust(app, view, row, 1);
			}
		} break;
	}
}

//- table

//- multi selection
// NOTE: one bitset over every track key (177 * 114 bits = 2.5KB), so a selection survives
// switching reciters and views and costs one bit test per drawn row.

internal b32 track_selected(App *app, u32 key)
{
	return key < app->store->entry_count && ((app->selected[key >> 6] >> (key & 63)) & 1);
}

internal void track_select(App *app, u32 key, b32 on)
{
	if(key >= app->store->entry_count || track_selected(app, key) == on) return;
	app->selected[key >> 6] ^= (1ull << (key & 63));
	app->selected_count += on ? 1 : (u32)-1;
}

internal void selection_clear(App *app)
{
	MemSetZero(app->selected, sizeof(u64) * ((app->store->entry_count + 63) / 64));
	app->selected_count = 0;
	app->visual         = false;
}

// NOTE: rows between the visual anchor and the cursor count as selected while V is active
internal b32 row_in_visual(App *app, View *view, s32 index, s32 cursor)
{
	if(!app->visual || app->visual_view != (u32)(view - app->layout.views)) return false;
	s32 lo = Min(app->visual_anchor, cursor), hi = Max(app->visual_anchor, cursor);
	return index >= lo && index <= hi;
}

internal void visual_commit(App *app, View *view, Row *rows, u32 count)
{
	if(!app->visual) return;
	s32 cursor = view_cursor(app, view, rows, count);
	s32 lo = Clamp(Min(app->visual_anchor, cursor), 0, (s32)count - 1), hi = Clamp(Max(app->visual_anchor, cursor), 0, (s32)count - 1);
	for(s32 index = lo; index <= hi && count; ++index) {
		u32 key = row_track_key(&rows[index]);
		if(key != TRACK_NONE) track_select(app, key, true);
	}
	app->visual = false;
}

// NOTE: selected keys in playing order: by reciter, then surah. 316 words, ctz per hit.
internal u32 selection_keys(App *app, u32 *out, u32 capacity)
{
	u32 count = 0;
	u32 words = (app->store->entry_count + 63) / 64;
	for(u32 word = 0; word < words && count < capacity; ++word) {
		u64 bits = app->selected[word];
		while(bits && count < capacity) {
			u32 bit = (u32)__builtin_ctzll(bits);
			out[count++] = word * 64 + bit;
			bits &= bits - 1;
		}
	}
	return count;
}

//- queue

internal void app_send_queue(App *app)
{
	decoder_command(app->decoder, DECODER_QUEUE_CLEAR, 0, 0);
	for(u32 index = 0; index < app->queue_count; ++index) {
		decoder_command(app->decoder, DECODER_QUEUE_ADD, app->queue[index], 0);
	}
}

// NOTE: play these tracks as a queue, in order, gapless between them like autoplay
internal void app_play_queue(App *app, const u32 *keys, u32 count)
{
	count = Min(count, (u32)DECODER_QUEUE_CAPACITY);
	if(count == 0 || !app->audio_ok) return;
	if(keys != app->queue) MemMove(app->queue, keys, sizeof(u32) * count);
	app->queue_count = count;
	app_send_queue(app);
	app->requested_key = app->queue[0];
	app->paused        = false;
	audio_output_set_paused(app->output, false);
	decoder_command(app->decoder, DECODER_SET_AUTOPLAY, 0, app->settings.autoplay);
	decoder_command(app->decoder, DECODER_PLAY, app->queue[0], 0);
}

internal void app_play_selection(App *app, View *view, Row *rows, u32 count)
{
	if(view) visual_commit(app, view, rows, count);
	u32 keys = selection_keys(app, app->queue, DECODER_QUEUE_CAPACITY);
	if(keys == 0) return;
	app_play_queue(app, app->queue, keys);
	app_message(app, "playing %u selected surahs", keys);
	selection_clear(app);
}

internal void app_play_in_queue(App *app, u32 key)
{
	app->requested_key = key;
	app->paused        = false;
	audio_output_set_paused(app->output, false);
	decoder_command(app->decoder, DECODER_PLAY, key, 0);
}

internal s32 queue_find(App *app, u32 key)
{
	for(u32 index = 0; index < app->queue_count; ++index) if(app->queue[index] == key) return (s32)index;
	return -1;
}

internal void queue_remove(App *app, u32 key)
{
	s32 at = queue_find(app, key);
	if(at < 0) return;
	for(u32 index = (u32)at; index + 1 < app->queue_count; ++index) app->queue[index] = app->queue[index + 1];
	--app->queue_count;
	app_send_queue(app);
}

//- columns

internal void view_columns_setup(View *view, Column *columns, u32 count)
{
	if(view->column_count == count) return;
	view->column_count  = count;
	view->column_hidden = 0;
	for(u32 index = 0; index < count; ++index) {
		view->column_order[index]  = (u8)index;
		view->column_weight[index] = columns[index].width;
	}
}

typedef struct ColumnLayout ColumnLayout;
struct ColumnLayout {
	u32 count;                 // visible columns
	u32 logical[UI_MAX_COLUMNS];
	f32 x0[UI_MAX_COLUMNS];
	f32 x1[UI_MAX_COLUMNS];
	f32 total;                 // sum of visible weights
};

internal ColumnLayout column_layout(View *view, Rect area)
{
	ColumnLayout layout = {};
	for(u32 index = 0; index < view->column_count; ++index) {
		u32 c = view->column_order[index];
		if(!((view->column_hidden >> c) & 1)) {
			layout.logical[layout.count++] = c;
			layout.total += view->column_weight[c];
		}
	}
	f32 x = area.x0, w = rect_w(area);
	for(u32 index = 0; index < layout.count; ++index) {
		layout.x0[index] = x;
		x += w * view->column_weight[layout.logical[index]] / Max(layout.total, 0.0001f);
		layout.x1[index] = (index + 1 == layout.count) ? area.x1 : x;
	}
	return layout;
}

// NOTE: column headers get the same gestures as tabs and panel gaps
internal void draw_column_headers(App *app, PlatformInput *input, View *view, Column *columns, Rect header, ColumnLayout *layout)
{
	DrawList   *d      = &app->draw;
	FontSystem *fonts  = &app->fonts;
	s32         self   = (s32)(view - app->layout.views);
	b32         free   = app->drag_view < 0 && app->resize_panel < 0 && app->overlay == UI_OVERLAY_NONE;
	f32         base   = ui_baseline(app, FONT_REGULAR, UI_FONT_SMALL, header.y0, rect_h(header));
	draw_rect(d, header, COLOR_HEADER, 0);

	for(u32 index = 0; index < layout->count; ++index) {
		u32  c    = layout->logical[index];
		Rect cell = {layout->x0[index], header.y0, layout->x1[index], header.y1};
		b32  over = free && ui_hovered(input, cell);
		if(app->column_drag_view == self && app->column_drag_active && app->column_drag_column == c) draw_rect(d, cell, COLOR_DROP, 0);
		else if(over) draw_rect(d, cell, COLOR_HOVER, 0);
		draw_text_fit(d, fonts, FONT_REGULAR, UI_FONT_SMALL, cell.x0 + 8, base, rect_w(cell) - 12, str8((char *)columns[c].title), COLOR_TEXT_FAINT);
		if(index > 0) draw_rect(d, Rect{cell.x0, header.y0 + 4, cell.x0 + 1, header.y1 - 4}, COLOR_PANEL_EDGE, 0);

		//- edge on the right: resize, like a panel gap
		Rect edge = {cell.x1 - 3, header.y0, cell.x1 + 3, header.y1};
		b32  on_edge = free && index + 1 < layout->count && ui_hovered(input, edge);
		if(on_edge) app->table_cursor = PLATFORM_CURSOR_RESIZE_X;
		if(on_edge && ButtonPressed(input->mouse[0])) {
			app->column_resize_view  = self;
			app->column_resize_index = index;
			input->mouse[0].half_transition_count = 0;
			continue;
		}
		//- body: drag to reorder, middle click hides, like a tab
		if(over && ButtonPressed(input->mouse[0])) {
			app->column_drag_view   = self;
			app->column_drag_column = c;
			app->column_drag_active = false;
			app->column_drag_x      = input->mouse_x;
		}
		if(over && ButtonPressed(input->mouse[2]) && layout->count > 1) {
			view->column_hidden |= (1u << c);
			app_message(app, "column %s hidden, :columns brings it back", columns[c].title);
		}
	}

	//- resizing: the two columns around the edge trade weight, the sum stays the same
	if(app->column_resize_view == self) {
		u32 index = app->column_resize_index;
		if(index + 1 < layout->count) {
			u32 a = layout->logical[index], b = layout->logical[index + 1];
			f32 pair = view->column_weight[a] + view->column_weight[b];
			f32 per_px = layout->total / Max(rect_w(header), 1.0f);
			f32 wa   = (input->mouse_x - layout->x0[index]) * per_px;
			wa       = Clamp(wa, pair * 0.08f, pair * 0.92f);
			view->column_weight[a] = wa;
			view->column_weight[b] = pair - wa;
		}
		app->table_cursor = PLATFORM_CURSOR_RESIZE_X;
		app->animating    = true;
		if(!input->mouse[0].ended_down) app->column_resize_view = -1;
	}

	//- reordering: drop before the first column whose middle is right of the mouse
	if(app->column_drag_view == self) {
		if(fabsf(input->mouse_x - app->column_drag_x) > 6) app->column_drag_active = true;
		if(app->column_drag_active) {
			u32 slot = layout->count;
			for(u32 index = 0; index < layout->count; ++index) {
				if(input->mouse_x < (layout->x0[index] + layout->x1[index]) * 0.5f) { slot = index; break; }
			}
			f32 line_x = (slot < layout->count) ? layout->x0[slot] : layout->x1[layout->count - 1] - 2;
			draw_rect(d, Rect{line_x, header.y0, line_x + 2, header.y1}, COLOR_ACCENT, 0);
			app->table_cursor = PLATFORM_CURSOR_GRABBING;
			app->animating    = true;
			if(!input->mouse[0].ended_down) {
				// rebuild the order: everything but the dragged column, with it inserted at the slot
				u32 target = (slot < layout->count) ? layout->logical[slot] : UINT32_MAX;
				u8  order[UI_MAX_COLUMNS];
				u32 n = 0;
				for(u32 index = 0; index < view->column_count; ++index) {
					u8 c = view->column_order[index];
					if(c == app->column_drag_column) continue;
					if(c == target) order[n++] = (u8)app->column_drag_column;
					order[n++] = c;
				}
				if(target == UINT32_MAX || target == app->column_drag_column) {
					if(n < view->column_count) order[n++] = (u8)app->column_drag_column;
				}
				if(n == view->column_count) MemCpy(view->column_order, order, n);
			}
		}
		if(!input->mouse[0].ended_down) app->column_drag_view = -1;
	}
}

internal void draw_table(App *app, PlatformInput *input, s32 panel, View *view, Rect area, b32 focused)
{
	DrawList    *d       = &app->draw;
	FontSystem  *fonts   = &app->fonts;
	ScratchArena scratch = ScratchGet();

	Row *rows       = PushArray(scratch.arena, Row, UI_MAX_ROWS);
	u32  count      = view_rows(app, view, rows, UI_MAX_ROWS);
	view->row_count = count;

	Column columns[UI_MAX_COLUMNS];
	u32    column_count = view_columns((ViewKind)view->kind, columns);
	view_columns_setup(view, columns, column_count);
	ColumnLayout layout = column_layout(view, area);

	//- column header
	Rect header = {area.x0, area.y0, area.x1, area.y0 + UI_COLUMN_H};
	if(UI_COLUMN_H > 0) draw_column_headers(app, input, view, columns, header, &layout);

	//- body
	Rect body   = {area.x0, header.y1, area.x1, area.y1};
	f32  row_h  = UI_ROW_H;
	f32  view_h = rect_h(body);
	s32  cursor = view_cursor(app, view, rows, count);

	if(ui_hovered(input, body) && input->scroll_y != 0) {
		view->scroll.target += input->scroll_y * row_h * (f32)ui_theme.scroll_lines;
	}
	if(app->keep_selection_visible || (focused && input->key_count)) {
		// NOTE: keep a row of context around the cursor, like scrolloff=1
		f32 y = (f32)cursor * row_h;
		if(y - row_h < view->scroll.target) view->scroll.target = y - row_h;
		if(y + 2 * row_h > view->scroll.target + view_h) view->scroll.target = y + 2 * row_h - view_h;
	}
	scroll_update(&view->scroll, (f32)count * row_h, view_h, app->dt, &app->animating);

	u32 first           = (u32)(view->scroll.offset / row_h);
	u32 last            = Min(count, first + (u32)(view_h / row_h) + 2);
	view->first_visible = first;
	view->visible_rows  = (u32)(view_h / row_h);

	b32 busy = app->drag_view >= 0 || app->resize_panel >= 0 || app->column_drag_view >= 0 || app->column_resize_view >= 0 || app->overlay != UI_OVERLAY_NONE;

	draw_clip_push(d, body);
	Cells cells;
	for(u32 index = first; index < last; ++index) {
		Row *row      = &rows[index];
		f32  y        = body.y0 + (f32)index * row_h - view->scroll.offset;
		Rect rect     = {body.x0, y, body.x1, y + row_h};
		b32  selected = ((s32)index == cursor);
		b32  hovered  = ui_hovered(input, rect_intersect(rect, body)) && !busy;
		u32  key      = row_track_key(row);
		b32  marked   = (key != TRACK_NONE) && (track_selected(app, key) || row_in_visual(app, view, (s32)index, cursor));

		view_cells(app, view, row, &cells, scratch.arena);

		if(ui_theme.zebra && (index & 1)) draw_rect(d, rect, COLOR_ZEBRA, 0);
		if(marked) draw_rect(d, rect, COLOR_MARKED, 0);
		if(selected) draw_rect(d, rect, focused ? COLOR_SELECTED : COLOR_HOVER, 0);
		else if(hovered) draw_rect(d, rect, COLOR_HOVER, 0);
		if(marked) draw_rect(d, Rect{rect.x1 - 4, rect.y0 + 3, rect.x1 - 2, rect.y1 - 3}, COLOR_TEXT_DIM, 0);
		if(cells.bright) draw_rect(d, Rect{rect.x0, rect.y0, rect.x0 + 2, rect.y1}, COLOR_ACCENT, 0);

		u32 color = cells.bright ? COLOR_ACCENT : (cells.dim ? COLOR_TEXT_FAINT : COLOR_TEXT);
		for(u32 slot = 0; slot < layout.count; ++slot) {
			u32 c      = layout.logical[slot];
			f32 cx     = layout.x0[slot];
			f32 w      = layout.x1[slot] - layout.x0[slot];
			f32 indent = 0;
			if(c == 0) {
				indent = (f32)row->depth * ui_theme.tree_indent;
				if(row->expandable) {
					draw_text(d, fonts, FONT_MONO, UI_FONT, cx + 8 + indent, ui_baseline(app, FONT_MONO, UI_FONT, y, row_h), str8(row->expanded ? "-" : "+"), COLOR_TEXT_DIM);
					indent += 14.0f;
				}
			}
			FontKind font = columns[c].mono ? FONT_MONO : ((cells.bright && ui_theme.bold_playing && c == 0) ? FONT_SEMIBOLD : FONT_REGULAR);
			if(c == 1 && cells.has_swatch) {
				// NOTE: color settings show a sample square, the hex value follows it
				f32  side = Min(row_h - 8, 14.0f);
				Rect sw   = {cx + 8, y + (row_h - side) * 0.5f, cx + 8 + side, y + (row_h + side) * 0.5f};
				draw_rect(d, sw, cells.swatch, 0);
				draw_border(d, sw, COLOR_PANEL_EDGE, 0, 1);
				indent = side + 8;
			}
			u32 tint = (c > 0 && !cells.bright) ? (cells.dim ? COLOR_TEXT_FAINT : COLOR_TEXT_DIM) : color;
			f32 tx   = cx + 8 + indent;
			f32 base = ui_baseline(app, font, UI_FONT, y, row_h);

			if(c + 1 == column_count && cells.progress >= 0 && cells.text[c].size == 0) {
				Rect bar = {cx + 8, y + row_h * 0.5f - 2, cx + w - 10, y + row_h * 0.5f + 2};
				draw_rect(d, bar, COLOR_TRACK, 0);
				draw_rect(d, Rect{bar.x0, bar.y0, bar.x0 + rect_w(bar) * cells.progress, bar.y1}, COLOR_TEXT_DIM, 0);
			} else if(view->kind == VIEW_PLAYING && row->a == FIELD_POSITION && c == 1) {
				// NOTE: the position value is text plus a seek bar you can click
				f32  tw  = draw_text(d, fonts, font, UI_FONT, tx, base, cells.text[c], tint);
				Rect bar = {tx + tw + 12, y + row_h * 0.5f - 2, cx + w - 10, y + row_h * 0.5f + 2};
				if(rect_w(bar) > 20) {
					draw_rect(d, bar, COLOR_TRACK, 0);
					draw_rect(d, Rect{bar.x0, bar.y0, bar.x0 + rect_w(bar) * Clamp(cells.progress, 0.0f, 1.0f), bar.y1}, COLOR_ACCENT, 0);
					u64  total = app_track_total(app);
					Rect hit   = {bar.x0, rect.y0, bar.x1, rect.y1};
					if(hovered && ui_clicked(input, hit) && total && app_current_key(app) != TRACK_NONE) {
						f32 t = Clamp((input->mouse_x - bar.x0) / rect_w(bar), 0.0f, 1.0f);
						decoder_command(app->decoder, DECODER_SEEK, 0, (u64)((f64)t * (f64)total));
						input->mouse[0].half_transition_count = 0;
					}
				}
			} else {
				draw_text_fit(d, fonts, font, UI_FONT, tx, base, w - 14 - indent, cells.text[c], tint);
			}
		}

		//- mouse: click moves the cursor, double click (or the +) activates,
		//  ctrl click toggles the row in the selection, shift click selects up to it
		if(hovered && ButtonPressed(input->mouse[0])) {
			app->layout.focused = panel;
			u64 now    = time_now_ns();
			b32 twice  = (now - app->last_click_ns < (u64)ui_theme.double_click_ms * 1000000ull) && fabsf(input->mouse_x - app->last_click_x) < 4 && fabsf(input->mouse_y - app->last_click_y) < 4;
			b32 on_box = row->expandable && layout.count && layout.logical[0] == 0 && input->mouse_x < body.x0 + 8 + row->depth * ui_theme.tree_indent + 14.0f;
			if((input->mods & PLATFORM_MOD_CTRL) && key != TRACK_NONE) {
				track_select(app, key, !track_selected(app, key));
				now = 0;
			} else if((input->mods & PLATFORM_MOD_SHIFT) && key != TRACK_NONE) {
				s32 lo = Min(cursor, (s32)index), hi = Max(cursor, (s32)index);
				for(s32 at = lo; at <= hi; ++at) if(row_track_key(&rows[at]) != TRACK_NONE) track_select(app, row_track_key(&rows[at]), true);
				now = 0;
			} else if(twice || on_box) {
				view_activate(app, view, row);
				now = 0;
			}
			view_set_cursor(app, view, rows, count, (s32)index);
			app->last_click_ns = now;
			app->last_click_x  = input->mouse_x;
			app->last_click_y  = input->mouse_y;
		}
	}
	draw_clip_pop(d);

	if(count == 0) {
		const char *empty = "nothing here";
		if(view->kind == VIEW_OFFLINE) empty = "nothing downloaded yet: yy downloads a surah, Y a whole reciter";
		if(view->kind == VIEW_DOWNLOADS) empty = "no downloads running";
		if(view->kind == VIEW_QUEUE) empty = "empty: select surahs (v, V, ctrl click) and press enter";
		draw_text_fit(d, fonts, FONT_REGULAR, UI_FONT, body.x0 + 10, body.y0 + 18, rect_w(body) - 20, str8((char *)empty), COLOR_TEXT_FAINT);
	}

	//- scrollbar
	f32 content = (f32)count * row_h;
	if(content > view_h && ui_theme.show_scrollbars) {
		f32 thumb_h = Max(view_h * view_h / content, 20.0f);
		f32 thumb_y = body.y0 + (view_h - thumb_h) * (view->scroll.offset / (content - view_h));
		draw_rect(d, Rect{body.x1 - 4, thumb_y, body.x1 - 1, thumb_y + thumb_h}, COLOR_TRACK, 0);
	}

	scratch_end(&scratch);
}

//- panels

internal DropZone drop_zone(Rect rect, f32 x, f32 y)
{
	f32 u = (x - rect.x0) / Max(rect_w(rect), 1.0f);
	f32 v = (y - rect.y0) / Max(rect_h(rect), 1.0f);
	if(u < 0.25f) return DROP_LEFT;
	if(u > 0.75f) return DROP_RIGHT;
	if(v < 0.25f) return DROP_TOP;
	if(v > 0.75f) return DROP_BOTTOM;
	return DROP_CENTER;
}

internal Rect drop_preview(Rect rect, DropZone zone)
{
	switch(zone) {
		case DROP_LEFT: return Rect{rect.x0, rect.y0, rect.x0 + rect_w(rect) * 0.5f, rect.y1};
		case DROP_RIGHT: return Rect{rect.x0 + rect_w(rect) * 0.5f, rect.y0, rect.x1, rect.y1};
		case DROP_TOP: return Rect{rect.x0, rect.y0, rect.x1, rect.y0 + rect_h(rect) * 0.5f};
		case DROP_BOTTOM: return Rect{rect.x0, rect.y0 + rect_h(rect) * 0.5f, rect.x1, rect.y1};
		default: return rect;
	}
}

// NOTE: a view as one line: each row's value side by side (the Value column, or the first one).
// rows marked right are placed from the right edge first, the rest flow from the left into what's
// left. drag it like a tab to move the view elsewhere, middle click closes it.
internal b32 draw_bar(App *app, PlatformInput *input, s32 panel, s32 view_index, Rect rect, b32 modal)
{
	DrawList    *d       = &app->draw;
	FontSystem  *fonts   = &app->fonts;
	View        *view    = &app->layout.views[view_index];
	f32          size    = UI_FONT_SMALL;
	ScratchArena scratch = ScratchGet();
	draw_rect(d, rect, COLOR_BG, 0);

	if(!modal && ui_hovered(input, rect) && app->drag_view < 0) {
		if(ButtonPressed(input->mouse[0])) {
			app->drag_view   = view_index;
			app->drag_panel  = panel;
			app->drag_x      = input->mouse_x;
			app->drag_y      = input->mouse_y;
			app->drag_active = false;
		}
		if(ButtonPressed(input->mouse[2])) {
			Panel *p = &app->layout.panels[panel];
			scratch_end(&scratch);
			layout_close_view(&app->layout, panel, p->active_tab);
			return true;
		}
	}

	Row  *rows  = PushArray(scratch.arena, Row, UI_MAX_ROWS);
	u32   count = view_rows(app, view, rows, UI_MAX_ROWS);
	// NOTE: field | value views show the value (an empty one is skipped), others their first column
	Column columns[UI_MAX_COLUMNS];
	u32    shown = (view_columns((ViewKind)view->kind, columns) >= 2 && (view->kind == VIEW_STATUS || view->kind == VIEW_PLAYING || view->kind == VIEW_PROFILER || view->kind == VIEW_SETTINGS)) ? 1 : 0;
	Cells *all  = PushArray(scratch.arena, Cells, count);
	f32   baseline = ui_baseline(app, FONT_MONO, size, rect.y0, Min(rect_h(rect), UI_STATUS_H));
	f32   right    = rect.x1 - 10;
	draw_clip_push(d, rect);
	for(u32 pass = 0; pass < 2; ++pass) {
		f32 left = rect.x0;
		for(u32 index = 0; index < count; ++index) {
			Cells *cells = &all[index];
			if(pass == 0) {
				MemSetZero(cells, sizeof(*cells));
				view_cells(app, view, &rows[index], cells, scratch.arena);
			}
			String8 text = cells->text[shown];
			if(text.size == 0 || (b32)cells->right != (pass == 0)) continue;
			u32 color = cells->dim ? COLOR_TEXT_DIM : COLOR_TEXT;
			if(cells->right) {
				right -= font_measure(fonts, FONT_MONO, size, text);
				draw_text(d, fonts, FONT_MONO, size, right, baseline, text, color);
				right -= 18;
			} else if(cells->bright) {
				f32 w = font_measure(fonts, FONT_MONO, size, text) + 16;
				draw_rect(d, Rect{left, rect.y0, left + w, rect.y1}, COLOR_TAB_ACTIVE, 0);
				draw_text(d, fonts, FONT_MONO, size, left + 8, baseline, text, COLOR_TEXT);
				left += w + 10;
			} else if(right - left > 24) {
				left += draw_text_fit(d, fonts, FONT_REGULAR, size, left, baseline, right - left - 8, text, COLOR_TEXT_DIM) + 18;
			}
		}
	}
	draw_clip_pop(d);
	scratch_end(&scratch);
	return false;
}

internal void draw_panels(App *app, PlatformInput *input)
{
	DrawList   *d      = &app->draw;
	FontSystem *fonts  = &app->fonts;
	Layout     *layout = &app->layout;
	u32         cursor = PLATFORM_CURSOR_DEFAULT;
	b32         modal  = (app->overlay != UI_OVERLAY_NONE);
	f32         tab_font = UI_FONT_SMALL + 0.5f;

	//- split handles: drag the gap between two panels
	for(s32 index = 0; index < UI_MAX_PANELS && !modal; ++index) {
		Panel *p = &layout->panels[index];
		if(p->kind != PANEL_SPLIT) continue;
		Rect a      = layout->panels[p->children[0]].rect;
		Rect handle = (p->axis == 0) ? Rect{a.x1 - 1, p->rect.y0, a.x1 + UI_GAP + 1, p->rect.y1}
		                             : Rect{p->rect.x0, a.y1 - 1, p->rect.x1, a.y1 + UI_GAP + 1};
		b32 over = ui_hovered(input, handle) && app->drag_view < 0;
		if(over && ButtonPressed(input->mouse[0])) app->resize_panel = index;
		if(over || app->resize_panel == index) cursor = (p->axis == 0) ? PLATFORM_CURSOR_RESIZE_X : PLATFORM_CURSOR_RESIZE_Y;
	}
	if(app->resize_panel >= 0) {
		Panel *p = &layout->panels[app->resize_panel];
		if(p->kind == PANEL_SPLIT) {
			f32 t    = (p->axis == 0) ? (input->mouse_x - p->rect.x0) / rect_w(p->rect) : (input->mouse_y - p->rect.y0) / rect_h(p->rect);
			p->ratio = Clamp(t, 0.1f, 0.9f);
			// NOTE: a bottom panel dragged down to a few lines snaps into a bar (whole status lines),
			// dragged back up it becomes a table again
			f32 lines = (p->rect.y1 - input->mouse_y) / UI_STATUS_H;
			if(p->axis == 1 && lines < 3.5f) p->ratio = -Max(roundf(lines), 1.0f);
		}
		if(!input->mouse[0].ended_down) app->resize_panel = -1;
		app->animating = true;
	}

	//- leaves
	for(s32 index = 0; index < UI_MAX_PANELS; ++index) {
		Panel *p = &layout->panels[index];
		if(p->kind != PANEL_LEAF) continue;
		b32  focused = (layout->focused == index) && !modal;
		Rect rect    = p->rect;

		// NOTE: too short for tabs + a header + a row: the active view becomes a bar
		if(panel_is_bar(layout, index)) {
			s32 view = panel_active_view(layout, index);
			if(view >= 0 && draw_bar(app, input, index, view, rect, modal)) return; // closed: layout changed
			continue;
		}
		draw_rect(d, rect, COLOR_PANEL, 0);

		//- tab bar
		// NOTE: tabs keep their natural width while they fit and shrink evenly when they don't,
		// so a panel can hold many views without spilling into its neighbour
		Rect bar = {rect.x0, rect.y0, rect.x1, rect.y0 + UI_TAB_H};
		draw_rect(d, bar, COLOR_BG, 0);
		ScratchArena tab_scratch = ScratchGet();
		String8 *titles = PushArray(tab_scratch.arena, String8, UI_MAX_TABS);
		f32     *widths = PushArray(tab_scratch.arena, f32, UI_MAX_TABS);
		f32      total  = 0;
		for(u32 t = 0; t < p->tab_count; ++t) {
			titles[t] = view_title(tab_scratch.arena, &layout->views[p->tabs[t]]);
			widths[t] = font_measure(fonts, FONT_REGULAR, tab_font, titles[t]) + 24;
			total += widths[t] + 1;
		}
		f32 fit = (total > rect_w(bar) && total > 0) ? rect_w(bar) / total : 1.0f;
		draw_clip_push(d, bar);
		f32 tx = bar.x0;
		for(u32 t = 0; t < p->tab_count; ++t) {
			String8 title  = titles[t];
			f32     w      = Max(widths[t] * fit, 28.0f);
			Rect    tab    = {tx, bar.y0, tx + w, bar.y1};
			b32     active = (t == p->active_tab);
			b32     over   = ui_hovered(input, rect_intersect(tab, bar)) && !modal;
			draw_rect(d, tab, active ? COLOR_TAB_ACTIVE : (over ? COLOR_TAB : COLOR_BG), 0);
			if(active && focused) draw_rect(d, Rect{tab.x0, tab.y0, tab.x1, tab.y0 + 2}, COLOR_ACCENT, 0);
			draw_text_fit(d, fonts, FONT_REGULAR, tab_font, tab.x0 + 12 * Min(fit, 1.0f), ui_baseline(app, FONT_REGULAR, tab_font, tab.y0, UI_TAB_H), w - 16, title,
			              active ? (focused ? COLOR_ACCENT : COLOR_TEXT) : COLOR_TEXT_DIM);

			if(over && ButtonPressed(input->mouse[0])) {
				p->active_tab    = t;
				layout->focused  = index;
				app->drag_view   = p->tabs[t];
				app->drag_panel  = index;
				app->drag_x      = input->mouse_x;
				app->drag_y      = input->mouse_y;
				app->drag_active = false;
			}
			if(over && ButtonPressed(input->mouse[2])) {
				draw_clip_pop(d);
				scratch_end(&tab_scratch);
				layout_close_view(layout, index, t);
				return; // the layout changed under us, it's drawn again next frame
			}
			tx += w + 1;
		}
		draw_clip_pop(d);
		scratch_end(&tab_scratch);

		//- empty tab bar space is the window's title bar: drag to move, double click to maximize
		Rect empty = {tx, bar.y0, bar.x1, bar.y1};
		if(!modal && !PlatformWindowIsLayer(app->window) && ui_clicked(input, empty) && app->drag_view < 0) {
			u64 now = time_now_ns();
			if(now - app->last_click_ns < (u64)ui_theme.double_click_ms * 1000000ull) {
				PlatformWindowToggleMaximized(app->window);
				app->last_click_ns = 0;
			} else {
				app->last_click_ns = now;
				PlatformWindowBeginMove(app->window);
			}
		}

		//- content
		Rect content = {rect.x0, bar.y1, rect.x1, rect.y1};
		s32  view    = panel_active_view(layout, index);
		if(view >= 0) {
			draw_clip_push(d, content);
			draw_table(app, input, index, &layout->views[view], content, focused);
			draw_clip_pop(d);
		} else {
			draw_text(d, fonts, FONT_MONO, UI_FONT_SMALL, content.x0 + 10, content.y0 + 20, str8(":view reciters | surahs | offline | playing | downloads | settings"), COLOR_TEXT_FAINT);
		}

		draw_border(d, rect, focused ? COLOR_FOCUS_EDGE : COLOR_PANEL_EDGE, 0, 1);
	}

	//- tab drag and drop
	if(app->drag_view >= 0) {
		f32 moved = fabsf(input->mouse_x - app->drag_x) + fabsf(input->mouse_y - app->drag_y);
		if(moved > 6) app->drag_active = true;
		if(app->drag_active) {
			cursor         = PLATFORM_CURSOR_GRABBING;
			app->animating = true;
			for(s32 index = 0; index < UI_MAX_PANELS; ++index) {
				Panel *p = &layout->panels[index];
				if(p->kind != PANEL_LEAF || !ui_hovered(input, p->rect)) continue;
				DropZone zone    = drop_zone(p->rect, input->mouse_x, input->mouse_y);
				Rect     preview = drop_preview(p->rect, zone);
				draw_rect(d, preview, COLOR_DROP, 0);
				draw_border(d, preview, COLOR_FOCUS_EDGE, 0, 1);
				if(!input->mouse[0].ended_down) {
					layout_move_view(layout, app->drag_panel, app->drag_view, index, zone);
					break;
				}
			}
			if(app->drag_view >= 0 && layout->views[app->drag_view].kind != VIEW_NONE) {
				ScratchArena ghost_scratch = ScratchGet();
				String8      title         = view_title(ghost_scratch.arena, &layout->views[app->drag_view]);
				f32     w     = font_measure(fonts, FONT_REGULAR, tab_font, title) + 24;
				Rect    ghost = {input->mouse_x + 10, input->mouse_y + 10, input->mouse_x + 10 + w, input->mouse_y + 10 + UI_TAB_H};
				draw_rect(d, ghost, COLOR_TAB_ACTIVE, 0);
				draw_border(d, ghost, COLOR_FOCUS_EDGE, 0, 1);
				draw_text(d, fonts, FONT_REGULAR, tab_font, ghost.x0 + 12, ui_baseline(app, FONT_REGULAR, tab_font, ghost.y0, UI_TAB_H), title, COLOR_TEXT);
				scratch_end(&ghost_scratch);
			}
		}
		if(!input->mouse[0].ended_down) app->drag_view = -1;
	}

	if(cursor == PLATFORM_CURSOR_DEFAULT) cursor = app->table_cursor;
	if(app->cursor_shape != cursor) {
		app->cursor_shape = cursor;
		PlatformWindowSetCursor(app->window, (PlatformCursor)cursor);
	}
}

//- overlays

internal void search_update(App *app)
{
	app->result_count  = 0;
	app->result_cursor = 0;
	if(app->input_size == 0) return;

	// NOTE: a number jumps straight to that surah
	u32 number  = 0;
	b32 numeric = true;
	for(u32 index = 0; index < app->input_size; ++index) {
		char c = app->input[index];
		if(c < '0' || c > '9') {
			numeric = false;
			break;
		}
		number = number * 10 + (u32)(c - '0');
	}
	if(numeric && number >= 1 && number <= SURAH_COUNT) {
		app->results[app->result_count++] = SearchResult{UINT32_MAX, number - 1};
	}

	for(u32 qari = 0; qari < app->catalog->qari_count && app->result_count < UI_MAX_RESULTS; ++qari) {
		if(str8_contains_nocase(app->catalog->qaris[qari].name, app->input, app->input_size)) {
			app->results[app->result_count++] = SearchResult{qari, 0};
		}
	}
	for(u32 surah = 0; surah < SURAH_COUNT && app->result_count < UI_MAX_RESULTS; ++surah) {
		Surah *s = &app->catalog->surahs[surah];
		if(numeric && surah == number - 1) continue;
		if(str8_contains_nocase(s->name, app->input, app->input_size) || str8_contains_nocase(s->english, app->input, app->input_size)) {
			app->results[app->result_count++] = SearchResult{UINT32_MAX, surah};
		}
	}
}

internal void overlay_open(App *app, UIOverlay overlay)
{
	app->overlay        = overlay;
	app->overlay_opened = true;
	app->input_size     = 0;
	app->result_count   = 0;
	app->result_cursor  = 0;
	if(overlay != UI_OVERLAY_EDIT) {
		return;
	}
	// NOTE: start from the current value, like editing a watch expression
	View *view  = &app->layout.views[app->edit_view];
	char  text[64];
	text[0] = 0;
	if(view->kind == VIEW_PLAYING && app->edit_field == FIELD_POSITION) format_duration(text, sizeof(text), app->position.rate ? (f64)app->position.frame / app->position.rate : 0.0);
	if(view->kind == VIEW_PLAYING && app->edit_field == FIELD_VOLUME) snprintf(text, sizeof(text), "%.0f", app->settings.volume * 100);
	if(view->kind == VIEW_SETTINGS) {
		ScratchArena scratch = ScratchGet();
		String8      value   = settings_format(scratch.arena, &app->settings, settings_desc(app->edit_field));
		snprintf(text, sizeof(text), Str8Fmt, Str8Arg(value));
		scratch_end(&scratch);
	}
	app->input_size = (u32)Min(strlen(text), sizeof(app->input) - 1);
	MemCpy(app->input, text, app->input_size);
}

// NOTE: pick a reciter / surah from anywhere: it moves the shared selection, so every view follows
internal void search_accept(App *app, SearchResult result)
{
	app->jump_back = app_place(app);
	if(result.qari != UINT32_MAX) {
		app->qari = (s32)result.qari;
		layout_open(&app->layout, VIEW_RECITERS);
	} else {
		app->surah = (s32)result.surah;
		layout_open(&app->layout, VIEW_SURAHS);
	}
	app->keep_selection_visible = true;
}

internal f64 parse_duration(const char *text)
{
	f64 total = 0, part = 0;
	for(const char *at = text; *at; ++at) {
		if(*at == ':') {
			total = (total + part) * 60.0;
			part  = 0;
		} else if(*at >= '0' && *at <= '9') {
			part = part * 10 + (*at - '0');
		}
	}
	return total + part;
}

internal void edit_accept(App *app)
{
	char text[65];
	MemCpy(text, app->input, app->input_size);
	text[app->input_size] = 0;
	View *view            = &app->layout.views[app->edit_view];
	f64   value           = atof(text);
	if(view->kind == VIEW_PLAYING) {
		if(app->edit_field == FIELD_POSITION && app->position.rate) decoder_command(app->decoder, DECODER_SEEK, 0, (u64)(parse_duration(text) * app->position.rate));
		if(app->edit_field == FIELD_VOLUME) app->settings.volume = (f32)(value / 100.0);
	} else if(view->kind == VIEW_SETTINGS) {
		if(!settings_parse(&app->settings, settings_desc(app->edit_field), text)) app_message(app, "could not read \"%s\"", text);
	}
	app_apply_settings(app);
}

//- command completion
// NOTE: computed from the typed text every time it's needed (a few dozen candidates, microseconds),
// so the only state is the highlighted row (result_cursor). nothing new lives in App, which keeps
// this hot reloadable.

typedef struct CommandDesc CommandDesc;
struct CommandDesc {
	const char *name;
	const char *args;
	const char *help;
	b32         takes_arg;
};

global_variable const CommandDesc ui_commands[] = {
	{"view",    "<view>",           "open or focus a view",                         1},
	{"vs",      "<view>",           "open a view split to the right",               1},
	{"sp",      "<view>",           "open a view split below",                      1},
	{"set",     "<name>=<value>",   "change any setting",                           1},
	{"vol",     "<0-100>",          "volume",                                       1},
	{"zoom",    "<0.6-3>",          "ui zoom",                                      1},
	{"columns", "",                 "bring back the hidden columns of this view",   0},
	{"reset",   "",                 "back to the default panel layout",             0},
	{"dl",      "",                 "download every surah of the selected reciter", 0},
	{"q",       "",                 "quit",                                         0},
	{"e",       "<view>",           "same as view",                                 1},
	{"open",    "<view>",           "same as view",                                 1},
	{"qa",      "",                 "quit",                                         0},
	{"wq",      "",                 "quit (state is always saved)",                 0},
};

typedef struct Completion Completion;
struct Completion {
	String8 text;
	String8 detail;
	u32     from;   // where in the input the completed token starts
	char    suffix; // appended on accept: ' ' or '=' when an argument follows, 0 otherwise
};

#define UI_MAX_COMPLETIONS 64

// NOTE: 2 = prefix, 1 = somewhere inside, 0 = no match. case insensitive.
internal u32 completion_match(const char *candidate, const char *token, u32 token_size)
{
	String8 c = str8((char *)candidate);
	if(token_size == 0) return 2;
	if(c.size >= token_size && strncasecmp(candidate, token, token_size) == 0) return 2;
	return str8_contains_nocase(c, token, token_size) ? 1 : 0;
}

typedef struct CompletionList CompletionList;
struct CompletionList {
	Completion items[UI_MAX_COMPLETIONS];
	u32        count;
	u32        from;
	const char *token;
	u32        token_size;
	u32        pass;   // 2 = collecting prefix matches, 1 = substring matches
};

internal void completion_add(CompletionList *list, const char *text, String8 detail, char suffix)
{
	if(list->count >= UI_MAX_COMPLETIONS || completion_match(text, list->token, list->token_size) != list->pass) return;
	Completion *item = &list->items[list->count++];
	item->text   = str8((char *)text);
	item->detail = detail;
	item->from   = list->from;
	item->suffix = suffix;
}

internal const CommandDesc *command_resolve(const char *word, u32 size)
{
	const CommandDesc *found = NULL;
	u32                hits  = 0;
	for(u32 index = 0; index < ArrayCount(ui_commands); ++index) {
		if(strlen(ui_commands[index].name) == size && !strncmp(ui_commands[index].name, word, size)) return &ui_commands[index];
		if(!strncmp(ui_commands[index].name, word, size)) { found = &ui_commands[index]; ++hits; }
	}
	return (hits == 1) ? found : NULL;
}

internal SettingDesc *setting_resolve(const char *name, u32 size)
{
	SettingDesc *found = NULL;
	u32          hits  = 0;
	for(u32 index = 0; index < settings_desc_count(); ++index) {
		SettingDesc *desc = settings_desc(index);
		if(desc->kind == SETTING_KIND_SECTION || desc->kind == SETTING_KIND_ACTION || desc->kind == SETTING_KIND_INFO) continue;
		if(strlen(desc->name) == size && !strncasecmp(desc->name, name, size)) return desc;
		if(!strncasecmp(desc->name, name, size)) { found = desc; ++hits; }
	}
	return (hits == 1) ? found : NULL;
}

internal u32 command_completions(App *app, Arena *arena, CompletionList *list)
{
	char text[65];
	MemCpy(text, app->input, app->input_size);
	text[app->input_size] = 0;
	list->count = 0;

	const char *space = strchr(text, ' ');
	for(list->pass = 2; list->pass >= 1; --list->pass) {
		if(!space) {
			//- the command itself
			list->from       = 0;
			list->token      = text;
			list->token_size = app->input_size;
			for(u32 index = 0; index < ArrayCount(ui_commands); ++index) {
				const CommandDesc *command = &ui_commands[index];
				completion_add(list, command->name, ui_format(arena, "%-15s %s", command->args, command->help), command->takes_arg ? ' ' : 0);
			}
			continue;
		}

		const CommandDesc *command = command_resolve(text, (u32)(space - text));
		const char        *rest    = space + 1;
		if(!command) break;

		if(!strcmp(command->name, "view") || !strcmp(command->name, "e") || !strcmp(command->name, "open") || !strcmp(command->name, "vs") || !strcmp(command->name, "sp")) {
			list->from       = (u32)(rest - text);
			list->token      = rest;
			list->token_size = (u32)strlen(rest);
			ViewType types[UI_MAX_VIEW_TYPES];
			u32      types_count = view_types(types);
			for(u32 index = 0; index < types_count; ++index) {
				View probe  = {};
				probe.kind  = types[index].kind;
				probe.group = types[index].group;
				completion_add(list, types[index].name, view_title(arena, &probe), 0);
			}
		} else if(!strcmp(command->name, "set")) {
			const char *equals = strchr(rest, '=');
			if(!equals) {
				//- setting names, with their current value
				list->from       = (u32)(rest - text);
				list->token      = rest;
				list->token_size = (u32)strlen(rest);
				for(u32 index = 0; index < settings_desc_count(); ++index) {
					SettingDesc *desc = settings_desc(index);
					if(desc->kind == SETTING_KIND_SECTION || desc->kind == SETTING_KIND_ACTION || desc->kind == SETTING_KIND_INFO) continue;
					String8 value = settings_format(arena, &app->settings, desc);
					completion_add(list, desc->name, ui_format(arena, "%-20.*s %s", Str8Arg(value), desc->note ? desc->note : ""), '=');
				}
			} else {
				//- values for that setting
				SettingDesc *desc = setting_resolve(rest, (u32)(equals - rest));
				if(!desc) break;
				list->from       = (u32)(equals + 1 - text);
				list->token      = equals + 1;
				list->token_size = (u32)strlen(equals + 1);
				switch(desc->kind) {
					case SETTING_KIND_BOOL: {
						completion_add(list, "on", str8_zero(), 0);
						completion_add(list, "off", str8_zero(), 0);
					} break;
					case SETTING_KIND_ENUM:
					case SETTING_KIND_CHOICE: {
						for(u32 index = 0; index < desc->count; ++index) completion_add(list, desc->names[index], str8_zero(), 0);
					} break;
					case SETTING_KIND_FONT: {
						for(u32 index = 0; index < UI_FONT_CHOICES; ++index) {
							if(index < ArrayCount(ui_fonts) && font_installed(index)) completion_add(list, ui_fonts[index].name, str8_zero(), 0);
						}
					} break;
					default: {
						// numbers and colors: offer the current value to edit from
						String8 value = settings_format(arena, &app->settings, desc);
						char   *copy  = PushArray(arena, char, value.size + 1);
						MemCpy(copy, value.data, value.size);
						copy[value.size] = 0;
						for(char *at = copy; *at; ++at) if(*at == '%') *at = 0; // "80%" -> "80"
						completion_add(list, copy, str8("current value"), 0);
					} break;
				}
			}
		} else if(!strcmp(command->name, "vol") || !strcmp(command->name, "zoom")) {
			list->from       = (u32)(rest - text);
			list->token      = rest;
			list->token_size = (u32)strlen(rest);
			char *value = PushArray(arena, char, 16);
			if(!strcmp(command->name, "vol")) snprintf(value, 16, "%.0f", app->settings.volume * 100.0f);
			else snprintf(value, 16, "%.2f", app->settings.zoom);
			completion_add(list, value, str8("current value"), 0);
		}
	}
	return list->count;
}

internal void command_accept_completion(App *app, Completion *item)
{
	u32 size = Min(item->from, (u32)sizeof(app->input) - 1);
	u32 take = (u32)Min(item->text.size, (u64)(sizeof(app->input) - 1 - size));
	MemCpy(app->input + size, item->text.data, take);
	size += take;
	if(item->suffix && size < sizeof(app->input) - 1) app->input[size++] = item->suffix;
	app->input_size    = size;
	app->result_cursor = 0;
}

internal void command_run(App *app)
{
	char text[65];
	MemCpy(text, app->input, app->input_size);
	text[app->input_size] = 0;
	char *arg = strchr(text, ' ');
	if(arg) {
		*arg++ = 0;
		while(*arg == ' ') ++arg;
	}
	const CommandDesc *resolved = (text[0] && !(text[0] >= '0' && text[0] <= '9')) ? command_resolve(text, (u32)strlen(text)) : NULL;
	if(resolved) snprintf(text, sizeof(text), "%s", resolved->name);

	if(!strcmp(text, "q") || !strcmp(text, "q!") || !strcmp(text, "qa") || !strcmp(text, "wq") || !strcmp(text, "x")) {
		app->quit = true;
	} else if(text[0] >= '0' && text[0] <= '9') {
		u32 number = (u32)atoi(text);
		if(number >= 1 && number <= SURAH_COUNT) {
			app->jump_back              = app_place(app);
			app->surah                  = (s32)number - 1;
			app->keep_selection_visible = true;
			layout_open(&app->layout, VIEW_SURAHS);
		}
	} else if((!strcmp(text, "view") || !strcmp(text, "e") || !strcmp(text, "open") || !strcmp(text, "vs") || !strcmp(text, "sp")) && arg && arg[0]) {
		ViewType type;
		if(view_resolve(arg, &type)) {
			if(!strcmp(text, "vs")) layout_split_with(&app->layout, (ViewKind)type.kind, 0, type.group);
			else if(!strcmp(text, "sp")) layout_split_with(&app->layout, (ViewKind)type.kind, 1, type.group);
			else layout_open(&app->layout, (ViewKind)type.kind, type.group);
			return;
		}
		app_message(app, "no view called %s (:view views lists them all)", arg);
	} else if(!strcmp(text, "vol") && arg) {
		app_set_volume(app, (f32)atof(arg) / 100.0f);
	} else if(!strcmp(text, "zoom") && arg) {
		app->settings.zoom = (f32)atof(arg);
		app_apply_settings(app);
	} else if(!strcmp(text, "set") && arg) {
		if(settings_set(&app->settings, arg)) app_apply_settings(app);
		else app_message(app, "unknown setting or value: %s", arg);
	} else if(!strcmp(text, "columns") || !strcmp(text, "cols")) {
		s32 view = panel_active_view(&app->layout, app->layout.focused);
		if(view >= 0) app->layout.views[view].column_count = 0; // set up again from the defaults
	} else if(!strcmp(text, "reset")) {
		ui_layout_default(&app->layout);
	} else if(!strcmp(text, "dl") || !strcmp(text, "download")) {
		if(app->qari >= 0) app_message(app, "queued %u surahs", store_request_qari(app->store, (u32)app->qari));
	} else if(text[0]) {
		app_message(app, "not a command: %s", text);
	}
}

internal void draw_overlay(App *app, PlatformInput *input, Rect window)
{
	if(app->overlay == UI_OVERLAY_NONE) return;
	DrawList    *d       = &app->draw;
	FontSystem  *fonts   = &app->fonts;
	ScratchArena scratch = ScratchGet();

	CompletionList *completions = NULL;
	u32             shown       = (app->overlay == UI_OVERLAY_SEARCH) ? Min(app->result_count, 12u) : 0;
	if(app->overlay == UI_OVERLAY_COMMAND) {
		completions        = PushStruct(scratch.arena, CompletionList);
		u32 count          = command_completions(app, scratch.arena, completions);
		app->result_cursor = (count == 0) ? 0 : Clamp(app->result_cursor, 0, (s32)count - 1);
		shown              = Min(count, 12u);
	}
	f32  w     = Min(560.0f, rect_w(window) - 40);
	f32  h     = 40 + (f32)shown * UI_ROW_H + (shown ? 6 : 0);
	Rect box   = {window.x0 + (rect_w(window) - w) * 0.5f, window.y0 + rect_h(window) * 0.18f, 0, 0};
	box.x1     = box.x0 + w;
	box.y1     = box.y0 + h;

	draw_rect(d, window, 0x00000066u, 0);
	draw_shadow(d, box, 0x000000AAu, 0, 18);
	draw_rect(d, box, COLOR_TAB_ACTIVE, 0);
	draw_border(d, box, COLOR_FOCUS_EDGE, 0, 1);

	String8 label = str8(app->search_backward ? "?" : "/");
	if(app->overlay == UI_OVERLAY_COMMAND) label = str8(":");
	if(app->overlay == UI_OVERLAY_CONFIRM) {
		label = ui_format(scratch.arena, "delete every downloaded surah of " Str8Fmt "?  y / n", Str8Arg(app->catalog->qaris[app->confirm_qari].name));
	} else if(app->overlay == UI_OVERLAY_EDIT) {
		View *view = &app->layout.views[app->edit_view];
		Row   row  = {app->edit_field, 0, (u8)(view->kind == VIEW_PLAYING ? ROW_FIELD : ROW_SETTING), 0, 0, 0};
		Cells cells;
		view_cells(app, view, &row, &cells, scratch.arena);
		label = ui_format(scratch.arena, Str8Fmt " = ", Str8Arg(cells.text[0]));
	}

	f32 size     = UI_FONT + 1;
	f32 baseline = ui_baseline(app, FONT_MONO, size, box.y0, 40);
	f32 lw       = draw_text(d, fonts, FONT_MONO, size, box.x0 + 14, baseline, label, COLOR_TEXT_DIM);
	if(app->overlay != UI_OVERLAY_CONFIRM) {
		f32 tw = draw_text(d, fonts, FONT_MONO, size, box.x0 + 14 + lw, baseline, ToString8Size(app->input, app->input_size), COLOR_TEXT);
		if(fmodf(app->time, 1.0f) < 0.6f) draw_rect(d, Rect{box.x0 + 15 + lw + tw, box.y0 + 11, box.x0 + 23 + lw + tw, box.y0 + 29}, 0xFFFFFF99u, 0);
		app->animating = true;
	}

	f32 y = box.y0 + 40;
	if(completions) {
		// NOTE: keep the highlighted row inside the 12 we show
		u32 first = (app->result_cursor >= (s32)shown) ? (u32)app->result_cursor - shown + 1 : 0;
		for(u32 row = 0; row < shown; ++row) {
			u32         index = first + row;
			Completion *item  = &completions->items[index];
			Rect        rect  = {box.x0 + 4, y, box.x1 - 4, y + UI_ROW_H};
			if((s32)index == app->result_cursor) draw_rect(d, rect, COLOR_SELECTED, 0);
			if(ui_clicked(input, rect)) command_accept_completion(app, item);
			f32 b    = ui_baseline(app, FONT_MONO, UI_FONT, y, UI_ROW_H);
			f32 name = draw_text(d, fonts, FONT_MONO, UI_FONT, rect.x0 + 10, b, item->text, COLOR_TEXT);
			f32 dx   = Max(name + 24, rect_w(rect) * 0.32f);
			draw_text_fit(d, fonts, FONT_MONO, UI_FONT_SMALL, rect.x0 + dx, b, rect_w(rect) - dx - 10, item->detail, COLOR_TEXT_DIM);
			y += UI_ROW_H;
		}
		shown = 0; // the search rows below don't apply
	}
	for(u32 index = 0; index < shown; ++index) {
		SearchResult *result = &app->results[index];
		Rect          rect   = {box.x0 + 4, y, box.x1 - 4, y + UI_ROW_H};
		if((s32)index == app->result_cursor) draw_rect(d, rect, COLOR_SELECTED, 0);
		if(ui_clicked(input, rect)) {
			search_accept(app, *result);
			app->overlay = UI_OVERLAY_NONE;
		}
		String8 kind, name;
		if(result->qari != UINT32_MAX) {
			kind = str8("reciter");
			name = app->catalog->qaris[result->qari].name;
		} else {
			Surah *surah = &app->catalog->surahs[result->surah];
			kind         = str8("surah");
			name         = ui_format(scratch.arena, "%u. " Str8Fmt "  (" Str8Fmt ")", result->surah + 1, Str8Arg(surah->name), Str8Arg(surah->english));
		}
		f32 b = ui_baseline(app, FONT_REGULAR, UI_FONT, y, UI_ROW_H);
		draw_text(d, fonts, FONT_MONO, UI_FONT_SMALL, rect.x0 + 10, b, kind, COLOR_TEXT_FAINT);
		draw_text_fit(d, fonts, FONT_REGULAR, UI_FONT, rect.x0 + 80, b, rect_w(rect) - 90, name, COLOR_TEXT);
		y += UI_ROW_H;
	}
	scratch_end(&scratch);
}

//- keyboard

internal View *focused_view(App *app)
{
	s32 view = panel_active_view(&app->layout, app->layout.focused);
	return view >= 0 ? &app->layout.views[view] : NULL;
}

// NOTE: n / N: the next row in the focused view whose text matches the last search
internal void search_repeat(App *app, b32 reverse)
{
	View *view = focused_view(app);
	if(!view || app->last_search_size == 0) return;
	ScratchArena scratch = ScratchGet();
	Row *rows  = PushArray(scratch.arena, Row, UI_MAX_ROWS);
	u32  count = view_rows(app, view, rows, UI_MAX_ROWS);
	s32  start = view_cursor(app, view, rows, count);
	s32  step  = (reverse != app->last_search_backward) ? -1 : 1;
	Cells cells;
	for(u32 n = 1; n <= count; ++n) {
		s32 index = (s32)((start + step * (s32)n + (s32)count * 2) % (s32)count);
		view_cells(app, view, &rows[index], &cells, scratch.arena);
		b32 hit = false;
		for(u32 c = 0; c < 3 && !hit; ++c) hit = str8_contains_nocase(cells.text[c], app->last_search, app->last_search_size);
		if(hit) {
			if((step > 0) != (index > start)) app_message(app, step > 0 ? "search hit BOTTOM, continuing at TOP" : "search hit TOP, continuing at BOTTOM");
			view_set_cursor(app, view, rows, count, index);
			break;
		}
	}
	scratch_end(&scratch);
}

internal void ui_keyboard_overlay(App *app, PlatformInput *input)
{
	for(u32 index = 0; index < input->key_count; ++index) {
		PlatformKeyEvent *event = &input->keys[index];
		u32 sym  = event->keysym;
		b32 ctrl = (event->mods & PLATFORM_MOD_CTRL) != 0;

		if(app->overlay == UI_OVERLAY_CONFIRM) {
			if(sym == XKB_KEY_y || sym == XKB_KEY_Y) app_delete_qari(app, app->confirm_qari);
			app->overlay = UI_OVERLAY_NONE;
			return;
		}
		if(sym == XKB_KEY_Escape || (ctrl && (sym == XKB_KEY_bracketleft || sym == XKB_KEY_c))) {
			app->overlay = UI_OVERLAY_NONE;
			return;
		}
		if(sym == XKB_KEY_Return || sym == XKB_KEY_KP_Enter) {
			UIOverlay overlay = app->overlay;
			app->overlay      = UI_OVERLAY_NONE;
			if(overlay == UI_OVERLAY_SEARCH) {
				MemCpy(app->last_search, app->input, app->input_size);
				app->last_search_size     = app->input_size;
				app->last_search_backward = app->search_backward;
				if(app->result_count > 0) search_accept(app, app->results[app->result_cursor]);
			} else if(overlay == UI_OVERLAY_COMMAND) {
				command_run(app);
			} else if(overlay == UI_OVERLAY_EDIT) {
				edit_accept(app);
			}
			return;
		}
		if(sym == XKB_KEY_BackSpace) {
			if(app->input_size == 0 && app->overlay != UI_OVERLAY_EDIT) {
				app->overlay = UI_OVERLAY_NONE;
				return;
			}
			while(app->input_size > 0) {
				u8 c = (u8)app->input[--app->input_size];
				if((c & 0xC0) != 0x80) break;
			}
		}
		if(ctrl && sym == XKB_KEY_u) app->input_size = 0;
		if(ctrl && sym == XKB_KEY_w) {
			while(app->input_size > 0 && app->input[app->input_size - 1] == ' ') --app->input_size;
			while(app->input_size > 0 && app->input[app->input_size - 1] != ' ') --app->input_size;
		}
		if(app->overlay == UI_OVERLAY_COMMAND) {
			ScratchArena    scratch = ScratchGet();
			CompletionList *list    = PushStruct(scratch.arena, CompletionList);
			u32             count   = command_completions(app, scratch.arena, list);
			if(sym == XKB_KEY_Tab && count) {
				command_accept_completion(app, &list->items[Clamp(app->result_cursor, 0, (s32)count - 1)]);
			}
			s32 step = 0;
			if(sym == XKB_KEY_Down || (ctrl && (sym == XKB_KEY_n || sym == XKB_KEY_j))) step = 1;
			if(sym == XKB_KEY_Up || sym == XKB_KEY_ISO_Left_Tab || (ctrl && (sym == XKB_KEY_p || sym == XKB_KEY_k))) step = -1;
			if(step && count) app->result_cursor = (app->result_cursor + step + (s32)count) % (s32)count;
			if(sym == XKB_KEY_BackSpace || (ctrl && (sym == XKB_KEY_u || sym == XKB_KEY_w))) app->result_cursor = 0;
			scratch_end(&scratch);
			continue;
		}
		s32 move = 0;
		if(sym == XKB_KEY_Down || sym == XKB_KEY_Tab || (ctrl && (sym == XKB_KEY_n || sym == XKB_KEY_j))) move = 1;
		if(sym == XKB_KEY_Up || sym == XKB_KEY_ISO_Left_Tab || (ctrl && (sym == XKB_KEY_p || sym == XKB_KEY_k))) move = -1;
		if(move && app->result_count) app->result_cursor = (app->result_cursor + move + (s32)app->result_count) % (s32)app->result_count;
	}

	if(!app->overlay_opened && input->text_size > 0) {
		u32 take = Min((u32)sizeof(app->input) - 1 - app->input_size, input->text_size);
		MemCpy(app->input + app->input_size, input->text, take);
		app->input_size += take;
		if(app->overlay == UI_OVERLAY_COMMAND) app->result_cursor = 0; // typing narrows the list, start at the top
	}
	if(app->overlay == UI_OVERLAY_SEARCH) search_update(app);
}

internal void ui_keyboard(App *app, PlatformInput *input)
{
	if(app->overlay != UI_OVERLAY_NONE) {
		ui_keyboard_overlay(app, input);
		app->overlay_opened = false;
		return;
	}

	// NOTE: most frames carry no keys: don't build the focused view's rows just to look at nothing
	if(input->key_count == 0) {
		return;
	}

	View        *view    = focused_view(app);
	ScratchArena scratch = ScratchGet();
	Row         *rows    = PushArray(scratch.arena, Row, UI_MAX_ROWS);
	u32          count   = view ? view_rows(app, view, rows, UI_MAX_ROWS) : 0;

	for(u32 index = 0; index < input->key_count && app->overlay == UI_OVERLAY_NONE; ++index) {
		PlatformKeyEvent *event   = &input->keys[index];
		u32               sym     = event->keysym;
		b32               ctrl    = (event->mods & PLATFORM_MOD_CTRL) != 0;
		u32               pending = app->pending;
		u32               n       = app->count ? app->count : 1;
		s32               cursor  = view ? view_cursor(app, view, rows, count) : 0;
		s32               page    = view ? Max((s32)view->visible_rows, 1) : 10;
		Row              *row     = (view && count) ? &rows[Clamp(cursor, 0, (s32)count - 1)] : NULL;

		// NOTE: modifiers on their own are not keys
		if(sym == XKB_KEY_Shift_L || sym == XKB_KEY_Shift_R || sym == XKB_KEY_Control_L || sym == XKB_KEY_Control_R ||
		   sym == XKB_KEY_Alt_L || sym == XKB_KEY_Alt_R || sym == XKB_KEY_Super_L || sym == XKB_KEY_Super_R) {
			continue;
		}
		app->pending = 0;

		//- second key of a two key command
		if(pending) {
			Layout *layout = &app->layout;
			if(pending == 'g') {
				if(sym == XKB_KEY_g && view) {
					app->jump_back = app_place(app);
					view_set_cursor(app, view, rows, count, app->count ? (s32)app->count - 1 : 0);
				}
				if(sym == XKB_KEY_t || sym == XKB_KEY_T) {
					Panel *p = &layout->panels[layout->focused];
					if(p->tab_count) p->active_tab = (p->active_tab + (sym == XKB_KEY_t ? 1 : p->tab_count - 1)) % p->tab_count;
				}
			} else if(pending == 'z' && view) {
				f32 y = (f32)cursor * UI_ROW_H, h = (f32)view->visible_rows * UI_ROW_H;
				if(sym == XKB_KEY_z) view->scroll.target = y - h * 0.5f;
				if(sym == XKB_KEY_t) view->scroll.target = y;
				if(sym == XKB_KEY_b) view->scroll.target = y - h + UI_ROW_H;
			} else if(pending == 'd' && sym == XKB_KEY_d && row && view->kind == VIEW_QUEUE) {
				queue_remove(app, row_track_key(row));
			} else if(pending == 'd' && sym == XKB_KEY_d && row) {
				if(row_track_key(row) != TRACK_NONE) app_delete(app, row_track_key(row));
				else app_message(app, "dd works on surahs, D removes a whole reciter");
			} else if(pending == 'y' && sym == XKB_KEY_y && row) {
				if(row->kind == ROW_QARI) app_message(app, "queued %u surahs", store_request_qari(app->store, row->a));
				else app_download(app, row_track_key(row) != TRACK_NONE ? row_track_key(row) : app_selected_key(app));
			} else if(pending == 'm') {
				if(sym >= XKB_KEY_a && sym <= XKB_KEY_z) {
					app->marks[sym - XKB_KEY_a] = app_place(app);
					app_message(app, "mark %c set", (char)('a' + sym - XKB_KEY_a));
				}
			} else if(pending == '\'' || pending == '`') {
				if(sym >= XKB_KEY_a && sym <= XKB_KEY_z) app_goto_place(app, app->marks[sym - XKB_KEY_a]);
				if(sym == XKB_KEY_apostrophe || sym == XKB_KEY_grave) app_goto_place(app, app->jump_back);
			} else if(pending == 'w') {
				switch(sym) {
					case XKB_KEY_h: case XKB_KEY_Left:  layout_focus_direction(layout, -1, 0); break;
					case XKB_KEY_l: case XKB_KEY_Right: layout_focus_direction(layout, 1, 0); break;
					case XKB_KEY_k: case XKB_KEY_Up:    layout_focus_direction(layout, 0, -1); break;
					case XKB_KEY_j: case XKB_KEY_Down:  layout_focus_direction(layout, 0, 1); break;
					case XKB_KEY_w: case XKB_KEY_W:     layout_focus_next(layout); break;
					case XKB_KEY_v: layout_split_focused(layout, 0); break;
					case XKB_KEY_s: layout_split_focused(layout, 1); break;
					case XKB_KEY_c: case XKB_KEY_q: {
						Panel *p = &layout->panels[layout->focused];
						if(p->tab_count) layout_close_view(layout, layout->focused, p->active_tab);
					} break;
					case XKB_KEY_equal: {
						for(s32 i = 0; i < UI_MAX_PANELS; ++i) if(layout->panels[i].kind == PANEL_SPLIT) layout->panels[i].ratio = 0.5f;
					} break;
				}
			}
			app->count = 0;
			// NOTE: layout or selection may have changed, rebuild the row list for the next key
			view  = focused_view(app);
			count = view ? view_rows(app, view, rows, UI_MAX_ROWS) : 0;
			continue;
		}

		//- count prefix
		if(!ctrl && ((sym >= XKB_KEY_1 && sym <= XKB_KEY_9) || (sym == XKB_KEY_0 && app->count))) {
			app->count = Min(app->count * 10 + (sym - XKB_KEY_0), 99999u);
			continue;
		}

		//- zoom
		if(ctrl && (sym == XKB_KEY_equal || sym == XKB_KEY_plus)) { app->settings.zoom += 0.1f; app_apply_settings(app); continue; }
		if(ctrl && sym == XKB_KEY_minus) { app->settings.zoom -= 0.1f; app_apply_settings(app); continue; }
		if(ctrl && sym == XKB_KEY_0) { app->settings.zoom = UI_ZOOM_DEFAULT; app_apply_settings(app); continue; }

		s32 motion = INT32_MIN; // new cursor row when this key is a motion
		if(ctrl) {
			switch(sym) {
				case XKB_KEY_d: motion = cursor + (s32)n * page / 2; break;
				case XKB_KEY_u: motion = cursor - (s32)n * page / 2; break;
				case XKB_KEY_f: motion = cursor + (s32)n * page; break;
				case XKB_KEY_b: motion = cursor - (s32)n * page; break;
				case XKB_KEY_n: motion = cursor + (s32)n; break;
				case XKB_KEY_p: motion = cursor - (s32)n; break;
				case XKB_KEY_e: {
					if(view) {
						view->scroll.target += UI_ROW_H * n;
						motion = Max(cursor, (s32)view->first_visible + (s32)n + 1);
					}
				} break;
				case XKB_KEY_y: {
					if(view) {
						view->scroll.target -= UI_ROW_H * n;
						motion = Min(cursor, (s32)(view->first_visible + view->visible_rows) - (s32)n - 2);
					}
				} break;
				case XKB_KEY_w: app->pending = 'w'; continue;
				// NOTE: panels directly, without the ^w prefix
				case XKB_KEY_h: case XKB_KEY_Left:  layout_focus_direction(&app->layout, -1, 0); break;
				case XKB_KEY_l: case XKB_KEY_Right: layout_focus_direction(&app->layout, 1, 0); break;
				case XKB_KEY_k: case XKB_KEY_Up:    layout_focus_direction(&app->layout, 0, -1); break;
				case XKB_KEY_j: case XKB_KEY_Down:  layout_focus_direction(&app->layout, 0, 1); break;
				case XKB_KEY_Tab:                   layout_cycle_views(&app->layout, 1); break;
				case XKB_KEY_ISO_Left_Tab:          layout_cycle_views(&app->layout, -1); break; // ctrl-shift-tab
			}
		} else {
			switch(sym) {
				case XKB_KEY_j: case XKB_KEY_Down: motion = cursor + (s32)n; break;
				case XKB_KEY_k: case XKB_KEY_Up:   motion = cursor - (s32)n; break;
				case XKB_KEY_G: case XKB_KEY_End: {
					app->jump_back = app_place(app);
					motion         = app->count ? (s32)app->count - 1 : (s32)count - 1;
				} break;
				case XKB_KEY_Home: motion = 0; break;
				case XKB_KEY_Page_Down: motion = cursor + page; break;
				case XKB_KEY_Page_Up: motion = cursor - page; break;
				case XKB_KEY_H: if(view) motion = (s32)view->first_visible + (s32)(app->count ? app->count - 1 : 0); break;
				case XKB_KEY_M: if(view) motion = (s32)view->first_visible + (s32)Min(view->visible_rows, count - view->first_visible) / 2; break;
				case XKB_KEY_L: if(view) motion = (s32)(view->first_visible + Min(view->visible_rows, count - view->first_visible)) - 1 - (s32)(app->count ? app->count - 1 : 0); break;

				case XKB_KEY_y: case XKB_KEY_d: {
					// NOTE: in visual mode y / d act on the selection right away, like vim operators
					if(app->visual || app->selected_count) {
						if(view) visual_commit(app, view, rows, count);
						u32 *keys = PushArray(scratch.arena, u32, app->selected_count + 1);
						u32  n    = selection_keys(app, keys, app->selected_count);
						for(u32 i = 0; i < n; ++i) {
							if(sym == XKB_KEY_y) store_request(app->store, keys[i], false);
							else if(keys[i] != app_current_key(app)) store_delete(app->store, keys[i]);
						}
						app_message(app, sym == XKB_KEY_y ? "downloading %u surahs" : "deleted %u surahs from disk", n);
						selection_clear(app);
						break;
					}
					app->pending = (u32)('a' + (sym - XKB_KEY_a));
					continue;
				}
				case XKB_KEY_g: case XKB_KEY_z: case XKB_KEY_m: {
					app->pending = (u32)('a' + (sym - XKB_KEY_a));
					continue;
				}
				case XKB_KEY_v: {
					// NOTE: v toggles the row, V starts a range (V again keeps it, esc drops it)
					if(row && row_track_key(row) != TRACK_NONE) track_select(app, row_track_key(row), !track_selected(app, row_track_key(row)));
				} break;
				case XKB_KEY_V: {
					if(!view) break;
					if(app->visual) {
						visual_commit(app, view, rows, count);
					} else {
						app->visual        = true;
						app->visual_anchor = cursor;
						app->visual_view   = (u32)(view - app->layout.views);
					}
				} break;
				case XKB_KEY_apostrophe: app->pending = '\''; continue;
				case XKB_KEY_grave: app->pending = '`'; continue;

				case XKB_KEY_l: case XKB_KEY_Right: {
					if(row && row->expandable && !row->expanded) view_set_expanded(view, row->a, true);
					else if(view && row && (view->kind == VIEW_PLAYING || view->kind == VIEW_SETTINGS)) view_adjust(app, view, row, 1);
					else if(sym == XKB_KEY_Right) app_seek_seconds(app, app->settings.seek_seconds);
				} break;
				case XKB_KEY_h: case XKB_KEY_Left: {
					if(view && row && view->kind == VIEW_OFFLINE) {
						if(row->expandable && row->expanded) view_set_expanded(view, row->a, false);
						else if(row->depth > 0) {
							for(s32 i = cursor; i >= 0; --i) {
								if(rows[i].depth == 0) { motion = i; break; }
							}
						}
					} else if(view && row && (view->kind == VIEW_PLAYING || view->kind == VIEW_SETTINGS)) {
						view_adjust(app, view, row, -1);
					} else if(sym == XKB_KEY_Left) {
						app_seek_seconds(app, -(f64)app->settings.seek_seconds);
					}
				} break;

				case XKB_KEY_Return: case XKB_KEY_KP_Enter: case XKB_KEY_o: case XKB_KEY_space: {
					// NOTE: with a selection, enter and space play it as a queue
					if(app->visual || app->selected_count) app_play_selection(app, view, rows, count);
					else if(sym == XKB_KEY_space) app_toggle_pause(app);
					else if(view && row) view_activate(app, view, row);
				} break;
				case XKB_KEY_x: {
					if(app->audio_ok) {
						decoder_command(app->decoder, DECODER_STOP, 0, 0);
						app->requested_key = TRACK_NONE;
					}
				} break;

				case XKB_KEY_slash: case XKB_KEY_question: {
					app->search_backward = (sym == XKB_KEY_question);
					overlay_open(app, UI_OVERLAY_SEARCH);
				} break;
				case XKB_KEY_colon: overlay_open(app, UI_OVERLAY_COMMAND); break;
				case XKB_KEY_n: for(u32 i = 0; i < n; ++i) search_repeat(app, false); break;
				case XKB_KEY_N: for(u32 i = 0; i < n; ++i) search_repeat(app, true); break;

				case XKB_KEY_Y: {
					if(row && (row->kind == ROW_SURAH || row->kind == ROW_QARI)) app_message(app, "queued %u surahs", store_request_qari(app->store, row->a));
				} break;
				case XKB_KEY_D: {
					u32 qari = (row && (row->kind == ROW_QARI || row->kind == ROW_SURAH)) ? row->a : (u32)Max(app->qari, 0);
					if(app->settings.confirm_delete) {
						app->confirm_qari = qari;
						overlay_open(app, UI_OVERLAY_CONFIRM);
					} else {
						app_delete_qari(app, qari);
					}
				} break;

				case XKB_KEY_less: case XKB_KEY_comma: app_step_track(app, -(s32)n); break;
				case XKB_KEY_greater: case XKB_KEY_period: app_step_track(app, (s32)n); break;
				case XKB_KEY_bracketleft:  app_seek_seconds(app, -(f64)app->settings.seek_seconds * n); break;
				case XKB_KEY_bracketright: app_seek_seconds(app, (f64)app->settings.seek_seconds * n); break;
				case XKB_KEY_braceleft:    app_seek_seconds(app, -(f64)app->settings.seek_seconds * app->settings.seek_big * n); break;
				case XKB_KEY_braceright:   app_seek_seconds(app, (f64)app->settings.seek_seconds * app->settings.seek_big * n); break;
				case XKB_KEY_plus: case XKB_KEY_equal: case XKB_KEY_KP_Add: app_set_volume(app, app->settings.volume + 0.05f * n); break;
				case XKB_KEY_minus: case XKB_KEY_KP_Subtract: app_set_volume(app, app->settings.volume - 0.05f * n); break;
				case XKB_KEY_a: {
					app->settings.autoplay = (app->settings.autoplay + 1) % 3;
					app_apply_settings(app);
					app_message(app, "autoplay: %s", autoplay_name(app->settings.autoplay));
				} break;
				case XKB_KEY_Tab: layout_focus_next(&app->layout); break;
				case XKB_KEY_q: app->quit = true; break;
				case XKB_KEY_Escape: {
					if(app->visual) app->visual = false;
					else if(app->selected_count) selection_clear(app);
					else app->message[0] = 0;
				} break;
			}
		}

		if(motion != INT32_MIN && view && count) {
			view_set_cursor(app, view, rows, count, Clamp(motion, 0, (s32)count - 1));
		}
		app->count = 0;
		view       = focused_view(app);
		count      = view ? view_rows(app, view, rows, UI_MAX_ROWS) : 0;
	}
	scratch_end(&scratch);
}


//- frame

// NOTE: fonts come from the settings. font files are loaded once into the host's arena (so they
// survive a hot reload) and only swapped into the font system when the choice actually changes.
internal String8 app_font_file(App *app, u32 choice)
{
	if(choice >= UI_FONT_CHOICES) return str8_zero();
	if(app->font_files[choice].size == 0 && access(font_choice(choice)->path, R_OK) == 0) {
		app->font_files[choice] = FileLoad(app->arena, str8((char *)font_choice(choice)->path));
	}
	return app->font_files[choice];
}

internal void ui_frame(App *app, PlatformInput *input_raw)
{
	app->animating    = false;
	app->ticking      = false;
	app->table_cursor = PLATFORM_CURSOR_DEFAULT;
	ui_settings       = &app->settings;
	ui_theme          = app->settings;

	font_set_data(&app->fonts, FONT_REGULAR, app_font_file(app, app->settings.font_ui));
	font_set_data(&app->fonts, FONT_SEMIBOLD, app_font_file(app, app->settings.font_bold));
	font_set_data(&app->fonts, FONT_MONO, app_font_file(app, app->settings.font_mono));

	// NOTE: zoom: the ui works in "ui units" = logical pixels / zoom. the draw list scales by
	// buffer scale * zoom, the font system rasterizes at that size, and mouse input is divided.
	f32 zoom = (app->settings.zoom > 0) ? app->settings.zoom : 1.0f;
	font_set_scale(&app->fonts, (f32)app->scale * zoom);
	PlatformInput input = *input_raw;
	input.mouse_x /= zoom;
	input.mouse_y /= zoom;

	if(!layout_valid(&app->layout)) ui_layout_default(&app->layout);

	// NOTE: per phase timing for the profiler. a clock read is a register read (cntvct), ~free
	u64 t_keys = time_now_ns();
	ui_keyboard(app, &input);
	if(app->quit) return;
	u64 t_keys_end = time_now_ns();

	f32  w      = (f32)app->width / zoom;
	f32  h      = (f32)app->height / zoom;
	Rect window = {0, 0, w, h};

	draw_begin(&app->draw, app->renderer.extent.width, app->renderer.extent.height, (f32)app->scale * zoom);
	app->draw.rounding   = 0.0f;
	app->draw.text_gamma = app->settings.text_gamma;
	// NOTE: a normal window is cleared to the background by the render pass already. the layer
	// surface clears transparent, so there the background is a real quad
	if(PlatformWindowIsLayer(app->window)) draw_rect(&app->draw, window, COLOR_BG, 0);

	Rect panels = {UI_GAP, UI_GAP, w - UI_GAP, h - UI_GAP};
	layout_compute(&app->layout, app->layout.root, panels);

	u64 t_panels = time_now_ns();
	draw_panels(app, &input);
	u64 t_status = time_now_ns();
	u64 t_overlay = t_status; // the footer is a view now, drawn with the panels
	draw_overlay(app, &input, window);
	u64 t_end = time_now_ns();
	if(app->profiler) {
		u64 spans[PROFILE_UI_PHASES] = {t_keys_end - t_keys, t_status - t_panels, t_overlay - t_status, t_end - t_overlay};
		for(u32 phase = 0; phase < PROFILE_UI_PHASES; ++phase) {
			f32 *us = &app->profiler->ui_phase_us[phase];
			*us += ((f32)spans[phase] / 1000.0f - *us) * 0.05f;
		}
	}

	app->keep_selection_visible = false;
	if(app_current_key(app) != TRACK_NONE && !app->paused) app->ticking = true;
	if(app->profiler && app->profiler->sampling) app->ticking = true;
}