Example #1
0
	def setDisplayByName(self, name):
		if not name:
			self.display = None
			self.displaySize = 0
			return
		try:
			newDisplay = _getDisplayDriver(name)
			if newDisplay == self.display.__class__:
				# This is the same driver as was already set, so just re-initialise it.
				self.display.terminate()
				newDisplay = self.display
				newDisplay.__init__()
			else:
				newDisplay = newDisplay()
				if self.display:
					try:
						self.display.terminate()
					except:
						log.error("Error terminating previous display driver", exc_info=True)
				self.display = newDisplay
			self.displaySize = newDisplay.numCells
			self.enabled = bool(self.displaySize)
			config.conf["braille"]["display"] = name
			log.info("Loaded braille display driver %s" % name)
			return True
		except:
			log.error("Error initializing display driver", exc_info=True)
			self.setDisplayByName("noBraille")
			return False
Example #2
0
def setSynth(name,isFallback=False):
	global _curSynth,_audioOutputDevice
	if name is None: 
		_curSynth.terminate()
		_curSynth=None
		return True
	if name=='auto':
		# Default to OneCore on Windows 10 and above, and eSpeak on previous Operating Systems
		name='oneCore' if winVersion.winVersion.major>=10 else 'espeak'
	if _curSynth:
		_curSynth.cancel()
		_curSynth.terminate()
		prevSynthName = _curSynth.name
		_curSynth = None
	else:
		prevSynthName = None
	try:
		_curSynth=getSynthInstance(name)
		_audioOutputDevice=config.conf["speech"]["outputDevice"]
		if not isFallback:
			config.conf["speech"]["synth"]=name
		log.info("Loaded synthDriver %s"%name)
		return True
	except:
		log.error("setSynth", exc_info=True)
		if prevSynthName:
			setSynth(prevSynthName,isFallback=True)
		elif name not in ('espeak','silence'):
			setSynth('espeak',isFallback=True)
		elif name=='espeak':
			setSynth('silence',isFallback=True)
		return False
Example #3
0
def initialize(voice = default_jtalk_voice):
	global player, voice_args
	global speaker_attenuation
	voice_args = voice
	speaker_attenuation = voice_args['speaker_attenuation']
	if not _espeak.espeakDLL:
		_espeak.initialize()
		log.debug("jtalk using eSpeak version %s" % _espeak.info())
	_espeak.setVoiceByLanguage("en")
	_espeak.setVoiceAndVariant(variant=voice["espeak_variant"])
	if not player:
		player = nvwave.WavePlayer(channels=1, samplesPerSec=voice_args['samp_rate'], bitsPerSample=16, outputDevice=config.conf["speech"]["outputDevice"])
	if not _bgthread.bgThread:
		_bgthread.initialize()
	if not mecab:
		Mecab_initialize(log.info, jtalk_dir, dic_dir, user_dics)
	jtalkPrepare.setup()

	jt_dll = os.path.join(jtalk_dir, 'libopenjtalk.dll')
	log.debug('jt_dll %s' % jt_dll)
	libjt_initialize(jt_dll)
	log.debug(libjt_version())

	if os.path.isfile(voice_args['htsvoice']):
		libjt_load(voice_args['htsvoice'])
		log.info("loaded " + voice_args['htsvoice'])
	else:
		log.error("load error " + voice_args['htsvoice'])
	libjt_set_alpha(voice_args['alpha'])
	libjt_set_beta(voice_args['beta'])
Example #4
0
	def connected_to_relay(self):
		log.info("Control connector connected")
		beep_sequence.beep_sequence((720, 100), 50, (720, 100), 50, (720, 100))
		# Translators: Presented in direct (client to server) remote connection when the controlled computer is ready.
		speech.speakMessage(_("Connected to control server"))
		self.push_clipboard_item.Enable(True)
		write_connection_to_config(self.control_connector.address)
Example #5
0
def resetConfiguration(factoryDefaults=False):
	"""Loads the configuration, installs the correct language support and initialises audio so that it will use the configured synth and speech settings.
	"""
	import config
	import braille
	import speech
	import languageHandler
	import inputCore
	log.debug("Terminating braille")
	braille.terminate()
	log.debug("terminating speech")
	speech.terminate()
	log.debug("terminating addonHandler")
	addonHandler.terminate()
	log.debug("Reloading config")
	config.load(factoryDefaults=factoryDefaults)
	logHandler.setLogLevelFromConfig()
	#Language
	lang = config.conf["general"]["language"]
	log.debug("setting language to %s"%lang)
	languageHandler.setLanguage(lang)
	# Addons
	addonHandler.initialize()
	#Speech
	log.debug("initializing speech")
	speech.initialize()
	#braille
	log.debug("Initializing braille")
	braille.initialize()
	log.debug("Reloading user and locale input gesture maps")
	inputCore.manager.loadUserGestureMap()
	inputCore.manager.loadLocaleGestureMap()
	log.info("Reverted to saved configuration")
Example #6
0
	def __init__(self):
		super(BrailleDisplayDriver, self).__init__()
		self.numCells = 0

		for portType, port in _getPorts():
			# Try talking to the display.
			try:
				self._ser = serial.Serial(port, baudrate=BAUD_RATE, parity=PARITY, timeout=TIMEOUT, writeTimeout=TIMEOUT)
			except serial.SerialException:
				continue
			# This will cause the number of cells to be returned.
			self._sendMessage(MSG_INIT)
			# #5406: With the new USB driver, the first command is ignored after a reconnection.
			# Worse, if we don't receive a reply,
			# _handleResponses freezes for some reason despite the timeout.
			# Send the init message again just in case.
			self._sendMessage(MSG_INIT)
			self._handleResponses(wait=True)
			if not self.numCells:
				# HACK: When connected via bluetooth, the display sometimes reports communication not allowed on the first attempt.
				self._sendMessage(MSG_INIT)
				self._handleResponses(wait=True)
			if self.numCells:
				# A display responded.
				log.info("Found display with {cells} cells connected via {type} ({port})".format(
					cells=self.numCells, type=portType, port=port))
				break

		else:
			raise RuntimeError("No display found")

		self._readTimer = wx.PyTimer(self._handleResponses)
		self._readTimer.Start(READ_INTERVAL)
		self._keysDown = set()
		self._ignoreKeyReleases = False
Example #7
0
def _crashHandler(exceptionInfo):
	threadId = ctypes.windll.kernel32.GetCurrentThreadId()
	# An exception might have been set for this thread.
	# Clear it so that it doesn't get raised in this function.
	ctypes.pythonapi.PyThreadState_SetAsyncExc(threadId, None)

	# Write a minidump.
	dumpPath = os.path.abspath(os.path.join(globalVars.appArgs.logFileName, "..", "nvda_crash.dmp"))
	try:
		with file(dumpPath, "w") as mdf:
			mdExc = MINIDUMP_EXCEPTION_INFORMATION(ThreadId=threadId,
				ExceptionPointers=exceptionInfo, ClientPointers=False)
			if not ctypes.windll.DbgHelp.MiniDumpWriteDump(
				ctypes.windll.kernel32.GetCurrentProcess(),
				os.getpid(),
				msvcrt.get_osfhandle(mdf.fileno()),
				0, # MiniDumpNormal
				ctypes.byref(mdExc),
				None,
				None
			):
				raise ctypes.WinError()
	except:
		log.critical("NVDA crashed! Error writing minidump", exc_info=True)
	else:
		log.critical("NVDA crashed! Minidump written to %s" % dumpPath)

	log.info("Restarting due to crash")
	core.restart()
	return 1 # EXCEPTION_EXECUTE_HANDLER
Example #8
0
	def _handleInputHelp(self, gesture, onlyLog=False):
		textList = [gesture.displayName]
		script = gesture.script
		runScript = False
		logMsg = "Input help: gesture %s"%gesture.logIdentifier
		if script:
			scriptName = scriptHandler.getScriptName(script)
			logMsg+=", bound to script %s" % scriptName
			scriptLocation = scriptHandler.getScriptLocation(script)
			if scriptLocation:
				logMsg += " on %s" % scriptLocation
			if scriptName == "toggleInputHelp":
				runScript = True
			else:
				desc = script.__doc__
				if desc:
					textList.append(desc)

		log.info(logMsg)
		if onlyLog:
			return

		import braille
		braille.handler.message("\t\t".join(textList))
		# Punctuation must be spoken for the gesture name (the first chunk) so that punctuation keys are spoken.
		speech.speakText(textList[0], reason=controlTypes.REASON_MESSAGE, symbolLevel=characterProcessing.SYMLVL_ALL)
		for text in textList[1:]:
			speech.speakMessage(text)

		if runScript:
			script(gesture)
Example #9
0
	def __init__(self, port="auto"):
		super(BrailleDisplayDriver, self).__init__()
		self.numCells = 0
		self._model = None
		if port == "auto":
			tryPorts = self._getAutoPorts(hwPortUtils.listComPorts(onlyAvailable=True))
		else:
			try:
				btName = next(portInfo.get("bluetoothName","") for portInfo in hwPortUtils.listComPorts() if portInfo.get("port")==port)
				btPrefix = next(prefix for prefix in bluetoothPrefixes if btName.startswith(prefix))
				tryPorts = ((port, "bluetooth", btPrefix),)
			except StopIteration:
				tryPorts = ()

		for port, portType, identifier in tryPorts:
			self.isBulk = portType=="USB bulk"
			# Try talking to the display.
			try:
				if self.isBulk:
					# onReceiveSize based on max packet size according to USB endpoint information.
					self._dev = hwIo.Bulk(port, 0, 1, self._onReceive, writeSize=0, onReceiveSize=64)
				else:
					self._dev = hwIo.Serial(port, baudrate=BAUD_RATE, parity=PARITY, timeout=self.timeout, writeTimeout=self.timeout, onReceive=self._onReceive)
			except EnvironmentError:
				log.debugWarning("", exc_info=True)
				continue
			for i in xrange(3):
				self._sendCellCountRequest()
				# Wait for an expected response.
				if self.isBulk:
					# Hims Bulk devices sometimes present themselves to the system while not yet ready.
					# For example, when switching the connection mode toggle on the Braille EDGE from Bluetooth to USB,
					# the USB device is connected but not yet ready.
					# Wait ten times the timeout, which is ugly, but effective.
					self._dev.waitForRead(self.timeout*10)
				else:
					self._dev.waitForRead(self.timeout)
				if self.numCells:
					break
			if not self.numCells:
				log.debugWarning("No response from potential Hims display")
				self._dev.close()
				continue
			if portType=="USB serial":
				self._model = SyncBraille()
			elif self.isBulk:
				self._sendIdentificationRequests(usbId=identifier)
			elif portType=="bluetooth" and identifier:
				self._sendIdentificationRequests(bluetoothPrefix=identifier)
			else:
				self._sendIdentificationRequests()
			if self._model:
				# A display responded.
				log.info("Found {device} connected via {type} ({port})".format(
					device=self._model.name, type=portType, port=port))
				break

			self._dev.close()
		else:
			raise RuntimeError("No Hims display found")
Example #10
0
    def __init__(self, port="Auto"):
        super(BrailleDisplayDriver, self).__init__()
        self.numCells = 0
        self._deviceID = None

        if port == "auto":
            tryPorts = self._getAutoPorts(hwPortUtils.listComPorts(onlyAvailable=True))
        else:
            tryPorts = ((port, "serial"),)
        for port, portType in tryPorts:
            # At this point, a port bound to this display has been found.
            # Try talking to the display.
            self.isHid = portType == "USB HID"
            try:
                if self.isHid:
                    self._dev = hwIo.Hid(port, onReceive=self._onReceive)
                else:
                    self._dev = hwIo.Serial(
                        port, baudrate=BAUD_RATE, timeout=TIMEOUT, writeTimeout=TIMEOUT, onReceive=self._onReceive
                    )
            except EnvironmentError:
                continue
            if self.isHid:
                try:
                    # It's essential to send protocol on for the Orbit Reader 20.
                    self._sendRequest(BAUM_PROTOCOL_ONOFF, True)
                except EnvironmentError:
                    # Pronto! and VarioUltra don't support BAUM_PROTOCOL_ONOFF.
                    pass
                    # Explicitly request device info.
                    # Even where it's supported, BAUM_PROTOCOL_ONOFF doesn't always return device info.
                self._sendRequest(BAUM_REQUEST_INFO, 0)
            else:  # Serial
                # If the protocol is already on, sending protocol on won't return anything.
                # First ensure it's off.
                self._sendRequest(BAUM_PROTOCOL_ONOFF, False)
                # This will cause the device id, serial number and number of cells to be returned.
                self._sendRequest(BAUM_PROTOCOL_ONOFF, True)
                # Send again in case the display misses the first one.
                self._sendRequest(BAUM_PROTOCOL_ONOFF, True)
            for i in xrange(3):
                # An expected response hasn't arrived yet, so wait for it.
                self._dev.waitForRead(TIMEOUT)
                if self.numCells and self._deviceID:
                    break
            if self.numCells:
                # A display responded.
                log.info(
                    "Found {device} connected via {type} ({port})".format(
                        device=self._deviceID, type=portType, port=port
                    )
                )
                break
            self._dev.close()

        else:
            raise RuntimeError("No Baum display found")

        self._keysDown = {}
        self._ignoreKeyReleases = False
Example #11
0
	def query_API(self):
		"""Query the API.

		This method creates a new client.

		"""
		log.info("Querying the API...")
		self.client = Client.queryWeather("Hanford,us")
Example #12
0
	def on_connected_as_slave(self):
		log.info("Control connector connected")
		beep_sequence.beep_sequence_async((720, 100), 50, (720, 100), 50, (720, 100))
		# Translators: Presented in direct (client to server) remote connection when the controlled computer is ready.
		speech.speakMessage(_("Connected to control server"))
		self.push_clipboard_item.Enable(True)
		self.copy_link_item.Enable(True)
		configuration.write_connection_to_config(self.slave_transport.address)
Example #13
0
	def __init__(self):
		super(BrailleDisplayDriver, self).__init__()
		self.numCells = 0
		self._deviceID = None

		# Scan all available com ports.
		# Try bluetooth ports last.
		for portInfo in sorted(hwPortUtils.listComPorts(onlyAvailable=True), key=lambda item: "bluetoothName" in item):
			port = portInfo["port"]
			hwID = portInfo["hardwareID"]
			if hwID.startswith(r"FTDIBUS\COMPORT"):
				# USB.
				portType = "USB"
				try:
					usbID = hwID.split("&", 1)[1]
				except IndexError:
					continue
				if usbID not in USB_IDS:
					continue
			elif "bluetoothName" in portInfo:
				# Bluetooth.
				portType = "bluetooth"
				btName = portInfo["bluetoothName"]
				if not any(btName.startswith(prefix) for prefix in BLUETOOTH_NAMES):
					continue
			else:
				continue

			# At this point, a port bound to this display has been found.
			# Try talking to the display.
			try:
				self._ser = serial.Serial(port, baudrate=BAUD_RATE, timeout=TIMEOUT, writeTimeout=TIMEOUT)
			except serial.SerialException:
				continue
			# This will cause the number of cells to be returned.
			self._sendRequest(BAUM_DISPLAY_DATA)
			# Send again in case the display misses the first one.
			self._sendRequest(BAUM_DISPLAY_DATA)
			# We just sent less bytes than we should,
			# so we need to send another request in order for the display to know the previous request is finished.
			self._sendRequest(BAUM_DEVICE_ID)
			self._handleResponses(wait=True)
			if self.numCells:
				# A display responded.
				if not self._deviceID:
					# Bah. The response to our device ID query hasn't arrived yet, so wait for it.
					self._handleResponses(wait=True)
				log.info("Found {device} connected via {type} ({port})".format(
					device=self._deviceID, type=portType, port=port))
				break

		else:
			raise RuntimeError("No Baum display found")

		self._readTimer = wx.PyTimer(self._handleResponses)
		self._readTimer.Start(READ_INTERVAL)
		self._keysDown = {}
		self._ignoreKeyReleases = False
Example #14
0
def initialize():
	global _remoteLib, _remoteLoader64, localLib, generateBeep, VBuf_getTextInRange, lastLanguageID, lastLayoutString
	hkl=c_ulong(windll.User32.GetKeyboardLayout(0)).value
	lastLanguageID=winUser.LOWORD(hkl)
	KL_NAMELENGTH=9
	buf=create_unicode_buffer(KL_NAMELENGTH)
	res=windll.User32.GetKeyboardLayoutNameW(buf)
	if res:
		lastLayoutString=buf.value
	localLib=cdll.LoadLibrary(os.path.join(versionedLibPath,'nvdaHelperLocal.dll'))
	for name,func in [
		("nvdaController_speakText",nvdaController_speakText),
		("nvdaController_cancelSpeech",nvdaController_cancelSpeech),
		("nvdaController_brailleMessage",nvdaController_brailleMessage),
		("nvdaControllerInternal_requestRegistration",nvdaControllerInternal_requestRegistration),
		("nvdaControllerInternal_inputLangChangeNotify",nvdaControllerInternal_inputLangChangeNotify),
		("nvdaControllerInternal_typedCharacterNotify",nvdaControllerInternal_typedCharacterNotify),
		("nvdaControllerInternal_displayModelTextChangeNotify",nvdaControllerInternal_displayModelTextChangeNotify),
		("nvdaControllerInternal_logMessage",nvdaControllerInternal_logMessage),
		("nvdaControllerInternal_inputCompositionUpdate",nvdaControllerInternal_inputCompositionUpdate),
		("nvdaControllerInternal_inputCandidateListUpdate",nvdaControllerInternal_inputCandidateListUpdate),
		("nvdaControllerInternal_IMEOpenStatusUpdate",nvdaControllerInternal_IMEOpenStatusUpdate),
		("nvdaControllerInternal_inputConversionModeUpdate",nvdaControllerInternal_inputConversionModeUpdate),
		("nvdaControllerInternal_vbufChangeNotify",nvdaControllerInternal_vbufChangeNotify),
		("nvdaControllerInternal_installAddonPackageFromPath",nvdaControllerInternal_installAddonPackageFromPath),
		("nvdaControllerInternal_drawFocusRectNotify",nvdaControllerInternal_drawFocusRectNotify),
	]:
		try:
			_setDllFuncPointer(localLib,"_%s"%name,func)
		except AttributeError as e:
			log.error("nvdaHelperLocal function pointer for %s could not be found, possibly old nvdaHelperLocal dll"%name,exc_info=True)
			raise e
	localLib.nvdaHelperLocal_initialize()
	generateBeep=localLib.generateBeep
	generateBeep.argtypes=[c_char_p,c_float,c_int,c_int,c_int]
	generateBeep.restype=c_int
	# The rest of this function (to do with injection) only applies if NVDA is not running as a Windows store application
	# Handle VBuf_getTextInRange's BSTR out parameter so that the BSTR will be freed automatically.
	VBuf_getTextInRange = CFUNCTYPE(c_int, c_int, c_int, c_int, POINTER(BSTR), c_int)(
		("VBuf_getTextInRange", localLib),
		((1,), (1,), (1,), (2,), (1,)))
	if config.isAppX:
		log.info("Remote injection disabled due to running as a Windows Store Application")
		return
	#Load nvdaHelperRemote.dll but with an altered search path so it can pick up other dlls in lib
	h=windll.kernel32.LoadLibraryExW(os.path.abspath(os.path.join(versionedLibPath,u"nvdaHelperRemote.dll")),0,0x8)
	if not h:
		log.critical("Error loading nvdaHelperRemote.dll: %s" % WinError())
		return
	_remoteLib=CDLL("nvdaHelperRemote",handle=h)
	if _remoteLib.injection_initialize(globalVars.appArgs.secure) == 0:
		raise RuntimeError("Error initializing NVDAHelperRemote")
	if not _remoteLib.installIA2Support():
		log.error("Error installing IA2 support")
	#Manually start the in-process manager thread for this NVDA main thread now, as a slow system can cause this action to confuse WX
	_remoteLib.initInprocManagerThreadIfNeeded()
	if os.environ.get('PROCESSOR_ARCHITEW6432')=='AMD64':
		_remoteLoader64=RemoteLoader64()
Example #15
0
 def on_connected_as_slave(self):
     log.info("Control connector connected")
     beep_sequence.beep_sequence_async((720, 100), 50, (720, 100), 50,
                                       (720, 100))
     # Translators: Presented in direct (client to server) remote connection when the controlled computer is ready.
     speech.speakMessage(_("Connected to control server"))
     self.push_clipboard_item.Enable(True)
     self.copy_link_item.Enable(True)
     configuration.write_connection_to_config(self.slave_transport.address)
Example #16
0
	def _get_numCells(self):
		if self._alva_NumCells==0:
			NumCells = c_int(0)
			AlvaLib.AlvaGetCells(0, byref(NumCells))
			if NumCells.value==0:
				raise RuntimeError("Cannot obtain number of cells")
			self._alva_NumCells = NumCells.value
			log.info("ALVA BC6xx has %d cells" %self._alva_NumCells)
		return self._alva_NumCells
Example #17
0
File: kgs.py Project: ma10/nvdajp
def bmDisConnect(hBrl, port):
    global fConnection, numCells
    ret = hBrl.bmEndDisplayMode()
    log.info("BmEndDisplayMode %s %d" % (port, ret))
    ret = hBrl.bmEnd()
    log.info("BmEnd %s %d" % (port, ret))
    numCells = 0
    fConnection = False
    return ret
	def script_copyLast(self, gesture):
		log.info(str(self._history))
		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)
Example #19
0
 def _get_numCells(self):
     if self._alva_NumCells == 0:
         NumCells = c_int(0)
         AlvaLib.AlvaGetCells(0, byref(NumCells))
         if NumCells.value == 0:
             raise RuntimeError("Cannot obtain number of cells")
         self._alva_NumCells = NumCells.value
         log.info("ALVA BC6xx has %d cells" % self._alva_NumCells)
     return self._alva_NumCells
Example #20
0
 def terminate(self):
     log.info("MDV terminate")
     super(BrailleDisplayDriver, self).terminate()
     try:
         mbDll.BrlTerminate()
         self._keyCheckTimer.Stop()
         self._keyCheckTimer = None
     except:
         pass
Example #21
0
    def __init__(self, driver, module_id):
        super().__init__(driver, module_id)
        driver.numCells = self.number_cells
        self.input_handler = self.process_main_data_packet  # None for output only modules
        driver.mainModule = self

        self.cumul_d_keys = 0

        log.info(f"VarioPro{self.number_cells} main module initialized")
	def saveProfileTriggers(self):
		"""Save profile trigger information to disk.
		This should be called whenever L{profilesToTriggers} is modified.
		"""
		if globalVars.appArgs.secure:
			# Never save if running securely.
			return
		self.triggersToProfiles.parent.write()
		log.info("Profile triggers saved")
Example #23
0
	def saveProfileTriggers(self):
		"""Save profile trigger information to disk.
		This should be called whenever L{profilesToTriggers} is modified.
		"""
		if globalVars.appArgs.secure:
			# Never save if running securely.
			return
		self.triggersToProfiles.parent.write()
		log.info("Profile triggers saved")
Example #24
0
    def __init__(self, port="auto"):
        super(BrailleDisplayDriver, self).__init__()
        self.numCells = 0
        self._model = None
        self._ignoreKeyReleases = False
        self._keysDown = set()
        self._brailleInput = False
        self._hidSerialBuffer = ""

        if port == "auto":
            tryPorts = self._getAutoPorts(
                hwPortUtils.listComPorts(onlyAvailable=True))
        else:
            tryPorts = ((port, "serial"), )
        for port, portType in tryPorts:
            # At this point, a port bound to this display has been found.
            # Try talking to the display.
            self.isHid = portType.startswith("USB HID")
            self.isHidSerial = portType == "USB HID serial converter"
            try:
                if self.isHid:
                    self._dev = hwIo.Hid(port, onReceive=self._onReceive)
                    if self.isHidSerial:
                        # This is either the standalone HID adapter cable for older displays,
                        # or an older display with a HID - serial adapter built in
                        # Send a flush to open the serial channel
                        self._dev.write(HT_HID_RPT_InCommand +
                                        HT_HID_CMD_FlushBuffers)
                else:
                    self._dev = hwIo.Serial(port,
                                            baudrate=BAUD_RATE,
                                            parity=PARITY,
                                            timeout=self.timeout,
                                            writeTimeout=self.timeout,
                                            onReceive=self._onReceive)
            except EnvironmentError:
                log.debugWarning("", exc_info=True)
                continue

            self.sendPacket(HT_PKT_RESET)
            for _i in xrange(3):
                # An expected response hasn't arrived yet, so wait for it.
                self._dev.waitForRead(self.timeout)
                if self.numCells and self._model:
                    break

            if self.numCells:
                # A display responded.
                self._model.postInit()
                log.info("Found {device} connected via {type} ({port})".format(
                    device=self._model.name, type=portType, port=port))
                break
            self._dev.close()

        else:
            raise RuntimeError("No Handy Tech display found")
    def __init__(self, port="auto"):
        super(BrailleDisplayDriver, self).__init__()
        self.numCells = 0
        self._deviceID: Optional[str] = None

        for portType, portId, port, portInfo in self._getTryPorts(port):
            # At this point, a port bound to this display has been found.
            # Try talking to the display.
            self.isHid = portType == bdDetect.KEY_HID
            try:
                if self.isHid:
                    self._dev = hwIo.Hid(port, onReceive=self._onReceive)
                else:
                    self._dev = hwIo.Serial(port,
                                            baudrate=BAUD_RATE,
                                            timeout=TIMEOUT,
                                            writeTimeout=TIMEOUT,
                                            onReceive=self._onReceive)
            except EnvironmentError:
                log.debugWarning("", exc_info=True)
                continue
            if self.isHid:
                try:
                    # It's essential to send protocol on for the Orbit Reader 20.
                    self._sendRequest(BAUM_PROTOCOL_ONOFF, True)
                except EnvironmentError:
                    # Pronto! and VarioUltra don't support BAUM_PROTOCOL_ONOFF.
                    pass
                # Explicitly request device info.
                # Even where it's supported, BAUM_PROTOCOL_ONOFF doesn't always return device info.
                self._sendRequest(BAUM_REQUEST_INFO, 0)
            else:  # Serial
                # If the protocol is already on, sending protocol on won't return anything.
                # First ensure it's off.
                self._sendRequest(BAUM_PROTOCOL_ONOFF, False)
                # This will cause the device id, serial number and number of cells to be returned.
                self._sendRequest(BAUM_PROTOCOL_ONOFF, True)
                # Send again in case the display misses the first one.
                self._sendRequest(BAUM_PROTOCOL_ONOFF, True)
            for i in range(3):
                # An expected response hasn't arrived yet, so wait for it.
                self._dev.waitForRead(TIMEOUT)
                if self.numCells and self._deviceID:
                    break
            if self.numCells:
                # A display responded.
                log.info("Found {device} connected via {type} ({port})".format(
                    device=self._deviceID, type=portType, port=port))
                break
            self._dev.close()

        else:
            raise RuntimeError("No Baum display found")

        self._keysDown = {}
        self._ignoreKeyReleases = False
 def innerFunc(*args, **kwargs):
     func(*args, **kwargs)
     try:
         clips = initClipSfile()
         clip = api.getClipData()
         log.info(clip)
         clips['recent'].insert(0, clip)
         writeClips(clips)
     except OSError:
         pass
Example #27
0
	def connectUSB(self,devlist):
		"""try to connect to usb device,is triggered when BRXCOM is not installed and bluetooth
connection could not be established"""
		try:
			self._dev = ftdi2.open_ex(devlist[0])
			self._dev.set_baud_rate(self._baud)
			self._dev.inWaiting = self._dev.get_queue_status
			log.info("connectUSB success")
		except:
			log.debugWarning("connectUSB failed")
def testForExitRequired():
    """This function tests if NVDA should never have been started automatically after session logon.
	If this is the case, it logs an info message and exits.
	"""
    if ((not config.getStartAfterLogon())
            and globalVars.appArgs.easeOfAccess == True):
        log.info(
            'Startup option workaround: NVDA was not set to start automatically after logon so it will shut down immediately.'
        )
        wx.GetApp().ExitMainLoop()
Example #29
0
	def onEndSession(evt):
		# NVDA will be terminated as soon as this function returns, so save configuration if appropriate.
		config.saveOnExit()
		speech.cancelSpeech()
		if not globalVars.appArgs.minimal and config.conf["general"]["playStartAndExitSounds"]:
			try:
				nvwave.playWaveFile("waves\\exit.wav",async=False)
			except:
				pass
		log.info("Windows session ending")
Example #30
0
    def connectUSB(self, devlist: List[bytes]):
        """Try to connect to usb device, this is triggered when bluetooth
connection could not be established"""
        try:
            self._dev = ftdi2.open_ex(devlist[0])
            self._dev.set_baud_rate(self._baud)
            self._dev.inWaiting = self._dev.get_queue_status
            log.info("connectUSB success")
        except:
            log.debugWarning("connectUSB failed")
Example #31
0
    def __init__(self, port="auto"):
        super(BrailleDisplayDriver, self).__init__()
        self.numCells = 0
        self._model = None

        for match in self._getTryPorts(port):
            portType, portId, port, portInfo = match
            self.isBulk = portType == bdDetect.KEY_CUSTOM
            # Try talking to the display.
            try:
                if self.isBulk:
                    # onReceiveSize based on max packet size according to USB endpoint information.
                    self._dev = hwIo.Bulk(port,
                                          0,
                                          1,
                                          self._onReceive,
                                          writeSize=0,
                                          onReceiveSize=64)
                else:
                    self._dev = hwIo.Serial(port,
                                            baudrate=BAUD_RATE,
                                            parity=PARITY,
                                            timeout=self.timeout,
                                            writeTimeout=self.timeout,
                                            onReceive=self._onReceive)
            except EnvironmentError:
                log.debugWarning("", exc_info=True)
                continue
            for i in xrange(3):
                self._sendCellCountRequest()
                # Wait for an expected response.
                if self.isBulk:
                    # Hims Bulk devices sometimes present themselves to the system while not yet ready.
                    # For example, when switching the connection mode toggle on the Braille EDGE from Bluetooth to USB,
                    # the USB device is connected but not yet ready.
                    # Wait ten times the timeout, which is ugly, but effective.
                    self._dev.waitForRead(self.timeout * 10)
                else:
                    self._dev.waitForRead(self.timeout)
                if self.numCells:
                    break
            if not self.numCells:
                log.debugWarning("No response from potential Hims display")
                self._dev.close()
                continue
            self._sendIdentificationRequests(match)
            if self._model:
                # A display responded.
                log.info("Found {device} connected via {type} ({port})".format(
                    device=self._model.name, type=portType, port=port))
                break

            self._dev.close()
        else:
            raise RuntimeError("No Hims display found")
Example #32
0
def resetConfiguration(factoryDefaults=False):
    """Loads the configuration, installs the correct language support and initialises audio so that it will use the configured synth and speech settings.
	"""
    import config
    import braille
    import brailleInput
    import speech
    import vision
    import inputCore
    import tones
    log.debug("Terminating vision")
    vision.terminate()
    log.debug("Terminating braille")
    braille.terminate()
    log.debug("Terminating brailleInput")
    brailleInput.terminate()
    log.debug("terminating speech")
    speech.terminate()
    log.debug("terminating tones")
    tones.terminate()
    log.debug("terminating addonHandler")
    addonHandler.terminate()
    log.debug("Reloading config")
    config.conf.reset(factoryDefaults=factoryDefaults)
    logHandler.setLogLevelFromConfig()
    # Language
    if languageHandler.isLanguageForced():
        lang = globalVars.appArgs.language
    else:
        lang = config.conf["general"]["language"]
    log.debug("setting language to %s" % lang)
    languageHandler.setLanguage(lang)
    # Addons
    addonHandler.initialize()
    # Tones
    tones.initialize()
    #Speech
    log.debug("initializing speech")
    speech.initialize()
    #braille
    log.debug("Initializing brailleInput")
    brailleInput.initialize()
    log.debug("Initializing braille")
    braille.initialize()
    # Vision
    log.debug("initializing vision")
    vision.initialize()
    log.debug("Reloading user and locale input gesture maps")
    inputCore.manager.loadUserGestureMap()
    inputCore.manager.loadLocaleGestureMap()
    import audioDucking
    if audioDucking.isAudioDuckingSupported():
        audioDucking.handlePostConfigProfileSwitch()
    log.info("Reverted to saved configuration")
Example #33
0
	def onOk(self,evt):
		super(ActivateEmoticonsDialog, self).onOk(evt)
		conf["Activation settings"]["activateAtStart"] = self.activateList.GetSelection()
		try:
			conf.validate(val, copy=True)
			conf.write()
			log.info("Emoticons add-on configuration saved.")
		except Exception, e:
			log.warning("Could not save Emoticons add-on configuration.")
			log.debugWarning("", exc_info=True)
			raise e
 def onLabel(self, evt):
     idCategory = self.categories.GetSelection()
     idLabel = self.labels.GetSelection()
     key = "%d:%s" % (idCategory, self.getIDFromIndex(idCategory, idLabel))
     label = self.label.GetValue()
     if idCategory >= 0 and idLabel >= 0:
         if self.getLabelFromID() == label:
             if key in self.roleLabels.keys():
                 log.info("%s deleted" % self.roleLabels.pop(key))
         else:
             self.roleLabels[key] = label
Example #35
0
	def __init__(self):
		_espeak.initialize()
		log.info("Using eSpeak version %s" % _espeak.info())
		lang=languageHandler.getLanguage()
		_espeak.setVoiceByLanguage(lang)
		self._language=lang
		self._variantDict=_espeak.getVariantDict()
		self.variant="max"
		self.rate=30
		self.pitch=40
		self.inflection=75
Example #36
0
 def __contains__(self, data):
     if self._useVirtualBuffer:
         # log.info("Searching for node offset %d in a %d length collection" %(data.offset, len(self._collection)))
         for x in self._collection:
             if x == data:
                 return True
     else:
         log.info(
             "operator __contains__ not supported for non-virtualbuffer wcgd!ts"
         )
         return False
Example #37
0
	def __init__(self):
		self.__lib=load_tts_library()
		self.__cancel_flag=threading.Event()
		self.__player=audio_player(self.__cancel_flag)
		self.__sample_rate_callback=sample_rate_callback(self.__lib,self.__player)
		self.__c_sample_rate_callback=RHVoice_callback_types.set_sample_rate(self.__sample_rate_callback)
		self.__speech_callback=speech_callback(self.__lib,self.__player,self.__cancel_flag)
		self.__c_speech_callback=RHVoice_callback_types.play_speech(self.__speech_callback)
		self.__mark_callback=mark_callback(self.__lib)
		self.__c_mark_callback=RHVoice_callback_types.process_mark(self.__mark_callback)
		resource_paths=[os.path.join(addon.path,"data").encode("UTF-8") for addon in addonHandler.getRunningAddons() if (addon.name.startswith("RHVoice-language") or addon.name.startswith("RHVoice-voice"))]
		c_resource_paths=(c_char_p*(len(resource_paths)+1))(*(resource_paths+[None]))
		init_params=RHVoice_init_params(None,
										config_path.encode("utf-8"),
										c_resource_paths,
										RHVoice_callbacks(self.__c_sample_rate_callback,
															  self.__c_speech_callback,
														  self.__c_mark_callback,
														  cast(None,RHVoice_callback_types.word_starts),
														  cast(None,RHVoice_callback_types.word_ends),
														  cast(None,RHVoice_callback_types.sentence_starts),
														  cast(None,RHVoice_callback_types.sentence_ends),
														  cast(None,RHVoice_callback_types.play_audio)),
										0)
		self.__tts_engine=self.__lib.RHVoice_new_tts_engine(byref(init_params))
		if not self.__tts_engine:
			raise RuntimeError("RHVoice: initialization error")
		nvda_language=languageHandler.getLanguage().split("_")[0]
		number_of_voices=self.__lib.RHVoice_get_number_of_voices(self.__tts_engine)
		native_voices=self.__lib.RHVoice_get_voices(self.__tts_engine)
		self.__voice_languages=dict()
		self.__languages=set()
		for i in range(number_of_voices):
			native_voice=native_voices[i]
			self.__voice_languages[native_voice.name.decode("utf-8")]=native_voice.language.decode("utf-8")
			self.__languages.add(native_voice.language.decode("utf-8"))
		self.__profile=None
		self.__profiles=list()
		number_of_profiles=self.__lib.RHVoice_get_number_of_voice_profiles(self.__tts_engine)
		native_profile_names=self.__lib.RHVoice_get_voice_profiles(self.__tts_engine)
		for i in range(number_of_profiles):
			name=native_profile_names[i].decode("utf-8")
			self.__profiles.append(name)
			if (self.__profile is None) and (nvda_language==self.__voice_languages[name.split("+")[0]]):
				self.__profile=name
		if self.__profile is None:
			self.__profile=self.__profiles[0]
		self.__rate=50
		self.__pitch=50
		self.__volume=50
		self.__tts_queue=Queue.Queue()
		self.__tts_thread=TTSThread(self.__tts_queue)
		self.__tts_thread.start()
		log.info("Using RHVoice version {}".format(self.__lib.RHVoice_get_version()))
Example #38
0
 def script_custom(self, gesture):
     webApp = self.markerQuery.markerManager.webApp
     if not hasattr(self.markerQuery, "customActionName"):
         ui.message(_("customAction not found"))
         return
     action = "action_%s" % self.markerQuery.customActionName
     log.info("custom webapp : %s" % webApp)
     if hasattr(webApp, action):
         getattr(webApp, action)(self)
     else:
         ui.message(u"%s introuvable" % action)
Example #39
0
	def __init__(self):
		_espeak.initialize()
		log.info("Using eSpeak NG version %s" % _espeak.info())
		lang=languageHandler.getLanguage()
		_espeak.setVoiceByLanguage(lang)
		self._language=lang
		self._variantDict=_espeak.getVariantDict()
		self.variant="max"
		self.rate=30
		self.pitch=40
		self.inflection=75
Example #40
0
 def run(self):
     while self.running:
         try:
             self.connector.run()
         except self.run_except:
             log.debugWarning("Connection failed", exc_info=True)
             time.sleep(self.connect_delay)
             continue
         else:
             time.sleep(self.connect_delay)
     log.info("Ending control connector thread %s" % self.name)
Example #41
0
 def __init__(self):
     super(GlobalPlugin, self).__init__()
     if globalVars.appArgs.secure:
         return
     if config.isAppX:
         return
     _config.load_json()
     location.load_region_code()
     log.info("Accurate weather plugin initialized")
     gui.settingsDialogs.NVDASettingsDialog.categoryClasses.append(
         settingsGUI.AccurateWeatherPanel)
Example #42
0
 def _handleReadError(self, error: int) -> bool:
     if error == 995:  # Broken I/O pipe, terminate and allow restart
         if not self._restarting:
             # Will not cause a data race since this driver runs on one thread
             self._restarting = True
             log.info(
                 "Freedom Scientific display implicitly disconnected by suspend, reinitializing"
             )
             self.terminate()
             self.__init__()
         return True
     return False
Example #43
0
    def __init__(self):
        super(BrailleDisplayDriver, self).__init__()

        for portInfo in hwPortUtils.listComPorts(onlyAvailable=True):
            port = portInfo["port"]
            hwID = portInfo["hardwareID"]
            #log.info("Found port {port} with hardwareID {hwID}".format(port=port, hwID=hwID))
            if not hwID.startswith(r"FTDIBUS\COMPORT"):
                continue
            try:
                usbID = hwID.split("&", 1)[1]
            except IndexError:
                continue
            if usbID not in HEDO_USB_IDS:
                continue
            # At this point, a port bound to this display has been found.
            # Try talking to the display.
            try:
                self._ser = serial.Serial(port,
                                          baudrate=HEDO_BAUDRATE,
                                          timeout=HEDO_TIMEOUT,
                                          writeTimeout=HEDO_TIMEOUT,
                                          parity=serial.PARITY_ODD,
                                          bytesize=serial.EIGHTBITS,
                                          stopbits=serial.STOPBITS_ONE)
            except serial.SerialException:
                continue

            # Prepare a blank line
            totalCells: int = HEDO_CELL_COUNT + HEDO_CELL_COUNT
            cells: bytes = HEDO_INIT + bytes(totalCells)

            # Send the blank line twice
            self._ser.write(cells)
            self._ser.flush()
            self._ser.write(cells)
            self._ser.flush()

            # Read out the input buffer
            ackS: bytes = self._ser.read(2)
            if HEDO_ACK in ackS:
                log.info("Found hedo ProfiLine connected via {port}".format(
                    port=port))
                break

        else:
            raise RuntimeError("No hedo display found")

        self._readTimer = wx.PyTimer(self.handleResponses)
        self._readTimer.Start(HEDO_READ_INTERVAL)

        self._keysDown = set()
        self._ignoreKeyReleases = False
	def __init__(self, port="auto"):
		super(BrailleDisplayDriver, self).__init__()
		self.numCells = 0
		self._model = None
		self._ignoreKeyReleases = False
		self._keysDown = set()
		self.brailleInput = False
		self._dotFirmness = 1
		self._hidSerialBuffer = b""
		self._atc = False
		self._sleepcounter = 0

		for portType, portId, port, portInfo in self._getTryPorts(port):
			# At this point, a port bound to this display has been found.
			# Try talking to the display.
			self.isHid = portType == bdDetect.KEY_HID
			self.isHidSerial = portId in USB_IDS_HID_CONVERTER
			self.port = port
			try:
				if self.isHidSerial:
					# This is either the standalone HID adapter cable for older displays,
					# or an older display with a HID - serial adapter built in
					self._dev = hwIo.Hid(port, onReceive=self._hidSerialOnReceive)
					# Send a flush to open the serial channel
					self._dev.write(HT_HID_RPT_InCommand + HT_HID_CMD_FlushBuffers)
				elif self.isHid:
					self._dev = hwIo.Hid(port, onReceive=self._hidOnReceive)
				else:
					self._dev = hwIo.Serial(port, baudrate=BAUD_RATE, parity=PARITY,
						timeout=self.timeout, writeTimeout=self.timeout, onReceive=self._serialOnReceive)
			except EnvironmentError:
				log.debugWarning("", exc_info=True)
				continue

			self.sendPacket(HT_PKT_RESET)
			for _i in range(3):
				# An expected response hasn't arrived yet, so wait for it.
				self._dev.waitForRead(self.timeout)
				if self.numCells and self._model:
					break

			if self.numCells:
				# A display responded.
				self._model.postInit()
				log.info("Found {device} connected via {type} ({port})".format(
					device=self._model.name, type=portType, port=port))
				# Create the message window on the ui thread.
				wx.CallAfter(self.create_message_window)
				break
			self._dev.close()

		else:
			raise RuntimeError("No Handy Tech display found")
Example #45
0
    def __init__(self, port="Auto"):
        super(BrailleDisplayDriver, self).__init__()
        self.numCells = 0
        self._deviceID = None

        if port == "auto":
            tryPorts = self._getAutoPorts(
                hwPortUtils.listComPorts(onlyAvailable=True))
        else:
            tryPorts = ((port, "serial"), )
        for port, portType in tryPorts:
            # At this point, a port bound to this display has been found.
            # Try talking to the display.
            self.isHid = portType == "USB HID"
            try:
                if self.isHid:
                    self._dev = hwIo.Hid(port, onReceive=self._onReceive)
                else:
                    self._dev = hwIo.Serial(port,
                                            baudrate=BAUD_RATE,
                                            timeout=TIMEOUT,
                                            writeTimeout=TIMEOUT,
                                            onReceive=self._onReceive)
            except EnvironmentError:
                continue
            if self.isHid:
                # Some displays don't support BAUM_PROTOCOL_ONOFF.
                self._sendRequest(BAUM_REQUEST_INFO, 0)
            else:
                # If the protocol is already on, sending protocol on won't return anything.
                # First ensure it's off.
                self._sendRequest(BAUM_PROTOCOL_ONOFF, False)
                # This will cause the device id, serial number and number of cells to be returned.
                self._sendRequest(BAUM_PROTOCOL_ONOFF, True)
                # Send again in case the display misses the first one.
                self._sendRequest(BAUM_PROTOCOL_ONOFF, True)
            for i in xrange(3):
                # An expected response hasn't arrived yet, so wait for it.
                self._dev.waitForRead(TIMEOUT)
                if self.numCells and self._deviceID:
                    break
            if self.numCells:
                # A display responded.
                log.info("Found {device} connected via {type} ({port})".format(
                    device=self._deviceID, type=portType, port=port))
                break
            self._dev.close()

        else:
            raise RuntimeError("No Baum display found")

        self._keysDown = {}
        self._ignoreKeyReleases = False
def getAnalyze(textInfo, unit):
	log.info("getAnalyse: %s, %s" % (unit, textInfo.text))
	errorPositions = {}
	if _NVDAConfigManager.toggleReportSymbolMismatchAnalysisOption(False):
		checkSymbolsDiscrepancies(textInfo, errorPositions)
	if _NVDAConfigManager.toggleReportAnomaliesOption(False):
		checkAnomalies(textInfo, unit, errorPositions)
	if _NVDAConfigManager.toggleReportFormattingChangesOption(False):
		checkFormatingChanges(textInfo, unit, errorPositions)
	alertCount = getAlertCount(errorPositions)
	textList = getReportText(errorPositions)
	return (alertCount, textList)
Example #47
0
 def update(self, location):
     self.check_interval(location)
     weather_url = self.get_api_url(location)
     data = util.get_data_from_url(weather_url)
     self.raw = json.loads(data)
     if self.raw["status"] != "ok":
         ui.message(_("Quota exceeded please try tomorrow"))
         return None
     log.info(self.raw)
     for e in self.supported_realtime_entries:
         location[e] = self.__getattribute__(str(e))
     location["last_provider"] = self.provider_id
def checkExtraWhiteSpace(info, unit, errorPositions):
	text = info.text
	log.info("checkExtraWhiteSpace: %s" % text)
	if hasattr(info.bookmark, "_end"):
		curEndPos = info.bookmark._end._endOffset
	else:
		curEndPos = info.bookmark.endOffset
	tempInfo = info.copy()
	tempInfo.collapse()
	tempInfo.expand(textInfos.UNIT_STORY)
	if hasattr(tempInfo.bookmark, "_end"):
		storyEndPos = tempInfo.bookmark._end._endOffset
	else:
		storyEndPos = tempInfo.bookmark.endOffset
	if unit == textInfos.UNIT_WORD:
		text = text.strip()
	else:
		text = text.replace("\r", "")
		text = text.replace("\n", "")
	if len(text) == 0:
		return
	eol = False
	if len(text) != len(info.text) or curEndPos == storyEndPos:
		# there is end of line.
		eol = True
	# replacing non-breaking space by simple space
	text = text.replace(chr(0xA0), " ")
	if _NVDAConfigManager.spaceOrTabAtEndAnomalyOption():
		if text[-1] == "\t" and eol:
			if len(text) not in errorPositions:
				errorPositions[len(text)] = []
			errorPositions[len(text)].append(("tabAtEnd", None))
		elif text[-1].isspace() and eol:
			if len(text) not in errorPositions:
				errorPositions[len(text)] = []
			errorPositions[len(text)].append(("spaceAtEnd", None))
	if _NVDAConfigManager.multipleContigousSpacesAnomalyOption():
		end = False
		temp = text
		dec = 0
		while not end:
			index = temp.find("  ")
			if index < 0:
				break
			pos = index + dec + 1
			if pos not in errorPositions:
				errorPositions[pos] = []
			errorPositions[pos].append(("multipleSpaces", None))
			temp = temp[index:].lstrip()
			if len(temp) == 0:
				break
			dec = text.find(temp)
Example #49
0
	def MTAThreadFunc(self):
		try:
			oledll.ole32.CoInitializeEx(None,comtypes.COINIT_MULTITHREADED) 
			isUIA8=False
			try:
				self.clientObject=CoCreateInstance(CUIAutomation8._reg_clsid_,interface=IUIAutomation,clsctx=CLSCTX_INPROC_SERVER)
				isUIA8=True
			except (COMError,WindowsError,NameError):
				self.clientObject=CoCreateInstance(CUIAutomation._reg_clsid_,interface=IUIAutomation,clsctx=CLSCTX_INPROC_SERVER)
			if isUIA8:
				# #8009: use appropriate interface based on highest supported interface.
				# #8338: made easier by traversing interfaces supported on Windows 8 and later in reverse.
				for interface in reversed(CUIAutomation8._com_interfaces_):
					try:
						self.clientObject=self.clientObject.QueryInterface(interface)
						break
					except COMError:
						pass
				# Windows 10 RS5 provides new performance features for UI Automation including event coalescing and connection recovery. 
				# Enable all of these where available.
				if isinstance(self.clientObject,IUIAutomation6):
					self.clientObject.CoalesceEvents=CoalesceEventsOptions_Enabled
					self.clientObject.ConnectionRecoveryBehavior=ConnectionRecoveryBehaviorOptions_Enabled
			log.info("UIAutomation: %s"%self.clientObject.__class__.__mro__[1].__name__)
			self.windowTreeWalker=self.clientObject.createTreeWalker(self.clientObject.CreateNotCondition(self.clientObject.CreatePropertyCondition(UIA_NativeWindowHandlePropertyId,0)))
			self.windowCacheRequest=self.clientObject.CreateCacheRequest()
			self.windowCacheRequest.AddProperty(UIA_NativeWindowHandlePropertyId)
			self.UIAWindowHandleCache={}
			self.baseTreeWalker=self.clientObject.RawViewWalker
			self.baseCacheRequest=self.windowCacheRequest.Clone()
			import UIAHandler
			self.ItemIndex_PropertyId=NVDAHelper.localLib.registerUIAProperty(byref(ItemIndex_Property_GUID),u"ItemIndex",1)
			self.ItemCount_PropertyId=NVDAHelper.localLib.registerUIAProperty(byref(ItemCount_Property_GUID),u"ItemCount",1)
			for propertyId in (UIA_FrameworkIdPropertyId,UIA_AutomationIdPropertyId,UIA_ClassNamePropertyId,UIA_ControlTypePropertyId,UIA_ProviderDescriptionPropertyId,UIA_ProcessIdPropertyId,UIA_IsTextPatternAvailablePropertyId,UIA_IsContentElementPropertyId,UIA_IsControlElementPropertyId):
				self.baseCacheRequest.addProperty(propertyId)
			self.baseCacheRequest.addPattern(UIA_TextPatternId)
			self.rootElement=self.clientObject.getRootElementBuildCache(self.baseCacheRequest)
			self.reservedNotSupportedValue=self.clientObject.ReservedNotSupportedValue
			self.ReservedMixedAttributeValue=self.clientObject.ReservedMixedAttributeValue
			self.clientObject.AddFocusChangedEventHandler(self.baseCacheRequest,self)
			self.clientObject.AddPropertyChangedEventHandler(self.rootElement,TreeScope_Subtree,self.baseCacheRequest,self,UIAPropertyIdsToNVDAEventNames.keys())
			for x in UIAEventIdsToNVDAEventNames.iterkeys():  
				self.clientObject.addAutomationEventHandler(x,self.rootElement,TreeScope_Subtree,self.baseCacheRequest,self)
			# #7984: add support for notification event (IUIAutomation5, part of Windows 10 build 16299 and later).
			if isinstance(self.clientObject, IUIAutomation5):
				self.clientObject.AddNotificationEventHandler(self.rootElement,TreeScope_Subtree,self.baseCacheRequest,self)
		except Exception as e:
			self.MTAThreadInitException=e
		finally:
			self.MTAThreadInitEvent.set()
		self.MTAThreadStopEvent.wait()
		self.clientObject.RemoveAllEventHandlers()
Example #50
0
def initialize():
	""" Initializes the add-ons subsystem. """
	if config.isAppX:
		log.info("Add-ons not supported when running as a Windows Store application")
		return
	loadState()
	removeFailedDeletions()
	completePendingAddonRemoves()
	completePendingAddonInstalls()
	# #3090: Are there add-ons that are supposed to not run for this session?
	disableAddonsIfAny()
	saveState()
	getAvailableAddons(refresh=True)
Example #51
0
def setFocusToWebApp(srcApp, webAppName):
    global activeWebApp

    if activeWebApp == srcApp:
        log.info("Posting setFocus event to ourself is not allowed.")
        return True
    for app in webModuleHandler.getWebModules():
        if app.name == webAppName:
            sendWebAppEvent('event_webApp_setFocus', srcApp, app)
            return True
    log.info("Set focus to webApp %s failed: Application not found.",
             webAppName)
    return False
Example #52
0
	def connectBluetooth(self):
		"""try to connect to bluetooth device first, bluetooth is only supported on Braillex Trio"""
		if(self._baud == 0 and self._dev is None):
			for portInfo in sorted(hwPortUtils.listComPorts(onlyAvailable=True), key=lambda item: "bluetoothName" in item):
				port = portInfo["port"]
				hwID = portInfo["hardwareID"]
				if "bluetoothName" in portInfo:
					if portInfo["bluetoothName"][0:14] == "braillex trio " or  portInfo["bluetoothName"][0:13] == "braillex live":
						try:
							self._dev = serial.Serial(port, baudrate = 57600,timeout = BLUETOOTH_TIMEOUT, writeTimeout = BLUETOOTH_TIMEOUT)
							log.info("connectBluetooth success")
						except:
							log.debugWarning("connectBluetooth failed")
Example #53
0
	def __init__(self, port="auto"):
		super(BrailleDisplayDriver, self).__init__()
		self.numCells = 0
		self._model = None
		self._ignoreKeyReleases = False
		self._keysDown = set()
		self._brailleInput = False
		self._hidSerialBuffer = ""

		if port == "auto":
			tryPorts = self._getAutoPorts(hwPortUtils.listComPorts(onlyAvailable=True))
		else:
			tryPorts = ((port, "serial"),)
		for port, portType in tryPorts:
			# At this point, a port bound to this display has been found.
			# Try talking to the display.
			self.isHid = portType.startswith("USB HID")
			self.isHidSerial = portType == "USB HID serial converter"
			try:
				if self.isHid:
					self._dev = hwIo.Hid(port, onReceive=self._onReceive)
					if self.isHidSerial:
						# This is either the standalone HID adapter cable for older displays,
						# or an older display with a HID - serial adapter built in
						# Send a flush to open the serial channel
						self._dev.write(HT_HID_RPT_InCommand + HT_HID_CMD_FlushBuffers)
				else:
					self._dev = hwIo.Serial(port, baudrate=BAUD_RATE, parity=PARITY,
						timeout=self.timeout, writeTimeout=self.timeout, onReceive=self._onReceive)
			except EnvironmentError:
				log.debugWarning("", exc_info=True)
				continue

			self.sendPacket(HT_PKT_RESET)
			for _i in xrange(3):
				# An expected response hasn't arrived yet, so wait for it.
				self._dev.waitForRead(self.timeout)
				if self.numCells and self._model:
					break

			if self.numCells:
				# A display responded.
				self._model.postInit()
				log.info("Found {device} connected via {type} ({port})".format(
					device=self._model.name, type=portType, port=port))
				break
			self._dev.close()

		else:
			raise RuntimeError("No Handy Tech display found")
Example #54
0
def _doSynthVoiceDictBackupAndMove(synthName, oldFileNameToNewFileNameList=None):
	""" Move all files for the synth to the backup dir for each file in the backup
	dir copy it to the synthvoice dir using the new name if it we have one.
	"""
	import shutil
	
	if not os.path.isdir(voiceDictsPath):
		os.makedirs(voiceDictsPath)
	if not os.path.isdir(voiceDictsBackupPath):
		os.makedirs(voiceDictsBackupPath)
	
	newDictPath = os.path.join(voiceDictsPath,synthName)
	needsUpgrade = not os.path.isdir(newDictPath)
	if needsUpgrade:
		log.info("Upgrading voice dictionaries for %s"%synthName)

		# always make the new directory, this prevents the upgrade from
		# occuring more than once.
		os.makedirs(newDictPath)

		# look for files that need to be upgraded  in the old voice 
		# dicts diectory
		voiceDictGlob=os.path.join(
				speechDictsPath,
				r"{synthName}*".format(synthName=synthName)
				)
		log.debug("voiceDictGlob: %s"%voiceDictGlob)

		for actualPath in glob.glob(voiceDictGlob):
			log.debug("processing file: %s" % actualPath)
			# files will be copied here before we modify them so as to avoid
			# any data loss.
			shutil.copy(actualPath, voiceDictsBackupPath)
			
			actualBasename = os.path.basename(actualPath)
			log.debug("basename: %s" % actualBasename)
			
			renameTo = actualBasename
			if oldFileNameToNewFileNameList:
				for oldFname, newFname in oldFileNameToNewFileNameList:
					if oldFname == actualBasename:
						log.debug("renaming {} to {} and moving to {}".format(
							actualPath,
							newFname,
							newDictPath
							))
						renameTo = newFname
						break
			shutil.move(actualPath, os.path.join(newDictPath, renameTo))
Example #55
0
def initialize():
	global handler
	config.addConfigDirsToPythonPackagePath(brailleDisplayDrivers)
	log.info("Using liblouis version %s" % louis.version())
	handler = BrailleHandler()
	handler.setDisplayByName(config.conf["braille"]["display"])

	# Update the display to the current focus/review position.
	if not handler.enabled or not api.getDesktopObject():
		# Braille is disabled or focus/review hasn't yet been initialised.
		return
	if handler.tether == handler.TETHER_FOCUS:
		handler.handleGainFocus(api.getFocusObject())
	else:
		handler.handleReviewMove()
Example #56
0
	def script_announceOWMForecast(self, gesture):
		if self.fetcher.client is None:
			ui.message("Loading, please wait and try again in a few seconds...")
			return

		client = self.fetcher.client
		if client.error:
			ui.message("{0} {1}".format(client.statusCode, client.errorReason))
			self.fetcher.valid = False
			self.fetcher = Fetcher()
			self.fetcher.start()
		else:
			forecast = client.forecast
			message = forecast.getMessage()
			ui.message(message)
			log.info(message)
Example #57
0
	def connectBrxCom(self):#connect to brxcom server (provided by papenmeier)
		try:
			brxcomkey=_winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE,"SOFTWARE\\FHP\\BrxCom")
			value, vtype = _winreg.QueryValueEx(brxcomkey, "InstallPath")
			_winreg.CloseKey(brxcomkey)
			self._brxnvda = c.cdll.LoadLibrary(str(value+"\\brxnvda.dll"))
			if(self._brxnvda.brxnvda_init(str(value+"\\BrxCom.dll").decode("mbcs"))==0):
				self._baud=1 #prevent bluetooth from connecting
				self.numCells=self._brxnvda.brxnvda_numCells();
				self._voffset=self._brxnvda.brxnvda_numVertCells();
				log.info("Found Braille Display connected via BRXCom")
				self.startTimer()
				return None
		except:
			log.debugWarning("BRXCom is not installed")
			self._brxnvda = None
	def save(self):
		"""Save all modified profiles and the base configuration to disk.
		"""
		if globalVars.appArgs.secure:
			# Never save the config if running securely.
			return
		try:
			self.profiles[0].write()
			log.info("Base configuration saved")
			for name in self._dirtyProfiles:
				self._profileCache[name].write()
				log.info("Saved configuration profile %s" % name)
			self._dirtyProfiles.clear()
		except Exception as e:
			log.warning("Error saving configuration; probably read only file system")
			log.debugWarning("", exc_info=True)
			raise e
Example #59
0
	def onOWMSettings(self, event):
		"""Pop a dialog with OWM settings."""
		locations = locationList.retrieve()
		selected = configFile['location']
		locationName = locationList.get(selected).name
		locationValues = {}
		for location in locations:
			locationValues[location.id] = (location.name, location.country)

		dialog = LocationDialog(gui.mainFrame, -1, "Select OWM Location",
				locationValues, locationName)
		gui.mainFrame.prePopup()
		ret = dialog.ShowModal()
		gui.mainFrame.postPopup()
		if ret == wx.ID_OK:
			log.info("Focused {0}, {1}".format(locationList.path,
					dialog.location.focusedLocationName))