def PutWindowOnForeground(hwnd, sleepNb, sleepTime): winUser.setForegroundWindow(hwnd) for i in [sleepTime]*(sleepNb-1): time.sleep(i) if winUser.getForegroundWindow() == hwnd: return True # last chance KeyboardInputGesture.fromName("alt+Tab").send() time.sleep(sleepTime) if winUser.getForegroundWindow() == hwnd: return True return False
def _isSecureObjectWhileLockScreenActivated( obj: NVDAObjects.NVDAObject) -> bool: """ While Windows is locked, Windows 10 and 11 allow for object navigation outside of the lockscreen. @return: C{True} if the Windows 10/11 lockscreen is active and C{obj} is outside of the lockscreen. According to MS docs, "There is no function you can call to determine whether the workstation is locked." https://docs.microsoft.com/en-gb/windows/win32/api/winuser/nf-winuser-lockworkstation """ runningAppModules = appModuleHandler.runningTable.values() lockAppModule = next(filter(_isLockAppAndAlive, runningAppModules), None) if lockAppModule is None: return False # The LockApp process might be kept alive # So determine if it is active, check the foreground window foregroundHWND = winUser.getForegroundWindow() foregroundProcessId, _threadId = winUser.getWindowThreadProcessID( foregroundHWND) isLockAppForeground = foregroundProcessId == lockAppModule.processID isObjectOutsideLockApp = obj.appModule.processID != foregroundProcessId if isLockAppForeground and isObjectOutsideLockApp: if log.isEnabledFor(log.DEBUG): devInfo = '\n'.join(obj.devInfo) log.debug(f"Attempt at navigating to a secure object: {devInfo}") return True return False
def event_gainFocus(vmID,accContext): tempContext=accContext while tempContext: try: tempContext=bridgeDll.getActiveDescendent(vmID,tempContext) except: tempContext=None try: depth=bridgeDll.getObjectDepth(vmID,tempContext) except: depth=-1 if tempContext and (depth<=0 or bridgeDll.isSameObject(vmID,accContext,tempContext)): tempContext=None if tempContext: bridgeDll.releaseJavaObject(vmID,accContext) accContext=tempContext jabContext=JABContext(vmID=vmID,accContext=accContext) if not winUser.isDescendantWindow(winUser.getForegroundWindow(),jabContext.hwnd): return focus=eventHandler.lastQueuedFocusObject if (isinstance(focus,NVDAObjects.JAB.JAB) and focus.jabContext==jabContext): return obj=NVDAObjects.JAB.JAB(jabContext=jabContext) if obj.role==controlTypes.ROLE_UNKNOWN: return eventHandler.queueEvent("gainFocus",obj)
def event_valueChange(self): global lastMSNHistoryValue if winUser.isDescendantWindow(winUser.getForegroundWindow(),self.windowHandle): value=self.value if value!=lastMSNHistoryValue and config.conf["presentation"]["reportDynamicContentChanges"]: speech.speakText(value) lastMSNHistoryValue=value
def _shouldGetEvents(): global _deferUntilForegroundWindow, _foregroundDefers if _deferUntilForegroundWindow: # #3831: Sometimes, a foreground event is fired, # but GetForegroundWindow() takes a short while to return this new foreground. curForegroundWindow = winUser.getForegroundWindow() curForegroundClassName = winUser.getClassName(curForegroundWindow) futureForegroundClassName = winUser.getClassName( _deferUntilForegroundWindow) if (_foregroundDefers < MAX_FOREGROUND_DEFERS and curForegroundWindow != _deferUntilForegroundWindow): # Wait a core cycle before handling events to give the foreground window time to update. core.requestPump() _foregroundDefers += 1 if isMSAADebugLoggingEnabled(): log.debugWarning( f"Foreground still {curForegroundWindow} ({curForegroundClassName}). " f"Deferring until foreground is {_deferUntilForegroundWindow} ({futureForegroundClassName}), " f"defer count {_foregroundDefers}") return False else: # Either the foreground window is now correct # or we've already had the maximum number of defers. # (Sometimes, foreground events are fired even when the foreground hasn't actually changed.) if curForegroundWindow != _deferUntilForegroundWindow: log.debugWarning( "Foreground took too long to change. " f"Foreground still {curForegroundWindow} ({curForegroundClassName}). " f"Should be {_deferUntilForegroundWindow} ({futureForegroundClassName})" ) _deferUntilForegroundWindow = None return True
def _get_isAlive(self): if self.isLoading: return True root = self.rootNVDAObject if not root: return False if not winUser.isWindow(root.windowHandle): return False if root.appModule.appName.startswith( 'wwahost') and not winUser.isDescendantWindow( winUser.getForegroundWindow(), root.windowHandle): # #4572: When a wwahost hosted app is in the background it gets suspended and all COM calls freeze. # Therefore we don't have enough info to say whether its dead or not. We assume it is alive until we can get a better answer. return True try: if not root.IAccessibleRole: # The root object is dead. return False except watchdog.CallCancelled: # #1831: If the root object isn't responding, treat the buffer as dead. # Otherwise, we'll keep querying it on every focus change and freezing. return False states = root.states if controlTypes.STATE_EDITABLE in states: return False return True
def script_sayCurKeyboardLanguage(self, gesture): import winUser import scriptHandler import ctypes import languageHandler # Getting the handle of the foreground window. curWindow = winUser.getForegroundWindow() # Getting the threadID. threadID = winUser.getWindowThreadProcessID(curWindow)[1] # Getting the keyboard layout iD. klID = winUser.getKeyboardLayout(threadID) # Extract language ID from klID. lID = klID & (2**16 - 1) # Getting the current keyboard language description from ctypes.windll.kernel32.GetLocaleInfoW. # Some language IDs are not available in the local.windows_locale dictionary, it is best to search their description directly in Windows itself buf = ctypes.create_unicode_buffer(1024) res = ctypes.windll.kernel32.GetLocaleInfoW( lID, languageHandler.LOCALE_SLANGUAGE, buf, 1024) desc = buf.value defaultOsl = locale.getdefaultlocale()[0] repeatCount = scriptHandler.getLastScriptRepeatCount() if repeatCount == 0: ui.message(desc) else: ui.message(languageHandler.getLanguageDescription(defaultOsl))
def pumpAll(): global _deferUntilForegroundWindow,_foregroundDefers if _deferUntilForegroundWindow: # #3831: Sometimes, a foreground event is fired, # but GetForegroundWindow() takes a short while to return this new foreground. if _foregroundDefers<MAX_FOREGROUND_DEFERS and winUser.getForegroundWindow()!=_deferUntilForegroundWindow: # Wait a core cycle before handling events to give the foreground window time to update. core.requestPump() _foregroundDefers+=1 return else: # Either the foreground window is now correct # or we've already had the maximum number of defers. # (Sometimes, foreground events are fired even when the foreground hasn't actually changed.) _deferUntilForegroundWindow=None #Receive all the winEvents from the limiter for this cycle winEvents=winEventLimiter.flushEvents() focusWinEvents=[] validFocus=False fakeFocusEvent=None for winEvent in winEvents[0-MAX_WINEVENTS:]: # #4001: Ideally, we'd call shouldAcceptEvent in winEventCallback, # but this causes focus issues when starting applications. if not eventHandler.shouldAcceptEvent(winEventIDsToNVDAEventNames[winEvent[0]], windowHandle=winEvent[1]): continue #We want to only pass on one focus event to NVDA, but we always want to use the most recent possible one if winEvent[0] in (winUser.EVENT_OBJECT_FOCUS,winUser.EVENT_SYSTEM_FOREGROUND): focusWinEvents.append(winEvent) continue else: for focusWinEvent in reversed(focusWinEvents): procFunc=processForegroundWinEvent if focusWinEvent[0]==winUser.EVENT_SYSTEM_FOREGROUND else processFocusWinEvent if procFunc(*(focusWinEvent[1:])): validFocus=True break focusWinEvents=[] if winEvent[0]==winUser.EVENT_SYSTEM_DESKTOPSWITCH: processDesktopSwitchWinEvent(*winEvent[1:]) elif winEvent[0]==winUser.EVENT_OBJECT_SHOW: processShowWinEvent(*winEvent[1:]) elif winEvent[0] in MENU_EVENTIDS+(winUser.EVENT_SYSTEM_SWITCHEND,): # If there is no valid focus event, we may need to use this to fake the focus later. fakeFocusEvent=winEvent else: processGenericWinEvent(*winEvent) for focusWinEvent in reversed(focusWinEvents): procFunc=processForegroundWinEvent if focusWinEvent[0]==winUser.EVENT_SYSTEM_FOREGROUND else processFocusWinEvent if procFunc(*(focusWinEvent[1:])): validFocus=True break if fakeFocusEvent: # Try this as a last resort. if fakeFocusEvent[0] in (winUser.EVENT_SYSTEM_MENUSTART, winUser.EVENT_SYSTEM_MENUPOPUPSTART): # menuStart needs to be handled specially and might act even if there was a valid focus event. processMenuStartWinEvent(*fakeFocusEvent, validFocus=validFocus) elif not validFocus: # Other fake focus events only need to be handled if there was no valid focus event. processFakeFocusWinEvent(*fakeFocusEvent)
def putWindowOnForeground(hwnd, sleepNb=10, sleepTime=0.1): winUser.setForegroundWindow(hwnd) try: winUser.setForegroundWindow(hwnd) except: pass for i in [sleepTime] * (sleepNb - 1): time.sleep(i) if winUser.getForegroundWindow() == hwnd: return True # last chance keyboardHandler.KeyboardInputGesture.fromName("alt+Tab").send() keyboardHandler.KeyboardInputGesture.fromName("alt+Tab").send() time.sleep(sleepTime) if winUser.getForegroundWindow() == hwnd: return True return False
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. """ if winUser.getWindowThreadProcessID(winUser.getForegroundWindow())[0] != os.getpid(): # This process is not the foreground process, so bring it to the foreground. self.Raise()
def postPopup(self): """Clean up after a popup dialog or menu. This should be called after a dialog or menu was popped up for the user. """ if not winUser.isWindowVisible(winUser.getForegroundWindow()): # The current foreground window is invisible, so we want to return to the previous foreground window. # Showing and hiding our main window seems to achieve this. self.Show() self.Hide()
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. """ if winUser.getWindowThreadProcessID( winUser.getForegroundWindow())[0] != os.getpid(): # This process is not the foreground process, so bring it to the foreground. self.Raise()
def getKeyboardLayout(): curWindow = winUser.getForegroundWindow() threadID = winUser.getWindowThreadProcessID(curWindow)[1] klID = winUser.getKeyboardLayout(threadID) lID = klID & (2**16 - 1) try: localeName = locale.windows_locale[lID] except KeyError: localeName = None return localeName
def event_gainFocus(vmID,accContext,hwnd): jabContext=JABContext(hwnd=hwnd,vmID=vmID,accContext=accContext) if not winUser.isDescendantWindow(winUser.getForegroundWindow(),jabContext.hwnd): return focus=eventHandler.lastQueuedFocusObject if (isinstance(focus,NVDAObjects.JAB.JAB) and focus.jabContext==jabContext): return obj=NVDAObjects.JAB.JAB(jabContext=jabContext) if obj.role==controlTypes.ROLE_UNKNOWN: return eventHandler.queueEvent("gainFocus",obj)
def getKeyboardLanguage(self): # Code borrowed from sayCurrentKeyboardLanguage add-on, by Abdel: # https://github.com/abdel792/sayCurrentKeyboardLanguage # Getting the handle of the foreground window. curWindow = winUser.getForegroundWindow() # Getting the threadID. threadID = winUser.getWindowThreadProcessID(curWindow)[1] # Getting the keyboard layout iD. klID = winUser.getKeyboardLayout(threadID) # Extract language ID from klID. lID = klID & (2**16 - 1) return lID
def shouldAcceptEvent(eventName, windowHandle=None): """Check whether an event should be accepted from a platform API. Creating NVDAObjects and executing events can be expensive and might block the main thread noticeably if the object is slow to respond. Therefore, this should be used before NVDAObject creation to filter out any unnecessary events. A platform API handler may do its own filtering before this. """ if not windowHandle: # We can't filter without a window handle. return True key = (eventName, winUser.getWindowThreadProcessID(windowHandle)[0], winUser.getClassName(windowHandle)) if key in _acceptEvents: return True if eventName == "valueChange" and config.conf["presentation"]["progressBarUpdates"]["reportBackgroundProgressBars"]: return True if eventName == "show": # Only accept 'show' events for specific cases, as otherwise we get flooded. return winUser.getClassName(windowHandle) in ( "Frame Notification Bar", # notification bars "tooltips_class32", # tooltips "mscandui21.candidate", "mscandui40.candidate", "MSCandUIWindow_Candidate", # IMM candidates "TTrayAlert", # 5405: Skype ) if eventName == "reorder": # Prevent another flood risk. return winUser.getClassName(windowHandle) == "TTrayAlert" # #4841: Skype if eventName == "alert" and winUser.getClassName(winUser.getAncestor(windowHandle, winUser.GA_PARENT)) == "ToastChildWindowClass": # Toast notifications. return True if eventName in ("menuEnd", "switchEnd", "desktopSwitch"): # #5302, #5462: These events can be fired on the desktop window # or windows that would otherwise be blocked. # Platform API handlers will translate these events to focus events anyway, # so we must allow them here. return True if windowHandle == winUser.getDesktopWindow(): # #5595: Events for the cursor get mapped to the desktop window. return True fg = winUser.getForegroundWindow() if (winUser.isDescendantWindow(fg, windowHandle) # #3899, #3905: Covers cases such as the Firefox Page Bookmarked window and OpenOffice/LibreOffice context menus. or winUser.isDescendantWindow(fg, winUser.getAncestor(windowHandle, winUser.GA_ROOTOWNER))): # This is for the foreground application. return True if (winUser.user32.GetWindowLongW(windowHandle, winUser.GWL_EXSTYLE) & winUser.WS_EX_TOPMOST or winUser.user32.GetWindowLongW(winUser.getAncestor(windowHandle, winUser.GA_ROOT), winUser.GWL_EXSTYLE) & winUser.WS_EX_TOPMOST): # This window or its root is a topmost window. # This includes menus, combo box pop-ups and the task switching list. return True return False
def shouldAcceptEvent(eventName, windowHandle=None): """Check whether an event should be accepted from a platform API. Creating NVDAObjects and executing events can be expensive and might block the main thread noticeably if the object is slow to respond. Therefore, this should be used before NVDAObject creation to filter out any unnecessary events. A platform API handler may do its own filtering before this. """ if not windowHandle: # We can't filter without a window handle. return True key = (eventName, winUser.getWindowThreadProcessID(windowHandle)[0], winUser.getClassName(windowHandle)) if key in _acceptEvents: return True if eventName == "valueChange" and config.conf["presentation"]["progressBarUpdates"]["reportBackgroundProgressBars"]: return True if eventName == "show": # Only accept 'show' events for specific cases, as otherwise we get flooded. return winUser.getClassName(windowHandle) in ( "Frame Notification Bar", # notification bars "tooltips_class32", # tooltips "mscandui21.candidate", "mscandui40.candidate", "MSCandUIWindow_Candidate", # IMM candidates "TTrayAlert", # 5405: Skype ) if eventName == "reorder": # Prevent another flood risk. return winUser.getClassName(windowHandle) == "TTrayAlert" # #4841: Skype if eventName == "alert" and winUser.getClassName(winUser.getAncestor(windowHandle, winUser.GA_PARENT)) == "ToastChildWindowClass": # Toast notifications. return True if eventName in ("menuEnd", "switchEnd", "desktopSwitch"): # #5302, #5462: These events can be fired on the desktop window # or windows that would otherwise be blocked. # Platform API handlers will translate these events to focus events anyway, # so we must allow them here. return True fg = winUser.getForegroundWindow() if (winUser.isDescendantWindow(fg, windowHandle) # #3899, #3905: Covers cases such as the Firefox Page Bookmarked window and OpenOffice/LibreOffice context menus. or winUser.isDescendantWindow(fg, winUser.getAncestor(windowHandle, winUser.GA_ROOTOWNER))): # This is for the foreground application. return True if (winUser.user32.GetWindowLongW(windowHandle, winUser.GWL_EXSTYLE) & winUser.WS_EX_TOPMOST or winUser.user32.GetWindowLongW(winUser.getAncestor(windowHandle, winUser.GA_ROOT), winUser.GWL_EXSTYLE) & winUser.WS_EX_TOPMOST): # This window or its root is a topmost window. # This includes menus, combo box pop-ups and the task switching list. return True return False
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 getImageFromSource(self, current_source): if current_source == "clipboardImage": recognizeImage = self.getImageFromClipboard() imageInfo = RecogImageInfo(0, 0, recognizeImage.width, recognizeImage.height, 1) return imageInfo, recognizeImage elif current_source == "clipboardURL": return None elif current_source == "foreGroundWindow": foregroundWindow = winUser.getForegroundWindow() desktopWindow = winUser.getDesktopWindow() foregroundRect = RECT() desktopRect = RECT() winUser.user32.GetWindowRect(foregroundWindow, byref(foregroundRect)) winUser.user32.GetWindowRect(desktopWindow, byref(desktopRect)) left = max(foregroundRect.left, desktopRect.left) right = min(foregroundRect.right, desktopRect.right) top = max(foregroundRect.top, desktopRect.top) bottom = min(foregroundRect.bottom, desktopRect.bottom) if right <= left or bottom <= top: ui.message(_("Current window position is invalid.")) return from locationHelper import RectLTRB windowRectLTRB = RectLTRB( left=left, right=right, top=top, bottom=bottom ) imageInfo = RecogImageInfo( windowRectLTRB.left, windowRectLTRB.top, windowRectLTRB.width, windowRectLTRB.height, 1 ) recognizeImage = ImageGrab.grab(( windowRectLTRB.top, windowRectLTRB.left, windowRectLTRB.width, windowRectLTRB.height )) return imageInfo, recognizeImage elif current_source == "wholeDesktop": recognizeImage = ImageGrab.grab() imageInfo = RecogImageInfo(0, 0, recognizeImage.width, recognizeImage.height, 1) return imageInfo, recognizeImage else: # Translators: Reported when source is not correct. ui.message(_("Unknown source: %s" % current_source)) return None
def checkWindowListAddonInstalled(): h = winUser.getForegroundWindow() addonCheckList = [ "fakeClipboardAnouncement", "listDesFenetres", "ListeIconesZoneNotification", "DitDossierOuvrirEnregistrer"] for addon in addonHandler.getRunningAddons(): if addon.manifest["name"] in addonCheckList: # Translators: message of message box msg = _("Attention, you must uninstall %s addon because it is now included in this addon.") # noqa:E501 gui.messageBox(msg % addon.manifest["name"]) break winUser.setForegroundWindow(h)
def kwargsFromSuper(cls,kwargs,relation=None): windowHandle=None if relation in ('focus','foreground'): windowHandle=winUser.getForegroundWindow() if not windowHandle: windowHandle=winUser.getDesktopWindow() if windowHandle and relation=="focus": threadID=winUser.getWindowThreadProcessID(windowHandle)[1] threadInfo=winUser.getGUIThreadInfo(threadID) if threadInfo.hwndFocus: windowHandle=threadInfo.hwndFocus elif isinstance(relation,tuple): windowHandle=_windowFromPoint(ctypes.wintypes.POINT(relation[0],relation[1])) if not windowHandle: return False kwargs['windowHandle']=windowHandle return True
def isArabicKeyboardLayout(): """ Test if the keyboard layout is Arabic to avoid an error reported by a user. """ import locale curWindow = winUser.getForegroundWindow() threadID = winUser.getWindowThreadProcessID(curWindow)[1] klID = winUser.getKeyboardLayout(threadID) lID = klID & (2**16 - 1) try: localeName = locale.windows_locale[lID] except KeyError: localeName = None if localeName and localeName.startswith("ar_"): return True return False
def processFocusWinEvent(window,objectID,childID,force=False): """checks to see if the focus win event is not the same as the existing focus, then converts the win event to an NVDA event (instanciating an NVDA Object) then calls processFocusNVDAEvent. If all is ok it returns True. @type window: integer @param objectID: a win event's object ID @type objectID: integer @param childID: a win event's child ID @type childID: integer @param force: If True, the shouldAllowIAccessibleFocusEvent property of the object is ignored. @type force: boolean @returns: True if the focus is valid and was handled, False otherwise. @rtype: boolean """ windowClassName=winUser.getClassName(window) # Generally, we must ignore focus on child windows of SDM windows as we only want the SDM MSAA events. # However, we don't want to ignore focus if the child ID isn't 0, # as this is a child control and the SDM MSAA events don't handle child controls. if childID==0 and not windowClassName.startswith('bosa_sdm') and winUser.getClassName(winUser.getAncestor(window,winUser.GA_PARENT)).startswith('bosa_sdm'): return False rootWindow=winUser.getAncestor(window,winUser.GA_ROOT) # If this window is not within the foreground window and this window or its root window is not a popup window, and this window's root window is not the highest in the z-order if not winUser.isDescendantWindow(winUser.getForegroundWindow(),window) and not (winUser.getWindowStyle(window) & winUser.WS_POPUP or winUser.getWindowStyle(rootWindow)&winUser.WS_POPUP) and winUser.getPreviousWindow(rootWindow)!=0: # This is a focus event from a background window, so ignore it. return False #Notify appModuleHandler of this new foreground window appModuleHandler.update(winUser.getWindowThreadProcessID(window)[0]) #If Java access bridge is running, and this is a java window, then pass it to java and forget about it if JABHandler.isRunning and JABHandler.isJavaWindow(window): JABHandler.event_enterJavaWindow(window) return True #Convert the win event to an NVDA event NVDAEvent=winEventToNVDAEvent(winUser.EVENT_OBJECT_FOCUS,window,objectID,childID,useCache=False) if not NVDAEvent: return False eventName,obj=NVDAEvent if (childID==0 and obj.IAccessibleRole==oleacc.ROLE_SYSTEM_LIST) or (objectID==winUser.OBJID_CLIENT and "SysListView32" in obj.windowClassName): # Some controls incorrectly fire focus on child ID 0, even when there is a child with focus. try: realChildID=obj.IAccessibleObject.accFocus except: realChildID=None if isinstance(realChildID,int) and realChildID>0 and realChildID!=childID: realObj=NVDAObjects.IAccessible.IAccessible(IAccessibleObject=obj.IAccessibleObject,IAccessibleChildID=realChildID,event_windowHandle=window,event_objectID=objectID,event_childID=realChildID) if realObj: obj=realObj return processFocusNVDAEvent(obj,force=force)
def processForegroundWinEvent(window, objectID, childID): """checks to see if the foreground win event is not the same as the existing focus or any of its parents, then converts the win event to an NVDA event (instantiating an NVDA Object) and then checks the NVDAObject against the existing focus object. If all is ok it queues the foreground event to NVDA and returns True. @param window: a win event's window handle @type window: integer @param objectID: a win event's object ID @type objectID: integer @param childID: a win event's child ID @type childID: integer @returns: True if the foreground was processed, False otherwise. @rtype: boolean """ # Ignore foreground events on windows that aren't the current foreground window if window != winUser.getForegroundWindow(): return False # If there is a pending gainFocus, it will handle the foreground object. oldFocus = eventHandler.lastQueuedFocusObject # If this foreground win event's window is an ancestor of the existing focus's window, then ignore it if (isinstance(oldFocus, NVDAObjects.window.Window) and winUser.isDescendantWindow(window, oldFocus.windowHandle)): return False # If the existing focus has the same win event params as these, then ignore this event if (isinstance(oldFocus, NVDAObjects.IAccessible.IAccessible) and window == oldFocus.event_windowHandle and objectID == oldFocus.event_objectID and childID == oldFocus.event_childID): return False # Notify appModuleHandler of this new foreground window appModuleHandler.update(winUser.getWindowThreadProcessID(window)[0]) # If Java access bridge is running, and this is a java window, then pass it to java and forget about it if JABHandler.isRunning and JABHandler.isJavaWindow(window): JABHandler.event_enterJavaWindow(window) return True # Convert the win event to an NVDA event NVDAEvent = winEventToNVDAEvent(winUser.EVENT_SYSTEM_FOREGROUND, window, objectID, childID, useCache=False) if not NVDAEvent: return False eventHandler.queueEvent(*NVDAEvent) 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 _shouldGetEvents(): global _deferUntilForegroundWindow, _foregroundDefers if _deferUntilForegroundWindow: # #3831: Sometimes, a foreground event is fired, # but GetForegroundWindow() takes a short while to return this new foreground. if ( _foregroundDefers < MAX_FOREGROUND_DEFERS and winUser.getForegroundWindow() != _deferUntilForegroundWindow ): # Wait a core cycle before handling events to give the foreground window time to update. core.requestPump() _foregroundDefers += 1 return False else: # Either the foreground window is now correct # or we've already had the maximum number of defers. # (Sometimes, foreground events are fired even when the foreground hasn't actually changed.) _deferUntilForegroundWindow = None return True
def callback(): h = winUser.getForegroundWindow() obj = api.getFocusObject() if gui.messageBox( # Translators: message to ask the user if he want quit RadioSure. _("Are you sure you want to quit RadioSure?"), # Translators: dialog's title. _("Warning"), wx.YES_NO | wx.NO_DEFAULT | wx.ICON_WARNING) == wx.YES: oldSpeechMode = getSpeechMode() setSpeechMode_off() winUser.setForegroundWindow(h) obj.setFocus() eventHandler.queueEvent("gainFocus", obj) time.sleep(0.1) api.processPendingEvents() clickButton("exitButton") setSpeechMode(oldSpeechMode) else: winUser.setForegroundWindow(h) time.sleep(0.5) obj.setFocus() eventHandler.queueEvent("gainFocus", obj)
def _get_isAlive(self): if self.isLoading: return True root=self.rootNVDAObject if not root: return False if not winUser.isWindow(root.windowHandle): return False if root.appModule.appName.startswith('wwahost') and not winUser.isDescendantWindow(winUser.getForegroundWindow(),root.windowHandle): # #4572: When a wwahost hosted app is in the background it gets suspended and all COM calls freeze. # Therefore we don't have enough info to say whether its dead or not. We assume it is alive until we can get a better answer. return True try: if not root.IAccessibleRole: # The root object is dead. return False except watchdog.CallCancelled: # #1831: If the root object isn't responding, treat the buffer as dead. # Otherwise, we'll keep querying it on every focus change and freezing. return False states=root.states if controlTypes.STATE_EDITABLE in states: return False return True
def processForegroundWinEvent(window,objectID,childID): """checks to see if the foreground win event is not the same as the existing focus or any of its parents, then converts the win event to an NVDA event (instanciating an NVDA Object) and then checks the NVDAObject against the existing focus object. If all is ok it queues the foreground event to NVDA and returns True. @param window: a win event's window handle @type window: integer @param objectID: a win event's object ID @type objectID: integer @param childID: a win event's child ID @type childID: integer @returns: True if the foreground was processed, False otherwise. @rtype: boolean """ #Ignore foreground events on windows that aren't the current foreground window if window!=winUser.getForegroundWindow(): return False # If there is a pending gainFocus, it will handle the foreground object. oldFocus=eventHandler.lastQueuedFocusObject #If this foreground win event's window is an ancestor of the existing focus's window, then ignore it if isinstance(oldFocus,NVDAObjects.window.Window) and winUser.isDescendantWindow(window,oldFocus.windowHandle): return False #If the existing focus has the same win event params as these, then ignore this event if isinstance(oldFocus,NVDAObjects.IAccessible.IAccessible) and window==oldFocus.event_windowHandle and objectID==oldFocus.event_objectID and childID==oldFocus.event_childID: return False #Notify appModuleHandler of this new foreground window appModuleHandler.update(winUser.getWindowThreadProcessID(window)[0]) #If Java access bridge is running, and this is a java window, then pass it to java and forget about it if JABHandler.isRunning and JABHandler.isJavaWindow(window): JABHandler.event_enterJavaWindow(window) return True #Convert the win event to an NVDA event NVDAEvent=winEventToNVDAEvent(winUser.EVENT_SYSTEM_FOREGROUND,window,objectID,childID,useCache=False) if not NVDAEvent: return False eventHandler.queueEvent(*NVDAEvent) return True
def IsActive(self): #4714: In wxPython 3, ProgressDialog.IsActive always seems to return False. return winUser.isDescendantWindow(winUser.getForegroundWindow(), self.Handle)
def event_valueChange(self): if self.event_childID==0 and self.event_objectID == winUser.OBJID_CLIENT and winUser.isDescendantWindow(winUser.getForegroundWindow(),self.windowHandle): # Acrobat has indicated that a page has died and been replaced by a new one. # The new page has the same event params, so we must bypass NVDA's IAccessible caching. obj = getNVDAObjectFromEvent(self.windowHandle, -4, 0) if not obj: return eventHandler.queueEvent("gainFocus",obj)
def shouldAcceptEvent(eventName, windowHandle=None): """Check whether an event should be accepted from a platform API. Creating NVDAObjects and executing events can be expensive and might block the main thread noticeably if the object is slow to respond. Therefore, this should be used before NVDAObject creation to filter out any unnecessary events. A platform API handler may do its own filtering before this. """ if not windowHandle: # We can't filter without a window handle. return True wClass = winUser.getClassName(windowHandle) key = (eventName, winUser.getWindowThreadProcessID(windowHandle)[0], wClass) if key in _acceptEvents: return True if eventName == "valueChange" and config.conf["presentation"][ "progressBarUpdates"]["reportBackgroundProgressBars"]: return True if eventName == "hide": return False if eventName == "show": # Only accept 'show' events for specific cases, as otherwise we get flooded. return wClass in ( "Frame Notification Bar", # notification bars "tooltips_class32", # tooltips "mscandui21.candidate", "mscandui40.candidate", "MSCandUIWindow_Candidate", # IMM candidates "TTrayAlert", # 5405: Skype ) if eventName == "alert" and winUser.getClassName( winUser.getAncestor(windowHandle, winUser.GA_PARENT)) == "ToastChildWindowClass": # Toast notifications. return True if eventName in ("menuEnd", "switchEnd", "desktopSwitch"): # #5302, #5462: These events can be fired on the desktop window # or windows that would otherwise be blocked. # Platform API handlers will translate these events to focus events anyway, # so we must allow them here. return True if windowHandle == winUser.getDesktopWindow(): # #5595: Events for the cursor get mapped to the desktop window. return True # #6713: Edge (and soon all UWP apps) will no longer have windows as descendants of the foreground window. # However, it does look like they are always equal to or descendants of the "active" window of the input thread. gi = winUser.getGUIThreadInfo(0) if wClass.startswith('Windows.UI.Core'): if winUser.isDescendantWindow(gi.hwndActive, windowHandle): return True fg = winUser.getForegroundWindow() fgClassName = winUser.getClassName(fg) if wClass == "NetUIHWND" and fgClassName in ("Net UI Tool Window Layered", "Net UI Tool Window"): # #5504: In Office >= 2013 with the ribbon showing only tabs, # when a tab is expanded, the window we get from the focus object is incorrect. # This window isn't beneath the foreground window, # so our foreground application checks fail. # Just compare the root owners. if winUser.getAncestor(windowHandle, winUser.GA_ROOTOWNER) == winUser.getAncestor( fg, winUser.GA_ROOTOWNER): return True if (winUser.isDescendantWindow(fg, windowHandle) # #3899, #3905: Covers cases such as the Firefox Page Bookmarked window and OpenOffice/LibreOffice context menus. or winUser.isDescendantWindow( fg, winUser.getAncestor(windowHandle, winUser.GA_ROOTOWNER))): # This is for the foreground application. return True if (winUser.user32.GetWindowLongW(windowHandle, winUser.GWL_EXSTYLE) & winUser.WS_EX_TOPMOST or winUser.user32.GetWindowLongW( winUser.getAncestor(windowHandle, winUser.GA_ROOT), winUser.GWL_EXSTYLE) & winUser.WS_EX_TOPMOST): # This window or its root is a topmost window. # This includes menus, combo box pop-ups and the task switching list. return True # This may be an event for a windowless embedded Chrome document # (E.g. Microsoft Loop component). if wClass == "Chrome_RenderWidgetHostHWND": # The event is for a Chromium document if winUser.getClassName(gi.hwndFocus) == "Chrome_WidgetWin_0": # The real win32 focus is on a Chrome embedding window. # See if we can get from the event's Chromium document to the Chrome embedding window # via ancestors in the UIA tree. rootWindowHandle = winUser.getAncestor(windowHandle, winUser.GA_ROOT) import UIAHandler try: rootElement = UIAHandler.handler.clientObject.elementFromHandle( rootWindowHandle) except COMError: log.debugWarning( "Could not create UIA element for root of Chromium document", exc_info=True) else: condition = UIAHandler.handler.clientObject.CreatePropertyCondition( UIAHandler.UIA_NativeWindowHandlePropertyId, gi.hwndFocus) try: walker = UIAHandler.handler.clientObject.CreateTreeWalker( condition) ancestorElement = walker.NormalizeElement(rootElement) except COMError: log.debugWarning( "Unable to normalize root Chromium element to focused ancestor", exc_info=True) ancestorElement = None if ancestorElement: # The real focused window is an ancestor of the Chromium document in the UIA tree. return True return False
def shouldAcceptEvent(eventName, windowHandle=None): """Check whether an event should be accepted from a platform API. Creating NVDAObjects and executing events can be expensive and might block the main thread noticeably if the object is slow to respond. Therefore, this should be used before NVDAObject creation to filter out any unnecessary events. A platform API handler may do its own filtering before this. """ if not windowHandle: # We can't filter without a window handle. return True wClass = winUser.getClassName(windowHandle) key = (eventName, winUser.getWindowThreadProcessID(windowHandle)[0], wClass) if key in _acceptEvents: return True if eventName == "valueChange" and config.conf["presentation"][ "progressBarUpdates"]["reportBackgroundProgressBars"]: return True if eventName == "show": # Only accept 'show' events for specific cases, as otherwise we get flooded. return wClass in ( "Frame Notification Bar", # notification bars "tooltips_class32", # tooltips "mscandui21.candidate", "mscandui40.candidate", "MSCandUIWindow_Candidate", # IMM candidates "TTrayAlert", # 5405: Skype ) if eventName == "reorder": # Prevent another flood risk. return wClass == "TTrayAlert" # #4841: Skype if eventName == "alert" and winUser.getClassName( winUser.getAncestor(windowHandle, winUser.GA_PARENT)) == "ToastChildWindowClass": # Toast notifications. return True if eventName in ("menuEnd", "switchEnd", "desktopSwitch"): # #5302, #5462: These events can be fired on the desktop window # or windows that would otherwise be blocked. # Platform API handlers will translate these events to focus events anyway, # so we must allow them here. return True if windowHandle == winUser.getDesktopWindow(): # #5595: Events for the cursor get mapped to the desktop window. return True # #6713: Edge (and soon all UWP apps) will no longer have windows as descendants of the foreground window. # However, it does look like they are always equal to or descendants of the "active" window of the input thread. if wClass.startswith('Windows.UI.Core'): gi = winUser.getGUIThreadInfo(0) if winUser.isDescendantWindow(gi.hwndActive, windowHandle): return True fg = winUser.getForegroundWindow() if wClass == "NetUIHWND" and winUser.getClassName( fg) == "Net UI Tool Window Layered": # #5504: In Office >= 2013 with the ribbon showing only tabs, # when a tab is expanded, the window we get from the focus object is incorrect. # This window isn't beneath the foreground window, # so our foreground application checks fail. # Just compare the root owners. if winUser.getAncestor(windowHandle, winUser.GA_ROOTOWNER) == winUser.getAncestor( fg, winUser.GA_ROOTOWNER): return True if (winUser.isDescendantWindow(fg, windowHandle) # #3899, #3905: Covers cases such as the Firefox Page Bookmarked window and OpenOffice/LibreOffice context menus. or winUser.isDescendantWindow( fg, winUser.getAncestor(windowHandle, winUser.GA_ROOTOWNER))): # This is for the foreground application. return True if (winUser.user32.GetWindowLongW(windowHandle, winUser.GWL_EXSTYLE) & winUser.WS_EX_TOPMOST or winUser.user32.GetWindowLongW( winUser.getAncestor(windowHandle, winUser.GA_ROOT), winUser.GWL_EXSTYLE) & winUser.WS_EX_TOPMOST): # This window or its root is a topmost window. # This includes menus, combo box pop-ups and the task switching list. return True return False
def _get_isInForeground(self): fg=winUser.getForegroundWindow() return self.windowHandle==fg or winUser.isDescendantWindow(fg,self.windowHandle)
def shouldAcceptEvent(eventName, windowHandle=None): """Check whether an event should be accepted from a platform API. Creating NVDAObjects and executing events can be expensive and might block the main thread noticeably if the object is slow to respond. Therefore, this should be used before NVDAObject creation to filter out any unnecessary events. A platform API handler may do its own filtering before this. """ if not windowHandle: # We can't filter without a window handle. return True wClass = winUser.getClassName(windowHandle) key = (eventName, winUser.getWindowThreadProcessID(windowHandle)[0], wClass) if key in _acceptEvents: return True if eventName == "valueChange" and config.conf["presentation"]["progressBarUpdates"]["reportBackgroundProgressBars"]: return True if eventName == "show": # Only accept 'show' events for specific cases, as otherwise we get flooded. return wClass in ( "Frame Notification Bar", # notification bars "tooltips_class32", # tooltips "mscandui21.candidate", "mscandui40.candidate", "MSCandUIWindow_Candidate", # IMM candidates "TTrayAlert", # 5405: Skype ) if eventName == "reorder": # Prevent another flood risk. return wClass == "TTrayAlert" # #4841: Skype if eventName == "alert" and winUser.getClassName(winUser.getAncestor(windowHandle, winUser.GA_PARENT)) == "ToastChildWindowClass": # Toast notifications. return True if eventName in ("menuEnd", "switchEnd", "desktopSwitch"): # #5302, #5462: These events can be fired on the desktop window # or windows that would otherwise be blocked. # Platform API handlers will translate these events to focus events anyway, # so we must allow them here. return True if windowHandle == winUser.getDesktopWindow(): # #5595: Events for the cursor get mapped to the desktop window. return True # #6713: Edge (and soon all UWP apps) will no longer have windows as descendants of the foreground window. # However, it does look like they are always equal to or descendants of the "active" window of the input thread. if wClass.startswith('Windows.UI.Core'): gi=winUser.getGUIThreadInfo(0) if winUser.isDescendantWindow(gi.hwndActive,windowHandle): return True fg = winUser.getForegroundWindow() if wClass == "NetUIHWND" and winUser.getClassName(fg) == "Net UI Tool Window Layered": # #5504: In Office >= 2013 with the ribbon showing only tabs, # when a tab is expanded, the window we get from the focus object is incorrect. # This window isn't beneath the foreground window, # so our foreground application checks fail. # Just compare the root owners. if winUser.getAncestor(windowHandle, winUser.GA_ROOTOWNER) == winUser.getAncestor(fg, winUser.GA_ROOTOWNER): return True if (winUser.isDescendantWindow(fg, windowHandle) # #3899, #3905: Covers cases such as the Firefox Page Bookmarked window and OpenOffice/LibreOffice context menus. or winUser.isDescendantWindow(fg, winUser.getAncestor(windowHandle, winUser.GA_ROOTOWNER))): # This is for the foreground application. return True if (winUser.user32.GetWindowLongW(windowHandle, winUser.GWL_EXSTYLE) & winUser.WS_EX_TOPMOST or winUser.user32.GetWindowLongW(winUser.getAncestor(windowHandle, winUser.GA_ROOT), winUser.GWL_EXSTYLE) & winUser.WS_EX_TOPMOST): # This window or its root is a topmost window. # This includes menus, combo box pop-ups and the task switching list. return True return False