示例#1
0
def newCpbDel(self):
	if hasattr(self, "_deleted"):
		# Don't allow this to be called more than once.
		log.debugWarning("COM pointer %r already deleted" % self)
		return
	_cpbDel(self)
	self._deleted = True
示例#2
0
	def _handleResponse(self, msgId, payload):
		if msgId == MSG_INIT_RESP:
			if ord(payload[0]) != 0:
				# Communication not allowed.
				log.debugWarning("Display at %r reports communication not allowed" % self._ser.port)
				return
			self.numCells = ord(payload[2])

		elif msgId == MSG_KEY_DOWN:
			payload = ord(payload)
			self._keysDown.add(payload)
			# This begins a new key combination.
			self._ignoreKeyReleases = False

		elif msgId == MSG_KEY_UP:
			payload = ord(payload)
			if not self._ignoreKeyReleases and self._keysDown:
				try:
					inputCore.manager.executeGesture(InputGesture(self._keysDown))
				except inputCore.NoInputGestureAction:
					pass
				# Any further releases are just the rest of the keys in the combination being released,
				# so they should be ignored.
				self._ignoreKeyReleases = True
			self._keysDown.discard(payload)

		else:
			log.debugWarning("Unknown message: id {id!r}, payload {payload!r}".format(id=msgId, payload=payload))
示例#3
0
	def _handleSystemPacket(self, type, data):
		if type==EB_SYSTEM_TYPE:
			deviceType = ord(data)
			self.deviceType = DEVICE_TYPES[deviceType]
			if 0x01<=deviceType<=0x06: # Iris
				self.keys = KEYS_IRIS
			elif 0x07<=deviceType<=0x0d: # Esys
				self.keys = KEYS_ESYS
			elif 0x0e<=deviceType<=0x11: # Esitime
				self.keys = KEYS_ESITIME
			else:
				log.debugWarning("Unknown device identifier %r"%data)
		elif type==EB_SYSTEM_DISPLAY_LENGTH:
			self.numCells = ord(data)
		elif type==EB_SYSTEM_FRAME_LENGTH:
			self._frameLength = bytesToInt(data)
		elif type==EB_SYSTEM_PROTOCOL and self.isHid:
			protocol = data.rstrip("\x00 ")
			try:
				version = float(protocol[:4])
			except ValueError:
				pass
			else:
				self.receivesAckPackets = version>=3.0
		elif type==EB_SYSTEM_IDENTITY:
			return # End of system information
		self._deviceData[type]=data.rstrip("\x00 ")
示例#4
0
	def onOk(self, evt):
		self.Destroy()
		if self.addCheckBox.Value or self.searchRadioBox.Selection < 2:  # Add or search
			text = self.searchTextEdit.Value
		actionToPerform = self.searchRadioBox.Selection
		if actionToPerform < 2:  # Search
			caseSensitive = self.caseSensitiveCheckBox.Value
			if actionToPerform == 0:
				core.callLater(1000, doFindText, text, caseSensitive=caseSensitive)
			else:
				core.callLater(1000, doFindTextUp, text, caseSensitive=caseSensitive)
		if self.addCheckBox.Value or self.removeCheckBox.Value:
			savedStrings = self.savedTexts
			if self.removeCheckBox.Value:
				del savedStrings[self.savedTextsComboBox.Selection]
			if self.addCheckBox.Value and not "\n" in text and not text in savedStrings:
				savedStrings.insert(0, text)
			if len(savedStrings) == 0:
				os.remove(self.searchFile)
				return
			try:
				with codecs.open(self.searchFile, "w", "utf-8") as f:
					f.write("\n".join(savedStrings))
			except Exception as e:
				log.debugWarning("Error saving strings of text for specific search", exc_info=True)
				raise e
	def _triggerProfileExit(self, trigger):
		"""Called by L{ProfileTrigger.exit}}}.
		"""
		if not self.profileTriggersEnabled:
			return
		if self._suspendedTriggers is not None:
			if trigger in self._suspendedTriggers:
				# This trigger was entered and is now being exited.
				# These cancel each other out.
				del self._suspendedTriggers[trigger]
			else:
				self._suspendedTriggers[trigger] = "exit"
			return

		profile = trigger._profile
		if profile is None:
			return
		profile.triggered = False
		try:
			self.profiles.remove(profile)
		except ValueError:
			# This is probably due to the user resetting the configuration.
			log.debugWarning("Profile not active when exiting trigger")
			return
		self._handleProfileSwitch()
示例#6
0
def doPreGainFocus(obj,sleepMode=False):
	oldForeground=api.getForegroundObject()
	oldFocus=api.getFocusObject()
	oldTreeInterceptor=oldFocus.treeInterceptor if oldFocus else None
	api.setFocusObject(obj)
	if globalVars.focusDifferenceLevel<=1:
		newForeground=api.getDesktopObject().objectInForeground()
		if not newForeground:
			log.debugWarning("Can not get real foreground, resorting to focus ancestors")
			ancestors=api.getFocusAncestors()
			if len(ancestors)>1:
				newForeground=ancestors[1]
			else:
				newForeground=obj
		api.setForegroundObject(newForeground)
		executeEvent('foreground',newForeground)
	if sleepMode: return True
	#Fire focus entered events for all new ancestors of the focus if this is a gainFocus event
	for parent in globalVars.focusAncestors[globalVars.focusDifferenceLevel:]:
		executeEvent("focusEntered",parent)
	if obj.treeInterceptor is not oldTreeInterceptor:
		if hasattr(oldTreeInterceptor,"event_treeInterceptor_loseFocus"):
			oldTreeInterceptor.event_treeInterceptor_loseFocus()
		if obj.treeInterceptor and obj.treeInterceptor.isReady and hasattr(obj.treeInterceptor,"event_treeInterceptor_gainFocus"):
			obj.treeInterceptor.event_treeInterceptor_gainFocus()
	return True
示例#7
0
	def onDelete(self, evt):
		if gui.messageBox(
			# Translators: The confirmation prompt displayed when the user requests to delete a bookmark.
			_("This bookmark will be permanently deleted. This action cannot be undone."),
			# Message translated in NVDA core.
			translate("Confirm Deletion"),
			wx.OK | wx.CANCEL | wx.ICON_QUESTION, self
		) != wx.OK:
			return
		del self.bookmarks[self.pos]
		if len(self.bookmarks.keys()) > 0:
			try:
				pickle.dump(self.bookmarks, file(self.fileName, "wb"))
				self.notesListBox.Delete(self.notesListBox.Selection)
				self.notesListBox.Selection = 0
				self.onNotesChange(None)
				self.notesListBox.SetFocus()
			except Exception as e:
				log.debugWarning("Error deleting bookmark", exc_info=True)
				raise e
		else:
			try:
				os.remove(self.fileName)
				self.Destroy()
				wx.CallAfter(gui.messageBox,
					# Translators: The message presented when all bookmarks have been deleted from the Notes dialog.
					_("No bookmarks"),
					# Translators: The title of the warning dialog when all bookmarks have been deleted.
					_("Bookmarks deleted"),
					wx.OK | wx.ICON_WARNING, None)
			except WindowsError:
				pass
示例#8
0
	def onDelete(self, evt):
		index = self.profileList.Selection
		if gui.messageBox(
			# Translators: The confirmation prompt displayed when the user requests to delete a configuration profile.
			_("This profile will be permanently deleted. This action cannot be undone."),
			# Translators: The title of the confirmation dialog for deletion of a configuration profile.
			_("Confirm Deletion"),
			wx.OK | wx.CANCEL | wx.ICON_QUESTION, self
		) != wx.OK:
			return
		name = self.profileNames[index]
		try:
			config.conf.deleteProfile(name)
		except:
			log.debugWarning("", exc_info=True)
			# Translators: An error displayed when deleting a configuration profile fails.
			gui.messageBox(_("Error deleting profile."),
				_("Error"), wx.OK | wx.ICON_ERROR, self)
			return
		del self.profileNames[index]
		self.profileList.Delete(index)
		self.profileList.SetString(0, self.getProfileDisplay(None, includeStates=True))
		self.profileList.Selection = 0
		self.onProfileListChoice(None)
		self.profileList.SetFocus()
示例#9
0
	def initOverlayClass(self):
		try:
			serv = self.IAccessibleObject.QueryInterface(IServiceProvider)
		except COMError:
			log.debugWarning("Could not get IServiceProvider")
			return

		if self.event_objectID > 0:
			self.accID = self.event_objectID
		elif self.event_childID > 0:
			self.accID = self.event_childID
		else:
			try:
				self.accID = serv.QueryService(SID_AccID, IAccID).get_accID()
			except COMError:
				self.accID = None

		# Get the IPDDomNode.
		try:
			self.pdDomNode = serv.QueryService(SID_GetPDDomNode, IGetPDDomNode).get_PDDomNode(self.IAccessibleChildID)
		except COMError:
			self.pdDomNode = None

		if self.pdDomNode:
			# If this node has IPDDomElement, query to that.
			try:
				self.pdDomNode = self.pdDomNode.QueryInterface(IPDDomElement)
			except COMError:
				pass
示例#10
0
	def onRename(self, evt):
		index = self.profileList.Selection
		oldName = self.profileNames[index]
		# Translators: The label of a field to enter a new name for a configuration profile.
		with wx.TextEntryDialog(self, _("New name:"),
				# Translators: The title of the dialog to rename a configuration profile.
				_("Rename Profile"), defaultValue=oldName) as d:
			if d.ShowModal() == wx.ID_CANCEL:
				return
			newName = api.filterFileName(d.Value)
		try:
			config.conf.renameProfile(oldName, newName)
		except ValueError:
			# Translators: An error displayed when renaming a configuration profile
			# and a profile with the new name already exists.
			gui.messageBox(_("That profile already exists. Please choose a different name."),
				_("Error"), wx.OK | wx.ICON_ERROR, self)
			return
		except:
			log.debugWarning("", exc_info=True)
			gui.messageBox(_("Error renaming profile."),
				_("Error"), wx.OK | wx.ICON_ERROR, self)
			return
		self.profileNames[index] = newName
		self.profileList.SetString(index, self.getProfileDisplay(newName, includeStates=True))
		self.profileList.Selection = index
		self.profileList.SetFocus()
示例#11
0
	def _handleResponse(self, command, arg):
		if command == BAUM_CELL_COUNT:
			self.numCells = ord(arg)
		elif command == BAUM_DEVICE_ID:
			self._deviceID = arg

		elif command in KEY_NAMES:
			arg = sum(ord(byte) << offset * 8 for offset, byte in enumerate(arg))
			if arg < self._keysDown.get(command, 0):
				# Release.
				if not self._ignoreKeyReleases:
					# The first key released executes the key combination.
					try:
						inputCore.manager.executeGesture(InputGesture(self._keysDown))
					except inputCore.NoInputGestureAction:
						pass
					# Any further releases are just the rest of the keys in the combination being released,
					# so they should be ignored.
					self._ignoreKeyReleases = True
			else:
				# Press.
				# This begins a new key combination.
				self._ignoreKeyReleases = False
			self._keysDown[command] = arg

		elif command == BAUM_POWERDOWN:
			log.debug("Power down")
		elif command in (BAUM_COMMUNICATION_CHANNEL, BAUM_SERIAL_NUMBER):
			pass

		else:
			log.debugWarning("Unknown command {command!r}, arg {arg!r}".format(command=command, arg=arg))
示例#12
0
文件: __init__.py 项目: bramd/nvda
	def _getPlaceholderAttribute(self, attrs, placeholderAttrsKey):
		"""Gets the placeholder attribute to be used.
		@return: The placeholder attribute when there is no content within the ControlField.
		None when the ControlField has content.
		@note: The content is considered empty if it holds a single space.
		"""
		placeholder = attrs.get(placeholderAttrsKey)
		# For efficiency, only check if it is valid to return placeholder when we have a placeholder value to return.
		if not placeholder:
			return None
		# Get the start and end offsets for the field. This can be used to check if the field has any content.
		try:
			start, end = self._getOffsetsFromFieldIdentifier(
				int(attrs.get('controlIdentifier_docHandle')),
				int(attrs.get('controlIdentifier_ID')))
		except (LookupError, ValueError):
			log.debugWarning("unable to get offsets used to fetch content")
			return placeholder
		else:
			valueLen = end - start
			if not valueLen: # value is empty, use placeholder
				return placeholder
			# Because fetching the content of the field could result in a large amount of text
			# we only do it in order to check for space.
			# We first compare the length by comparing the offsets, if the length is less than 2 (ie
			# could hold space)
			if valueLen < 2:
				controlFieldText = self.obj.makeTextInfo(textInfos.offsets.Offsets(start, end)).text
				if not controlFieldText or controlFieldText == ' ':
					return placeholder
		return None
示例#13
0
def getSynthList():
	synthList=[]
	# The synth that should be placed at the end of the list.
	lastSynth = None
	for loader, name, isPkg in pkgutil.iter_modules(synthDrivers.__path__):
		if name.startswith('_'):
			continue
		try:
			synth=_getSynthDriver(name)
		except:
			log.error("Error while importing SynthDriver %s"%name,exc_info=True)
			continue
		try:
			if synth.check():
				if synth.name == "silence":
					lastSynth = (synth.name,synth.description)
				else:
					synthList.append((synth.name,synth.description))
			else:
				log.debugWarning("Synthesizer '%s' doesn't pass the check, excluding from list"%name)
		except:
			log.error("",exc_info=True)
	synthList.sort(key=lambda s : s[1].lower())
	if lastSynth:
		synthList.append(lastSynth)
	return synthList
示例#14
0
	def script_saveBookmark(self, gesture):
		obj = api.getFocusObject()
		appName=appModuleHandler.getAppNameFromProcessID(obj.processID,True)
		if appName == "MicrosoftEdgeCP.exe":
			gesture.send()
			return
		treeInterceptor=obj.treeInterceptor
		if isinstance(treeInterceptor, BrowseModeDocumentTreeInterceptor) and not treeInterceptor.passThrough:
			obj=treeInterceptor
		else:
			gesture.send()
			return
		bookmark = obj.makeTextInfo(textInfos.POSITION_CARET).bookmark
		bookmarks = getSavedBookmarks()
		noteTitle = obj.makeTextInfo(textInfos.POSITION_SELECTION).text[:100].encode("utf-8")
		if bookmark.startOffset in bookmarks:
			noteBody = bookmarks[bookmark.startOffset].body
		else:
			noteBody = ""
		bookmarks[bookmark.startOffset] = Note(noteTitle, noteBody)
		fileName = getFileBookmarks()
		try:
			pickle.dump(bookmarks, file(fileName, "wb"))
			ui.message(
				# Translators: message presented when a position is saved as a bookmark.
				_("Saved position at character %d") % bookmark.startOffset)
		except Exception as e:
			log.debugWarning("Error saving bookmark", exc_info=True)
			ui.message(
				# Translators: message presented when a bookmark cannot be saved.
				_("Cannot save bookmark"))
			raise e
示例#15
0
文件: skype.py 项目: ehollig/nvda
	def _gainedFocus(self):
		# The user has entered this Skype conversation.
		if self.appModule.conversation:
			# Another conversation was previously focused. Clean it up.
			self.appModule.conversation.lostFocus()

		self.appModule.conversation = self
		try:
			self.outputList = NVDAObjects.IAccessible.getNVDAObjectFromEvent(
				windowUtils.findDescendantWindow(self.windowHandle, className="TChatContentControl"),
				winUser.OBJID_CLIENT, 0).lastChild
		except LookupError:
			log.debugWarning("Couldn't find output list")
			self.outputList = None
		else:
			self.outputList.startMonitoring()
		for wClass, role in TYPING_INDICATOR_MATCH:
			try:
				self.typingIndicator = NVDAObjects.IAccessible.getNVDAObjectFromEvent(
					windowUtils.findDescendantWindow(self.windowHandle, className=wClass),
					winUser.OBJID_CLIENT, 1)
			except LookupError:
				continue
			self.typingIndicator.startMonitoring()
			break
		else:
			log.debugWarning("Couldn't find typing indicator")
			self.typingIndicator = None
示例#16
0
	def event_stateChange(self):
		try:
			self._JABAccContextInfo=self.jabContext.getAccessibleContextInfo()
		except RuntimeError:
			log.debugWarning("Error getting accessible context info, probably dead object")
			return
		super(JAB,self).event_stateChange()
	def speak(self,speechSequence):
		"""
		Speaks the given sequence of text and speech commands.
		This base implementation will fallback to making use of the old speakText and speakCharacter methods. But new synths should override this method to support its full functionality.
		@param speechSequence: a list of text strings and SpeechCommand objects (such as index and parameter changes).
		@type speechSequence: list of string and L{speechCommand}
		"""
		import speech
		lastIndex=None
		text=""
		origSpeakFunc=self.speakText
		speechSequence=iter(speechSequence)
		while True:
			item = next(speechSequence,None)
			if text and (item is None or isinstance(item,(speech.IndexCommand,speech.CharacterModeCommand))):
				# Either we're about to handle a command or this is the end of the sequence.
				# Speak the text since the last command we handled.
				origSpeakFunc(text,index=lastIndex)
				text=""
				lastIndex=None
			if item is None:
				# No more items.
				break
			if isinstance(item,basestring):
				# Merge the text between commands into a single chunk.
				text+=item
			elif isinstance(item,speech.IndexCommand):
				lastIndex=item.index
			elif isinstance(item,speech.CharacterModeCommand):
				origSpeakFunc=self.speakCharacter if item.state else self.speakText
			elif isinstance(item,speech.SpeechCommand):
				log.debugWarning("Unknown speech command: %s"%item)
			else:
				log.error("Unknown item in speech sequence: %s"%item)
示例#18
0
文件: oneCore.py 项目: ehollig/nvda
	def __init__(self):
		super(SynthDriver, self).__init__()
		self._dll = NVDAHelper.getHelperLocalWin10Dll()
		self._dll.ocSpeech_getCurrentVoiceLanguage.restype = ctypes.c_wchar_p
		# Set initial values for parameters that can't be queried when prosody is not supported.
		# This initialises our cache for the value.
		# When prosody is supported, the values are used for cachign reasons.
		self._rate = 50
		self._pitch = 50
		self._volume = 100

		if self.supportsProsodyOptions:
			self._dll.ocSpeech_getPitch.restype = ctypes.c_double
			self._dll.ocSpeech_getVolume.restype = ctypes.c_double
			self._dll.ocSpeech_getRate.restype = ctypes.c_double
		else:
			log.debugWarning("Prosody options not supported")
		self._handle = self._dll.ocSpeech_initialize()
		self._callbackInst = ocSpeech_Callback(self._callback)
		self._dll.ocSpeech_setCallback(self._handle, self._callbackInst)
		self._dll.ocSpeech_getVoices.restype = NVDAHelper.bstrReturn
		self._dll.ocSpeech_getCurrentVoiceId.restype = ctypes.c_wchar_p
		self._player= None
		# Initialize state.
		self._queuedSpeech = []
		self._wasCancelled = False
		self._isProcessing = False
		# Initialize the voice to a sane default
		self.voice=self._getDefaultVoice()
示例#19
0
	def __init__(self, model, keys, isBrailleInput=False):
		super(InputGesture, self).__init__()
		self.model = model.genericName.replace(" ","")
		self.keys = set(keys)

		self.keyNames = names = []
		if isBrailleInput:
			self.dots = self._calculateDots()
		for key in keys:
			if isBrailleInput and (
				key in KEY_SPACES or (key in (KEY_LEFT, KEY_RIGHT) and isinstance(model,EasyBraille))
			):
				self.space = True
				names.append("space")
			elif isBrailleInput and key in KEY_DOTS:
				names.append("dot%d"%KEY_DOTS[key])
			elif KEY_ROUTING <= key < KEY_ROUTING + model.numCells:
				self.routingIndex = key - KEY_ROUTING
				names.append("routing")
			else:
				try:
					names.append(model.keys[key])
				except KeyError:
					log.debugWarning("Unknown key %d" % key)

		self.id = "+".join(names)
示例#20
0
文件: __init__.py 项目: jhomme/nvda
	def _reportErrorInPreviousWord(self):
		try:
			# self might be a descendant of the text control; e.g. Symphony.
			# We want to deal with the entire text, so use the caret object.
			info = api.getCaretObject().makeTextInfo(textInfos.POSITION_CARET)
			# This gets called for characters which might end a word; e.g. space.
			# The character before the caret is the word end.
			# The one before that is the last of the word, which is what we want.
			info.move(textInfos.UNIT_CHARACTER, -2)
			info.expand(textInfos.UNIT_CHARACTER)
			fields = info.getTextWithFields()
		except RuntimeError:
			return
		except:
			# Focus probably moved.
			log.debugWarning("Error fetching last character of previous word", exc_info=True)
			return
		for command in fields:
			if isinstance(command, textInfos.FieldCommand) and command.command == "formatChange" and command.field.get("invalid-spelling"):
				break
		else:
			# No error.
			return
		import nvwave
		nvwave.playWaveFile(r"waves\textError.wav")
示例#21
0
文件: espeak.py 项目: lpintes/NVDA
	def speak(self,speechSequence):
		defaultLanguage=self._language
		textList=[]
		langChanged=False
		for item in speechSequence:
			if isinstance(item,basestring):
				s=unicode(item)
				# Replace \01, as this is used for embedded commands.
				#Also replace < and > as espeak handles xml
				s=s.translate({ord(u'\01'):None,ord(u'<'):u'&lt;',ord(u'>'):u'&gt;'})
				textList.append(s)
			elif isinstance(item,speech.IndexCommand):
				textList.append("<mark name=\"%d\" />"%item.index)
			elif isinstance(item,speech.CharacterModeCommand):
				textList.append("<say-as interpret-as=\"characters\">" if item.state else "</say-as>")
			elif isinstance(item,speech.LangChangeCommand):
				if langChanged:
					textList.append("</voice>")
				textList.append("<voice xml:lang=\"%s\">"%(item.lang if item.lang else defaultLanguage).replace('_','-'))
				langChanged=True
			elif isinstance(item,speech.SpeechCommand):
				log.debugWarning("Unsupported speech command: %s"%item)
			else:
				log.error("Unknown speech: %s"%item)
		if langChanged:
			textList.append("</voice>")
		text=u"".join(textList)
		_espeak.speak(text)
示例#22
0
	def __init__(self, keys):
		super(InputGesture, self).__init__()
		self.keyCodes = set(keys)

		self.keyNames = names = set()
		isBrailleInput = True
		for key in self.keyCodes:
			if isBrailleInput:
				if DOT1_KEY <= key <= DOT8_KEY:
					self.dots |= 1 << (key - DOT1_KEY)
				elif key == SPACE_KEY:
					self.space = True
				else:
					# This is not braille input.
					isBrailleInput = False
					self.dots = 0
					self.space = False
			if key >= FIRST_ROUTING_KEY:
				names.add("routing")
				self.routingIndex = key - FIRST_ROUTING_KEY
			else:
				try:
					names.add(KEY_NAMES[key])
				except KeyError:
					log.debugWarning("Unknown key with id %d" % key)

		self.id = "+".join(names)
示例#23
0
	def _get_mathMl(self):
		from comtypes.gen.ISimpleDOM import ISimpleDOMNode
		try:
			node = self.IAccessibleObject.QueryInterface(ISimpleDOMNode)
			# Try the data-mathml attribute.
			attrNames = (BSTR * 1)("data-mathml")
			namespaceIds = (c_short * 1)(0)
			attr = node.attributesForNames(1, attrNames, namespaceIds)
			if attr:
				import mathPres
				if not mathPres.getLanguageFromMath(attr) and self.language:
					attr = mathPres.insertLanguageIntoMath(attr, self.language)
				return attr
			if self.IA2Attributes.get("tag") != "math":
				# This isn't MathML.
				raise LookupError
			if self.language:
				attrs = ' xml:lang="%s"' % self.language
			else:
				attrs = ""
			return "<math%s>%s</math>" % (attrs, node.innerHTML)
		except COMError:
			log.debugWarning("Error retrieving math. "
				"Not supported in this browser or ISimpleDOM COM proxy not registered.", exc_info=True)
			raise LookupError
示例#24
0
	def getTextWithFields(self,formatConfig=None):
		if not formatConfig:
			formatConfig=config.conf['documentFormatting']
		formatConfig['autoLanguageSwitching']=config.conf['speech'].get('autoLanguageSwitching',False)
		startOffset=self._rangeObj.start
		endOffset=self._rangeObj.end
		if startOffset==endOffset:
			return []
		text=BSTR()
		formatConfigFlags=sum(y for x,y in formatConfigFlagsMap.iteritems() if formatConfig.get(x,False))
		res=NVDAHelper.localLib.nvdaInProcUtils_winword_getTextInRange(self.obj.appModule.helperLocalBindingHandle,self.obj.windowHandle,startOffset,endOffset,formatConfigFlags,ctypes.byref(text))
		if res or not text:
			log.debugWarning("winword_getTextInRange failed with %d"%res)
			return [self.text]
		commandList=XMLFormatting.XMLTextParser().parse(text.value)
		for index,item in enumerate(commandList):
			if isinstance(item,textInfos.FieldCommand):
				field=item.field
				if isinstance(field,textInfos.ControlField):
					item.field=self._normalizeControlField(field)
				elif isinstance(field,textInfos.FormatField):
					item.field=self._normalizeFormatField(field)
			elif index>0 and isinstance(item,basestring) and item.isspace():
				 #2047: don't expose language for whitespace as its incorrect for east-asian languages 
				lastItem=commandList[index-1]
				if isinstance(lastItem,textInfos.FieldCommand) and isinstance(lastItem.field,textInfos.FormatField):
					try:
						del lastItem.field['language']
					except KeyError:
						pass
		return commandList
示例#25
0
def initialize():
	global state, _stateFilename, autoChecker
	_stateFilename = os.path.join(globalVars.appArgs.configPath, "updateCheckState.pickle")
	try:
		state = cPickle.load(file(_stateFilename, "r"))
	except:
		log.debugWarning("Couldn't retrieve update state", exc_info=True)
		# Defaults.
		state = {
			"lastCheck": 0,
			"dontRemindVersion": None,
		}
		_setStateToNone(state)

	# check the pending version against the current version
	# and make sure that pendingUpdateFile and pendingUpdateVersion are part of the state dictionary.
	if "pendingUpdateVersion" not in state or state["pendingUpdateVersion"] == versionInfo.version:
		_setStateToNone(state)
	# remove all update files except the one that is currently pending (if any)
	try:
		for fileName in os.listdir(storeUpdatesDir):
			f=os.path.join(storeUpdatesDir, fileName)
			if f != state["pendingUpdateFile"]:
				os.remove(f)
				log.debug("Update file %s removed"%f)
	except OSError:
		log.warning("Unable to remove old update file %s"%f, exc_info=True)

	if not globalVars.appArgs.launcher and (config.conf["update"]["autoCheck"] or (config.conf["update"]["startupNotification"] and isPendingUpdate())):
		autoChecker = AutoUpdateChecker()
示例#26
0
def disconnectConsole():
	global consoleObject, consoleOutputHandle, consoleWinEventHookHandles, checkDeadTimer
	if not consoleObject:
		log.debugWarning("console was not connected")
		return False
	checkDeadTimer.Stop()
	checkDeadTimer=None
	#Unregister any win events we are using
	for handle in consoleWinEventHookHandles:
		winUser.unhookWinEvent(handle)
	consoleEventHookHandles=[]
	consoleObject.stopMonitoring()
	winKernel.closeHandle(consoleOutputHandle)
	consoleOutputHandle=None
	consoleObject=None
	try:
		wincon.SetConsoleCtrlHandler(_consoleCtrlHandler,False)
	except WindowsError:
		pass
	#Try freeing NVDA from this console
	try:
		wincon.FreeConsole()
	except WindowsError:
		pass
	return True
示例#27
0
def recognizeNavigatorObject(recognizer):
	"""User interface function to recognize content in the navigator object.
	This should be called from a script or in response to a GUI action.
	@param recognizer: The content recognizer to use.
	@type recognizer: L{contentRecog.ContentRecognizer}
	"""
	global _activeRecog
	if isinstance(api.getFocusObject(), RecogResultNVDAObject):
		# Translators: Reported when content recognition (e.g. OCR) is attempted,
		# but the user is already reading a content recognition result.
		ui.message(_("Already in a content recognition result"))
		return
	nav = api.getNavigatorObject()
	# Translators: Reported when content recognition (e.g. OCR) is attempted,
	# but the content is not visible.
	notVisibleMsg = _("Content is not visible")
	try:
		left, top, width, height = nav.location
	except TypeError:
		log.debugWarning("Object returned location %r" % nav.location)
		ui.message(notVisibleMsg)
		return
	try:
		imgInfo = RecogImageInfo.createFromRecognizer(left, top, width, height, recognizer)
	except ValueError:
		ui.message(notVisibleMsg)
		return
	if _activeRecog:
		_activeRecog.cancel()
	# Translators: Reporting when content recognition (e.g. OCR) begins.
	ui.message(_("Recognizing"))
	sb = screenBitmap.ScreenBitmap(imgInfo.recogWidth, imgInfo.recogHeight)
	pixels = sb.captureImage(left, top, width, height)
	_activeRecog = recognizer
	recognizer.recognize(pixels, imgInfo, _recogOnResult)
示例#28
0
	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
示例#29
0
def accessibleObjectFromEvent(window,objectID,childID):
	try:
		pacc,childID=oleacc.AccessibleObjectFromEvent(window,objectID,childID)
	except Exception as e:
		log.debugWarning("oleacc.AccessibleObjectFromEvent with window %s, objectID %s and childID %s: %s"%(window,objectID,childID,e))
		return None
	return (normalizeIAccessible(pacc,childID),childID)
示例#30
0
def tryRemoveFile(path,numRetries=6,retryInterval=0.5,rebootOK=False):
	dirPath=os.path.dirname(path)
	tempPath=tempfile.mktemp(dir=dirPath)
	try:
		os.rename(path,tempPath)
	except (WindowsError,IOError):
		raise RetriableFailure("Failed to rename file %s before  remove"%path)
	for count in xrange(numRetries):
		try:
			if os.path.isdir(tempPath):
				shutil.rmtree(tempPath)
			else:
				os.remove(tempPath)
			return
		except OSError:
			pass
		time.sleep(retryInterval)
	if rebootOK:
		log.debugWarning("Failed to delete file %s, marking for delete on reboot"%tempPath)
		MoveFileEx=windll.kernel32.MoveFileExW if isinstance(tempPath,unicode) else windll.kernel32.MoveFileExA
		MoveFileEx("\\\\?\\"+tempPath,None,4)
		return
	try:
		os.rename(tempPath,path)
	except:
		log.error("Unable to rename back to %s before retriable failier"%path)
	raise RetriableFailure("File %s could not be removed"%path)
示例#31
0
 def _bg(self):
     success = False
     for url in self.urls:
         try:
             self._download(url)
         except:
             log.debugWarning("Error downloading %s" % url, exc_info=True)
         else:  #Successfully downloaded or canceled
             if not self._shouldCancel:
                 success = True
             break
     else:
         # None of the URLs succeeded.
         self._guiExec(self._error)
         return
     if not success:
         try:
             os.remove(self.destPath)
         except OSError:
             pass
         return
     self._guiExec(self._downloadSuccess)
示例#32
0
 def _initTts(self, voice=None):
     self.tts = comtypes.client.CreateObject(self.COM_CLASS)
     if voice:
         # #749: It seems that SAPI 5 doesn't reset the audio parameters when the voice is changed,
         # but only when the audio output is changed.
         # Therefore, set the voice before setting the audio output.
         # Otherwise, we will get poor speech quality in some cases.
         self.tts.voice = voice
     outputDeviceID = nvwave.outputDeviceNameToID(
         config.conf["speech"]["outputDevice"], True)
     if outputDeviceID >= 0:
         self.tts.audioOutput = self.tts.getAudioOutputs()[outputDeviceID]
     self._eventsConnection = comtypes.client.GetEvents(
         self.tts, SapiSink(weakref.ref(self)))
     self.tts.EventInterests = constants.SVEBookmark | constants.SVEEndInputStream
     from comInterfaces.SpeechLib import ISpAudio
     try:
         self.ttsAudioStream = self.tts.audioOutputStream.QueryInterface(
             ISpAudio)
     except COMError:
         log.debugWarning("SAPI5 voice does not support ISPAudio")
         self.ttsAudioStream = None
示例#33
0
 def _dispatch(self, command, arg):
     space = False
     if command == THUNB_KEYS_TAG:
         gesture = InputGesture(keys=arg)
     elif command == CURSOR_KEY_TAG:
         gesture = InputGesture(routing=arg)
     elif command in (DOTS_TAG, DOTS_SPACE_TAG, DOTS_ENTER_TAG,
                      DOTS_BACKSPACE_TAG):
         if command != DOTS_TAG:
             space = True
         if command == DOTS_ENTER_TAG:
             # Stuppid bug in the implementation
             # Force dot8 here, although it should be already there
             arg |= DOT_8
         gesture = InputGesture(dots=arg, space=space)
     else:
         log.debugWarning("Unknown command")
         return
     try:
         inputCore.manager.executeGesture(gesture)
     except inputCore.NoInputGestureAction:
         pass
示例#34
0
def callback(wav,numsamples,event):
	try:
		global player, isSpeaking, lastIndex
		if not isSpeaking:
			return 1
		for e in event:
			if e.type==espeakEVENT_MARK:
				lastIndex=int(e.id.name)
			elif e.type==espeakEVENT_LIST_TERMINATED:
				break
		if not wav:
			player.idle()
			isSpeaking = False
			return 0
		if numsamples > 0:
			try:
				player.feed(string_at(wav, numsamples * sizeof(c_short)))
			except:
				log.debugWarning("Error feeding audio to nvWave",exc_info=True)
		return 0
	except:
		log.error("callback", exc_info=True)
示例#35
0
 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()
     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
示例#36
0
def connectConsole(obj):
	global consoleObject, consoleOutputHandle, checkDeadTimer
	#Get the process ID of the console this NVDAObject is fore
	processID,threadID=winUser.getWindowThreadProcessID(obj.windowHandle)
	#Attach NVDA to this console so we can access its text etc
	try:
		wincon.AttachConsole(processID)
	except WindowsError as e:
		log.debugWarning("Could not attach console: %s"%e)
		return False
	wincon.SetConsoleCtrlHandler(_consoleCtrlHandler,True)
	consoleOutputHandle=winKernel.CreateFile(u"CONOUT$",winKernel.GENERIC_READ|winKernel.GENERIC_WRITE,winKernel.FILE_SHARE_READ|winKernel.FILE_SHARE_WRITE,None,winKernel.OPEN_EXISTING,0,None)                                                     
	#Register this callback with all the win events we need, storing the given handles for removal later
	for eventID in (winUser.EVENT_CONSOLE_CARET,winUser.EVENT_CONSOLE_UPDATE_REGION,winUser.EVENT_CONSOLE_UPDATE_SIMPLE,winUser.EVENT_CONSOLE_UPDATE_SCROLL,winUser.EVENT_CONSOLE_LAYOUT):
		handle=winUser.setWinEventHook(eventID,eventID,0,consoleWinEventHook,0,0,0)
		if not handle:
			raise OSError("could not register eventID %s"%eventID)
		consoleWinEventHookHandles.append(handle)
	consoleObject=obj
	checkDeadTimer=wx.PyTimer(_checkDead)
	checkDeadTimer.Start(CHECK_DEAD_INTERVAL)
	return True
示例#37
0
def locateHTMLElementByID(document, ID):
    try:
        elements = document.getElementsByName(ID)
        if elements is not None:
            element = elements.item(0)
        else:  #probably IE 10 in standards mode (#3151)
            try:
                element = document.all.item(ID)
            except:
                element = None
        if element is None:  #getElementsByName doesn't return element with specified ID in IE11 (#5784)
            try:
                element = document.getElementByID(ID)
            except COMError as e:
                log.debugWarning(
                    "document.getElementByID failed with COMError %s" % e)
                element = None
    except COMError as e:
        log.debugWarning("document.getElementsByName failed with COMError %s" %
                         e)
        element = None
    if element:
        return element
    try:
        nodeName = document.body.nodeName
    except COMError as e:
        log.debugWarning("document.body.nodeName failed with COMError %s" % e)
        return None
    if nodeName:
        nodeName = nodeName.upper()
    if nodeName == "FRAMESET":
        tag = "frame"
    else:
        tag = "iframe"
    try:
        frames = document.getElementsByTagName(tag)
    except COMError as e:
        log.debugWarning(
            "document.getElementsByTagName failed with COMError %s" % e)
        return None
    if not frames:  #frames can be None in IE 10
        return None
    for frame in frames:
        childElement = getChildHTMLNodeFromFrame(frame)
        if not childElement:
            continue
        childElement = locateHTMLElementByID(childElement.document, ID)
        if not childElement: continue
        return childElement
示例#38
0
    def _callback(self, bytes, len, markers):
        if len == 0:
            # The C++ code will log an error with details.
            log.debugWarning("ocSpeech_speak failed!")
            self._processQueue()
            return
        # This gets called in a background thread.
        stream = io.BytesIO(ctypes.string_at(bytes, len))
        wav = wave.open(stream, "r")
        self._maybeInitPlayer(wav)
        data = wav.readframes(wav.getnframes())
        if markers:
            markers = markers.split('|')
        else:
            markers = []
        prevPos = 0

        # Push audio up to each marker so we can sync the audio with the markers.
        for marker in markers:
            if self._wasCancelled:
                break
            name, pos = marker.split(':')
            index = int(name)
            pos = int(pos)
            # pos is a time offset in 100-nanosecond units.
            # Convert this to a byte offset.
            # Order the equation so we don't have to do floating point.
            pos = pos * self._bytesPerSec // HUNDRED_NS_PER_SEC
            # Push audio up to this marker.
            self._player.feed(data[prevPos:pos],
                              onDone=lambda index=index: synthIndexReached.
                              notify(synth=self, index=index))
            prevPos = pos
        if self._wasCancelled:
            log.debug("Cancelled, stopped pushing audio")
        else:
            self._player.feed(data[prevPos:])
            log.debug("Done pushing audio")
        self._processQueue()
示例#39
0
 def IUIAutomationFocusChangedEventHandler_HandleFocusChangedEvent(
         self, sender):
     if not self.MTAThreadInitEvent.isSet():
         # UIAHandler hasn't finished initialising yet, so just ignore this event.
         if _isDebug():
             log.debug(
                 "HandleFocusChangedEvent: event received while not fully initialized"
             )
         return
     self.lastFocusedUIAElement = sender
     if not self.isNativeUIAElement(sender):
         if _isDebug():
             log.debug(
                 "HandleFocusChangedEvent: Ignoring for non native element")
         return
     import NVDAObjects.UIA
     if isinstance(eventHandler.lastQueuedFocusObject, NVDAObjects.UIA.UIA):
         lastFocusObj = eventHandler.lastQueuedFocusObject
         # Ignore duplicate focus events.
         # It seems that it is possible for compareElements to return True, even though the objects are different.
         # Therefore, don't ignore the event if the last focus object has lost its hasKeyboardFocus state.
         try:
             if (not lastFocusObj.shouldAllowDuplicateUIAFocusEvent
                     and self.clientObject.compareElements(
                         sender, lastFocusObj.UIAElement)
                     and lastFocusObj.UIAElement.currentHasKeyboardFocus):
                 if _isDebug():
                     log.debugWarning(
                         "HandleFocusChangedEvent: Ignoring duplicate focus event"
                     )
                 return
         except COMError:
             if _isDebug():
                 log.debugWarning(
                     "HandleFocusChangedEvent: Couldn't check for duplicate focus event",
                     exc_info=True)
     window = self.getNearestWindowHandle(sender)
     if window and not eventHandler.shouldAcceptEvent("gainFocus",
                                                      windowHandle=window):
         if _isDebug():
             log.debug(
                 "HandleFocusChangedEvent: Ignoring for shouldAcceptEvent=False"
             )
         return
     try:
         obj = NVDAObjects.UIA.UIA(UIAElement=sender)
     except Exception:
         if _isDebug():
             log.debugWarning(
                 "HandleFocusChangedEvent: Exception while creating object",
                 exc_info=True)
         return
     if not obj or not obj.shouldAllowUIAFocusEvent:
         if _isDebug():
             log.debug(
                 "HandleFocusChangedEvent: Ignoring because no object or ignored by object itself"
             )
         return
     eventHandler.queueEvent("gainFocus", obj)
示例#40
0
文件: handyTech.py 项目: latys/nvda
    def __init__(self, model, keys, isBrailleInput=False):
        super(InputGesture, self).__init__()
        self.model = model.genericName
        self.keys = set(keys)

        self.keyNames = names = []
        for key in keys:
            if isBrailleInput:
                self.dots = self._calculateDots()
                if key in KEY_SPACES or (key in (KEY_LEFT, KEY_RIGHT)
                                         and isinstance(model, EasyBraille)):
                    self.space = True
            if KEY_ROUTING <= key < KEY_ROUTING + model.numCells:
                self.routingIndex = key - KEY_ROUTING
                names.append("routing")
            elif not isBrailleInput:
                try:
                    names.append(model.keys[key])
                except KeyError:
                    log.debugWarning("Unknown key %d" % key)

        self.id = "+".join(names)
示例#41
0
    def __init__(self, keys):
        super(InputGesture, self).__init__()
        self.keyCodes = set(keys)

        self.keyNames = names = set()
        for group, number in self.keyCodes:
            if group == ALVA_CR_GROUP:
                if number & ALVA_2ND_CR_MASK:
                    names.add("routing2")
                    self.routingIndex = number & ~ALVA_2ND_CR_MASK
                else:
                    names.add("routing")
                    self.routingIndex = number
            else:
                try:
                    names.add(ALVA_KEYS[group][number])
                except (KeyError, IndexError):
                    log.debugWarning(
                        "Unknown key with group %d and number %d" %
                        (group, number))

        self.id = "+".join(names)
示例#42
0
	def script_saveTempBookmark(self, gesture):
		obj = api.getFocusObject()
		appName=appModuleHandler.getAppNameFromProcessID(obj.processID,True)
		if appName == "MicrosoftEdgeCP.exe":
			gesture.send()
			return
		treeInterceptor=obj.treeInterceptor
		if isinstance(treeInterceptor, BrowseModeDocumentTreeInterceptor) and not treeInterceptor.passThrough:
			obj=treeInterceptor
		else:
			gesture.send()
			return
		bookmark = obj.makeTextInfo(textInfos.POSITION_CARET).bookmark
		fileName = getFileTempBookmark()
		try:
			with codecs.open(fileName, "w", "utf-8") as f:
				f.write(str(bookmark.startOffset))
				# Translators: Message presented when a temporary bookmark is saved.
				ui.message(_("Saved temporary bookmark at position %d" % bookmark.startOffset))
		except Exception as e:
			log.debugWarning("Error saving temporary bookmark", exc_info=True)
			raise e
示例#43
0
	def __init__(self, port="auto"):
		super(BrailleDisplayDriver,self).__init__()
		self.numCells = 0
		self._rawKeyboardInput = False
		self._deviceId = None

		for portType, portId, port, portInfo in self._getTryPorts(port):
			self.isHid = portType == bdDetect.KEY_HID
			# Try talking to the display.
			try:
				if self.isHid:
					self._dev = hwIo.Hid(port, onReceive=self._hidOnReceive)
					self._deviceId = int(portId[-2:],16)
				else:
					self._dev = hwIo.Serial(port, timeout=self.timeout, writeTimeout=self.timeout, onReceive=self._ser6OnReceive)
					# Get the device ID
					self._ser6SendMessage(b"?", b"?")
					for i in xrange(3):
						self._dev.waitForRead(self.timeout)
						if self._deviceId: # Display responded
							break
					else: # No response from display
						continue
			except EnvironmentError:
				log.debugWarning("", exc_info=True)
				continue
			self._updateSettings()
			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
			self._dev.close()

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

		self._keysDown = set()
		self._ignoreKeyReleases = False
示例#44
0
def showHelp(helpId: str):
	"""Display the corresponding section of the user guide when either the Help
	button in an NVDA dialog is pressed or the F1 key is pressed on a
	recognized control.
	"""

	import ui
	import queueHandler
	if not helpId:
		# Translators: Message indicating no context sensitive help is available for the control or dialog.
		noHelpMessage = _("No help available here.")
		queueHandler.queueFunction(queueHandler.eventQueue, ui.message, noHelpMessage)
		return
	helpFile = documentationUtils.getDocFilePath("userGuide.html")
	if helpFile is None:
		# Translators: Message shown when trying to display context sensitive help,
		# indicating that	the user guide could not be found.
		noHelpMessage = _("No user guide found.")
		log.debugWarning("No user guide found: possible cause - running from source without building user docs")
		queueHandler.queueFunction(queueHandler.eventQueue, ui.message, noHelpMessage)
		return
	log.debug(f"Opening help: helpId = {helpId}, userGuidePath: {helpFile}")

	nvdaTempDir = os.path.join(tempfile.gettempdir(), "nvda")
	if not os.path.exists(nvdaTempDir):
		os.mkdir(nvdaTempDir)

	contextHelpRedirect = os.path.join(nvdaTempDir, "contextHelp.html")
	try:
		# a redirect is necessary because not all browsers support opening a fragment URL from the command line.
		writeRedirect(helpId, helpFile, contextHelpRedirect)
	except Exception:
		log.error("Unable to write context help redirect file.", exc_info=True)
		return

	try:
		os.startfile(f"file://{contextHelpRedirect}")
	except Exception:
		log.error("Unable to launch context help.", exc_info=True)
示例#45
0
    def _getDTE(self):
        # Return the already fetched instance if there is one.
        try:
            if self._DTE:
                return self._DTE
        except AttributeError:
            pass

        # Retrieve and cache the top level automation object for the IDE
        DTEVersion = VsVersion_None
        bctx = objbase.CreateBindCtx()
        ROT = objbase.GetRunningObjectTable()
        for mon in ROT:
            # Test for the strings Visual Studio may have registered with.
            displayName = mon.GetDisplayName(bctx, None)
            if "!VisualStudio.DTE.9.0:%d" % self.processID == displayName:
                DTEVersion = VsVersion_2008
            elif "!VisualStudio.DTE.8.0:%d" % self.processID == displayName:
                DTEVersion = VsVersion_2005
            elif "!VisualStudio.DTE.7.1:%d" % self.processID == displayName:
                DTEVersion = VsVersion_2003
            elif "!VisualStudio.DTE:%d" % self.processID == displayName:
                DTEVersion = VsVersion_2002

            if DTEVersion != VsVersion_None:
                self._DTEVersion = DTEVersion
                self._DTE = comtypes.client.dynamic.Dispatch(
                    ROT.GetObject(mon).QueryInterface(IDispatch))
                break

        else:
            # None found.
            log.debugWarning("No top level automation object found")
            self._DTE = None
            self._DTEVersion = VsVersion_None

        # Loop has completed
        return self._DTE
示例#46
0
文件: __init__.py 项目: hss16/nvda
def shouldUseUIAInMSWord(appModule: appModuleHandler.AppModule) -> bool:
    allow = AllowUiaInMSWord.getConfig()
    if allow == AllowUiaInMSWord.ALWAYS:
        log.debug("User has requested UIA in MS Word always")
        return True
    canUseOlderInProcessApproach = bool(appModule.helperLocalBindingHandle)
    if not canUseOlderInProcessApproach:
        log.debug(
            "Using UIA in MS Word as no alternative object model available")
        return True
    if winVersion.getWinVer() < winVersion.WIN11:
        log.debug(
            "Not using UIA in MS Word on pre Windows 11 OS due to missing custom extensions"
        )
        return False
    if allow != AllowUiaInMSWord.WHERE_SUITABLE:
        log.debug("User does not want UIA in MS Word unless necessary")
        return False
    isOfficeApp = appModule.productName.startswith(
        ("Microsoft Office", "Microsoft Outlook"))
    if not isOfficeApp:
        log.debug(f"Unknown Office app: {appModule.productName}")
        return False
    try:
        officeVersion = tuple(
            int(x) for x in appModule.productVersion.split('.')[:3])
    except Exception:
        log.debugWarning(
            f"Unable to parse office version: {appModule.productVersion}",
            exc_info=True)
        return False
    if officeVersion < (16, 0, 15000):
        log.debug(
            f"MS word too old for suitable UIA, Office version: {officeVersion}"
        )
        return False
    log.debug(f"Using UIA due to suitable Office version: {officeVersion}")
    return True
示例#47
0
def _watcher():
	global isAttemptingRecovery
	while True:
		# Wait for the core to die.
		winKernel.waitForSingleObject(_coreDeadTimer, winKernel.INFINITE)
		if not isRunning:
			return
		# The core hasn't reported alive for MIN_CORE_ALIVE_TIMEOUT.
		waited = MIN_CORE_ALIVE_TIMEOUT
		while not _isAlive() and not _shouldRecoverAfterMinTimeout():
			# The core is still dead and fast recovery doesn't apply.
			# Wait up to NORMAL_ALIVE_TIMEOUT.
			time.sleep(MIN_CORE_ALIVE_TIMEOUT)
			waited += MIN_CORE_ALIVE_TIMEOUT
			if waited >= NORMAL_CORE_ALIVE_TIMEOUT:
				break
		if _isAlive():
			continue
		if log.isEnabledFor(log.DEBUGWARNING):
			log.debugWarning("Trying to recover from freeze, core stack:\n%s"%
				"".join(traceback.format_stack(sys._current_frames()[core.mainThreadId])))
		lastTime=time.time()
		isAttemptingRecovery = True
		# Cancel calls until the core is alive.
		# This event will be reset by alive().
		windll.kernel32.SetEvent(_cancelCallEvent)
		# Some calls have to be killed individually.
		while True:
			curTime=time.time()
			if curTime-lastTime>FROZEN_WARNING_TIMEOUT:
				lastTime=curTime
				log.warning("Core frozen in stack:\n%s"%
					"".join(traceback.format_stack(sys._current_frames()[core.mainThreadId])))
			_recoverAttempt()
			time.sleep(RECOVER_ATTEMPT_INTERVAL)
			if _isAlive():
				break
		isAttemptingRecovery = False
示例#48
0
 def IUIAutomationNotificationEventHandler_HandleNotificationEvent(
         self, sender, NotificationKind, NotificationProcessing,
         displayString, activityId):
     if not self.MTAThreadInitEvent.isSet():
         # UIAHandler hasn't finished initialising yet, so just ignore this event.
         if _isDebug():
             log.debug(
                 "HandleNotificationEvent: event received while not fully initialized"
             )
         return
     import NVDAObjects.UIA
     try:
         obj = NVDAObjects.UIA.UIA(UIAElement=sender)
     except Exception:
         if _isDebug():
             log.debugWarning(
                 "HandleNotificationEvent: Exception while creating object: "
                 f"NotificationProcessing={NotificationProcessing} "
                 f"displayString={displayString} "
                 f"activityId={activityId}",
                 exc_info=True)
         return
     if not obj:
         # Sometimes notification events can be fired on a UIAElement that has no windowHandle and does not connect through parents back to the desktop.
         # There is nothing we can do with these.
         if _isDebug():
             log.debug(
                 "HandleNotificationEvent: Ignoring because no object: "
                 f"NotificationProcessing={NotificationProcessing} "
                 f"displayString={displayString} "
                 f"activityId={activityId}")
         return
     eventHandler.queueEvent("UIA_notification",
                             obj,
                             notificationKind=NotificationKind,
                             notificationProcessing=NotificationProcessing,
                             displayString=displayString,
                             activityId=activityId)
示例#49
0
    def _saveSpecificSettings(cls, clsOrInst: Any,
                              settings: SupportedSettingType) -> None:
        """
		Save values for settings to config.
		The values from the attributes of `clsOrInst` that match the `id` of each setting are saved to config.
		@param clsOrInst: Destination for the values.
		@param settings: The settings to load.
		"""
        section = cls._getConfigSection()
        settingsId = cls.getId()
        conf = config.conf[section][settingsId]
        for setting in settings:
            if not setting.useConfig:
                continue
            try:
                conf[setting.id] = getattr(clsOrInst, setting.id)
            except UnsupportedConfigParameterError:
                log.debugWarning(
                    f"Unsupported setting {setting.id!r}; ignoring",
                    exc_info=True)
                continue
        if settings:
            log.debug(f"Saved settings for {cls.__qualname__}")
示例#50
0
 def onPostponeButton(self, evt):
     finalDest = os.path.join(storeUpdatesDir,
                              os.path.basename(self.destPath))
     try:
         os.renames(self.destPath, finalDest)
     except:
         log.debugWarning("Unable to rename the file from {} to {}".format(
             self.destPath, finalDest),
                          exc_info=True)
         gui.messageBox(
             # Translators: The message when a downloaded update file could not be preserved.
             _("Unable to postpone update."),
             # Translators: The title of the message when a downloaded update file could not be preserved.
             _("Error"),
             wx.OK | wx.ICON_ERROR)
         finalDest = self.destPath
     state["pendingUpdateFile"] = finalDest
     state["pendingUpdateVersion"] = self.version
     # Postponing an update indicates that the user is likely interested in getting a reminder.
     # Therefore, clear the dontRemindVersion.
     state["dontRemindVersion"] = None
     saveState()
     self.EndModal(wx.ID_CLOSE)
示例#51
0
	def __init__(
			self,
			parent: wx.Window,
			providerControl: VisionProviderStateControl
	):
		self._providerControl = providerControl
		initiallyEnabledInConfig = NVDAHighlighter.isEnabledInConfig()
		if not initiallyEnabledInConfig:
			settingsStorage = self._getSettingsStorage()
			settingsToCheck = [
				settingsStorage.highlightBrowseMode,
				settingsStorage.highlightFocus,
				settingsStorage.highlightNavigator,
			]
			if any(settingsToCheck):
				log.debugWarning(
					"Highlighter disabled in config while some of its settings are enabled. "
					"This will be corrected"
				)
				settingsStorage.highlightBrowseMode = False
				settingsStorage.highlightFocus = False
				settingsStorage.highlightNavigator = False
		super().__init__(parent)
示例#52
0
 def _get__columnOrderArray(self):
     coa = (c_int * self.columnCount)()
     processHandle = self.processHandle
     internalCoa = winKernel.virtualAllocEx(processHandle, None,
                                            sizeof(coa),
                                            winKernel.MEM_COMMIT,
                                            winKernel.PAGE_READWRITE)
     try:
         winKernel.writeProcessMemory(processHandle, internalCoa,
                                      byref(coa), sizeof(coa), None)
         res = watchdog.cancellableSendMessage(self.windowHandle,
                                               LVM_GETCOLUMNORDERARRAY,
                                               self.columnCount,
                                               internalCoa)
         if res:
             winKernel.readProcessMemory(processHandle, internalCoa,
                                         byref(coa), sizeof(coa), None)
         else:
             log.debugWarning("LVM_GETCOLUMNORDERARRAY failed for list")
     finally:
         winKernel.virtualFreeEx(processHandle, internalCoa, 0,
                                 winKernel.MEM_RELEASE)
     return coa
示例#53
0
	def onOk(self,evt):

		self.mathrule[1].description = self.descriptionWidget.GetValue()

		for index, item in enumerate(self.mathrule[1].serialized_order):
			if isinstance(item, int):
				self.mathrule[1].serialized_order[index] = self.so_widgets[index].GetSelection()
			elif isinstance(item, tuple):
				self.mathrule[1].serialized_order[index] = (self.so_widgets[index].GetValue(), u'*')
			else:
				self.mathrule[1].serialized_order[index] = self.so_widgets[index].GetValue()

		for index, item in enumerate(self.mathrule[1].role):
			self.mathrule[1].role[index] = self.role_widgets[index].GetValue()

		try:
			self.ruleEntry = ''
		except Exception as e:
			log.debugWarning("Could not add dictionary entry due to (regex error) : %s" % e)
			# Translators: This is an error message to let the user know that the dictionary entry is not valid.
			gui.messageBox(_("Regular Expression error: \"%s\".")%e, _("Dictionary Entry Error"), wx.OK|wx.ICON_WARNING, self)
			return 
		evt.Skip()
示例#54
0
文件: sapi4.py 项目: wafiqtaher/nvda
 def speak(self, speechSequence):
     textList = []
     charMode = False
     for item in speechSequence:
         if isinstance(item, basestring):
             textList.append(item.replace('\\', '\\\\'))
         elif isinstance(item, speech.IndexCommand):
             textList.append("\\mrk=%d\\" % item.index)
         elif isinstance(item, speech.CharacterModeCommand):
             textList.append("\\RmS=1\\" if item.state else "\\RmS=0\\")
             charMode = item.state
         elif isinstance(item, speech.SpeechCommand):
             log.debugWarning("Unsupported speech command: %s" % item)
         else:
             log.error("Unknown speech: %s" % item)
     if charMode:
         # Some synths stay in character mode if we don't explicitly disable it.
         textList.append("\\RmS=0\\")
     text = "".join(textList)
     flags = TTSDATAFLAG_TAGGED
     self._ttsCentral.TextData(VOICECHARSET.CHARSET_TEXT, flags,
                               TextSDATA(text), self._bufSinkPtr,
                               ITTSBufNotifySink._iid_)
示例#55
0
    def emulateKey(self, key: str, withModifiers: bool = True):
        """Emulates a key using the keyboard emulation system.
		If emulation fails (e.g. because of an unknown key), a debug warning is logged
		and the system falls back to sending unicode characters.
		@param withModifiers: Whether this key emulation should include the modifiers that are held virtually.
			Note that this method does not take care of clearing L{self.currentModifiers}.
		"""
        if withModifiers:
            # The emulated key should be the last item in the identifier string.
            keys = list(self.currentModifiers)
            keys.append(key)
            gesture = "+".join(keys)
        else:
            gesture = key
        try:
            inputCore.manager.emulateGesture(
                keyboardHandler.KeyboardInputGesture.fromName(gesture))
        except:
            log.debugWarning(
                "Unable to emulate %r, falling back to sending unicode characters"
                % gesture,
                exc_info=True)
            self.sendChars(key)
示例#56
0
 def extractDataFromResponse(self, response):
     dataMap = {}
     data = response.read()
     # 'data' contains the JSON data. The following formats the JSON data for display.
     parsed = json.loads(data)
     data = json.loads(data)
     try:
         dscr = data['description']
         s = dscr['captions']
         s1 = s[0]
         # Translators: to display result of API
         dataMap['description'] = s1['text']
         dataMap['confidence'] = str((round(s1['confidence'], 2)) * 100)
         color = data['color']
         dataMap['fgColor'] = color['dominantColorForeground']
         dataMap['bgColor'] = color['dominantColorBackground']
     except Exception as e:
         # Translators: a message when API is not able to return a description for image on web page
         ui.message(_(data['message']))
         log.debugWarning("Error- %s: %s", type(e), e)
         log.debugWarning("Error Message from API- %s: %s ", data['code'],
                          data['message'])
     return dataMap
示例#57
0
def event_stateChange(vmID, accContext, oldState, newState):
    jabContext = JABContext(vmID=vmID, accContext=accContext)
    if not jabContext.hwnd:
        log.debugWarning(
            "Unable to obtain window handle for accessible context")
        return
    focus = api.getFocusObject()
    #For broken tabs and menus, we need to watch for things being selected and pretend its a focus change
    stateList = newState.split(',')
    if "focused" in stateList or "selected" in stateList:
        obj = NVDAObjects.JAB.JAB(jabContext=jabContext)
        if not obj:
            return
        if focus != obj and eventHandler.lastQueuedFocusObject != obj and obj.role in (
                controlTypes.Role.MENUITEM, controlTypes.Role.TAB,
                controlTypes.Role.MENU):
            eventHandler.queueEvent("gainFocus", obj)
            return
    obj = focus if (isinstance(focus, NVDAObjects.JAB.JAB) and focus.jabContext
                    == jabContext) else NVDAObjects.JAB.JAB(
                        jabContext=jabContext)
    if obj:
        eventHandler.queueEvent("stateChange", obj)
示例#58
0
def accNavigate(pacc, childID, direction):
	try:
		res = pacc.accNavigate(direction, childID)
	except COMError:
		res = None
	if not res:
		return None
	elif isinstance(res, int):
		if childID == 0 and oleacc.NAVDIR_UP <= direction <= oleacc.NAVDIR_PREVIOUS:
			parentRes = accParent(pacc, 0)
			if not parentRes:
				return None
			pacc = parentRes[0]
		return pacc, res
	elif (
		isinstance(res, comtypes.client.lazybind.Dispatch)
		or isinstance(res, comtypes.client.dynamic._Dispatch)
		or isinstance(res, IUnknown)
	):
		return normalizeIAccessible(res, 0), 0
	else:
		log.debugWarning("Unknown IAccessible type: %s" % res, stack_info=True)
		return None
示例#59
0
 def onOk(self, evt):
     self.Destroy()
     if self.addCheckBox.Value or self.searchRadioBox.Selection < 2:  # Add or search
         text = self.searchTextEdit.Value
     actionToPerform = self.searchRadioBox.Selection
     if actionToPerform < 2:  # Search
         caseSensitive = self.caseSensitiveCheckBox.Value
         if actionToPerform == 0:
             core.callLater(1000,
                            doFindText,
                            text,
                            caseSensitive=caseSensitive)
         else:
             core.callLater(1000,
                            doFindTextUp,
                            text,
                            caseSensitive=caseSensitive)
         global lastFindText, lastCaseSensitivity
         lastFindText = text
         lastCaseSensitivity = caseSensitive
     if self.addCheckBox.Value or self.removeCheckBox.Value:
         savedStrings = self.savedTexts
         if self.removeCheckBox.Value:
             del savedStrings[self.savedTextsComboBox.Selection]
         if self.addCheckBox.Value and not "\n" in text and not text in savedStrings:
             savedStrings.insert(0, text)
         if len(savedStrings) == 0:
             os.remove(self.searchFile)
             return
         try:
             with open(self.searchFile, "w", encoding="utf-8") as f:
                 f.write("\n".join(savedStrings))
         except Exception as e:
             log.debugWarning(
                 "Error saving strings of text for specific search",
                 exc_info=True)
             raise e
示例#60
0
	def _reportErrorInPreviousWord(self):
		try:
			# self might be a descendant of the text control; e.g. Symphony.
			# We want to deal with the entire text, so use the caret object.
			info = api.getCaretObject().makeTextInfo(textInfos.POSITION_CARET)
			# This gets called for characters which might end a word; e.g. space.
			# The character before the caret is the word end.
			# The one before that is the last of the word, which is what we want.
			info.move(textInfos.UNIT_CHARACTER, -2)
			info.expand(textInfos.UNIT_CHARACTER)
		except Exception:
			# Focus probably moved.
			log.debugWarning("Error fetching last character of previous word", exc_info=True)
			return

		# Fetch the formatting for the last word to see if it is marked as a spelling error,
		# However perform the fetch and check in a future core cycle
		# To give the content control more time to detect and mark the error itself.
		# #12161: MS Word's UIA implementation certainly requires this delay.
		def _delayedDetection():
			try:
				fields = info.getTextWithFields()
			except Exception:
				log.debugWarning("Error fetching formatting for last character of previous word", exc_info=True)
				return
			for command in fields:
				if (
					isinstance(command, textInfos.FieldCommand)
					and command.command == "formatChange"
					and command.field.get("invalid-spelling")
				):
					break
			else:
				# No error.
				return
			nvwave.playWaveFile(os.path.join(globalVars.appDir, "waves", "textError.wav"))
		core.callLater(50, _delayedDetection)