teksilo-platform 0.24.0

Platform integration for Teksilo — winit and AccessKit adapters, clipboard, OS theme, native file dialogs, drag-and-drop and menus.
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
// SPDX-License-Identifier: MPL-2.0
// SPDX-FileCopyrightText: 2026 FernTech

//! Windows: completing a composition, answering the input method's requests
//! about the document, the input scope, and a subclass tap that traces.
//!
//! Every attached window's HWND is kept, so that [`finish_composition`] can
//! have the input method complete the window's IME composition when the
//! focused field ends it, and tell the field what it committed; see that
//! function for what winit does around it.
//!
//! winit 0.30 reads the text input system through IMM32 alone: a commit is
//! the `GCS_RESULTSTR` of a `WM_IME_COMPOSITION`, and everything else is a
//! key press. Measured on Windows 11, voice typing (Win+H) and the emoji
//! panel (Win+.) both deliver their text to such a window as IMM results,
//! which CUAS bridges from TSF, and neither the messages nor TSF's
//! compartments tell them apart from each other or from an input method's
//! commit. Telling voice typing apart needs a TSF text store of our own
//! (`engineering/docs/tsf-text-store.md`).
//!
//! The tap is a `SetWindowSubclass` on winit's HWND, installed on every
//! attached window, so it sees every message winit sees, just before winit
//! does. It is a tap, not a filter: every message is passed on with
//! `DefSubclassProc`, unconditionally, so what winit receives is unchanged,
//! with one documented exception, the input method's requests below. It
//! follows the two rules `pen/windows.rs` sets for sharing an HWND with the
//! title bar's, the pen's and AccessKit's subclasses: a subclass id from a
//! private range, and always chaining.
//!
//! # The input method's requests
//!
//! An input method asks the window about its document with `WM_IME_REQUEST`,
//! and winit has no arm for it: every request reached `DefWindowProc` and was
//! answered "nothing". The tap answers four of them from the focused text
//! widget's [`TextInputDocument`] (`imm_requests` holds the half that needs
//! no platform) and returns that answer instead of passing the message on:
//!
//! - `IMR_QUERYCHARPOSITION`, where a character of the composition is drawn,
//!   converted to the screen with the window's DPI and `ClientToScreen`, so
//!   the candidate window follows the character being converted;
//! - `IMR_DOCUMENTFEED`, the text around the composition.
//!
//! Reconversion (`IMR_RECONVERTSTRING`, `IMR_CONFIRMRECONVERTSTRING`) is not
//! answered: measured on Windows 11 with the Microsoft Japanese IME, it
//! opened 6 times of 6 in one session and 0 of 24 in later ones (with the
//! text around the selection or the selection alone), while a Win32 edit
//! control reconverted at the same moments, and a reconversion that does not
//! open stays pending in the input method. See the design document.
//!
//! The tap runs before winit has the message, so it calls nothing that can
//! deliver a message (see below), and runs no application code: it asks the
//! document whether it can answer without a change
//! ([`is_available`](TextInputDocument::is_available)) before reading it,
//! and a document that cannot (the widget is in the middle of its own work,
//! or holds typing not yet inserted, which a read would insert, firing the
//! application's change callbacks) is not read. Its request goes on to
//! winit, which answers "nothing" as it always did, and so does every other
//! request. Most requests arrive while winit handles another message (round
//! 5), which is when a widget is likely to be busy.
//!
//! # No input scope
//!
//! A password field takes no input method on Windows because winit takes
//! the window's input context away while it has the focus. The window keeps
//! the `IS_DEFAULT` input scope: measured, `IS_PASSWORD` set on the window
//! (`SetInputScope`) closes the Microsoft Japanese and Korean input methods
//! for the whole window once the field is left, and opening the IMM context
//! again does not bring them back. The password scope belongs to the TSF
//! store's disabled context.
//!
//! # Tracing
//!
//! When `TEKSILO_TEXT_INPUT_TRACE` is set, the tap also logs to stderr the
//! keyboard, character and IME messages the window receives, each with where `GetCurrentInputMessageSource` says it came from and its
//! `GetMessageExtraInfo`. After winit has handled the start of a composition,
//! a composition message or the end of one, it also logs:
//!
//! - the IMM composition and result strings (not at the start);
//! - who owns the compositions in TSF's focused context;
//! - the active keyboard TIP.
//!
//! Once, when it attaches, it logs the same TSF state as a baseline, and with
//! it TSF's speech, handwriting and keyboard compartments, read at each of the
//! four levels they can be set at (global, thread, the focused document, its
//! top context) along with any other compartment listed there, and the
//! foreground window's class and the image of the process that owns it.
//!
//! Run it from PowerShell:
//!
//! ```text
//! $env:TEKSILO_TEXT_INPUT_TRACE=1; cargo run -p rich-text-editor
//! ```
//!
//! then type, compose with an IME, dictate with Win+H and pick from Win+. in
//! the editor. A line reads:
//!
//! ```text
//! [text-input] #57 Window(1) WM_KEYDOWN vk=0xe7 VK_PACKET scan=0x00 ext=0 alt=0 prev=0 up=0 rep=1 src=keyboard/injected extra=0x0
//! [text-input] #58 Window(1) WM_CHAR unit=0xd83d high-surrogate scan=0x00 ext=0 alt=0 prev=0 up=0 rep=1 src=keyboard/injected extra=0x0
//! [text-input] #61 Window(1) WM_IME_COMPOSITION last=0x006f 'o' flags=0x1bf [GCS_COMPREADSTR|...] src=unavailable/unavailable extra=0x0
//! [text-input] #61   imm: comp="hello" [0068 0065 006c 006c 006f] result=<none> cursor=5 delta=0
//! [text-input] #61   tsf: apartment=main STA, thread focus=true, top context dynamic=0x0 static=0x4 [TRANSITORY]
//! [text-input] #61   tsf: composition 0 owner={...}
//! [text-input] #61   tsf: active keyboard profile: TIP langid=0x0409 clsid={...} profile={...} hkl=0x0 flags=0x3 [ACTIVE|ENABLED]
//! ```
//!
//! and the attach baseline adds:
//!
//! ```text
//! [text-input] #3   tsf: global compartments (9 listed): SPEECH_OPENCLOSE=I4 0, SPEECH_DISABLED=empty (unlisted), ...
//! [text-input] #3   tsf: global compartments, others: SPEECH_UI_STATUS=I4 0, {...}=UNKNOWN non-null
//! [text-input] #3   fg: hwnd=0x40a1c class="CASCADIA_HOSTING_WINDOW_CLASS" pid=7312 tid=7316 this window=false this process=false image="C:\\...\\WindowsTerminal.exe"
//! ```
//!
//! The number is one sequence across every window, so the lines a probe adds
//! carry the number of the message they belong to. Lines a message prints
//! while winit is handling an earlier one come between that message's line
//! and its probe lines.
//!
//! # What it has measured
//!
//! Voice typing and the emoji panel arrive identically: one
//! `WM_IME_COMPOSITION` carrying `GCS_RESULTSTR` alone, with no composition
//! before it and none in TSF's top context, whatever profile is active. A
//! keyboard IME's commit differs: a composition comes first, the commit's
//! flags are `0x1e00`, and TSF names the composition's owner. Reading the
//! compartments and the foreground window at every composition told the
//! first two apart no better, which is why they are now read only once.
//!
//! # The probes change nothing they measure
//!
//! **Nothing that can deliver a message runs before winit has the current
//! one.** A TSF call can be a cross-process COM call, and one made from an STA
//! waits in a modal loop that delivers the messages other threads send to the
//! window meanwhile. That reordered input: a Korean IME commits a syllable and
//! at once starts the next one, and with compartments read at the commit, the
//! next syllable's `WM_IME_STARTCOMPOSITION` and `WM_IME_COMPOSITION` reached
//! winit before the commit did, which lost the committed syllable and its
//! preedit. So before `DefSubclassProc` the tap only reads what describes the
//! message being dispatched (its input source and extra info, which a later
//! call would no longer report) and writes the log line; besides tracing, it
//! answers a request from the document and forgets a reconversion, which
//! read the widget's state and write the tap's own. The IMM and TSF
//! probes run after `DefSubclassProc` returns: winit has handled the message
//! by then, and its own read does not consume the strings, so the IMM probe
//! reads what winit read unless something winit's handling caused changed
//! them, in which case the change is in the log between the two. Those probes
//! touch no per-window state, since winit's handling may have closed the
//! window and freed it.
//!
//! The tap never initialises COM: winit's `OleInitialize` has already made the
//! UI thread an STA, and initialising it again with another model could only
//! fail or, on a thread that had none, fix its apartment. When COM is not
//! initialised the TSF probe says so and stops. Nor does it create a thread
//! manager: `CoCreateInstance(CLSID_TF_ThreadMgr)` returns the thread's one
//! when it exists but creates one when it does not, so the probe asks msctf for
//! the existing one with `TF_GetThreadMgr`. A message the window receives
//! while a probe runs is logged, marked, and probes nothing, so a probe never
//! recurses. Nor is one probed that winit's handling of another message sent
//! (it is marked too): probing there would deliver messages while winit is
//! still in the middle of that other one. For the same reason the attach
//! baseline is skipped when the window is created while winit is handling a
//! message of another tapped window.
//!
//! Compartments are read, never written. Reading one goes through
//! `GetCompartment`, which may create this process's handle on a compartment
//! it has not touched yet; that writes no value and notifies no sink. So that
//! the baseline shows what existed before the tap looked, each level's
//! compartments are listed (`EnumCompartments`) before any is read, and a
//! watched compartment that was not listed is marked `(unlisted)`.

use std::cell::{Cell, RefCell};
use std::collections::HashMap;
use std::ffi::c_void;
use std::panic::{AssertUnwindSafe, catch_unwind};
use std::rc::Rc;
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};

use raw_window_handle::RawWindowHandle;
use teksilo_core::AppEventPoster;
use teksilo_core::raw_handle::ParentHandle;
use teksilo_core::text_input_document::TextInputDocument;
use teksilo_core::text_surface::TextSurfaces;
use teksilo_core::window::TeksiloWindowId;

mod tsf;

use super::imm_completion::{self, ImmCompletion, ImmMessage};
use super::imm_requests::{self, ReconvertString};
use super::{FinishedComposition, StoreFocus, TextStoreMode, text_store_mode};

use windows::Win32::Foundation::{
    CO_E_NOTINITIALIZED, CloseHandle, HWND, LPARAM, LRESULT, POINT, RECT, S_OK, WPARAM,
};
use windows::Win32::Graphics::Gdi::ClientToScreen;
use windows::Win32::System::Com::{
    APTTYPE, APTTYPE_MAINSTA, APTTYPE_MTA, APTTYPE_NA, APTTYPE_STA, APTTYPEQUALIFIER,
    CLSCTX_INPROC_SERVER, CoCreateInstance, CoGetApartmentType,
};
use windows::Win32::System::LibraryLoader::{GetModuleHandleW, GetProcAddress};
use windows::Win32::System::Threading::{
    GetCurrentProcessId, OpenProcess, PROCESS_NAME_WIN32, PROCESS_QUERY_LIMITED_INFORMATION,
    QueryFullProcessImageNameW,
};
use windows::Win32::System::Variant::{
    VARIANT, VT_BOOL, VT_BSTR, VT_EMPTY, VT_I2, VT_I4, VT_INT, VT_UI4, VT_UINT, VT_UNKNOWN,
    VariantClear,
};
use windows::Win32::UI::HiDpi::GetDpiForWindow;
use windows::Win32::UI::Input::Ime::{
    CPS_CANCEL, CPS_COMPLETE, CS_INSERTCHAR, CS_NOMOVECARET, GCS_COMPATTR, GCS_COMPCLAUSE,
    GCS_COMPREADATTR, GCS_COMPREADCLAUSE, GCS_COMPREADSTR, GCS_COMPSTR, GCS_CURSORPOS,
    GCS_DELTASTART, GCS_RESULTCLAUSE, GCS_RESULTREADCLAUSE, GCS_RESULTREADSTR, GCS_RESULTSTR, HIMC,
    IME_COMPOSITION_STRING, IME_CONVERSION_MODE, IME_SENTENCE_MODE, IMECHARPOSITION,
    IMN_CHANGECANDIDATE, IMN_CLOSECANDIDATE, IMN_CLOSESTATUSWINDOW, IMN_GUIDELINE,
    IMN_OPENCANDIDATE, IMN_OPENSTATUSWINDOW, IMN_PRIVATE, IMN_SETCANDIDATEPOS,
    IMN_SETCOMPOSITIONFONT, IMN_SETCOMPOSITIONWINDOW, IMN_SETCONVERSIONMODE, IMN_SETOPENSTATUS,
    IMN_SETSENTENCEMODE, IMN_SETSTATUSWINDOWPOS, IMN_SOFTKBDDESTROYED, IMR_CANDIDATEWINDOW,
    IMR_COMPOSITIONFONT, IMR_COMPOSITIONWINDOW, IMR_CONFIRMRECONVERTSTRING, IMR_DOCUMENTFEED,
    IMR_QUERYCHARPOSITION, IMR_RECONVERTSTRING, ImmGetCompositionStringW, ImmGetContext,
    ImmGetConversionStatus, ImmGetOpenStatus, ImmNotifyIME, ImmReleaseContext, NI_COMPOSITIONSTR,
    RECONVERTSTRING,
};
use windows::Win32::UI::Input::KeyboardAndMouse::{GetKeyboardLayout, VK_PACKET, VK_PROCESSKEY};
use windows::Win32::UI::Input::{
    GetCurrentInputMessageSource, IMDT_KEYBOARD, IMDT_MOUSE, IMDT_PEN, IMDT_TOUCH, IMDT_TOUCHPAD,
    IMDT_UNAVAILABLE, IMO_HARDWARE, IMO_INJECTED, IMO_SYSTEM, IMO_UNAVAILABLE,
    INPUT_MESSAGE_SOURCE,
};
use windows::Win32::UI::Shell::{DefSubclassProc, RemoveWindowSubclass, SetWindowSubclass};
use windows::Win32::UI::TextServices::{
    CLSID_TF_InputProcessorProfiles, GUID_COMPARTMENT_CONVERSIONMODEBIAS,
    GUID_COMPARTMENT_EMPTYCONTEXT, GUID_COMPARTMENT_ENABLED_PROFILES_UPDATED,
    GUID_COMPARTMENT_HANDWRITING_OPENCLOSE, GUID_COMPARTMENT_KEYBOARD_DISABLED,
    GUID_COMPARTMENT_KEYBOARD_INPUTMODE, GUID_COMPARTMENT_KEYBOARD_INPUTMODE_CONVERSION,
    GUID_COMPARTMENT_KEYBOARD_INPUTMODE_SENTENCE, GUID_COMPARTMENT_KEYBOARD_OPENCLOSE,
    GUID_COMPARTMENT_SAPI_AUDIO, GUID_COMPARTMENT_SPEECH_CFGMENU, GUID_COMPARTMENT_SPEECH_DISABLED,
    GUID_COMPARTMENT_SPEECH_GLOBALSTATE, GUID_COMPARTMENT_SPEECH_OPENCLOSE,
    GUID_COMPARTMENT_SPEECH_UI_STATUS, GUID_COMPARTMENT_TIPUISTATUS,
    GUID_COMPARTMENT_TRANSITORYEXTENSION, GUID_COMPARTMENT_TRANSITORYEXTENSION_DOCUMENTMANAGER,
    GUID_COMPARTMENT_TRANSITORYEXTENSION_PARENT, GUID_TFCAT_TIP_KEYBOARD, ITfCompartmentMgr,
    ITfContext, ITfContextComposition, ITfInputProcessorProfileMgr, ITfThreadMgr,
    TF_INPUTPROCESSORPROFILE, TF_IPP_FLAG_ACTIVE, TF_IPP_FLAG_ENABLED,
    TF_IPP_FLAG_SUBSTITUTEDBYINPUTPROCESSOR, TF_PROFILETYPE_INPUTPROCESSOR,
    TF_PROFILETYPE_KEYBOARDLAYOUT, TS_SS_DISJOINTSEL, TS_SS_NOHIDDENTEXT, TS_SS_REGIONS,
    TS_SS_TKBAUTOCORRECTENABLE, TS_SS_TKBPREDICTIONENABLE, TS_SS_TRANSITORY, TS_SS_UWPCONTROL,
};
use windows::Win32::UI::WindowsAndMessaging::{
    GetClassNameW, GetForegroundWindow, GetMessageExtraInfo, GetWindowThreadProcessId,
    UNICODE_NOCHAR, WM_CHAR, WM_DEADCHAR, WM_IME_CHAR, WM_IME_COMPOSITION, WM_IME_ENDCOMPOSITION,
    WM_IME_KEYDOWN, WM_IME_KEYUP, WM_IME_NOTIFY, WM_IME_REQUEST, WM_IME_SELECT, WM_IME_SETCONTEXT,
    WM_IME_STARTCOMPOSITION, WM_INPUTLANGCHANGE, WM_KEYDOWN, WM_KEYUP, WM_KILLFOCUS, WM_NCDESTROY,
    WM_SETFOCUS, WM_SYSCHAR, WM_SYSDEADCHAR, WM_SYSKEYDOWN, WM_SYSKEYUP, WM_UNICHAR,
};
use windows::core::{GUID, HRESULT, Interface, PWSTR, s, w};

/// One trace line, through the module's switch.
macro_rules! tap_trace {
    ($($arg:tt)*) => {
        super::trace(format_args!($($arg)*))
    };
}

// ---------------------------------------------------------------------------
// Attaching, and installing and removing the tap
// ---------------------------------------------------------------------------

/// Subclass ids for this tap: a private range, distinct from the title bar's
/// (`0xFE_111_000`), the pen's (`0xFE_112_000`), the quit target's
/// (`0xFE_113_000`) and the completion capture's ([`CAPTURE_SUBCLASS_ID`]),
/// so no two can ever collide on one HWND.
static NEXT_SUBCLASS_ID: AtomicUsize = AtomicUsize::new(0xFE_114_000);

/// Orders every traced message, across windows.
static NEXT_SEQUENCE: AtomicU64 = AtomicU64::new(1);

thread_local! {
    /// Every attached window's HWND, whether its tap could be installed or
    /// not: what [`finish_composition`] acts on. `attach`, `detach` and
    /// `finish_composition` run on the UI thread, which owns every HWND.
    static WINDOWS: RefCell<HashMap<TeksiloWindowId, HWND>> = RefCell::new(HashMap::new());
    /// The installed taps. `attach` and `detach` run on the UI thread, which
    /// owns every HWND they touch.
    static TAPS: RefCell<HashMap<TeksiloWindowId, Tap>> = RefCell::new(HashMap::new());
    /// How many messages winit is handling on this thread, passed on by a tap.
    static HANDLING: Cell<u32> = const { Cell::new(0) };
    /// Whether a probe is running on this thread.
    static PROBING: Cell<bool> = const { Cell::new(false) };
}

/// What the subclass procedure reads through `dwRefData`.
struct TapState {
    window_id: TeksiloWindowId,
    /// The window tree's text surfaces, whose focused document answers the
    /// input method's requests.
    surfaces: TextSurfaces,
}

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

/// One installed subclass. Dropping it removes the subclass; the state the
/// procedure reads lives on while a call of the procedure holds it.
#[derive(Debug)]
struct Tap {
    hwnd: HWND,
    subclass_id: usize,
    state: Rc<TapState>,
}

impl Tap {
    /// The `dwRefData` the procedure is installed with: the shared state,
    /// which stays put however the `Tap` itself moves.
    fn ref_data(&self) -> usize {
        Rc::as_ptr(&self.state) as usize
    }
}

impl Drop for Tap {
    fn drop(&mut self) {
        // Synchronous on this thread. Fails harmlessly when the window is
        // already gone (the procedure removed itself at `WM_NCDESTROY`).
        unsafe {
            let _ = RemoveWindowSubclass(self.hwnd, Some(text_input_proc), self.subclass_id);
        }
    }
}

pub(super) fn attach(
    window_id: TeksiloWindowId,
    parent: &ParentHandle,
    poster: Arc<dyn AppEventPoster>,
    surfaces: TextSurfaces,
) {
    let Some(hwnd) = hwnd_of(parent) else {
        return;
    };

    // A second attach for one window replaces the first.
    detach(window_id);
    WINDOWS.with_borrow_mut(|windows| windows.insert(window_id, hwnd));
    install_tap(window_id, hwnd, surfaces.clone());
    tsf::attach(window_id, hwnd, poster, surfaces);
}

/// See [`super::set_text_store_focus`].
pub(super) fn set_text_store_focus(parent: &ParentHandle, focus: StoreFocus) {
    if let Some(hwnd) = hwnd_of(parent) {
        tsf::set_text_store_focus(hwnd, focus);
    }
}

/// See [`super::text_store_mode_for`].
pub(super) fn text_store_mode_for(parent: &ParentHandle) -> TextStoreMode {
    let mode = text_store_mode();
    if mode != TextStoreMode::Off && hwnd_of(parent).is_some_and(tsf::has_store) {
        mode
    } else {
        TextStoreMode::Off
    }
}

/// See [`super::legacy_input_method_active`].
pub(super) fn legacy_input_method_active() -> bool {
    let layout = unsafe { GetKeyboardLayout(0) };
    is_legacy_input_method(layout.0 as usize)
}

/// Whether a keyboard layout handle is an IMM32 input method's: its high
/// word, the device, is `0xE0xx`. A TSF text service runs over a plain
/// keyboard layout (the Microsoft Japanese IME's is `0x04110411`).
fn is_legacy_input_method(layout: usize) -> bool {
    (layout as u32) >> 28 == 0xE
}

/// See [`super::terminate_text_store_composition`].
pub(super) fn terminate_text_store_composition(parent: &ParentHandle) -> bool {
    hwnd_of(parent).is_some_and(tsf::terminate_composition)
}

/// See [`super::take_key_taken_by_text_store`].
pub(super) fn take_key_taken_by_text_store() -> bool {
    tsf::take_key_taken()
}

/// The HWND behind a window handle, `None` for one that is not a Win32 one.
fn hwnd_of(parent: &ParentHandle) -> Option<HWND> {
    let RawWindowHandle::Win32(handle) = parent.raw_window_handle() else {
        return None;
    };
    Some(HWND(handle.hwnd.get() as *mut c_void))
}

/// Install the tap on a window.
fn install_tap(window_id: TeksiloWindowId, hwnd: HWND, surfaces: TextSurfaces) {
    let tap = Tap {
        hwnd,
        subclass_id: NEXT_SUBCLASS_ID.fetch_add(1, Ordering::Relaxed),
        state: Rc::new(TapState {
            window_id,
            surfaces,
        }),
    };
    let installed =
        unsafe { SetWindowSubclass(hwnd, Some(text_input_proc), tap.subclass_id, tap.ref_data()) };
    let seq = next_sequence();
    if !installed.as_bool() {
        tap_trace!(
            "#{seq} {window_id} SetWindowSubclass returned FALSE; no requests answered, not traced"
        );
        return;
    }
    tap_trace!(
        "#{seq} {window_id} attached hwnd={:#x} subclass={:#x}",
        hwnd.0 as usize,
        tap.subclass_id
    );
    // A baseline for the compositions to come. Not while winit is handling a
    // message: a probe can deliver the messages sent to the window meanwhile,
    // and winit would see them in the middle of that one.
    if super::trace_enabled() {
        if winit_is_handling() {
            tap_trace!("#{seq}   baseline skipped: winit is handling a message");
        } else {
            let _probing = Probing::enter();
            probe_tsf(seq, Reach::Baseline);
            probe_foreground(seq, hwnd);
        }
    }
    TAPS.with_borrow_mut(|taps| taps.insert(window_id, tap));
}

pub(super) fn detach(window_id: TeksiloWindowId) {
    if let Some(hwnd) = WINDOWS.with_borrow_mut(|windows| windows.remove(&window_id)) {
        tsf::detach(hwnd);
    }
    // Taken out of the map first and dropped after the borrow ends, so
    // nothing `RemoveWindowSubclass` might run can find the map borrowed.
    let tap = TAPS.with_borrow_mut(|taps| taps.remove(&window_id));
    drop(tap);
}

fn next_sequence() -> u64 {
    NEXT_SEQUENCE.fetch_add(1, Ordering::Relaxed)
}

// ---------------------------------------------------------------------------
// The subclass procedure
// ---------------------------------------------------------------------------

/// Answers the input method's requests, logs, chains, and probes after winit
/// has handled the message.
unsafe extern "system" fn text_input_proc(
    hwnd: HWND,
    msg: u32,
    wparam: WPARAM,
    lparam: LPARAM,
    uid: usize,
    dw_ref_data: usize,
) -> LRESULT {
    let state: Option<Rc<TapState>> = (dw_ref_data != 0).then(|| {
        let state = dw_ref_data as *const TapState;
        // SAFETY: `dw_ref_data` is `Rc::as_ptr` of the state of the `Tap`
        // that installed this subclass. Only code winit runs can drop that
        // `Tap`, and none has run yet, so the `Rc` is alive here; this call
        // takes a reference of its own, which keeps the state alive past
        // whatever winit's handling drops.
        unsafe {
            Rc::increment_strong_count(state);
            Rc::from_raw(state)
        }
    });
    // Before winit has the message: nothing that can deliver another one.
    let probe_after = state.as_deref().and_then(|state| {
        // No panic may unwind into user32.
        catch_unwind(AssertUnwindSafe(|| log_message(state, msg, wparam, lparam)))
            .ok()
            .flatten()
    });
    if let Some(state) = state.as_deref()
        && msg == WM_IME_REQUEST
    {
        let answer = catch_unwind(AssertUnwindSafe(|| {
            answer_request(state, hwnd, wparam.0 as u32, lparam)
        }))
        .ok()
        .flatten();
        if let Some(answer) = answer {
            return answer;
        }
    }
    if msg == WM_KEYDOWN || msg == WM_SYSKEYDOWN {
        // The key-trace verdict: a key the text services passed on.
        tsf::note_window_key_down(wparam.0 as u32);
    }
    if msg == WM_NCDESTROY {
        // The documented place to remove a subclass. `Tap::drop` then finds
        // nothing to remove, which is harmless.
        unsafe {
            let _ = RemoveWindowSubclass(hwnd, Some(text_input_proc), uid);
        }
    }
    let result = {
        let _handling = Handling::enter();
        unsafe { DefSubclassProc(hwnd, msg, wparam, lparam) }
    };
    // After winit has handled it: the probes. They read no state, since
    // winit's handling may have closed the window.
    if let Some(seq) = probe_after {
        let _ = catch_unwind(AssertUnwindSafe(|| probe_message(hwnd, msg, seq)));
    }
    result
}

/// How a message reached the tap.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Arrival {
    /// Dispatched with nothing of the tap's on the stack.
    Direct,
    /// Sent while winit was handling another message of a tapped window.
    WhileHandling,
    /// Delivered by one of the tap's probes.
    DuringProbe,
}

impl Arrival {
    /// How the message being dispatched arrived. A thread whose locals are
    /// gone counts as probing, so it probes nothing.
    fn now() -> Self {
        if PROBING.try_with(Cell::get).unwrap_or(true) {
            Self::DuringProbe
        } else if winit_is_handling() {
            Self::WhileHandling
        } else {
            Self::Direct
        }
    }

    /// What the log line adds to say so.
    fn mark(self) -> &'static str {
        match self {
            Self::Direct => "",
            Self::WhileHandling => " (sent while winit handled another message)",
            Self::DuringProbe => " (sent during a probe)",
        }
    }
}

/// Whether winit is handling a message a tap passed on, on this thread.
fn winit_is_handling() -> bool {
    HANDLING.try_with(Cell::get).unwrap_or(0) > 0
}

/// Counts a message winit is handling, for as long as it lives.
struct Handling;

impl Handling {
    fn enter() -> Self {
        let _ = HANDLING.try_with(|count| count.set(count.get() + 1));
        Self
    }
}

impl Drop for Handling {
    fn drop(&mut self) {
        let _ = HANDLING.try_with(|count| count.set(count.get().saturating_sub(1)));
    }
}

/// Marks the thread as probing for as long as it lives, restoring what it
/// found (on a panic too).
struct Probing {
    outer: bool,
}

impl Probing {
    fn enter() -> Self {
        let outer = PROBING
            .try_with(|probing| probing.replace(true))
            .unwrap_or(true);
        Self { outer }
    }
}

impl Drop for Probing {
    fn drop(&mut self) {
        let _ = PROBING.try_with(|probing| probing.set(self.outer));
    }
}

/// Log one message, before winit has it, when tracing. Returns the
/// message's sequence number when it is one to probe once winit has handled
/// it: a composition message that arrived directly.
///
/// Calls nothing that can deliver a message.
fn log_message(state: &TapState, msg: u32, wparam: WPARAM, lparam: LPARAM) -> Option<u64> {
    if !super::trace_enabled() {
        return None;
    }
    let name = message_name(msg)?;
    // Both describe the message being dispatched, and a later call would no
    // longer report them.
    let source = input_source();
    let extra = unsafe { GetMessageExtraInfo() }.0;
    let seq = next_sequence();
    let arrival = Arrival::now();
    tap_trace!(
        "#{seq} {} {name} {} src={source} extra={extra:#x}{}",
        state.window_id,
        describe(msg, wparam, lparam),
        arrival.mark()
    );
    let probed = matches!(
        msg,
        WM_IME_STARTCOMPOSITION | WM_IME_COMPOSITION | WM_IME_ENDCOMPOSITION
    ) || (msg == WM_IME_NOTIFY
        && matches!(
            wparam.0 as u32,
            IMN_OPENCANDIDATE | IMN_CLOSECANDIDATE | IMN_SETOPENSTATUS
        ));
    (probed && arrival == Arrival::Direct).then_some(seq)
}

/// Probe IMM and TSF for a composition message winit has just handled.
///
/// The IMM strings after `WM_IME_ENDCOMPOSITION` are what winit's own handling
/// of it read: while it still holds a preedit there, it commits the result
/// string again (see `imm_completion`).
fn probe_message(hwnd: HWND, msg: u32, seq: u64) {
    let _probing = Probing::enter();
    if matches!(
        msg,
        WM_IME_COMPOSITION | WM_IME_ENDCOMPOSITION | WM_IME_NOTIFY
    ) {
        probe_imm(hwnd, seq);
    }
    probe_tsf(seq, Reach::Message);
}

// ---------------------------------------------------------------------------
// Describing a message
// ---------------------------------------------------------------------------

/// The messages the tap logs, by name. `None` for every other message.
fn message_name(msg: u32) -> Option<&'static str> {
    Some(match msg {
        WM_KEYDOWN => "WM_KEYDOWN",
        WM_KEYUP => "WM_KEYUP",
        WM_SYSKEYDOWN => "WM_SYSKEYDOWN",
        WM_SYSKEYUP => "WM_SYSKEYUP",
        WM_CHAR => "WM_CHAR",
        WM_SYSCHAR => "WM_SYSCHAR",
        WM_DEADCHAR => "WM_DEADCHAR",
        WM_SYSDEADCHAR => "WM_SYSDEADCHAR",
        WM_UNICHAR => "WM_UNICHAR",
        WM_IME_STARTCOMPOSITION => "WM_IME_STARTCOMPOSITION",
        WM_IME_ENDCOMPOSITION => "WM_IME_ENDCOMPOSITION",
        WM_IME_COMPOSITION => "WM_IME_COMPOSITION",
        WM_IME_NOTIFY => "WM_IME_NOTIFY",
        WM_IME_SETCONTEXT => "WM_IME_SETCONTEXT",
        WM_IME_CHAR => "WM_IME_CHAR",
        WM_IME_REQUEST => "WM_IME_REQUEST",
        WM_IME_SELECT => "WM_IME_SELECT",
        WM_IME_KEYDOWN => "WM_IME_KEYDOWN",
        WM_IME_KEYUP => "WM_IME_KEYUP",
        WM_INPUTLANGCHANGE => "WM_INPUTLANGCHANGE",
        WM_SETFOCUS => "WM_SETFOCUS",
        WM_KILLFOCUS => "WM_KILLFOCUS",
        _ => return None,
    })
}

/// The fields of one logged message, decoded.
fn describe(msg: u32, wparam: WPARAM, lparam: LPARAM) -> String {
    let (w, l) = (wparam.0, lparam.0);
    match msg {
        WM_KEYDOWN | WM_KEYUP | WM_SYSKEYDOWN | WM_SYSKEYUP | WM_IME_KEYDOWN | WM_IME_KEYUP => {
            format!("{} {}", virtual_key(w), key_flags(l))
        }
        WM_CHAR | WM_SYSCHAR | WM_DEADCHAR | WM_SYSDEADCHAR | WM_IME_CHAR => {
            format!("{} {}", utf16_unit(w), key_flags(l))
        }
        WM_UNICHAR if w as u32 == UNICODE_NOCHAR => "probe (UNICODE_NOCHAR)".to_owned(),
        WM_UNICHAR => format!("{} {}", code_point(w), key_flags(l)),
        WM_IME_COMPOSITION => format!(
            "last={} flags={:#x} [{}]",
            utf16_unit(w),
            l as u32,
            flag_names(l as u32, COMPOSITION_FLAGS)
        ),
        WM_IME_NOTIFY => format!("{} lparam={l:#x}", named(w as u32, NOTIFY_COMMANDS)),
        WM_IME_SETCONTEXT => format!(
            "active={} show={:#x} [{}]",
            w != 0,
            l as u32,
            flag_names(l as u32, SHOW_UI_FLAGS)
        ),
        WM_IME_REQUEST => named(w as u32, REQUEST_COMMANDS),
        WM_IME_SELECT => format!("selected={} hkl={l:#x}", w != 0),
        WM_INPUTLANGCHANGE => format!("charset={w} hkl={l:#x}"),
        _ => String::new(),
    }
}

/// A virtual key, with the two that matter here named: `VK_PACKET` (a
/// Unicode unit injected as a keystroke) and `VK_PROCESSKEY` (a key an IME
/// took).
fn virtual_key(wparam: usize) -> String {
    let vk = wparam as u16;
    let tag = if vk == VK_PACKET.0 {
        " VK_PACKET"
    } else if vk == VK_PROCESSKEY.0 {
        " VK_PROCESSKEY"
    } else {
        ""
    };
    format!("vk={vk:#04x}{tag}")
}

/// The keystroke fields of a key or character message's `lParam`. Whether the
/// keystroke was injected is not among them: that is the input source's
/// `originId`.
fn key_flags(lparam: isize) -> String {
    let bits = lparam as u32;
    format!(
        "scan={:#04x} ext={} alt={} prev={} up={} rep={}",
        (bits >> 16) & 0xFF,
        (bits >> 24) & 1,
        (bits >> 29) & 1,
        (bits >> 30) & 1,
        (bits >> 31) & 1,
        bits & 0xFFFF
    )
}

/// One UTF-16 unit, marked when it is half of a surrogate pair.
fn utf16_unit(wparam: usize) -> String {
    let unit = wparam as u32;
    match unit {
        0xD800..=0xDBFF => format!("unit={unit:#06x} high-surrogate"),
        0xDC00..=0xDFFF => format!("unit={unit:#06x} low-surrogate"),
        _ => match char::from_u32(unit) {
            Some(c) => format!("unit={unit:#06x} {c:?}"),
            None => format!("unit={unit:#06x}"),
        },
    }
}

/// One UTF-32 code point, as `WM_UNICHAR` carries it.
fn code_point(wparam: usize) -> String {
    let value = wparam as u32;
    match char::from_u32(value) {
        Some(c) => format!("U+{value:04X} {c:?}"),
        None => format!("U+{value:04X} (not a scalar value)"),
    }
}

/// The names of the bits set in `bits`, with any bit the table does not name
/// left as hex.
fn flag_names(bits: u32, table: &[(u32, &str)]) -> String {
    let mut names = Vec::new();
    let mut rest = bits;
    for &(flag, name) in table {
        if flag != 0 && bits & flag == flag {
            names.push(name.to_owned());
            rest &= !flag;
        }
    }
    if rest != 0 {
        names.push(format!("{rest:#x}"));
    }
    if names.is_empty() {
        "none".to_owned()
    } else {
        names.join("|")
    }
}

/// The name of a command value, or the value in hex.
fn named(value: u32, table: &[(u32, &str)]) -> String {
    table
        .iter()
        .find(|&&(known, _)| known == value)
        .map_or_else(|| format!("{value:#x}"), |&(_, name)| name.to_owned())
}

/// `WM_IME_COMPOSITION`'s `lParam` bits.
const COMPOSITION_FLAGS: &[(u32, &str)] = &[
    (GCS_COMPREADSTR.0, "GCS_COMPREADSTR"),
    (GCS_COMPREADATTR.0, "GCS_COMPREADATTR"),
    (GCS_COMPREADCLAUSE.0, "GCS_COMPREADCLAUSE"),
    (GCS_COMPSTR.0, "GCS_COMPSTR"),
    (GCS_COMPATTR.0, "GCS_COMPATTR"),
    (GCS_COMPCLAUSE.0, "GCS_COMPCLAUSE"),
    (GCS_CURSORPOS.0, "GCS_CURSORPOS"),
    (GCS_DELTASTART.0, "GCS_DELTASTART"),
    (GCS_RESULTREADSTR.0, "GCS_RESULTREADSTR"),
    (GCS_RESULTREADCLAUSE.0, "GCS_RESULTREADCLAUSE"),
    (GCS_RESULTSTR.0, "GCS_RESULTSTR"),
    (GCS_RESULTCLAUSE.0, "GCS_RESULTCLAUSE"),
    (CS_INSERTCHAR, "CS_INSERTCHAR"),
    (CS_NOMOVECARET, "CS_NOMOVECARET"),
];

/// `WM_IME_SETCONTEXT`'s `lParam` bits (`ISC_SHOWUI*`).
const SHOW_UI_FLAGS: &[(u32, &str)] = &[
    (0x8000_0000, "COMPOSITIONWINDOW"),
    (0x4000_0000, "GUIDELINE"),
    (0x0000_0001, "CANDIDATEWINDOW0"),
    (0x0000_0002, "CANDIDATEWINDOW1"),
    (0x0000_0004, "CANDIDATEWINDOW2"),
    (0x0000_0008, "CANDIDATEWINDOW3"),
];

/// `WM_IME_NOTIFY`'s `wParam` commands.
const NOTIFY_COMMANDS: &[(u32, &str)] = &[
    (IMN_CLOSESTATUSWINDOW, "IMN_CLOSESTATUSWINDOW"),
    (IMN_OPENSTATUSWINDOW, "IMN_OPENSTATUSWINDOW"),
    (IMN_CHANGECANDIDATE, "IMN_CHANGECANDIDATE"),
    (IMN_CLOSECANDIDATE, "IMN_CLOSECANDIDATE"),
    (IMN_OPENCANDIDATE, "IMN_OPENCANDIDATE"),
    (IMN_SETCONVERSIONMODE, "IMN_SETCONVERSIONMODE"),
    (IMN_SETSENTENCEMODE, "IMN_SETSENTENCEMODE"),
    (IMN_SETOPENSTATUS, "IMN_SETOPENSTATUS"),
    (IMN_SETCANDIDATEPOS, "IMN_SETCANDIDATEPOS"),
    (IMN_SETCOMPOSITIONFONT, "IMN_SETCOMPOSITIONFONT"),
    (IMN_SETCOMPOSITIONWINDOW, "IMN_SETCOMPOSITIONWINDOW"),
    (IMN_SETSTATUSWINDOWPOS, "IMN_SETSTATUSWINDOWPOS"),
    (IMN_GUIDELINE, "IMN_GUIDELINE"),
    (IMN_PRIVATE, "IMN_PRIVATE"),
    (IMN_SOFTKBDDESTROYED, "IMN_SOFTKBDDESTROYED"),
];

/// `WM_IME_REQUEST`'s `wParam` commands.
const REQUEST_COMMANDS: &[(u32, &str)] = &[
    (IMR_COMPOSITIONWINDOW, "IMR_COMPOSITIONWINDOW"),
    (IMR_CANDIDATEWINDOW, "IMR_CANDIDATEWINDOW"),
    (IMR_COMPOSITIONFONT, "IMR_COMPOSITIONFONT"),
    (IMR_RECONVERTSTRING, "IMR_RECONVERTSTRING"),
    (IMR_CONFIRMRECONVERTSTRING, "IMR_CONFIRMRECONVERTSTRING"),
    (IMR_QUERYCHARPOSITION, "IMR_QUERYCHARPOSITION"),
    (IMR_DOCUMENTFEED, "IMR_DOCUMENTFEED"),
];

/// A TSF context's static status bits (`TS_SS_*`).
const STATIC_STATUS_FLAGS: &[(u32, &str)] = &[
    (TS_SS_DISJOINTSEL, "DISJOINTSEL"),
    (TS_SS_REGIONS, "REGIONS"),
    (TS_SS_TRANSITORY, "TRANSITORY"),
    (TS_SS_NOHIDDENTEXT, "NOHIDDENTEXT"),
    (TS_SS_TKBAUTOCORRECTENABLE, "TKBAUTOCORRECTENABLE"),
    (TS_SS_TKBPREDICTIONENABLE, "TKBPREDICTIONENABLE"),
    (TS_SS_UWPCONTROL, "UWPCONTROL"),
];

/// An input processor profile's flags (`TF_IPP_FLAG_*`).
const PROFILE_FLAGS: &[(u32, &str)] = &[
    (TF_IPP_FLAG_ACTIVE, "ACTIVE"),
    (TF_IPP_FLAG_ENABLED, "ENABLED"),
    (
        TF_IPP_FLAG_SUBSTITUTEDBYINPUTPROCESSOR,
        "SUBSTITUTEDBYINPUTPROCESSOR",
    ),
];

/// Where `GetCurrentInputMessageSource` says the message being dispatched came
/// from, as `device/origin`.
fn input_source() -> String {
    let mut source = INPUT_MESSAGE_SOURCE::default();
    if let Err(error) = unsafe { GetCurrentInputMessageSource(&mut source) } {
        return format!("<{}>", hresult(&error));
    }
    let device = match source.deviceType {
        IMDT_UNAVAILABLE => "unavailable".to_owned(),
        IMDT_KEYBOARD => "keyboard".to_owned(),
        IMDT_MOUSE => "mouse".to_owned(),
        IMDT_TOUCH => "touch".to_owned(),
        IMDT_PEN => "pen".to_owned(),
        IMDT_TOUCHPAD => "touchpad".to_owned(),
        other => format!("{:#x}", other.0),
    };
    let origin = match source.originId {
        IMO_UNAVAILABLE => "unavailable".to_owned(),
        IMO_HARDWARE => "hardware".to_owned(),
        IMO_INJECTED => "injected".to_owned(),
        IMO_SYSTEM => "system".to_owned(),
        other => format!("{:#x}", other.0),
    };
    format!("{device}/{origin}")
}

/// A failed call's `HRESULT` and message. A call that succeeded with a null
/// out-pointer (which `windows` reports as an error carrying `S_OK`) reads
/// as `null`.
fn hresult(error: &windows::core::Error) -> String {
    let code = error.code();
    if code.is_ok() {
        return "null".to_owned();
    }
    format!("{:#010x} {}", code.0 as u32, error.message().trim_end())
}

// ---------------------------------------------------------------------------
// The IMM probe
// ---------------------------------------------------------------------------

/// Read the window's current composition and result strings.
fn probe_imm(hwnd: HWND, seq: u64) {
    let himc = unsafe { ImmGetContext(hwnd) };
    if himc.is_invalid() {
        tap_trace!("#{seq}   imm: the window has no input context");
        return;
    }
    let composition = composition_string(himc, GCS_COMPSTR);
    let result = composition_string(himc, GCS_RESULTSTR);
    let cursor = unsafe { ImmGetCompositionStringW(himc, GCS_CURSORPOS, None, 0) };
    let delta = unsafe { ImmGetCompositionStringW(himc, GCS_DELTASTART, None, 0) };
    let open = unsafe { ImmGetOpenStatus(himc) }.as_bool();
    let (mut conversion, mut sentence) = (IME_CONVERSION_MODE(0), IME_SENTENCE_MODE(0));
    let _ = unsafe { ImmGetConversionStatus(himc, Some(&mut conversion), Some(&mut sentence)) };
    unsafe {
        let _ = ImmReleaseContext(hwnd, himc);
    }
    tap_trace!(
        "#{seq}   imm: comp={composition} result={result} cursor={cursor} delta={delta} open={open} conversion={:#x} sentence={:#x}",
        conversion.0,
        sentence.0
    );
}

/// One of an input context's strings, with its UTF-16 units in hex, so a lone
/// surrogate shows. Reading does not consume it.
fn composition_string(himc: HIMC, which: IME_COMPOSITION_STRING) -> String {
    // The length is in bytes; a negative one is `IMM_ERROR_NODATA` (-1) or
    // `IMM_ERROR_GENERAL` (-2).
    let bytes = unsafe { ImmGetCompositionStringW(himc, which, None, 0) };
    if bytes < 0 {
        return format!("<error {bytes}>");
    }
    if bytes == 0 {
        return "<none>".to_owned();
    }
    let mut units = vec![0u16; bytes as usize / 2];
    let read = unsafe {
        ImmGetCompositionStringW(
            himc,
            which,
            Some(units.as_mut_ptr().cast()),
            (units.len() * 2) as u32,
        )
    };
    if read < 0 {
        return format!("<error {read}>");
    }
    units.truncate(read as usize / 2);
    let hex: Vec<String> = units.iter().map(|unit| format!("{unit:04x}")).collect();
    format!("{:?} [{}]", String::from_utf16_lossy(&units), hex.join(" "))
}

// ---------------------------------------------------------------------------
// The TSF probe
// ---------------------------------------------------------------------------

/// How much of TSF a probe reads.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Reach {
    /// After a composition message: the focused context, its compositions and
    /// the active keyboard TIP.
    Message,
    /// At attach: the same, and the compartments at every level.
    Baseline,
}

/// Ask TSF about the focused context and its compositions, the compartments
/// at a baseline, and which keyboard TIP is active.
fn probe_tsf(seq: u64, reach: Reach) {
    let apartment = match com_apartment() {
        Ok(apartment) => apartment,
        Err(problem) => {
            tap_trace!("#{seq}   tsf: {problem}; not probed");
            return;
        }
    };
    match existing_thread_manager() {
        Ok(manager) => probe_thread_manager(seq, apartment, &manager, reach),
        Err(why) => tap_trace!("#{seq}   tsf: apartment={apartment}, no thread manager: {why}"),
    }
    probe_keyboard_profile(seq);
}

/// This thread's COM apartment, or why COM cannot be used here. Never
/// initialises COM.
fn com_apartment() -> Result<&'static str, String> {
    let mut kind = APTTYPE::default();
    let mut qualifier = APTTYPEQUALIFIER::default();
    match unsafe { CoGetApartmentType(&mut kind, &mut qualifier) } {
        Ok(()) => Ok(match kind {
            APTTYPE_STA => "STA",
            APTTYPE_MAINSTA => "main STA",
            APTTYPE_MTA => "MTA",
            APTTYPE_NA => "NA",
            _ => "unknown",
        }),
        Err(error) if error.code() == CO_E_NOTINITIALIZED => {
            Err("COM is not initialised on this thread".to_owned())
        }
        Err(error) => Err(format!("CoGetApartmentType failed: {}", hresult(&error))),
    }
}

/// The thread manager this thread already has.
///
/// msctf exports `TF_GetThreadMgr` with no import library, hence
/// `GetProcAddress`. When msctf is not loaded, nothing in the process is using
/// TSF.
fn existing_thread_manager() -> Result<ITfThreadMgr, String> {
    /// `HRESULT WINAPI TF_GetThreadMgr(ITfThreadMgr **pptim)`.
    type GetThreadMgr = unsafe extern "system" fn(*mut *mut c_void) -> HRESULT;

    let module = unsafe { GetModuleHandleW(w!("msctf.dll")) }
        .map_err(|_| "msctf.dll is not loaded".to_owned())?;
    let Some(export) = (unsafe { GetProcAddress(module, s!("TF_GetThreadMgr")) }) else {
        return Err("msctf.dll exports no TF_GetThreadMgr".to_owned());
    };
    // SAFETY: the export has the signature `GetThreadMgr` spells out.
    let get = unsafe {
        std::mem::transmute::<unsafe extern "system" fn() -> isize, GetThreadMgr>(export)
    };
    let mut raw: *mut c_void = std::ptr::null_mut();
    let result = unsafe { get(&mut raw) };
    if result.is_err() {
        return Err(format!(
            "TF_GetThreadMgr failed: {}",
            hresult(&windows::core::Error::from_hresult(result))
        ));
    }
    if raw.is_null() {
        return Err("this thread has none".to_owned());
    }
    // SAFETY: `TF_GetThreadMgr` hands over a reference it has added;
    // `from_raw` takes it over and releases it on drop.
    Ok(unsafe { ITfThreadMgr::from_raw(raw) })
}

/// The focused document and its top context, the owner of each composition
/// in it, and at a baseline the compartments at every level.
fn probe_thread_manager(seq: u64, apartment: &str, manager: &ITfThreadMgr, reach: Reach) {
    let thread_focus = match unsafe { manager.IsThreadFocus() } {
        Ok(focus) => focus.as_bool().to_string(),
        Err(error) => format!("<{}>", hresult(&error)),
    };
    let prefix = format!("tsf: apartment={apartment}, thread focus={thread_focus}");
    let document = match unsafe { manager.GetFocus() } {
        Ok(document) => Some(document),
        Err(error) => {
            tap_trace!("#{seq}   {prefix}, focused document: {}", hresult(&error));
            None
        }
    };
    let context = document
        .as_ref()
        .and_then(|document| match unsafe { document.GetTop() } {
            Ok(context) => Some(context),
            Err(error) => {
                tap_trace!("#{seq}   {prefix}, top context: {}", hresult(&error));
                None
            }
        });
    if let Some(context) = &context {
        match unsafe { context.GetStatus() } {
            Ok(status) => tap_trace!(
                "#{seq}   {prefix}, top context dynamic={:#x} static={:#x} [{}]",
                status.dwDynamicFlags,
                status.dwStaticFlags,
                flag_names(status.dwStaticFlags, STATIC_STATUS_FLAGS)
            ),
            Err(error) => {
                tap_trace!("#{seq}   {prefix}, top context status: {}", hresult(&error))
            }
        }
        probe_compositions(seq, context);
    }
    if reach != Reach::Baseline {
        return;
    }
    probe_compartments(seq, "global", unsafe { manager.GetGlobalCompartment() });
    probe_compartments(seq, "thread", manager.cast());
    if let Some(document) = &document {
        probe_compartments(seq, "document", document.cast());
    }
    if let Some(context) = &context {
        probe_compartments(seq, "context", context.cast());
    }
}

/// The owner of each composition in `context`.
fn probe_compositions(seq: u64, context: &ITfContext) {
    let views = match context
        .cast::<ITfContextComposition>()
        .and_then(|composition| unsafe { composition.EnumCompositions() })
    {
        Ok(views) => views,
        Err(error) => {
            tap_trace!("#{seq}   tsf: compositions: {}", hresult(&error));
            return;
        }
    };
    /// A context holds one composition, rarely more; the cap only bounds a
    /// misbehaving enumerator.
    const MAX_COMPOSITIONS: usize = 16;
    let mut count = 0;
    while count < MAX_COMPOSITIONS {
        let mut slot = [None];
        let mut fetched = 0u32;
        if let Err(error) = unsafe { views.Next(&mut slot, &mut fetched) } {
            tap_trace!("#{seq}   tsf: composition {count}: {}", hresult(&error));
            break;
        }
        let Some(view) = slot[0].take().filter(|_| fetched > 0) else {
            break;
        };
        match unsafe { view.GetOwnerClsid() } {
            Ok(owner) => tap_trace!("#{seq}   tsf: composition {count} owner={{{owner:?}}}"),
            Err(error) => {
                tap_trace!(
                    "#{seq}   tsf: composition {count} owner: {}",
                    hresult(&error)
                )
            }
        }
        count += 1;
    }
    if count == 0 {
        tap_trace!("#{seq}   tsf: no composition in the top context");
    }
}

/// The compartments the trace always reads, at every level.
const WATCHED_COMPARTMENTS: &[(GUID, &str)] = &[
    (GUID_COMPARTMENT_SPEECH_OPENCLOSE, "SPEECH_OPENCLOSE"),
    (GUID_COMPARTMENT_SPEECH_DISABLED, "SPEECH_DISABLED"),
    (GUID_COMPARTMENT_SPEECH_GLOBALSTATE, "SPEECH_GLOBALSTATE"),
    (
        GUID_COMPARTMENT_HANDWRITING_OPENCLOSE,
        "HANDWRITING_OPENCLOSE",
    ),
    (GUID_COMPARTMENT_KEYBOARD_OPENCLOSE, "KEYBOARD_OPENCLOSE"),
    (GUID_COMPARTMENT_KEYBOARD_DISABLED, "KEYBOARD_DISABLED"),
];

/// Other compartments TSF defines, named when a level lists them.
const OTHER_KNOWN_COMPARTMENTS: &[(GUID, &str)] = &[
    (GUID_COMPARTMENT_CONVERSIONMODEBIAS, "CONVERSIONMODEBIAS"),
    (GUID_COMPARTMENT_EMPTYCONTEXT, "EMPTYCONTEXT"),
    (
        GUID_COMPARTMENT_ENABLED_PROFILES_UPDATED,
        "ENABLED_PROFILES_UPDATED",
    ),
    (GUID_COMPARTMENT_KEYBOARD_INPUTMODE, "KEYBOARD_INPUTMODE"),
    (
        GUID_COMPARTMENT_KEYBOARD_INPUTMODE_CONVERSION,
        "KEYBOARD_INPUTMODE_CONVERSION",
    ),
    (
        GUID_COMPARTMENT_KEYBOARD_INPUTMODE_SENTENCE,
        "KEYBOARD_INPUTMODE_SENTENCE",
    ),
    (GUID_COMPARTMENT_SAPI_AUDIO, "SAPI_AUDIO"),
    (GUID_COMPARTMENT_SPEECH_CFGMENU, "SPEECH_CFGMENU"),
    (GUID_COMPARTMENT_SPEECH_UI_STATUS, "SPEECH_UI_STATUS"),
    (GUID_COMPARTMENT_TIPUISTATUS, "TIPUISTATUS"),
    (GUID_COMPARTMENT_TRANSITORYEXTENSION, "TRANSITORYEXTENSION"),
    (
        GUID_COMPARTMENT_TRANSITORYEXTENSION_DOCUMENTMANAGER,
        "TRANSITORYEXTENSION_DOCUMENTMANAGER",
    ),
    (
        GUID_COMPARTMENT_TRANSITORYEXTENSION_PARENT,
        "TRANSITORYEXTENSION_PARENT",
    ),
];

/// The most compartments one level is expected to list; the cap only bounds
/// a misbehaving enumerator.
const MAX_LISTED_COMPARTMENTS: usize = 64;

/// Read one level's compartments: the watched ones whether or not the level
/// lists them, then every other one it lists.
fn probe_compartments(seq: u64, level: &str, manager: windows::core::Result<ITfCompartmentMgr>) {
    let manager = match manager {
        Ok(manager) => manager,
        Err(error) => {
            tap_trace!("#{seq}   tsf: {level} compartments: {}", hresult(&error));
            return;
        }
    };
    // Listed before anything is read, so the list is what existed before the
    // probe looked.
    let (listed, listing) = match listed_compartments(&manager) {
        Ok(listed) => {
            let listing = format!("{} listed", listed.len());
            (listed, listing)
        }
        Err(error) => (Vec::new(), format!("listing: {}", hresult(&error))),
    };
    let watched: Vec<String> = WATCHED_COMPARTMENTS
        .iter()
        .map(|(guid, name)| {
            let mark = if listed.contains(guid) {
                ""
            } else {
                " (unlisted)"
            };
            format!("{name}={}{mark}", read_compartment(&manager, guid))
        })
        .collect();
    tap_trace!(
        "#{seq}   tsf: {level} compartments ({listing}): {}",
        watched.join(", ")
    );
    let others: Vec<String> = listed
        .iter()
        .filter(|guid| {
            !WATCHED_COMPARTMENTS
                .iter()
                .any(|(watched, _)| watched == *guid)
        })
        .map(|guid| {
            format!(
                "{}={}",
                compartment_name(guid),
                read_compartment(&manager, guid)
            )
        })
        .collect();
    if !others.is_empty() {
        tap_trace!(
            "#{seq}   tsf: {level} compartments, others: {}",
            others.join(", ")
        );
    }
}

/// The compartments a level lists, in its order.
fn listed_compartments(manager: &ITfCompartmentMgr) -> windows::core::Result<Vec<GUID>> {
    let guids = unsafe { manager.EnumCompartments() }?;
    let mut listed = Vec::new();
    while listed.len() < MAX_LISTED_COMPARTMENTS {
        let mut batch = [GUID::zeroed(); 16];
        let mut fetched = 0u32;
        let result = unsafe { guids.Next(&mut batch, Some(&mut fetched)) };
        result.ok()?;
        let fetched = (fetched as usize).min(batch.len());
        listed.extend_from_slice(&batch[..fetched]);
        // `S_FALSE` (fewer than asked for) ends the list.
        if result != S_OK || fetched == 0 {
            break;
        }
    }
    Ok(listed)
}

/// A compartment's name, or its GUID when TSF does not define it.
fn compartment_name(guid: &GUID) -> String {
    WATCHED_COMPARTMENTS
        .iter()
        .chain(OTHER_KNOWN_COMPARTMENTS)
        .find(|(known, _)| known == guid)
        .map_or_else(|| format!("{{{guid:?}}}"), |(_, name)| (*name).to_owned())
}

/// One compartment's value, or why it could not be read.
fn read_compartment(manager: &ITfCompartmentMgr, guid: &GUID) -> String {
    let compartment = match unsafe { manager.GetCompartment(guid) } {
        Ok(compartment) => compartment,
        Err(error) => return format!("<{}>", hresult(&error)),
    };
    match unsafe { compartment.GetValue() } {
        Ok(mut value) => describe_variant(&mut value),
        Err(error) => format!("<{}>", hresult(&error)),
    }
}

/// A `VARIANT`'s type and value, then cleared (the caller owns it, and
/// `VARIANT` has no `Drop`).
fn describe_variant(value: &mut VARIANT) -> String {
    // SAFETY: `vt` says which member of the union is live, and only that
    // member is read.
    let text = unsafe {
        let tagged = &value.Anonymous.Anonymous;
        let data = &tagged.Anonymous;
        match tagged.vt {
            VT_EMPTY => "empty".to_owned(),
            VT_I4 => format!("I4 {}", data.lVal),
            VT_INT => format!("INT {}", data.intVal),
            VT_UI4 => format!("UI4 {}", data.ulVal),
            VT_UINT => format!("UINT {}", data.uintVal),
            VT_I2 => format!("I2 {}", data.iVal),
            VT_BOOL => format!("BOOL {}", data.boolVal.0 != 0),
            VT_BSTR => format!("BSTR {:?}", (*data.bstrVal).to_string()),
            VT_UNKNOWN => {
                let set = if data.punkVal.is_some() {
                    "non-null"
                } else {
                    "null"
                };
                format!("UNKNOWN {set}")
            }
            other => format!("vt={:#x}", other.0),
        }
    };
    unsafe {
        let _ = VariantClear(value);
    }
    text
}

/// The active keyboard input processor profile: a TIP (an IME, voice
/// typing's, if it has one) or a plain keyboard layout.
fn probe_keyboard_profile(seq: u64) {
    let profiles: ITfInputProcessorProfileMgr = match unsafe {
        CoCreateInstance(&CLSID_TF_InputProcessorProfiles, None, CLSCTX_INPROC_SERVER)
    } {
        Ok(profiles) => profiles,
        Err(error) => {
            tap_trace!("#{seq}   tsf: profile manager: {}", hresult(&error));
            return;
        }
    };
    let mut profile = TF_INPUTPROCESSORPROFILE::default();
    if let Err(error) = unsafe { profiles.GetActiveProfile(&GUID_TFCAT_TIP_KEYBOARD, &mut profile) }
    {
        tap_trace!("#{seq}   tsf: active keyboard profile: {}", hresult(&error));
        return;
    }
    let kind = match profile.dwProfileType {
        TF_PROFILETYPE_INPUTPROCESSOR => "TIP".to_owned(),
        TF_PROFILETYPE_KEYBOARDLAYOUT => "keyboard layout".to_owned(),
        other => format!("type {other:#x}"),
    };
    tap_trace!(
        "#{seq}   tsf: active keyboard profile: {kind} langid={:#06x} clsid={{{:?}}} profile={{{:?}}} hkl={:#x} flags={:#x} [{}]",
        profile.langid,
        profile.clsid,
        profile.guidProfile,
        profile.hkl.0 as usize,
        profile.dwFlags,
        flag_names(profile.dwFlags, PROFILE_FLAGS)
    );
}

// ---------------------------------------------------------------------------
// The foreground probe
// ---------------------------------------------------------------------------

/// The foreground window, its class, and the image of the process that owns
/// it. `hwnd` is the tapped window, so the line says whether the foreground is
/// it.
fn probe_foreground(seq: u64, hwnd: HWND) {
    let foreground = unsafe { GetForegroundWindow() };
    if foreground.is_invalid() {
        tap_trace!("#{seq}   fg: no foreground window");
        return;
    }
    let mut class = [0u16; 256];
    let length = unsafe { GetClassNameW(foreground, &mut class) };
    let class = match usize::try_from(length) {
        Ok(length) if length > 0 => format!(
            "{:?}",
            String::from_utf16_lossy(&class[..length.min(class.len())])
        ),
        _ => "<unknown>".to_owned(),
    };
    let mut pid = 0u32;
    let tid = unsafe { GetWindowThreadProcessId(foreground, Some(&mut pid)) };
    let this_process = pid == unsafe { GetCurrentProcessId() };
    tap_trace!(
        "#{seq}   fg: hwnd={:#x} class={class} pid={pid} tid={tid} this window={} this process={this_process} image={}",
        foreground.0 as usize,
        foreground == hwnd,
        process_image(pid)
    );
}

/// The full path of a process's image, or why it could not be read (a
/// protected process refuses even the limited query).
fn process_image(pid: u32) -> String {
    let process = match unsafe { OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, false, pid) } {
        Ok(process) => process,
        Err(error) => return format!("<{}>", hresult(&error)),
    };
    let mut path = [0u16; 1024];
    let mut length = path.len() as u32;
    let result = unsafe {
        QueryFullProcessImageNameW(
            process,
            PROCESS_NAME_WIN32,
            PWSTR(path.as_mut_ptr()),
            &mut length,
        )
    };
    unsafe {
        let _ = CloseHandle(process);
    }
    match result {
        Ok(()) => format!(
            "{:?}",
            String::from_utf16_lossy(&path[..(length as usize).min(path.len())])
        ),
        Err(error) => format!("<{}>", hresult(&error)),
    }
}

// ---------------------------------------------------------------------------
// Answering the input method's requests
// ---------------------------------------------------------------------------

// `imm_requests` lays the string out after a header of this size.
const _: () = assert!(imm_requests::RECONVERTSTRING_HEADER == size_of::<RECONVERTSTRING>());

/// Answer `WM_IME_REQUEST` `command` from the focused document: the result
/// to return, or `None` to pass the request on to winit, which answers
/// "nothing". Before winit has the message, so it calls nothing that can
/// deliver one and runs no application code: the document's probe, its
/// reads only once the probe says they change nothing, `GetDpiForWindow`,
/// `ClientToScreen`.
fn answer_request(state: &TapState, hwnd: HWND, command: u32, lparam: LPARAM) -> Option<LRESULT> {
    let name = match command {
        IMR_QUERYCHARPOSITION => "IMR_QUERYCHARPOSITION",
        IMR_DOCUMENTFEED => "IMR_DOCUMENTFEED",
        IMR_RECONVERTSTRING | IMR_CONFIRMRECONVERTSTRING => {
            if super::trace_enabled() {
                tap_trace!(
                    "#{} {} {}: not answered (reconversion is left for the TSF store); passed on",
                    next_sequence(),
                    state.window_id,
                    named(command, REQUEST_COMMANDS)
                );
            }
            return None;
        }
        _ => return None,
    };
    let answer = state.surfaces.with_focused_input_document(|document| {
        // Asked first, and alone when it says no: it changes nothing, where
        // a read with typing not yet inserted would insert it and run the
        // application's change callbacks, ahead of winit.
        if !document.is_available() {
            return Err(Unavailable);
        }
        Ok(match command {
            IMR_QUERYCHARPOSITION => query_char_position(document, hwnd, lparam),
            _ => imm_requests::document_feed(document)
                .and_then(|string| write_reconvert_string(&string, lparam)),
        })
    });
    if super::trace_enabled() {
        let seq = next_sequence();
        let window_id = state.window_id;
        match &answer {
            Some(Ok(Some(LRESULT(result)))) => {
                tap_trace!("#{seq} {window_id} answered {name}: {result:#x}")
            }
            Some(Ok(None)) => {
                tap_trace!("#{seq} {window_id} {name}: nothing to answer; passed on")
            }
            Some(Err(Unavailable)) => tap_trace!(
                "#{seq} {window_id} {name}: the document cannot answer without a change \
                 (busy, or typing not yet inserted); passed on"
            ),
            None => tap_trace!("#{seq} {window_id} {name}: no focused document; passed on"),
        }
    }
    answer.and_then(Result::ok).flatten()
}

/// The focused document cannot answer without a change: see
/// [`TextInputDocument::is_available`].
#[derive(Debug)]
struct Unavailable;

/// `IMR_QUERYCHARPOSITION`: fill the `IMECHARPOSITION` at `lparam` with
/// where the asked character of the composition is drawn, on the screen.
fn query_char_position(
    document: &dyn TextInputDocument,
    hwnd: HWND,
    lparam: LPARAM,
) -> Option<LRESULT> {
    let request = lparam.0 as *mut IMECHARPOSITION;
    if request.is_null() {
        return None;
    }
    // SAFETY: the input method hands a structure it owns for the length of
    // the call; its `dwSize` says how much of it there is.
    let mut position = unsafe { request.read_unaligned() };
    if (position.dwSize as usize) < size_of::<IMECHARPOSITION>() {
        return None;
    }
    let answer = imm_requests::char_position(document, position.dwCharPos as usize)?;
    let dpi = unsafe { GetDpiForWindow(hwnd) };
    if dpi == 0 {
        return None;
    }
    let scale = dpi as f32 / 96.0;
    position.pt = to_screen(hwnd, answer.caret.x, answer.caret.y, scale);
    position.cLineHeight = (answer.caret.height * scale).round().max(1.0) as u32;
    if let Some(visible) = answer.document {
        let top_left = to_screen(hwnd, visible.x, visible.y, scale);
        let bottom_right = to_screen(hwnd, visible.right(), visible.bottom(), scale);
        position.rcDocument = RECT {
            left: top_left.x,
            top: top_left.y,
            right: bottom_right.x,
            bottom: bottom_right.y,
        };
    }
    if super::trace_enabled() {
        let document = position.rcDocument;
        tap_trace!(
            "  char position {} -> screen ({}, {}) height {}, document ({}, {})..({}, {}); caret window-logical {:?}",
            position.dwCharPos,
            position.pt.x,
            position.pt.y,
            position.cLineHeight,
            document.left,
            document.top,
            document.right,
            document.bottom,
            answer.caret
        );
    }
    // SAFETY: as above.
    unsafe { request.write_unaligned(position) };
    Some(LRESULT(1))
}

/// A window-logical point on the screen: scaled to the client area's pixels,
/// as winit scales the IME cursor area, then `ClientToScreen`.
fn to_screen(hwnd: HWND, x: f32, y: f32, scale: f32) -> POINT {
    let mut point = POINT {
        x: (x * scale).round() as i32,
        y: (y * scale).round() as i32,
    };
    unsafe {
        let _ = ClientToScreen(hwnd, &mut point);
    }
    point
}

/// Answer `IMR_RECONVERTSTRING` or `IMR_DOCUMENTFEED` with `string`: its
/// size when `lparam` is null (the input method's first call), else written
/// into the `RECONVERTSTRING` there, which its `dwSize` says is large
/// enough, and its size again (as Firefox answers); `0` when it is not.
fn write_reconvert_string(string: &ReconvertString, lparam: LPARAM) -> Option<LRESULT> {
    let fields = string.fields()?;
    let buffer = lparam.0 as *mut u8;
    if buffer.is_null() {
        return Some(LRESULT(fields.size as isize));
    }
    // SAFETY: the input method hands a buffer it owns for the length of the
    // call, `dwSize` bytes long, which is checked before anything past the
    // header is written.
    unsafe {
        let header = buffer.cast::<RECONVERTSTRING>();
        let given = header.read_unaligned().dwSize;
        if given < fields.size {
            return Some(LRESULT(0));
        }
        header.write_unaligned(RECONVERTSTRING {
            dwSize: given,
            dwVersion: 0,
            dwStrLen: fields.str_len,
            dwStrOffset: fields.str_offset,
            dwCompStrLen: fields.comp_len,
            dwCompStrOffset: fields.comp_offset,
            dwTargetStrLen: fields.target_len,
            dwTargetStrOffset: fields.target_offset,
        });
        std::ptr::copy_nonoverlapping(
            string.units.as_ptr().cast::<u8>(),
            buffer.add(fields.str_offset as usize),
            string.units.len() * 2,
        );
    }
    if super::trace_enabled() {
        tap_trace!(
            "  RECONVERTSTRING size={} str_len={} comp={}+{} target={}+{} (byte offset+units), from character {}: {:?}",
            fields.size,
            fields.str_len,
            fields.comp_offset,
            fields.comp_len,
            fields.target_offset,
            fields.target_len,
            string.start,
            String::from_utf16_lossy(&string.units)
        );
    }
    Some(LRESULT(fields.size as isize))
}

// ---------------------------------------------------------------------------
// Completing a composition
// ---------------------------------------------------------------------------

/// The subclass id of the capture [`finish_composition`] installs for as long
/// as it completes a composition: a private range, distinct from the trace
/// tap's (see [`NEXT_SUBCLASS_ID`]). One window completes at a time, so one id
/// serves them all.
const CAPTURE_SUBCLASS_ID: usize = 0xFE_115_000;

// The flags the completion reads in `WM_IME_COMPOSITION`'s `lParam` are IMM's.
const _: () = assert!(
    imm_completion::GCS_COMPSTR == GCS_COMPSTR.0
        && imm_completion::GCS_RESULTSTR == GCS_RESULTSTR.0
);

thread_local! {
    /// The completion [`finish_composition`] is capturing, and the window it
    /// is for: set around its `ImmNotifyIME` calls, fed by [`capture_proc`].
    static CAPTURE: RefCell<Option<(HWND, ImmCompletion)>> = const { RefCell::new(None) };
}

/// Complete the window's composition, which the focused field is ending (a
/// click elsewhere, a focus change), and say what the input method committed
/// for it and what winit will commit once the handler returns.
///
/// It asks the input method to complete the composition
/// (`ImmNotifyIME(NI_COMPOSITIONSTR, CPS_COMPLETE)`), as a native edit control
/// does when the caret leaves it, so that the field keeps the input method's
/// own form of the text rather than the one it showed: measured in Notepad,
/// Microsoft Pinyin commits "nihao" for the "ni'hao" it shows. The input
/// method sends its messages to the window from inside the call (measured
/// with `CPS_CANCEL`: its `WM_IME_ENDCOMPOSITION` reached the window while
/// winit was still handling the click). winit handles each
/// as it comes and holds the events they make until the application is done
/// with the one it is handling, so they reach the field after it has kept the
/// text. A subclass installed for the call ([`capture_proc`]) shows each
/// message to an [`ImmCompletion`] before winit has it, which says what the
/// input method committed (its `GCS_RESULTSTR`s) and what winit commits for
/// the messages (see `imm_completion` for winit's rules): the application
/// drops those ([`FinishedComposition::late_commits`]).
///
/// An input method still composing after the call (it refused the
/// completion, sent nothing for it, or composed again) is then told to cancel
/// (`CPS_CANCEL`), so that it composes no more at the place the field has
/// left; the text it still composed is kept after what it committed. The
/// capture follows the cancel's messages too.
///
/// With no subclass to capture through, the hook cancels instead, and the
/// field keeps what the composition showed: a cancel produces no result, and
/// CUAS (which serves every TSF input method to an IMM32 window like
/// winit's) writes the context's strings afresh at each update, so what winit
/// reads at the end and commits is an empty string, which inserts nothing.
///
/// `None` when the window is not attached or has no input context (its IME is
/// not allowed, so nothing is composing), and the caller's fallback, toggling
/// winit's IME, then finds nothing to reset either.
pub(super) fn finish_composition(window_id: TeksiloWindowId) -> Option<FinishedComposition> {
    let hwnd = WINDOWS
        .try_with(|windows| windows.borrow().get(&window_id).copied())
        .ok()
        .flatten();
    let seq = next_sequence();
    let Some(hwnd) = hwnd else {
        tap_trace!("#{seq} {window_id} finish composition: the window is not attached");
        return None;
    };
    // A composition a text service holds in the store: it ends it, and
    // writes its last text into the field itself (4.11).
    if tsf::terminate_composition(hwnd) {
        tap_trace!("#{seq} {window_id} finish composition: the store's, terminated");
        return Some(FinishedComposition::default());
    }
    let himc = unsafe { ImmGetContext(hwnd) };
    if himc.is_invalid() {
        tap_trace!("#{seq} {window_id} finish composition: the window has no input context");
        return None;
    }
    if super::trace_enabled() {
        tap_trace!(
            "#{seq} {window_id} finish composition: comp={} result={}",
            composition_string(himc, GCS_COMPSTR),
            composition_string(himc, GCS_RESULTSTR)
        );
    }
    let finished = complete(hwnd, himc, seq);
    unsafe {
        let _ = ImmReleaseContext(hwnd, himc);
    }
    Some(finished)
}

/// [`finish_composition`]'s calls to the input method, in `himc`, the input
/// context of `hwnd`.
fn complete(hwnd: HWND, himc: HIMC, seq: u64) -> FinishedComposition {
    let tracing = super::trace_enabled();
    let Some(capture) = Capture::install(hwnd) else {
        let cancelled = unsafe { ImmNotifyIME(himc, NI_COMPOSITIONSTR, CPS_CANCEL, 0) };
        tap_trace!(
            "#{seq}   no capture subclass: cancelled instead, which returned {}",
            cancelled.as_bool()
        );
        return FinishedComposition::default();
    };
    // The input method sends its messages to the window from inside this
    // call; winit handles them as they come and holds the events they make
    // until the application is done with the one it is handling.
    let completed = unsafe { ImmNotifyIME(himc, NI_COMPOSITIONSTR, CPS_COMPLETE, 0) };
    if tracing {
        tap_trace!(
            "#{seq}   complete returned {}; now comp={} result={}",
            completed.as_bool(),
            composition_string(himc, GCS_COMPSTR),
            composition_string(himc, GCS_RESULTSTR)
        );
    }
    let left = capture.left_composing();
    if let Some(left) = &left {
        let cancelled = unsafe { ImmNotifyIME(himc, NI_COMPOSITIONSTR, CPS_CANCEL, 0) };
        tap_trace!(
            "#{seq}   still composing {left:?}: cancel returned {}",
            cancelled.as_bool()
        );
    }
    let completion = capture.finish();
    let finished = FinishedComposition {
        committed: completion.committed(left.as_deref()),
        late_commits: completion.winit_commits().to_vec(),
    };
    tap_trace!(
        "#{seq}   the input method committed {:?}; winit commits {:?} after the handler",
        finished.committed,
        finished.late_commits
    );
    finished
}

/// The capture subclass on the window being completed, and the completion it
/// feeds, for as long as it lives (a panic included).
struct Capture {
    hwnd: HWND,
}

impl Capture {
    /// Start capturing `hwnd`'s messages. `None` when a capture is already
    /// running on this thread, or the subclass could not be installed.
    fn install(hwnd: HWND) -> Option<Self> {
        let started = CAPTURE
            .try_with(|slot| match slot.try_borrow_mut() {
                Ok(mut slot) if slot.is_none() => {
                    *slot = Some((hwnd, ImmCompletion::new()));
                    true
                }
                _ => false,
            })
            .unwrap_or(false);
        if !started {
            return None;
        }
        // Installed last, so it is called first: before the trace tap, the
        // other subclasses and winit.
        let installed =
            unsafe { SetWindowSubclass(hwnd, Some(capture_proc), CAPTURE_SUBCLASS_ID, 0) };
        if !installed.as_bool() {
            Self::clear();
            return None;
        }
        Some(Self { hwnd })
    }

    /// See [`ImmCompletion::left_composing`].
    fn left_composing(&self) -> Option<String> {
        CAPTURE
            .try_with(|slot| {
                let slot = slot.try_borrow().ok()?;
                let (_, completion) = slot.as_ref()?;
                completion.left_composing().map(str::to_owned)
            })
            .ok()
            .flatten()
    }

    /// Stop capturing, and hand over what was captured.
    fn finish(self) -> ImmCompletion {
        let completion = CAPTURE
            .try_with(|slot| {
                let mut slot = slot.try_borrow_mut().ok()?;
                slot.take().map(|(_, completion)| completion)
            })
            .ok()
            .flatten();
        drop(self);
        completion.unwrap_or_default()
    }

    fn clear() {
        let _ = CAPTURE.try_with(|slot| {
            if let Ok(mut slot) = slot.try_borrow_mut() {
                *slot = None;
            }
        });
    }
}

impl Drop for Capture {
    fn drop(&mut self) {
        // Fails harmlessly when the window is already gone (the procedure
        // removed itself at `WM_NCDESTROY`).
        unsafe {
            let _ = RemoveWindowSubclass(self.hwnd, Some(capture_proc), CAPTURE_SUBCLASS_ID);
        }
        Self::clear();
    }
}

/// Shows the window's composition messages to the completion being
/// captured, then passes every message on, unconditionally: what winit
/// receives is unchanged.
unsafe extern "system" fn capture_proc(
    hwnd: HWND,
    msg: u32,
    wparam: WPARAM,
    lparam: LPARAM,
    uid: usize,
    _dw_ref_data: usize,
) -> LRESULT {
    if matches!(msg, WM_IME_COMPOSITION | WM_IME_ENDCOMPOSITION) {
        // No panic may unwind into user32.
        let _ = catch_unwind(AssertUnwindSafe(|| capture_message(hwnd, msg, lparam)));
    }
    if msg == WM_NCDESTROY {
        unsafe {
            let _ = RemoveWindowSubclass(hwnd, Some(capture_proc), uid);
        }
    }
    unsafe { DefSubclassProc(hwnd, msg, wparam, lparam) }
}

/// Show one composition message of `hwnd` to the completion, with the input
/// context's strings read as winit is about to read them. Reading does not
/// consume them, and calls nothing that can deliver a message.
fn capture_message(hwnd: HWND, msg: u32, lparam: LPARAM) {
    let capturing = CAPTURE
        .try_with(|slot| {
            slot.try_borrow()
                .is_ok_and(|slot| slot.as_ref().is_some_and(|(window, _)| *window == hwnd))
        })
        .unwrap_or(false);
    if !capturing {
        return;
    }
    let himc = unsafe { ImmGetContext(hwnd) };
    // winit reads from the same context; with none, every read fails and it
    // does nothing.
    let read = |which| {
        (!himc.is_invalid())
            .then(|| winit_string(himc, which))
            .flatten()
    };
    let message = if msg == WM_IME_COMPOSITION {
        let flags = lparam.0 as u32;
        ImmMessage::Composition {
            flags,
            result: (flags & imm_completion::GCS_RESULTSTR != 0)
                .then(|| read(GCS_RESULTSTR))
                .flatten(),
            composition: (flags & imm_completion::GCS_COMPSTR != 0)
                .then(|| read(GCS_COMPSTR))
                .flatten(),
        }
    } else {
        ImmMessage::End {
            result: read(GCS_RESULTSTR),
        }
    };
    if !himc.is_invalid() {
        unsafe {
            let _ = ImmReleaseContext(hwnd, himc);
        }
    }
    if super::trace_enabled() {
        let seq = next_sequence();
        match &message {
            ImmMessage::Composition {
                flags,
                result,
                composition,
            } => tap_trace!(
                "#{seq} capture: WM_IME_COMPOSITION flags={flags:#x} result={result:?} comp={composition:?}"
            ),
            ImmMessage::End { result } => {
                tap_trace!("#{seq} capture: WM_IME_ENDCOMPOSITION result={result:?}")
            }
        }
    }
    let _ = CAPTURE.try_with(|slot| {
        if let Ok(mut slot) = slot.try_borrow_mut()
            && let Some((_, completion)) = slot.as_mut()
        {
            completion.message(&message);
        }
    });
}

/// One of an input context's strings as winit reads it
/// (`ImeContext::get_composition_string`): empty when the context holds
/// none, `None` on an error and for an odd byte count or UTF-16 that is not
/// valid, which winit gives up on.
fn winit_string(himc: HIMC, which: IME_COMPOSITION_STRING) -> Option<String> {
    let bytes = unsafe { ImmGetCompositionStringW(himc, which, None, 0) };
    if bytes < 0 {
        return None;
    }
    if bytes == 0 {
        return Some(String::new());
    }
    let mut units = vec![0u16; (bytes as usize).div_ceil(2)];
    let read = unsafe {
        ImmGetCompositionStringW(himc, which, Some(units.as_mut_ptr().cast()), bytes as u32)
    };
    if read < 0 || read % 2 != 0 {
        return None;
    }
    units.truncate(read as usize / 2);
    String::from_utf16(&units).ok()
}

#[cfg(test)]
mod tests {
    use std::ops::Range;

    use super::*;
    use teksilo_canvas::{Point, Rect, SizeProposal};
    use teksilo_core::text_input_document::{FirstLineRect, Utf16Index};
    use teksilo_core::text_surface::TextSurface;
    use teksilo_core::{BuildContext, EventContext, HandlerSet, LayoutContext, LayoutResponse};
    use teksilo_core::{Widget, WidgetTree};
    use windows::Win32::UI::WindowsAndMessaging::{
        CreateWindowExW, DefWindowProcW, DestroyWindow, RegisterClassW, SendMessageW,
        WINDOW_EX_STYLE, WNDCLASSW, WS_OVERLAPPED,
    };
    use windows::core::PCWSTR;

    unsafe extern "system" fn plain_proc(
        hwnd: HWND,
        msg: u32,
        wparam: WPARAM,
        lparam: LPARAM,
    ) -> LRESULT {
        unsafe { DefWindowProcW(hwnd, msg, wparam, lparam) }
    }

    /// A hidden window of this thread, which nothing else knows of.
    fn hidden_window() -> HWND {
        unsafe {
            let instance = GetModuleHandleW(PCWSTR::null()).expect("this module");
            let class = w!("TeksiloImmCompletionTest");
            let wc = WNDCLASSW {
                lpfnWndProc: Some(plain_proc),
                hInstance: instance.into(),
                lpszClassName: class,
                ..Default::default()
            };
            // A second registration fails harmlessly: the first one stands.
            RegisterClassW(&wc);
            CreateWindowExW(
                WINDOW_EX_STYLE(0),
                class,
                w!("imm completion"),
                WS_OVERLAPPED,
                0,
                0,
                0,
                0,
                None,
                None,
                Some(instance.into()),
                None,
            )
            .expect("a hidden window")
        }
    }

    fn send(hwnd: HWND, msg: u32, lparam: u32) {
        unsafe {
            let _ = SendMessageW(hwnd, msg, Some(WPARAM(0)), Some(LPARAM(lparam as isize)));
        }
    }

    /// The capture sees the composition messages sent to its window while it
    /// is installed, with the input context's strings read as winit reads
    /// them, and is gone once it has handed over what it saw.
    #[test]
    fn the_capture_sees_the_messages_sent_while_it_is_installed() {
        let hwnd = hidden_window();
        let capture = Capture::install(hwnd).expect("the capture is installed");
        assert!(Capture::install(hwnd).is_none(), "one capture at a time");
        assert_eq!(
            capture.left_composing().as_deref(),
            Some(""),
            "nothing sent yet: winit would still compose"
        );
        send(hwnd, WM_IME_COMPOSITION, GCS_RESULTSTR.0);
        send(hwnd, WM_IME_ENDCOMPOSITION, 0);
        assert_eq!(capture.left_composing(), None, "the end was seen");
        let completion = capture.finish();
        // An input context with no composition holds an empty result, which
        // winit commits and the field does not keep. With no context, winit
        // reads nothing.
        let has_context = unsafe {
            let himc = ImmGetContext(hwnd);
            let valid = !himc.is_invalid();
            if valid {
                let _ = ImmReleaseContext(hwnd, himc);
            }
            valid
        };
        let expected: &[&str] = if has_context { &[""] } else { &[] };
        assert_eq!(completion.winit_commits(), expected);
        assert_eq!(completion.committed(None), None);

        // The subclass went with the capture: a completion left in the slot by
        // hand hears nothing of a message sent now.
        CAPTURE.with_borrow_mut(|slot| *slot = Some((hwnd, ImmCompletion::new())));
        send(hwnd, WM_IME_ENDCOMPOSITION, 0);
        let heard = CAPTURE.with_borrow_mut(|slot| slot.take());
        assert_eq!(
            heard.map(|(_, completion)| completion.left_composing().map(str::to_owned)),
            Some(Some(String::new())),
            "no subclass fed it"
        );
        unsafe {
            let _ = DestroyWindow(hwnd);
        }
    }

    // -- The input method's requests --------------------------------------

    /// Reconversion is not answered: it goes on to winit, which answers
    /// nothing, and the document is not read for it.
    #[test]
    fn reconversion_is_passed_on() {
        let window_id = TeksiloWindowId::new(0xFE_0008);
        let document = line("abc", 1..2);
        let (hwnd, _tree) = window_with(document.clone(), window_id);
        let mut buffer = reconvert_buffer(64);
        for command in [IMR_RECONVERTSTRING, IMR_CONFIRMRECONVERTSTRING] {
            assert_eq!(request(hwnd, command, 0), 0);
            assert_eq!(request(hwnd, command, buffer.as_mut_ptr() as isize), 0);
        }
        assert_eq!(document.reads.get(), 0);
        assert_eq!(
            request(hwnd, IMR_DOCUMENTFEED, 0),
            32 + 6,
            "the document feed is answered"
        );
        detach(window_id);
        unsafe {
            let _ = DestroyWindow(hwnd);
        }
    }

    /// One line of text, every character 10 wide and 20 tall, the text at
    /// (5, 7) in the window. Busy while `busy` is set. With `pending` set it
    /// holds typing not yet inserted, which a read inserts first, as the
    /// framework's widgets do (counted in `insertions`, the change a
    /// callback would report).
    #[derive(Debug)]
    struct Line {
        text: String,
        selection: Range<usize>,
        busy: Cell<bool>,
        pending: Cell<bool>,
        /// How many reads it answered.
        reads: Cell<usize>,
        /// How many times a read inserted the pending typing.
        insertions: Cell<usize>,
    }

    impl Line {
        fn read(&self) -> Option<()> {
            if self.busy.get() {
                return None;
            }
            if self.pending.replace(false) {
                self.insertions.set(self.insertions.get() + 1);
            }
            self.reads.set(self.reads.get() + 1);
            Some(())
        }
        fn len(&self) -> usize {
            self.text.chars().count()
        }
    }

    impl TextInputDocument for Line {
        fn is_available(&self) -> bool {
            !self.busy.get() && !self.pending.get()
        }
        fn char_count(&self) -> Option<usize> {
            self.read().map(|()| self.len())
        }
        fn text_in(&self, range: Range<usize>) -> Option<String> {
            self.read()?;
            let end = range.end.min(self.len());
            let start = range.start.min(end);
            Some(self.text.chars().skip(start).take(end - start).collect())
        }
        fn selection(&self) -> Option<Range<usize>> {
            self.read().map(|()| self.selection.clone())
        }
        fn caret(&self) -> Option<usize> {
            self.read().map(|()| self.selection.end)
        }
        fn composition_range(&self) -> Option<Range<usize>> {
            None
        }
        fn first_line_rect(&self, range: Range<usize>) -> Option<FirstLineRect> {
            self.read()?;
            let end = range.end.min(self.len());
            let start = range.start.min(end);
            Some(FirstLineRect {
                rect: Rect::new(
                    5.0 + start as f32 * 10.0,
                    7.0,
                    ((end - start) as f32 * 10.0).max(1.0),
                    20.0,
                ),
                covered: start..end,
            })
        }
        fn offset_at_point(&self, _: Point) -> Option<usize> {
            None
        }
        fn visible_text_rect(&self) -> Option<Rect> {
            self.read().map(|()| Rect::new(5.0, 7.0, 300.0, 20.0))
        }
        fn is_editable(&self) -> bool {
            !self.busy.get()
        }
        fn is_secure(&self) -> bool {
            self.busy.get()
        }
        fn writing_tools_allowed(&self) -> bool {
            false
        }
        fn utf16_index(&self) -> Option<Rc<Utf16Index>> {
            self.read().map(|()| Rc::new(Utf16Index::new(&self.text)))
        }
    }

    impl TextSurface for Line {
        fn can_undo(&self) -> bool {
            false
        }
        fn can_redo(&self) -> bool {
            false
        }
        fn undo(&self) {}
        fn redo(&self) {}
        fn has_selection(&self) -> bool {
            !self.selection.is_empty()
        }
        fn is_read_only(&self) -> bool {
            false
        }
        fn allows_copy(&self) -> bool {
            true
        }
        fn cut(&self, _: &EventContext<'_>) {}
        fn copy(&self, _: &EventContext<'_>) {}
        fn paste(&self, _: &EventContext<'_>) {}
        fn paste_plain(&self, _: &EventContext<'_>) {}
        fn select_all(&self) {}
        fn input_document(&self) -> Option<&dyn TextInputDocument> {
            Some(self)
        }
    }

    /// A focusable widget that registers `line` as its text surface.
    #[derive(Debug)]
    struct Field {
        line: Rc<Line>,
    }

    impl Widget for Field {
        fn build(&mut self, ctx: &mut BuildContext) -> Vec<teksilo_core::WidgetId> {
            ctx.apply_self_handlers(HandlerSet::new().focusable(true));
            ctx.register_text_surface(self.line.clone());
            vec![]
        }
        fn layout_response(&self, proposal: SizeProposal, _: &LayoutContext) -> LayoutResponse {
            proposal.resolve(300.0, 20.0).into()
        }
    }

    /// A hidden window whose focused text field is `line`, with the tap
    /// installed as `window_id`. The tree must outlive the requests.
    fn window_with(line: Rc<Line>, window_id: TeksiloWindowId) -> (HWND, WidgetTree) {
        let hwnd = hidden_window();
        let mut tree = WidgetTree::new();
        let id = tree.add(Field { line });
        tree.layout(SizeProposal::exact(300.0, 20.0));
        tree.focus(id);
        WINDOWS.with_borrow_mut(|windows| windows.insert(window_id, hwnd));
        install_tap(window_id, hwnd, tree.text_surfaces());
        (hwnd, tree)
    }

    fn line(text: &str, selection: Range<usize>) -> Rc<Line> {
        Rc::new(Line {
            text: text.to_owned(),
            selection,
            busy: Cell::new(false),
            pending: Cell::new(false),
            reads: Cell::new(0),
            insertions: Cell::new(0),
        })
    }

    fn request(hwnd: HWND, command: u32, lparam: isize) -> isize {
        unsafe {
            SendMessageW(
                hwnd,
                WM_IME_REQUEST,
                Some(WPARAM(command as usize)),
                Some(LPARAM(lparam)),
            )
        }
        .0
    }

    /// A buffer of `bytes`, aligned for `RECONVERTSTRING`, its `dwSize` set.
    fn reconvert_buffer(bytes: usize) -> Vec<u32> {
        let mut buffer = vec![0u32; bytes.div_ceil(4)];
        buffer[0] = bytes as u32;
        buffer
    }

    /// The string, composition range and target range (UTF-16 units) a
    /// filled `RECONVERTSTRING` carries.
    fn read_back(buffer: &[u32]) -> (String, Range<usize>, Range<usize>) {
        let header = unsafe { buffer.as_ptr().cast::<RECONVERTSTRING>().read() };
        let units = unsafe {
            std::slice::from_raw_parts(
                buffer
                    .as_ptr()
                    .cast::<u8>()
                    .add(header.dwStrOffset as usize)
                    .cast::<u16>(),
                header.dwStrLen as usize,
            )
        };
        let comp = header.dwCompStrOffset as usize / 2;
        let target = header.dwTargetStrOffset as usize / 2;
        (
            String::from_utf16(units).expect("UTF-16"),
            comp..comp + header.dwCompStrLen as usize,
            target..target + header.dwTargetStrLen as usize,
        )
    }

    /// The text around the composition, or around the selection with an
    /// empty composition string at its start: written where the input method
    /// says, and refused when its buffer is too small.
    #[test]
    fn the_document_feed_is_written_and_a_buffer_too_small_is_refused() {
        let window_id = TeksiloWindowId::new(0xFE_0002);
        let (hwnd, _tree) = window_with(line("abc", 1..2), window_id);
        assert_eq!(
            request(hwnd, IMR_DOCUMENTFEED, 0),
            38,
            "the size, asked first"
        );
        let mut small = reconvert_buffer(32 + 2);
        assert_eq!(
            request(hwnd, IMR_DOCUMENTFEED, small.as_mut_ptr() as isize),
            0,
            "the string does not fit"
        );
        let mut buffer = reconvert_buffer(32 + 6);
        assert_eq!(
            request(hwnd, IMR_DOCUMENTFEED, buffer.as_mut_ptr() as isize),
            38
        );
        assert_eq!(read_back(&buffer), ("abc".to_owned(), 1..1, 1..2));
        detach(window_id);
        unsafe {
            let _ = DestroyWindow(hwnd);
        }
    }

    #[test]
    fn a_character_position_is_on_the_screen() {
        let window_id = TeksiloWindowId::new(0xFE_0003);
        let (hwnd, _tree) = window_with(line("abcdef", 2..2), window_id);
        let mut position = IMECHARPOSITION {
            dwSize: size_of::<IMECHARPOSITION>() as u32,
            dwCharPos: 0,
            ..Default::default()
        };
        assert_eq!(
            request(
                hwnd,
                IMR_QUERYCHARPOSITION,
                std::ptr::from_mut(&mut position) as isize
            ),
            1
        );
        let scale = unsafe { GetDpiForWindow(hwnd) } as f32 / 96.0;
        let expected = to_screen(hwnd, 25.0, 7.0, scale);
        assert_eq!((position.pt.x, position.pt.y), (expected.x, expected.y));
        assert_eq!(position.cLineHeight, (20.0 * scale).round() as u32);
        let corner = to_screen(hwnd, 5.0, 7.0, scale);
        assert_eq!(
            (position.rcDocument.left, position.rcDocument.top),
            (corner.x, corner.y)
        );
        position.dwCharPos = 1;
        assert_eq!(
            request(
                hwnd,
                IMR_QUERYCHARPOSITION,
                std::ptr::from_mut(&mut position) as isize
            ),
            0,
            "past the (empty) selection: passed on, and winit answers nothing"
        );
        detach(window_id);
        unsafe {
            let _ = DestroyWindow(hwnd);
        }
    }

    /// A widget in the middle of its own work: the request goes on to winit
    /// (here `DefWindowProc`, which answers 0), and the document is not read.
    #[test]
    fn a_busy_document_is_not_read_and_the_request_goes_on() {
        let window_id = TeksiloWindowId::new(0xFE_0004);
        let document = line("abc", 0..0);
        let (hwnd, _tree) = window_with(document.clone(), window_id);
        document.busy.set(true);
        let mut buffer = reconvert_buffer(64);
        for command in [IMR_QUERYCHARPOSITION, IMR_DOCUMENTFEED] {
            assert_eq!(request(hwnd, command, 0), 0);
            assert_eq!(request(hwnd, command, buffer.as_mut_ptr() as isize), 0);
        }
        assert_eq!(document.reads.get(), 0, "only the probe was asked");

        document.busy.set(false);
        assert_eq!(
            request(hwnd, IMR_DOCUMENTFEED, 0),
            32 + 6,
            "an available document answers"
        );
        detach(window_id);
        unsafe {
            let _ = DestroyWindow(hwnd);
        }
    }

    /// Typing not yet inserted: a read would insert it and run the
    /// application's change callbacks ahead of winit, so the request goes on
    /// to winit unanswered, and the typing stays where it was.
    #[test]
    fn a_request_does_not_insert_typing_not_yet_inserted() {
        let window_id = TeksiloWindowId::new(0xFE_0006);
        let document = line("abc", 1..1);
        let (hwnd, _tree) = window_with(document.clone(), window_id);
        document.pending.set(true);
        let mut position = IMECHARPOSITION {
            dwSize: size_of::<IMECHARPOSITION>() as u32,
            ..Default::default()
        };
        let mut buffer = reconvert_buffer(64);
        assert_eq!(
            request(
                hwnd,
                IMR_QUERYCHARPOSITION,
                std::ptr::from_mut(&mut position) as isize
            ),
            0
        );
        assert_eq!(request(hwnd, IMR_DOCUMENTFEED, 0), 0);
        assert_eq!(
            request(hwnd, IMR_DOCUMENTFEED, buffer.as_mut_ptr() as isize),
            0
        );
        assert_eq!(document.insertions.get(), 0, "the typing is not inserted");
        assert_eq!(document.reads.get(), 0, "nor anything read");
        assert!(document.pending.get());
        detach(window_id);
        unsafe {
            let _ = DestroyWindow(hwnd);
        }
    }

    /// An IMM32 input method's layout handle has device `0xE0xx`; a plain
    /// keyboard layout, under which a TSF text service runs, does not.
    #[test]
    fn a_legacy_input_method_is_told_by_its_layout_handle() {
        assert!(is_legacy_input_method(0xE001_0411));
        assert!(!is_legacy_input_method(0x0411_0411), "Japanese, a TIP");
        assert!(!is_legacy_input_method(0x040C_040C), "French");
        assert!(
            !is_legacy_input_method(0xF002_0409),
            "Dvorak, a layout variant"
        );
    }
}