-
Notifications
You must be signed in to change notification settings - Fork 0
/
__init__.py
626 lines (605 loc) · 20.5 KB
/
__init__.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
# coding: utf-8
# Copyright 2023 Emil-18
# An add-on that enhances support for win 32 controls that don't support MSAA/IAccessible
# This add-on is licensed under the same license as NVDA. See the copying.txt file for more information
#* imports
import addonHandler
addonHandler.initTranslation()
import api
import appModuleHandler
import config
import controlTypes
import displayModel
import eventHandler
import globalPluginHandler
import globalVars
import gui
import IAccessibleHandler
import json
import locationHelper
import mouseHandler
import os
import sys
import textInfos
import threading
import tones
import ui
import UIAHandler
import winUser
import wx
from ctypes import *
from ctypes.wintypes import POINT, WPARAM, LPARAM
from globalVars import appPid
from gui.settingsDialogs import SettingsDialog
from NVDAObjects import *
from scriptHandler import script, getLastScriptRepeatCount
from time import sleep
from NVDAObjects.window import edit
#* global variables
path = config.getInstalledUserConfigPath()
configPath = os.path.join(path, 'controlConfig.ini')
disabled = False
#* needed dlls
user32 = windll.user32
kernel32 = windll.kernel32
oleacc = windll.oleacc
#* helper functions
cachedAppNames = {}
notWin32 = ('MSAA', 'UIA', 'normal')
def getKeyFromWindow(windowHandle, bypassDisabled = False):
if disabled and not bypassDisabled:
return
global cachedAppNames
processID = winUser.getWindowThreadProcessID(windowHandle)[0]
# calling the get app name from process ID function on every NVDAObject that gets instansiated causes a large drop in performence, so cache it.
appName = cachedAppNames.get(processID)
if not appName:
appName = appModuleHandler.getAppNameFromProcessID(processID)
cachedAppNames.update({processID: appName})
className = winUser.getClassName(windowHandle)
return(appName+className)
def getConfigFromWindow(windowHandle):
key = getKeyFromWindow(windowHandle)
c = cfg.get(key)
return c
def shouldUseWin32(windowHandle):
c = getConfigFromWindow(windowHandle)
use = bool(c and not c[0] in notWin32)
return(use)
def findSupportedClass(windowHandle):
supported = []
cls = None
for i in supportedClasses:
if i.isSupported(windowHandle):
supported.append(i)
length = len(supported)
if length == 1:
cls = supported[0]
return(cls)
# No class or multiple classes gave True, so look at their names and check if the window class include their name
className = winUser.getClassName(windowHandle)
supportedNames = []
for i in supportedClasses:
if i.__name__.lower() in className.lower():
supportedNames.append(i)
if len(supportedNames) == 1:
cls = supportedNames[0]
return(cls)
#* redefinitions
oldGetPossibleAPIClasses = window.Window.getPossibleAPIClasses
@classmethod
def newGetPossibleAPIClasses(cls, kwargs, relation = None):
windowHandle = kwargs['windowHandle']
if shouldUseWin32(windowHandle):
yield(Win32)
return()
for i in oldGetPossibleAPIClasses(kwargs, relation = relation):
yield(i)
oldWinEventToNVDAEvent = IAccessibleHandler.winEventToNVDAEvent
def newWinEventToNVDAEvent(eventID, window, objectID, childID, useCache = True):
try:
old = oldWinEventToNVDAEvent(eventID, window, objectID, childID, useCache)
except:
old = False
if not shouldUseWin32(window) or not old:
return(old)
name = old[0]
cls = configNamesToClasses[getConfigFromWindow(window)[0]]
index = childID - cls.winEventToIndex
obj = cls(windowHandle = window, index = index)
return(name, obj)
oldProcessFocusWinEvent = IAccessibleHandler.processFocusWinEvent
def newProcessFocusWinEvent(window, objectID, childID, force = False):
try:
return(oldProcessFocusWinEvent(window, objectID, childID, force = force))
except:
pass
event = IAccessibleHandler.winEventToNVDAEvent(winUser.EVENT_OBJECT_FOCUS, window, objectID, childID, useCache = False)
if not event:
return(False)
IAccessibleHandler.processFocusNVDAEvent(event[1], force = force)
return(True)
oldIsUIAWindow = UIAHandler.UIAHandler.isUIAWindow
def newIsUIAWindow(self, windowHandle, *args, **kwargs):
conf = getConfigFromWindow(windowHandle)
if not conf:
return(oldIsUIAWindow(self, windowHandle, *args, **kwargs))
cls = conf[0]
if shouldUseWin32(windowHandle) or cls in notWin32 and cls != 'UIA':
return(False)
return(True)
class TimerMixin():
shouldMonitorFocusEvents = False
# def _get_shouldMonitorCaretEvents(self):
# try:
# self.makeTextInfo(textInfos.POSITION_CARET)
# return(True)
# except:
# return(False)
shouldMonitorCaretEvents = True
def initOverlayClass(self):
self.staticName = self.name
self.staticValue = self.value
self.staticStates = self.states
if self.shouldMonitorFocusEvents:
self.focusObject = self.getFocusObject()
try:
self.staticCaret = self.makeTextInfo(textInfos.POSITION_CARET)
except:
pass
def event_gainFocus(self):
timer.Start(50)
if not self.shouldMonitorFocusEvents:
super(TimerMixin, self).event_gainFocus()
return()
if self.index <0: # The parent object, e.g a list, got focus, but we want to fire a focus event on the child object that actualy has the system focus.
f = self.getFocus()
if f:
obj = Win32(self.windowHandle, f)
eventHandler.queueEvent('gainFocus', obj)
return()
super(TimerMixin, self).event_gainFocus()
def event_loseFocus(self):
timer.Stop()
super(TimerMixin, self).event_loseFocus()
def event_caret(self):
try:
caret = self.makeTextInfo(textInfos.POSITION_CARET)
except:
return
self.staticCaret = caret
super(TimerMixin, self).event_caret()
def event_nameChange(self):
self.staticName = self.name
super(TimerMixin, self).event_nameChange()
def event_valueChange(self):
self.staticValue = self.value
super(TimerMixin, self).event_valueChange()
def event_stateChange(self):
self.staticStates = self.states
super(TimerMixin, self).event_stateChange()
class Win32(window.Window):
'''
Support for win32 controls that don't support IAccessible
'''
winEventToIndex = 0
index = 0
isComplex = False # The control has other controls that NVDA should treat as NVDAObjects inside of it, such as a list.
baseRole = controlTypes.Role.WINDOW
clicks = 1 # the number of clicks that normaly are required to activate a control
def _get_role(self):
return(self.baseRole)
def __init__(self, windowHandle = None, index = -1):
if self.isComplex:
self.index = index
super(Win32, self).__init__(windowHandle = windowHandle)
def _get_win32Name(self):
return(self.windowText)
def doWindowAction(self):
pass
def click(self):
point = self.location.center
obj = NVDAObject.objectFromPoint(*point)
if obj != self:
return(False)
mousePos = winUser.getCursorPos()
winUser.setCursorPos(*point)
for i in range(self.clicks):
mouseHandler.doPrimaryClick()
winUser.setCursorPos(*mousePos)
return(True)
def doAction(self, index = None):
if not self.click():
self.doWindowAction()
def _isEqual(self, other):
eq = super(Win32, self)._isEqual(other)
if eq:
eq = self.index == other.index
return(eq)
@staticmethod
def isSupported(windowHandle):
return(False)
@classmethod
def getPossibleAPIClasses(cls, kwargs, relation = None):
handle = kwargs.get('windowHandle')
c = getConfigFromWindow(handle)[0]
yield configNamesToClasses[c]
@classmethod
def kwargsFromSuper(cls, kwargs, relation = None):
return(True)
def _get_name(self):
name = self.displayText
if not name or name.isspace() or len(name) >500:
name = self.win32Name
return(name)
def _get_states(self):
states = super(Win32, self).states
focus = api.getFocusObject().windowHandle
if self.windowHandle == focus:
states.add(controlTypes.State.FOCUSED)
return(states)
def _get_keyboardShortcut(self):
shortcut = 'Alt+'
letter = ''
name = self.win32Name
for i in range(len(name)):
if name[i] == '&':
try:
letter = name[i+1]
break
except:
pass
if letter:
return(shortcut+letter)
return('')
def timerFunc(self):
focus = api.getFocusObject()
if not isinstance(focus, TimerMixin): return
curFocus = None
checkFocus = focus.shouldMonitorFocusEvents
if checkFocus:
curFocus = focus
focusChanged = False
if checkFocus:
if not focus.focusObj == focus.getFocusObj():
eventHandler.queueEvent('gainFocus', focus.getFocusObj())
return
focusChanged = True
if not focusChanged:
if focus.staticName != focus.name:
eventHandler.queueEvent('nameChange', focus)
if focus.staticValue != focus.value:
eventHandler.queueEvent('valueChange', focus)
if focus.staticStates != focus.states:
eventHandler.queueEvent('stateChange', focus)
if focus.shouldMonitorCaretEvents:
try:
caret = focus.makeTextInfo(textInfos.POSITION_CARET)
except:
return
if caret != focus.staticCaret:
eventHandler.queueEvent('caret', focus)
timer = wx.Timer(gui.mainFrame)
gui.mainFrame.Bind(wx.EVT_TIMER, handler = timerFunc, source = timer)
#* slider support
#** slider messages
TBM_GETPOS = 1024
TBM_GETRANGEMAX = 1026
class Slider(Win32):
baseRole = controlTypes.Role.SLIDER
def _get_value(self):
res = (winUser.sendMessage(self.windowHandle, TBM_GETPOS, 0, 0))
return(str(res))
@staticmethod
def isSupported(windowHandle):
res = winUser.sendMessage(windowHandle, TBM_GETRANGEMAX, 0, 0)
return(bool(res))
@classmethod
def kwargsFromSuper(cls, kwargs, relation = None):
return(True)
#* edit support
#** edit messages
EM_GETLINECOUNT = 186
class NewEditTextInfo(window.edit.EditTextInfo):
def _getTextRange(self, *args, **kwargs):
try:
return(super(NewEditTextInfo, self)._getTextRange(*args, **kwargs))
except:
return('')
class Edit(edit.UnidentifiedEdit, Win32):
shouldMonitorCaretEvents = True
baseRole = controlTypes.Role.EDITABLETEXT
def _get_name(self):
return(winUser.getWindowText(self.windowHandle))
def _get_TextInfo(self):
info = super(Edit, self)._get_TextInfo()
if info == edit.EditTextInfo:
return(NewEditTextInfo)
return(info)
@staticmethod
def isSupported(windowHandle):
res = winUser.sendMessage(windowHandle, EM_GETLINECOUNT, 0, 0)
return(bool(res))
@classmethod
def kwargsFromSuper(cls, kwargs, relation = None):
return(True)
#* button support
#** button messages.
BM_GETCHECK = 240
BM_CLICK = 245
class Button(Win32):
baseRole = controlTypes.Role.BUTTON
def getActionName(self, index = None):
# Translators: the default action message for a button
string = _('Press')
return(string)
def doWindowAction(self, index = None):
winUser.sendMessage(self.windowHandle, BM_CLICK, 0, 0)
@staticmethod
def isSupported(windowHandle):
return(False)
@classmethod
def kwargsFromSuper(*args, **kwargs):
return(True)
class CheckBox(Button):
baseRole = controlTypes.Role.CHECKBOX
def _get_states(self):
states = super(CheckBox, self)._get_states()
res = winUser.sendMessage(self.windowHandle, BM_GETCHECK, 0, 0)
if res == 1:
states.add(controlTypes.State.CHECKED)
elif res == 2:
states.add(controlTypes.State.HALFCHECKED)
return(states)
@classmethod
def kwargsFromSuper(*args, **kwargs):
return(True)
class RadioButton(CheckBox):
baseRole = controlTypes.Role.RADIOBUTTON
@classmethod
def kwargsFromSuper(*args, **kwargs):
return(True)
class Text(Win32):
baseRole = controlTypes.Role.STATICTEXT
@classmethod
def kwargsFromSuper(*args, **kwargs):
return(True)
class Unknown(Win32):
baseRole = controlTypes.Role.UNKNOWN
def event_textChange(self):
info = displayModel.DisplayModelTextInfo(self, textInfos.POSITION_ALL)
try:
start, end = info._getSelectionOffsets()
except:
return
if not end>start:
return
start, end = info._getPointFromOffset(start), info._getPointFromOffset(end)
l = locationHelper.RectLTRB(start.x, start.y, end.x, end.y)
l = l.toLTWH()
obj = DisplayModelText(windowHandle = self.windowHandle, location = l)
if obj != api.getFocusObject():
eventHandler.executeEvent('gainFocus', obj)
@classmethod
def kwargsFromSuper(*args, **kwargs):
return(True)
class DisplayModelText(Win32):
def __init__(self, windowHandle = None, location = None, name):
self.location = location
self.windowHandle = windowHandle
super(DisplayModelText, self).__init__(windowHandle = self.windowHandle)
def _isEqual(self, other):
return(self.name == other.name and self.location == other.location)
cfg = {}
supportedControls = []
classNamesToNVDAControlTypeNames = {}
supportedClasses = [
Slider,
Edit,
Button,
CheckBox,
RadioButton,
Text,
Unknown
]
configNamesToClasses = {}
for i in supportedClasses:
configNamesToClasses.update({i.__name__: i})
supportedControls.append(i.baseRole.displayString)
classNamesToNVDAControlTypeNames.update({i.__name__: i.baseRole.displayString})
supportedControls.sort()
# Translators: an option in a combo box
supportedControls.insert(0, _('Use normal add-on behavior'))
supportedControls.append('MSAA')
supportedControls.append('UIA')
# Translators: an option in a combo box
normal = _('Use normal NVDA behavior')
supportedControls.append(normal)
classNamesToNVDAControlTypeNames.update({'MSAA': 'MSAA', 'UIA': 'UIA', 'normal': normal})
class ControlDialog(SettingsDialog):
# Translators: The title for the control type selection dialog
title = _('Select control type')
helpId = None
def __init__(self, *args, obj, **kwargs):
self.obj = obj
super(ControlDialog, self).__init__(*args, **kwargs)
def makeSettings(self, settingsSizer):
helper = gui.guiHelper.BoxSizerHelper(self, sizer = settingsSizer)
obj = window.Window(windowHandle = self.obj.windowHandle)
name = obj.name
if not name:
# Translators: a part of the text in a dialog box
name = 'unlabeled'
role = obj.role.displayString
# Translators: The start of a text in a dialog box. The name and control type of a control in windows will be appended directly after this text, so end this with a space.
start = _('Select a control type. NVDA will behave as if ')
middle = name+' '+role
# Translators: the end of a text in a dialog box. This text will be appended directly after a control type, so start this with a space.
end = _(' and all similar controls in the same program are the control type you selected, for example, if you select button, all similar controls will be treated as buttons')
text = start+middle+end
self.StaticText = helper.addItem(wx.StaticText(self, label = text))
# Translators: A label for a combo box
label = _('Control type:')
self.choice = helper.addLabeledControl(label, wx.Choice, choices = supportedControls)
# Translators: the label for a check box
label2 = _('rely on events. Only change if you know what you are doing')
self.checkBox = wx.CheckBox(self, label = label2)
helper.addItem(self.checkBox)
# Translators: The label for a check box
label = _('Temporarily use normal add-on behavior for all controls')
self.disable = wx.CheckBox(self, label = label)
helper.addItem(self.disable)
self.disable.SetValue(disabled)
def postInit(self):
self.key = getKeyFromWindow(self.obj.windowHandle, bypassDisabled = True)
conf = cfg.get(self.key)
if not conf:
self.choice.SetSelection(0)
else:
className = conf[0]
type = classNamesToNVDAControlTypeNames.get(className)
index = supportedControls.index(type)
self.choice.SetSelection(index)
eventSupport = conf[1]
self.checkBox.SetValue(eventSupport)
self.choice.SetFocus()
def onOk(self, *args, **kwargs):
global disabled
disabled = self.disable.GetValue()
global cfg
if cfg.get(self.key):
cfg.pop(self.key)
selection = self.choice.GetSelection()
if not selection: # The user wants to use the control as normal, so return here.
return(super(ControlDialog, self).onOk(*args, **kwargs))
conf = {}
name = supportedControls[selection]
for i in classNamesToNVDAControlTypeNames.keys():
if classNamesToNVDAControlTypeNames.get(i) == name:
name = i
checked = self.checkBox.GetValue()
conf = [name, checked]
cfg.update({self.key: conf})
return(super(ControlDialog, self).onOk(*args, **kwargs))
class GlobalPlugin(globalPluginHandler.GlobalPlugin):
def __init__(self):
super(GlobalPlugin, self).__init__()
window.Window.getPossibleAPIClasses = newGetPossibleAPIClasses
IAccessibleHandler.winEventToNVDAEvent = newWinEventToNVDAEvent
UIAHandler.UIAHandler.isUIAWindow = newIsUIAWindow
IAccessibleHandler.processFocusWinEvent = newProcessFocusWinEvent
global cfg
try:
open(configPath, 'x')
except:
pass
f = open(configPath, )
try:
cfg = json.load(f)
except:
pass
f.close()
self.displayObj = None
def terminate(self):
super(GlobalPlugin, self).terminate()
window.Window.getPossibleAPIClasses = oldGetPossibleAPIClasses
IAccessibleHandler.winEventToNVDAEvent = oldWinEventToNVDAEvent
UIAHandler.UIAHandler.isUIAWindow = oldIsUIAWindow
IAccessibleHandler.processFocusWinEvent = oldProcessFocusWinEvent
f = open(configPath, 'w+')
json.dump(cfg, f, indent = 4)
f.close()
def chooseNVDAObjectOverlayClasses(self, obj, clsList):
conf = getConfigFromWindow(obj.windowHandle)
copyList = clsList.copy()
if conf and shouldUseWin32(obj.windowHandle) and issubclass(obj.APIClass, Win32):
for i in copyList:
if i == window.Window:
break
if issubclass(i, window.Window) and not issubclass(i, Win32):
clsList.remove(i)
if conf and conf[0] == 'UIA':
for i in copyList:
if issubclass(i, IAccessible.IAccessible):
clsList.remove(i)
if conf and conf[0] == 'MSAA':
for i in copyList:
if issubclass(i, UIA.UIA):
clsList.remove(i)
if conf and not conf[1]:
clsList.insert(0, TimerMixin)
return()
if conf:
return
if not IAccessible.ContentGenericClient in clsList: # NVDA seams to recognise this window, so continue as normal.
return()
# NVDA doesn't recognise this window
cls = findSupportedClass(obj.windowHandle)
if cls:
clsList.remove(IAccessible.ContentGenericClient)
clsList.insert(0, TimerMixin)
clsList.insert(0, cls)
key = getKeyFromWindow(obj.windowHandle)
name = cls.__name__
# cfg.update({key: [name, False]})
return()
clsList.insert(0, Unknown)
def event_gainFocus(self, obj, nextHandler):
displayObj = self.displayObj
if displayObj and displayObj.windowHandle != obj.windowHandle:
try:
displayModel.requestTextChangeNotifications(displayObj, False)
except:
pass
self.displayObj = None
if not displayObj and isinstance(obj, Unknown):
self.displayObj = obj
displayModel.requestTextChangeNotifications(obj, True)
nextHandler()
@script(
# Translators: Describes the select control type script
description = _('Lets you choose from a list of controls how NVDA will treat the control with focus. For example, choos \'button\' To tell NVDA to treat it as a button.'),
gesture = 'kb:nvda+alt+c'
)
def script_selectControlType(self, gesture, obj = None):
if not obj:
obj = api.getFocusObject()
message = None
if not isinstance(obj, window.Window):
# Translators: The message that is reported when the NVDAObject is a custom object, that has no assosiation with a control in Windows.
message = _('You can not assign another control type to this object, because it has no assosiation with a control in Windows')
elif obj.processID == appPid:
#Translators: The message reported when the object belongs to the NVDA process
message = _('You can not assign another control type to any object contained within NVDA, because if done wrong, you may not be able to reverse the changes you have made')
if message:
ui.message(message)
return
gui.mainFrame._popupSettingsDialog(ControlDialog, obj = obj)
@script(
# Translators: describes the select control from navigator script:
description = _('Lets you choose from a list of controls how NVDA will treat the control where the navigator object is located. For example, choos \'button\' To tell NVDA to treat it as a button.'),
gesture = 'kb:nvda+shift+alt+c'
)
def script_selectControlFromNavigator(self, gesture):
nav = api.getNavigatorObject()
if not nav:
ui.message(translate('no navigator object'))
return()
self.script_selectControlType(gesture, obj = nav)
@script(
# Translators: Describes the find control type script
description = _('Tries to find out an report the type of the control with focus. If pressed twice, information about the control where the navigator object is located will be reported instead'),
gesture = 'kb:nvda+alt+r'
)
def script_findControlType(self, gesture):
if not getLastScriptRepeatCount():
windowHandle = api.getFocusObject().windowHandle
else:
windowHandle = api.getNavigatorObject().windowHandle
cls = findSupportedClass(windowHandle)
if not cls:
# Translators: The message reported when NVDA can't find out what type of control it is
message = _('Unable to find control type')
ui.message(message)
return
ui.message(cls.baseRole.displayString)