1 /*
<lambda>null2  * Copyright (C) 2020 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 @file:JvmName("AccessibilityNodeInfoUtils")
18 
19 package com.android.compatibility.common.util
20 
21 import android.graphics.Rect
22 import android.view.accessibility.AccessibilityNodeInfo
23 import androidx.test.InstrumentationRegistry
24 
25 val UI_ROOT: AccessibilityNodeInfo get() =
26     InstrumentationRegistry.getInstrumentation().uiAutomation.rootInActiveWindow
27 
28 val AccessibilityNodeInfo.bounds: Rect get() = Rect().also { getBoundsInScreen(it) }
29 
AccessibilityNodeInfonull30 fun AccessibilityNodeInfo.click() {
31     val bounds = bounds
32     SystemUtil.runShellCommand("input tap ${bounds.centerX()} ${bounds.centerY()}")
33 }
34 
AccessibilityNodeInfonull35 fun AccessibilityNodeInfo.depthFirstSearch(
36     condition: (AccessibilityNodeInfo) -> Boolean
37 ): AccessibilityNodeInfo? {
38     for (child in children) {
39         child?.depthFirstSearch(condition)?.let { return it }
40     }
41     if (condition(this)) return this
42     return null
43 }
44 
AccessibilityNodeInfonull45 fun AccessibilityNodeInfo.lowestCommonAncestor(
46     condition1: (AccessibilityNodeInfo) -> Boolean,
47     condition2: (AccessibilityNodeInfo) -> Boolean
48 ): AccessibilityNodeInfo? {
49     return depthFirstSearch { node ->
50         node.depthFirstSearch(condition1) != null &&
51                 node.depthFirstSearch(condition2) != null
52     }
53 }
54 
55 val AccessibilityNodeInfo.children: List<AccessibilityNodeInfo> get() =
inull56     List(childCount) { i -> getChild(i) }
57 
58 val AccessibilityNodeInfo.textAsString: String? get() = (text as CharSequence?).toString()
59 
60 @JvmOverloads
<lambda>null61 fun uiDump(ui: AccessibilityNodeInfo? = UI_ROOT) = buildString {
62     UiDumpUtils.dumpNodes(ui, this)
63 }