summaryrefslogtreecommitdiffstats
path: root/win/tkWinAccessibility.c
blob: 557f437f4bc29af9400c9669bcda376edd74bcaa (plain)
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
/*
 * tkWinAccessibility.c
 *
 *    This file implements the platform-native Microsoft Active
 *    Accessibility API for Tk on Windows and supports UI Automation
 *    through the MSAA-UIA bridge provided by Windows.
 *
 * Copyright (c) 2024-2025 Kevin Walzer
 *
 * See the file "license.terms" for information on usage and redistribution of
 * this file, and for a DISCLAIMER OF ALL WARRANTIES.
 *
 */

#include <tcl.h>
#include <tk.h>
#include "tkWinInt.h"
#include <oleacc.h>
#include <oaidl.h>
#include <oleauto.h>
#include <UIAutomation.h>

#include <initguid.h>
#include <tlhelp32.h>
#include <tchar.h>
#include <windows.h>
#include <stdarg.h>
#include <stdio.h>
#include <limits.h>

/*
 *----------------------------------------------------------------------
 *
 * Data definitions for MSAA-Tk integration.
 *
 *----------------------------------------------------------------------
 */

/* Define global lock constants. */
static CRITICAL_SECTION TkGlobalLock;
static INIT_ONCE TkInitOnce = INIT_ONCE_STATIC_INIT;
#define TkGlobalLock()   EnterCriticalSection(&TkGlobalLock)
#define TkGlobalUnlock() LeaveCriticalSection(&TkGlobalLock)

/* TkRootAccessible structure. */
typedef struct TkRootAccessible {
    IAccessibleVtbl *lpVtbl;
    Tk_Window win;
    Tk_Window toplevel;
    Tcl_Interp *interp;
    HWND hwnd;
    char *pathName;
    IAccessible **children;
    int numChildren;
    LONG refCount;
} TkRootAccessible;

/*
 * Map script-level roles to C roles for MSAA.
 */

struct WinRoleMap {
    const char *tkrole;
    LONG winrole;
};

const struct WinRoleMap roleMap[] = {
    {"Button", ROLE_SYSTEM_PUSHBUTTON},
    {"Canvas", ROLE_SYSTEM_CLIENT},
    {"Checkbutton", ROLE_SYSTEM_CHECKBUTTON},
    {"Combobox", ROLE_SYSTEM_COMBOBOX},
    {"Entry", ROLE_SYSTEM_TEXT},
    {"Label", ROLE_SYSTEM_STATICTEXT},
    {"Listbox", ROLE_SYSTEM_LIST},
    {"Notebook", ROLE_SYSTEM_PAGETABLIST},
    {"Progressbar", ROLE_SYSTEM_PROGRESSBAR},
    {"Radiobutton", ROLE_SYSTEM_RADIOBUTTON},
    {"Scale", ROLE_SYSTEM_SLIDER},
    {"Scrollbar", ROLE_SYSTEM_SCROLLBAR},
    {"Spinbox", ROLE_SYSTEM_SPINBUTTON},
    {"Table", ROLE_SYSTEM_TABLE},
    {"Text", ROLE_SYSTEM_TEXT},
    {"Tree", ROLE_SYSTEM_OUTLINE},
    {"Toggleswitch", ROLE_SYSTEM_CHECKBUTTON},
    {NULL, 0}
};

/* Hash table for managing accessibility attributes. */
extern Tcl_HashTable *TkAccessibilityObject;

/* Hash tables for linking Tk windows to accessibility object and HWND. */
static Tcl_HashTable *tkAccessibleTable;
static bool tkAccessibleTableInitialized = false;
static Tcl_HashTable *toplevelChildTables = NULL;

/* Data structures for managing execution on main thread. */
typedef void (*MainThreadFunc)(int num_args, void** args);

typedef struct {
    Tcl_Event header;
    MainThreadFunc func;
    int num_args;
    void* args[6];
    HANDLE doneEvent;
} MainThreadSyncEvent;

/*
 * Need main thread, main interp, and command struct
 * for accessible operations on main thread
 * defined here.
 */
static Tcl_ThreadId mainThreadId;
static volatile HRESULT mainThreadResult = E_FAIL;

typedef struct {
    Tcl_Event header;
    char *command;
    Tk_Window win;
} ActionEvent;

/*
 *----------------------------------------------------------------------
 *
 * Prototypes for toplevel MSAA objects. These will always run on background
 * threads. Any calls into Tcl/Tk functions must be guarded with a global
 * thread lock or explicitly pushed to the main thread because Tk is not
 * thread safe.
 *
 *----------------------------------------------------------------------
 */

/* Protoypes of glue functions to the IAccessible COM API - toplevels. */
static HRESULT STDMETHODCALLTYPE TkRootAccessible_QueryInterface(IAccessible *this, REFIID riid, void **ppvObject);
static ULONG STDMETHODCALLTYPE TkRootAccessible_AddRef(IAccessible *this);
static ULONG STDMETHODCALLTYPE TkRootAccessible_Release(IAccessible *this);
static HRESULT STDMETHODCALLTYPE TkRootAccessible_GetTypeInfoCount(IAccessible *this, UINT *pctinfo);
static HRESULT STDMETHODCALLTYPE TkRootAccessible_GetTypeInfo(IAccessible *this, UINT iTInfo, LCID lcid, ITypeInfo **ppTInfo);
static HRESULT STDMETHODCALLTYPE TkRootAccessible_GetIDsOfNames(IAccessible *this, REFIID riid, LPOLESTR *rgszNames, UINT cNames, LCID lcid, DISPID *rgDispId);
static HRESULT STDMETHODCALLTYPE TkRootAccessible_Invoke(IAccessible *this, DISPID dispIdMember, REFIID riid, LCID lcid, WORD wFlags, DISPPARAMS *pDispParams, VARIANT *pVarResult, EXCEPINFO *pExcepInfo, UINT *puArgErr);

/* Prototypes of empty stub functions required by MSAA-toplevels. */
HRESULT STDMETHODCALLTYPE TkRootAccessible_get_accHelpTopic(IAccessible *this, BSTR *pszHelpFile, VARIANT varChild, long *pidTopic);
HRESULT STDMETHODCALLTYPE TkRootAccessible_get_accKeyboardShortcut(IAccessible *this, VARIANT varChild, BSTR *pszKeyboardShortcut);
HRESULT STDMETHODCALLTYPE TkRootAccessible_get_accSelection(IAccessible *this, VARIANT *pvarChildren);
HRESULT STDMETHODCALLTYPE TkRootAccessible_accNavigate(IAccessible *this, long navDir, VARIANT varStart, VARIANT *pvarEndUpAt);
HRESULT STDMETHODCALLTYPE TkRootAccessible_accHitTest(IAccessible *this, long xLeft, long yTop, VARIANT *pvarChild);
HRESULT STDMETHODCALLTYPE TkRootAccessible_put_accName(IAccessible *this, VARIANT varChild, BSTR szName);
HRESULT STDMETHODCALLTYPE TkRootAccessible_put_accValue(IAccessible *this, VARIANT varChild, BSTR szValue);

/* Prototypes of the MSAA functions that actually implement accessibility for Tk widgets on Windows - toplevels. */
static HRESULT STDMETHODCALLTYPE TkRootAccessible_get_accName(IAccessible *this, VARIANT varChild, BSTR *pszName);
static HRESULT STDMETHODCALLTYPE TkRootAccessible_get_accRole(IAccessible *this, VARIANT varChild, VARIANT *pvarRole);
static HRESULT STDMETHODCALLTYPE TkRootAccessible_get_accState(IAccessible *this, VARIANT varChild, VARIANT *pvarState);
static HRESULT STDMETHODCALLTYPE TkRootAccessible_get_accValue(IAccessible *this, VARIANT varChild, BSTR *pszValue);
static HRESULT STDMETHODCALLTYPE TkRootAccessible_get_accParent(IAccessible *this, IDispatch **ppdispParent);
static HRESULT STDMETHODCALLTYPE TkRootAccessible_get_accChildCount(IAccessible *this, LONG *pcChildren);
static HRESULT STDMETHODCALLTYPE TkRootAccessible_get_accChild(IAccessible *this, VARIANT varChild, IDispatch **ppdispChild);
static HRESULT STDMETHODCALLTYPE TkRootAccessible_accLocation(IAccessible *this, LONG *pxLeft, LONG *pyTop, LONG *pcxWidth, LONG *pcyHeight, VARIANT varChild);
static HRESULT STDMETHODCALLTYPE TkRootAccessible_accSelect(IAccessible *this, long flags, VARIANT varChild);
static HRESULT STDMETHODCALLTYPE TkRootAccessible_get_accDefaultAction(IAccessible *this, VARIANT varChild, BSTR *pszDefaultAction);
static HRESULT STDMETHODCALLTYPE TkRootAccessible_accDoDefaultAction(IAccessible *this, VARIANT varChild);
static HRESULT STDMETHODCALLTYPE TkRootAccessible_get_accHelp(IAccessible *this, VARIANT varChild, BSTR* pszHelp);
static HRESULT STDMETHODCALLTYPE TkRootAccessible_get_accDescription(IAccessible *this, VARIANT varChild, BSTR *pszDescription);
static HRESULT STDMETHODCALLTYPE TkRootAccessible_get_accFocus(IAccessible *this, VARIANT *pvarChild);

/* VTable for MSAA root accessible. */
static IAccessibleVtbl tkRootAccessibleVtbl = {
    TkRootAccessible_QueryInterface,
    TkRootAccessible_AddRef,
    TkRootAccessible_Release,
    TkRootAccessible_GetTypeInfoCount,
    TkRootAccessible_GetTypeInfo,
    TkRootAccessible_GetIDsOfNames,
    TkRootAccessible_Invoke,
    TkRootAccessible_get_accParent,
    TkRootAccessible_get_accChildCount,
    TkRootAccessible_get_accChild,
    TkRootAccessible_get_accName,
    TkRootAccessible_get_accValue,
    TkRootAccessible_get_accDescription,
    TkRootAccessible_get_accRole,
    TkRootAccessible_get_accState,
    TkRootAccessible_get_accHelp,
    TkRootAccessible_get_accHelpTopic,
    TkRootAccessible_get_accKeyboardShortcut,
    TkRootAccessible_get_accFocus,
    TkRootAccessible_get_accSelection,
    TkRootAccessible_get_accDefaultAction,
    TkRootAccessible_accSelect,
    TkRootAccessible_accLocation,
    TkRootAccessible_accNavigate,
    TkRootAccessible_accHitTest,
    TkRootAccessible_accDoDefaultAction,
    TkRootAccessible_put_accName,
    TkRootAccessible_put_accValue
};

/*
 *----------------------------------------------------------------------
 *
 * Prototypes for child widgets using MSAA childId. These will be called
 * from a global lock or explicitly run on the main thread.
 *
 *----------------------------------------------------------------------
 */

static HRESULT TkAccRole(Tk_Window win, VARIANT *pvarRole);
static void ComputeAndCacheCheckedState(Tk_Window win, Tcl_Interp *interp);
static HRESULT TkAccState(Tk_Window win, VARIANT *pvarState);
static void TkAccFocus(int num_args, void **args);
static HRESULT TkAccDescription(Tk_Window win, BSTR *pDesc);
static HRESULT TkAccValue(Tk_Window win, BSTR *pValue);
static void TkDoDefaultAction(int num_args, void **args);
static HRESULT TkAccHelp(Tk_Window win, BSTR *pszHelp);
static int TkAccChildCount(Tk_Window win);
static int ActionEventProc(Tcl_Event *ev, int flags);
static HRESULT TkAccChild_GetRect(Tcl_Interp *interp, char *path, RECT *rect);


/*
 *----------------------------------------------------------------------
 *
 * Prototypes for functions to manage threading activities.
 *
 *----------------------------------------------------------------------
 */
int ExecuteOnMainThreadSync(Tcl_Event *ev, int flags);
void RunOnMainThreadSync(MainThreadFunc func, int num_args, ...);
void HandleWMGetObjectOnMainThread(int num_args, void **args);
BOOL CALLBACK InitGlobalLockOnce(PINIT_ONCE InitOnce, PVOID param, PVOID *Context);
void EnsureGlobalLockInitialized(void);

/*
 *----------------------------------------------------------------------
 *
 * Prototypes of Tk functions that support MSAA integration
 * and help implement the script-level API.
 *
 *----------------------------------------------------------------------
 */

void InitTkAccessibleTable(void);
void InitChildIdTable(void);
void ClearChildIdTableForToplevel(Tk_Window toplevel);
TkRootAccessible *GetTkAccessibleForWindow(Tk_Window win);
static TkRootAccessible *CreateRootAccessible(Tcl_Interp *interp, HWND hwnd, const char *pathName);
static void SetChildIdForTkWindow(Tk_Window win, int id, Tcl_HashTable *childIdTable);
static int GetChildIdForTkWindow(Tk_Window win, Tcl_HashTable *childIdTable);
Tk_Window GetToplevelOfWidget(Tk_Window tkwin);
static Tcl_HashTable *GetChildIdTableForToplevel(Tk_Window toplevel);
Tk_Window GetTkWindowForChildId(int id, Tk_Window toplevel);
int IsScreenReaderRunning(void *clientData, Tcl_Interp *interp, int argc, Tcl_Obj *const argv[]);
static int EmitSelectionChanged(void *clientData,Tcl_Interp *ip, int objc, Tcl_Obj *const objv[]);
static int EmitFocusChanged(void *cd, Tcl_Interp *interp, int objc, Tcl_Obj *const objv[]);
void TkRootAccessible_RegisterForCleanup(Tk_Window tkwin, void *tkAccessible);
static void TkRootAccessible_DestroyHandler(void *clientData, XEvent *eventPtr);
static void AssignChildIdsRecursive(Tk_Window win, int *nextId, Tcl_Interp *interp, Tk_Window toplevel);
void InitAccessibilityMainThread(void);
int TkRootAccessibleObjCmd(void *clientData, Tcl_Interp *interp, int objc, Tcl_Obj *const objv[]);
int TkWinAccessiblity_Init(Tcl_Interp *interp);

/*
 *----------------------------------------------------------------------
 *
 * Glue functions to the IAccessible COM API - toplevels.
 *
 *----------------------------------------------------------------------
 */

/* Empty stub functions required by MSAA. */
HRESULT STDMETHODCALLTYPE TkRootAccessible_get_accHelpTopic(
    TCL_UNUSED(IAccessible *), /* this */
    TCL_UNUSED(BSTR *), /* pszHelpFile */
    TCL_UNUSED(VARIANT), /* varChild */
    TCL_UNUSED(long *)) /* pidTopic */
{
    return E_NOTIMPL;
}

HRESULT STDMETHODCALLTYPE TkRootAccessible_get_accKeyboardShortcut(
    TCL_UNUSED(IAccessible *), /* this */
    TCL_UNUSED(VARIANT), /* varChild */
    TCL_UNUSED(BSTR *)) /* pszKeyboardShortcut */
{
    return E_NOTIMPL;
}

HRESULT STDMETHODCALLTYPE TkRootAccessible_get_accSelection(
    TCL_UNUSED(IAccessible *), /* this */
    TCL_UNUSED(VARIANT *)) /*pvarChildren */
{
    return E_NOTIMPL;
}

HRESULT STDMETHODCALLTYPE TkRootAccessible_accNavigate(
    TCL_UNUSED(IAccessible *), /* this */
    TCL_UNUSED(long), /* navDir */
    TCL_UNUSED(VARIANT), /* varStart */
    TCL_UNUSED(VARIANT *)) /* pvarEndUpAt */
{
    return E_NOTIMPL;
}

HRESULT STDMETHODCALLTYPE TkRootAccessible_accHitTest(
    TCL_UNUSED(IAccessible *), /* this */
    TCL_UNUSED(long), /* xLeft */
    TCL_UNUSED(long), /* yTop */
    TCL_UNUSED(VARIANT *)) /* pvarChild */
{
    return E_NOTIMPL;
}

HRESULT STDMETHODCALLTYPE TkRootAccessible_put_accName(
    TCL_UNUSED(IAccessible *), /* this */
    TCL_UNUSED(VARIANT), /* varChild */
    TCL_UNUSED(BSTR)) /* szName */
{
    return E_NOTIMPL;
}

HRESULT STDMETHODCALLTYPE TkRootAccessible_put_accValue(
    TCL_UNUSED(IAccessible *), /* this */
    TCL_UNUSED(VARIANT), /* varChild */
    TCL_UNUSED(BSTR)) /* szValue */
{
    return E_NOTIMPL;
}

/*
 *----------------------------------------------------------------------
 * Begin active MSAA functions. These are run on a background thread
 * and if they need to call into Tk to read data, a global thread lock
 * will be applied.
 *----------------------------------------------------------------------
 */

static HRESULT STDMETHODCALLTYPE TkRootAccessible_QueryInterface(
    IAccessible *this,
    REFIID riid,
    void **ppvObject)
{
    if (!ppvObject) return E_INVALIDARG;
    if (IsEqualIID(riid, &IID_IUnknown) || IsEqualIID(riid, &IID_IDispatch) || IsEqualIID(riid, &IID_IAccessible)) {
	*ppvObject = this;
	TkRootAccessible_AddRef(this);
	return S_OK;
    }
    *ppvObject = NULL;
    return E_NOINTERFACE;
}

/* Function to add memory reference to the MSAA object. */
static ULONG STDMETHODCALLTYPE TkRootAccessible_AddRef(
    IAccessible *this)
{
    if (!this) return E_INVALIDARG;
    TkRootAccessible *tkAccessible = (TkRootAccessible *)this;
    return InterlockedIncrement(&tkAccessible->refCount);
}

/* Function to free the MSAA object. */
static ULONG STDMETHODCALLTYPE TkRootAccessible_Release(
    IAccessible *this)
{
    if (!this) return E_INVALIDARG;
    TkRootAccessible *tkAccessible = (TkRootAccessible *)this;
    ULONG count = InterlockedDecrement(&tkAccessible->refCount);
    if (count == 0) {
	TkGlobalLock();
	if (tkAccessible->win && tkAccessibleTableInitialized) {
	    Tcl_HashEntry *entry = Tcl_FindHashEntry(tkAccessibleTable, tkAccessible->win);
	    if (entry) {
		Tcl_DeleteHashEntry(entry);
	    }
	}
	if (tkAccessible->pathName) {
	    ckfree(tkAccessible->pathName);
	    tkAccessible->pathName = NULL;
	}
	ckfree(tkAccessible);
	TkGlobalUnlock();
    }
    return count;
}

/* The number of type information interfaces provided by the object. */
static HRESULT STDMETHODCALLTYPE TkRootAccessible_GetTypeInfoCount(
    TCL_UNUSED(IAccessible *), /* this */
    UINT *pctinfo)
{
    if (!pctinfo) return E_INVALIDARG;
    *pctinfo = 1;
    return S_OK;
}

/*
 * Retrieves the type information for an object, which can then be used
 * to get the type information for an interface.
 */
static HRESULT STDMETHODCALLTYPE TkRootAccessible_GetTypeInfo(
    TCL_UNUSED(IAccessible *), /* this */
    UINT iTInfo,
    LCID lcid,
    ITypeInfo **ppTInfo)
{
    if (!ppTInfo) return E_INVALIDARG;
    *ppTInfo = NULL;
    if (iTInfo != 0) return DISP_E_BADINDEX;

    ITypeLib *pTypeLib = NULL;
    HRESULT hr = LoadRegTypeLib(&LIBID_Accessibility, 1, 1, lcid, &pTypeLib);
    if (FAILED(hr)) return hr;

    ITypeInfo *pTypeInfo = NULL;
    hr = pTypeLib->lpVtbl->GetTypeInfoOfGuid(pTypeLib, &IID_IAccessible, &pTypeInfo);
    pTypeLib->lpVtbl->Release(pTypeLib);
    if (FAILED(hr)) return hr;

    *ppTInfo = pTypeInfo;
    return S_OK;
}

/*
 * Maps a single member and an optional set of argument names to a
 * corresponding set of integer DISPIDs, which can be used on subsequent calls
 * to Invoke.
 */
static HRESULT STDMETHODCALLTYPE TkRootAccessible_GetIDsOfNames(
    IAccessible *this,
    TCL_UNUSED(REFIID), /* riid */
    LPOLESTR *rgszNames,
    UINT cNames,
    LCID lcid,
    DISPID *rgDispId)
{
    if (!rgszNames || !rgDispId) return E_INVALIDARG;
    ITypeInfo *pTypeInfo = NULL;
    HRESULT hr = TkRootAccessible_GetTypeInfo(this, 0, lcid, &pTypeInfo);
    if (FAILED(hr) || !pTypeInfo) return E_FAIL;

    hr = DispGetIDsOfNames(pTypeInfo, rgszNames, cNames, rgDispId);
    pTypeInfo->lpVtbl->Release(pTypeInfo);
    return hr;
}

/* Provides access to properties and methods exposed by an MSAA object. */
static HRESULT STDMETHODCALLTYPE TkRootAccessible_Invoke(
    IAccessible *this,
    DISPID dispIdMember,
    TCL_UNUSED(REFIID), /* riid */
    TCL_UNUSED(LCID), /* lcid */
    TCL_UNUSED(WORD), /* wFlags */
    TCL_UNUSED(DISPPARAMS *), /* pDispParams */
    VARIANT *pVarResult,
    TCL_UNUSED(EXCEPINFO *), /* pExcepInfo */
    TCL_UNUSED(UINT *)) /* puArgErr */
{
    if (!pVarResult) return E_INVALIDARG;
    VariantInit(pVarResult);

    VARIANT selfVar;
    selfVar.vt = VT_I4;
    selfVar.lVal = CHILDID_SELF;

    switch (dispIdMember) {
    case DISPID_ACC_NAME:
	return TkRootAccessible_get_accName(this, selfVar, &pVarResult->bstrVal);
    case DISPID_ACC_VALUE:
	return TkRootAccessible_get_accValue(this, selfVar, &pVarResult->bstrVal);
    case DISPID_ACC_ROLE:
	return TkRootAccessible_get_accRole(this, selfVar, pVarResult);
    case DISPID_ACC_STATE:
	return TkRootAccessible_get_accState(this, selfVar, pVarResult);
    case DISPID_ACC_DESCRIPTION:
	return TkRootAccessible_get_accDescription(this, selfVar, &pVarResult->bstrVal);
    case DISPID_ACC_HELP:
	return TkRootAccessible_get_accHelp(this, selfVar, &pVarResult->bstrVal);
    case DISPID_ACC_DEFAULTACTION:
	return TkRootAccessible_get_accDefaultAction(this, selfVar, &pVarResult->bstrVal);
    case DISPID_ACC_DODEFAULTACTION:
	return TkRootAccessible_accDoDefaultAction(this, selfVar);
    case DISPID_ACC_FOCUS:
	return TkRootAccessible_get_accFocus(this, pVarResult);
    }
    return S_OK;
}

/*
 * Function to map accessible name to MSAA. We pass the description string
 * to the name property so that we can get correct labeling on both NVDA
 * and Narrator.
 */

static HRESULT STDMETHODCALLTYPE TkRootAccessible_get_accName(
    IAccessible *this,
    VARIANT varChild,
    BSTR *pszName)
{
    if (!pszName) return E_INVALIDARG;
    *pszName = NULL;

    TkGlobalLock();
    TkRootAccessible *tkAccessible = (TkRootAccessible *)this;
    if (!tkAccessible->toplevel) {
	TkGlobalUnlock();
	return E_INVALIDARG;
    }

    /* Toplevel. */
    if (varChild.vt == VT_I4 && varChild.lVal == CHILDID_SELF) {
	HWND hwnd = Tk_GetHWND(Tk_WindowId(tkAccessible->toplevel));
	int wlen = GetWindowTextLengthW(hwnd);
	WCHAR *wbuf = (WCHAR *)ckalloc((wlen + 1) * sizeof(WCHAR));

	/* Read the actual UTF-16 title. */
	if (!GetWindowTextW(hwnd, wbuf, wlen + 1)) {
	    ckfree((char *)wbuf);
	    *pszName = SysAllocString(L"");
	    TkGlobalUnlock();
	    return S_OK;
	}
	*pszName = SysAllocString(wbuf);
	ckfree((char *)wbuf);
	TkGlobalUnlock();
	return S_OK;
    }


    /* Child widgets - return description. */
    if (varChild.vt == VT_I4 && varChild.lVal > 0) {
	Tk_Window child = GetTkWindowForChildId(varChild.lVal, tkAccessible->toplevel);
	if (child) {            
	    HRESULT hr = TkAccDescription(child, pszName);
	    TkGlobalUnlock();
	    return hr;
	}
    }

    TkGlobalUnlock();
    return E_INVALIDARG;
}

/* Function to map accessible role to MSAA. For toplevels, return ROLE_SYSTEM_WINDOW. */
static HRESULT STDMETHODCALLTYPE TkRootAccessible_get_accRole(
    IAccessible *this,
    VARIANT varChild,
    VARIANT *pvarRole)
{
    if (!pvarRole) return E_INVALIDARG;
    if (varChild.vt == VT_I4 && varChild.lVal == CHILDID_SELF) {
	pvarRole->vt = VT_I4;
	pvarRole->lVal = ROLE_SYSTEM_WINDOW;
	return S_OK;
    }

    TkGlobalLock();
    TkRootAccessible *tkAccessible = (TkRootAccessible *)this;
    if (varChild.vt == VT_I4 && varChild.lVal > 0) {
	Tk_Window child = GetTkWindowForChildId(varChild.lVal, tkAccessible->toplevel);
	if (!child) {
	    TkGlobalUnlock();
	    return E_INVALIDARG;
	}
	HRESULT hr = TkAccRole(child, pvarRole);
	TkGlobalUnlock();
	return hr;
    }
    TkGlobalUnlock();
    return E_INVALIDARG;
}

/* Function to map accessible state to MSAA. For toplevel, return STATE_SYSTEM_FOCUSABLE. */
static HRESULT STDMETHODCALLTYPE TkRootAccessible_get_accState(
    IAccessible *this,
    VARIANT varChild,
    VARIANT *pvarState)
{
    if (!pvarState) return E_INVALIDARG;
    if (varChild.vt == VT_I4 && varChild.lVal == CHILDID_SELF) {
	pvarState->vt = VT_I4;
	pvarState->lVal = STATE_SYSTEM_FOCUSABLE;
	return S_OK;
    }

    TkGlobalLock();
    TkRootAccessible *tkAccessible = (TkRootAccessible *)this;
    if (varChild.vt == VT_I4 && varChild.lVal > 0) {
	Tk_Window child = GetTkWindowForChildId(varChild.lVal, tkAccessible->toplevel);
	if (!child) {
	    TkGlobalUnlock();
	    return E_INVALIDARG;
	}
	HRESULT hr = TkAccState(child, pvarState);
	TkGlobalUnlock();
	return hr;
    }
    TkGlobalUnlock();
    return DISP_E_MEMBERNOTFOUND;
}

/* Function to map accessible value to MSAA. For toplevel, return NULL. */
static HRESULT STDMETHODCALLTYPE TkRootAccessible_get_accValue(
    IAccessible *this,
    VARIANT varChild,
    BSTR *pszValue)
{
    if (!pszValue) return E_INVALIDARG;
    if (varChild.vt == VT_I4 && varChild.lVal == CHILDID_SELF) {
	*pszValue = NULL;
	return DISP_E_MEMBERNOTFOUND;
    }

    TkGlobalLock();
    TkRootAccessible *tkAccessible = (TkRootAccessible *)this;
    if (varChild.vt == VT_I4 && varChild.lVal > 0) {
	Tk_Window child = GetTkWindowForChildId(varChild.lVal, tkAccessible->toplevel);
	if (!child) {
	    TkGlobalUnlock();
	    return E_INVALIDARG;
	}
	HRESULT hr = TkAccValue(child, pszValue);
	TkGlobalUnlock();
	return hr;
    }
    TkGlobalUnlock();
    return DISP_E_MEMBERNOTFOUND;
}

/* Function to get accessible parent. For toplevel, return NULL. */
static HRESULT STDMETHODCALLTYPE TkRootAccessible_get_accParent(
    TCL_UNUSED(IAccessible *), /* this */
    IDispatch **ppdispParent)
{
    if (!ppdispParent) return E_INVALIDARG;
    *ppdispParent = NULL;
    return S_OK;
}

/* Function to get number of accessible children to MSAA. */
static HRESULT STDMETHODCALLTYPE TkRootAccessible_get_accChildCount(
    IAccessible *this,
    LONG *pcChildren)
{
    if (!pcChildren) return E_INVALIDARG;
    TkGlobalLock();
    TkRootAccessible *tkAccessible = (TkRootAccessible *)this;
    if (!tkAccessible->toplevel) {
	TkGlobalUnlock();
	*pcChildren = 0;
	return S_FALSE;
    }
    int count = TkAccChildCount(tkAccessible->toplevel);
    TkGlobalUnlock();

    *pcChildren = count < 0 ? 0 : count;
    return S_OK;
}

/* Function to get accessible children to MSAA. */
static HRESULT STDMETHODCALLTYPE TkRootAccessible_get_accChild(
    IAccessible *this,
    VARIANT varChild,
    IDispatch **ppdispChild)
{
    if (!ppdispChild) return E_INVALIDARG;
    *ppdispChild = NULL;
    if (varChild.vt != VT_I4 || varChild.lVal <= 0) return E_INVALIDARG;

    TkGlobalLock();
    TkRootAccessible *tkAccessible = (TkRootAccessible *)this;
    if (!tkAccessible->toplevel) {
	TkGlobalUnlock();
	return E_INVALIDARG;
    }
    ClearChildIdTableForToplevel(tkAccessible->toplevel);
    int nextId = 1;
    AssignChildIdsRecursive(tkAccessible->toplevel, &nextId, tkAccessible->interp, tkAccessible->toplevel);
    Tk_Window childWin = GetTkWindowForChildId(varChild.lVal, tkAccessible->toplevel);
    if (!childWin) {
	TkGlobalUnlock();
	return E_INVALIDARG;
    }
    TkGlobalUnlock();
    return S_OK;
}

/* Function to get accessible frame to MSAA. */
static HRESULT STDMETHODCALLTYPE TkRootAccessible_accLocation(
    IAccessible *this,
    LONG *pxLeft,
    LONG *pyTop,
    LONG *pcxWidth,
    LONG *pcyHeight,
    VARIANT varChild)
{
    if (!pxLeft || !pyTop || !pcxWidth || !pcyHeight) return E_INVALIDARG;
    TkGlobalLock();
    TkRootAccessible *tkAccessible = (TkRootAccessible *)this;
    if (!tkAccessible->toplevel || !tkAccessible->hwnd) {
	TkGlobalUnlock();
	return E_INVALIDARG;
    }
    if (varChild.vt == VT_I4 && varChild.lVal == CHILDID_SELF) {
	RECT clientRect;
	GetClientRect(tkAccessible->hwnd, &clientRect);
	POINT screenCoords = { clientRect.left, clientRect.top };
	MapWindowPoints(tkAccessible->hwnd, HWND_DESKTOP, &screenCoords, 1);
	*pxLeft = screenCoords.x;
	*pyTop = screenCoords.y;
	*pcxWidth = clientRect.right - clientRect.left;
	*pcyHeight = clientRect.bottom - clientRect.top;
	TkGlobalUnlock();
	return S_OK;
    }
    if (varChild.vt == VT_I4 && varChild.lVal > 0) {
	Tk_Window child = GetTkWindowForChildId(varChild.lVal, tkAccessible->toplevel);
	if (!child) {
	    TkGlobalUnlock();
	    return E_INVALIDARG;
	}
	RECT rect = { 0 };
	HRESULT hr = TkAccChild_GetRect(tkAccessible->interp, Tk_PathName(child), &rect);
	if (hr == S_OK) {
	    *pxLeft = rect.left;
	    *pyTop = rect.top;
	    *pcxWidth = rect.right - rect.left;
	    *pcyHeight = rect.bottom - rect.top;
	    TkGlobalUnlock();
	    return S_OK;
	}
    }
    TkGlobalUnlock();
    return E_INVALIDARG;
}

/* Function to set accessible selection on Tk widget. */
static HRESULT STDMETHODCALLTYPE TkRootAccessible_accSelect(
    TCL_UNUSED(IAccessible *), /* this */
    TCL_UNUSED(long), /* flags */
    TCL_UNUSED(VARIANT)) /* varChild */
{
    return E_NOTIMPL;
}

/* Function to return default action for role. */
static HRESULT STDMETHODCALLTYPE TkRootAccessible_get_accDefaultAction(
    IAccessible *this,
    VARIANT varChild,
    BSTR *pszDefaultAction)
{
    if (!pszDefaultAction) return E_INVALIDARG;
    *pszDefaultAction = NULL;
    if (varChild.vt == VT_I4 && varChild.lVal == CHILDID_SELF) return S_FALSE; /* Top-level window has no default action. */

    VARIANT varRole;
    VariantInit(&varRole);
    TkGlobalLock();
    TkRootAccessible *tkAccessible = (TkRootAccessible *)this;
    HRESULT hr = tkAccessible->lpVtbl->get_accRole(this, varChild, &varRole);
    if (FAILED(hr) || varRole.vt != VT_I4) {
	VariantClear(&varRole);
	TkGlobalUnlock();
	return S_FALSE;
    }
    const wchar_t *action = NULL;
    switch (varRole.lVal) {
    case ROLE_SYSTEM_PUSHBUTTON:
    case ROLE_SYSTEM_RADIOBUTTON:
    case ROLE_SYSTEM_CHECKBUTTON:
	action = L"Press";
	break;
    case ROLE_SYSTEM_TEXT:
	action = L"Edit";
	break;
    case ROLE_SYSTEM_OUTLINE:
    case ROLE_SYSTEM_TABLE:
	action = L"Select";
	break;
    default:
	break;
    }
    VariantClear(&varRole);
    if (action) {
	*pszDefaultAction = SysAllocString(action);
	TkGlobalUnlock();
	return S_OK;
    }
    TkGlobalUnlock();
    return S_FALSE;
}


/* Function to get button press to MSAA. */
static HRESULT STDMETHODCALLTYPE TkRootAccessible_accDoDefaultAction(
    TCL_UNUSED(IAccessible *), /* this */
    VARIANT varChild)
{
    if (varChild.vt == VT_I4 && varChild.lVal == CHILDID_SELF) return S_OK;
    if (varChild.vt == VT_I4 && varChild.lVal > 0) {
	mainThreadResult = E_FAIL;
	MainThreadFunc func = (MainThreadFunc)TkDoDefaultAction;
	int childId = varChild.lVal;
	RunOnMainThreadSync(func, 1, INT2PTR(childId));
	return mainThreadResult;
    }
    return E_INVALIDARG;
}

/* Function to get accessible help to MSAA. */
static HRESULT STDMETHODCALLTYPE TkRootAccessible_get_accHelp(
    IAccessible *this,
    VARIANT varChild,
    BSTR* pszHelp)
{
    if (!pszHelp) return E_INVALIDARG;
    TkGlobalLock();
    TkRootAccessible *tkAccessible = (TkRootAccessible *)this;
    if (!tkAccessible->toplevel) {
	TkGlobalUnlock();
	return E_INVALIDARG;
    }
    if (varChild.vt == VT_I4 && varChild.lVal > 0) {
	Tk_Window child = GetTkWindowForChildId(varChild.lVal, tkAccessible->toplevel);
	if (!child) {
	    TkGlobalUnlock();
	    return E_INVALIDARG;
	}
	HRESULT hr = TkAccHelp(child, pszHelp);
	TkGlobalUnlock();
	return hr;
    }
    TkGlobalUnlock();
    return E_INVALIDARG;
}

/* Function to get accessible focus to MSAA. */
static HRESULT STDMETHODCALLTYPE TkRootAccessible_get_accFocus(
    IAccessible *this,
    VARIANT *pvarChild)
{
    if (!pvarChild) return E_INVALIDARG;
    VariantInit(pvarChild);
    TkGlobalLock();
    TkRootAccessible *tkAccessible = (TkRootAccessible *)this;
    if (!tkAccessible->toplevel || !tkAccessible->hwnd) {
	TkGlobalUnlock();
	return E_INVALIDARG;
    }
    HWND hwnd = tkAccessible->hwnd;
    TkGlobalUnlock();
    MainThreadFunc func = (MainThreadFunc)TkAccFocus;
    RunOnMainThreadSync(func, 2, (void*)hwnd, (void*)pvarChild);
    return S_OK;
}

/*
 * Function to get accessible description to MSAA.
 */
static HRESULT STDMETHODCALLTYPE TkRootAccessible_get_accDescription(
	IAccessible *this,
	VARIANT varChild,
	BSTR *pszDescription)
{
    if (!pszDescription) return E_INVALIDARG;
    TkGlobalLock();
    TkRootAccessible *tkAccessible = (TkRootAccessible *)this;
    if (!tkAccessible->toplevel) {
	TkGlobalUnlock();
	return E_INVALIDARG;
    }
    if (varChild.vt == VT_I4 && varChild.lVal == CHILDID_SELF) {
	*pszDescription = SysAllocString(L"Window");
	TkGlobalUnlock();
	return S_OK;
    }
    if (varChild.vt == VT_I4 && varChild.lVal > 0) {
	Tk_Window child = GetTkWindowForChildId(varChild.lVal, tkAccessible->toplevel);
	if (!child) {
	    TkGlobalUnlock();
	    return E_INVALIDARG;
	}
	HRESULT hr = TkAccDescription(child, pszDescription);
	TkGlobalUnlock();
	return hr;
    }
    TkGlobalUnlock();
    return E_INVALIDARG;
}

/*
 *----------------------------------------------------------------------
 *
 * Glue functions - child widgets.
 *
 *----------------------------------------------------------------------
 */

/* Function to map accessible role to MSAA. */
static HRESULT TkAccRole(
    Tk_Window win,
    VARIANT *pvarRole)
{
    if (!win || !pvarRole) return E_INVALIDARG;
    TkGlobalLock();

    Tcl_HashEntry *hPtr = Tcl_FindHashEntry(TkAccessibilityObject, (ClientData)win);
    if (!hPtr) {
	TkGlobalUnlock();
	return S_FALSE;
    }

    Tcl_HashTable *AccessibleAttributes = (Tcl_HashTable *)Tcl_GetHashValue(hPtr);
    Tcl_HashEntry *hPtr2 = Tcl_FindHashEntry(AccessibleAttributes, "role");
    if (!hPtr2) {
	TkGlobalUnlock();
	return S_FALSE;
    }

    const char *tkrole = Tcl_GetString(Tcl_GetHashValue(hPtr2));
    LONG result = ROLE_SYSTEM_CLIENT; /* Fallback value */

    for (int i = 0; roleMap[i].tkrole != NULL; i++) {
	if (strcmp(tkrole, roleMap[i].tkrole) == 0) {
	    result = roleMap[i].winrole;
	    break;
	}
    }

    pvarRole->vt = VT_I4;
    pvarRole->lVal = result;

    TkGlobalUnlock();
    return S_OK;
}

/*
 * Helper function to get selected state on check/radiobuttons.
 */

static void
ComputeAndCacheCheckedState(
    Tk_Window win,
    Tcl_Interp *interp)
{
    if (!win || !interp) {
	return;
    }

    /* Look up accessibility attributes table for this window. */
    Tcl_HashEntry *hPtr = Tcl_FindHashEntry(TkAccessibilityObject, (char *)win);
    if (!hPtr) {
	return;
    }
    Tcl_HashTable *AccessibleAttributes = (Tcl_HashTable *)Tcl_GetHashValue(hPtr);

    /* Find role */
    Tcl_HashEntry *rolePtr = Tcl_FindHashEntry(AccessibleAttributes, "role");
    const char *tkrole = NULL;
    if (rolePtr) {
	tkrole = Tcl_GetString(Tcl_GetHashValue(rolePtr));
    }
    if (!tkrole) {
	return;
    }

    /* Only handle check-like widgets */
    if (strcmp(tkrole, "Checkbutton") != 0 &&
	strcmp(tkrole, "Radiobutton") != 0 &&
	strcmp(tkrole, "Toggleswitch") != 0) {
	return;
    }

    int isChecked = 0;
    const char *path = Tk_PathName(win);

    /* Special-case: ttk::toggleswitch — ALWAYS use instate selected. */
    if (strcmp(tkrole, "Toggleswitch") == 0) {
	Tcl_Obj *stateCmd = Tcl_ObjPrintf("%s instate selected", path);
	if (!stateCmd) return;
	Tcl_IncrRefCount(stateCmd);
	if (Tcl_EvalObjEx(interp, stateCmd, TCL_EVAL_GLOBAL) == TCL_OK) {
	    const char *result = Tcl_GetStringResult(interp);
	    if (result && strcmp(result, "1") == 0) {
		isChecked = 1;
	    }
	}
	Tcl_DecrRefCount(stateCmd);

	/* Proceed to cache/notify below. */
	goto cache_and_notify;
    }

    /*
	 * For Checkbutton and Radiobutton: prefer -variable based detection if present.
     * Note: ttk widgets sometimes auto-create variables — but toggleswitch was handled above.
     */

    Tcl_Obj *varCmd = Tcl_ObjPrintf("%s cget -variable", path);
    if (!varCmd) return;
    Tcl_IncrRefCount(varCmd);

    const char *varName = NULL;
    int haveVarName = 0;
    if (Tcl_EvalObjEx(interp, varCmd, TCL_EVAL_GLOBAL) == TCL_OK) {
	varName = Tcl_GetStringResult(interp);
	if (varName && *varName) {
	    haveVarName = 1;
	}
    } else {
	/* evaluation failed; clean up and return */
	Tcl_DecrRefCount(varCmd);
	return;
    }
    Tcl_DecrRefCount(varCmd);

    if (haveVarName) {
	/* Grab the variable value (global). */
	const char *varVal = Tcl_GetVar(interp, varName, TCL_GLOBAL_ONLY);
	if (varVal) {
	    /* Determine which cget to use: -onvalue for checkbutton, -value for radiobutton. */
	    Tcl_Obj *valueCmd = NULL;
	    if (strcmp(tkrole, "Checkbutton") == 0) {
		valueCmd = Tcl_ObjPrintf("%s cget -onvalue", path);
	    } else if (strcmp(tkrole, "Radiobutton") == 0) {
		valueCmd = Tcl_ObjPrintf("%s cget -value", path);
	    }

	    if (valueCmd) {
		Tcl_IncrRefCount(valueCmd);
		const char *onValue = NULL;
		if (Tcl_EvalObjEx(interp, valueCmd, TCL_EVAL_GLOBAL) == TCL_OK) {
		    onValue = Tcl_GetStringResult(interp);
		}
		Tcl_DecrRefCount(valueCmd);

		if (onValue && varVal && strcmp(varVal, onValue) == 0) {
		    isChecked = 1;
		}
	    }
	} else {
	    /* variable exists but has no value — fall back to instate selected. */
	    Tcl_Obj *stateCmd = Tcl_ObjPrintf("%s instate selected", path);
	    if (!stateCmd) return;
	    Tcl_IncrRefCount(stateCmd);
	    if (Tcl_EvalObjEx(interp, stateCmd, TCL_EVAL_GLOBAL) == TCL_OK) {
		const char *result = Tcl_GetStringResult(interp);
		if (result && strcmp(result, "1") == 0) {
		    isChecked = 1;
		}
	    }
	    Tcl_DecrRefCount(stateCmd);
	}
    } else {
	/* No variable: fall back to widget state (works for ttk and classic when variable not used). */
	Tcl_Obj *stateCmd = Tcl_ObjPrintf("%s instate selected", path);
	if (!stateCmd) return;
	Tcl_IncrRefCount(stateCmd);
	if (Tcl_EvalObjEx(interp, stateCmd, TCL_EVAL_GLOBAL) == TCL_OK) {
	    const char *result = Tcl_GetStringResult(interp);
	    if (result && strcmp(result, "1") == 0) {
		isChecked = 1;
	    }
	}
	Tcl_DecrRefCount(stateCmd);
    }

cache_and_notify:
    /* Cache the checked state as a Tcl_Obj string "0" or "1" in AccessibleAttributes->"value". */
    TkGlobalLock();
    Tcl_HashEntry *valuePtr;
    int newEntry;
    valuePtr = Tcl_CreateHashEntry(AccessibleAttributes, "value", &newEntry);

    char buf[2];
    snprintf(buf, sizeof(buf), "%d", isChecked);
    Tcl_Obj *valObj = Tcl_NewStringObj(buf, -1);
    Tcl_IncrRefCount(valObj);

    if (!newEntry) {
	/* Replace existing value: free previous Tcl_Obj if present. */
	Tcl_Obj *old = (Tcl_Obj *)Tcl_GetHashValue(valuePtr);
	if (old) {
	    Tcl_DecrRefCount(old);
	}
    }
    Tcl_SetHashValue(valuePtr, valObj);
    TkGlobalUnlock();

    /* Notify MSAA about both value and state changes. */
    {
	Tk_Window toplevel = GetToplevelOfWidget(win);
	if (!toplevel) {
	    return;
	}
	Tcl_HashTable *childIdTable = GetChildIdTableForToplevel(toplevel);
	LONG childId = GetChildIdForTkWindow(win, childIdTable);
	if (childId > 0) {
	    HWND hwnd = Tk_GetHWND(Tk_WindowId(toplevel));
	    NotifyWinEvent(EVENT_OBJECT_VALUECHANGE, hwnd, OBJID_CLIENT, childId);
	    NotifyWinEvent(EVENT_OBJECT_STATECHANGE, hwnd, OBJID_CLIENT, childId);
	}
    }
}

/* Function to map accessible state to MSAA. */
static HRESULT TkAccState(
    Tk_Window win,
    VARIANT *pvarState)
{
    if (!win || !pvarState) {
	return E_INVALIDARG;
    }
    Tcl_HashEntry *hPtr = Tcl_FindHashEntry(TkAccessibilityObject, win);
    if (!hPtr) {
	return S_FALSE;
    }
    Tcl_HashTable *AccessibleAttributes = Tcl_GetHashValue(hPtr);

    long state = STATE_SYSTEM_FOCUSABLE | STATE_SYSTEM_SELECTABLE; /* Reasonable default. */

    Tcl_HashEntry *hPtr2 = Tcl_FindHashEntry(AccessibleAttributes, "state");
    if (hPtr2) {
	const char *stateresult = Tcl_GetString(Tcl_GetHashValue(hPtr2));
	if (strcmp(stateresult, "disabled") == 0) {
	    state = STATE_SYSTEM_UNAVAILABLE;
	}
    }

    /* Check for checked state using cached value. */
    Tcl_HashEntry *rolePtr = Tcl_FindHashEntry(AccessibleAttributes, "role");
    if (rolePtr) {
	const char *tkrole = Tcl_GetString(Tcl_GetHashValue(rolePtr));
	if (strcmp(tkrole, "Checkbutton") == 0 ||
	    strcmp(tkrole, "Radiobutton") == 0 ||
	    strcmp(tkrole, "Toggleswitch") == 0) {
	    Tcl_HashEntry *valuePtr = Tcl_FindHashEntry(AccessibleAttributes, "value");
	    if (valuePtr) {
		const char *value = Tcl_GetString(Tcl_GetHashValue(valuePtr));
		if (value && strcmp(value, "1") == 0) {
		    state |= STATE_SYSTEM_CHECKED;
		}
	    } else {
	    }
	}
    }

    TkWindow *focusPtr = TkGetFocusWin((TkWindow *)win);
    if (focusPtr == (TkWindow *)win) {
	state |= STATE_SYSTEM_FOCUSED;
    }

    pvarState->vt = VT_I4;
    pvarState->lVal = state;
    return S_OK;
}

/* Function to map accessible value to MSAA. */
static HRESULT TkAccValue(
    Tk_Window win,
    BSTR *pValue)
{
    if (!win || !pValue) return E_INVALIDARG;
    Tcl_HashEntry *hPtr = Tcl_FindHashEntry(TkAccessibilityObject, win);
    if (!hPtr) return S_FALSE;
    Tcl_HashTable *AccessibleAttributes = Tcl_GetHashValue(hPtr);
    Tcl_HashEntry *hPtr2 = Tcl_FindHashEntry(AccessibleAttributes, "value");
    if (!hPtr2) return S_FALSE;
    const char *val = Tcl_GetString(Tcl_GetHashValue(hPtr2));
    Tcl_DString ds;
    Tcl_DStringInit(&ds);
    *pValue = SysAllocString(Tcl_UtfToWCharDString(val, -1, &ds));
    Tcl_DStringFree(&ds);
    return S_OK;
}

/* Event proc which calls the ActionEventProc procedure. */
static int ActionEventProc(
    Tcl_Event *ev,
    TCL_UNUSED(int)) /* flags */
{
    ActionEvent *event = (ActionEvent *)ev;
    if (!event || !event->win || !event->command) return 1;
    Tcl_Interp *interp = Tk_Interp(event->win);
    if (!interp) return 1;
    int code = Tcl_EvalEx(interp, event->command, -1, TCL_EVAL_GLOBAL);
    if (code != TCL_OK) return TCL_ERROR;
    ckfree(event->command);
    return 1;
}

/* Function to get button press to MSAA. */
static void TkDoDefaultAction(
    TCL_UNUSED(int), /* num_args */
    void **args)
{
    int childId = (int)PTR2INT(args[0]);
    ActionEvent *event = NULL;
    if (!childId) {
	mainThreadResult = E_INVALIDARG;
	return;
    }
    TkGlobalLock();
    Tk_Window toplevel = NULL;
    Tcl_HashSearch search;
    Tcl_HashEntry *entry;
    for (entry = Tcl_FirstHashEntry(tkAccessibleTable, &search); entry != NULL; entry = Tcl_NextHashEntry(&search)) {
	TkRootAccessible *acc = (TkRootAccessible *)Tcl_GetHashValue(entry);
	Tk_Window win = GetTkWindowForChildId(childId, acc->toplevel);
	if (win) {
	    toplevel = acc->toplevel;
	    break;
	}
    }
    if (!toplevel) {
	TkGlobalUnlock();
	mainThreadResult = E_INVALIDARG;
	return;
    }
    Tk_Window win = GetTkWindowForChildId(childId, toplevel);
    if (!win) {
	TkGlobalUnlock();
	mainThreadResult = E_INVALIDARG;
	return;
    }
    Tcl_HashEntry *hPtr = Tcl_FindHashEntry(TkAccessibilityObject, (char *)win);
    if (!hPtr) {
	TkGlobalUnlock();
	mainThreadResult = E_INVALIDARG;
	return;
    }
    Tcl_HashTable *AccessibleAttributes = (Tcl_HashTable *)Tcl_GetHashValue(hPtr);
    if (!AccessibleAttributes) {
	TkGlobalUnlock();
	mainThreadResult = E_INVALIDARG;
	return;
    }
    Tcl_HashEntry *hPtr2 = Tcl_FindHashEntry(AccessibleAttributes, "action");
    if (!hPtr2) {
	TkGlobalUnlock();
	mainThreadResult = E_INVALIDARG;
	return;
    }
    const char *action = Tcl_GetString(Tcl_GetHashValue(hPtr2));
    if (!action) {
	TkGlobalUnlock();
	mainThreadResult = E_INVALIDARG;
	return;
    }
    event = (ActionEvent *)ckalloc(sizeof(ActionEvent));
    if (event == NULL) {
	TkGlobalUnlock();
	mainThreadResult = E_OUTOFMEMORY;
	return;
    }
    event->header.proc = ActionEventProc;
    event->command = ckalloc(strlen(action) + 1);
    strcpy(event->command, action);
    event->win = win;

    /* Update checked state and notify MSAA. */
    ComputeAndCacheCheckedState(win, Tk_Interp(win));

    TkGlobalUnlock();
    Tcl_QueueEvent((Tcl_Event *)event, TCL_QUEUE_TAIL);
    mainThreadResult = S_OK;
    return;
}

/* Function to get MSAA focus. */
static void TkAccFocus(
    TCL_UNUSED(int), /* num_args */
    void **args)
{
    HWND hwnd = (HWND)args[0];
    VARIANT *pvarChild = (VARIANT*)args[1];
    if (!hwnd || !pvarChild) return;
    Tk_Window win = Tk_HWNDToWindow(hwnd);
    if (!win) return;
    Tk_Window toplevel = GetToplevelOfWidget(win);
    if (!toplevel) return;
    TkWindow *focusPtr = TkGetFocusWin((TkWindow *)win);
    Tk_Window focusWin = (Tk_Window)focusPtr;
    if (!focusWin || focusWin == win) {
	pvarChild->vt = VT_I4;
	pvarChild->lVal = CHILDID_SELF;
	return;
    }
    TkGlobalLock();
    ClearChildIdTableForToplevel(toplevel);
    int nextId = 1;
    AssignChildIdsRecursive(toplevel, &nextId, Tk_Interp(win), toplevel);
    int childId = GetChildIdForTkWindow(focusWin, GetChildIdTableForToplevel(toplevel));
    TkGlobalUnlock();
    if (childId > 0) {
	pvarChild->vt = VT_I4;
	pvarChild->lVal = childId;
	return;
    } else {
	pvarChild->vt = VT_I4;
	pvarChild->lVal = CHILDID_SELF;
	return;
    }
}

/* Function to get MSAA description. */
static HRESULT TkAccDescription(
    Tk_Window win,
    BSTR *pDesc)
{
    if (!win || !pDesc) return E_INVALIDARG;
    Tcl_HashEntry *hPtr = Tcl_FindHashEntry(TkAccessibilityObject, win);
    if (!hPtr) return S_FALSE;
    Tcl_HashTable *AccessibleAttributes = Tcl_GetHashValue(hPtr);
    Tcl_HashEntry *hPtr2 = Tcl_FindHashEntry(AccessibleAttributes, "description");
    if (!hPtr2) return S_FALSE;
    const char *desc = Tcl_GetString(Tcl_GetHashValue(hPtr2));
    Tcl_DString ds;
    Tcl_DStringInit(&ds);
    *pDesc = SysAllocString(Tcl_UtfToWCharDString(desc, -1, &ds));
    Tcl_DStringFree(&ds);
    return S_OK;
}

/* Function to get MSAA help. */
static HRESULT TkAccHelp(
    Tk_Window win,
    BSTR *pszHelp)
{
    if (!win || !pszHelp) return E_INVALIDARG;
    Tcl_HashEntry *hPtr = Tcl_FindHashEntry(TkAccessibilityObject, win);
    if (!hPtr) return S_FALSE;
    Tcl_HashTable *AccessibleAttributes = Tcl_GetHashValue(hPtr);
    Tcl_HashEntry *hPtr2 = Tcl_FindHashEntry(AccessibleAttributes, "help");
    if (!hPtr2) return S_FALSE;
    const char *help = Tcl_GetString(Tcl_GetHashValue(hPtr2));
    Tcl_DString ds;
    Tcl_DStringInit(&ds);
    *pszHelp = SysAllocString(Tcl_UtfToWCharDString(help, -1, &ds));
    Tcl_DStringFree(&ds);
    return S_OK;
}

/* Function to get number of child window objects. */
static int TkAccChildCount(Tk_Window win)
{
    if (!win) return -1;
    int count = 0;
    TkWindow *child = (TkWindow*)win;
    Tk_Window toplevel = GetToplevelOfWidget(win);
    if (!toplevel) return -1;
    TkWindow *winPtr = (TkWindow *)toplevel;

    /* Step through all child widgets of toplevel to get child count. */
    for (child = winPtr->childList; child != NULL; child = child->nextPtr) {
	if (Tk_IsMapped(child)) count++;
    }

    return count;
}

/* Function to get child rect. */
static HRESULT TkAccChild_GetRect(
    Tcl_Interp *interp,
    char *path,
    RECT *rect)
{
    if (!interp || !path || !rect) return S_FALSE;
    Tk_Window child = Tk_NameToWindow(interp, path, Tk_MainWindow(interp));
    if (!child || !Tk_IsMapped(child)) return S_FALSE;
    int x, y;
    Tk_GetRootCoords(child, &x, &y);
    int w = Tk_Width(child);
    int h = Tk_Height(child);
    rect->left = x;
    rect->top = y;
    rect->right = x + w;
    rect->bottom = y + h;
    return S_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * General/utility functions to help integrate the MSAA API to
 * the Tcl script-level API. We are using HWND's for toplevel windows
 * and unique childIDs for all accessible child widgets. We are using
 * several hash tables to maintain bidrectional mappings between widgets
 * and childIDs.
 *
 *----------------------------------------------------------------------
 */

/* Function to map Tk window to MSAA attributes. */
static TkRootAccessible *CreateRootAccessible(
    Tcl_Interp *interp,
    HWND hwnd,
    const char *pathName)
{
    if (!interp || !hwnd || !pathName) {
	Tcl_SetResult(interp, "Invalid arguments to CreateRootAccessible", TCL_STATIC);
	return NULL;
    }
    Tk_Window win = Tk_NameToWindow(interp, pathName, Tk_MainWindow(interp));
    if (!win) {
	Tcl_SetResult(interp, "Window not found", TCL_STATIC);
	return NULL;
    }
    if (!Tk_IsTopLevel(win)) {
	Tcl_SetResult(interp, "Window is not a toplevel", TCL_STATIC);
	return NULL;
    }
    Tk_MakeWindowExist(win);
    TkRootAccessible *tkAccessible = (TkRootAccessible *)ckalloc(sizeof(TkRootAccessible));
    if (!tkAccessible) {
	Tcl_SetResult(interp, "Memory allocation failed for TkRootAccessible", TCL_STATIC);
	return NULL;
    }
    tkAccessible->pathName = ckalloc(strlen(pathName) + 1);
    if (!tkAccessible->pathName) {
	ckfree(tkAccessible);
	Tcl_SetResult(interp, "Memory allocation failed for pathName", TCL_STATIC);
	return NULL;
    }
    strcpy(tkAccessible->pathName, pathName);
    tkAccessible->lpVtbl = &tkRootAccessibleVtbl;
    tkAccessible->interp = interp;
    tkAccessible->hwnd = hwnd;
    tkAccessible->refCount = 1;
    tkAccessible->win = win;
    tkAccessible->toplevel = win;
    tkAccessible->children = NULL;
    tkAccessible->numChildren = 0;
    Tcl_HashEntry *entry;
    int newEntry;
    TkGlobalLock();
    if (!tkAccessibleTableInitialized) {
	InitTkAccessibleTable();
    }
    entry = Tcl_CreateHashEntry(tkAccessibleTable, win, &newEntry);
    Tcl_SetHashValue(entry, tkAccessible);
    TkGlobalUnlock();
    TkRootAccessible_AddRef((IAccessible*)tkAccessible);
    NotifyWinEvent(EVENT_OBJECT_CREATE, hwnd, OBJID_CLIENT, CHILDID_SELF);
    NotifyWinEvent(EVENT_OBJECT_SHOW, hwnd, OBJID_CLIENT, CHILDID_SELF);
    NotifyWinEvent(EVENT_OBJECT_NAMECHANGE, hwnd, OBJID_CLIENT, CHILDID_SELF);
    return tkAccessible;
}

/* Function to map Tk window to MSAA ID's. */
static void SetChildIdForTkWindow(
    Tk_Window win,
    int id,
    Tcl_HashTable *childIdTable)
{
    if (!win || !childIdTable) return;
    Tcl_HashEntry *entry;
    int newEntry;
    TkGlobalLock();
    entry = Tcl_CreateHashEntry(childIdTable, win, &newEntry);
    Tcl_SetHashValue(entry, INT2PTR(id));
    TkGlobalUnlock();
}

/* Function to retrieve MSAA ID for a specifc Tk window. */
static int GetChildIdForTkWindow(
    Tk_Window win,
    Tcl_HashTable *childIdTable)
{
    if (!win || !childIdTable) return -1;
    Tcl_HashEntry *entry;
    TkGlobalLock();
    entry = Tcl_FindHashEntry(childIdTable, win);
    if (!entry) {
	TkGlobalUnlock();
	return -1;
    }
    int id = PTR2INT(Tcl_GetHashValue(entry));
    TkGlobalUnlock();
    return id;
}

/* Function to retrieve Tk window for a specifc MSAA ID. */
Tk_Window GetTkWindowForChildId(
    int id,
    Tk_Window toplevel)
{
    if (!toplevel) return NULL;
    /*
     * We are looking for a specific child ID within a specific toplevel,
     * each one tracked separately in this hash table.
     */
    Tcl_HashTable *childIdTable = GetChildIdTableForToplevel(toplevel);
    if (!childIdTable) return NULL;
    Tcl_HashSearch search;
    Tcl_HashEntry *entry;
    TkGlobalLock();
    for (entry = Tcl_FirstHashEntry(childIdTable, &search); entry != NULL; entry = Tcl_NextHashEntry(&search)) {
	if (PTR2INT(Tcl_GetHashValue(entry)) == id) {
	    Tk_Window win = (Tk_Window)Tcl_GetHashKey(childIdTable, entry);
	    TkGlobalUnlock();
	    return win;
	}
    }
    TkGlobalUnlock();
    return NULL;
}

/* Function to get child ID table for a toplevel. We are using a separate table for each toplevel. */
static Tcl_HashTable *GetChildIdTableForToplevel(
    Tk_Window toplevel)
{
    if (!toplevel || !toplevelChildTables) return NULL;
    Tcl_HashEntry *entry;
    int newEntry;
    Tcl_HashTable *childIdTable;
    TkGlobalLock();
    entry = Tcl_CreateHashEntry(toplevelChildTables, toplevel, &newEntry);
    if (newEntry) {
	childIdTable = (Tcl_HashTable *)ckalloc(sizeof(Tcl_HashTable));
	if (!childIdTable) {
	    TkGlobalUnlock();
	    return NULL;
	}
	Tcl_InitHashTable(childIdTable, TCL_ONE_WORD_KEYS);
	Tcl_SetHashValue(entry, childIdTable);
    } else {
	childIdTable = (Tcl_HashTable *)Tcl_GetHashValue(entry);
    }
    TkGlobalUnlock();
    return childIdTable;
}

/* Function to return the toplevel window that contains a given Tk widget. */
Tk_Window GetToplevelOfWidget(
    Tk_Window tkwin)
{
    if (!tkwin) return NULL;
    Tk_Window current = tkwin;
    if (Tk_IsTopLevel(current)) return current;
    while (current != NULL && Tk_WindowId(current) != None) {
	Tk_Window parent = Tk_Parent(current);
	if (parent == NULL || Tk_IsTopLevel(current)) break;
	current = parent;
    }
    return Tk_IsTopLevel(current) ? current : NULL;
}

/* Function to initialize Tk -> MSAA hash table. */
void InitTkAccessibleTable(void)
{
    if (!tkAccessibleTableInitialized) {
	tkAccessibleTable = (Tcl_HashTable *)ckalloc(sizeof(Tcl_HashTable));
	if (tkAccessibleTable) {
	    Tcl_InitHashTable(tkAccessibleTable, TCL_ONE_WORD_KEYS);
	    tkAccessibleTableInitialized = true;
	}
    }
}

/* Function to initialize childId hash table. */
void InitChildIdTable(void)
{
    if (!toplevelChildTables) {
	toplevelChildTables = (Tcl_HashTable *)ckalloc(sizeof(Tcl_HashTable));
	if (toplevelChildTables) {
	    Tcl_InitHashTable(toplevelChildTables, TCL_ONE_WORD_KEYS);
	}
    }
}

/* Function to clear childId hash table for a toplevel. */
void ClearChildIdTableForToplevel(
				  Tk_Window toplevel)
{
    if (!toplevel || !toplevelChildTables) return;
    Tcl_HashEntry *entry = Tcl_FindHashEntry(toplevelChildTables, toplevel);
    if (!entry) return;
    Tcl_HashTable *childIdTable = (Tcl_HashTable *)Tcl_GetHashValue(entry);
    Tcl_HashSearch search;
    Tcl_HashEntry *childEntry;
    TkGlobalLock();
    for (childEntry = Tcl_FirstHashEntry(childIdTable, &search); childEntry != NULL; childEntry = Tcl_NextHashEntry(&search)) {
	Tcl_DeleteHashEntry(childEntry);
    }
    Tcl_DeleteHashEntry(entry); /* Remove toplevel entry to prevent memory leaks. */
    ckfree(childIdTable);
    TkGlobalUnlock();
}

/* Function to retrieve accessible object associated with Tk window. */
TkRootAccessible *GetTkAccessibleForWindow(
    Tk_Window win)
{
    if (!win || !tkAccessibleTableInitialized) return NULL;
    Tcl_HashEntry *entry = Tcl_FindHashEntry(tkAccessibleTable, win);
    if (entry) return (TkRootAccessible *)Tcl_GetHashValue(entry);
    return NULL;
}

/* Function to assign childId's dynamically. */
static void AssignChildIdsRecursive(
    Tk_Window win,
    int *nextId,
    Tcl_Interp *interp,
    Tk_Window toplevel)
{
    if (!win || !interp || !toplevel || !Tk_IsMapped(win)) {
	return;
    }
    Tcl_HashTable *childIdTable = GetChildIdTableForToplevel(toplevel);
    if (!childIdTable) {
	return;
    }
    SetChildIdForTkWindow(win, *nextId, childIdTable);
    (*nextId)++;

    /* Initialize checked state for checkbuttons and radiobuttons. */
    ComputeAndCacheCheckedState(win, interp);

    TkWindow *winPtr = (TkWindow *)win;
    for (TkWindow *child = winPtr->childList; child != NULL; child = child->nextPtr) {
	AssignChildIdsRecursive((Tk_Window)child, nextId, interp, toplevel);
    }
}

/*
 *----------------------------------------------------------------------
 *
 * Threading functions. These manage the integration of accessibility operations
 * on background threads and Tk execution on the main thread.
 *
 *----------------------------------------------------------------------
 */

/* Handle WM_GETOBJECT call on main thread. */
void HandleWMGetObjectOnMainThread(
    TCL_UNUSED(int), /* num_args */
    void **args)
{
    HWND hwnd = (HWND)args[0];
    WPARAM wParam = (WPARAM)args[1];
    LPARAM lParam = (LPARAM)args[2];
    LRESULT *outResult = (LRESULT *)args[3];
    if (outResult) *outResult = 0;

    Tk_Window tkwin = Tk_HWNDToWindow(hwnd);

    /* Handle MSAA requests. */
    if ((LONG)lParam == OBJID_CLIENT) {
	TkRootAccessible *msaaProvider = GetTkAccessibleForWindow(tkwin);
	if (!msaaProvider) {
	    Tcl_Interp *interp = Tk_Interp(tkwin);
	    if (!interp) return;

	    msaaProvider = CreateRootAccessible(interp, hwnd, Tk_PathName(tkwin));
	    if (msaaProvider) {
		TkRootAccessible_RegisterForCleanup(tkwin, msaaProvider);
	    }
	}

	if (msaaProvider && outResult) {
	    *outResult = LresultFromObject(&IID_IAccessible, wParam, (IUnknown *)msaaProvider);
	}
    }
}

/* Event handler that executes on main thread. */
int ExecuteOnMainThreadSync(
    Tcl_Event *ev,
    TCL_UNUSED(int)) /*flags */
{
    MainThreadSyncEvent *event = (MainThreadSyncEvent *)ev;
    if (!event) return 1;
    switch(event->num_args) {
    case 0: event->func(0, NULL); break;
    case 1: event->func(1, event->args); break;
    case 2: event->func(2, event->args); break;
    case 3: event->func(3, event->args); break;
    case 4: event->func(4, event->args); break;
    case 5: event->func(5, event->args); break;
    }
    SetEvent(event->doneEvent);
    ckfree(event);
    return 1;
}

/* Synchronous execution with variable arguments. */
void RunOnMainThreadSync(
    MainThreadFunc func,
    int num_args, ...)
{
    if (Tcl_GetCurrentThread() == mainThreadId) {
	void *args[6];
	va_list ap;
	va_start(ap, num_args);
	for (int i = 0; i < num_args; i++) {
	    args[i] = va_arg(ap, void*);
	}
	va_end(ap);
	func(num_args, args);
	return;
    }
    MainThreadSyncEvent *event = (MainThreadSyncEvent *)ckalloc(sizeof(MainThreadSyncEvent));
    if (!event) return;
    event->header.proc = ExecuteOnMainThreadSync;
    event->func = func;
    event->num_args = num_args;
    event->doneEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
    if (!event->doneEvent) {
	ckfree(event);
	return;
    }
    va_list ap;
    va_start(ap, num_args);
    for (int i = 0; i < num_args; i++) {
	event->args[i] = va_arg(ap, void*);
    }
    va_end(ap);
    Tcl_ThreadQueueEvent(mainThreadId, (Tcl_Event *)event, TCL_QUEUE_TAIL);
    Tcl_ThreadAlert(mainThreadId);
    DWORD result = WaitForSingleObject(event->doneEvent, 500);
    if (result == WAIT_TIMEOUT) {
	CloseHandle(event->doneEvent);
	ckfree(event);
    }
    CloseHandle(event->doneEvent);
}

/* Initialize during Tcl startup. */
void InitAccessibilityMainThread(void)
{
    mainThreadId = Tcl_GetCurrentThread();
}

/* Initiate global thread lock. */
BOOL CALLBACK InitGlobalLockOnce(
    TCL_UNUSED(PINIT_ONCE), /* InitOnce */
    TCL_UNUSED(PVOID), /* param */
    TCL_UNUSED(PVOID *)) /* Context */
{
    InitializeCriticalSection(&TkGlobalLock);
    return TRUE;
}

/* Wrapper for global thread lock. */
void EnsureGlobalLockInitialized(void)
{
    InitOnceExecuteOnce(&TkInitOnce, InitGlobalLockOnce, NULL, NULL);
}

/*
 * Functions to implement direct script-level
 * Tcl commands.
 */

/*
 *----------------------------------------------------------------------
 *
 * IsScreenReaderRunning --
 *
 * Runtime check to see if screen reader is running.
 *
 * Results:
 *    Returns if screen reader is active or not.
 *
 * Side effects:
 *    None.
 *
 *----------------------------------------------------------------------
 */
int IsScreenReaderRunning(
    TCL_UNUSED(void *), /* clientData */
    Tcl_Interp *interp,
    TCL_UNUSED(int), /* objc */
    TCL_UNUSED(Tcl_Obj *const *)) /* objv */
{
    BOOL screenReader = FALSE;

    /* First check the system-wide flag (covers NVDA, JAWS, etc.) */
    SystemParametersInfo(SPI_GETSCREENREADER, 0, &screenReader, 0);

    if (!screenReader) {
	/* Fallback: explicitly check for Narrator.exe */
	HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
	if (hSnapshot != INVALID_HANDLE_VALUE) {
	    PROCESSENTRY32 pe;
	    pe.dwSize = sizeof(PROCESSENTRY32);
	    if (Process32First(hSnapshot, &pe)) {
		do {
		    if (_tcsicmp(pe.szExeFile, TEXT("Narrator.exe")) == 0) {
			screenReader = TRUE;
			break;
		    }
		} while (Process32Next(hSnapshot, &pe));
	    }
	    CloseHandle(hSnapshot);
	}
    }

    Tcl_SetObjResult(interp, Tcl_NewBooleanObj(screenReader));
    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * EmitSelectionChanged --
 *
 * Accessibility system notification when selection changed.
 *
 * Results:
 *    Accessibility system is made aware when a selection is changed.
 *
 * Side effects:
 *    None.
 *
 *----------------------------------------------------------------------
 */

static int EmitSelectionChanged(
    TCL_UNUSED(void *), /* clientData */
    Tcl_Interp *ip,
    int objc,
    Tcl_Obj *const objv[])
{
    if (objc < 2) {
	Tcl_WrongNumArgs(ip, 1, objv, "window?");
	return TCL_ERROR;
    }

    Tk_Window path = Tk_NameToWindow(ip, Tcl_GetString(objv[1]), Tk_MainWindow(ip));
    if (!path) {
	Tcl_SetResult(ip, "Invalid window name", TCL_STATIC);
	return TCL_ERROR;
    }

    Tk_Window toplevel = GetToplevelOfWidget(path);
    if (!toplevel || !Tk_IsTopLevel(toplevel)) {
	Tcl_SetResult(ip, "Window must be in a toplevel", TCL_STATIC);
	return TCL_ERROR;
    }

    Tk_MakeWindowExist(path);

    /* Update checked state. */
    ComputeAndCacheCheckedState(path, ip);

    TkGlobalLock();
    Tcl_HashTable *childIdTable = GetChildIdTableForToplevel(toplevel);
    LONG childId = GetChildIdForTkWindow(path, childIdTable);

    if (childId > 0) {
	HWND hwnd = Tk_GetHWND(Tk_WindowId(toplevel));

	/* Send comprehensive notifications for Narrator compatibility. */
	NotifyWinEvent(EVENT_OBJECT_VALUECHANGE, hwnd, OBJID_CLIENT, childId);
	NotifyWinEvent(EVENT_OBJECT_STATECHANGE, hwnd, OBJID_CLIENT, childId);
	NotifyWinEvent(EVENT_OBJECT_NAMECHANGE, hwnd, OBJID_CLIENT, childId);
	NotifyWinEvent(EVENT_OBJECT_SELECTION, hwnd, OBJID_CLIENT, childId);
    }

    TkGlobalUnlock();
    return TCL_OK;
}



/*
 *----------------------------------------------------------------------
 *
 * TkRootAccessible_RegisterForCleanup --
 *
 * Register event handler for destroying accessibility element.
 *
 * Results:
 *      Event handler is registered.
 *
 * Side effects:
 *    None.
 *
 *----------------------------------------------------------------------
 */
void TkRootAccessible_RegisterForCleanup(
    Tk_Window tkwin,
    void *tkAccessible)
{
    if (!tkwin || !tkAccessible) return;
    Tk_CreateEventHandler(tkwin, StructureNotifyMask, TkRootAccessible_DestroyHandler, tkAccessible);
}

/*
 *----------------------------------------------------------------------
 *
 * TkRootAccessible_DestroyHandler --
 *
 * Clean up accessibility element structures when window is destroyed.
 *
 * Results:
 *    Accessibility element is deallocated.
 *
 * Side effects:
 *    None.
 *
 *----------------------------------------------------------------------
 */
static void TkRootAccessible_DestroyHandler(
    void *clientData,
    XEvent *eventPtr)
{
    if (!clientData|| eventPtr->type != DestroyNotify) return;
    TkRootAccessible *tkAccessible = (TkRootAccessible *)clientData;
    if (!tkAccessible || !tkAccessible->toplevel) return;
    TkGlobalLock();

    /* Clean up MSAA table. */
    if (tkAccessibleTableInitialized) {
	Tcl_HashEntry *entry = Tcl_FindHashEntry(tkAccessibleTable, tkAccessible->toplevel);
	if (entry) {
	    Tcl_DeleteHashEntry(entry);
	}
    }

    ClearChildIdTableForToplevel(tkAccessible->toplevel);
    TkRootAccessible_Release((IAccessible *)tkAccessible);
    TkGlobalUnlock();
}

/*
 *----------------------------------------------------------------------
 *
 * EmitFocusChanged --
 *
 * Accessibility system notification when focus changed.
 *
 * Results:
 *    Accessibility system is made aware when focus is changed.
 *
 * Side effects:
 *    None.
 *
 *----------------------------------------------------------------------
 */
static int EmitFocusChanged(
    TCL_UNUSED(void *), /* cd */
    Tcl_Interp *interp,
    int objc,
    Tcl_Obj *const objv[])
{
    if (objc < 2) {
	Tcl_WrongNumArgs(interp, 1, objv, "window");
	return TCL_ERROR;
    }
    const char *path = Tcl_GetString(objv[1]);
    Tk_Window win = Tk_NameToWindow(interp, path, Tk_MainWindow(interp));
    if (!win) {
	Tcl_SetResult(interp, "Invalid window name", TCL_STATIC);
	return TCL_OK;
    }
    Tk_MakeWindowExist(win);
    Tk_Window toplevel = GetToplevelOfWidget(win);
    if (!toplevel || !Tk_IsTopLevel(toplevel)) {
	Tcl_SetResult(interp, "Window must be in a toplevel", TCL_STATIC);
	return TCL_OK;
    }
    TkGlobalLock();
    Tcl_HashTable *childIdTable = GetChildIdTableForToplevel(toplevel);
    if (!childIdTable) {
	Tcl_SetResult(interp, "Failed to get child ID table for toplevel", TCL_STATIC);
	TkGlobalUnlock();
	return TCL_OK;
    }
    ClearChildIdTableForToplevel(toplevel);
    int nextId = 1;
    AssignChildIdsRecursive(toplevel, &nextId, interp, toplevel);
    LONG childId = GetChildIdForTkWindow(win, childIdTable);
    if (childId <= 0) {
	Tcl_AppendResult(interp, "Failed to find child ID for ", path, NULL);
	TkGlobalUnlock();
	return TCL_OK;
    }
    NotifyWinEvent(EVENT_OBJECT_FOCUS, Tk_GetHWND(Tk_WindowId(toplevel)), OBJID_CLIENT, childId);
    TkGlobalUnlock();
    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * TkRootAccessibleObjCmd --
 *
 *    Main command for adding and managing accessibility objects to Tk
 *    widgets on Windows using the Microsoft Active Accessibility API.
 *
 * Results:
 *      A standard Tcl result.
 *
 * Side effects:
 *    Tk widgets are now accessible to screen readers.
 *
 *----------------------------------------------------------------------
 */
int TkRootAccessibleObjCmd(
    TCL_UNUSED(void *), /* clientData */
    Tcl_Interp *interp,
    int objc,
    Tcl_Obj *const objv[])
{
    if (objc != 2) {
	Tcl_WrongNumArgs(interp, 1, objv, "window");
	return TCL_ERROR;
    }
    char *windowName = Tcl_GetString(objv[1]);
    Tk_Window tkwin = Tk_NameToWindow(interp, windowName, Tk_MainWindow(interp));
    if (!tkwin) {
	Tcl_SetResult(interp, "Invalid window name", TCL_STATIC);
	return TCL_OK;
    }
    Tk_Window toplevel = GetToplevelOfWidget(tkwin);
    if (!toplevel || !Tk_IsTopLevel(toplevel)) {
	Tcl_SetResult(interp, "Window must be a toplevel", TCL_STATIC);
	return TCL_OK;
    }
    Tk_MakeWindowExist(toplevel);
    HWND hwnd = Tk_GetHWND(Tk_WindowId(toplevel));
    if (!hwnd) {
	Tcl_SetResult(interp, "Failed to get HWND for toplevel", TCL_STATIC);
	return TCL_OK;
    }
    TkGlobalLock();
    TkRootAccessible *accessible = CreateRootAccessible(interp, hwnd, windowName);
    if (!accessible) {
	TkGlobalUnlock();
	Tcl_SetResult(interp, "Unable to create accessible object", TCL_STATIC);
	return TCL_OK;
    }
    TkRootAccessible_RegisterForCleanup(toplevel, accessible);
    Tcl_HashTable *childIdTable = GetChildIdTableForToplevel(toplevel);
    if (!childIdTable) {
	TkRootAccessible_Release((IAccessible *)accessible);
	Tcl_SetResult(interp, "Failed to create child ID table for toplevel", TCL_STATIC);
	TkGlobalUnlock();
	return TCL_OK;
    }
    ClearChildIdTableForToplevel(toplevel);
    int nextId = 1;
    AssignChildIdsRecursive(toplevel, &nextId, interp, toplevel);
    TkGlobalUnlock();
    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * TkWinAccessiblity_Init --
 *
 *    Initializes the accessibility module.
 *
 * Results:
 *      A standard Tcl result.
 *
 * Side effects:
 *    Accessibility module is now activated.
 *
 *----------------------------------------------------------------------
 */
int TkWinAccessiblity_Init(
    Tcl_Interp *interp)
{
    /* Initialize global lock, hash tables, and main thread. */
    EnsureGlobalLockInitialized();
    TkGlobalLock();
    InitAccessibilityMainThread();
    InitTkAccessibleTable();
    InitChildIdTable();
    TkGlobalUnlock();

    /* Initialize Tcl commands. */
    Tcl_CreateObjCommand(interp, "::tk::accessible::add_acc_object", TkRootAccessibleObjCmd, NULL, NULL);
    Tcl_CreateObjCommand(interp, "::tk::accessible::emit_selection_change", EmitSelectionChanged, NULL, NULL);
    Tcl_CreateObjCommand(interp, "::tk::accessible::emit_focus_change", EmitFocusChanged, NULL, NULL);
    Tcl_CreateObjCommand(interp, "::tk::accessible::check_screenreader", IsScreenReaderRunning, NULL, NULL);
    return TCL_OK;
}

/*
 * Local Variables:
 * mode: c
 * c-basic-offset: 4
 * fill-column: 78
 * End:
 */