-
-
Notifications
You must be signed in to change notification settings - Fork 614
/
speech.py
2509 lines (2345 loc) · 95.7 KB
/
speech.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) 2006-2021 NV Access Limited, Peter Vágner, Aleksey Sadovoy, Babbage B.V., Bill Dengler,
# Julien Cochuyt
"""High-level functions to speak information.
"""
import itertools
import weakref
import unicodedata
import time
import colors
import api
import controlTypes
from controlTypes import OutputReason
import tones
from synthDriverHandler import getSynth
import re
import textInfos
import speechDictHandler
import characterProcessing
import languageHandler
from . import manager
from .commands import (
# Commands that are used in this file.
SpeechCommand,
PitchCommand,
LangChangeCommand,
BeepCommand,
EndUtteranceCommand,
CharacterModeCommand,
)
from . import types
from .types import (
SpeechSequence,
SequenceItemT,
logBadSequenceTypes,
GeneratorWithReturn,
_flattenNestedSequences
)
from typing import (
Iterable,
Optional,
Dict,
List,
Any,
Generator,
Union,
Tuple,
)
from logHandler import log
import config
import aria
from .priorities import Spri
from enum import IntEnum
from dataclasses import dataclass
from copy import copy
_speechState: Optional['SpeechState'] = None
_curWordChars: List[str] = []
class SpeechMode(IntEnum):
off = 0
beeps = 1
talk = 2
@dataclass
class SpeechState:
beenCanceled = True
isPaused = False
#: How speech should be handled; one of SpeechMode.off, SpeechMode.beeps or SpeechMode.talk.
speechMode: SpeechMode = SpeechMode.talk
# Length of the beep tone when speech mode is beeps
speechMode_beeps_ms = 15
#: The number of typed characters for which to suppress speech.
_suppressSpeakTypedCharactersNumber = 0
#: The time at which suppressed typed characters were sent.
_suppressSpeakTypedCharactersTime: Optional[float] = None
# Property values that are kept from getPropertiesSpeech
oldTreeLevel = None
oldTableID = None
oldRowNumber = None
oldRowSpan = None
oldColumnNumber = None
oldColumnSpan = None
def getState():
return copy(_speechState)
def setSpeechMode(newMode: SpeechMode):
_speechState.speechMode = newMode
def initialize():
global _speechState
_speechState = SpeechState()
#Set containing locale codes for languages supporting conjunct characters
LANGS_WITH_CONJUNCT_CHARS = {'hi', 'as', 'bn', 'gu', 'kn', 'kok', 'ml', 'mni', 'mr', 'pa', 'te', 'ur', 'ta'}
#: The string used to separate distinct chunks of text when multiple chunks should be spoken without pauses.
# #555: Use two spaces so that numbers from adjacent chunks aren't treated as a single number
# for languages such as French and German which use space as a thousands separator.
CHUNK_SEPARATOR = " "
#: If a chunk of text contains only these characters, it will be considered blank.
BLANK_CHUNK_CHARS = frozenset((" ", "\n", "\r", "\0", u"\xa0"))
def isBlank(text):
"""Determine whether text should be reported as blank.
@param text: The text in question.
@type text: str
@return: C{True} if the text is blank, C{False} if not.
@rtype: bool
"""
return not text or set(text) <= BLANK_CHUNK_CHARS
RE_CONVERT_WHITESPACE = re.compile("[\0\r\n]")
def processText(locale,text,symbolLevel):
text = speechDictHandler.processText(text)
text = characterProcessing.processSpeechSymbols(locale, text, symbolLevel)
text = RE_CONVERT_WHITESPACE.sub(u" ", text)
return text.strip()
def cancelSpeech():
"""Interupts the synthesizer from currently speaking"""
# Import only for this function to avoid circular import.
from .sayAll import SayAllHandler
SayAllHandler.stop()
if _speechState.beenCanceled:
return
elif _speechState.speechMode == SpeechMode.off:
return
elif _speechState.speechMode == SpeechMode.beeps:
return
_manager.cancel()
_speechState.beenCanceled = True
_speechState.isPaused = False
def pauseSpeech(switch):
getSynth().pause(switch)
_speechState.isPaused = switch
_speechState.beenCanceled = False
def _getSpeakMessageSpeech(
text: str,
) -> SpeechSequence:
"""Gets the speech sequence for a given message.
@param text: the message to speak
"""
if text is None:
return []
if isBlank(text):
return [
# Translators: This is spoken when the line is considered blank.
_("blank"),
]
return [text, ]
def speakMessage(
text: str,
priority: Optional[Spri] = None
) -> None:
"""Speaks a given message.
@param text: the message to speak
@param priority: The speech priority.
"""
seq = _getSpeakMessageSpeech(text)
if seq:
speak(seq, symbolLevel=None, priority=priority)
def getCurrentLanguage():
synth = getSynth()
language=None
if synth:
try:
language=synth.language if config.conf['speech']['trustVoiceLanguage'] else None
except NotImplementedError:
pass
if language:
language=languageHandler.normalizeLanguage(language)
if not language:
language=languageHandler.getLanguage()
return language
def spellTextInfo(
info: textInfos.TextInfo,
useCharacterDescriptions: bool = False,
priority: Optional[Spri] = None
) -> None:
"""Spells the text from the given TextInfo, honouring any LangChangeCommand objects it finds if autoLanguageSwitching is enabled."""
if not config.conf['speech']['autoLanguageSwitching']:
speakSpelling(info.text,useCharacterDescriptions=useCharacterDescriptions)
return
curLanguage=None
for field in info.getTextWithFields({}):
if isinstance(field,str):
speakSpelling(field,curLanguage,useCharacterDescriptions=useCharacterDescriptions,priority=priority)
elif isinstance(field,textInfos.FieldCommand) and field.command=="formatChange":
curLanguage=field.field.get('language')
def speakSpelling(
text: str,
locale: Optional[str] = None,
useCharacterDescriptions: bool = False,
priority: Optional[Spri] = None
) -> None:
# This could be a very large list. In future we could convert this into chunks.
seq = list(getSpellingSpeech(
text,
locale=locale,
useCharacterDescriptions=useCharacterDescriptions
))
speak(seq, priority=priority)
def _getSpellingSpeechAddCharMode(
seq: Generator[SequenceItemT, None, None],
) -> Generator[SequenceItemT, None, None]:
"""Inserts CharacterMode commands in a speech sequence generator to ensure any single character
is spelt by the synthesizer.
@param seq: The speech sequence to be spelt.
"""
charMode = False
for item in seq:
if isinstance(item, str):
if len(item) == 1:
if not charMode:
yield CharacterModeCommand(True)
charMode = True
elif charMode:
yield CharacterModeCommand(False)
charMode = False
yield item
def _getSpellingCharAddCapNotification(
speakCharAs: str,
sayCapForCapitals: bool,
capPitchChange: int,
beepForCapitals: bool,
) -> Generator[SequenceItemT, None, None]:
"""This function produces a speech sequence containing a character to be spelt as well as commands
to indicate that this character is uppercase if applicable.
@param speakCharAs: The character as it will be spoken by the synthesizer.
@param sayCapForCapitals: indicates if 'cap' should be reported along with the currently spelt character.
@param capPitchChange: pitch offset to apply while spelling the currently spelt character.
@param beepForCapitals: indicates if a cap notification beep should be produced while spelling the currently
spellt character.
"""
if sayCapForCapitals:
# Translators: cap will be spoken before the given letter when it is capitalized.
capMsg = _("cap %s")
(capMsgBefore, capMsgAfter) = capMsg.split('%s')
else:
capMsgBefore = ''
capMsgAfter = ''
if capPitchChange:
yield PitchCommand(offset=capPitchChange)
if beepForCapitals:
yield BeepCommand(2000, 50)
if capMsgBefore:
yield capMsgBefore
yield speakCharAs
if capMsgAfter:
yield capMsgAfter
if capPitchChange:
yield PitchCommand()
def _getSpellingSpeechWithoutCharMode(
text: str,
locale: str,
useCharacterDescriptions: bool,
sayCapForCapitals: bool,
capPitchChange: int,
beepForCapitals: bool,
) -> Generator[SequenceItemT, None, None]:
defaultLanguage=getCurrentLanguage()
if not locale or (not config.conf['speech']['autoDialectSwitching'] and locale.split('_')[0]==defaultLanguage.split('_')[0]):
locale=defaultLanguage
if not text:
# Translators: This is spoken when NVDA moves to an empty line.
yield _("blank")
return
if not text.isspace():
text=text.rstrip()
textLength=len(text)
count = 0
localeHasConjuncts = True if locale.split('_',1)[0] in LANGS_WITH_CONJUNCT_CHARS else False
charDescList = getCharDescListFromText(text,locale) if localeHasConjuncts else text
for item in charDescList:
if localeHasConjuncts:
# item is a tuple containing character and its description
speakCharAs = item[0]
charDesc = item[1]
else:
# item is just a character.
speakCharAs = item
if useCharacterDescriptions:
charDesc=characterProcessing.getCharacterDescription(locale,speakCharAs.lower())
uppercase=speakCharAs.isupper()
if useCharacterDescriptions and charDesc:
IDEOGRAPHIC_COMMA = u"\u3001"
speakCharAs=charDesc[0] if textLength>1 else IDEOGRAPHIC_COMMA.join(charDesc)
else:
speakCharAs=characterProcessing.processSpeechSymbol(locale,speakCharAs)
if config.conf['speech']['autoLanguageSwitching']:
yield LangChangeCommand(locale)
yield from _getSpellingCharAddCapNotification(
speakCharAs,
uppercase and sayCapForCapitals,
capPitchChange if uppercase else 0,
uppercase and beepForCapitals,
)
yield EndUtteranceCommand()
def getSpellingSpeech(
text: str,
locale: Optional[str] = None,
useCharacterDescriptions: bool = False
) -> Generator[SequenceItemT, None, None]:
synth = getSynth()
synthConfig = config.conf["speech"][synth.name]
if synth.isSupported("pitch"):
capPitchChange = synthConfig["capPitchChange"]
else:
capPitchChange = 0
seq = _getSpellingSpeechWithoutCharMode(
text,
locale,
useCharacterDescriptions,
sayCapForCapitals=synthConfig["sayCapForCapitals"],
capPitchChange=capPitchChange,
beepForCapitals=synthConfig["beepForCapitals"],
)
if synthConfig["useSpellingFunctionality"]:
seq = _getSpellingSpeechAddCharMode(seq)
yield from seq
def getCharDescListFromText(text,locale):
"""This method prepares a list, which contains character and its description for all characters the text is made up of, by checking the presence of character descriptions in characterDescriptions.dic of that locale for all possible combination of consecutive characters in the text.
This is done to take care of conjunct characters present in several languages such as Hindi, Urdu, etc.
"""
charDescList = []
charDesc=None
i = len(text)
while i:
subText = text[:i]
charDesc = characterProcessing.getCharacterDescription(locale,subText)
if charDesc or i==1:
if not charDesc:
# #5375: We're down to a single character (i == 1) and we don't have a description.
# Try converting to lower case.
# This provides for upper case English characters (which only have lower case descriptions).
charDesc = characterProcessing.getCharacterDescription(locale,subText.lower())
charDescList.append((subText,charDesc))
text = text[i:]
i = len(text)
else:
i = i - 1
return charDescList
def speakObjectProperties( # noqa: C901
obj,
reason: OutputReason = OutputReason.QUERY,
_prefixSpeechCommand: Optional[SpeechCommand] = None,
priority: Optional[Spri] = None,
**allowedProperties
):
speechSequence = getObjectPropertiesSpeech(
obj,
reason,
_prefixSpeechCommand,
**allowedProperties,
)
if speechSequence:
speak(speechSequence, priority=priority)
# C901 'getObjectPropertiesSpeech' is too complex
# Note: when working on getObjectPropertiesSpeech, look for opportunities to simplify
# and move logic out into smaller helper functions.
def getObjectPropertiesSpeech( # noqa: C901
obj,
reason: OutputReason = OutputReason.QUERY,
_prefixSpeechCommand: Optional[SpeechCommand] = None,
**allowedProperties
) -> SpeechSequence:
#Fetch the values for all wanted properties
newPropertyValues={}
positionInfo=None
for name,value in allowedProperties.items():
if name=="includeTableCellCoords":
# This is verbosity info.
newPropertyValues[name]=value
elif name.startswith('positionInfo_') and value:
if positionInfo is None:
positionInfo=obj.positionInfo
elif value and name == "current":
# getPropertiesSpeech names this "current", but the NVDAObject property is
# named "isCurrent", it's type should always be controltypes.IsCurrent
newPropertyValues['current'] = obj.isCurrent
elif value:
# Certain properties such as row and column numbers have presentational versions, which should be used for speech if they are available.
# Therefore redirect to those values first if they are available, falling back to the normal properties if not.
names=[name]
if name=='rowNumber':
names.insert(0,'presentationalRowNumber')
elif name=='columnNumber':
names.insert(0,'presentationalColumnNumber')
elif name=='rowCount':
names.insert(0,'presentationalRowCount')
elif name=='columnCount':
names.insert(0,'presentationalColumnCount')
for tryName in names:
try:
newPropertyValues[name]=getattr(obj,tryName)
except NotImplementedError:
continue
break
if positionInfo:
if allowedProperties.get('positionInfo_level',False) and 'level' in positionInfo:
newPropertyValues['positionInfo_level']=positionInfo['level']
if allowedProperties.get('positionInfo_indexInGroup',False) and 'indexInGroup' in positionInfo:
newPropertyValues['positionInfo_indexInGroup']=positionInfo['indexInGroup']
if allowedProperties.get('positionInfo_similarItemsInGroup',False) and 'similarItemsInGroup' in positionInfo:
newPropertyValues['positionInfo_similarItemsInGroup']=positionInfo['similarItemsInGroup']
#Fetched the cached properties and update them with the new ones
oldCachedPropertyValues=getattr(obj,'_speakObjectPropertiesCache',{}).copy()
cachedPropertyValues=oldCachedPropertyValues.copy()
cachedPropertyValues.update(newPropertyValues)
obj._speakObjectPropertiesCache=cachedPropertyValues
#If we should only cache we can stop here
if reason == OutputReason.ONLYCACHE:
return []
#If only speaking change, then filter out all values that havn't changed
if reason == OutputReason.CHANGE:
for name in set(newPropertyValues)&set(oldCachedPropertyValues):
if newPropertyValues[name]==oldCachedPropertyValues[name]:
del newPropertyValues[name]
elif name=="states": #states need specific handling
oldStates=oldCachedPropertyValues[name]
newStates=newPropertyValues[name]
newPropertyValues['states']=newStates-oldStates
newPropertyValues['negativeStates']=oldStates-newStates
#properties such as states need to know the role to speak properly, give it as a _ name
newPropertyValues['_role']=newPropertyValues.get('role',obj.role)
# The real states are needed also, as the states entry might be filtered.
newPropertyValues['_states']=obj.states
if "rowNumber" in newPropertyValues or "columnNumber" in newPropertyValues:
# We're reporting table cell info, so pass the table ID.
try:
newPropertyValues["_tableID"]=obj.tableID
except NotImplementedError:
pass
if allowedProperties.get('placeholder', False):
newPropertyValues['placeholder']=obj.placeholder
# When speaking an object due to a focus change, the 'selected' state should not be reported if only one item is selected.
# This is because that one item will be the focused object, and saying selected is redundant.
# Rather, 'unselected' will be spoken for an unselected object if 1 or more items are selected.
states=newPropertyValues.get('states')
if states is not None and reason == OutputReason.FOCUS:
if (
controlTypes.STATE_SELECTABLE in states
and controlTypes.STATE_FOCUSABLE in states
and controlTypes.STATE_SELECTED in states
and obj.selectionContainer
and obj.selectionContainer.getSelectedItemsCount(2)==1
):
# We must copy the states set and put it back in newPropertyValues otherwise mutating the original states set in-place will wrongly change the cached states.
# This would then cause 'selected' to be announced as a change when any other state happens to change on this object in future.
states=states.copy()
states.discard(controlTypes.STATE_SELECTED)
states.discard(controlTypes.STATE_SELECTABLE)
newPropertyValues['states']=states
#Get the speech text for the properties we want to speak, and then speak it
speechSequence = getPropertiesSpeech(reason=reason, **newPropertyValues)
if speechSequence:
if _prefixSpeechCommand is not None:
speechSequence.insert(0, _prefixSpeechCommand)
from eventHandler import _getFocusLossCancellableSpeechCommand
cancelCommand = _getFocusLossCancellableSpeechCommand(obj, reason)
if cancelCommand is not None:
speechSequence.append(cancelCommand)
return speechSequence
def _getPlaceholderSpeechIfTextEmpty(
obj,
reason: OutputReason,
) -> Tuple[bool, SpeechSequence]:
""" Attempt to get speech for placeholder attribute if text for 'obj' is empty. Don't report the placeholder
value unless the text is empty, because it is confusing to hear the current value (presumably typed by the
user) *and* the placeholder. The placeholder should "disappear" once the user types a value.
@return: (True, SpeechSequence) if text for obj was considered empty and we attempted to get speech for the
placeholder value. (False, []) if text for obj was not considered empty.
"""
textEmpty = obj._isTextEmpty
if textEmpty:
return True, getObjectPropertiesSpeech(obj, reason=reason, placeholder=True)
return False, []
def speakObject(
obj,
reason: OutputReason = OutputReason.QUERY,
_prefixSpeechCommand: Optional[SpeechCommand] = None,
priority: Optional[Spri] = None
):
sequence = getObjectSpeech(
obj,
reason,
_prefixSpeechCommand,
)
if sequence:
speak(sequence, priority=priority)
# C901 'getObjectSpeech' is too complex
# Note: when working on getObjectSpeech, look for opportunities to simplify
# and move logic out into smaller helper functions.
def getObjectSpeech( # noqa: C901
obj,
reason: OutputReason = OutputReason.QUERY,
_prefixSpeechCommand: Optional[SpeechCommand] = None,
):
role=obj.role
# Choose when we should report the content of this object's textInfo, rather than just the object's value
import browseMode
shouldReportTextContent=not (
# focusEntered should never present text content
(reason == OutputReason.FOCUSENTERED)
# The rootNVDAObject of a browseMode document in browse mode (not passThrough)
# should never present text content
or (
isinstance(obj.treeInterceptor, browseMode.BrowseModeDocumentTreeInterceptor)
and not obj.treeInterceptor.passThrough
and obj == obj.treeInterceptor.rootNVDAObject
)
# objects that do not report as having navigableText should not report their text content either
or not obj._hasNavigableText
)
allowProperties = _objectSpeech_calculateAllowedProps(reason, shouldReportTextContent)
if reason == OutputReason.FOCUSENTERED:
# Aside from excluding some properties, focus entered should be spoken like focus.
reason = OutputReason.FOCUS
sequence = getObjectPropertiesSpeech(
obj,
reason=reason,
_prefixSpeechCommand=_prefixSpeechCommand,
**allowProperties
)
if reason == OutputReason.ONLYCACHE:
return sequence
if shouldReportTextContent:
try:
info = obj.makeTextInfo(textInfos.POSITION_SELECTION)
except (NotImplementedError, RuntimeError):
info = None
if info and not info.isCollapsed:
# if there is selected text, then there is a value and we do not report placeholder
sequence.extend(getPreselectedTextSpeech(info.text))
else:
if not info:
info = obj.makeTextInfo(textInfos.POSITION_FIRST)
info.expand(textInfos.UNIT_LINE)
textEmpty, placeholderSeq = _getPlaceholderSpeechIfTextEmpty(obj, reason)
sequence.extend(placeholderSeq)
speechGen = getTextInfoSpeech(
info,
unit=textInfos.UNIT_LINE,
reason=OutputReason.CARET,
)
sequence.extend(_flattenNestedSequences(speechGen))
elif role == controlTypes.ROLE_MATH:
import mathPres
mathPres.ensureInit()
if mathPres.speechProvider:
try:
sequence.extend(
mathPres.speechProvider.getSpeechForMathMl(obj.mathMl)
)
except (NotImplementedError, LookupError):
pass
return sequence
def _objectSpeech_calculateAllowedProps(reason, shouldReportTextContent):
allowProperties = {
'name': True,
'role': True,
'roleText': True,
'states': True,
'value': True,
'description': True,
'keyboardShortcut': True,
'positionInfo_level': True,
'positionInfo_indexInGroup': True,
'positionInfo_similarItemsInGroup': True,
"cellCoordsText": True,
"rowNumber": True,
"columnNumber": True,
"includeTableCellCoords": True,
"columnCount": True,
"rowCount": True,
"rowHeaderText": True,
"columnHeaderText": True,
"rowSpan": True,
"columnSpan": True,
"current": True
}
if reason == OutputReason.FOCUSENTERED:
allowProperties["value"] = False
allowProperties["keyboardShortcut"] = False
allowProperties["positionInfo_level"] = False
if not config.conf["presentation"]["reportObjectDescriptions"]:
allowProperties["description"] = False
if not config.conf["presentation"]["reportKeyboardShortcuts"]:
allowProperties["keyboardShortcut"] = False
if not config.conf["presentation"]["reportObjectPositionInformation"]:
allowProperties["positionInfo_level"] = False
allowProperties["positionInfo_indexInGroup"] = False
allowProperties["positionInfo_similarItemsInGroup"] = False
if reason != OutputReason.QUERY:
allowProperties["rowCount"] = False
allowProperties["columnCount"] = False
formatConf = config.conf["documentFormatting"]
if not formatConf["reportTableCellCoords"]:
allowProperties["cellCoordsText"] = False
# rowNumber and columnNumber might be needed even if we're not reporting coordinates.
allowProperties["includeTableCellCoords"] = False
if not formatConf["reportTableHeaders"]:
allowProperties["rowHeaderText"] = False
allowProperties["columnHeaderText"] = False
if (
not formatConf["reportTables"]
or (
not formatConf["reportTableCellCoords"]
and not formatConf["reportTableHeaders"]
)
):
# We definitely aren't reporting any table info at all.
allowProperties["rowNumber"] = False
allowProperties["columnNumber"] = False
allowProperties["rowSpan"] = False
allowProperties["columnSpan"] = False
if shouldReportTextContent:
allowProperties['value'] = False
return allowProperties
def speakText(
text: str,
reason: OutputReason = OutputReason.MESSAGE,
symbolLevel: Optional[int] = None,
priority: Optional[Spri] = None
):
"""Speaks some text.
@param text: The text to speak.
@param reason: Unused
@param symbolLevel: The symbol verbosity level; C{None} (default) to use the user's configuration.
@param priority: The speech priority.
"""
seq = _getSpeakMessageSpeech(text)
if seq:
speak(seq, symbolLevel=symbolLevel, priority=priority)
RE_INDENTATION_SPLIT = re.compile(r"^([^\S\r\n\f\v]*)(.*)$", re.UNICODE | re.DOTALL)
def splitTextIndentation(text):
"""Splits indentation from the rest of the text.
@param text: The text to split.
@type text: str
@return: Tuple of indentation and content.
@rtype: (str, str)
"""
return RE_INDENTATION_SPLIT.match(text).groups()
RE_INDENTATION_CONVERT = re.compile(r"(?P<char>\s)(?P=char)*", re.UNICODE)
IDT_BASE_FREQUENCY = 220 #One octave below middle A.
IDT_TONE_DURATION = 80 #Milleseconds
IDT_MAX_SPACES = 72
def getIndentationSpeech(indentation: str, formatConfig: Dict[str, bool]) -> SpeechSequence:
"""Retrieves the indentation speech sequence for a given string of indentation.
@param indentation: The string of indentation.
@param formatConfig: The configuration to use.
"""
speechIndentConfig = formatConfig["reportLineIndentation"]
toneIndentConfig = (
formatConfig["reportLineIndentationWithTones"]
and _speechState.speechMode == SpeechMode.talk
)
indentSequence: SpeechSequence = []
if not indentation:
if toneIndentConfig:
indentSequence.append(BeepCommand(IDT_BASE_FREQUENCY, IDT_TONE_DURATION))
if speechIndentConfig:
indentSequence.append(
# Translators: This is spoken when the given line has no indentation.
_("no indent")
)
return indentSequence
#The non-breaking space is semantically a space, so we replace it here.
indentation = indentation.replace(u"\xa0", u" ")
res = []
locale=languageHandler.getLanguage()
quarterTones = 0
for m in RE_INDENTATION_CONVERT.finditer(indentation):
raw = m.group()
symbol = characterProcessing.processSpeechSymbol(locale, raw[0])
count = len(raw)
if symbol == raw[0]:
# There is no replacement for this character, so do nothing.
res.append(raw)
elif count == 1:
res.append(symbol)
else:
res.append(u"{count} {symbol}".format(count=count, symbol=symbol))
quarterTones += (count*4 if raw[0]== "\t" else count)
speak = speechIndentConfig
if toneIndentConfig:
if quarterTones <= IDT_MAX_SPACES:
pitch = IDT_BASE_FREQUENCY*2**(quarterTones/24.0) #24 quarter tones per octave.
indentSequence.append(BeepCommand(pitch, IDT_TONE_DURATION))
else:
#we have more than 72 spaces (18 tabs), and must speak it since we don't want to hurt the users ears.
speak = True
if speak:
indentSequence.extend(res)
return indentSequence
# C901 'speak' is too complex
# Note: when working on speak, look for opportunities to simplify
# and move logic out into smaller helper functions.
def speak( # noqa: C901
speechSequence: SpeechSequence,
symbolLevel: Optional[int] = None,
priority: Spri = Spri.NORMAL
):
"""Speaks a sequence of text and speech commands
@param speechSequence: the sequence of text and L{SpeechCommand} objects to speak
@param symbolLevel: The symbol verbosity level; C{None} (default) to use the user's configuration.
@param priority: The speech priority.
"""
logBadSequenceTypes(speechSequence)
# in case priority was explicitly passed in as None, set to default.
priority: Spri = Spri.NORMAL if priority is None else priority
if not speechSequence: # Pointless - nothing to speak
return
import speechViewer
if speechViewer.isActive:
speechViewer.appendSpeechSequence(speechSequence)
if _speechState.speechMode == SpeechMode.off:
return
elif _speechState.speechMode == SpeechMode.beeps:
tones.beep(config.conf["speech"]["beepSpeechModePitch"], _speechState.speechMode_beeps_ms)
return
if _speechState.isPaused:
cancelSpeech()
_speechState.beenCanceled = False
#Filter out redundant LangChangeCommand objects
#And also fill in default values
autoLanguageSwitching=config.conf['speech']['autoLanguageSwitching']
autoDialectSwitching=config.conf['speech']['autoDialectSwitching']
curLanguage=defaultLanguage=getCurrentLanguage()
prevLanguage=None
defaultLanguageRoot=defaultLanguage.split('_')[0]
oldSpeechSequence=speechSequence
speechSequence=[]
for item in oldSpeechSequence:
if isinstance(item,LangChangeCommand):
if not autoLanguageSwitching: continue
curLanguage=item.lang
if not curLanguage or (not autoDialectSwitching and curLanguage.split('_')[0]==defaultLanguageRoot):
curLanguage=defaultLanguage
elif isinstance(item,str):
if not item: continue
if autoLanguageSwitching and curLanguage!=prevLanguage:
speechSequence.append(LangChangeCommand(curLanguage))
prevLanguage=curLanguage
speechSequence.append(item)
else:
speechSequence.append(item)
if not speechSequence:
# After normalisation, the sequence is empty.
# There's nothing to speak.
return
import inputCore
inputCore.logTimeSinceInput()
log.io("Speaking %r" % speechSequence)
if symbolLevel is None:
symbolLevel=config.conf["speech"]["symbolLevel"]
curLanguage=defaultLanguage
inCharacterMode=False
for index in range(len(speechSequence)):
item=speechSequence[index]
if isinstance(item,CharacterModeCommand):
inCharacterMode=item.state
if autoLanguageSwitching and isinstance(item,LangChangeCommand):
curLanguage=item.lang
if isinstance(item,str):
speechSequence[index]=processText(curLanguage,item,symbolLevel)
if not inCharacterMode:
speechSequence[index]+=CHUNK_SEPARATOR
_manager.speak(speechSequence, priority)
def speakPreselectedText(
text: str,
priority: Optional[Spri] = None
):
""" Helper method to announce that a newly focused control already has
text selected. This method is in contrast with L{speakTextSelected}.
The method will speak the word "selected" with the provided text appended.
The announcement order is different from L{speakTextSelected} in order to
inform a user that the newly focused control has content that is selected,
which they may unintentionally overwrite.
@remarks: Implemented using L{getPreselectedTextSpeech}
"""
seq = getPreselectedTextSpeech(text)
if seq:
speak(seq, symbolLevel=None, priority=priority)
def getPreselectedTextSpeech(
text: str
) -> SpeechSequence:
""" Helper method to get the speech sequence to announce a newly focused control already has
text selected.
This method will speak the word "selected" with the provided text appended.
The announcement order is different from L{speakTextSelected} in order to
inform a user that the newly focused control has content that is selected,
which they may unintentionally overwrite.
@remarks: Implemented using L{_getSelectionMessageSpeech}, which allows for
creating a speech sequence with an arbitrary attached message.
"""
return _getSelectionMessageSpeech(
# Translators: This is spoken to indicate that some text is already selected.
# 'selected' preceding text is intentional.
# For example 'selected hello world'
_("selected %s"),
text
)
def speakTextSelected(
text: str,
priority: Optional[Spri] = None
):
""" Helper method to announce that the user has caused text to be selected.
This method is in contrast with L{speakPreselectedText}.
The method will speak the provided text with the word "selected" appended.
@remarks: Implemented using L{speakSelectionMessage}, which allows for
speaking text with an arbitrary attached message.
"""
# Translators: This is spoken to indicate what has just been selected.
# The text preceding 'selected' is intentional.
# For example 'hello world selected'
speakSelectionMessage(_("%s selected"), text, priority)
def speakSelectionMessage(
message: str,
text: str,
priority: Optional[Spri] = None
):
seq = _getSelectionMessageSpeech(message, text)
if seq:
speak(seq, symbolLevel=None, priority=priority)
def _getSelectionMessageSpeech(
message: str,
text: str,
) -> SpeechSequence:
if len(text) < 512:
return _getSpeakMessageSpeech(message % text)
# Translators: This is spoken when the user has selected a large portion of text.
# Example output "1000 characters"
numCharactersText = _("%d characters") % len(text)
return _getSpeakMessageSpeech(message % numCharactersText)
# C901 'speakSelectionChange' is too complex
# Note: when working on speakSelectionChange, look for opportunities to simplify
# and move logic out into smaller helper functions.
def speakSelectionChange( # noqa: C901
oldInfo: textInfos.TextInfo,
newInfo: textInfos.TextInfo,
speakSelected: bool = True,
speakUnselected: bool = True,
generalize: bool = False,
priority: Optional[Spri] = None
):
"""Speaks a change in selection, either selected or unselected text.
@param oldInfo: a TextInfo instance representing what the selection was before
@param newInfo: a TextInfo instance representing what the selection is now
@param generalize: if True, then this function knows that the text may have changed between the creation of the oldInfo and newInfo objects, meaning that changes need to be spoken more generally, rather than speaking the specific text, as the bounds may be all wrong.
@param priority: The speech priority.
"""
selectedTextList=[]
unselectedTextList=[]
if newInfo.isCollapsed and oldInfo.isCollapsed:
return
startToStart=newInfo.compareEndPoints(oldInfo,"startToStart")
startToEnd=newInfo.compareEndPoints(oldInfo,"startToEnd")
endToStart=newInfo.compareEndPoints(oldInfo,"endToStart")
endToEnd=newInfo.compareEndPoints(oldInfo,"endToEnd")
if speakSelected and oldInfo.isCollapsed:
selectedTextList.append(newInfo.text)
elif speakUnselected and newInfo.isCollapsed:
unselectedTextList.append(oldInfo.text)
else:
if startToEnd>0 or endToStart<0:
if speakSelected and not newInfo.isCollapsed:
selectedTextList.append(newInfo.text)
if speakUnselected and not oldInfo.isCollapsed:
unselectedTextList.append(oldInfo.text)
else:
if speakSelected and startToStart<0 and not newInfo.isCollapsed:
tempInfo=newInfo.copy()
tempInfo.setEndPoint(oldInfo,"endToStart")
selectedTextList.append(tempInfo.text)
if speakSelected and endToEnd>0 and not newInfo.isCollapsed:
tempInfo=newInfo.copy()
tempInfo.setEndPoint(oldInfo,"startToEnd")
selectedTextList.append(tempInfo.text)
if startToStart>0 and not oldInfo.isCollapsed:
tempInfo=oldInfo.copy()
tempInfo.setEndPoint(newInfo,"endToStart")
unselectedTextList.append(tempInfo.text)
if endToEnd<0 and not oldInfo.isCollapsed:
tempInfo=oldInfo.copy()
tempInfo.setEndPoint(newInfo,"startToEnd")
unselectedTextList.append(tempInfo.text)
locale=getCurrentLanguage()
if speakSelected:
if not generalize:
for text in selectedTextList:
if len(text)==1:
text=characterProcessing.processSpeechSymbol(locale,text)
speakTextSelected(text, priority=priority)
elif len(selectedTextList)>0:
text=newInfo.text
if len(text)==1:
text=characterProcessing.processSpeechSymbol(locale,text)
speakTextSelected(text, priority=priority)
if speakUnselected:
if not generalize:
for text in unselectedTextList:
if len(text)==1:
text=characterProcessing.processSpeechSymbol(locale,text)
# Translators: This is spoken to indicate what has been unselected. for example 'hello unselected'
speakSelectionMessage(_("%s unselected"),text,priority=priority)
elif len(unselectedTextList)>0:
if not newInfo.isCollapsed:
text=newInfo.text
if len(text)==1: