muri 0.13.2

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

#![allow(unsafe_code)]

mod input;
mod present;
mod window;

#[cfg(feature = "a11y")]
mod a11y;

use std::cell::{Cell, RefCell};
use std::ptr::null_mut;
use std::rc::Rc;
#[cfg(feature = "a11y")]
use std::sync::atomic::AtomicIsize;
use std::sync::atomic::{AtomicU32, Ordering};
use std::sync::Once;

use windows_sys::Win32::Foundation::{HWND, LPARAM, LRESULT, POINT, RECT, S_OK, WPARAM};
use windows_sys::Win32::Graphics::Gdi::{
    CreateBitmap, CreateDIBSection, DeleteObject, GetDC, GetMonitorInfoW, MonitorFromPoint,
    MonitorFromRect, ReleaseDC, BITMAPINFO, BITMAPINFOHEADER, BI_RGB, DIB_RGB_COLORS, HGDIOBJ,
    MONITORINFO, MONITOR_DEFAULTTONEAREST,
};
use windows_sys::Win32::System::LibraryLoader::GetModuleHandleW;
use windows_sys::Win32::System::Registry::{RegGetValueW, HKEY_CURRENT_USER, RRF_RT_REG_DWORD};
use windows_sys::Win32::UI::HiDpi::{
    GetDpiForMonitor, GetDpiForSystem, GetDpiForWindow, MDT_EFFECTIVE_DPI,
};
use windows_sys::Win32::UI::Shell::{
    Shell_NotifyIconGetRect, Shell_NotifyIconW, NIF_ICON, NIF_MESSAGE, NIF_STATE, NIF_TIP, NIM_ADD,
    NIM_DELETE, NIM_MODIFY, NIS_HIDDEN, NOTIFYICONDATAW, NOTIFYICONIDENTIFIER,
};
use windows_sys::Win32::UI::WindowsAndMessaging::{
    CallNextHookEx, CreateIconIndirect, CreateWindowExW, DefWindowProcW, DestroyIcon,
    DestroyWindow, DispatchMessageW, GetCursorPos, GetMessageW, GetWindowLongPtrW, GetWindowRect,
    PostMessageW, PostQuitMessage, RegisterClassW, RegisterWindowMessageW, SetWindowsHookExW,
    TranslateMessage, UnhookWindowsHookEx, GWLP_USERDATA, HC_ACTION, HHOOK, HICON, HWND_MESSAGE,
    ICONINFO, KBDLLHOOKSTRUCT, MSG, MSLLHOOKSTRUCT, WH_KEYBOARD_LL, WH_MOUSE_LL, WM_ACTIVATEAPP,
    WM_APP, WM_KEYDOWN, WM_LBUTTONDOWN, WM_LBUTTONUP, WM_MOUSEMOVE, WM_RBUTTONDOWN, WNDCLASSW,
};

use crate::anchor::place_popup;
use crate::error::{Error, Result};
use crate::flyout::{next_flyout, place_flyout, HoverTarget};
use crate::geometry::{Edge, LogicalPoint, LogicalRect, LogicalSize};
use crate::keynav::{handle_key, FlyoutFocus, MenuFocus, NavAction, NavKey};
use crate::menu::{Icon, Item, Menu, MenuId};
use crate::platform::{Appearance, Platform};
use crate::render::paint::{render_menu, LaidMenu};
use crate::render::RasterDrawer;
use crate::style::Color;
use crate::theme::{MenuOptions, OsFamily, Theme};
use crate::{Tray, TrayCommand};

/// Windows baseline screen DPI: 96 DPI is 100% scale (Win32
/// `USER_DEFAULT_SCREEN_DPI`); a monitor's effective DPI ÷ this is its scale.
const BASE_DPI: f32 = 96.0;

/// Typographic points per inch — for device-pixel ↔ point conversion of font
/// metrics (`GDI` reports `lfHeight` in device pixels).
const POINTS_PER_INCH: f32 = 72.0;

/// The private window message the tray icon posts back to its owner window.
const WM_TRAY_CALLBACK: u32 = WM_APP + 1;
/// The private message that asks the pump to drain the event + command inbox.
const WM_MURI_DRAIN: u32 = WM_APP + 2;
/// The notification icon's id within its owner window.
const TRAY_ICON_UID: u32 = 0x0001;
/// `GWLP_USERDATA` tag stored on the popup window.
const POPUP_TAG: isize = 1;
/// Base `GWLP_USERDATA` tag for flyout windows; a flyout at stack depth `d` is
/// tagged `FLYOUT_TAG + d` so the shared window procedure can recover its level.
const FLYOUT_TAG: isize = 2;

/// Registers the message-only owner window class exactly once per process.
/// A [`Once`] (not a swapped flag) so a second thread blocks until the first has
/// finished `RegisterClassW` — otherwise it could observe the class as
/// "registered" and `CreateWindowExW` before registration actually completed.
static TRAY_CLASS_ONCE: Once = Once::new();
/// Registers the layered-popup window class exactly once per process (same
/// register-before-observe guarantee as [`TRAY_CLASS_ONCE`]).
static POPUP_CLASS_ONCE: Once = Once::new();
/// The `RegisterWindowMessageW("TaskbarCreated")` broadcast id, resolved once at
/// install so `wnd_proc` can re-add the icon after an Explorer restart.
static TASKBAR_CREATED_MSG: AtomicU32 = AtomicU32::new(0);

/// The owner `HWND` (as an `isize`) the pump listens on, stored in a *thread-safe*
/// static so a producer on ANY thread can wake the pump with `PostMessageW`. Set
/// in the run loops alongside the thread-local [`OWNER_HWND`]. Unlike that
/// thread-local, this is readable from a foreign UIA thread — the one guarantee
/// `accesskit_windows` does not give us about `do_action` (it may fire off-thread,
/// unlike `accesskit_macos`, which is main-thread-only). `PostMessageW` is
/// documented thread-safe, so waking across the thread hop is sound.
#[cfg(feature = "a11y")]
static A11Y_OWNER: AtomicIsize = AtomicIsize::new(0);

/// Cross-thread inbox for UIA action requests raised on a foreign thread. The
/// action payload can't ride the thread-local [`EVENTS`] queue (empty on the
/// foreign thread), so it is pushed here and drained on the pump thread. Kept
/// separate from [`EVENTS`] precisely because it must be `Send`/lockable.
#[cfg(feature = "a11y")]
static A11Y_ACTIONS: std::sync::Mutex<Vec<(WindowKind, accesskit::ActionRequest)>> =
    std::sync::Mutex::new(Vec::new());

thread_local! {
    /// The single running [`AppState`], reachable from every callback and the
    /// drain. Set once in [`run_event_loop`].
    static MAIN_APP: RefCell<Option<Rc<RefCell<AppState>>>> = const { RefCell::new(None) };

    /// Pending high-level UI events, pushed by callbacks and applied by the drain.
    /// Each entry is tagged with the id of the [`PopupSession`] that owns it
    /// (#33), so a nested session's [`PopupSession::drain_events`] only consumes
    /// its own events — an enclosing session's events stay queued, untouched,
    /// until *it* drains. Without this a tray click handler that opens a nested
    /// context menu before the outer popup closes could have the outer window's
    /// events drained/applied by the nested session (wrong hover, or a click
    /// fired for a row never clicked).
    static EVENTS: RefCell<Vec<(u32, UiEvent)>> = const { RefCell::new(Vec::new()) };

    /// The owner window, so on-thread callbacks can post a drain to it.
    static OWNER_HWND: Cell<isize> = const { Cell::new(0) };

    /// Monotonically increasing counter handing out unique [`PopupSession`] ids
    /// (#33). Ids are never reused within a thread's lifetime (see
    /// [`next_session_id`]), so a stale queued event can never be misattributed
    /// to an unrelated later session.
    static NEXT_SESSION_ID: Cell<u32> = const { Cell::new(1) };

    /// The id of the innermost [`PopupSession`] currently pumping messages on
    /// this thread (`0` = none yet). Global, window-less events — the tray
    /// click, and the low-level mouse/keyboard hooks — have no `HWND` to recover
    /// a session id from, so they're attributed to whichever session is "on top"
    /// of the pump stack, mirroring how [`OWNER_HWND`] already tracks the same
    /// nesting for `WM_MURI_DRAIN` routing (#33).
    static ACTIVE_SESSION: Cell<u32> = const { Cell::new(0) };

    /// Reference-counted global low-level hooks, shared across all popup sessions
    /// on the pump thread so nested sessions don't double-install them (#34).
    static HOOKS: RefCell<HookState> =
        const { RefCell::new(HookState { mouse: null_mut(), kbd: null_mut(), refs: 0 }) };
}

/// Allocate a fresh, unique id for a new [`PopupSession`] (#33). `0` is reserved
/// for "no session yet" ([`ACTIVE_SESSION`]'s initial value), so the counter
/// starts at `1` and skips back over `0` on wraparound (practically unreachable,
/// but cheap to guard).
fn next_session_id() -> u32 {
    NEXT_SESSION_ID.with(|c| {
        let id = c.get();
        c.set(id.wrapping_add(1).max(1));
        id
    })
}

/// The id of the innermost [`PopupSession`] currently pumping on this thread, for
/// tagging a window-less [`UiEvent`] (see [`ACTIVE_SESSION`]).
fn active_session() -> u32 {
    ACTIVE_SESSION.with(|c| c.get())
}

/// Split `events` into (this session's events, in original relative order) and
/// (every other session's events, also in original relative order) (#33). Pure
/// logic behind [`take_session_events`], factored out so the session-id
/// filtering is unit-testable without a live `HWND`/message pump.
fn partition_session_events(
    events: Vec<(u32, UiEvent)>,
    session_id: u32,
) -> (Vec<UiEvent>, Vec<(u32, UiEvent)>) {
    let (mine, other): (Vec<_>, Vec<_>) = events.into_iter().partition(|(id, _)| *id == session_id);
    (mine.into_iter().map(|(_, event)| event).collect(), other)
}

/// Remove and return every queued event tagged `session_id`, leaving every other
/// session's events in [`EVENTS`] untouched and in their original relative order
/// (#33). Both [`PopupSession::drain_events`] and [`AppState::drain`] use this
/// instead of draining the whole inbox, so a nested session's drain can never
/// consume — or reorder — an enclosing session's still-pending events.
fn take_session_events(session_id: u32) -> Vec<UiEvent> {
    EVENTS.with(|e| {
        let taken = std::mem::take(&mut *e.borrow_mut());
        let (mine, other) = partition_session_events(taken, session_id);
        *e.borrow_mut() = other;
        mine
    })
}

/// The thread-shared `WH_MOUSE_LL`/`WH_KEYBOARD_LL` handles + install refcount.
struct HookState {
    mouse: HHOOK,
    kbd: HHOOK,
    refs: u32,
}

/// Encode a Rust string as a NUL-terminated UTF-16 buffer for the Win32 `*W`
/// APIs.
fn wide(s: &str) -> Vec<u16> {
    s.encode_utf16().chain(std::iter::once(0)).collect()
}

/// Enqueue a UI event tagged with the id of the [`PopupSession`] that owns it
/// (#33) and ask the pump to drain. Safe from any on-thread callback (it takes
/// no [`AppState`] borrow).
pub(super) fn push_event(session_id: u32, event: UiEvent) {
    EVENTS.with(|e| e.borrow_mut().push((session_id, event)));
    let owner = OWNER_HWND.with(|h| h.get());
    if owner != 0 {
        unsafe {
            PostMessageW(owner as HWND, WM_MURI_DRAIN, 0, 0);
        }
    }
}

/// Enqueue a UIA action request from *any* thread and wake the pump.
///
/// `accesskit_windows` may invoke its action handler on a foreign UIA thread, so
/// this deliberately avoids the thread-local [`push_event`] path: it pushes the
/// action into the thread-safe [`A11Y_ACTIONS`] inbox and posts `WM_MURI_DRAIN`
/// to the [`A11Y_OWNER`] `HWND` (thread-safe static), which the pump drains via
/// [`PopupSession::drain_a11y_actions`]. Without this, every NVDA/Narrator
/// focus/activate raised off-thread would be silently dropped.
#[cfg(feature = "a11y")]
pub(super) fn push_a11y_action(kind: WindowKind, request: accesskit::ActionRequest) {
    if let Ok(mut q) = A11Y_ACTIONS.lock() {
        q.push((kind, request));
    }
    let owner = A11Y_OWNER.load(Ordering::SeqCst);
    if owner != 0 {
        unsafe {
            PostMessageW(owner as HWND, WM_MURI_DRAIN, 0, 0);
        }
    }
}

/// Which muri window an event came from. Flyouts carry their **depth** on the open
/// stack (`0` = the first flyout, opened from the popup; `1` = its child; …) so a
/// callback can tag its events with the exact level without consulting shared
/// state (decision #8, N-level submenus) — mirroring the macOS backend.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub(super) enum WindowKind {
    /// The top-level popup anchored to the tray icon.
    Popup,
    /// An open submenu flyout at the given stack depth (`0` = first flyout).
    Flyout(usize),
}

impl WindowKind {
    /// The menu level this window renders: `0` is the top-level menu, `k` the
    /// submenu reached by descending `k` open flyouts.
    fn menu_level(self) -> usize {
        match self {
            WindowKind::Popup => 0,
            WindowKind::Flyout(depth) => depth + 1,
        }
    }

    /// The `GWLP_USERDATA` tag identifying this window's kind + depth, so the
    /// shared `wnd_proc` can recover the exact stack level from an `HWND`. This
    /// tag alone is *not* unique across nested [`PopupSession`]s (every popup is
    /// tagged `POPUP_TAG` regardless of which session opened it) — see
    /// [`packed_tag`], which additionally encodes the owning session's id.
    fn tag(self) -> isize {
        match self {
            WindowKind::Popup => POPUP_TAG,
            WindowKind::Flyout(depth) => FLYOUT_TAG + depth as isize,
        }
    }
}

/// Pack a window's [`WindowKind`] tag together with its owning [`PopupSession`]'s
/// id (#33) into the single `GWLP_USERDATA` slot: the low 32 bits hold the kind
/// tag (as before #33), the high 32 bits hold the session id. Both halves are
/// small, always-non-negative values, so the packing is exact and lossless —
/// relies on `isize` being 64-bit, true of the `x86_64-pc-windows-msvc` target
/// this backend compiles for (see the module doc comment).
fn packed_tag(kind: WindowKind, session_id: u32) -> isize {
    (((session_id as u64) << 32) | (kind.tag() as u64)) as isize
}

/// A translated, backend-neutral UI event awaiting application on the drain.
pub(super) enum UiEvent {
    /// The tray icon was left-clicked — toggle the popup.
    TrayClicked,
    /// The pointer moved over a window (window-local logical points).
    MouseMoved {
        /// Which window.
        kind: WindowKind,
        /// X in the window's logical points.
        x: f32,
        /// Y in the window's logical points.
        y: f32,
    },
    /// A left mouse-up (a click) landed on a window.
    MouseClick {
        /// Which window.
        kind: WindowKind,
        /// X in the window's logical points.
        x: f32,
        /// Y in the window's logical points.
        y: f32,
    },
    /// A navigation key was pressed (observed by the global keyboard hook).
    Key(NavKey),
    /// A system-wide mouse-down at a physical screen point (from `WH_MOUSE_LL`).
    /// The drain dismisses the stack if it lands outside every muri window.
    GlobalMouseDown {
        /// Physical screen x.
        x: i32,
        /// Physical screen y.
        y: i32,
    },
    /// The application lost activation (`WM_ACTIVATEAPP` false) — dismiss.
    AppDeactivated,
    // UIA action requests do NOT ride this (thread-local) queue: `do_action` may
    // fire on a foreign UIA thread, so they travel through the thread-safe
    // [`A11Y_ACTIONS`] inbox and [`push_a11y_action`] instead.
}

/// Extract the signed `(x, y)` from an `LPARAM`-packed point (client pixels).
fn lparam_xy(lparam: LPARAM) -> (i32, i32) {
    let x = (lparam & 0xFFFF) as i16 as i32;
    let y = ((lparam >> 16) & 0xFFFF) as i16 as i32;
    (x, y)
}

/// The `(WindowKind, owning session id)` tagged on a window via `GWLP_USERDATA`
/// ([`packed_tag`]), or `None` for the message-only owner window (untagged) or
/// an unrecognized tag. The session id is what lets [`PopupSession::drain_events`]
/// tell nested sessions' events apart (#33).
fn window_kind(hwnd: HWND) -> Option<(WindowKind, u32)> {
    let raw = unsafe { GetWindowLongPtrW(hwnd, GWLP_USERDATA) } as u64;
    let session_id = (raw >> 32) as u32;
    let tag = (raw & 0xFFFF_FFFF) as isize;
    let kind = match tag {
        POPUP_TAG => WindowKind::Popup,
        n if n >= FLYOUT_TAG => WindowKind::Flyout((n - FLYOUT_TAG) as usize),
        _ => return None,
    };
    Some((kind, session_id))
}

/// The shared window procedure for the owner, popup, and flyout windows. Every
/// arm is tiny: it translates a native message into a [`UiEvent`] (or drains),
/// never touching [`AppState`] except through the serialized drain.
unsafe extern "system" fn wnd_proc(
    hwnd: HWND,
    msg: u32,
    wparam: WPARAM,
    lparam: LPARAM,
) -> LRESULT {
    match msg {
        WM_MURI_DRAIN => {
            let app = MAIN_APP.with(|slot| slot.borrow().clone());
            if let Some(app) = app {
                if let Ok(mut state) = app.try_borrow_mut() {
                    state.drain();
                }
            }
            0
        }
        WM_TRAY_CALLBACK => {
            // The low word of lParam carries the actual mouse message. This
            // fires on the owner window (no per-session `HWND` tag), so it's
            // attributed to whichever session is innermost/active (#33).
            if (lparam & 0xFFFF) as u32 == WM_LBUTTONUP {
                push_event(active_session(), UiEvent::TrayClicked);
            }
            0
        }
        WM_MOUSEMOVE => {
            if let Some((kind, session_id)) = window_kind(hwnd) {
                let (x, y) = to_logical_client(hwnd, lparam_xy(lparam));
                push_event(session_id, UiEvent::MouseMoved { kind, x, y });
            }
            0
        }
        WM_LBUTTONUP => {
            if let Some((kind, session_id)) = window_kind(hwnd) {
                let (x, y) = to_logical_client(hwnd, lparam_xy(lparam));
                push_event(session_id, UiEvent::MouseClick { kind, x, y });
            }
            0
        }
        WM_ACTIVATEAPP => {
            if wparam == 0 {
                // Window-less (fires on the owner window): attribute to the
                // active session, same as `WM_TRAY_CALLBACK` above (#33).
                push_event(active_session(), UiEvent::AppDeactivated);
            }
            0
        }
        _ if msg != 0 && msg == TASKBAR_CREATED_MSG.load(Ordering::SeqCst) => {
            // Explorer restarted; re-add our icon (spec 21 §1).
            let app = MAIN_APP.with(|slot| slot.borrow().clone());
            if let Some(app) = app {
                if let Ok(mut state) = app.try_borrow_mut() {
                    if let Anchor::Tray(a) = &mut state.session.anchor {
                        // Re-add is best-effort in this broadcast handler: a
                        // `wnd_proc` cannot surface an error to a caller, and a
                        // failed re-add simply leaves the icon absent until the
                        // next `TaskbarCreated` broadcast retries it. Hence the
                        // `Result` is intentionally discarded (not silently
                        // swallowed).
                        let _ = a.readd();
                    }
                }
            }
            0
        }
        _ => DefWindowProcW(hwnd, msg, wparam, lparam),
    }
}

/// Convert a window-local physical-pixel client point to the window's logical
/// coordinates (points), using the window's own DPI.
fn to_logical_client(hwnd: HWND, (x, y): (i32, i32)) -> (f32, f32) {
    let dpi = unsafe { GetDpiForWindow(hwnd) };
    let scale = if dpi == 0 { 1.0 } else { dpi as f32 / BASE_DPI };
    (x as f32 / scale, y as f32 / scale)
}

/// Global low-level mouse hook: marshal every system-wide button-down point to
/// the drain, which decides dismissal (point-in-any-window). Does *zero* work
/// beyond posting, so it can never exceed the low-level-hook timeout.
///
// DEVICE-VERIFY(0.9.0): the hook only fires against real system input; the
// point-in-any-window decision it feeds is unit-tested here, but the hook
// installation/latency itself needs a Windows box.
unsafe extern "system" fn mouse_hook_proc(code: i32, wparam: WPARAM, lparam: LPARAM) -> LRESULT {
    if code == HC_ACTION as i32 {
        let msg = wparam as u32;
        if msg == WM_LBUTTONDOWN || msg == WM_RBUTTONDOWN {
            let data = &*(lparam as *const MSLLHOOKSTRUCT);
            // System-wide, window-less: attribute to the active session (#33).
            push_event(
                active_session(),
                UiEvent::GlobalMouseDown {
                    x: data.pt.x,
                    y: data.pt.y,
                },
            );
        }
    }
    CallNextHookEx(null_mut(), code, wparam, lparam)
}

/// Global low-level keyboard hook: translate menu-nav key-downs to [`NavKey`]s
/// while a popup is open (a `WS_EX_NOACTIVATE` popup does not receive `WM_KEYDOWN`
/// itself). Observes but never consumes keys.
///
// DEVICE-VERIFY(0.9.0): keyboard delivery to a non-activating popup is the
// same "needs keys but never focused" bind macOS hits; the low-level hook is the
// specified resolution but can only be exercised on a device.
unsafe extern "system" fn kbd_hook_proc(code: i32, wparam: WPARAM, lparam: LPARAM) -> LRESULT {
    if code == HC_ACTION as i32 && wparam as u32 == WM_KEYDOWN {
        let data = &*(lparam as *const KBDLLHOOKSTRUCT);
        if let Some(key) = input::translate_vk(data.vkCode as u16) {
            // System-wide, window-less: attribute to the active session (#33).
            push_event(active_session(), UiEvent::Key(key));
        }
    }
    CallNextHookEx(null_mut(), code, wparam, lparam)
}

// =============================================================================
// Icon decode: muri PNG `Icon` → HICON
// =============================================================================

/// Decode a muri PNG [`Icon`] into an `HICON` at `size`×`size` device pixels
/// (scaled with nearest-neighbour), or `None` for non-PNG icons / bad bytes.
///
/// Builds a 32-bit top-down straight-alpha BGRA color bitmap plus a monochrome
/// mask, then `CreateIconIndirect`; the returned `HICON` owns its own copy, so
/// both source bitmaps are deleted before returning (spec 21 §1).
///
/// # Safety
/// Calls raw GDI; the returned handle (if any) must be freed with `DestroyIcon`.
unsafe fn decode_hicon(icon: &Icon, size: i32) -> Option<HICON> {
    let bytes = match icon {
        Icon::Png(bytes) | Icon::Svg(bytes) => bytes,
        _ => return None,
    };
    let (rgba, src_w, src_h) = crate::render::decode_icon_bytes(bytes)?;
    let (sw, sh) = (src_w as i32, src_h as i32);
    if sw == 0 || sh == 0 || size <= 0 {
        return None;
    }
    let src = &rgba[..];

    let screen_dc = GetDC(null_mut());
    if screen_dc.is_null() {
        return None;
    }
    let mut bmi: BITMAPINFO = std::mem::zeroed();
    bmi.bmiHeader = BITMAPINFOHEADER {
        biSize: std::mem::size_of::<BITMAPINFOHEADER>() as u32,
        biWidth: size,
        biHeight: -size, // top-down
        biPlanes: 1,
        biBitCount: 32,
        biCompression: BI_RGB,
        biSizeImage: 0,
        biXPelsPerMeter: 0,
        biYPelsPerMeter: 0,
        biClrUsed: 0,
        biClrImportant: 0,
    };
    let mut bits: *mut core::ffi::c_void = null_mut();
    let color = CreateDIBSection(screen_dc, &bmi, DIB_RGB_COLORS, &mut bits, null_mut(), 0);
    ReleaseDC(null_mut(), screen_dc);
    if color.is_null() || bits.is_null() {
        if !color.is_null() {
            DeleteObject(color as HGDIOBJ);
        }
        return None;
    }

    // Nearest-neighbour scale into straight-alpha BGRA. `decode_png` already
    // yields straight-alpha RGBA, so this is just the R/B channel swap.
    let dst = std::slice::from_raw_parts_mut(bits.cast::<u8>(), (size * size * 4) as usize);
    for row in 0..size {
        for col in 0..size {
            let sx = (col * sw / size).clamp(0, sw - 1);
            let sy = (row * sh / size).clamp(0, sh - 1);
            let s = ((sy * sw + sx) * 4) as usize;
            let d = ((row * size + col) * 4) as usize;
            let a = src[s + 3];
            let (r, g, b) = if a == 0 {
                (0, 0, 0)
            } else {
                (src[s], src[s + 1], src[s + 2])
            };
            dst[d] = b;
            dst[d + 1] = g;
            dst[d + 2] = r;
            dst[d + 3] = a;
        }
    }

    // A same-size monochrome mask (zeros): 32-bit alpha carries transparency, so
    // the AND mask is inert, but `CreateIconIndirect` still requires one.
    let mask = CreateBitmap(size, size, 1, 1, std::ptr::null());
    if mask.is_null() {
        DeleteObject(color as HGDIOBJ);
        return None;
    }

    let info = ICONINFO {
        fIcon: 1,
        xHotspot: 0,
        yHotspot: 0,
        hbmMask: mask,
        hbmColor: color,
    };
    let hicon = CreateIconIndirect(&info);
    DeleteObject(color as HGDIOBJ);
    DeleteObject(mask as HGDIOBJ);
    if hicon.is_null() {
        None
    } else {
        Some(hicon)
    }
}

// =============================================================================
// Anchor geometry
// =============================================================================

/// The tray icon's physical geometry resolved against the monitor it sits on, in
/// one shared logical space (physical pixels ÷ DPI scale) so [`place_popup`] and
/// [`place_flyout`] can work in the exact same coordinates the macOS backend
/// uses. [`WinGeometry::to_physical`] converts a logical origin back to physical
/// pixels for window placement.
#[derive(Clone, Copy)]
struct WinGeometry {
    /// Anchor rect (physical pixels, virtual-screen space).
    anchor: RECT,
    /// The anchor monitor's work area (physical pixels).
    work: RECT,
    /// Logical pixels per physical pixel's inverse (physical / scale = logical).
    scale: f32,
}

impl WinGeometry {
    fn anchor_rect_local(&self) -> LogicalRect {
        self.rect_local(&self.anchor)
    }

    fn work_area_local(&self) -> LogicalRect {
        self.rect_local(&self.work)
    }

    fn rect_local(&self, r: &RECT) -> LogicalRect {
        LogicalRect::new(
            LogicalPoint::new(r.left as f32 / self.scale, r.top as f32 / self.scale),
            LogicalSize::new(
                (r.right - r.left) as f32 / self.scale,
                (r.bottom - r.top) as f32 / self.scale,
            ),
        )
    }

    /// A logical top-left origin back to a physical screen point.
    fn to_physical(self, origin: LogicalPoint) -> (i32, i32) {
        (
            (origin.x * self.scale).round() as i32,
            (origin.y * self.scale).round() as i32,
        )
    }

    /// Resolve a caller-supplied logical anchor `rect` against the monitor it lands
    /// on, producing the same shared-logical geometry the tray path uses — the
    /// anchor geometry for a pointer/rect-anchored [`ContextMenu`](crate::ContextMenu)
    /// / [`Popup`](crate::Popup) that has no tray icon (spec 21 §3).
    ///
    // DEVICE-VERIFY(0.9.0): multi-monitor point resolution. The first
    // logical->physical conversion uses the *system* DPI to find the monitor, then
    // snaps to that monitor's effective DPI; a secondary display with a different
    // scale needs a real multi-monitor box to confirm the anchor lands on (and
    // flips against) the right monitor — the same fragility the macOS `for_rect`
    // carries.
    fn for_rect(rect: LogicalRect) -> Option<WinGeometry> {
        let sys_dpi = unsafe { GetDpiForSystem() };
        let sys_scale = if sys_dpi == 0 {
            1.0
        } else {
            sys_dpi as f32 / BASE_DPI
        };
        let to_phys = |scale: f32| RECT {
            left: (rect.origin.x * scale).round() as i32,
            top: (rect.origin.y * scale).round() as i32,
            right: ((rect.origin.x + rect.size.width) * scale).round() as i32,
            bottom: ((rect.origin.y + rect.size.height) * scale).round() as i32,
        };

        let probe = to_phys(sys_scale);
        let hmon = unsafe { MonitorFromRect(&probe, MONITOR_DEFAULTTONEAREST) };
        if hmon.is_null() {
            return None;
        }

        // Snap to the resolved monitor's effective DPI so the stored physical
        // anchor and `to_physical`/`rect_local` round-trip stay self-consistent.
        let mut dpi_x: u32 = 96;
        let mut dpi_y: u32 = 96;
        let scale = if unsafe { GetDpiForMonitor(hmon, MDT_EFFECTIVE_DPI, &mut dpi_x, &mut dpi_y) }
            == S_OK
            && dpi_x != 0
        {
            dpi_x as f32 / BASE_DPI
        } else {
            sys_scale
        };
        let anchor = to_phys(scale);

        let mut mi: MONITORINFO = unsafe { std::mem::zeroed() };
        mi.cbSize = std::mem::size_of::<MONITORINFO>() as u32;
        let work = if unsafe { GetMonitorInfoW(hmon, &mut mi) } != 0 {
            mi.rcWork
        } else {
            RECT {
                left: 0,
                top: 0,
                right: (1440.0 * scale) as i32,
                bottom: (900.0 * scale) as i32,
            }
        };

        Some(WinGeometry {
            anchor,
            work,
            scale,
        })
    }
}

// =============================================================================
// The notification-area anchor
// =============================================================================

/// The Windows notification-area anchor. Owns the message-only window, the
/// registered icon, and the current `HICON` until dropped.
pub struct WindowsAnchor {
    /// The message-only window that owns the notification icon.
    hwnd: HWND,
    /// Whether the icon is currently registered (so `Drop` can remove it).
    installed: bool,
    /// The current tooltip, retained so a `TaskbarCreated` re-add keeps it.
    tooltip: Option<String>,
    /// The live `HICON` (destroyed on replacement / drop), and the `Arc` bytes it
    /// was decoded from so `set_icon` on a tick can skip re-decoding. The retained
    /// `Arc` (not a bare pointer value) is what makes the skip sound: it keeps the
    /// source allocation alive so a freed-and-reused address can't be mistaken for
    /// the same icon (ABA), and it is compared with [`Arc::ptr_eq`].
    hicon: HICON,
    icon_bytes: Option<std::sync::Arc<[u8]>>,
}

impl std::fmt::Debug for WindowsAnchor {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("WindowsAnchor")
            .field("installed", &self.installed)
            .finish()
    }
}

impl Default for WindowsAnchor {
    fn default() -> Self {
        Self::new()
    }
}

impl WindowsAnchor {
    /// Create the (not-yet-installed) Windows anchor.
    pub fn new() -> Self {
        WindowsAnchor {
            hwnd: null_mut(),
            installed: false,
            tooltip: None,
            hicon: null_mut(),
            icon_bytes: None,
        }
    }

    /// Create the message-only window that owns the notification icon.
    unsafe fn create_message_window(&mut self) -> Result<()> {
        let hinstance = GetModuleHandleW(null_mut());
        let class_name = wide("muri_tray_msgwnd");

        TRAY_CLASS_ONCE.call_once(|| unsafe {
            let mut wc: WNDCLASSW = std::mem::zeroed();
            wc.lpfnWndProc = Some(wnd_proc);
            wc.hInstance = hinstance;
            wc.lpszClassName = class_name.as_ptr();
            RegisterClassW(&wc);
        });

        let hwnd = CreateWindowExW(
            0,
            class_name.as_ptr(),
            null_mut(),
            0,
            0,
            0,
            0,
            0,
            HWND_MESSAGE,
            null_mut(),
            hinstance,
            null_mut(),
        );
        if hwnd.is_null() {
            return Err(Error::TrayInstall(
                "could not create tray message window".into(),
            ));
        }
        self.hwnd = hwnd;
        Ok(())
    }

    /// The `NOTIFYICONIDENTIFIER` naming this anchor's icon.
    fn identifier(&self) -> NOTIFYICONIDENTIFIER {
        let mut id: NOTIFYICONIDENTIFIER = unsafe { std::mem::zeroed() };
        id.cbSize = std::mem::size_of::<NOTIFYICONIDENTIFIER>() as u32;
        id.hWnd = self.hwnd;
        id.uID = TRAY_ICON_UID;
        id
    }

    /// A zeroed `NOTIFYICONDATAW` pre-filled with this anchor's identity.
    fn base_nid(&self) -> NOTIFYICONDATAW {
        let mut nid: NOTIFYICONDATAW = unsafe { std::mem::zeroed() };
        nid.cbSize = std::mem::size_of::<NOTIFYICONDATAW>() as u32;
        nid.hWnd = self.hwnd;
        nid.uID = TRAY_ICON_UID;
        nid
    }

    /// Copy a tooltip string into a `szTip` array (NUL-terminated, clamped).
    ///
    /// Reserve the last slot so a NUL terminator always remains: [`base_nid`]
    /// zero-initializes the array, so leaving `dst[n..]` untouched keeps it `0`.
    /// Without this, a tooltip encoding to ≥128 UTF-16 units would fill every
    /// slot and Win32 would read past `szTip`.
    fn fill_tip(tip: &str, dst: &mut [u16; 128]) {
        let src = wide(tip);
        let n = src.len().min(dst.len() - 1);
        dst[..n].copy_from_slice(&src[..n]);
    }

    /// Replace the live `HICON` from an [`Icon`] (skips re-decode when the same
    /// `Arc` bytes are passed again), returning the handle to store in `hIcon`.
    ///
    /// Surfaces decode failure honestly: undecodable `Icon::Png` bytes yield
    /// `Err(Error::BadIcon(..))` rather than silently substituting a stock/blank
    /// icon while the caller believes the requested icon was set. Non-raster kinds
    /// (`Svg`/`Checkmark`/`Symbol`) have no tray `HICON`; they resolve to a null
    /// handle (no tray image), which is not a decode failure.
    unsafe fn resolve_hicon(&mut self, icon: &Icon) -> Result<HICON> {
        // Fast path: the same PNG bytes passed again (e.g. an unchanged icon on a
        // ~0.75s menu tick) skip the re-decode. Guarded by `Arc::ptr_eq` on the
        // *retained* Arc, never a bare pointer value: a freed-and-reused
        // allocation could otherwise land different bytes at the same address and
        // return a stale HICON for the previous icon (ABA).
        if let Icon::Png(bytes) = icon {
            if !self.hicon.is_null()
                && self
                    .icon_bytes
                    .as_ref()
                    .is_some_and(|b| std::sync::Arc::ptr_eq(b, bytes))
            {
                return Ok(self.hicon);
            }
        }
        let new = match icon {
            Icon::Png(_) => decode_hicon(icon, 16)
                .ok_or_else(|| Error::BadIcon("could not decode PNG tray icon bytes".into()))?,
            Icon::Svg(_) => decode_hicon(icon, 16)
                .ok_or_else(|| Error::BadIcon("could not rasterize SVG tray icon bytes".into()))?,
            _ => null_mut(),
        };
        if !self.hicon.is_null() {
            DestroyIcon(self.hicon);
        }
        self.hicon = new;
        self.icon_bytes = match icon {
            Icon::Png(bytes) => Some(std::sync::Arc::clone(bytes)),
            _ => None,
        };
        Ok(new)
    }

    fn install(&mut self, icon: &Icon, tooltip: Option<&str>) -> Result<()> {
        unsafe {
            // Decode the icon *before* creating any window or registering the
            // notification icon, so an undecodable icon fails cleanly (with no
            // window to tear down) and the caller learns the icon was rejected
            // rather than seeing a silent blank-icon "success".
            let hicon = self.resolve_hicon(icon)?;

            self.create_message_window()?;
            self.tooltip = tooltip.map(str::to_owned);

            let mut nid = self.base_nid();
            nid.uFlags = NIF_ICON | NIF_MESSAGE | NIF_TIP;
            nid.uCallbackMessage = WM_TRAY_CALLBACK;
            nid.hIcon = hicon;
            if let Some(tip) = tooltip {
                Self::fill_tip(tip, &mut nid.szTip);
            }

            // `Shell_NotifyIconW` returns a `BOOL`: nonzero on success. A zero
            // return means `NIM_ADD` did not register the icon, so undo the window
            // and surface the failure instead of leaving `installed` false while
            // reporting success.
            if Shell_NotifyIconW(NIM_ADD, &nid) == 0 {
                let _ = DestroyWindow(self.hwnd);
                self.hwnd = null_mut();
                return Err(Error::TrayInstall(
                    "Shell_NotifyIcon(NIM_ADD) failed".into(),
                ));
            }
            self.installed = true;
        }
        Ok(())
    }

    /// Re-add the icon after an Explorer (`TaskbarCreated`) restart.
    fn readd(&mut self) -> Result<()> {
        if self.hwnd.is_null() {
            return Ok(());
        }
        unsafe {
            let mut nid = self.base_nid();
            nid.uFlags = NIF_ICON | NIF_MESSAGE | NIF_TIP;
            nid.uCallbackMessage = WM_TRAY_CALLBACK;
            nid.hIcon = self.hicon;
            if let Some(tip) = self.tooltip.clone() {
                Self::fill_tip(&tip, &mut nid.szTip);
            }
            if Shell_NotifyIconW(NIM_ADD, &nid) == 0 {
                return Err(Error::TrayInstall("Shell_NotifyIcon re-add failed".into()));
            }
            self.installed = true;
        }
        Ok(())
    }

    /// Replace the tray icon (`NIM_MODIFY`).
    fn set_icon(&mut self, icon: &Icon) {
        if !self.installed {
            return;
        }
        unsafe {
            // On undecodable bytes, keep the current icon rather than clearing it
            // to a blank handle: the async `SetIcon` command has no channel to
            // report an error, and silently substituting a wrong/blank icon would
            // be the very bug FIX 4 removes from the `install` path.
            let Ok(hicon) = self.resolve_hicon(icon) else {
                return;
            };
            let mut nid = self.base_nid();
            nid.uFlags = NIF_ICON;
            nid.hIcon = hicon;
            Shell_NotifyIconW(NIM_MODIFY, &nid);
        }
    }

    /// Replace the tooltip / accessible name (`NIM_MODIFY`).
    fn set_tooltip(&mut self, tooltip: Option<&str>) {
        self.tooltip = tooltip.map(str::to_owned);
        if !self.installed {
            return;
        }
        unsafe {
            let mut nid = self.base_nid();
            nid.uFlags = NIF_TIP;
            if let Some(tip) = tooltip {
                Self::fill_tip(tip, &mut nid.szTip);
            }
            Shell_NotifyIconW(NIM_MODIFY, &nid);
        }
    }

    /// Show or hide the status item (`NIM_MODIFY` with `NIF_STATE`).
    fn set_visible(&self, visible: bool) {
        if !self.installed {
            return;
        }
        unsafe {
            let mut nid = self.base_nid();
            nid.uFlags = NIF_STATE;
            nid.dwStateMask = NIS_HIDDEN;
            nid.dwState = if visible { 0 } else { NIS_HIDDEN };
            Shell_NotifyIconW(NIM_MODIFY, &nid);
        }
    }

    /// Resolve the anchor + its monitor's work area into one logical space.
    fn geometry(&self) -> Option<WinGeometry> {
        if !self.installed {
            return None;
        }
        let dpi = unsafe { GetDpiForWindow(self.hwnd) };
        let scale = if dpi == 0 { 1.0 } else { dpi as f32 / BASE_DPI };

        let id = self.identifier();
        let mut anchor: RECT = unsafe { std::mem::zeroed() };
        let ok = unsafe { Shell_NotifyIconGetRect(&id, &mut anchor) } == S_OK;
        if !ok {
            // DEVICE-VERIFY(0.9.0): under the overflow ("hidden icons") flyout,
            // `Shell_NotifyIconGetRect` returns the chevron rect or fails; fall
            // back to a cursor-anchored open (spec 21 §2, risk #4).
            let mut pt: POINT = unsafe { std::mem::zeroed() };
            if unsafe { windows_sys::Win32::UI::WindowsAndMessaging::GetCursorPos(&mut pt) } == 0 {
                return None;
            }
            anchor = RECT {
                left: pt.x,
                top: pt.y,
                right: pt.x + 1,
                bottom: pt.y + 1,
            };
        }

        let hmon = unsafe { MonitorFromRect(&anchor, MONITOR_DEFAULTTONEAREST) };
        let mut mi: MONITORINFO = unsafe { std::mem::zeroed() };
        mi.cbSize = std::mem::size_of::<MONITORINFO>() as u32;
        let work = if !hmon.is_null() && unsafe { GetMonitorInfoW(hmon, &mut mi) } != 0 {
            mi.rcWork
        } else {
            // Fall back to a generous default rect so placement still clamps.
            RECT {
                left: 0,
                top: 0,
                right: (1440.0 * scale) as i32,
                bottom: (900.0 * scale) as i32,
            }
        };

        Some(WinGeometry {
            anchor,
            work,
            scale,
        })
    }

    /// The tray icon's physical screen rect straight from
    /// `Shell_NotifyIconGetRect`, or `None` when it can't be resolved (e.g. the
    /// icon lives in the overflow "hidden icons" flyout). Unlike [`geometry`],
    /// this never falls back to the cursor — a caller hit-testing a global mouse
    /// click against the icon needs the icon's *actual* location or nothing.
    ///
    /// [`geometry`]: WindowsAnchor::geometry
    fn icon_rect_physical(&self) -> Option<RECT> {
        if !self.installed {
            return None;
        }
        let id = self.identifier();
        let mut rect: RECT = unsafe { std::mem::zeroed() };
        if unsafe { Shell_NotifyIconGetRect(&id, &mut rect) } == S_OK {
            Some(rect)
        } else {
            None
        }
    }

    fn anchor_rect(&self) -> Result<LogicalRect> {
        self.geometry()
            .map(|g| g.anchor_rect_local())
            .ok_or_else(|| Error::Platform("tray icon not installed".into()))
    }

    fn work_area(&self) -> Result<LogicalRect> {
        self.geometry()
            .map(|g| g.work_area_local())
            .ok_or_else(|| Error::Platform("tray icon not installed".into()))
    }

    fn supports_tray_anchor(&self) -> bool {
        true
    }

    /// Where a popup of `popup` size should open, anchored to the tray icon and
    /// clamped into `work_area`. Retained for API parity with the shared
    /// [`place_popup`]; the live loop resolves placement through
    /// `WindowsAnchor::geometry` so it shares the exact math macOS uses. Taskbars
    /// usually sit at the bottom, so the popup grows up from the icon
    /// ([`Edge::Top`]).
    pub fn popup_origin(&self, popup: LogicalSize, work_area: LogicalRect) -> Result<LogicalPoint> {
        let anchor = self.anchor_rect()?;
        Ok(place_popup(anchor, popup, work_area, Edge::Top, 2.0))
    }
}

impl Drop for WindowsAnchor {
    fn drop(&mut self) {
        unsafe {
            if self.installed {
                let nid = self.base_nid();
                Shell_NotifyIconW(NIM_DELETE, &nid);
            }
            if !self.hicon.is_null() {
                DestroyIcon(self.hicon);
            }
            if !self.hwnd.is_null() {
                let _ = DestroyWindow(self.hwnd);
            }
        }
    }
}

// =============================================================================
// Anchor
// =============================================================================

/// Where a session's popup anchors: the live tray icon (which also owns icon /
/// tooltip / visibility) or a fixed rectangle for a pointer-anchored
/// [`ContextMenu`](crate::ContextMenu) / [`Popup`](crate::Popup) (spec 21 §3).
/// [`Tray`], `ContextMenu`, and `Popup` all drive one [`PopupSession`]; they differ
/// only in how the anchor rectangle is obtained.
enum Anchor {
    /// The `Shell_NotifyIcon` tray anchor (its geometry follows the icon).
    Tray(WindowsAnchor),
    /// A fixed anchor rectangle, resolved once against its monitor.
    Fixed(WinGeometry),
}

impl Anchor {
    /// The current anchor geometry (anchor + work rects + scale).
    fn geometry(&self) -> Option<WinGeometry> {
        match self {
            Anchor::Tray(a) => a.geometry(),
            Anchor::Fixed(g) => Some(*g),
        }
    }
}

// =============================================================================
// Panels + app state
// =============================================================================

/// A live popup or flyout window: its `HWND`, the raster drawer that paints it,
/// its layout / hover state, and its physical top-left.
struct Panel {
    hwnd: HWND,
    drawer: RasterDrawer,
    laid: Option<LaidMenu>,
    cursor: LogicalPoint,
    hovered: Option<usize>,
    /// Top-left origin in the shared logical space (for `place_flyout`).
    origin: LogicalPoint,
    /// Physical top-left, where the layered blit positions the window.
    px: i32,
    py: i32,
    #[cfg(feature = "a11y")]
    adapter: accesskit_windows::SubclassingAdapter,
    #[cfg(feature = "a11y")]
    snapshot: Rc<RefCell<a11y::A11ySnapshot>>,
}

impl Panel {
    fn destroy(&self) {
        unsafe {
            DestroyWindow(self.hwnd);
        }
    }

    /// The window's on-screen rectangle in physical pixels, for hit-testing a
    /// global mouse-down.
    fn phys_rect(&self) -> (i32, i32, i32, i32) {
        let mut r: RECT = unsafe { std::mem::zeroed() };
        if unsafe { GetWindowRect(self.hwnd, &mut r) } != 0 {
            (r.left, r.top, r.right, r.bottom)
        } else {
            (0, 0, 0, 0)
        }
    }
}

/// One open flyout level: the row (within its parent level's menu) it opened from,
/// and its native window. Level `k` of [`PopupSession::flyouts`] is window depth
/// `k` ([`WindowKind::Flyout`]) and its menu is
/// [`PopupSession::menu_at_level`]`(k + 1)`. Mirrors the macOS `Flyout`.
struct Flyout {
    /// Item index (within the parent level's menu) this flyout opened from.
    parent: usize,
    /// The flyout's native window.
    panel: Panel,
}

/// The shared popup machinery: the top-level popup, the **stack** of open flyout
/// windows (decision #8), the global hooks that drive dismissal + keyboard nav,
/// and everything needed to render/anchor them. [`Tray`],
/// [`ContextMenu`](crate::ContextMenu), and [`Popup`](crate::Popup) all drive one
/// of these; they differ only in how the anchor rectangle is obtained
/// ([`Anchor`]) — spec 21 §3. This is the Windows analogue of the macOS
/// `PopupSession`.
///
/// The click handler is stored as a `Box<dyn Fn + 'a>`: the tray uses a `'static`
/// handler owned for the whole run loop; a context menu borrows the caller's
/// handler for the duration of its blocking `open_at` / `anchored_to` call.
struct PopupSession<'a> {
    /// This session's unique id (#33), allocated by [`next_session_id`]. Tags
    /// every window this session opens ([`packed_tag`]) and every [`UiEvent`]
    /// that originates from it, so nested sessions' events never conflate.
    session_id: u32,
    /// The top-level menu; source of truth for rendering + a11y.
    menu: Menu,
    options: MenuOptions,
    /// Row-activation sink; dispatches the activated [`MenuId`].
    dispatch: Box<dyn Fn(&MenuId) + 'a>,
    /// How the popup anchors (tray icon or a fixed rect).
    anchor: Anchor,
    /// Which edge the popup grows from relative to its anchor.
    edge: Edge,
    hinstance: windows_sys::Win32::Foundation::HINSTANCE,
    popup: Option<Panel>,
    /// The open flyout window stack, shallowest first (decision #8).
    flyouts: Vec<Flyout>,
    /// The global hooks, live only while a popup is open.
    mouse_hook: HHOOK,
    kbd_hook: HHOOK,
}

impl PopupSession<'_> {
    /// The resolved theme for the current appearance.
    fn theme(&self) -> Theme {
        // Resolve against the host family (Windows) + live appearance; a
        // `System(..)` source additionally gets the live accent, the Segoe UI
        // face/size, and opaque-when-transparency-disabled. Explicit family /
        // preset / custom themes render as authored. (Live per-app menu text
        // colors would need WinRT `UISettings`; the tuned Win11 base palette
        // covers dark/light for now — noted follow-up.)
        let mut theme = self
            .options
            .theme
            .resolve(OsFamily::Windows, system_is_dark());
        if self.options.theme.injects_system() {
            if let Some((r, g, b, a)) = system_accent() {
                theme.accent = Color::Rgba(r, g, b, a);
            }
            if let Some(font) = read_system_menu_font() {
                font.apply_size_to(&mut theme);
            }
            if !transparency_enabled() {
                theme.make_opaque();
            }
        }
        theme
    }

    /// The menu shown at the given level: `0` is the top-level menu, `k` the
    /// submenu reached by descending the first `k` open flyouts' parents. Returns
    /// `None` if a parent along the way is no longer a submenu (e.g. the menu was
    /// swapped underneath an open flyout). Borrows straight out of [`self.menu`]
    /// (no clone), mirroring the macOS `menu_at_level`.
    ///
    /// [`self.menu`]: PopupSession::menu
    fn menu_at_level(&self, level: usize) -> Option<&Menu> {
        crate::menu::descend(
            &self.menu,
            self.flyouts.iter().take(level).map(|f| f.parent),
        )
    }

    fn panel(&self, kind: WindowKind) -> Option<&Panel> {
        match kind {
            WindowKind::Popup => self.popup.as_ref(),
            WindowKind::Flyout(d) => self.flyouts.get(d).map(|f| &f.panel),
        }
    }

    fn panel_mut(&mut self, kind: WindowKind) -> Option<&mut Panel> {
        match kind {
            WindowKind::Popup => self.popup.as_mut(),
            WindowKind::Flyout(d) => self.flyouts.get_mut(d).map(|f| &mut f.panel),
        }
    }

    /// The open-flyout parent stack ([`next_flyout`]'s representation).
    fn flyout_stack(&self) -> Vec<usize> {
        self.flyouts.iter().map(|f| f.parent).collect()
    }

    /// Rebuild the current keyboard/mouse selection from the windows' hovered rows.
    fn current_focus(&self) -> MenuFocus {
        MenuFocus {
            top: self.popup.as_ref().and_then(|p| p.hovered),
            flyout: self
                .flyouts
                .iter()
                .map(|f| FlyoutFocus {
                    parent: f.parent,
                    child: f.panel.hovered,
                })
                .collect(),
        }
    }

    // -- hooks ---------------------------------------------------------------

    /// Install the global low-level hooks, **reference-counted per thread** (#34).
    /// Low-level hooks are per-thread and every popup session shares the one pump
    /// thread, so nested sessions must share a single `WH_MOUSE_LL`/`WH_KEYBOARD_LL`
    /// pair — otherwise each session installs its own and every system input event
    /// is delivered (and enqueued) twice. This session takes one ref; the actual
    /// `SetWindowsHookExW` runs only on the 0→1 transition.
    fn install_hooks(&mut self) {
        if !self.mouse_hook.is_null() {
            return; // this session already holds a ref (idempotent per session)
        }
        let hinstance = self.hinstance;
        HOOKS.with(|h| {
            let mut h = h.borrow_mut();
            if h.refs == 0 {
                h.mouse =
                    unsafe { SetWindowsHookExW(WH_MOUSE_LL, Some(mouse_hook_proc), hinstance, 0) };
                h.kbd =
                    unsafe { SetWindowsHookExW(WH_KEYBOARD_LL, Some(kbd_hook_proc), hinstance, 0) };
            }
            h.refs += 1;
            // Mirror the shared handles into the session as its "holds a ref" flag.
            self.mouse_hook = h.mouse;
            self.kbd_hook = h.kbd;
        });
    }

    /// Release this session's hook ref; the last release (1→0) unhooks (#34).
    fn remove_hooks(&mut self) {
        if self.mouse_hook.is_null() {
            return; // this session holds no ref
        }
        self.mouse_hook = null_mut();
        self.kbd_hook = null_mut();
        HOOKS.with(|h| {
            let mut h = h.borrow_mut();
            if h.refs > 0 {
                h.refs -= 1;
                if h.refs == 0 {
                    if !h.mouse.is_null() {
                        unsafe { UnhookWindowsHookEx(h.mouse) };
                        h.mouse = null_mut();
                    }
                    if !h.kbd.is_null() {
                        unsafe { UnhookWindowsHookEx(h.kbd) };
                        h.kbd = null_mut();
                    }
                }
            }
        });
    }

    // -- open / close --------------------------------------------------------

    fn open_popup(&mut self) {
        if self.popup.is_some() {
            return;
        }
        let theme = self.theme();
        let Some(geom) = self.anchor.geometry() else {
            return;
        };
        let scale = geom.scale.max(1.0);

        // Reuse the measuring drawer as the panel drawer so shaping/glyph caches
        // carry into the first paint (menu not shaped twice per open) (#23).
        // Forced-OS theme -> target OS font; else host-native (#54).
        let mut drawer = RasterDrawer::for_menu_options(scale, &self.options);
        let laid = render_menu(&mut drawer, &self.menu, &theme, &self.options, None);

        let origin = place_popup(
            geom.anchor_rect_local(),
            laid.size,
            geom.work_area_local(),
            self.edge,
            2.0,
        );
        let (px, py) = geom.to_physical(origin);

        let class = wide("muri_popup_wnd");
        register_popup_class(self.hinstance, &class);
        let hwnd = unsafe {
            window::create_popup(
                class.as_ptr(),
                self.hinstance,
                packed_tag(WindowKind::Popup, self.session_id),
            )
        };
        if hwnd.is_null() {
            return;
        }

        #[cfg(feature = "a11y")]
        let snapshot = Rc::new(RefCell::new(a11y::A11ySnapshot {
            menu: self.menu.clone(),
            focus: MenuFocus {
                top: None,
                flyout: Vec::new(),
            },
        }));
        #[cfg(feature = "a11y")]
        let adapter = unsafe { a11y::make_adapter(hwnd, Rc::clone(&snapshot), WindowKind::Popup) };

        self.popup = Some(Panel {
            hwnd,
            drawer,
            laid: Some(laid),
            cursor: LogicalPoint::default(),
            hovered: None,
            origin,
            px,
            py,
            #[cfg(feature = "a11y")]
            adapter,
            #[cfg(feature = "a11y")]
            snapshot,
        });

        self.redraw(WindowKind::Popup);
        unsafe { window::raise_topmost(hwnd) };
        self.install_hooks();
        self.sync_a11y();
    }

    /// Push a flyout for row `parent_index` of the currently deepest open level
    /// (the popup when no flyout is open), placed beside its parent window by
    /// [`place_flyout`]. Mirrors the macOS `push_flyout`: `parent_index` indexes
    /// the deepest level's menu, so descending nested submenus resolves correctly.
    fn push_flyout(&mut self, parent_index: usize) {
        let depth = self.flyouts.len();
        // The level whose row we're opening from == the current deepest level.
        let Some(parent_menu) = self.menu_at_level(depth) else {
            return;
        };
        let Some(child) = (match parent_menu.items.get(parent_index) {
            Some(Item::Submenu { menu, .. }) => Some(menu.clone()),
            _ => None,
        }) else {
            return;
        };

        let (parent_origin, parent_size, scale, row_rect) = {
            let parent_panel = if depth == 0 {
                self.popup.as_ref()
            } else {
                self.flyouts.get(depth - 1).map(|f| &f.panel)
            };
            let Some(pp) = parent_panel else {
                return;
            };
            let Some(rect) = pp
                .laid
                .as_ref()
                .and_then(|l| l.rows.iter().find(|r| r.index == parent_index))
                .map(|r| r.rect)
            else {
                return;
            };
            (
                pp.origin,
                pp.laid.as_ref().map(|l| l.size).unwrap_or_default(),
                pp.drawer.scale(),
                rect,
            )
        };

        let theme = self.theme();
        let Some(geom) = self.anchor.geometry() else {
            return;
        };
        // Reuse the measuring drawer as the flyout drawer (#23).
        // Forced-OS theme -> target OS font; else host-native (#54).
        let mut drawer = RasterDrawer::for_menu_options(scale, &self.options);
        let child_laid = render_menu(&mut drawer, &child, &theme, &self.options, None);

        let parent_rect = LogicalRect::new(parent_origin, parent_size);
        let placement = place_flyout(
            parent_rect,
            row_rect,
            child_laid.size,
            geom.work_area_local(),
        );
        let (px, py) = geom.to_physical(placement.origin);

        let kind = WindowKind::Flyout(depth);
        let class = wide("muri_popup_wnd");
        register_popup_class(self.hinstance, &class);
        let hwnd = unsafe {
            window::create_popup(
                class.as_ptr(),
                self.hinstance,
                packed_tag(kind, self.session_id),
            )
        };
        if hwnd.is_null() {
            return;
        }

        #[cfg(feature = "a11y")]
        let snapshot = Rc::new(RefCell::new(a11y::A11ySnapshot {
            menu: child.clone(),
            focus: MenuFocus {
                top: None,
                flyout: Vec::new(),
            },
        }));
        #[cfg(feature = "a11y")]
        let adapter = unsafe { a11y::make_adapter(hwnd, Rc::clone(&snapshot), kind) };

        self.flyouts.push(Flyout {
            parent: parent_index,
            panel: Panel {
                hwnd,
                drawer,
                laid: None,
                cursor: LogicalPoint::default(),
                hovered: None,
                origin: placement.origin,
                px,
                py,
                #[cfg(feature = "a11y")]
                adapter,
                #[cfg(feature = "a11y")]
                snapshot,
            },
        });

        self.redraw(kind);
        unsafe { window::raise_topmost(hwnd) };
        self.sync_a11y();
    }

    /// Close every flyout deeper than `len`, destroying their windows.
    fn truncate_flyouts(&mut self, len: usize) {
        while self.flyouts.len() > len {
            if let Some(f) = self.flyouts.pop() {
                f.panel.destroy();
            }
        }
    }

    /// Reconcile the open flyout window stack to `target` (per-level parent
    /// indices, as produced by [`next_flyout`]): keep the common prefix, close
    /// anything deeper, then push the remaining levels. Mirrors macOS.
    fn apply_flyout_stack(&mut self, target: &[usize]) {
        let common = common_flyout_prefix(&self.flyout_stack(), target);
        self.truncate_flyouts(common);
        for &parent in &target[common..] {
            self.push_flyout(parent);
        }
    }

    fn close_popup(&mut self) {
        self.remove_hooks();
        self.truncate_flyouts(0);
        if let Some(popup) = self.popup.take() {
            popup.destroy();
        }
    }

    // -- present -------------------------------------------------------------

    /// Re-render one window from its level's menu + hovered row. Mirrors macOS's
    /// unified `redraw`.
    fn redraw(&mut self, kind: WindowKind) {
        let theme = self.theme();
        let options = self.options.clone();
        // Borrow the level's menu from `self.menu`; the panel below is taken from
        // the disjoint `self.popup`/`self.flyouts` fields (not via `panel_mut`,
        // which would borrow all of `self`), so no clone is needed on redraw.
        let Some(menu) = crate::menu::descend(
            &self.menu,
            self.flyouts
                .iter()
                .take(kind.menu_level())
                .map(|f| f.parent),
        ) else {
            return;
        };
        let panel = match kind {
            WindowKind::Popup => self.popup.as_mut(),
            WindowKind::Flyout(d) => self.flyouts.get_mut(d).map(|f| &mut f.panel),
        };
        let Some(panel) = panel else {
            return;
        };
        let laid = render_menu(&mut panel.drawer, menu, &theme, &options, panel.hovered);
        unsafe {
            present::present_layered(panel.hwnd, panel.drawer.framebuffer(), panel.px, panel.py)
        };
        panel.laid = Some(laid);
    }

    fn redraw_all(&mut self) {
        self.redraw(WindowKind::Popup);
        for d in 0..self.flyouts.len() {
            self.redraw(WindowKind::Flyout(d));
        }
    }

    // -- pointer -------------------------------------------------------------

    fn set_cursor(&mut self, kind: WindowKind, pt: LogicalPoint) {
        if let Some(p) = self.panel_mut(kind) {
            p.cursor = pt;
        }
    }

    /// Handle a cursor move over `kind`: update its hovered row (repaint on
    /// change), then drive the flyout stack from the pure hover-stack rule.
    /// Mirrors the macOS `on_cursor` — one path for the popup and every flyout.
    fn on_cursor(&mut self, kind: WindowKind, pt: LogicalPoint) {
        let (hovered, changed) = {
            let Some(p) = self.panel_mut(kind) else {
                return;
            };
            p.cursor = pt;
            let h = p.laid.as_ref().and_then(|l| l.hit(pt));
            let changed = h != p.hovered;
            if changed {
                p.hovered = h;
            }
            (h, changed)
        };
        if changed {
            self.redraw(kind);
        }
        let panel_depth = kind.menu_level();
        let level_menu = self.menu_at_level(panel_depth);
        let target = match hovered {
            Some(i)
                if level_menu
                    .is_some_and(|m| matches!(m.items.get(i), Some(Item::Submenu { .. }))) =>
            {
                HoverTarget::ParentRow {
                    panel: panel_depth,
                    index: i,
                }
            }
            Some(_) => HoverTarget::OtherRow { panel: panel_depth },
            None => HoverTarget::Outside,
        };
        let next = next_flyout(&self.flyout_stack(), target);
        self.apply_flyout_stack(&next);
        self.sync_a11y();
    }

    /// Handle a click on `kind`: a submenu row opens (or switches to) its nested
    /// flyout, closing anything deeper; a leaf row dispatches its id and dismisses.
    /// Mirrors the macOS `on_click` — the flyout branch now honors submenu rows so
    /// clicking a nested submenu opens the next level instead of dispatching.
    fn on_click(&mut self, kind: WindowKind) {
        let level = kind.menu_level();
        let Some(menu) = self.menu_at_level(level) else {
            return;
        };
        let (hit, id) = {
            let Some(p) = self.panel(kind) else {
                return;
            };
            (
                p.laid.as_ref().and_then(|l| l.hit(p.cursor)),
                p.laid.as_ref().and_then(|l| l.id_at(p.cursor)),
            )
        };
        if let Some(i) = hit {
            if matches!(menu.items.get(i), Some(Item::Submenu { .. })) {
                // Open (or switch to) this row's flyout, closing anything deeper.
                self.truncate_flyouts(level);
                self.push_flyout(i);
                return;
            }
        }
        if let Some(id) = id {
            if !id.is_none() {
                (self.dispatch)(&id);
            }
            self.close_popup();
        }
    }

    // -- keyboard ------------------------------------------------------------

    fn on_key_nav(&mut self, key: NavKey) {
        let mut focus = self.current_focus();
        let action = handle_key(&self.menu, &mut focus, key);
        if let Some(popup) = self.popup.as_mut() {
            popup.hovered = focus.top;
        }
        match action {
            NavAction::None => return,
            NavAction::Redraw => {}
            // `i` indexes the deepest open level's menu (the level `handle_key`
            // just descended into), which is exactly what `push_flyout` opens
            // from — so nested submenus descend correctly.
            NavAction::OpenFlyout(i) => self.push_flyout(i),
            NavAction::CloseFlyout => {
                let keep = self.flyouts.len().saturating_sub(1);
                self.truncate_flyouts(keep);
            }
            NavAction::Activate(id) => {
                if !id.is_none() {
                    (self.dispatch)(&id);
                }
                self.close_popup();
                return;
            }
            NavAction::CloseAll => {
                self.close_popup();
                return;
            }
        }
        // Write the (possibly new) per-level child selections back into the
        // flyouts that still exist.
        for (k, f) in self.flyouts.iter_mut().enumerate() {
            if let Some(ff) = focus.flyout.get(k) {
                f.panel.hovered = ff.child;
            }
        }
        self.redraw_all();
        self.sync_a11y();
    }

    // -- dismiss -------------------------------------------------------------

    /// A physical mouse-down: dismiss the stack if it fell outside every open
    /// muri window (spec 21 §2, the point-in-any-window rule).
    fn on_global_mouse_down(&mut self, x: i32, y: i32) {
        if self.popup.is_none() {
            return;
        }
        let mut rects = Vec::with_capacity(1 + self.flyouts.len());
        if let Some(p) = self.popup.as_ref() {
            rects.push(p.phys_rect());
        }
        for f in &self.flyouts {
            rects.push(f.panel.phys_rect());
        }
        if point_in_any(&rects, x, y) {
            return;
        }
        // A mouse-down on the tray icon itself is a toggle handled by the paired
        // `WM_TRAY_CALLBACK` (button-up): dismissing here would close-then-reopen
        // (flicker) so a tray click could never close an open popup. Hit-test the
        // icon's *reliable* rect (never the cursor fallback), so a spurious rect
        // can't swallow a genuine outside-click dismiss. When the rect is
        // unavailable (icon in the overflow flyout) we fall through and dismiss —
        // in that layout the icon isn't directly clickable while a popup is open
        // anyway (opening the overflow flyout is itself the dismissing click).
        if let Anchor::Tray(a) = &self.anchor {
            if let Some(r) = a.icon_rect_physical() {
                if x >= r.left && x < r.right && y >= r.top && y < r.bottom {
                    return;
                }
            }
        }
        self.close_popup();
    }

    // -- accessibility -------------------------------------------------------

    #[cfg(feature = "a11y")]
    fn is_submenu_at_path(&self, path: &[usize]) -> bool {
        let mut menu = &self.menu;
        for (k, &idx) in path.iter().enumerate() {
            match menu.items.get(idx) {
                Some(Item::Submenu { menu: child, .. }) => {
                    if k + 1 == path.len() {
                        return true;
                    }
                    menu = child;
                }
                _ => return false,
            }
        }
        false
    }

    #[cfg(feature = "a11y")]
    fn menu_id_at_path(&self, path: &[usize]) -> Option<MenuId> {
        let mut menu = &self.menu;
        for (k, &idx) in path.iter().enumerate() {
            match menu.items.get(idx)? {
                Item::Row(row) if k + 1 == path.len() => return Some(row.id.clone()),
                Item::Submenu { menu: child, .. } => menu = child,
                _ => return None,
            }
        }
        None
    }

    /// Push a fresh `TreeUpdate` to every open window's adapter (Option B: one
    /// per-window adapter per stack level — spec 30 §3). Each window's tree is its
    /// own level's menu; its focus is that window's selection, and any deeper open
    /// levels are carried as its expanded sub-stack. Mirrors the macOS `sync_a11y`.
    #[cfg(feature = "a11y")]
    fn sync_a11y(&mut self) {
        let full = self.current_focus();
        // The `menu` closures below are only invoked when the panel's adapter is
        // active (an AT is listening), so the `Menu` clone is skipped entirely on
        // the hot hover/keynav path when nothing is attached (spec 30 §3).
        let root = &self.menu;
        if let Some(popup) = self.popup.as_mut() {
            a11y::sync(
                &mut popup.adapter,
                &popup.snapshot,
                || root.clone(),
                MenuFocus {
                    top: full.top,
                    flyout: full.flyout.clone(),
                },
            );
        }
        // Pre-collect the open flyouts' parent indices so each level's menu can be
        // borrowed from `self.menu` (via `descend`) while the matching panel in the
        // disjoint `self.flyouts` is mutably borrowed for its adapter.
        let parents: Vec<usize> = self.flyouts.iter().map(|f| f.parent).collect();
        for d in 0..self.flyouts.len() {
            let Some(menu) = crate::menu::descend(&self.menu, parents[..=d].iter().copied()) else {
                continue;
            };
            let top = full.flyout.get(d).and_then(|f| f.child);
            let sub: Vec<FlyoutFocus> = full.flyout.iter().skip(d + 1).copied().collect();
            if let Some(f) = self.flyouts.get_mut(d) {
                a11y::sync(
                    &mut f.panel.adapter,
                    &f.panel.snapshot,
                    || menu.clone(),
                    MenuFocus { top, flyout: sub },
                );
            }
        }
    }

    #[cfg(not(feature = "a11y"))]
    #[inline]
    fn sync_a11y(&mut self) {}

    #[cfg(feature = "a11y")]
    fn on_a11y_action(&mut self, kind: WindowKind, request: accesskit::ActionRequest) {
        let target = crate::a11y::AxId(request.target.0);
        let level = kind.menu_level();
        let Some(menu) = self.menu_at_level(level) else {
            return;
        };
        let tree = crate::a11y::build_tree(menu);
        let Some(rel_path) = crate::a11y::locate_path(&tree, target) else {
            return;
        };
        // Absolute path from the top-level menu = the parents that lead to this
        // window (levels 1..=level) followed by the in-window path.
        let mut abs: Vec<usize> = self.flyouts.iter().take(level).map(|f| f.parent).collect();
        abs.extend_from_slice(&rel_path);
        self.apply_a11y(&abs, request.action);
    }

    #[cfg(feature = "a11y")]
    fn apply_a11y(&mut self, abs: &[usize], action: accesskit::Action) {
        use accesskit::Action;
        if abs.is_empty() {
            return;
        }
        match action {
            Action::Focus => {
                // Open flyouts for every submenu ancestor along the path (all but
                // the final element), then select the final row in its window.
                let target = &abs[..abs.len() - 1];
                self.apply_flyout_stack(target);
                let final_kind = if target.is_empty() {
                    WindowKind::Popup
                } else {
                    WindowKind::Flyout(target.len() - 1)
                };
                if let (Some(&last), Some(p)) = (abs.last(), self.panel_mut(final_kind)) {
                    p.hovered = Some(last);
                }
                if let (Some(&first), Some(p)) = (abs.first(), self.popup.as_mut()) {
                    p.hovered = Some(first);
                }
                self.redraw_all();
                self.sync_a11y();
            }
            Action::Click => {
                if self.is_submenu_at_path(abs) {
                    self.apply_flyout_stack(abs);
                    if let (Some(&first), Some(p)) = (abs.first(), self.popup.as_mut()) {
                        p.hovered = Some(first);
                    }
                    self.sync_a11y();
                    return;
                }
                if let Some(id) = self.menu_id_at_path(abs) {
                    if !id.is_none() {
                        (self.dispatch)(&id);
                    }
                }
                self.close_popup();
            }
            _ => {}
        }
    }

    // -- drain ---------------------------------------------------------------

    fn apply_event(&mut self, event: UiEvent) {
        match event {
            UiEvent::TrayClicked => {
                if self.popup.is_some() {
                    self.close_popup();
                } else {
                    self.open_popup();
                }
            }
            UiEvent::MouseMoved { kind, x, y } => {
                self.on_cursor(kind, LogicalPoint::new(x, y));
            }
            UiEvent::MouseClick { kind, x, y } => {
                self.set_cursor(kind, LogicalPoint::new(x, y));
                self.on_click(kind);
            }
            UiEvent::Key(key) => self.on_key_nav(key),
            UiEvent::GlobalMouseDown { x, y } => self.on_global_mouse_down(x, y),
            UiEvent::AppDeactivated => {
                // DEVICE-VERIFY(0.9.0): whether a non-activating popup lets the
                // owning app "deactivate" here (vs. the mouse hook being the sole
                // dismiss path) can only be confirmed on a device.
                if self.popup.is_some() {
                    self.close_popup();
                }
            }
        }
    }

    /// Drain and apply every UIA action queued by a (possibly foreign) UIA thread
    /// into the pump-thread state. Returns whether any action was applied, so the
    /// drain loops keep spinning until the cross-thread inbox is empty too.
    #[cfg(feature = "a11y")]
    fn drain_a11y_actions(&mut self) -> bool {
        let actions = A11Y_ACTIONS
            .lock()
            .map(|mut q| std::mem::take(&mut *q))
            .unwrap_or_default();
        let any = !actions.is_empty();
        for (kind, request) in actions {
            self.on_a11y_action(kind, request);
        }
        any
    }

    /// Apply all pending UI events *tagged with this session's id* (#33),
    /// looping until this session's slice of the inbox is empty (applying one
    /// can enqueue more). Events tagged with a different (enclosing or sibling)
    /// session's id are left in [`EVENTS`] untouched — see [`take_session_events`].
    /// The standalone `open_at` / `anchored_to` pump uses this on the caller's
    /// stack; the tray drains through [`AppState::drain`] instead so it also
    /// applies [`TrayHandle`](crate::TrayHandle) commands.
    fn drain_events(&mut self) {
        loop {
            let events = take_session_events(self.session_id);
            let had_events = !events.is_empty();
            for event in events {
                self.apply_event(event);
            }
            #[cfg(feature = "a11y")]
            let had_actions = self.drain_a11y_actions();
            #[cfg(not(feature = "a11y"))]
            let had_actions = false;
            if !had_events && !had_actions {
                break;
            }
        }
    }
}

impl Drop for PopupSession<'_> {
    /// Tear down any windows + hooks still live if the session is dropped while a
    /// popup is open (spec 21 §2). If the `GetMessageW` pump exits via a foreign
    /// `WM_QUIT` while a popup is open, `close_popup` never runs on the normal
    /// path, which would leak the popup/flyout `HWND`s and leave the
    /// `WH_MOUSE_LL` / `WH_KEYBOARD_LL` hooks installed. `close_popup` nulls its
    /// hooks and takes/clears the windows it destroys, so running it here is
    /// idempotent with the normal path — no double-free / double-unhook.
    fn drop(&mut self) {
        self.close_popup();
    }
}

/// The tray's run-loop state: the shared [`PopupSession`] plus the [`Tray`] whose
/// icon / tooltip / command inbox drive the persistent tray surface.
struct AppState {
    session: PopupSession<'static>,
    tray: Tray,
}

impl AppState {
    fn apply_command(&mut self, command: TrayCommand) {
        match command {
            TrayCommand::SetMenu(menu) => {
                self.tray.menu = menu.clone();
                self.session.menu = menu;
                if self.session.popup.is_some() {
                    // Structure may have changed under an open flyout; drop the
                    // whole flyout stack, then repaint + refresh the a11y tree live.
                    self.session.truncate_flyouts(0);
                    self.session.redraw(WindowKind::Popup);
                    self.session.sync_a11y();
                }
            }
            TrayCommand::SetIcon(icon) => {
                self.tray.icon = icon;
                let icon = self.tray.icon.clone();
                if let Anchor::Tray(a) = &mut self.session.anchor {
                    a.set_icon(&icon);
                }
            }
            TrayCommand::SetTooltip(tooltip) => {
                self.tray.tooltip = tooltip;
                let tip = self.tray.tooltip.clone();
                if let Anchor::Tray(a) = &mut self.session.anchor {
                    a.set_tooltip(tip.as_deref());
                }
            }
            TrayCommand::SetTitle(title) => {
                // The Windows notification area has no text label (the menu-bar
                // title is a macOS concept); retain it, but there is nothing to
                // draw here.
                self.tray.title = title;
            }
            TrayCommand::SetVisible(visible) => {
                if let Anchor::Tray(a) = &self.session.anchor {
                    a.set_visible(visible);
                }
            }
            TrayCommand::Open => {
                if self.session.popup.is_none() {
                    self.session.open_popup();
                }
            }
            TrayCommand::Close => self.session.close_popup(),
            TrayCommand::Shutdown => {
                // Post WM_QUIT so GetMessageW returns 0 and run_event_loop exits;
                // unwinding drops AppState -> WindowsAnchor::Drop, which removes
                // the notification icon (NIM_DELETE). Ends the 'muri-tray' thread.
                unsafe { PostQuitMessage(0) };
            }
            TrayCommand::SetTheme(theme) => {
                self.session.options.theme = theme;
                self.repaint_open_popup();
            }
            TrayCommand::SetOptions(options) => {
                self.session.options = options;
                self.repaint_open_popup();
            }
            TrayCommand::QueryAnchorRect(reply) => {
                let rect = match &self.session.anchor {
                    Anchor::Tray(a) => a.anchor_rect().ok(),
                    _ => None,
                };
                let _ = reply.send(rect);
            }
        }
    }

    /// Repaint an already-open popup after a live theme/options swap (#45), so an
    /// in-menu theme switcher redraws instantly instead of only on next open.
    fn repaint_open_popup(&mut self) {
        if self.session.popup.is_some() {
            self.session.truncate_flyouts(0);
            self.session.redraw(WindowKind::Popup);
            self.session.sync_a11y();
        }
    }

    /// Apply all pending commands and UI events *tagged with this session's id*
    /// (#33), looping until both inboxes are empty (applying one can enqueue
    /// more). See [`take_session_events`]: a nested `open_at` / `anchored_to`
    /// session opened from a command/click handler below leaves its own events
    /// queued for its own drain, so they're never double-applied here.
    fn drain(&mut self) {
        loop {
            let events = take_session_events(self.session.session_id);
            let commands: Vec<TrayCommand> = self
                .tray
                .commands
                .lock()
                .map(|mut q| std::mem::take(&mut *q))
                .unwrap_or_default();
            let had_work = !events.is_empty() || !commands.is_empty();
            for command in commands {
                self.apply_command(command);
            }
            for event in events {
                self.session.apply_event(event);
            }
            #[cfg(feature = "a11y")]
            let had_actions = self.session.drain_a11y_actions();
            #[cfg(not(feature = "a11y"))]
            let had_actions = false;
            if !had_work && !had_actions {
                break;
            }
        }
    }
}

/// Descend `menu` through the submenu-row indices in `stack` (the open flyout
/// parents, shallowest first), **borrowing** the menu at that depth — the menu
/// whose rows the deepest open flyout selects among. Returns `None` if some index
/// along the way is not a submenu (e.g. the menu was swapped underneath an open
/// flyout).
///
/// A thin `&[usize]` wrapper over [`crate::menu::descend`], so the N-level
/// submenu resolution that [`PopupSession::menu_at_level`] (and hence the click /
/// keyboard dispatch paths) relies on is unit-testable without creating real
/// windows. Borrows rather than clones, so it is free on the redraw hot path.
///
/// The live paths call [`PopupSession::menu_at_level`]/[`crate::menu::descend`]
/// directly (borrowing disjoint fields of `self`); this wrapper exists for the
/// slice-based unit tests, hence `#[cfg(test)]`.
#[cfg(test)]
fn menu_at_stack<'a>(menu: &'a Menu, stack: &[usize]) -> Option<&'a Menu> {
    crate::menu::descend(menu, stack.iter().copied())
}

/// The length of the common prefix between the currently open flyout stack
/// (`current`, shallowest first) and a `target` stack — the number of levels
/// [`PopupSession::apply_flyout_stack`] keeps before it truncates the deeper open
/// levels and pushes the target's remaining levels. Pure, so the N-level flyout
/// reconciliation (switch-to-shallower-sibling, re-hover-open-parent) is
/// unit-testable without creating real windows.
fn common_flyout_prefix(current: &[usize], target: &[usize]) -> usize {
    let mut common = 0;
    while common < target.len() && common < current.len() && current[common] == target[common] {
        common += 1;
    }
    common
}

/// Whether `(x, y)` lies inside any `(left, top, right, bottom)` rectangle. Pure,
/// so the outside-click dismiss decision the (device-only) `WH_MOUSE_LL` hook
/// feeds is unit-testable.
fn point_in_any(rects: &[(i32, i32, i32, i32)], x: i32, y: i32) -> bool {
    rects
        .iter()
        .any(|&(l, t, r, b)| x >= l && x < r && y >= t && y < b)
}

/// Register the layered-popup window class once per process.
fn register_popup_class(hinstance: windows_sys::Win32::Foundation::HINSTANCE, class: &[u16]) {
    POPUP_CLASS_ONCE.call_once(|| unsafe {
        let mut wc: WNDCLASSW = std::mem::zeroed();
        wc.lpfnWndProc = Some(wnd_proc);
        wc.hInstance = hinstance;
        wc.lpszClassName = class.as_ptr();
        RegisterClassW(&wc);
    });
}

// =============================================================================
// System appearance
// =============================================================================

/// Query whether the system uses a dark app theme (`AppsUseLightTheme == 0` under
/// `HKCU`), defaulting to light if the value can't be read.
/// The live Windows accent color via `DwmGetColorizationColor` (the DWM
/// colorization/accent color, `0xAARRGGBB`), or `None` if DWM composition is
/// off. Injected into `Color::Accent` so the selection/checkmark follows the
/// user's Windows accent (#14).
/// Read the Windows menu font (`SPI_GETNONCLIENTMETRICS` → `lfMenuFont`, normally
/// Segoe UI) as a [`SystemFont`](crate::platform::SystemFont). Free function so
/// both the [`Platform`] impl and the popup `theme()` can call it.
fn read_system_menu_font() -> Option<crate::platform::SystemFont> {
    use crate::platform::{SystemFont, SystemFontSource};
    use windows_sys::Win32::UI::WindowsAndMessaging::{
        SystemParametersInfoW, NONCLIENTMETRICSW, SPI_GETNONCLIENTMETRICS,
    };
    unsafe {
        let mut ncm: NONCLIENTMETRICSW = std::mem::zeroed();
        ncm.cbSize = std::mem::size_of::<NONCLIENTMETRICSW>() as u32;
        let ok = SystemParametersInfoW(
            SPI_GETNONCLIENTMETRICS,
            ncm.cbSize,
            (&mut ncm as *mut NONCLIENTMETRICSW).cast(),
            0,
        );
        if ok == 0 {
            return None;
        }
        let lf = ncm.lfMenuFont;
        // `lfFaceName` is a null-terminated UTF-16 buffer (typically Segoe UI,
        // which fontdb resolves by name on Windows).
        let len = lf
            .lfFaceName
            .iter()
            .position(|&c| c == 0)
            .unwrap_or(lf.lfFaceName.len());
        let family = String::from_utf16_lossy(&lf.lfFaceName[..len]);
        if family.is_empty() {
            return None;
        }
        // lfHeight < 0 is the char height in device pixels; convert to points at
        // the 96-DPI baseline (the size is a secondary refinement).
        let point_size = if lf.lfHeight < 0 {
            (-lf.lfHeight as f32) * POINTS_PER_INCH / BASE_DPI
        } else {
            0.0
        };
        Some(SystemFont {
            source: SystemFontSource::Family(family),
            point_size,
        })
    }
}

fn system_accent() -> Option<(u8, u8, u8, u8)> {
    use windows_sys::Win32::Graphics::Dwm::DwmGetColorizationColor;
    unsafe {
        let mut color: u32 = 0;
        let mut opaque: i32 = 0;
        // Returns S_OK (0) on success; anything else means unavailable.
        if DwmGetColorizationColor(&mut color, &mut opaque) != 0 {
            return None;
        }
        let a = ((color >> 24) & 0xff) as u8;
        let r = ((color >> 16) & 0xff) as u8;
        let g = ((color >> 8) & 0xff) as u8;
        let b = (color & 0xff) as u8;
        Some((r, g, b, if a == 0 { 255 } else { a }))
    }
}

fn system_is_dark() -> bool {
    read_personalize_dword("AppsUseLightTheme", 1) == 0
}

/// Whether Windows transparency effects are enabled (Settings › Personalization ›
/// Colors › Transparency effects, registry `EnableTransparency`). When off, Win11
/// menus render opaque, so the theme drops its acrylic translucency to match.
/// Defaults to enabled if the value is missing.
fn transparency_enabled() -> bool {
    read_personalize_dword("EnableTransparency", 1) != 0
}

/// Read a DWORD from `…\CurrentVersion\Themes\Personalize`, returning `default`
/// if the value is absent/unreadable.
fn read_personalize_dword(value_name: &str, default: u32) -> u32 {
    unsafe {
        let subkey = wide("Software\\Microsoft\\Windows\\CurrentVersion\\Themes\\Personalize");
        let value = wide(value_name);
        let mut data: u32 = default;
        let mut size = std::mem::size_of::<u32>() as u32;
        let rc = RegGetValueW(
            HKEY_CURRENT_USER,
            subkey.as_ptr(),
            value.as_ptr(),
            RRF_RT_REG_DWORD,
            null_mut(),
            (&mut data as *mut u32).cast(),
            &mut size,
        );
        if rc == 0 {
            data
        } else {
            default
        }
    }
}

// =============================================================================
// Platform seam (ADR-0002)
// =============================================================================

/// The Windows [`Platform`] implementation: a `Shell_NotifyIcon` tray anchor plus
/// the native layered non-activating popup + flyout message-pump loop, the
/// `UpdateLayeredWindow` present path, the per-window UIA adapter (behind
/// `a11y`), and the appearance / work-area queries. Every Win32-specific
/// dependency (`windows-sys`, `accesskit_windows`) lives in this module behind
/// the [`Platform`] trait — no `HWND` crosses the seam.
#[derive(Debug, Default)]
pub struct WindowsPlatform {
    anchor: WindowsAnchor,
}

impl WindowsPlatform {
    /// Create the (not-yet-installed) Windows platform.
    pub fn new() -> Self {
        WindowsPlatform {
            anchor: WindowsAnchor::new(),
        }
    }
}

impl Platform for WindowsPlatform {
    fn install_tray(&mut self, icon: &Icon, tooltip: Option<&str>) -> Result<()> {
        // Scan installed fonts in the background so the first menu open is instant.
        crate::render::prewarm_system_fonts();
        self.anchor.install(icon, tooltip)
    }

    fn tray_anchor_rect(&self) -> Result<LogicalRect> {
        self.anchor.anchor_rect()
    }

    fn supports_tray_anchor(&self) -> bool {
        self.anchor.supports_tray_anchor()
    }

    fn cursor_position(&self) -> Option<LogicalPoint> {
        // `GetCursorPos`: physical pixels, virtual-screen space, top-left origin.
        // Convert to logical using the effective DPI of the monitor under the
        // cursor — the same `physical / scale` logical space the popup path uses.
        // DEVICE-VERIFY(0.10.7): per-monitor DPI on a mixed-DPI multi-monitor setup.
        let mut pt = POINT { x: 0, y: 0 };
        if unsafe { GetCursorPos(&mut pt) } == 0 {
            return None;
        }
        let hmon = unsafe { MonitorFromPoint(pt, MONITOR_DEFAULTTONEAREST) };
        let mut dpi_x: u32 = 96;
        let mut dpi_y: u32 = 96;
        let scale = if !hmon.is_null()
            && unsafe { GetDpiForMonitor(hmon, MDT_EFFECTIVE_DPI, &mut dpi_x, &mut dpi_y) } == S_OK
            && dpi_x != 0
        {
            dpi_x as f32 / BASE_DPI
        } else {
            1.0
        };
        Some(LogicalPoint::new(pt.x as f32 / scale, pt.y as f32 / scale))
    }

    fn appearance(&self) -> Appearance {
        Appearance::from_is_dark(system_is_dark())
    }

    fn system_menu_font(&self) -> Option<crate::platform::SystemFont> {
        read_system_menu_font()
    }

    fn work_area(&self) -> LogicalRect {
        self.anchor.work_area().unwrap_or_else(|_| {
            LogicalRect::new(LogicalPoint::new(0.0, 0.0), LogicalSize::new(1440.0, 900.0))
        })
    }

    fn run_tray(self, tray: Tray) -> Result<()> {
        // Blocking path: an install failure surfaces directly through the return
        // value, so the install handshake fires into a local channel we don't
        // consume (`_wait` stays alive for the duration of the call).
        let (report, _wait) = std::sync::mpsc::channel();
        run_event_loop(tray, &report)
    }

    fn spawn_tray(self, tray: Tray) -> Result<()> {
        // The tray's HWND, message pump and thread-local state all live on the
        // thread that runs `run_event_loop`, so a dedicated background thread is
        // fully self-consistent; a `TrayHandle` drives it cross-thread by
        // `PostMessageW`-ing the (thread-safe) owner window. `spawn_tray_thread`
        // blocks until `run_event_loop` has fired the install handshake, so a
        // real `Shell_NotifyIcon(NIM_ADD)` failure is surfaced synchronously here.
        super::spawn_tray_thread(tray, run_event_loop)
    }

    fn open_popup_session(
        &mut self,
        menu: Menu,
        options: MenuOptions,
        on_click: &(dyn Fn(&MenuId) + '_),
        anchor: LogicalRect,
        edge: Edge,
    ) -> Result<()> {
        run_popup_session(menu, options, on_click, anchor, edge)
    }
}

/// Install the tray icon and run the native Win32 message pump, opening the
/// styled popup on click and dispatching row clicks to the tray's handler.
/// Consumes the [`Tray`]; returns when the pump exits (a `WM_QUIT`).
fn run_event_loop(mut tray: Tray, report: &super::InstallReport) -> Result<()> {
    let hinstance = unsafe { GetModuleHandleW(null_mut()) };

    // Resolve the Explorer-restart broadcast id once.
    let taskbar_msg = unsafe { RegisterWindowMessageW(wide("TaskbarCreated").as_ptr()) };
    TASKBAR_CREATED_MSG.store(taskbar_msg, Ordering::SeqCst);

    let mut anchor = WindowsAnchor::new();
    // Install handshake (EH-1): report the real `Shell_NotifyIcon(NIM_ADD)` result
    // synchronously — *before* entering the blocking pump — so a spawn-path caller
    // (the native `Tray::spawn`) learns the icon never installed instead
    // of seeing a false `Ok`. The blocking `run_tray` path also propagates it via
    // the return value.
    if let Err(e) = anchor.install(&tray.icon, tray.tooltip.as_deref()) {
        let msg = match &e {
            Error::TrayInstall(m) => m.clone(),
            other => other.to_string(),
        };
        let _ = report.send(Err(Error::TrayInstall(msg)));
        return Err(e);
    }
    let owner = anchor.hwnd as isize;
    OWNER_HWND.with(|h| h.set(owner));
    // Also publish the owner in the thread-safe static so a UIA action raised on a
    // foreign thread can wake this pump (spec 30 §3, FIX 1).
    #[cfg(feature = "a11y")]
    A11Y_OWNER.store(owner, Ordering::SeqCst);

    // Install the TrayHandle waker so posts from any thread schedule a drain by
    // posting to the (thread-safe) owner window.
    if let Ok(mut waker) = tray.waker.lock() {
        *waker = Some(Box::new(move || unsafe {
            PostMessageW(owner as HWND, WM_MURI_DRAIN, 0, 0);
        }));
    }

    // Report the install success only NOW — after the TrayHandle waker is stored
    // — so a command posted by a handle obtained before this point still wakes the
    // pump instead of sitting unserviced until the next unrelated message (#F2/F3).
    let _ = report.send(Ok(()));

    // Move the tray's click handler into the session's dispatch sink (owned for the
    // whole run loop, hence `'static`). Preserve `Tray::dispatch`'s behavior:
    // run the per-surface handler, then project the activation onto the global
    // `MenuEvent` channel (callers only ever invoke this for addressable ids).
    let surface = tray.surface_id;
    let dispatch: Box<dyn Fn(&MenuId) + 'static> = match tray.on_click.take() {
        Some(handler) => Box::new(move |id| {
            handler(id);
            crate::event::emit(id.clone(), surface);
        }),
        None => Box::new(move |id| crate::event::emit(id.clone(), surface)),
    };

    // Allocate this session's unique id (#33) and mark it active so window-less
    // events (tray click, global hooks) fired before any nested session opens
    // are attributed to it.
    let session_id = next_session_id();
    ACTIVE_SESSION.with(|c| c.set(session_id));

    let session = PopupSession {
        session_id,
        menu: tray.menu.clone(),
        options: tray.options.clone(),
        dispatch,
        anchor: Anchor::Tray(anchor),
        // Taskbars usually sit at the bottom, so the popup grows up from the icon.
        edge: Edge::Top,
        hinstance,
        popup: None,
        flyouts: Vec::new(),
        mouse_hook: null_mut(),
        kbd_hook: null_mut(),
    };

    // Keep an Arc to the waker slot before `tray` moves into `AppState`, so we
    // can clear the stale `WakeFn` once the pump exits — otherwise a surviving
    // `TrayHandle` would `PostMessageW` a destroyed owner HWND.
    let waker_arc = std::sync::Arc::clone(&tray.waker);

    let state = Rc::new(RefCell::new(AppState { session, tray }));
    MAIN_APP.with(|slot| *slot.borrow_mut() = Some(Rc::clone(&state)));

    // Apply any commands a handle posted before the loop came up.
    push_drain(owner as HWND);

    unsafe {
        let mut msg: MSG = std::mem::zeroed();
        while GetMessageW(&mut msg, null_mut(), 0, 0) > 0 {
            TranslateMessage(&msg);
            DispatchMessageW(&msg);
        }
    }

    MAIN_APP.with(|slot| *slot.borrow_mut() = None);
    OWNER_HWND.with(|h| h.set(0));
    ACTIVE_SESSION.with(|c| c.set(0));
    // Clear the waker so a `TrayHandle` outliving the pump can't post to the
    // now-destroyed owner window.
    if let Ok(mut waker) = waker_arc.lock() {
        *waker = None;
    }
    #[cfg(feature = "a11y")]
    A11Y_OWNER.store(0, Ordering::SeqCst);
    Ok(())
}

/// Post a bare drain request to the owner window.
fn push_drain(owner: HWND) {
    unsafe {
        PostMessageW(owner, WM_MURI_DRAIN, 0, 0);
    }
}

/// Run a pointer/rect-anchored [`ContextMenu`](crate::ContextMenu) /
/// [`Popup`](crate::Popup) session to completion (spec 21 §3): open the styled
/// popup at `anchor`, then pump the Win32 message loop — draining muri UI events
/// after each dispatched message — until the whole stack dismisses. Reuses the
/// shared [`PopupSession`]; the only difference from the tray is that the anchor is
/// a fixed rect, the handler is borrowed for the call rather than owned for a run
/// loop, and there is no persistent owner window / [`MAIN_APP`] / command inbox —
/// the pump drains `EVENTS` directly on the caller's stack. This is the Windows
/// analogue of the macOS `run_popup_session`.
fn run_popup_session(
    menu: Menu,
    options: MenuOptions,
    on_click: &(dyn Fn(&MenuId) + '_),
    anchor: LogicalRect,
    edge: Edge,
) -> Result<()> {
    let hinstance = unsafe { GetModuleHandleW(null_mut()) };
    let geom = WinGeometry::for_rect(anchor)
        .ok_or_else(|| Error::Platform("no monitor available for the popup".into()))?;

    let session_id = next_session_id();
    let mut session = PopupSession {
        session_id,
        menu,
        options,
        dispatch: Box::new(move |id| on_click(id)),
        anchor: Anchor::Fixed(geom),
        edge,
        hinstance,
        popup: None,
        flyouts: Vec::new(),
        mouse_hook: null_mut(),
        kbd_hook: null_mut(),
    };
    // Mark this session active (#33) so window-less events (global hooks) raised
    // once its popup opens are attributed to it rather than an enclosing
    // session's (e.g. a tray loop that opened us from a click handler). Restored
    // below so control returning to an enclosing session also restores *its*
    // "active" status.
    let prev_active_session = ACTIVE_SESSION.with(|c| c.replace(session_id));
    session.open_popup();
    let Some(popup_hwnd) = session.popup.as_ref().map(|p| p.hwnd) else {
        ACTIVE_SESSION.with(|c| c.set(prev_active_session));
        return Err(Error::Platform("failed to open the popup window".into()));
    };

    // Route on-thread callbacks' drain posts at our own popup window so a global
    // hook event (`WH_MOUSE_LL` / `WH_KEYBOARD_LL`) wakes `GetMessageW` promptly.
    // Save and restore any prior owner (e.g. a tray loop) so a context menu opened
    // from within a tray callback doesn't strand the tray's inbox routing.
    let prev_owner = OWNER_HWND.with(|h| h.replace(popup_hwnd as isize));
    // Mirror the thread-safe owner so foreign-thread UIA actions wake this pump;
    // restore the prior value (e.g. a tray loop's) when the session ends.
    #[cfg(feature = "a11y")]
    let prev_a11y_owner = A11Y_OWNER.swap(popup_hwnd as isize, Ordering::SeqCst);

    // DEVICE-VERIFY(0.9.0): scoped modal pump. Unlike the tray, this drives the
    // popup with a bounded `GetMessageW` loop (no persistent owner window, no
    // `MAIN_APP`, no command inbox) so `open_at` / `anchored_to` blocks on the
    // caller's stack and returns when the menu dismisses. Callbacks still enqueue
    // into the shared `EVENTS` inbox, which we drain after each dispatched message;
    // that the `WS_EX_NOACTIVATE` popup + global hooks deliver these events as
    // expected can only be confirmed on a real Windows display.
    unsafe {
        let mut msg: MSG = std::mem::zeroed();
        while session.popup.is_some() {
            let got = GetMessageW(&mut msg, null_mut(), 0, 0);
            if got <= 0 {
                // `WM_QUIT` (0) or an error (-1): stop pumping and tear down below.
                break;
            }
            TranslateMessage(&msg);
            DispatchMessageW(&msg);
            session.drain_events();
        }
    }

    // Ensure the windows + hooks are gone even if the pump exited on `WM_QUIT`
    // with the popup still open (`close_popup` is a no-op once already closed).
    session.close_popup();
    OWNER_HWND.with(|h| h.set(prev_owner));
    ACTIVE_SESSION.with(|c| c.set(prev_active_session));
    #[cfg(feature = "a11y")]
    A11Y_OWNER.store(prev_a11y_owner, Ordering::SeqCst);
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn point_in_any_matches_windows_rects() {
        // Two windows: a popup and a flyout to its right.
        let rects = [(100, 200, 300, 500), (300, 220, 460, 420)];
        // Inside the popup.
        assert!(point_in_any(&rects, 150, 250));
        // Inside the flyout.
        assert!(point_in_any(&rects, 400, 300));
        // In the gap above / outside both → a dismissing click.
        assert!(!point_in_any(&rects, 150, 100));
        assert!(!point_in_any(&rects, 500, 300));
        // Right/bottom edges are exclusive (a click on the far edge is outside).
        assert!(!point_in_any(&[(0, 0, 10, 10)], 10, 5));
        assert!(!point_in_any(&[(0, 0, 10, 10)], 5, 10));
        assert!(point_in_any(&[(0, 0, 10, 10)], 0, 0));
    }

    // FIX 6: the N-level flyout reconciliation `apply_flyout_stack` performs —
    // keep the common prefix, close everything deeper, push the rest — must hold
    // beyond the single happy path. `common_flyout_prefix` is the pure decision it
    // rests on, so these guard the multi-level cases directly.
    #[test]
    fn flyout_reconcile_switches_to_shallower_sibling() {
        // A 3-deep stack switches to a shallower sibling under the first level:
        // level 0 is kept, levels 1 and 2 are closed, and the sibling is pushed.
        let current = [1, 2, 3];
        let target = [1, 5];
        let common = common_flyout_prefix(&current, &target);
        assert_eq!(common, 1, "only the shared level-0 parent is kept");
        // truncate_flyouts(common) would close depths >= 1 (the old 2 and 3)…
        assert_eq!(&current[common..], &[2, 3]);
        // …and the remaining target levels (the sibling 5) get pushed.
        assert_eq!(&target[common..], &[5]);
    }

    #[test]
    fn flyout_reconcile_rehovering_open_parent_keeps_children() {
        // Re-hovering an already-open parent chain yields an identical target, so
        // the entire stack is the common prefix: nothing is closed, nothing pushed
        // (no flyout flicker on a redundant hover).
        let current = [1, 2];
        let target = [1, 2];
        let common = common_flyout_prefix(&current, &target);
        assert_eq!(common, 2);
        assert!(current[common..].is_empty(), "no deeper level is closed");
        assert!(target[common..].is_empty(), "no level is re-pushed");
    }

    #[test]
    fn flyout_reconcile_switching_top_sibling_and_collapsing() {
        // Switching the top-level sibling shares nothing: the whole old stack is
        // closed and the new one is opened from scratch.
        assert_eq!(common_flyout_prefix(&[1, 2], &[5]), 0);
        // Extending an open parent one level deeper keeps it and pushes the child.
        assert_eq!(common_flyout_prefix(&[1], &[1, 2]), 1);
        // An empty target (outside-hover) collapses everything.
        assert_eq!(common_flyout_prefix(&[1, 2, 3], &[]), 0);
        // An empty current (nothing open) has no common prefix to keep.
        assert_eq!(common_flyout_prefix(&[], &[1, 2]), 0);
    }

    #[test]
    fn geometry_maps_logical_to_physical_round_trip() {
        let geom = WinGeometry {
            anchor: RECT {
                left: 1800,
                top: 1400,
                right: 1832,
                bottom: 1432,
            },
            work: RECT {
                left: 0,
                top: 0,
                right: 3840,
                bottom: 2100,
            },
            scale: 2.0,
        };
        // Work area in logical space is physical / scale.
        let wa = geom.work_area_local();
        assert_eq!(wa.size.width, 1920.0);
        assert_eq!(wa.size.height, 1050.0);
        // A logical origin converts back to physical by * scale.
        let (px, py) = geom.to_physical(LogicalPoint::new(100.0, 50.0));
        assert_eq!((px, py), (200, 100));
        // The anchor is below the work area (taskbar), as expected on Windows.
        let anchor = geom.anchor_rect_local();
        assert_eq!(anchor.origin.y, 700.0);
    }

    // FIX 2 (conformance): `fill_tip` must always leave a NUL terminator, even
    // when the tooltip encodes to ≥128 UTF-16 units — otherwise Win32 reads past
    // `szTip`.
    #[test]
    fn fill_tip_always_nul_terminates_when_overlong() {
        let long = "A".repeat(200);
        let mut buf = [0u16; 128];
        WindowsAnchor::fill_tip(&long, &mut buf);
        // The final slot is a guaranteed NUL terminator.
        assert_eq!(
            buf[buf.len() - 1],
            0,
            "the last szTip slot must remain a NUL terminator"
        );
        // The 127 usable slots are filled with content (no truncation to nothing).
        assert_eq!(buf[0], u16::from(b'A'));
        assert_eq!(buf[126], u16::from(b'A'));
        assert_ne!(buf[126], 0);
    }

    #[test]
    fn fill_tip_terminates_a_short_tooltip_too() {
        let mut buf = [0u16; 128];
        WindowsAnchor::fill_tip("Hi", &mut buf);
        assert_eq!(buf[0], u16::from(b'H'));
        assert_eq!(buf[1], u16::from(b'i'));
        // `wide` appends its own NUL, and the rest stays zero.
        assert_eq!(buf[2], 0);
        assert_eq!(buf[127], 0);
    }

    // FIX 1 (correctness): a 2-level-nested menu must open the nested flyout and
    // dispatch the *deep leaf* id — not the submenu row's id, and not resolved
    // against the top-level menu. We prove the N-level resolution the fixed click
    // and keyboard paths rely on, without creating real windows.
    #[test]
    fn nested_submenu_opens_deep_flyout_and_dispatches_deep_leaf() {
        use crate::menu::Row;

        // top:  0 "a"
        //       1 "outer" ->  0 "inner_leaf"
        //                     1 "inner_leaf2"
        //                     2 "middle" -> 0 "deep_leaf"
        //       2 "quit"
        //
        // `middle` sits at index 2 *within the outer flyout*; index 2 in the
        // *top* menu is the non-submenu "quit" — so a flyout-local index resolved
        // against the top menu (the single-level bug) lands on the wrong item.
        let menu = Menu::new()
            .row(Row::new("a").label("Apple"))
            .submenu(
                Row::new("outer").label("Outer"),
                Menu::new()
                    .row(Row::new("inner_leaf").label("Inner Leaf"))
                    .row(Row::new("inner_leaf2").label("Inner Leaf 2"))
                    .submenu(
                        Row::new("middle").label("Middle"),
                        Menu::new().row(Row::new("deep_leaf").label("Deep Leaf")),
                    ),
            )
            .row(Row::new("quit").label("Quit"));
        let outer = 1; // submenu index in the top-level menu
        let middle = 2; // submenu index *within* the outer flyout

        // Level descent (drives `menu_at_level`, hence every click / key path).
        assert_eq!(menu_at_stack(&menu, &[]).unwrap().items.len(), 3);
        let level1 = menu_at_stack(&menu, &[outer]).expect("outer is a submenu");
        // The nested submenu row is detected as a *submenu* at flyout level 1, so
        // `on_click`'s flyout branch opens the next level instead of dispatching.
        assert!(
            matches!(level1.items.get(middle), Some(Item::Submenu { .. })),
            "clicking the nested submenu row must open a deeper flyout"
        );
        // The single-level bug in the flesh: resolving the flyout-local `middle`
        // index against the *top* menu (as the old `open_flyout(i)` / flyout-click
        // path did) hits "quit", a non-submenu — so it can never open the nested
        // flyout. Only the deepest-level resolution is correct.
        assert!(
            menu_at_stack(&menu, &[middle]).is_none(),
            "top-level resolution of a flyout-local submenu index must fail"
        );

        // The deepest level's leaf carries the deep id — what actually gets
        // dispatched — not the "middle" submenu row's id.
        let deepest = menu_at_stack(&menu, &[outer, middle]).expect("middle is a submenu");
        match deepest.items.first() {
            Some(Item::Row(row)) => assert_eq!(row.id, MenuId::from("deep_leaf")),
            other => panic!("expected the deep leaf row, got {other:?}"),
        }

        // Mouse: hovering the nested submenu row inside flyout level 1 grows the
        // open stack to two levels (decision #8), so a click there opens it.
        let stack_after_hover = next_flyout(
            &[outer],
            HoverTarget::ParentRow {
                panel: 1,
                index: middle,
            },
        );
        assert_eq!(stack_after_hover, vec![outer, middle]);

        // Keyboard: with the outer flyout open + the nested submenu selected,
        // Right descends. `handle_key` returns the *flyout-local* index and pushes
        // the frame, so `push_flyout` (which opens from the deepest open level)
        // resolves it correctly — the exact index the old `open_flyout(i)`, which
        // resolved against the top menu, would have mis-opened.
        let mut focus = MenuFocus {
            top: Some(outer),
            flyout: vec![FlyoutFocus {
                parent: outer,
                child: Some(middle),
            }],
        };
        let action = handle_key(&menu, &mut focus, NavKey::Right);
        assert_eq!(action, NavAction::OpenFlyout(middle));
        let parents: Vec<usize> = focus.flyout.iter().map(|f| f.parent).collect();
        assert_eq!(
            parents,
            vec![outer, middle],
            "keyboard descent must build the same 2-level stack the mouse does"
        );
        // And resolving that keyboard stack lands on the deep leaf.
        let deepest = menu_at_stack(&menu, &parents).expect("keyboard stack resolves");
        match deepest.items.first() {
            Some(Item::Row(row)) => assert_eq!(row.id, MenuId::from("deep_leaf")),
            other => panic!("expected the deep leaf row, got {other:?}"),
        }
    }

    // #33: nested popup sessions must not conflate each other's queued events.
    // `partition_session_events` is the pure logic behind `take_session_events`
    // (in turn behind both `PopupSession::drain_events` and `AppState::drain`),
    // so the session-id filtering is exercised here on a plain `Vec` — no
    // `HWND`/message pump required.
    #[test]
    fn session_events_are_filtered_by_owning_session_and_order_preserved() {
        let outer = 1u32;
        let inner = 2u32;
        let events = vec![
            (
                outer,
                UiEvent::MouseMoved {
                    kind: WindowKind::Popup,
                    x: 1.0,
                    y: 1.0,
                },
            ),
            (
                inner,
                UiEvent::MouseMoved {
                    kind: WindowKind::Popup,
                    x: 2.0,
                    y: 2.0,
                },
            ),
            (
                outer,
                UiEvent::MouseClick {
                    kind: WindowKind::Popup,
                    x: 3.0,
                    y: 3.0,
                },
            ),
            (
                inner,
                UiEvent::MouseClick {
                    kind: WindowKind::Popup,
                    x: 4.0,
                    y: 4.0,
                },
            ),
        ];

        let (mine, other) = partition_session_events(events, inner);

        // Only the inner session's two events come back, in their original order.
        assert_eq!(mine.len(), 2);
        assert!(matches!(
            mine[0],
            UiEvent::MouseMoved { x, .. } if x == 2.0
        ));
        assert!(matches!(
            mine[1],
            UiEvent::MouseClick { x, .. } if x == 4.0
        ));

        // The outer session's two events are left behind, untouched and still in
        // their original order — an inner (nested) session's drain must never
        // consume, drop, or reorder an outer session's still-pending events.
        assert_eq!(other.len(), 2);
        assert_eq!(other[0].0, outer);
        assert_eq!(other[1].0, outer);
        assert!(matches!(
            other[0].1,
            UiEvent::MouseMoved { x, .. } if x == 1.0
        ));
        assert!(matches!(
            other[1].1,
            UiEvent::MouseClick { x, .. } if x == 3.0
        ));
    }

    // #33: `GWLP_USERDATA` must roundtrip both the window's `WindowKind` and its
    // owning session's id, so two nested sessions' popups (both tagged
    // `POPUP_TAG`) remain distinguishable by session id alone.
    #[test]
    fn packed_tag_roundtrips_kind_and_session_id() {
        for (kind, session_id) in [
            (WindowKind::Popup, 1u32),
            (WindowKind::Popup, 2u32),
            (WindowKind::Flyout(0), 1u32),
            (WindowKind::Flyout(3), 42u32),
        ] {
            let raw = packed_tag(kind, session_id);
            // Mirror `window_kind`'s decode without a live `HWND`.
            let decoded_session = ((raw as u64) >> 32) as u32;
            let decoded_tag = (raw as u64 & 0xFFFF_FFFF) as isize;
            assert_eq!(decoded_session, session_id);
            assert_eq!(decoded_tag, kind.tag());
        }

        // Two sessions' top-level popups share the same `WindowKind` tag but
        // pack to different `GWLP_USERDATA` values — the crux of the #33 fix.
        assert_ne!(
            packed_tag(WindowKind::Popup, 1),
            packed_tag(WindowKind::Popup, 2)
        );
    }
}