noesis_bevy 0.10.0

Bevy plugin that drives the Noesis GUI Native SDK and renders its UIs into a Bevy frame via wgpu compositing.
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
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
//! Render-graph integration: composites each [`NoesisView`] camera's UI into
//! the Bevy frame.
//!
//! [`NoesisRenderPlugin`] is a sub-plugin on [`RenderApp`] that:
//!
//! - Builds a [`WgpuRenderDevice`] against Bevy's shared `wgpu::Device` and
//!   registers it with Noesis in [`Plugin::finish`].
//! - Installs a [`BevyXamlProvider`] whose backing [`SharedXamlMap`] is
//!   refreshed each frame from the main world's [`XamlRegistry`] via a
//!   system running in [`ExtractSchedule`].
//! - Lazily builds a [`noesis_runtime::view::View`] + intermediate `Rgba8Unorm`
//!   texture the first frame the configured XAML URI resolves.
//! - Drives Noesis (layout, render-tree snapshot, offscreen + onscreen
//!   render) from a `Render` schedule system; the graph node itself only
//!   blits the pre-populated intermediate into the camera's [`ViewTarget`].
//! - Registers [`NoesisNode`] into [`Core2d`] between
//!   [`Node2d::MainTransparentPass`] and [`Node2d::EndMainPass`].
//!
//! The intermediate is `Rgba8Unorm` because [`WgpuRenderDevice`]'s pipeline
//! cache compiles every shader variant against that one color format.
//! The blit pipeline is cached per encountered `ViewTarget` format. Both go
//! away once `PipelineCache` keys on format.
//!
//! # Lifecycle ordering
//!
//! Noesis demands a strict teardown sequence: `Renderer::shutdown()` must
//! run while both the `View` and the registered `RenderDevice` are still
//! alive, then the `View` drops, then the device's [`Registered`] guard,
//! then the provider's. We enforce this by holding every Noesis handle
//! in `NoesisRenderState` and implementing [`Drop`] explicitly.
//!
//! [`Registered`]: noesis_runtime::render_device::Registered

use std::borrow::Cow;
use std::collections::{HashMap, HashSet};
use std::sync::Arc;

use bevy::core_pipeline::core_2d::graph::{Core2d, Node2d};
use bevy::core_pipeline::core_3d::graph::{Core3d, Node3d};
use bevy::prelude::*;
use bevy_render::{
    Render, RenderApp, RenderSystems,
    extract_component::{ExtractComponent, ExtractComponentPlugin},
    render_graph::{
        NodeRunError, RenderGraphContext, RenderGraphExt, RenderLabel, ViewNode, ViewNodeRunner,
    },
    renderer::{RenderContext, RenderDevice, RenderQueue},
    view::ViewTarget,
};
use noesis_runtime::animation::{Animation, DoubleAnimation, Timeline};
use noesis_runtime::commands::Command;
use noesis_runtime::events::{
    ClickSubscription, EventArgs, EventSubscription, KeyDownSubscription, subscribe_click,
    subscribe_event, subscribe_keydown,
};
use noesis_runtime::input::KeyBinding;
use noesis_runtime::transforms::{CompositeTransform, CompositeTransform3D, MatrixTransform3D};
use noesis_runtime::view::{FrameworkElement, Key, View};

use crate::binding::{BindingEntry, BuiltBinding};
use crate::commands::{CommandEntry, CommandsDef, SharedCommandQueue};
use crate::events::{SharedClickQueue, SharedKeyDownQueue};
use crate::font::{BevyFontProvider, FontRegistry, SharedFontMap};
use crate::image::{BevyTextureProvider, ImageRegistry, SharedImageMap};
use crate::items::{CollectionViewOp, ItemValue, ItemsBinding, ObjectSource};
use crate::plain_vm::PlainVmEntry;
use crate::render_device::WgpuRenderDevice;
use crate::routed_events::{RoutedEventSnapshot, SharedRoutedEventQueue};
use crate::viewmodel::{AttachTarget, SharedVmChangedQueue, ViewModelDef, VmEntry, VmValue};
use crate::xaml::{BevyXamlProvider, SharedXamlMap, XamlRegistry};

/// Color format of the per-view intermediate Noesis paints into. Must match
/// the private `RT_COLOR_FORMAT` in `render_device::wgpu_device`.
const INTERMEDIATE_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Rgba8Unorm;

fn flags_from(config: &NoesisView) -> u32 {
    let mut f = 0;
    if config.ppaa {
        f |= noesis_runtime::view::RenderFlag::Ppaa as u32;
    }
    f
}

/// `Rgba8UnormSrgb` alias of the intermediate, used for sampling during the
/// blit when `ViewTarget` is itself sRGB-encoded. See `create_intermediate`
/// and [`NoesisNode::run`] for the gamma-roundtrip rationale.
const INTERMEDIATE_SAMPLE_FORMAT_SRGB: wgpu::TextureFormat = wgpu::TextureFormat::Rgba8UnormSrgb;

/// Whether a `ViewTarget` colour format stores *linear* values that are
/// gamma-encoded downstream (i.e. an HDR camera's float target). These need the
/// same sRGB→linear decode on blit as a true sRGB target (see [`NoesisNode::run`]).
/// A plain `Rgba8Unorm` target is excluded: it is written and displayed raw.
fn is_linear_float(format: wgpu::TextureFormat) -> bool {
    matches!(
        format,
        wgpu::TextureFormat::Rgba16Float
            | wgpu::TextureFormat::Rgba32Float
            | wgpu::TextureFormat::Rg11b10Ufloat
    )
}

/// One double-buffer slot: a Noesis-painted texture plus its two views (a raw
/// `Rgba8Unorm` render view + an `Rgba8UnormSrgb` alias for sampling).
struct Intermediate {
    // Owned so the GPU allocation outlives the views; not read directly.
    #[allow(dead_code)]
    texture: wgpu::Texture,
    view: wgpu::TextureView,
    sample_view: wgpu::TextureView,
}

fn create_intermediate(device: &wgpu::Device, size: UVec2) -> Intermediate {
    // Two views over the same bytes:
    //
    //   `render_view` (`Rgba8Unorm`): Noesis writes sRGB colours straight
    //                    into the bytes (no linearisation in the pipeline;
    //                    DeviceCaps::linearRendering = false), so the stored
    //                    byte values already match the sRGB representation.
    //
    //   `sample_view` (`Rgba8UnormSrgb`): used by the blit sampler when the
    //                    camera's ViewTarget is sRGB. Reading through the
    //                    sRGB alias applies the sRGB → linear decode; the
    //                    ViewTarget write re-applies linear → sRGB, and the
    //                    round-trip reproduces the stored byte value. Without
    //                    this the byte value would be treated as linear on
    //                    read and gamma-encoded on write, ending ~40 %
    //                    brighter than intended.
    //
    // Requires listing the sRGB alias in `view_formats` at creation time
    // (wgpu restricts which formats may be reinterpreted later).
    let tex = device.create_texture(&wgpu::TextureDescriptor {
        label: Some("noesis intermediate"),
        size: wgpu::Extent3d {
            width: size.x,
            height: size.y,
            depth_or_array_layers: 1,
        },
        mip_level_count: 1,
        sample_count: 1,
        dimension: wgpu::TextureDimension::D2,
        format: INTERMEDIATE_FORMAT,
        usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING,
        view_formats: &[INTERMEDIATE_SAMPLE_FORMAT_SRGB],
    });
    let render_view = tex.create_view(&wgpu::TextureViewDescriptor {
        label: Some("noesis intermediate (render, Unorm)"),
        format: Some(INTERMEDIATE_FORMAT),
        ..Default::default()
    });
    let sample_view = tex.create_view(&wgpu::TextureViewDescriptor {
        label: Some("noesis intermediate (sample, UnormSrgb)"),
        format: Some(INTERMEDIATE_SAMPLE_FORMAT_SRGB),
        ..Default::default()
    });
    Intermediate {
        texture: tex,
        view: render_view,
        sample_view,
    }
}

/// Build a live `Noesis::Style` from a [`StyleSpec`](crate::styles::StyleSpec):
/// its `BasedOn` base (recursively), unconditional setters, and property / data /
/// multi triggers. `name` / `uri` are for diagnostics only. Returns `None` (and
/// warns) when the target type can't be resolved; an unresolvable base style
/// warns and is skipped, but the style is still built. The returned style is
/// unsealed; seal it by applying it to an element.
fn build_noesis_style(
    spec: &crate::styles::StyleSpec,
    name: &str,
    uri: &str,
) -> Option<noesis_runtime::styles::Style> {
    use noesis_runtime::binding::Binding;
    use noesis_runtime::styles::{DataTrigger, MultiTrigger, Style, Trigger};

    let mut style = Style::new();
    if !style.set_target_type(&spec.target_type) {
        warn!(
            "NoesisStyles: unknown TargetType {:?} for {name:?} in scene {uri:?}",
            spec.target_type,
        );
        return None;
    }

    // BasedOn: build the base chain first and link it. Noesis takes its own
    // reference, so `base` may drop at the end of this scope.
    if let Some(base_spec) = &spec.based_on {
        if let Some(base) = build_noesis_style(base_spec, name, uri) {
            style.set_based_on(&base);
        } else {
            warn!(
                "NoesisStyles: BasedOn style (TargetType {:?}) skipped for {name:?} in scene {uri:?}",
                base_spec.target_type,
            );
        }
    }

    for (property, value) in &spec.setters {
        if !style.add_setter(property, &value.to_boxed()) {
            warn!(
                "NoesisStyles: setter {property:?} unresolved on {:?} ({name:?})",
                spec.target_type,
            );
        }
    }

    for trig in &spec.triggers {
        let mut trigger = Trigger::new();
        if !trigger.set_property(&spec.target_type, &trig.property) {
            warn!(
                "NoesisStyles: trigger property {:?} unresolved on {:?} ({name:?})",
                trig.property, spec.target_type,
            );
            continue;
        }
        if !trigger.set_value(&trig.value.to_boxed()) {
            warn!(
                "NoesisStyles: trigger value for {:?} rejected ({name:?})",
                trig.property
            );
        }
        for (property, value) in &trig.setters {
            if !trigger.add_setter(&spec.target_type, property, &value.to_boxed()) {
                warn!(
                    "NoesisStyles: trigger setter {property:?} unresolved on {:?} ({name:?})",
                    spec.target_type,
                );
            }
        }
        let _ = style.add_trigger(&trigger);
    }

    for dt in &spec.data_triggers {
        let mut trigger = DataTrigger::new();
        let mut binding = Binding::new(&dt.binding_path);
        if dt.relative_source_self {
            binding = binding.relative_source_self();
        }
        let _ = trigger.set_binding(&binding);
        if !trigger.set_value(&dt.value.to_boxed()) {
            warn!(
                "NoesisStyles: data-trigger value for {:?} rejected ({name:?})",
                dt.binding_path
            );
        }
        for (property, value) in &dt.setters {
            if !trigger.add_setter(&spec.target_type, property, &value.to_boxed()) {
                warn!(
                    "NoesisStyles: data-trigger setter {property:?} unresolved on {:?} ({name:?})",
                    spec.target_type,
                );
            }
        }
        let _ = style.add_trigger(&trigger);
    }

    for mt in &spec.multi_triggers {
        let mut trigger = MultiTrigger::new();
        for (property, value) in &mt.conditions {
            if !trigger.add_condition(&spec.target_type, property, &value.to_boxed()) {
                warn!(
                    "NoesisStyles: multi-trigger condition {property:?} unresolved on {:?} ({name:?})",
                    spec.target_type,
                );
            }
        }
        for (property, value) in &mt.setters {
            if !trigger.add_setter(&spec.target_type, property, &value.to_boxed()) {
                warn!(
                    "NoesisStyles: multi-trigger setter {property:?} unresolved on {:?} ({name:?})",
                    spec.target_type,
                );
            }
        }
        let _ = style.add_trigger(&trigger);
    }

    Some(style)
}

// ─────────────────────────────────────────────────────────────────────────────
// Public configuration
// ─────────────────────────────────────────────────────────────────────────────

/// Per-view scene configuration. Add as a [`Component`] to the camera entity
/// you also tag with [`NoesisCamera`]; the render app receives a copy on that
/// entity via [`ExtractComponent`]. One [`NoesisView`] == one live Noesis
/// `View` + intermediate, composited onto that camera. Multiple tagged
/// cameras drive multiple independent views.
///
/// Spawning a `NoesisView` auto-attaches every per-view bridge component (text,
/// visibility, dependency properties, items, focus, geometry, and the rest) via
/// required components, each defaulting to empty. This is what makes a write
/// survive when it is set before the scene exists: the component is already
/// there, so a `Startup`/`OnEnter` system can write into it and the value lands
/// once the scene builds (a freshly built scene re-applies each bridge's current
/// state). An empty bridge component costs nothing: its `Default` allocates no
/// heap and its reconcile pass returns immediately. The data-binding bridges
/// [`NoesisVm`](crate::NoesisVm) and [`NoesisCommands`](crate::commands::NoesisCommands)
/// are not auto-attached: they require an explicit class or command-host name, so
/// you add them yourself, and they keep their own state across scene rebuilds.
#[derive(Component, ExtractComponent, Clone, Debug)]
#[require(
    crate::animation::NoesisAnimation,
    crate::binding::NoesisBinding,
    crate::brushes::NoesisBrushes,
    crate::dp::NoesisDp,
    crate::events::NoesisClickWatch,
    crate::events::NoesisKeyDownWatch,
    crate::focus::NoesisFocus,
    crate::focus_input::NoesisFocusControl,
    crate::geometry::NoesisGeometry,
    crate::imaging::NoesisImaging,
    crate::inlines::NoesisInlines,
    crate::items::NoesisItems,
    crate::layout::NoesisLayout,
    crate::routed_events::NoesisEventWatch,
    crate::shapes::NoesisShapes,
    crate::styles::NoesisStyles,
    crate::svg::NoesisSvg,
    crate::text::NoesisText,
    crate::transforms::NoesisTransform,
    crate::transforms3d::NoesisTransform3D,
    crate::typography::NoesisTypography,
    crate::visibility::NoesisVisibility,
    crate::visual_state::NoesisVisualState
)]
pub struct NoesisView {
    /// Asset URI [`XamlRegistry`] keys on, typically the path passed to
    /// `AssetServer::load("foo.xaml")`.
    pub xaml_uri: String,
    /// Size of the intermediate render target Noesis paints into. The blit
    /// stretches this to fill whatever camera `ViewTarget` it composes on.
    pub size: UVec2,
    /// DPI scale for the view's content (1.0 == 96 ppi). Scales all UI crisply
    /// (vector re-tessellation, not an upscale blur) without changing
    /// [`size`](Self::size). Drive it from the window's scale factor for
    /// resolution-independent UI. Re-applied live via `View::set_scale` when it
    /// changes; no scene rebuild.
    pub scale: f32,
    /// Folder URIs whose fonts must be loaded before the XAML is parsed.
    /// Noesis's `CachedFontProvider` caches an empty folder the first
    /// time it scans one, so if fonts haven't loaded by the time we run
    /// `FrameworkElement::load`, all text in that folder renders
    /// invisibly forever. Populate this with each folder your XAML
    /// references in `FontFamily="Folder/#Family"` attributes.
    ///
    /// Folder URIs should match Noesis's form (no trailing slash), e.g.
    /// `"Fonts"` for `FontFamily="Fonts/#Bitter"`.
    pub wait_for_fonts: Vec<String>,
    /// Specific `(folder, filename)` pairs that must be present in
    /// `FontRegistry` before scene build. Stronger guard than
    /// [`wait_for_fonts`](Self::wait_for_fonts): that one only checks "at
    /// least one entry in this folder", which unblocks scene creation as
    /// soon as the first font arrives, too early when the scene's
    /// application resources need *a specific* font (e.g. the theme's
    /// PT Root UI). Populate with the critical filenames your theme +
    /// scene jointly require.
    pub wait_for_font_files: Vec<(String, String)>,
    /// Specific image URIs that must be present in [`crate::ImageRegistry`]
    /// before scene build. Noesis's `TextureProvider::GetTextureInfo`
    /// returns an empty / zero-size info when the URI is unknown, and the
    /// XAML parser caches that as a permanent "no texture for this URI",
    /// so an `<Image Source="Big.png"/>` whose decode hadn't finished
    /// when the scene built renders empty *forever*, even after the
    /// bytes land. Populate with the URIs your scene's images reference
    /// to keep the scene from building until they're all decoded.
    pub wait_for_images: Vec<String>,
    /// Toggle Noesis's built-in Per-Primitive AA ([`RenderFlag::Ppaa`]).
    /// Changing this at runtime re-calls `View::set_flags`; no scene
    /// rebuild, no View teardown.
    ///
    /// [`RenderFlag::Ppaa`]: noesis_runtime::view::RenderFlag::Ppaa
    pub ppaa: bool,
    /// `ResourceDictionary` URIs to install as the process-global
    /// application resources (styles, brushes, `ControlTemplate`s), in
    /// dependency order. Each URI must resolve via the same XAML
    /// provider that serves `xaml_uri`. Loaded once on first scene
    /// build; later changes are ignored.
    ///
    /// The plugin uses
    /// [`noesis_runtime::gui::install_app_resources_chain`]: an
    /// empty parent `ResourceDictionary` is installed up front, then
    /// each leaf is added to `parent.MergedDictionaries` and its
    /// `Source` assigned in order. This ensures cross-sibling
    /// `{StaticResource Foo}` references inside one leaf can find
    /// keys from earlier leaves (the simpler `LoadXaml +
    /// SetApplicationResources` path silently null-resolves them).
    ///
    /// A single-URI list works fine: it installs that one dict
    /// as a merged child of an otherwise-empty parent. For the Noesis
    /// SDK sample themes, that means a `vec![\"NoesisTheme.DarkBlue.xaml\"]`
    /// is sufficient (the `xaml_viewer` example does this via
    /// `--theme`).
    pub application_resources: Vec<String>,
    /// Font families Noesis falls back to when an element doesn't
    /// resolve its declared `FontFamily`. Each entry is a Noesis-style
    /// path-rooted family, e.g. `"Fonts/#Bitter"` or
    /// `"Fonts/#PT Root UI"`. The first entry that has glyphs for a
    /// codepoint wins.
    ///
    /// Installed once per process via `Noesis::SetFontFallbacks` after
    /// the font registry has at least one entry. The plugin eagerly
    /// registers every loaded font face with Noesis's
    /// `CachedFontProvider` before scene build (and incrementally as
    /// new fonts arrive), so this list is purely the WPF-style fallback
    /// chain; there's no need to mention non-fallback families just
    /// to make `FontFamily="Fonts/#X"` references resolve.
    ///
    /// Defaults to empty: with no fallback declared, Noesis uses the faces it
    /// resolves from `FontFamily` references directly. Set this to your own
    /// chain (e.g. `["Fonts/#Bitter"]`) when you want a process-wide fallback.
    /// An earlier release defaulted to `["Fonts/#Bitter"]`, which warned in apps
    /// that didn't ship that font.
    pub font_fallbacks: Vec<String>,
}

impl Default for NoesisView {
    fn default() -> Self {
        Self {
            xaml_uri: String::new(),
            size: UVec2::new(512, 512),
            scale: 1.0,
            wait_for_fonts: Vec::new(),
            wait_for_font_files: Vec::new(),
            wait_for_images: Vec::new(),
            ppaa: true,
            application_resources: Vec::new(),
            font_fallbacks: Vec::new(),
        }
    }
}

// ─────────────────────────────────────────────────────────────────────────────
// Render-world resource: owns Noesis handles + the per-scene instance
// ─────────────────────────────────────────────────────────────────────────────

/// **Non-send** render-world resource: the runtime's `View`/`Renderer`/device
/// handles are `!Send`/`!Sync` (`NonNull`-based), so this cannot be a regular
/// Bevy `Resource`. Inserted via `World::insert_non_send_resource` and accessed
/// through `NonSend`/`NonSendMut`; it stays pinned to the render thread, which
/// is where every Noesis call must happen. See the lifecycle invariants in
/// `CLAUDE.md`.
pub(crate) struct NoesisRenderState {
    device: wgpu::Device,
    shared_map: SharedXamlMap,
    shared_fonts: SharedFontMap,
    shared_images: SharedImageMap,
    // `Option` so `Drop` can take + drop each in the right order.
    registered_device: Option<noesis_runtime::render_device::Registered>,
    registered_provider: Option<noesis_runtime::xaml_provider::Registered>,
    registered_fonts: Option<noesis_runtime::font_provider::Registered>,
    registered_textures: Option<noesis_runtime::texture_provider::Registered>,
    /// Live scenes keyed by the render-world view entity (the camera carrying
    /// [`NoesisView`] + [`NoesisCamera`]). Built/torn down per entity by
    /// [`Self::ensure_scene`]; the blit node looks each one up by its view
    /// entity. Empty until the first `NoesisView`'s XAML resolves.
    scenes: HashMap<Entity, SceneInstance>,
    /// Entities whose scene was (re)built during this frame's Ensure pass. The
    /// Apply-set bridges read it so a write applies even when the component last
    /// changed before its scene existed: a freshly-built scene re-runs every
    /// bridge's apply against the current component state. Cleared at the top of
    /// each Ensure pass.
    scenes_built_this_frame: HashSet<Entity>,
    /// One-time flag for `SetFontFallbacks`/`SetFontDefaultProperties`;
    /// must fire AFTER Bevy has loaded at least one font into
    /// `SharedFontMap`, because Noesis's `SetFontFallbacks` eagerly runs
    /// `FontProvider::ScanFolder` to prime its cache.
    fallbacks_installed: bool,
    /// `(folder, filename)` pairs we've already eagerly registered with
    /// the C++ `CachedFontProvider` cache. Used by
    /// [`Self::register_pending_fonts`] to diff incrementally so we
    /// re-register each face exactly once. The eager-registration path
    /// makes scan-time gating irrelevant: any face present here is
    /// findable by `MatchFont` regardless of when `ScanFolder` ran.
    registered_faces: HashSet<(String, String)>,
    /// URI list already handed to
    /// `gui::install_app_resources_chain`. Guards us against
    /// re-installing the same chain every frame. `None` means we
    /// haven't installed anything yet; `Some(chain)` records exactly
    /// what we last installed.
    loaded_app_resources_chain: Option<Vec<String>>,
    /// Wall-clock origin for `View::Update(time)`. Bevy's `Time<Real>`
    /// isn't extracted to the render world by default (only
    /// `Time<Virtual>` and the generic `Time` are), so we keep our own.
    /// Drives storyboard progression; `elapsed_secs_f64()` each frame
    /// vs. Noesis's requirement for monotonically-increasing seconds.
    clock_origin: std::time::Instant,
    /// Last `swallow` set installed for each subscribed keydown name.
    /// Used by [`Self::sync_keydown_subscriptions`] to detect when a
    /// swallow list has changed and re-bind the C++-side handler with
    /// the new closure (which captures `swallow` by value).
    last_keydown_swallow: HashMap<(Entity, String), Vec<Key>>,
    /// Last `(mark_handled, handled_too)` flags installed per subscribed
    /// `(view, x:Name, event name)`. The routed-event callback captures these
    /// by value, so a flag change can't be patched in place; we detect it
    /// here and drop + re-create the subscription. Mirrors
    /// [`Self::last_keydown_swallow`]. Keyed across views; pruned per view at
    /// sync time.
    last_event_config: HashMap<(Entity, String, &'static str), (bool, bool)>,
    /// Reusable offscreen view for baking label panels (lazily built). Lives
    /// here so it shares the single registered device and its renderer is torn
    /// down before the device drops (see [`Drop`]).
    bake_rig: Option<BakeRig>,
    /// Live Rust-owned view models. Each owns a
    /// `ClassInstance` + `ClassRegistration` and is attached as a scene
    /// element's `DataContext`. Stored here (not in [`SceneInstance`]) so a VM
    /// survives scene rebuilds; the attach pass re-binds it to the new view.
    /// Released in [`Drop`] before the registered device, while Noesis is still
    /// initialized. Keyed by view entity. See [`crate::viewmodel`].
    view_models: HashMap<Entity, VmEntry>,
    /// Rust-owned `ItemsSource` collections keyed by `x:Name`. Each
    /// owns an `ObservableCollection` bound to a named `ItemsControl`. Like
    /// [`Self::view_models`] they outlive scene rebuilds (re-bound by the apply
    /// pass) and are released in [`Drop`] before the registered device. See
    /// [`crate::items`]. Keyed by `(view entity, x:Name)` so each view owns its
    /// list collections.
    items_sources: HashMap<(Entity, String), ItemsBinding>,
    /// Rust-owned plain-struct view models keyed by view entity + component
    /// `TypeId`. Each owns a reflected `PlainVmClass` + instance
    /// bound as that view's element `DataContext`. Same rebuild/teardown rules as
    /// [`Self::view_models`]; released in [`Drop`] before the registered device.
    /// See [`crate::plain_vm`].
    plain_vms: HashMap<(Entity, std::any::TypeId), PlainVmEntry>,
    /// Live Rust-owned command hosts (`ICommand` bridge). Each owns a
    /// `ClassInstance` + `ClassRegistration` + the per-command `Command`
    /// objects, bound as a scene element's `DataContext`. Outlives scene
    /// rebuilds (re-bound by the attach pass) and is released in `Drop`
    /// before the registered device. Keyed by view entity. See
    /// [`crate::commands`].
    command_hosts: HashMap<Entity, CommandEntry>,
    /// Rust-owned converted/multi bindings keyed by `(view entity, x:Name,
    /// property)`. Each owns the built `Binding`/`MultiBinding` + its
    /// `Converter`/`MultiConverter`, attached to a named element's DP. Same
    /// rebuild/teardown rules as [`Self::items_sources`] (re-bound by the apply
    /// pass after a scene rebuild); released in [`Drop`] before the registered
    /// device. See [`crate::binding`].
    binding_entries: HashMap<(Entity, String, String), BindingEntry>,
    /// Process-global integration callback guards (cursor / open-URL /
    /// play-audio) registered once by [`crate::integration::NoesisIntegrationPlugin`].
    /// Owned here (rather than in that plugin's own resource) so their `Drop`
    /// (which unregisters via FFI) is guaranteed to run BEFORE `shutdown()`:
    /// Bevy gives no drop order between two main-world resources, and
    /// unregistering after `shutdown()` dereferences torn-down engine state.
    /// Type-erased so `render` needn't name the per-hook guard types. See
    /// [`Self::own_integration_guards`].
    integration_guards: Vec<Box<dyn std::any::Any + Send>>,
}

struct SceneInstance {
    view: View,
    renderer_initialized: bool,
    /// Double-buffered intermediates. Each frame the main thread paints
    /// `intermediates[write_index]`, publishes it as the view's
    /// [`NoesisIntermediate`], then flips `write_index`. With Bevy's
    /// 1-frame-deep pipelined rendering, the render thread blits frame N's
    /// buffer while the main thread paints frame N+1 into the *other* buffer,
    /// so the two never touch the same texture and the composite can't tear.
    intermediates: [Intermediate; 2],
    write_index: usize,
    size: UVec2,
    built_for_uri: String,
    /// The exact XAML bytes this scene was parsed from. Held so
    /// [`NoesisRenderState::ensure_scene`] can detect a hot-reload: when the
    /// shared map's `Arc<Vec<u8>>` for [`Self::built_for_uri`] no longer points
    /// at these bytes (an asset `Modified` event or a direct
    /// [`XamlRegistry::insert`] both allocate a fresh `Arc`), the markup
    /// changed and the scene is rebuilt against the new bytes.
    built_bytes: Arc<Vec<u8>>,
    /// Last render flags written to the view via `View::set_flags`.
    /// Re-applied only when [`NoesisView`] changes; avoids the FFI call
    /// on every frame.
    applied_flags: u32,
    /// Last DPI scale written via `View::set_scale`. Re-applied only on change,
    /// like [`applied_flags`](Self::applied_flags).
    applied_scale: f32,
    /// Active `BaseButton::Click` subscriptions keyed by `x:Name`. Synced
    /// each frame against [`crate::events::NoesisClickWatch`] by
    /// [`NoesisRenderState::sync_click_subscriptions`]. Drops with the
    /// scene; orphaned subscriptions can't outlive their button.
    click_subs: HashMap<String, ClickSubscription>,
    /// Active `UIElement::KeyDown` subscriptions keyed by `x:Name`. Synced
    /// each frame against [`crate::events::NoesisKeyDownWatch`] by
    /// [`NoesisRenderState::sync_keydown_subscriptions`]. Same lifetime
    /// rules as `click_subs`.
    keydown_subs: HashMap<String, KeyDownSubscription>,
    /// Active generic `RoutedEvent` subscriptions keyed by `(x:Name, event
    /// name)`; one element may be watched for several events. Synced each
    /// frame against [`crate::routed_events::NoesisEventWatch`] by
    /// [`NoesisRenderState::sync_event_subscriptions_for`]. Drops with the
    /// scene; same orphan-safety rules as `click_subs` / `keydown_subs`. The
    /// `&'static str` half is `RoutedEvent::as_str()` (the enum is not `Hash`,
    /// its stable name is).
    event_subs: HashMap<(String, &'static str), EventSubscription>,
    /// Last text snapshot per name in [`crate::text::NoesisTextReadWatch`].
    /// Used to dedupe `NoesisTextChanged` emissions: only push when the
    /// text actually differs from the previous frame's snapshot. Names
    /// removed from the watch get pruned out of this map at sync time.
    text_snapshots: HashMap<String, String>,
    /// Last value snapshot per `(x:Name, property)` in
    /// [`crate::dp::NoesisDpReadWatch`]. Same dedupe role as
    /// [`Self::text_snapshots`] but for arbitrary typed DPs; lives in the
    /// scene so it resets on rebuild.
    dp_snapshots: HashMap<(String, String), crate::dp::DpValue>,
    /// `CompositeTransform` handles assigned as elements' `RenderTransform` by
    /// [`crate::transforms::NoesisTransform`], keyed by `x:Name`. Each is held at
    /// +1 so it stays alive while it is the element's live transform; it is the
    /// *same* object Noesis stores (assignment `AddRef`'s our pointer, it does not
    /// clone), so reading it back reflects the element's true transform. Drops
    /// with the scene; reassigning a name replaces (and releases) the old one.
    transform_handles: HashMap<String, CompositeTransform>,
    /// Last [`TransformSpec`](crate::transforms::TransformSpec) snapshot per
    /// `x:Name`, to dedupe [`crate::transforms::NoesisTransformChanged`]
    /// emissions. Resets on scene rebuild.
    transform_snapshots: HashMap<String, crate::transforms::TransformSpec>,
    /// `CompositeTransform3D` handles assigned as elements' `Transform3D` by
    /// [`crate::transforms3d::NoesisTransform3D`], keyed by `x:Name`. Held at +1
    /// (the same object Noesis stores) so the poll can read it back; same
    /// lifetime/identity rules as [`Self::transform_handles`].
    transform3d_handles: HashMap<String, CompositeTransform3D>,
    /// Last [`Transform3DSpec`](crate::transforms3d::Transform3DSpec) snapshot
    /// per `x:Name`, to dedupe
    /// [`crate::transforms3d::NoesisTransform3DChanged`] emissions. Resets on
    /// scene rebuild.
    transform3d_snapshots: HashMap<String, crate::transforms3d::Transform3DSpec>,
    /// `MatrixTransform3D` handles assigned as elements' `Transform3D` by
    /// [`crate::transforms3d::NoesisTransform3D`]'s matrix writes, keyed by
    /// `x:Name`. Held at +1 (the same object Noesis stores) so the poll can read
    /// it back; same lifetime/identity rules as [`Self::transform3d_handles`].
    /// Distinct from [`Self::transform3d_handles`] because the two transform
    /// kinds carry different read-back payloads; a name should use one or the
    /// other (both write the single `Transform3D` DP, so the later apply wins).
    matrix_transform3d_handles: HashMap<String, MatrixTransform3D>,
    /// Last 12-float `Transform3` matrix snapshot per `x:Name`, to dedupe
    /// [`crate::transforms3d::NoesisMatrixTransform3DChanged`] emissions. Resets
    /// on scene rebuild.
    matrix_transform3d_snapshots: HashMap<String, [f32; 12]>,
    /// Last brush read back per `(x:Name, property)` painted by
    /// [`crate::brushes::NoesisBrushes`]. Dedupes [`crate::brushes::NoesisBrushChanged`]
    /// emissions; resets on scene rebuild.
    brush_snapshots: HashMap<(String, String), crate::brushes::BrushReadback>,
    /// Last typed font value per `(x:Name, field)` watched by
    /// [`crate::typography::NoesisTypography`]. Dedupes `NoesisTypographyChanged`
    /// emissions; resets on scene rebuild. Distinct from [`Self::dp_snapshots`]
    /// because enum font DPs need the typed getters, not the generic `i32` read.
    typo_snapshots:
        HashMap<(String, crate::typography::TypographyField), crate::typography::TypographyValue>,
    /// Installed `KeyBinding`s keyed by `(x:Name, key ordinal, modifier
    /// bits)`, synced against [`crate::focus_input::NoesisFocusControl::bindings`].
    /// Diff-reconciled: a spec dropped from the component detaches its binding
    /// via `KeyBinding::remove_from`. Remaining entries drop with the scene.
    input_bindings: HashMap<(String, i32, i32), InstalledKeyBinding>,
    /// Last `(candidate, predicted_name, matches_expected)` per
    /// [`crate::focus_input::FocusPredict`] ident, to dedupe
    /// [`crate::focus_input::NoesisFocusPredicted`] emissions. Resets on scene
    /// rebuild.
    predict_snapshots: HashMap<(String, i32, Option<String>), (bool, Option<String>, bool)>,
    /// Last image read-back per `x:Name` watched by
    /// [`crate::imaging::NoesisImaging`]. Dedupes
    /// [`crate::imaging::NoesisImageChanged`] emissions; resets on scene rebuild.
    image_snapshots: HashMap<String, crate::imaging::ImageReadback>,
    /// Live inline handle trees built by [`crate::inlines::NoesisInlines`], keyed
    /// by `x:Name`. Held so the read-back can re-read live `Run` text / `Hyperlink`
    /// URIs; the `TextBlock`'s collection also owns these (`AddRef`'d on add), so
    /// they stay valid while it keeps them. Drops with the scene.
    inline_handles: HashMap<String, Vec<crate::inlines::BuiltInline>>,
    /// Last inline read-back per `x:Name` watched by `NoesisInlines`. Dedupes
    /// [`crate::inlines::NoesisInlinesChanged`] emissions; resets on scene rebuild.
    inlines_snapshots: HashMap<String, crate::inlines::InlinesReadback>,
}

/// One installed `KeyBinding`. Holds the `Command` *and* the `KeyBinding` at +1
/// so neither is released while the binding lives in the element's
/// `InputBindings`. On reconcile a dropped spec calls `binding.remove_from` to
/// detach it; scene teardown drops both, releasing our references. `command` is
/// held only to keep its +1 alive for the binding's lifetime.
struct InstalledKeyBinding {
    #[allow(dead_code)] // held only to keep the command's +1 alive.
    command: Command,
    binding: KeyBinding,
}

/// A persistent, camera-less Noesis view reused to bake label panels to
/// offscreen textures. Unlike [`SceneInstance`] it owns no intermediate (it
/// renders straight into a caller-supplied [`wgpu::TextureView`]) and is never
/// composited to a camera. One rig serves every label of the same template;
/// see [`NoesisRenderState::bake_into`].
struct BakeRig {
    view: View,
    renderer_initialized: bool,
    /// Template URI the rig's content was loaded from; a different URI forces
    /// a rebuild.
    built_for_uri: String,
    /// Last size handed to `View::set_size`; re-applied only on change.
    size: UVec2,
}

impl NoesisRenderState {
    fn new(device: wgpu::Device, queue: wgpu::Queue) -> Self {
        let shared_map = SharedXamlMap::default();
        let shared_fonts = SharedFontMap::default();
        let shared_images = SharedImageMap::default();
        let wgpu_rd = WgpuRenderDevice::new(device.clone(), queue);
        let registered_device = noesis_runtime::render_device::register(wgpu_rd);
        let xaml_prov = BevyXamlProvider::from_shared(shared_map.clone());
        let registered_provider = noesis_runtime::xaml_provider::set_xaml_provider(xaml_prov);
        let font_prov = BevyFontProvider::from_shared(shared_fonts.clone());
        let registered_fonts = noesis_runtime::font_provider::set_font_provider(font_prov);
        let texture_prov = BevyTextureProvider::from_shared(shared_images.clone());
        let registered_textures =
            noesis_runtime::texture_provider::set_texture_provider(texture_prov);

        // Font fallbacks must NOT be installed here. Noesis's
        // `SetFontFallbacks` eagerly invokes `FontProvider::ScanFolder`
        // to prime its cache; if we call it before Bevy has finished
        // loading the font assets into `SharedFontMap`, the scan returns
        // empty and `CachedFontProvider` caches that empty result
        // forever. Defer installation until `ensure_scene` sees at least
        // one font (see `install_font_fallbacks_if_needed` below).

        Self {
            device,
            shared_map,
            shared_fonts,
            shared_images,
            registered_device: Some(registered_device),
            registered_provider: Some(registered_provider),
            registered_fonts: Some(registered_fonts),
            registered_textures: Some(registered_textures),
            scenes: HashMap::new(),
            scenes_built_this_frame: HashSet::new(),
            fallbacks_installed: false,
            registered_faces: HashSet::new(),
            loaded_app_resources_chain: None,
            clock_origin: std::time::Instant::now(),
            last_keydown_swallow: HashMap::new(),
            last_event_config: HashMap::new(),
            bake_rig: None,
            view_models: HashMap::new(),
            items_sources: HashMap::new(),
            plain_vms: HashMap::new(),
            command_hosts: HashMap::new(),
            binding_entries: HashMap::new(),
            integration_guards: Vec::new(),
        }
    }

    /// Take ownership of the process-global integration callback guards so they
    /// drop before `shutdown()` (see [`Self::integration_guards`]). The caller
    /// registers exactly once; guards already present are replaced. Main-thread
    /// only.
    pub(crate) fn own_integration_guards(&mut self, guards: Vec<Box<dyn std::any::Any + Send>>) {
        self.integration_guards = guards;
    }

    /// Build view `entity`'s [`VmEntry`] on first sight (register the Noesis
    /// class, instantiate, wire the entity-tagged change forwarder). No-op if it
    /// already exists. Main-thread only.
    pub(crate) fn ensure_view_model(
        &mut self,
        entity: Entity,
        def: &ViewModelDef,
        changed: &SharedVmChangedQueue,
    ) {
        if self.view_models.contains_key(&entity) {
            return;
        }
        match VmEntry::build(entity, def, changed) {
            Some(entry) => {
                self.view_models.insert(entity, entry);
            }
            None => warn!(
                "NoesisViewModel: failed to register/instantiate class {:?} (duplicate name?)",
                def.class_name(),
            ),
        }
    }

    /// Apply queued writes to view `entity`'s view-model instance. Unknown
    /// property names log a warning. No-op when the entry isn't built yet.
    pub(crate) fn apply_view_model_writes_for(
        &mut self,
        entity: Entity,
        writes: &[(String, VmValue)],
    ) {
        let Some(entry) = self.view_models.get(&entity) else {
            return;
        };
        for (prop, value) in writes {
            if !entry.write(prop, value) {
                warn!("NoesisViewModel: view {entity:?} has no property {prop:?}");
            }
        }
    }

    /// Attach any not-yet-attached view model as its target's `DataContext` in
    /// its own view's scene. No-op until that view (and any named target) exists;
    /// retries each frame, and re-attaches after a scene rebuild.
    pub(crate) fn attach_view_models(&mut self) {
        for (&entity, entry) in &mut self.view_models {
            let Some(scene) = self.scenes.get(&entity) else {
                continue;
            };
            let Some(content) = scene.view.content() else {
                continue;
            };
            let uri = &scene.built_for_uri;
            if !entry.needs_attach(uri) {
                continue;
            }
            let target = match entry.target() {
                AttachTarget::Root => scene.view.content(),
                AttachTarget::Named(name) => content.find_name(name),
            };
            let Some(mut element) = target else {
                warn!(
                    "NoesisViewModel: attach target for view {:?} not found in scene {:?}",
                    entity, scene.built_for_uri,
                );
                continue;
            };
            if element.set_data_context(entry.instance()) {
                entry.mark_attached(uri);
            } else {
                warn!("NoesisViewModel: set_data_context returned false for view {entity:?}");
            }
        }
    }

    /// Build view `entity`'s [`CommandEntry`] on first sight (register the Noesis
    /// command-host class, instantiate, build a `Command` per declared name tagged
    /// with `entity` and pushing to `queue`). No-op if it already exists.
    /// Main-thread only.
    pub(crate) fn ensure_commands(
        &mut self,
        entity: Entity,
        def: &CommandsDef,
        queue: &SharedCommandQueue,
    ) {
        if self.command_hosts.contains_key(&entity) {
            return;
        }
        match CommandEntry::build(entity, def, queue) {
            Some(entry) => {
                self.command_hosts.insert(entity, entry);
            }
            None => warn!(
                "NoesisCommands: failed to register/instantiate class {:?} (duplicate name?)",
                def.class_name(),
            ),
        }
    }

    /// Apply queued enabled-state edits to view `entity`'s command host. Unknown
    /// command names log a warning. No-op when the host isn't built yet.
    pub(crate) fn apply_command_enables_for(&mut self, entity: Entity, enables: &[(String, bool)]) {
        let Some(entry) = self.command_hosts.get(&entity) else {
            return;
        };
        for (name, value) in enables {
            if !entry.set_enabled(name, *value) {
                warn!("NoesisCommands: view {entity:?} has no command {name:?}");
            }
        }
    }

    /// Attach any not-yet-attached command host as its target's `DataContext` in
    /// its own view's scene. No-op until that view (and any named target) exists;
    /// retries each frame, and re-attaches after a scene rebuild. Mirrors
    /// [`Self::attach_view_models`].
    pub(crate) fn attach_commands(&mut self) {
        for (&entity, entry) in &mut self.command_hosts {
            let Some(scene) = self.scenes.get(&entity) else {
                continue;
            };
            let Some(content) = scene.view.content() else {
                continue;
            };
            let uri = &scene.built_for_uri;
            if !entry.needs_attach(uri) {
                continue;
            }
            let target = match entry.target() {
                AttachTarget::Root => scene.view.content(),
                AttachTarget::Named(name) => content.find_name(name),
            };
            let Some(mut element) = target else {
                warn!(
                    "NoesisCommands: attach target for view {:?} not found in scene {:?}",
                    entity, scene.built_for_uri,
                );
                continue;
            };
            if element.set_data_context(entry.instance()) {
                entry.mark_attached(uri);
            } else {
                warn!("NoesisCommands: set_data_context returned false for view {entity:?}");
            }
        }
    }

    /// Reconcile view `entity`'s [`NoesisItems`] component. When `changed`, set
    /// each named element's collection to the desired typed item list and its
    /// desired selection (creating a collection per `(entity, name)` on first
    /// use, pruning names no longer present). Every frame, bind any unbound
    /// collection to its element's `ItemsSource` (handles first resolution and
    /// re-binding after a rebuild), then drive any pending selection and
    /// collection-view navigation.
    pub(crate) fn apply_items_for(
        &mut self,
        entity: Entity,
        sources: &HashMap<String, Vec<ItemValue>>,
        objects: &HashMap<String, ObjectSource>,
        select: &HashMap<String, i32>,
        navigate: &HashMap<String, CollectionViewOp>,
        changed: bool,
    ) {
        if changed {
            // Prune this view's collections whose name was removed.
            self.items_sources.retain(|(ent, name), _| {
                *ent != entity || sources.contains_key(name) || objects.contains_key(name)
            });
            for (name, items) in sources {
                let binding = self
                    .items_sources
                    .entry((entity, name.clone()))
                    .or_default();
                binding.set_typed(items);
                binding.set_desired_select(select.get(name).copied());
                binding.set_desired_nav(navigate.get(name).copied());
            }
            for (name, source) in objects {
                let binding = self
                    .items_sources
                    .entry((entity, name.clone()))
                    .or_default();
                binding.set_objects(source);
                binding.set_desired_select(select.get(name).copied());
                binding.set_desired_nav(navigate.get(name).copied());
            }
        }

        let Some(scene) = self.scenes.get(&entity) else {
            return;
        };
        let Some(content) = scene.view.content() else {
            return;
        };
        let uri = scene.built_for_uri.clone();
        for ((ent, name), binding) in &mut self.items_sources {
            if *ent != entity {
                continue;
            }
            let Some(mut element) = content.find_name(name) else {
                if binding.needs_bind(&uri) {
                    warn!(
                        "NoesisItems: x:Name {:?} not found in scene {:?}",
                        name, scene.built_for_uri,
                    );
                }
                continue;
            };
            if binding.needs_bind(&uri) {
                if element.set_items_source(binding.collection()) {
                    binding.mark_bound(&uri);
                } else {
                    warn!("NoesisItems: element {name:?} is not an ItemsControl; skipped");
                    continue;
                }
            }
            binding.drive_selection(&mut element);
            // Navigation runs last so it wins when both select and navigate are
            // set for the same control (both move the shared current item).
            binding.drive_navigation();
        }
    }

    /// Poll each of view `entity`'s bound list controls, returning
    /// `(x:Name, count, selected_index, current_position, current-typed-value)`
    /// for every control whose snapshot changed since the last poll. Drives the
    /// [`NoesisItemsCurrent`](crate::items::NoesisItemsCurrent) read-back.
    pub(crate) fn poll_items_for(
        &mut self,
        entity: Entity,
    ) -> Vec<(String, usize, i32, i32, Option<ItemValue>)> {
        let mut out = Vec::new();
        let Some(scene) = self.scenes.get(&entity) else {
            return out;
        };
        let Some(content) = scene.view.content() else {
            return out;
        };
        for ((ent, name), binding) in &mut self.items_sources {
            if *ent != entity {
                continue;
            }
            let Some(element) = content.find_name(name) else {
                continue;
            };
            if let Some((count, selected_index, current_position, current)) =
                binding.read_changed(&element)
            {
                out.push((
                    name.clone(),
                    count,
                    selected_index,
                    current_position,
                    current,
                ));
            }
        }
        out
    }

    /// Whether view `entity` already has a built binding for `(element,
    /// property)`. The bridge builds each target's runtime binding once.
    pub(crate) fn has_binding(&self, entity: Entity, element: &str, property: &str) -> bool {
        self.binding_entries
            .contains_key(&(entity, element.to_owned(), property.to_owned()))
    }

    /// Store a freshly built binding for view `entity`'s `(element, property)`
    /// target. Bound to its element by the next [`Self::bind_pending_for`] pass.
    pub(crate) fn insert_binding(
        &mut self,
        entity: Entity,
        element: String,
        property: String,
        built: BuiltBinding,
    ) {
        self.binding_entries
            .insert((entity, element, property), BindingEntry::new(built));
    }

    /// Attach any of view `entity`'s not-yet-bound bindings onto their named
    /// element's DP. No-op until the view (and named element) exists; retries each
    /// frame, and re-attaches after a scene rebuild. Mirrors
    /// [`Self::apply_items_for`]'s bind pass.
    pub(crate) fn bind_pending_for(&mut self, entity: Entity) {
        let Some(scene) = self.scenes.get(&entity) else {
            return;
        };
        let Some(content) = scene.view.content() else {
            return;
        };
        let uri = scene.built_for_uri.clone();
        for ((ent, element, property), entry) in &mut self.binding_entries {
            if *ent != entity || !entry.needs_bind(&uri) {
                continue;
            }
            let Some(target) = content.find_name(element) else {
                warn!(
                    "NoesisBinding: x:Name {:?} not found in scene {:?}",
                    element, scene.built_for_uri,
                );
                continue;
            };
            if entry.bind_onto(&target, property) {
                entry.mark_bound(&uri);
            } else {
                warn!(
                    "NoesisBinding: binding {element:?}.{property:?} failed \
                     (unknown property or type mismatch)",
                );
            }
        }
    }

    /// Reconcile view `entity`'s plain-struct view model of type `type_id`:
    /// register + instantiate on first sight, apply a pending field snapshot
    /// (Rust→UI), attach it as its target's `DataContext` once the view + element
    /// exist (re-attaching after a rebuild), and return any queued two-way edits
    /// (UI→Rust) for the caller to apply back into the component. The metadata is
    /// passed in (not generic) so one method serves every VM type. See
    /// [`crate::plain_vm`].
    pub(crate) fn sync_plain_vm(
        &mut self,
        entity: Entity,
        type_id: std::any::TypeId,
        type_name: &str,
        props: &[(&'static str, crate::plain_vm::PlainType)],
        target: &AttachTarget,
        snapshot: Option<Vec<crate::plain_vm::PlainValue>>,
    ) -> Vec<(u32, crate::plain_vm::PlainValue)> {
        let key = (entity, type_id);
        if let std::collections::hash_map::Entry::Vacant(slot) = self.plain_vms.entry(key) {
            let Some(entry) = PlainVmEntry::build(type_name, props, target.clone()) else {
                warn!(
                    "NoesisViewModel: failed to register plain VM {type_name:?} (duplicate name?)",
                );
                return Vec::new();
            };
            slot.insert(entry);
        }

        if let (Some(entry), Some(snapshot)) = (self.plain_vms.get(&key), snapshot) {
            entry.apply_snapshot(&snapshot);
        }

        // Attach as DataContext once this view's scene + target element exist;
        // re-attach after a rebuild. Disjoint field borrows (`scenes` vs
        // `plain_vms`) keep the borrow checker happy.
        if let Some(scene) = self.scenes.get(&entity)
            && let Some(content) = scene.view.content()
        {
            let uri = scene.built_for_uri.clone();
            if let Some(entry) = self.plain_vms.get_mut(&key)
                && entry.needs_attach(&uri)
            {
                let element = match entry.target() {
                    AttachTarget::Root => scene.view.content(),
                    AttachTarget::Named(name) => content.find_name(name),
                };
                match element {
                    Some(mut element) => {
                        if !entry.attach_to(&mut element, &uri) {
                            warn!(
                                "NoesisViewModel: set_data_context returned false for \
                                 {type_name:?} (target not a FrameworkElement?)",
                            );
                        }
                    }
                    None => warn!(
                        "NoesisViewModel: attach target for {type_name:?} not found in scene {:?}",
                        scene.built_for_uri,
                    ),
                }
            }
        }

        self.plain_vms
            .get(&key)
            .map(PlainVmEntry::drain_writebacks)
            .unwrap_or_default()
    }

    /// Eagerly register every `(folder, filename)` pair currently in
    /// [`SharedFontMap`] that we haven't already handed to the C++
    /// `CachedFontProvider`. Called both before scene build (so the
    /// initial population is in place when XAML's first font lookup
    /// runs) and on every render-app sync (so fonts that arrive after
    /// scene build are picked up before they're ever requested).
    ///
    /// This bypasses Noesis's lazy `ScanFolder` model, which only fires
    /// once per folder and then caches its result, making any face that
    /// wasn't loaded at scan time permanently invisible without this.
    fn register_pending_fonts(&mut self) {
        let Some(registered) = self.registered_fonts.as_ref() else {
            return;
        };
        let pairs: Vec<(String, String)> = {
            let guard = self.shared_fonts.0.lock().expect("SharedFontMap poisoned");
            guard
                .keys()
                .filter(|pair| !self.registered_faces.contains(*pair))
                .cloned()
                .collect()
        };
        if pairs.is_empty() {
            return;
        }
        for (folder, filename) in pairs {
            registered.register_font(&folder, &filename);
            self.registered_faces.insert((folder, filename));
        }
    }

    /// Run once, the first time our font map holds any entries. Installs
    /// the Noesis font fallback chain and default properties so unstyled
    /// elements get a real font. Guarded by a flag because
    /// `SetFontFallbacks` is a process-global Noesis setting and Noesis
    /// caches its scan of each folder forever after first call.
    fn install_font_fallbacks_if_needed(&mut self, fallbacks: &[String]) {
        if self.fallbacks_installed {
            return;
        }
        let has_fonts = {
            let guard = self.shared_fonts.0.lock().expect("SharedFontMap poisoned");
            !guard.is_empty()
        };
        if !has_fonts {
            return;
        }
        let refs: Vec<&str> = fallbacks.iter().map(String::as_str).collect();
        noesis_runtime::font_provider::set_font_fallbacks(&refs);
        // WPF defaults (size=12, weight=Normal=400, stretch=Normal=5,
        // style=Normal=0).
        noesis_runtime::font_provider::set_font_default_properties(12.0, 400, 5, 0);
        info!(
            "NoesisRenderState: font fallbacks installed: {:?}",
            fallbacks,
        );
        self.fallbacks_installed = true;
    }

    fn shared_map(&self) -> &SharedXamlMap {
        &self.shared_map
    }

    fn shared_fonts(&self) -> &SharedFontMap {
        &self.shared_fonts
    }

    fn shared_images(&self) -> &SharedImageMap {
        &self.shared_images
    }

    /// Build (or rebuild) the scene instance if the configured URI has
    /// bytes in the shared map and the current instance (if any) is stale.
    /// No-op when the XAML hasn't arrived yet.
    fn ensure_scene(&mut self, entity: Entity, config: &NoesisView) {
        if config.xaml_uri.is_empty() {
            self.teardown_scene(entity);
            return;
        }

        // Current bytes for this URI in the shared map (`None` until the XAML
        // first lands). Cloning the `Arc` is cheap and lets us both detect a
        // hot-reload (by pointer identity) and stamp the rebuilt scene.
        let current_bytes = {
            let guard = self.shared_map.0.lock().expect("SharedXamlMap poisoned");
            guard.get(&config.xaml_uri).cloned()
        };

        // Hot-reload: the URI is unchanged but its bytes were replaced. Both
        // `update_xaml_registry` (asset `Modified`) and `XamlRegistry::insert`
        // allocate a fresh `Arc` for replaced bytes, so an `Arc::ptr_eq`
        // mismatch means the markup changed; force a full rebuild (not a
        // resize) against the new bytes. The bridges (view-models, items,
        // bindings, commands) re-attach after the rebuild via `teardown_scene`.
        let bytes_changed = matches!(
            (self.scenes.get(&entity), &current_bytes),
            (Some(scene), Some(bytes))
                if scene.built_for_uri == config.xaml_uri
                    && !Arc::ptr_eq(&scene.built_bytes, bytes)
        );

        // Same URI + bytes, different size: resize in place without tearing
        // down the View. Rebuild just the intermediate texture; `View::set_size`
        // informs Noesis without invalidating the renderer. Important for
        // desktop window drags, which fire `WindowResized` at every pixel.
        if !bytes_changed
            && let Some(scene) = self.scenes.get_mut(&entity)
            && scene.built_for_uri == config.xaml_uri
            && scene.size != config.size
        {
            scene.view.set_size(config.size.x, config.size.y);
            scene.intermediates = [
                create_intermediate(&self.device, config.size),
                create_intermediate(&self.device, config.size),
            ];
            scene.size = config.size;
            return;
        }

        let up_to_date = !bytes_changed
            && self
                .scenes
                .get(&entity)
                .is_some_and(|s| s.built_for_uri == config.xaml_uri && s.size == config.size);
        if up_to_date {
            return;
        }

        self.teardown_scene(entity);

        // Confirm the XAML is currently present; skip if not.
        let Some(current_bytes) = current_bytes else {
            return;
        };
        // Defer scene creation until `wait_for_fonts` is satisfied (or
        // never set). Noesis's `CachedFontProvider` caches the result of
        // `ScanFolder` the first time it's called; if we build the View
        // before fonts have loaded, Noesis sees an empty folder and
        // never rescans, so all text renders invisible.
        for folder in &config.wait_for_fonts {
            let guard = self.shared_fonts.0.lock().expect("SharedFontMap poisoned");
            let have = guard.keys().any(|(f, _)| f == folder);
            if !have {
                return;
            }
        }
        for (folder, filename) in &config.wait_for_font_files {
            let guard = self.shared_fonts.0.lock().expect("SharedFontMap poisoned");
            let have = guard.contains_key(&(folder.clone(), filename.clone()));
            if !have {
                return;
            }
        }
        // Same problem as fonts but for textures: Noesis caches a
        // missing-texture lookup the first time GetTextureInfo returns
        // empty, and never asks again. Wait for every URI the scene
        // references to be in `SharedImageMap` before letting the View
        // construct.
        for uri in &config.wait_for_images {
            let guard = self
                .shared_images
                .0
                .lock()
                .expect("SharedImageMap poisoned");
            if !guard.contains_key(uri) {
                return;
            }
        }
        // If the scene references application resources (a theme),
        // wait for every URI in the chain to reach the provider;
        // otherwise the chain installer's `SetSource` calls hit empty
        // bytes and the leaf stays empty. Loop guards against any one
        // late-arriving URI delaying scene build for the rest.
        {
            let guard = self.shared_map.0.lock().expect("SharedXamlMap poisoned");
            for uri in &config.application_resources {
                if !guard.contains_key(uri) {
                    return;
                }
            }
        }

        // Eagerly register every font currently in `SharedFontMap` with
        // the C++ `CachedFontProvider` before XAML parsing runs. Noesis's
        // own lazy `ScanFolder` model fires once per folder during
        // `SetFontFallbacks` (or first font lookup) and caches its
        // result; pre-populating the cache here means a `FontFamily`
        // referenced from XAML resolves regardless of whether its file
        // happened to be loaded by scan time.
        self.register_pending_fonts();

        // Fonts are in the map now; this is the safe moment to install the
        // fallback chain. Noesis will immediately invoke our provider's
        // `scan_folder("Fonts")`; any face we haven't already eagerly
        // registered above gets picked up by the scan callback.
        self.install_font_fallbacks_if_needed(&config.font_fallbacks);

        // Application resources must be installed BEFORE the scene's XAML
        // is parsed, or the scene's `<Style TargetType="Button">` can't
        // resolve theme brushes. One-shot; re-configuring the URI later
        // would currently require a process restart.
        self.install_application_resources_if_needed(config);

        let Some(element) = FrameworkElement::load(&config.xaml_uri) else {
            warn!(
                "FrameworkElement::load({:?}) returned None despite bytes being in the registry",
                config.xaml_uri,
            );
            return;
        };
        let mut view = View::create(element);
        view.set_size(config.size.x, config.size.y);
        view.set_scale(config.scale);
        let initial_flags = flags_from(config);
        view.set_flags(initial_flags);
        // Intentionally do NOT call SetProjectionMatrix. Noesis derives the
        // primitive→clip projection from `DeviceCaps` (clip_space_y_inverted,
        // depth_range_zero_to_one); supplying an OpenGL-style ortho here makes
        // its render-tree visibility pass cull child elements (verified in
        // tests/headless_xaml_nested.rs). The reference IntegrationGLUT sample
        // also never calls SetProjectionMatrix.

        // `activate()` is required for Noesis to route keyboard input; the
        // view is created deactivated, so pre-seed it here. Focus loss is
        // picked up later via the NoesisInputEvent::Focus pipeline.
        view.activate();

        let intermediates = [
            create_intermediate(&self.device, config.size),
            create_intermediate(&self.device, config.size),
        ];
        info!(
            "NoesisRenderState: scene built — view + intermediate at {}x{} for uri {:?}",
            config.size.x, config.size.y, config.xaml_uri,
        );

        self.scenes.insert(
            entity,
            SceneInstance {
                view,
                renderer_initialized: false,
                intermediates,
                write_index: 0,
                size: config.size,
                built_for_uri: config.xaml_uri.clone(),
                built_bytes: current_bytes,
                applied_flags: initial_flags,
                applied_scale: config.scale,
                click_subs: HashMap::new(),
                keydown_subs: HashMap::new(),
                event_subs: HashMap::new(),
                text_snapshots: HashMap::new(),
                dp_snapshots: HashMap::new(),
                transform_handles: HashMap::new(),
                transform_snapshots: HashMap::new(),
                transform3d_handles: HashMap::new(),
                transform3d_snapshots: HashMap::new(),
                matrix_transform3d_handles: HashMap::new(),
                matrix_transform3d_snapshots: HashMap::new(),
                brush_snapshots: HashMap::new(),
                typo_snapshots: HashMap::new(),
                input_bindings: HashMap::new(),
                predict_snapshots: HashMap::new(),
                image_snapshots: HashMap::new(),
                inline_handles: HashMap::new(),
                inlines_snapshots: HashMap::new(),
            },
        );
        self.scenes_built_this_frame.insert(entity);
    }

    /// Whether `entity`'s scene was (re)built this frame. Apply-set bridges OR
    /// this with their own change detection so a write that was set before the
    /// scene existed still lands once it does, and so a hot-reload re-seeds the
    /// current component state. See [`Self::scenes_built_this_frame`].
    pub(crate) fn scene_rebuilt_this_frame(&self, entity: Entity) -> bool {
        self.scenes_built_this_frame.contains(&entity)
    }

    /// Apply view `entity`'s desired element visibility (`x:Name → visible`).
    /// No-op until the scene exists; missing names warn.
    pub(crate) fn apply_visibility_for(&mut self, entity: Entity, desired: &HashMap<String, bool>) {
        if desired.is_empty() {
            return;
        }
        let Some(scene) = self.scenes.get_mut(&entity) else {
            return;
        };
        let Some(content) = scene.view.content() else {
            return;
        };
        for (name, &visible) in desired {
            let Some(mut element) = content.find_name(name) else {
                warn!(
                    "NoesisVisibility: x:Name {:?} not found in scene {:?}",
                    name, scene.built_for_uri,
                );
                continue;
            };
            element.set_visibility(visible);
        }
    }

    /// Apply view `entity`'s desired element margins (`x:Name → [l, t, r, b]`).
    pub(crate) fn apply_layout_for(&mut self, entity: Entity, desired: &HashMap<String, [f32; 4]>) {
        if desired.is_empty() {
            return;
        }
        let Some(scene) = self.scenes.get_mut(&entity) else {
            return;
        };
        let Some(content) = scene.view.content() else {
            return;
        };
        for (name, &[left, top, right, bottom]) in desired {
            let Some(mut element) = content.find_name(name) else {
                warn!(
                    "NoesisLayout: x:Name {:?} not found in scene {:?}",
                    name, scene.built_for_uri,
                );
                continue;
            };
            element.set_margin(left, top, right, bottom);
        }
    }

    /// Apply view `entity`'s desired visual-state transitions
    /// (`x:Name → (state, use_transitions)`) via `VisualStateManager::GoToState`.
    /// No-op until the scene exists; missing names warn, and a failed transition
    /// (non-templated element, or unknown state) warns too.
    pub(crate) fn apply_visual_state_for(
        &mut self,
        entity: Entity,
        desired: &HashMap<String, (String, bool)>,
    ) {
        if desired.is_empty() {
            return;
        }
        let Some(scene) = self.scenes.get_mut(&entity) else {
            return;
        };
        let Some(content) = scene.view.content() else {
            return;
        };
        for (name, (state, use_transitions)) in desired {
            // `go_to_state` takes `&self`, so no `mut` binding needed.
            let Some(element) = content.find_name(name) else {
                warn!(
                    "NoesisVisualState: x:Name {:?} not found in scene {:?}",
                    name, scene.built_for_uri,
                );
                continue;
            };
            if !element.go_to_state(state, *use_transitions) {
                warn!(
                    "NoesisVisualState: GoToState({state:?}) failed for {name:?} \
                     in scene {:?} (not a templated control, or unknown state)",
                    scene.built_for_uri,
                );
            }
        }
    }

    /// Begin view `entity`'s requested code-built animations
    /// (`x:Name → AnimationSpec`) via `Animation::begin_on` against each named
    /// element's scalar dependency property. No-op until the scene exists;
    /// missing names warn, and a failed begin (unknown / non-`float` property,
    /// or a disconnected target) warns too. Re-begin replaces any clock already
    /// running on the same property (`SnapshotAndReplace`).
    pub(crate) fn begin_animations_for(
        &mut self,
        entity: Entity,
        desired: &HashMap<String, crate::animation::AnimationSpec>,
    ) {
        if desired.is_empty() {
            return;
        }
        let Some(scene) = self.scenes.get_mut(&entity) else {
            return;
        };
        let Some(content) = scene.view.content() else {
            return;
        };
        for (name, spec) in desired {
            let Some(element) = content.find_name(name) else {
                warn!(
                    "NoesisAnimation: x:Name {:?} not found in scene {:?}",
                    name, scene.built_for_uri,
                );
                continue;
            };
            let mut anim = DoubleAnimation::new();
            // From/To/Duration return false only on a type/read-only mismatch,
            // impossible on a freshly-created DoubleAnimation; ignore them.
            let _ = anim.set_from(spec.from);
            let _ = anim.set_to(Some(spec.to));
            let _ = anim.set_duration_secs(spec.duration_secs);
            if !anim.begin_on(
                &element,
                &spec.property,
                noesis_runtime::animation::HandoffBehavior::SnapshotAndReplace,
            ) {
                warn!(
                    "NoesisAnimation: begin_on({:?}) failed for {name:?} in scene {:?} \
                     (unknown / non-float property, or disconnected target)",
                    spec.property, scene.built_for_uri,
                );
            }
        }
    }

    /// Reconcile view `entity`'s `BaseButton::Click` subscriptions against its
    /// [`NoesisClickWatch`] component's names. Each callback pushes
    /// `(entity, name)` so the emitted [`NoesisClicked`] carries the view.
    pub(crate) fn sync_click_subscriptions_for(
        &mut self,
        entity: Entity,
        watch: &[String],
        queue: &SharedClickQueue,
    ) {
        let Some(scene) = self.scenes.get_mut(&entity) else {
            return;
        };

        // Drop subscriptions that are no longer requested. `retain` runs
        // each entry's drop in place, which fires the C++ unsubscribe.
        scene.click_subs.retain(|k, _| watch.iter().any(|w| w == k));

        // Add new subscriptions. Pull the View's content tree once per
        // frame; `find_name` is cheap but the FFI hop isn't free.
        let needs_new = watch.iter().any(|n| !scene.click_subs.contains_key(n));
        if !needs_new {
            return;
        }
        let Some(content) = scene.view.content() else {
            return;
        };
        for name in watch {
            if scene.click_subs.contains_key(name) {
                continue;
            }
            let Some(element) = content.find_name(name) else {
                warn!(
                    "NoesisClickWatch: x:Name {:?} not found in scene {:?}",
                    name, scene.built_for_uri,
                );
                continue;
            };
            let queue_handle = queue.clone();
            let captured_name = name.clone();
            let Some(sub) = subscribe_click(&element, move || {
                queue_handle.push(entity, captured_name.clone());
            }) else {
                warn!("NoesisClickWatch: element {name:?} is not a BaseButton; skipping");
                continue;
            };
            scene.click_subs.insert(name.clone(), sub);
        }
    }

    /// Reconcile the active `UIElement::KeyDown` subscription set against
    /// `entries`. Mirrors [`Self::sync_click_subscriptions`]: adds /
    /// drops subscriptions to match the desired watch list. The
    /// per-entry `swallow` set is captured by the closure so each
    /// callback can mark `out_handled = true` for keys the watcher
    /// wants to suppress propagation on.
    pub(crate) fn sync_keydown_subscriptions_for(
        &mut self,
        entity: Entity,
        entries: &[crate::events::KeyDownWatchEntry],
        queue: &SharedKeyDownQueue,
    ) {
        let Some(scene) = self.scenes.get_mut(&entity) else {
            return;
        };

        scene
            .keydown_subs
            .retain(|k, _| entries.iter().any(|e| e.name == *k));

        // Always re-bind every entry. Swallow lists may change between
        // frames and the C++-side handler captured them at subscription
        // time, so we can't update in place; we drop and re-create.
        // Cheap: a single FFI ref-bump + delegate add per entry, only on
        // the frames the watch actually changes.
        for entry in entries {
            // If the existing subscription's swallow set matches the
            // requested one, leave it alone. We track this on the Bevy
            // side via a sibling map keyed by name.
            if scene.keydown_subs.contains_key(&entry.name)
                && self
                    .last_keydown_swallow
                    .get(&(entity, entry.name.clone()))
                    .is_some_and(|prev| prev == &entry.swallow)
            {
                continue;
            }

            let Some(content) = scene.view.content() else {
                return;
            };
            let Some(element) = content.find_name(&entry.name) else {
                warn!(
                    "NoesisKeyDownWatch: x:Name {:?} not found in scene {:?}",
                    entry.name, scene.built_for_uri,
                );
                continue;
            };

            let queue_handle = queue.clone();
            let captured_name = entry.name.clone();
            let swallow = entry.swallow.clone();
            let Some(sub) = subscribe_keydown(&element, move |key: Key| {
                queue_handle.push(entity, captured_name.clone(), key);
                swallow.contains(&key)
            }) else {
                warn!(
                    "NoesisKeyDownWatch: element {:?} is not a UIElement; skipping",
                    entry.name
                );
                continue;
            };
            scene.keydown_subs.insert(entry.name.clone(), sub);
            self.last_keydown_swallow
                .insert((entity, entry.name.clone()), entry.swallow.clone());
        }

        // Prune this view's swallow snapshots whose name is no longer watched
        // (leave other views' entries intact).
        self.last_keydown_swallow
            .retain(|(ent, name), _| *ent != entity || entries.iter().any(|e| &e.name == name));
    }

    /// Reconcile view `entity`'s generic `RoutedEvent` subscriptions against
    /// `entries`. Mirrors [`Self::sync_keydown_subscriptions_for`]: adds /
    /// drops subscriptions to match the desired watch list, and re-binds an
    /// entry whose `(mark_handled, handled_too)` flags changed (the callback
    /// captures them by value). Each callback snapshots the live args and pushes
    /// `(entity, name, event, snapshot)` so the emitted [`NoesisRoutedEvent`]
    /// carries the originating view.
    pub(crate) fn sync_event_subscriptions_for(
        &mut self,
        entity: Entity,
        entries: &[crate::routed_events::EventWatchEntry],
        queue: &SharedRoutedEventQueue,
    ) {
        let Some(scene) = self.scenes.get_mut(&entity) else {
            return;
        };

        // Drop subscriptions that are no longer requested. `retain` runs each
        // entry's drop in place, which fires the C++ unsubscribe.
        scene.event_subs.retain(|(name, evname), _| {
            entries
                .iter()
                .any(|e| e.name == *name && e.event.as_str() == *evname)
        });

        for entry in entries {
            let evname = entry.event.as_str();
            let key = (entry.name.clone(), evname);

            // Leave an existing subscription alone iff its captured flags still
            // match the requested ones (sibling map keyed by view + name + event).
            if scene.event_subs.contains_key(&key)
                && self
                    .last_event_config
                    .get(&(entity, entry.name.clone(), evname))
                    .is_some_and(|prev| *prev == (entry.mark_handled, entry.handled_too))
            {
                continue;
            }

            // Pull the content tree per change. `find_name` is cheap but the FFI
            // hop isn't free, so we only reach here on the frames the watch moved.
            let Some(content) = scene.view.content() else {
                return;
            };
            let Some(element) = content.find_name(&entry.name) else {
                warn!(
                    "NoesisEventWatch: x:Name {:?} not found in scene {:?}",
                    entry.name, scene.built_for_uri,
                );
                continue;
            };

            let queue_handle = queue.clone();
            let captured_name = entry.name.clone();
            let captured_event = entry.event;
            let mark_handled = entry.mark_handled;
            let Some(sub) = subscribe_event(
                &element,
                entry.event,
                entry.handled_too,
                move |args: &EventArgs| {
                    let snapshot = RoutedEventSnapshot::capture(args);
                    queue_handle.push(entity, captured_name.clone(), captured_event, snapshot);
                    mark_handled
                },
            ) else {
                warn!(
                    "NoesisEventWatch: element {:?} not a UIElement / event {:?} unknown; skipping",
                    entry.name, evname,
                );
                continue;
            };

            // Replace any stale sub (flag change); drop runs the C++ unsubscribe.
            scene.event_subs.insert(key, sub);
            self.last_event_config.insert(
                (entity, entry.name.clone(), evname),
                (entry.mark_handled, entry.handled_too),
            );
        }

        // Prune this view's config snapshots whose (name, event) is no longer
        // watched (leave other views' entries intact).
        self.last_event_config.retain(|(ent, name, evname), _| {
            *ent != entity
                || entries
                    .iter()
                    .any(|e| &e.name == name && e.event.as_str() == *evname)
        });
    }

    /// Write each `(x:Name → text)` desired by view `entity`'s [`NoesisText`]
    /// component onto that view's elements. Missing names / non-text targets log
    /// a warning. No-op until the view's scene exists.
    pub(crate) fn apply_text_writes_for(
        &mut self,
        entity: Entity,
        set: &std::collections::HashMap<String, String>,
    ) {
        if set.is_empty() {
            return;
        }
        let Some(scene) = self.scenes.get_mut(&entity) else {
            return;
        };
        let Some(content) = scene.view.content() else {
            return;
        };
        for (name, text) in set {
            let Some(mut element) = content.find_name(name) else {
                warn!(
                    "NoesisText: x:Name {:?} not found in scene {:?}",
                    name, scene.built_for_uri,
                );
                continue;
            };
            if !element.set_text(text) {
                warn!("NoesisText: element {name:?} is not a TextBox/TextBlock; set_text skipped");
                continue;
            }
            // Update the snapshot eagerly so the read pass doesn't emit a phantom
            // NoesisTextChanged for a write we just made ourselves.
            scene.text_snapshots.insert(name.clone(), text.clone());
        }
    }

    /// Apply each `(x:Name → FontStyling)` desired by view `entity`'s
    /// [`NoesisTypography`](crate::typography::NoesisTypography) component onto
    /// that view's `TextElement`s. Each block's `Some` fields are written; `None`
    /// fields are skipped. Missing names log a warning; a field a target doesn't
    /// expose is logged at debug. No-op until the view's scene exists.
    pub(crate) fn apply_typography_for(
        &mut self,
        entity: Entity,
        set: &HashMap<String, crate::typography::FontStyling>,
    ) {
        if set.is_empty() {
            return;
        }
        let Some(scene) = self.scenes.get_mut(&entity) else {
            return;
        };
        let Some(content) = scene.view.content() else {
            return;
        };
        for (name, styling) in set {
            if styling.is_empty() {
                continue;
            }
            let Some(element) = content.find_name(name) else {
                warn!(
                    "NoesisTypography: x:Name {:?} not found in scene {:?}",
                    name, scene.built_for_uri,
                );
                continue;
            };
            if let Some(size) = styling.font_size
                && !noesis_runtime::typography::set_font_size(&element, size)
            {
                debug!("NoesisTypography: {name:?} did not accept FontSize");
            }
            if let Some(source) = &styling.font_family {
                // A fresh FontFamily holds one +1 ref; set_font_family AddRefs on
                // the Noesis side, so the handle can drop at scope end.
                let family = noesis_runtime::typography::FontFamily::new(source);
                if !noesis_runtime::typography::set_font_family(&element, &family) {
                    debug!("NoesisTypography: {name:?} did not accept FontFamily");
                }
            }
            if let Some(weight) = styling.font_weight
                && !noesis_runtime::typography::set_font_weight(&element, weight)
            {
                debug!("NoesisTypography: {name:?} did not accept FontWeight");
            }
            if let Some(style) = styling.font_style
                && !noesis_runtime::typography::set_font_style(&element, style)
            {
                debug!("NoesisTypography: {name:?} did not accept FontStyle");
            }
            if let Some(stretch) = styling.font_stretch
                && !noesis_runtime::typography::set_font_stretch(&element, stretch)
            {
                debug!("NoesisTypography: {name:?} did not accept FontStretch");
            }
        }
    }

    /// Poll view `entity`'s watched typed font properties, returning
    /// `(x:Name, value)` for each that changed since last frame (deduped against
    /// the per-scene snapshot). First poll after a watch is added always reports.
    ///
    /// Uses the runtime's *typed* font getters rather than the generic DP read
    /// path: `FontWeight`/`FontStyle`/`FontStretch` are enum DPs and don't
    /// round-trip through `get_i32`.
    pub(crate) fn poll_typography_reads_for(
        &mut self,
        entity: Entity,
        watched: &[crate::typography::TypographyWatch],
    ) -> Vec<(String, crate::typography::TypographyValue)> {
        use crate::typography::{TypographyField, TypographyValue};
        use noesis_runtime::typography as ty;

        let mut changed = Vec::new();
        let Some(scene) = self.scenes.get_mut(&entity) else {
            return changed;
        };
        scene.typo_snapshots.retain(|(name, field), _| {
            watched.iter().any(|w| &w.name == name && w.field == *field)
        });
        if watched.is_empty() {
            return changed;
        }
        let Some(content) = scene.view.content() else {
            return changed;
        };
        for watch in watched {
            let Some(element) = content.find_name(&watch.name) else {
                continue;
            };
            let current = match watch.field {
                TypographyField::FontSize => ty::font_size(&element).map(TypographyValue::FontSize),
                TypographyField::FontFamily => {
                    ty::get_font_family(&element).map(|f| TypographyValue::FontFamily(f.source()))
                }
                TypographyField::FontWeight => {
                    ty::font_weight(&element).map(TypographyValue::FontWeight)
                }
                TypographyField::FontStyle => {
                    ty::font_style(&element).map(TypographyValue::FontStyle)
                }
                TypographyField::FontStretch => {
                    ty::font_stretch(&element).map(TypographyValue::FontStretch)
                }
            };
            let Some(current) = current else {
                continue;
            };
            let key = (watch.name.clone(), watch.field);
            if scene.typo_snapshots.get(&key) == Some(&current) {
                continue;
            }
            scene.typo_snapshots.insert(key, current.clone());
            changed.push((watch.name.clone(), current));
        }
        changed
    }

    /// Populate each named `TextBlock`'s `Inlines` with the desired inline tree
    /// from view `entity`'s [`crate::inlines::NoesisInlines`] component. Builds
    /// the live Noesis inlines and stores their handles in the scene for the
    /// read-back. Re-apply is full replacement: any existing `Inlines` content
    /// (from an earlier apply or authored in XAML) is cleared
    /// (`InlineCollection::clear`) and rebuilt from the spec. No-op until the
    /// scene exists.
    pub(crate) fn apply_inlines_for(
        &mut self,
        entity: Entity,
        set: &HashMap<String, Vec<crate::inlines::InlineSpec>>,
    ) {
        if set.is_empty() {
            return;
        }
        let Some(scene) = self.scenes.get_mut(&entity) else {
            return;
        };
        let Some(content) = scene.view.content() else {
            return;
        };
        for (name, specs) in set {
            if specs.is_empty() {
                continue;
            }
            let Some(element) = content.find_name(name) else {
                warn!(
                    "NoesisInlines: x:Name {:?} not found in scene {:?}",
                    name, scene.built_for_uri,
                );
                continue;
            };
            let Some(mut collection) = noesis_runtime::text_inlines::text_block_inlines(&element)
            else {
                warn!("NoesisInlines: element {name:?} is not a TextBlock; skipped");
                continue;
            };
            // Clear any existing content, then drop our previously-built handles
            // (releasing their refs) before building the replacement so the live
            // collection holds only the new inlines.
            if collection.count() != 0 {
                collection.clear();
            }
            scene.inline_handles.remove(name);
            let built = crate::inlines::build_into(&mut collection, specs);
            scene.inline_handles.insert(name.clone(), built);
        }
    }

    /// Poll view `entity`'s watched `TextBlock`s, returning `(x:Name, readback)`
    /// for each whose live inline structure changed since last frame (deduped
    /// against the per-scene snapshot). The read re-reads the *live* collection
    /// count and pointer identity, plus the live `Run` text / `Hyperlink` URIs of
    /// the handles the bridge built. First poll after a watch is added reports.
    pub(crate) fn poll_inlines_reads_for(
        &mut self,
        entity: Entity,
        watched: &[String],
    ) -> Vec<(String, crate::inlines::InlinesReadback)> {
        let mut changed = Vec::new();
        let Some(scene) = self.scenes.get_mut(&entity) else {
            return changed;
        };
        scene
            .inlines_snapshots
            .retain(|name, _| watched.iter().any(|w| w == name));
        if watched.is_empty() {
            return changed;
        }
        let Some(content) = scene.view.content() else {
            return changed;
        };
        for name in watched {
            let Some(element) = content.find_name(name) else {
                continue;
            };
            let Some(collection) = noesis_runtime::text_inlines::text_block_inlines(&element)
            else {
                continue;
            };
            let empty = Vec::new();
            let tree = scene.inline_handles.get(name).unwrap_or(&empty);
            let current = crate::inlines::readback(tree, &collection);
            if scene.inlines_snapshots.get(name) == Some(&current) {
                continue;
            }
            scene
                .inlines_snapshots
                .insert(name.clone(), current.clone());
            changed.push((name.clone(), current));
        }
        changed
    }

    /// Apply view `entity`'s desired `Path` geometries (`x:Name → points`).
    pub(crate) fn apply_geometry_for(
        &mut self,
        entity: Entity,
        desired: &HashMap<String, Vec<[f32; 2]>>,
    ) {
        if desired.is_empty() {
            return;
        }
        let Some(scene) = self.scenes.get_mut(&entity) else {
            return;
        };
        let Some(content) = scene.view.content() else {
            return;
        };
        for (name, points) in desired {
            let Some(mut element) = content.find_name(name) else {
                warn!(
                    "NoesisGeometry: x:Name {:?} not found in scene {:?}",
                    name, scene.built_for_uri,
                );
                continue;
            };
            if !element.set_path_points(points) {
                warn!("NoesisGeometry: element {name:?} is not a Path (or < 2 points); skipped",);
            }
        }
    }

    /// Build view `entity`'s desired code-built shapes (`x:Name → spec`) and
    /// assign each to its named container element. Each spec becomes a fresh
    /// Noesis `Rectangle`/`Ellipse`/`Line` (size, corner radii, optional solid
    /// fill/stroke + thickness); the container adopts it as its `Content`
    /// (`ContentControl`) or, failing that, its decorator `Child`
    /// (`Border`/`Decorator`). Noesis takes its own reference, so the Rust shape
    /// handle drops right after. Missing names (and containers that accept
    /// neither) warn. Called when the view's `NoesisShapes` component changes.
    pub(crate) fn apply_shapes_for(
        &mut self,
        entity: Entity,
        desired: &HashMap<String, crate::shapes::ShapeSpec>,
    ) {
        use crate::shapes::ShapeKind;
        use noesis_runtime::brushes::SolidColorBrush;
        use noesis_runtime::shapes::{Ellipse, Line, Rectangle, Shape};

        if desired.is_empty() {
            return;
        }
        let Some(scene) = self.scenes.get_mut(&entity) else {
            return;
        };
        let Some(content) = scene.view.content() else {
            return;
        };

        // Apply the shared fill/stroke/thickness paint of `spec` to any built
        // `Shape`, then return it as an owning element handle ready for the tree.
        fn finish<S: Shape>(
            mut shape: S,
            spec: &crate::shapes::ShapeSpec,
        ) -> noesis_runtime::view::FrameworkElement {
            if let Some(rgba) = spec.fill {
                shape.set_fill(&SolidColorBrush::new(rgba));
            }
            if let Some(rgba) = spec.stroke {
                shape.set_stroke(&SolidColorBrush::new(rgba));
            }
            if let Some(t) = spec.stroke_thickness {
                shape.set_stroke_thickness(t);
            }
            shape.as_element()
        }

        for (name, spec) in desired {
            let Some(mut element) = content.find_name(name) else {
                warn!(
                    "NoesisShapes: x:Name {:?} not found in scene {:?}",
                    name, scene.built_for_uri,
                );
                continue;
            };
            let shape_el = match spec.kind {
                ShapeKind::Rectangle {
                    width,
                    height,
                    radius_x,
                    radius_y,
                } => {
                    let mut r = Rectangle::new();
                    r.set_width(width);
                    r.set_height(height);
                    r.set_radius_x(radius_x);
                    r.set_radius_y(radius_y);
                    finish(r, spec)
                }
                ShapeKind::Ellipse { width, height } => {
                    let mut e = Ellipse::new();
                    e.set_width(width);
                    e.set_height(height);
                    finish(e, spec)
                }
                ShapeKind::Line { x1, y1, x2, y2 } => {
                    let mut l = Line::new();
                    l.set_points(x1, y1, x2, y2);
                    finish(l, spec)
                }
            };
            // ContentControl `Content` first; fall back to a Decorator/Border
            // `Child`. Either takes its own reference to the shape.
            if !element.set_content(&shape_el) && !element.set_decorator_child(&shape_el) {
                warn!(
                    "NoesisShapes: container {name:?} accepts neither Content nor a decorator Child; skipped",
                );
            }
        }
    }

    /// Parse view `entity`'s [`NoesisSvg`](crate::svg::NoesisSvg) sources and
    /// size each named element to the parsed outline's measured bounds. Returns
    /// `(name, bounds)` (`bounds` = `[x, y, width, height]`) for every source
    /// that resolved to a live element and parsed: the read-back the SVG bridge
    /// turns into [`NoesisSvgChanged`](crate::svg::NoesisSvgChanged). Missing
    /// names and unparseable sources warn and are skipped (no entry).
    pub(crate) fn apply_svg_for(
        &mut self,
        entity: Entity,
        desired: &HashMap<String, String>,
    ) -> Vec<(String, [f32; 4])> {
        use noesis_runtime::svg::SvgPath;

        let mut applied = Vec::new();
        if desired.is_empty() {
            return applied;
        }
        let Some(scene) = self.scenes.get_mut(&entity) else {
            return applied;
        };
        let Some(content) = scene.view.content() else {
            return applied;
        };
        for (name, source) in desired {
            let Some(mut element) = content.find_name(name) else {
                warn!(
                    "NoesisSvg: x:Name {:?} not found in scene {:?}",
                    name, scene.built_for_uri,
                );
                continue;
            };
            let Some(path) = SvgPath::parse(source) else {
                warn!("NoesisSvg: source for {name:?} failed to parse; skipped");
                continue;
            };
            let bounds = path.bounds();
            // Size the element to the SVG's measured extent; a non-sizable target
            // (no Width/Height DP) still reports its bounds but warns on the set.
            if !element.set_width(bounds[2]) || !element.set_height(bounds[3]) {
                warn!(
                    "NoesisSvg: element {name:?} did not accept Width/Height; bounds still reported"
                );
            }
            applied.push((name.clone(), bounds));
        }
        applied
    }

    /// Move keyboard focus to `target` (an `x:Name`) in view `entity`, if set.
    /// Called when the view's `NoesisFocus` component changes.
    pub(crate) fn apply_focus_for(&mut self, entity: Entity, target: Option<&str>) {
        let Some(name) = target else {
            return;
        };
        let Some(scene) = self.scenes.get_mut(&entity) else {
            return;
        };
        let Some(content) = scene.view.content() else {
            return;
        };
        let Some(mut element) = content.find_name(name) else {
            warn!(
                "NoesisFocus: x:Name {:?} not found in scene {:?}",
                name, scene.built_for_uri,
            );
            return;
        };
        if !element.focus() {
            warn!("NoesisFocus: element {name:?} refused focus (non-focusable?)");
        }
    }

    /// Apply view `entity`'s one-shot directional / tab focus moves
    /// (`UIElement::MoveFocus`). Missing names warn; a move that didn't shift
    /// focus warns (non-traversable direction / no neighbour).
    pub(crate) fn apply_focus_moves_for(
        &mut self,
        entity: Entity,
        moves: &[crate::focus_input::FocusMove],
    ) {
        if moves.is_empty() {
            return;
        }
        let Some(scene) = self.scenes.get_mut(&entity) else {
            return;
        };
        let Some(content) = scene.view.content() else {
            return;
        };
        for m in moves {
            let Some(mut element) = content.find_name(&m.from) else {
                warn!(
                    "NoesisFocusControl: move-from x:Name {:?} not found in scene {:?}",
                    m.from, scene.built_for_uri,
                );
                continue;
            };
            if !element.move_focus(m.direction, m.wrapped) {
                warn!(
                    "NoesisFocusControl: MoveFocus({:?}, wrapped={}) from {:?} moved nothing",
                    m.direction, m.wrapped, m.from,
                );
            }
        }
    }

    /// Apply view `entity`'s one-shot focus-engagement actions
    /// (`UIElement::Focus(engage)`).
    pub(crate) fn apply_focus_engages_for(
        &mut self,
        entity: Entity,
        engages: &[crate::focus_input::FocusEngage],
    ) {
        if engages.is_empty() {
            return;
        }
        let Some(scene) = self.scenes.get_mut(&entity) else {
            return;
        };
        let Some(content) = scene.view.content() else {
            return;
        };
        for e in engages {
            let Some(mut element) = content.find_name(&e.name) else {
                warn!(
                    "NoesisFocusControl: engage x:Name {:?} not found in scene {:?}",
                    e.name, scene.built_for_uri,
                );
                continue;
            };
            if !element.focus_engage(e.engage) {
                warn!(
                    "NoesisFocusControl: element {:?} refused focus(engage={})",
                    e.name, e.engage,
                );
            }
        }
    }

    /// Reconcile view `entity`'s `KeyBinding`s against `specs`. Each binding's
    /// command callback pushes `(entity, name, key, modifiers)` onto `queue`, so
    /// the emitted `NoesisFocusBindingFired` carries the originating view.
    /// Bindings already installed are left alone; bindings dropped from `specs`
    /// are detached from their element via `KeyBinding::remove_from` and then
    /// forgotten (releasing our `+1` references). Mirrors
    /// `sync_click_subscriptions_for`.
    pub(crate) fn sync_key_bindings_for(
        &mut self,
        entity: Entity,
        specs: &[crate::focus_input::KeyBindingSpec],
        queue: &crate::focus_input::SharedFocusBindingQueue,
    ) {
        let Some(scene) = self.scenes.get_mut(&entity) else {
            return;
        };

        // Idents installed but no longer requested: detach + forget these.
        let dropped: Vec<(String, i32, i32)> = scene
            .input_bindings
            .keys()
            .filter(|k| !specs.iter().any(|s| &s.ident() == *k))
            .cloned()
            .collect();
        let needs_new = specs
            .iter()
            .any(|s| !scene.input_bindings.contains_key(&s.ident()));
        if dropped.is_empty() && !needs_new {
            return;
        }
        let Some(content) = scene.view.content() else {
            return;
        };

        // Detach dropped bindings from their element, then drop our refs. The
        // element name is the ident's first field; `remove_from` is a no-op if
        // the element vanished. Detaching before drop ensures the chord stops
        // firing immediately, not just when the scene tears down.
        for ident in dropped {
            if let Some(installed) = scene.input_bindings.remove(&ident)
                && let Some(element) = content.find_name(&ident.0)
            {
                installed.binding.remove_from(&element);
            }
        }

        for spec in specs {
            let ident = spec.ident();
            if scene.input_bindings.contains_key(&ident) {
                continue;
            }
            let Some(element) = content.find_name(&spec.name) else {
                warn!(
                    "NoesisFocusControl: binding x:Name {:?} not found in scene {:?}",
                    spec.name, scene.built_for_uri,
                );
                continue;
            };

            let queue_handle = queue.clone();
            let view = entity;
            let name = spec.name.clone();
            let key = spec.key;
            let modifiers = spec.modifiers;
            // Fire-always command: pushes the chord onto the shared queue.
            let command = Command::new(move |_param| {
                queue_handle.push(view, name.clone(), key, modifiers);
            });

            let Some(binding) = KeyBinding::new(&command, spec.key, spec.modifiers) else {
                warn!(
                    "NoesisFocusControl: could not build KeyBinding for {:?} (command not an ICommand?)",
                    spec.name,
                );
                continue;
            };
            if !binding.add_to(&element) {
                warn!(
                    "NoesisFocusControl: element {:?} is not a UIElement; binding skipped",
                    spec.name,
                );
                continue;
            }
            scene
                .input_bindings
                .insert(ident, InstalledKeyBinding { command, binding });
        }
    }

    /// Poll view `entity`'s focus predictions. For each `FocusPredict` returns
    /// `(from, direction, candidate, predicted_name, matches_expected)` when the
    /// answer changed since last frame (deduped against the per-scene snapshot).
    /// First poll after a watch is added always reports. `predicted_name` is the
    /// predicted element's actual `x:Name` (via
    /// `FrameworkElement::predict_focus_name`); `matches_expected` is `true` when
    /// that name equals the watch's `expect`. Mirrors `poll_dp_reads_for`.
    pub(crate) fn poll_focus_predictions_for(
        &mut self,
        entity: Entity,
        predicts: &[crate::focus_input::FocusPredict],
    ) -> Vec<(
        String,
        crate::focus_input::FocusNavigationDirection,
        bool,
        Option<String>,
        bool,
    )> {
        let mut changed = Vec::new();
        let Some(scene) = self.scenes.get_mut(&entity) else {
            return changed;
        };
        scene
            .predict_snapshots
            .retain(|k, _| predicts.iter().any(|p| &p.ident() == k));
        if predicts.is_empty() {
            return changed;
        }
        let Some(content) = scene.view.content() else {
            return changed;
        };
        for p in predicts {
            let Some(from) = content.find_name(&p.from) else {
                continue;
            };
            let candidate = from.predict_focus(p.direction).is_some();
            let predicted_name = from.predict_focus_name(p.direction);
            let matches_expected = match &p.expect {
                Some(expect) => predicted_name.as_deref() == Some(expect.as_str()),
                None => false,
            };
            let ident = p.ident();
            let snapshot = (candidate, predicted_name.clone(), matches_expected);
            if scene.predict_snapshots.get(&ident) == Some(&snapshot) {
                continue;
            }
            scene.predict_snapshots.insert(ident, snapshot);
            changed.push((
                p.from.clone(),
                p.direction,
                candidate,
                predicted_name,
                matches_expected,
            ));
        }
        changed
    }

    /// Poll the `Text` of each watched element in view `entity`, returning the
    /// `(x:Name, text)` pairs that changed since last frame (deduped against the
    /// per-scene snapshot). The first poll after a name is watched always
    /// reports (snapshot starts empty), so callers see the current value.
    pub(crate) fn poll_text_reads_for(
        &mut self,
        entity: Entity,
        watched: &[String],
    ) -> Vec<(String, String)> {
        let mut changed = Vec::new();
        let Some(scene) = self.scenes.get_mut(&entity) else {
            return changed;
        };
        scene
            .text_snapshots
            .retain(|k, _| watched.iter().any(|w| w == k));
        if watched.is_empty() {
            return changed;
        }
        let Some(content) = scene.view.content() else {
            return changed;
        };
        for name in watched {
            let Some(element) = content.find_name(name) else {
                continue;
            };
            let current = element.text().unwrap_or_default();
            if scene.text_snapshots.get(name) == Some(&current) {
                continue;
            }
            scene.text_snapshots.insert(name.clone(), current.clone());
            changed.push((name.clone(), current));
        }
        changed
    }

    /// Apply view `entity`'s desired generic-DP writes, keyed by
    /// `(x:Name, property)`. Missing names / type mismatches warn.
    pub(crate) fn apply_dp_for(
        &mut self,
        entity: Entity,
        desired: &HashMap<(String, String), crate::dp::DpValue>,
    ) {
        if desired.is_empty() {
            return;
        }
        let Some(scene) = self.scenes.get_mut(&entity) else {
            return;
        };
        let Some(content) = scene.view.content() else {
            return;
        };
        for ((name, property), value) in desired {
            let Some(mut element) = content.find_name(name) else {
                warn!(
                    "NoesisDp: x:Name {:?} not found in scene {:?}",
                    name, scene.built_for_uri,
                );
                continue;
            };
            if value.write_to(&mut element, property) {
                // Update the snapshot eagerly so the read pass doesn't emit a
                // phantom change for a write we just issued ourselves.
                scene
                    .dp_snapshots
                    .insert((name.clone(), property.clone()), value.clone());
            } else {
                warn!("NoesisDp: write to {name:?}.{property:?} failed (unknown property or type)");
            }
        }
    }

    /// Poll view `entity`'s watched DPs, returning `(name, property, value)`
    /// for each that changed since last frame (deduped against the per-scene
    /// snapshot). First poll after a watch is added always reports.
    pub(crate) fn poll_dp_reads_for(
        &mut self,
        entity: Entity,
        watched: &[crate::dp::DpWatch],
    ) -> Vec<(String, String, crate::dp::DpValue)> {
        let mut changed = Vec::new();
        let Some(scene) = self.scenes.get_mut(&entity) else {
            return changed;
        };
        scene.dp_snapshots.retain(|(name, property), _| {
            watched
                .iter()
                .any(|w| &w.name == name && &w.property == property)
        });
        if watched.is_empty() {
            return changed;
        }
        let Some(content) = scene.view.content() else {
            return changed;
        };
        for watch in watched {
            let Some(element) = content.find_name(&watch.name) else {
                continue;
            };
            let Some(current) = watch.kind.read_from(&element, &watch.property) else {
                continue;
            };
            let key = (watch.name.clone(), watch.property.clone());
            if scene.dp_snapshots.get(&key) == Some(&current) {
                continue;
            }
            scene.dp_snapshots.insert(key, current.clone());
            changed.push((watch.name.clone(), watch.property.clone(), current));
        }
        changed
    }

    /// Assign view `entity`'s desired `RenderTransform`s (`x:Name → spec`). Each
    /// spec becomes a `CompositeTransform` held at +1 in
    /// [`Self::transform_handles`] (the same object Noesis stores), so the poll
    /// can read it back. Missing names / non-`UIElement` targets warn.
    pub(crate) fn apply_transforms_for(
        &mut self,
        entity: Entity,
        desired: &HashMap<String, crate::transforms::TransformSpec>,
    ) {
        let Some(scene) = self.scenes.get_mut(&entity) else {
            return;
        };
        // Drop handles for names no longer requested; releasing each handle's +1
        // (Noesis still holds its own ref until the DP is overwritten / cleared).
        scene
            .transform_handles
            .retain(|k, _| desired.contains_key(k));
        if desired.is_empty() {
            return;
        }
        let Some(content) = scene.view.content() else {
            return;
        };
        for (name, spec) in desired {
            let Some(mut element) = content.find_name(name) else {
                warn!(
                    "NoesisTransform: x:Name {:?} not found in scene {:?}",
                    name, scene.built_for_uri,
                );
                continue;
            };
            let transform = CompositeTransform::new(spec.to_fields());
            if element.set_render_transform(&transform) {
                scene.transform_handles.insert(name.clone(), transform);
            } else {
                warn!(
                    "NoesisTransform: {name:?} has no RenderTransform (not a UIElement?) \
                     in scene {:?}",
                    scene.built_for_uri,
                );
            }
        }
    }

    /// Assign view `entity`'s desired `Transform3D`s (`x:Name → spec`). Each
    /// spec becomes a `CompositeTransform3D` held at +1 in
    /// [`Self::transform3d_handles`] (the same object Noesis stores), so the
    /// poll can read it back. Missing names / non-`UIElement` targets warn.
    /// Mirror of [`Self::apply_transforms_for`], but for `UIElement::Transform3D`
    /// rather than `RenderTransform`.
    pub(crate) fn apply_transforms3d_for(
        &mut self,
        entity: Entity,
        desired: &HashMap<String, crate::transforms3d::Transform3DSpec>,
    ) {
        let Some(scene) = self.scenes.get_mut(&entity) else {
            return;
        };
        // Drop handles for names no longer requested; releasing each handle's +1
        // (Noesis still holds its own ref until the DP is overwritten / cleared).
        scene
            .transform3d_handles
            .retain(|k, _| desired.contains_key(k));
        if desired.is_empty() {
            return;
        }
        let Some(content) = scene.view.content() else {
            return;
        };
        for (name, spec) in desired {
            let Some(mut element) = content.find_name(name) else {
                warn!(
                    "NoesisTransform3D: x:Name {:?} not found in scene {:?}",
                    name, scene.built_for_uri,
                );
                continue;
            };
            let transform = CompositeTransform3D::new(spec.to_fields());
            if element.set_transform3d(&transform) {
                scene.transform3d_handles.insert(name.clone(), transform);
            } else {
                warn!(
                    "NoesisTransform3D: {name:?} has no Transform3D (not a UIElement?) \
                     in scene {:?}",
                    scene.built_for_uri,
                );
            }
        }
    }

    /// Poll view `entity`'s named elements' live `Transform3D`s, returning
    /// `(name, spec)` for each that changed since last frame (deduped against the
    /// per-scene snapshot). A name only reports while the element's current
    /// `Transform3D` is the exact object we assigned (pointer identity), so the
    /// read-back is element-sourced proof the assignment took, not an echo of
    /// the component. First poll after assignment always reports. Mirror of
    /// [`Self::poll_transforms_for`].
    pub(crate) fn poll_transforms3d_for(
        &mut self,
        entity: Entity,
        names: &[&str],
    ) -> Vec<(String, crate::transforms3d::Transform3DSpec)> {
        use crate::transforms3d::Transform3DSpec;
        let mut changed = Vec::new();
        let Some(scene) = self.scenes.get_mut(&entity) else {
            return changed;
        };
        scene
            .transform3d_snapshots
            .retain(|name, _| names.contains(&name.as_str()));
        if names.is_empty() {
            return changed;
        }
        let Some(content) = scene.view.content() else {
            return changed;
        };
        for &name in names {
            let Some(handle) = scene.transform3d_handles.get(name) else {
                continue;
            };
            let Some(element) = content.find_name(name) else {
                continue;
            };
            // Read the element's live Transform3D; only trust it when it is the
            // very object we assigned (Noesis stores our pointer, no clone).
            let Some(live) = element.transform3d() else {
                continue;
            };
            if live.raw() != handle.raw() {
                continue;
            }
            let current = Transform3DSpec::from_fields(handle.get());
            if scene.transform3d_snapshots.get(name) == Some(&current) {
                continue;
            }
            scene
                .transform3d_snapshots
                .insert(name.to_string(), current);
            changed.push((name.to_string(), current));
        }
        changed
    }

    /// Assign view `entity`'s desired raw 3D matrix transforms (`x:Name → 12
    /// `Transform3` floats`). Each becomes a `MatrixTransform3D` held at +1 in
    /// [`Self::matrix_transform3d_handles`] (the same object Noesis stores), so
    /// the poll can read it back. Missing names / non-`UIElement` targets warn.
    /// Matrix analogue of [`Self::apply_transforms3d_for`]; both set the single
    /// `UIElement::Transform3D` DP, so a name given both kinds keeps whichever
    /// applied last.
    pub(crate) fn apply_matrix_transforms3d_for(
        &mut self,
        entity: Entity,
        desired: &HashMap<String, [f32; 12]>,
    ) {
        let Some(scene) = self.scenes.get_mut(&entity) else {
            return;
        };
        // Drop handles for names no longer requested; releasing each handle's +1.
        scene
            .matrix_transform3d_handles
            .retain(|k, _| desired.contains_key(k));
        if desired.is_empty() {
            return;
        }
        let Some(content) = scene.view.content() else {
            return;
        };
        for (name, matrix) in desired {
            let Some(mut element) = content.find_name(name) else {
                warn!(
                    "NoesisTransform3D(matrix): x:Name {:?} not found in scene {:?}",
                    name, scene.built_for_uri,
                );
                continue;
            };
            let transform = MatrixTransform3D::new(*matrix);
            if element.set_transform3d(&transform) {
                scene
                    .matrix_transform3d_handles
                    .insert(name.clone(), transform);
            } else {
                warn!(
                    "NoesisTransform3D(matrix): {name:?} has no Transform3D (not a UIElement?) \
                     in scene {:?}",
                    scene.built_for_uri,
                );
            }
        }
    }

    /// Poll view `entity`'s named elements' live raw 3D matrix transforms,
    /// returning `(name, matrix)` for each that changed since last frame (deduped
    /// against the per-scene snapshot). A name only reports while the element's
    /// current `Transform3D` is the exact `MatrixTransform3D` we assigned (pointer
    /// identity), so the read-back is element-sourced proof the assignment took.
    /// First poll after assignment always reports. Matrix analogue of
    /// [`Self::poll_transforms3d_for`].
    pub(crate) fn poll_matrix_transforms3d_for(
        &mut self,
        entity: Entity,
        names: &[&str],
    ) -> Vec<(String, [f32; 12])> {
        let mut changed = Vec::new();
        let Some(scene) = self.scenes.get_mut(&entity) else {
            return changed;
        };
        scene
            .matrix_transform3d_snapshots
            .retain(|name, _| names.contains(&name.as_str()));
        if names.is_empty() {
            return changed;
        }
        let Some(content) = scene.view.content() else {
            return changed;
        };
        for &name in names {
            let Some(handle) = scene.matrix_transform3d_handles.get(name) else {
                continue;
            };
            let Some(element) = content.find_name(name) else {
                continue;
            };
            // Trust the value only when the element's live Transform3D is the very
            // object we assigned (Noesis stores our pointer, no clone).
            let Some(live) = element.transform3d() else {
                continue;
            };
            if live.raw() != handle.raw() {
                continue;
            }
            let current = handle.get();
            if scene.matrix_transform3d_snapshots.get(name) == Some(&current) {
                continue;
            }
            scene
                .matrix_transform3d_snapshots
                .insert(name.to_string(), current);
            changed.push((name.to_string(), current));
        }
        changed
    }

    /// Paint view `entity`'s elements with the desired code-built brushes
    /// (`(x:Name, target) → spec`). Each spec is built into a fresh Noesis brush
    /// and assigned through the element's typed brush sugar; Noesis takes its own
    /// reference, so the Rust handle is dropped right after. Missing names warn;
    /// a target the element lacks (e.g. `Fill` on a `Border`) warns too.
    /// Called when the view's `NoesisBrushes` component changes.
    pub(crate) fn apply_brushes_for(
        &mut self,
        entity: Entity,
        desired: &HashMap<(String, crate::brushes::BrushTarget), crate::brushes::BrushSpec>,
    ) {
        use crate::brushes::{BrushSpec, BrushTarget};
        use noesis_runtime::brushes::{GradientStop, LinearGradientBrush, SolidColorBrush};
        use noesis_runtime::view::FrameworkElement;

        if desired.is_empty() {
            return;
        }
        let Some(scene) = self.scenes.get_mut(&entity) else {
            return;
        };
        let Some(content) = scene.view.content() else {
            return;
        };

        // Assign any `Brush` to `target`'s DP via the element's safe sugar.
        fn assign(
            target: BrushTarget,
            el: &mut FrameworkElement,
            brush: &impl noesis_runtime::brushes::Brush,
        ) -> bool {
            match target {
                BrushTarget::Background => el.set_background(brush),
                BrushTarget::Foreground => el.set_foreground(brush),
                BrushTarget::Fill => el.set_fill(brush),
                BrushTarget::Stroke => el.set_stroke(brush),
            }
        }

        for ((name, target), spec) in desired {
            let Some(mut element) = content.find_name(name) else {
                warn!(
                    "NoesisBrushes: x:Name {:?} not found in scene {:?}",
                    name, scene.built_for_uri,
                );
                continue;
            };
            let ok = match spec {
                BrushSpec::Solid(rgba) => {
                    let brush = SolidColorBrush::new(*rgba);
                    assign(*target, &mut element, &brush)
                }
                BrushSpec::LinearGradient { start, end, stops } => {
                    let mut brush = LinearGradientBrush::new();
                    brush.set_start_point(start[0], start[1]);
                    brush.set_end_point(end[0], end[1]);
                    for stop in stops {
                        brush.add_stop(GradientStop::new(stop.offset, stop.color));
                    }
                    assign(*target, &mut element, &brush)
                }
            };
            if !ok {
                warn!(
                    "NoesisBrushes: assigning {:?} to {name:?} failed (no such property on this element type)",
                    target.property(),
                );
            }
        }
    }

    /// Build view `entity`'s desired code-built styles (`x:Name → spec`) and
    /// assign each to its named element via `FrameworkElement::set_style`. Each
    /// spec becomes a fresh `Noesis::Style` (target type + setters + property
    /// triggers); Noesis takes its own reference, so the Rust handle is dropped
    /// right after. A `Style` is sealed on first apply, so rebuilding per change
    /// is correct. Missing names / unknown target types / unresolvable
    /// properties warn. Called when the view's `NoesisStyles` component changes.
    pub(crate) fn apply_styles_for(
        &mut self,
        entity: Entity,
        desired: &HashMap<String, crate::styles::StyleSpec>,
    ) {
        if desired.is_empty() {
            return;
        }
        let Some(scene) = self.scenes.get_mut(&entity) else {
            return;
        };
        let uri = scene.built_for_uri.clone();
        let Some(content) = scene.view.content() else {
            return;
        };

        for (name, spec) in desired {
            let Some(mut element) = content.find_name(name) else {
                warn!("NoesisStyles: x:Name {name:?} not found in scene {uri:?}");
                continue;
            };
            let Some(style) = build_noesis_style(spec, name, &uri) else {
                continue;
            };
            if !element.set_style(&style) {
                warn!("NoesisStyles: {name:?} is not a FrameworkElement in scene {uri:?}");
            }
        }
    }

    /// Build a `ResourceDictionary` from `entries` (code-built brushes + boxed
    /// scalar values) plus any parsed `merged_xaml` fragments, and install it as
    /// the process-global application resources (`GUI::SetApplicationResources`).
    /// Noesis takes its own reference, so the Rust dictionary handle drops right
    /// after. Returns the declared `entries` keys confirmed resolvable through
    /// the live application resources (sorted): the read-back the
    /// [`NoesisResources`](crate::resources::NoesisResources) bridge surfaces.
    /// Called from the `Sync` phase (before scene build) when the resource
    /// changes, so a scene's `{StaticResource}` can resolve at parse time.
    pub(crate) fn install_app_resources_from(
        &mut self,
        entries: &HashMap<String, crate::resources::ResourceEntry>,
        merged_xaml: &[String],
    ) -> Vec<String> {
        use crate::brushes::BrushSpec;
        use crate::resources::ResourceEntry;
        use noesis_runtime::brushes::{GradientStop, LinearGradientBrush, SolidColorBrush};
        use noesis_runtime::resources::{
            ResourceDictionary, application_resources_contains, set_application_resources,
        };

        let mut dict = ResourceDictionary::new();

        // Merge parsed dictionaries first; own entries added afterwards win on a
        // key collision (base entries take precedence over merged, per WPF).
        for xaml in merged_xaml {
            match ResourceDictionary::parse(xaml) {
                Some(merged) => {
                    if !dict.add_merged(&merged) {
                        warn!("NoesisResources: failed to merge a parsed ResourceDictionary");
                    }
                }
                None => warn!(
                    "NoesisResources: a merged_xaml fragment did not parse as a <ResourceDictionary>",
                ),
            }
        }

        for (key, entry) in entries {
            let ok = match entry {
                ResourceEntry::Value(value) => dict.add_boxed(key, &value.to_boxed()),
                ResourceEntry::Brush(BrushSpec::Solid(rgba)) => {
                    dict.add_brush(key, &SolidColorBrush::new(*rgba))
                }
                ResourceEntry::Brush(BrushSpec::LinearGradient { start, end, stops }) => {
                    let mut brush = LinearGradientBrush::new();
                    brush.set_start_point(start[0], start[1]);
                    brush.set_end_point(end[0], end[1]);
                    for stop in stops {
                        brush.add_stop(GradientStop::new(stop.offset, stop.color));
                    }
                    dict.add_brush(key, &brush)
                }
            };
            if !ok {
                warn!("NoesisResources: failed to add resource {key:?}");
            }
        }

        set_application_resources(&dict);

        // Confirm against the live global (now our dict) so the read-back proves
        // the install took, not just that we built the spec.
        let mut present: Vec<String> = entries
            .keys()
            .filter(|key| application_resources_contains(key))
            .cloned()
            .collect();
        present.sort();
        info!(
            "Installed Noesis application resources: {} entries, {} merged dicts, {} present",
            entries.len(),
            merged_xaml.len(),
            present.len(),
        );
        present
    }

    /// Poll view `entity`'s named elements' live `RenderTransform`s, returning
    /// `(name, spec)` for each that changed since last frame (deduped against the
    /// per-scene snapshot). A name only reports while the element's current
    /// `RenderTransform` is the exact object we assigned (pointer identity), so
    /// the read-back is element-sourced proof the assignment took, not an echo
    /// of the component. First poll after assignment always reports.
    pub(crate) fn poll_transforms_for(
        &mut self,
        entity: Entity,
        names: &[&str],
    ) -> Vec<(String, crate::transforms::TransformSpec)> {
        use crate::transforms::TransformSpec;
        let mut changed = Vec::new();
        let Some(scene) = self.scenes.get_mut(&entity) else {
            return changed;
        };
        scene
            .transform_snapshots
            .retain(|name, _| names.contains(&name.as_str()));
        if names.is_empty() {
            return changed;
        }
        let Some(content) = scene.view.content() else {
            return changed;
        };
        for &name in names {
            let Some(handle) = scene.transform_handles.get(name) else {
                continue;
            };
            let Some(element) = content.find_name(name) else {
                continue;
            };
            // Read the element's live RenderTransform; only trust it when it is
            // the very object we assigned (Noesis stores our pointer, no clone).
            let Some(live) = element.render_transform() else {
                continue;
            };
            if live.raw() != handle.raw() {
                continue;
            }
            let current = TransformSpec::from_fields(handle.get());
            if scene.transform_snapshots.get(name) == Some(&current) {
                continue;
            }
            scene.transform_snapshots.insert(name.to_string(), current);
            changed.push((name.to_string(), current));
        }
        changed
    }

    /// Poll view `entity`'s painted targets, returning `(name, target, readback)`
    /// for each whose live brush changed since last frame (deduped against the
    /// per-scene snapshot). A `SolidColorBrush` reports its exact color
    /// ([`BrushReadback::Solid`](crate::brushes::BrushReadback::Solid)); any other
    /// live brush (e.g. a gradient) reports
    /// [`BrushReadback::NonSolid`](crate::brushes::BrushReadback::NonSolid); a
    /// target with no brush at all (unpainted / failed assign) reports nothing.
    /// The read-back proves the assignment landed; first poll after a target is
    /// painted always reports.
    pub(crate) fn poll_brush_reads_for(
        &mut self,
        entity: Entity,
        desired: &HashMap<(String, crate::brushes::BrushTarget), crate::brushes::BrushSpec>,
    ) -> Vec<(
        String,
        crate::brushes::BrushTarget,
        crate::brushes::BrushReadback,
    )> {
        use crate::brushes::BrushReadback;
        let mut changed = Vec::new();
        let Some(scene) = self.scenes.get_mut(&entity) else {
            return changed;
        };
        scene.brush_snapshots.retain(|(name, property), _| {
            desired
                .keys()
                .any(|(n, t)| n == name && t.property() == property)
        });
        if desired.is_empty() {
            return changed;
        }
        let Some(content) = scene.view.content() else {
            return changed;
        };
        for (name, target) in desired.keys() {
            let Some(element) = content.find_name(name) else {
                continue;
            };
            let property = target.property();
            // Solid: read the exact color. Otherwise, if a brush is present at
            // all (non-null DP), it's a non-solid brush (e.g. a gradient), the
            // only gradient signal the unsafe-free crate can read. No brush ⇒
            // nothing landed ⇒ stay silent.
            let current = if let Some(color) = element.solid_brush_color(property) {
                BrushReadback::Solid(color)
            } else if element.get_component(property).is_some() {
                BrushReadback::NonSolid
            } else {
                continue;
            };
            let key = (name.clone(), property.to_string());
            if scene.brush_snapshots.get(&key) == Some(&current) {
                continue;
            }
            scene.brush_snapshots.insert(key, current);
            changed.push((name.clone(), *target, current));
        }
        changed
    }

    /// Poll view `entity`'s watched `<Image>` elements, returning `(name,
    /// readback)` for each whose resolved size / source presence changed since
    /// last frame (deduped against the per-scene snapshot). The read-back is
    /// element-sourced: `ActualWidth`/`ActualHeight` come from the live layout,
    /// which Noesis derives from the source's pixel size via our texture
    /// provider's `GetTextureInfo`. So once a staged bitmap resolves, a
    /// `Stretch="None"` element reports the bitmap's exact dimensions; an
    /// unresolvable source reports `[0.0, 0.0]`. First poll after a name is
    /// watched always reports.
    pub(crate) fn poll_image_reads_for(
        &mut self,
        entity: Entity,
        desired: &HashMap<String, crate::imaging::ImageBitmap>,
    ) -> Vec<(String, crate::imaging::ImageReadback)> {
        use crate::imaging::ImageReadback;
        let mut changed = Vec::new();
        let Some(scene) = self.scenes.get_mut(&entity) else {
            return changed;
        };
        scene
            .image_snapshots
            .retain(|name, _| desired.contains_key(name));
        if desired.is_empty() {
            return changed;
        }
        let Some(content) = scene.view.content() else {
            return changed;
        };
        for name in desired.keys() {
            let Some(element) = content.find_name(name) else {
                continue;
            };
            let current = ImageReadback {
                has_source: element.image_source().is_some(),
                actual_size: [
                    element.actual_width().unwrap_or(0.0),
                    element.actual_height().unwrap_or(0.0),
                ],
            };
            if scene.image_snapshots.get(name) == Some(&current) {
                continue;
            }
            scene.image_snapshots.insert(name.clone(), current);
            changed.push((name.clone(), current));
        }
        changed
    }

    /// Reapply per-frame tweakables that don't require a scene rebuild (the PPAA
    /// flag and the DPI scale). Called every frame before Noesis is driven.
    /// Cheap: a compare per knob; each FFI call only fires on change.
    fn apply_live_flags(&mut self, entity: Entity, config: &NoesisView) {
        let Some(scene) = self.scenes.get_mut(&entity) else {
            return;
        };
        let desired = flags_from(config);
        if desired != scene.applied_flags {
            scene.view.set_flags(desired);
            scene.applied_flags = desired;
        }
        // Exact dedup against the last-applied value (like `applied_flags`): the
        // caller already quantizes scale, so any difference is a real change.
        #[allow(clippy::float_cmp)]
        if config.scale != scene.applied_scale {
            scene.view.set_scale(config.scale);
            scene.applied_scale = config.scale;
        }
    }

    fn install_application_resources_if_needed(&mut self, config: &NoesisView) {
        if config.application_resources.is_empty() {
            return;
        }
        if self
            .loaded_app_resources_chain
            .as_ref()
            .is_some_and(|loaded| loaded == &config.application_resources)
        {
            return;
        }
        // Every URI in the chain must already be in the provider map: the
        // chain installer's `SetSource` calls fire synchronously and resolve
        // through the same provider.
        {
            let guard = self.shared_map.0.lock().expect("SharedXamlMap poisoned");
            for uri in &config.application_resources {
                if !guard.contains_key(uri) {
                    return; // wait for the registry to pick it up
                }
            }
        }
        if noesis_runtime::gui::install_app_resources_chain(&config.application_resources) {
            info!(
                "Installed Noesis application resources chain ({} entries): {:?}",
                config.application_resources.len(),
                config.application_resources,
            );
            self.loaded_app_resources_chain = Some(config.application_resources.clone());
        } else {
            warn!(
                "install_app_resources_chain returned false for {:?}",
                config.application_resources,
            );
        }
    }

    /// Apply a batch of queued input events onto the live View. No-op when
    /// the scene hasn't been built yet; events are lost in that case, which
    /// is fine: pre-scene input targets nothing.
    fn apply_input(&mut self, events: &[crate::input::NoesisInputEvent]) {
        // Input routes to the single primary view; multi-view routing (which
        // view owns the pointer) isn't implemented yet.
        let Some(scene) = self.scenes.values_mut().next() else {
            return;
        };
        use crate::input::NoesisInputEvent as E;
        for ev in events {
            match *ev {
                E::MouseMove { x, y } => {
                    let _ = scene.view.mouse_move(x, y);
                }
                E::MouseButton {
                    down: true,
                    x,
                    y,
                    button,
                } => {
                    let _ = scene.view.mouse_button_down(x, y, button);
                }
                E::MouseButton {
                    down: false,
                    x,
                    y,
                    button,
                } => {
                    let _ = scene.view.mouse_button_up(x, y, button);
                }
                E::MouseWheel { x, y, delta } => {
                    let _ = scene.view.mouse_wheel(x, y, delta);
                }
                E::Scroll {
                    x,
                    y,
                    value,
                    horizontal: false,
                } => {
                    let _ = scene.view.scroll(x, y, value);
                }
                E::Scroll {
                    x,
                    y,
                    value,
                    horizontal: true,
                } => {
                    let _ = scene.view.hscroll(x, y, value);
                }
                E::TouchDown { x, y, id } => {
                    let _ = scene.view.touch_down(x, y, id);
                }
                E::TouchMove { x, y, id } => {
                    let _ = scene.view.touch_move(x, y, id);
                }
                E::TouchUp { x, y, id } => {
                    let _ = scene.view.touch_up(x, y, id);
                }
                E::KeyDown(k) => {
                    let _ = scene.view.key_down(k);
                }
                E::KeyUp(k) => {
                    let _ = scene.view.key_up(k);
                }
                E::Char(cp) => {
                    let _ = scene.view.char_input(cp);
                }
                E::Focus(true) => scene.view.activate(),
                E::Focus(false) => scene.view.deactivate(),
            }
        }
    }

    /// Drive one Noesis frame into the intermediate. Call during the
    /// `Render` schedule (before `NoesisNode::run`) so the intermediate
    /// is populated when the node blits.
    fn drive_frame(&mut self) {
        let time_secs = self.clock_origin.elapsed().as_secs_f64();
        // Split the borrow so each scene can use the shared registered device
        // while we iterate the scene map mutably.
        let Self {
            scenes,
            registered_device,
            ..
        } = self;
        if scenes.is_empty() {
            return;
        }
        let registered_device = registered_device
            .as_mut()
            .expect("registered_device dropped mid-frame");

        for scene in scenes.values_mut() {
            // Lazy renderer init: needs both the live View and the registered
            // device, so it happens on first frame here (not at scene creation).
            if !scene.renderer_initialized {
                let mut renderer = scene.view.renderer();
                renderer.init(registered_device);
                // Don't call renderer.shutdown() here; keep the init live.
                scene.renderer_initialized = true;
            }

            // Paint into this frame's back buffer (the one the render thread is
            // not currently blitting). `publish_intermediates` flips the index.
            registered_device
                .device_mut::<WgpuRenderDevice>()
                .set_onscreen_target(
                    scene.intermediates[scene.write_index].view.clone(),
                    scene.size.x,
                    scene.size.y,
                );

            let _changed = scene.view.update(time_secs);
            let mut renderer = scene.view.renderer();
            let _ = renderer.update_render_tree();
            let _ = renderer.render_offscreen();
            renderer.render(false, true);
            // WgpuRenderDevice auto-submits at end_onscreen_render, so the
            // intermediate is ready to sample by the time the graph runs.
        }
    }

    /// Publish each rendered scene's just-painted buffer onto its camera entity
    /// as a [`NoesisIntermediate`] component (the main→render handoff; only
    /// `Send + Sync` `TextureView`s cross the boundary), then flip `write_index`
    /// so the next frame paints the *other* buffer while the render thread blits
    /// this one.
    fn publish_intermediates(&mut self, commands: &mut Commands) {
        for (&entity, scene) in &mut self.scenes {
            if !scene.renderer_initialized {
                continue;
            }
            let published = &scene.intermediates[scene.write_index];
            commands.entity(entity).insert(NoesisIntermediate {
                view: published.view.clone(),
                sample_view: published.sample_view.clone(),
            });
            scene.write_index ^= 1;
        }
    }

    /// Render label template `xaml_uri` (with `fields` applied to named
    /// `TextBlock`/`TextBox` elements) into `target` at `size`, reusing one
    /// persistent offscreen rig view. Mirrors [`Self::drive_frame`] but points
    /// the device at the caller's texture instead of an intermediate, and never
    /// blits to a camera.
    ///
    /// Returns `false` when prerequisites aren't ready yet (the font fallback
    /// chain isn't installed, or the template's bytes haven't reached the XAML
    /// provider), so the caller can retry on a later frame.
    pub(crate) fn bake_into(
        &mut self,
        target: &wgpu::TextureView,
        xaml_uri: &str,
        size: UVec2,
        fields: &[(String, String)],
    ) -> bool {
        // Gate on fonts: the live scene installs the process-global fallback
        // chain once fonts load (see `install_font_fallbacks_if_needed`).
        // Baking before that point would rasterize invisible text.
        if !self.fallbacks_installed {
            return false;
        }

        let needs_build = self
            .bake_rig
            .as_ref()
            .is_none_or(|rig| rig.built_for_uri != xaml_uri);
        if needs_build {
            {
                let guard = self.shared_map.0.lock().expect("SharedXamlMap poisoned");
                if !guard.contains_key(xaml_uri) {
                    return false;
                }
            }
            self.teardown_bake_rig();
            let Some(element) = FrameworkElement::load(xaml_uri) else {
                warn!("bake_into: FrameworkElement::load({xaml_uri:?}) returned None");
                return false;
            };
            let mut view = View::create(element);
            view.set_size(size.x, size.y);
            view.set_scale(1.0);
            view.activate();
            self.bake_rig = Some(BakeRig {
                view,
                renderer_initialized: false,
                built_for_uri: xaml_uri.to_string(),
                size,
            });
        }

        let time_secs = self.clock_origin.elapsed().as_secs_f64();
        let registered_device = self
            .registered_device
            .as_mut()
            .expect("registered_device dropped mid-bake");
        let rig = self.bake_rig.as_mut().expect("rig built above");

        if let Some(content) = rig.view.content() {
            for (name, text) in fields {
                if let Some(mut element) = content.find_name(name) {
                    let _ = element.set_text(text);
                } else {
                    warn!("bake_into: x:Name {name:?} not found in {xaml_uri:?}");
                }
            }
        }
        if rig.size != size {
            rig.view.set_size(size.x, size.y);
            rig.size = size;
        }

        if !rig.renderer_initialized {
            let mut renderer = rig.view.renderer();
            renderer.init(registered_device);
            rig.renderer_initialized = true;
        }

        registered_device
            .device_mut::<WgpuRenderDevice>()
            .set_onscreen_target(target.clone(), size.x, size.y);

        let _ = rig.view.update(time_secs);
        let mut renderer = rig.view.renderer();
        let _ = renderer.update_render_tree();
        let _ = renderer.render_offscreen();
        renderer.render(false, true);
        true
    }

    fn teardown_bake_rig(&mut self) {
        let Some(mut rig) = self.bake_rig.take() else {
            return;
        };
        if rig.renderer_initialized {
            // Must run while the registered device is still alive.
            rig.view.renderer().shutdown();
        }
        drop(rig);
    }

    /// Tear down the scene for `entity` (if any), in Noesis's required order:
    /// `Renderer::shutdown` while the registered device is still alive, then the
    /// `View` drops. No-op when that entity has no live scene.
    fn teardown_scene(&mut self, entity: Entity) {
        // This view's view models / items collections / plain VMs outlive the
        // scene rebuild; mark them unbound so the next apply pass re-binds
        // against the new tree. All are keyed by (or filtered to) this entity.
        if let Some(entry) = self.view_models.get_mut(&entity) {
            entry.reset_attach();
        }
        for ((ent, _), binding) in &mut self.items_sources {
            if *ent == entity {
                binding.reset_bind();
            }
        }
        for ((ent, _), entry) in &mut self.plain_vms {
            if *ent == entity {
                entry.reset_attach();
            }
        }
        if let Some(entry) = self.command_hosts.get_mut(&entity) {
            entry.reset_attach();
        }
        for ((ent, _, _), entry) in &mut self.binding_entries {
            if *ent == entity {
                entry.reset_bind();
            }
        }
        let Some(mut scene) = self.scenes.remove(&entity) else {
            return;
        };
        if scene.renderer_initialized {
            // Must run while the registered device is still alive.
            scene.view.renderer().shutdown();
        }
        drop(scene);
    }

    /// Tear down every live scene (for app/render-state teardown). Same ordered
    /// shutdown as [`Self::teardown_scene`], applied to all entities.
    fn teardown_all_scenes(&mut self) {
        let entities: Vec<Entity> = self.scenes.keys().copied().collect();
        for entity in entities {
            self.teardown_scene(entity);
        }
    }
}

impl Drop for NoesisRenderState {
    fn drop(&mut self) {
        // Strict teardown order (Noesis demands it):
        //   1. scenes (Renderer::shutdown + View drop) FIRST: a `View` holds
        //      refs to the VM `ClassInstance`s / plain-VM instances it was given
        //      as `DataContext` and to the `ObservableCollection`s set as
        //      `ItemsSource`. Those refs must release before we drop the owners,
        //      or the owner's `ClassRegistration` unregisters the class while a
        //      live (View-held) instance still references it → use-after-free.
        //   2. view-models / items / plain-vms: now the last refs; safe to drop.
        //   3. bake rig, registered device + providers, then global `shutdown()`.
        // This `Drop` owns `shutdown()` (rather than a separate guard) so the
        // ordering is guaranteed: Bevy gives no drop order between two main-world
        // resources, and calling `shutdown()` early deadlocks/crashes.
        self.teardown_all_scenes();
        self.view_models.clear();
        self.items_sources.clear();
        self.plain_vms.clear();
        self.command_hosts.clear();
        self.binding_entries.clear();
        self.teardown_bake_rig();
        drop(self.registered_device.take());
        drop(self.registered_provider.take());
        drop(self.registered_fonts.take());
        drop(self.registered_textures.take());
        // Process-global integration callbacks: unregister (their `Drop`) while
        // the engine is still up; after `shutdown()` it would crash.
        self.integration_guards.clear();
        noesis_runtime::shutdown();
    }
}

// ─────────────────────────────────────────────────────────────────────────────
// Blit pipeline: stretch the intermediate onto ViewTarget
// ─────────────────────────────────────────────────────────────────────────────

pub(crate) struct BlitPipeline {
    pipeline: wgpu::RenderPipeline,
    bind_group_layout: wgpu::BindGroupLayout,
    sampler: wgpu::Sampler,
}

/// Premultiplied-alpha "over": `result = src.rgb + dst.rgb * (1 - src.a)`. Used
/// by *both* compositing nodes to composite the UI directly onto the camera's
/// cleared/finished `ViewTarget` (`LoadOp::Load`): transparent intermediate
/// texels (a == 0) leave the target intact, fully-opaque texels (a == 1)
/// overwrite it, and the fractional-alpha edges Noesis emits with
/// `RenderFlag::Ppaa` enabled blend correctly.
///
/// Noesis writes *premultiplied* alpha into the intermediate (its own
/// `BlendMode::SrcOver` is `One, OneMinusSrcAlpha`). Compositing premultiplied
/// here keeps the `ViewTarget` correct and independent of the clear colour, and
/// stays identical to a 1:1 overwrite whenever the target was cleared
/// transparent (dst == 0 ⇒ result == src). A plain overwrite (`blend = None`)
/// would discard the clear colour and let it bleed through PPAA edges.
const PREMULTIPLIED_OVER: wgpu::BlendState = wgpu::BlendState {
    color: wgpu::BlendComponent {
        src_factor: wgpu::BlendFactor::One,
        dst_factor: wgpu::BlendFactor::OneMinusSrcAlpha,
        operation: wgpu::BlendOperation::Add,
    },
    alpha: wgpu::BlendComponent {
        src_factor: wgpu::BlendFactor::One,
        dst_factor: wgpu::BlendFactor::OneMinusSrcAlpha,
        operation: wgpu::BlendOperation::Add,
    },
};

impl BlitPipeline {
    /// Build the compositing pipeline for `target_format`. Both render-graph
    /// nodes use the same [`PREMULTIPLIED_OVER`] blend so the UI composites
    /// correctly over whatever the camera left in its `ViewTarget`.
    fn new(device: &wgpu::Device, target_format: wgpu::TextureFormat) -> Self {
        let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
            label: Some("noesis blit shader"),
            source: wgpu::ShaderSource::Wgsl(Cow::Borrowed(BLIT_WGSL)),
        });

        let bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
            label: Some("noesis blit bgl"),
            entries: &[
                wgpu::BindGroupLayoutEntry {
                    binding: 0,
                    visibility: wgpu::ShaderStages::FRAGMENT,
                    ty: wgpu::BindingType::Texture {
                        sample_type: wgpu::TextureSampleType::Float { filterable: true },
                        view_dimension: wgpu::TextureViewDimension::D2,
                        multisampled: false,
                    },
                    count: None,
                },
                wgpu::BindGroupLayoutEntry {
                    binding: 1,
                    visibility: wgpu::ShaderStages::FRAGMENT,
                    ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
                    count: None,
                },
            ],
        });

        let sampler = device.create_sampler(&wgpu::SamplerDescriptor {
            label: Some("noesis blit sampler"),
            mag_filter: wgpu::FilterMode::Linear,
            min_filter: wgpu::FilterMode::Linear,
            ..Default::default()
        });

        let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
            label: Some("noesis blit pipeline layout"),
            bind_group_layouts: &[&bind_group_layout],
            push_constant_ranges: &[],
        });

        let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
            label: Some("noesis blit pipeline"),
            layout: Some(&pipeline_layout),
            vertex: wgpu::VertexState {
                module: &shader,
                entry_point: Some("vs_main"),
                compilation_options: wgpu::PipelineCompilationOptions::default(),
                buffers: &[],
            },
            primitive: wgpu::PrimitiveState::default(),
            depth_stencil: None,
            multisample: wgpu::MultisampleState::default(),
            fragment: Some(wgpu::FragmentState {
                module: &shader,
                entry_point: Some("fs_main"),
                compilation_options: wgpu::PipelineCompilationOptions::default(),
                targets: &[Some(wgpu::ColorTargetState {
                    format: target_format,
                    blend: Some(PREMULTIPLIED_OVER),
                    write_mask: wgpu::ColorWrites::ALL,
                })],
            }),
            multiview: None,
            cache: None,
        });

        Self {
            pipeline,
            bind_group_layout,
            sampler,
        }
    }

    fn bind_group(&self, device: &wgpu::Device, src: &wgpu::TextureView) -> wgpu::BindGroup {
        device.create_bind_group(&wgpu::BindGroupDescriptor {
            label: Some("noesis blit bg"),
            layout: &self.bind_group_layout,
            entries: &[
                wgpu::BindGroupEntry {
                    binding: 0,
                    resource: wgpu::BindingResource::TextureView(src),
                },
                wgpu::BindGroupEntry {
                    binding: 1,
                    resource: wgpu::BindingResource::Sampler(&self.sampler),
                },
            ],
        })
    }
}

const BLIT_WGSL: &str = r"
struct VertexOut {
    @builtin(position) pos: vec4<f32>,
    @location(0) uv: vec2<f32>,
}

@vertex
fn vs_main(@builtin(vertex_index) idx: u32) -> VertexOut {
    // Fullscreen triangle covering NDC [-1, 3] x [-1, 3] clipped to viewport.
    let x = f32((idx << 1u) & 2u);
    let y = f32(idx & 2u);
    var out: VertexOut;
    out.pos = vec4<f32>(x * 2.0 - 1.0, 1.0 - y * 2.0, 0.0, 1.0);
    out.uv  = vec2<f32>(x, y);
    return out;
}

@group(0) @binding(0) var src_texture: texture_2d<f32>;
@group(0) @binding(1) var src_sampler: sampler;

@fragment
fn fs_main(in: VertexOut) -> @location(0) vec4<f32> {
    return textureSample(src_texture, src_sampler, in.uv);
}
";

/// Test-only: run the production compositing blit (same [`BlitPipeline`] +
/// [`PREMULTIPLIED_OVER`] blend + `LoadOp::Load` the render-graph nodes use) of
/// `src` onto `target`. Lets integration tests exercise the real premultiplied
/// composite without standing up a render world. Not part of the public API.
#[doc(hidden)]
pub fn blit_composite_for_test(
    device: &wgpu::Device,
    encoder: &mut wgpu::CommandEncoder,
    src: &wgpu::TextureView,
    target: &wgpu::TextureView,
    target_format: wgpu::TextureFormat,
) {
    let blit = BlitPipeline::new(device, target_format);
    let bg = blit.bind_group(device, src);
    let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
        label: Some("blit_composite_for_test"),
        color_attachments: &[Some(wgpu::RenderPassColorAttachment {
            view: target,
            resolve_target: None,
            depth_slice: None,
            ops: wgpu::Operations {
                load: wgpu::LoadOp::Load,
                store: wgpu::StoreOp::Store,
            },
        })],
        depth_stencil_attachment: None,
        timestamp_writes: None,
        occlusion_query_set: None,
    });
    pass.set_pipeline(&blit.pipeline);
    pass.set_bind_group(0, &bg, &[]);
    pass.draw(0..3, 0..1);
}

#[derive(Resource, Default)]
pub(crate) struct BlitPipelineCache {
    /// Premultiplied-alpha "over" pipeline, one per encountered target format.
    /// Both the Core2d and Core3d nodes share it (see [`PREMULTIPLIED_OVER`]).
    over: HashMap<wgpu::TextureFormat, BlitPipeline>,
}

impl BlitPipelineCache {
    fn get(&self, format: wgpu::TextureFormat) -> Option<&BlitPipeline> {
        self.over.get(&format)
    }

    fn ensure(&mut self, device: &wgpu::Device, format: wgpu::TextureFormat) {
        self.over
            .entry(format)
            .or_insert_with(|| BlitPipeline::new(device, format));
    }
}

// ─────────────────────────────────────────────────────────────────────────────
// Systems (render app)
// ─────────────────────────────────────────────────────────────────────────────

/// Copy the [`XamlRegistry`] into the [`SharedXamlMap`] backing
/// [`BevyXamlProvider`]. Runs on the main thread (alongside the rest of the
/// Noesis driving pipeline) directly against the main-world registry.
#[allow(clippy::needless_pass_by_value)]
fn sync_xaml_provider_map(
    registry: Option<Res<XamlRegistry>>,
    state: Option<NonSend<NoesisRenderState>>,
) {
    let (Some(registry), Some(state)) = (registry, state) else {
        return;
    };
    state.shared_map().sync_from(&registry);
}

/// Copy the extracted [`FontRegistry`] into the [`SharedFontMap`] backing
/// [`BevyFontProvider`], then eagerly register any newly-arrived fonts
/// with the C++ `CachedFontProvider` cache. Mirrors
/// [`sync_xaml_provider_map`] for fonts but with the extra eager-register
/// step: fonts that finish loading after scene build get picked up here
/// before any later XAML lookup (or `FontFamily` change at runtime) tries
/// to resolve them.
#[allow(clippy::needless_pass_by_value)]
fn sync_font_provider_map(
    registry: Option<Res<FontRegistry>>,
    state: Option<NonSendMut<NoesisRenderState>>,
) {
    let (Some(registry), Some(mut state)) = (registry, state) else {
        return;
    };
    state.shared_fonts().sync_from(&registry);
    state.register_pending_fonts();
}

/// Copy the extracted [`ImageRegistry`] into the [`SharedImageMap`]
/// backing [`BevyTextureProvider`]. Mirrors the XAML / font sync
/// systems.
#[allow(clippy::needless_pass_by_value)]
fn sync_texture_provider_map(
    registry: Option<Res<ImageRegistry>>,
    state: Option<NonSend<NoesisRenderState>>,
) {
    let (Some(registry), Some(state)) = (registry, state) else {
        return;
    };
    state.shared_images().sync_from(&registry);
}

/// Ensure a live [`SceneInstance`] exists for each [`NoesisView`] entity once
/// its XAML bytes land in the shared map. Iterates the extracted view entities;
/// each drives its own scene keyed by entity.
#[allow(clippy::needless_pass_by_value)]
fn ensure_noesis_scene(
    views: Query<(Entity, &NoesisView)>,
    state: Option<NonSendMut<NoesisRenderState>>,
) {
    let Some(mut state) = state else {
        return;
    };
    // Reset the per-frame rebuild set before this pass repopulates it; the
    // Apply systems that follow read it within the same frame.
    state.scenes_built_this_frame.clear();
    for (entity, config) in &views {
        state.ensure_scene(entity, config);
    }
}

/// Re-apply each view's per-frame live settings (PPAA + DPI scale). Cheap:
/// compares against the last-applied value and only fires an FFI call on change.
#[allow(clippy::needless_pass_by_value)]
fn apply_live_scene_flags(
    views: Query<(Entity, &NoesisView)>,
    state: Option<NonSendMut<NoesisRenderState>>,
) {
    let Some(mut state) = state else {
        return;
    };
    for (entity, config) in &views {
        state.apply_live_flags(entity, config);
    }
}

/// Drain [`NoesisInputQueue`] onto the live View. Runs after
/// [`ensure_noesis_scene`] (so the scene exists) and before
/// [`drive_noesis_frame`] (so `View::Update` picks up the state these
/// events produced: hover highlights, button presses, etc.).
#[allow(clippy::needless_pass_by_value)]
fn apply_noesis_input(
    queue: Option<Res<crate::input::NoesisInputQueue>>,
    state: Option<NonSendMut<NoesisRenderState>>,
) {
    let (Some(queue), Some(mut state)) = (queue, state) else {
        return;
    };
    if queue.events.is_empty() {
        return;
    }
    state.apply_input(&queue.events);
}

/// Drive Noesis for the frame (layout, update render tree, render into each
/// view's intermediate), then publish each intermediate onto its camera entity
/// for the render world to blit. Runs last in the main-world driving chain.
#[allow(clippy::needless_pass_by_value)]
fn drive_noesis_frame(mut commands: Commands, state: Option<NonSendMut<NoesisRenderState>>) {
    let Some(mut state) = state else {
        return;
    };
    state.drive_frame();
    state.publish_intermediates(&mut commands);
}

/// Build a blit pipeline per-ViewTarget-format encountered. Cheap miss +
/// no-op on hit.
#[allow(clippy::needless_pass_by_value)]
fn prepare_noesis_blit(
    render_device: Res<RenderDevice>,
    targets: Query<&ViewTarget>,
    mut cache: ResMut<BlitPipelineCache>,
) {
    for target in &targets {
        cache.ensure(render_device.wgpu_device(), target.main_texture_format());
    }
}

// ─────────────────────────────────────────────────────────────────────────────
// NoesisNode: blits the intermediate into ViewTarget
// ─────────────────────────────────────────────────────────────────────────────

/// Render-graph label for the Core2d compositing node ([`NoesisNode`]). Used to
/// position the node between [`Node2d::MainTransparentPass`] and
/// [`Node2d::EndMainPass`] in [`Core2d`].
#[derive(Debug, Hash, PartialEq, Eq, Clone, RenderLabel)]
pub struct NoesisNodeLabel;

/// Marks the camera Noesis composites its UI onto. Add this to the camera
/// (`Camera2d` or `Camera3d`) whose final image the UI should overlay.
///
/// The blit runs *inside that camera's* render graph (Core2d or Core3d), after
/// its post-processing, so it composes cleanly with whatever the camera does
/// (HDR, image-based lighting, bloom, DOF, …). It does **not** rely on
/// a second window-targeting camera sharing the 3D camera's `ViewTarget`, which
/// breaks the moment the host adds standard 3D features. Tag exactly the
/// camera(s) you want the UI on; untagged cameras (e.g. offscreen effect passes)
/// are skipped.
#[derive(Component, ExtractComponent, Clone, Copy, Default, Debug)]
pub struct NoesisCamera;

/// The painted intermediate for a view, published onto the camera entity by the
/// main-world driving systems and `ExtractComponent`'d to the render world for
/// the blit. This is the **only** Noesis data that crosses to the render world;
/// `View`/`Renderer` stay pinned to the main thread (see `NoesisRenderState`).
/// Both fields are `wgpu::TextureView` (Arc-backed, `Send + Sync`), so the
/// cross-world hand-off is a cheap clone.
#[derive(Component, ExtractComponent, Clone)]
pub struct NoesisIntermediate {
    /// `Rgba8Unorm` raw view, sampled when the target is plain `Rgba8Unorm`.
    view: wgpu::TextureView,
    /// `Rgba8UnormSrgb` alias, sampled when the target is sRGB/HDR so the
    /// stored bytes round-trip through an sRGB→linear→sRGB decode/encode.
    sample_view: wgpu::TextureView,
}

/// Ordering for the main-world Noesis driving pipeline (all on the main thread).
/// Bridge plugins add their per-view apply systems to [`NoesisSet::Apply`] so
/// element writes land before the frame is driven. Phases run in listed order.
#[derive(SystemSet, Debug, Clone, PartialEq, Eq, Hash)]
pub enum NoesisSet {
    /// Copy asset registries into the provider-backing shared maps.
    Sync,
    /// Build / resize each [`NoesisView`]'s live scene.
    Ensure,
    /// Apply queued element writes + input onto the live views (bridges here).
    Apply,
    /// `View::Update` + `Renderer::Render` into each intermediate, then publish.
    Drive,
}

/// Shared blit body for both nodes. Premultiplied-alpha composites the UI over
/// whatever the camera left in its `ViewTarget` (`LoadOp::Load`): the Core2d
/// node runs on every 2D view, the Core3d node only on views tagged
/// [`NoesisCamera`]. Both use the same [`PREMULTIPLIED_OVER`] blend so PPAA's
/// fractional-alpha edges composite correctly instead of overwriting the clear
/// colour (see [`PREMULTIPLIED_OVER`]).
fn blit_noesis_ui(
    render_context: &mut RenderContext<'_>,
    intermediate: &NoesisIntermediate,
    view_target: &ViewTarget,
    world: &World,
) -> Result<(), NodeRunError> {
    let Some(cache) = world.get_resource::<BlitPipelineCache>() else {
        return Ok(());
    };
    let target_format = view_target.main_texture_format();
    let Some(blit) = cache.get(target_format) else {
        // prepare_noesis_blit should have created it; if it hasn't by
        // now we'd draw garbage so skip cleanly.
        return Ok(());
    };

    // Choose how to sample Noesis's sRGB-encoded intermediate bytes so the
    // composite is correct for the camera's ViewTarget colour space:
    //
    // - sRGB target (`Rgba8UnormSrgb`): the write path applies linear→sRGB,
    //   so sample through the sRGB alias (sRGB→linear on read). The encode
    //   undoes the decode and the stored bytes round-trip exactly.
    // - HDR/float target (`Rgba16Float`, …): values are *linear*
    //   scene-referred and get tonemapped + sRGB-encoded downstream on the
    //   way to the swapchain. So, like the sRGB case, the UI's sRGB bytes
    //   must be decoded to linear on read; otherwise they're treated as
    //   linear and encoded a second time, washing the UI out too bright.
    // - plain `Rgba8Unorm`: written and displayed raw, so sample the raw
    //   view and skip the gamma decode.
    let decode_srgb = target_format.is_srgb() || is_linear_float(target_format);
    let sample_view = if decode_srgb {
        &intermediate.sample_view
    } else {
        &intermediate.view
    };
    let bg = blit.bind_group(render_context.render_device().wgpu_device(), sample_view);

    let encoder = render_context.command_encoder();
    let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
        label: Some("NoesisNode blit"),
        color_attachments: &[Some(wgpu::RenderPassColorAttachment {
            view: view_target.main_texture_view(),
            resolve_target: None,
            depth_slice: None,
            ops: wgpu::Operations {
                load: wgpu::LoadOp::Load,
                store: wgpu::StoreOp::Store,
            },
        })],
        depth_stencil_attachment: None,
        timestamp_writes: None,
        occlusion_query_set: None,
    });
    pass.set_pipeline(&blit.pipeline);
    pass.set_bind_group(0, &bg, &[]);
    pass.draw(0..3, 0..1);
    drop(pass);

    Ok(())
}

/// Core2d compositing node: runs on **every** Core2d view. Premultiplied-alpha
/// composites the UI over the view's `ViewTarget`; when that target was cleared
/// transparent (a UI camera layered over a lower camera) the result is identical
/// to a 1:1 overwrite, and Bevy's multi-camera step folds it over the
/// lower camera.
#[derive(Default)]
pub struct NoesisNode;

impl ViewNode for NoesisNode {
    type ViewQuery = (&'static ViewTarget, &'static NoesisIntermediate);

    fn run<'w>(
        &self,
        _graph: &mut RenderGraphContext,
        render_context: &mut RenderContext<'w>,
        (view_target, intermediate): (&'w ViewTarget, &'w NoesisIntermediate),
        world: &'w World,
    ) -> Result<(), NodeRunError> {
        blit_noesis_ui(render_context, intermediate, view_target, world)
    }
}

/// Render-graph label for the Core3d overlay node ([`NoesisOverlayNode`]). Used
/// to position the node late in [`Core3d`] so the UI composites over the
/// camera's finished scene.
#[derive(Debug, Hash, PartialEq, Eq, Clone, RenderLabel)]
pub struct NoesisOverlayNodeLabel;

/// Core3d overlay node: runs only on views tagged [`NoesisCamera`], compositing
/// the UI premultiplied-alpha over the camera's finished scene. This is the
/// single-camera path that keeps working when the host adds IBL/bloom/DOF.
#[derive(Default)]
pub struct NoesisOverlayNode;

impl ViewNode for NoesisOverlayNode {
    type ViewQuery = (
        &'static ViewTarget,
        &'static NoesisCamera,
        &'static NoesisIntermediate,
    );

    fn run<'w>(
        &self,
        _graph: &mut RenderGraphContext,
        render_context: &mut RenderContext<'w>,
        (view_target, _marker, intermediate): (
            &'w ViewTarget,
            &'w NoesisCamera,
            &'w NoesisIntermediate,
        ),
        world: &'w World,
    ) -> Result<(), NodeRunError> {
        blit_noesis_ui(render_context, intermediate, view_target, world)
    }
}

// ─────────────────────────────────────────────────────────────────────────────
// Plugin
// ─────────────────────────────────────────────────────────────────────────────

/// Sub-plugin that wires Noesis into [`RenderApp`]: it registers the wgpu-backed
/// `RenderDevice`, installs the XAML/font/image providers, runs the main-world
/// driving pipeline ([`NoesisSet`]), and adds the blit nodes to [`Core2d`] and
/// [`Core3d`]. Added for you by the top-level `NoesisPlugin`; you don't add this
/// one directly.
pub struct NoesisRenderPlugin;

impl Plugin for NoesisRenderPlugin {
    fn build(&self, app: &mut App) {
        // The painted intermediate is the only Noesis data the render world sees;
        // it rides each camera entity. (`NoesisView` + the bridges stay
        // main-world; Noesis is thread-affine and lives on the main thread.)
        app.add_plugins((
            ExtractComponentPlugin::<NoesisIntermediate>::default(),
            ExtractComponentPlugin::<NoesisCamera>::default(),
        ));

        // Main-world driving pipeline: all on the main thread (the one thread
        // Bevy pins reliably), satisfying Noesis's thread-affinity contract.
        // Bridge plugins slot their per-view apply systems into `NoesisSet::Apply`.
        app.configure_sets(
            PostUpdate,
            (
                NoesisSet::Sync,
                NoesisSet::Ensure,
                NoesisSet::Apply,
                NoesisSet::Drive,
            )
                .chain(),
        )
        .add_systems(
            PostUpdate,
            (
                (
                    sync_xaml_provider_map,
                    sync_font_provider_map,
                    sync_texture_provider_map,
                )
                    .in_set(NoesisSet::Sync),
                ensure_noesis_scene.in_set(NoesisSet::Ensure),
                (apply_live_scene_flags, apply_noesis_input).in_set(NoesisSet::Apply),
                drive_noesis_frame.in_set(NoesisSet::Drive),
            ),
        );

        let Some(render_app) = app.get_sub_app_mut(RenderApp) else {
            warn!("RenderApp not present; NoesisRenderPlugin compositing is a no-op");
            return;
        };

        render_app
            .init_resource::<BlitPipelineCache>()
            .add_systems(Render, prepare_noesis_blit.in_set(RenderSystems::Prepare))
            // Core2d: premultiplied composite on any 2D view that has published
            // an intermediate (the `ViewQuery` gates on `NoesisIntermediate`).
            .add_render_graph_node::<ViewNodeRunner<NoesisNode>>(Core2d, NoesisNodeLabel)
            .add_render_graph_edges(
                Core2d,
                (
                    Node2d::MainTransparentPass,
                    NoesisNodeLabel,
                    Node2d::EndMainPass,
                ),
            )
            // Core3d: opt-in overlay on views tagged `NoesisCamera`, composited
            // after all 3D post-processing (tonemapping, bloom, the host's own
            // passes) and before upscaling, so it survives IBL/bloom/DOF and
            // needs no second window-targeting camera.
            .add_render_graph_node::<ViewNodeRunner<NoesisOverlayNode>>(
                Core3d,
                NoesisOverlayNodeLabel,
            )
            .add_render_graph_edges(
                Core3d,
                (
                    Node3d::EndMainPassPostProcessing,
                    NoesisOverlayNodeLabel,
                    Node3d::Upscaling,
                ),
            );
    }

    /// Create `NoesisRenderState` as a **main-world non-send resource**. Runs
    /// on the main thread (so the resource, and every Noesis handle it owns,
    /// is pinned there, satisfying thread-affinity) and after `RenderPlugin::finish`
    /// has populated the render sub-app's `RenderDevice`/`RenderQueue`, which we
    /// clone out (both are `Arc`-backed, `Send + Sync`).
    fn finish(&self, app: &mut App) {
        let Some(render_app) = app.get_sub_app(RenderApp) else {
            return;
        };
        let device = render_app
            .world()
            .resource::<RenderDevice>()
            .wgpu_device()
            .clone();
        let queue = (**render_app.world().resource::<RenderQueue>().0).clone();
        app.insert_non_send_resource(NoesisRenderState::new(device, queue));
    }
}

#[cfg(test)]
mod tests {
    use super::is_linear_float;
    use wgpu::TextureFormat;

    #[test]
    fn hdr_float_targets_decode_srgb() {
        // HDR camera ViewTargets store linear values (encoded downstream), so the
        // blit must treat them like sRGB targets and decode on sample.
        assert!(is_linear_float(TextureFormat::Rgba16Float));
        assert!(is_linear_float(TextureFormat::Rgba32Float));
        assert!(is_linear_float(TextureFormat::Rg11b10Ufloat));
    }

    #[test]
    fn noesis_view_requires_the_bridge_components() {
        use bevy::prelude::*;

        // Spawning a bare NoesisView must auto-attach every per-view bridge, so a
        // write set before the scene exists has somewhere to land. No Noesis
        // runtime needed: required components are pure ECS composition.
        let mut world = World::new();
        let view = world
            .spawn(super::NoesisView {
                xaml_uri: "x.xaml".to_string(),
                ..default()
            })
            .id();
        let e = world.entity(view);
        assert!(e.contains::<crate::text::NoesisText>());
        assert!(e.contains::<crate::visibility::NoesisVisibility>());
        assert!(e.contains::<crate::dp::NoesisDp>());
        assert!(e.contains::<crate::items::NoesisItems>());
        assert!(e.contains::<crate::focus::NoesisFocus>());
        assert!(e.contains::<crate::svg::NoesisSvg>());
        assert!(e.contains::<crate::events::NoesisClickWatch>());
        // The explicitly-constructed binding bridges are not auto-attached.
        assert!(!e.contains::<crate::viewmodel::NoesisVm>());
        assert!(!e.contains::<crate::commands::NoesisCommands>());
    }

    #[test]
    fn ldr_unorm_targets_sample_raw() {
        // Plain 8-bit targets are written/displayed raw; no gamma decode. (sRGB
        // targets are handled separately via TextureFormat::is_srgb.)
        assert!(!is_linear_float(TextureFormat::Rgba8Unorm));
        assert!(!is_linear_float(TextureFormat::Bgra8Unorm));
        assert!(!is_linear_float(TextureFormat::Rgba8UnormSrgb));
    }
}