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

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

1. Redistributions of source code must retain the above copyright notice, this
   list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
   this list of conditions and the following disclaimer in the documentation
   and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */

#include "util.h"

#include "app.h"
#include "bindingswidget.h"
#include "bookmarks.h"
#include "color.h"
#include "command.h"
#include "defs.h"
#include "documentwidget.h"
#include "feeds.h"
#include "gmutil.h"
#include "inputwidget.h"
#include "keys.h"
#include "labelwidget.h"
#include "root.h"
#include "text.h"
#include "touch.h"
#include "widget.h"
#include "window.h"

#if defined (iPlatformAppleMobile)
#   include "../ios.h"
#endif

#if defined (iPlatformAppleDesktop)
#   include "macos.h"
#endif

#include <the_Foundation/math.h>
#include <the_Foundation/path.h>
#include <SDL_timer.h>

iBool isCommand_SDLEvent(const SDL_Event *d) {
    return d->type == SDL_USEREVENT && d->user.code == command_UserEventCode;
}

iBool isCommand_UserEvent(const SDL_Event *d, const char *cmd) {
    return d->type == SDL_USEREVENT && d->user.code == command_UserEventCode &&
           equal_Command(d->user.data1, cmd);
}

const char *command_UserEvent(const SDL_Event *d) {
    if (d->type == SDL_USEREVENT && d->user.code == command_UserEventCode) {
        return d->user.data1;
    }
    return "";
}

iInt2 coord_MouseWheelEvent(const SDL_MouseWheelEvent *ev) {
    return mouseCoord_Window(get_Window(), ev->which);
}

static void removePlus_(iString *str) {
    if (endsWith_String(str, "+")) {
        removeEnd_String(str, 1);
        appendCStr_String(str, " ");
    }
}

void toString_Sym(int key, int kmods, iString *str) {
#if defined (iPlatformApple)
    if (kmods & KMOD_CTRL) {
        appendChar_String(str, 0x2303);
    }
    if (kmods & KMOD_ALT) {
        appendChar_String(str, 0x2325);
    }
    if (kmods & KMOD_SHIFT) {
        appendCStr_String(str, shift_Icon);
    }
    if (kmods & KMOD_GUI) {
        appendChar_String(str, 0x2318);
    }
#else
    if (kmods & KMOD_CTRL) {
        appendCStr_String(str, "Ctrl+");
    }
    if (kmods & KMOD_ALT) {
        appendCStr_String(str, "Alt+");
    }
    if (kmods & KMOD_SHIFT) {
        appendCStr_String(str, shift_Icon "+");
    }
    if (kmods & KMOD_GUI) {
        appendCStr_String(str, "Meta+");
    }
#endif
    if (kmods & KMOD_CAPS) {
        appendCStr_String(str, "Caps+");
    }
    if (key == 0x20) {
        appendCStr_String(str, "Space");
    }
    else if (key == SDLK_ESCAPE) {
        appendCStr_String(str, "Esc");
    }
    else if (key == SDLK_LEFT) {
        removePlus_(str);
        appendChar_String(str, 0x2190);
    }
    else if (key == SDLK_RIGHT) {
        removePlus_(str);
        appendChar_String(str, 0x2192);
    }
    else if (key == SDLK_UP) {
        removePlus_(str);
        appendChar_String(str, 0x2191);
    }
    else if (key == SDLK_DOWN) {
        removePlus_(str);
        appendChar_String(str, 0x2193);
    }
    else if (key < 128 && (isalnum(key) || ispunct(key))) {
        if (ispunct(key)) removePlus_(str);
        appendChar_String(str, upper_Char(key));
    }
    else if (key == SDLK_BACKSPACE) {
        removePlus_(str);
        appendChar_String(str, 0x232b); /* Erase to the Left */
    }
    else if (key == SDLK_DELETE) {
        removePlus_(str);
        appendChar_String(str, 0x2326); /* Erase to the Right */
    }
    else if (key == SDLK_RETURN) {
        removePlus_(str);
        appendCStr_String(str, return_Icon); /* Leftwards arrow with a hook */
    }
    else {
        appendCStr_String(str, SDL_GetKeyName(key));
    }
}

iBool isMod_Sym(int key) {
    return key == SDLK_LALT || key == SDLK_RALT || key == SDLK_LCTRL || key == SDLK_RCTRL ||
           key == SDLK_LGUI || key == SDLK_RGUI || key == SDLK_LSHIFT || key == SDLK_RSHIFT ||
           key == SDLK_CAPSLOCK;
}

int normalizedMod_Sym(int key) {
    if (key == SDLK_RSHIFT) key = SDLK_LSHIFT;
    if (key == SDLK_RCTRL) key = SDLK_LCTRL;
    if (key == SDLK_RALT) key = SDLK_LALT;
    if (key == SDLK_RGUI) key = SDLK_LGUI;
    return key;
}

int keyMods_Sym(int kmods) {
    kmods &= (KMOD_SHIFT | KMOD_ALT | KMOD_CTRL | KMOD_GUI | KMOD_CAPS);
    /* Don't treat left/right modifiers differently. */
    if (kmods & KMOD_SHIFT) kmods |= KMOD_SHIFT;
    if (kmods & KMOD_ALT)   kmods |= KMOD_ALT;
    if (kmods & KMOD_CTRL)  kmods |= KMOD_CTRL;
    if (kmods & KMOD_GUI)   kmods |= KMOD_GUI;
    return kmods;
}

int keyMod_ReturnKeyFlag(int flag) {
    flag &= mask_ReturnKeyFlag;
    const int kmods[4] = { 0, KMOD_SHIFT, KMOD_CTRL, KMOD_GUI };
    if (flag < 0 || flag >= iElemCount(kmods)) return 0;
    return kmods[flag];
}

int openTabMode_Sym(int kmods) {
    const int km = keyMods_Sym(kmods);
    return (km == KMOD_SHIFT ? otherRoot_OpenTabFlag : 0) | /* open to the side */
           (((km & KMOD_PRIMARY) && (km & KMOD_SHIFT)) ? new_OpenTabFlag :
            (km & KMOD_PRIMARY) ? newBackground_OpenTabFlag : 0);
}

iRangei intersect_Rangei(iRangei a, iRangei b) {
    if (a.end < b.start || a.start > b.end) {
        return (iRangei){ 0, 0 };
    }
    return (iRangei){ iMax(a.start, b.start), iMin(a.end, b.end) };
}

iRangei union_Rangei(iRangei a, iRangei b) {
    if (isEmpty_Rangei(a)) return b;
    if (isEmpty_Rangei(b)) return a;
    return (iRangei){ iMin(a.start, b.start), iMax(a.end, b.end) };
}

iBool isSelectionBreaking_Char(iChar c) {
    return isSpace_Char(c) || (c == '@' || c == '-' || c == '/' || c == '\\' || c == ',');
}

static const char *moveBackward_(const char *pos, iRangecc bounds, int mode) {
    iChar ch;
    while (pos > bounds.start) {
        int len = decodePrecedingBytes_MultibyteChar(pos, bounds.start, &ch);
        if (len > 0) {
            if (mode & word_RangeExtension && isSelectionBreaking_Char(ch)) break;
            if (mode & line_RangeExtension && ch == '\n') break;
            pos -= len;
        }
        else break;
    }
    return pos;
}

static const char *moveForward_(const char *pos, iRangecc bounds, int mode) {
    iChar ch;
    while (pos < bounds.end) {
        int len = decodeBytes_MultibyteChar(pos, bounds.end, &ch);
        if (len > 0) {
            if (mode & word_RangeExtension && isSelectionBreaking_Char(ch)) break;
            if (mode & line_RangeExtension && ch == '\n') break;
            pos += len;
        }
        else break;
    }
    return pos;
}

void extendRange_Rangecc(iRangecc *d, iRangecc bounds, int mode) {
    if (!d->start) return;
    if (d->end >= d->start) {
        if (mode & moveStart_RangeExtension) {
            d->start = moveBackward_(d->start, bounds, mode);
        }
        if (mode & moveEnd_RangeExtension) {
            d->end = moveForward_(d->end, bounds, mode);
        }
    }
    else {
        if (mode & moveStart_RangeExtension) {
            d->start = moveForward_(d->start, bounds, mode);
        }
        if (mode & moveEnd_RangeExtension) {
            d->end = moveBackward_(d->end, bounds, mode);
        }
    }
}

/*----------------------------------------------------------------------------------------------*/

iBool isFinished_Anim(const iAnim *d) {
    return d->from == d->to || frameTime_Window(get_Window()) >= d->due;
}

void init_Anim(iAnim *d, float value) {
    d->due = d->when = SDL_GetTicks();
    d->from = d->to = value;
    d->bounce = 0.0f;
    d->flags = 0;
}

iLocalDef float pos_Anim_(const iAnim *d, uint32_t now) {
    return (float) (now - d->when) / (float) (d->due - d->when);
}

iLocalDef float easeIn_(float t) {
    return t * t;
}

iLocalDef float easeOut_(float t) {
    return t * (2.0f - t);
}

iLocalDef float easeBoth_(float t) {
    if (t < 0.5f) {
        return easeIn_(t * 2.0f) * 0.5f;
    }
    return 0.5f + easeOut_((t - 0.5f) * 2.0f) * 0.5f;
}

static float valueAt_Anim_(const iAnim *d, const uint32_t now) {
    if (now >= d->due) {
        return d->to;
    }
    if (now <= d->when) {
        return d->from;
    }
    float t = pos_Anim_(d, now);
    const iBool isSoft     = (d->flags & softer_AnimFlag) != 0;
    const iBool isVerySoft = (d->flags & muchSofter_AnimFlag) != 0;
    if ((d->flags & easeBoth_AnimFlag) == easeBoth_AnimFlag) {
        t = easeBoth_(t);
        if (isSoft) t = easeBoth_(t);
        if (isVerySoft) t = easeBoth_(easeBoth_(t));
    }
    else if (d->flags & easeIn_AnimFlag) {
        t = easeIn_(t);
        if (isSoft) t = easeIn_(t);
        if (isVerySoft) t = easeIn_(easeIn_(t));
    }
    else if (d->flags & easeOut_AnimFlag) {
        t = easeOut_(t);
        if (isSoft) t = easeOut_(t);
        if (isVerySoft) t = easeOut_(easeOut_(t));
    }
    float value = d->from * (1.0f - t) + d->to * t;
    if (d->flags & bounce_AnimFlag) {
        t = (1.0f - easeOut_(easeOut_(t))) * easeOut_(t);
        value += d->bounce * t;
    }
    return value;
}

void setValue_Anim(iAnim *d, float to, uint32_t span) {
    if (span == 0) {
        d->from = d->to = to;
        d->when = d->due = frameTime_Window(get_Window()); /* effectively in the past */
    }
    else if (fabsf(to - d->to) > 0.00001f) {
        const uint32_t now = SDL_GetTicks();
        d->from = valueAt_Anim_(d, now);
        d->to   = to;
        d->when = now;
        d->due  = now + span;
    }
    d->bounce = 0;
}

void setValueSpeed_Anim(iAnim *d, float to, float unitsPerSecond) {
    if (iAbs(d->to - to) > 0.0001f || !isFinished_Anim(d)) {
        const uint32_t now   = SDL_GetTicks();
        const float    from  = valueAt_Anim_(d, now);
        const float    delta = to - from;
        const uint32_t span  = (fabsf(delta) / unitsPerSecond) * 1000;
        d->from              = from;
        d->to                = to;
        d->when              = now;
        d->due               = d->when + span;
        d->bounce            = 0;
    }
}

void setValueEased_Anim(iAnim *d, float to, uint32_t span) {
    if (fabsf(to - d->to) <= 0.00001f) {
        d->to = to; /* Pretty much unchanged. */
        return;
    }
    const uint32_t now = SDL_GetTicks();
    if (isFinished_Anim(d)) {
        d->from  = d->to;
        d->flags = easeBoth_AnimFlag;
    }
    else {
        d->from  = valueAt_Anim_(d, now);
        d->flags = easeOut_AnimFlag;
    }
    d->to     = to;
    d->when   = now;
    d->due    = now + span;
    d->bounce = 0;
}

void setFlags_Anim(iAnim *d, int flags, iBool set) {
    iChangeFlags(d->flags, flags, set);
}

void stop_Anim(iAnim *d) {
    d->from = d->to = value_Anim(d);
    d->when = d->due = SDL_GetTicks();
}

float pos_Anim(const iAnim *d) {
    return pos_Anim_(d, frameTime_Window(get_Window()));
}

float value_Anim(const iAnim *d) {
    return valueAt_Anim_(d, frameTime_Window(get_Window()));
}

/*-----------------------------------------------------------------------------------------------*/

void init_Click(iClick *d, iAnyObject *widget, int button) {
    d->isActive = iFalse;
    d->button   = button;
    d->bounds   = as_Widget(widget);
    d->minHeight = 0;
    d->startPos = zero_I2();
    d->pos      = zero_I2();
}

iBool contains_Click(const iClick *d, iInt2 coord) {
    if (d->minHeight) {
        iRect rect = bounds_Widget(d->bounds);
        rect.size.y = iMax(d->minHeight, rect.size.y);
        return contains_Rect(rect, coord);
    }
    return contains_Widget(d->bounds, coord);
}

enum iClickResult processEvent_Click(iClick *d, const SDL_Event *event) {
    if (event->type == SDL_MOUSEMOTION) {
        const iInt2 pos = init_I2(event->motion.x, event->motion.y);
        if (d->isActive) {
            d->pos = pos;
            return drag_ClickResult;
        }
    }
    if (event->type != SDL_MOUSEBUTTONDOWN && event->type != SDL_MOUSEBUTTONUP) {
        return none_ClickResult;
    }
    const SDL_MouseButtonEvent *mb = &event->button;
    if (mb->button != d->button) {
        return none_ClickResult;
    }
    const iInt2 pos = init_I2(mb->x, mb->y);
    if (event->type == SDL_MOUSEBUTTONDOWN) {
        d->count = mb->clicks;
    }
    if (!d->isActive) {
        if (mb->state == SDL_PRESSED) {
            if (contains_Click(d, pos)) {
                d->isActive = iTrue;
                d->startPos = d->pos = pos;
                setMouseGrab_Widget(d->bounds);
                return started_ClickResult;
            }
        }
    }
    else { /* Active. */
        if (mb->state == SDL_RELEASED) {
            enum iClickResult result = contains_Click(d, pos)
                                           ? finished_ClickResult
                                           : aborted_ClickResult;
            d->isActive = iFalse;
            d->pos = pos;
            setMouseGrab_Widget(NULL);
            return result;
        }
    }
    return none_ClickResult;
}

void cancel_Click(iClick *d) {
    if (d->isActive) {
        d->isActive = iFalse;
        setMouseGrab_Widget(NULL);
    }
}

iBool isMoved_Click(const iClick *d) {
    return dist_I2(d->startPos, d->pos) > 2;
}

iInt2 pos_Click(const iClick *d) {
    return d->pos;
}

iRect rect_Click(const iClick *d) {
    return initCorners_Rect(min_I2(d->startPos, d->pos), max_I2(d->startPos, d->pos));
}

iInt2 delta_Click(const iClick *d) {
    return sub_I2(d->pos, d->startPos);
}

/*----------------------------------------------------------------------------------------------*/

void init_SmoothScroll(iSmoothScroll *d, iWidget *owner, iSmoothScrollNotifyFunc notify) {
    reset_SmoothScroll(d);
    d->widget = owner;
    d->notify = notify;
}

void reset_SmoothScroll(iSmoothScroll *d) {
    init_Anim(&d->pos, 0);
    d->max = 0;
    d->overscroll = (deviceType_App() != desktop_AppDeviceType ? 100 * gap_UI : 0);
}

void setMax_SmoothScroll(iSmoothScroll *d, int max) {
    max = iMax(0, max);
    if (max != d->max) {
        d->max = max;
        if (targetValue_Anim(&d->pos) > d->max) {
            d->pos.to = d->max;
        }
    }
}

static int overscroll_SmoothScroll_(const iSmoothScroll *d) {
    if (d->overscroll) {
        const int y = value_Anim(&d->pos);
        if (y <= 0) {
            return y;
        }
        if (y >= d->max) {
            return y - d->max;
        }
    }
    return 0;
}

float pos_SmoothScroll(const iSmoothScroll *d) {
    return value_Anim(&d->pos) - overscroll_SmoothScroll_(d) * 0.667f;
}

iBool isFinished_SmoothScroll(const iSmoothScroll *d) {
    return isFinished_Anim(&d->pos);
}

void moveSpan_SmoothScroll(iSmoothScroll *d, int offset, uint32_t span) {
#if !defined (iPlatformMobile)
    if (!prefs_App()->smoothScrolling) {
        span = 0; /* always instant */
    }
#endif
    int destY = targetValue_Anim(&d->pos) + offset;
    if (destY < -d->overscroll) {
        destY = -d->overscroll;
    }
    if (d->max > 0) {
        if (destY >= d->max + d->overscroll) {
            destY = d->max + d->overscroll;
        }
    }
    else {
        destY = 0;
    }
    if (span) {
        setValueEased_Anim(&d->pos, destY, span);
    }
    else {
        setValue_Anim(&d->pos, destY, 0);
    }
    if (d->overscroll && widgetMode_Touch(d->widget) == momentum_WidgetTouchMode) {
        const int osDelta = overscroll_SmoothScroll_(d);
        if (osDelta) {
            const float remaining = stopWidgetMomentum_Touch(d->widget);
            span = iMini(1000, 50 * sqrt(remaining / gap_UI));
            setValue_Anim(&d->pos, osDelta < 0 ? 0 : d->max, span);
            d->pos.flags = bounce_AnimFlag | easeOut_AnimFlag | softer_AnimFlag;
            //            printf("remaining: %f  dur: %d\n", remaining, duration);
            d->pos.bounce = (osDelta < 0 ? -1 : 1) *
                            iMini(5 * d->overscroll, remaining * remaining * 0.00005f);
        }
    }
    if (d->notify) {
        d->notify(d->widget, offset, span);
    }
}

void move_SmoothScroll(iSmoothScroll *d, int offset) {
    moveSpan_SmoothScroll(d, offset, 0 /* instantly */);
}

iBool processEvent_SmoothScroll(iSmoothScroll *d, const SDL_Event *ev) {
    if (ev->type == SDL_USEREVENT && ev->user.code == widgetTouchEnds_UserEventCode) {
        const int osDelta = overscroll_SmoothScroll_(d);
        if (osDelta) {
            moveSpan_SmoothScroll(d, -osDelta, 100 * sqrt(iAbs(osDelta) / gap_UI));
            d->pos.flags = easeOut_AnimFlag | muchSofter_AnimFlag;
        }
        return iTrue;
    }
    return iFalse;
}

/*-----------------------------------------------------------------------------------------------*/

iWidget *makePadding_Widget(int size) {
    iWidget *pad = new_Widget();
    setId_Widget(pad, "padding");
    setFixedSize_Widget(pad, init1_I2(size));
    return pad;
}

iLabelWidget *makeHeading_Widget(const char *text) {
    iLabelWidget *heading = new_LabelWidget(text, NULL);
    setFlags_Widget(as_Widget(heading), frameless_WidgetFlag | alignLeft_WidgetFlag, iTrue);
    setBackgroundColor_Widget(as_Widget(heading), none_ColorId);
    return heading;
}

iWidget *makeVDiv_Widget(void) {
    iWidget *div = new_Widget();
    setFlags_Widget(div, resizeChildren_WidgetFlag | arrangeVertical_WidgetFlag | unhittable_WidgetFlag, iTrue);
    return div;
}

iWidget *makeHDiv_Widget(void) {
    iWidget *div = new_Widget();
    setFlags_Widget(div, resizeChildren_WidgetFlag | arrangeHorizontal_WidgetFlag | unhittable_WidgetFlag, iTrue);
    return div;
}

iWidget *addAction_Widget(iWidget *parent, int key, int kmods, const char *command) {
    iLabelWidget *action = newKeyMods_LabelWidget("", key, kmods, command);
    setFixedSize_Widget(as_Widget(action), zero_I2());
    addChildFlags_Widget(parent, iClob(action), hidden_WidgetFlag);
    return as_Widget(action);
}

iBool isAction_Widget(const iWidget *d) {
    return isInstance_Object(d, &Class_LabelWidget) && isEqual_I2(d->rect.size, zero_I2());
}

/*-----------------------------------------------------------------------------------------------*/

static iBool isCommandIgnoredByMenus_(const char *cmd) {
    if (equal_Command(cmd, "window.focus.lost") ||
        equal_Command(cmd, "window.focus.gained")) return iTrue;
    /* TODO: Perhaps a common way of indicating which commands are notifications and should not
       be reacted to by menus? */
    return equal_Command(cmd, "media.updated") ||
           equal_Command(cmd, "media.player.update") ||
           startsWith_CStr(cmd, "feeds.update.") ||
           equal_Command(cmd, "bookmarks.request.started") ||
           equal_Command(cmd, "bookmarks.request.finished") ||
           equal_Command(cmd, "bookmarks.changed") ||
           equal_Command(cmd, "document.autoreload") ||
           equal_Command(cmd, "document.reload") ||
           equal_Command(cmd, "document.request.started") ||
           equal_Command(cmd, "document.request.updated") ||
           equal_Command(cmd, "document.request.finished") ||
           equal_Command(cmd, "document.changed") ||
           equal_Command(cmd, "scrollbar.fade") ||
           equal_Command(cmd, "visited.changed") ||
           (deviceType_App() == desktop_AppDeviceType && equal_Command(cmd, "window.resized")) ||
           equal_Command(cmd, "widget.overflow") ||
           equal_Command(cmd, "window.reload.update") ||
           equal_Command(cmd, "window.mouse.exited") ||
           equal_Command(cmd, "window.mouse.entered") ||
           (equal_Command(cmd, "mouse.clicked") && !arg_Command(cmd)); /* button released */
}

static iLabelWidget *parentMenuButton_(const iWidget *menu) {
    if (isInstance_Object(menu->parent, &Class_LabelWidget)) {
        iLabelWidget *button = (iLabelWidget *) menu->parent;
        if (!cmp_String(command_LabelWidget(button), "menu.open")) {
            return button;
        }
    }
    return NULL;
}

static iBool menuHandler_(iWidget *menu, const char *cmd) {
    if (isVisible_Widget(menu)) {
        if (equalWidget_Command(cmd, menu, "menu.opened")) {
            return iFalse;
        }
        if (equal_Command(cmd, "menu.open") && pointer_Command(cmd) == menu->parent) {
            /* Don't reopen self; instead, root will close the menu. */
            return iFalse;
        }
        if ((equal_Command(cmd, "mouse.clicked") || equal_Command(cmd, "mouse.missed")) &&
            arg_Command(cmd)) {
            if (hitChild_Window(get_Window(), coord_Command(cmd)) == parentMenuButton_(menu)) {
                return iFalse;
            }
            /* Dismiss open menus when clicking outside them. */
            closeMenu_Widget(menu);
            return iTrue;
        }
        if (!isCommandIgnoredByMenus_(cmd)) {
            closeMenu_Widget(menu);
        }
    }
    return iFalse;
}

static iWidget *makeMenuSeparator_(void) {
    iWidget *sep = new_Widget();
    setBackgroundColor_Widget(sep, uiSeparator_ColorId);
    sep->rect.size.y = gap_UI / 3;
    if (deviceType_App() != desktop_AppDeviceType) {
        sep->rect.size.y = gap_UI / 2;
    }
    setFlags_Widget(sep, hover_WidgetFlag | fixedHeight_WidgetFlag, iTrue);
    return sep;
}

void makeMenuItems_Widget(iWidget *menu, const iMenuItem *items, size_t n) {
    const iBool isPortraitPhone = (deviceType_App() == phone_AppDeviceType && isPortrait_App());
    int64_t     itemFlags       = (deviceType_App() != desktop_AppDeviceType ? 0 : 0) |
                                  (isPortraitPhone ? extraPadding_WidgetFlag : 0);
    iBool    haveIcons  = iFalse;
    iWidget *horizGroup = NULL;
    for (size_t i = 0; i < n; ++i) {
        const iMenuItem *item = &items[i];
        if (!item->label) {
            break;
        }
        const char *labelText = item->label;
        if (!startsWith_CStr(labelText, ">>>")) {
            horizGroup = NULL;
        }
        if (equal_CStr(labelText, "---")) {
            addChild_Widget(menu, iClob(makeMenuSeparator_()));
        }
        else {
            iBool isInfo = iFalse;
            iBool isDisabled = iFalse;
            if (startsWith_CStr(labelText, ">>>")) {
                labelText += 3;
                if (!horizGroup) {
                    horizGroup = makeHDiv_Widget();
                    setFlags_Widget(horizGroup, resizeHeightOfChildren_WidgetFlag, iFalse);
                    setFlags_Widget(horizGroup, arrangeHeight_WidgetFlag, iTrue);
                    addChild_Widget(menu, iClob(horizGroup));
                }
            }
            if (startsWith_CStr(labelText, "```")) {
                labelText += 3;
                isInfo = iTrue;
            }
            if (startsWith_CStr(labelText, "///")) {
                labelText += 3;
                isDisabled = iTrue;
            }
            iLabelWidget *label = addChildFlags_Widget(
                horizGroup ? horizGroup : menu,
                iClob(newKeyMods_LabelWidget(labelText, item->key, item->kmods, item->command)),
                noBackground_WidgetFlag | frameless_WidgetFlag | alignLeft_WidgetFlag |
                drawKey_WidgetFlag | itemFlags);
            setWrap_LabelWidget(label, isInfo);
            haveIcons |= checkIcon_LabelWidget(label);
            updateSize_LabelWidget(label); /* drawKey was set */
            setFlags_Widget(as_Widget(label), disabled_WidgetFlag, isDisabled);
            if (isInfo) {
                setFlags_Widget(as_Widget(label), fixedHeight_WidgetFlag, iTrue); /* wrap changes height */
                setTextColor_LabelWidget(label, uiTextAction_ColorId);
            }
        }
    }
    if (deviceType_App() == phone_AppDeviceType) {
        addChild_Widget(menu, iClob(makeMenuSeparator_()));
        addChildFlags_Widget(menu,
                             iClob(new_LabelWidget("${cancel}", "cancel")),
                             itemFlags | noBackground_WidgetFlag | frameless_WidgetFlag |
                             alignLeft_WidgetFlag);
    }
    if (haveIcons) {
        /* All items must have icons if at least one of them has. */
        iForEach(ObjectList, i, children_Widget(menu)) {
            if (isInstance_Object(i.object, &Class_LabelWidget)) {
                iLabelWidget *label = i.object;
                if (!isWrapped_LabelWidget(label) && icon_LabelWidget(label) == 0) {
                    setIcon_LabelWidget(label, ' ');
                }
            }
        }
    }
}

static iArray *deepCopyMenuItems_(iWidget *menu, const iMenuItem *items, size_t n) {
    iArray *array = new_Array(sizeof(iMenuItem));
    iString cmd;
    init_String(&cmd);
    for (size_t i = 0; i < n; i++) {
        const iMenuItem *item = &items[i];
        const char *itemCommand = item->command;
#if 0
        if (itemCommand) {
            /* Make it appear the command is coming from the right widget. */
            setCStr_String(&cmd, itemCommand);
            if (!hasLabel_Command(itemCommand, "ptr")) {
                size_t firstSpace = indexOf_String(&cmd, ' ');
                iBlock ptr;
                init_Block(&ptr, 0);
                printf_Block(&ptr, " ptr:%p", menu);
                if (firstSpace != iInvalidPos) {
                    insertData_Block(&cmd.chars, firstSpace, data_Block(&ptr), size_Block(&ptr));
                }
                else {
                    append_Block(&cmd.chars, &ptr);
                }
                deinit_Block(&ptr);
            }
            itemCommand = cstr_String(&cmd);
        }
#endif
        pushBack_Array(array, &(iMenuItem){
            item->label ? iDupStr(item->label) : NULL,
            item->key,
            item->kmods,
            itemCommand ? iDupStr(itemCommand) : NULL /* NOTE: Only works with string commands. */
        });
    }
    deinit_String(&cmd);
    return array;
}

static void deleteMenuItems_(iArray *items) {
    iForEach(Array, i, items) {
        iMenuItem *item = i.value;
        free((void *) item->label);
        free((void *) item->command);
    }
    delete_Array(items);
}

iWidget *makeMenu_Widget(iWidget *parent, const iMenuItem *items, size_t n) {
    iWidget *menu = new_Widget();
#if defined (iHaveNativeContextMenus)
    setFlags_Widget(menu, hidden_WidgetFlag | nativeMenu_WidgetFlag, iTrue);
    setUserData_Object(menu, deepCopyMenuItems_(menu, items, n));
    addChild_Widget(parent, menu);
    iRelease(menu); /* owned by parent now */
    /* Keyboard shortcuts still need to triggerable via the menu, although the items don't exist. */ {
        for (size_t i = 0; i < n; i++) {
            const iMenuItem *item = &items[i];
            if (item->key) {
                addAction_Widget(menu, item->key, item->kmods, item->command);
            }
        }
    }
#else
    /* Non-native custom popup menu. This may still be displayed inside a separate window. */
    setDrawBufferEnabled_Widget(menu, iTrue);
    setBackgroundColor_Widget(menu, uiBackgroundMenu_ColorId);
    if (deviceType_App() != desktop_AppDeviceType) {
        setPadding1_Widget(menu, 2 * gap_UI);
    }
    else {
        setPadding1_Widget(menu, gap_UI / 2);
    }
    setFlags_Widget(menu,
                    keepOnTop_WidgetFlag | collapse_WidgetFlag | hidden_WidgetFlag |
                        arrangeVertical_WidgetFlag | arrangeSize_WidgetFlag |
                        resizeChildrenToWidestChild_WidgetFlag | overflowScrollable_WidgetFlag |
                        (isPortraitPhone_App() ? drawBackgroundToVerticalSafeArea_WidgetFlag : 0),
                    iTrue);
    if (!isPortraitPhone_App()) {
        setFrameColor_Widget(menu, uiSeparator_ColorId);
    }
    makeMenuItems_Widget(menu, items, n);
    addChild_Widget(parent, menu);
    iRelease(menu); /* owned by parent now */
    setCommandHandler_Widget(menu, menuHandler_);
    iWidget *cancel = addAction_Widget(menu, SDLK_ESCAPE, 0, "cancel");
    setId_Widget(cancel, "menu.cancel");
    setFlags_Widget(cancel, disabled_WidgetFlag, iTrue);
#endif
    return menu;
}

void openMenu_Widget(iWidget *d, iInt2 windowCoord) {
    openMenuFlags_Widget(d, windowCoord, postCommands_MenuOpenFlags);
}

static void updateMenuItemFonts_Widget_(iWidget *d) {
    const iBool isPortraitPhone = (deviceType_App() == phone_AppDeviceType && isPortrait_App());
    const iBool isSlidePanel    = (flags_Widget(d) & horizontalOffset_WidgetFlag) != 0;
    iForEach(ObjectList, i, children_Widget(d)) {
        if (isInstance_Object(i.object, &Class_LabelWidget)) {
            iLabelWidget *label = i.object;
            const iBool isCaution = startsWith_String(text_LabelWidget(label), uiTextCaution_ColorEscape);
            if (isWrapped_LabelWidget(label)) {
                continue;
            }
            if (deviceType_App() == desktop_AppDeviceType) {
                setFont_LabelWidget(label, isCaution ? uiLabelBold_FontId : uiLabel_FontId);
            }
            else if (isPortraitPhone) {
                if (!isSlidePanel) {
                    setFont_LabelWidget(label, isCaution ? defaultBigBold_FontId : defaultBig_FontId);
                }
            }
            else {
                setFont_LabelWidget(label, isCaution ? uiContentBold_FontId : uiContent_FontId);
            }
        }
        else if (childCount_Widget(i.object)) {
            updateMenuItemFonts_Widget_(i.object);
        }
    }
}

iMenuItem *findNativeMenuItem_Widget(iWidget *menu, const char *commandSuffix) {
    iAssert(flags_Widget(menu) & nativeMenu_WidgetFlag);
    iForEach(Array, i, userData_Object(menu)) {
        iMenuItem *item = i.value;
        if (item->command && endsWith_Rangecc(range_CStr(item->command), commandSuffix)) {
            return item;
        }
    }
    return NULL;
}

void setPrefix_NativeMenuItem(iMenuItem *item, const char *prefix, iBool set) {
    if (!item->label) {
        return;
    }
    const iBool hasPrefix = startsWith_CStr(item->label, prefix);
    if (hasPrefix && !set) {
        char *label = iDupStr(item->label + 3);
        free((char *) item->label);
        item->label = label;
    }
    else if (!hasPrefix && set) {
        char *label = malloc(strlen(item->label) + 4);
        memcpy(label, prefix, 3);
        strcpy(label + 3, item->label);
        free((char *) item->label);
        item->label = label;
    }
}

void setSelected_NativeMenuItem(iMenuItem *item, iBool isSelected) {
    if (item) {
        setPrefix_NativeMenuItem(item, "///", iFalse);
        setPrefix_NativeMenuItem(item, "###", isSelected);
    }
}

void setDisabled_NativeMenuItem(iMenuItem *item, iBool isDisabled) {
    if (item) {
        setPrefix_NativeMenuItem(item, "###", iFalse);
        setPrefix_NativeMenuItem(item, "///", isDisabled);
    }
}

void setLabel_NativeMenuItem(iMenuItem *item, const char *label) {
    free((char *) item->label);
    item->label = iDupStr(label);
}

void setMenuItemLabel_Widget(iWidget *menu, const char *command, const char *newLabel) {
    if (flags_Widget(menu) & nativeMenu_WidgetFlag) {
        iArray *items = userData_Object(menu);
        iAssert(items);
        iForEach(Array, i, items) {
            iMenuItem *item = i.value;
            if (item->command && !iCmpStr(item->command, command)) {
                setLabel_NativeMenuItem(item, newLabel);
                break;
            }
        }
    }
    else {
        iLabelWidget *menuItem = findMenuItem_Widget(menu, command);
        if (menuItem) {
            setTextCStr_LabelWidget(menuItem, newLabel);
            checkIcon_LabelWidget(menuItem);
        }
    }
}

void setMenuItemLabelByIndex_Widget(iWidget *menu, size_t index, const char *newLabel) {
    if (!menu) {
        return;
    }
    if (flags_Widget(menu) & nativeMenu_WidgetFlag) {
        iArray *items = userData_Object(menu);
        iAssert(items);
        iAssert(index < size_Array(items));
        setLabel_NativeMenuItem(at_Array(items, index), newLabel);
    }
    else {
        iLabelWidget *menuItem = child_Widget(menu, index);
        iAssert(isInstance_Object(menuItem, &Class_LabelWidget));
        setTextCStr_LabelWidget(menuItem, newLabel);
        checkIcon_LabelWidget(menuItem);
    }
}

void unselectAllNativeMenuItems_Widget(iWidget *menu) {
    iArray *items = userData_Object(menu);
    iAssert(items);
    iForEach(Array, i, items) {
        setSelected_NativeMenuItem(i.value, iFalse);
    }
}

iLocalDef iBool isUsingMenuPopupWindows_(void) {
#if defined (LAGRANGE_ENABLE_POPUP_MENUS)
    return deviceType_App() == desktop_AppDeviceType;
#else
    return iFalse;
#endif
}

void releaseNativeMenu_Widget(iWidget *d) {
#if defined (iHaveNativeContextMenus)
    iArray *items = userData_Object(d);
    iAssert(flags_Widget(d) & nativeMenu_WidgetFlag);
    iAssert(items);
    deleteMenuItems_(items);
    setUserData_Object(d, NULL);
#else
    iUnused(d);
#endif
}

void openMenuFlags_Widget(iWidget *d, iInt2 windowCoord, int menuOpenFlags) {
    const iBool postCommands = (menuOpenFlags & postCommands_MenuOpenFlags) != 0;
#if defined (iHaveNativeContextMenus)
    const iArray *items = userData_Object(d);
    iAssert(flags_Widget(d) & nativeMenu_WidgetFlag);
    iAssert(items);
    showPopupMenu_MacOS(d, windowCoord, constData_Array(items), size_Array(items));
#else
    const iRect rootRect        = rect_Root(d->root);
    const iInt2 rootSize        = rootRect.size;
    const iBool isPortraitPhone = (deviceType_App() == phone_AppDeviceType && isPortrait_App());
    const iBool isSlidePanel    = (flags_Widget(d) & horizontalOffset_WidgetFlag) != 0;
    if (postCommands) {
        postCommand_App("cancel"); /* dismiss any other menus */
    }
    /* Menu closes when commands are emitted, so handle any pending ones beforehand. */
    processEvents_App(postedEventsOnly_AppEventMode);
    setFlags_Widget(d, hidden_WidgetFlag, iFalse);
    setFlags_Widget(d, commandOnMouseMiss_WidgetFlag, iTrue);
    setFlags_Widget(findChild_Widget(d, "menu.cancel"), disabled_WidgetFlag, iFalse);
    if (isUsingMenuPopupWindows_()) {
        if (postCommands) {
            postCommand_Widget(d, "menu.opened");
        }
        updateMenuItemFonts_Widget_(d);
        iRoot *oldRoot = current_Root();
        setFlags_Widget(d, keepOnTop_WidgetFlag, iFalse);
        setUserData_Object(d, parent_Widget(d));
        iAssert(userData_Object(d));
        removeChild_Widget(parent_Widget(d), d); /* we'll borrow the widget for a while */
        SDL_Window *sdlWin = get_Window()->win;
        iInt2 winPos;
        SDL_GetWindowPosition(sdlWin, &winPos.x, &winPos.y);
//        const iRect winRect =
        const float pixelRatio = get_Window()->pixelRatio;
        iInt2 menuPos = add_I2(winPos,
                               divf_I2(sub_I2(windowCoord, divi_I2(gap2_UI, 2)), pixelRatio));
        arrange_Widget(d);
        /* Check display bounds. */ {
            const iInt2 menuSize = divf_I2(d->rect.size, pixelRatio);
            if (menuOpenFlags & center_MenuOpenFlags) {
                iInt2 winSize;
                SDL_GetWindowSize(sdlWin, &winSize.x, &winSize.y);
                menuPos = sub_I2(add_I2(winPos, divi_I2(winSize, 2)), divi_I2(menuSize, 2));
            }
            SDL_Rect displayRect;
            SDL_GetDisplayBounds(SDL_GetWindowDisplayIndex(get_Window()->win), &displayRect);
            menuPos.x = iMin(menuPos.x, displayRect.x + displayRect.w - menuSize.x);
            menuPos.y = iMin(menuPos.y, displayRect.y + displayRect.h - menuSize.y);
        }
        iWindow *win = newPopup_Window(menuPos, d); /* window takes the widget */
        SDL_SetWindowTitle(win->win, "Menu");
        addPopup_App(win);
        SDL_ShowWindow(win->win);
        draw_Window(win);
        setCurrent_Window(mainWindow_App());
        setCurrent_Root(oldRoot);
        return;
    }
    raise_Widget(d);
    if (isPortraitPhone) {
        setFlags_Widget(d, arrangeWidth_WidgetFlag | resizeChildrenToWidestChild_WidgetFlag, iFalse);
        setFlags_Widget(d, resizeWidthOfChildren_WidgetFlag | drawBackgroundToBottom_WidgetFlag, iTrue);
        if (!isSlidePanel) {
            setFlags_Widget(d, borderTop_WidgetFlag, iTrue);
        }
        d->rect.size.x = rootSize.x;
    }
    updateMenuItemFonts_Widget_(d);
    arrange_Widget(d);
    if (isPortraitPhone) {
        if (isSlidePanel) {
            d->rect.pos = zero_I2();
        }
        else {
            d->rect.pos = init_I2(0, rootSize.y);
        }
    }
    else {
        d->rect.pos = windowToLocal_Widget(d, windowCoord);
    }
    /* Ensure the full menu is visible. */
    const iRect bounds       = bounds_Widget(d);
    int         leftExcess   = left_Rect(rootRect) - left_Rect(bounds);
    int         rightExcess  = right_Rect(bounds) - right_Rect(rootRect);
    int         topExcess    = top_Rect(rootRect) - top_Rect(bounds);
    int         bottomExcess = bottom_Rect(bounds) - bottom_Rect(rootRect);
#if defined (iPlatformAppleMobile)
    /* Reserve space for the system status bar. */ {
        float l, t, r, b;
        safeAreaInsets_iOS(&l, &t, &r, &b);
        topExcess    += t;
        bottomExcess += iMax(b, get_MainWindow()->keyboardHeight);
        leftExcess   += l;
        rightExcess  += r;
    }
#endif
    if (bottomExcess > 0 && (!isPortraitPhone || !isSlidePanel)) {
        d->rect.pos.y -= bottomExcess;
    }
    if (topExcess > 0) {
        d->rect.pos.y += topExcess;
    }
    if (rightExcess > 0) {
        d->rect.pos.x -= rightExcess;
    }
    if (leftExcess > 0) {
        d->rect.pos.x += leftExcess;
    }
    postRefresh_App();
    if (postCommands) {
        postCommand_Widget(d, "menu.opened");
    }
    setupMenuTransition_Mobile(d, iTrue);
#endif    
}

void closeMenu_Widget(iWidget *d) {
    if (flags_Widget(d) & nativeMenu_WidgetFlag) {
        return; /* Handled natively. */
    }
    if (d == NULL || flags_Widget(d) & hidden_WidgetFlag) {
        return; /* Already closed. */
    }
    if (isUsingMenuPopupWindows_()) {
        iWindow *win = window_Widget(d);
        iAssert(type_Window(win) == popup_WindowType);
        iWidget *originalParent = userData_Object(d);
        setUserData_Object(d, NULL);
        win->roots[0]->widget = NULL;
        setRoot_Widget(d, originalParent->root);
        addChild_Widget(originalParent, d);
        setFlags_Widget(d, keepOnTop_WidgetFlag, iTrue);
        SDL_HideWindow(win->win);
        collect_Garbage(win, (iDeleteFunc) delete_Window); /* get rid of it after event processing */
    }
    setFlags_Widget(d, hidden_WidgetFlag, iTrue);
    setFlags_Widget(findChild_Widget(d, "menu.cancel"), disabled_WidgetFlag, iTrue);
    postRefresh_App();
    postCommand_Widget(d, "menu.closed");
    setupMenuTransition_Mobile(d, iFalse);
}

iLabelWidget *findMenuItem_Widget(iWidget *menu, const char *command) {
    iForEach(ObjectList, i, children_Widget(menu)) {
        if (isInstance_Object(i.object, &Class_LabelWidget)) {
            iLabelWidget *menuItem = i.object;
            if (!cmp_String(command_LabelWidget(menuItem), command)) {
                return menuItem;
            }
        }
    }
    return NULL;
}

void setMenuItemDisabled_Widget(iWidget *menu, const char *command, iBool disable) {
    if (flags_Widget(menu) & nativeMenu_WidgetFlag) {
        setDisabled_NativeMenuItem(findNativeMenuItem_Widget(menu, command), disable);
    }
    else {
        iLabelWidget *item = findMenuItem_Widget(menu, command);
        if (item) {
            setFlags_Widget(as_Widget(item), disabled_WidgetFlag, disable);
        }
    }
}

void setMenuItemDisabledByIndex_Widget(iWidget *menu, size_t index, iBool disable) {
    if (!menu) {
        return;
    }
    if (flags_Widget(menu) & nativeMenu_WidgetFlag) {
        setDisabled_NativeMenuItem(at_Array(userData_Object(menu), index), disable);
    }
    else {
        setFlags_Widget(child_Widget(menu, index), disabled_WidgetFlag, disable);
    }    
}

int checkContextMenu_Widget(iWidget *menu, const SDL_Event *ev) {
    if (menu && ev->type == SDL_MOUSEBUTTONDOWN && ev->button.button == SDL_BUTTON_RIGHT) {
        if (isVisible_Widget(menu)) {
            closeMenu_Widget(menu);
            return 0x1;
        }
        const iInt2 mousePos = init_I2(ev->button.x, ev->button.y);
        if (contains_Widget(menu->parent, mousePos)) {
            openMenu_Widget(menu, mousePos);
            return 0x2;
        }
    }
    return 0;
}

iLabelWidget *makeMenuButton_LabelWidget(const char *label, const iMenuItem *items, size_t n) {
    iLabelWidget *button = new_LabelWidget(label, "menu.open");
    iWidget *menu = makeMenu_Widget(as_Widget(button), items, n);
    setId_Widget(menu, "menu");
    return button;
}

const iString *removeMenuItemLabelPrefixes_String(const iString *d) {
    iString *str = copy_String(d);
    for (;;) {
        if (startsWith_String(str, "###")) {
            remove_Block(&str->chars, 0, 3);
            continue;
        }
        if (startsWith_String(str, "///")) {
            remove_Block(&str->chars, 0, 3);
            continue;
        }
        if (startsWith_String(str, "```")) {
            remove_Block(&str->chars, 0, 3);
            continue;
        }
        break;
    }
    return collect_String(str);
}

void updateDropdownSelection_LabelWidget(iLabelWidget *dropButton, const char *selectedCommand) {
    iWidget *menu = findChild_Widget(as_Widget(dropButton), "menu");
    if (flags_Widget(menu) & nativeMenu_WidgetFlag) {
        unselectAllNativeMenuItems_Widget(menu);
        iMenuItem *item = findNativeMenuItem_Widget(menu, selectedCommand);
        if (item) {
            setSelected_NativeMenuItem(item, iTrue);
            updateText_LabelWidget(dropButton,
                                   removeMenuItemLabelPrefixes_String(collectNewCStr_String(item->label)));
        }
        return;
    }
    iForEach(ObjectList, i, children_Widget(menu)) {
        if (isInstance_Object(i.object, &Class_LabelWidget)) {
            iLabelWidget *item = i.object;
            const iBool isSelected = endsWith_String(command_LabelWidget(item), selectedCommand);
            setFlags_Widget(as_Widget(item), selected_WidgetFlag, isSelected);
            if (isSelected) {
                updateText_LabelWidget(dropButton, sourceText_LabelWidget(item));
            }
        }
    }
}

/*-----------------------------------------------------------------------------------------------*/

static iBool isTabPage_Widget_(const iWidget *tabs, const iWidget *page) {
    return page && page->parent == findChild_Widget(tabs, "tabs.pages");
}

static void unfocusFocusInsideTabPage_(const iWidget *page) {
    iWidget *focus = focus_Widget();
    if (page && focus && hasParent_Widget(focus, page)) {
//        printf("unfocus inside page: %p\n", focus);
        setFocus_Widget(NULL);
    }
}

static iBool tabSwitcher_(iWidget *tabs, const char *cmd) {
    if (equal_Command(cmd, "tabs.switch")) {
        iWidget *target = pointerLabel_Command(cmd, "page");
        if (!target) {
            target = findChild_Widget(tabs, cstr_Rangecc(range_Command(cmd, "id")));
        }
        if (!target) return iFalse;
        unfocusFocusInsideTabPage_(currentTabPage_Widget(tabs));
        if (flags_Widget(target) & focusable_WidgetFlag) {
            setFocus_Widget(target);
        }
        if (isTabPage_Widget_(tabs, target)) {
            showTabPage_Widget(tabs, target);
            return iTrue;
        }
        else if (hasParent_Widget(target, tabs)) {
            /* Some widget on a page. */
            while (target && !isTabPage_Widget_(tabs, target)) {
                target = target->parent;
            }
            showTabPage_Widget(tabs, target);
            return iTrue;
        }
    }
    else if (equal_Command(cmd, "tabs.next") || equal_Command(cmd, "tabs.prev")) {
        unfocusFocusInsideTabPage_(currentTabPage_Widget(tabs));
        iWidget *pages = findChild_Widget(tabs, "tabs.pages");
        int tabIndex = 0;
        iConstForEach(ObjectList, i, pages->children) {
            const iWidget *child = constAs_Widget(i.object);
            if (isVisible_Widget(child)) break;
            tabIndex++;
        }
        const int dir = (equal_Command(cmd, "tabs.next") ? +1 : -1);
        /* If out of tabs, rotate to the next set of tabs if one is available. */
        if ((tabIndex == 0 && dir < 0) || (tabIndex == childCount_Widget(pages) - 1 && dir > 0)) {
            iWidget *nextTabs = findChild_Widget(otherRoot_Window(get_Window(), tabs->root)->widget,
                                                 "doctabs");
            iWidget *nextPages = findChild_Widget(nextTabs, "tabs.pages");
            tabIndex = (dir < 0 ? childCount_Widget(nextPages) - 1 : 0);
            showTabPage_Widget(nextTabs, child_Widget(nextPages, tabIndex));
            postCommand_App("keyroot.next");
        }
        else {
            showTabPage_Widget(tabs, child_Widget(pages, tabIndex + dir));
        }
        refresh_Widget(tabs);
        return iTrue;
    }
    return iFalse;
}

iWidget *makeTabs_Widget(iWidget *parent) {
    iWidget *tabs = makeVDiv_Widget();
    iWidget *buttons = addChild_Widget(tabs, iClob(new_Widget()));
    setFlags_Widget(buttons,
                    resizeWidthOfChildren_WidgetFlag | arrangeHorizontal_WidgetFlag |
                        arrangeHeight_WidgetFlag,
                    iTrue);
    setId_Widget(buttons, "tabs.buttons");
    iWidget *content = addChildFlags_Widget(tabs, iClob(makeHDiv_Widget()), expand_WidgetFlag);
    setId_Widget(content, "tabs.content");
    iWidget *pages = addChildFlags_Widget(
        content, iClob(new_Widget()), expand_WidgetFlag | resizeChildren_WidgetFlag);
    setId_Widget(pages, "tabs.pages");
    addChild_Widget(parent, iClob(tabs));
    setCommandHandler_Widget(tabs, tabSwitcher_);
    return tabs;
}

static void addTabPage_Widget_(iWidget *tabs, enum iWidgetAddPos addPos, iWidget *page,
                               const char *label, int key, int kmods) {
    iWidget *   pages   = findChild_Widget(tabs, "tabs.pages");
    const iBool isSel   = childCount_Widget(pages) == 0;
    iWidget *   buttons = findChild_Widget(tabs, "tabs.buttons");
    iWidget *   button  = addChildPos_Widget(
        buttons,
        iClob(newKeyMods_LabelWidget(label, key, kmods, format_CStr("tabs.switch page:%p", page))),
        addPos);
    setFlags_Widget(button, selected_WidgetFlag, isSel);
    setFlags_Widget(button, commandOnClick_WidgetFlag | expand_WidgetFlag, iTrue);
    setNoTopFrame_LabelWidget((iLabelWidget *) button, iTrue);
    addChildPos_Widget(pages, page, addPos);
    if (tabCount_Widget(tabs) > 1) {
        setFlags_Widget(buttons, hidden_WidgetFlag, iFalse);
    }
    setFlags_Widget(page, hidden_WidgetFlag | disabled_WidgetFlag, !isSel);
}

void appendTabPage_Widget(iWidget *tabs, iWidget *page, const char *label, int key, int kmods) {
    addTabPage_Widget_(tabs, back_WidgetAddPos, page, label, key, kmods);
}

void prependTabPage_Widget(iWidget *tabs, iWidget *page, const char *label, int key, int kmods) {
    addTabPage_Widget_(tabs, front_WidgetAddPos, page, label, key, kmods);
}

void moveTabButtonToEnd_Widget(iWidget *tabButton) {
    iWidget *buttons = tabButton->parent;
    iWidget *tabs    = buttons->parent;
    removeChild_Widget(buttons, tabButton);
    addChild_Widget(buttons, iClob(tabButton));
    arrange_Widget(tabs);
}

iWidget *tabPage_Widget(iWidget *tabs, size_t index) {
    iWidget *pages = findChild_Widget(tabs, "tabs.pages");
    return child_Widget(pages, index);
}

iWidget *removeTabPage_Widget(iWidget *tabs, size_t index) {
    iWidget *buttons = findChild_Widget(tabs, "tabs.buttons");
    iWidget *pages   = findChild_Widget(tabs, "tabs.pages");
    iWidget *button  = removeChild_Widget(buttons, child_Widget(buttons, index));
    iRelease(button);
    iWidget *page = child_Widget(pages, index);
    setFlags_Widget(page, hidden_WidgetFlag | disabled_WidgetFlag, iFalse);
    removeChild_Widget(pages, page); /* `page` is now ours */
    if (tabCount_Widget(tabs) <= 1 && flags_Widget(buttons) & collapse_WidgetFlag) {
        setFlags_Widget(buttons, hidden_WidgetFlag, iTrue);
    }
    return page;
}

void resizeToLargestPage_Widget(iWidget *tabs) {
    if (!tabs) return;
//    puts("RESIZE TO LARGEST PAGE ...");
    iWidget *pages = findChild_Widget(tabs, "tabs.pages");
    iForEach(ObjectList, i, children_Widget(pages)) {
        setMinSize_Widget(i.object, zero_I2());
        iWidget *w = i.object;
        w->rect.size = zero_I2();
    }
    arrange_Widget(tabs);
    iInt2 largest = zero_I2();
    iConstForEach(ObjectList, j, children_Widget(pages)) {
        const iWidget *page = constAs_Widget(j.object);
        largest = max_I2(largest, page->rect.size);
    }
    iForEach(ObjectList, k, children_Widget(pages)) {
        setMinSize_Widget(k.object, largest);
    }
    setFixedSize_Widget(tabs, addY_I2(largest, height_Widget(findChild_Widget(tabs, "tabs.buttons"))));
//    puts("... DONE WITH RESIZE TO LARGEST PAGE");
}

iLabelWidget *tabButtonForPage_Widget_(iWidget *tabs, const iWidget *page) {
    iWidget *buttons = findChild_Widget(tabs, "tabs.buttons");
    iForEach(ObjectList, i, buttons->children) {
        iAssert(isInstance_Object(i.object, &Class_LabelWidget));
        iAny *label = i.object;
        if (pointerLabel_Command(cstr_String(command_LabelWidget(label)), "page") == page) {
            return label;
        }
    }
    return NULL;
}

void showTabPage_Widget(iWidget *tabs, const iWidget *page) {
    if (!page) {
        return;
    }
    /* Select the corresponding button. */ {
        iWidget *buttons = findChild_Widget(tabs, "tabs.buttons");
        iForEach(ObjectList, i, buttons->children) {
            iAssert(isInstance_Object(i.object, &Class_LabelWidget));
            iAny *label = i.object;
            const iBool isSel =
                (pointerLabel_Command(cstr_String(command_LabelWidget(label)), "page") == page);
            setFlags_Widget(label, selected_WidgetFlag, isSel);
        }
    }
    /* Show/hide pages. */ {
        iWidget *pages = findChild_Widget(tabs, "tabs.pages");
        iForEach(ObjectList, i, pages->children) {
            iWidget *child = as_Widget(i.object);
            setFlags_Widget(child, hidden_WidgetFlag | disabled_WidgetFlag, child != page);
        }
    }
    /* Notify. */
    if (!isEmpty_String(id_Widget(page))) {
        postCommandf_Root(page->root, "tabs.changed id:%s", cstr_String(id_Widget(page)));
    }
}

iLabelWidget *tabPageButton_Widget(iWidget *tabs, const iAnyObject *page) {
    return tabButtonForPage_Widget_(tabs, page);
}

iBool isTabButton_Widget(const iWidget *d) {
    return d->parent && cmp_String(id_Widget(d->parent), "tabs.buttons") == 0;
}

void setTabPageLabel_Widget(iWidget *tabs, const iAnyObject *page, const iString *label) {
    iLabelWidget *button = tabButtonForPage_Widget_(tabs, page);
    setText_LabelWidget(button, label);
    arrange_Widget(tabs);
}

size_t tabPageIndex_Widget(const iWidget *tabs, const iAnyObject *page) {
    iWidget *pages = findChild_Widget(tabs, "tabs.pages");
    return childIndex_Widget(pages, page);
}

const iWidget *currentTabPage_Widget(const iWidget *tabs) {
    iWidget *pages = findChild_Widget(tabs, "tabs.pages");
    iConstForEach(ObjectList, i, pages->children) {
        if (isVisible_Widget(i.object)) {
            return constAs_Widget(i.object);
        }
    }
    return NULL;
}

size_t tabCount_Widget(const iWidget *tabs) {
    return childCount_Widget(findChild_Widget(tabs, "tabs.pages"));
}

/*-----------------------------------------------------------------------------------------------*/

iWidget *makeSheet_Widget(const char *id) {
    iWidget *sheet = new_Widget();
    setId_Widget(sheet, id);
    useSheetStyle_Widget(sheet);
    return sheet;
}

void useSheetStyle_Widget(iWidget *d) {
    setPadding1_Widget(d, 3 * gap_UI);
    setFrameColor_Widget(d, uiSeparator_ColorId);
    setBackgroundColor_Widget(d, uiBackground_ColorId);
    setFlags_Widget(d,
                    parentCannotResize_WidgetFlag | focusRoot_WidgetFlag | mouseModal_WidgetFlag |
                        keepOnTop_WidgetFlag | arrangeVertical_WidgetFlag | arrangeSize_WidgetFlag |
                        centerHorizontal_WidgetFlag | overflowScrollable_WidgetFlag,
                    iTrue);
}

static void acceptValueInput_(iWidget *dlg) {
    const iInputWidget *input = findChild_Widget(dlg, "input");
    if (!isEmpty_String(id_Widget(dlg))) {
        const iString *val = text_InputWidget(input);
        postCommandf_App("%s arg:%d value:%s",
                         cstr_String(id_Widget(dlg)),
                         toInt_String(val),
                         cstr_String(val));
    }
}

static void updateValueInputWidth_(iWidget *dlg) {
    const iRect safeRoot = safeRect_Root(dlg->root);
    const iInt2 rootSize = safeRoot.size;
    iWidget *   title    = findChild_Widget(dlg, "valueinput.title");
    iWidget *   prompt   = findChild_Widget(dlg, "valueinput.prompt");
    if (deviceType_App() == phone_AppDeviceType) {
        dlg->rect.size.x = rootSize.x;
    }
    else {
        dlg->rect.size.x =
            iMin(rootSize.x, iMaxi(iMaxi(100 * gap_UI, title->rect.size.x), prompt->rect.size.x));
    }
    /* Adjust the maximum number of visible lines. */
    int footer = 6 * gap_UI + get_MainWindow()->keyboardHeight;
    iWidget *buttons = findChild_Widget(dlg, "dialogbuttons");
    if (buttons) {
        footer += height_Widget(buttons);
    }
    iInputWidget *input = findChild_Widget(dlg, "input");
    setLineLimits_InputWidget(input,
                              1,
                              (bottom_Rect(safeRect_Root(dlg->root)) - footer -
                               top_Rect(boundsWithoutVisualOffset_Widget(as_Widget(input)))) /
                                  lineHeight_Text(font_InputWidget(input)));
}

iBool valueInputHandler_(iWidget *dlg, const char *cmd) {
    iWidget *ptr = as_Widget(pointer_Command(cmd));
    if (equal_Command(cmd, "window.resized") || equal_Command(cmd, "keyboard.changed")) {
        if (isVisible_Widget(dlg)) {
            updateValueInputWidth_(dlg);
            arrange_Widget(dlg);
        }
        return iFalse;
    }
    if (equal_Command(cmd, "input.ended")) {
        if (argLabel_Command(cmd, "enter") && hasParent_Widget(ptr, dlg)) {
            if (arg_Command(cmd)) {
                acceptValueInput_(dlg);
            }
            else {
                postCommandf_App("valueinput.cancelled id:%s", cstr_String(id_Widget(dlg)));
                setId_Widget(dlg, ""); /* no further commands to emit */
            }
            setupSheetTransition_Mobile(dlg, top_TransitionDir);
            destroy_Widget(dlg);
            return iTrue;
        }
        return iFalse;
    }
    else if (equal_Command(cmd, "valueinput.cancel")) {
        postCommandf_App("valueinput.cancelled id:%s", cstr_String(id_Widget(dlg)));
        setId_Widget(dlg, ""); /* no further commands to emit */
        setupSheetTransition_Mobile(dlg, top_TransitionDir);
        destroy_Widget(dlg);
        return iTrue;
    }
    else if (equal_Command(cmd, "valueinput.accept")) {
        acceptValueInput_(dlg);
        setupSheetTransition_Mobile(dlg, top_TransitionDir);        
        destroy_Widget(dlg);
        return iTrue;
    }
    return iFalse;
}

iWidget *makeDialogButtons_Widget(const iMenuItem *actions, size_t numActions) {
    iWidget *div = new_Widget();
    setId_Widget(div, "dialogbuttons");
    setFlags_Widget(div,
                    arrangeHorizontal_WidgetFlag | arrangeHeight_WidgetFlag |
                        resizeToParentWidth_WidgetFlag |
                        resizeWidthOfChildren_WidgetFlag,
                    iTrue);
    /* If there is no separator, align everything to the right. */
    iBool haveSep = iFalse;
    for (size_t i = 0; i < numActions; i++) {
        if (!iCmpStr(actions[i].label, "---")) {
            haveSep = iTrue;
            break;
        }
    }
    if (!haveSep) {
        addChildFlags_Widget(div, iClob(new_Widget()), expand_WidgetFlag);
    }
    int fonts[2] = { uiLabel_FontId, uiLabelBold_FontId };
    if (deviceType_App() == phone_AppDeviceType) {
        fonts[0] = defaultMedium_FontId;
        fonts[1] = defaultMediumBold_FontId;
    }
    for (size_t i = 0; i < numActions; i++) {
        const char *label     = actions[i].label;
        const char *cmd       = actions[i].command;
        int         key       = actions[i].key;
        int         kmods     = actions[i].kmods;
        const iBool isDefault = (i == numActions - 1);
        if (*label == '*' || *label == '&') {
            continue; /* Special value selection items for a Question dialog. */
        }
        if (startsWith_CStr(label, "```")) {
            /* Annotation. */
            iLabelWidget *annotation = addChild_Widget(div, iClob(new_LabelWidget(label + 3, NULL)));
            setTextColor_LabelWidget(annotation, uiTextAction_ColorId);
            continue;
        }
        if (!iCmpStr(label, "---")) {
            /* Separator.*/
            addChildFlags_Widget(div, iClob(new_Widget()), expand_WidgetFlag);
            continue;
        }
        if (!iCmpStr(label, "${cancel}") && !cmd) {
            cmd = "cancel";
            key = SDLK_ESCAPE;
            kmods = 0;
        }
        if (isDefault) {
            if (!key) {
                key = SDLK_RETURN;
                kmods = 0;
            }
            if (label == NULL) {
                label = format_CStr(uiTextAction_ColorEscape "%s", cstr_Lang("dlg.default"));
            }
        }
        iLabelWidget *button =
            addChild_Widget(div, iClob(newKeyMods_LabelWidget(label, key, kmods, cmd)));
        if (isDefault) {
            setId_Widget(as_Widget(button), "default");
        }
        setFlags_Widget(as_Widget(button), alignLeft_WidgetFlag | drawKey_WidgetFlag, isDefault);
        setFont_LabelWidget(button, isDefault ? fonts[1] : fonts[0]);
    }
    return div;
}

iWidget *makeValueInput_Widget(iWidget *parent, const iString *initialValue, const char *title,
                               const char *prompt, const char *acceptLabel, const char *command) {
    if (parent) {
        setFocus_Widget(NULL);
    }
    iWidget *dlg = makeSheet_Widget(command);
    setCommandHandler_Widget(dlg, valueInputHandler_);
    if (parent) {
        addChild_Widget(parent, iClob(dlg));
    }
    setId_Widget(
        addChildFlags_Widget(dlg, iClob(new_LabelWidget(title, NULL)), frameless_WidgetFlag),
        "valueinput.title");
    setId_Widget(
        addChildFlags_Widget(dlg, iClob(new_LabelWidget(prompt, NULL)), frameless_WidgetFlag),
        "valueinput.prompt");
    iInputWidget *input = addChildFlags_Widget(dlg, iClob(new_InputWidget(0)),
                                               resizeToParentWidth_WidgetFlag);
    setContentPadding_InputWidget(input, 0.5f * gap_UI, 0.5f * gap_UI);
    if (deviceType_App() == phone_AppDeviceType) {
        setFont_InputWidget(input, defaultBig_FontId);
        setBackgroundColor_Widget(dlg, uiBackgroundSidebar_ColorId);
        setContentPadding_InputWidget(input, gap_UI, gap_UI);
    }
    if (initialValue) {
        setText_InputWidget(input, initialValue);
    }
    setId_Widget(as_Widget(input), "input");
    addChild_Widget(dlg, iClob(makePadding_Widget(gap_UI)));
    addChild_Widget(dlg,
                    iClob(makeDialogButtons_Widget(
                        (iMenuItem[]){ { "${cancel}", SDLK_ESCAPE, 0, "valueinput.cancel" },
                                       { acceptLabel,
                                         SDLK_RETURN,
                                         acceptKeyMod_ReturnKeyBehavior(prefs_App()->returnKey),
                                         "valueinput.accept" } },
                        2)));
//    finalizeSheet_Mobile(dlg);
    arrange_Widget(dlg);
    if (parent) {
        setFocus_Widget(as_Widget(input));
    }
    /* Check that the top is in the safe area. */ {
        int top = top_Rect(bounds_Widget(dlg));
        int delta = top - top_Rect(safeRect_Root(dlg->root));
        if (delta < 0) {
            dlg->rect.pos.y -= delta;
        }
    }
    updateValueInputWidth_(dlg);
    setupSheetTransition_Mobile(dlg, incoming_TransitionFlag | top_TransitionDir);
    return dlg;
}

void updateValueInput_Widget(iWidget *d, const char *title, const char *prompt) {
    setTextCStr_LabelWidget(findChild_Widget(d, "valueinput.title"), title);
    setTextCStr_LabelWidget(findChild_Widget(d, "valueinput.prompt"), prompt);
    updateValueInputWidth_(d);
}

static iBool messageHandler_(iWidget *msg, const char *cmd) {
    /* Almost any command dismisses the sheet. */
    /* TODO: Add a "notification" type of user events to separate them from user actions. */
    if (!(equal_Command(cmd, "media.updated") ||
          equal_Command(cmd, "media.player.update") ||
          equal_Command(cmd, "bookmarks.request.finished") ||
          equal_Command(cmd, "document.autoreload") ||
          equal_Command(cmd, "document.reload") ||
          equal_Command(cmd, "document.request.updated") ||
          equal_Command(cmd, "scrollbar.fade") ||
          equal_Command(cmd, "widget.overflow") ||
          equal_Command(cmd, "edgeswipe.ended") ||
          startsWith_CStr(cmd, "window."))) {
        setupSheetTransition_Mobile(msg, iFalse);
        destroy_Widget(msg);
    }
    return iFalse;
}

iWidget *makeSimpleMessage_Widget(const char *title, const char *msg) {
    return makeMessage_Widget(title,
                              msg,
                              (iMenuItem[]){ { "${dlg.message.ok}", 0, 0, "message.ok" } },
                              1);
}

iWidget *makeMessage_Widget(const char *title, const char *msg, const iMenuItem *items,
                            size_t numItems) {
    iWidget *dlg = makeQuestion_Widget(title, msg, items, numItems);
    addAction_Widget(dlg, SDLK_ESCAPE, 0, "message.ok");
    addAction_Widget(dlg, SDLK_SPACE, 0, "message.ok");
    return dlg;
}

iWidget *makeQuestion_Widget(const char *title, const char *msg,
                             const iMenuItem *items, size_t numItems) {
    processEvents_App(postedEventsOnly_AppEventMode);
    if (isUsingPanelLayout_Mobile()) {
        iArray *panelItems = collectNew_Array(sizeof(iMenuItem));
        pushBackN_Array(panelItems, (iMenuItem[]){
            { format_CStr("title text:%s", title) },
            { format_CStr("label text:%s", msg) },
            { NULL }
        }, 3);
        for (size_t i = 0; i < numItems; i++) {
            const iMenuItem *item = &items[i];
            const char first = item->label[0];
            if (first == '*' || first == '&') {
                insert_Array(panelItems, size_Array(panelItems) - 1,
                             &(iMenuItem){ format_CStr("button selected:%d text:%s",
                                                       first == '&' ? 1 : 0, item->label + 1),
                                           0, 0, item->command });
            }
        }
        iWidget *dlg = makePanels_Mobile("", data_Array(panelItems), items, numItems);
        setCommandHandler_Widget(dlg, messageHandler_);
        setupSheetTransition_Mobile(dlg, iTrue);
        return dlg;
    }
    iWidget *dlg = makeSheet_Widget("");
    setCommandHandler_Widget(dlg, messageHandler_);
    addChildFlags_Widget(dlg, iClob(new_LabelWidget(title, NULL)), frameless_WidgetFlag);
    addChildFlags_Widget(dlg, iClob(new_LabelWidget(msg, NULL)), frameless_WidgetFlag);
    /* Check for value selections. */
    for (size_t i = 0; i < numItems; i++) {
        const iMenuItem *item = &items[i];
        const char first = item->label[0];
        if (first == '*' || first == '&') {
            iLabelWidget *option =
                addChildFlags_Widget(dlg,
                                 iClob(newKeyMods_LabelWidget(item->label + 1,
                                                              item->key,
                                                              item->kmods,
                                                              item->command)),
                                 resizeToParentWidth_WidgetFlag |
                                 (first == '&' ? selected_WidgetFlag : 0));
            if (deviceType_App() != desktop_AppDeviceType) {
                setFont_LabelWidget(option, defaultBig_FontId);
            }
        }
    }
    addChild_Widget(dlg, iClob(makePadding_Widget(gap_UI)));
    addChild_Widget(dlg, iClob(makeDialogButtons_Widget(items, numItems)));
    addChild_Widget(dlg->root->widget, iClob(dlg));
    arrange_Widget(dlg); /* BUG: This extra arrange shouldn't be needed but the dialog won't
                            be arranged correctly unless it's here. */
    setupSheetTransition_Mobile(dlg, iTrue);
    return dlg;
}

void setToggle_Widget(iWidget *d, iBool active) {
    if (d) {
        setFlags_Widget(d, selected_WidgetFlag, active);
        iLabelWidget *label = (iLabelWidget *) d;
        if (!cmp_String(text_LabelWidget(label), cstr_Lang("toggle.yes")) ||
            !cmp_String(text_LabelWidget(label), cstr_Lang("toggle.no"))) {
            updateText_LabelWidget(
                (iLabelWidget *) d,
                collectNewCStr_String(isSelected_Widget(d) ? "${toggle.yes}" : "${toggle.no}"));
        }
        else {
            refresh_Widget(d);
        }
    }
}

static iBool toggleHandler_(iWidget *d, const char *cmd) {
    if (equal_Command(cmd, "toggle") && pointer_Command(cmd) == d) {
        setToggle_Widget(d, (flags_Widget(d) & selected_WidgetFlag) == 0);
        postCommand_Widget(d,
                           format_CStr("%s.changed arg:%d",
                                       cstr_String(id_Widget(d)),
                                       isSelected_Widget(d) ? 1 : 0));
        return iTrue;
    }
    else if (equal_Command(cmd, "lang.changed")) {
        /* TODO: Measure labels again. */
    }
    return iFalse;
}

iWidget *makeToggle_Widget(const char *id) {
    iWidget *toggle = as_Widget(new_LabelWidget("${toggle.yes}", "toggle")); /* "YES" for sizing */
    setId_Widget(toggle, id);
    /* TODO: Measure both labels and use the larger of the two. */
    updateTextCStr_LabelWidget((iLabelWidget *) toggle, "${toggle.no}"); /* actual initial value */
    setFlags_Widget(toggle, fixedWidth_WidgetFlag, iTrue);
    setCommandHandler_Widget(toggle, toggleHandler_);
    return toggle;
}

void appendFramelessTabPage_Widget(iWidget *tabs, iWidget *page, const char *title, int shortcut,
                                   int kmods) {
    appendTabPage_Widget(tabs, page, title, shortcut, kmods);
    setFlags_Widget(
        (iWidget *) back_ObjectList(children_Widget(findChild_Widget(tabs, "tabs.buttons"))),
        frameless_WidgetFlag | noBackground_WidgetFlag,
        iTrue);
}

iWidget *makeTwoColumns_Widget(iWidget **headings, iWidget **values) {
    iWidget *page = new_Widget();
    setFlags_Widget(page, arrangeHorizontal_WidgetFlag | arrangeSize_WidgetFlag, iTrue);
    *headings = addChildFlags_Widget(
        page, iClob(new_Widget()), arrangeVertical_WidgetFlag | arrangeSize_WidgetFlag);
    *values = addChildFlags_Widget(
        page, iClob(new_Widget()), arrangeVertical_WidgetFlag | arrangeSize_WidgetFlag);
    return page;
}

iLabelWidget *dialogAcceptButton_Widget(const iWidget *d) {
    iWidget *buttonParent = findChild_Widget(d, "dialogbuttons");
    if (!buttonParent) {
        iAssert(isUsingPanelLayout_Mobile());
        buttonParent = findChild_Widget(d, "panel.back");
    }
    return (iLabelWidget *) lastChild_Widget(buttonParent);
}

iWidget *appendTwoColumnTabPage_Widget(iWidget *tabs, const char *title, int shortcut, iWidget **headings,
                                       iWidget **values) {
    /* TODO: Use `makeTwoColumnWidget_()`, see above. */
    iWidget *page = new_Widget();
    setFlags_Widget(page, arrangeVertical_WidgetFlag | arrangeSize_WidgetFlag, iTrue);
    addChildFlags_Widget(page, iClob(new_Widget()), expand_WidgetFlag);
    setPadding_Widget(page, 0, gap_UI, 0, gap_UI);
    iWidget *columns = new_Widget();
    addChildFlags_Widget(page, iClob(columns), arrangeHorizontal_WidgetFlag | arrangeSize_WidgetFlag);
    *headings = addChildFlags_Widget(
        columns, iClob(new_Widget()), arrangeVertical_WidgetFlag | arrangeSize_WidgetFlag);
    *values = addChildFlags_Widget(
        columns, iClob(new_Widget()), arrangeVertical_WidgetFlag | arrangeSize_WidgetFlag);
    addChildFlags_Widget(page, iClob(new_Widget()), expand_WidgetFlag);
    appendFramelessTabPage_Widget(tabs, iClob(page), title, shortcut, shortcut ? KMOD_PRIMARY : 0);
    return page;
}

static void makeTwoColumnHeading_(const char *title, iWidget *headings, iWidget *values) {
    addChildFlags_Widget(headings,
                         iClob(makeHeading_Widget(format_CStr(uiHeading_ColorEscape "%s", title))),
                         ignoreForParentWidth_WidgetFlag);
    addChild_Widget(values, iClob(makeHeading_Widget("")));
}

static void expandInputFieldWidth_(iInputWidget *input) {
    if (!input) return;
    iWidget *page = as_Widget(input)->parent->parent->parent->parent; /* tabs > page > values > input */
    as_Widget(input)->rect.size.x =
        right_Rect(bounds_Widget(page)) - left_Rect(bounds_Widget(constAs_Widget(input)));
}

static void addRadioButton_(iWidget *parent, const char *id, const char *label, const char *cmd) {
    setId_Widget(
        addChildFlags_Widget(parent, iClob(new_LabelWidget(label, cmd)), radio_WidgetFlag),
        id);
}

static const iArray *makeFontItems_(const char *id) {
    const struct {
        const char *   name;
        enum iTextFont cfgId;
    } fonts[] = { { "Nunito", nunito_TextFont },
                  { "Source Sans 3", sourceSans3_TextFont },
                  { "Fira Sans", firaSans_TextFont },
                  { "---", -1 },
                  { "Literata", literata_TextFont },
                  { "Tinos", tinos_TextFont },
                  { "---", -1 },
                  { "Iosevka", iosevka_TextFont } };
    iArray *items = collectNew_Array(sizeof(iMenuItem));
    iForIndices(i, fonts) {
        pushBack_Array(items,
                       &(iMenuItem){ fonts[i].name,
                                     0,
                                     0,
                                     fonts[i].cfgId >= 0
                                         ? format_CStr("!%s.set arg:%d", id, fonts[i].cfgId)
                                         : NULL });
    }
    pushBack_Array(items, &(iMenuItem){ NULL }); /* terminator */
    return items;
}

static void addFontButtons_(iWidget *parent, const char *id) {
    const iArray *items = makeFontItems_(id);
    iLabelWidget *button = makeMenuButton_LabelWidget("Source Sans 3",
                                                      constData_Array(items), size_Array(items));
    setBackgroundColor_Widget(findChild_Widget(as_Widget(button), "menu"),
                              uiBackgroundMenu_ColorId);
    setId_Widget(as_Widget(button), format_CStr("prefs.%s", id));
    addChildFlags_Widget(parent, iClob(button), alignLeft_WidgetFlag);
}

#if 0
static int cmp_MenuItem_(const void *e1, const void *e2) {
    const iMenuItem *a = e1, *b = e2;
    return iCmpStr(a->label, b->label);
}
#endif

void updatePreferencesLayout_Widget(iWidget *prefs) {
    if (!prefs || deviceType_App() != desktop_AppDeviceType) {
        return;
    }
    /* Doing manual layout here because the widget arranging logic isn't sophisticated enough. */
    /* TODO: Make the arranging more sophisticated to automate this. */
    static const char *inputIds[] = {
        "prefs.searchurl",
        "prefs.downloads",
        "prefs.userfont",
        "prefs.ca.file",
        "prefs.ca.path",
        "prefs.proxy.gemini",
        "prefs.proxy.gopher",
        "prefs.proxy.http"
    };
    iWidget *tabs = findChild_Widget(prefs, "prefs.tabs");
    /* Input fields expand to the right edge. */
    /* TODO: Add an arrangement flag for this. */
    iForIndices(i, inputIds) {
        iInputWidget *input = findChild_Widget(tabs, inputIds[i]);
        if (input) {
            as_Widget(input)->rect.size.x = 0;
        }
    }
    iWidget *bindings = findChild_Widget(prefs, "bindings");
    if (bindings) {
        bindings->rect.size.x = 0;
    }
    resizeToLargestPage_Widget(tabs);
    arrange_Widget(prefs);
    iForIndices(i, inputIds) {
        expandInputFieldWidth_(findChild_Widget(tabs, inputIds[i]));
    }
}

static void addDialogInputWithHeadingAndFlags_(iWidget *headings, iWidget *values, const char *labelText,
                                               const char *inputId, iInputWidget *input, int64_t flags) {
    iLabelWidget *head = addChild_Widget(headings, iClob(makeHeading_Widget(labelText)));
#if defined (iPlatformMobile)
    /* On mobile, inputs have 2 gaps of extra padding. */
    setFixedSize_Widget(as_Widget(head), init_I2(-1, height_Widget(input)));
    setPadding_Widget(as_Widget(head), 0, gap_UI, 0, 0);
#endif
    setId_Widget(addChild_Widget(values, input), inputId);
    if (deviceType_App() != phone_AppDeviceType) {
        /* Ensure that the label has the same height as the input widget. */
        as_Widget(head)->sizeRef = as_Widget(input);
    }
    setFlags_Widget(as_Widget(head), flags, iTrue);
    setFlags_Widget(as_Widget(input), flags, iTrue);
}

static void addDialogInputWithHeading_(iWidget *headings, iWidget *values, const char *labelText,
                                       const char *inputId, iInputWidget *input) {
    addDialogInputWithHeadingAndFlags_(headings, values, labelText, inputId, input, 0);
}

iInputWidget *addTwoColumnDialogInputField_Widget(iWidget *headings, iWidget *values,
                                                  const char *labelText, const char *inputId,
                                                  iInputWidget *input) {
    addDialogInputWithHeading_(headings, values, labelText, inputId, input);
    return input;
}

static void addDialogPadding_(iWidget *headings, iWidget *values) {
    const int bigGap = lineHeight_Text(uiLabel_FontId) * 3 / 4;
    addChild_Widget(headings, iClob(makePadding_Widget(bigGap)));
    addChild_Widget(values,   iClob(makePadding_Widget(bigGap)));    
}

static void addPrefsInputWithHeading_(iWidget *headings, iWidget *values,
                                      const char *id, iInputWidget *input) {
    addDialogInputWithHeading_(headings, values, format_CStr("${%s}", id), id, input);
}

static void addDialogToggle_(iWidget *headings, iWidget *values,
                             const char *heading, const char *toggleId) {
    addChild_Widget(headings, iClob(makeHeading_Widget(heading)));
    addChild_Widget(values, iClob(makeToggle_Widget(toggleId)));
}

size_t findWidestLabel_MenuItem(const iMenuItem *items, size_t num) {
    int widest = 0;
    size_t widestPos = iInvalidPos;
    for (size_t i = 0; i < num && items[i].label; i++) {
        const int width =
            measure_Text(uiLabel_FontId,
                         translateCStr_Lang(items[i].label))
                .advance.x;
        if (widestPos == iInvalidPos || width > widest) {
            widest = width;
            widestPos = i;
        }
    }
    return widestPos;
}

iChar removeIconPrefix_String(iString *d) {
    if (isEmpty_String(d)) {
        return 0;
    }
    iStringConstIterator iter;
    init_StringConstIterator(&iter, d);
    iChar icon = iter.value;
    next_StringConstIterator(&iter);
    if (iter.value == ' ' && icon >= 0x100) {
        remove_Block(&d->chars, 0, iter.next - constBegin_String(d));
        return icon;
    }
    return 0;
}

iWidget *makeDialog_Widget(const char *id,
                           const iMenuItem *itemsNullTerminated,
                           const iMenuItem *actions, size_t numActions) {
    iWidget *dlg = makeSheet_Widget(id);
    /* TODO: Construct desktop dialogs using NULL-terminated item arrays, like mobile panels. */
    addChild_Widget(dlg, iClob(makePadding_Widget(gap_UI)));
    addChild_Widget(dlg, iClob(makeDialogButtons_Widget(actions, numActions)));
    addChild_Widget(dlg->root->widget, iClob(dlg));
    arrange_Widget(dlg);
    setupSheetTransition_Mobile(dlg, iTrue);
    return dlg;
}

iWidget *makePreferences_Widget(void) {
    /* Common items. */
    const iMenuItem langItems[] = { { "${lang.de} - de", 0, 0, "uilang id:de" },
                                    { "${lang.en} - en", 0, 0, "uilang id:en" },
                                    { "${lang.es} - es", 0, 0, "uilang id:es" },
                                    { "${lang.es.mx} - es", 0, 0, "uilang id:es_MX" },
                                    { "${lang.eo} - eo", 0, 0, "uilang id:eo" },
                                    { "${lang.fi} - fi", 0, 0, "uilang id:fi" },
                                    { "${lang.fr} - fr", 0, 0, "uilang id:fr" },
                                    { "${lang.gl} - gl", 0, 0, "uilang id:gl" },
                                    { "${lang.ia} - ia", 0, 0, "uilang id:ia" },
                                    { "${lang.ie} - ie", 0, 0, "uilang id:ie" },
                                    { "${lang.isv} - isv", 0, 0, "uilang id:isv" },
                                    { "${lang.pl} - pl", 0, 0, "uilang id:pl" },
                                    { "${lang.ru} - ru", 0, 0, "uilang id:ru" },
                                    { "${lang.sk} - sk", 0, 0, "uilang id:sk" },
                                    { "${lang.sr} - sr", 0, 0, "uilang id:sr" },
                                    { "${lang.tok} - tok", 0, 0, "uilang id:tok" },
                                    { "${lang.zh.hans} - zh", 0, 0, "uilang id:zh_Hans" },
                                    { "${lang.zh.hant} - zh", 0, 0, "uilang id:zh_Hant" },
                                    { NULL } };
    const iMenuItem returnKeyBehaviors[] = {
        { "${prefs.returnkey.linebreak} " uiTextAction_ColorEscape shift_Icon return_Icon
                                                                    restore_ColorEscape
          "    ${prefs.returnkey.accept} " uiTextAction_ColorEscape return_Icon,
          0,
          0,
          format_CStr("returnkey.set arg:%d", default_ReturnKeyBehavior) },
        { "${prefs.returnkey.linebreak} " uiTextAction_ColorEscape return_Icon restore_ColorEscape
          "    ${prefs.returnkey.accept} " uiTextAction_ColorEscape shift_Icon return_Icon,
          0,
          0,
          format_CStr("returnkey.set arg:%d", acceptWithShift_ReturnKeyBehavior) },
        { "${prefs.returnkey.linebreak} " uiTextAction_ColorEscape return_Icon restore_ColorEscape
          "    ${prefs.returnkey.accept} " uiTextAction_ColorEscape
#if defined (iPlatformApple)
          "\u2318" return_Icon,
#else
          "Ctrl" return_Icon,
#endif
          0,
          0,
          format_CStr("returnkey.set arg:%d", acceptWithPrimaryMod_ReturnKeyBehavior) },
        { NULL }
    };
    iMenuItem docThemes[2][max_GmDocumentTheme + 1];
    for (int i = 0; i < 2; ++i) {
        const iBool isDark = (i == 0);
        const char *mode = isDark ? "dark" : "light";
        const iMenuItem items[max_GmDocumentTheme + 1] = {
            { "${prefs.doctheme.name.colorfuldark}", 0, 0, format_CStr("doctheme.%s.set arg:%d", mode, colorfulDark_GmDocumentTheme) },
            { "${prefs.doctheme.name.colorfullight}", 0, 0, format_CStr("doctheme.%s.set arg:%d", mode, colorfulLight_GmDocumentTheme) },
            { "${prefs.doctheme.name.black}", 0, 0, format_CStr("doctheme.%s.set arg:%d", mode, black_GmDocumentTheme) },
            { "${prefs.doctheme.name.gray}", 0, 0, format_CStr("doctheme.%s.set arg:%d", mode, gray_GmDocumentTheme) },
            { "${prefs.doctheme.name.white}", 0, 0, format_CStr("doctheme.%s.set arg:%d", mode, white_GmDocumentTheme) },
            { "${prefs.doctheme.name.sepia}", 0, 0, format_CStr("doctheme.%s.set arg:%d", mode, sepia_GmDocumentTheme) },
            { "${prefs.doctheme.name.highcontrast}", 0, 0, format_CStr("doctheme.%s.set arg:%d", mode, highContrast_GmDocumentTheme) },
            { NULL }
        };
        memcpy(docThemes[i], items, sizeof(items));
    }
    const iMenuItem imgStyles[] = {
        { "${prefs.imagestyle.original}",  0, 0, format_CStr("imagestyle.set arg:%d", original_ImageStyle) },
        { "${prefs.imagestyle.grayscale}", 0, 0, format_CStr("imagestyle.set arg:%d", grayscale_ImageStyle) },
        { "${prefs.imagestyle.bgfg}",      0, 0, format_CStr("imagestyle.set arg:%d", bgFg_ImageStyle) },
        { "${prefs.imagestyle.text}",      0, 0, format_CStr("imagestyle.set arg:%d", textColorized_ImageStyle) },
        { "${prefs.imagestyle.preformat}", 0, 0, format_CStr("imagestyle.set arg:%d", preformatColorized_ImageStyle) },
        { NULL }
    };
    /* Create the Preferences UI. */
    if (isUsingPanelLayout_Mobile()) {
        const iMenuItem pinSplitItems[] = {
            { "button id:prefs.pinsplit.0 label:prefs.pinsplit.none",  0, 0, "pinsplit.set arg:0" },
            { "button id:prefs.pinsplit.1 label:prefs.pinsplit.left",  0, 0, "pinsplit.set arg:1" },
            { "button id:prefs.pinsplit.2 label:prefs.pinsplit.right", 0, 0, "pinsplit.set arg:2" },
            { NULL }
        };
        const iMenuItem themeItems[] = {
            { "button id:prefs.theme.0 label:prefs.theme.black", 0, 0, "theme.set arg:0" },
            { "button id:prefs.theme.1 label:prefs.theme.dark",  0, 0, "theme.set arg:1" },
            { "button id:prefs.theme.2 label:prefs.theme.light", 0, 0, "theme.set arg:2" },
            { "button id:prefs.theme.3 label:prefs.theme.white", 0, 0, "theme.set arg:3" },
            { NULL }  
        };
        const iMenuItem accentItems[] = {
            { "button id:prefs.accent.0 label:prefs.accent.teal", 0, 0, "accent.set arg:0" },
            { "button id:prefs.accent.1 label:prefs.accent.orange", 0, 0, "accent.set arg:1" },
            { NULL }
        };
        const iMenuItem satItems[] = {
            { "button id:prefs.saturation.3 text:100 %", 0, 0, "saturation.set arg:100" },
            { "button id:prefs.saturation.2 text:66 %", 0, 0, "saturation.set arg:66" },
            { "button id:prefs.saturation.1 text:33 %", 0, 0, "saturation.set arg:33" },
            { "button id:prefs.saturation.0 text:0 %", 0, 0, "saturation.set arg:0" },
            { NULL }  
        };
        const iMenuItem monoFontItems[] = {
            { "button id:prefs.mono.gemini" },
            { "button id:prefs.mono.gopher" },
            { NULL }  
        };
        const iMenuItem boldLinkItems[] = {
            { "button id:prefs.boldlink.dark" },
            { "button id:prefs.boldlink.light" },
            { NULL }  
        };
        const iMenuItem lineWidthItems[] = {
            { "button id:prefs.linewidth.30 text:\u20132", 0, 0, "linewidth.set arg:30" },
            { "button id:prefs.linewidth.34 text:\u20131", 0, 0, "linewidth.set arg:34" },
            { "button id:prefs.linewidth.38 label:prefs.linewidth.normal", 0, 0, "linewidth.set arg:38" },
            { "button id:prefs.linewidth.43 text:+1", 0, 0, "linewidth.set arg:43" },
            { "button id:prefs.linewidth.48 text:+2", 0, 0, "linewidth.set arg:48" },
            { "button id:prefs.linewidth.1000 label:prefs.linewidth.fill", 0, 0, "linewidth.set arg:1000" },
            { NULL }              
        };
        const iMenuItem quoteItems[] = {
            { "button id:prefs.quoteicon.1 label:prefs.quoteicon.icon", 0, 0, "quoteicon.set arg:1" },
            { "button id:prefs.quoteicon.0 label:prefs.quoteicon.line", 0, 0, "quoteicon.set arg:0" },
            { NULL }  
        };
        const iMenuItem generalPanelItems[] = {
            { "title id:heading.prefs.general" },
            { "heading text:${prefs.searchurl}" },
            { "input id:prefs.searchurl url:1 noheading:1" },
            { "padding" },
            { "toggle id:prefs.archive.openindex" },
            { "radio device:1 id:prefs.pinsplit", 0, 0, (const void *) pinSplitItems },
            { "padding" },
            { "dropdown id:prefs.uilang", 0, 0, (const void *) langItems },
            { NULL }
        };
        const iMenuItem uiPanelItems[] = {
            { "title id:heading.prefs.interface" },
            { "dropdown device:1 id:prefs.returnkey", 0, 0, (const void *) returnKeyBehaviors },
            { "padding device:1" },
            { "toggle id:prefs.hoverlink" },
            { "toggle device:2 id:prefs.hidetoolbarscroll" },
            { "heading id:heading.prefs.sizing" },
            { "input id:prefs.uiscale maxlen:8" },
            { NULL }
        };
        const iMenuItem colorPanelItems[] = {
            { "title id:heading.prefs.colors" },
            { "heading id:heading.prefs.uitheme" },
            { "toggle id:prefs.ostheme" },
            { "radio id:prefs.theme", 0, 0, (const void *) themeItems },
            { "radio id:prefs.accent", 0, 0, (const void *) accentItems },
            { "heading id:heading.prefs.pagecontent" },
            { "dropdown id:prefs.doctheme.dark", 0, 0, (const void *) docThemes[0] },
            { "dropdown id:prefs.doctheme.light", 0, 0, (const void *) docThemes[1] },
            { "radio id:prefs.saturation", 0, 0, (const void *) satItems },
            { "padding" },
            { "dropdown id:prefs.imagestyle", 0, 0, (const void *) imgStyles },
            { NULL }  
        };
        const iMenuItem fontPanelItems[] = {
            { "title id:heading.prefs.fonts" },
            { "dropdown id:prefs.headingfont", 0, 0, (const void *) constData_Array(makeFontItems_("headingfont")) },
            { "dropdown id:prefs.font", 0, 0, (const void *) constData_Array(makeFontItems_("font")) },
            { "buttons id:prefs.mono", 0, 0, (const void *) monoFontItems },
            { "buttons id:prefs.boldlink", 0, 0, (const void *) boldLinkItems },
            { NULL }  
        };
        const iMenuItem stylePanelItems[] = {
            { "title id:heading.prefs.style" },
            { "radio id:prefs.linewidth", 0, 0, (const void *) lineWidthItems },
            { "padding" },
            { "input id:prefs.linespacing maxlen:5" },
            { "radio id:prefs.quoteicon", 0, 0, (const void *) quoteItems },
            { "padding" },
            { "toggle id:prefs.biglede" },
            { "toggle id:prefs.plaintext.wrap" },
            { "toggle id:prefs.collapsepreonload" },
            { "toggle id:prefs.sideicon" },
            { "toggle id:prefs.centershort" },            
            { NULL }    
        };
        const iMenuItem networkPanelItems[] = {
            { "title id:heading.prefs.network" },
            { "toggle id:prefs.decodeurls" },
            { "padding" },
            { "input id:prefs.cachesize maxlen:4 selectall:1 unit:mb" },
            { "input id:prefs.memorysize maxlen:4 selectall:1 unit:mb" },
            { "heading text:${prefs.proxy.gemini}" },
            { "input id:prefs.proxy.gemini noheading:1" },
            { "heading text:${prefs.proxy.gopher}" },
            { "input id:prefs.proxy.gopher noheading:1" },
            { "heading text:${prefs.proxy.http}" },
            { "input id:prefs.proxy.http noheading:1" },
            { NULL }
        };
        const iMenuItem identityPanelItems[] = {
            { "title id:sidebar.identities" },
            { NULL }  
        };
        iString *aboutText = collectNew_String(); {
            setCStr_String(aboutText, "Lagrange " LAGRANGE_APP_VERSION);
#if defined (iPlatformAppleMobile)
            appendFormat_String(aboutText, " (" LAGRANGE_IOS_VERSION ") %s" LAGRANGE_IOS_BUILD_DATE,
                                escape_Color(uiTextDim_ColorId));
#endif
        }
        const iMenuItem aboutPanelItems[] = {
            { format_CStr("heading text:%s", cstr_String(aboutText)) },
            { "button text:" clock_Icon " ${menu.releasenotes}", 0, 0, "!open url:about:version" },
            { "button text:" globe_Icon " ${menu.website}", 0, 0, "!open url:https://gmi.skyjake.fi/lagrange" },
            { "button text:" envelope_Icon " @jk@skyjake.fi", 0, 0, "!open url:https://skyjake.fi/@jk" },
            { "padding" },
            { "button text:" info_Icon " ${menu.aboutpages}", 0, 0, "!open url:about:about" },
            { "button text:" bug_Icon " ${menu.debug}", 0, 0, "!open url:about:debug" },
            { NULL }
        };
        iWidget *dlg = makePanels_Mobile("prefs", (iMenuItem[]){
            { "title id:heading.settings" },
            { "panel text:" gear_Icon " ${heading.prefs.general}", 0, 0, (const void *) generalPanelItems },
            { "panel icon:0x1f5a7 id:heading.prefs.network", 0, 0, (const void *) networkPanelItems },
            { "panel text:" person_Icon " ${sidebar.identities}", 0, 0, (const void *) identityPanelItems },
            { "padding" },
            { "panel icon:0x1f4f1 id:heading.prefs.interface", 0, 0, (const void *) uiPanelItems },
            { "panel icon:0x1f3a8 id:heading.prefs.colors", 0, 0, (const void *) colorPanelItems },
            { "panel icon:0x1f5da id:heading.prefs.fonts", 0, 0, (const void *) fontPanelItems },
            { "panel icon:0x1f660 id:heading.prefs.style", 0, 0, (const void *) stylePanelItems },
            { "padding" },
            { "button text:" info_Icon " ${menu.help}", 0, 0, "!open url:about:help" },
            { "padding" },
            { "panel text:" planet_Icon " ${menu.about}", 0, 0, (const void *) aboutPanelItems },
            { NULL }
        }, NULL, 0);
        setupSheetTransition_Mobile(dlg, iTrue);
        return dlg;
    }
    iWidget *dlg = makeSheet_Widget("prefs");
    addChildFlags_Widget(dlg,
                         iClob(new_LabelWidget(uiHeading_ColorEscape "${heading.prefs}", NULL)),
                         frameless_WidgetFlag);
    iWidget *tabs = makeTabs_Widget(dlg);
    setBackgroundColor_Widget(findChild_Widget(tabs, "tabs.buttons"), uiBackgroundSidebar_ColorId);
    setId_Widget(tabs, "prefs.tabs");
    iWidget *headings, *values;
    /* General preferences. */ {
        appendTwoColumnTabPage_Widget(tabs, "${heading.prefs.general}", '1', &headings, &values);
#if defined (LAGRANGE_ENABLE_DOWNLOAD_EDIT)
        addPrefsInputWithHeading_(headings, values, "prefs.downloads", iClob(new_InputWidget(0)));
#endif
        iInputWidget *searchUrl;
        addPrefsInputWithHeading_(headings, values, "prefs.searchurl", iClob(searchUrl = new_InputWidget(0)));
        setUrlContent_InputWidget(searchUrl, iTrue);
        addDialogPadding_(headings, values);
        addDialogToggle_(headings, values, "${prefs.hoverlink}", "prefs.hoverlink");
        addDialogToggle_(headings, values, "${prefs.archive.openindex}", "prefs.archive.openindex");
        if (deviceType_App() != phone_AppDeviceType) {
            addChild_Widget(headings, iClob(makeHeading_Widget("${prefs.pinsplit}")));
            iWidget *pinSplit = new_Widget();
            /* Split mode document pinning. */ {
                addRadioButton_(pinSplit, "prefs.pinsplit.0", "${prefs.pinsplit.none}", "pinsplit.set arg:0");
                addRadioButton_(pinSplit, "prefs.pinsplit.1", "${prefs.pinsplit.left}", "pinsplit.set arg:1");
                addRadioButton_(pinSplit, "prefs.pinsplit.2", "${prefs.pinsplit.right}", "pinsplit.set arg:2");
            }
            addChildFlags_Widget(values, iClob(pinSplit), arrangeHorizontal_WidgetFlag | arrangeSize_WidgetFlag);
        }
        addDialogPadding_(headings, values);
        /* UI languages. */ {
            iArray *uiLangs = collectNew_Array(sizeof(iMenuItem));
            pushBackN_Array(uiLangs, langItems, iElemCount(langItems) - 1);
            /* TODO: Add an arrange flag for resizing parent to widest child. */
            size_t widestPos = findWidestLabel_MenuItem(data_Array(uiLangs), size_Array(uiLangs));
            addChild_Widget(headings, iClob(makeHeading_Widget("${prefs.uilang}")));
            setId_Widget(addChildFlags_Widget(values,
                                              iClob(makeMenuButton_LabelWidget(
                                                  value_Array(uiLangs, widestPos, iMenuItem).label,
                                                  data_Array(uiLangs),
                                                  size_Array(uiLangs))),
                                              alignLeft_WidgetFlag),
                         "prefs.uilang");
        }
    }
    /* User Interface. */ {
        appendTwoColumnTabPage_Widget(tabs, "${heading.prefs.interface}", '2', &headings, &values);
#if defined (LAGRANGE_ENABLE_CUSTOM_FRAME)
        addDialogToggle_(headings, values, "${prefs.customframe}", "prefs.customframe");
#endif
        addChild_Widget(headings, iClob(makeHeading_Widget("${prefs.returnkey}")));
        /* Return key behaviors. */ {
            iLabelWidget *returnKey = makeMenuButton_LabelWidget(
                returnKeyBehaviors[findWidestLabel_MenuItem(returnKeyBehaviors,
                                                        iElemCount(returnKeyBehaviors) - 1)]
                    .label,
                returnKeyBehaviors,
                iElemCount(returnKeyBehaviors) - 1);
            setBackgroundColor_Widget(findChild_Widget(as_Widget(returnKey), "menu"),
                                      uiBackgroundMenu_ColorId);
            setId_Widget(addChildFlags_Widget(values, iClob(returnKey), alignLeft_WidgetFlag),
                         "prefs.returnkey");
        }
        addDialogToggle_(headings, values, "${prefs.animate}", "prefs.animate");
        makeTwoColumnHeading_("${heading.prefs.scrolling}", headings, values);
        addDialogToggle_(headings, values, "${prefs.smoothscroll}", "prefs.smoothscroll");
        /* Scroll speeds. */ {
            for (int type = 0; type < max_ScrollType; type++) {
                const char *typeStr = (type == mouse_ScrollType ? "mouse" : "keyboard");
                addChild_Widget(headings,
                                iClob(makeHeading_Widget(type == mouse_ScrollType
                                                             ? "${prefs.scrollspeed.mouse}"
                                                             : "${prefs.scrollspeed.keyboard}")));
                iWidget *scrollSpeed = new_Widget();
                addRadioButton_(scrollSpeed, format_CStr("prefs.scrollspeed.%s.7",  typeStr), "0", format_CStr("scrollspeed arg:7  type:%d", type));
                addRadioButton_(scrollSpeed, format_CStr("prefs.scrollspeed.%s.10", typeStr), "1", format_CStr("scrollspeed arg:10 type:%d", type));
                addRadioButton_(scrollSpeed, format_CStr("prefs.scrollspeed.%s.13", typeStr), "2", format_CStr("scrollspeed arg:13 type:%d", type));
                addRadioButton_(scrollSpeed, format_CStr("prefs.scrollspeed.%s.17", typeStr), "3", format_CStr("scrollspeed arg:17 type:%d", type));
                addRadioButton_(scrollSpeed, format_CStr("prefs.scrollspeed.%s.23", typeStr), "4", format_CStr("scrollspeed arg:23 type:%d", type));
                addRadioButton_(scrollSpeed, format_CStr("prefs.scrollspeed.%s.30", typeStr), "5", format_CStr("scrollspeed arg:30 type:%d", type));
                addRadioButton_(scrollSpeed, format_CStr("prefs.scrollspeed.%s.40", typeStr), "6", format_CStr("scrollspeed arg:40 type:%d", type));
                addChildFlags_Widget(
                    values, iClob(scrollSpeed), arrangeHorizontal_WidgetFlag | arrangeSize_WidgetFlag);
            }
        }
        addDialogToggle_(headings, values, "${prefs.imageloadscroll}", "prefs.imageloadscroll");
        if (deviceType_App() == phone_AppDeviceType) {
            addDialogToggle_(headings, values, "${prefs.hidetoolbarscroll}", "prefs.hidetoolbarscroll");
        }
        makeTwoColumnHeading_("${heading.prefs.sizing}", headings, values);
        addPrefsInputWithHeading_(headings, values, "prefs.uiscale", iClob(new_InputWidget(8)));
        if (deviceType_App() == desktop_AppDeviceType) {
            addDialogToggle_(headings, values, "${prefs.retainwindow}", "prefs.retainwindow");
        }
    }
    /* Colors. */ {
        appendTwoColumnTabPage_Widget(tabs, "${heading.prefs.colors}", '3', &headings, &values);
        makeTwoColumnHeading_("${heading.prefs.uitheme}", headings, values);
#if defined (iPlatformApple) || defined (iPlatformMSys)
        addDialogToggle_(headings, values, "${prefs.ostheme}", "prefs.ostheme");
#endif
        addChild_Widget(headings, iClob(makeHeading_Widget("${prefs.theme}")));
        iWidget *themes = new_Widget();
        /* Themes. */ {
            setId_Widget(addChild_Widget(themes, iClob(new_LabelWidget("${prefs.theme.black}", "theme.set arg:0"))), "prefs.theme.0");
            setId_Widget(addChild_Widget(themes, iClob(new_LabelWidget("${prefs.theme.dark}", "theme.set arg:1"))), "prefs.theme.1");
            setId_Widget(addChild_Widget(themes, iClob(new_LabelWidget("${prefs.theme.light}", "theme.set arg:2"))), "prefs.theme.2");
            setId_Widget(addChild_Widget(themes, iClob(new_LabelWidget("${prefs.theme.white}", "theme.set arg:3"))), "prefs.theme.3");
        }
        addChildFlags_Widget(values, iClob(themes), arrangeHorizontal_WidgetFlag | arrangeSize_WidgetFlag);
        /* Accents. */
        iWidget *accent = new_Widget(); {
            setId_Widget(addChild_Widget(accent, iClob(new_LabelWidget("${prefs.accent.teal}", "accent.set arg:0"))), "prefs.accent.0");
            setId_Widget(addChild_Widget(accent, iClob(new_LabelWidget("${prefs.accent.orange}", "accent.set arg:1"))), "prefs.accent.1");
        }
        addChild_Widget(headings, iClob(makeHeading_Widget("${prefs.accent}")));
        addChildFlags_Widget(values, iClob(accent), arrangeHorizontal_WidgetFlag | arrangeSize_WidgetFlag);
        makeTwoColumnHeading_("${heading.prefs.pagecontent}", headings, values);
        for (int i = 0; i < 2; ++i) {
            const iBool isDark = (i == 0);
            const char *mode = isDark ? "dark" : "light";
            addChild_Widget(headings, iClob(makeHeading_Widget(isDark ? "${prefs.doctheme.dark}" : "${prefs.doctheme.light}")));
            iLabelWidget *button = makeMenuButton_LabelWidget(
                docThemes[i][findWidestLabel_MenuItem(docThemes[i], max_GmDocumentTheme)].label,
                docThemes[i],
                max_GmDocumentTheme);
            //            setFrameColor_Widget(findChild_Widget(as_Widget(button), "menu"),
            //                                 uiBackgroundSelected_ColorId);
            setBackgroundColor_Widget(findChild_Widget(as_Widget(button), "menu"), uiBackgroundMenu_ColorId);
            setId_Widget(addChildFlags_Widget(values, iClob(button), alignLeft_WidgetFlag),
                         format_CStr("prefs.doctheme.%s", mode));
        }
        addChild_Widget(headings, iClob(makeHeading_Widget("${prefs.saturation}")));
        iWidget *sats = new_Widget();
        /* Saturation levels. */ {
            addRadioButton_(sats, "prefs.saturation.3", "100 %", "saturation.set arg:100");
            addRadioButton_(sats, "prefs.saturation.2", "66 %", "saturation.set arg:66");
            addRadioButton_(sats, "prefs.saturation.1", "33 %", "saturation.set arg:33");
            addRadioButton_(sats, "prefs.saturation.0", "0 %", "saturation.set arg:0");
        }
        addChildFlags_Widget(values, iClob(sats), arrangeHorizontal_WidgetFlag | arrangeSize_WidgetFlag);
        /* Colorize images. */ {
            addChild_Widget(headings, iClob(makeHeading_Widget("${prefs.imagestyle}")));
            iLabelWidget *button = makeMenuButton_LabelWidget(
                imgStyles[findWidestLabel_MenuItem(imgStyles, iElemCount(imgStyles) - 1)].label,
                imgStyles,
                iElemCount(imgStyles) - 1);
            setBackgroundColor_Widget(findChild_Widget(as_Widget(button), "menu"),
                                      uiBackgroundMenu_ColorId);
            setId_Widget(addChildFlags_Widget(values, iClob(button), alignLeft_WidgetFlag),
                         "prefs.imagestyle");
        }
    }
    /* Fonts. */ {
        setId_Widget(appendTwoColumnTabPage_Widget(tabs, "${heading.prefs.fonts}", '4', &headings, &values), "prefs.page.fonts");
        /* Fonts. */ {
            addChild_Widget(headings, iClob(makeHeading_Widget("${prefs.headingfont}")));
            addFontButtons_(values, "headingfont");
            addChild_Widget(headings, iClob(makeHeading_Widget("${prefs.font}")));
            addFontButtons_(values, "font");
            addDialogPadding_(headings, values);
            addChild_Widget(headings, iClob(makeHeading_Widget("${prefs.mono}")));
            iWidget *mono = new_Widget(); {
                iWidget *tog;
                setTextCStr_LabelWidget(
                    addChild_Widget(mono, tog = iClob(makeToggle_Widget("prefs.mono.gemini"))),
                    "${prefs.mono.gemini}");
                setFlags_Widget(tog, fixedWidth_WidgetFlag, iFalse);
                updateSize_LabelWidget((iLabelWidget *) tog);
                setTextCStr_LabelWidget(
                    addChild_Widget(mono, tog = iClob(makeToggle_Widget("prefs.mono.gopher"))),
                    "${prefs.mono.gopher}");
                setFlags_Widget(tog, fixedWidth_WidgetFlag, iFalse);
                updateSize_LabelWidget((iLabelWidget *) tog);
            }
            addChildFlags_Widget(values, iClob(mono), arrangeHorizontal_WidgetFlag | arrangeSize_WidgetFlag);
            addChild_Widget(headings, iClob(makeHeading_Widget("${prefs.boldlink}")));
            iWidget *boldLink = new_Widget(); {
                /* TODO: Add a utility function for this type of toggles? (also for above) */
                iWidget *tog;
                setTextCStr_LabelWidget(
                    addChild_Widget(boldLink, tog = iClob(makeToggle_Widget("prefs.boldlink.dark"))),
                    "${prefs.boldlink.dark}");
                setFlags_Widget(tog, fixedWidth_WidgetFlag, iFalse);
                updateSize_LabelWidget((iLabelWidget *) tog);
                setTextCStr_LabelWidget(
                    addChild_Widget(boldLink, tog = iClob(makeToggle_Widget("prefs.boldlink.light"))),
                    "${prefs.boldlink.light}");
                setFlags_Widget(tog, fixedWidth_WidgetFlag, iFalse);
                updateSize_LabelWidget((iLabelWidget *) tog);
            }
            addChildFlags_Widget(values, iClob(boldLink), arrangeHorizontal_WidgetFlag | arrangeSize_WidgetFlag);
            addDialogPadding_(headings, values);
            /* Custom font. */ {
                iInputWidget *customFont = new_InputWidget(0);
                setHint_InputWidget(customFont, "${hint.prefs.userfont}");
                addPrefsInputWithHeading_(headings, values, "prefs.userfont", iClob(customFont));
            }
        }        
    }
    /* Style. */ {
        setId_Widget(appendTwoColumnTabPage_Widget(tabs, "${heading.prefs.style}", '5', &headings, &values), "prefs.page.style");
//        makeTwoColumnHeading_("${heading.prefs.paragraph}", headings, values);
        addChild_Widget(headings, iClob(makeHeading_Widget("${prefs.linewidth}")));
        iWidget *widths = new_Widget();
        /* Line widths. */ {
            addRadioButton_(widths, "prefs.linewidth.30", "\u20132", "linewidth.set arg:30");
            addRadioButton_(widths, "prefs.linewidth.34", "\u20131", "linewidth.set arg:34");
            addRadioButton_(widths, "prefs.linewidth.38", "${prefs.linewidth.normal}", "linewidth.set arg:38");
            addRadioButton_(widths, "prefs.linewidth.43", "+1", "linewidth.set arg:43");
            addRadioButton_(widths, "prefs.linewidth.48", "+2", "linewidth.set arg:48");
            addRadioButton_(widths, "prefs.linewidth.1000", "${prefs.linewidth.fill}", "linewidth.set arg:1000");
        }
        addChildFlags_Widget(values, iClob(widths), arrangeHorizontal_WidgetFlag | arrangeSize_WidgetFlag);
        addPrefsInputWithHeading_(headings, values, "prefs.linespacing", iClob(new_InputWidget(5)));
        addChild_Widget(headings, iClob(makeHeading_Widget("${prefs.quoteicon}")));
        iWidget *quote = new_Widget(); {
            addRadioButton_(quote, "prefs.quoteicon.1", "${prefs.quoteicon.icon}", "quoteicon.set arg:1");
            addRadioButton_(quote, "prefs.quoteicon.0", "${prefs.quoteicon.line}", "quoteicon.set arg:0");
        }
        addChildFlags_Widget(values, iClob(quote), arrangeHorizontal_WidgetFlag | arrangeSize_WidgetFlag);
        addDialogToggle_(headings, values, "${prefs.biglede}", "prefs.biglede");
        addDialogToggle_(headings, values, "${prefs.plaintext.wrap}", "prefs.plaintext.wrap");
        addDialogToggle_(headings, values, "${prefs.collapsepreonload}", "prefs.collapsepreonload");
        addDialogPadding_(headings, values);
        addDialogToggle_(headings, values, "${prefs.sideicon}", "prefs.sideicon");
        addDialogToggle_(headings, values, "${prefs.centershort}", "prefs.centershort");
    }
    /* Network. */ {
        appendTwoColumnTabPage_Widget(tabs, "${heading.prefs.network}", '6', &headings, &values);
        addChild_Widget(headings, iClob(makeHeading_Widget("${prefs.decodeurls}")));
        addChild_Widget(values, iClob(makeToggle_Widget("prefs.decodeurls")));
        /* Cache size. */ {
            iInputWidget *cache = new_InputWidget(4);
            setSelectAllOnFocus_InputWidget(cache, iTrue);
            addPrefsInputWithHeading_(headings, values, "prefs.cachesize", iClob(cache));
            iWidget *unit =
                addChildFlags_Widget(as_Widget(cache),
                                     iClob(new_LabelWidget("${mb}", NULL)),
                                     frameless_WidgetFlag | moveToParentRightEdge_WidgetFlag |
                                     resizeToParentHeight_WidgetFlag);
            setContentPadding_InputWidget(cache, 0, width_Widget(unit) - 4 * gap_UI);
        }
        /* Memory size. */ {
            iInputWidget *mem = new_InputWidget(4);
            setSelectAllOnFocus_InputWidget(mem, iTrue);
            addPrefsInputWithHeading_(headings, values, "prefs.memorysize", iClob(mem));
            iWidget *unit =
                addChildFlags_Widget(as_Widget(mem),
                                     iClob(new_LabelWidget("${mb}", NULL)),
                                     frameless_WidgetFlag | moveToParentRightEdge_WidgetFlag |
                                         resizeToParentHeight_WidgetFlag);
            setContentPadding_InputWidget(mem, 0, width_Widget(unit) - 4 * gap_UI);
        }
        makeTwoColumnHeading_("${heading.prefs.certs}", headings, values);
        addPrefsInputWithHeading_(headings, values, "prefs.ca.file", iClob(new_InputWidget(0)));
        addPrefsInputWithHeading_(headings, values, "prefs.ca.path", iClob(new_InputWidget(0)));
        makeTwoColumnHeading_("${heading.prefs.proxies}", headings, values);
        addPrefsInputWithHeading_(headings, values, "prefs.proxy.gemini", iClob(new_InputWidget(0)));
        addPrefsInputWithHeading_(headings, values, "prefs.proxy.gopher", iClob(new_InputWidget(0)));
        addPrefsInputWithHeading_(headings, values, "prefs.proxy.http", iClob(new_InputWidget(0)));
    }
    /* Keybindings. */
    if (deviceType_App() == desktop_AppDeviceType) {
        iBindingsWidget *bind = new_BindingsWidget();
        appendFramelessTabPage_Widget(tabs, iClob(bind), "${heading.prefs.keys}", '7', KMOD_PRIMARY);
    }
    addChild_Widget(dlg, iClob(makePadding_Widget(gap_UI)));
    updatePreferencesLayout_Widget(dlg);
    addChild_Widget(dlg,
                    iClob(makeDialogButtons_Widget(
                        (iMenuItem[]){ { "${close}", SDLK_ESCAPE, 0, "prefs.dismiss" } }, 1)));
    addChild_Widget(dlg->root->widget, iClob(dlg));
//    finalizeSheet_Mobile(dlg);
//    arrange_Widget(dlg);
    setupSheetTransition_Mobile(dlg, iTrue);
//    printTree_Widget(dlg);
    return dlg;
}

iWidget *makeBookmarkEditor_Widget(void) {
    const iMenuItem actions[] = {
        { "${cancel}" },
        { uiTextCaution_ColorEscape "${dlg.bookmark.save}", SDLK_RETURN, KMOD_PRIMARY, "bmed.accept" }
    };
    if (isUsingPanelLayout_Mobile()) {
        const iMenuItem items[] = {
            { "title id:bmed.heading text:${heading.bookmark.edit}" },
            { "heading id:dlg.bookmark.url" },
            { "input id:bmed.url url:1 noheading:1" },
            { "padding" },
            { "input id:bmed.title text:${dlg.bookmark.title}" },
            { "input id:bmed.tags text:${dlg.bookmark.tags}" },
            { "input id:bmed.icon maxlen:1 text:${dlg.bookmark.icon}" },
            { "heading text:${heading.bookmark.tags}" },
            { "toggle id:bmed.tag.home text:${bookmark.tag.home}" },
            { "toggle id:bmed.tag.remote text:${bookmark.tag.remote}" },
            { "toggle id:bmed.tag.linksplit text:${bookmark.tag.linksplit}" },
            { NULL }
        };
        iWidget *dlg = makePanels_Mobile("bmed", items, actions, iElemCount(actions));
        setupSheetTransition_Mobile(dlg, iTrue);
        return dlg;
    }
    iWidget *dlg = makeSheet_Widget("bmed");
    setId_Widget(addChildFlags_Widget(
                     dlg,
                     iClob(new_LabelWidget(uiHeading_ColorEscape "${heading.bookmark.edit}", NULL)),
                     frameless_WidgetFlag),
                 "bmed.heading");
    iWidget *headings, *values;
    addChild_Widget(dlg, iClob(makeTwoColumns_Widget(&headings, &values)));
    iInputWidget *inputs[4];
    addDialogInputWithHeading_(headings, values, "${dlg.bookmark.title}", "bmed.title", iClob(inputs[0] = new_InputWidget(0)));
    addDialogInputWithHeading_(headings, values, "${dlg.bookmark.url}",   "bmed.url",   iClob(inputs[1] = new_InputWidget(0)));
    setUrlContent_InputWidget(inputs[1], iTrue);
    addDialogInputWithHeading_(headings, values, "${dlg.bookmark.tags}",  "bmed.tags",  iClob(inputs[2] = new_InputWidget(0)));
    addDialogInputWithHeading_(headings, values, "${dlg.bookmark.icon}",  "bmed.icon",  iClob(inputs[3] = new_InputWidget(1)));
    /* Buttons for special tags. */
    addChild_Widget(dlg, iClob(makePadding_Widget(gap_UI)));
    addChild_Widget(dlg, iClob(makeTwoColumns_Widget(&headings, &values)));
    makeTwoColumnHeading_("${heading.bookmark.tags}", headings, values);
    addDialogToggle_(headings, values, "${bookmark.tag.home}", "bmed.tag.home");
    addDialogToggle_(headings, values, "${bookmark.tag.remote}", "bmed.tag.remote");
    addDialogToggle_(headings, values, "${bookmark.tag.linksplit}", "bmed.tag.linksplit");
    arrange_Widget(dlg);
    for (int i = 0; i < 3; ++i) {
        as_Widget(inputs[i])->rect.size.x = 100 * gap_UI - headings->rect.size.x;
    }
    addChild_Widget(dlg, iClob(makePadding_Widget(gap_UI)));
    addChild_Widget(dlg, iClob(makeDialogButtons_Widget(actions, iElemCount(actions))));
    addChild_Widget(get_Root()->widget, iClob(dlg));
    setupSheetTransition_Mobile(dlg, iTrue);
    return dlg;
}

static iBool handleBookmarkCreationCommands_SidebarWidget_(iWidget *editor, const char *cmd) {
    if (equal_Command(cmd, "bmed.accept") || equal_Command(cmd, "cancel")) {
        if (equal_Command(cmd, "bmed.accept")) {
            const iString *title = text_InputWidget(findChild_Widget(editor, "bmed.title"));
            const iString *url   = text_InputWidget(findChild_Widget(editor, "bmed.url"));
            const iString *tags  = text_InputWidget(findChild_Widget(editor, "bmed.tags"));
            const iString *icon  = collect_String(trimmed_String(text_InputWidget(findChild_Widget(editor, "bmed.icon"))));
            const uint32_t id    = add_Bookmarks(bookmarks_App(), url, title, tags, first_String(icon));
            iBookmark *    bm    = get_Bookmarks(bookmarks_App(), id);
            if (!isEmpty_String(icon)) {
                addTagIfMissing_Bookmark(bm, userIcon_BookmarkTag);
            }
            if (isSelected_Widget(findChild_Widget(editor, "bmed.tag.home"))) {
                addTag_Bookmark(bm, homepage_BookmarkTag);
            }
            if (isSelected_Widget(findChild_Widget(editor, "bmed.tag.remote"))) {
                addTag_Bookmark(bm, remoteSource_BookmarkTag);
            }
            if (isSelected_Widget(findChild_Widget(editor, "bmed.tag.linksplit"))) {
                addTag_Bookmark(bm, linkSplit_BookmarkTag);
            }
            postCommand_App("bookmarks.changed");
        }
        setupSheetTransition_Mobile(editor, iFalse);
        destroy_Widget(editor);
        return iTrue;
    }
    return iFalse;
}

iWidget *makeBookmarkCreation_Widget(const iString *url, const iString *title, iChar icon) {
    iWidget *dlg = makeBookmarkEditor_Widget();
    setId_Widget(dlg, "bmed.create");
    setTextCStr_LabelWidget(findChild_Widget(dlg, "bmed.heading"),
                            uiHeading_ColorEscape "${heading.bookmark.add}");
    iUrl parts;
    init_Url(&parts, url);
    setTextCStr_InputWidget(findChild_Widget(dlg, "bmed.title"),
                            title ? cstr_String(title) : cstr_Rangecc(parts.host));
    setText_InputWidget(findChild_Widget(dlg, "bmed.url"), url);
    setId_Widget(
        addChildFlags_Widget(
            dlg,
            iClob(new_LabelWidget(cstrCollect_String(newUnicodeN_String(&icon, 1)), NULL)),
            collapse_WidgetFlag | hidden_WidgetFlag | disabled_WidgetFlag),
        "bmed.icon");
    setCommandHandler_Widget(dlg, handleBookmarkCreationCommands_SidebarWidget_);
    return dlg;
}

static iBool handleFeedSettingCommands_(iWidget *dlg, const char *cmd) {
    if (equal_Command(cmd, "cancel")) {
        setupSheetTransition_Mobile(dlg, iFalse);
        destroy_Widget(dlg);
        return iTrue;
    }
    if (equal_Command(cmd, "feedcfg.accept")) {
        iString *feedTitle =
            collect_String(copy_String(text_InputWidget(findChild_Widget(dlg, "feedcfg.title"))));
        trim_String(feedTitle);
        if (isEmpty_String(feedTitle)) {
            return iTrue;
        }
        int id = argLabel_Command(cmd, "bmid");
        const iBool headings = isSelected_Widget(findChild_Widget(dlg, "feedcfg.type.headings"));
        const iString *tags = collectNewFormat_String("subscribed%s", headings ? " headings" : "");
        if (!id) {
            const size_t numSubs = numSubscribed_Feeds();
            const iString *url   = url_DocumentWidget(document_App());
            add_Bookmarks(bookmarks_App(),
                          url,
                          feedTitle,
                          tags,
                          siteIcon_GmDocument(document_DocumentWidget(document_App())));
            if (numSubs == 0) {
                /* Auto-refresh after first addition. */
                postCommand_App("feeds.refresh");
            }
        }
        else {
            iBookmark *bm = get_Bookmarks(bookmarks_App(), id);
            if (bm) {
                set_String(&bm->title, feedTitle);
                set_String(&bm->tags, tags);
            }
        }
        postCommand_App("bookmarks.changed");
        setupSheetTransition_Mobile(dlg, iFalse);
        destroy_Widget(dlg);
        return iTrue;
    }
    return iFalse;
}

iWidget *makeFeedSettings_Widget(uint32_t bookmarkId) {
    const char *headingText = bookmarkId ? uiHeading_ColorEscape "${heading.feedcfg}"
                                         : uiHeading_ColorEscape "${heading.subscribe}";
    const iMenuItem actions[] = { { "${cancel}" },
                                  { bookmarkId ? uiTextCaution_ColorEscape "${dlg.feed.save}"
                                               : uiTextCaution_ColorEscape "${dlg.feed.sub}",
                                    SDLK_RETURN,
                                    KMOD_PRIMARY,
                                    format_CStr("feedcfg.accept bmid:%d", bookmarkId) } };
    iWidget *dlg;
    if (isUsingPanelLayout_Mobile()) {
        const iMenuItem typeItems[] = {
            { "button id:feedcfg.type.gemini label:dlg.feed.type.gemini", 0, 0, "feedcfg.type arg:0" },
            { "button id:feedcfg.type.headings label:dlg.feed.type.headings", 0, 0, "feedcfg.type arg:1" },
            { NULL }
        };
        dlg = makePanels_Mobile("feedcfg", (iMenuItem[]){
            { format_CStr("title id:feedcfg.heading text:%s", headingText) },
            { "input id:feedcfg.title text:${dlg.feed.title}" },
            { "radio id:dlg.feed.entrytype", 0, 0, (const void *) typeItems },
            { NULL }
        }, actions, iElemCount(actions));
    }
    else {
        dlg = makeSheet_Widget("feedcfg");
        setId_Widget(
            addChildFlags_Widget(dlg, iClob(new_LabelWidget(headingText, NULL)), frameless_WidgetFlag),
            "feedcfg.heading");
        iWidget *headings, *values;
        addChild_Widget(dlg, iClob(makeTwoColumns_Widget(&headings, &values)));
        iInputWidget *input = new_InputWidget(0);
        addDialogInputWithHeading_(headings, values, "${dlg.feed.title}", "feedcfg.title", iClob(input));
        addChild_Widget(headings, iClob(makeHeading_Widget("${dlg.feed.entrytype}")));
        iWidget *types = new_Widget(); {
            addRadioButton_(types, "feedcfg.type.gemini", "${dlg.feed.type.gemini}", "feedcfg.type arg:0");
            addRadioButton_(types, "feedcfg.type.headings", "${dlg.feed.type.headings}", "feedcfg.type arg:1");
        }
        addChildFlags_Widget(values, iClob(types), arrangeHorizontal_WidgetFlag | arrangeSize_WidgetFlag);
        iWidget *buttons =
            addChild_Widget(dlg, iClob(makeDialogButtons_Widget(actions, iElemCount(actions))));
        setId_Widget(child_Widget(buttons, childCount_Widget(buttons) - 1), "feedcfg.save");
        arrange_Widget(dlg);
        as_Widget(input)->rect.size.x = 100 * gap_UI - headings->rect.size.x;
        addChild_Widget(get_Root()->widget, iClob(dlg));
//        finalizeSheet_Mobile(dlg);
    }
    /* Initialize. */ {
        const iBookmark *bm  = bookmarkId ? get_Bookmarks(bookmarks_App(), bookmarkId) : NULL;
        setText_InputWidget(findChild_Widget(dlg, "feedcfg.title"),
                            bm ? &bm->title : feedTitle_DocumentWidget(document_App()));
        setFlags_Widget(findChild_Widget(dlg,
                                         hasTag_Bookmark(bm, headings_BookmarkTag)
                                             ? "feedcfg.type.headings"
                                             : "feedcfg.type.gemini"),
                        selected_WidgetFlag,
                        iTrue);
        setCommandHandler_Widget(dlg, handleFeedSettingCommands_);
    }
    setupSheetTransition_Mobile(dlg, incoming_TransitionFlag);
    return dlg;
}

iWidget *makeIdentityCreation_Widget(void) {
    const iMenuItem actions[] = { { "${dlg.newident.more}", 0, 0, "ident.showmore" },
                                  { "---" },
                                  { "${cancel}", SDLK_ESCAPE, 0, "ident.cancel" },
                                  { uiTextAction_ColorEscape "${dlg.newident.create}",
                                    SDLK_RETURN,
                                    KMOD_PRIMARY,
                                    "ident.accept" } };
    iUrl url;
    init_Url(&url, url_DocumentWidget(document_App()));
    const iMenuItem scopeItems[] = {
        { format_CStr("${dlg.newident.scope.domain}:\n%s", cstr_Rangecc(url.host)), 0, 0, "ident.scope arg:0" },
        { format_CStr("${dlg.newident.scope.page}:\n%s", cstr_Rangecc(url.path)), 0, 0, "ident.scope arg:1" },
        { "${dlg.newident.scope.none}", 0, 0, "ident.scope arg:2" },
        { NULL }
    };
    iWidget *dlg;
    if (isUsingPanelLayout_Mobile()) {
        dlg = makePanels_Mobile("ident", (iMenuItem[]){
            { "title id:ident.heading text:${heading.newident}" },
            { "label text:${dlg.newident.rsa.selfsign}" },
            { "dropdown id:ident.scope text:${dlg.newident.scope}", 0, 0,
              (const void *) scopeItems },
            { "input id:ident.until hint:hint.newident.date maxlen:19 text:${dlg.newident.until}" },
            //{ "padding" },
            //{ "toggle id:ident.temp text:${dlg.newident.temp}" },
            //{ "label text:${help.ident.temp}" },
            { "heading id:dlg.newident.commonname" },
            { "input id:ident.common noheading:1" },
            { "padding collapse:1" },
            { "input collapse:1 id:ident.email hint:hint.newident.optional text:${dlg.newident.email}" },
            { "input collapse:1 id:ident.userid hint:hint.newident.optional text:${dlg.newident.userid}" },
            { "input collapse:1 id:ident.domain hint:hint.newident.optional text:${dlg.newident.domain}" },
            { "input collapse:1 id:ident.org hint:hint.newident.optional text:${dlg.newident.org}" },
            { "input collapse:1 id:ident.country hint:hint.newident.optional text:${dlg.newident.country}" },
            { NULL }
        }, actions, iElemCount(actions));
    }
    else {
        dlg = makeSheet_Widget("ident");
        setId_Widget(addChildFlags_Widget(
                         dlg,
                         iClob(new_LabelWidget(uiHeading_ColorEscape "${heading.newident}", NULL)),
                         frameless_WidgetFlag),
                     "ident.heading");
        iWidget *page = new_Widget();
        addChildFlags_Widget(
            dlg, iClob(new_LabelWidget("${dlg.newident.rsa.selfsign}", NULL)), frameless_WidgetFlag);
        /* TODO: Use makeTwoColumnWidget_? */
        addChild_Widget(dlg, iClob(page));
        setFlags_Widget(page, arrangeHorizontal_WidgetFlag | arrangeSize_WidgetFlag, iTrue);
        iWidget *headings = addChildFlags_Widget(
            page, iClob(new_Widget()), arrangeVertical_WidgetFlag | arrangeSize_WidgetFlag);
        iWidget *values = addChildFlags_Widget(
            page, iClob(new_Widget()), arrangeVertical_WidgetFlag | arrangeSize_WidgetFlag);
        setId_Widget(headings, "headings");
        setId_Widget(values, "values");
        iInputWidget *inputs[6];
        /* Where will the new identity be active on? */ {
            iWidget *head = addChild_Widget(headings, iClob(makeHeading_Widget("${dlg.newident.scope}")));
            iWidget *val;
            setId_Widget(
                addChild_Widget(values,
                                val = iClob(makeMenuButton_LabelWidget(
                                    scopeItems[0].label, scopeItems, iElemCount(scopeItems)))),
                "ident.scope");
            head->sizeRef = val;
        }
        addDialogInputWithHeading_(headings,
                                   values,
                                   "${dlg.newident.until}",
                                   "ident.until",
                                   iClob(newHint_InputWidget(19, "${hint.newident.date}")));
        addDialogInputWithHeading_(headings,
                                   values,
                                   "${dlg.newident.commonname}",
                                   "ident.common",
                                   iClob(inputs[0] = new_InputWidget(0)));
        /* Temporary? */ {
            addChild_Widget(headings, iClob(makeHeading_Widget("${dlg.newident.temp}")));
            iWidget *tmpGroup = new_Widget();
            setFlags_Widget(tmpGroup, arrangeSize_WidgetFlag | arrangeHorizontal_WidgetFlag, iTrue);
            addChild_Widget(tmpGroup, iClob(makeToggle_Widget("ident.temp")));
            setId_Widget(
                addChildFlags_Widget(tmpGroup,
                                     iClob(new_LabelWidget(uiTextCaution_ColorEscape warning_Icon
                                                           "  ${dlg.newident.notsaved}",
                                                           NULL)),
                                     hidden_WidgetFlag | frameless_WidgetFlag),
                "ident.temp.note");
            addChild_Widget(values, iClob(tmpGroup));
        }
        addChildFlags_Widget(headings, iClob(makePadding_Widget(gap_UI)), collapse_WidgetFlag | hidden_WidgetFlag);
        addChildFlags_Widget(values, iClob(makePadding_Widget(gap_UI)), collapse_WidgetFlag | hidden_WidgetFlag);
        addDialogInputWithHeadingAndFlags_(headings, values, "${dlg.newident.email}",   "ident.email",   iClob(inputs[1] = newHint_InputWidget(0, "${hint.newident.optional}")), collapse_WidgetFlag | hidden_WidgetFlag);
        addDialogInputWithHeadingAndFlags_(headings, values, "${dlg.newident.userid}",  "ident.userid",  iClob(inputs[2] = newHint_InputWidget(0, "${hint.newident.optional}")), collapse_WidgetFlag | hidden_WidgetFlag);
        addDialogInputWithHeadingAndFlags_(headings, values, "${dlg.newident.domain}",  "ident.domain",  iClob(inputs[3] = newHint_InputWidget(0, "${hint.newident.optional}")), collapse_WidgetFlag | hidden_WidgetFlag);
        addDialogInputWithHeadingAndFlags_(headings, values, "${dlg.newident.org}",     "ident.org",     iClob(inputs[4] = newHint_InputWidget(0, "${hint.newident.optional}")), collapse_WidgetFlag | hidden_WidgetFlag);
        addDialogInputWithHeadingAndFlags_(headings, values, "${dlg.newident.country}", "ident.country", iClob(inputs[5] = newHint_InputWidget(0, "${hint.newident.optional}")), collapse_WidgetFlag | hidden_WidgetFlag);
        arrange_Widget(dlg);
        for (size_t i = 0; i < iElemCount(inputs); ++i) {
            as_Widget(inputs[i])->rect.size.x = 100 * gap_UI - headings->rect.size.x;
        }
        addChild_Widget(dlg, iClob(makeDialogButtons_Widget(actions, iElemCount(actions))));
        addChild_Widget(get_Root()->widget, iClob(dlg));
    }
    setupSheetTransition_Mobile(dlg, iTrue);
    return dlg;
}

static const iMenuItem languages[] = {
    { "${lang.ar}", 0, 0, "xlt.lang id:ar" },
    { "${lang.zh}", 0, 0, "xlt.lang id:zh" },
    { "${lang.en}", 0, 0, "xlt.lang id:en" },
    { "${lang.fr}", 0, 0, "xlt.lang id:fr" },
    { "${lang.de}", 0, 0, "xlt.lang id:de" },
    { "${lang.hi}", 0, 0, "xlt.lang id:hi" },
    { "${lang.it}", 0, 0, "xlt.lang id:it" },
    { "${lang.ja}", 0, 0, "xlt.lang id:ja" },
    { "${lang.pt}", 0, 0, "xlt.lang id:pt" },
    { "${lang.ru}", 0, 0, "xlt.lang id:ru" },
    { "${lang.es}", 0, 0, "xlt.lang id:es" },
    { NULL }
};

static iBool translationHandler_(iWidget *dlg, const char *cmd) {
    iUnused(dlg);
    if (equal_Command(cmd, "xlt.lang")) {
        const iMenuItem *langItem = &languages[languageIndex_CStr(cstr_Rangecc(range_Command(cmd, "id")))];
        iWidget *widget = pointer_Command(cmd);
        iLabelWidget *drop;
        if (flags_Widget(widget) & nativeMenu_WidgetFlag) {
            drop = (iLabelWidget *) parent_Widget(widget);
        }
        else {
            drop = (iLabelWidget *) parent_Widget(parent_Widget(widget));
        }
        iAssert(isInstance_Object(drop, &Class_LabelWidget));
        updateDropdownSelection_LabelWidget(drop, langItem->command);
        return iTrue;
    }
    return iFalse;
}

const char *languageId_String(const iString *menuItemLabel) {
    iForIndices(i, languages) {
        if (!languages[i].label) break;
        if (!cmp_String(menuItemLabel, translateCStr_Lang(languages[i].label))) {
            return cstr_Rangecc(range_Command(languages[i].command, "id"));
        }
    }
    return "";
}

int languageIndex_CStr(const char *langId) {
    iForIndices(i, languages) {
        if (!languages[i].label) break;
        if (equal_Rangecc(range_Command(languages[i].command, "id"), langId)) {
            return (int) i;
        }
    }
    return -1;
}

iWidget *makeTranslation_Widget(iWidget *parent) {
    const iMenuItem actions[] = {
        { "${cancel}", SDLK_ESCAPE, 0, "translation.cancel" },
        { uiTextAction_ColorEscape "${dlg.translate}", SDLK_RETURN, 0, "translation.submit" }                                   
    };
    iWidget *dlg;
    if (isUsingPanelLayout_Mobile()) {
        dlg = makePanelsParent_Mobile(parent, "xlt", (iMenuItem[]){
            { "title id:heading.translate" },
            { "dropdown id:xlt.from text:${dlg.translate.from}", 0, 0, (const void *) languages },
            { "dropdown id:xlt.to text:${dlg.translate.to}",     0, 0, (const void *) languages },
            { NULL }                              
        }, actions, iElemCount(actions));
    }
    else {
        dlg = makeSheet_Widget("xlt");
        setFlags_Widget(dlg, keepOnTop_WidgetFlag, iFalse);
        dlg->minSize.x = 70 * gap_UI;
        addChildFlags_Widget(
            dlg,
            iClob(new_LabelWidget(uiHeading_ColorEscape "${heading.translate}", NULL)),
            frameless_WidgetFlag);
        addChild_Widget(dlg, iClob(makePadding_Widget(lineHeight_Text(uiLabel_FontId))));
        iWidget *headings, *values;
        iWidget *page;
        addChild_Widget(dlg, iClob(page = makeTwoColumns_Widget(&headings, &values)));
        setId_Widget(page, "xlt.langs");
        iLabelWidget *fromLang, *toLang;
        const size_t numLangs = iElemCount(languages) - 1;
        const char *widestLabel = languages[findWidestLabel_MenuItem(languages, numLangs)].label;
        /* Source language. */ {
            addChild_Widget(headings, iClob(makeHeading_Widget("${dlg.translate.from}")));
            setId_Widget(addChildFlags_Widget(values,
                                              iClob(fromLang = makeMenuButton_LabelWidget(
                                                        widestLabel, languages, numLangs)),
                                              alignLeft_WidgetFlag),
                         "xlt.from");
            setBackgroundColor_Widget(findChild_Widget(as_Widget(fromLang), "menu"),
                                      uiBackgroundMenu_ColorId);
        }
        /* Target language. */ {
            addChild_Widget(headings, iClob(makeHeading_Widget("${dlg.translate.to}")));
            setId_Widget(addChildFlags_Widget(values,
                                              iClob(toLang = makeMenuButton_LabelWidget(
                                                        widestLabel, languages, numLangs)),
                                              alignLeft_WidgetFlag),
                         "xlt.to");
            setBackgroundColor_Widget(findChild_Widget(as_Widget(toLang), "menu"),
                                      uiBackgroundMenu_ColorId);
        }
        addChild_Widget(dlg, iClob(makePadding_Widget(lineHeight_Text(uiLabel_FontId))));
        addChild_Widget(dlg, iClob(makeDialogButtons_Widget(actions, iElemCount(actions))));
        addChild_Widget(parent, iClob(dlg));
        arrange_Widget(dlg);
    }
    /* Update choices. */
    updateDropdownSelection_LabelWidget(findChild_Widget(dlg, "xlt.from"),
                                        languages[prefs_App()->langFrom].command);
    updateDropdownSelection_LabelWidget(findChild_Widget(dlg, "xlt.to"),
                                        languages[prefs_App()->langTo].command);
//    updateText_LabelWidget(
//        findChild_Widget(dlg, "xlt.from"),
//        text_LabelWidget(child_Widget(findChild_Widget(findChild_Widget(dlg, "xlt.from"), "menu"),
//                                      prefs_App()->langFrom)));
//    updateText_LabelWidget(
//        findChild_Widget(dlg, "xlt.to"),
//        text_LabelWidget(child_Widget(findChild_Widget(findChild_Widget(dlg, "xlt.to"), "menu"),
//                                      prefs_App()->langTo)));
    setCommandHandler_Widget(dlg, translationHandler_);
    setupSheetTransition_Mobile(dlg, iTrue);
    return dlg;
}