forked from nvaccess/nvda
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbraille.py
3847 lines (3496 loc) · 144 KB
/
braille.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
# A part of NonVisual Desktop Access (NVDA)
# This file is covered by the GNU General Public License.
# See the file COPYING for more details.
# Copyright (C) 2008-2024 NV Access Limited, Joseph Lee, Babbage B.V., Davy Kager, Bram Duvigneau,
# Leonard de Ruijter, Burman's Computer and Education Ltd., Julien Cochuyt
from enum import StrEnum
import itertools
import typing
from typing import (
TYPE_CHECKING,
Any,
Callable,
Dict,
Generator,
Iterable,
List,
NamedTuple,
Optional,
Set,
Tuple,
Union,
Type,
)
from locale import strxfrm
from annotation import _AnnotationRolesT
import driverHandler
import pkgutil
import importlib
import contextlib
import ctypes.wintypes
import threading
import time
import wx
import louisHelper
import louis
import gui
from controlTypes.state import State
import winKernel
import keyboardHandler
import baseObject
import config
from config.configFlags import (
ShowMessages,
TetherTo,
BrailleMode,
ReportTableHeaders,
OutputMode,
)
from config.featureFlagEnums import ReviewRoutingMovesSystemCaretFlag, FontFormattingBrailleModeFlag
from logHandler import log
import controlTypes
import api
import textInfos
import brailleDisplayDrivers
import inputCore
import brailleTables
import re
import scriptHandler
import collections
import extensionPoints
import hwPortUtils
import bdDetect
import queueHandler
import brailleViewer
from autoSettingsUtils.driverSetting import BooleanDriverSetting, NumericDriverSetting
from utils.security import objectBelowLockScreenAndWindowsIsLocked
from textUtils import isUnicodeNormalized, UnicodeNormalizationOffsetConverter
import hwIo
from editableText import EditableText
if TYPE_CHECKING:
from NVDAObjects import NVDAObject
from speech.types import SpeechSequence
FALLBACK_TABLE = config.conf.getConfigValidation(("braille", "translationTable")).default
"""Table to use if the output table configuration is invalid."""
roleLabels: typing.Dict[controlTypes.Role, str] = {
# Translators: Displayed in braille for an object which is a
# window.
controlTypes.Role.WINDOW: _("wnd"),
# Translators: Displayed in braille for an object which is a
# dialog.
controlTypes.Role.DIALOG: _("dlg"),
# Translators: Displayed in braille for an object which is a
# check box.
controlTypes.Role.CHECKBOX: _("chk"),
# Translators: Displayed in braille for an object which is a
# radio button.
controlTypes.Role.RADIOBUTTON: _("rbtn"),
# Translators: Displayed in braille for an object which is an
# editable text field.
controlTypes.Role.EDITABLETEXT: _("edt"),
# Translators: Displayed in braille for an object which is a
# button.
controlTypes.Role.BUTTON: _("btn"),
# Translators: Displayed in braille for an object which is a
# menu bar.
controlTypes.Role.MENUBAR: _("mnubar"),
# Translators: Displayed in braille for an object which is a
# menu item.
controlTypes.Role.MENUITEM: _("mnuitem"),
# Translators: Displayed in braille for an object which is a
# menu.
controlTypes.Role.POPUPMENU: _("mnu"),
# Translators: Displayed in braille for an object which is a
# combo box.
controlTypes.Role.COMBOBOX: _("cbo"),
# Translators: Displayed in braille for an object which is a
# list.
controlTypes.Role.LIST: _("lst"),
# Translators: Displayed in braille for an object which is a
# graphic.
controlTypes.Role.GRAPHIC: _("gra"),
# Translators: Displayed in braille for toast notifications and for an object which is a
# help balloon.
controlTypes.Role.HELPBALLOON: _("hlp"),
# Translators: Displayed in braille for an object which is a
# tool tip.
controlTypes.Role.TOOLTIP: _("tltip"),
# Translators: Displayed in braille for an object which is a
# link.
controlTypes.Role.LINK: _("lnk"),
# Translators: Displayed in braille for an object which is a
# tree view.
controlTypes.Role.TREEVIEW: _("tv"),
# Translators: Displayed in braille for an object which is a
# tree view item.
controlTypes.Role.TREEVIEWITEM: _("tvitem"),
# Translators: Displayed in braille for an object which is a
# tab control.
controlTypes.Role.TABCONTROL: _("tabctl"),
# Translators: Displayed in braille for an object which is a
# progress bar.
controlTypes.Role.PROGRESSBAR: _("prgbar"),
# Translators: Displayed in braille for an object which is an
# indeterminate progress bar, aka busy indicator.
controlTypes.Role.BUSY_INDICATOR: _("bsyind"),
# Translators: Displayed in braille for an object which is a
# scroll bar.
controlTypes.Role.SCROLLBAR: _("scrlbar"),
# Translators: Displayed in braille for an object which is a
# status bar.
controlTypes.Role.STATUSBAR: _("stbar"),
# Translators: Displayed in braille for an object which is a
# table.
controlTypes.Role.TABLE: _("tbl"),
# Translators: Displayed in braille for an object which is a
# tool bar.
controlTypes.Role.TOOLBAR: _("tlbar"),
# Translators: Displayed in braille for an object which is a
# drop down button.
controlTypes.Role.DROPDOWNBUTTON: _("drbtn"),
# Displayed in braille for an object which is a
# separator.
controlTypes.Role.SEPARATOR: "⠤⠤⠤⠤⠤",
# Translators: Displayed in braille for an object which is a
# block quote.
controlTypes.Role.BLOCKQUOTE: _("bqt"),
# Translators: Displayed in braille for an object which is a
# document.
controlTypes.Role.DOCUMENT: _("doc"),
# Translators: Displayed in braille for an object which is a
# application.
controlTypes.Role.APPLICATION: _("app"),
# Translators: Displayed in braille for an object which is a
# grouping.
controlTypes.Role.GROUPING: _("grp"),
# Translators: Displayed in braille for an object which is a
# caption.
controlTypes.Role.CAPTION: _("cap"),
# Translators: Displayed in braille for an object which is a
# embedded object.
controlTypes.Role.EMBEDDEDOBJECT: _("embedded"),
# Translators: Displayed in braille for an object which is a
# end note.
controlTypes.Role.ENDNOTE: _("enote"),
# Translators: Displayed in braille for an object which is a
# foot note.
controlTypes.Role.FOOTNOTE: _("fnote"),
# Translators: Displayed in braille for an object which is a
# terminal.
controlTypes.Role.TERMINAL: _("term"),
# Translators: Displayed in braille for an object which is a
# section.
controlTypes.Role.SECTION: _("sect"),
# Translators: Displayed in braille for an object which is a
# toggle button.
controlTypes.Role.TOGGLEBUTTON: _("tgbtn"),
# Translators: Displayed in braille for an object which is a
# split button.
controlTypes.Role.SPLITBUTTON: _("splbtn"),
# Translators: Displayed in braille for an object which is a
# menu button.
controlTypes.Role.MENUBUTTON: _("mnubtn"),
# Translators: Displayed in braille for an object which is a
# spin button.
controlTypes.Role.SPINBUTTON: _("spnbtn"),
# Translators: Displayed in braille for an object which is a
# tree view button.
controlTypes.Role.TREEVIEWBUTTON: _("tvbtn"),
# Translators: Displayed in braille for an object which is a
# menu.
controlTypes.Role.MENU: _("mnu"),
# Translators: Displayed in braille for an object which is a
# panel.
controlTypes.Role.PANEL: _("pnl"),
# Translators: Displayed in braille for an object which is a
# password edit.
controlTypes.Role.PASSWORDEDIT: _("pwdedt"),
# Translators: Displayed in braille for an object which is deleted.
controlTypes.Role.DELETED_CONTENT: _("del"),
# Translators: Displayed in braille for an object which is inserted.
controlTypes.Role.INSERTED_CONTENT: _("ins"),
# Translators: Displayed in braille for a landmark.
controlTypes.Role.LANDMARK: _("lmk"),
# Translators: Displayed in braille for an object which is an article.
controlTypes.Role.ARTICLE: _("art"),
# Translators: Displayed in braille for an object which is a region.
controlTypes.Role.REGION: _("rgn"),
# Translators: Displayed in braille for an object which is a figure.
controlTypes.Role.FIGURE: _("fig"),
# Translators: Displayed in braille for an object which represents marked (highlighted) content
controlTypes.Role.MARKED_CONTENT: _("hlght"),
# Translators: Displayed in braille when an object is a comment.
controlTypes.Role.COMMENT: _("cmnt"),
# Translators: Displayed in braille when an object is a suggestion.
controlTypes.Role.SUGGESTION: _("sggstn"),
# Translators: Displayed in braille when an object is a definition.
controlTypes.Role.DEFINITION: _("definition"),
# Translators: Displayed in braille when an object is a switch control
controlTypes.Role.SWITCH: _("swtch"),
}
positiveStateLabels = {
# Translators: Displayed in braille when an object is selected.
controlTypes.State.SELECTED: _("sel"),
# Displayed in braille when an object (e.g. a toggle button) is pressed.
controlTypes.State.PRESSED: "⢎⣿⡱",
# Displayed in braille when an object (e.g. a toggle button) is half pressed.
controlTypes.State.HALF_PRESSED: "⢎⣸⡱",
# Displayed in braille when an object (e.g. a check box) is checked.
controlTypes.State.CHECKED: "⣏⣿⣹",
# Displayed in braille when an object (e.g. a check box) is half checked.
controlTypes.State.HALFCHECKED: "⣏⣸⣹",
# Translators: Displayed in braille when an object (e.g. an editable text field) is read-only.
controlTypes.State.READONLY: _("ro"),
# Translators: Displayed in braille when an object (e.g. a tree view item) is expanded.
controlTypes.State.EXPANDED: _("-"),
# Translators: Displayed in braille when an object (e.g. a tree view item) is collapsed.
controlTypes.State.COLLAPSED: _("+"),
# Translators: Displayed in braille when an object has a popup (usually a sub-menu).
controlTypes.State.HASPOPUP: _("submnu"),
# Translators: Displayed in braille when a protected control or a document is encountered.
controlTypes.State.PROTECTED: _("***"),
# Translators: Displayed in braille when a required form field is encountered.
controlTypes.State.REQUIRED: _("req"),
# Translators: Displayed in braille when an invalid entry has been made.
controlTypes.State.INVALID_ENTRY: _("invalid"),
# Translators: Displayed in braille when an object supports autocompletion.
controlTypes.State.AUTOCOMPLETE: _("..."),
# Translators: Displayed in braille when an edit field allows typing multiple lines of text such as comment fields on websites.
controlTypes.State.MULTILINE: _("mln"),
# Translators: Displayed in braille when an object is clickable.
controlTypes.State.CLICKABLE: _("clk"),
# Translators: Displayed in braille when an object is sorted ascending.
controlTypes.State.SORTED_ASCENDING: _("sorted asc"),
# Translators: Displayed in braille when an object is sorted descending.
controlTypes.State.SORTED_DESCENDING: _("sorted desc"),
# Translators: Displayed in braille when an object (usually a graphic) has a long description.
controlTypes.State.HASLONGDESC: _("ldesc"),
# Translators: Displayed in braille when there is a formula on a spreadsheet cell.
controlTypes.State.HASFORMULA: _("frml"),
# Translators: Displayed in braille when there is a comment for a spreadsheet cell or piece of text in a document.
controlTypes.State.HASCOMMENT: _("cmnt"),
# Translators: Displayed in braille when a control is switched on
controlTypes.State.ON: "⣏⣿⣹",
# Translators: Displayed in braille when a link destination points to the same page
controlTypes.State.INTERNAL_LINK: _("smp"),
}
negativeStateLabels = {
# Translators: Displayed in braille when an object is not selected.
controlTypes.State.SELECTED: _("nsel"),
# Displayed in braille when an object (e.g. a toggle button) is not pressed.
controlTypes.State.PRESSED: "⢎⣀⡱",
# Displayed in braille when an object (e.g. a check box) is not checked.
controlTypes.State.CHECKED: "⣏⣀⣹",
# Displayed in braille when an object (e.g. a switch control) is switched off.
controlTypes.State.ON: "⣏⣀⣹",
}
landmarkLabels = {
# Translators: Displayed in braille for the banner landmark, normally found on web pages.
"banner": pgettext("braille landmark abbreviation", "bnnr"),
# Translators: Displayed in braille for the complementary landmark, normally found on web pages.
"complementary": pgettext("braille landmark abbreviation", "cmpl"),
# Translators: Displayed in braille for the contentinfo landmark, normally found on web pages.
"contentinfo": pgettext("braille landmark abbreviation", "cinf"),
# Translators: Displayed in braille for the main landmark, normally found on web pages.
"main": pgettext("braille landmark abbreviation", "main"),
# Translators: Displayed in braille for the navigation landmark, normally found on web pages.
"navigation": pgettext("braille landmark abbreviation", "navi"),
# Translators: Displayed in braille for the search landmark, normally found on web pages.
"search": pgettext("braille landmark abbreviation", "srch"),
# Translators: Displayed in braille for the form landmark, normally found on web pages.
"form": pgettext("braille landmark abbreviation", "form"),
}
#: Cursor shapes
CURSOR_SHAPES = (
# Translators: The description of a braille cursor shape.
(0xC0, _("Dots 7 and 8")),
# Translators: The description of a braille cursor shape.
(0x80, _("Dot 8")),
# Translators: The description of a braille cursor shape.
(0xFF, _("All dots")),
)
SELECTION_SHAPE = 0xC0 #: Dots 7 and 8
END_OF_BRAILLE_OUTPUT_SHAPE = 0xFF # All dots
"""
The braille shape shown on a braille display when
the number of cells used by the braille handler is lower than the actual number of cells.
The 0 based position of the shape is equal to the number of cells used by the braille handler.
"""
#: Unicode braille indicator at the start of untranslated braille input.
INPUT_START_IND = "⣏"
#: Unicode braille indicator at the end of untranslated braille input.
INPUT_END_IND = " ⣹"
class FormatTagDelimiter(StrEnum):
"""Delimiters for the start and end of format tags.
As these are shapes, they should be provided in unicode braille.
"""
START = "⣋"
END = "⣙"
# used to separate chunks of text when programmatically joined
TEXT_SEPARATOR = " "
#: Identifier for a focus context presentation setting that
#: only shows as much as possible focus context information when the context has changed.
CONTEXTPRES_CHANGEDCONTEXT = "changedContext"
#: Identifier for a focus context presentation setting that
#: shows as much as possible focus context information if the focus object doesn't fill up the whole display.
CONTEXTPRES_FILL = "fill"
#: Identifier for a focus context presentation setting that
#: always shows the object with focus at the very left of the braille display.
CONTEXTPRES_SCROLL = "scroll"
#: Focus context presentations associated with their user readable and translatable labels
focusContextPresentations = [
# Translators: The label for a braille focus context presentation setting that
# only shows as much as possible focus context information when the context has changed.
(CONTEXTPRES_CHANGEDCONTEXT, _("Fill display for context changes")),
# Translators: The label for a braille focus context presentation setting that
# shows as much as possible focus context information if the focus object doesn't fill up the whole display.
# This was the pre NVDA 2017.3 default.
(CONTEXTPRES_FILL, _("Always fill display")),
# Translators: The label for a braille focus context presentation setting that
# always shows the object with focus at the very left of the braille display
# (i.e. you will have to scroll back for focus context information).
(CONTEXTPRES_SCROLL, _("Only when scrolling back")),
]
#: Named tuple for a region with start and end positions in a buffer
RegionWithPositions = collections.namedtuple("RegionWithPositions", ("region", "start", "end"))
#: Automatic constant to be used by braille displays that support the "automatic" port
#: and automatic braille display detection
#: @type: tuple
# Translators: String representing automatic port selection for braille displays.
AUTOMATIC_PORT = ("auto", _("Automatic"))
#: Used in place of a specific braille display driver name to indicate that
#: braille displays should be automatically detected and used.
#: @type: str
AUTO_DISPLAY_NAME = AUTOMATIC_PORT[0]
NO_BRAILLE_DISPLAY_NAME: str = "noBraille"
"""The name of the noBraille display driver."""
#: A port name which indicates that USB should be used.
#: @type: tuple
# Translators: String representing the USB port selection for braille displays.
USB_PORT = ("usb", _("USB"))
#: A port name which indicates that Bluetooth should be used.
#: @type: tuple
# Translators: String representing the Bluetooth port selection for braille displays.
BLUETOOTH_PORT = ("bluetooth", _("Bluetooth"))
class FormattingMarker(NamedTuple):
"""A pair of braille symbols that indicate the start and end of a particular type of font formatting.
As these are shapes, they should be provided in unicode braille.
"""
start: str
end: str
fontAttributeFormattingMarkers: dict[str, FormattingMarker] = {
"bold": FormattingMarker(
# Translators: Brailled at the start of bold text.
# This is the English letter "b" in braille.
start=pgettext("braille formatting symbol", "⠃"),
# Translators: Brailled at the end of bold text.
# This is the English letter "b" plus dot 7 in braille.
end=pgettext("braille formatting symbol", "⡃"),
),
"italic": FormattingMarker(
# Translators: Brailled at the start of italic text.
# This is the English letter "i" in braille.
start=pgettext("braille formatting symbol", "⠊"),
# Translators: Brailled at the end of italic text.
# This is the English letter "i" plus dot 7 in braille.
end=pgettext("braille formatting symbol", "⡊"),
),
"underline": FormattingMarker(
# Translators: Brailled at the start of underlined text.
# This is the English letter "u" in braille.
start=pgettext("braille formatting symbol", "⠥"),
# Translators: Brailled at the end of underlined text.
# This is the English letter "u" plus dot 7 in braille.
end=pgettext("braille formatting symbol", "⡥"),
),
"strikethrough": FormattingMarker(
# Translators: Brailled at the start of strikethrough text.
# This is the English letter "s" in braille.
start=pgettext("braille formatting symbol", "⠎"),
# Translators: Brailled at the end of strikethrough text.
# This is the English letter "s" plus dot 7 in braille.
end=pgettext("braille formatting symbol", "⡎"),
),
}
def NVDAObjectHasUsefulText(obj: "NVDAObject") -> bool:
"""Does obj contain useful text to display in braille
:param obj: object to check
:return: True if there is useful text, False if not
"""
if objectBelowLockScreenAndWindowsIsLocked(obj):
return False
import displayModel
if issubclass(obj.TextInfo, displayModel.DisplayModelTextInfo):
# #1711: Flat review (using displayModel) should always be presented on the braille display
return True
if obj._hasNavigableText or isinstance(obj, EditableText):
return True
return False
def _getDisplayDriver(moduleName: str, caseSensitive: bool = True) -> Type["BrailleDisplayDriver"]:
try:
return importlib.import_module(
"brailleDisplayDrivers.%s" % moduleName,
package="brailleDisplayDrivers",
).BrailleDisplayDriver
except ImportError as initialException:
if caseSensitive:
raise initialException
for loader, name, isPkg in pkgutil.iter_modules(brailleDisplayDrivers.__path__):
if name.startswith("_") or name.lower() != moduleName.lower():
continue
return importlib.import_module(
"brailleDisplayDrivers.%s" % name,
package="brailleDisplayDrivers",
).BrailleDisplayDriver
else:
raise initialException
def getDisplayList(excludeNegativeChecks=True) -> List[Tuple[str, str]]:
"""Gets a list of available display driver names with their descriptions.
@param excludeNegativeChecks: excludes all drivers for which the check method returns C{False}.
@type excludeNegativeChecks: bool
@return: list of tuples with driver names and descriptions.
"""
displayList = []
# The display that should be placed at the end of the list.
lastDisplay = None
for display in getDisplayDrivers():
try:
if not excludeNegativeChecks or display.check():
if display.name == "noBraille":
lastDisplay = (display.name, display.description)
else:
displayList.append((display.name, display.description))
else:
log.debugWarning(f"Braille display driver {display.name} reports as unavailable, excluding")
except: # noqa: E722
log.error("", exc_info=True)
displayList.sort(key=lambda d: strxfrm(d[1]))
if lastDisplay:
displayList.append(lastDisplay)
return displayList
class Region(object):
"""A region of braille to be displayed.
Each portion of braille to be displayed is represented by a region.
The region is responsible for retrieving its text and the cursor and selection positions, translating it into braille cells and handling cursor routing requests relative to its braille cells.
The L{BrailleBuffer} containing this region will call L{update} and expect that L{brailleCells}, L{brailleCursorPos}, L{brailleSelectionStart} and L{brailleSelectionEnd} will be set appropriately.
L{routeTo} will be called to handle a cursor routing request.
"""
def __init__(self):
#: The original, raw text of this region.
self.rawText = ""
#: The position of the cursor in L{rawText}, C{None} if the cursor is not in this region.
#: @type: int
self.cursorPos = None
#: The start of the selection in L{rawText} (inclusive), C{None} if there is no selection in this region.
#: @type: int
self.selectionStart = None
#: The end of the selection in L{rawText} (exclusive), C{None} if there is no selection in this region.
#: @type: int
self.selectionEnd = None
#: The translated braille representation of this region.
#: @type: [int, ...]
self.brailleCells = []
#: liblouis typeform flags for each character in L{rawText},
#: C{None} if no typeform info.
#: @type: [int, ...]
self.rawTextTypeforms = None
#: A list mapping positions in L{rawText} to positions in L{brailleCells}.
#: @type: [int, ...]
self.rawToBraillePos = []
#: A list mapping positions in L{brailleCells} to positions in L{rawText}.
#: @type: [int, ...]
self.brailleToRawPos = []
#: The position of the cursor in L{brailleCells}, C{None} if the cursor is not in this region.
self.brailleCursorPos: Optional[int] = None
#: The position of the selection start in L{brailleCells}, C{None} if there is no selection in this region.
#: @type: int
self.brailleSelectionStart = None
#: The position of the selection end in L{brailleCells}, C{None} if there is no selection in this region.
#: @type: int
self.brailleSelectionEnd = None
#: Whether to hide all previous regions.
#: @type: bool
self.hidePreviousRegions = False
#: Whether this region should be positioned at the absolute left of the display when focused.
#: @type: bool
self.focusToHardLeft = False
def update(self):
"""Update this region.
Subclasses should extend this to update L{rawText}, L{cursorPos}, L{selectionStart} and L{selectionEnd} if necessary.
The base class method handles translation of L{rawText} into braille, placing the result in L{brailleCells}.
Typeform information from L{rawTextTypeforms} is used, if any.
L{rawToBraillePos} and L{brailleToRawPos} are updated according to the translation.
L{brailleCursorPos}, L{brailleSelectionStart} and L{brailleSelectionEnd} are similarly updated based on L{cursorPos}, L{selectionStart} and L{selectionEnd}, respectively.
@postcondition: L{brailleCells}, L{brailleCursorPos}, L{brailleSelectionStart} and L{brailleSelectionEnd} are updated and ready for rendering.
"""
mode = louis.dotsIO
if config.conf["braille"]["expandAtCursor"] and self.cursorPos is not None:
mode |= louis.compbrlAtCursor
converter: UnicodeNormalizationOffsetConverter | None = None
textToTranslate = self.rawText
textToTranslateTypeforms = self.rawTextTypeforms
cursorPos = self.cursorPos
if config.conf["braille"]["unicodeNormalization"] and not isUnicodeNormalized(textToTranslate):
converter = UnicodeNormalizationOffsetConverter(textToTranslate)
textToTranslate = converter.encoded
if textToTranslateTypeforms is not None:
# Typeforms must be adapted to represent normalized characters.
textToTranslateTypeforms = [
textToTranslateTypeforms[strOffset] for strOffset in converter.computedEncodedToStrOffsets
]
if cursorPos is not None:
# Convert the cursor position to a normalized offset.
cursorPos = converter.strToEncodedOffsets(cursorPos)
self.brailleCells, brailleToRawPos, rawToBraillePos, self.brailleCursorPos = louisHelper.translate(
[handler.table.fileName, "braille-patterns.cti"],
textToTranslate,
typeform=textToTranslateTypeforms,
mode=mode,
cursorPos=cursorPos,
)
if converter:
# The received brailleToRawPos contains braille to normalized positions.
# Process them to represent real raw positions by converting them from normalized ones.
brailleToRawPos = [converter.encodedToStrOffsets(i) for i in brailleToRawPos]
# The received rawToBraillePos contains normalized to braille positions.
# Create a new list based on real raw positions.
rawToBraillePos = [rawToBraillePos[i] for i in converter.computedStrToEncodedOffsets]
self.brailleToRawPos = brailleToRawPos
self.rawToBraillePos = rawToBraillePos
if (
self.selectionStart is not None
and self.selectionEnd is not None
and config.conf["braille"]["showSelection"]
):
try:
# Mark the selection.
self.brailleSelectionStart = self.rawToBraillePos[self.selectionStart]
if self.selectionEnd >= len(self.rawText):
self.brailleSelectionEnd = len(self.brailleCells)
else:
self.brailleSelectionEnd = self.rawToBraillePos[self.selectionEnd]
for pos in range(self.brailleSelectionStart, self.brailleSelectionEnd):
self.brailleCells[pos] |= SELECTION_SHAPE
except IndexError:
pass
def routeTo(self, braillePos):
"""Handle a cursor routing request.
For example, this might activate an object or move the cursor to the requested position.
@param braillePos: The routing position in L{brailleCells}.
@type braillePos: int
@note: If routing the cursor, L{brailleToRawPos} can be used to translate L{braillePos} into a position in L{rawText}.
"""
def nextLine(self):
"""Move to the next line if possible."""
def previousLine(self, start=False):
"""Move to the previous line if possible.
@param start: C{True} to move to the start of the line, C{False} to move to the end.
@type start: bool
"""
def __repr__(self):
return f"{self.__class__.__name__} ({self.rawText!r})"
class TextRegion(Region):
"""A simple region containing a string of text."""
def __init__(self, text):
super(TextRegion, self).__init__()
self.rawText = text
def _getAnnotationProperty(
propertyValues: Dict[str, Any],
) -> str:
# Translators: Braille when there are further details/annotations that can be fetched manually.
genericDetailsRole = _("details")
detailsRoles: _AnnotationRolesT = propertyValues.get("detailsRoles", tuple())
if not detailsRoles:
log.debugWarning(
"There should always be detailsRoles (at least a single None value) when hasDetails is true.",
)
return genericDetailsRole
else:
# Translators: Braille when there are further details/annotations that can be fetched manually.
# %s specifies the type of details (e.g. "has comment suggestion")
hasDetailsRoleTemplate = _("has %s")
rolesLabels = list(
(
hasDetailsRoleTemplate % roleLabels.get(role, role.displayString)
for role in detailsRoles
if role # handle None case without the "has X" grammar.
)
)
if None in detailsRoles:
rolesLabels.insert(0, genericDetailsRole)
return " ".join(rolesLabels) # no comma to save cells on braille display
# C901 'getPropertiesBraille' is too complex
# Note: when working on getPropertiesBraille, look for opportunities to simplify
# and move logic out into smaller helper functions.
def getPropertiesBraille(**propertyValues) -> str: # noqa: C901
textList = []
name = propertyValues.get("name")
if name:
textList.append(name)
role: Optional[Union[controlTypes.Role, int]] = propertyValues.get("role")
roleText = propertyValues.get("roleText")
states = propertyValues.get("states")
positionInfo = propertyValues.get("positionInfo")
level = positionInfo.get("level") if positionInfo else None
cellCoordsText = propertyValues.get("cellCoordsText")
rowNumber = propertyValues.get("rowNumber")
columnNumber = propertyValues.get("columnNumber")
# When fetching row and column span
# default the values to 1 to make further checks a lot simpler.
# After all, a table cell that has no rowspan implemented is assumed to span one row.
rowSpan = propertyValues.get("rowSpan") or 1
columnSpan = propertyValues.get("columnSpan") or 1
includeTableCellCoords = propertyValues.get("includeTableCellCoords", True)
if role is not None and not roleText:
role = controlTypes.Role(role)
if role == controlTypes.Role.HEADING and level:
# Translators: Displayed in braille for a heading with a level.
# %s is replaced with the level.
roleText = _("h%s") % level
level = None
elif role == controlTypes.Role.LINK and states and controlTypes.State.VISITED in states:
states = states.copy()
states.discard(controlTypes.State.VISITED)
# Translators: Displayed in braille for a link which has been visited.
roleText = _("vlnk")
elif (
name or cellCoordsText or rowNumber or columnNumber
) and role in controlTypes.silentRolesOnFocus:
roleText = None
else:
roleText = roleLabels.get(role, role.displayString)
elif role is None:
role = propertyValues.get("_role")
value = propertyValues.get("value")
if value and role not in controlTypes.silentValuesForRoles:
textList.append(value)
if states is not None:
textList.extend(
controlTypes.processAndLabelStates(
role,
states,
controlTypes.OutputReason.FOCUS,
states,
None,
positiveStateLabels,
negativeStateLabels,
),
)
if roleText:
textList.append(roleText)
errorMessage = propertyValues.get("errorMessage")
if errorMessage:
textList.append(errorMessage)
description = propertyValues.get("description")
if description:
textList.append(description)
hasDetails = propertyValues.get("hasDetails")
if hasDetails:
textList.append(_getAnnotationProperty(propertyValues))
keyboardShortcut = propertyValues.get("keyboardShortcut")
if keyboardShortcut:
textList.append(keyboardShortcut)
if positionInfo:
indexInGroup = positionInfo.get("indexInGroup")
similarItemsInGroup = positionInfo.get("similarItemsInGroup")
if indexInGroup and similarItemsInGroup:
# Translators: Brailled to indicate the position of an item in a group of items (such as a list).
# {number} is replaced with the number of the item in the group.
# {total} is replaced with the total number of items in the group.
textList.append(_("{number} of {total}").format(number=indexInGroup, total=similarItemsInGroup))
if level is not None:
# Translators: Displayed in braille when an object (e.g. a tree view item) has a hierarchical level.
# %s is replaced with the level.
textList.append(_("lv %s") % positionInfo["level"])
if rowNumber:
if includeTableCellCoords and not cellCoordsText:
if rowSpan > 1:
# Translators: Displayed in braille for the table cell row numbers when a cell spans multiple rows.
# Occurences of %s are replaced with the corresponding row numbers.
rowStr = _("r{rowNumber}-{rowSpan}").format(
rowNumber=rowNumber,
rowSpan=rowNumber + rowSpan - 1,
)
else:
# Translators: Displayed in braille for a table cell row number.
# %s is replaced with the row number.
rowStr = _("r{rowNumber}").format(rowNumber=rowNumber)
textList.append(rowStr)
if columnNumber:
columnHeaderText = propertyValues.get("columnHeaderText")
if columnHeaderText:
textList.append(columnHeaderText)
if includeTableCellCoords and not cellCoordsText:
if columnSpan > 1:
# Translators: Displayed in braille for the table cell column numbers when a cell spans multiple columns.
# Occurences of %s are replaced with the corresponding column numbers.
columnStr = _("c{columnNumber}-{columnSpan}").format(
columnNumber=columnNumber,
columnSpan=columnNumber + columnSpan - 1,
)
else:
# Translators: Displayed in braille for a table cell column number.
# %s is replaced with the column number.
columnStr = _("c{columnNumber}").format(columnNumber=columnNumber)
textList.append(columnStr)
isCurrent = propertyValues.get("current", controlTypes.IsCurrent.NO)
if isCurrent != controlTypes.IsCurrent.NO:
textList.append(isCurrent.displayString)
placeholder = propertyValues.get("placeholder", None)
if placeholder:
textList.append(placeholder)
if includeTableCellCoords and cellCoordsText:
textList.append(cellCoordsText)
return TEXT_SEPARATOR.join([x for x in textList if x])
class NVDAObjectRegion(Region):
"""A region to provide a braille representation of an NVDAObject.
This region will update based on the current state of the associated NVDAObject.
A cursor routing request will activate the object's default action.
"""
def __init__(self, obj: "NVDAObject", appendText: str = ""):
"""Constructor.
@param obj: The associated NVDAObject.
@param appendText: Text which should always be appended to the NVDAObject text, useful if this region will always precede other regions.
"""
if objectBelowLockScreenAndWindowsIsLocked(obj):
raise RuntimeError("NVDA object is secure and should not be initialized as a braille region")
super().__init__()
self.obj = obj
self.appendText = appendText
def update(self):
obj = self.obj
presConfig = config.conf["presentation"]
role = obj.role
name = obj.name
placeholderValue = obj.placeholder
if placeholderValue and not obj._isTextEmpty:
placeholderValue = None
errorMessage = obj.errorMessage
if errorMessage and State.INVALID_ENTRY not in obj.states:
errorMessage = None
# determine if description should be read
_shouldUseDescription = (
obj.description # is there a description
and obj.description
!= name # the description must not be a duplicate of name, prevent double braille
and (
presConfig["reportObjectDescriptions"] # report description always
or (
# aria description provides more relevant information than other sources of description such as
# a 'title' attribute.
# It should be used for extra details that would be obvious visually.
config.conf["annotations"]["reportAriaDescription"]
and obj.descriptionFrom == controlTypes.DescriptionFrom.ARIA_DESCRIPTION
)
)
)
description = obj.description if _shouldUseDescription else None
detailsRoles = obj.annotations.roles if obj.annotations else None
text = getPropertiesBraille(
name=name,
role=role,
roleText=obj.roleTextBraille,
current=obj.isCurrent,
placeholder=placeholderValue,
hasDetails=bool(obj.annotations),
detailsRoles=detailsRoles,
value=obj.value if not NVDAObjectHasUsefulText(obj) else None,
states=obj.states,
description=description,
keyboardShortcut=obj.keyboardShortcut if presConfig["reportKeyboardShortcuts"] else None,
positionInfo=obj.positionInfo if presConfig["reportObjectPositionInformation"] else None,
cellCoordsText=obj.cellCoordsText
if config.conf["documentFormatting"]["reportTableCellCoords"]
else None,
errorMessage=errorMessage,
)
if role == controlTypes.Role.MATH:
import mathPres
if mathPres.brailleProvider:
try:
text += TEXT_SEPARATOR + mathPres.brailleProvider.getBrailleForMathMl(
obj.mathMl,
)
except (NotImplementedError, LookupError):
pass
self.rawText = text + self.appendText
super(NVDAObjectRegion, self).update()
def routeTo(self, braillePos):
try:
self.obj.doAction()
except NotImplementedError:
pass
class ReviewNVDAObjectRegion(NVDAObjectRegion):
"""A region to provide a braille representation of an NVDAObject when braille is tethered to review.
This region behaves very similar to its base class.
However, when the move system caret when routing review cursor braille setting is active,
pressing a routing key will first focus the object before executing the default action.
"""
def routeTo(self, braillePos: int):
if _routingShouldMoveSystemCaret() and self.obj.isFocusable and not self.obj.hasFocus:
self.obj.setFocus()
super().routeTo(braillePos)
def getControlFieldBraille(
info: textInfos.TextInfo,
field: textInfos.Field,
ancestors: typing.List[textInfos.Field],
reportStart: bool,
formatConfig: config.AggregatedSection,
) -> Optional[str]:
presCat = field.getPresentationCategory(ancestors, formatConfig)
# Cache this for later use.
field._presCat = presCat
role = field.get("role", controlTypes.Role.UNKNOWN)
if reportStart:
# If this is a container, only report it if this is the start of the node.
if presCat == field.PRESCAT_CONTAINER and not field.get("_startOfNode"):
return None
else:
# We only report ends for containers that are not landmarks/regions
# and only if this is the end of the node.
if (
presCat != field.PRESCAT_CONTAINER
or not field.get("_endOfNode")
or role == controlTypes.Role.LANDMARK
):
return None
description = None
_descriptionFrom: controlTypes.DescriptionFrom = field.get("_description-from")
_descriptionIsContent: bool = field.get("descriptionIsContent", False)
if (
not _descriptionIsContent
# Note "reportObjectDescriptions" is not a reason to include description,
# "Object" implies focus/object nav, getControlFieldBraille calculates text for Browse mode.
# There is no way to identify getControlFieldBraille being called for reason focus, as is done in speech.
and (
config.conf["annotations"]["reportAriaDescription"]
and _descriptionFrom == controlTypes.DescriptionFrom.ARIA_DESCRIPTION
)
):
description = field.get("description", None)
states = field.get("states", set())
value = field.get("value", None)
current = field.get("current", controlTypes.IsCurrent.NO)
placeholder = field.get("placeholder", None)
errorMessage = None
if errorMessage and State.INVALID_ENTRY in states:
errorMessage = field.get("errorMessage", None)
hasDetails = field.get("hasDetails", False) and config.conf["annotations"]["reportDetails"]
if config.conf["annotations"]["reportDetails"]:
detailsRoles: Set[Union[None, controlTypes.Role]] = field.get("detailsRoles")
else:
detailsRoles = set()
roleText = field.get("roleTextBraille", field.get("roleText"))
landmark = field.get("landmark")
if not roleText and role == controlTypes.Role.LANDMARK and landmark:
roleText = f"{roleLabels[controlTypes.Role.LANDMARK]} {landmarkLabels[landmark]}"
content = field.get("content")
if presCat == field.PRESCAT_LAYOUT:
return _getControlFieldForLayoutPresentation(
description=description,
current=current,
hasDetails=hasDetails,
detailsRoles=detailsRoles,
role=role,
content=content,
)
elif role in (
controlTypes.Role.TABLECELL,
controlTypes.Role.TABLECOLUMNHEADER,
controlTypes.Role.TABLEROWHEADER,
) and field.get("table-id"):
return _getControlFieldForTableCell(
description=description,
current=current,
hasDetails=hasDetails,
detailsRoles=detailsRoles,
field=field,
formatConfig=formatConfig,
states=states,
)
elif reportStart:
return _getControlFieldForReportStart(
description=description,
current=current,
hasDetails=hasDetails,
detailsRoles=detailsRoles,
field=field,
role=role,
states=states,
content=content,
info=info,
value=value,
roleText=roleText,
placeholder=placeholder,
errorMessage=errorMessage,