lieui 0.1.0-alpha.2

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

use std::any::Any;
use std::rc::Rc;
use std::time::Instant;

use lieui_geom::{Rect, Size};

use lieui_geom::Point;

use crate::align::{AlignStats, align};
use crate::cmd::{CmdBuf, apply_cmds};
use crate::event::{Ctx, DispatchOutcome, Event, EventKind, EventView};
use crate::focus;
use crate::hit;
use crate::input::{self, InputEvent};
use crate::layout::{self, LayoutStats};
use crate::reactive::{Dirty, Runtime};
use crate::render::{RenderStats, Renderer};
use crate::track::{FocusState, NodeId, Track};
use crate::view::ViewBuf;
use crate::window::WindowId;

// ───────────────────────── 窗口配置 ─────────────────────────

/// 窗口配置(M4 会补 icon / position / 主题 / 字体等)
#[derive(Clone, Debug, PartialEq)]
pub struct WindowConfig {
    pub title: String,
    pub size: Size,
    pub min_size: Option<Size>,
    pub max_size: Option<Size>,
    /// 窗口底色(必须**不透明**:softbuffer 无 alpha 通道)。
    /// `None` = 跟随主题的 `window_background`(`rt.set_theme` 时随之变化);
    /// 显式设置的底色**优先于主题**(主题切换不再改它)。
    pub background: Option<lieui_geom::Color>,
    pub resizable: bool,
    pub decorations: bool,
    pub always_on_top: bool,
    /// 是否使用框架的 loading 遮罩(默认 `true`)。
    ///
    /// 关掉后 `Runtime::begin_busy` / `spawn_task_busy` 只维护状态,
    /// 遮罩由用户自己渲染(`Runtime::busy_items` 能拿到忙碌项)。
    pub auto_busy_overlay: bool,
    /// **整窗重绘模式**(默认 `false` = 用脏区局部重绘)。
    ///
    /// 打开后每帧都整窗重绘:脏区带来的收益(实测 1280×720 下局部重绘比整窗快
    /// 20~90×)全部放弃,换来"绝不会因为漏标脏区而留残影"的确定性。
    /// 用途:① 排查残影类 bug 时一键对照;② 对正确性要求高于性能的场景。
    pub full_repaint: bool,
}

impl Default for WindowConfig {
    fn default() -> Self {
        Self {
            title: "lieui".to_string(),
            size: Size::new(800.0, 600.0),
            min_size: None,
            max_size: None,
            background: None,
            resizable: true,
            decorations: true,
            always_on_top: false,
            auto_busy_overlay: true,
            full_repaint: false,
        }
    }
}

impl WindowConfig {
    pub fn background(mut self, c: lieui_geom::Color) -> Self {
        self.background = Some(c);
        self
    }

    /// 关闭框架的 loading 遮罩(自己渲染,见 `Runtime::busy_items`)
    pub fn auto_busy_overlay(mut self, on: bool) -> Self {
        self.auto_busy_overlay = on;
        self
    }

    /// 整窗重绘模式:放弃脏区带来的局部重绘收益,换取"绝不因漏标而残影"的确定性。
    ///
    /// 排查残影 bug 时的对照开关:若打开后残影消失,说明某处**漏标脏区**
    /// (自绘节点改状态没 `cx.damage(..)`、改了非 `Signal` 状态没 `invalidate`……)。
    pub fn full_repaint(mut self, on: bool) -> Self {
        self.full_repaint = on;
        self
    }
}

impl WindowConfig {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn title(mut self, t: impl Into<String>) -> Self {
        self.title = t.into();
        self
    }

    pub fn size(mut self, w: f32, h: f32) -> Self {
        self.size = Size::new(w, h);
        self
    }

    pub fn min_size(mut self, w: f32, h: f32) -> Self {
        self.min_size = Some(Size::new(w, h));
        self
    }

    pub fn max_size(mut self, w: f32, h: f32) -> Self {
        self.max_size = Some(Size::new(w, h));
        self
    }

    pub fn resizable(mut self, v: bool) -> Self {
        self.resizable = v;
        self
    }

    pub fn decorations(mut self, v: bool) -> Self {
        self.decorations = v;
        self
    }

    pub fn always_on_top(mut self, v: bool) -> Self {
        self.always_on_top = v;
        self
    }
}

/// 关闭请求的裁决(`GettingFocus` 那种"返回值可取消"风格,不用闭包)
#[derive(Copy, Clone, PartialEq, Eq, Debug, Default)]
pub enum CloseAction {
    #[default]
    Close,
    Cancel,
}

// ───────────────────────── 请求队列的便捷入口 ─────────────────────────

/// `Ctx` 请求关窗的载荷
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub struct CloseWindow(pub WindowId);

/// 在 `update()` / `on_tick()` 里请求开一个新窗口(真窗口由平台层在下一帧创建)。
///
/// ```ignore
/// fn on_tick(self: &Rc<Self>, cx: &mut Ctx, _now: Instant) {
///     if self.need_about.get() {
///         self.need_about.set(false);
///         lieui::app::open_window(cx, WindowConfig::new().title("关于").size(320.0, 200.0), About::default());
///     }
/// }
/// ```
pub fn open_window(cx: &Ctx, cfg: WindowConfig, vm: impl ViewModel) {
    cx.request::<(WindowConfig, Rc<dyn WindowView>)>((cfg, erased(Rc::new(vm))));
}

/// 请求关闭**当前**窗口(`CloseAction::Close` 之外的显式入口)
pub fn close_self(cx: &Ctx) {
    cx.request(CloseWindow(cx.window()));
}

// ───────────────────────── 外部数据 ─────────────────────────

/// 外部来源推给 UI 线程的数据(PTY 输出、后台任务结果……)。
///
/// 必须 `Send`:它要能穿过 `RepaintHandle`(`EventLoopProxy`)从别的线程回到 UI 线程。
pub struct ExternalData(Box<dyn Any + Send>);

impl ExternalData {
    pub fn new<T: Send + 'static>(v: T) -> Self {
        Self(Box::new(v))
    }

    pub fn downcast<T: 'static>(self) -> Option<T> {
        self.0.downcast::<T>().ok().map(|b| *b)
    }

    pub fn downcast_ref<T: 'static>(&self) -> Option<&T> {
        self.0.downcast_ref::<T>()
    }
}

impl std::fmt::Debug for ExternalData {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str("ExternalData(..)")
    }
}

// ───────────────────────── ViewModel ─────────────────────────

/// 窗口视图模型:**一个窗口一个实例**(不同窗口可以是不同类型,见 §3.14)。
///
/// 约束(§3.3):
/// 1. `view()` **不在每帧跑**——挂载一次 + 每次 `Signal` 变更后再跑一次;
/// 2. `view()` 必须**无副作用**,内部禁止 `Signal::set`(debug 下会 panic);
/// 3. 视图态(hover/滚动/编辑缓冲)不归 Model,由保留树持有。
pub trait ViewModel: 'static {
    /// 声明式:状态 → 描述。receiver 是 `&Rc<Self>`,让闭包能捕获 `Rc<Self>` 调自己的命令方法。
    fn view(self: &Rc<Self>, v: &mut ViewBuf);

    /// 外部数据(后台线程经 `RepaintHandle` 回到 UI 线程后调用)
    fn on_external(self: &Rc<Self>, _cx: &mut Ctx, _data: ExternalData) {}

    /// 关闭请求;返回 [`CloseAction::Cancel`] 可拦截
    fn on_close_request(self: &Rc<Self>, _cx: &mut Ctx) -> CloseAction {
        CloseAction::Close
    }

    /// 逐帧钩子(每帧都跑);注意 `view()` 不会因此重跑,只重绘由 `cx.damage(..)` 指定的区域
    fn on_tick(self: &Rc<Self>, _cx: &mut Ctx, _now: Instant) {}

    /// **动画帧**:只在上一帧调过 `cx.request_animation()` 时被调用(见 [`crate::timer`])。
    ///
    /// 想持续动画就在回调里再 `cx.request_animation()` 一次;停手即停帧(空闲零功耗)。
    /// `dt` = 距上一帧的时长(做按时间推进的动画用它,别假设固定步长)。
    /// 需要重绘时自己标脏(`cx.damage(node)`)——框架不会替你决定重绘范围。
    fn on_animation(self: &Rc<Self>, _cx: &mut Ctx, _now: Instant, _dt: std::time::Duration) {}
}

/// 对象安全的窗口视图。
///
/// `ViewModel::view` 的 receiver 是 `&Rc<Self>`,不能直接 `dyn`,所以加这一层薄擦除——
/// 换来"**不同窗口可以是不同的 `ViewModel` 类型**",以及 `App` 自身不带泛型。
pub trait WindowView {
    fn view_erased(&self, v: &mut ViewBuf);
    fn on_tick(&self, cx: &mut Ctx, now: Instant);
    fn on_animation(&self, cx: &mut Ctx, now: Instant, dt: std::time::Duration);
    fn on_external(&self, cx: &mut Ctx, data: ExternalData);
    fn on_close_request(&self, cx: &mut Ctx) -> CloseAction;
}

/// 把 `Rc<V>` 包装成 `dyn WindowView` 的适配器。
///
/// 为什么需要这层包装:Rust 的 unsizing 强转 `Rc<V> → Rc<dyn Trait>` 要求 `V: Trait + Sized`,
/// 而 `ViewModel::view` 的 receiver 是 `&Rc<Self>` —— 拿不到 `Rc` 就调不了它。
/// 所以真正的 `WindowView` 实现挂在**持有 `Rc<V>` 的适配器**上(多一次指针跳转,可忽略)。
struct VmAdapter<V: ViewModel>(Rc<V>);

impl<V: ViewModel> WindowView for VmAdapter<V> {
    fn view_erased(&self, v: &mut ViewBuf) {
        V::view(&self.0, v)
    }

    fn on_tick(&self, cx: &mut Ctx, now: Instant) {
        V::on_tick(&self.0, cx, now)
    }

    fn on_animation(&self, cx: &mut Ctx, now: Instant, dt: std::time::Duration) {
        V::on_animation(&self.0, cx, now, dt)
    }

    fn on_external(&self, cx: &mut Ctx, data: ExternalData) {
        V::on_external(&self.0, cx, data)
    }

    fn on_close_request(&self, cx: &mut Ctx) -> CloseAction {
        V::on_close_request(&self.0, cx)
    }
}

/// 把 `Rc<VM>` 擦除成窗口视图句柄。
///
/// 同一个 `Rc<VM>` 可以擦除多次给多个窗口(**共享一个 VM 实例**),
/// 也可以各建各的(每个窗口一个实例)。
pub fn erased<V: ViewModel>(vm: Rc<V>) -> Rc<dyn WindowView> {
    Rc::new(VmAdapter(vm))
}

// ───────────────────────── 帧统计 ─────────────────────────

/// 一帧做了/该做什么(测试与调试的观测点)
#[derive(Clone, Debug, Default, PartialEq)]
pub struct FrameStats {
    /// 本帧消费掉的脏标志
    pub dirty: Dirty,
    /// 是否重跑了 `view()` + `align`
    pub view_ran: bool,
    pub align: AlignStats,
    /// 本次重排统计(`ran == false` 表示本帧没有重排)
    pub layout: LayoutStats,
    /// 本帧被重新落位的锚定层数(popup / tooltip 跟随锚点)
    pub anchored_layers: usize,
    /// 跑完后**仍有**待重排(正常恒为 `false`)
    pub layout_pending: bool,
    /// 本帧是否需要重绘(消费脏区前的事实)
    pub paint_pending: bool,
    /// 待上屏(**M4** 由 softbuffer 消费;M3 只到"像素已就绪")
    pub present_pending: bool,
    /// 本帧累积的脏矩形(M3 用它决定行带;M4 会连同一起交给 `present_with_damage`)
    pub damage: Vec<Rect>,
    /// 整窗脏
    pub damage_all: bool,
    /// 本次展开 + 光栅化统计
    pub render: RenderStats,
}

impl FrameStats {
    /// 这一帧有没有实际干活
    pub fn is_idle(&self) -> bool {
        !self.view_ran && !self.layout.ran && !self.paint_pending && !self.present_pending
    }

    /// 本帧光栅化的像素数(基准/调试用)
    pub fn rasterized_pixels(&self) -> u64 {
        self.render.raster.pixels
    }
}

/// 一次指针输入的处理结果
#[derive(Clone, Debug, Default, PartialEq)]
pub struct PointerOutcome {
    /// 实际分发的事件条数(含 hover 进入/离开与合成的 `Tapped`)
    pub events: usize,
    /// 是否有任一处理器声明已处理
    pub handled: bool,
    /// 合成的点击目标
    pub tapped: Option<NodeId>,
    /// 是否触发了滚轮的框架默认滚动
    pub scrolled: bool,
}

// ───────────────────────── 窗口运行时 ─────────────────────────

/// 一个窗口的全部可变状态(每窗口一套)
pub struct WindowCtx {
    id: WindowId,
    cfg: WindowConfig,
    size: Size,
    track: Track,
    view_buf: ViewBuf,
    view: Rc<dyn WindowView>,
    last_align: AlignStats,
    renderer: Renderer,
    /// 底色是否由用户显式指定(true ⇒ 主题切换不再改窗口底色)
    explicit_background: bool,
    /// 光标闪烁:下一次翻转时刻(None = 没有聚焦的输入框,不需要动画)
    next_blink: Option<Instant>,
    /// 框架 tooltip 会话(悬停带 `tooltip` 的节点 → 计时 → 浮出;移开/按下 → 消失)
    tooltip: Option<TooltipSession>,
    /// loading 遮罩的 spinner 实例(跨帧保留;`Color` = 主题 accent,变了就重建)
    spinner: Option<(crate::geom::Color, crate::custom::CustomCell)>,
    /// 本窗口当前还有忙碌项(每帧刷新)——`next_wakeup` 靠它决定要不要继续定时唤醒
    /// (有遮罩就要 30fps 驱动 spinner,并给"最短可见时间"到点的收尾留出时机)
    has_busy: bool,
    /// 上一帧的时刻(算动画 `dt`)
    last_tick: Instant,
    /// 本窗口的**时钟**下次到期时刻(定时器 / 动画帧;`frame()` 里刷新)
    next_clock: Option<Instant>,
}

/// 悬停到 tooltip 浮出的延迟
pub const TOOLTIP_DELAY: std::time::Duration = std::time::Duration::from_millis(600);

/// 一个进行中的 tooltip 会话
struct TooltipSession {
    /// 带 tooltip 描述的节点(tooltip 层锚在它上面)
    target: NodeId,
    /// 悬停开始时刻(arm 计时起点)
    since: Instant,
    /// 已浮出的 tooltip 层根(None = 还在计时)
    layer: Option<crate::track::RootId>,
}

/// 光标闪烁周期
pub const BLINK_PERIOD: std::time::Duration = std::time::Duration::from_millis(530);

impl WindowCtx {
    pub fn new(id: WindowId, cfg: WindowConfig, view: Rc<dyn WindowView>, rt: &Runtime) -> Self {
        rt.register_window(id);
        // 首帧必须跑一次 view(),否则树是空的
        rt.mark(id, Dirty::VIEW);
        let size = cfg.size;
        // 底色:显式设置优先;否则跟随主题
        let background = cfg.background.unwrap_or_else(|| rt.theme().window_background);
        let explicit_background = cfg.background.is_some();
        let renderer = Renderer::new(size, background);
        Self {
            id,
            cfg,
            size,
            track: Track::new(),
            view_buf: ViewBuf::new(),
            view,
            last_align: AlignStats::default(),
            renderer,
            explicit_background,
            next_blink: None,
            tooltip: None,
            spinner: None,
            has_busy: false,
            last_tick: Instant::now(),
            next_clock: None,
        }
    }

    pub fn id(&self) -> WindowId {
        self.id
    }

    pub fn config(&self) -> &WindowConfig {
        &self.cfg
    }

    /// 客户区尺寸(布局的可用空间)
    pub fn size(&self) -> Size {
        self.size
    }

    /// 窗口尺寸变化(M4 由 winit 调用):整窗重排 + 整窗脏 + 重建 pixmap
    pub fn set_size(&mut self, rt: &Runtime, size: Size) {
        if self.size == size {
            return;
        }
        self.size = size;
        self.renderer.resize(size);
        self.track.mark_all_layout_dirty();
        rt.mark(self.id, Dirty::LAYOUT | Dirty::PAINT | Dirty::PRESENT);
    }

    /// 当前帧的图像(未渲染时是全零/旧帧)
    pub fn pixmap(&self) -> &vello_cpu::Pixmap {
        self.renderer.pixmap()
    }

    /// 换窗口底色(主题切换;调用方应同时 `mark_all_layout_dirty` + 整窗脏)
    pub fn set_background(&mut self, rt: &Runtime, color: lieui_geom::Color) {
        self.renderer.set_background(color);
        self.track.damage_whole_window();
        rt.mark(self.id, Dirty::PAINT | Dirty::PRESENT);
    }

    /// DPI 缩放变化(M4 由 winit 调用):只改光栅分辨率 + 整窗脏,**不动布局**。
    ///
    /// 注意:命中测试吃的是**逻辑**坐标,所以 winit 侧要把物理光标位置除以 scale。
    pub fn set_scale_factor(&mut self, rt: &Runtime, scale: f32) {
        if (self.renderer.scale() - scale).abs() < 1e-6 {
            return;
        }
        self.renderer.set_scale(scale);
        self.track.damage_whole_window();
        rt.mark(self.id, Dirty::PAINT | Dirty::PRESENT);
    }

    pub fn scale_factor(&self) -> f32 {
        self.renderer.scale()
    }

    /// 物理尺寸(pixmap / softbuffer surface 的尺寸)
    pub fn physical_size(&self) -> Size {
        self.renderer.physical_size()
    }

    pub fn track(&self) -> &Track {
        &self.track
    }

    pub fn track_mut(&mut self) -> &mut Track {
        &mut self.track
    }

    pub fn view_buf(&self) -> &ViewBuf {
        &self.view_buf
    }

    /// 最近一次 `align` 的统计
    pub fn last_align(&self) -> AlignStats {
        self.last_align
    }

    /// 内容根(挂载后才有)
    pub fn content_root(&self) -> Option<NodeId> {
        self.track.content_root().map(|r| r.node)
    }

    // ── 帧 ──

    /// 跑一帧:消费脏标志 → `view()`/`align` → **重排** → 取走脏区(M3 在这里光栅化 + 上屏)。
    pub fn frame(&mut self, rt: &Runtime) -> FrameStats {
        let dirty = rt.take_dirty(self.id);
        let mut st = FrameStats {
            dirty,
            ..Default::default()
        };

        // ⓪ 忙碌收尾:收掉"最短可见时间"已过的遮罩项(见 `task::set_busy_min_visible`)。
        // 放在帧首:快任务挂上遮罩后立刻结束的情况,也能保证遮罩被画出来过。
        rt.reap_busy(Instant::now());
        self.has_busy = rt.is_busy(self.id);

        // ⓪ 主题同步:全局主题变了 ⇒ 渲染器换 token 快照 + **整窗重绘**。
        // 窗口底色仅在"未显式指定"时跟随主题(`WindowConfig.background` 优先)。
        //
        // 为什么要整窗脏:换主题影响的不只是"自己有 paint 脏的节点"——窗口底色、以及画面里
        // 未被 token 覆盖的兜底色(光标/选区/滚动条/焦点框等)都会变;只靠既有脏矩形会留下
        // 旧底色的残块(此前 `set_theme` 只置 `Dirty::PAINT`,底色没被重画)。
        let theme = rt.theme();
        if self.renderer.options_mut().theme != theme {
            let bg_follows = !self.explicit_background;
            let opts = self.renderer.options_mut();
            opts.theme = theme;
            if bg_follows {
                opts.background = theme.window_background;
            }
            self.track.damage_whole_window();
        }

        // ① 响应式回路:任何 Signal 变更都只置 VIEW,这里统一消费一次(批处理免费)
        if dirty.contains(Dirty::VIEW) {
            rt.begin_view(self.id);
            // 主题快照先注入:DSL 在构造 widget 时把 token 烘焙进描述(设计 §3.10)
            self.view_buf.set_theme(rt.theme());
            self.view_buf.begin();
            self.view.view_erased(&mut self.view_buf);
            // 后台任务忙碌 ⇒ 追加框架 loading 遮罩层(声明式:忙碌项清空就不声明,
            // 下一帧 align 的 stale 清理会把旧层删掉)
            self.push_busy_overlay(rt);
            rt.end_view();

            st.view_ran = true;
            self.last_align = align(&mut self.track, &self.view_buf);
            st.align = self.last_align;
        }

        // ② 重排:只跑"边界集合"的子树(见 `layout::layout`)
        if dirty.contains(Dirty::LAYOUT) || self.track.has_layout_dirty() {
            st.layout = layout::layout(&mut self.track, self.size);
        }

        // ②.5 锚定层落位:popup / tooltip 要等布局给出锚点 rect 与自身尺寸才能定位。
        // 挪了层的旧 ∪ 新矩形已登记进脏区 ⇒ 本帧的渲染自然会覆盖。
        st.anchored_layers = layout::place_anchored_layers(&mut self.track, self.size);

        // ②.6 滚动变化:偏移真的变了(滚轮 / 拖滚动条 / ScrollTo)⇒ 给容器派发
        // `ScrollChanged`(Direct,带新偏移)。信号处理器据此重跑 view——虚拟列表靠它换窗。
        for sc_id in self.track.take_scroll_changes() {
            if !self.track.contains(sc_id) {
                continue;
            }
            let offset = self.track.scroll_offset(sc_id);
            let path = vec![sc_id];
            self.dispatch(rt, &path, &Event::Scroll { offset });
        }

        // ③ 光栅化:消费脏区(只重画受影响的行带,其余像素保留上一帧)。
        // `full_repaint` 模式:不看脏区,每帧整窗重绘(确定性优先)。
        st.layout_pending = self.track.has_layout_dirty();
        let (mut damage, mut damage_all) = self.track.take_damage();
        if self.cfg.full_repaint {
            damage.clear();
            damage_all = true;
        }
        st.damage = damage;
        st.damage_all = damage_all;
        st.paint_pending = dirty.contains(Dirty::PAINT) || st.damage_all || !st.damage.is_empty();
        if st.paint_pending {
            st.render = self.renderer.render(&self.track, &st.damage, st.damage_all);
        }

        // ④ 上屏:M4 由 softbuffer 消费(`present_with_damage`);M3 到此"像素已就绪"
        st.present_pending = dirty.contains(Dirty::PRESENT) || st.paint_pending;

        // ⑤ 刷新时钟:下一帧何时该醒(定时器 / 动画帧),供 `next_wakeup` 汇总
        self.next_clock = rt.next_deadline(self.id);

        st
    }

    // ── 动画(光标闪烁)──

    /// 翻转闪烁相位。**只在有键盘聚焦的输入框时动作**——没有聚焦输入框的窗口
    /// 永远不会被唤醒(空闲帧零功耗)。返回 true ⇒ 本帧有重绘义务。
    ///
    /// 平台层负责定时唤醒(`ControlFlow::WaitUntil`);打字会重置相位(光标常亮)。
    pub fn animate(&mut self, now: Instant) -> bool {
        // loading 遮罩:spinner 相位由挂钟决定 ⇒ 每个动画帧只需把卡片标脏重绘
        // (不重跑 `view()`,也不重排)
        if let Some(card) = self.busy_card() {
            self.track.mark_paint_dirty(card);
        }

        let focused_input = self
            .track
            .focused
            .filter(|f| self.track.input_is_active(*f))
            .is_some();

        if !focused_input {
            if self.track.blink_on {
                self.track.blink_on = false;
                self.next_blink = None;
                // 擦掉残留的光标
                if let Some(f) = self.track.focused {
                    self.track.mark_paint_dirty(f);
                }
                return true;
            }
            self.next_blink = None;
            return false;
        }

        match self.next_blink {
            None => {
                // 刚拿到焦点:光标先亮
                self.track.blink_on = true;
                self.next_blink = Some(now + BLINK_PERIOD);
                if let Some(f) = self.track.focused {
                    self.track.mark_paint_dirty(f);
                }
                true
            }
            Some(t) if now >= t => {
                self.track.blink_on = !self.track.blink_on;
                self.next_blink = Some(now + BLINK_PERIOD);
                if let Some(f) = self.track.focused {
                    self.track.mark_paint_dirty(f);
                }
                true
            }
            Some(_) => false,
        }
    }

    /// 下一次需要唤醒的时刻(平台层据此设置 `ControlFlow::WaitUntil`)。
    ///
    /// 汇总**所有**唤醒源,平台层不必知道有哪些动画:
    /// - 框架内部:光标闪烁、tooltip 计时、loading spinner;
    /// - 时钟([`crate::timer`]):定时器到期、动画帧(`next_clock`,`frame()` 里刷新)。
    ///
    /// 没有任何来源 ⇒ `None`(平台用 `ControlFlow::Wait`:空闲零功耗)。
    pub fn next_wakeup(&self) -> Option<Instant> {
        // 有遮罩(含"挂着等最短可见时间到点"的)⇒ 定时唤醒:驱动 spinner + 到点收尾
        let spin = self
            .has_busy
            .then(|| Instant::now() + crate::overlay::SPIN_PERIOD);
        let blink = match (self.next_blink, self.tooltip.as_ref()) {
            (Some(b), Some(t)) if t.layer.is_none() => Some(b.min(t.since + TOOLTIP_DELAY)),
            (_, Some(t)) if t.layer.is_none() => Some(t.since + TOOLTIP_DELAY),
            (b, _) => b,
        };
        [spin, blink, self.next_clock].into_iter().flatten().min()
    }

    // ── loading 遮罩(后台任务忙碌时由框架声明)──

    /// 声明本帧的忙碌遮罩(无忙碌项或窗口关闭了自动遮罩 ⇒ 什么都不做)
    fn push_busy_overlay(&mut self, rt: &Runtime) {
        if !self.cfg.auto_busy_overlay {
            return;
        }
        let items = rt.busy_items(self.id);
        if items.is_empty() {
            return;
        }
        // spinner 实例跨帧保留(主题 accent 变了才重建)
        let accent = rt.theme().accent;
        if self.spinner.as_ref().map(|(c, _)| *c) != Some(accent) {
            self.spinner = Some((
                accent,
                crate::custom::cell(crate::overlay::Spinner::new(accent)),
            ));
        }
        let spinner = self.spinner.as_ref().unwrap().1.clone();
        crate::overlay::push_busy_overlay(&mut self.view_buf, &items, spinner);
    }

    /// 遮罩卡片节点(loading 动画的标脏目标)。
    ///
    /// 结构固定:tag 层根 → 第一个子节点(卡片)。找不到 ⇒ `None`(没有遮罩)。
    fn busy_card(&self) -> Option<NodeId> {
        let root = self.track.root_by_tag(crate::overlay::BUSY_OVERLAY_TAG)?;
        self.track.children(root.node).first().copied()
    }

    // ── 事件 ──
    ///
    /// `path` 是命中链(`path[0]` 最外层、`path.last()` 目标),M1 由调用方给出(测试/无头场景),
    /// M2 起由命中测试产出。
    pub fn dispatch(
        &mut self,
        rt: &Runtime,
        path: &[NodeId],
        ev: &Event,
    ) -> DispatchOutcome {
        let mut cmds = CmdBuf::new();

        // ① 框架内置行为(先于用户处理器;直接拿 `&mut Track`,不占处理器槽位)
        //    传 `&Event` 而非摘要:IME 预编辑带字符串 payload
        crate::widgets::handle_route(&mut self.track, path, ev, &mut cmds);

        // ② 用户处理器(两段式:只读收集 → 调用;处理器只拿 `&mut Ctx`)
        let out = crate::event::dispatch(rt, self.id, &self.track, path, ev, &mut cmds);

        // ③ 落命令(借用释放后统一写树)
        if !cmds.is_empty() {
            let d = apply_cmds(&mut self.track, cmds.as_slice());
            rt.mark(self.id, d);
        }

        // ④ 打字重置闪烁相位:输入期间光标保持常亮(500ms 内没有新输入才熄灭)
        if matches!(
            ev.kind(),
            EventKind::CharacterReceived | EventKind::KeyDown | EventKind::PointerPressed
        ) && self
            .track
            .focused
            .filter(|f| self.track.input_is_active(*f))
            .is_some()
        {
            self.track.blink_on = true;
            self.next_blink = Some(Instant::now() + BLINK_PERIOD);
        }
        out
    }

    // ── 命中 ──

    /// 命中链(纯函数,无副作用)
    pub fn hit(&self, p: Point) -> Vec<NodeId> {
        hit::hit_path(&self.track, p)
    }

    /// 命中目标(最深节点)
    pub fn hit_target(&self, p: Point) -> Option<NodeId> {
        hit::hit_test(&self.track, p)
    }

    // ── 指针输入 ──

    /// 一步指针输入:状态机 → 逐个分发 → 未被处理的滚轮走框架默认滚动。
    ///
    /// M4 的 winit 层只需把 `CursorMoved` / `MouseInput` / `MouseWheel` 翻译成 [`InputEvent`]。
    pub fn pointer(&mut self, rt: &Runtime, ev: InputEvent) -> PointerOutcome {
        let step = input::step(&mut self.track, ev);
        let mut outcome = PointerOutcome {
            events: step.events.len(),
            tapped: step.tapped,
            ..Default::default()
        };

        let mut wheel_path: Option<Vec<NodeId>> = None;
        for (path, e) in step.events {
            if e.kind() == EventKind::PointerWheelChanged {
                wheel_path = Some(path.clone());
            }
            let d = self.dispatch(rt, &path, &e);
            outcome.handled |= d.handled;
        }

        if let InputEvent::Wheel { delta, .. } = ev
            && !outcome.handled
            && let Some(path) = wheel_path
        {
            outcome.scrolled = input::default_wheel_scroll(&mut self.track, &path, delta);
        }

        // tooltip 会话跟随 hover:命中链变了 ⇒ 重新定位目标(移开/按下 ⇒ 关闭)
        if step.hover_changed || matches!(ev, InputEvent::Down { .. }) {
            self.sync_tooltip();
        }

        outcome
    }

    // ── tooltip(框架自管层)──

    /// 根据当前 hover 链重算 tooltip 目标:从最深节点向上找第一个带 tooltip 的。
    /// 目标变了 ⇒ 关掉旧层、重新计时;没有目标 ⇒ 整个会话结束。
    fn sync_tooltip(&mut self) {
        let target = self
            .track
            .hover_path
            .iter()
            .rev()
            .copied()
            .find(|id| self.track.get(*id).is_some_and(|n| n.tooltip.is_some()));

        match (target, &mut self.tooltip) {
            (Some(t), Some(s)) if s.target == t => {} // 悬停目标没变:继续计时/保持
            (t, s) => {
                // 目标变了(或离开):关掉旧层
                if let Some(sess) = s
                    && let Some(rid) = sess.layer.take()
                {
                    self.track.remove_root(rid);
                }
                *s = t.map(|target| TooltipSession {
                    target,
                    since: Instant::now(),
                    layer: None,
                });
            }
        }
    }

    /// 已浮出的 tooltip 同步主题配色。
    ///
    /// tooltip 层是**框架自管层**(`align` 不会删除它,也不会重建内容),所以主题切换后
    /// 必须在这里补一次上色,否则它一直挂着旧主题的底色/文字色。
    fn sync_tooltip_theme(&mut self) {
        let theme = self.renderer.options().theme;
        let Some(rid) = self.tooltip.as_ref().and_then(|s| s.layer) else {
            return;
        };
        let Some(node) = self.track.root(rid).map(|r| r.node) else {
            return;
        };
        let changed = self.track.get(node).is_some_and(|n| {
            n.paint.background_color != Some(theme.tooltip_background)
                || n.text.color != theme.tooltip_text
        });
        if !changed {
            return;
        }
        if let Some(n) = self.track.get_mut(node) {
            n.paint.background_color = Some(theme.tooltip_background);
            n.text.color = theme.tooltip_text;
        }
        self.track.mark_paint_dirty(node);
    }

    /// 每帧推进 tooltip 会话(到时浮出;目标失效/文本消失 ⇒ 收回)。
    pub fn update_tooltip(&mut self, now: Instant) {
        self.sync_tooltip_theme();
        let theme = self.renderer.options().theme;
        let mut open: Option<(NodeId, String)> = None;
        let mut close: Option<crate::track::RootId> = None;

        if let Some(sess) = &mut self.tooltip {
            let alive = self
                .track
                .get(sess.target)
                .is_some_and(|n| n.tooltip.is_some());
            if !alive {
                if let Some(rid) = sess.layer.take() {
                    close = Some(rid);
                }
                self.tooltip = None;
            } else if sess.layer.is_none() && now >= sess.since + TOOLTIP_DELAY {
                open = self
                    .track
                    .get(sess.target)
                    .and_then(|n| n.tooltip.clone())
                    .map(|text| (sess.target, text));
            }
        }

        if let Some(rid) = close {
            self.track.remove_root(rid);
        }
        if let Some((target, text)) = open {
            let rid = self.open_tooltip_layer(&theme, target, text);
            if let Some(sess) = &mut self.tooltip {
                sess.layer = Some(rid);
            }
        }
    }

    /// 建 tooltip 层(锚到目标节点右侧,放不下自动翻到左侧/钳到视口)。
    fn open_tooltip_layer(
        &mut self,
        theme: &crate::theme::Theme,
        target: NodeId,
        text: String,
    ) -> crate::track::RootId {
        let node = self.track.create(crate::track::Kind::Text(text), None);
        if let Some(n) = self.track.get_mut(node) {
            n.paint.background_color = Some(theme.tooltip_background);
            n.paint.border_radius = 4.0;
            n.text.color = theme.tooltip_text;
            n.text.spec.font_size = 12.0;
            n.text.spec.wrap = false;
            // 按**墨迹盒**参与尺寸与居中:节点高 = 墨迹高 ⇒ 上下各 6px 的 padding 对称,
            // 字形视觉中心与卡片中心重合(行盒的 ascent/descent 不对称会让文本看着偏上)。
            n.text.spec.optical_align = true;
            n.layout = n
                .layout
                .clone()
                .padding_top(6.0)
                .padding_bottom(6.0)
                .padding_left(10.0)
                .padding_right(10.0);
        }
        let rid = self.track.add_framework_root(crate::track::Layer::Tooltip, None, node);
        if let Some(r) = self.track.root_mut(rid) {
            r.opts.anchor = Some(crate::track::Anchor {
                target: crate::track::AnchorTarget::Node(target),
                placement: crate::track::Placement::RightOf,
            });
        }
        rid
    }

    // ── 键盘 / 焦点 ──

    /// 键盘事件:发给焦点节点的祖先链(无焦点时发给内容根,冒泡到根)
    pub fn key(&mut self, rt: &Runtime, ev: Event) -> DispatchOutcome {
        let path = match self.track.focused {
            Some(id) => hit::path_to(&self.track, id),
            None => match self.content_root() {
                Some(root) => hit::path_to(&self.track, root),
                None => Vec::new(),
            },
        };
        if path.is_empty() {
            return DispatchOutcome::default();
        }
        self.dispatch(rt, &path, &ev)
    }

    /// Tab / Shift+Tab 焦点迁移(框架默认行为),并派发 `LostFocus` / `GotFocus`
    pub fn tab(&mut self, rt: &Runtime, forward: bool) -> Option<NodeId> {
        let target = focus::next_tab(&self.track, self.track.focused, forward);
        self.focus(rt, target, FocusState::Keyboard);
        target
    }

    /// 程序化聚焦(并派发 `LostFocus` / `GotFocus`)
    pub fn focus(&mut self, rt: &Runtime, target: Option<NodeId>, state: FocusState) {
        let change = focus::set_focus(&mut self.track, target, state);
        for (id, kind) in [
            (change.lost, EventKind::LostFocus),
            (change.got, EventKind::GotFocus),
        ] {
            if let Some(id) = id {
                let path = hit::path_to(&self.track, id);
                self.dispatch(rt, &path, &Event::simple(kind));
            }
        }
    }

    /// 逐帧钩子。`cx.damage(..)` 只标脏,不会重跑 `view()`。
    ///
    /// 每帧顺序(统一时钟,见 [`crate::timer`]):
    /// ① 到期定时器(回调在表外执行 ⇒ 回调里能安全地再建定时器)
    /// ② 若上一帧请求过动画帧 ⇒ `ViewModel::on_animation`(带 `dt`)
    /// ③ `ViewModel::on_tick`(框架既有钩子:光标闪烁相位等)
    pub fn tick(&mut self, rt: &Runtime, now: Instant) {
        // tooltip 会话推进(到时浮出 / 目标失效收回)
        self.update_tooltip(now);
        let dt = now.saturating_duration_since(self.last_tick);
        self.last_tick = now;
        let mut cx = Ctx::new(rt, self.id, EventView::tick());

        // ① 定时器:取走到期的(表外执行,避免回调里借用到同一张表)
        for mut timer in rt.take_due_timers(self.id, now) {
            if let Some(mut cb) = timer.take_cb() {
                cb(&mut cx);
                timer.cb = Some(cb); // 周期定时器要还回去
            }
            rt.reschedule_timer(timer, now);
        }

        // ② 动画帧(经典 RAF 语义:回调里再 `cx.request_animation()` 才继续)
        if rt.take_animation_request(self.id) {
            self.view.on_animation(&mut cx, now, dt);
        }

        // ③ 既有逐帧钩子
        self.view.on_tick(&mut cx, now);

        if !cx.cmds().is_empty() {
            let cmds = cx.take_cmds();
            let d = apply_cmds(&mut self.track, &cmds);
            rt.mark(self.id, d);
        }
    }

    /// 外部数据(后台线程 → UI 线程)
    ///
    /// 框架先消费自己的消息(任务进度 / 任务完成收尾,见 [`crate::task`]):
    /// - 进度消息 ⇒ 到此为止(驱动遮罩);
    /// - 任务完成 ⇒ 框架收尾(清任务表 + 收遮罩),**再**交给 `ViewModel::on_external`
    ///   取载荷。
    pub fn external(&mut self, rt: &Runtime, data: ExternalData) {
        if crate::task::on_task_message(rt, self.id, &data) {
            return;
        }
        let mut cx = Ctx::new(rt, self.id, EventView::external());
        self.view.on_external(&mut cx, data);
        if !cx.cmds().is_empty() {
            let cmds = cx.take_cmds();
            let d = apply_cmds(&mut self.track, &cmds);
            rt.mark(self.id, d);
        }
    }

    /// 关闭请求:`Cancel` 表示拦截
    pub fn close_requested(&mut self, rt: &Runtime) -> CloseAction {
        let mut cx = Ctx::new(rt, self.id, EventView::simple(EventKind::Unloaded));
        self.view.on_close_request(&mut cx)
    }
}

impl std::fmt::Debug for WindowCtx {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("WindowCtx")
            .field("id", &self.id)
            .field("title", &self.cfg.title)
            .field("nodes", &self.track.len())
            .finish()
    }
}

// ───────────────────────── App ─────────────────────────

/// 应用:窗口表 + 共享运行时。
///
/// **没有泛型参数**——窗口的 `ViewModel` 已被擦除成 `Rc<dyn WindowView>`。
#[derive(Default)]
pub struct App {
    rt: Runtime,
    next_window: u32,
    windows: Vec<WindowCtx>,
}

impl App {
    pub fn new(rt: Runtime) -> Self {
        Self {
            rt,
            next_window: 1,
            windows: Vec::new(),
        }
    }

    pub fn runtime(&self) -> Runtime {
        self.rt.clone()
    }

    /// 注册一个窗口。`vm` 可以是任意 `impl ViewModel`(**不同窗口类型可以不同**)。
    pub fn window<V: ViewModel>(&mut self, cfg: WindowConfig, vm: V) -> WindowId {
        self.window_erased(cfg, erased(Rc::new(vm)))
    }

    /// 以**已擦除的句柄**注册窗口。
    ///
    /// 用于两个场景:① 多窗口**共享同一个 VM 实例**(`erased(rc.clone())` 两次);
    /// ② 窗口视图由用户自己实现 `WindowView`(不经 `ViewModel`)。
    pub fn window_erased(&mut self, cfg: WindowConfig, view: Rc<dyn WindowView>) -> WindowId {
        let id = WindowId::new(self.next_window);
        self.next_window += 1;
        self.windows.push(WindowCtx::new(id, cfg, view, &self.rt));
        id
    }

    pub fn windows(&self) -> &[WindowCtx] {
        &self.windows
    }

    pub fn window_ctx(&self, id: WindowId) -> Option<&WindowCtx> {
        self.windows.iter().find(|w| w.id == id)
    }

    pub fn window_ctx_mut(&mut self, id: WindowId) -> Option<&mut WindowCtx> {
        self.windows.iter_mut().find(|w| w.id == id)
    }

    /// 逐窗口跑一帧(**与平台层一帧同构**:消费外部事件 → tick(定时器/动画/on_tick)
    /// → frame);返回每个窗口的 `FrameStats`。
    ///
    /// 顺带消费 [`Runtime::take_pending_external`](本地投递队列):**没有平台唤醒器**
    /// 时(无头测试、自己驱动帧)这就是"事件循环",后台任务/自定义事件的投递会自动落地;
    /// 有平台时队列恒空 ⇒ 零开销。
    pub fn frame_all(&mut self) -> Vec<(WindowId, FrameStats)> {
        let rt = self.rt.clone();
        for (w, data) in rt.take_pending_external() {
            if let Some(ctx) = self.windows.iter_mut().find(|c| c.id == w) {
                ctx.external(&rt, data);
            }
        }
        let now = Instant::now();
        self.windows
            .iter_mut()
            .map(|w| {
                w.tick(&rt, now);
                (w.id, w.frame(&rt))
            })
            .collect()
    }

    /// 关闭窗口(注销其脏标志,丢弃其保留树)。
    ///
    /// 顺带**取消该窗口的后台任务**并清掉它的忙碌项(否则线程会继续跑到结束、
    /// 结果却无人接收;见 [`crate::task`])。
    pub fn close_window(&mut self, id: WindowId) -> bool {
        let before = self.windows.len();
        self.windows.retain(|w| w.id != id);
        let removed = self.windows.len() != before;
        if removed {
            self.rt.cancel_tasks_of(id);
            self.rt.cancel_timers_of(id);
            self.rt.unregister_window(id);
        }
        removed
    }

    /// 立即以**已擦除句柄**开窗(`Ctx` 请求走 [`App::drain_requests`])
    pub fn open_window_erased(
        &mut self,
        cfg: WindowConfig,
        view: Rc<dyn WindowView>,
    ) -> WindowId {
        let id = WindowId::new(self.next_window);
        self.next_window += 1;
        self.windows
            .push(WindowCtx::new(id, cfg, view, &self.rt));
        id
    }

    // ── 请求队列(`Ctx::request` / `app::open_window` 写入)──

    /// 处理待处理请求:开窗 / 关窗。返回 `(新增的窗口, 被关闭的窗口)` 供平台层同步真实窗口。
    ///
    /// 无窗口环境(测试)也能用 —— 这正是把请求做成队列而不是直接建窗的原因。
    pub fn drain_requests(&mut self) -> (Vec<WindowId>, Vec<WindowId>) {
        let opens: Vec<(WindowConfig, Rc<dyn WindowView>)> =
            self.rt.requests().take::<(WindowConfig, Rc<dyn WindowView>)>();
        let closes: Vec<CloseWindow> = self.rt.requests().take::<CloseWindow>();

        let mut opened = Vec::with_capacity(opens.len());
        for (cfg, view) in opens {
            opened.push(self.open_window_erased(cfg, view));
        }
        let mut closed = Vec::new();
        for CloseWindow(id) in closes {
            if self.close_window(id) {
                closed.push(id);
            }
        }
        (opened, closed)
    }

    /// 还有待处理请求吗
    pub fn has_pending_requests(&self) -> bool {
        !self.rt.requests().is_empty()
    }

    /// 进入 winit 事件循环(阻塞直到退出)。**M4**。
    ///
    /// 需要窗口层(`platform`):它负责创建真实窗口、把 winit 事件翻译成
    /// [`InputEvent`] / [`Event`],并把 pixmap 用 `present_with_damage` 上屏。
    #[cfg(feature = "winit")]
    pub fn run(self) -> Result<(), Box<dyn std::error::Error>> {
        crate::platform::run(self, None)
    }

    /// 同上,但在进入循环前把 [`crate::platform::RepaintHandle`] 交给调用方
    /// (后台线程靠它唤醒 UI 线程)。
    #[cfg(feature = "winit")]
    pub fn run_with_handle(
        self,
        on_ready: impl FnOnce(crate::platform::RepaintHandle) + 'static,
    ) -> Result<(), Box<dyn std::error::Error>> {
        crate::platform::run(self, Some(Box::new(on_ready)))
    }

    /// 本帧有窗口需要干活吗(M4 用它决定是否 `request_redraw`)
    pub fn any_dirty(&self) -> bool {
        self.rt.windows().iter().any(|w| !self.rt.peek_dirty(*w).is_empty())
    }

    // 说明:`run()`(winit 事件循环)与 `Ctx::open_window`(动态开窗)在 **M4** 落地——
    // 它们需要真实的 winit 窗口与事件循环;M1 只做"纯逻辑的帧驱动",便于无头单测。
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::event::{
        Event, EventKind, KeyCode, Modifiers, NamedKey, PointerButton, PointerId,
    };
    use crate::reactive::{Signal, act1};
    use std::time::Duration;
    use crate::theme::Theme;
    use crate::track::{Kind, Layer, Placement};

    // ── 一个 counter ViewModel(就是 §九 示例的形态,去掉 winit 部分)──

    struct Counter {
        count: Signal<i32>,
    }

    impl Counter {
        fn inc(&self) {
            self.count.update(|v| *v += 1);
        }
    }

    impl ViewModel for Counter {
        fn view(self: &Rc<Self>, v: &mut ViewBuf) {
            v.column(|c| {
                c.gap(12.0);
                c.text("Counter").font_size(48.0);
                c.text(self.count.get().to_string()).font_size(72.0);
                c.row(|r| {
                    r.button("+1").on_tap(act(self, Self::inc));
                });
            });
        }
    }

    fn act<T: 'static>(vm: &Rc<T>, f: fn(&T)) -> impl Fn() + 'static {
        let me = Rc::clone(vm);
        move || f(&me)
    }

    fn find_text(t: &Track, needle: &str) -> Option<NodeId> {
        t.descendants(t.content_root()?.node)
            .into_iter()
            .find(|n| matches!(t.get(*n).map(|x| &x.kind), Some(Kind::Text(s)) if s == needle))
    }

    fn setup() -> (Runtime, App, Rc<Counter>, WindowId) {
        let rt = Runtime::new();
        let mut app = App::new(rt.clone());
        let vm = Rc::new(Counter {
            count: Signal::new(&rt, 0),
        });
        let id = app.window_erased(WindowConfig::new().title("Counter"), erased(vm.clone()));
        (rt, app, vm, id)
    }

    #[test]
    fn first_frame_mounts_the_tree() {
        let (_, mut app, _, id) = setup();
        let stats = app.frame_all();
        let (_, st) = &stats[0];

        assert!(st.view_ran);
        assert_eq!(
            st.align.created, 5,
            "column + 2 text + row + 1 button = 5 个节点"
        );
        assert!(st.damage_all, "首次挂载整窗脏");

        let w = app.window_ctx(id).unwrap();
        assert_eq!(w.track().len(), 5);
        assert!(find_text(w.track(), "0").is_some());
    }

    #[test]
    fn second_frame_is_idle_without_state_change() {
        let (_, mut app, _, _) = setup();
        app.frame_all();
        let stats = app.frame_all();
        let (_, st) = &stats[0];

        assert!(st.is_idle(), "无状态变化应完全空闲:{st:?}");
        assert_eq!(st.align.patched, 0);
        assert!(st.damage.is_empty() && !st.damage_all);
    }

    #[test]
    fn signal_change_reruns_view_and_patches_only_that_node() {
        let (_, mut app, vm, id) = setup();
        app.frame_all();

        vm.count.set(1); // 只置脏,不立即干活
        assert!(app.any_dirty());

        let stats = app.frame_all();
        let (_, st) = &stats[0];
        assert!(st.view_ran);
        assert_eq!(st.align.patched, 1, "只有一个文本节点变化");
        assert_eq!(st.align.created, 0);
        assert_eq!(st.align.destroyed, 0);

        let w = app.window_ctx(id).unwrap();
        assert!(find_text(w.track(), "1").is_some());
        assert!(find_text(w.track(), "0").is_none());
        // 节点身份保持(视图态不丢)
        assert_eq!(w.track().len(), 5);
    }

    #[test]
    fn button_closure_changes_state_and_next_frame_renders_it() {
        let (rt, mut app, vm, id) = setup();
        app.frame_all();

        // 模拟点击:命中链 = 内容根 → row → button(M2 会由命中测试给出)
        let w = app.window_ctx(id).unwrap();
        let root = w.content_root().unwrap();
        let row = w.track().children(root)[2];
        let button = w.track().children(row)[0];
        let path = vec![root, row, button];

        let out = app
            .window_ctx_mut(id)
            .unwrap()
            .dispatch(&rt, &path, &Event::Simple { kind: EventKind::Tapped });
        assert_eq!(out.invoked, 1, "只有按钮注册了处理器");
        assert_eq!(vm.count.get(), 1, "闭包直接改了 Signal");

        // 下一帧:重跑 view() → align → 只 patch 那一行文本
        let stats = app.frame_all();
        assert!(stats[0].1.view_ran);
        assert_eq!(stats[0].1.align.patched, 1);
        let w = app.window_ctx(id).unwrap();
        assert!(find_text(w.track(), "1").is_some());
    }

    #[test]
    fn handler_can_request_repaint_without_rerunning_view() {
        struct Once {
            count: Signal<i32>,
        }
        impl ViewModel for Once {
            fn view(self: &Rc<Self>, v: &mut ViewBuf) {
                v.column(|c| {
                    c.text(self.count.get().to_string())
                        .on_tap_with(|cx| cx.request_repaint());
                });
            }
        }

        let rt = Runtime::new();
        let mut app = App::new(rt.clone());
        let id = app.window(WindowConfig::new(), Once { count: Signal::new(&rt, 0) });
        app.frame_all();

        // 命中链:内容根 → 那个文本节点(处理器挂在文本节点上)
        let w = app.window_ctx(id).unwrap();
        let root = w.content_root().unwrap();
        let text = w.track().children(root)[0];
        let path = vec![root, text];

        let d0 = rt.peek_dirty(id);
        assert!(d0.is_empty(), "空闲窗口不该带脏标志");

        app.window_ctx_mut(id)
            .unwrap()
            .dispatch(&rt, &path, &Event::Simple { kind: EventKind::Tapped });

        let stats = app.frame_all();
        let st = &stats[0].1;
        assert!(!st.view_ran, "request_repaint 不应触发 view()");
        assert!(st.paint_pending);
    }

    #[test]
    fn two_windows_share_signals_but_keep_separate_trees() {
        let rt = Runtime::new();
        let shared = Signal::new(&rt, 7);

        struct Panel {
            v: Signal<i32>,
            label: &'static str,
        }
        impl ViewModel for Panel {
            fn view(self: &Rc<Self>, v: &mut ViewBuf) {
                v.column(|c| {
                    c.text(format!("{} = {}", self.label, self.v.get()));
                });
            }
        }

        let mut app = App::new(rt.clone());
        let a = app.window(
            WindowConfig::new().title("A"),
            Panel {
                v: shared.clone(),
                label: "A",
            },
        );
        let b = app.window(
            WindowConfig::new().title("B"),
            Panel {
                v: shared.clone(),
                label: "B",
            },
        );
        app.frame_all();

        assert!(find_text(app.window_ctx(a).unwrap().track(), "A = 7").is_some());
        assert!(find_text(app.window_ctx(b).unwrap().track(), "B = 7").is_some());

        // 改共享 signal:两个窗口都会重跑 view()(R1 保守传播)
        shared.set(8);
        let stats = app.frame_all();
        assert!(stats[0].1.view_ran && stats[1].1.view_ran);
        assert!(find_text(app.window_ctx(a).unwrap().track(), "A = 8").is_some());
        assert!(find_text(app.window_ctx(b).unwrap().track(), "B = 8").is_some());

        // 两棵树的节点数一致但互不影响
        assert_eq!(
            app.window_ctx(a).unwrap().track().len(),
            app.window_ctx(b).unwrap().track().len()
        );
    }

    #[test]
    fn closing_a_window_drops_its_flags() {
        let (rt, mut app, _, id) = setup();
        app.frame_all();
        assert!(app.close_window(id));
        assert!(app.window_ctx(id).is_none());
        assert!(rt.windows().is_empty());
        assert!(!app.close_window(id), "重复关闭返回 false");
    }

    #[test]
    fn tick_hook_runs_without_rerunning_view() {
        use std::cell::Cell;

        struct Anim {
            ticks: Rc<Cell<u32>>,
        }
        impl ViewModel for Anim {
            fn view(self: &Rc<Self>, v: &mut ViewBuf) {
                v.column(|c| {
                    c.text("t").key("t");
                });
            }
            fn on_tick(self: &Rc<Self>, cx: &mut Ctx, _now: Instant) {
                self.ticks.set(self.ticks.get() + 1);
                cx.damage_all();
            }
        }

        let rt = Runtime::new();
        let mut app = App::new(rt.clone());
        let ticks = Rc::new(Cell::new(0));
        let _ = app.window(WindowConfig::new(), Anim { ticks: ticks.clone() });
        app.frame_all();
        assert_eq!(ticks.get(), 1, "一帧 = 一次 on_tick");

        let stats = app.frame_all();
        assert_eq!(ticks.get(), 2, "每帧都跑 on_tick");
        let st = &stats[0].1;
        assert!(!st.view_ran, "on_tick 只重绘,不重跑 view()");
        assert!(st.paint_pending);
    }

    #[test]
    fn external_data_reaches_the_view_model() {
        struct Ext {
            got: Rc<std::cell::Cell<u32>>,
        }
        impl ViewModel for Ext {
            fn view(self: &Rc<Self>, v: &mut ViewBuf) {
                v.column(|c| {
                    c.text("x");
                });
            }
            fn on_external(self: &Rc<Self>, cx: &mut Ctx, data: ExternalData) {
                if let Some(n) = data.downcast::<u32>() {
                    self.got.set(n);
                }
                cx.damage_all();
            }
        }

        let rt = Runtime::new();
        let mut app = App::new(rt.clone());
        let got = Rc::new(std::cell::Cell::new(0));
        let id = app.window(WindowConfig::new(), Ext { got: got.clone() });
        app.frame_all();

        app.window_ctx_mut(id)
            .unwrap()
            .external(&rt, ExternalData::new(42u32));
        assert_eq!(got.get(), 42);
        assert!(app.frame_all()[0].1.paint_pending);
    }

    #[test]
    fn close_request_can_be_cancelled() {
        struct Guard;
        impl ViewModel for Guard {
            fn view(self: &Rc<Self>, v: &mut ViewBuf) {
                v.column(|c| {
                    c.text("g");
                });
            }
            fn on_close_request(self: &Rc<Self>, _cx: &mut Ctx) -> CloseAction {
                CloseAction::Cancel
            }
        }

        let rt = Runtime::new();
        let mut app = App::new(rt.clone());
        let id = app.window(WindowConfig::new(), Guard);
        app.frame_all();
        assert_eq!(
            app.window_ctx_mut(id).unwrap().close_requested(&rt),
            CloseAction::Cancel
        );
    }

    // ─────────────── M2:布局 / 命中 / 输入 端到端 ───────────────

    fn center(t: &Track, id: NodeId) -> Point {
        let r = crate::layout::rect_of(t, id);
        Point::new(r.x + r.width / 2.0, r.y + r.height / 2.0)
    }

    #[test]
    fn frame_runs_layout_then_goes_idle() {
        let (_, mut app, _, id) = setup();
        let first = app.frame_all()[0].1.clone();

        assert!(first.view_ran);
        assert!(first.layout.ran, "首帧必须重排");
        assert!(first.layout.nodes >= 5);
        assert!(!first.layout_pending, "跑完后不应再有重排义务");

        let w = app.window_ctx(id).unwrap();
        let root = w.content_root().unwrap();
        let rect = crate::layout::rect_of(w.track(), root);
        assert_eq!(rect.width, w.size().width, "内容根撑满窗口宽度");
        assert_eq!(rect.height, w.size().height);

        let second = app.frame_all()[0].1.clone();
        assert!(second.is_idle(), "无变化时第二帧应空闲:{second:?}");
    }

    #[test]
    fn resize_relayouts_the_whole_window() {
        let (rt, mut app, _, id) = setup();
        app.frame_all();

        app.window_ctx_mut(id)
            .unwrap()
            .set_size(&rt, Size::new(200.0, 150.0));
        let st = app.frame_all()[0].1.clone();
        assert!(st.layout.ran);
        assert!(st.layout.moved > 0, "尺寸变化应移动节点");
        assert!(st.damage_all);

        let w = app.window_ctx(id).unwrap();
        let root = w.content_root().unwrap();
        assert_eq!(crate::layout::rect_of(w.track(), root).width, 200.0);
    }

    #[test]
    fn click_reaches_the_button_through_hit_testing() {
        let (rt, mut app, vm, id) = setup();
        app.frame_all();

        let w = app.window_ctx(id).unwrap();
        let root = w.content_root().unwrap();
        let row = w.track().children(root)[2];
        let button = w.track().children(row)[0];
        let pos = center(w.track(), button);
        assert!(crate::layout::rect_of(w.track(), button).width > 0.0);

        // 用命中测试算出来的位置(不是手写 path)驱动输入
        let down = app.window_ctx_mut(id).unwrap().pointer(
            &rt,
            InputEvent::Down {
                pointer: PointerId(0),
                pos,
                button: PointerButton::Left,
            },
        );
        assert!(down.events > 0);

        let up = app.window_ctx_mut(id).unwrap().pointer(
            &rt,
            InputEvent::Up {
                pointer: PointerId(0),
                pos,
                button: PointerButton::Left,
            },
        );
        assert_eq!(up.tapped, Some(button), "命中测试 → 点击合成");
        assert_eq!(vm.count.get(), 1, "闭包已改 Signal");

        let st = app.frame_all()[0].1.clone();
        assert!(st.view_ran);
        assert_eq!(st.align.patched, 1, "只有那一行文本变了");
        let w = app.window_ctx(id).unwrap();
        assert!(find_text(w.track(), "1").is_some());
    }

    #[test]
    fn press_outside_the_button_then_move_away_does_not_click() {
        let (rt, mut app, vm, id) = setup();
        app.frame_all();

        let w = app.window_ctx(id).unwrap();
        let root = w.content_root().unwrap();
        let row = w.track().children(root)[2];
        let button = w.track().children(row)[0];
        let start = center(w.track(), button);
        let away = Point::new(5.0, 290.0);

        let w = app.window_ctx_mut(id).unwrap();
        w.pointer(&rt, InputEvent::Down { pointer: PointerId(0), pos: start, button: PointerButton::Left });
        let up = w.pointer(&rt, InputEvent::Up { pointer: PointerId(0), pos: away, button: PointerButton::Left });

        assert_eq!(up.tapped, None);
        assert_eq!(vm.count.get(), 0);
    }

    #[test]
    fn hover_follows_the_pointer_and_marks_damage() {
        let (rt, mut app, _, id) = setup();
        app.frame_all();
        let _ = app.frame_all(); // 清空挂载脏区

        let w = app.window_ctx(id).unwrap();
        let root = w.content_root().unwrap();
        let row = w.track().children(root)[2];
        let button = w.track().children(row)[0];
        let pos = center(w.track(), button);

        let w = app.window_ctx_mut(id).unwrap();
        let out = w.pointer(&rt, InputEvent::Move { pointer: PointerId(0), pos });
        assert!(out.events > 0);
        assert!(w.track().state(button).pointer_over);
        assert!(w.track().state(root).pointer_over, "整条链都置 pointer_over");

        // 只重绘,不重跑 view()
        let st = app.frame_all()[0].1.clone();
        assert!(!st.view_ran, "hover 不经过 view()");
        assert!(st.paint_pending);
        assert!(st.damage_all || !st.damage.is_empty());

        let w = app.window_ctx_mut(id).unwrap();
        w.pointer(&rt, InputEvent::Leave);
        assert!(!w.track().state(button).pointer_over);
    }

    #[test]
    fn tab_moves_focus_in_declaration_order() {
        struct Form;
        impl ViewModel for Form {
            fn view(self: &Rc<Self>, v: &mut ViewBuf) {
                v.column(|c| {
                    c.text("x").tab_stop(true);
                    c.text("y").tab_stop(true);
                });
            }
        }

        let rt = Runtime::new();
        let mut app = App::new(rt.clone());
        let id = app.window(WindowConfig::new(), Form);
        app.frame_all();

        let w = app.window_ctx(id).unwrap();
        let root = w.content_root().unwrap();
        let kids = w.track().children(root).to_vec();
        assert!(kids.len() >= 2);

        let w = app.window_ctx_mut(id).unwrap();
        // 走真焦点入口(内部 set_focus + LostFocus/GotFocus 派发)
        w.focus(&rt, Some(kids[0]), FocusState::Keyboard);
        assert_eq!(w.track().focused, Some(kids[0]));
        assert_eq!(w.track().get(kids[0]).unwrap().focus_state, FocusState::Keyboard);

        let next = w.tab(&rt, true);
        assert_eq!(next, Some(kids[1]));
        assert_eq!(w.track().focused, Some(kids[1]));
        assert_eq!(w.track().get(kids[0]).unwrap().focus_state, FocusState::Unfocused);

        // 循环回第一个
        assert_eq!(w.tab(&rt, true), Some(kids[0]));
        assert_eq!(w.tab(&rt, false), Some(kids[1]), "Shift+Tab 反向");
    }

    #[test]
    fn wheel_scrolls_the_container_when_no_handler_claims_it() {
        struct List {
            n: Signal<i32>,
        }
        impl ViewModel for List {
            fn view(self: &Rc<Self>, v: &mut ViewBuf) {
                v.column(|c| {
                    for i in 0..20 {
                        c.text(format!("row {i}")).font_size(20.0);
                    }
                });
                let _ = self.n.get();
            }
        }

        let rt = Runtime::new();
        let mut app = App::new(rt.clone());
        let id = app.window(
            WindowConfig::new().size(200.0, 100.0),
            List { n: Signal::new(&rt, 0) },
        );
        app.frame_all();

        // 手工把内容根变成滚动容器(M5 的 Scroll 组件会做这件事)
        {
            let w = app.window_ctx_mut(id).unwrap();
            let root = w.content_root().unwrap();
            w.track_mut().get_mut(root).unwrap().layout.overflow_scroll = true;
            w.track_mut().mark_all_layout_dirty();
        }
        let st = app.frame_all()[0].1.clone();
        assert!(st.layout.ran);

        let (root, content_h) = {
            let w = app.window_ctx(id).unwrap();
            let root = w.content_root().unwrap();
            (root, w.track().get(root).unwrap().content_size.height)
        };
        assert!(content_h > 100.0, "内容比视口高:{content_h}");

        let out = app.window_ctx_mut(id).unwrap().pointer(
            &rt,
            InputEvent::Wheel {
                pointer: PointerId(0),
                pos: Point::new(10.0, 50.0),
                delta: (0.0, -60.0), // 负 = 向下滚 ⇒ offset 增大
            },
        );
        assert!(out.scrolled, "无处理器认领 ⇒ 框架默认滚动");
        let w = app.window_ctx(id).unwrap();
        assert_eq!(w.track().scroll_offset(root), (0.0, 60.0));

        // 记一个子节点(row 5)的滚动前位置
        let y_before = {
            let w = app.window_ctx(id).unwrap();
            let t = w.track();
            let rows = t.children(root);
            crate::layout::rect_of(t, rows[5]).y
        };

        // 滚动 ⇒ 边界重排(子树按新偏移平移)+ 重绘:内容真的动
        let st = app.frame_all()[0].1.clone();
        assert!(st.layout.ran, "滚动触发边界重排(子树平移到新偏移)");
        assert!(st.paint_pending);
        let y_after = {
            let w = app.window_ctx(id).unwrap();
            let t = w.track();
            let rows = t.children(root);
            crate::layout::rect_of(t, rows[5]).y
        };
        assert!(
            (y_after - (y_before - 60.0)).abs() < 0.5,
            "内容随偏移上移 60:{y_before} → {y_after}"
        );
    }

    // ─────────────── M3:光栅化 / 脏区 ───────────────

    fn pixel(ctx: &WindowCtx, x: u16, y: u16) -> vello_cpu::color::PremulRgba8 {
        let pix = ctx.pixmap();
        pix.data()[usize::from(y) * usize::from(pix.width()) + usize::from(x)]
    }

    fn opaque(r: u8, g: u8, b: u8) -> vello_cpu::color::PremulRgba8 {
        vello_cpu::color::PremulRgba8::from_u8_array([r, g, b, 255])
    }

    #[test]
    fn frame_paints_background_and_content() {
        struct Paint;
        impl ViewModel for Paint {
            fn view(self: &Rc<Self>, v: &mut ViewBuf) {
                v.column(|c| {
                    c.container(|k| {
                        k.width(50.0);
                        k.height(50.0);
                        k.background(lieui_geom::Color::RED);
                    });
                });
            }
        }

        let rt = Runtime::new();
        let mut app = App::new(rt.clone());
        let id = app.window(WindowConfig::new().size(200.0, 120.0), Paint);
        let st = app.frame_all()[0].1.clone();
        assert!(st.render.raster.rasterized);
        assert!(st.render.ops >= 2, "底色 + 内容:{:?}", st.render);

        let ctx = app.window_ctx(id).unwrap();
        assert_eq!(pixel(ctx, 25, 25), opaque(255, 0, 0), "红块已画出");
        assert_eq!(pixel(ctx, 150, 100), opaque(245, 245, 245), "其余是窗口底色");
    }

    #[test]
    fn idle_frame_does_not_render() {
        let (_, mut app, _, id) = setup();
        app.frame_all();
        let st = app.frame_all()[0].1.clone();

        assert!(!st.paint_pending);
        assert!(!st.present_pending);
        assert!(!st.render.raster.rasterized, "空闲帧不碰像素");
        assert_eq!(st.rasterized_pixels(), 0);
        let _ = id;
    }

    #[test]
    fn damage_really_limits_repainting() {
        struct Two;
        impl ViewModel for Two {
            fn view(self: &Rc<Self>, v: &mut ViewBuf) {
                v.column(|c| {
                    c.container(|k| {
                        k.width(50.0);
                        k.height(50.0);
                        k.background(lieui_geom::Color::RED);
                    });
                });
            }
        }

        let rt = Runtime::new();
        let mut app = App::new(rt.clone());
        let id = app.window(WindowConfig::new().size(200.0, 120.0), Two);
        app.frame_all();
        assert_eq!(pixel(app.window_ctx(id).unwrap(), 25, 25), opaque(255, 0, 0));

        // 直接改颜色(不经过 align)并**只报告远处一小块脏区**
        {
            let w = app.window_ctx_mut(id).unwrap();
            let root = w.content_root().unwrap();
            let block = w.track().children(root)[0];
            w.track_mut().get_mut(block).unwrap().paint.background_color =
                Some(lieui_geom::Color::GREEN);
            w.track_mut().damage_rect(Rect::new(150.0, 90.0, 10.0, 10.0));
            rt.mark(id, Dirty::PAINT | Dirty::PRESENT);
        }

        let st = app.frame_all()[0].1.clone();
        assert!(st.paint_pending);
        assert!(st.render.raster.pixels < 200 * 120 / 5, "只画了脏区行带");
        // 脏区之外**保持上一帧**的红色 —— 这正是"局部光栅化"的证据
        assert_eq!(
            pixel(app.window_ctx(id).unwrap(), 25, 25),
            opaque(255, 0, 0),
            "未报告脏区的地方不应被重画"
        );

        // 整窗脏 ⇒ 这次才更新成绿色
        {
            let w = app.window_ctx_mut(id).unwrap();
            w.track_mut().damage_whole_window();
            rt.mark(id, Dirty::PAINT | Dirty::PRESENT);
        }
        app.frame_all();
        assert_eq!(
            pixel(app.window_ctx(id).unwrap(), 25, 25),
            opaque(0, 128, 0),
            "整窗脏后内容更新"
        );
    }

    #[test]
    fn click_only_repaints_a_band() {
        let rt = Runtime::new();
        let mut app = App::new(rt.clone());
        let vm = Rc::new(Counter {
            count: Signal::new(&rt, 0),
        });
        let id = app.window_erased(
            WindowConfig::new().size(400.0, 300.0),
            erased(Rc::clone(&vm)),
        );
        app.frame_all();

        let w = app.window_ctx(id).unwrap();
        let root = w.content_root().unwrap();
        let row = w.track().children(root)[2];
        let button = w.track().children(row)[0];
        let pos = center(w.track(), button);

        {
            let w = app.window_ctx_mut(id).unwrap();
            w.pointer(&rt, InputEvent::Down { pointer: PointerId(0), pos, button: PointerButton::Left });
            w.pointer(&rt, InputEvent::Up { pointer: PointerId(0), pos, button: PointerButton::Left });
        }
        assert_eq!(vm.count.get(), 1);

        let st = app.frame_all()[0].1.clone();
        assert!(st.view_ran && st.layout.ran);
        assert!(st.paint_pending);
        let total = 400u64 * 300;
        assert!(
            st.rasterized_pixels() < total / 5,
            "只重画了脏区:{} / {total}(batches={})",
            st.rasterized_pixels(),
            st.render.raster.batches
        );
        // 渲染确实产生了内容(不是空 pixmap)
        let ctx = app.window_ctx(id).unwrap();
        assert_eq!(pixel(ctx, 1, 299), opaque(245, 245, 245));
    }

    #[test]
    fn resize_rebuilds_the_pixmap_and_repaints() {
        let (rt, mut app, _, id) = setup();
        app.frame_all();
        {
            let ctx = app.window_ctx(id).unwrap();
            assert_eq!(ctx.pixmap().width(), 800);
            assert_eq!(ctx.pixmap().height(), 600);
        }

        app.window_ctx_mut(id)
            .unwrap()
            .set_size(&rt, Size::new(320.0, 240.0));
        let st = app.frame_all()[0].1.clone();
        assert!(st.damage_all);
        assert!(st.render.raster.rasterized);
        assert_eq!(st.render.raster.batches, 1, "整窗 ⇒ 一个批次");
        assert_eq!(st.render.raster.pixels, 320 * 240);

        let ctx = app.window_ctx(id).unwrap();
        assert_eq!(ctx.pixmap().width(), 320);
        assert_eq!(ctx.pixmap().height(), 240);
        assert_eq!(pixel(ctx, 300, 200), opaque(245, 245, 245));
    }

    // ─────────────── M4:窗口请求队列 / DPI ───────────────

    #[test]
    fn ctx_can_request_a_new_window() {
        struct Panel;
        impl ViewModel for Panel {
            fn view(self: &Rc<Self>, v: &mut ViewBuf) {
                v.column(|c| {
                    c.text("panel");
                });
            }
        }

        struct Root {
            open: Signal<bool>,
        }
        impl ViewModel for Root {
            fn view(self: &Rc<Self>, v: &mut ViewBuf) {
                v.column(|c| {
                    c.text("root");
                });
            }
            fn on_tick(self: &Rc<Self>, cx: &mut Ctx, _now: Instant) {
                if self.open.get() {
                    self.open.set(false);
                    crate::app::open_window(
                        cx,
                        WindowConfig::new().title("panel").size(120.0, 60.0),
                        Panel,
                    );
                }
            }
        }

        let rt = Runtime::new();
        let mut app = App::new(rt.clone());
        let vm = Rc::new(Root {
            open: Signal::new(&rt, false),
        });
        let root_id = app.window_erased(WindowConfig::new(), erased(Rc::clone(&vm)));
        app.frame_all();
        assert_eq!(app.windows().len(), 1);
        assert!(!app.has_pending_requests());

        // 请求开窗(队列化,不立即建窗)
        vm.open.set(true);
        app.window_ctx_mut(root_id)
            .unwrap()
            .tick(&rt, Instant::now());
        assert!(app.has_pending_requests());

        let (opened, closed) = app.drain_requests();
        assert_eq!(opened.len(), 1);
        assert!(closed.is_empty());
        assert_eq!(app.windows().len(), 2);

        // 新窗口照样能跑完整管线
        let stats = app.frame_all();
        let (_, st) = stats.iter().find(|(w, _)| *w == opened[0]).unwrap();
        assert!(st.view_ran && st.render.raster.rasterized);
        assert!(find_text(app.window_ctx(opened[0]).unwrap().track(), "panel").is_some());
    }

    #[test]
    fn ctx_can_close_its_own_window() {
        struct SelfClosing {
            done: Signal<bool>,
        }
        impl ViewModel for SelfClosing {
            fn view(self: &Rc<Self>, v: &mut ViewBuf) {
                v.column(|c| {
                    c.text("bye");
                });
            }
            fn on_tick(self: &Rc<Self>, cx: &mut Ctx, _now: Instant) {
                if self.done.get() {
                    crate::app::close_self(cx);
                }
            }
        }

        let rt = Runtime::new();
        let mut app = App::new(rt.clone());
        let id = app.window(
            WindowConfig::new(),
            SelfClosing {
                done: Signal::new(&rt, true),
            },
        );
        app.frame_all();
        app.window_ctx_mut(id)
            .unwrap()
            .tick(&rt, Instant::now());

        let (opened, closed) = app.drain_requests();
        assert!(opened.is_empty());
        assert_eq!(closed, vec![id]);
        assert!(app.window_ctx(id).is_none());
        assert_eq!(app.runtime().windows().len(), 0, "脏标志表也清掉了");
    }

    #[test]
    fn scale_factor_resizes_the_pixmap_without_relayout() {
        let (rt, mut app, _, id) = setup();
        app.frame_all();
        {
            let ctx = app.window_ctx(id).unwrap();
            assert_eq!(ctx.pixmap().width(), 800);
            assert_eq!(ctx.scale_factor(), 1.0);
        }

        app.window_ctx_mut(id)
            .unwrap()
            .set_scale_factor(&rt, 2.0);
        let st = app.frame_all()[0].1.clone();
        assert!(!st.layout.ran, "DPI 变化不吃布局");
        assert!(st.paint_pending);

        let ctx = app.window_ctx(id).unwrap();
        assert_eq!(ctx.pixmap().width(), 1600);
        assert_eq!(ctx.pixmap().height(), 1200);
        assert_eq!(ctx.size(), Size::new(800.0, 600.0), "逻辑尺寸不变");
        // 命中测试用逻辑坐标:内容根仍是 800×600 的逻辑矩形
        assert_eq!(app.window_ctx(id).unwrap().hit_target(Point::new(10.0, 10.0)).is_some(), true);
    }

    // ─────────────── M5:内置行为 + 双向绑定 ───────────────

    struct Controls {
        volume: Signal<f32>,
        agree: Signal<bool>,
    }

    impl ViewModel for Controls {
        fn view(self: &Rc<Self>, v: &mut ViewBuf) {
            v.column(|c| {
                c.gap(8.0);
                c.slider_bound(&self.volume, 0.0, 10.0);
                c.checkbox_bound(&self.agree);
            });
        }
    }

    fn controls() -> (Runtime, App, Rc<Controls>, WindowId, NodeId, NodeId) {
        let rt = Runtime::new();
        let mut app = App::new(rt.clone());
        let vm = Rc::new(Controls {
            volume: Signal::new(&rt, 0.0),
            agree: Signal::new(&rt, false),
        });
        let id = app.window_erased(
            WindowConfig::new().size(200.0, 120.0),
            erased(Rc::clone(&vm)),
        );
        app.frame_all();
        let (slider, checkbox) = {
            let w = app.window_ctx(id).unwrap();
            let root = w.content_root().unwrap();
            let kids = w.track().children(root);
            (kids[0], kids[1])
        };
        (rt, app, vm, id, slider, checkbox)
    }

    #[test]
    fn slider_drag_writes_back_the_bound_signal() {
        let (rt, mut app, vm, id, slider, _) = controls();
        let rect = crate::layout::rect_of(app.window_ctx(id).unwrap().track(), slider);
        assert_eq!(rect.width, 140.0, "slider 默认宽");

        let p = Point::new(rect.x + rect.width * 0.5, rect.y + rect.height * 0.5);
        let out = app.window_ctx_mut(id).unwrap().pointer(
            &rt,
            InputEvent::Down {
                pointer: PointerId(0),
                pos: p,
                button: PointerButton::Left,
            },
        );
        assert!(out.events > 0);
        assert!((vm.volume.get() - 5.0).abs() < 0.01, "拖到中点 ⇒ 5");
        {
            let w = app.window_ctx(id).unwrap();
            assert_eq!(w.track().captured_by(PointerId(0)), Some(slider), "拖拽期间捕获指针");
            assert!(matches!(
                w.track().get(slider).map(|n| &n.kind),
                Some(Kind::Slider { dragging: true, .. })
            ));
        }

        // 拖到右端(并越界一点)⇒ 钳到 max
        app.window_ctx_mut(id).unwrap().pointer(
            &rt,
            InputEvent::Move {
                pointer: PointerId(0),
                pos: Point::new(rect.right() + 50.0, p.y),
            },
        );
        assert_eq!(vm.volume.get(), 10.0);

        // 松开 ⇒ 结束拖拽 + 释放捕获
        app.window_ctx_mut(id).unwrap().pointer(
            &rt,
            InputEvent::Up {
                pointer: PointerId(0),
                pos: Point::new(rect.right(), p.y),
                button: PointerButton::Left,
            },
        );
        let w = app.window_ctx(id).unwrap();
        assert_eq!(w.track().captured_by(PointerId(0)), None);
        assert!(matches!(
            w.track().get(slider).map(|n| &n.kind),
            Some(Kind::Slider { dragging: false, .. })
        ));
    }

    #[test]
    fn slider_drag_and_the_next_view_do_not_fight() {
        let (rt, mut app, vm, id, slider, _) = controls();
        let rect = crate::layout::rect_of(app.window_ctx(id).unwrap().track(), slider);
        let p = Point::new(rect.x + rect.width * 0.25, rect.y + 5.0);

        let w = app.window_ctx_mut(id).unwrap();
        w.pointer(&rt, InputEvent::Down { pointer: PointerId(0), pos: p, button: PointerButton::Left });
        w.pointer(&rt, InputEvent::Up { pointer: PointerId(0), pos: p, button: PointerButton::Left });
        assert!((vm.volume.get() - 2.5).abs() < 0.01);

        // 立即写节点 + 写 signal ⇒ 下一帧 view() 产出的描述值与节点一致 ⇒ 零 patch
        let st = app.frame_all()[0].1.clone();
        assert_eq!(st.align.patched, 0, "不应产生「值回弹」式补丁:{st:?}");
        assert!(!st.layout.ran || st.layout.moved == 0);
    }

    #[test]
    fn unbound_slider_ignores_the_pointer() {
        struct Plain;
        impl ViewModel for Plain {
            fn view(self: &Rc<Self>, v: &mut ViewBuf) {
                v.column(|c| {
                    c.slider(0.5);
                });
            }
        }

        let rt = Runtime::new();
        let mut app = App::new(rt.clone());
        let id = app.window(WindowConfig::new().size(200.0, 120.0), Plain);
        app.frame_all();
        let slider = {
            let w = app.window_ctx(id).unwrap();
            w.track().children(w.content_root().unwrap())[0]
        };
        let rect = crate::layout::rect_of(app.window_ctx(id).unwrap().track(), slider);

        app.window_ctx_mut(id).unwrap().pointer(
            &rt,
            InputEvent::Down {
                pointer: PointerId(0),
                pos: Point::new(rect.right(), rect.y + 5.0),
                button: PointerButton::Left,
            },
        );
        let w = app.window_ctx(id).unwrap();
        assert!(
            matches!(w.track().get(slider).map(|n| &n.kind), Some(Kind::Slider { value, dragging, .. }) if (*value - 0.5).abs() < 1e-3 && !*dragging),
            "未绑定 ⇒ 框架不接管拖拽(desc 是唯一真相):{:?}",
            w.track().get(slider).map(|n| &n.kind)
        );
        assert_eq!(w.track().captured_by(PointerId(0)), None);
    }

    #[test]
    fn bound_checkbox_toggles_on_tap() {
        let (rt, mut app, vm, id, _, checkbox) = controls();
        let rect = crate::layout::rect_of(app.window_ctx(id).unwrap().track(), checkbox);
        let p = Point::new(rect.x + 5.0, rect.y + 5.0);

        let w = app.window_ctx_mut(id).unwrap();
        let down = w.pointer(&rt, InputEvent::Down { pointer: PointerId(0), pos: p, button: PointerButton::Left });
        let up = w.pointer(&rt, InputEvent::Up { pointer: PointerId(0), pos: p, button: PointerButton::Left });
        assert_eq!(down.tapped, None);
        assert_eq!(up.tapped, Some(checkbox));
        assert!(vm.agree.get(), "Tapped ⇒ 框架翻转绑定的 signal");

        // 再点一次翻回来
        let w = app.window_ctx_mut(id).unwrap();
        w.pointer(&rt, InputEvent::Down { pointer: PointerId(0), pos: p, button: PointerButton::Left });
        w.pointer(&rt, InputEvent::Up { pointer: PointerId(0), pos: p, button: PointerButton::Left });
        assert!(!vm.agree.get());
    }

    #[test]
    fn unbound_checkbox_is_left_to_user_handlers() {
        struct Plain {
            clicks: Rc<std::cell::Cell<u32>>,
        }
        impl ViewModel for Plain {
            fn view(self: &Rc<Self>, v: &mut ViewBuf) {
                let clicks = Rc::clone(&self.clicks);
                v.column(|c| {
                    c.checkbox(false).on_tap(move || clicks.set(clicks.get() + 1));
                });
            }
        }

        let rt = Runtime::new();
        let mut app = App::new(rt.clone());
        let clicks = Rc::new(std::cell::Cell::new(0));
        let id = app.window(
            WindowConfig::new().size(200.0, 120.0),
            Plain {
                clicks: Rc::clone(&clicks),
            },
        );
        app.frame_all();
        let cb = {
            let w = app.window_ctx(id).unwrap();
            w.track().children(w.content_root().unwrap())[0]
        };
        let rect = crate::layout::rect_of(app.window_ctx(id).unwrap().track(), cb);
        let p = Point::new(rect.x + 5.0, rect.y + 5.0);

        let w = app.window_ctx_mut(id).unwrap();
        w.pointer(&rt, InputEvent::Down { pointer: PointerId(0), pos: p, button: PointerButton::Left });
        w.pointer(&rt, InputEvent::Up { pointer: PointerId(0), pos: p, button: PointerButton::Left });

        assert_eq!(clicks.get(), 1, "用户处理器被调用");
        let w = app.window_ctx(id).unwrap();
        assert!(
            matches!(w.track().get(cb).map(|n| &n.kind), Some(Kind::Checkbox { checked: false })),
            "未绑定 ⇒ 框架不改状态"
        );
    }

    // ─────────────── M5:输入框(Input)───────────────

    struct Form {
        name: Signal<String>,
    }

    impl ViewModel for Form {
        fn view(self: &Rc<Self>, v: &mut ViewBuf) {
            v.column(|c| {
                c.input_bound(&self.name).placeholder("姓名");
            });
        }
    }

    fn form(initial: &str) -> (Runtime, App, Rc<Form>, WindowId, NodeId) {
        let rt = Runtime::new();
        let mut app = App::new(rt.clone());
        let vm = Rc::new(Form {
            name: Signal::new(&rt, initial.to_string()),
        });
        let id = app.window_erased(
            WindowConfig::new().size(240.0, 80.0),
            erased(Rc::clone(&vm)),
        );
        app.frame_all();
        let input = {
            let w = app.window_ctx(id).unwrap();
            w.track().children(w.content_root().unwrap())[0]
        };
        (rt, app, vm, id, input)
    }

    fn input_state(app: &App, id: WindowId, input: NodeId) -> (String, usize, usize, String) {
        let w = app.window_ctx(id).unwrap();
        match w.track().get(input).map(|n| &n.kind) {
            Some(Kind::Input {
                text,
                caret,
                anchor,
                preedit,
                ..
            }) => (text.clone(), *caret, *anchor, preedit.clone()),
            other => panic!("不是输入框:{other:?}"),
        }
    }

    /// 在输入框右端点一下:拿到焦点 + 光标落到末尾(多数用例的默认动作)
    fn click_input(app: &mut App, rt: &Runtime, id: WindowId, input: NodeId) {
        let rect = crate::layout::rect_of(app.window_ctx(id).unwrap().track(), input);
        click_input_at(app, rt, id, input, rect.right());
    }

    /// 在输入框里点一下(并让它拿到焦点)
    fn click_input_at(app: &mut App, rt: &Runtime, id: WindowId, input: NodeId, x: f32) {
        let rect = crate::layout::rect_of(app.window_ctx(id).unwrap().track(), input);
        let p = Point::new(x, rect.y + rect.height * 0.5);
        let w = app.window_ctx_mut(id).unwrap();
        w.pointer(
            rt,
            InputEvent::Down {
                pointer: PointerId(0),
                pos: p,
                button: PointerButton::Left,
            },
        );
        w.pointer(
            rt,
            InputEvent::Up {
                pointer: PointerId(0),
                pos: p,
                button: PointerButton::Left,
            },
        );
    }

    fn type_chars(app: &mut App, rt: &Runtime, id: WindowId, s: &str) {
        for ch in s.chars() {
            app.window_ctx_mut(id)
                .unwrap()
                .key(rt, Event::char_received(ch));
        }
    }

    fn press_key(app: &mut App, rt: &Runtime, id: WindowId, code: KeyCode, mods: Modifiers) {
        app.window_ctx_mut(id).unwrap().key(
            rt,
            Event::key_with(EventKind::KeyDown, code, mods),
        );
    }

    #[test]
    fn typing_writes_back_to_the_bound_signal() {
        let (rt, mut app, vm, id, input) = form("");
        click_input(&mut app, &rt, id, input);
        assert_eq!(app.window_ctx(id).unwrap().track().focused, Some(input));

        type_chars(&mut app, &rt, id, "abc");
        assert_eq!(vm.name.get(), "abc");
        let (text, caret, anchor, _) = input_state(&app, id, input);
        assert_eq!((text.as_str(), caret, anchor), ("abc", 3, 3));

        // 编辑回写的值与描述一致 ⇒ 下一帧不产生补丁(光标不会被"值回弹"打断)
        let st = app.frame_all()[0].1.clone();
        assert_eq!(st.align.patched, 0, "{st:?}");
    }

    #[test]
    fn click_places_the_caret_at_the_clicked_glyph() {
        let (rt, mut app, _, id, input) = form("abcd");
        let rect = crate::layout::rect_of(app.window_ctx(id).unwrap().track(), input);
        let spec = app
            .window_ctx(id)
            .unwrap()
            .track()
            .get(input)
            .unwrap()
            .text
            .spec
            .clone();
        let pad = app
            .window_ctx(id)
            .unwrap()
            .track()
            .get(input)
            .unwrap()
            .layout
            .padding[0];
        let w_ab = lieui_text::TextEngine::measure_text("ab", &spec).0 as f32;

        click_input_at(&mut app, &rt, id, input, rect.x + pad + w_ab);
        assert_eq!(input_state(&app, id, input).1, 2, "点在 a 与 b 之间");

        type_chars(&mut app, &rt, id, "X");
        assert_eq!(input_state(&app, id, input).0, "abXcd");
    }

    #[test]
    fn backspace_delete_and_arrows_edit_around_the_caret() {
        let (rt, mut app, vm, id, input) = form("abcd");
        click_input(&mut app, &rt, id, input); // 光标落在末尾
        assert_eq!(input_state(&app, id, input).1, 4);

        press_key(&mut app, &rt, id, KeyCode::Named(NamedKey::Left), Modifiers::EMPTY);
        press_key(&mut app, &rt, id, KeyCode::Named(NamedKey::Left), Modifiers::EMPTY);
        assert_eq!(input_state(&app, id, input).1, 2);

        press_key(&mut app, &rt, id, KeyCode::Named(NamedKey::Backspace), Modifiers::EMPTY);
        assert_eq!(input_state(&app, id, input).0, "acd");

        press_key(&mut app, &rt, id, KeyCode::Named(NamedKey::Delete), Modifiers::EMPTY);
        assert_eq!(input_state(&app, id, input).0, "ad");
        assert_eq!(vm.name.get(), "ad");

        press_key(&mut app, &rt, id, KeyCode::Named(NamedKey::Home), Modifiers::EMPTY);
        assert_eq!(input_state(&app, id, input).1, 0);
        press_key(&mut app, &rt, id, KeyCode::Named(NamedKey::End), Modifiers::EMPTY);
        assert_eq!(input_state(&app, id, input).1, 2);
    }

    #[test]
    fn shift_arrows_select_and_typing_replaces_the_selection() {
        let (rt, mut app, vm, id, input) = form("abcd");
        click_input(&mut app, &rt, id, input);

        press_key(&mut app, &rt, id, KeyCode::Named(NamedKey::Left), Modifiers::SHIFT);
        press_key(&mut app, &rt, id, KeyCode::Named(NamedKey::Left), Modifiers::SHIFT);
        let (_, caret, anchor, _) = input_state(&app, id, input);
        assert_eq!((caret, anchor), (2, 4), "从末尾向左扩选两个字符");

        type_chars(&mut app, &rt, id, "Z");
        assert_eq!(input_state(&app, id, input).0, "abZ", "输入替换选区");
        assert_eq!(vm.name.get(), "abZ");
    }

    #[test]
    fn ctrl_a_selects_all_and_backspace_clears_it() {
        let (rt, mut app, vm, id, input) = form("hello");
        click_input(&mut app, &rt, id, input);

        press_key(
            &mut app,
            &rt,
            id,
            KeyCode::Char('a'),
            Modifiers::CTRL,
        );
        let (_, caret, anchor, _) = input_state(&app, id, input);
        assert_eq!((caret, anchor), (5, 0), "全选");

        press_key(&mut app, &rt, id, KeyCode::Named(NamedKey::Backspace), Modifiers::EMPTY);
        assert_eq!(input_state(&app, id, input).0, "");
        assert_eq!(vm.name.get(), "");
    }

    #[test]
    fn dragging_extends_the_selection() {
        let (rt, mut app, _, id, input) = form("abcdef");
        let rect = crate::layout::rect_of(app.window_ctx(id).unwrap().track(), input);
        let mid_y = rect.y + rect.height * 0.5;

        // 按住(不松手)落在左侧
        {
            let w = app.window_ctx_mut(id).unwrap();
            w.pointer(
                &rt,
                InputEvent::Down {
                    pointer: PointerId(0),
                    pos: Point::new(rect.x + 6.0, mid_y),
                    button: PointerButton::Left,
                },
            );
        }
        assert_eq!(input_state(&app, id, input).1, 0, "点在左侧 ⇒ 光标 0");
        assert_eq!(
            app.window_ctx(id).unwrap().track().captured_by(PointerId(0)),
            Some(input),
            "编辑期间捕获指针"
        );

        // 拖到右侧 ⇒ 扩选(锚点不动)
        app.window_ctx_mut(id).unwrap().pointer(
            &rt,
            InputEvent::Move {
                pointer: PointerId(0),
                pos: Point::new(rect.right(), mid_y),
            },
        );
        let (_, caret, anchor, _) = input_state(&app, id, input);
        assert!(
            caret > anchor,
            "向右拖 ⇒ 光标在锚点右侧(caret={caret} anchor={anchor})"
        );

        // 松手后捕获释放
        app.window_ctx_mut(id).unwrap().pointer(
            &rt,
            InputEvent::Up {
                pointer: PointerId(0),
                pos: Point::new(rect.right(), mid_y),
                button: PointerButton::Left,
            },
        );
        assert_eq!(app.window_ctx(id).unwrap().track().captured_by(PointerId(0)), None);
    }

    #[test]
    fn ime_preedit_then_commit_inserts_text() {
        let (rt, mut app, vm, id, input) = form("");
        click_input(&mut app, &rt, id, input);

        // 预编辑:只进组合串,不动文本
        app.window_ctx_mut(id).unwrap().dispatch(
            &rt,
            &[input],
            &Event::ImePreedit {
                text: "zhong".to_string(),
                cursor: Some((0, 5)),
            },
        );
        assert_eq!(input_state(&app, id, input).3, "zhong");
        assert_eq!(input_state(&app, id, input).0, "");
        assert_eq!(vm.name.get(), "");

        // 提交:一个字符一条 CharacterReceived(平台的实现方式)
        type_chars(&mut app, &rt, id, "中");
        let (text, _, _, preedit) = input_state(&app, id, input);
        assert_eq!(text, "中");
        assert_eq!(preedit, "", "提交后组合串清空");
        assert_eq!(vm.name.get(), "中");
    }

    #[test]
    fn losing_focus_clears_the_preedit() {
        let (rt, mut app, _, id, input) = form("");
        click_input(&mut app, &rt, id, input);
        app.window_ctx_mut(id).unwrap().dispatch(
            &rt,
            &[input],
            &Event::ImePreedit {
                text: "ab".to_string(),
                cursor: None,
            },
        );
        assert_eq!(input_state(&app, id, input).3, "ab");

        app.window_ctx_mut(id)
            .unwrap()
            .dispatch(&rt, &[input], &Event::simple(EventKind::LostFocus));
        assert_eq!(input_state(&app, id, input).3, "");
    }

    #[test]
    fn unfocused_input_ignores_characters() {
        let (rt, mut app, vm, id, input) = form("");
        // 没有点进去(没有焦点)时敲字不应落进输入框
        type_chars(&mut app, &rt, id, "x");
        assert_eq!(input_state(&app, id, input).0, "");
        assert_eq!(vm.name.get(), "");
    }

    #[test]
    fn unbound_input_ignores_editing() {
        struct Plain;
        impl ViewModel for Plain {
            fn view(self: &Rc<Self>, v: &mut ViewBuf) {
                v.column(|c| {
                    c.input("固定文本");
                });
            }
        }

        let rt = Runtime::new();
        let mut app = App::new(rt.clone());
        let id = app.window(WindowConfig::new().size(240.0, 80.0), Plain);
        app.frame_all();
        let input = {
            let w = app.window_ctx(id).unwrap();
            w.track().children(w.content_root().unwrap())[0]
        };
        click_input(&mut app, &rt, id, input);
        type_chars(&mut app, &rt, id, "zzz");

        let (text, caret, _, _) = input_state(&app, id, input);
        assert_eq!(text, "固定文本", "未绑定 ⇒ 编辑不生效");
        assert_eq!(caret, "固定文本".len());
    }

    #[test]
    fn model_change_replaces_the_buffer_and_puts_the_caret_at_the_end() {
        let (rt, mut app, vm, id, input) = form("ab");
        click_input(&mut app, &rt, id, input);
        press_key(&mut app, &rt, id, KeyCode::Named(NamedKey::Home), Modifiers::EMPTY);
        assert_eq!(input_state(&app, id, input).1, 0);

        // 模型侧改值(模拟"外部同步")
        vm.name.set("hello".to_string());
        app.frame_all();

        let (text, caret, anchor, _) = input_state(&app, id, input);
        assert_eq!((text.as_str(), caret, anchor), ("hello", 5, 5));
    }

    #[test]
    fn tab_moves_focus_away_from_an_input() {
        struct TwoFields {
            a: Signal<String>,
            b: Signal<String>,
        }
        impl ViewModel for TwoFields {
            fn view(self: &Rc<Self>, v: &mut ViewBuf) {
                v.column(|c| {
                    c.input_bound(&self.a);
                    c.input_bound(&self.b);
                });
            }
        }

        let rt = Runtime::new();
        let mut app = App::new(rt.clone());
        let vm = Rc::new(TwoFields {
            a: Signal::new(&rt, String::new()),
            b: Signal::new(&rt, String::new()),
        });
        let id = app.window_erased(WindowConfig::new().size(240.0, 120.0), erased(Rc::clone(&vm)));
        app.frame_all();
        let (first, second) = {
            let w = app.window_ctx(id).unwrap();
            let kids = w.track().children(w.content_root().unwrap());
            (kids[0], kids[1])
        };

        click_input(&mut app, &rt, id, first);
        type_chars(&mut app, &rt, id, "a");
        assert_eq!(vm.a.get(), "a");

        app.window_ctx_mut(id).unwrap().tab(&rt, true);
        assert_eq!(app.window_ctx(id).unwrap().track().focused, Some(second));

        type_chars(&mut app, &rt, id, "b");
        assert_eq!((vm.a.get(), vm.b.get()), ("a".to_string(), "b".to_string()));
    }

    // ─────────────── M5:锚定层(popup)───────────────

    struct Menu {
        open: Signal<bool>,
    }

    impl ViewModel for Menu {
        fn view(self: &Rc<Self>, v: &mut ViewBuf) {
            v.column(|c| {
                c.gap(8.0);
                c.button("菜单")
                    .key("btn")
                    .on_tap(act(self, |s| s.open.set(!s.open.get())));
            });
            if self.open.get() {
                v.popup_at("btn", Placement::Below, |p| {
                    p.text("菜单项 A");
                    p.text("菜单项 B");
                });
            }
        }
    }

    #[test]
    fn popup_opens_on_tap_and_follows_the_anchor() {
        let rt = Runtime::new();
        let mut app = App::new(rt.clone());
        let id = app.window(
            WindowConfig::new().size(300.0, 200.0),
            Menu {
                open: Signal::new(&rt, false),
            },
        );
        app.frame_all();
        let btn = {
            let w = app.window_ctx(id).unwrap();
            w.track().children(w.content_root().unwrap())[0]
        };
        assert!(
            app.window_ctx(id)
                .unwrap()
                .track()
                .roots_of(Layer::Popup)
                .next()
                .is_none(),
            "没开菜单前没有 popup 层"
        );

        // 点按钮 ⇒ open = true ⇒ view() 声明 popup ⇒ 布局后落位
        let rect = crate::layout::rect_of(app.window_ctx(id).unwrap().track(), btn);
        let p = rect.center();
        {
            let w = app.window_ctx_mut(id).unwrap();
            w.pointer(
                &rt,
                InputEvent::Down {
                    pointer: PointerId(0),
                    pos: p,
                    button: PointerButton::Left,
                },
            );
            w.pointer(
                &rt,
                InputEvent::Up {
                    pointer: PointerId(0),
                    pos: p,
                    button: PointerButton::Left,
                },
            );
        }
        app.frame_all();

        let (br, pr) = {
            let w = app.window_ctx(id).unwrap();
            let t = w.track();
            let popup = t.roots_of(Layer::Popup).next().expect("popup 层出现了").node;
            (crate::layout::rect_of(t, btn), crate::layout::rect_of(t, popup))
        };
        assert_eq!(pr.x, br.x, "Below 与锚点左对齐");
        assert!(
            (pr.y - (br.bottom() + 4.0)).abs() < 0.5,
            "层在锚点下方留间距:{br:?} -> {pr:?}"
        );

        // 再点一次(按钮被 popup 挡不住:popup 在按钮下方)⇒ 关闭 ⇒ popup 层消失
        {
            let w = app.window_ctx_mut(id).unwrap();
            w.pointer(
                &rt,
                InputEvent::Down {
                    pointer: PointerId(0),
                    pos: p,
                    button: PointerButton::Left,
                },
            );
            w.pointer(
                &rt,
                InputEvent::Up {
                    pointer: PointerId(0),
                    pos: p,
                    button: PointerButton::Left,
                },
            );
        }
        app.frame_all();
        assert!(
            app.window_ctx(id)
                .unwrap()
                .track()
                .roots_of(Layer::Popup)
                .next()
                .is_none(),
            "再点一次后 popup 层消失"
        );
    }

    // ─────────────── M6:ComboBox(A 档组合:按钮 + 锚定弹层)───────────────

    struct Picker {
        open: Signal<bool>,
        choice: Signal<String>,
    }

    /// **A 档组合函数**(≈ 组件就是普通函数):锚定按钮 + 轻关闭弹层。
    /// 不需要任何新机制——这正是"组合覆盖 ~90%"的验收。
    fn combo(
        vm: &Rc<Picker>,
        v: &mut ViewBuf,
        anchor_key: &str,
        options: &[&str],
    ) {
        v.column(|c| {
            c.button("选择水果")
                .key(anchor_key)
                .on_tap(act(vm, |s| s.open.set(!s.open.get())));
        });
        if vm.open.get() {
            v.popup_at(anchor_key, Placement::Below, |p| {
                // 轻关闭:点击弹层之外 ⇒ 层根收到 Dismissed ⇒ 翻自己的状态
                let me = Rc::clone(vm);
                p.on(EventKind::Dismissed, move |_| me.open.set(false));
                for opt in options {
                    let me = Rc::clone(vm);
                    let label = opt.to_string();
                    p.text(opt.to_string())
                        .padding(6.0)
                        .width(80.0)
                        .on_tap(move || {
                            me.choice.set(label.clone());
                            me.open.set(false);
                        });
                }
            });
        }
    }

    impl ViewModel for Picker {
        fn view(self: &Rc<Self>, v: &mut ViewBuf) {
            combo(self, v, "combo-btn", &["苹果", "香蕉", "樱桃"]);
        }
    }

    fn picker() -> (Runtime, App, Rc<Picker>, WindowId) {
        let rt = Runtime::new();
        let mut app = App::new(rt.clone());
        let vm = Rc::new(Picker {
            open: Signal::new(&rt, false),
            choice: Signal::new(&rt, String::new()),
        });
        let id = app.window_erased(
            WindowConfig::new().size(200.0, 200.0),
            erased(Rc::clone(&vm)),
        );
        app.frame_all();
        (rt, app, vm, id)
    }

    fn popup_root_of(app: &App, id: WindowId) -> Option<NodeId> {
        app.window_ctx(id)
            .unwrap()
            .track()
            .roots_of(Layer::Popup)
            .next()
            .map(|r| r.node)
    }

    #[test]
    fn combo_dropdown_opens_selects_and_light_dismisses() {
        let (rt, mut app, vm, id) = picker();
        let btn = app
            .window_ctx(id)
            .unwrap()
            .track()
            .children(app.window_ctx(id).unwrap().content_root().unwrap())[0];

        assert!(popup_root_of(&app, id).is_none(), "展开前没有弹层");

        // ① 点锚点 ⇒ 弹层出现,锚定按钮下方、左对齐
        tap_node(&mut app, &rt, id, btn);
        app.frame_all();
        let (br, pr, items) = {
            let w = app.window_ctx(id).unwrap();
            let t = w.track();
            let popup = popup_root_of(&app, id).expect("弹层出现");
            let items: Vec<NodeId> = t
                .descendants(popup)
                .into_iter()
                .filter(|n| matches!(t.get(*n).unwrap().kind, Kind::Text(_)))
                .collect();
            (
                crate::layout::rect_of(t, btn),
                crate::layout::rect_of(t, popup),
                items,
            )
        };
        assert_eq!(pr.x, br.x, "Below 左对齐");
        assert!((pr.y - (br.bottom() + 4.0)).abs() < 0.5);
        assert_eq!(items.len(), 3, "三个选项");

        // ② 点"香蕉" ⇒ 选中 + 弹层关闭(选项自己翻 open)
        tap_node(&mut app, &rt, id, items[1]);
        assert_eq!(vm.choice.get(), "香蕉");
        assert_eq!(vm.open.get(), false);
        app.frame_all();
        assert!(popup_root_of(&app, id).is_none(), "选择后弹层消失");

        // ③ 再展开,点击弹层之外 ⇒ 轻关闭
        tap_node(&mut app, &rt, id, btn);
        app.frame_all();
        assert!(popup_root_of(&app, id).is_some());
        {
            let w = app.window_ctx_mut(id).unwrap();
            w.pointer(
                &rt,
                InputEvent::Down {
                    pointer: PointerId(0),
                    pos: Point::new(190.0, 190.0),
                    button: PointerButton::Left,
                },
            );
            w.pointer(
                &rt,
                InputEvent::Up {
                    pointer: PointerId(0),
                    pos: Point::new(190.0, 190.0),
                    button: PointerButton::Left,
                },
            );
        }
        assert_eq!(vm.open.get(), false, "点外部 ⇒ Dismissed ⇒ 关闭");
        app.frame_all();
        assert!(popup_root_of(&app, id).is_none());

        // ④ 锚点在关闭状态再点 ⇒ 重新展开(toggle 与 dismiss 不互相打架)
        tap_node(&mut app, &rt, id, btn);
        assert_eq!(vm.open.get(), true);
    }

    #[test]
    fn anchor_click_while_open_closes_the_dropdown() {
        let (rt, mut app, vm, id) = picker();
        let btn = app
            .window_ctx(id)
            .unwrap()
            .track()
            .children(app.window_ctx(id).unwrap().content_root().unwrap())[0];

        tap_node(&mut app, &rt, id, btn);
        app.frame_all();
        assert!(popup_root_of(&app, id).is_some());

        // 弹层开着时再点锚点:Tapped(toggle→false) 先于 Dismissed(→false) ⇒ 关闭且保持关闭
        tap_node(&mut app, &rt, id, btn);
        assert_eq!(vm.open.get(), false);
        app.frame_all();
        assert!(popup_root_of(&app, id).is_none());
    }

    // ─────────────── M6:MenuBar(组合 + 嵌套弹层)───────────────

    struct MenuVm {
        /// 当前打开的菜单名("" = 全关)——声明式互斥,同 Radio 原理
        open_menu: Signal<String>,
        /// "查找"子菜单是否展开
        sub_open: Signal<bool>,
        last: Signal<String>,
    }

    impl ViewModel for MenuVm {
        fn view(self: &Rc<Self>, v: &mut ViewBuf) {
            // ── 菜单条:一排锚点按钮(行固定高,按钮不被拉伸成整窗)──
            v.row(|r| {
                r.height(28.0);
                r.button("文件")
                    .key("menu-文件")
                    .on_tap(act1(self, |s, m: String| {
                        // toggle 自己(打开时再点 = 关闭)
                        s.open_menu
                            .set(if s.open_menu.get() == m { String::new() } else { m });
                    }, "文件".to_string()));
                r.button("编辑")
                    .key("menu-编辑")
                    .on_tap(act1(self, |s, m: String| {
                        s.open_menu
                            .set(if s.open_menu.get() == m { String::new() } else { m });
                    }, "编辑".to_string()));
            });

            // ── 弹层:声明式存在(open_menu 是唯一真相),锚定各自的按钮 ──
            if self.open_menu.get() == "文件" {
                v.popup_at("menu-文件", Placement::Below, |p| {
                    let me = Rc::clone(self);
                    // 轻关闭守卫:只关自己(避免清掉刚打开的兄弟菜单)
                    p.on(EventKind::Dismissed, move |_| {
                        if me.open_menu.get() == "文件" {
                            me.open_menu.set(String::new());
                        }
                    });
                    for item in ["新建", "打开"] {
                        let me = Rc::clone(self);
                        let label = item.to_string();
                        p.text(item.to_string())
                            .padding(6.0)
                            .width(90.0)
                            .on_tap(move || {
                                me.last.set(label.clone());
                                me.open_menu.set(String::new());
                            });
                    }
                });
            }
            if self.open_menu.get() == "编辑" {
                v.popup_at("menu-编辑", Placement::Below, |p| {
                    let me = Rc::clone(self);
                    p.on(EventKind::Dismissed, move |_| {
                        if me.open_menu.get() == "编辑" {
                            me.open_menu.set(String::new());
                        }
                    });
                    p.text("撤销")
                        .padding(6.0)
                        .width(90.0)
                        .on_tap({
                            let me = Rc::clone(self);
                            move || {
                                me.last.set("撤销".to_string());
                                me.open_menu.set(String::new());
                            }
                        });
                    // 子菜单锚点:这一项本身是下级弹层的锚
                    p.text("查找 ▸")
                        .padding(6.0)
                        .width(90.0)
                        .key("item-查找")
                        .on_tap(act(self, |s| s.sub_open.set(!s.sub_open.get())));
                });
            }
            // ── 子层级:锚点在另一个弹层里(RightOf),验证嵌套弹层 ──
            if self.open_menu.get() == "编辑" && self.sub_open.get() {
                v.popup_at("item-查找", Placement::RightOf, |p| {
                    let me = Rc::clone(self);
                    p.text("查找内容")
                        .padding(6.0)
                        .width(90.0)
                        .on_tap(move || {
                            me.last.set("查找内容".to_string());
                            me.open_menu.set(String::new());
                            me.sub_open.set(false);
                        });
                });
            }
        }
    }

    fn menu_vm() -> (Runtime, App, Rc<MenuVm>, WindowId) {
        let rt = Runtime::new();
        let mut app = App::new(rt.clone());
        let vm = Rc::new(MenuVm {
            open_menu: Signal::new(&rt, String::new()),
            sub_open: Signal::new(&rt, false),
            last: Signal::new(&rt, String::new()),
        });
        let id = app.window_erased(
            WindowConfig::new().size(300.0, 220.0),
            erased(Rc::clone(&vm)),
        );
        app.frame_all();
        (rt, app, vm, id)
    }

    fn menu_buttons(app: &App, id: WindowId) -> (NodeId, NodeId) {
        let w = app.window_ctx(id).unwrap();
        let kids = w.track().children(w.content_root().unwrap());
        (kids[0], kids[1])
    }

    fn popup_texts(app: &App, id: WindowId) -> Vec<String> {
        let w = app.window_ctx(id).unwrap();
        let t = w.track();
        let Some(popup) = t.roots_of(Layer::Popup).next().map(|r| r.node) else {
            return Vec::new();
        };
        t.descendants(popup)
            .into_iter()
            .filter_map(|n| match &t.get(n).unwrap().kind {
                Kind::Text(s) => Some(s.clone()),
                _ => None,
            })
            .collect()
    }

    #[test]
    fn menu_bar_opens_one_menu_at_a_time_and_reanchors() {
        let (rt, mut app, _, id) = menu_vm();
        let (btn_file, btn_edit) = menu_buttons(&app, id);

        assert!(popup_texts(&app, id).is_empty(), "初始没有弹层");

        // 打开"文件"
        tap_node(&mut app, &rt, id, btn_file);
        app.frame_all();
        assert_eq!(popup_texts(&app, id), vec!["新建".to_string(), "打开".to_string()]);

        // 直接点"编辑":文件关闭、编辑打开(tapped 先行、dismiss 只关自己)
        tap_node(&mut app, &rt, id, btn_edit);
        app.frame_all();
        assert_eq!(popup_texts(&app, id), vec!["撤销".to_string(), "查找 ▸".to_string()]);

        // 弹层重新锚定到"编辑"按钮下方(跨帧跟随锚点)
        let (br, pr) = {
            let w = app.window_ctx(id).unwrap();
            let t = w.track();
            let popup = t.roots_of(Layer::Popup).next().unwrap().node;
            (
                crate::layout::rect_of(t, btn_edit),
                crate::layout::rect_of(t, popup),
            )
        };
        assert_eq!(pr.x, br.x, "x 对齐:br={br:?} pr={pr:?}");
        assert!(
            (pr.y - (br.bottom() + 4.0)).abs() < 0.5,
            "y 锚定:br={br:?} pr={pr:?}"
        );

        // 再点"编辑":关闭
        tap_node(&mut app, &rt, id, btn_edit);
        app.frame_all();
        assert!(popup_texts(&app, id).is_empty());
    }

    #[test]
    fn menu_item_fires_and_submenu_nests_to_the_right() {
        let (rt, mut app, vm, id) = menu_vm();
        let (btn_file, _) = menu_buttons(&app, id);

        // 文件 → 新建:动作触发 + 菜单关闭
        tap_node(&mut app, &rt, id, btn_file);
        app.frame_all();
        let item = {
            let w = app.window_ctx(id).unwrap();
            let t = w.track();
            let popup = t.roots_of(Layer::Popup).next().unwrap().node;
            t.descendants(popup)
                .into_iter()
                .find(|n| matches!(&t.get(*n).unwrap().kind, Kind::Text(s) if s == "新建"))
                .expect("有 新建 项")
        };
        tap_node(&mut app, &rt, id, item);
        assert_eq!(vm.last.get(), "新建");
        assert_eq!(vm.open_menu.get(), "");
        app.frame_all();
        assert!(popup_texts(&app, id).is_empty());

        // 编辑 → 查找 ▸:子菜单出现在右侧(RightOf,锚点是弹层内的项)
        let (_, btn_edit) = menu_buttons(&app, id);
        tap_node(&mut app, &rt, id, btn_edit);
        app.frame_all();
        let find_item = {
            let w = app.window_ctx(id).unwrap();
            let t = w.track();
            let popup = t.roots_of(Layer::Popup).next().unwrap().node;
            t.descendants(popup)
                .into_iter()
                .find(|n| matches!(&t.get(*n).unwrap().kind, Kind::Text(s) if s == "查找 ▸"))
                .expect("有 查找 项")
        };
        tap_node(&mut app, &rt, id, find_item);
        app.frame_all();

        // 两个弹层:菜单 + 子菜单(同层后声明者在上面)
        let (item_r, sub_r) = {
            let w = app.window_ctx(id).unwrap();
            let t = w.track();
            let mut roots = t.roots_of(Layer::Popup).map(|r| r.node);
            let _menu = roots.next().unwrap();
            let sub = roots.next().expect("子菜单弹层存在");
            (
                crate::layout::rect_of(t, find_item),
                crate::layout::rect_of(t, sub),
            )
        };
        assert!(
            (sub_r.x - (item_r.right() + 4.0)).abs() < 0.5,
            "子菜单在锚点右侧:item={item_r:?} sub={sub_r:?}"
        );
        assert!((sub_r.y - item_r.y).abs() < 0.5, "子菜单与锚点顶对齐");

        // 点子菜单项:动作 + 全部关闭(含子菜单状态)
        let sub_item = {
            let w = app.window_ctx(id).unwrap();
            let t = w.track();
            let mut roots = t.roots_of(Layer::Popup).map(|r| r.node);
            let _menu = roots.next().unwrap();
            let sub = roots.next().unwrap();
            t.descendants(sub)
                .into_iter()
                .find(|n| matches!(&t.get(*n).unwrap().kind, Kind::Text(s) if s == "查找内容"))
                .expect("有 查找内容 项")
        };
        tap_node(&mut app, &rt, id, sub_item);
        assert_eq!(vm.last.get(), "查找内容");
        assert_eq!(vm.open_menu.get(), "");
        assert_eq!(vm.sub_open.get(), false);
        app.frame_all();
        assert!(popup_texts(&app, id).is_empty(), "全部弹层关闭");
    }

    #[test]
    fn clicking_outside_closes_the_open_menu() {
        let (rt, mut app, vm, id) = menu_vm();
        let (btn_file, _) = menu_buttons(&app, id);

        tap_node(&mut app, &rt, id, btn_file);
        app.frame_all();
        assert!(!popup_texts(&app, id).is_empty());

        // 点窗口右下角(远离菜单条与弹层)⇒ 轻关闭
        {
            let w = app.window_ctx_mut(id).unwrap();
            w.pointer(
                &rt,
                InputEvent::Down {
                    pointer: PointerId(0),
                    pos: Point::new(280.0, 200.0),
                    button: PointerButton::Left,
                },
            );
            w.pointer(
                &rt,
                InputEvent::Up {
                    pointer: PointerId(0),
                    pos: Point::new(280.0, 200.0),
                    button: PointerButton::Left,
                },
            );
        }
        assert_eq!(vm.open_menu.get(), "", "点外部 ⇒ Dismissed ⇒ 关闭");
        app.frame_all();
        assert!(popup_texts(&app, id).is_empty());
    }

    // ─────────────── M6:VirtualList(ScrollChanged + 组合)───────────────

    /// 用**框架 API**(`ViewBuf::virtual_list`)声明 1000 行长列表。
    struct LongList {
        vl: VirtualListState,
        items: Vec<u32>,
    }

    impl ViewModel for LongList {
        fn view(self: &Rc<Self>, v: &mut ViewBuf) {
            v.scroll(|s| {
                s.height(240.0);
                s.width(140.0);
                // 只物化可见窗口:窗口起点由 `vl` 记住,`ScrollChanged` 时自动回写
                s.virtual_list(&self.vl, &self.items, |i| *i as u64, 24.0, 240.0, |v, i| {
                    v.row(|r| {
                        r.height(24.0);
                        r.text(format!("Item {i}")).font_size(16.0);
                    });
                });
            });
        }
    }

    fn long_list_with(count: u32) -> (Runtime, App, Rc<LongList>, WindowId) {
        let rt = Runtime::new();
        let mut app = App::new(rt.clone());
        let vm = Rc::new(LongList {
            vl: VirtualListState::new(&rt),
            items: (0..count).collect(),
        });
        let id = app.window_erased(
            WindowConfig::new().size(200.0, 300.0),
            erased(Rc::clone(&vm)),
        );
        app.frame_all();
        (rt, app, vm, id)
    }

    fn long_list() -> (Runtime, App, Rc<LongList>, WindowId) {
        long_list_with(1000)
    }

    /// 滚动容器 = 内容根本身(`v.scroll` 在 view 顶层声明)
    fn scroll_node(app: &App, id: WindowId) -> NodeId {
        app.window_ctx(id).unwrap().content_root().unwrap()
    }

    fn visible_labels(app: &App, id: WindowId) -> Vec<String> {
        let w = app.window_ctx(id).unwrap();
        let t = w.track();
        let scroll = scroll_node(app, id);
        t.descendants(scroll)
            .into_iter()
            .filter_map(|n| match &t.get(n).unwrap().kind {
                Kind::Text(s) if s.starts_with("Item ") => Some(s.clone()),
                _ => None,
            })
            .collect()
    }

    /// 可见行 = `(item 下标, 行节点)`(行节点 = keyed item 的根,也是 key 所在处)
    fn visible_rows(app: &App, id: WindowId) -> Vec<(u32, NodeId)> {
        let w = app.window_ctx(id).unwrap();
        let t = w.track();
        let scroll = scroll_node(app, id);
        let mut out = Vec::new();
        for n in t.descendants(scroll) {
            let Some(node) = t.get(n) else { continue };
            if let Kind::Text(s) = &node.kind
                && let Some(rest) = s.strip_prefix("Item ")
                && let Ok(i) = rest.parse::<u32>()
                && let Some(p) = t.parent_of(n)
            {
                out.push((i, p));
            }
        }
        out
    }

    #[test]
    fn virtual_list_materializes_only_the_visible_window() {
        let (rt, mut app, _vm, id) = long_list();
        let scroll = scroll_node(&app, id);

        // 1000 行只渲染 11 行(240/24 + 1),标签是前 11 个
        let labels = visible_labels(&app, id);
        assert_eq!(labels.len(), 11, "只物化可见窗口:{}", labels.len());
        assert_eq!(labels[0], "Item 0");
        assert_eq!(labels[10], "Item 10");

        // 内容尺寸是"虚拟"的完整高度 ⇒ 滚动条诚实
        assert!(
            (app.window_ctx(id).unwrap().track().get(scroll).unwrap().content_size.height - 24000.0)
                .abs()
                < 0.5,
            "内容高 = 1000 × 24"
        );

        // 滚一屏:ScrollChanged ⇒ first=10 ⇒ 下一帧换一批行
        {
            let w = app.window_ctx_mut(id).unwrap();
            w.pointer(
                &rt,
                InputEvent::Wheel {
                    pointer: PointerId(0),
                    pos: Point::new(60.0, 120.0),
                    delta: (0.0, -240.0), // 负 = 向下滚一屏
                },
            );
        }
        app.frame_all(); // 派发 ScrollChanged ⇒ 信号写入(本帧还是旧行)
        app.frame_all(); // view 重跑 ⇒ 换窗
        let labels = visible_labels(&app, id);
        assert_eq!(labels.len(), 11, "窗口大小不变");
        assert_eq!(labels[0], "Item 10", "窗口前移 10 行:{labels:?}");
        assert_eq!(labels[10], "Item 20");

        // 滚动位置在保留树里(视图态)⇒ 与信号一致,不回弹
        assert!(
            (app.window_ctx(id)
                .unwrap()
                .track()
                .scroll_offset(scroll)
                .1
                - 240.0)
                .abs()
                < 0.5
        );
    }

    /// **key 复用**:滚动后仍然可见的行必须复用原节点(`NodeId` 不变)
    /// —— 这是"行内状态不丢"(选中 / 输入框 / 展开态)的前提。
    #[test]
    fn virtual_list_reuses_rows_by_key_when_scrolling() {
        let (rt, mut app, _vm, id) = long_list();
        let scroll = scroll_node(&app, id);

        let before = visible_rows(&app, id);
        assert_eq!(before.len(), 11, "窗口 240/24 + 1");

        // 滚 5 行(120px)
        app.window_ctx_mut(id)
            .unwrap()
            .track_mut()
            .set_scroll_offset(scroll, (0.0, 120.0));
        app.frame_all(); // 派发 ScrollChanged ⇒ 回写窗口起点
        app.frame_all(); // view 重跑 ⇒ 换窗

        let after = visible_rows(&app, id);
        assert_eq!(after[0].0, 5, "窗口前移 5 行:{after:?}");
        assert_eq!(after[10].0, 15);

        // 重叠区(Item 5..=10)两帧都在 ⇒ 节点必须复用
        for (idx, node) in before.iter().filter(|(i, _)| (5..=10).contains(i)) {
            let (_, after_node) = after
                .iter()
                .find(|(i, _)| i == idx)
                .unwrap_or_else(|| panic!("Item {idx} 应仍在窗口内"));
            assert_eq!(
                node, after_node,
                "Item {idx} 的行节点应被 key 复用(而不是按下标重建)"
            );
        }
        let _ = &rt;
    }

    /// 边界:空列表 / 起点越界都不能 panic、不能越界切片
    #[test]
    fn virtual_list_handles_empty_and_out_of_range() {
        let (_rt, mut app, vm, id) = long_list_with(0);
        assert!(visible_rows(&app, id).is_empty(), "空列表物化 0 行");
        let scroll = scroll_node(&app, id);
        assert!(
            app.window_ctx(id).unwrap().track().get(scroll).unwrap().content_size.height < 0.5,
            "空列表内容高为 0"
        );

        // 起点远超 count:clamp 后不物化任何行
        vm.vl.set_first(99_999);
        app.frame_all();
        assert!(visible_rows(&app, id).is_empty());

        // 只有 1 项时也正常
        let (_rt2, app2, _vm2, id2) = long_list_with(1);
        let rows = visible_rows(&app2, id2);
        assert_eq!(rows.len(), 1);
        assert_eq!(rows[0].0, 0);
    }

    /// `virtual_list` 的虚拟占位:内容总高 = count × item_h(滚动条因此"诚实"),
    /// 且**没有**额外的占位节点(用内容列的 padding 撑,而非空 row)。
    #[test]
    fn virtual_list_pads_instead_of_inserting_spacer_nodes() {
        let (_rt, app, _vm, id) = long_list();
        let w = app.window_ctx(id).unwrap();
        let t = w.track();
        let scroll = scroll_node(&app, id);
        // 滚动容器 → 内容列 → 11 行(没有第二个占位节点)
        let col = t.children(scroll)[0];
        assert_eq!(t.children(col).len(), 11, "内容列只放可见行");
        assert_eq!(t.get(scroll).unwrap().content_size.height, 24.0 * 1000.0);
    }

    #[test]
    fn scrolling_back_reveals_earlier_items() {
        let (_rt, mut app, _vm, id) = long_list();
        let scroll = scroll_node(&app, id);

        // 直接把偏移滚到很深(模拟 ScrollTo / 大量滚轮)
        app.window_ctx_mut(id)
            .unwrap()
            .track_mut()
            .set_scroll_offset(scroll, (0.0, 24000.0 - 240.0));
        app.frame_all(); // 派发 ScrollChanged ⇒ 信号写入
        app.frame_all(); // view 重跑 ⇒ 换窗
        let labels = visible_labels(&app, id);
        assert_eq!(labels.last().map(String::as_str), Some("Item 999"), "{labels:?}");
    }

    #[test]
    fn popup_layer_draws_an_opaque_surface() {
        let (rt, mut app, _, id) = picker();
        let btn = app
            .window_ctx(id)
            .unwrap()
            .track()
            .children(app.window_ctx(id).unwrap().content_root().unwrap())[0];

        tap_node(&mut app, &rt, id, btn);
        app.frame_all();
        let popup = popup_root_of(&app, id).expect("弹层出现");
        let pr = crate::layout::rect_of(app.window_ctx(id).unwrap().track(), popup);

        // 采样弹层的内边距区域(无内容覆盖)⇒ 应是不透明的弹层底色,而非窗口底色
        let ctx = app.window_ctx(id).unwrap();
        let p = pixel(ctx, (pr.x + 3.0) as u16, (pr.y + 3.0) as u16);
        assert_eq!(
            p,
            opaque(
                Theme::light().input_background.r,
                Theme::light().input_background.g,
                Theme::light().input_background.b
            ),
            "弹层底色 = 主题 input_background(不透明):{p:?}"
        );
    }

    #[test]
    fn hover_repaints_the_button_with_its_hover_color() {
        struct Btn;
        impl ViewModel for Btn {
            fn view(self: &Rc<Self>, v: &mut ViewBuf) {
                v.column(|c| {
                    c.button("B");
                });
            }
        }

        let rt = Runtime::new();
        let mut app = App::new(rt.clone());
        let id = app.window(WindowConfig::new().size(200.0, 100.0), Btn);
        app.frame_all();
        let btn = app
            .window_ctx(id)
            .unwrap()
            .track()
            .children(app.window_ctx(id).unwrap().content_root().unwrap())[0];
        let r = crate::layout::rect_of(app.window_ctx(id).unwrap().track(), btn);
        // 采样点:左缘内侧(避开圆角与文字)
        let (sx, sy) = ((r.x + 5.0) as u16, (r.center().y) as u16);

        let before = { pixel(app.window_ctx(id).unwrap(), sx, sy) };

        // 指针移到按钮上 ⇒ hover 态 ⇒ 重绘为 hover 色
        app.window_ctx_mut(id).unwrap().pointer(
            &rt,
            InputEvent::Move {
                pointer: PointerId(0),
                pos: r.center(),
            },
        );
        app.frame_all();

        let after = { pixel(app.window_ctx(id).unwrap(), sx, sy) };
        let t = Theme::light();
        assert_eq!(
            before,
            opaque(t.control.r, t.control.g, t.control.b),
            "常态 = control"
        );
        assert_eq!(
            after,
            opaque(t.control_hover.r, t.control_hover.g, t.control_hover.b),
            "hover = control_hover"
        );
    }

    // ─────────────── M6:开关 / 单选 ───────────────

    struct Toggles {
        on: Signal<bool>,
        color: Signal<String>,
    }

    impl ViewModel for Toggles {
        fn view(self: &Rc<Self>, v: &mut ViewBuf) {
            v.column(|c| {
                c.gap(8.0);
                c.switch_bound(&self.on);
                c.radio_bound(&self.color, "red");
                c.radio_bound(&self.color, "green");
                // 只显示形态(未绑定 ⇒ 内置行为不激活)
                c.switch(true);
                c.radio(true);
            });
        }
    }

    fn toggles() -> (Runtime, App, Rc<Toggles>, WindowId, Vec<NodeId>) {
        let rt = Runtime::new();
        let mut app = App::new(rt.clone());
        let vm = Rc::new(Toggles {
            on: Signal::new(&rt, false),
            color: Signal::new(&rt, "red".to_string()),
        });
        let id = app.window_erased(
            WindowConfig::new().size(200.0, 200.0),
            erased(Rc::clone(&vm)),
        );
        app.frame_all();
        let kids = app
            .window_ctx(id)
            .unwrap()
            .track()
            .children(app.window_ctx(id).unwrap().content_root().unwrap())
            .to_vec();
        (rt, app, vm, id, kids)
    }

    fn tap_node(app: &mut App, rt: &Runtime, id: WindowId, node: NodeId) {
        let p = crate::layout::rect_of(app.window_ctx(id).unwrap().track(), node).center();
        let w = app.window_ctx_mut(id).unwrap();
        w.pointer(
            rt,
            InputEvent::Down {
                pointer: PointerId(0),
                pos: p,
                button: PointerButton::Left,
            },
        );
        w.pointer(
            rt,
            InputEvent::Up {
                pointer: PointerId(0),
                pos: p,
                button: PointerButton::Left,
            },
        );
    }

    #[test]
    fn switch_bound_toggles_the_signal_and_the_desc_follows() {
        let (rt, mut app, vm, id, kids) = toggles();
        tap_node(&mut app, &rt, id, kids[0]);
        assert_eq!(vm.on.get(), true, "点击 ⇒ 写回 signal");

        // 下一帧 desc 跟上(apply_to 判等 ⇒ 零补丁,不回弹)
        app.frame_all();

        tap_node(&mut app, &rt, id, kids[0]);
        assert_eq!(vm.on.get(), false);

        // 未绑定的只显示形态:点不变
        tap_node(&mut app, &rt, id, kids[3]);
        assert_eq!(vm.on.get(), false);
    }

    #[test]
    fn radio_group_is_mutually_exclusive_via_the_view_rerun() {
        let (rt, mut app, vm, id, kids) = toggles();
        assert_eq!(vm.color.get(), "red", "初始选中 red");

        // 点 green ⇒ signal 变 ⇒ 下一帧两个 radio 的 selected 由对齐器自然更新
        tap_node(&mut app, &rt, id, kids[2]);
        assert_eq!(vm.color.get(), "green");

        app.frame_all();
        let (red_sel, green_sel) = {
            let t = app.window_ctx(id).unwrap().track();
            (
                matches!(t.get(kids[1]).unwrap().kind, Kind::Radio { selected: true, .. }),
                matches!(t.get(kids[2]).unwrap().kind, Kind::Radio { selected: true, .. }),
            )
        };
        assert!(!red_sel && green_sel, "声明式互斥:red=false green=true");

        // 点回 red:同样只需一次信号写入
        tap_node(&mut app, &rt, id, kids[1]);
        assert_eq!(vm.color.get(), "red");
    }

    #[test]
    fn unbound_radio_ignores_taps() {
        let (rt, mut app, vm, id, kids) = toggles();
        tap_node(&mut app, &rt, id, kids[4]);
        assert_eq!(vm.color.get(), "red", "未绑定 ⇒ 编辑不生效");
    }

    // ─────────────── M5:主题 ───────────────

    // ─────────────── 后台任务 + loading 遮罩(框架级) ───────────────

    #[test]
    fn background_task_shows_overlay_animates_and_delivers_its_result() {
        use crate::task::TaskEvent;

        /// 任务结果的落地目标
        struct Worker {
            report: Signal<Option<u32>>,
        }
        impl ViewModel for Worker {
            fn view(self: &Rc<Self>, v: &mut ViewBuf) {
                v.column(|c| {
                    c.center();
                    c.text(format!("report={:?}", self.report.get()));
                });
            }
            fn on_external(self: &Rc<Self>, _cx: &mut Ctx, data: ExternalData) {
                if let Some(ev) = data.downcast::<TaskEvent>()
                    && let Some(r) = ev.payload.downcast::<u32>()
                {
                    self.report.set(Some(r));
                }
            }
        }

        let rt = Runtime::new();
        let mut app = App::new(rt.clone());
        let vm = Rc::new(Worker {
            report: Signal::new(&rt, None),
        });
        let id = app.window_erased(
            WindowConfig::new().size(400.0, 300.0),
            erased(Rc::clone(&vm)),
        );
        app.frame_all();

        // 无头环境没有平台唤醒器 ⇒ 投递走本地队列(测试正好用它当"事件循环")
        assert!(!rt.is_online());

        // 起任务 + 遮罩
        let handle = rt.spawn_task_busy(id, "正在处理…", |ctx| {
            ctx.progress(1, 2);
            7u32
        });

        // 下一帧:view 重跑(遮罩是声明式的)⇒ 遮罩层出现在保留树里
        let stats = app.frame_all();
        assert!(stats[0].1.view_ran, "忙碌状态变化 ⇒ 重跑 view");
        {
            let w = app.window_ctx(id).unwrap();
            assert!(
                w.track().root_by_tag(crate::overlay::BUSY_OVERLAY_TAG).is_some(),
                "遮罩层已声明"
            );
        }

        // 动画:动画帧把**卡片**标脏(只重绘,不重跑 view),并给出下一次唤醒时刻
        {
            let ctx = app.window_ctx_mut(id).unwrap();
            let _ = ctx.track_mut().take_damage(); // 清掉前面的脏区,只看动画帧贡献
            ctx.animate(Instant::now());
            let (damage, all) = ctx.track_mut().take_damage();
            assert!(all || !damage.is_empty(), "有遮罩 ⇒ 动画帧有重绘义务");
            assert!(ctx.next_wakeup().is_some(), "遮罩 ⇒ 定时唤醒(spinner)");
        }
        // 遮罩确实画到了屏幕上:卡片内的 padding 区应是卡片底色(不是窗口底色)
        {
            let ctx = app.window_ctx(id).unwrap();
            let track = ctx.track();
            let root = track
                .root_by_tag(crate::overlay::BUSY_OVERLAY_TAG)
                .expect("遮罩层在")
                .node;
            let card = track.children(root)[0];
            let r = crate::layout::rect_of(track, card);
            let light = Theme::light();
            assert_eq!(
                pixel(ctx, (r.x + 10.0) as u16, (r.y + 10.0) as u16),
                opaque(
                    light.input_background.r,
                    light.input_background.g,
                    light.input_background.b
                ),
                "窗口里出现了遮罩卡片({r:?})"
            );
        }

        // 等任务跑完(`frame_all` 会消费本地投递队列 ⇒ 等价于平台层的事件循环)
        let deadline = Instant::now() + std::time::Duration::from_secs(5);
        while (!handle.is_done() || vm.report.get().is_none()) && Instant::now() < deadline {
            app.frame_all();
            std::thread::sleep(std::time::Duration::from_millis(2));
        }
        app.frame_all();

        // 结果落地 + 遮罩自动收起
        assert_eq!(vm.report.get(), Some(7), "任务返回值经 TaskEvent 落到 Signal");
        assert!(
            !rt.is_busy(id) && !rt.has_tasks(id),
            "完成 ⇒ 任务表与忙碌项都清空"
        );
        {
            let ctx = app.window_ctx(id).unwrap();
            assert!(
                ctx.track().root_by_tag(crate::overlay::BUSY_OVERLAY_TAG).is_none(),
                "完成 ⇒ 遮罩层消失"
            );
            assert!(
                ctx.next_wakeup().is_none(),
                "遮罩消失且没有聚焦输入框/tooltip ⇒ 回到零唤醒(空闲零功耗)"
            );
        }
    }

    // ─────────────── 统一时钟:定时器 / 动画帧 ───────────────

    use crate::event::Emitter;
    use crate::view::VirtualListState;
    use std::cell::Cell;

    /// 计时器 + 动画的观察 VM
    struct Clocked {
        timeouts: Rc<Cell<u32>>,
        intervals: Rc<Cell<u32>>,
        frames: Rc<Cell<u32>>,
        last_dt_ms: Rc<Cell<u128>>,
        /// 还要不要再要一帧(模拟"动画结束就停")
        keep_animating: Rc<Cell<bool>>,
    }

    impl ViewModel for Clocked {
        fn view(self: &Rc<Self>, v: &mut ViewBuf) {
            v.column(|c| {
                c.text("clock");
            });
        }

        fn on_animation(self: &Rc<Self>, cx: &mut Ctx, _now: Instant, dt: std::time::Duration) {
            self.frames.set(self.frames.get() + 1);
            self.last_dt_ms.set(dt.as_millis());
            if self.keep_animating.get() {
                cx.request_animation(); // 经典 RAF:想继续就再要一帧
            }
        }
    }

    fn clocked_vm() -> Clocked {
        Clocked {
            timeouts: Rc::new(Cell::new(0)),
            intervals: Rc::new(Cell::new(0)),
            frames: Rc::new(Cell::new(0)),
            last_dt_ms: Rc::new(Cell::new(0)),
            keep_animating: Rc::new(Cell::new(true)),
        }
    }

    #[test]
    fn timeouts_fire_once_and_intervals_keep_firing_until_cancelled() {
        let rt = Runtime::new();
        let mut app = App::new(rt.clone());
        let vm = clocked_vm();
        let id = app.window(
            WindowConfig::new().size(200.0, 120.0),
            Clocked {
                timeouts: Rc::clone(&vm.timeouts),
                intervals: Rc::clone(&vm.intervals),
                frames: Rc::clone(&vm.frames),
                last_dt_ms: Rc::clone(&vm.last_dt_ms),
                keep_animating: Rc::clone(&vm.keep_animating),
            },
        );
        app.frame_all();

        // 一次性:立即到期 ⇒ 下一帧触发一次,之后不再有
        rt.set_timeout(id, std::time::Duration::ZERO, {
            let t = Rc::clone(&vm.timeouts);
            move |_| t.set(t.get() + 1)
        });
        assert!(rt.next_deadline(id).is_some(), "有定时器 ⇒ 平台会定时唤醒");
        app.frame_all();
        assert_eq!(vm.timeouts.get(), 1);
        assert!(rt.next_deadline(id).is_none(), "一次性定时器跑完就没了");
        app.frame_all();
        assert_eq!(vm.timeouts.get(), 1, "不会再触发");

        // 周期:首次立即到期,之后每 1ms 一次;取消后停
        let handle = rt.set_interval(id, std::time::Duration::ZERO, {
            let i = Rc::clone(&vm.intervals);
            move |_| i.set(i.get() + 1)
        });
        app.frame_all();
        let after_first = vm.intervals.get();
        assert!(after_first >= 1, "周期定时器触发");
        std::thread::sleep(std::time::Duration::from_millis(3)); // 跨过下一个间隔
        app.frame_all();
        assert!(vm.intervals.get() > after_first, "还会继续触发");

        handle.cancel();
        let stopped = vm.intervals.get();
        app.frame_all();
        assert_eq!(vm.intervals.get(), stopped, "取消后不再触发");
        assert!(rt.next_deadline(id).is_none());
    }

    #[test]
    fn animation_frames_run_only_while_requested_and_expose_dt() {
        let rt = Runtime::new();
        let mut app = App::new(rt.clone());
        let vm = clocked_vm();
        let id = app.window(
            WindowConfig::new().size(200.0, 120.0),
            Clocked {
                timeouts: Rc::clone(&vm.timeouts),
                intervals: Rc::clone(&vm.intervals),
                frames: Rc::clone(&vm.frames),
                last_dt_ms: Rc::clone(&vm.last_dt_ms),
                keep_animating: Rc::clone(&vm.keep_animating),
            },
        );
        app.frame_all();
        assert_eq!(vm.frames.get(), 0, "没请求就不跑动画");

        rt.request_animation(id);
        app.frame_all();
        assert_eq!(vm.frames.get(), 1, "请求一次 = 一帧");
        assert!(rt.next_deadline(id).is_some(), "持续动画 ⇒ 平台持续唤醒");

        std::thread::sleep(std::time::Duration::from_millis(2));
        app.frame_all();
        assert_eq!(vm.frames.get(), 2, "回调里再请求 ⇒ 连续跑");
        assert!(vm.last_dt_ms.get() >= 1, "dt 是真实帧间隔(毫秒)");

        // 停手:不再请求 ⇒ 动画停(空闲零功耗)
        vm.keep_animating.set(false);
        app.frame_all();
        let last = vm.frames.get();
        app.frame_all();
        app.frame_all();
        assert_eq!(vm.frames.get(), last, "不请求就不再跑");
        assert!(rt.next_deadline(id).is_none());
        assert!(app.window_ctx(id).unwrap().next_wakeup().is_none(), "回到零唤醒");
    }

    #[test]
    fn custom_events_reach_on_external_through_the_frame_driver() {
        struct Bus {
            got: Signal<Vec<String>>,
        }
        impl ViewModel for Bus {
            fn view(self: &Rc<Self>, v: &mut ViewBuf) {
                v.column(|c| {
                    c.text("bus");
                });
            }
            fn on_external(self: &Rc<Self>, _cx: &mut Ctx, data: ExternalData) {
                if let Some(s) = data.downcast::<String>() {
                    self.got.update(|v| v.push(s));
                }
            }
        }

        let rt = Runtime::new();
        let mut app = App::new(rt.clone());
        let vm = Rc::new(Bus {
            got: Signal::new(&rt, Vec::new()),
        });
        let id = app.window_erased(
            WindowConfig::new(),
            erased(Rc::clone(&vm)),
        );
        app.frame_all();

        // UI 线程发事件
        assert!(rt.emit(id, "hello".to_string()));
        // 跨线程(或业务层)用发射器发事件
        let tx = Emitter::<String>::new(&rt, id);
        let t = std::thread::spawn(move || tx.emit("world".to_string()));
        assert!(t.join().unwrap());

        app.frame_all(); // 帧驱动消费队列
        let mut got = vm.got.get();
        got.sort();
        assert_eq!(got, vec!["hello".to_string(), "world".to_string()]);
    }

    /// `full_repaint`:不看脏区,每帧整窗重绘(逃生舱 / 残影对照工具)
    #[test]
    fn full_repaint_mode_always_redraws_the_whole_window() {
        struct Page {
            n: Signal<u32>,
        }
        impl ViewModel for Page {
            fn view(self: &Rc<Self>, v: &mut ViewBuf) {
                v.column(|c| {
                    c.text(format!("n={}", self.n.get()));
                });
            }
        }

        // 普通模式:只改一个文本 ⇒ 只重画那一小块
        let rt = Runtime::new();
        let mut app = App::new(rt.clone());
        let vm = Rc::new(Page {
            n: Signal::new(&rt, 0),
        });
        let _id = app.window_erased(
            WindowConfig::new().size(400.0, 300.0),
            erased(Rc::clone(&vm)),
        );
        app.frame_all();
        vm.n.set(1);
        let st = app.frame_all();
        assert!(!st[0].1.damage_all, "默认走脏区");
        assert!(st[0].1.render.raster.pixels < 400 * 300, "不是整窗");

        // 整窗重绘模式:同样只改一个文本,但整窗重画
        let rt = Runtime::new();
        let mut app = App::new(rt.clone());
        let vm = Rc::new(Page {
            n: Signal::new(&rt, 0),
        });
        let _id = app.window_erased(
            WindowConfig::new().size(400.0, 300.0).full_repaint(true),
            erased(Rc::clone(&vm)),
        );
        app.frame_all();
        vm.n.set(1);
        let st = app.frame_all();
        assert!(st[0].1.damage_all, "full_repaint ⇒ 整窗脏");
        assert_eq!(st[0].1.render.raster.pixels, 400 * 300, "整窗像素都重画");
    }

    /// 快活儿也要看得见遮罩:忙碌段在**两次出帧之间**开始又结束(小文件读盘的真实情形,
    /// 完成消息往往先于下一帧被处理),配了最短可见时间后下一帧仍然画得出遮罩。
    #[test]
    fn a_fast_busy_section_still_shows_the_overlay() {
        struct Empty;
        impl ViewModel for Empty {
            fn view(self: &Rc<Self>, v: &mut ViewBuf) {
                v.column(|c| {
                    c.text("主界面");
                });
            }
        }

        let rt = Runtime::new();
        rt.set_busy_min_visible(Duration::from_millis(300));
        let mut app = App::new(rt.clone());
        let id = app.window(WindowConfig::new().size(400.0, 300.0), Empty);
        app.frame_all();

        // 忙碌段瞬间开始又结束(中间没有出过帧)
        let busy = rt.begin_busy(id, "正在打开…");
        busy.finish();

        // 下一帧:遮罩必须在 —— 没有它用户就什么都看不到
        app.frame_all();
        {
            let ctx = app.window_ctx(id).unwrap();
            assert!(
                ctx.track()
                    .root_by_tag(crate::overlay::BUSY_OVERLAY_TAG)
                    .is_some(),
                "最短可见期内遮罩要在"
            );
            assert!(ctx.next_wakeup().is_some(), "还要定时唤醒去收它");
        }

        // 到点 ⇒ 收掉;下一帧没有遮罩,回到零唤醒
        assert!(rt.reap_busy(Instant::now() + Duration::from_millis(400)));
        app.frame_all();
        {
            let ctx = app.window_ctx(id).unwrap();
            assert!(
                ctx.track()
                    .root_by_tag(crate::overlay::BUSY_OVERLAY_TAG)
                    .is_none(),
                "到点 ⇒ 遮罩收起"
            );
            assert!(ctx.next_wakeup().is_none(), "遮罩收掉 ⇒ 回到零唤醒");
        }
    }

    /// 整窗图片(PDF 预览那类)不得盖住浮层:遮罩是**后**声明的 Modal 层,必须压在图上。
    ///
    /// 症状来源:光栅层原先把图片 op 统一放到批次末尾 blit("图片总在最上层"),
    /// 于是预览图盖住了 loading 遮罩 —— 用户"看不到进度 modal"。
    #[test]
    fn busy_overlay_covers_a_full_window_image() {
        struct Pic;
        impl ViewModel for Pic {
            fn view(self: &Rc<Self>, v: &mut ViewBuf) {
                // 整窗一张纯红图(2×2 拉伸铺满)
                v.image(std::sync::Arc::new(crate::ImageData {
                    width: 2,
                    height: 2,
                    rgba: vec![
                        255, 0, 0, 255, 255, 0, 0, 255, //
                        255, 0, 0, 255, 255, 0, 0, 255,
                    ],
                }))
                .expand(true);
            }
        }

        let rt = Runtime::new();
        let mut app = App::new(rt.clone());
        let id = app.window(WindowConfig::new().size(400.0, 300.0), Pic);
        app.frame_all();
        {
            let ctx = app.window_ctx(id).unwrap();
            assert_eq!(pixel(ctx, 200, 150), opaque(255, 0, 0), "先确认整窗都是图");
        }

        // 忙碌遮罩压上来:卡片底色必须出现在图上(旧实现这里还是红的)
        let busy = rt.begin_busy(id, "正在打开…");
        app.frame_all();
        {
            let ctx = app.window_ctx(id).unwrap();
            let root = ctx
                .track()
                .root_by_tag(crate::overlay::BUSY_OVERLAY_TAG)
                .expect("遮罩层在")
                .node;
            let card = ctx.track().children(root)[0];
            let r = crate::layout::rect_of(ctx.track(), card);
            let light = Theme::light();
            assert_eq!(
                pixel(ctx, (r.x + 10.0) as u16, (r.y + 10.0) as u16),
                opaque(
                    light.input_background.r,
                    light.input_background.g,
                    light.input_background.b
                ),
                "遮罩卡片压在图片之上"
            );
        }
        busy.finish();
    }

    /// 忙碌遮罩是 Modal 层 ⇒ 下层的按钮点不到(交互被挡住)
    #[test]
    fn busy_overlay_blocks_input_to_the_content_below() {
        let rt = Runtime::new();
        let mut app = App::new(rt.clone());
        let vm = Rc::new(Counter {
            count: Signal::new(&rt, 0),
        });
        let id = app.window_erased(
            WindowConfig::new().size(400.0, 300.0),
            erased(Rc::clone(&vm)),
        );
        app.frame_all();

        // `Counter` 的 view 结构固定:内容根第 3 个子节点是个 row,里面第 1 个是「+1」按钮
        let button = {
            let w = app.window_ctx(id).unwrap();
            let root = w.content_root().unwrap();
            let row = w.track().children(root)[2];
            w.track().children(row)[0]
        };

        tap_node(&mut app, &rt, id, button);
        assert_eq!(vm.count.get(), 1, "平时点得到");

        // 遮罩起来:同样点一下 ⇒ 下层按钮收不到
        let busy = rt.begin_busy(id, "后台任务进行中…");
        app.frame_all();
        tap_node(&mut app, &rt, id, button);
        assert_eq!(vm.count.get(), 1, "遮罩挡住下层交互");

        // 收起遮罩 ⇒ 恢复交互
        busy.finish();
        app.frame_all();
        tap_node(&mut app, &rt, id, button);
        assert_eq!(vm.count.get(), 2, "遮罩消失后恢复交互");
    }

    /// 跟随系统:OS 深色上报 ⇒ 重跑 view + 窗口底色跟随(未显式指定底色时)
    #[test]
    fn system_theme_mode_follows_the_os_and_repaints_the_window() {
        use crate::theme::ThemeMode;

        struct Empty;
        impl ViewModel for Empty {
            fn view(self: &Rc<Self>, v: &mut ViewBuf) {
                v.column(|c| {
                    c.text("hi");
                });
            }
        }

        let rt = Runtime::new();
        let mut app = App::new(rt.clone());
        let id = app.window(WindowConfig::new().size(60.0, 40.0), Empty);
        app.frame_all();
        let light = Theme::light();
        {
            let ctx = app.window_ctx(id).unwrap();
            let bg = pixel(ctx, 5, 35); // 文字下方
            assert_eq!(
                bg,
                opaque(
                    light.window_background.r,
                    light.window_background.g,
                    light.window_background.b
                ),
                "默认浅色底"
            );
        }

        // 切「跟随系统」:默认浅色不变
        rt.set_theme_mode(ThemeMode::System);
        app.frame_all();
        assert_eq!(rt.theme(), Theme::light());

        // OS 转深色 ⇒ 底色与控件一起跟随(view 重跑)
        rt.set_system_dark(true);
        let st = app.frame_all()[0].1.clone();
        assert!(st.view_ran, "系统主题变化 ⇒ view 重跑");
        let dark = Theme::dark();
        {
            let ctx = app.window_ctx(id).unwrap();
            let bg = pixel(ctx, 5, 35);
            assert_eq!(
                bg,
                opaque(
                    dark.window_background.r,
                    dark.window_background.g,
                    dark.window_background.b
                ),
                "跟随系统 ⇒ 窗口底色变深"
            );
        }
    }

    #[test]
    fn theme_switch_recolors_the_controls_on_the_next_frame() {
        struct Btn;
        impl ViewModel for Btn {
            fn view(self: &Rc<Self>, v: &mut ViewBuf) {
                v.column(|c| {
                    c.center();
                    c.button("按钮");
                });
            }
        }

        let rt = Runtime::new();
        let mut app = App::new(rt.clone());
        let id = app.window(WindowConfig::new().size(200.0, 200.0), Btn);
        app.frame_all();

        // 取按钮左下角内侧一点(避开圆角与文字)
        let (sx, sy) = {
            let w = app.window_ctx(id).unwrap();
            let t = w.track();
            let r = crate::layout::rect_of(t, t.children(w.content_root().unwrap())[0]);
            ((r.x + 6.0) as u16, (r.bottom() - 3.0) as u16)
        };
        let light = Theme::light();
        let dark = Theme::dark();

        // 浅色:按钮底 = control token
        {
            let ctx = app.window_ctx(id).unwrap();
            assert_eq!(
                pixel(ctx, sx, sy),
                opaque(light.control.r, light.control.g, light.control.b),
                "按钮底色 = 主题 control"
            );
        }

        // 切深色 ⇒ 重跑 view(token 重新烘焙)+ 整窗重绘 ⇒ 按钮变深
        rt.set_theme(dark);
        let st = app.frame_all()[0].1.clone();
        assert!(st.view_ran, "主题切换 ⇒ view 重跑");
        {
            let ctx = app.window_ctx(id).unwrap();
            assert_eq!(
                pixel(ctx, sx, sy),
                opaque(dark.control.r, dark.control.g, dark.control.b),
                "切主题后按钮底色跟随"
            );
        }

        // 同值切换是 no-op:不再重跑
        rt.set_theme(dark);
        let st = app.frame_all()[0].1.clone();
        assert!(!st.view_ran, "同主题切换是 no-op");
    }

    #[test]
    fn explicit_window_background_survives_theme_switch() {
        struct Empty;
        impl ViewModel for Empty {
            fn view(self: &Rc<Self>, _v: &mut ViewBuf) {}
        }

        let rt = Runtime::new();
        let mut app = App::new(rt.clone());
        let id = app.window(
            WindowConfig::new()
                .size(100.0, 100.0)
                .background(lieui_geom::Color::RED),
            Empty,
        );
        app.frame_all();

        rt.set_theme(Theme::dark());
        app.frame_all();
        let ctx = app.window_ctx(id).unwrap();
        assert_eq!(pixel(ctx, 50, 50), opaque(255, 0, 0), "显式底色优先于主题");
    }

    // ─────────────── M6 收尾:光标闪烁 + 输入框水平滚动 ───────────────

    #[test]
    fn tooltip_opens_after_hover_delay_and_closes_on_leave() {
        struct T;
        impl ViewModel for T {
            fn view(self: &Rc<Self>, v: &mut ViewBuf) {
                v.column(|c| {
                    c.text("hover me").font_size(20.0).tooltip("i am a tooltip");
                    c.text("plain");
                });
            }
        }

        let rt = Runtime::new();
        let mut app = App::new(rt.clone());
        let id = app.window(WindowConfig::new().size(300.0, 200.0), T);
        app.frame_all();

        // 找到带 tooltip 的文本节点
        let target = {
            let w = app.window_ctx(id).unwrap();
            let root = w.content_root().unwrap();
            w.track()
                .children(root)
                .iter()
                .copied()
                .find(|k| w.track().get(*k).is_some_and(|n| n.tooltip.is_some()))
                .unwrap()
        };

        // 悬停到目标上(会话 armed,但未到延迟 ⇒ 无 tooltip 层)
        let center = {
            let w = app.window_ctx(id).unwrap();
            let r = crate::layout::rect_of(w.track(), target);
            Point::new(r.x + r.width / 2.0, r.y + r.height / 2.0)
        };
        app.window_ctx_mut(id).unwrap().pointer(
            &rt,
            InputEvent::Move {
                pointer: PointerId(0),
                pos: center,
            },
        );
        app.frame_all();
        assert!(
            app.window_ctx(id)
                .unwrap()
                .track()
                .roots_of(crate::track::Layer::Tooltip)
                .next()
                .is_none(),
            "未到延迟 ⇒ 不应出现 tooltip 层"
        );

        // 时间到(tick 推进会话)⇒ 浮出,且锚到目标节点
        let now = Instant::now() + TOOLTIP_DELAY + Duration::from_millis(50);
        app.window_ctx_mut(id).unwrap().tick(&rt, now);
        app.frame_all();
        {
            let w = app.window_ctx(id).unwrap();
            let tip_root = w
                .track()
                .roots_of(crate::track::Layer::Tooltip)
                .next()
                .expect("延迟到 ⇒ tooltip 层应出现");
            assert!(tip_root.framework, "tooltip 层是框架自管的");
            match &tip_root.opts.anchor.as_ref().unwrap().target {
                crate::track::AnchorTarget::Node(t) => assert_eq!(*t, target, "锚到 hover 节点"),
                other => panic!("tooltip 锚点应为 Node:{other:?}"),
            }
        }

        // 切换主题 ⇒ 已浮出的 tooltip 也要换色(框架自管层不会被 view 重建)
        let dark = Theme::dark();
        rt.set_theme(dark);
        app.frame_all();
        app.window_ctx_mut(id).unwrap().tick(&rt, now);
        app.frame_all();
        {
            let w = app.window_ctx(id).unwrap();
            let tip_root = w
                .track()
                .roots_of(crate::track::Layer::Tooltip)
                .next()
                .expect("主题切换不影响 tooltip 的存在");
            let n = w.track().get(tip_root.node).unwrap();
            assert_eq!(
                n.paint.background_color,
                Some(dark.tooltip_background),
                "tooltip 底色跟随主题"
            );
            assert_eq!(n.text.color, dark.tooltip_text, "tooltip 文字色跟随主题");
        }

        // 移开 ⇒ 消失(align 不得回收框架自管层——消失必须来自会话本身)
        app.window_ctx_mut(id).unwrap().pointer(
            &rt,
            InputEvent::Move {
                pointer: PointerId(0),
                pos: Point::new(150.0, 150.0),
            },
        );
        app.frame_all();
        assert!(
            app.window_ctx(id)
                .unwrap()
                .track()
                .roots_of(crate::track::Layer::Tooltip)
                .next()
                .is_none(),
            "移开 ⇒ tooltip 层应消失"
        );
    }

    /// tooltip 的文本按**墨迹盒**居中:盒高 = 墨迹高 + 上下各 6px,
    /// 于是字形上下留白相等(行盒 ascent/descent 不对称会让文本看着往上顶)。
    /// 像素级验证:上下 padding 带是纯底色,字形只出现在中间那条墨迹带里。
    #[test]
    fn tooltip_text_is_centered_by_its_ink_box() {
        struct T;
        impl ViewModel for T {
            fn view(self: &Rc<Self>, v: &mut ViewBuf) {
                v.column(|c| {
                    c.text("hover me").font_size(20.0).tooltip("i am a tooltip");
                });
            }
        }

        let rt = Runtime::new();
        let mut app = App::new(rt.clone());
        let id = app.window(WindowConfig::new().size(300.0, 200.0), T);
        app.frame_all();

        let target = {
            let w = app.window_ctx(id).unwrap();
            let root = w.content_root().unwrap();
            w.track()
                .children(root)
                .iter()
                .copied()
                .find(|k| w.track().get(*k).is_some_and(|n| n.tooltip.is_some()))
                .unwrap()
        };
        let center = {
            let w = app.window_ctx(id).unwrap();
            let r = crate::layout::rect_of(w.track(), target);
            Point::new(r.x + r.width / 2.0, r.y + r.height / 2.0)
        };
        app.window_ctx_mut(id).unwrap().pointer(
            &rt,
            InputEvent::Move {
                pointer: PointerId(0),
                pos: center,
            },
        );
        let now = Instant::now() + TOOLTIP_DELAY + Duration::from_millis(50);
        app.window_ctx_mut(id).unwrap().tick(&rt, now);
        app.frame_all();

        let w = app.window_ctx(id).unwrap();
        let tip_node = w
            .track()
            .roots_of(crate::track::Layer::Tooltip)
            .next()
            .expect("tooltip 层在")
            .node;
        let n = w.track().get(tip_node).unwrap();
        assert!(n.text.spec.optical_align, "tooltip 走墨迹盒对齐");

        let rect = crate::layout::rect_of(w.track(), tip_node);
        let ink = lieui_text::TextEngine::ink_bounds("i am a tooltip", &n.text.spec)
            .expect("tooltip 文本有墨迹");
        assert!(
            (rect.height - (ink.height() + 12.0)).abs() < 0.01,
            "tooltip 盒高 = 墨迹高 + 12:{} vs {}",
            rect.height,
            ink.height()
        );

        // 远离圆角(左右各让 8px)取横带:上/下 padding 带必须是纯底色,
        // 字形只出现在中间那条墨迹带里 ⇒ 上下留白相等。
        let xs: Vec<u16> = ((rect.x + 8.0) as u16..=(rect.right() - 8.0) as u16).collect();
        let bg = pixel(w, xs[0], (rect.y + 2.0) as u16);
        let band_uniform = |y: u16| xs.iter().all(|x| pixel(w, *x, y) == bg);
        assert!(
            band_uniform((rect.y + 2.0) as u16),
            "顶部 padding 带是纯底色"
        );
        assert!(
            band_uniform((rect.bottom() - 2.0) as u16),
            "底部 padding 带是纯底色"
        );

        let mid: Vec<u16> = ((rect.y + 6.0) as u16..(rect.y + 6.0 + ink.height()) as u16).collect();
        let ink_px = mid
            .iter()
            .filter(|y| xs.iter().any(|x| pixel(w, *x, **y) != bg))
            .count();
        assert!(ink_px > 0, "中间墨迹带里应有字形像素");
    }

    #[test]
    fn caret_blinks_only_while_an_input_is_focused() {
        let (rt, mut app, _, id, input) = form("abc");

        // 未聚焦:animate 是 no-op(不会唤醒,也不会画光标)
        assert!(!app.window_ctx_mut(id).unwrap().animate(Instant::now()));
        assert!(!app.window_ctx(id).unwrap().track().blink_on);

        // 点进输入框:dispatch 重置相位 ⇒ 光标常亮
        click_input(&mut app, &rt, id, input);
        assert!(app.window_ctx(id).unwrap().track().blink_on);

        // 静止一个周期 ⇒ 翻转为灭;再一个周期 ⇒ 又亮
        let later = Instant::now() + BLINK_PERIOD + Duration::from_millis(50);
        assert!(app.window_ctx_mut(id).unwrap().animate(later));
        assert!(!app.window_ctx(id).unwrap().track().blink_on, "周期到 ⇒ 灭");
        assert!(app
            .window_ctx_mut(id)
            .unwrap()
            .animate(later + BLINK_PERIOD));
        assert!(app.window_ctx(id).unwrap().track().blink_on, "再翻转为亮");

        // 未到周期:不动(这就是"聚焦才动,其余零功耗"的保证)
        assert!(!app
            .window_ctx_mut(id)
            .unwrap()
            .animate(later + BLINK_PERIOD + Duration::from_millis(100)));
    }

    #[test]
    fn input_horizontally_scrolls_to_keep_the_caret_visible() {
        let (rt, mut app, vm, id, input) = form("");
        click_input(&mut app, &rt, id, input);

        // 打 40 个字符:远超默认 200 宽的输入框
        type_chars(&mut app, &rt, id, "0123456789abcdef0123456789abcdef01234567");
        app.frame_all();

        let (scroll, caret) = {
            let w = app.window_ctx(id).unwrap();
            match w.track().get(input).map(|n| &n.kind) {
                Some(Kind::Input { caret, scroll, .. }) => (*scroll, *caret),
                other => panic!("{other:?}"),
            }
        };
        assert!(caret == 40);
        assert!(scroll > 0.0, "文本超宽 ⇒ 自动水平滚动,光标保持可见:{scroll}");

        // Home:光标回 0 ⇒ 滚动也回 0(可见窗口跟随光标)
        press_key(&mut app, &rt, id, KeyCode::Named(NamedKey::Home), Modifiers::EMPTY);
        app.frame_all();
        let (caret2, scroll2) = {
            let w = app.window_ctx(id).unwrap();
            match w.track().get(input).map(|n| &n.kind) {
                Some(Kind::Input { caret, scroll, .. }) => (*caret, *scroll),
                other => panic!("{other:?}"),
            }
        };
        assert_eq!(caret2, 0);
        assert!((scroll2 - 0.0).abs() < 0.01, "Home ⇒ 滚动回 0:{scroll2}");
        assert_eq!(vm.name.get().len(), 40);
    }

    // ─────────────── M6 修复回归:滚动平移 + 滚动容器内拖滑块 ───────────────

    #[test]
    fn scrolling_translates_the_content_on_the_next_layout() {
        use crate::track::Layer;

        let mut t = crate::track::Track::new();
        let sc = t.create(Kind::Box, None);
        {
            let n = t.get_mut(sc).unwrap();
            n.layout.dim = [200.0, 200.0];
            n.layout.overflow_scroll = true;
        }
        t.add_root(Layer::Content, None, sc);
        let child = t.create(Kind::Box, None);
        t.get_mut(child).unwrap().layout.dim = [100.0, 400.0];
        t.append_child(sc, child);
        crate::layout::layout(&mut t, Size::new(400.0, 400.0));
        let y0 = crate::layout::rect_of(&t, child).y;

        // 滚动 100 ⇒ 下一次布局把子原点平移 -100
        assert!(t.set_scroll_offset(sc, (0.0, 100.0)));
        crate::layout::layout(&mut t, Size::new(400.0, 400.0));
        let y1 = crate::layout::rect_of(&t, child).y;
        assert!((y1 - (y0 - 100.0)).abs() < 0.5, "内容随偏移平移:{y0} → {y1}");
    }

    #[test]
    fn slider_inside_scroll_container_drags() {
        struct Holder {
            vol: Signal<f32>,
        }
        impl ViewModel for Holder {
            fn view(self: &Rc<Self>, v: &mut ViewBuf) {
                v.scroll(|s| {
                    s.width(300.0);
                    s.height(200.0);
                    s.slider_bound(&self.vol, 0.0, 10.0);
                });
            }
        }

        let rt = Runtime::new();
        let mut app = App::new(rt.clone());
        let vm = Rc::new(Holder {
            vol: Signal::new(&rt, 0.0),
        });
        let id = app.window_erased(
            WindowConfig::new().size(400.0, 300.0),
            erased(Rc::clone(&vm)),
        );
        app.frame_all();

        let scroll = app.window_ctx(id).unwrap().content_root().unwrap();
        let slider = app.window_ctx(id).unwrap().track().children(scroll)[0];
        let r = crate::layout::rect_of(app.window_ctx(id).unwrap().track(), slider);

        // 按下并拖到滑块右端
        {
            let w = app.window_ctx_mut(id).unwrap();
            w.pointer(
                &rt,
                InputEvent::Down {
                    pointer: PointerId(0),
                    pos: r.center(),
                    button: PointerButton::Left,
                },
            );
            w.pointer(
                &rt,
                InputEvent::Move {
                    pointer: PointerId(0),
                    pos: Point::new(r.right() - 2.0, r.center().y),
                },
            );
        }
        assert!(vm.vol.get() > 9.0, "拖到右端 ⇒ 音量接近 10:{}", vm.vol.get());
    }

    #[test]
    fn disabled_slider_ignores_the_pointer() {
        struct Off {
            volume: Signal<f32>,
        }
        impl ViewModel for Off {
            fn view(self: &Rc<Self>, v: &mut ViewBuf) {
                v.column(|c| {
                    c.slider_bound(&self.volume, 0.0, 10.0).enabled(false);
                });
            }
        }

        let rt = Runtime::new();
        let mut app = App::new(rt.clone());
        let vm = Rc::new(Off {
            volume: Signal::new(&rt, 1.0),
        });
        let id = app.window_erased(
            WindowConfig::new().size(200.0, 120.0),
            erased(Rc::clone(&vm)),
        );
        app.frame_all();
        let slider = {
            let w = app.window_ctx(id).unwrap();
            w.track().children(w.content_root().unwrap())[0]
        };
        let rect = crate::layout::rect_of(app.window_ctx(id).unwrap().track(), slider);

        app.window_ctx_mut(id).unwrap().pointer(
            &rt,
            InputEvent::Down {
                pointer: PointerId(0),
                pos: Point::new(rect.right(), rect.y + 5.0),
                button: PointerButton::Left,
            },
        );
        assert_eq!(vm.volume.get(), 1.0, "禁用 ⇒ 内置行为不执行");
        assert_eq!(
            app.window_ctx(id).unwrap().track().captured_by(PointerId(0)),
            None
        );
    }

    #[test]
    fn focus_ring_is_repainted_without_rerunning_view() {
        let rt = Runtime::new();
        let mut app = App::new(rt.clone());
        let vm = Rc::new(Counter {
            count: Signal::new(&rt, 0),
        });
        let id = app.window_erased(WindowConfig::new(), erased(vm));
        app.frame_all();

        // 找到按钮并给它 tab_stop + 键盘焦点(模拟 Tab 导航)
        let button = {
            let w = app.window_ctx(id).unwrap();
            let root = w.content_root().unwrap();
            let row = w.track().children(root)[2];
            w.track().children(row)[0]
        };
        app.window_ctx_mut(id)
            .unwrap()
            .track_mut()
            .get_mut(button)
            .unwrap()
            .tab_stop = true;
        app.window_ctx_mut(id)
            .unwrap()
            .tab(&rt, true)
            .expect("有可聚焦节点");

        let st = app.frame_all()[0].1.clone();
        assert!(!st.view_ran, "焦点变化不重跑 view()");
        assert!(st.paint_pending);
        assert!(st.render.scene.ops > 0);
    }
}