wallr-core 0.8.0

Core library for wallr - wallpaper engine, GPU transitions, theme provider dispatch, and video playback.
Documentation
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
use crate::config::WallrConfig;
use crate::ipc::{IpcCommand, IpcResponse, IpcSocket, remove_socket_if_owned};
use crate::renderer::Renderer;
use crate::wallpaper::{SetOptions, WallpaperEngine};
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use tokio::sync::Mutex;

use raw_window_handle::{
    DisplayHandle, HasDisplayHandle, HasWindowHandle, RawDisplayHandle, RawWindowHandle,
    WaylandDisplayHandle, WaylandWindowHandle, WindowHandle,
};
use smithay_client_toolkit::{
    compositor::{CompositorHandler, CompositorState},
    delegate_registry,
    output::{OutputHandler, OutputState},
    registry::{ProvidesRegistryState, RegistryState},
    registry_handlers,
    shell::WaylandSurface,
    shell::wlr_layer::{
        Anchor, KeyboardInteractivity, Layer, LayerShell, LayerShellHandler, LayerSurface,
        LayerSurfaceConfigure,
    },
    shm::slot::{Buffer as ShmBuffer, SlotPool},
    shm::{Shm, ShmHandler},
};
use wayland_client::{
    Connection, Dispatch, Proxy, QueueHandle,
    globals::registry_queue_init,
    protocol::{wl_compositor, wl_output, wl_surface},
};
use wayland_protocols::wp::viewporter::client::{
    wp_viewport::{self, WpViewport},
    wp_viewporter::{self, WpViewporter},
};
#[derive(Debug, thiserror::Error)]
pub enum DaemonError {
    #[error("daemon already running: {0}")]
    AlreadyRunning(String),
    #[error("failed to start daemon: {0}")]
    StartError(String),
    #[error("I/O error: {0}")]
    Io(#[from] std::io::Error),
    #[error("IPC error: {0}")]
    Ipc(#[from] crate::ipc::IpcError),
    #[error("Config error: {0}")]
    Config(#[from] crate::config::ConfigError),
    #[error("Wallpaper error: {0}")]
    Wallpaper(#[from] crate::wallpaper::WallpaperError),
}

/// Borrowed raw Wayland handles for `wgpu::Instance::create_surface`.
///
/// The pointers reference the compositor display connection and the layer
/// surface, both owned by the daemon for at least as long as the resulting
/// render state. This type is only constructed on a blocking worker and never
/// outlives the `create_surface` call.
pub struct WaylandWindow {
    pub display: *mut std::ffi::c_void,
    pub surface: *mut std::ffi::c_void,
}

// SAFETY: `create_surface` requires Send + Sync on its window handle. The
// raw pointers are immutable handles to objects whose lifetime is enforced by
// `RenderState` (it holds a cloned `wl_surface` proxy and the daemon keeps the
// display connection alive). No pointer is dereferenced outside the Wayland
// client/backend while the owning connection exists.
unsafe impl Send for WaylandWindow {}
unsafe impl Sync for WaylandWindow {}

impl HasWindowHandle for WaylandWindow {
    fn window_handle(&self) -> Result<WindowHandle<'_>, raw_window_handle::HandleError> {
        let surface = std::ptr::NonNull::new(self.surface)
            .ok_or(raw_window_handle::HandleError::Unavailable)?;
        let handle = WaylandWindowHandle::new(surface);
        unsafe { Ok(WindowHandle::borrow_raw(RawWindowHandle::Wayland(handle))) }
    }
}

impl HasDisplayHandle for WaylandWindow {
    fn display_handle(&self) -> Result<DisplayHandle<'_>, raw_window_handle::HandleError> {
        let display = std::ptr::NonNull::new(self.display)
            .ok_or(raw_window_handle::HandleError::Unavailable)?;
        let handle = WaylandDisplayHandle::new(display);
        unsafe { Ok(DisplayHandle::borrow_raw(RawDisplayHandle::Wayland(handle))) }
    }
}

#[derive(Clone)]
struct OutputInfo {
    name: String,
    width: u32,
    height: u32,
    scale_factor: i32,
    wl_output: wl_output::WlOutput,
}

#[derive(Clone)]
struct OutputLifecycle {
    name: String,
    render_state: std::sync::Arc<tokio::sync::Mutex<RenderState>>,
    active: std::sync::Arc<std::sync::atomic::AtomicBool>,
}

struct WaylandState {
    registry_state: RegistryState,
    output_state: OutputState,
    compositor_state: CompositorState,
    shm: Shm,
    outputs: std::collections::HashMap<u32, OutputInfo>,
    surfaces: Vec<(u32, LayerSurface)>,
    viewporter: Option<WpViewporter>,
    viewports: std::collections::HashMap<u32, WpViewport>,
    output_lifecycles: std::collections::HashMap<u32, OutputLifecycle>,
    pending_restores: std::collections::HashSet<u32>,
    /// Layer shell protocol object for creating background surfaces.
    layer_shell: LayerShell,
    /// Compositor protocol object for creating input regions.
    compositor: wl_compositor::WlCompositor,
    /// Shared daemon context for hotplug: creates and destroys render states
    /// when outputs appear or disappear.
    hotplug: Option<DaemonHotplug>,
}

/// Wrapper around a raw display/surface pointer that must cross into a
/// `spawn_blocking` task or an `Arc`-shared `RenderState`.
///
/// SAFETY: the daemon's `Connection` (display) is held for the process
/// lifetime, and each raw surface pointer is paired with a cloned
/// `wl_surface::WlSurface` proxy in `RenderState`, so the protocol object
/// cannot be destroyed while the pointer is in use. Output teardown waits for
/// the render lock and stops playback before dropping that proxy.
struct SendDisplayPtr(*mut std::ffi::c_void);
unsafe impl Send for SendDisplayPtr {}
unsafe impl Sync for SendDisplayPtr {}

/// Shared context for hotplug operations. Stored in `WaylandState` so the
/// output callbacks can create/destroy render states without needing access
/// to the full `Daemon` state.
struct DaemonHotplug {
    renderer: std::sync::Arc<std::sync::Mutex<Option<std::sync::Arc<Renderer>>>>,
    config: crate::config::WallrConfig,
    display_ptr: SendDisplayPtr,
    /// Shared render-state map. Protected by `tokio::sync::Mutex` so the IPC
    /// handler (async) and the Wayland callbacks (sync, via `blocking_dispatch`)
    /// can both access it. The Wayland thread never holds this across an await,
    /// so there is no risk of deadlocking the event loop.
    render_states: std::sync::Arc<
        tokio::sync::Mutex<
            std::collections::HashMap<String, std::sync::Arc<tokio::sync::Mutex<RenderState>>>,
        >,
    >,
}

impl ProvidesRegistryState for WaylandState {
    fn registry(&mut self) -> &mut RegistryState {
        &mut self.registry_state
    }

    registry_handlers![OutputState,];
}

impl CompositorHandler for WaylandState {
    fn scale_factor_changed(
        &mut self,
        _conn: &Connection,
        _qh: &QueueHandle<Self>,
        _surface: &wl_surface::WlSurface,
        _new_factor: i32,
    ) {
    }
    fn transform_changed(
        &mut self,
        _conn: &Connection,
        _qh: &QueueHandle<Self>,
        _surface: &wl_surface::WlSurface,
        _new_transform: wl_output::Transform,
    ) {
    }
    fn frame(
        &mut self,
        _conn: &Connection,
        _qh: &QueueHandle<Self>,
        _surface: &wl_surface::WlSurface,
        _time: u32,
    ) {
    }
    fn surface_enter(
        &mut self,
        _conn: &Connection,
        _qh: &QueueHandle<Self>,
        _surface: &wl_surface::WlSurface,
        _output: &wl_output::WlOutput,
    ) {
    }
    fn surface_leave(
        &mut self,
        _conn: &Connection,
        _qh: &QueueHandle<Self>,
        _surface: &wl_surface::WlSurface,
        _output: &wl_output::WlOutput,
    ) {
    }
}

impl wayland_client::Dispatch<wayland_client::protocol::wl_region::WlRegion, ()> for WaylandState {
    fn event(
        _state: &mut WaylandState,
        _region: &wayland_client::protocol::wl_region::WlRegion,
        _event: wayland_client::protocol::wl_region::Event,
        _data: &(),
        _conn: &Connection,
        _qh: &QueueHandle<WaylandState>,
    ) {
    }
}

impl Dispatch<WpViewporter, ()> for WaylandState {
    fn event(
        _state: &mut WaylandState,
        _proxy: &WpViewporter,
        _event: wp_viewporter::Event,
        _data: &(),
        _conn: &Connection,
        _qh: &QueueHandle<WaylandState>,
    ) {
    }
}

impl Dispatch<WpViewport, ()> for WaylandState {
    fn event(
        _state: &mut WaylandState,
        _proxy: &WpViewport,
        _event: wp_viewport::Event,
        _data: &(),
        _conn: &Connection,
        _qh: &QueueHandle<WaylandState>,
    ) {
    }
}

fn viewport_destination(configured: (u32, u32), physical: (u32, u32)) -> Option<(i32, i32)> {
    let (width, height) = configured;
    let (physical_width, physical_height) = physical;
    match (width, height) {
        (0, 0) => None,
        (0, height) if physical_height > 0 => {
            let width = (u64::from(height) * u64::from(physical_width)
                + u64::from(physical_height) / 2)
                / u64::from(physical_height);
            Some((i32::try_from(width).ok()?, i32::try_from(height).ok()?))
        }
        (width, 0) if physical_width > 0 => {
            let height = (u64::from(width) * u64::from(physical_height)
                + u64::from(physical_width) / 2)
                / u64::from(physical_width);
            Some((i32::try_from(width).ok()?, i32::try_from(height).ok()?))
        }
        (width, height) => Some((i32::try_from(width).ok()?, i32::try_from(height).ok()?)),
    }
}

#[cfg(test)]
mod viewport_tests {
    use super::{
        VideoPresentAction, advance_gif_slots, clamp_max_fps, clamp_preload_frames,
        is_transient_wallpaper_error, is_usable_wallpaper_file, persist_wallpaper_at,
        read_wallpaper_state, validate_live_config, video_present_action, viewport_destination,
        write_wallpaper_state,
    };
    use crate::renderer::FrameStatus;

    #[test]
    fn gif_slots_never_flip_to_an_unuploaded_frame() {
        // Warm path: idle texture already holds the target frame.
        let advanced = advance_gif_slots(0, 0, 1, 1, true);
        assert_eq!((advanced.0, advanced.1, advanced.3), (1, 1, true));

        // Upload failure: keep presenting the old frame, retry later.
        let retry = advance_gif_slots(0, 0, 2, 1, false);
        assert_eq!((retry.0, retry.1, retry.3), (0, 0, false));

        // Retry succeeds once the decoder catches up.
        let retried = advance_gif_slots(0, 0, 2, 1, true);
        assert_eq!((retried.0, retried.1, retried.3), (1, 1, true));

        // Same-frame repeats keep the current texture.
        let same = advance_gif_slots(1, 1, 2, 1, true);
        assert_eq!((same.0, same.1, same.3), (1, 1, true));

        // Skip-ahead jump after a busy present still lands on the newest
        // frame, never on a stale texture.
        let jump = advance_gif_slots(1, 1, 2, 4, true);
        assert_eq!((jump.0, jump.1, jump.3), (0, 4, true));
    }

    #[test]
    fn preserves_complete_configure_size() {
        assert_eq!(
            viewport_destination((3072, 1728), (3840, 2160)),
            Some((3072, 1728))
        );
    }

    #[test]
    fn derives_missing_dimension_from_physical_aspect_ratio() {
        assert_eq!(
            viewport_destination((0, 1728), (3840, 2160)),
            Some((3072, 1728))
        );
        assert_eq!(
            viewport_destination((3072, 0), (3840, 2160)),
            Some((3072, 1728))
        );
        assert_eq!(viewport_destination((0, 0), (3840, 2160)), None);
    }

    #[test]
    fn retries_recoverable_video_surface_failures() {
        assert_eq!(
            video_present_action(FrameStatus::TimedOut),
            VideoPresentAction::Retry
        );
        assert_eq!(
            video_present_action(FrameStatus::Outdated),
            VideoPresentAction::Reconfigure
        );
        assert_eq!(
            video_present_action(FrameStatus::Lost),
            VideoPresentAction::Reconfigure
        );
    }

    #[test]
    fn rotates_wallpaper_state_only_after_successful_persistence() {
        let temporary = tempfile::tempdir().expect("temporary directory");
        let first = temporary.path().join("first.jpg");
        let second = temporary.path().join("second.jpg");
        std::fs::write(&first, b"first").expect("first wallpaper");
        std::fs::write(&second, b"second").expect("second wallpaper");

        persist_wallpaper_at(temporary.path(), "DP-1", &first).expect("persist first");
        assert_eq!(
            read_wallpaper_state(temporary.path(), "last_wallpaper", "DP-1"),
            Some(first.clone())
        );
        assert_eq!(
            read_wallpaper_state(temporary.path(), "previous_wallpaper", "DP-1"),
            None
        );

        persist_wallpaper_at(temporary.path(), "DP-1", &second).expect("persist second");
        assert_eq!(
            read_wallpaper_state(temporary.path(), "last_wallpaper", "DP-1"),
            Some(second)
        );
        assert_eq!(
            read_wallpaper_state(temporary.path(), "previous_wallpaper", "DP-1"),
            Some(first)
        );

        let missing = temporary.path().join("missing.jpg");
        write_wallpaper_state(temporary.path(), "last_wallpaper", "DP-1", &missing)
            .expect("persist missing path for restore test");
        assert_eq!(
            read_wallpaper_state(temporary.path(), "last_wallpaper", "DP-1"),
            Some(missing)
        );
    }

    #[test]
    fn wallpaper_state_preserves_non_utf8_and_whitespace() {
        use std::os::unix::ffi::OsStringExt;

        let temporary = tempfile::tempdir().expect("temporary directory");
        let wallpaper = std::path::PathBuf::from(std::ffi::OsString::from_vec(
            b" /tmp/wallpaper-\xff.jpg ".to_vec(),
        ));

        write_wallpaper_state(temporary.path(), "last_wallpaper", "DP-1", &wallpaper)
            .expect("persist wallpaper path");

        assert_eq!(
            read_wallpaper_state(temporary.path(), "last_wallpaper", "DP-1"),
            Some(wallpaper)
        );
    }

    #[test]
    fn retries_only_explicitly_transient_errors() {
        let timed_out = anyhow::Error::new(std::io::Error::new(
            std::io::ErrorKind::TimedOut,
            "temporary timeout",
        ));
        let missing = anyhow::Error::new(std::io::Error::new(
            std::io::ErrorKind::NotFound,
            "missing wallpaper",
        ));
        let recoverable_video = anyhow::Error::new(crate::video::VideoError::QueueFull);

        assert!(is_transient_wallpaper_error(&timed_out));
        assert!(is_transient_wallpaper_error(&recoverable_video));
        assert!(!is_transient_wallpaper_error(&missing));
        assert!(!is_transient_wallpaper_error(&anyhow::anyhow!(
            "invalid dimensions"
        )));
    }

    #[test]
    fn live_video_params_stay_bounded() {
        assert_eq!(clamp_preload_frames(0), 1);
        assert_eq!(clamp_preload_frames(2), 2);
        assert_eq!(clamp_preload_frames(100), 3);
        assert_eq!(clamp_max_fps(None), None);
        assert_eq!(clamp_max_fps(Some(0)), None);
        assert_eq!(clamp_max_fps(Some(60)), Some(60));
        assert_eq!(clamp_max_fps(Some(10_000)), Some(240));
    }

    #[test]
    fn watcher_requires_non_empty_files() {
        let temporary = tempfile::tempdir().expect("temporary directory");
        let empty = temporary.path().join("empty.jpg");
        let filled = temporary.path().join("filled.jpg");
        std::fs::write(&empty, b"").expect("empty file");
        std::fs::write(&filled, b"data").expect("filled file");
        assert!(!is_usable_wallpaper_file(&empty));
        assert!(is_usable_wallpaper_file(&filled));
        assert!(!is_usable_wallpaper_file(
            &temporary.path().join("missing.jpg")
        ));
    }

    #[test]
    fn reload_rejects_absurd_live_values() {
        let mut cfg = crate::config::WallrConfig::default();
        assert!(validate_live_config(&cfg).is_ok());
        cfg.video.preload_frames = 1000;
        assert!(validate_live_config(&cfg).is_err());
        cfg.video.preload_frames = 2;
        cfg.daemon.max_fps = Some(0);
        assert!(validate_live_config(&cfg).is_err());
    }
}

impl LayerShellHandler for WaylandState {
    fn configure(
        &mut self,
        _conn: &Connection,
        _qh: &QueueHandle<Self>,
        layer: &LayerSurface,
        configure: LayerSurfaceConfigure,
        _serial: u32,
    ) {
        // SCTK acknowledges the configure. wgpu owns subsequent buffer commits,
        // which must not race with a bufferless commit when explicit sync is active.
        let output_id = self.surfaces.iter().find_map(|(output_id, surface)| {
            (surface.wl_surface().id() == layer.wl_surface().id()).then_some(*output_id)
        });
        let Some(output_id) = output_id else {
            return;
        };
        let destination = self.outputs.get(&output_id).and_then(|output| {
            viewport_destination(configure.new_size, (output.width, output.height))
        });
        if let Some(viewport) = self.viewports.get(&output_id) {
            let Some((logical_width, logical_height)) = destination else {
                tracing::warn!(
                    "Output {output_id} configure omitted both dimensions; waiting for a usable size"
                );
                return;
            };
            viewport.set_destination(logical_width, logical_height);
            tracing::debug!(
                "Configured viewport destination for output {output_id}: {logical_width}x{logical_height}"
            );
        }
        if !self.pending_restores.remove(&output_id) {
            return;
        }
        let Some(lifecycle) = self.output_lifecycles.get(&output_id).cloned() else {
            return;
        };
        let Some(render_states) = self
            .hotplug
            .as_ref()
            .map(|hotplug| hotplug.render_states.clone())
        else {
            return;
        };

        tokio::spawn(async move {
            if !lifecycle.active.load(Ordering::SeqCst) {
                return;
            }
            restore_cached_wallpaper(&lifecycle.name, &lifecycle.render_state).await;

            let mut states = render_states.lock().await;
            if lifecycle.active.load(Ordering::SeqCst) {
                states.insert(lifecycle.name.clone(), lifecycle.render_state);
                tracing::info!("Output configured: {}", lifecycle.name);
            }
        });
    }

    fn closed(&mut self, _conn: &Connection, _qh: &QueueHandle<Self>, _layer: &LayerSurface) {}
}

impl ShmHandler for WaylandState {
    fn shm_state(&mut self) -> &mut Shm {
        &mut self.shm
    }
}

impl OutputHandler for WaylandState {
    fn output_state(&mut self) -> &mut OutputState {
        &mut self.output_state
    }
    fn new_output(
        &mut self,
        _conn: &Connection,
        _qh: &QueueHandle<Self>,
        output: wl_output::WlOutput,
    ) {
        let id = output.id().protocol_id();
        tracing::info!("Output detected: protocol_id={id}");

        let mut info = OutputInfo {
            name: format!("output-{id}"),
            width: 1920,
            height: 1080,
            scale_factor: 1,
            wl_output: output,
        };

        // Resolve the compositor-provided name (e.g. "DP-1", "HDMI-A-1").
        if let Some(info_data) = self.output_state.info(&info.wl_output) {
            if let Some(mode) = info_data.modes.iter().find(|m| m.current) {
                info.width = mode.dimensions.0 as u32;
                info.height = mode.dimensions.1 as u32;
            }
            info.scale_factor = info_data.scale_factor;
            let resolved = info_data
                .name
                .as_deref()
                .filter(|n| !n.is_empty())
                .or(info_data.description.as_deref().filter(|n| !n.is_empty()));
            if let Some(real_name) = resolved {
                info.name = real_name.to_string();
            } else if !info_data.make.is_empty() || !info_data.model.is_empty() {
                let fallback = format!("{} {}", info_data.make, info_data.model)
                    .trim()
                    .to_string();
                if !fallback.is_empty() {
                    info.name = fallback;
                }
            }
        }

        self.outputs.insert(id, info.clone());

        // Create a render state for the new output.
        // Extract values from hotplug before passing &mut self to avoid
        // borrow checker conflicts (hotplug is inside self).
        if self.hotplug.is_some() {
            let name = info.name.clone();
            let renderer = self.hotplug.as_ref().unwrap().renderer.clone();
            let display_ptr = self.hotplug.as_ref().unwrap().display_ptr.0;
            let config = self.hotplug.as_ref().unwrap().config.clone();
            match create_render_state_for_output_sync(
                &renderer,
                display_ptr,
                self,
                _qh,
                &info,
                &config,
            ) {
                Ok(rs) => {
                    let rs = std::sync::Arc::new(tokio::sync::Mutex::new(rs));
                    self.output_lifecycles.insert(
                        id,
                        OutputLifecycle {
                            name,
                            render_state: rs,
                            active: std::sync::Arc::new(std::sync::atomic::AtomicBool::new(true)),
                        },
                    );
                    self.pending_restores.insert(id);
                }
                Err(e) => {
                    tracing::error!("Hotplug: failed to create render state for {name}: {e}");
                }
            }
        }
    }
    fn update_output(
        &mut self,
        _conn: &Connection,
        _qh: &QueueHandle<Self>,
        output: wl_output::WlOutput,
    ) {
        let id = output.id().protocol_id();
        if let Some(info) = self.outputs.get_mut(&id) {
            let mut new_width = info.width;
            let mut new_height = info.height;
            let mut new_scale = info.scale_factor;

            if let Some(mode) = self
                .output_state
                .info(&output)
                .and_then(|i| i.modes.iter().find(|m| m.current).cloned())
            {
                new_width = mode.dimensions.0 as u32;
                new_height = mode.dimensions.1 as u32;
            }
            if let Some(info_data) = self.output_state.info(&output) {
                new_scale = info_data.scale_factor;
                let resolved = info_data
                    .name
                    .as_deref()
                    .filter(|n| !n.is_empty())
                    .or(info_data.description.as_deref().filter(|n| !n.is_empty()));
                if let Some(real_name) = resolved {
                    if real_name != info.name {
                        tracing::info!(
                            "Output {id}: resolved name '{}' -> '{}'",
                            info.name,
                            real_name
                        );
                        info.name = real_name.to_string();
                    }
                } else if info.name.starts_with("output-")
                    && (!info_data.make.is_empty() || !info_data.model.is_empty())
                {
                    let fallback = format!("{} {}", info_data.make, info_data.model)
                        .trim()
                        .to_string();
                    if !fallback.is_empty() {
                        tracing::info!(
                            "Output {id}: fallback name '{}' -> '{}'",
                            info.name,
                            fallback
                        );
                        info.name = fallback;
                    }
                }
            }

            let changed = new_width != info.width
                || new_height != info.height
                || new_scale != info.scale_factor;

            info.width = new_width;
            info.height = new_height;
            info.scale_factor = new_scale;

            // Reconfigure the wgpu surface when dimensions or scale change.
            if changed {
                let name = info.name.clone();
                if let Some(ref hotplug) = self.hotplug {
                    let render_states = hotplug.render_states.clone();
                    tokio::spawn(async move {
                        let states = render_states.lock().await;
                        if let Some(rs) = states.get(&name) {
                            let mut lock = rs.lock().await;
                            lock.width = new_width;
                            lock.height = new_height;
                            if let Some(gpu) = lock.gpu.as_ref() {
                                if let Ok(shared) = lock.renderer.lock()
                                    && let Some(renderer) = shared.as_ref()
                                {
                                    gpu.surface.configure(
                                        &renderer.device,
                                        &wgpu::SurfaceConfiguration {
                                            usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
                                            format: gpu.format,
                                            width: new_width,
                                            height: new_height,
                                            present_mode: wgpu::PresentMode::Fifo,
                                            alpha_mode: wgpu::CompositeAlphaMode::Opaque,
                                            view_formats: vec![],
                                            color_space: wgpu::SurfaceColorSpace::default(),
                                            desired_maximum_frame_latency: 1,
                                        },
                                    );
                                }
                                tracing::info!(
                                    "Hotplug: reconfigured {name} to {new_width}x{new_height}"
                                );
                            }
                        }
                    });
                }
            }
        }
    }
    fn output_destroyed(
        &mut self,
        _conn: &Connection,
        _qh: &QueueHandle<Self>,
        output: wl_output::WlOutput,
    ) {
        let id = output.id().protocol_id();
        if let Some(info) = self.outputs.remove(&id) {
            tracing::info!("Output disconnected: {} (protocol_id={})", info.name, id);
            self.pending_restores.remove(&id);
            let viewport = self.viewports.remove(&id);
            let layer_surface = self
                .surfaces
                .iter()
                .position(|(pid, _)| *pid == id)
                .map(|position| self.surfaces.swap_remove(position).1);
            let lifecycle = self.output_lifecycles.remove(&id);
            if let Some(lifecycle) = &lifecycle {
                lifecycle.active.store(false, Ordering::SeqCst);
            }
            // Remove the render state from the shared map and stop playback.
            if let (Some(hotplug), Some(lifecycle)) = (&self.hotplug, lifecycle) {
                let render_states = hotplug.render_states.clone();
                tokio::spawn(async move {
                    let mut states = render_states.lock().await;
                    if states
                        .get(&lifecycle.name)
                        .is_some_and(|state| Arc::ptr_eq(state, &lifecycle.render_state))
                    {
                        states.remove(&lifecycle.name);
                    }
                    drop(states);

                    let state = lifecycle.render_state.lock().await;
                    state.playback_gen.fetch_add(1, Ordering::SeqCst);
                    state.pacer.notify();
                    state.video_playback.stop();
                    let render_lock = state.render_lock.clone();
                    drop(state);

                    let _ = tokio::task::spawn_blocking(move || {
                        drop(
                            render_lock
                                .lock()
                                .unwrap_or_else(|poisoned| poisoned.into_inner()),
                        );
                    })
                    .await;
                    if let Some(viewport) = viewport {
                        viewport.destroy();
                    }
                    drop(layer_surface);
                    tracing::info!("Hotplug: cleaned up render state for {}", lifecycle.name);
                });
            } else {
                if let Some(viewport) = viewport {
                    viewport.destroy();
                }
                drop(layer_surface);
            }
        }
    }
}

delegate_registry!(WaylandState);

smithay_client_toolkit::delegate_dispatch2!(WaylandState);

/// Wakes paced live-playback loops when a new commit bumps the generation.
struct LivePacer {
    lock: std::sync::Mutex<()>,
    cond: std::sync::Condvar,
}

impl LivePacer {
    fn new() -> Self {
        Self {
            lock: std::sync::Mutex::new(()),
            cond: std::sync::Condvar::new(),
        }
    }

    fn notify(&self) {
        let _guard = self.lock.lock().unwrap();
        self.cond.notify_all();
    }

    /// Blocks until `deadline` or until `notify` is called, whichever comes
    /// first.
    fn wait_until(&self, deadline: std::time::Instant) {
        let guard = self.lock.lock().unwrap();
        let now = std::time::Instant::now();
        if deadline <= now {
            return;
        }
        // A notification is a real scheduling event: it means a newer
        // wallpaper may have superseded the current player.  Using
        // `wait_timeout_while` with an always-true predicate turns every
        // notify into a spurious wakeup and makes the waiter sleep until its
        // full deadline anyway (up to 24h for paused GIFs).  A plain timed
        // wait returns on notify; the caller then checks the generation and
        // exits without another decode/upload/present.
        let _ = self.cond.wait_timeout(guard, deadline - now);
    }
}

struct RenderState {
    /// GPU resources are grouped behind one ownership boundary so the next
    /// lazy-GPU step can replace this with an optional, on-demand state
    /// without changing static Wayland/shm fields.
    gpu: Option<GpuState>,
    renderer: std::sync::Arc<std::sync::Mutex<Option<std::sync::Arc<Renderer>>>>,
    display_ptr: SendDisplayPtr,
    raw_surface: SendDisplayPtr,
    /// Serializes transition rendering. The lock is only ever held by the
    /// detached render task, never by the IPC loop, so a stalled present
    /// cannot freeze the daemon.
    render_lock: std::sync::Arc<std::sync::Mutex<()>>,
    /// Bumped on every commit. Live playback checks it each frame and stops
    /// as soon as a new wallpaper supersedes the one it is playing.
    playback_gen: std::sync::Arc<std::sync::atomic::AtomicU64>,
    /// Wakes paced live-playback loops when a new commit bumps the generation,
    /// so an old player exits immediately instead of after its sleep quantum.
    pacer: std::sync::Arc<LivePacer>,
    current_bind: Option<wgpu::BindGroup>,
    current_tex: Option<wgpu::Texture>,
    width: u32,
    height: u32,
    current_width: u32,
    current_height: u32,
    /// Video playback manager
    video_playback: std::sync::Arc<crate::video::VideoPlayback>,
    /// Hardware backend to request for new decoders (from `video.hw_decode`).
    hw_accel: crate::video::HwAccel,
    /// GPU adapter policy shared by all outputs in this daemon.
    preferred_gpu: crate::video::GpuSelection,
    /// Maximum decoded frames buffered ahead of presentation.
    preload_frames: usize,
    /// Optional cap for live video presentation.
    max_fps: Option<u32>,
    /// Current scaling mode for live playback.
    scaling_mode: u32,
    /// Effect used by the active request, for idempotent switch detection.
    current_effect: Option<crate::animation::Effect>,
    /// Per-output uniform buffer + bind group (Issue #9 race fix).
    /// Path of the last wallpaper set on this output (for restore).
    last_wallpaper: Option<std::path::PathBuf>,
    /// Previous wallpaper state before blank (for restore).
    pre_blank: Option<(std::path::PathBuf, u32)>,
    /// Whether this output is currently blanked.
    blanked: bool,
    /// GIF playback paused state (shared with play_live task).
    gif_paused: std::sync::Arc<std::sync::atomic::AtomicBool>,
    /// Shared-memory fast path for completed static wallpapers. Dynamic
    /// content and transitions continue to use wgpu; static content can drop
    /// its GPU image and become compositor-owned with no render loop.
    shm_surface: wl_surface::WlSurface,
    /// Server handle for (re)creating the pool. `Shm` itself is not Clone,
    /// but the underlying proxy is; a fresh handle is minted on demand.
    shm_server: wayland_client::protocol::wl_shm::WlShm,
    shm_pool: SlotPool,
    /// Ping-pong shm buffers. The parked buffer is usually the currently
    /// displayed one (legitimately compositor-held), so single-buffer reuse
    /// can never hit in steady use; alternating guarantees the idle buffer
    /// was released when its sibling was presented, bounding the pool.
    shm_buffers: [Option<ShmBuffer>; 2],
    shm_index: usize,
    shm_width: u32,
    shm_height: u32,
    /// Compressed decoded pixels for the static wl_shm path. Keeping the
    /// cache compressed avoids retaining a second full-size framebuffer next
    /// to the compositor-owned shared-memory buffers.
    cached_shm_image: Option<CachedShmImage>,
    /// A layer surface must not switch from wgpu explicit-sync commits to
    /// bufferless `wl_shm` commits. Some compositors reject that sequence
    /// with a missing acquire timeline. Keep static requests on wgpu after
    /// the first GPU presentation for this surface.
    gpu_surface_used: bool,
    /// Cached video texture for reuse across same-dimension video playback.
    /// Reusing Y/UV planes, conversion resources, and output texture avoids
    /// reallocating GPU memory on every video switch when resolution is unchanged.
    /// Wrapped in Arc so it can be shared with active playback tasks.
    cached_video_texture: Option<std::sync::Arc<crate::renderer::VideoTexture>>,
    /// Whether videos restart from the beginning at end of stream.
    loop_video: bool,
}

struct CachedShmImage {
    path: std::path::PathBuf,
    modified: std::time::SystemTime,
    size: u64,
    scaling_mode: u32,
    output_width: u32,
    output_height: u32,
    width: u32,
    height: u32,
    compressed: Vec<u8>,
    raw_len: usize,
}

struct GpuState {
    renderer: std::sync::Arc<Renderer>,
    /// Owned, not leaked: output hotplug must release the swapchain when the
    /// monitor disappears. Detached render tasks clone the `Arc`.
    surface: std::sync::Arc<wgpu::Surface<'static>>,
    format: wgpu::TextureFormat,
    per_output_uniforms: std::sync::Arc<crate::renderer::PerOutputUniforms>,
}

/// Everything the transition render task needs; the daemon state has already
/// been promoted to the new wallpaper before a transition is spawned.
struct CommitData {
    bg_bind: wgpu::BindGroup,
    new_bind: wgpu::BindGroup,
    img_width: u32,
    img_height: u32,
    old_img_width: u32,
    old_img_height: u32,
    format: wgpu::TextureFormat,
    width: u32,
    height: u32,
    /// Animated frames to play live after the transition, when the committed
    /// file is a GIF.
    animated: Option<crate::animated::AnimatedImage>,
    /// Video metadata when committed file is a video.
    is_video: bool,
    /// Plane and conversion resources retained across transition and playback.
    /// Shared via Arc so the cache can retain it for reuse after playback ends.
    video_texture: Option<std::sync::Arc<crate::renderer::VideoTexture>>,
    /// Playback generation captured at commit time; live playback stops when
    /// it no longer matches `RenderState::playback_gen`.
    generation: u64,
    /// Scaling mode: 0=Fill, 1=Fit, 2=Stretch, 3=Center, 4=Tile.
    scaling_mode: u32,
    /// Optional cap for live video presentation.
    max_fps: Option<u32>,
}

impl RenderState {
    fn ensure_gpu(&mut self) -> anyhow::Result<()> {
        if self.gpu.is_some() {
            return Ok(());
        }

        let renderer = {
            let mut shared = self
                .renderer
                .lock()
                .map_err(|_| anyhow::anyhow!("renderer initialization lock poisoned"))?;
            if let Some(renderer) = shared.as_ref() {
                renderer.clone()
            } else {
                let renderer = tokio::runtime::Handle::current()
                    .block_on(Renderer::new(&self.preferred_gpu))
                    .map_err(|e| anyhow::anyhow!("GPU init failed: {e}"))?;
                let renderer = std::sync::Arc::new(renderer);
                *shared = Some(renderer.clone());
                renderer
            }
        };

        let window_handle = WaylandWindow {
            display: self.display_ptr.0,
            surface: self.raw_surface.0,
        };
        let wgpu_surface = renderer
            .instance
            .create_surface(&window_handle)
            .map_err(|e| anyhow::anyhow!("wgpu surface creation failed: {e:?}"))?;
        let formats = wgpu_surface.get_capabilities(&renderer.adapter).formats;
        let format = formats
            .iter()
            .copied()
            .find(|format| *format == wgpu::TextureFormat::Bgra8UnormSrgb)
            .or_else(|| formats.into_iter().next())
            .unwrap_or(wgpu::TextureFormat::Bgra8UnormSrgb);
        wgpu_surface.configure(
            &renderer.device,
            &wgpu::SurfaceConfiguration {
                usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
                format,
                width: self.width,
                height: self.height,
                present_mode: wgpu::PresentMode::Fifo,
                alpha_mode: wgpu::CompositeAlphaMode::Opaque,
                view_formats: vec![],
                color_space: wgpu::SurfaceColorSpace::default(),
                desired_maximum_frame_latency: 1,
            },
        );
        // SAFETY: the Wayland display and layer surface are retained by the
        // daemon for the lifetime of this render state. `RenderState` owns a
        // cloned `wl_surface` proxy and output teardown waits for the render
        // lock before dropping it, so extending the borrow to 'static is
        // valid. Storing the surface by value (instead of leaking it) lets a
        // disconnected output release the swapchain.
        // SAFETY: `create_surface` borrows the Wayland display/surface for
        // the call; the daemon retains both for the lifetime of this render
        // state (the `Connection` lives until process exit and the cloned
        // `wl_surface` proxy is stored in `RenderState`). Extending the
        // borrow to `'static` is therefore sound. The `Surface` is later
        // released by dropping the `Arc`, which hands the swapchain back to
        // wgpu; it is not leaked.
        let wgpu_surface: wgpu::Surface<'static> = unsafe { std::mem::transmute(wgpu_surface) };
        let surface = std::sync::Arc::new(wgpu_surface);
        self.gpu = Some(GpuState {
            renderer: renderer.clone(),
            surface,
            format,
            per_output_uniforms: std::sync::Arc::new(renderer.create_per_output_uniforms()),
        });
        Ok(())
    }

    fn set_wallpaper(
        &mut self,
        path: &std::path::Path,
        effect: &crate::animation::Effect,
        duration_ms: u32,
        scaling_mode: u32,
    ) -> anyhow::Result<()> {
        // Setting the already-active source is an idempotent operation. Do
        // not decode it, allocate another GPU texture, or enqueue another
        // transition merely because a watcher/IPC client repeated the same
        // request. This is especially important for bursty wallpaper
        // scripts, where the no-op path should be effectively free.
        if !self.blanked
            && (self.current_bind.is_some() || self.shm_buffers.iter().any(|b| b.is_some()))
            && self.last_wallpaper.as_deref() == Some(path)
            && self.scaling_mode == scaling_mode
            && self.current_effect.as_ref() == Some(effect)
        {
            return Ok(());
        }
        // A zero-duration static commit does not need a shader or a swapchain
        // frame. Hand the pixels directly to the compositor and release the
        // persistent GPU image, matching the low-idle-cost architecture used
        // by dedicated static wallpaper daemons.
        let is_animated_image = matches!(
            path.extension().and_then(|extension| extension.to_str()),
            Some("gif" | "GIF" | "apng" | "APNG")
        );
        if duration_ms == 0
            && !is_animated_image
            && !crate::video::VideoDecoder::is_video_file(path)
            && !self.gpu_surface_used
        {
            // Cancel an older transition before taking the shared-memory
            // route. Otherwise a FIFO-presenting render task can retain the
            // render lock and its GPU resources while this static request
            // falls back or waits, inflating settled RSS after a switch.
            self.playback_gen.fetch_add(1, Ordering::SeqCst);
            self.pacer.notify();
            self.video_playback.stop();
        }
        if duration_ms == 0
            && !is_animated_image
            && !crate::video::VideoDecoder::is_video_file(path)
            && !self.gpu_surface_used
            && self.commit_static_shm(path, scaling_mode)?
        {
            self.current_bind = None;
            self.current_tex = None;
            self.current_width = 0;
            self.current_height = 0;
            self.scaling_mode = scaling_mode;
            self.current_effect = Some(effect.clone());
            self.last_wallpaper = Some(path.to_path_buf());
            self.blanked = false;
            // Dropping the old bind group/texture is enough to release the
            // Rust-side ownership. A blocking device drain here makes every
            // static switch wait for unrelated GPU work even though the new
            // frame is already compositor-owned through wl_shm. The render
            // path polls when it actually needs synchronization.
            return Ok(());
        }
        self.ensure_gpu()?;
        let commit = self.commit_wallpaper(path, scaling_mode)?;
        self.gpu_surface_used = true;
        self.scaling_mode = scaling_mode;
        self.current_effect = Some(effect.clone());
        self.spawn_transition(commit, effect, duration_ms);
        // Update last_wallpaper after successful commit
        self.last_wallpaper = Some(path.to_path_buf());
        Ok(())
    }

    fn commit_static_shm(
        &mut self,
        path: &std::path::Path,
        scaling_mode: u32,
    ) -> anyhow::Result<bool> {
        use image::{ImageDecoder, ImageReader};

        // The wgpu transition task and the wl_shm fast path target the same
        // layer surface. Serialize the protocol commit so a static switch
        // cannot race an in-flight GPU present.
        // A transition can be parked indefinitely in FIFO present while a
        // compositor is suspended or a monitor is disabled. Never make an
        // IPC/static switch wait behind that task: fall back to the normal
        // GPU commit, which promotes the new generation and lets the stale
        // transition exit before it renders again.
        let Some(_render_guard) = self.render_lock.try_lock().ok() else {
            return Ok(false);
        };

        let source = std::fs::metadata(path)?;
        let modified = source.modified().unwrap_or(std::time::UNIX_EPOCH);
        let cached = self.cached_shm_image.as_ref().filter(|cached| {
            cached.path == path
                && cached.modified == modified
                && cached.size == source.len()
                && cached.scaling_mode == scaling_mode
                && cached.output_width == self.width
                && cached.output_height == self.height
        });
        let cached_rgba = cached.and_then(|cached| {
            zstd::bulk::decompress(&cached.compressed, cached.raw_len)
                .ok()
                .map(|rgba| (rgba, cached.width, cached.height))
        });
        let (rgba, width, height) = if let Some((rgba, width, height)) = cached_rgba {
            (rgba, width, height)
        } else {
            let decoder = ImageReader::open(path)?.into_decoder()?;
            let (source_width, source_height) = decoder.dimensions();
            Renderer::validate_static_decode(source_width, source_height, decoder.total_bytes())?;
            let image = image::DynamicImage::from_decoder(decoder)?;
            let (rgba, width, height) = crate::renderer::prepare_image_rgba(
                &image,
                self.width,
                self.height,
                scaling_mode,
                wgpu::Limits::default().max_texture_dimension_2d,
            )?;
            let rgba = rgba.into_raw();
            let compressed = zstd::bulk::compress(&rgba, 1)?;
            if compressed.len() <= STATIC_CACHE_LIMIT_BYTES {
                self.cached_shm_image = Some(CachedShmImage {
                    path: path.to_path_buf(),
                    modified,
                    size: source.len(),
                    scaling_mode,
                    output_width: self.width,
                    output_height: self.height,
                    width,
                    height,
                    raw_len: rgba.len(),
                    compressed,
                });
            } else {
                self.cached_shm_image = None;
            }
            (rgba, width, height)
        };
        if width != self.width || height != self.height {
            // wl_shm buffers are displayed at their native size. The GPU path
            // remains responsible for center/tile and other non-fullscreen
            // modes that cannot be represented by one compositor buffer.
            return Ok(false);
        }

        let stride = width
            .checked_mul(4)
            .ok_or_else(|| anyhow::anyhow!("static image stride overflow"))?;
        // Ping-pong between two buffers. The parked buffer is usually the
        // currently displayed one (legitimately compositor-held, so waiting
        // on it is futile); alternating guarantees the idle sibling was
        // released when its partner was presented, so steady-state switching
        // never allocates and the pool never grows.
        let mut used_slot = 0usize;
        let mut chosen: Option<ShmBuffer> = None;
        if self.shm_width == width && self.shm_height == height {
            for _ in 0..2 {
                let slot = self.shm_index % 2;
                self.shm_index = self.shm_index.wrapping_add(1);
                if let Some(buffer) = self.shm_buffers[slot].take() {
                    if buffer.canvas(&mut self.shm_pool).is_some() {
                        chosen = Some(buffer);
                        used_slot = slot;
                        break;
                    }
                    self.shm_buffers[slot] = Some(buffer);
                }
            }
            if chosen.is_none() {
                // Both slots busy under sustained flood. Wait briefly for a
                // release on a detached task (never the Wayland event loop).
                'wait: for _ in 0..10 {
                    std::thread::sleep(std::time::Duration::from_millis(5));
                    for slot in 0..2 {
                        if let Some(buffer) = self.shm_buffers[slot].take() {
                            if buffer.canvas(&mut self.shm_pool).is_some() {
                                chosen = Some(buffer);
                                used_slot = slot;
                                break 'wait;
                            }
                            self.shm_buffers[slot] = Some(buffer);
                        }
                    }
                }
            }
        } else {
            // Output size changed: drop both parked buffers (rare path).
            self.shm_buffers = [None, None];
        }
        let buffer = match chosen {
            Some(buffer) => buffer,
            None => {
                // No free buffer. Never grow the pool beyond the pair:
                // pool growth is process-lifetime high-water billed to
                // post-workload RSS (measured ~390 MiB retained after 90
                // rapid switches with unbounded growth).
                if self.shm_width != width || self.shm_height != height {
                    // Output size changed: reset the pair (rare path).
                    self.shm_buffers = [None, None];
                    let (new_buffer, _) = self.shm_pool.create_buffer(
                        width as i32,
                        height as i32,
                        stride as i32,
                        wayland_client::protocol::wl_shm::Format::Xrgb8888,
                    )?;
                    used_slot = 0;
                    new_buffer
                } else if let Some(slot) = self.shm_buffers.iter().position(|slot| slot.is_none()) {
                    // Priming the pair: still bounded at two buffers.
                    let (new_buffer, _) = self.shm_pool.create_buffer(
                        width as i32,
                        height as i32,
                        stride as i32,
                        wayland_client::protocol::wl_shm::Format::Xrgb8888,
                    )?;
                    used_slot = slot;
                    new_buffer
                } else {
                    // Both slots busy: the compositor is more than a frame
                    // behind under flood. Fall back to the GPU path instead
                    // of growing the pool; it promotes its own texture and
                    // a later commit reuses a released slot.
                    return Ok(false);
                }
            }
        };
        let canvas = buffer
            .canvas(&mut self.shm_pool)
            .ok_or_else(|| anyhow::anyhow!("shared-memory wallpaper buffer is still active"))?;
        for (src, dst) in rgba
            .as_chunks::<4>()
            .0
            .iter()
            .zip(canvas.as_chunks_mut::<4>().0.iter_mut())
        {
            // XRGB8888 is stored as B,G,R,X on little-endian Wayland hosts.
            // Write channels directly so the hot conversion loop does not
            // construct a temporary slice for every pixel.
            dst[0] = src[2];
            dst[1] = src[1];
            dst[2] = src[0];
            dst[3] = 0xff;
        }
        buffer
            .attach_to(&self.shm_surface)
            .map_err(|e| anyhow::anyhow!(e))?;
        self.shm_surface
            .damage_buffer(0, 0, width as i32, height as i32);
        self.shm_surface.commit();
        self.shm_buffers[used_slot] = Some(buffer);
        self.shm_width = width;
        self.shm_height = height;
        Ok(true)
    }

    /// Loads the new wallpaper and atomically promotes it to the current
    /// frame. The outgoing bind group stays alive for the transition, so the
    /// render task can keep drawing from it after this commit returns.
    fn commit_wallpaper(
        &mut self,
        path: &std::path::Path,
        scaling_mode: u32,
    ) -> anyhow::Result<CommitData> {
        use image::{ImageDecoder, ImageReader};
        let gpu = self
            .gpu
            .as_ref()
            .expect("GPU state required for dynamic content");

        // Check if this is a video file FIRST
        if crate::video::VideoDecoder::is_video_file(path) {
            tracing::info!("Video file detected: {:?}", path);

            let generation = self.playback_gen.load(Ordering::SeqCst).wrapping_add(1);
            let renderer = gpu.renderer.clone();
            // Prepare and validate the new decoder before replacing active
            // playback. A failed video therefore leaves the old wallpaper and
            // decoder untouched.
            let mut prepared = crate::video::VideoPlayback::prepare(
                path,
                self.hw_accel,
                self.preload_frames,
                self.loop_video,
                // Allow slow software decoders a fair window to produce the
                // first frame before falling back to a black start.
                std::time::Duration::from_secs(5),
                move |metadata| {
                    renderer
                        .validate_video_texture(metadata.width, metadata.height)
                        .map_err(crate::video::VideoError::GpuResourceCreation)
                },
            )?;
            prepared.set_max_output_fps(self.max_fps);
            let metadata = prepared.metadata().clone();
            let first_frame = prepared.take_first_frame();

            let (tex_width, tex_height) = first_frame
                .as_ref()
                .map(|frame| (frame.width, frame.height))
                .unwrap_or((metadata.width, metadata.height));

            // Reuse the cached video texture if dimensions match, avoiding
            // Y/UV/output texture reallocation when switching between same-resolution videos.
            let video_texture = if let Some(cached) = self.cached_video_texture.as_ref()
                && cached.matches_dimensions(tex_width, tex_height)
            {
                tracing::debug!("Reusing video texture for {}x{}", tex_width, tex_height);
                // Keep the Arc in the cache; clone for CommitData so both hold a reference
                cached.clone()
            } else {
                if let Some(previous) = self.cached_video_texture.as_ref() {
                    tracing::debug!(
                        "Video resolution changed, recreating texture: {}x{} -> {}x{}",
                        previous.width(),
                        previous.height(),
                        tex_width,
                        tex_height
                    );
                }
                let new_texture =
                    std::sync::Arc::new(gpu.renderer.create_video_texture(tex_width, tex_height)?);
                // Store in cache for future reuse
                self.cached_video_texture = Some(new_texture.clone());
                new_texture
            };
            let (img_width, img_height) = if let Some(frame) = first_frame {
                gpu.renderer
                    .update_video_texture(&video_texture, &frame.data)?;
                (frame.width, frame.height)
            } else {
                // WebGPU initializes the output to black when no frame arrives.
                tracing::warn!("No first frame available, using black texture");
                (metadata.width, metadata.height)
            };
            self.video_playback.commit(prepared, generation);
            self.playback_gen.store(generation, Ordering::SeqCst);
            self.pacer.notify();
            let new_tex = video_texture.texture().clone();
            let new_bind = video_texture.bind_group().clone();

            let old_bind = self.current_bind.take();
            let (old_img_width, old_img_height) = if old_bind.is_some() {
                (self.current_width.max(1), self.current_height.max(1))
            } else {
                (img_width, img_height)
            };
            let bg_bind = old_bind.unwrap_or_else(|| new_bind.clone());

            drop(self.current_tex.take());
            self.current_tex = Some(new_tex);
            self.current_bind = Some(new_bind.clone());
            self.current_width = img_width;
            self.current_height = img_height;

            return Ok(CommitData {
                bg_bind,
                new_bind,
                img_width,
                img_height,
                old_img_width,
                old_img_height,
                format: gpu.format,
                width: self.width,
                height: self.height,
                animated: None,
                is_video: true,
                video_texture: Some(video_texture),
                generation,
                scaling_mode,
                max_fps: self.max_fps,
            });
        }

        // Stream animated frames (GIF) on demand during playback; the
        // transition's incoming texture is the GIF's first frame.
        let mut animated = crate::animated::AnimatedImage::decode(path)?;
        let (new_tex, new_bind, img_width, img_height) = if let Some(anim) = animated.as_mut() {
            let (w, h) = (anim.width, anim.height);
            let (tex, bind) = gpu.renderer.create_texture(w, h)?;
            let first = anim.first_frame();
            if !first.is_empty() {
                gpu.renderer.update_texture(&tex, first, w, h);
            }
            (tex, bind, w, h)
        } else {
            let decoder = ImageReader::open(path)?.into_decoder()?;
            let (source_width, source_height) = decoder.dimensions();
            Renderer::validate_static_decode(source_width, source_height, decoder.total_bytes())?;
            let new_img = image::DynamicImage::from_decoder(decoder)?;
            let (tex, bind, width, height) =
                gpu.renderer
                    .load_texture(&new_img, self.width, self.height, scaling_mode)?;
            (tex, bind, width, height)
        };

        // Only supersede active video playback after the replacement has
        // decoded and allocated successfully.
        self.video_playback.stop();
        // Release cached video texture when switching away from video.
        // Static and GIF wallpapers don't need NV12 conversion resources.
        self.cached_video_texture = None;

        let old_bind = self.current_bind.take();
        let (old_img_width, old_img_height) = if old_bind.is_some() {
            (self.current_width.max(1), self.current_height.max(1))
        } else {
            (img_width, img_height)
        };
        // Keep the last image as the outgoing frame. On the first ever run,
        // using the incoming image for both sides is a clean no-op transition;
        // it avoids a black flash while still allowing the cached wallpaper
        // restored at daemon startup to become the real outgoing frame.
        let bg_bind = old_bind.unwrap_or_else(|| new_bind.clone());

        drop(self.current_tex.take());
        self.current_tex = Some(new_tex);
        self.current_bind = Some(new_bind.clone());
        self.current_width = img_width;
        self.current_height = img_height;

        let generation = self.playback_gen.fetch_add(1, Ordering::SeqCst) + 1;
        self.pacer.notify();

        Ok(CommitData {
            bg_bind,
            new_bind,
            img_width,
            img_height,
            old_img_width,
            old_img_height,
            format: gpu.format,
            width: self.width,
            height: self.height,
            animated,
            is_video: false,
            video_texture: None,
            generation,
            scaling_mode,
            max_fps: self.max_fps,
        })
    }

    /// Renders the committed transition on a detached blocking task. The IPC
    /// path never waits on GPU presents, so a stalled compositor (monitor
    /// off, suspend) cannot hang the daemon. Transitions are serialized by
    /// the render lock: a later one simply waits until the earlier drains.
    fn spawn_transition(
        &self,
        commit: CommitData,
        effect: &crate::animation::Effect,
        duration_ms: u32,
    ) {
        let gpu = self
            .gpu
            .as_ref()
            .expect("GPU state required for transitions");
        let renderer = gpu.renderer.clone();
        let surface = std::sync::Arc::clone(&gpu.surface);
        let render_lock = self.render_lock.clone();
        let playback_gen = self.playback_gen.clone();
        let pacer = self.pacer.clone();
        let video_playback = self.video_playback.clone();
        let per_output_uniforms = std::sync::Arc::clone(&gpu.per_output_uniforms);
        let gif_paused = self.gif_paused.clone();
        let effect = effect.clone();
        drop(tokio::task::spawn_blocking(move || {
            render_transition(
                renderer,
                surface,
                render_lock,
                playback_gen,
                pacer,
                video_playback,
                gif_paused,
                commit,
                effect,
                duration_ms,
                &per_output_uniforms,
            );
        }));
    }
}

async fn restore_cached_wallpaper(name: &str, render_state: &Arc<Mutex<RenderState>>) {
    let state_root = wallpaper_state_root();
    let Some(path) = read_wallpaper_state(&state_root, "last_wallpaper", name) else {
        return;
    };

    let effect = crate::animation::Effect::Fade(crate::animation::FadeParams::default());
    // Restoring a cached static wallpaper does not need an entrance
    // transition. Avoid decoding/uploading a temporary GPU frame at daemon
    // startup; static images can settle directly through the zero-duration
    // path, while GIF/video inputs still select their dynamic pipeline.
    if let Err(err) = set_wallpaper_with_retry(render_state, &path, &effect, 0, 0).await {
        tracing::warn!("Failed to restore wallpaper for {name} from {path:?}: {err}");
        let Some(previous) = read_wallpaper_state(&state_root, "previous_wallpaper", name) else {
            return;
        };
        match set_wallpaper_with_retry(render_state, &previous, &effect, 0, 0).await {
            Ok(()) => {
                if let Err(persist_err) =
                    write_wallpaper_state(&state_root, "last_wallpaper", name, &previous)
                {
                    tracing::warn!(
                        "Restored previous wallpaper for {name}, but failed to update state: {persist_err}"
                    );
                } else {
                    tracing::warn!("Restored previous wallpaper for {name} after {path:?} failed");
                }
            }
            Err(previous_err) => tracing::warn!(
                "Failed to restore previous wallpaper for {name} from {previous:?}: {previous_err}"
            ),
        }
    }
}

const WALLPAPER_RETRY_ATTEMPTS: usize = 3;
const WALLPAPER_RETRY_DELAY: std::time::Duration = std::time::Duration::from_millis(150);
/// `SlotPool` grows automatically when a buffer does not fit. Keep daemon
/// startup cheap instead of reserving a full output-sized shm mapping before
/// the first static wallpaper is requested.
const INITIAL_SHM_POOL_BYTES: usize = 4096;
/// Keep the static cache from competing with the compositor's framebuffer
/// buffers. Large photographic frames are decoded again instead of becoming
/// a hidden resident-memory tax.
const STATIC_CACHE_LIMIT_BYTES: usize = 4 * 1024 * 1024;

async fn set_wallpaper_with_retry(
    render_state: &Arc<Mutex<RenderState>>,
    path: &std::path::Path,
    effect: &crate::animation::Effect,
    duration_ms: u32,
    scaling_mode: u32,
) -> anyhow::Result<()> {
    let render_state = Arc::clone(render_state);
    let path = path.to_path_buf();
    let effect = effect.clone();

    tokio::task::spawn_blocking(move || {
        let mut attempt = 1;
        loop {
            let result = {
                let mut state = render_state.blocking_lock();
                state.set_wallpaper(&path, &effect, duration_ms, scaling_mode)
            };
            match result {
                Ok(()) => return Ok(()),
                Err(err)
                    if attempt < WALLPAPER_RETRY_ATTEMPTS
                        && is_transient_wallpaper_error(&err) =>
                {
                    tracing::warn!(
                        "Transient wallpaper error for {path:?} (attempt {attempt}/{WALLPAPER_RETRY_ATTEMPTS}): {err}"
                    );
                    attempt += 1;
                    std::thread::sleep(WALLPAPER_RETRY_DELAY);
                }
                Err(err) => return Err(err),
            }
        }
    })
    .await?
}

fn is_transient_wallpaper_error(err: &anyhow::Error) -> bool {
    err.chain().any(|cause| {
        cause
            .downcast_ref::<std::io::Error>()
            .is_some_and(|io_err| {
                matches!(
                    io_err.kind(),
                    std::io::ErrorKind::Interrupted
                        | std::io::ErrorKind::WouldBlock
                        | std::io::ErrorKind::TimedOut
                )
            })
            || cause
                .downcast_ref::<crate::video::VideoError>()
                .is_some_and(crate::video::VideoError::is_recoverable)
    })
}

fn wallpaper_state_root() -> std::path::PathBuf {
    dirs::cache_dir()
        .unwrap_or_else(|| std::path::PathBuf::from("/tmp"))
        .join("wallr")
}

fn wallpaper_state_path(root: &std::path::Path, state_dir: &str, name: &str) -> std::path::PathBuf {
    root.join(state_dir).join(name)
}

fn read_wallpaper_state(
    root: &std::path::Path,
    state_dir: &str,
    name: &str,
) -> Option<std::path::PathBuf> {
    use std::os::unix::ffi::OsStringExt;

    let path = std::fs::read(wallpaper_state_path(root, state_dir, name)).ok()?;
    let wallpaper = std::path::PathBuf::from(std::ffi::OsString::from_vec(path));
    (!wallpaper.as_os_str().is_empty()).then_some(wallpaper)
}

fn write_wallpaper_state(
    root: &std::path::Path,
    state_dir: &str,
    name: &str,
    wallpaper: &std::path::Path,
) -> std::io::Result<()> {
    use std::io::Write;
    use std::os::unix::ffi::OsStrExt;
    use std::sync::atomic::{AtomicU64, Ordering};

    static TEMP_ID: AtomicU64 = AtomicU64::new(0);

    let state_path = wallpaper_state_path(root, state_dir, name);
    let parent = state_path
        .parent()
        .ok_or_else(|| std::io::Error::other("wallpaper state path has no parent"))?;
    std::fs::create_dir_all(parent)?;
    let file_name = state_path
        .file_name()
        .and_then(|value| value.to_str())
        .unwrap_or("wallpaper");

    loop {
        let id = TEMP_ID.fetch_add(1, Ordering::Relaxed);
        let temporary_path = parent.join(format!(".{file_name}.{}.{}.tmp", std::process::id(), id));
        match std::fs::OpenOptions::new()
            .write(true)
            .create_new(true)
            .open(&temporary_path)
        {
            Ok(mut temporary) => {
                if let Err(err) = temporary
                    .write_all(wallpaper.as_os_str().as_bytes())
                    .and_then(|()| temporary.sync_all())
                    .and_then(|()| std::fs::rename(&temporary_path, &state_path))
                {
                    let _ = std::fs::remove_file(&temporary_path);
                    return Err(err);
                }
                return Ok(());
            }
            Err(err) if err.kind() == std::io::ErrorKind::AlreadyExists => continue,
            Err(err) => return Err(err),
        }
    }
}

fn persist_wallpaper(name: &str, wallpaper: &std::path::Path) -> std::io::Result<()> {
    let root = wallpaper_state_root();
    persist_wallpaper_at(&root, name, wallpaper)
}

fn persist_wallpaper_at(
    root: &std::path::Path,
    name: &str,
    wallpaper: &std::path::Path,
) -> std::io::Result<()> {
    let current = read_wallpaper_state(root, "last_wallpaper", name);
    // Hot-path no-op: a repeated set of the already-active wallpaper (bursty
    // scripts, benchmark loops) must not pay two temp-file writes, two
    // fsyncs, and two renames per call. The on-disk state is already correct,
    // and fsync latency spikes are the dominant jitter source on this path.
    if current.as_deref() == Some(wallpaper) {
        return Ok(());
    }
    let previous = current.filter(|current| current.exists() && current != wallpaper);
    write_wallpaper_state(root, "last_wallpaper", name, wallpaper)?;
    if let Some(previous) = previous {
        write_wallpaper_state(root, "previous_wallpaper", name, &previous)?;
    }
    Ok(())
}

/// Presents one frame per vsync until the wall-clock duration elapses. With
/// PresentMode::Fifo, `get_current_texture` blocks until the previous frame
/// is presented, so this loop is paced to the monitor refresh rate, and the
/// transition lasts exactly `duration_ms` on any refresh rate - frame-count
/// pacing would run too fast on high-refresh panels and too slow when the
/// present rate is low. If the compositor stops presenting, the loop can park
/// inside a present; that is fine here because the task is detached.
#[allow(clippy::too_many_arguments)]
fn render_transition(
    renderer: std::sync::Arc<Renderer>,
    surface: std::sync::Arc<wgpu::Surface<'static>>,
    render_lock: std::sync::Arc<std::sync::Mutex<()>>,
    playback_gen: std::sync::Arc<std::sync::atomic::AtomicU64>,
    pacer: std::sync::Arc<LivePacer>,
    video_playback: std::sync::Arc<crate::video::VideoPlayback>,
    gif_paused: std::sync::Arc<std::sync::atomic::AtomicBool>,
    mut commit: CommitData,
    effect: crate::animation::Effect,
    duration_ms: u32,
    per_output_uniforms: &crate::renderer::PerOutputUniforms,
) {
    // Do this check before taking the render lock. Rapid IPC updates can
    // otherwise queue several detached tasks, each retaining a complete
    // incoming/outgoing GPU resource pair while waiting for its turn.
    if playback_gen.load(Ordering::Acquire) != commit.generation {
        reclaim_commit_resources(&renderer, commit);
        return;
    }
    let _guard = render_lock
        .lock()
        .unwrap_or_else(|poisoned| poisoned.into_inner());

    let duration = std::time::Duration::from_millis(u64::from(duration_ms.max(1)));
    let start = std::time::Instant::now();
    loop {
        // A newer commit owns the output now. Abort before doing any more
        // CPU/GPU work so superseded transitions release their bind groups,
        // textures, and task stack immediately instead of queueing behind the
        // render lock for the full transition duration.
        if playback_gen.load(Ordering::Acquire) != commit.generation {
            reclaim_commit_resources(&renderer, commit);
            return;
        }
        let progress = start.elapsed().as_secs_f32() / duration.as_secs_f32();
        let uniforms = crate::animation::compute_effect_uniforms(&effect, progress.clamp(0.0, 1.0));
        let status = renderer.render_frame(
            crate::renderer::FrameRequest {
                surface: &surface,
                format: commit.format,
                bg_bind: &commit.bg_bind,
                new_bind: &commit.new_bind,
                effect: &uniforms,
                width: commit.width,
                height: commit.height,
                img_width: commit.img_width,
                img_height: commit.img_height,
                old_img_width: commit.old_img_width,
                old_img_height: commit.old_img_height,
                scaling_mode: commit.scaling_mode,
            },
            per_output_uniforms,
        );
        let status = match status {
            Ok(status) => status,
            Err(err) => {
                eprintln!("wallr: transition render failed: {err}");
                break;
            }
        };
        if progress >= 1.0 {
            break;
        }
        match status {
            crate::renderer::FrameStatus::Presented => {}
            // A stalled compositor parks inside `get_current_texture`; a
            // timeout just means "try the next vsync" without breaking the
            // wall-clock duration. Yield briefly so a struggling compositor
            // is not hammered with back-to-back acquires.
            crate::renderer::FrameStatus::TimedOut => {
                std::thread::sleep(std::time::Duration::from_millis(4));
            }
            // The swapchain is stale (resize, scale, recreation). Reconfigure
            // once and continue the transition instead of blanking.
            crate::renderer::FrameStatus::Outdated | crate::renderer::FrameStatus::Lost => {
                surface.configure(
                    &renderer.device,
                    &wgpu::SurfaceConfiguration {
                        usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
                        format: commit.format,
                        width: commit.width.max(1),
                        height: commit.height.max(1),
                        present_mode: wgpu::PresentMode::Fifo,
                        alpha_mode: wgpu::CompositeAlphaMode::Opaque,
                        view_formats: vec![],
                        color_space: wgpu::SurfaceColorSpace::default(),
                        desired_maximum_frame_latency: 1,
                    },
                );
            }
        }
    }

    // The transition ended; if the committed wallpaper is an animated GIF and
    // nothing superseded it while we rendered, keep the render lock and play
    // the frames live until the next commit bumps the generation.
    let mut animated = commit.animated.take();
    if let Some(animated) = animated.as_mut()
        && playback_gen.load(Ordering::SeqCst) == commit.generation
    {
        play_live(
            &renderer,
            &surface,
            &commit,
            animated,
            &playback_gen,
            &pacer,
            &gif_paused,
            per_output_uniforms,
        );
    } else if commit.is_video && playback_gen.load(Ordering::SeqCst) == commit.generation {
        play_video(
            &renderer,
            &surface,
            &commit,
            &video_playback,
            &playback_gen,
            &pacer,
            per_output_uniforms,
        );
    }
    // Ensure resources from a completed static transition, or a live player
    // that just stopped, are handed back to the backend before the detached
    // task disappears. This is intentionally outside the frame hot path.
    reclaim_commit_resources(&renderer, commit);
}

fn reclaim_commit_resources(renderer: &Renderer, commit: CommitData) {
    drop(commit);
    renderer
        .device
        .poll(wgpu::PollType::wait_indefinitely())
        .ok();
}

/// GIF double-buffer slot advance.
///
/// Returns the new (displayed texture index, displayed frame, idle-texture
/// frame) plus whether the requested frame can be shown. A failed upload
/// leaves the previous frame presented so the caller retries; flipping to
/// an unwritten texture makes the wallpaper visibly alternate between the
/// old and new image.
fn advance_gif_slots(
    cur: usize,
    cur_frame: usize,
    next_frame: usize,
    index: usize,
    upload_ok: bool,
) -> (usize, usize, usize, bool) {
    if index == cur_frame {
        return (cur, cur_frame, next_frame, true);
    }
    let target = cur ^ 1;
    if next_frame == index {
        // The idle texture was already warmed with this frame.
        return (target, index, next_frame, true);
    }
    if upload_ok {
        return (target, index, index, true);
    }
    (cur, cur_frame, next_frame, false)
}

/// Presents live wallpaper frames until the next commit. One frame is
/// presented per GIF frame boundary instead of at the monitor refresh rate.
/// Two textures are double-buffered and frames are decompressed directly
/// into a mapped staging ring (no intermediate copy), so the wake path only
/// presents and the pacing sleep hides the decode/upload entirely.
#[allow(clippy::too_many_arguments)]
fn play_live(
    renderer: &Renderer,
    surface: &wgpu::Surface<'static>,
    commit: &CommitData,
    animated: &mut crate::animated::AnimatedImage,
    playback_gen: &std::sync::atomic::AtomicU64,
    pacer: &LivePacer,
    gif_paused: &std::sync::Arc<std::sync::atomic::AtomicBool>,
    per_output_uniforms: &crate::renderer::PerOutputUniforms,
) {
    let Ok((tex_a, bind_a)) = renderer.create_texture(animated.width, animated.height) else {
        tracing::warn!(
            "GIF dimensions {}x{} exceed the GPU texture limit",
            animated.width,
            animated.height
        );
        return;
    };
    let Ok((tex_b, bind_b)) = renderer.create_texture(animated.width, animated.height) else {
        tracing::warn!(
            "GIF dimensions {}x{} exceed the GPU texture limit",
            animated.width,
            animated.height
        );
        return;
    };
    let (frame_w, frame_h) = (animated.width, animated.height);
    let (bytes_per_row, rows) = (frame_w * 4, frame_h);
    let frame_bytes = bytes_per_row as u64 * rows as u64;

    // Map+decompress+copy path needs a byte-per-row multiple of the copy
    // alignment; fall back to write_texture for odd widths.
    let direct_upload = bytes_per_row % 256 == 0;
    let staging: Vec<wgpu::Buffer> = if direct_upload {
        (0..2)
            .map(|_| {
                renderer.device.create_buffer(&wgpu::BufferDescriptor {
                    label: Some("wallr-gif-staging"),
                    size: frame_bytes,
                    usage: wgpu::BufferUsages::MAP_WRITE | wgpu::BufferUsages::COPY_SRC,
                    mapped_at_creation: false,
                })
            })
            .collect()
    } else {
        Vec::new()
    };

    let first = animated.first_frame();
    if !first.is_empty() {
        renderer.update_texture(&tex_a, first, frame_w, frame_h);
        renderer.update_texture(&tex_b, first, frame_w, frame_h);
    }
    let binds = [bind_a, bind_b];
    let textures = [tex_a, tex_b];

    // Uploads frame `index` into `textures[tgt]`. Returns true when the GPU
    // copy was recorded.
    let upload = |renderer: &Renderer,
                  tgt: usize,
                  index: usize,
                  slot: usize,
                  animated: &mut crate::animated::AnimatedImage|
     -> bool {
        if direct_upload {
            let buffer = &staging[slot];
            let slice = buffer.slice(..);
            slice.map_async(wgpu::MapMode::Write, |_| {});
            renderer
                .device
                .poll(wgpu::PollType::wait_indefinitely())
                .ok();
            let size = slice.size() as usize;
            let mut tmp = vec![0u8; size];
            let ok = animated.decompress_into(index, &mut tmp);
            if ok {
                let mut mapped = slice.get_mapped_range_mut().unwrap();
                mapped.copy_from_slice(&tmp);
            }
            buffer.unmap();
            if ok {
                let mut encoder = renderer
                    .device
                    .create_command_encoder(&wgpu::CommandEncoderDescriptor::default());
                encoder.copy_buffer_to_texture(
                    wgpu::TexelCopyBufferInfo {
                        buffer,
                        layout: wgpu::TexelCopyBufferLayout {
                            offset: 0,
                            bytes_per_row: Some(bytes_per_row),
                            rows_per_image: Some(rows),
                        },
                    },
                    wgpu::TexelCopyTextureInfo {
                        texture: &textures[tgt],
                        mip_level: 0,
                        origin: wgpu::Origin3d::ZERO,
                        aspect: wgpu::TextureAspect::All,
                    },
                    wgpu::Extent3d {
                        width: frame_w,
                        height: frame_h,
                        depth_or_array_layers: 1,
                    },
                );
                renderer.queue.submit([encoder.finish()]);
                return true;
            }
        } else {
            let frame = animated.frame_at(index);
            if !frame.is_empty() {
                renderer.update_texture(&textures[tgt], frame, frame_w, frame_h);
                return true;
            }
        }
        false
    };

    let mut cur = 0usize; // texture index currently holding the presented frame
    let mut cur_frame = 0usize; // frame index currently in texture `cur`
    let mut next_frame = 0usize; // frame index currently in the idle texture
    let mut slot = 0usize; // staging ring slot for the next upload
    let start = std::time::Instant::now();
    let mut paused_elapsed = std::time::Duration::ZERO; // Accumulated pause time
    let static_effect = crate::animation::Effect::Fade(crate::animation::FadeParams::default());
    loop {
        if playback_gen.load(Ordering::SeqCst) != commit.generation {
            return;
        }

        // Check if paused - if so, keep presenting the current frame but don't advance
        if gif_paused.load(Ordering::SeqCst) {
            // The compositor retains the last committed buffer. Re-presenting
            // an identical frame while paused only burns CPU/GPU time and
            // wakes laptops needlessly. Park until resume or a replacement
            // wallpaper notifies the shared pacer.
            let pause_start = std::time::Instant::now();
            pacer.wait_until(std::time::Instant::now() + std::time::Duration::from_secs(86_400));
            paused_elapsed += pause_start.elapsed();
            continue;
        }

        let index = animated.frame_index_at(start.elapsed() - paused_elapsed);
        if index != cur_frame {
            // Advance the double buffer only when the next frame actually
            // reaches the GPU. Uploads fail transiently while the streaming
            // decoder catches up (loop wrap, uncached tail). Flipping the
            // presented texture without data would show a stale frame for a
            // whole frame period: the on-screen result looks exactly like
            // the wallpaper alternating old/new/old as uploads alternate
            // success and failure. Keep displaying the last good frame and
            // retry on the next pass instead.
            let target = cur ^ 1;
            let upload_ok = if next_frame == index {
                true
            } else {
                let ok = upload(renderer, target, index, slot, animated);
                if ok {
                    slot ^= 1;
                }
                ok
            };
            let (new_cur, new_cur_frame, new_next, displayable) =
                advance_gif_slots(cur, cur_frame, next_frame, index, upload_ok);
            if !displayable {
                // The decoder has not caught up yet. Yield briefly so it can
                // produce the frame instead of busy-spinning the program
                // whole (a spin keeps every present late and reads as
                // heavy frame-by-frame staggering); then retry.
                pacer.wait_until(std::time::Instant::now() + std::time::Duration::from_millis(2));
                continue;
            }
            cur = new_cur;
            cur_frame = new_cur_frame;
            next_frame = new_next;
        }
        let uniforms = crate::animation::compute_effect_uniforms(&static_effect, 1.0);
        let status = renderer.render_frame(
            crate::renderer::FrameRequest {
                surface,
                format: commit.format,
                bg_bind: &binds[cur],
                new_bind: &binds[cur],
                effect: &uniforms,
                width: commit.width,
                height: commit.height,
                img_width: animated.width,
                img_height: animated.height,
                old_img_width: animated.width,
                old_img_height: animated.height,
                scaling_mode: commit.scaling_mode,
            },
            per_output_uniforms,
        );
        match status {
            Ok(crate::renderer::FrameStatus::Presented) => {}
            // A timeout is transient compositor backpressure, not a reason
            // to stop the animation: yield briefly and keep presenting.
            // (Previously any non-present status killed GIF playback.)
            Ok(crate::renderer::FrameStatus::TimedOut) => {
                std::thread::sleep(std::time::Duration::from_millis(4));
            }
            Ok(crate::renderer::FrameStatus::Outdated | crate::renderer::FrameStatus::Lost) => {
                surface.configure(
                    &renderer.device,
                    &wgpu::SurfaceConfiguration {
                        usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
                        format: commit.format,
                        width: commit.width.max(1),
                        height: commit.height.max(1),
                        present_mode: wgpu::PresentMode::Fifo,
                        alpha_mode: wgpu::CompositeAlphaMode::Opaque,
                        view_formats: vec![],
                        color_space: wgpu::SurfaceColorSpace::default(),
                        desired_maximum_frame_latency: 1,
                    },
                );
            }
            Err(err) => {
                tracing::warn!("GIF present failed ({err}), stopping playback");
                return;
            }
        }

        // Pace to the next GIF frame boundary instead of presenting at the
        // monitor refresh rate: an animated wallpaper only needs a present
        // when its frame changes. A commit wakes us via the pacer. The
        // boundary is computed in absolute time (frame_start is loop-relative,
        // so add the completed loops) to stay correct after the animation
        // wraps. While waiting, warm the idle texture with the next frame so
        // the wake path stays on the hot critical section.
        let elapsed = start.elapsed() - paused_elapsed;
        let total: std::time::Duration = animated.total_duration();
        let loops = (elapsed.as_millis() / total.as_millis().max(1)) as u64;
        let next_change = animated.frame_start(index + 1) + total * (loops as u32);
        let wait = next_change.saturating_sub(elapsed);
        if wait > std::time::Duration::ZERO {
            let next = index + 1;
            if next_frame != next && upload(renderer, cur ^ 1, next, slot, animated) {
                slot ^= 1;
                next_frame = next;
            }
            // A failed warm leaves next_frame stale on purpose: the boundary
            // path above re-attempts the upload when the frame is needed.
            pacer.wait_until(std::time::Instant::now() + wait);
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum VideoPresentAction {
    Presented,
    Retry,
    Reconfigure,
}

fn video_present_action(status: crate::renderer::FrameStatus) -> VideoPresentAction {
    match status {
        crate::renderer::FrameStatus::Presented => VideoPresentAction::Presented,
        crate::renderer::FrameStatus::TimedOut => VideoPresentAction::Retry,
        crate::renderer::FrameStatus::Outdated | crate::renderer::FrameStatus::Lost => {
            VideoPresentAction::Reconfigure
        }
    }
}

/// Live video playback loop: continuously updates texture with decoded frames.
fn play_video(
    renderer: &Renderer,
    surface: &wgpu::Surface<'static>,
    commit: &CommitData,
    video_playback: &std::sync::Arc<crate::video::VideoPlayback>,
    playback_gen: &std::sync::atomic::AtomicU64,
    pacer: &LivePacer,
    per_output_uniforms: &crate::renderer::PerOutputUniforms,
) {
    let mut width = commit.img_width;
    let mut height = commit.img_height;

    let Some(initial) = commit.video_texture.as_ref() else {
        tracing::warn!("Video conversion resources unavailable");
        return;
    };
    // Task-local texture handle. Unchanged resolution reuses the commit's
    // GPU resources every frame (upload + NV12 conversion only); only a
    // genuine mid-stream resolution change recreates them.
    let mut owned_replacement: Option<crate::renderer::VideoTexture> = None;
    let mut texture: &crate::renderer::VideoTexture = initial.as_ref();
    let static_effect = crate::animation::Effect::Fade(crate::animation::FadeParams::default());

    let min_frame_interval = commit
        .max_fps
        .filter(|fps| *fps > 0)
        .map(|fps| std::time::Duration::from_secs_f64(1.0 / f64::from(fps)));
    let mut last_present: Option<std::time::Instant> = None;
    let mut paused_last_iteration = false;
    loop {
        // A newer commit superseded us. Do NOT touch the shared
        // `video_playback` here: the successor commit already replaced the
        // decoder (video) or stopped it (static image), and stopping it now
        // would kill the successor's playback too.
        if playback_gen.load(Ordering::SeqCst) != commit.generation {
            return;
        }

        if let (Some(interval), Some(previous)) = (min_frame_interval, last_present) {
            pacer.wait_until(previous + interval);
            if playback_gen.load(Ordering::SeqCst) != commit.generation {
                return;
            }
        }

        // Pull the next displayable frame. The decoder queue is bounded, so
        // this never blocks; unchanged frames need no upload or presentation.
        let mut frame_uploaded = false;
        if let Some(frame) = video_playback.next_frame_in_generation(commit.generation) {
            // Mid-stream resolution change (rare): recreate only the video
            // conversion resources instead of dropping every subsequent frame.
            if frame.width != width || frame.height != height {
                match renderer.create_video_texture(frame.width, frame.height) {
                    Ok(replacement) => {
                        tracing::info!(
                            "Video resolution changed {}x{} -> {}x{}, recreated conversion resources",
                            width,
                            height,
                            frame.width,
                            frame.height
                        );
                        width = frame.width;
                        height = frame.height;
                        // Drop any previous mid-stream replacement before
                        // installing the new one so only one spare texture
                        // is ever alive in this task.
                        owned_replacement.take();
                        owned_replacement = Some(replacement);
                        texture = owned_replacement.as_ref().expect("just stored");
                    }
                    Err(err) => {
                        tracing::warn!("Video resolution change rejected: {err}");
                        pacer.wait_until(
                            std::time::Instant::now() + std::time::Duration::from_millis(2),
                        );
                        continue;
                    }
                }
            }
            if let Err(err) = renderer.update_video_texture(texture, &frame.data) {
                // A transient GPU hiccup must not end playback; retry on the
                // next frame instead.
                tracing::warn!("Video frame upload failed: {err}");
            } else {
                frame_uploaded = true;
            }
            // `frame` owns the only copy of the decoded planes; it drops here
            // after GPU upload instead of lingering in any queue or cache.
        }

        if !frame_uploaded {
            if playback_gen.load(Ordering::SeqCst) != commit.generation {
                return;
            }
            if video_playback.is_paused() {
                // Deliberately paused: rest cheaply and wait for resume.
                // Keep the watchdog and frame pacing state fresh so a resume
                // does not trip the stall detector or replay a burst of stale
                // frames at full speed.
                last_present = None;
                paused_last_iteration = true;
                pacer.wait_until(std::time::Instant::now() + std::time::Duration::from_millis(100));
                continue;
            }
            if paused_last_iteration {
                // First iteration after resume: reset pacing baseline so the
                // first post-pause frame is presented immediately instead of
                // being dropped as "already due".
                last_present = None;
                paused_last_iteration = false;
            }
            if video_playback.decoder_state() == Some(crate::video::DecoderState::Failed) {
                tracing::warn!("video decoder failed, stopping playback");
                return;
            }
            let wait = video_playback
                .time_until_next_frame_in_generation(commit.generation)
                .unwrap_or(std::time::Duration::from_millis(2));
            if playback_gen.load(Ordering::SeqCst) != commit.generation {
                return;
            }
            pacer.wait_until(std::time::Instant::now() + wait);
            continue;
        }

        let uniforms = crate::animation::compute_effect_uniforms(&static_effect, 1.0);
        let status = renderer.render_frame(
            crate::renderer::FrameRequest {
                surface,
                format: commit.format,
                bg_bind: texture.bind_group(),
                new_bind: texture.bind_group(),
                effect: &uniforms,
                width: commit.width,
                height: commit.height,
                img_width: width,
                img_height: height,
                old_img_width: width,
                old_img_height: height,
                scaling_mode: commit.scaling_mode,
            },
            per_output_uniforms,
        );

        match status.map(video_present_action) {
            Ok(VideoPresentAction::Presented) => {
                last_present = Some(std::time::Instant::now());
            }
            Ok(action) => {
                if action == VideoPresentAction::Reconfigure {
                    surface.configure(
                        &renderer.device,
                        &wgpu::SurfaceConfiguration {
                            usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
                            format: commit.format,
                            width: commit.width,
                            height: commit.height,
                            present_mode: wgpu::PresentMode::Fifo,
                            alpha_mode: wgpu::CompositeAlphaMode::Opaque,
                            view_formats: vec![],
                            color_space: wgpu::SurfaceColorSpace::default(),
                            desired_maximum_frame_latency: 1,
                        },
                    );
                }
                pacer.wait_until(std::time::Instant::now() + std::time::Duration::from_millis(100));
            }
            Err(err) => {
                tracing::warn!("Video present failed ({err}), stopping playback");
                video_playback.stop();
                return;
            }
        }
    }
}

/// Resolve target render states from an optional monitor name.
/// Returns all states when `monitor` is None, or the specific named state.
/// Returns an empty vec for unknown monitor names (letting callers return
/// an error).
async fn resolve_targets(
    render_states: &std::collections::HashMap<
        String,
        std::sync::Arc<tokio::sync::Mutex<RenderState>>,
    >,
    monitor: Option<&str>,
) -> Vec<std::sync::Arc<tokio::sync::Mutex<RenderState>>> {
    match monitor {
        Some(name) => {
            if let Some(rs) = render_states.get(name) {
                vec![rs.clone()]
            } else {
                Vec::new()
            }
        }
        None => render_states.values().cloned().collect(),
    }
}

fn resolve_named_targets(
    render_states: &std::collections::HashMap<
        String,
        std::sync::Arc<tokio::sync::Mutex<RenderState>>,
    >,
    monitor: Option<&str>,
) -> Vec<(String, std::sync::Arc<tokio::sync::Mutex<RenderState>>)> {
    match monitor {
        Some(name) => render_states
            .get(name)
            .map(|state| vec![(name.to_string(), state.clone())])
            .unwrap_or_default(),
        None => render_states
            .iter()
            .map(|(name, state)| (name.clone(), state.clone()))
            .collect(),
    }
}

type RenderStateMap = std::collections::HashMap<String, Arc<Mutex<RenderState>>>;
type SharedRenderStates = std::sync::Arc<tokio::sync::Mutex<RenderStateMap>>;

/// Snapshot target states while holding the map lock briefly, then drop the
/// guard before any decode, GPU, or theme work. Holding the map lock across
/// long operations would block hotplug insert/remove and other IPC commands.
async fn snapshot_targets(
    map: &SharedRenderStates,
    monitor: Option<&str>,
) -> Vec<Arc<Mutex<RenderState>>> {
    let states = map.lock().await;
    resolve_targets(&states, monitor).await
}

async fn snapshot_named_targets(
    map: &SharedRenderStates,
    monitor: Option<&str>,
) -> Vec<(String, Arc<Mutex<RenderState>>)> {
    let states = map.lock().await;
    resolve_named_targets(&states, monitor)
}

async fn snapshot_all_named(map: &SharedRenderStates) -> Vec<(String, Arc<Mutex<RenderState>>)> {
    let states = map.lock().await;
    states
        .iter()
        .map(|(name, state)| (name.clone(), state.clone()))
        .collect()
}

/// Returns settled outputs' shared-memory pools to the OS.
///
/// A committed shm buffer stays mapped as long as its pool lives, which
/// otherwise pins a full output-sized mapping per output forever (plus any
/// flood growth). Once nothing is drawing, the compositor already owns the
/// displayed pixels, so the pool and both ping-pong buffers can go: the
/// next static set recreates a fresh minimal pool. Settled means no set in
/// flight (state guard free) and no live transition, video, or GIF (those
/// hold the render lock for their whole run). One async task, no OS thread.
async fn reap_idle_shm_pools(states: SharedRenderStates) {
    loop {
        // Reclaim promptly after the last switch. A full 4K pair can be
        // dozens of MiB, so waiting a whole second makes short-lived command
        // bursts look like a leak to users and power monitors.
        tokio::time::sleep(std::time::Duration::from_millis(250)).await;
        for (_, state) in snapshot_all_named(&states).await {
            let Ok(mut locked) = state.try_lock() else {
                continue;
            };
            if locked.render_lock.try_lock().is_err() {
                continue;
            }
            if locked.shm_pool.len() > INITIAL_SHM_POOL_BYTES {
                locked.shm_buffers = [None, None];
                locked.shm_width = 0;
                locked.shm_height = 0;
                let fresh = SlotPool::new(
                    INITIAL_SHM_POOL_BYTES,
                    &smithay_client_toolkit::shm::Shm::from(locked.shm_server.clone()),
                );
                match fresh {
                    Ok(pool) => locked.shm_pool = pool,
                    Err(_) => continue,
                }
            }
            // Quiescent heap: hand freed top pages back as well. Only free
            // pages move, so live allocations are unaffected.
            // SAFETY: malloc_trim only releases unallocated pages back to
            // the OS; it cannot invalidate live pointers. The return value
            // (whether anything was released) is intentionally ignored.
            unsafe {
                libc::malloc_trim(0);
            }
        }
    }
}

/// Caps for live-applied configuration. Keeps queues bounded and prevents
/// absurd scheduling values from IPC or config reload. Wallpaper playback
/// needs at most ~3 decoded frames in flight (bounded queue + one pending);
/// a larger backlog only retains obsolete frames the display can never show.
pub(crate) fn clamp_preload_frames(requested: usize) -> usize {
    requested.clamp(1, 3)
}

pub(crate) fn clamp_max_fps(requested: Option<u32>) -> Option<u32> {
    match requested {
        Some(0) | None => None,
        Some(fps) => Some(fps.clamp(1, 240)),
    }
}

/// Returns true when `path` looks like a usable wallpaper file: exists, is a
/// file, and has non-zero size. Used by IPC to avoid decoding
/// partially-written files.
fn is_usable_wallpaper_file(path: &std::path::Path) -> bool {
    std::fs::metadata(path).is_ok_and(|m| m.is_file() && m.len() > 0)
}

/// Validates a freshly loaded config before it replaces the live one.
/// Only checks values applied at runtime; unknown future keys are ignored by
/// serde defaults and never fail reload.
fn validate_live_config(cfg: &WallrConfig) -> Result<(), String> {
    if cfg.video.preload_frames > 64 {
        return Err(format!(
            "video.preload_frames {} exceeds maximum 64",
            cfg.video.preload_frames
        ));
    }
    if let Some(fps) = cfg.daemon.max_fps
        && (fps == 0 || fps > 1000)
    {
        return Err(format!("daemon.max_fps {fps} out of range 1..=1000"));
    }
    Ok(())
}

/// Tune glibc malloc for a wallpaper daemon's bursty allocation pattern.
/// Animated/video decode issues thousands of transient multi-MB buffers
/// (GIF canvases, zstd scratch, NV12 planes). Under that churn glibc's
/// default *dynamic* mmap threshold adapts upward, after which freed blocks
/// are retained in per-thread arenas instead of being munmap'd: measured
/// 78 MiB stuck after GIF→static with defaults vs 25 MiB with a fixed
/// 128 KiB threshold (identical workload, `MALLOC_MMAP_THRESHOLD_` experiment).
/// A fixed threshold keeps transient decode buffers on mmap (returned to the
/// OS on free); a small trim threshold returns sbrk heap promptly.
#[cfg(target_os = "linux")]
fn tune_allocator() {
    // SAFETY: mallopt with valid M_* parameters only adjusts allocator
    // thresholds; it cannot invalidate live pointers. A 0 return merely
    // keeps glibc defaults.
    unsafe {
        libc::mallopt(libc::M_MMAP_THRESHOLD, 128 * 1024);
        libc::mallopt(libc::M_TRIM_THRESHOLD, 64 * 1024);
    }
}

pub struct Daemon {
    config: WallrConfig,
    /// Explicit `--config` path, if any. Reload must re-read the same file
    /// the daemon was started with instead of silently falling back to the
    /// default location.
    config_path: Option<std::path::PathBuf>,
    paused: Arc<AtomicBool>,
    engine: Arc<Mutex<WallpaperEngine>>,
}

impl Daemon {
    pub fn new(config: WallrConfig) -> Result<Self, DaemonError> {
        Self::with_config_path(config, None)
    }

    pub fn with_config_path(
        config: WallrConfig,
        config_path: Option<std::path::PathBuf>,
    ) -> Result<Self, DaemonError> {
        let engine = WallpaperEngine::new(config.clone())?;
        Ok(Self {
            config,
            config_path,
            paused: Arc::new(AtomicBool::new(false)),
            engine: Arc::new(Mutex::new(engine)),
        })
    }

    pub async fn start(self) -> Result<(), DaemonError> {
        tune_allocator();
        let socket_path = crate::config::expand_path(&self.config.daemon.socket)?;
        // Reserve the socket before spending seconds on Wayland/GPU setup.
        // The advisory lock plus inode-checked guard prevents concurrent
        // startup from unlinking a live daemon's socket.
        let socket = IpcSocket::acquire(&socket_path).await.map_err(|err| {
            if matches!(err, crate::ipc::IpcError::AlreadyRunning(_)) {
                DaemonError::AlreadyRunning(socket_path.to_string_lossy().to_string())
            } else {
                DaemonError::Ipc(err)
            }
        })?;
        let socket_identity = socket.identity();

        let conn = Connection::connect_to_env()
            .map_err(|e| DaemonError::StartError(format!("failed to connect to wayland: {e:?}")))?;
        let backend = conn.backend();
        let display_ptr = backend.display_ptr() as *mut std::ffi::c_void;

        let (globals, mut event_queue) = registry_queue_init(&conn)
            .map_err(|e| DaemonError::StartError(format!("registry_queue_init failed: {e:?}")))?;
        let qh = event_queue.handle();

        let compositor_state = CompositorState::bind(&globals, &qh)
            .map_err(|e| DaemonError::StartError(format!("compositor bind failed: {e:?}")))?;
        let layer_shell = LayerShell::bind(&globals, &qh)
            .map_err(|e| DaemonError::StartError(format!("layer_shell bind failed: {e:?}")))?;
        let shm = Shm::bind(&globals, &qh)
            .map_err(|e| DaemonError::StartError(format!("shm bind failed: {e:?}")))?;

        // Bind compositor once for creating empty input regions (passthrough).
        let compositor = globals
            .bind::<wl_compositor::WlCompositor, WaylandState, smithay_client_toolkit::globals::GlobalData>(
                &qh,
                1..=4,
                smithay_client_toolkit::globals::GlobalData,
            )
            .map_err(|e| DaemonError::StartError(format!("compositor bind failed: {e:?}")))?;
        let viewporter = globals
            .bind::<WpViewporter, WaylandState, ()>(&qh, 1..=1, ())
            .ok();
        if viewporter.is_none() {
            tracing::warn!(
                "wp_viewporter is unavailable; fractional outputs will use integer buffer scaling"
            );
        }

        let mut wayland_state = WaylandState {
            registry_state: RegistryState::new(&globals),
            output_state: OutputState::new(&globals, &qh),
            compositor_state,
            shm,
            outputs: std::collections::HashMap::new(),
            surfaces: Vec::new(),
            viewporter,
            viewports: std::collections::HashMap::new(),
            output_lifecycles: std::collections::HashMap::new(),
            pending_restores: std::collections::HashSet::new(),
            layer_shell,
            compositor,
            hotplug: None,
        };

        // Multiple roundtrips: some compositors deliver output events lazily
        // across several dispatch cycles. Five roundtrips ensures all outputs
        // are discovered and their modes/scale are populated.
        for i in 0..5 {
            event_queue
                .roundtrip(&mut wayland_state)
                .map_err(|e| DaemonError::StartError(format!("roundtrip {i} failed: {e:?}")))?;
        }

        if wayland_state.outputs.is_empty() {
            return Err(DaemonError::StartError(
                "no outputs detected after roundtrip".into(),
            ));
        }

        tracing::info!(
            "Detected {} output(s): {:?}",
            wayland_state.outputs.len(),
            wayland_state
                .outputs
                .values()
                .map(|o| format!("{} ({}x{})", o.name, o.width, o.height))
                .collect::<Vec<_>>()
        );

        let renderer: std::sync::Arc<std::sync::Mutex<Option<std::sync::Arc<Renderer>>>> =
            std::sync::Arc::new(std::sync::Mutex::new(None));

        // Create a LayerSurface, wgpu Surface, and RenderState for every
        // known output. The key is the output's human-readable name (e.g.
        // "DP-1", "eDP-1") so IPC can target a specific monitor.
        let mut render_states_map: std::collections::HashMap<String, Arc<Mutex<RenderState>>> =
            std::collections::HashMap::new();

        // Collect output info first so we can pass &mut wayland_state to the
        // helper (we need &mut to push LayerSurfaces into the surfaces vec).
        let output_info: Vec<(u32, OutputInfo)> = wayland_state
            .outputs
            .iter()
            .map(|(k, v)| {
                (
                    *k,
                    OutputInfo {
                        name: v.name.clone(),
                        width: v.width,
                        height: v.height,
                        scale_factor: v.scale_factor,
                        wl_output: v.wl_output.clone(),
                    },
                )
            })
            .collect();

        for (proto_id, info) in &output_info {
            let name = info.name.clone();
            let rs = Self::create_render_state_for_output(
                &renderer,
                display_ptr,
                &mut wayland_state,
                &qh,
                info,
                &self.config,
            )
            .await?;
            let rs = Arc::new(Mutex::new(rs));
            render_states_map.insert(name.clone(), rs.clone());
            wayland_state.output_lifecycles.insert(
                *proto_id,
                OutputLifecycle {
                    name: name.clone(),
                    render_state: rs,
                    active: Arc::new(std::sync::atomic::AtomicBool::new(true)),
                },
            );
            wayland_state.pending_restores.insert(*proto_id);

            tracing::info!("Output ready: {name} ({proto_id})");
        }

        // Wrap the render-state map in Arc<Mutex<...>> so it can be shared
        // between the Wayland event loop (hotplug) and the IPC handler.
        let render_states: std::sync::Arc<
            tokio::sync::Mutex<std::collections::HashMap<String, Arc<Mutex<RenderState>>>>,
        > = std::sync::Arc::new(tokio::sync::Mutex::new(render_states_map));

        // Store the hotplug context in WaylandState so output callbacks can
        // create/destroy render states when outputs appear or disappear.
        wayland_state.hotplug = Some(DaemonHotplug {
            renderer: renderer.clone(),
            config: self.config.clone(),
            display_ptr: SendDisplayPtr(display_ptr),
            render_states: render_states.clone(),
        });

        // One more roundtrip to catch outputs that appeared between the
        // initial roundtrips and the hotplug context being stored.
        event_queue
            .roundtrip(&mut wayland_state)
            .map_err(|e| DaemonError::StartError(format!("hotplug roundtrip failed: {e:?}")))?;

        let paused_clone = self.paused.clone();
        let engine_clone = self.engine.clone();
        let render_states_clone = render_states.clone();
        // Return settled outputs' shm pools to the OS (see reap_idle_shm_pools).
        tokio::spawn(reap_idle_shm_pools(render_states.clone()));
        // Generation counter for theme/hook work. Rapid A→B→C switches bump
        // the counter; detached theme tasks with a stale generation exit
        // without invoking external processes for obsolete wallpapers.
        let theme_gen = Arc::new(std::sync::atomic::AtomicU64::new(0));
        let theme_gen_clone = theme_gen.clone();

        // Graceful shutdown on POSIX signals: stop video decoding, remove the
        // IPC socket, and exit. The compositor releases the layer-shell
        // surface automatically when the process exits.
        {
            let rs_map = render_states.clone();
            let socket_path = socket_path.clone();
            tokio::spawn(async move {
                use tokio::signal::unix::{SignalKind, signal};
                let Ok(mut term) = signal(SignalKind::terminate()) else {
                    return;
                };
                let Ok(mut int) = signal(SignalKind::interrupt()) else {
                    return;
                };
                let Ok(mut hup) = signal(SignalKind::hangup()) else {
                    return;
                };
                tokio::select! {
                    _ = term.recv() => {}
                    _ = int.recv() => {}
                    _ = hup.recv() => {}
                }
                tracing::info!("Signal received, shutting down gracefully");
                let states = rs_map.lock().await;
                for rs in states.values() {
                    if let Ok(state) = rs.try_lock() {
                        state.video_playback.stop();
                    }
                }
                drop(states);
                remove_socket_if_owned(&socket_path, socket_identity);
                std::process::exit(0);
            });
        }

        let ipc_socket_path = socket_path.clone();
        let reload_config_path = self.config_path.clone();
        socket.spawn(move |cmd| {
            let paused = paused_clone.clone();
            let engine = engine_clone.clone();
            let render_states_map = render_states_clone.clone();
            let theme_gen = theme_gen_clone.clone();
            let stop_socket = ipc_socket_path.clone();
            let stop_identity = socket_identity;
            let reload_config_path = reload_config_path.clone();
            async move {
                match cmd {
                    IpcCommand::Pause { monitor } => {
                        let targets =
                            snapshot_targets(&render_states_map, monitor.as_deref()).await;
                        if targets.is_empty() {
                            return IpcResponse {
                                success: false,
                                message: Some("no matching outputs".into()),
                            };
                        }
                        if monitor.is_none() {
                            paused.store(true, Ordering::SeqCst);
                        }
                        for rs in targets {
                            let rs_lock = rs.lock().await;
                            rs_lock.video_playback.pause();
                            rs_lock.gif_paused.store(true, Ordering::SeqCst);
                        }
                        IpcResponse {
                            success: true,
                                message: Some("paused".into()),
                        }
                    }
                    IpcCommand::Resume { monitor } => {
                        let targets =
                            snapshot_targets(&render_states_map, monitor.as_deref()).await;
                        if targets.is_empty() {
                            return IpcResponse {
                                success: false,
                                message: Some("no matching outputs".into()),
                            };
                        }
                        if monitor.is_none() {
                            paused.store(false, Ordering::SeqCst);
                        }
                        for rs in targets {
                            let rs_lock = rs.lock().await;
                            rs_lock.video_playback.resume();
                            rs_lock.gif_paused.store(false, Ordering::SeqCst);
                            rs_lock.pacer.notify();
                        }
                        IpcResponse {
                            success: true,
                                message: Some("resumed".into()),
                        }
                    }
                    IpcCommand::Reload => {
                        // Re-read config from disk, validate, and apply live
                        // values without rebuilding GPU state. Invalid configs
                        // keep the previous valid configuration.
                        let reload_path = reload_config_path.clone();
                        let fresh = tokio::task::spawn_blocking(move || {
                            crate::config::load_config(reload_path.as_deref())
                                .map_err(|e| e.to_string())
                                .and_then(|cfg| {
                                    validate_live_config(&cfg)?;
                                    Ok(cfg)
                                })
                        })
                        .await;
                        let fresh = match fresh {
                            Ok(Ok(cfg)) => cfg,
                            Ok(Err(reason)) => {
                                return IpcResponse {
                                    success: false,
                                    message: Some(format!("reload rejected: {reason}")),
                                };
                            }
                            Err(err) => {
                                return IpcResponse {
                                    success: false,
                                    message: Some(format!("reload task failed: {err}")),
                                };
                            }
                        };
                        let preload = clamp_preload_frames(fresh.video.preload_frames);
                        let max_fps = clamp_max_fps(fresh.daemon.max_fps);
                        let hw_accel =
                            crate::video::HwAccel::from_config(&fresh.video.hw_decode);
                        {
                            let mut eng = engine.lock().await;
                            eng.config = fresh.clone();
                        }
                        let reload_config = fresh.clone();
                        let reload_result = tokio::task::spawn_blocking(move || {
                            WallpaperEngine::new(reload_config)?.reload_blocking()
                        })
                        .await;
                        match reload_result {
                            Ok(Ok(())) => {}
                            Ok(Err(e)) => {
                                return IpcResponse {
                                    success: false,
                                    message: Some(e.to_string()),
                                };
                            }
                            Err(e) => {
                                return IpcResponse {
                                    success: false,
                                    message: Some(format!("reload task failed: {e}")),
                                };
                            }
                        }
                        // Apply video params per output without holding the
                        // map lock across awaits.
                        let targets = snapshot_all_named(&render_states_map).await;
                        for (_, rs) in targets {
                            let mut rs_lock = rs.lock().await;
                            rs_lock.hw_accel = hw_accel;
                            rs_lock.preload_frames = preload;
                            rs_lock.max_fps = max_fps;
                        }
                        let _ = theme_gen;
                        IpcResponse {
                            success: true,
                            message: Some("reloaded".into()),
                        }
                    }
                    IpcCommand::Preview {
                        path,
                        effect,
                        duration_ms,
                        fps,
                        no_theme,
                        theme_override,
                        monitor,
                        scaling_mode,
                    } => {
                        if paused.load(Ordering::SeqCst) {
                            return IpcResponse {
                                success: false,
                                message: Some("daemon is paused".into()),
                            };
                        }
                        let p = std::path::PathBuf::from(&path);
                        if !is_usable_wallpaper_file(&p) {
                            return IpcResponse {
                                success: false,
                                message: Some(format!("file not found or unreadable: {}", path)),
                            };
                        }

                        // Snapshot targets first, then drop the map lock
                        // before any decode/upload work so hotplug stays
                        // responsive while a switch is in flight.
                        let targets =
                            snapshot_named_targets(&render_states_map, monitor.as_deref()).await;
                        if targets.is_empty() {
                            return IpcResponse {
                                success: false,
                                message: match &monitor {
                                    Some(name) => Some(format!("unknown monitor: {name}")),
                                    None => Some("no outputs available".into()),
                                },
                            };
                        }

                        let effect = effect.unwrap_or_else(|| {
                            crate::animation::Effect::Fade(crate::animation::FadeParams::default())
                        });
                        // Live playback only starts after the transition, so for
                        // videos an unrequested 2s fade reads as a long "load".
                        // Default to a short fade unless the user asked for one.
                        let is_video = crate::video::VideoDecoder::is_video_file(&p);
                        let duration = duration_ms
                            .unwrap_or(if is_video { 150 } else { 2000 })
                            .min(crate::ipc::MAX_DURATION_MS);
                        let sm = scaling_mode.unwrap_or(crate::config::ScalingMode::Fill);
                        let scaling_mode_u32 = match sm {
                            crate::config::ScalingMode::Fill => 0u32,
                            crate::config::ScalingMode::Fit => 1,
                            crate::config::ScalingMode::Stretch => 2,
                            crate::config::ScalingMode::Center => 3,
                            crate::config::ScalingMode::Tile => 4,
                        };

                        let mut last_err = None;
                        for (name, rs) in &targets {
                            if let Some(fps) = fps {
                                rs.lock().await.max_fps = Some(clamp_max_fps(Some(fps)).unwrap());
                            }
                            let result = set_wallpaper_with_retry(
                                rs,
                                &p,
                                &effect,
                                duration,
                                scaling_mode_u32,
                            )
                            .await;

                            match result {
                                Err(e) => last_err = Some(format!("render failed: {e}")),
                                Ok(()) => {
                                    if let Err(err) = persist_wallpaper(name, &p) {
                                        tracing::warn!(
                                            "Wallpaper changed on {name}, but state persistence failed: {err}"
                                        );
                                    }
                                }
                            }
                        }

                        match last_err {
                            Some(e) => IpcResponse {
                                success: false,
                                message: Some(e),
                            },
                            None => {
                                // Wallpaper is already visible at this point.
                                // Theme/hooks/reload run detached so they never
                                // block the next switch. Rapid A→B→C switches
                                // supersede queued theme work via the
                                // generation counter.
                                let generation =
                                    theme_gen.fetch_add(1, Ordering::SeqCst) + 1;
                                let opts = SetOptions {
                                    no_theme,
                                    theme_provider: theme_override,
                                    monitor,
                                };
                                let theme_gen_check = theme_gen.clone();
                                let p_clone = p.clone();
                                // Never run hooks or theme providers on the
                                // async runtime: they are synchronous
                                // subprocess waits that previously froze the
                                // current-thread daemon for their duration.
                                let config = {
                                    let eng = engine.lock().await;
                                    eng.config.clone()
                                };
                                tokio::task::spawn_blocking(move || {
                                    if theme_gen_check.load(Ordering::SeqCst) != generation {
                                        return;
                                    }
                                    let mut eng = match WallpaperEngine::new(config) {
                                        Ok(engine) => engine,
                                        Err(err) => {
                                            tracing::warn!(
                                                "Post-render theme setup failed for {p_clone:?}: {err}"
                                            );
                                            return;
                                        }
                                    };
                                    if let Err(e) =
                                        eng.set_wallpaper_blocking(&p_clone, &opts)
                                    {
                                        tracing::warn!(
                                            "Post-render hooks/theme failed for {p_clone:?}: {e}"
                                        );
                                    }
                                });
                                IpcResponse {
                                    success: true,
                                    message: None,
                                }
                            }
                        }
                    }
                    IpcCommand::Stop => {
                        let targets = snapshot_all_named(&render_states_map).await;
                        for (_, rs) in targets {
                            let state = rs.lock().await;
                            state.playback_gen.fetch_add(1, Ordering::SeqCst);
                            state.pacer.notify();
                            state.video_playback.stop();
                        }
                        let sp = stop_socket.clone();
                        tokio::spawn(async move {
                            tokio::time::sleep(std::time::Duration::from_millis(300)).await;
                            remove_socket_if_owned(&sp, stop_identity);
                            std::process::exit(0);
                        });
                        IpcResponse {
                            success: true,
                                message: Some("stopping".into()),
                        }
                    }
                    IpcCommand::Status => {
                        let state = if paused.load(Ordering::SeqCst) {
                            "paused"
                        } else {
                            "running"
                        };
                        IpcResponse {
                            success: true,
                            message: Some(format!("wallr daemon {}", state)),
                        }
                    }
                    IpcCommand::Seek {
                        timestamp_ms,
                        monitor,
                    } => {
                        let targets =
                            snapshot_named_targets(&render_states_map, monitor.as_deref()).await;
                        if targets.is_empty() {
                            return IpcResponse {
                                success: false,
                                message: match &monitor {
                                    Some(name) => Some(format!("unknown monitor: {name}")),
                                    None => Some("no outputs available".into()),
                                },
                            };
                        }
                        // When monitor is unspecified, seek all outputs.
                        // The map lock was already dropped; work only on the
                        // snapshot so hotplug stays responsive.
                        let mut seek_count = 0u32;
                        let mut errors = Vec::new();
                        for (name, rs) in &targets {
                            let rs_lock = rs.lock().await;
                            match rs_lock
                                .video_playback
                                .seek(std::time::Duration::from_millis(timestamp_ms))
                            {
                                Ok(()) => {
                                    seek_count += 1;
                                }
                                Err(e) => {
                                    errors.push(format!("{}: {}", name, e));
                                }
                            }
                        }
                        if seek_count == 0 {
                            IpcResponse {
                                success: false,
                                message: Some(format!(
                                    "Seek failed on all outputs: {}",
                                    errors.join("; ")
                                )),
                            }
                        } else if !errors.is_empty() {
                            IpcResponse {
                                success: true,
                                message: Some(format!(
                                    "Seeked {} output(s) to {}ms, {} failed: {}",
                                    seek_count,
                                    timestamp_ms,
                                    errors.len(),
                                    errors.join("; ")
                                )),
                            }
                        } else {
                            IpcResponse {
                                success: true,
                                message: Some(format!(
                                    "Seeked {} output(s) to {}ms",
                                    seek_count, timestamp_ms
                                )),
                            }
                        }
                    }
                    IpcCommand::Info { monitor } => {
                        let targets =
                            snapshot_named_targets(&render_states_map, monitor.as_deref()).await;
                        if targets.is_empty() {
                            return IpcResponse {
                                success: false,
                                message: match &monitor {
                                    Some(name) => Some(format!("unknown monitor: {name}")),
                                    None => Some("no outputs available".into()),
                                },
                            };
                        }

                        let mut lines = vec![
                            format!("wallr v{}", env!("CARGO_PKG_VERSION")),
                            String::new(),
                            format!("outputs: {}", targets.len()),
                        ];
                        for (name, _) in &targets {
                            lines.push(format!("  - {name}"));
                        }

                        // Collect target output info
                        for (name, rs) in &targets {
                            let rs_lock = rs.lock().await;
                            // GPU state is lazy: a static-only output may never
                            // have initialized it. Report that instead of
                            // panicking the IPC handler task.
                            let gpu_info = rs_lock.gpu.as_ref().map_or_else(
                                || "gpu: not initialized (static content)".to_string(),
                                |gpu| {
                                    crate::video::gpu::adapter_diagnostics(&gpu.renderer.adapter)
                                },
                            );

                            lines.push(String::new());
                            lines.push(format!("[{name}] {}x{}", rs_lock.width, rs_lock.height));
                            lines.push(gpu_info);

                            match rs_lock.video_playback.metadata() {
                                Some(meta) => {
                                    let decoder_info = rs_lock.video_playback.decoder_info();
                                    let hw = rs_lock.video_playback.hw_accel_in_use();
                                    let state = if rs_lock.video_playback.is_paused() {
                                        "paused"
                                    } else {
                                        "playing"
                                    };
                                    let position = rs_lock
                                        .video_playback
                                        .position()
                                        .map(|p| format!("{:.2}s", p.as_secs_f64()))
                                        .unwrap_or_else(|| "?".to_string());
                                    lines.push(String::new());
                                    lines.push("video:".into());
                                    lines.push(format!(
                                        "  resolution: {}x{}",
                                        meta.width, meta.height
                                    ));
                                    lines.push(format!("  fps: {:.2}", meta.fps));
                                    lines.push(format!(
                                        "  duration: {:.2}s",
                                        meta.duration.as_secs_f64()
                                    ));
                                    lines.push(format!(
                                        "  codec: {}",
                                        decoder_info
                                            .as_ref()
                                            .map(|d| d.codec_name.as_str())
                                            .unwrap_or("unknown")
                                    ));
                                    lines.push(format!("  container: {}", meta.format));
                                    lines.push(format!("  decoder: {}", hw.name()));
                                    if let Some(info) = decoder_info.as_ref() {
                                        lines.push(format!("  decoder state: {}", info.state.name()));
                                    }
                                    lines.push(format!(
                                        "  gpu decode: {}",
                                        if hw == crate::video::HwAccel::Software {
                                            "disabled"
                                        } else {
                                            "enabled"
                                        }
                                    ));
                                    if let Some(info) = decoder_info.as_ref()
                                        && info.dropped_frames > 0
                                    {
                                        lines.push(format!(
                                            "  dropped frames: {}",
                                            info.dropped_frames
                                        ));
                                    }
                                    lines.push(format!("  state: {} @ {}", state, position));
                                }
                                None => {
                                    lines.push(String::new());
                                    lines.push("video: none active".into());
                                    lines.push("decoder: idle".into());
                                }
                            }
                        }

                        IpcResponse {
                            success: true,
                            message: Some(lines.join("\n")),
                        }
                    }
                    IpcCommand::MonitorList => {
                        let targets = snapshot_all_named(&render_states_map).await;
                        let mut lines = Vec::new();
                        for (name, rs) in &targets {
                            let lock = rs.lock().await;
                            lines.push(format!("{}: {}x{}", name, lock.width, lock.height));
                        }
                        if lines.is_empty() {
                            IpcResponse {
                                success: true,
                                message: Some("no monitors connected".into()),
                            }
                        } else {
                            IpcResponse {
                                success: true,
                                message: Some(lines.join("\n")),
                            }
                        }
                    }
                    IpcCommand::MonitorCurrent => {
                        // Return info for the first output as "current".
                        let targets = snapshot_all_named(&render_states_map).await;
                        if let Some((name, rs)) = targets.first() {
                            let lock = rs.lock().await;
                            IpcResponse {
                                success: true,
                                message: Some(format!("{}: {}x{}", name, lock.width, lock.height)),
                            }
                        } else {
                            IpcResponse {
                                success: false,
                                message: Some("no monitors connected".into()),
                            }
                        }
                    }
                    IpcCommand::Blank {
                        monitor,
                        effect,
                        duration_ms,
                    } => {
                        let targets =
                            snapshot_named_targets(&render_states_map, monitor.as_deref()).await;
                        if targets.is_empty() {
                            return IpcResponse {
                                success: false,
                                message: match &monitor {
                                    Some(name) => Some(format!("unknown monitor: {name}")),
                                    None => Some("no outputs available".into()),
                                },
                            };
                        }
                        let mut blanked_count = 0u32;
                        let mut errors = Vec::new();
                        let black_effect = effect.unwrap_or_else(|| {
                            crate::animation::Effect::Fade(crate::animation::FadeParams::default())
                        });
                        let duration = duration_ms.unwrap_or(800);
                        let mut blank_file = match tempfile::Builder::new()
                            .prefix("wallr_blank-")
                            .suffix(".png")
                            .tempfile()
                        {
                            Ok(file) => file,
                            Err(e) => {
                                return IpcResponse {
                                    success: false,
                                    message: Some(format!("failed to create blank image: {e}")),
                                };
                            }
                        };
                        let blank_path = blank_file.path().to_path_buf();
                        let blank = image::DynamicImage::ImageRgba8(
                            image::RgbaImage::from_pixel(1, 1, image::Rgba([0, 0, 0, 255])),
                        );
                        if let Err(e) = blank
                            .write_to(blank_file.as_file_mut(), image::ImageFormat::Png)
                        {
                            return IpcResponse {
                                success: false,
                                message: Some(format!("failed to write blank image: {e}")),
                            };
                        }

                        for (name, rs) in &targets {
                            let rs = Arc::clone(rs);
                            let blank_path = blank_path.clone();
                            let black_effect = black_effect.clone();
                            let blanked = tokio::task::spawn_blocking(move || {
                                let mut lock = rs.blocking_lock();
                                if lock.blanked {
                                    return Ok(false);
                                }
                                let previous = (
                                    lock.last_wallpaper.clone().unwrap_or_default(),
                                    lock.scaling_mode,
                                );
                                lock.set_wallpaper(&blank_path, &black_effect, duration, 0)?;
                                lock.pre_blank = Some(previous);
                                lock.blanked = true;
                                Ok::<bool, anyhow::Error>(true)
                            })
                            .await;
                            match blanked {
                                Ok(Ok(true)) => blanked_count += 1,
                                Ok(Ok(false)) => {}
                                Ok(Err(e)) => errors.push(format!("{name}: blank failed: {e}")),
                                Err(e) => errors.push(format!("{name}: blank task failed: {e}")),
                            }
                        }
                        if errors.is_empty() {
                            IpcResponse {
                                success: true,
                                message: Some(format!("blanked {blanked_count} output(s)")),
                            }
                        } else {
                            IpcResponse {
                                success: false,
                                message: Some(format!(
                                    "blanked {blanked_count} output(s), {} error(s): {}",
                                    errors.len(),
                                    errors.join("; ")
                                )),
                            }
                        }
                    }
                    IpcCommand::Restore {
                        monitor,
                        effect,
                        duration_ms,
                    } => {
                        let targets =
                            snapshot_named_targets(&render_states_map, monitor.as_deref()).await;
                        if targets.is_empty() {
                            return IpcResponse {
                                success: false,
                                message: match &monitor {
                                    Some(name) => Some(format!("unknown monitor: {name}")),
                                    None => Some("no outputs available".into()),
                                },
                            };
                        }
                        let mut restored_count = 0u32;
                        let mut errors = Vec::new();
                        let restore_effect = effect.unwrap_or_else(|| {
                            crate::animation::Effect::Fade(crate::animation::FadeParams::default())
                        });
                        let duration = duration_ms.unwrap_or(800).min(crate::ipc::MAX_DURATION_MS);

                        for (name, rs) in &targets {
                            let rs = Arc::clone(rs);
                            let restore_effect = restore_effect.clone();
                            let result = tokio::task::spawn_blocking(move || {
                                let mut lock = rs.blocking_lock();
                                if !lock.blanked {
                                    return None;
                                }
                                let result = match lock.pre_blank.clone() {
                                    Some((path, scaling_mode)) if path.exists() => lock
                                        .set_wallpaper(
                                            &path,
                                            &restore_effect,
                                            duration,
                                            scaling_mode,
                                        )
                                        .map_err(|e| format!("restore failed: {e}")),
                                    Some(_) => Err("wallpaper path no longer exists".to_string()),
                                    None => Err("no previous wallpaper to restore".to_string()),
                                };
                                if result.is_ok() {
                                    lock.blanked = false;
                                    lock.pre_blank = None;
                                }
                                Some(result)
                            })
                            .await;
                            match result {
                                Ok(Some(Ok(()))) => restored_count += 1,
                                Ok(Some(Err(e))) => errors.push(format!("{name}: {e}")),
                                Ok(None) => {}
                                Err(e) => errors.push(format!("{name}: restore task failed: {e}")),
                            }
                        }
                        if !errors.is_empty() {
                            IpcResponse {
                                success: restored_count > 0,
                                message: Some(format!(
                                    "restored {} output(s), {} error(s): {}",
                                    restored_count,
                                    errors.len(),
                                    errors.join("; ")
                                )),
                            }
                        } else {
                            IpcResponse {
                                success: true,
                                message: Some(format!("restored {restored_count} output(s)")),
                            }
                        }
                    }
                }
            }
        });

        tokio::task::spawn_blocking(move || {
            loop {
                if let Err(e) = event_queue.blocking_dispatch(&mut wayland_state) {
                    eprintln!("Wayland dispatch error: {e:?}");
                    break;
                }
            }
            // The compositor connection is dead (e.g. the compositor exited
            // or killed our layer surface with a protocol error). Rendering
            // can never recover, so exit and let the supervisor restart us.
            eprintln!("wallr: Wayland connection lost, exiting");
            std::process::exit(1);
        });

        loop {
            tokio::time::sleep(std::time::Duration::from_secs(3600)).await;
        }
    }

    /// Creates a LayerSurface, wgpu Surface, and RenderState for a single
    /// Wayland output.
    #[allow(clippy::too_many_arguments)]
    async fn create_render_state_for_output(
        renderer: &std::sync::Arc<std::sync::Mutex<Option<std::sync::Arc<Renderer>>>>,
        display_ptr: *mut std::ffi::c_void,
        wayland_state: &mut WaylandState,
        qh: &QueueHandle<WaylandState>,
        output: &OutputInfo,
        config: &WallrConfig,
    ) -> Result<RenderState, DaemonError> {
        let wl_surface = wayland_state.compositor_state.create_surface(qh);
        let layer_surface = wayland_state.layer_shell.create_layer_surface(
            qh,
            wl_surface,
            Layer::Background,
            Some("wallr"),
            Some(&output.wl_output),
        );
        layer_surface.set_anchor(Anchor::TOP | Anchor::BOTTOM | Anchor::LEFT | Anchor::RIGHT);
        layer_surface.set_exclusive_zone(-1);
        layer_surface.set_keyboard_interactivity(KeyboardInteractivity::None);

        // Empty input region so clicks pass through to the desktop.
        let empty_region = wayland_state.compositor.create_region(qh, ());
        layer_surface
            .wl_surface()
            .set_input_region(Some(&empty_region));
        let output_id = output.wl_output.id().protocol_id();
        let viewport = wayland_state
            .viewporter
            .as_ref()
            .map(|viewporter| viewporter.get_viewport(layer_surface.wl_surface(), qh, ()));
        let scale_factor = if viewport.is_some() {
            1
        } else if output.scale_factor > 0 {
            output.scale_factor
        } else {
            1
        };
        layer_surface.wl_surface().set_buffer_scale(scale_factor);
        layer_surface.commit();
        empty_region.destroy();
        if let Some(viewport) = viewport {
            wayland_state.viewports.insert(output_id, viewport);
        }

        // mode.dimensions already returns physical pixels; do not multiply by scale.
        let width = output.width;
        let height = output.height;

        let raw_surface = layer_surface.wl_surface().id().as_ptr() as *mut std::ffi::c_void;
        let shm_surface = layer_surface.wl_surface().clone();
        wayland_state.surfaces.push((output_id, layer_surface));

        Ok(RenderState {
            gpu: None,
            renderer: renderer.clone(),
            display_ptr: SendDisplayPtr(display_ptr),
            raw_surface: SendDisplayPtr(raw_surface),
            render_lock: std::sync::Arc::new(std::sync::Mutex::new(())),
            playback_gen: std::sync::Arc::new(std::sync::atomic::AtomicU64::new(0)),
            pacer: std::sync::Arc::new(LivePacer::new()),
            current_bind: None,
            current_tex: None,
            width,
            height,
            current_width: 0,
            current_height: 0,
            video_playback: std::sync::Arc::new(crate::video::VideoPlayback::new()),
            hw_accel: crate::video::HwAccel::from_config(&config.video.hw_decode),
            preferred_gpu: config.video.preferred_gpu.clone(),
            preload_frames: clamp_preload_frames(config.video.preload_frames),
            max_fps: clamp_max_fps(config.daemon.max_fps),
            scaling_mode: 0,
            current_effect: None,
            last_wallpaper: None,
            pre_blank: None,
            blanked: false,
            gif_paused: std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)),
            shm_surface,
            shm_server: wayland_state.shm.wl_shm().clone(),
            shm_pool: SlotPool::new(INITIAL_SHM_POOL_BYTES, &wayland_state.shm).map_err(|e| {
                DaemonError::StartError(format!("shared-memory pool creation failed: {e}"))
            })?,
            shm_buffers: [None, None],
            shm_index: 0,
            shm_width: 0,
            shm_height: 0,
            cached_shm_image: None,
            gpu_surface_used: false,
            cached_video_texture: None,
            loop_video: config.wallpaper.loop_video,
        })
    }
}

/// Synchronous version of `Daemon::create_render_state_for_output` for hotplug.
/// Reuses the existing adapter from the renderer instead of requesting a
/// new one, avoiding the async requirement.
#[allow(clippy::too_many_arguments)]
fn create_render_state_for_output_sync(
    renderer: &std::sync::Arc<std::sync::Mutex<Option<std::sync::Arc<Renderer>>>>,
    display_ptr: *mut std::ffi::c_void,
    wayland_state: &mut WaylandState,
    qh: &QueueHandle<WaylandState>,
    output: &OutputInfo,
    config: &WallrConfig,
) -> Result<RenderState, DaemonError> {
    let wl_surface = wayland_state.compositor_state.create_surface(qh);
    let layer_surface = wayland_state.layer_shell.create_layer_surface(
        qh,
        wl_surface,
        Layer::Background,
        Some("wallr"),
        Some(&output.wl_output),
    );
    layer_surface.set_anchor(Anchor::TOP | Anchor::BOTTOM | Anchor::LEFT | Anchor::RIGHT);
    layer_surface.set_exclusive_zone(-1);
    layer_surface.set_keyboard_interactivity(KeyboardInteractivity::None);

    let empty_region = wayland_state.compositor.create_region(qh, ());
    layer_surface
        .wl_surface()
        .set_input_region(Some(&empty_region));
    let output_id = output.wl_output.id().protocol_id();
    let viewport = wayland_state
        .viewporter
        .as_ref()
        .map(|viewporter| viewporter.get_viewport(layer_surface.wl_surface(), qh, ()));
    let scale_factor = if viewport.is_some() {
        1
    } else if output.scale_factor > 0 {
        output.scale_factor
    } else {
        1
    };
    layer_surface.wl_surface().set_buffer_scale(scale_factor);
    layer_surface.commit();
    empty_region.destroy();
    if let Some(viewport) = viewport {
        wayland_state.viewports.insert(output_id, viewport);
    }

    // mode.dimensions already returns physical pixels; do not multiply by scale.
    let width = output.width;
    let height = output.height;

    let raw_surface = layer_surface.wl_surface().id().as_ptr() as *mut std::ffi::c_void;
    let shm_surface = layer_surface.wl_surface().clone();
    wayland_state.surfaces.push((output_id, layer_surface));

    Ok(RenderState {
        gpu: None,
        renderer: renderer.clone(),
        display_ptr: SendDisplayPtr(display_ptr),
        raw_surface: SendDisplayPtr(raw_surface),
        render_lock: std::sync::Arc::new(std::sync::Mutex::new(())),
        playback_gen: std::sync::Arc::new(std::sync::atomic::AtomicU64::new(0)),
        pacer: std::sync::Arc::new(LivePacer::new()),
        current_bind: None,
        current_tex: None,
        width,
        height,
        current_width: 0,
        current_height: 0,
        video_playback: std::sync::Arc::new(crate::video::VideoPlayback::new()),
        hw_accel: crate::video::HwAccel::from_config(&config.video.hw_decode),
        preferred_gpu: config.video.preferred_gpu.clone(),
        preload_frames: clamp_preload_frames(config.video.preload_frames),
        max_fps: clamp_max_fps(config.daemon.max_fps),
        scaling_mode: 0,
        current_effect: None,
        last_wallpaper: None,
        pre_blank: None,
        blanked: false,
        gif_paused: std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)),
        shm_surface,
        shm_server: wayland_state.shm.wl_shm().clone(),
        shm_pool: SlotPool::new(INITIAL_SHM_POOL_BYTES, &wayland_state.shm).map_err(|e| {
            DaemonError::StartError(format!("shared-memory pool creation failed: {e}"))
        })?,
        shm_buffers: [None, None],
        shm_index: 0,
        shm_width: 0,
        shm_height: 0,
        cached_shm_image: None,
        gpu_surface_used: false,
        cached_video_texture: None,
        loop_video: config.wallpaper.loop_video,
    })
}