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
def _update_Toolbars(self, callback=0): global toolBars obj = api.getForegroundObject() if not obj or obj.name == None: try: obj = api.getFocusAncestors()[2] except: obj = api.getFocusObject().parent.parent.parent if not obj: return winHandle = obj.windowHandle winClass = obj.windowClassName if winHandle in toolBars: return True else: activeToolBars = { tb.name.lstrip('Audacity ').rstrip('Toolbar'): tb for tb in obj.recursiveDescendants if tb.role == controlTypes.ROLE_TOOLBAR } if bool(len(activeToolBars)): toolBars[winHandle] = activeToolBars return True elif callback != 1: self._update_Toolbars(1) else: return
def updateNamespaceSnapshotVars(self): """Update the console namespace with a snapshot of NVDA's current state. This creates/updates variables for the current focus, navigator object, etc. Typically, used before the NVDA python console is opened, after which, calls to the 'api' module will refer to this new focus. """ try: caretPos = api.getCaretPosition() except RuntimeError: log.debug( "Unable to set caretPos snapshot variable for python console.") caretPos = None self._namespaceSnapshotVars = { "focus": api.getFocusObject(), # Copy the focus ancestor list, as it gets mutated once it is replaced in api.setFocusObject. "focusAnc": list(api.getFocusAncestors()), "fdl": api.getFocusDifferenceLevel(), "fg": api.getForegroundObject(), "nav": api.getNavigatorObject(), "caretObj": api.getCaretObject(), "caretPos": caretPos, "review": api.getReviewPosition(), "mouse": api.getMouseObject(), "brlRegions": braille.handler.buffer.regions, } self.namespace.update(self._namespaceSnapshotVars)
def modo(self): try: focus = api.getFocusObject() vbuf = focus.treeInterceptor if not vbuf: #ui.message("no2") for obj in itertools.chain((api.getFocusObject(), ), reversed(api.getFocusAncestors())): try: obj.treeInterceptorClass except: continue break else: return ti = treeInterceptorHandler.update(obj, force=True) if not ti: return if focus in ti: focus.treeInterceptor = ti if isinstance(ti, browseMode.BrowseModeTreeInterceptor ) and not ti.passThrough: browseMode.reportPassThrough(ti, False) return if not isinstance(vbuf, browseMode.BrowseModeTreeInterceptor): return if vbuf.passThrough: return True else: return False except: error = "Error modo"
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 event_nameChange(self): if self in api.getFocusAncestors(): speech.speakObjectProperties(self, name=True, reason=controlTypes.REASON_CHANGE) braille.handler.handleUpdate(self) self.handlePossibleProfileSwitch()
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
def _get_script_hacky(self): #Workaround until DB 1.1 when I fix NVDA to not need repeated scripts. #Mostly based on scriptHandler.findScript, but no globalGestureMapness focus = api.getFocusObject() if not focus: return None ti = focus.treeInterceptor if ti: func = self._getScriptFromObject(ti) if func and (not ti.passThrough or getattr( func, "ignoreTreeInterceptorPassThrough", False)): return func # NVDAObject level. func = self._getScriptFromObject(focus) if func: return func for obj in reversed(api.getFocusAncestors()): func = self._getScriptFromObject(obj) if func and getattr(func, 'canPropagate', False): return func # Global commands. func = self._getScriptFromObject(globalCommands.commands) if func: return func
def getRoot(self): """selects or adjusts root object for search.""" ancestors = api.getFocusAncestors() for ancestor in ancestors: if isinstance(ancestor, WindowRoot): self.root = ancestor debugLog("Use WindowRoot instance for root") break curFocus = api.getFocusObject() self.curAppName = curFocus.appModule.appName if curFocus.appModule else None debugLog("%s toolbars session" % self.curAppName) # root adjustments if self.curAppName in ("calibre", ): while curFocus.role != roles.WINDOW: curFocus = curFocus.simpleParent self.root = curFocus.simpleParent elif self.curAppName in ("thunderbird", ): # to get only toolbars for actual context self.root = api.getForegroundObject() elif self.curAppName == "explorer" and curFocus.simpleParent.simpleParent == desktopObject: debugLog("Desktop list detected, root adjustment") # set root as desktopObject self.root = curFocus.simpleParent.simpleParent # adjust appName as specified in desktopObject above (see condition later) self.curAppName = "csrss" # try a generic solution if ((not self.root) and (ancestors[0] == desktopObject) and (ancestors[1].appModule and ancestors[1].appModule.appName == self.curAppName)): debugLog("Use ancestors[1] for root") self.root = ancestors[1]
def findScript(self): if not (isinstance(self.scriptPath, list) and len(self.scriptPath) == 3): return None module, cls, scriptName = self.scriptPath focus = api.getFocusObject() if not focus: return None if scriptName.startswith("kb:"): # Emulate a key press. return scriptHandler._makeKbEmulateScript(scriptName) import globalCommands # Global plugin level. if cls == 'GlobalPlugin': for plugin in globalPluginHandler.runningPlugins: if module == plugin.__module__: func = getattr(plugin, "script_%s" % scriptName, None) if func: return func # App module level. app = focus.appModule if app and cls == 'AppModule' and module == app.__module__: func = getattr(app, "script_%s" % scriptName, None) if func: return func # Vision enhancement provider level for provider in vision.handler.getActiveProviderInstances(): if isinstance(provider, baseObject.ScriptableObject): if cls == 'VisionEnhancementProvider' and module == provider.__module__: func = getattr(app, "script_%s" % scriptName, None) if func: return func # Tree interceptor level. treeInterceptor = focus.treeInterceptor if treeInterceptor and treeInterceptor.isReady: func = getattr(treeInterceptor, "script_%s" % scriptName, None) if func: return func # NVDAObject level. func = getattr(focus, "script_%s" % scriptName, None) if func: return func for obj in reversed(api.getFocusAncestors()): func = getattr(obj, "script_%s" % scriptName, None) if func and getattr(func, 'canPropagate', False): return func # Global commands. func = getattr(globalCommands.commands, "script_%s" % scriptName, None) if func: return func return None
def internal_hasFocus(sourceContext): focus = api.getFocusObject() if isinstance(focus, NVDAObjects.JAB.JAB) and focus.jabContext == sourceContext: return True ancestors = reversed(api.getFocusAncestors()) return any((isinstance(x, NVDAObjects.JAB.JAB) and x.jabContext == sourceContext for x in ancestors))
def getToolBar(self, key): obj = api.getForegroundObject() if obj.name == None: obj = api.getFocusAncestors()[2] wh = api.winUser.getForegroundWindow() if wh in toolBars: return toolBars[wh].get(key) elif obj.windowClassName == 'wxWindowNR' and self._update_Toolbars(): return toolBars[wh].get(key)
def internal_hasFocus(sourceContext): focus = api.getFocusObject() if isinstance(focus, NVDAObjects.JAB.JAB) and focus.jabContext == sourceContext: return True ancestors = api.getFocusAncestors() for ancestor in reversed(ancestors): if isinstance(ancestor, NVDAObjects.JAB.JAB) and ancestor.jabContext == sourceContext: return True return False
def script_MoveToTopParent(self, gesture): parents = list(filter(lambda p: not p.parent, api.getFocusAncestors())) # This is not standard navigation because we jump to the top of the tree. if parents: message = shared.NavigateTo(u"parent", parents[0]) ui.message(message) else: message = u"No more parents." ui.message(message)
def getFocusContextRegions(obj, oldFocusRegions=None): global _cachedFocusAncestorsEnd # Late import to avoid circular import. from treeInterceptorHandler import TreeInterceptor ancestors = api.getFocusAncestors() ancestorsEnd = len(ancestors) if isinstance(obj, TreeInterceptor): obj = obj.rootNVDAObject # We only want the ancestors of the buffer's root NVDAObject. if obj != api.getFocusObject(): # Search backwards through the focus ancestors to find the index of obj. for index, ancestor in itertools.izip(xrange(len(ancestors) - 1, 0, -1), reversed(ancestors)): if obj == ancestor: ancestorsEnd = index break if oldFocusRegions: # We have the regions from the previous focus, so use them as a cache to avoid rebuilding regions which are the same. # We need to generate new regions from _cachedFocusAncestorsEnd onwards. # However, we must ensure that it is not beyond the last ancestor we wish to consider. # Also, we don't ever want to fetch ancestor 0 (the desktop). newAncestorsStart = max(min(_cachedFocusAncestorsEnd, ancestorsEnd), 1) # Search backwards through the old regions to find the last common region. for index, region in itertools.izip(xrange(len(oldFocusRegions) - 1, -1, -1), reversed(oldFocusRegions)): ancestorIndex = getattr(region, "_focusAncestorIndex", None) if ancestorIndex is None: continue if ancestorIndex < newAncestorsStart: # This is the last common region. # An ancestor may have been skipped and not have a region, which means that we need to grab new ancestors from this point. newAncestorsStart = ancestorIndex + 1 commonRegionsEnd = index + 1 break else: # No common regions were found. commonRegionsEnd = 0 newAncestorsStart = 1 # Yield the common regions. for region in oldFocusRegions[0:commonRegionsEnd]: yield region else: # Fetch all ancestors. newAncestorsStart = 1 for index, parent in enumerate(ancestors[newAncestorsStart:ancestorsEnd], newAncestorsStart): if not parent.isPresentableFocusAncestor: continue region = NVDAObjectRegion(parent, appendText=" ") region._focusAncestorIndex = index region.update() yield region _cachedFocusAncestorsEnd = ancestorsEnd
def doPreDocumentLoadComplete(obj): focusObject = api.getFocusObject() if (not obj.treeInterceptor or not obj.treeInterceptor.isAlive or obj.treeInterceptor.shouldPrepare) and ( obj == focusObject or obj in api.getFocusAncestors()): ti = treeInterceptorHandler.update(obj) if ti: obj.treeInterceptor = ti #Focus may be in this new treeInterceptor, so force focus to look up its treeInterceptor focusObject.treeInterceptor = treeInterceptorHandler.getTreeInterceptor( focusObject) return True
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 findScript(self): if not (isinstance(self.scriptPath,list) and len(self.scriptPath)==3): return None module,cls,scriptName=self.scriptPath focus = api.getFocusObject() if not focus: return None if scriptName.startswith("kb:"): # Emulate a key press. return scriptHandler._makeKbEmulateScript(scriptName) import globalCommands # Global plugin level. if cls=='GlobalPlugin': for plugin in globalPluginHandler.runningPlugins: if module==plugin.__module__: func = getattr(plugin, "script_%s" % scriptName, None) if func: return func # App module level. app = focus.appModule if app and cls=='AppModule' and module==app.__module__: func = getattr(app, "script_%s" % scriptName, None) if func: return func # Tree interceptor level. treeInterceptor = focus.treeInterceptor if treeInterceptor and treeInterceptor.isReady: func = getattr(treeInterceptor , "script_%s" % scriptName, None) # We are no keyboard input return func # NVDAObject level. func = getattr(focus, "script_%s" % scriptName, None) if func: return func for obj in reversed(api.getFocusAncestors()): func = getattr(obj, "script_%s" % scriptName, None) if func and getattr(func, 'canPropagate', False): return func # Global commands. func = getattr(globalCommands.commands, "script_%s" % scriptName, None) if func: return func return None
def prePopup(self): """Prepare for a popup. This should be called before any dialog or menu which should pop up for the user. L{postPopup} should be called after the dialog or menu has been shown. @postcondition: A dialog or menu may be shown. """ nvdaPid = os.getpid() focus = api.getFocusObject() if focus.processID != nvdaPid: self.prevFocus = focus self.prevFocusAncestors = api.getFocusAncestors() if winUser.getWindowThreadProcessID(winUser.getForegroundWindow())[0] != nvdaPid: # This process is not the foreground process, so bring it to the foreground. self.Raise()
def event_gainFocus(self): #See if this object is the focus and the focus is on a group item. #if so, then morph this object to a groupingItem object if self is api.getFocusObject(): groupIndex=watchdog.cancellableSendMessage(self.windowHandle,LVM_GETFOCUSEDGROUP,0,0) if groupIndex>=0: info=self.getListGroupInfo(groupIndex) if info is not None: ancestors=api.getFocusAncestors() if api.getFocusDifferenceLevel()==len(ancestors)-1: self.event_focusEntered() groupingObj=GroupingItem(windowHandle=self.windowHandle,parentNVDAObject=self,groupInfo=info) return eventHandler.queueEvent("gainFocus",groupingObj) return super(List,self).event_gainFocus()
def reloadAppModules(): """Reloads running appModules. especially, it clears the cache of running appModules and deletes them from sys.modules. Each appModule will then be reloaded immediately. """ global appModules state = [] for mod in runningTable.itervalues(): state.append({ key: getattr(mod, key) for key in ( "processID", # #2892: We must save nvdaHelperRemote handles, as we can't reinitialize without a foreground/focus event. # Also, if there is an active context handle such as a loaded buffer, # nvdaHelperRemote can't reinit until that handle dies. "helperLocalBindingHandle", "_inprocRegistrationHandle", # #5380: We must save config profile triggers so they can be cleaned up correctly. # Otherwise, they'll remain active forever. "_configProfileTrigger", ) if hasattr(mod, key) }) # #2892: Don't disconnect from nvdaHelperRemote during termination. mod._helperPreventDisconnect = True terminate() del appModules mods = [ k for k, v in sys.modules.iteritems() if k.startswith("appModules") and v is not None ] for mod in mods: del sys.modules[mod] import appModules initialize() for entry in state: pid = entry.pop("processID") mod = getAppModuleFromProcessID(pid) mod.__dict__.update(entry) # The appModule property for existing NVDAObjects will now be None, since their AppModule died. # Force focus, navigator, etc. objects to re-fetch, # since NVDA depends on the appModule property for these. for obj in itertools.chain( (api.getFocusObject(), api.getNavigatorObject()), api.getFocusAncestors()): try: del obj._appModuleRef except AttributeError: continue # Fetch and cache right away; the process could die any time. obj.appModule
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() import eventHandler eventHandler.handleAppTerminate(deadMod) try: deadMod.terminate() except: log.exception("Error terminating app module %r" % deadMod)
def updateNamespaceSnapshotVars(self): """Update the console namespace with a snapshot of NVDA's current state. This creates/updates variables for the current focus, navigator object, etc. """ self._namespaceSnapshotVars = { "focus": api.getFocusObject(), # Copy the focus ancestor list, as it gets mutated once it is replaced in api.setFocusObject. "focusAnc": list(api.getFocusAncestors()), "fdl": api.getFocusDifferenceLevel(), "fg": api.getForegroundObject(), "nav": api.getNavigatorObject(), "review":api.getReviewPosition(), "mouse": api.getMouseObject(), "brlRegions": braille.handler.buffer.regions, } self.namespace.update(self._namespaceSnapshotVars)
def updateNamespaceSnapshotVars(self): """Update the console namespace with a snapshot of NVDA's current state. This creates/updates variables for the current focus, navigator object, etc. """ self._namespaceSnapshotVars = { "focus": api.getFocusObject(), # Copy the focus ancestor list, as it gets mutated once it is replaced in api.setFocusObject. "focusAnc": list(api.getFocusAncestors()), "fdl": api.getFocusDifferenceLevel(), "fg": api.getForegroundObject(), "nav": api.getNavigatorObject(), "review": api.getReviewPosition(), "mouse": api.getMouseObject(), "brlRegions": braille.handler.buffer.regions, } self.namespace.update(self._namespaceSnapshotVars)
def doPreGainFocus(obj, sleepMode=False): oldForeground = api.getForegroundObject() oldFocus = api.getFocusObject() oldTreeInterceptor = oldFocus.treeInterceptor if oldFocus else None api.setFocusObject(obj) if speech.manager._shouldCancelExpiredFocusEvents(): log._speechManagerDebug( "executeEvent: Removing cancelled speech commands.") # ask speechManager to check if any of it's queued utterances should be cancelled # Note: Removing cancelled speech commands should happen after all dependencies for the isValid check # have been updated: # - lastQueuedFocusObject # - obj.WAS_GAIN_FOCUS_OBJ_ATTR_NAME # - api.getFocusAncestors() # These are updated: # - lastQueuedFocusObject & obj.WAS_GAIN_FOCUS_OBJ_ATTR_NAME # - Set in stack: _trackFocusObject, eventHandler.queueEvent # - Which results in executeEvent being called, then doPreGainFocus # - api.getFocusAncestors() via api.setFocusObject() called in doPreGainFocus speech._manager.removeCancelledSpeechCommands() 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
def prePopup(self): """Prepare for a popup. This should be called before any dialog or menu which should pop up for the user. L{postPopup} should be called after the dialog or menu has been shown. @postcondition: A dialog or menu may be shown. """ focus = api.getFocusObject() # Do not set prevFocus if the focus is on a control rendered by NVDA itself, such as the NVDA menu. # This allows to refer to the control that had focus before opening the menu while still using NVDA # on its own controls. # The check for NVDA process ID can be bypassed by setting the optional attribute # L{isPrevFocusOnNvdaPopup} to L{True} when a NVDA dialog offers customizable bound gestures, # eg. the NVDA Python Console. if focus.processID != globalVars.appPid or getattr(focus, "isPrevFocusOnNvdaPopup", False): self.prevFocus = focus self.prevFocusAncestors = api.getFocusAncestors() if winUser.getWindowThreadProcessID(winUser.getForegroundWindow())[0] != globalVars.appPid: # This process is not the foreground process, so bring it to the foreground. self.Raise()
def script_virtualWindowReview(self, nextHandler): # Find the first focus ansestor that have any display text, according to the display model # This must be the root application window, or something close to that. text = None root = None for ancestor in api.getFocusAncestors(): if ancestor.appModule and ancestor.displayText: root = ancestor break if root: text = root.displayText.replace("\0", ' ') obj = api.getFocusObject() if obj.windowClassName == u'ConsoleWindowClass': info = obj.makeTextInfo(textInfos.POSITION_FIRST) info.expand(textInfos.UNIT_STORY) text = info.clipboardText if text: activate() virtualWindowViewer.outputCtrl.SetValue(text)
def script_virtualWindowReview(self, gesture): # Find the first focus ancestor that have any display text, according to the display model # This must be the root application window, or something close to that. # In case of universal apps, traverse child elements. text = None obj = api.getFocusObject() # Because it may take a while to iterate through elements, play abeep to alert users of this fact and the fact it's a UWP screen. if obj.windowClassName.startswith("Windows.UI.Core"): import tones tones.beep(400, 300) text = "\n".join(obtainUWPWindowText()) tones.beep(400, 50) else: root = None for ancestor in api.getFocusAncestors(): if ancestor.appModule and ancestor.displayText: root = ancestor break if root: info = root.makeTextInfo(textInfos.POSITION_FIRST) # sys.maxint is gone in Python 3 as integer bit width can grow arbitrarily. # Use the static value (0x7fffffff or (2^31)-1) directly. info.move(textInfos.UNIT_LINE, 0x7fffffff, endPoint="end") text = info.clipboardText.replace("\0", " ") if obj.windowClassName == u'ConsoleWindowClass': info = obj.makeTextInfo(textInfos.POSITION_FIRST) info.expand(textInfos.UNIT_STORY) text = info.clipboardText.rstrip() if text: name = api.getForegroundObject().name if name in (None, ""): # Translators: The title of the virtual review window when the foreground window has no name, commonly seen when all windows are minimized. name = _("No title") # Translators: Title of the window shown for reading text on screen via a window. ui.browseableMessage( text, title=_("Virtual review: {screenName}").format( screenName=name)) else: # Translator: Message shown when no text can be virtualized. ui.message(_("No text to display"))
def reloadAppModules(): """Reloads running appModules. especially, it clears the cache of running appModules and deletes them from sys.modules. Each appModule will then be reloaded immediately. """ global appModules state = [] for mod in runningTable.itervalues(): state.append({key: getattr(mod, key) for key in ("processID", # #2892: We must save nvdaHelperRemote handles, as we can't reinitialize without a foreground/focus event. # Also, if there is an active context handle such as a loaded buffer, # nvdaHelperRemote can't reinit until that handle dies. "helperLocalBindingHandle", "_inprocRegistrationHandle", # #5380: We must save config profile triggers so they can be cleaned up correctly. # Otherwise, they'll remain active forever. "_configProfileTrigger", ) if hasattr(mod, key)}) # #2892: Don't disconnect from nvdaHelperRemote during termination. mod._helperPreventDisconnect = True terminate() del appModules mods=[k for k,v in sys.modules.iteritems() if k.startswith("appModules") and v is not None] for mod in mods: del sys.modules[mod] import appModules initialize() for entry in state: pid = entry.pop("processID") mod = getAppModuleFromProcessID(pid) mod.__dict__.update(entry) # The appModule property for existing NVDAObjects will now be None, since their AppModule died. # Force focus, navigator, etc. objects to re-fetch, # since NVDA depends on the appModule property for these. for obj in itertools.chain((api.getFocusObject(), api.getNavigatorObject()), api.getFocusAncestors()): try: del obj._appModuleRef except AttributeError: continue # Fetch and cache right away; the process could die any time. obj.appModule
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 findScript(gesture, searchWebApp=True): global activeWebApp global useInternalBrowser global webAccessEnabled global defaultBrowserScripts focus = api.getFocusObject() if not focus: return None # Import late to avoid circular import. # We need to import this here because this might be the first import of this module # and it might be needed by global maps. import globalCommands globalMapScripts = [] globalMaps = [ inputCore.manager.userGestureMap, inputCore.manager.localeGestureMap ] globalMap = braille.handler.display.gestureMap if globalMap: globalMaps.append(globalMap) for globalMap in globalMaps: for identifier in gesture.identifiers: globalMapScripts.extend(globalMap.getScriptsForGesture(identifier)) # Gesture specific scriptable object. obj = gesture.scriptableObject if obj: func = scriptHandler._getObjScript(obj, gesture, globalMapScripts) if func: return func # Global plugin default scripts. for plugin in globalPluginHandler.runningPlugins: func = scriptHandler._getObjScript(plugin, gesture, globalMapScripts) if func: return func # webApp scripts webApp = focus.getWebApp() if webApp is not None and searchWebApp is True: # Search if a place marker uses this shortcut if webApp.markerManager: func = webApp.markerManager.getMarkerScript( gesture, globalMapScripts) if func: return func func = scriptHandler._getObjScript(webApp.widgetManager, gesture, globalMapScripts) if func: return func activeWidget = getattr(webApp, 'activeWidget', None) if activeWidget is not None: func = scriptHandler._getObjScript(activeWidget, gesture, globalMapScripts) if func: return func func = scriptHandler._getObjScript(webApp, gesture, globalMapScripts) if func: return func ti = webApp.treeInterceptor if hasattr(ti, 'nodeManager') and (useInternalBrowser is True or activeWidget is not None): func = scriptHandler._getObjScript(webApp.presenter, gesture, globalMapScripts) if func: return func func = scriptHandler._getObjScript(ti.nodeManager, gesture, globalMapScripts) if func: return func # App module default scripts. app = focus.appModule if app: # browsers default scripts. if supportWebApp(focus): func = scriptHandler._getObjScript(defaultBrowserScripts, gesture, globalMapScripts) if func: return func func = scriptHandler._getObjScript(app, gesture, globalMapScripts) if func: return func # Tree interceptor level. treeInterceptor = focus.treeInterceptor if treeInterceptor and treeInterceptor.isReady: func = scriptHandler._getObjScript(treeInterceptor, gesture, globalMapScripts) from browseMode import BrowseModeTreeInterceptor if isinstance(treeInterceptor, BrowseModeTreeInterceptor): func = treeInterceptor.getAlternativeScript(gesture, func) if func and (not treeInterceptor.passThrough or getattr( func, "ignoreTreeInterceptorPassThrough", False)) and ( useInternalBrowser is False or getattr(activeWebApp, 'activeWidget', None) is None): return func # NVDAObject level. func = scriptHandler._getObjScript(focus, gesture, globalMapScripts) if func: return func for obj in reversed(api.getFocusAncestors()): func = scriptHandler._getObjScript(obj, gesture, globalMapScripts) if func and getattr(func, 'canPropagate', False): return func # Global commands. func = scriptHandler._getObjScript(globalCommands.commands, gesture, globalMapScripts) if func: return func return None
def findScript(gesture): focus = api.getFocusObject() if not focus: return None # Import late to avoid circular import. # We need to import this here because this might be the first import of this module # and it might be needed by global maps. import globalCommands globalMapScripts = [] globalMaps = [ inputCore.manager.userGestureMap, inputCore.manager.localeGestureMap ] globalMap = braille.handler.display.gestureMap if globalMap: globalMaps.append(globalMap) for globalMap in globalMaps: for identifier in gesture.normalizedIdentifiers: globalMapScripts.extend(globalMap.getScriptsForGesture(identifier)) # Gesture specific scriptable object. obj = gesture.scriptableObject if obj: func = _getObjScript(obj, gesture, globalMapScripts) if func: return func # Global plugin level. for plugin in globalPluginHandler.runningPlugins: func = _getObjScript(plugin, gesture, globalMapScripts) if func: return func # App module level. app = focus.appModule if app: func = _getObjScript(app, gesture, globalMapScripts) if func: return func # Braille display level if isinstance(braille.handler.display, baseObject.ScriptableObject): func = _getObjScript(braille.handler.display, gesture, globalMapScripts) if func: return func # Vision enhancement provider level for provider in vision.handler.getActiveProviderInstances(): if isinstance(provider, baseObject.ScriptableObject): func = _getObjScript(provider, gesture, globalMapScripts) if func: return func # Tree interceptor level. treeInterceptor = focus.treeInterceptor if treeInterceptor and treeInterceptor.isReady: func = _getObjScript(treeInterceptor, gesture, globalMapScripts) from browseMode import BrowseModeTreeInterceptor if isinstance(treeInterceptor, BrowseModeTreeInterceptor): func = treeInterceptor.getAlternativeScript(gesture, func) if func and (not treeInterceptor.passThrough or getattr( func, "ignoreTreeInterceptorPassThrough", False)): return func # NVDAObject level. func = _getObjScript(focus, gesture, globalMapScripts) if func: return func for obj in reversed(api.getFocusAncestors()): func = _getObjScript(obj, gesture, globalMapScripts) if func and getattr(func, 'canPropagate', False): return func # Configuration profile activation scripts func = _getObjScript(globalCommands.configProfileActivationCommands, gesture, globalMapScripts) if func: return func # Global commands. func = _getObjScript(globalCommands.commands, gesture, globalMapScripts) if func: return func return None
def getAllGestureMappings(self, obj=None, ancestors=None): if not obj: obj = api.getFocusObject() ancestors = api.getFocusAncestors() return _AllGestureMappingsRetriever(obj, ancestors).results
def doPreDocumentLoadComplete(obj): focusObject=api.getFocusObject() if (not obj.treeInterceptor or not obj.treeInterceptor.isAlive or obj.treeInterceptor.shouldPrepare) and (obj==focusObject or obj in api.getFocusAncestors()): ti=treeInterceptorHandler.update(obj) if ti: obj.treeInterceptor=ti #Focus may be in this new treeInterceptor, so force focus to look up its treeInterceptor focusObject.treeInterceptor=treeInterceptorHandler.getTreeInterceptor(focusObject) return True
from colors import RGB import config from controlTypes import roleLabels from controlTypes import stateLabels import globalPluginHandler import ui from virtualBuffers import VirtualBuffer isWebElement = lambda theObject: isinstance(theObject.treeInterceptor, VirtualBuffer) developerToolkitIsEnabled = lambda: config.conf["developertoolkit"]["isEnabled" ] isDetailedMessages = lambda: config.conf["developertoolkit"][ "isDetailedMessages"] hasLocation = lambda theObject: hasattr(theObject, 'location') isFocusAncestor = lambda a: a in api.getFocusAncestors() colorAsRGB = lambda: config.conf["developertoolkit"]["displayColorFormat"] == 0 colorAsHex = lambda: config.conf["developertoolkit"]["displayColorFormat"] == 1 colorAsName = lambda: config.conf["developertoolkit"]["displayColorFormat" ] == 2 isColor = lambda x: isinstance(x, RGB) isBool = lambda x: isinstance(x, bool) def getSizeAndPosition(descendant, ancestor): # The relative parent isn't an ancestor of the descendant. if descendant and not isFocusAncestor(ancestor) and hasLocation( descendant): dtk = list( filter( lambda p: isinstance(
def findScript(gesture): focus = api.getFocusObject() if not focus: return None # Import late to avoid circular import. # We need to import this here because this might be the first import of this module # and it might be needed by global maps. import globalCommands globalMapScripts = [] globalMaps = [inputCore.manager.userGestureMap, inputCore.manager.localeGestureMap] globalMap = braille.handler.display.gestureMap if globalMap: globalMaps.append(globalMap) for globalMap in globalMaps: for identifier in gesture.identifiers: globalMapScripts.extend(globalMap.getScriptsForGesture(identifier)) # Gesture specific scriptable object. obj = gesture.scriptableObject if obj: func = _getObjScript(obj, gesture, globalMapScripts) if func: return func # Global plugin level. for plugin in globalPluginHandler.runningPlugins: func = _getObjScript(plugin, gesture, globalMapScripts) if func: return func # App module level. app = focus.appModule if app: func = _getObjScript(app, gesture, globalMapScripts) if func: return func # Tree interceptor level. treeInterceptor = focus.treeInterceptor if treeInterceptor and treeInterceptor.isReady: func = _getObjScript(treeInterceptor, gesture, globalMapScripts) if func and (not treeInterceptor.passThrough or getattr(func,"ignoreTreeInterceptorPassThrough",False)): return func # NVDAObject level. func = _getObjScript(focus, gesture, globalMapScripts) if func: return func for obj in reversed(api.getFocusAncestors()): func = _getObjScript(obj, gesture, globalMapScripts) if func and getattr(func, 'canPropagate', False): return func # Global commands. func = _getObjScript(globalCommands.commands, gesture, globalMapScripts) if func: return func return None
def isAncestorOfCurrentFocus(): return obj in api.getFocusAncestors()
def findScript(gesture): focus = api.getFocusObject() if not focus: return None # Import late to avoid circular import. # We need to import this here because this might be the first import of this module # and it might be needed by global maps. import globalCommands globalMapScripts = [] globalMaps = [ inputCore.manager.userGestureMap, inputCore.manager.localeGestureMap ] globalMap = braille.handler.display.gestureMap if globalMap: globalMaps.append(globalMap) for globalMap in globalMaps: for identifier in gesture.identifiers: globalMapScripts.extend(globalMap.getScriptsForGesture(identifier)) # Gesture specific scriptable object. obj = gesture.scriptableObject if obj: func = _getObjScript(obj, gesture, globalMapScripts) if func: return func # Global plugin level. for plugin in globalPluginHandler.runningPlugins: func = _getObjScript(plugin, gesture, globalMapScripts) if func: return func # App module level. app = focus.appModule if app: func = _getObjScript(app, gesture, globalMapScripts) if func: return func # Tree interceptor level. treeInterceptor = focus.treeInterceptor if treeInterceptor and treeInterceptor.isReady: func = _getObjScript(treeInterceptor, gesture, globalMapScripts) if func and (not treeInterceptor.passThrough or getattr( func, "ignoreTreeInterceptorPassThrough", False)): return func # NVDAObject level. func = _getObjScript(focus, gesture, globalMapScripts) if func: return func for obj in reversed(api.getFocusAncestors()): func = _getObjScript(obj, gesture, globalMapScripts) if func and getattr(func, 'canPropagate', False): return func # Global commands. func = _getObjScript(globalCommands.commands, gesture, globalMapScripts) if func: return func return None
def isAncestorOfCurrentFocus(self): return self._obj in api.getFocusAncestors()