Fix Chromium context menu bouncing back to browse mode (#21184)
Closes #18670
Summary of the issue:
In Chromium-based browsers (Chrome, Edge), pressing the applications key or Shift+F10 on an unfocused link in browse mode often opens the context menu visually, briefly announces the first menu item (Open link in new tab), and immediately bounces NVDA back into browse mode on the link. Arrow keys then navigate the webpage instead of the open context menu until focus is manually restored.
Description of user facing changes:
In Chromium-based web browsers, opening the context menu from browse mode with the applications key or Shift+F10 now keeps focus in the context menu instead of bouncing back to browse mode.
Description of developer facing changes:
None.
Description of development approach:
When BrowseModeTreeInterceptor.script_passThrough runs for Applications or Shift+F10 on an unfocused element in browse mode, _focusLastFocusableObject() requests focus asynchronously via accSelect(SELFLAG_TAKEFOCUS) and script_passThrough immediately passes the gesture through:
Chromium's browser process opens the native Views UIA context menu (ShowInactive()) and fires UIA_AutomationFocusChangedEventId on the first MenuItemView, which NVDA's UIA MTA thread queues directly into eventQueue.
Meanwhile, the renderer's MSAA EVENT_OBJECT_FOCUS for the link on Chrome_RenderWidgetHostHWND either arrives after the menu opens or is overtaken by the UIA MTA thread while shouldAllowIAccessibleFocusEvent runs on the main thread. Because MenuHost uses ShowInactive(), the link still reports STATE_SYSTEM_FOCUSED, so IAccessibleHandler.processFocusNVDAEvent queues gainFocus for the link after the menu item and bounces NVDA back to browse mode.
To fix this without adding input lag or fragile timeouts to script_passThrough:
Added _hasActiveUIAFocusInSameProcess(obj) in source/IAccessibleHandler/__init__.py and called it in processFocusNVDAEvent right after obj.shouldAllowIAccessibleFocusEvent.
For non-forced Chrome_RenderWidgetHostHWND focus events, if eventHandler.lastQueuedFocusObject is a NVDAObjects.UIA.UIA object in the same process whose UIAElement.currentHasKeyboardFocus is still True (catching COMError as False), the stale MSAA focus event is dropped.
Scoping to Chrome_RenderWidgetHostHWND and the same process ensures legitimate MSAA controls (such as Win32 #32768 popup menus over UIA hosts, cross-process Alt+Tab, and transitions back from the browser's UIA address bar or closing the context menu with Escape) remain unaffected.