forked from nvaccess/nvda
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbraille.py
2293 lines (2124 loc) · 90.9 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
# -*- coding: UTF-8 -*-
#braille.py
#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-2018 NV Access Limited, Joseph Lee, Babbage B.V., Davy Kager, Bram Duvigneau
import sys
import itertools
import os
import pkgutil
import ctypes.wintypes
import threading
import time
import wx
import louis
import winKernel
import keyboardHandler
import baseObject
import config
from logHandler import log
import controlTypes
import api
import textInfos
import brailleDisplayDrivers
import inputCore
import brailleTables
from collections import namedtuple
import re
import scriptHandler
roleLabels = {
# 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 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 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: u"⠤⠤⠤⠤⠤",
# 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
# 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"),
}
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: u"⢎⣿⡱",
# Displayed in braille when an object (e.g. a check box) is checked.
controlTypes.STATE_CHECKED: u"⣏⣿⣹",
# Displayed in braille when an object (e.g. a check box) is half checked.
controlTypes.STATE_HALFCHECKED: u"⣏⣸⣹",
# 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"),
}
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: u"⢎⣀⡱",
# Displayed in braille when an object (e.g. a check box) is not checked.
controlTypes.STATE_CHECKED: u"⣏⣀⣹",
}
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"),
# Strictly speaking, region isn't a landmark, but it is very similar.
# Translators: Displayed in braille for a significant region, normally found on web pages.
"region": pgettext("braille landmark abbreviation", "rgn"),
}
#: 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
#: Unicode braille indicator at the start of untranslated braille input.
INPUT_START_IND = u"⣏"
#: Unicode braille indicator at the end of untranslated braille input.
INPUT_END_IND = u" ⣹"
# 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 = namedtuple("RegionWithPositions",("region","start","end"))
def NVDAObjectHasUsefulText(obj):
import displayModel
if issubclass(obj.TextInfo,displayModel.DisplayModelTextInfo):
# #1711: Flat review (using displayModel) should always be presented on the braille display
return True
else:
# Let the NVDAObject choose if the text should be presented
return obj._hasNavigableText
def _getDisplayDriver(name):
return __import__("brailleDisplayDrivers.%s" % name, globals(), locals(), ("brailleDisplayDrivers",)).BrailleDisplayDriver
def getDisplayList(excludeNegativeChecks=True):
"""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.
@rtype: [(str,unicode)]
"""
displayList = []
# The display that should be placed at the end of the list.
lastDisplay = None
for loader, name, isPkg in pkgutil.iter_modules(brailleDisplayDrivers.__path__):
if name.startswith('_'):
continue
try:
display = _getDisplayDriver(name)
except:
log.error("Error while importing braille display driver %s" % name,
exc_info=True)
continue
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("Braille display driver %s reports as unavailable, excluding" % name)
except:
log.error("", exc_info=True)
displayList.sort(key=lambda d : d[1].lower())
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.
#: @type: int
self.brailleCursorPos = 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
text=unicode(self.rawText).replace('\0','')
braille, self.brailleToRawPos, self.rawToBraillePos, brailleCursorPos = louis.translate(
[os.path.join(brailleTables.TABLES_DIR, config.conf["braille"]["translationTable"]),
"braille-patterns.cti"],
text,
# liblouis mutates typeform if it is a list.
typeform=tuple(self.rawTextTypeforms) if isinstance(self.rawTextTypeforms, list) else self.rawTextTypeforms,
mode=mode, cursorPos=self.cursorPos or 0)
# liblouis gives us back a character string of cells, so convert it to a list of ints.
# For some reason, the highest bit is set, so only grab the lower 8 bits.
self.brailleCells = [ord(cell) & 255 for cell in braille]
# #2466: HACK: liblouis incorrectly truncates trailing spaces from its output in some cases.
# Detect this and add the spaces to the end of the output.
if self.rawText and self.rawText[-1] == " ":
# rawToBraillePos isn't truncated, even though brailleCells is.
# Use this to figure out how long brailleCells should be and thus how many spaces to add.
correctCellsLen = self.rawToBraillePos[-1] + 1
currentCellsLen = len(self.brailleCells)
if correctCellsLen > currentCellsLen:
self.brailleCells.extend((0,) * (correctCellsLen - currentCellsLen))
if self.cursorPos is not None:
# HACK: The cursorPos returned by liblouis is notoriously buggy (#2947 among other issues).
# rawToBraillePos is usually accurate.
try:
brailleCursorPos = self.rawToBraillePos[self.cursorPos]
except IndexError:
pass
else:
brailleCursorPos = None
self.brailleCursorPos = brailleCursorPos
if self.selectionStart is not None and self.selectionEnd is not None:
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 xrange(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
"""
class TextRegion(Region):
"""A simple region containing a string of text.
"""
def __init__(self, text):
super(TextRegion, self).__init__()
self.rawText = text
def getBrailleTextForProperties(**propertyValues):
textList = []
name = propertyValues.get("name")
if name:
textList.append(name)
role = 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")
rowSpan = propertyValues.get("rowSpan")
columnSpan = propertyValues.get("columnSpan")
includeTableCellCoords = propertyValues.get("includeTableCellCoords", True)
if role is not None and not roleText:
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, controlTypes.roleLabels[role])
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:
textList.extend(
controlTypes.processAndLabelStates(role, states, controlTypes.REASON_FOCUS, states, None, positiveStateLabels, negativeStateLabels)
)
if roleText:
textList.append(roleText)
description = propertyValues.get("description")
if description:
textList.append(description)
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)
current = propertyValues.get('current', False)
if current:
try:
textList.append(controlTypes.isCurrentLabels[current])
except KeyError:
log.debugWarning("Aria-current value not handled: %s"%current)
textList.append(controlTypes.isCurrentLabels[True])
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, appendText=""):
"""Constructor.
@param obj: The associated NVDAObject.
@type obj: L{NVDAObjects.NVDAObject}
@param appendText: Text which should always be appended to the NVDAObject text, useful if this region will always precede other regions.
@type appendText: str
"""
super(NVDAObjectRegion, self).__init__()
self.obj = obj
self.appendText = appendText
def update(self):
obj = self.obj
presConfig = config.conf["presentation"]
role = obj.role
placeholderValue = obj.placeholder
if placeholderValue and not obj._isTextEmpty:
placeholderValue = None
text = getBrailleTextForProperties(
name=obj.name,
role=role,
roleText=obj.roleText,
current=obj.isCurrent,
placeholder=placeholderValue,
value=obj.value if not NVDAObjectHasUsefulText(obj) else None ,
states=obj.states,
description=obj.description if presConfig["reportObjectDescriptions"] else None,
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,
)
if role == controlTypes.ROLE_MATH:
import mathPres
mathPres.ensureInit()
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
def getControlFieldBraille(info, field, ancestors, reportStart, formatConfig):
presCat = field.getPresentationCategory(ancestors, formatConfig)
# Cache this for later use.
field._presCat = presCat
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
# and only if this is the end of the node.
if presCat != field.PRESCAT_CONTAINER or not field.get("_endOfNode"):
return None
role = field.get("role", controlTypes.ROLE_UNKNOWN)
states = field.get("states", set())
value=field.get('value',None)
current=field.get('current', None)
placeholder=field.get('placeholder', None)
if presCat == field.PRESCAT_LAYOUT:
text = []
# The only item we report for these fields is clickable, if present.
if controlTypes.STATE_CLICKABLE in states:
text.append(getBrailleTextForProperties(states={controlTypes.STATE_CLICKABLE}))
if current:
text.append(getBrailleTextForProperties(current=current))
return TEXT_SEPARATOR.join(text) if len(text) != 0 else None
elif role in (controlTypes.ROLE_TABLECELL, controlTypes.ROLE_TABLECOLUMNHEADER, controlTypes.ROLE_TABLEROWHEADER) and field.get("table-id"):
# Table cell.
reportTableHeaders = formatConfig["reportTableHeaders"]
reportTableCellCoords = formatConfig["reportTableCellCoords"]
props = {
"states": states,
"rowNumber": field.get("table-rownumber"),
"columnNumber": field.get("table-columnnumber"),
"rowSpan": field.get("table-rowsspanned"),
"columnSpan": field.get("table-columnsspanned"),
"includeTableCellCoords": reportTableCellCoords,
"current": current,
}
if reportTableHeaders:
props["columnHeaderText"] = field.get("table-columnheadertext")
return getBrailleTextForProperties(**props)
elif reportStart:
props = {
# Don't report the role for math here.
# However, we still need to pass it (hence "_role").
"_role" if role == controlTypes.ROLE_MATH else "role": role,
"states": states,"value":value, "current":current, "placeholder":placeholder}
if config.conf["presentation"]["reportKeyboardShortcuts"]:
kbShortcut = field.get("keyboardShortcut")
if kbShortcut:
props["keyboardShortcut"] = kbShortcut
level = field.get("level")
if level:
props["positionInfo"] = {"level": level}
text = getBrailleTextForProperties(**props)
content = field.get("content")
if content:
if text:
text += TEXT_SEPARATOR
text += content
elif role == controlTypes.ROLE_MATH:
import mathPres
mathPres.ensureInit()
if mathPres.brailleProvider:
try:
if text:
text += TEXT_SEPARATOR
text += mathPres.brailleProvider.getBrailleForMathMl(
info.getMathMl(field))
except (NotImplementedError, LookupError):
pass
return text
else:
# Translators: Displayed in braille at the end of a control field such as a list or table.
# %s is replaced with the control's role.
return (_("%s end") %
getBrailleTextForProperties(role=role))
def getFormatFieldBraille(field, fieldCache, isAtStart, formatConfig):
"""Generates the braille text for the given format field.
@param field: The format field to examine.
@type field: {str : str, ...}
@param fieldCache: The format field of the previous run; i.e. the cached format field.
@type fieldCache: {str : str, ...}
@param isAtStart: True if this format field precedes any text in the line/paragraph.
This is useful to restrict display of information which should only appear at the start of the line/paragraph;
e.g. the line number or line prefix (list bullet/number).
@type isAtStart: bool
@param formatConfig: The formatting config.
@type formatConfig: {str : bool, ...}
"""
textList = []
if isAtStart:
if formatConfig["reportLineNumber"]:
lineNumber = field.get("line-number")
if lineNumber:
textList.append("%s" % lineNumber)
linePrefix = field.get("line-prefix")
if linePrefix:
textList.append(linePrefix)
if formatConfig["reportHeadings"]:
headingLevel=field.get('heading-level')
if headingLevel:
# Translators: Displayed in braille for a heading with a level.
# %s is replaced with the level.
textList.append(_("h%s")%headingLevel)
if formatConfig["reportLinks"]:
link=field.get("link")
oldLink=fieldCache.get("link")
if link and link != oldLink:
textList.append(roleLabels[controlTypes.ROLE_LINK])
fieldCache.clear()
fieldCache.update(field)
return TEXT_SEPARATOR.join([x for x in textList if x])
class TextInfoRegion(Region):
pendingCaretUpdate=False #: True if the cursor should be updated for this region on the display
allowPageTurns=True #: True if a page turn should be tried when a TextInfo cannot move anymore and the object supports page turns.
def __init__(self, obj):
super(TextInfoRegion, self).__init__()
self.obj = obj
def _isMultiline(self):
# A region's object can either be an NVDAObject or a tree interceptor.
# Tree interceptors should always be multiline.
from treeInterceptorHandler import TreeInterceptor
if isinstance(self.obj, TreeInterceptor):
return True
# Terminals are inherently multiline, so they don't have the multiline state.
return (self.obj.role == controlTypes.ROLE_TERMINAL or controlTypes.STATE_MULTILINE in self.obj.states)
def _getSelection(self):
"""Retrieve the selection.
If there is no selection, retrieve the collapsed cursor.
@return: The selection.
@rtype: L{textInfos.TextInfo}
"""
try:
return self.obj.makeTextInfo(textInfos.POSITION_SELECTION)
except:
return self.obj.makeTextInfo(textInfos.POSITION_FIRST)
def _setCursor(self, info):
"""Set the cursor.
@param info: The range to which the cursor should be moved.
@type info: L{textInfos.TextInfo}
"""
try:
info.updateCaret()
except NotImplementedError:
log.debugWarning("", exc_info=True)
def _getTypeformFromFormatField(self, field):
typeform = louis.plain_text
if field.get("bold", False):
typeform |= louis.bold
if field.get("italic", False):
typeform |= louis.italic
if field.get("underline", False):
typeform |= louis.underline
return typeform
def _addFieldText(self, text, contentPos, separate=True):
if separate and self.rawText:
# Separate this field text from the rest of the text.
text = TEXT_SEPARATOR + text
self.rawText += text
textLen = len(text)
self.rawTextTypeforms.extend((louis.plain_text,) * textLen)
self._rawToContentPos.extend((contentPos,) * textLen)
def _addTextWithFields(self, info, formatConfig, isSelection=False):
shouldMoveCursorToFirstContent = not isSelection and self.cursorPos is not None
ctrlFields = []
typeform = louis.plain_text
formatFieldAttributesCache = getattr(info.obj, "_brailleFormatFieldAttributesCache", {})
for command in info.getTextWithFields(formatConfig=formatConfig):
if isinstance(command, basestring):
self._isFormatFieldAtStart = False
if not command:
continue
if self._endsWithField:
# The last item added was a field,
# so add a space before the content.
self.rawText += TEXT_SEPARATOR
self.rawTextTypeforms.append(louis.plain_text)
self._rawToContentPos.append(self._currentContentPos)
if isSelection and self.selectionStart is None:
# This is where the content begins.
self.selectionStart = len(self.rawText)
elif shouldMoveCursorToFirstContent:
# This is the first piece of content after the cursor.
# Position the cursor here, as it may currently be positioned on control field text.
self.cursorPos = len(self.rawText)
shouldMoveCursorToFirstContent = False
self.rawText += command
commandLen = len(command)
self.rawTextTypeforms.extend((typeform,) * commandLen)
endPos = self._currentContentPos + commandLen
self._rawToContentPos.extend(xrange(self._currentContentPos, endPos))
self._currentContentPos = endPos
if isSelection:
# The last time this is set will be the end of the content.
self.selectionEnd = len(self.rawText)
self._endsWithField = False
elif isinstance(command, textInfos.FieldCommand):
cmd = command.command
field = command.field
if cmd == "formatChange":
typeform = self._getTypeformFromFormatField(field)
text = getFormatFieldBraille(field, formatFieldAttributesCache, self._isFormatFieldAtStart, formatConfig)
if not text:
continue
# Map this field text to the start of the field's content.
self._addFieldText(text, self._currentContentPos)
elif cmd == "controlStart":
if self._skipFieldsNotAtStartOfNode and not field.get("_startOfNode"):
text = None
else:
text = info.getControlFieldBraille(field, ctrlFields, True, formatConfig)
# Place this field on a stack so we can access it for controlEnd.
ctrlFields.append(field)
if not text:
continue
if getattr(field, "_presCat") == field.PRESCAT_MARKER:
# In this case, the field text is what the user cares about,
# not the actual content.
fieldStart = len(self.rawText)
if fieldStart > 0:
# There'll be a space before the field text.
fieldStart += 1
if isSelection and self.selectionStart is None:
self.selectionStart = fieldStart
elif shouldMoveCursorToFirstContent:
self.cursorPos = fieldStart
shouldMoveCursorToFirstContent = False
# Map this field text to the start of the field's content.
self._addFieldText(text, self._currentContentPos)
elif cmd == "controlEnd":
field = ctrlFields.pop()
text = info.getControlFieldBraille(field, ctrlFields, False, formatConfig)
if not text:
continue
# Map this field text to the end of the field's content.
self._addFieldText(text, self._currentContentPos - 1)
self._endsWithField = True
if isSelection and self.selectionStart is None:
# There is no selection. This is a cursor.
self.cursorPos = len(self.rawText)
if not self._skipFieldsNotAtStartOfNode:
# We only render fields that aren't at the start of their nodes for the first part of the reading unit.
# Otherwise, we'll render fields that have already been rendered.
self._skipFieldsNotAtStartOfNode = True
info.obj._brailleFormatFieldAttributesCache = formatFieldAttributesCache
def _getReadingUnit(self):
return textInfos.UNIT_PARAGRAPH if config.conf["braille"]["readByParagraph"] else textInfos.UNIT_LINE
def update(self):
formatConfig = config.conf["documentFormatting"]
unit = self._getReadingUnit()
self.rawText = ""
self.rawTextTypeforms = []
self.cursorPos = None
# The output includes text representing fields which isn't part of the real content in the control.
# Therefore, maintain a map of positions in the output to positions in the content.
self._rawToContentPos = []
self._currentContentPos = 0
self.selectionStart = self.selectionEnd = None
self._isFormatFieldAtStart = True
self._skipFieldsNotAtStartOfNode = False
self._endsWithField = False
# Selection has priority over cursor.
# HACK: Some TextInfos only support UNIT_LINE properly if they are based on POSITION_CARET,
# and copying the TextInfo breaks this ability.
# So use the original TextInfo for line and a copy for cursor/selection.
self._readingInfo = readingInfo = self._getSelection()
sel = readingInfo.copy()
if not sel.isCollapsed:
# There is a selection.
if self.obj.isTextSelectionAnchoredAtStart:
# The end of the range is exclusive, so make it inclusive first.
readingInfo.move(textInfos.UNIT_CHARACTER, -1, "end")
# Collapse the selection to the unanchored end.
readingInfo.collapse(end=self.obj.isTextSelectionAnchoredAtStart)
# Get the reading unit at the selection.
readingInfo.expand(unit)
# Restrict the selection to the reading unit.
if sel.compareEndPoints(readingInfo, "startToStart") < 0:
sel.setEndPoint(readingInfo, "startToStart")
if sel.compareEndPoints(readingInfo, "endToEnd") > 0:
sel.setEndPoint(readingInfo, "endToEnd")
else:
# There is a cursor.
# Get the reading unit at the cursor.
readingInfo.expand(unit)
# Not all text APIs support offsets, so we can't always get the offset of the selection relative to the start of the reading unit.
# Therefore, grab the reading unit in three parts.
# First, the chunk from the start of the reading unit to the start of the selection.
chunk = readingInfo.copy()
chunk.collapse()
chunk.setEndPoint(sel, "endToStart")
self._addTextWithFields(chunk, formatConfig)
# If the user is entering braille, place any untranslated braille before the selection.
# Import late to avoid circular import.
import brailleInput
text = brailleInput.handler.untranslatedBraille
if text:
rawInputIndStart = len(self.rawText)
# _addFieldText adds text to self.rawText and updates other state accordingly.
self._addFieldText(INPUT_START_IND + text + INPUT_END_IND, None, separate=False)
rawInputIndEnd = len(self.rawText)
else:
rawInputIndStart = None
# Now, the selection itself.
self._addTextWithFields(sel, formatConfig, isSelection=True)
# Finally, get the chunk from the end of the selection to the end of the reading unit.
chunk.setEndPoint(readingInfo, "endToEnd")
chunk.setEndPoint(sel, "startToEnd")
self._addTextWithFields(chunk, formatConfig)
# Strip line ending characters.
self.rawText = self.rawText.rstrip("\r\n\0\v\f")
rawTextLen = len(self.rawText)
if rawTextLen < len(self._rawToContentPos):
# The stripped text is shorter than the original.
self._currentContentPos = self._rawToContentPos[rawTextLen]
del self.rawTextTypeforms[rawTextLen:]
# Trimming _rawToContentPos doesn't matter,
# because we'll only ever ask for indexes valid in rawText.
#del self._rawToContentPos[rawTextLen:]
if rawTextLen == 0 or not self._endsWithField:
# There is no text left after stripping line ending characters,
# or the last item added can be navigated with a cursor.
# Add a space in case the cursor is at the end of the reading unit.
self.rawText += TEXT_SEPARATOR
rawTextLen += 1
self.rawTextTypeforms.append(louis.plain_text)
self._rawToContentPos.append(self._currentContentPos)
if self.cursorPos is not None and self.cursorPos >= rawTextLen:
self.cursorPos = rawTextLen - 1
# The selection end doesn't have to be checked, Region.update() makes sure brailleSelectionEnd is valid.
# If this is not the start of the object, hide all previous regions.
start = readingInfo.obj.makeTextInfo(textInfos.POSITION_FIRST)
self.hidePreviousRegions = (start.compareEndPoints(readingInfo, "startToStart") < 0)
# Don't touch focusToHardLeft if it is already true
# For example, it can be set to True in getFocusContextRegions when this region represents the first new focus ancestor
# Alternatively, BrailleHandler._doNewObject can set this to True when this region represents the focus object and the focus ancestry didn't change
if not self.focusToHardLeft:
# If this is a multiline control, position it at the absolute left of the display when focused.
self.focusToHardLeft = self._isMultiline()
super(TextInfoRegion, self).update()
if rawInputIndStart is not None:
assert rawInputIndEnd is not None, "rawInputIndStart set but rawInputIndEnd isn't"
# These are the start and end of the untranslated input area,
# including the start and end indicators.
self._brailleInputIndStart = self.rawToBraillePos[rawInputIndStart]
self._brailleInputIndEnd = self.rawToBraillePos[rawInputIndEnd]
# These are the start and end of the actual untranslated input, excluding indicators.
self._brailleInputStart = self._brailleInputIndStart + len(INPUT_START_IND)
self._brailleInputEnd = self._brailleInputIndEnd - len(INPUT_END_IND)
self.brailleCursorPos = self._brailleInputStart + brailleInput.handler.untranslatedCursorPos
else:
self._brailleInputIndStart = None
def getTextInfoForBraillePos(self, braillePos):
pos = self._rawToContentPos[self.brailleToRawPos[braillePos]]
# pos is relative to the start of the reading unit.
# Therefore, get the start of the reading unit...
dest = self._readingInfo.copy()
dest.collapse()
# and move pos characters from there.
dest.move(textInfos.UNIT_CHARACTER, pos)
return dest
def routeTo(self, braillePos):
if self._brailleInputIndStart is not None and self._brailleInputIndStart <= braillePos < self._brailleInputIndEnd:
# The user is moving within untranslated braille input.
if braillePos < self._brailleInputStart:
# The user routed to the start indicator. Route to the start of the input.
braillePos = self._brailleInputStart
elif braillePos > self._brailleInputEnd:
# The user routed to the end indicator. Route to the end of the input.
braillePos = self._brailleInputEnd