6.3.4 Alpha2 - 新增 Paddle Lite / WebSocket; 修复屏幕旋转浮动按钮异常; 优化日志复制与导出
This commit is contained in:
1 parent
4674f94520
commit
4481f539f9
164 files changed
+3149
-1428
No files matched your search
@@ -25,21 +25,21 @@
|
||||
|
||||
### 简介
|
||||
|
||||
* Android 平台支持 [无障碍服务](https://developer.android.com/guide/topics/ui/accessibility/service?hl=zh-cn) 的 JavaScript 自动化工具
|
||||
* 需要 Android [API](https://developer.android.com/guide/topics/manifest/uses-sdk-element#ApiLevels) [24](https://developer.android.com/reference/android/os/Build.VERSION_CODES#N) ([7.0](https://zh.wikipedia.org/wiki/Android_Nougat)) [[N](https://developer.android.com/reference/android/os/Build.VERSION_CODES#N)] 及以上操作系统
|
||||
* 克隆 (clone) 自 [hyb1996/Auto.js](https://github.com/hyb1996/Auto.js)
|
||||
|
||||
******
|
||||
|
||||
### 指南
|
||||
[Auto.js](https://github.com/hyb1996/Auto.js) 是一款 Android 平台支持 [无障碍服务](https://developer.android.com/guide/topics/ui/accessibility/service?hl=zh-cn) 的 JavaScript 自动化工具软件.
|
||||
|
||||
******
|
||||
Auto.js 由 [hyb1996](https://github.com/hyb1996) 于 Jan 27, 2017 初次发布, 于 Mar 13, 2020 停止维护, 最终版本名称为 `4.1.1 alpha2`.
|
||||
|
||||
* [应用文档](https://docs.autojs6.com)
|
||||
* [使用手册 (待编写)](https://docs.autojs6.com/#/manual)
|
||||
* [疑难解答](https://docs.autojs6.com/#/qa)
|
||||
* [项目编译构建](#项目编译构建)
|
||||
* [脚本开发辅助](#脚本开发辅助)
|
||||
AutoJs6 在 Auto.js 最终项目的基础上, 于 Dec 1, 2021 进行二次开发, 继续保持开源免费.
|
||||
|
||||
基于 Auto.js 二次开发的开源项目 (以开发时间排序, 仅部分列举):
|
||||
|
||||
| 项目名称 | 应用名称 | 开发者 | 开发时间 |
|
||||
|:-----------------------------------------------------:|:----------------------:|:-----------------------------------------------------:|:------------:|
|
||||
| [Auto.js](https://github.com/TonyJiangWJ/Auto.js) | Auto.js M | [TonyJiangWJ](https://github.com/TonyJiangWJ) | Nov 21, 2019 |
|
||||
| [AutoX](https://github.com/kkevsekk1/AutoX) | Autox.js / Autox.js v6 | [kkevsekk1](https://github.com/kkevsekk1) | Jul 24, 2020 |
|
||||
| [AutoJs6](https://github.com/SuperMonster003/AutoJs6) | AutoJs6 | [SuperMonster003](https://github.com/SuperMonster003) | Dec 1, 2021 |
|
||||
|
||||
******
|
||||
|
||||
@@ -62,6 +62,27 @@
|
||||
|
||||
******
|
||||
|
||||
### 环境
|
||||
|
||||
******
|
||||
|
||||
- Android 操作系统
|
||||
- [API](https://developer.android.com/guide/topics/manifest/uses-sdk-element#ApiLevels) [24](https://developer.android.com/reference/android/os/Build.VERSION_CODES#N) ([7.0](https://zh.wikipedia.org/wiki/Android_Nougat)) [[N](https://developer.android.com/reference/android/os/Build.VERSION_CODES#N)] 及以上
|
||||
|
||||
******
|
||||
|
||||
### 指南
|
||||
|
||||
******
|
||||
|
||||
* [应用文档](https://docs.autojs6.com)
|
||||
* [使用手册 (待编写)](https://docs.autojs6.com/#/manual)
|
||||
* [疑难解答](https://docs.autojs6.com/#/qa)
|
||||
* [项目编译构建](#项目编译构建)
|
||||
* [脚本开发辅助](#脚本开发辅助)
|
||||
|
||||
******
|
||||
|
||||
### 主要变更
|
||||
|
||||
******
|
||||
@@ -74,33 +95,33 @@
|
||||
|
||||
* [Rhino](https://github.com/mozilla/rhino/) 引擎由 [v1.7.7.2](https://github.com/mozilla/rhino/releases/tag/Rhino1_7_7_2_Release) 升级至 [v1.7.15-SNAPSHOT](http://rhino.autojs6.com/blob/dbe3f43ba5eb01e7f76139208f36c383dcd1c488/gradle.properties#L3)
|
||||
|
||||
* 支持 [Object.values()](https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Object/values)
|
||||
* 支持 [Object.values()](https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Object/values)
|
||||
|
||||
```javascript
|
||||
Object.values({name: 'Max', age: 4}); // ['max', 4]
|
||||
```
|
||||
```javascript
|
||||
Object.values({name: 'Max', age: 4}); // ['max', 4]
|
||||
```
|
||||
|
||||
* 支持 [Array.prototype.includes()](https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/includes)
|
||||
* 支持 [Array.prototype.includes()](https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/includes)
|
||||
|
||||
```javascript
|
||||
[10, 20, NaN].includes(20); // true
|
||||
```
|
||||
```javascript
|
||||
[10, 20, NaN].includes(20); // true
|
||||
```
|
||||
|
||||
* 支持 [BigInt](https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/BigInt)
|
||||
* 支持 [BigInt](https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/BigInt)
|
||||
|
||||
```javascript
|
||||
typeof 567n === 'bigint'; // true
|
||||
```
|
||||
```javascript
|
||||
typeof 567n === 'bigint'; // true
|
||||
```
|
||||
|
||||
* 支持 [模板字符串](https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Template_literals)
|
||||
* 支持 [模板字符串](https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Template_literals)
|
||||
|
||||
```javascript
|
||||
`Lucky number: ${(Math.random() * 100).toFixed(0)}`
|
||||
```
|
||||
```javascript
|
||||
`Lucky number: ${(Math.random() * 100).toFixed(0)}`
|
||||
```
|
||||
|
||||
* 查看 Rhino 引擎 [更多新特性](http://project.autojs6.com/blob/master/app/src/main/assets/doc/RHINO.md)
|
||||
* 查看 Rhino 引擎 [更多新特性](http://project.autojs6.com/blob/master/app/src/main/assets/doc/RHINO.md)
|
||||
|
||||
* 查看 Rhino 引擎 [兼容性列表](https://mozilla.github.io/rhino/compat/engines.html)
|
||||
* 查看 Rhino 引擎 [兼容性列表](https://mozilla.github.io/rhino/compat/engines.html)
|
||||
|
||||
******
|
||||
|
||||
@@ -110,6 +131,35 @@
|
||||
|
||||
[comment]: <> "Version history only shows last 3 versions"
|
||||
|
||||
# v6.3.4
|
||||
|
||||
###### 2023/10/03
|
||||
|
||||
* `新增` ocr 模块支持 Paddle Lite 引擎 (by [TonyJiangWJ](https://github.com/TonyJiangWJ)) _[`pr #120`](http://pr.autojs6.com/120)_
|
||||
* `新增` WebSocket 模块 (参阅 项目文档 > [颜色类](https://docs.autojs6.com/#/webSocketType))
|
||||
* `新增` device.rotation / device.orientation 等方法
|
||||
* `新增` 内部 Java 类支持 class 静态属性访问
|
||||
* `修复` VSCode 插件保存文件到本地时文件扩展名信息丢失的问题
|
||||
* `修复` 使用协程特性运行项目产生未捕获异常致使应用崩溃的问题
|
||||
* `修复` 重启或退出应用时浮动按钮无法记录其位置状态信息的问题
|
||||
* `修复` 设备屏幕方向改变时无法获取更新后的设备配置信息的问题
|
||||
* `修复` 屏幕旋转至横向时 Toolbar 标题字体过小的问题
|
||||
* `修复` 屏幕旋转至横向时应用主页的页签排版过于拥挤的问题
|
||||
* `修复` 屏幕旋转至横向时浮动按钮可能溢出屏幕的问题 _[`issue #90`](http://issues.autojs6.com/90)_
|
||||
* `修复` 屏幕多次旋转时无法恢复浮动按钮的坐标及屏幕侧边方向的问题
|
||||
* `修复` 消息浮动框在多个脚本同时运行时可能存在被遮蔽的问题 _[`issue #67`](http://issues.autojs6.com/67)_
|
||||
* `修复` 使用广播分析布局时点击布局无法弹出菜单且导致应用崩溃的问题
|
||||
* `修复` 第二次及以后创建的 WebSocket 实例均无法正常触发监听器的问题
|
||||
* `修复` 重新合并部分 PR (by [aiselp](https://github.com/aiselp)) 以解决部分脚本无法正常结束运行的问题 _[`pr #75`](http://pr.autojs6.com/75)_ _[`pr #78`](http://pr.autojs6.com/78)_
|
||||
* `修复` 撤销 importPackage 的全局重定向方法以避免某些作用域下的包导入异常 _[`issue #88`](http://issues.autojs6.com/88)_
|
||||
* `修复` 日志活动页面使用复制或导出功能时可能导致应用崩溃的问题
|
||||
* `优化` 日志活动页面导出功能重命名为发送功能并重新实现符合实际意义的导出功能
|
||||
* `优化` 日志活动页面发送功能支持条目数量过大时自动截取并作出提示
|
||||
* `优化` ocr 模块同时兼容 Google MLKit 及 Paddle Lite 引擎 (参阅 项目文档 > [光学字符识别](https://docs.autojs6.com/#/ocr?id=p-mode))
|
||||
* `优化` 提升无障碍服务自动启动的成功概率
|
||||
* `优化` 构建工具自适应 Java 发行版本以尽量避免 "无效的发行版本" 问题
|
||||
* `优化` 部分 Kotlin 注解处理由 kapt 迁移至 KSP
|
||||
|
||||
# v6.3.3
|
||||
|
||||
###### 2023/07/21
|
||||
@@ -161,42 +211,10 @@
|
||||
* `优化` 服务端模式开启后保持常开状态 (除非手动关闭或应用进程结束) _[`issue #64`](http://issues.autojs6.com/64#issuecomment-1596990158)_
|
||||
* `优化` 实现 AutoJs6 与 VSCode 插件的双向版本检测并提示异常检测结果 _[`issue #89`](http://issues.autojs6.com/89)_
|
||||
* `优化` 增加短信数据读取权限 (android.permission.READ_SMS) (默认关闭)
|
||||
* `优化` findMultiColors 方法内部实现 (by [LYS](https://github.com/LYS86)) _[`pr #72`](http://pr.autojs6.com/72)_
|
||||
* `优化` findMultiColors 方法内部实现 (by [LYS86](https://github.com/LYS86)) _[`pr #72`](http://pr.autojs6.com/72)_
|
||||
* `优化` runtime.loadDex/loadJar/load 支持按目录级别加载或同时加载多个文件
|
||||
* `优化` 部分依赖或本地库版本调整 _[`CHANGELOG.md`](http://project.autojs6.com/blob/master/app/src/main/assets/doc/CHANGELOG.md#v632)_
|
||||
|
||||
# v6.3.1
|
||||
|
||||
###### 2023/05/26
|
||||
|
||||
* `新增` 发布通知权限及主页抽屉开关 _[`issue #55`](http://issues.autojs6.com/55)_
|
||||
* `新增` UI 模式支持简单的 Android 布局解析 (参阅 示例代码 > 布局 > 简单安卓布局)
|
||||
* `新增` UI 模式增加 console / imagebutton / ratingbar / switch / textclock / togglebutton 等控件
|
||||
* `新增` UI 模式控件的颜色色值支持 [OmniColor](https://docs.autojs6.com/#/omniTypes?id=omnicolor) 类型 (如 color="orange")
|
||||
* `新增` UI 模式的控件完全支持 attr 方法设置控件属性 (如 ui.text.attr('color', 'blue'))
|
||||
* `新增` UI 模式控件支持布尔类型属性值的缺省形式 (如 clickable="true" 可简写为 clickable 或 isClickable)
|
||||
* `新增` button 控件支持 isColored 及 isBorderless 布尔类型属性
|
||||
* `新增` console.resetGlobalLogConfig 方法用于重置全局日志配置
|
||||
* `新增` web.newWebSocket 方法用于创建 Web Socket 实例 (参阅 项目文档 > [万维网](https://docs.autojs6.com/#/web?id=m-newwebsocket))
|
||||
* `修复` 文件管理器的文件夹排序异常
|
||||
* `修复` floaty 模块构建的浮动窗口无法调节样式及位置的问题 _[`issue #60`](http://issues.autojs6.com/60)_
|
||||
* `修复` floaty 模块构建的浮动窗口与系统状态栏重叠的问题
|
||||
* `修复` http.postMultipart 方法功能异常 _[`issue #56`](http://issues.autojs6.com/56)_
|
||||
* `修复` Android 7.x 无法运行任何脚本的问题 _[`issue #61`](http://issues.autojs6.com/61)_
|
||||
* `修复` sign.property 文件不存在时无法构建项目的问题
|
||||
* `修复` 高版本系统 AutoJs6 置于后台时可能因无前台通知权限而崩溃的问题 (API >= 33)
|
||||
* `修复` 调用 console.show 方法后日志窗口点击 FAB 按钮无法清空日志的问题
|
||||
* `修复` 脚本编辑器调试时出现的 prototype 空指针异常
|
||||
* `修复` 脚本编辑器运行脚本时在缓存文件夹运行临时脚本而非先保存再在原始位置运行以避免可能的脚本内容丢失问题
|
||||
* `修复` 调整布局层次分析的层级色条宽度避免层级过多时控件名称无法显示的问题 _[`issue #46`](http://issues.autojs6.com/46)_
|
||||
* `优化` 布局分析浮动窗口增加退出按钮以关闭窗口 _[`issue #63`](http://issues.autojs6.com/63)_
|
||||
* `优化` 脚本绝对路径使用简称形式以缩减文本长度并增加可读性
|
||||
* `优化` 将 Error 替换为 Exception 避免出现异常时 AutoJs6 应用崩溃
|
||||
* `优化` 视图 (View) 绑定方式由 ButterKnife 迁移至 View Binding _[`issue #48`](http://issues.autojs6.com/48)_
|
||||
* `优化` 服务端模式非正常关闭时将于 AutoJs6 启动时自动开启 _[`issue #64`](http://issues.autojs6.com/64)_
|
||||
* `优化` 客户端模式非正常关闭时将于 AutoJs6 启动时按最近一次的历史地址自动连接
|
||||
* `优化` 部分依赖或本地库版本调整 _[`CHANGELOG.md`](http://project.autojs6.com/blob/master/app/src/main/assets/doc/CHANGELOG.md#v631)_
|
||||
|
||||
##### 更多版本历史可参阅
|
||||
|
||||
* [CHANGELOG.md](http://changelog.autojs6.com)
|
||||
@@ -207,27 +225,18 @@
|
||||
|
||||
******
|
||||
|
||||
建议始终使用 Android Studio 进行 AutoJs6 调试或开发.
|
||||
如需对 AutoJs6 开源项目进行调试或开发, 可使用 Android Studio 或 [IntelliJ IDEA](https://www.jetbrains.com/idea/) ([Jetbrains](https://www.jetbrains.com/) 公司产品).
|
||||
|
||||
如需使用 [IntelliJ IDEA](https://www.jetbrains.com/idea/) ([Jetbrains](https://www.jetbrains.com/) 公司产品), 需留意以下注意事项:
|
||||
|
||||
- IntelliJ IDEA 版本建议不低于 `2022.3.3 (Ultimate Edition)`
|
||||
- IntelliJ IDEA 的 Gradle JVM 版本不低于 `19`
|
||||
- 回退 Gradle 构建工具版本至 IDEA 支持的版本
|
||||
- 如 `classpath("com.android.tools.build:gradle:7.4.0")`
|
||||
- 具体版本可根据 IDEA 的错误提示获知
|
||||
- 回退 Kotlin 脚本 (KTS) 语法
|
||||
- 如 ` com.android.build.api.dsl.CommonExtension#options` 需回退为 `packagingOptions`
|
||||
- ... ...
|
||||
本小节以 Android Studio 为例介绍 AutoJs6 开源项目的编译构建方法, IntelliJ IDEA 与之类似.
|
||||
|
||||
#### Android Studio 准备
|
||||
|
||||
下载 `Android Studio Flamingo | 2022.2.1 Patch 2` 版本 (按需选择其一):
|
||||
下载 `Android Studio Giraffe | 2022.3.1 Patch 2` 版本 (按需选择其一):
|
||||
|
||||
- [android-studio-2022.2.1.20-windows.exe](https://redirector.gvt1.com/edgedl/android/studio/install/2022.2.1.20/android-studio-2022.2.1.20-windows.exe) (1.0 GB)
|
||||
- [android-studio-2022.2.1.20-windows.zip](https://redirector.gvt1.com/edgedl/android/studio/ide-zips/2022.2.1.20/android-studio-2022.2.1.20-windows.zip) (1.0 GB)
|
||||
- [android-studio-2022.3.1.20-windows.exe](https://redirector.gvt1.com/edgedl/android/studio/install/2022.3.1.20/android-studio-2022.3.1.20-windows.exe) (1.1 GB)
|
||||
- [android-studio-2022.3.1.20-windows.zip](https://redirector.gvt1.com/edgedl/android/studio/ide-zips/2022.3.1.20/android-studio-2022.3.1.20-windows.zip) (1.1 GB)
|
||||
|
||||
> 注: 上述版本发布时间为 2023 年 5 月 24 日. 如需下载其他版本, 或上述链接已失效, 可访问 [Android Studio 发行版本归档](https://developer.android.com/studio/archive) 页面.
|
||||
> 注: 上述版本发布时间为 2023 年 9 月 28 日. 如需下载其他版本, 或上述链接已失效, 可访问 [Android Studio 发行版本归档](https://developer.android.com/studio/archive?hl=en) 页面.
|
||||
|
||||
安装或解压上述文件, 运行 Android Studio 软件 (如 `"D:\android-studio\bin\studio64.exe"`).
|
||||
|
||||
@@ -252,12 +261,12 @@ Android SDK (安卓软件开发工具包)
|
||||
|
||||
#### JDK 准备
|
||||
|
||||
AutoJs6 项目依赖的 `JDK (Java 开发工具包)` 发行版本不低于 `19`.
|
||||
AutoJs6 项目依赖的 `JDK (Java 开发工具包)` 发行版本不低于 `17`.
|
||||
|
||||
> 注: 如果计算机系统已安装 JDK 且版本不低于 17, 则可跳过此小节内容.
|
||||
|
||||
JDK 可使用 IDE 直接下载, 或访问 [Oracle 网站](https://www.oracle.com/java/technologies/downloads/) 下载.
|
||||
|
||||
> 注: 如果计算机系统已安装 JDK 且版本不低于 19, 则可跳过此小节内容.
|
||||
|
||||
在 Android Studio 软件中使用快捷键 `CTRL + ALT + S` 打开设置页面:
|
||||
|
||||
```text
|
||||
@@ -268,12 +277,9 @@ Gradle
|
||||
|
||||
`Gradle JDK` 处可选择或添加不同版本的 JDK.
|
||||
|
||||
- 列表中存在合适版本的 JDK
|
||||
- 直接选择即可
|
||||
- 选择 `Download JDK (下载 JDK)` 下载新的 JDK
|
||||
- 选择一个版本不低于 19 的 JDK, 点击 `Download (下载)` 按钮并等待下载完成
|
||||
- 选择 `Add JDK (添加 JDK)` 添加已存在的本地 JDK
|
||||
- 如计算机系统已存在合适版本的 JDK, 可定位其目录并完成 JDK 添加
|
||||
如果列表中已存在合适版本的 JDK (>= `17`), 则直接选择即可.
|
||||
否则可以选择 `Download JDK (下载 JDK)` 下载合适的 JDK, 点击 `Download (下载)` 按钮并等待下载完成.
|
||||
也可以选择 `Add JDK (添加 JDK)` 添加已存在的本地 JDK, 定位其目录并完成 JDK 添加.
|
||||
|
||||
#### AutoJs6 资源克隆
|
||||
|
||||
@@ -295,14 +301,14 @@ Gradle
|
||||
打包项目并生成可安装到安卓设备的 APK 文件:
|
||||
|
||||
- 调试版 (Debug Version)
|
||||
- `Build (构建)` -> `Build Bundle(s) / APK(s)` -> `Build APK(s)`
|
||||
- 生成带默认签名的调试版安装包
|
||||
- 路径示例: `"D:\AutoJs6\app\build\outputs\apk\debug\"`
|
||||
- `Build (构建)` -> `Build Bundle(s) / APK(s)` -> `Build APK(s)`
|
||||
- 生成带默认签名的调试版安装包
|
||||
- 路径示例: `"D:\AutoJs6\app\build\outputs\apk\debug\"`
|
||||
- 发布版 (Release Version)
|
||||
- `Build (构建)` -> `Generate Signed Bundle / APK`
|
||||
- 选择 `APK` 选项
|
||||
- 准备好签名文件 (新建或选取), 生成已签名的发布版安装包
|
||||
- 路径示例: `"D:\AutoJs6\app\release\"`
|
||||
- `Build (构建)` -> `Generate Signed Bundle / APK`
|
||||
- 选择 `APK` 选项
|
||||
- 准备好签名文件 (新建或选取), 生成已签名的发布版安装包
|
||||
- 路径示例: `"D:\AutoJs6\app\release\"`
|
||||
|
||||
> 参阅: [Android Docs](https://developer.android.com/studio/run?hl=zh-cn)
|
||||
|
||||
@@ -328,31 +334,34 @@ Gradle
|
||||
|
||||
- [AutoJs6-Documentation](http://docs-project.autojs6.com) - AutoJs6 应用文档
|
||||
|
||||
******
|
||||
现有的脚本开发项目可作为参考, 激发个人脚本项目的创作灵感:
|
||||
|
||||
### 相关项目
|
||||
- [Ant-Forest](https://github.com/TonyJiangWJ/Ant-Forest) - 蚂蚁森林能量自动收取脚本 by [TonyJiangWJ](https://github.com/TonyJiangWJ)
|
||||
- [Ant-Forest](https://github.com/SuperMonster003/Ant-Forest) - 蚂蚁森林能量自动收取脚本 by [SuperMonster003](https://github.com/SuperMonster003)
|
||||
- [autojs](https://github.com/e1399579/autojs) - Auto.js 实用脚本 by [e1399579](https://github.com/e1399579)
|
||||
- [autojsDemo](https://github.com/snailuncle/autojsDemo) - Auto.js 演示示例 by [snailuncle](https://github.com/snailuncle)
|
||||
|
||||
******
|
||||
|
||||
[AutoX (Autox.js)](https://github.com/kkevsekk1/AutoX) by [kkevsekk1](https://github.com/kkevsekk1)
|
||||
### 贡献参与
|
||||
|
||||
- 安卓平台 JavaScript 自动化工具 (Auto.js 二次开发项目)
|
||||
******
|
||||
|
||||
[AutoJs6-Documentation](http://docs-project.autojs6.com) by [SuperMonster003](https://github.com/SuperMonster003)
|
||||
感谢每一位参与 AutoJs6 项目开发的贡献人员.
|
||||
|
||||
- AutoJs6 应用文档
|
||||
| 贡献人员 | 提交数 | 最近提交 |
|
||||
|:-----------------------------------------------------:|:-------------------------------------------------------------------------------:|:------------:|
|
||||
| [TonyJiangWJ](https://github.com/TonyJiangWJ) | [3](https://github.com/SuperMonster003/AutoJs6/commits?author=TonyJiangWJ) | Aug 29, 2023 |
|
||||
| [SuperMonster003](https://github.com/SuperMonster003) | [33](https://github.com/SuperMonster003/AutoJs6/commits?author=SuperMonster003) | Jul 21, 2023 |
|
||||
| [LZX284](https://github.com/LZX284) (Ai) | [4](https://github.com/SuperMonster003/AutoJs6/commits?author=LZX284) | Jul 20, 2023 |
|
||||
| [little-alei](https://github.com/little-alei) (抠脚本人) | [12](https://github.com/SuperMonster003/AutoJs6/commits?author=little-alei) | Jul 12, 2023 |
|
||||
| [aiselp](https://github.com/aiselp) | [6](https://github.com/SuperMonster003/AutoJs6/pulls?q=is%3Apr+author%3Aaiselp) | Jun 14, 2023 |
|
||||
| [LYS86](https://github.com/LYS86) (LYS) | [2](https://github.com/SuperMonster003/AutoJs6/commits?author=LYS86) | Jun 3, 2023 |
|
||||
|
||||
[AutoJs6-VSCode-Extension](http://vscext-project.autojs6.com) by [SuperMonster003](https://github.com/SuperMonster003)
|
||||
|
||||
- AutoJs6 调试器 (VSCode 平台插件)
|
||||
|
||||
[AutoJs6-TypeScript-Declarations](http://dts-project.autojs6.com) by [SuperMonster003](https://github.com/SuperMonster003)
|
||||
|
||||
- AutoJs6 声明文件 (代码智能补全)
|
||||
|
||||
[Ant-Forest](https://github.com/SuperMonster003/Ant-Forest) by [SuperMonster003](https://github.com/SuperMonster003)
|
||||
|
||||
- 蚂蚁森林能量自动收取脚本 (AutoJs6 示例脚本项目)
|
||||
> 数据统计区间: Dec 1, 2021 - Oct 3, 2023.
|
||||
> 数据条目按 "最近提交" 列排序 (降序).
|
||||
> 新发起的暂未处理的 Pull Request, 将在合并处理后加入数据统计.
|
||||
> 部分贡献人员在 [GitHub Contributors](https://github.com/SuperMonster003/AutoJs6/graphs/contributors) 未能正常出现, 其提交记录为空, 仍可通过 [Pull Request](https://github.com/SuperMonster003/AutoJs6/pulls) 查看贡献记录.
|
||||
|
||||
[//]: # (
|
||||
# --------------------------------------------------------------#
|
||||
|
||||
+95
-22
@@ -1,4 +1,4 @@
|
||||
@file:Suppress("UnstableApiUsage", "SpellCheckingInspection")
|
||||
@file:Suppress("SpellCheckingInspection")
|
||||
|
||||
import com.android.build.gradle.internal.api.ApplicationVariantImpl
|
||||
import com.android.build.gradle.internal.api.BaseVariantOutputImpl
|
||||
@@ -15,8 +15,9 @@ val versions = Versions("$rootDir/version.properties")
|
||||
|
||||
plugins {
|
||||
id("com.android.application")
|
||||
kotlin("android")
|
||||
kotlin("kapt")
|
||||
id("com.google.devtools.ksp")
|
||||
id("org.jetbrains.kotlin.kapt") /* kotlin("kapt") */
|
||||
id("org.jetbrains.kotlin.android") /* kotlin("android") */
|
||||
}
|
||||
|
||||
dependencies /* Unclassified */ {
|
||||
@@ -38,7 +39,7 @@ dependencies /* Unclassified */ {
|
||||
implementation("de.psdev.licensesdialog:licensesdialog:2.2.0")
|
||||
|
||||
// Commons Lang
|
||||
implementation("org.apache.commons:commons-lang3:3.12.0")
|
||||
implementation("org.apache.commons:commons-lang3:3.13.0")
|
||||
|
||||
// Retrofit
|
||||
implementation("com.squareup.retrofit2:retrofit:2.9.0")
|
||||
@@ -47,14 +48,14 @@ dependencies /* Unclassified */ {
|
||||
implementation("com.jakewharton.retrofit:retrofit2-kotlin-coroutines-adapter:0.9.2")
|
||||
|
||||
// Glide
|
||||
implementation("com.github.bumptech.glide:glide:4.15.1")
|
||||
kapt("com.github.bumptech.glide:compiler:4.15.1")
|
||||
implementation("com.github.bumptech.glide:glide:4.16.0")
|
||||
ksp("com.github.bumptech.glide:ksp:4.16.0")
|
||||
|
||||
// Joda Time
|
||||
implementation("joda-time:joda-time:2.12.5")
|
||||
|
||||
// Flurry
|
||||
implementation("com.flurry.android:analytics:14.3.0")
|
||||
implementation("com.flurry.android:analytics:14.4.0")
|
||||
|
||||
// Bugly
|
||||
implementation(project(":libs:com.tencent.bugly.crashreport-4.0.4"))
|
||||
@@ -63,7 +64,7 @@ dependencies /* Unclassified */ {
|
||||
implementation("com.squareup.okhttp3:okhttp:5.0.0-alpha.11")
|
||||
|
||||
// Webkit
|
||||
implementation("androidx.webkit:webkit:1.7.0")
|
||||
implementation("androidx.webkit:webkit:1.8.0")
|
||||
|
||||
// Gson
|
||||
implementation("com.google.code.gson:gson:2.10.1")
|
||||
@@ -76,8 +77,7 @@ dependencies /* Unclassified */ {
|
||||
implementation("log4j:log4j:1.2.17")
|
||||
|
||||
// Preference
|
||||
implementation("androidx.preference:preference:1.2.0")
|
||||
implementation("androidx.preference:preference-ktx:1.2.0")
|
||||
implementation("androidx.preference:preference-ktx:1.2.1")
|
||||
|
||||
// RootShell
|
||||
implementation("com.github.Stericson:RootShell:1.6")
|
||||
@@ -130,6 +130,11 @@ dependencies /* Unclassified */ {
|
||||
implementation(files("$rootDir/libs/javamail-android/activation.jar"))
|
||||
implementation(files("$rootDir/libs/javamail-android/additionnal.jar"))
|
||||
implementation(files("$rootDir/libs/javamail-android/mail.jar"))
|
||||
|
||||
// Shizuku
|
||||
implementation("dev.rikka.shizuku:api:13.1.5")
|
||||
implementation("dev.rikka.shizuku:provider:13.1.5")
|
||||
implementation("org.lsposed.hiddenapibypass:hiddenapibypass:4.3@aar")
|
||||
}
|
||||
|
||||
dependencies /* Test */ {
|
||||
@@ -140,9 +145,11 @@ dependencies /* Test */ {
|
||||
|
||||
dependencies /* Annotations */ {
|
||||
// Android Annotations
|
||||
kapt("org.androidannotations:androidannotations:4.8.0")
|
||||
implementation("org.androidannotations:androidannotations-api:4.8.0")
|
||||
implementation("androidx.annotation:annotation:1.6.0")
|
||||
implementation("androidx.annotation:annotation:1.7.0")
|
||||
// FIXME by SuperMonster003 on Aug 17, 2023.
|
||||
// ! Failed to migrate it from kapt to KSP.
|
||||
kapt("org.androidannotations:androidannotations:4.8.0")
|
||||
|
||||
// JCIP Annotations
|
||||
implementation("net.jcip:jcip-annotations:1.0")
|
||||
@@ -250,7 +257,7 @@ dependencies /* Auto.js Extensions */ {
|
||||
// Extracted from com.github.hyb1996:MutableTheme:1.0.0
|
||||
// @Legacy com.jrummyapps:colorpicker:2.1.7
|
||||
implementation("com.jaredrummler:colorpicker:1.1.0")
|
||||
implementation("androidx.recyclerview:recyclerview:1.3.0")
|
||||
implementation("androidx.recyclerview:recyclerview:1.3.1")
|
||||
implementation("com.github.ozodrukh:CircularReveal:2.0.1")
|
||||
}
|
||||
|
||||
@@ -349,6 +356,10 @@ android {
|
||||
|
||||
buildFeatures {
|
||||
viewBinding = true
|
||||
|
||||
// @Hint by SuperMonster003 on Aug 14, 2023.
|
||||
// ! Substitution of "android.defaults.buildfeatures.buildconfig=true"
|
||||
buildConfig = true
|
||||
}
|
||||
|
||||
defaultConfig {
|
||||
@@ -466,22 +477,68 @@ class Versions(filePath: String) {
|
||||
val appVersionCode = properties["VERSION_BUILD"].let { it as String }.toInt()
|
||||
val vscodeExtRequiredVersion = properties["VSCODE_EXT_REQUIRED_VERSION"] as String
|
||||
|
||||
private val javaVersionMinSupported = properties["JAVA_VERSION_MIN_SUPPORTED"]
|
||||
.let { it as String }.toInt()
|
||||
.also {
|
||||
if (!JavaVersion.current().isCompatibleWith(JavaVersion.toVersion(it))) {
|
||||
throw GradleException("Current Gradle JDK version ${JavaVersion.current()} does not meet the minimum requirement which $it is needed.")
|
||||
}
|
||||
}
|
||||
private val javaVersionMinSuggested = properties["JAVA_VERSION_MIN_SUGGESTED"]
|
||||
.let { it as String }.toInt()
|
||||
.also {
|
||||
if (!JavaVersion.current().isCompatibleWith(JavaVersion.toVersion(it))) {
|
||||
logger.error("It is recommended to upgrade current Gradle JDK version ${JavaVersion.current()} to $it or higher.")
|
||||
}
|
||||
}
|
||||
private val javaVersionRaw = properties["JAVA_VERSION"] as String
|
||||
private var javaVersionInfoSuffix = ""
|
||||
private val javaVersionCeilMap = mapOf(
|
||||
"as" to mapOf(
|
||||
/* Empty so far. */
|
||||
),
|
||||
"idea" to mapOf(
|
||||
"2023.2" to javaVersionMinSuggested, /* Aug 17, 2023. */
|
||||
"2023.1" to javaVersionMinSuggested, /* Aug 17, 2023. */
|
||||
"2022.3" to javaVersionMinSuggested, /* Aug 17, 2023. */
|
||||
),
|
||||
)
|
||||
|
||||
val javaVersion: JavaVersion by lazy {
|
||||
val minSupportedVersion = 17
|
||||
var versionInt = javaVersionRaw.toInt()
|
||||
while (versionInt > minSupportedVersion) {
|
||||
|
||||
while (versionInt > javaVersionMinSupported) {
|
||||
@Suppress("EnumValuesSoftDeprecate")
|
||||
if (JvmTarget.values().any { it.name.contains(Regex("_$versionInt$")) }) {
|
||||
break
|
||||
}
|
||||
versionInt -= 1
|
||||
}
|
||||
|
||||
if (!JavaVersion.toVersion("$versionInt").isCompatibleWith(JavaVersion.toVersion(javaVersionRaw))) {
|
||||
javaVersionInfoSuffix += " [fallback]"
|
||||
}
|
||||
|
||||
val platformVersion = gradle.extra["platformVersion"] as String
|
||||
val platformType = gradle.extra["platformType"] as String
|
||||
|
||||
javaVersionCeilMap[platformType]!![platformVersion]?.let { ceil: Int ->
|
||||
if (versionInt > ceil) {
|
||||
versionInt = ceil
|
||||
javaVersionInfoSuffix += " [coerced]"
|
||||
}
|
||||
}
|
||||
|
||||
if (!JavaVersion.current().isCompatibleWith(JavaVersion.toVersion(versionInt))) {
|
||||
versionInt = JavaVersion.current().majorVersion.toInt()
|
||||
javaVersionInfoSuffix += " [consistent]"
|
||||
}
|
||||
|
||||
JavaVersion.toVersion(versionInt.toString())
|
||||
}
|
||||
|
||||
private var isBuildNumberAutoIncremented = false
|
||||
private val minBuildTimeGap = Utils.hours2Millis(0.5)
|
||||
private val minBuildTimeGap = Utils.hours2Millis(0.75)
|
||||
private val assembleTargets = mapOf("app" to listOf("debug", "release"))
|
||||
|
||||
private val isBuildGapEnough
|
||||
@@ -506,12 +563,28 @@ class Versions(filePath: String) {
|
||||
properties.store(file.writer(), null)
|
||||
}
|
||||
|
||||
fun showInfo() = arrayOf(
|
||||
"Version name: $appVersionName",
|
||||
"Version code: $appVersionCode${" [auto-incremented]".takeIf { isBuildNumberAutoIncremented } ?: ""}",
|
||||
"SDK versions: min [$sdkVersionMin] / target [$sdkVersionTarget] / compile [$sdkVersionCompile]",
|
||||
"Java version: $javaVersion${" [fallback]".takeUnless { javaVersion.isCompatibleWith(JavaVersion.toVersion(javaVersionRaw)) } ?: ""}",
|
||||
).forEach { println(it) }
|
||||
fun showInfo() {
|
||||
val title = "Version information for AutoJs6 app library"
|
||||
|
||||
val infoVerName = "Version name: $appVersionName"
|
||||
val infoVerCode = "Version code: $appVersionCode${" [auto-incremented]".takeIf { isBuildNumberAutoIncremented } ?: ""}"
|
||||
val infoVerSdk = "SDK versions: min [$sdkVersionMin] / target [$sdkVersionTarget] / compile [$sdkVersionCompile]"
|
||||
val infoVerJava = "Java version: $javaVersion$javaVersionInfoSuffix"
|
||||
|
||||
val maxLength = arrayOf(title, infoVerName, infoVerCode, infoVerSdk, infoVerJava).maxOf { it.length }
|
||||
|
||||
arrayOf(
|
||||
"=".repeat(maxLength),
|
||||
title,
|
||||
"-".repeat(maxLength),
|
||||
infoVerName,
|
||||
infoVerCode,
|
||||
infoVerSdk,
|
||||
infoVerJava,
|
||||
"=".repeat(maxLength),
|
||||
"",
|
||||
).forEach { println(it) }
|
||||
}
|
||||
|
||||
fun handleIfNeeded(project: Project) = assembleTargets.forEach {
|
||||
val targetName = it.key
|
||||
|
||||
@@ -20,12 +20,18 @@
|
||||
! Target API >= 30: WRT + [ MSV<29> ] + LGC + MAN
|
||||
-->
|
||||
|
||||
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
|
||||
<uses-permission
|
||||
android:name="android.permission.READ_EXTERNAL_STORAGE"
|
||||
android:maxSdkVersion="32" />
|
||||
|
||||
<uses-permission
|
||||
android:name="android.permission.WRITE_EXTERNAL_STORAGE"
|
||||
android:maxSdkVersion="29" />
|
||||
|
||||
<uses-permission android:name="android.permission.READ_MEDIA_IMAGES" />
|
||||
<uses-permission android:name="android.permission.READ_MEDIA_VIDEO" />
|
||||
<uses-permission android:name="android.permission.READ_MEDIA_AUDIO" />
|
||||
|
||||
<uses-permission
|
||||
android:name="android.permission.MANAGE_EXTERNAL_STORAGE"
|
||||
tools:ignore="ScopedStorage" />
|
||||
@@ -39,10 +45,6 @@
|
||||
|
||||
<uses-permission android:name="com.android.launcher.permission.UNINSTALL_SHORTCUT" />
|
||||
|
||||
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
|
||||
|
||||
<uses-permission android:name="android.permission.READ_SMS" />
|
||||
|
||||
<uses-permission
|
||||
android:name="android.permission.READ_PRIVILEGED_PHONE_STATE"
|
||||
tools:ignore="ProtectedPermissions" />
|
||||
@@ -72,6 +74,8 @@
|
||||
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
|
||||
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_MEDIA_PROJECTION" />
|
||||
|
||||
<uses-permission
|
||||
android:name="android.permission.DUMP"
|
||||
tools:ignore="ProtectedPermissions" />
|
||||
@@ -92,9 +96,6 @@
|
||||
android:name="android.permission.WRITE_SECURE_SETTINGS"
|
||||
tools:ignore="ProtectedPermissions" />
|
||||
|
||||
<uses-permission android:name="android.permission.QUERY_ALL_PACKAGES"
|
||||
tools:ignore="QueryAllPackagesPermission" />
|
||||
|
||||
<!-- 非 AutoJs6 运行必需, 不会主动申请, 脚本可自行申请 -->
|
||||
|
||||
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
|
||||
@@ -103,6 +104,15 @@
|
||||
|
||||
<uses-permission android:name="android.permission.RECORD_AUDIO" />
|
||||
|
||||
<!-- Dangerous permission witch should be treated carefully. -->
|
||||
|
||||
<!-- <uses-permission android:name="android.permission.READ_CONTACTS" />-->
|
||||
<!-- <uses-permission android:name="android.permission.WRITE_CONTACTS" />-->
|
||||
|
||||
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
|
||||
|
||||
<uses-permission android:name="android.permission.READ_SMS" />
|
||||
|
||||
<application
|
||||
android:name="org.autojs.autojs.App"
|
||||
android:allowBackup="false"
|
||||
@@ -138,6 +148,7 @@
|
||||
|
||||
<activity
|
||||
android:name="org.autojs.autojs.ui.main.MainActivity"
|
||||
android:exported="true"
|
||||
android:launchMode="singleTask"
|
||||
android:theme="@style/AppTheme.FullScreen" />
|
||||
|
||||
@@ -553,6 +564,14 @@
|
||||
android:enabled="true"
|
||||
android:foregroundServiceType="mediaProjection" />
|
||||
|
||||
<!-- This provider is required by Shizuku, remove this if your app only supports Sui -->
|
||||
<provider
|
||||
android:name="rikka.shizuku.ShizukuProvider"
|
||||
android:authorities="org.autojs.autojs6.shizuku"
|
||||
android:enabled="true"
|
||||
android:exported="true"
|
||||
android:multiprocess="false"
|
||||
android:permission="android.permission.INTERACT_ACROSS_USERS_FULL" />
|
||||
</application>
|
||||
|
||||
</manifest>
|
||||
@@ -6,9 +6,42 @@
|
||||
|
||||
# v6.3.4
|
||||
|
||||
###### 2023/07/25
|
||||
###### 2023/10/03
|
||||
|
||||
* `新增` ocr 模块支持 Paddle Lite 引擎 (by [TonyJiangWJ](https://github.com/TonyJiangWJ)) _[`pr #120`](http://pr.autojs6.com/120)_
|
||||
* `新增` WebSocket 模块 (参阅 项目文档 > [颜色类](https://docs.autojs6.com/#/webSocketType))
|
||||
* `新增` device.rotation / device.orientation 等方法
|
||||
* `新增` 内部 Java 类支持 class 静态属性访问
|
||||
* `修复` VSCode 插件保存文件到本地时文件扩展名信息丢失的问题
|
||||
* `修复` 使用协程特性运行项目产生未捕获异常致使应用崩溃的问题
|
||||
* `修复` 重启或退出应用时浮动按钮无法记录其位置状态信息的问题
|
||||
* `修复` 设备屏幕方向改变时无法获取更新后的设备配置信息的问题
|
||||
* `修复` 屏幕旋转至横向时 Toolbar 标题字体过小的问题
|
||||
* `修复` 屏幕旋转至横向时应用主页的页签排版过于拥挤的问题
|
||||
* `修复` 屏幕旋转至横向时浮动按钮可能溢出屏幕的问题 _[`issue #90`](http://issues.autojs6.com/90)_
|
||||
* `修复` 屏幕多次旋转时无法恢复浮动按钮的坐标及屏幕侧边方向的问题
|
||||
* `修复` 消息浮动框在多个脚本同时运行时可能存在被遮蔽的问题 _[`issue #67`](http://issues.autojs6.com/67)_
|
||||
* `修复` 使用广播分析布局时点击布局无法弹出菜单且导致应用崩溃的问题
|
||||
* `修复` 第二次及以后创建的 WebSocket 实例均无法正常触发监听器的问题
|
||||
* `修复` 重新合并部分 PR (by [aiselp](https://github.com/aiselp)) 以解决部分脚本无法正常结束运行的问题 _[`pr #75`](http://pr.autojs6.com/75)_ _[`pr #78`](http://pr.autojs6.com/78)_
|
||||
* `修复` 撤销 importPackage 的全局重定向方法以避免某些作用域下的包导入异常 _[`issue #88`](http://issues.autojs6.com/88)_
|
||||
* `修复` 日志活动页面使用复制或导出功能时可能导致应用崩溃的问题
|
||||
* `优化` 日志活动页面导出功能重命名为发送功能并重新实现符合实际意义的导出功能
|
||||
* `优化` 日志活动页面发送功能支持条目数量过大时自动截取并作出提示
|
||||
* `优化` ocr 模块同时兼容 Google MLKit 及 Paddle Lite 引擎 (参阅 项目文档 > [光学字符识别](https://docs.autojs6.com/#/ocr?id=p-mode))
|
||||
* `优化` 提升无障碍服务自动启动的成功概率
|
||||
* `优化` 构建工具自适应 Java 发行版本以尽量避免 "无效的发行版本" 问题
|
||||
* `优化` 部分 Kotlin 注解处理由 kapt 迁移至 KSP
|
||||
* `优化` 附加 Rikka Shizuku 版本 13.1.5
|
||||
* `优化` 升级 Gradle Compile 版本 33 -> 34
|
||||
* `优化` 升级 Gradle 版本 8.3-rc-1 -> 8.4-rc-3
|
||||
* `优化` 升级 Apache Commons Lang3 版本 3.12.0 -> 3.13.0
|
||||
* `优化` 升级 Glide 版本 4.15.1 -> 4.16.0
|
||||
* `优化` 升级 Android Analytics 版本 14.3.0 -> 14.4.0
|
||||
* `优化` 升级 Androidx WebKit 版本 1.7.0 -> 1.8.0
|
||||
* `优化` 升级 Androidx Preference 版本 1.2.0 -> 1.2.1
|
||||
* `优化` 升级 Androidx Annotation 版本 1.6.0 -> 1.7.0
|
||||
* `优化` 升级 Androidx Recyclerview 版本 1.3.0 -> 1.3.1
|
||||
|
||||
# v6.3.3
|
||||
|
||||
@@ -62,7 +95,7 @@
|
||||
* `优化` 服务端模式开启后保持常开状态 (除非手动关闭或应用进程结束) _[`issue #64`](http://issues.autojs6.com/64#issuecomment-1596990158)_
|
||||
* `优化` 实现 AutoJs6 与 VSCode 插件的双向版本检测并提示异常检测结果 _[`issue #89`](http://issues.autojs6.com/89)_
|
||||
* `优化` 增加短信数据读取权限 (android.permission.READ_SMS) (默认关闭)
|
||||
* `优化` findMultiColors 方法内部实现 (by [LYS](https://github.com/LYS86)) _[`pr #72`](http://pr.autojs6.com/72)_
|
||||
* `优化` findMultiColors 方法内部实现 (by [LYS86](https://github.com/LYS86)) _[`pr #72`](http://pr.autojs6.com/72)_
|
||||
* `优化` runtime.loadDex/loadJar/load 支持按目录级别加载或同时加载多个文件
|
||||
* `优化` 升级 Leakcanary 版本 2.11 -> 2.12
|
||||
* `优化` 升级 Android Analytics 版本 14.2.0 -> 14.3.0
|
||||
@@ -166,7 +199,7 @@
|
||||
* `优化` 升级 Zip4j 版本 2.11.2 -> 2.11.5
|
||||
* `优化` 升级 Junit 版本 5.9.2 -> 5.9.3
|
||||
* `优化` 升级 Androidx Annotation 版本 1.5.0 -> 1.6.0
|
||||
* `优化` 升级 Jackson Databind 版本 2.14.1 -> 2.14.2
|
||||
* `优化` 升级 Jackson DataBind 版本 2.14.1 -> 2.14.2
|
||||
* `优化` 升级 Desugar JDK Libs 版本 2.0.0 -> 2.0.3
|
||||
|
||||
# v6.2.0
|
||||
|
||||
@@ -278,7 +278,7 @@
|
||||
<h3>OCR 特性<span><a class="mark" href="#qa_ocr" id="qa_ocr">#</a></span></h3>
|
||||
<p>AutoJs6 的 OCR 特性是基于 <a href="https://developers.google.com/ml-kit?hl=zh-cn">Google ML Kit</a> 的 <a href="https://developers.google.com/ml-kit/vision/text-recognition/android?hl=zh-cn">文字识别 API</a> 实现的.</p>
|
||||
<blockquote>
|
||||
<p>注: AutoJs6 的 <a href="http://project.autojs6.com/blob/master/app/src/main/java/org/autojs/autojs/runtime/api/MlKitOCR.kt">OCR 实现源码</a> 参考自 <a href="https://github.com/TonyJiangWJ">TonyJiangWJ</a> 的 <a href="https://github.com/TonyJiangWJ/Auto.js">开源项目</a>.</p>
|
||||
<p>注: AutoJs6 的 <a href="http://project.autojs6.com/blob/master/app/src/main/java/org/autojs/autojs/runtime/api/OcrMLKit.kt">OCR 实现源码</a> 参考自 <a href="https://github.com/TonyJiangWJ">TonyJiangWJ</a> 的 <a href="https://github.com/TonyJiangWJ/Auto.js">开源项目</a>.</p>
|
||||
</blockquote>
|
||||
<blockquote>
|
||||
<p>参阅: <a href="ocr.html">光学字符识别 (OCR)</a> 模块</p>
|
||||
|
||||
+27
-18
@@ -23,6 +23,7 @@ let Crypto = org.autojs.autojs.core.crypto.Crypto;
|
||||
let Image = org.autojs.autojs.core.image.ImageWrapper;
|
||||
let ColorTable = org.autojs.autojs.core.image.ColorTable;
|
||||
let Canvas = org.autojs.autojs.core.graphics.ScriptCanvas;
|
||||
let EventEmitter = org.autojs.autojs.core.eventloop.EventEmitter;
|
||||
let UiObject = org.autojs.autojs.core.automator.UiObject;
|
||||
let UiObjectCollection = org.autojs.autojs.core.automator.UiObjectCollection;
|
||||
let ImageWrapper = org.autojs.autojs.core.image.ImageWrapper;
|
||||
@@ -33,6 +34,7 @@ let OkHttpClient = Packages.okhttp3.OkHttpClient;
|
||||
let ScriptInterruptedException = org.autojs.autojs.runtime.exception.ScriptInterruptedException;
|
||||
let ReentrantLock = java.util.concurrent.locks.ReentrantLock;
|
||||
let ScreenMetrics = org.autojs.autojs.runtime.api.ScreenMetrics;
|
||||
let ScriptRuntime = org.autojs.autojs.runtime.ScriptRuntime;
|
||||
let StandardCharsets = java.nio.charset.StandardCharsets;
|
||||
let WebView = android.webkit.WebView;
|
||||
let WebViewClient = android.webkit.WebViewClient;
|
||||
@@ -93,13 +95,6 @@ let JsWebView = org.autojs.autojs.core.ui.widget.JsWebView;
|
||||
/* Global assignment. */
|
||||
|
||||
Object.assign(this, {
|
||||
io: Packages.io,
|
||||
okio: Packages.okio,
|
||||
de: Packages.de,
|
||||
ezy: Packages.ezy,
|
||||
kotlin: Packages.kotlin,
|
||||
okhttp3: Packages.okhttp3,
|
||||
androidx: Packages.androidx,
|
||||
isNullish(o) {
|
||||
// nullish coalescing operator: ??
|
||||
return o === null || o === undefined;
|
||||
@@ -358,15 +353,29 @@ Object.assign(this, {
|
||||
__importClass__(typeof clazz === 'string' ? Packages[clazz] : clazz);
|
||||
});
|
||||
},
|
||||
// 重定向 importPackage 使其支持字符串参数.
|
||||
/**
|
||||
* @global
|
||||
*/
|
||||
importPackage() {
|
||||
Array.from(arguments).forEach(pkg => {
|
||||
__importPackage__(typeof pkg === 'string' ? Packages[pkg] : pkg);
|
||||
});
|
||||
},
|
||||
// FIXME by SuperMonster003 on Jul 27, 2023.
|
||||
// ! This makes importPackage() behave abnormally
|
||||
// ! when calling it in a JavaScript module,
|
||||
// ! even with "with" scope binding expression.
|
||||
// !
|
||||
// // 重定向 importPackage 使其支持字符串参数.
|
||||
// /**
|
||||
// * @global
|
||||
// */
|
||||
// importPackage() {
|
||||
// let args = Array.from(arguments);
|
||||
// let expression =
|
||||
// 'args.forEach((pkg) => {' + '\n' +
|
||||
// ' __importPackage__(typeof pkg === \'string\' ? Packages[pkg] : pkg);' + '\n' +
|
||||
// '});';
|
||||
// // @ScopeBinding
|
||||
// // noinspection WithStatementJS
|
||||
// with (context) {
|
||||
// return (/* @IIFE */ function () {
|
||||
// return eval(expression);
|
||||
// })();
|
||||
// }
|
||||
// },
|
||||
/**
|
||||
* @global
|
||||
*/
|
||||
@@ -485,7 +494,7 @@ Object.assign(this, {
|
||||
|
||||
/* ! ocr < images */
|
||||
/* ! ocr < files */
|
||||
[ 'ocr', 'paddle_ocr' ],
|
||||
[ 'ocr' ],
|
||||
|
||||
/* Safe to put last regardless of the order, no guarantee ;). */
|
||||
[ 'floaty', 'storages', 'device', 'recorder', 'toast' ],
|
||||
@@ -498,7 +507,7 @@ Object.assign(this, {
|
||||
bindPrologue() {
|
||||
// 重定向 require 以支持相对路径和 npm 模块.
|
||||
global.Module = require('jvm-npm');
|
||||
global.require = id => Module.require(id);
|
||||
global.require = Module.require;
|
||||
|
||||
global.i18n.loadAll();
|
||||
global.i18n.setLocale('default');
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
let { util, plugins } = global;
|
||||
|
||||
/**
|
||||
* @param {org.autojs.autojs.runtime.ScriptRuntime} scriptRuntime
|
||||
* @param {ScriptRuntime} scriptRuntime
|
||||
* @param {org.mozilla.javascript.Scriptable | global} scope
|
||||
* @return {Internal.Arrayx}
|
||||
*/
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
let { plugins, Arrayx, Numberx } = global;
|
||||
|
||||
/**
|
||||
* @param {org.autojs.autojs.runtime.ScriptRuntime} scriptRuntime
|
||||
* @param {ScriptRuntime} scriptRuntime
|
||||
* @param {org.mozilla.javascript.Scriptable | global} scope
|
||||
* @return {Internal.Mathx}
|
||||
*/
|
||||
@@ -14,7 +14,7 @@ module.exports = (scriptRuntime, scope) => {
|
||||
* @implements Internal.Mathx
|
||||
*/
|
||||
const MathxCtor = function () {
|
||||
// Empty interface body.
|
||||
/* Empty body. */
|
||||
};
|
||||
|
||||
MathxCtor.prototype = {
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
let { util, plugins } = global;
|
||||
|
||||
/**
|
||||
* @param {org.autojs.autojs.runtime.ScriptRuntime} scriptRuntime
|
||||
* @param {ScriptRuntime} scriptRuntime
|
||||
* @param {org.mozilla.javascript.Scriptable | global} scope
|
||||
* @return {Internal.Numberx}
|
||||
*/
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
let { autojs } = global;
|
||||
|
||||
/**
|
||||
* @param {org.autojs.autojs.runtime.ScriptRuntime} scriptRuntime
|
||||
* @param {ScriptRuntime} scriptRuntime
|
||||
* @param {org.mozilla.javascript.Scriptable | global} scope
|
||||
* @return {Internal.RootAutomator}
|
||||
*/
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
let { autojs, shell, files, util } = global;
|
||||
|
||||
/**
|
||||
* @param {org.autojs.autojs.runtime.ScriptRuntime} scriptRuntime
|
||||
* @param {ScriptRuntime} scriptRuntime
|
||||
* @param {org.mozilla.javascript.Scriptable | global} scope
|
||||
* @return {Internal.App}
|
||||
*/
|
||||
@@ -30,7 +30,7 @@ module.exports = function (scriptRuntime, scope) {
|
||||
* @extends Internal.App
|
||||
*/
|
||||
const App = function () {
|
||||
// Empty interface body.
|
||||
/* Empty body. */
|
||||
};
|
||||
|
||||
App.prototype = {
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
let { util } = global;
|
||||
|
||||
/**
|
||||
* @param {org.autojs.autojs.runtime.ScriptRuntime} scriptRuntime
|
||||
* @param {ScriptRuntime} scriptRuntime
|
||||
* @param {org.mozilla.javascript.Scriptable | global} scope
|
||||
* @return {Internal.Autojs}
|
||||
*/
|
||||
@@ -24,7 +24,7 @@ module.exports = function (scriptRuntime, scope) {
|
||||
* @implements Internal.Autojs
|
||||
*/
|
||||
const Autojs = function () {
|
||||
// Empty interface body.
|
||||
/* Empty body. */
|
||||
};
|
||||
|
||||
Autojs.prototype = {
|
||||
@@ -54,6 +54,18 @@ module.exports = function (scriptRuntime, scope) {
|
||||
},
|
||||
R: global.R,
|
||||
name: context.getString(R.strings.app_name),
|
||||
get rotation() {
|
||||
return ScreenMetrics.getRotation();
|
||||
},
|
||||
get orientation() {
|
||||
return ScreenMetrics.getOrientation();
|
||||
},
|
||||
isScreenPortrait() {
|
||||
return ScreenMetrics.isScreenPortrait();
|
||||
},
|
||||
isScreenLandscape() {
|
||||
return ScreenMetrics.isScreenLandscape();
|
||||
},
|
||||
isRootAvailable() {
|
||||
return RootUtils.isRootAvailable();
|
||||
},
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
let { util } = global;
|
||||
|
||||
/**
|
||||
* @param {org.autojs.autojs.runtime.ScriptRuntime} scriptRuntime
|
||||
* @param {ScriptRuntime} scriptRuntime
|
||||
* @param {org.mozilla.javascript.Scriptable | global} scope
|
||||
* @return {Internal.Automator}
|
||||
*/
|
||||
@@ -136,8 +136,8 @@ module.exports = function (scriptRuntime, scope) {
|
||||
gestureAsync(duration, points) {
|
||||
return rtAutomator.gestureAsync.apply(rtAutomator, [ 0 ].concat(Array.from(arguments)));
|
||||
},
|
||||
swipe(x1, y1, x2, y2, delay) {
|
||||
return rtAutomator.swipe(x1, y1, x2, y2, delay);
|
||||
swipe(x1, y1, x2, y2, duration) {
|
||||
return rtAutomator.swipe(x1, y1, x2, y2, duration);
|
||||
},
|
||||
isServiceRunning() {
|
||||
return rtAutomator.isServiceRunning();
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/**
|
||||
* @param {org.autojs.autojs.runtime.ScriptRuntime} scriptRuntime
|
||||
* @param {ScriptRuntime} scriptRuntime
|
||||
* @param {org.mozilla.javascript.Scriptable | global} scope
|
||||
* @return {Internal.Base64}
|
||||
*/
|
||||
@@ -11,7 +11,7 @@ module.exports = function (scriptRuntime, scope) {
|
||||
* @implements Internal.Base64
|
||||
*/
|
||||
const Base64Ctor = function () {
|
||||
// Empty interface body.
|
||||
/* Empty body. */
|
||||
};
|
||||
|
||||
Base64Ctor.prototype = {
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
let { util } = global;
|
||||
|
||||
/**
|
||||
* @param {org.autojs.autojs.runtime.ScriptRuntime} scriptRuntime
|
||||
* @param {ScriptRuntime} scriptRuntime
|
||||
* @param {org.mozilla.javascript.Scriptable | global} scope
|
||||
* @return {Internal.Colors}
|
||||
*/
|
||||
@@ -63,10 +63,10 @@ module.exports = function (scriptRuntime, scope) {
|
||||
Color.prototype = {
|
||||
constructor: Color,
|
||||
toString() {
|
||||
return this.digest();
|
||||
return this.summary();
|
||||
},
|
||||
digest() {
|
||||
return colors.digest.apply(colors, [ this.color ].concat(Array.from(arguments)));
|
||||
summary() {
|
||||
return colors.summary.apply(colors, [ this.color ].concat(Array.from(arguments)));
|
||||
},
|
||||
toHex() {
|
||||
return colors.toHex.apply(colors, [ this.color ].concat(Array.from(arguments)));
|
||||
@@ -250,7 +250,7 @@ module.exports = function (scriptRuntime, scope) {
|
||||
* @extends Internal.Colors
|
||||
*/
|
||||
const Colors = function () {
|
||||
// Empty class body.
|
||||
/* Empty body. */
|
||||
};
|
||||
|
||||
Colors.prototype = {
|
||||
@@ -666,7 +666,7 @@ module.exports = function (scriptRuntime, scope) {
|
||||
let args = [ _.Color ].concat(Array.from(arguments));
|
||||
return new (Function.prototype.bind.apply(_.Color, args));
|
||||
},
|
||||
digest(color) {
|
||||
summary(color) {
|
||||
let [ r, g, b, a ] = this.toRgba(color);
|
||||
let niceA = _.toDoubleComponent(a).toFixed(2).replace(/0$/, '');
|
||||
return `hex(${this.toHex(color)}), rgba(${r},${g},${b}/${niceA}), int(${this.toInt(color)})`;
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
let { files, util, s13n } = global;
|
||||
|
||||
/**
|
||||
* @param {org.autojs.autojs.runtime.ScriptRuntime} scriptRuntime
|
||||
* @param {ScriptRuntime} scriptRuntime
|
||||
* @param {org.mozilla.javascript.Scriptable | global} scope
|
||||
* @return {Internal.Console}
|
||||
*/
|
||||
@@ -27,7 +27,7 @@ module.exports = function (scriptRuntime, scope) {
|
||||
* @extends Internal.Console
|
||||
*/
|
||||
const Console = function () {
|
||||
// Empty interface body.
|
||||
/* Empty body. */
|
||||
};
|
||||
|
||||
Console.prototype = {
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
let { engines, global: _global } = global;
|
||||
|
||||
/**
|
||||
* @param {org.autojs.autojs.runtime.ScriptRuntime} scriptRuntime
|
||||
* @param {ScriptRuntime} scriptRuntime
|
||||
* @param {org.mozilla.javascript.Scriptable | global} scope
|
||||
* @return {Internal.Continuation}
|
||||
*/
|
||||
@@ -41,7 +41,13 @@ module.exports = function (scriptRuntime, scope) {
|
||||
*/
|
||||
let result = this.cont.suspend();
|
||||
if (result.error !== null) {
|
||||
throw result.error;
|
||||
// throw result.error;
|
||||
if (typeof result.error.message === 'string') {
|
||||
ScriptRuntime.popException(result.error.message);
|
||||
} else {
|
||||
ScriptRuntime.popException(String(result.error));
|
||||
}
|
||||
return result.error;
|
||||
}
|
||||
return result.result;
|
||||
},
|
||||
@@ -64,7 +70,7 @@ module.exports = function (scriptRuntime, scope) {
|
||||
*/
|
||||
const Continuation = function () {
|
||||
return Object.assign(function () {
|
||||
// Empty interface body.
|
||||
/* Empty body. */
|
||||
}, Continuation.prototype);
|
||||
};
|
||||
|
||||
@@ -97,7 +103,7 @@ module.exports = function (scriptRuntime, scope) {
|
||||
* @implements Internal.Continuation.PromiseExtension
|
||||
*/
|
||||
const PromiseExtension = function () {
|
||||
// Empty interface body.
|
||||
/* Empty body. */
|
||||
};
|
||||
|
||||
Object.assign(PromiseExtension.prototype, {
|
||||
|
||||
@@ -3,12 +3,11 @@
|
||||
let { util } = global;
|
||||
|
||||
/**
|
||||
* @param {org.autojs.autojs.runtime.ScriptRuntime} scriptRuntime
|
||||
* @param {ScriptRuntime} scriptRuntime
|
||||
* @param {org.mozilla.javascript.Scriptable | global} scope
|
||||
* @return {Internal.Device}
|
||||
*/
|
||||
module.exports = function (scriptRuntime, scope) {
|
||||
const ScreenMetrics = org.autojs.autojs.runtime.api.ScreenMetrics;
|
||||
const NetworkUtils = org.autojs.autojs.util.NetworkUtils;
|
||||
const DeviceUtils = org.autojs.autojs.util.DeviceUtils;
|
||||
|
||||
@@ -20,7 +19,7 @@ module.exports = function (scriptRuntime, scope) {
|
||||
* @extends Internal.Device
|
||||
*/
|
||||
const Device = function () {
|
||||
// Empty interface body.
|
||||
/* Empty body. */
|
||||
};
|
||||
|
||||
Device.prototype = {
|
||||
@@ -32,7 +31,10 @@ module.exports = function (scriptRuntime, scope) {
|
||||
return ScreenMetrics.getDeviceScreenHeight();
|
||||
},
|
||||
get rotation() {
|
||||
return ScreenMetrics.getRotation();
|
||||
return rtDevice.getRotation();
|
||||
},
|
||||
get orientation() {
|
||||
return rtDevice.getOrientation();
|
||||
},
|
||||
get density() {
|
||||
return ScreenMetrics.getDeviceScreenDensity();
|
||||
@@ -63,6 +65,12 @@ module.exports = function (scriptRuntime, scope) {
|
||||
isScreenOff() {
|
||||
return !rtDevice.isScreenOn();
|
||||
},
|
||||
isScreenPortrait() {
|
||||
return rtDevice.isScreenPortrait();
|
||||
},
|
||||
isScreenLandscape() {
|
||||
return rtDevice.isScreenLandscape();
|
||||
},
|
||||
getIpAddress(useIPv4) {
|
||||
return useIPv4 === undefined
|
||||
? NetworkUtils.getIpAddress()
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
let { colors, threads, ui } = global;
|
||||
|
||||
/**
|
||||
* @param {org.autojs.autojs.runtime.ScriptRuntime} scriptRuntime
|
||||
* @param {ScriptRuntime} scriptRuntime
|
||||
* @param {org.mozilla.javascript.Scriptable | global} scope
|
||||
* @return {Internal.Dialogs}
|
||||
*/
|
||||
@@ -19,7 +19,7 @@ module.exports = function (scriptRuntime, scope) {
|
||||
* @implements Internal.Dialogs
|
||||
*/
|
||||
const Dialogs = function () {
|
||||
// Empty interface body.
|
||||
/* Empty body. */
|
||||
};
|
||||
|
||||
Dialogs.prototype = {
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
let { files } = global;
|
||||
|
||||
/**
|
||||
* @param {org.autojs.autojs.runtime.ScriptRuntime} scriptRuntime
|
||||
* @param {ScriptRuntime} scriptRuntime
|
||||
* @param {org.mozilla.javascript.Scriptable | global} scope
|
||||
* @return {Internal.Engines}
|
||||
*/
|
||||
@@ -18,7 +18,7 @@ module.exports = function (scriptRuntime, scope) {
|
||||
* @extends Internal.Engines
|
||||
*/
|
||||
const Engines = function () {
|
||||
// Empty class body.
|
||||
/* Empty body. */
|
||||
};
|
||||
|
||||
Engines.prototype = {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
// noinspection JSUnusedGlobalSymbols
|
||||
|
||||
/**
|
||||
* @param {org.autojs.autojs.runtime.ScriptRuntime} scriptRuntime
|
||||
* @param {ScriptRuntime} scriptRuntime
|
||||
* @param {org.mozilla.javascript.Scriptable | global} scope
|
||||
* @return {Internal.Events}
|
||||
*/
|
||||
@@ -12,7 +12,7 @@ module.exports = function (scriptRuntime, scope) {
|
||||
* @extends Internal.Events
|
||||
*/
|
||||
const Events = function () {
|
||||
// Empty class body.
|
||||
/* Empty body. */
|
||||
};
|
||||
|
||||
Events.prototype = {
|
||||
@@ -37,7 +37,7 @@ module.exports = function (scriptRuntime, scope) {
|
||||
* @implements Internal.Keys
|
||||
*/
|
||||
const Keys = function () {
|
||||
// Empty interface body.
|
||||
/* Empty body. */
|
||||
};
|
||||
|
||||
Keys.prototype = {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/**
|
||||
* @param {org.autojs.autojs.runtime.ScriptRuntime} scriptRuntime
|
||||
* @param {ScriptRuntime} scriptRuntime
|
||||
* @param {org.mozilla.javascript.Scriptable | global} scope
|
||||
* @return {Internal.Files}
|
||||
*/
|
||||
@@ -12,7 +12,7 @@ module.exports = function (scriptRuntime, scope) {
|
||||
* @extends Internal.Files
|
||||
*/
|
||||
const Files = function () {
|
||||
// Empty class body.
|
||||
/* Empty body. */
|
||||
};
|
||||
|
||||
Files.prototype = {
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
// noinspection UnnecessaryLocalVariableJS
|
||||
|
||||
/**
|
||||
* @param {org.autojs.autojs.runtime.ScriptRuntime} scriptRuntime
|
||||
* @param {ScriptRuntime} scriptRuntime
|
||||
* @param {org.mozilla.javascript.Scriptable | global} scope
|
||||
* @return {Internal.Floaty}
|
||||
*/
|
||||
@@ -12,7 +14,7 @@ module.exports = function (scriptRuntime, scope) {
|
||||
* @implements Internal.Floaty
|
||||
*/
|
||||
const Floaty = function () {
|
||||
// Empty interface body.
|
||||
/* Empty body. */
|
||||
};
|
||||
|
||||
Floaty.prototype = {
|
||||
@@ -28,6 +30,7 @@ module.exports = function (scriptRuntime, scope) {
|
||||
},
|
||||
hasPermission: () => rtFloaty.hasPermission(),
|
||||
requestPermission: () => rtFloaty.requestPermission(),
|
||||
ensurePermission: () => rtFloaty.ensurePermission(),
|
||||
};
|
||||
|
||||
return Floaty;
|
||||
|
||||
@@ -7,8 +7,6 @@ let { autojs, console, device, pickup, ui, s13n, Numberx } = global;
|
||||
/* Here, importClass() is not recommended for intelligent code completion in IDE like WebStorm. */
|
||||
/* The same is true of destructuring assignment syntax (like `let {Uri} = android.net`). */
|
||||
|
||||
let ScriptRuntime = org.autojs.autojs.runtime.ScriptRuntime;
|
||||
|
||||
/**
|
||||
* @param {org.autojs.autojs.runtime.ScriptRuntime} runtime
|
||||
* @param {org.mozilla.javascript.Scriptable | global} scope
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
let { ui } = global;
|
||||
|
||||
/**
|
||||
* @param {org.autojs.autojs.runtime.ScriptRuntime} scriptRuntime
|
||||
* @param {ScriptRuntime} scriptRuntime
|
||||
* @param {org.mozilla.javascript.Scriptable | global} scope
|
||||
* @return {Internal.Http}
|
||||
*/
|
||||
@@ -26,7 +26,7 @@ module.exports = function (scriptRuntime, scope) {
|
||||
* @implements Internal.Http
|
||||
*/
|
||||
const Http = function () {
|
||||
// Empty interface body.
|
||||
/* Empty body. */
|
||||
};
|
||||
|
||||
Http.prototype = {
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
let { files } = global;
|
||||
|
||||
/**
|
||||
* @param {org.autojs.autojs.runtime.ScriptRuntime} scriptRuntime
|
||||
* @param {ScriptRuntime} scriptRuntime
|
||||
* @param {org.mozilla.javascript.Scriptable | global} scope
|
||||
* @return {Internal.I18n}
|
||||
*/
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
let { files, util, ui, threads } = global;
|
||||
|
||||
/**
|
||||
* @param {org.autojs.autojs.runtime.ScriptRuntime} scriptRuntime
|
||||
* @param {ScriptRuntime} scriptRuntime
|
||||
* @param {org.mozilla.javascript.Scriptable | global} scope
|
||||
* @return {Internal.Images}
|
||||
*/
|
||||
@@ -42,7 +42,7 @@ module.exports = function (scriptRuntime, scope) {
|
||||
*/
|
||||
const Images = function () {
|
||||
return Object.assign(function () {
|
||||
// Empty interface body.
|
||||
/* Empty body. */
|
||||
}, Images.prototype);
|
||||
};
|
||||
|
||||
@@ -577,19 +577,23 @@ module.exports = function (scriptRuntime, scope) {
|
||||
};
|
||||
|
||||
/**
|
||||
* @class
|
||||
* @extends Images.MatchingResult
|
||||
* @param {Images.TemplateMatch[] | java.lang.Iterable<Images.TemplateMatch>} list
|
||||
*/
|
||||
const MatchingResult = function (list) {
|
||||
Object.defineProperties(this, {
|
||||
matches: {
|
||||
value: Array.isArray(list) ? list : scriptRuntime.bridges.getBridges().toArray(list),
|
||||
enumerable: true,
|
||||
},
|
||||
points: {
|
||||
get() {
|
||||
return this.matches.map(m => m.point);
|
||||
},
|
||||
enumerable: false,
|
||||
Object.assign(this, {
|
||||
matches: (() => {
|
||||
if (Array.isArray(list)) {
|
||||
return list;
|
||||
}
|
||||
// noinspection UnnecessaryLocalVariableJS
|
||||
/** @type Images.TemplateMatch[] */
|
||||
let results = scriptRuntime.bridges.getBridges().toArray(list);
|
||||
return results;
|
||||
})(),
|
||||
get points() {
|
||||
return this.matches.map(m => m.point);
|
||||
},
|
||||
});
|
||||
};
|
||||
@@ -606,6 +610,9 @@ module.exports = function (scriptRuntime, scope) {
|
||||
if (!this.matches.length) {
|
||||
return null;
|
||||
}
|
||||
/**
|
||||
* @type Images.TemplateMatch
|
||||
*/
|
||||
let target = this.matches[0];
|
||||
this.matches.forEach(m => target = compareFn(target, m) > 0 ? m : target);
|
||||
return target;
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/**
|
||||
* @param {org.autojs.autojs.runtime.ScriptRuntime} scriptRuntime
|
||||
* @param {ScriptRuntime} scriptRuntime
|
||||
* @param {org.mozilla.javascript.Scriptable | global} scope
|
||||
* @return {Internal.Media}
|
||||
*/
|
||||
@@ -10,7 +10,7 @@ module.exports = function (scriptRuntime, scope) {
|
||||
* @extends Internal.Media
|
||||
*/
|
||||
const Media = function () {
|
||||
// Empty interface body.
|
||||
/* Empty body. */
|
||||
};
|
||||
|
||||
Media.prototype = {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
// noinspection JSUnusedLocalSymbols,UnnecessaryLocalVariableJS
|
||||
|
||||
/**
|
||||
* @param {org.autojs.autojs.runtime.ScriptRuntime} scriptRuntime
|
||||
* @param {ScriptRuntime} scriptRuntime
|
||||
* @param {org.mozilla.javascript.Scriptable | global} scope
|
||||
* @return {Internal.Notice}
|
||||
*/
|
||||
@@ -47,7 +47,7 @@ module.exports = function (scriptRuntime, scope) {
|
||||
* @implements {Notice.Config}
|
||||
*/
|
||||
const Config = function () {
|
||||
// Empty interface body.
|
||||
/* Empty body. */
|
||||
};
|
||||
|
||||
Config.prototype = {
|
||||
@@ -86,7 +86,7 @@ module.exports = function (scriptRuntime, scope) {
|
||||
* @implements {Notice.Channel}
|
||||
*/
|
||||
const Channel = function () {
|
||||
// Empty interface body.
|
||||
/* Empty body. */
|
||||
};
|
||||
|
||||
Channel.prototype = {
|
||||
|
||||
@@ -1,95 +1,228 @@
|
||||
// noinspection UnnecessaryLocalVariableJS,JSUnusedLocalSymbols
|
||||
// noinspection JSUnusedLocalSymbols
|
||||
|
||||
/* Overwritten protection. */
|
||||
|
||||
let { images, files } = global;
|
||||
let { images } = global;
|
||||
|
||||
/**
|
||||
* @param {org.autojs.autojs.runtime.ScriptRuntime} scriptRuntime
|
||||
* @param {ScriptRuntime} scriptRuntime
|
||||
* @param {org.mozilla.javascript.Scriptable | global} scope
|
||||
* @return {Internal.Ocr}
|
||||
*/
|
||||
module.exports = function (scriptRuntime, scope) {
|
||||
|
||||
const rtOcr = scriptRuntime.mlKitOCR;
|
||||
|
||||
let _ = {
|
||||
OcrCtor: (/* @IIFE */ () => {
|
||||
|
||||
/**
|
||||
* @type {{[modeName in Internal.Ocr.ModeName]: Internal.Ocr.ModeName}}
|
||||
*/
|
||||
const modeName = {
|
||||
mlkit: 'mlkit',
|
||||
paddle: 'paddle',
|
||||
unknown: 'unknown',
|
||||
};
|
||||
|
||||
/**
|
||||
* @type {Internal.Ocr.ModeName}
|
||||
*/
|
||||
let _mode = modeName.unknown;
|
||||
|
||||
const defaultPrivateDescriptor = {
|
||||
configurable: false,
|
||||
writable: false,
|
||||
enumerable: false,
|
||||
};
|
||||
|
||||
const defaultProtectedDescriptor = {
|
||||
configurable: false,
|
||||
writable: false,
|
||||
enumerable: true, /* Emphasis. */
|
||||
};
|
||||
|
||||
const instanceFunc = function (img, options) {
|
||||
if (typeof arguments[0] === 'string') {
|
||||
let img = images.read(/* path = */ arguments[0]);
|
||||
if (img === null) {
|
||||
throw TypeError(`Invalid image of path "${arguments[0]}" for ocr(img, options?)`);
|
||||
}
|
||||
return OcrCtor.prototype.recognizeText(img.oneShot(), options);
|
||||
}
|
||||
return OcrCtor.prototype.recognizeText.apply(OcrCtor.prototype, arguments);
|
||||
};
|
||||
|
||||
/**
|
||||
* @implements Internal.Ocr
|
||||
*/
|
||||
const OcrCtor = function () {
|
||||
|
||||
/** @global */
|
||||
const ocr = function (img, options) {
|
||||
if (typeof arguments[0] === 'string') {
|
||||
let img = images.read(/* path = */ arguments[0]);
|
||||
if (img === null) {
|
||||
throw TypeError(`Invalid image of path "${arguments[0]}" for ocr(img, options?)`);
|
||||
}
|
||||
return OcrCtor.prototype.recognizeText(img.oneShot(), options);
|
||||
}
|
||||
return OcrCtor.prototype.recognizeText.apply(OcrCtor.prototype, arguments);
|
||||
};
|
||||
|
||||
return Object.assign(ocr, OcrCtor.prototype);
|
||||
let o = Object.assign(instanceFunc, OcrCtor.prototype);
|
||||
Object.defineProperties(instanceFunc, Object.getOwnPropertyDescriptors(OcrCtor.prototype));
|
||||
return o;
|
||||
};
|
||||
|
||||
OcrCtor.prototype = {
|
||||
constructor: OcrCtor,
|
||||
recognizeText(img, options) {
|
||||
_modeName: modeName,
|
||||
_forcibleModeArgIndex: 10,
|
||||
mlkit: require('ocr-mlkit')(scriptRuntime, scope),
|
||||
paddle: require('ocr-paddle')(scriptRuntime, scope),
|
||||
get mode() {
|
||||
return _mode;
|
||||
},
|
||||
set mode(mode) {
|
||||
this.tap(mode);
|
||||
},
|
||||
tap(mode) {
|
||||
if (mode === this.mlkit || String(mode).toLowerCase() === modeName.mlkit) {
|
||||
_mode = modeName.mlkit;
|
||||
} else if (mode === this.paddle || String(mode).toLowerCase() === modeName.paddle) {
|
||||
_mode = modeName.paddle;
|
||||
} else {
|
||||
_mode = modeName.unknown;
|
||||
throw TypeError(`Unknown mode (value: ${mode}, species: ${species(mode)}) for ocr.tap(mode)`);
|
||||
}
|
||||
},
|
||||
recognizeText() {
|
||||
if (typeof arguments[0] === 'string') {
|
||||
|
||||
// @Signature
|
||||
// recognizeText(imgPath: string, options?: DetectOptionsMLKit | DetectOptionsPaddle): string[];
|
||||
// recognizeText(imgPath: string, region: Images.Options.Region): string[];
|
||||
|
||||
let img = images.read(/* path = */ arguments[0]);
|
||||
if (img === null) {
|
||||
throw TypeError(`Invalid image of path "${arguments[0]}" for ocr.recognizeText(img, options?)`);
|
||||
}
|
||||
return this.recognizeText(img.oneShot(), options);
|
||||
// @Overload
|
||||
// recognizeText(img: ImageWrapper, options?: DetectOptionsMLKit | DetectOptionsPaddle): string[];
|
||||
// recognizeText(img: ImageWrapper, region: Images.Options.Region): string[];
|
||||
return this.recognizeText(img.oneShot(), arguments[1]);
|
||||
}
|
||||
if (_.shouldTakenAsRegion(arguments[1])) {
|
||||
|
||||
// @Signature recognizeText(img: ImageWrapper, region: Images.Options.Region): string[];
|
||||
|
||||
// @Overload recognizeText(img: ImageWrapper, options: DetectOptionsMLKit | DetectOptionsPaddle): string[];
|
||||
return this.recognizeText(img, { region: arguments[1] });
|
||||
}
|
||||
let opt = options || {};
|
||||
|
||||
// @Signature recognizeText(img: ImageWrapper, options?: DetectOptionsMLKit | DetectOptionsPaddle): string[];
|
||||
|
||||
/** @type {Internal.Ocr.DetectOptions} */
|
||||
let opt = /* options */ arguments[1] || {};
|
||||
let region = opt.region;
|
||||
if (region === null) {
|
||||
return [];
|
||||
}
|
||||
if (region === undefined) {
|
||||
return Array.from(rtOcr.recognizeText(img));
|
||||
|
||||
/** @type Internal.Ocr.RecognizeTextMethod */
|
||||
let recognizeTextMethod;
|
||||
|
||||
switch (arguments[OcrCtor.prototype._forcibleModeArgIndex] || _mode) {
|
||||
case modeName.mlkit:
|
||||
recognizeTextMethod = this.mlkit.recognizeTextMethodCreator(opt);
|
||||
break;
|
||||
case modeName.paddle:
|
||||
recognizeTextMethod = this.paddle.recognizeTextMethodCreator(opt);
|
||||
break;
|
||||
default:
|
||||
throw TypeError(`Can't call ocr.recognizeText with an unknown mode (value: ${_mode}, species: ${species(_mode)})`);
|
||||
}
|
||||
let results = Array.from(rtOcr.recognizeText(images.clip(img, region).oneShot()));
|
||||
|
||||
let img = arguments[0];
|
||||
if (region === undefined) {
|
||||
return recognizeTextMethod(img);
|
||||
}
|
||||
let results = recognizeTextMethod(
|
||||
images.clip(img, region).oneShot(),
|
||||
);
|
||||
img.shoot();
|
||||
return results;
|
||||
},
|
||||
detect(img, options) {
|
||||
detect() {
|
||||
if (typeof arguments[0] === 'string') {
|
||||
|
||||
// @Signature
|
||||
// detect(imgPath: string, options?: DetectOptionsMLKit | DetectOptionsPaddle): org.autojs.autojs.runtime.api.OcrResult[];
|
||||
// detect(imgPath: string, region: Images.Options.Region): org.autojs.autojs.runtime.api.OcrResult[];
|
||||
|
||||
let img = images.read(/* path = */ arguments[0]);
|
||||
if (img === null) {
|
||||
throw TypeError(`Invalid image of path "${arguments[0]}" for ocr.detect(img, options?)`);
|
||||
}
|
||||
return this.detect(img.oneShot(), options);
|
||||
// @Overload
|
||||
// detect(img: ImageWrapper, options?: DetectOptionsMLKit | DetectOptionsPaddle): org.autojs.autojs.runtime.api.OcrResult[];
|
||||
// detect(img: ImageWrapper, region: Images.Options.Region): org.autojs.autojs.runtime.api.OcrResult[];
|
||||
return this.detect(img.oneShot(), arguments[1]);
|
||||
}
|
||||
if (_.shouldTakenAsRegion(arguments[1])) {
|
||||
|
||||
// @Signature detect(img: ImageWrapper, region: Images.Options.Region): org.autojs.autojs.runtime.api.OcrResult[];
|
||||
|
||||
// @Overload detect(img: ImageWrapper, options: DetectOptionsMLKit | DetectOptionsPaddle): org.autojs.autojs.runtime.api.OcrResult[];
|
||||
return this.detect(img, { region: arguments[1] });
|
||||
}
|
||||
let opt = options || {};
|
||||
|
||||
// @Signature detect(img: ImageWrapper, options?: DetectOptionsMLKit | DetectOptionsPaddle): org.autojs.autojs.runtime.api.OcrResult[];
|
||||
|
||||
let opt = /* options */ arguments[1] || {};
|
||||
let region = opt.region;
|
||||
if (region === null) {
|
||||
return [];
|
||||
}
|
||||
/**
|
||||
* @type {org.autojs.autojs.runtime.api.OcrResult[]}
|
||||
*/
|
||||
let resultList = rtOcr.detect(region !== undefined ? images.clip(img, region).oneShot() : img).toArray();
|
||||
if (!isNullish(region)) {
|
||||
resultList.forEach((result) => {
|
||||
let rect = images.buildRegion(img, region);
|
||||
result.bounds.offset(rect.x, rect.y);
|
||||
});
|
||||
|
||||
/** type {Internal.Ocr.DetectMethod} */
|
||||
let detectMethod;
|
||||
|
||||
switch (_mode) {
|
||||
case modeName.mlkit:
|
||||
detectMethod = this.mlkit.detectMethodCreator(opt);
|
||||
break;
|
||||
case modeName.paddle:
|
||||
detectMethod = this.paddle.detectMethodCreator(opt);
|
||||
break;
|
||||
default:
|
||||
throw TypeError(`Can't call ocr.detect with an unknown mode (value: ${_mode}, species: ${species(_mode)})`);
|
||||
}
|
||||
return Array.from(resultList);
|
||||
|
||||
let img = arguments[0];
|
||||
if (region === undefined) {
|
||||
return detectMethod(img);
|
||||
}
|
||||
let results = detectMethod(images.clip(img, region).oneShot());
|
||||
results.forEach((result) => {
|
||||
let rect = images.buildRegion(img, region);
|
||||
result.bounds.offset(rect.x, rect.y);
|
||||
});
|
||||
img.shoot();
|
||||
return results;
|
||||
},
|
||||
summary() {
|
||||
return [
|
||||
`[ OCR summary ]`,
|
||||
`Current mode: ${this.mode}`,
|
||||
`Available modes: [ ${Object.values(modeName).filter(n => n !== modeName.unknown).join(', ')} ]`,
|
||||
].join('\n');
|
||||
},
|
||||
toString() {
|
||||
return this.summary();
|
||||
},
|
||||
};
|
||||
|
||||
/* Set prototype descriptors. */
|
||||
|
||||
Object.defineProperties(OcrCtor.prototype, {
|
||||
_modeName: defaultPrivateDescriptor,
|
||||
_forcibleModeArgIndex: defaultPrivateDescriptor,
|
||||
mode: { configurable: false },
|
||||
constructor: defaultProtectedDescriptor,
|
||||
mlkit: defaultProtectedDescriptor,
|
||||
paddle: defaultProtectedDescriptor,
|
||||
tap: defaultProtectedDescriptor,
|
||||
summary: defaultProtectedDescriptor,
|
||||
toString: defaultProtectedDescriptor,
|
||||
});
|
||||
|
||||
return OcrCtor;
|
||||
})(),
|
||||
shouldTakenAsRegion(o) {
|
||||
@@ -104,5 +237,8 @@ module.exports = function (scriptRuntime, scope) {
|
||||
*/
|
||||
const ocr = new _.OcrCtor();
|
||||
|
||||
/* Init OCR mode with MLKit. */
|
||||
ocr.mode = 'mlkit';
|
||||
|
||||
return ocr;
|
||||
};
|
||||
@@ -1,120 +0,0 @@
|
||||
// noinspection UnnecessaryLocalVariableJS,JSUnusedLocalSymbols
|
||||
|
||||
/* Overwritten protection. */
|
||||
|
||||
let { images } = global;
|
||||
|
||||
/**
|
||||
* @param {org.autojs.autojs.runtime.ScriptRuntime} scriptRuntime
|
||||
* @param {org.mozilla.javascript.Scriptable | global} scope
|
||||
* @return {Internal.Ocr}
|
||||
*/
|
||||
module.exports = function (scriptRuntime, scope) {
|
||||
|
||||
const rtOcr = scriptRuntime.paddleOCR;
|
||||
|
||||
let _ = {
|
||||
OcrCtor: (/* @IIFE */ () => {
|
||||
/**
|
||||
* @implements Internal.Ocr
|
||||
*/
|
||||
const OcrCtor = function () {
|
||||
|
||||
/** @global */
|
||||
const ocr = function (img, options) {
|
||||
if (typeof arguments[0] === 'string') {
|
||||
let img = images.read(/* path = */ arguments[0]);
|
||||
if (img === null) {
|
||||
throw TypeError(`Invalid image of path "${arguments[0]}" for ocr(img, options?)`);
|
||||
}
|
||||
return OcrCtor.prototype.recognizeText(img.oneShot(), options);
|
||||
}
|
||||
return OcrCtor.prototype.recognizeText.apply(OcrCtor.prototype, arguments);
|
||||
};
|
||||
|
||||
return Object.assign(ocr, OcrCtor.prototype);
|
||||
};
|
||||
|
||||
OcrCtor.prototype = {
|
||||
constructor: OcrCtor,
|
||||
recognizeText(img, options) {
|
||||
if (typeof arguments[0] === 'string') {
|
||||
let img = images.read(/* path = */ arguments[0]);
|
||||
if (img === null) {
|
||||
throw TypeError(`Invalid image of path "${arguments[0]}" for ocr.recognizeText(img, options?)`);
|
||||
}
|
||||
return this.recognizeText(img.oneShot(), options);
|
||||
}
|
||||
if (_.shouldTakenAsRegion(arguments[1])) {
|
||||
return this.recognizeText(img, { region: arguments[1] });
|
||||
}
|
||||
let opt = options || {};
|
||||
let region = opt.region;
|
||||
if (region === null) {
|
||||
return [];
|
||||
}
|
||||
let cpuThreadNum = opt.cpuThreadNum || 4
|
||||
let useSlim = opt.useSlim
|
||||
if (useSlim === undefined) {
|
||||
// 默认使用轻量化模型
|
||||
useSlim = true
|
||||
}
|
||||
if (region === undefined) {
|
||||
return Array.from(rtOcr.recognizeText(img, cpuThreadNum, useSlim));
|
||||
}
|
||||
let results = Array.from(rtOcr.recognizeText(images.clip(img, region).oneShot()));
|
||||
img.shoot();
|
||||
return results;
|
||||
},
|
||||
detect(img, options) {
|
||||
if (typeof arguments[0] === 'string') {
|
||||
let img = images.read(/* path = */ arguments[0]);
|
||||
if (img === null) {
|
||||
throw TypeError(`Invalid image of path "${arguments[0]}" for ocr.detect(img, options?)`);
|
||||
}
|
||||
return this.detect(img.oneShot(), options);
|
||||
}
|
||||
if (_.shouldTakenAsRegion(arguments[1])) {
|
||||
return this.detect(img, { region: arguments[1] });
|
||||
}
|
||||
let opt = options || {};
|
||||
let region = opt.region;
|
||||
if (region === null) {
|
||||
return [];
|
||||
}
|
||||
let cpuThreadNum = opt.cpuThreadNum || 4
|
||||
let useSlim = opt.useSlim
|
||||
if (useSlim === undefined) {
|
||||
// 默认使用轻量化模型
|
||||
useSlim = true
|
||||
}
|
||||
/**
|
||||
* @type {org.autojs.autojs.runtime.api.OcrResult[]}
|
||||
*/
|
||||
let resultList = rtOcr.detect(region !== undefined ? images.clip(img, region).oneShot() : img, cpuThreadNum, useSlim).toArray();
|
||||
if (!isNullish(region)) {
|
||||
resultList.forEach((result) => {
|
||||
let rect = images.buildRegion(img, region);
|
||||
result.bounds.offset(rect.x, rect.y);
|
||||
});
|
||||
}
|
||||
return Array.from(resultList);
|
||||
},
|
||||
};
|
||||
|
||||
return OcrCtor;
|
||||
})(),
|
||||
shouldTakenAsRegion(o) {
|
||||
return o instanceof org.opencv.core.Rect
|
||||
|| o instanceof android.graphics.Rect
|
||||
|| Array.isArray(o);
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* @type {Internal.Ocr}
|
||||
*/
|
||||
const ocr = new _.OcrCtor();
|
||||
|
||||
return ocr;
|
||||
};
|
||||
@@ -1,5 +1,5 @@
|
||||
/**
|
||||
* @param {org.autojs.autojs.runtime.ScriptRuntime} scriptRuntime
|
||||
* @param {ScriptRuntime} scriptRuntime
|
||||
* @param {org.mozilla.javascript.Scriptable | global} scope
|
||||
* @return {Internal.Plugins}
|
||||
*/
|
||||
@@ -10,7 +10,7 @@ module.exports = function (scriptRuntime, scope) {
|
||||
* @implements Internal.Plugins
|
||||
*/
|
||||
const Plugins = function () {
|
||||
// Empty interface body.
|
||||
/* Empty body. */
|
||||
};
|
||||
|
||||
Plugins.prototype = {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
// noinspection JSUnusedGlobalSymbols
|
||||
|
||||
/**
|
||||
* @param {org.autojs.autojs.runtime.ScriptRuntime} scriptRuntime
|
||||
* @param {ScriptRuntime} scriptRuntime
|
||||
* @param {org.mozilla.javascript.Scriptable | global} scope
|
||||
* @return {Internal.Recorder}
|
||||
*/
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
// noinspection JSUnusedLocalSymbols,UnnecessaryLocalVariableJS
|
||||
|
||||
/**
|
||||
* @param {org.autojs.autojs.runtime.ScriptRuntime} scriptRuntime
|
||||
* @param {ScriptRuntime} scriptRuntime
|
||||
* @param {org.mozilla.javascript.Scriptable | global} scope
|
||||
* @return {Internal.S13n}
|
||||
*/
|
||||
@@ -12,7 +12,7 @@ module.exports = function (scriptRuntime, scope) {
|
||||
* @extends Internal.S13n
|
||||
*/
|
||||
const S13n = function () {
|
||||
// Empty interface body.
|
||||
/* Empty body. */
|
||||
};
|
||||
|
||||
S13n.prototype = {
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
let { i18n } = global;
|
||||
|
||||
/**
|
||||
* @param {org.autojs.autojs.runtime.ScriptRuntime} scriptRuntime
|
||||
* @param {ScriptRuntime} scriptRuntime
|
||||
* @param {org.mozilla.javascript.Scriptable | global} scope
|
||||
* @return {() => Internal.Selector}
|
||||
*/
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/**
|
||||
* @param {org.autojs.autojs.runtime.ScriptRuntime} scriptRuntime
|
||||
* @param {ScriptRuntime} scriptRuntime
|
||||
* @param {org.mozilla.javascript.Scriptable | global} scope
|
||||
* @return {Internal.Sensors}
|
||||
*/
|
||||
@@ -10,7 +10,7 @@ module.exports = function (scriptRuntime, scope) {
|
||||
* @extends Internal.Sensors
|
||||
*/
|
||||
const Sensors = function () {
|
||||
// Empty interface body.
|
||||
/* Empty body. */
|
||||
};
|
||||
|
||||
Sensors.prototype = {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/**
|
||||
* @param {org.autojs.autojs.runtime.ScriptRuntime} scriptRuntime
|
||||
* @param {ScriptRuntime} scriptRuntime
|
||||
* @param {org.mozilla.javascript.Scriptable | global} scope
|
||||
* @return {Internal.Shell}
|
||||
*/
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/**
|
||||
* @param {org.autojs.autojs.runtime.ScriptRuntime} scriptRuntime
|
||||
* @param {ScriptRuntime} scriptRuntime
|
||||
* @param {org.mozilla.javascript.Scriptable | global} scope
|
||||
* @return {Internal.Storages}
|
||||
*/
|
||||
@@ -47,7 +47,7 @@ module.exports = function (scriptRuntime, scope) {
|
||||
* @implements Internal.Storages
|
||||
*/
|
||||
const Storage = function () {
|
||||
// Empty interface body.
|
||||
/* Empty body. */
|
||||
};
|
||||
|
||||
Storage.prototype = {
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
let { ui, threads, files } = global;
|
||||
|
||||
/**
|
||||
* @param {org.autojs.autojs.runtime.ScriptRuntime} scriptRuntime
|
||||
* @param {ScriptRuntime} scriptRuntime
|
||||
* @param {org.mozilla.javascript.Scriptable | global} scope
|
||||
* @return {Internal.Tasks}
|
||||
*/
|
||||
@@ -22,7 +22,7 @@ module.exports = function (scriptRuntime, scope) {
|
||||
* @implements Internal.Tasks
|
||||
*/
|
||||
let Task = function () {
|
||||
// Empty interface body.
|
||||
/* Empty body. */
|
||||
};
|
||||
|
||||
Task.prototype = {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
// noinspection NpmUsedModulesInstalled
|
||||
|
||||
/**
|
||||
* @param {org.autojs.autojs.runtime.ScriptRuntime} scriptRuntime
|
||||
* @param {ScriptRuntime} scriptRuntime
|
||||
* @param {org.mozilla.javascript.Scriptable | global} scope
|
||||
* @return {Internal.Threads}
|
||||
*/
|
||||
@@ -18,7 +18,7 @@ module.exports = function (scriptRuntime, scope) {
|
||||
* @implements Internal.Threads
|
||||
*/
|
||||
const Threads = function () {
|
||||
// Empty interface body.
|
||||
/* Empty body. */
|
||||
};
|
||||
|
||||
Threads.prototype = {
|
||||
@@ -73,7 +73,7 @@ module.exports = function (scriptRuntime, scope) {
|
||||
* @implements Internal.Threads.PromiseExtension
|
||||
*/
|
||||
const PromiseExtension = function () {
|
||||
// Empty interface body.
|
||||
/* Empty body. */
|
||||
};
|
||||
|
||||
Object.assign(PromiseExtension.prototype, {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/**
|
||||
* @param {org.autojs.autojs.runtime.ScriptRuntime} scriptRuntime
|
||||
* @param {ScriptRuntime} scriptRuntime
|
||||
* @param {org.mozilla.javascript.Scriptable | global} scope
|
||||
* @return {Internal.Timers}
|
||||
*/
|
||||
@@ -11,7 +11,7 @@ module.exports = function (scriptRuntime, scope) {
|
||||
* @implements Internal.Timers
|
||||
*/
|
||||
const Timers = function () {
|
||||
// Empty interface body.
|
||||
/* Empty body. */
|
||||
};
|
||||
|
||||
Timers.prototype = {
|
||||
|
||||
@@ -1,86 +1,26 @@
|
||||
// noinspection UnnecessaryLocalVariableJS,JSUnusedLocalSymbols
|
||||
|
||||
/**
|
||||
* @param {org.autojs.autojs.runtime.ScriptRuntime} scriptRuntime
|
||||
* @param {ScriptRuntime} scriptRuntime
|
||||
* @param {org.mozilla.javascript.Scriptable | global} scope
|
||||
* @return {Internal.Toast}
|
||||
*/
|
||||
module.exports = function (scriptRuntime, scope) {
|
||||
let rtToast = scriptRuntime.toast;
|
||||
let _ = {
|
||||
uiHandler: runtime.getUiHandler(),
|
||||
toasts: {
|
||||
/**
|
||||
* @type {Set<android.widget.Toast>}
|
||||
*/
|
||||
pool: new Set(),
|
||||
lock: new ReentrantLock(),
|
||||
add(t) {
|
||||
if (t instanceof Toast) {
|
||||
this.lock.lock();
|
||||
this.pool.add(t);
|
||||
this.addCallback(t);
|
||||
this.lock.unlock();
|
||||
}
|
||||
},
|
||||
/**
|
||||
* @param {android.widget.Toast} t
|
||||
*/
|
||||
addCallback(t) {
|
||||
_.uiHandler.postDelayed(new java.lang.Runnable({
|
||||
run: () => _.toasts.remove(t),
|
||||
}), this.getDuration(t) + 1e3 /* As toast may show with some delay. */);
|
||||
},
|
||||
remove(t) {
|
||||
if (this.pool.has(t)) {
|
||||
this.lock.lock();
|
||||
this.pool.delete(t);
|
||||
this.lock.unlock();
|
||||
}
|
||||
},
|
||||
dismissAll() {
|
||||
if (this.pool.size > 0) {
|
||||
this.lock.lock();
|
||||
this.pool.forEach((t) => t.cancel());
|
||||
this.pool.clear();
|
||||
this.lock.unlock();
|
||||
}
|
||||
},
|
||||
getDuration(t) {
|
||||
let du = {
|
||||
SHORT_DELAY: 2e3,
|
||||
LONG_DELAY: 3.5e3,
|
||||
};
|
||||
switch (t.getDuration()) {
|
||||
case Toast.LENGTH_SHORT:
|
||||
return du.SHORT_DELAY;
|
||||
case Toast.LENGTH_LONG:
|
||||
return du.LONG_DELAY;
|
||||
default:
|
||||
return Math.max.apply(null, Object.values(du));
|
||||
}
|
||||
},
|
||||
},
|
||||
ToastCtor: (/* @IIFE */ () => {
|
||||
/**
|
||||
* @implements Internal.Toast
|
||||
*/
|
||||
const ToastCtor = function () {
|
||||
// @Caution by SuperMonster003 on Oct 11, 2022.
|
||||
// ! android.widget.Toast.makeText() doesn't work well on Android API Level 28 (Android 9) [P].
|
||||
// ! There hasn't been a solution for this so far.
|
||||
// ! Tested devices:
|
||||
// ! 1. SONY XPERIA XZ1 Compact (G8441)
|
||||
// ! 2. Android Studio AVD (Android 9.0 x86)
|
||||
const Ctor = function () {
|
||||
/** @global */
|
||||
const toast = function (msg, isLong, isForcible) {
|
||||
const instance = function (msg, isLong, isForcible) {
|
||||
let $ = {
|
||||
rex: {
|
||||
badge: {
|
||||
long: /^l(ong)?$/i,
|
||||
short: /^s(hort)?$/i,
|
||||
forcible: /^f(orcible)?$/i,
|
||||
},
|
||||
toast() {
|
||||
this.init(arguments);
|
||||
this.show();
|
||||
},
|
||||
init() {
|
||||
this.message = isNullish(msg) ? '' : String(msg);
|
||||
this.isForcible = this.parseIsForcible(isForcible);
|
||||
@@ -94,13 +34,13 @@ module.exports = function (scriptRuntime, scope) {
|
||||
return Boolean(isLong);
|
||||
}
|
||||
if (typeof isLong === 'string') {
|
||||
if (this.rex.long.test(isLong)) {
|
||||
if (this.badge.long.test(isLong)) {
|
||||
return true;
|
||||
}
|
||||
if (this.rex.short.test(isLong)) {
|
||||
if (this.badge.short.test(isLong)) {
|
||||
return false;
|
||||
}
|
||||
if (this.rex.forcible.test(isLong)) {
|
||||
if (this.badge.forcible.test(isLong)) {
|
||||
this.isForcible = true;
|
||||
return false;
|
||||
}
|
||||
@@ -116,42 +56,31 @@ module.exports = function (scriptRuntime, scope) {
|
||||
return Boolean(isForcible);
|
||||
}
|
||||
if (typeof isForcible === 'string') {
|
||||
if (this.rex.forcible.test(isForcible)) {
|
||||
if (this.badge.forcible.test(isForcible)) {
|
||||
return true;
|
||||
}
|
||||
throw Error(`Invalid param: {name: isForcible, value: ${isForcible}, type: ${species(isForcible)}.`);
|
||||
}
|
||||
return false;
|
||||
},
|
||||
show() {
|
||||
_.uiHandler.post(() => {
|
||||
if ($.isForcible) {
|
||||
_.toasts.dismissAll();
|
||||
}
|
||||
let len = $.isLong ? Toast.LENGTH_LONG : Toast.LENGTH_SHORT;
|
||||
let o = Toast.makeText(_.uiHandler.getContext(), $.message, len);
|
||||
_.toasts.add(o);
|
||||
o.show();
|
||||
});
|
||||
makeToast() {
|
||||
rtToast.makeToast(this.message, this.isLong, this.isForcible);
|
||||
},
|
||||
};
|
||||
|
||||
$.toast();
|
||||
$.init();
|
||||
$.makeToast();
|
||||
};
|
||||
|
||||
return Object.assign(toast, ToastCtor.prototype);
|
||||
return Object.assign(instance, Ctor.prototype);
|
||||
};
|
||||
|
||||
ToastCtor.prototype = {
|
||||
constructor: ToastCtor,
|
||||
dismissAll() {
|
||||
_.uiHandler.post(() => {
|
||||
_.toasts.dismissAll();
|
||||
});
|
||||
},
|
||||
Ctor.prototype = {
|
||||
constructor: Ctor,
|
||||
dismissAll: () => rtToast.dismissAll(),
|
||||
};
|
||||
|
||||
return ToastCtor;
|
||||
return Ctor;
|
||||
})(),
|
||||
};
|
||||
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
let { files } = global;
|
||||
|
||||
/**
|
||||
* @param {org.autojs.autojs.runtime.ScriptRuntime} scriptRuntime
|
||||
* @param {ScriptRuntime} scriptRuntime
|
||||
* @param {org.mozilla.javascript.Scriptable | global} scope
|
||||
* @return {Internal.UI}
|
||||
*/
|
||||
@@ -54,7 +54,7 @@ module.exports = function (scriptRuntime, scope) {
|
||||
* @extends Internal.UI
|
||||
*/
|
||||
const UI = function () {
|
||||
// Empty class body.
|
||||
/* Empty body. */
|
||||
};
|
||||
|
||||
UI.prototype = {
|
||||
@@ -67,7 +67,7 @@ module.exports = function (scriptRuntime, scope) {
|
||||
let Widget = function () {
|
||||
this.__attrs__ = {};
|
||||
return Object.assign(function () {
|
||||
// Empty interface body.
|
||||
/* Empty body. */
|
||||
}, Widget.prototype);
|
||||
};
|
||||
|
||||
|
||||
@@ -22,7 +22,7 @@
|
||||
// USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
|
||||
/**
|
||||
* @param {org.autojs.autojs.runtime.ScriptRuntime} scriptRuntime
|
||||
* @param {ScriptRuntime} scriptRuntime
|
||||
* @param {org.mozilla.javascript.Scriptable | global} scope
|
||||
* @return {Internal.Util}
|
||||
*/
|
||||
@@ -38,7 +38,7 @@ module.exports = function (scriptRuntime, scope) {
|
||||
* @implements Internal.Util
|
||||
*/
|
||||
const Util = function () {
|
||||
// Empty interface body.
|
||||
/* Empty body. */
|
||||
};
|
||||
|
||||
Util.prototype = {
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
let { http } = global;
|
||||
|
||||
/**
|
||||
* @param {org.autojs.autojs.runtime.ScriptRuntime} scriptRuntime
|
||||
* @param {ScriptRuntime} scriptRuntime
|
||||
* @param {org.mozilla.javascript.Scriptable | global} scope
|
||||
* @return {Internal.Web}
|
||||
*/
|
||||
@@ -20,7 +20,7 @@ module.exports = function (scriptRuntime, scope) {
|
||||
* @implements Internal.Web
|
||||
*/
|
||||
const Web = function () {
|
||||
// Empty interface body.
|
||||
/* Empty body. */
|
||||
};
|
||||
|
||||
Web.prototype = {
|
||||
@@ -43,7 +43,7 @@ module.exports = function (scriptRuntime, scope) {
|
||||
return new InjectableWebClient(Context.getCurrentContext(), scope);
|
||||
},
|
||||
newWebSocket(url) {
|
||||
return new org.autojs.autojs.core.web.WebSocket(http.__okhttp__, url);
|
||||
return new scope.WebSocket(url);
|
||||
},
|
||||
};
|
||||
|
||||
@@ -55,6 +55,33 @@ module.exports = function (scriptRuntime, scope) {
|
||||
*/
|
||||
let methods = [ 'newInjectableWebView', 'newInjectableWebClient', 'newWebSocket' ];
|
||||
__asGlobal__(web, methods, scope);
|
||||
|
||||
const WebSocket = function () {
|
||||
if (!(this instanceof WebSocket)) {
|
||||
throw TypeError('WebSocket must be called as constructor');
|
||||
}
|
||||
if (arguments[0] instanceof MutableOkHttp) {
|
||||
this.client = arguments[0];
|
||||
this.url = arguments[1];
|
||||
} else {
|
||||
this.client = http.__okhttp__;
|
||||
this.url = arguments[0];
|
||||
}
|
||||
if (typeof this.url !== 'string') {
|
||||
throw TypeError(`Invalid url (value: ${this.url}, species: ${species(this.url)}) for WebSocket`);
|
||||
}
|
||||
return new org.autojs.autojs.core.web.WebSocket(this.client, this.url);
|
||||
};
|
||||
|
||||
/* Append all primitive static fields. */
|
||||
Object.keys(org.autojs.autojs.core.web.WebSocket).forEach((key) => {
|
||||
let value = org.autojs.autojs.core.web.WebSocket[key]
|
||||
if (isPrimitive(value)) {
|
||||
WebSocket[key] = value;
|
||||
}
|
||||
});
|
||||
|
||||
scope.WebSocket = WebSocket;
|
||||
},
|
||||
};
|
||||
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
// noinspection UnnecessaryLocalVariableJS,JSUnusedLocalSymbols
|
||||
|
||||
/**
|
||||
* @param {ScriptRuntime} scriptRuntime
|
||||
* @param {org.mozilla.javascript.Scriptable | global} scope
|
||||
* @return {Internal.OcrMLKit}
|
||||
*/
|
||||
module.exports = function (scriptRuntime, scope) {
|
||||
|
||||
const rtOcrMLKit = scriptRuntime.ocrMLKit;
|
||||
|
||||
let _ = {
|
||||
OcrMLKitCtor: (/* @IIFE */ () => {
|
||||
/**
|
||||
* @implements Internal.OcrMLKit
|
||||
*/
|
||||
const OcrMLKitCtor = function () {
|
||||
return Object.assign(function () {
|
||||
let argArray = Array.from(arguments);
|
||||
/** @type {Internal.Ocr.ModeName} */
|
||||
argArray[ocr['_forcibleModeArgIndex']] = ocr['_modeName']['mlkit'];
|
||||
return ocr.recognizeText.apply(ocr, argArray);
|
||||
}, OcrMLKitCtor.prototype);
|
||||
};
|
||||
|
||||
OcrMLKitCtor.prototype = {
|
||||
constructor: OcrMLKitCtor,
|
||||
recognizeTextMethodCreator(options) {
|
||||
return function (img) {
|
||||
return Array.from(rtOcrMLKit.recognizeText(img));
|
||||
};
|
||||
},
|
||||
detectMethodCreator(options) {
|
||||
return function (img) {
|
||||
return Array.from(rtOcrMLKit.detect(img).toArray());
|
||||
};
|
||||
},
|
||||
};
|
||||
|
||||
return OcrMLKitCtor;
|
||||
})(),
|
||||
};
|
||||
|
||||
/**
|
||||
* @type {Internal.OcrMLKit}
|
||||
*/
|
||||
const ocrMLKit = new _.OcrMLKitCtor();
|
||||
|
||||
return ocrMLKit;
|
||||
};
|
||||
@@ -0,0 +1,68 @@
|
||||
// noinspection UnnecessaryLocalVariableJS,JSUnusedLocalSymbols
|
||||
|
||||
/**
|
||||
* @param {ScriptRuntime} scriptRuntime
|
||||
* @param {org.mozilla.javascript.Scriptable | global} scope
|
||||
* @return {Internal.OcrPaddle}
|
||||
*/
|
||||
module.exports = function (scriptRuntime, scope) {
|
||||
|
||||
const rtOcrPaddle = scriptRuntime.ocrPaddle;
|
||||
|
||||
let _ = {
|
||||
OcrPaddleCtor: (/* @IIFE */ () => {
|
||||
/**
|
||||
* @implements Internal.OcrPaddle
|
||||
*/
|
||||
const OcrPaddleCtor = function () {
|
||||
return Object.assign(function () {
|
||||
let argArray = Array.from(arguments);
|
||||
/** @type {Internal.Ocr.ModeName} */
|
||||
argArray[ocr['_forcibleModeArgIndex']] = ocr['_modeName']['paddle'];
|
||||
return ocr.recognizeText.apply(ocr, argArray);
|
||||
}, OcrPaddleCtor.prototype);
|
||||
};
|
||||
|
||||
OcrPaddleCtor.prototype = {
|
||||
constructor: OcrPaddleCtor,
|
||||
recognizeTextMethodCreator(options) {
|
||||
return function (img) {
|
||||
const { cpuThreadNum, useSlim } = options;
|
||||
|
||||
let niceUseSlim = useSlim === undefined ? true : Boolean(useSlim);
|
||||
let niceCpuThreadNum = cpuThreadNum || 4;
|
||||
|
||||
return Array.from(rtOcrPaddle.recognizeText(
|
||||
img,
|
||||
niceCpuThreadNum,
|
||||
niceUseSlim,
|
||||
));
|
||||
};
|
||||
},
|
||||
detectMethodCreator(options) {
|
||||
return function (img) {
|
||||
const { cpuThreadNum, useSlim } = options;
|
||||
|
||||
let niceUseSlim = useSlim === undefined ? true : Boolean(useSlim);
|
||||
let niceCpuThreadNum = cpuThreadNum || 4;
|
||||
|
||||
return Array.from(rtOcrPaddle.detect(
|
||||
img,
|
||||
niceCpuThreadNum,
|
||||
niceUseSlim,
|
||||
).toArray());
|
||||
};
|
||||
},
|
||||
};
|
||||
|
||||
return OcrPaddleCtor;
|
||||
})(),
|
||||
};
|
||||
|
||||
/**
|
||||
* @type {Internal.OcrPaddle}
|
||||
*/
|
||||
const ocrPaddle = new _.OcrPaddleCtor();
|
||||
|
||||
return ocrPaddle;
|
||||
};
|
||||
@@ -0,0 +1,7 @@
|
||||
auto();
|
||||
events.observeKey();
|
||||
events.setKeyInterceptionEnabled(true);
|
||||
events.on('volume_down', () => {
|
||||
app.sendBroadcast('bounds');
|
||||
exit();
|
||||
});
|
||||
@@ -1,22 +1,24 @@
|
||||
var num1 = dialogs.input("请输入第一个数字");
|
||||
var op = dialogs.singleChoice("请选择运算", ["加", "减", "乘", "除", "幂"]);
|
||||
var num2 = dialogs.input("请输入第二个数字");
|
||||
var result = 0;
|
||||
switch(op){
|
||||
case 0:
|
||||
result = num1 + num2;
|
||||
break;
|
||||
case 1:
|
||||
result = num1 - num2;
|
||||
break;
|
||||
case 2:
|
||||
result = num1 * num2;
|
||||
break;
|
||||
case 3:
|
||||
result = num1 / num2;
|
||||
break;
|
||||
case 4:
|
||||
result = Math.pow(num1, num2);
|
||||
break;
|
||||
}
|
||||
alert("运算结果", result);
|
||||
(/* @IIFE */ function () {
|
||||
var num1 = dialogs.input('请输入第一个数字');
|
||||
var op = dialogs.singleChoice('请选择运算', [ '加', '减', '乘', '除', '幂' ]);
|
||||
var num2 = dialogs.input('请输入第二个数字');
|
||||
var result = 0;
|
||||
switch (op) {
|
||||
case 0:
|
||||
result = num1 + num2;
|
||||
break;
|
||||
case 1:
|
||||
result = num1 - num2;
|
||||
break;
|
||||
case 2:
|
||||
result = num1 * num2;
|
||||
break;
|
||||
case 3:
|
||||
result = num1 / num2;
|
||||
break;
|
||||
case 4:
|
||||
result = Math.pow(num1, num2);
|
||||
break;
|
||||
}
|
||||
alert('运算结果', result);
|
||||
})();
|
||||
@@ -8,7 +8,7 @@
|
||||
* 每一个的时长都为350毫秒
|
||||
*/
|
||||
|
||||
gestures([350, [300, 400], [300, 1400]],
|
||||
gestures([0, 350, [300, 400], [300, 1400]],
|
||||
[350, [600, 400], [600, 1400]],
|
||||
[350, [900, 400], [900, 1400]]
|
||||
);
|
||||
@@ -50,7 +50,6 @@ abstract class AbstractAutoJs protected constructor(protected val application: A
|
||||
private set
|
||||
|
||||
val context: Context = application.applicationContext
|
||||
|
||||
val appUtils by lazy { createAppUtils(context) }
|
||||
val globalConsole by lazy { createGlobalConsole() }
|
||||
|
||||
@@ -108,7 +107,7 @@ abstract class AbstractAutoJs protected constructor(protected val application: A
|
||||
application.registerActivityLifecycleCallbacks(object : SimpleActivityLifecycleCallbacks() {
|
||||
|
||||
override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {
|
||||
ScreenMetrics.initIfNeeded(activity)
|
||||
ScreenMetrics.init(activity)
|
||||
appUtils.setCurrentActivity(activity)
|
||||
registerOnSharedPreferenceChangeListener(SharedPreferences.OnSharedPreferenceChangeListener { _, key ->
|
||||
if (key == StringUtils.key(R.string.key_keep_screen_on_when_in_foreground)) {
|
||||
|
||||
@@ -1,12 +1,15 @@
|
||||
package org.autojs.autojs
|
||||
|
||||
import android.annotation.SuppressLint
|
||||
import android.app.Application
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.content.res.Configuration
|
||||
import android.graphics.Bitmap
|
||||
import android.graphics.drawable.Drawable
|
||||
import android.net.Uri
|
||||
import android.os.Build
|
||||
import android.util.Log
|
||||
import android.view.View
|
||||
import android.widget.ImageView
|
||||
import androidx.localbroadcastmanager.content.LocalBroadcastManager
|
||||
@@ -31,10 +34,13 @@ import org.autojs.autojs.timing.TimedTaskManager
|
||||
import org.autojs.autojs.timing.TimedTaskScheduler
|
||||
import org.autojs.autojs.tool.CrashHandler
|
||||
import org.autojs.autojs.ui.error.ErrorReportActivity
|
||||
import org.autojs.autojs.ui.floating.FloatyWindowManger
|
||||
import org.autojs.autojs.util.ViewUtils
|
||||
import org.autojs.autojs6.BuildConfig
|
||||
import org.autojs.autojs6.R
|
||||
import org.lsposed.hiddenapibypass.HiddenApiBypass
|
||||
import java.lang.ref.WeakReference
|
||||
import java.lang.reflect.Method
|
||||
|
||||
|
||||
/**
|
||||
@@ -61,7 +67,7 @@ class App : MultiDexApplication() {
|
||||
setUpDebugEnvironment()
|
||||
|
||||
AutoJs.initInstance(this)
|
||||
GlobalKeyObserver.init()
|
||||
GlobalKeyObserver.initIfNeeded()
|
||||
setupDrawableImageLoader()
|
||||
TimedTaskScheduler.init(this)
|
||||
initDynamicBroadcastReceivers()
|
||||
@@ -73,7 +79,21 @@ class App : MultiDexApplication() {
|
||||
}
|
||||
|
||||
override fun attachBaseContext(base: Context) {
|
||||
super.attachBaseContext(localeAppDelegate.attachBaseContext(base))
|
||||
// @Caution by SuperMonster003 on Aug 2, 2023.
|
||||
// ! This will cause AutoJs6 not being aware of
|
||||
// ! configuration changes (like orientation and so forth).
|
||||
// super.attachBaseContext(localeAppDelegate.attachBaseContext(base))
|
||||
|
||||
super.attachBaseContext(base)
|
||||
|
||||
// @Dubious by SuperMonster003 on Aug 2, 2023.
|
||||
// ! Locale helper may be not work as expected ?
|
||||
localeAppDelegate.attachBaseContext(base)
|
||||
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
|
||||
HiddenApiBypass.addHiddenApiExemptions("L");
|
||||
}
|
||||
Log.d("Shizuku", "${App::class.java.getSimpleName()} attachBaseContext | Process=${getProcessNameCompat()}")
|
||||
}
|
||||
|
||||
private fun setUpStaticsTool() {
|
||||
@@ -216,10 +236,11 @@ class App : MultiDexApplication() {
|
||||
override fun onConfigurationChanged(newConfig: Configuration) {
|
||||
localeAppDelegate.onConfigurationChanged(this)
|
||||
ViewUtils.onConfigurationChanged(newConfig)
|
||||
FloatyWindowManger.getCircularMenu()?.savePosition(newConfig)
|
||||
super.onConfigurationChanged(newConfig)
|
||||
}
|
||||
|
||||
override fun getApplicationContext() = LocaleHelper.onAttach(super.getApplicationContext())
|
||||
override fun getApplicationContext() = LocaleHelper.onAttach(super.getApplicationContext())
|
||||
|
||||
companion object {
|
||||
|
||||
@@ -230,6 +251,19 @@ class App : MultiDexApplication() {
|
||||
val app: App
|
||||
get() = instance.get()!!
|
||||
|
||||
fun getProcessNameCompat(): String {
|
||||
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) Application.getProcessName() else {
|
||||
try {
|
||||
@SuppressLint("PrivateApi") val activityThread = Class.forName("android.app.ActivityThread")
|
||||
@SuppressLint("DiscouragedPrivateApi") val method: Method = activityThread.getDeclaredMethod("currentProcessName")
|
||||
method.invoke(null) as String
|
||||
} catch (e: ClassNotFoundException) {
|
||||
e.printStackTrace()
|
||||
"Unknown process name"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -57,12 +57,12 @@ class AutoJs private constructor(private val appContext: Application) : Abstract
|
||||
when {
|
||||
action.equals(LayoutBoundsFloatyWindow::class.java.name, true) -> {
|
||||
capture(object : LayoutInspectFloatyWindow {
|
||||
override fun create(nodeInfo: NodeInfo?) = LayoutBoundsFloatyWindow(nodeInfo, context)
|
||||
override fun create(nodeInfo: NodeInfo?) = LayoutBoundsFloatyWindow(nodeInfo, context, true)
|
||||
})
|
||||
}
|
||||
action.equals(LayoutHierarchyFloatyWindow::class.java.name, true) -> {
|
||||
capture(object : LayoutInspectFloatyWindow {
|
||||
override fun create(nodeInfo: NodeInfo?) = LayoutHierarchyFloatyWindow(nodeInfo, context)
|
||||
override fun create(nodeInfo: NodeInfo?) = LayoutHierarchyFloatyWindow(nodeInfo, context, true)
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -167,9 +167,11 @@ class AutoJs private constructor(private val appContext: Application) : Abstract
|
||||
/* Broadcasts. */
|
||||
|
||||
putProperty(BroadcastShortForm.INSPECT_LAYOUT_BOUNDS.fullName, LayoutBoundsFloatyWindow::class.java.name)
|
||||
putProperty(BroadcastShortForm.LAYOUT_BOUNDS.fullName, LayoutBoundsFloatyWindow::class.java.name)
|
||||
putProperty(BroadcastShortForm.BOUNDS.fullName, LayoutBoundsFloatyWindow::class.java.name)
|
||||
|
||||
putProperty(BroadcastShortForm.INSPECT_LAYOUT_HIERARCHY.fullName, LayoutHierarchyFloatyWindow::class.java.name)
|
||||
putProperty(BroadcastShortForm.LAYOUT_HIERARCHY.fullName, LayoutHierarchyFloatyWindow::class.java.name)
|
||||
putProperty(BroadcastShortForm.HIERARCHY.fullName, LayoutHierarchyFloatyWindow::class.java.name)
|
||||
}
|
||||
|
||||
@@ -181,6 +183,7 @@ class AutoJs private constructor(private val appContext: Application) : Abstract
|
||||
private set
|
||||
|
||||
@Synchronized
|
||||
@JvmStatic
|
||||
fun initInstance(application: Application) {
|
||||
if (!isInitialized) {
|
||||
instance = AutoJs(application)
|
||||
|
||||
@@ -18,7 +18,6 @@ import pxb.android.tinysign.TinySign;
|
||||
/**
|
||||
* Created by Stardust on 2017/10/23.
|
||||
*/
|
||||
|
||||
public class ApkPackager {
|
||||
|
||||
private InputStream mApkInputStream;
|
||||
|
||||
@@ -3,7 +3,6 @@ package org.autojs.autojs.apkbuilder.util;
|
||||
/**
|
||||
* Created by Stardust on 2017/10/23.
|
||||
*/
|
||||
|
||||
public interface BoolFunction<T> {
|
||||
|
||||
boolean accept(T t);
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
package org.autojs.autojs.apkbuilder.util;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
@@ -9,10 +8,8 @@ import java.io.OutputStream;
|
||||
/**
|
||||
* Created by Stardust on 2017/10/23.
|
||||
*/
|
||||
|
||||
public class StreamUtils {
|
||||
|
||||
|
||||
public static void write(InputStream inputStream, OutputStream out) throws IOException {
|
||||
byte[] buffer = new byte[4096];
|
||||
int len;
|
||||
@@ -30,4 +27,5 @@ public class StreamUtils {
|
||||
}
|
||||
return outputStream.toByteArray();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -102,14 +102,14 @@ object DialogUtils {
|
||||
MaterialDialog.Builder(context)
|
||||
.title(context.getString(R.string.dialog_button_more))
|
||||
.content(contentMore)
|
||||
.positiveText(R.string.dialog_button_back)
|
||||
.positiveText(R.string.dialog_button_dismiss)
|
||||
.build()
|
||||
.also { preference.longClickPromptMoreDialogHandler(it) }
|
||||
.show()
|
||||
}
|
||||
}
|
||||
}
|
||||
.positiveText(R.string.dialog_button_back)
|
||||
.positiveText(R.string.dialog_button_dismiss)
|
||||
.onPositive { dialog, _ -> dialog.dismiss() }
|
||||
.autoDismiss(false)
|
||||
.build()
|
||||
|
||||
@@ -55,7 +55,7 @@ class JsonSocketClientTool(context: Context) : AbstractJsonSocketTool(context) {
|
||||
val host = Pref.getServerAddress()
|
||||
if (isAutoConnect) {
|
||||
devPlugin
|
||||
.connectToRemoteServer(host, mClientModeItem, true)
|
||||
.connectToRemoteServer(context, host, mClientModeItem, true)
|
||||
.subscribe(Observers.emptyConsumer(), Observers.emptyConsumer())
|
||||
return
|
||||
}
|
||||
@@ -96,14 +96,14 @@ class JsonSocketClientTool(context: Context) : AbstractJsonSocketTool(context) {
|
||||
.show()
|
||||
}
|
||||
}
|
||||
.negativeText(R.string.dialog_button_back)
|
||||
.negativeText(R.string.dialog_button_cancel)
|
||||
.negativeColorRes(R.color.dialog_button_default)
|
||||
.onNegative { dHistories, _ -> dHistories.dismiss() }
|
||||
.autoDismiss(false)
|
||||
.show()
|
||||
.also { DialogUtils.toggleContentViewByItems(it) }
|
||||
}
|
||||
.negativeText(R.string.text_back)
|
||||
.negativeText(R.string.text_cancel)
|
||||
.onNegative { dialog, _ -> dialog.dismiss() }
|
||||
.autoDismiss(false)
|
||||
.dismissListener(onConnectionDialogDismissed)
|
||||
@@ -120,15 +120,15 @@ class JsonSocketClientTool(context: Context) : AbstractJsonSocketTool(context) {
|
||||
dialog.inputEditText!!.filters += InputFilter { source, start, end, dest, dstart, dend ->
|
||||
if (end > start) {
|
||||
val fullText = dest.substring(0, dstart) +
|
||||
source.subSequence(start, end) +
|
||||
dest.substring(dend)
|
||||
source.subSequence(start, end) +
|
||||
dest.substring(dend)
|
||||
if (dstart > 0) {
|
||||
val prevNearest = dest[dstart - 1]
|
||||
if (Regex(rexDot).matches(prevNearest.toString()) && Regex(rexDot).matches(source)) {
|
||||
if (Regex(REGEX_DOT).matches(prevNearest.toString()) && Regex(REGEX_DOT).matches(source)) {
|
||||
showSnack(dialog, R.string.error_repeated_dot_symbol)
|
||||
return@InputFilter ""
|
||||
}
|
||||
if (Regex(rexColon).matches(prevNearest.toString()) && Regex(rexColon).matches(source)) {
|
||||
if (Regex(REGEX_COLON).matches(prevNearest.toString()) && Regex(REGEX_COLON).matches(source)) {
|
||||
showSnack(dialog, R.string.error_repeated_colon_symbol)
|
||||
return@InputFilter ""
|
||||
}
|
||||
@@ -141,8 +141,8 @@ class JsonSocketClientTool(context: Context) : AbstractJsonSocketTool(context) {
|
||||
showSnack(dialog, R.string.error_invalid_ip_address)
|
||||
return@InputFilter ""
|
||||
}
|
||||
if (!fullText.contains(Regex(rexColon))) {
|
||||
fullText.split(Regex(rexDot)).dropLastWhile { it.isEmpty() }.forEach { s ->
|
||||
if (!fullText.contains(Regex(REGEX_COLON))) {
|
||||
fullText.split(Regex(REGEX_DOT)).dropLastWhile { it.isEmpty() }.forEach { s ->
|
||||
if (s.toIntOrNull()?.let { it <= 255 } != true) {
|
||||
showSnack(dialog, R.string.error_dot_decimal_notation_num_over_255)
|
||||
return@InputFilter ""
|
||||
@@ -150,14 +150,14 @@ class JsonSocketClientTool(context: Context) : AbstractJsonSocketTool(context) {
|
||||
}
|
||||
} else {
|
||||
if (!fullText.matches(rexFullIpWithColon)) {
|
||||
if (!dest.substring(0, dstart).contains(Regex(rexColon)) && dend == dest.length) {
|
||||
if (!dest.substring(0, dstart).contains(Regex(REGEX_COLON)) && dend == dest.length) {
|
||||
showSnack(dialog, R.string.error_colon_must_follow_a_valid_ip_address)
|
||||
} else {
|
||||
showSnack(dialog, R.string.error_invalid_ip_address)
|
||||
}
|
||||
return@InputFilter ""
|
||||
}
|
||||
fullText.split(Regex("$rexDot|$rexColon")).dropLastWhile { it.isEmpty() }.forEachIndexed { index, s ->
|
||||
fullText.split(Regex("$REGEX_DOT|$REGEX_COLON")).dropLastWhile { it.isEmpty() }.forEachIndexed { index, s ->
|
||||
if (index < 4 && s.toIntOrNull()?.let { it <= 255 } != true) {
|
||||
showSnack(dialog, R.string.error_dot_decimal_notation_num_over_255)
|
||||
return@InputFilter ""
|
||||
@@ -170,8 +170,8 @@ class JsonSocketClientTool(context: Context) : AbstractJsonSocketTool(context) {
|
||||
}
|
||||
}
|
||||
return@InputFilter source
|
||||
.replace(Regex("$rexDot+"), ".")
|
||||
.replace(Regex("$rexColon+"), ":")
|
||||
.replace(Regex("$REGEX_DOT+"), ".")
|
||||
.replace(Regex("$REGEX_COLON+"), ":")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -193,22 +193,22 @@ class JsonSocketClientTool(context: Context) : AbstractJsonSocketTool(context) {
|
||||
}
|
||||
dialog.dismiss()
|
||||
devPlugin
|
||||
.connectToRemoteServer(input, mClientModeItem)
|
||||
.connectToRemoteServer(context, input, mClientModeItem)
|
||||
.subscribe({ Pref.setServerAddress(input) }, onConnectionException)
|
||||
}
|
||||
|
||||
companion object {
|
||||
|
||||
const val rexDot = "[,.,。\\u0020]"
|
||||
const val rexColon = "[::]"
|
||||
const val REGEX_DOT = "[,.,。\\u0020]"
|
||||
const val REGEX_COLON = "[::]"
|
||||
|
||||
private const val rexIpDec = "\\d{1,3}"
|
||||
private const val rexPort = "\\d{1,5}"
|
||||
private const val REGEX_IP_DEC = "\\d{1,3}"
|
||||
private const val REGEX_PORT = "\\d{1,5}"
|
||||
|
||||
val rexPartialIp = Regex("^$rexIpDec($rexDot($rexIpDec($rexDot($rexIpDec($rexDot($rexIpDec)?)?)?)?)?)?")
|
||||
val rexFullIpWithColon = Regex("\\d+$rexDot\\d+$rexDot\\d+$rexDot\\d+$rexColon\\d*")
|
||||
val rexValidIp = Regex("$rexIpDec$rexDot$rexIpDec$rexDot$rexIpDec$rexDot$rexIpDec($rexColon$rexPort)?")
|
||||
val rexAcceptable = Regex("($rexDot|$rexColon|\\d)+")
|
||||
val rexPartialIp = Regex("^$REGEX_IP_DEC($REGEX_DOT($REGEX_IP_DEC($REGEX_DOT($REGEX_IP_DEC($REGEX_DOT($REGEX_IP_DEC)?)?)?)?)?)?")
|
||||
val rexFullIpWithColon = Regex("\\d+$REGEX_DOT\\d+$REGEX_DOT\\d+$REGEX_DOT\\d+$REGEX_COLON\\d*")
|
||||
val rexValidIp = Regex("$REGEX_IP_DEC$REGEX_DOT$REGEX_IP_DEC$REGEX_DOT$REGEX_IP_DEC$REGEX_DOT$REGEX_IP_DEC($REGEX_COLON$REGEX_PORT)?")
|
||||
val rexAcceptable = Regex("($REGEX_DOT|$REGEX_COLON|\\d)+")
|
||||
|
||||
}
|
||||
|
||||
|
||||
@@ -97,6 +97,8 @@ class AccessibilityTool(val context: Context) {
|
||||
private fun enableWithRoot(timeout: Long? = null): Boolean = when (timeout != null) {
|
||||
true -> enableWithRoot() && AccessibilityService.waitForEnabled(timeout.toLong())
|
||||
else -> try {
|
||||
disableWithRoot()
|
||||
|
||||
val services = getEnabledWithRoot(true)
|
||||
|
||||
val cmdServices = "settings put secure enabled_accessibility_services $services"
|
||||
@@ -116,8 +118,12 @@ class AccessibilityTool(val context: Context) {
|
||||
private fun enableWithSecure(timeout: Long? = null): Boolean = when (timeout != null) {
|
||||
true -> enableWithSecure() && AccessibilityService.waitForEnabled(timeout)
|
||||
else -> try {
|
||||
Secure.putString(context.contentResolver, Secure.ENABLED_ACCESSIBILITY_SERVICES, getEnabledWithSecure(true))
|
||||
disableWithSecure()
|
||||
|
||||
val enabledWithSecure = getEnabledWithSecure(true)
|
||||
Secure.putString(context.contentResolver, Secure.ENABLED_ACCESSIBILITY_SERVICES, enabledWithSecure)
|
||||
Secure.putInt(context.contentResolver, Secure.ACCESSIBILITY_ENABLED, 1)
|
||||
|
||||
isEnabled()
|
||||
} catch (e: Exception) {
|
||||
false
|
||||
|
||||
@@ -171,7 +171,7 @@ class SimpleActionAutomator(private val accessibilityBridge: AccessibilityBridge
|
||||
fun longClick(x: Int, y: Int) = globalActionAutomatorForGesture.longClick(x, y)
|
||||
|
||||
@ScriptInterface
|
||||
fun swipe(x1: Int, y1: Int, x2: Int, y2: Int, delay: Int) = globalActionAutomatorForGesture.swipe(x1, y1, x2, y2, delay.toLong())
|
||||
fun swipe(x1: Int, y1: Int, x2: Int, y2: Int, duration: Int) = globalActionAutomatorForGesture.swipe(x1, y1, x2, y2, duration.toLong())
|
||||
|
||||
@ScriptInterface
|
||||
fun paste(target: ActionTarget) = performAction(target.createAction(AccessibilityNodeInfo.ACTION_PASTE))
|
||||
|
||||
@@ -184,6 +184,6 @@ class GlobalActionAutomator(private val mHandler: Handler?, private val serviceP
|
||||
|
||||
private fun scaleY(y: Int) = mScreenMetrics?.scaleX(y) ?: y
|
||||
|
||||
fun swipe(x1: Int, y1: Int, x2: Int, y2: Int, delay: Long) = gesture(0, delay, intArrayOf(x1, y1), intArrayOf(x2, y2))
|
||||
fun swipe(x1: Int, y1: Int, x2: Int, y2: Int, duration: Long) = gesture(0, duration, intArrayOf(x1, y1), intArrayOf(x2, y2))
|
||||
|
||||
}
|
||||
@@ -61,6 +61,10 @@ class UiObjectCollection private constructor(private val nodes: List<UiObject?>)
|
||||
return success
|
||||
}
|
||||
|
||||
override fun toString(): String {
|
||||
return "${UiObjectCollection::class.java.name}@${hashCode()}"
|
||||
}
|
||||
|
||||
companion object {
|
||||
|
||||
val EMPTY = of(emptyList())
|
||||
|
||||
@@ -1,30 +1,40 @@
|
||||
package org.autojs.autojs.core.console
|
||||
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.net.Uri
|
||||
import android.os.CountDownTimer
|
||||
import android.os.Looper
|
||||
import android.util.Log
|
||||
import androidx.annotation.ColorInt
|
||||
import com.afollestad.materialdialogs.DialogAction
|
||||
import com.afollestad.materialdialogs.MaterialDialog
|
||||
import org.autojs.autojs.annotation.ScriptInterface
|
||||
import org.autojs.autojs.permission.DisplayOverOtherAppsPermission
|
||||
import org.autojs.autojs.pref.Language
|
||||
import org.autojs.autojs.runtime.ScriptRuntime
|
||||
import org.autojs.autojs.runtime.api.AbstractConsole
|
||||
import org.autojs.autojs.runtime.exception.ScriptInterruptedException
|
||||
import org.autojs.autojs.tool.UiHandler
|
||||
import org.autojs.autojs.ui.common.NotAskAgainDialog
|
||||
import org.autojs.autojs.ui.enhancedfloaty.FloatyService
|
||||
import org.autojs.autojs.ui.enhancedfloaty.ResizableExpandableFloatyWindow
|
||||
import org.autojs.autojs.ui.enhancedfloaty.gesture.DragGesture
|
||||
import org.autojs.autojs.util.ClipboardUtils
|
||||
import org.autojs.autojs.util.StringUtils.key
|
||||
import org.autojs.autojs.util.ViewUtils
|
||||
import org.autojs.autojs.util.ViewUtils.setViewMeasure
|
||||
import org.autojs.autojs6.R
|
||||
import org.joda.time.format.DateTimeFormat
|
||||
import org.opencv.core.Point
|
||||
import org.opencv.core.Size
|
||||
import java.io.IOException
|
||||
import java.lang.ref.WeakReference
|
||||
import java.util.concurrent.ArrayBlockingQueue
|
||||
import java.util.concurrent.BlockingQueue
|
||||
import java.util.concurrent.atomic.AtomicInteger
|
||||
import kotlin.math.ceil
|
||||
import kotlin.math.pow
|
||||
|
||||
|
||||
/**
|
||||
* Created by Stardust on 2017/5/2.
|
||||
@@ -36,6 +46,8 @@ open class ConsoleImpl(val uiHandler: UiHandler) : AbstractConsole() {
|
||||
var configurator = Configurator()
|
||||
|
||||
private val mDefaultSafeDelay: Long = 360
|
||||
private val mSafeSizeToSend: Int = 2.0.pow(16).toInt()
|
||||
private val mSafeSizeToCopy: Int = 2.0.pow(19).toInt()
|
||||
|
||||
private var mLogListeners = ArrayList<WeakReference<LogListener?>>()
|
||||
private var mConsoleView: WeakReference<ConsoleView?>? = null
|
||||
@@ -43,7 +55,9 @@ open class ConsoleImpl(val uiHandler: UiHandler) : AbstractConsole() {
|
||||
@get:Synchronized
|
||||
private var mCountDownTimer: CountDownTimer? = null
|
||||
|
||||
private val context = uiHandler.context
|
||||
private val context: Context
|
||||
get() = mConsoleView?.get()?.context ?: uiHandler.context
|
||||
|
||||
private val mLockWindowShow = Object()
|
||||
private val mLockWindowCreated = Object()
|
||||
private val mLockConsoleView = Object()
|
||||
@@ -51,7 +65,7 @@ open class ConsoleImpl(val uiHandler: UiHandler) : AbstractConsole() {
|
||||
private val mFloatyWindow: ResizableExpandableFloatyWindow
|
||||
private val mConsoleFloaty: ConsoleFloaty
|
||||
private val mInput: BlockingQueue<String> = ArrayBlockingQueue(1)
|
||||
private val mDisplayOverOtherAppsPerm = DisplayOverOtherAppsPermission(context)
|
||||
private val mDisplayOverOtherAppsPerm = DisplayOverOtherAppsPermission(uiHandler.context)
|
||||
|
||||
val logEntries = ArrayList<LogEntry>()
|
||||
|
||||
@@ -60,7 +74,9 @@ open class ConsoleImpl(val uiHandler: UiHandler) : AbstractConsole() {
|
||||
private set
|
||||
|
||||
private val logEntriesJoint
|
||||
get() = logEntries.joinToString("\n") { it.content }
|
||||
get() = synchronized(logEntries) {
|
||||
logEntries.joinToString("\n") { it.content }
|
||||
}
|
||||
|
||||
// val size: Size
|
||||
// get() = configurator.size ?: Size()
|
||||
@@ -123,26 +139,174 @@ open class ConsoleImpl(val uiHandler: UiHandler) : AbstractConsole() {
|
||||
mLogListeners.forEach { it.get()?.onLogClear() }
|
||||
}
|
||||
|
||||
fun copyAll() {
|
||||
fun copyAll() = copyAll(logEntriesJoint)
|
||||
|
||||
private fun copyAll(text: String, cutOutEntriesSize: Int = -1) {
|
||||
if (text.isEmpty()) {
|
||||
ViewUtils.showToast(context, R.string.text_no_log_entries_to_copy)
|
||||
return
|
||||
}
|
||||
try {
|
||||
ClipboardUtils.setClip(context, logEntriesJoint)
|
||||
ViewUtils.showToast(context, R.string.text_already_copied_to_clip)
|
||||
} catch (_: Exception) {
|
||||
ViewUtils.showToast(context, R.string.text_failed)
|
||||
ClipboardUtils.setClip(context, text)
|
||||
if (cutOutEntriesSize >= 0) {
|
||||
ViewUtils.showToast(
|
||||
context, context.getString(
|
||||
R.string.text_already_copied_to_clip_but_only_latest_few_items,
|
||||
cutOutEntriesSize
|
||||
), true
|
||||
)
|
||||
} else {
|
||||
ViewUtils.showToast(context, R.string.text_already_copied_to_clip)
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
e.printStackTrace()
|
||||
if (text.length < mSafeSizeToCopy || cutOutEntriesSize >= 0) {
|
||||
ViewUtils.showToast(context, R.string.text_failed_to_copy)
|
||||
return
|
||||
}
|
||||
try {
|
||||
val cutOutEntries = cutOutEntries(mSafeSizeToCopy)
|
||||
copyAll(cutOutEntries.joinToString("\n") { it.content }, cutOutEntries.size)
|
||||
} catch (e: Exception) {
|
||||
e.printStackTrace()
|
||||
ViewUtils.showToast(context, R.string.text_failed_to_copy)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun export() {
|
||||
val sendIntent: Intent = Intent().apply {
|
||||
@Suppress("SpellCheckingInspection")
|
||||
mConsoleView?.get()?.export("autojs6-log-${DateTimeFormat.forPattern("yyyyMMdd-HHmmss").print(System.currentTimeMillis())}.txt")
|
||||
}
|
||||
|
||||
fun export(uri: Uri?) {
|
||||
val message = logEntriesJoint
|
||||
if (message.isEmpty()) {
|
||||
ViewUtils.showToast(context, R.string.text_no_log_entries_to_export)
|
||||
return
|
||||
}
|
||||
try {
|
||||
context.contentResolver.openOutputStream(uri ?: return)?.use {
|
||||
it.write(message.toByteArray())
|
||||
it.flush()
|
||||
}
|
||||
ViewUtils.showToast(
|
||||
context,
|
||||
context.getString(R.string.text_some_items_exported, logEntries.size),
|
||||
true,
|
||||
)
|
||||
} catch (e: IOException) {
|
||||
e.printStackTrace()
|
||||
MaterialDialog.Builder(context)
|
||||
.title(R.string.text_prompt)
|
||||
.content(R.string.text_failed_to_export_log_entries)
|
||||
.cancelable(false)
|
||||
.autoDismiss(false)
|
||||
.neutralText(R.string.text_details)
|
||||
.neutralColorRes(R.color.dialog_button_hint)
|
||||
.onNeutral { dialog, _ ->
|
||||
dialog.setActionButton(DialogAction.NEUTRAL, null)
|
||||
dialog.setActionButton(DialogAction.POSITIVE, R.string.dialog_button_dismiss)
|
||||
dialog.contentView?.text = e.stackTraceToString()
|
||||
dialog.titleView?.text = context.getString(R.string.text_details)
|
||||
}
|
||||
.positiveText(R.string.dialog_button_dismiss)
|
||||
.onPositive { dialog, _ -> dialog.dismiss() }
|
||||
.show()
|
||||
}
|
||||
}
|
||||
|
||||
fun send() {
|
||||
val message = logEntriesJoint
|
||||
if (message.isEmpty()) {
|
||||
ViewUtils.showToast(context, R.string.text_no_log_entries_to_send)
|
||||
return
|
||||
}
|
||||
try {
|
||||
send(message)
|
||||
} catch (e: Exception) {
|
||||
e.printStackTrace()
|
||||
if (message.length < mSafeSizeToSend) {
|
||||
throw Exception(e)
|
||||
}
|
||||
|
||||
try {
|
||||
val cutOutEntries = cutOutEntries(mSafeSizeToSend)
|
||||
|
||||
val msgReason = context.getString(R.string.text_num_of_log_entries_exceeds_limit_for_sending, logEntries.size)
|
||||
val msgAction = context.getString(R.string.text_only_latest_few_items_will_be_sent, cutOutEntries.size)
|
||||
|
||||
NotAskAgainDialog.Builder(
|
||||
context,
|
||||
key(R.string.key_dialog_num_of_log_entries_exceeds_limit_for_sending),
|
||||
).apply {
|
||||
title(R.string.text_prompt)
|
||||
content("$msgReason, $msgAction.")
|
||||
cancelable(false)
|
||||
negativeText(R.string.dialog_button_quit)
|
||||
positiveText(R.string.dialog_button_continue)
|
||||
positiveColorRes(R.color.dialog_button_attraction)
|
||||
onPositive { _, _ -> send(cutOutEntries) }
|
||||
if (show() == null) {
|
||||
ViewUtils.showToast(context, msgAction.replaceFirstChar {
|
||||
if (it.isLowerCase()) it.titlecase(Language.getPrefLanguage().locale)
|
||||
else it.toString()
|
||||
}, true)
|
||||
send(cutOutEntries)
|
||||
}
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
e.printStackTrace()
|
||||
MaterialDialog.Builder(context)
|
||||
.title(R.string.text_prompt)
|
||||
.content(R.string.text_failed_to_send_log_entries)
|
||||
.cancelable(false)
|
||||
.autoDismiss(false)
|
||||
.neutralText(R.string.text_details)
|
||||
.neutralColorRes(R.color.dialog_button_hint)
|
||||
.onNeutral { dialog, _ ->
|
||||
dialog.setActionButton(DialogAction.NEUTRAL, null)
|
||||
dialog.setActionButton(DialogAction.POSITIVE, R.string.text_close)
|
||||
dialog.contentView?.text = e.stackTraceToString()
|
||||
dialog.titleView?.text = context.getString(R.string.text_details)
|
||||
}
|
||||
.positiveText(R.string.dialog_button_dismiss)
|
||||
.onPositive { dialog, _ -> dialog.dismiss() }
|
||||
.show()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun send(entries: MutableList<LogEntry>) {
|
||||
send(entries.joinToString("\n") { it.content })
|
||||
}
|
||||
|
||||
private fun send(message: String) {
|
||||
val sendIntent = Intent().apply {
|
||||
action = Intent.ACTION_SEND
|
||||
putExtra(Intent.EXTRA_TEXT, logEntriesJoint)
|
||||
putExtra(Intent.EXTRA_TEXT, message)
|
||||
type = "text/plain"
|
||||
}
|
||||
context.startActivity(Intent.createChooser(sendIntent, null).apply {
|
||||
uiHandler.context.startActivity(Intent.createChooser(sendIntent, null).apply {
|
||||
addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
|
||||
})
|
||||
}
|
||||
|
||||
private fun cutOutEntries(maxLength: Int): MutableList<LogEntry> {
|
||||
var accLength = 0
|
||||
val chosenEntries = mutableListOf<LogEntry>()
|
||||
synchronized(logEntries) {
|
||||
for (entry in logEntries.reversed()) {
|
||||
if (accLength >= maxLength) {
|
||||
break
|
||||
}
|
||||
accLength += entry.content.length
|
||||
chosenEntries.add(0, entry)
|
||||
}
|
||||
}
|
||||
return chosenEntries
|
||||
}
|
||||
|
||||
override fun show() = show(false)
|
||||
|
||||
@ScriptInterface
|
||||
@@ -153,7 +317,7 @@ open class ConsoleImpl(val uiHandler: UiHandler) : AbstractConsole() {
|
||||
synchronized(mLockWindowShow) {
|
||||
if (!mDisplayOverOtherAppsPerm.has()) {
|
||||
mDisplayOverOtherAppsPerm.config()
|
||||
uiHandler.toast(R.string.error_no_draw_overlays_permission)
|
||||
uiHandler.toast(R.string.error_no_display_over_other_apps_permission)
|
||||
return
|
||||
}
|
||||
if (isReset) reset()
|
||||
@@ -168,7 +332,7 @@ open class ConsoleImpl(val uiHandler: UiHandler) : AbstractConsole() {
|
||||
// SecurityException: https://github.com/hyb1996-guest/AutoJsIssueReport/issues/4781
|
||||
} catch (e: Exception) {
|
||||
e.printStackTrace()
|
||||
uiHandler.toast(R.string.error_no_draw_overlays_permission)
|
||||
uiHandler.toast(R.string.error_no_display_over_other_apps_permission)
|
||||
}
|
||||
}
|
||||
synchronized(mLockWindowCreated) {
|
||||
@@ -214,7 +378,7 @@ open class ConsoleImpl(val uiHandler: UiHandler) : AbstractConsole() {
|
||||
}
|
||||
|
||||
private fun startFloatyService() {
|
||||
context.startService(Intent(context, FloatyService::class.java))
|
||||
uiHandler.context.startService(Intent(uiHandler.context, FloatyService::class.java))
|
||||
}
|
||||
|
||||
@ScriptInterface
|
||||
@@ -234,7 +398,7 @@ open class ConsoleImpl(val uiHandler: UiHandler) : AbstractConsole() {
|
||||
configurator.setSize(w, h)
|
||||
if (isShowing) {
|
||||
mConsoleFloaty.expandedView?.let {
|
||||
setViewMeasure(it, w.toInt(), h.toInt())
|
||||
ViewUtils.setViewMeasure(it, w.toInt(), h.toInt())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -22,6 +22,7 @@ import androidx.recyclerview.widget.RecyclerView;
|
||||
|
||||
import org.autojs.autojs.tool.MapBuilder;
|
||||
import org.autojs.autojs.ui.enhancedfloaty.ResizableExpandableFloatyWindow;
|
||||
import org.autojs.autojs.ui.log.LogActivity;
|
||||
import org.autojs.autojs.util.DisplayUtils;
|
||||
import org.autojs.autojs6.R;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
@@ -40,6 +41,7 @@ public class ConsoleView extends FrameLayout implements ConsoleImpl.LogListener
|
||||
private final static int sRefreshInterval = 100;
|
||||
private final Map<Integer, Integer> mColors = new MapBuilder<Integer, Integer>().build();
|
||||
private ConsoleImpl mConsole;
|
||||
private LogActivity mLogActivity;
|
||||
private RecyclerView mLogListRecyclerView;
|
||||
private EditText mEditText;
|
||||
private ResizableExpandableFloatyWindow mWindow;
|
||||
@@ -240,6 +242,16 @@ public class ConsoleView extends FrameLayout implements ConsoleImpl.LogListener
|
||||
mConsole.setConsoleView(this);
|
||||
}
|
||||
|
||||
public void setLogActivity(LogActivity activity) {
|
||||
mLogActivity = activity;
|
||||
}
|
||||
|
||||
public void export(String fileName) {
|
||||
if (mLogActivity != null) {
|
||||
mLogActivity.export(fileName);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onNewLog(ConsoleImpl.LogEntry logEntry) {
|
||||
|
||||
|
||||
@@ -26,7 +26,7 @@ import java.util.Locale;
|
||||
*/
|
||||
@SuppressLint("ConstantLocale")
|
||||
public class GlobalConsole extends ConsoleImpl {
|
||||
private static final String TAG = "GlobalConsole";
|
||||
private static final String TAG = GlobalConsole.class.getSimpleName();
|
||||
private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("HH:mm:ss.SSS", Locale.getDefault());
|
||||
private static final Logger LOGGER = Logger.getLogger(GlobalConsole.class);
|
||||
|
||||
@@ -45,7 +45,7 @@ public class GlobalConsole extends ConsoleImpl {
|
||||
return log;
|
||||
}
|
||||
|
||||
private Priority toLog4jLevel(int level) {
|
||||
protected Priority toLog4jLevel(int level) {
|
||||
switch (level) {
|
||||
case VERBOSE, DEBUG -> {
|
||||
return Level.DEBUG;
|
||||
@@ -66,7 +66,7 @@ public class GlobalConsole extends ConsoleImpl {
|
||||
}
|
||||
}
|
||||
|
||||
private String getLevelChar(int level) {
|
||||
protected String getLevelChar(int level) {
|
||||
return switch (level) {
|
||||
case VERBOSE -> "V";
|
||||
case DEBUG -> "D";
|
||||
|
||||
@@ -1,19 +0,0 @@
|
||||
package org.autojs.autojs.core.console
|
||||
|
||||
import android.content.Context
|
||||
import android.util.AttributeSet
|
||||
import org.autojs.autojs.AutoJs
|
||||
|
||||
class JsConsoleView : ConsoleView {
|
||||
|
||||
constructor(context: Context) : super(context)
|
||||
|
||||
constructor(context: Context, attrs: AttributeSet?) : super(context, attrs)
|
||||
|
||||
constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr)
|
||||
|
||||
init {
|
||||
setConsole(AutoJs.instance.globalConsole)
|
||||
}
|
||||
|
||||
}
|
||||
@@ -3,7 +3,6 @@ package org.autojs.autojs.core.http
|
||||
import okhttp3.Interceptor
|
||||
import okhttp3.OkHttpClient
|
||||
import okhttp3.Response
|
||||
import java.net.SocketTimeoutException
|
||||
import java.util.concurrent.TimeUnit
|
||||
|
||||
/**
|
||||
@@ -14,31 +13,28 @@ class MutableOkHttp : OkHttpClient() {
|
||||
|
||||
private var mOkHttpClient: OkHttpClient
|
||||
private val maxRetries = 3
|
||||
private var mTimeout = (30 * 1000).toLong()
|
||||
private var mTimeout = 30 * 1000L
|
||||
private val mRetryInterceptor = Interceptor { chain: Interceptor.Chain ->
|
||||
val request = chain.request()
|
||||
var response: Response? = null
|
||||
var tryCount = 0
|
||||
do {
|
||||
var succeed: Boolean
|
||||
var isSuccessful: Boolean
|
||||
try {
|
||||
response?.close()
|
||||
chain.proceed(request).apply {
|
||||
response = this
|
||||
succeed = isSuccessful
|
||||
}
|
||||
} catch (e: SocketTimeoutException) {
|
||||
succeed = false
|
||||
response = chain.proceed(request).also { isSuccessful = it.isSuccessful }
|
||||
} catch (e: Exception) {
|
||||
isSuccessful = false
|
||||
if (tryCount >= maxRetries) {
|
||||
throw e
|
||||
}
|
||||
}
|
||||
if (succeed || tryCount >= maxRetries) {
|
||||
if (isSuccessful || tryCount >= maxRetries) {
|
||||
break
|
||||
}
|
||||
tryCount++
|
||||
} while (true)
|
||||
response!!
|
||||
response ?: throw Exception("Failed to make a request")
|
||||
}
|
||||
|
||||
init {
|
||||
|
||||
@@ -130,7 +130,7 @@ public class ColorFinder {
|
||||
@Deprecated
|
||||
@ScriptInterface
|
||||
@SuppressWarnings("deprecation")
|
||||
@CodeAuthor(name = "LYS", homepage = "https://github.com/LYS86")
|
||||
@CodeAuthor(name = "LYS86", homepage = "https://github.com/LYS86")
|
||||
public Point[] findAllMultiColors(ImageWrapper image, int firstColor, int threshold, Rect rect, int[] points) {
|
||||
Point[] firstPoints = findAllPointsForColor(image, firstColor, threshold, rect);
|
||||
List<Point> resultPoints = new ArrayList<>();
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
package org.autojs.autojs.core.inputevent;
|
||||
|
||||
import android.content.Context;
|
||||
|
||||
import androidx.annotation.NonNull;
|
||||
|
||||
import android.text.TextUtils;
|
||||
|
||||
import org.autojs.autojs6.R;
|
||||
@@ -67,7 +69,6 @@ public class InputEventObserver {
|
||||
void onInputEvent(@NonNull InputEvent e);
|
||||
}
|
||||
|
||||
private static InputEventObserver sGlobal;
|
||||
private final CopyOnWriteArrayList<InputEventListener> mInputEventListeners = new CopyOnWriteArrayList<>();
|
||||
private final Context mContext;
|
||||
private Shell mShell;
|
||||
@@ -76,18 +77,10 @@ public class InputEventObserver {
|
||||
mContext = context;
|
||||
}
|
||||
|
||||
public static InputEventObserver getGlobal(Context context) {
|
||||
if (sGlobal == null) {
|
||||
initGlobal(context);
|
||||
}
|
||||
return sGlobal;
|
||||
}
|
||||
|
||||
private static void initGlobal(Context context) {
|
||||
if (sGlobal != null)
|
||||
return;
|
||||
sGlobal = new InputEventObserver(context);
|
||||
sGlobal.observe();
|
||||
public static InputEventObserver initObserver(Context context) {
|
||||
var inputEventObserver = new InputEventObserver(context);
|
||||
inputEventObserver.observe();
|
||||
return inputEventObserver;
|
||||
}
|
||||
|
||||
public void observe() {
|
||||
|
||||
@@ -1,128 +1,45 @@
|
||||
package org.autojs.autojs.core.looper
|
||||
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import android.os.MessageQueue
|
||||
import android.os.MessageQueue.IdleHandler
|
||||
import android.util.Log
|
||||
import org.autojs.autojs.lang.ThreadCompat
|
||||
import org.autojs.autojs.rhino.AutoJsContext
|
||||
import org.autojs.autojs.runtime.ScriptRuntime
|
||||
import org.autojs.autojs.runtime.api.Threads
|
||||
import org.autojs.autojs.runtime.api.Timers
|
||||
import org.autojs.autojs.runtime.exception.ScriptInterruptedException
|
||||
import org.mozilla.javascript.Context
|
||||
import java.util.concurrent.CopyOnWriteArrayList
|
||||
import java.util.concurrent.ConcurrentLinkedQueue
|
||||
import java.util.concurrent.locks.ReentrantLock
|
||||
import kotlin.concurrent.withLock
|
||||
|
||||
/**
|
||||
* Created by Stardust on 2017/7/29.
|
||||
* Modified by SuperMonster003 as of Jul 12, 2023.
|
||||
* Transformed by SuperMonster003 on Jul 12, 2023.
|
||||
* Modified by aiselp as of Jun 4, 2023.
|
||||
* ! 调整内容:
|
||||
* ! 使此类只负责单 loop 线程生命周期管理, 移除繁琐的调用链
|
||||
* ! 调整 timer 由此类创建
|
||||
* ! 通过向此类添加 AsyncTask 以监听线程退出事件
|
||||
* Modified by SuperMonster003 as of Aug 28, 2023.
|
||||
*/
|
||||
// @Overruled by SuperMonster003 on Jul 12, 2023.
|
||||
// ! Author: aiselp
|
||||
// ! Related PR:
|
||||
// ! http://pr.autojs6.com/75
|
||||
// ! Reason:
|
||||
// ! Sorry but my current capabilities are not sufficient
|
||||
// ! to fully understand everything from above pull request(s),
|
||||
// ! so most of the code will remain as is. :)
|
||||
class Loopers(runtime: ScriptRuntime) : IdleHandler {
|
||||
interface LooperQuitHandler {
|
||||
fun shouldQuit(): Boolean
|
||||
}
|
||||
|
||||
private val waitWhenIdle: ThreadLocal<Boolean> = object : ThreadLocal<Boolean>() {
|
||||
override fun initialValue(): Boolean {
|
||||
return Looper.myLooper() == Looper.getMainLooper()
|
||||
}
|
||||
}
|
||||
private val waitIds: ThreadLocal<HashSet<Int>> = object : ThreadLocal<HashSet<Int>>() {
|
||||
override fun initialValue(): HashSet<Int> {
|
||||
return HashSet()
|
||||
}
|
||||
}
|
||||
private val maxWaitId: ThreadLocal<Int> = object : ThreadLocal<Int>() {
|
||||
override fun initialValue(): Int {
|
||||
return 0
|
||||
}
|
||||
}
|
||||
private val looperQuitHandlers = ThreadLocal<CopyOnWriteArrayList<LooperQuitHandler>>()
|
||||
class Loopers(val runtime: ScriptRuntime) {
|
||||
|
||||
@Volatile
|
||||
private var mServantLooper: Looper? = null
|
||||
private val mTimers: Timers
|
||||
@Suppress("DEPRECATION")
|
||||
private var mMainLooperQuitHandler: LooperQuitHandler? = null
|
||||
private val mMainHandler: Handler
|
||||
private val mMainLooper: Looper?
|
||||
private val mThreads: Threads
|
||||
private val mMainMessageQueue: MessageQueue
|
||||
private var waitWhenIdle: Boolean
|
||||
private val allTasks = ConcurrentLinkedQueue<AsyncTask>()
|
||||
|
||||
init {
|
||||
mTimers = runtime.timers
|
||||
mThreads = runtime.threads
|
||||
prepare()
|
||||
mMainLooper = Looper.myLooper()
|
||||
mMainHandler = Handler(Looper.getMainLooper())
|
||||
mMainMessageQueue = Looper.myQueue()
|
||||
}
|
||||
|
||||
fun addLooperQuitHandler(handler: LooperQuitHandler) {
|
||||
var handlers = looperQuitHandlers.get()
|
||||
if (handlers == null) {
|
||||
handlers = CopyOnWriteArrayList()
|
||||
looperQuitHandlers.set(handlers)
|
||||
}
|
||||
handlers.add(handler)
|
||||
}
|
||||
|
||||
fun removeLooperQuitHandler(handler: LooperQuitHandler): Boolean {
|
||||
val handlers = looperQuitHandlers.get()
|
||||
return handlers != null && handlers.remove(handler)
|
||||
}
|
||||
|
||||
private fun shouldQuitLooper(): Boolean {
|
||||
if (Thread.currentThread().isInterrupted) {
|
||||
return true
|
||||
}
|
||||
if (mTimers.hasPendingCallbacks()) {
|
||||
return false
|
||||
}
|
||||
if (waitWhenIdle.get() == true || waitIds.get()?.isNotEmpty() == true) {
|
||||
return false
|
||||
}
|
||||
if ((Context.getCurrentContext() as AutoJsContext).hasPendingContinuation()) {
|
||||
return false
|
||||
}
|
||||
val handlers = looperQuitHandlers.get() ?: return true
|
||||
for (handler in handlers) {
|
||||
if (!handler.shouldQuit()) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
private fun initServantThread() {
|
||||
ThreadCompat {
|
||||
Looper.prepare()
|
||||
mServantLooper = Looper.myLooper()
|
||||
@Suppress("PLATFORM_CLASS_MAPPED_TO_KOTLIN")
|
||||
synchronized(this@Loopers as Object) {
|
||||
notifyAll()
|
||||
}
|
||||
Looper.loop()
|
||||
}.start()
|
||||
}
|
||||
private val lock = ReentrantLock()
|
||||
private val condition = lock.newCondition()
|
||||
|
||||
val servantLooper: Looper
|
||||
get() {
|
||||
if (mServantLooper == null) {
|
||||
initServantThread()
|
||||
@Suppress("PLATFORM_CLASS_MAPPED_TO_KOTLIN")
|
||||
synchronized(this@Loopers as Object) {
|
||||
lock.withLock {
|
||||
try {
|
||||
wait()
|
||||
condition.await()
|
||||
} catch (e: InterruptedException) {
|
||||
throw ScriptInterruptedException(e)
|
||||
}
|
||||
@@ -131,69 +48,145 @@ class Loopers(runtime: ScriptRuntime) : IdleHandler {
|
||||
return mServantLooper!!
|
||||
}
|
||||
|
||||
private fun quitServantLooper() {
|
||||
mServantLooper?.quit()
|
||||
val timer: Timer
|
||||
val myLooper: Looper
|
||||
|
||||
init {
|
||||
prepare()
|
||||
myLooper = Looper.myLooper()!!
|
||||
timer = Timer(runtime, myLooper)
|
||||
waitWhenIdle = myLooper == Looper.getMainLooper()
|
||||
}
|
||||
|
||||
fun waitWhenIdle(): Int {
|
||||
val id = maxWaitId.get()!!
|
||||
Log.d(LOG_TAG, "waitWhenIdle: $id")
|
||||
maxWaitId.set(id + 1)
|
||||
waitIds.get()!!.add(id)
|
||||
return id
|
||||
@Deprecated("Deprecated in Java", ReplaceWith("AsyncTask"))
|
||||
interface LooperQuitHandler {
|
||||
fun shouldQuit(): Boolean
|
||||
}
|
||||
|
||||
fun doNotWaitWhenIdle(waitId: Int) {
|
||||
Log.d(LOG_TAG, "doNotWaitWhenIdle: $waitId")
|
||||
waitIds.get()!!.remove(waitId)
|
||||
open class AsyncTask(private val desc: String) {
|
||||
|
||||
private val allBind = ConcurrentLinkedQueue<Loopers>()
|
||||
|
||||
var isEnd: Boolean = false
|
||||
private set
|
||||
|
||||
// 线程即将退出时调用, 返回 true 阻止线程退出, 只要有一个 task 返回 true 线程就不会退出
|
||||
open fun onFinish(loopers: Loopers) = true
|
||||
|
||||
fun end() {
|
||||
isEnd = true
|
||||
}
|
||||
|
||||
// 线程正在退出, 这里应该结束任务的执行, 回收资源
|
||||
open fun onStop(loopers: Loopers) = Unit
|
||||
|
||||
override fun toString() = "AsyncTask: $desc"
|
||||
|
||||
}
|
||||
|
||||
fun createAndAddAsyncTask(desc: String): AsyncTask {
|
||||
return AsyncTask(desc).also { allTasks.add(it) }
|
||||
}
|
||||
|
||||
fun addAsyncTask(task: AsyncTask) {
|
||||
synchronized(myLooper) {
|
||||
allTasks.add(task)
|
||||
}
|
||||
}
|
||||
|
||||
fun removeAsyncTask(task: AsyncTask) {
|
||||
synchronized(myLooper) {
|
||||
allTasks.remove(task)
|
||||
timer.post(EMPTY_RUNNABLE)
|
||||
}
|
||||
}
|
||||
|
||||
private fun checkTask(): Boolean {
|
||||
allTasks.removeAll(allTasks.filter { it.isEnd }.toSet())
|
||||
return allTasks.any { it.onFinish(this) }
|
||||
}
|
||||
|
||||
private fun shouldQuitLooper(): Boolean {
|
||||
synchronized(myLooper) {
|
||||
return when {
|
||||
Thread.currentThread().isInterrupted -> true
|
||||
timer.hasPendingCallbacks() -> false
|
||||
// 检查是否有运行中的线程
|
||||
checkTask() -> false
|
||||
waitWhenIdle -> false
|
||||
(Context.getCurrentContext() as AutoJsContext).hasPendingContinuation() -> false
|
||||
else -> true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun initServantThread() {
|
||||
ThreadCompat {
|
||||
Looper.prepare()
|
||||
mServantLooper = Looper.myLooper()
|
||||
lock.withLock {
|
||||
condition.signalAll()
|
||||
}
|
||||
Looper.loop()
|
||||
}.start()
|
||||
}
|
||||
|
||||
@Deprecated("Deprecated in Java", ReplaceWith("AsyncTask"))
|
||||
fun waitWhenIdle(b: Boolean) {
|
||||
waitWhenIdle.set(b)
|
||||
waitWhenIdle = b
|
||||
}
|
||||
|
||||
fun recycle() {
|
||||
quitServantLooper()
|
||||
mMainMessageQueue.removeIdleHandler(this)
|
||||
Log.d(LOG_TAG, "recycle")
|
||||
for (task in allTasks.filter { !it.isEnd }) {
|
||||
try {
|
||||
task.onStop(this)
|
||||
} catch (e: Exception) {
|
||||
Log.w(LOG_TAG, e)
|
||||
}
|
||||
}
|
||||
mServantLooper?.quit()
|
||||
}
|
||||
|
||||
fun setMainLooperQuitHandler(mainLooperQuitHandler: LooperQuitHandler?) {
|
||||
@Deprecated("Deprecated in Java", ReplaceWith("AsyncTask"))
|
||||
fun setMainLooperQuitHandler(@Suppress("DEPRECATION") mainLooperQuitHandler: LooperQuitHandler?) {
|
||||
mMainLooperQuitHandler = mainLooperQuitHandler
|
||||
}
|
||||
|
||||
override fun queueIdle(): Boolean {
|
||||
val l = Looper.myLooper() ?: return true
|
||||
if (l == mMainLooper) {
|
||||
Log.d(LOG_TAG, "main looper queueIdle")
|
||||
if (shouldQuitLooper() && !mThreads.hasRunningThreads() && mMainLooperQuitHandler != null && mMainLooperQuitHandler!!.shouldQuit()) {
|
||||
Log.d(LOG_TAG, "main looper quit")
|
||||
l.quit()
|
||||
}
|
||||
} else {
|
||||
Log.d(LOG_TAG, "looper queueIdle: $l")
|
||||
if (shouldQuitLooper()) {
|
||||
l.quit()
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
fun prepare() {
|
||||
private fun prepare() {
|
||||
if (Looper.myLooper() == null) {
|
||||
LooperHelper.prepare()
|
||||
}
|
||||
Looper.myQueue().addIdleHandler(this)
|
||||
Looper.myQueue().addIdleHandler(MessageQueue.IdleHandler {
|
||||
if (this == runtime.loopers) {
|
||||
Log.d(LOG_TAG, "main looper queueIdle")
|
||||
if (shouldQuitLooper() && mMainLooperQuitHandler?.shouldQuit() == true) {
|
||||
Log.d(LOG_TAG, "main looper quit")
|
||||
Looper.myLooper()?.quitSafely()
|
||||
}
|
||||
} else {
|
||||
Log.d(LOG_TAG, "looper queueIdle $this")
|
||||
if (shouldQuitLooper()) {
|
||||
Log.d(LOG_TAG, "looper quit $this")
|
||||
Looper.myLooper()?.quitSafely()
|
||||
}
|
||||
}
|
||||
return@IdleHandler true
|
||||
})
|
||||
}
|
||||
|
||||
fun notifyThreadExit(thread: TimerThread) {
|
||||
Log.d(LOG_TAG, "notifyThreadExit: $thread")
|
||||
// 当子线程退成时,主线程需要检查自身是否退出(主线程在所有子线程执行完成后才能退出,如果主线程已经执行完任务仍然要等待所有子线程),
|
||||
// 此时通过向主线程发送一个空的Runnable,主线程执行完这个Runnable后会触发IdleHandler,从而检查自身是否退出
|
||||
mMainHandler.post(EMPTY_RUNNABLE)
|
||||
// 当子线程退成时, 主线程需要检查自身是否退出 (主线程在所有子线程执行完成后才能退出, 如果主线程已经执行完任务仍然要等待所有子线程),
|
||||
// 此时通过向主线程发送一个空的 Runnable, 主线程执行完这个 Runnable 后会触发 IdleHandler, 从而检查自身是否退出
|
||||
// mHandler.post(EMPTY_RUNNABLE)
|
||||
}
|
||||
|
||||
companion object {
|
||||
|
||||
private const val LOG_TAG = "Loopers"
|
||||
private val EMPTY_RUNNABLE = Runnable {}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -3,120 +3,137 @@ package org.autojs.autojs.core.looper
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import android.os.SystemClock
|
||||
import android.util.SparseArray
|
||||
import org.autojs.autojs.concurrent.VolatileBox
|
||||
import org.autojs.autojs.runtime.ScriptRuntime
|
||||
import kotlin.math.max
|
||||
import org.mozilla.javascript.BaseFunction
|
||||
import org.mozilla.javascript.Context
|
||||
import org.mozilla.javascript.Scriptable
|
||||
import org.mozilla.javascript.Undefined
|
||||
import java.util.concurrent.ConcurrentHashMap
|
||||
import kotlin.random.Random
|
||||
|
||||
/**
|
||||
* Created by Stardust on 2017/12/27.
|
||||
* Modified by aiselp as of Jun 14, 2023.
|
||||
* Modified by SuperMonster003 as of Jul 12, 2023.
|
||||
* Transformed by SuperMonster003 on Jul 12, 2023.
|
||||
*/
|
||||
// @Overruled by SuperMonster003 on Jul 12, 2023.
|
||||
// ! Author: aiselp
|
||||
// ! Related PR:
|
||||
// ! http://pr.autojs6.com/75
|
||||
// ! http://pr.autojs6.com/78
|
||||
// ! Reason:
|
||||
// ! Sorry but my current capabilities are not sufficient
|
||||
// ! to fully understand everything from above pull request(s),
|
||||
// ! so most of the code will remain as is. :)
|
||||
class Timer @JvmOverloads constructor(runtime: ScriptRuntime, maxCallbackMillisForAllThread: VolatileBox<Long>, private val looper: Looper? = Looper.myLooper()) {
|
||||
class Timer(runtime: ScriptRuntime, looper: Looper) {
|
||||
|
||||
private val mHandlerCallbacks = SparseArray<Runnable?>()
|
||||
private var mCallbackMaxId = 0
|
||||
private val myLooper: Looper = looper
|
||||
private val mHandlerCallbacks = ConcurrentHashMap<Int, Runnable?>()
|
||||
private val mRuntime: ScriptRuntime = runtime
|
||||
@Suppress("DEPRECATION")
|
||||
private val mHandler = looper?.let { Handler(it) } ?: Handler()
|
||||
private var mMaxCallbackUptimeMillis: Long = 0
|
||||
private val mMaxCallbackMillisForAllThread: VolatileBox<Long> = maxCallbackMillisForAllThread
|
||||
private val mHandler: Handler = Handler(looper)
|
||||
private val isUiLoop: Boolean = looper == Looper.getMainLooper()
|
||||
private val context: Context? by lazy { Context.getCurrentContext() }
|
||||
|
||||
fun setTimeout(callback: Any, delay: Long, vararg args: Array<out Any?>): Int {
|
||||
mCallbackMaxId++
|
||||
val id = mCallbackMaxId
|
||||
constructor(runtime: ScriptRuntime) : this(runtime, Looper.myLooper()!!)
|
||||
|
||||
fun setTimeout(callback: Any, delay: Long, vararg args: Any?): Int {
|
||||
val id = createTimerId()
|
||||
val r = Runnable {
|
||||
callFunction(callback, args)
|
||||
callFunction(callback, null, args)
|
||||
mHandlerCallbacks.remove(id)
|
||||
}
|
||||
mHandlerCallbacks.put(id, r)
|
||||
mHandlerCallbacks[id] = r
|
||||
postDelayed(r, delay)
|
||||
return id
|
||||
}
|
||||
|
||||
private fun callFunction(callback: Any, args: Array<out Any>) {
|
||||
private fun callFunction(callback: Any, thiz: Any?, args: Any?) {
|
||||
val func = callback as BaseFunction
|
||||
val map: Array<Any> =
|
||||
(args as? Array<*>)?.map { Context.javaToJS(it, callback.parentScope) }
|
||||
?.toTypedArray() ?: emptyArray()
|
||||
try {
|
||||
mRuntime.bridges.callFunction(callback, null, args)
|
||||
func.call(
|
||||
context ?: Context.enter(), func.parentScope,
|
||||
thiz as? Scriptable ?: Undefined.SCRIPTABLE_UNDEFINED, map
|
||||
)
|
||||
} catch (e: Exception) {
|
||||
if (Looper.myLooper() == Looper.getMainLooper()) {
|
||||
if (isUiLoop) {
|
||||
mRuntime.exit(e)
|
||||
} else {
|
||||
throw e
|
||||
}
|
||||
} else throw e
|
||||
} finally {
|
||||
context ?: Context.exit()
|
||||
}
|
||||
}
|
||||
|
||||
fun clearTimeout(id: Int) = clearCallback(id)
|
||||
@Synchronized
|
||||
private fun createTimerId(): Int {
|
||||
var id: Int
|
||||
do {
|
||||
id = Random.nextInt()
|
||||
} while (mHandlerCallbacks.containsKey(id))
|
||||
mHandlerCallbacks[id] = EMPTY_RUNNABLE
|
||||
return id
|
||||
}
|
||||
|
||||
fun setInterval(listener: Any, interval: Long, vararg args: Any): Int {
|
||||
mCallbackMaxId++
|
||||
val id = mCallbackMaxId
|
||||
val r = object : Runnable {
|
||||
fun setInterval(listener: Any, interval: Long, vararg args: Any?): Int {
|
||||
val id = createTimerId()
|
||||
val r: Runnable = object : Runnable {
|
||||
override fun run() {
|
||||
mHandlerCallbacks[id] ?: return
|
||||
callFunction(listener, args)
|
||||
if (mHandlerCallbacks[id] == null) return
|
||||
callFunction(listener, null, args)
|
||||
postDelayed(this, interval)
|
||||
}
|
||||
}
|
||||
mHandlerCallbacks.put(id, r)
|
||||
mHandlerCallbacks[id] = r
|
||||
postDelayed(r, interval)
|
||||
return id
|
||||
}
|
||||
|
||||
fun postDelayed(r: Runnable, interval: Long) {
|
||||
val uptime = SystemClock.uptimeMillis() + interval
|
||||
mHandler.postAtTime(r, uptime)
|
||||
mMaxCallbackUptimeMillis = mMaxCallbackUptimeMillis.coerceAtLeast(uptime)
|
||||
synchronized(mMaxCallbackMillisForAllThread) { mMaxCallbackMillisForAllThread.set(max(mMaxCallbackMillisForAllThread.get(), uptime)) }
|
||||
}
|
||||
|
||||
// @Reference to aiselp (https://github.com/aiselp) on Jul 18, 2023.
|
||||
fun post(r: Runnable) {
|
||||
looper?.let {
|
||||
synchronized(it) {
|
||||
mHandler.post(r)
|
||||
}
|
||||
synchronized(myLooper) {
|
||||
val uptime = SystemClock.uptimeMillis() + interval
|
||||
mHandler.postAtTime(r, uptime)
|
||||
}
|
||||
}
|
||||
|
||||
fun clearInterval(id: Int) = clearCallback(id)
|
||||
fun post(r: Runnable) {
|
||||
synchronized(myLooper) {
|
||||
mHandler.post(r)
|
||||
}
|
||||
}
|
||||
|
||||
fun setImmediate(listener: Any, vararg args: Any): Int {
|
||||
mCallbackMaxId++
|
||||
val id = mCallbackMaxId
|
||||
fun clearInterval(id: Int): Boolean = clearCallback(id)
|
||||
fun clearImmediate(id: Int): Boolean = clearCallback(id)
|
||||
fun clearTimeout(id: Int): Boolean = clearCallback(id)
|
||||
|
||||
fun setImmediate(listener: Any, vararg args: Any?): Int {
|
||||
val id = createTimerId()
|
||||
val r = Runnable {
|
||||
callFunction(listener, args)
|
||||
callFunction(listener, null, args)
|
||||
mHandlerCallbacks.remove(id)
|
||||
}
|
||||
mHandlerCallbacks.put(id, r)
|
||||
postDelayed(r, 0)
|
||||
mHandlerCallbacks[id] = r
|
||||
post(r)
|
||||
return id
|
||||
}
|
||||
|
||||
fun clearImmediate(id: Int) = clearCallback(id)
|
||||
|
||||
private fun clearCallback(id: Int): Boolean {
|
||||
val callback = mHandlerCallbacks[id]
|
||||
if (callback != null) {
|
||||
mHandler.removeCallbacks(callback)
|
||||
mHandlerCallbacks.remove(id)
|
||||
if (mHandlerCallbacks.isEmpty()) mHandler.post(EMPTY_RUNNABLE)
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
fun hasPendingCallbacks() = mMaxCallbackUptimeMillis > SystemClock.uptimeMillis()
|
||||
fun hasPendingCallbacks(): Boolean {
|
||||
return mHandlerCallbacks.size > 0
|
||||
}
|
||||
|
||||
fun removeAllCallbacks() = mHandler.removeCallbacksAndMessages(null)
|
||||
fun removeAllCallbacks() {
|
||||
mHandler.removeCallbacksAndMessages(null)
|
||||
}
|
||||
|
||||
companion object {
|
||||
|
||||
private const val LOG_TAG = "Timer"
|
||||
private val EMPTY_RUNNABLE = Runnable {}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,60 +1,45 @@
|
||||
package org.autojs.autojs.core.looper
|
||||
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import androidx.annotation.CallSuper
|
||||
import org.autojs.autojs.concurrent.VolatileBox
|
||||
import org.autojs.autojs.engine.RhinoJavaScriptEngine
|
||||
import org.autojs.autojs.lang.ThreadCompat
|
||||
import org.autojs.autojs.runtime.ScriptRuntime
|
||||
import org.autojs.autojs.runtime.exception.ScriptInterruptedException
|
||||
import org.autojs.autojs.util.StringUtils.str
|
||||
import org.autojs.autojs6.R
|
||||
import org.mozilla.javascript.Context
|
||||
import java.util.concurrent.ConcurrentHashMap
|
||||
|
||||
/**
|
||||
* Created by Stardust on 2017/12/27.
|
||||
* Modified by SuperMonster003 as of Jul 12, 2023.
|
||||
* Transformed by SuperMonster003 on Jul 12, 2023.
|
||||
*/
|
||||
// @Overruled by SuperMonster003 on Jul 12, 2023.
|
||||
// ! Author: aiselp
|
||||
// ! Related PR:
|
||||
// ! http://pr.autojs6.com/75
|
||||
// ! Reason:
|
||||
// ! Sorry but my current capabilities are not sufficient
|
||||
// ! to fully understand everything from above pull request(s),
|
||||
// ! so most of the code will remain as is. :)
|
||||
@Suppress("unused")
|
||||
open class TimerThread(
|
||||
private val scriptRuntime: ScriptRuntime,
|
||||
private val maxCallbackUptimeMillisForAllThreads: VolatileBox<Long>,
|
||||
private val target: Runnable
|
||||
) : ThreadCompat(target) {
|
||||
open class TimerThread(private val mRuntime: ScriptRuntime, private val mTarget: Runnable) : ThreadCompat(mTarget) {
|
||||
|
||||
private var mTimer: Timer? = null
|
||||
private var mRunning = false
|
||||
private val mRunningLock = Object()
|
||||
private val mAsyncTask = Loopers.AsyncTask("TimerThread")
|
||||
|
||||
var loopers: Loopers? = null
|
||||
|
||||
init {
|
||||
mRuntime.loopers.addAsyncTask(mAsyncTask)
|
||||
}
|
||||
|
||||
override fun run() {
|
||||
scriptRuntime.loopers.prepare()
|
||||
mTimer = Timer(scriptRuntime, maxCallbackUptimeMillisForAllThreads).also {
|
||||
sTimerMap[currentThread()] = it
|
||||
}
|
||||
(scriptRuntime.engines.myEngine() as? RhinoJavaScriptEngine)?.enterContext()
|
||||
loopers = Loopers(mRuntime)
|
||||
mTimer = loopers!!.timer
|
||||
sTimerMap[currentThread()] = mTimer!!
|
||||
(mRuntime.engines.myEngine() as RhinoJavaScriptEngine).enterContext()
|
||||
notifyRunning()
|
||||
@Suppress("DEPRECATION")
|
||||
Looper.myLooper()?.let {
|
||||
Handler(it).post(target)
|
||||
} ?: Handler().post(target)
|
||||
mTimer!!.post(mTarget)
|
||||
try {
|
||||
Looper.loop()
|
||||
} catch (e: Throwable) {
|
||||
if (!ScriptInterruptedException.causedByInterrupted(e)) {
|
||||
scriptRuntime.console.error("${currentThread()}: $e")
|
||||
mRuntime.console.error(currentThread().toString() + ": ", e)
|
||||
}
|
||||
} finally {
|
||||
// mRuntime.console.log("TimerThread exit");
|
||||
onExit()
|
||||
mTimer = null
|
||||
Context.exit()
|
||||
@@ -76,49 +61,69 @@ open class TimerThread(
|
||||
|
||||
@CallSuper
|
||||
protected open fun onExit() {
|
||||
scriptRuntime.loopers.notifyThreadExit(this)
|
||||
mRuntime.loopers.removeAsyncTask(mAsyncTask)
|
||||
mRuntime.loopers.notifyThreadExit(this)
|
||||
}
|
||||
|
||||
fun setTimeout(callback: Any, delay: Long, vararg args: Any): Int {
|
||||
return timer.setTimeout(callback, delay, *args)
|
||||
}
|
||||
|
||||
fun setTimeout(callback: Any): Int {
|
||||
return setTimeout(callback, 1)
|
||||
}
|
||||
|
||||
val timer: Timer
|
||||
get() {
|
||||
checkNotNull(mTimer) { str(R.string.error_thread_is_not_alive) }
|
||||
return mTimer!!
|
||||
checkNotNull(mTimer) { "thread is not alive" }
|
||||
return mTimer as Timer
|
||||
}
|
||||
|
||||
fun setTimeout(callback: Any, delay: Long, vararg args: Array<out Any?>) = timer.setTimeout(callback, delay, *args)
|
||||
fun clearTimeout(id: Int): Boolean {
|
||||
return timer.clearTimeout(id)
|
||||
}
|
||||
|
||||
fun clearTimeout(id: Int) = timer.clearTimeout(id)
|
||||
fun setInterval(listener: Any?, interval: Long, vararg args: Any): Int {
|
||||
return timer.setInterval(listener!!, interval, *args)
|
||||
}
|
||||
|
||||
fun setInterval(listener: Any, interval: Long, vararg args: Array<out Any?>) = timer.setInterval(listener, interval, *args)
|
||||
fun setInterval(listener: Any?): Int {
|
||||
return setInterval(listener, 1)
|
||||
}
|
||||
|
||||
fun clearInterval(id: Int) = timer.clearInterval(id)
|
||||
fun clearInterval(id: Int): Boolean {
|
||||
return timer.clearInterval(id)
|
||||
}
|
||||
|
||||
fun setImmediate(listener: Any, vararg args: Array<out Any?>) = timer.setImmediate(listener, *args)
|
||||
fun setImmediate(listener: Any, vararg args: Any): Int {
|
||||
return timer.setImmediate(listener, *args)
|
||||
}
|
||||
|
||||
fun clearImmediate(id: Int) = timer.clearImmediate(id)
|
||||
fun clearImmediate(id: Int): Boolean {
|
||||
return timer.clearImmediate(id)
|
||||
}
|
||||
|
||||
@Throws(InterruptedException::class)
|
||||
fun waitFor() {
|
||||
synchronized(mRunningLock) {
|
||||
if (!mRunning) {
|
||||
mRunningLock.wait()
|
||||
}
|
||||
if (mRunning) return
|
||||
mRunningLock.wait()
|
||||
}
|
||||
}
|
||||
|
||||
override fun toString() = "Thread[$name,$priority]"
|
||||
override fun toString(): String {
|
||||
return "Thread[$name,$priority]"
|
||||
}
|
||||
|
||||
companion object {
|
||||
|
||||
private val sTimerMap = ConcurrentHashMap<Thread, Timer?>()
|
||||
|
||||
@JvmStatic
|
||||
fun getTimerForThread(thread: Thread) = sTimerMap[thread]
|
||||
fun getTimerForThread(thread: Thread): Timer? {
|
||||
return sTimerMap[thread]
|
||||
}
|
||||
|
||||
@JvmStatic
|
||||
val timerForCurrentThread
|
||||
val timerForCurrentThread: Timer?
|
||||
get() = getTimerForThread(currentThread())
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -4,7 +4,6 @@ import android.content.Context;
|
||||
import android.widget.EditText;
|
||||
|
||||
import com.afollestad.materialdialogs.MaterialDialog;
|
||||
|
||||
import org.autojs.autojs.core.eventloop.EventEmitter;
|
||||
import org.autojs.autojs.core.looper.Loopers;
|
||||
import org.autojs.autojs.core.looper.Timer;
|
||||
@@ -13,6 +12,8 @@ import org.autojs.autojs.tool.UiHandler;
|
||||
|
||||
/**
|
||||
* Created by Stardust on 2018/4/17.
|
||||
* Modified by SuperMonster003 as of Mar 20, 2022.
|
||||
* Modified by aiselp as of Jun 10, 2023.
|
||||
*/
|
||||
public class JsDialogBuilder extends MaterialDialog.Builder {
|
||||
|
||||
@@ -21,7 +22,7 @@ public class JsDialogBuilder extends MaterialDialog.Builder {
|
||||
private final Timer mTimer;
|
||||
private final Loopers mLoopers;
|
||||
private JsDialog mDialog;
|
||||
private volatile int mWaitId = -1;
|
||||
private volatile Loopers.AsyncTask task;
|
||||
|
||||
public JsDialogBuilder(Context context, ScriptRuntime runtime) {
|
||||
super(context);
|
||||
@@ -55,14 +56,14 @@ public class JsDialogBuilder extends MaterialDialog.Builder {
|
||||
}
|
||||
});
|
||||
dismissListener(dialog -> {
|
||||
mTimer.postDelayed(() -> mLoopers.doNotWaitWhenIdle(mWaitId), 0);
|
||||
mTimer.postDelayed(() -> mLoopers.removeAsyncTask(task), 0);
|
||||
emit("dismiss", dialog);
|
||||
});
|
||||
cancelListener(dialog -> emit("cancel", dialog));
|
||||
}
|
||||
|
||||
public void onShowCalled() {
|
||||
mTimer.postDelayed(() -> mWaitId = mLoopers.waitWhenIdle(), 0);
|
||||
mTimer.postDelayed(() -> task = mLoopers.createAndAddAsyncTask("js-dialog"), 0);
|
||||
}
|
||||
|
||||
public JsDialog getDialog() {
|
||||
|
||||
@@ -2,19 +2,42 @@ package org.autojs.autojs.core.ui.widget
|
||||
|
||||
import android.content.Context
|
||||
import android.util.AttributeSet
|
||||
import org.autojs.autojs.AutoJs
|
||||
import android.util.Log
|
||||
import org.apache.log4j.Logger
|
||||
import org.autojs.autojs.core.console.ConsoleImpl
|
||||
import org.autojs.autojs.core.console.ConsoleView
|
||||
import org.autojs.autojs.core.console.GlobalConsole
|
||||
import org.autojs.autojs.tool.UiHandler
|
||||
import org.autojs.autojs.util.ViewUtils
|
||||
import java.util.Locale
|
||||
|
||||
class JsConsoleView : ConsoleView {
|
||||
|
||||
private val TAG = JsConsoleView::class.java.simpleName
|
||||
private val LOGGER = Logger.getLogger(JsConsoleView::class.java)
|
||||
|
||||
constructor(context: Context) : super(context)
|
||||
|
||||
constructor(context: Context, attrs: AttributeSet?) : super(context, attrs)
|
||||
|
||||
constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr)
|
||||
|
||||
init {
|
||||
setConsole(AutoJs.instance.globalConsole)
|
||||
}
|
||||
// init {
|
||||
// setConsole(object : GlobalConsole(UiHandler(context)) {
|
||||
// override fun println(level: Int, charSequence: CharSequence): String {
|
||||
// val log = String.format(Locale.getDefault(), "%s", charSequence)
|
||||
// LOGGER.log(toLog4jLevel(level), log)
|
||||
// Log.d(TAG, log)
|
||||
// super.println(level, log)
|
||||
// return log
|
||||
// }
|
||||
// })
|
||||
// }
|
||||
//
|
||||
// override fun onNewLog(logEntry: ConsoleImpl.LogEntry?) {
|
||||
// if (logEntry != null) {
|
||||
// ViewUtils.showToast(context, logEntry.content.toString())
|
||||
// }
|
||||
// }
|
||||
|
||||
}
|
||||
@@ -8,19 +8,20 @@ import okhttp3.WebSocketListener
|
||||
import okio.ByteString
|
||||
import org.autojs.autojs.AutoJs
|
||||
import org.autojs.autojs.core.eventloop.EventEmitter
|
||||
|
||||
val runtime = AutoJs.instance.runtime
|
||||
import java.lang.ref.WeakReference
|
||||
|
||||
/**
|
||||
* Created by SuperMonster003 on Apr 30, 2023.
|
||||
*/
|
||||
// @Reference to kkevsekk1/AutoX (https://github.com/kkevsekk1/AutoX) on Apr 30, 2023.
|
||||
class WebSocket @JvmOverloads constructor(val client: OkHttpClient, val url: String, isInCurrentThread: Boolean = true) : EventEmitter(
|
||||
runtime.bridges, runtime.timers.timerForCurrentThread.takeIf { isInCurrentThread }
|
||||
AutoJs.instance.runtime.bridges, AutoJs.instance.runtime.timers.timerForCurrentThread.takeIf { isInCurrentThread }
|
||||
), okhttp3.WebSocket {
|
||||
|
||||
private var maxRebuildTimes = Int.MAX_VALUE
|
||||
private var currentRebuildTimes = 0
|
||||
private var isExitOnClose = false
|
||||
private var exitOnCloseTimeout = DEFAULT_EXIT_ON_CLOSE_TIMEOUT
|
||||
|
||||
private var listener: WebSocketMessageListener
|
||||
private lateinit var webSocket: okhttp3.WebSocket
|
||||
@@ -32,16 +33,17 @@ class WebSocket @JvmOverloads constructor(val client: OkHttpClient, val url: Str
|
||||
|
||||
private fun build() {
|
||||
webSocket = client.newWebSocket(Builder().url(url).build(), listener)
|
||||
instances.add(WeakReference(this))
|
||||
}
|
||||
|
||||
fun rebuild() {
|
||||
cancel()
|
||||
if (currentRebuildTimes < maxRebuildTimes) {
|
||||
build()
|
||||
currentRebuildTimes += 1
|
||||
} else {
|
||||
emit("max_rebuild", maxRebuildTimes, this)
|
||||
emit(EVENT_MAX_REBUILDS, maxRebuildTimes, this)
|
||||
}
|
||||
currentRebuildTimes += 1
|
||||
}
|
||||
|
||||
fun rebuild(maxRebuildTimes: Int) {
|
||||
@@ -53,7 +55,10 @@ class WebSocket @JvmOverloads constructor(val client: OkHttpClient, val url: Str
|
||||
|
||||
override fun close(code: Int, reason: String?) = webSocket.close(code, reason)
|
||||
|
||||
fun close(code: Int) = webSocket.close(code, null)
|
||||
@JvmOverloads
|
||||
fun close(code: Int = CODE_CLOSE_NORMAL) = webSocket.close(code, null)
|
||||
|
||||
fun close(reason: String?) = webSocket.close(CODE_CLOSE_NORMAL, reason)
|
||||
|
||||
override fun queueSize() = webSocket.queueSize()
|
||||
|
||||
@@ -63,34 +68,47 @@ class WebSocket @JvmOverloads constructor(val client: OkHttpClient, val url: Str
|
||||
|
||||
override fun send(bytes: ByteString) = webSocket.send(bytes)
|
||||
|
||||
override fun on(eventName: String, listener: Any) = this.also { super.on(eventName, listener) }
|
||||
override fun once(eventName: String, listener: Any) = this.also { super.once(eventName, listener) }
|
||||
|
||||
@JvmOverloads
|
||||
fun exitOnClose(isExitOnClose: Boolean = true) {
|
||||
this.isExitOnClose = isExitOnClose
|
||||
}
|
||||
|
||||
fun exitOnClose(timeout: Long) {
|
||||
exitOnClose(true)
|
||||
exitOnCloseTimeout = maxOf(0, timeout)
|
||||
}
|
||||
|
||||
inner class WebSocketMessageListener(private val ws: WebSocket) : WebSocketListener() {
|
||||
|
||||
override fun onClosed(webSocket: okhttp3.WebSocket, code: Int, reason: String) {
|
||||
ws.emit("closed", code, reason, ws)
|
||||
}
|
||||
|
||||
override fun onClosing(webSocket: okhttp3.WebSocket, code: Int, reason: String) {
|
||||
ws.emit("closing", code, reason, ws)
|
||||
}
|
||||
|
||||
override fun onFailure(webSocket: okhttp3.WebSocket, t: Throwable, response: Response?) {
|
||||
Log.w(Companion.TAG, "onFailure")
|
||||
t.printStackTrace()
|
||||
ws.emit("failure", t, response, ws)
|
||||
override fun onOpen(webSocket: okhttp3.WebSocket, response: Response) {
|
||||
ws.emit(EVENT_OPEN, response, ws)
|
||||
}
|
||||
|
||||
override fun onMessage(webSocket: okhttp3.WebSocket, text: String) {
|
||||
ws.emit("message", text, ws)
|
||||
ws.emit("text", text, ws)
|
||||
ws.emit(EVENT_MESSAGE, text, ws)
|
||||
ws.emit(EVENT_TEXT, text, ws)
|
||||
}
|
||||
|
||||
override fun onMessage(webSocket: okhttp3.WebSocket, bytes: ByteString) {
|
||||
ws.emit("message", bytes, ws)
|
||||
ws.emit("bytes", bytes, ws)
|
||||
ws.emit(EVENT_MESSAGE, bytes, ws)
|
||||
ws.emit(EVENT_BYTES, bytes, ws)
|
||||
}
|
||||
|
||||
override fun onOpen(webSocket: okhttp3.WebSocket, response: Response) {
|
||||
ws.emit("open", response, ws)
|
||||
override fun onClosing(webSocket: okhttp3.WebSocket, code: Int, reason: String) {
|
||||
ws.emit(EVENT_CLOSING, code, reason, ws)
|
||||
}
|
||||
|
||||
override fun onClosed(webSocket: okhttp3.WebSocket, code: Int, reason: String) {
|
||||
ws.emit(EVENT_CLOSED, code, reason, ws)
|
||||
}
|
||||
|
||||
override fun onFailure(webSocket: okhttp3.WebSocket, t: Throwable, response: Response?) {
|
||||
Log.w(TAG, "onFailure")
|
||||
t.printStackTrace()
|
||||
ws.emit(EVENT_FAILURE, t, response, ws)
|
||||
}
|
||||
|
||||
}
|
||||
@@ -99,6 +117,139 @@ class WebSocket @JvmOverloads constructor(val client: OkHttpClient, val url: Str
|
||||
|
||||
private val TAG = WebSocket::class.java.simpleName
|
||||
|
||||
private val instances = ArrayList<WeakReference<WebSocket>>()
|
||||
|
||||
/**
|
||||
* Successful operation / regular socket shutdown.
|
||||
*
|
||||
* zh-CN: 成功操作或常规的 Socket 关闭.
|
||||
*/
|
||||
const val CODE_CLOSE_NORMAL = 1000
|
||||
|
||||
/**
|
||||
* Client is leaving (browser tab closing).
|
||||
*
|
||||
* zh-CN: 终端正在处于移除状态, 服务端或客户端即将不可用.
|
||||
*/
|
||||
const val CODE_CLOSE_GOING_AWAY = 1001
|
||||
|
||||
/**
|
||||
* Endpoint received a malformed frame.
|
||||
*
|
||||
* zh-CN: 终端因协议错误或无效帧而即将终止连接.
|
||||
*/
|
||||
const val CODE_CLOSE_PROTOCOL_ERROR = 1002
|
||||
|
||||
/**
|
||||
* Endpoint received an unsupported frame (e.g. binary-only endpoint received text frame).
|
||||
*
|
||||
* zh-CN: 终端因帧数据类型不支持而即将终止连接.
|
||||
*/
|
||||
const val CODE_CLOSE_UNSUPPORTED = 1003
|
||||
|
||||
/**
|
||||
* Expected close status, received none.
|
||||
*
|
||||
* zh-CN: 不包含错误原因, 仅代表已经关闭的状态.
|
||||
*/
|
||||
const val CODE_CLOSED_NO_STATUS = 1005
|
||||
|
||||
/**
|
||||
* No close code frame has been receieved.
|
||||
*
|
||||
* zh-CN: 异常关闭 (如浏览器关闭).
|
||||
*/
|
||||
const val CODE_CLOSE_ABNORMAL = 1006
|
||||
|
||||
/**
|
||||
* Endpoint received inconsistent message (e.g. malformed UTF-8).
|
||||
*
|
||||
* zh-CN: 终端接收到不一致的报文 (如异常格式的 UTF-8).
|
||||
*/
|
||||
const val CODE_UNSUPPORTED_PAYLOAD = 1007
|
||||
|
||||
/**
|
||||
* Generic code used for situations other than 1003 and 1009.
|
||||
*
|
||||
* zh-CN: 终端因收到了违反其策略的报文而即将终止连接.
|
||||
*/
|
||||
const val CODE_POLICY_VIOLATION = 1008
|
||||
|
||||
/**
|
||||
* Endpoint won't process large frame.
|
||||
*
|
||||
* zh-CN: 终端因无法处理长度过大的报文而即将终止连接.
|
||||
*/
|
||||
const val CODE_CLOSE_TOO_LARGE = 1009
|
||||
|
||||
/**
|
||||
* Client wanted an extension which server did not negotiate.
|
||||
*
|
||||
* zh-CN: 终端因期望与服务端进行扩展协商而即将终止连接.
|
||||
*/
|
||||
const val CODE_MANDATORY_EXTENSION = 1010
|
||||
|
||||
/**
|
||||
* Internal server error while operating.
|
||||
*
|
||||
* zh-CN: 服务端因发生内部错误而即将终止连接.
|
||||
*/
|
||||
const val CODE_SERVER_ERROR = 1011
|
||||
|
||||
/**
|
||||
* Server/service is restarting.
|
||||
*
|
||||
* zh-CN: 服务端正在重启过程中.
|
||||
*/
|
||||
const val CODE_SERVICE_RESTART = 1012
|
||||
|
||||
/**
|
||||
* Temporary server condition forced blocking client's request.
|
||||
*
|
||||
* zh-CN: 服务端临时拒绝了终端请求.
|
||||
*/
|
||||
const val CODE_TRY_AGAIN_LATER = 1013
|
||||
|
||||
/**
|
||||
* Server acting as gateway received an invalid response.
|
||||
*
|
||||
* zh-CN: 网关服务器接收到无效的请求.
|
||||
*/
|
||||
const val CODE_BAD_GATEWAY = 1014
|
||||
|
||||
/**
|
||||
* Transport Layer Security handshake failure.
|
||||
*
|
||||
* zh-CN: TLS 握手失败 (如服务端证书未通过验证等).
|
||||
*/
|
||||
const val CODE_TLS_HANDSHAKE_FAIL = 1015
|
||||
|
||||
const val EVENT_CLOSED = "closed"
|
||||
const val EVENT_CLOSING = "closing"
|
||||
const val EVENT_FAILURE = "failure"
|
||||
const val EVENT_TEXT = "text"
|
||||
const val EVENT_MESSAGE = "message"
|
||||
const val EVENT_BYTES = "bytes"
|
||||
const val EVENT_OPEN = "open"
|
||||
const val EVENT_MAX_REBUILDS = "max_rebuilds"
|
||||
|
||||
private const val DEFAULT_EXIT_ON_CLOSE_TIMEOUT = 0L
|
||||
|
||||
@JvmStatic
|
||||
fun onExit(reason: String?) {
|
||||
val wsList = instances.mapNotNull { ref -> ref.get() }
|
||||
if (wsList.isNotEmpty()) {
|
||||
Log.d(TAG, "onExit ready")
|
||||
wsList.forEach {
|
||||
val r = {
|
||||
Log.d(TAG, "onExit triggered after delayed")
|
||||
if (it.isExitOnClose) it.close(CODE_CLOSE_NORMAL, reason)
|
||||
}
|
||||
AutoJs.instance.runtime.uiHandler.postDelayed(r, it.exitOnCloseTimeout)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -179,11 +179,12 @@ public class ScriptEngineService {
|
||||
return mScriptEngineManager.stopAll();
|
||||
}
|
||||
|
||||
public void stopAllAndToast() {
|
||||
public int stopAllAndToast() {
|
||||
int n = stopAll();
|
||||
if (n > 0) {
|
||||
mUiHandler.toast(mContext.getResources().getQuantityString(R.plurals.text_already_stop_n_scripts, n, n));
|
||||
}
|
||||
return n;
|
||||
}
|
||||
|
||||
public Set<ScriptEngine> getEngines() {
|
||||
|
||||
@@ -27,23 +27,18 @@ public class GlobalKeyObserver implements OnKeyListener, ShellKeyObserver.KeyLis
|
||||
private boolean mVolumeDownFromShell, mVolumeDownFromAccessibility;
|
||||
private boolean mVolumeUpFromShell, mVolumeUpFromAccessibility;
|
||||
|
||||
GlobalKeyObserver() {
|
||||
public GlobalKeyObserver() {
|
||||
AccessibilityService.Companion.getStickOnKeyObserver()
|
||||
.addListener(this);
|
||||
ShellKeyObserver observer = new ShellKeyObserver();
|
||||
observer.setKeyListener(this);
|
||||
InputEventObserver.getGlobal(GlobalAppContext.get()).addListener(observer);
|
||||
InputEventObserver.initObserver(GlobalAppContext.get()).addListener(observer);
|
||||
}
|
||||
|
||||
public static GlobalKeyObserver getSingleton() {
|
||||
public static void initIfNeeded() {
|
||||
if (sSingleton == null) {
|
||||
sSingleton = new GlobalKeyObserver();
|
||||
}
|
||||
return sSingleton;
|
||||
}
|
||||
|
||||
public static void init() {
|
||||
if (Pref.isUseVolumeControlRunningEnabled()) getSingleton();
|
||||
}
|
||||
|
||||
public void onVolumeUp() {
|
||||
|
||||
+18
-3
@@ -1,5 +1,6 @@
|
||||
package org.autojs.autojs.external.receiver;
|
||||
|
||||
import android.annotation.SuppressLint;
|
||||
import android.content.BroadcastReceiver;
|
||||
import android.content.Context;
|
||||
import android.content.IntentFilter;
|
||||
@@ -30,13 +31,22 @@ public class DynamicBroadcastReceivers {
|
||||
private final Context mContext;
|
||||
|
||||
|
||||
@SuppressLint("UnspecifiedRegisterReceiverFlag")
|
||||
public DynamicBroadcastReceivers(Context context) {
|
||||
mContext = context;
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
|
||||
mContext.registerReceiver(mDefaultActionReceiver, createIntentFilter(StaticBroadcastReceiver.ACTIONS));
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
|
||||
mContext.registerReceiver(mDefaultActionReceiver, createIntentFilter(StaticBroadcastReceiver.ACTIONS), Context.RECEIVER_NOT_EXPORTED);
|
||||
} else {
|
||||
mContext.registerReceiver(mDefaultActionReceiver, createIntentFilter(StaticBroadcastReceiver.ACTIONS));
|
||||
}
|
||||
IntentFilter filter = createIntentFilter(StaticBroadcastReceiver.PACKAGE_ACTIONS);
|
||||
filter.addDataScheme("package");
|
||||
mContext.registerReceiver(mPackageActionReceiver, filter);
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
|
||||
mContext.registerReceiver(mPackageActionReceiver, filter, Context.RECEIVER_NOT_EXPORTED);
|
||||
} else {
|
||||
mContext.registerReceiver(mPackageActionReceiver, filter);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -120,6 +130,7 @@ public class DynamicBroadcastReceivers {
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressLint("UnspecifiedRegisterReceiverFlag")
|
||||
boolean register() {
|
||||
if (actions.isEmpty())
|
||||
return false;
|
||||
@@ -128,7 +139,11 @@ public class DynamicBroadcastReceivers {
|
||||
LocalBroadcastManager broadcastManager = LocalBroadcastManager.getInstance(mContext);
|
||||
broadcastManager.registerReceiver(receiver, intentFilter);
|
||||
} else {
|
||||
mContext.registerReceiver(receiver, intentFilter);
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
|
||||
mContext.registerReceiver(receiver, intentFilter, Context.RECEIVER_NOT_EXPORTED);
|
||||
} else {
|
||||
mContext.registerReceiver(receiver, intentFilter);
|
||||
}
|
||||
}
|
||||
Log.d(LOG_TAG, "register: " + actions);
|
||||
return true;
|
||||
|
||||
@@ -316,7 +316,7 @@ public class UpdateChecker {
|
||||
neutralButton.setOnClickListener(v -> new MaterialDialog.Builder(context)
|
||||
.title(R.string.text_prompt)
|
||||
.content(R.string.prompt_add_ignored_version)
|
||||
.negativeText(R.string.dialog_button_back)
|
||||
.negativeText(R.string.dialog_button_cancel)
|
||||
.positiveText(R.string.dialog_button_confirm)
|
||||
.positiveColorRes(R.color.dialog_button_warn)
|
||||
.onPositive((dPrompt, which) -> {
|
||||
@@ -525,7 +525,7 @@ public class UpdateChecker {
|
||||
this
|
||||
.title(title)
|
||||
.content(content)
|
||||
.positiveText(R.string.text_back)
|
||||
.positiveText(R.string.dialog_button_dismiss)
|
||||
.cancelable(false);
|
||||
}
|
||||
|
||||
@@ -540,7 +540,7 @@ public class UpdateChecker {
|
||||
.content(R.string.text_getting_release_notes)
|
||||
.neutralText(R.string.dialog_button_ignore_current_update)
|
||||
.neutralColor(context.getColor(R.color.dialog_button_warn))
|
||||
.negativeText(R.string.dialog_button_back)
|
||||
.negativeText(R.string.dialog_button_cancel)
|
||||
.negativeColor(context.getColor(R.color.dialog_button_default))
|
||||
.positiveText(R.string.dialog_button_update_now)
|
||||
.positiveColor(context.getColor(R.color.dialog_button_unavailable))
|
||||
|
||||
@@ -157,9 +157,9 @@ public class DownloadManager {
|
||||
.onNeutral((dialog, which) -> new MaterialDialog.Builder(context)
|
||||
.title(R.string.text_prompt)
|
||||
.content(R.string.text_download_interruption_warning)
|
||||
.negativeText(R.string.text_back)
|
||||
.negativeText(R.string.dialog_button_back)
|
||||
.negativeColorRes(R.color.dialog_button_hint)
|
||||
.positiveText(R.string.text_continue)
|
||||
.positiveText(R.string.dialog_button_continue)
|
||||
.positiveColorRes(R.color.dialog_button_caution)
|
||||
.onPositive((d2, which2) -> {
|
||||
dialog.getActionButton(DialogAction.POSITIVE).performClick();
|
||||
|
||||
@@ -46,7 +46,7 @@ class DisplayOverOtherAppsPermission(override val context: Context) : Permission
|
||||
}
|
||||
val r = Runnable {
|
||||
toggle()
|
||||
ViewUtils.showToast(context, R.string.error_no_draw_overlays_permission)
|
||||
ViewUtils.showToast(context, R.string.error_no_display_over_other_apps_permission)
|
||||
}
|
||||
if (Looper.myLooper() != Looper.getMainLooper()) {
|
||||
Handler(Looper.getMainLooper()).post(r)
|
||||
|
||||
@@ -206,7 +206,7 @@ public class DevPluginResponseHandler implements Handler {
|
||||
private void copyDir(File fromDir, File toDir) throws FileNotFoundException {
|
||||
toDir.mkdirs();
|
||||
File[] files = fromDir.listFiles();
|
||||
if (files == null || files.length == 0) {
|
||||
if (files == null) {
|
||||
return;
|
||||
}
|
||||
for (File file : files) {
|
||||
|
||||
@@ -88,10 +88,10 @@ class DevPluginService(val context: Context) {
|
||||
}
|
||||
|
||||
@AnyThread
|
||||
fun connectToRemoteServer(host: String, clientModeItem: DrawerMenuDisposableItem?) = connectToRemoteServer(host, clientModeItem, false)
|
||||
fun connectToRemoteServer(context: Context, host: String, clientModeItem: DrawerMenuDisposableItem?) = connectToRemoteServer(context, host, clientModeItem, false)
|
||||
|
||||
@AnyThread
|
||||
fun connectToRemoteServer(host: String, clientModeItem: DrawerMenuDisposableItem?, ignoreExceptions: Boolean): Observable<JsonSocketClient> {
|
||||
fun connectToRemoteServer(context: Context, host: String, clientModeItem: DrawerMenuDisposableItem?, ignoreExceptions: Boolean): Observable<JsonSocketClient> {
|
||||
try {
|
||||
var port = Port.PC_SERVER
|
||||
var ip = host
|
||||
@@ -101,7 +101,7 @@ class DevPluginService(val context: Context) {
|
||||
ip = host.substring(0, i)
|
||||
}
|
||||
return Observable
|
||||
.just(JsonSocketClient(this, ip, port))
|
||||
.just(JsonSocketClient(this, context, ip, port))
|
||||
.observeOn(Schedulers.newThread())
|
||||
.doOnNext { jsonSocketClient ->
|
||||
try {
|
||||
@@ -179,9 +179,10 @@ class DevPluginService(val context: Context) {
|
||||
}
|
||||
}
|
||||
|
||||
@AnyThread // FIXME by SuperMonster003 as of Dec 29, 2021.
|
||||
// FIXME by SuperMonster003 as of Dec 29, 2021.
|
||||
// ! Would print double (may be even more times) the amount of
|
||||
// ! messages on VSCode when multi connection were established.
|
||||
@AnyThread
|
||||
fun print(log: String?) {
|
||||
jsonSocketClient?.writeLog(log)
|
||||
jsonSocketServer?.writeLog(log)
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package org.autojs.autojs.pluginclient
|
||||
|
||||
import android.app.Activity
|
||||
import android.content.Context
|
||||
import android.text.util.Linkify
|
||||
import android.util.Log
|
||||
import androidx.annotation.MainThread
|
||||
@@ -24,7 +25,7 @@ import java.net.SocketTimeoutException
|
||||
import java.util.concurrent.Executors
|
||||
|
||||
|
||||
class JsonSocketClient(service: DevPluginService?, host: String?, port: Int) : JsonSocket(service) {
|
||||
class JsonSocketClient(service: DevPluginService?, private val ctx: Context, host: String?, port: Int) : JsonSocket(service) {
|
||||
|
||||
private val jsonSocketExecutor = Executors.newSingleThreadExecutor()
|
||||
|
||||
@@ -83,6 +84,8 @@ class JsonSocketClient(service: DevPluginService?, host: String?, port: Int) : J
|
||||
}, HANDSHAKE_TIMEOUT.toLong())
|
||||
}
|
||||
|
||||
override fun getContext() = ctx
|
||||
|
||||
private fun onHello(message: JsonObject) {
|
||||
var currentVersion: String? = null
|
||||
val requiredVersion = BuildConfig.VSCODE_EXT_REQUIRED_VERSION
|
||||
@@ -127,7 +130,7 @@ class JsonSocketClient(service: DevPluginService?, host: String?, port: Int) : J
|
||||
MaterialDialog.Builder(activity)
|
||||
.title(activity.getString(R.string.text_connection_cannot_be_established))
|
||||
.content(msg)
|
||||
.positiveText(R.string.dialog_button_back)
|
||||
.positiveText(R.string.dialog_button_dismiss)
|
||||
.build()
|
||||
.also {
|
||||
it.contentView?.apply {
|
||||
|
||||
@@ -37,9 +37,6 @@ object Pref {
|
||||
if (key == key(R.string.key_guard_mode)) {
|
||||
AccessibilityConfig.refreshUnintendedGuardState()
|
||||
}
|
||||
if (key == key(R.string.key_use_volume_control_record) || key == key(R.string.key_use_volume_control_running) && isUseVolumeControlRunningEnabled) {
|
||||
GlobalKeyObserver.init()
|
||||
}
|
||||
}
|
||||
|
||||
init {
|
||||
@@ -249,9 +246,15 @@ object Pref {
|
||||
@JvmStatic
|
||||
fun putBoolean(@KeyRes keyRes: Int, value: Boolean) = putBoolean(key(keyRes), value)
|
||||
|
||||
@JvmStatic
|
||||
fun putBooleanSync(@KeyRes keyRes: Int, value: Boolean) = putBooleanSync(key(keyRes), value)
|
||||
|
||||
@JvmStatic
|
||||
fun putBoolean(key: String?, value: Boolean) = sPref.edit().putBoolean(key, value).apply()
|
||||
|
||||
@JvmStatic
|
||||
fun putBooleanSync(key: String?, value: Boolean) = sPref.edit().putBoolean(key, value).commit()
|
||||
|
||||
@JvmStatic
|
||||
fun getBoolean(@KeyRes keyRes: Int, defValue: Boolean) = getBoolean(key(keyRes), defValue)
|
||||
|
||||
@@ -264,12 +267,24 @@ object Pref {
|
||||
@JvmStatic
|
||||
fun putInt(key: String?, value: Int) = sPref.edit().putInt(key, value).apply()
|
||||
|
||||
@JvmStatic
|
||||
fun putIntSync(key: String?, value: Int) = sPref.edit().putInt(key, value).commit()
|
||||
|
||||
@JvmStatic
|
||||
fun putFloat(key: String?, value: Float) = sPref.edit().putFloat(key, value).apply()
|
||||
|
||||
@JvmStatic
|
||||
fun putFloatSync(key: String?, value: Float) = sPref.edit().putFloat(key, value).commit()
|
||||
|
||||
@JvmStatic
|
||||
fun getInt(@KeyRes keyRes: Int, defValue: Int): Int = getInt(key(keyRes), defValue)
|
||||
|
||||
@JvmStatic
|
||||
fun getInt(key: String?, defValue: Int): Int = sPref.getInt(key, defValue)
|
||||
|
||||
@JvmStatic
|
||||
fun getFloat(key: String?, defValue: Float): Float = sPref.getFloat(key, defValue)
|
||||
|
||||
@JvmStatic
|
||||
fun putLong(@KeyRes keyRes: Int, value: Long) = sPref.edit().putLong(key(keyRes), value).apply()
|
||||
|
||||
|
||||
@@ -22,6 +22,7 @@ import org.autojs.autojs.core.image.Colors;
|
||||
import org.autojs.autojs.core.image.ImageWrapper;
|
||||
import org.autojs.autojs.core.image.capture.ScreenCaptureRequester;
|
||||
import org.autojs.autojs.core.looper.Loopers;
|
||||
import org.autojs.autojs.core.web.WebSocket;
|
||||
import org.autojs.autojs.engine.ScriptEngineService;
|
||||
import org.autojs.autojs.lang.ThreadCompat;
|
||||
import org.autojs.autojs.pio.PFiles;
|
||||
@@ -39,11 +40,12 @@ import org.autojs.autojs.runtime.api.Files;
|
||||
import org.autojs.autojs.runtime.api.Floaty;
|
||||
import org.autojs.autojs.runtime.api.Images;
|
||||
import org.autojs.autojs.runtime.api.Media;
|
||||
import org.autojs.autojs.runtime.api.MlKitOCR;
|
||||
import org.autojs.autojs.runtime.api.PaddleOCR;
|
||||
import org.autojs.autojs.runtime.api.OcrMLKit;
|
||||
import org.autojs.autojs.runtime.api.OcrPaddle;
|
||||
import org.autojs.autojs.runtime.api.Plugins;
|
||||
import org.autojs.autojs.runtime.api.ProcessShell;
|
||||
import org.autojs.autojs.runtime.api.ScreenMetrics;
|
||||
import org.autojs.autojs.runtime.api.ScriptToast;
|
||||
import org.autojs.autojs.runtime.api.Sensors;
|
||||
import org.autojs.autojs.runtime.api.Threads;
|
||||
import org.autojs.autojs.runtime.api.Timers;
|
||||
@@ -242,10 +244,13 @@ public class ScriptRuntime {
|
||||
private final Images images;
|
||||
|
||||
@ScriptVariable
|
||||
public final MlKitOCR mlKitOCR;
|
||||
public final ScriptToast toast;
|
||||
|
||||
@ScriptVariable
|
||||
public final PaddleOCR paddleOCR;
|
||||
public final OcrMLKit ocrMLKit;
|
||||
|
||||
@ScriptVariable
|
||||
public final OcrPaddle ocrPaddle;
|
||||
|
||||
private static WeakReference<Context> applicationContext;
|
||||
private final Map<String, Object> mProperties = new ConcurrentHashMap<>();
|
||||
@@ -281,8 +286,9 @@ public class ScriptRuntime {
|
||||
media = new Media(context, this);
|
||||
plugins = new Plugins(context, this);
|
||||
|
||||
mlKitOCR = new MlKitOCR();
|
||||
paddleOCR = new PaddleOCR();
|
||||
ocrMLKit = new OcrMLKit();
|
||||
ocrPaddle = new OcrPaddle();
|
||||
toast = new ScriptToast(context, this);
|
||||
}
|
||||
|
||||
public void init() {
|
||||
@@ -327,10 +333,6 @@ public class ScriptRuntime {
|
||||
return accessibilityBridge;
|
||||
}
|
||||
|
||||
public void toast(final String text) {
|
||||
uiHandler.toast(text);
|
||||
}
|
||||
|
||||
public void sleep(long millis) {
|
||||
try {
|
||||
Thread.sleep(millis);
|
||||
@@ -536,6 +538,8 @@ public class ScriptRuntime {
|
||||
}
|
||||
});
|
||||
|
||||
ignoresException(() -> WebSocket.onExit("Triggered by " + ScriptRuntime.class.getSimpleName()));
|
||||
|
||||
// @Hint by 抠脚本人 on Jul 10, 2023.
|
||||
// ! 清空无障碍事件.
|
||||
ignoresException(AccessibilityService::clearAccessibilityEventCallback);
|
||||
@@ -558,8 +562,8 @@ public class ScriptRuntime {
|
||||
ignoresException(loopers::recycle);
|
||||
ignoresException(this::recycleShell);
|
||||
ignoresException(images::releaseScreenCapturer);
|
||||
ignoresException(mlKitOCR::release);
|
||||
ignoresException(paddleOCR::release);
|
||||
ignoresException(ocrMLKit::release);
|
||||
ignoresException(ocrPaddle::release);
|
||||
ignoresException(sensors::unregisterAll);
|
||||
ignoresException(timers::recycle);
|
||||
ignoresException(ui::recycle);
|
||||
|
||||
@@ -44,8 +44,8 @@ public abstract class AbstractShell {
|
||||
this(false);
|
||||
}
|
||||
|
||||
public AbstractShell(boolean root) {
|
||||
this(null, root);
|
||||
public AbstractShell(boolean isExecWithRoot) {
|
||||
this(null, isExecWithRoot);
|
||||
}
|
||||
|
||||
public AbstractShell(Context context, boolean isExecWithRoot) {
|
||||
@@ -67,9 +67,9 @@ public abstract class AbstractShell {
|
||||
public abstract void exit();
|
||||
|
||||
public void SetTouchDevice(int touchDevice) {
|
||||
if (mTouchDevice > 0)
|
||||
return;
|
||||
mTouchDevice = touchDevice;
|
||||
if (mTouchDevice <= 0) {
|
||||
mTouchDevice = touchDevice;
|
||||
}
|
||||
}
|
||||
|
||||
public void SendEvent(int type, int code, int value) {
|
||||
|
||||
@@ -219,8 +219,10 @@ class AppUtils {
|
||||
enum class BroadcastShortForm(val shortName: String) {
|
||||
|
||||
INSPECT_LAYOUT_BOUNDS("inspect_layout_bounds"),
|
||||
LAYOUT_BOUNDS("layout_bounds"),
|
||||
BOUNDS("bounds"),
|
||||
INSPECT_LAYOUT_HIERARCHY("inspect_layout_hierarchy"),
|
||||
LAYOUT_HIERARCHY("layout_hierarchy"),
|
||||
HIERARCHY("hierarchy"),
|
||||
;
|
||||
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
package org.autojs.autojs.runtime.api;
|
||||
|
||||
import static android.content.Context.WINDOW_SERVICE;
|
||||
|
||||
import android.Manifest;
|
||||
import android.annotation.SuppressLint;
|
||||
import android.app.ActivityManager;
|
||||
@@ -7,6 +9,7 @@ import android.content.Context;
|
||||
import android.content.Intent;
|
||||
import android.content.IntentFilter;
|
||||
import android.content.pm.PackageManager;
|
||||
import android.content.res.Configuration;
|
||||
import android.media.AudioManager;
|
||||
import android.net.wifi.WifiInfo;
|
||||
import android.net.wifi.WifiManager;
|
||||
@@ -17,6 +20,7 @@ import android.os.VibrationEffect;
|
||||
import android.os.Vibrator;
|
||||
import android.provider.Settings;
|
||||
import android.view.Display;
|
||||
import android.view.Surface;
|
||||
import android.view.WindowManager;
|
||||
|
||||
import androidx.annotation.NonNull;
|
||||
@@ -25,6 +29,8 @@ import androidx.annotation.Nullable;
|
||||
import org.autojs.autojs.pio.PFiles;
|
||||
import org.autojs.autojs.pio.UncheckedIOException;
|
||||
import org.autojs.autojs.util.DeviceUtils;
|
||||
import org.autojs.autojs.util.RomUtils;
|
||||
import org.autojs.autojs.util.RomUtils.Brand;
|
||||
import org.autojs.autojs6.R;
|
||||
|
||||
import java.net.NetworkInterface;
|
||||
@@ -36,6 +42,7 @@ import ezy.assist.compat.SettingsCompat;
|
||||
|
||||
/**
|
||||
* Created by Stardust on 2017/12/2.
|
||||
* Modified by SuperMonster003 as of Jan 1, 2022.
|
||||
*/
|
||||
public class Device {
|
||||
|
||||
@@ -87,6 +94,10 @@ public class Device {
|
||||
|
||||
public static String imei;
|
||||
|
||||
public final Manufacturers manufacturers;
|
||||
public final RomUtils roms;
|
||||
public final Brand brands;
|
||||
|
||||
private final Context mContext;
|
||||
private final Vibrator mVibrator;
|
||||
private PowerManager.WakeLock mWakeLock;
|
||||
@@ -95,6 +106,9 @@ public class Device {
|
||||
public Device(Context context) {
|
||||
mContext = context;
|
||||
mVibrator = context.getSystemService(Vibrator.class);
|
||||
manufacturers = new Manufacturers();
|
||||
roms = RomUtils.INSTANCE;
|
||||
brands = Brand.INSTANCE;
|
||||
imei = DeviceUtils.getIMEI(context);
|
||||
serial = DeviceUtils.getSerial();
|
||||
}
|
||||
@@ -237,7 +251,7 @@ public class Device {
|
||||
}
|
||||
|
||||
public boolean isScreenOn() {
|
||||
return ((WindowManager) getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay().getState() == Display.STATE_ON;
|
||||
return getDefaultDisplay().getState() == Display.STATE_ON;
|
||||
}
|
||||
|
||||
public void wakeUpIfNeeded() {
|
||||
@@ -303,6 +317,30 @@ public class Device {
|
||||
mVibrator.cancel();
|
||||
}
|
||||
|
||||
public int getOrientation() {
|
||||
if (isScreenLandscape()) {
|
||||
return Configuration.ORIENTATION_LANDSCAPE;
|
||||
}
|
||||
if (isScreenPortrait()) {
|
||||
return Configuration.ORIENTATION_PORTRAIT;
|
||||
}
|
||||
return Configuration.ORIENTATION_UNDEFINED;
|
||||
}
|
||||
|
||||
public int getRotation() {
|
||||
return getDefaultDisplay().getRotation();
|
||||
}
|
||||
|
||||
public boolean isScreenPortrait() {
|
||||
int rotation = getRotation();
|
||||
return rotation == Surface.ROTATION_0 || rotation == Surface.ROTATION_180;
|
||||
}
|
||||
|
||||
public boolean isScreenLandscape() {
|
||||
int rotation = getRotation();
|
||||
return rotation == Surface.ROTATION_90 || rotation == Surface.ROTATION_270;
|
||||
}
|
||||
|
||||
private void checkWriteSettingsPermission() {
|
||||
if (SettingsCompat.canWriteSettings(mContext)) {
|
||||
return;
|
||||
@@ -311,12 +349,16 @@ public class Device {
|
||||
throw new SecurityException(mContext.getString(R.string.error_no_write_settings_permission));
|
||||
}
|
||||
|
||||
private void checkReadPhoneStatePermission() {
|
||||
if (mContext.checkSelfPermission(Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
|
||||
public void ensureReadPhoneStatePermission() {
|
||||
if (!hasReadPhoneStatePermission()) {
|
||||
throw new SecurityException(mContext.getString(R.string.error_no_read_phone_state_permission));
|
||||
}
|
||||
}
|
||||
|
||||
public boolean hasReadPhoneStatePermission() {
|
||||
return mContext.checkSelfPermission(Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_GRANTED;
|
||||
}
|
||||
|
||||
// just to avoid warning of null pointer to make android studio happy..
|
||||
@NonNull
|
||||
@SuppressWarnings("unchecked")
|
||||
@@ -412,4 +454,140 @@ public class Device {
|
||||
'}';
|
||||
}
|
||||
|
||||
private Display getDefaultDisplay() {
|
||||
return ((WindowManager) getSystemService(WINDOW_SERVICE)).getDefaultDisplay();
|
||||
}
|
||||
|
||||
public boolean isManufacturer(String manufacturer) {
|
||||
return manufacturers.is(manufacturer);
|
||||
}
|
||||
|
||||
public class Manufacturers {
|
||||
|
||||
private boolean is(String manufacturer) {
|
||||
return manufacturer.equalsIgnoreCase(Build.MANUFACTURER);
|
||||
}
|
||||
|
||||
/**
|
||||
* HTC.
|
||||
*/
|
||||
public boolean isHtc() {
|
||||
return is("htc");
|
||||
}
|
||||
|
||||
/**
|
||||
* LG.
|
||||
*/
|
||||
public boolean isLG() {
|
||||
return is("lg");
|
||||
}
|
||||
|
||||
/**
|
||||
* 一加.
|
||||
*/
|
||||
public boolean isOnePlus() {
|
||||
return is("oneplus");
|
||||
}
|
||||
|
||||
/**
|
||||
* 三星.
|
||||
*/
|
||||
public boolean isSamsung() {
|
||||
return is("samsung");
|
||||
}
|
||||
|
||||
/**
|
||||
* 中兴.
|
||||
*/
|
||||
public boolean isZte() {
|
||||
return is("zte");
|
||||
}
|
||||
|
||||
/**
|
||||
* 乐视.
|
||||
*/
|
||||
public boolean isLetv() {
|
||||
return is("letv");
|
||||
}
|
||||
|
||||
/**
|
||||
* 华为.
|
||||
*/
|
||||
public boolean isHuawei() {
|
||||
return is("huawei") || isNova() || isHonor();
|
||||
}
|
||||
|
||||
/**
|
||||
* Huawei (华为) Nova.
|
||||
*/
|
||||
public boolean isNova() {
|
||||
return is("nova");
|
||||
}
|
||||
|
||||
/**
|
||||
* Huawei (华为) 荣耀.
|
||||
*/
|
||||
public boolean isHonor() {
|
||||
return is("honor");
|
||||
}
|
||||
|
||||
/**
|
||||
* 小米.
|
||||
*/
|
||||
public boolean isXiaomi() {
|
||||
return is("xiaomi") || brands.isRedmi() || brands.isMiMix();
|
||||
}
|
||||
|
||||
/**
|
||||
* 欧珀.
|
||||
*/
|
||||
public boolean isOppo() {
|
||||
return is("oppo");
|
||||
}
|
||||
|
||||
/**
|
||||
* 索尼.
|
||||
*/
|
||||
public boolean isSony() {
|
||||
return is("sony") || brands.isXperia();
|
||||
}
|
||||
|
||||
/**
|
||||
* 维沃.
|
||||
*/
|
||||
public boolean isVivo() {
|
||||
return is("vivo");
|
||||
}
|
||||
|
||||
/**
|
||||
* 联想.
|
||||
*/
|
||||
public boolean isLenovo() {
|
||||
return is("lenovo");
|
||||
}
|
||||
|
||||
/**
|
||||
* 酷派.
|
||||
* 宇龙计算机通信科技 (深圳) 有限公司.
|
||||
*/
|
||||
public boolean isCoolpad() {
|
||||
return is("yulong");
|
||||
}
|
||||
|
||||
/**
|
||||
* 锤子.
|
||||
*/
|
||||
public boolean isSmartisan() {
|
||||
return is("smartisan");
|
||||
}
|
||||
|
||||
/**
|
||||
* 魅族.
|
||||
*/
|
||||
public boolean isMeizu() {
|
||||
return is("meizu");
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -133,7 +133,7 @@ public class Events extends EventEmitter implements OnKeyListener, TouchObserver
|
||||
return;
|
||||
ensureHandler();
|
||||
mLoopers.waitWhenIdle(true);
|
||||
mTouchObserver = new TouchObserver(InputEventObserver.getGlobal(mContext));
|
||||
mTouchObserver = new TouchObserver(InputEventObserver.initObserver(mContext));
|
||||
mTouchObserver.setOnTouchEventListener(this);
|
||||
mTouchObserver.observe();
|
||||
}
|
||||
|
||||
@@ -18,6 +18,7 @@ import org.autojs.autojs.runtime.exception.ScriptInterruptedException
|
||||
import org.autojs.autojs.tool.UiHandler
|
||||
import org.autojs.autojs.util.ViewUtils.setViewMeasure
|
||||
import org.autojs.autojs6.R
|
||||
import java.lang.Exception
|
||||
import java.util.concurrent.CopyOnWriteArraySet
|
||||
|
||||
/**
|
||||
@@ -73,6 +74,13 @@ class Floaty(private val mUiHandler: UiHandler, private val mRuntime: ScriptRunt
|
||||
@ScriptInterface
|
||||
fun requestPermission() = mDisplayOverOtherAppsPerm.request()
|
||||
|
||||
@ScriptInterface
|
||||
fun ensurePermission() {
|
||||
if (!hasPermission()) {
|
||||
throw Exception(mContext.getString(R.string.error_no_display_over_other_apps_permission))
|
||||
}
|
||||
}
|
||||
|
||||
@Synchronized
|
||||
fun closeAll() {
|
||||
mWindows.apply {
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
package org.autojs.autojs.runtime.api
|
||||
|
||||
import java.lang.Exception
|
||||
|
||||
interface IPermissionToggleable {
|
||||
|
||||
val description: String
|
||||
|
||||
fun has(): Boolean
|
||||
|
||||
fun toggle(forcible: Boolean = false) {
|
||||
try {
|
||||
if (!has()) request(forcible) else revoke()
|
||||
} catch (e: Exception) {
|
||||
when (e) {
|
||||
is PermissionRequestException -> {
|
||||
throw PermissionToggleException("$description can't ..., may be not able to request")
|
||||
}
|
||||
is PermissionRevokeException -> {
|
||||
throw PermissionToggleException("$description can't ..., may be not able to revoke")
|
||||
}
|
||||
else -> throw e
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun request(forcible: Boolean) {
|
||||
if (forcible) {
|
||||
try {
|
||||
revoke()
|
||||
} catch (e: PermissionRevokeException) {
|
||||
throw PermissionRequestException("$description can't ...")
|
||||
}
|
||||
}
|
||||
request()
|
||||
}
|
||||
|
||||
fun request() {
|
||||
try {
|
||||
config()
|
||||
} catch (e: PermissionConfigException) {
|
||||
throw PermissionRequestException("$description can't ...")
|
||||
}
|
||||
}
|
||||
|
||||
fun requestIfNeeded(forcible: Boolean = false) {
|
||||
if (!has()) request(forcible)
|
||||
}
|
||||
|
||||
fun revoke() {
|
||||
try {
|
||||
config()
|
||||
} catch (e: PermissionConfigException) {
|
||||
throw PermissionRevokeException("$description can't ...")
|
||||
}
|
||||
}
|
||||
|
||||
fun revokeIfNeeded() {
|
||||
if (has()) revoke()
|
||||
}
|
||||
|
||||
fun config() {
|
||||
throw PermissionConfigException("$description can't ...")
|
||||
}
|
||||
|
||||
class PermissionRequestException(e: String) : Exception(e)
|
||||
|
||||
class PermissionRevokeException(e: String) : Exception(e)
|
||||
|
||||
class PermissionConfigException(e: String) : Exception(e)
|
||||
|
||||
class PermissionToggleException(e: String) : Exception(e)
|
||||
|
||||
}
|
||||
+1
-1
@@ -11,7 +11,7 @@ import org.autojs.autojs.core.image.ImageWrapper
|
||||
* Created by SuperMonster003 on Mar 18, 2023.
|
||||
*/
|
||||
// @Reference to TonyJiangWJ/Auto.js (https://github.com/TonyJiangWJ/Auto.js) on Mar 18, 2023.
|
||||
class MlKitOCR {
|
||||
class OcrMLKit {
|
||||
|
||||
private var recognizer: TextRecognizer? = null
|
||||
|
||||
+2
-1
@@ -6,6 +6,7 @@ import android.util.Log;
|
||||
|
||||
import com.baidu.paddle.lite.ocr.OcrResult;
|
||||
import com.baidu.paddle.lite.ocr.Predictor;
|
||||
|
||||
import org.autojs.autojs.app.GlobalAppContext;
|
||||
import org.autojs.autojs.concurrent.VolatileDispose;
|
||||
import org.autojs.autojs.core.image.ImageWrapper;
|
||||
@@ -17,7 +18,7 @@ import java.util.List;
|
||||
* @author TonyJiangWJ
|
||||
* @since 2023-08-06
|
||||
*/
|
||||
public class PaddleOCR {
|
||||
public class OcrPaddle {
|
||||
private final Predictor mPredictor = new Predictor();
|
||||
|
||||
public synchronized boolean init(boolean useSlim) {
|
||||
@@ -0,0 +1,49 @@
|
||||
package org.autojs.autojs.runtime.api
|
||||
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import org.autojs.autojs.util.RomUtils
|
||||
|
||||
class Permissions(private val context: Context) {
|
||||
|
||||
var postNotifications: IPermissionToggleable? = null
|
||||
var notificationAccess: IPermissionToggleable? = null
|
||||
var usageStatesAccess: IPermissionToggleable? = null
|
||||
var ignoreBatteryOptimizations: IPermissionToggleable? = null
|
||||
var backgroundStart = object : IPermissionToggleable {
|
||||
override val description = "后台弹出界面 / Start in background"
|
||||
override fun has() = RomUtils.isBackgroundStartGranted(context)
|
||||
override fun config() = when {
|
||||
RomUtils.isMiui() -> {
|
||||
Intent("miui.intent.action.APP_PERM_EDITOR").apply {
|
||||
setClassName(
|
||||
"com.miui.securitycenter",
|
||||
"com.miui.permcenter.permissions.PermissionsEditorActivity",
|
||||
)
|
||||
putExtra("extra_pkgname", context.packageName)
|
||||
addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
|
||||
}.let { context.startActivity(it) }
|
||||
}
|
||||
else -> super.config()
|
||||
}
|
||||
}
|
||||
var displayOverOtherApps: IPermissionToggleable? = null
|
||||
var writeSystemSettings: IPermissionToggleable? = null
|
||||
var writeSecuritySettings: IPermissionToggleable? = null
|
||||
var projectMediaAccess: IPermissionToggleable? = null
|
||||
val isBackgroundStartGranted: Boolean
|
||||
get() = RomUtils.isBackgroundStartGranted(context)
|
||||
|
||||
// TODO by SuperMonster003 on Aug 28, 2023.
|
||||
|
||||
/* permissions.postNotifications */
|
||||
/* permissions.notificationAccess */
|
||||
/* permissions.usageStatesAccess */
|
||||
/* permissions.ignoreBatteryOptimizations */
|
||||
/* permissions.backgroundStart */
|
||||
/* permissions.displayOverOtherApps */
|
||||
/* permissions.writeSystemSettings */
|
||||
/* permissions.writeSecuritySettings */
|
||||
/* permissions.projectMediaAccess */
|
||||
|
||||
}
|
||||
@@ -1,15 +1,18 @@
|
||||
package org.autojs.autojs.runtime.api
|
||||
|
||||
import android.app.Activity
|
||||
import android.content.res.Configuration
|
||||
import android.content.res.Configuration.ORIENTATION_LANDSCAPE
|
||||
import android.content.res.Configuration.ORIENTATION_PORTRAIT
|
||||
import android.content.res.Resources
|
||||
import android.graphics.Point
|
||||
import android.util.DisplayMetrics
|
||||
import android.view.Display
|
||||
import android.view.Surface
|
||||
import android.view.Surface.ROTATION_0
|
||||
import android.view.WindowManager
|
||||
|
||||
/**
|
||||
* Created by Stardust on 2017/4/26.
|
||||
*/
|
||||
@Suppress("unused")
|
||||
class ScreenMetrics(private var designWidth: Int, private var designHeight: Int) {
|
||||
|
||||
constructor() : this(0, 0)
|
||||
@@ -21,79 +24,111 @@ class ScreenMetrics(private var designWidth: Int, private var designHeight: Int)
|
||||
|
||||
@JvmOverloads
|
||||
fun scaleX(x: Int, width: Int = designWidth) = when {
|
||||
width == 0 || activity == null -> x
|
||||
width == 0 || !isInitialized -> x
|
||||
else -> x * deviceScreenWidth / width
|
||||
}
|
||||
|
||||
@JvmOverloads
|
||||
fun scaleY(y: Int, height: Int = designHeight) = when {
|
||||
height == 0 || activity == null -> y
|
||||
height == 0 || !isInitialized -> y
|
||||
else -> y * deviceScreenHeight / height
|
||||
}
|
||||
|
||||
@JvmOverloads
|
||||
fun rescaleX(x: Int, width: Int = designWidth) = when {
|
||||
width == 0 || activity == null -> x
|
||||
width == 0 || !isInitialized -> x
|
||||
else -> x * width / deviceScreenWidth
|
||||
}
|
||||
|
||||
@JvmOverloads
|
||||
fun rescaleY(y: Int, height: Int = designHeight) = when {
|
||||
height == 0 || activity == null -> y
|
||||
height == 0 || !isInitialized -> y
|
||||
else -> y * height / deviceScreenHeight
|
||||
}
|
||||
|
||||
companion object {
|
||||
|
||||
private val metrics: DisplayMetrics = DisplayMetrics()
|
||||
private var mWindowManager: WindowManager? = null
|
||||
private var mResources: Resources? = null
|
||||
|
||||
private var activity: Activity? = null
|
||||
private var isInitialized = false
|
||||
|
||||
@Suppress("DEPRECATION")
|
||||
private val defaultDisplay: Display?
|
||||
get() = activity?.windowManager?.defaultDisplay
|
||||
|
||||
@JvmStatic
|
||||
val rotation: Int
|
||||
get() = defaultDisplay?.rotation ?: 0
|
||||
get() = mWindowManager?.defaultDisplay?.rotation ?: ROTATION_0
|
||||
|
||||
@JvmStatic
|
||||
val orientation: Int
|
||||
get() = mResources?.configuration?.orientation ?: ORIENTATION_PORTRAIT
|
||||
|
||||
@JvmStatic
|
||||
val isScreenPortrait: Boolean
|
||||
get() = orientation == ORIENTATION_PORTRAIT
|
||||
|
||||
@JvmStatic
|
||||
val isScreenLandscape: Boolean
|
||||
get() = orientation == ORIENTATION_LANDSCAPE
|
||||
|
||||
@JvmStatic
|
||||
@Suppress("DEPRECATION")
|
||||
val deviceScreenWidth: Int
|
||||
get() = toOriAwarePoint(metrics.widthPixels, metrics.heightPixels).x
|
||||
get() {
|
||||
mResources?.displayMetrics?.widthPixels?.takeIf { it > 0 }?.let { return it }
|
||||
|
||||
@JvmStatic
|
||||
val deviceScreenHeight: Int
|
||||
get() = toOriAwarePoint(metrics.widthPixels, metrics.heightPixels).y
|
||||
val metricsLegacy = DisplayMetrics()
|
||||
val display = mWindowManager?.defaultDisplay?.apply { getRealMetrics(metricsLegacy) }
|
||||
metricsLegacy.widthPixels.takeIf { it > 0 }?.let { return it }
|
||||
|
||||
@JvmStatic
|
||||
val deviceScreenDensity: Int
|
||||
get() = metrics.densityDpi
|
||||
display?.width?.takeIf { it > 0 }?.let { return it }
|
||||
|
||||
@JvmStatic
|
||||
fun initIfNeeded(activity: Activity) {
|
||||
this.activity ?: let {
|
||||
this.activity = activity
|
||||
@Suppress("DEPRECATION")
|
||||
defaultDisplay?.getRealMetrics(this.metrics)
|
||||
return 0
|
||||
}
|
||||
|
||||
@JvmStatic
|
||||
@Suppress("DEPRECATION")
|
||||
val deviceScreenHeight: Int
|
||||
get() {
|
||||
mResources?.displayMetrics?.heightPixels?.takeIf { it > 0 }?.let { return it }
|
||||
|
||||
val metricsLegacy = DisplayMetrics()
|
||||
val display = mWindowManager?.defaultDisplay?.apply { getRealMetrics(metricsLegacy) }
|
||||
metricsLegacy.heightPixels.takeIf { it > 0 }?.let { return it }
|
||||
|
||||
display?.height?.takeIf { it > 0 }?.let { return it }
|
||||
|
||||
return 0
|
||||
}
|
||||
|
||||
@JvmStatic
|
||||
@Suppress("DEPRECATION")
|
||||
val deviceScreenDensity: Int
|
||||
get() {
|
||||
val metricsLegacy = DisplayMetrics()
|
||||
mWindowManager?.defaultDisplay?.apply { getRealMetrics(metricsLegacy) }
|
||||
return metricsLegacy.densityDpi
|
||||
}
|
||||
|
||||
@JvmStatic
|
||||
fun init(activity: Activity) {
|
||||
mWindowManager = activity.windowManager
|
||||
mResources = activity.resources
|
||||
isInitialized = true
|
||||
}
|
||||
|
||||
@JvmStatic
|
||||
fun isScreenLandscape() = listOf(Surface.ROTATION_90, Surface.ROTATION_270).contains(rotation)
|
||||
|
||||
private fun toOriAwarePoint(a: Int, b: Int) = arrayOf(minOf(a, b), maxOf(a, b))
|
||||
.apply { if (isScreenLandscape()) reverse() }
|
||||
.apply { if (isScreenLandscape) reverse() }
|
||||
.let { Point(it[0], it[1]) }
|
||||
|
||||
@JvmStatic
|
||||
fun getOrientationAwareScreenWidth(orientation: Int) = when (orientation) {
|
||||
Configuration.ORIENTATION_LANDSCAPE -> deviceScreenHeight
|
||||
ORIENTATION_LANDSCAPE -> deviceScreenHeight
|
||||
else -> deviceScreenWidth
|
||||
}
|
||||
|
||||
@JvmStatic
|
||||
fun getOrientationAwareScreenHeight(orientation: Int) = when (orientation) {
|
||||
Configuration.ORIENTATION_LANDSCAPE -> deviceScreenWidth
|
||||
ORIENTATION_LANDSCAPE -> deviceScreenWidth
|
||||
else -> deviceScreenHeight
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
package org.autojs.autojs.runtime.api;
|
||||
|
||||
import android.content.Context;
|
||||
import android.os.Handler;
|
||||
import android.util.Log;
|
||||
import android.widget.Toast;
|
||||
|
||||
import org.autojs.autojs.runtime.ScriptRuntime;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
/**
|
||||
* Created by SuperMonster003 on Aug 3, 2023.
|
||||
*/
|
||||
public class ScriptToast {
|
||||
|
||||
private static final String TAG = ScriptToast.class.getSimpleName();
|
||||
private final Context mContext;
|
||||
private final ScriptRuntime mScriptRuntime;
|
||||
private final Handler mUiHandler;
|
||||
|
||||
private static final ConcurrentHashMap<Toast, ScriptRuntime> pool = new ConcurrentHashMap<>();
|
||||
|
||||
public ScriptToast(Context context, ScriptRuntime runtime) {
|
||||
mContext = context;
|
||||
mScriptRuntime = runtime;
|
||||
mUiHandler = mScriptRuntime.uiHandler;
|
||||
}
|
||||
|
||||
// @Caution by SuperMonster003 on Oct 11, 2022.
|
||||
// ! android.widget.ScriptToast.makeText() doesn't work well on Android API Level 28 (Android 9) [P].
|
||||
// ! There hasn't been a solution for this so far.
|
||||
// ! Tested devices:
|
||||
// ! 1. SONY XPERIA XZ1 Compact (G8441)
|
||||
// ! 2. Android Studio AVD (Android 9.0 x86)
|
||||
public void makeToast(String msg, boolean isLong, boolean isForcible) {
|
||||
synchronized (ScriptToast.class) {
|
||||
if (isForcible) {
|
||||
dismissAll();
|
||||
}
|
||||
Toast toast = Toast.makeText(mContext, msg, isLong ? Toast.LENGTH_LONG : Toast.LENGTH_SHORT);
|
||||
Log.d(TAG + " new toast", toast.toString());
|
||||
toast.show();
|
||||
Log.d(TAG + " before put", pool.toString());
|
||||
pool.put(toast, mScriptRuntime);
|
||||
Log.d(TAG + " after put", pool.toString());
|
||||
addCallback(toast);
|
||||
}
|
||||
}
|
||||
|
||||
private void addCallback(Toast toast) {
|
||||
// FIXME by SuperMonster003 on Aug 3, 2023.
|
||||
// ! A more graceful way is needed.
|
||||
// @Hint by SuperMonster003 on Aug 3, 2023.
|
||||
// ! It is proved that Toast.Callback for Android API Level 30+
|
||||
// ! was not a good replacement.
|
||||
mUiHandler.postDelayed(() -> dismiss(toast), getAccumulatedDuration());
|
||||
}
|
||||
|
||||
private long getAccumulatedDuration() {
|
||||
var sum = 200L;
|
||||
for (Map.Entry<Toast, ScriptRuntime> entry : pool.entrySet()) {
|
||||
Toast toast = entry.getKey();
|
||||
sum += toast.getDuration() == Toast.LENGTH_SHORT ? 2_000L : 3_500L;
|
||||
}
|
||||
return sum;
|
||||
}
|
||||
|
||||
private void dismiss(Toast aim) {
|
||||
Log.d(TAG + " before dismiss", pool.toString());
|
||||
for (Map.Entry<Toast, ScriptRuntime> entry : pool.entrySet()) {
|
||||
Toast toast = entry.getKey();
|
||||
ScriptRuntime scriptRuntime = entry.getValue();
|
||||
if (scriptRuntime == mScriptRuntime && toast == aim) {
|
||||
toast.cancel();
|
||||
pool.remove(toast);
|
||||
}
|
||||
}
|
||||
Log.d(TAG + " after dismiss", pool.toString());
|
||||
}
|
||||
|
||||
public void dismissAll() {
|
||||
Log.d(TAG + " before disAll", pool.toString());
|
||||
for (Map.Entry<Toast, ScriptRuntime> entry : pool.entrySet()) {
|
||||
Toast toast = entry.getKey();
|
||||
ScriptRuntime scriptRuntime = entry.getValue();
|
||||
if (scriptRuntime == mScriptRuntime) {
|
||||
toast.cancel();
|
||||
pool.remove(toast);
|
||||
}
|
||||
}
|
||||
Log.d(TAG + " after disAll", pool.toString());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -10,7 +10,6 @@ import androidx.annotation.NonNull;
|
||||
|
||||
import org.autojs.autojs.core.eventloop.EventEmitter;
|
||||
import org.autojs.autojs.core.looper.Loopers;
|
||||
import org.autojs.autojs.pref.Language;
|
||||
import org.autojs.autojs.runtime.ScriptBridges;
|
||||
import org.autojs.autojs.runtime.ScriptRuntime;
|
||||
import org.autojs.autojs.tool.MapBuilder;
|
||||
@@ -22,8 +21,10 @@ import java.util.Set;
|
||||
|
||||
/**
|
||||
* Created by Stardust on 2018/2/5.
|
||||
* Modified by SuperMonster003 as of Dec 5, 2021.
|
||||
* Modified by aiselp as of Jun 10, 2023.
|
||||
*/
|
||||
public class Sensors extends EventEmitter implements Loopers.LooperQuitHandler {
|
||||
public class Sensors extends EventEmitter {
|
||||
|
||||
public class SensorEventEmitter extends EventEmitter implements SensorEventListener {
|
||||
|
||||
@@ -83,6 +84,13 @@ public class Sensors extends EventEmitter implements Loopers.LooperQuitHandler {
|
||||
private final ScriptBridges mScriptBridges;
|
||||
private final SensorEventEmitter mNoOpSensorEventEmitter;
|
||||
private final ScriptRuntime mScriptRuntime;
|
||||
private final Loopers.AsyncTask mAsyncTask = new Loopers.AsyncTask("Sensors") {
|
||||
@Override
|
||||
public boolean onFinish(@NonNull Loopers loopers) {
|
||||
return !mSensorEventEmitters.isEmpty();
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
public Sensors(Context context, ScriptRuntime runtime) {
|
||||
super(runtime.bridges);
|
||||
@@ -90,7 +98,7 @@ public class Sensors extends EventEmitter implements Loopers.LooperQuitHandler {
|
||||
mScriptBridges = runtime.bridges;
|
||||
mNoOpSensorEventEmitter = new SensorEventEmitter(runtime.bridges);
|
||||
mScriptRuntime = runtime;
|
||||
runtime.loopers.addLooperQuitHandler(this);
|
||||
runtime.loopers.addAsyncTask(mAsyncTask);
|
||||
}
|
||||
|
||||
public SensorEventEmitter register(String sensorName) {
|
||||
@@ -122,13 +130,8 @@ public class Sensors extends EventEmitter implements Loopers.LooperQuitHandler {
|
||||
return emitter;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean shouldQuit() {
|
||||
return mSensorEventEmitters.isEmpty();
|
||||
}
|
||||
|
||||
public Sensor getSensor(String sensorName) {
|
||||
sensorName = sensorName.toUpperCase(Language.getPrefLanguage().getLocale());
|
||||
sensorName = sensorName.toUpperCase();
|
||||
Integer type = SENSORS.get(sensorName);
|
||||
type = type == null ? getSensorTypeByReflect(sensorName) : type;
|
||||
return type == null ? null : mSensorManager.getDefaultSensor(type);
|
||||
@@ -159,6 +162,6 @@ public class Sensors extends EventEmitter implements Loopers.LooperQuitHandler {
|
||||
}
|
||||
mSensorEventEmitters.clear();
|
||||
}
|
||||
mScriptRuntime.loopers.removeLooperQuitHandler(this);
|
||||
mScriptRuntime.loopers.removeAsyncTask(mAsyncTask);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package org.autojs.autojs.runtime.api;
|
||||
|
||||
import android.content.Context;
|
||||
|
||||
import org.autojs.autojs.util.RomUtils;
|
||||
|
||||
public class Services {
|
||||
|
||||
private final Context mContext;
|
||||
|
||||
public Services(Context context) {
|
||||
mContext = context;
|
||||
}
|
||||
|
||||
// TODO by SuperMonster003 on Aug 28, 2023.
|
||||
|
||||
/* services.a11y (a11y) */
|
||||
/* services.foregroundService */
|
||||
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package org.autojs.autojs.runtime.api;
|
||||
|
||||
import android.content.Context;
|
||||
|
||||
import org.autojs.autojs.util.RomUtils;
|
||||
|
||||
public class Settings {
|
||||
|
||||
private final Context mContext;
|
||||
|
||||
public Settings(Context context) {
|
||||
mContext = context;
|
||||
}
|
||||
|
||||
// TODO by SuperMonster003 on Aug 28, 2023.
|
||||
|
||||
/* settings.floatingButton */
|
||||
/* settings.clientMode */
|
||||
/* settings.serverMode */
|
||||
/* settings.autoNightMode */
|
||||
/* settings.nightMode */
|
||||
/* settings.themeColor */
|
||||
/* settings.language */
|
||||
/* settings.documentationSource */
|
||||
/* settings.isKeepScreenOnWhenInForeground */
|
||||
/* settings.isShowDocumentationLauncherIcon */
|
||||
/* settings.isShowHiddenFilesAndFolders */
|
||||
/* settings.workingDirectory */
|
||||
/* settings.forcibleRootCheck */
|
||||
/* ... ... */
|
||||
|
||||
}
|
||||
Loaded 100 of 164 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user