taskbar-focus 0.6.0

A tiny Pomodoro/focus timer that lives in the Windows tray and toggles Do Not Disturb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
//! The settings window.
//!
//! Plain Win32 controls created in code - no resource script, no dialog
//! template - so the whole layout is readable in one place and needs no build
//! tooling. It is modeless: the timer keeps ticking while it is open, and the
//! status line at the bottom updates live.
//!
//! The window is a navigation list on the left and one page of settings on the
//! right. Every control is created once, hidden, and described by an [`Item`];
//! [`relayout`] then decides which items belong on screen - the selected page,
//! or everything matching the search box - and stacks them down the pane. That
//! is what lets the search box reach across pages without rebuilding anything.
//!
//! The window is drawn in the Windows 11 style with [`crate::ui::fluent`]. The
//! pane paints the cards, the icon at the left of each one and the frames of
//! the text boxes itself, since Windows has no control for any of them.
//! Checkboxes are drawn as switches and the footer buttons as Windows 11
//! buttons through custom draw, so they stay real controls: clicking, the
//! keyboard, their checked state and what screen readers say all keep working.

use windows::core::PCWSTR;
use windows::Win32::Foundation::{HWND, LPARAM, LRESULT, POINT, RECT, WPARAM};
use windows::Win32::Graphics::Gdi::{
    BeginPaint, BitBlt, CreateCompatibleBitmap, CreateCompatibleDC, CreateFontIndirectW,
    CreateSolidBrush, DeleteDC, DeleteObject, DrawTextW, EndPaint, FillRect, GetDC, InvalidateRect,
    PtInRect, RedrawWindow, ReleaseDC, SelectObject, SetBkColor, SetBkMode, SetTextColor,
    DT_CALCRECT, DT_CENTER, DT_END_ELLIPSIS, DT_LEFT, DT_NOPREFIX, DT_RIGHT, DT_SINGLELINE,
    DT_VCENTER, DT_WORDBREAK, HBRUSH, HDC, HFONT, LOGFONTW, PAINTSTRUCT, RDW_ALLCHILDREN,
    RDW_ERASE, RDW_INVALIDATE, SRCCOPY, TRANSPARENT,
};
use windows::Win32::System::LibraryLoader::GetModuleHandleW;
use windows::Win32::System::SystemServices::{SS_CENTER, SS_ENDELLIPSIS};
use windows::Win32::UI::Controls::{
    SetScrollInfo, BST_CHECKED, CDDS_PREPAINT, CDIS_FOCUS, CDIS_HOT, CDIS_SELECTED, CDRF_DODEFAULT,
    CDRF_SKIPDEFAULT, DRAWITEMSTRUCT, EM_LIMITTEXT, EM_SETCUEBANNER, EM_SETREADONLY, EM_SETSEL,
    NMCUSTOMDRAW, NM_CUSTOMDRAW, ODS_SELECTED, TOOLTIPS_CLASSW, TTF_IDISHWND, TTF_SUBCLASS,
    TTM_ADDTOOLW, TTM_SETMAXTIPWIDTH, TTS_ALWAYSTIP, TTTOOLINFOW, WC_BUTTONW, WC_COMBOBOXW,
    WC_EDITW, WC_LISTBOXW, WC_STATICW,
};
use windows::Win32::UI::Input::KeyboardAndMouse::{
    EnableWindow, GetCapture, GetFocus, IsWindowEnabled, ReleaseCapture, SetCapture, SetFocus,
    MOD_SHIFT, VIRTUAL_KEY, VK_BACK, VK_CONTROL, VK_DELETE, VK_DOWN, VK_ESCAPE, VK_LCONTROL,
    VK_LMENU, VK_LSHIFT, VK_LWIN, VK_MENU, VK_RCONTROL, VK_RMENU, VK_RSHIFT, VK_RWIN, VK_SHIFT,
    VK_TAB, VK_UP,
};
use windows::Win32::UI::WindowsAndMessaging::*;

use crate::config::{Config, LengthPreset, Preset, Shortcuts, WakePolicy};
use crate::lock::settings::{ClockTime, DayLock, LockSettings};
use crate::os::localtime::{day_halves, DAY_NAMES};
use crate::ui::app::App;
use crate::ui::fluent::{self, rect, rgb, Look, Shape};
use crate::ui::hotkeys;
use crate::ui::shortcuts::{self, Place};
use crate::ui::wide;

const CLASS: &str = "TaskbarFocusSettings";
const PANE_CLASS: &str = "TaskbarFocusSettingsPane";

const ID_SAVE: usize = 1;
const ID_CANCEL: usize = 2;
const ID_SAVE_AS: usize = 3;
const ID_DEFAULTS: usize = 4;

const ID_SEARCH: usize = 10;
const ID_NAV: usize = 11;
const ID_TITLE: usize = 12;
const ID_EMPTY: usize = 13;
const ID_STATUS: usize = 14;

const ID_PRESET: usize = 100;
const ID_NAME: usize = 101;
const ID_FOCUS: usize = 102;
const ID_SHORT: usize = 103;
const ID_LONG: usize = 104;
const ID_SESSIONS: usize = 105;

const ID_SEQUENCE: usize = 110;
const ID_AUTO_BREAK: usize = 111;
const ID_AUTO_FOCUS: usize = 112;
const ID_REPEAT_CYCLES: usize = 116;
const ID_STRICT: usize = 113;
const ID_RESTORE_SESSION: usize = 114;
const ID_WAKE: usize = 115;

const ID_DND: usize = 120;
const ID_DND_SHORT_BREAK: usize = 121;
const ID_MUTE_TRAY: usize = 122;
const ID_MUTE_WINDOW: usize = 123;
const ID_MINI: usize = 131;
const ID_TOPMOST: usize = 132;

const ID_NOTIFY: usize = 140;
const ID_N_FS: usize = 141;
const ID_N_FE: usize = 142;
const ID_N_BS: usize = 143;
const ID_N_BE: usize = 144;
const ID_ALERT_TOAST: usize = 145;
const ID_REQUIRE_DISMISS: usize = 146;
const ID_ALERT_OVERLAY: usize = 147;
const ID_ALERT_FLASH: usize = 148;
const ID_FLASH_LENGTH: usize = 149;

const ID_MUTE: usize = 150;
const ID_S_FS: usize = 151;
const ID_S_FE: usize = 152;
const ID_S_BS: usize = 153;
const ID_S_BE: usize = 154;

const ID_HOTKEYS: usize = 160;
const ID_HK_TOGGLE: usize = 161;
const ID_HK_SKIP: usize = 162;

/// The first of seven weekday checkboxes; the parts of each day's lock time
/// and its strict switch follow, seven of each.
const ID_LOCK_DAY: usize = 170;
const ID_LOCK_HOUR: usize = 180;
const ID_LOCK_STRICT: usize = 190;
const ID_LOCK_MINUTE: usize = 300;
/// The AM/PM drop-down, only there when Windows uses a 12-hour clock.
const ID_LOCK_HALF: usize = 310;
const ID_LOCK_NUMBER: usize = 200;
const ID_AUTOSTART: usize = 210;
const ID_KEYS: usize = 220;
/// The first of the shortcut fields, one for each of [`shortcuts::ALL`].
const ID_KEY: usize = 230;

/// A whole-number lock setting: its label, limits, and where it is stored.
struct LockNumber {
    label: &'static str,
    max: i64,
    min: i64,
    icon: &'static str,
    desc: &'static str,
    get: fn(&LockSettings) -> i64,
    set: fn(&mut LockSettings, i64),
}

/// The whole-number lock settings, in page order. Those from
/// [`FIRST_ADVANCED`] on go under Advanced.
const LOCK_NUMBERS: [LockNumber; 8] = [
    LockNumber {
        label: "Cutoff (minutes)",
        min: 0,
        max: 720,
        icon: "\u{E916}",
        desc: "How long before a lock it can no longer be postponed or skipped.",
        get: |s| s.cutoff_minutes,
        set: |s, v| s.cutoff_minutes = v,
    },
    LockNumber {
        label: "Postpone by (minutes)",
        min: 1,
        max: 240,
        icon: "\u{E823}",
        desc: "How much one postponement adds to the lock time.",
        get: |s| s.postpone_minutes,
        set: |s, v| s.postpone_minutes = v,
    },
    LockNumber {
        label: "Postponements per day",
        min: 0,
        max: 10,
        icon: "\u{E9D5}",
        desc: "How often one day's lock can be postponed.",
        get: |s| s.max_postponements,
        set: |s, v| s.max_postponements = v,
    },
    LockNumber {
        label: "Locked period (minutes)",
        min: 0,
        max: 120,
        icon: "\u{E72E}",
        desc: "Unlocking sooner locks the PC again. 0 locks once.",
        get: |s| s.locked_minutes,
        set: |s, v| s.locked_minutes = v,
    },
    LockNumber {
        label: "Warn before cutoff (min)",
        min: 0,
        max: 120,
        icon: "\u{EA8F}",
        desc: "0 shows no warning before the cutoff.",
        get: |s| s.warn_before_cutoff_minutes,
        set: |s, v| s.warn_before_cutoff_minutes = v,
    },
    LockNumber {
        label: "Warn before lock (min)",
        min: 0,
        max: 30,
        icon: "\u{EA8F}",
        desc: "No longer than the cutoff. 0 shows no warning.",
        get: |s| s.warn_before_lock_minutes,
        set: |s, v| s.warn_before_lock_minutes = v,
    },
    LockNumber {
        label: "Return window (minutes)",
        min: 0,
        max: 240,
        icon: "\u{E81C}",
        desc: "Returning this long after a missed lock still locks the PC.",
        get: |s| s.return_window_minutes,
        set: |s, v| s.return_window_minutes = v,
    },
    LockNumber {
        label: "Relock delay (seconds)",
        min: 5,
        max: 300,
        icon: "\u{E916}",
        desc: "Time between unlocking too early and locking again.",
        get: |s| s.relock_delay_seconds,
        set: |s, v| s.relock_delay_seconds = v,
    },
];
const FIRST_ADVANCED: usize = 4;

/// The pages, in the order they appear in the navigation list.
const PAGES: [&str; 9] = [
    "General",
    "Timer",
    "Sequence",
    "Notifications",
    "Do Not Disturb",
    "Sounds",
    "Timer window",
    "Hotkeys",
    "PC lock",
];

const PAGE_GENERAL: usize = 0;
const PAGE_TIMER: usize = 1;
const PAGE_SEQUENCE: usize = 2;
const PAGE_NOTIFICATIONS: usize = 3;
const PAGE_DND: usize = 4;
const PAGE_SOUNDS: usize = 5;
const PAGE_WINDOW: usize = 6;
const PAGE_HOTKEYS: usize = 7;
const PAGE_LOCK: usize = 8;

const CLIENT_W: i32 = 900;
const CLIENT_H: i32 = 640;
const PAD: i32 = 4;
const SIDEBAR_W: i32 = 248;
const NAV_ROW: i32 = 36;
const NAV_Y: i32 = 72;
/// The search box's frame, which is painted around a borderless edit control.
const SEARCH_BOX: RECT = rect(12, 20, SIDEBAR_W - 12, 52);
const CONTENT_X: i32 = SIDEBAR_W + 4;
const TITLE_Y: i32 = 20;
/// Where the current page's icon is painted, at the left of its title.
const TITLE_ICON: RECT = rect(CONTENT_X, TITLE_Y, CONTENT_X + 32, TITLE_Y + 40);
const PANE_Y: i32 = 76;
const FOOTER_H: i32 = 64;
const FOOTER_Y: i32 = CLIENT_H - FOOTER_H;
const PANE_W: i32 = CLIENT_W - CONTENT_X - 8;
const PANE_H: i32 = FOOTER_Y - PANE_Y;
/// Usable width inside the pane, leaving room for the scroll bar.
const ITEM_W: i32 = PANE_W - 17 - 20;
/// Width a caption is created with; layout gives it its real width.
const CAP_W: i32 = 300;
/// Left edge of a card's icon.
const CARD_X: i32 = 16;
/// Least space above and below the contents of a card.
const CARD_Y: i32 = 14;
/// Left edge of a card's caption and description.
const TEXT_X: i32 = 56;
/// Width of a text box or a drop-down at the right of a card.
const FIELD_W: i32 = 200;
/// Width of a switch together with its On or Off.
const SWITCH_CTL_W: i32 = 92;
/// Height of a text box, a drop-down or a switch's control.
const FIELD_H: i32 = 32;
/// Height of the text line inside a text box.
const EDIT_H: i32 = 20;
/// Width of the hour or minute box of a lock time, arrows included.
const CLOCK_W: i32 = 66;
/// Width of the up and down chevrons inside an hour or minute box.
const SPIN_W: i32 = 18;
/// The timer that repeats a held chevron.
const SPIN_TIMER: usize = 1;
/// How long a chevron must be held before it repeats, and how often it then
/// repeats, in milliseconds.
const SPIN_DELAY: u32 = 400;
const SPIN_REPEAT: u32 = 60;
/// Width of the colon between the hour and the minutes.
const COLON_W: i32 = 12;
/// Width of the AM/PM drop-down.
const HALF_W: i32 = 76;
/// Space between neighbouring cards.
const GAP: i32 = 4;
/// Extra left inset of an option nested under the switch that governs it.
const INDENT: i32 = 32;
/// Added to a control's id to give its caption, and its description, an id of
/// their own, so they can be greyed out with it.
const CAPTION_ID: usize = 10_000;
const DESC_ID: usize = 20_000;

/// The icon for each page, in the same order as [`PAGES`]: gear, stopwatch,
/// repeat, bell, moon, speaker, monitor, keyboard, padlock.
const PAGE_ICONS: [&str; 9] = [
    "\u{E713}", "\u{E916}", "\u{E8EE}", "\u{EA8F}", "\u{E708}", "\u{E767}", "\u{E7F4}", "\u{E765}",
    "\u{E72E}",
];

/// What a row in the settings pane looks like, which decides how it is laid
/// out and whether the search box can match it.
#[derive(PartialEq)]
enum Kind {
    /// A bold caption introducing the cards below it. Not itself on a card.
    Header,
    /// A checkbox filling the width of its card.
    Check,
    /// A caption on the left of its card and an edit box or drop-down on the
    /// right.
    Field,
    /// A grey paragraph explaining a whole group. Not on a card.
    Note,
    /// A weekday: its switch, lock time and strict switch on one line.
    Day,
}

/// How a static control wants to be painted: which surface it sits on, and
/// whether its text is secondary.
mod paint_as {
    /// Normal text on a card.
    pub const CARD: isize = 0;
    /// Secondary text on a card.
    pub const CARD_GREY: isize = 1;
    /// A section caption, on the page background.
    pub const PAGE: isize = 2;
    /// Secondary text on the page background.
    pub const PAGE_GREY: isize = 3;
    /// Secondary text on the window background, outside the pane.
    pub const WINDOW_GREY: isize = 4;
    /// The text of a text box, which sits on the box's own white.
    pub const FIELD: isize = 5;
}

/// One row of the settings pane.
struct Item {
    page: usize,
    /// The header this row belongs to; a header points at itself. A header is
    /// shown during a search when any of its rows matched.
    section: usize,
    kind: Kind,
    /// The switch, text box or drop-down; the static of a header or a note; the
    /// day's own switch for a [`Kind::Day`].
    hwnd: HWND,
    /// The caption at the left of the card, the day's name for a
    /// [`Kind::Day`], otherwise invalid.
    caption: HWND,
    /// The grey text under the caption, otherwise invalid.
    desc: HWND,
    /// The lock time and strict switch of a [`Kind::Day`], otherwise invalid.
    day: DayControls,
    /// The glyph drawn in the card's icon column. Empty for rows with no card.
    icon: &'static str,
    /// Extra left inset, used to nest options under the switch that governs
    /// them.
    indent: i32,
    /// Height the control itself is created and laid out with. A drop-down is
    /// told the height of its *open* list; Windows shrinks the closed control
    /// to one row itself.
    ctl_h: i32,
    /// Everything a search matches against, already lowercased.
    search: String,
}

/// The controls of a weekday's row after its own switch. `half` is invalid on
/// a 24-hour clock.
#[derive(Clone, Copy, Default)]
struct DayControls {
    hour: HWND,
    colon: HWND,
    minute: HWND,
    half: HWND,
    strict: HWND,
}

impl DayControls {
    fn all(&self) -> [HWND; 5] {
        [self.hour, self.colon, self.minute, self.half, self.strict]
    }
}

/// A card to paint behind a row, in content coordinates, with the glyph that
/// belongs in its icon column.
struct Card {
    rect: RECT,
    icon: &'static str,
    /// The row's control, whose being disabled greys the icon.
    control: HWND,
    /// Whether clicking anywhere on the card flips its switch.
    toggles: bool,
}

/// The painted frame of a text box, in content coordinates, and its edit
/// control.
struct Field {
    rect: RECT,
    edit: HWND,
    /// Whether up and down chevrons are painted at the right of the frame.
    spin: bool,
}

impl Field {
    /// The up and down chevrons of a box with [`Field::spin`], in content
    /// coordinates.
    fn chevrons(&self) -> [RECT; 2] {
        let left = self.rect.right - 4 - SPIN_W;
        let right = self.rect.right - 3;
        let mid = (self.rect.top + self.rect.bottom) / 2;
        [
            rect(left, self.rect.top + 3, right, mid),
            rect(left, mid, right, self.rect.bottom - 3),
        ]
    }
}

/// A chevron being held down: the box it steps and by how much.
#[derive(Clone, Copy, PartialEq)]
struct Spinning {
    edit: HWND,
    delta: i32,
}

struct State {
    app: *mut App,
    font: HFONT,
    /// For descriptions, notes and the status line.
    small: HFONT,
    bold: HFONT,
    title: HFONT,
    /// The system icon font, for the glyph at the left of every card and page.
    icons: HFONT,
    /// The icon font at the size of the page title, for the glyph beside it.
    title_icons: HFONT,
    /// A small icon font, for the chevrons inside an hour or minute box.
    chevrons: HFONT,
    tooltip: HWND,
    /// The scrolling container holding every setting.
    pane: HWND,
    page_bg: HBRUSH,
    card: HBRUSH,
    field: HBRUSH,
    /// The user's accent colour, as `0xRRGGBB`.
    accent: u32,
    items: Vec<Item>,
    /// The card behind each visible row, in content coordinates. Rows that are
    /// hidden, or that have no card, are not in here.
    cards: Vec<Card>,
    /// The frames of the visible text boxes.
    fields: Vec<Field>,
    /// The chevron held down right now, which repeats on [`SPIN_TIMER`].
    spinning: Option<Spinning>,
    page: usize,
    scroll: i32,
    /// Height of the currently laid out page, for the scroll range.
    content_h: i32,
    /// Presets as currently edited, so switching the combo keeps changes.
    presets: Vec<Preset>,
    current: usize,
}

/// Open the settings window. Returns its handle, or `None` if creation failed.
pub fn open(owner: HWND, app: *mut App) -> Option<HWND> {
    unsafe {
        let instance = GetModuleHandleW(None).ok()?;

        let class = wide(CLASS);
        RegisterClassW(&WNDCLASSW {
            lpfnWndProc: Some(wndproc),
            hInstance: instance.into(),
            lpszClassName: class.as_pcwstr(),
            hCursor: LoadCursorW(None, IDC_ARROW).ok()?,
            hIcon: crate::ui::app::shared_icon(),
            ..Default::default()
        });

        let pane_class = wide(PANE_CLASS);
        RegisterClassW(&WNDCLASSW {
            lpfnWndProc: Some(pane_wndproc),
            hInstance: instance.into(),
            lpszClassName: pane_class.as_pcwstr(),
            hCursor: LoadCursorW(None, IDC_ARROW).ok()?,
            ..Default::default()
        });

        let style = WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU | WS_CLIPCHILDREN;
        let mut rc = RECT {
            left: 0,
            top: 0,
            right: CLIENT_W,
            bottom: CLIENT_H,
        };
        let _ = AdjustWindowRect(&mut rc, style, false);

        let title = wide(&format!("{} Settings", crate::APP_NAME));
        let hwnd = CreateWindowExW(
            WINDOW_EX_STYLE::default(),
            class.as_pcwstr(),
            title.as_pcwstr(),
            style,
            CW_USEDEFAULT,
            CW_USEDEFAULT,
            rc.right - rc.left,
            rc.bottom - rc.top,
            Some(owner),
            None,
            Some(instance.into()),
            None,
        )
        .ok()?;

        let pane = CreateWindowExW(
            WS_EX_CONTROLPARENT,
            pane_class.as_pcwstr(),
            PCWSTR::null(),
            WS_CHILD | WS_VISIBLE | WS_VSCROLL | WS_CLIPCHILDREN,
            CONTENT_X,
            PANE_Y,
            PANE_W,
            PANE_H,
            Some(hwnd),
            None,
            Some(instance.into()),
            None,
        )
        .ok()?;

        let config = (*app).config().clone();
        let presets = config.presets.clone();
        let current = presets
            .iter()
            .position(|p| p.name == config.preset().name)
            .unwrap_or(0);

        let fonts = gui_fonts();
        let ptr = Box::into_raw(Box::new(State {
            app,
            font: fonts.body,
            small: fonts.small,
            bold: fonts.bold,
            title: fonts.title,
            icons: fonts.icons,
            title_icons: fonts.title_icons,
            chevrons: fonts.chevrons,
            tooltip: make_tooltip(hwnd),
            pane,
            page_bg: CreateSolidBrush(rgb(fluent::BACKGROUND)),
            card: CreateSolidBrush(rgb(fluent::CARD)),
            field: CreateSolidBrush(rgb(fluent::FIELD)),
            accent: fluent::accent(),
            items: Vec::new(),
            cards: Vec::new(),
            fields: Vec::new(),
            spinning: None,
            page: 0,
            scroll: 0,
            content_h: 0,
            presets,
            current,
        }));
        SetWindowLongPtrW(hwnd, GWLP_USERDATA, ptr as isize);
        SetWindowLongPtrW(pane, GWLP_USERDATA, ptr as isize);

        build(hwnd, &mut *ptr, &config);
        relayout(hwnd, &mut *ptr);
        sync_dependencies((*ptr).pane);
        refresh_status(hwnd);

        let _ = ShowWindow(hwnd, SW_SHOW);
        let _ = SetForegroundWindow(hwnd);
        Some(hwnd)
    }
}

/// The fonts of the settings window, in the sizes Windows 11 uses: 14 pixel
/// body text, 12 pixel secondary text and a 28 pixel page title.
struct Fonts {
    body: HFONT,
    small: HFONT,
    bold: HFONT,
    title: HFONT,
    icons: HFONT,
    title_icons: HFONT,
    chevrons: HFONT,
}

fn gui_fonts() -> Fonts {
    unsafe {
        let mut ncm = NONCLIENTMETRICSW {
            cbSize: std::mem::size_of::<NONCLIENTMETRICSW>() as u32,
            ..Default::default()
        };
        let ok = SystemParametersInfoW(
            SPI_GETNONCLIENTMETRICS,
            ncm.cbSize,
            Some(&mut ncm as *mut _ as *mut _),
            SYSTEM_PARAMETERS_INFO_UPDATE_FLAGS(0),
        )
        .is_ok();
        let base: LOGFONTW = if ok {
            ncm.lfMessageFont
        } else {
            LOGFONTW::default()
        };
        let sized = |height: i32, weight: i32, faces: &[&str]| {
            let mut lf = base;
            lf.lfHeight = -height;
            lf.lfWeight = weight;
            text_font(&lf, faces)
        };
        let text = ["Segoe UI Variable Text", "Segoe UI"];
        let display = ["Segoe UI Variable Display", "Segoe UI"];
        let mut icon_lf = base;
        icon_lf.lfHeight = -16;
        icon_lf.lfWeight = 400;
        let mut title_icon_lf = icon_lf;
        title_icon_lf.lfHeight = -26;
        let mut chevron_lf = icon_lf;
        chevron_lf.lfHeight = -9;
        Fonts {
            body: sized(14, 400, &text),
            small: sized(12, 400, &text),
            bold: sized(14, 600, &text),
            title: sized(28, 600, &display),
            icons: fluent::icon_font(&icon_lf),
            title_icons: fluent::icon_font(&title_icon_lf),
            chevrons: fluent::icon_font(&chevron_lf),
        }
    }
}

/// The first of `faces` that is installed, or the message font's own face.
unsafe fn text_font(base: &LOGFONTW, faces: &[&str]) -> HFONT {
    for face in faces {
        let mut lf = *base;
        fluent::set_face(&mut lf, face);
        let font = CreateFontIndirectW(&lf);
        if fluent::font_is(font, face) {
            return font;
        }
        let _ = DeleteObject(font.into());
    }
    CreateFontIndirectW(base)
}

unsafe fn make_tooltip(parent: HWND) -> HWND {
    let h = CreateWindowExW(
        WINDOW_EX_STYLE::default(),
        TOOLTIPS_CLASSW,
        PCWSTR::null(),
        WINDOW_STYLE(TTS_ALWAYSTIP),
        0,
        0,
        0,
        0,
        Some(parent),
        None,
        None,
        None,
    )
    .unwrap_or_default();
    if !h.is_invalid() {
        SendMessageW(h, TTM_SETMAXTIPWIDTH, None, Some(LPARAM(320)));
    }
    h
}

std::thread_local! {
    /// A tooltip control stores a *pointer* to its text rather than copying it,
    /// so these buffers have to outlive the `TTM_ADDTOOLW` call. They are owned
    /// here for the life of the settings window and cleared when it closes.
    static TIP_TEXT: std::cell::RefCell<Vec<Vec<u16>>> =
        const { std::cell::RefCell::new(Vec::new()) };
}

/// Attach hover help to a control. The visible description stays one line; the
/// full explanation is one hover away.
unsafe fn tip(tooltip: HWND, control: HWND, text: &str) {
    if tooltip.is_invalid() || control.is_invalid() || text.is_empty() {
        return;
    }
    let ptr = TIP_TEXT.with(|c| {
        let mut v = c.borrow_mut();
        v.push(text.encode_utf16().chain(std::iter::once(0)).collect());

        v.last_mut().unwrap().as_mut_ptr()
    });
    let ti = TTTOOLINFOW {
        cbSize: std::mem::size_of::<TTTOOLINFOW>() as u32,
        uFlags: TTF_IDISHWND | TTF_SUBCLASS,
        hwnd: GetParent(control).unwrap_or_default(),
        uId: control.0 as usize,
        lpszText: windows::core::PWSTR(ptr),
        ..Default::default()
    };
    SendMessageW(
        tooltip,
        TTM_ADDTOOLW,
        None,
        Some(LPARAM(&ti as *const _ as isize)),
    );
}

#[allow(clippy::too_many_arguments)]
unsafe fn ctl(
    parent: HWND,
    class: PCWSTR,
    text: &str,
    style: WINDOW_STYLE,
    x: i32,
    y: i32,
    w: i32,
    h: i32,
    id: usize,
    font: HFONT,
) -> HWND {
    let t = wide(text);
    let hwnd = CreateWindowExW(
        WINDOW_EX_STYLE::default(),
        class,
        t.as_pcwstr(),
        WS_CHILD | style,
        x,
        y,
        w,
        h,
        Some(parent),
        Some(HMENU(id as *mut _)),
        None,
        None,
    )
    .unwrap_or_default();
    SendMessageW(
        hwnd,
        WM_SETFONT,
        Some(WPARAM(font.0 as usize)),
        Some(LPARAM(1)),
    );
    hwnd
}

/// Record how a static control wants to be painted; see [`paint_as`].
unsafe fn painted_as(h: HWND, how: isize) {
    if !h.is_invalid() {
        SetWindowLongPtrW(h, GWLP_USERDATA, how);
    }
}

/// Collects the settings rows as they are created.
struct Rows {
    pane: HWND,
    font: HFONT,
    small: HFONT,
    bold: HFONT,
    tooltip: HWND,
    page: usize,
    section: usize,
    items: Vec<Item>,
}

impl Rows {
    unsafe fn header(&mut self, page: usize, title: &str) {
        self.page = page;
        self.section = self.items.len();
        let h = ctl(
            self.pane,
            WC_STATICW,
            title,
            WINDOW_STYLE(0),
            0,
            0,
            ITEM_W,
            22,
            0,
            self.bold,
        );
        painted_as(h, paint_as::PAGE);
        self.push(Row {
            kind: Kind::Header,
            hwnd: h,
            ctl_h: 22,
            label: title,
            ..Row::default()
        });
    }

    unsafe fn check(
        &mut self,
        icon: &'static str,
        id: usize,
        label: &str,
        on: bool,
        desc: &str,
        help: &str,
    ) {
        self.check_at(icon, 0, id, label, on, desc, help);
    }

    /// A switch nested under the switch above it.
    unsafe fn sub_check(
        &mut self,
        icon: &'static str,
        id: usize,
        label: &str,
        on: bool,
        help: &str,
    ) {
        self.check_at(icon, INDENT, id, label, on, "", help);
    }

    /// A checkbox, drawn as a switch at the right of its card. It keeps its
    /// label as its text, which is what a screen reader announces.
    #[allow(clippy::too_many_arguments)]
    unsafe fn check_at(
        &mut self,
        icon: &'static str,
        indent: i32,
        id: usize,
        label: &str,
        on: bool,
        desc: &str,
        help: &str,
    ) {
        let h = self.switch(id, label, on, SWITCH_CTL_W);
        tip(self.tooltip, h, help);
        let caption = self.caption(label, id);
        let d = self.description(desc, id);
        self.push(Row {
            kind: Kind::Check,
            hwnd: h,
            caption,
            desc: d,
            icon,
            indent,
            ctl_h: FIELD_H,
            label,
            description: desc,
            help,
            ..Row::default()
        });
    }

    unsafe fn switch(&self, id: usize, label: &str, on: bool, width: i32) -> HWND {
        let h = ctl(
            self.pane,
            WC_BUTTONW,
            label,
            WINDOW_STYLE(BS_AUTOCHECKBOX as u32 | WS_TABSTOP.0),
            0,
            0,
            width,
            FIELD_H,
            id,
            self.font,
        );
        let state = if on { BST_CHECKED.0 as usize } else { 0 };
        SendMessageW(h, BM_SETCHECK, Some(WPARAM(state)), None);
        h
    }

    /// A borderless edit control; the pane paints its frame.
    unsafe fn edit(&self, id: usize, value: &str, width: i32) -> HWND {
        let e = ctl(
            self.pane,
            WC_EDITW,
            value,
            WINDOW_STYLE(WS_TABSTOP.0 | ES_AUTOHSCROLL as u32),
            0,
            0,
            width,
            EDIT_H,
            id,
            self.font,
        );
        painted_as(e, paint_as::FIELD);
        e
    }

    unsafe fn field(
        &mut self,
        icon: &'static str,
        id: usize,
        label: &str,
        value: &str,
        desc: &str,
        help: &str,
    ) {
        let caption = self.caption(label, id);
        let e = self.edit(id, value, FIELD_W);
        tip(self.tooltip, e, help);
        let d = self.description(desc, id);
        self.push(Row {
            kind: Kind::Field,
            hwnd: e,
            caption,
            desc: d,
            icon,
            ctl_h: EDIT_H,
            label,
            description: desc,
            help,
            ..Row::default()
        });
    }

    /// A box that records a shortcut instead of taking typed text; see
    /// [`record_key`]. It is read-only, so nothing can be typed or pasted into
    /// it, and says "Press a key" while empty.
    unsafe fn key_field(
        &mut self,
        icon: &'static str,
        id: usize,
        label: &str,
        value: &str,
        desc: &str,
        help: &str,
    ) {
        self.field(icon, id, label, value, desc, help);
        if let Ok(e) = GetDlgItem(Some(self.pane), id as i32) {
            SendMessageW(e, EM_SETREADONLY, Some(WPARAM(1)), None);
            let cue = wide("Press a key");
            SendMessageW(
                e,
                EM_SETCUEBANNER,
                Some(WPARAM(1)),
                Some(LPARAM(cue.as_pcwstr().0 as isize)),
            );
        }
    }

    /// A drop-down. `options` are added in order and `selected` is preselected.
    #[allow(clippy::too_many_arguments)]
    unsafe fn combo(
        &mut self,
        icon: &'static str,
        id: usize,
        label: &str,
        options: &[&str],
        selected: usize,
        desc: &str,
        help: &str,
    ) {
        let caption = self.caption(label, id);
        let h = self.dropdown(id, options, selected, FIELD_W);
        tip(self.tooltip, h, help);
        let d = self.description(desc, id);
        self.push(Row {
            kind: Kind::Field,
            hwnd: h,
            caption,
            desc: d,
            icon,
            ctl_h: 240,
            label,
            description: desc,
            help,
            ..Row::default()
        });
    }

    /// A drop-down list `width` wide, with `options` in order and `selected`
    /// preselected.
    unsafe fn dropdown(&self, id: usize, options: &[&str], selected: usize, width: i32) -> HWND {
        let h = ctl(
            self.pane,
            WC_COMBOBOXW,
            "",
            WINDOW_STYLE(CBS_DROPDOWNLIST as u32 | WS_TABSTOP.0 | WS_VSCROLL.0),
            0,
            0,
            width,
            240,
            id,
            self.font,
        );
        SendMessageW(
            h,
            CB_SETITEMHEIGHT,
            Some(WPARAM(usize::MAX)),
            Some(LPARAM(FIELD_H as isize - 6)),
        );
        SendMessageW(h, CB_SETITEMHEIGHT, Some(WPARAM(0)), Some(LPARAM(24)));
        for o in options {
            let t = wide(o);
            SendMessageW(
                h,
                CB_ADDSTRING,
                None,
                Some(LPARAM(t.as_pcwstr().0 as isize)),
            );
        }
        SendMessageW(h, CB_SETCURSEL, Some(WPARAM(selected)), None);
        h
    }

    /// A two-digit box for the hour or minutes of a lock time. The pane paints
    /// up and down chevrons at its right; see [`Field::chevrons`] and
    /// [`step_key`].
    unsafe fn clock_box(&self, id: usize, value: &str, help: &str) -> HWND {
        let e = self.edit(id, value, CLOCK_W - 22 - SPIN_W);
        SetWindowLongW(e, GWL_STYLE, GetWindowLongW(e, GWL_STYLE) | ES_NUMBER);
        SendMessageW(e, EM_LIMITTEXT, Some(WPARAM(2)), None);
        tip(self.tooltip, e, help);
        e
    }

    /// One weekday's lock, on a single line.
    unsafe fn day(&mut self, index: usize, lock: &DayLock) {
        let name = DAY_NAMES[index];
        let on = self.switch(ID_LOCK_DAY + index, name, lock.enabled, 48);
        tip(self.tooltip, on, "Lock the PC on this day.");
        let caption = self.caption(name, ID_LOCK_DAY + index);
        let halves = day_halves();
        let (hour_text, minute_text, afternoon) = clock_parts(lock.time, halves.is_some());
        let hour = self.clock_box(
            ID_LOCK_HOUR + index,
            &hour_text,
            "The hour of the lock. Use the arrows or the Up and Down keys.",
        );
        let colon = ctl(
            self.pane,
            WC_STATICW,
            ":",
            WINDOW_STYLE(SS_CENTER.0),
            0,
            0,
            COLON_W,
            EDIT_H,
            0,
            self.font,
        );
        painted_as(colon, paint_as::CARD);
        let minute = self.clock_box(
            ID_LOCK_MINUTE + index,
            &minute_text,
            "The minutes of the lock. Use the arrows or the Up and Down keys.",
        );
        let half = match &halves {
            Some([am, pm]) => {
                let h = self.dropdown(ID_LOCK_HALF + index, &[am, pm], afternoon as usize, HALF_W);
                tip(self.tooltip, h, "Morning or afternoon.");
                h
            }
            None => HWND::default(),
        };
        let strict = self.switch(ID_LOCK_STRICT + index, "Strict", lock.strict, 104);
        let help = "After the cutoff, Exit is refused and this day's lock cannot be \
                    changed until its locked period ends.";
        tip(self.tooltip, strict, help);
        self.push(Row {
            kind: Kind::Day,
            hwnd: on,
            caption,
            day: DayControls {
                hour,
                colon,
                minute,
                half,
                strict,
            },
            ctl_h: FIELD_H,
            label: name,
            description: "lock time strict",
            help,
            ..Row::default()
        });
    }

    unsafe fn note(&mut self, text: &str) {
        let h = ctl(
            self.pane,
            WC_STATICW,
            text,
            WINDOW_STYLE(0),
            0,
            0,
            ITEM_W,
            16,
            0,
            self.small,
        );
        painted_as(h, paint_as::PAGE_GREY);
        self.push(Row {
            kind: Kind::Note,
            hwnd: h,
            label: text,
            ..Row::default()
        });
    }

    /// The visible label of a row. It must be created just before the row's
    /// text box or drop-down, which screen readers name after the label
    /// preceding it.
    unsafe fn caption(&self, label: &str, id: usize) -> HWND {
        let h = ctl(
            self.pane,
            WC_STATICW,
            label,
            WINDOW_STYLE(SS_ENDELLIPSIS.0),
            0,
            0,
            CAP_W,
            EDIT_H,
            id + CAPTION_ID,
            self.font,
        );
        painted_as(h, paint_as::CARD);
        h
    }

    unsafe fn description(&self, text: &str, id: usize) -> HWND {
        if text.is_empty() {
            return HWND::default();
        }
        let h = ctl(
            self.pane,
            WC_STATICW,
            text,
            WINDOW_STYLE(0),
            0,
            0,
            CAP_W,
            16,
            id + DESC_ID,
            self.small,
        );
        painted_as(h, paint_as::CARD_GREY);
        h
    }

    fn push(&mut self, row: Row) {
        let section = if row.kind == Kind::Header {
            self.items.len()
        } else {
            self.section
        };
        let heading = self
            .items
            .get(section)
            .map(|h| h.search.clone())
            .unwrap_or_default();
        self.items.push(Item {
            page: self.page,
            section,
            search: format!(
                "{} {} {} {} {}",
                PAGES[self.page], heading, row.label, row.description, row.help
            )
            .to_lowercase(),
            kind: row.kind,
            hwnd: row.hwnd,
            caption: row.caption,
            desc: row.desc,
            day: row.day,
            icon: row.icon,
            indent: row.indent,
            ctl_h: row.ctl_h,
        });
    }
}

/// What [`Rows::push`] needs to know about a new row.
struct Row<'a> {
    kind: Kind,
    hwnd: HWND,
    caption: HWND,
    desc: HWND,
    day: DayControls,
    icon: &'static str,
    indent: i32,
    ctl_h: i32,
    label: &'a str,
    description: &'a str,
    help: &'a str,
}

impl Default for Row<'_> {
    fn default() -> Self {
        Row {
            kind: Kind::Note,
            hwnd: HWND::default(),
            caption: HWND::default(),
            desc: HWND::default(),
            day: DayControls::default(),
            icon: "",
            indent: 0,
            ctl_h: 0,
            label: "",
            description: "",
            help: "",
        }
    }
}

unsafe fn build(hwnd: HWND, st: &mut State, cfg: &Config) {
    let f = st.font;

    let search = ctl(
        hwnd,
        WC_EDITW,
        "",
        WINDOW_STYLE(WS_VISIBLE.0 | WS_TABSTOP.0 | ES_AUTOHSCROLL as u32),
        SEARCH_BOX.left + 12,
        SEARCH_BOX.top + (FIELD_H - EDIT_H) / 2,
        SEARCH_BOX.right - SEARCH_BOX.left - 44,
        EDIT_H,
        ID_SEARCH,
        f,
    );
    painted_as(search, paint_as::FIELD);
    let keys = &cfg.shortcuts;
    let cue = wide(&format!(
        "Search settings{}",
        key_hint(keys, &keys.settings.search)
    ));
    SendMessageW(
        search,
        EM_SETCUEBANNER,
        Some(WPARAM(1)),
        Some(LPARAM(cue.as_pcwstr().0 as isize)),
    );
    tip(
        st.tooltip,
        search,
        "Type a word to see every matching setting from all pages at once.",
    );

    let nav = ctl(
        hwnd,
        WC_LISTBOXW,
        "",
        WINDOW_STYLE(
            WS_VISIBLE.0
                | WS_TABSTOP.0
                | LBS_NOTIFY as u32
                | LBS_HASSTRINGS as u32
                | LBS_OWNERDRAWFIXED as u32
                | LBS_NOINTEGRALHEIGHT as u32,
        ),
        8,
        NAV_Y,
        SIDEBAR_W - 16,
        NAV_ROW * PAGES.len() as i32,
        ID_NAV,
        f,
    );
    SendMessageW(
        nav,
        LB_SETITEMHEIGHT,
        Some(WPARAM(0)),
        Some(LPARAM(NAV_ROW as isize)),
    );
    for p in PAGES {
        let t = wide(p);
        SendMessageW(
            nav,
            LB_ADDSTRING,
            None,
            Some(LPARAM(t.as_pcwstr().0 as isize)),
        );
    }
    SendMessageW(nav, LB_SETCURSEL, Some(WPARAM(0)), None);

    let title = ctl(
        hwnd,
        WC_STATICW,
        PAGES[0],
        WINDOW_STYLE(WS_VISIBLE.0),
        CONTENT_X + TITLE_ICON.right - TITLE_ICON.left + 8,
        TITLE_Y,
        PANE_W - (TITLE_ICON.right - TITLE_ICON.left + 8),
        40,
        ID_TITLE,
        st.title,
    );
    painted_as(title, paint_as::PAGE);

    let status = ctl(
        hwnd,
        WC_STATICW,
        "",
        WINDOW_STYLE(WS_VISIBLE.0),
        20,
        FOOTER_Y - 52,
        SIDEBAR_W - 40,
        36,
        ID_STATUS,
        st.small,
    );
    painted_as(status, paint_as::WINDOW_GREY);

    let tooltip = st.tooltip;
    let by = FOOTER_Y + (FOOTER_H - FIELD_H) / 2;
    let b = |x: i32, w: i32, text: &str, id: usize, help: &str| {
        let h = ctl(
            hwnd,
            WC_BUTTONW,
            text,
            WINDOW_STYLE(WS_VISIBLE.0 | WS_TABSTOP.0),
            x,
            by,
            w,
            FIELD_H,
            id,
            f,
        );
        tip(tooltip, h, help);
    };
    b(20, 140, "Restore defaults", ID_DEFAULTS,
        "Reset every setting on this window to its original value. Nothing is saved until you press Save.");
    let right = CLIENT_W - 20;
    b(
        right - 104 - 8 - 104 - 8 - 168,
        168,
        "Save as new preset",
        ID_SAVE_AS,
        "Keep the current preset untouched and store these timer lengths under the name above.",
    );
    b(
        right - 104 - 8 - 104,
        104,
        "Save",
        ID_SAVE,
        &format!(
            "Apply these settings and close.{}",
            key_hint(keys, &keys.settings.save)
        ),
    );
    b(
        right - 104,
        104,
        "Cancel",
        ID_CANCEL,
        &format!(
            "Close without saving.{}",
            key_hint(keys, &keys.settings.close)
        ),
    );

    let empty = ctl(
        st.pane,
        WC_STATICW,
        "Nothing matches that. Try a shorter word.",
        WINDOW_STYLE(0),
        0,
        0,
        ITEM_W,
        20,
        ID_EMPTY,
        st.small,
    );
    painted_as(empty, paint_as::PAGE_GREY);

    let mut rows = Rows {
        pane: st.pane,
        font: st.font,
        small: st.small,
        bold: st.bold,
        tooltip: st.tooltip,
        page: 0,
        section: 0,
        items: Vec::new(),
    };
    build_rows(&mut rows, st, cfg);
    st.items = rows.items;
}

unsafe fn build_rows(r: &mut Rows, st: &State, cfg: &Config) {
    let p = st.presets[st.current.min(st.presets.len() - 1)].clone();
    let names: Vec<&str> = st.presets.iter().map(|p| p.name.as_str()).collect();

    r.header(PAGE_GENERAL, "Startup");
    r.check(
        "\u{E7E8}",
        ID_AUTOSTART,
        "Start with Windows",
        crate::os::autostart::is_on(),
        "Opens the app when you sign in. A PC lock only happens while it runs.",
        "Adds one value to the startup list of your own Windows account.",
    );

    r.header(PAGE_TIMER, "Preset");
    r.combo(
        "\u{E8FD}",
        ID_PRESET,
        "Preset",
        &names,
        st.current,
        "The set of lengths the timer runs with.",
        "Switch between saved presets. Edit the boxes below and press Save to \
         change this preset, or Save as new preset to keep both.",
    );
    r.field(
        "\u{E8EC}",
        ID_NAME,
        "Preset name",
        &p.name,
        "Shown in the tray menu and usable with --preset.",
        "Renaming here and pressing Save renames the preset.",
    );

    r.header(PAGE_TIMER, "Lengths");
    r.field(
        "\u{E916}",
        ID_FOCUS,
        "Focus (minutes)",
        &num(p.focus_minutes),
        "Fractions are allowed, e.g. 0.5 for 30 seconds.",
        "How long one focus session lasts.",
    );
    r.field(
        "\u{EC32}",
        ID_SHORT,
        "Short break (minutes)",
        &num(p.short_break_minutes),
        "Taken after most focus sessions.",
        "The break taken after most focus sessions.",
    );
    r.field(
        "\u{E823}",
        ID_LONG,
        "Long break (minutes)",
        &num(p.long_break_minutes),
        "Taken after every Nth focus session.",
        "The longer break taken after every Nth focus session.",
    );
    r.field(
        "\u{E9D5}",
        ID_SESSIONS,
        "Sessions per long break",
        &p.sessions_before_long_break.to_string(),
        "4 is the classic Pomodoro cadence.",
        "How many focus sessions to complete before earning a long break.",
    );

    r.header(PAGE_SEQUENCE, "Automatic sequence");
    r.check(
        "\u{E8EE}",
        ID_SEQUENCE,
        "Run the Pomodoro sequence",
        cfg.behavior.sequence_enabled,
        "Turn this off to use the app as a plain manual timer.",
        "Master switch for focus, break and long break running one after another.",
    );
    r.sub_check(
        "\u{EC32}",
        ID_AUTO_BREAK,
        "Start a break when focus ends",
        cfg.behavior.auto_start_break,
        "When a focus session completes, begin the break automatically.",
    );
    r.sub_check(
        "\u{E916}",
        ID_AUTO_FOCUS,
        "Start focus when a break ends",
        cfg.behavior.auto_start_focus,
        "When a break completes, begin the next focus session automatically.",
    );
    r.sub_check(
        "\u{E8EE}",
        ID_REPEAT_CYCLES,
        "Start another cycle after a long break",
        cfg.behavior.repeat_cycles,
        "When the long break ends, begin a new focus session even if \
         “Start focus when a break ends” is off.",
    );

    r.header(PAGE_SEQUENCE, "Interruptions");
    r.check(
        "\u{E72E}",
        ID_STRICT,
        "Strict focus",
        cfg.behavior.strict_focus,
        "Confirm before stopping or skipping a running focus session.",
        "Ask for confirmation before stopping or skipping a running focus session, \
         so a stray click cannot end it. Breaks are never guarded.",
    );
    r.check(
        "\u{E81C}",
        ID_RESTORE_SESSION,
        "Restore an interrupted session on restart",
        cfg.behavior.restore_session_on_restart,
        "It always comes back paused, never running.",
        "If the app closes mid-session, bring the remaining time back next time it starts.",
    );
    r.combo(
        "\u{E7E8}",
        ID_WAKE,
        "After sleep",
        &[
            "Count the time asleep",
            "Ignore the time asleep",
            "Pause the timer",
        ],
        match cfg.behavior.wake_policy {
            WakePolicy::CountSleep => 0,
            WakePolicy::IgnoreSleep => 1,
            WakePolicy::Pause => 2,
        },
        "What a running timer does when the machine wakes up.",
        "Counting the time asleep means a 25 minute session started before a two \
         hour nap is simply over.",
    );

    r.header(PAGE_NOTIFICATIONS, "Windows notifications");
    r.check(
        "\u{EA8F}",
        ID_NOTIFY,
        "Show notifications",
        cfg.notifications.enabled,
        "Master switch for all notifications.",
        "Turn this off to make the app silent in the notification centre.",
    );
    r.sub_check(
        "\u{E916}",
        ID_N_FS,
        "Focus started",
        cfg.notifications.events.focus_start,
        "Notify when a focus session begins.",
    );
    r.sub_check(
        "\u{E7C1}",
        ID_N_FE,
        "Focus ended",
        cfg.notifications.events.focus_end,
        "Notify when a focus session completes.",
    );
    r.sub_check(
        "\u{EC32}",
        ID_N_BS,
        "Break started",
        cfg.notifications.events.break_start,
        "Notify when a break begins.",
    );
    r.sub_check(
        "\u{E823}",
        ID_N_BE,
        "Break ended",
        cfg.notifications.events.break_end,
        "Notify when a break completes.",
    );

    r.header(PAGE_NOTIFICATIONS, "When a session ends");
    r.note(
        "Pick any combination. Options that need another switch stay dimmed \
         until that switch is on. Overlay and flash still work under Do Not \
         Disturb.",
    );
    r.check(
        "\u{EA8F}",
        ID_ALERT_TOAST,
        "Tray toast",
        cfg.alerts.toast,
        "Needs “Show notifications” above.",
        "Posts the usual Windows toast when a focus or break ends. Disabled \
         while Show notifications is off.",
    );
    r.check(
        "\u{E7F4}",
        ID_ALERT_OVERLAY,
        "Centre overlay",
        cfg.alerts.overlay,
        "A large card in the middle of the screen.",
        "A dimmed backdrop and centred card that is hard to miss.",
    );
    r.sub_check(
        "\u{E769}",
        ID_REQUIRE_DISMISS,
        "Wait for dismiss — pauses the timer",
        cfg.alerts.require_dismiss,
        "Needs Centre overlay. Keeps the card open and pauses until Continue.",
    );
    r.check(
        "\u{E706}",
        ID_ALERT_FLASH,
        "Screen flash",
        cfg.alerts.flash,
        "A colour pulse across every screen.",
        "A colour pulse across every screen. Short is two quick pulses; Extra long is eight slower ones.",
    );
    r.combo(
        "\u{E706}",
        ID_FLASH_LENGTH,
        "Flash length",
        &["Short", "Normal", "Long", "Extra long"],
        cfg.alerts.flash_length.index(),
        "How long the screen flash runs.",
        "Needs Screen flash. Short is two quick pulses; Extra long is eight slower ones.",
    );

    r.header(PAGE_DND, "Muting");
    r.check(
        "\u{E708}",
        ID_DND,
        "Mute notifications during focus",
        cfg.dnd.enabled,
        "Do Not Disturb goes on with focus and off with a break.",
        "Switch Windows Do Not Disturb on when focus starts and off when a break starts.",
    );
    r.sub_check(
        "\u{E708}",
        ID_DND_SHORT_BREAK,
        "Keep it on during short breaks",
        cfg.dnd.keep_on_short_break,
        "Only a long break turns Do Not Disturb off. Needs muting during focus.",
    );
    r.note(
        "Your priority apps and contacts still get through - Windows keeps \
         applying your own priority list, which this app never touches.",
    );

    r.header(PAGE_DND, "Muted indicator");
    r.note("Only used while muting during focus is switched on.");
    r.sub_check(
        "\u{EA8F}",
        ID_MUTE_TRAY,
        "Add a separate bell beside the clock",
        cfg.dnd.mute_tray_icon,
        "A second tray icon, present only while muted. Needs muting during focus.",
    );
    r.sub_check(
        "\u{E7ED}",
        ID_MUTE_WINDOW,
        "Show a muted bell in the timer window",
        cfg.dnd.mute_window,
        "Next to the countdown. Needs muting during focus.",
    );
    r.note(
        "Windows only shows its own muted icon for changes made from the taskbar. \
         These draw the same crossed-out bell instead. The timer icon stays \
         dedicated to progress because it cannot show both legibly.",
    );

    r.header(PAGE_SOUNDS, "Alert sounds");
    r.note(
        "Plays the Windows Asterisk sound from your scheme. Mute system sounds \
         in Windows if you want silence.",
    );
    r.check(
        "\u{E74F}",
        ID_MUTE,
        "Mute all sounds",
        cfg.sounds.muted,
        "When on, the switches below do nothing.",
        "Silences every cue without forgetting which ones you had chosen.",
    );
    r.sub_check(
        "\u{E916}",
        ID_S_FS,
        "Focus started",
        cfg.sounds.events.focus_start,
        "Play a cue when a focus session begins.",
    );
    r.sub_check(
        "\u{E7C1}",
        ID_S_FE,
        "Focus ended",
        cfg.sounds.events.focus_end,
        "Play a cue when a focus session completes.",
    );
    r.sub_check(
        "\u{EC32}",
        ID_S_BS,
        "Break started",
        cfg.sounds.events.break_start,
        "Play a cue when a break begins.",
    );
    r.sub_check(
        "\u{E823}",
        ID_S_BE,
        "Break ended",
        cfg.sounds.events.break_end,
        "Play a cue when a break completes.",
    );

    r.header(PAGE_WINDOW, "Compact timer");
    r.check(
        "\u{E7F4}",
        ID_MINI,
        "Show the compact timer window",
        cfg.display.mini_window,
        "A small resizable countdown you can click to start or pause.",
        "Drag its edges to shrink it to roughly the height of a taskbar button, \
         or make it large. Click it to start or pause.",
    );
    r.sub_check(
        "\u{E718}",
        ID_TOPMOST,
        "Keep it above other windows",
        cfg.display.always_on_top,
        "Needs the compact timer window. Stays visible over other apps.",
    );
    r.note("The tray icon always stays visible; these are extra readouts.");

    r.header(PAGE_HOTKEYS, "Global hotkeys");
    r.check(
        "\u{E765}",
        ID_HOTKEYS,
        "Enable global hotkeys",
        cfg.hotkeys.enabled,
        "Hotkeys work from any application.",
        "If another program already owns a combination, you will be told.",
    );
    r.key_field(
        "\u{E768}",
        ID_HK_TOGGLE,
        "Start / pause",
        &cfg.hotkeys.toggle,
        "Click, then press the keys. Backspace removes it.",
        "Needs Ctrl, Alt, Shift or Win.",
    );
    r.key_field(
        "\u{E893}",
        ID_HK_SKIP,
        "Skip to next",
        &cfg.hotkeys.skip,
        "Click, then press the keys. Backspace removes it.",
        "Needs Ctrl, Alt, Shift or Win.",
    );

    r.header(PAGE_HOTKEYS, "Keyboard shortcuts");
    r.check(
        "\u{E765}",
        ID_KEYS,
        "Use keyboard shortcuts",
        cfg.shortcuts.enabled,
        "To change one, click its box and press the new key. Backspace removes it.",
        "Keys that work while the app's menu or one of its windows is open.",
    );
    let mut place = None;
    for (i, key) in shortcuts::ALL.iter().enumerate() {
        if place != Some(key.place) {
            place = Some(key.place);
            let (title, note) = match key.place {
                Place::Menu => (
                    "Tray menu",
                    "One letter or digit, pressed while the menu is open. The presets in \
                     the Preset menu are numbered 1 to 9.",
                ),
                Place::TimerWindow => (
                    "Timer window",
                    "Any key, pressed while the timer window is in front.",
                ),
                Place::Settings => (
                    "Settings window",
                    "Needs Ctrl, Alt or Win, unless it is Esc or a function key. Changes \
                     here take effect after Save.",
                ),
            };
            r.header(PAGE_HOTKEYS, title);
            r.note(note);
        }
        r.key_field(
            key.icon,
            ID_KEY + i,
            key.label,
            (key.get)(&cfg.shortcuts),
            "",
            "Click, then press the new key. Backspace removes this shortcut.",
        );
    }

    r.header(PAGE_LOCK, "Days");
    for index in 0..7 {
        r.day(index, cfg.lock.day(index));
    }
    for (i, n) in LOCK_NUMBERS.iter().enumerate() {
        match i {
            0 => r.header(PAGE_LOCK, "Timing"),
            FIRST_ADVANCED => r.header(PAGE_LOCK, "Advanced"),
            _ => {}
        }
        let limits = format!("From {} to {}.", n.min, n.max);
        let value = (n.get)(&cfg.lock).to_string();
        r.field(n.icon, ID_LOCK_NUMBER + i, n.label, &value, n.desc, &limits);
    }
}

/// The text currently in the search box, lowercased and trimmed.
unsafe fn query(hwnd: HWND) -> String {
    text_of(hwnd, ID_SEARCH).trim().to_lowercase()
}

/// Show the rows that belong on screen - the selected page, or everything the
/// search box matches - and stack them down the pane.
unsafe fn relayout(hwnd: HWND, st: &mut State) {
    let q = query(hwnd);
    let mut visible = vec![false; st.items.len()];
    if q.is_empty() {
        for (i, it) in st.items.iter().enumerate() {
            visible[i] = it.page == st.page;
        }
    } else {
        for i in 0..st.items.len() {
            if st.items[i].kind != Kind::Header && st.items[i].search.contains(&q) {
                visible[i] = true;
                visible[st.items[i].section] = true;
            }
        }
    }

    let focus = GetFocus();
    let mut cards = Vec::new();
    let mut fields = Vec::new();
    let mut y = PAD;
    for (i, it) in st.items.iter().enumerate() {
        if !visible[i] {
            hide(it);
            continue;
        }
        let (next, card) = place(it, y, &mut fields);
        y = next;
        if let Some(rect) = card {
            cards.push(Card {
                rect,
                icon: it.icon,
                control: it.hwnd,
                toggles: it.kind == Kind::Check,
            });
        }
    }
    st.cards = cards;
    st.fields = fields;
    st.content_h = y;

    let none = !visible.iter().any(|v| *v);
    if let Ok(h) = GetDlgItem(Some(st.pane), ID_EMPTY as i32) {
        let _ = SetWindowPos(h, None, 2, PAD, ITEM_W, 20, SWP_NOZORDER);
        let _ = ShowWindow(h, if none { SW_SHOW } else { SW_HIDE });
    }

    if !focus.is_invalid() && !IsWindowVisible(focus).as_bool() {
        let fallback = if q.is_empty() { ID_NAV } else { ID_SEARCH };
        if let Ok(h) = GetDlgItem(Some(hwnd), fallback as i32) {
            let _ = SetFocus(Some(h));
        }
    }

    let heading = if q.is_empty() {
        PAGES[st.page]
    } else {
        "Search results"
    };
    if let Ok(nav) = GetDlgItem(Some(hwnd), ID_NAV as i32) {
        let sel = if q.is_empty() { st.page as isize } else { -1 };
        SendMessageW(nav, LB_SETCURSEL, Some(WPARAM(sel as usize)), None);
    }
    if let Ok(h) = GetDlgItem(Some(hwnd), ID_TITLE as i32) {
        let t = wide(heading);
        let _ = SetWindowTextW(h, t.as_pcwstr());
        let _ = InvalidateRect(Some(h), None, true);
    }
    let _ = InvalidateRect(Some(hwnd), Some(&TITLE_ICON), false);

    st.scroll = 0;
    set_scroll_range(st);
    let _ = RedrawWindow(
        Some(st.pane),
        None,
        None,
        RDW_INVALIDATE | RDW_ERASE | RDW_ALLCHILDREN,
    );
}

unsafe fn hide(it: &Item) {
    for h in [it.hwnd, it.caption, it.desc]
        .into_iter()
        .chain(it.day.all())
    {
        if !h.is_invalid() {
            let _ = ShowWindow(h, SW_HIDE);
        }
    }
}

/// How tall `h`'s text is when wrapped to `width`, in its own font.
unsafe fn text_height(h: HWND, width: i32) -> i32 {
    let mut buf = [0u16; 512];
    let n = GetWindowTextW(h, &mut buf) as usize;
    let dc = GetDC(Some(h));
    let font = HFONT(SendMessageW(h, WM_GETFONT, None, None).0 as *mut _);
    let old = SelectObject(dc, font.into());
    let mut rc = rect(0, 0, width, 0);
    DrawTextW(
        dc,
        &mut buf[..n],
        &mut rc,
        DT_CALCRECT | DT_WORDBREAK | DT_NOPREFIX,
    );
    SelectObject(dc, old);
    ReleaseDC(Some(h), dc);
    rc.bottom.max(16)
}

/// Position one row at `y`, returning the top of the next row and the card to
/// paint behind this one. The frames of its text boxes are added to `fields`.
unsafe fn place(it: &Item, y: i32, fields: &mut Vec<Field>) -> (i32, Option<RECT>) {
    let show = |h: HWND, x: i32, y: i32, w: i32, hh: i32| {
        if !h.is_invalid() {
            let _ = SetWindowPos(h, None, x, y, w, hh, SWP_NOZORDER);
            let _ = ShowWindow(h, SW_SHOW);
        }
    };
    let mut text_box = |edit: HWND, spin: bool, x: i32, top: i32, w: i32| {
        let frame = rect(x, top, x + w, top + FIELD_H);
        let spin_w = if spin { SPIN_W } else { 0 };
        show(
            edit,
            x + 11,
            top + (FIELD_H - EDIT_H) / 2,
            w - 22 - spin_w,
            EDIT_H,
        );
        fields.push(Field {
            rect: frame,
            edit,
            spin,
        });
    };
    let left = it.indent;
    let right = ITEM_W;
    let card = |top: i32, bottom: i32| rect(left, top, right, bottom);

    match it.kind {
        Kind::Header => {
            let y = if y > PAD { y + 22 } else { y };
            show(it.hwnd, 2, y, ITEM_W, 22);
            (y + 30, None)
        }
        Kind::Note => {
            let width = ITEM_W - left - 4;
            let h = text_height(it.hwnd, width);
            show(it.hwnd, left + 2, y + 2, width, h);
            (y + h + 14, None)
        }
        Kind::Check | Kind::Field => {
            let control_w = if it.kind == Kind::Check {
                SWITCH_CTL_W
            } else {
                FIELD_W
            };
            let text_x = left + TEXT_X;
            let text_w = right - 16 - control_w - 24 - text_x;
            let desc_h = if it.desc.is_invalid() {
                0
            } else {
                text_height(it.desc, text_w)
            };
            let block = EDIT_H + if desc_h > 0 { desc_h + 2 } else { 0 };
            let card_h = (block + CARD_Y * 2).max(FIELD_H + 20);
            let top = y + (card_h - block) / 2;
            show(it.caption, text_x, top, text_w, EDIT_H);
            if desc_h > 0 {
                show(it.desc, text_x, top + EDIT_H + 2, text_w, desc_h);
            }
            let control_x = right - 16 - control_w;
            let control_y = y + (card_h - FIELD_H) / 2;
            match it.kind {
                Kind::Check => show(it.hwnd, control_x, control_y, control_w, FIELD_H),
                _ if it.ctl_h > FIELD_H => show(it.hwnd, control_x, control_y, control_w, it.ctl_h),
                _ => text_box(it.hwnd, false, control_x, control_y, control_w),
            }
            let bottom = y + card_h;
            (bottom + GAP, Some(card(y, bottom)))
        }
        Kind::Day => {
            let card_h = FIELD_H + 20;
            let control_y = y + 10;
            show(it.hwnd, left + 8, control_y, 48, FIELD_H);
            show(
                it.caption,
                left + 68,
                y + (card_h - EDIT_H) / 2,
                120,
                EDIT_H,
            );
            let d = &it.day;
            let text_y = y + (card_h - EDIT_H) / 2;
            let mut x = left + 196;
            text_box(d.hour, true, x, control_y, CLOCK_W);
            x += CLOCK_W;
            show(d.colon, x, text_y, COLON_W, EDIT_H);
            x += COLON_W;
            text_box(d.minute, true, x, control_y, CLOCK_W);
            x += CLOCK_W + 8;
            show(d.half, x, control_y, HALF_W, 240);
            centre_closed_dropdown(d.half, x, control_y);
            show(d.strict, right - 16 - 104, control_y, 104, FIELD_H);
            let bottom = y + card_h;
            (bottom + GAP, Some(card(y, bottom)))
        }
    }
}

/// Move the drop-down `h`, placed with its top at `top`, down so that its
/// closed box sits in the middle of a [`FIELD_H`] line like the text boxes
/// beside it. Windows decides the closed height itself.
unsafe fn centre_closed_dropdown(h: HWND, x: i32, top: i32) {
    if h.is_invalid() {
        return;
    }
    let mut rc = RECT::default();
    let _ = GetWindowRect(h, &mut rc);
    let offset = (FIELD_H - (rc.bottom - rc.top)) / 2;
    let _ = SetWindowPos(
        h,
        None,
        x,
        top + offset.max(0),
        0,
        0,
        SWP_NOZORDER | SWP_NOSIZE,
    );
}

unsafe fn set_scroll_range(st: &State) {
    let mut rc = RECT::default();
    let _ = GetClientRect(st.pane, &mut rc);
    let si = SCROLLINFO {
        cbSize: std::mem::size_of::<SCROLLINFO>() as u32,
        fMask: SIF_RANGE | SIF_PAGE | SIF_POS,
        nMin: 0,
        nMax: (st.content_h + 16 - 1).max(0),
        nPage: rc.bottom as u32,
        nPos: st.scroll,
        ..Default::default()
    };
    SetScrollInfo(st.pane, SB_VERT, &si, true);
}

/// Scroll the pane so that `pos` pixels of content are above the top edge.
unsafe fn scroll_to(st: &mut State, pos: i32) {
    let mut rc = RECT::default();
    let _ = GetClientRect(st.pane, &mut rc);
    let max = (st.content_h + 16 - rc.bottom).max(0);
    let pos = pos.clamp(0, max);
    let dy = st.scroll - pos;
    if dy == 0 {
        return;
    }
    st.scroll = pos;
    ScrollWindowEx(
        st.pane,
        0,
        dy,
        None,
        None,
        None,
        None,
        SW_SCROLLCHILDREN | SW_INVALIDATE | SW_ERASE,
    );
    set_scroll_range(st);
}

/// Paint the pane behind its controls: the cards with their icons and the
/// frames of the text boxes. Drawn off screen and copied in one go, so that
/// scrolling does not flicker.
unsafe fn paint_pane(st: &State, hwnd: HWND, hdc: HDC) {
    let mut client = RECT::default();
    let _ = GetClientRect(hwnd, &mut client);
    let (w, h) = (client.right, client.bottom);
    if w <= 0 || h <= 0 {
        return;
    }
    let mem = CreateCompatibleDC(Some(hdc));
    let bitmap = CreateCompatibleBitmap(hdc, w, h);
    let old_bitmap = SelectObject(mem, bitmap.into());
    FillRect(mem, &client, st.page_bg);

    let on_screen = |r: &RECT| {
        let r = rect(r.left, r.top - st.scroll, r.right, r.bottom - st.scroll);
        (r.bottom > 0 && r.top < h).then_some(r)
    };
    let old_font = SelectObject(mem, st.icons.into());
    SetBkMode(mem, TRANSPARENT);
    for c in &st.cards {
        let Some(r) = on_screen(&c.rect) else {
            continue;
        };
        fluent::smooth(
            mem,
            r,
            fluent::BACKGROUND,
            &[Shape::Rounded {
                rect: r,
                radius: 6,
                fill: fluent::CARD,
                edge: Some(fluent::CARD_EDGE),
            }],
        );
        let enabled = IsWindowEnabled(c.control).as_bool();
        SetTextColor(
            mem,
            rgb(if enabled {
                fluent::TEXT
            } else {
                fluent::TEXT_DISABLED
            }),
        );
        draw_icon(mem, c.icon, r.left + CARD_X, r.top, 24, r.bottom - r.top);
    }
    SelectObject(mem, old_font);

    let focus = GetFocus();
    for f in &st.fields {
        let Some(r) = on_screen(&f.rect) else {
            continue;
        };
        let enabled = IsWindowEnabled(f.edit).as_bool();
        let shapes = fluent::text_box(r, focus == f.edit, enabled, st.accent);
        fluent::smooth(mem, r, fluent::CARD, &shapes);
        if f.spin {
            paint_chevrons(st, mem, f, enabled);
        }
    }

    let _ = BitBlt(hdc, 0, 0, w, h, Some(mem), 0, 0, SRCCOPY);
    SelectObject(mem, old_bitmap);
    let _ = DeleteObject(bitmap.into());
    let _ = DeleteDC(mem);
}

/// Draw the up and down chevrons of the box `f` onto the pane's `hdc`, with a
/// grey patch behind the one held down.
unsafe fn paint_chevrons(st: &State, hdc: HDC, f: &Field, enabled: bool) {
    let old_font = SelectObject(hdc, st.chevrons.into());
    SetBkMode(hdc, TRANSPARENT);
    SetTextColor(
        hdc,
        rgb(if enabled {
            fluent::TEXT_SECONDARY
        } else {
            fluent::TEXT_DISABLED
        }),
    );
    for (chevron, (glyph, delta)) in f.chevrons().iter().zip([("\u{E70E}", 1), ("\u{E70D}", -1)]) {
        let r = rect(
            chevron.left,
            chevron.top - st.scroll,
            chevron.right,
            chevron.bottom - st.scroll,
        );
        if st.spinning
            == Some(Spinning {
                edit: f.edit,
                delta,
            })
        {
            let patch = Shape::Rounded {
                rect: rect(r.left, r.top + 1, r.right, r.bottom - 1),
                radius: 3,
                fill: fluent::SELECTED,
                edge: None,
            };
            fluent::smooth(hdc, r, fluent::FIELD, &[patch]);
        }
        draw_icon(
            hdc,
            glyph,
            r.left,
            r.top,
            r.right - r.left,
            r.bottom - r.top,
        );
    }
    SelectObject(hdc, old_font);
}

/// Draw one icon glyph, centred in the box it is given.
unsafe fn draw_icon(hdc: HDC, icon: &str, x: i32, y: i32, w: i32, h: i32) {
    if icon.is_empty() {
        return;
    }
    let mut glyph: Vec<u16> = icon.encode_utf16().collect();
    let mut rc = rect(x, y, x + w, y + h);
    DrawTextW(
        hdc,
        &mut glyph,
        &mut rc,
        DT_CENTER | DT_SINGLELINE | DT_VCENTER | DT_NOPREFIX,
    );
}

/// Draw one navigation entry: a rounded highlight and an accent bar for the
/// page being shown, plain text for the rest.
unsafe fn paint_nav_item(st: &State, dis: &DRAWITEMSTRUCT) {
    let rc = dis.rcItem;
    let mut shapes = Vec::new();
    if dis.itemState.0 & ODS_SELECTED.0 != 0 {
        shapes.push(Shape::Rounded {
            rect: rect(rc.left, rc.top + 2, rc.right, rc.bottom - 2),
            radius: 4,
            fill: fluent::SELECTED,
            edge: None,
        });
        let mid = (rc.top + rc.bottom) / 2;
        shapes.push(Shape::Rounded {
            rect: rect(rc.left, mid - 8, rc.left + 3, mid + 8),
            radius: 1,
            fill: st.accent,
            edge: None,
        });
    }
    fluent::smooth(dis.hDC, rc, fluent::BACKGROUND, &shapes);

    let mut text = [0u16; 64];
    let n = SendMessageW(
        dis.hwndItem,
        LB_GETTEXT,
        Some(WPARAM(dis.itemID as usize)),
        Some(LPARAM(text.as_mut_ptr() as isize)),
    )
    .0;
    if n <= 0 {
        return;
    }
    SetBkMode(dis.hDC, TRANSPARENT);
    SetTextColor(dis.hDC, rgb(fluent::TEXT));

    let old_font = SelectObject(dis.hDC, st.icons.into());
    draw_icon(
        dis.hDC,
        PAGE_ICONS
            .get(dis.itemID as usize)
            .copied()
            .unwrap_or_default(),
        rc.left + 14,
        rc.top,
        20,
        rc.bottom - rc.top,
    );
    SelectObject(dis.hDC, st.font.into());
    let mut text_rc = rect(rc.left + 48, rc.top, rc.right - 8, rc.bottom);
    DrawTextW(
        dis.hDC,
        &mut text[..n as usize],
        &mut text_rc,
        DT_LEFT | DT_SINGLELINE | DT_VCENTER | DT_END_ELLIPSIS,
    );
    SelectObject(dis.hDC, old_font);
}

/// Whether `h` should show where the keyboard focus is. Windows hides focus
/// rectangles until the keyboard is used.
unsafe fn shows_focus(h: HWND) -> bool {
    let state = SendMessageW(h, WM_QUERYUISTATE, None, None).0 as u32;
    state & UISF_HIDEFOCUS == 0
}

/// Whether `h` is a checkbox. The style alone is not enough: a drop-down list
/// and some tooltips carry the same style number.
unsafe fn is_checkbox(h: HWND) -> bool {
    let mut class = [0u16; 16];
    let n = GetClassNameW(h, &mut class) as usize;
    let style = GetWindowLongW(h, GWL_STYLE) as u32 & BS_TYPEMASK as u32;
    String::from_utf16_lossy(&class[..n]).eq_ignore_ascii_case("Button")
        && style == BS_AUTOCHECKBOX as u32
}

/// Draw a checkbox as a switch, or a footer button as a Windows 11 button.
/// Anything else is left to Windows.
unsafe fn custom_draw(st: &State, lparam: LPARAM) -> LRESULT {
    let cd = &*(lparam.0 as *const NMCUSTOMDRAW);
    if cd.hdr.code != NM_CUSTOMDRAW {
        return LRESULT(0);
    }
    let h = cd.hdr.hwndFrom;
    let id = cd.hdr.idFrom;
    let is_switch = is_checkbox(h);
    let is_button = [ID_SAVE, ID_CANCEL, ID_SAVE_AS, ID_DEFAULTS].contains(&id);
    if !is_switch && !is_button {
        return LRESULT(CDRF_DODEFAULT as isize);
    }
    if cd.dwDrawStage != CDDS_PREPAINT {
        return LRESULT(CDRF_DODEFAULT as isize);
    }
    let rc = cd.rc;
    let look = Look {
        enabled: IsWindowEnabled(h).as_bool(),
        hot: cd.uItemState.0 & CDIS_HOT.0 != 0,
        pressed: cd.uItemState.0 & CDIS_SELECTED.0 != 0,
        focus: cd.uItemState.0 & CDIS_FOCUS.0 != 0 && shows_focus(h),
    };
    let mut buf = [0u16; 64];
    let n = GetWindowTextW(h, &mut buf) as usize;
    let mut label: Vec<u16> = buf[..n].to_vec();
    SetBkMode(cd.hdc, TRANSPARENT);
    let old_font = SelectObject(cd.hdc, st.font.into());
    if is_switch {
        let on = SendMessageW(h, BM_GETCHECK, None, None).0 == BST_CHECKED.0 as isize;
        let x = rc.right - fluent::SWITCH_W - 4;
        let y = rc.top + (rc.bottom - rc.top - fluent::SWITCH_H) / 2;
        fluent::smooth(
            cd.hdc,
            rc,
            fluent::CARD,
            &fluent::switch(x, y, on, look, st.accent),
        );
        let day_switch = (ID_LOCK_DAY..ID_LOCK_DAY + 7).contains(&id);
        let strict = (ID_LOCK_STRICT..ID_LOCK_STRICT + 7).contains(&id);
        if !day_switch {
            if !strict {
                label = if on { "On" } else { "Off" }.encode_utf16().collect();
            }
            SetTextColor(
                cd.hdc,
                rgb(if look.enabled {
                    fluent::TEXT
                } else {
                    fluent::TEXT_DISABLED
                }),
            );
            let mut text_rc = rect(rc.left, rc.top, x - 12, rc.bottom);
            DrawTextW(
                cd.hdc,
                &mut label,
                &mut text_rc,
                DT_RIGHT | DT_SINGLELINE | DT_VCENTER | DT_NOPREFIX,
            );
        }
    } else {
        let primary = id == ID_SAVE;
        fluent::smooth(
            cd.hdc,
            rc,
            fluent::BACKGROUND,
            &fluent::button(rc, primary, look, st.accent),
        );
        let colour = match (primary, look.enabled) {
            (true, true) => 0xFFFFFF,
            (false, true) => fluent::TEXT,
            (_, false) => fluent::TEXT_DISABLED,
        };
        SetTextColor(cd.hdc, rgb(colour));
        let mut text_rc = rc;
        DrawTextW(
            cd.hdc,
            &mut label,
            &mut text_rc,
            DT_CENTER | DT_SINGLELINE | DT_VCENTER | DT_NOPREFIX,
        );
    }
    SelectObject(cd.hdc, old_font);
    LRESULT(CDRF_SKIPDEFAULT as isize)
}

/// Repaint the frame of the text box `edit`, whose focus changed.
unsafe fn repaint_field(st: &State, edit: HWND) {
    if let Some(f) = st.fields.iter().find(|f| f.edit == edit) {
        let r = rect(
            f.rect.left,
            f.rect.top - st.scroll,
            f.rect.right,
            f.rect.bottom - st.scroll,
        );
        let _ = InvalidateRect(Some(st.pane), Some(&r), false);
    }
}

/// The settings window's own keyboard shortcuts, as set on its Hotkeys page.
/// They work wherever the focus is inside the window, as last saved. Returns
/// whether `msg` was one of them, in which case it must not be passed on.
///
/// Esc closing the window normally comes from Windows' dialog keys. Here it is
/// swallowed unless Esc is the key set for closing, so that changing or
/// removing that shortcut really does take Esc away.
///
/// A control that asks for the key itself, such as an open dropdown closing
/// its list on Esc, gets it instead.
pub fn shortcut(hwnd: HWND, msg: &MSG, keys: &Shortcuts) -> bool {
    unsafe {
        if msg.message != WM_KEYDOWN && msg.message != WM_SYSKEYDOWN {
            return false;
        }
        if msg.hwnd != hwnd && !IsChild(hwnd, msg.hwnd).as_bool() {
            return false;
        }
        let wants = SendMessageW(
            msg.hwnd,
            WM_GETDLGCODE,
            Some(WPARAM(msg.wParam.0)),
            Some(LPARAM(msg as *const MSG as isize)),
        );
        if wants.0 as u32 & DLGC_WANTMESSAGE != 0 {
            return false;
        }
        let vk = msg.wParam.0 as u32;
        let set = &keys.settings;
        let is = |value: &String| shortcuts::pressed(keys, value, vk);
        if is(&set.search) {
            if let Ok(search) = GetDlgItem(Some(hwnd), ID_SEARCH as i32) {
                let _ = SetFocus(Some(search));
                SendMessageW(search, EM_SETSEL, Some(WPARAM(0)), Some(LPARAM(-1)));
            }
        } else if is(&set.save) {
            SendMessageW(hwnd, WM_COMMAND, Some(WPARAM(ID_SAVE)), None);
        } else if is(&set.close) {
            SendMessageW(hwnd, WM_COMMAND, Some(WPARAM(ID_CANCEL)), None);
        } else if is(&set.next_page) {
            turn_page(hwnd, 1);
        } else if is(&set.previous_page) {
            turn_page(hwnd, -1);
        } else {
            return msg.message == WM_KEYDOWN && vk == u32::from(VK_ESCAPE.0);
        }
        true
    }
}

/// What a shortcut box on the Hotkeys page accepts.
#[derive(Clone, Copy, PartialEq)]
enum KeyBox {
    /// A global hotkey, which needs a modifier.
    Global,
    /// A key used only inside the app, where it is checked on Save.
    Local(Place),
}

/// The kind of shortcut box `h` is, if it is one.
unsafe fn key_box(h: HWND) -> Option<KeyBox> {
    match GetDlgCtrlID(h) as usize {
        ID_HK_TOGGLE | ID_HK_SKIP => Some(KeyBox::Global),
        id if (ID_KEY..ID_KEY + shortcuts::ALL.len()).contains(&id) => {
            Some(KeyBox::Local(shortcuts::ALL[id - ID_KEY].place))
        }
        _ => None,
    }
}

/// Keys that boxes of the settings window `hwnd` handle themselves, before
/// any shortcut or dialog key: recording a shortcut, and stepping a lock time
/// with Up and Down. Returns whether `msg` was used up, in which case it must
/// not be passed on.
pub fn box_key(hwnd: HWND, msg: &MSG) -> bool {
    unsafe { IsChild(hwnd, msg.hwnd).as_bool() && (record_key(msg) || step_key(msg)) }
}

/// Up and Down in an hour or minute box step it, like its chevrons.
unsafe fn step_key(msg: &MSG) -> bool {
    if msg.message != WM_KEYDOWN || !is_clock_box(msg.hwnd) {
        return false;
    }
    let delta = match VIRTUAL_KEY(msg.wParam.0 as u16) {
        VK_UP => 1,
        VK_DOWN => -1,
        _ => return false,
    };
    step_clock(msg.hwnd, delta);
    true
}

/// Record a key pressed in a shortcut box, replacing the whole shortcut at
/// once. Returns whether `msg` was used up.
///
/// Backspace and Delete on their own empty the box, which removes the
/// shortcut, and Tab and Shift+Tab still move between controls. A modifier on
/// its own waits for the key that goes with it. A key the box refuses, see
/// [`record`], leaves the box as it was and is passed on, so the window's own
/// keys such as Esc and Ctrl+S still work there. Key releases are used up, so
/// that releasing Alt does not open the window menu.
///
/// A global hotkey that is already registered reaches the app as a hotkey
/// instead, and is recorded through [`record_hotkey`].
unsafe fn record_key(msg: &MSG) -> bool {
    if !matches!(
        msg.message,
        WM_KEYDOWN | WM_SYSKEYDOWN | WM_KEYUP | WM_SYSKEYUP
    ) {
        return false;
    }
    let Some(kind) = key_box(msg.hwnd) else {
        return false;
    };
    let vk = msg.wParam.0 as u32;
    let modifiers = shortcuts::held_modifiers();
    let plain = |key: VIRTUAL_KEY| vk == u32::from(key.0) && modifiers == 0;
    if vk == u32::from(VK_TAB.0) && modifiers & !MOD_SHIFT.0 == 0 {
        return false;
    }
    if matches!(msg.message, WM_KEYUP | WM_SYSKEYUP) {
        return true;
    }
    if is_modifier(vk) {
        return true;
    }
    if plain(VK_BACK) || plain(VK_DELETE) {
        set_key_text(msg.hwnd, "");
        return true;
    }
    record(msg.hwnd, kind, hotkeys::Accelerator { modifiers, vk })
}

/// A global hotkey pressed while a shortcut box of the settings window `hwnd`
/// has the focus, with the `lparam` of its `WM_HOTKEY`. Returns whether the
/// box recorded it, in which case its action must not run.
pub fn record_hotkey(hwnd: HWND, lparam: LPARAM) -> bool {
    unsafe {
        let focus = GetFocus();
        if !IsChild(hwnd, focus).as_bool() {
            return false;
        }
        let Some(kind) = key_box(focus) else {
            return false;
        };
        let accel = hotkeys::Accelerator {
            modifiers: (lparam.0 & 0xF) as u32,
            vk: ((lparam.0 >> 16) & 0xFFFF) as u32,
        };
        record(focus, kind, accel)
    }
}

/// Put `accel` into the shortcut box `edit` of kind `kind`, if the box can
/// take it, and say whether it did. A tray menu box takes one letter or digit,
/// a global hotkey needs a modifier, a key in the settings window must leave
/// typing alone, and every key needs a name.
unsafe fn record(edit: HWND, kind: KeyBox, accel: hotkeys::Accelerator) -> bool {
    let letter =
        char::from_u32(accel.vk).is_some_and(|c| c.is_ascii_uppercase() || c.is_ascii_digit());
    let text = match kind {
        KeyBox::Local(Place::Menu) if accel.modifiers != 0 || !letter => None,
        KeyBox::Local(Place::Settings) if !shortcuts::typing_safe(accel) => None,
        KeyBox::Global if accel.modifiers == 0 => None,
        _ => hotkeys::format(accel),
    };
    let Some(text) = text else {
        return false;
    };
    set_key_text(edit, &text);
    true
}

/// Show `text` in the shortcut box `edit`, with the caret after it.
unsafe fn set_key_text(edit: HWND, text: &str) {
    let _ = SetWindowTextW(edit, wide(text).as_pcwstr());
    SendMessageW(edit, EM_SETSEL, Some(WPARAM(usize::MAX)), Some(LPARAM(-1)));
}

/// Whether `vk` is Ctrl, Alt, Shift or Win, on either side.
fn is_modifier(vk: u32) -> bool {
    [
        VK_CONTROL,
        VK_LCONTROL,
        VK_RCONTROL,
        VK_MENU,
        VK_LMENU,
        VK_RMENU,
        VK_SHIFT,
        VK_LSHIFT,
        VK_RSHIFT,
        VK_LWIN,
        VK_RWIN,
    ]
    .iter()
    .any(|k| u32::from(k.0) == vk)
}

/// `" (key)"` for a tooltip or the search box, or nothing when the shortcut
/// is off or removed.
fn key_hint(keys: &Shortcuts, value: &str) -> String {
    match (keys.enabled, value.trim()) {
        (true, key) if !key.is_empty() => format!(" ({key})"),
        _ => String::new(),
    }
}

/// Show the page `step` places after the current one, wrapping around, and
/// leave any search.
unsafe fn turn_page(hwnd: HWND, step: i32) {
    if !query(hwnd).is_empty() {
        if let Ok(search) = GetDlgItem(Some(hwnd), ID_SEARCH as i32) {
            let _ = SetWindowTextW(search, PCWSTR::null());
        }
    }
    let ptr = GetWindowLongPtrW(hwnd, GWLP_USERDATA) as *mut State;
    if ptr.is_null() {
        return;
    }
    let st = &mut *ptr;
    let pages = PAGES.len() as i32;
    st.page = (st.page as i32 + step).rem_euclid(pages) as usize;
    relayout(hwnd, st);
}

/// Update the live status line. Called from the app on every tick.
pub fn refresh_status(hwnd: HWND) {
    unsafe {
        let ptr = GetWindowLongPtrW(hwnd, GWLP_USERDATA) as *mut State;
        if ptr.is_null() {
            return;
        }
        let app = &*(*ptr).app;
        let dnd = app.orch.dnd_status();
        let text = format!("{}   \u{2022}   {}", app.orch.tooltip(), dnd);
        if let Ok(h) = GetDlgItem(Some(hwnd), ID_STATUS as i32) {
            let w = wide(&text);
            let _ = SetWindowTextW(h, w.as_pcwstr());
        }
    }
}

/// Format a duration without a pointless trailing `.0`.
fn num(v: f64) -> String {
    if (v.fract()).abs() < 1e-9 {
        format!("{}", v as i64)
    } else {
        format!("{v}")
    }
}

unsafe fn text_of(parent: HWND, id: usize) -> String {
    let h = GetDlgItem(Some(parent), id as i32).unwrap_or_default();
    if h.is_invalid() {
        return String::new();
    }
    let mut buf = [0u16; 256];
    let n = GetWindowTextW(h, &mut buf);
    String::from_utf16_lossy(&buf[..n as usize])
}

/// Enable or disable dependent controls so irrelevant options cannot be
/// toggled while their parent switch is off.
unsafe fn sync_dependencies(pane: HWND) {
    let set_enabled = |id: usize, enabled: bool| {
        if let Ok(control) = GetDlgItem(Some(pane), id as i32) {
            let _ = EnableWindow(control, enabled);
        }
    };
    let sequence = checked(pane, ID_SEQUENCE);
    set_enabled(ID_AUTO_BREAK, sequence);
    set_enabled(ID_AUTO_FOCUS, sequence);
    set_enabled(ID_REPEAT_CYCLES, sequence);

    let notifications = checked(pane, ID_NOTIFY);
    for id in [ID_N_FS, ID_N_FE, ID_N_BS, ID_N_BE, ID_ALERT_TOAST] {
        set_enabled(id, notifications);
    }

    set_enabled(ID_REQUIRE_DISMISS, checked(pane, ID_ALERT_OVERLAY));

    let dnd = checked(pane, ID_DND);
    set_enabled(ID_DND_SHORT_BREAK, dnd);
    set_enabled(ID_MUTE_TRAY, dnd);
    set_enabled(ID_MUTE_WINDOW, dnd);

    let sounds_unmuted = !checked(pane, ID_MUTE);
    for id in [ID_S_FS, ID_S_FE, ID_S_BS, ID_S_BE] {
        set_enabled(id, sounds_unmuted);
    }
    set_enabled(ID_FLASH_LENGTH, checked(pane, ID_ALERT_FLASH));

    set_enabled(ID_TOPMOST, checked(pane, ID_MINI));

    let hotkeys = checked(pane, ID_HOTKEYS);
    set_enabled(ID_HK_TOGGLE, hotkeys);
    set_enabled(ID_HK_SKIP, hotkeys);

    let keys = checked(pane, ID_KEYS);
    for i in 0..shortcuts::ALL.len() {
        set_enabled(ID_KEY + i, keys);
    }
    let _ = RedrawWindow(
        Some(pane),
        None,
        None,
        RDW_INVALIDATE | RDW_ERASE | RDW_ALLCHILDREN,
    );
}

unsafe fn checked(parent: HWND, id: usize) -> bool {
    let h = GetDlgItem(Some(parent), id as i32).unwrap_or_default();
    !h.is_invalid() && SendMessageW(h, BM_GETCHECK, None, None).0 == BST_CHECKED.0 as isize
}

unsafe fn set_checked(parent: HWND, id: usize, on: bool) {
    if let Ok(h) = GetDlgItem(Some(parent), id as i32) {
        SendMessageW(
            h,
            BM_SETCHECK,
            Some(WPARAM(if on { BST_CHECKED.0 as usize } else { 0 })),
            None,
        );
    }
}

unsafe fn combo_index(parent: HWND, id: usize) -> usize {
    let h = GetDlgItem(Some(parent), id as i32).unwrap_or_default();
    if h.is_invalid() {
        return 0;
    }
    let i = SendMessageW(h, CB_GETCURSEL, None, None).0;
    if i < 0 {
        0
    } else {
        i as usize
    }
}

/// A lock time as the text of its hour and minute boxes, and whether it is in
/// the afternoon. On a 12-hour clock the hour runs from 1 to 12.
fn clock_parts(time: ClockTime, twelve_hour: bool) -> (String, String, bool) {
    let (h, m) = (time.0 / 60, time.0 % 60);
    let hour = if twelve_hour {
        ((h + 11) % 12 + 1).to_string()
    } else {
        format!("{h:02}")
    };
    (hour, format!("{m:02}"), h >= 12)
}

/// The lock time in an hour and minute box, with `afternoon` set only on a
/// 12-hour clock, or `None` if either box is out of range.
fn clock_time(hour: &str, minute: &str, afternoon: Option<bool>) -> Option<ClockTime> {
    let h: u16 = hour.trim().parse().ok()?;
    let m: u16 = minute.trim().parse().ok()?;
    let h = match afternoon {
        Some(pm) if (1..=12).contains(&h) => h % 12 + if pm { 12 } else { 0 },
        None if h < 24 => h,
        _ => return None,
    };
    (m < 60).then_some(ClockTime(h * 60 + m))
}

/// Whether `h` is the hour or minute box of a lock time.
unsafe fn is_clock_box(h: HWND) -> bool {
    let id = GetDlgCtrlID(h) as usize;
    (ID_LOCK_HOUR..ID_LOCK_HOUR + 7).contains(&id)
        || (ID_LOCK_MINUTE..ID_LOCK_MINUTE + 7).contains(&id)
}

/// Move the hour or minute box `edit` by `delta`, wrapping around at either
/// end, and select the new value so typing replaces it. From an empty box, up
/// gives the lowest value and down the highest.
unsafe fn step_clock(edit: HWND, delta: i32) {
    let id = GetDlgCtrlID(edit) as usize;
    let twelve_hour = day_halves().is_some();
    let (low, high, pad) = match id {
        _ if (ID_LOCK_MINUTE..ID_LOCK_MINUTE + 7).contains(&id) => (0, 59, true),
        _ if twelve_hour => (1, 12, false),
        _ => (0, 23, true),
    };
    let mut buf = [0u16; 8];
    let n = GetWindowTextW(edit, &mut buf) as usize;
    let current = String::from_utf16_lossy(&buf[..n])
        .trim()
        .parse::<i32>()
        .map_or(if delta > 0 { low - 1 } else { low }, |v| {
            v.clamp(low, high)
        });
    let span = high - low + 1;
    let next = (current - low + delta).rem_euclid(span) + low;
    let text = if pad {
        format!("{next:02}")
    } else {
        next.to_string()
    };
    let _ = SetWindowTextW(edit, wide(&text).as_pcwstr());
    SendMessageW(edit, EM_SETSEL, Some(WPARAM(0)), Some(LPARAM(-1)));
}

/// A duration field: `Ok(minutes)`, or `Err(())` if the text is unusable.
fn parse_minutes(s: &str) -> Result<f64, ()> {
    s.trim()
        .parse::<f64>()
        .ok()
        .filter(|v| v.is_finite() && *v > 0.0)
        .ok_or(())
}

/// Read the preset fields, reporting the first unusable one by name rather than
/// silently reverting it behind the user's back.
unsafe fn read_preset(pane: HWND, base: &Preset) -> Result<Preset, &'static str> {
    let name = text_of(pane, ID_NAME).trim().to_string();
    Ok(Preset {
        name: if name.is_empty() {
            base.name.clone()
        } else {
            name
        },
        focus_minutes: parse_minutes(&text_of(pane, ID_FOCUS)).map_err(|_| "Focus (minutes)")?,
        short_break_minutes: parse_minutes(&text_of(pane, ID_SHORT))
            .map_err(|_| "Short break (minutes)")?,
        long_break_minutes: parse_minutes(&text_of(pane, ID_LONG))
            .map_err(|_| "Long break (minutes)")?,
        sessions_before_long_break: text_of(pane, ID_SESSIONS)
            .trim()
            .parse::<u32>()
            .ok()
            .filter(|n| *n > 0)
            .ok_or("Sessions per long break")?,
    })
}

/// Read the Lock page, or say what is wrong with it.
unsafe fn read_lock(pane: HWND, lock: &mut LockSettings) -> Result<(), String> {
    for (index, name) in DAY_NAMES.iter().enumerate() {
        let afternoon = GetDlgItem(Some(pane), (ID_LOCK_HALF + index) as i32)
            .is_ok()
            .then(|| combo_index(pane, ID_LOCK_HALF + index) == 1);
        let hours = if afternoon.is_some() {
            "1 to 12"
        } else {
            "0 to 23"
        };
        let time = clock_time(
            &text_of(pane, ID_LOCK_HOUR + index),
            &text_of(pane, ID_LOCK_MINUTE + index),
            afternoon,
        )
        .ok_or_else(|| {
            format!("{name}'s lock needs an hour from {hours} and minutes from 0 to 59.")
        })?;
        *lock.day_mut(index) = DayLock {
            enabled: checked(pane, ID_LOCK_DAY + index),
            time,
            strict: checked(pane, ID_LOCK_STRICT + index),
        };
    }
    for (i, n) in LOCK_NUMBERS.iter().enumerate() {
        let value = text_of(pane, ID_LOCK_NUMBER + i)
            .trim()
            .parse()
            .ok()
            .filter(|v| (n.min..=n.max).contains(v))
            .ok_or_else(|| {
                let (label, min, max) = (n.label, n.min, n.max);
                format!("\"{label}\" needs a whole number from {min} to {max}.")
            })?;
        (n.set)(lock, value);
    }
    let max = lock.max_warn_before_lock();
    if lock.warn_before_lock_minutes > max {
        return Err(format!(
            "\"Warn before lock (min)\" cannot be longer than the cutoff, so at most {max}."
        ));
    }
    Ok(())
}

unsafe fn collect(st: &mut State, save_as_new: bool) -> Result<Config, String> {
    let pane = st.pane;
    let app = &mut *st.app;
    let mut cfg = app.config().clone();

    let idx = st.current.min(st.presets.len().saturating_sub(1));
    read_lock(pane, &mut cfg.lock)?;
    let edited = read_preset(pane, &st.presets[idx])
        .map_err(|field| format!("\"{field}\" needs a number greater than zero."))?;
    if save_as_new && !st.presets.iter().any(|p| p.name == edited.name) {
        st.presets.push(edited.clone());
    } else {
        st.presets[idx] = edited.clone();
    }
    cfg.presets = st.presets.clone();
    cfg.active_preset = edited.name;

    cfg.behavior.sequence_enabled = checked(pane, ID_SEQUENCE);
    cfg.behavior.auto_start_break = checked(pane, ID_AUTO_BREAK);
    cfg.behavior.auto_start_focus = checked(pane, ID_AUTO_FOCUS);
    cfg.behavior.repeat_cycles = checked(pane, ID_REPEAT_CYCLES);
    cfg.behavior.strict_focus = checked(pane, ID_STRICT);
    cfg.behavior.restore_session_on_restart = checked(pane, ID_RESTORE_SESSION);
    cfg.behavior.wake_policy = match combo_index(pane, ID_WAKE) {
        1 => WakePolicy::IgnoreSleep,
        2 => WakePolicy::Pause,
        _ => WakePolicy::CountSleep,
    };

    cfg.dnd.enabled = checked(pane, ID_DND);
    cfg.dnd.keep_on_short_break = checked(pane, ID_DND_SHORT_BREAK);
    cfg.dnd.mute_tray_icon = checked(pane, ID_MUTE_TRAY);
    cfg.dnd.mute_window = checked(pane, ID_MUTE_WINDOW);
    cfg.display.mini_window = checked(pane, ID_MINI);
    cfg.display.always_on_top = checked(pane, ID_TOPMOST);

    cfg.notifications.enabled = checked(pane, ID_NOTIFY);
    cfg.notifications.events.focus_start = checked(pane, ID_N_FS);
    cfg.notifications.events.focus_end = checked(pane, ID_N_FE);
    cfg.notifications.events.break_start = checked(pane, ID_N_BS);
    cfg.notifications.events.break_end = checked(pane, ID_N_BE);

    cfg.alerts.toast = checked(pane, ID_ALERT_TOAST);
    cfg.alerts.overlay = checked(pane, ID_ALERT_OVERLAY);
    cfg.alerts.flash = checked(pane, ID_ALERT_FLASH);
    cfg.alerts.require_dismiss = checked(pane, ID_REQUIRE_DISMISS);

    cfg.sounds.muted = checked(pane, ID_MUTE);
    cfg.sounds.events.focus_start = checked(pane, ID_S_FS);
    cfg.sounds.events.focus_end = checked(pane, ID_S_FE);
    cfg.sounds.events.break_start = checked(pane, ID_S_BS);
    cfg.sounds.events.break_end = checked(pane, ID_S_BE);
    cfg.alerts.flash_length = LengthPreset::from_index(combo_index(pane, ID_FLASH_LENGTH));

    cfg.hotkeys.enabled = checked(pane, ID_HOTKEYS);
    cfg.hotkeys.toggle = text_of(pane, ID_HK_TOGGLE).trim().to_string();
    cfg.hotkeys.skip = text_of(pane, ID_HK_SKIP).trim().to_string();

    cfg.shortcuts.enabled = checked(pane, ID_KEYS);
    for (i, key) in shortcuts::ALL.iter().enumerate() {
        let mut value = text_of(pane, ID_KEY + i).trim().to_string();
        if key.place == Place::Menu {
            value = value.to_uppercase();
        }
        *(key.slot)(&mut cfg.shortcuts) = value;
    }
    shortcuts::validate(&cfg.shortcuts)?;

    Ok(cfg)
}

/// Load the selected preset's values into the edit fields.
unsafe fn show_preset(st: &State) {
    let Some(p) = st.presets.get(st.current) else {
        return;
    };
    for (id, val) in [
        (ID_NAME, p.name.clone()),
        (ID_FOCUS, num(p.focus_minutes)),
        (ID_SHORT, num(p.short_break_minutes)),
        (ID_LONG, num(p.long_break_minutes)),
        (ID_SESSIONS, p.sessions_before_long_break.to_string()),
    ] {
        if let Ok(h) = GetDlgItem(Some(st.pane), id as i32) {
            let t = wide(&val);
            let _ = SetWindowTextW(h, t.as_pcwstr());
        }
    }
}

/// Put every control back to the built-in defaults, without saving.
unsafe fn restore_defaults(st: &mut State) {
    let pane = st.pane;
    let d = Config::default();
    st.presets = d.presets.clone();
    st.current = 0;
    if let Ok(h) = GetDlgItem(Some(pane), ID_PRESET as i32) {
        SendMessageW(h, CB_RESETCONTENT, None, None);
        for p in &st.presets {
            let t = wide(&p.name);
            SendMessageW(
                h,
                CB_ADDSTRING,
                None,
                Some(LPARAM(t.as_pcwstr().0 as isize)),
            );
        }
        SendMessageW(h, CB_SETCURSEL, Some(WPARAM(0)), None);
    }
    show_preset(st);

    for (id, v) in [
        (ID_SEQUENCE, d.behavior.sequence_enabled),
        (ID_AUTO_BREAK, d.behavior.auto_start_break),
        (ID_AUTO_FOCUS, d.behavior.auto_start_focus),
        (ID_REPEAT_CYCLES, d.behavior.repeat_cycles),
        (ID_STRICT, d.behavior.strict_focus),
        (ID_RESTORE_SESSION, d.behavior.restore_session_on_restart),
        (ID_DND, d.dnd.enabled),
        (ID_DND_SHORT_BREAK, d.dnd.keep_on_short_break),
        (ID_MUTE_TRAY, d.dnd.mute_tray_icon),
        (ID_MUTE_WINDOW, d.dnd.mute_window),
        (ID_MINI, d.display.mini_window),
        (ID_TOPMOST, d.display.always_on_top),
        (ID_NOTIFY, d.notifications.enabled),
        (ID_N_FS, d.notifications.events.focus_start),
        (ID_N_FE, d.notifications.events.focus_end),
        (ID_N_BS, d.notifications.events.break_start),
        (ID_N_BE, d.notifications.events.break_end),
        (ID_MUTE, d.sounds.muted),
        (ID_S_FS, d.sounds.events.focus_start),
        (ID_S_FE, d.sounds.events.focus_end),
        (ID_S_BS, d.sounds.events.break_start),
        (ID_S_BE, d.sounds.events.break_end),
        (ID_ALERT_TOAST, d.alerts.toast),
        (ID_ALERT_OVERLAY, d.alerts.overlay),
        (ID_ALERT_FLASH, d.alerts.flash),
        (ID_REQUIRE_DISMISS, d.alerts.require_dismiss),
        (ID_HOTKEYS, d.hotkeys.enabled),
        (ID_AUTOSTART, false),
    ] {
        set_checked(pane, id, v);
    }
    let set_text = |id: usize, text: &str| {
        if let Ok(h) = GetDlgItem(Some(pane), id as i32) {
            let _ = SetWindowTextW(h, wide(text).as_pcwstr());
        }
    };
    for index in 0..7 {
        let lock = d.lock.day(index);
        set_checked(pane, ID_LOCK_DAY + index, lock.enabled);
        set_checked(pane, ID_LOCK_STRICT + index, lock.strict);
        let twelve_hour = GetDlgItem(Some(pane), (ID_LOCK_HALF + index) as i32).ok();
        let (hour, minute, afternoon) = clock_parts(lock.time, twelve_hour.is_some());
        set_text(ID_LOCK_HOUR + index, &hour);
        set_text(ID_LOCK_MINUTE + index, &minute);
        if let Some(half) = twelve_hour {
            SendMessageW(half, CB_SETCURSEL, Some(WPARAM(afternoon as usize)), None);
        }
    }
    for (i, n) in LOCK_NUMBERS.iter().enumerate() {
        set_text(ID_LOCK_NUMBER + i, &(n.get)(&d.lock).to_string());
    }
    set_checked(pane, ID_KEYS, d.shortcuts.enabled);
    for (i, key) in shortcuts::ALL.iter().enumerate() {
        set_text(ID_KEY + i, (key.get)(&d.shortcuts));
    }
    if let Ok(h) = GetDlgItem(Some(pane), ID_WAKE as i32) {
        let sel = match d.behavior.wake_policy {
            WakePolicy::CountSleep => 0,
            WakePolicy::IgnoreSleep => 1,
            WakePolicy::Pause => 2,
        };
        SendMessageW(h, CB_SETCURSEL, Some(WPARAM(sel)), None);
    }
    if let Ok(h) = GetDlgItem(Some(pane), ID_FLASH_LENGTH as i32) {
        SendMessageW(
            h,
            CB_SETCURSEL,
            Some(WPARAM(d.alerts.flash_length.index())),
            None,
        );
    }
    for (id, v) in [
        (ID_HK_TOGGLE, d.hotkeys.toggle),
        (ID_HK_SKIP, d.hotkeys.skip),
    ] {
        if let Ok(h) = GetDlgItem(Some(pane), id as i32) {
            let t = wide(&v);
            let _ = SetWindowTextW(h, t.as_pcwstr());
        }
    }
}

/// Give a static control or a text box the colours of the surface it sits on.
/// Text belonging to a disabled control is greyed with it.
unsafe fn paint_static(st: &State, in_pane: bool, wparam: WPARAM, lparam: LPARAM) -> LRESULT {
    let child = HWND(lparam.0 as *mut _);
    let how = GetWindowLongPtrW(child, GWLP_USERDATA);
    let hdc = HDC(wparam.0 as *mut _);
    let enabled = IsWindowEnabled(child).as_bool() && linked_enabled(child);
    let colour = match how {
        _ if !enabled => fluent::TEXT_DISABLED,
        paint_as::CARD_GREY | paint_as::PAGE_GREY | paint_as::WINDOW_GREY => fluent::TEXT_SECONDARY,
        _ => fluent::TEXT,
    };
    SetTextColor(hdc, rgb(colour));
    let brush = match how {
        paint_as::FIELD if enabled => {
            SetBkColor(hdc, rgb(fluent::FIELD));
            st.field
        }
        paint_as::FIELD => {
            SetBkColor(hdc, rgb(fluent::CARD));
            st.card
        }
        paint_as::CARD | paint_as::CARD_GREY if in_pane => {
            SetBkMode(hdc, TRANSPARENT);
            st.card
        }
        _ => {
            SetBkMode(hdc, TRANSPARENT);
            st.page_bg
        }
    };
    LRESULT(brush.0 as isize)
}

/// Whether the control a caption or description belongs to is enabled. Any
/// other control counts as enabled.
unsafe fn linked_enabled(child: HWND) -> bool {
    let id = GetDlgCtrlID(child) as usize;
    let owner = match id {
        DESC_ID.. => id - DESC_ID,
        CAPTION_ID.. => id - CAPTION_ID,
        _ => return true,
    };
    let Ok(parent) = GetParent(child) else {
        return true;
    };
    match GetDlgItem(Some(parent), owner as i32) {
        Ok(h) => IsWindowEnabled(h).as_bool(),
        Err(_) => true,
    }
}

/// Step a box for a chevron just pressed, and keep stepping on
/// [`SPIN_TIMER`] while it is held.
unsafe fn start_spin(st: &mut State, spin: Spinning) {
    st.spinning = Some(spin);
    step_clock(spin.edit, spin.delta);
    SetCapture(st.pane);
    SetTimer(Some(st.pane), SPIN_TIMER, SPIN_DELAY, None);
    repaint_field(st, spin.edit);
}

/// Step the box of the held chevron again, faster from now on.
unsafe fn repeat_spin(st: &mut State) {
    let Some(spin) = st.spinning else {
        let _ = KillTimer(Some(st.pane), SPIN_TIMER);
        return;
    };
    step_clock(spin.edit, spin.delta);
    SetTimer(Some(st.pane), SPIN_TIMER, SPIN_REPEAT, None);
}

/// Let go of the held chevron, if any.
unsafe fn stop_spin(st: &mut State) {
    let Some(spin) = st.spinning.take() else {
        return;
    };
    let _ = KillTimer(Some(st.pane), SPIN_TIMER);
    if GetCapture() == st.pane {
        let _ = ReleaseCapture();
    }
    repaint_field(st, spin.edit);
}

/// Toggle the switch of the card under a click, the way a Windows 11 settings
/// card does, or focus the text box whose frame was clicked, stepping it when
/// the click was on one of its chevrons.
unsafe fn click_pane(st: &mut State, x: i32, y: i32) {
    let point = POINT {
        x,
        y: y + st.scroll,
    };
    if let Some(f) = st
        .fields
        .iter()
        .find(|f| PtInRect(&f.rect, point).as_bool())
    {
        let edit = f.edit;
        let [up, down] = f.chevrons();
        let delta = match f.spin && IsWindowEnabled(edit).as_bool() {
            true if PtInRect(&up, point).as_bool() => 1,
            true if PtInRect(&down, point).as_bool() => -1,
            _ => 0,
        };
        let _ = SetFocus(Some(edit));
        if delta != 0 {
            start_spin(st, Spinning { edit, delta });
        }
        return;
    }
    let Some(card) = st.cards.iter().find(|c| PtInRect(&c.rect, point).as_bool()) else {
        return;
    };
    if !card.toggles || !IsWindowEnabled(card.control).as_bool() {
        return;
    }
    let _ = SetFocus(Some(card.control));
    let id = GetDlgCtrlID(card.control) as usize;
    let pane = st.pane;
    set_checked(pane, id, !checked(pane, id));
    SendMessageW(
        pane,
        WM_COMMAND,
        Some(WPARAM(id | ((BN_CLICKED as usize) << 16))),
        Some(LPARAM(card.control.0 as isize)),
    );
}

unsafe extern "system" fn pane_wndproc(
    hwnd: HWND,
    msg: u32,
    wparam: WPARAM,
    lparam: LPARAM,
) -> LRESULT {
    let ptr = GetWindowLongPtrW(hwnd, GWLP_USERDATA) as *mut State;
    if ptr.is_null() {
        return DefWindowProcW(hwnd, msg, wparam, lparam);
    }
    let st = &mut *ptr;

    match msg {
        WM_COMMAND => {
            let code = ((wparam.0 >> 16) & 0xFFFF) as u32;
            if code == EN_SETFOCUS || code == EN_KILLFOCUS {
                repaint_field(st, HWND(lparam.0 as *mut _));
            }
            if let Ok(parent) = GetParent(hwnd) {
                SendMessageW(parent, WM_COMMAND, Some(wparam), Some(lparam));
            }
            LRESULT(0)
        }
        WM_NOTIFY => custom_draw(st, lparam),
        WM_ERASEBKGND => LRESULT(1),
        WM_PAINT => {
            let mut ps = PAINTSTRUCT::default();
            let hdc = BeginPaint(hwnd, &mut ps);
            paint_pane(st, hwnd, hdc);
            let _ = EndPaint(hwnd, &ps);
            LRESULT(0)
        }
        WM_LBUTTONDOWN => {
            let x = (lparam.0 & 0xFFFF) as i16 as i32;
            let y = ((lparam.0 >> 16) & 0xFFFF) as i16 as i32;
            click_pane(st, x, y);
            LRESULT(0)
        }
        WM_TIMER if wparam.0 == SPIN_TIMER => {
            repeat_spin(st);
            LRESULT(0)
        }
        WM_LBUTTONUP | WM_CAPTURECHANGED => {
            stop_spin(st);
            LRESULT(0)
        }
        WM_CTLCOLORSTATIC | WM_CTLCOLOREDIT => paint_static(st, true, wparam, lparam),
        WM_VSCROLL => {
            let mut si = SCROLLINFO {
                cbSize: std::mem::size_of::<SCROLLINFO>() as u32,
                fMask: SIF_ALL,
                ..Default::default()
            };
            let _ = GetScrollInfo(hwnd, SB_VERT, &mut si);
            let pos = match SCROLLBAR_COMMAND((wparam.0 & 0xFFFF) as i32) {
                SB_LINEUP => st.scroll - 28,
                SB_LINEDOWN => st.scroll + 28,
                SB_PAGEUP => st.scroll - si.nPage as i32,
                SB_PAGEDOWN => st.scroll + si.nPage as i32,
                SB_THUMBTRACK | SB_THUMBPOSITION => si.nTrackPos,
                SB_TOP => 0,
                SB_BOTTOM => st.content_h,
                _ => st.scroll,
            };
            scroll_to(st, pos);
            LRESULT(0)
        }
        WM_MOUSEWHEEL => {
            let delta = ((wparam.0 >> 16) & 0xFFFF) as i16;
            scroll_to(st, st.scroll - delta as i32 * 48 / 120);
            LRESULT(0)
        }
        _ => DefWindowProcW(hwnd, msg, wparam, lparam),
    }
}

/// Paint the window around the pane: the background, the search box, the icon
/// beside the page title and the line above the footer.
unsafe fn paint_window(st: &State, hwnd: HWND, hdc: HDC) {
    FillRect(hdc, &rect(0, 0, CLIENT_W, CLIENT_H), st.page_bg);
    fluent::smooth(
        hdc,
        rect(0, FOOTER_Y, CLIENT_W, FOOTER_Y + 1),
        fluent::CARD_EDGE,
        &[],
    );
    let focused = GetDlgCtrlID(GetFocus()) as usize == ID_SEARCH;
    fluent::smooth(
        hdc,
        SEARCH_BOX,
        fluent::BACKGROUND,
        &fluent::text_box(SEARCH_BOX, focused, true, st.accent),
    );
    let old_font = SelectObject(hdc, st.icons.into());
    SetBkMode(hdc, TRANSPARENT);
    SetTextColor(hdc, rgb(fluent::TEXT_SECONDARY));
    draw_icon(
        hdc,
        "\u{E721}",
        SEARCH_BOX.right - 32,
        SEARCH_BOX.top,
        24,
        SEARCH_BOX.bottom - SEARCH_BOX.top,
    );
    let page_icon = if query(hwnd).is_empty() {
        PAGE_ICONS.get(st.page).copied().unwrap_or_default()
    } else {
        "\u{E721}"
    };
    SelectObject(hdc, st.title_icons.into());
    SetTextColor(hdc, rgb(fluent::TEXT));
    draw_icon(
        hdc,
        page_icon,
        TITLE_ICON.left,
        TITLE_ICON.top,
        TITLE_ICON.right - TITLE_ICON.left,
        TITLE_ICON.bottom - TITLE_ICON.top,
    );
    SelectObject(hdc, old_font);
}

unsafe extern "system" fn wndproc(hwnd: HWND, msg: u32, wparam: WPARAM, lparam: LPARAM) -> LRESULT {
    let ptr = GetWindowLongPtrW(hwnd, GWLP_USERDATA) as *mut State;
    if ptr.is_null() {
        return DefWindowProcW(hwnd, msg, wparam, lparam);
    }

    match msg {
        WM_ERASEBKGND => LRESULT(1),
        WM_PAINT => {
            let mut ps = PAINTSTRUCT::default();
            let hdc = BeginPaint(hwnd, &mut ps);
            paint_window(&*ptr, hwnd, hdc);
            let _ = EndPaint(hwnd, &ps);
            LRESULT(0)
        }
        WM_NOTIFY => custom_draw(&*ptr, lparam),
        WM_LBUTTONDOWN => {
            let point = POINT {
                x: (lparam.0 & 0xFFFF) as i16 as i32,
                y: ((lparam.0 >> 16) & 0xFFFF) as i16 as i32,
            };
            if PtInRect(&SEARCH_BOX, point).as_bool() {
                if let Ok(h) = GetDlgItem(Some(hwnd), ID_SEARCH as i32) {
                    let _ = SetFocus(Some(h));
                }
            }
            LRESULT(0)
        }
        WM_CTLCOLORSTATIC | WM_CTLCOLOREDIT => paint_static(&*ptr, false, wparam, lparam),
        WM_CTLCOLORLISTBOX => {
            SetBkMode(HDC(wparam.0 as *mut _), TRANSPARENT);
            LRESULT((*ptr).page_bg.0 as isize)
        }
        WM_DRAWITEM => {
            let dis = &*(lparam.0 as *const DRAWITEMSTRUCT);
            if dis.CtlID == ID_NAV as u32 && dis.itemID != u32::MAX {
                paint_nav_item(&*ptr, dis);
            }
            LRESULT(1)
        }
        WM_COMMAND => {
            let id = wparam.0 & 0xFFFF;
            let code = ((wparam.0 >> 16) & 0xFFFF) as u32;
            let st = &mut *ptr;
            match (id, code) {
                (ID_SEARCH, EN_CHANGE) => relayout(hwnd, st),
                (ID_SEARCH, EN_SETFOCUS | EN_KILLFOCUS) => {
                    let _ = InvalidateRect(Some(hwnd), Some(&SEARCH_BOX), false);
                }
                (ID_NAV, LBN_SELCHANGE) => {
                    let sel = SendMessageW(
                        GetDlgItem(Some(hwnd), ID_NAV as i32).unwrap_or_default(),
                        LB_GETCURSEL,
                        None,
                        None,
                    )
                    .0;
                    if sel >= 0 {
                        st.page = sel as usize;
                        relayout(hwnd, st);
                    }
                }
                (ID_PRESET, CBN_SELCHANGE) => {
                    let idx = st.current.min(st.presets.len().saturating_sub(1));
                    if let Ok(p) = read_preset(st.pane, &st.presets[idx]) {
                        st.presets[idx] = p;
                    }
                    st.current = combo_index(st.pane, ID_PRESET);
                    show_preset(st);
                }
                (ID_DEFAULTS, BN_CLICKED) => {
                    restore_defaults(st);
                    sync_dependencies(st.pane);
                }
                (
                    ID_SEQUENCE | ID_NOTIFY | ID_ALERT_OVERLAY | ID_ALERT_FLASH | ID_DND | ID_MUTE
                    | ID_MINI | ID_HOTKEYS | ID_KEYS | ID_S_FS | ID_S_FE | ID_S_BS | ID_S_BE,
                    BN_CLICKED,
                ) => sync_dependencies(st.pane),
                (ID_SAVE | ID_SAVE_AS, BN_CLICKED) => match collect(st, id == ID_SAVE_AS) {
                    Ok(cfg) => {
                        let autostart = crate::os::autostart::set(checked(st.pane, ID_AUTOSTART));
                        (*st.app).apply_config(cfg);
                        if let Err(why) = autostart {
                            let msg = wide(&format!(
                                "Start with Windows: {why}\n\nEverything else has been saved."
                            ));
                            let cap = wide(crate::APP_NAME);
                            MessageBoxW(
                                Some(hwnd),
                                msg.as_pcwstr(),
                                cap.as_pcwstr(),
                                MB_OK | MB_ICONWARNING,
                            );
                        }
                        let _ = DestroyWindow(hwnd);
                    }
                    Err(problem) => {
                        let msg = wide(&format!("{problem}\n\nNothing has been saved."));
                        let cap = wide(crate::APP_NAME);
                        MessageBoxW(
                            Some(hwnd),
                            msg.as_pcwstr(),
                            cap.as_pcwstr(),
                            MB_OK | MB_ICONWARNING,
                        );
                    }
                },
                (ID_CANCEL, BN_CLICKED) => {
                    let _ = DestroyWindow(hwnd);
                }
                _ => {}
            }
            LRESULT(0)
        }
        WM_CLOSE => {
            let _ = DestroyWindow(hwnd);
            LRESULT(0)
        }
        WM_DESTROY => {
            let st = Box::from_raw(ptr);
            TIP_TEXT.with(|c| c.borrow_mut().clear());
            for font in [
                st.font,
                st.small,
                st.bold,
                st.title,
                st.icons,
                st.title_icons,
                st.chevrons,
            ] {
                let _ = DeleteObject(font.into());
            }
            for brush in [st.page_bg, st.card, st.field] {
                let _ = DeleteObject(brush.into());
            }
            (*st.app).on_settings_closed();
            SetWindowLongPtrW(hwnd, GWLP_USERDATA, 0);
            LRESULT(0)
        }
        _ => DefWindowProcW(hwnd, msg, wparam, lparam),
    }
}