From d1a4257e964fb8e2908c11c2e9eb4ea70c29aa61 Mon Sep 17 00:00:00 2001 From: lisonge Date: Sat, 20 Jul 2024 22:40:55 +0800 Subject: [PATCH] fix: lru error cache in some devices (#664) --- .../main/kotlin/li/songe/gkd/service/AbExt.kt | 29 ++++++++++++++----- 1 file changed, 21 insertions(+), 8 deletions(-) diff --git a/app/src/main/kotlin/li/songe/gkd/service/AbExt.kt b/app/src/main/kotlin/li/songe/gkd/service/AbExt.kt index 5a80979..79b89a9 100644 --- a/app/src/main/kotlin/li/songe/gkd/service/AbExt.kt +++ b/app/src/main/kotlin/li/songe/gkd/service/AbExt.kt @@ -25,6 +25,7 @@ import li.songe.selector.getCharSequenceInvoke import li.songe.selector.getIntInvoke import li.songe.selector.initDefaultTypeInfo + val AccessibilityService.safeActiveWindow: AccessibilityNodeInfo? get() = try { // java.lang.SecurityException: Call from user 0 as user -2 without permission INTERACT_ACROSS_USERS or INTERACT_ACROSS_USERS_FULL not allowed. @@ -241,17 +242,25 @@ private operator fun LruCache.set(child: K, value: V): V { private const val MAX_CACHE_SIZE = MAX_DESCENDANTS_SIZE class NodeCache { - private val childMap = + private var childMap = LruCache, AccessibilityNodeInfo>(MAX_CACHE_SIZE) - val indexMap = LruCache(MAX_CACHE_SIZE) - private val parentMap = LruCache(MAX_CACHE_SIZE) + private var indexMap = LruCache(MAX_CACHE_SIZE) + private var parentMap = LruCache(MAX_CACHE_SIZE) var rootNode: AccessibilityNodeInfo? = null fun clear() { rootNode = null - childMap.evictAll() - parentMap.evictAll() - indexMap.evictAll() + try { + childMap.evictAll() + parentMap.evictAll() + indexMap.evictAll() + } catch (e: Exception) { + // https://github.com/gkd-kit/gkd/issues/664 + // 在某些机型上 未知原因 缓存不一致 导致删除失败 + childMap = LruCache(MAX_CACHE_SIZE) + indexMap = LruCache(MAX_CACHE_SIZE) + parentMap = LruCache(MAX_CACHE_SIZE) + } } fun getRoot(node: AccessibilityNodeInfo): AccessibilityNodeInfo? { @@ -265,6 +274,10 @@ class NodeCache { val sizeList: List get() = listOf(childMap.size(), parentMap.size(), indexMap.size()) + fun getPureIndex(node: AccessibilityNodeInfo): Int? { + return indexMap[node] + } + fun getIndex(node: AccessibilityNodeInfo): Int { indexMap[node]?.let { return it } getParent(node)?.forEachIndexed { index, child -> @@ -428,7 +441,7 @@ fun createCacheTransform(): CacheTransform { sequence { val parentVal = cache.getParent(node) ?: return@sequence // 如果 node 由 quickFind 得到, 则第一次调用此方法可能得到 cache.index 是空 - val index = cache.indexMap[node] + val index = cache.getPureIndex(node) if (index != null) { var i = index - 1 var offset = 0 @@ -458,7 +471,7 @@ fun createCacheTransform(): CacheTransform { traverseAfterBrothers = { node, connectExpression -> val parentVal = cache.getParent(node) if (parentVal != null) { - val index = cache.indexMap[node] + val index = cache.getPureIndex(node) if (index != null) { sequence { var i = index + 1