Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -348,6 +348,18 @@ class AssistantService : AccessibilityService() {
* node of the active window. Returns null when unavailable; the caller treats the result
* exactly like a null event.source and recycles it like one. All node access is guarded —
* the root can be stale the moment we ask (#125).
*
* Two-stage: `findFocus(FOCUS_INPUT)` keeps precedence (it surfaces sources upstream
* accepts), and a bounded recursive search for an editable+focused node runs only when
* `findFocus` reports nothing — some hosts expose the input deeper in the tree than
* `findFocus` reaches.
*
* Ownership: when `findFocus` returns non-null, this method recycles `root` and returns the
* focused node. When `findFocus` returns null, ownership of `root` is transferred to
* [FocusedEditableFinder] which recycles every visited node except the match it returns
* (or all on miss). The outer catch's `safeRecycle` is a safety net for the rare case where
* an exception escapes before the finder takes ownership; double-recycle is benign
* (`safeRecycle` catches `IllegalStateException`, and on API 33+ `recycle()` is a no-op).
Comment on lines +360 to +362
*/
private fun findFocusedEditableSource(): AccessibilityNodeInfo? {
val root = try {
Expand All @@ -359,8 +371,14 @@ class AssistantService : AccessibilityService() {
try {
val focused = root.findFocus(AccessibilityNodeInfo.FOCUS_INPUT)
if (focused === root) return root
root.safeRecycle()
return focused
if (focused != null) {
root.safeRecycle()
return focused
}
// Second stage: findFocus found nothing, so walk the tree for an editable+focused
// node. The walk recycles every visited node except the match it returns.
val found = FocusedEditableFinder.find(AccessibilityFocusNode(root)) as? AccessibilityFocusNode
return found?.node
} catch (e: Exception) {
Log.w(TAG, "focused-node fallback failed", e)
root.safeRecycle()
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
package com.musheer360.swiftslate.service

import android.view.accessibility.AccessibilityNodeInfo

/**
* Minimal seam over a node in the accessibility tree so the fallback walk can be unit-tested
* with a fake tree. The real accessibility API can throw [IllegalStateException] from any
* accessor when the underlying view has gone away, so implementations are free to throw and
* [FocusedEditableFinder] must tolerate it.
*/
internal interface FocusNode {
val isEditable: Boolean
val isFocused: Boolean
val isPassword: Boolean
val childCount: Int

/** May return null for a recycled/gone child; may throw like the real API. */
fun getChild(index: Int): FocusNode?

fun recycle()
}

/**
* Bounded depth-first search for the node that is both editable and focused.
*
* This is the second-stage fallback behind [AccessibilityNodeInfo.findFocus]`(FOCUS_INPUT)`:
* `findFocus` keeps precedence (it can return container nodes upstream still accepts), and this
* walk only runs when `findFocus` reports nothing. Some hosts expose the editable input only as
* a deeper node that `findFocus` does not surface.
*
* The walk is deliberately bounded so a pathological or very deep tree cannot spike the main
* thread: at most [NODE_BUDGET] nodes are visited and the recursion never goes deeper than
* [MAX_DEPTH]. Every visited node is recycled on the way out — including when a node method
* throws mid-walk — except the node returned as the match, which the caller takes ownership of.
*
* Must be called on the main thread. The underlying [AccessibilityNodeInfo] accessors are
* Binder IPCs that block on the app's UI thread; calling off the main thread is unsafe and
* violates the service's threading contract. `remaining` is per-invocation state, so concurrent
* calls do not share mutable state, but the service already serializes calls via
* [AssistantService.FOCUS_FALLBACK_MIN_INTERVAL_MS].
*/
internal object FocusedEditableFinder {

const val NODE_BUDGET = 500
const val MAX_DEPTH = 32

/** Must be called on the main thread — see class KDoc. */
fun find(root: FocusNode): FocusNode? {
var remaining = NODE_BUDGET

fun walk(node: FocusNode, depth: Int): FocusNode? {
// Recycle `node` on every exit except when it is the returned match. The finally
// block guarantees recycling even when an accessor throws mid-walk.
var keep = false
try {
if (remaining <= 0 || depth > MAX_DEPTH) return null
remaining--
// Defense-in-depth: password fields are also editable+focused but must never be
// returned as a typing target. The caller in AssistantService also checks
// isPassword after the fallback, but filtering here prevents future reuse from
// leaking password nodes if that check is ever forgotten.
if (node.isPassword) {
// Fall through to child scan — do not keep this node, recycle in finally.
} else if (node.isEditable && node.isFocused) {
keep = true
return node
}
val childCount = node.childCount
for (i in 0 until childCount) {
val child = node.getChild(i) ?: continue
val found = walk(child, depth + 1)
if (found != null) return found
Comment on lines +68 to +72
}
return null
} catch (e: Exception) {
// The node went stale mid-walk. Treat this branch as a miss; `finally` recycles
// this frame's node and children already visited were recycled in their frames.
return null
} finally {
if (!keep) node.recycle()
}
}

return walk(root, 0)
}
}

/** Bridges a real [AccessibilityNodeInfo] to [FocusNode] without swallowing its exceptions. */
internal class AccessibilityFocusNode(val node: AccessibilityNodeInfo) : FocusNode {
override val isEditable: Boolean get() = node.isEditable
override val isFocused: Boolean get() = node.isFocused
override val isPassword: Boolean get() = node.isPassword
override val childCount: Int get() = node.childCount
override fun getChild(index: Int): FocusNode? =
node.getChild(index)?.let(::AccessibilityFocusNode)

override fun recycle() {
try {
node.recycle()
} catch (_: Exception) {
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,216 @@
package com.musheer360.swiftslate.service

import org.junit.Assert.assertFalse
import org.junit.Assert.assertNull
import org.junit.Assert.assertSame
import org.junit.Assert.assertTrue
import org.junit.Test

/**
* Exercises [FocusedEditableFinder] against a fake tree, since the real
* [android.view.accessibility.AccessibilityNodeInfo] is Binder-backed and unavailable under the
* JVM. The fake mirrors the one thing that matters here: accessors can throw once a node is
* stale, and `recycle()` records whether the walk cleaned up after itself.
*/
private class FakeNode(
val name: String,
isEditable: Boolean = false,
isFocused: Boolean = false,
isPassword: Boolean = false,
val children: MutableList<FakeNode> = mutableListOf(),
val throwOnChildAccess: Boolean = false,
val throwOnIsEditable: Boolean = false,
val throwOnIsFocused: Boolean = false,
val throwOnIsPassword: Boolean = false,
) : FocusNode {
private val editableValue = isEditable
private val focusedValue = isFocused
private val passwordValue = isPassword
var recycled = false
private set

override val isEditable: Boolean
get() {
if (throwOnIsEditable) throw IllegalStateException("stale isEditable: $name")
return editableValue
}

override val isFocused: Boolean
get() {
if (throwOnIsFocused) throw IllegalStateException("stale isFocused: $name")
return focusedValue
}

override val isPassword: Boolean
get() {
if (throwOnIsPassword) throw IllegalStateException("stale isPassword: $name")
return passwordValue
}

override val childCount: Int
get() {
if (throwOnChildAccess) throw IllegalStateException("stale node: $name")
return children.size
}

override fun getChild(index: Int): FocusNode? {
if (throwOnChildAccess) throw IllegalStateException("stale node: $name")
return children.getOrNull(index)
}

override fun recycle() {
recycled = true
}
}

class FocusedEditableFinderTest {

@Test
fun matchAtRoot_returnsTheRootWithoutRecycling() {
val root = FakeNode("root", isEditable = true, isFocused = true)
assertSame(root, FocusedEditableFinder.find(root))
assertFalse(root.recycled)
}

@Test
fun deepMatch_returnsTheLeafAndRecyclesItsAncestors() {
val leaf = FakeNode("leaf", isEditable = true, isFocused = true)
val mid = FakeNode("mid", children = mutableListOf(leaf))
val root = FakeNode("root", children = mutableListOf(mid))

assertSame(leaf, FocusedEditableFinder.find(root))
assertTrue(root.recycled)
assertTrue(mid.recycled)
assertFalse(leaf.recycled)
}

@Test
fun miss_recyclesEveryVisitedNode() {
val grandchild = FakeNode("grandchild")
val left = FakeNode("left", children = mutableListOf(grandchild))
val right = FakeNode("right")
val root = FakeNode("root", children = mutableListOf(left, right))

assertNull(FocusedEditableFinder.find(root))
assertTrue(root.recycled)
assertTrue(left.recycled)
assertTrue(right.recycled)
assertTrue(grandchild.recycled)
}

@Test
fun budgetCap_stopsBeforeAChainLongerThanTheBudget() {
// One node past the budget, with the only match at the far end of a linear chain.
// Note: depth also caps at 32, so a deep chain hits depth first. To isolate budget,
// use a wide shallow tree where all children are at depth 1.
val root = FakeNode("root")
repeat(FocusedEditableFinder.NODE_BUDGET + 1) { i ->
val isLast = i == FocusedEditableFinder.NODE_BUDGET
root.children.add(FakeNode("n$i", isEditable = isLast, isFocused = isLast))
}
assertNull(FocusedEditableFinder.find(root))
// Verify no leak — root and all visited children must be recycled on miss.
assertTrue(root.recycled)
for (i in 0 until FocusedEditableFinder.NODE_BUDGET + 1) assertTrue("n$i not recycled", root.children[i].recycled)
}

@Test
fun depthCap_stopsBeforeAMatchBeyondMaxDepth() {
val chain = (0..FocusedEditableFinder.MAX_DEPTH + 1).map { i ->
val last = i == FocusedEditableFinder.MAX_DEPTH + 1
FakeNode("n$i", isEditable = last, isFocused = last)
}
for (i in 0 until chain.size - 1) chain[i].children.add(chain[i + 1])

assertNull(FocusedEditableFinder.find(chain.first()))
}

@Test
fun exceptionMidWalk_recyclesEveryNodeAlreadyVisited() {
val healthy = FakeNode("healthy")
val stale = FakeNode(
"stale",
throwOnChildAccess = true,
children = mutableListOf(FakeNode("unreachable-child")),
)
val root = FakeNode("root", children = mutableListOf(healthy, stale))

// stale.childCount throws mid-walk; the walk must not crash and must not leak the
// nodes it already obtained.
assertNull(FocusedEditableFinder.find(root))
assertTrue(root.recycled)
assertTrue(healthy.recycled)
assertTrue(stale.recycled)
}

@Test
fun isEditableThrows_recyclesNode() {
val throwing = FakeNode("throwEditable", throwOnIsEditable = true, isFocused = true)
val root = FakeNode("root", children = mutableListOf(throwing))
assertNull(FocusedEditableFinder.find(root))
assertTrue(root.recycled)
assertTrue(throwing.recycled)
}

@Test
fun isFocusedThrows_recyclesNode() {
val throwing = FakeNode("throwFocused", isEditable = true, throwOnIsFocused = true)
val root = FakeNode("root", children = mutableListOf(throwing))
assertNull(FocusedEditableFinder.find(root))
assertTrue(root.recycled)
assertTrue(throwing.recycled)
}

@Test
fun isPasswordThrows_recyclesNode() {
val throwing = FakeNode("throwPassword", throwOnIsPassword = true, isEditable = true, isFocused = true)
val root = FakeNode("root", children = mutableListOf(throwing))
assertNull(FocusedEditableFinder.find(root))
assertTrue(root.recycled)
assertTrue(throwing.recycled)
}

@Test
fun getChildReturnsNull_skipsAndFindsSibling() {
val leaf = FakeNode("leaf", isEditable = true, isFocused = true)
val holeParent = object : FocusNode {
override val isEditable = false
override val isFocused = false
override val isPassword = false
override val childCount = 2
var recycled = false
override fun getChild(index: Int): FocusNode? = if (index == 0) null else leaf
override fun recycle() { recycled = true }
}
val customRoot = object : FocusNode {
override val isEditable = false
override val isFocused = false
override val isPassword = false
override val childCount = 1
var recycled = false
override fun getChild(index: Int): FocusNode? = holeParent
override fun recycle() { recycled = true }
}
assertSame(leaf, FocusedEditableFinder.find(customRoot))
assertFalse(leaf.recycled)
}

@Test
fun wideTree_respectsBudgetAndFindsMatch() {
val match = FakeNode("match", isEditable = true, isFocused = true)
val root = FakeNode("root", children = mutableListOf())
repeat(100) { root.children.add(FakeNode("noise$it")) }
root.children.add(match)
assertSame(match, FocusedEditableFinder.find(root))
assertFalse(match.recycled)
}

@Test
fun passwordNode_isNotReturnedEvenIfEditableAndFocused() {
val password = FakeNode("pwd", isEditable = true, isFocused = true, isPassword = true)
val root = FakeNode("root", children = mutableListOf(password))
assertNull(FocusedEditableFinder.find(root))
assertTrue(root.recycled)
assertTrue(password.recycled)
}
}
Loading