forked from nvaccess/nvda
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathspeech.py
executable file
·1874 lines (1771 loc) · 81.3 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
# -*- coding: UTF-8 -*-
#speech.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) 2006-2017 NV Access Limited, Peter Vágner, Aleksey Sadovoy, Babbage B.V.
"""High-level functions to speak information.
"""
import itertools
import weakref
import unicodedata
import time
import colors
import globalVars
from logHandler import log
import api
import controlTypes
import config
import tones
import synthDriverHandler
from synthDriverHandler import *
import re
import textInfos
import queueHandler
import speechDictHandler
import characterProcessing
import languageHandler
speechMode_off=0
speechMode_beeps=1
speechMode_talk=2
#: How speech should be handled; one of speechMode_off, speechMode_beeps or speechMode_talk.
speechMode=speechMode_talk
speechMode_beeps_ms=15
beenCanceled=True
isPaused=False
curWordChars=[]
#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 = " "
oldTreeLevel=None
oldTableID=None
oldRowNumber=None
oldRowSpan=None
oldColumnNumber=None
oldColumnSpan=None
def initialize():
"""Loads and sets the synth driver configured in nvda.ini."""
synthDriverHandler.initialize()
setSynth(config.conf["speech"]["synth"])
def terminate():
setSynth(None)
speechViewerObj=None
#: 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 getLastSpeechIndex():
"""Gets the last index passed by the synthesizer. Indexing is used so that its possible to find out when a certain peace of text has been spoken yet. Usually the character position of the text is passed to speak functions as the index.
@returns: the last index encountered
@rtype: int
"""
return getSynth().lastIndex
def cancelSpeech():
"""Interupts the synthesizer from currently speaking"""
global beenCanceled, isPaused, _speakSpellingGenerator
# Import only for this function to avoid circular import.
import sayAllHandler
sayAllHandler.stop()
speakWithoutPauses._pendingSpeechSequence=[]
speakWithoutPauses.lastSentIndex=None
if _speakSpellingGenerator:
_speakSpellingGenerator.close()
if beenCanceled:
return
elif speechMode==speechMode_off:
return
elif speechMode==speechMode_beeps:
return
getSynth().cancel()
beenCanceled=True
isPaused=False
def pauseSpeech(switch):
global isPaused, beenCanceled
getSynth().pause(switch)
isPaused=switch
beenCanceled=False
def speakMessage(text,index=None):
"""Speaks a given message.
@param text: the message to speak
@type text: string
@param index: the index to mark this current text with, its best to use the character position of the text if you know it
@type index: int
"""
speakText(text,index=index,reason=controlTypes.REASON_MESSAGE)
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,useCharacterDescriptions=False):
"""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,basestring):
speakSpelling(field,curLanguage,useCharacterDescriptions=useCharacterDescriptions)
elif isinstance(field,textInfos.FieldCommand) and field.command=="formatChange":
curLanguage=field.field.get('language')
_speakSpellingGenerator=None
def speakSpelling(text,locale=None,useCharacterDescriptions=False):
global beenCanceled, _speakSpellingGenerator
import speechViewer
if speechViewer.isActive:
speechViewer.appendText(text)
if speechMode==speechMode_off:
return
elif speechMode==speechMode_beeps:
tones.beep(config.conf["speech"]["beepSpeechModePitch"],speechMode_beeps_ms)
return
if isPaused:
cancelSpeech()
beenCanceled=False
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.
return getSynth().speak((_("blank"),))
if not text.isspace():
text=text.rstrip()
if _speakSpellingGenerator and _speakSpellingGenerator.gi_frame:
_speakSpellingGenerator.send((text,locale,useCharacterDescriptions))
else:
_speakSpellingGenerator=_speakSpellingGen(text,locale,useCharacterDescriptions)
try:
# Speak the first character before this function returns.
next(_speakSpellingGenerator)
except StopIteration:
return
queueHandler.registerGeneratorObject(_speakSpellingGenerator)
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 _speakSpellingGen(text,locale,useCharacterDescriptions):
synth=getSynth()
synthConfig=config.conf["speech"][synth.name]
buf=[(text,locale,useCharacterDescriptions)]
for text,locale,useCharacterDescriptions in buf:
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
char = item[0]
charDesc = item[1]
else:
# item is just a character.
char = item
if useCharacterDescriptions:
charDesc=characterProcessing.getCharacterDescription(locale,char.lower())
uppercase=char.isupper()
if useCharacterDescriptions and charDesc:
#Consider changing to multiple synth speech calls
char=charDesc[0] if textLength>1 else u"\u3001".join(charDesc)
else:
char=characterProcessing.processSpeechSymbol(locale,char)
if uppercase and synthConfig["sayCapForCapitals"]:
# Translators: cap will be spoken before the given letter when it is capitalized.
char=_("cap %s")%char
if uppercase and synth.isSupported("pitch") and synthConfig["capPitchChange"]:
oldPitch=synthConfig["pitch"]
synth.pitch=max(0,min(oldPitch+synthConfig["capPitchChange"],100))
count = len(char)
index=count+1
log.io("Speaking character %r"%char)
speechSequence=[LangChangeCommand(locale)] if config.conf['speech']['autoLanguageSwitching'] else []
if len(char) == 1 and synthConfig["useSpellingFunctionality"]:
speechSequence.append(CharacterModeCommand(True))
if index is not None:
speechSequence.append(IndexCommand(index))
speechSequence.append(char)
synth.speak(speechSequence)
if uppercase and synth.isSupported("pitch") and synthConfig["capPitchChange"]:
synth.pitch=oldPitch
while textLength>1 and (isPaused or getLastSpeechIndex()!=index):
for x in xrange(2):
args=yield
if args: buf.append(args)
if uppercase and synthConfig["beepForCapitals"]:
tones.beep(2000,50)
args=yield
if args: buf.append(args)
def speakObjectProperties(obj,reason=controlTypes.REASON_QUERY,index=None,**allowedProperties):
#Fetch the values for all wanted properties
newPropertyValues={}
positionInfo=None
for name,value in allowedProperties.iteritems():
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:
try:
newPropertyValues[name]=getattr(obj,name)
except NotImplementedError:
pass
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==controlTypes.REASON_ONLYCACHE:
return
#If only speaking change, then filter out all values that havn't changed
if reason==controlTypes.REASON_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
newPropertyValues['current']=obj.isCurrent
if allowedProperties.get('placeholder', False):
newPropertyValues['placeholder']=obj.placeholder
#Get the speech text for the properties we want to speak, and then speak it
text=getSpeechTextForProperties(reason,**newPropertyValues)
if text:
speakText(text,index=index)
def _speakPlaceholderIfEmpty(info, obj, reason):
""" attempt to speak placeholder attribute if the textInfo 'info' is empty
@return: True if info was considered empty, and we attempted to speak the placeholder value.
False if info was not considered empty.
"""
textEmpty = obj._isTextEmpty
if textEmpty:
speakObjectProperties(obj,reason=reason,placeholder=True)
return True
return False
def speakObject(obj,reason=controlTypes.REASON_QUERY,index=None):
from NVDAObjects import NVDAObjectTextInfo
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==controlTypes.REASON_FOCUSENTERED) or
# The rootNVDAObject of a browseMode document in browse mode (not passThrough) should never present text content
(isinstance(obj.treeInterceptor,browseMode.BrowseModeDocumentTreeInterceptor) and not obj.treeInterceptor.passThrough and obj==obj.treeInterceptor.rootNVDAObject) or
# objects that do not report as having navigableText should not report their text content either
not obj._hasNavigableText
)
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}
if reason==controlTypes.REASON_FOCUSENTERED:
allowProperties["value"]=False
allowProperties["keyboardShortcut"]=False
allowProperties["positionInfo_level"]=False
# Aside from excluding some properties, focus entered should be spoken like focus.
reason=controlTypes.REASON_FOCUS
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!=controlTypes.REASON_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
speakObjectProperties(obj,reason=reason,index=index,**allowProperties)
if reason==controlTypes.REASON_ONLYCACHE:
return
if shouldReportTextContent:
try:
info=obj.makeTextInfo(textInfos.POSITION_SELECTION)
if not info.isCollapsed:
# if there is selected text, then there is a value and we do not report placeholder
# Translators: This is spoken to indicate what has been selected. for example 'selected hello world'
speakSelectionMessage(_("selected %s"),info.text)
else:
info.expand(textInfos.UNIT_LINE)
_speakPlaceholderIfEmpty(info, obj, reason)
speakTextInfo(info,unit=textInfos.UNIT_LINE,reason=controlTypes.REASON_CARET)
except:
newInfo=obj.makeTextInfo(textInfos.POSITION_ALL)
if not _speakPlaceholderIfEmpty(newInfo, obj, reason):
speakTextInfo(newInfo,unit=textInfos.UNIT_PARAGRAPH,reason=controlTypes.REASON_CARET)
elif role==controlTypes.ROLE_MATH:
import mathPres
mathPres.ensureInit()
if mathPres.speechProvider:
try:
speak(mathPres.speechProvider.getSpeechForMathMl(obj.mathMl))
except (NotImplementedError, LookupError):
pass
def speakText(text,index=None,reason=controlTypes.REASON_MESSAGE,symbolLevel=None):
"""Speaks some text.
@param text: The text to speak.
@type text: str
@param index: The index to mark this text with, which can be used later to determine whether this piece of text has been spoken.
@type index: int
@param reason: The reason for this speech; one of the controlTypes.REASON_* constants.
@param symbolLevel: The symbol verbosity level; C{None} (default) to use the user's configuration.
"""
speechSequence=[]
if index is not None:
speechSequence.append(IndexCommand(index))
if text is not None:
if isBlank(text):
# Translators: This is spoken when the line is considered blank.
text=_("blank")
speechSequence.append(text)
speak(speechSequence,symbolLevel=symbolLevel)
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: basestring
@return: Tuple of indentation and content.
@rtype: (basestring, basestring)
"""
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, formatConfig):
"""Retrieves the phrase to be spoken for a given string of indentation.
@param indentation: The string of indentation.
@type indentation: unicode
@param formatConfig: The configuration to use.
@type formatConfig: dict
@return: The phrase to be spoken.
@rtype: unicode
"""
speechIndentConfig = formatConfig["reportLineIndentation"]
toneIndentConfig = formatConfig["reportLineIndentationWithTones"] and speechMode == speechMode_talk
if not indentation:
if toneIndentConfig:
tones.beep(IDT_BASE_FREQUENCY, IDT_TONE_DURATION)
# Translators: This is spoken when the given line has no indentation.
return (_("no indent") if speechIndentConfig else "")
#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:
#Remove me during speech refactor.
pitch = IDT_BASE_FREQUENCY*2**(quarterTones/24.0) #24 quarter tones per octave.
tones.beep(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
return (" ".join(res) if speak else "")
def speak(speechSequence,symbolLevel=None):
"""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.
"""
if not speechSequence: #Pointless - nothing to speak
return
import speechViewer
if speechViewer.isActive:
for item in speechSequence:
if isinstance(item,basestring):
speechViewer.appendText(item)
global beenCanceled, curWordChars
curWordChars=[]
if speechMode==speechMode_off:
return
elif speechMode==speechMode_beeps:
tones.beep(config.conf["speech"]["beepSpeechModePitch"],speechMode_beeps_ms)
return
if isPaused:
cancelSpeech()
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,basestring):
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
log.io("Speaking %r" % speechSequence)
if symbolLevel is None:
symbolLevel=config.conf["speech"]["symbolLevel"]
curLanguage=defaultLanguage
inCharacterMode=False
for index in xrange(len(speechSequence)):
item=speechSequence[index]
if isinstance(item,CharacterModeCommand):
inCharacterMode=item.state
if autoLanguageSwitching and isinstance(item,LangChangeCommand):
curLanguage=item.lang
if isinstance(item,basestring):
speechSequence[index]=processText(curLanguage,item,symbolLevel)
if not inCharacterMode:
speechSequence[index]+=CHUNK_SEPARATOR
getSynth().speak(speechSequence)
def speakSelectionMessage(message,text):
if len(text) < 512:
speakMessage(message % text)
else:
# Translators: This is spoken when the user has selected a large portion of text. Example output "1000 characters"
speakMessage(message % _("%d characters") % len(text))
def speakSelectionChange(oldInfo,newInfo,speakSelected=True,speakUnselected=True,generalize=False):
"""Speaks a change in selection, either selected or unselected text.
@param oldInfo: a TextInfo instance representing what the selection was before
@type oldInfo: L{textInfos.TextInfo}
@param newInfo: a TextInfo instance representing what the selection is now
@type newInfo: L{textInfos.TextInfo}
@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.
@type generalize: boolean
"""
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)
# Translators: This is spoken while the user is in the process of selecting something, For example: "hello selected"
speakSelectionMessage(_("%s selected"),text)
elif len(selectedTextList)>0:
text=newInfo.text
if len(text)==1:
text=characterProcessing.processSpeechSymbol(locale,text)
# Translators: This is spoken to indicate what has been selected. for example 'selected hello world'
speakSelectionMessage(_("selected %s"),text)
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)
elif len(unselectedTextList)>0:
if not newInfo.isCollapsed:
text=newInfo.text
if len(text)==1:
text=characterProcessing.processSpeechSymbol(locale,text)
# Translators: This is spoken to indicate when the previous selection was removed and a new selection was made. for example 'hello world selected instead'
speakSelectionMessage(_("%s selected instead"),text)
else:
# Translators: Reported when selection is removed.
speakMessage(_("selection removed"))
#: The number of typed characters for which to suppress speech.
_suppressSpeakTypedCharactersNumber = 0
#: The time at which suppressed typed characters were sent.
_suppressSpeakTypedCharactersTime = None
def _suppressSpeakTypedCharacters(number):
"""Suppress speaking of typed characters.
This should be used when sending a string of characters to the system
and those characters should not be spoken individually as if the user were typing them.
@param number: The number of characters to suppress.
@type number: int
"""
global _suppressSpeakTypedCharactersNumber, _suppressSpeakTypedCharactersTime
_suppressSpeakTypedCharactersNumber += number
_suppressSpeakTypedCharactersTime = time.time()
#: The character to use when masking characters in protected fields.
PROTECTED_CHAR = "*"
#: The first character which is not a Unicode control character.
#: This is used to test whether a character should be spoken as a typed character;
#: i.e. it should have a visual or spatial representation.
FIRST_NONCONTROL_CHAR = u" "
def speakTypedCharacters(ch):
global curWordChars
typingIsProtected=api.isTypingProtected()
if typingIsProtected:
realChar=PROTECTED_CHAR
else:
realChar=ch
if unicodedata.category(ch)[0] in "LMN":
curWordChars.append(realChar)
elif ch=="\b":
# Backspace, so remove the last character from our buffer.
del curWordChars[-1:]
elif ch==u'\u007f':
# delete character produced in some apps with control+backspace
return
elif len(curWordChars)>0:
typedWord="".join(curWordChars)
curWordChars=[]
if log.isEnabledFor(log.IO):
log.io("typed word: %s"%typedWord)
if config.conf["keyboard"]["speakTypedWords"] and not typingIsProtected:
speakText(typedWord)
global _suppressSpeakTypedCharactersNumber, _suppressSpeakTypedCharactersTime
if _suppressSpeakTypedCharactersNumber > 0:
# We primarily suppress based on character count and still have characters to suppress.
# However, we time out after a short while just in case.
suppress = time.time() - _suppressSpeakTypedCharactersTime <= 0.1
if suppress:
_suppressSpeakTypedCharactersNumber -= 1
else:
_suppressSpeakTypedCharactersNumber = 0
_suppressSpeakTypedCharactersTime = None
else:
suppress = False
if not suppress and config.conf["keyboard"]["speakTypedCharacters"] and ch >= FIRST_NONCONTROL_CHAR:
speakSpelling(realChar)
class SpeakTextInfoState(object):
"""Caches the state of speakTextInfo such as the current controlField stack, current formatfield and indentation."""
__slots__=[
'objRef',
'controlFieldStackCache',
'formatFieldAttributesCache',
'indentationCache',
]
def __init__(self,obj):
if isinstance(obj,SpeakTextInfoState):
oldState=obj
self.objRef=oldState.objRef
else:
self.objRef=weakref.ref(obj)
oldState=getattr(obj,'_speakTextInfoState',None)
self.controlFieldStackCache=list(oldState.controlFieldStackCache) if oldState else []
self.formatFieldAttributesCache=oldState.formatFieldAttributesCache if oldState else {}
self.indentationCache=oldState.indentationCache if oldState else ""
def updateObj(self):
obj=self.objRef()
if obj:
obj._speakTextInfoState=self.copy()
def copy(self):
return self.__class__(self)
def _speakTextInfo_addMath(speechSequence, info, field):
import mathPres
mathPres.ensureInit()
if not mathPres.speechProvider:
return
try:
speechSequence.extend(mathPres.speechProvider.getSpeechForMathMl(info.getMathMl(field)))
except (NotImplementedError, LookupError):
return
def speakTextInfo(info,useCache=True,formatConfig=None,unit=None,reason=controlTypes.REASON_QUERY,index=None,onlyInitialFields=False,suppressBlanks=False):
onlyCache=reason==controlTypes.REASON_ONLYCACHE
if isinstance(useCache,SpeakTextInfoState):
speakTextInfoState=useCache
elif useCache:
speakTextInfoState=SpeakTextInfoState(info.obj)
else:
speakTextInfoState=None
autoLanguageSwitching=config.conf['speech']['autoLanguageSwitching']
extraDetail=unit in (textInfos.UNIT_CHARACTER,textInfos.UNIT_WORD)
if not formatConfig:
formatConfig=config.conf["documentFormatting"]
if extraDetail:
formatConfig=formatConfig.copy()
formatConfig['extraDetail']=True
reportIndentation=unit==textInfos.UNIT_LINE and ( formatConfig["reportLineIndentation"] or formatConfig["reportLineIndentationWithTones"])
speechSequence=[]
#Fetch the last controlFieldStack, or make a blank one
controlFieldStackCache=speakTextInfoState.controlFieldStackCache if speakTextInfoState else []
formatFieldAttributesCache=speakTextInfoState.formatFieldAttributesCache if speakTextInfoState else {}
textWithFields=info.getTextWithFields(formatConfig)
# We don't care about node bounds, especially when comparing fields.
# Remove them.
for command in textWithFields:
if not isinstance(command,textInfos.FieldCommand):
continue
field=command.field
if not field:
continue
try:
del field["_startOfNode"]
except KeyError:
pass
try:
del field["_endOfNode"]
except KeyError:
pass
#Make a new controlFieldStack and formatField from the textInfo's initialFields
newControlFieldStack=[]
newFormatField=textInfos.FormatField()
initialFields=[]
for field in textWithFields:
if isinstance(field,textInfos.FieldCommand) and field.command in ("controlStart","formatChange"):
initialFields.append(field.field)
else:
break
if len(initialFields)>0:
del textWithFields[0:len(initialFields)]
endFieldCount=0
for field in reversed(textWithFields):
if isinstance(field,textInfos.FieldCommand) and field.command=="controlEnd":
endFieldCount+=1
else:
break
if endFieldCount>0:
del textWithFields[0-endFieldCount:]
for field in initialFields:
if isinstance(field,textInfos.ControlField):
newControlFieldStack.append(field)
elif isinstance(field,textInfos.FormatField):
newFormatField.update(field)
else:
raise ValueError("unknown field: %s"%field)
#Calculate how many fields in the old and new controlFieldStacks are the same
commonFieldCount=0
for count in xrange(min(len(newControlFieldStack),len(controlFieldStackCache))):
# #2199: When comparing controlFields try using uniqueID if it exists before resorting to compairing the entire dictionary
oldUniqueID=controlFieldStackCache[count].get('uniqueID')
newUniqueID=newControlFieldStack[count].get('uniqueID')
if ((oldUniqueID is not None or newUniqueID is not None) and newUniqueID==oldUniqueID) or (newControlFieldStack[count]==controlFieldStackCache[count]):
commonFieldCount+=1
else:
break
# #2591: Only if the reason is not focus, Speak the exit of any controlFields not in the new stack.
# We don't do this for focus because hearing "out of list", etc. isn't useful when tabbing or using quick navigation and makes navigation less efficient.
if reason!=controlTypes.REASON_FOCUS:
endingBlock=False
for count in reversed(xrange(commonFieldCount,len(controlFieldStackCache))):
text=info.getControlFieldSpeech(controlFieldStackCache[count],controlFieldStackCache[0:count],"end_removedFromControlFieldStack",formatConfig,extraDetail,reason=reason)
if text:
speechSequence.append(text)
if not endingBlock and reason==controlTypes.REASON_SAYALL:
endingBlock=bool(int(controlFieldStackCache[count].get('isBlock',0)))
if endingBlock:
speechSequence.append(SpeakWithoutPausesBreakCommand())
# The TextInfo should be considered blank if we are only exiting fields (i.e. we aren't entering any new fields and there is no text).
isTextBlank=True
# Even when there's no speakable text, we still need to notify the synth of the index.
if index is not None:
speechSequence.append(IndexCommand(index))
#Get speech text for any fields that are in both controlFieldStacks, if extra detail is not requested
if not extraDetail:
for count in xrange(commonFieldCount):
field=newControlFieldStack[count]
text=info.getControlFieldSpeech(field,newControlFieldStack[0:count],"start_inControlFieldStack",formatConfig,extraDetail,reason=reason)
if text:
speechSequence.append(text)
isTextBlank=False
if field.get("role")==controlTypes.ROLE_MATH:
isTextBlank=False
_speakTextInfo_addMath(speechSequence,info,field)
#Get speech text for any fields in the new controlFieldStack that are not in the old controlFieldStack
for count in xrange(commonFieldCount,len(newControlFieldStack)):
field=newControlFieldStack[count]
text=info.getControlFieldSpeech(field,newControlFieldStack[0:count],"start_addedToControlFieldStack",formatConfig,extraDetail,reason=reason)
if text:
speechSequence.append(text)
isTextBlank=False
if field.get("role")==controlTypes.ROLE_MATH:
isTextBlank=False
_speakTextInfo_addMath(speechSequence,info,field)
commonFieldCount+=1
#Fetch the text for format field attributes that have changed between what was previously cached, and this textInfo's initialFormatField.
text=info.getFormatFieldSpeech(newFormatField,formatFieldAttributesCache,formatConfig,reason=reason,unit=unit,extraDetail=extraDetail,initialFormat=True)
if text:
speechSequence.append(text)
if autoLanguageSwitching:
language=newFormatField.get('language')
speechSequence.append(LangChangeCommand(language))
lastLanguage=language
if onlyInitialFields or (unit in (textInfos.UNIT_CHARACTER,textInfos.UNIT_WORD) and len(textWithFields)>0 and len(textWithFields[0])==1 and all((isinstance(x,textInfos.FieldCommand) and x.command=="controlEnd") for x in itertools.islice(textWithFields,1,None) )):
if not onlyCache:
if onlyInitialFields or any(isinstance(x,basestring) for x in speechSequence):
speak(speechSequence)
if not onlyInitialFields:
speakSpelling(textWithFields[0],locale=language if autoLanguageSwitching else None)
if useCache:
speakTextInfoState.controlFieldStackCache=newControlFieldStack
speakTextInfoState.formatFieldAttributesCache=formatFieldAttributesCache
if not isinstance(useCache,SpeakTextInfoState):
speakTextInfoState.updateObj()
return
#Move through the field commands, getting speech text for all controlStarts, controlEnds and formatChange commands
#But also keep newControlFieldStack up to date as we will need it for the ends
# Add any text to a separate list, as it must be handled differently.
#Also make sure that LangChangeCommand objects are added before any controlField or formatField speech
relativeSpeechSequence=[]
inTextChunk=False
allIndentation=""
indentationDone=False
for command in textWithFields:
if isinstance(command,basestring):
if reportIndentation and not indentationDone:
indentation,command=splitTextIndentation(command)
# Combine all indentation into one string for later processing.
allIndentation+=indentation
if command:
# There was content after the indentation, so there is no more indentation.
indentationDone=True
if command:
if inTextChunk:
relativeSpeechSequence[-1]+=command
else:
relativeSpeechSequence.append(command)
inTextChunk=True
elif isinstance(command,textInfos.FieldCommand):
newLanguage=None
if command.command=="controlStart":
# Control fields always start a new chunk, even if they have no field text.
inTextChunk=False
fieldText=info.getControlFieldSpeech(command.field,newControlFieldStack,"start_relative",formatConfig,extraDetail,reason=reason)
newControlFieldStack.append(command.field)
elif command.command=="controlEnd":
# Control fields always start a new chunk, even if they have no field text.
inTextChunk=False
fieldText=info.getControlFieldSpeech(newControlFieldStack[-1],newControlFieldStack[0:-1],"end_relative",formatConfig,extraDetail,reason=reason)
del newControlFieldStack[-1]
if commonFieldCount>len(newControlFieldStack):
commonFieldCount=len(newControlFieldStack)
elif command.command=="formatChange":
fieldText=info.getFormatFieldSpeech(command.field,formatFieldAttributesCache,formatConfig,reason=reason,unit=unit,extraDetail=extraDetail)
if fieldText:
inTextChunk=False
if autoLanguageSwitching:
newLanguage=command.field.get('language')
if lastLanguage!=newLanguage:
# The language has changed, so this starts a new text chunk.
inTextChunk=False
if not inTextChunk:
if fieldText:
if autoLanguageSwitching and lastLanguage is not None:
# Fields must be spoken in the default language.
relativeSpeechSequence.append(LangChangeCommand(None))
lastLanguage=None
relativeSpeechSequence.append(fieldText)
if command.command=="controlStart" and command.field.get("role")==controlTypes.ROLE_MATH:
_speakTextInfo_addMath(relativeSpeechSequence,info,command.field)
if autoLanguageSwitching and newLanguage!=lastLanguage:
relativeSpeechSequence.append(LangChangeCommand(newLanguage))
lastLanguage=newLanguage
if reportIndentation and speakTextInfoState and allIndentation!=speakTextInfoState.indentationCache:
indentationSpeech=getIndentationSpeech(allIndentation, formatConfig)
if autoLanguageSwitching and speechSequence[-1].lang is not None:
# Indentation must be spoken in the default language,
# but the initial format field specified a different language.
# Insert the indentation before the LangChangeCommand.
speechSequence.insert(-1, indentationSpeech)
else:
speechSequence.append(indentationSpeech)
if speakTextInfoState: speakTextInfoState.indentationCache=allIndentation
# Don't add this text if it is blank.
relativeBlank=True
for x in relativeSpeechSequence:
if isinstance(x,basestring) and not isBlank(x):
relativeBlank=False
break
if not relativeBlank:
speechSequence.extend(relativeSpeechSequence)
isTextBlank=False
#Finally get speech text for any fields left in new controlFieldStack that are common with the old controlFieldStack (for closing), if extra detail is not requested
if autoLanguageSwitching and lastLanguage is not None:
speechSequence.append(LangChangeCommand(None))
lastLanguage=None
if not extraDetail:
for count in reversed(xrange(min(len(newControlFieldStack),commonFieldCount))):
text=info.getControlFieldSpeech(newControlFieldStack[count],newControlFieldStack[0:count],"end_inControlFieldStack",formatConfig,extraDetail,reason=reason)
if text:
speechSequence.append(text)
isTextBlank=False
# If there is nothing that should cause the TextInfo to be considered non-blank, blank should be reported, unless we are doing a say all.
if not suppressBlanks and reason != controlTypes.REASON_SAYALL and isTextBlank:
# Translators: This is spoken when the line is considered blank.
speechSequence.append(_("blank"))
#Cache a copy of the new controlFieldStack for future use
if useCache:
speakTextInfoState.controlFieldStackCache=list(newControlFieldStack)
speakTextInfoState.formatFieldAttributesCache=formatFieldAttributesCache
if not isinstance(useCache,SpeakTextInfoState):
speakTextInfoState.updateObj()
if not onlyCache and speechSequence:
if reason==controlTypes.REASON_SAYALL:
speakWithoutPauses(speechSequence)
else:
speak(speechSequence)
def getSpeechTextForProperties(reason=controlTypes.REASON_QUERY,**propertyValues):
global oldTreeLevel, oldTableID, oldRowNumber, oldRowSpan, oldColumnNumber, oldColumnSpan
textList=[]
name=propertyValues.get('name')
if name:
textList.append(name)
if 'role' in propertyValues:
role=propertyValues['role']
speakRole=True
elif '_role' in propertyValues:
speakRole=False
role=propertyValues['_role']
else:
speakRole=False
role=controlTypes.ROLE_UNKNOWN
value=propertyValues.get('value') if role not in controlTypes.silentValuesForRoles else None
cellCoordsText=propertyValues.get('cellCoordsText')
rowNumber=propertyValues.get('rowNumber')