File: render.c

package info (click to toggle)
foot 1.25.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 3,108 kB
  • sloc: ansic: 41,260; python: 474; sh: 181; xml: 57; makefile: 18
file content (5454 lines) | stat: -rw-r--r-- 186,183 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
#include "render.h"

#include <limits.h>
#include <signal.h>
#include <string.h>
#include <unistd.h>

#include <sys/ioctl.h>
#include <sys/time.h>
#include <sys/timerfd.h>
#include <sys/epoll.h>
#include <pthread.h>

#include "macros.h"
#if HAS_INCLUDE(<pthread_np.h>)
 #include <pthread_np.h>
 #define pthread_setname_np(thread, name) (pthread_set_name_np(thread, name), 0)
#elif defined(__NetBSD__)
 #define pthread_setname_np(thread, name) pthread_setname_np(thread, "%s", (void *)name)
#endif

#include <presentation-time.h>
#include <wayland-cursor.h>
#include <xdg-shell.h>
#include <xdg-toplevel-icon-v1.h>

#include <fcft/fcft.h>

#define LOG_MODULE "render"
#define LOG_ENABLE_DBG 0
#include "log.h"
#include "box-drawing.h"
#include "char32.h"
#include "config.h"
#include "cursor-shape.h"
#include "grid.h"
#include "ime.h"
#include "quirks.h"
#include "search.h"
#include "selection.h"
#include "shm.h"
#include "sixel.h"
#include "srgb.h"
#include "url-mode.h"
#include "util.h"
#include "xmalloc.h"

#define TIME_SCROLL_DAMAGE 0

struct renderer {
    struct fdm *fdm;
    struct wayland *wayl;
};

static struct {
    size_t total;
    size_t zero;  /* commits presented in less than one frame interval */
    size_t one;   /* commits presented in one frame interval */
    size_t two;   /* commits presented in two or more frame intervals */
} presentation_statistics = {0};

static void fdm_hook_refresh_pending_terminals(struct fdm *fdm, void *data);

struct renderer *
render_init(struct fdm *fdm, struct wayland *wayl)
{
    struct renderer *renderer = malloc(sizeof(*renderer));
    if (unlikely(renderer == NULL)) {
        LOG_ERRNO("malloc() failed");
        return NULL;
    }

    *renderer = (struct renderer) {
        .fdm = fdm,
        .wayl = wayl,
    };

    if (!fdm_hook_add(fdm, &fdm_hook_refresh_pending_terminals, renderer,
                      FDM_HOOK_PRIORITY_NORMAL))
    {
        LOG_ERR("failed to register FDM hook");
        free(renderer);
        return NULL;
    }

    return renderer;
}

void
render_destroy(struct renderer *renderer)
{
    if (renderer == NULL)
        return;

    fdm_hook_del(renderer->fdm, &fdm_hook_refresh_pending_terminals,
                 FDM_HOOK_PRIORITY_NORMAL);

    free(renderer);
}

static void DESTRUCTOR
log_presentation_statistics(void)
{
    if (presentation_statistics.total == 0)
        return;

    const size_t total = presentation_statistics.total;
    LOG_INFO("presentation statistics: zero=%f%%, one=%f%%, two=%f%%",
             100. * presentation_statistics.zero / total,
             100. * presentation_statistics.one / total,
             100. * presentation_statistics.two / total);
}

static void
sync_output(void *data,
            struct wp_presentation_feedback *wp_presentation_feedback,
            struct wl_output *output)
{
}

struct presentation_context {
    struct terminal *term;
    struct timeval input;
    struct timeval commit;
};

static void
presented(void *data,
          struct wp_presentation_feedback *wp_presentation_feedback,
          uint32_t tv_sec_hi, uint32_t tv_sec_lo, uint32_t tv_nsec,
          uint32_t refresh, uint32_t seq_hi, uint32_t seq_lo, uint32_t flags)
{
    struct presentation_context *ctx = data;
    struct terminal *term = ctx->term;
    const struct timeval *input = &ctx->input;
    const struct timeval *commit = &ctx->commit;

    const struct timeval presented = {
        .tv_sec = (uint64_t)tv_sec_hi << 32 | tv_sec_lo,
        .tv_usec = tv_nsec / 1000,
    };

    bool use_input = (input->tv_sec > 0 || input->tv_usec > 0) &&
        timercmp(&presented, input, >);
    char msg[1024];
    int chars = 0;

    if (use_input && timercmp(&presented, input, <))
        return;
    else if (timercmp(&presented, commit, <))
        return;

    LOG_DBG("commit: %lu s %lu µs, presented: %lu s %lu µs",
            commit->tv_sec, commit->tv_usec, presented.tv_sec, presented.tv_usec);

    if (use_input) {
        struct timeval diff;
        timersub(commit, input, &diff);
        chars += snprintf(
            &msg[chars], sizeof(msg) - chars,
            "input - %llu µs -> ", (unsigned long long)diff.tv_usec);
    }

    struct timeval diff;
    timersub(&presented, commit, &diff);
    chars += snprintf(
        &msg[chars], sizeof(msg) - chars,
        "commit - %llu µs -> ", (unsigned long long)diff.tv_usec);

    if (use_input) {
        xassert(timercmp(&presented, input, >));
        timersub(&presented, input, &diff);
    } else {
        xassert(timercmp(&presented, commit, >));
        timersub(&presented, commit, &diff);
    }

    chars += snprintf(
        &msg[chars], sizeof(msg) - chars,
        "presented (total: %llu µs)", (unsigned long long)diff.tv_usec);

    unsigned frame_count = 0;
    if (tll_length(term->window->on_outputs) > 0) {
        const struct monitor *mon = tll_front(term->window->on_outputs);
        frame_count = (diff.tv_sec * 1000000. + diff.tv_usec) / (1000000. / mon->refresh);
    }

    presentation_statistics.total++;
    if (frame_count >= 2)
        presentation_statistics.two++;
    else if (frame_count >= 1)
        presentation_statistics.one++;
    else
        presentation_statistics.zero++;

#define _log_fmt "%s (more than %u frames)"

    if (frame_count >= 2)
        LOG_ERR(_log_fmt, msg, frame_count);
    else if (frame_count >= 1)
        LOG_WARN(_log_fmt, msg, frame_count);
    else
        LOG_INFO(_log_fmt, msg, frame_count);

#undef _log_fmt

    wp_presentation_feedback_destroy(wp_presentation_feedback);
    free(ctx);
}

static void
discarded(void *data, struct wp_presentation_feedback *wp_presentation_feedback)
{
    struct presentation_context *ctx = data;
    wp_presentation_feedback_destroy(wp_presentation_feedback);
    free(ctx);
}

static const struct wp_presentation_feedback_listener presentation_feedback_listener = {
    .sync_output = &sync_output,
    .presented = &presented,
    .discarded = &discarded,
};

static struct fcft_font *
attrs_to_font(const struct terminal *term, const struct attributes *attrs)
{
    int idx = attrs->italic << 1 | attrs->bold;
    return term->fonts[idx];
}

static pixman_color_t
color_hex_to_pixman_srgb(uint32_t color, uint16_t alpha)
{
    return (pixman_color_t){
        .alpha = alpha,  /* Consider alpha linear already? */
        .red = srgb_decode_8_to_16((color >> 16) & 0xff),
        .green = srgb_decode_8_to_16((color >> 8) & 0xff),
        .blue = srgb_decode_8_to_16((color >> 0) & 0xff),
    };
}

static inline pixman_color_t
color_hex_to_pixman_with_alpha(uint32_t color, uint16_t alpha, bool srgb)
{
    pixman_color_t ret;

    if (srgb)
        ret = color_hex_to_pixman_srgb(color, alpha);
    else {
        ret = (pixman_color_t){
            .red =   ((color >> 16 & 0xff) | (color >> 8 & 0xff00)),
            .green = ((color >>  8 & 0xff) | (color >> 0 & 0xff00)),
            .blue =  ((color >>  0 & 0xff) | (color << 8 & 0xff00)),
            .alpha = alpha,
            };
    }

    ret.red = (uint32_t)ret.red * alpha / 0xffff;
    ret.green = (uint32_t)ret.green * alpha / 0xffff;
    ret.blue = (uint32_t)ret.blue * alpha / 0xffff;

    return ret;
}

static inline pixman_color_t
color_hex_to_pixman(uint32_t color, bool srgb)
{
    /* Count on the compiler optimizing this */
    return color_hex_to_pixman_with_alpha(color, 0xffff, srgb);
}

static inline int i_lerp(int from, int to, float t) {
    return from + (to - from) * t;
}

static inline uint32_t
color_blend_towards(uint32_t from, uint32_t to, float amount)
{
    if (unlikely(amount == 0))
        return from;
    float t = 1 - 1/amount;

    uint32_t alpha = from & 0xff000000;
    uint8_t r = i_lerp((from>>16)&0xff, (to>>16)&0xff, t);
    uint8_t g = i_lerp((from>>8)&0xff, (to>>8)&0xff, t);
    uint8_t b = i_lerp((from>>0)&0xff, (to>>0)&0xff, t);

    return alpha | (r<<16) | (g<<8) | (b<<0);
}

static inline uint32_t
color_dim(const struct terminal *term, uint32_t color)
{
    const struct config *conf = term->conf;
    const uint8_t custom_dim = conf->colors.use_custom.dim;

    if (unlikely(custom_dim != 0)) {
        for (size_t i = 0; i < 8; i++) {
            if (((custom_dim >> i) & 1) == 0)
                continue;

            if (term->colors.table[0 + i] == color) {
                /* "Regular" color, return the corresponding "dim" */
                return conf->colors.dim[i];
            }

            else if (term->colors.table[8 + i] == color) {
                /* "Bright" color, return the corresponding "regular" */
                return term->colors.table[i];
            }
        }
    }

    const struct color_theme *theme = term->colors.active_theme == COLOR_THEME1
        ? &conf->colors
        : &conf->colors2;

    return color_blend_towards(
        color,
        theme->dim_blend_towards == DIM_BLEND_TOWARDS_BLACK ? 0x00000000 : 0x00ffffff,
        conf->dim.amount);
}

static inline uint32_t
color_brighten(const struct terminal *term, uint32_t color)
{
    /*
     * First try to match the color against the base 8 colors. If we
     * find a match, return the corresponding bright color.
     */
    if (term->conf->bold_in_bright.palette_based) {
        for (size_t i = 0; i < 8; i++) {
            if (term->colors.table[i] == color)
                return term->colors.table[i + 8];
        }
        return color;
    }

    return color_blend_towards(color, 0x00ffffff, term->conf->bold_in_bright.amount);
}

static void
draw_hollow_block(const struct terminal *term, pixman_image_t *pix,
                  const pixman_color_t *color, int x, int y, int cell_cols)
{
    const int scale = (int)roundf(term->scale);
    const int width = min(min(scale, term->cell_width), term->cell_height);

    pixman_image_fill_rectangles(
        PIXMAN_OP_SRC, pix, color, 4,
        (pixman_rectangle16_t []){
         {x, y, cell_cols * term->cell_width, width},                              /* top */
         {x, y, width, term->cell_height},                                         /* left */
         {x + cell_cols * term->cell_width - width, y, width, term->cell_height},  /* right */
         {x, y + term->cell_height - width, cell_cols * term->cell_width, width},  /* bottom */
        });
}

static void
draw_beam_cursor(const struct terminal *term, pixman_image_t *pix,
                 const struct fcft_font *font,
                 const pixman_color_t *color, int x, int y)
{
    int baseline = y + term->font_baseline - term->fonts[0]->ascent;
    pixman_image_fill_rectangles(
        PIXMAN_OP_SRC, pix, color,
        1, &(pixman_rectangle16_t){
            x, baseline,
            term_pt_or_px_as_pixels(term, &term->conf->cursor.beam_thickness),
            term->fonts[0]->ascent + term->fonts[0]->descent});
}

static int
underline_offset(const struct terminal *term, const struct fcft_font *font)
{
    return term->font_baseline -
        (term->conf->use_custom_underline_offset
         ? -term_pt_or_px_as_pixels(term, &term->conf->underline_offset)
         : font->underline.position);
}

static void
draw_underline_cursor(const struct terminal *term, pixman_image_t *pix,
               const struct fcft_font *font,
                      const pixman_color_t *color, int x, int y, int cols)
{
    int thickness = term->conf->cursor.underline_thickness.px >= 0
        ? term_pt_or_px_as_pixels(
            term, &term->conf->cursor.underline_thickness)
        : font->underline.thickness;

    /* Make sure the line isn't positioned below the cell */
    const int y_ofs = min(underline_offset(term, font) + thickness,
                          term->cell_height - thickness);

    pixman_image_fill_rectangles(
        PIXMAN_OP_SRC, pix, color,
        1, &(pixman_rectangle16_t){
            x, y + y_ofs, cols * term->cell_width, thickness});
}

static void
draw_underline(const struct terminal *term, pixman_image_t *pix,
               const struct fcft_font *font,
               const pixman_color_t *color, int x, int y, int cols)
{
    const int thickness = term->conf->underline_thickness.px >= 0
        ? term_pt_or_px_as_pixels(
            term, &term->conf->underline_thickness)
        : font->underline.thickness;

    /* Make sure the line isn't positioned below the cell */
    const int y_ofs = min(underline_offset(term, font),
                          term->cell_height - thickness);

    pixman_image_fill_rectangles(
        PIXMAN_OP_SRC, pix, color,
        1, &(pixman_rectangle16_t){
            x, y + y_ofs, cols * term->cell_width, thickness});
}

static void
draw_styled_underline(const struct terminal *term, pixman_image_t *pix,
                      const struct fcft_font *font,
                      const pixman_color_t *color,
                      enum underline_style style, int x, int y, int cols)
{
    xassert(style != UNDERLINE_NONE);

    if (style == UNDERLINE_SINGLE) {
        draw_underline(term, pix, font, color, x, y, cols);
        return;
    }

    const int thickness = term->conf->underline_thickness.px >= 0
        ? term_pt_or_px_as_pixels(
            term, &term->conf->underline_thickness)
        : font->underline.thickness;

    int y_ofs;

    /* Make sure the line isn't positioned below the cell */
    switch (style) {
    case UNDERLINE_DOUBLE:
    case UNDERLINE_CURLY:
        y_ofs = min(underline_offset(term, font),
                    term->cell_height - thickness * 3);
        break;

    case UNDERLINE_DASHED:
    case UNDERLINE_DOTTED:
        y_ofs = min(underline_offset(term, font),
                    term->cell_height - thickness);
        break;

    case UNDERLINE_NONE:
    case UNDERLINE_SINGLE:
    default:
        BUG("unexpected underline style: %d", (int)style);
        return;
    }

    const int ceil_w = cols * term->cell_width;

    switch (style) {
    case UNDERLINE_DOUBLE: {
        const pixman_rectangle16_t rects[] = {
            {x, y + y_ofs, ceil_w, thickness},
            {x, y + y_ofs + thickness * 2, ceil_w, thickness}};
        pixman_image_fill_rectangles(PIXMAN_OP_SRC, pix, color, 2, rects);
        break;
    }

    case UNDERLINE_DASHED: {
        const int ceil_w = cols * term->cell_width;
        const int dash_w = ceil_w / 3 + (ceil_w % 3 > 0);
        const pixman_rectangle16_t rects[] = {
            {x, y + y_ofs, dash_w, thickness},
            {x + dash_w * 2, y + y_ofs, dash_w, thickness},
        };
        pixman_image_fill_rectangles(
            PIXMAN_OP_SRC, pix, color, 2, rects);
        break;
    }

    case UNDERLINE_DOTTED: {
        /* Number of dots per cell */
        int per_cell = (term->cell_width / thickness) / 2;
        if (per_cell == 0)
            per_cell = 1;

        xassert(per_cell >= 1);

        /* Spacing between dots; start with the same width as the dots
           themselves, then widen them if necessary, to consume unused
           pixels */
        int spacing[per_cell];
        for (int i = 0; i < per_cell; i++)
            spacing[i] = thickness;

        /* Pixels remaining at the end of the cell */
        int remaining = term->cell_width - (per_cell * 2) * thickness;

        /* Spread out the left-over pixels across the spacing between
           the dots */
        for (int i = 0; remaining > 0; i = (i + 1) % per_cell, remaining--)
            spacing[i]++;

        xassert(remaining <= 0);

        pixman_rectangle16_t rects[per_cell];
        int dot_x = x;
        for (int i = 0; i < per_cell; i++) {
            rects[i] = (pixman_rectangle16_t){
                dot_x, y + y_ofs, thickness, thickness
            };

            dot_x += thickness + spacing[i];
        }

        pixman_image_fill_rectangles(PIXMAN_OP_SRC, pix, color, per_cell, rects);
        break;
    }

    case UNDERLINE_CURLY: {
        const int top = y + y_ofs;
        const int bot = top + thickness * 3;
        const int half_x = x + ceil_w / 2.0, full_x = x + ceil_w;

        const double bt_2 = (bot - top) * (bot - top);
        const double th_2 = thickness * thickness;
        const double hx_2 = ceil_w * ceil_w / 4.0;
        const int th = round(sqrt(th_2 + (th_2 * bt_2 / hx_2)) / 2.);

        #define I(x) pixman_int_to_fixed(x)
        const pixman_trapezoid_t traps[] = {
#if 0  /* characters sit within the "dips" of the curlies */
            {
                I(top), I(bot),
                {{I(x), I(top + th)}, {I(half_x), I(bot + th)}},
                {{I(x), I(top - th)}, {I(half_x), I(bot - th)}},
            },
            {
                I(top), I(bot),
                {{I(half_x), I(bot - th)}, {I(full_x), I(top - th)}},
                {{I(half_x), I(bot + th)}, {I(full_x), I(top + th)}},
            }
#else  /* characters sit on top of the curlies */
            {
                I(top), I(bot),
                {{I(x), I(bot - th)}, {I(half_x), I(top - th)}},
                {{I(x), I(bot + th)}, {I(half_x), I(top + th)}},
            },
            {
                I(top), I(bot),
                {{I(half_x), I(top + th)}, {I(full_x), I(bot + th)}},
                {{I(half_x), I(top - th)}, {I(full_x), I(bot - th)}},
            }
#endif
        };

        pixman_image_t *fill = pixman_image_create_solid_fill(color);
        pixman_composite_trapezoids(
            PIXMAN_OP_OVER, fill, pix, PIXMAN_a8, 0, 0, 0, 0,
            sizeof(traps) / sizeof(traps[0]), traps);

        pixman_image_unref(fill);
        break;
    }

    case UNDERLINE_NONE:
    case UNDERLINE_SINGLE:
        BUG("underline styles not supposed to be handled here");
        break;
    }
}

static void
draw_strikeout(const struct terminal *term, pixman_image_t *pix,
               const struct fcft_font *font,
               const pixman_color_t *color, int x, int y, int cols)
{
    const int thickness = term->conf->strikeout_thickness.px >= 0
        ? term_pt_or_px_as_pixels(
            term, &term->conf->strikeout_thickness)
        : font->strikeout.thickness;

    /* Try to center custom strikeout */
    const int position = term->conf->strikeout_thickness.px >= 0
        ? font->strikeout.position - round(font->strikeout.thickness / 2.) + round(thickness / 2.)
        : font->strikeout.position;

    pixman_image_fill_rectangles(
        PIXMAN_OP_SRC, pix, color,
        1, &(pixman_rectangle16_t){
            x, y + term->font_baseline - position,
            cols * term->cell_width, thickness});
}

static void
cursor_colors_for_cell(const struct terminal *term, const struct cell *cell,
                       const pixman_color_t *fg, const pixman_color_t *bg,
                       pixman_color_t *cursor_color, pixman_color_t *text_color,
                       bool gamma_correct)
{
    if (term->colors.cursor_bg >> 31)
        *cursor_color = color_hex_to_pixman(term->colors.cursor_bg, gamma_correct);
    else
        *cursor_color = *fg;

    if (term->colors.cursor_fg >> 31)
        *text_color = color_hex_to_pixman(term->colors.cursor_fg, gamma_correct);
    else {
        xassert(bg->alpha == 0xffff);
        *text_color = *bg;
    }

    if (text_color->red == cursor_color->red &&
        text_color->green == cursor_color->green &&
        text_color->blue == cursor_color->blue)
    {
        *text_color = color_hex_to_pixman(term->colors.bg, gamma_correct);
        *cursor_color = color_hex_to_pixman(term->colors.fg, gamma_correct);
    }
}

static void
draw_cursor(const struct terminal *term, const struct cell *cell,
            const struct fcft_font *font, pixman_image_t *pix, pixman_color_t *fg,
            const pixman_color_t *bg, int x, int y, int cols)
{
    pixman_color_t cursor_color;
    pixman_color_t text_color;
    cursor_colors_for_cell(term, cell, fg, bg, &cursor_color, &text_color,
                           wayl_do_linear_blending(term->wl, term->conf));

    if (unlikely(!term->kbd_focus)) {
        switch (term->conf->cursor.unfocused_style) {
        case CURSOR_UNFOCUSED_UNCHANGED:
            break;

        case CURSOR_UNFOCUSED_HOLLOW:
            draw_hollow_block(term, pix, &cursor_color, x, y, cols);
            return;

        case CURSOR_UNFOCUSED_NONE:
            return;
        }
    }

    switch (term->cursor_style) {
    case CURSOR_BLOCK:
        if (likely(term->cursor_blink.state == CURSOR_BLINK_ON) ||
            !term->kbd_focus)
        {
            *fg = text_color;
            pixman_image_fill_rectangles(
                PIXMAN_OP_SRC, pix, &cursor_color, 1,
                &(pixman_rectangle16_t){x, y, cols * term->cell_width, term->cell_height});
        }
        break;

    case CURSOR_BEAM:
        if (likely(term->cursor_blink.state == CURSOR_BLINK_ON ||
                   !term->kbd_focus))
        {
            draw_beam_cursor(term, pix, font, &cursor_color, x, y);
        }
        break;

    case CURSOR_UNDERLINE:
        if (likely(term->cursor_blink.state == CURSOR_BLINK_ON ||
                   !term->kbd_focus))
        {
            draw_underline_cursor(term, pix, font, &cursor_color, x, y, cols);
        }
        break;

    case CURSOR_HOLLOW:
        if (likely(term->cursor_blink.state == CURSOR_BLINK_ON))
            draw_hollow_block(term, pix, &cursor_color, x, y, cols);
        break;
    }
}

static int
render_cell(struct terminal *term, pixman_image_t *pix,
            pixman_region32_t *damage, struct row *row, int row_no, int col,
            bool has_cursor)
{
    struct cell *cell = &row->cells[col];
    if (cell->attrs.clean)
        return 0;

    cell->attrs.clean = 1;
    cell->attrs.confined = true;

    int width = term->cell_width;
    int height = term->cell_height;
    const int x = term->margins.left + col * width;
    const int y = term->margins.top + row_no * height;

    uint32_t _fg = 0;
    uint32_t _bg = 0;

    uint16_t alpha = 0xffff;
    const bool is_selected = cell->attrs.selected;

    /* Use cell specific color, if set, otherwise the default colors (possible reversed) */
    switch (cell->attrs.fg_src) {
    case COLOR_RGB:
        _fg = cell->attrs.fg;
        break;

    case COLOR_BASE16:
    case COLOR_BASE256:
        xassert(cell->attrs.fg < ALEN(term->colors.table));
        _fg = term->colors.table[cell->attrs.fg];
        break;

    case COLOR_DEFAULT:
        _fg = term->reverse ? term->colors.bg : term->colors.fg;
        break;
    }

    switch (cell->attrs.bg_src) {
    case COLOR_RGB:
        _bg = cell->attrs.bg;
        break;

    case COLOR_BASE16:
    case COLOR_BASE256:
        xassert(cell->attrs.bg < ALEN(term->colors.table));
        _bg = term->colors.table[cell->attrs.bg];
        break;

    case COLOR_DEFAULT:
        _bg = term->reverse ? term->colors.fg : term->colors.bg;
        break;
    }

    if (unlikely(is_selected)) {
        const uint32_t cell_fg = _fg;
        const uint32_t cell_bg = _bg;

        const bool custom_fg = term->colors.selection_fg >> 24 == 0;
        const bool custom_bg = term->colors.selection_bg >> 24 == 0;
        const bool custom_both = custom_fg && custom_bg;

        if (custom_both) {
            _fg = term->colors.selection_fg;
            _bg = term->colors.selection_bg;
        } else if (custom_bg) {
            _bg = term->colors.selection_bg;
            _fg = cell->attrs.reverse ? cell_bg : cell_fg;
        } else if (custom_fg) {
            _fg = term->colors.selection_fg;
            _bg = cell->attrs.reverse ? cell_fg : cell_bg;
        } else {
            _bg = cell_fg;
            _fg = cell_bg;
        }

        if (unlikely(_fg == _bg)) {
            /* Invert bg when selected/highlighted text has same fg/bg */
            _bg = ~_bg;
            alpha = 0xffff;
        }

    } else {
        if (unlikely(cell->attrs.reverse)) {
            uint32_t swap = _fg;
            _fg = _bg;
            _bg = swap;
        }

        else if (!term->window->is_fullscreen && term->colors.alpha != 0xffff) {
            switch (term->conf->colors.alpha_mode) {
            case ALPHA_MODE_DEFAULT: {
                if (cell->attrs.bg_src == COLOR_DEFAULT) {
                    alpha = term->colors.alpha;
                }
                break;
            }

            case ALPHA_MODE_MATCHING: {
                if (cell->attrs.bg_src == COLOR_DEFAULT ||
                    ((cell->attrs.bg_src == COLOR_BASE16 ||
                      cell->attrs.bg_src == COLOR_BASE256) &&
                     term->colors.table[cell->attrs.bg] == term->colors.bg) ||
                    (cell->attrs.bg_src == COLOR_RGB &&
                     cell->attrs.bg == term->colors.bg))
                {
                    alpha = term->colors.alpha;
                }
                break;
            }

            case ALPHA_MODE_ALL: {
                alpha = term->colors.alpha;
                break;
            }
            }
        } else {
            /*
             * Note: disable transparency when fullscreened.
             *
             * This is because the wayland protocol mandates no screen
             * content is shown behind the fullscreened window.
             *
             * The _intent_ of the specification is that a black (or
             * other static color) should be used as background.
             *
             * There's a bit of gray area however, and some
             * compositors have chosen to interpret the specification
             * in a way that allows wallpapers to be seen through a
             * fullscreen window.
             *
             * Given that a) the intent of the specification, and b)
             * we don't know what the compositor will do, we simply
             * disable transparency while in fullscreen.
             *
             * To see why, consider what happens if we keep our
             * transparency. For example, if the background color is
             * white, and alpha is 0.5, then the window will be drawn
             * in a shade of gray while fullscreened.
             *
             * See
             * https://gitlab.freedesktop.org/wayland/wayland-protocols/-/issues/116
             * for a discussion on whether transparent, fullscreen
             * windows should be allowed in some way or not.
             *
             * NOTE: if changing this, also update render_margin()
             */
            xassert(alpha == 0xffff);
        }
    }

    if (cell->attrs.dim)
        _fg = color_dim(term, _fg);
    if (term->conf->bold_in_bright.enabled && cell->attrs.bold)
        _fg = color_brighten(term, _fg);

    if (cell->attrs.blink && term->blink.state == BLINK_OFF)
        _fg = color_blend_towards(_fg, 0x00000000, term->conf->dim.amount);

    const bool gamma_correct = wayl_do_linear_blending(term->wl, term->conf);
    pixman_color_t fg = color_hex_to_pixman(_fg, gamma_correct);
    pixman_color_t bg = color_hex_to_pixman_with_alpha(_bg, alpha, gamma_correct);

    struct fcft_font *font = attrs_to_font(term, &cell->attrs);
    const struct composed *composed = NULL;
    const struct fcft_grapheme *grapheme = NULL;
    const struct fcft_glyph *single = NULL;
    const struct fcft_glyph **glyphs = NULL;
    unsigned glyph_count = 0;

    char32_t base = cell->wc;
    int cell_cols = 1;

    if (base != 0) {
        if (unlikely(
                /* Classic box drawings */
                (base >= GLYPH_BOX_DRAWING_FIRST &&
                 base <= GLYPH_BOX_DRAWING_LAST) ||

                /* Braille */
                (base >= GLYPH_BRAILLE_FIRST &&
                 base <= GLYPH_BRAILLE_LAST) ||

                /*
                 * Unicode 13 "Symbols for Legacy Computing"
                 * sub-ranges below.
                 *
                 * Note, the full range is U+1FB00 - U+1FBF9
                 */
                (base >= GLYPH_LEGACY_FIRST &&
                 base <= GLYPH_LEGACY_LAST) ||

                /*
                 * Unicode 16 "Symbols for Legacy Computing Supplement"
                 *
                 * Note, the full range is U+1CC00 - U+1CEAF
                 */
                (base >= GLYPH_OCTANTS_FIRST &&
                 base <= GLYPH_OCTANTS_LAST)) &&

            likely(!term->conf->box_drawings_uses_font_glyphs))
        {
            struct fcft_glyph ***arr;
            size_t count;
            size_t idx;

            if (base >= GLYPH_LEGACY_FIRST) {
                arr = &term->custom_glyphs.legacy;
                count = GLYPH_LEGACY_COUNT;
                idx = base - GLYPH_LEGACY_FIRST;
            } else if (base >= GLYPH_OCTANTS_FIRST) {
                arr = &term->custom_glyphs.octants;
                count = GLYPH_OCTANTS_COUNT;
                idx = base - GLYPH_OCTANTS_FIRST;
            } else if (base >= GLYPH_BRAILLE_FIRST) {
                arr = &term->custom_glyphs.braille;
                count = GLYPH_BRAILLE_COUNT;
                idx = base - GLYPH_BRAILLE_FIRST;
            } else {
                arr = &term->custom_glyphs.box_drawing;
                count = GLYPH_BOX_DRAWING_COUNT;
                idx = base - GLYPH_BOX_DRAWING_FIRST;
            }

            if (unlikely(*arr == NULL))
                *arr = xcalloc(count, sizeof((*arr)[0]));

            if (likely((*arr)[idx] != NULL))
                single = (*arr)[idx];
            else {
                mtx_lock(&term->render.workers.lock);

                /* Other thread may have instantiated it while we
                 * acquired the lock */
                single = (*arr)[idx];
                if (likely(single == NULL))
                    single = (*arr)[idx] = box_drawing(term, base);
                mtx_unlock(&term->render.workers.lock);
            }

            if (single != NULL) {
                glyph_count = 1;
                glyphs = &single;
                cell_cols = single->cols;
            }
        }

        else if (base >= CELL_COMB_CHARS_LO && base <= CELL_COMB_CHARS_HI)
        {
            composed = composed_lookup(term->composed, base - CELL_COMB_CHARS_LO);
            base = composed->chars[0];

            if (term->conf->can_shape_grapheme && term->conf->tweak.grapheme_shaping) {
                grapheme = fcft_rasterize_grapheme_utf32(
                    font, composed->count, composed->chars, term->font_subpixel);
            }

            if (grapheme != NULL) {
                const int forced_width = composed->forced_width;

                cell_cols = forced_width > 0 ? forced_width : composed->width;

                composed = NULL;
                glyphs = grapheme->glyphs;
                glyph_count = grapheme->count;

                if (forced_width > 0)
                    glyph_count = min(glyph_count, forced_width);
            }
        }

        if (single == NULL && grapheme == NULL) {
            if (unlikely(base >= CELL_SPACER)) {
                glyph_count = 0;
                cell_cols = 1;
            } else {
                xassert(base != 0);
                single = fcft_rasterize_char_utf32(font, base, term->font_subpixel);
                if (single == NULL) {
                    glyph_count = 0;
                    cell_cols = 1;
                } else {
                    glyph_count = 1;
                    glyphs = &single;

                    const size_t forced_width = composed != NULL ? composed->forced_width : 0;
                    cell_cols = forced_width > 0 ? forced_width : single->cols;
                }
            }
        }
    }

    assert(glyph_count == 0 || glyphs != NULL);

    const int cols_left = term->cols - col;
    cell_cols = max(1, min(cell_cols, cols_left));

    /*
     * Determine cells that will bleed into their right neighbor and remember
     * them for cleanup in the next frame.
     */
    int render_width = cell_cols * width;
    if (term->conf->tweak.overflowing_glyphs &&
        glyph_count > 0 &&
        cols_left > cell_cols)
    {
        int glyph_width = 0, advance = 0;
        for (size_t i = 0; i < glyph_count; i++) {
            glyph_width = max(glyph_width,
                              advance + glyphs[i]->x + glyphs[i]->width);
            advance += glyphs[i]->advance.x;
        }

        if (glyph_width > render_width) {
            render_width = min(glyph_width, render_width + width);

            for (int i = 0; i < cell_cols; i++)
                row->cells[col + i].attrs.confined = false;
        }
    }

    pixman_region32_t clip;
    pixman_region32_init_rect(
        &clip, x, y,
        render_width, term->cell_height);
    pixman_image_set_clip_region32(pix, &clip);

    if (damage != NULL) {
        pixman_region32_union_rect(
            damage, damage, x, y, render_width, term->cell_height);
    }

    pixman_region32_fini(&clip);

    /* Background */
    pixman_image_fill_rectangles(
        PIXMAN_OP_SRC, pix, &bg, 1,
        &(pixman_rectangle16_t){x, y, cell_cols * width, height});

    if (cell->attrs.blink && term->blink.fd < 0) {
        /* TODO: use a custom lock for this? */
        mtx_lock(&term->render.workers.lock);
        term_arm_blink_timer(term);
        mtx_unlock(&term->render.workers.lock);
    }

    if (unlikely(has_cursor && term->cursor_style == CURSOR_BLOCK && term->kbd_focus)) {
        const pixman_color_t bg_without_alpha = color_hex_to_pixman(_bg, gamma_correct);
        draw_cursor(term, cell, font, pix, &fg, &bg_without_alpha, x, y, cell_cols);
    }

    if (cell->wc == 0 || cell->wc >= CELL_SPACER || cell->wc == U'\t' ||
        (unlikely(cell->attrs.conceal) && !is_selected))
    {
        goto draw_cursor;
    }

    pixman_image_t *clr_pix = pixman_image_create_solid_fill(&fg);

    int pen_x = x;
    for (unsigned i = 0; i < glyph_count; i++) {
        const int letter_x_ofs = i == 0 ? term->font_x_ofs : 0;

        const struct fcft_glyph *glyph = glyphs[i];
        if (glyph == NULL)
            continue;

        int g_x = glyph->x;
        int g_y = glyph->y;

        if (i > 0 && glyph->x >= 0 && cell_cols == 1)
            g_x -= term->cell_width;

        if (unlikely(glyph->is_color_glyph)) {
            /* Glyph surface is a pre-rendered image (typically a color emoji...) */
            if (!(cell->attrs.blink && term->blink.state == BLINK_OFF)) {
                pixman_image_composite32(
                    PIXMAN_OP_OVER, glyph->pix, NULL, pix, 0, 0, 0, 0,
                    pen_x + letter_x_ofs + g_x, y + term->font_baseline - g_y,
                    glyph->width, glyph->height);
            }
        } else {
            pixman_image_composite32(
                PIXMAN_OP_OVER, clr_pix, glyph->pix, pix, 0, 0, 0, 0,
                pen_x + letter_x_ofs + g_x, y + term->font_baseline - g_y,
                glyph->width, glyph->height);

            /* Combining characters */
            if (composed != NULL) {
                assert(glyph_count == 1);

                for (size_t j = 1; j < composed->count; j++) {
                    const struct fcft_glyph *g = fcft_rasterize_char_utf32(
                        font, composed->chars[j], term->font_subpixel);

                    if (g == NULL)
                        continue;

                    /*
                     * Fonts _should_ assume the pen position is now
                     * *after* the base glyph, and thus use negative
                     * offsets for combining glyphs.
                     *
                     * Not all fonts behave like this however, and we
                     * try to accommodate both variants.
                     *
                     * Since we haven't moved our pen position yet, we
                     * add a full cell width to the offset (or two, in
                     * case of double-width characters).
                     *
                     * If the font does *not* use negative offsets,
                     * we'd normally use an offset of 0. However, to
                     * somewhat deal with double-width glyphs we use
                     * an offset of *one* cell.
                     */
                    int x_ofs = cell_cols == 1
                        ? g->x < 0
                            ? cell_cols * term->cell_width
                            : (cell_cols - 1) * term->cell_width
                        : 0;

                    if (cell_cols > 1)
                        pen_x += term->cell_width;

                    pixman_image_composite32(
                        PIXMAN_OP_OVER, clr_pix, g->pix, pix, 0, 0, 0, 0,
                        /* Some fonts use a negative offset, while others use a
                         * "normal" offset */
                        pen_x + letter_x_ofs + x_ofs + g->x,
                        y + term->font_baseline - g->y, g->width, g->height);
                }
            }
        }

        pen_x += cell_cols > 1 ? term->cell_width : glyph->advance.x;
    }

    pixman_image_unref(clr_pix);

    /* Underline */
    if (cell->attrs.underline) {
        pixman_color_t underline_color = fg;
        enum underline_style underline_style = UNDERLINE_SINGLE;

        /* Check if cell has a styled underline. This lookup is fairly
           expensive... */
        if (row->extra != NULL) {
            for (int i = 0; i < row->extra->underline_ranges.count; i++) {
                const struct row_range *range = &row->extra->underline_ranges.v[i];

                if (range->start > col)
                    break;

                if (range->start <= col && col <= range->end) {
                    switch (range->underline.color_src) {
                    case COLOR_BASE256:
                        underline_color = color_hex_to_pixman(
                            term->colors.table[range->underline.color], gamma_correct);
                        break;

                    case COLOR_RGB:
                        underline_color =
                            color_hex_to_pixman(range->underline.color, gamma_correct);
                        break;

                    case COLOR_DEFAULT:
                        break;

                    case COLOR_BASE16:
                        BUG("underline color can't be base-16");
                        break;
                    }

                    underline_style = range->underline.style;
                    break;
                }
            }
        }

        draw_styled_underline(
            term, pix, font, &underline_color, underline_style, x, y, cell_cols);

    }

    if (cell->attrs.strikethrough)
        draw_strikeout(term, pix, font, &fg, x, y, cell_cols);

    if (unlikely(cell->attrs.url)) {
        pixman_color_t url_color = color_hex_to_pixman(
            term->conf->colors.use_custom.url
            ? term->conf->colors.url
            : term->colors.table[3],
            gamma_correct);
        draw_underline(term, pix, font, &url_color, x, y, cell_cols);
    }

draw_cursor:
    if (has_cursor && (term->cursor_style != CURSOR_BLOCK || !term->kbd_focus)) {
        const pixman_color_t bg_without_alpha = color_hex_to_pixman(_bg, gamma_correct);
        draw_cursor(term, cell, font, pix, &fg, &bg_without_alpha, x, y, cell_cols);
    }

    pixman_image_set_clip_region32(pix, NULL);
    return cell_cols;
}

static void
render_row(struct terminal *term, pixman_image_t *pix,
           pixman_region32_t *damage, struct row *row,
           int row_no, int cursor_col)
{
    for (int col = term->cols - 1; col >= 0; col--)
        render_cell(term, pix, damage, row, row_no, col, cursor_col == col);
}

static void
render_urgency(struct terminal *term, struct buffer *buf)
{
    uint32_t red = term->colors.table[1];
    pixman_color_t bg = color_hex_to_pixman(
        red, wayl_do_linear_blending(term->wl, term->conf));

    int width = min(min(term->margins.left, term->margins.right),
                    min(term->margins.top, term->margins.bottom));

    pixman_image_fill_rectangles(
        PIXMAN_OP_SRC, buf->pix[0], &bg, 4,
        (pixman_rectangle16_t[]){
            /* Top */
            {0, 0, term->width, width},

            /* Bottom */
            {0, term->height - width, term->width, width},

            /* Left */
            {0, width, width, term->height - 2 * width},

            /* Right */
            {term->width - width, width, width, term->height - 2 * width},
        });
}

static void
render_margin(struct terminal *term, struct buffer *buf,
              int start_line, int end_line, bool apply_damage)
{
    /* Fill area outside the cell grid with the default background color */
    const int rmargin = term->width - term->margins.right;
    const int bmargin = term->height - term->margins.bottom;
    const int line_count = end_line - start_line;

    const bool gamma_correct = wayl_do_linear_blending(term->wl, term->conf);
    const uint32_t _bg = !term->reverse ? term->colors.bg : term->colors.fg;
    uint16_t alpha = term->colors.alpha;

    if (term->window->is_fullscreen) {
        /* Disable alpha in fullscreen - see render_cell() for details */
        alpha = 0xffff;
    }

    pixman_color_t bg = color_hex_to_pixman_with_alpha(_bg, alpha, gamma_correct);

    pixman_image_fill_rectangles(
        PIXMAN_OP_SRC, buf->pix[0], &bg, 4,
        (pixman_rectangle16_t[]){
            /* Top */
            {0, 0, term->width, term->margins.top},

            /* Bottom */
            {0, bmargin, term->width, term->margins.bottom},

            /* Left */
            {0, term->margins.top + start_line * term->cell_height,
             term->margins.left, line_count * term->cell_height},

            /* Right */
            {rmargin, term->margins.top + start_line * term->cell_height,
             term->margins.right, line_count * term->cell_height},
    });

    if (term->render.urgency)
        render_urgency(term, buf);

    /* Ensure the updated regions are copied to the next frame's
     * buffer when we're double buffering */
    pixman_region32_union_rect(
        &buf->dirty[0], &buf->dirty[0], 0, 0, term->width, term->margins.top);
    pixman_region32_union_rect(
        &buf->dirty[0], &buf->dirty[0], 0, bmargin, term->width, term->margins.bottom);
    pixman_region32_union_rect(
        &buf->dirty[0], &buf->dirty[0], 0, 0, term->margins.left, term->height);
    pixman_region32_union_rect(
        &buf->dirty[0], &buf->dirty[0],
        rmargin, 0, term->margins.right, term->height);

    if (apply_damage) {
        /* Top */
        wl_surface_damage_buffer(
            term->window->surface.surf, 0, 0, term->width, term->margins.top);

        /* Bottom */
        wl_surface_damage_buffer(
            term->window->surface.surf, 0, bmargin, term->width, term->margins.bottom);

        /* Left */
        wl_surface_damage_buffer(
            term->window->surface.surf,
            0, term->margins.top + start_line * term->cell_height,
            term->margins.left, line_count * term->cell_height);

        /* Right */
        wl_surface_damage_buffer(
            term->window->surface.surf,
            rmargin, term->margins.top + start_line * term->cell_height,
            term->margins.right, line_count * term->cell_height);
    }
}

static void
grid_render_scroll(struct terminal *term, struct buffer *buf,
                   const struct damage *dmg)
{
    LOG_DBG(
        "damage: SCROLL: %d-%d by %d lines",
        dmg->region.start, dmg->region.end, dmg->lines);

    const int region_size = dmg->region.end - dmg->region.start;

    if (dmg->lines >= region_size) {
        /* The entire scroll region will be scrolled out (i.e. replaced) */
        return;
    }

    const int height = (region_size - dmg->lines) * term->cell_height;
    xassert(height > 0);

#if TIME_SCROLL_DAMAGE
    struct timespec start_time;
    clock_gettime(CLOCK_MONOTONIC, &start_time);
#endif

    int dst_y = term->margins.top + (dmg->region.start + 0) * term->cell_height;
    int src_y = term->margins.top + (dmg->region.start + dmg->lines) * term->cell_height;

    /*
     * SHM scrolling can be *much* faster, but it depends on how many
     * lines we're scrolling, and how much repairing we need to do.
     *
     * In short, scrolling a *large* number of rows is faster with a
     * memmove, while scrolling a *small* number of lines is faster
     * with SHM scrolling.
     *
     * However, since we need to restore the scrolling regions when
     * SHM scrolling, we also need to take this into account.
     *
     * Finally, we also have to restore the window margins, and this
     * is a *huge* performance hit when scrolling a large number of
     * lines (in addition to the sloweness of SHM scrolling as
     * method).
     *
     * So, we need to figure out when to SHM scroll, and when to
     * memmove.
     *
     * For now, assume that the both methods perform roughly the same,
     * given an equal number of bytes to move/allocate, and use the
     * method that results in the least amount of bytes to touch.
     *
     * Since number of lines directly translates to bytes, we can
     * simply count lines.
     *
     * SHM scrolling needs to first "move" (punch hole + allocate)
     * dmg->lines number of lines, and then we need to restore
     * the bottom scroll region.
     *
     * If the total number of lines is less than half the screen - use
     * SHM. Otherwise use memmove.
     */
    bool try_shm_scroll =
        shm_can_scroll(buf) && (
            dmg->lines +
            dmg->region.start +
            (term->rows - dmg->region.end)) < term->rows / 2;

    bool did_shm_scroll = false;

    //try_shm_scroll = false;
    //try_shm_scroll = true;

    if (try_shm_scroll) {
        did_shm_scroll = shm_scroll(
            buf, dmg->lines * term->cell_height,
            term->margins.top, dmg->region.start * term->cell_height,
            term->margins.bottom, (term->rows - dmg->region.end) * term->cell_height);
    }

    if (did_shm_scroll) {
        /* Restore margins */
        render_margin(
            term, buf, dmg->region.end - dmg->lines, term->rows, false);
    } else {
        /* Fallback for when we either cannot do SHM scrolling, or it failed */
        uint8_t *raw = buf->data;
        memmove(raw + dst_y * buf->stride,
                raw + src_y * buf->stride,
                height * buf->stride);
    }

#if TIME_SCROLL_DAMAGE
    struct timespec end_time;
    clock_gettime(CLOCK_MONOTONIC, &end_time);

    struct timespec memmove_time;
    timespec_sub(&end_time, &start_time, &memmove_time);
    LOG_INFO("scrolled %dKB (%d lines) using %s in %lds %ldns",
             height * buf->stride / 1024, dmg->lines,
             did_shm_scroll ? "SHM" : try_shm_scroll ? "memmove (SHM failed)" :  "memmove",
             (long)memmove_time.tv_sec, memmove_time.tv_nsec);
#endif

    wl_surface_damage_buffer(
        term->window->surface.surf, term->margins.left, dst_y,
        term->width - term->margins.left - term->margins.right, height);

    /*
     * TODO: remove this if re-enabling scroll damage when re-applying
     * last frame's damage (see reapply_old_damage()
     */
    pixman_region32_union_rect(
        &buf->dirty[0], &buf->dirty[0], 0, dst_y, buf->width, height);
}

static void
grid_render_scroll_reverse(struct terminal *term, struct buffer *buf,
                           const struct damage *dmg)
{
    LOG_DBG(
        "damage: SCROLL REVERSE: %d-%d by %d lines",
        dmg->region.start, dmg->region.end, dmg->lines);

    const int region_size = dmg->region.end - dmg->region.start;

    if (dmg->lines >= region_size) {
        /* The entire scroll region will be scrolled out (i.e. replaced) */
        return;
    }

    const int height = (region_size - dmg->lines) * term->cell_height;
    xassert(height > 0);

#if TIME_SCROLL_DAMAGE
    struct timespec start_time;
    clock_gettime(CLOCK_MONOTONIC, &start_time);
#endif

    int src_y = term->margins.top + (dmg->region.start + 0) * term->cell_height;
    int dst_y = term->margins.top + (dmg->region.start + dmg->lines) * term->cell_height;

    bool try_shm_scroll =
        shm_can_scroll(buf) && (
            dmg->lines +
            dmg->region.start +
            (term->rows - dmg->region.end)) < term->rows / 2;

    bool did_shm_scroll = false;

    if (try_shm_scroll) {
        did_shm_scroll = shm_scroll(
            buf, -dmg->lines * term->cell_height,
            term->margins.top, dmg->region.start * term->cell_height,
            term->margins.bottom, (term->rows - dmg->region.end) * term->cell_height);
    }

    if (did_shm_scroll) {
        /* Restore margins */
        render_margin(
            term, buf, dmg->region.start, dmg->region.start + dmg->lines, false);
    } else {
        /* Fallback for when we either cannot do SHM scrolling, or it failed */
        uint8_t *raw = buf->data;
        memmove(raw + dst_y * buf->stride,
                raw + src_y * buf->stride,
                height * buf->stride);
    }

#if TIME_SCROLL_DAMAGE
    struct timespec end_time;
    clock_gettime(CLOCK_MONOTONIC, &end_time);

    struct timespec memmove_time;
    timespec_sub(&end_time, &start_time, &memmove_time);
    LOG_INFO("scrolled REVERSE %dKB (%d lines) using %s in %lds %ldns",
             height * buf->stride / 1024, dmg->lines,
             did_shm_scroll ? "SHM" : try_shm_scroll ? "memmove (SHM failed)" :  "memmove",
             (long)memmove_time.tv_sec, memmove_time.tv_nsec);
#endif

    wl_surface_damage_buffer(
        term->window->surface.surf, term->margins.left, dst_y,
        term->width - term->margins.left - term->margins.right, height);

    /*
     * TODO: remove this if re-enabling scroll damage when re-applying
     * last frame's damage (see reapply_old_damage()
     */
    pixman_region32_union_rect(
        &buf->dirty[0], &buf->dirty[0], 0, dst_y, buf->width, height);
}

static void
render_sixel_chunk(struct terminal *term, pixman_image_t *pix,
                   pixman_region32_t *damage, const struct sixel *sixel,
                   int term_start_row, int img_start_row, int count)
{
    /* Translate row/column to x/y pixel values */
    const int x = term->margins.left + sixel->pos.col * term->cell_width;
    const int y = term->margins.top + term_start_row * term->cell_height;

    /* Width/height, in pixels - and don't touch the window margins */
    const int width = max(
        0,
        min(sixel->width,
            term->width - x - term->margins.right));
    const int height = max(
        0,
        min(
            min(count * term->cell_height,                          /* 'count' number of rows */
                sixel->height - img_start_row * term->cell_height), /* What remains of the sixel */
            term->height - y - term->margins.bottom));

    /* Verify we're not stepping outside the grid */
    xassert(x >= term->margins.left);
    xassert(y >= term->margins.top);
    xassert(width == 0 || x + width <= term->width - term->margins.right);
    xassert(height == 0 || y + height <= term->height - term->margins.bottom);

    //LOG_DBG("sixel chunk: %dx%d %dx%d", x, y, width, height);

    pixman_image_composite32(
        sixel->opaque ? PIXMAN_OP_SRC : PIXMAN_OP_OVER,
        sixel->pix,
        NULL,
        pix,
        0, img_start_row * term->cell_height,
        0, 0,
        x, y,
        width, height);

    if (damage != NULL)
        pixman_region32_union_rect(damage, damage, x, y, width, height);
}

static void
render_sixel(struct terminal *term, pixman_image_t *pix,
             pixman_region32_t *damage, const struct coord *cursor,
             const struct sixel *sixel)
{
    xassert(sixel->pix != NULL);
    xassert(sixel->width >= 0);
    xassert(sixel->height >= 0);

    const int view_end = (term->grid->view + term->rows - 1) & (term->grid->num_rows - 1);
    const bool last_row_needs_erase = sixel->height % term->cell_height != 0;
    const bool last_col_needs_erase = sixel->width % term->cell_width != 0;

    int chunk_img_start = -1;  /* Image-relative start row of chunk */
    int chunk_term_start = -1; /* Viewport relative start row of chunk */
    int chunk_row_count = 0;   /* Number of rows to emit */

#define maybe_emit_sixel_chunk_then_reset()                             \
    if (chunk_row_count != 0) {                                         \
        render_sixel_chunk(                                             \
            term, pix, damage, sixel,                                   \
            chunk_term_start, chunk_img_start, chunk_row_count);        \
        chunk_term_start = chunk_img_start = -1;                        \
        chunk_row_count = 0;                                            \
    }

    /*
     * Iterate all sixel rows:
     *
     *  - ignore rows that aren't visible on-screen
     *  - ignore rows that aren't dirty (they have already been rendered)
     *  - chunk consecutive dirty rows into a 'chunk'
     *  - emit (render) chunk as soon as a row isn't visible, or is clean
     *  - emit final chunk after we've iterated all rows
     *
     * The purpose of this is to reduce the amount of pixels that
     * needs to be composited and marked as damaged for the
     * compositor.
     *
     * Since we do CPU based composition, rendering is a slow and
     * heavy task for foot, and thus it is important to not re-render
     * things unnecessarily.
     */

    for (int _abs_row_no = sixel->pos.row;
         _abs_row_no < sixel->pos.row + sixel->rows;
         _abs_row_no++)
    {
        const int abs_row_no = _abs_row_no & (term->grid->num_rows - 1);
        const int term_row_no =
            (abs_row_no - term->grid->view + term->grid->num_rows) &
            (term->grid->num_rows - 1);

        /* Check if row is in the visible viewport */
        if (view_end >= term->grid->view) {
            /* Not wrapped */
            if (!(abs_row_no >= term->grid->view && abs_row_no <= view_end)) {
                /* Not visible */
                maybe_emit_sixel_chunk_then_reset();
                continue;
            }
        } else {
            /* Wrapped */
            if (!(abs_row_no >= term->grid->view || abs_row_no <= view_end)) {
                /* Not visible */
                maybe_emit_sixel_chunk_then_reset();
                continue;
            }
        }

        /* Is the row dirty? */
        struct row *row = term->grid->rows[abs_row_no];
        xassert(row != NULL);  /* Should be visible */

        if (!row->dirty) {
            maybe_emit_sixel_chunk_then_reset();
            continue;
        }

        int cursor_col = cursor->row == term_row_no ? cursor->col : -1;

        /*
         * If image contains transparent parts, render all (dirty)
         * cells beneath it.
         *
         * If image is opaque, loop cells and set their 'clean' bit,
         * to prevent the grid rendered from overwriting the sixel
         *
         * If the last sixel row only partially covers the cell row,
         * 'erase' the cell by rendering them.
         *
         * In all cases, do *not* clear the 'dirty' bit on the row, to
         * ensure the regular renderer includes them in the damage
         * rect.
         */
        if (!sixel->opaque) {
            /* TODO: multithreading */
            render_row(term, pix, damage, row, term_row_no, cursor_col);
        } else {
            for (int col = sixel->pos.col;
                 col < min(sixel->pos.col + sixel->cols, term->cols);
                 col++)
            {
                struct cell *cell = &row->cells[col];

                if (!cell->attrs.clean) {
                    bool last_row = abs_row_no == sixel->pos.row + sixel->rows - 1;
                    bool last_col = col == sixel->pos.col + sixel->cols - 1;

                    if ((last_row_needs_erase && last_row) ||
                        (last_col_needs_erase && last_col))
                    {
                        render_cell(term, pix, damage, row, term_row_no, col, cursor_col == col);
                    } else {
                        cell->attrs.clean = 1;
                        cell->attrs.confined = 1;
                    }
                }
            }
        }

        if (chunk_term_start == -1) {
            xassert(chunk_img_start == -1);
            chunk_term_start = term_row_no;
            chunk_img_start = _abs_row_no - sixel->pos.row;
            chunk_row_count = 1;
        } else
            chunk_row_count++;
    }

    maybe_emit_sixel_chunk_then_reset();
#undef maybe_emit_sixel_chunk_then_reset
}

static void
render_sixel_images(struct terminal *term, pixman_image_t *pix,
                    pixman_region32_t *damage, const struct coord *cursor)
{
    if (likely(tll_length(term->grid->sixel_images)) == 0)
        return;

    const int scrollback_end
        = (term->grid->offset + term->rows) & (term->grid->num_rows - 1);

    const int view_start
        = (term->grid->view
           - scrollback_end
           + term->grid->num_rows) & (term->grid->num_rows - 1);

    const int view_end = view_start + term->rows - 1;

    //LOG_DBG("SIXELS: %zu images, view=%d-%d",
    //        tll_length(term->grid->sixel_images), view_start, view_end);

    tll_foreach(term->grid->sixel_images, it) {
        const struct sixel *six = &it->item;
        const int start
            = (six->pos.row
               - scrollback_end
               + term->grid->num_rows) & (term->grid->num_rows - 1);
        const int end = start + six->rows - 1;

        //LOG_DBG("  sixel: %d-%d", start, end);
        if (start > view_end) {
            /* Sixel starts after view ends, no need to try to render it */
            continue;
        } else if (end < view_start) {
            /* Image ends before view starts. Since the image list is
             * sorted, we can safely stop here */
            break;
        }

        sixel_sync_cache(term, &it->item);
        render_sixel(term, pix, damage, cursor, &it->item);
    }
}

#if defined(FOOT_IME_ENABLED) && FOOT_IME_ENABLED
static void
render_ime_preedit_for_seat(struct terminal *term, struct seat *seat,
                            struct buffer *buf)
{
    if (likely(seat->ime.preedit.cells == NULL))
        return;

    if (unlikely(term->is_searching))
        return;

    const bool gamma_correct = wayl_do_linear_blending(term->wl, term->conf);

    /* Adjust cursor position to viewport */
    struct coord cursor;
    cursor = term->grid->cursor.point;
    cursor.row += term->grid->offset;
    cursor.row -= term->grid->view;
    cursor.row &= term->grid->num_rows - 1;

    if (cursor.row < 0 || cursor.row >= term->rows)
        return;

    int cells_needed = seat->ime.preedit.count;

    if (seat->ime.preedit.cursor.start == cells_needed &&
        seat->ime.preedit.cursor.end == cells_needed)
    {
        /* Cursor will be drawn *after* the pre-edit string, i.e. in
         * the cell *after*. This means we need to copy, and dirty,
         * one extra cell from the original grid, or we'll leave
         * trailing "cursors" after us if the user deletes text while
         * pre-editing */
        cells_needed++;
    }

    int row_idx = cursor.row;
    int col_idx = cursor.col;
    int ime_ofs = 0;  /* Offset into pre-edit string to start rendering at */

    int cells_left = term->cols - cursor.col;
    int cells_used = min(cells_needed, term->cols);

    /* Adjust start of pre-edit text to the left if string doesn't fit on row */
    if (cells_left < cells_used)
        col_idx -= cells_used - cells_left;

    if (cells_needed > cells_used) {
        int start = seat->ime.preedit.cursor.start;
        int end = seat->ime.preedit.cursor.end;

        if (start == end) {
            /* Ensure *end* of pre-edit string is visible */
            ime_ofs = cells_needed - cells_used;
        } else {
            /* Ensure the *beginning* of the cursor-area is visible */
            ime_ofs = start;

            /* Display as much as possible of the pre-edit string */
            if (cells_needed - ime_ofs < cells_used)
                ime_ofs = cells_needed - cells_used;
        }

        /* Make sure we don't start in the middle of a character */
        while (ime_ofs < cells_needed &&
               seat->ime.preedit.cells[ime_ofs].wc >= CELL_SPACER)
        {
            ime_ofs++;
        }
    }

    xassert(col_idx >= 0);
    xassert(col_idx < term->cols);

    struct row *row = grid_row_in_view(term->grid, row_idx);

    /* Don't start pre-edit text in the middle of a double-width character */
    while (col_idx > 0 && row->cells[col_idx].wc >= CELL_SPACER) {
        cells_used++;
        col_idx--;
    }

    /*
     * Copy original content (render_cell() reads cell data directly
     * from grid), and mark all cells as dirty. This ensures they are
     * re-rendered when the pre-edit text is modified or removed.
     */
    struct cell *real_cells = xmalloc(cells_used * sizeof(real_cells[0]));
    for (int i = 0; i < cells_used; i++) {
        xassert(col_idx + i < term->cols);
        real_cells[i] = row->cells[col_idx + i];
        real_cells[i].attrs.clean = 0;
    }
    row->dirty = true;

    /* Render pre-edit text */
    xassert(seat->ime.preedit.cells[ime_ofs].wc < CELL_SPACER);
    for (int i = 0, idx = ime_ofs; idx < seat->ime.preedit.count; i++, idx++) {
        const struct cell *cell = &seat->ime.preedit.cells[idx];

        if (cell->wc >= CELL_SPACER)
            continue;

        int width = max(1, c32width(cell->wc));
        if (col_idx + i + width > term->cols)
            break;

        row->cells[col_idx + i] = *cell;
        render_cell(term, buf->pix[0], NULL, row, row_idx, col_idx + i, false);
    }

    int start = seat->ime.preedit.cursor.start - ime_ofs;
    int end = seat->ime.preedit.cursor.end - ime_ofs;

    if (!seat->ime.preedit.cursor.hidden) {
        const struct cell *start_cell = &seat->ime.preedit.cells[0];

        pixman_color_t fg = color_hex_to_pixman(term->colors.fg, gamma_correct);
        pixman_color_t bg = color_hex_to_pixman(term->colors.bg, gamma_correct);

        pixman_color_t cursor_color, text_color;
        cursor_colors_for_cell(
            term, start_cell, &fg, &bg, &cursor_color, &text_color, gamma_correct);

        int x = term->margins.left + (col_idx + start) * term->cell_width;
        int y = term->margins.top + row_idx * term->cell_height;

        if (end == start) {
            /* Bar */
            if (start >= 0) {
                struct fcft_font *font = attrs_to_font(term, &start_cell->attrs);
                draw_beam_cursor(term, buf->pix[0], font, &cursor_color, x, y);
            }
            term_ime_set_cursor_rect(term, x, y, 1, term->cell_height);
        }

        else if (end > start) {
            /* Hollow cursor */
            if (start >= 0 && end <= term->cols) {
                int cols = end - start;
                draw_hollow_block(term, buf->pix[0], &cursor_color, x, y, cols);
            }

            term_ime_set_cursor_rect(
                term, x, y, (end - start) * term->cell_width, term->cell_height);
        }
    }

    /* Restore original content (but do not render) */
    for (int i = 0; i < cells_used; i++)
        row->cells[col_idx + i] = real_cells[i];
    free(real_cells);

    const int damage_x = term->margins.left + col_idx * term->cell_width;
    const int damage_y = term->margins.top + row_idx * term->cell_height;
    const int damage_w = cells_used * term->cell_width;
    const int damage_h = term->cell_height;

    wl_surface_damage_buffer(
        term->window->surface.surf,
        damage_x, damage_y, damage_w, damage_h);
}
#endif

static void
render_ime_preedit(struct terminal *term, struct buffer *buf)
{
#if defined(FOOT_IME_ENABLED) && FOOT_IME_ENABLED
    tll_foreach(term->wl->seats, it) {
        if (it->item.kbd_focus == term)
            render_ime_preedit_for_seat(term, &it->item, buf);
    }
#endif
}

static void
render_overlay_single_pixel(struct terminal *term, enum overlay_style style,
                            pixman_color_t color)
{
    struct wayland *wayl = term->wl;
    struct wayl_sub_surface *overlay = &term->window->overlay;
    struct wl_buffer *buf = NULL;

    /*
     * In an ideal world, we'd only update the surface (i.e. commit
     * any changes) if anything has actually changed.
     *
     * For technical reasons, we can't do that, since we can't
     * determine whether the last committed buffer is still valid
     * (i.e. does it correspond to the current overlay style, *and*
     * does last frame's size match the current size?)
     *
     * What we _can_ do is use the fact that single-pixel buffers
     * don't have a size; you have to use a viewport to "size" them.
     *
     * This means we can check if the last frame's overlay style is
     * the same as the current size. If so, then we *know* that the
     * currently attached buffer is valid, and we *don't* have to
     * create a new single-pixel buffer.
     *
     * What we do *not* know if the *size* is still valid. This means
     * we do have to do the viewport calls, and a surface commit.
     *
     * This is still better than *always* creating a new buffer.
     */

    assert(style == OVERLAY_UNICODE_MODE || style == OVERLAY_FLASH);
    assert(wayl->single_pixel_manager != NULL);
    assert(overlay->surface.viewport != NULL);

    quirk_weston_subsurface_desync_on(overlay->sub);

    if (style != term->render.last_overlay_style) {
        buf = wp_single_pixel_buffer_manager_v1_create_u32_rgba_buffer(
            wayl->single_pixel_manager,
            (double)color.red / 0xffff * 0xffffffff,
            (double)color.green / 0xffff * 0xffffffff,
            (double)color.blue / 0xffff * 0xffffffff,
            (double)color.alpha / 0xffff * 0xffffffff);

        wl_surface_set_buffer_scale(overlay->surface.surf, 1);
        wl_surface_attach(overlay->surface.surf, buf, 0, 0);
    }

    wp_viewport_set_destination(
        overlay->surface.viewport,
        roundf(term->width / term->scale),
        roundf(term->height / term->scale));

    wl_subsurface_set_position(overlay->sub, 0, 0);

    wl_surface_damage_buffer(
        overlay->surface.surf, 0, 0, term->width, term->height);

    wl_surface_commit(overlay->surface.surf);
    quirk_weston_subsurface_desync_off(overlay->sub);

    term->render.last_overlay_style = style;

    if (buf != NULL) {
        wl_buffer_destroy(buf);
    }
}

void
render_overlay(struct terminal *term)
{
    struct wayl_sub_surface *overlay = &term->window->overlay;
    const bool unicode_mode_active = term->unicode_mode.active;

    const enum overlay_style style =
        term->is_searching ? OVERLAY_SEARCH :
        term->flash.active ? OVERLAY_FLASH :
        unicode_mode_active ? OVERLAY_UNICODE_MODE :
        OVERLAY_NONE;

    if (likely(style == OVERLAY_NONE)) {
        if (term->render.last_overlay_style != OVERLAY_NONE) {
            /* Unmap overlay sub-surface */
            wl_surface_attach(overlay->surface.surf, NULL, 0, 0);
            wl_surface_commit(overlay->surface.surf);
            term->render.last_overlay_style = OVERLAY_NONE;
            term->render.last_overlay_buf = NULL;
        }
        return;
    }

    pixman_color_t color;

    switch (style) {
    case OVERLAY_SEARCH:
    case OVERLAY_UNICODE_MODE:
        color = (pixman_color_t){0, 0, 0, 0x7fff};
        break;

    case OVERLAY_FLASH:
        color = color_hex_to_pixman_with_alpha(
                term->conf->colors.flash,
                term->conf->colors.flash_alpha,
                wayl_do_linear_blending(term->wl, term->conf));
        break;

    case OVERLAY_NONE:
        xassert(false);
        break;
    }

    const bool single_pixel =
        (style == OVERLAY_UNICODE_MODE || style == OVERLAY_FLASH) &&
        term->wl->single_pixel_manager != NULL &&
        overlay->surface.viewport != NULL;

    if (single_pixel) {
        render_overlay_single_pixel(term, style, color);
        return;
    }

    struct buffer *buf = shm_get_buffer(
        term->render.chains.overlay, term->width, term->height, true);
    pixman_image_set_clip_region32(buf->pix[0], NULL);

    /* Bounding rectangle of damaged areas - for wl_surface_damage_buffer() */
    pixman_box32_t damage_bounds;

    if (style == OVERLAY_SEARCH) {
        /*
         * When possible, we only update the areas that have *changed*
         * since the last frame. That means:
         *
         *  - clearing/erasing cells that are now selected, but weren't
         *    in the last frame
         *  - dimming cells that were selected, but aren't anymore
         *
         * To do this, we save the last frame's selected cells as a
         * pixman region.
         *
         * Then, we calculate the corresponding region for this
         * frame's selected cells.
         *
         * Last frame's region minus this frame's region gives us the
         * region that needs to be *dimmed* in this frame
         *
         * This frame's region minus last frame's region gives us the
         * region that needs to be *cleared* in this frame.
         *
         * Finally, the union of the two "diff" regions above, gives
         * us the total region affected by a change, in either way. We
         * use this as the bounding box for the
         * wl_surface_damage_buffer() call.
         */
        pixman_region32_t *see_through = &term->render.last_overlay_clip;
        pixman_region32_t old_see_through;
        const bool buffer_reuse =
            buf == term->render.last_overlay_buf &&
            style == term->render.last_overlay_style &&
            buf->age == 0;

        if (!buffer_reuse) {
            /* Can't reuse last frame's damage - set to full window,
             * to ensure *everything* is updated */
            pixman_region32_init_rect(
                &old_see_through, 0, 0, buf->width, buf->height);
        } else {
            /* Use last frame's saved region */
            pixman_region32_init(&old_see_through);
            pixman_region32_copy(&old_see_through, see_through);
        }

        pixman_region32_clear(see_through);

        /* Build region consisting of all current search matches */
        struct search_match_iterator iter = search_matches_new_iter(term);
        for (struct range match = search_matches_next(&iter);
             match.start.row >= 0;
             match = search_matches_next(&iter))
        {
            int r = match.start.row;
            int start_col = match.start.col;
            const int end_row = match.end.row;

            while (true) {
                const int end_col =
                    r == end_row ? match.end.col : term->cols - 1;

                int x = term->margins.left + start_col * term->cell_width;
                int y = term->margins.top + r * term->cell_height;
                int width = (end_col + 1 - start_col) * term->cell_width;
                int height = 1 * term->cell_height;

                pixman_region32_union_rect(
                    see_through, see_through, x, y, width, height);

                if (++r > end_row)
                    break;

                start_col = 0;
            }
        }

        /* Areas that need to be cleared: cells that were dimmed in
         * the last frame but is now see-through */
        pixman_region32_t new_see_through;
        pixman_region32_init(&new_see_through);

        if (buffer_reuse)
            pixman_region32_subtract(&new_see_through, see_through, &old_see_through);
        else {
            /* Buffer content is unknown - explicitly clear *all*
             * current see-through areas */
            pixman_region32_copy(&new_see_through, see_through);
        }
        pixman_image_set_clip_region32(buf->pix[0], &new_see_through);

        /* Areas that need to be dimmed: cells that were cleared in
         * the last frame but is not anymore */
        pixman_region32_t new_dimmed;
        pixman_region32_init(&new_dimmed);
        pixman_region32_subtract(&new_dimmed, &old_see_through, see_through);
        pixman_region32_fini(&old_see_through);

        /* Total affected area */
        pixman_region32_t damage;
        pixman_region32_init(&damage);
        pixman_region32_union(&damage, &new_see_through, &new_dimmed);
        damage_bounds = damage.extents;

        /* Clear cells that became selected in this frame. */
        pixman_image_fill_rectangles(
            PIXMAN_OP_SRC, buf->pix[0], &(pixman_color_t){0}, 1,
            &(pixman_rectangle16_t){0, 0, term->width, term->height});

        /* Set clip region for the newly dimmed cells. The actual
         * paint call is done below */
        pixman_image_set_clip_region32(buf->pix[0], &new_dimmed);

        pixman_region32_fini(&new_see_through);
        pixman_region32_fini(&new_dimmed);
        pixman_region32_fini(&damage);
    }

    else if (buf == term->render.last_overlay_buf &&
             style == term->render.last_overlay_style)
    {
        xassert(style == OVERLAY_FLASH || style == OVERLAY_UNICODE_MODE);
        shm_did_not_use_buf(buf);
        return;
    } else {
        pixman_image_set_clip_region32(buf->pix[0], NULL);
        damage_bounds = (pixman_box32_t){0, 0, buf->width, buf->height};
    }

    pixman_image_fill_rectangles(
        PIXMAN_OP_SRC, buf->pix[0], &color, 1,
        &(pixman_rectangle16_t){0, 0, term->width, term->height});

    quirk_weston_subsurface_desync_on(overlay->sub);
    wayl_surface_scale(
        term->window, &overlay->surface, buf, term->scale);
    wl_subsurface_set_position(overlay->sub, 0, 0);
    wl_surface_attach(overlay->surface.surf, buf->wl_buf, 0, 0);

    wl_surface_damage_buffer(
        overlay->surface.surf,
        damage_bounds.x1, damage_bounds.y1,
        damage_bounds.x2 - damage_bounds.x1,
        damage_bounds.y2 - damage_bounds.y1);

    wl_surface_commit(overlay->surface.surf);
    quirk_weston_subsurface_desync_off(overlay->sub);

    buf->age = 0;
    term->render.last_overlay_buf = buf;
    term->render.last_overlay_style = style;
}

int
render_worker_thread(void *_ctx)
{
    struct render_worker_context *ctx = _ctx;
    struct terminal *term = ctx->term;
    const int my_id = ctx->my_id;
    free(ctx);

    sigset_t mask;
    sigfillset(&mask);
    pthread_sigmask(SIG_SETMASK, &mask, NULL);

    char proc_title[16];
    snprintf(proc_title, sizeof(proc_title), "foot:render:%d", my_id);

    if (pthread_setname_np(pthread_self(), proc_title) < 0)
        LOG_ERRNO("render worker %d: failed to set process title", my_id);

    sem_t *start = &term->render.workers.start;
    sem_t *done = &term->render.workers.done;
    mtx_t *lock = &term->render.workers.lock;

    while (true) {
        sem_wait(start);

        struct buffer *buf = term->render.workers.buf;

        bool frame_done = false;

        /* Translate offset-relative cursor row to view-relative */
        struct coord cursor = {-1, -1};
        if (!term->hide_cursor) {
            cursor = term->grid->cursor.point;
            cursor.row += term->grid->offset;
            cursor.row -= term->grid->view;
            cursor.row &= term->grid->num_rows - 1;
        }

        while (!frame_done) {
            mtx_lock(lock);
            xassert(tll_length(term->render.workers.queue) > 0);

            int row_no = tll_pop_front(term->render.workers.queue);
            mtx_unlock(lock);

            switch (row_no) {
            default: {
                struct row *row = grid_row_in_view(term->grid, row_no);
                int cursor_col = cursor.row == row_no ? cursor.col : -1;

                render_row(term, buf->pix[my_id], &buf->dirty[my_id],
                           row, row_no, cursor_col);
                break;
            }

            case -1:
                frame_done = true;
                sem_post(done);
                break;

            case -2:
                return 0;

            case -3: {
                if (term->conf->tweak.render_timer != RENDER_TIMER_NONE)
                    clock_gettime(CLOCK_MONOTONIC, &term->render.workers.preapplied_damage.start);

                mtx_lock(&term->render.workers.preapplied_damage.lock);
                buf = term->render.workers.preapplied_damage.buf;
                xassert(buf != NULL);

                if (likely(term->render.last_buf != NULL)) {
                    mtx_unlock(&term->render.workers.preapplied_damage.lock);

                    pixman_region32_t dmg;
                    pixman_region32_init(&dmg);

                    if (buf->age == 0)
                        ; /* No need to do anything */
                    else if (buf->age == 1)
                        pixman_region32_copy(&dmg,
                                             &term->render.last_buf->dirty[0]);
                    else
                        pixman_region32_init_rect(&dmg, 0, 0, buf->width,
                                                  buf->height);

                    pixman_image_set_clip_region32(buf->pix[my_id], &dmg);
                    pixman_image_composite32(PIXMAN_OP_SRC,
                                             term->render.last_buf->pix[my_id],
                                             NULL, buf->pix[my_id], 0, 0, 0, 0, 0,
                                             0, buf->width, buf->height);

                    pixman_region32_fini(&dmg);

                    buf->age = 0;
                    shm_unref(term->render.last_buf);
                    shm_addref(buf);
                    term->render.last_buf = buf;

                    mtx_lock(&term->render.workers.preapplied_damage.lock);
                }

                term->render.workers.preapplied_damage.buf = NULL;
                cnd_signal(&term->render.workers.preapplied_damage.cond);
                mtx_unlock(&term->render.workers.preapplied_damage.lock);

                if (term->conf->tweak.render_timer != RENDER_TIMER_NONE)
                    clock_gettime(CLOCK_MONOTONIC, &term->render.workers.preapplied_damage.stop);

                frame_done = true;
                break;
            }
            }
        }
    };

    return -1;
}

static void
wait_for_preapply_damage(struct terminal *term)
{
    if (!term->render.preapply_last_frame_damage)
        return;
    if (term->render.workers.preapplied_damage.buf == NULL)
        return;

    mtx_lock(&term->render.workers.preapplied_damage.lock);
    while (term->render.workers.preapplied_damage.buf != NULL) {
        cnd_wait(&term->render.workers.preapplied_damage.cond,
                 &term->render.workers.preapplied_damage.lock);
    }
    mtx_unlock(&term->render.workers.preapplied_damage.lock);
}

struct csd_data
get_csd_data(const struct terminal *term, enum csd_surface surf_idx)
{
    xassert(term->window->csd_mode == CSD_YES);

    const bool borders_visible = wayl_win_csd_borders_visible(term->window);
    const bool title_visible = wayl_win_csd_titlebar_visible(term->window);

    const float scale = term->scale;

    const int border_width = borders_visible
        ? roundf(term->conf->csd.border_width * scale) : 0;

    const int title_height = title_visible
        ? roundf(term->conf->csd.title_height * scale) : 0;

    const int button_width = title_visible
        ? roundf(term->conf->csd.button_width * scale) : 0;

    int remaining_width = term->width;

    const int button_close_width = remaining_width >= button_width ? button_width : 0;
    remaining_width -= button_close_width;
    const int button_close_start = remaining_width;

    const int button_maximize_width = remaining_width >= button_width &&
        term->window->wm_capabilities.maximize ? button_width : 0;
    remaining_width -= button_maximize_width;
    const int button_maximize_start = remaining_width;

    const int button_minimize_width = remaining_width >= button_width &&
        term->window->wm_capabilities.minimize ? button_width : 0;
    remaining_width -= button_minimize_width;
    const int button_minimize_start = remaining_width;

    /*
     * With fractional scaling, we must ensure the offset, when
     * divided by the scale (in set_position()), and the scaled back
     * (by the compositor), matches the actual pixel count made up by
     * the titlebar and the border.
     */
    const int top_offset = roundf(
        scale * (roundf(-title_height / scale) - roundf(border_width / scale)));

    const int top_bottom_width = roundf(
        scale * (roundf(term->width / scale) + 2 * roundf(border_width / scale)));

    const int left_right_height = roundf(
        scale * (roundf(title_height / scale) + roundf(term->height / scale)));

    switch (surf_idx) {
    case CSD_SURF_TITLE:  return (struct csd_data){            0, -title_height,      term->width,      title_height};
    case CSD_SURF_LEFT:   return (struct csd_data){-border_width, -title_height,     border_width, left_right_height};
    case CSD_SURF_RIGHT:  return (struct csd_data){  term->width, -title_height,     border_width, left_right_height};
    case CSD_SURF_TOP:    return (struct csd_data){-border_width,    top_offset, top_bottom_width,      border_width};
    case CSD_SURF_BOTTOM: return (struct csd_data){-border_width,  term->height, top_bottom_width,      border_width};

    /* Positioned relative to CSD_SURF_TITLE */
    case CSD_SURF_MINIMIZE: return (struct csd_data){button_minimize_start, 0, button_minimize_width, title_height};
    case CSD_SURF_MAXIMIZE: return (struct csd_data){button_maximize_start, 0, button_maximize_width, title_height};
    case CSD_SURF_CLOSE:    return (struct csd_data){   button_close_start, 0,    button_close_width, title_height};

    case CSD_SURF_COUNT:
        break;
    }

    BUG("Invalid csd_surface type");
    return (struct csd_data){0};
}

static void
csd_commit(struct terminal *term, struct wayl_surface *surf, struct buffer *buf)
{
    wayl_surface_scale(term->window, surf, buf, term->scale);
    wl_surface_attach(surf->surf, buf->wl_buf, 0, 0);
    wl_surface_damage_buffer(surf->surf, 0, 0, buf->width, buf->height);
    wl_surface_commit(surf->surf);
}

static void
render_csd_part(struct terminal *term,
                struct wl_surface *surf, struct buffer *buf,
                int width, int height, pixman_color_t *color)
{
    xassert(term->window->csd_mode == CSD_YES);

    pixman_image_fill_rectangles(
        PIXMAN_OP_SRC, buf->pix[0], color, 1,
        &(pixman_rectangle16_t){0, 0, buf->width, buf->height});
}

static void
render_osd(struct terminal *term, const struct wayl_sub_surface *sub_surf,
           struct fcft_font *font, struct buffer *buf,
           const char32_t *text, uint32_t _fg, uint32_t _bg,
           unsigned x)
{
    pixman_region32_t clip;
    pixman_region32_init_rect(&clip, 0, 0, buf->width, buf->height);
    pixman_image_set_clip_region32(buf->pix[0], &clip);
    pixman_region32_fini(&clip);

    const bool gamma_correct = wayl_do_linear_blending(term->wl, term->conf);
    uint16_t alpha = _bg >> 24 | (_bg >> 24 << 8);
    pixman_color_t bg = color_hex_to_pixman_with_alpha(_bg, alpha, gamma_correct);
    pixman_image_fill_rectangles(
        PIXMAN_OP_SRC, buf->pix[0], &bg, 1,
        &(pixman_rectangle16_t){0, 0, buf->width, buf->height});

    pixman_color_t fg = color_hex_to_pixman(_fg, gamma_correct);
    const int x_ofs = term->font_x_ofs;

    const size_t len = c32len(text);
    struct fcft_text_run *text_run = NULL;
    const struct fcft_glyph **glyphs = NULL;
    const struct fcft_glyph *_glyphs[len];
    size_t glyph_count = 0;

    if (fcft_capabilities() & FCFT_CAPABILITY_TEXT_RUN_SHAPING) {
        text_run = fcft_rasterize_text_run_utf32(
            font, len, (const char32_t *)text, term->font_subpixel);

        if (text_run != NULL) {
            glyphs = text_run->glyphs;
            glyph_count = text_run->count;
        }
    }

    if (glyphs == NULL) {
        for (size_t i = 0; i < len; i++) {
            const struct fcft_glyph *glyph = fcft_rasterize_char_utf32(
                font, text[i], term->font_subpixel);

            if (glyph == NULL)
                continue;

            _glyphs[glyph_count++] = glyph;
        }

        glyphs = _glyphs;
    }

    pixman_image_t *src = pixman_image_create_solid_fill(&fg);

    /* Calculate baseline  */
    unsigned y;
    {
        const int line_height = buf->height;
        const int font_height = max(font->height, font->ascent + font->descent);
        const int glyph_top_y = round((line_height - font_height) / 2.);
        y = term->font_y_ofs + glyph_top_y + font->ascent;
    }

    for (size_t i = 0; i < glyph_count; i++) {
        const struct fcft_glyph *glyph = glyphs[i];

        if (unlikely(glyph->is_color_glyph)) {
            pixman_image_composite32(
                PIXMAN_OP_OVER, glyph->pix, NULL, buf->pix[0], 0, 0, 0, 0,
                x + x_ofs + glyph->x, y - glyph->y,
                glyph->width, glyph->height);
        } else {
            pixman_image_composite32(
                PIXMAN_OP_OVER, src, glyph->pix, buf->pix[0], 0, 0, 0, 0,
                x + x_ofs + glyph->x, y - glyph->y,
                glyph->width, glyph->height);
        }

        x += glyph->advance.x;
    }

    fcft_text_run_destroy(text_run);
    pixman_image_unref(src);
    pixman_image_set_clip_region32(buf->pix[0], NULL);

    quirk_weston_subsurface_desync_on(sub_surf->sub);
    wayl_surface_scale(term->window, &sub_surf->surface, buf, term->scale);
    wl_surface_attach(sub_surf->surface.surf, buf->wl_buf, 0, 0);
    wl_surface_damage_buffer(sub_surf->surface.surf, 0, 0, buf->width, buf->height);

    if (alpha == 0xffff) {
        struct wl_region *region = wl_compositor_create_region(term->wl->compositor);
        if (region != NULL) {
            wl_region_add(region, 0, 0, buf->width, buf->height);
            wl_surface_set_opaque_region(sub_surf->surface.surf, region);
            wl_region_destroy(region);
        }
    } else
        wl_surface_set_opaque_region(sub_surf->surface.surf, NULL);

    wl_surface_commit(sub_surf->surface.surf);
    quirk_weston_subsurface_desync_off(sub_surf->sub);
}

static void
render_csd_title(struct terminal *term, const struct csd_data *info,
                 struct buffer *buf)
{
    xassert(term->window->csd_mode == CSD_YES);

    struct wayl_sub_surface *surf = &term->window->csd.surface[CSD_SURF_TITLE];
    if (info->width == 0 || info->height == 0)
        return;

    uint32_t bg = term->conf->csd.color.title_set
        ? term->conf->csd.color.title
        : 0xffu << 24 | term->conf->colors.fg;
    uint32_t fg = term->conf->csd.color.buttons_set
        ? term->conf->csd.color.buttons
        : term->conf->colors.bg;

    if (!term->visual_focus) {
        bg = color_dim(term, bg);
        fg = color_dim(term, fg);
    }

    char32_t *_title_text = ambstoc32(term->window_title);
    const char32_t *title_text = _title_text != NULL ? _title_text : U"";

    struct wl_window *win = term->window;

    const struct fcft_glyph *M = fcft_rasterize_char_utf32(
        win->csd.font, U'M', term->font_subpixel);

    const int margin = M != NULL ? M->advance.x : win->csd.font->max_advance.x;

    render_osd(term, surf, win->csd.font, buf, title_text, fg, bg, margin);
    csd_commit(term, &surf->surface, buf);
    free(_title_text);
}

static void
render_csd_border(struct terminal *term, enum csd_surface surf_idx,
                  const struct csd_data *info, struct buffer *buf)
{
    xassert(term->window->csd_mode == CSD_YES);
    xassert(surf_idx >= CSD_SURF_LEFT && surf_idx <= CSD_SURF_BOTTOM);

    struct wayl_surface *surf = &term->window->csd.surface[surf_idx].surface;

    if (info->width == 0 || info->height == 0)
        return;

    const bool gamma_correct = wayl_do_linear_blending(term->wl, term->conf);

    {
        /* Fully transparent - no need to do a color space transform */
        pixman_color_t color = color_hex_to_pixman_with_alpha(0, 0, gamma_correct);
        render_csd_part(term, surf->surf, buf, info->width, info->height, &color);
    }

    /*
     * The "visible" border.
     */

    float scale = term->scale;
    int bwidth = (int)roundf(term->conf->csd.border_width * scale);
    int vwidth = (int)roundf(term->conf->csd.border_width_visible * scale); /* Visible size */

    xassert(bwidth >= vwidth);

    if (vwidth > 0) {

        const struct config *conf = term->conf;
        int x = 0, y = 0, w = 0, h = 0;


        switch (surf_idx) {
        case CSD_SURF_TOP:
        case CSD_SURF_BOTTOM:
            x = bwidth - vwidth;
            y = surf_idx == CSD_SURF_TOP ? info->height - vwidth : 0;
            w = info->width - 2 * x;
            h = vwidth;
            break;

        case CSD_SURF_LEFT:
        case CSD_SURF_RIGHT:
            x = surf_idx == CSD_SURF_LEFT ? bwidth - vwidth : 0;
            y = 0;
            w = vwidth;
            h = info->height;
            break;

        case CSD_SURF_TITLE:
        case CSD_SURF_MINIMIZE:
        case CSD_SURF_MAXIMIZE:
        case CSD_SURF_CLOSE:
        case CSD_SURF_COUNT:
            BUG("unexpected CSD surface type");
        }

        xassert(x >= 0);
        xassert(y >= 0);
        xassert(w >= 0);
        xassert(h >= 0);

        xassert(x + w <= info->width);
        xassert(y + h <= info->height);

        uint32_t _color =
            conf->csd.color.border_set ? conf->csd.color.border :
            conf->csd.color.title_set ? conf->csd.color.title :
            0xffu << 24 | term->conf->colors.fg;
        if (!term->visual_focus)
            _color = color_dim(term, _color);

        uint16_t alpha = _color >> 24 | (_color >> 24 << 8);
        pixman_color_t color =
            color_hex_to_pixman_with_alpha(_color, alpha, gamma_correct);

        pixman_image_fill_rectangles(
            PIXMAN_OP_SRC, buf->pix[0], &color, 1,
            &(pixman_rectangle16_t){x, y, w, h});
    }

    csd_commit(term, surf, buf);
}

static pixman_color_t
get_csd_button_fg_color(const struct terminal *term)
{
    const struct config *conf = term->conf;
    uint32_t _color = conf->colors.bg;
    uint16_t alpha = 0xffff;

    if (conf->csd.color.buttons_set) {
        _color = conf->csd.color.buttons;
        alpha = _color >> 24 | (_color >> 24 << 8);
    }

    return color_hex_to_pixman_with_alpha(
        _color, alpha, wayl_do_linear_blending(term->wl, term->conf));
}

static void
render_csd_button_minimize(struct terminal *term, struct buffer *buf)
{
    pixman_color_t color = get_csd_button_fg_color(term);
    pixman_image_t *src = pixman_image_create_solid_fill(&color);

    const int max_height = buf->height / 3;
    const int max_width = buf->width / 3;

    int width = min(max_height, max_width);
    int thick = min(width / 2, 1 * term->scale);

    const int x_margin = (buf->width - width) / 2;
    const int y_margin = (buf->height - width) / 2;

    xassert(x_margin + width - thick >= 0);
    xassert(width - 2 * thick >= 0);
    xassert(y_margin + width - thick >= 0);
    pixman_image_fill_rectangles(
        PIXMAN_OP_SRC, buf->pix[0], &color, 1,
        (pixman_rectangle16_t[]) {
            {x_margin, y_margin + width - thick, width, thick}
    });

    pixman_image_unref(src);
}

static void
render_csd_button_maximize_maximized(
    struct terminal *term, struct buffer *buf)
{
    pixman_color_t color = get_csd_button_fg_color(term);
    pixman_image_t *src = pixman_image_create_solid_fill(&color);

    const int max_height = buf->height / 3;
    const int max_width = buf->width / 3;

    int width = min(max_height, max_width);
    int thick = min(width / 2, 1 * term->scale);

    const int x_margin = (buf->width - width) / 2;
    const int y_margin = (buf->height - width) / 2;
    const int shrink = 1;
    xassert(x_margin + width - thick >= 0);
    xassert(width - 2 * thick >= 0);
    xassert(y_margin + width - thick >= 0);

    pixman_image_fill_rectangles(
        PIXMAN_OP_SRC, buf->pix[0], &color, 4,
        (pixman_rectangle16_t[]){
            {x_margin + shrink, y_margin + shrink, width - 2 * shrink, thick},
            { x_margin + shrink, y_margin + thick, thick, width - 2 * thick - shrink },
            { x_margin + width - thick - shrink, y_margin + thick, thick, width - 2 * thick - shrink },
            { x_margin + shrink, y_margin + width - thick - shrink, width - 2 * shrink, thick }});

    pixman_image_unref(src);

}

static void
render_csd_button_maximize_window(
    struct terminal *term, struct buffer *buf)
{
    pixman_color_t color = get_csd_button_fg_color(term);
    pixman_image_t *src = pixman_image_create_solid_fill(&color);

    const int max_height = buf->height / 3;
    const int max_width = buf->width / 3;

    int width = min(max_height, max_width);
    int thick = min(width / 2, 1 * term->scale);

    const int x_margin = (buf->width - width) / 2;
    const int y_margin = (buf->height - width) / 2;

    xassert(x_margin + width - thick >= 0);
    xassert(width - 2 * thick >= 0);
    xassert(y_margin + width - thick >= 0);

    pixman_image_fill_rectangles(
        PIXMAN_OP_SRC, buf->pix[0], &color, 4,
        (pixman_rectangle16_t[]) {
            {x_margin, y_margin, width, thick},
            { x_margin, y_margin + thick, thick, width - 2 * thick },
            { x_margin + width - thick, y_margin + thick, thick, width - 2 * thick },
            { x_margin, y_margin + width - thick, width, thick }
    });

    pixman_image_unref(src);
}

static void
render_csd_button_maximize(struct terminal *term, struct buffer *buf)
{
    if (term->window->is_maximized)
        render_csd_button_maximize_maximized(term, buf);
    else
        render_csd_button_maximize_window(term, buf);
}

static void
render_csd_button_close(struct terminal *term, struct buffer *buf)
{
    pixman_color_t color = get_csd_button_fg_color(term);
    pixman_image_t *src = pixman_image_create_solid_fill(&color);

    const int max_height = buf->height / 3;
    const int max_width = buf->width / 3;

    int width = min(max_height, max_width);
    int thick = min(width / 2, 1 * term->scale);
    const int x_margin = (buf->width - width) / 2;
    const int y_margin = (buf->height - width) / 2;

    xassert(x_margin + width - thick >= 0);
    xassert(width - 2 * thick >= 0);
    xassert(y_margin + width - thick >= 0);

    pixman_triangle_t tri[4] = {
        {
            .p1 = {
                .x = pixman_int_to_fixed(x_margin),
                .y = pixman_int_to_fixed(y_margin + thick),
            },
            .p2 = {
                .x = pixman_int_to_fixed(x_margin + width - thick),
                .y = pixman_int_to_fixed(y_margin + width),
            },
            .p3 = {
                .x = pixman_int_to_fixed(x_margin + thick),
                .y = pixman_int_to_fixed(y_margin),
            },
        },

        {
            .p1 = {
                .x = pixman_int_to_fixed(x_margin + width),
                .y = pixman_int_to_fixed(y_margin + width - thick),
            },
            .p2 = {
                .x = pixman_int_to_fixed(x_margin + thick),
                .y = pixman_int_to_fixed(y_margin),
            },
            .p3 = {
                .x = pixman_int_to_fixed(x_margin + width - thick),
                .y = pixman_int_to_fixed(y_margin + width),
            },
        },

        {
            .p1 = {
                .x = pixman_int_to_fixed(x_margin),
                .y = pixman_int_to_fixed(y_margin + width - thick),
            },
            .p2 = {
                .x = pixman_int_to_fixed(x_margin + width),
                .y = pixman_int_to_fixed(y_margin + thick),
            },
            .p3 = {
                .x = pixman_int_to_fixed(x_margin + thick),
                .y = pixman_int_to_fixed(y_margin + width),
            },
        },

        {
            .p1 = {
                .x = pixman_int_to_fixed(x_margin + width),
                .y = pixman_int_to_fixed(y_margin + thick),
            },
            .p2 = {
                .x = pixman_int_to_fixed(x_margin),
                .y = pixman_int_to_fixed(y_margin + width - thick),
            },
            .p3 = {
                .x = pixman_int_to_fixed(x_margin + width - thick),
                .y = pixman_int_to_fixed(y_margin),
            },
        },
    };

    pixman_composite_triangles(
        PIXMAN_OP_OVER, src, buf->pix[0], PIXMAN_a1,
        0, 0, 0, 0, 4, tri);

    pixman_image_unref(src);
}

static bool
any_pointer_is_on_button(const struct terminal *term, enum csd_surface csd_surface)
{
    if (unlikely(tll_length(term->wl->seats) == 0))
        return false;

    tll_foreach(term->wl->seats, it) {
        const struct seat *seat = &it->item;

        if (seat->mouse.x < 0)
            continue;
        if (seat->mouse.y < 0)
            continue;

        struct csd_data info = get_csd_data(term, csd_surface);
        if (seat->mouse.x > info.width)
            continue;

        if (seat->mouse.y > info.height)
            continue;
        return true;
    }

    return false;
}

static void
render_csd_button(struct terminal *term, enum csd_surface surf_idx,
                  const struct csd_data *info, struct buffer *buf)
{
    xassert(term->window->csd_mode == CSD_YES);
    xassert(surf_idx >= CSD_SURF_MINIMIZE && surf_idx <= CSD_SURF_CLOSE);

    struct wayl_surface *surf = &term->window->csd.surface[surf_idx].surface;

    if (info->width == 0 || info->height == 0)
        return;

    uint32_t _color;
    uint16_t alpha = 0xffff;
    bool is_active = false;
    bool is_set = false;
    const uint32_t *conf_color = NULL;

    switch (surf_idx) {
    case CSD_SURF_MINIMIZE:
        _color = term->conf->colors.table[4];  /* blue */
        is_set = term->conf->csd.color.minimize_set;
        conf_color = &term->conf->csd.color.minimize;
        is_active = term->active_surface == TERM_SURF_BUTTON_MINIMIZE &&
                    any_pointer_is_on_button(term, CSD_SURF_MINIMIZE);
        break;

    case CSD_SURF_MAXIMIZE:
        _color = term->conf->colors.table[2];  /* green */
        is_set = term->conf->csd.color.maximize_set;
        conf_color = &term->conf->csd.color.maximize;
        is_active = term->active_surface == TERM_SURF_BUTTON_MAXIMIZE &&
                    any_pointer_is_on_button(term, CSD_SURF_MAXIMIZE);
        break;

    case CSD_SURF_CLOSE:
        _color = term->conf->colors.table[1];  /* red */
        is_set = term->conf->csd.color.close_set;
        conf_color = &term->conf->csd.color.quit;
        is_active = term->active_surface == TERM_SURF_BUTTON_CLOSE &&
                    any_pointer_is_on_button(term, CSD_SURF_CLOSE);
        break;

    default:
        BUG("unhandled surface type: %u", (unsigned)surf_idx);
        break;
    }

    if (is_active) {
        if (is_set) {
            _color = *conf_color;
            alpha = _color >> 24 | (_color >> 24 << 8);
        }
    } else {
        _color = 0;
        alpha = 0;
    }

    if (!term->visual_focus)
        _color = color_dim(term, _color);

    const bool gamma_correct = wayl_do_linear_blending(term->wl, term->conf);
    pixman_color_t color = color_hex_to_pixman_with_alpha(_color, alpha, gamma_correct);
    render_csd_part(term, surf->surf, buf, info->width, info->height, &color);

    switch (surf_idx) {
    case CSD_SURF_MINIMIZE: render_csd_button_minimize(term, buf); break;
    case CSD_SURF_MAXIMIZE: render_csd_button_maximize(term, buf); break;
    case CSD_SURF_CLOSE:    render_csd_button_close(term, buf); break;

    default:
        BUG("unhandled surface type: %u", (unsigned)surf_idx);
        break;
    }

    csd_commit(term, surf, buf);
}

static void
render_csd(struct terminal *term)
{
    xassert(term->window->csd_mode == CSD_YES);

    if (term->window->is_fullscreen)
        return;

    const float scale = term->scale;
    struct csd_data infos[CSD_SURF_COUNT];
    int widths[CSD_SURF_COUNT];
    int heights[CSD_SURF_COUNT];

    for (size_t i = 0; i < CSD_SURF_COUNT; i++) {
        infos[i] = get_csd_data(term, i);
        const int x = infos[i].x;
        const int y = infos[i].y;
        const int width = infos[i].width;
        const int height = infos[i].height;

        struct wl_surface *surf = term->window->csd.surface[i].surface.surf;
        struct wl_subsurface *sub = term->window->csd.surface[i].sub;

        xassert(surf != NULL);
        xassert(sub != NULL);

        if (width == 0 || height == 0) {
            widths[i] = heights[i] = 0;
            wl_subsurface_set_position(sub, 0, 0);
            wl_surface_attach(surf, NULL, 0, 0);
            wl_surface_commit(surf);
            continue;
        }

        widths[i] = width;
        heights[i] = height;
        wl_subsurface_set_position(sub, roundf(x / scale), roundf(y / scale));
    }

    struct buffer *bufs[CSD_SURF_COUNT];
    shm_get_many(term->render.chains.csd, CSD_SURF_COUNT, widths, heights, bufs, true);

    for (size_t i = CSD_SURF_LEFT; i <= CSD_SURF_BOTTOM; i++)
        render_csd_border(term, i, &infos[i], bufs[i]);
    for (size_t i = CSD_SURF_MINIMIZE; i <= CSD_SURF_CLOSE; i++)
        render_csd_button(term, i, &infos[i], bufs[i]);
    render_csd_title(term, &infos[CSD_SURF_TITLE], bufs[CSD_SURF_TITLE]);
}

static void
render_scrollback_position(struct terminal *term)
{
    if (term->conf->scrollback.indicator.position == SCROLLBACK_INDICATOR_POSITION_NONE)
        return;

    struct wl_window *win = term->window;

    if (term->grid->view == term->grid->offset) {
        if (win->scrollback_indicator.surface.surf != NULL)
            wayl_win_subsurface_destroy(&win->scrollback_indicator);
        return;
    }

    if (win->scrollback_indicator.surface.surf == NULL) {
        if (!wayl_win_subsurface_new(
                win, &win->scrollback_indicator, false))
        {
            LOG_ERR("failed to create scrollback indicator surface");
            return;
        }
    }

    xassert(win->scrollback_indicator.surface.surf != NULL);
    xassert(win->scrollback_indicator.sub != NULL);

    /* Find absolute row number of the scrollback start */
    int scrollback_start = term->grid->offset + term->rows;
    int empty_rows = 0;
    while (term->grid->rows[scrollback_start & (term->grid->num_rows - 1)] == NULL) {
        scrollback_start++;
        empty_rows++;
    }

    /* Rebase viewport against scrollback start (so that 0 is at
     * the beginning of the scrollback) */
    int rebased_view = term->grid->view - scrollback_start + term->grid->num_rows;
    rebased_view &= term->grid->num_rows - 1;

    /* How much of the scrollback is actually used? */
    int populated_rows = term->grid->num_rows - empty_rows;
    xassert(populated_rows > 0);
    xassert(populated_rows <= term->grid->num_rows);

    /*
     * How far down in the scrollback we are.
     *
     *    0% -> at the beginning of the scrollback
     *  100% -> at the bottom, i.e. where new lines are inserted
     */
    double percent =
        rebased_view + term->rows == populated_rows
        ? 1.0
        : (double)rebased_view / (populated_rows - term->rows);

    char32_t _text[64];
    const char32_t *text = _text;
    int cell_count = 0;

    /* *What* to render */
    switch (term->conf->scrollback.indicator.format) {
    case SCROLLBACK_INDICATOR_FORMAT_PERCENTAGE: {
        char percent_str[8];
        snprintf(percent_str, sizeof(percent_str), "%u%%", (int)(100 * percent));
        mbstoc32(_text, percent_str, ALEN(_text));
        cell_count = 3;
        break;
    }

    case SCROLLBACK_INDICATOR_FORMAT_LINENO: {
        char lineno_str[64];
        snprintf(lineno_str, sizeof(lineno_str), "%d", rebased_view + 1);
        mbstoc32(_text, lineno_str, ALEN(_text));
        cell_count = (int)ceilf(log10f(term->grid->num_rows));
        break;
    }

    case SCROLLBACK_INDICATOR_FORMAT_TEXT:
        text = term->conf->scrollback.indicator.text;
        cell_count = c32len(text);
        break;
    }

    const float scale = term->scale;
    const int margin = (int)roundf(3. * scale);

    int width = margin + cell_count * term->cell_width + margin;
    int height = margin + term->cell_height + margin;

    width = roundf(scale * ceilf(width / scale));
    height = roundf(scale * ceilf(height / scale));

    /* *Where* to render - parent relative coordinates */
    int surf_top = 0;
    switch (term->conf->scrollback.indicator.position) {
    case SCROLLBACK_INDICATOR_POSITION_NONE:
        BUG("Invalid scrollback indicator position type");
        return;

    case SCROLLBACK_INDICATOR_POSITION_FIXED:
        surf_top = term->cell_height - margin;
        break;

    case SCROLLBACK_INDICATOR_POSITION_RELATIVE: {
        int lines = term->rows - 2;  /* Avoid using first and last rows */
        if (term->is_searching) {
            /* Make sure we don't collide with the scrollback search box */
            lines--;
        }

        lines = max(lines, 0);

        int pixels = max(lines * term->cell_height - height + 2 * margin, 0);
        surf_top = term->cell_height - margin + (int)(percent * pixels);
        break;
    }
    }

    int x = term->width - margin - width;
    int y = term->margins.top + surf_top;

    x = roundf(scale * ceilf(x / scale));
    y = roundf(scale * ceilf(y / scale));

    if (y + height > term->height) {
        wl_surface_attach(win->scrollback_indicator.surface.surf, NULL, 0, 0);
        wl_surface_commit(win->scrollback_indicator.surface.surf);
        return;
    }

    struct buffer_chain *chain = term->render.chains.scrollback_indicator;
    struct buffer *buf = shm_get_buffer(chain, width, height, false);

    wl_subsurface_set_position(
        win->scrollback_indicator.sub, roundf(x / scale), roundf(y / scale));

    uint32_t fg = term->colors.table[0];
    uint32_t bg = term->colors.table[8 + 4];
    if (term->conf->colors.use_custom.scrollback_indicator) {
        fg = term->conf->colors.scrollback_indicator.fg;
        bg = term->conf->colors.scrollback_indicator.bg;
    }

    render_osd(
        term,
        &win->scrollback_indicator,
        term->fonts[0], buf, text,
        fg, 0xffu << 24 | bg,
        width - margin - c32len(text) * term->cell_width);
}

static void
render_render_timer(struct terminal *term, struct timespec render_time)
{
    struct wl_window *win = term->window;

    char usecs_str[256];
    double usecs = render_time.tv_sec * 1000000 + render_time.tv_nsec / 1000.0;
    snprintf(usecs_str, sizeof(usecs_str), "%.2f µs", usecs);

    char32_t text[256];
    mbstoc32(text, usecs_str, ALEN(text));

    const float scale = term->scale;
    const int cell_count = c32len(text);
    const int margin = (int)roundf(3. * scale);

    int width = margin + cell_count * term->cell_width + margin;
    int height = margin + term->cell_height + margin;

    width = roundf(scale * ceilf(width / scale));
    height = roundf(scale * ceilf(height / scale));

    struct buffer_chain *chain = term->render.chains.render_timer;
    struct buffer *buf = shm_get_buffer(chain, width, height, false);

    wl_subsurface_set_position(
        win->render_timer.sub,
        roundf(margin / scale),
        roundf((term->margins.top + term->cell_height - margin) / scale));

    render_osd(
        term,
        &win->render_timer,
        term->fonts[0], buf, text,
        term->colors.table[0], 0xffu << 24 | term->colors.table[8 + 1],
        margin);
}

static void frame_callback(
    void *data, struct wl_callback *wl_callback, uint32_t callback_data);

static const struct wl_callback_listener frame_listener = {
    .done = &frame_callback,
};

static void
force_full_repaint(struct terminal *term, struct buffer *buf)
{
    tll_free(term->grid->scroll_damage);
    render_margin(term, buf, 0, term->rows, true);
    term_damage_view(term);
}

static void
reapply_old_damage(struct terminal *term, struct buffer *new, struct buffer *old)
{
    if (new->age > 1) {
        memcpy(new->data, old->data, new->height * new->stride);
        return;
    }

    pixman_region32_t dirty;
    pixman_region32_init(&dirty);

    /*
     * Figure out current frame's damage region
     *
     * If current frame doesn't have any scroll damage, we can simply
     * subtract this frame's damage from the last frame's damage. That
     * way, we don't have to copy areas from the old frame that'll
     * just get overwritten by current frame.
     *
     * Note that this is row based. A "half damaged" row is not
     * excluded. I.e. the entire row will be copied from the old frame
     * to the new, and then when actually rendering the new frame, the
     * updated cells will overwrite parts of the copied row.
     *
     * Since we're scanning the entire viewport anyway, we also track
     * whether *all* cells are to be updated. In this case, just force
     * a full re-rendering, and don't copy anything from the old
     * frame.
     */
    bool full_repaint_needed = true;

    for (int r = 0; r < term->rows; r++) {
        const struct row *row = grid_row_in_view(term->grid, r);

        if (!row->dirty) {
            full_repaint_needed = false;
            continue;
        }

        bool row_all_dirty = true;
        for (int c = 0; c < term->cols; c++) {
            if (row->cells[c].attrs.clean) {
                row_all_dirty = false;
                full_repaint_needed = false;
                break;
            }
        }

        if (row_all_dirty) {
            pixman_region32_union_rect(
                &dirty, &dirty,
                term->margins.left,
                term->margins.top + r * term->cell_height,
                term->width - term->margins.left - term->margins.right,
                term->cell_height);
        }
    }

    if (full_repaint_needed) {
        force_full_repaint(term, new);
        return;
    }

    /*
     * TODO: re-apply last frame's scroll damage
     *
     * We used to do this, but it turned out to be buggy. If we decide
     * to re-add it, this is where to do it. Note that we'd also have
     * to remove the updates to buf->dirty from grid_render_scroll()
     * and grid_render_scroll_reverse().
     */

    if (tll_length(term->grid->scroll_damage) == 0) {
        /*
         * We can only subtract current frame's damage from the old
         * frame's if we don't have any scroll damage.
         *
         * If we do have scroll damage, the damage region we
         * calculated above is not (yet) valid - we need to apply the
         * current frame's scroll damage *first*. This is done later,
         * when rendering the frame.
         */
        pixman_region32_subtract(&dirty, &old->dirty[0], &dirty);
        pixman_image_set_clip_region32(new->pix[0], &dirty);
    } else {
        /* Copy *all* of last frame's damaged areas */
        pixman_image_set_clip_region32(new->pix[0], &old->dirty[0]);
    }

    pixman_image_composite32(
        PIXMAN_OP_SRC, old->pix[0], NULL, new->pix[0],
        0, 0, 0, 0, 0, 0, term->width, term->height);

    pixman_image_set_clip_region32(new->pix[0], NULL);
    pixman_region32_fini(&dirty);
}

static void
dirty_old_cursor(struct terminal *term)
{
    if (term->render.last_cursor.row != NULL && !term->render.last_cursor.hidden) {
        struct row *row = term->render.last_cursor.row;
        struct cell *cell = &row->cells[term->render.last_cursor.col];
        cell->attrs.clean = 0;
        row->dirty = true;
    }

    /* Remember current cursor position, for the next frame */
    term->render.last_cursor.row = grid_row(term->grid, term->grid->cursor.point.row);
    term->render.last_cursor.col = term->grid->cursor.point.col;
    term->render.last_cursor.hidden = term->hide_cursor;
}

static void
dirty_cursor(struct terminal *term)
{
    if (term->hide_cursor)
        return;

    const struct coord *cursor = &term->grid->cursor.point;

    struct row *row = grid_row(term->grid, cursor->row);
    struct cell *cell = &row->cells[cursor->col];
    cell->attrs.clean = 0;
    row->dirty = true;
}

static void
grid_render(struct terminal *term)
{
    if (term->shutdown.in_progress)
        return;

    struct timespec start_time;
    struct timespec start_wait_preapply = {0}, stop_wait_preapply = {0};
    struct timespec start_double_buffering = {0}, stop_double_buffering = {0};

    /* Might be a thread doing pre-applied damage */
    if (unlikely(term->render.preapply_last_frame_damage &&
                 term->render.workers.preapplied_damage.buf != NULL))
    {
        clock_gettime(CLOCK_MONOTONIC, &start_wait_preapply);
        wait_for_preapply_damage(term);
        clock_gettime(CLOCK_MONOTONIC, &stop_wait_preapply);
    }

    if (term->conf->tweak.render_timer != RENDER_TIMER_NONE)
        clock_gettime(CLOCK_MONOTONIC, &start_time);

    xassert(term->width > 0);
    xassert(term->height > 0);

    struct buffer_chain *chain = term->render.chains.grid;
    bool use_alpha = !term->window->is_fullscreen &&
                     term->colors.alpha != 0xffff;
    struct buffer *buf = shm_get_buffer(
        chain, term->width, term->height, use_alpha);

    /* Dirty old and current cursor cell, to ensure they're repainted */
    dirty_old_cursor(term);
    dirty_cursor(term);

    LOG_DBG("buffer age: %u (%p)", buf->age, (void *)buf);

    if (term->render.last_buf == NULL ||
        term->render.last_buf->width != buf->width ||
        term->render.last_buf->height != buf->height ||
        term->render.margins)
    {
        force_full_repaint(term, buf);
    }

    else if (buf->age > 0) {
        LOG_DBG("buffer age: %u (%p)", buf->age, (void *)buf);

        xassert(term->render.last_buf != NULL);
        xassert(term->render.last_buf != buf);
        xassert(term->render.last_buf->width == buf->width);
        xassert(term->render.last_buf->height == buf->height);

        if (++term->render.frames_since_last_immediate_release > 10) {
            static bool have_warned = false;

            if (!term->render.preapply_last_frame_damage &&
                term->conf->tweak.preapply_damage &&
                term->render.workers.count > 0)
            {
                LOG_INFO("enabling pre-applied frame damage");
                term->render.preapply_last_frame_damage = true;
            } else if (!have_warned && !term->render.preapply_last_frame_damage) {
                LOG_WARN("compositor is not releasing buffers immediately; "
                         "expect lower rendering performance");
                have_warned = true;
            }
        }

        clock_gettime(CLOCK_MONOTONIC, &start_double_buffering);
        reapply_old_damage(term, buf, term->render.last_buf);
        clock_gettime(CLOCK_MONOTONIC, &stop_double_buffering);
    } else if (!term->render.preapply_last_frame_damage) {
        term->render.frames_since_last_immediate_release = 0;
    }

    if (term->render.last_buf != NULL) {
        shm_unref(term->render.last_buf);
        term->render.last_buf = NULL;
    }

    term->render.last_buf = buf;
    shm_addref(buf);
    buf->age = 0;


    tll_foreach(term->grid->scroll_damage, it) {
        switch (it->item.type) {
        case DAMAGE_SCROLL:
            if (term->grid->view == term->grid->offset)
                grid_render_scroll(term, buf, &it->item);
            break;

        case DAMAGE_SCROLL_REVERSE:
            if (term->grid->view == term->grid->offset)
                grid_render_scroll_reverse(term, buf, &it->item);
            break;

        case DAMAGE_SCROLL_IN_VIEW:
            grid_render_scroll(term, buf, &it->item);
            break;

        case DAMAGE_SCROLL_REVERSE_IN_VIEW:
            grid_render_scroll_reverse(term, buf, &it->item);
            break;
        }

        tll_remove(term->grid->scroll_damage, it);
    }

    /*
     * Ensure selected cells have their 'selected' bit set. This is
     * normally "automatically" true - the bit is set when the
     * selection is made.
     *
     * However, if the cell is updated (printed to) while the
     * selection is active, the 'selected' bit is cleared. Checking
     * for this and re-setting the bit in term_print() is too
     * expensive performance wise.
     *
     * Instead, we synchronize the selection bits here and now. This
     * makes the performance impact linear to the number of selected
     * cells rather than to the number of updated cells.
     *
     * (note that selection_dirty_cells() will not set the dirty flag
     * on cells where the 'selected' bit is already set)
     */
    selection_dirty_cells(term);

    /* Translate offset-relative row to view-relative, unless cursor
     * is hidden, then we just set it to -1 */
    struct coord cursor = {-1, -1};
    if (!term->hide_cursor) {
        cursor = term->grid->cursor.point;
        cursor.row += term->grid->offset;
        cursor.row -= term->grid->view;
        cursor.row &= term->grid->num_rows - 1;
    }

    if (term->conf->tweak.overflowing_glyphs) {
        /*
         * Pre-pass to dirty cells affected by overflowing glyphs.
         *
         * Given any two pair of cells where the first cell is
         * overflowing into the second, *both* cells must be
         * re-rendered if any one of them is dirty.
         *
         * Thus, given a string of overflowing glyphs, with a single
         * dirty cell in the middle, we need to re-render the entire
         * string.
         */
        for (int r = 0; r < term->rows; r++) {
            struct row *row = grid_row_in_view(term->grid, r);

            if (!row->dirty)
                continue;

            /* Loop row from left to right, looking for dirty cells */
            for (struct cell *cell = &row->cells[0];
                 cell < &row->cells[term->cols];
                 cell++)
            {
                if (cell->attrs.clean)
                    continue;

                /*
                 * Cell is dirty, go back and dirty previous cells, if
                 * they are overflowing.
                 *
                 * As soon as we see a non-overflowing cell we can
                 * stop, since it isn't affecting the string of
                 * overflowing glyphs that follows it.
                 *
                 * As soon as we see a dirty cell, we can stop, since
                 * that means we've already handled it (remember the
                 * outer loop goes from left to right).
                 */
                for (struct cell *c = cell - 1; c >= &row->cells[0]; c--) {
                    if (c->attrs.confined)
                        break;
                    if (!c->attrs.clean)
                        break;
                    c->attrs.clean = false;
                }

                /*
                 * Now move forward, dirtying all cells until we hit a
                 * non-overflowing cell.
                 *
                 * Note that the first non-overflowing cell must be
                 * re-rendered as well, but any cell *after* that is
                 * unaffected by the string of overflowing glyphs
                 * we're dealing with right now.
                 *
                 * For performance, this iterates the *outer* loop's
                 * cell pointer - no point in re-checking all these
                 * glyphs again, in the outer loop.
                 */
                for (; cell < &row->cells[term->cols]; cell++) {
                    cell->attrs.clean = false;
                    if (cell->attrs.confined)
                        break;
                }
            }
        }
    }

#if defined(_DEBUG)
    for (int r = 0; r < term->rows; r++) {
        const struct row *row = grid_row_in_view(term->grid, r);

        if (row->dirty) {
            bool all_clean = true;
            for (int c = 0; c < term->cols; c++) {
                if (!row->cells[c].attrs.clean) {
                    all_clean = false;
                    break;
                }
            }
            if (all_clean)
                BUG("row #%d is dirty, but all cells are marked as clean", r);
        } else {
            for (int c = 0; c < term->cols; c++) {
                if (!row->cells[c].attrs.clean)
                    BUG("row #%d is clean, but cell #%d is dirty", r, c);
            }
        }
    }
#endif

    pixman_region32_t damage;
    pixman_region32_init(&damage);

    render_sixel_images(term, buf->pix[0], &damage, &cursor);


    if (term->render.workers.count > 0) {
        mtx_lock(&term->render.workers.lock);
        term->render.workers.buf = buf;
        for (size_t i = 0; i < term->render.workers.count; i++)
            sem_post(&term->render.workers.start);

        xassert(tll_length(term->render.workers.queue) == 0);
    }

    for (int r = 0; r < term->rows; r++) {
        struct row *row = grid_row_in_view(term->grid, r);

        if (!row->dirty)
            continue;

        row->dirty = false;

        if (term->render.workers.count > 0)
            tll_push_back(term->render.workers.queue, r);

        else {
            /* TODO: damage region */
            int cursor_col = cursor.row == r ? cursor.col : -1;
            render_row(term, buf->pix[0], &damage, row, r, cursor_col);
        }
    }

    /* Signal workers the frame is done */
    if (term->render.workers.count > 0) {
        for (size_t i = 0; i < term->render.workers.count; i++)
            tll_push_back(term->render.workers.queue, -1);
        mtx_unlock(&term->render.workers.lock);

        for (size_t i = 0; i < term->render.workers.count; i++)
            sem_wait(&term->render.workers.done);
        term->render.workers.buf = NULL;
    }

    for (size_t i = 0; i < term->render.workers.count; i++)
        pixman_region32_union(&damage, &damage, &buf->dirty[i + 1]);

    pixman_region32_union(&buf->dirty[0], &buf->dirty[0], &damage);

    {
        int box_count = 0;
        pixman_box32_t *boxes = pixman_region32_rectangles(&damage, &box_count);

        for (size_t i = 0; i < box_count; i++) {
            wl_surface_damage_buffer(
                term->window->surface.surf,
                boxes[i].x1, boxes[i].y1,
                boxes[i].x2 - boxes[i].x1, boxes[i].y2 - boxes[i].y1);
        }
    }

    pixman_region32_fini(&damage);

    render_overlay(term);
    render_ime_preedit(term, buf);
    render_scrollback_position(term);

    if (term->conf->tweak.render_timer != RENDER_TIMER_NONE) {
        struct timespec end_time;
        clock_gettime(CLOCK_MONOTONIC, &end_time);

        struct timespec wait_time;
        timespec_sub(&stop_wait_preapply, &start_wait_preapply, &wait_time);

        struct timespec render_time;
        timespec_sub(&end_time, &start_time, &render_time);

        struct timespec double_buffering_time;
        timespec_sub(&stop_double_buffering, &start_double_buffering, &double_buffering_time);

        struct timespec preapply_damage;
        timespec_sub(&term->render.workers.preapplied_damage.stop,
                     &term->render.workers.preapplied_damage.start,
                     &preapply_damage);

        struct timespec total_render_time;
        timespec_add(&render_time, &double_buffering_time, &total_render_time);
        timespec_add(&wait_time, &total_render_time, &total_render_time);

        switch (term->conf->tweak.render_timer) {
        case RENDER_TIMER_LOG:
        case RENDER_TIMER_BOTH:
            LOG_INFO(
                "frame rendered in %lds %9ldns "
                "(%lds %9ldns wait, %lds %9ldns rendering, %lds %9ldns double buffering) not included: %lds %ldns pre-apply damage",
                (long)total_render_time.tv_sec,
                total_render_time.tv_nsec,
                (long)wait_time.tv_sec,
                wait_time.tv_nsec,
                (long)render_time.tv_sec,
                render_time.tv_nsec,
                (long)double_buffering_time.tv_sec,
                double_buffering_time.tv_nsec,
                (long)preapply_damage.tv_sec,
                preapply_damage.tv_nsec);
            break;

        case RENDER_TIMER_OSD:
        case RENDER_TIMER_NONE:
            break;
        }

        switch (term->conf->tweak.render_timer) {
        case RENDER_TIMER_OSD:
        case RENDER_TIMER_BOTH:
            render_render_timer(term, total_render_time);
            break;

        case RENDER_TIMER_LOG:
        case RENDER_TIMER_NONE:
            break;
        }
    }

    xassert(term->grid->offset >= 0 && term->grid->offset < term->grid->num_rows);
    xassert(term->grid->view >= 0 && term->grid->view < term->grid->num_rows);

    xassert(term->window->frame_callback == NULL);
    term->window->frame_callback = wl_surface_frame(term->window->surface.surf);
    wl_callback_add_listener(term->window->frame_callback, &frame_listener, term);

    wayl_win_scale(term->window, buf);

    if (term->wl->presentation != NULL && term->conf->presentation_timings) {
        struct timespec commit_time;
        clock_gettime(term->wl->presentation_clock_id, &commit_time);

        struct wp_presentation_feedback *feedback = wp_presentation_feedback(
            term->wl->presentation, term->window->surface.surf);

        if (feedback == NULL) {
            LOG_WARN("failed to create presentation feedback");
        } else {
            struct presentation_context *ctx = xmalloc(sizeof(*ctx));
            *ctx = (struct presentation_context){
                .term = term,
                .input.tv_sec = term->render.input_time.tv_sec,
                .input.tv_usec = term->render.input_time.tv_nsec / 1000,
                .commit.tv_sec = commit_time.tv_sec,
                .commit.tv_usec = commit_time.tv_nsec / 1000,
            };

            wp_presentation_feedback_add_listener(
                feedback, &presentation_feedback_listener, ctx);

            term->render.input_time.tv_sec = 0;
            term->render.input_time.tv_nsec = 0;
        }
    }

    if (term->conf->tweak.damage_whole_window) {
        wl_surface_damage_buffer(
            term->window->surface.surf, 0, 0, INT32_MAX, INT32_MAX);
    }

    wl_surface_attach(term->window->surface.surf, buf->wl_buf, 0, 0);
    wl_surface_commit(term->window->surface.surf);
}

static void
render_search_box(struct terminal *term)
{
    xassert(term->window->search.sub != NULL);

    /*
     * We treat the search box pretty much like a row of cells. That
     * is, a glyph is either 1 or 2 (or more) "cells" wide.
     *
     * The search 'length', and 'cursor' (position) is in
     * *characters*, not cells. This means we need to translate from
     * character count to cell count when calculating the length of
     * the search box, where in the search string we should start
     * rendering etc.
     */

#if defined(FOOT_IME_ENABLED) && FOOT_IME_ENABLED
    /* TODO: do we want to/need to handle multi-seat? */
    struct seat *ime_seat = NULL;
    tll_foreach(term->wl->seats, it) {
        if (it->item.kbd_focus == term) {
            ime_seat = &it->item;
            break;
        }
    }

    size_t text_len = term->search.len;
    if (ime_seat != NULL && ime_seat->ime.preedit.text != NULL)
        text_len += c32len(ime_seat->ime.preedit.text);

    char32_t *text = xmalloc((text_len + 1) *  sizeof(char32_t));
    text[0] = U'\0';

    /* Copy everything up to the cursor */
    c32ncpy(text, term->search.buf, term->search.cursor);
    text[term->search.cursor] = U'\0';

    /* Insert pre-edit text at cursor */
    if (ime_seat != NULL && ime_seat->ime.preedit.text != NULL)
        c32cat(text, ime_seat->ime.preedit.text);

    /* And finally everything after the cursor */
    c32ncat(text, &term->search.buf[term->search.cursor],
            term->search.len - term->search.cursor);
#else
    const char32_t *text = term->search.buf;
    const size_t text_len = term->search.len;
#endif

    /* Calculate the width of each character */
    int widths[text_len + 1];
    for (size_t i = 0; i < text_len; i++)
        widths[i] = max(0, c32width(text[i]));
    widths[text_len] = 0;

    const size_t total_cells = c32swidth(text, text_len);
    const size_t wanted_visible_cells = max(20, total_cells);

    const float scale = term->scale;
    xassert(scale >= 1.);
    const size_t margin = (size_t)roundf(3 * scale);

    size_t width = term->width - 2 * margin;
    size_t height = min(
        term->height - 2 * margin,
        margin + 1 * term->cell_height + margin);

    width = roundf(scale * ceilf((term->width - 2 * margin) / scale));
    height = roundf(scale * ceilf(height / scale));

    size_t visible_width = min(
        term->width - 2 * margin,
        margin + wanted_visible_cells * term->cell_width + margin);

    const size_t visible_cells = (visible_width - 2 * margin) / term->cell_width;
    size_t glyph_offset = term->render.search_glyph_offset;

    struct buffer_chain *chain = term->render.chains.search;
    struct buffer *buf = shm_get_buffer(chain, width, height, true);

    pixman_region32_t clip;
    pixman_region32_init_rect(&clip, 0, 0, width, height);
    pixman_image_set_clip_region32(buf->pix[0], &clip);
    pixman_region32_fini(&clip);

#define WINDOW_X(x) (margin + x)
#define WINDOW_Y(y) (term->height - margin - height + y)

    const bool is_match = term->search.match_len == text_len;
    const bool custom_colors = is_match
        ? term->conf->colors.use_custom.search_box_match
        : term->conf->colors.use_custom.search_box_no_match;

    /* Background - yellow on empty/match, red on mismatch (default) */
    const bool gamma_correct = wayl_do_linear_blending(term->wl, term->conf);
    const pixman_color_t color = color_hex_to_pixman(
        is_match
        ? (custom_colors
           ? term->conf->colors.search_box.match.bg
           : term->colors.table[3])
        : (custom_colors
           ? term->conf->colors.search_box.no_match.bg
           : term->colors.table[1]),
        gamma_correct);

    pixman_image_fill_rectangles(
        PIXMAN_OP_SRC, buf->pix[0], &color,
        1, &(pixman_rectangle16_t){width - visible_width, 0, visible_width, height});

    pixman_color_t transparent = color_hex_to_pixman_with_alpha(0, 0, gamma_correct);
    pixman_image_fill_rectangles(
        PIXMAN_OP_SRC, buf->pix[0], &transparent,
        1, &(pixman_rectangle16_t){0, 0, width - visible_width, height});

    struct fcft_font *font = term->fonts[0];
    const int x_left = width - visible_width + margin;
    const int x_ofs = term->font_x_ofs;
    int x = x_left;
    int y = margin;

    pixman_color_t fg = color_hex_to_pixman(
        custom_colors
        ? (is_match
           ? term->conf->colors.search_box.match.fg
           : term->conf->colors.search_box.no_match.fg)
        : term->colors.table[0],
        gamma_correct);

    /* Move offset we start rendering at, to ensure the cursor is visible */
    for (size_t i = 0, cell_idx = 0; i <= term->search.cursor; cell_idx += widths[i], i++) {
        if (i != term->search.cursor)
            continue;

#if (FOOT_IME_ENABLED) && FOOT_IME_ENABLED
        if (ime_seat != NULL && ime_seat->ime.preedit.cells != NULL) {
            if (ime_seat->ime.preedit.cursor.start == ime_seat->ime.preedit.cursor.end) {
                /* All IME's I've seen so far keeps the cursor at
                 * index 0, so ensure the *end* of the pre-edit string
                 * is visible */
                cell_idx += ime_seat->ime.preedit.count;
            } else {
                /* Try to predict in which direction we'll shift the text */
                if (cell_idx + ime_seat->ime.preedit.cursor.start > glyph_offset)
                    cell_idx += ime_seat->ime.preedit.cursor.end;
                else
                    cell_idx += ime_seat->ime.preedit.cursor.start;
            }
        }
#endif

        if (cell_idx < glyph_offset) {
            /* Shift to the *left*, making *this* character the
             * *first* visible one */
            term->render.search_glyph_offset = glyph_offset = cell_idx;
        }

        else if (cell_idx > glyph_offset + visible_cells) {
            /* Shift to the *right*, making *this* character the
             * *last* visible one */
            term->render.search_glyph_offset = glyph_offset =
                cell_idx - min(cell_idx, visible_cells);
        }

        /* Adjust offset if there is free space available */
        if (total_cells - glyph_offset < visible_cells) {
            term->render.search_glyph_offset = glyph_offset =
                total_cells - min(total_cells, visible_cells);
        }

        break;
    }

    /* Ensure offset is at a character boundary */
    for (size_t i = 0, cell_idx = 0; i <= text_len; cell_idx += widths[i], i++) {
        if (cell_idx >= glyph_offset) {
            term->render.search_glyph_offset = glyph_offset = cell_idx;
            break;
        }
    }

    /*
     * Render the search string, starting at 'glyph_offset'. Note that
     * glyph_offset is in cells, not characters
     */
    for (size_t i = 0,
             cell_idx = 0,
             width = widths[i],
             next_cell_idx = width;
         i < text_len;
         i++,
             cell_idx = next_cell_idx,
             width = widths[i],
             next_cell_idx += width)
    {
    /* Convert subsurface coordinates to window coordinates*/
        /* Render cursor */
        if (i == term->search.cursor) {
#if defined(FOOT_IME_ENABLED) && FOOT_IME_ENABLED
            bool have_preedit =
                ime_seat != NULL && ime_seat->ime.preedit.cells != NULL;
            bool hidden =
                ime_seat != NULL && ime_seat->ime.preedit.cursor.hidden;

            if (have_preedit && !hidden) {
                /* Cursor may be outside the visible area:
                 * cell_idx-glyph_offset can be negative */
                int cells_left = visible_cells - max(
                    (ssize_t)(cell_idx - glyph_offset), 0);

                /* If cursor is outside the visible area, we need to
                 * adjust our rectangle's position */
                int start = ime_seat->ime.preedit.cursor.start
                    + min((ssize_t)(cell_idx - glyph_offset), 0);
                int end = ime_seat->ime.preedit.cursor.end
                    + min((ssize_t)(cell_idx - glyph_offset), 0);

                if (start == end) {
                    int count = min(ime_seat->ime.preedit.count, cells_left);

                    /* Underline the entire (visible part of) pre-edit text */
                    draw_underline(term, buf->pix[0], font, &fg, x, y, count);

                    /* Bar-styled cursor, if in the visible area */
                    if (start >= 0 && start <= visible_cells) {
                        draw_beam_cursor(
                            term, buf->pix[0], font, &fg,
                            x + start * term->cell_width, y);
                    }

                    term_ime_set_cursor_rect(term,
                        WINDOW_X(x + start * term->cell_width), WINDOW_Y(y),
                        1, term->cell_height);
                } else {
                    /* Underline everything before and after the cursor */
                    int count1 = min(start, cells_left);
                    int count2 = max(
                        min(ime_seat->ime.preedit.count - ime_seat->ime.preedit.cursor.end,
                            cells_left - end),
                        0);
                    draw_underline(term, buf->pix[0], font, &fg, x, y, count1);
                    draw_underline(term, buf->pix[0], font, &fg, x + end * term->cell_width, y, count2);

                    /* TODO: how do we handle a partially hidden rectangle? */
                    if (start >= 0 && end <= visible_cells) {
                        draw_hollow_block(
                            term, buf->pix[0], &fg, x + start * term->cell_width, y, end - start);
                    }
                    term_ime_set_cursor_rect(term,
                        WINDOW_X(x + start * term->cell_width), WINDOW_Y(y),
                        term->cell_width * (end - start), term->cell_height);
                }
            } else if (!have_preedit)
#endif
            {
                /* Cursor *should* be in the visible area */
                xassert(cell_idx >= glyph_offset);
                xassert(cell_idx <= glyph_offset + visible_cells);
                draw_beam_cursor(term, buf->pix[0], font, &fg, x, y);
                term_ime_set_cursor_rect(
                    term, WINDOW_X(x), WINDOW_Y(y), 1, term->cell_height);
            }
        }

        if (next_cell_idx >= glyph_offset && next_cell_idx - glyph_offset > visible_cells) {
            /* We're now beyond the visible area - nothing more to render */
            break;
        }

        if (cell_idx < glyph_offset) {
            /* We haven't yet reached the visible part of the string */
            cell_idx = next_cell_idx;
            continue;
        }

        const struct fcft_glyph *glyph = fcft_rasterize_char_utf32(
            font, text[i], term->font_subpixel);

        if (glyph == NULL) {
            cell_idx = next_cell_idx;
            continue;
        }

        if (unlikely(glyph->is_color_glyph)) {
            pixman_image_composite32(
                PIXMAN_OP_OVER, glyph->pix, NULL, buf->pix[0], 0, 0, 0, 0,
                x + x_ofs + glyph->x, y + term->font_baseline - glyph->y,
                glyph->width, glyph->height);
        } else {
            int combining_ofs = width == 0
                ? (glyph->x < 0
                   ? width * term->cell_width
                   : (width - 1) * term->cell_width)
                : 0;  /* Not a zero-width character - no additional offset */
            pixman_image_t *src = pixman_image_create_solid_fill(&fg);
            pixman_image_composite32(
                PIXMAN_OP_OVER, src, glyph->pix, buf->pix[0], 0, 0, 0, 0,
                x + x_ofs + combining_ofs + glyph->x,
                y + term->font_baseline - glyph->y,
            glyph->width, glyph->height);
            pixman_image_unref(src);
        }

        x += width * term->cell_width;
        cell_idx = next_cell_idx;
    }

#if defined(FOOT_IME_ENABLED) && FOOT_IME_ENABLED
        if (ime_seat != NULL && ime_seat->ime.preedit.cells != NULL)
            /* Already rendered */;
        else
#endif
        if (term->search.cursor >= term->search.len) {
            draw_beam_cursor(term, buf->pix[0], font, &fg, x, y);
            term_ime_set_cursor_rect(
                term, WINDOW_X(x), WINDOW_Y(y), 1, term->cell_height);
        }

    quirk_weston_subsurface_desync_on(term->window->search.sub);

    /* TODO: this is only necessary on a window resize */
    wl_subsurface_set_position(
        term->window->search.sub,
        roundf(margin / scale),
        roundf(max(0, (int32_t)term->height - height - margin) / scale));

    wayl_surface_scale(term->window, &term->window->search.surface, buf, scale);
    wl_surface_attach(term->window->search.surface.surf, buf->wl_buf, 0, 0);
    wl_surface_damage_buffer(term->window->search.surface.surf, 0, 0, width, height);

    struct wl_region *region = wl_compositor_create_region(term->wl->compositor);
    if (region != NULL) {
        wl_region_add(region, width - visible_width, 0, visible_width, height);
        wl_surface_set_opaque_region(term->window->search.surface.surf, region);
        wl_region_destroy(region);
    }

    wl_surface_commit(term->window->search.surface.surf);
    quirk_weston_subsurface_desync_off(term->window->search.sub);

#if defined(FOOT_IME_ENABLED) && FOOT_IME_ENABLED
    free(text);
#endif
#undef WINDOW_X
#undef WINDOW_Y
}

static void
render_urls(struct terminal *term)
{
    struct wl_window *win = term->window;
    xassert(tll_length(win->urls) > 0);

    const float scale = term->scale;
    const int x_margin = (int)roundf(2 * scale);
    const int y_margin = (int)roundf(1 * scale);

    /* Calculate view start, counted from the *current* scrollback start */
    const int scrollback_end
        = (term->grid->offset + term->rows) & (term->grid->num_rows - 1);
    const int view_start
        = (term->grid->view
           - scrollback_end
           + term->grid->num_rows) & (term->grid->num_rows - 1);
    const int view_end = view_start + term->rows - 1;

    const bool show_url = term->urls_show_uri_on_jump_label;

    /*
     * There can potentially be a lot of URLs.
     *
     * Since each URL is a separate sub-surface, and requires its own
     * SHM buffer, we may be allocating a lot of buffers.
     *
     * SHM buffers normally have their own, private SHM buffer
     * pool. Each pool is mmapped, and thus allocates *at least*
     * 4K. Since URL labels are typically small, we end up using an
     * excessive amount of both virtual and physical memory.
     *
     * For this reason, we instead use shm_get_many(), which uses a
     * single, shared pool for all buffers.
     *
     * To be able to use it, we need to have all the *all* the buffer
     * dimensions up front.
     *
     * Thus, the first iteration through the URLs do the heavy
     * lifting: builds the label contents and calculates both its
     * position and size. But instead of rendering the label
     * immediately, we store the calculated data, and then do a second
     * pass, where we first get all our buffers, and then render to
     * them.
     */

    /* Positioning data + label contents */
    struct {
        const struct wl_url *url;
        char32_t *text;
        int x;
        int y;
    } info[tll_length(win->urls)];

    /* For shm_get_many() */
    int widths[tll_length(win->urls)];
    int heights[tll_length(win->urls)];

    size_t render_count = 0;

    tll_foreach(win->urls, it) {
        const struct url *url = it->item.url;
        const char32_t *key = url->key;
        const size_t entered_key_len = c32len(term->url_keys);

        if (key == NULL) {
            /* TODO: if we decide to use the .text field, we cannot
             * just skip the entire jump label like this */
            continue;
        }

        struct wl_surface *surf = it->item.surf.surface.surf;
        struct wl_subsurface *sub_surf = it->item.surf.sub;

        if (surf == NULL || sub_surf == NULL)
            continue;

        bool hide = false;
        const struct coord *pos = &url->range.start;
        const int _row
            = (pos->row
               - scrollback_end
               + term->grid->num_rows) & (term->grid->num_rows - 1);

        if (_row < view_start || _row > view_end)
            hide = true;
        if (c32len(key) <= entered_key_len)
            hide = true;
        if (c32ncasecmp(term->url_keys, key, entered_key_len) != 0)
            hide = true;

        if (hide) {
            wl_surface_attach(surf, NULL, 0, 0);
            wl_surface_commit(surf);
            continue;
        }

        int col = pos->col;
        int row = pos->row - term->grid->view;
        while (row < 0)
            row += term->grid->num_rows;
        row &= (term->grid->num_rows - 1);

        /* Position label slightly above and to the left */
        int x = col * term->cell_width - 15 * term->cell_width / 10;
        int y = row * term->cell_height - 5 * term->cell_height / 10;

        /* Don't position it outside our window */
        if (x < -term->margins.left)
            x = -term->margins.left;
        if (y < -term->margins.top)
            y = -term->margins.top;

        /* Maximum width of label, in pixels */
        const int max_width =
            term->width - term->margins.left - term->margins.right - x;
        const int max_cols = max_width / term->cell_width;

        const size_t key_len = c32len(key);

        size_t url_len = mbstoc32(NULL, url->url, 0);
        if (url_len == (size_t)-1)
            url_len = 0;

        char32_t url_wchars[url_len + 1];
        mbstoc32(url_wchars, url->url, url_len + 1);

        /* Format label, not yet subject to any size limitations */
        size_t chars = key_len + (show_url ? (2 + url_len) : 0);
        char32_t label[chars + 1];
        label[chars] = U'\0';

        if (show_url) {
            c32cpy(label, key);
            c32cat(label, U": ");
            c32cat(label, url_wchars);
        } else
            c32ncpy(label, key, chars);

        /* Upper case the key characters */
        for (size_t i = 0; i < c32len(key); i++)
            label[i] = toc32upper(label[i]);

        /* Blank already entered key characters */
        for (size_t i = 0; i < entered_key_len; i++)
            label[i] = U' ';

        /*
         * Don't extend outside our window
         *
         * Truncate label so that it doesn't extend outside our
         * window.
         *
         * Do it in a way such that we don't cut the label in the
         * middle of a double-width character.
         */

        int cols = 0;

        for (size_t i = 0; i <= c32len(label); i++) {
            int _cols = c32swidth(label, i);

            if (_cols == (size_t)-1)
                continue;

            if (_cols >= max_cols) {
                if (i > 0)
                    label[i - 1] = U'…';
                label[i] = U'\0';
                cols = max_cols;
                break;
            }
            cols = _cols;
        }

        if (cols == 0)
            continue;

        int width = x_margin + cols * term->cell_width + x_margin;
        int height = y_margin + term->cell_height + y_margin;

        width = roundf(scale * ceilf(width / scale));
        height = roundf(scale * ceilf(height / scale));

        info[render_count].url = &it->item;
        info[render_count].text = xc32dup(label);
        info[render_count].x = x;
        info[render_count].y = y;

        widths[render_count] = width;
        heights[render_count] = height;

        render_count++;
    }

    struct buffer_chain *chain = term->render.chains.url;
    struct buffer *bufs[render_count];
    shm_get_many(chain, render_count, widths, heights, bufs, false);

    uint32_t fg = term->conf->colors.use_custom.jump_label
        ? term->conf->colors.jump_label.fg
        : term->colors.table[0];
    uint32_t bg = term->conf->colors.use_custom.jump_label
        ? term->conf->colors.jump_label.bg
        : term->colors.table[3];

    for (size_t i = 0; i < render_count; i++) {
        const struct wayl_sub_surface *sub_surf = &info[i].url->surf;

        const char32_t *label = info[i].text;
        const int x = info[i].x;
        const int y = info[i].y;

        xassert(sub_surf->surface.surf != NULL);
        xassert(sub_surf->sub != NULL);

        wl_subsurface_set_position(
            sub_surf->sub,
            roundf((term->margins.left + x) / scale),
            roundf((term->margins.top + y) / scale));

        render_osd(
            term, sub_surf, term->fonts[0], bufs[i], label,
            fg, 0xffu << 24 | bg, x_margin);

        free(info[i].text);
    }
}

static void
render_update_title(struct terminal *term)
{
    static const size_t max_len = 2048;

    const char *title = term->window_title != NULL ? term->window_title : "foot";
    char *copy = NULL;

    if (strlen(title) > max_len) {
        copy = xstrndup(title, max_len);
        title = copy;
    }

    xdg_toplevel_set_title(term->window->xdg_toplevel, title);
    free(copy);
}

static void
frame_callback(void *data, struct wl_callback *wl_callback, uint32_t callback_data)
{
    struct terminal *term = data;

    xassert(term->window->frame_callback == wl_callback);
    wl_callback_destroy(wl_callback);
    term->window->frame_callback = NULL;

    bool grid = term->render.pending.grid;
    bool csd = term->render.pending.csd;
    bool search = term->is_searching && term->render.pending.search;
    bool urls = urls_mode_is_active(term) > 0 && term->render.pending.urls;

    term->render.pending.grid = false;
    term->render.pending.csd = false;
    term->render.pending.search = false;
    term->render.pending.urls = false;

    struct grid *original_grid = term->grid;
    if (urls_mode_is_active(term)) {
        xassert(term->url_grid_snapshot != NULL);
        term->grid = term->url_grid_snapshot;
    }

    if (csd && term->window->csd_mode == CSD_YES) {
        quirk_weston_csd_on(term);
        render_csd(term);
        quirk_weston_csd_off(term);
    }

    if (search)
        render_search_box(term);

    if (urls)
        render_urls(term);

    if ((grid && !term->delayed_render_timer.is_armed) || (csd | search | urls))
        grid_render(term);

    tll_foreach(term->wl->seats, it) {
        if (it->item.ime_focus == term)
            ime_update_cursor_rect(&it->item);
    }

    term->grid = original_grid;
}

static void
tiocswinsz(struct terminal *term)
{
    if (term->ptmx >= 0) {
        if (ioctl(term->ptmx, (unsigned int)TIOCSWINSZ,
                     &(struct winsize){
                         .ws_row = term->rows,
                         .ws_col = term->cols,
                         .ws_xpixel = term->cols * term->cell_width,
                         .ws_ypixel = term->rows * term->cell_height}) < 0)
        {
            LOG_ERRNO("TIOCSWINSZ");
        }

        term_send_size_notification(term);
    }
}

static void
delayed_reflow_of_normal_grid(struct terminal *term)
{
    if (term->interactive_resizing.grid == NULL)
        return;

    xassert(term->interactive_resizing.new_rows > 0);

    struct coord *const tracking_points[] = {
        &term->selection.coords.start,
        &term->selection.coords.end,
    };

    /* Reflow the original (since before the resize was started) grid,
     * to the *current* dimensions */
    grid_resize_and_reflow(
        term->interactive_resizing.grid, term,
        term->interactive_resizing.new_rows, term->normal.num_cols,
        term->interactive_resizing.old_screen_rows, term->rows,
        term->selection.coords.end.row >= 0 ? ALEN(tracking_points) : 0,
        tracking_points);

    /* Replace the current, truncated, "normal" grid with the
     * correctly reflowed one */
    grid_free(&term->normal);
    term->normal = *term->interactive_resizing.grid;
    free(term->interactive_resizing.grid);

    term->hide_cursor = term->interactive_resizing.old_hide_cursor;

    /* Reset */
    term->interactive_resizing.grid = NULL;
    term->interactive_resizing.old_screen_rows = 0;
    term->interactive_resizing.new_rows = 0;
    term->interactive_resizing.old_hide_cursor = false;

    /* Invalidate render pointers */
    wait_for_preapply_damage(term);
    shm_unref(term->render.last_buf);
    term->render.last_buf = NULL;
    term->render.last_cursor.row = NULL;

    tll_free(term->normal.scroll_damage);
    sixel_reflow_grid(term, &term->normal);

    if (term->grid == &term->normal) {
        term_damage_view(term);
        render_refresh(term);
    }

    term_ptmx_resume(term);
}

static bool
fdm_tiocswinsz(struct fdm *fdm, int fd, int events, void *data)
{
    struct terminal *term = data;

    if (events & EPOLLIN) {
        tiocswinsz(term);
        delayed_reflow_of_normal_grid(term);
    }

    if (term->window->resize_timeout_fd >= 0) {
        fdm_del(fdm, term->window->resize_timeout_fd);
        term->window->resize_timeout_fd = -1;
    }
    return true;
}

static void
send_dimensions_to_client(struct terminal *term)
{
    struct wl_window *win = term->window;

    if (!win->is_resizing || term->conf->resize_delay_ms == 0) {
        /* Send new dimensions to client immediately */
        tiocswinsz(term);
        delayed_reflow_of_normal_grid(term);

        /* And make sure to reset and deallocate a lingering timer */
        if (win->resize_timeout_fd >= 0) {
            fdm_del(term->fdm, win->resize_timeout_fd);
            win->resize_timeout_fd = -1;
        }
    } else {
        /* Send new dimensions to client "in a while" */
        assert(win->is_resizing && term->conf->resize_delay_ms > 0);

        int fd = win->resize_timeout_fd;
        uint16_t delay_ms = term->conf->resize_delay_ms;
        bool successfully_scheduled = false;

        if (fd < 0) {
            /* Lazy create timer fd */
            fd = timerfd_create(CLOCK_MONOTONIC, TFD_CLOEXEC | TFD_NONBLOCK);
            if (fd < 0)
                LOG_ERRNO("failed to create TIOCSWINSZ timer");
            else if (!fdm_add(term->fdm, fd, EPOLLIN, &fdm_tiocswinsz, term)) {
                close(fd);
                fd = -1;
            }

            win->resize_timeout_fd = fd;
        }

        if (fd >= 0) {
            /* Reset timeout */
            const struct itimerspec timeout = {
                .it_value = {
                    .tv_sec = delay_ms / 1000,
                    .tv_nsec = (delay_ms % 1000) * 1000000,
                },
            };

            if (timerfd_settime(fd, 0, &timeout, NULL) < 0) {
                LOG_ERRNO("failed to arm TIOCSWINSZ timer");
                fdm_del(term->fdm, fd);
                win->resize_timeout_fd = -1;
            } else
                successfully_scheduled = true;
        }

        if (!successfully_scheduled) {
            tiocswinsz(term);
            delayed_reflow_of_normal_grid(term);
        }
    }
}

static void
set_size_from_grid(struct terminal *term, int *width, int *height, int cols, int rows)
{
    int new_width, new_height;

    /* Nominal grid dimensions */
    new_width = cols * term->cell_width;
    new_height = rows * term->cell_height;

    /* Include any configured padding */
    new_width += 2 * term->conf->pad_x * term->scale;
    new_height += 2 * term->conf->pad_y * term->scale;

    /* Round to multiples of scale */
    new_width = round(term->scale * round(new_width / term->scale));
    new_height = round(term->scale * round(new_height / term->scale));

    if (width != NULL)
        *width = new_width;
    if (height != NULL)
        *height = new_height;
}

/* Move to terminal.c? */
bool
render_resize(struct terminal *term, int width, int height, uint8_t opts)
{
    if (term->shutdown.in_progress)
        return false;

    if (!term->window->is_configured)
        return false;

    if (term->cell_width == 0 && term->cell_height == 0)
        return false;

    const bool is_floating =
        !term->window->is_maximized &&
        !term->window->is_fullscreen &&
        !term->window->is_tiled;

    /* Convert logical size to physical size */
    const float scale = term->scale;
    width = round(width * scale);
    height = round(height * scale);

    /* If the grid should be kept, the size should be overridden */
    if (is_floating && (opts & RESIZE_KEEP_GRID)) {
        set_size_from_grid(term, &width, &height, term->cols, term->rows);
    }

    if (width == 0) {
        /* The compositor is letting us choose the width */
        if (term->stashed_width != 0) {
            /* If a default size is requested, prefer the "last used" size */
            width = term->stashed_width;
        } else {
            /* Otherwise, use a user-configured size */
            switch (term->conf->size.type) {
            case CONF_SIZE_PX:
                width = term->conf->size.width;

                if (wayl_win_csd_borders_visible(term->window))
                    width -= 2 * term->conf->csd.border_width_visible;

                width *= scale;
                break;

            case CONF_SIZE_CELLS:
                set_size_from_grid(term, &width, NULL,
                                   term->conf->size.width, term->conf->size.height);
                break;
            }
        }
    }

    if (height == 0) {
        /* The compositor is letting us choose the height */
        if (term->stashed_height != 0) {
            /* If a default size is requested, prefer the "last used" size */
            height = term->stashed_height;
        } else {
            /* Otherwise, use a user-configured size */
            switch (term->conf->size.type) {
            case CONF_SIZE_PX:
                height = term->conf->size.height;

                /* Take CSDs into account */
                if (wayl_win_csd_titlebar_visible(term->window))
                    height -= term->conf->csd.title_height;

                if (wayl_win_csd_borders_visible(term->window))
                    height -= 2 * term->conf->csd.border_width_visible;

                height *= scale;
                break;

            case CONF_SIZE_CELLS:
                set_size_from_grid(term, NULL, &height,
                                   term->conf->size.width, term->conf->size.height);
                break;
            }
        }
    }

    /* Don't shrink grid too much */
    const int min_cols = 1;
    const int min_rows = 1;

    /* Minimum window size (must be divisible by the scaling factor)*/
    const int min_width = roundf(scale * ceilf((min_cols * term->cell_width) / scale));
    const int min_height = roundf(scale * ceilf((min_rows * term->cell_height) / scale));

    width = max(width, min_width);
    height = max(height, min_height);

    /* Padding */
    const int max_pad_x = (width - min_width) / 2;
    const int max_pad_y = (height - min_height) / 2;
    const int pad_x = min(max_pad_x, scale * term->conf->pad_x);
    const int pad_y = min(max_pad_y, scale * term->conf->pad_y);

    if (is_floating &&
        (opts & RESIZE_BY_CELLS) &&
        term->conf->resize_by_cells)
    {
        /* If resizing in cell increments, restrict the width and height */
        width = ((width - 2 * pad_x) / term->cell_width) * term->cell_width + 2 * pad_x;
        width = max(min_width, roundf(scale * roundf(width / scale)));

        height = ((height - 2 * pad_y) / term->cell_height) * term->cell_height + 2 * pad_y;
        height = max(min_height, roundf(scale * roundf(height / scale)));
    }

    if (!(opts & RESIZE_FORCE) &&
        width == term->width &&
        height == term->height &&
        scale == term->scale)
    {
        return false;
    }

    /* Cancel an application initiated "Synchronized Update" */
    term_disable_app_sync_updates(term);

    /* Drop out of URL mode */
    urls_reset(term);

    LOG_DBG("resized: size=%dx%d (scale=%.2f)", width, height, term->scale);
    term->width = width;
    term->height = height;

    /* Screen rows/cols before resize */
    int old_cols = term->cols;
    int old_rows = term->rows;

    /* Screen rows/cols after resize */
    const int new_cols = (term->width - 2 * pad_x) / term->cell_width;
    const int new_rows = (term->height - 2 * pad_y) / term->cell_height;

    /*
     * Requirements for scrollback:
     *
     *   a) total number of rows (visible + scrollback history) must be
     *      a power of two
     *   b) must be representable in a plain int (signed)
     *
     * This means that on a "normal" system, where ints are 32-bit,
     * the largest possible scrollback size is 1073741824 (0x40000000,
     * 1 << 30).
     *
     * The largest *signed* int is 2147483647 (0x7fffffff), which is
     * *not* a power of two.
     *
     * Note that these are theoretical limits. Most of the time,
     * you'll get a memory allocation failure when trying to allocate
     * the grid array.
     */
    const unsigned max_scrollback = (INT_MAX >> 1) + 1;
    const unsigned scrollback_lines_not_yet_power_of_two =
        min((uint64_t)term->render.scrollback_lines + new_rows - 1, max_scrollback);

    /* Grid rows/cols after resize */
    const int new_normal_grid_rows =
        min(1u << (32 - __builtin_clz(scrollback_lines_not_yet_power_of_two)),
            max_scrollback);
    const int new_alt_grid_rows =
        min(1u << (32 - __builtin_clz(new_rows)), max_scrollback);

    LOG_DBG("grid rows: %d", new_normal_grid_rows);

    xassert(new_cols >= 1);
    xassert(new_rows >= 1);

    /* Margins */
    const int grid_width = new_cols * term->cell_width;
    const int grid_height = new_rows * term->cell_height;
    const int total_x_pad = term->width - grid_width;
    const int total_y_pad = term->height - grid_height;

    const enum center_when center = term->conf->center_when;
    const bool centered_padding =
        center == CENTER_ALWAYS ||
        (center == CENTER_MAXIMIZED_AND_FULLSCREEN &&
         (term->window->is_fullscreen || term->window->is_maximized)) ||
        (center == CENTER_FULLSCREEN && term->window->is_fullscreen);

    if (centered_padding && !term->window->is_resizing) {
        term->margins.left = total_x_pad / 2;
        term->margins.top = total_y_pad / 2;
    } else {
        term->margins.left = pad_x;
        term->margins.top = pad_y;
    }
    term->margins.right = total_x_pad - term->margins.left;
    term->margins.bottom = total_y_pad - term->margins.top;

    xassert(term->margins.left >= pad_x);
    xassert(term->margins.right >= pad_x);
    xassert(term->margins.top >= pad_y);
    xassert(term->margins.bottom >= pad_y);

    if (new_cols == old_cols && new_rows == old_rows) {
        LOG_DBG("grid layout unaffected; skipping reflow");
        term->interactive_resizing.new_rows = new_normal_grid_rows;
        goto damage_view;
    }


    /*
     * Since text reflow is slow, don't do it *while* resizing. Only
     * do it when done, or after "pausing" the resize for sufficiently
     * long. We reuse the TIOCSWINSZ timer to handle this. See
     * send_dimensions_to_client() and fdm_tiocswinsz().
     *
     * To be able to do the final reflow correctly, we need a copy of
     * the original grid, before the resize started.
     */
    if (term->window->is_resizing && term->conf->resize_delay_ms > 0) {
        if (term->interactive_resizing.grid == NULL) {
            term_ptmx_pause(term);

            /* Stash the current 'normal' grid, as-is, to be used when
             * doing the final reflow */
            term->interactive_resizing.old_screen_rows = term->rows;
            term->interactive_resizing.old_cols = term->cols;
            term->interactive_resizing.old_hide_cursor = term->hide_cursor;
            term->interactive_resizing.grid = xmalloc(sizeof(*term->interactive_resizing.grid));
            *term->interactive_resizing.grid = term->normal;

            if (term->grid == &term->normal)
                term->interactive_resizing.selection_coords = term->selection.coords;
        } else {
            /* We'll replace the current temporary grid, with a new
             * one (again based on the original grid) */
            grid_free(&term->normal);
        }

        struct grid *orig = term->interactive_resizing.grid;

        /*
         * Copy the current viewport (of the original grid) to a new
         * grid that will be used during the resize. For now, throw
         * away sixels and OSC-8 URLs. They'll be "restored" when we
         * do the final reflow.
         *
         * Note that OSC-8 URLs are perfectly ok to throw away; they
         * cannot be interacted with during the resize. And, even if
         * url.osc8-underline=always, the "underline" attribute is
         * part of the cell, not the URI struct (and thus our faked
         * grid will still render OSC-8 links underlined).
         *
         * TODO:
         *  - sixels?
         */
        struct grid g = {
            .num_rows = 1 << (32 - __builtin_clz(term->interactive_resizing.old_screen_rows)),
            .num_cols = term->interactive_resizing.old_cols,
            .offset = 0,
            .view = 0,
            .cursor = orig->cursor,
            .saved_cursor = orig->saved_cursor,
            .rows = xcalloc(g.num_rows, sizeof(g.rows[0])),
            .cur_row = NULL,
            .scroll_damage = tll_init(),
            .sixel_images = tll_init(),
            .kitty_kbd = orig->kitty_kbd,
        };

        term->selection.coords.start.row -= orig->view;
        term->selection.coords.end.row -= orig->view;

        for (size_t i = 0, j = orig->view;
             i < term->interactive_resizing.old_screen_rows;
             i++, j = (j + 1) & (orig->num_rows - 1))
        {
            g.rows[i] = grid_row_alloc(g.num_cols, false);
            memcpy(g.rows[i]->cells,
                   orig->rows[j]->cells,
                   g.num_cols * sizeof(g.rows[i]->cells[0]));

            if (orig->rows[j]->extra == NULL ||
                orig->rows[j]->extra->underline_ranges.count == 0)
            {
                continue;
            }

            /*
             * Copy underline ranges
             */

            const struct row_ranges *underline_src = &orig->rows[j]->extra->underline_ranges;

            const int count = underline_src->count;
            g.rows[i]->extra = xcalloc(1, sizeof(*g.rows[i]->extra));
            g.rows[i]->extra->underline_ranges.v = xmalloc(
                count * sizeof(g.rows[i]->extra->underline_ranges.v[0]));

            struct row_ranges *underline_dst = &g.rows[i]->extra->underline_ranges;
            underline_dst->count = underline_dst->size = count;

            for (int k = 0; k < count; k++)
                underline_dst->v[k] = underline_src->v[k];
        }

        term->normal = g;
        term->hide_cursor = true;
    }

    if (term->grid == &term->alt)
        selection_cancel(term);
    else {
        /*
         * Don't cancel, but make sure there aren't any ongoing
         * selections after the resize.
         */
        tll_foreach(term->wl->seats, it) {
            if (it->item.kbd_focus == term)
                selection_finalize(&it->item, term, it->item.pointer.serial);
        }
    }

    /*
     * TODO: if we remove the selection_finalize() call above (i.e. if
     * we start allowing selections to be ongoing across resizes), the
     * selection's pivot point coordinates *must* be added to the
     * tracking points list.
     */
    /* Resize grids */
    if (term->window->is_resizing && term->conf->resize_delay_ms > 0) {
        /* Simple truncating resize, *while* an interactive resize is
         * ongoing. */
        xassert(term->interactive_resizing.grid != NULL);
        xassert(new_normal_grid_rows > 0);
        term->interactive_resizing.new_rows = new_normal_grid_rows;

        grid_resize_without_reflow(
            &term->normal, new_alt_grid_rows, new_cols,
            term->interactive_resizing.old_screen_rows, new_rows);
    } else {
        /* Full text reflow */

        int old_normal_rows = old_rows;

        if (term->interactive_resizing.grid != NULL) {
            /* Throw away the current, truncated, "normal" grid, and
             * use the original grid instead (from before the resize
             * started) */
            grid_free(&term->normal);
            term->normal = *term->interactive_resizing.grid;
            free(term->interactive_resizing.grid);

            term->hide_cursor = term->interactive_resizing.old_hide_cursor;
            term->selection.coords = term->interactive_resizing.selection_coords;

            old_normal_rows = term->interactive_resizing.old_screen_rows;

            term->interactive_resizing.grid = NULL;
            term->interactive_resizing.old_screen_rows = 0;
            term->interactive_resizing.new_rows = 0;
            term->interactive_resizing.old_hide_cursor = false;
            term->interactive_resizing.selection_coords = (struct range){{-1, -1}, {-1, -1}};
            term_ptmx_resume(term);
        }

        struct coord *const tracking_points[] = {
            &term->selection.coords.start,
            &term->selection.coords.end,
        };

        grid_resize_and_reflow(
            &term->normal, term, new_normal_grid_rows, new_cols, old_normal_rows, new_rows,
            term->selection.coords.end.row >= 0 ? ALEN(tracking_points) : 0,
            tracking_points);
    }

    grid_resize_without_reflow(
        &term->alt, new_alt_grid_rows, new_cols, old_rows, new_rows);

    /* Reset tab stops */
    tll_free(term->tab_stops);
    for (int c = 0; c < new_cols; c += 8)
        tll_push_back(term->tab_stops, c);

    term->cols = new_cols;
    term->rows = new_rows;

    sixel_reflow(term);

    LOG_DBG("resized: grid: cols=%d, rows=%d "
            "(left-margin=%d, right-margin=%d, top-margin=%d, bottom-margin=%d)",
            term->cols, term->rows,
            term->margins.left, term->margins.right,
            term->margins.top, term->margins.bottom);

    if (term->scroll_region.start >= term->rows)
        term->scroll_region.start = 0;
    if (term->scroll_region.end > term->rows ||
        term->scroll_region.end >= old_rows)
    {
        term->scroll_region.end = term->rows;
    }

    term->render.last_cursor.row = NULL;

damage_view:
    /* Signal TIOCSWINSZ */
    send_dimensions_to_client(term);

    if (is_floating) {
        /* Stash current size, to enable us to restore it when we're
         * being un-maximized/fullscreened/tiled */
        term->stashed_width = term->width;
        term->stashed_height = term->height;
    }

    {
        const bool title_shown = wayl_win_csd_titlebar_visible(term->window);
        const bool border_shown = wayl_win_csd_borders_visible(term->window);

        const int title = title_shown
            ? roundf(term->conf->csd.title_height * scale)
            : 0;
        const int border = border_shown
            ? roundf(term->conf->csd.border_width_visible * scale)
            : 0;

        /* Must use surface logical coordinates (same calculations as
           in get_csd_data(), but with different inputs) */
        const int toplevel_min_width = roundf(border / scale) +
                                       roundf(min_width / scale) +
                                       roundf(border / scale);

        const int toplevel_min_height = roundf(border / scale) +
                                        roundf(title / scale) +
                                        roundf(min_height / scale) +
                                        roundf(border / scale);

        const int toplevel_width = roundf(border / scale) +
                                   roundf(term->width / scale) +
                                   roundf(border / scale);

        const int toplevel_height = roundf(border / scale) +
                                    roundf(title / scale) +
                                    roundf(term->height / scale) +
                                    roundf(border / scale);

        const int x = roundf(-border / scale);
        const int y = roundf(-title / scale) - roundf(border / scale);

        xdg_toplevel_set_min_size(
            term->window->xdg_toplevel,
            toplevel_min_width, toplevel_min_height);

        xdg_surface_set_window_geometry(
            term->window->xdg_surface,
            x, y, toplevel_width, toplevel_height);
    }

    tll_free(term->normal.scroll_damage);
    tll_free(term->alt.scroll_damage);

    wait_for_preapply_damage(term);
    shm_unref(term->render.last_buf);
    term->render.last_buf = NULL;
    term_damage_view(term);
    render_refresh_csd(term);
    render_refresh_search(term);
    render_refresh(term);

    return true;
}

static void xcursor_callback(
    void *data, struct wl_callback *wl_callback, uint32_t callback_data);
static const struct wl_callback_listener xcursor_listener = {
    .done = &xcursor_callback,
};

bool
render_xcursor_is_valid(const struct seat *seat, const char *cursor)
{
    if (cursor == NULL)
        return false;
    if (seat->pointer.theme == NULL)
        return false;
    return wl_cursor_theme_get_cursor(seat->pointer.theme, cursor) != NULL;
}

static void
render_xcursor_update(struct seat *seat)
{
    /* If called from a frame callback, we may no longer have mouse focus */
    if (!seat->mouse_focus)
        return;

    xassert(seat->pointer.shape != CURSOR_SHAPE_NONE);

    if (seat->pointer.shape == CURSOR_SHAPE_HIDDEN) {
        /* Hide cursor */
        LOG_DBG("hiding cursor using client-side NULL-surface");
        wl_surface_attach(seat->pointer.surface.surf, NULL, 0, 0);
        wl_pointer_set_cursor(
            seat->wl_pointer, seat->pointer.serial, seat->pointer.surface.surf,
            0, 0);
        wl_surface_commit(seat->pointer.surface.surf);
        return;
    }

    const enum cursor_shape shape = seat->pointer.shape;
    const char *const xcursor = seat->pointer.last_custom_xcursor;

    if (seat->pointer.shape_device != NULL) {
        xassert(shape != CURSOR_SHAPE_CUSTOM || xcursor != NULL);

        const enum wp_cursor_shape_device_v1_shape custom_shape =
            (shape == CURSOR_SHAPE_CUSTOM && xcursor != NULL
                ? cursor_string_to_server_shape(
                    xcursor, seat->wayl->shape_manager_version)
                : 0);

        if (shape != CURSOR_SHAPE_CUSTOM || custom_shape != 0) {
            xassert(custom_shape == 0 || shape == CURSOR_SHAPE_CUSTOM);

            const enum wp_cursor_shape_device_v1_shape wp_shape = custom_shape != 0
                ? custom_shape
                : cursor_shape_to_server_shape(shape);

            LOG_DBG("setting %scursor shape using cursor-shape-v1",
                    custom_shape != 0 ? "custom " : "");

            wp_cursor_shape_device_v1_set_shape(
                seat->pointer.shape_device,
                seat->pointer.serial,
                wp_shape);

            return;
        }
    }

    LOG_DBG("setting %scursor shape using a client-side cursor surface",
            seat->pointer.shape == CURSOR_SHAPE_CUSTOM ? "custom " : "");

    if (seat->pointer.cursor == NULL) {
        /*
         * Normally, we never get here with a NULL-cursor, because we
         * only schedule a cursor update when we succeed to load the
         * cursor image.
         *
         * However, it is possible that we did succeed to load an
         * image, and scheduled an update. But, *before* the scheduled
         * update triggers, the user mvoes the pointer, and we try to
         * load a new cursor image. This time failing.
         *
         * In this case, we have a NULL cursor, but the scheduled
         * update is still scheduled.
         */
        return;
    }

    const float scale = seat->pointer.scale;
    struct wl_cursor_image *image = seat->pointer.cursor->images[0];
    struct wl_buffer *buf = wl_cursor_image_get_buffer(image);

    wayl_surface_scale_explicit_width_height(
        seat->mouse_focus->window,
        &seat->pointer.surface, image->width, image->height, scale);

    wl_surface_attach(seat->pointer.surface.surf, buf, 0, 0);

    wl_pointer_set_cursor(
        seat->wl_pointer, seat->pointer.serial,
        seat->pointer.surface.surf,
        image->hotspot_x / scale, image->hotspot_y / scale);

    wl_surface_damage_buffer(
        seat->pointer.surface.surf, 0, 0, INT32_MAX, INT32_MAX);

    xassert(seat->pointer.xcursor_callback == NULL);
    seat->pointer.xcursor_callback = wl_surface_frame(seat->pointer.surface.surf);
    wl_callback_add_listener(seat->pointer.xcursor_callback, &xcursor_listener, seat);

    wl_surface_commit(seat->pointer.surface.surf);
}

static void
xcursor_callback(void *data, struct wl_callback *wl_callback, uint32_t callback_data)
{
    struct seat *seat = data;

    xassert(seat->pointer.xcursor_callback == wl_callback);
    wl_callback_destroy(wl_callback);
    seat->pointer.xcursor_callback = NULL;

    if (seat->pointer.xcursor_pending) {
        render_xcursor_update(seat);
        seat->pointer.xcursor_pending = false;
    }
}

static void
fdm_hook_refresh_pending_terminals(struct fdm *fdm, void *data)
{
    struct renderer *renderer = data;
    struct wayland *wayl = renderer->wayl;

    tll_foreach(renderer->wayl->terms, it) {
        struct terminal *term = it->item;

        if (unlikely(term->shutdown.in_progress || !term->window->is_configured))
            continue;

        bool grid = term->render.refresh.grid;
        bool csd = term->render.refresh.csd;
        bool search = term->is_searching && term->render.refresh.search;
        bool urls = urls_mode_is_active(term) && term->render.refresh.urls;

        if (!(grid | csd | search | urls))
            continue;

        if (term->render.app_sync_updates.enabled && !(csd | search | urls))
            continue;

        term->render.refresh.grid = false;
        term->render.refresh.csd = false;
        term->render.refresh.search = false;
        term->render.refresh.urls = false;

        if (term->window->frame_callback == NULL) {
            struct grid *original_grid = term->grid;
            if (urls_mode_is_active(term)) {
                xassert(term->url_grid_snapshot != NULL);
                term->grid = term->url_grid_snapshot;
            }

            if (csd && term->window->csd_mode == CSD_YES) {
                quirk_weston_csd_on(term);
                render_csd(term);
                quirk_weston_csd_off(term);
            }
            if (search)
                render_search_box(term);
            if (urls)
                render_urls(term);
            if (grid | csd | search | urls)
                grid_render(term);

            tll_foreach(term->wl->seats, it) {
                if (it->item.ime_focus == term)
                    ime_update_cursor_rect(&it->item);
            }

            term->grid = original_grid;
        } else {
            /* Tells the frame callback to render again */
            term->render.pending.grid |= grid;
            term->render.pending.csd |= csd;
            term->render.pending.search |= search;
            term->render.pending.urls |= urls;
        }
    }

    tll_foreach(wayl->seats, it) {
        if (it->item.pointer.xcursor_pending) {
            if (it->item.pointer.xcursor_callback == NULL) {
                render_xcursor_update(&it->item);
                it->item.pointer.xcursor_pending = false;
            } else {
                /* Frame callback will call render_xcursor_update() */
            }
        }
    }
}

void
render_refresh_title(struct terminal *term)
{
    struct timespec now;
    if (clock_gettime(CLOCK_MONOTONIC, &now) < 0)
        return;

    struct timespec diff;
    timespec_sub(&now, &term->render.title.last_update, &diff);

    if (diff.tv_sec == 0 && diff.tv_nsec < 8333 * 1000) {
        const struct itimerspec timeout = {
            .it_value = {.tv_nsec = 8333 * 1000 - diff.tv_nsec},
        };

        timerfd_settime(term->render.title.timer_fd, 0, &timeout, NULL);
    } else {
        term->render.title.last_update = now;
        render_update_title(term);
    }

    render_refresh_csd(term);
}

void
render_refresh_app_id(struct terminal *term)
{
    struct timespec now;
    if (clock_gettime(CLOCK_MONOTONIC, &now) < 0)
        return;

    struct timespec diff;
    timespec_sub(&now, &term->render.app_id.last_update, &diff);

    if (diff.tv_sec == 0 && diff.tv_nsec < 8333 * 1000) {
        const struct itimerspec timeout = {
            .it_value = {.tv_nsec = 8333 * 1000 - diff.tv_nsec},
        };

        timerfd_settime(term->render.app_id.timer_fd, 0, &timeout, NULL);
        return;
    }

    const char *app_id =
        term->app_id != NULL ? term->app_id : term->conf->app_id;

    xdg_toplevel_set_app_id(term->window->xdg_toplevel, app_id);
    term->render.app_id.last_update = now;
}

void
render_refresh_icon(struct terminal *term)
{
    if (term->wl->toplevel_icon_manager == NULL) {
        LOG_DBG("compositor does not implement xdg-toplevel-icon: "
                "ignoring request to refresh window icon");
        return;
    }

    struct timespec now;
    if (clock_gettime(CLOCK_MONOTONIC, &now) < 0)
        return;

    struct timespec diff;
    timespec_sub(&now, &term->render.icon.last_update, &diff);

    if (diff.tv_sec == 0 && diff.tv_nsec < 8333 * 1000) {
        const struct itimerspec timeout = {
            .it_value = {.tv_nsec = 8333 * 1000 - diff.tv_nsec},
        };

        timerfd_settime(term->render.icon.timer_fd, 0, &timeout, NULL);
        return;
    }

    const char *icon_name = term_icon(term);
    LOG_DBG("setting toplevel icon: %s", icon_name);

    struct xdg_toplevel_icon_v1 *icon =
        xdg_toplevel_icon_manager_v1_create_icon(term->wl->toplevel_icon_manager);
    xdg_toplevel_icon_v1_set_name(icon, icon_name);
    xdg_toplevel_icon_manager_v1_set_icon(
        term->wl->toplevel_icon_manager, term->window->xdg_toplevel, icon);
    xdg_toplevel_icon_v1_destroy(icon);

    term->render.icon.last_update = now;
}

void
render_refresh(struct terminal *term)
{
    term->render.refresh.grid = true;
}

void
render_refresh_csd(struct terminal *term)
{
    if (term->window->csd_mode == CSD_YES)
        term->render.refresh.csd = true;
}

void
render_refresh_search(struct terminal *term)
{
    if (term->is_searching)
        term->render.refresh.search = true;
}

void
render_refresh_urls(struct terminal *term)
{
    if (urls_mode_is_active(term))
        term->render.refresh.urls = true;
}

bool
render_xcursor_set(struct seat *seat, struct terminal *term,
                   enum cursor_shape shape)
{
    if (seat->pointer.theme == NULL && seat->pointer.shape_device == NULL)
        return false;

    if (seat->mouse_focus == NULL) {
        seat->pointer.shape = CURSOR_SHAPE_NONE;
        return true;
    }

    if (seat->mouse_focus != term) {
        /* This terminal doesn't have mouse focus */
        return true;
    }

    if (seat->pointer.shape == shape &&
        !(shape == CURSOR_SHAPE_CUSTOM &&
          !streq(seat->pointer.last_custom_xcursor,
                 term->mouse_user_cursor)))
    {
        return true;
    }

    if (shape == CURSOR_SHAPE_HIDDEN) {
        seat->pointer.cursor = NULL;
        free(seat->pointer.last_custom_xcursor);
        seat->pointer.last_custom_xcursor = NULL;
    }

    else if (seat->pointer.shape_device == NULL) {
        const char *const custom_xcursors[] = {term->mouse_user_cursor, NULL};
        const char *const *xcursors = shape == CURSOR_SHAPE_CUSTOM
            ? custom_xcursors
            : cursor_shape_to_string(shape);

        xassert(xcursors[0] != NULL);

        seat->pointer.cursor = NULL;

        for (size_t i = 0; xcursors[i] != NULL; i++) {
            seat->pointer.cursor =
                wl_cursor_theme_get_cursor(seat->pointer.theme, xcursors[i]);

            if (seat->pointer.cursor != NULL) {
                LOG_DBG("loaded xcursor %s", xcursors[i]);
                break;
            }
        }

        if (seat->pointer.cursor == NULL) {
            LOG_ERR(
                "failed to load xcursor pointer '%s', and all of its fallbacks",
                xcursors[0]);
            return false;
        }
    } else {
        /* Server-side cursors - no need to load anything */
    }

    if (shape == CURSOR_SHAPE_CUSTOM) {
        free(seat->pointer.last_custom_xcursor);
        seat->pointer.last_custom_xcursor =
            xstrdup(term->mouse_user_cursor);
    }

    /* FDM hook takes care of actual rendering */
    seat->pointer.shape = shape;
    seat->pointer.xcursor_pending = true;
    return true;
}

void
render_buffer_release_callback(struct buffer *buf, void *data)
{
    /*
     * Called from shm.c when a buffer is released
     *
     * We use it to pre-apply last-frame's damage to it, when we're
     * forced to double buffer (compositor doesn't release buffers
     * immediately).
     *
     * The timeline is thus:
     *   1. We render and push a new frame
     *   2. Some (hopefully short) time after that, the compositor releases the previous buffer
     *   3. We're called, and kick off the thread that copies the changes from (1) to the just freed buffer
     *   4. Time passes....
     *   5. The compositor calls our frame callback, signalling to us that it's time to start rendering the next frame
     *   6. Hopefully, our thread is already done with copying the changes, otherwise we stall, waiting for it
     *   7. We render the frame as if the compositor does immediate releases.
     *
     * What's the gain? Reduced latency, by applying the previous
     * frame's damage as soon as possible, we shorten the time it
     * takes to render the frame after the frame callback.
     *
     * This means the compositor can, in theory, push the frame
     * callback closer to the vblank deadline, and thus reduce input
     * latency. Not all compositors (most, in fact?) don't adapt like
     * this, unfortunately. But some allows the user to manually
     * configure the deadline.
     */
    struct terminal *term = data;

    if (likely(buf->age != 1))
        return;

    if (likely(!term->render.preapply_last_frame_damage))
        return;

    if (term->render.last_buf == NULL)
        return;

    if (term->render.last_buf->age != 0)
        return;

    if (buf->width != term->render.last_buf->width)
        return;

    if (buf->height != term->render.last_buf->height)
        return;

    xassert(term->render.workers.count > 0);
    xassert(term->render.last_buf != NULL);

    xassert(term->render.last_buf->age == 0);
    xassert(term->render.last_buf != buf);

    mtx_lock(&term->render.workers.preapplied_damage.lock);
    if (term->render.workers.preapplied_damage.buf != NULL) {
        mtx_unlock(&term->render.workers.preapplied_damage.lock);
        return;
    }

    xassert(term->render.workers.preapplied_damage.buf == NULL);
    term->render.workers.preapplied_damage.buf = buf;
    term->render.workers.preapplied_damage.start = (struct timespec){0};
    term->render.workers.preapplied_damage.stop = (struct timespec){0};
    mtx_unlock(&term->render.workers.preapplied_damage.lock);

    mtx_lock(&term->render.workers.lock);
    sem_post(&term->render.workers.start);
    xassert(tll_length(term->render.workers.queue) == 0);
    tll_push_back(term->render.workers.queue, -3);
    mtx_unlock(&term->render.workers.lock);
}