From 15f7c3549804d5952acb052dc3da693794eb5ddf Mon Sep 17 00:00:00 2001 From: cryptotavares Date: Tue, 17 Nov 2026 00:18:03 +0000 Subject: [PATCH 1/4] fix: refuse Android taps on a covered target (TARGET_OBSCURED) Android taps had no occlusion check: a tap on a target covered by the Expo dev-client "Tools" button, a floating tab bar or the keyboard reported success and hit the overlay. Before each tap and long press, check the snapshot the target came from (no device call): a drawn node of a higher window (the keyboard, a system window) at the tap point, or a node of the same window drawn after the target (by the helper's drawing-order) that is not part of the target per `hitsTarget`, throws `TargetObscuredError`. A node of the input-method window sets `keyboard: true`, so `click --dismiss-keyboard` can retry. Stock uiautomator dumps have no window or draw-order data, so their taps go ahead as before. --- .../adb-helper-search-keyboard.xml | 281 +++++ .../__fixtures__/adb-helper-wallet-home.xml | 1047 +++++++++++++++++ src/backends/adb-backend.test.ts | 41 + src/backends/adb-backend.ts | 81 +- src/utils/android-hit-test.test.ts | 322 +++++ src/utils/android-hit-test.ts | 376 ++++++ src/utils/hit-test.ts | 19 +- 7 files changed, 2160 insertions(+), 7 deletions(-) create mode 100644 src/backends/__fixtures__/adb-helper-search-keyboard.xml create mode 100644 src/backends/__fixtures__/adb-helper-wallet-home.xml create mode 100644 src/utils/android-hit-test.test.ts create mode 100644 src/utils/android-hit-test.ts diff --git a/src/backends/__fixtures__/adb-helper-search-keyboard.xml b/src/backends/__fixtures__/adb-helper-search-keyboard.xml new file mode 100644 index 0000000..afbbccd --- /dev/null +++ b/src/backends/__fixtures__/adb-helper-search-keyboard.xml @@ -0,0 +1,281 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/backends/__fixtures__/adb-helper-wallet-home.xml b/src/backends/__fixtures__/adb-helper-wallet-home.xml new file mode 100644 index 0000000..d44ef6d --- /dev/null +++ b/src/backends/__fixtures__/adb-helper-wallet-home.xml @@ -0,0 +1,1047 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/backends/adb-backend.test.ts b/src/backends/adb-backend.test.ts index 4079c7c..f8f339a 100644 --- a/src/backends/adb-backend.test.ts +++ b/src/backends/adb-backend.test.ts @@ -724,6 +724,47 @@ describe('AdbBackend.tapElement', () => { ).toHaveLength(0); }); + it('refuses to tap an element that another node covers', async () => { + const covered = parseAndroidHierarchy( + ``, + ); + const target = findElement(covered, { identifier: 'submit' }, true); + + await expect( + backend.tapElement( + { identifier: 'submit' }, + { element: target as UIElement }, + ), + ).rejects.toMatchObject({ + code: 'TARGET_OBSCURED', + keyboard: false, + message: expect.stringContaining('label="Tools"'), + }); + expect(tapCalls()).toHaveLength(0); + }); + + it('refuses to long-press an element that the keyboard covers', async () => { + mockExecStrict.mockImplementation(async (_cmd, args) => { + if (args?.includes('wm')) { + return 'Physical size: 1080x2400'; + } + return args?.includes('cat') || args?.includes('dump') + ? `` + : ''; + }); + + await expect( + backend.longPress({ identifier: 'far' }), + ).rejects.toMatchObject({ + code: 'TARGET_OBSCURED', + keyboard: true, + message: expect.stringContaining('by the keyboard: '), + }); + expect( + mockExecStrict.mock.calls.filter(([, args]) => args?.includes('swipe')), + ).toHaveLength(0); + }); + it('snapshots to find the element when none is passed', async () => { mockExecStrict.mockImplementation(async (_cmd, args) => args?.includes('cat') || args?.includes('dump') diff --git a/src/backends/adb-backend.ts b/src/backends/adb-backend.ts index 2dde8bf..88f6cbb 100644 --- a/src/backends/adb-backend.ts +++ b/src/backends/adb-backend.ts @@ -55,6 +55,11 @@ import type { } from './types.js'; import { runWebViewCdp } from './webview-cdp.js'; import { ACCEPT_LABELS, DENY_LABELS } from '../utils/alert-labels.js'; +import { + assertAndroidHittable, + setAndroidNodeInfo, +} from '../utils/android-hit-test.js'; +import type { AndroidWindowInfo } from '../utils/android-hit-test.js'; import { findElement, describeElement, @@ -326,7 +331,9 @@ export class AdbBackend implements DeviceBackend { ); } - const { x, y } = visibleCenter(element, await this.#cachedWindowSize()); + const screen = await this.#cachedWindowSize(); + const { x, y } = visibleCenter(element, screen); + assertAndroidHittable(element, { x, y }, screen); await this.tapCoordinates(x, y); return { @@ -952,10 +959,9 @@ export class AdbBackend implements DeviceBackend { ); } - const { x: cx, y: cy } = visibleCenter( - element, - await this.#cachedWindowSize(), - ); + const screen = await this.#cachedWindowSize(); + const { x: cx, y: cy } = visibleCenter(element, screen); + assertAndroidHittable(element, { x: cx, y: cy }, screen); await this.#adb([ 'shell', 'input', @@ -1280,6 +1286,8 @@ function collectTextValues(elements: UIElement[], texts: string[]): void { export function parseAndroidHierarchy(xml: string): UIElement[] { const roots: UIElement[] = []; const stack: UIElement[][] = [roots]; + // The nearest parsed ancestor of each open tag; undefined at the top. + const parents: (UIElement | undefined)[] = [undefined]; // Matches all , , and tags in document order const tagRegex = /<(\/?)node(?:\s+([^>]*?))?\s*(\/?)>/gu; @@ -1294,6 +1302,7 @@ export function parseAndroidHierarchy(xml: string): UIElement[] { if (isClosing) { if (stack.length > 1) { stack.pop(); + parents.pop(); } continue; } @@ -1305,16 +1314,78 @@ export function parseAndroidHierarchy(xml: string): UIElement[] { element.children = []; } parent.push(element); + setAndroidNodeInfo(element, { + roots, + parent: parents[parents.length - 1], + ...parseHitTestAttributes(attrs), + }); } if (!isSelfClosing) { // Even invalid nodes need a frame, or their closing tag pops the parent. stack.push(element?.children ?? parent); + parents.push(element ?? parents[parents.length - 1]); } } return roots; } +/** + * Read the attributes the tap hit test needs. The snapshot helper adds + * `drawing-order`, `visible-to-user` and, on window roots, `window-*`; a + * stock uiautomator dump has none of them. + * + * @param attrs - The raw attribute string of the tag. + * @returns The hit-test data. + */ +function parseHitTestAttributes(attrs: string): { + drawingOrder: number | undefined; + visibleToUser: boolean; + clickable: boolean; + window: AndroidWindowInfo | undefined; +} { + const get = (name: string): string | undefined => + attrs.match(new RegExp(`\\s${name}="([^"]*)"`, 'u'))?.[1]; + const drawingOrder = get('drawing-order'); + const windowType = get('window-type'); + const windowLayer = get('window-layer'); + const windowBounds = parseBounds(get('window-bounds')); + return { + drawingOrder: + drawingOrder === undefined ? undefined : parseInt(drawingOrder, 10), + visibleToUser: get('visible-to-user') !== 'false', + clickable: get('clickable') === 'true', + window: + windowType !== undefined && windowLayer !== undefined && windowBounds + ? { + type: parseInt(windowType, 10), + layer: parseInt(windowLayer, 10), + bounds: windowBounds, + } + : undefined, + }; +} + +/** + * @param bounds - Bounds in the `[x1,y1][x2,y2]` format. + * @returns The frame, or undefined when missing or malformed. + */ +function parseBounds( + bounds: string | undefined, +): UIElement['frame'] | undefined { + const match = bounds?.match(/\[(-?\d+),(-?\d+)\]\[(-?\d+),(-?\d+)\]/u); + if (!match) { + return undefined; + } + const [x1, y1, x2, y2] = match.slice(1).map((value) => parseInt(value, 10)); + return { + x: x1, + y: y1, + width: Math.max(0, x2 - x1), + height: Math.max(0, y2 - y1), + }; +} + /** * Parse one node. Off-screen views can have negative or inverted bounds. * diff --git a/src/utils/android-hit-test.test.ts b/src/utils/android-hit-test.test.ts new file mode 100644 index 0000000..30bad23 --- /dev/null +++ b/src/utils/android-hit-test.test.ts @@ -0,0 +1,322 @@ +import { readFileSync } from 'node:fs'; +import { describe, expect, it } from 'vitest'; + +import { assertAndroidHittable } from './android-hit-test.js'; +import { findElement, visibleCenter } from './element.js'; +import { TargetObscuredError } from './hit-test.js'; +import { parseAndroidHierarchy } from '../backends/adb-backend.js'; +import type { UIElement } from '../backends/types.js'; + +const SCREEN = { width: 1080, height: 2400 }; + +/** + * Snapshot-helper XML recorded on the Android emulator (1080x2400, + * MetaMask Mobile dev build). Texts, labels and most resource ids are + * blanked; tree, bounds, windows and drawing order are as captured. + * + * - wallet home, with the Expo dev-client "Tools" button over the + * hamburger menu button; + * - the account list search, with Gboard's floating toolbar shown (the + * emulator has a hardware keyboard). + * + * @param name - The fixture name. + * @returns The parsed hierarchy. + */ +const fixture = (name: string): UIElement[] => + parseAndroidHierarchy( + readFileSync( + new URL( + `../backends/__fixtures__/adb-helper-${name}.xml`, + import.meta.url, + ), + 'utf8', + ), + ); + +/** + * Run the hit test at the element's visible center. + * + * @param element - The element to tap. + * @returns The error thrown, or undefined when the tap may go ahead. + */ +const check = (element: UIElement): TargetObscuredError | undefined => { + try { + assertAndroidHittable(element, visibleCenter(element, SCREEN), SCREEN); + return undefined; + } catch (error) { + if (error instanceof TargetObscuredError) { + return error; + } + throw error; + } +}; + +const byId = (hierarchy: UIElement[], identifier: string): UIElement => { + const element = findElement(hierarchy, { identifier }, true); + if (!element) { + throw new Error(`no ${identifier} in the fixture`); + } + return element; +}; + +const node = (attrs: string, children = ''): string => + children ? `${children}` : ``; + +const xml = (...windows: string[]): string => + `${windows.join('')}`; + +const APP_WINDOW = + 'window-index="1" window-type="1" window-layer="0" window-bounds="[0,0][1080,2400]"'; + +describe('assertAndroidHittable (recorded helper XML)', () => { + const home = fixture('wallet-home'); + const search = fixture('search-keyboard'); + + it('refuses the hamburger button under the Expo "Tools" button', () => { + const error = check(byId(home, 'navbar-hamburger-menu-button')); + + expect(error).toBeInstanceOf(TargetObscuredError); + expect(error).toMatchObject({ code: 'TARGET_OBSCURED', keyboard: false }); + expect(error?.message).toContain( + 'id="navbar-hamburger-menu-button" is covered at (973, 137) by ' + + 'android.view.View around android.widget.ImageView label="Tools"', + ); + expect(error?.message).toContain('Close the overlay'); + }); + + it('refuses a token row under the floating tab bar, naming the tab', () => { + const error = check(byId(home, 'asset-row-3')); + + expect(error?.message).toContain('by android.view.ViewGroup'); + expect(error?.keyboard).toBe(false); + }); + + it.each([ + 'tab-bar-item-Wallet', + 'tab-bar-item-Trending', + 'tab-bar-floating-trade-button', + 'account-picker', + 'wallet-send-button', + 'wallet-receive-button', + 'wallet-search-button', + 'homepage-section-title-tokens', + 'asset-row-1', + ])('lets a tap on the free %s through (wallet home)', (identifier) => { + expect(check(byId(home, identifier))).toBeUndefined(); + }); + + it.each([ + 'multichain-account-selector-search-input', + 'back-arrow-button', + 'account-list-add-account-button', + 'button-icon', + ])('lets a tap on the free %s through (keyboard up)', (identifier) => { + expect(check(byId(search, identifier))).toBeUndefined(); + }); + + it('refuses a point under the keyboard, naming the keyboard', () => { + const input = byId(search, 'multichain-account-selector-search-input'); + // Gboard's floating toolbar key at [108,151][211,248] is above the app. + let error: unknown; + try { + assertAndroidHittable(input, { x: 150, y: 240 }, SCREEN); + } catch (caught) { + error = caught; + } + + expect(error).toBeInstanceOf(TargetObscuredError); + expect(error).toMatchObject({ keyboard: true, x: 150, y: 240 }); + expect((error as Error).message).toContain('by the keyboard: '); + expect((error as Error).message).toContain( + 'Dismiss the keyboard (device_dismiss_keyboard)', + ); + }); + + it('ignores the keyboard window outside its drawn nodes', () => { + // The IME window's bounds cover y 137..2400, but nothing is drawn here. + const input = byId(search, 'multichain-account-selector-search-input'); + + expect(() => + assertAndroidHittable(input, { x: 540, y: 300 }, SCREEN), + ).not.toThrow(); + }); +}); + +describe('assertAndroidHittable (rules)', () => { + const target = + 'resource-id="target" class="android.widget.Button" clickable="true" visible-to-user="true" bounds="[100,100][300,200]"'; + + const appWindow = (...children: string[]): string => + node( + `${APP_WINDOW} class="android.widget.FrameLayout" visible-to-user="true" drawing-order="0" bounds="[0,0][1080,2400]"`, + children.join(''), + ); + + const targetIn = (hierarchy: UIElement[]): UIElement => + byId(hierarchy, 'target'); + + it('refuses a sibling drawn after the target', () => { + const hierarchy = parseAndroidHierarchy( + xml( + appWindow( + node(`${target} drawing-order="1"`), + node( + 'resource-id="sheet" class="android.view.ViewGroup" content-desc="Sheet" visible-to-user="true" drawing-order="2" bounds="[0,150][1080,900]"', + ), + ), + ), + ); + + expect(check(targetIn(hierarchy))?.message).toContain('id="sheet"'); + }); + + it('ignores a sibling drawn before the target', () => { + const hierarchy = parseAndroidHierarchy( + xml( + appWindow( + node( + 'resource-id="under" class="android.view.ViewGroup" content-desc="Under" visible-to-user="true" drawing-order="1" bounds="[0,0][1080,900]"', + ), + node(`${target} drawing-order="2"`), + ), + ), + ); + + expect(check(targetIn(hierarchy))).toBeUndefined(); + }); + + it('ignores an overlay that is not visible to the user', () => { + const hierarchy = parseAndroidHierarchy( + xml( + appWindow( + node(`${target} drawing-order="1"`), + node( + 'class="android.view.View" content-desc="Fade" visible-to-user="false" drawing-order="2" bounds="[0,0][1080,300]"', + ), + ), + ), + ); + + expect(check(targetIn(hierarchy))).toBeUndefined(); + }); + + it('ignores a full-width wrapper, but not its drawn children', () => { + const wrapper = (child: string): UIElement[] => + parseAndroidHierarchy( + xml( + appWindow( + node(`${target} drawing-order="1"`), + node( + 'class="android.view.ViewGroup" visible-to-user="true" drawing-order="2" bounds="[0,120][1080,400]"', + child, + ), + ), + ), + ); + + expect( + check( + targetIn( + wrapper( + node( + 'class="android.widget.Button" content-desc="Far" clickable="true" visible-to-user="true" drawing-order="1" bounds="[600,120][800,400]"', + ), + ), + ), + ), + ).toBeUndefined(); + expect( + check( + targetIn( + wrapper( + node( + 'class="android.widget.Button" content-desc="Over" clickable="true" visible-to-user="true" drawing-order="1" bounds="[150,120][250,400]"', + ), + ), + ), + )?.message, + ).toContain('label="Over"'); + }); + + it('accepts a later-drawn node inside the target (its own icon)', () => { + const hierarchy = parseAndroidHierarchy( + xml( + appWindow( + node(`${target} drawing-order="1"`), + node( + 'class="android.widget.ImageView" visible-to-user="true" drawing-order="2" bounds="[150,120][250,180]"', + ), + ), + ), + ); + + expect(check(targetIn(hierarchy))).toBeUndefined(); + }); + + it('refuses a node of a higher system window, not as the keyboard', () => { + const hierarchy = parseAndroidHierarchy( + xml( + node( + 'window-index="0" window-type="3" window-layer="2" window-bounds="[0,0][1080,400]" class="android.widget.FrameLayout" visible-to-user="true" drawing-order="0" bounds="[0,0][1080,400]"', + node( + 'resource-id="com.android.systemui:id/heads_up" class="android.widget.FrameLayout" visible-to-user="true" drawing-order="1" bounds="[0,0][1080,300]"', + ), + ), + appWindow(node(`${target} drawing-order="1"`)), + ), + ); + + const error = check(targetIn(hierarchy)); + expect(error?.message).toContain('com.android.systemui:id/heads_up'); + expect(error?.keyboard).toBe(false); + }); + + it('ignores lower windows', () => { + const hierarchy = parseAndroidHierarchy( + xml( + node( + 'window-index="0" window-type="1" window-layer="5" window-bounds="[0,0][1080,2400]" class="android.widget.FrameLayout" visible-to-user="true" drawing-order="0" bounds="[0,0][1080,2400]"', + node(`${target} drawing-order="1"`), + ), + node( + 'window-index="1" window-type="1" window-layer="0" window-bounds="[0,0][1080,2400]" class="android.widget.FrameLayout" visible-to-user="true" drawing-order="0" bounds="[0,0][1080,2400]"', + node( + 'class="android.widget.Button" content-desc="Behind" clickable="true" visible-to-user="true" drawing-order="1" bounds="[0,0][1080,900]"', + ), + ), + ), + ); + + expect(check(targetIn(hierarchy))).toBeUndefined(); + }); + + it('lets every tap through for a stock uiautomator dump', () => { + // No window metadata and no drawing-order: nothing can be told. + const hierarchy = parseAndroidHierarchy( + xml( + node( + 'class="android.widget.FrameLayout" bounds="[0,0][1080,2400]"', + node( + 'resource-id="target" class="android.widget.Button" clickable="true" bounds="[100,100][300,200]"', + ) + + node( + 'class="android.widget.Button" content-desc="Over" clickable="true" bounds="[0,0][1080,900]"', + ), + ), + ), + ); + + expect(check(targetIn(hierarchy))).toBeUndefined(); + }); + + it('lets a tap through for an element that is not from a snapshot', () => { + expect( + check({ + type: 'android.widget.Button', + identifier: 'target', + frame: { x: 100, y: 100, width: 200, height: 100 }, + enabled: true, + }), + ).toBeUndefined(); + }); +}); diff --git a/src/utils/android-hit-test.ts b/src/utils/android-hit-test.ts new file mode 100644 index 0000000..8f1a6ac --- /dev/null +++ b/src/utils/android-hit-test.ts @@ -0,0 +1,376 @@ +import { hitsTarget, TargetObscuredError } from './hit-test.js'; +import type { HitTestWindow } from './hit-test.js'; +import type { UIElement } from '../backends/types.js'; + +/** `AccessibilityWindowInfo.TYPE_INPUT_METHOD`: the software keyboard. */ +const WINDOW_TYPE_INPUT_METHOD = 2; + +type Frame = UIElement['frame']; + +/** Window metadata the snapshot helper puts on each window root. */ +export type AndroidWindowInfo = { + type: number; + layer: number; + bounds: Frame; +}; + +/** + * What the Android hierarchy XML says about a node beyond `UIElement`. Only + * set for nodes parsed by `parseAndroidHierarchy`. + */ +export type AndroidNodeInfo = { + /** The parsed hierarchy (all window roots) the node belongs to. */ + roots: UIElement[]; + /** The parent node; undefined for a window root. */ + parent: UIElement | undefined; + /** Draw order among siblings (higher is drawn later, on top). */ + drawingOrder: number | undefined; + visibleToUser: boolean; + clickable: boolean; + /** Set on window roots captured by the snapshot helper. */ + window: AndroidWindowInfo | undefined; +}; + +const nodeInfo = new WeakMap(); + +/** + * Record the Android-only data of a parsed node. + * + * @param element - The parsed node. + * @param info - Its Android data. + */ +export function setAndroidNodeInfo( + element: UIElement, + info: AndroidNodeInfo, +): void { + nodeInfo.set(element, info); +} + +/** + * Find what a tap at `point` would hit instead of `target`, from the + * snapshot the target came from. No device call. + * + * - A higher window (the keyboard, a system window): any drawn node of it at + * the point. A window's root frame is often the whole screen and + * transparent, so only nodes that draw or take input count (clickable, + * labelled, or leaves). + * - The target's window: a node drawn after the target (higher + * `drawing-order` where the two branches split) that contains the point and + * draws there: it is clickable, labelled or a leaf, or wraps such a node + * inside its frame (an overlay button's background around its icon). A + * wrapper as wide as the window is a transparent layout row and is ignored; + * its drawn children still count. `hitsTarget` then decides, as on iOS, whether the + * node is part of the target. + * + * Without the helper's window metadata or draw order (a stock uiautomator + * dump), or for an element that is not from a parsed snapshot, nothing can be + * told, so the tap goes ahead. + * + * @param target - The element to tap. + * @param point - The tap point. + * @param point.x - X in pixels. + * @param point.y - Y in pixels. + * @param screen - The screen size in pixels. + * @throws {TargetObscuredError} When another node is on top at the point. + */ +export function assertAndroidHittable( + target: UIElement, + point: { x: number; y: number }, + screen: HitTestWindow, +): void { + const info = nodeInfo.get(target); + if (!info) { + return; + } + const chain = ancestorChain(target); + const targetRoot = chain[0] ?? target; + const targetWindow = nodeInfo.get(targetRoot)?.window; + + if (targetWindow) { + const higher = info.roots + .filter((root) => { + const window = nodeInfo.get(root)?.window; + return ( + root !== targetRoot && window && window.layer > targetWindow.layer + ); + }) + .sort( + (a, b) => + (nodeInfo.get(b)?.window?.layer ?? 0) - + (nodeInfo.get(a)?.window?.layer ?? 0), + ); + for (const root of higher) { + const window = nodeInfo.get(root)?.window as AndroidWindowInfo; + const hit = deepest( + root, + (node) => + contains(node.frame, point) && drawsItself(node, window.bounds), + ); + if (hit) { + throw new TargetObscuredError(target, hit, point, { + keyboard: window.type === WINDOW_TYPE_INPUT_METHOD, + obscuredByDescription: describeObscurer(hit), + }); + } + } + } + + const windowBounds = targetWindow?.bounds ?? { + x: 0, + y: 0, + width: screen.width, + height: screen.height, + }; + const hits = matching( + targetRoot, + (node) => + node !== target && + contains(node.frame, point) && + drawnAfter(node, target) && + drawsAt(node, windowBounds), + ); + // Deepest and last drawn first, so the error names what is really on top. + for (const hit of hits.reverse()) { + if (!hitsTarget(target, hit, chain, screen, info.roots)) { + throw new TargetObscuredError(target, hit, point, { + keyboard: false, + obscuredByDescription: describeObscurer(hit), + }); + } + } +} + +/** + * @param element - A parsed node. + * @returns Its ancestors, root first and parent last. + */ +function ancestorChain(element: UIElement): UIElement[] { + const chain: UIElement[] = []; + let parent = nodeInfo.get(element)?.parent; + while (parent) { + chain.unshift(parent); + parent = nodeInfo.get(parent)?.parent; + } + return chain; +} + +/** + * The last node in tree order that matches, which is the deepest and the + * last drawn among matching siblings. + * + * @param root - The subtree to search. + * @param matches - The predicate. + * @returns The node, or undefined. + */ +function deepest( + root: UIElement, + matches: (node: UIElement) => boolean, +): UIElement | undefined { + return matching(root, matches).at(-1); +} + +/** + * @param root - The subtree to search. + * @param matches - The predicate. + * @returns The matching nodes, in tree order. + */ +function matching( + root: UIElement, + matches: (node: UIElement) => boolean, +): UIElement[] { + const found: UIElement[] = []; + const walk = (node: UIElement): void => { + if (matches(node)) { + found.push(node); + } + node.children?.forEach(walk); + }; + walk(root); + return found; +} + +/** + * Whether `node` is drawn after (on top of) `target`: where their branches + * split, the node's branch has the higher `drawing-order`. Ancestors and + * descendants of the target are never drawn after it. + * + * @param node - A node in the target's window. + * @param target - The target. + * @returns True when the node is drawn on top of the target. + */ +function drawnAfter(node: UIElement, target: UIElement): boolean { + const nodeChain = [...ancestorChain(node), node]; + const targetChain = [...ancestorChain(target), target]; + let split = 0; + while ( + split < nodeChain.length && + split < targetChain.length && + nodeChain[split] === targetChain[split] + ) { + split += 1; + } + if (split === 0 || split >= nodeChain.length || split >= targetChain.length) { + return false; + } + const nodeOrder = nodeInfo.get(nodeChain[split])?.drawingOrder; + const targetOrder = nodeInfo.get(targetChain[split])?.drawingOrder; + return ( + nodeOrder !== undefined && + targetOrder !== undefined && + nodeOrder > targetOrder + ); +} + +/** + * Whether a node draws or takes input itself: visible, with an area, not the + * size of its window, and clickable, labelled, or a leaf. + * + * @param node - The node. + * @param window - Its window's bounds. + * @returns True when the node draws. + */ +function drawsItself(node: UIElement, window: Frame): boolean { + const info = nodeInfo.get(node); + if (!info?.visibleToUser || !hasArea(node.frame)) { + return false; + } + if (containsFrame(node.frame, window)) { + return false; + } + return ( + info.clickable || + Boolean(node.label ?? node.value) || + !node.children?.length + ); +} + +/** + * Whether a node in the target's window draws at its frame: it draws itself, + * or it wraps a node that does and is not a window-sized transparent wrapper. + * + * @param node - The node. + * @param window - The window's bounds. + * @returns True when the node covers what is under it. + */ +function drawsAt(node: UIElement, window: Frame): boolean { + if (drawsItself(node, window)) { + return true; + } + const info = nodeInfo.get(node); + if (!info?.visibleToUser || !hasArea(node.frame)) { + return false; + } + // A wrapper as wide as the window is a transparent layout row (a floating + // tab bar's container); its drawn children still count. + if (node.frame.width >= window.width) { + return false; + } + return drawnDescendantInside(node, node.frame, window); +} + +/** + * @param node - The node. + * @param frame - The wrapper's frame. + * @param window - Its window's bounds. + * @returns True when a descendant that draws itself lies inside `frame`. + */ +function drawnDescendantInside( + node: UIElement, + frame: Frame, + window: Frame, +): boolean { + return (node.children ?? []).some( + (child) => + (drawsItself(child, window) && containsFrame(frame, child.frame)) || + drawnDescendantInside(child, frame, window), + ); +} + +/** + * A description of the obscuring node. An unnamed wrapper (an overlay + * button's background) is named by the first labelled node inside it. + * + * @param node - The obscuring node. + * @returns The description, or undefined to use the default. + */ +function describeObscurer(node: UIElement): string | undefined { + if (node.label ?? node.identifier ?? node.value) { + return undefined; + } + const named = findNamed(node); + return named ? `${node.type} around ${describeNamed(named)}` : undefined; +} + +/** + * @param node - The node. + * @returns The first descendant with a label, identifier or value. + */ +function findNamed(node: UIElement): UIElement | undefined { + for (const child of node.children ?? []) { + if (child.label ?? child.identifier ?? child.value) { + return child; + } + const below = findNamed(child); + if (below) { + return below; + } + } + return undefined; +} + +/** + * @param node - A named node. + * @returns Its type and names. + */ +function describeNamed(node: UIElement): string { + const parts = [node.type]; + if (node.label) { + parts.push(`label="${node.label}"`); + } + if (node.identifier) { + parts.push(`id="${node.identifier}"`); + } + if (node.value) { + parts.push(`value="${node.value}"`); + } + return parts.join(' '); +} + +/** + * @param frame - A frame. + * @returns True when it has a positive width and height. + */ +function hasArea(frame: Frame): boolean { + return frame.width > 0 && frame.height > 0; +} + +/** + * @param frame - A frame. + * @param point - A point. + * @param point.x - X. + * @param point.y - Y. + * @returns True when the point is inside the frame (right and bottom edges + * excluded, as Android bounds are). + */ +function contains(frame: Frame, point: { x: number; y: number }): boolean { + return ( + point.x >= frame.x && + point.x < frame.x + frame.width && + point.y >= frame.y && + point.y < frame.y + frame.height + ); +} + +/** + * @param outer - The containing frame. + * @param inner - The contained frame. + * @returns True when `inner` lies inside `outer`. + */ +function containsFrame(outer: Frame, inner: Frame): boolean { + return ( + inner.x >= outer.x && + inner.y >= outer.y && + inner.x + inner.width <= outer.x + outer.width && + inner.y + inner.height <= outer.y + outer.height + ); +} diff --git a/src/utils/hit-test.ts b/src/utils/hit-test.ts index 999cef6..da39014 100644 --- a/src/utils/hit-test.ts +++ b/src/utils/hit-test.ts @@ -30,19 +30,34 @@ export class TargetObscuredError extends Error { readonly y: number; + /** + * @param target - The element the caller wanted to tap. + * @param obscuredBy - The element at the tap point. + * @param point - The tap point. + * @param point.x - X. + * @param point.y - Y. + * @param options - Overrides for backends that know more than the element + * (Android: the keyboard is a window type, not an element type). + * @param options.keyboard - Whether `obscuredBy` belongs to the keyboard. + * Defaults to `isKeyboardElement(obscuredBy)`. + * @param options.obscuredByDescription - How to name `obscuredBy` in the + * message. Defaults to `describeElement(obscuredBy)`. + */ constructor( target: UIElement, obscuredBy: UIElement, point: { x: number; y: number }, + options: { keyboard?: boolean; obscuredByDescription?: string } = {}, ) { - const keyboard = isKeyboardElement(obscuredBy); + const keyboard = options.keyboard ?? isKeyboardElement(obscuredBy); const advice = keyboard ? 'Dismiss the keyboard (device_dismiss_keyboard) and retry.' : 'Close the overlay, or scroll the target into a free area.'; super( `TARGET_OBSCURED: ${describeElement(target)} is covered at ` + `(${point.x}, ${point.y}) by ${keyboard ? 'the keyboard: ' : ''}` + - `${describeElement(obscuredBy)}. Nothing was tapped. ${advice}`, + `${options.obscuredByDescription ?? describeElement(obscuredBy)}. ` + + `Nothing was tapped. ${advice}`, ); this.name = 'TargetObscuredError'; this.obscuredBy = obscuredBy; From 5a6b6f2c280ced0c4a175f58e66fa05504592278 Mon Sep 17 00:00:00 2001 From: cryptotavares Date: Tue, 17 Nov 2026 01:46:38 +0000 Subject: [PATCH 2/4] fix: narrow the Android occlusion rules and skip it without window data Return early when the target's window root has no window metadata: a stock uiautomator dump from android15-qpr2 on has drawing-order but no window-* or visible-to-user. Count a wrapper as drawn only when it is small or at most twice the area of its drawn content, so a box-none host around a floating button is transparent. Do not count large non-clickable, unlabelled leaves (at least half the window or full width) as opaque. Keep accepting a later-drawn sibling inside the target as a documented trade-off. Document the fail-open cases (copied element, maxNodes cut) and name the keyboard by its class only. --- src/utils/android-hit-test.test.ts | 145 +++++++++++++++++++- src/utils/android-hit-test.ts | 211 +++++++++++++++++++++-------- 2 files changed, 292 insertions(+), 64 deletions(-) diff --git a/src/utils/android-hit-test.test.ts b/src/utils/android-hit-test.test.ts index 30bad23..620cb86 100644 --- a/src/utils/android-hit-test.test.ts +++ b/src/utils/android-hit-test.test.ts @@ -126,7 +126,9 @@ describe('assertAndroidHittable (recorded helper XML)', () => { expect(error).toBeInstanceOf(TargetObscuredError); expect(error).toMatchObject({ keyboard: true, x: 150, y: 240 }); - expect((error as Error).message).toContain('by the keyboard: '); + expect((error as Error).message).toContain( + 'is covered at (150, 240) by the keyboard: android.widget.FrameLayout. ', + ); expect((error as Error).message).toContain( 'Dismiss the keyboard (device_dismiss_keyboard)', ); @@ -238,13 +240,90 @@ describe('assertAndroidHittable (rules)', () => { ).toContain('label="Over"'); }); - it('accepts a later-drawn node inside the target (its own icon)', () => { + it('accepts a later-drawn sibling inside the target (trade-off)', () => { + // Its own icon drawn as a sibling, or an overlay that fits inside the + // target: they can't be told apart, so both go through. + const overlay = (bounds: string): UIElement[] => + parseAndroidHierarchy( + xml( + appWindow( + node(`${target} drawing-order="1"`), + node( + `class="android.widget.ImageView" visible-to-user="true" drawing-order="2" bounds="${bounds}"`, + ), + ), + ), + ); + + expect(check(targetIn(overlay('[150,120][250,180]')))).toBeUndefined(); + expect(check(targetIn(overlay('[100,100][300,200]')))).toBeUndefined(); + }); + + it('ignores a box-none container around a floating button', () => { + // An RN `box-none` host: a wrapper much larger than what it draws. const hierarchy = parseAndroidHierarchy( xml( appWindow( node(`${target} drawing-order="1"`), node( - 'class="android.widget.ImageView" visible-to-user="true" drawing-order="2" bounds="[150,120][250,180]"', + 'class="android.view.ViewGroup" visible-to-user="true" drawing-order="2" bounds="[42,63][1038,2400]"', + node( + 'resource-id="fab" class="android.widget.Button" content-desc="Add" clickable="true" visible-to-user="true" drawing-order="1" bounds="[870,2100][1000,2230]"', + ), + ), + ), + ), + ); + + expect(() => + assertAndroidHittable(targetIn(hierarchy), { x: 200, y: 150 }, SCREEN), + ).not.toThrow(); + }); + + it('refuses a close wrapper around a drawn node (an overlay button)', () => { + // As the Expo "Tools" button: a 137 px background around a 68 px icon. + const overlay = (bounds: string, icon: string): UIElement[] => + parseAndroidHierarchy( + xml( + appWindow( + node(`${target} drawing-order="1"`), + node( + `class="android.view.View" visible-to-user="true" drawing-order="2" bounds="${bounds}"`, + node( + `class="android.widget.ImageView" content-desc="Tools" visible-to-user="true" drawing-order="1" bounds="${icon}"`, + ), + ), + ), + ), + ); + + expect( + check(targetIn(overlay('[150,80][287,217]', '[184,114][252,182]'))) + ?.message, + ).toContain('android.view.View around android.widget.ImageView'); + // Larger than the small-size rule, but at most twice its drawn content + // (400x400 around 350x230); the tap point is on the wrapper only. + expect( + check(targetIn(overlay('[60,60][460,460]', '[90,210][440,440]'))) + ?.message, + ).toContain('android.view.View around android.widget.ImageView'); + // Just over twice its drawn content: a transparent container. + expect( + check(targetIn(overlay('[60,60][460,460]', '[90,230][440,440]'))), + ).toBeUndefined(); + }); + + it.each([ + ['an inset absolute-fill host', '[0,63][1080,2400]'], + ['a full-width layer', '[0,50][1080,400]'], + ['a layer over half the window', '[0,0][800,1700]'], + ])('ignores a large unlabelled leaf drawn later: %s', (_name, bounds) => { + const hierarchy = parseAndroidHierarchy( + xml( + appWindow( + node(`${target} drawing-order="1"`), + node( + `class="android.view.ViewGroup" visible-to-user="true" drawing-order="2" bounds="${bounds}"`, ), ), ), @@ -253,6 +332,40 @@ describe('assertAndroidHittable (rules)', () => { expect(check(targetIn(hierarchy))).toBeUndefined(); }); + it.each([ + ['clickable', 'clickable="true"'], + ['labelled', 'content-desc="Backdrop"'], + ['with a resource id', 'resource-id="backdrop"'], + ])('refuses a large leaf drawn later that is %s', (_name, attr) => { + const hierarchy = parseAndroidHierarchy( + xml( + appWindow( + node(`${target} drawing-order="1"`), + node( + `class="android.view.ViewGroup" ${attr} visible-to-user="true" drawing-order="2" bounds="[0,63][1080,2400]"`, + ), + ), + ), + ); + + expect(check(targetIn(hierarchy))).toBeInstanceOf(TargetObscuredError); + }); + + it('refuses a small unlabelled leaf drawn later', () => { + const hierarchy = parseAndroidHierarchy( + xml( + appWindow( + node(`${target} drawing-order="1"`), + node( + 'class="android.view.View" visible-to-user="true" drawing-order="2" bounds="[150,120][450,400]"', + ), + ), + ), + ); + + expect(check(targetIn(hierarchy))).toBeInstanceOf(TargetObscuredError); + }); + it('refuses a node of a higher system window, not as the keyboard', () => { const hierarchy = parseAndroidHierarchy( xml( @@ -291,16 +404,17 @@ describe('assertAndroidHittable (rules)', () => { }); it('lets every tap through for a stock uiautomator dump', () => { - // No window metadata and no drawing-order: nothing can be told. + // From android15-qpr2 on, the stock dumper writes drawing-order, but + // never window metadata or visible-to-user: nothing can be told. const hierarchy = parseAndroidHierarchy( xml( node( - 'class="android.widget.FrameLayout" bounds="[0,0][1080,2400]"', + 'class="android.widget.FrameLayout" drawing-order="0" bounds="[0,0][1080,2400]"', node( - 'resource-id="target" class="android.widget.Button" clickable="true" bounds="[100,100][300,200]"', + 'resource-id="target" class="android.widget.Button" clickable="true" drawing-order="1" bounds="[100,100][300,200]"', ) + node( - 'class="android.widget.Button" content-desc="Over" clickable="true" bounds="[0,0][1080,900]"', + 'class="android.widget.Button" content-desc="Over" clickable="true" drawing-order="2" bounds="[0,0][1080,900]"', ), ), ), @@ -309,6 +423,23 @@ describe('assertAndroidHittable (rules)', () => { expect(check(targetIn(hierarchy))).toBeUndefined(); }); + it('lets a tap through for a copy of a snapshot element', () => { + const hierarchy = parseAndroidHierarchy( + xml( + appWindow( + node(`${target} drawing-order="1"`), + node( + 'resource-id="sheet" class="android.view.ViewGroup" content-desc="Sheet" visible-to-user="true" drawing-order="2" bounds="[0,150][1080,900]"', + ), + ), + ), + ); + const copy = JSON.parse(JSON.stringify(targetIn(hierarchy))) as UIElement; + + expect(check(targetIn(hierarchy))).toBeInstanceOf(TargetObscuredError); + expect(check(copy)).toBeUndefined(); + }); + it('lets a tap through for an element that is not from a snapshot', () => { expect( check({ diff --git a/src/utils/android-hit-test.ts b/src/utils/android-hit-test.ts index 8f1a6ac..28044f8 100644 --- a/src/utils/android-hit-test.ts +++ b/src/utils/android-hit-test.ts @@ -7,6 +7,26 @@ const WINDOW_TYPE_INPUT_METHOD = 2; type Frame = UIElement['frame']; +/** + * A wrapper with a drawn node inside counts as drawn over its whole frame + * when its area is at most this many times the area its drawn nodes cover. + */ +const WRAPPER_MAX_AREA_RATIO = 2; + +/** + * ...or when each side is at most this share of the window's shorter side + * (a small overlay button: the Expo "Tools" background is 137 px around a + * 68 px icon on a 1080 px wide screen). + */ +const WRAPPER_SMALL_SIDE_RATIO = 0.2; + +/** + * A non-clickable leaf with no text, content-desc or resource id is a + * transparent host, not a surface, when it covers at least this share of the + * window's area (or its full width). + */ +const LARGE_LEAF_AREA_RATIO = 0.5; + /** Window metadata the snapshot helper puts on each window root. */ export type AndroidWindowInfo = { type: number; @@ -56,15 +76,27 @@ export function setAndroidNodeInfo( * labelled, or leaves). * - The target's window: a node drawn after the target (higher * `drawing-order` where the two branches split) that contains the point and - * draws there: it is clickable, labelled or a leaf, or wraps such a node - * inside its frame (an overlay button's background around its icon). A - * wrapper as wide as the window is a transparent layout row and is ignored; - * its drawn children still count. `hitsTarget` then decides, as on iOS, whether the - * node is part of the target. + * draws there (see `drawsItself` and `drawsAt`). + * + * `hitsTarget` then decides, as on iOS, whether the node is part of the + * target. Deliberate trade-off: it accepts any node whose frame lies inside + * the target's. Here that node is never the target's descendant + * (`drawnAfter` excludes those), but a sibling drawn on top; React Native + * draws a control's content that way (a field's input over its container, a + * label or icon over a pressable's background). So a sibling overlay that + * fits inside the target is a false accept, not a refusal. + * + * The check fails open (the tap goes ahead) when nothing can be told: + * + * - the target's window root has no window metadata: a stock `uiautomator + * dump` (the fallback), which has no `window-*` or `visible-to-user`, and + * from android15-qpr2 on has `drawing-order`; + * - the element is not a node of a parsed snapshot: a copy, or an + * `options.element` that went through JSON, has no recorded node data. * - * Without the helper's window metadata or draw order (a stock uiautomator - * dump), or for an element that is not from a parsed snapshot, nothing can be - * told, so the tap goes ahead. + * A helper tree cut at `maxNodes` can miss the nodes drawn last, so an + * overlay there is not seen and the tap goes ahead (a false accept, never a + * false refusal). * * @param target - The element to tap. * @param point - The tap point. @@ -85,42 +117,37 @@ export function assertAndroidHittable( const chain = ancestorChain(target); const targetRoot = chain[0] ?? target; const targetWindow = nodeInfo.get(targetRoot)?.window; + if (!targetWindow) { + return; + } - if (targetWindow) { - const higher = info.roots - .filter((root) => { - const window = nodeInfo.get(root)?.window; - return ( - root !== targetRoot && window && window.layer > targetWindow.layer - ); - }) - .sort( - (a, b) => - (nodeInfo.get(b)?.window?.layer ?? 0) - - (nodeInfo.get(a)?.window?.layer ?? 0), - ); - for (const root of higher) { - const window = nodeInfo.get(root)?.window as AndroidWindowInfo; - const hit = deepest( - root, - (node) => - contains(node.frame, point) && drawsItself(node, window.bounds), - ); - if (hit) { - throw new TargetObscuredError(target, hit, point, { - keyboard: window.type === WINDOW_TYPE_INPUT_METHOD, - obscuredByDescription: describeObscurer(hit), - }); - } + const higher = info.roots + .filter((root) => { + const window = nodeInfo.get(root)?.window; + return root !== targetRoot && window && window.layer > targetWindow.layer; + }) + .sort( + (a, b) => + (nodeInfo.get(b)?.window?.layer ?? 0) - + (nodeInfo.get(a)?.window?.layer ?? 0), + ); + for (const root of higher) { + const window = nodeInfo.get(root)?.window as AndroidWindowInfo; + const hit = deepest( + root, + (node) => contains(node.frame, point) && drawsItself(node, window.bounds), + ); + if (hit) { + const keyboard = window.type === WINDOW_TYPE_INPUT_METHOD; + throw new TargetObscuredError(target, hit, point, { + keyboard, + // Keyboard ids are obfuscated and say nothing; the class is enough. + obscuredByDescription: keyboard ? hit.type : describeObscurer(hit), + }); } } - const windowBounds = targetWindow?.bounds ?? { - x: 0, - y: 0, - width: screen.width, - height: screen.height, - }; + const windowBounds = targetWindow.bounds; const hits = matching( targetRoot, (node) => @@ -225,6 +252,15 @@ function drawnAfter(node: UIElement, target: UIElement): boolean { * Whether a node draws or takes input itself: visible, with an area, not the * size of its window, and clickable, labelled, or a leaf. * + * A large leaf that is not clickable and has no text, content-desc or + * resource id is not counted: React Native renders absolute-fill hosts and + * `box-none` / `pointerEvents="none"` layers as such leaves. Without + * edge-to-edge they are inset (below the status bar, `[0,63][1080,2400]`), + * so they are not window-sized. "Large" is at least half the window's area, + * or its full width (a transparent header layer such as `[0,50][1080,400]`). + * A real full-width surface still counts when it is clickable or labelled, + * or as a wrapper around drawn nodes (`drawsAt`). + * * @param node - The node. * @param window - Its window's bounds. * @returns True when the node draws. @@ -237,16 +273,32 @@ function drawsItself(node: UIElement, window: Frame): boolean { if (containsFrame(node.frame, window)) { return false; } - return ( - info.clickable || - Boolean(node.label ?? node.value) || - !node.children?.length - ); + if (info.clickable || node.label || node.value) { + return true; + } + if (node.children?.length) { + return false; + } + if (node.identifier) { + return true; + } + const large = + node.frame.width >= window.width || + area(node.frame) >= area(window) * LARGE_LEAF_AREA_RATIO; + return !large; } /** * Whether a node in the target's window draws at its frame: it draws itself, - * or it wraps a node that does and is not a window-sized transparent wrapper. + * or it is a wrapper close around nodes that do (an overlay button's + * background around its icon). + * + * A wrapper counts only when its area is at most + * {@link WRAPPER_MAX_AREA_RATIO} times the area its drawn nodes cover, or when + * it is small (each side at most {@link WRAPPER_SMALL_SIDE_RATIO} of the + * window's shorter side). A larger wrapper is a transparent layout container + * (a `box-none` host around a floating button, or a row as wide as the + * window); its drawn children still count on their own. * * @param node - The node. * @param window - The window's bounds. @@ -260,30 +312,67 @@ function drawsAt(node: UIElement, window: Frame): boolean { if (!info?.visibleToUser || !hasArea(node.frame)) { return false; } - // A wrapper as wide as the window is a transparent layout row (a floating - // tab bar's container); its drawn children still count. if (node.frame.width >= window.width) { return false; } - return drawnDescendantInside(node, node.frame, window); + const drawn = drawnDescendantsInside(node, node.frame, window); + if (drawn.length === 0) { + return false; + } + const smallSide = + Math.min(window.width, window.height) * WRAPPER_SMALL_SIDE_RATIO; + if (node.frame.width <= smallSide && node.frame.height <= smallSide) { + return true; + } + return area(node.frame) <= unionArea(drawn) * WRAPPER_MAX_AREA_RATIO; } /** * @param node - The node. * @param frame - The wrapper's frame. * @param window - Its window's bounds. - * @returns True when a descendant that draws itself lies inside `frame`. + * @returns The frames of the descendants that draw themselves inside `frame`. */ -function drawnDescendantInside( +function drawnDescendantsInside( node: UIElement, frame: Frame, window: Frame, -): boolean { - return (node.children ?? []).some( - (child) => - (drawsItself(child, window) && containsFrame(frame, child.frame)) || - drawnDescendantInside(child, frame, window), - ); +): Frame[] { + return (node.children ?? []).flatMap((child) => [ + ...(drawsItself(child, window) && containsFrame(frame, child.frame) + ? [child.frame] + : []), + ...drawnDescendantsInside(child, frame, window), + ]); +} + +/** + * @param frames - Frames. + * @returns The area of their union. + */ +function unionArea(frames: Frame[]): number { + const xs = [ + ...new Set(frames.flatMap((frame) => [frame.x, frame.x + frame.width])), + ].sort((a, b) => a - b); + let total = 0; + for (let i = 0; i + 1 < xs.length; i++) { + const left = xs[i]; + const right = xs[i + 1]; + const spans = frames + .filter((frame) => frame.x <= left && frame.x + frame.width >= right) + .map((frame) => [frame.y, frame.y + frame.height] as const) + .sort((a, b) => a[0] - b[0]); + let covered = 0; + let end = -Infinity; + for (const [top, bottom] of spans) { + if (bottom > end) { + covered += bottom - Math.max(top, end); + end = bottom; + } + } + total += covered * (right - left); + } + return total; } /** @@ -336,6 +425,14 @@ function describeNamed(node: UIElement): string { return parts.join(' '); } +/** + * @param frame - A frame. + * @returns Its area. + */ +function area(frame: Frame): number { + return frame.width * frame.height; +} + /** * @param frame - A frame. * @returns True when it has a positive width and height. From 07d034b9beca8afc017bdef3ee6e9f4f7ca92781 Mon Sep 17 00:00:00 2001 From: cryptotavares Date: Tue, 17 Nov 2026 08:29:38 +0000 Subject: [PATCH 3/4] fix: refuse Android taps inside the keyboard's touchable region While the snapshot has an input-method window above the target, read the keyboard's touchable region (dumpsys window InputMethod, visible IME windows only) at tap time and refuse a point inside it as the keyboard. The accessibility tree can miss Gboard's floating suggestion key, and the IME window bounds lag behind it and are far larger than the keys with a hardware keyboard, so neither can stand in for it. No extra device call without a keyboard window; a failed read falls back to the snapshot. --- .../adb-dumpsys-window-ime-hidden.txt | 50 +++++ .../adb-dumpsys-window-ime-shown.txt | 37 ++++ src/backends/adb-backend.test.ts | 88 +++++++++ src/backends/adb-backend.ts | 39 +++- src/utils/android-hit-test.test.ts | 174 +++++++++++++++++- src/utils/android-hit-test.ts | 112 ++++++++++- 6 files changed, 487 insertions(+), 13 deletions(-) create mode 100644 src/backends/__fixtures__/adb-dumpsys-window-ime-hidden.txt create mode 100644 src/backends/__fixtures__/adb-dumpsys-window-ime-shown.txt diff --git a/src/backends/__fixtures__/adb-dumpsys-window-ime-hidden.txt b/src/backends/__fixtures__/adb-dumpsys-window-ime-hidden.txt new file mode 100644 index 0000000..4376675 --- /dev/null +++ b/src/backends/__fixtures__/adb-dumpsys-window-ime-hidden.txt @@ -0,0 +1,50 @@ +WINDOW MANAGER WINDOWS (dumpsys window windows) + Window #0 Window{e7383a7 u0 InputMethod}: + mDisplayId=0 mSession=Session{ddabfdb 7031:u0a10166} mClient=android.os.BinderProxy@f93e466 + mOwnerUid=10166 showForAllUsers=false package=com.google.android.inputmethod.latin appop=NONE + mAttrs={(0,0)(fillxfill) gr=BOTTOM CENTER_VERTICAL sim={adjust=pan} ty=INPUT_METHOD fmt=TRANSPARENT wanim=0x1030056 receive insets ignoring z-order + fl=NOT_FOCUSABLE LAYOUT_IN_SCREEN SPLIT_TOUCH HARDWARE_ACCELERATED DRAWS_SYSTEM_BAR_BACKGROUNDS + pfl=EDGE_TO_EDGE_ENFORCED FIT_INSETS_CONTROLLED + apr=LIGHT_NAVIGATION_BARS + bhv=DEFAULT + fitTypes=statusBars navigationBars + fitSides=LEFT TOP RIGHT + dvrrWindowFrameRateHint=true} + Requested w=1080 h=2337 mLayoutSeq=2676 + mIsImWindow=true mIsWallpaper=false mIsFloatingLayer=true + mBaseLayer=131000 mSubLayer=0 mToken=WindowToken{d243025 type=2011 android.os.Binder@4ad9c1c} + mViewVisibility=0x8 mHaveFrame=true mObscured=false + mGivenContentInsets=[0,2211][0,0] mGivenVisibleInsets=[0,2211][0,0] + mTouchableInsets=3 mGivenInsetsPending=false + touchable region=SkRegion((0,2274,1080,2400)) + mFullConfiguration={1.0 310mcc260mnc [en_US] ldltr sw411dp w411dp h914dp 420dpi nrml long compactNeeded port finger qwerty/v/v dpad/v winConfig={ mBounds=Rect(0, 0 - 1080, 2400) mAppBounds=Rect(0, 0 - 1080, 2400) mMaxBounds=Rect(0, 0 - 1080, 2400) mDisplayRotation=ROTATION_0 mWindowingMode=fullscreen mActivityType=undefined mAlwaysOnTop=undefined mRotation=ROTATION_0} s.9 fontWeightAdjustment=0} + mLastReportedConfiguration={1.0 310mcc260mnc [en_US] ldltr sw411dp w411dp h914dp 420dpi nrml long compactNeeded port finger qwerty/v/v dpad/v winConfig={ mBounds=Rect(0, 0 - 1080, 2400) mAppBounds=Rect(0, 0 - 1080, 2400) mMaxBounds=Rect(0, 0 - 1080, 2400) mDisplayRotation=ROTATION_0 mWindowingMode=fullscreen mActivityType=undefined mAlwaysOnTop=undefined mRotation=ROTATION_0} s.9 fontWeightAdjustment=0} + mHasSurface=false isReadyForDisplay()=false mWindowRemovalAllowed=false + Frames: parent=[0,63][1080,2400] display=[0,63][1080,2400] frame=[0,63][1080,2400] last=[0,63][1080,2400] insetsChanged=false + surface=[0,0][0,0] + ContainerAnimator: + mLeash=Surface(name=Surface(name=e7383a7 InputMethod#5696)/@0xc1d8bfd - animation-leash of insets_animation#10870)/@0x8216eb2 mAnimationType=insets_animation + Animation: com.android.server.wm.InsetsSourceProvider$ControlAdapter@5a28e03 + ControlAdapter mCapturedLeash=Surface(name=Surface(name=e7383a7 InputMethod#5696)/@0xc1d8bfd - animation-leash of insets_animation#10870)/@0x8216eb2 + WindowStateAnimator{db8d88 InputMethod}: + mDrawState=NO_SURFACE mLastHidden=false + mEnterAnimationPending=false + isOnScreen=false + isVisible=false + keepClearAreas: restricted=[], unrestricted=[] + mPrepareSyncSeqId=0 + mBufferSeqId=0 + + mGlobalConfiguration={1.0 310mcc260mnc [en_US] ldltr sw411dp w411dp h914dp 420dpi nrml long compactNeeded port finger qwerty/v/v dpad/v winConfig={ mBounds=Rect(0, 0 - 1080, 2400) mAppBounds=Rect(0, 0 - 1080, 2400) mMaxBounds=Rect(0, 0 - 1080, 2400) mDisplayRotation=ROTATION_0 mWindowingMode=fullscreen mActivityType=undefined mAlwaysOnTop=undefined mRotation=ROTATION_0} s.9 fontWeightAdjustment=0} + mHasPermanentDpad=false + mTopFocusedDisplayId=0 + Minimum task size of display#0 220 + mBlurEnabled=true + mDisableSecureWindows=false + mHighResSnapshotScale=0.8 + mSnapshotEnabled=true + SnapshotCache Task + mHighResSnapshotScale=0.6 + mSnapshotEnabled=true + SnapshotCache Activity + UserSavedFile userId=0 diff --git a/src/backends/__fixtures__/adb-dumpsys-window-ime-shown.txt b/src/backends/__fixtures__/adb-dumpsys-window-ime-shown.txt new file mode 100644 index 0000000..f0f3f29 --- /dev/null +++ b/src/backends/__fixtures__/adb-dumpsys-window-ime-shown.txt @@ -0,0 +1,37 @@ +WINDOW MANAGER WINDOWS (dumpsys window windows) + Window #0 Window{e7383a7 u0 InputMethod}: + mDisplayId=0 mSession=Session{ddabfdb 7031:u0a10166} mClient=android.os.BinderProxy@f93e466 + mOwnerUid=10166 showForAllUsers=false package=com.google.android.inputmethod.latin appop=NONE + mAttrs={(0,0)(fillxfill) gr=BOTTOM CENTER_VERTICAL sim={adjust=pan} ty=INPUT_METHOD fmt=TRANSPARENT wanim=0x1030056 receive insets ignoring z-order + fl=NOT_FOCUSABLE LAYOUT_IN_SCREEN SPLIT_TOUCH HARDWARE_ACCELERATED + pfl=EDGE_TO_EDGE_ENFORCED FIT_INSETS_CONTROLLED + bhv=DEFAULT + fitTypes=statusBars navigationBars + fitSides=LEFT TOP RIGHT + dvrrWindowFrameRateHint=true} + Requested w=1080 h=2337 mLayoutSeq=2741 + mIsImWindow=true mIsWallpaper=false mIsFloatingLayer=true + mBaseLayer=131000 mSubLayer=0 mToken=WindowToken{d243025 type=2011 android.os.Binder@4ad9c1c} + mViewVisibility=0x0 mHaveFrame=true mObscured=false + mGivenContentInsets=[0,2337][0,0] mGivenVisibleInsets=[0,2337][0,0] + mTouchableInsets=3 mGivenInsetsPending=false + touchable region=SkRegion((94,137,225,262)(21,863,169,1553)(0,2337,1080,2400)) + mFullConfiguration={1.0 310mcc260mnc [en_US] ldltr sw411dp w411dp h914dp 420dpi nrml long compactNeeded port finger qwerty/v/v dpad/v winConfig={ mBounds=Rect(0, 0 - 1080, 2400) mAppBounds=Rect(0, 0 - 1080, 2400) mMaxBounds=Rect(0, 0 - 1080, 2400) mDisplayRotation=ROTATION_0 mWindowingMode=fullscreen mActivityType=undefined mAlwaysOnTop=undefined mRotation=ROTATION_0} s.9 fontWeightAdjustment=0} + mLastReportedConfiguration={1.0 310mcc260mnc [en_US] ldltr sw411dp w411dp h914dp 420dpi nrml long compactNeeded port finger qwerty/v/v dpad/v winConfig={ mBounds=Rect(0, 0 - 1080, 2400) mAppBounds=Rect(0, 0 - 1080, 2400) mMaxBounds=Rect(0, 0 - 1080, 2400) mDisplayRotation=ROTATION_0 mWindowingMode=fullscreen mActivityType=undefined mAlwaysOnTop=undefined mRotation=ROTATION_0} s.9 fontWeightAdjustment=0} + mHasSurface=true isReadyForDisplay()=true mWindowRemovalAllowed=false + Frames: parent=[0,63][1080,2400] display=[0,63][1080,2400] frame=[0,63][1080,2400] last=[0,63][1080,2400] insetsChanged=false + surface=[0,0][0,0] + ContainerAnimator: + mLeash=Surface(name=Surface(name=e7383a7 InputMethod#5696)/@0xc1d8bfd - animation-leash of insets_animation#10952)/@0x23dd89f mAnimationType=insets_animation + Animation: com.android.server.wm.InsetsSourceProvider$ControlAdapter@64fddec + ControlAdapter mCapturedLeash=Surface(name=Surface(name=e7383a7 InputMethod#5696)/@0xc1d8bfd - animation-leash of insets_animation#10952)/@0x23dd89f + WindowStateAnimator{db8d88 InputMethod}: + mSurface=Surface(name=InputMethod#10962)/@0x62795b5 + Surface: shown=true mDrawState=HAS_DRAWN mLastHidden=false + mEnterAnimationPending=false + isOnScreen=true + isVisible=true + keepClearAreas: restricted=[], unrestricted=[] + Requested non-default-visibility types: captionBar + mPrepareSyncSeqId=0 + mBufferSeqId=0 diff --git a/src/backends/adb-backend.test.ts b/src/backends/adb-backend.test.ts index 5669a4b..e9c6867 100644 --- a/src/backends/adb-backend.test.ts +++ b/src/backends/adb-backend.test.ts @@ -765,6 +765,94 @@ describe('AdbBackend.tapElement', () => { ).toHaveLength(0); }); + describe('with a keyboard window in the snapshot', () => { + // A keyboard window whose snapshot has no node at the target (the key is + // missing from the tree), over a free app button at (300, 230). + const withKeyboard = parseAndroidHierarchy( + ``, + ); + const target = findElement( + withKeyboard, + { identifier: 'submit' }, + true, + ) as UIElement; + const imeDump = (region: string, visible = true): string => + `WINDOW MANAGER WINDOWS (dumpsys window windows)\n Window #0 Window{e7383a7 u0 InputMethod}:\n mAttrs={(0,0)(fillxfill) ty=INPUT_METHOD fmt=TRANSPARENT}\n touchable region=SkRegion(${region})\n isOnScreen=${String(visible)}\n isVisible=${String(visible)}\n`; + const imeReads = (): unknown[][] => + mockExecStrict.mock.calls.filter(([, args]) => + args?.includes('InputMethod'), + ); + const fakeDevice = (dump: string | Error): void => { + mockExecStrict.mockImplementation(async (_cmd, args) => { + if (args?.includes('wm')) { + return 'Physical size: 1080x2400'; + } + if (args?.includes('InputMethod')) { + if (dump instanceof Error) { + throw dump; + } + return dump; + } + return ''; + }); + }; + + it('refuses a tap inside the touchable region the snapshot missed', async () => { + fakeDevice(imeDump('(94,137,525,262)(21,863,169,1553)')); + + await expect( + backend.tapElement({ identifier: 'submit' }, { element: target }), + ).rejects.toMatchObject({ + code: 'TARGET_OBSCURED', + keyboard: true, + message: expect.stringContaining( + 'by the keyboard: touchable area [94,137][525,262]', + ), + }); + expect(imeReads()).toStrictEqual([ + [ + 'adb', + ['-s', 'emulator-5554', 'shell', 'dumpsys', 'window', 'InputMethod'], + ], + ]); + expect(tapCalls()).toHaveLength(0); + }); + + it('taps when the point is outside the touchable region', async () => { + fakeDevice(imeDump('(94,137,225,180)(21,863,169,1553)')); + + await backend.tapElement({ identifier: 'submit' }, { element: target }); + + expect(tapCalls()).toHaveLength(1); + }); + + it('taps when the keyboard window is no longer visible', async () => { + fakeDevice(imeDump('(0,0,1080,2400)', false)); + + await backend.tapElement({ identifier: 'submit' }, { element: target }); + + expect(tapCalls()).toHaveLength(1); + }); + + it('falls back to the snapshot when the region cannot be read', async () => { + fakeDevice(new Error('adb: device offline')); + + await backend.tapElement({ identifier: 'submit' }, { element: target }); + + expect(imeReads()).toHaveLength(1); + expect(tapCalls()).toHaveLength(1); + }); + + it('does not read the region without a keyboard window', async () => { + fakeDevice(imeDump('(0,0,1080,2400)')); + + await backend.tapElement({ identifier: 'submit' }, { element }); + + expect(imeReads()).toHaveLength(0); + expect(tapCalls()).toHaveLength(1); + }); + }); + it('snapshots to find the element when none is passed', async () => { mockExecStrict.mockImplementation(async (_cmd, args) => args?.includes('cat') || args?.includes('dump') diff --git a/src/backends/adb-backend.ts b/src/backends/adb-backend.ts index 09c6007..dbbf9f7 100644 --- a/src/backends/adb-backend.ts +++ b/src/backends/adb-backend.ts @@ -57,6 +57,8 @@ import { runWebViewCdp } from './webview-cdp.js'; import { ACCEPT_LABELS, DENY_LABELS } from '../utils/alert-labels.js'; import { assertAndroidHittable, + hasInputMethodAbove, + parseInputMethodTouchableRegion, setAndroidNodeInfo, } from '../utils/android-hit-test.js'; import type { AndroidWindowInfo } from '../utils/android-hit-test.js'; @@ -338,7 +340,7 @@ export class AdbBackend implements DeviceBackend { const screen = await this.#cachedWindowSize(); const { x, y } = visibleCenter(element, screen); - assertAndroidHittable(element, { x, y }, screen); + await this.#assertHittable(element, { x, y }, screen); await this.tapCoordinates(x, y); return { @@ -992,7 +994,7 @@ export class AdbBackend implements DeviceBackend { const screen = await this.#cachedWindowSize(); const { x: cx, y: cy } = visibleCenter(element, screen); - assertAndroidHittable(element, { x: cx, y: cy }, screen); + await this.#assertHittable(element, { x: cx, y: cy }, screen); await this.#adb([ 'shell', 'input', @@ -1049,6 +1051,39 @@ export class AdbBackend implements DeviceBackend { return texts.join('\n'); } + /** + * Refuse a tap on a covered target (see `assertAndroidHittable`). When the + * snapshot has a keyboard window above the target, also read where the + * keyboard takes touches now (`dumpsys window InputMethod`, ~20–30 ms), so + * a tap under a key the snapshot missed is refused too. Without a keyboard + * window there is no extra device call. If the read fails, the check uses + * the snapshot only, as before. + * + * @param element - The element to tap. + * @param point - The tap point. + * @param point.x - X in pixels. + * @param point.y - Y in pixels. + * @param screen - The screen size. + */ + async #assertHittable( + element: UIElement, + point: { x: number; y: number }, + screen: WindowSize, + ): Promise { + let keyboardRegion; + if (hasInputMethodAbove(element)) { + const dump = await this.#adb([ + 'shell', + 'dumpsys', + 'window', + 'InputMethod', + ]).catch(() => undefined); + keyboardRegion = + dump === undefined ? undefined : parseInputMethodTouchableRegion(dump); + } + assertAndroidHittable(element, point, screen, { keyboardRegion }); + } + /** * The screen size, read once per backend (one `adb shell wm size`) for the * tap viewport check. A failed read is not cached. diff --git a/src/utils/android-hit-test.test.ts b/src/utils/android-hit-test.test.ts index 620cb86..3d31d07 100644 --- a/src/utils/android-hit-test.test.ts +++ b/src/utils/android-hit-test.test.ts @@ -1,7 +1,11 @@ import { readFileSync } from 'node:fs'; import { describe, expect, it } from 'vitest'; -import { assertAndroidHittable } from './android-hit-test.js'; +import { + assertAndroidHittable, + hasInputMethodAbove, + parseInputMethodTouchableRegion, +} from './android-hit-test.js'; import { findElement, visibleCenter } from './element.js'; import { TargetObscuredError } from './hit-test.js'; import { parseAndroidHierarchy } from '../backends/adb-backend.js'; @@ -9,6 +13,16 @@ import type { UIElement } from '../backends/types.js'; const SCREEN = { width: 1080, height: 2400 }; +/** + * @param file - A file name under `src/backends/__fixtures__`. + * @returns Its text. + */ +const fixtureText = (file: string): string => + readFileSync( + new URL(`../backends/__fixtures__/${file}`, import.meta.url), + 'utf8', + ); + /** * Snapshot-helper XML recorded on the Android emulator (1080x2400, * MetaMask Mobile dev build). Texts, labels and most resource ids are @@ -23,15 +37,41 @@ const SCREEN = { width: 1080, height: 2400 }; * @returns The parsed hierarchy. */ const fixture = (name: string): UIElement[] => - parseAndroidHierarchy( - readFileSync( - new URL( - `../backends/__fixtures__/adb-helper-${name}.xml`, - import.meta.url, - ), - 'utf8', - ), - ); + parseAndroidHierarchy(fixtureText(`adb-helper-${name}.xml`)); + +/** + * Remove the subtree of the first node with these bounds. + * + * @param xml - Helper XML. + * @param bounds - The node's `bounds` attribute value. + * @returns The XML without that node and its children. + */ +const withoutSubtree = (xml: string, bounds: string): string => { + const start = xml.indexOf(`bounds="${bounds}"`); + const open = xml.lastIndexOf(']*?(\/?)>/gu; + tag.lastIndex = open; + let depth = 0; + for (let match = tag.exec(xml); match; match = tag.exec(xml)) { + if (match[1]) { + depth -= 1; + } else if (!match[2]) { + depth += 1; + } + if (depth === 0) { + return xml.slice(0, open) + xml.slice(tag.lastIndex); + } + } + throw new Error(`no node with bounds ${bounds}`); +}; + +/** + * `dumpsys window InputMethod` recorded on the same emulator: Gboard's + * floating toolbar shown (`isVisible=true`, the touchable region is the + * suggestion key, the toolbar and the navigation bar strip), and hidden. + */ +const IME_SHOWN = fixtureText('adb-dumpsys-window-ime-shown.txt'); +const IME_HIDDEN = fixtureText('adb-dumpsys-window-ime-hidden.txt'); /** * Run the hit test at the element's visible center. @@ -134,6 +174,120 @@ describe('assertAndroidHittable (recorded helper XML)', () => { ); }); + describe('the keyboard touchable region', () => { + // As seen live: Gboard's floating "Zz" suggestion key missing from the + // snapshot (its container [94,137][1080,2400] and everything under it). + const searchXml = fixtureText('adb-helper-search-keyboard.xml'); + const withoutZz = parseAndroidHierarchy( + withoutSubtree(searchXml, '[94,137][1080,2400]'), + ); + const region = parseInputMethodTouchableRegion(IME_SHOWN); + const input = byId(withoutZz, 'multichain-account-selector-search-input'); + + it('parses the recorded region of the shown keyboard', () => { + expect(region).toStrictEqual([ + { x: 94, y: 137, width: 131, height: 125 }, + { x: 21, y: 863, width: 148, height: 690 }, + { x: 0, y: 2337, width: 1080, height: 63 }, + ]); + }); + + it('is the only thing that catches a key missing from the snapshot', () => { + // Without the region, the snapshot alone lets the tap through. + expect(() => + assertAndroidHittable(input, { x: 150, y: 240 }, SCREEN), + ).not.toThrow(); + + let error: unknown; + try { + assertAndroidHittable(input, { x: 150, y: 240 }, SCREEN, { + keyboardRegion: region, + }); + } catch (caught) { + error = caught; + } + expect(error).toBeInstanceOf(TargetObscuredError); + expect(error).toMatchObject({ keyboard: true, x: 150, y: 240 }); + expect((error as Error).message).toContain( + 'by the keyboard: touchable area [94,137][225,262]. ', + ); + expect((error as Error).message).toContain( + 'Dismiss the keyboard (device_dismiss_keyboard)', + ); + }); + + it('refuses a point under the toolbar or the navigation bar strip', () => { + for (const point of [ + { x: 95, y: 1324 }, + { x: 540, y: 2380 }, + ]) { + expect(() => + assertAndroidHittable(input, point, SCREEN, { + keyboardRegion: region, + }), + ).toThrow(TargetObscuredError); + } + }); + + it.each([ + 'multichain-account-selector-search-input', + 'back-arrow-button', + 'account-list-add-account-button', + 'button-icon', + ])( + 'lets a tap on the free %s through (above or beside the keyboard)', + (identifier) => { + const element = byId(withoutZz, identifier); + + expect(() => + assertAndroidHittable( + element, + visibleCenter(element, SCREEN), + SCREEN, + { keyboardRegion: region }, + ), + ).not.toThrow(); + }, + ); + + it('is empty when the keyboard is hidden', () => { + expect(parseInputMethodTouchableRegion(IME_HIDDEN)).toStrictEqual([]); + }); + + it('is unknown when a visible keyboard has no region line', () => { + expect( + parseInputMethodTouchableRegion( + IME_SHOWN.replace(/touchable region=.*$/mu, ''), + ), + ).toBeUndefined(); + }); + + it('is empty without an input-method window in the dump', () => { + expect( + parseInputMethodTouchableRegion( + IME_SHOWN.replace(/ty=INPUT_METHOD/u, 'ty=BASE_APPLICATION'), + ), + ).toStrictEqual([]); + }); + + it('is only needed when the snapshot has a keyboard window', () => { + expect(hasInputMethodAbove(input)).toBe(true); + expect(hasInputMethodAbove(byId(home, 'account-picker'))).toBe(false); + }); + + it('changes nothing without a keyboard window (wallet home)', () => { + const hamburger = byId(home, 'navbar-hamburger-menu-button'); + const picker = byId(home, 'account-picker'); + + expect(check(hamburger)?.keyboard).toBe(false); + expect(() => + assertAndroidHittable(picker, visibleCenter(picker, SCREEN), SCREEN, { + keyboardRegion: [], + }), + ).not.toThrow(); + }); + }); + it('ignores the keyboard window outside its drawn nodes', () => { // The IME window's bounds cover y 137..2400, but nothing is drawn here. const input = byId(search, 'multichain-account-selector-search-input'); diff --git a/src/utils/android-hit-test.ts b/src/utils/android-hit-test.ts index 28044f8..c3d33a1 100644 --- a/src/utils/android-hit-test.ts +++ b/src/utils/android-hit-test.ts @@ -66,14 +66,97 @@ export function setAndroidNodeInfo( nodeInfo.set(element, info); } +/** + * Whether the snapshot `target` came from has an input-method (keyboard) + * window above the target's window. Only then is the keyboard's touchable + * region worth reading (see {@link parseInputMethodTouchableRegion}). + * + * @param target - The element to tap. + * @returns True when a keyboard window is above the target's window. + */ +export function hasInputMethodAbove(target: UIElement): boolean { + const info = nodeInfo.get(target); + const targetRoot = ancestorChain(target)[0] ?? target; + const targetWindow = nodeInfo.get(targetRoot)?.window; + if (!info || !targetWindow) { + return false; + } + return info.roots.some((root) => { + const window = nodeInfo.get(root)?.window; + return ( + window?.type === WINDOW_TYPE_INPUT_METHOD && + window.layer > targetWindow.layer + ); + }); +} + +/** + * Read the keyboard's touchable region from `dumpsys window InputMethod`: + * the `touchable region=SkRegion((l,t,r,b)…)` of each input-method window + * (`ty=INPUT_METHOD`) that is visible (`isVisible=true`), in screen pixels. + * + * This is where the keyboard takes touches right now, whatever its + * accessibility tree shows. Gboard's floating toolbar (hardware keyboard on) + * is `(94,137,225,262)(21,863,169,1553)(0,2337,1080,2400)`: the suggestion + * key, the toolbar, and the navigation bar strip. The accessibility tree can + * miss the suggestion key, and the window bounds lag behind it. + * + * @param dump - The `dumpsys window InputMethod` output. + * @returns The rects; empty when no keyboard window is visible; undefined + * when a visible keyboard window has no readable region (unknown). + */ +export function parseInputMethodTouchableRegion( + dump: string, +): Frame[] | undefined { + const rects: Frame[] = []; + for (const block of dump.split(/^\s*Window #\d+ /mu).slice(1)) { + if (!/\bty=INPUT_METHOD\b/u.test(block)) { + continue; + } + if (!/\bisVisible=true\b/u.test(block)) { + continue; + } + const region = + /touchable region=SkRegion\(((?:\(-?\d+,-?\d+,-?\d+,-?\d+\))*)\)/u.exec( + block, + ); + if (!region) { + return undefined; + } + for (const [, left, top, right, bottom] of (region[1] ?? '').matchAll( + /\((-?\d+),(-?\d+),(-?\d+),(-?\d+)\)/gu, + )) { + const frame = { + x: Number(left), + y: Number(top), + width: Number(right) - Number(left), + height: Number(bottom) - Number(top), + }; + if (hasArea(frame)) { + rects.push(frame); + } + } + } + return rects; +} + /** * Find what a tap at `point` would hit instead of `target`, from the - * snapshot the target came from. No device call. + * snapshot the target came from, and, while a keyboard is up, the keyboard's + * touchable region read at tap time. * * - A higher window (the keyboard, a system window): any drawn node of it at * the point. A window's root frame is often the whole screen and * transparent, so only nodes that draw or take input count (clickable, * labelled, or leaves). + * - The keyboard's touchable region (`options.keyboardRegion`), when the + * caller read it: a point inside it is refused as the keyboard, even when the + * snapshot has no keyboard node there. Gboard's floating suggestion key is + * sometimes missing from the accessibility tree, and the keyboard window's + * bounds lag behind what is drawn, so neither can stand in for it. The + * window bounds or the drawn keys widened to the full width would also + * refuse free targets on the upper screen, because with a hardware keyboard + * the window is much larger than its keys. * - The target's window: a node drawn after the target (higher * `drawing-order` where the two branches split) that contains the point and * draws there (see `drawsItself` and `drawsAt`). @@ -103,12 +186,17 @@ export function setAndroidNodeInfo( * @param point.x - X in pixels. * @param point.y - Y in pixels. * @param screen - The screen size in pixels. + * @param options - Data read from the device at tap time. + * @param options.keyboardRegion - The keyboard's touchable region, from + * {@link parseInputMethodTouchableRegion}. Omit when there is no keyboard + * window in the snapshot, or the region can't be read. * @throws {TargetObscuredError} When another node is on top at the point. */ export function assertAndroidHittable( target: UIElement, point: { x: number; y: number }, screen: HitTestWindow, + options: { keyboardRegion?: Frame[] } = {}, ): void { const info = nodeInfo.get(target); if (!info) { @@ -147,6 +235,20 @@ export function assertAndroidHittable( } } + const keyboardRect = options.keyboardRegion?.find((rect) => + contains(rect, point), + ); + if (keyboardRect) { + const keyboardRoot = + info.roots.find( + (root) => nodeInfo.get(root)?.window?.type === WINDOW_TYPE_INPUT_METHOD, + ) ?? targetRoot; + throw new TargetObscuredError(target, keyboardRoot, point, { + keyboard: true, + obscuredByDescription: `touchable area ${formatRect(keyboardRect)}`, + }); + } + const windowBounds = targetWindow.bounds; const hits = matching( targetRoot, @@ -425,6 +527,14 @@ function describeNamed(node: UIElement): string { return parts.join(' '); } +/** + * @param frame - A frame. + * @returns It as Android bounds, `[left,top][right,bottom]`. + */ +function formatRect(frame: Frame): string { + return `[${frame.x},${frame.y}][${frame.x + frame.width},${frame.y + frame.height}]`; +} + /** * @param frame - A frame. * @returns Its area. From 1322043b1c1f86d1af852be7f738ca10cec7dc06 Mon Sep 17 00:00:00 2001 From: cryptotavares Date: Tue, 17 Nov 2026 08:39:50 +0000 Subject: [PATCH 4/4] refactor: simplify the Android occlusion check - AdbBackend#assertHittable: compute the keyboard dump in one expression instead of a mutable local assigned inside an `if`. - assertAndroidHittable: carry each higher window's metadata with its root, which drops the unchecked `as AndroidWindowInfo` cast and the repeated `nodeInfo` lookup while sorting. - drawsAt: one guard for the node's visibility, area and full width. No behaviour change. --- src/backends/adb-backend.ts | 21 +++++++++------------ src/utils/android-hit-test.ts | 24 +++++++++++------------- 2 files changed, 20 insertions(+), 25 deletions(-) diff --git a/src/backends/adb-backend.ts b/src/backends/adb-backend.ts index dbbf9f7..68393e8 100644 --- a/src/backends/adb-backend.ts +++ b/src/backends/adb-backend.ts @@ -1070,18 +1070,15 @@ export class AdbBackend implements DeviceBackend { point: { x: number; y: number }, screen: WindowSize, ): Promise { - let keyboardRegion; - if (hasInputMethodAbove(element)) { - const dump = await this.#adb([ - 'shell', - 'dumpsys', - 'window', - 'InputMethod', - ]).catch(() => undefined); - keyboardRegion = - dump === undefined ? undefined : parseInputMethodTouchableRegion(dump); - } - assertAndroidHittable(element, point, screen, { keyboardRegion }); + const dump = hasInputMethodAbove(element) + ? await this.#adb(['shell', 'dumpsys', 'window', 'InputMethod']).catch( + () => undefined, + ) + : undefined; + assertAndroidHittable(element, point, screen, { + keyboardRegion: + dump === undefined ? undefined : parseInputMethodTouchableRegion(dump), + }); } /** diff --git a/src/utils/android-hit-test.ts b/src/utils/android-hit-test.ts index c3d33a1..bc37299 100644 --- a/src/utils/android-hit-test.ts +++ b/src/utils/android-hit-test.ts @@ -210,17 +210,14 @@ export function assertAndroidHittable( } const higher = info.roots - .filter((root) => { + .flatMap((root) => { const window = nodeInfo.get(root)?.window; - return root !== targetRoot && window && window.layer > targetWindow.layer; + return root !== targetRoot && window && window.layer > targetWindow.layer + ? [{ root, window }] + : []; }) - .sort( - (a, b) => - (nodeInfo.get(b)?.window?.layer ?? 0) - - (nodeInfo.get(a)?.window?.layer ?? 0), - ); - for (const root of higher) { - const window = nodeInfo.get(root)?.window as AndroidWindowInfo; + .sort((a, b) => b.window.layer - a.window.layer); + for (const { root, window } of higher) { const hit = deepest( root, (node) => contains(node.frame, point) && drawsItself(node, window.bounds), @@ -411,10 +408,11 @@ function drawsAt(node: UIElement, window: Frame): boolean { return true; } const info = nodeInfo.get(node); - if (!info?.visibleToUser || !hasArea(node.frame)) { - return false; - } - if (node.frame.width >= window.width) { + if ( + !info?.visibleToUser || + !hasArea(node.frame) || + node.frame.width >= window.width + ) { return false; } const drawn = drawnDescendantsInside(node, node.frame, window);