├── .gitignore ├── .idea ├── encodings.xml ├── misc.xml └── runConfigurations.xml ├── LICENSE ├── README.md ├── app ├── .gitignore ├── build.gradle ├── proguard-rules.pro └── src │ ├── androidTest │ └── java │ │ └── com │ │ └── github │ │ └── cmzf │ │ └── androidinspector │ │ └── ExampleInstrumentedTest.java │ ├── main │ ├── AndroidManifest.xml │ ├── assets │ │ ├── index.html │ │ ├── inspector.css │ │ ├── inspector.js │ │ └── jquery-3.4.1.min.js │ ├── java │ │ └── com │ │ │ └── github │ │ │ └── cmzf │ │ │ └── androidinspector │ │ │ ├── AccessibilityService.java │ │ │ ├── Global.java │ │ │ ├── InspectorServer.java │ │ │ ├── MainActivity.java │ │ │ ├── ScreenCaptureService.java │ │ │ ├── UiObject.java │ │ │ └── Utils.java │ └── res │ │ ├── drawable-v24 │ │ └── ic_launcher_foreground.xml │ │ ├── drawable │ │ └── ic_launcher_background.xml │ │ ├── layout │ │ └── activity_main.xml │ │ ├── mipmap-anydpi-v26 │ │ ├── ic_launcher.xml │ │ └── ic_launcher_round.xml │ │ ├── mipmap-hdpi │ │ ├── ic_launcher.png │ │ └── ic_launcher_round.png │ │ ├── mipmap-mdpi │ │ ├── ic_launcher.png │ │ └── ic_launcher_round.png │ │ ├── mipmap-xhdpi │ │ ├── ic_launcher.png │ │ └── ic_launcher_round.png │ │ ├── mipmap-xxhdpi │ │ ├── ic_launcher.png │ │ └── ic_launcher_round.png │ │ ├── mipmap-xxxhdpi │ │ ├── ic_launcher.png │ │ └── ic_launcher_round.png │ │ ├── values │ │ ├── colors.xml │ │ ├── strings.xml │ │ └── styles.xml │ │ └── xml │ │ └── accessibility_service_config.xml │ └── test │ └── java │ └── com │ └── github │ └── cmzf │ └── androidinspector │ └── ExampleUnitTest.java ├── build.gradle ├── gradle.properties ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── screenshots ├── 1.jpg ├── 2.jpg └── 3.jpg └── settings.gradle /.gitignore: -------------------------------------------------------------------------------- 1 | # Built application files 2 | *.apk 3 | *.aar 4 | *.ap_ 5 | *.aab 6 | 7 | # Files for the ART/Dalvik VM 8 | *.dex 9 | 10 | # Java class files 11 | *.class 12 | 13 | # Generated files 14 | bin/ 15 | gen/ 16 | out/ 17 | # Uncomment the following line in case you need and you don't have the release build type files in your app 18 | # release/ 19 | 20 | # Gradle files 21 | .gradle/ 22 | build/ 23 | 24 | # Local configuration file (sdk path, etc) 25 | local.properties 26 | 27 | # Proguard folder generated by Eclipse 28 | proguard/ 29 | 30 | # Log Files 31 | *.log 32 | 33 | # Android Studio Navigation editor temp files 34 | .navigation/ 35 | 36 | # Android Studio captures folder 37 | captures/ 38 | 39 | # IntelliJ 40 | *.iml 41 | .idea/workspace.xml 42 | .idea/tasks.xml 43 | .idea/gradle.xml 44 | .idea/assetWizardSettings.xml 45 | .idea/dictionaries 46 | .idea/libraries 47 | # Android Studio 3 in .gitignore file. 48 | .idea/caches 49 | .idea/modules.xml 50 | # Comment next line if keeping position of elements in Navigation Editor is relevant for you 51 | .idea/navEditor.xml 52 | 53 | # Keystore files 54 | # Uncomment the following lines if you do not want to check your keystore files in. 55 | #*.jks 56 | #*.keystore 57 | 58 | # External native build folder generated in Android Studio 2.2 and later 59 | .externalNativeBuild 60 | .cxx/ 61 | 62 | # Google Services (e.g. APIs or Firebase) 63 | # google-services.json 64 | 65 | # Freeline 66 | freeline.py 67 | freeline/ 68 | freeline_project_description.json 69 | 70 | # fastlane 71 | fastlane/report.xml 72 | fastlane/Preview.html 73 | fastlane/screenshots 74 | fastlane/test_output 75 | fastlane/readme.md 76 | 77 | # Version control 78 | vcs.xml 79 | 80 | # lint 81 | lint/intermediates/ 82 | lint/generated/ 83 | lint/outputs/ 84 | lint/tmp/ 85 | # lint/reports/ 86 | -------------------------------------------------------------------------------- /.idea/encodings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /.idea/misc.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 9 | -------------------------------------------------------------------------------- /.idea/runConfigurations.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 11 | 12 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Android Inspector 2 | A productive UI layout inspector app for Android and Appium, with embed HTTP server, is an alternative to uiautomatorviewer (monitor.bat). 3 | 4 | # Usage 5 | 1. Download apk from 6 | [releases page](https://github.com/cmzf/android-inspector/releases), 7 | and install it. 8 | 2. Click "START" button, and grant capture screen and accessibility 9 | permissions for Inspector. 10 | 3. Connect your PC and mobile in the same WIFI, or adb forward over a 11 | USB connection, then open the URL. 12 | 13 | # Screenshots 14 | ![screen 1](screenshots/1.jpg) 15 | 16 | ![screen 2](screenshots/2.jpg) 17 | 18 | ![screen 3](screenshots/3.jpg) 19 | -------------------------------------------------------------------------------- /app/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | -------------------------------------------------------------------------------- /app/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.application' 2 | 3 | android { 4 | compileSdkVersion 29 5 | buildToolsVersion "29.0.2" 6 | defaultConfig { 7 | applicationId "com.github.cmzf.androidinspector" 8 | minSdkVersion 26 9 | targetSdkVersion 29 10 | versionCode 200119 11 | versionName "2.0" 12 | testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" 13 | } 14 | buildTypes { 15 | release { 16 | minifyEnabled false 17 | proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' 18 | applicationVariants.all { variant -> 19 | variant.outputs.all { 20 | outputFileName = "${variant.applicationId}-${variant.name}-${variant.versionName}-${variant.versionCode}.apk" 21 | } 22 | } 23 | } 24 | } 25 | compileOptions { 26 | sourceCompatibility JavaVersion.VERSION_1_8 27 | targetCompatibility JavaVersion.VERSION_1_8 28 | } 29 | } 30 | 31 | dependencies { 32 | implementation fileTree(dir: 'libs', include: ['*.jar']) 33 | implementation 'androidx.appcompat:appcompat:1.1.0' 34 | implementation 'androidx.constraintlayout:constraintlayout:1.1.3' 35 | 36 | implementation 'com.github.koush:AndroidAsync:69baf973a1' 37 | implementation 'com.alibaba:fastjson:1.2.62' 38 | 39 | testImplementation 'junit:junit:4.12' 40 | androidTestImplementation 'androidx.test:runner:1.2.0' 41 | androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0' 42 | } 43 | -------------------------------------------------------------------------------- /app/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # You can control the set of applied configuration files using the 3 | # proguardFiles setting in build.gradle. 4 | # 5 | # For more details, see 6 | # http://developer.android.com/guide/developing/tools/proguard.html 7 | 8 | # If your project uses WebView with JS, uncomment the following 9 | # and specify the fully qualified class name to the JavaScript interface 10 | # class: 11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 12 | # public *; 13 | #} 14 | 15 | # Uncomment this to preserve the line number information for 16 | # debugging stack traces. 17 | #-keepattributes SourceFile,LineNumberTable 18 | 19 | # If you keep the line number information, uncomment this to 20 | # hide the original source file name. 21 | #-renamesourcefileattribute SourceFile 22 | -------------------------------------------------------------------------------- /app/src/androidTest/java/com/github/cmzf/androidinspector/ExampleInstrumentedTest.java: -------------------------------------------------------------------------------- 1 | package com.github.cmzf.androidinspector; 2 | 3 | import android.content.Context; 4 | 5 | import androidx.test.InstrumentationRegistry; 6 | import androidx.test.runner.AndroidJUnit4; 7 | 8 | import org.junit.Test; 9 | import org.junit.runner.RunWith; 10 | 11 | import static org.junit.Assert.*; 12 | 13 | /** 14 | * Instrumented test, which will execute on an Android device. 15 | * 16 | * @see Testing documentation 17 | */ 18 | @RunWith(AndroidJUnit4.class) 19 | public class ExampleInstrumentedTest { 20 | @Test 21 | public void useAppContext() { 22 | // Context of the app under test. 23 | Context appContext = InstrumentationRegistry.getTargetContext(); 24 | 25 | assertEquals("com.github.cmzf.androidinspector", appContext.getPackageName()); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /app/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 6 | 13 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 26 | 27 | 28 | 29 | 32 | 33 | 34 | 35 | 36 | -------------------------------------------------------------------------------- /app/src/main/assets/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | Android Inspector 7 | 8 | 9 |
10 |
11 |
12 |
# screen
13 |
14 | 15 |
16 |
17 |
18 |
19 |
# tree
20 |
21 |
22 |
23 |
# attrs
24 |
25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | 116 | 117 | 118 | 119 | 120 | 121 | 122 | 123 | 124 | 125 | 126 | 127 | 128 | 129 | 130 | 131 | 132 | 133 | 134 | 135 | 136 | 137 | 138 | 139 | 140 | 141 | 142 | 143 | 144 | 145 | 146 | 147 | 148 | 149 | 150 | 151 | 152 | 153 | 154 | 155 | 156 | 157 | 158 | 159 | 160 | 161 | 162 | 163 | 164 | 165 | 166 | 167 | 168 | 169 | 170 | 171 | 172 | 173 | 174 |
attrvalue
id
cls
pkg
text
desc
xpath
bounds
visibleToUser
index
childCount
checkable
clickable
contextClickable
dismissable
editable
focusable
longClickable
scrollable
accessibilityFocused
checked
enabled
focused
selected
contentInvalid
drawingOrder
extraData
extras
hintText
inputType
maxTextLength
multiLine
password
showingHintText
textSelectionEnd
textSelectionStart
windowId
175 |
176 |
177 |
178 |
179 | 180 | 181 | 182 | -------------------------------------------------------------------------------- /app/src/main/assets/inspector.css: -------------------------------------------------------------------------------- 1 | html, 2 | body { 3 | font-family: Consolas, monospace; 4 | font-size: 12px; 5 | height: 100%; 6 | margin: 0; 7 | padding: 0; 8 | width: 100%; 9 | overflow: hidden; 10 | } 11 | 12 | #container { 13 | box-sizing: border-box; 14 | height: 100%; 15 | padding: 10px; 16 | position: relative; 17 | min-height: 700px; 18 | } 19 | #prepare-mask { 20 | height: 100%; 21 | width: 100%; 22 | position: absolute; 23 | z-index: 9999; 24 | background: #ffffff; 25 | box-sizing: border-box; 26 | } 27 | 28 | #panel1, 29 | #panel2 { 30 | box-sizing: border-box; 31 | height: 100%; 32 | min-width: 300px; 33 | padding-top: 2em; 34 | position: relative; 35 | } 36 | 37 | #panel1 { 38 | float: left; 39 | } 40 | #panel2 { 41 | margin-left: 300px; 42 | } 43 | 44 | #panel21, 45 | #panel22 { 46 | box-sizing: border-box; 47 | float: left; 48 | height: 100%; 49 | min-width: 500px; 50 | overflow-y: auto; 51 | padding-left: 1.5em; 52 | width: 50%; 53 | } 54 | 55 | #panel1 .tabs, 56 | #panel2 .tabs { 57 | position: absolute; 58 | margin-left: 0; 59 | margin-bottom: 10px; 60 | font-weight: bold; 61 | top: 0; 62 | } 63 | 64 | #screen { 65 | float: left; 66 | height: 100%; 67 | position: relative; 68 | } 69 | 70 | #screen .node { 71 | position: absolute; 72 | margin: 0; 73 | top: 0; 74 | left: 0; 75 | padding: 0; 76 | z-index: 0; 77 | pointer-events: none; 78 | } 79 | 80 | #screen .node.node0 { 81 | outline: 1px solid #ffffff; 82 | } 83 | 84 | #screen .node.hover { 85 | outline: 1px solid #0066ff !important; 86 | z-index: 9999 !important; 87 | } 88 | 89 | #screen .node.current { 90 | background: #ff000033; 91 | outline: 1px solid #ff0000; 92 | } 93 | 94 | #tree { 95 | box-sizing: border-box; 96 | cursor: default; 97 | float: left; 98 | min-height: 1.65em; 99 | position: relative; 100 | width: 100%; 101 | } 102 | 103 | #tree .node { 104 | border: 1px solid #0066ff; 105 | list-style-type: none; 106 | padding: 0 0 0 10px; 107 | border-width: 1px 0 0 1px; 108 | background: #ffffff33; 109 | display: none; 110 | } 111 | 112 | #tree .node .name { 113 | display: block; 114 | padding: 3px 0; 115 | } 116 | 117 | #tree .node.node0 { 118 | border-width: 1px; 119 | } 120 | 121 | #tree .node.invisible { 122 | text-decoration: line-through; 123 | } 124 | 125 | #tree .node.hover { 126 | background-color: #00ff0099; 127 | } 128 | 129 | #tree .node.descendants>.name::after { 130 | content: "+"; 131 | float: right; 132 | padding-right: 10px; 133 | transition: 0.5s ease-in-out; 134 | } 135 | 136 | #tree .node.descendants>.node { 137 | display: none !important; 138 | } 139 | 140 | #tree .node.descendants.expand>.name::after { 141 | content: "-"; 142 | float: right; 143 | padding-right: 10px; 144 | transition: 0.5s ease-in-out; 145 | } 146 | 147 | #tree .node.descendants.expand>.node { 148 | display: block !important; 149 | } 150 | 151 | #tree .node.current { 152 | background-color: #ff000099; 153 | border-color: #ff0000; 154 | } 155 | 156 | #tree .node.current>.name { 157 | color: #ffffff; 158 | } 159 | 160 | /* #tree .current>.name::before { 161 | content: "▶"; 162 | margin-right: 5px; 163 | font-size: 0.8em; 164 | } */ 165 | 166 | #attrs { 167 | float: left; 168 | position: relative; 169 | width: 100%; 170 | } 171 | 172 | #attrs table { 173 | margin: 0; 174 | padding: 0; 175 | border-collapse: collapse; 176 | border-spacing: 0; 177 | width: 100%; 178 | word-break: break-all; 179 | } 180 | 181 | #attrs td, 182 | th { 183 | border: 1px solid #0066ff; 184 | padding: 3px 10px; 185 | text-align: left; 186 | } 187 | 188 | #attrs tr:nth-child(even) { 189 | background: #f6f6f6; 190 | } 191 | 192 | #attrs .name { 193 | width: 30%; 194 | } 195 | 196 | 197 | #logs { 198 | margin-left: 20px; 199 | margin-bottom: 20px; 200 | float: left; 201 | position: relative; 202 | border: 1px solid #0066ff; 203 | padding: 1em; 204 | width: 600px; 205 | box-sizing: border-box; 206 | } 207 | 208 | #console { 209 | margin-left: 20px; 210 | margin-bottom: 20px; 211 | float: left; 212 | position: relative; 213 | border: 1px solid #0066ff; 214 | padding: 1em; 215 | width: 600px; 216 | box-sizing: border-box; 217 | } -------------------------------------------------------------------------------- /app/src/main/assets/inspector.js: -------------------------------------------------------------------------------- 1 | $(function () { 2 | var tree = null; 3 | $.ajax({ 4 | url: '/api/tree', 5 | type: 'GET', 6 | dataType: 'json', 7 | async: false, 8 | success: function (data) { 9 | tree = data; 10 | } 11 | }); 12 | 13 | var scale = $("#screen>img").height() / tree.node.bounds.bottom; 14 | $("#screen>img").css({ 15 | height: $("#screen>img").height() + "px", 16 | }); 17 | $("#screen").css({ 18 | height: $("#screen").height() + "px", 19 | }); 20 | $("#container").css({ 21 | height: $("#container").outerHeight() + "px" 22 | }); 23 | $("#panel1").css({ 24 | 'width': $("#screen").width() + "px", 25 | }); 26 | $("#panel2").css({ 27 | 'margin-left': $("#screen").width() + "px", 28 | }); 29 | $("#prepare-mask").hide(); 30 | 31 | 32 | function formatTree(tree, index, xpath) { 33 | index = index || 0; 34 | tree.node.xpath = (xpath || '/') + '/' + tree.node.cls + '[' + index + ']' + 35 | (tree.node.id ? "[@resource-id='" + tree.node.id + "']" : '') + 36 | (tree.node.text ? "[@text='" + tree.node.text + "']" : '') + 37 | (tree.node.desc ? "[@content-desc='" + tree.node.desc + "']" : ''); 38 | tree.node.index = index; 39 | tree.node.bounds.centerX = (tree.node.bounds.left + tree.node.bounds.right) / 2 40 | tree.node.bounds.centerY = (tree.node.bounds.top + tree.node.bounds.bottom) / 2 41 | tree.node.bounds.width = tree.node.bounds.right - tree.node.bounds.left; 42 | tree.node.bounds.height = tree.node.bounds.bottom - tree.node.bounds.top; 43 | if (tree.children) { 44 | let i = 0; 45 | tree.children.forEach(element => { 46 | formatTree(element, i, tree.node.xpath); 47 | i++; 48 | }); 49 | } 50 | } 51 | formatTree(tree); 52 | 53 | function treeToList(tree) { 54 | var treeNodes = {}; 55 | treeNodes[tree.node.hash] = tree.node; 56 | if (tree.children) { 57 | tree.children 58 | .forEach(element => { 59 | var children = treeToList(element); 60 | for (const key in children) { 61 | treeNodes[key] = children[key]; 62 | } 63 | }); 64 | } 65 | return treeNodes; 66 | } 67 | var treeNodes = treeToList(tree); 68 | 69 | function genRange(tree, base) { 70 | var $dom = $(`
`); 71 | var baseTop = (base && base.top + 0) || 0; 72 | var baseLeft = (base && base.left + 0) || 0; 73 | var baseLv = (base && base.lv + 0) || 0; 74 | $dom.css({ 75 | top: (tree.node.bounds.top - baseTop) * scale + "px", 76 | left: (tree.node.bounds.left - baseLeft) * scale + "px", 77 | width: (tree.node.bounds.right - tree.node.bounds.left) * scale + "px", 78 | height: (tree.node.bounds.bottom - tree.node.bounds.top) * scale + "px", 79 | }); 80 | $dom.addClass("node" + baseLv); 81 | if (tree.children) { 82 | tree.children 83 | .forEach(element => { 84 | $dom.append( 85 | genRange(element, { 86 | top: tree.node.bounds.top, 87 | left: tree.node.bounds.left, 88 | lv: baseLv + 1 89 | }) 90 | ); 91 | }); 92 | } 93 | return $dom; 94 | } 95 | 96 | function genTree(tree, base) { 97 | var $dom = $( 98 | `
cls(${tree.node.cls})${tree.node.id ? '.id('+tree.node.id+')' : ''}${tree.node.text ? '.text('+tree.node.text+')' : ''}${tree.node.desc ? '.desc('+tree.node.desc+')' : ''}
` 99 | ); 100 | var baseLv = (base && base.lv + 0) || 0; 101 | $dom.addClass("node" + baseLv); 102 | if (baseLv == 0) { 103 | $dom.css('display', 'block'); 104 | } 105 | if (!tree.node.visibleToUser) { 106 | $dom.addClass('invisible'); 107 | } 108 | if (tree.children) { 109 | $dom.addClass('descendants'); 110 | tree.children 111 | .forEach(element => { 112 | $dom.append( 113 | genTree(element, { 114 | lv: baseLv + 1 115 | }) 116 | ); 117 | }); 118 | } 119 | return $dom; 120 | } 121 | 122 | function displayAttrs(node) { 123 | node = node || treeNodes[$("#tree .node.current:first").data('hash')]; 124 | $("#attrs table td.value").html(''); 125 | for (const key in node) { 126 | $(`tr#attr-${key} td.value`).text(typeof node[key] == 'object' ? JSON.stringify(node[key]) : node[key]); 127 | } 128 | } 129 | $("#screen").append(genRange(tree)); 130 | $("#tree").append(genTree(tree)); 131 | $("#screen").mousemove(function (e) { 132 | $('#screen .node').removeClass("hover"); 133 | $('#tree .node').removeClass("hover expand"); 134 | for (const key in treeNodes) { 135 | var bounds = treeNodes[key].bounds; 136 | if (bounds.left * scale < e.offsetX && e.offsetX < bounds.right * scale && 137 | bounds.top * scale < e.offsetY && e.offsetY < bounds.bottom * scale) { 138 | if (!$("#rnode-" + key).is('.node0')) { 139 | $("#rnode-" + key).addClass("hover"); 140 | $("#tnode-" + key).addClass("hover"); 141 | } 142 | $("#tnode-" + key).parents('.node').removeClass("hover").add($("#tnode-" + key)).addClass( 143 | "expand"); 144 | } 145 | } 146 | displayAttrs(treeNodes[$("#tree .node.hover:first").data('hash')]); 147 | }).mouseleave(function (e) { 148 | $('#tree .node').removeClass("hover expand"); 149 | $('#tree .current').parents('.node').add($('#tree .current')).addClass("expand"); 150 | }).click(function (e) { 151 | $('#screen .node').removeClass("current"); 152 | $('#tree .node').removeClass("current expand"); 153 | for (const key in treeNodes) { 154 | var bounds = treeNodes[key].bounds; 155 | if (bounds.left * scale < e.offsetX && e.offsetX < bounds.right * scale && 156 | bounds.top * scale < e.offsetY && e.offsetY < bounds.bottom * scale) { 157 | if (!$("#rnode-" + key).is('.node0')) { 158 | $("#rnode-" + key).addClass("current"); 159 | $("#tnode-" + key).addClass("current"); 160 | } 161 | $("#rnode-" + key).parents('.node').removeClass("current"); 162 | $("#tnode-" + key).parents('.node').removeClass("current").add($("#tnode-" + key)).addClass( 163 | "expand"); 164 | } 165 | } 166 | displayAttrs(); 167 | }); 168 | 169 | $("#tree") 170 | .mouseleave(function (e) { 171 | $('#tree .node').removeClass("hover"); 172 | displayAttrs(); 173 | }) 174 | .on("mouseover", ".node", function (e) { 175 | e.stopPropagation(); 176 | 177 | $('#screen .node').removeClass("hover"); 178 | $('#tree .node').removeClass("hover"); 179 | $(this).addClass("hover"); 180 | $("#rnode-" + $(this).data("hash")).addClass("hover"); 181 | displayAttrs(treeNodes[$(this).data("hash")]); 182 | }) 183 | .on("click", ".node", function (e) { 184 | e.stopPropagation(); 185 | 186 | $('#screen .node').removeClass("current"); 187 | $('#tree .node').removeClass("current expand"); 188 | $(this).addClass("current"); 189 | $("#rnode-" + $(this).data("hash")).addClass("current"); 190 | $(this).parents('.node').add(this).addClass("expand"); 191 | displayAttrs(treeNodes[$(this).data("hash")]); 192 | }); 193 | }); -------------------------------------------------------------------------------- /app/src/main/assets/jquery-3.4.1.min.js: -------------------------------------------------------------------------------- 1 | /*! jQuery v3.4.1 | (c) JS Foundation and other contributors | jquery.org/license */ 2 | !function(e,t){"use strict";"object"==typeof module&&"object"==typeof module.exports?module.exports=e.document?t(e,!0):function(e){if(!e.document)throw new Error("jQuery requires a window with a document");return t(e)}:t(e)}("undefined"!=typeof window?window:this,function(C,e){"use strict";var t=[],E=C.document,r=Object.getPrototypeOf,s=t.slice,g=t.concat,u=t.push,i=t.indexOf,n={},o=n.toString,v=n.hasOwnProperty,a=v.toString,l=a.call(Object),y={},m=function(e){return"function"==typeof e&&"number"!=typeof e.nodeType},x=function(e){return null!=e&&e===e.window},c={type:!0,src:!0,nonce:!0,noModule:!0};function b(e,t,n){var r,i,o=(n=n||E).createElement("script");if(o.text=e,t)for(r in c)(i=t[r]||t.getAttribute&&t.getAttribute(r))&&o.setAttribute(r,i);n.head.appendChild(o).parentNode.removeChild(o)}function w(e){return null==e?e+"":"object"==typeof e||"function"==typeof e?n[o.call(e)]||"object":typeof e}var f="3.4.1",k=function(e,t){return new k.fn.init(e,t)},p=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g;function d(e){var t=!!e&&"length"in e&&e.length,n=w(e);return!m(e)&&!x(e)&&("array"===n||0===t||"number"==typeof t&&0+~]|"+M+")"+M+"*"),U=new RegExp(M+"|>"),X=new RegExp($),V=new RegExp("^"+I+"$"),G={ID:new RegExp("^#("+I+")"),CLASS:new RegExp("^\\.("+I+")"),TAG:new RegExp("^("+I+"|[*])"),ATTR:new RegExp("^"+W),PSEUDO:new RegExp("^"+$),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+M+"*(even|odd|(([+-]|)(\\d*)n|)"+M+"*(?:([+-]|)"+M+"*(\\d+)|))"+M+"*\\)|)","i"),bool:new RegExp("^(?:"+R+")$","i"),needsContext:new RegExp("^"+M+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+M+"*((?:-\\d)?\\d*)"+M+"*\\)|)(?=[^-]|$)","i")},Y=/HTML$/i,Q=/^(?:input|select|textarea|button)$/i,J=/^h\d$/i,K=/^[^{]+\{\s*\[native \w/,Z=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,ee=/[+~]/,te=new RegExp("\\\\([\\da-f]{1,6}"+M+"?|("+M+")|.)","ig"),ne=function(e,t,n){var r="0x"+t-65536;return r!=r||n?t:r<0?String.fromCharCode(r+65536):String.fromCharCode(r>>10|55296,1023&r|56320)},re=/([\0-\x1f\x7f]|^-?\d)|^-$|[^\0-\x1f\x7f-\uFFFF\w-]/g,ie=function(e,t){return t?"\0"===e?"\ufffd":e.slice(0,-1)+"\\"+e.charCodeAt(e.length-1).toString(16)+" ":"\\"+e},oe=function(){T()},ae=be(function(e){return!0===e.disabled&&"fieldset"===e.nodeName.toLowerCase()},{dir:"parentNode",next:"legend"});try{H.apply(t=O.call(m.childNodes),m.childNodes),t[m.childNodes.length].nodeType}catch(e){H={apply:t.length?function(e,t){L.apply(e,O.call(t))}:function(e,t){var n=e.length,r=0;while(e[n++]=t[r++]);e.length=n-1}}}function se(t,e,n,r){var i,o,a,s,u,l,c,f=e&&e.ownerDocument,p=e?e.nodeType:9;if(n=n||[],"string"!=typeof t||!t||1!==p&&9!==p&&11!==p)return n;if(!r&&((e?e.ownerDocument||e:m)!==C&&T(e),e=e||C,E)){if(11!==p&&(u=Z.exec(t)))if(i=u[1]){if(9===p){if(!(a=e.getElementById(i)))return n;if(a.id===i)return n.push(a),n}else if(f&&(a=f.getElementById(i))&&y(e,a)&&a.id===i)return n.push(a),n}else{if(u[2])return H.apply(n,e.getElementsByTagName(t)),n;if((i=u[3])&&d.getElementsByClassName&&e.getElementsByClassName)return H.apply(n,e.getElementsByClassName(i)),n}if(d.qsa&&!A[t+" "]&&(!v||!v.test(t))&&(1!==p||"object"!==e.nodeName.toLowerCase())){if(c=t,f=e,1===p&&U.test(t)){(s=e.getAttribute("id"))?s=s.replace(re,ie):e.setAttribute("id",s=k),o=(l=h(t)).length;while(o--)l[o]="#"+s+" "+xe(l[o]);c=l.join(","),f=ee.test(t)&&ye(e.parentNode)||e}try{return H.apply(n,f.querySelectorAll(c)),n}catch(e){A(t,!0)}finally{s===k&&e.removeAttribute("id")}}}return g(t.replace(B,"$1"),e,n,r)}function ue(){var r=[];return function e(t,n){return r.push(t+" ")>b.cacheLength&&delete e[r.shift()],e[t+" "]=n}}function le(e){return e[k]=!0,e}function ce(e){var t=C.createElement("fieldset");try{return!!e(t)}catch(e){return!1}finally{t.parentNode&&t.parentNode.removeChild(t),t=null}}function fe(e,t){var n=e.split("|"),r=n.length;while(r--)b.attrHandle[n[r]]=t}function pe(e,t){var n=t&&e,r=n&&1===e.nodeType&&1===t.nodeType&&e.sourceIndex-t.sourceIndex;if(r)return r;if(n)while(n=n.nextSibling)if(n===t)return-1;return e?1:-1}function de(t){return function(e){return"input"===e.nodeName.toLowerCase()&&e.type===t}}function he(n){return function(e){var t=e.nodeName.toLowerCase();return("input"===t||"button"===t)&&e.type===n}}function ge(t){return function(e){return"form"in e?e.parentNode&&!1===e.disabled?"label"in e?"label"in e.parentNode?e.parentNode.disabled===t:e.disabled===t:e.isDisabled===t||e.isDisabled!==!t&&ae(e)===t:e.disabled===t:"label"in e&&e.disabled===t}}function ve(a){return le(function(o){return o=+o,le(function(e,t){var n,r=a([],e.length,o),i=r.length;while(i--)e[n=r[i]]&&(e[n]=!(t[n]=e[n]))})})}function ye(e){return e&&"undefined"!=typeof e.getElementsByTagName&&e}for(e in d=se.support={},i=se.isXML=function(e){var t=e.namespaceURI,n=(e.ownerDocument||e).documentElement;return!Y.test(t||n&&n.nodeName||"HTML")},T=se.setDocument=function(e){var t,n,r=e?e.ownerDocument||e:m;return r!==C&&9===r.nodeType&&r.documentElement&&(a=(C=r).documentElement,E=!i(C),m!==C&&(n=C.defaultView)&&n.top!==n&&(n.addEventListener?n.addEventListener("unload",oe,!1):n.attachEvent&&n.attachEvent("onunload",oe)),d.attributes=ce(function(e){return e.className="i",!e.getAttribute("className")}),d.getElementsByTagName=ce(function(e){return e.appendChild(C.createComment("")),!e.getElementsByTagName("*").length}),d.getElementsByClassName=K.test(C.getElementsByClassName),d.getById=ce(function(e){return a.appendChild(e).id=k,!C.getElementsByName||!C.getElementsByName(k).length}),d.getById?(b.filter.ID=function(e){var t=e.replace(te,ne);return function(e){return e.getAttribute("id")===t}},b.find.ID=function(e,t){if("undefined"!=typeof t.getElementById&&E){var n=t.getElementById(e);return n?[n]:[]}}):(b.filter.ID=function(e){var n=e.replace(te,ne);return function(e){var t="undefined"!=typeof e.getAttributeNode&&e.getAttributeNode("id");return t&&t.value===n}},b.find.ID=function(e,t){if("undefined"!=typeof t.getElementById&&E){var n,r,i,o=t.getElementById(e);if(o){if((n=o.getAttributeNode("id"))&&n.value===e)return[o];i=t.getElementsByName(e),r=0;while(o=i[r++])if((n=o.getAttributeNode("id"))&&n.value===e)return[o]}return[]}}),b.find.TAG=d.getElementsByTagName?function(e,t){return"undefined"!=typeof t.getElementsByTagName?t.getElementsByTagName(e):d.qsa?t.querySelectorAll(e):void 0}:function(e,t){var n,r=[],i=0,o=t.getElementsByTagName(e);if("*"===e){while(n=o[i++])1===n.nodeType&&r.push(n);return r}return o},b.find.CLASS=d.getElementsByClassName&&function(e,t){if("undefined"!=typeof t.getElementsByClassName&&E)return t.getElementsByClassName(e)},s=[],v=[],(d.qsa=K.test(C.querySelectorAll))&&(ce(function(e){a.appendChild(e).innerHTML="",e.querySelectorAll("[msallowcapture^='']").length&&v.push("[*^$]="+M+"*(?:''|\"\")"),e.querySelectorAll("[selected]").length||v.push("\\["+M+"*(?:value|"+R+")"),e.querySelectorAll("[id~="+k+"-]").length||v.push("~="),e.querySelectorAll(":checked").length||v.push(":checked"),e.querySelectorAll("a#"+k+"+*").length||v.push(".#.+[+~]")}),ce(function(e){e.innerHTML="";var t=C.createElement("input");t.setAttribute("type","hidden"),e.appendChild(t).setAttribute("name","D"),e.querySelectorAll("[name=d]").length&&v.push("name"+M+"*[*^$|!~]?="),2!==e.querySelectorAll(":enabled").length&&v.push(":enabled",":disabled"),a.appendChild(e).disabled=!0,2!==e.querySelectorAll(":disabled").length&&v.push(":enabled",":disabled"),e.querySelectorAll("*,:x"),v.push(",.*:")})),(d.matchesSelector=K.test(c=a.matches||a.webkitMatchesSelector||a.mozMatchesSelector||a.oMatchesSelector||a.msMatchesSelector))&&ce(function(e){d.disconnectedMatch=c.call(e,"*"),c.call(e,"[s!='']:x"),s.push("!=",$)}),v=v.length&&new RegExp(v.join("|")),s=s.length&&new RegExp(s.join("|")),t=K.test(a.compareDocumentPosition),y=t||K.test(a.contains)?function(e,t){var n=9===e.nodeType?e.documentElement:e,r=t&&t.parentNode;return e===r||!(!r||1!==r.nodeType||!(n.contains?n.contains(r):e.compareDocumentPosition&&16&e.compareDocumentPosition(r)))}:function(e,t){if(t)while(t=t.parentNode)if(t===e)return!0;return!1},D=t?function(e,t){if(e===t)return l=!0,0;var n=!e.compareDocumentPosition-!t.compareDocumentPosition;return n||(1&(n=(e.ownerDocument||e)===(t.ownerDocument||t)?e.compareDocumentPosition(t):1)||!d.sortDetached&&t.compareDocumentPosition(e)===n?e===C||e.ownerDocument===m&&y(m,e)?-1:t===C||t.ownerDocument===m&&y(m,t)?1:u?P(u,e)-P(u,t):0:4&n?-1:1)}:function(e,t){if(e===t)return l=!0,0;var n,r=0,i=e.parentNode,o=t.parentNode,a=[e],s=[t];if(!i||!o)return e===C?-1:t===C?1:i?-1:o?1:u?P(u,e)-P(u,t):0;if(i===o)return pe(e,t);n=e;while(n=n.parentNode)a.unshift(n);n=t;while(n=n.parentNode)s.unshift(n);while(a[r]===s[r])r++;return r?pe(a[r],s[r]):a[r]===m?-1:s[r]===m?1:0}),C},se.matches=function(e,t){return se(e,null,null,t)},se.matchesSelector=function(e,t){if((e.ownerDocument||e)!==C&&T(e),d.matchesSelector&&E&&!A[t+" "]&&(!s||!s.test(t))&&(!v||!v.test(t)))try{var n=c.call(e,t);if(n||d.disconnectedMatch||e.document&&11!==e.document.nodeType)return n}catch(e){A(t,!0)}return 0":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(e){return e[1]=e[1].replace(te,ne),e[3]=(e[3]||e[4]||e[5]||"").replace(te,ne),"~="===e[2]&&(e[3]=" "+e[3]+" "),e.slice(0,4)},CHILD:function(e){return e[1]=e[1].toLowerCase(),"nth"===e[1].slice(0,3)?(e[3]||se.error(e[0]),e[4]=+(e[4]?e[5]+(e[6]||1):2*("even"===e[3]||"odd"===e[3])),e[5]=+(e[7]+e[8]||"odd"===e[3])):e[3]&&se.error(e[0]),e},PSEUDO:function(e){var t,n=!e[6]&&e[2];return G.CHILD.test(e[0])?null:(e[3]?e[2]=e[4]||e[5]||"":n&&X.test(n)&&(t=h(n,!0))&&(t=n.indexOf(")",n.length-t)-n.length)&&(e[0]=e[0].slice(0,t),e[2]=n.slice(0,t)),e.slice(0,3))}},filter:{TAG:function(e){var t=e.replace(te,ne).toLowerCase();return"*"===e?function(){return!0}:function(e){return e.nodeName&&e.nodeName.toLowerCase()===t}},CLASS:function(e){var t=p[e+" "];return t||(t=new RegExp("(^|"+M+")"+e+"("+M+"|$)"))&&p(e,function(e){return t.test("string"==typeof e.className&&e.className||"undefined"!=typeof e.getAttribute&&e.getAttribute("class")||"")})},ATTR:function(n,r,i){return function(e){var t=se.attr(e,n);return null==t?"!="===r:!r||(t+="","="===r?t===i:"!="===r?t!==i:"^="===r?i&&0===t.indexOf(i):"*="===r?i&&-1:\x20\t\r\n\f]*)[\x20\t\r\n\f]*\/?>(?:<\/\1>|)$/i;function j(e,n,r){return m(n)?k.grep(e,function(e,t){return!!n.call(e,t,e)!==r}):n.nodeType?k.grep(e,function(e){return e===n!==r}):"string"!=typeof n?k.grep(e,function(e){return-1)[^>]*|#([\w-]+))$/;(k.fn.init=function(e,t,n){var r,i;if(!e)return this;if(n=n||q,"string"==typeof e){if(!(r="<"===e[0]&&">"===e[e.length-1]&&3<=e.length?[null,e,null]:L.exec(e))||!r[1]&&t)return!t||t.jquery?(t||n).find(e):this.constructor(t).find(e);if(r[1]){if(t=t instanceof k?t[0]:t,k.merge(this,k.parseHTML(r[1],t&&t.nodeType?t.ownerDocument||t:E,!0)),D.test(r[1])&&k.isPlainObject(t))for(r in t)m(this[r])?this[r](t[r]):this.attr(r,t[r]);return this}return(i=E.getElementById(r[2]))&&(this[0]=i,this.length=1),this}return e.nodeType?(this[0]=e,this.length=1,this):m(e)?void 0!==n.ready?n.ready(e):e(k):k.makeArray(e,this)}).prototype=k.fn,q=k(E);var H=/^(?:parents|prev(?:Until|All))/,O={children:!0,contents:!0,next:!0,prev:!0};function P(e,t){while((e=e[t])&&1!==e.nodeType);return e}k.fn.extend({has:function(e){var t=k(e,this),n=t.length;return this.filter(function(){for(var e=0;e\x20\t\r\n\f]*)/i,he=/^$|^module$|\/(?:java|ecma)script/i,ge={option:[1,""],thead:[1,"","
"],col:[2,"","
"],tr:[2,"","
"],td:[3,"","
"],_default:[0,"",""]};function ve(e,t){var n;return n="undefined"!=typeof e.getElementsByTagName?e.getElementsByTagName(t||"*"):"undefined"!=typeof e.querySelectorAll?e.querySelectorAll(t||"*"):[],void 0===t||t&&A(e,t)?k.merge([e],n):n}function ye(e,t){for(var n=0,r=e.length;nx",y.noCloneChecked=!!me.cloneNode(!0).lastChild.defaultValue;var Te=/^key/,Ce=/^(?:mouse|pointer|contextmenu|drag|drop)|click/,Ee=/^([^.]*)(?:\.(.+)|)/;function ke(){return!0}function Se(){return!1}function Ne(e,t){return e===function(){try{return E.activeElement}catch(e){}}()==("focus"===t)}function Ae(e,t,n,r,i,o){var a,s;if("object"==typeof t){for(s in"string"!=typeof n&&(r=r||n,n=void 0),t)Ae(e,s,n,r,t[s],o);return e}if(null==r&&null==i?(i=n,r=n=void 0):null==i&&("string"==typeof n?(i=r,r=void 0):(i=r,r=n,n=void 0)),!1===i)i=Se;else if(!i)return e;return 1===o&&(a=i,(i=function(e){return k().off(e),a.apply(this,arguments)}).guid=a.guid||(a.guid=k.guid++)),e.each(function(){k.event.add(this,t,i,r,n)})}function De(e,i,o){o?(Q.set(e,i,!1),k.event.add(e,i,{namespace:!1,handler:function(e){var t,n,r=Q.get(this,i);if(1&e.isTrigger&&this[i]){if(r.length)(k.event.special[i]||{}).delegateType&&e.stopPropagation();else if(r=s.call(arguments),Q.set(this,i,r),t=o(this,i),this[i](),r!==(n=Q.get(this,i))||t?Q.set(this,i,!1):n={},r!==n)return e.stopImmediatePropagation(),e.preventDefault(),n.value}else r.length&&(Q.set(this,i,{value:k.event.trigger(k.extend(r[0],k.Event.prototype),r.slice(1),this)}),e.stopImmediatePropagation())}})):void 0===Q.get(e,i)&&k.event.add(e,i,ke)}k.event={global:{},add:function(t,e,n,r,i){var o,a,s,u,l,c,f,p,d,h,g,v=Q.get(t);if(v){n.handler&&(n=(o=n).handler,i=o.selector),i&&k.find.matchesSelector(ie,i),n.guid||(n.guid=k.guid++),(u=v.events)||(u=v.events={}),(a=v.handle)||(a=v.handle=function(e){return"undefined"!=typeof k&&k.event.triggered!==e.type?k.event.dispatch.apply(t,arguments):void 0}),l=(e=(e||"").match(R)||[""]).length;while(l--)d=g=(s=Ee.exec(e[l])||[])[1],h=(s[2]||"").split(".").sort(),d&&(f=k.event.special[d]||{},d=(i?f.delegateType:f.bindType)||d,f=k.event.special[d]||{},c=k.extend({type:d,origType:g,data:r,handler:n,guid:n.guid,selector:i,needsContext:i&&k.expr.match.needsContext.test(i),namespace:h.join(".")},o),(p=u[d])||((p=u[d]=[]).delegateCount=0,f.setup&&!1!==f.setup.call(t,r,h,a)||t.addEventListener&&t.addEventListener(d,a)),f.add&&(f.add.call(t,c),c.handler.guid||(c.handler.guid=n.guid)),i?p.splice(p.delegateCount++,0,c):p.push(c),k.event.global[d]=!0)}},remove:function(e,t,n,r,i){var o,a,s,u,l,c,f,p,d,h,g,v=Q.hasData(e)&&Q.get(e);if(v&&(u=v.events)){l=(t=(t||"").match(R)||[""]).length;while(l--)if(d=g=(s=Ee.exec(t[l])||[])[1],h=(s[2]||"").split(".").sort(),d){f=k.event.special[d]||{},p=u[d=(r?f.delegateType:f.bindType)||d]||[],s=s[2]&&new RegExp("(^|\\.)"+h.join("\\.(?:.*\\.|)")+"(\\.|$)"),a=o=p.length;while(o--)c=p[o],!i&&g!==c.origType||n&&n.guid!==c.guid||s&&!s.test(c.namespace)||r&&r!==c.selector&&("**"!==r||!c.selector)||(p.splice(o,1),c.selector&&p.delegateCount--,f.remove&&f.remove.call(e,c));a&&!p.length&&(f.teardown&&!1!==f.teardown.call(e,h,v.handle)||k.removeEvent(e,d,v.handle),delete u[d])}else for(d in u)k.event.remove(e,d+t[l],n,r,!0);k.isEmptyObject(u)&&Q.remove(e,"handle events")}},dispatch:function(e){var t,n,r,i,o,a,s=k.event.fix(e),u=new Array(arguments.length),l=(Q.get(this,"events")||{})[s.type]||[],c=k.event.special[s.type]||{};for(u[0]=s,t=1;t\x20\t\r\n\f]*)[^>]*)\/>/gi,qe=/\s*$/g;function Oe(e,t){return A(e,"table")&&A(11!==t.nodeType?t:t.firstChild,"tr")&&k(e).children("tbody")[0]||e}function Pe(e){return e.type=(null!==e.getAttribute("type"))+"/"+e.type,e}function Re(e){return"true/"===(e.type||"").slice(0,5)?e.type=e.type.slice(5):e.removeAttribute("type"),e}function Me(e,t){var n,r,i,o,a,s,u,l;if(1===t.nodeType){if(Q.hasData(e)&&(o=Q.access(e),a=Q.set(t,o),l=o.events))for(i in delete a.handle,a.events={},l)for(n=0,r=l[i].length;n")},clone:function(e,t,n){var r,i,o,a,s,u,l,c=e.cloneNode(!0),f=oe(e);if(!(y.noCloneChecked||1!==e.nodeType&&11!==e.nodeType||k.isXMLDoc(e)))for(a=ve(c),r=0,i=(o=ve(e)).length;r").attr(n.scriptAttrs||{}).prop({charset:n.scriptCharset,src:n.url}).on("load error",i=function(e){r.remove(),i=null,e&&t("error"===e.type?404:200,e.type)}),E.head.appendChild(r[0])},abort:function(){i&&i()}}});var Vt,Gt=[],Yt=/(=)\?(?=&|$)|\?\?/;k.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var e=Gt.pop()||k.expando+"_"+kt++;return this[e]=!0,e}}),k.ajaxPrefilter("json jsonp",function(e,t,n){var r,i,o,a=!1!==e.jsonp&&(Yt.test(e.url)?"url":"string"==typeof e.data&&0===(e.contentType||"").indexOf("application/x-www-form-urlencoded")&&Yt.test(e.data)&&"data");if(a||"jsonp"===e.dataTypes[0])return r=e.jsonpCallback=m(e.jsonpCallback)?e.jsonpCallback():e.jsonpCallback,a?e[a]=e[a].replace(Yt,"$1"+r):!1!==e.jsonp&&(e.url+=(St.test(e.url)?"&":"?")+e.jsonp+"="+r),e.converters["script json"]=function(){return o||k.error(r+" was not called"),o[0]},e.dataTypes[0]="json",i=C[r],C[r]=function(){o=arguments},n.always(function(){void 0===i?k(C).removeProp(r):C[r]=i,e[r]&&(e.jsonpCallback=t.jsonpCallback,Gt.push(r)),o&&m(i)&&i(o[0]),o=i=void 0}),"script"}),y.createHTMLDocument=((Vt=E.implementation.createHTMLDocument("").body).innerHTML="
",2===Vt.childNodes.length),k.parseHTML=function(e,t,n){return"string"!=typeof e?[]:("boolean"==typeof t&&(n=t,t=!1),t||(y.createHTMLDocument?((r=(t=E.implementation.createHTMLDocument("")).createElement("base")).href=E.location.href,t.head.appendChild(r)):t=E),o=!n&&[],(i=D.exec(e))?[t.createElement(i[1])]:(i=we([e],t,o),o&&o.length&&k(o).remove(),k.merge([],i.childNodes)));var r,i,o},k.fn.load=function(e,t,n){var r,i,o,a=this,s=e.indexOf(" ");return-1").append(k.parseHTML(e)).find(r):e)}).always(n&&function(e,t){a.each(function(){n.apply(this,o||[e.responseText,t,e])})}),this},k.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(e,t){k.fn[t]=function(e){return this.on(t,e)}}),k.expr.pseudos.animated=function(t){return k.grep(k.timers,function(e){return t===e.elem}).length},k.offset={setOffset:function(e,t,n){var r,i,o,a,s,u,l=k.css(e,"position"),c=k(e),f={};"static"===l&&(e.style.position="relative"),s=c.offset(),o=k.css(e,"top"),u=k.css(e,"left"),("absolute"===l||"fixed"===l)&&-1<(o+u).indexOf("auto")?(a=(r=c.position()).top,i=r.left):(a=parseFloat(o)||0,i=parseFloat(u)||0),m(t)&&(t=t.call(e,n,k.extend({},s))),null!=t.top&&(f.top=t.top-s.top+a),null!=t.left&&(f.left=t.left-s.left+i),"using"in t?t.using.call(e,f):c.css(f)}},k.fn.extend({offset:function(t){if(arguments.length)return void 0===t?this:this.each(function(e){k.offset.setOffset(this,t,e)});var e,n,r=this[0];return r?r.getClientRects().length?(e=r.getBoundingClientRect(),n=r.ownerDocument.defaultView,{top:e.top+n.pageYOffset,left:e.left+n.pageXOffset}):{top:0,left:0}:void 0},position:function(){if(this[0]){var e,t,n,r=this[0],i={top:0,left:0};if("fixed"===k.css(r,"position"))t=r.getBoundingClientRect();else{t=this.offset(),n=r.ownerDocument,e=r.offsetParent||n.documentElement;while(e&&(e===n.body||e===n.documentElement)&&"static"===k.css(e,"position"))e=e.parentNode;e&&e!==r&&1===e.nodeType&&((i=k(e).offset()).top+=k.css(e,"borderTopWidth",!0),i.left+=k.css(e,"borderLeftWidth",!0))}return{top:t.top-i.top-k.css(r,"marginTop",!0),left:t.left-i.left-k.css(r,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){var e=this.offsetParent;while(e&&"static"===k.css(e,"position"))e=e.offsetParent;return e||ie})}}),k.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(t,i){var o="pageYOffset"===i;k.fn[t]=function(e){return _(this,function(e,t,n){var r;if(x(e)?r=e:9===e.nodeType&&(r=e.defaultView),void 0===n)return r?r[i]:e[t];r?r.scrollTo(o?r.pageXOffset:n,o?n:r.pageYOffset):e[t]=n},t,e,arguments.length)}}),k.each(["top","left"],function(e,n){k.cssHooks[n]=ze(y.pixelPosition,function(e,t){if(t)return t=_e(e,n),$e.test(t)?k(e).position()[n]+"px":t})}),k.each({Height:"height",Width:"width"},function(a,s){k.each({padding:"inner"+a,content:s,"":"outer"+a},function(r,o){k.fn[o]=function(e,t){var n=arguments.length&&(r||"boolean"!=typeof e),i=r||(!0===e||!0===t?"margin":"border");return _(this,function(e,t,n){var r;return x(e)?0===o.indexOf("outer")?e["inner"+a]:e.document.documentElement["client"+a]:9===e.nodeType?(r=e.documentElement,Math.max(e.body["scroll"+a],r["scroll"+a],e.body["offset"+a],r["offset"+a],r["client"+a])):void 0===n?k.css(e,t,i):k.style(e,t,n,i)},s,n?e:void 0,n)}})}),k.each("blur focus focusin focusout resize scroll click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup contextmenu".split(" "),function(e,n){k.fn[n]=function(e,t){return 0 { 48 | AccessibilityNodeInfo eventRootNode = super.getRootInActiveWindow(); 49 | if (eventRootNode != null) { 50 | eventRootInActiveWindow = eventRootNode; 51 | } 52 | }).start(); 53 | } 54 | 55 | private void setCurrentActivity(String pkgName, String clsName) { 56 | if (clsName.startsWith("android.view.") || clsName.startsWith("android.widget.")) { 57 | return; 58 | } 59 | try { 60 | ComponentName componentName = new ComponentName(pkgName, clsName); 61 | currentActivity = Global.getMainActivity().getPackageManager().getActivityInfo(componentName, 0).name; 62 | } catch (PackageManager.NameNotFoundException e) { 63 | return; 64 | } 65 | } 66 | 67 | public String getCurrentPackage() { 68 | UiObject root = getRootUiObject(); 69 | return root != null ? root.getPkg() : ""; 70 | } 71 | 72 | public String getCurrentActivity() { 73 | return currentActivity; 74 | } 75 | 76 | @Override 77 | public void onInterrupt() { 78 | 79 | } 80 | 81 | public UiObject getRootUiObject() { 82 | AccessibilityNodeInfo root = eventRootInActiveWindow; 83 | if (root == null) { 84 | root = super.getRootInActiveWindow(); 85 | } 86 | return UiObject.wrap(root); 87 | } 88 | } 89 | -------------------------------------------------------------------------------- /app/src/main/java/com/github/cmzf/androidinspector/Global.java: -------------------------------------------------------------------------------- 1 | package com.github.cmzf.androidinspector; 2 | 3 | import android.app.Application; 4 | import android.os.Handler; 5 | import android.os.HandlerThread; 6 | import android.widget.Toast; 7 | 8 | public class Global { 9 | private static MainActivity mainActivity; 10 | private static Application mainApplication; 11 | private static Handler mainHandler; 12 | private static HandlerThread mainHandlerThread; 13 | 14 | public static Application getMainApplication() { 15 | return mainApplication; 16 | } 17 | 18 | public static void setMainApplication(Application mainApplication) { 19 | Global.mainApplication = mainApplication; 20 | } 21 | 22 | public static MainActivity getMainActivity() { 23 | return mainActivity; 24 | } 25 | 26 | public static void setMainActivity(MainActivity mainActivity) { 27 | Global.mainActivity = mainActivity; 28 | } 29 | 30 | public static AccessibilityService getAccessibilityService() { 31 | return AccessibilityService.getInstance(); 32 | } 33 | 34 | public static ScreenCaptureService getScreenCaptureService() { 35 | return ScreenCaptureService.getInstance(); 36 | } 37 | 38 | public static InspectorServer getInspectorServer() { 39 | return InspectorServer.getInstance(); 40 | } 41 | 42 | public static Handler getMainHandler() { 43 | if (mainHandler == null) { 44 | mainHandler = new Handler(getMainHandlerThread().getLooper()); 45 | } 46 | return mainHandler; 47 | } 48 | 49 | public static HandlerThread getMainHandlerThread() { 50 | if (mainHandlerThread == null) { 51 | mainHandlerThread = new HandlerThread("mainHandlerThread"); 52 | mainHandlerThread.start(); 53 | } 54 | return mainHandlerThread; 55 | } 56 | 57 | public static void toast(String text) { 58 | toast(text, Toast.LENGTH_LONG); 59 | } 60 | 61 | public static void toast(String text, int duration) { 62 | Toast.makeText(getMainActivity(), text, duration).show(); 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /app/src/main/java/com/github/cmzf/androidinspector/InspectorServer.java: -------------------------------------------------------------------------------- 1 | package com.github.cmzf.androidinspector; 2 | 3 | import com.alibaba.fastjson.JSON; 4 | import com.koushikdutta.async.AsyncServer; 5 | import com.koushikdutta.async.http.server.AsyncHttpServer; 6 | import com.koushikdutta.async.http.server.AsyncHttpServerRequest; 7 | import com.koushikdutta.async.http.server.AsyncHttpServerResponse; 8 | import com.koushikdutta.async.http.server.AsyncHttpServerRouter; 9 | 10 | public class InspectorServer { 11 | private static InspectorServer instance; 12 | private AsyncServer asyncServer = new AsyncServer(); 13 | private AsyncHttpServer httpServer = new AsyncHttpServer(); 14 | 15 | private InspectorServer() { 16 | } 17 | 18 | public static InspectorServer getInstance() { 19 | if (instance == null) { 20 | instance = new InspectorServer(); 21 | } 22 | return instance; 23 | } 24 | 25 | public void stopServer() { 26 | httpServer.stop(); 27 | asyncServer.stop(); 28 | } 29 | 30 | private void apiTree(AsyncHttpServerRequest request, AsyncHttpServerResponse response) { 31 | response.setContentType("application/json"); 32 | response.getHeaders().set("Access-Control-Allow-Origin", "*"); 33 | response.send(JSON.toJSONString(Global.getAccessibilityService().getRootUiObject().uiTree())); 34 | response.end(); 35 | } 36 | 37 | private void apiScreen(AsyncHttpServerRequest request, AsyncHttpServerResponse response) { 38 | response.getHeaders().set("Access-Control-Allow-Origin", "*"); 39 | response.send("image/jpg", Global.getScreenCaptureService().getScreenImage()); 40 | response.end(); 41 | } 42 | 43 | public void startServer(int port) { 44 | stopServer(); 45 | httpServer.get("/api/tree", this::apiTree); 46 | httpServer.get("/api/screen", this::apiScreen); 47 | httpServer.get("/.*", this::assetLoader); 48 | httpServer.listen(asyncServer, port); 49 | } 50 | 51 | private void assetLoader(AsyncHttpServerRequest request, AsyncHttpServerResponse response) { 52 | AsyncHttpServerRouter.Asset asset = AsyncHttpServer.getAssetStream(Global.getMainActivity(), request.getPath().substring(1)); 53 | if (asset != null) { 54 | response.sendStream(asset.inputStream, asset.available); 55 | } else { 56 | response.code(404); 57 | } 58 | response.end(); 59 | } 60 | 61 | } 62 | -------------------------------------------------------------------------------- /app/src/main/java/com/github/cmzf/androidinspector/MainActivity.java: -------------------------------------------------------------------------------- 1 | package com.github.cmzf.androidinspector; 2 | 3 | import android.app.PendingIntent; 4 | import android.content.Intent; 5 | import android.graphics.Color; 6 | import android.net.Uri; 7 | import android.os.Bundle; 8 | import android.view.View; 9 | import android.widget.Button; 10 | import android.widget.TextView; 11 | import android.widget.Toast; 12 | 13 | import androidx.annotation.Nullable; 14 | import androidx.appcompat.app.AppCompatActivity; 15 | 16 | import java.text.MessageFormat; 17 | 18 | public class MainActivity extends AppCompatActivity { 19 | 20 | private static final int REQUESR_SCREEN_CAPTURE = 101; 21 | 22 | @Override 23 | protected void onCreate(Bundle savedInstanceState) { 24 | super.onCreate(savedInstanceState); 25 | setContentView(R.layout.activity_main); 26 | setTitle(R.string.activity_name); 27 | 28 | Global.setMainActivity(this); 29 | Global.setMainApplication(this.getApplication()); 30 | 31 | Global.getMainHandler().post(new Runnable() { 32 | @Override 33 | public void run() { 34 | String ip = Utils.getWifiIpAddress(); 35 | String message = MessageFormat.format((ip.equals("") ? "" : "http://{0}:{1}\n- or -\n") + 36 | "adb forward tcp:{1} tcp:{1}\nhttp://localhost:{1}", ip, getServerPortView().getText()); 37 | 38 | runOnUiThread(() -> { 39 | getInspectorUrlView().setText(message); 40 | }); 41 | 42 | Global.getMainHandler().postDelayed(this, 5000); 43 | } 44 | }); 45 | } 46 | 47 | private TextView getInspectorUrlView() { 48 | return this.findViewById(R.id.inspectorUrl); 49 | } 50 | 51 | private TextView getServerPortView() { 52 | return this.findViewById(R.id.serverPort); 53 | } 54 | 55 | private Button getServerTogglerView() { 56 | return this.findViewById(R.id.serverToggler); 57 | } 58 | 59 | public void onClick(View view) { 60 | switch (view.getId()) { 61 | case R.id.inspectorUrl: 62 | copyInspectorUrl(view); 63 | break; 64 | case R.id.serverToggler: 65 | toggleInspectorServer(view); 66 | break; 67 | case R.id.checkVersion: 68 | forkMeOnGithub(view); 69 | break; 70 | } 71 | } 72 | 73 | private void forkMeOnGithub(View view) { 74 | startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://github.com/cmzf/android-inspector"))); 75 | } 76 | 77 | private void delayToggleButton(Button button, String text) { 78 | button.setEnabled(false); 79 | button.setBackgroundColor(Color.parseColor(text.toLowerCase().equals("start") ? "#33CC33" : "#CC3333")); 80 | button.getBackground().setAlpha(100); 81 | 82 | Global.getMainHandler().post(new Runnable() { 83 | private float delay = 3.0f; 84 | private float step = 0.1f; 85 | 86 | @Override 87 | public void run() { 88 | MainActivity.this.runOnUiThread(() -> { 89 | button.setText(String.format("%.1f", delay)); 90 | delay -= step; 91 | if (delay > 0) { 92 | Global.getMainHandler().postDelayed(this, (long) (step * 1000 / 2)); // half for ui update 93 | } else { 94 | Global.getMainHandler().post(() -> runOnUiThread(() -> { 95 | button.setEnabled(true); 96 | button.setText(text); 97 | button.getBackground().setAlpha(255); 98 | })); 99 | } 100 | }); 101 | } 102 | }); 103 | } 104 | 105 | private void toggleInspectorServer(View view) { 106 | Button button = (Button) view; 107 | TextView portView = getServerPortView(); 108 | TextView urlView = getInspectorUrlView(); 109 | 110 | if (button.getText().toString().toLowerCase().equals("start")) { 111 | if (!Global.getScreenCaptureService().hasPermission()) { 112 | Global.getScreenCaptureService().requestProjection(REQUESR_SCREEN_CAPTURE); 113 | return; 114 | } 115 | 116 | button.setEnabled(false); 117 | button.setBackgroundColor(Color.LTGRAY); 118 | 119 | Utils.ensureAccessibilityServiceEnabled(() -> { 120 | bringMeFront(); 121 | 122 | int port; 123 | try { 124 | port = Integer.valueOf(String.valueOf(portView.getText())); 125 | if (port < 1024 || port > 65535) { 126 | throw new Exception(); 127 | } 128 | } catch (Exception e) { 129 | Toast.makeText(this, "port not allowed!", Toast.LENGTH_LONG).show(); 130 | 131 | runOnUiThread(() -> { 132 | button.setEnabled(true); 133 | button.setBackgroundColor(Color.parseColor("#33CC33")); 134 | }); 135 | return; 136 | } 137 | 138 | runOnUiThread(() -> { 139 | portView.setEnabled(false); 140 | urlView.setVisibility(View.VISIBLE); 141 | }); 142 | 143 | 144 | Global.getInspectorServer().startServer(port); 145 | Global.getScreenCaptureService().startProjection(); 146 | 147 | delayToggleButton(button, "STOP"); 148 | }, () -> { 149 | bringMeFront(); 150 | 151 | runOnUiThread(() -> { 152 | toggleInspectorServer(view); 153 | }); 154 | }); 155 | } else { 156 | portView.setEnabled(true); 157 | urlView.setVisibility(View.INVISIBLE); 158 | 159 | Global.getInspectorServer().stopServer(); 160 | Global.getScreenCaptureService().stopProjection(); 161 | 162 | delayToggleButton(button, "START"); 163 | } 164 | } 165 | 166 | private void bringMeFront() { 167 | final Intent intent = new Intent(this, getClass()); 168 | intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP); 169 | final PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0); 170 | try { 171 | pendingIntent.send(); 172 | } catch (PendingIntent.CanceledException e) { 173 | e.printStackTrace(); 174 | } 175 | } 176 | 177 | private void copyInspectorUrl(View view) { 178 | Utils.setClipBoard(getInspectorUrlView().getText()); 179 | Toast.makeText(this, "copied!", Toast.LENGTH_LONG).show(); 180 | } 181 | 182 | @Override 183 | protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) { 184 | super.onActivityResult(requestCode, resultCode, data); 185 | Global.getScreenCaptureService().onActivityResult(requestCode, resultCode, data); 186 | if (requestCode == REQUESR_SCREEN_CAPTURE && resultCode == RESULT_OK) { 187 | toggleInspectorServer(getServerTogglerView()); 188 | } 189 | } 190 | 191 | @Override 192 | protected void onDestroy() { 193 | super.onDestroy(); 194 | Global.getScreenCaptureService().stopProjection(); 195 | } 196 | } 197 | -------------------------------------------------------------------------------- /app/src/main/java/com/github/cmzf/androidinspector/ScreenCaptureService.java: -------------------------------------------------------------------------------- 1 | package com.github.cmzf.androidinspector; 2 | 3 | // https://github.com/mtsahakis/MediaProjectionDemo 4 | 5 | import android.app.Activity; 6 | import android.content.Context; 7 | import android.content.Intent; 8 | import android.graphics.Bitmap; 9 | import android.graphics.PixelFormat; 10 | import android.hardware.display.DisplayManager; 11 | import android.hardware.display.VirtualDisplay; 12 | import android.media.Image; 13 | import android.media.ImageReader; 14 | import android.media.projection.MediaProjection; 15 | import android.media.projection.MediaProjectionManager; 16 | import android.util.DisplayMetrics; 17 | import android.util.Log; 18 | import android.view.Display; 19 | import android.view.OrientationEventListener; 20 | 21 | import java.io.ByteArrayOutputStream; 22 | import java.nio.ByteBuffer; 23 | 24 | 25 | public class ScreenCaptureService { 26 | 27 | private static final String TAG = ScreenCaptureService.class.getCanonicalName(); 28 | private static ScreenCaptureService sInstance; 29 | private final Object mScreenBitmapLock = new Object(); 30 | private MediaProjection mMediaProjection; 31 | private MediaProjectionManager mProjectionManager; 32 | private ImageReader mImageReader; 33 | private Display mDisplay; 34 | private VirtualDisplay mVirtualDisplay; 35 | private OrientationChangeCallback mOrientationChangeCallback; 36 | private int mRequestCode; 37 | private DisplayMetrics mMetrics = new DisplayMetrics(); 38 | private Bitmap mScreenBitmap; 39 | 40 | public static ScreenCaptureService getInstance() { 41 | if (sInstance == null) { 42 | sInstance = new ScreenCaptureService(); 43 | } 44 | return sInstance; 45 | } 46 | 47 | public void startProjection() { 48 | mDisplay = Global.getMainActivity().getWindowManager().getDefaultDisplay(); 49 | 50 | // create virtual display depending on device width / height 51 | createVirtualDisplay(); 52 | 53 | // register orientation change callback 54 | mOrientationChangeCallback = new OrientationChangeCallback(Global.getMainActivity()); 55 | if (mOrientationChangeCallback.canDetectOrientation()) { 56 | mOrientationChangeCallback.enable(); 57 | } 58 | 59 | // register media projection stop callback 60 | mMediaProjection.registerCallback(new MediaProjectionStopCallback(), Global.getMainHandler()); 61 | } 62 | 63 | protected void onActivityResult(int requestCode, int resultCode, Intent data) { 64 | if (requestCode == mRequestCode) { 65 | if (resultCode == Activity.RESULT_OK) { 66 | mMediaProjection = mProjectionManager.getMediaProjection(resultCode, data); 67 | } else { 68 | mProjectionManager = null; 69 | } 70 | } 71 | } 72 | 73 | public void stopProjection() { 74 | Global.getMainHandler().post(() -> { 75 | if (mMediaProjection != null) { 76 | mMediaProjection.stop(); 77 | } 78 | }); 79 | } 80 | 81 | private void createVirtualDisplay() { 82 | mDisplay.getRealMetrics(mMetrics); 83 | 84 | // start capture reader 85 | mImageReader = ImageReader.newInstance(mMetrics.widthPixels, mMetrics.heightPixels, PixelFormat.RGBA_8888, 2); 86 | mVirtualDisplay = mMediaProjection.createVirtualDisplay(TAG, mMetrics.widthPixels, mMetrics.heightPixels, mMetrics.densityDpi, 87 | DisplayManager.VIRTUAL_DISPLAY_FLAG_OWN_CONTENT_ONLY | DisplayManager.VIRTUAL_DISPLAY_FLAG_PUBLIC, 88 | mImageReader.getSurface(), null, Global.getMainHandler()); 89 | mImageReader.setOnImageAvailableListener(new ImageAvailableListener(), Global.getMainHandler()); 90 | } 91 | 92 | public byte[] getScreenImage() { 93 | synchronized (mScreenBitmapLock) { 94 | ByteArrayOutputStream stream = new ByteArrayOutputStream(); 95 | mScreenBitmap.compress(Bitmap.CompressFormat.JPEG, 85, stream); 96 | return stream.toByteArray(); 97 | } 98 | } 99 | 100 | public boolean hasPermission() { 101 | return mMediaProjection != null; 102 | } 103 | 104 | public void requestProjection(int requestCode) { 105 | mRequestCode = requestCode; 106 | 107 | // call for the projection manager 108 | mProjectionManager = (MediaProjectionManager) Global.getMainActivity().getSystemService(Context.MEDIA_PROJECTION_SERVICE); 109 | 110 | Global.getMainActivity().startActivityForResult(mProjectionManager.createScreenCaptureIntent(), mRequestCode); 111 | } 112 | 113 | private class ImageAvailableListener implements ImageReader.OnImageAvailableListener { 114 | @Override 115 | public void onImageAvailable(ImageReader reader) { 116 | Image image = reader.acquireLatestImage(); 117 | if (image != null) { 118 | Image.Plane[] planes = image.getPlanes(); 119 | ByteBuffer buffer = planes[0].getBuffer(); 120 | int pixelStride = planes[0].getPixelStride(); 121 | int rowStride = planes[0].getRowStride(); 122 | int rowPadding = rowStride - pixelStride * mMetrics.widthPixels; 123 | 124 | // create bitmap 125 | Bitmap bitmap = Bitmap.createBitmap(mMetrics.widthPixels + rowPadding / pixelStride, mMetrics.heightPixels, Bitmap.Config.ARGB_8888); 126 | bitmap.copyPixelsFromBuffer(buffer); 127 | synchronized (mScreenBitmapLock) { 128 | // trim black border 129 | mScreenBitmap = Bitmap.createBitmap(bitmap, 0, 0, mMetrics.widthPixels, mMetrics.heightPixels); 130 | } 131 | bitmap.recycle(); 132 | } 133 | 134 | if (image != null) { 135 | image.close(); 136 | } 137 | } 138 | } 139 | 140 | private class OrientationChangeCallback extends OrientationEventListener { 141 | 142 | OrientationChangeCallback(Context context) { 143 | super(context); 144 | } 145 | 146 | @Override 147 | public void onOrientationChanged(int orientation) { 148 | Global.getMainHandler().postDelayed(() -> { 149 | try { 150 | // clean up 151 | if (mVirtualDisplay != null) mVirtualDisplay.release(); 152 | if (mImageReader != null) mImageReader.setOnImageAvailableListener(null, null); 153 | 154 | // re-create virtual display depending on device width / height 155 | createVirtualDisplay(); 156 | } catch (Exception e) { 157 | e.printStackTrace(); 158 | } 159 | }, 2000); 160 | } 161 | } 162 | 163 | private class MediaProjectionStopCallback extends MediaProjection.Callback { 164 | @Override 165 | public void onStop() { 166 | Log.e("ScreenCaptureService", "stopping projection."); 167 | Global.getMainHandler().post(() -> { 168 | if (mVirtualDisplay != null) mVirtualDisplay.release(); 169 | if (mImageReader != null) mImageReader.setOnImageAvailableListener(null, null); 170 | if (mOrientationChangeCallback != null) mOrientationChangeCallback.disable(); 171 | mMediaProjection.unregisterCallback(MediaProjectionStopCallback.this); 172 | mMediaProjection = null; 173 | mProjectionManager = null; 174 | }); 175 | } 176 | } 177 | } -------------------------------------------------------------------------------- /app/src/main/java/com/github/cmzf/androidinspector/UiObject.java: -------------------------------------------------------------------------------- 1 | package com.github.cmzf.androidinspector; 2 | 3 | import android.graphics.Rect; 4 | import android.os.Bundle; 5 | import android.view.accessibility.AccessibilityNodeInfo; 6 | 7 | import java.io.Serializable; 8 | import java.util.ArrayList; 9 | import java.util.List; 10 | import java.util.Objects; 11 | 12 | public class UiObject { 13 | 14 | private static final String TAG = UiObject.class.getCanonicalName(); 15 | 16 | private final AccessibilityNodeInfo mInfo; 17 | 18 | private UiObject(AccessibilityNodeInfo info) { 19 | mInfo = info; 20 | } 21 | 22 | public static UiObject wrap(AccessibilityNodeInfo info) { 23 | if (info == null) { 24 | return null; 25 | } 26 | return new UiObject(info); 27 | } 28 | 29 | public UiObject parent() { 30 | AccessibilityNodeInfo info = mInfo.getParent(); 31 | return info != null ? wrap(info) : null; 32 | } 33 | 34 | @Override 35 | public String toString() { 36 | return "<" + getCls() 37 | + " hash='" + mInfo.hashCode() + "'" 38 | + (!"".equals(getId()) ? " id='" + getId() + "'" : "") 39 | + (!"".equals(getPkg()) ? " pkg='" + getPkg() + "'" : "") 40 | + (!"".equals(getText()) ? " text='" + getText() + "'" : "") 41 | + (!"".equals(getDesc()) ? " desc='" + getDesc() + "'" : "") 42 | + " />"; 43 | } 44 | 45 | public UiTree uiTree() { 46 | return uiTree(this); 47 | } 48 | 49 | public UiTree uiTree(UiObject node) { 50 | ArrayList> treeChildren = new ArrayList<>(); 51 | ArrayList children = node.children(); 52 | for (UiObject child : children) { 53 | treeChildren.add(treeChildren.size(), uiTree(child)); 54 | } 55 | return new UiTree<>(node, treeChildren); 56 | } 57 | 58 | public ArrayList children() { 59 | if (mInfo == null) { 60 | return new ArrayList<>(); 61 | } 62 | int childCount = mInfo.getChildCount(); 63 | ArrayList list = new ArrayList<>(mInfo.getChildCount()); 64 | for (int i = 0; i < childCount; i++) { 65 | AccessibilityNodeInfo info = mInfo.getChild(i); 66 | if (info != null) { 67 | list.add(wrap(info)); 68 | } 69 | } 70 | return list; 71 | } 72 | 73 | public ArrayList descendants() { 74 | return descendants(false); 75 | } 76 | 77 | public ArrayList descendants(boolean withSelf) { 78 | ArrayList result = new ArrayList<>(); 79 | if (withSelf) { 80 | result.add(this); 81 | } 82 | 83 | ArrayList items = children(); 84 | for (UiObject item : items) { 85 | result.addAll(item.descendants(true)); 86 | } 87 | return result; 88 | } 89 | 90 | public String getId() { 91 | return Objects.toString(mInfo.getViewIdResourceName(), ""); 92 | } 93 | 94 | public String getHash() { 95 | return String.valueOf(mInfo.hashCode()); 96 | } 97 | 98 | public String getText() { 99 | if (mInfo.isPassword()) { 100 | return ""; 101 | } 102 | return Objects.toString(mInfo.getText(), ""); 103 | } 104 | 105 | public String getDesc() { 106 | return Objects.toString(mInfo.getContentDescription(), ""); 107 | } 108 | 109 | public String getCls() { 110 | return Objects.toString(mInfo.getClassName(), ""); 111 | } 112 | 113 | public String getPkg() { 114 | return Objects.toString(mInfo.getPackageName(), ""); 115 | } 116 | 117 | public Rect getBounds() { 118 | Rect bounds = new Rect(); 119 | mInfo.getBoundsInScreen(bounds); 120 | return bounds; 121 | } 122 | 123 | public List getExtraData() { 124 | return mInfo.getAvailableExtraData(); 125 | } 126 | 127 | public int getChildCount() { 128 | return mInfo.getChildCount(); 129 | } 130 | 131 | public int getDrawingOrder() { 132 | return mInfo.getDrawingOrder(); 133 | } 134 | 135 | public Bundle getExtras() { 136 | return mInfo.getExtras(); 137 | } 138 | 139 | public String getHintText() { 140 | return Objects.toString(mInfo.getHintText(), ""); 141 | } 142 | 143 | public int getInputType() { 144 | return mInfo.getInputType(); 145 | } 146 | 147 | public int getMaxTextLength() { 148 | return mInfo.getMaxTextLength(); 149 | } 150 | 151 | public int getMovementGranularities() { 152 | return mInfo.getMovementGranularities(); 153 | } 154 | 155 | public int getTextSelectionEnd() { 156 | return mInfo.getTextSelectionEnd(); 157 | } 158 | 159 | public int getTextSelectionStart() { 160 | return mInfo.getTextSelectionStart(); 161 | } 162 | 163 | public int getWindowId() { 164 | return mInfo.getWindowId(); 165 | } 166 | 167 | public boolean isCheckable() { 168 | return mInfo.isCheckable(); 169 | } 170 | 171 | public boolean isChecked() { 172 | return mInfo.isChecked(); 173 | } 174 | 175 | public boolean isClickable() { 176 | return mInfo.isClickable(); 177 | } 178 | 179 | public boolean isEditable() { 180 | return mInfo.isEditable(); 181 | } 182 | 183 | public boolean isEnabled() { 184 | return mInfo.isEnabled(); 185 | } 186 | 187 | public boolean isLongClickable() { 188 | return mInfo.isLongClickable(); 189 | } 190 | 191 | public boolean isMultiLine() { 192 | return mInfo.isMultiLine(); 193 | } 194 | 195 | public boolean isPassword() { 196 | return mInfo.isPassword(); 197 | } 198 | 199 | public boolean isScrollable() { 200 | return mInfo.isScrollable(); 201 | } 202 | 203 | public boolean isSelected() { 204 | return mInfo.isSelected(); 205 | } 206 | 207 | public boolean isVisibleToUser() { 208 | return mInfo.isVisibleToUser(); 209 | } 210 | 211 | public boolean isAccessibilityFocused() { 212 | return mInfo.isAccessibilityFocused(); 213 | } 214 | 215 | public boolean isContentInvalid() { 216 | return mInfo.isContentInvalid(); 217 | } 218 | 219 | public boolean isContextClickable() { 220 | return mInfo.isContextClickable(); 221 | } 222 | 223 | public boolean isDismissable() { 224 | return mInfo.isDismissable(); 225 | } 226 | 227 | public boolean isFocusable() { 228 | return mInfo.isFocusable(); 229 | } 230 | 231 | public boolean isFocused() { 232 | return mInfo.isFocused(); 233 | } 234 | 235 | public boolean isImportantForAccessibility() { 236 | return mInfo.isImportantForAccessibility(); 237 | } 238 | 239 | public boolean isShowingHintText() { 240 | return mInfo.isShowingHintText(); 241 | } 242 | 243 | public static class UiTree implements Serializable { 244 | private T node; 245 | private ArrayList> children; 246 | 247 | public UiTree(T node, ArrayList> children) { 248 | this.node = node; 249 | if (children.size() > 0) { 250 | this.children = children; 251 | } 252 | } 253 | 254 | public T getNode() { 255 | return node; 256 | } 257 | 258 | public ArrayList> getChildren() { 259 | return children; 260 | } 261 | } 262 | } 263 | -------------------------------------------------------------------------------- /app/src/main/java/com/github/cmzf/androidinspector/Utils.java: -------------------------------------------------------------------------------- 1 | package com.github.cmzf.androidinspector; 2 | 3 | import android.app.PendingIntent; 4 | import android.content.ClipData; 5 | import android.content.ClipboardManager; 6 | import android.content.Context; 7 | import android.content.Intent; 8 | import android.net.wifi.WifiInfo; 9 | import android.net.wifi.WifiManager; 10 | import android.provider.Settings; 11 | import android.widget.Toast; 12 | 13 | class Utils { 14 | 15 | private static WifiInfo getWifiInfo() { 16 | WifiManager wifiManager = (WifiManager) Global.getMainActivity().getSystemService(Context.WIFI_SERVICE); 17 | return wifiManager.getConnectionInfo(); 18 | } 19 | 20 | public static String getWifiIpAddress() { 21 | final int ip = getWifiInfo().getIpAddress(); 22 | if (ip == 0) { 23 | return ""; 24 | } 25 | return String.format("%d.%d.%d.%d", (ip & 0xff), (ip >> 8 & 0xff), (ip >> 16 & 0xff), (ip >> 24 & 0xff)); 26 | } 27 | 28 | public static void setClipBoard(CharSequence text) { 29 | ClipboardManager clipboard = (ClipboardManager) Global.getMainActivity().getSystemService(Context.CLIPBOARD_SERVICE); 30 | ClipData clip = ClipData.newPlainText(Global.getMainApplication().getPackageName(), text); 31 | clipboard.setPrimaryClip(clip); 32 | } 33 | 34 | public static void ensureAccessibilityServiceEnabled(Runnable enterCallback, Runnable exitCallback) { 35 | long checkInterval = 2000; 36 | String appName = Global.getMainActivity().getString(R.string.app_name); 37 | 38 | final Runnable exitWrapper = new Runnable() { 39 | @Override 40 | public void run() { 41 | if (Global.getAccessibilityService() == null) { 42 | Global.toast("accessibility disconnected"); 43 | exitCallback.run(); 44 | } else { 45 | Global.getMainHandler().postDelayed(this, checkInterval); 46 | } 47 | } 48 | }; 49 | final Runnable enterWrapper = new Runnable() { 50 | @Override 51 | public void run() { 52 | if (Global.getAccessibilityService() != null) { 53 | enterCallback.run(); 54 | Global.getMainHandler().postDelayed(exitWrapper, checkInterval); 55 | } else { 56 | Global.getMainHandler().postDelayed(this, checkInterval); 57 | Global.toast("turn on accessibility for " + appName, Toast.LENGTH_SHORT); 58 | } 59 | } 60 | }; 61 | 62 | long enterDelay = 0; 63 | if (Global.getAccessibilityService() == null) { 64 | Global.toast("need accessibility service"); 65 | Global.getMainHandler().postDelayed(Utils::gotoAccessibilityService, 2000); 66 | enterDelay = 3000; 67 | } 68 | Global.getMainHandler().postDelayed(enterWrapper, enterDelay); 69 | } 70 | 71 | private static void gotoAccessibilityService() { 72 | final Intent intent = new Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 73 | final PendingIntent pendingIntent = PendingIntent.getActivity(Global.getMainActivity(), 0, intent, 0); 74 | try { 75 | pendingIntent.send(); 76 | } catch (PendingIntent.CanceledException e) { 77 | e.printStackTrace(); 78 | } 79 | } 80 | 81 | } 82 | -------------------------------------------------------------------------------- /app/src/main/res/drawable-v24/ic_launcher_foreground.xml: -------------------------------------------------------------------------------- 1 | 7 | 12 | 13 | 19 | 22 | 25 | 26 | 27 | 28 | 34 | 35 | -------------------------------------------------------------------------------- /app/src/main/res/drawable/ic_launcher_background.xml: -------------------------------------------------------------------------------- 1 | 2 | 7 | 10 | 15 | 20 | 25 | 30 | 35 | 40 | 45 | 50 | 55 | 60 | 65 | 70 | 75 | 80 | 85 | 90 | 95 | 100 | 105 | 110 | 115 | 120 | 125 | 130 | 135 | 140 | 145 | 150 | 155 | 160 | 165 | 170 | 171 | -------------------------------------------------------------------------------- /app/src/main/res/layout/activity_main.xml: -------------------------------------------------------------------------------- 1 | 2 | 8 | 9 | 27 | 28 | 43 | 44 | 60 | 61 | 77 | 78 | 95 | 96 |