优化 选择器搜索控件的DFS算法,改递归为栈,加快速度并且避免出现StackOverflow的问题
This commit is contained in:
@@ -2,6 +2,7 @@ package com.stardust.automator.search
|
|||||||
|
|
||||||
import com.stardust.automator.UiObject
|
import com.stardust.automator.UiObject
|
||||||
import com.stardust.automator.filter.Filter
|
import com.stardust.automator.filter.Filter
|
||||||
|
import java.util.*
|
||||||
|
|
||||||
import kotlin.collections.ArrayList
|
import kotlin.collections.ArrayList
|
||||||
|
|
||||||
@@ -12,32 +13,26 @@ import kotlin.collections.ArrayList
|
|||||||
object DFS : SearchAlgorithm {
|
object DFS : SearchAlgorithm {
|
||||||
|
|
||||||
override fun search(root: UiObject, filter: Filter, limit: Int): ArrayList<UiObject> {
|
override fun search(root: UiObject, filter: Filter, limit: Int): ArrayList<UiObject> {
|
||||||
val list = ArrayList<UiObject>()
|
val result = ArrayList<UiObject>()
|
||||||
if (filter.filter(root)) {
|
val stack = LinkedList<UiObject>()
|
||||||
list.add(root)
|
stack.push(root)
|
||||||
if (list.size >= limit) {
|
while (stack.isNotEmpty()) {
|
||||||
return list
|
val parent = stack.pop()
|
||||||
|
for (i in parent.childCount - 1 downTo 0) {
|
||||||
|
val child = parent.child(i) ?: continue
|
||||||
|
stack.push(child)
|
||||||
}
|
}
|
||||||
}
|
if (filter.filter(parent)) {
|
||||||
searchChildren(root, list, filter, limit)
|
result.add(parent)
|
||||||
return list
|
if (result.size >= limit) {
|
||||||
}
|
|
||||||
|
|
||||||
private fun searchChildren(parent: UiObject, list: MutableList<UiObject>, filter: Filter, limit: Int) {
|
|
||||||
for (i in 0 until parent.childCount) {
|
|
||||||
val child = parent.child(i) ?: continue
|
|
||||||
val isTarget = filter.filter(child)
|
|
||||||
if (isTarget) {
|
|
||||||
list.add(child)
|
|
||||||
if (list.size >= limit) {
|
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
}
|
} else {
|
||||||
searchChildren(child, list, filter, limit)
|
if (parent !== root) {
|
||||||
if (!isTarget) {
|
parent.recycle()
|
||||||
child.recycle()
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
return result
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user