diff --git a/README.md b/README.md
index 9b747f02..b9589c1f 100644
--- a/README.md
+++ b/README.md
@@ -26,6 +26,7 @@
### 简介
* Android 平台支持无障碍服务的 JavaScript 自动化工具
+* 需要 [Android 7.0](https://zh.wikipedia.org/wiki/Android_Nougat) (`API 24`) 及以上
* 复刻 (Fork) 自 [hyb1996/Auto.js](https://github.com/hyb1996/Auto.js)
******
@@ -53,7 +54,7 @@
* 支持将脚本文件或项目打包为 APK 文件
* 支持利用 Root 权限扩展功能 (屏幕点击/滑动/录制/Shell)
* 支持作为 Tasker 插件使用
-* 支持与 VSCode 连接并进行桌面开发 (需要 [AutoJs6-VSCode-Ext](https://github.com/SuperMonster003/AutoJs6-VSCode-Ext) 插件)
+* 支持与 VSCode 连接并进行桌面开发 (需要 [AutoJs6-VSCode-Extension](https://github.com/SuperMonster003/AutoJs6-VSCode-Extension) 插件)
******
@@ -61,7 +62,10 @@
******
-* Rhino 引擎由 [v1.7.7.2](https://github.com/mozilla/rhino/releases/tag/Rhino1_7_7_2_Release) 升级至 [v1.7.14 (SNAPSHOT)](https://github.com/mozilla/rhino/)
+* VSCode 插件支持客户端 (LAN) 及服务端 (LAN/ADB) 连接方式
+
+
+* Rhino 引擎由 [v1.7.7.2](https://github.com/mozilla/rhino/releases/tag/Rhino1_7_7_2_Release) 升级至 [v1.7.14](https://github.com/mozilla/rhino/)
* 支持 [Object.values()](https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Object/values)
@@ -99,6 +103,25 @@
[comment]: <> "Version history only shows last 3 versions"
+# v6.0.2
+
+###### 2022/02/05
+
+* `新增` images.bilateralFilter() 双边滤波图像处理方法
+* `修复` 多次调用 toast 只生效最后一次调用的问题
+* `修复` toast.dismiss() 可能无效的问题
+* `修复` 客户端模式及服务端模式开关可能无法正常工作的问题
+* `修复` 客户端模式及服务端模式开关状态不能正常刷新的问题
+* `修复` Android 7 解析 UI 模式 text 元素异常 (Ref to TonyJiangWJ) _[`issue #4`](https://github.com/SuperMonster003/AutoJs6/issues/4)_
+* `优化` 忽略 sleep() 的 ScriptInterruptedException 异常
+* `优化` 附加 Androidx AppCompat (Legacy) 版本 1.0.2
+* `优化` 升级 Androidx AppCompat 版本 1.4.0 -> 1.4.1
+* `优化` 升级 Androidx Preference 版本 1.1.1 -> 1.2.0
+* `优化` 升级 Okhttp3 版本 3.10.0 -> 5.0.0-alpha.3 -> 5.0.0-alpha.4
+* `优化` 升级 Android Material 版本 1.6.0-alpha01 -> 1.6.0-alpha02
+* `优化` 升级 Android Gradle 插件版本 7.2.0-alpha06 -> 7.2.0-beta01
+* `优化` 升级 Gradle 发行版本 7.3.3 -> 7.4-rc-2
+
# v6.0.1
###### 2022/01/01
@@ -190,11 +213,11 @@
******
-* [AutoJs6-VSCode-Ext](https://github.com/SuperMonster003/AutoJs6-VSCode-Ext) { author: [SuperMonster003](https://github.com/SuperMonster003) }
+* [AutoJs6-VSCode-Extension](https://github.com/SuperMonster003/AutoJs6-VSCode-Extension) { author: [SuperMonster003](https://github.com/SuperMonster003) }
- `适用于 VSCode 的桌面开发插件 (二次开发项目)`
* [AutoX](https://github.com/kkevsekk1/AutoX) { author: [kkevsekk1](https://github.com/kkevsekk1) }
- `安卓平台 JavaScript 自动化工具 (二次开发项目)`
-[//]: # (* [Auto.js-TypeScript-Declarations](https://github.com/SuperMonster003/Auto.js-TypeScript-Declarations) { author: [SuperMonster003](https://github.com/SuperMonster003) })
-[//]: # ( - `Auto.js 声明文件 (.d.ts)`)
+[comment]: <> (* [Auto.js-TypeScript-Declarations](https://github.com/SuperMonster003/Auto.js-TypeScript-Declarations) { author: [SuperMonster003](https://github.com/SuperMonster003) })
+[comment]: <> ( - `Auto.js 声明文件 (.d.ts)`)
diff --git a/app/build.gradle b/app/build.gradle
index 21f48c8e..13fdffe5 100644
--- a/app/build.gradle
+++ b/app/build.gradle
@@ -1,16 +1,12 @@
plugins {
- id "com.android.application"
- id "com.jakewharton.butterknife"
- id "kotlin-android"
- id "kotlin-kapt"
+ id 'com.android.application'
+ id 'com.jakewharton.butterknife'
+ id 'kotlin-android'
+ id 'kotlin-kapt'
}
-def annotationsVer = "4.8.0"
-def butterKnifeVer = "10.2.3"
-def leakcanaryVer = "2.7"
-
def properties = new Properties()
-def propFile = new File("sign.properties")
+def propFile = new File('sign.properties')
def isPropFileExists = propFile.exists()
isPropFileExists && properties.load(new FileInputStream(propFile))
@@ -22,32 +18,32 @@ tasks.withType(org.jetbrains.kotlin.gradle.tasks.KotlinCompile).all {
}
// tasks.withType(JavaCompile) {
-// options.compilerArgs << "-Xlint:deprecation" << "-Xlint:unchecked"
+// options.compilerArgs << '-Xlint:deprecation' << '-Xlint:unchecked'
// }
android {
signingConfigs {
isPropFileExists && release {
- storeFile file(properties["storeFile"])
- keyPassword properties["keyPassword"]
- keyAlias properties["keyAlias"]
- storePassword properties["storePassword"]
+ storeFile file(properties['storeFile'])
+ keyPassword properties['keyPassword']
+ keyAlias properties['keyAlias']
+ storePassword properties['storePassword']
}
}
- compileSdkVersion versions.compile
+ compileSdkVersion versions.project.compile
defaultConfig {
- applicationId "org.autojs.autojs"
- minSdkVersion versions.mini
- targetSdkVersion versions.target
- versionCode versions.appVersionCode
- versionName versions.appVersionName
- testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
+ applicationId 'org.autojs.autojs'
+ minSdkVersion versions.project.mini
+ targetSdkVersion versions.project.target
+ versionCode versions.project.appVersionCode
+ versionName versions.project.appVersionName
+ testInstrumentationRunner 'androidx.test.runner.AndroidJUnitRunner'
multiDexEnabled true
javaCompileOptions {
annotationProcessorOptions {
arguments = [
- "resourcePackageName": applicationId,
- "androidManifestFile": "$projectDir/src/main/AndroidManifest.xml".toString()
+ 'resourcePackageName': applicationId,
+ 'androidManifestFile': "$projectDir/src/main/AndroidManifest.xml".toString()
]
}
}
@@ -56,7 +52,7 @@ android {
debug {
shrinkResources false
minifyEnabled false
- proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
+ proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
if (isPropFileExists) {
signingConfig signingConfigs.release
}
@@ -68,7 +64,7 @@ android {
release {
shrinkResources false
minifyEnabled false
- proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
+ proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
if (isPropFileExists) {
signingConfig signingConfigs.release
}
@@ -77,17 +73,17 @@ android {
compileOptions {
sourceCompatibility JavaVersion.VERSION_16
targetCompatibility JavaVersion.VERSION_16
- encoding = "utf-8"
+ encoding = 'utf-8'
}
lintOptions {
abortOnError false
- disable "MissingTranslation"
- disable "ExtraTranslation"
+ disable 'MissingTranslation'
+ disable 'ExtraTranslation'
}
configurations.all {
- resolutionStrategy.force "com.google.code.findbugs:jsr305:3.0.1"
+ resolutionStrategy.force 'com.google.code.findbugs:jsr305:3.0.1'
}
- flavorDimensions "channel"
+ flavorDimensions 'channel'
splits {
// Configures multiple APKs based on ABI.
abi {
@@ -101,7 +97,7 @@ android {
reset()
// Specifies a list of ABIs that Gradle should create APKs for.
- include "armeabi-v7a"
+ include 'x86', 'armeabi-v7a'
// Specifies that we do not want to also generate a universal APK that includes all ABIs.
universalApk false
@@ -109,14 +105,14 @@ android {
}
productFlavors {
common {
- buildConfigField "String", "CHANNEL", "\"common\""
- buildConfigField "String", "APP_SINCE_DATE", "\"${versions.appSinceDate}\""
+ buildConfigField 'String', 'CHANNEL', '"common"'
+ buildConfigField 'String', 'APP_SINCE_DATE', "\"${versions.project.appSinceDate}\""
}
}
applicationVariants.all { variant ->
variant.mergeAssetsProvider.configure {
doLast {
- delete(fileTree(dir: outputDir, includes: ["declarations/**"]))
+ delete(fileTree(dir: outputDir, includes: ['declarations/**']))
}
}
}
@@ -128,103 +124,94 @@ repositories {
dependencies {
// JUnit
- testImplementation "junit:junit:${junitVer}"
+ testImplementation "junit:junit:${versions.junit}"
// LeakCanary
- debugImplementation "com.squareup.leakcanary:leakcanary-android:${leakcanaryVer}"
+ debugImplementation "com.squareup.leakcanary:leakcanary-android:${versions.leakcanary}"
// Kotlin
- implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:1.6.0-native-mt"
+ implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.6.0-native-mt'
// Android Annotations
- kapt "org.androidannotations:androidannotations:${annotationsVer}"
- implementation "org.androidannotations:androidannotations-api:${annotationsVer}"
+ kapt "org.androidannotations:androidannotations:${versions.annotations}"
+ implementation "org.androidannotations:androidannotations-api:${versions.annotations}"
// ButterKnife
- kapt "com.jakewharton:butterknife-compiler:${butterKnifeVer}"
- implementation "com.jakewharton:butterknife:${butterKnifeVer}"
+ kapt "com.jakewharton:butterknife-compiler:${versions.butterKnife}"
+ implementation "com.jakewharton:butterknife:${versions.butterKnife}"
// Android supports
- implementation "androidx.appcompat:appcompat:1.4.0"
- implementation "androidx.cardview:cardview:1.0.0"
- implementation "com.google.android.material:material:1.6.0-alpha01"
- implementation "androidx.multidex:multidex:2.0.1"
-
- // Material Dialogs
- implementation "com.afollestad.material-dialogs:core:0.9.6.0"
+ implementation 'androidx.cardview:cardview:1.0.0'
+ implementation 'androidx.multidex:multidex:2.0.1'
// SwipeRefreshLayout
- implementation "androidx.swiperefreshlayout:swiperefreshlayout:1.1.0"
+ implementation 'androidx.swiperefreshlayout:swiperefreshlayout:1.1.0'
// Common Markdown
- implementation "com.github.atlassian:commonmark-java:commonmark-parent-0.9.0"
+ implementation 'com.github.atlassian:commonmark-java:commonmark-parent-0.9.0'
// Android issue reporter (a github issue reporter)
- implementation "com.heinrichreimersoftware:android-issue-reporter:1.3.1"
+ implementation 'com.heinrichreimersoftware:android-issue-reporter:1.3.1'
// MultiLevelListView
- implementation "com.github.hyb1996:android-multi-level-listview:1.1"
+ implementation 'com.github.hyb1996:android-multi-level-listview:1.1'
// Licenses Dialog
- implementation "de.psdev.licensesdialog:licensesdialog:2.2.0"
+ implementation 'de.psdev.licensesdialog:licensesdialog:2.2.0'
// Expandable RecyclerView
- implementation "com.bignerdranch.android:expandablerecyclerview:3.0.0-RC1"
+ implementation 'com.bignerdranch.android:expandablerecyclerview:3.0.0-RC1'
// FlexibleDivider
- implementation "com.yqritc:recyclerview-flexibledivider:1.4.0"
+ implementation 'com.yqritc:recyclerview-flexibledivider:1.4.0'
// AVLoadingView
- implementation "com.wang.avi:library:2.1.3"
+ implementation 'com.wang.avi:library:2.1.3'
// Commons Lang
- implementation "org.apache.commons:commons-lang3:3.12.0"
+ implementation 'org.apache.commons:commons-lang3:3.12.0'
// Expandable RecyclerView
- implementation "com.thoughtbot:expandablerecyclerview:1.3"
+ implementation 'com.thoughtbot:expandablerecyclerview:1.3'
- implementation "com.github.hyb1996:Auto.js-ApkBuilder:1.0.1"
+ implementation 'com.github.hyb1996:Auto.js-ApkBuilder:1.0.1'
// RxJava
- implementation "io.reactivex.rxjava2:rxjava:2.2.21"
- implementation "io.reactivex.rxjava2:rxandroid:2.1.1"
+ implementation 'io.reactivex.rxjava2:rxjava:2.2.21'
+ implementation 'io.reactivex.rxjava2:rxandroid:2.1.1'
// Retrofit
- implementation "com.squareup.retrofit2:retrofit:2.9.0"
- implementation "com.squareup.retrofit2:converter-gson:2.9.0"
- implementation "com.jakewharton.retrofit:retrofit2-rxjava2-adapter:1.0.0"
- implementation "com.jakewharton.retrofit:retrofit2-kotlin-coroutines-adapter:0.9.2"
+ implementation 'com.squareup.retrofit2:retrofit:2.9.0'
+ implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
+ implementation 'com.jakewharton.retrofit:retrofit2-rxjava2-adapter:1.0.0'
+ implementation 'com.jakewharton.retrofit:retrofit2-kotlin-coroutines-adapter:0.9.2'
// Glide
- kapt "com.github.bumptech.glide:compiler:4.12.0"
- implementation "com.github.bumptech.glide:glide:4.12.0"
+ kapt "com.github.bumptech.glide:compiler:${versions.glide}"
// Joda Time
- implementation "joda-time:joda-time:2.10.13"
+ implementation 'joda-time:joda-time:2.10.13'
// Tasker Plugin
- implementation "com.twofortyfouram:android-plugin-client-sdk-for-locale:4.0.3"
+ implementation 'com.twofortyfouram:android-plugin-client-sdk-for-locale:4.0.3'
// Flurry
- implementation "com.flurry.android:analytics:13.1.0"
-
- // Material Dialogs
- implementation "com.afollestad.material-dialogs:commons:0.9.6.0"
+ implementation 'com.flurry.android:analytics:13.1.0'
// Android Job
- implementation "com.evernote:android-job:1.4.2"
+ implementation 'com.evernote:android-job:1.4.2'
// Extracted from com.github.hyb1996:MutableTheme:1.0.0
- implementation "com.jrummyapps:colorpicker:2.1.7"
- implementation "androidx.recyclerview:recyclerview:1.2.1"
- implementation "com.github.ozodrukh:CircularReveal:2.0.1"
+ implementation 'com.jrummyapps:colorpicker:2.1.7'
+ implementation 'androidx.recyclerview:recyclerview:1.2.1'
+ implementation 'com.github.ozodrukh:CircularReveal:2.0.1'
// Bugly
- implementation project(":libs:com.tencent.bugly.crashreport-2.6.6")
+ implementation project(':libs:com.tencent.bugly.crashreport-2.6.6')
- implementation project(":automator")
- implementation project(":common")
- implementation project(":autojs")
+ implementation project(':automator')
+ implementation project(':common')
+ implementation project(':autojs')
}
java {
diff --git a/app/src/main/assets/doc/CHANGELOG.md b/app/src/main/assets/doc/CHANGELOG.md
index eb524821..17fb8a35 100644
--- a/app/src/main/assets/doc/CHANGELOG.md
+++ b/app/src/main/assets/doc/CHANGELOG.md
@@ -4,6 +4,25 @@
******
+# v6.0.2
+
+###### 2022/02/05
+
+* `新增` images.bilateralFilter() 双边滤波图像处理方法
+* `修复` 多次调用 toast 只生效最后一次调用的问题
+* `修复` toast.dismiss() 可能无效的问题
+* `修复` 客户端模式及服务端模式开关可能无法正常工作的问题
+* `修复` 客户端模式及服务端模式开关状态不能正常刷新的问题
+* `修复` Android 7 解析 UI 模式 text 元素异常 (Ref to TonyJiangWJ) _[`issue #4`](https://github.com/SuperMonster003/AutoJs6/issues/4)_
+* `优化` 忽略 sleep() 的 ScriptInterruptedException 异常
+* `优化` 附加 Androidx AppCompat (Legacy) 版本 1.0.2
+* `优化` 升级 Androidx AppCompat 版本 1.4.0 -> 1.4.1
+* `优化` 升级 Androidx Preference 版本 1.1.1 -> 1.2.0
+* `优化` 升级 Okhttp3 版本 3.10.0 -> 5.0.0-alpha.3 -> 5.0.0-alpha.4
+* `优化` 升级 Android Material 版本 1.6.0-alpha01 -> 1.6.0-alpha02
+* `优化` 升级 Android Gradle 插件版本 7.2.0-alpha06 -> 7.2.0-beta01
+* `优化` 升级 Gradle 发行版本 7.3.3 -> 7.4-rc-2
+
# v6.0.1
###### 2022/01/01
diff --git a/app/src/main/assets/docs/all.html b/app/src/main/assets/docs/all.html
index b9861522..44a23296 100644
--- a/app/src/main/assets/docs/all.html
+++ b/app/src/main/assets/docs/all.html
@@ -961,7 +961,7 @@
如果想要在电脑而不是手机上开发Auto.js,可以使用VS Code以及相应的Auto.js插件使得在电脑上编辑的脚本能推送到手机运行,参见Auto.js-VSCode-Extension。
本文档的章节大致上是以模块来分的,总体上可以分成"自动操作"类模块(控件操作、触摸模拟、按键模拟等)和其他类模块(设备、应用、界面等)。
-"自动操作"的部分又可以大致分为基于控件和基于坐标的操作。基于坐标的操作是传统按键精灵、触摸精灵等脚本软件采用的方式,通过屏幕坐标来点击、长按指定位置模拟操作,从而到达目的。例如click(100, 200), press(100, 200, 500)等。这种方式在游戏类脚本中比较有可行性,结合找图找色、坐标放缩功能也能达到较好的兼容性。但是,这种方式对一般软件脚本却难以达到想要的效果,而且这种方式需要安卓7.0版本以上或者root权限才能执行。所以对于一般软件脚本(例如批量添加联系人、自动提取短信验证码等等),我们采用基于控件的模拟操作方式,结合通知事情、按键事情等达成更好的工作流。这些部分的文档参见基于控件的操作和基于坐标的操作。
+"自动操作"的部分又可以大致分为基于控件和基于坐标的操作。基于坐标的操作是传统按键精灵、触摸精灵等脚本软件采用的方式,通过屏幕坐标来点击、长按指定位置模拟操作,从而到达目的。例如click(100, 200), press(100, 200, 500)等。这种方式在游戏类脚本中比较有可行性,结合找图找色、坐标放缩功能也能达到较好的兼容性。但是,这种方式对一般软件脚本却难以达到想要的效果,而且这种方式需要root权限才能执行。所以对于一般软件脚本(例如批量添加联系人、自动提取短信验证码等等),我们采用基于控件的模拟操作方式,结合通知事情、按键事情等达成更好的工作流。这些部分的文档参见基于控件的操作和基于坐标的操作。
其他部分主要包括:
- app: 应用。启动应用,卸载应用,使用应用查看、编辑文件、访问网页,发送应用间广播等。
diff --git a/app/src/main/assets/docs/overview.html b/app/src/main/assets/docs/overview.html
index 62da9798..6f7a5020 100644
--- a/app/src/main/assets/docs/overview.html
+++ b/app/src/main/assets/docs/overview.html
@@ -88,7 +88,7 @@
- 如果想要在电脑而不是手机上开发Auto.js,可以使用VS Code以及相应的Auto.js插件使得在电脑上编辑的脚本能推送到手机运行,参见Auto.js-VSCode-Extension。
本文档的章节大致上是以模块来分的,总体上可以分成"自动操作"类模块(控件操作、触摸模拟、按键模拟等)和其他类模块(设备、应用、界面等)。
-"自动操作"的部分又可以大致分为基于控件和基于坐标的操作。基于坐标的操作是传统按键精灵、触摸精灵等脚本软件采用的方式,通过屏幕坐标来点击、长按指定位置模拟操作,从而到达目的。例如click(100, 200), press(100, 200, 500)等。这种方式在游戏类脚本中比较有可行性,结合找图找色、坐标放缩功能也能达到较好的兼容性。但是,这种方式对一般软件脚本却难以达到想要的效果,而且这种方式需要安卓7.0版本以上或者root权限才能执行。所以对于一般软件脚本(例如批量添加联系人、自动提取短信验证码等等),我们采用基于控件的模拟操作方式,结合通知事情、按键事情等达成更好的工作流。这些部分的文档参见基于控件的操作和基于坐标的操作。
+"自动操作"的部分又可以大致分为基于控件和基于坐标的操作。基于坐标的操作是传统按键精灵、触摸精灵等脚本软件采用的方式,通过屏幕坐标来点击、长按指定位置模拟操作,从而到达目的。例如click(100, 200), press(100, 200, 500)等。这种方式在游戏类脚本中比较有可行性,结合找图找色、坐标放缩功能也能达到较好的兼容性。但是,这种方式对一般软件脚本却难以达到想要的效果,而且这种方式需要root权限才能执行。所以对于一般软件脚本(例如批量添加联系人、自动提取短信验证码等等),我们采用基于控件的模拟操作方式,结合通知事情、按键事情等达成更好的工作流。这些部分的文档参见基于控件的操作和基于坐标的操作。
其他部分主要包括:
- app: 应用。启动应用,卸载应用,使用应用查看、编辑文件、访问网页,发送应用间广播等。
diff --git a/app/src/main/java/org/autojs/autojs/autojs/AutoJs.java b/app/src/main/java/org/autojs/autojs/autojs/AutoJs.java
index 15e56062..ea86c983 100644
--- a/app/src/main/java/org/autojs/autojs/autojs/AutoJs.java
+++ b/app/src/main/java/org/autojs/autojs/autojs/AutoJs.java
@@ -32,6 +32,9 @@ import org.autojs.autojs.ui.floating.layoutinspector.LayoutHierarchyFloatyWindow
import org.autojs.autojs.ui.log.LogActivity_;
import org.autojs.autojs.ui.settings.SettingsActivity_;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+
/**
* Created by Stardust on 2017/4/2.
@@ -41,11 +44,13 @@ public class AutoJs extends com.stardust.autojs.AutoJs {
private static AutoJs instance;
+ // @Thank to Zen2H
+ private final ExecutorService printExecutor = Executors.newSingleThreadExecutor();
+
public static AutoJs getInstance() {
return instance;
}
-
public synchronized static void initInstance(Application application) {
if (instance != null) {
return;
@@ -108,11 +113,18 @@ public class AutoJs extends com.stardust.autojs.AutoJs {
@Override
protected GlobalConsole createGlobalConsole() {
+ DevPluginService devPluginService = DevPluginService.getInstance();
return new GlobalConsole(getUiHandler()) {
@Override
public String println(int level, CharSequence charSequence) {
String log = super.println(level, charSequence);
- new Thread(() -> DevPluginService.getInstance().print(log)).start();
+
+ // FIXME by SuperMonster003 on Feb 2, 2022
+ // ! When running in 'ui' thread (`ui.run`, `ui.post`),
+ // ! android.os.NetworkOnMainThreadException may happen.
+ // ! Further more, dunno if a thread executor is a good idea.
+ printExecutor.submit(() -> devPluginService.print(log));
+
return log;
}
};
diff --git a/app/src/main/java/org/autojs/autojs/pluginclient/DevPluginService.java b/app/src/main/java/org/autojs/autojs/pluginclient/DevPluginService.java
index c42694a7..d0ff97e1 100644
--- a/app/src/main/java/org/autojs/autojs/pluginclient/DevPluginService.java
+++ b/app/src/main/java/org/autojs/autojs/pluginclient/DevPluginService.java
@@ -80,7 +80,7 @@ public class DevPluginService {
private volatile JsonSocketClient mJsonSocketClient;
private volatile JsonSocketServer mJsonSocketServer;
- private volatile ServerSocket mAJServerSocket;
+ private volatile ServerSocket mServerSocket;
public DevPluginService() {
File cache = new File(GlobalAppContext.get().getCacheDir(), "remote_project");
@@ -97,6 +97,11 @@ public class DevPluginService {
return mJsonSocketServer;
}
+ @Nullable
+ public ServerSocket getServerSocket() {
+ return mServerSocket;
+ }
+
@AnyThread
public Observable connectToRemoteServer(String host) {
int port = Port.PC_SERVER;
@@ -135,11 +140,11 @@ public class DevPluginService {
.doOnNext(jsonSocketServer -> {
try {
mJsonSocketServer = jsonSocketServer;
- mAJServerSocket = jsonSocketServer.getServerSocket();
- if (mAJServerSocket != null) {
+ mServerSocket = jsonSocketServer.getServerSocket();
+ if (mServerSocket != null) {
jsonSocketServer
.setStateConnected()
- .setSocket(mAJServerSocket.accept())
+ .setSocket(mServerSocket.accept())
.subscribeMessage()
.monitorMessage()
.sayHello();
diff --git a/app/src/main/java/org/autojs/autojs/pluginclient/JsonSocket.java b/app/src/main/java/org/autojs/autojs/pluginclient/JsonSocket.java
index 286c3676..1e6bb3f0 100644
--- a/app/src/main/java/org/autojs/autojs/pluginclient/JsonSocket.java
+++ b/app/src/main/java/org/autojs/autojs/pluginclient/JsonSocket.java
@@ -21,7 +21,6 @@ import com.stardust.autojs.runtime.api.Device;
import com.stardust.util.MapBuilder;
import org.autojs.autojs.BuildConfig;
-import org.autojs.autojs.tool.IOTool;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
@@ -196,13 +195,12 @@ abstract public class JsonSocket extends Socket {
public void monitorMessage(Socket socket, JsonSocket jsonSocket) {
new Thread(() -> {
- InputStream inputStream = null;
- InputStreamReader inputStreamReader = null;
- BufferedReader bufferedReader = null;
- try {
- inputStream = socket.getInputStream();
- inputStreamReader = new InputStreamReader(inputStream, StandardCharsets.UTF_8);
- bufferedReader = new BufferedReader(inputStreamReader);
+ // try (AutoCloseable) { ... }
+ // @Thank to Zen2H
+ try (InputStream inputStream = socket.getInputStream();
+ InputStreamReader inputStreamReader = new InputStreamReader(inputStream, StandardCharsets.UTF_8);
+ BufferedReader bufferedReader = new BufferedReader(inputStreamReader)
+ ) {
final StringBuilder stringBuilder = new StringBuilder();
String readLine;
Log.d(TAG, "bufferedReader is reading lines...");
@@ -216,9 +214,6 @@ abstract public class JsonSocket extends Socket {
} catch (IOException e) {
e.printStackTrace();
} finally {
- IOTool.close(bufferedReader);
- IOTool.close(inputStreamReader);
- IOTool.close(inputStream);
try {
jsonSocket.switchOff();
} catch (IOException e) {
diff --git a/app/src/main/java/org/autojs/autojs/pluginclient/JsonSocketClient.java b/app/src/main/java/org/autojs/autojs/pluginclient/JsonSocketClient.java
index 29ad03eb..be2da8b5 100644
--- a/app/src/main/java/org/autojs/autojs/pluginclient/JsonSocketClient.java
+++ b/app/src/main/java/org/autojs/autojs/pluginclient/JsonSocketClient.java
@@ -12,6 +12,8 @@ import com.google.gson.JsonObject;
import java.io.IOException;
import java.net.Socket;
import java.util.HashMap;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.subjects.PublishSubject;
@@ -20,6 +22,8 @@ public class JsonSocketClient extends JsonSocket {
private static final String TAG = JsonSocketClient.class.getSimpleName();
+ private final ExecutorService jsonSocketExecutor = Executors.newSingleThreadExecutor();
+
public static final PublishSubject cxnState = PublishSubject.create();
private final PublishSubject mJsonElementPublishSubject = PublishSubject.create();
@@ -32,14 +36,14 @@ public class JsonSocketClient extends JsonSocket {
// @Constructor
public JsonSocketClient(String host, int port) {
- new Thread(() -> {
+ jsonSocketExecutor.submit(() -> {
try {
setStateConnecting();
mSocket = new Socket(host, port);
} catch (IOException e) {
e.printStackTrace();
}
- }).start();
+ });
}
public boolean isSocketReady() {
@@ -80,6 +84,7 @@ public class JsonSocketClient extends JsonSocket {
mSocket.close();
mSocket = null;
}
+ jsonSocketExecutor.shutdown();
}
@Override
diff --git a/app/src/main/java/org/autojs/autojs/tool/ThreadTool.java b/app/src/main/java/org/autojs/autojs/tool/ThreadTool.java
index 6f97d2c2..82cbf392 100644
--- a/app/src/main/java/org/autojs/autojs/tool/ThreadTool.java
+++ b/app/src/main/java/org/autojs/autojs/tool/ThreadTool.java
@@ -12,8 +12,8 @@ public class ThreadTool {
try {
//noinspection BusyWait
Thread.sleep(200);
- } catch (InterruptedException e) {
- e.printStackTrace();
+ } catch (InterruptedException ignore) {
+ // ignored
}
}
result.set(true);
diff --git a/app/src/main/java/org/autojs/autojs/ui/main/MainActivity.java b/app/src/main/java/org/autojs/autojs/ui/main/MainActivity.java
index d3c786c7..008b3294 100644
--- a/app/src/main/java/org/autojs/autojs/ui/main/MainActivity.java
+++ b/app/src/main/java/org/autojs/autojs/ui/main/MainActivity.java
@@ -7,6 +7,7 @@ import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
+import android.os.Process;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
@@ -185,7 +186,7 @@ public class MainActivity extends BaseActivity implements OnActivityResultDelega
stopService(new Intent(view.getContext(), FloatyService.class));
AutoJs.getInstance().getScriptEngineService().stopAll();
finish();
- Runtime.getRuntime().exit(0);
+ Process.killProcess(Process.myPid());
}
@Click(R.id.restart)
@@ -199,7 +200,7 @@ public class MainActivity extends BaseActivity implements OnActivityResultDelega
}
Intent mainIntent = Intent.makeRestartActivityTask(componentName);
context.startActivity(mainIntent);
- Runtime.getRuntime().exit(0);
+ Process.killProcess(Process.myPid());
}
@Override
diff --git a/app/src/main/java/org/autojs/autojs/ui/main/drawer/DrawerFragment.java b/app/src/main/java/org/autojs/autojs/ui/main/drawer/DrawerFragment.java
index f3fd626a..11fd157c 100644
--- a/app/src/main/java/org/autojs/autojs/ui/main/drawer/DrawerFragment.java
+++ b/app/src/main/java/org/autojs/autojs/ui/main/drawer/DrawerFragment.java
@@ -52,6 +52,7 @@ import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import java.io.IOException;
+import java.net.ServerSocket;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Objects;
@@ -408,33 +409,58 @@ public class DrawerFragment extends androidx.fragment.app.Fragment {
}
- private void toggleRemoteServerCxn(DrawerMenuItemViewHolder holder) throws IOException {
- JsonSocketClient jsonSocketClient = devPlugin.getJsonSocketClient();
- boolean disconnected = jsonSocketClient == null || !jsonSocketClient.isSocketReady();
- boolean checked = holder.getSwitchCompat().isChecked();
-
- if (checked) {
- if (disconnected) {
- inputRemoteHost();
- }
+ private void toggleRemoteServerCxn(DrawerMenuItemViewHolder holder) {
+ boolean isChecked = holder.getSwitchCompat().isChecked();
+ boolean isDisconnected = !isJsonSocketClientConnected();
+ if (isChecked && isDisconnected) {
+ inputRemoteHost();
} else {
- if (jsonSocketClient != null) {
- jsonSocketClient.switchOff();
+ disconnectJsonSocketClientIFN();
+ }
+ }
+
+ private void disconnectJsonSocketClientIFN() {
+ JsonSocketClient client = devPlugin.getJsonSocketClient();
+ if (client != null) {
+ try {
+ client.switchOff();
+ } catch (IOException e) {
+ e.printStackTrace();
}
}
}
- @SuppressLint("CheckResult")
- private void toggleLocalServerCxn(DrawerMenuItemViewHolder holder) throws IOException {
- JsonSocketServer jsonSocketServer = devPlugin.getJsonSocketServer();
- boolean checked = holder.getSwitchCompat().isChecked();
+ private boolean isJsonSocketClientConnected() {
+ JsonSocketClient client = devPlugin.getJsonSocketClient();
+ return client != null && client.isSocketReady();
+ }
- if (checked) {
- devPlugin.enableLocalServer()
+ @SuppressLint("CheckResult")
+ private void toggleLocalServerCxn(DrawerMenuItemViewHolder holder) {
+ boolean isChecked = holder.getSwitchCompat().isChecked();
+ boolean isDisconnected = !isServerSocketConnected();
+
+ if (isChecked && isDisconnected) {
+ devPlugin
+ .enableLocalServer()
.subscribe(Observers.emptyConsumer(), this::onAJServerConnectException);
} else {
- if (jsonSocketServer != null) {
- jsonSocketServer.switchOff();
+ disconnectServerSocketIFN();
+ }
+ }
+
+ private boolean isServerSocketConnected() {
+ ServerSocket serverSocket = devPlugin.getServerSocket();
+ return serverSocket != null && !serverSocket.isClosed();
+ }
+
+ private void disconnectServerSocketIFN() {
+ ServerSocket serverSocket = devPlugin.getServerSocket();
+ if (serverSocket != null) {
+ try {
+ serverSocket.close();
+ } catch (IOException e) {
+ e.printStackTrace();
}
}
}
@@ -511,6 +537,8 @@ public class DrawerFragment extends androidx.fragment.app.Fragment {
setChecked(mDisplayOverOtherAppsItem, FloatingPermission.canDrawOverlays(context));
setChecked(mWriteSystemSettingsItem, Settings.System.canWrite(getContext()));
setChecked(mWriteSecuritySettingsItem, hasWriteSecureSettingsAccess());
+ setChecked(mClientModeItem, isJsonSocketClientConnected());
+ setChecked(mServerModeItem, isServerSocketConnected());
}
private boolean isAccessibilityServiceEnabled() {
diff --git a/app/src/main/java/org/autojs/autojs/ui/shortcut/ShortcutCreateActivity.java b/app/src/main/java/org/autojs/autojs/ui/shortcut/ShortcutCreateActivity.java
index 2aec7e0a..f979bdb3 100644
--- a/app/src/main/java/org/autojs/autojs/ui/shortcut/ShortcutCreateActivity.java
+++ b/app/src/main/java/org/autojs/autojs/ui/shortcut/ShortcutCreateActivity.java
@@ -10,9 +10,11 @@ import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.PersistableBundle;
+
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
+
import android.util.Log;
import android.view.View;
import android.widget.CheckBox;
@@ -65,8 +67,8 @@ public class ShortcutCreateActivity extends AppCompatActivity {
private void showDialog() {
View view = View.inflate(this, R.layout.shortcut_create_dialog, null);
ButterKnife.bind(this, view);
- mUseAndroidNShortcut.setVisibility(Build.VERSION.SDK_INT >= Build.VERSION_CODES.N ?
- View.VISIBLE : View.GONE);
+ mUseAndroidNShortcut.setVisibility(Build.VERSION.SDK_INT == Build.VERSION_CODES.N_MR1
+ ? View.VISIBLE : View.GONE);
mName.setText(mScriptFile.getSimplifiedName());
new ThemeColorMaterialDialogBuilder(this)
.customView(view, false)
@@ -90,7 +92,7 @@ public class ShortcutCreateActivity extends AppCompatActivity {
@SuppressLint("NewApi") //for fool android studio
private void createShortcut() {
- if ((Build.VERSION.SDK_INT >= Build.VERSION_CODES.N_MR1 && mUseAndroidNShortcut.isChecked())
+ if ((Build.VERSION.SDK_INT == Build.VERSION_CODES.N_MR1 && mUseAndroidNShortcut.isChecked())
|| Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
createShortcutByShortcutManager();
return;
@@ -132,7 +134,7 @@ public class ShortcutCreateActivity extends AppCompatActivity {
}
- @SuppressLint("CheckResult")
+ @SuppressLint({"CheckResult", "MissingSuperCall"})
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != RESULT_OK) {
@@ -149,7 +151,7 @@ public class ShortcutCreateActivity extends AppCompatActivity {
return;
}
Uri uri = data.getData();
- if(uri == null){
+ if (uri == null) {
return;
}
Observable.fromCallable(() -> BitmapFactory.decodeStream(getContentResolver().openInputStream(uri)))
@@ -158,9 +160,7 @@ public class ShortcutCreateActivity extends AppCompatActivity {
.subscribe((bitmap -> {
mIcon.setImageBitmap(bitmap);
mIsDefaultIcon = false;
- }), error -> {
- Log.e(LOG_TAG, "decode stream", error);
- });
+ }), error -> Log.e(LOG_TAG, "decode stream", error));
}
}
diff --git a/autojs/build.gradle b/autojs/build.gradle
index dcff52d8..bc933605 100644
--- a/autojs/build.gradle
+++ b/autojs/build.gradle
@@ -1,6 +1,6 @@
plugins {
- id "com.android.library"
- id "kotlin-android"
+ id 'com.android.library'
+ id 'kotlin-android'
}
tasks.withType(org.jetbrains.kotlin.gradle.tasks.KotlinCompile).all {
@@ -10,21 +10,21 @@ tasks.withType(org.jetbrains.kotlin.gradle.tasks.KotlinCompile).all {
}
// tasks.withType(JavaCompile) {
-// options.compilerArgs << "-Xlint:deprecation" << "-Xlint:unchecked"
+// options.compilerArgs << '-Xlint:deprecation' << '-Xlint:unchecked'
// }
android {
- compileSdkVersion versions.compile
+ compileSdkVersion versions.project.compile
defaultConfig {
- minSdkVersion versions.mini
- targetSdkVersion versions.target
+ minSdkVersion versions.project.mini
+ targetSdkVersion versions.project.target
- testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
+ testInstrumentationRunner 'androidx.test.runner.AndroidJUnitRunner'
}
buildTypes {
release {
minifyEnabled false
- proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
+ proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
compileOptions {
@@ -41,32 +41,27 @@ repositories {
}
dependencies {
- testImplementation "junit:junit:${junitVer}"
+ testImplementation "junit:junit:${versions.junit}"
- implementation "net.lingala.zip4j:zip4j:2.9.1"
-
- implementation "com.afollestad.material-dialogs:core:0.9.6.0"
- implementation "com.google.android.material:material:1.6.0-alpha01"
+ implementation 'net.lingala.zip4j:zip4j:2.9.1'
// OkHttp
- implementation "com.squareup.okhttp3:okhttp:5.0.0-alpha.3"
+ implementation 'com.squareup.okhttp3:okhttp:5.0.0-alpha.4'
// Gson
- implementation "com.google.code.gson:gson:2.8.9"
+ implementation 'com.google.code.gson:gson:2.8.9'
// Log4j
- implementation group: "de.mindpipe.android", name: "android-logging-log4j", version: "1.0.3"
- implementation group: "log4j", name: "log4j", version: "1.2.17"
+ implementation 'de.mindpipe.android:android-logging-log4j:1.0.3'
+ implementation 'log4j:log4j:1.2.17'
// Terminal emulator
- api project(":libs:jackpal.androidterm.libtermexec-1.0")
- api project(":libs:jackpal.androidterm.emulatorview-1.0.42")
- api project(":libs:jackpal.androidterm-1.0.70")
+ api project(':libs:jackpal.androidterm.libtermexec-1.0')
+ api project(':libs:jackpal.androidterm.emulatorview-1.0.42')
+ api project(':libs:jackpal.androidterm-1.0.70')
- api project(":libs:com.android.dx-1.7.0")
- api project(":libs:org.mozilla.rhino-1.7.14")
- api project(":libs:org.opencv-4.5.4")
+ api project(':libs:com.android.dx-1.7.0')
- api project(":common")
- api project(":automator")
+ api project(':common')
+ api project(':automator')
}
\ No newline at end of file
diff --git a/autojs/src/main/assets/modules/__globals__.js b/autojs/src/main/assets/modules/__globals__.js
index aac94f52..ad4b1c30 100644
--- a/autojs/src/main/assets/modules/__globals__.js
+++ b/autojs/src/main/assets/modules/__globals__.js
@@ -1,6 +1,8 @@
let Looper = android.os.Looper;
let Toast = android.widget.Toast;
let Runnable = java.lang.Runnable;
+let ScriptInterruptedException = com.stardust.autojs.runtime.exception.ScriptInterruptedException;
+let ReentrantLock = java.util.concurrent.locks.ReentrantLock;
module.exports = function (runtime, global) {
let _ = {
@@ -54,6 +56,28 @@ module.exports = function (runtime, global) {
}
return this.buildTypes.release;
},
+ toasts: {
+ /**
+ * @type {android.widget.Toast[]}
+ */
+ pool: [],
+ lock: new ReentrantLock(),
+ add(t) {
+ if (t instanceof Toast) {
+ this.lock.lock();
+ this.pool.push(t);
+ this.lock.unlock();
+ }
+ },
+ dismiss() {
+ this.lock.lock();
+ this.pool.forEach((t) => {
+ t.cancel();
+ });
+ this.pool.splice(0);
+ this.lock.unlock();
+ },
+ },
};
Object.assign(global, {
@@ -62,29 +86,15 @@ module.exports = function (runtime, global) {
androidx: Packages.androidx,
toast(msg, is_long, is_forcible) {
let $ = {
- cache: null,
- toast(msg, is_long, is_forcible) {
+ toast() {
this.init(arguments);
- this.post();
+ this.show();
},
- /** @param {IArguments} args */
- init(args) {
- let [msg, is_long, is_forcible] = args;
+ init() {
this.message = isNullish(msg) ? '' : msg.toString();
this.is_long = this.parseIsLong(is_long);
this.is_forcible = is_forcible;
},
- post() {
- ui.post(() => {
- new android.os.Handler(Looper.getMainLooper()).post(new Runnable({
- run() {
- $.is_forcible && $.dismiss();
- $.cache = Toast.makeText(context, $.message, $.is_long);
- $.show();
- },
- }));
- });
- },
parseIsLong(is_long) {
if (typeof is_long === 'number') {
return Number(!!is_long);
@@ -97,22 +107,23 @@ module.exports = function (runtime, global) {
}
return 0;
},
- dismiss() {
- if (this.cache instanceof Toast) {
- this.cache.cancel();
- this.cache = null;
- }
- },
show() {
- this.cache.show();
+ ui.post(() => {
+ new android.os.Handler(Looper.getMainLooper()).post(new Runnable({
+ run() {
+ if ($.is_forcible) {
+ $.dismiss();
+ }
+ $.toastObj = Toast.makeText(context, $.message, $.is_long);
+ _.toasts.add($.toastObj);
+ $.toastObj.show();
+ },
+ }));
+ });
},
};
- (function $LazY() {
- this.toast = $.toast.bind($);
- this.toast.dismiss = () => $.dismiss();
- return this.toast;
- }.call(this)).apply(null, arguments);
+ $.toast();
},
toastLog(msg, is_long, is_forcible) {
this.toast.apply(this, arguments);
@@ -136,7 +147,13 @@ module.exports = function (runtime, global) {
sleep(min, max) {
if (this.trigger()) {
this.parseArgs(min, max);
- runtime.sleep(this.min + this.rand_bound);
+ try {
+ runtime.sleep(this.min + this.rand_bound);
+ } catch (e) {
+ if (!(e.javaException instanceof ScriptInterruptedException)) {
+ throw e;
+ }
+ }
}
},
trigger() {
@@ -262,5 +279,17 @@ module.exports = function (runtime, global) {
isReference(o) {
return o === Object(o);
},
- });
+ $bind() {
+ this.toast.dismiss = function () {
+ ui.post(() => {
+ new android.os.Handler(Looper.getMainLooper()).post(new Runnable({
+ run() {
+ _.toasts.dismiss();
+ },
+ }));
+ });
+ };
+ return this;
+ },
+ }.$bind());
};
\ No newline at end of file
diff --git a/autojs/src/main/assets/modules/__images__.js b/autojs/src/main/assets/modules/__images__.js
index a1951631..50ebeb6a 100644
--- a/autojs/src/main/assets/modules/__images__.js
+++ b/autojs/src/main/assets/modules/__images__.js
@@ -1,104 +1,128 @@
// noinspection NpmUsedModulesInstalled
+const ResultAdapter = require('result_adapter');
+
const Point = org.opencv.core.Point;
const Rect = org.opencv.core.Rect;
const Scalar = org.opencv.core.Scalar;
const Size = org.opencv.core.Size;
const Core = org.opencv.core.Core;
const Imgproc = org.opencv.imgproc.Imgproc;
+
+const Gravity = android.view.Gravity;
+
const Mat = com.stardust.autojs.core.opencv.Mat;
const Images = com.stardust.autojs.runtime.api.Images;
+const ColorDetector = com.stardust.autojs.core.image.ColorDetector;
+const ScreenCapturer = com.stardust.autojs.core.image.capture.ScreenCapturer;
const DEF_COLOR_THRESHOLD = 4;
module.exports = function (runtime, scope) {
- const ResultAdapter = require('result_adapter');
+ const colors = Object.assign(Object.create(runtime.colors), {
+ alpha(color) {
+ return _.parseColor(color) >>> 24;
+ },
+ red(color) {
+ return (_.parseColor(color) >> 16) & 0xFF;
+ },
+ green(color) {
+ return (_.parseColor(color) >> 8) & 0xFF;
+ },
+ blue(color) {
+ return _.parseColor(color) & 0xFF;
+ },
+ isSimilar(c1, c2, threshold, algorithm) {
+ let t = _.parseNumber(threshold, DEF_COLOR_THRESHOLD);
+ let c = _.parseColor(c2);
+ return _.getColorDetector(_.parseColor(c1), algorithm || 'diff', t)
+ .detectsColor(colors.red(c), colors.green(c), colors.blue(c));
+ },
+ });
const MatchingResult = (function $iiFe() {
let comparators = {
- 'left': (l, r) => l.point.x - r.point.x,
- 'top': (l, r) => l.point.y - r.point.y,
- 'right': (l, r) => r.point.x - l.point.x,
- 'bottom': (l, r) => r.point.y - l.point.y,
+ left: (l, r) => l.point.x - r.point.x,
+ top: (l, r) => l.point.y - r.point.y,
+ right: (l, r) => r.point.x - l.point.x,
+ bottom: (l, r) => r.point.y - l.point.y,
};
function MatchingResult(list) {
- if (Array.isArray(list)) {
- this.matches = list;
- } else {
- this.matches = runtime.bridges.getBridges().toArray(list);
- }
+ this.matches = Array.isArray(list) ? list : runtime.bridges.getBridges().toArray(list);
+
+ // @LazyGetter
Object.defineProperty(this, 'points', {
- get() {
- if (typeof this.__points__ === 'undefined') {
- this.__points__ = this.matches.map(m => m.point);
- }
- return this.__points__;
+ set(v) {
+ Object.defineProperty(this, 'points', {value: v});
},
+ get() {
+ return this.points = this.matches.map(m => m.point);
+ },
+ enumerable: true,
+ configurable: true,
});
}
- MatchingResult.prototype.first = function () {
- return this.matches.length ? this.matches[0] : null;
- };
- MatchingResult.prototype.last = function () {
- return this.matches.length ? this.matches[this.matches.length - 1] : null;
- };
- MatchingResult.prototype.findMax = function (cmp) {
- if (!this.matches.length) {
- return null;
- }
- let target = this.matches[0];
- this.matches.forEach(m => target = cmp(target, m) > 0 ? m : target);
- return target;
- };
- MatchingResult.prototype.leftmost = function () {
- return this.findMax(comparators.left);
- };
- MatchingResult.prototype.topmost = function () {
- return this.findMax(comparators.top);
- };
- MatchingResult.prototype.rightmost = function () {
- return this.findMax(comparators.right);
- };
- MatchingResult.prototype.bottommost = function () {
- return this.findMax(comparators.bottom);
- };
- MatchingResult.prototype.worst = function () {
- return this.findMax((l, r) => l.similarity - r.similarity);
- };
- MatchingResult.prototype.best = function () {
- return this.findMax((l, r) => r.similarity - l.similarity);
- };
- MatchingResult.prototype.sortBy = function (cmp) {
- let comparatorFn = null;
- if (typeof cmp === 'string') {
- cmp.split('-').forEach((direction) => {
- let buildInFn = comparators[direction];
- if (!buildInFn) {
- throw new Error('unknown direction \'' + direction + '\' in \'' + cmp + '\'');
- }
- (function (fn) {
+ Object.assign(MatchingResult.prototype, {
+ first() {
+ return this.matches.length ? this.matches[0] : null;
+ },
+ last() {
+ return this.matches.length ? this.matches[this.matches.length - 1] : null;
+ },
+ findMax(cmp) {
+ if (!this.matches.length) {
+ return null;
+ }
+ let target = this.matches[0];
+ this.matches.forEach(m => target = cmp(target, m) > 0 ? m : target);
+ return target;
+ },
+ leftmost() {
+ return this.findMax(comparators.left);
+ },
+ topmost() {
+ return this.findMax(comparators.top);
+ },
+ rightmost() {
+ return this.findMax(comparators.right);
+ },
+ bottommost() {
+ return this.findMax(comparators.bottom);
+ },
+ worst() {
+ return this.findMax((l, r) => l.similarity - r.similarity);
+ },
+ best() {
+ return this.findMax((l, r) => r.similarity - l.similarity);
+ },
+ sortBy(cmp) {
+ let comparatorFn = null;
+ if (typeof cmp === 'string') {
+ cmp.split('-').forEach((direction) => {
+ let buildInFn = comparators[direction];
+ if (!buildInFn) {
+ throw new Error(`unknown direction '${direction}' in '${cmp}'`);
+ }
if (comparatorFn === null) {
- comparatorFn = fn;
+ comparatorFn = buildInFn;
} else {
comparatorFn = (function (comparatorFn, fn) {
return function (l, r) {
let cmpValue = comparatorFn(l, r);
return cmpValue === 0 ? fn(l, r) : cmpValue;
};
- })(comparatorFn, fn);
+ })(comparatorFn, buildInFn);
}
- })(buildInFn);
- });
- } else {
- comparatorFn = cmp;
- }
- let clone = this.matches.slice();
- clone.sort(comparatorFn);
- return new MatchingResult(clone);
- };
+ });
+ } else {
+ comparatorFn = cmp;
+ }
+ return new MatchingResult(this.matches.slice().sort(comparatorFn));
+ },
+ });
return MatchingResult;
})();
@@ -107,440 +131,445 @@ module.exports = function (runtime, scope) {
const colorFinder = rtImages.colorFinder;
- function getColorDetector(color, algorithm, threshold) {
- switch (algorithm) {
- case 'rgb':
- return new com.stardust.autojs.core.image.ColorDetector.RGBDistanceDetector(color, threshold);
- case 'equal':
- return new com.stardust.autojs.core.image.ColorDetector.EqualityDetector(color);
- case 'diff':
- return new com.stardust.autojs.core.image.ColorDetector.DifferenceDetector(color, threshold);
- case 'rgb+':
- return new com.stardust.autojs.core.image.ColorDetector.WeightedRGBDistanceDetector(color, threshold);
- case 'hs':
- return new com.stardust.autojs.core.image.ColorDetector.HSDistanceDetector(color, threshold);
- }
- throw new Error('Unknown algorithm: ' + algorithm);
- }
-
- function toPointArray(points) {
- let arr = [];
- for (let i = 0; i < points.length; i++) {
- arr.push(points[i]);
- }
- return arr;
- }
-
- function buildRegion(region, img) {
- if (region === undefined) {
- region = [];
- }
- let x = region[0] === undefined ? 0 : region[0];
- let y = region[1] === undefined ? 0 : region[1];
- let width = region[2] === undefined ? img.getWidth() - x : region[2];
- let height = region[3] === undefined ? (img.getHeight() - y) : region[3];
- let r = new Rect(x, y, width, height);
- if (x < 0 || y < 0 || x + width > img.width || y + height > img.height) {
- throw new Error('out of region: region = [' + [x, y, width, height] + '], image.size = [' + [img.width, img.height] + ']');
- }
- return r;
- }
-
- function parseColor(color) {
- if (typeof color === 'string') {
- color = colors.parseColor(color);
- }
- return color;
- }
-
- function newSize(size) {
- if (!Array.isArray(size)) {
- size = [size, size];
- }
- if (size.length === 1) {
- size = [size[0], size[0]];
- }
- return new Size(size[0], size[1]);
- }
-
- function initIfNeeded() {
- rtImages.initOpenCvIfNeeded();
- }
-
- const colors = Object.create(runtime.colors, {
- alpha: {
- value(color) {
- color = parseColor(color);
- return color >>> 24;
- },
- enumerable: true,
+ const _ = {
+ initIfNeeded() {
+ rtImages.initOpenCvIfNeeded();
},
- red: {
- value(color) {
- color = parseColor(color);
- return (color >> 16) & 0xFF;
- },
- enumerable: true,
+ /**
+ * @param {number} x
+ * @param {number} min
+ * @param {number} max
+ * @param {number} [def=0]
+ * @returns {number}
+ */
+ clamp: (x, min, max, def) => {
+ return Math.min(Math.max(_.parseNumber(x, def), min), max);
},
- green: {
- value(color) {
- color = parseColor(color);
- return (color >> 8) & 0xFF;
- },
- enumerable: true,
+ requestScreenCapture(orientation) {
+ return ResultAdapter.wait(rtImages.requestScreenCapture(orientation));
},
- blue: {
- value(color) {
- color = parseColor(color);
- return color & 0xFF;
- },
- enumerable: true,
+ /**
+ * @param {any} num
+ * @param {number|function():number} [def=0]
+ * @returns {number}
+ */
+ parseNumber(num, def) {
+ return typeof num === 'number' ? num : typeof def === 'function' ? def() : def || 0;
},
- isSimilar: {
- value(c1, c2, threshold, algorithm) {
- c1 = parseColor(c1);
- c2 = parseColor(c2);
- threshold = threshold === undefined ? 4 : threshold;
- algorithm = algorithm === undefined ? 'diff' : algorithm;
- let colorDetector = getColorDetector(c1, algorithm, threshold);
- return colorDetector.detectsColor(colors.red(c2), colors.green(c2), colors.blue(c2));
- },
- enumerable: true,
+ /**
+ * @param {number|number[]} size
+ * @returns {org.opencv.core.Size}
+ */
+ parseSize(size) {
+ let width, height;
+ if (!Array.isArray(size)) {
+ width = height = size;
+ } else {
+ if (size.length === 1) {
+ width = height = size[0];
+ } else {
+ [width, height] = size;
+ }
+ }
+ return new Size(width, height);
},
- });
+ /**
+ * @param {number|string} color
+ * @returns {number}
+ */
+ parseColor(color) {
+ if (typeof color === 'string') {
+ return colors.parseColor(color);
+ }
+ return color;
+ },
+ /**
+ * @param {number[]} point
+ * @returns {org.opencv.core.Point}
+ */
+ parsePoint(point) {
+ let [x, y] = point;
+ return new Point(x, y);
+ },
+ parseQuality(q) {
+ return this.clamp(q, 0, 100, 100);
+ },
+ parseScalar(color, offset) {
+ let d = this.clamp(offset, -255, 255, 0);
+ return new Scalar(colors.red(color) + d, colors.green(color) + d, colors.blue(color) + d, colors.alpha(color));
+ },
+ parseScalars(color, threshold) {
+ let thd = this.clamp(threshold, 0, 255, 0);
+ return {
+ lowerBound: _.parseScalar(color, -thd),
+ upperBound: _.parseScalar(color, +thd),
+ };
+ },
+ parseBorderType(type) {
+ return Core['BORDER_' + (type || 'DEFAULT')];
+ },
+ /**
+ * @param {{
+ * threshold?: number,
+ * similarity?: number,
+ * }} options
+ * @param {number} [def]
+ * @returns {number}
+ */
+ parseThreshold(options, def) {
+ let opt = options || {};
+ if (opt.similarity) {
+ return Math.trunc(255 * (1 - opt.similarity));
+ }
+ return opt.threshold || (def === undefined ? DEF_COLOR_THRESHOLD : def);
+ },
+ /**
+ * @param {{
+ * weakThreshold?: number,
+ * }} options
+ * @param {number} [def]
+ * @returns {number}
+ */
+ parseWeakThreshold(options, def) {
+ let opt = options || {};
+ return opt.weakThreshold || def;
+ },
+ resize(img, mat, size, fx, fy, interpolation) {
+ Imgproc.resize(img.mat, mat, this.parseSize(0), fx, fy, Imgproc['INTER_' + (interpolation || 'LINEAR')]);
+ },
+ /**
+ * @param {com.stardust.autojs.core.image.ImageWrapper} img
+ * @param {{region?: number[]}} [o]
+ * @returns {?org.opencv.core.Rect}
+ */
+ buildRegion(img, o) {
+ if (!o || !o.region) {
+ return null;
+ }
+
+ let [x, y, w, h] = o.region;
+ x = _.parseNumber(x, 0);
+ y = _.parseNumber(y, 0);
+ w = _.parseNumber(w, () => img.getWidth() - x);
+ h = _.parseNumber(h, () => img.getHeight() - y);
+
+ return _.checkAndGetImageRect(new Rect(x, y, w, h), img);
+ },
+ /**
+ * @param {org.opencv.core.Point[]} points - Java Array
+ * @returns {org.opencv.core.Point[]}
+ */
+ toPointArray(points) {
+ let arr = [];
+ for (let i = 0; i < points.length; i++) {
+ arr.push(points[i]);
+ }
+ return arr;
+ },
+ /**
+ * @param {org.opencv.core.Rect} rect
+ * @param {com.stardust.autojs.core.image.ImageWrapper} img
+ * @returns {org.opencv.core.Rect}
+ */
+ checkAndGetImageRect(rect, img) {
+ let {x, y, width, height} = rect;
+ if (x < 0) {
+ throw Error(`X of region must be non-negative rather than ${x}`);
+ }
+ if (y < 0) {
+ throw Error(`Y of region must be non-negative rather than ${y}`);
+ }
+ if (x + width > img.width) {
+ throw Error(`Width of region overstepped:\n${x} + ${width} > ${img.width}`);
+ }
+ if (y + height > img.height) {
+ throw Error(`Height of region overstepped:\n${y} + ${height} > ${img.height}`);
+ }
+ return rect;
+ },
+ getColorDetector(color, algorithm, threshold) {
+ switch (algorithm) {
+ case 'rgb':
+ return new ColorDetector.RGBDistanceDetector(color, threshold);
+ case 'equal':
+ return new ColorDetector.EqualityDetector(color);
+ case 'diff':
+ return new ColorDetector.DifferenceDetector(color, threshold);
+ case 'rgb+':
+ return new ColorDetector.WeightedRGBDistanceDetector(color, threshold);
+ case 'hs':
+ return new ColorDetector.HSDistanceDetector(color, threshold);
+ }
+ throw Error('Unknown algorithm for detector: ' + algorithm);
+ },
+ };
const images = () => void 0;
- images.requestScreenCapture = function (landscape) {
- let ScreenCapturer = com.stardust.autojs.core.image.capture.ScreenCapturer;
- let orientation = ScreenCapturer.ORIENTATION_AUTO;
- if (landscape === true) {
- orientation = ScreenCapturer.ORIENTATION_LANDSCAPE;
- }
- if (landscape === false) {
- orientation = ScreenCapturer.ORIENTATION_PORTRAIT;
- }
- return ResultAdapter.wait(rtImages.requestScreenCapture(orientation));
- };
-
- images.save = function (img, path, format, quality) {
- format = format || 'png';
- quality = quality === undefined ? 100 : quality;
- return rtImages.save(img, path, format, quality);
- };
-
- images.saveImage = function (img, path, format, quality) {
- return images.save(img, path, format, quality);
- };
-
- images.grayscale = function (img, dstCn) {
- return images.cvtColor(img, 'BGR2GRAY', dstCn);
- };
-
- images.threshold = function (img, threshold, maxVal, type) {
- initIfNeeded();
- let mat = new Mat();
- type = type || 'BINARY';
- type = Imgproc['THRESH_' + type];
- Imgproc.threshold(img.mat, mat, threshold, maxVal, type);
- return images.matToImage(mat);
- };
-
- images.inRange = function (img, lowerBound, upperBound) {
- initIfNeeded();
- let lb = new Scalar(colors.red(lowerBound), colors.green(lowerBound),
- colors.blue(lowerBound), colors.alpha(lowerBound));
- let ub = new Scalar(colors.red(upperBound), colors.green(upperBound),
- colors.blue(upperBound), colors.alpha(lowerBound));
- let bi = new Mat();
- Core.inRange(img.mat, lb, ub, bi);
- return images.matToImage(bi);
- };
-
- images.interval = function (img, color, threshold) {
- initIfNeeded();
- let lb = new Scalar(colors.red(color) - threshold, colors.green(color) - threshold,
- colors.blue(color) - threshold, colors.alpha(color));
- let ub = new Scalar(colors.red(color) + threshold, colors.green(color) + threshold,
- colors.blue(color) + threshold, colors.alpha(color));
- let bi = new Mat();
- Core.inRange(img.mat, lb, ub, bi);
- return images.matToImage(bi);
- };
-
- images.adaptiveThreshold = function (img, maxValue, adaptiveMethod, thresholdType, blockSize, C) {
- initIfNeeded();
- let mat = new Mat();
- adaptiveMethod = Imgproc['ADAPTIVE_THRESH_' + adaptiveMethod];
- thresholdType = Imgproc['THRESH_' + thresholdType];
- Imgproc.adaptiveThreshold(img.mat, mat, maxValue, adaptiveMethod, thresholdType, blockSize, C);
- return images.matToImage(mat);
-
- };
-
- images.blur = function (img, size, point, type) {
- initIfNeeded();
- let mat = new Mat();
- size = newSize(size);
- type = Core['BORDER_' + (type || 'DEFAULT')];
- if (point === undefined) {
- Imgproc.blur(img.mat, mat, size);
- } else {
- Imgproc.blur(img.mat, mat, size, new Point(point[0], point[1]), type);
- }
- return images.matToImage(mat);
- };
-
- images.medianBlur = function (img, size) {
- initIfNeeded();
- let mat = new Mat();
- Imgproc.medianBlur(img.mat, mat, size);
- return images.matToImage(mat);
- };
-
- images.gaussianBlur = function (img, size, sigmaX, sigmaY, type) {
- initIfNeeded();
- let mat = new Mat();
- size = newSize(size);
- sigmaX = sigmaX === undefined ? 0 : sigmaX;
- sigmaY = sigmaY === undefined ? 0 : sigmaY;
- type = Core['BORDER_' + (type || 'DEFAULT')];
- Imgproc.GaussianBlur(img.mat, mat, size, sigmaX, sigmaY, type);
- return images.matToImage(mat);
- };
-
- images.cvtColor = function (img, code, dstCn) {
- initIfNeeded();
- let mat = new Mat();
- code = Imgproc['COLOR_' + code];
- if (dstCn === undefined) {
- Imgproc.cvtColor(img.mat, mat, code);
- } else {
- Imgproc.cvtColor(img.mat, mat, code, dstCn);
- }
- return images.matToImage(mat);
- };
-
- images.findCircles = function (grayImg, options) {
- initIfNeeded();
- options = options || {};
- let mat = options.region === undefined ? grayImg.mat : new Mat(grayImg.mat, buildRegion(options.region, grayImg));
- let resultMat = new Mat();
- let dp = options.dp === undefined ? 1 : options.dp;
- let minDst = options.minDst === undefined ? grayImg.height / 8 : options.minDst;
- let param1 = options.param1 === undefined ? 100 : options.param1;
- let param2 = options.param2 === undefined ? 100 : options.param2;
- let minRadius = options.minRadius === undefined ? 0 : options.minRadius;
- let maxRadius = options.maxRadius === undefined ? 0 : options.maxRadius;
- Imgproc.HoughCircles(mat, resultMat, Imgproc.CV_HOUGH_GRADIENT, dp, minDst, param1, param2, minRadius, maxRadius);
- let result = [];
- for (let i = 0; i < resultMat.rows(); i++) {
- for (let j = 0; j < resultMat.cols(); j++) {
- let d = resultMat.get(i, j);
- result.push({
- x: d[0],
- y: d[1],
- radius: d[2],
- });
+ const images_ext = {
+ requestScreenCapture(landscape) {
+ switch (landscape) {
+ case true:
+ return _.requestScreenCapture(ScreenCapturer.ORIENTATION_LANDSCAPE);
+ case false:
+ return _.requestScreenCapture(ScreenCapturer.ORIENTATION_PORTRAIT);
+ default:
+ return _.requestScreenCapture(ScreenCapturer.ORIENTATION_AUTO);
}
- }
- if (options.region !== undefined) {
- mat.release();
- }
- resultMat.release();
- return result;
- };
-
- images.resize = function (img, size, interpolation) {
- initIfNeeded();
- let mat = new Mat();
- interpolation = Imgproc['INTER_' + (interpolation || 'LINEAR')];
- Imgproc.resize(img.mat, mat, newSize(size), 0, 0, interpolation);
- return images.matToImage(mat);
- };
-
- images.scale = function (img, fx, fy, interpolation) {
- initIfNeeded();
- let mat = new Mat();
- interpolation = Imgproc['INTER_' + (interpolation || 'LINEAR')];
- Imgproc.resize(img.mat, mat, newSize([0, 0]), fx, fy, interpolation);
- return images.matToImage(mat);
- };
-
- images.rotate = function (img, degree, x, y) {
- initIfNeeded();
- if (x === undefined) {
- x = img.width / 2;
- }
- if (y === undefined) {
- y = img.height / 2;
- }
- return rtImages.rotate(img, x, y, degree);
- };
-
- images.concat = function (img1, img2, direction) {
- initIfNeeded();
- direction = direction || 'right';
- return Images.concat(img1, img2, android.view.Gravity[direction.toUpperCase()]);
- };
-
- images.detectsColor = function (img, color, x, y, threshold, algorithm) {
- initIfNeeded();
- color = parseColor(color);
- algorithm = algorithm || 'diff';
- threshold = threshold || DEF_COLOR_THRESHOLD;
- let colorDetector = getColorDetector(color, algorithm, threshold);
- let pixel = images.pixel(img, x, y);
- return colorDetector.detectsColor(colors.red(pixel), colors.green(pixel), colors.blue(pixel));
- };
-
- images.findColor = function (img, color, options) {
- initIfNeeded();
- color = parseColor(color);
- options = options || {};
- let region = options.region || [];
- let threshold = function $iiFe() {
- if (options.similarity) {
- return parseInt(255 * (1 - options.similarity));
+ },
+ save(img, path, format, quality) {
+ return rtImages.save(img, path, format || 'png', _.parseQuality(quality));
+ },
+ saveImage(img, path, format, quality) {
+ return this.save(img, path, format, quality);
+ },
+ grayscale(img, dstCn) {
+ return this.cvtColor(img, 'BGR2GRAY', dstCn);
+ },
+ threshold(img, threshold, maxVal, type) {
+ _.initIfNeeded();
+ let mat = new Mat();
+ Imgproc.threshold(img.mat, mat, threshold, maxVal, Imgproc['THRESH_' + (type || 'BINARY')]);
+ return this.matToImage(mat);
+ },
+ inRange(img, lowerBound, upperBound) {
+ _.initIfNeeded();
+ let dst = new Mat();
+ Core.inRange(img.mat, _.parseScalar(lowerBound), _.parseScalar(upperBound), dst);
+ return this.matToImage(dst);
+ },
+ interval(img, color, threshold) {
+ _.initIfNeeded();
+ let {lowerBound, upperBound} = _.parseScalars(color, threshold);
+ let dst = new Mat();
+ Core.inRange(img.mat, lowerBound, upperBound, dst);
+ return this.matToImage(dst);
+ },
+ adaptiveThreshold(img, maxValue, adaptiveMethod, thresholdType, blockSize, C) {
+ _.initIfNeeded();
+ let mat = new Mat();
+ Imgproc.adaptiveThreshold(img.mat, mat, maxValue,
+ Imgproc['ADAPTIVE_THRESH_' + adaptiveMethod],
+ Imgproc['THRESH_' + thresholdType], blockSize, C);
+ return this.matToImage(mat);
+ },
+ blur(img, size, point, type) {
+ _.initIfNeeded();
+ let mat = new Mat();
+ if (point === undefined) {
+ Imgproc.blur(img.mat, mat, _.parseSize(size));
+ } else {
+ Imgproc.blur(img.mat, mat, _.parseSize(size), _.parsePoint(point), _.parseBorderType(type));
}
- return options.threshold || DEF_COLOR_THRESHOLD;
- }();
-
- if (options.region) {
- return colorFinder.findColor(img, color, threshold, buildRegion(region, img));
- } else {
- return colorFinder.findColor(img, color, threshold, null);
- }
- };
-
- images.findColorInRegion = function (img, color, x, y, width, height, threshold) {
- return findColor(img, color, {
- region: [x, y, width, height],
- threshold: threshold,
- });
- };
-
- images.findColorEquals = function (img, color, x, y, width, height) {
- return findColor(img, color, {
- region: [x, y, width, height],
- threshold: 0,
- });
- };
-
- images.findAllPointsForColor = function (img, color, options) {
- initIfNeeded();
- color = parseColor(color);
- options = options || {};
- let threshold = function $iiFe() {
- if (options.similarity) {
- return parseInt(255 * (1 - options.similarity));
+ return this.matToImage(mat);
+ },
+ medianBlur(img, size) {
+ _.initIfNeeded();
+ let mat = new Mat();
+ Imgproc.medianBlur(img.mat, mat, size);
+ return this.matToImage(mat);
+ },
+ gaussianBlur(img, size, sigmaX, sigmaY, type) {
+ _.initIfNeeded();
+ let mat = new Mat();
+ let x = _.parseNumber(sigmaX);
+ let y = _.parseNumber(sigmaY);
+ Imgproc.GaussianBlur(img.mat, mat, _.parseSize(size), x, y, _.parseBorderType(type));
+ return this.matToImage(mat);
+ },
+ bilateralFilter(img, d, sigmaColor, sigmaSpace, borderType) {
+ _.initIfNeeded();
+ let mat = new Mat();
+ Imgproc.bilateralFilter(img.mat, mat,
+ _.parseNumber(d, 0),
+ _.parseNumber(sigmaColor, 40),
+ _.parseNumber(sigmaSpace, 20),
+ _.parseBorderType(borderType));
+ return images.matToImage(mat);
+ },
+ cvtColor(img, code, dstCn) {
+ _.initIfNeeded();
+ let mat = new Mat();
+ if (dstCn === undefined) {
+ Imgproc.cvtColor(img.mat, mat, Imgproc['COLOR_' + code]);
+ } else {
+ Imgproc.cvtColor(img.mat, mat, Imgproc['COLOR_' + code], dstCn);
}
- return options.threshold || DEF_COLOR_THRESHOLD;
- }();
- if (options.region) {
- return toPointArray(colorFinder.findAllPointsForColor(img, color, threshold, buildRegion(options.region, img)));
- } else {
- return toPointArray(colorFinder.findAllPointsForColor(img, color, threshold, null));
- }
+ return this.matToImage(mat);
+ },
+ findCircles(grayImg, options) {
+ let $ = {
+ getResult() {
+ this.init();
+ this.parseArgs();
+ this.release();
+
+ return this.results;
+ },
+ init() {
+ _.initIfNeeded();
+ },
+ parseArgs() {
+ this.options = options || {};
+ this.region = this.options.region;
+ this.parseImage();
+ this.parseCircles();
+ },
+ parseImage() {
+ this.image = this.region
+ ? new Mat(grayImg.mat, _.buildRegion(grayImg, this))
+ : grayImg.mat;
+ },
+ parseCircles() {
+ let cir = this.circles = new Mat();
+
+ Imgproc.HoughCircles(this.image, cir, Imgproc.CV_HOUGH_GRADIENT,
+ _.parseNumber(this.options['dp'], 1),
+ _.parseNumber(this.options['minDst'], () => grayImg.height / 8),
+ _.parseNumber(this.options['param1'], 100),
+ _.parseNumber(this.options['param2'], 100),
+ _.parseNumber(this.options['minRadius'], 0),
+ _.parseNumber(this.options['maxRadius'], 0),
+ );
+
+ this.results = [];
+ for (let i = 0; i < cir.rows(); i++) {
+ for (let j = 0; j < cir.cols(); j++) {
+ let [x, y, radius] = cir.get(i, j);
+ this.results.push({x, y, radius});
+ }
+ }
+ },
+ release() {
+ if (this.region) {
+ this.image.release();
+ }
+ this.circles.release();
+ },
+ };
+
+ return $.getResult();
+ },
+ resize(img, size, interpolation) {
+ _.initIfNeeded();
+ let mat = new Mat();
+ _.resize(img, mat, size, 0, 0, interpolation);
+ return this.matToImage(mat);
+ },
+ scale(img, fx, fy, interpolation) {
+ _.initIfNeeded();
+ let mat = new Mat();
+ _.resize(img, mat, 0, fx, fy, interpolation);
+ return this.matToImage(mat);
+ },
+ rotate(img, degree, x, y) {
+ _.initIfNeeded();
+ x = _.parseNumber(x, () => img.width / 2);
+ y = _.parseNumber(y, () => img.height / 2);
+ return rtImages.rotate(img, x, y, degree);
+ },
+ concat(img1, img2, direction) {
+ _.initIfNeeded();
+ return Images.concat(img1, img2, Gravity[(direction || 'right').toUpperCase()]);
+ },
+ detectsColor(img, color, x, y, threshold, algorithm) {
+ _.initIfNeeded();
+ let pixel = images.pixel(img, x, y);
+ return _.getColorDetector(_.parseColor(color), algorithm || 'diff', threshold || DEF_COLOR_THRESHOLD)
+ .detectsColor(colors.red(pixel), colors.green(pixel), colors.blue(pixel));
+ },
+ findColor(img, color, options) {
+ _.initIfNeeded();
+ let opt = options || {};
+ return colorFinder.findColor(img, _.parseColor(color), _.parseThreshold(opt), _.buildRegion(img, opt));
+ },
+ findColorInRegion(img, color, x, y, width, height, threshold) {
+ return this.findColor(img, color, {
+ region: [x, y, width, height],
+ threshold: threshold,
+ });
+ },
+ findColorEquals(img, color, x, y, width, height) {
+ return this.findColor(img, color, {
+ region: [x, y, width, height],
+ threshold: 0,
+ });
+ },
+ findAllPointsForColor(img, color, options) {
+ _.initIfNeeded();
+ let opt = options || {};
+ return _.toPointArray(colorFinder.findAllPointsForColor(img, _.parseColor(color), _.parseThreshold(opt), _.buildRegion(img, opt)));
+ },
+ findMultiColors(img, firstColor, paths, options) {
+ _.initIfNeeded();
+ let list = java.lang.reflect.Array.newInstance(java.lang.Integer.TYPE, paths.length * 3);
+ for (let i = 0; i < paths.length; i++) {
+ let [x, y, color] = paths[i];
+ list[i * 3] = x;
+ list[i * 3 + 1] = y;
+ list[i * 3 + 2] = _.parseColor(color);
+ }
+ let opt = options || {};
+ return colorFinder.findMultiColors(img, _.parseColor(firstColor), _.parseThreshold(opt), _.buildRegion(img, opt), list);
+ },
+ findImage(img, template, options) {
+ _.initIfNeeded();
+ let opt = options || {};
+ return rtImages.findImage(img, template,
+ _.parseWeakThreshold(opt, 0.6),
+ _.parseThreshold(opt, 0.9),
+ _.buildRegion(img, opt),
+ _.parseNumber(opt.level, -1));
+ },
+ matchTemplate(img, template, options) {
+ _.initIfNeeded();
+ let opt = options || {};
+ return new MatchingResult(rtImages.matchTemplate(img, template,
+ _.parseWeakThreshold(opt, 0.6),
+ _.parseThreshold(opt, 0.9),
+ _.buildRegion(img, opt),
+ _.parseNumber(opt.level, -1),
+ _.parseNumber(opt.max, 5)));
+ },
+ findImageInRegion(img, template, x, y, width, height, threshold) {
+ return this.findImage(img, template, {
+ region: [x, y, width, height],
+ threshold: threshold,
+ });
+ },
+ fromBase64(base64) {
+ return rtImages.fromBase64(base64);
+ },
+ toBase64(img, format, quality) {
+ return rtImages.toBase64(img, format || 'png', _.parseQuality(quality));
+ },
+ fromBytes(bytes) {
+ return rtImages.fromBytes(bytes);
+ },
+ toBytes(img, format, quality) {
+ return rtImages.toBytes(img, format || 'png', _.parseQuality(quality));
+ },
+ readPixels(path) {
+ let img = images.read(path);
+ let bitmap = img.getBitmap();
+ let w = bitmap.getWidth();
+ let h = bitmap.getHeight();
+ let pixels = util.java.array('int', w * h);
+ bitmap.getPixels(pixels, 0, w, 0, 0, w, h);
+ img.recycle();
+ return {
+ data: pixels,
+ width: w,
+ height: h,
+ };
+ },
+ matToImage(img) {
+ _.initIfNeeded();
+ return Image.ofMat(img);
+ },
};
- images.findMultiColors = function (img, firstColor, paths, options) {
- initIfNeeded();
- options = options || {};
- firstColor = parseColor(firstColor);
- let list = java.lang.reflect.Array.newInstance(java.lang.Integer.TYPE, paths.length * 3);
- for (let i = 0; i < paths.length; i++) {
- let p = paths[i];
- list[i * 3] = p[0];
- list[i * 3 + 1] = p[1];
- list[i * 3 + 2] = parseColor(p[2]);
- }
- let region = options.region ? buildRegion(options.region, img) : null;
- let threshold = options.threshold === undefined ? DEF_COLOR_THRESHOLD : options.threshold;
- return colorFinder.findMultiColors(img, firstColor, threshold, region, list);
- };
-
- images.findImage = function (img, template, options) {
- initIfNeeded();
- options = options || {};
- let threshold = options.threshold || 0.9;
- let maxLevel = -1;
- if (typeof options.level === 'number') {
- maxLevel = options.level;
- }
- let weakThreshold = options.weakThreshold || 0.6;
- if (options.region) {
- return rtImages.findImage(img, template, weakThreshold, threshold, buildRegion(options.region, img), maxLevel);
- } else {
- return rtImages.findImage(img, template, weakThreshold, threshold, null, maxLevel);
- }
- };
-
- images.matchTemplate = function (img, template, options) {
- initIfNeeded();
- options = options || {};
- let threshold = options.threshold || 0.9;
- let maxLevel = -1;
- if (typeof options.level === 'number') {
- maxLevel = options.level;
- }
- let max = options.max || 5;
- let weakThreshold = options.weakThreshold || 0.6;
- let result;
- if (options.region) {
- result = rtImages.matchTemplate(img, template, weakThreshold, threshold, buildRegion(options.region, img), maxLevel, max);
- } else {
- result = rtImages.matchTemplate(img, template, weakThreshold, threshold, null, maxLevel, max);
- }
- return new MatchingResult(result);
- };
-
- images.findImageInRegion = function (img, template, x, y, width, height, threshold) {
- return images.findImage(img, template, {
- region: [x, y, width, height],
- threshold: threshold,
- });
- };
-
- images.fromBase64 = function (base64) {
- return rtImages.fromBase64(base64);
- };
-
- images.toBase64 = function (img, format, quality) {
- format = format || 'png';
- quality = quality === undefined ? 100 : quality;
- return rtImages.toBase64(img, format, quality);
- };
-
- images.fromBytes = function (bytes) {
- return rtImages.fromBytes(bytes);
- };
-
- images.toBytes = function (img, format, quality) {
- format = format || 'png';
- quality = quality === undefined ? 100 : quality;
- return rtImages.toBytes(img, format, quality);
- };
-
- images.readPixels = function (path) {
- let img = images.read(path);
- let bitmap = img.getBitmap();
- let w = bitmap.getWidth();
- let h = bitmap.getHeight();
- let pixels = util.java.array('int', w * h);
- bitmap.getPixels(pixels, 0, w, 0, 0, w, h);
- img.recycle();
- return {
- data: pixels,
- width: w,
- height: h,
- };
- };
-
- images.matToImage = function (img) {
- initIfNeeded();
- return Image.ofMat(img);
- };
+ Object.assign(images, images_ext);
util.__assignFunctions__(rtImages, images, ['captureScreen', 'read', 'copy', 'load', 'clip', 'pixel']);
diff --git a/autojs/src/main/java/com/stardust/autojs/core/accessibility/SimpleActionAutomator.kt b/autojs/src/main/java/com/stardust/autojs/core/accessibility/SimpleActionAutomator.kt
index 4912bfda..e0047d1a 100644
--- a/autojs/src/main/java/com/stardust/autojs/core/accessibility/SimpleActionAutomator.kt
+++ b/autojs/src/main/java/com/stardust/autojs/core/accessibility/SimpleActionAutomator.kt
@@ -6,7 +6,6 @@ import android.graphics.Rect
import android.os.Build
import android.os.Handler
import android.view.accessibility.AccessibilityNodeInfo
-import androidx.annotation.RequiresApi
import com.stardust.autojs.annotation.ScriptInterface
import com.stardust.autojs.runtime.ScriptRuntime
import com.stardust.autojs.runtime.accessibility.AccessibilityConfig
@@ -41,7 +40,6 @@ class SimpleActionAutomator(private val mAccessibilityBridge: AccessibilityBridg
return ActionTarget.BoundsActionTarget(Rect(left, top, right, bottom))
}
- @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
@ScriptInterface
fun editable(i: Int): ActionTarget {
ScriptRuntime.requiresApi(Build.VERSION_CODES.LOLLIPOP)
@@ -104,14 +102,12 @@ class SimpleActionAutomator(private val mAccessibilityBridge: AccessibilityBridg
}
@ScriptInterface
- @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
fun setText(target: ActionTarget, text: String): Boolean {
ScriptRuntime.requiresApi(Build.VERSION_CODES.LOLLIPOP)
return performAction(target.createAction(AccessibilityNodeInfo.ACTION_SET_TEXT, text))
}
@ScriptInterface
- @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
fun appendText(target: ActionTarget, text: String): Boolean {
ScriptRuntime.requiresApi(Build.VERSION_CODES.LOLLIPOP)
return performAction(target.createAction(UiObject.ACTION_APPEND_TEXT, text))
@@ -128,7 +124,6 @@ class SimpleActionAutomator(private val mAccessibilityBridge: AccessibilityBridg
}
@ScriptInterface
- @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
fun powerDialog(): Boolean {
ScriptRuntime.requiresApi(Build.VERSION_CODES.LOLLIPOP)
return performGlobalAction(AccessibilityService.GLOBAL_ACTION_POWER_DIALOG)
@@ -150,33 +145,27 @@ class SimpleActionAutomator(private val mAccessibilityBridge: AccessibilityBridg
}
@ScriptInterface
- @RequiresApi(api = Build.VERSION_CODES.N)
fun splitScreen(): Boolean {
return performGlobalAction(AccessibilityService.GLOBAL_ACTION_TOGGLE_SPLIT_SCREEN)
}
@ScriptInterface
- @RequiresApi(api = Build.VERSION_CODES.N)
fun gesture(start: Long, duration: Long, vararg points: IntArray): Boolean {
prepareForGesture()
return mGlobalActionAutomator.gesture(start, duration, *points)
}
- @RequiresApi(api = Build.VERSION_CODES.N)
fun gestureAsync(start: Long, duration: Long, vararg points: IntArray) {
prepareForGesture()
mGlobalActionAutomator.gestureAsync(start, duration, *points)
}
- @RequiresApi(api = Build.VERSION_CODES.N)
fun gestures(strokes: Any): Boolean {
prepareForGesture()
@Suppress("UNCHECKED_CAST")
return mGlobalActionAutomator.gestures(*strokes as Array)
}
- //如果这里用GestureDescription.StrokeDescription[]为参数,安卓7.0以下会因为找不到这个类而报错
- @RequiresApi(api = Build.VERSION_CODES.N)
fun gesturesAsync(strokes: Any) {
prepareForGesture()
@Suppress("UNCHECKED_CAST")
@@ -195,28 +184,24 @@ class SimpleActionAutomator(private val mAccessibilityBridge: AccessibilityBridg
}
@ScriptInterface
- @RequiresApi(api = Build.VERSION_CODES.N)
fun click(x: Int, y: Int): Boolean {
prepareForGesture()
return mGlobalActionAutomator.click(x, y)
}
@ScriptInterface
- @RequiresApi(api = Build.VERSION_CODES.N)
fun press(x: Int, y: Int, delay: Int): Boolean {
prepareForGesture()
return mGlobalActionAutomator.press(x, y, delay)
}
@ScriptInterface
- @RequiresApi(api = Build.VERSION_CODES.N)
fun longClick(x: Int, y: Int): Boolean {
prepareForGesture()
return mGlobalActionAutomator.longClick(x, y)
}
@ScriptInterface
- @RequiresApi(api = Build.VERSION_CODES.N)
fun swipe(x1: Int, y1: Int, x2: Int, y2: Int, delay: Int): Boolean {
prepareForGesture()
return mGlobalActionAutomator.swipe(x1, y1, x2, y2, delay.toLong())
@@ -228,7 +213,6 @@ class SimpleActionAutomator(private val mAccessibilityBridge: AccessibilityBridg
return service.performGlobalAction(action)
}
- @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
@ScriptInterface
fun paste(target: ActionTarget): Boolean {
ScriptRuntime.requiresApi(18)
@@ -244,7 +228,7 @@ class SimpleActionAutomator(private val mAccessibilityBridge: AccessibilityBridg
if (AccessibilityConfig.isUnintendedGuardEnabled() && isRunningPackageSelf) {
return false
}
- val roots = mAccessibilityBridge.windowRoots().filter { it != null }
+ val roots = mAccessibilityBridge.windowRoots().filterNotNull()
if (roots.isEmpty())
return false
var succeed = true
diff --git a/autojs/src/main/java/com/stardust/autojs/core/image/ColorFinder.java b/autojs/src/main/java/com/stardust/autojs/core/image/ColorFinder.java
index d5dba865..46ca22cc 100644
--- a/autojs/src/main/java/com/stardust/autojs/core/image/ColorFinder.java
+++ b/autojs/src/main/java/com/stardust/autojs/core/image/ColorFinder.java
@@ -2,6 +2,7 @@ package com.stardust.autojs.core.image;
import android.graphics.Color;
import android.os.Build;
+
import androidx.annotation.RequiresApi;
import com.stardust.autojs.core.opencv.MatOfPoint;
@@ -23,7 +24,7 @@ import org.opencv.core.Scalar;
@RequiresApi(api = Build.VERSION_CODES.KITKAT)
public class ColorFinder {
- private ScreenMetrics mScreenMetrics;
+ private final ScreenMetrics mScreenMetrics;
public ColorFinder(ScreenMetrics screenMetrics) {
mScreenMetrics = screenMetrics;
@@ -56,7 +57,6 @@ public class ColorFinder {
}
public Point[] findAllPointsForColor(ImageWrapper image, int color, int threshold, Rect rect) {
-
MatOfPoint matOfPoint = findColorInner(image, color, threshold, rect);
if (matOfPoint == null) {
return new Point[0];
@@ -64,9 +64,9 @@ public class ColorFinder {
Point[] points = matOfPoint.toArray();
OpenCVHelper.release(matOfPoint);
if (rect != null) {
- for (int i = 0; i < points.length; i++) {
- points[i].x = mScreenMetrics.scaleX((int) (points[i].x + rect.x));
- points[i].y = mScreenMetrics.scaleX((int) (points[i].y + rect.y));
+ for (Point point : points) {
+ point.x = mScreenMetrics.scaleX((int) (point.x + rect.x));
+ point.y = mScreenMetrics.scaleX((int) (point.y + rect.y));
}
}
return points;
diff --git a/autojs/src/main/java/com/stardust/autojs/core/ui/inflater/DynamicLayoutInflater.java b/autojs/src/main/java/com/stardust/autojs/core/ui/inflater/DynamicLayoutInflater.java
index 37c0b4fb..3af92c73 100644
--- a/autojs/src/main/java/com/stardust/autojs/core/ui/inflater/DynamicLayoutInflater.java
+++ b/autojs/src/main/java/com/stardust/autojs/core/ui/inflater/DynamicLayoutInflater.java
@@ -1,9 +1,6 @@
package com.stardust.autojs.core.ui.inflater;
import android.content.Context;
-import android.os.Build;
-import androidx.annotation.NonNull;
-import androidx.annotation.Nullable;
import android.util.AttributeSet;
import android.util.Log;
import android.view.InflateException;
@@ -19,6 +16,9 @@ import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.TimePicker;
+import androidx.annotation.NonNull;
+import androidx.annotation.Nullable;
+
import com.google.android.material.appbar.AppBarLayout;
import com.stardust.autojs.core.ui.inflater.inflaters.AppBarInflater;
import com.stardust.autojs.core.ui.inflater.inflaters.BaseViewInflater;
@@ -64,7 +64,7 @@ public class DynamicLayoutInflater {
private Map> mViewAttrSetters = new HashMap<>();
private Map> mViewCreators = new HashMap<>();
private Context mContext;
- private ResourceParser mResourceParser;
+ private final ResourceParser mResourceParser;
@NonNull
private LayoutInflaterDelegate mLayoutInflaterDelegate = LayoutInflaterDelegate.NO_OP;
private int mInflateFlags;
@@ -74,7 +74,7 @@ public class DynamicLayoutInflater {
registerViewAttrSetters();
}
- @SuppressWarnings("IncompleteCopyConstructor")
+ @SuppressWarnings("CopyConstructorMissesField")
public DynamicLayoutInflater(DynamicLayoutInflater inflater) {
this.mResourceParser = inflater.mResourceParser;
this.mContext = inflater.mContext;
@@ -159,7 +159,7 @@ public class DynamicLayoutInflater {
return mLayoutInflaterDelegate.afterInflation(context, doInflation(context, xml, parent, attachToParent), xml, parent);
}
- public InflateContext newInflateContext(){
+ public InflateContext newInflateContext() {
return new InflateContext();
}
@@ -291,7 +291,7 @@ public class DynamicLayoutInflater {
}
Class> clazz = Class.forName(name);
String style = attrs.get("style");
- if (style == null || Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
+ if (style == null) {
return (View) clazz.getConstructor(Context.class).newInstance(mContext);
} else {
int styleRes = Res.parseStyle(mContext, style);
@@ -316,7 +316,6 @@ public class DynamicLayoutInflater {
return attributes;
}
- @SuppressWarnings("unchecked")
protected void applyAttributes(InflateContext context, View view, ViewInflater setter, Map attrs, @Nullable ViewGroup parent) {
if (setter != null) {
for (Map.Entry entry : attrs.entrySet()) {
diff --git a/autojs/src/main/java/com/stardust/autojs/core/ui/widget/JsTextView.java b/autojs/src/main/java/com/stardust/autojs/core/ui/widget/JsTextView.java
index 9341b1d8..5695915f 100644
--- a/autojs/src/main/java/com/stardust/autojs/core/ui/widget/JsTextView.java
+++ b/autojs/src/main/java/com/stardust/autojs/core/ui/widget/JsTextView.java
@@ -1,18 +1,15 @@
package com.stardust.autojs.core.ui.widget;
-import android.annotation.SuppressLint;
import android.content.Context;
+import android.util.AttributeSet;
import androidx.annotation.Nullable;
-import androidx.annotation.RequiresApi;
import androidx.appcompat.widget.AppCompatTextView;
-import android.util.AttributeSet;
/**
* Created by Stardust on 2017/5/15.
*/
-@SuppressLint("AppCompatCustomView")
public class JsTextView extends AppCompatTextView {
public JsTextView(Context context) {
diff --git a/autojs/src/main/java/com/stardust/autojs/core/ui/widget/JsTextViewLegacy.java b/autojs/src/main/java/com/stardust/autojs/core/ui/widget/JsTextViewLegacy.java
new file mode 100644
index 00000000..4665bdea
--- /dev/null
+++ b/autojs/src/main/java/com/stardust/autojs/core/ui/widget/JsTextViewLegacy.java
@@ -0,0 +1,30 @@
+package com.stardust.autojs.core.ui.widget;
+
+import android.content.Context;
+import android.util.AttributeSet;
+
+import androidx.annotation.Nullable;
+import androidx.appcompatlegacy.widget.AppCompatTextView;
+
+public class JsTextViewLegacy extends AppCompatTextView {
+
+ public JsTextViewLegacy(Context context) {
+ super(context);
+ }
+
+ public JsTextViewLegacy(Context context, @Nullable AttributeSet attrs) {
+ super(context, attrs);
+ }
+
+ public JsTextViewLegacy(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
+ super(context, attrs, defStyleAttr);
+ }
+
+ public String text() {
+ return getText().toString();
+ }
+
+ public void text(CharSequence text) {
+ setText(text);
+ }
+}
diff --git a/autojs/src/main/java/com/stardust/autojs/core/ui/xml/XmlConverter.java b/autojs/src/main/java/com/stardust/autojs/core/ui/xml/XmlConverter.java
index a39de109..439dd8c6 100644
--- a/autojs/src/main/java/com/stardust/autojs/core/ui/xml/XmlConverter.java
+++ b/autojs/src/main/java/com/stardust/autojs/core/ui/xml/XmlConverter.java
@@ -1,9 +1,6 @@
package com.stardust.autojs.core.ui.xml;
-import androidx.appcompat.widget.Toolbar;
-import androidx.cardview.widget.CardView;
-import androidx.drawerlayout.widget.DrawerLayout;
-
+import android.os.Build;
import android.widget.CheckBox;
import android.widget.DatePicker;
import android.widget.ProgressBar;
@@ -13,6 +10,9 @@ import android.widget.ScrollView;
import android.widget.SeekBar;
import android.widget.TimePicker;
+import androidx.cardview.widget.CardView;
+import androidx.drawerlayout.widget.DrawerLayout;
+
import com.google.android.material.appbar.AppBarLayout;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.stardust.autojs.core.graphics.ScriptCanvasView;
@@ -27,6 +27,7 @@ import com.stardust.autojs.core.ui.widget.JsRelativeLayout;
import com.stardust.autojs.core.ui.widget.JsSpinner;
import com.stardust.autojs.core.ui.widget.JsTabLayout;
import com.stardust.autojs.core.ui.widget.JsTextView;
+import com.stardust.autojs.core.ui.widget.JsTextViewLegacy;
import com.stardust.autojs.core.ui.widget.JsToolbar;
import com.stardust.autojs.core.ui.widget.JsViewPager;
import com.stardust.autojs.core.ui.widget.JsWebView;
@@ -59,7 +60,9 @@ public class XmlConverter {
.map("horizontal", JsLinearLayout.class.getName())
.map("relative", JsRelativeLayout.class.getName())
.map("button", JsButton.class.getName())
- .map("text", JsTextView.class.getName())
+ .map("text", Build.VERSION.SDK_INT < Build.VERSION_CODES.O
+ ? JsTextViewLegacy.class.getName()
+ : JsTextView.class.getName())
.map("input", JsEditText.class.getName())
.map("img", JsImageView.class.getName())
.map("datepicker", DatePicker.class.getName())
diff --git a/autojs/src/main/java/com/stardust/autojs/runtime/ScriptRuntime.java b/autojs/src/main/java/com/stardust/autojs/runtime/ScriptRuntime.java
index 8acda87d..5c713f77 100644
--- a/autojs/src/main/java/com/stardust/autojs/runtime/ScriptRuntime.java
+++ b/autojs/src/main/java/com/stardust/autojs/runtime/ScriptRuntime.java
@@ -332,9 +332,6 @@ public class ScriptRuntime {
}
public void requestPermissions(String[] permissions) {
- if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
- return;
- }
Context context = uiHandler.getContext();
permissions = Permissions.getPermissionsNeedToRequest(context, permissions);
if (permissions.length == 0)
@@ -412,9 +409,7 @@ public class ScriptRuntime {
mRootShell = null;
mShellSupplier = null;
});
- if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
- ignoresException(images::releaseScreenCapturer);
- }
+ ignoresException(images::releaseScreenCapturer);
ignoresException(sensors::unregisterAll);
ignoresException(timers::recycle);
ignoresException(ui::recycle);
@@ -456,8 +451,7 @@ public class ScriptRuntime {
public static String getStackTrace(Throwable e, boolean printJavaStackTrace) {
String message = e.getMessage();
StringBuilder scriptTrace = new StringBuilder(message == null ? "" : message + "\n");
- if (e instanceof RhinoException) {
- RhinoException rhinoException = (RhinoException) e;
+ if (e instanceof RhinoException rhinoException) {
scriptTrace.append(rhinoException.details()).append("\n");
for (ScriptStackElement element : rhinoException.getScriptStack()) {
element.renderV8Style(scriptTrace);
diff --git a/automator/build.gradle b/automator/build.gradle
index a74f5da8..4fbd0a0f 100644
--- a/automator/build.gradle
+++ b/automator/build.gradle
@@ -1,5 +1,5 @@
-apply plugin: "com.android.library"
-apply plugin: "kotlin-android"
+apply plugin: 'com.android.library'
+apply plugin: 'kotlin-android'
tasks.withType(org.jetbrains.kotlin.gradle.tasks.KotlinCompile).all {
kotlinOptions {
@@ -8,13 +8,13 @@ tasks.withType(org.jetbrains.kotlin.gradle.tasks.KotlinCompile).all {
}
android {
- compileSdkVersion versions.compile
+ compileSdkVersion versions.project.compile
defaultConfig {
- minSdkVersion versions.mini
- targetSdkVersion versions.target
+ minSdkVersion versions.project.mini
+ targetSdkVersion versions.project.target
- testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
+ testInstrumentationRunner 'androidx.test.runner.AndroidJUnitRunner'
}
compileOptions {
@@ -27,7 +27,7 @@ android {
buildTypes {
release {
minifyEnabled false
- proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
+ proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
@@ -37,7 +37,7 @@ repositories {
}
dependencies {
- testImplementation "junit:junit:${junitVer}"
- implementation "androidx.appcompat:appcompat:1.4.0"
- api project(":common")
+ testImplementation "junit:junit:${versions.junit}"
+
+ api project(':common')
}
diff --git a/build.gradle b/build.gradle
index 21032041..abde686f 100644
--- a/build.gradle
+++ b/build.gradle
@@ -4,39 +4,47 @@ import org.apache.groovy.json.internal.LazyMap
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
- ext.kotlinVer = "1.6.10"
- ext.junitVer = "4.13.2"
+ ext.versions = [
+ 'junit' : '4.13.2',
+ 'glide' : '4.12.0',
+ 'kotlin' : '1.6.10',
+ 'leakcanary' : '2.8.1',
+ 'annotations' : '4.8.0',
+ 'butterKnife' : '10.2.3',
+ // TODO upgrade to 3.x (more difficult than expected)
+ 'materialDialogs': '0.9.6.0',
+ ]
repositories {
mavenCentral()
google()
- maven { url "https://maven.aliyun.com/repository/central" }
- maven { url "https://maven.aliyun.com/repository/google" }
- maven { url "https://maven.aliyun.com/repository/gradle-plugin" }
- maven { url "https://maven.aliyun.com/repository/jcenter" }
- maven { url "https://maven.aliyun.com/repository/public" }
- maven { url "https://repo.huaweicloud.com/repository/maven" }
+ maven { url 'https://maven.aliyun.com/repository/central' }
+ maven { url 'https://maven.aliyun.com/repository/google' }
+ maven { url 'https://maven.aliyun.com/repository/gradle-plugin' }
+ maven { url 'https://maven.aliyun.com/repository/jcenter' }
+ maven { url 'https://maven.aliyun.com/repository/public' }
+ maven { url 'https://repo.huaweicloud.com/repository/maven' }
}
dependencies {
- classpath "com.android.tools.build:gradle:7.2.0-alpha06"
+ classpath 'com.android.tools.build:gradle:7.2.0-beta01'
- classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:${kotlinVer}"
- classpath "com.jakewharton:butterknife-gradle-plugin:10.2.1"
+ classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:${versions.kotlin}"
+ classpath 'com.jakewharton:butterknife-gradle-plugin:10.2.1'
- classpath "org.codehaus.groovy:groovy-json:3.0.8"
+ classpath 'org.codehaus.groovy:groovy-json:3.0.8'
}
}
allprojects {
repositories {
- maven { url "https://jitpack.io" }
- maven { url "https://oss.sonatype.org/content/repositories/snapshots/" }
+ maven { url 'https://jitpack.io' }
+ maven { url 'https://oss.sonatype.org/content/repositories/snapshots/' }
mavenCentral()
- maven { url "https://maven.aliyun.com/repository/central" }
- maven { url "https://maven.aliyun.com/repository/google" }
- maven { url "https://maven.aliyun.com/repository/gradle-plugin" }
- maven { url "https://maven.aliyun.com/repository/jcenter" }
- maven { url "https://maven.aliyun.com/repository/public" }
- maven { url "https://repo.huaweicloud.com/repository/maven" }
+ maven { url 'https://maven.aliyun.com/repository/central' }
+ maven { url 'https://maven.aliyun.com/repository/google' }
+ maven { url 'https://maven.aliyun.com/repository/gradle-plugin' }
+ maven { url 'https://maven.aliyun.com/repository/jcenter' }
+ maven { url 'https://maven.aliyun.com/repository/public' }
+ maven { url 'https://repo.huaweicloud.com/repository/maven' }
google()
}
}
@@ -45,6 +53,4 @@ task clean(type: Delete) {
delete rootProject.buildDir
}
-ext {
- versions = new JsonSlurper().parse(file("./project-versions.json")) as LazyMap
-}
+ext.versions.project = new JsonSlurper().parse(file("./project-versions.json")) as LazyMap
\ No newline at end of file
diff --git a/common/build.gradle b/common/build.gradle
index ee08221e..5396114e 100644
--- a/common/build.gradle
+++ b/common/build.gradle
@@ -1,8 +1,8 @@
-apply plugin: "com.android.library"
-apply plugin: "kotlin-android"
+apply plugin: 'com.android.library'
+apply plugin: 'kotlin-android'
// tasks.withType(JavaCompile) {
-// options.compilerArgs << "-Xlint:deprecation"
+// options.compilerArgs << '-Xlint:deprecation'
// }
tasks.withType(org.jetbrains.kotlin.gradle.tasks.KotlinCompile).all {
@@ -12,19 +12,19 @@ tasks.withType(org.jetbrains.kotlin.gradle.tasks.KotlinCompile).all {
}
android {
- compileSdkVersion versions.compile
+ compileSdkVersion versions.project.compile
defaultConfig {
- minSdkVersion versions.mini
- targetSdkVersion versions.target
+ minSdkVersion versions.project.mini
+ targetSdkVersion versions.project.target
- testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
+ testInstrumentationRunner 'androidx.test.runner.AndroidJUnitRunner'
}
buildTypes {
release {
minifyEnabled false
- proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
+ proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
lintOptions {
@@ -37,33 +37,51 @@ android {
}
dependencies {
- testImplementation "junit:junit:${junitVer}"
+ testImplementation "junit:junit:${versions.junit}"
// Kotlin
- api "org.jetbrains.kotlin:kotlin-stdlib-jdk7:${kotlinVer}"
+ // noinspection DifferentStdlibGradleVersion
+ api "org.jetbrains.kotlin:kotlin-stdlib-jdk7:${versions.kotlin}"
+
+ // Android supports
+ api 'com.google.android.material:material:1.6.0-alpha02'
+
+ // Material Dialogs
+ api "com.afollestad.material-dialogs:core:${versions.materialDialogs}"
+ api "com.afollestad.material-dialogs:commons:${versions.materialDialogs}"
+
+ // Glide
+ api "com.github.bumptech.glide:glide:${versions.glide}"
// RoundedImageView
- api "com.makeramen:roundedimageview:2.3.0"
+ api 'com.makeramen:roundedimageview:2.3.0'
// EventBus
- api "org.greenrobot:eventbus:3.3.1"
+ api 'org.greenrobot:eventbus:3.3.1'
// Annotation
- api "androidx.annotation:annotation:1.3.0"
+ api 'androidx.annotation:annotation:1.3.0'
// Preference
- api "androidx.preference:preference-ktx:1.1.1"
+ api 'androidx.preference:preference-ktx:1.2.0'
// RootShell
- api "com.github.Stericson:RootShell:1.6"
+ api 'com.github.Stericson:RootShell:1.6'
// JDeferred
- api "org.jdeferred:jdeferred-android-aar:1.2.6"
+ api 'org.jdeferred:jdeferred-android-aar:1.2.6'
// Auto.js
- api "com.github.hyb1996:settingscompat:1.1.5"
- api "com.github.hyb1996:EnhancedFloaty:0.31"
+ api 'com.github.hyb1996:settingscompat:1.1.5'
+ api 'com.github.hyb1996:EnhancedFloaty:0.31'
+
+ // AppCompat
+ api 'androidx.appcompat:appcompat:1.4.1'
+ api project(':libs:androidx.appcompat-1.0.2')
+
+ // OpenCV
+ api project(':libs:org.opencv-4.5.4')
// Rhino
- api project(":libs:org.mozilla.rhino-1.7.14")
+ api project(':libs:org.mozilla.rhino-1.7.14')
}
diff --git a/common/src/main/java/com/stardust/util/SdkVersionUtil.java b/common/src/main/java/com/stardust/util/SdkVersionUtil.java
index d66be0a7..35ba7793 100644
--- a/common/src/main/java/com/stardust/util/SdkVersionUtil.java
+++ b/common/src/main/java/com/stardust/util/SdkVersionUtil.java
@@ -10,15 +10,14 @@ public class SdkVersionUtil {
"1.0", "1.1", "1.5", "1.6", "2.0", "2.0.1", "2.1.x", "2.2.x",
"2.3", "2.3.3", "3.0.x", "3.1.x", "3.2", "4.0", "4.0.3", "4.1",
"4.2", "4.3", "4.4.2", "4.4W", "5.0", "5.1", "6.0", "7.0", "7.1",
- "8.0"
+ "8.0", "8.1", "9", "10", "11", "12"
};
public static String sdkIntToString(int i) {
- if (i > 26) {
+ if (i > 31) {
return "Unknown";
}
return SDK_VERSIONS[i - 1];
}
-
}
diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties
index 35475a35..d8545bd0 100644
--- a/gradle/wrapper/gradle-wrapper.properties
+++ b/gradle/wrapper/gradle-wrapper.properties
@@ -1,6 +1,6 @@
-#Thu Dec 30 20:07:37 CST 2021
+#Sat Feb 05 15:16:06 CST 2022
distributionBase=GRADLE_USER_HOME
-distributionUrl=https\://services.gradle.org/distributions/gradle-7.3.3-all.zip
+distributionUrl=https\://services.gradle.org/distributions/gradle-7.4-rc-2-bin.zip
distributionPath=wrapper/dists
zipStorePath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
diff --git a/inrt/build.gradle b/inrt/build.gradle
index 8c5428f4..d90f7a8c 100644
--- a/inrt/build.gradle
+++ b/inrt/build.gradle
@@ -1,22 +1,22 @@
-apply plugin: "com.android.application"
-apply plugin: "kotlin-android"
+apply plugin: 'com.android.application'
+apply plugin: 'kotlin-android'
android {
- compileSdkVersion versions.compile
+ compileSdkVersion versions.project.compile
defaultConfig {
- applicationId "com.stardust.auojs.inrt"
- minSdkVersion versions.mini
- targetSdkVersion versions.target
- versionCode versions.appVersionCode
- versionName versions.appVersionName
- testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
+ applicationId 'com.stardust.auojs.inrt'
+ minSdkVersion versions.project.mini
+ targetSdkVersion versions.project.target
+ versionCode versions.project.appVersionCode
+ versionName versions.project.appVersionName
+ testInstrumentationRunner 'androidx.test.runner.AndroidJUnitRunner'
multiDexEnabled true
}
lintOptions {
abortOnError false
- disable "MissingTranslation"
- disable "ExtraTranslation"
+ disable 'MissingTranslation'
+ disable 'ExtraTranslation'
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_16
@@ -37,7 +37,7 @@ android {
reset()
// Specifies a list of ABIs that Gradle should create APKs for.
- include "armeabi-v7a"
+ include 'x86', 'armeabi-v7a'
// Specifies that we do not want to also generate a universal APK that includes all ABIs.
universalApk false
@@ -46,51 +46,51 @@ android {
buildTypes {
debug {
minifyEnabled false
- proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
+ proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
release {
minifyEnabled false
- proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
+ proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
def buildApkPluginForAbi(File pluginProjectDir, String abi) {
copy {
- from file("..\\app\\release\\")
- into new File(pluginProjectDir, "app\\src\\main\\assets")
- def fileName = "inrt-" + abi + "-release.apk"
+ from file('..\\app\\release\\')
+ into new File(pluginProjectDir, 'app\\src\\main\\assets')
+ def fileName = 'inrt-' + abi + '-release.apk'
include fileName
- rename fileName, "template.apk"
+ rename fileName, 'template.apk'
}
exec {
workingDir pluginProjectDir
- commandLine "gradlew.bat", "assembleRelease"
+ commandLine 'gradlew.bat', 'assembleRelease'
}
copy {
- from new File(pluginProjectDir, "app\\build\\outputs\\apk\\release")
- into file("..\\common\\release")
- def fileName = "打包插件-" + versions.appVersionName + "-release.apk"
+ from new File(pluginProjectDir, 'app\\build\\outputs\\apk\\release')
+ into file('..\\common\\release')
+ def fileName = '打包插件-' + versions.project.appVersionName + '-release.apk'
include fileName
- rename fileName, "打包插件-" + abi + "-" + versions.appVersionName + "-release.apk"
+ rename fileName, '打包插件-' + abi + '-' + versions.project.appVersionName + '-release.apk'
}
}
task buildApkPlugin {
doLast {
- def pluginProjectDirPath = "..\\..\\AutoJsApkBuilderPlugin"
+ def pluginProjectDirPath = '..\\..\\AutoJsApkBuilderPlugin'
def pluginProjectDir = file(pluginProjectDirPath)
if (!pluginProjectDir.exists() || !pluginProjectDir.isDirectory()) {
- println "pluginProjectDir not exists"
+ println 'pluginProjectDir not exists'
return
}
- buildApkPluginForAbi(pluginProjectDir, "armeabi-v7a")
+ buildApkPluginForAbi(pluginProjectDir, 'armeabi-v7a')
}
}
tasks.whenTaskAdded { task ->
- if (task.name == "assembleRelease") {
- task.finalizedBy "buildApkPlugin"
+ if (task.name == 'assembleRelease') {
+ task.finalizedBy 'buildApkPlugin'
}
}
@@ -105,14 +105,9 @@ repositories {
}
dependencies {
- testImplementation "junit:junit:${junitVer}"
+ testImplementation "junit:junit:${versions.junit}"
- implementation "com.github.bumptech.glide:glide:4.12.0"
-
- implementation project(":libs:org.mozilla.rhino-1.7.14")
- implementation project(":libs:org.opencv-4.5.4")
-
- implementation project(":automator")
- implementation project(":common")
- implementation project(":autojs")
+ implementation project(':automator')
+ implementation project(':common')
+ implementation project(':autojs')
}
diff --git a/libs/androidx.appcompat-1.0.2/appcompatlegacy.aar b/libs/androidx.appcompat-1.0.2/appcompatlegacy.aar
new file mode 100644
index 00000000..a952bea6
Binary files /dev/null and b/libs/androidx.appcompat-1.0.2/appcompatlegacy.aar differ
diff --git a/libs/androidx.appcompat-1.0.2/build.gradle b/libs/androidx.appcompat-1.0.2/build.gradle
new file mode 100644
index 00000000..f8269f36
--- /dev/null
+++ b/libs/androidx.appcompat-1.0.2/build.gradle
@@ -0,0 +1,2 @@
+configurations.maybeCreate('default')
+artifacts.add('default', file('appcompatlegacy.aar'))
\ No newline at end of file
diff --git a/libs/com.android.dx-1.7.0/build.gradle b/libs/com.android.dx-1.7.0/build.gradle
index f5c271b6..bc155dc8 100644
--- a/libs/com.android.dx-1.7.0/build.gradle
+++ b/libs/com.android.dx-1.7.0/build.gradle
@@ -1,2 +1,2 @@
-configurations.maybeCreate("default")
-artifacts.add("default", file("dx.jar"))
\ No newline at end of file
+configurations.maybeCreate('default')
+artifacts.add('default', file('dx.jar'))
\ No newline at end of file
diff --git a/libs/com.tencent.bugly.crashreport-2.6.6/build.gradle b/libs/com.tencent.bugly.crashreport-2.6.6/build.gradle
index 50395f95..5d7b73f7 100644
--- a/libs/com.tencent.bugly.crashreport-2.6.6/build.gradle
+++ b/libs/com.tencent.bugly.crashreport-2.6.6/build.gradle
@@ -1,2 +1,2 @@
-configurations.maybeCreate("default")
-artifacts.add("default", file("crashreport-2.6.6.aar"))
\ No newline at end of file
+configurations.maybeCreate('default')
+artifacts.add('default', file('crashreport-2.6.6.aar'))
\ No newline at end of file
diff --git a/libs/jackpal.androidterm-1.0.70/build.gradle b/libs/jackpal.androidterm-1.0.70/build.gradle
index 5269ce81..52c57d72 100644
--- a/libs/jackpal.androidterm-1.0.70/build.gradle
+++ b/libs/jackpal.androidterm-1.0.70/build.gradle
@@ -1,2 +1,2 @@
-configurations.maybeCreate("default")
-artifacts.add("default", file("term-debug.aar"))
\ No newline at end of file
+configurations.maybeCreate('default')
+artifacts.add('default', file('term-debug.aar'))
\ No newline at end of file
diff --git a/libs/jackpal.androidterm.emulatorview-1.0.42/build.gradle b/libs/jackpal.androidterm.emulatorview-1.0.42/build.gradle
index 20411115..66aeed8e 100644
--- a/libs/jackpal.androidterm.emulatorview-1.0.42/build.gradle
+++ b/libs/jackpal.androidterm.emulatorview-1.0.42/build.gradle
@@ -1,2 +1,2 @@
-configurations.maybeCreate("default")
-artifacts.add("default", file("emulatorview-release.aar"))
\ No newline at end of file
+configurations.maybeCreate('default')
+artifacts.add('default', file('emulatorview-release.aar'))
\ No newline at end of file
diff --git a/libs/jackpal.androidterm.libtermexec-1.0/build.gradle b/libs/jackpal.androidterm.libtermexec-1.0/build.gradle
index 7273945a..ca427f4b 100644
--- a/libs/jackpal.androidterm.libtermexec-1.0/build.gradle
+++ b/libs/jackpal.androidterm.libtermexec-1.0/build.gradle
@@ -1,2 +1,2 @@
-configurations.maybeCreate("default")
-artifacts.add("default", file("libtermexec-release.aar"))
\ No newline at end of file
+configurations.maybeCreate('default')
+artifacts.add('default', file('libtermexec-release.aar'))
\ No newline at end of file
diff --git a/libs/org.mozilla.rhino-1.7.14/build.gradle b/libs/org.mozilla.rhino-1.7.14/build.gradle
index 650d5236..1386eba5 100644
--- a/libs/org.mozilla.rhino-1.7.14/build.gradle
+++ b/libs/org.mozilla.rhino-1.7.14/build.gradle
@@ -4,5 +4,5 @@ tasks.withType(org.jetbrains.kotlin.gradle.tasks.KotlinCompile).all {
}
}
-configurations.maybeCreate("default")
-artifacts.add("default", file("rhino-1.7.14.jar"))
\ No newline at end of file
+configurations.maybeCreate('default')
+artifacts.add('default', file('rhino-1.7.14.jar'))
\ No newline at end of file
diff --git a/libs/org.opencv-4.5.4/build.gradle b/libs/org.opencv-4.5.4/build.gradle
index eb6c3887..7d9e5391 100644
--- a/libs/org.opencv-4.5.4/build.gradle
+++ b/libs/org.opencv-4.5.4/build.gradle
@@ -1,2 +1,2 @@
-configurations.maybeCreate("default")
-artifacts.add("default", file("opencv-4.5.4.aar"))
\ No newline at end of file
+configurations.maybeCreate('default')
+artifacts.add('default', file('opencv-4.5.4.aar'))
\ No newline at end of file
diff --git a/project-versions.json b/project-versions.json
index 0cc6375c..64b960fe 100644
--- a/project-versions.json
+++ b/project-versions.json
@@ -1,7 +1,7 @@
{
- "appVersionCode": 694,
- "appVersionName": "6.0.1",
- "appSinceDate": "Jan 1, 2022",
+ "appVersionCode": 718,
+ "appVersionName": "6.0.2",
+ "appSinceDate": "Feb 5, 2022",
"target": 28,
"mini": 24,
"compile": 31
diff --git a/settings.gradle b/settings.gradle
index 5216b873..423c1061 100644
--- a/settings.gradle
+++ b/settings.gradle
@@ -1,9 +1,10 @@
include ':app', ':automator', ':common', ':autojs', ':inrt'
-include ":libs:com.android.dx-1.7.0"
-include ":libs:com.tencent.bugly.crashreport-2.6.6"
-include ":libs:jackpal.androidterm.emulatorview-1.0.42"
-include ":libs:jackpal.androidterm.libtermexec-1.0"
-include ":libs:jackpal.androidterm-1.0.70"
-include ":libs:org.mozilla.rhino-1.7.14"
-include ":libs:org.opencv-4.5.4"
\ No newline at end of file
+include ':libs:com.android.dx-1.7.0'
+include ':libs:com.tencent.bugly.crashreport-2.6.6'
+include ':libs:jackpal.androidterm.emulatorview-1.0.42'
+include ':libs:jackpal.androidterm.libtermexec-1.0'
+include ':libs:jackpal.androidterm-1.0.70'
+include ':libs:org.mozilla.rhino-1.7.14'
+include ':libs:org.opencv-4.5.4'
+include ':libs:androidx.appcompat-1.0.2'
\ No newline at end of file