forked from mltony/nvda-tonys-enhancements
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdraft2.py
1205 lines (1092 loc) · 45.6 KB
/
draft2.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
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
# -*- coding: UTF-8 -*-
#A part of Tony's Enhancements addon for NVDA
#Copyright (C) 2019 Tony Malykh
#This file is covered by the GNU General Public License.
#See the file COPYING.txt for more details.
import addonHandler
import api
import bisect
import collections
import config
import controlTypes
import core
import copy
import ctypes
from ctypes import create_string_buffer, byref
import documentBase
import editableText
import globalPluginHandler
import gui
from gui import guiHelper, nvdaControls
import inputCore
import itertools
import json
import keyboardHandler
from logHandler import log
import math
import NVDAHelper
from NVDAObjects import behaviors, NVDAObject
from NVDAObjects.IAccessible import IAccessible
from NVDAObjects.UIA import UIA
from NVDAObjects.window import winword
import nvwave
import operator
import os
import re
import sayAllHandler
from scriptHandler import script, willSayAllResume
import speech
import string
import struct
import textInfos
import threading
import time
import tones
import types
import ui
import watchdog
import wave
import winUser
import wx
winmm = ctypes.windll.winmm
debug = True
if debug:
import threading
LOG_FILE_NAME = "C:\\Users\\tony\\Dropbox\\1.txt"
f = open(LOG_FILE_NAME, "w")
f.close()
LOG_MUTEX = threading.Lock()
def mylog(s):
with LOG_MUTEX:
f = open(LOG_FILE_NAME, "a", encoding='utf-8')
print(s, file=f)
#f.write(s.encode('UTF-8'))
#f.write('\n')
f.close()
else:
def mylog(*arg, **kwarg):
pass
def myAssert(condition):
if not condition:
raise RuntimeError("Assertion failed")
defaultDynamicKeystrokes = """
*:F1
*:F2
*:F3
*:F4
*:F5
*:F6
*:F7
*:F8
*:F9
*:F9
*:F10
*:F11
*:F12
code:Alt+DownArrow
code:Alt+UpArrow
code:Alt+Home
code:Alt+End
code:Alt+PageUp
code:Alt+PageDown
""".strip()
defaultLangMap = '''
en:[a-zA-Z]
ru:[а-яА-Я]
zh_CN:[⺀-⺙⺛-⻳⼀-⿕々〇〡-〩〸-〺〻㐀-䶵一-鿃豈-鶴侮-頻並-龎]
'''.strip()
module = "tonysEnhancements"
def initConfiguration():
confspec = {
"blockDoubleInsert" : "boolean( default=False)",
"blockDoubleCaps" : "boolean( default=False)",
"blockScrollLock" : "boolean( default=False)",
"nvdaVolume" : "integer( default=100, min=0, max=100)",
"busyBeep" : "boolean( default=False)",
"dynamicKeystrokesTable" : f"string( default='{defaultDynamicKeystrokes}')",
"fixWindowNumber" : "boolean( default=False)",
"detectInsertMode" : "boolean( default=False)",
"suppressUnselected" : "boolean( default=False)",
"enableLangMap" : "boolean( default=False)",
"langMap" : f"string( default='{defaultLangMap}')",
"quickSearch1" : f"string( default='')",
"quickSearch2" : f"string( default='')",
"quickSearch3" : f"string( default='')",
"priority" : "integer( default=0, min=0, max=3)",
}
config.conf.spec[module] = confspec
def getConfig(key):
value = config.conf[module][key]
return value
def setConfig(key, value):
config.conf[module][key] = value
def parseDynamicKeystrokes(s):
result = set()
for line in s.splitlines():
tokens = line.strip().split(":")
if (len(tokens) == 0) or (len(line) == 0):
continue
if len(tokens) != 2:
raise ValueError(f"Dynamic shortcuts configuration: invalid line: {line}")
app = tokens[0]
try:
kb = keyboardHandler.KeyboardInputGesture.fromName(tokens[1]).identifiers[0]
except (KeyError, IndexError):
raise ValueError(f"Invalid kb shortcut {tokens[1]} ")
result.add((app, kb))
return result
dynamicKeystrokes = None
def reloadDynamicKeystrokes():
global dynamicKeystrokes
dynamicKeystrokes = parseDynamicKeystrokes(getConfig("dynamicKeystrokesTable"))
def parseLangMap(s):
result = {}
for line in s.splitlines():
tokens = line.strip().split(":")
if (len(tokens) == 0) or (len(line) == 0):
continue
if len(tokens) != 2:
raise ValueError(f"LangMap configuration: invalid line: {line}")
lang = tokens[0]
try:
r = re.compile(tokens[1])
except Exception as e:
raise ValueError(f"Invalid regex for language {lang}: {tokens[1]}: {e}")
result[lang] = r
return result
langMap = None
def reloadLangMap():
global langMap
langMap = parseLangMap(getConfig("langMap"))
priorityNames = _("Normal,Above normal,High,Realtime").split(",")
priorityValues = [
# https://docs.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-setpriorityclass?redirectedfrom=MSDN
0x00000020,
0x00008000,
0x00000080,
0x00000100
]
def updatePriority():
index = getConfig("priority")
priority = priorityValues[index]
result = ctypes.windll.kernel32.SetPriorityClass(ctypes.windll.kernel32.GetCurrentProcess(), priority)
if result == 0:
gui.messageBox(_("Failed to set process priority to %s.") % priorityNames[index], _("Tony's enhancement add-on encountered an error"), wx.OK|wx.ICON_WARNING, None)
addonHandler.initTranslation()
initConfiguration()
reloadDynamicKeystrokes()
reloadLangMap()
updatePriority()
class MultilineEditTextDialog(wx.Dialog):
def __init__(self, parent, text, title_string, onTextComplete):
# Translators: Title of calibration dialog
super(MultilineEditTextDialog, self).__init__(parent, title=title_string)
self.text = text
self.onTextComplete = onTextComplete
mainSizer = wx.BoxSizer(wx.VERTICAL)
sHelper = gui.guiHelper.BoxSizerHelper(self, orientation=wx.VERTICAL)
self.textCtrl = wx.TextCtrl(self, style=wx.TE_MULTILINE)
self.textCtrl.Bind(wx.EVT_CHAR, self.onChar)
self.Bind(wx.EVT_CHAR_HOOK, self.OnKeyUP)
sHelper.addItem(self.textCtrl)
self.textCtrl.SetValue(text)
self.SetFocus()
#self.Maximize(True)
self.OkButton = sHelper.addItem (wx.Button (self, label = _('OK')))
self.OkButton.Bind(wx.EVT_BUTTON, self.onOk)
self.cancelButton = sHelper.addItem (wx.Button (self, label = _('Cancel')))
self.cancelButton.Bind(wx.EVT_BUTTON, self.onCancel)
def onChar(self, event):
control = event.ControlDown()
shift = event.ShiftDown()
alt = event.AltDown()
keyCode = event.GetKeyCode()
if event.GetKeyCode() == 1:
# Control+A
self.textCtrl.SetSelection(-1,-1)
elif event.GetKeyCode() == wx.WXK_HOME:
if not any([control, shift, alt]):
curPos = self.textCtrl.GetInsertionPoint()
lineNum = len(self.textCtrl.GetRange( 0, self.textCtrl.GetInsertionPoint() ).split("\n")) - 1
colNum = len(self.textCtrl.GetRange( 0, self.textCtrl.GetInsertionPoint() ).split("\n")[-1])
lineText = self.textCtrl.GetLineText(lineNum)
m = re.search("^\s*", lineText)
if not m:
raise Exception("This regular expression must match always.")
indent = len(m.group(0))
if indent == colNum:
newColNum = 0
else:
newColNum = indent
self.textCtrl.SetInsertionPoint(curPos - colNum + newColNum)
else:
event.Skip()
else:
event.Skip()
def OnKeyUP(self, event):
keyCode = event.GetKeyCode()
if keyCode == wx.WXK_ESCAPE:
self.text = self.textCtrl.GetValue()
self.EndModal(wx.ID_CANCEL)
wx.CallAfter(lambda: self.onTextComplete(wx.ID_CANCEL, self.text, None))
event.Skip()
def onOk(self, evt):
self.text = self.textCtrl.GetValue()
self.EndModal(wx.ID_OK)
wx.CallAfter(lambda: self.onTextComplete(wx.ID_OK, self.text, None))
def onCancel(self, evt):
self.text = self.textCtrl.GetValue()
self.EndModal(wx.ID_CANCEL)
wx.CallAfter(lambda: self.onTextComplete(wx.ID_CANCEL, self.text, None))
class SettingsDialog(gui.SettingsDialog):
# Translators: Title for the settings dialog
title = _("Tony's enhancements settings")
def __init__(self, *args, **kwargs):
super(SettingsDialog, self).__init__(*args, **kwargs)
self.dynamicKeystrokesTable = getConfig("dynamicKeystrokesTable")
self.langMap = getConfig("langMap")
def makeSettings(self, settingsSizer):
sHelper = gui.guiHelper.BoxSizerHelper(self, sizer=settingsSizer)
# checkbox Detect insert mode
# Translators: Checkbox for insert mode detection
label = _("Detect insert mode in text documents and beep on every keystroke when insert mode is on.")
self.detectInsertModeCheckbox = sHelper.addItem(wx.CheckBox(self, label=label))
self.detectInsertModeCheckbox.Value = getConfig("detectInsertMode")
# checkbox block double insert
# Translators: Checkbox for block double insert
label = _("Block double insert")
self.blockDoubleInsertCheckbox = sHelper.addItem(wx.CheckBox(self, label=label))
self.blockDoubleInsertCheckbox.Value = getConfig("blockDoubleInsert")
# checkbox block double caps
# Translators: Checkbox for block double caps
label = _("Block double Caps Lock")
self.blockDoubleCapsCheckbox = sHelper.addItem(wx.CheckBox(self, label=label))
self.blockDoubleCapsCheckbox.Value = getConfig("blockDoubleCaps")
# checkbox Busy beep
# Translators: Checkbox for busy beep
label = _("Beep when NVDA is busy")
self.busyBeepCheckbox = sHelper.addItem(wx.CheckBox(self, label=label))
self.busyBeepCheckbox.Value = getConfig("busyBeep")
# checkbox fix windows+Number
# Translators: Checkbox for windows_Number
label = _("Fix focus being stuck in the taskbar when pressing Windows+Number")
self.fixWindowNumberCheckbox = sHelper.addItem(wx.CheckBox(self, label=label))
self.fixWindowNumberCheckbox.Value = getConfig("fixWindowNumber")
# checkbox suppress unselected
# Translators: Checkbox for suppress unselected
label = _("Suppress saying of 'unselected'.")
self.suppressUnselectedCheckbox = sHelper.addItem(wx.CheckBox(self, label=label))
self.suppressUnselectedCheckbox.Value = getConfig("suppressUnselected")
# NVDA volume slider
sizer=wx.BoxSizer(wx.HORIZONTAL)
# Translators: slider to select NVDA volume
label=wx.StaticText(self,wx.ID_ANY,label=_("NVDA volume"))
slider=wx.Slider(self, wx.NewId(), minValue=0,maxValue=100)
slider.SetValue(getConfig("nvdaVolume"))
sizer.Add(label)
sizer.Add(slider)
settingsSizer.Add(sizer)
self.nvdaVolumeSlider = slider
# Dynamic keystrokes table
# Translators: Label for dynamic keystrokes table edit box
label = _("Edit dynamic keystrokes table - see add-on documentation for more information")
#self.dynamicKeystrokesEdit = gui.guiHelper.LabeledControlHelper(self, _("Dynamic keystrokes table - see add-on documentation for more information"), wx.TextCtrl, style=wx.TE_MULTILINE).control
#self.dynamicKeystrokesEdit.Value = getConfig("dynamicKeystrokesTable")
self.dynamicButton = sHelper.addItem (wx.Button (self, label = label))
self.dynamicButton.Bind(wx.EVT_BUTTON, self.onDynamicClick)
# LangMap checkbox and multiline edit button
label = _("Enable automatic language switching based on character set")
self.langMapCheckbox = sHelper.addItem(wx.CheckBox(self, label=label))
self.langMapCheckbox.Value = getConfig("enableLangMap")
label = _('Edit language map')
self.langMapButton = sHelper.addItem (wx.Button (self, label = label))
self.langMapButton.Bind(wx.EVT_BUTTON, self.onLangMapClick)
# QuickSearch regexp text edit
self.quickSearchEdit = gui.guiHelper.LabeledControlHelper(self, _("QuickSearch1 regexp (assigned to PrintScreen)"), wx.TextCtrl).control
self.quickSearchEdit.Value = getConfig("quickSearch1")
# QuickSearch2 regexp text edit
self.quickSearch2Edit = gui.guiHelper.LabeledControlHelper(self, _("QuickSearch2 regexp (assigned to ScrollLock))"), wx.TextCtrl).control
self.quickSearch2Edit.Value = getConfig("quickSearch2")
# QuickSearch3 regexp text edit
self.quickSearch3Edit = gui.guiHelper.LabeledControlHelper(self, _("QuickSearch3 regexp (assigned to Pause)"), wx.TextCtrl).control
self.quickSearch3Edit.Value = getConfig("quickSearch3")
# checkbox block scroll lock
# Translators: Checkbox for blocking scroll lock
label = _("Suppress scroll lock mode announcements")
self.blockScrollLockCheckbox = sHelper.addItem(wx.CheckBox(self, label=label))
self.blockScrollLockCheckbox.Value = getConfig("blockScrollLock")
# System priority Combo box
# Translators: Label for system priority combo box
label = _("NVDA process system priority:")
self.priorityCombobox = sHelper.addLabeledControl(label, wx.Choice, choices=priorityNames)
index = getConfig("priority")
self.priorityCombobox.Selection = index
def dynamicCallback(self, result, text, keystroke):
if result == wx.ID_OK:
try:
parseDynamicKeystrokes(text)
except Exception as e:
gui.messageBox(f"Error parsing dynamic keystrokes table: {e}",
_("Error"),wx.OK|wx.ICON_INFORMATION,self)
self.popupDynamic(text=text)
return
self.dynamicKeystrokesTable = text
def onDynamicClick(self, evt):
self.popupDynamic(text=self.dynamicKeystrokesTable)
def popupDynamic(self, text):
title = _('Edit dynamic keystrokes table')
gui.mainFrame.prePopup()
dialog = MultilineEditTextDialog(self,
text=text,
title_string=title,
onTextComplete=lambda result, text, keystroke: self.dynamicCallback(result, text, keystroke)
)
result = dialog.ShowModal()
gui.mainFrame.postPopup()
def langMapCallback(self, result, text, keystroke):
if result == wx.ID_OK:
try:
parseLangMap(text)
except Exception as e:
gui.messageBox(f"Error parsing language map: {e}",
_("Error"),wx.OK|wx.ICON_INFORMATION,self)
self.popupLangMap(text=text)
return
self.langMap = text
def onLangMapClick(self, evt):
self.popupLangMap(text=self.langMap)
def popupLangMap(self, text):
title = _('Edit language amp')
gui.mainFrame.prePopup()
dialog = MultilineEditTextDialog(self,
text=text,
title_string=title,
onTextComplete=lambda result, text, keystroke: self.langMapCallback(result, text, keystroke)
)
result = dialog.ShowModal()
gui.mainFrame.postPopup()
def onOk(self, evt):
try:
parseDynamicKeystrokes(self.dynamicKeystrokesTable)
except Exception as e:
self.dynamicButton.SetFocus()
ui.message(f"Error parsing dynamic keystrokes table: {e}")
return
setConfig("blockDoubleInsert", self.blockDoubleInsertCheckbox.Value)
setConfig("blockDoubleCaps", self.blockDoubleCapsCheckbox.Value)
setConfig("busyBeep", self.busyBeepCheckbox.Value)
setConfig("fixWindowNumber", self.fixWindowNumberCheckbox.Value)
setConfig("suppressUnselected", self.suppressUnselectedCheckbox.Value)
setConfig("detectInsertMode", self.detectInsertModeCheckbox.Value)
setConfig("nvdaVolume", self.nvdaVolumeSlider.Value)
setConfig("dynamicKeystrokesTable", self.dynamicKeystrokesTable)
reloadDynamicKeystrokes()
setConfig("enableLangMap", self.langMapCheckbox.Value)
setConfig("langMap", self.langMap)
reloadLangMap()
setConfig("quickSearch1", self.quickSearchEdit.Value)
setConfig("quickSearch2", self.quickSearch2Edit.Value)
setConfig("quickSearch3", self.quickSearch3Edit.Value)
setConfig("blockScrollLock", self.blockScrollLockCheckbox.Value)
updateScrollLockBlocking()
setConfig("priority", self.priorityCombobox.Selection)
updatePriority()
super(SettingsDialog, self).onOk(evt)
class Memoize:
def __init__(self, f):
self.f = f
self.memo = {}
def __call__(self, *args):
if not args in self.memo:
self.memo[args] = self.f(*args)
#Warning: You may wish to do a deepcopy here if returning objects
return self.memo[args]
class Beeper:
BASE_FREQ = speech.IDT_BASE_FREQUENCY
def getPitch(self, indent):
return self.BASE_FREQ*2**(indent/24.0) #24 quarter tones per octave.
BEEP_LEN = 10 # millis
PAUSE_LEN = 5 # millis
MAX_CRACKLE_LEN = 400 # millis
MAX_BEEP_COUNT = MAX_CRACKLE_LEN // (BEEP_LEN + PAUSE_LEN)
def __init__(self):
self.player = nvwave.WavePlayer(
channels=2,
samplesPerSec=int(tones.SAMPLE_RATE),
bitsPerSample=16,
outputDevice=config.conf["speech"]["outputDevice"],
wantDucking=False
)
self.stopSignal = False
def fancyCrackle(self, levels, volume):
levels = self.uniformSample(levels, self.MAX_BEEP_COUNT )
beepLen = self.BEEP_LEN
pauseLen = self.PAUSE_LEN
pauseBufSize = NVDAHelper.generateBeep(None,self.BASE_FREQ,pauseLen,0, 0)
beepBufSizes = [NVDAHelper.generateBeep(None,self.getPitch(l), beepLen, volume, volume) for l in levels]
bufSize = sum(beepBufSizes) + len(levels) * pauseBufSize
buf = ctypes.create_string_buffer(bufSize)
bufPtr = 0
for l in levels:
bufPtr += NVDAHelper.generateBeep(
ctypes.cast(ctypes.byref(buf, bufPtr), ctypes.POINTER(ctypes.c_char)),
self.getPitch(l), beepLen, volume, volume)
bufPtr += pauseBufSize # add a short pause
self.player.stop()
self.player.feed(buf.raw)
def simpleCrackle(self, n, volume):
return self.fancyCrackle([0] * n, volume)
NOTES = "A,B,H,C,C#,D,D#,E,F,F#,G,G#".split(",")
NOTE_RE = re.compile("[A-H][#]?")
BASE_FREQ = 220
def getChordFrequencies(self, chord):
myAssert(len(self.NOTES) == 12)
prev = -1
result = []
for m in self.NOTE_RE.finditer(chord):
s = m.group()
i =self.NOTES.index(s)
while i < prev:
i += 12
result.append(int(self.BASE_FREQ * (2 ** (i / 12.0))))
prev = i
return result
@Memoize
def prepareFancyBeep(self, chord, length, left=10, right=10):
beepLen = length
freqs = self.getChordFrequencies(chord)
intSize = 8 # bytes
bufSize = max([NVDAHelper.generateBeep(None,freq, beepLen, right, left) for freq in freqs])
if bufSize % intSize != 0:
bufSize += intSize
bufSize -= (bufSize % intSize)
bbs = []
result = [0] * (bufSize//intSize)
for freq in freqs:
buf = ctypes.create_string_buffer(bufSize)
NVDAHelper.generateBeep(buf, freq, beepLen, right, left)
bytes = bytearray(buf)
unpacked = struct.unpack("<%dQ" % (bufSize // intSize), bytes)
result = map(operator.add, result, unpacked)
maxInt = 1 << (8 * intSize)
result = map(lambda x : x %maxInt, result)
packed = struct.pack("<%dQ" % (bufSize // intSize), *result)
return packed
def fancyBeep(self, chord, length, left=10, right=10, repetitions=1 ):
self.player.stop()
buffer = self.prepareFancyBeep(self, chord, length, left, right)
self.player.feed(buffer)
repetitions -= 1
if repetitions > 0:
self.stopSignal = False
# This is a crappy implementation of multithreading. It'll deadlock if you poke it.
# Don't use for anything serious.
def threadFunc(repetitions):
for i in range(repetitions):
if self.stopSignal:
return
self.player.feed(buffer)
t = threading.Thread(target=threadFunc, args=(repetitions,))
t.start()
def uniformSample(self, a, m):
n = len(a)
if n <= m:
return a
# Here assume n > m
result = []
for i in range(0, m*n, n):
result.append(a[i // m])
return result
def stop(self):
self.stopSignal = True
self.player.stop()
originalWaveOpen = None
originalWatchdogAlive = None
originalWatchdogAsleep = None
def preWaveOpen(selfself, *args, **kwargs):
global originalWaveOpen
result = originalWaveOpen(selfself, *args, **kwargs)
volume = getConfig("nvdaVolume")
volume2 = int(0xFFFF * (volume / 100))
volume2 = volume2 | (volume2 << 16)
winmm.waveOutSetVolume(selfself._waveout, volume2)
return result
def findTableCell(selfself, gesture, movement="next", axis=None, index = 0):
from scriptHandler import isScriptWaiting
if isScriptWaiting():
return
formatConfig=config.conf["documentFormatting"].copy()
formatConfig["reportTables"]=True
try:
tableID, origRow, origCol, origRowSpan, origColSpan = selfself._getTableCellCoords(selfself.selection)
info = selfself._getTableCellAt(tableID, selfself.selection,origRow, origCol)
except LookupError:
# Translators: The message reported when a user attempts to use a table movement command
# when the cursor is not within a table.
ui.message(_("Not in a table cell"))
return
MAX_TABLE_DIMENSION = 500
edgeFound = False
for attempt in range(MAX_TABLE_DIMENSION):
tableID, origRow, origCol, origRowSpan, origColSpan = selfself._getTableCellCoords(info)
try:
info = selfself._getNearestTableCell(tableID, info, origRow, origCol, origRowSpan, origColSpan, movement, axis)
except LookupError:
edgeFound = True
break
if not edgeFound:
ui.message(_("Cannot find edge of table in this direction"))
info = self._getTableCellAt(tableID, self.selection,origRow, origCol)
info.collapse()
self.selection = info
return
if index > 1:
inverseMovement = "next" if movement == "previous" else "previous"
for i in range(1, index):
tableID, origRow, origCol, origRowSpan, origColSpan = selfself._getTableCellCoords(info)
try:
info = selfself._getNearestTableCell(tableID, selfself.selection, origRow, origCol, origRowSpan, origColSpan, inverseMovement, axis)
except LookupError:
ui.message(_("Cannot find {axis} with index {index} in this table").format(**locals()))
return
speech.speakTextInfo(info,formatConfig=formatConfig,reason=controlTypes.REASON_CARET)
info.collapse()
selfself.selection = info
def speakColumn(selfself, gesture):
movement = "next"
axis = "row"
from scriptHandler import isScriptWaiting
if isScriptWaiting():
return
formatConfig=config.conf["documentFormatting"].copy()
formatConfig["reportTables"]=True
try:
tableID, origRow, origCol, origRowSpan, origColSpan = selfself._getTableCellCoords(selfself.selection)
info = selfself._getTableCellAt(tableID, selfself.selection,origRow, origCol)
except LookupError:
# Translators: The message reported when a user attempts to use a table movement command
# when the cursor is not within a table.
ui.message(_("Not in a table cell"))
return
MAX_TABLE_DIMENSION = 500
for attempt in range(MAX_TABLE_DIMENSION):
speech.speakTextInfo(info, formatConfig=formatConfig, reason=controlTypes.REASON_CARET)
tableID, origRow, origCol, origRowSpan, origColSpan = selfself._getTableCellCoords(info)
try:
info = selfself._getNearestTableCell(tableID, info, origRow, origCol, origRowSpan, origColSpan, movement, axis)
except LookupError:
break
wdTime = 0
wdAsleep = False
wdTimeout = 0.3 # seconds
def preWatchdogAlive():
global wdTime, wdAsleep
current = time.time()
delta = current - wdTime
wdTime = current
wdAsleep = False
originalWatchdogAlive()
def preWatchdogAsleep():
global wdTime, wdAsleep
current = time.time()
delta = current - wdTime
wdTime = current
wdAsleep = True
originalWatchdogAsleep()
wdAsleep = True
class MyWatchdog(threading.Thread):
def __init__(self):
super().__init__()
self.stopSignal = False
def run(self):
global wdTime, wdAsleep, wdTimeout
time.sleep(5)
while not self.stopSignal:
if getConfig("busyBeep"):
while not wdAsleep and (time.time() - wdTime) > wdTimeout:
tones.beep(150, 10, left=25, right=25)
#time.sleep(0.01)
time.sleep(0.1)
def terminate(self):
self.stopSignal = True
gestureCounter = 0
storedText = None
speakAnywayAfter = 0.1 # seconds
def checkUpdate(localGestureCounter, attempt, originalTimestamp, gesture=None, spokenAnyway=False):
global gestureCounter, storedText
if gestureCounter != localGestureCounter:
return
try:
focus = api.getFocusObject()
textInfo = focus.makeTextInfo(textInfos.POSITION_CARET)
textInfo.expand(textInfos.UNIT_LINE)
text = textInfo.text
except Exception as e:
log.warning(f"Error retrieving text during dynamic keystroke handling: {e}")
return
if attempt == 0:
storedText = text
else:
if text != storedText:
if spokenAnyway:
speech.cancelSpeech()
speech.speakTextInfo(textInfo, unit=textInfos.UNIT_LINE)
return
elapsed = time.time() - originalTimestamp
if not spokenAnyway and elapsed > speakAnywayAfter:
speech.speakTextInfo(textInfo, unit=textInfos.UNIT_LINE)
spokenAnyway = True
if elapsed < 1.0:
sleepTime = 25 # ms
elif elapsed < 10:
sleepTime = 1000 # ms
else:
sleepTime = 5000
core.callLater(sleepTime, checkUpdate, localGestureCounter, attempt+1, originalTimestamp, spokenAnyway=spokenAnyway)
allModifiers = [
winUser.VK_LCONTROL, winUser.VK_RCONTROL,
winUser.VK_LSHIFT, winUser.VK_RSHIFT, winUser.VK_LMENU,
winUser.VK_RMENU, winUser.VK_LWIN, winUser.VK_RWIN,
]
def executeAsynchronously(gen):
"""
This function executes a generator-function in such a manner, that allows updates from the operating system to be processed during execution.
For an example of such generator function, please see GlobalPlugin.script_editJupyter.
Specifically, every time the generator function yilds a positive number,, the rest of the generator function will be executed
from within wx.CallLater() call.
If generator function yields a value of 0, then the rest of the generator function
will be executed from within wx.CallAfter() call.
This allows clear and simple expression of the logic inside the generator function, while still allowing NVDA to process update events from the operating system.
Essentially the generator function will be paused every time it calls yield, then the updates will be processed by NVDA and then the remainder of generator function will continue executing.
"""
if not isinstance(gen, types.GeneratorType):
raise Exception("Generator function required")
try:
value = gen.__next__()
except StopIteration:
return
l = lambda gen=gen: executeAsynchronously(gen)
core.callLater(value, executeAsynchronously, gen)
originalSpeechSpeak = None
def processLanguages(command):
if isinstance(command, speech.commands.LangChangeCommand):
return
if not isinstance(command, str):
yield command
return
s = command
global langMap
if False:
langMap = {
'en': re.compile(r'[a-zA-Z]'),
'ru': re.compile(r'[а-яА-Я]'),
}
curLang = None
i = -1
prev = 0
while i+1 < len(s):
minIndex = None
minLang = None
for lang, r in langMap.items():
if lang == curLang:
continue
m = r.search(s, pos=i+1)
if m is not None:
if minIndex is None or m.start(0) < minIndex:
minIndex = m.start(0)
minLang = lang
if minLang is not None:
if minIndex > prev:
yield s[prev:minIndex]
yield speech.commands.LangChangeCommand(minLang)
curLang = minLang
i = minIndex
prev = minIndex
else:
break
if i < len(s):
i = max(i, 0)
yield s[i:]
def newSpeechSpeak(speechSequence, *args, **kwargs):
sequence = speechSequence
if getConfig('enableLangMap'):
sequence = [subcommand for command in sequence for subcommand in processLanguages(command)]
#mylog(str(sequence))
return originalSpeechSpeak(sequence, *args, **kwargs)
originalSpeakSelectionChange = None
originalCaretMovementScriptHelper = None
performingShiftGesture = False
def preSpeakSelectionChange(oldInfo, newInfo, *args, **kwargs):
if getConfig('suppressUnselected') and not performingShiftGesture:
# Setting speakUnselected to false if user is not intending to select/unselect things
if len(args) >= 2:
args[1] = False
else:
kwargs['speakUnselected'] = False
return originalSpeakSelectionChange(oldInfo, newInfo, *args, **kwargs)
def updateScrollLockBlocking():
doBlock = getConfig("blockScrollLock")
TOGGLE_KEYS = {
winUser.VK_CAPITAL,
winUser.VK_NUMLOCK,
}
if not doBlock:
TOGGLE_KEYS.add(winUser.VK_SCROLL)
keyboardHandler.KeyboardInputGesture.TOGGLE_KEYS = frozenset(TOGGLE_KEYS)
updateScrollLockBlocking()
logSpeech = False
if True:
from speech.priorities import Spri
import traceback
originalSpeak = speech.speak
def speak(
speechSequence,
symbolLevel = None,
priority: Spri = Spri.NORMAL
):
if logSpeech:
mylog([s for s in speechSequence if isinstance(s, str)])
for line in traceback.format_stack():
mylog(" " + line.strip())
return originalSpeak(speechSequence, symbolLevel, priority)
speech.speak = speak
tones.beep(500, 500)
class GlobalPlugin(globalPluginHandler.GlobalPlugin):
scriptCategory = _("Tony's Enhancements")
def __init__(self, *args, **kwargs):
super(GlobalPlugin, self).__init__(*args, **kwargs)
self.createMenu()
self.injectHooks()
self.injectTableFunctions()
self.lastConsoleUpdateTime = 0
self.beeper = Beeper()
def createMenu(self):
def _popupMenu(evt):
gui.mainFrame._popupSettingsDialog(SettingsDialog)
self.prefsMenuItem = gui.mainFrame.sysTrayIcon.preferencesMenu.Append(wx.ID_ANY, _("Tony's enhancements..."))
gui.mainFrame.sysTrayIcon.Bind(wx.EVT_MENU, _popupMenu, self.prefsMenuItem)
def terminate(self):
self.removeHooks()
prefMenu = gui.mainFrame.sysTrayIcon.preferencesMenu
prefMenu.Remove(self.prefsMenuItem)
quickSearchGestures = ",PrintScreen,ScrollLock,Pause".split(",")
def injectHooks(self):
global originalWaveOpen, originalWatchdogAlive, originalWatchdogAsleep, originalSpeakSelectionChange, originalCaretMovementScriptHelper, originalSpeechSpeak
self.originalExecuteGesture = inputCore.InputManager.executeGesture
inputCore.InputManager.executeGesture = lambda selfself, gesture, *args, **kwargs: self.preExecuteGesture(selfself, gesture, *args, **kwargs)
originalWaveOpen = nvwave.WavePlayer.open
nvwave.WavePlayer.open = preWaveOpen
originalWatchdogAlive = watchdog.alive
watchdog.alive = preWatchdogAlive
originalWatchdogAsleep = watchdog.asleep
watchdog.asleep = preWatchdogAsleep
self.myWatchdog = MyWatchdog()
self.myWatchdog.setDaemon(True)
self.myWatchdog.start()
originalSpeakSelectionChange = speech.speakSelectionChange
speech.speakSelectionChange = preSpeakSelectionChange
originalSpeechSpeak = speech.speak
speech.speak = newSpeechSpeak
for i in [1,2,3]:
configKey = f"quickSearch{i}"
script = lambda selfself, gesture, configKey=configKey: self.script_quickSearch(selfself, gesture, getConfig(configKey))
script.category = "Tony's enhancements"
script.__name__ = _("QuickSearch") + str(i)
script.__doc__ = _("Performs QuickSearch back or forward in editables according to quickSearch{i} regexp").format(**locals())
setattr(editableText.EditableText, f"script_quickSearch{i}", script)
editableText.EditableText._EditableText__gestures[f"kb:{self.quickSearchGestures[i]}"] = f"quickSearch{i}"
editableText.EditableText._EditableText__gestures[f"kb:Shift+{self.quickSearchGestures[i]}"] = f"quickSearch{i}"
def removeHooks(self):
global originalWaveOpen
inputCore.InputManager.executeGesture = self.originalExecuteGesture
nvwave.WavePlayer.open = originalWaveOpen
watchdog.alive = originalWatchdogAlive
watchdog.asleep = originalWatchdogAsleep
self.myWatchdog.terminate()
speech.speakSelectionChange = originalSpeakSelectionChange
speech.speak = originalSpeechSpeak
for i in [1,2,3]:
delattr(editableText.EditableText, f"script_quickSearch{i}")
del editableText.EditableText._EditableText__gestures[f"kb:{self.quickSearchGestures[i]}"]
del editableText.EditableText._EditableText__gestures[f"kb:Shift+{self.quickSearchGestures[i]}"]
windowsSwitchingRe = re.compile(r':windows\+\d$')
typingKeystrokeRe = re.compile(r':((shift\+)?[A-Za-z0-9]|space)$')
shiftSelectionKeystroke = re.compile(r':(control\+)?shift\+((up|down|left|right)Arrow|home|end|pageUp|pageDown)$')
def preExecuteGesture(self, selfself, gesture, *args, **kwargs):
global gestureCounter, editorMovingCaret, performingShiftGesture
gestureCounter += 1
editorMovingCaret = False
if (
getConfig("blockDoubleInsert") and
gesture.vkCode == winUser.VK_INSERT and
not gesture.isNVDAModifierKey
):
tones.beep(500, 50)
return
if (
getConfig("blockDoubleCaps") and
gesture.vkCode == winUser.VK_CAPITAL and
not gesture.isNVDAModifierKey
):
tones.beep(500, 50)
return
kb = gesture.identifiers
if len(kb) == 0:
pass
else:
kb = kb[0]
focus = api.getFocusObject()
appName = focus.appModule.appName
if(
dynamicKeystrokes is not None and (
("*", kb) in dynamicKeystrokes
or (appName, kb) in dynamicKeystrokes
)
):
core.callLater(0,
checkUpdate,
gestureCounter, 0, time.time(), gesture
)
if getConfig("fixWindowNumber") and self.windowsSwitchingRe.search(kb) is not None:
executeAsynchronously(self.asyncSwitchWindowHandler(gestureCounter))
if getConfig("detectInsertMode") and self.typingKeystrokeRe.search(kb):
text = None
caret = None
executeAsynchronously(self.insertModeDetector(gestureCounter, text, caret))
if getConfig('suppressUnselected') and self.shiftSelectionKeystroke.search(kb) is not None:
performingShiftGesture = True
else:
performingShiftGesture = False
return self.originalExecuteGesture(selfself, gesture, *args, **kwargs)
def asyncSwitchWindowHandler(self, thisGestureCounter):
global gestureCounter
timeout = time.time() + 2
yield 1
# step 1. wait for all modifiers to be released
while True:
if time.time() > timeout:
return
if gestureCounter != thisGestureCounter:
return
status = [
winUser.getKeyState(k) & 32768
for k in allModifiers
]
if not any(status):
break
yield 1
# Step 2
#for i in range(100):
yield 50
if gestureCounter != thisGestureCounter:
return
if True:
focus = api.getFocusObject()
if focus.appModule.appName == "explorer":
if focus.windowClassName == "TaskListThumbnailWnd":
kbdEnter = keyboardHandler.KeyboardInputGesture.fromName("Enter")
kbdEnter.send()
tones.beep(100, 20)
return
def getCurrentLineAndCaret(self):
focus = api.getFocusObject()
caretInfo = focus.makeTextInfo(textInfos.POSITION_SELECTION)
if len(caretInfo.text) > 0:
return "", -10
lineInfo = caretInfo.copy()
lineInfo.expand(textInfos.UNIT_LINE)
lineText = lineInfo.text
# Command line prompt reports every line containing ~120 whitespaces, therefore it appears as if insert mode is on and is overwriting spaces.