From 19dac12614b5f65a9d13fb474db07628fd3d18e6 Mon Sep 17 00:00:00 2001 From: hyb1996 <946994919@qq.com> Date: Fri, 4 Aug 2017 15:19:57 +0800 Subject: [PATCH] refactor(module autojs): package com.stardust.autojs.runtime.inputevent add: module engines --- .../assets/help/documentation/一般常用函数.md | 5 + .../documentation/事件与按键、触摸监听.md | 37 +- app/src/main/assets/js/functions.json | 1 + .../sample/事件与按键、触摸监听/Toast监听.js | 9 + .../sample/事件与按键、触摸监听/通知监听.js | 21 ++ .../sample/脚本引擎/停止所有正在运行的脚本.js | 1 + .../assets/sample/脚本引擎/运行录制文件.js | 14 + .../sample/脚本引擎/运行新的脚本任务.js | 6 + .../assets/sample/脚本引擎/运行脚本文件.js | 14 + .../stardust/scriptdroid/autojs/AutoJs.java | 3 + .../menu/content/RecordNavigatorContent.java | 26 +- .../stardust/scriptdroid/script/Scripts.java | 11 +- .../src/main/assets/javascript_engine_init.js | 2 +- autojs/src/main/assets/modules/__app__.js | 2 +- autojs/src/main/assets/modules/__engines__.js | 43 +++ .../autojs/execution/ExecutionConfig.java | 4 +- .../execution/RunnableScriptExecution.java | 2 +- .../execution/ScriptExecuteActivity.java | 2 +- .../autojs/runtime/ScriptRuntime.java | 13 + .../autojs/runtime/api/AbstractShell.java | 4 + .../stardust/autojs/runtime/api/AppUtils.java | 12 + .../stardust/autojs/runtime/api/Engines.java | 43 +++ .../stardust/autojs/runtime/api/Events.java | 12 +- .../inputevent/InputEventConverter.java | 136 ------- .../record/inputevent/InputEventObserver.java | 137 +++++++ .../record/inputevent/InputEventRecorder.java | 87 ++--- ...java => InputEventToAutoFileRecorder.java} | 17 +- .../inputevent/InputEventToJsConverter.java | 158 --------- ...=> InputEventToRootAutomatorRecorder.java} | 14 +- .../InputEventToSendEventConverter.java | 52 --- ...a => InputEventToSendEventJsRecorder.java} | 14 +- .../record/inputevent/KeyObserver.java | 335 ++++++++++++++++-- .../record/inputevent/TouchObserver.java | 102 +++--- .../record/inputevent/TouchRecorder.java | 57 ++- .../autojs/script/AutoFileSource.java | 4 + .../res/xml/accessibility_service_config.xml | 2 +- .../accessibility/NotificationListener.java | 64 +++- 37 files changed, 904 insertions(+), 562 deletions(-) create mode 100644 app/src/main/assets/sample/事件与按键、触摸监听/Toast监听.js create mode 100644 app/src/main/assets/sample/事件与按键、触摸监听/通知监听.js create mode 100644 app/src/main/assets/sample/脚本引擎/停止所有正在运行的脚本.js create mode 100644 app/src/main/assets/sample/脚本引擎/运行录制文件.js create mode 100644 app/src/main/assets/sample/脚本引擎/运行新的脚本任务.js create mode 100644 app/src/main/assets/sample/脚本引擎/运行脚本文件.js create mode 100644 autojs/src/main/assets/modules/__engines__.js create mode 100644 autojs/src/main/java/com/stardust/autojs/runtime/api/Engines.java delete mode 100644 autojs/src/main/java/com/stardust/autojs/runtime/record/inputevent/InputEventConverter.java create mode 100644 autojs/src/main/java/com/stardust/autojs/runtime/record/inputevent/InputEventObserver.java rename autojs/src/main/java/com/stardust/autojs/runtime/record/inputevent/{InputEventToAutoFileConverter.java => InputEventToAutoFileRecorder.java} (86%) delete mode 100644 autojs/src/main/java/com/stardust/autojs/runtime/record/inputevent/InputEventToJsConverter.java rename autojs/src/main/java/com/stardust/autojs/runtime/record/inputevent/{InputEventToRootAutomatorConverter.java => InputEventToRootAutomatorRecorder.java} (90%) delete mode 100644 autojs/src/main/java/com/stardust/autojs/runtime/record/inputevent/InputEventToSendEventConverter.java rename autojs/src/main/java/com/stardust/autojs/runtime/record/inputevent/{InputEventToSendEventJsConverter.java => InputEventToSendEventJsRecorder.java} (90%) diff --git a/app/src/main/assets/help/documentation/一般常用函数.md b/app/src/main/assets/help/documentation/一般常用函数.md index a1209639..4ab50a8c 100644 --- a/app/src/main/assets/help/documentation/一般常用函数.md +++ b/app/src/main/assets/help/documentation/一般常用函数.md @@ -32,6 +32,11 @@ launchApp("微信"); 获取应用的包名。例如getPackageName("QQ")为"com.tencent.mobileqq"。如果有相同名称的应用,只返回其中某一个的包名。如果不存在这个名称的应用,会返回空字符串。 +### getAppName(packageName) +* packageName \ 应用包名 + +返回对应包名的应用的名称。如果应用不存在,返回null。 + ### openAppSetting(packageName) * packageName \ 应用包名 diff --git a/app/src/main/assets/help/documentation/事件与按键、触摸监听.md b/app/src/main/assets/help/documentation/事件与按键、触摸监听.md index 57c868b1..6b42f383 100644 --- a/app/src/main/assets/help/documentation/事件与按键、触摸监听.md +++ b/app/src/main/assets/help/documentation/事件与按键、触摸监听.md @@ -104,7 +104,9 @@ events.loop(); 删除所有事件监听函数。 -### key事件 +### 事件: 'key' +* keyCode \ 键值 +* event \ 事件 当有按键被按下或弹起时会触发该事件。 ``` @@ -122,7 +124,9 @@ events.loop(); * KeyEvent.KEYCODE_VOLUME_UP 音量上键 * KeyEvent.KEYCODE_VOLUME_DOWN 音量下键 -### key_down事件 +### 事件: 'key_down' +* keyCode \ 键值 +* event \ 事件 当有按键被按下时会触发该事件。 ``` @@ -134,7 +138,9 @@ events.on("key_down", function(keyCode, event){ events.loop(); ``` -### key_up事件 +### 事件: 'key_up' +* keyCode \ 键值 +* event \ 事件 当有按键弹起时会触发该事件。 ``` @@ -148,27 +154,34 @@ events.loop(); ### obverseNotification() +开启通知(包括Toast)监听。 +``` +events.obverseNotification(); +events.onNotification(function(notification){ + log(notification.getText()); +}); +events.onToast(function(toast){ + log(toast.getText()); +}); +``` - - - -### toast事件 - - +### 事件: 'toast' +* toast \ + * getText() 获取Toast的文本内容 + * getPackageName() 获取发出Toast的应用包名 ### 事件: 'notification' -* notification \ 通知 +* notification \ 通知 ``` events.observeNotification(); events.on("notification", function(notification){ - log(notification. + log(notification); }); ``` - # EventEmitter ### EventEmitter.defaultMaxListeners diff --git a/app/src/main/assets/js/functions.json b/app/src/main/assets/js/functions.json index aeea2c54..7154b301 100644 --- a/app/src/main/assets/js/functions.json +++ b/app/src/main/assets/js/functions.json @@ -244,6 +244,7 @@ "emitter", "observeKey", "observeTouch", + "observeNotification", "onKeyDown", "onKeyUp", "onceKeyDown", diff --git a/app/src/main/assets/sample/事件与按键、触摸监听/Toast监听.js b/app/src/main/assets/sample/事件与按键、触摸监听/Toast监听.js new file mode 100644 index 00000000..f7c2be8d --- /dev/null +++ b/app/src/main/assets/sample/事件与按键、触摸监听/Toast监听.js @@ -0,0 +1,9 @@ +auto(); +events.observeNotification(); +events.onToast(function(toast){ + var pkg = toast.getPackageName(); + log("Toast内容: " + toast.getText() + + " 来自: " + getAppName(pkg) + + " 包名: " + pkg); +}); +toast("监听中,请在日志中查看记录的Toast及其内容"); \ No newline at end of file diff --git a/app/src/main/assets/sample/事件与按键、触摸监听/通知监听.js b/app/src/main/assets/sample/事件与按键、触摸监听/通知监听.js new file mode 100644 index 00000000..e087b4de --- /dev/null +++ b/app/src/main/assets/sample/事件与按键、触摸监听/通知监听.js @@ -0,0 +1,21 @@ +auto(); +events.observeNotification(); +events.onNotification(function(info, notification){ + printNotification(info, notification); +}); +toast("监听中,请在日志中查看记录的通知及其内容"); + +function printNotification(info, notification){ + log("应用包名: " + info.getPackageName()); + log("通知文本: " + info.getTexts()); + log("通知优先级: " + notification.priority); + log("通知目录: " + notification.category); + log("通知创建时间: " + new Date(notification.creationTime)); + log("通知时间: " + new Date(notification.when)); + log("通知数: " + notification.number); + log("通知摘要: " + notification.tickerText); + for(var i = 0; i < notification.actions.length; i++){ + var action = notification.actions[i]; + log("通知" + (i + 1) + ": " + action.title); + } +} \ No newline at end of file diff --git a/app/src/main/assets/sample/脚本引擎/停止所有正在运行的脚本.js b/app/src/main/assets/sample/脚本引擎/停止所有正在运行的脚本.js new file mode 100644 index 00000000..6a132133 --- /dev/null +++ b/app/src/main/assets/sample/脚本引擎/停止所有正在运行的脚本.js @@ -0,0 +1 @@ +engines.stopAllAndToast(); \ No newline at end of file diff --git a/app/src/main/assets/sample/脚本引擎/运行录制文件.js b/app/src/main/assets/sample/脚本引擎/运行录制文件.js new file mode 100644 index 00000000..d6d8a2f9 --- /dev/null +++ b/app/src/main/assets/sample/脚本引擎/运行录制文件.js @@ -0,0 +1,14 @@ + +var scriptsPath = "/sdcard/脚本/"; +if(!files.exists(scriptsPath)){ + scriptsPath = "/sdcard/Scripts/"; +} +var scriptFiles = files.listDir(scriptsPath, function(name){ + return name.endsWith(".auto"); +}); +var i = dialogs.singleChoice("请选择要运行的脚本", scriptFiles); +if(i < 0){ + exit(); +} +var path = files.join(scriptsPath, scriptFiles[i]); +engines.execAutoFile(path); \ No newline at end of file diff --git a/app/src/main/assets/sample/脚本引擎/运行新的脚本任务.js b/app/src/main/assets/sample/脚本引擎/运行新的脚本任务.js new file mode 100644 index 00000000..96d2a9b5 --- /dev/null +++ b/app/src/main/assets/sample/脚本引擎/运行新的脚本任务.js @@ -0,0 +1,6 @@ +var script = "toast('Hello, Auto.js');" + + "sleep(3000);" + + "toast('略略略');"; +var execution = engines.execScript(script); +sleep(1000); +execution.getEngine().forceStop(); \ No newline at end of file diff --git a/app/src/main/assets/sample/脚本引擎/运行脚本文件.js b/app/src/main/assets/sample/脚本引擎/运行脚本文件.js new file mode 100644 index 00000000..a7544056 --- /dev/null +++ b/app/src/main/assets/sample/脚本引擎/运行脚本文件.js @@ -0,0 +1,14 @@ + +var scriptsPath = "/sdcard/脚本/"; +if(!files.exists(scriptsPath)){ + scriptsPath = "/sdcard/Scripts/"; +} +var scriptFiles = files.listDir(scriptsPath, function(name){ + return name.endsWith(".js"); +}); +var i = dialogs.singleChoice("请选择要运行的脚本", scriptFiles); +if(i < 0){ + exit(); +} +var path = files.join(scriptsPath, scriptFiles[i]); +engines.execScriptFile(path); \ No newline at end of file diff --git a/app/src/main/java/com/stardust/scriptdroid/autojs/AutoJs.java b/app/src/main/java/com/stardust/scriptdroid/autojs/AutoJs.java index 7e7b8986..be8758f9 100644 --- a/app/src/main/java/com/stardust/scriptdroid/autojs/AutoJs.java +++ b/app/src/main/java/com/stardust/scriptdroid/autojs/AutoJs.java @@ -23,6 +23,7 @@ import com.stardust.autojs.runtime.api.AbstractShell; import com.stardust.autojs.runtime.api.AppUtils; import com.stardust.autojs.runtime.api.Console; import com.stardust.autojs.runtime.api.image.ScreenCaptureRequester; +import com.stardust.autojs.runtime.record.inputevent.InputEventObserver; import com.stardust.autojs.script.AutoFileSource; import com.stardust.autojs.script.JavaScriptSource; import com.stardust.scriptdroid.App; @@ -84,6 +85,7 @@ public class AutoJs { addAccessibilityServiceDelegates(); mScriptEngineService.registerGlobalScriptExecutionListener(new ScriptExecutionGlobalListener()); registerActivityLifecycleCallbacks(); + InputEventObserver.initGlobal(context); } private ScriptEngineService buildScriptEngineService() { @@ -107,6 +109,7 @@ public class AutoJs { .setAccessibilityBridge(new AccessibilityBridgeImpl()) .setUiHandler(mUiHandler) .setAppUtils(mAppUtils) + .setEngineService(mScriptEngineService) .setShellSupplier(new Supplier() { @Override public AbstractShell get() { diff --git a/app/src/main/java/com/stardust/scriptdroid/external/floatingwindow/menu/content/RecordNavigatorContent.java b/app/src/main/java/com/stardust/scriptdroid/external/floatingwindow/menu/content/RecordNavigatorContent.java index 84b73bc2..f717b099 100644 --- a/app/src/main/java/com/stardust/scriptdroid/external/floatingwindow/menu/content/RecordNavigatorContent.java +++ b/app/src/main/java/com/stardust/scriptdroid/external/floatingwindow/menu/content/RecordNavigatorContent.java @@ -12,6 +12,7 @@ import android.widget.Toast; import com.stardust.autojs.runtime.record.Recorder; import com.stardust.autojs.runtime.record.accessibility.AccessibilityActionRecorder; +import com.stardust.autojs.runtime.record.inputevent.InputEventObserver; import com.stardust.autojs.runtime.record.inputevent.KeyObserver; import com.stardust.autojs.runtime.record.inputevent.TouchRecorder; import com.stardust.scriptdroid.App; @@ -61,9 +62,11 @@ public class RecordNavigatorContent implements NavigatorContent, Recorder.OnStat private Recorder mRecorder; + private TouchRecorder mTouchRecorder; private Context mContext; private boolean mDiscard = false; private KeyObserver mKeyObserver; + private InputEventObserver mInputEventObserver = InputEventObserver.getGlobal(); private OnKeyListener mVolumeKeyListener = new OnKeyListener() { @Override public void onKeyEvent(int keyCode, KeyEvent event) { @@ -72,7 +75,7 @@ public class RecordNavigatorContent implements NavigatorContent, Recorder.OnStat && Pref.isRecordVolumeControlEnable()) { if (mRecorder == null) { startRecord(); - } else if (alreadyStartedRecord()) { + } else if (alreadyStartRecord()) { stopRecord(); } } @@ -85,9 +88,10 @@ public class RecordNavigatorContent implements NavigatorContent, Recorder.OnStat ButterKnife.bind(this, mView); HoverMenuService.getEventBus().register(this); AccessibilityService.getStickOnKeyObserver().addListener(mVolumeKeyListener); + mTouchRecorder = TouchRecorder.getGlobal(context); if (Pref.hasRecordTrigger()) { - mKeyObserver = new KeyObserver(mContext); - mKeyObserver.startListening(); + mKeyObserver = new KeyObserver(); + mInputEventObserver.addListener(mKeyObserver); mKeyObserver.setKeyListener(this); } } @@ -148,7 +152,12 @@ public class RecordNavigatorContent implements NavigatorContent, Recorder.OnStat private void startRecord() { mDiscard = false; - mRecorder = mRecordedByRootSwitch.isChecked() ? new TouchRecorder(mContext) : AutoJs.getInstance().getAccessibilityActionRecorder(); + if (mRecordedByRootSwitch.isChecked()) { + mTouchRecorder.reset(); + mRecorder = mTouchRecorder; + } else { + mRecorder = AutoJs.getInstance().getAccessibilityActionRecorder(); + } mRecorder.setOnStateChangedListener(this); mRecorder.start(); setState(Recorder.STATE_RECORDING); @@ -187,9 +196,8 @@ public class RecordNavigatorContent implements NavigatorContent, Recorder.OnStat public void onMenuExit() { HoverMenuService.getEventBus().unregister(this); AccessibilityService.getStickOnKeyObserver().addListener(mVolumeKeyListener); - if (mKeyObserver != null) { - mKeyObserver.stopListening(); - } + mInputEventObserver.recycle(); + mInputEventObserver.removeListener(mKeyObserver); } @Subscribe @@ -228,7 +236,7 @@ public class RecordNavigatorContent implements NavigatorContent, Recorder.OnStat @Override public void onKeyDown(String keyName) { if (keyName.equals(Pref.getStopRecordTrigger())) { - if (alreadyStartedRecord()) + if (alreadyStartRecord()) stopRecord(); } else if (keyName.equals(Pref.getStartRecordTrigger())) { if (mRecorder == null) @@ -236,7 +244,7 @@ public class RecordNavigatorContent implements NavigatorContent, Recorder.OnStat } } - private boolean alreadyStartedRecord() { + private boolean alreadyStartRecord() { return mRecorder != null && mRecorder.getState() == Recorder.STATE_RECORDING && mRecorder.getState() == Recorder.STATE_PAUSED; } diff --git a/app/src/main/java/com/stardust/scriptdroid/script/Scripts.java b/app/src/main/java/com/stardust/scriptdroid/script/Scripts.java index f71c789f..66208ed5 100644 --- a/app/src/main/java/com/stardust/scriptdroid/script/Scripts.java +++ b/app/src/main/java/com/stardust/scriptdroid/script/Scripts.java @@ -9,7 +9,6 @@ import com.stardust.autojs.execution.ScriptExecution; import com.stardust.autojs.execution.ScriptExecutionListener; import com.stardust.autojs.execution.SimpleScriptExecutionListener; import com.stardust.autojs.runtime.ScriptInterruptedException; -import com.stardust.autojs.script.JavaScriptFileSource; import com.stardust.autojs.script.ScriptSource; import com.stardust.autojs.script.StringScriptSource; import com.stardust.scriptdroid.App; @@ -85,17 +84,17 @@ public class Scripts { public static ScriptExecution run(ScriptSource source, String directoryPath) { return AutoJs.getInstance().getScriptEngineService().execute(source, new ExecutionConfig() - .requirePath(directoryPath, StorageScriptProvider.DEFAULT_DIRECTORY_PATH)); + .path(directoryPath, StorageScriptProvider.DEFAULT_DIRECTORY_PATH)); } public static ScriptExecution run(ScriptSource source) { return AutoJs.getInstance().getScriptEngineService().execute(source, new ExecutionConfig() - .requirePath(StorageScriptProvider.DEFAULT_DIRECTORY_PATH)); + .path(StorageScriptProvider.DEFAULT_DIRECTORY_PATH)); } public static ScriptExecution runWithBroadcastSender(ScriptSource scriptSource, String directoryPath) { return AutoJs.getInstance().getScriptEngineService().execute(scriptSource, BROADCAST_SENDER_SCRIPT_EXECUTION_LISTENER, - new ExecutionConfig().requirePath(directoryPath, StorageScriptProvider.DEFAULT_DIRECTORY_PATH)); + new ExecutionConfig().path(directoryPath, StorageScriptProvider.DEFAULT_DIRECTORY_PATH)); } public static ScriptExecution run(Context context, Sample file) { @@ -105,14 +104,14 @@ public class Scripts { public static ScriptExecution runWithBroadcastSender(ScriptSource source) { return AutoJs.getInstance().getScriptEngineService().execute(source, BROADCAST_SENDER_SCRIPT_EXECUTION_LISTENER, - new ExecutionConfig().requirePath(StorageScriptProvider.DEFAULT_DIRECTORY_PATH)); + new ExecutionConfig().path(StorageScriptProvider.DEFAULT_DIRECTORY_PATH)); } public static ScriptExecution runRepeatedly(ScriptFile scriptFile, int loopTimes, long delay, long interval) { ScriptSource source = scriptFile.toSource(); String directoryPath = scriptFile.getParent(); return AutoJs.getInstance().getScriptEngineService().execute(source, new ExecutionConfig() - .requirePath(directoryPath, StorageScriptProvider.DEFAULT_DIRECTORY_PATH) + .path(directoryPath, StorageScriptProvider.DEFAULT_DIRECTORY_PATH) .loop(delay, loopTimes, interval)); } } diff --git a/autojs/src/main/assets/javascript_engine_init.js b/autojs/src/main/assets/javascript_engine_init.js index 2f1c8d5d..d73d5b02 100644 --- a/autojs/src/main/assets/javascript_engine_init.js +++ b/autojs/src/main/assets/javascript_engine_init.js @@ -37,7 +37,7 @@ require("__general__")(__runtime__, this); (function(scope){ - var modules = ['app', 'automator', 'console', 'dialogs', 'io', 'selector', 'shell', 'web', 'ui', "images", "timers", "events"]; + var modules = ['app', 'automator', 'console', 'dialogs', 'io', 'selector', 'shell', 'web', 'ui', "images", "timers", "events", "engines"]; var len = modules.length; for(var i = 0; i < len; i++) { var m = modules[i]; diff --git a/autojs/src/main/assets/modules/__app__.js b/autojs/src/main/assets/modules/__app__.js index d0de5e09..ef0091d8 100644 --- a/autojs/src/main/assets/modules/__app__.js +++ b/autojs/src/main/assets/modules/__app__.js @@ -40,7 +40,7 @@ module.exports = function(__runtime__, scope){ app.launch = app.launchPackage; - scope.__asGlobal__(app, ['launchPackage', 'launch', 'launchApp', 'getPackageName', 'openAppSetting']); + scope.__asGlobal__(app, ['launchPackage', 'launch', 'launchApp', 'getPackageName', 'getAppName', 'openAppSetting']); return app; } diff --git a/autojs/src/main/assets/modules/__engines__.js b/autojs/src/main/assets/modules/__engines__.js new file mode 100644 index 00000000..cd1d532e --- /dev/null +++ b/autojs/src/main/assets/modules/__engines__.js @@ -0,0 +1,43 @@ + +module.exports = function(__runtime__, scope){ + var rtEngines = __runtime__.engines; + + var engines = {}; + + engines.execScript = function(name, script, config){ + config = fillConfig(config); + return rtEngines.execScript(name, script, config); + } + + engines.execScriptFile = function(path, config){ + config = fillConfig(config); + return rtEngines.execScriptFile(path, config); + } + + engines.execAutoFile = function(path, config){ + config = fillConfig(config); + return rtEngines.execAutoFile(path, config); + } + + engines.stopAll = rtEngines.stopAll.bind(rtEngines); + engines.stopAllAndToast = rtEngines.stopAllAndToast.bind(rtEngines); + + function fillConfig(c){ + var config = new com.stardust.autojs.execution.ExecutionConfig(); + c = c || {}; + if(c.path){ + if(typeof(c.path) == "string"){ + config.path([c.path]); + }else{ + config.path(c.path); + } + } + c.delay = c.delay || 0; + c.interval = c.interval || 0; + c.loopTimes = c.loopTimes || 1; + config.loop(c.delay, c.loopTimes, c.interval); + return config; + } + + return engines; +} \ No newline at end of file diff --git a/autojs/src/main/java/com/stardust/autojs/execution/ExecutionConfig.java b/autojs/src/main/java/com/stardust/autojs/execution/ExecutionConfig.java index 9990e839..251d97f3 100644 --- a/autojs/src/main/java/com/stardust/autojs/execution/ExecutionConfig.java +++ b/autojs/src/main/java/com/stardust/autojs/execution/ExecutionConfig.java @@ -24,12 +24,12 @@ public class ExecutionConfig implements Serializable { return this; } - public ExecutionConfig requirePath(String... requirePath) { + public ExecutionConfig path(String... requirePath) { mRequirePath = requirePath; return this; } - public String[] getExecutePath() { + public String[] getPath() { return mRequirePath; } diff --git a/autojs/src/main/java/com/stardust/autojs/execution/RunnableScriptExecution.java b/autojs/src/main/java/com/stardust/autojs/execution/RunnableScriptExecution.java index 6070297f..379685d2 100644 --- a/autojs/src/main/java/com/stardust/autojs/execution/RunnableScriptExecution.java +++ b/autojs/src/main/java/com/stardust/autojs/execution/RunnableScriptExecution.java @@ -47,7 +47,7 @@ public class RunnableScriptExecution extends ScriptExecution.AbstractScriptExecu } private void prepare(ScriptEngine engine) { - engine.setTag(ScriptEngine.TAG_PATH, getConfig().getExecutePath()); + engine.setTag(ScriptEngine.TAG_PATH, getConfig().getPath()); engine.init(); } diff --git a/autojs/src/main/java/com/stardust/autojs/execution/ScriptExecuteActivity.java b/autojs/src/main/java/com/stardust/autojs/execution/ScriptExecuteActivity.java index 7b7def70..d1d79540 100644 --- a/autojs/src/main/java/com/stardust/autojs/execution/ScriptExecuteActivity.java +++ b/autojs/src/main/java/com/stardust/autojs/execution/ScriptExecuteActivity.java @@ -68,7 +68,7 @@ public class ScriptExecuteActivity extends AppCompatActivity { private void prepare() { mScriptEngine.put("activity", this); - mScriptEngine.setTag(ScriptEngine.TAG_PATH, mScriptExecution.getConfig().getExecutePath()); + mScriptEngine.setTag(ScriptEngine.TAG_PATH, mScriptExecution.getConfig().getPath()); mScriptEngine.init(); } diff --git a/autojs/src/main/java/com/stardust/autojs/runtime/ScriptRuntime.java b/autojs/src/main/java/com/stardust/autojs/runtime/ScriptRuntime.java index dd0d3ec3..36573d34 100644 --- a/autojs/src/main/java/com/stardust/autojs/runtime/ScriptRuntime.java +++ b/autojs/src/main/java/com/stardust/autojs/runtime/ScriptRuntime.java @@ -5,11 +5,13 @@ import android.os.Build; import android.os.Looper; import com.stardust.autojs.R; +import com.stardust.autojs.ScriptEngineService; import com.stardust.autojs.engine.ScriptEngine; import com.stardust.autojs.rhino.AndroidClassLoader; import com.stardust.autojs.runtime.api.AbstractShell; import com.stardust.autojs.runtime.api.AppUtils; import com.stardust.autojs.runtime.api.Console; +import com.stardust.autojs.runtime.api.Engines; import com.stardust.autojs.runtime.api.Events; import com.stardust.autojs.runtime.api.Loopers; import com.stardust.autojs.runtime.api.ScriptBridges; @@ -55,6 +57,7 @@ public class ScriptRuntime { private Supplier mShellSupplier; private ScreenCaptureRequester mScreenCaptureRequester; private AppUtils mAppUtils; + private ScriptEngineService mEngineService; public Builder() { @@ -90,6 +93,12 @@ public class ScriptRuntime { return this; } + public Builder setEngineService(ScriptEngineService service) { + mEngineService = service; + return this; + } + + public ScriptRuntime build() { return new ScriptRuntime(this); } @@ -130,6 +139,9 @@ public class ScriptRuntime { @ScriptVariable public final AccessibilityBridge accessibilityBridge; + @ScriptVariable + public final Engines engines; + private Images images; private static WeakReference applicationContext; @@ -154,6 +166,7 @@ public class ScriptRuntime { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { images = new Images(context, this, builder.mScreenCaptureRequester); } + engines = new Engines(builder.mEngineService); dialogs = new Dialogs(app, mUiHandler); } diff --git a/autojs/src/main/java/com/stardust/autojs/runtime/api/AbstractShell.java b/autojs/src/main/java/com/stardust/autojs/runtime/api/AbstractShell.java index 613bfe18..4c985fc2 100644 --- a/autojs/src/main/java/com/stardust/autojs/runtime/api/AbstractShell.java +++ b/autojs/src/main/java/com/stardust/autojs/runtime/api/AbstractShell.java @@ -102,6 +102,8 @@ public abstract class AbstractShell { } private int scaleX(int x) { + if (mScreenMetrics == null) + return x; return mScreenMetrics.scaleX(x); } @@ -110,6 +112,8 @@ public abstract class AbstractShell { } private int scaleY(int y) { + if (mScreenMetrics == null) + return y; return mScreenMetrics.scaleY(y); } diff --git a/autojs/src/main/java/com/stardust/autojs/runtime/api/AppUtils.java b/autojs/src/main/java/com/stardust/autojs/runtime/api/AppUtils.java index 89f2907e..8c816549 100644 --- a/autojs/src/main/java/com/stardust/autojs/runtime/api/AppUtils.java +++ b/autojs/src/main/java/com/stardust/autojs/runtime/api/AppUtils.java @@ -62,6 +62,18 @@ public class AppUtils { return null; } + @ScriptInterface + public String getAppName(String packageName) { + PackageManager packageManager = mContext.getPackageManager(); + try { + ApplicationInfo applicationInfo = packageManager.getApplicationInfo(packageName, 0); + CharSequence appName = packageManager.getApplicationLabel(applicationInfo); + return appName == null ? null : appName.toString(); + } catch (PackageManager.NameNotFoundException e) { + return null; + } + } + @ScriptInterface public boolean openAppSetting(String packageName) { return IntentUtil.goToAppDetailSettings(mContext, packageName); diff --git a/autojs/src/main/java/com/stardust/autojs/runtime/api/Engines.java b/autojs/src/main/java/com/stardust/autojs/runtime/api/Engines.java new file mode 100644 index 00000000..8e74c45f --- /dev/null +++ b/autojs/src/main/java/com/stardust/autojs/runtime/api/Engines.java @@ -0,0 +1,43 @@ +package com.stardust.autojs.runtime.api; + +import com.stardust.autojs.ScriptEngineService; +import com.stardust.autojs.execution.ExecutionConfig; +import com.stardust.autojs.execution.ScriptExecution; +import com.stardust.autojs.script.AutoFileSource; +import com.stardust.autojs.script.JavaScriptFileSource; +import com.stardust.autojs.script.StringScriptSource; + +/** + * Created by Stardust on 2017/8/4. + */ + +public class Engines { + + private ScriptEngineService mEngineService; + + public Engines(ScriptEngineService engineService) { + mEngineService = engineService; + } + + public ScriptExecution execScript(String name, String script, ExecutionConfig config) { + return mEngineService.execute(new StringScriptSource(name, script), config); + } + + public ScriptExecution execScriptFile(String path, ExecutionConfig config) { + return mEngineService.execute(new JavaScriptFileSource(path), config); + } + + public ScriptExecution execAutoFile(String path, ExecutionConfig config) { + return mEngineService.execute(new AutoFileSource(path), config); + } + + public int stopAll() { + return mEngineService.stopAll(); + } + + public void stopAllAndToast() { + mEngineService.stopAllAndToast(); + } + + +} diff --git a/autojs/src/main/java/com/stardust/autojs/runtime/api/Events.java b/autojs/src/main/java/com/stardust/autojs/runtime/api/Events.java index b88cc342..780f3ec3 100644 --- a/autojs/src/main/java/com/stardust/autojs/runtime/api/Events.java +++ b/autojs/src/main/java/com/stardust/autojs/runtime/api/Events.java @@ -9,6 +9,7 @@ import android.view.accessibility.AccessibilityEvent; import com.stardust.autojs.runtime.AccessibilityBridge; import com.stardust.autojs.runtime.ScriptException; +import com.stardust.autojs.runtime.record.inputevent.InputEventObserver; import com.stardust.autojs.runtime.record.inputevent.TouchObserver; import com.stardust.view.accessibility.AccessibilityService; import com.stardust.view.accessibility.NotificationListener; @@ -68,7 +69,7 @@ public class Events extends EventEmitter implements OnKeyListener, TouchObserver return; ensureHandler(); mLoopers.waitWhenIdle(true); - mTouchObserver = new TouchObserver(mContext); + mTouchObserver = new TouchObserver(InputEventObserver.getGlobal()); mTouchObserver.setOnTouchEventListener(this); mTouchObserver.observe(); } @@ -126,6 +127,9 @@ public class Events extends EventEmitter implements OnKeyListener, TouchObserver if (mListeningNotification) return; mListeningNotification = true; + ensureHandler(); + mLoopers.waitWhenIdle(true); + mAccessibilityBridge.ensureServiceEnabled(); mAccessibilityBridge.getNotificationObserver() .addListener(this); } @@ -192,11 +196,11 @@ public class Events extends EventEmitter implements OnKeyListener, TouchObserver @Override - public void onNotification(final AccessibilityEvent event, final String[] notification) { + public void onNotification(final AccessibilityEvent event, final NotificationInfo notification) { mHandler.post(new Runnable() { @Override public void run() { - emit("toast", new Object[]{notification}); + emit("toast", notification); } }); } @@ -206,7 +210,7 @@ public class Events extends EventEmitter implements OnKeyListener, TouchObserver mHandler.post(new Runnable() { @Override public void run() { - emit("notification", notification); + emit("notification", NotificationInfo.fromEvent(event), notification); } }); diff --git a/autojs/src/main/java/com/stardust/autojs/runtime/record/inputevent/InputEventConverter.java b/autojs/src/main/java/com/stardust/autojs/runtime/record/inputevent/InputEventConverter.java deleted file mode 100644 index 0facfcb7..00000000 --- a/autojs/src/main/java/com/stardust/autojs/runtime/record/inputevent/InputEventConverter.java +++ /dev/null @@ -1,136 +0,0 @@ -package com.stardust.autojs.runtime.record.inputevent; - -import android.support.annotation.NonNull; -import android.text.TextUtils; -import android.widget.Toast; - -import com.stardust.autojs.runtime.record.Recorder; - -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -/** - * Created by Stardust on 2017/3/7. - */ - -public abstract class InputEventConverter { - - static class Event { - - static final Pattern PATTERN = Pattern.compile("^\\[([^\\]]*)\\]\\s+([^:]*):\\s+([^\\s]*)\\s+([^\\s]*)\\s+([^\\s]*)\\s*$"); - - static Event parseEvent(String eventStr) { - Matcher matcher = Event.PATTERN.matcher(eventStr); - if (!matcher.matches()) { - throw new EventFormatException(eventStr); - } - double time; - try { - time = Double.parseDouble(matcher.group(1)); - } catch (NumberFormatException e) { - throw new EventFormatException(eventStr, e); - } - return new Event(time, matcher.group(2), matcher.group(3), matcher.group(4), matcher.group(5)); - } - - - double time; - String device; - String type; - String code; - String value; - - public Event(double time, String device, String type, String code, String value) { - this.time = time; - this.device = device; - this.type = type; - this.code = code; - this.value = value; - } - - - @Override - public String toString() { - return "Event{" + - "time=" + time + - ", device='" + device + '\'' + - ", type='" + type + '\'' + - ", code='" + code + '\'' + - ", value='" + value + '\'' + - '}'; - } - } - - - private final static Pattern LAST_INT_PATTERN = Pattern.compile("[^0-9]+([0-9]+)$"); - - - protected boolean mConverting = false; - private int mState = Recorder.STATE_NOT_START; - - public void convertEventIfFormatCorrect(String eventStr) { - if (!mConverting) - return; - if (TextUtils.isEmpty(eventStr) || !eventStr.startsWith("[")) - return; - Event event = parseEventOrNull(eventStr); - if (event != null) { - convertEvent(event); - } - } - - public abstract void convertEvent(@NonNull Event event); - - public String getGetEventCommand() { - return "getevent -t -l"; - } - - - public void start() { - mConverting = true; - mState = Recorder.STATE_RECORDING; - } - - public void resume() { - mConverting = true; - mState = Recorder.STATE_RECORDING; - } - - public void pause() { - mConverting = false; - mState = Recorder.STATE_PAUSED; - } - - public void stop() { - mConverting = false; - mState = Recorder.STATE_STOPPED; - } - - public abstract String getCode(); - - private boolean mFirstEventFormatError = true; - - public Event parseEventOrNull(String eventStr) { - try { - return Event.parseEvent(eventStr); - } catch (EventFormatException e) { - e.printStackTrace(); - if (mFirstEventFormatError) { - mFirstEventFormatError = false; - } - return null; - } - - } - - public static int parseDeviceNumber(String device) { - Matcher matcher = LAST_INT_PATTERN.matcher(device); - if (matcher.find()) { - String someNumberStr = matcher.group(1); - return Integer.parseInt(someNumberStr); - } - return -1; - } - - -} diff --git a/autojs/src/main/java/com/stardust/autojs/runtime/record/inputevent/InputEventObserver.java b/autojs/src/main/java/com/stardust/autojs/runtime/record/inputevent/InputEventObserver.java new file mode 100644 index 00000000..daca2e32 --- /dev/null +++ b/autojs/src/main/java/com/stardust/autojs/runtime/record/inputevent/InputEventObserver.java @@ -0,0 +1,137 @@ +package com.stardust.autojs.runtime.record.inputevent; + +import android.content.Context; +import android.support.annotation.NonNull; +import android.text.TextUtils; + +import com.stardust.autojs.runtime.api.Shell; + +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * Created by Stardust on 2017/8/4. + */ + +public class InputEventObserver { + + public static class InputEvent { + static final Pattern PATTERN = Pattern.compile("^\\[([^\\]]*)\\]\\s+([^:]*):\\s+([^\\s]*)\\s+([^\\s]*)\\s+([^\\s]*)\\s*$"); + + static InputEvent parse(String eventStr) { + Matcher matcher = PATTERN.matcher(eventStr); + if (!matcher.matches()) { + throw new EventFormatException(eventStr); + } + double time; + try { + time = Double.parseDouble(matcher.group(1)); + } catch (NumberFormatException e) { + throw new EventFormatException(eventStr, e); + } + return new InputEvent(time, matcher.group(2), matcher.group(3), matcher.group(4), matcher.group(5)); + } + + + double time; + String device; + String type; + String code; + String value; + + public InputEvent(double time, String device, String type, String code, String value) { + this.time = time; + this.device = device; + this.type = type; + this.code = code; + this.value = value; + } + + + @Override + public String toString() { + return "Event{" + + "time=" + time + + ", device='" + device + '\'' + + ", type='" + type + '\'' + + ", code='" + code + '\'' + + ", value='" + value + '\'' + + '}'; + } + } + + public interface InputEventListener { + void onInputEvent(@NonNull InputEvent e); + } + + private static InputEventObserver sGlobal; + private CopyOnWriteArrayList mInputEventListeners = new CopyOnWriteArrayList<>(); + private Context mContext; + private Shell mShell; + + public InputEventObserver(Context context) { + mContext = context; + } + + public static InputEventObserver getGlobal() { + return sGlobal; + } + + public static void initGlobal(Context context) { + sGlobal = new InputEventObserver(context); + sGlobal.observe(); + } + + public void observe() { + if (mShell != null) + throw new IllegalStateException("observe() should be called only once"); + mShell = new Shell(mContext, true); + mShell.setCallback(new Shell.SimpleCallback() { + @Override + public void onNewLine(String str) { + if (mShell.isInitialized()) { + onInputEvent(str); + } + } + + @Override + public void onInitialized() { + mShell.exec("getevent -t"); + } + + }); + } + + public void onInputEvent(String eventStr) { + if (TextUtils.isEmpty(eventStr) || !eventStr.startsWith("[")) + return; + try { + InputEvent event = InputEvent.parse(eventStr); + dispatchInputEvent(event); + } catch (Exception ignored) { + + } + } + + private void dispatchInputEvent(InputEvent event) { + for (InputEventListener listener : mInputEventListeners) { + listener.onInputEvent(event); + } + } + + public void addListener(InputEventListener listener) { + mInputEventListeners.add(listener); + } + + public boolean removeListener(InputEventListener listener) { + return mInputEventListeners.remove(listener); + } + + + public void recycle() { + mShell.exit(); + } + + +} diff --git a/autojs/src/main/java/com/stardust/autojs/runtime/record/inputevent/InputEventRecorder.java b/autojs/src/main/java/com/stardust/autojs/runtime/record/inputevent/InputEventRecorder.java index 8a0c823b..b4edb591 100644 --- a/autojs/src/main/java/com/stardust/autojs/runtime/record/inputevent/InputEventRecorder.java +++ b/autojs/src/main/java/com/stardust/autojs/runtime/record/inputevent/InputEventRecorder.java @@ -1,79 +1,60 @@ package com.stardust.autojs.runtime.record.inputevent; -import android.content.Context; +import android.support.annotation.NonNull; +import android.util.Log; -import com.stardust.autojs.runtime.api.Shell; import com.stardust.autojs.runtime.record.Recorder; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + /** - * Created by Stardust on 2017/3/6. + * Created by Stardust on 2017/3/7. */ -public class InputEventRecorder extends Recorder.AbstractRecorder { - - private static final String TAG = "InputEventRecorder"; - private String mGetEventCommand; - private Shell mShell; - protected InputEventConverter mInputEventConverter; - private Context mContext; +public abstract class InputEventRecorder extends Recorder.AbstractRecorder implements InputEventObserver.InputEventListener { - protected InputEventRecorder(Context context, InputEventConverter inputEventConverter) { - mGetEventCommand = inputEventConverter.getGetEventCommand(); - mInputEventConverter = inputEventConverter; - mContext = context; - } + private final static Pattern LAST_INT_PATTERN = Pattern.compile("[^0-9]+([0-9]+)$"); - public void listen() { - mShell = new Shell(mContext, true); - mShell.setCallback(new Shell.SimpleCallback() { - @Override - public void onNewLine(String str) { - if (mShell.isInitialized()) { - convertEvent(str); - } - } - @Override - public void onInitialized() { - mShell.exec(mGetEventCommand); - } + protected boolean mRecording = false; - @Override - public void onInterrupted(InterruptedException e) { - stop(); - } - }); - } - - @Override protected void startImpl() { - mInputEventConverter.start(); + mRecording = true; } - @Override - protected void pauseImpl() { - mInputEventConverter.pause(); - } - - @Override protected void resumeImpl() { - mInputEventConverter.resume(); + mRecording = true; + } + + protected void pauseImpl() { + mRecording = false; } - @Override protected void stopImpl() { - mShell.exit(); - mInputEventConverter.stop(); + mRecording = false; } + public abstract String getCode(); + + static int parseDeviceNumber(String device) { + Matcher matcher = LAST_INT_PATTERN.matcher(device); + if (matcher.find()) { + String someNumberStr = matcher.group(1); + return Integer.parseInt(someNumberStr); + } + return -1; + } + + @Override - public String getCode() { - return mInputEventConverter.getCode(); - } - - protected void convertEvent(String eventStr) { - mInputEventConverter.convertEventIfFormatCorrect(eventStr); + public void onInputEvent(@NonNull InputEventObserver.InputEvent e) { + if (!mRecording) { + return; + } + recordInputEvent(e); } + protected abstract void recordInputEvent(InputEventObserver.InputEvent e); } diff --git a/autojs/src/main/java/com/stardust/autojs/runtime/record/inputevent/InputEventToAutoFileConverter.java b/autojs/src/main/java/com/stardust/autojs/runtime/record/inputevent/InputEventToAutoFileRecorder.java similarity index 86% rename from autojs/src/main/java/com/stardust/autojs/runtime/record/inputevent/InputEventToAutoFileConverter.java rename to autojs/src/main/java/com/stardust/autojs/runtime/record/inputevent/InputEventToAutoFileRecorder.java index b388c4ee..73fca5c9 100644 --- a/autojs/src/main/java/com/stardust/autojs/runtime/record/inputevent/InputEventToAutoFileConverter.java +++ b/autojs/src/main/java/com/stardust/autojs/runtime/record/inputevent/InputEventToAutoFileRecorder.java @@ -2,6 +2,7 @@ package com.stardust.autojs.runtime.record.inputevent; import android.content.Context; import android.support.annotation.NonNull; +import android.util.Log; import com.stardust.autojs.engine.RootAutomatorEngine; import com.stardust.autojs.runtime.api.RootAutomator; @@ -19,14 +20,15 @@ import java.util.Date; * Created by Stardust on 2017/8/2. */ -public class InputEventToAutoFileConverter extends InputEventConverter { +public class InputEventToAutoFileRecorder extends InputEventRecorder { + private static final String LOG_TAG = "InputEventToAutoFileRec"; private double mLastEventTime; private int mTouchDevice = -1; private DataOutputStream mDataOutputStream; private File mTmpFile; - public InputEventToAutoFileConverter(Context context) { + public InputEventToAutoFileRecorder(Context context) { try { mTmpFile = new File(context.getCacheDir(), SimpleDateFormat.getDateTimeInstance().format(new Date()) + ".auto"); mTmpFile.deleteOnExit(); @@ -49,16 +51,17 @@ public class InputEventToAutoFileConverter extends InputEventConverter { @Override - public void convertEvent(@NonNull InputEventConverter.Event event) { + public void recordInputEvent(@NonNull InputEventObserver.InputEvent event) { try { convertEventOrThrow(event); + Log.d(LOG_TAG, "recordInputEvent: " + event); } catch (IOException e) { e.printStackTrace(); } } - private void convertEventOrThrow(Event event) throws IOException { + private void convertEventOrThrow(InputEventObserver.InputEvent event) throws IOException { if (mLastEventTime == 0) { mLastEventTime = event.time; } else if (event.time - mLastEventTime > 0.001) { @@ -86,12 +89,6 @@ public class InputEventToAutoFileConverter extends InputEventConverter { mDataOutputStream.writeInt(value); } - - @Override - public String getGetEventCommand() { - return "getevent -t"; - } - public String getCode() { return mTmpFile.getAbsolutePath(); } diff --git a/autojs/src/main/java/com/stardust/autojs/runtime/record/inputevent/InputEventToJsConverter.java b/autojs/src/main/java/com/stardust/autojs/runtime/record/inputevent/InputEventToJsConverter.java deleted file mode 100644 index 0d836079..00000000 --- a/autojs/src/main/java/com/stardust/autojs/runtime/record/inputevent/InputEventToJsConverter.java +++ /dev/null @@ -1,158 +0,0 @@ -package com.stardust.autojs.runtime.record.inputevent; - -import android.support.annotation.NonNull; - -import com.stardust.util.MapEntries; - -import java.util.HashMap; -import java.util.Map; - -/** - * Created by Stardust on 2017/3/7. - */ - -public class InputEventToJsConverter extends InputEventConverter { - - interface EventHandler { - void handle(Event event); - } - - abstract static class Router implements EventHandler { - - private Map mEventHandlerMap = new HashMap<>(); - - Router put(String key, EventHandler handler) { - mEventHandlerMap.put(key, handler); - return this; - } - - @Override - public void handle(Event event) { - EventHandler handler = mEventHandlerMap.get(getKey(event)); - if (handler != null) { - handler.handle(event); - } - } - - protected abstract String getKey(Event event); - } - - private class TypeRouter extends Router { - - TypeRouter() { - put("EV_ABS", new AbsHandler()); - put("EV_SYN", new SyncHandler()); - put("EV_KEY", new KeyHandler()); - } - - @Override - protected String getKey(Event event) { - return event.type; - } - } - - private static class Point { - int x, y; - } - - private class AbsHandler implements EventHandler { - - @Override - public void handle(Event event) { - if (event.code.equals("ABS_MT_POSITION_X")) { - mTouchPoint.x = Integer.parseInt(event.value, 16); - mTouchTime = event.time; - } else if (event.code.equals("ABS_MT_POSITION_Y")) { - mTouchPoint.y = Integer.parseInt(event.value, 16); - mTouchTime = event.time; - } - } - } - - private class SyncHandler implements EventHandler { - - @Override - public void handle(Event event) { - if (mTouchDown) { - if (mSwipe) { - appendCodeIfNotStopped(event); - mSwipe = false; - } else { - mLastTouchPoint.x = mTouchPoint.x; - mLastTouchPoint.y = mTouchPoint.y; - mSwipe = true; - } - } - } - - private void appendCodeIfNotStopped(Event event) { - if (!mConverting) - return; - long interval = (long) (1000 * (event.time - mTouchTime)); - mCode.append("sh.Swipe(") - .append(mLastTouchPoint.x).append(", ").append(mLastTouchPoint.y).append(", ") - .append(mTouchPoint.x).append(", ").append(mTouchPoint.y); - if (interval >= 1) { - mCode.append(", ").append(interval); - } - mCode.append(");\n"); - } - } - - private class KeyHandler implements EventHandler { - - private Map mKeyPressCodeMap = new MapEntries() - .entry("KEY_HOME", "Home") - .entry("KEY_MENU", "Menu") - .entry("KEY_VOLUMEDOWN", "VolumeDown") - .entry("KEY_VOLUMEUP", "VolumeUp") - .entry("KEY_BACK", "Back") - .entry("KEY_CAMERA", "Camera") - .map(); - - @Override - public void handle(Event event) { - if (event.code.equals("BTN_TOUCH")) { - mTouchDown = event.value.equals("DOWN"); - if (!mTouchDown && mSwipe) { - if (mConverting) - mCode.append("sh.Tap(").append(mLastTouchPoint.x).append(", ").append(mLastTouchPoint.y).append(");\n"); - mSwipe = false; - } - } else if (event.value.equals("UP")) { - appendKeyPressCode(event); - } - } - - private void appendKeyPressCode(Event event) { - String code = mKeyPressCodeMap.get(event.code); - if (code != null) { - mCode.append("sh.").append(code).append("();\n"); - } - } - } - - private EventHandler mEventHandler = new TypeRouter(); - private StringBuilder mCode = new StringBuilder().append("var sh = new Shell(true);\n"); - private Point mTouchPoint = new Point(), mLastTouchPoint = new Point(); - private boolean mTouchDown = false, mSwipe = false; - private double mTouchTime; - - - @Override - public void convertEvent(@NonNull Event event) { - mEventHandler.handle(event); - } - - @Override - public void stop() { - super.stop(); - mCode.append("sh.exitAndWaitFor();"); - } - - public String getCode() { - return mCode.toString(); - } - - -} diff --git a/autojs/src/main/java/com/stardust/autojs/runtime/record/inputevent/InputEventToRootAutomatorConverter.java b/autojs/src/main/java/com/stardust/autojs/runtime/record/inputevent/InputEventToRootAutomatorRecorder.java similarity index 90% rename from autojs/src/main/java/com/stardust/autojs/runtime/record/inputevent/InputEventToRootAutomatorConverter.java rename to autojs/src/main/java/com/stardust/autojs/runtime/record/inputevent/InputEventToRootAutomatorRecorder.java index 9322f398..8b5e7ade 100644 --- a/autojs/src/main/java/com/stardust/autojs/runtime/record/inputevent/InputEventToRootAutomatorConverter.java +++ b/autojs/src/main/java/com/stardust/autojs/runtime/record/inputevent/InputEventToRootAutomatorRecorder.java @@ -2,9 +2,6 @@ package com.stardust.autojs.runtime.record.inputevent; import android.support.annotation.NonNull; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - import static com.stardust.util.ScreenMetrics.getDeviceScreenHeight; import static com.stardust.util.ScreenMetrics.getDeviceScreenWidth; @@ -12,7 +9,7 @@ import static com.stardust.util.ScreenMetrics.getDeviceScreenWidth; * Created by Stardust on 2017/8/1. */ -public class InputEventToRootAutomatorConverter extends InputEventConverter { +public class InputEventToRootAutomatorRecorder extends InputEventRecorder { private double mLastEventTime; @@ -21,7 +18,7 @@ public class InputEventToRootAutomatorConverter extends InputEventConverter { private int mLastTouchX = -1; private int mLastTouchY = -1; - public InputEventToRootAutomatorConverter() { + public InputEventToRootAutomatorRecorder() { mCode.append("var ra = new RootAutomator();\n") .append("ra.setScreenMetrics(").append(getDeviceScreenWidth()).append(", ") .append(getDeviceScreenHeight()).append(");\n"); @@ -29,7 +26,7 @@ public class InputEventToRootAutomatorConverter extends InputEventConverter { @Override - public void convertEvent(@NonNull Event event) { + public void recordInputEvent(@NonNull InputEventObserver.InputEvent event) { if (mLastEventTime == 0) { mLastEventTime = event.time; } else if (event.time - mLastEventTime > 0.001) { @@ -101,11 +98,6 @@ public class InputEventToRootAutomatorConverter extends InputEventConverter { mTouchDevice = i; } - @Override - public String getGetEventCommand() { - return "getevent -t"; - } - public String getCode() { return mCode.toString(); } diff --git a/autojs/src/main/java/com/stardust/autojs/runtime/record/inputevent/InputEventToSendEventConverter.java b/autojs/src/main/java/com/stardust/autojs/runtime/record/inputevent/InputEventToSendEventConverter.java deleted file mode 100644 index aa7c9261..00000000 --- a/autojs/src/main/java/com/stardust/autojs/runtime/record/inputevent/InputEventToSendEventConverter.java +++ /dev/null @@ -1,52 +0,0 @@ -package com.stardust.autojs.runtime.record.inputevent; - -import android.support.annotation.NonNull; - -import java.text.DecimalFormat; - - -/** - * Created by Stardust on 2017/3/7. - */ - -public class InputEventToSendEventConverter extends InputEventConverter { - - private static final DecimalFormat DELAY_FORMAT = new DecimalFormat("#.###"); - - private double mLastEventTime; - private StringBuilder mSendEventCommands = new StringBuilder(); - - @Override - public void convertEvent(@NonNull Event event) { - if (mLastEventTime == 0) { - mLastEventTime = event.time; - } else if (event.time - mLastEventTime > 0.1) { - mSendEventCommands.append("sleep ").append(DELAY_FORMAT.format(event.time - mLastEventTime)).append("\n"); - mLastEventTime = event.time; - } - mSendEventCommands.append("sendevent ") - .append(event.device).append(" ") - .append(hex2dec(event.type)).append(" ") - .append(hex2dec(event.code)).append(" ") - .append(hex2dec(event.value)).append("\n"); - - } - - @Override - public String getGetEventCommand() { - return "getevent -t"; - } - - public String getCode() { - return mSendEventCommands.toString(); - } - - private static String hex2dec(String hex) { - try { - return String.valueOf((int) Long.parseLong(hex, 16)); - } catch (NumberFormatException e) { - throw new EventFormatException(e); - } - } - -} diff --git a/autojs/src/main/java/com/stardust/autojs/runtime/record/inputevent/InputEventToSendEventJsConverter.java b/autojs/src/main/java/com/stardust/autojs/runtime/record/inputevent/InputEventToSendEventJsRecorder.java similarity index 90% rename from autojs/src/main/java/com/stardust/autojs/runtime/record/inputevent/InputEventToSendEventJsConverter.java rename to autojs/src/main/java/com/stardust/autojs/runtime/record/inputevent/InputEventToSendEventJsRecorder.java index d1263f6d..ab4fbd0f 100644 --- a/autojs/src/main/java/com/stardust/autojs/runtime/record/inputevent/InputEventToSendEventJsConverter.java +++ b/autojs/src/main/java/com/stardust/autojs/runtime/record/inputevent/InputEventToSendEventJsRecorder.java @@ -2,9 +2,6 @@ package com.stardust.autojs.runtime.record.inputevent; import android.support.annotation.NonNull; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - import static com.stardust.util.ScreenMetrics.getDeviceScreenHeight; import static com.stardust.util.ScreenMetrics.getDeviceScreenWidth; @@ -12,7 +9,7 @@ import static com.stardust.util.ScreenMetrics.getDeviceScreenWidth; * Created by Stardust on 2017/5/3. */ -public class InputEventToSendEventJsConverter extends InputEventConverter { +public class InputEventToSendEventJsRecorder extends InputEventRecorder { private double mLastEventTime; private StringBuilder mCode = new StringBuilder(); @@ -20,7 +17,7 @@ public class InputEventToSendEventJsConverter extends InputEventConverter { private int mLastTouchX = -1; private int mLastTouchY = -1; - public InputEventToSendEventJsConverter() { + public InputEventToSendEventJsRecorder() { mCode.append("var sh = new Shell(true);\n") .append("sh.SetScreenMetrics(").append(getDeviceScreenWidth()).append(", ") .append(getDeviceScreenHeight()).append(");\n"); @@ -28,7 +25,7 @@ public class InputEventToSendEventJsConverter extends InputEventConverter { @Override - public void convertEvent(@NonNull Event event) { + public void recordInputEvent(@NonNull InputEventObserver.InputEvent event) { if (mLastEventTime == 0) { mLastEventTime = event.time; } else if (event.time - mLastEventTime > 0.03) { @@ -97,11 +94,6 @@ public class InputEventToSendEventJsConverter extends InputEventConverter { mTouchDevice = i; } - @Override - public String getGetEventCommand() { - return "getevent -t"; - } - public String getCode() { return mCode.toString(); } diff --git a/autojs/src/main/java/com/stardust/autojs/runtime/record/inputevent/KeyObserver.java b/autojs/src/main/java/com/stardust/autojs/runtime/record/inputevent/KeyObserver.java index f8f8de1f..73f4d71e 100644 --- a/autojs/src/main/java/com/stardust/autojs/runtime/record/inputevent/KeyObserver.java +++ b/autojs/src/main/java/com/stardust/autojs/runtime/record/inputevent/KeyObserver.java @@ -2,12 +2,284 @@ package com.stardust.autojs.runtime.record.inputevent; import android.content.Context; import android.support.annotation.NonNull; +import android.util.SparseArray; +import android.view.KeyEvent; + +import java.lang.reflect.Field; +import java.util.HashMap; +import java.util.Map; /** * Created by Stardust on 2017/5/4. */ -public class KeyObserver { +public class KeyObserver implements InputEventObserver.InputEventListener { + + + public static final int KEY_RESERVED = 0; + public static final int KEY_ESC = 1; + public static final int KEY_1 = 2; + public static final int KEY_2 = 3; + public static final int KEY_3 = 4; + public static final int KEY_4 = 5; + public static final int KEY_5 = 6; + public static final int KEY_6 = 7; + public static final int KEY_7 = 8; + public static final int KEY_8 = 9; + public static final int KEY_9 = 10; + public static final int KEY_0 = 11; + public static final int KEY_MINUS = 12; + public static final int KEY_EQUAL = 13; + public static final int KEY_BACKSPACE = 14; + public static final int KEY_TAB = 15; + public static final int KEY_Q = 16; + public static final int KEY_W = 17; + public static final int KEY_E = 18; + public static final int KEY_R = 19; + public static final int KEY_T = 20; + public static final int KEY_Y = 21; + public static final int KEY_U = 22; + public static final int KEY_I = 23; + public static final int KEY_O = 24; + public static final int KEY_P = 25; + public static final int KEY_LEFTBRACE = 26; + public static final int KEY_RIGHTBRACE = 27; + public static final int KEY_ENTER = 28; + public static final int KEY_LEFTCTRL = 29; + public static final int KEY_A = 30; + public static final int KEY_S = 31; + public static final int KEY_D = 32; + public static final int KEY_F = 33; + public static final int KEY_G = 34; + public static final int KEY_H = 35; + public static final int KEY_J = 36; + public static final int KEY_K = 37; + public static final int KEY_L = 38; + public static final int KEY_SEMICOLON = 39; + public static final int KEY_APOSTROPHE = 40; + public static final int KEY_GRAVE = 41; + public static final int KEY_LEFTSHIFT = 42; + public static final int KEY_BACKSLASH = 43; + public static final int KEY_Z = 44; + public static final int KEY_X = 45; + public static final int KEY_C = 46; + public static final int KEY_V = 47; + public static final int KEY_B = 48; + public static final int KEY_N = 49; + public static final int KEY_M = 50; + public static final int KEY_COMMA = 51; + public static final int KEY_DOT = 52; + public static final int KEY_SLASH = 53; + public static final int KEY_RIGHTSHIFT = 54; + public static final int KEY_KPASTERISK = 55; + public static final int KEY_LEFTALT = 56; + public static final int KEY_SPACE = 57; + public static final int KEY_CAPSLOCK = 58; + public static final int KEY_F1 = 59; + public static final int KEY_F2 = 60; + public static final int KEY_F3 = 61; + public static final int KEY_F4 = 62; + public static final int KEY_F5 = 63; + public static final int KEY_F6 = 64; + public static final int KEY_F7 = 65; + public static final int KEY_F8 = 66; + public static final int KEY_F9 = 67; + public static final int KEY_F10 = 68; + public static final int KEY_NUMLOCK = 69; + public static final int KEY_SCROLLLOCK = 70; + public static final int KEY_KP7 = 71; + public static final int KEY_KP8 = 72; + public static final int KEY_KP9 = 73; + public static final int KEY_KPMINUS = 74; + public static final int KEY_KP4 = 75; + public static final int KEY_KP5 = 76; + public static final int KEY_KP6 = 77; + public static final int KEY_KPPLUS = 78; + public static final int KEY_KP1 = 79; + public static final int KEY_KP2 = 80; + public static final int KEY_KP3 = 81; + public static final int KEY_KP0 = 82; + public static final int KEY_KPDOT = 83; + + public static final int KEY_ZENKAKUHANKAKU = 85; + public static final int KEY_102ND = 86; + public static final int KEY_F11 = 87; + public static final int KEY_F12 = 88; + public static final int KEY_RO = 89; + public static final int KEY_KATAKANA = 90; + public static final int KEY_HIRAGANA = 91; + public static final int KEY_HENKAN = 92; + public static final int KEY_KATAKANAHIRAGANA = 93; + public static final int KEY_MUHENKAN = 94; + public static final int KEY_KPJPCOMMA = 95; + public static final int KEY_KPENTER = 96; + public static final int KEY_RIGHTCTRL = 97; + public static final int KEY_KPSLASH = 98; + public static final int KEY_SYSRQ = 99; + public static final int KEY_RIGHTALT = 100; + public static final int KEY_LINEFEED = 101; + public static final int KEY_HOME = 102; + public static final int KEY_UP = 103; + public static final int KEY_PAGEUP = 104; + public static final int KEY_LEFT = 105; + public static final int KEY_RIGHT = 106; + public static final int KEY_END = 107; + public static final int KEY_DOWN = 108; + public static final int KEY_PAGEDOWN = 109; + public static final int KEY_INSERT = 110; + public static final int KEY_DELETE = 111; + public static final int KEY_MACRO = 112; + public static final int KEY_MUTE = 113; + public static final int KEY_VOLUMEDOWN = 114; + public static final int KEY_VOLUMEUP = 115; + public static final int KEY_POWER = 116; /* SC System Power Down */ + public static final int KEY_KPEQUAL = 117; + public static final int KEY_KPPLUSMINUS = 118; + public static final int KEY_PAUSE = 119; + public static final int KEY_SCALE = 120; /* AL Compiz Scale (Expose) */ + + public static final int KEY_KPCOMMA = 121; + public static final int KEY_HANGEUL = 122; + public static final int KEY_HANGUEL = KEY_HANGEUL; + public static final int KEY_HANJA = 123; + public static final int KEY_YEN = 124; + public static final int KEY_LEFTMETA = 125; + public static final int KEY_RIGHTMETA = 126; + public static final int KEY_COMPOSE = 127; + + public static final int KEY_STOP = 128; /* AC Stop */ + public static final int KEY_AGAIN = 129; + public static final int KEY_PROPS = 130; /* AC Properties */ + public static final int KEY_UNDO = 131; /* AC Undo */ + public static final int KEY_FRONT = 132; + public static final int KEY_COPY = 133; /* AC Copy */ + public static final int KEY_OPEN = 134; /* AC Open */ + public static final int KEY_PASTE = 135; /* AC Paste */ + public static final int KEY_FIND = 136; /* AC Search */ + public static final int KEY_CUT = 137; /* AC Cut */ + public static final int KEY_HELP = 138; /* AL Integrated Help Center */ + public static final int KEY_MENU = 139; /* Menu (show menu) */ + public static final int KEY_CALC = 140; /* AL Calculator */ + public static final int KEY_SETUP = 141; + public static final int KEY_SLEEP = 142; /* SC System Sleep */ + public static final int KEY_WAKEUP = 143; /* System Wake Up */ + public static final int KEY_FILE = 144; /* AL Local Machine Browser */ + public static final int KEY_SENDFILE = 145; + public static final int KEY_DELETEFILE = 146; + public static final int KEY_XFER = 147; + public static final int KEY_PROG1 = 148; + public static final int KEY_PROG2 = 149; + public static final int KEY_WWW = 150; /* AL Internet Browser */ + public static final int KEY_MSDOS = 151; + public static final int KEY_COFFEE = 152; /* AL Terminal Lock/Screensaver */ + public static final int KEY_SCREENLOCK = KEY_COFFEE; + public static final int KEY_ROTATE_DISPLAY = 153; /* Display orientation for e.g. tablets */ + public static final int KEY_DIRECTION = KEY_ROTATE_DISPLAY; + public static final int KEY_CYCLEWINDOWS = 154; + public static final int KEY_MAIL = 155; + public static final int KEY_BOOKMARKS = 156; /* AC Bookmarks */ + public static final int KEY_COMPUTER = 157; + public static final int KEY_BACK = 158; /* AC Back */ + public static final int KEY_FORWARD = 159; /* AC Forward */ + public static final int KEY_CLOSECD = 160; + public static final int KEY_EJECTCD = 161; + public static final int KEY_EJECTCLOSECD = 162; + public static final int KEY_NEXTSONG = 163; + public static final int KEY_PLAYPAUSE = 164; + public static final int KEY_PREVIOUSSONG = 165; + public static final int KEY_STOPCD = 166; + public static final int KEY_RECORD = 167; + public static final int KEY_REWIND = 168; + public static final int KEY_PHONE = 169; /* Media Select Telephone */ + public static final int KEY_ISO = 170; + public static final int KEY_CONFIG = 171; /* AL Consumer Control Configuration */ + public static final int KEY_HOMEPAGE = 172; /* AC Home */ + public static final int KEY_REFRESH = 173; /* AC Refresh */ + public static final int KEY_EXIT = 174; /* AC Exit */ + public static final int KEY_MOVE = 175; + public static final int KEY_EDIT = 176; + public static final int KEY_SCROLLUP = 177; + public static final int KEY_SCROLLDOWN = 178; + public static final int KEY_KPLEFTPAREN = 179; + public static final int KEY_KPRIGHTPAREN = 180; + public static final int KEY_NEW = 181; /* AC New */ + public static final int KEY_REDO = 182; /* AC Redo/Repeat */ + + public static final int KEY_F13 = 183; + public static final int KEY_F14 = 184; + public static final int KEY_F15 = 185; + public static final int KEY_F16 = 186; + public static final int KEY_F17 = 187; + public static final int KEY_F18 = 188; + public static final int KEY_F19 = 189; + public static final int KEY_F20 = 190; + public static final int KEY_F21 = 191; + public static final int KEY_F22 = 192; + public static final int KEY_F23 = 193; + public static final int KEY_F24 = 194; + + public static final int KEY_PLAYCD = 200; + public static final int KEY_PAUSECD = 201; + public static final int KEY_PROG3 = 202; + public static final int KEY_PROG4 = 203; + public static final int KEY_DASHBOARD = 204; /* AL Dashboard */ + public static final int KEY_SUSPEND = 205; + public static final int KEY_CLOSE = 206; /* AC Close */ + public static final int KEY_PLAY = 207; + public static final int KEY_FASTFORWARD = 208; + public static final int KEY_BASSBOOST = 209; + public static final int KEY_PRINT = 210; /* AC Print */ + public static final int KEY_HP = 211; + public static final int KEY_CAMERA = 212; + public static final int KEY_SOUND = 213; + public static final int KEY_QUESTION = 214; + public static final int KEY_EMAIL = 215; + public static final int KEY_CHAT = 216; + public static final int KEY_SEARCH = 217; + public static final int KEY_CONNECT = 218; + public static final int KEY_FINANCE = 219; /* AL Checkbook/Finance */ + public static final int KEY_SPORT = 220; + public static final int KEY_SHOP = 221; + public static final int KEY_ALTERASE = 222; + public static final int KEY_CANCEL = 223; /* AC Cancel */ + public static final int KEY_BRIGHTNESSDOWN = 224; + public static final int KEY_BRIGHTNESSUP = 225; + public static final int KEY_MEDIA = 226; + + public static final int KEY_SWITCHVIDEOMODE = 227; /* Cycle between available video + outputs (Monitor/LCD/TV-out/etc) */ + public static final int KEY_KBDILLUMTOGGLE = 228; + public static final int KEY_KBDILLUMDOWN = 229; + public static final int KEY_KBDILLUMUP = 230; + + public static final int KEY_SEND = 231; /* AC Send */ + public static final int KEY_REPLY = 232; /* AC Reply */ + public static final int KEY_FORWARDMAIL = 233; /* AC Forward Msg */ + public static final int KEY_SAVE = 234; /* AC Save */ + public static final int KEY_DOCUMENTS = 235; + + public static final int KEY_BATTERY = 236; + + public static final int KEY_BLUETOOTH = 237; + public static final int KEY_WLAN = 238; + public static final int KEY_UWB = 239; + + public static final int KEY_UNKNOWN = 240; + + public static final int KEY_VIDEO_NEXT = 241; /* drive next video source */ + public static final int KEY_VIDEO_PREV = 242; /* drive previous video source */ + public static final int KEY_BRIGHTNESS_CYCLE = 243; /* brightness up, after max is min */ + public static final int KEY_BRIGHTNESS_AUTO = 244; /* Set Auto Brightness: manual + brightness control is off, + rely on ambient */ + public static final int KEY_BRIGHTNESS_ZERO = KEY_BRIGHTNESS_AUTO; + public static final int KEY_DISPLAY_OFF = 245; /* display device to off state */ + + public static final int KEY_WWAN = 246; /* Wireless WAN (LTE, UMTS, GSM, etc.) */ + public static final int KEY_WIMAX = KEY_WWAN; + public static final int KEY_RFKILL = 247; /* Key that controls all radios */ + + public static final int KEY_MICMUTE = 248; public interface KeyListener { @@ -17,39 +289,42 @@ public class KeyObserver { } - private InputEventRecorder mObserver; + private static final Map keyNameToCode = new HashMap<>(); + private static final SparseArray keyCodeToName = new SparseArray<>(); + private KeyListener mKeyListener; - public KeyObserver(Context context) { - mObserver = new InputEventRecorder(context, new InputEventConverter() { - @Override - public void convertEvent(@NonNull Event event) { - if (event.value.equalsIgnoreCase("UP")) { - notifyKeyUp(event.code); - } - if (event.value.equalsIgnoreCase("DOWN")) { - notifyKeyDown(event.code); - } - } + public KeyObserver() { - @Override - public String getCode() { - return null; - } - }); } public void setKeyListener(KeyListener keyListener) { mKeyListener = keyListener; } - public void startListening() { - mObserver.listen(); - mObserver.start(); + @Override + public void onInputEvent(@NonNull InputEventObserver.InputEvent event) { + if (!event.type.equals("0001")) { + return; + } + if (event.value.equalsIgnoreCase("00000000")) { + notifyKeyUp(keyCodeToKeyName(Integer.parseInt(event.code, 16))); + } + if (event.value.equalsIgnoreCase("00000001")) { + notifyKeyDown(keyCodeToKeyName(Integer.parseInt(event.code, 16))); + } } - public void stopListening() { - mObserver.stopImpl(); + public static String keyCodeToKeyName(int code) { + return keyCodeToName.get(code); + } + + + public static int keyNameToCode(String name) { + Integer code = keyNameToCode.get(name); + if (code == null) + return -1; + return code; } private void notifyKeyDown(String keyName) { @@ -64,4 +339,18 @@ public class KeyObserver { } } + static { + try { + for (Field field : KeyObserver.class.getFields()) { + if (field.getName().startsWith("KEY_")) { + int keyCode = (int) field.get(null); + keyCodeToName.put(keyCode, field.getName()); + keyNameToCode.put(field.getName(), keyCode); + } + } + } catch (IllegalAccessException e) { + e.printStackTrace(); + } + } + } diff --git a/autojs/src/main/java/com/stardust/autojs/runtime/record/inputevent/TouchObserver.java b/autojs/src/main/java/com/stardust/autojs/runtime/record/inputevent/TouchObserver.java index 0d047fc7..a61edc06 100644 --- a/autojs/src/main/java/com/stardust/autojs/runtime/record/inputevent/TouchObserver.java +++ b/autojs/src/main/java/com/stardust/autojs/runtime/record/inputevent/TouchObserver.java @@ -1,33 +1,35 @@ package com.stardust.autojs.runtime.record.inputevent; -import android.content.Context; import android.support.annotation.NonNull; +import static com.stardust.autojs.runtime.record.inputevent.InputEventRecorder.parseDeviceNumber; + /** * Created by Stardust on 2017/7/20. */ -public class TouchObserver { +public class TouchObserver implements InputEventObserver.InputEventListener { + public interface OnTouchEventListener { void onTouch(int x, int y); } private int mTouchX, mTouchY; - private InputEventRecorder mRecorder; private OnTouchEventListener mOnTouchEventListener; + private int mLastTouchX = -1, mLastTouchY = -1; + private InputEventObserver mInputEventObserver; - public TouchObserver(Context context) { - mRecorder = new InputEventRecorder(context, new TouchEventObserver()); + public TouchObserver(InputEventObserver observer) { + mInputEventObserver = observer; } public void observe() { - mRecorder.listen(); - mRecorder.start(); + mInputEventObserver.addListener(this); } public void stop() { - mRecorder.stop(); + mInputEventObserver.removeListener(this); } public void setOnTouchEventListener(OnTouchEventListener onTouchEventListener) { @@ -37,66 +39,50 @@ public class TouchObserver { private void onTouch(int x, int y) { mTouchX = x; mTouchY = y; - if(mOnTouchEventListener != null){ + if (mOnTouchEventListener != null) { mOnTouchEventListener.onTouch(x, y); } } - - private class TouchEventObserver extends InputEventConverter { - - private int mLastTouchX = -1, mLastTouchY = -1; - - @Override - public void convertEvent(@NonNull Event event) { - int device = parseDeviceNumber(event.device); - int type = (int) Long.parseLong(event.type, 16); - int code = (int) Long.parseLong(event.code, 16); - int value = (int) Long.parseLong(event.value, 16); - if (type != 3) { - return; - } - if (code == 53) { - onTouchX(value); - return; - } - if (code == 54) { - onTouchY(value); - return; - } - if (mLastTouchX >= 0) { - onTouch(mLastTouchX, mTouchY); - mLastTouchX = -1; - return; - } - if (mLastTouchY >= 0) { - onTouch(mTouchX, mLastTouchY); - mLastTouchY = -1; - } + @Override + public void onInputEvent(@NonNull InputEventObserver.InputEvent event) { + int device = parseDeviceNumber(event.device); + int type = (int) Long.parseLong(event.type, 16); + int code = (int) Long.parseLong(event.code, 16); + int value = (int) Long.parseLong(event.value, 16); + if (type != 3) { + return; } - - private void onTouchX(int value) { - mLastTouchX = value; + if (code == 53) { + onTouchX(value); + return; } - - private void onTouchY(int value) { - if (mLastTouchX > 0) { - onTouch(mLastTouchX, value); - return; - } - mLastTouchY = value; + if (code == 54) { + onTouchY(value); + return; } - - @Override - public String getGetEventCommand() { - return "getevent -t"; + if (mLastTouchX >= 0) { + onTouch(mLastTouchX, mTouchY); + mLastTouchX = -1; + return; } - - @Override - public String getCode() { - return null; + if (mLastTouchY >= 0) { + onTouch(mTouchX, mLastTouchY); + mLastTouchY = -1; } } + private void onTouchX(int value) { + mLastTouchX = value; + } + + private void onTouchY(int value) { + if (mLastTouchX > 0) { + onTouch(mLastTouchX, value); + return; + } + mLastTouchY = value; + } + } diff --git a/autojs/src/main/java/com/stardust/autojs/runtime/record/inputevent/TouchRecorder.java b/autojs/src/main/java/com/stardust/autojs/runtime/record/inputevent/TouchRecorder.java index bab35bcd..54222418 100644 --- a/autojs/src/main/java/com/stardust/autojs/runtime/record/inputevent/TouchRecorder.java +++ b/autojs/src/main/java/com/stardust/autojs/runtime/record/inputevent/TouchRecorder.java @@ -2,21 +2,68 @@ package com.stardust.autojs.runtime.record.inputevent; import android.content.Context; +import com.stardust.autojs.runtime.record.Recorder; + /** * Created by Stardust on 2017/3/16. */ -public class TouchRecorder extends InputEventRecorder { +public class TouchRecorder extends Recorder.AbstractRecorder { + + private static TouchRecorder sInstance; + private InputEventRecorder mInputEventRecorder; + private Context mContext; + private InputEventObserver mInputEventObserver; + + public TouchRecorder(Context context, InputEventObserver observer) { + mContext = context; + mInputEventObserver = observer; + } public TouchRecorder(Context context) { - super(context, new InputEventToAutoFileConverter(context)); - listen(); + mContext = context; + mInputEventObserver = new InputEventObserver(context); + mInputEventObserver.observe(); } + public static TouchRecorder getGlobal(Context context) { + if (sInstance == null) + sInstance = new TouchRecorder(context); + return sInstance; + } @Override - public void stop() { - super.stop(); + protected void startImpl() { + mInputEventRecorder = new InputEventToAutoFileRecorder(mContext); + mInputEventObserver.addListener(mInputEventRecorder); + mInputEventRecorder.start(); } + @Override + protected void pauseImpl() { + super.pauseImpl(); + mInputEventRecorder.pause(); + } + + @Override + protected void resumeImpl() { + super.resumeImpl(); + mInputEventRecorder.resume(); + } + + @Override + protected void stopImpl() { + mInputEventRecorder.stop(); + mInputEventObserver.removeListener(mInputEventRecorder); + } + + @Override + public String getCode() { + return mInputEventRecorder.getCode(); + } + + + public void reset() { + setState(STATE_NOT_START); + } } diff --git a/autojs/src/main/java/com/stardust/autojs/script/AutoFileSource.java b/autojs/src/main/java/com/stardust/autojs/script/AutoFileSource.java index 34fb4f87..ebb8b7a3 100644 --- a/autojs/src/main/java/com/stardust/autojs/script/AutoFileSource.java +++ b/autojs/src/main/java/com/stardust/autojs/script/AutoFileSource.java @@ -35,4 +35,8 @@ public class AutoFileSource extends ScriptSource { return mFile; } + @Override + public String toString() { + return mFile.toString(); + } } diff --git a/autojs/src/main/res/xml/accessibility_service_config.xml b/autojs/src/main/res/xml/accessibility_service_config.xml index edab932f..a538ccb9 100644 --- a/autojs/src/main/res/xml/accessibility_service_config.xml +++ b/autojs/src/main/res/xml/accessibility_service_config.xml @@ -8,4 +8,4 @@ android:canRequestFilterKeyEvents="true" android:canRetrieveWindowContent="true" android:description="@string/text_accessibility_service_description" - android:notificationTimeout="100"/> \ No newline at end of file + android:notificationTimeout="0"/> \ No newline at end of file diff --git a/automator/src/main/java/com/stardust/view/accessibility/NotificationListener.java b/automator/src/main/java/com/stardust/view/accessibility/NotificationListener.java index 933b0665..7ce0f731 100644 --- a/automator/src/main/java/com/stardust/view/accessibility/NotificationListener.java +++ b/automator/src/main/java/com/stardust/view/accessibility/NotificationListener.java @@ -7,9 +7,7 @@ import android.support.annotation.Nullable; import android.util.Log; import android.view.accessibility.AccessibilityEvent; -import com.stardust.util.ArrayUtils; - -import java.util.Arrays; +import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Set; @@ -21,7 +19,59 @@ import java.util.concurrent.CopyOnWriteArrayList; public interface NotificationListener { - void onNotification(AccessibilityEvent event, String[] notification); + class NotificationInfo { + + private String mPackageName; + private String mText; + private List mTexts; + + public NotificationInfo(String packageName, List texts) { + mPackageName = packageName; + mTexts = texts; + if (mTexts.size() > 0) { + mText = mTexts.get(0); + } + } + + public NotificationInfo(CharSequence packageName, List list) { + mPackageName = packageName.toString(); + mTexts = new ArrayList<>(list.size()); + for (CharSequence text : list) { + mTexts.add(text.toString()); + } + if (mTexts.size() > 0) { + mText = mTexts.get(0); + } + } + + + public static NotificationInfo fromEvent(AccessibilityEvent event) { + return new NotificationInfo(event.getPackageName(), event.getText()); + } + + public String getPackageName() { + return mPackageName; + } + + public String getText() { + return mText; + } + + public List getTexts() { + return mTexts; + } + + @Override + public String toString() { + return "NotificationInfo{" + + "packageName='" + mPackageName + '\'' + + ", text='" + mText + '\'' + + ", texts=" + mTexts + + '}'; + } + } + + void onNotification(AccessibilityEvent event, NotificationInfo notification); void onNotification(AccessibilityEvent event, Notification notification); @@ -40,12 +90,12 @@ public interface NotificationListener { } @Override - public void onNotification(AccessibilityEvent event, String[] notification) { + public void onNotification(AccessibilityEvent event, NotificationInfo notification) { for (NotificationListener listener : mNotificationListeners) { try { listener.onNotification(event, notification); } catch (Exception e) { - Log.e(TAG, "Error onNotification: " + Arrays.toString(notification) + " Listener: " + listener, e); + Log.e(TAG, "Error onNotification: " + notification + " Listener: " + listener, e); } } } @@ -82,7 +132,7 @@ public interface NotificationListener { return false; } if (list != null) { - onNotification(event, ArrayUtils.toStringArray(list)); + onNotification(event, new NotificationInfo(event.getPackageName(), list)); } } return false;