Tk Source Code

Check-in [f5796a3e]
Login

Many hyperlinks are disabled.
Use anonymous login to enable hyperlinks.

Overview
Comment:Substantial attempt to track non-root toplevels and their child widgets in the accessibility hierarchy
Downloads: Tarball | ZIP archive
Timelines: family | ancestors | descendants | both | tka11y
Files: files | file ages | folders
SHA3-256: f5796a3e45c5a9c865c444411af082feef8b05af7452b2be0fe7f5bb6c57d183
User & Date: kevin_walzer 2025-06-26 03:59:00.060
Context
2025-06-26
04:35
Revert unintended indentation changes check-in: fd50f006 user: kevin_walzer tags: tka11y
03:59
Substantial attempt to track non-root toplevels and their child widgets in the accessibility hierarchy check-in: f5796a3e user: kevin_walzer tags: tka11y
2025-06-25
17:56
Minor cleanup check-in: 52e5bdba user: kevin_walzer tags: tka11y
Changes
Unified Diff Ignore Whitespace Patch
Changes to library/accessibility.tcl.
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
		    focus -force $w
		}
	    } else {
		return
	    }
	}
	if {[tk windowingsystem] eq "win32"} {
	    after idle ::tk::accessible::emit_focus_change $w
	}
    }
    
    # Set initial accessible attributes and add binding to <Map> event.
    # If the accessibility role is already set, return because
    # we only want these to fire once.
    







|







239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
		    focus -force $w
		}
	    } else {
		return
	    }
	}
	if {[tk windowingsystem] eq "win32"} {
	    ::tk::accessible::emit_focus_change $w
	}
    }
    
    # Set initial accessible attributes and add binding to <Map> event.
    # If the accessibility role is already set, return because
    # we only want these to fire once.
    
554
555
556
557
558
559
560





561
562
563
564
565
566
567
568
569
					       Notebook \
					       [%W tab current -text] \
					       {} \
					       {}\
					   }

    # Activate accessibility object when mapped.





	bind all <Map> {+::tk::accessible::add_acc_object %W}
  
    # Various bindings to capture data/selection changes for
    # widgets that support returning a value. 

    #Selection changes.
    bind Listbox <<ListboxSelect>> {+::tk::accessible::_updateselection %W} 
    bind Treeview <<TreeviewSelect>> {+::tk::accessible::_updateselection %W}
    bind TCombobox <<ComboboxSelected>> {+::tk::accessible::_updateselection %W}







>
>
>
>
>
|
|







554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
					       Notebook \
					       [%W tab current -text] \
					       {} \
					       {}\
					   }

    # Activate accessibility object when mapped.
    if {[tk windowingsystem] eq "win32"} {
	bind Toplevel <Map> {
	    after 0 [list ::tk::accessible::add_acc_object %W]
	}
    }
    bind all <Map> {+::tk::accessible::add_acc_object %W}
    
    # Various bindings to capture data/selection changes for
    # widgets that support returning a value. 

    #Selection changes.
    bind Listbox <<ListboxSelect>> {+::tk::accessible::_updateselection %W} 
    bind Treeview <<TreeviewSelect>> {+::tk::accessible::_updateselection %W}
    bind TCombobox <<ComboboxSelected>> {+::tk::accessible::_updateselection %W}
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
    bind TScrollbar <Map> {+::tk::accessible::acc_help %W "Use the touchpad or mouse wheel to move the scrollbar."}
    bind Menubutton <Map> {+::tk::accessible::acc_help %W "Use the touchpad or mouse wheel to pop up the menu."}
    bind TMenubutton <Map> {+::tk::accessible::acc_help %W "Use the touchpad or mouse wheel to pop up the menu."}
    bind TNotebook <Map> {+::tk::accessible::acc_help %W "Use the Tab and Right/Left arrow keys to navigate between notebook tabs."}
    bind Text <Map> {+::tk::accessible::acc_help %W "Use normal keyboard shortcuts to navigate the text widget."}
    
    if {[tk windowingsystem] eq "win32"} {
	 bind all <FocusIn> {+::tk::accessible::_forceTkFocus %W}
    }
	
    
    # Finally, export the main commands.
    namespace export acc_role acc_name acc_description acc_value acc_state acc_action acc_help get_acc_role get_acc_name get_acc_description get_acc_value get_acc_state get_acc_action get_acc_help add_acc_object emit_selection_change check_screenreader
    namespace ensemble create
}

# Add these commands to the tk command ensemble: tk accessible.
namespace ensemble configure tk -map \
    [dict merge [namespace ensemble configure tk -map] \
	 {accessible ::tk::accessible}]










|

|













644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
    bind TScrollbar <Map> {+::tk::accessible::acc_help %W "Use the touchpad or mouse wheel to move the scrollbar."}
    bind Menubutton <Map> {+::tk::accessible::acc_help %W "Use the touchpad or mouse wheel to pop up the menu."}
    bind TMenubutton <Map> {+::tk::accessible::acc_help %W "Use the touchpad or mouse wheel to pop up the menu."}
    bind TNotebook <Map> {+::tk::accessible::acc_help %W "Use the Tab and Right/Left arrow keys to navigate between notebook tabs."}
    bind Text <Map> {+::tk::accessible::acc_help %W "Use normal keyboard shortcuts to navigate the text widget."}
    
    if {[tk windowingsystem] eq "win32"} {
	bind all <FocusIn> {+::tk::accessible::_forceTkFocus %W}
    }
    
    
    # Finally, export the main commands.
    namespace export acc_role acc_name acc_description acc_value acc_state acc_action acc_help get_acc_role get_acc_name get_acc_description get_acc_value get_acc_state get_acc_action get_acc_help add_acc_object emit_selection_change check_screenreader
    namespace ensemble create
}

# Add these commands to the tk command ensemble: tk accessible.
namespace ensemble configure tk -map \
    [dict merge [namespace ensemble configure tk -map] \
	 {accessible ::tk::accessible}]



Changes to win/tkWinAccessibility.c.
1
2
3
4
5
6
7
8
9
10
11
12
/*
 * tkWinAccessibility.c --
 *
 *	  This file implements the platform-native Microsoft Active 
 *	  Accessibility API for Tk on Windows.  
 *
 * Copyright (c) 2024-2025 Kevin Walzer/WordTech Communications LLC.
 *
 * See the file "license.terms" for information on usage and redistribution of
 * this file, and for a DISCLAIMER OF ALL WARRANTIES.
 *
 */



|
|







1
2
3
4
5
6
7
8
9
10
11
12
/*
 * tkWinAccessibility.c --
 *
 *	  This file implements the platform-native Microsoft Active
 *	  Accessibility API for Tk on Windows.
 *
 * Copyright (c) 2024-2025 Kevin Walzer/WordTech Communications LLC.
 *
 * See the file "license.terms" for information on usage and redistribution of
 * this file, and for a DISCLAIMER OF ALL WARRANTIES.
 *
 */
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
#include <windows.h>
#include <stdarg.h>
#include <stdio.h>

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

/* Define the GUID for the MSAA interface. */
DEFINE_GUID(IID_IAccessible, 0x618736e0, 0x3c3d, 0x11cf, 0x81, 0xc, 0x0, 0xaa, 0x0, 0x38, 0x9b, 0x71);





/* 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. 
 */
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},
    {"Menu", ROLE_SYSTEM_MENUPOPUP},
    {"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},
    {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 int tkAccessibleTableInitialized = 0;
static Tcl_HashTable *hwndToTkWindowTable;
static int hwndToTkWindowTableInitialized = 0;
static Tcl_HashTable *childIdTable = 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 Tcl_Interp *accessibleInterp = NULL;
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);







|






>
>
>
>









|
|
|
|
|
|
|
|
|



|
|


|
|



|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|








<
<






|
|
|
|
|








<



|
|
|








|







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
#include <windows.h>
#include <stdarg.h>
#include <stdio.h>

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

/* Define the GUID for the MSAA interface. */
DEFINE_GUID(IID_IAccessible, 0x618736e0, 0x3c3d, 0x11cf, 0x81, 0xc, 0x0, 0xaa, 0x0, 0x38, 0x9b, 0x71);

/* Define array size for non-root toplevels. */
#define MAX_EXTRA_TOPLEVELS 20
#define SYNTHETIC_CHILD_BASE 1000

/* 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.
 */
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},
  {"Menu", ROLE_SYSTEM_MENUPOPUP},
  {"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},
  {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 int tkAccessibleTableInitialized = 0;


static Tcl_HashTable *childIdTable = 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);
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
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 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 HRESULT TkAccState(Tk_Window win, VARIANT *pvarState);
static HRESULT TkAccFocus(int num_args, void **args);







|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|






|







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
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 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 HRESULT TkAccState(Tk_Window win, VARIANT *pvarState);
static HRESULT TkAccFocus(int num_args, void **args);
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
HRESULT HandleWMGetObjectOnMainThreadVaList(va_list 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 InitHwndToTkWindowTable(void);
void InitChildIdTable(void);
void ClearChildIdTable(void);
TkRootAccessible *GetTkAccessibleForWindow(Tk_Window win);
Tk_Window GetTkWindowForHwnd(HWND hwnd);
static TkRootAccessible *CreateRootAccessible(Tcl_Interp *interp, HWND hwnd, const char *pathName);

static void SetChildIdForTkWindow(Tk_Window win, int id);
static int GetChildIdForTkWindow(Tk_Window win);
Tk_Window GetToplevelOfWidget(Tk_Window tkwin);
Tk_Window GetTkWindowForChildId(int id);
int IsScreenReaderRunning(ClientData clientData, Tcl_Interp *interp, int argc, Tcl_Obj *const argv[]);
int EmitSelectionChanged(ClientData clientData,Tcl_Interp *ip, int objc, Tcl_Obj *const objv[]);
int EmitFocusChanged(ClientData clientData,Tcl_Interp *ip, int objc, Tcl_Obj *const objv[]);
void TkRootAccessible_RegisterForCleanup(Tk_Window tkwin, void *tkAccessible);
static void TkRootAccessible_DestroyHandler(ClientData clientData, XEvent *eventPtr);
static void AssignChildIdsRecursive(Tk_Window win, int *nextId, Tcl_Interp *interp);
void InitAccessibilityMainThread(void);
int TkRootAccessibleObjCmd(ClientData 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( IAccessible *this, BSTR *pszHelpFile, VARIANT varChild, long *pidTopic)
{
    return E_NOTIMPL;
}

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

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

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

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

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

HRESULT STDMETHODCALLTYPE TkRootAccessible_put_accValue(IAccessible *this, VARIANT varChild, 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 (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)
{
    TkRootAccessible *tkAccessible = (TkRootAccessible *)this;
    return InterlockedIncrement(&tkAccessible->refCount);
}

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

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

    *pctinfo = 1; /* We provide one type information interface. */
    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(IAccessible *this, UINT iTInfo, LCID lcid, ITypeInfo **ppTInfo)
{
    if (!ppTInfo) {
	return E_POINTER;
    }
    *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, REFIID riid, LPOLESTR *rgszNames, UINT cNames, LCID lcid, DISPID *rgDispId)
{
    ITypeInfo *pTypeInfo = NULL;
    HRESULT hr;

    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, REFIID riid, LCID lcid, WORD wFlags, DISPPARAMS *pDispParams, VARIANT *pVarResult, EXCEPINFO *pExcepInfo, UINT *puArgErr)
{
    IDispatch* pDisp = NULL;
    
    {
	if (!pVarResult) {
	    return E_POINTER;
	}

	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.*/
static HRESULT STDMETHODCALLTYPE TkRootAccessible_get_accName(IAccessible *this, VARIANT varChild, BSTR *pName)
{
    if (!pName) return E_INVALIDARG;
    /*
     * No need to return name; same as role 
     * and screen readers read it twice. 
     */
    TkRootAccessible *tkAccessible = (TkRootAccessible *)this;
    pName = NULL;
    return S_OK;
}

/* 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);





	if (!child) {
	    TkGlobalUnlock();
	    return E_INVALIDARG;
	}
	




	HRESULT hr = TkAccRole(child, pvarRole);






	TkGlobalUnlock();
	return hr; 

    }



    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);
	
	if (!child) {
	    TkGlobalUnlock();	  
	    return E_INVALIDARG;
	}
	HRESULT hr = TkAccState(child, pvarState);
	TkGlobalUnlock();
	return hr;
    }

    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);
	if (!child) {
	    TkGlobalUnlock();	  
	    return E_INVALIDARG;
	}
	HRESULT hr = TkAccValue(child, pszValue);
	TkGlobalUnlock();
	return hr;
    }

    return DISP_E_MEMBERNOTFOUND;
}

/* Function to get accessible parent. For toplevel, return NULL. */
static HRESULT STDMETHODCALLTYPE TkRootAccessible_get_accParent(IAccessible *this, IDispatch **ppdispParent) 
{

    TkRootAccessible *tkAccessible = (TkRootAccessible *)this;

    /* For toplevel, set ppdispParent to NULL and return S_OK. */
    *ppdispParent = NULL;
    return S_OK;
}

/* Function to get number of accessible children to MSAA. */
static HRESULT STDMETHODCALLTYPE TkRootAccessible_get_accChildCount(IAccessible *this, LONG *pcChildren)
{


    TkGlobalLock();
    TkRootAccessible *tkAccessible = (TkRootAccessible *)this;
	






    int count = TkAccChildCount(tkAccessible->win);
    TkGlobalUnlock();
     



    if (count < 0) {


	*pcChildren = 0;
	return S_FALSE; 
    } 
  
    *pcChildren = 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;

    /* We only support VT_I4 child IDs */
    if (varChild.vt != VT_I4 || varChild.lVal <= 0) {
	return E_INVALIDARG;
    }


    /* Lookup child Tk_Window for this ID. */
    TkGlobalLock();
    TkRootAccessible *tkAccessible = (TkRootAccessible *)this;


    ClearChildIdTable();     
    Tk_Window toplevel = GetToplevelOfWidget(tkAccessible->win);
    int nextId = 1;
    AssignChildIdsRecursive(toplevel, &nextId, accessibleInterp);
    Tk_Window childWin = GetTkWindowForChildId(varChild.lVal);
    if (!childWin) {
	TkGlobalUnlock();
	return E_INVALIDARG;
    }

	










    TkGlobalUnlock();


    /* 
     * MSAA expects only VT_DISPATCH if the child is *an object* — we don’t 
     * return that.  So we just say "this ID is valid but not an object". 

     * MSAA will then call get_accName/Role/etc. with that ID).
     */







    return S_FALSE;  /* Child exists but is not an object (per MSAA spec). */

























}

/* 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 (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);
	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 focus on Tk widget. For toplevel, just return. */
static HRESULT STDMETHODCALLTYPE TkRootAccessible_accSelect(IAccessible *thisPtr, long flags, 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. For toplevel, just return. */
static HRESULT STDMETHODCALLTYPE TkRootAccessible_accDoDefaultAction(IAccessible *this, VARIANT varChild)
{
    if (varChild.vt == VT_I4 && varChild.lVal == CHILDID_SELF) {
        return S_OK;
    }

    if (varChild.vt == VT_I4 && varChild.lVal > 0) {
	/* Pass childId to main thread. */
	mainThreadResult = E_FAIL;
	MainThreadFunc func = (MainThreadFunc)TkDoDefaultAction;
	int childId = varChild.lVal;
	RunOnMainThreadSync(func, 1, (void*)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 (varChild.vt == VT_I4 && varChild.lVal > 0) {  
	Tk_Window child = GetTkWindowForChildId(varChild.lVal);
	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); /* Initialize the VARIANT to VT_EMPTY.*/

    HWND hwnd = NULL;
    TkGlobalLock();
    TkRootAccessible *tkAccessible = (TkRootAccessible *)this;
    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 (varChild.vt == VT_I4 && varChild.lVal == CHILDID_SELF) {
	/* Toplevel window. */
	*pszDescription = L"Window";
	TkGlobalUnlock();
	return S_OK;
    }






    if (varChild.vt == VT_I4 && varChild.lVal > 0) {  
	Tk_Window child = GetTkWindowForChildId(varChild.lVal);
	if (!child) {
	    TkGlobalUnlock();	
	    return E_INVALIDARG;
	}
	HRESULT hr = TkAccDescription(child, pszDescription);
	TkGlobalUnlock();
	return hr;
    }

    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;
    }	  

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

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

    const char *tkrole = Tcl_GetString(Tcl_GetHashValue(hPtr2));
    int role = ROLE_SYSTEM_CLIENT; /* Fallback. */

    for (int i = 0; roleMap[i].tkrole != NULL; i++) {
	if (strcmp(tkrole, roleMap[i].tkrole) == 0) {
	    role = roleMap[i].winrole;
	    break;
	}
    }
    pvarRole->vt = VT_I4;
    pvarRole->lVal = role;

    return S_OK;
}

/* 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);
    Tcl_HashEntry *hPtr2 = Tcl_FindHashEntry(AccessibleAttributes, "state");

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

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

    /* Check if this widget has focus. */
    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, int flags)
{
    (void) flags;
    ActionEvent *event = (ActionEvent *)ev;
	
    /* Make sure key fields are not NULL. */
    if (!event || !event->win || !event->command) {
	return 1;
    }

    /*
     * Get the interpreter associated with this Tk_Window. 
     * This is critical to ensure correct command processing - 
     * if the interpreter is a different one, the command will
     * silently fail. 
     */
    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 HRESULT TkDoDefaultAction(int num_args, void **args)
{

    int childId = (int)args[0];
    ActionEvent *event = NULL; 

    HRESULT result = S_FALSE; 

    if (!childId  || !accessibleInterp) {
	result = E_INVALIDARG;
	mainThreadResult = result;
	return mainThreadResult;
    }

    Tk_Window win = GetTkWindowForChildId(childId);
    if (!win) {
	result = E_INVALIDARG;
	mainThreadResult = result;
	return mainThreadResult;
    }
		
    Tcl_HashEntry *hPtr = Tcl_FindHashEntry(TkAccessibilityObject, (char *)win);
    if (!hPtr) {
	result = E_INVALIDARG;
	mainThreadResult = result;
	return mainThreadResult;
    }

    Tcl_HashTable *AccessibleAttributes = (Tcl_HashTable *)Tcl_GetHashValue(hPtr);
    if (!AccessibleAttributes) {
	result = E_INVALIDARG;
	mainThreadResult = result;
	return mainThreadResult;
    }

    Tcl_HashEntry *hPtr2 = Tcl_FindHashEntry(AccessibleAttributes, "action");
    if (!hPtr2) {
	result = E_INVALIDARG;
	mainThreadResult = result;
	return mainThreadResult;
    }
	
    const char *action = Tcl_GetString(Tcl_GetHashValue(hPtr2));
    if (!action) {
	result = E_INVALIDARG;
	mainThreadResult = result;
	return mainThreadResult;
    }
    
    event = (ActionEvent *)ckalloc(sizeof(ActionEvent));
    if (event == NULL) {
	result = E_OUTOFMEMORY;
	mainThreadResult = result;
	return mainThreadResult;
    }

    event->header.proc = ActionEventProc;
    const char *cmd = action; 
    event->command = ckalloc(strlen(cmd) + 1);
    strcpy(event->command, cmd); 
    event->win = win; 
    Tcl_QueueEvent((Tcl_Event *)event, TCL_QUEUE_TAIL);
    result = S_OK;

    mainThreadResult = result;
    return result;
}

/* Function to get MSAA focus. */
static HRESULT TkAccFocus(int num_args, void **args)
{
    HWND hwnd = (HWND)args[0];
    VARIANT *pvarChild = (VARIANT*)args[1]; 
    Tk_Window win = GetTkWindowForHwnd(hwnd);  /* Now running on main thread — safe. */
    if (!win || !pvarChild) return E_INVALIDARG;
	   
    /* Get the current Tk focus window.*/
    TkWindow *focusPtr = TkGetFocusWin((TkWindow *)win);
    Tk_Window focusWin = (Tk_Window)focusPtr;

    /* If no focus, or focus is on the root window itself. */
    if (!focusWin || focusWin == win) {
	pvarChild->vt = VT_I4;
	pvarChild->lVal = CHILDID_SELF;
	return S_OK;
    }

    /* Ensure child IDs are up-to-date before looking up. */
    TkGlobalLock();
    ClearChildIdTable();
    int nextId = 1; /* Child IDs start from 1. */
    TkRootAccessible *tkAccessible = GetTkAccessibleForWindow(win);
    AssignChildIdsRecursive(tkAccessible->win, &nextId, accessibleInterp);

    /* Look up ID for the focused child.*/
    int childId = GetChildIdForTkWindow(focusWin);

    if (childId > 0) {
	pvarChild->vt = VT_I4;
	pvarChild->lVal = childId;
	TkGlobalUnlock();
	return S_OK;
    } else {
	/* Fallback if child was focused but not found in ID table. */
	pvarChild->vt = VT_I4;
	pvarChild->lVal = CHILDID_SELF; /* Indicate no specific child focus found. */
	TkGlobalUnlock();
	return S_OK; 
    }
}

/* 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) 
{
    int count = 0;
  
    TkWindow *child = (TkWindow*)win;
    Tk_Window toplevel = GetToplevelOfWidget(win);
    TkWindow *winPtr = (TkWindow *)toplevel;
    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)
{
    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
 * the Tcl script-level API. 
 *
 *----------------------------------------------------------------------
 */

/* Function to map Tk window to MSAA attributes. */
static TkRootAccessible *CreateRootAccessible(Tcl_Interp *interp, HWND hwnd, const char *pathName)
{
	
    TkRootAccessible *tkAccessible = (TkRootAccessible *)ckalloc(sizeof(TkRootAccessible));
  
    Tk_Window win = Tk_NameToWindow(interp, pathName, Tk_MainWindow(interp));
	Tk_MakeWindowExist(win);
	
    if (tkAccessible) {
	tkAccessible->lpVtbl = &tkRootAccessibleVtbl;
	tkAccessible->interp = interp;
	tkAccessible->hwnd = hwnd;
	tkAccessible->pathName = pathName;
	tkAccessible->refCount = 1;
	tkAccessible->win = win;
    }
  
    /*Add objects to hash tables. */
    Tcl_HashEntry *entry;
    int newEntry;
    entry = Tcl_CreateHashEntry(tkAccessibleTable, win, &newEntry);
    Tcl_SetHashValue(entry, tkAccessible);
  
    entry = Tcl_CreateHashEntry(hwndToTkWindowTable, hwnd, &newEntry);
    Tcl_SetHashValue(entry, win);
  
    TkRootAccessible_AddRef((IAccessible*)tkAccessible); 

    /* Notify screen readers of creation. */







    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)
{
    if (!childIdTable) {
	childIdTable = (Tcl_HashTable *)ckalloc(sizeof(Tcl_HashTable));
	Tcl_InitHashTable(childIdTable, TCL_ONE_WORD_KEYS);
    }

    Tcl_HashEntry *entry;
    int newEntry;

    entry = Tcl_CreateHashEntry(childIdTable, (ClientData)win, &newEntry);
    Tcl_SetHashValue(entry, INT2PTR(id));
  
}

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

/* Function to retrieve Tk window for a specifc MSAA ID. */
Tk_Window GetTkWindowForChildId(int id)
{
    if (!childIdTable){	  
	return NULL;
    }	  

    Tcl_HashSearch search;
    Tcl_HashEntry *entry;
    for (entry = Tcl_FirstHashEntry(childIdTable, &search);
	 entry != NULL;
	 entry = Tcl_NextHashEntry(&search)) {
	if (PTR2INT(Tcl_GetHashValue(entry)) == id) {	
	    return (Tk_Window)Tcl_GetHashKey(childIdTable, entry);
	}
    }
    return NULL;
}

/* Function to return the Tk toplevel window that contains a given Tk widget. */
Tk_Window GetToplevelOfWidget(Tk_Window tkwin)
{
       	
    /* First check if the tkwin is NULL (destroyed). If yes, exit. */
    if (tkwin == NULL) {	  
	return NULL;
    }

    /*Tk window exists. Now look for toplevel. If no parent found, return null. */
    Tk_Window current = tkwin;
    while (current != NULL && Tk_WindowId(current) != None) {
	Tk_Window parent = Tk_Parent(current);
	if (parent == NULL) {
	    break;
	}
	current = parent;
    }
    return current;
}

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

/* Function to initialize HWND -> Tk hash table. */
void InitHwndToTkWindowTable(void) {
	
    if (!hwndToTkWindowTableInitialized) {
	hwndToTkWindowTable = (Tcl_HashTable *)ckalloc(sizeof(Tcl_HashTable));
	Tcl_InitHashTable(hwndToTkWindowTable, TCL_ONE_WORD_KEYS);
	hwndToTkWindowTableInitialized = 1;
    }
}


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

/* Function to clear childId hash table. */
void ClearChildIdTable(void)
{
    if (!childIdTable) {	  
	return;
    }

    Tcl_HashSearch search;
    Tcl_HashEntry *entry;

    for (entry = Tcl_FirstHashEntry(childIdTable, &search); entry != NULL; entry = Tcl_NextHashEntry(&search)) {
	Tcl_DeleteHashEntry(entry);
    }  
}

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

/* Function to retrieve Tk window associated with HWND. */
Tk_Window GetTkWindowForHwnd(HWND hwnd) {
	      		
    if (!hwndToTkWindowTableInitialized) {	  
	return NULL;
    }
  
    Tcl_HashEntry *entry = Tcl_FindHashEntry(hwndToTkWindowTable, (ClientData)hwnd);
    if (entry) {	  
	return (Tk_Window)Tcl_GetHashValue(entry);
    }
  
    return NULL;
}

/* Function to assign childId's dynamically. */
static void AssignChildIdsRecursive(Tk_Window win, int *nextId, Tcl_Interp *interp)
{
	
    if (!Tk_IsMapped(win)){
	return;
    }

    /* Assign an ID to this widget. */
    SetChildIdForTkWindow(win, (*nextId)++);

    /* Recurse into children. */
    TkWindow *winPtr = (TkWindow *)win;
    for (TkWindow *child = winPtr->childList; child != NULL; child = child->nextPtr) {
	AssignChildIdsRecursive((Tk_Window)child, nextId, interp);
    }
}

/* Handle WM_GETOBJECT call on main thread. */
void HandleWMGetObjectOnMainThread(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;
    }

    if ((LONG)lParam == OBJID_CLIENT) {
        Tk_Window tkwin = GetTkWindowForHwnd(hwnd);
        if (tkwin) {
            TkRootAccessible *acc = GetTkAccessibleForWindow(tkwin);
            if (acc) {
                *outResult = LresultFromObject(&IID_IAccessible, wParam, (IUnknown *)acc);
                return;
            }
        }
    }
}

/* Event handler that executes on main thread */
int ExecuteOnMainThreadSync(Tcl_Event *ev, int flags) 
{
    MainThreadSyncEvent *event = (MainThreadSyncEvent *)ev;
    
    /* Execute with appropriate arguments. */
    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;
    }
    
    /* Signal completion and clean up. */
    SetEvent(event->doneEvent);
    ckfree(event);
    return 1;
}

/* Synchronous execution with variable arguments */
void RunOnMainThreadSync(MainThreadFunc func, int num_args, ...) 
{
    /* If already on the main thread, call function directly. */
    if (Tcl_GetCurrentThread() == mainThreadId) {
        void *args[6];  /*Support up to 6 args here.*/
        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;
    }
	
    /* Otherwise, allocate and initialize event. */
    MainThreadSyncEvent *event = (MainThreadSyncEvent *)ckalloc(sizeof(MainThreadSyncEvent));
    event->header.proc = ExecuteOnMainThreadSync ;
    event->func = func;
    event->num_args = num_args;
    event->doneEvent = CreateEvent(NULL, TRUE, FALSE, NULL);

    /* Extract variable arguments. */
    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);

    /* Queue and wait for completion. */
    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(PINIT_ONCE InitOnce, PVOID param, 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(
			  ClientData clientData,
			  Tcl_Interp *interp, /* Current interpreter. */
			  int argc, /* Number of arguments. */
			  Tcl_Obj *const argv[]) /* Argument objects. */
{
    /*
     * MSVC complains if this parameter is stubbed out
     * with TCL_UNUSED.
     */
    (void) clientData;
	
    BOOL screenReader = FALSE;
    SystemParametersInfo(SPI_GETSCREENREADER, 0, &screenReader, 0);
    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(
		     ClientData clientData,
		     Tcl_Interp *ip,		/* Current interpreter. */
		     int objc,			/* Number of arguments. */
		     Tcl_Obj *const objv[])	/* Argument objects. */
{
    /*
     * MSVC complains if this parameter is stubbed out
     * with TCL_UNUSED.
     */
    (void) clientData;
	
  
    if (objc < 2) {
	Tcl_WrongNumArgs(ip, 1, objv, "window?");
	return TCL_ERROR;
    }
    Tk_Window path;
	
    path = Tk_NameToWindow(ip, Tcl_GetString(objv[1]), Tk_MainWindow(ip));
    if (path == NULL) {
	Tk_MakeWindowExist(path);

    }
	







    /* Fire notification of new value. */
    HWND hwnd = Tk_GetHWND(Tk_WindowId(path));   
    NotifyWinEvent(EVENT_OBJECT_VALUECHANGE, hwnd, OBJID_CLIENT, 0);
	
    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)
{
    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(ClientData clientData, XEvent *eventPtr)
{
		
    if (eventPtr->type == DestroyNotify) {
	TkGlobalLock();
	TkRootAccessible *tkAccessible = (TkRootAccessible *)clientData;
	Tk_Window win = tkAccessible->win; 
	if (tkAccessible) {
	    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(ClientData 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) return TCL_ERROR;

    Tk_MakeWindowExist(win);
    Tk_Window toplevel = GetToplevelOfWidget(win);
    HWND hwnd = Tk_GetHWND(Tk_WindowId(toplevel));

    TkGlobalLock();
    ClearChildIdTable(); 
    int nextId = 1;
    AssignChildIdsRecursive(toplevel, &nextId, interp);

    LONG childId = GetChildIdForTkWindow(win);

    if (childId <= 0) {
	Tcl_AppendResult(interp, "Failed to find child ID for ", path, NULL);
	TkGlobalUnlock();
	return TCL_OK;
    }

    NotifyWinEvent(EVENT_OBJECT_FOCUS, hwnd, 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(
			   ClientData clientData,
			   Tcl_Interp *interp, /* Current interpreter. */
			   int objc, /* Number of arguments. */
			   Tcl_Obj *const objv[]) /* Argument objects. */
{
	
    (void) clientData;
    HWND hwnd = NULL;

    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));
	Tk_MakeWindowExist(tkwin);

    if (tkwin == NULL) {
	Tcl_SetResult(interp, "Invalid window name.", TCL_STATIC);
	return TCL_ERROR;
    }
  
    if (Tk_IsTopLevel(tkwin)) { 
	hwnd = Tk_GetHWND(Tk_WindowId(tkwin)); 
    } else {
	/* 
	 * The accessible root is typically the toplevel window, but support
	 * child widgets just in case. 
	 */
	Tk_Window toplevel = GetToplevelOfWidget(tkwin);




	hwnd = Tk_GetHWND(Tk_WindowId(toplevel)); 
    }

    TkGlobalLock();






    TkRootAccessible *accessible = CreateRootAccessible(interp, hwnd, windowName);


    TkRootAccessible_RegisterForCleanup(tkwin, accessible);
	
    if (accessible == NULL) {		
	Tcl_SetResult(interp, "Failed to create accessible object.", TCL_STATIC);
	return TCL_ERROR;
    }

    /* Initial assignment of child IDs right after creating the root accessible. */
    ClearChildIdTable(); /* Clear any previous IDs. */
    int nextId = 1;

    AssignChildIdsRecursive(tkwin, &nextId, interp); /* Assign IDs starting from the 'tkwin' (which should be the toplevel). */
    TkGlobalUnlock();


















    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * TkWinAccessibility_Init --
 *
 *	Initializes the accessibility module.
 *
 * Results:
 *
 *      A standard Tcl result.
 *
 * Side effects:
 *
 *	Accessibility module is now activated.
 *
 *----------------------------------------------------------------------
 */

int TkWinAccessiblity_Init(Tcl_Interp *interp)
{	





    /*Set base interpreter for accessing on main thread. */
    accessibleInterp = interp; 



    /*Initialize object-tracking hash tables. */	
    EnsureGlobalLockInitialized();
    TkGlobalLock();
    InitAccessibilityMainThread();
    InitTkAccessibleTable();







    InitHwndToTkWindowTable();
















    TkGlobalUnlock();
  
    /*Create Tcl commands. */
    Tcl_CreateObjCommand(accessibleInterp, "::tk::accessible::add_acc_object", TkRootAccessibleObjCmd, NULL, NULL);
    Tcl_CreateObjCommand(accessibleInterp, "::tk::accessible::emit_selection_change", EmitSelectionChanged, NULL, NULL);
    Tcl_CreateObjCommand(accessibleInterp, "::tk::accessible::emit_focus_change", EmitFocusChanged, NULL, NULL);
    Tcl_CreateObjCommand(accessibleInterp, "::tk::accessible::check_screenreader", IsScreenReaderRunning, NULL, NULL);

    return TCL_OK;
}

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









|






<




|
>


















|








|




|




|




|




|




|




|





|







|
|
|
|
|
|
|





|
|





|
|
|
|
|
|
|
|
|
|
|
|
|
|





|
|
|

|
|


|
|
|



|
|
|
|

|
|
|

|
|
|
|
|

|
|
|
|
|
|

|
|


|
|
|




|
|

|
|
|
|

|
|

|





|
|
|
|
|
|

|

|
|
|

|
|
|

|
|

|
|

|
|

|
|

|
|

|
|
|
|
|

|
|
|
|
|





|
|
|
|
|
|
|
|





|
>
|
>
>
>
|
>
>
>
>
|
|
>
|

|
>
>
>
>
|
>
|

|
|
|
>
>
>
>
|
<
|
|
|
|
>
>
>
>
|
>
>
>
>
>
>

|
>

|
>
>
|





|

|
|
|
|
|
|
|
|

>
>
>
>
>
|
|
|
|
|
|
|
|
|
|
|
|

|





|

|
|
|
|
|
|
|

>
>
>
>
>
|
|
|
|
|
|
|
|
|
|
|

|



|


|

|
|
|





>

|
|
|
>
>
>
>
>
>
|
|
|
>
>
>
|
>
>
|
<
|
|
|
>
|

<




|
|

<
|
|
|

<
<
|
|
>
>
|
<
|
|
<
<
<
<
|
>
|
>
>
>
>
>
>
>
>
>
>
|
|
>
|
<
|
>
|
|
>
>
|
>
>
>
>
|
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>





|
|

|
|

|
|
|
|

|
|

|
|
|
|
|
|
|

>
>
>
>
>
|
|
|
|
|
|
|

|
|
|
|
|
|
|
|
|
|
|
|
|



|

|





|
|

|

|
|
|

|
|
|
|
|
|
>
>
>
>
>
|
|
|
|
|
|
|

|
|
|
|
|
|
|

|
|
|

|
|
|
|

|
|
|

|

|
|
|
|
|

|
|





|
|
|

|
|
|
|
|
|
|
|
|






|
|
|
|
|

>
>
>
>
>
|
|
|
|
|
|
|
|
|
|
|
|
|





|
|

|
|
|
|
|

|
|
|






|
|
|
|

|
|
|
|
|
|

>
>
>
>
>
|
|
|
|
|
|
|
|
|
|

|





|




|


|
|
|
|

|
|
|
|

|
|
|
|
|

|
|

|
|
|
|
|
|
|
|

|





|
|
|

|
|
|
|
|

|
|

|

|
|
|
|
|
|

|
|
|
|
|
|
|
|
|
|





|
|
|
|
|
|
|
|
|
|

|
|
|
|
|
|

|
|
|
|
|
|
|








|
|
|
|
|
|
|

|
|
|
|
|
|
|
|
|
|

|
|
|
|
|
|
|






|
|

|

|
|
|
|
|

|
|
|
|
|
|
|
|
|
|
|
|
|

|
|
|
|
|
|

|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|

|
|
|
|
|
|
|

|
|





|
|
|
|
|
|
|
|

|
|
|
|
|
|

|
|
|
|
<
|

|
|

|
|
|
|
|
|
|
|
|
|
|
|






|
|
|

|
|

|
|
|

|
|
|
|
|
|
|






|
|
|

|
|

|
|
|

|
|
|
|
|
|
|




|

|
|
|
|
|
|
|
|
|
|
|





|

|
|
|

|
|
|
|
|
|
|
|

|







|





|

|
|
|
<
<
<
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
<
|
|
|
|
>
>
>
>
>
>
>
|
>
>
|
>
>
>
>
>
|
>
>
>
>
>
>
|
<
|
|
>
>




|
|
|
|

|
|

|
|
|





|
|
|
|
|
|
|
|
|





|
|
|

|
|
|
|
|
|
|
|
|
|





|
|
|
|
|

|
|
|
|
|
|
|
|
|
|




|
|
|
|
|
|
|


<
<
<
<
<
<
<
<
<
<
<


|
|
|
|
|





|
|
|

|
|

|
|
|




|
|
|
|
|
|
|
|
|
|
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<





|
|
|
|

|
|

|
|
|
|
|




|
|
|
|

|
|
|

|
|
|
|
|
|
|
|
|
|



|

|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|


|
|

|
|
|
|
|
|
|
|
|

|
|
|
|
|
|
|
|
|
|

|
|
|
|
|
|
|

|
|
|
|
|
|
|
|
|




|



|

|
|



|

|


|
|
|







|


|













|
|
|
|
|
|
|
|
|
|
|










|














|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
>
|
|
>
>
>
>
>
>
>
|
<
|
|
|











|









|
|










|









|
|
|
|
|
|
|
|
|
|
|










|







|
|
|
|
|
|

|
|
|

<
|
|

|
|
|
|

|

|
|
|
|
|

|
|
|








|



|














|
|
|

|
|
|
|

|
|
<

|
|
|
|
|
<
<
<
<
<
<
<
|
>
>
>
>
|
|

|
>
>
>
>
>
>
|
>
>
|
|
|
|
|
|

|
|
|
>
|
|

>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
|











|









|
>

>
>
>
|
|
>
>

|
|
|
|
|
>
>
>
>
>
>
>
|
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
|
|
|
|
|
|
|

|

<
<
<
<
<
<
<
<
<


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
HRESULT HandleWMGetObjectOnMainThreadVaList(va_list 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 ClearChildIdTable(void);
TkRootAccessible *GetTkAccessibleForWindow(Tk_Window win);
Tk_Window GetTkWindowForHwnd(HWND hwnd);
static TkRootAccessible *CreateRootAccessible(Tcl_Interp *interp, HWND hwnd, Tk_Window tkwin);
static int GetExtraToplevels(Tk_Window rootWin, Tk_Window toplevels[], int maxCount);
static void SetChildIdForTkWindow(Tk_Window win, int id);
static int GetChildIdForTkWindow(Tk_Window win);
Tk_Window GetToplevelOfWidget(Tk_Window tkwin);
Tk_Window GetTkWindowForChildId(int id);
int IsScreenReaderRunning(ClientData clientData, Tcl_Interp *interp, int argc, Tcl_Obj *const argv[]);
int EmitSelectionChanged(ClientData clientData,Tcl_Interp *ip, int objc, Tcl_Obj *const objv[]);
int EmitFocusChanged(ClientData clientData,Tcl_Interp *ip, int objc, Tcl_Obj *const objv[]);
void TkRootAccessible_RegisterForCleanup(Tk_Window tkwin, void *tkAccessible);
static void TkRootAccessible_DestroyHandler(ClientData clientData, XEvent *eventPtr);
static void AssignChildIdsRecursive(Tk_Window win, int *nextId, Tcl_Interp *interp);
void InitAccessibilityMainThread(void);
int TkRootAccessibleObjCmd(ClientData 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( IAccessible *this, BSTR *pszHelpFile, VARIANT varChild, long *pidTopic)
{
  return E_NOTIMPL;
}

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

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

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

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

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

HRESULT STDMETHODCALLTYPE TkRootAccessible_put_accValue(IAccessible *this, VARIANT varChild, 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 (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)
{
  TkRootAccessible *tkAccessible = (TkRootAccessible *)this;
  return InterlockedIncrement(&tkAccessible->refCount);
}

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

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

  *pctinfo = 1; /* We provide one type information interface. */
  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(IAccessible *this, UINT iTInfo, LCID lcid, ITypeInfo **ppTInfo)
{
  if (!ppTInfo) {
    return E_POINTER;
  }
  *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, REFIID riid, LPOLESTR *rgszNames, UINT cNames, LCID lcid, DISPID *rgDispId)
{
  ITypeInfo *pTypeInfo = NULL;
  HRESULT hr;

  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, REFIID riid, LCID lcid, WORD wFlags, DISPPARAMS *pDispParams, VARIANT *pVarResult, EXCEPINFO *pExcepInfo, UINT *puArgErr)
{
  IDispatch* pDisp = NULL;

  {
    if (!pVarResult) {
      return E_POINTER;
    }

    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.*/
static HRESULT STDMETHODCALLTYPE TkRootAccessible_get_accName(IAccessible *this, VARIANT varChild, BSTR *pName)
{
  if (!pName) return E_INVALIDARG;
  /*
   * No need to return name; same as role
   * and screen readers read it twice.
   */
  TkRootAccessible *tkAccessible = (TkRootAccessible *)this;
  *pName = NULL; /* Explicitly set to NULL */
  return S_OK;
}

/* 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;
  VariantInit(pvarRole); /* Always init output. */

  TkGlobalLock();
  TkRootAccessible *tkAccessible = (TkRootAccessible *)this;

  if (varChild.vt == VT_I4) {
    LONG childId = varChild.lVal;

    if (childId == CHILDID_SELF) {
      /* The window itself. */
      pvarRole->vt = VT_I4;
      pvarRole->lVal = ROLE_SYSTEM_WINDOW;
      TkGlobalUnlock();
      return S_OK;
    }

    /* 
     * Real widget children.  Re-assign child IDs for this toplevel's 
     * hierarchy to ensure freshness.
     */
    ClearChildIdTable();
    int nextId = 1;
    AssignChildIdsRecursive(tkAccessible->win, &nextId, tkAccessible->interp);

    int widgetCount = TkAccChildCount(tkAccessible->win);
    if (childId >= 1 && childId <= widgetCount) {
      Tk_Window child = GetTkWindowForChildId(childId);
      if (child) {
	HRESULT hr = TkAccRole(child, pvarRole);
	TkGlobalUnlock();
	return hr;
      }

      TkGlobalUnlock();
      return E_INVALIDARG;
    }

    /* Synthetic toplevels (only for ".") */
    const char *path = Tk_PathName(tkAccessible->win);
    if (strcmp(path, ".") == 0 && childId >= SYNTHETIC_CHILD_BASE) {
      int index = childId - SYNTHETIC_CHILD_BASE;

      Tk_Window extraToplevels[MAX_EXTRA_TOPLEVELS];
      int extraCount = GetExtraToplevels(tkAccessible->win, extraToplevels, MAX_EXTRA_TOPLEVELS);

      if (index >= 0 && index < extraCount) {
	pvarRole->vt = VT_I4;
	pvarRole->lVal = ROLE_SYSTEM_WINDOW;
	TkGlobalUnlock();
	return S_OK;
      }
    }
  }

  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;

  /* Re-assign child IDs for this toplevel's hierarchy to ensure freshness. */
  ClearChildIdTable();
  int nextId = 1;
  AssignChildIdsRecursive(tkAccessible->win, &nextId, tkAccessible->interp);

  if (varChild.vt == VT_I4 && varChild.lVal > 0) {

    Tk_Window child = GetTkWindowForChildId(varChild.lVal);

    if (!child) {
      TkGlobalUnlock();
      return E_INVALIDARG;
    }
    HRESULT hr = TkAccState(child, pvarState);
    TkGlobalUnlock();
    return hr;
  }

  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;

  /* Re-assign child IDs for this toplevel's hierarchy to ensure freshness. */
  ClearChildIdTable();
  int nextId = 1;
  AssignChildIdsRecursive(tkAccessible->win, &nextId, tkAccessible->interp);

  if (varChild.vt == VT_I4 && varChild.lVal > 0) {

    Tk_Window child = GetTkWindowForChildId(varChild.lVal);
    if (!child) {
      TkGlobalUnlock();
      return E_INVALIDARG;
    }
    HRESULT hr = TkAccValue(child, pszValue);
    TkGlobalUnlock();
    return hr;
  }

  return DISP_E_MEMBERNOTFOUND;
}

/* Function to get accessible parent. For toplevel, return NULL. */
static HRESULT STDMETHODCALLTYPE TkRootAccessible_get_accParent(IAccessible *this, IDispatch **ppdispParent)
{

  TkRootAccessible *tkAccessible = (TkRootAccessible *)this;

  /* For toplevel, set ppdispParent to NULL and return S_OK. */
  *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;

  /* Clear and re-assign child IDs for this toplevel's hierarchy. */
  ClearChildIdTable();
  int nextId = 1;
  AssignChildIdsRecursive(tkAccessible->win, &nextId, tkAccessible->interp);

  /* Count actual child widgets of this window. */
  int widgetCount = TkAccChildCount(tkAccessible->win);
  int total = widgetCount;

  /* Add other toplevels only if this is the root window (".") */
  Tk_Window win = tkAccessible->win;
  const char *path = Tk_PathName(win);
  if (strcmp(path, ".") == 0) {
    Tk_Window extraToplevels[MAX_EXTRA_TOPLEVELS];
    int extraCount = GetExtraToplevels(win, extraToplevels, MAX_EXTRA_TOPLEVELS);
    total += extraCount;

  }

  *pcChildren = total;
  TkGlobalUnlock();
  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 < 1) {
    return E_INVALIDARG;
  }



  TkGlobalLock();
  TkRootAccessible *tkAccessible = (TkRootAccessible *)this;

  /* Clear and re-assign child IDs for this toplevel's hierarchy. */
  ClearChildIdTable();

  int nextId = 1;
  AssignChildIdsRecursive(tkAccessible->win, &nextId, tkAccessible->interp);





  LONG childId = varChild.lVal;

  /* Handle real widget children. */
  int widgetCount = TkAccChildCount(tkAccessible->win);
  if (childId >= 1 && childId <= widgetCount) {
    Tk_Window child = GetTkWindowForChildId(childId);
    if (child) {
      /* Check if this child is itself a registered IAccessible (i.e., another toplevel). */
      TkRootAccessible *childAcc = GetTkAccessibleForWindow(child);
      if (childAcc) {
	*ppdispChild = (IDispatch *)childAcc;
	childAcc->lpVtbl->AddRef((IAccessible *)childAcc);
	TkGlobalUnlock();
	return S_OK;
      } else {
	/* 

	 * This is a regular child widget, not an IAccessible itself. 
	 * Return S_OK with *ppdispChild = NULL, so MSAA client queries 
	 * parent with childId. 
	 */
	TkGlobalUnlock();
	return S_OK;
      }
    }
    TkGlobalUnlock();
    return E_INVALIDARG; /* Child ID exists but no corresponding Tk_Window or mapping. */
  }

  /* 
   * Handle synthetic children representing other toplevels 
   *(only applies to root window's IAccessible).
   */
  const char *path = Tk_PathName(tkAccessible->win);
  if (strcmp(path, ".") == 0 && childId >= SYNTHETIC_CHILD_BASE) {
    int index = childId - SYNTHETIC_CHILD_BASE;

    Tk_Window extraToplevels[MAX_EXTRA_TOPLEVELS];
    int extraCount = GetExtraToplevels(tkAccessible->win, extraToplevels, MAX_EXTRA_TOPLEVELS);

    if (index >= 0 && index < extraCount) {
      Tk_Window topWin = extraToplevels[index];
      TkRootAccessible *topAcc = GetTkAccessibleForWindow(topWin);
      if (topAcc) {
	*ppdispChild = (IDispatch *)topAcc;
	topAcc->lpVtbl->AddRef((IAccessible *)topAcc);
	TkGlobalUnlock();
	return S_OK;
      }
    }
  }

  TkGlobalUnlock();
  return E_INVALIDARG;
}

/* 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 (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;
  }

  /* Re-assign child IDs for this toplevel's hierarchy to ensure freshness. */
  ClearChildIdTable();
  int nextId = 1;
  AssignChildIdsRecursive(tkAccessible->win, &nextId, tkAccessible->interp);

  if (varChild.vt == VT_I4 && varChild.lVal > 0) {

    Tk_Window child = GetTkWindowForChildId(varChild.lVal);
    if (!child) {
      TkGlobalUnlock();
      return E_INVALIDARG;
    }

    RECT rect = { 0 };
    HRESULT hr = TkAccChild_GetRect(Tk_Interp(child), 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 focus on Tk widget. For toplevel, just return. */
static HRESULT STDMETHODCALLTYPE TkRootAccessible_accSelect(IAccessible *thisPtr, long flags, 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;

  /* Re-assign child IDs for this toplevel's hierarchy to ensure freshness. */
  ClearChildIdTable();
  int nextId = 1;
  AssignChildIdsRecursive(tkAccessible->win, &nextId, tkAccessible->interp);

  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. For toplevel, just return. */
static HRESULT STDMETHODCALLTYPE TkRootAccessible_accDoDefaultAction(IAccessible *this, VARIANT varChild)
{
  if (varChild.vt == VT_I4 && varChild.lVal == CHILDID_SELF) {
    return S_OK;
  }

  if (varChild.vt == VT_I4 && varChild.lVal > 0) {
    /* Pass childId to main thread. */
    mainThreadResult = E_FAIL;
    MainThreadFunc func = (MainThreadFunc)TkDoDefaultAction;
    int childId = varChild.lVal;
    RunOnMainThreadSync(func, 1, (void*)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;

  /* Re-assign child IDs for this toplevel's hierarchy to ensure freshness. */
  ClearChildIdTable();
  int nextId = 1;
  AssignChildIdsRecursive(tkAccessible->win, &nextId, tkAccessible->interp);

  if (varChild.vt == VT_I4 && varChild.lVal > 0) {
    Tk_Window child = GetTkWindowForChildId(varChild.lVal);
    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); /* Initialize the VARIANT to VT_EMPTY.*/

  HWND hwnd = NULL;
  TkGlobalLock();
  TkRootAccessible *tkAccessible = (TkRootAccessible *)this;
  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 (varChild.vt == VT_I4 && varChild.lVal == CHILDID_SELF) {
    /* Toplevel window. */
    *pszDescription = SysAllocString(L"Window"); /* Allocate string */
    TkGlobalUnlock();
    return S_OK;
  }

  /* Re-assign child IDs for this toplevel's hierarchy to ensure freshness. */
  ClearChildIdTable();
  int nextId = 1;
  AssignChildIdsRecursive(tkAccessible->win, &nextId, tkAccessible->interp);

  if (varChild.vt == VT_I4 && varChild.lVal > 0) {
    Tk_Window child = GetTkWindowForChildId(varChild.lVal);
    if (!child) {
      TkGlobalUnlock();
      return E_INVALIDARG;
    }
    HRESULT hr = TkAccDescription(child, pszDescription);
    TkGlobalUnlock();
    return hr;
  }

  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;
  }

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

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

  const char *tkrole = Tcl_GetString(Tcl_GetHashValue(hPtr2));
  int role = ROLE_SYSTEM_CLIENT; /* Fallback. */

  for (int i = 0; roleMap[i].tkrole != NULL; i++) {
    if (strcmp(tkrole, roleMap[i].tkrole) == 0) {
      role = roleMap[i].winrole;
      break;
    }
  }
  pvarRole->vt = VT_I4;
  pvarRole->lVal = role;

  return S_OK;
}

/* 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);
  Tcl_HashEntry *hPtr2 = Tcl_FindHashEntry(AccessibleAttributes, "state");

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

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

  /* Check if this widget has focus. */
  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, int flags)
{
  (void) flags;
  ActionEvent *event = (ActionEvent *)ev;

  /* Make sure key fields are not NULL. */
  if (!event || !event->win || !event->command) {
    return 1;
  }

  /*
   * Get the interpreter associated with this Tk_Window.
   * This is critical to ensure correct command processing -
   * if the interpreter is a different one, the command will
   * silently fail.
   */
  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 HRESULT TkDoDefaultAction(int num_args, void **args)
{

  int childId = (int)args[0];
  ActionEvent *event = NULL;

  HRESULT result = S_FALSE;

  if (!childId) {
    result = E_INVALIDARG;
    mainThreadResult = result;
    return mainThreadResult;
  }

  Tk_Window win = GetTkWindowForChildId(childId);
  if (!win) {
    result = E_INVALIDARG;
    mainThreadResult = result;
    return mainThreadResult;
  }

  Tcl_HashEntry *hPtr = Tcl_FindHashEntry(TkAccessibilityObject, (char *)win);
  if (!hPtr) {
    result = E_INVALIDARG;
    mainThreadResult = result;
    return mainThreadResult;
  }

  Tcl_HashTable *AccessibleAttributes = (Tcl_HashTable *)Tcl_GetHashValue(hPtr);
  if (!AccessibleAttributes) {
    result = E_INVALIDARG;
    mainThreadResult = result;
    return mainThreadResult;
  }

  Tcl_HashEntry *hPtr2 = Tcl_FindHashEntry(AccessibleAttributes, "action");
  if (!hPtr2) {
    result = E_INVALIDARG;
    mainThreadResult = result;
    return mainThreadResult;
  }

  const char *action = Tcl_GetString(Tcl_GetHashValue(hPtr2));
  if (!action) {
    result = E_INVALIDARG;
    mainThreadResult = result;
    return mainThreadResult;
  }

  event = (ActionEvent *)ckalloc(sizeof(ActionEvent));
  if (event == NULL) {
    result = E_OUTOFMEMORY;
    mainThreadResult = result;
    return mainThreadResult;
  }

  event->header.proc = ActionEventProc;
  const char *cmd = action;
  event->command = ckalloc(strlen(cmd) + 1);
  strcpy(event->command, cmd);
  event->win = win;
  Tcl_QueueEvent((Tcl_Event *)event, TCL_QUEUE_TAIL);
  result = S_OK;

  mainThreadResult = result;
  return result;
}

/* Function to get MSAA focus. */
static HRESULT TkAccFocus(int num_args, void **args)
{
  HWND hwnd = (HWND)args[0];
  VARIANT *pvarChild = (VARIANT*)args[1];
  Tk_Window win = Tk_HWNDToWindow(hwnd);
  if (!win || !pvarChild) return E_INVALIDARG;

  /* Get the current Tk focus window.*/
  TkWindow *focusPtr = TkGetFocusWin((TkWindow *)win);
  Tk_Window focusWin = (Tk_Window)focusPtr;

  /* If no focus, or focus is on the root window itself. */
  if (!focusWin || focusWin == win) {
    pvarChild->vt = VT_I4;
    pvarChild->lVal = CHILDID_SELF;
    return S_OK;
  }

  /* Ensure child IDs are up-to-date before looking up. */
  TkGlobalLock();
  ClearChildIdTable();
  int nextId = 1; /* Child IDs start from 1. */

  AssignChildIdsRecursive(win, &nextId, Tk_Interp(win));

  /* Look up ID for the focused child.*/
  int childId = GetChildIdForTkWindow(focusWin);

  if (childId > 0) {
    pvarChild->vt = VT_I4;
    pvarChild->lVal = childId;
    TkGlobalUnlock();
    return S_OK;
  } else {
    /* Fallback if child was focused but not found in ID table. */
    pvarChild->vt = VT_I4;
    pvarChild->lVal = CHILDID_SELF; /* Indicate no specific child focus found. */
    TkGlobalUnlock();
    return S_OK;
  }
}

/* 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)
{
  int count = 0;

  TkWindow *child = (TkWindow*)win;
  Tk_Window toplevel = GetToplevelOfWidget(win);
  TkWindow *winPtr = (TkWindow *)toplevel; /* Use the toplevel's childList. */
  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)
{
  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
 * the Tcl script-level API.
 *
 *----------------------------------------------------------------------
 */

/* Function to map Tk window to MSAA attributes. */
static TkRootAccessible *CreateRootAccessible(Tcl_Interp *interp, HWND hwnd, Tk_Window tkwin)
{

  TkRootAccessible *tkAccessible = (TkRootAccessible *)ckalloc(sizeof(TkRootAccessible));




  if (tkAccessible) {
    tkAccessible->lpVtbl = &tkRootAccessibleVtbl;
    tkAccessible->interp = interp;
    tkAccessible->hwnd = hwnd;
    tkAccessible->pathName = Tk_PathName(tkwin); // Get path from the provided Tk_Window
    tkAccessible->refCount = 1;
    tkAccessible->win = tkwin; // Use the provided Tk_Window directly
  }

  /*Add objects to hash tables. */
  Tcl_HashEntry *entry;
  int newEntry;
  entry = Tcl_CreateHashEntry(tkAccessibleTable, tkwin, &newEntry); // Use tkwin as key
  Tcl_SetHashValue(entry, tkAccessible);

  TkRootAccessible_AddRef((IAccessible*)tkAccessible);


  return tkAccessible;
}
/*
 * Function to pull in all toplevel windows. MSAA only registers
 * the root toplevel (.) by default.
 */
static int GetExtraToplevels(Tk_Window rootWin, Tk_Window toplevels[], int maxCount) {
  int count = 0;
  TkWindow *winPtr;
  TkDisplay *dispPtr = ((TkWindow *)rootWin)->dispPtr;

  Tcl_HashSearch search;
  Tcl_HashEntry *entryPtr;

  /* Iterate through ALL windows in the display's hash table. */
  for (entryPtr = Tcl_FirstHashEntry(&dispPtr->winTable, &search);
       entryPtr != NULL;
       entryPtr = Tcl_NextHashEntry(&search)) {
    winPtr = (TkWindow *)Tcl_GetHashValue(entryPtr);

    /* Filter for toplevels excluding the root window. */
    if (Tk_IsTopLevel((Tk_Window)winPtr) && (Tk_Window)winPtr != rootWin) {
      if (count < maxCount) {
	toplevels[count++] = (Tk_Window)winPtr;
      } else {
	break;  /* Stop if array is full. */
      }

    }
  }
  return count;
}

/* Function to map Tk window to MSAA ID's. */
static void SetChildIdForTkWindow(Tk_Window win, int id)
{
  if (!childIdTable) {
    childIdTable = (Tcl_HashTable *)ckalloc(sizeof(Tcl_HashTable));
    Tcl_InitHashTable(childIdTable, TCL_ONE_WORD_KEYS);
  }

  Tcl_HashEntry *entry;
  int newEntry;

  entry = Tcl_CreateHashEntry(childIdTable, (ClientData)win, &newEntry);
  Tcl_SetHashValue(entry, INT2PTR(id));

}

/* Function to retrieve MSAA ID for a specifc Tk window. */
static int GetChildIdForTkWindow(Tk_Window win)
{
  if (!childIdTable){
    return -1;
  }

  Tcl_HashEntry *entry = Tcl_FindHashEntry(childIdTable, (ClientData)win);
  if (!entry) {
    return -1;
  }
  return PTR2INT(Tcl_GetHashValue(entry));
}

/* Function to retrieve Tk window for a specifc MSAA ID. */
Tk_Window GetTkWindowForChildId(int id)
{
  if (!childIdTable){
    return NULL;
  }

  Tcl_HashSearch search;
  Tcl_HashEntry *entry;
  for (entry = Tcl_FirstHashEntry(childIdTable, &search);
       entry != NULL;
       entry = Tcl_NextHashEntry(&search)) {
    if (PTR2INT(Tcl_GetHashValue(entry)) == id) {
      return (Tk_Window)Tcl_GetHashKey(childIdTable, entry);
    }
  }
  return NULL;
}

/* Function to return the Tk toplevel window that contains a given Tk widget. */
Tk_Window GetToplevelOfWidget(Tk_Window tkwin)
{

  /* First check if the tkwin is NULL (destroyed). If yes, exit. */
  if (tkwin == NULL) {
    return NULL;
  }

  /*Tk window exists. Now look for toplevel. If no parent found, return null. */
  Tk_Window current = tkwin;
  while (current != NULL && Tk_WindowId(current) != None) {
    Tk_Window parent = Tk_Parent(current);
    if (parent == NULL) {
      break;
    }
    current = parent;
  }
  return current;
}

/* Function to initialize Tk -> MSAA hash table. */
void InitTkAccessibleTable(void) {

  if (!tkAccessibleTableInitialized) {
    tkAccessibleTable = (Tcl_HashTable *)ckalloc(sizeof(Tcl_HashTable));
    Tcl_InitHashTable(tkAccessibleTable, TCL_ONE_WORD_KEYS);
    tkAccessibleTableInitialized = 1;
  }

}












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

/* Function to clear childId hash table. */
void ClearChildIdTable(void)
{
  if (!childIdTable) {
    return;
  }

  Tcl_HashSearch search;
  Tcl_HashEntry *entry;

  for (entry = Tcl_FirstHashEntry(childIdTable, &search); entry != NULL; entry = Tcl_NextHashEntry(&search)) {
    Tcl_DeleteHashEntry(entry);
  }
}

/* Function to retrieve accessible object associated with Tk window. */
TkRootAccessible *GetTkAccessibleForWindow(Tk_Window win) {

  if (!tkAccessibleTableInitialized) {
    return NULL;
  }

  Tcl_HashEntry *entry = Tcl_FindHashEntry(tkAccessibleTable, (ClientData)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)
{

  if (!win || !Tk_IsMapped(win)){ /* Add null check for 'win' */
    return;
  }

  /* Assign an ID to this widget. */
  SetChildIdForTkWindow(win, (*nextId)++);

  /* Recurse into children. */
  TkWindow *winPtr = (TkWindow *)win;
  for (TkWindow *child = winPtr->childList; child != NULL; child = child->nextPtr) {
    AssignChildIdsRecursive((Tk_Window)child, nextId, interp);
  }
}

/* Handle WM_GETOBJECT call on main thread. */
void HandleWMGetObjectOnMainThread(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;
  }

  if ((LONG)lParam == OBJID_CLIENT) {
    Tk_Window tkwin = Tk_HWNDToWindow(hwnd);
    if (tkwin) {
      TkRootAccessible *acc = GetTkAccessibleForWindow(tkwin);
      if (acc) {
	*outResult = LresultFromObject(&IID_IAccessible, wParam, (IUnknown *)acc);
	return;
      }
    }
  }
}

/* Event handler that executes on main thread */
int ExecuteOnMainThreadSync(Tcl_Event *ev, int flags)
{
  MainThreadSyncEvent *event = (MainThreadSyncEvent *)ev;

  /* Execute with appropriate arguments. */
  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;
  }

  /* Signal completion and clean up. */
  SetEvent(event->doneEvent);
  ckfree(event);
  return 1;
}

/* Synchronous execution with variable arguments. */
void RunOnMainThreadSync(MainThreadFunc func, int num_args, ...)
{
  /* If already on the main thread, call function directly. */
  if (Tcl_GetCurrentThread() == mainThreadId) {
    void *args[6];  /*Support up to 6 args here.*/
    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;
  }

  /* Otherwise, allocate and initialize event. */
  MainThreadSyncEvent *event = (MainThreadSyncEvent *)ckalloc(sizeof(MainThreadSyncEvent));
  event->header.proc = ExecuteOnMainThreadSync ;
  event->func = func;
  event->num_args = num_args;
  event->doneEvent = CreateEvent(NULL, TRUE, FALSE, NULL);

  /* Extract variable arguments. */
  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);

  /* Queue and wait for completion. */
  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(PINIT_ONCE InitOnce, PVOID param, 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(
			  ClientData clientData,
			  Tcl_Interp *interp, /* Current interpreter. */
			  int argc, /* Number of arguments. */
			  Tcl_Obj *const argv[]) /* Argument objects. */
{
  /*
   * MSVC complains if this parameter is stubbed out
   * with TCL_UNUSED.
   */
  (void) clientData;

  BOOL screenReader = FALSE;
  SystemParametersInfo(SPI_GETSCREENREADER, 0, &screenReader, 0);
  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(
		     ClientData clientData,
		     Tcl_Interp *ip,		/* Current interpreter. */
		     int objc,			/* Number of arguments. */
		     Tcl_Obj *const objv[])	/* Argument objects. */
{
  /*
   * MSVC complains if this parameter is stubbed out
   * with TCL_UNUSED.
   */
  (void) clientData;


  if (objc < 2) {
    Tcl_WrongNumArgs(ip, 1, objv, "window?");
    return TCL_ERROR;
  }
  Tk_Window win;

  win = Tk_NameToWindow(ip, Tcl_GetString(objv[1]), Tk_MainWindow(ip));
  if (win == NULL) {
    /* Tk_MakeWindowExist(win); // Do not call Tk_MakeWindowExist here */
    return TCL_ERROR;
  }

  /* Get the toplevel window's HWND for NotifyWinEvent */
  Tk_Window toplevel = GetToplevelOfWidget(win);
  if (!toplevel) {
    return TCL_ERROR;
  }
  HWND hwnd = Tk_GetHWND(Tk_WindowId(toplevel));

  /* Fire notification of new value. */

  NotifyWinEvent(EVENT_OBJECT_VALUECHANGE, hwnd, OBJID_CLIENT, 0);

  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)
{
  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(ClientData clientData, XEvent *eventPtr)
{

  if (eventPtr->type == DestroyNotify) {
    TkGlobalLock();
    TkRootAccessible *tkAccessible = (TkRootAccessible *)clientData;
    Tk_Window win = tkAccessible->win;
    if (tkAccessible) {
      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(ClientData 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) return TCL_ERROR;


  Tk_Window toplevel = GetToplevelOfWidget(win);
  HWND hwnd = Tk_GetHWND(Tk_WindowId(toplevel));

  TkGlobalLock();
  ClearChildIdTable();
  int nextId = 1;
  AssignChildIdsRecursive(toplevel, &nextId, interp);

  LONG childId = GetChildIdForTkWindow(win);

  if (childId <= 0) {
    Tcl_AppendResult(interp, "Failed to find child ID for ", path, NULL);
    TkGlobalUnlock();
    return TCL_OK;
  }

  NotifyWinEvent(EVENT_OBJECT_FOCUS, hwnd, 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(
			   ClientData clientData,
			   Tcl_Interp *interp, /* Current interpreter. */
			   int objc, /* Number of arguments. */
			   Tcl_Obj *const objv[]) /* Argument objects. */
{

  (void) clientData;
  HWND hwnd = NULL;

  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 == NULL) {
    Tcl_SetResult(interp, "Invalid window name.", TCL_STATIC);
    return TCL_ERROR;
  }








  Tk_Window toplevel_of_tkwin = GetToplevelOfWidget(tkwin);
  if (toplevel_of_tkwin == NULL) {
    Tcl_SetResult(interp, "Could not determine toplevel for window.", TCL_STATIC);
    return TCL_ERROR;
  }
  hwnd = Tk_GetHWND(Tk_WindowId(toplevel_of_tkwin));


  TkGlobalLock();
  /* 
   * CreateRootAccessible for the toplevel if it doesn't already exist 
   * (TkWinAccessiblity_Init covers existing ones).
   */
  TkRootAccessible *accessible = GetTkAccessibleForWindow(toplevel_of_tkwin);
  if (!accessible) {
    accessible = CreateRootAccessible(interp, hwnd, toplevel_of_tkwin);
  }
  /* Register the cleanup handler for the target window, not necessarily the toplevel. */
  TkRootAccessible_RegisterForCleanup(tkwin, accessible);

  if (accessible == NULL) {
    Tcl_SetResult(interp, "Failed to create accessible object.", TCL_STATIC);
    return TCL_ERROR;
  }

  /* Initial assignment of child IDs right after creating the root accessible. */
  ClearChildIdTable(); /* Clear any previous IDs. */
  int nextId = 1;
  /* Assign IDs for the hierarchy starting from the *toplevel* of the provided tkwin. */
  AssignChildIdsRecursive(toplevel_of_tkwin, &nextId, interp);
  TkGlobalUnlock();

  /* 
   * Notify screen readers of creation. 
   * Use the HWND of the toplevel, but the CHILDID_SELF of the
   *   target tkwin if it's the toplevel, 
   * or its actual child ID if it's a child. 
   */
  LONG childId = GetChildIdForTkWindow(tkwin);
  if (childId == -1) { /* If it's the toplevel itself or an unmapped widget. */
    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);
  } else {
    NotifyWinEvent(EVENT_OBJECT_CREATE, hwnd, OBJID_CLIENT, childId);
    NotifyWinEvent(EVENT_OBJECT_SHOW, hwnd, OBJID_CLIENT, childId);
    NotifyWinEvent(EVENT_OBJECT_NAMECHANGE, hwnd, OBJID_CLIENT, childId);
  }

  return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * TkWinAccessibility_Init --
 *
 *	Initializes the accessibility module.
 *
 * Results:
 *
 * A standard Tcl result.
 *
 * Side effects:
 *
 *	Accessibility module is now activated.
 *
 *----------------------------------------------------------------------
 */

int TkWinAccessiblity_Init(Tcl_Interp *interp)
{
  Tk_Window rootWin = Tk_MainWindow(interp);

  /* Ensure the root window exists and has an HWND before proceeding. */
  if (rootWin != NULL) {
    Tk_MakeWindowExist(rootWin);
  } else {
    Tcl_SetResult(interp, "Failed to get Tk_MainWindow.", TCL_STATIC);
    return TCL_ERROR;
  }

  /*Initialize object-tracking hash tables. */
  EnsureGlobalLockInitialized();
  TkGlobalLock();
  InitAccessibilityMainThread();
  InitTkAccessibleTable();
  InitChildIdTable(); /* Ensure child ID table is also initialized. */

  /* Register root window. */
  HWND rootHwnd = Tk_GetHWND(Tk_WindowId(rootWin));
  CreateRootAccessible(interp, rootHwnd, rootWin);

  /* Register all other toplevel windows */
  TkWindow *winPtr;
  TkDisplay *dispPtr = ((TkWindow *)rootWin)->dispPtr;
  Tcl_HashSearch search;
  Tcl_HashEntry *entryPtr;

  for (entryPtr = Tcl_FirstHashEntry(&dispPtr->winTable, &search);
       entryPtr != NULL;
       entryPtr = Tcl_NextHashEntry(&search)) {
    winPtr = (TkWindow *)Tcl_GetHashValue(entryPtr);

    /* Filter for toplevels excluding the root window and ensuring it's not already handled. */
    if (Tk_IsTopLevel((Tk_Window)winPtr) && (Tk_Window)winPtr != rootWin && !GetTkAccessibleForWindow((Tk_Window)winPtr)) {
      HWND hwnd = Tk_GetHWND(Tk_WindowId((Tk_Window)winPtr));
      CreateRootAccessible(interp, hwnd, (Tk_Window)winPtr);
    }
  }

  TkGlobalUnlock();

  /*Create 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;
}