crcbl-shell 0.17.1

Crucible windowing shell: own Wayland, X11, Web/canvas and headless backends
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
//! Hand-written FFI to `user32`, `gdi32`, `shcore`, `shell32`, `imm32`,
//! `dwmapi`, `ole32` and `kernel32`, and the wire structures the Win32 backend
//! passes across it.
//!
//! # Decision: `#[link]`, not `dlopen` — the opposite of the two Linux backends
//!
//! `x11::ffi` and `wayland::ffi` both load their libraries with `dlopen`, and
//! both state the same reason: the registry in [`backend`](crate::backend) is a
//! fall-through list, so an entry has to be able to fail at *runtime*. A
//! `DT_NEEDED` on `libwayland-client.so.0` kills the process in `ld.so` before
//! [`open`](crate::open) runs, on any machine that does not have it — and a
//! machine without libwayland is an ordinary machine.
//!
//! **That premise does not hold here, and the asymmetry is deliberate rather
//! than an oversight.** `user32.dll`, `gdi32.dll`, `shell32.dll`, `imm32.dll`,
//! `ole32.dll` and `kernel32.dll` are part of the operating system: a Windows
//! that lacks them is not a Windows this engine failed to support, it is a
//! Windows that cannot run any process at all. `shcore.dll` ships with every
//! Windows since 8.1 and `dwmapi.dll` with every one since Vista, both below
//! this backend's floor. There is nothing for a runtime
//! probe to discover, and `LoadLibraryW` + `GetProcAddress` for the system
//! libraries would buy exactly one thing: a fallible code path with no failure.
//!
//! The registry consequence is the one that matters and it is satisfied:
//! Windows has a single backend, so there is no fall-through to protect. If a
//! second Windows backend is ever added, the entry that must be able to fail is
//! *that* one.
//!
//! # Decision: Windows 10 version 1607 is the floor
//!
//! Set by DPI, not by anything else here. The windowing rules in
//! `docs/notes/backends.md` require
//! "one `scale_factor` concept over … per-monitor-v2 (Windows)", and the three
//! APIs that make per-monitor DPI work — `SetProcessDpiAwarenessContext`,
//! `GetDpiForWindow` and `AdjustWindowRectExForDpi` — all arrive in 1607.
//! `GetPointerType` and the `WM_POINTER*` messages are Windows 8, below the
//! floor; everything else this module declares is Windows XP-era.
//!
//! One wrinkle is worth stating rather than discovering: the *awareness context
//! value* [`DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2`](value::DPI_PER_MONITOR_AWARE_V2)
//! is documented from 1703, one release after the function that takes it. On a
//! 1607 host the call therefore fails with `ERROR_INVALID_PARAMETER` instead of
//! being missing, which is why
//! `shell::set_dpi_awareness` inspects
//! `GetLastError` rather than treating a `FALSE` return as fatal. Below 1607
//! the process fails to *start*, in the loader, exactly as the Linux backends'
//! `dlopen` argument predicts — and that is the price of linking, paid
//! knowingly on a platform where the libraries cannot be absent.
//!
//! # What is deliberately not declared
//!
//! | Not used | What it would buy | Why not |
//! | --- | --- | --- |
//! | `EnumDisplayDevicesW` | a monitor's marketing name | it usually answers "Generic PnP Monitor", which is worse than the device name for telling two displays apart |
//! | `ToUnicode` | the character a key produces | it **consumes** dead-key state, so calling it would eat the accent `WM_CHAR` was about to deliver. [`MapVirtualKeyW`] with `MAPVK_VK_TO_CHAR` answers the same question without side effects |
//! | `GetAsyncKeyState` | modifier state | it reads the hardware *now*, not at the message's time. [`GetKeyboardState`] is the snapshot that belongs to the message being processed |
//! | `RegisterDragDrop` and `IDropTarget` | drag *feedback* — a drop cursor, hover highlighting, non-file formats | it is COM: `OleInitialize`, a hand-written vtable, `IUnknown` reference counting and an apartment this crate does not own. `WM_DROPFILES` delivers the file paths the seam asks for; see `win32::dnd` for the whole comparison |
//! | `SetClipboardData` with a null handle | delayed rendering — claim the format now, produce the bytes when asked | the owner must answer `WM_RENDERFORMAT` **synchronously, from the window procedure**, and this backend's procedure records rather than acts for the reason its own docs give. See `win32::clipboard` |
//! | `AddClipboardFormatListener` | a "the clipboard changed" event | the seam has no such event, and a backend that invented one would be the only implementation of it |
//! | `SetTimer` | a frame during a modal resize loop | see the `win32` module docs — it needs a callback the seam does not have |

#![allow(non_snake_case)]

use core::ffi::c_void;

// ---------------------------------------------------------------------------
// Scalar aliases
// ---------------------------------------------------------------------------

/// Every Win32 handle this backend touches: `HWND`, `HINSTANCE`, `HMONITOR`,
/// `HCURSOR`, `HBRUSH`, `HMENU`, `HDC`.
///
/// One alias rather than a newtype per kind, for the reason the X11 backend
/// uses one `Cookie` for every `xcb_*_cookie_t`: they are the same thing on the
/// wire, and the type system cannot check which one a message actually carried.
/// Where a distinction matters it is in the parameter name.
pub type Handle = *mut c_void;

/// `WPARAM`.
pub type Wparam = usize;
/// `LPARAM`.
pub type Lparam = isize;
/// `LRESULT`.
pub type Lresult = isize;
/// `BOOL` — zero is false, anything else is true. **Not** `bool`: Win32
/// functions return `TRUE` as `1` but callbacks may return any non-zero value,
/// and `bool` has exactly two valid bit patterns.
pub type Bool32 = i32;

/// `WNDPROC`.
pub type WindowProc = unsafe extern "system" fn(Handle, u32, Wparam, Lparam) -> Lresult;

/// `MONITORENUMPROC`.
pub type MonitorEnumProc = unsafe extern "system" fn(Handle, Handle, *mut Rect, Lparam) -> Bool32;

/// `ENUMRESNAMEPROCW`: one resource's name, which is an integer id in the low
/// word when its high bits are zero and a NUL-terminated string otherwise.
pub type EnumResNameProc =
    unsafe extern "system" fn(Handle, *const u16, *mut u16, Lparam) -> Bool32;

// ---------------------------------------------------------------------------
// Structures
// ---------------------------------------------------------------------------

/// `RECT` — left, top, right, bottom, and the right/bottom edges are
/// **exclusive**.
///
/// The single most common Win32 mistake is treating it as a position and a
/// size; it is two corners, and `GetClientRect` always answers with a zero
/// origin.
#[repr(C)]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Rect {
    /// Left edge, inclusive.
    pub left: i32,
    /// Top edge, inclusive.
    pub top: i32,
    /// Right edge, exclusive.
    pub right: i32,
    /// Bottom edge, exclusive.
    pub bottom: i32,
}

impl Rect {
    /// Width, clamped at zero — a rectangle whose right edge is left of its
    /// left one is degenerate rather than negative-width.
    pub const fn width(self) -> i32 {
        if self.right > self.left {
            self.right - self.left
        } else {
            0
        }
    }

    /// Height, on the same terms as [`width`](Self::width).
    pub const fn height(self) -> i32 {
        if self.bottom > self.top {
            self.bottom - self.top
        } else {
            0
        }
    }

    /// The overlap of two rectangles, degenerate when they do not touch.
    ///
    /// Here because **`ClipCursor` intersects with the virtual screen** before
    /// applying: a window wider than the desktop gets a clip narrower than its
    /// client area, and nothing reports that it happened. A test that asserts
    /// the clip equals the client rectangle is therefore asserting something the
    /// API does not promise; one that asserts it equals this is asserting what
    /// it does.
    ///
    /// Test-only, because the backend never has to compute the clamp — the
    /// system applies it — and only a test has to *predict* it.
    #[cfg(test)]
    pub const fn intersect(self, other: Self) -> Self {
        let left = if self.left > other.left {
            self.left
        } else {
            other.left
        };
        let top = if self.top > other.top {
            self.top
        } else {
            other.top
        };
        let right = if self.right < other.right {
            self.right
        } else {
            other.right
        };
        let bottom = if self.bottom < other.bottom {
            self.bottom
        } else {
            other.bottom
        };
        Self {
            left,
            top,
            right,
            bottom,
        }
    }
}

/// `APPBARDATA`: what every `SHAppBarMessage` call reads and writes.
#[repr(C)]
#[derive(Clone, Copy, Debug)]
pub struct AppBarData {
    /// The structure's own size, which the shell checks.
    pub cb_size: u32,
    /// The appbar's window.
    pub hwnd: Handle,
    /// The message the shell sends the appbar its `ABN_*` notifications in.
    pub callback_message: u32,
    /// An `ABE_*` edge.
    pub edge: u32,
    /// The appbar's rectangle, in desktop pixels.
    pub rc: Rect,
    /// Message-specific.
    pub l_param: Lparam,
}

impl AppBarData {
    /// One for `hwnd`, with every other field zero.
    pub fn new(hwnd: Handle) -> Self {
        Self {
            cb_size: size_of::<Self>() as u32,
            hwnd,
            callback_message: 0,
            edge: 0,
            rc: Rect::default(),
            l_param: 0,
        }
    }
}

/// `POINT`.
#[repr(C)]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Point {
    /// Horizontal coordinate.
    pub x: i32,
    /// Vertical coordinate.
    pub y: i32,
}

/// `MSG`.
///
/// `l_private` is declared by `winuser.h` only under `_MAC`; on x64 it sits in
/// what is otherwise the structure's tail padding, so the struct is 48 bytes
/// either way. Declaring it is free, and reading a message into a buffer the
/// system considers larger than ours is the failure that is not free.
#[repr(C)]
#[derive(Clone, Copy, Debug, Default)]
pub struct Msg {
    /// Window the message is for, or null for a thread message.
    pub hwnd: Handle,
    /// `WM_*`.
    pub message: u32,
    /// First parameter.
    pub w_param: Wparam,
    /// Second parameter.
    pub l_param: Lparam,
    /// `GetTickCount` milliseconds when the message was posted — the clock
    /// [`TimeBase`](super::TimeBase) rebases.
    pub time: u32,
    /// Cursor position in screen coordinates when the message was posted.
    pub pt: Point,
    /// Undocumented tail; see the type docs.
    pub l_private: u32,
}

// The derived `Default` zeroes every field, including the `Handle`, which is
// what `PeekMessageW` expects to be handed: it writes the whole structure and
// reads none of it.

/// `WNDCLASSEXW`.
#[repr(C)]
#[derive(Clone, Copy, Debug)]
pub struct WndClassExW {
    /// `size_of::<WndClassExW>()`, which the system validates.
    pub cb_size: u32,
    /// `CS_*` class styles.
    pub style: u32,
    /// The window procedure.
    pub lpfn_wnd_proc: WindowProc,
    /// Extra bytes after the class structure. Zero.
    pub cb_cls_extra: i32,
    /// Extra bytes after each window instance. Zero — this backend keeps its
    /// per-window state in `GWLP_USERDATA` instead; see [`super::proc`].
    pub cb_wnd_extra: i32,
    /// Module that owns the class.
    pub h_instance: Handle,
    /// Large icon. Null: the default is used.
    pub h_icon: Handle,
    /// Class cursor.
    pub h_cursor: Handle,
    /// Background brush.
    pub hbr_background: Handle,
    /// Menu resource name. Null.
    pub lpsz_menu_name: *const u16,
    /// Class name, NUL-terminated UTF-16.
    pub lpsz_class_name: *const u16,
    /// Small icon. Null.
    pub h_icon_sm: Handle,
}

/// `CREATESTRUCTW`, of which this backend reads exactly one field.
///
/// [`lp_create_params`](Self::lp_create_params) is how the `lpParam` handed to
/// `CreateWindowExW` reaches the window procedure, and it is the only way:
/// `WM_NCCREATE` arrives before `CreateWindowExW` has returned, so there is no
/// `HWND` to have stored anything against yet.
#[repr(C)]
#[derive(Clone, Copy, Debug)]
pub struct CreateStructW {
    /// The `lpParam` argument of `CreateWindowExW`.
    pub lp_create_params: *mut c_void,
    /// Module handle.
    pub h_instance: Handle,
    /// Menu handle.
    pub h_menu: Handle,
    /// Parent window.
    pub hwnd_parent: Handle,
    /// Height.
    pub cy: i32,
    /// Width.
    pub cx: i32,
    /// Top.
    pub y: i32,
    /// Left.
    pub x: i32,
    /// Window style.
    pub style: i32,
    /// Window name.
    pub lpsz_name: *const u16,
    /// Class name.
    pub lpsz_class: *const u16,
    /// Extended style.
    pub dw_ex_style: u32,
}

/// `MINMAXINFO` — what `WM_GETMINMAXINFO` asks the window to fill in.
///
/// The two fields that matter are the **track** sizes, which bound an
/// interactive resize. `pt_max_size` bounds a *maximize* and is deliberately
/// left alone: a maximized window that is smaller than the monitor because a
/// size constraint said so is not what a maximize button means.
#[repr(C)]
#[derive(Clone, Copy, Debug, Default)]
pub struct MinMaxInfo {
    /// Reserved.
    pub pt_reserved: Point,
    /// Size of a maximized window.
    pub pt_max_size: Point,
    /// Position of a maximized window.
    pub pt_max_position: Point,
    /// Smallest the user may drag the window to, in **window** pixels.
    pub pt_min_track_size: Point,
    /// Largest the user may drag the window to, in **window** pixels.
    pub pt_max_track_size: Point,
}

/// `WINDOWPLACEMENT` — the whole of a window's restored geometry and show
/// state.
///
/// Saved on the way into borderless and restored on the way out, because
/// remembering only the window rectangle loses whether the window was
/// maximized, and restoring a maximized window as a floating one of the same
/// size is visibly wrong.
#[repr(C)]
#[derive(Clone, Copy, Debug, Default)]
pub struct WindowPlacement {
    /// `size_of::<WindowPlacement>()`, which the system validates.
    pub length: u32,
    /// `WPF_*` flags.
    pub flags: u32,
    /// `SW_*` show state.
    pub show_cmd: u32,
    /// Minimized position.
    pub pt_min_position: Point,
    /// Maximized position.
    pub pt_max_position: Point,
    /// Restored rectangle, in workspace coordinates.
    pub rc_normal_position: Rect,
}

/// `MONITORINFOEXW`.
///
/// The `EX` half is [`sz_device`](Self::sz_device), and it is why this is the
/// structure used rather than plain `MONITORINFO`: the device name is the only
/// stable per-monitor identity Win32 offers without a second API, and
/// [`MonitorId`](crate::MonitorId) must not be reused within a session.
#[repr(C)]
#[derive(Clone, Copy, Debug)]
pub struct MonitorInfoExW {
    /// `size_of::<MonitorInfoExW>()`, which selects the `EX` form.
    pub cb_size: u32,
    /// The monitor's rectangle in virtual-screen coordinates.
    pub rc_monitor: Rect,
    /// The same, minus taskbars and appbars.
    pub rc_work: Rect,
    /// `MONITORINFOF_PRIMARY`.
    pub dw_flags: u32,
    /// `\\.\DISPLAY1` and friends, NUL-padded.
    pub sz_device: [u16; 32],
}

impl Default for MonitorInfoExW {
    fn default() -> Self {
        Self {
            cb_size: size_of::<Self>() as u32,
            rc_monitor: Rect::default(),
            rc_work: Rect::default(),
            dw_flags: 0,
            sz_device: [0; 32],
        }
    }
}

/// `DEVMODEW`, flattened.
///
/// The two unions in the real structure are each replaced by their display
/// arm, because this backend reads exactly one field out of it —
/// [`dm_display_frequency`](Self::dm_display_frequency) — and an arm only a
/// printer driver writes is layout, not meaning. The layout assertions in this
/// module's tests are what make that safe: get the padding wrong and every
/// field after the mistake is read from the wrong offset, which produces a
/// plausible number rather than a crash.
#[repr(C)]
#[derive(Clone, Copy, Debug)]
pub struct DevModeW {
    /// Device name.
    pub dm_device_name: [u16; 32],
    /// Structure version.
    pub dm_spec_version: u16,
    /// Driver version.
    pub dm_driver_version: u16,
    /// `size_of::<DevModeW>()`, which the driver validates.
    pub dm_size: u16,
    /// Extra driver bytes after this structure. Zero.
    pub dm_driver_extra: u16,
    /// Which fields are meaningful.
    pub dm_fields: u32,
    /// Where the display sits on the virtual desktop: `dmPosition`, the start
    /// of the printer/display union's display arm. The printer arm,
    /// `dmOrientation` to `dmPrintQuality`, covers the same bytes as this
    /// field and the two after it.
    pub dm_position: Point,
    /// `DMDO_*` rotation.
    pub dm_display_orientation: u32,
    /// `DMDFO_*` scaling, for a fixed-resolution output.
    pub dm_display_fixed_output: u32,
    /// Colour.
    pub dm_color: i16,
    /// Duplex.
    pub dm_duplex: i16,
    /// Y resolution.
    pub dm_y_resolution: i16,
    /// TrueType option.
    pub dm_tt_option: i16,
    /// Collation.
    pub dm_collate: i16,
    /// Form name.
    pub dm_form_name: [u16; 32],
    /// Logical pixels per inch.
    pub dm_log_pixels: u16,
    /// Bits per pixel.
    pub dm_bits_per_pel: u32,
    /// Width in pixels.
    pub dm_pels_width: u32,
    /// Height in pixels.
    pub dm_pels_height: u32,
    /// The display-flags/n-up union, both of whose arms are a `DWORD`.
    pub dm_display_flags: u32,
    /// **Refresh rate in whole hertz.** The only field this backend reads.
    pub dm_display_frequency: u32,
    /// ICM method.
    pub dm_icm_method: u32,
    /// ICM intent.
    pub dm_icm_intent: u32,
    /// Media type.
    pub dm_media_type: u32,
    /// Dither type.
    pub dm_dither_type: u32,
    /// Reserved.
    pub dm_reserved1: u32,
    /// Reserved.
    pub dm_reserved2: u32,
    /// Panning width.
    pub dm_panning_width: u32,
    /// Panning height.
    pub dm_panning_height: u32,
}

impl Default for DevModeW {
    fn default() -> Self {
        // Zeroed apart from `dm_size`, which is how the driver knows which
        // fields of which generation of the structure it may write.
        Self {
            dm_device_name: [0; 32],
            dm_spec_version: 0,
            dm_driver_version: 0,
            dm_size: size_of::<Self>() as u16,
            dm_driver_extra: 0,
            dm_fields: 0,
            dm_position: Point::default(),
            dm_display_orientation: 0,
            dm_display_fixed_output: 0,
            dm_color: 0,
            dm_duplex: 0,
            dm_y_resolution: 0,
            dm_tt_option: 0,
            dm_collate: 0,
            dm_form_name: [0; 32],
            dm_log_pixels: 0,
            dm_bits_per_pel: 0,
            dm_pels_width: 0,
            dm_pels_height: 0,
            dm_display_flags: 0,
            dm_display_frequency: 0,
            dm_icm_method: 0,
            dm_icm_intent: 0,
            dm_media_type: 0,
            dm_dither_type: 0,
            dm_reserved1: 0,
            dm_reserved2: 0,
            dm_panning_width: 0,
            dm_panning_height: 0,
        }
    }
}

/// `LUID` — a locally unique identifier; here, which adapter (GPU) a
/// `QueryDisplayConfig` path or mode belongs to.
#[repr(C)]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Luid {
    /// Low 32 bits.
    pub low_part: u32,
    /// High 32 bits.
    pub high_part: i32,
}

/// `DISPLAYCONFIG_2DREGION` — a width and height, with no position.
#[repr(C)]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct DisplayConfig2dRegion {
    /// Width in pixels.
    pub cx: u32,
    /// Height in pixels.
    pub cy: u32,
}

/// `DISPLAYCONFIG_RATIONAL` — a numerator over a denominator, the exact form
/// `QueryDisplayConfig` reports a signal rate in.
#[repr(C)]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct DisplayConfigRational {
    /// Numerator.
    pub numerator: u32,
    /// Denominator.
    pub denominator: u32,
}

impl DisplayConfigRational {
    /// The rate this rational expresses in millihertz, truncated, or `None`
    /// for a degenerate rational (a zero numerator or denominator).
    ///
    /// `divider` is the signal's `vSyncFreqDivider` (0 for a progressive
    /// mode): when non-zero, the rate is the rational divided by it, which is
    /// the interlaced case. 60000/1001 → 59940, the 59.94 Hz mode
    /// `EnumDisplaySettingsW` reports as the integer 60.
    pub const fn millihertz(self, divider: u32) -> Option<u32> {
        if self.numerator == 0 || self.denominator == 0 {
            return None;
        }
        let denominator = if divider == 0 {
            self.denominator
        } else {
            self.denominator.saturating_mul(divider)
        };
        if denominator == 0 {
            return None;
        }
        Some(self.numerator.saturating_mul(1_000) / denominator)
    }
}

/// `DISPLAYCONFIG_VIDEO_SIGNAL_INFO` — the signal a target mode describes.
#[repr(C)]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct DisplayConfigVideoSignalInfo {
    /// Pixel clock in hertz.
    pub pixel_rate: u64,
    /// Horizontal sync frequency.
    pub h_sync_freq: DisplayConfigRational,
    /// Vertical sync frequency — the refresh rate, once
    /// [`additional_signal_info`](Self::additional_signal_info)'s divider has
    /// been applied.
    pub v_sync_freq: DisplayConfigRational,
    /// The visible region.
    pub active_size: DisplayConfig2dRegion,
    /// The whole scan-out region.
    pub total_size: DisplayConfig2dRegion,
    /// The `AdditionalSignalInfo` union value: `videoStandard` in the low 16
    /// bits, `vSyncFreqDivider` in bits 16-21.
    pub additional_signal_info: u32,
    /// `DISPLAYCONFIG_SCANLINE_ORDERING`.
    pub scan_line_ordering: i32,
}

/// `DISPLAYCONFIG_TARGET_MODE` — the mode a target (a display) is driving.
#[repr(C)]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct DisplayConfigTargetMode {
    /// The signal, including the exact refresh rational.
    pub target_video_signal_info: DisplayConfigVideoSignalInfo,
}

/// `DISPLAYCONFIG_MODE_INFO` — one entry of the mode array `QueryDisplayConfig`
/// fills.
///
/// The tail is a union of a 48-byte `DISPLAYCONFIG_TARGET_MODE` and a 20-byte
/// `DISPLAYCONFIG_SOURCE_MODE`, so [`target_mode`](Self::target_mode) — the
/// larger arm — determines the layout. This backend only reads target modes.
#[repr(C)]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct DisplayConfigModeInfo {
    /// `DISPLAYCONFIG_MODE_INFO_TYPE`: target, source or desktop image.
    pub info_type: i32,
    /// The adapter's id for this mode.
    pub id: u32,
    /// The adapter this mode belongs to.
    pub adapter_id: Luid,
    /// The union's larger arm, and therefore the layout; valid only when
    /// `info_type` is `DISPLAYCONFIG_MODE_INFO_TYPE_TARGET`.
    pub target_mode: DisplayConfigTargetMode,
}

/// `DISPLAYCONFIG_PATH_SOURCE_INFO` — the source half of a path.
#[repr(C)]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct DisplayConfigPathSourceInfo {
    /// The adapter.
    pub adapter_id: Luid,
    /// The source's id on that adapter.
    pub id: u32,
    /// The `modeInfoIdx` union value: the **source** mode's index in the high
    /// 16 bits, the clone-group id in the low 16.
    pub mode_info_idx: u32,
    /// `DISPLAYCONFIG_SOURCE_IN_USE` and friends.
    pub status_flags: u32,
}

/// `DISPLAYCONFIG_PATH_TARGET_INFO` — the target half of a path.
#[repr(C)]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct DisplayConfigPathTargetInfo {
    /// The adapter.
    pub adapter_id: Luid,
    /// The target's id on that adapter.
    pub id: u32,
    /// The `modeInfoIdx` union value: the **target** mode's index in the high
    /// 16 bits, the desktop-mode index in the low 16.
    pub mode_info_idx: u32,
    /// `DISPLAYCONFIG_VIDEO_OUTPUT_TECHNOLOGY`.
    pub output_technology: i32,
    /// `DISPLAYCONFIG_ROTATION`.
    pub rotation: i32,
    /// `DISPLAYCONFIG_SCALING`.
    pub scaling: i32,
    /// The path's own refresh; the target mode's signal carries the exact one.
    pub refresh_rate: DisplayConfigRational,
    /// `DISPLAYCONFIG_SCANLINE_ORDERING`.
    pub scan_line_ordering: i32,
    /// Whether the target is present.
    pub target_available: Bool32,
    /// `DISPLAYCONFIG_TARGET_IN_USE` and friends.
    pub status_flags: u32,
}

impl DisplayConfigPathTargetInfo {
    /// The target mode's index in the mode array `QueryDisplayConfig` filled:
    /// the high 16 bits of [`mode_info_idx`](Self::mode_info_idx), whose low 16
    /// bits are the desktop-mode index and are ignored. `None` for the "no
    /// mode" sentinel, `DISPLAYCONFIG_PATH_TARGET_MODE_IDX_INVALID`.
    pub const fn target_mode_index(self) -> Option<usize> {
        let index = (self.mode_info_idx >> 16) as usize;
        if index == value::DISPLAYCONFIG_PATH_TARGET_MODE_IDX_INVALID as usize {
            None
        } else {
            Some(index)
        }
    }
}

/// `DISPLAYCONFIG_PATH_INFO` — one path: a source driving a target.
#[repr(C)]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct DisplayConfigPathInfo {
    /// The source half.
    pub source_info: DisplayConfigPathSourceInfo,
    /// The target half.
    pub target_info: DisplayConfigPathTargetInfo,
    /// `DISPLAYCONFIG_PATH_ACTIVE` and friends.
    pub flags: u32,
}

/// `DISPLAYCONFIG_DEVICE_INFO_HEADER` — the request every
/// `DisplayConfigGetDeviceInfo` call is framed with.
#[repr(C)]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct DisplayConfigDeviceInfoHeader {
    /// `DISPLAYCONFIG_DEVICE_INFO_TYPE`: which request this is.
    pub kind: i32,
    /// Size of the request structure, which the system validates.
    pub size: u32,
    /// The adapter the request is about.
    pub adapter_id: Luid,
    /// The source or target id on that adapter.
    pub id: u32,
}

/// `DISPLAYCONFIG_SOURCE_DEVICE_NAME` — the `GET_SOURCE_NAME` request's answer.
///
/// [`view_gdi_device_name`](Self::view_gdi_device_name) is the source's
/// `\\.\DISPLAYn` name — the same string `MONITORINFOEXW::szDevice` carries,
/// which is the identity this backend maps monitors through.
#[repr(C)]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct DisplayConfigSourceDeviceName {
    /// The request header, answered in place.
    pub header: DisplayConfigDeviceInfoHeader,
    /// The GDI device name, NUL-padded. `CCHDEVICENAME` = 32.
    pub view_gdi_device_name: [u16; 32],
}

/// `TRACKMOUSEEVENT` — what `TrackMouseEvent` is asked to watch for.
///
/// Needed because **Windows has no `WM_MOUSEENTER`**. A window is told when the
/// pointer leaves and never when it arrives, and only if it asked: this
/// structure is the asking, and it re-arms one shot at a time. See
/// [`proc`](super::proc) for where the entry half is derived from.
#[repr(C)]
#[derive(Clone, Copy, Debug, Default)]
pub struct TrackMouse {
    /// `size_of::<TrackMouse>()`, which the system validates.
    pub cb_size: u32,
    /// `TME_*`.
    pub dw_flags: u32,
    /// The window to watch.
    pub hwnd_track: Handle,
    /// Hover timeout, unused without `TME_HOVER`.
    pub dw_hover_time: u32,
}

/// `DROPFILES` — the header of the block an `HDROP` names.
///
/// **Test-only, and deliberately.** The backend never parses this: it reads a
/// drop through `DragQueryFileW`, which is shell32's job precisely because the
/// [`f_wide`](Self::f_wide) ANSI case and the file list's framing are shell32's
/// to own. What a test needs is the other direction — CI has nobody to drag a
/// file onto a window, so the only way to exercise `WM_DROPFILES` at all is to
/// build the block the shell would have handed over and send the message.
///
/// The layout assertion in this module's tests is what makes that synthesis
/// trustworthy: a header of the wrong length puts the file list at an offset
/// `DragQueryFileW` does not look at, and the test would then report zero files
/// and read as a backend bug.
///
/// `shlobj_core.h` declares it under `pshpack1.h`, so the C structure is
/// byte-aligned; this one is 4-aligned with the same size and offsets. That is
/// only safe in the direction it is used — a test writing a block for shell32
/// to read — and would not be for reading a `DROPFILES` out of shell memory.
#[cfg(test)]
#[repr(C)]
#[derive(Clone, Copy, Debug, Default)]
pub struct DropFiles {
    /// Offset of the file list from the start of this structure, in bytes.
    pub p_files: u32,
    /// Where the drop happened, in the window's client coordinates.
    pub pt: Point,
    /// Whether the drop was on the non-client area.
    pub f_nc: Bool32,
    /// **`TRUE` for a `WCHAR` file list**, which is the only kind this engine
    /// produces and the field an ANSI-era sender sets to `FALSE`.
    pub f_wide: Bool32,
}

/// `RAWINPUTDEVICE` — one usage page/usage pair to receive `WM_INPUT` for.
#[repr(C)]
#[derive(Clone, Copy, Debug, Default)]
pub struct RawInputDevice {
    /// HID usage page. `0x01` is the generic desktop page.
    pub us_usage_page: u16,
    /// HID usage within the page. `0x02` is the mouse.
    pub us_usage: u16,
    /// `RIDEV_*`.
    pub dw_flags: u32,
    /// Where `WM_INPUT` is delivered. Null means "follow the keyboard focus",
    /// which is what this backend wants — see [`input`](super::input).
    pub hwnd_target: Handle,
}

/// `RAWINPUTHEADER`.
#[repr(C)]
#[derive(Clone, Copy, Debug, Default)]
pub struct RawInputHeader {
    /// `RIM_TYPE*`.
    pub dw_type: u32,
    /// Size of the whole `RAWINPUT` this heads.
    pub dw_size: u32,
    /// The device that produced it, or null for injected input. What a
    /// [`DeviceId`](crcbl_core::input::DeviceId) is resolved from; see
    /// [`devices`](super::devices).
    pub h_device: Handle,
    /// The `wParam` of the `WM_INPUT` that carried it.
    pub w_param: Wparam,
}

/// `RAWMOUSE`.
///
/// The two-byte hole after [`us_flags`](Self::us_flags) is the C union's
/// alignment, spelled out rather than left to the compiler: the union's first
/// arm is a `ULONG`, so it starts at offset 4 whatever `usFlags` did. Naming it
/// changes nothing the compiler would not have done — `#[repr(C)]` inserts the
/// same two bytes — and it is here so a reader diffing this against `winuser.h`
/// can see that the gap was noticed rather than missed.
///
/// The layout assertion in this module's tests checks every field's offset and
/// width, so a field that is absent, the wrong width or swapped with its
/// neighbour all fail it. That is the real hazard: reading
/// [`l_last_x`](Self::l_last_x) from offset 8 instead of 12 gives half a button
/// mask as a mouse delta, and a plausible number rather than a crash. Same
/// shape as [`DevModeW`]'s, checked the same way.
#[repr(C)]
#[derive(Clone, Copy, Debug, Default)]
pub struct RawMouse {
    /// `MOUSE_MOVE_RELATIVE`, `MOUSE_MOVE_ABSOLUTE`, `MOUSE_VIRTUAL_DESKTOP`.
    /// **The field that decides what the two coordinates mean.**
    pub us_flags: u16,
    /// The union's alignment padding.
    pub padding: u16,
    /// `usButtonFlags` in the low half — the `RI_MOUSE_*` edges this report
    /// carries — and `usButtonData`, the wheel delta, in the high half. Not
    /// turned into events: the button *messages* carry position and ordering,
    /// and raw edges would double every click. Read only to say which device a
    /// button message came from.
    pub ul_buttons: u32,
    /// Raw button state, likewise unread.
    pub ul_raw_buttons: u32,
    /// Relative motion, or an absolute coordinate — see
    /// [`us_flags`](Self::us_flags).
    pub l_last_x: i32,
    /// See [`l_last_x`](Self::l_last_x).
    pub l_last_y: i32,
    /// Driver-supplied extra information.
    pub ul_extra_information: u32,
}

/// `COMPOSITIONFORM` — where an input method draws its composition window.
#[repr(C)]
#[derive(Clone, Copy, Debug, Default)]
pub struct CompositionForm {
    /// `CFS_*`: which of the two fields below mean anything.
    pub dw_style: u32,
    /// The window's top-left, in client coordinates, for `CFS_POINT`.
    pub pt_current_pos: Point,
    /// The area it may use, in client coordinates, for `CFS_RECT` (not used
    /// here: `CFS_POINT` puts the window at the caret).
    pub rc_area: Rect,
}

/// `CANDIDATEFORM` — where an input method opens its candidate list.
#[repr(C)]
#[derive(Clone, Copy, Debug, Default)]
pub struct CandidateForm {
    /// Which candidate list; `0` is the one every input method has.
    pub dw_index: u32,
    /// `CFS_*`.
    pub dw_style: u32,
    /// Where the list goes, in client coordinates.
    pub pt_current_pos: Point,
    /// For `CFS_EXCLUDE`, the area the list must not cover.
    pub rc_area: Rect,
}

/// `RAWKEYBOARD`.
#[repr(C)]
#[derive(Clone, Copy, Debug, Default)]
pub struct RawKeyboard {
    /// The set 1 scan code, without its prefix — see
    /// [`flags`](Self::flags).
    pub make_code: u16,
    /// `RI_KEY_BREAK` for a release, `RI_KEY_E0`/`RI_KEY_E1` for a prefix.
    pub flags: u16,
    /// Reserved.
    pub reserved: u16,
    /// The virtual key. Not read: the key *message* is what names the symbol.
    pub v_key: u16,
    /// The legacy message this report corresponds to.
    pub message: u32,
    /// Driver-supplied extra information.
    pub extra_information: u32,
}

/// The tail of `RAWINPUT`, narrowed to the two arms this backend registers.
///
/// `RAWHID` is the third arm and variable-length; no HID usage other than the
/// generic mouse and keyboard is registered, so it cannot arrive.
#[repr(C)]
#[derive(Clone, Copy)]
pub union RawInputData {
    /// Valid when the header's `dwType` is `RIM_TYPEMOUSE`.
    pub mouse: RawMouse,
    /// Valid when the header's `dwType` is `RIM_TYPEKEYBOARD`.
    pub keyboard: RawKeyboard,
}

/// `RAWINPUT`.
///
/// The [`header`](Self::header)'s `dwType` is checked before either arm of
/// [`data`](Self::data) is read, which is what makes the union sound rather than
/// hopeful. [`Default`] initializes the larger arm, so every byte of the smaller
/// one is initialized too.
#[repr(C)]
#[derive(Clone, Copy)]
pub struct RawInput {
    /// Type, size and source device.
    pub header: RawInputHeader,
    /// The report, as the header's type says.
    pub data: RawInputData,
}

impl Default for RawInput {
    fn default() -> Self {
        Self {
            header: RawInputHeader::default(),
            data: RawInputData {
                mouse: RawMouse::default(),
            },
        }
    }
}

// ---------------------------------------------------------------------------
// Constants
// ---------------------------------------------------------------------------

/// Window and extended window styles.
pub mod style {
    /// `WS_POPUP` — no frame, no caption. Borderless is this bit and the
    /// absence of the others.
    pub const POPUP: u32 = 0x8000_0000;
    /// `WS_VISIBLE`.
    pub const VISIBLE: u32 = 0x1000_0000;
    /// `WS_CLIPSIBLINGS`.
    pub const CLIP_SIBLINGS: u32 = 0x0400_0000;
    /// `WS_CLIPCHILDREN`.
    pub const CLIP_CHILDREN: u32 = 0x0200_0000;
    /// `WS_CAPTION` — the title bar, and `WS_BORDER | WS_DLGFRAME`.
    pub const CAPTION: u32 = 0x00C0_0000;
    /// `WS_SYSMENU` — the system menu, and therefore the close button.
    pub const SYS_MENU: u32 = 0x0008_0000;
    /// `WS_THICKFRAME` — the resize border.
    pub const THICK_FRAME: u32 = 0x0004_0000;
    /// `WS_MINIMIZEBOX`.
    pub const MINIMIZE_BOX: u32 = 0x0002_0000;
    /// `WS_MAXIMIZEBOX`.
    pub const MAXIMIZE_BOX: u32 = 0x0001_0000;
    /// `WS_OVERLAPPEDWINDOW`.
    pub const OVERLAPPED_WINDOW: u32 =
        CAPTION | SYS_MENU | THICK_FRAME | MINIMIZE_BOX | MAXIMIZE_BOX;

    /// `WS_EX_APPWINDOW` — force a taskbar button.
    pub const EX_APP_WINDOW: u32 = 0x0004_0000;
    /// `WS_EX_WINDOWEDGE`.
    pub const EX_WINDOW_EDGE: u32 = 0x0000_0100;
    /// `WS_EX_TOOLWINDOW` — no taskbar button and no place in Alt-Tab: what
    /// a panel is.
    pub const EX_TOOL_WINDOW: u32 = 0x0000_0080;
    /// `WS_EX_TOPMOST` — above every window without it.
    pub const EX_TOPMOST: u32 = 0x0000_0008;
    /// `WS_EX_NOACTIVATE` — a click does not make the window the foreground
    /// one, so the keyboard stays where it was. Mouse messages still arrive.
    pub const EX_NO_ACTIVATE: u32 = 0x0800_0000;
    /// `WS_EX_NOREDIRECTIONBITMAP` — DWM keeps no redirection surface for the
    /// window, so it shows only what DirectComposition gives it: what a
    /// transparent window is. Fixed at creation; a style rewrite carries it
    /// across rather than trying to change it.
    pub const EX_NO_REDIRECTION_BITMAP: u32 = 0x0020_0000;
    /// `WS_EX_ACCEPTFILES` — **what `DragAcceptFiles` sets**, and therefore
    /// state rather than style.
    ///
    /// Documented as the extended style that call toggles, which is the whole
    /// reason it is named here: a mode change rewrites the extended style word
    /// from [`geometry::styles`](super::super::geometry::styles), and a rewrite
    /// that does not carry this bit across silently stops a window receiving
    /// `WM_DROPFILES`. Exactly the hazard `WS_VISIBLE` has, one word over.
    pub const EX_ACCEPT_FILES: u32 = 0x0000_0010;
}

/// `DwmSetWindowAttribute`'s attributes and values, for the frame a
/// transparent window is given.
pub mod dwm {
    /// `DWMWA_WINDOW_CORNER_PREFERENCE`: whether DWM rounds the window's
    /// corners. Windows 11 and later; earlier versions refuse the attribute and
    /// never round.
    pub const WINDOW_CORNER_PREFERENCE: u32 = 33;
    /// `DWMWCP_DEFAULT`: the system decides.
    pub const CORNER_DEFAULT: u32 = 0;
    /// `DWMWCP_DONOTROUND`: square corners.
    pub const CORNER_DO_NOT_ROUND: u32 = 1;
    /// `DWMWA_BORDER_COLOR`: the colour of the border DWM draws around the
    /// window. Windows 11 and later, like the corner preference.
    pub const BORDER_COLOR: u32 = 34;
    /// `DWMWA_COLOR_DEFAULT`: the system's border.
    pub const COLOR_DEFAULT: u32 = 0xFFFF_FFFF;
    /// `DWMWA_COLOR_NONE`: no border at all.
    pub const COLOR_NONE: u32 = 0xFFFF_FFFE;
}

/// `SHAppBarMessage`'s messages, edges and notifications.
pub mod appbar {
    /// `ABM_NEW`: registers an appbar and its callback message.
    pub const NEW: u32 = 0x0000_0000;
    /// `ABM_REMOVE`: gives the appbar's space back.
    pub const REMOVE: u32 = 0x0000_0001;
    /// `ABM_QUERYPOS`: asks where a proposed rectangle may go, which moves it
    /// clear of the taskbar and every other appbar on that edge.
    pub const QUERY_POS: u32 = 0x0000_0002;
    /// `ABM_SETPOS`: reserves the rectangle.
    pub const SET_POS: u32 = 0x0000_0003;
    /// `ABM_ACTIVATE`: the appbar was activated or deactivated.
    pub const ACTIVATE: u32 = 0x0000_0006;
    /// `ABM_WINDOWPOSCHANGED`: the appbar's window moved.
    pub const WINDOW_POS_CHANGED: u32 = 0x0000_0009;

    /// `ABE_LEFT`.
    pub const EDGE_LEFT: u32 = 0;
    /// `ABE_TOP`.
    pub const EDGE_TOP: u32 = 1;
    /// `ABE_RIGHT`.
    pub const EDGE_RIGHT: u32 = 2;
    /// `ABE_BOTTOM`.
    pub const EDGE_BOTTOM: u32 = 3;

    /// `ABN_POSCHANGED`: the taskbar or another appbar moved, so this one has
    /// to ask for its place again.
    pub const POS_CHANGED: u32 = 0x0000_0001;
    /// `ABN_FULLSCREENAPP`: a full-screen window opened on this appbar's
    /// monitor (`lParam` nonzero) or the last one closed (zero).
    pub const FULL_SCREEN_APP: u32 = 0x0000_0002;
}

/// The messages the window procedure recognizes.
pub mod msg {
    /// `WM_DESTROY`.
    pub const DESTROY: u32 = 0x0002;
    /// `WM_MOVE` — the window moved, so a pointer clip built from its client
    /// rectangle is now in the wrong place.
    pub const MOVE: u32 = 0x0003;
    /// `WM_SIZE`.
    pub const SIZE: u32 = 0x0005;
    /// `WM_ACTIVATE` — a window of this thread was activated or deactivated.
    pub const ACTIVATE: u32 = 0x0006;
    /// `WM_SETFOCUS`.
    pub const SET_FOCUS: u32 = 0x0007;
    /// `WM_KILLFOCUS`.
    pub const KILL_FOCUS: u32 = 0x0008;
    /// `WM_CLOSE`.
    pub const CLOSE: u32 = 0x0010;
    /// `WM_ACTIVATEAPP` — the foreground moved to or from another process.
    pub const ACTIVATE_APP: u32 = 0x001C;
    /// `WM_SETCURSOR` — asked on every pointer movement over the window, and
    /// the **only** place a cursor shape may be set.
    pub const SET_CURSOR: u32 = 0x0020;
    /// `WM_NCHITTEST` — which part of the window a point is over, and whether
    /// the window is there at all for the pointer.
    pub const NC_HIT_TEST: u32 = 0x0084;
    /// `WM_GETMINMAXINFO`.
    pub const GET_MIN_MAX_INFO: u32 = 0x0024;
    /// `WM_GETOBJECT` — an accessibility client asking for the window's
    /// provider. `lParam` names which object; see `access`. Behind the
    /// feature, because without an adapter nothing answers it.
    #[cfg(feature = "accesskit")]
    pub const GET_OBJECT: u32 = 0x003D;
    /// `WM_DISPLAYCHANGE`.
    pub const DISPLAY_CHANGE: u32 = 0x007E;
    /// `WM_GETICON` — which icon a window shows in one of the
    /// [`ICON_BIG`](super::value::ICON_BIG) and
    /// [`ICON_SMALL`](super::value::ICON_SMALL) slots. Test-only: the backend
    /// keeps the icons it sets and never asks.
    #[cfg(test)]
    pub const GET_ICON: u32 = 0x007F;
    /// `WM_SETICON` — gives a window its own icon in one slot, over its
    /// class's. `lParam` is the icon, which stays the sender's to destroy.
    pub const SET_ICON: u32 = 0x0080;
    /// `WM_WINDOWPOSCHANGED` — the window's size, position or place in the
    /// z-order changed. The default handler is what sends `WM_SIZE` and
    /// `WM_MOVE` from it.
    pub const WINDOW_POS_CHANGED: u32 = 0x0047;
    /// `WM_SETTINGCHANGE` — a system parameter changed. With
    /// [`SPI_SET_WORK_AREA`](super::value::SPI_SET_WORK_AREA) it is a monitor's
    /// work area moving: the taskbar, or an appbar coming or going.
    pub const SETTING_CHANGE: u32 = 0x001A;
    /// `WM_APP + 1`: what this backend registers appbars with, so the shell's
    /// `ABN_*` notifications arrive as this message, with the notification in
    /// `wParam`.
    pub const APP_BAR: u32 = 0x8001;
    /// `WM_NCCREATE`.
    pub const NC_CREATE: u32 = 0x0081;
    /// `WM_NCDESTROY`.
    pub const NC_DESTROY: u32 = 0x0082;
    /// `WM_INPUT_DEVICE_CHANGE` — a raw input device arrived or left. `lParam`
    /// is its handle, `wParam` says which.
    pub const INPUT_DEVICE_CHANGE: u32 = 0x00FE;
    /// `WM_INPUT` — a raw input report.
    pub const INPUT: u32 = 0x00FF;
    /// `WM_KEYDOWN`.
    pub const KEY_DOWN: u32 = 0x0100;
    /// `WM_KEYUP`.
    pub const KEY_UP: u32 = 0x0101;
    /// `WM_CHAR` — one UTF-16 code unit of committed text.
    pub const CHAR: u32 = 0x0102;
    /// `WM_SYSKEYDOWN` — a key pressed with Alt held, or F10.
    pub const SYS_KEY_DOWN: u32 = 0x0104;
    /// `WM_SYSKEYUP`.
    pub const SYS_KEY_UP: u32 = 0x0105;
    /// `WM_IME_STARTCOMPOSITION` — an input method began composing.
    pub const IME_START_COMPOSITION: u32 = 0x010D;
    /// `WM_IME_ENDCOMPOSITION` — the composition was committed or abandoned.
    pub const IME_END_COMPOSITION: u32 = 0x010E;
    /// `WM_IME_COMPOSITION` — the composition changed. `lParam` holds the
    /// `GCS_*` flags naming what did.
    pub const IME_COMPOSITION: u32 = 0x010F;
    /// `WM_IME_SETCONTEXT` — the window is gaining or losing the active input
    /// context. `lParam` holds the `ISC_*` flags saying which of the input
    /// method's own windows the default handler should show.
    pub const IME_SET_CONTEXT: u32 = 0x0281;
    /// `WM_SYSCOMMAND` — a window-menu command. `wParam`'s low four bits are
    /// the system's own and are masked off before comparing with an `SC_*`.
    pub const SYS_COMMAND: u32 = 0x0112;
    /// `WM_MOUSEMOVE`.
    pub const MOUSE_MOVE: u32 = 0x0200;
    /// `WM_LBUTTONDOWN`.
    pub const L_BUTTON_DOWN: u32 = 0x0201;
    /// `WM_LBUTTONUP`.
    pub const L_BUTTON_UP: u32 = 0x0202;
    /// `WM_RBUTTONDOWN`.
    pub const R_BUTTON_DOWN: u32 = 0x0204;
    /// `WM_RBUTTONUP`.
    pub const R_BUTTON_UP: u32 = 0x0205;
    /// `WM_MBUTTONDOWN`.
    pub const M_BUTTON_DOWN: u32 = 0x0207;
    /// `WM_MBUTTONUP`.
    pub const M_BUTTON_UP: u32 = 0x0208;
    /// `WM_MOUSEWHEEL`.
    pub const MOUSE_WHEEL: u32 = 0x020A;
    /// `WM_XBUTTONDOWN` — the two thumb buttons, told apart by `wParam`.
    pub const X_BUTTON_DOWN: u32 = 0x020B;
    /// `WM_XBUTTONUP`.
    pub const X_BUTTON_UP: u32 = 0x020C;
    /// `WM_MOUSEHWHEEL` — the tilt wheel.
    pub const MOUSE_H_WHEEL: u32 = 0x020E;
    /// `WM_POINTERUPDATE` — a pointer moved or changed state. `wParam`'s low
    /// word is the pointer id and its high word the `POINTER_MESSAGE_FLAG_*`
    /// bits; `lParam` is the position in **screen** coordinates.
    pub const POINTER_UPDATE: u32 = 0x0245;
    /// `WM_POINTERDOWN` — a pointer made contact.
    pub const POINTER_DOWN: u32 = 0x0246;
    /// `WM_POINTERUP` — a pointer broke contact.
    pub const POINTER_UP: u32 = 0x0247;
    /// `WM_POINTERCAPTURECHANGED` — the window lost the pointer's capture, so
    /// the rest of its gesture will not arrive here.
    pub const POINTER_CAPTURE_CHANGED: u32 = 0x024C;
    /// `WM_SIZING`.
    pub const SIZING: u32 = 0x0214;
    /// `WM_CAPTURECHANGED` — somebody else took the mouse capture, so ours is
    /// gone whether we released it or not.
    pub const CAPTURE_CHANGED: u32 = 0x0215;
    /// `WM_DROPFILES` — files were dropped on a window that asked for them with
    /// `DragAcceptFiles`. `wParam` is an `HDROP`; see [`dnd`](super::super::dnd).
    pub const DROP_FILES: u32 = 0x0233;
    /// `WM_EXITSIZEMOVE` — the modal drag loop finished.
    pub const EXIT_SIZE_MOVE: u32 = 0x0232;
    /// `WM_MOUSELEAVE` — the one-shot `TrackMouseEvent` armed for.
    pub const MOUSE_LEAVE: u32 = 0x02A3;
    /// `WM_DPICHANGED`.
    pub const DPI_CHANGED: u32 = 0x02E0;
}

/// Everything else, by the name it has in the SDK.
pub mod value {
    /// `SIZE_MINIMIZED`, the `wParam` of a `WM_SIZE` that means "iconified".
    pub const SIZE_MINIMIZED: usize = 1;

    /// `GWL_STYLE`.
    pub const GWL_STYLE: i32 = -16;
    /// `GWL_EXSTYLE`.
    pub const GWL_EX_STYLE: i32 = -20;
    /// `GWLP_USERDATA` — where the window procedure finds this shell's shared
    /// state. See the `proc` module.
    pub const GWLP_USERDATA: i32 = -21;

    /// `SW_HIDE`.
    pub const SW_HIDE: i32 = 0;
    /// `SW_SHOWNORMAL`.
    pub const SW_SHOW_NORMAL: i32 = 1;
    /// `SW_SHOWNOACTIVATE` — shown at its last size and position, and not
    /// activated: how a panel that takes no keyboard is shown.
    pub const SW_SHOW_NO_ACTIVATE: i32 = 4;
    /// `SW_MINIMIZE`: `ShowWindow` command that iconifies the window.
    ///
    /// Test-only, like [`PM_NOREMOVE`]: the backend never minimizes a window,
    /// and the clip test restores it again with [`SW_RESTORE`].
    #[cfg(test)]
    pub const SW_MINIMIZE: i32 = 6;
    /// `SW_RESTORE`: `ShowWindow` command that un-iconifies and activates.
    ///
    /// Test-only; see [`SW_MINIMIZE`].
    #[cfg(test)]
    pub const SW_RESTORE: i32 = 9;

    /// `SWP_NOSIZE`.
    pub const SWP_NO_SIZE: u32 = 0x0001;
    /// `SWP_NOMOVE`.
    pub const SWP_NO_MOVE: u32 = 0x0002;
    /// `SWP_NOZORDER`.
    pub const SWP_NO_Z_ORDER: u32 = 0x0004;
    /// `SWP_NOACTIVATE`.
    pub const SWP_NO_ACTIVATE: u32 = 0x0010;
    /// `SWP_FRAMECHANGED` — **required** after a style change, or the system
    /// keeps drawing the old frame until something else forces a recalculation.
    pub const SWP_FRAME_CHANGED: u32 = 0x0020;
    /// `SWP_NOOWNERZORDER`.
    pub const SWP_NO_OWNER_Z_ORDER: u32 = 0x0200;
    /// `HWND_BOTTOM`, as `SetWindowPos`'s insert-after: the bottom of the
    /// z-order.
    pub const HWND_BOTTOM: isize = 1;
    /// `HWND_TOPMOST`, as `SetWindowPos`'s insert-after: the top of the
    /// topmost band, which the window joins.
    pub const HWND_TOPMOST: isize = -1;

    /// `PM_REMOVE`.
    pub const PM_REMOVE: u32 = 0x0001;

    /// `PM_NOREMOVE` — read the message at the head of the queue and leave it
    /// there.
    ///
    /// Test-only, and `#[cfg(test)]` rather than merely unused: the backend
    /// itself always drains with [`PM_REMOVE`], and the one caller is the
    /// diagnostic peek that explains a wait which came back before its timeout.
    /// A `QS_*` word says what *kind* of message is in the queue; this is how a
    /// test gets the id, the window and the parameters of the actual one.
    #[cfg(test)]
    pub const PM_NOREMOVE: u32 = 0x0000;

    /// `MONITORINFOF_PRIMARY`.
    pub const MONITOR_PRIMARY: u32 = 0x0000_0001;
    /// `MONITOR_DEFAULTTONEAREST`.
    pub const MONITOR_DEFAULT_TO_NEAREST: u32 = 0x0000_0002;

    /// `HTTRANSPARENT`, as `WM_NCHITTEST`'s answer: the window is not there
    /// for the pointer, which goes to the window beneath it on this thread.
    pub const HT_TRANSPARENT: isize = -1;

    /// `SPI_SETWORKAREA`, as `WM_SETTINGCHANGE`'s `wParam`.
    pub const SPI_SET_WORK_AREA: usize = 0x002F;

    /// `MDT_EFFECTIVE_DPI` — the scale the *user* chose, which is the one every
    /// other window on the desktop is laid out at.
    pub const MDT_EFFECTIVE_DPI: i32 = 0;

    /// `ENUM_CURRENT_SETTINGS`.
    pub const ENUM_CURRENT_SETTINGS: u32 = 0xFFFF_FFFF;

    /// `QDC_ONLY_ACTIVE_PATHS` — `QueryDisplayConfig` flags: only the paths
    /// currently driving a display.
    pub const QDC_ONLY_ACTIVE_PATHS: u32 = 0x0000_0002;
    /// `DISPLAYCONFIG_DEVICE_INFO_GET_SOURCE_NAME` — the
    /// `DisplayConfigGetDeviceInfo` request that names a path's source.
    pub const DISPLAYCONFIG_DEVICE_INFO_GET_SOURCE_NAME: i32 = 1;
    /// `DISPLAYCONFIG_MODE_INFO_TYPE_TARGET` — a mode array entry describing a
    /// target (a display) rather than a source.
    pub const DISPLAYCONFIG_MODE_INFO_TYPE_TARGET: i32 = 2;
    /// `DISPLAYCONFIG_PATH_TARGET_MODE_IDX_INVALID` — the "no mode" sentinel in
    /// the high 16 bits of `DisplayConfigPathTargetInfo::mode_info_idx`.
    pub const DISPLAYCONFIG_PATH_TARGET_MODE_IDX_INVALID: u32 = 0xffff;
    /// `ERROR_SUCCESS` — the LONG success code every `LONG`-returning call here
    /// reports.
    pub const ERROR_SUCCESS: i32 = 0;

    /// `DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2`, which is a pseudo-handle
    /// rather than an enumerator.
    pub const DPI_PER_MONITOR_AWARE_V2: isize = -4;

    /// `USER_DEFAULT_SCREEN_DPI` — the DPI that is 100%.
    pub const DEFAULT_DPI: u32 = 96;

    /// `CW_USEDEFAULT` — "you choose", for a position with no monitor to
    /// place against.
    ///
    /// The literal is `0x80000000` as a **signed** `int`, which is
    /// `i32::MIN` — not a large positive number, and a window placed at a
    /// large positive number is off the desktop.
    pub const CW_USE_DEFAULT: i32 = i32::MIN;

    /// `IDC_ARROW`, as the integer resource id `MAKEINTRESOURCE` wraps.
    pub const IDC_ARROW: usize = 32_512;
    /// `IDC_IBEAM`.
    pub const IDC_IBEAM: usize = 32_513;
    /// `IDC_WAIT`.
    pub const IDC_WAIT: usize = 32_514;
    /// `IDC_CROSS`.
    pub const IDC_CROSS: usize = 32_515;
    /// `IDC_SIZENWSE`.
    pub const IDC_SIZE_NWSE: usize = 32_642;
    /// `IDC_SIZENESW`.
    pub const IDC_SIZE_NESW: usize = 32_643;
    /// `IDC_SIZEWE`.
    pub const IDC_SIZE_WE: usize = 32_644;
    /// `IDC_SIZENS`.
    pub const IDC_SIZE_NS: usize = 32_645;
    /// `IDC_SIZEALL`.
    pub const IDC_SIZE_ALL: usize = 32_646;
    /// `IDC_NO`.
    pub const IDC_NO: usize = 32_648;
    /// `IDC_HAND`.
    pub const IDC_HAND: usize = 32_649;
    /// `IDC_APPSTARTING`.
    pub const IDC_APP_STARTING: usize = 32_650;

    /// `BLACK_BRUSH`.
    pub const BLACK_BRUSH: i32 = 4;
    /// `RGN_OR` — `CombineRgn` makes the union of its two sources.
    pub const RGN_OR: i32 = 2;
    /// `ERROR` — what `CombineRgn` answers when it could not combine.
    pub const REGION_ERROR: i32 = 0;
    /// `CS_HREDRAW | CS_VREDRAW` — repaint the whole client area on a resize,
    /// so a window being dragged wider does not show stale pixels in the strip
    /// that just appeared.
    pub const CS_REDRAW: u32 = 0x0002 | 0x0001;

    /// `ERROR_ACCESS_DENIED` — what `SetProcessDpiAwarenessContext`
    /// reports when the awareness was already set, by a manifest or by an
    /// earlier call.
    pub const ERROR_ACCESS_DENIED: u32 = 5;
    /// `ERROR_CLASS_ALREADY_EXISTS`.
    pub const ERROR_CLASS_ALREADY_EXISTS: u32 = 1410;

    /// `QS_ALLINPUT` — every kind of message, `QS_SENDMESSAGE` included.
    ///
    /// **Not what the wait asks for**; see [`QS_ALL_EVENTS`]. This is what
    /// `GetQueueStatus` is asked for when a test has to explain a wait that came
    /// back early, because reporting *everything* is what makes the diagnosis
    /// complete — and it is the bit this constant has and the other one does not
    /// that ended a three-round-trip investigation.
    ///
    /// `MWMO_INPUTAVAILABLE` is deliberately **not** declared beside it: the
    /// shell's `wait` drains the queue itself and then sleeps with no flags,
    /// which is the stronger form of what that flag was there for. The CI
    /// evidence that took it out is written up on that function.
    ///
    /// Test-only since the wait moved to [`QS_ALL_EVENTS`], on the same terms as
    /// [`Rect::intersect`](super::Rect::intersect): the backend never asks for
    /// this mask, and only a test has to *explain* a wake.
    #[cfg(test)]
    pub const QS_ALL_INPUT: u32 = 0x04FF;
    /// `QS_ALLEVENTS` — `QS_ALLINPUT` **minus `QS_SENDMESSAGE`**, and what
    /// [`wait`](crate::win32::Win32Shell) actually sleeps on.
    ///
    /// # The one bit that cannot be drained
    ///
    /// A message *sent* to a window of this thread — `SendMessageW` from another
    /// process, and the system does this constantly — sets `QS_SENDMESSAGE`.
    /// `PeekMessageW` **processes** such a message but never *returns* it, so it
    /// can neither report it nor clear its bit: the instrumented CI run that
    /// settled this reported `GetQueueStatus` = `0x400040` with `PeekMessageW`
    /// (`PM_NOREMOVE`) answering `None` in the same breath. MSDN says as much in
    /// its own caveat — the presence of a `QS_` flag does not guarantee that a
    /// subsequent `PeekMessage` will return a message. So a wait that includes
    /// `QS_SENDMESSAGE` returns immediately, every time, and no amount of
    /// draining fixes it because there is nothing retrievable to drain.
    ///
    /// # What it costs, stated rather than glossed
    ///
    /// A sent message that arrives *while* this thread is asleep no longer wakes
    /// it; it waits out the timeout and is dispatched by the next
    /// `drain_messages`. That is the trade this constant makes, and it is the
    /// reason `SendMessageTimeout` exists — a well-behaved broadcaster does not
    /// rely on the recipient being awake.
    pub const QS_ALL_EVENTS: u32 = 0x04BF;
    /// `INFINITE`.
    pub const INFINITE: u32 = 0xFFFF_FFFF;
    /// `WAIT_OBJECT_0` — the first handle was signalled, or, with a handle
    /// count of zero, a message is available. With `n` handles a message is
    /// `WAIT_OBJECT_0 + n`.
    pub const WAIT_OBJECT_0: u32 = 0;
    /// `CREATE_WAITABLE_TIMER_HIGH_RESOLUTION` — a timer that fires to the
    /// hundred-nanosecond due time rather than on the next system clock tick.
    /// Windows 10 1803 and later; refused as an invalid parameter before that.
    pub const CREATE_WAITABLE_TIMER_HIGH_RESOLUTION: u32 = 0x0000_0002;
    /// `TIMER_MODIFY_STATE | SYNCHRONIZE` — enough to set a timer and wait on it.
    pub const TIMER_SET_AND_WAIT: u32 = 0x0000_0002 | 0x0010_0000;
    /// `WAIT_TIMEOUT` — the wait slept for its whole timeout, which is the
    /// outcome [`ShellCaps::EVENT_WAIT`](crate::ShellCaps::EVENT_WAIT) claims is
    /// reachable.
    pub const WAIT_TIMEOUT: u32 = 258;
    /// `WAIT_FAILED`. `GetLastError` says why, and a wait that fails returns
    /// *immediately* — which is indistinguishable from a wait that woke, unless
    /// the return value is read.
    pub const WAIT_FAILED: u32 = 0xFFFF_FFFF;

    /// `ES_SYSTEM_REQUIRED` — the system does not sleep while it is held.
    pub const ES_SYSTEM_REQUIRED: u32 = 0x0000_0001;
    /// `ES_DISPLAY_REQUIRED` — the display stays on, and with it the
    /// screensaver stays off, while it is held.
    pub const ES_DISPLAY_REQUIRED: u32 = 0x0000_0002;
    /// `ES_CONTINUOUS` — the other flags passed with it hold until the next
    /// call, rather than resetting the idle timer once. Passed alone, it ends
    /// whatever the thread held.
    pub const ES_CONTINUOUS: u32 = 0x8000_0000;

    /// `COINIT_APARTMENTTHREADED` — the single-threaded apartment, which is
    /// what `ShellExecuteW`'s documentation asks its caller to be in.
    pub const COINIT_APARTMENT_THREADED: u32 = 0x2;
    /// `COINIT_DISABLE_OLE1DDE` — no OLE 1 DDE window, as the same
    /// documentation asks.
    pub const COINIT_DISABLE_OLE1DDE: u32 = 0x4;
    /// `S_OK` from `CoInitializeEx`: this call made the apartment.
    pub const S_OK: i32 = 0;
    /// `S_FALSE` from `CoInitializeEx`: the thread was already in a
    /// single-threaded apartment. Still owes a `CoUninitialize`.
    pub const S_FALSE: i32 = 1;
    /// `RPC_E_CHANGED_MODE` — the thread is already in the multithreaded
    /// apartment. Nothing was initialized and nothing is owed.
    pub const RPC_E_CHANGED_MODE: i32 = 0x8001_0106_u32.cast_signed();

    /// `HTCLIENT` — the `WM_SETCURSOR` hit-test code for the drawable area.
    ///
    /// Every other value is a piece of the frame the *system* owns a cursor
    /// for: the resize arrows on a border, the arrow over the caption. Setting
    /// ours for those would replace a working resize affordance with an arrow.
    pub const HT_CLIENT: u32 = 1;

    /// `TME_LEAVE`.
    pub const TME_LEAVE: u32 = 0x0000_0002;

    /// `SC_KEYMENU` — the `WM_SYSCOMMAND` that opens the window menu from the
    /// keyboard.
    pub const SC_KEY_MENU: usize = 0xF100;
    /// The bits of a `WM_SYSCOMMAND`'s `wParam` that name the command; the low
    /// four are the system's own.
    pub const SC_COMMAND_MASK: usize = 0xFFF0;

    /// `XBUTTON1` — the `wParam` high word of a `WM_XBUTTON*`, "back".
    pub const XBUTTON1: u32 = 0x0001;
    /// `XBUTTON2` — "forward".
    pub const XBUTTON2: u32 = 0x0002;

    /// `WHEEL_DELTA` — one detent of a notched wheel.
    ///
    /// A high-resolution wheel reports fractions of it, which is why the
    /// division that produces
    /// [`ScrollDelta::Lines`](crcbl_core::input::ScrollDelta::Lines) is done in
    /// floating point rather than as an integer count of detents.
    ///
    /// `i16` because that is the width the message carries it in, and because
    /// it converts to `f32` losslessly — a widening cast on the divisor is the
    /// kind of thing that goes unnoticed until a lint changes.
    pub const WHEEL_DELTA: i16 = 120;

    /// `PT_TOUCH` — the `POINTER_INPUT_TYPE` `GetPointerType` answers for a
    /// finger. Pen, touchpad and mouse pointers have their own values and are
    /// left to the legacy mouse messages `DefWindowProc` synthesizes from them.
    pub const PT_TOUCH: u32 = 2;
    /// `POINTER_MESSAGE_FLAG_INCONTACT`, in the high word of a pointer
    /// message's `wParam`.
    pub const POINTER_MESSAGE_FLAG_IN_CONTACT: u32 = 0x0004;
    /// `POINTER_MESSAGE_FLAG_PRIMARY` — the first contact of the interaction,
    /// the only one the system turns into mouse messages.
    pub const POINTER_MESSAGE_FLAG_PRIMARY: u32 = 0x2000;
    /// `POINTER_MESSAGE_FLAG_CANCELED` — the system took the gesture away, so
    /// this `WM_POINTERUP` is not a completed touch.
    pub const POINTER_MESSAGE_FLAG_CANCELED: u32 = 0x8000;

    /// `HID_USAGE_PAGE_GENERIC`.
    pub const HID_USAGE_PAGE_GENERIC: u16 = 0x01;
    /// `HID_USAGE_GENERIC_MOUSE`.
    pub const HID_USAGE_GENERIC_MOUSE: u16 = 0x02;
    /// `HID_USAGE_GENERIC_KEYBOARD`.
    pub const HID_USAGE_GENERIC_KEYBOARD: u16 = 0x06;
    /// `RIDEV_DEVNOTIFY` — deliver `WM_INPUT_DEVICE_CHANGE` when a device of
    /// this usage arrives or leaves.
    pub const RIDEV_DEV_NOTIFY: u32 = 0x0000_2000;
    /// `RID_INPUT` — ask `GetRawInputData` for the report rather than its
    /// header.
    pub const RID_INPUT: u32 = 0x1000_0003;
    /// `RIDI_DEVICENAME` — ask `GetRawInputDeviceInfoW` for the device's
    /// interface path, which outlives the handle across a replug.
    pub const RIDI_DEVICE_NAME: u32 = 0x2000_0007;
    /// `RIM_TYPEMOUSE`.
    pub const RIM_TYPE_MOUSE: u32 = 0;
    /// `RIM_TYPEKEYBOARD`.
    pub const RIM_TYPE_KEYBOARD: u32 = 1;
    /// `RI_KEY_BREAK` — the report is a release.
    pub const RI_KEY_BREAK: u16 = 0x0001;
    /// `RI_KEY_E0` — the scan code carries the `E0` prefix.
    pub const RI_KEY_E0: u16 = 0x0002;
    /// `RI_KEY_E1` — the scan code carries the `E1` prefix (Pause alone).
    pub const RI_KEY_E1: u16 = 0x0004;
    /// `RI_MOUSE_LEFT_BUTTON_DOWN`; each button's up edge is the next bit.
    pub const RI_MOUSE_LEFT_BUTTON_DOWN: u16 = 0x0001;
    /// `RI_MOUSE_RIGHT_BUTTON_DOWN`.
    pub const RI_MOUSE_RIGHT_BUTTON_DOWN: u16 = 0x0004;
    /// `RI_MOUSE_MIDDLE_BUTTON_DOWN`.
    pub const RI_MOUSE_MIDDLE_BUTTON_DOWN: u16 = 0x0010;
    /// `RI_MOUSE_BUTTON_4_DOWN` — `XBUTTON1`, "back".
    pub const RI_MOUSE_BUTTON_4_DOWN: u16 = 0x0040;
    /// `RI_MOUSE_BUTTON_5_DOWN` — `XBUTTON2`, "forward".
    pub const RI_MOUSE_BUTTON_5_DOWN: u16 = 0x0100;
    /// `RI_MOUSE_WHEEL`.
    pub const RI_MOUSE_WHEEL: u16 = 0x0400;
    /// `RI_MOUSE_HWHEEL`.
    pub const RI_MOUSE_H_WHEEL: u16 = 0x0800;
    /// `GIDC_REMOVAL` — the `wParam` of a `WM_INPUT_DEVICE_CHANGE` for a device
    /// that left.
    pub const GIDC_REMOVAL: usize = 2;

    /// `GCS_COMPSTR` — the composition string changed, or the index that reads
    /// it.
    pub const GCS_COMP_STR: u32 = 0x0008;
    /// `ISC_SHOWUICOMPOSITIONWINDOW` — in `WM_IME_SETCONTEXT`'s `lParam`, asks
    /// the default handler to show the input method's own composition window.
    pub const ISC_SHOW_UI_COMPOSITION_WINDOW: u32 = 0x8000_0000;
    /// `GCS_CURSORPOS` — the index that reads the cursor within it.
    pub const GCS_CURSOR_POS: u32 = 0x0080;
    /// `GCS_RESULTSTR` — the composition produced a result, or the index that
    /// reads it.
    pub const GCS_RESULT_STR: u32 = 0x0800;
    /// `IACE_DEFAULT` — give a window back its default input context.
    pub const IACE_DEFAULT: u32 = 0x0010;
    /// `CFS_DEFAULT` — the input method places its window itself.
    pub const CFS_DEFAULT: u32 = 0x0000;
    /// `CFS_POINT` — the composition window starts at `ptCurrentPos`.
    pub const CFS_POINT: u32 = 0x0002;
    /// `CFS_EXCLUDE` — the candidate list opens at `ptCurrentPos` without
    /// covering `rcArea`.
    pub const CFS_EXCLUDE: u32 = 0x0080;
    /// `MOUSE_MOVE_ABSOLUTE` — the report carries a *position*, not a delta.
    ///
    /// Set by a remote-desktop session, a tablet and some virtual machines. A
    /// backend that assumes relative motion reads a screen coordinate as a
    /// delta, which sends the camera to the far wall on the first event.
    pub const MOUSE_MOVE_ABSOLUTE: u16 = 0x0001;
    /// `MOUSE_VIRTUAL_DESKTOP` — an absolute report normalized over the whole
    /// virtual desktop rather than over the primary monitor.
    pub const MOUSE_VIRTUAL_DESKTOP: u16 = 0x0002;
    /// The range an absolute [`RawMouse`](super::RawMouse) coordinate is
    /// normalized to.
    pub const ABSOLUTE_RANGE: i32 = 65_535;

    /// `SM_CXSCREEN`.
    pub const SM_CX_SCREEN: i32 = 0;
    /// `SM_CYSCREEN`.
    pub const SM_CY_SCREEN: i32 = 1;
    /// `SM_XVIRTUALSCREEN` — the virtual screen's left edge, which is
    /// **negative** whenever a secondary monitor sits to the left of the
    /// primary. A virtual screen assumed to start at the origin is the reason a
    /// multi-monitor rectangle test passes on one desk and fails on another.
    ///
    /// Test-only, with the two extents below it: the backend never needs the
    /// desktop's origin, because `ClipCursor` clamps to it without being asked.
    /// A test that has to predict the clamp does.
    #[cfg(test)]
    pub const SM_X_VIRTUAL_SCREEN: i32 = 76;
    /// `SM_YVIRTUALSCREEN`. See [`SM_X_VIRTUAL_SCREEN`].
    #[cfg(test)]
    pub const SM_Y_VIRTUAL_SCREEN: i32 = 77;
    /// `SM_CXVIRTUALSCREEN`.
    pub const SM_CX_VIRTUAL_SCREEN: i32 = 78;
    /// `SM_CYVIRTUALSCREEN`.
    pub const SM_CY_VIRTUAL_SCREEN: i32 = 79;
    /// `SM_CXICON` — the side of a large icon, at the system DPI, or at the
    /// DPI `GetSystemMetricsForDpi` is given.
    pub const SM_CX_ICON: i32 = 11;
    /// `SM_CXSMICON` — the side of a small icon, as [`SM_CX_ICON`].
    pub const SM_CX_SM_ICON: i32 = 49;
    /// `ICON_BIG`, the `wParam` of `WM_SETICON` for the icon the taskbar and
    /// the task switcher show.
    pub const ICON_BIG: usize = 1;
    /// `ICON_SMALL`, the `wParam` of `WM_SETICON` for the caption's icon.
    pub const ICON_SMALL: usize = 0;

    /// `RT_GROUP_ICON`, the resource type of an icon as a whole: one entry per
    /// icon, naming the images of each size inside it. Passed as an integer
    /// resource id.
    pub const RT_GROUP_ICON: usize = 14;
    /// `IMAGE_ICON`, what `LoadImageW` is asked to load.
    pub const IMAGE_ICON: u32 = 1;
    /// `LOAD_LIBRARY_AS_DATAFILE | LOAD_LIBRARY_AS_IMAGE_RESOURCE`: a module
    /// mapped for its resources alone, with none of its code run.
    #[cfg(test)]
    pub const LOAD_AS_RESOURCES: u32 = 0x0000_0022;

    /// `CF_UNICODETEXT` — UTF-16, NUL-terminated, and the only text format
    /// worth writing.
    ///
    /// The system **synthesizes** `CF_TEXT` and `CF_OEMTEXT` from it on demand
    /// and synthesizes it back from them, which is why this backend has no
    /// equivalent of X11's `TARGETS` negotiation for text: Windows does that
    /// negotiation itself, in the window station, for the one format everybody
    /// agrees on.
    pub const CF_UNICODETEXT: u32 = 13;

    /// `CF_HDROP` — a file list, the block behind an `HDROP`, which is what
    /// Explorer's "copy" puts on the clipboard. Read with `DragQueryFileW`,
    /// exactly as a `WM_DROPFILES` handle is.
    pub const CF_HDROP: u32 = 15;

    /// `GMEM_MOVEABLE` — the allocation flag `SetClipboardData` requires.
    ///
    /// A clipboard payload is handed to the *system*, which may move or discard
    /// it, so it is reached through `GlobalLock` rather than as a pointer.
    pub const GMEM_MOVEABLE: u32 = 0x0002;

    /// The `iFile` that asks `DragQueryFileW` for the file **count** rather
    /// than for a path. `0xFFFFFFFF` in the SDK, where the parameter is a
    /// `UINT`.
    pub const DRAG_QUERY_COUNT: u32 = 0xFFFF_FFFF;

    /// `MAPVK_VK_TO_CHAR` — the unshifted character a virtual key produces in
    /// the current layout, with no dead-key side effect.
    pub const MAPVK_VK_TO_CHAR: u32 = 2;
    /// `MAPVK_VK_TO_VSC_EX` — the scan code a virtual key sits on in the
    /// current layout, with an `E0` or `E1` prefix in the high byte where the
    /// call knows one.
    pub const MAPVK_VK_TO_VSC_EX: u32 = 4;

    /// `VK_SHIFT`-adjacent virtual keys, left and right told apart.
    ///
    /// The AltGr disambiguation in
    /// [`keys::modifiers`](crate::win32::keys::modifiers) depends on seeing
    /// *which* Control is down, so it reads these first and the unsided
    /// [`VK_SHIFT`]/[`VK_CONTROL`]/[`VK_MENU`] only where they add a key.
    pub const VK_L_SHIFT: usize = 0xA0;
    /// See [`VK_L_SHIFT`].
    pub const VK_R_SHIFT: usize = 0xA1;
    /// See [`VK_L_SHIFT`].
    pub const VK_L_CONTROL: usize = 0xA2;
    /// See [`VK_L_SHIFT`].
    pub const VK_R_CONTROL: usize = 0xA3;
    /// See [`VK_L_SHIFT`]. `VK_MENU` is Windows' name for Alt.
    pub const VK_L_MENU: usize = 0xA4;
    /// See [`VK_L_SHIFT`].
    pub const VK_R_MENU: usize = 0xA5;
    /// `VK_SHIFT`: either Shift, which Windows sets with a sided one and
    /// alone for a key injected by this unsided virtual key.
    pub const VK_SHIFT: usize = 0x10;
    /// `VK_CONTROL`. See [`VK_SHIFT`].
    pub const VK_CONTROL: usize = 0x11;
    /// `VK_MENU`: Alt. See [`VK_SHIFT`].
    pub const VK_MENU: usize = 0x12;
    /// `VK_LWIN`.
    pub const VK_L_WIN: usize = 0x5B;
    /// `VK_RWIN`.
    pub const VK_R_WIN: usize = 0x5C;
    /// `VK_CAPITAL` — Caps Lock, read for its *toggle* bit.
    pub const VK_CAPITAL: usize = 0x14;
    /// `VK_NUMLOCK`, likewise.
    pub const VK_NUM_LOCK: usize = 0x90;
    /// `VK_PROCESSKEY` — the virtual key a `WM_KEYDOWN` carries in place of
    /// the real one when an input method consumed the keystroke. A `u16`
    /// because it is compared with a key message's `wParam`, not used as an
    /// index into a keyboard-state snapshot.
    pub const VK_PROCESS_KEY: u16 = 0xE5;

    /// The `WMSZ_*` edge a `WM_SIZING` is being dragged by.
    pub const WMSZ_LEFT: usize = 1;
    /// See [`WMSZ_LEFT`].
    pub const WMSZ_RIGHT: usize = 2;
    /// See [`WMSZ_LEFT`].
    pub const WMSZ_TOP: usize = 3;
    /// See [`WMSZ_LEFT`].
    pub const WMSZ_TOP_LEFT: usize = 4;
    /// See [`WMSZ_LEFT`].
    pub const WMSZ_TOP_RIGHT: usize = 5;
    /// See [`WMSZ_LEFT`].
    pub const WMSZ_BOTTOM: usize = 6;
    /// See [`WMSZ_LEFT`].
    pub const WMSZ_BOTTOM_LEFT: usize = 7;
    /// See [`WMSZ_LEFT`].
    pub const WMSZ_BOTTOM_RIGHT: usize = 8;
}

// ---------------------------------------------------------------------------
// The imports
// ---------------------------------------------------------------------------

// The `user32` surface: window classes, windows, messages, monitors and DPI.
#[cfg(target_os = "windows")]
#[link(name = "user32")]
unsafe extern "system" {
    pub fn RegisterClassExW(class: *const WndClassExW) -> u16;
    pub fn CreateWindowExW(
        ex_style: u32,
        class_name: *const u16,
        window_name: *const u16,
        style: u32,
        x: i32,
        y: i32,
        width: i32,
        height: i32,
        parent: Handle,
        menu: Handle,
        instance: Handle,
        param: *mut c_void,
    ) -> Handle;
    pub fn DestroyWindow(hwnd: Handle) -> Bool32;
    pub fn DefWindowProcW(hwnd: Handle, message: u32, w_param: Wparam, l_param: Lparam) -> Lresult;
    pub fn GetWindowLongPtrW(hwnd: Handle, index: i32) -> isize;
    pub fn SetWindowLongPtrW(hwnd: Handle, index: i32, value: isize) -> isize;
    pub fn ShowWindow(hwnd: Handle, command: i32) -> Bool32;
    pub fn IsWindowVisible(hwnd: Handle) -> Bool32;
    pub fn IsIconic(hwnd: Handle) -> Bool32;
    pub fn SetWindowTextW(hwnd: Handle, text: *const u16) -> Bool32;
    pub fn SetWindowPos(
        hwnd: Handle,
        insert_after: Handle,
        x: i32,
        y: i32,
        width: i32,
        height: i32,
        flags: u32,
    ) -> Bool32;
    pub fn GetWindowPlacement(hwnd: Handle, placement: *mut WindowPlacement) -> Bool32;
    pub fn SetWindowPlacement(hwnd: Handle, placement: *const WindowPlacement) -> Bool32;
    pub fn GetClientRect(hwnd: Handle, rect: *mut Rect) -> Bool32;
    pub fn AdjustWindowRectExForDpi(
        rect: *mut Rect,
        style: u32,
        menu: Bool32,
        ex_style: u32,
        dpi: u32,
    ) -> Bool32;
    pub fn PeekMessageW(
        message: *mut Msg,
        hwnd: Handle,
        filter_min: u32,
        filter_max: u32,
        remove: u32,
    ) -> Bool32;
    /// Turns a virtual-key message into the `WM_CHAR` the layout says it
    /// produces, and posts it back to the front of this thread's queue.
    ///
    /// **The one call in the pump that is not about delivery.** A `WM_KEYDOWN`
    /// says which key went down; the *character* it produces — dead keys
    /// composed, AltGr applied, an IME's committed string — exists only because
    /// this ran. Without it `WM_CHAR` is never generated for a real keystroke
    /// and the whole [`Char`](super::events::RawEvent::Char) path is
    /// unreachable, however well tested it is by hand.
    pub fn TranslateMessage(message: *const Msg) -> Bool32;
    pub fn DispatchMessageW(message: *const Msg) -> Lresult;
    // `WM_SETICON`, which has no function of its own. The tests also send the
    // two synchronous messages this backend answers — `WM_GETMINMAXINFO` and
    // `WM_SIZING` — which are otherwise only sent by a user dragging a window
    // edge, which CI cannot do. Sending them by hand is what makes the
    // constraint path testable at all.
    pub fn SendMessageW(hwnd: Handle, message: u32, w_param: Wparam, l_param: Lparam) -> Lresult;
    // Test-only: a message *posted* rather than sent is the one a wait's own
    // drain dispatches, which is the case `Win32Shell::wait` returns
    // `Wake::Recorded` for.
    #[cfg(test)]
    pub fn PostMessageW(hwnd: Handle, message: u32, w_param: Wparam, l_param: Lparam) -> Bool32;
    pub fn MsgWaitForMultipleObjectsEx(
        count: u32,
        handles: *const Handle,
        milliseconds: u32,
        wake_mask: u32,
        flags: u32,
    ) -> u32;
    // Test-only, like `SendMessageW` above and for a related reason: outside a
    // test nothing knows what the queue *should* hold, so a `QS_*` reading
    // answers no question the backend can act on. Inside one it is how a wait
    // that woke when the queue was known to be empty explains itself. The high
    // word is "there is a message now", the low word "there has been one since
    // you last looked" — the distinction `MWMO_INPUTAVAILABLE` turns on.
    #[cfg(test)]
    pub fn GetQueueStatus(flags: u32) -> u32;
    pub fn MonitorFromWindow(hwnd: Handle, flags: u32) -> Handle;
    pub fn MonitorFromPoint(point: Point, flags: u32) -> Handle;
    // Where the frame is, for building an input region in window coordinates;
    // also how tests read back where a panel landed.
    pub fn GetWindowRect(hwnd: Handle, rect: *mut Rect) -> Bool32;
    pub fn EnumDisplayMonitors(
        hdc: Handle,
        clip: *const Rect,
        callback: MonitorEnumProc,
        data: Lparam,
    ) -> Bool32;
    pub fn GetMonitorInfoW(monitor: Handle, info: *mut MonitorInfoExW) -> Bool32;
    pub fn EnumDisplaySettingsW(device: *const u16, mode: u32, dev_mode: *mut DevModeW) -> Bool32;
    // The exact refresh rate: `QueryDisplayConfig`'s `DISPLAYCONFIG_RATIONAL`
    // carries 60000/1001 where `EnumDisplaySettingsW` reports the integer 60.
    // `GetDisplayConfigBufferSizes` sizes the two arrays the query fills, and
    // `DisplayConfigGetDeviceInfo` names each path's source so a monitor's
    // `\\.\DISPLAYn` can be matched to its mode.
    pub fn GetDisplayConfigBufferSizes(
        flags: u32,
        path_count: *mut u32,
        mode_count: *mut u32,
    ) -> i32;
    pub fn QueryDisplayConfig(
        flags: u32,
        path_count: *mut u32,
        paths: *mut DisplayConfigPathInfo,
        mode_count: *mut u32,
        modes: *mut DisplayConfigModeInfo,
        topology: *mut u32,
    ) -> i32;
    pub fn DisplayConfigGetDeviceInfo(request: *mut DisplayConfigDeviceInfoHeader) -> i32;
    pub fn GetDpiForWindow(hwnd: Handle) -> u32;
    pub fn SetProcessDpiAwarenessContext(context: isize) -> Bool32;
    pub fn LoadCursorW(instance: Handle, name: usize) -> Handle;
    // The time of the message currently being processed, on the same
    // `GetTickCount` clock as `Msg::time`. A window procedure is not handed its
    // message's `MSG`, so this is the only way to stamp an event from inside
    // one — see `TimeBase`.
    pub fn GetMessageTime() -> i32;
    pub fn TrackMouseEvent(track: *mut TrackMouse) -> Bool32;
    pub fn SetCapture(hwnd: Handle) -> Handle;
    pub fn ReleaseCapture() -> Bool32;
    // A null rectangle *releases* the clip, which is the call that must run
    // when a window loses focus. See `input` for why that is not optional.
    pub fn ClipCursor(rect: *const Rect) -> Bool32;
    // Test-only: the clip is otherwise invisible from inside the process that
    // set it, and "the pointer is confined" is a claim about the *system's*
    // state rather than about a field this backend keeps. Reading it back is
    // what makes the confinement tests able to fail.
    #[cfg(test)]
    pub fn GetClipCursor(rect: *mut Rect) -> Bool32;
    // A panel that takes the keyboard asks for the foreground with this. The
    // tests use it too: `ClipCursor` and `SetCursorPos` are restricted to the
    // process that owns the foreground window, and CI has nobody to click on
    // ours. This is the click.
    pub fn SetForegroundWindow(hwnd: Handle) -> Bool32;
    // The other half of that request: `SetForegroundWindow` can be refused,
    // answer success while the foreground lock leaves another process in
    // front, or be honoured and then overtaken, and none of it shows up in
    // anything this backend keeps. A panel asks this afterwards to know whether
    // the foreground is really its own (see `panel::foreground_granted`), and
    // the tests ask it to confirm the foreground they depend on.
    pub fn GetForegroundWindow() -> Handle;
    // The window of this thread holding the keyboard focus, or null. Read once,
    // when a window's accessibility adapter is made: a window shown as it is
    // created takes the focus before the adapter exists to hear it.
    #[cfg(feature = "accesskit")]
    pub fn GetFocus() -> Handle;
    pub fn ClientToScreen(hwnd: Handle, point: *mut Point) -> Bool32;
    pub fn ScreenToClient(hwnd: Handle, point: *mut Point) -> Bool32;
    // The region is in window coordinates, frame included. On success the
    // **system** owns it and frees it when the window goes or a later call
    // replaces it; on failure it stays the caller's. Null removes the region.
    pub fn SetWindowRgn(hwnd: Handle, region: Handle, redraw: Bool32) -> i32;
    // Which kind of device a `WM_POINTER*` message's pointer id belongs to.
    // Answers only while that pointer is live, which is why it is asked inside
    // the window procedure rather than at translation time.
    pub fn GetPointerType(pointer_id: u32, kind: *mut u32) -> Bool32;
    pub fn SetCursorPos(x: i32, y: i32) -> Bool32;
    pub fn GetCursorPos(point: *mut Point) -> Bool32;
    pub fn SetCursor(cursor: Handle) -> Handle;
    // Returns the new display count; the cursor is drawn while it is >= 0,
    // which is why the count has to be balanced rather than merely decremented.
    pub fn ShowCursor(show: Bool32) -> i32;
    pub fn GetKeyboardState(state: *mut u8) -> Bool32;
    pub fn MapVirtualKeyW(code: u32, map_type: u32) -> u32;
    pub fn RegisterRawInputDevices(devices: *const RawInputDevice, count: u32, size: u32)
    -> Bool32;
    pub fn GetRawInputData(
        raw_input: Handle,
        command: u32,
        data: *mut c_void,
        size: *mut u32,
        header_size: u32,
    ) -> u32;
    // With `RIDI_DEVICENAME`, `size` is in **characters**, not bytes, and a
    // null `data` asks for the length the name needs.
    pub fn GetRawInputDeviceInfoW(
        device: Handle,
        command: u32,
        data: *mut c_void,
        size: *mut u32,
    ) -> u32;
    pub fn GetSystemMetrics(index: i32) -> i32;
    // A window's icon sizes at its own DPI; see `window::IconSides`.
    pub fn GetSystemMetricsForDpi(index: i32, dpi: u32) -> i32;
    // The executable's own icon for the window class and each window; see
    // `icon::IconSource`.
    pub fn LoadImageW(
        instance: Handle,
        name: *const u16,
        kind: u32,
        width: i32,
        height: i32,
        flags: u32,
    ) -> Handle;
    pub fn DestroyIcon(icon: Handle) -> Bool32;
    // The clipboard. `OpenClipboard` **fails while another process has it
    // open**, which is routine rather than exceptional, so every one of these
    // is reached through the guard in `win32::clipboard` and never directly.
    // A registered format id is an atom in the window station's table, is the
    // same number for the same name in every process, and is what carries a
    // mime type Windows has no `CF_*` for.
    pub fn RegisterClipboardFormatW(name: *const u16) -> u32;
    pub fn OpenClipboard(hwnd: Handle) -> Bool32;
    pub fn CloseClipboard() -> Bool32;
    pub fn EmptyClipboard() -> Bool32;
    // Ownership of the handle passes to the **system** on success, and stays
    // ours on failure — the asymmetry the guard exists to get right.
    pub fn SetClipboardData(format: u32, mem: Handle) -> Handle;
    // The returned handle belongs to the clipboard: it must not be freed, and
    // it is valid only until `CloseClipboard`.
    pub fn GetClipboardData(format: u32) -> Handle;
    // Test-only: "the clipboard was closed on every path out" is a claim about
    // the *system's* state, not about a field this backend keeps, and this is
    // the only thing that can see it. Null means nobody has it open.
    #[cfg(test)]
    pub fn GetOpenClipboardWindow() -> Handle;
}

// The `shell32` surface: file drops, the appbar a reserving panel is, and
// `ShellExecuteW` for `open_url`.
//
// The fifth system library, on the same terms as `shcore` above — `shell32.dll`
// is present on every Windows this backend can run on, so there is nothing for
// a runtime probe to discover. It is here because `WM_DROPFILES` hands over an
// `HDROP`, which is a shell object rather than a window-manager one: only these
// four calls can read it, and the alternative is parsing the `DROPFILES`
// structure by hand, which means owning the `fWide` ANSI case that shell32
// already owns. See `win32::dnd`.
#[cfg(target_os = "windows")]
#[link(name = "shell32")]
unsafe extern "system" {
    // Sets or clears `WS_EX_ACCEPTFILES`; see `style::EX_ACCEPT_FILES` for why
    // that matters to anything that rewrites the extended style word.
    pub fn DragAcceptFiles(hwnd: Handle, accept: Bool32);
    // Returns a message-specific value; `ABM_NEW` and `ABM_REMOVE` answer
    // `TRUE` on success, and `ABM_QUERYPOS` and `ABM_SETPOS` write `data.rc`.
    pub fn SHAppBarMessage(message: u32, data: *mut AppBarData) -> usize;
    // With `DRAG_QUERY_COUNT` it answers the number of files and writes
    // nothing; with an index and a null buffer it answers the length in
    // characters, excluding the terminator; with an index and a buffer it
    // copies and answers how much it copied.
    pub fn DragQueryFileW(hdrop: Handle, index: u32, buffer: *mut u16, size: u32) -> u32;
    // Where in the window's **client** area the drop happened.
    pub fn DragQueryPoint(hdrop: Handle, point: *mut Point) -> Bool32;
    // Releases the `HDROP`. Not optional: the memory is the shell's and is
    // leaked without it.
    pub fn DragFinish(hdrop: Handle);
    // Answers a pseudo-`HINSTANCE` that is greater than 32 on success and is
    // otherwise the error code. `owner` owns any message box it shows. See
    // `win32::browser`.
    pub fn ShellExecuteW(
        owner: Handle,
        verb: *const u16,
        file: *const u16,
        parameters: *const u16,
        directory: *const u16,
        show: i32,
    ) -> Handle;
}

// The `ole32` surface: entering and leaving a COM apartment around
// `ShellExecuteW`, which may hand the request to a COM handler. On the same
// terms as `shell32`: part of every Windows. See `win32::browser`.
#[cfg(target_os = "windows")]
#[link(name = "ole32")]
unsafe extern "system" {
    // An `HRESULT`: `S_OK` or `S_FALSE` owe a `CoUninitialize` on this
    // thread, `RPC_E_CHANGED_MODE` does not.
    pub fn CoInitializeEx(reserved: *const c_void, flags: u32) -> i32;
    pub fn CoUninitialize();
}

// The `imm32` surface: the input method's composition string, and where its
// windows go. A Text Services Framework IME reaches a window that is not
// TSF-aware through these same calls, so this is the whole surface for both.
#[cfg(target_os = "windows")]
#[link(name = "imm32")]
unsafe extern "system" {
    // Null for a window whose thread has no input context; released with
    // `ImmReleaseContext` by whoever took it.
    pub fn ImmGetContext(hwnd: Handle) -> Handle;
    pub fn ImmReleaseContext(hwnd: Handle, context: Handle) -> Bool32;
    // With a null buffer it answers the size in **bytes**; with a buffer it
    // copies and answers how many bytes it copied. `GCS_CURSORPOS` answers the
    // cursor as a code unit index and copies nothing.
    pub fn ImmGetCompositionStringW(
        context: Handle,
        index: u32,
        buffer: *mut c_void,
        size: u32,
    ) -> i32;
    pub fn ImmSetCompositionWindow(context: Handle, form: *const CompositionForm) -> Bool32;
    pub fn ImmSetCandidateWindow(context: Handle, form: *const CandidateForm) -> Bool32;
    // With a null context and no flags it leaves the window with no input
    // context, which keeps the input method out of it; `IACE_DEFAULT` gives
    // the window back its thread's default context.
    pub fn ImmAssociateContextEx(hwnd: Handle, context: Handle, flags: u32) -> Bool32;
}

// The `dwmapi` surface: one call, for the frame of a transparent window. On
// the same terms as `shcore`: the library is part of every Windows this backend
// runs on. An attribute the running Windows does not know is refused with
// `E_INVALIDARG`, which is a result, not a missing symbol.
#[cfg(target_os = "windows")]
#[link(name = "dwmapi")]
unsafe extern "system" {
    // An `HRESULT`; reads `size` bytes from `value`.
    pub fn DwmSetWindowAttribute(
        hwnd: Handle,
        attribute: u32,
        value: *const c_void,
        size: u32,
    ) -> i32;
}

// The `gdi32` surface: the class background brush, and the regions a window's
// input region is built from.
#[cfg(target_os = "windows")]
#[link(name = "gdi32")]
unsafe extern "system" {
    pub fn GetStockObject(object: i32) -> Handle;
    // Null when the system is out of GDI objects. The far edges are exclusive.
    pub fn CreateRectRgn(left: i32, top: i32, right: i32, bottom: i32) -> Handle;
    // Writes the combination into `destination`, which must already exist,
    // and answers the result's complexity, or `ERROR`.
    pub fn CombineRgn(destination: Handle, first: Handle, second: Handle, mode: i32) -> i32;
    pub fn DeleteObject(object: Handle) -> Bool32;
}

// The `shcore` surface: per-monitor DPI. `GetDpiForMonitor` lives here rather
// than in `user32` because it arrived with Windows 8.1's shell rather than with
// 1607's window manager. It is the per-*monitor* counterpart of
// `GetDpiForWindow`, and it is needed because a `MonitorInfo` has a scale
// factor even when no window of ours is on that monitor.
#[cfg(target_os = "windows")]
#[link(name = "shcore")]
unsafe extern "system" {
    pub fn GetDpiForMonitor(
        monitor: Handle,
        dpi_type: i32,
        dpi_x: *mut u32,
        dpi_y: *mut u32,
    ) -> i32;
}

// The `kernel32` surface.
#[cfg(target_os = "windows")]
#[link(name = "kernel32")]
unsafe extern "system" {
    pub fn GetModuleHandleW(name: *const u16) -> Handle;
    pub fn GetLastError() -> u32;
    // A module's resources, for the icon the window class takes from the
    // executable. The callback runs inside the call, once per name, and
    // returning zero stops the walk.
    pub fn EnumResourceNamesW(
        module: Handle,
        kind: *const u16,
        callback: EnumResNameProc,
        param: Lparam,
    ) -> Bool32;
    #[cfg(test)]
    pub fn LoadLibraryExW(name: *const u16, file: Handle, flags: u32) -> Handle;
    #[cfg(test)]
    pub fn FreeLibrary(module: Handle) -> Bool32;
    // The clipboard's payloads. A `GMEM_MOVEABLE` block has no address until it
    // is locked, and the lock count has to be balanced exactly as
    // `ShowCursor`'s does — an unbalanced one pins a block the system wants to
    // move for as long as the process lives.
    pub fn GlobalAlloc(flags: u32, bytes: usize) -> Handle;
    pub fn GlobalFree(mem: Handle) -> Handle;
    pub fn GlobalLock(mem: Handle) -> *mut c_void;
    pub fn GlobalUnlock(mem: Handle) -> Bool32;
    // May answer **more** than was asked for: the documented contract is that a
    // block is at least the requested size. See `win32::clipboard` for what
    // that means for a payload read back.
    pub fn GlobalSize(mem: Handle) -> usize;
    // Milliseconds since the system started, 64-bit: the clock `MSG::time` is
    // on. See `TimeBase` for why that makes Win32's timestamp rebasing the
    // easiest of the native backends' and still not free.
    pub fn GetTickCount64() -> u64;
    // The high-resolution timer `wait_events` sleeps on, so a short timeout is
    // not rounded up to the next clock tick. `due` is in 100 ns units and
    // negative for "relative to now".
    pub fn CreateWaitableTimerExW(
        attributes: *const c_void,
        name: *const u16,
        flags: u32,
        access: u32,
    ) -> Handle;
    pub fn SetWaitableTimer(
        timer: Handle,
        due: *const i64,
        period: i32,
        completion: *const c_void,
        argument: *const c_void,
        resume: Bool32,
    ) -> Bool32;
    pub fn CloseHandle(handle: Handle) -> Bool32;
    // The doorbell a `ShellWaker` rings from another thread: an auto-reset
    // event in the handle set `wait_events` waits on. See `win32::wake`.
    pub fn CreateEventW(
        attributes: *const c_void,
        manual_reset: Bool32,
        initial_state: Bool32,
        name: *const u16,
    ) -> Handle;
    pub fn SetEvent(event: Handle) -> Bool32;
    // What keeps the display on for `set_idle_inhibit`: the calling thread's
    // execution state, held until it is changed or the thread exits. Answers
    // the state it replaced, or zero for a refusal. See `win32::awake`.
    pub fn SetThreadExecutionState(flags: u32) -> u32;
}

// ---------------------------------------------------------------------------
// Small helpers over the imports
// ---------------------------------------------------------------------------

/// A Rust string as a NUL-terminated UTF-16 buffer, or `None` if it contains an
/// interior NUL.
///
/// Every `*W` entry point takes a NUL-terminated string, so an interior NUL
/// silently truncates rather than failing — a window titled `"save\0nothing"`
/// would appear as `"save"` in the taskbar with no error anywhere. The two
/// Linux backends reject the same input for the same reason, so the seam gives
/// one answer on every platform.
pub fn wide(text: &str) -> Option<Vec<u16>> {
    if text.as_bytes().contains(&0) {
        return None;
    }
    let mut buffer: Vec<u16> = text.encode_utf16().collect();
    buffer.push(0);
    Some(buffer)
}

/// `CLOCK`-equivalent: system uptime in nanoseconds.
///
/// `GetTickCount64` rather than `QueryPerformanceCounter`, and deliberately:
/// [`Msg::time`] is a `GetTickCount` value, so this is the clock the events
/// this backend has to rebase are already on. Reading a *different*, higher
/// resolution clock and subtracting a tick count from it would introduce an
/// error of up to one tick period (about 15.6 ms by default) into every
/// timestamp, in exchange for precision the source data does not have.
#[cfg(target_os = "windows")]
pub fn tick_nanos() -> u64 {
    // SAFETY: `GetTickCount64` takes no arguments, reads no memory and cannot
    // fail; it is available on every Windows this backend supports.
    unsafe { GetTickCount64() }.saturating_mul(1_000_000)
}

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

    /// The width of the field `select` picks out, read from its type alone —
    /// the function is never called.
    fn field_size<T, F>(_select: fn(&T) -> &F) -> usize {
        size_of::<F>()
    }

    /// Asserts a structure's size and every field's offset and width, one
    /// `field: offset, width;` row per field.
    ///
    /// The destructuring pattern names every row's field and has no `..`, so a
    /// field added to the declaration without a row here fails to compile
    /// rather than going unchecked.
    macro_rules! assert_layout {
        ($ty:ident, $size:literal, { $($field:ident: $offset:literal, $width:literal;)+ }) => {{
            let _every_field_has_a_row: fn($ty) = |value| {
                let $ty { $($field: _),+ } = value;
            };
            assert_eq!(size_of::<$ty>(), $size, concat!("size of ", stringify!($ty)));
            $(
                assert_eq!(
                    core::mem::offset_of!($ty, $field),
                    $offset,
                    concat!("offset of ", stringify!($ty), "::", stringify!($field))
                );
                assert_eq!(
                    field_size(|value: &$ty| &value.$field),
                    $width,
                    concat!("width of ", stringify!($ty), "::", stringify!($field))
                );
            )+
        }};
    }

    /// The layouts, field by field, against what `windows.h` produces on x64.
    ///
    /// Every number is the SDK's own `sizeof`/`offsetof` for the matching
    /// field, printed by a C program built with MSVC 19.44 (`_MSC_FULL_VER`
    /// 194435229) against Windows SDK 10.0.26100.0 for x64. They are the x64
    /// Windows ABI, fixed by it rather than by anything in this crate. Where
    /// the Rust declaration flattens a C union into one field, the row is the
    /// union's extent; where it names bytes C leaves anonymous, the row is
    /// that gap.
    ///
    /// Checking every field's offset, not only the size, is what catches two
    /// same-width fields declared in the wrong order: the size is unchanged,
    /// and each would read the other's value.
    ///
    /// A field of the right width and the wrong type — `u32` where the SDK has
    /// `LONG` — passes here. On Windows, `sdk_layout` checks every field's type,
    /// down the arms of each union flattened here, against the `windows`
    /// crate's declarations, which are generated from Windows' own metadata.
    ///
    /// These run on the host as well as on Windows, because every field is a
    /// fixed-width type or a pointer and 64-bit Linux lays them out
    /// identically — which is the point: a padding mistake in [`DevModeW`]
    /// would read the refresh rate from the wrong offset and report a
    /// plausible number, and that is not something a Windows-only test would
    /// have caught any better.
    #[test]
    fn the_structures_match_the_c_layout() {
        assert_layout!(Rect, 16, {
            left: 0, 4;
            top: 4, 4;
            right: 8, 4;
            bottom: 12, 4;
        });
        assert_layout!(Point, 8, {
            x: 0, 4;
            y: 4, 4;
        });
        assert_layout!(Msg, 48, {
            hwnd: 0, 8;
            message: 8, 4;
            w_param: 16, 8;
            l_param: 24, 8;
            time: 32, 4;
            pt: 36, 8;
            // C's tail padding; see the type docs.
            l_private: 44, 4;
        });
        assert_layout!(WndClassExW, 80, {
            cb_size: 0, 4;
            style: 4, 4;
            lpfn_wnd_proc: 8, 8;
            cb_cls_extra: 16, 4;
            cb_wnd_extra: 20, 4;
            h_instance: 24, 8;
            h_icon: 32, 8;
            h_cursor: 40, 8;
            hbr_background: 48, 8;
            lpsz_menu_name: 56, 8;
            lpsz_class_name: 64, 8;
            h_icon_sm: 72, 8;
        });
        assert_layout!(CreateStructW, 80, {
            lp_create_params: 0, 8;
            h_instance: 8, 8;
            h_menu: 16, 8;
            hwnd_parent: 24, 8;
            cy: 32, 4;
            cx: 36, 4;
            y: 40, 4;
            x: 44, 4;
            style: 48, 4;
            lpsz_name: 56, 8;
            lpsz_class: 64, 8;
            dw_ex_style: 72, 4;
        });
        assert_layout!(MinMaxInfo, 40, {
            pt_reserved: 0, 8;
            pt_max_size: 8, 8;
            pt_max_position: 16, 8;
            pt_min_track_size: 24, 8;
            pt_max_track_size: 32, 8;
        });
        assert_layout!(WindowPlacement, 44, {
            length: 0, 4;
            flags: 4, 4;
            show_cmd: 8, 4;
            pt_min_position: 12, 8;
            pt_max_position: 20, 8;
            rc_normal_position: 28, 16;
        });
        assert_layout!(MonitorInfoExW, 104, {
            cb_size: 0, 4;
            rc_monitor: 4, 16;
            rc_work: 20, 16;
            dw_flags: 36, 4;
            sz_device: 40, 64;
        });
        // The one with two unions in it, and the one whose fields are read
        // past the padding.
        assert_layout!(DevModeW, 220, {
            dm_device_name: 0, 64;
            dm_spec_version: 64, 2;
            dm_driver_version: 66, 2;
            dm_size: 68, 2;
            dm_driver_extra: 70, 2;
            dm_fields: 72, 4;
            // The printer/display union's display arm. The probe printed the
            // union's extent, 76 for 16 bytes; these rows split it at the
            // arm's members, which `sdk_layout` checks against the SDK.
            dm_position: 76, 8;
            dm_display_orientation: 84, 4;
            dm_display_fixed_output: 88, 4;
            dm_color: 92, 2;
            dm_duplex: 94, 2;
            dm_y_resolution: 96, 2;
            dm_tt_option: 98, 2;
            dm_collate: 100, 2;
            dm_form_name: 102, 64;
            dm_log_pixels: 166, 2;
            dm_bits_per_pel: 168, 4;
            dm_pels_width: 172, 4;
            dm_pels_height: 176, 4;
            // `dmDisplayFlags` / `dmNup`.
            dm_display_flags: 180, 4;
            dm_display_frequency: 184, 4;
            dm_icm_method: 188, 4;
            dm_icm_intent: 192, 4;
            dm_media_type: 196, 4;
            dm_dither_type: 200, 4;
            dm_reserved1: 204, 4;
            dm_reserved2: 208, 4;
            dm_panning_width: 212, 4;
            dm_panning_height: 216, 4;
        });

        // The `QueryDisplayConfig` structures, read for the exact refresh
        // rate. A wrong one reads a plausible wrong rate: an offset mistake in
        // `DisplayConfigVideoSignalInfo` would report 59.94 Hz as something
        // only a CRT ran at, and the whole point of asking `QueryDisplayConfig`
        // is that `EnumDisplaySettingsW` already rounds.
        assert_layout!(Luid, 8, {
            low_part: 0, 4;
            high_part: 4, 4;
        });
        assert_layout!(DisplayConfig2dRegion, 8, {
            cx: 0, 4;
            cy: 4, 4;
        });
        assert_layout!(DisplayConfigRational, 8, {
            numerator: 0, 4;
            denominator: 4, 4;
        });
        assert_layout!(DisplayConfigVideoSignalInfo, 48, {
            pixel_rate: 0, 8;
            h_sync_freq: 8, 8;
            v_sync_freq: 16, 8;
            active_size: 24, 8;
            total_size: 32, 8;
            // `AdditionalSignalInfo` / `videoStandard`.
            additional_signal_info: 40, 4;
            scan_line_ordering: 44, 4;
        });
        assert_layout!(DisplayConfigTargetMode, 48, {
            target_video_signal_info: 0, 48;
        });
        assert_layout!(DisplayConfigModeInfo, 64, {
            info_type: 0, 4;
            id: 4, 4;
            adapter_id: 8, 8;
            // The union's `targetMode`, its largest arm: `sourceMode` and
            // `desktopImageInfo` are smaller and start at the same offset.
            target_mode: 16, 48;
        });
        assert_layout!(DisplayConfigPathSourceInfo, 20, {
            adapter_id: 0, 8;
            id: 8, 4;
            mode_info_idx: 12, 4;
            status_flags: 16, 4;
        });
        assert_layout!(DisplayConfigPathTargetInfo, 48, {
            adapter_id: 0, 8;
            id: 8, 4;
            mode_info_idx: 12, 4;
            output_technology: 16, 4;
            rotation: 20, 4;
            scaling: 24, 4;
            refresh_rate: 28, 8;
            scan_line_ordering: 36, 4;
            target_available: 40, 4;
            status_flags: 44, 4;
        });
        assert_layout!(DisplayConfigPathInfo, 72, {
            source_info: 0, 20;
            target_info: 20, 48;
            flags: 68, 4;
        });
        assert_layout!(DisplayConfigDeviceInfoHeader, 20, {
            kind: 0, 4;
            size: 4, 4;
            adapter_id: 8, 8;
            id: 16, 4;
        });
        assert_layout!(DisplayConfigSourceDeviceName, 84, {
            header: 0, 20;
            view_gdi_device_name: 20, 64;
        });

        // The input structures. `RAWMOUSE` is the one that matters: its
        // `usFlags` is followed by two bytes of union alignment, and reading
        // `lLastX` from offset 6 instead of 12 would produce a delta made of
        // half a button mask — a plausible number, never a crash.
        assert_layout!(TrackMouse, 24, {
            cb_size: 0, 4;
            dw_flags: 4, 4;
            hwnd_track: 8, 8;
            dw_hover_time: 16, 4;
        });
        assert_layout!(RawInputDevice, 16, {
            us_usage_page: 0, 2;
            us_usage: 2, 2;
            dw_flags: 4, 4;
            hwnd_target: 8, 8;
        });
        assert_layout!(RawInputHeader, 24, {
            dw_type: 0, 4;
            dw_size: 4, 4;
            h_device: 8, 8;
            w_param: 16, 8;
        });
        assert_layout!(RawMouse, 24, {
            us_flags: 0, 2;
            // The gap before the union, which C leaves unnamed.
            padding: 2, 2;
            // `ulButtons` / `usButtonFlags` + `usButtonData`.
            ul_buttons: 4, 4;
            ul_raw_buttons: 8, 4;
            l_last_x: 12, 4;
            l_last_y: 16, 4;
            ul_extra_information: 20, 4;
        });
        assert_layout!(RawKeyboard, 16, {
            make_code: 0, 2;
            flags: 2, 2;
            reserved: 4, 2;
            v_key: 6, 2;
            message: 8, 4;
            extra_information: 12, 4;
        });
        assert_layout!(RawInput, 48, {
            header: 0, 24;
            data: 24, 24;
        });
        // The union has no row table, since a union pattern names one field;
        // each arm's width is its own structure's, asserted above. `RAWHID`,
        // the arm left out, is smaller than both.
        assert_eq!(size_of::<RawInputData>(), 24);
        assert_eq!(core::mem::offset_of!(RawInput, data.mouse), 24);
        assert_eq!(core::mem::offset_of!(RawInput, data.keyboard), 24);
        assert!(size_of::<RawKeyboard>() <= size_of::<RawMouse>());

        // The input method's placement forms. These rows were printed by the
        // same kind of program against mingw-w64's `imm.h`, built by GCC 16.2
        // for x64, rather than against the Windows SDK: the x64 ABI is the
        // same either way.
        assert_layout!(CompositionForm, 28, {
            dw_style: 0, 4;
            pt_current_pos: 4, 8;
            rc_area: 12, 16;
        });
        assert_layout!(CandidateForm, 32, {
            dw_index: 0, 4;
            dw_style: 4, 4;
            pt_current_pos: 8, 8;
            rc_area: 16, 16;
        });

        // The one a *test* writes rather than reads. A wrong length here puts
        // the file list where `DragQueryFileW` does not look, and the drop test
        // would then report zero files as though the backend had lost them.
        assert_layout!(DropFiles, 20, {
            p_files: 0, 4;
            pt: 4, 8;
            f_nc: 12, 4;
            f_wide: 16, 4;
        });
    }

    #[test]
    fn the_defaults_carry_the_sizes_the_system_validates() {
        // Three structures are self-describing, and a wrong `cbSize` is
        // rejected rather than tolerated — `GetMonitorInfoW` with the plain
        // `MONITORINFO` size silently does not fill in the device name.
        assert_eq!(
            u32::from(DevModeW::default().dm_size),
            size_of::<DevModeW>() as u32
        );
        assert_eq!(
            MonitorInfoExW::default().cb_size,
            size_of::<MonitorInfoExW>() as u32
        );
    }

    #[test]
    fn a_rectangle_is_two_corners_and_never_has_a_negative_size() {
        let rect = Rect {
            left: 100,
            top: 50,
            right: 1380,
            bottom: 770,
        };
        assert_eq!(rect.width(), 1280);
        assert_eq!(rect.height(), 720);
        // Degenerate rather than negative: a window rectangle that has been
        // dragged inside out is zero-sized, and a negative width propagated
        // into a `u32` size would be four billion pixels.
        let inverted = Rect {
            left: 10,
            top: 10,
            right: 0,
            bottom: 0,
        };
        assert_eq!(inverted.width(), 0);
        assert_eq!(inverted.height(), 0);
    }

    #[test]
    fn an_intersection_is_the_overlap_and_is_degenerate_when_there_is_none() {
        // What `ClipCursor` does to a rectangle before applying it, and the
        // reason this exists: the Windows runner's display is 1024×768, which
        // is *smaller* than the default window, so the clip comes back clamped
        // and a test that asserted the client rectangle failed on real, correct
        // behaviour.
        let client = Rect {
            left: 8,
            top: 31,
            right: 1036,
            bottom: 751,
        };
        let screen = Rect {
            left: 0,
            top: 0,
            right: 1024,
            bottom: 768,
        };
        assert_eq!(
            client.intersect(screen),
            Rect {
                left: 8,
                top: 31,
                right: 1024,
                bottom: 751
            },
            "only the edge that overhangs moves"
        );
        assert_eq!(
            client.intersect(client),
            client,
            "a window that fits is not clamped at all"
        );

        // A virtual screen whose origin is negative — a second monitor to the
        // left of the primary — must not be treated as starting at zero.
        let left_monitor = Rect {
            left: -1920,
            top: 0,
            right: -900,
            bottom: 1080,
        };
        let virtual_screen = Rect {
            left: -1920,
            top: 0,
            right: 1920,
            bottom: 1080,
        };
        assert_eq!(left_monitor.intersect(virtual_screen), left_monitor);

        // Disjoint rectangles produce a degenerate one rather than a negative
        // width, which `width`/`height` already clamp.
        let elsewhere = Rect {
            left: 4_000,
            top: 4_000,
            right: 5_000,
            bottom: 5_000,
        };
        let empty = client.intersect(elsewhere);
        assert_eq!((empty.width(), empty.height()), (0, 0));
    }

    #[test]
    fn a_string_with_an_interior_nul_has_no_utf16_form() {
        assert_eq!(
            wide("crcbl"),
            Some(vec![0x0063, 0x0072, 0x0063, 0x0062, 0x006C, 0])
        );
        assert_eq!(wide(""), Some(vec![0]));
        // Non-BMP characters become surrogate pairs, which is what UTF-16 is.
        assert_eq!(wide("🎮").map(|text| text.len()), Some(3));
        assert_eq!(wide("save\0nothing"), None);
    }

    #[test]
    fn the_overlapped_window_style_is_the_sum_of_its_parts() {
        // The literal in `winuser.h` is 0x00CF0000, and spelling it as a union
        // of named bits is only correct if it comes to the same number.
        assert_eq!(style::OVERLAPPED_WINDOW, 0x00CF_0000);
        assert_eq!(style::CAPTION, 0x00C0_0000);
        assert_eq!(value::CS_REDRAW, 0x0003);
    }

    #[test]
    fn the_transparency_values_are_the_sdks() {
        // `winuser.h` and `dwmapi.h`. A wrong one is an extended style or an
        // attribute the system ignores, and no call fails to say so.
        assert_eq!(style::EX_NO_REDIRECTION_BITMAP, 0x0020_0000);
        assert_eq!(dwm::WINDOW_CORNER_PREFERENCE, 33);
        assert_eq!(dwm::CORNER_DEFAULT, 0);
        assert_eq!(dwm::CORNER_DO_NOT_ROUND, 1);
        assert_eq!(dwm::BORDER_COLOR, 34);
        assert_eq!(dwm::COLOR_DEFAULT, 0xFFFF_FFFF);
        assert_eq!(dwm::COLOR_NONE, 0xFFFF_FFFE);
        // `wingdi.h`; a wrong mode intersects or subtracts instead.
        assert_eq!(value::RGN_OR, 2);
        assert_eq!(value::REGION_ERROR, 0);
    }

    /// The conversion from `QueryDisplayConfig`'s rational to millihertz, and
    /// the target-mode index extraction. These are the two pure pieces of the
    /// exact-refresh path; `win32::monitors` (Windows-only) only wires them.
    #[test]
    fn a_rational_and_a_mode_index_convert_exactly() {
        // 59.94 Hz — the mode `EnumDisplaySettingsW` reports as the integer 60.
        let ntsc = DisplayConfigRational {
            numerator: 60_000,
            denominator: 1_001,
        };
        assert_eq!(ntsc.millihertz(0), Some(59_940));
        // 60.00 Hz stays exact.
        let sixty = DisplayConfigRational {
            numerator: 60_000,
            denominator: 1_000,
        };
        assert_eq!(sixty.millihertz(0), Some(60_000));
        // A divider halves the rate (interlaced modes), per the structure's
        // `vSyncFreqDivider` contract.
        assert_eq!(sixty.millihertz(2), Some(30_000));
        // Degenerate rationals are "no rate", not zero hertz.
        assert_eq!(DisplayConfigRational::default().millihertz(0), None);
        assert_eq!(
            DisplayConfigRational {
                numerator: 1,
                denominator: 0
            }
            .millihertz(0),
            None
        );

        // The target-mode index is the high 16 bits; 0xffff there is "no mode".
        let with_mode = DisplayConfigPathTargetInfo {
            mode_info_idx: 0x0003_0005, // target mode 3, desktop mode 5
            ..Default::default()
        };
        assert_eq!(with_mode.target_mode_index(), Some(3));
        let without = DisplayConfigPathTargetInfo {
            mode_info_idx: 0xFFFF_0000, // target half is the invalid sentinel
            ..Default::default()
        };
        assert_eq!(without.target_mode_index(), None);
    }
}

#[cfg(all(test, target_os = "windows"))]
mod sdk_layout;