def filter(self, filterText: str): try: self.gesturesVM.filter(filterText) except Exception: log.exception() return self.tree.doRefresh(postFilter=True)
def initGestures(): global gesturesFileExists, iniGestures if profileFileExists and gesturesBDPath() != '?': log.debug('Main gestures map found') confGen = gesturesBDPath() confspec = ConfigObj(StringIO(""""""), encoding="UTF-8", list_values=False) iniGestures = ConfigObj(confGen, configspec=confspec, indent_type="\t", encoding="UTF-8") result = iniGestures.validate(Validator()) if result is not True: log.exception('Malformed configuration file') gesturesFileExists = False else: gesturesFileExists = True else: log.warn('No main gestures map (%s) found' % gesturesBDPath(1)) gesturesFileExists = False if gesturesFileExists: for g in iniGestures['globalCommands.GlobalCommands']: if isinstance( iniGestures['globalCommands.GlobalCommands'][g], list): for h in range( len(iniGestures['globalCommands.GlobalCommands'][g])): iniGestures[inputCore.normalizeGestureIdentifier( str(iniGestures['globalCommands.GlobalCommands'][g][h]))] = g elif ('kb:' in g and g not in ['kb:alt', 'kb:control', 'kb:windows', 'kb:control', 'kb:applications'] and 'br(' + curBD + '):' in str(iniGestures['globalCommands.GlobalCommands'][g])): iniGestures[inputCore.normalizeGestureIdentifier(str( iniGestures['globalCommands.GlobalCommands'][g])).replace('br(' + curBD + '):', '')] = g return gesturesFileExists, iniGestures
def handle(self): self._keepRunning = True try: self.wfile.write("NVDA Remote Python Console\n") self.console = pythonConsole.PythonConsole( outputFunc=self.wfile.write, setPromptFunc=self.setPrompt, exitFunc=self.exit) self.console.namespace.update({ "snap": self.console.updateNamespaceSnapshotVars, "rmSnap": self.console.removeNamespaceSnapshotVars, }) self._execDoneEvt = threading.Event() while self._keepRunning: line = self.rfile.readline() if not line: break line = line.rstrip("\r\n") # Execute in the main thread. wx.CallAfter(self.execute, line) # Wait until the line has finished executing before retrieving the next. self._execDoneEvt.wait() self._execDoneEvt.clear() except: log.exception("Error handling remote Python console request") finally: # Clean up the console. self.console = None
def update(processID, helperLocalBindingHandle=None, inprocRegistrationHandle=None): """Removes any appModules from the cache whose process has died, and also tries to load a new appModule for the given process ID if need be. @param processID: the ID of the process. @type processID: int @param helperLocalBindingHandle: an optional RPC binding handle pointing to the RPC server for this process @param inprocRegistrationHandle: an optional rpc context handle representing successful registration with the rpc server for this process """ for deadMod in [ mod for mod in runningTable.itervalues() if not mod.isAlive ]: log.debug("application %s closed" % deadMod.appName) del runningTable[deadMod.processID] if deadMod in set(o.appModule for o in api.getFocusAncestors() + [api.getFocusObject()] if o and o.appModule): if hasattr(deadMod, 'event_appLoseFocus'): deadMod.event_appLoseFocus() try: deadMod.terminate() except: log.exception("Error terminating app module %r" % deadMod) # This creates a new app module if necessary. mod = getAppModuleFromProcessID(processID) if helperLocalBindingHandle: mod.helperLocalBindingHandle = helperLocalBindingHandle if inprocRegistrationHandle: mod._inprocRegistrationHandle = inprocRegistrationHandle
def terminate(): for plugin in list(runningPlugins): runningPlugins.discard(plugin) try: plugin.terminate() except: log.exception("Error terminating global plugin %r" % plugin)
def elten_queue_thread(threadName=None): global stopThreads global eltenqueue global eltenpipest global eltenindex global eltenindexid global eltenmod lastSend = 0 while (True): if (stopThreads): break time.sleep(0.01) try: if (eltenpipest != None and eltenpipest != -1 and len(eltenqueue['gestures']) > 0): r = eltenqueue['gestures'][:] eltenqueue['gestures'] = [] j = {'msgtype': 2, 'gestures': r} w = json.dumps(j) + "\n" if (is_python_3_or_above): w = w.encode("utf-8") eltenpipest.write(w) lastSend = time.time() if (eltenpipest != None and eltenpipest != -1 and len(eltenqueue['indexes']) > 0): r = eltenqueue['indexes'][:] eltenqueue['indexes'] = [] j = {'msgtype': 3, 'indexes': r} w = json.dumps(j) + "\n" if (is_python_3_or_above): w = w.encode("utf-8") eltenpipest.write(w) lastSend = time.time() if (eltenpipest != None and eltenpipest != -1 and len(eltenqueue['statuses']) > 0): r = eltenqueue['statuses'][:] eltenqueue['statuses'] = [] j = {'msgtype': 4, 'statuses': r} w = json.dumps(j) + "\n" if (is_python_3_or_above): w = w.encode("utf-8") eltenpipest.write(w) lastSend = time.time() if (eltenpipest != None and eltenpipest != -1 and len(eltenqueue['returns']) > 0): r = eltenqueue['returns'][:] eltenqueue['returns'] = [] for w in r: eltenpipest.write(w) lastSend = time.time() if (lastSend < time.time() - 1 and appModuleHandler.getAppModuleForNVDAObject( api.getForegroundObject()) == eltenmod): eltenqueue['statuses'].append("noop") lastSend = time.time() except Exception as Argument: log.exception("Elten: queue thread") time.sleep(0.05) eltenqueue = { 'gestures': [], 'indexes': [], 'statuses': [], 'returns': [] }
def handle(self): self._keepRunning = True try: self.wfile.write("NVDA Remote Python Console\n") self.console = pythonConsole.PythonConsole(outputFunc=self.wfile.write, setPromptFunc=self.setPrompt, exitFunc=self.exit) self.console.namespace.update({ "snap": self.console.updateNamespaceSnapshotVars, "rmSnap": self.console.removeNamespaceSnapshotVars, }) self._execDoneEvt = threading.Event() while self._keepRunning: line = self.rfile.readline() if not line: break line = line.rstrip("\r\n") # Execute in the main thread. wx.CallAfter(self.execute, line) # Wait until the line has finished executing before retrieving the next. self._execDoneEvt.wait() self._execDoneEvt.clear() except: log.exception("Error handling remote Python console request") finally: # Clean up the console. self.console = None
def executeScript(script,gesture): """Executes a given script (function) passing it the given gesture. It also keeps track of the execution of duplicate scripts with in a certain amount of time, and counts how many times this happens. Use L{getLastScriptRepeatCount} to find out this count value. @param script: the function or method that should be executed. The function or method must take an argument of 'gesture'. @type script: callable. @param gesture: the input gesture that activated this script @type gesture: L{inputCore.InputGesture} """ global _lastScriptTime, _lastScriptCount, _lastScriptRef, _isScriptRunning lastScriptRef=_lastScriptRef() if _lastScriptRef else None #We don't allow the same script to be executed from with in itself, but we still should pass the key through scriptFunc=getattr(script,"__func__",script) if _isScriptRunning and lastScriptRef==scriptFunc: return gesture.send() _isScriptRunning=True try: scriptTime=time.time() scriptRef=weakref.ref(scriptFunc) if (scriptTime-_lastScriptTime)<=0.5 and scriptFunc==lastScriptRef: _lastScriptCount+=1 else: _lastScriptCount=0 _lastScriptRef=scriptRef _lastScriptTime=scriptTime script(gesture) except: log.exception("error executing script: %s with gesture %r"%(script,gesture.displayName)) finally: _isScriptRunning=False
def _monitor(self): try: oldLines = self._getTextLines() except: log.exception("Error getting initial lines") oldLines = [] while self._keepMonitoring: self._event.wait() if not self._keepMonitoring: break if self.STABILIZE_DELAY > 0: # wait for the text to stabilise. time.sleep(self.STABILIZE_DELAY) if not self._keepMonitoring: # Monitoring was stopped while waiting for the text to stabilise. break self._event.clear() try: newLines = self._getTextLines() if config.conf["presentation"]["reportDynamicContentChanges"]: outLines = self._calculateNewText(newLines, oldLines) if len(outLines) == 1 and len(outLines[0].strip()) == 1: # This is only a single character, # which probably means it is just a typed character, # so ignore it. del outLines[0] if outLines: queueHandler.queueFunction(queueHandler.eventQueue, self._reportNewLines, outLines) oldLines = newLines except: log.exception("Error getting lines or calculating new text")
def executeEvent(eventName, obj, **kwargs): """Executes an NVDA event. @param eventName: the name of the event type (e.g. 'gainFocus', 'nameChange') @type eventName: string @param obj: the object the event is for @type obj: L{NVDAObjects.NVDAObject} @param kwargs: Additional event parameters as keyword arguments. """ try: isGainFocus = eventName == "gainFocus" # Allow NVDAObjects to redirect focus events to another object of their choosing. if isGainFocus and obj.focusRedirect: obj=obj.focusRedirect sleepMode=obj.sleepMode if isGainFocus and speech.manager._shouldCancelExpiredFocusEvents(): log._speechManagerDebug("executeEvent: Removing cancelled speech commands.") # ask speechManager to check if any of it's queued utterances should be cancelled speech._manager.removeCancelledSpeechCommands() # Don't skip objects without focus here. Even if an object no longer has focus, it needs to be processed # to capture changes in document depth. For instance jumping into a list? # This needs further investigation; when the next object gets focus, it should # allow us to capture this information? if isGainFocus and not doPreGainFocus(obj, sleepMode=sleepMode): return elif not sleepMode and eventName=="documentLoadComplete" and not doPreDocumentLoadComplete(obj): return elif not sleepMode: _EventExecuter(eventName,obj,kwargs) except: log.exception("error executing event: %s on %s with extra args of %s"%(eventName,obj,kwargs))
def load(self, fileName): self.fileName=fileName comment="" del self[:] log.debug("Loading speech dictionary '%s'..." % fileName) if not os.path.isfile(fileName): log.debug("file '%s' not found." % fileName) return file = codecs.open(fileName,"r","utf_8_sig",errors="replace") for line in file: if line.isspace(): comment="" continue line=line.rstrip('\r\n') if line.startswith('#'): if comment: comment+=" " comment+=line[1:] else: temp=line.split("\t") if len(temp) ==4: pattern = temp[0].replace(r'\#','#') replace = temp[1].replace(r'\#','#') try: dictionaryEntry=SpeechDictEntry(pattern, replace, comment, caseSensitive=bool(int(temp[2])), type=int(temp[3])) self.append(dictionaryEntry) except Exception as e: log.exception("Dictionary (\"%s\") entry invalid for \"%s\" error raised: \"%s\"" % (fileName, line, e)) comment="" else: log.warning("can't parse line '%s'" % line) log.debug("%d loaded records." % len(self)) file.close() return
def _restoreProfileTriggers(self, triggers): for trigger in triggers: try: trigger.enter() except: log.exception("Error entering profile trigger %r" % trigger.spec) synthDriverHandler.handlePostConfigProfileSwitch(resetSpeechIfNeeded=False)
def _monitor(self): try: oldLines = self._getTextLines() except: log.exception("Error getting initial lines") oldLines = [] while self._keepMonitoring: self._event.wait() if not self._keepMonitoring: break if self.STABILIZE_DELAY > 0: # wait for the text to stabilise. time.sleep(self.STABILIZE_DELAY) if not self._keepMonitoring: # Monitoring was stopped while waiting for the text to stabilise. break self._event.clear() try: newLines = self._getTextLines() if config.conf["presentation"]["reportDynamicContentChanges"]: outLines = self._calculateNewText(newLines, oldLines) if len(outLines) == 1 and len(outLines[0]) == 1: # This is only a single character, # which probably means it is just a typed character, # so ignore it. del outLines[0] for line in outLines: queueHandler.queueFunction(queueHandler.eventQueue, self._reportNewText, line) oldLines = newLines except: log.exception("Error getting lines or calculating new text")
def _exitProfileTriggers(self, triggers): for trigger in reversed(triggers): try: trigger.exit() except: log.exception("Error exiting profile trigger %r" % trigger.spec) synthDriverHandler.handlePostConfigProfileSwitch(resetSpeechIfNeeded=False)
def _checkDead(): try: if isConsoleDead(): # We must disconnect NVDA from this console so it can close. disconnectConsole() except: log.exception()
def __init__(self, markerManager, dic): super(VirtualMarkerQuery, self).__init__(markerManager) self.dic = dic self.name = dic["name"] self.type = dic["type"] self.contextPageTitle = dic.get("contextPageTitle", "") self.contextPageType = dic.get("contextPageType", "") self.contextParent = dic.get("contextParent", "") self.priority = dic.get("priority") self.index = dic.get("index") self.mutation = None if "mutation" in dic: try: self.mutation = MUTATIONS[dic["mutation"]] except LookupError: log.exception( (u"Unexpected mutation template id \"{mutation}\" " u"in rule \"{rule}\".").format(mutation=dic["mutation"], rule=self.name)) self.gestures = dic.get("gestures", {}) gesturesMap = {} for gestureIdentifier in self.gestures.keys(): gesturesMap[gestureIdentifier] = "notFound" self.bindGestures(gesturesMap) self.autoAction = dic.get("autoAction") self.multiple = dic.get("multiple", False) self.formMode = dic.get("formMode", False) self.skip = dic.get("skip", False) self.sayName = dic.get("sayName", True) self.customName = dic.get("customName") self.customValue = dic.get("customValue") self.comment = dic.get("comment") self.createWidget = dic.get("createWidget", False)
def terminate(): for processID, app in runningTable.iteritems(): try: app.terminate() except: log.exception("Error terminating app module %r" % app) runningTable.clear()
def sync(self): """Synchronise with playback. This method blocks until the previously fed chunk of audio has finished playing. It is called automatically by L{feed}, so usually need not be called directly by the user. Note: it must be possible to call stop concurrently with sync, sync should be considered to be blocking the synth driver thread most of the time (ie sync waiting for the last pushed block of audio to complete, via the 'winKernal.waitForSingleObject' mechanism) """ with self._lock: if not self._prev_whdr: return assert self._waveout, "waveOut None before wait" while (not (self._prev_whdr.dwFlags & WHDR_DONE) # In case some sound driver can not keep track of the whdr from previous buffers, ensure that # 'waitForSingleObject' can not block for long, and exit this loop if stopping. and self._prevOnDone is not self.STOPPING): winKernel.waitForSingleObject(self._waveout_event, self._waveout_event_wait_ms) with self._waveout_lock: assert self._waveout, "waveOut None after wait" with self._global_waveout_lock: winmm.waveOutUnprepareHeader(self._waveout, LPWAVEHDR(self._prev_whdr), sizeof(WAVEHDR)) self._prev_whdr = None if self._prevOnDone not in (None, self.STOPPING): try: self._prevOnDone() except: log.exception("Error calling onDone") self._prevOnDone = None
def fetchAppModule(processID: int, appName: str) -> AppModule: """Returns an appModule found in the appModules directory, for the given application name. @param processID: process ID for it to be associated with @param appName: the application name for which an appModule should be found. @returns: the appModule. """ modName = appName try: importedMod = _importAppModuleForExecutable(modName) if importedMod is not None: return importedMod.AppModule(processID, appName) # Broad except since we do not know # what exceptions may be thrown during import / construction of the App Module. except Exception: log.exception(f"error in appModule {modName!r}") import ui import speech.priorities ui.message( # Translators: This is presented when errors are found in an appModule # (example output: error in appModule explorer). _("Error in appModule %s") % modName, speechPriority=speech.priorities.Spri.NOW) # Use the base AppModule. return AppModule(processID, appName)
def extractAttributes(self, ctx): speechPres = ctx.getPresentationString() braillePres = ctx.getBraillePresentationString() if braillePres is None: braillePres = speechPres if isinstance(braillePres, list): for s in braillePres: if isinstance(s, unicode): outStr = self.formatPresentation(s, ctx, True) self.brailleObjects.append(BrailleOffset(ctx, outStr)) else: try: outStr = ctx.getBraillePresentationStringForElement(s) except Exception as e: log.exception("getBraillePresentationStringForElement failed: %s" % e) outStr = u"sansnom" self.brailleObjects.append(BrailleOffset(ctx, outStr)) else: pObj = BrailleOffset(ctx, self.formatPresentation(braillePres, ctx, True)) if pObj.presentationString is False: pObj.updatePresentationString("sansnom") self.brailleObjects.append(pObj) presString = self.formatPresentation(speechPres, ctx) brailleString = "" # Builds the whole braille string, and update offsets accordingly. offset = 0 for obj in self.brailleObjects: brailleString += obj.presentationString + " " obj.setOffset(offset) offset = obj.endOffset + 1 return (presString, brailleString)
def catalog(self, errors=None): if not os.path.isdir(self.path): return for f in os.listdir(self.path): if os.path.isfile(os.path.join(self.path, f)): matches = re.match("^(.*)\.json$", f) if not matches: continue ref = matches.group(1) try: data = self.get(ref).data meta = {} for key in ("windowTitle", "url"): value = data.get("WebModule", data.get("WebApp", {})).get(key) if value: meta[key] = value except Exception: if errors: errors.append((ref, sys.exc_info())) else: log.exception( u"Error while retrieving item: ref={}".format(ref)) continue yield ref, meta
def read(self, path): try: with open(path, "r") as f: return json.load(f) except Exception: log.exception(u"Failed reading file: {}".format(path)) raise
def sync(self): """Synchronise with playback. This method blocks until the previously fed chunk of audio has finished playing. It is called automatically by L{feed}, so usually need not be called directly by the user. """ with self._lock: if not self._prev_whdr: return assert self._waveout, "waveOut None before wait" while not (self._prev_whdr.dwFlags & WHDR_DONE): winKernel.waitForSingleObject(self._waveout_event, winKernel.INFINITE) with self._waveout_lock: assert self._waveout, "waveOut None after wait" with self._global_waveout_lock: winmm.waveOutUnprepareHeader(self._waveout, LPWAVEHDR(self._prev_whdr), sizeof(WAVEHDR)) self._prev_whdr = None if self._prevOnDone is not None and self._prevOnDone is not self.STOPPING: try: self._prevOnDone() except: log.exception("Error calling onDone") self._prevOnDone = None
def _isImprovedConhostTextRangeAvailable(hwnd: int) -> bool: """This function determines whether microsoft/terminal#4495 and by extension microsoft/terminal#4018 are present in this conhost. In consoles before these PRs, a number of workarounds were needed in our UIA implementation. However, these do not fix all bugs and are problematic on newer console releases. This function is therefore used to determine whether this console's UIA implementation is good enough to use by default.""" # microsoft/terminal#4495: In newer consoles, # IUIAutomationTextRange::getVisibleRanges returns one visible range. # Therefore, if exactly one range is returned, it is almost definitely a newer console. try: UIAElement = UIAHandler.handler.clientObject.ElementFromHandleBuildCache( hwnd, UIAHandler.handler.baseCacheRequest) textAreaCacheRequest = UIAHandler.handler.baseCacheRequest.clone() textAreaCacheRequest.TreeScope = UIAHandler.TreeScope_Children textAreaCacheRequest.treeFilter = UIAHandler.handler.clientObject.createPropertyCondition( UIAHandler.UIA_AutomationIdPropertyId, "Text Area") textArea = UIAElement.buildUpdatedCache( textAreaCacheRequest).getCachedChildren().GetElement(0) UIATextPattern = textArea.GetCurrentPattern( UIAHandler.UIA_TextPatternId).QueryInterface( UIAHandler.IUIAutomationTextPattern) return UIATextPattern.GetVisibleRanges().length == 1 except (COMError, ValueError): log.exception() return False
def _set_nvdajp_keyEvents(): if not globalVars.appArgs.minimal: # Masataka.Shinke import nvdajp_keyEvents # Masataka.Shinke try: # Masataka.Shinke nvdajp_keyEvents.initialize() # Masataka.Shinke except: # Masataka.Shinke log.exception("Error retrieving initial nvdajp_keyEvents") # Masataka.Shinke
def executeScript(script, gesture): """Executes a given script (function) passing it the given gesture. It also keeps track of the execution of duplicate scripts with in a certain amount of time, and counts how many times this happens. Use L{getLastScriptRepeatCount} to find out this count value. @param script: the function or method that should be executed. The function or method must take an argument of 'gesture'. @type script: callable. @param gesture: the input gesture that activated this script @type gesture: L{inputCore.InputGesture} """ global _lastScriptTime, _lastScriptCount, _lastScriptRef, _isScriptRunning lastScriptRef = _lastScriptRef() if _lastScriptRef else None #We don't allow the same script to be executed from with in itself, but we still should pass the key through scriptFunc = getattr(script, "__func__", script) if _isScriptRunning and lastScriptRef == scriptFunc: return gesture.send() _isScriptRunning = True try: scriptTime = time.time() scriptRef = weakref.ref(scriptFunc) if (scriptTime - _lastScriptTime) <= 0.5 and scriptFunc == lastScriptRef: _lastScriptCount += 1 else: _lastScriptCount = 0 _lastScriptRef = scriptRef _lastScriptTime = scriptTime script(gesture) except: log.exception("error executing script: %s with gesture %r" % (script, gesture.displayName)) finally: _isScriptRunning = False
def fetchAppModule(processID, appName): """Returns an appModule found in the appModules directory, for the given application name. @param processID: process ID for it to be associated with @type processID: integer @param appName: the application name for which an appModule should be found. @type appName: str @returns: the appModule, or None if not found @rtype: AppModule """ # First, check whether the module exists. # We need to do this separately because even though an ImportError is raised when a module can't be found, it might also be raised for other reasons. modName = appName if doesAppModuleExist(modName): try: return importlib.import_module("appModules.%s" % modName, package="appModules").AppModule( processID, appName) except: log.exception(f"error in appModule {modName!r}") import ui import speech.priorities ui.message( # Translators: This is presented when errors are found in an appModule # (example output: error in appModule explorer). _("Error in appModule %s") % modName, speechPriority=speech.priorities.Spri.NOW) # Use the base AppModule. return AppModule(processID, appName)
def getWebModuleFactory(name): if not hasCustomModule(name): return WebModule mod = None try: if nvdaVersion < (2019, 3): # Python 2.x can't properly handle unicode module names, so convert them. name = name.encode("mbcs") mod = __import__("webModules.{}".format(name), globals(), locals(), ("webModules", )) else: import importlib mod = importlib.import_module("webModules.{}".format(name), package="webModules") except Exception: log.exception( "Could not import custom module webModules.{}".format(name)) if not mod: return WebModule apiVersion = getattr(mod, "API_VERSION", None) apiVersion = version.parse(apiVersion or "") if apiVersion != WebModule.API_VERSION: raise InvalidApiVersion(apiVersion) ctor = getattr(mod, "WebModule", None) if ctor is None: msg = u"Python module {} does not provide a 'WebModule' class: {}".format( mod.__name__, getattr(mod, "__file__", None) or getattr(mod, "__path__", None)) log.error(msg) raise AttributeError(msg) return ctor
def recursiveStackBuilder2(): if randint(1, 100) == 500: log.exception("boo!", stack_info=False) return if randint(0, 1): recursiveStackBuilder1() else: recursiveStackBuilder2()
def script_sayTitle(self, gesture): titleObj = api.getFocusObject() windowTitle = titleObj.windowText try: webAppTitle = self.pageTitle except Exception, e: log.exception("Error retrieving webApp title: %s" % e) webAppTitle = windowTitle
def _terminate(module, name=None): if name is None: name = module.__name__ log.debug("Terminating %s" % name) try: module.terminate() except: log.exception("Error terminating %s" % name)
def write(self, path, data): try: with open(path, "w") as f: json.dump(data, f, indent=4) except Exception: log.exception(u"Failed writing file: {path}".format(path=path)) return False return True
def recursiveStackBuilder1(): if randint(1, 200) == 30: log.exception("hahahahahahaha!", stack_info=False) return if randint(0, 1): recursiveStackBuilder1() else: recursiveStackBuilder2()
def notify(self, **kwargs): """Notify all registered handlers that the action has occurred. @param kwargs: Arguments to pass to the handlers. """ for handler in self.handlers: try: callWithSupportedKwargs(handler, **kwargs) except: log.exception("Error running handler %r for %r" % (handler, self))
def saveSettings(): global conf try: conf.validate(Validator(), copy=True) conf.write() log.debug('%s add-on configuration saved' % _addonName) except BaseException: log.exception('Cannot save Configuration') return
def flushQueue(queue): for count in xrange(queue.qsize() + 1): if not queue.empty(): (func, args, kwargs) = queue.get_nowait() watchdog.alive() try: func(*args, **kwargs) except: log.exception("Error in func %s from %s" % (func.__name__, queue.__name__))
def Notify(self): try: JABHandler.pumpAll() IAccessibleHandler.pumpAll() queueHandler.pumpAll() mouseHandler.pumpAll() except: log.exception("errors in this core pump cycle") baseObject.AutoPropertyObject.invalidateCaches() watchdog.alive()
def _rawWindowProc(hwnd, msg, wParam, lParam): try: inst = CustomWindow._hwndsToInstances[hwnd] except KeyError: return ctypes.windll.user32.DefWindowProcW(hwnd, msg, wParam, lParam) try: res = inst.windowProc(hwnd, msg, wParam, lParam) if res is not None: return res except: log.exception("Error in wndProc") return ctypes.windll.user32.DefWindowProcW(hwnd, msg, wParam, lParam)
def cleanup(): """Removes any appModules from the cache whose process has died. """ for deadMod in [mod for mod in runningTable.itervalues() if not mod.isAlive]: log.debug("application %s closed" % deadMod.appName) del runningTable[deadMod.processID] if deadMod in set(o.appModule for o in api.getFocusAncestors() + [api.getFocusObject()] if o and o.appModule): if hasattr(deadMod, "event_appLoseFocus"): deadMod.event_appLoseFocus() try: deadMod.terminate() except: log.exception("Error terminating app module %r" % deadMod)
def completePendingAddonRemoves(): """Removes any addons that could not be removed on the last run of NVDA""" user_addons = os.path.abspath(os.path.join(globalVars.appArgs.configPath, "addons")) pendingRemovesSet=state['pendingRemovesSet'] for addonName in list(pendingRemovesSet): addonPath=os.path.join(user_addons,addonName) if os.path.isdir(addonPath): addon=Addon(addonPath) try: addon.completeRemove() except RuntimeError: log.exception("Failed to remove %s add-on"%addonName) continue pendingRemovesSet.discard(addonName)
def _setInitialFocus(): """Sets the initial focus if no focus event was received at startup. """ import eventHandler import api if eventHandler.lastQueuedFocusObject: # The focus has already been set or a focus event is pending. return try: focus = api.getDesktopObject().objectWithFocus() if focus: eventHandler.queueEvent('gainFocus', focus) except: log.exception("Error retrieving initial focus")
def kwargsFromSuper(cls,kwargs,relation=None): IAccessibleObject=kwargs['IAccessibleObject'] #MSHTML should not be used for MSAA child elements. #However, objectFromPoint can hit an MSAA child element but we still should try MSHTML's own elementFromPoint even in this case. if kwargs.get('IAccessibleChildID') and not isinstance(relation,tuple): return False HTMLNode=None try: HTMLNode=HTMLNodeFromIAccessible(IAccessibleObject) except NotImplementedError: pass if not HTMLNode: return False if relation=="focus": # #4045: we must recurse into frames ourselves when fetching the active element of a document. while True: try: HTMLNode=HTMLNode.document.activeElement except: log.exception("Error getting activeElement") break nodeName=HTMLNode.nodeName or "" if nodeName.lower() not in ("frame","iframe"): # The IAccessibleObject may be incorrect now, so let the constructor recalculate it. del kwargs['IAccessibleObject'] break childElement=getChildHTMLNodeFromFrame(HTMLNode) if not childElement: break HTMLNode=childElement elif isinstance(relation,tuple): windowHandle=kwargs.get('windowHandle') p=ctypes.wintypes.POINT(x=relation[0],y=relation[1]) ctypes.windll.user32.ScreenToClient(windowHandle,ctypes.byref(p)) # #3494: MSHTML's internal coordinates are always at a hardcoded DPI (usually 96) no matter the system DPI or zoom level. xFactor,yFactor=getZoomFactorsFromHTMLDocument(HTMLNode.document) try: HTMLNode=HTMLNode.document.elementFromPoint(p.x/xFactor,p.y/yFactor) except: HTMLNode=None if not HTMLNode: log.debugWarning("Error getting HTMLNode with elementFromPoint") return False del kwargs['IAccessibleObject'] del kwargs['IAccessibleChildID'] kwargs['HTMLNode']=HTMLNode return True
def initialize(): global curMousePos (x,y)=winUser.getCursorPos() desktopObject=api.getDesktopObject() try: mouseObject=desktopObject.objectFromPoint(x,y) except: log.exception("Error retrieving initial mouse object") mouseObject=None if not mouseObject: mouseObject=api.getDesktopObject() api.setMouseObject(mouseObject) curMousePos=(x,y) winInputHook.initialize() winInputHook.setCallbacks(mouse=internal_mouseEvent)
def apply(self, value, **kwargs): """Pass a value to be filtered through all registered handlers. The value is passed to the first handler and the return value from that handler is passed to the next handler. This process continues for all handlers until the final handler. The return value from the final handler is returned to the caller. @param value: The value to be filtered. @param kwargs: Arguments to pass to the handlers. @return: The filtered value. """ for handler in self.handlers: try: value = callWithSupportedKwargs(handler, value, **kwargs) except: log.exception("Error running handler %r for %r" % (handler, self)) return value
def initialize(): global curMousePos, scrBmpObj, _shapeTimer scrBmpObj=screenBitmap.ScreenBitmap(1,1) (x,y)=winUser.getCursorPos() desktopObject=api.getDesktopObject() try: mouseObject=desktopObject.objectFromPoint(x,y) except: log.exception("Error retrieving initial mouse object") mouseObject=None if not mouseObject: mouseObject=api.getDesktopObject() api.setMouseObject(mouseObject) curMousePos=(x,y) winInputHook.initialize() winInputHook.setCallbacks(mouse=internal_mouseEvent) _shapeTimer = gui.NonReEntrantTimer(_reportShape)
def decide(self, **kwargs): """Call handlers to make a decision. If a handler returns False, processing stops and False is returned. If there are no handlers or all handlers return True, True is returned. @param kwargs: Arguments to pass to the handlers. @return: The decision. @rtype: bool """ for handler in self.handlers: try: decision = callWithSupportedKwargs(handler, **kwargs) except: log.exception("Error running handler %r for %r" % (handler, self)) continue if not decision: return False return True
def executeEvent(eventName,obj,**kwargs): """Executes an NVDA event. @param eventName: the name of the event type (e.g. 'gainFocus', 'nameChange') @type eventName: string @param obj: the object the event is for @type obj: L{NVDAObjects.NVDAObject} @param kwargs: Additional event parameters as keyword arguments. """ try: sleepMode=obj.appModule.sleepMode if obj and obj.appModule else False if eventName=="gainFocus" and not doPreGainFocus(obj,sleepMode=sleepMode): return elif not sleepMode and eventName=="documentLoadComplete" and not doPreDocumentLoadComplete(obj): return elif not sleepMode: _EventExecuter(eventName,obj,kwargs) except: log.exception("error executing event: %s on %s with extra args of %s"%(eventName,obj,kwargs))
def pumpAll(): # This dict can mutate during iteration, so use keys(). for ID in generators.keys(): # KeyError could occur within the generator itself, so retrieve the generator first. try: gen = generators[ID] except KeyError: # Generator was cancelled. This is fine. continue watchdog.alive() try: next(gen) except StopIteration: log.debug("generator %s finished"%ID) del generators[ID] except: log.exception("error in generator %d"%ID) del generators[ID] flushQueue(eventQueue)
def windowProc(self, hwnd, msg, wParam, lParam): if msg != win32con.WM_COPYDATA: return hwnd = wParam struct_pointer = lParam message_data = ctypes.cast(struct_pointer, PCOPYDATASTRUCT) url = ctypes.wstring_at(message_data.contents.lpData) log.info("Received url: %s" % url) try: con_info = connection_info.ConnectionInfo.from_url(url) except connection_info.URLParsingError: wx.CallLater(50, gui.messageBox, parent=gui.mainFrame, caption=_("Invalid URL"), # Translators: Message shown when an invalid URL has been provided. message=_("Unable to parse url \"%s\"")%url, style=wx.OK | wx.ICON_ERROR) log.exception("unable to parse nvdaremote:// url %s" % url) raise log.info("Connection info: %r" % con_info) if callable(self.callback): wx.CallLater(50, self.callback, con_info)
def kwargsFromSuper(cls,kwargs,relation=None): IAccessibleObject=kwargs['IAccessibleObject'] HTMLNode=None try: HTMLNode=HTMLNodeFromIAccessible(IAccessibleObject) except NotImplementedError: pass if not HTMLNode: return False if relation=="focus": try: HTMLNode=HTMLNode.document.activeElement # The IAccessibleObject may be incorrect now, so let the constructor recalculate it. del kwargs['IAccessibleObject'] except: log.exception("Error getting activeElement") kwargs['HTMLNode']=HTMLNode return True
def run(self): global _isPumpPending _isPumpPending = False watchdog.alive() try: if touchHandler.handler: touchHandler.handler.pump() JABHandler.pumpAll() IAccessibleHandler.pumpAll() queueHandler.pumpAll() mouseHandler.pumpAll() braille.pumpAll() except: log.exception("errors in this core pump cycle") baseObject.AutoPropertyObject.invalidateCaches() watchdog.asleep() if _isPumpPending and not _pump.IsRunning(): # #3803: Another pump was requested during this pump execution. # As our pump is not re-entrant, schedule another pump. _pump.Start(PUMP_MAX_DELAY, True)
def Notify(self): global _isPumpPending _isPumpPending = False watchdog.alive() try: if touchHandler.handler: touchHandler.handler.pump() JABHandler.pumpAll() IAccessibleHandler.pumpAll() queueHandler.pumpAll() mouseHandler.pumpAll() braille.pumpAll() except: log.exception("errors in this core pump cycle") baseObject.AutoPropertyObject.invalidateCaches() watchdog.asleep() if _isPumpPending and not _pump.IsRunning(): # #3803: A pump was requested, but the timer was ignored by a modal loop # because timers aren't re-entrant. # Therefore, schedule another pump. _pump.Start(PUMP_MAX_DELAY, True)
def update(processID,helperLocalBindingHandle=None,inprocRegistrationHandle=None): """Removes any appModules from the cache whose process has died, and also tries to load a new appModule for the given process ID if need be. @param processID: the ID of the process. @type processID: int @param helperLocalBindingHandle: an optional RPC binding handle pointing to the RPC server for this process @param inprocRegistrationHandle: an optional rpc context handle representing successful registration with the rpc server for this process """ for deadMod in [mod for mod in runningTable.itervalues() if not mod.isAlive]: log.debug("application %s closed"%deadMod.appName) del runningTable[deadMod.processID] if deadMod in set(o.appModule for o in api.getFocusAncestors()+[api.getFocusObject()] if o and o.appModule): if hasattr(deadMod,'event_appLoseFocus'): deadMod.event_appLoseFocus() try: deadMod.terminate() except: log.exception("Error terminating app module %r" % deadMod) # This creates a new app module if necessary. mod=getAppModuleFromProcessID(processID) if helperLocalBindingHandle: mod.helperLocalBindingHandle=helperLocalBindingHandle if inprocRegistrationHandle: mod._inprocRegistrationHandle=inprocRegistrationHandle
def pumpAll(): # This dict can mutate during iteration, so use keys(). for ID in generators.keys(): # KeyError could occur within the generator itself, so retrieve the generator first. try: gen = generators[ID] except KeyError: # Generator was cancelled. This is fine. continue watchdog.alive() try: next(gen) except StopIteration: log.debug("generator %s finished" % ID) del generators[ID] except: log.exception("error in generator %d" % ID) del generators[ID] # Lose our reference so Python can destroy the generator if appropriate. del gen if generators: core.requestPump() flushQueue(eventQueue)
def kwargsFromSuper(cls,kwargs,relation=None): IAccessibleObject=kwargs['IAccessibleObject'] #MSHTML should not be used for MSAA child elements. #However, objectFromPoint can hit an MSAA child element but we still should try MSHTML's own elementFromPoint even in this case. if kwargs.get('IAccessibleChildID') and not isinstance(relation,tuple): return False HTMLNode=None try: HTMLNode=HTMLNodeFromIAccessible(IAccessibleObject) except NotImplementedError: pass if not HTMLNode: return False if relation=="focus": try: HTMLNode=HTMLNode.document.activeElement # The IAccessibleObject may be incorrect now, so let the constructor recalculate it. del kwargs['IAccessibleObject'] except: log.exception("Error getting activeElement") elif isinstance(relation,tuple): windowHandle=kwargs.get('windowHandle') p=ctypes.wintypes.POINT(x=relation[0],y=relation[1]) ctypes.windll.user32.ScreenToClient(windowHandle,ctypes.byref(p)) try: HTMLNode=HTMLNode.document.elementFromPoint(p.x,p.y) except: HTMLNode=None if not HTMLNode: log.debugWarning("Error getting HTMLNode with elementFromPoint") return False del kwargs['IAccessibleObject'] del kwargs['IAccessibleChildID'] kwargs['HTMLNode']=HTMLNode return True