-
-
Notifications
You must be signed in to change notification settings - Fork 650
/
__init__.py
2780 lines (2539 loc) · 99.8 KB
/
__init__.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
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) 2009-2023 NV Access Limited, Joseph Lee, Mohammad Suliman, Babbage B.V., Leonard de Ruijter,
# Bill Dengler, Cyrille Bougot
"""Support for UI Automation (UIA) controls."""
from __future__ import annotations
import typing
from typing import (
Generator,
List,
Optional,
Dict,
Tuple,
Callable,
)
import array
from ctypes.wintypes import POINT
from comtypes import COMError
import time
import numbers
import colors
import languageHandler
import NVDAState
import UIAHandler
import UIAHandler.customProps
import UIAHandler.customAnnotations
import controlTypes
from controlTypes import TextPosition, TextAlign
import config
import speech
import api
import textInfos
from logHandler import log
from UIAHandler.types import (
IUIAutomationTextRangeT,
)
from UIAHandler.utils import (
BulkUIATextRangeAttributeValueFetcher,
UIATextRangeAttributeValueFetcher,
getChildrenWithCacheFromUIATextRange,
getEnclosingElementWithCacheFromUIATextRange,
iterUIARangeByUnit,
UIAMixedAttributeError,
UIATextRangeFromElement,
_shouldUseWindowsTerminalNotifications,
)
from NVDAObjects.window import Window
from NVDAObjects import (
NVDAObject,
NVDAObjectTextInfo,
InvalidNVDAObject,
)
from NVDAObjects.behaviors import (
ProgressBar,
EditableTextBase,
EditableTextWithoutAutoSelectDetection,
EditableTextWithAutoSelectDetection,
Dialog,
Notification,
EditableTextWithSuggestions,
ToolTip,
)
import braille
import locationHelper
import ui
import winVersion
import NVDAObjects
paragraphIndentIDs = {
UIAHandler.UIA_IndentationFirstLineAttributeId,
UIAHandler.UIA_IndentationLeadingAttributeId,
UIAHandler.UIA_IndentationTrailingAttributeId,
}
textAlignLabels = {
UIAHandler.HorizontalTextAlignment_Left: TextAlign.LEFT,
UIAHandler.HorizontalTextAlignment_Centered: TextAlign.CENTER,
UIAHandler.HorizontalTextAlignment_Right: TextAlign.RIGHT,
UIAHandler.HorizontalTextAlignment_Justified: TextAlign.JUSTIFY,
}
class UIATextInfo(textInfos.TextInfo):
_rangeObj: IUIAutomationTextRangeT
_cache_controlFieldNVDAObjectClass = True
def _get_controlFieldNVDAObjectClass(self):
"""
The NVDAObject class to be used by the _getTextWithFieldsForUIARange method when instantiating NVDAObjects in order to generate control fields for content.
L{UIA} is usually what you want, but if you know the class will always mutate to a certain subclass (E.g. WordDocumentNode) then performance gains can be made by returning the subclass here.
"""
return UIA
# UIA property IDs that should be automatically cached for control fields
_controlFieldUIACachedPropertyIDs = {
UIAHandler.UIA_IsValuePatternAvailablePropertyId,
UIAHandler.UIA_HasKeyboardFocusPropertyId,
UIAHandler.UIA_NamePropertyId,
UIAHandler.UIA_ToggleToggleStatePropertyId,
UIAHandler.UIA_HelpTextPropertyId,
UIAHandler.UIA.UIA_FullDescriptionPropertyId,
UIAHandler.UIA_AccessKeyPropertyId,
UIAHandler.UIA_AcceleratorKeyPropertyId,
UIAHandler.UIA_HasKeyboardFocusPropertyId,
UIAHandler.UIA_SelectionItemIsSelectedPropertyId,
UIAHandler.UIA_IsDataValidForFormPropertyId,
UIAHandler.UIA_IsRequiredForFormPropertyId,
UIAHandler.UIA_ValueIsReadOnlyPropertyId,
UIAHandler.UIA_ExpandCollapseExpandCollapseStatePropertyId,
UIAHandler.UIA_ToggleToggleStatePropertyId,
UIAHandler.UIA_IsKeyboardFocusablePropertyId,
UIAHandler.UIA_IsPasswordPropertyId,
UIAHandler.UIA_IsSelectionItemPatternAvailablePropertyId,
UIAHandler.UIA_GridItemRowPropertyId,
UIAHandler.UIA_TableItemRowHeaderItemsPropertyId,
UIAHandler.UIA_GridItemColumnPropertyId,
UIAHandler.UIA_TableItemColumnHeaderItemsPropertyId,
UIAHandler.UIA_GridRowCountPropertyId,
UIAHandler.UIA_GridColumnCountPropertyId,
UIAHandler.UIA_GridItemContainingGridPropertyId,
UIAHandler.UIA_RangeValueValuePropertyId,
UIAHandler.UIA_ValueValuePropertyId,
UIAHandler.UIA_PositionInSetPropertyId,
UIAHandler.UIA_SizeOfSetPropertyId,
UIAHandler.UIA_AriaRolePropertyId,
UIAHandler.UIA_LandmarkTypePropertyId,
UIAHandler.UIA_AriaPropertiesPropertyId,
UIAHandler.UIA_LevelPropertyId,
UIAHandler.UIA_IsEnabledPropertyId,
}
def _get__controlFieldUIACacheRequest(self):
"""The UIA cacheRequest object that will be used when fetching all UIA elements needed when generating control fields for this TextInfo's content."""
cacheRequest = UIAHandler.handler.baseCacheRequest.clone()
for ID in self._controlFieldUIACachedPropertyIDs:
try:
cacheRequest.addProperty(ID)
except COMError:
pass
UIATextInfo._controlFieldUIACacheRequest = self._controlFieldUIACacheRequest = cacheRequest
return cacheRequest
#: The UI Automation text units (in order of resolution) that should be used when fetching formatting.
UIAFormatUnits = [
UIAHandler.TextUnit_Format,
UIAHandler.TextUnit_Word,
UIAHandler.TextUnit_Character,
]
def find(self, text, caseSensitive=False, reverse=False):
tempRange = self._rangeObj.clone()
documentRange = self.obj.UIATextPattern.documentRange
if reverse:
tempRange.MoveEndpointByRange(
UIAHandler.TextPatternRangeEndpoint_Start,
documentRange,
UIAHandler.TextPatternRangeEndpoint_Start,
)
else:
if tempRange.move(UIAHandler.TextUnit_Character, 1) == 0:
return False
tempRange.MoveEndpointByRange(
UIAHandler.TextPatternRangeEndpoint_End,
documentRange,
UIAHandler.TextPatternRangeEndpoint_End,
)
try:
r = tempRange.findText(text, reverse, not caseSensitive)
except COMError:
r = None
if r:
r.MoveEndpointByRange(
UIAHandler.TextPatternRangeEndpoint_End,
r,
UIAHandler.TextPatternRangeEndpoint_Start,
)
self._rangeObj = r
return True
return False
def _getFormatFieldFontName(self, fetch: Callable[[int], int], formatField: textInfos.FormatField):
val = fetch(UIAHandler.UIA_FontNameAttributeId)
if val != UIAHandler.handler.reservedNotSupportedValue:
formatField["font-name"] = val
def _getFormatFieldFontSize(self, fetch: Callable[[int], int], formatField: textInfos.FormatField):
val = fetch(UIAHandler.UIA_FontSizeAttributeId)
if isinstance(val, numbers.Number):
# Translators: Abbreviation for points, a measurement of font size.
formatField["font-size"] = pgettext("font size", "%s pt") % float(val)
def _getFormatFieldFontAttributes(self, fetch: Callable[[int], int], formatField: textInfos.FormatField):
val = fetch(UIAHandler.UIA_FontWeightAttributeId)
if isinstance(val, int):
formatField["bold"] = val >= 700
val = fetch(UIAHandler.UIA_IsItalicAttributeId)
if val != UIAHandler.handler.reservedNotSupportedValue:
formatField["italic"] = val
val = fetch(UIAHandler.UIA_UnderlineStyleAttributeId)
if val != UIAHandler.handler.reservedNotSupportedValue:
formatField["underline"] = bool(val)
val = fetch(UIAHandler.UIA_StrikethroughStyleAttributeId)
if val != UIAHandler.handler.reservedNotSupportedValue:
formatField["strikethrough"] = bool(val)
def _getFormatFieldSuperscriptsAndSubscripts(
self,
fetch: Callable[[int], int],
formatField: textInfos.FormatField,
):
textPosition = None
val = fetch(UIAHandler.UIA_IsSuperscriptAttributeId)
if val != UIAHandler.handler.reservedNotSupportedValue and val:
textPosition = TextPosition.SUPERSCRIPT
else:
val = fetch(UIAHandler.UIA_IsSubscriptAttributeId)
if val != UIAHandler.handler.reservedNotSupportedValue and val:
textPosition = TextPosition.SUBSCRIPT
else:
textPosition = TextPosition.BASELINE
formatField["text-position"] = textPosition
def _getFormatFieldStyle(self, fetch: Callable[[int], int], formatField: textInfos.FormatField):
val = fetch(UIAHandler.UIA_StyleNameAttributeId)
if val != UIAHandler.handler.reservedNotSupportedValue:
formatField["style"] = val
def _getFormatFieldIndent(self, fetch: Callable[[int], int], formatField: textInfos.FormatField):
"""
Helper function to get indent formatting from UIA, using the fetch function passed as parameter.
The indent formatting is reported according to MS Word's convention.
@param fetch: gets formatting information from UIA.
@return: The indent formatting informations corresponding to what has been retrieved via the fetcher.
"""
val = fetch(UIAHandler.UIA_IndentationFirstLineAttributeId)
uiaIndentFirstLine = val if isinstance(val, float) else None
val = fetch(UIAHandler.UIA_IndentationLeadingAttributeId)
uiaIndentLeading = val if isinstance(val, float) else None
val = fetch(UIAHandler.UIA_IndentationTrailingAttributeId)
uiaIndentTrailing = val if isinstance(val, float) else None
if uiaIndentFirstLine is not None and uiaIndentLeading is not None:
reportedFirstLineIndent = uiaIndentFirstLine - uiaIndentLeading
if reportedFirstLineIndent > 0: # First line positive indent
reportedLeftIndent = uiaIndentLeading
reportedHangingIndent = None
elif reportedFirstLineIndent < 0: # First line negative indent
reportedLeftIndent = uiaIndentFirstLine
reportedHangingIndent = -reportedFirstLineIndent
reportedFirstLineIndent = None
else:
reportedLeftIndent = uiaIndentLeading
reportedFirstLineIndent = None
reportedHangingIndent = None
if reportedLeftIndent:
formatField["left-indent"] = self._getIndentValueDisplayString(reportedLeftIndent)
if reportedFirstLineIndent:
formatField["first-line-indent"] = self._getIndentValueDisplayString(reportedFirstLineIndent)
if reportedHangingIndent:
formatField["hanging-indent"] = self._getIndentValueDisplayString(reportedHangingIndent)
if uiaIndentTrailing:
formatField["right-indent"] = self._getIndentValueDisplayString(uiaIndentTrailing)
def _getFormatFieldAlignment(self, fetch: Callable[[int], int], formatField: textInfos.FormatField):
val = fetch(UIAHandler.UIA_HorizontalTextAlignmentAttributeId)
textAlign = textAlignLabels.get(val)
if textAlign:
formatField["text-align"] = textAlign
def _getFormatFieldColor(self, fetch: Callable[[int], int], formatField: textInfos.FormatField):
val = fetch(UIAHandler.UIA_BackgroundColorAttributeId)
if isinstance(val, int):
formatField["background-color"] = colors.RGB.fromCOLORREF(val)
val = fetch(UIAHandler.UIA_ForegroundColorAttributeId)
if isinstance(val, int):
formatField["color"] = colors.RGB.fromCOLORREF(val)
def _getFormatFieldLineSpacing(self, fetch: Callable[[int], int], formatField: textInfos.FormatField):
val = fetch(UIAHandler.UIA_LineSpacingAttributeId)
if val != UIAHandler.handler.reservedNotSupportedValue:
if val:
formatField["line-spacing"] = val
def _getFormatFieldLinks(self, fetch: Callable[[int], int], formatField: textInfos.FormatField):
val = fetch(UIAHandler.UIA_LinkAttributeId)
if val != UIAHandler.handler.reservedNotSupportedValue:
if val:
formatField["link"] = True
def _getFormatFieldHeadings(self, fetch: Callable[[int], int], formatField: textInfos.FormatField):
styleIDValue = fetch(UIAHandler.UIA_StyleIdAttributeId)
# #9842: styleIDValue can sometimes be a pointer to IUnknown.
# In Python 3, comparing an int with a pointer raises a TypeError.
if (
isinstance(styleIDValue, int)
and UIAHandler.StyleId_Heading1 <= styleIDValue <= UIAHandler.StyleId_Heading9
):
formatField["heading-level"] = (styleIDValue - UIAHandler.StyleId_Heading1) + 1
def _getFormatFieldAnnotationTypes(
self,
fetch: Callable[[int], int],
formatField: textInfos.FormatField,
formatConfig: Dict,
):
annotationTypes = fetch(UIAHandler.UIA_AnnotationTypesAttributeId)
# Some UIA implementations return a single value rather than a tuple.
# Always mutate to a tuple to allow for a generic x in y matching
if not isinstance(annotationTypes, tuple):
annotationTypes = (annotationTypes,)
if formatConfig["reportSpellingErrors"]:
if UIAHandler.AnnotationType_SpellingError in annotationTypes:
formatField["invalid-spelling"] = True
if UIAHandler.AnnotationType_GrammarError in annotationTypes:
formatField["invalid-grammar"] = True
if formatConfig["reportComments"]:
cats = self.obj._UIACustomAnnotationTypes
if cats.microsoftWord_draftComment.id and cats.microsoftWord_draftComment.id in annotationTypes:
formatField["comment"] = textInfos.CommentType.DRAFT
elif (
cats.microsoftWord_resolvedComment.id
and cats.microsoftWord_resolvedComment.id in annotationTypes
):
formatField["comment"] = textInfos.CommentType.RESOLVED
elif UIAHandler.AnnotationType_Comment in annotationTypes:
formatField["comment"] = True
if formatConfig["reportRevisions"]:
if UIAHandler.AnnotationType_InsertionChange in annotationTypes:
formatField["revision-insertion"] = True
elif UIAHandler.AnnotationType_DeletionChange in annotationTypes:
formatField["revision-deletion"] = True
if formatConfig["reportBookmarks"]:
cats = self.obj._UIACustomAnnotationTypes
if cats.microsoftWord_bookmark.id and cats.microsoftWord_bookmark.id in annotationTypes:
formatField["bookmark"] = True
def _getFormatFieldCulture(self, fetch: Callable[[int], int], formatField: textInfos.FormatField):
cultureVal = fetch(UIAHandler.UIA_CultureAttributeId)
if cultureVal and isinstance(cultureVal, int):
try:
formatField["language"] = languageHandler.windowsLCIDToLocaleName(cultureVal)
except: # noqa: E722
log.debugWarning("language error", exc_info=True)
pass
def _getFormatFieldAtRange( # noqa: C901
self,
textRange: IUIAutomationTextRangeT,
formatConfig: Dict,
ignoreMixedValues: bool = False,
) -> textInfos.FormatField:
"""
Fetches formatting for the given UI Automation Text range.
@param textRange: the text range whos formatting should be fetched.
@param formatConfig: the types of formatting requested.
@type formatConfig: a dictionary of NVDA document formatting configuration keys
with values set to true for those types that should be fetched.
@param ignoreMixedValues: If True, formatting that is mixed according to UI Automation will not be included.
If False, L{UIAHandler.utils.MixedAttributeError} will be raised if UI Automation gives back
a mixed attribute value signifying that the caller may want to try again with a smaller range.
@return: The formatting for the given text range.
"""
if not isinstance(textRange, UIAHandler.IUIAutomationTextRange):
raise ValueError("%s is not a text range" % textRange)
fetchAnnotationTypes = (
formatConfig["reportSpellingErrors"]
or formatConfig["reportComments"]
or formatConfig["reportRevisions"]
or formatConfig["reportBookmarks"]
)
try:
textRange = textRange.QueryInterface(UIAHandler.IUIAutomationTextRange3)
except (COMError, AttributeError):
fetcher = UIATextRangeAttributeValueFetcher(textRange)
else:
# Precalculate all the IDs we could possibly need so that they can be fetched in one cross-process call where supported
IDs = set()
if formatConfig["reportFontName"]:
IDs.add(UIAHandler.UIA_FontNameAttributeId)
if formatConfig["reportFontSize"]:
IDs.add(UIAHandler.UIA_FontSizeAttributeId)
if formatConfig["fontAttributeReporting"]:
IDs.add(UIAHandler.UIA_FontWeightAttributeId)
IDs.add(UIAHandler.UIA_IsItalicAttributeId)
IDs.add(UIAHandler.UIA_UnderlineStyleAttributeId)
IDs.add(UIAHandler.UIA_StrikethroughStyleAttributeId)
if formatConfig["reportSuperscriptsAndSubscripts"]:
IDs.add(UIAHandler.UIA_IsSuperscriptAttributeId)
IDs.add(UIAHandler.UIA_IsSubscriptAttributeId)
if formatConfig["reportParagraphIndentation"]:
IDs.update(set(paragraphIndentIDs))
if formatConfig["reportAlignment"]:
IDs.add(UIAHandler.UIA_HorizontalTextAlignmentAttributeId)
if formatConfig["reportColor"]:
IDs.add(UIAHandler.UIA_BackgroundColorAttributeId)
IDs.add(UIAHandler.UIA_ForegroundColorAttributeId)
if formatConfig["reportLineSpacing"]:
IDs.add(UIAHandler.UIA_LineSpacingAttributeId)
if formatConfig["reportLinks"]:
IDs.add(UIAHandler.UIA_LinkAttributeId)
if formatConfig["reportStyle"]:
IDs.add(UIAHandler.UIA_StyleNameAttributeId)
if formatConfig["reportHeadings"]:
IDs.add(UIAHandler.UIA_StyleIdAttributeId)
if fetchAnnotationTypes:
IDs.add(UIAHandler.UIA_AnnotationTypesAttributeId)
IDs.add(UIAHandler.UIA_CultureAttributeId)
fetcher = BulkUIATextRangeAttributeValueFetcher(textRange, IDs)
def fetch(id):
return fetcher.getValue(id, ignoreMixedValues=ignoreMixedValues)
formatField = textInfos.FormatField()
if formatConfig["reportFontName"]:
self._getFormatFieldFontName(fetch, formatField)
if formatConfig["reportFontSize"]:
self._getFormatFieldFontSize(fetch, formatField)
if formatConfig["fontAttributeReporting"]:
self._getFormatFieldFontAttributes(fetch, formatField)
if formatConfig["reportSuperscriptsAndSubscripts"]:
self._getFormatFieldSuperscriptsAndSubscripts(fetch, formatField)
if formatConfig["reportStyle"]:
self._getFormatFieldStyle(fetch, formatField)
if formatConfig["reportParagraphIndentation"]:
self._getFormatFieldIndent(fetch, formatField)
if formatConfig["reportAlignment"]:
self._getFormatFieldAlignment(fetch, formatField)
if formatConfig["reportColor"]:
self._getFormatFieldColor(fetch, formatField)
if formatConfig["reportLineSpacing"]:
self._getFormatFieldLineSpacing(fetch, formatField)
if formatConfig["reportLinks"]:
self._getFormatFieldLinks(fetch, formatField)
if formatConfig["reportHeadings"]:
self._getFormatFieldHeadings(fetch, formatField)
if fetchAnnotationTypes:
self._getFormatFieldAnnotationTypes(fetch, formatField, formatConfig)
self._getFormatFieldCulture(fetch, formatField)
return textInfos.FieldCommand("formatChange", formatField)
def _getIndentValueDisplayString(self, val: float) -> str:
"""A function returning the string to display in formatting info.
@param val: an indent value measured in points, fetched via
an UIAHandler.UIA_Indentation*AttributeId attribute.
@return: The string used in formatting information to report the length of an indentation.
"""
# convert points to inches (1pt = 1/72 in)
val /= 72.0
if languageHandler.useImperialMeasurements():
# Translators: a measurement in inches
valText = _("{val:.2f} in").format(val=val)
else:
# Convert from inches to centimetres
val *= 2.54
# Translators: a measurement in centimetres
valText = _("{val:.2f} cm").format(val=val)
return valText
# C901 '__init__' is too complex
# Note: when working on getPropertiesBraille, look for opportunities to simplify
# and move logic out into smaller helper functions.
def __init__( # noqa: C901
self,
obj: NVDAObject,
position: str,
_rangeObj: Optional[IUIAutomationTextRangeT] = None,
):
super(UIATextInfo, self).__init__(obj, position)
if _rangeObj:
try:
self._rangeObj = _rangeObj.clone()
except COMError:
# IUIAutomationTextRange::clone can sometimes fail, such as in UWP account login screens
log.debugWarning("Could not clone range", exc_info=True)
raise RuntimeError("Could not clone range")
elif position in (textInfos.POSITION_CARET, textInfos.POSITION_SELECTION):
try:
sel = self.obj.UIATextPattern.GetSelection()
except COMError:
raise RuntimeError("No selection available")
if sel.length > 0:
self._rangeObj: IUIAutomationTextRangeT = sel.getElement(0).clone()
else:
raise NotImplementedError("UIAutomationTextRangeArray is empty")
if position == textInfos.POSITION_CARET:
self.collapse()
elif isinstance(position, UIATextInfo): # bookmark
self._rangeObj = position._rangeObj
elif position == textInfos.POSITION_FIRST:
try:
self._rangeObj: IUIAutomationTextRangeT = self.obj.UIATextPattern.documentRange
except COMError:
# Error: first position not supported by the UIA text pattern.
raise RuntimeError
self.collapse()
elif position == textInfos.POSITION_LAST:
self._rangeObj: IUIAutomationTextRangeT = self.obj.UIATextPattern.documentRange
self.collapse(True)
elif position == textInfos.POSITION_ALL or position == self.obj:
self._rangeObj: IUIAutomationTextRangeT = self.obj.UIATextPattern.documentRange
elif isinstance(position, UIA) or isinstance(position, UIAHandler.IUIAutomationElement):
if isinstance(position, UIA):
position = position.UIAElement
try:
self._rangeObj: Optional[IUIAutomationTextRangeT] = self.obj.UIATextPattern.rangeFromChild(
position,
)
except COMError:
raise LookupError
# sometimes rangeFromChild can return a NULL range
if not self._rangeObj:
raise LookupError
elif isinstance(position, locationHelper.Point):
self._rangeObj: IUIAutomationTextRangeT = self.obj.UIATextPattern.RangeFromPoint(
position.toPOINT(),
)
elif isinstance(position, UIAHandler.IUIAutomationTextRange):
position = typing.cast(IUIAutomationTextRangeT, position)
self._rangeObj = position.clone()
else:
raise ValueError("Unknown position %s" % position)
def __eq__(self, other: "UIATextInfo"):
if self is other:
return True
if self.__class__ is not other.__class__:
return False
return bool(self._rangeObj.compare(other._rangeObj))
# As __eq__ was defined on this class, we must provide __hash__ to remain hashable.
# The default hash implementation is fine for our purposes.
def __hash__(self):
return super().__hash__()
def _get_NVDAObjectAtStart(self):
e = self.UIAElementAtStart
if e:
return UIA(UIAElement=e) or self.obj
return self.obj
def _get_UIAElementAtStart(self):
"""
Fetches the deepest UIA element at the start of the text range.
This may be via UIA's getChildren (in the case of embedded controls), or GetEnClosingElement.
"""
tempInfo = self.copy()
tempInfo.collapse()
# some implementations (Edge, Word) do not correctly class embedded objects (graphics, checkboxes) as being the enclosing element, even when the range is completely within them. Rather, they still list the object in getChildren.
# Thus we must check getChildren before getEnclosingElement.
tempInfo.expand(textInfos.UNIT_CHARACTER)
tempRange = tempInfo._rangeObj
try:
children = getChildrenWithCacheFromUIATextRange(tempRange, UIAHandler.handler.baseCacheRequest)
except COMError as e:
log.debugWarning("Could not get children from UIA text range, %s" % e)
children = None
if children and children.length == 1:
child = children.getElement(0)
else:
child = getEnclosingElementWithCacheFromUIATextRange(
tempRange,
UIAHandler.handler.baseCacheRequest,
)
return child
def _get_bookmark(self):
return self.copy()
UIAControlTypesWhereNameIsContent = {
UIAHandler.UIA_ButtonControlTypeId,
UIAHandler.UIA_HyperlinkControlTypeId,
UIAHandler.UIA_ImageControlTypeId,
UIAHandler.UIA_MenuItemControlTypeId,
UIAHandler.UIA_TabItemControlTypeId,
UIAHandler.UIA_TextControlTypeId,
UIAHandler.UIA_SplitButtonControlTypeId,
}
def _getControlFieldForUIAObject(
self,
obj: "UIA",
isEmbedded=False,
startOfNode=False,
endOfNode=False,
) -> textInfos.ControlField:
"""
Fetch control field information for the given UIA NVDAObject.
@param obj: the NVDAObject the control field is for.
@param isEmbedded: True if this NVDAObject is for a leaf node (has no useful children).
@param startOfNode: True if the control field represents the very start of this object.
@param endOfNode: True if the control field represents the very end of this object.
@return: The control field for this object
"""
role = obj.role
field = textInfos.ControlField()
# Ensure this controlField is unique to the object
runtimeID = field["runtimeID"] = obj.UIAElement.getRuntimeId()
field["_startOfNode"] = startOfNode
field["_endOfNode"] = endOfNode
field["role"] = obj.role
states = obj.states
# The user doesn't care about certain states, as they are obvious.
states.discard(controlTypes.State.EDITABLE)
states.discard(controlTypes.State.MULTILINE)
states.discard(controlTypes.State.FOCUSED)
field["states"] = states
field["nameIsContent"] = nameIsContent = (
obj.UIAElement.cachedControlType in self.UIAControlTypesWhereNameIsContent
)
if not nameIsContent:
field["name"] = obj.name
field["description"] = obj.description
field["level"] = obj.positionInfo.get("level")
if role == controlTypes.Role.TABLE:
field["table-id"] = runtimeID
try:
field["table-rowcount"] = obj.rowCount
field["table-columncount"] = obj.columnCount
except NotImplementedError:
pass
if role in (
controlTypes.Role.TABLECELL,
controlTypes.Role.DATAITEM,
controlTypes.Role.TABLECOLUMNHEADER,
controlTypes.Role.TABLEROWHEADER,
controlTypes.Role.HEADERITEM,
):
try:
field["table-rownumber"] = obj.rowNumber
field["table-rowsspanned"] = obj.rowSpan
field["table-columnnumber"] = obj.columnNumber
field["table-columnsspanned"] = obj.columnSpan
field["table-id"] = obj.table.UIAElement.getRuntimeId()
field["role"] = controlTypes.Role.TABLECELL
field["table-columnheadertext"] = obj.columnHeaderText
field["table-rowheadertext"] = obj.rowHeaderText
except NotImplementedError:
pass
return field
def _getTextFromUIARange(self, textRange: IUIAutomationTextRangeT) -> str:
"""
Fetches plain text from the given UI Automation text range.
Just calls getText(-1). This only exists to be overridden for filtering.
"""
return textRange.getText(-1)
def _getTextWithFields_text(
self,
textRange: IUIAutomationTextRangeT,
formatConfig: Dict,
UIAFormatUnits: Optional[List[int]] = None,
) -> Generator[textInfos.FieldCommand, None, None]:
"""
Yields format fields and text for the given UI Automation text range, split up by the first available UI Automation text unit that does not result in mixed attribute values.
@param textRange: the UI Automation text range to walk.
@param formatConfig: a dictionary of NVDA document formatting configuration keys
with values set to true for those types that should be fetched.
@param UIAFormatUnits: the UI Automation text units (in order of resolution) that should be used to split the text so as to avoid mixed attribute values. This is None by default.
If the parameter is a list of 1 or more units, The range will be split by the first unit in the list, and this method will be recursively run on each subrange, with the remaining units in this list given as the value of this parameter.
If this parameter is an empty list, then formatting and text is fetched for the entire range, but any mixed attribute values are ignored and no splitting occures.
If this parameter is None, text and formatting is fetched for the entire range in one go, but if mixed attribute values are found, it will split by the first unit in self.UIAFormatUnits, and run this method recursively on each subrange, providing the remaining units from self.UIAFormatUnits as the value of this parameter.
"""
debug = UIAHandler._isDebug() and log.isEnabledFor(log.DEBUG)
if debug:
log.debug("_getTextWithFields_text start")
if UIAFormatUnits:
unit = UIAFormatUnits[0]
furtherUIAFormatUnits = UIAFormatUnits[1:]
else:
# Fetching text and formatting from the entire range will be tried once before any possible splitting.
unit = None
furtherUIAFormatUnits = self.UIAFormatUnits if UIAFormatUnits is None else []
if debug:
log.debug(
f"Walking by unit {unit}, " f"with further units of: {furtherUIAFormatUnits}",
)
rangeIter = iterUIARangeByUnit(textRange, unit) if unit is not None else [textRange]
for tempRange in rangeIter:
text = self._getTextFromUIARange(tempRange) or ""
if text is not None:
if debug:
log.debug("Chunk has text. Fetching formatting")
try:
field = self._getFormatFieldAtRange(
tempRange,
formatConfig,
ignoreMixedValues=len(furtherUIAFormatUnits) == 0,
)
except UIAMixedAttributeError:
if debug:
log.debug("Mixed formatting. Trying higher resolution unit")
for subfield in self._getTextWithFields_text(
tempRange,
formatConfig,
UIAFormatUnits=furtherUIAFormatUnits,
):
yield subfield
if debug:
log.debug("Done yielding higher resolution unit")
continue
if debug:
log.debug("Yielding formatting and text")
log.debug(f"field: {field}, text: {text}")
if field:
yield field
yield text
if debug:
log.debug("Done _getTextWithFields_text")
# C901 '_getTextWithFieldsForUIARange' is too complex
# Note: when working on getPropertiesBraille, look for opportunities to simplify
# and move logic out into smaller helper functions.
def _getTextWithFieldsForUIARange( # noqa: C901
self,
rootElement: UIAHandler.IUIAutomationElement,
textRange: IUIAutomationTextRangeT,
formatConfig: Dict,
includeRoot: bool = False,
alwaysWalkAncestors: bool = True,
recurseChildren: bool = True,
_rootElementClipped: Tuple[bool, bool] = (True, True),
) -> Generator[textInfos.TextInfo.TextOrFieldsT, None, None]:
"""
Yields start and end control fields, and text, for the given UI Automation text range.
@param rootElement: the highest ancestor that encloses the given text range. This function will not walk higher than this point.
@param textRange: the UI Automation text range whos content should be fetched.
@param formatConfig: the types of formatting requested.
@type formatConfig: a dictionary of NVDA document formatting configuration keys
with values set to true for those types that should be fetched.
@param includeRoot: If true, then a control start and end will be yielded for the root element.
@param alwaysWalkAncestors: If true then control fields will be yielded for any element enclosing the given text range, that is a descendant of the root element. If false then the root element may be assumed to be the only ancestor.
@param recurseChildren: If true, this function will be recursively called for each child of the given text range, clipped to the bounds of this text range. Formatted text between the children will also be yielded. If false, only formatted text will be yielded.
@param _rootElementClipped: Indicates if textRange represents all of the given rootElement,
or is clipped at the start or end.
"""
debug = UIAHandler._isDebug() and log.isEnabledFor(log.DEBUG)
if debug:
log.debug("_getTextWithFieldsForUIARange")
log.debug("rootElement: %s" % rootElement.currentLocalizedControlType if rootElement else None)
log.debug("full text: %s" % textRange.getText(-1))
if recurseChildren:
childElements = getChildrenWithCacheFromUIATextRange(textRange, self._controlFieldUIACacheRequest)
# Specific check for embedded elements (checkboxes etc)
# Calling getChildren on their childRange always gives back the same child.
if childElements.length == 1:
childElement = childElements.getElement(0)
if childElement and UIAHandler.handler.clientObject.compareElements(
childElement,
rootElement,
):
log.debug("Detected embedded child")
recurseChildren = False
parentElements = []
if alwaysWalkAncestors:
if debug:
log.debug("Fetching parents starting from enclosingElement")
try:
parentElement = getEnclosingElementWithCacheFromUIATextRange(
textRange,
self._controlFieldUIACacheRequest,
)
except COMError:
parentElement = None
while parentElement:
isRoot = UIAHandler.handler.clientObject.compareElements(parentElement, rootElement)
if isRoot:
if debug:
log.debug("Hit root")
parentElements.append((parentElement, _rootElementClipped))
break
else:
if debug:
log.debug("parentElement: %s" % parentElement.currentLocalizedControlType)
try:
parentRange = self.obj.UIATextPattern.rangeFromChild(parentElement)
except COMError:
parentRange = None
if not parentRange:
if debug:
log.debug("parentRange is NULL. Breaking")
break
clippedStart = (
textRange.CompareEndpoints(
UIAHandler.TextPatternRangeEndpoint_Start,
parentRange,
UIAHandler.TextPatternRangeEndpoint_Start,
)
> 0
)
clippedEnd = (
textRange.CompareEndpoints(
UIAHandler.TextPatternRangeEndpoint_End,
parentRange,
UIAHandler.TextPatternRangeEndpoint_End,
)
< 0
)
parentElements.append((parentElement, (clippedStart, clippedEnd)))
parentElement = UIAHandler.handler.baseTreeWalker.getParentElementBuildCache(
parentElement,
self._controlFieldUIACacheRequest,
)
else:
parentElements.append((rootElement, _rootElementClipped))
if debug:
log.debug("Done fetching parents")
enclosingElement = parentElements[0][0] if parentElements else rootElement
if not includeRoot and parentElements:
del parentElements[-1]
parentFields = []
if debug:
log.debug("Generating controlFields for parents")
windowHandle = self.obj.windowHandle
controlFieldNVDAObjectClass = self.controlFieldNVDAObjectClass
for index, (parentElement, parentClipped) in enumerate(parentElements):
if debug:
log.debug("parentElement: %s" % parentElement.currentLocalizedControlType)
startOfNode = not parentClipped[0]
endOfNode = not parentClipped[1]
try:
obj = controlFieldNVDAObjectClass(
windowHandle=windowHandle,
UIAElement=parentElement,
initialUIACachedPropertyIDs=self._controlFieldUIACachedPropertyIDs,
)
objIsEmbedded = index == 0 and not recurseChildren
field = self._getControlFieldForUIAObject(
obj,
isEmbedded=objIsEmbedded,
startOfNode=startOfNode,
endOfNode=endOfNode,
)
except LookupError:
if debug:
log.debug("Failed to fetch controlField data for parentElement. Breaking")
continue
if not field:
continue
parentFields.append(field)
if debug:
log.debug("Done generating controlFields for parents")
log.debug("Yielding control starts for parents")
for field in reversed(parentFields):
yield textInfos.FieldCommand("controlStart", field)
if debug:
log.debug("Done yielding control starts for parents")
del parentElements
if debug:
log.debug("Yielding balanced fields for textRange")
# Move through the text range, collecting text and recursing into children
#: This variable is used to span lengths of plain text between child ranges as we iterate over getChildren
childCount = childElements.length if recurseChildren else 0
if childCount > 0:
tempRange = textRange.clone()
tempRange.MoveEndpointByRange(
UIAHandler.TextPatternRangeEndpoint_End,
tempRange,
UIAHandler.TextPatternRangeEndpoint_Start,
)
if debug:
log.debug("Child count: %s" % childElements.length)
log.debug("Walking children")
lastChildIndex = childCount - 1
lastChildEndDelta = 0
documentTextPattern = self.obj.UIATextPattern
rootElementControlType = rootElement.cachedControlType
for index in range(childCount):
childElement = childElements.getElement(index)
if not childElement or UIAHandler.handler.clientObject.compareElements(
childElement,
enclosingElement,
):
if debug:
log.debug("NULL childElement. Skipping")
continue
if rootElementControlType == UIAHandler.UIA_DataItemControlTypeId:
# #9090: MS Word has a rare bug where a child of a table cell's UIA textRange can be its containing page.
# At very least stop the infinite recursion.
childAutomationID = childElement.cachedAutomationId or ""
if childAutomationID.startswith("UIA_AutomationId_Word_Page_"):
continue
if debug:
log.debug("Fetched child %s (%s)" % (index, childElement.currentLocalizedControlType))
try:
childRange = documentTextPattern.rangeFromChild(childElement)
except COMError as e:
if debug:
log.debug(f"rangeFromChild failed with {e}")
childRange = None
if not childRange:
if debug:
log.debug("NULL childRange. Skipping")
continue
clippedStart = False
clippedEnd = False
if (
childRange.CompareEndpoints(
UIAHandler.TextPatternRangeEndpoint_End,
textRange,
UIAHandler.TextPatternRangeEndpoint_Start,
)
<= 0
):
if debug:
log.debug("Child completely before textRange. Skipping")
continue
if (
childRange.CompareEndpoints(
UIAHandler.TextPatternRangeEndpoint_Start,
textRange,
UIAHandler.TextPatternRangeEndpoint_End,
)
>= 0
):
if debug:
log.debug("Child at or past end of textRange. Breaking")
break
lastChildEndDelta = childRange.CompareEndpoints(
UIAHandler.TextPatternRangeEndpoint_End,
textRange,
UIAHandler.TextPatternRangeEndpoint_End,
)
if lastChildEndDelta > 0:
if debug:
log.debug(
"textRange ended part way through the child. " "Crop end of childRange to fit",
)
childRange.MoveEndpointByRange(
UIAHandler.TextPatternRangeEndpoint_End,
textRange,
UIAHandler.TextPatternRangeEndpoint_End,
)
clippedEnd = True
childStartDelta = childRange.CompareEndpoints(
UIAHandler.TextPatternRangeEndpoint_Start,
tempRange,
UIAHandler.TextPatternRangeEndpoint_End,
)
if childStartDelta > 0:
# plain text before this child
tempRange.MoveEndpointByRange(
UIAHandler.TextPatternRangeEndpoint_End,
childRange,
UIAHandler.TextPatternRangeEndpoint_Start,
)
if debug:
log.debug("Plain text before child")
for field in self._getTextWithFields_text(tempRange, formatConfig):
yield field
elif childStartDelta < 0:
if debug:
log.debug(
"textRange started part way through child. "
"Cropping Start of child range to fit",
)
childRange.MoveEndpointByRange(
UIAHandler.TextPatternRangeEndpoint_Start,
tempRange,
UIAHandler.TextPatternRangeEndpoint_End,
)
clippedStart = True
if (index == 0 or index == lastChildIndex) and childRange.CompareEndpoints(
UIAHandler.TextPatternRangeEndpoint_Start,
childRange,
UIAHandler.TextPatternRangeEndpoint_End,
) == 0:
if debug:
log.debug("childRange is degenerate. Skipping")
continue
if debug:
log.debug(f"Recursing into child {index}")
for field in self._getTextWithFieldsForUIARange(
childElement,
childRange,
formatConfig,
includeRoot=True,
alwaysWalkAncestors=False,
_rootElementClipped=(clippedStart, clippedEnd),
):
yield field
if debug:
log.debug(f"Done recursing into child {index}")
tempRange.MoveEndpointByRange(
UIAHandler.TextPatternRangeEndpoint_Start,
childRange,
UIAHandler.TextPatternRangeEndpoint_End,
)
if debug:
log.debug("children done")
# Plain text after the final child
if (
tempRange.CompareEndpoints(
UIAHandler.TextPatternRangeEndpoint_Start,