def event_valueChange(self): pbConf=config.conf["presentation"]["progressBarUpdates"] states=self.states if pbConf["progressBarOutputMode"]=="off" or controlTypes.STATE_INVISIBLE in states or controlTypes.STATE_OFFSCREEN in states: return super(ProgressBar,self).event_valueChange() val=self.value try: percentage = min(max(0.0, float(val.strip("%\0"))), 100.0) except (AttributeError, ValueError): log.debugWarning("Invalid value: %r" % val) return super(ProgressBar, self).event_valueChange() braille.handler.handleUpdate(self) if not pbConf["reportBackgroundProgressBars"] and not self.isInForeground: return try: left,top,width,height=self.location except: left=top=width=height=0 x=left+(width/2) y=top+(height/2) lastBeepProgressValue=self.progressValueCache.get("beep,%d,%d"%(x,y),None) if pbConf["progressBarOutputMode"] in ("beep","both") and (lastBeepProgressValue is None or abs(percentage-lastBeepProgressValue)>=pbConf["beepPercentageInterval"]): tones.beep(pbConf["beepMinHZ"]*2**(percentage/25.0),40) self.progressValueCache["beep,%d,%d"%(x,y)]=percentage lastSpeechProgressValue=self.progressValueCache.get("speech,%d,%d"%(x,y),None) if pbConf["progressBarOutputMode"] in ("speak","both") and (lastSpeechProgressValue is None or abs(percentage-lastSpeechProgressValue)>=pbConf["speechPercentageInterval"]): queueHandler.queueFunction(queueHandler.eventQueue,speech.speakMessage,_("%d percent")%percentage) self.progressValueCache["speech,%d,%d"%(x,y)]=percentage
def script_prevColumn(self, gesture): self.columnHeaders = self.parent.children[-1] if self.appModule.SPLColNumber <= 0: tones.beep(2000, 100) else: self.appModule.SPLColNumber -=1 self.announceColumnContent(self.appModule.SPLColNumber)
def callback(stationsListNVDAObject): from .rs_translations import getPlayingTranslation maxStationsToCheck = _addonConfigManager.getMaxStationsToCheck() stationCount = maxStationsToCheck while stationCount: stationCount -= 1 station = self.startStation(stationsListNVDAObject) maxDelayForConnexion = _addonConfigManager.getMaxDelayForConnexion( ) while maxDelayForConnexion: maxDelayForConnexion -= 1 time.sleep(1.0) infos = getPlayInfos() if getPlayingTranslation() in infos: # station is playing log.warning("playing: %s" % station.name) eventHandler.queueEvent("gainFocus", station) return # it's a bad station log.warning("no connexion: %s" % station.name) _addonConfigManager.recordBadStation(station.name) self.badStations.append(station.name) if stationCount == 0: # Translators: message to user there is none station with connexion. queueHandler.queueFunction( queueHandler.eventQueue, ui.message, # Translators: message to user _("None of the %s stations selected randomly could be connected" ) % maxStationsToCheck) eventHandler.queueEvent("gainFocus", station) else: if maxStationsToCheck - stationCount: tones.beep(500, 50)
def done(self): self.timer.Stop() pbConf = config.conf["presentation"]["progressBarUpdates"] if pbConf["progressBarOutputMode"] in ("beep", "both") and (pbConf["reportBackgroundProgressBars"] or self.IsActive()): tones.beep(1760, 40) self.Hide() self.Destroy()
def _fixConnection(hBrl, devName, port, keyCallbackInst, statusCallbackInst): global fConnection, isUnknownEquipment log.info("scanning port %s" % port) if port[:3] == 'COM': _port = int(port[3:]) - 1 else: return False, None SPEED = 3 # 9600bps fConnection = False isUnknownEquipment = False ret = hBrl.bmStart(devName, _port, SPEED, statusCallbackInst) log.info("bmStart(%s) returns %d" % (port, ret)) if ret: for loop in xrange(15): if fConnection: ret = hBrl.bmStartDisplayMode2(KGS_DISPMODE, keyCallbackInst) log.info("bmStartDisplayMode2() returns %d" % ret) break elif isUnknownEquipment: log.info("isUnknownEquipment") break time.sleep(0.5) tones.beep(400 + (loop * 20), 20) processEvents() if not fConnection: bmDisConnect(hBrl, _port) port = None tones.beep(200, 100) log.info("connection:%d port:%d" % (fConnection, _port)) return fConnection, port
def nvdaKgsStatusChangedProc(nStatus, nDispSize): global fConnection, numCells, isUnknownEquipment if nStatus == BMDRVS.DISCONNECTED: fConnection = False tones.beep(1000, 300) log.info("disconnect") elif nStatus == BMDRVS.CONNECTED: numCells = nDispSize fConnection = True tones.beep(1000, 30) log.info("display size:%d" % nDispSize) elif nStatus == BMDRVS.DRIVER_CANNOT_OPEN: fConnection = False log.info("driver cannot open") elif nStatus == BMDRVS.INVALID_DRIVER: fConnection = False log.info("invalid driver") elif nStatus == BMDRVS.OPEN_PORT_FAILED: #fConnection = False log.info("open port failed") elif nStatus == BMDRVS.CREATE_THREAD_FAILED: fConnection = False log.info("create thread failed") elif nStatus == BMDRVS.CHECKING_EQUIPMENT: log.info("checking equipment") elif nStatus == BMDRVS.UNKNOWN_EQUIPMENT: log.info("unknown equipment") isUnknownEquipment = True elif nStatus == BMDRVS.PORT_RELEASED: log.info("port released") elif nStatus == BMDRVS.MAX: log.info("max") else: log.info("status changed to %d" % nStatus)
def beep_start(self, thrc=False): if thrc and not self.isWorking: return False self.isWorking = True tones.beep(500, 100) self.bp = Timer(1, self.beep_start, [True]) self.bp.start() return True
def script_skipToCategory(self, gesture): self.cancelSpeech = False categories = (self.categories[self.catIndex + 1:] if self.catIndex + 1 < len(self.categories) else []) + (self.categories[:self.catIndex]) try: self.catIndex = self.categories.index( filter(lambda i: i[0].lower() == gesture.mainKeyName, categories).__next__()) - 1 # Compatibility with Python 2 except AttributeError: try: self.catIndex = self.categories.index( filter(lambda i: i[0].lower() == gesture.mainKeyName, categories)[0]) - 1 self.script_nextCategory(None) except IndexError: if self.categories[ self.catIndex][0].lower() == gesture.mainKeyName: ui.message(self.categories[self.catIndex]) else: tones.beep(200, 30) # End of compatibility with Python 2 except StopIteration: if self.categories[ self.catIndex][0].lower() == gesture.mainKeyName: ui.message(self.categories[self.catIndex]) else: tones.beep(200, 30) else: self.script_nextCategory(None)
def playAudioCoordinates(x, y, screenWidth, screenHeight, screenMinPos, detectBrightness=True,blurFactor=0): """ play audio coordinates: - left to right adjusting the volume between left and right speakers - top to bottom adjusts the pitch of the sound - brightness adjusts the volume of the sound Coordinates (x, y) are absolute, and can be negative. """ # make relative to (0,0) and positive x = x - screenMinPos.x y = y - screenMinPos.y minPitch=config.conf['mouse']['audioCoordinates_minPitch'] maxPitch=config.conf['mouse']['audioCoordinates_maxPitch'] curPitch=minPitch+((maxPitch-minPitch)*((screenHeight-y)/float(screenHeight))) if detectBrightness: startX=min(max(x-blurFactor,0),screenWidth)+screenMinPos.x startY=min(max(y-blurFactor,0),screenHeight)+screenMinPos.y width=min(blurFactor+1,screenWidth) height=min(blurFactor+1,screenHeight) grey=screenBitmap.rgbPixelBrightness(scrBmpObj.captureImage( startX, startY, width, height)[0][0]) brightness=grey/255.0 minBrightness=config.conf['mouse']['audioCoordinates_minVolume'] maxBrightness=config.conf['mouse']['audioCoordinates_maxVolume'] brightness=(brightness*(maxBrightness-minBrightness))+minBrightness else: brightness=config.conf['mouse']['audioCoordinates_maxVolume'] leftVolume=int((85*((screenWidth-float(x))/screenWidth))*brightness) rightVolume=int((85*(float(x)/screenWidth))*brightness) tones.beep(curPitch,40,left=leftVolume,right=rightVolume)
def _speakSpellingGen(text,locale,useCharacterDescriptions): textLength=len(text) synth=getSynth() synthConfig=config.conf["speech"][synth.name] for count,char in enumerate(text): uppercase=char.isupper() charDesc=None if useCharacterDescriptions: from characterProcessing import getCharacterDescription charDesc=getCharacterDescription(locale,char.lower()) if charDesc: char=charDesc else: char=processSymbol(char) if uppercase and synthConfig["sayCapForCapitals"]: char=_("cap %s")%char if uppercase and synth.isSupported("pitch") and synthConfig["raisePitchForCapitals"]: oldPitch=synthConfig["pitch"] synth.pitch=max(0,min(oldPitch+synthConfig["capPitchChange"],100)) index=count+1 log.io("Speaking character %r"%char) if len(char) == 1 and synthConfig["useSpellingFunctionality"]: synth.speakCharacter(char,index=index) else: synth.speakText(char,index=index) if uppercase and synth.isSupported("pitch") and synthConfig["raisePitchForCapitals"]: synth.pitch=oldPitch while textLength>1 and (isPaused or getLastSpeechIndex()!=index): yield yield if uppercase and synthConfig["beepForCapitals"]: tones.beep(2000,50)
def script_clockLayerCommands(self, gesture): if self.clockLayerModeActive: self.script_error(gesture) return self.bindGestures(self.__clockLayerGestures) self.clockLayerModeActive=True tones.beep(100, 10)
def speakSpelling(text,locale=None,useCharacterDescriptions=False): global beenCanceled, _speakSpellingGenID 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 from languageHandler import getLanguage locale=getLanguage() if not isinstance(text,basestring) or len(text)==0: return getSynth().speakText(processSymbol("")) if not text.isspace(): text=text.rstrip() gen=_speakSpellingGen(text,locale,useCharacterDescriptions) try: # Speak the first character before this function returns. next(gen) except StopIteration: return _speakSpellingGenID=queueHandler.registerGeneratorObject(gen)
def script_nextColumn(self, gesture): self.columnHeaders = self.parent.children[-1] if (self.appModule.SPLColNumber+1) == self.columnHeaders.childCount: tones.beep(2000, 100) else: self.appModule.SPLColNumber +=1 self.announceColumnContent(self.appModule.SPLColNumber)
def handle_client_connected(self, client=None, **kwargs): self.patcher.patch() if not self.patch_callbacks_added: self.add_patch_callbacks() self.patch_callbacks_added = True self.send_braille_info() tones.beep(1000, 300)
def find(self, text): """Find a window with the supplied text in its title. If the text isn't found in any title, search the text of consoles.""" consoles = set() text = text.lower() for c in api.getDesktopObject().children: name = c.name if name is None: continue if text in name.lower(): focus(c.windowHandle) return elif c.windowClassName == u'ConsoleWindowClass': consoles.add(c) #We didn't find the search text in the title, start searching consoles current_console = winConsoleHandler.consoleObject # If our current console is the one with the text in it, presumably we want another one, and if one isn't found, we'll refocus anyway if current_console is not None: consoles.remove(current_console) for console in consoles: #We assume this can't fail console_text = get_console_text(console) if text in console_text.lower(): focus(console.windowHandle) return else: #No consoles found if current_console: winConsoleHandler.connectConsole(current_console) if current_console == api.getFocusObject(): current_console.startMonitoring() #Keep echoing if we didn't switch tones.beep(300, 150)
def script_clockLayerCommands(self, gesture): if self.clockLayerModeActive: self.script_error(gesture) return for gesture in self._clockLayerGestures: self.bindGesture ("kb:%s" % gesture[0], gesture[1].__name__[7:]) self.clockLayerModeActive=True tones.beep(100, 10)
def event_typedCharacter(self, ch): speech.speakTypedCharacters(ch) import winUser if config.conf["keyboard"][ "beepForLowercaseWithCapslock"] and ch.islower( ) and winUser.getKeyState(winUser.VK_CAPITAL) & 1: import tones tones.beep(3000, 40)
def script_toggleEasyNavigation(self, gesture): if self.flagExplorationMode: if self.flagEasyNavigation: tones.beep(300, 100) self.disableEasyNavigation() else: tones.beep(1200, 100) self.enableEasyNavigation()
def script_controlPaneToForeground(self, gesture): obj = api.getForegroundObject() if hasattr(obj, "playbackControls"): api.setFocusObject(obj) obj.moveToItem(self.tpItemIndex) tones.beep(1200, 30) else: tones.beep(200, 30)
def threadMonitor(self, thread): i = 0 while thread.isAlive(): sleep(0.1) i += 1 if i == 10: beep(250, 90) i = 0
def script_nextString(self, gesture): global history_pos history_pos -= 1 if history_pos < 0: tones.beep(200, 100) history_pos += 1 oldSpeak(self._history[history_pos])
def script_prevString(self, gesture): global history_pos history_pos += 1 if history_pos > len(self._history) - 1: tones.beep(200, 100) history_pos -= 1 oldSpeak(self._history[history_pos])
def event_typedCharacter(self, ch): super(EditWindow, self).event_typedCharacter(ch) if not config.conf["notepadPp"]["lineLengthIndicator"]: return textInfo = self.makeTextInfo(textInfos.POSITION_CARET) textInfo.expand(textInfos.UNIT_LINE) if textInfo.bookmark.endOffset - textInfo.bookmark.startOffset >= config.conf["notepadPp"]["maxLineLength"]: tones.beep(500, 50)
def waitAfterDisconnect(): for loop in xrange(10): time.sleep(0.5) try: tones.beep(450 - (loop * 20), 20) except: pass processEvents()
def run(): parent = api.getFocusObject() vw = A8MInteraction(parent=parent) vw.set(data=globalVars.mathcontent, name="") try: vw.setFocus() except: tones.beep(100, 100)
def command(self, id_): try: kwargs = latexCommand[id_] command(**kwargs) except: tones.beep(100, 100) return eventHandler.executeEvent("gainFocus", self.parent)
def script_copyLast(self, gesture): text = self.getSequenceText(self._history[history_pos]) if config.conf['speechHistory']['trimWhitespaceFromStart']: text = text.lstrip() if config.conf['speechHistory']['trimWhitespaceFromEnd']: text = text.rstrip() if api.copyToClip(text): tones.beep(1500, 120)
def _showFromSlot(self, slotNumber): windowToShow = self.hiddenWindowsList.pop(slotNumber) self.hiddenWindowsList.save() if windowToShow.isAlive: windowToShow.show() tones.beep(180, 80) else: raise RuntimeError("This window no longer exists!")
def run(self): global wdTime, wdAsleep, wdTimeout time.sleep(5) while not self.stopSignal: if getConfig("busyBeep"): while not wdAsleep and (time.time() - wdTime) > wdTimeout: tones.beep(150, 10, left=25, right=25) #time.sleep(0.01) time.sleep(0.1)
def script_toggleSpeakPixels(self, gesture): if self.sayPixel == 1: self.sayPixel = 0 ui.message(_('report pixels off')) tones.beep(500, 200) else: self.sayPixel = 1 ui.message(_('report pixels on')) tones.beep(1000, 200)
def stopRemanence(self, beep=False): if self.remanenceActivation is False: return self.lastModifiers = [] if self.isRemanenceStarted(): self.remanenceTimer.Stop() self.remanenceTimer = None if beep and toggleBeepAtRemanenceEndAdvancedOption(False): tones.beep(3000, 20)
def script_ITLayer(self, gesture): # A run-time binding will occur from which we can perform various layered translation commands. # First, check if a second press of the script was done. if self.toggling: self.script_error(gesture) return self.bindGestures(self.__ITGestures) self.toggling = True tones.beep(100, 10)
def toggle_auto_scroll(self): if self._auto_scroll: self._auto_scroll.stop() self._auto_scroll = None tones.beep(100, 100) else: self._auto_scroll = self.AutoScroll() self._auto_scroll.start() tones.beep(300, 100)
def script_copyLast(self, gesture): import scriptHandler repeat = scriptHandler.getLastScriptRepeatCount() if repeat > 0: if api.copyToClip(history[history_pos].strip()): tones.beep(1500, 120) else: if api.copyToClip(history[history_pos]): tones.beep(1000, 120)
def playTone(self, pitch, length, stereoPosition='center'): if not config.conf['profilesSwitcher']['shouldPlaySound']: return if stereoPosition == 'left': stereoPosition = (50, 0) elif stereoPosition == 'right': stereoPosition = (0, 50) else: stereoPosition = (50, 50) beep(pitch, length, stereoPosition[0], stereoPosition[1])
def script_reportLineOverflow(self, gesture): if self.appModule.isAutocomplete: gesture.send() return self.script_caret_moveByLine(gesture) if not config.conf["notepadPp"]["lineLengthIndicator"]: return info = self.makeTextInfo(textInfos.POSITION_CARET) info.expand(textInfos.UNIT_LINE) if len(info.text.strip('\r\n\t ')) > config.conf["notepadPp"]["maxLineLength"]: tones.beep(500, 50)
def speakingHook(d): percentage=0 frequency=100 if d['status'] == 'downloading': percentage=int((float(d['downloaded_bytes'])/d['total_bytes'])*100) frequency=100+percentage tones.beep(frequency, 50) elif d['status'] == 'finished': ui.message(_("Download complete. Converting video.")) elif d['status'] == 'error': ui.message(_("Download error."))
def event_UIA_notification(self, obj, nextHandler, notificationKind=None, notificationProcessing=None, displayString=None, activityId=None): # Introduced in Version 1709, to be treated as a notification event. self.uiaDebugLogging(obj, "notification") if isinstance(obj, UIA) and globalVars.appArgs.debugLogging: log.debug("W10: UIA notification: sender: %s, notification kind: %s, notification processing: %s, display string: %s, activity ID: %s"%(obj.UIAElement,notificationKind,notificationProcessing,displayString,activityId)) # Play a debug tone if and only if notifications come from somewhere other than the active app. if obj.appModule != api.getFocusObject().appModule: import tones # For debugging purposes. tones.beep(500, 100) nextHandler()
def event_typedCharacter(self,ch): if config.conf["documentFormatting"]["reportSpellingErrors"] and config.conf["keyboard"]["alertForSpellingErrors"] and ( # Not alpha, apostrophe or control. ch.isspace() or (ch >= u" " and ch not in u"'\x7f" and not ch.isalpha()) ): # Reporting of spelling errors is enabled and this character ends a word. self._reportErrorInPreviousWord() speech.speakTypedCharacters(ch) import winUser if config.conf["keyboard"]["beepForLowercaseWithCapslock"] and ch.islower() and winUser.getKeyState(winUser.VK_CAPITAL)&1: import tones tones.beep(3000,40)
def event_typedCharacter(self, ch): speech.speakTypedCharacters(ch) import winUser if ( config.conf["keyboard"]["beepForLowercaseWithCapslock"] and ch.islower() and winUser.getKeyState(winUser.VK_CAPITAL) & 1 ): import tones tones.beep(3000, 40)
def event_caret(self): super(EditWindow, self).event_caret() if not config.conf["notepadPp"]["lineLengthIndicator"]: return caretInfo = self.makeTextInfo(textInfos.POSITION_CARET) lineStartInfo = self.makeTextInfo(textInfos.POSITION_CARET).copy() caretInfo.expand(textInfos.UNIT_CHARACTER) lineStartInfo.expand(textInfos.UNIT_LINE) caretPosition = caretInfo.bookmark.startOffset -lineStartInfo.bookmark.startOffset #Is it not a blank line, and are we further in the line than the marker position? if caretPosition > config.conf["notepadPp"]["maxLineLength"] -1 and caretInfo.text not in ['\r', '\n']: tones.beep(500, 50)
def resumeTouchInteraction(self, profileSwitch=False): if not touchHandler.handler: try: self.etsDebugOutput("etouch: attempting to enable touch handler") touchHandler.initialize() if not profileSwitch: ui.message("Touch passthrough off") import tones tones.beep(380, 100) except: if not profileSwitch: ui.message("Touch is not supported") finally: self.touchPassthroughTimer = None
def beep_sequence(*sequence): """ Play a simple synchronous monophonic beep sequence A beep sequence is an iterable containing one of two kinds of elements. An element consisting of a tuple of two items is interpreted as a frequency and duration. Note, this function plays beeps synchronously, unlike tones.beep A single integer is assumed to be a delay in ms. """ for element in sequence: if not isinstance(element, collections.Sequence): time.sleep(element / 1000) else: tone, duration = element time.sleep(duration / 1000) tones.beep(tone, duration)
def event_becomeNavigatorObject(self): l,t,w,h=self.location x = l+(w/2) y = t+(h/2) screenWidth, screenHeight = api.getDesktopObject().location[2:] if x <= screenWidth or y <= screenHeight: minPitch=config.conf['mouse']['audioCoordinates_minPitch'] maxPitch=config.conf['mouse']['audioCoordinates_maxPitch'] curPitch=minPitch+((maxPitch-minPitch)*((screenHeight-y)/float(screenHeight))) brightness=config.conf['mouse']['audioCoordinates_maxVolume'] leftVolume=int((85*((screenWidth-float(x))/screenWidth))*brightness) rightVolume=int((85*(float(x)/screenWidth))*brightness) tones.beep(curPitch,40,left=leftVolume,right=rightVolume) super(MapLocation,self).event_becomeNavigatorObject()
def Pulse(self): super(IndeterminateProgressDialog, self).Pulse() # We want progress to be spoken on the first pulse and every 10 pulses thereafter. # Therefore, cycle from 0 to 9 inclusive. self._speechCounter = (self._speechCounter + 1) % 10 pbConf = config.conf["presentation"]["progressBarUpdates"] if pbConf["progressBarOutputMode"] == "off": return if not pbConf["reportBackgroundProgressBars"] and not self.IsActive(): return if pbConf["progressBarOutputMode"] in ("beep", "both"): tones.beep(440, 40) if pbConf["progressBarOutputMode"] in ("speak", "both") and self._speechCounter == 0: # Translators: Announced periodically to indicate progress for an indeterminate progress bar. speech.speakMessage(_("Please wait"))
def _reportIndentChange(self, text): """ Reports the current level change as a tone. The first twenty levels are given distinct stereo positions, and otherwise, no tone will play. @var text: The text to report indents for. Only pass a homoginous set of tabs or spaces, because the length is calculated assuming each character is one indent unit. @type text: string @returns: Indent level. """ level = len(text) #assume 1 indent unit per character. if level > MAX_LEVEL: return level volume = speech.getSynth().volume note = 128*2**(level/MAX_LEVEL*3) #MAX_LEVEL*3 gives us 3 octaves of whole tones. #calculate stereo values. NVDA expects values between 0 and 100 for stereo volume for each channel. right = int((volume/(MAX_LEVEL-1))*level) left = volume-right tones.beep(note, 80, left=left, right=right) return level
def script_toggleTouchPassthrough(self, gesture): # First, check if timer is running, and if so, enable touch interaction (manual toggle). if ((not touchHandler.handler and config.conf["touch"]["manualPassthroughToggle"]) or (self.touchPassthroughTimer and self.touchPassthroughTimer.IsRunning())): self.etsDebugOutput("etouch: manually enabling touch handler") self.resumeTouchInteraction() return if touchHandler.handler: self.etsDebugOutput("etouch: disabling touch handler") touchHandler.terminate() ui.message("Touch passthrough on") import tones tones.beep(760, 100) if not config.conf["touch"]["manualPassthroughToggle"]: self.touchPassthroughTimer = wx.PyTimer(self.resumeTouchInteraction) self.touchPassthroughTimer.Start(config.conf["touch"]["commandPassthroughDuration"]*1000, True)
def _reportIndentChange(self, level): """ Reports the current level change as a tone. The first twenty levels are given distinct stereo positions, and otherwise, no tone will play. @var level: The level to report indents for. Only pass a homoginous set of tabs or spaces, because the length is calculated assuming each character is one indent unit. @type level: int """ volume = speech.getSynth().volume if config.conf["indentone"]["toneType"] & PITCH: note = 128*2**(level/MAX_LEVEL*3) #MAX_LEVEL*3 gives us 3 octaves of whole tones. else: note = 256 #calculate stereo values. NVDA expects values between 0 and 100 for stereo volume for each channel. if config.conf["indentone"]["toneType"] & STEREO: right = int((volume/(MAX_LEVEL-1))*level) left = volume-right else: left = right = 50 tones.beep(note, 80, left=left, right=right) return
def run(self): global playing tone=0 for p in self.toneData: if not playing: break try: tone+=1 tones.beep(int(p[0]), int(p[1])) time.sleep(float(p[2])) except ValueError: # Translators: This message will be displayed if there's an error with tone data playback. wx.CallAfter(gui.messageBox, _("""Woops! I found an error at tone number {toneNumber} while playing tone data file, some values are missing or incorrect. Please correct any errors and try again. Bad syntax: {syntax}""".format(toneNumber=tone, syntax=':'.join(p))), _("Error"), style=wx.OK | wx.CENTER|wx.ICON_ERROR) tone=len(self.toneData) break if tone>=len(self.toneData): playing=False
def playAudioCoordinates(x, y, screenWidth, screenHeight, detectBrightness=True,blurFactor=0): minPitch=config.conf['mouse']['audioCoordinates_minPitch'] maxPitch=config.conf['mouse']['audioCoordinates_maxPitch'] curPitch=minPitch+((maxPitch-minPitch)*((screenHeight-y)/float(screenHeight))) if detectBrightness: startX=min(max(x-blurFactor,0),screenWidth) width=min((x+blurFactor+1)-startX,screenWidth) startY=min(max(y-blurFactor,0),screenHeight) height=min((y+blurFactor+1)-startY,screenHeight) grey=screenBitmap.rgbPixelBrightness(scrBmpObj.captureImage(startX,startY,width,height)[0][0]) brightness=grey/255.0 minBrightness=config.conf['mouse']['audioCoordinates_minVolume'] maxBrightness=config.conf['mouse']['audioCoordinates_maxVolume'] brightness=(brightness*(maxBrightness-minBrightness))+minBrightness else: brightness=config.conf['mouse']['audioCoordinates_maxVolume'] leftVolume=int((85*((screenWidth-float(x))/screenWidth))*brightness) rightVolume=int((85*(float(x)/screenWidth))*brightness) tones.beep(curPitch,40,left=leftVolume,right=rightVolume)
def event_nameChange(self): #a nameChange event is fired by breakpoint UI control when the caret reaches a line with breakpoint, so, we rely on this to announce breakpoints global caretMovedToDifferentLine if not caretMovedToDifferentLine: #a nameChange event can be fired multiple times when moving by character within the same line, so, return if we already announced the break point for the current line return caretMovedToDifferentLine = False currentLineNum = _getCurLineNumber() BPLineNum = self._getLineNumber() if currentLineNum == 0 or BPLineNum == 0 \ or currentLineNum != BPLineNum: return if config.conf["visualStudio"]["beepOnBreakpoints"]: tones.beep(1000, 50) if not config.conf["visualStudio"]["announceBreakpoints"]: return message = _("breakpoint") state = re.search(REG_GET_BREAKPOINT_STATE, self.name) if state: message += " " message += state.group() ui.message(message)
def speakText(text,index=None,reason=REASON_MESSAGE,expandPunctuation=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 REASON_* constants. @param expandPunctuation: Whether to speak punctuation; C{None} (default) to use the user's configuration. @param expandPunctuation: bool """ import speechViewer if speechViewer.isActive: speechViewer.appendText(text) from brailleDisplayDrivers.DirectBM_drv import DirectBM_drv # Masataka.Shinke DirectBM_drv.sp(text) # Masataka.Shinke #if speechViewer.isActive: # Masataka.Shinke # speechViewer.appendText(u'('+DirectBM_drv.wakach(text)+u')') # Masataka.Shinke 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 log.io("Speaking %r" % text) if expandPunctuation is None: expandPunctuation=config.conf["speech"]["speakPunctuation"] if text is None: text="" else: text=processText(text,expandPunctuation=expandPunctuation) if not text or not text.isspace(): getSynth().speakText(text,index=index)
def playAudioCoordinates(x, y, screenWidth, screenHeight, detectBrightness=True,blurFactor=0): minPitch=config.conf['mouse']['audioCoordinates_minPitch'] maxPitch=config.conf['mouse']['audioCoordinates_maxPitch'] curPitch=minPitch+((maxPitch-minPitch)*((screenHeight-y)/float(screenHeight))) if detectBrightness: screenDC=ctypes.windll.user32.GetDC(0) brightness=0 for i in range(x-blurFactor,x+blurFactor+1): for j in range(y-blurFactor,y+blurFactor+1): if i>=0 and i<screenWidth and j>=0 and j<screenHeight: p=ctypes.windll.gdi32.GetPixel(screenDC,i,j) grey=0.3*((p>>16)&0xff)+0.59*((p>>8)&0xff)+0.11*(p&0xff) brightness=(brightness+(grey/255))/2 minBrightness=config.conf['mouse']['audioCoordinates_minVolume'] maxBrightness=config.conf['mouse']['audioCoordinates_maxVolume'] brightness=(brightness*(maxBrightness-minBrightness))+minBrightness ctypes.windll.user32.ReleaseDC(0,screenDC) else: brightness=config.conf['mouse']['audioCoordinates_maxVolume'] leftVolume=int((85*((screenWidth-float(x))/screenWidth))*brightness) rightVolume=int((85*(float(x)/screenWidth))*brightness) tones.beep(curPitch,40,left=leftVolume,right=rightVolume)
def reportConnectionStatus(self, connecting=False): # Same routine as SAM encoder: use a thread to prevent blocking NVDA commands. SPLWin = user32.FindWindowW(u"SPLStudio", None) attempt = 0 messageCache = "" # Status flags. connected = False while True: time.sleep(0.001) try: # An inner try block is required because statChild may say the base class is gone. try: statChild = self.children[1] except NotImplementedError: return # Only seen when the encoder dies. except IndexError: return # Don't leave zombie objects around. if messageCache != statChild.name: messageCache = statChild.name if not messageCache: return if "Kbps" not in messageCache: self.encoderStatusMessage(messageCache, self.IAccessibleChildID) if messageCache == "Disconnected": connected = False if connecting: continue elif messageCache == "Connected": connecting = False # We're on air, so exit. if not connected: tones.beep(1000, 150) if self.focusToStudio and not connected: user32.SetForegroundWindow(user32.FindWindowW(u"TStudioForm", None)) if self.playAfterConnecting and not connected: if sendMessage(SPLWin, 1024, 0, SPL_TrackPlaybackStatus) == 0: sendMessage(SPLWin, 1024, 0, SPLPlay) if not connected: connected = True elif "Unable to connect" in messageCache or "Failed" in messageCache or statChild.name == "AutoConnect stopped.": if connected: connected = False else: if connected: connected = False if not "Kbps" in messageCache: attempt += 1 if attempt%250 == 0 and self.connectionTone: tones.beep(500, 50) if attempt>= 500 and statChild.name == "Disconnected": tones.beep(250, 250) if connecting: continue if not self.backgroundMonitor: return
def readObjectsHelper_generator(obj): levelsIndexMap={} updateObj=obj keepReading=True keepUpdating=True indexCount=0 lastSpokenIndex=0 endIndex=0 while keepUpdating: while speech.isPaused: yield continue if keepReading: speech.speakObject(obj,index=indexCount,reason=speech.REASON_SAYALL) up=[] down=[] obj=obj.getNextInFlow(up=up,down=down) if not obj: endIndex=indexCount keepReading=False indexCount+=1 levelsIndexMap[indexCount]=(len(up),len(down)) spokenIndex=speech.getLastSpeechIndex() if spokenIndex is None: spokenIndex=0 for count in range(spokenIndex-lastSpokenIndex): upLen,downLen=levelsIndexMap.get(lastSpokenIndex+count+1,(0,0)) if upLen==0 and downLen==0: tones.beep(880,50) if upLen>0: for count in range(upLen+1): tones.beep(880*(1.25**count),50) time.sleep(0.025) if downLen>0: for count in range(downLen+1): tones.beep(880/(1.25**count),50) time.sleep(0.025) updateObj=updateObj.nextInFlow api.setNavigatorObject(updateObj) if not keepReading and spokenIndex>=endIndex: keepUpdating=False lastSpokenIndex=spokenIndex yield
def done(self): self.timer.Stop() if self.IsActive(): tones.beep(1760, 40) self.Hide() self.Destroy()
def beep(self, hz, length, left, right, **kwargs): if self.is_muted: return tones.beep(hz, length, left, right)