diff --git a/.idea/misc.xml b/.idea/misc.xml index 157352a8..497cbeb5 100644 --- a/.idea/misc.xml +++ b/.idea/misc.xml @@ -42,7 +42,7 @@ - + diff --git a/LICENSE.md b/LICENSE.md new file mode 100644 index 00000000..b82befc6 --- /dev/null +++ b/LICENSE.md @@ -0,0 +1,177 @@ +## creative commons + +# Attribution-NonCommercial-ShareAlike 4.0 International + +Creative Commons Corporation (“Creative Commons”) is not a law firm and does not provide legal services or legal advice. Distribution of Creative Commons public licenses does not create a lawyer-client or other relationship. Creative Commons makes its licenses and related information available on an “as-is” basis. Creative Commons gives no warranties regarding its licenses, any material licensed under their terms and conditions, or any related information. Creative Commons disclaims all liability for damages resulting from their use to the fullest extent possible. + +### Using Creative Commons Public Licenses + +Creative Commons public licenses provide a standard set of terms and conditions that creators and other rights holders may use to share original works of authorship and other material subject to copyright and certain other rights specified in the public license below. The following considerations are for informational purposes only, are not exhaustive, and do not form part of our licenses. + +* __Considerations for licensors:__ Our public licenses are intended for use by those authorized to give the public permission to use material in ways otherwise restricted by copyright and certain other rights. Our licenses are irrevocable. Licensors should read and understand the terms and conditions of the license they choose before applying it. Licensors should also secure all rights necessary before applying our licenses so that the public can reuse the material as expected. Licensors should clearly mark any material not subject to the license. This includes other CC-licensed material, or material used under an exception or limitation to copyright. [More considerations for licensors](http://wiki.creativecommons.org/Considerations_for_licensors_and_licensees#Considerations_for_licensors). + +* __Considerations for the public:__ By using one of our public licenses, a licensor grants the public permission to use the licensed material under specified terms and conditions. If the licensor’s permission is not necessary for any reason–for example, because of any applicable exception or limitation to copyright–then that use is not regulated by the license. Our licenses grant only permissions under copyright and certain other rights that a licensor has authority to grant. Use of the licensed material may still be restricted for other reasons, including because others have copyright or other rights in the material. A licensor may make special requests, such as asking that all changes be marked or described. Although not required by our licenses, you are encouraged to respect those requests where reasonable. [More considerations for the public](http://wiki.creativecommons.org/Considerations_for_licensors_and_licensees#Considerations_for_licensees). + +## Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International Public License + +By exercising the Licensed Rights (defined below), You accept and agree to be bound by the terms and conditions of this Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International Public License ("Public License"). To the extent this Public License may be interpreted as a contract, You are granted the Licensed Rights in consideration of Your acceptance of these terms and conditions, and the Licensor grants You such rights in consideration of benefits the Licensor receives from making the Licensed Material available under these terms and conditions. + +### Section 1 – Definitions. + +a. __Adapted Material__ means material subject to Copyright and Similar Rights that is derived from or based upon the Licensed Material and in which the Licensed Material is translated, altered, arranged, transformed, or otherwise modified in a manner requiring permission under the Copyright and Similar Rights held by the Licensor. For purposes of this Public License, where the Licensed Material is a musical work, performance, or sound recording, Adapted Material is always produced where the Licensed Material is synched in timed relation with a moving image. + +b. __Adapter's License__ means the license You apply to Your Copyright and Similar Rights in Your contributions to Adapted Material in accordance with the terms and conditions of this Public License. + +c. __BY-NC-SA Compatible License__ means a license listed at [creativecommons.org/compatiblelicenses](http://creativecommons.org/compatiblelicenses), approved by Creative Commons as essentially the equivalent of this Public License. + +d. __Copyright and Similar Rights__ means copyright and/or similar rights closely related to copyright including, without limitation, performance, broadcast, sound recording, and Sui Generis Database Rights, without regard to how the rights are labeled or categorized. For purposes of this Public License, the rights specified in Section 2(b)(1)-(2) are not Copyright and Similar Rights. + +e. __Effective Technological Measures__ means those measures that, in the absence of proper authority, may not be circumvented under laws fulfilling obligations under Article 11 of the WIPO Copyright Treaty adopted on December 20, 1996, and/or similar international agreements. + +f. __Exceptions and Limitations__ means fair use, fair dealing, and/or any other exception or limitation to Copyright and Similar Rights that applies to Your use of the Licensed Material. + +g. __License Elements__ means the license attributes listed in the name of a Creative Commons Public License. The License Elements of this Public License are Attribution, NonCommercial, and ShareAlike. + +h. __Licensed Material__ means the artistic or literary work, database, or other material to which the Licensor applied this Public License. + +i. __Licensed Rights__ means the rights granted to You subject to the terms and conditions of this Public License, which are limited to all Copyright and Similar Rights that apply to Your use of the Licensed Material and that the Licensor has authority to license. + +h. __Licensor__ means the individual(s) or entity(ies) granting rights under this Public License. + +i. __NonCommercial__ means not primarily intended for or directed towards commercial advantage or monetary compensation. For purposes of this Public License, the exchange of the Licensed Material for other material subject to Copyright and Similar Rights by digital file-sharing or similar means is NonCommercial provided there is no payment of monetary compensation in connection with the exchange. + +j. __Share__ means to provide material to the public by any means or process that requires permission under the Licensed Rights, such as reproduction, public display, public performance, distribution, dissemination, communication, or importation, and to make material available to the public including in ways that members of the public may access the material from a place and at a time individually chosen by them. + +k. __Sui Generis Database Rights__ means rights other than copyright resulting from Directive 96/9/EC of the European Parliament and of the Council of 11 March 1996 on the legal protection of databases, as amended and/or succeeded, as well as other essentially equivalent rights anywhere in the world. + +l. __You__ means the individual or entity exercising the Licensed Rights under this Public License. Your has a corresponding meaning. + +### Section 2 – Scope. + +a. ___License grant.___ + + 1. Subject to the terms and conditions of this Public License, the Licensor hereby grants You a worldwide, royalty-free, non-sublicensable, non-exclusive, irrevocable license to exercise the Licensed Rights in the Licensed Material to: + + A. reproduce and Share the Licensed Material, in whole or in part, for NonCommercial purposes only; and + + B. produce, reproduce, and Share Adapted Material for NonCommercial purposes only. + + 2. __Exceptions and Limitations.__ For the avoidance of doubt, where Exceptions and Limitations apply to Your use, this Public License does not apply, and You do not need to comply with its terms and conditions. + + 3. __Term.__ The term of this Public License is specified in Section 6(a). + + 4. __Media and formats; technical modifications allowed.__ The Licensor authorizes You to exercise the Licensed Rights in all media and formats whether now known or hereafter created, and to make technical modifications necessary to do so. The Licensor waives and/or agrees not to assert any right or authority to forbid You from making technical modifications necessary to exercise the Licensed Rights, including technical modifications necessary to circumvent Effective Technological Measures. For purposes of this Public License, simply making modifications authorized by this Section 2(a)(4) never produces Adapted Material. + + 5. __Downstream recipients.__ + + A. __Offer from the Licensor – Licensed Material.__ Every recipient of the Licensed Material automatically receives an offer from the Licensor to exercise the Licensed Rights under the terms and conditions of this Public License. + + B. __Additional offer from the Licensor – Adapted Material.__ Every recipient of Adapted Material from You automatically receives an offer from the Licensor to exercise the Licensed Rights in the Adapted Material under the conditions of the Adapter’s License You apply. + + C. __No downstream restrictions.__ You may not offer or impose any additional or different terms or conditions on, or apply any Effective Technological Measures to, the Licensed Material if doing so restricts exercise of the Licensed Rights by any recipient of the Licensed Material. + + 6. __No endorsement.__ Nothing in this Public License constitutes or may be construed as permission to assert or imply that You are, or that Your use of the Licensed Material is, connected with, or sponsored, endorsed, or granted official status by, the Licensor or others designated to receive attribution as provided in Section 3(a)(1)(A)(i). + +b. ___Other rights.___ + + 1. Moral rights, such as the right of integrity, are not licensed under this Public License, nor are publicity, privacy, and/or other similar personality rights; however, to the extent possible, the Licensor waives and/or agrees not to assert any such rights held by the Licensor to the limited extent necessary to allow You to exercise the Licensed Rights, but not otherwise. + + 2. Patent and trademark rights are not licensed under this Public License. + + 3. To the extent possible, the Licensor waives any right to collect royalties from You for the exercise of the Licensed Rights, whether directly or through a collecting society under any voluntary or waivable statutory or compulsory licensing scheme. In all other cases the Licensor expressly reserves any right to collect such royalties, including when the Licensed Material is used other than for NonCommercial purposes. + +### Section 3 – License Conditions. + +Your exercise of the Licensed Rights is expressly made subject to the following conditions. + +a. ___Attribution.___ + + 1. If You Share the Licensed Material (including in modified form), You must: + + A. retain the following if it is supplied by the Licensor with the Licensed Material: + + i. identification of the creator(s) of the Licensed Material and any others designated to receive attribution, in any reasonable manner requested by the Licensor (including by pseudonym if designated); + + ii. a copyright notice; + + iii. a notice that refers to this Public License; + + iv. a notice that refers to the disclaimer of warranties; + + v. a URI or hyperlink to the Licensed Material to the extent reasonably practicable; + + B. indicate if You modified the Licensed Material and retain an indication of any previous modifications; and + + C. indicate the Licensed Material is licensed under this Public License, and include the text of, or the URI or hyperlink to, this Public License. + + 2. You may satisfy the conditions in Section 3(a)(1) in any reasonable manner based on the medium, means, and context in which You Share the Licensed Material. For example, it may be reasonable to satisfy the conditions by providing a URI or hyperlink to a resource that includes the required information. + + 3. If requested by the Licensor, You must remove any of the information required by Section 3(a)(1)(A) to the extent reasonably practicable. + +b. ___ShareAlike.___ + +In addition to the conditions in Section 3(a), if You Share Adapted Material You produce, the following conditions also apply. + +1. The Adapter’s License You apply must be a Creative Commons license with the same License Elements, this version or later, or a BY-NC-SA Compatible License. + +2. You must include the text of, or the URI or hyperlink to, the Adapter's License You apply. You may satisfy this condition in any reasonable manner based on the medium, means, and context in which You Share Adapted Material. + +3. You may not offer or impose any additional or different terms or conditions on, or apply any Effective Technological Measures to, Adapted Material that restrict exercise of the rights granted under the Adapter's License You apply. + +### Section 4 – Sui Generis Database Rights. + +Where the Licensed Rights include Sui Generis Database Rights that apply to Your use of the Licensed Material: + +a. for the avoidance of doubt, Section 2(a)(1) grants You the right to extract, reuse, reproduce, and Share all or a substantial portion of the contents of the database for NonCommercial purposes only; + +b. if You include all or a substantial portion of the database contents in a database in which You have Sui Generis Database Rights, then the database in which You have Sui Generis Database Rights (but not its individual contents) is Adapted Material, including for purposes of Section 3(b); and + +c. You must comply with the conditions in Section 3(a) if You Share all or a substantial portion of the contents of the database. + +For the avoidance of doubt, this Section 4 supplements and does not replace Your obligations under this Public License where the Licensed Rights include other Copyright and Similar Rights. + +### Section 5 – Disclaimer of Warranties and Limitation of Liability. + +a. __Unless otherwise separately undertaken by the Licensor, to the extent possible, the Licensor offers the Licensed Material as-is and as-available, and makes no representations or warranties of any kind concerning the Licensed Material, whether express, implied, statutory, or other. This includes, without limitation, warranties of title, merchantability, fitness for a particular purpose, non-infringement, absence of latent or other defects, accuracy, or the presence or absence of errors, whether or not known or discoverable. Where disclaimers of warranties are not allowed in full or in part, this disclaimer may not apply to You.__ + +b. __To the extent possible, in no event will the Licensor be liable to You on any legal theory (including, without limitation, negligence) or otherwise for any direct, special, indirect, incidental, consequential, punitive, exemplary, or other losses, costs, expenses, or damages arising out of this Public License or use of the Licensed Material, even if the Licensor has been advised of the possibility of such losses, costs, expenses, or damages. Where a limitation of liability is not allowed in full or in part, this limitation may not apply to You.__ + +c. The disclaimer of warranties and limitation of liability provided above shall be interpreted in a manner that, to the extent possible, most closely approximates an absolute disclaimer and waiver of all liability. + +### Section 6 – Term and Termination. + +a. This Public License applies for the term of the Copyright and Similar Rights licensed here. However, if You fail to comply with this Public License, then Your rights under this Public License terminate automatically. + +b. Where Your right to use the Licensed Material has terminated under Section 6(a), it reinstates: + + 1. automatically as of the date the violation is cured, provided it is cured within 30 days of Your discovery of the violation; or + + 2. upon express reinstatement by the Licensor. + + For the avoidance of doubt, this Section 6(b) does not affect any right the Licensor may have to seek remedies for Your violations of this Public License. + +c. For the avoidance of doubt, the Licensor may also offer the Licensed Material under separate terms or conditions or stop distributing the Licensed Material at any time; however, doing so will not terminate this Public License. + +d. Sections 1, 5, 6, 7, and 8 survive termination of this Public License. + +### Section 7 – Other Terms and Conditions. + +a. The Licensor shall not be bound by any additional or different terms or conditions communicated by You unless expressly agreed. + +b. Any arrangements, understandings, or agreements regarding the Licensed Material not stated herein are separate from and independent of the terms and conditions of this Public License. + +### Section 8 – Interpretation. + +a. For the avoidance of doubt, this Public License does not, and shall not be interpreted to, reduce, limit, restrict, or impose conditions on any use of the Licensed Material that could lawfully be made without permission under this Public License. + +b. To the extent possible, if any provision of this Public License is deemed unenforceable, it shall be automatically reformed to the minimum extent necessary to make it enforceable. If the provision cannot be reformed, it shall be severed from this Public License without affecting the enforceability of the remaining terms and conditions. + +c. No term or condition of this Public License will be waived and no failure to comply consented to unless expressly agreed to by the Licensor. + +d. Nothing in this Public License constitutes or may be interpreted as a limitation upon, or waiver of, any privileges and immunities that apply to the Licensor or You, including from the legal processes of any jurisdiction or authority. + +``` +Creative Commons is not a party to its public licenses. Notwithstanding, Creative Commons may elect to apply one of its public licenses to material it publishes and in those instances will be considered the “Licensor.” Except for the limited purpose of indicating that material is shared under a Creative Commons public license or as otherwise permitted by the Creative Commons policies published at [creativecommons.org/policies](http://creativecommons.org/policies), Creative Commons does not authorize the use of the trademark “Creative Commons” or any other trademark or logo of Creative Commons without its prior written consent including, without limitation, in connection with any unauthorized modifications to any of its public licenses or any other arrangements, understandings, or agreements concerning use of licensed material. For the avoidance of doubt, this paragraph does not form part of the public licenses. + +Creative Commons may be contacted at creativecommons.org +``` \ No newline at end of file diff --git a/app/app20170205.apk b/app/app20170205.apk deleted file mode 100644 index 10da8c37..00000000 Binary files a/app/app20170205.apk and /dev/null differ diff --git a/app/build.gradle b/app/build.gradle index 4e71c319..3b2c8b90 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -6,8 +6,6 @@ android { defaultConfig { applicationId "com.stardust.scriptdroid" minSdkVersion 19 - //由于不知道在API24以上如何调起其他文件编辑器应用编辑文件,只能改到API23。FileProvider貌似只能查看编辑后不能保存? - //参照ScriptFileOperation.Edit targetSdkVersion 23 versionCode 1 versionName "1.0" diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index 471e75c0..c07c65bc 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -76,6 +76,7 @@ + diff --git a/app/src/main/assets/javasccript_engine_init.js b/app/src/main/assets/javasccript_engine_init.js index 5d3c781c..efc5525d 100644 --- a/app/src/main/assets/javasccript_engine_init.js +++ b/app/src/main/assets/javasccript_engine_init.js @@ -19,21 +19,11 @@ var launchApp = function(appName){ droid.launchApp(appName); } - -var text = function(str){ - return droid.text(str); -} - -var bounds = function(left, top, right, bottom){ - return droid.bounds(left, top, right, bottom); -} - - function performAction(action, args){ if(args.length == 4){ - return action(bounds(args[0], args[1], args[2], args[3])); + return action(droid.bounds(args[0], args[1], args[2], args[3])); }else{ - return action(text(args[0])); + return action(droid.text(args[0])); } } @@ -49,17 +39,9 @@ var longClick = function(a, b, c, d){ }, arguments); } -var scrollAllUp = function(){ - droid.scrollAllUp(); -} - -var scrollAllDown = function(){ - droid.scrollAllDown(); -} - var scrollUp = function(a, b, c, d){ if(arguments.length == 0) - return scrollAllUp(); + return droid.scrollAllUp(); return performAction(function(target){ return droid.scrollUp(target); }, arguments); @@ -67,7 +49,7 @@ var scrollUp = function(a, b, c, d){ var scrollDown = function(a, b, c, d){ if(arguments.length == 0) - return scrollAllDown(); + return droid.scrollAllDown(); return performAction(function(target){ return droid.scrollDown(target); }, arguments); @@ -95,10 +77,6 @@ var editable = function(i){ return droid.editable(i); } -var setText = function(target, str){ - return droid.setText(target, str); -} - var input = function(a, b){ if(arguments.length == 1){ return droid.setText(editable(-1), a); @@ -111,9 +89,11 @@ var sleep = function(millis){ droid.sleep(millis); } +var isStopped = function(){ + return droid.isStopped(); +} -importClass("java.lang.Runnable"); +var notStopped = function(){ + return !isStopped(); +} -var ui = function(action){ - droid.ui(new Runnable(action)); -} \ No newline at end of file diff --git a/app/src/main/assets/sample_force_qq_chat.js b/app/src/main/assets/sample_force_qq_chat.js new file mode 100644 index 00000000..500cb8c3 --- /dev/null +++ b/app/src/main/assets/sample_force_qq_chat.js @@ -0,0 +1,22 @@ +"ui"; + +importClass("android.widget.EditText"); +importClass("android.widget.Button"); +importClass("android.widget.LinearLayout"); +importClass("android.view.View.OnClickListener"); +importClass("android.content.Intent"); +importClass("android.net.Uri"); + +var qq = new EditText(activity); +qq.setHint("请输入QQ号"); +var btnOk = new Button(activity); +btnOk.setText("确定"); +var container = new LinearLayout(activity); +container.addView(qq); +container.addView(btnOk); +activity.setContentView(container); + +btnOk.setOnClickListener(new OnClickListener(function(view){ + activity.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("mqqwpa://im/chat?chat_type=wpa&uin=" + qq.getText()))); + activity.finish(); +})); \ No newline at end of file diff --git a/app/src/main/assets/sample_hello_big_sister.js b/app/src/main/assets/sample_hello_big_sister.js deleted file mode 100644 index c478c6ac..00000000 --- a/app/src/main/assets/sample_hello_big_sister.js +++ /dev/null @@ -1,4 +0,0 @@ -toast("大姐姐好") -for(var i = 0; i < 10; i++){ - toast("大姐姐今年有" + i + "块钱~"); -} \ No newline at end of file diff --git a/app/src/main/assets/sample_qq_hongbao.js b/app/src/main/assets/sample_qq_hongbao.js new file mode 100644 index 00000000..a7fc3d4e --- /dev/null +++ b/app/src/main/assets/sample_qq_hongbao.js @@ -0,0 +1,13 @@ +launch("com.tencent.mobileqq"); +toast("请打开一个聊天窗口"); +toast("出现红包时将会自动拆开并关闭"); +while(!isStopped()){ + if(click("点击拆开")){ + //拆开红包后尝试10次关闭红包页面 + for(var i = 0; i < 10; i++){ + sleep(300); + if(click("关闭")) + break; + } + } +} \ No newline at end of file diff --git a/app/src/main/assets/sample_simple_calculator.js b/app/src/main/assets/sample_simple_calculator.js index c246fa81..903733f1 100644 --- a/app/src/main/assets/sample_simple_calculator.js +++ b/app/src/main/assets/sample_simple_calculator.js @@ -1,7 +1,17 @@ +"ui"; importClass("com.afollestad.materialdialogs.MaterialDialog.Builder"); +importClass("com.afollestad.materialdialogs.MaterialDialog.InputCallback"); +importClass("android.content.DialogInterface.OnDismissListener"); -new Builder(context) - .title("请输入算式") - .content("测试") +new Builder(activity) + .title("简单计算器") + .input("请输入算式", "1+1", new InputCallback(function(dialog, input){ + eval("var ans = (" + input + ")"); + toast(ans); + })) + .positiveText("计算") + .dismissListener(new OnDismissListener(function(dialog){ + activity.finish(); + })) .show(); \ No newline at end of file diff --git a/app/src/main/java/com/stardust/app/NotRemindAgainDialog.java b/app/src/main/java/com/stardust/app/NotRemindAgainDialog.java index fc151697..1a10851f 100644 --- a/app/src/main/java/com/stardust/app/NotRemindAgainDialog.java +++ b/app/src/main/java/com/stardust/app/NotRemindAgainDialog.java @@ -28,7 +28,12 @@ public class NotRemindAgainDialog extends MaterialDialog { private boolean mRemind; public Builder(@NonNull Context context) { + this(context, null); + } + + public Builder(Context context, String key) { super(context); + mKeyRemind = key; readRemindStatus(); checkBoxPrompt(context.getString(R.string.text_do_not_remind_again), false, new CompoundButton.OnCheckedChangeListener() { @Override @@ -52,12 +57,13 @@ public class NotRemindAgainDialog extends MaterialDialog { } private void readRemindStatus() { - generatePreferenceKey(); + generatePreferenceKeyIfNeeded(); mRemind = PreferenceManager.getDefaultSharedPreferences(getContext()).getBoolean(mKeyRemind, true); } - private void generatePreferenceKey() { - mKeyRemind = md5(TextUtils.join("", Thread.currentThread().getStackTrace())); + private void generatePreferenceKeyIfNeeded() { + if (mKeyRemind == null) + mKeyRemind = md5(TextUtils.join("", Thread.currentThread().getStackTrace())); } } } diff --git a/app/src/main/java/com/stardust/scriptdroid/App.java b/app/src/main/java/com/stardust/scriptdroid/App.java index f9a0e7b2..c2d80eb7 100644 --- a/app/src/main/java/com/stardust/scriptdroid/App.java +++ b/app/src/main/java/com/stardust/scriptdroid/App.java @@ -1,6 +1,8 @@ package com.stardust.scriptdroid; +import android.app.Activity; import android.app.Application; +import android.os.Bundle; import android.preference.PreferenceManager; import com.stardust.util.CrashHandler; @@ -14,6 +16,7 @@ public class App extends Application { private static App instance; private static StateObserver stateObserver; + private static Activity currentActivity; public static App getApp() { return instance; @@ -26,8 +29,69 @@ public class App extends Application { public void onCreate() { super.onCreate(); - Thread.currentThread().setUncaughtExceptionHandler(new CrashHandler(ErrorReportActivity.class)); + Thread.setDefaultUncaughtExceptionHandler(new CrashHandler(ErrorReportActivity.class)); instance = this; stateObserver = new StateObserver(PreferenceManager.getDefaultSharedPreferences(this)); + registerActivityLifecycleCallbacks(new SimpleActivityLifecycleCallbacks() { + @Override + public void onActivityCreated(Activity activity, Bundle savedInstanceState) { + currentActivity = activity; + } + + + @Override + public void onActivityPaused(Activity activity) { + currentActivity = null; + } + + @Override + public void onActivityResumed(Activity activity) { + currentActivity = activity; + } + + }); + } + + public static Activity currentActivity() { + return currentActivity; + } + + + private static class SimpleActivityLifecycleCallbacks implements ActivityLifecycleCallbacks { + + @Override + public void onActivityCreated(Activity activity, Bundle savedInstanceState) { + + } + + @Override + public void onActivityStarted(Activity activity) { + + } + + @Override + public void onActivityResumed(Activity activity) { + + } + + @Override + public void onActivityPaused(Activity activity) { + + } + + @Override + public void onActivityStopped(Activity activity) { + + } + + @Override + public void onActivitySaveInstanceState(Activity activity, Bundle outState) { + + } + + @Override + public void onActivityDestroyed(Activity activity) { + + } } } diff --git a/app/src/main/java/com/stardust/scriptdroid/AssistModeSwitchService.java b/app/src/main/java/com/stardust/scriptdroid/AssistModeSwitchService.java index f9e43707..8d0fbdc2 100644 --- a/app/src/main/java/com/stardust/scriptdroid/AssistModeSwitchService.java +++ b/app/src/main/java/com/stardust/scriptdroid/AssistModeSwitchService.java @@ -6,7 +6,7 @@ import android.content.Intent; import android.os.IBinder; import android.support.annotation.Nullable; -import com.stardust.scriptdroid.droid.assist.Assistant; +import com.stardust.scriptdroid.droid.assist.BoundsAssistant; import static com.stardust.scriptdroid.ui.AssistModeSwitchNotification.KEY_ASSIST_MODE_NOTIFICATION; @@ -15,10 +15,18 @@ import static com.stardust.scriptdroid.ui.AssistModeSwitchNotification.KEY_ASSIS */ public class AssistModeSwitchService extends Service { + + private static final String EXTRA_INTENT_VALID = "intentValid"; + private static final String EXTRA_ACTION = "action"; + + private static final int ACTION_TOGGLE_ASSIST_MODE = 1; + private static final int ACTION_CANCEL_ASSIST_MODE_NOTIFICATION = 2; + + public static PendingIntent getStartIntent() { Intent intent = new Intent(App.getApp(), AssistModeSwitchService.class) - .putExtra("intentValid", true) - .putExtra("switch", "assistMode"); + .putExtra(EXTRA_INTENT_VALID, true) + .putExtra(EXTRA_ACTION, ACTION_TOGGLE_ASSIST_MODE); return PendingIntent.getService(App.getApp(), 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); } @@ -26,19 +34,23 @@ public class AssistModeSwitchService extends Service { public int onStartCommand(Intent intent, int flags, int startId) { boolean intentValid = intent.getBooleanExtra("intentValid", false); if (intentValid) { - String action = intent.getStringExtra("switch"); - if (action != null) { - if (action.equals("assistMode")) { - Assistant.setAssistModeEnable(!Assistant.isAssistModeEnable()); - } else { - App.getStateObserver().setState(KEY_ASSIST_MODE_NOTIFICATION, false); - } - } + performAction(intent.getIntExtra(EXTRA_ACTION, 0)); } stopSelf(); return super.onStartCommand(intent, flags, startId); } + private void performAction(int action) { + switch (action) { + case ACTION_TOGGLE_ASSIST_MODE: + BoundsAssistant.setAssistModeEnable(!BoundsAssistant.isAssistModeEnable()); + break; + case ACTION_CANCEL_ASSIST_MODE_NOTIFICATION: + App.getStateObserver().setState(KEY_ASSIST_MODE_NOTIFICATION, false); + break; + } + } + @Nullable @Override public IBinder onBind(Intent intent) { @@ -47,8 +59,8 @@ public class AssistModeSwitchService extends Service { public static PendingIntent getDeletePendingIntent() { Intent deleteIntent = new Intent(App.getApp(), AssistModeSwitchService.class) - .putExtra("intentValid", true) - .putExtra("switch", "assistModeNotification"); + .putExtra(EXTRA_INTENT_VALID, true) + .putExtra(EXTRA_ACTION, ACTION_CANCEL_ASSIST_MODE_NOTIFICATION); return PendingIntent.getService(App.getApp(), 0, deleteIntent, PendingIntent.FLAG_ONE_SHOT); } } diff --git a/app/src/main/java/com/stardust/scriptdroid/EditActivity.java b/app/src/main/java/com/stardust/scriptdroid/EditActivity.java index 86f2d2e8..831d9767 100644 --- a/app/src/main/java/com/stardust/scriptdroid/EditActivity.java +++ b/app/src/main/java/com/stardust/scriptdroid/EditActivity.java @@ -19,7 +19,6 @@ import com.jecelyin.editor.v2.ui.EditorDelegate; import com.jecelyin.editor.v2.view.EditorView; import com.jecelyin.editor.v2.view.menu.MenuDef; import com.stardust.scriptdroid.droid.Droid; -import com.stardust.scriptdroid.droid.runtime.DroidRuntime; import com.stardust.scriptdroid.editor920.Editor920Activity; import com.stardust.scriptdroid.ui.AssistClipListRecyclerView; import com.stardust.scriptdroid.ui.EditSideMenuFragment; @@ -58,7 +57,6 @@ public class EditActivity extends Editor920Activity { public void onCreate(Bundle b) { super.onCreate(b); - DroidRuntime.setContext(this); handleIntent(); setUpUI(); setUpEditor(); diff --git a/app/src/main/java/com/stardust/scriptdroid/ErrorReportActivity.java b/app/src/main/java/com/stardust/scriptdroid/ErrorReportActivity.java index 62cf892b..10ce199c 100644 --- a/app/src/main/java/com/stardust/scriptdroid/ErrorReportActivity.java +++ b/app/src/main/java/com/stardust/scriptdroid/ErrorReportActivity.java @@ -6,6 +6,8 @@ import android.os.Build; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.v7.widget.Toolbar; +import android.util.Log; +import android.widget.TextView; import android.widget.Toast; import com.afollestad.materialdialogs.DialogAction; @@ -20,22 +22,29 @@ import java.util.TimerTask; public class ErrorReportActivity extends BaseActivity { + private static final String TAG = "ErrorReportActivity"; + protected void onCreate(Bundle savedInstanceState) { try { super.onCreate(savedInstanceState); setUpUI(); handleIntent(); - } catch (Throwable throwable) { - throwable.printStackTrace(); + Log.e(TAG, "", throwable); } } private void handleIntent() { String message = getIntent().getStringExtra("message"); final String errorDetail = getIntent().getStringExtra("error"); + //showErrorMessage(message, errorDetail); + showErrorMessageByDialog(message, errorDetail); + } + + private void showErrorMessageByDialog(String message, final String errorDetail) { new MaterialDialog.Builder(this) - .content(message) + .title(R.string.text_crash) + .content(R.string.crash_feedback) .positiveText(R.string.text_exit) .negativeText(R.string.text_copy_debug_info) .onPositive(new MaterialDialog.SingleButtonCallback() { @@ -55,6 +64,10 @@ public class ErrorReportActivity extends BaseActivity { .show(); } + private void showErrorMessage(String message, String errorDetail) { + ((TextView) findViewById(R.id.error)).setText(message + "\n" + errorDetail); + } + private String getDeviceMessage() { return "Android: " + Build.VERSION.SDK_INT + "\n"; } @@ -86,13 +99,13 @@ public class ErrorReportActivity extends BaseActivity { getSupportActionBar().setHomeButtonEnabled(false); } - private void exit() { - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { - finishAffinity(); - } else { - finish(); - } + @Override + public void onBackPressed() { + exit(); + } + private void exit() { + finishAffinity(); } } diff --git a/app/src/main/java/com/stardust/scriptdroid/MainActivity.java b/app/src/main/java/com/stardust/scriptdroid/MainActivity.java index e09f3d99..37411b4f 100644 --- a/app/src/main/java/com/stardust/scriptdroid/MainActivity.java +++ b/app/src/main/java/com/stardust/scriptdroid/MainActivity.java @@ -54,7 +54,7 @@ public class MainActivity extends BaseActivity implements FileChooserDialog.File private void goToAccessibilityPermissionSettingIfDisabled() { if (!AccessibilityServiceUtils.isAccessibilityServiceEnabled(this, ActionPerformService.class)) { - new NotRemindAgainDialog.Builder(this) + new NotRemindAgainDialog.Builder(this, "goToAccessibilityPermissionSettingIfDisabled") .title(R.string.text_alert) .content(R.string.explain_accessibility_permission) .positiveText(R.string.text_go_to_setting) @@ -62,7 +62,7 @@ public class MainActivity extends BaseActivity implements FileChooserDialog.File .onPositive(new MaterialDialog.SingleButtonCallback() { @Override public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) { - AccessibilityServiceUtils.goToPermissionSetting(MainActivity.this); + AccessibilityServiceUtils.goToAccessibilitySetting(MainActivity.this); } }).show(); } diff --git a/app/src/main/java/com/stardust/scriptdroid/NonUiInitializer.java b/app/src/main/java/com/stardust/scriptdroid/NonUiInitializer.java index 503b6d22..554ace67 100644 --- a/app/src/main/java/com/stardust/scriptdroid/NonUiInitializer.java +++ b/app/src/main/java/com/stardust/scriptdroid/NonUiInitializer.java @@ -18,7 +18,9 @@ public class NonUiInitializer { private static final Map SAMPLES = new MapEntries() .entry("sample_open_wechat_moment.js", R.string.text_sample_open_what_moment) .entry("sample_open_running_services.js", R.string.text_sample_open_running_services) - .entry("sample_hello_big_sister.js", R.string.text_sample_hello_big_sister) + .entry("sample_qq_hongbao.js", R.string.text_sample_qq_hongbao) + .entry("sample_simple_calculator.js", R.string.text_sample_simple_calculator) + .entry("sample_force_qq_chat.js", R.string.text_sample_for_qq_chat) .map(); private static NonUiInitializer instance = new NonUiInitializer(); @@ -41,21 +43,25 @@ public class NonUiInitializer { } } - private void copySampleScriptFile() { + public int copySampleScriptFile() { ScriptFileList list = SharedPrefScriptFileList.getInstance(); - int succeedCount = 0; + int failCount = 0; for (Map.Entry entry : SAMPLES.entrySet()) { String assetFile = entry.getKey(); String name = getContext().getString(entry.getValue()); String path = ScriptFile.DEFAULT_FOLDER + name + ".js"; - if (FileUtils.copyAsset(assetFile, path)) { - list.add(new ScriptFile(name, path)); - succeedCount++; + if (!list.containsPath(path)) { + if (FileUtils.copyAsset(assetFile, path)) { + list.add(new ScriptFile(name, path)); + } else { + failCount++; + } } } - if (succeedCount > 0) { + if (failCount > 0) { Pref.def().edit().putBoolean(Pref.SAMPLE_SCRIPTS_COPIED, true).apply(); } + return failCount; } } diff --git a/app/src/main/java/com/stardust/scriptdroid/Pref.java b/app/src/main/java/com/stardust/scriptdroid/Pref.java index a7181626..db9b07e4 100644 --- a/app/src/main/java/com/stardust/scriptdroid/Pref.java +++ b/app/src/main/java/com/stardust/scriptdroid/Pref.java @@ -1,5 +1,6 @@ package com.stardust.scriptdroid; +import android.content.Context; import android.content.SharedPreferences; import android.preference.PreferenceManager; @@ -8,10 +9,28 @@ import android.preference.PreferenceManager; */ public class Pref { + private static final SharedPreferences DISPOSABLE_BOOLEAN = App.getApp().getSharedPreferences("DISPOSABLE_BOOLEAN", Context.MODE_PRIVATE); + public static final String SAMPLE_SCRIPTS_COPIED = "SAMPLE_SCRIPTS_COPIED"; + public static SharedPreferences def() { return PreferenceManager.getDefaultSharedPreferences(App.getApp()); } + public static boolean isFirstEnableAssistMode() { + return getDisposableBoolean("isFirstEnableAssistMode", true); + } + + private static boolean getDisposableBoolean(String key, boolean defaultValue) { + boolean b = DISPOSABLE_BOOLEAN.getBoolean(key, defaultValue); + if (b == defaultValue) { + DISPOSABLE_BOOLEAN.edit().putBoolean(key, !defaultValue).apply(); + } + return b; + } + + public static boolean isFirstGoToAccessibilitySetting() { + return getDisposableBoolean("isFirstGoToAccessibilitySetting", true); + } } diff --git a/app/src/main/java/com/stardust/scriptdroid/SettingsActivity.java b/app/src/main/java/com/stardust/scriptdroid/SettingsActivity.java index 66c27ff7..25d95356 100644 --- a/app/src/main/java/com/stardust/scriptdroid/SettingsActivity.java +++ b/app/src/main/java/com/stardust/scriptdroid/SettingsActivity.java @@ -7,6 +7,7 @@ import android.preference.PreferenceScreen; import android.support.annotation.Nullable; import android.support.v7.widget.Toolbar; import android.view.View; +import android.widget.Toast; import com.stardust.util.MapEntries; @@ -61,6 +62,16 @@ public class SettingsActivity extends BaseActivity { public void onStart() { super.onStart(); ACTION_MAP = new MapEntries() + .entry(getString(R.string.text_re_import_samples), new Runnable() { + @Override + public void run() { + int failCount = NonUiInitializer.getInstance().copySampleScriptFile(); + if (failCount <= 0) { + Toast.makeText(getActivity(), R.string.text_re_import_succeed, Toast.LENGTH_SHORT).show(); + } else + Toast.makeText(getActivity(), R.string.text_fail, Toast.LENGTH_SHORT).show(); + } + }) .entry(getString(R.string.text_about), new Runnable() { @Override public void run() { diff --git a/app/src/main/java/com/stardust/scriptdroid/droid/Droid.java b/app/src/main/java/com/stardust/scriptdroid/droid/Droid.java index f9e989ec..845ed94f 100644 --- a/app/src/main/java/com/stardust/scriptdroid/droid/Droid.java +++ b/app/src/main/java/com/stardust/scriptdroid/droid/Droid.java @@ -1,10 +1,15 @@ package com.stardust.scriptdroid.droid; +import android.app.Activity; +import android.content.DialogInterface; + +import com.afollestad.materialdialogs.MaterialDialog; import com.stardust.scriptdroid.App; import com.stardust.scriptdroid.R; import com.stardust.scriptdroid.droid.runtime.DroidRuntime; import com.stardust.scriptdroid.droid.script.DuktapeJavaScriptEngine; import com.stardust.scriptdroid.droid.script.JavaScriptEngine; +import com.stardust.scriptdroid.droid.script.ScriptExecuteActivity; import com.stardust.scriptdroid.file.FileUtils; import java.io.File; @@ -16,12 +21,14 @@ import java.io.FileNotFoundException; public class Droid { + public static final String UI = "\"ui\";"; + public interface OnRunFinishedListener { void onRunFinished(Object result, Exception e); } private static final DroidRuntime RUNTIME = DroidRuntime.getRuntime(); - private static final JavaScriptEngine JAVA_SCRIPT_ENGINE = new DuktapeJavaScriptEngine(RUNTIME); + public static final JavaScriptEngine JAVA_SCRIPT_ENGINE = new DuktapeJavaScriptEngine(RUNTIME); private static final OnRunFinishedListener DEFAULT_LISTENER = new OnRunFinishedListener() { @Override public void onRunFinished(Object result, Exception e) { @@ -33,7 +40,6 @@ public class Droid { private static Droid instance = new Droid(); protected Droid() { - } public static Droid getInstance() { @@ -59,8 +65,13 @@ public class Droid { } public void runScript(final String script, OnRunFinishedListener listener, RunningConfig config) { + listener = listener == null ? DEFAULT_LISTENER : listener; if (config.runInNewThread) { - new Thread(new RunScriptRunnable(script, listener, config)).start(); + if (script.startsWith(UI)) { + ScriptExecuteActivity.runScript(script, listener, config); + } else { + new Thread(new RunScriptRunnable(script, listener, config)).start(); + } } else { new RunScriptRunnable(script, listener, config).run(); } @@ -72,11 +83,6 @@ public class Droid { return JAVA_SCRIPT_ENGINE.stopAll(); } - - public void ensureNotStopped() { - JAVA_SCRIPT_ENGINE.ensureNotStopped(); - } - private void checkFile(File file) { if (file == null) { throw new NullPointerException("file = null"); @@ -95,8 +101,8 @@ public class Droid { private final String mScript; private OnRunFinishedListener mOnRunFinishedListener; - public RunScriptRunnable(String script, OnRunFinishedListener listener, RunningConfig config) { - mOnRunFinishedListener = listener == null ? DEFAULT_LISTENER : listener; + RunScriptRunnable(String script, OnRunFinishedListener listener, RunningConfig config) { + mOnRunFinishedListener = listener; mScript = script; } @@ -108,5 +114,10 @@ public class Droid { mOnRunFinishedListener.onRunFinished(null, e); } } + + public RunScriptRunnable setActivity(Activity a) { + JAVA_SCRIPT_ENGINE.set("activity", Activity.class, a); + return this; + } } } diff --git a/app/src/main/java/com/stardust/scriptdroid/droid/assist/AssistClipList.java b/app/src/main/java/com/stardust/scriptdroid/droid/assist/BoundsAssistClipList.java similarity index 90% rename from app/src/main/java/com/stardust/scriptdroid/droid/assist/AssistClipList.java rename to app/src/main/java/com/stardust/scriptdroid/droid/assist/BoundsAssistClipList.java index 1dc779be..0e123a71 100644 --- a/app/src/main/java/com/stardust/scriptdroid/droid/assist/AssistClipList.java +++ b/app/src/main/java/com/stardust/scriptdroid/droid/assist/BoundsAssistClipList.java @@ -4,7 +4,7 @@ package com.stardust.scriptdroid.droid.assist; * Created by Stardust on 2017/2/4. */ -public interface AssistClipList { +public interface BoundsAssistClipList { interface OnClipChangedListener { void onClipRemove(int position); diff --git a/app/src/main/java/com/stardust/scriptdroid/droid/assist/Assistant.java b/app/src/main/java/com/stardust/scriptdroid/droid/assist/BoundsAssistant.java similarity index 70% rename from app/src/main/java/com/stardust/scriptdroid/droid/assist/Assistant.java rename to app/src/main/java/com/stardust/scriptdroid/droid/assist/BoundsAssistant.java index c6297ca4..27a14e6d 100644 --- a/app/src/main/java/com/stardust/scriptdroid/droid/assist/Assistant.java +++ b/app/src/main/java/com/stardust/scriptdroid/droid/assist/BoundsAssistant.java @@ -6,29 +6,43 @@ import android.view.accessibility.AccessibilityEvent; import android.view.accessibility.AccessibilityNodeInfo; import android.widget.Toast; +import com.afollestad.materialdialogs.MaterialDialog; import com.stardust.scriptdroid.App; +import com.stardust.scriptdroid.Pref; +import com.stardust.scriptdroid.R; /** * Created by Stardust on 2017/2/4. */ -public class Assistant { +public class BoundsAssistant { public static final String KEY_ASSIST_MODE_ENABLE = "ASSIST_MODE_ENABLE"; private static boolean assistModeEnable; - private static AssistClipList assistClipList = SharedPrefAssistClipList.getInstance(); + private static BoundsAssistClipList boundsAssistClipList = SharedPrefBoundsAssistClipList.getInstance(); public static boolean isAssistModeEnable() { return assistModeEnable; } public static void setAssistModeEnable(boolean assistModeEnable) { - Assistant.assistModeEnable = assistModeEnable; + if (assistModeEnable && Pref.isFirstEnableAssistMode()) { + showAssistModeInfoDialog(); + } + BoundsAssistant.assistModeEnable = assistModeEnable; App.getStateObserver().setState(KEY_ASSIST_MODE_ENABLE, assistModeEnable); } + private static void showAssistModeInfoDialog() { + new MaterialDialog.Builder(App.currentActivity()) + .title(R.string.text_alert) + .content(R.string.assist_mode_notice) + .positiveText(R.string.ok) + .show(); + } + public static void performAssistance(AccessibilityEvent event) { if (!assistModeEnable) { return; @@ -53,7 +67,7 @@ public class Assistant { private static void saveAndAlertBounds(Rect rect) { String str = rect.toString().replace('-', ',').replace(" ", "").substring(4); - assistClipList.add(str); + boundsAssistClipList.add(str); Toast.makeText(App.getApp(), str, Toast.LENGTH_SHORT).show(); } diff --git a/app/src/main/java/com/stardust/scriptdroid/droid/assist/SharedPrefAssistClipList.java b/app/src/main/java/com/stardust/scriptdroid/droid/assist/SharedPrefBoundsAssistClipList.java similarity index 84% rename from app/src/main/java/com/stardust/scriptdroid/droid/assist/SharedPrefAssistClipList.java rename to app/src/main/java/com/stardust/scriptdroid/droid/assist/SharedPrefBoundsAssistClipList.java index aeec9f82..8715c6b0 100644 --- a/app/src/main/java/com/stardust/scriptdroid/droid/assist/SharedPrefAssistClipList.java +++ b/app/src/main/java/com/stardust/scriptdroid/droid/assist/SharedPrefBoundsAssistClipList.java @@ -15,24 +15,24 @@ import java.util.List; * Created by Stardust on 2017/2/4. */ -public class SharedPrefAssistClipList implements AssistClipList { +public class SharedPrefBoundsAssistClipList implements BoundsAssistClipList { private static final Gson GSON = new Gson(); - private static SharedPrefAssistClipList instance = new SharedPrefAssistClipList(App.getApp()); + private static SharedPrefBoundsAssistClipList instance = new SharedPrefBoundsAssistClipList(App.getApp()); private OnClipChangedListener mOnClipChangedListener; - public static SharedPrefAssistClipList getInstance() { + public static SharedPrefBoundsAssistClipList getInstance() { return instance; } private static final int MAX_SIZE = 10; - private static final String SHARED_PREF_NAME = "SharedPrefAssistClipList"; + private static final String SHARED_PREF_NAME = "SharedPrefBoundsAssistClipList"; private SharedPreferences mSharedPreferences; private List mAssistClipList = new LinkedList<>(); - public SharedPrefAssistClipList(Context context) { + public SharedPrefBoundsAssistClipList(Context context) { mSharedPreferences = context.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE); readFromSharedPref(); } diff --git a/app/src/main/java/com/stardust/scriptdroid/droid/runtime/DroidRuntime.java b/app/src/main/java/com/stardust/scriptdroid/droid/runtime/DroidRuntime.java index dc734982..b117ad7f 100644 --- a/app/src/main/java/com/stardust/scriptdroid/droid/runtime/DroidRuntime.java +++ b/app/src/main/java/com/stardust/scriptdroid/droid/runtime/DroidRuntime.java @@ -1,6 +1,5 @@ package com.stardust.scriptdroid.droid.runtime; -import android.content.Context; import android.content.Intent; import android.content.pm.ApplicationInfo; import android.content.pm.PackageManager; @@ -12,7 +11,6 @@ import android.widget.Toast; import com.afollestad.materialdialogs.MaterialDialog; import com.stardust.scriptdroid.App; import com.stardust.scriptdroid.R; -import com.stardust.scriptdroid.droid.Droid; import com.stardust.scriptdroid.droid.runtime.action.Action; import com.stardust.scriptdroid.droid.runtime.action.ActionFactory; import com.stardust.scriptdroid.droid.runtime.action.ActionPerformService; @@ -21,6 +19,8 @@ import com.stardust.scriptdroid.droid.runtime.api.IDroidRuntime; import java.util.List; +; + /** * Created by Stardust on 2017/1/27. */ @@ -29,21 +29,15 @@ public class DroidRuntime implements IDroidRuntime { private static final String TAG = "DroidRuntime"; private static DroidRuntime runtime = new DroidRuntime(); - private static Context context; private final Object mLock = new Object(); private boolean mActionPerformResult; - private boolean mActionPerformResultUpToDate; private Handler mUIHandler; public static DroidRuntime getRuntime() { return runtime; } - public static void setContext(Context context) { - DroidRuntime.context = context; - } - protected DroidRuntime() { mUIHandler = new Handler(App.getApp().getMainLooper()); } @@ -143,25 +137,20 @@ public class DroidRuntime implements IDroidRuntime { private boolean performAction(Action action) { if (ActionPerformService.getInstance() == null) { toast(App.getApp().getString(R.string.text_no_accessibility_permission)); - throw new PermissionDeniedException(App.getApp().getString(R.string.text_no_accessibility_permission)); + throw new ScriptStopException(App.getApp().getString(R.string.text_no_accessibility_permission)); } - ensureNotStopped(); ActionPerformService.setAction(action); synchronized (mLock) { try { mLock.wait(); } catch (InterruptedException e) { - throw new PermissionDeniedException("已停止运行"); + ActionPerformService.setActions(ActionPerformService.NO_ACTION); + throw new ScriptStopException(App.getApp().getString(R.string.text_script_stopped), e); } } return mActionPerformResult; } - private void ensureNotStopped() { - Droid.getInstance().ensureNotStopped(); - } - - @Override public void toast(final String text) { mUIHandler.post(new Runnable() { @@ -172,18 +161,48 @@ public class DroidRuntime implements IDroidRuntime { }); } + @Override public void sleep(long millis) { try { Thread.sleep(millis); } catch (InterruptedException e) { - e.printStackTrace(); + throw new ScriptStopException(e); } } + @Override + public boolean isStopped() { + return Thread.currentThread().isInterrupted(); + } + + @Override + public void stop() { + Thread.interrupted(); + } + @Override public MaterialDialog.Builder dialog() { - return new Builder(); + if (App.currentActivity() == null) { + Toast.makeText(App.getApp(), R.string.text_cannot_create_dialog_when_app_invisible, Toast.LENGTH_SHORT).show(); + throw new ScriptStopException(App.getApp().getString(R.string.text_cannot_create_dialog_when_app_invisible)); + } + return new MaterialDialog.Builder(App.currentActivity()) { + + public MaterialDialog show() { + mUIHandler.post(new Runnable() { + @Override + public void run() { + superShow(); + } + }); + return null; + } + + private void superShow() { + super.show(); + } + }; } public void notifyActionPerformed(boolean succeed) { @@ -193,16 +212,4 @@ public class DroidRuntime implements IDroidRuntime { } } - public class Builder extends MaterialDialog.Builder { - - public Builder() { - super(DroidRuntime.context); - } - - public MaterialDialog show(final MaterialDialog.Builder dialog) { - - return null; - } - } - } diff --git a/app/src/main/java/com/stardust/scriptdroid/droid/runtime/PermissionDeniedException.java b/app/src/main/java/com/stardust/scriptdroid/droid/runtime/PermissionDeniedException.java deleted file mode 100644 index cea2ac8e..00000000 --- a/app/src/main/java/com/stardust/scriptdroid/droid/runtime/PermissionDeniedException.java +++ /dev/null @@ -1,10 +0,0 @@ -package com.stardust.scriptdroid.droid.runtime; - -/** - * Created by Stardust on 2017/1/29. - */ -public class PermissionDeniedException extends RuntimeException { - public PermissionDeniedException(String message) { - super(message); - } -} diff --git a/app/src/main/java/com/stardust/scriptdroid/droid/runtime/ScriptStopException.java b/app/src/main/java/com/stardust/scriptdroid/droid/runtime/ScriptStopException.java new file mode 100644 index 00000000..b31da3a1 --- /dev/null +++ b/app/src/main/java/com/stardust/scriptdroid/droid/runtime/ScriptStopException.java @@ -0,0 +1,24 @@ +package com.stardust.scriptdroid.droid.runtime; + +/** + * Created by Stardust on 2017/1/29. + */ +public class ScriptStopException extends RuntimeException { + + + public ScriptStopException(String message, Throwable cause) { + super(message, cause); + } + + public ScriptStopException(String message) { + super(message); + } + + public ScriptStopException() { + + } + + public ScriptStopException(Throwable cause) { + super(cause); + } +} diff --git a/app/src/main/java/com/stardust/scriptdroid/droid/runtime/action/ActionPerformService.java b/app/src/main/java/com/stardust/scriptdroid/droid/runtime/action/ActionPerformService.java index b90764b0..da88bfb0 100644 --- a/app/src/main/java/com/stardust/scriptdroid/droid/runtime/action/ActionPerformService.java +++ b/app/src/main/java/com/stardust/scriptdroid/droid/runtime/action/ActionPerformService.java @@ -7,7 +7,7 @@ import android.view.accessibility.AccessibilityEvent; import android.view.accessibility.AccessibilityNodeInfo; import com.stardust.scriptdroid.App; -import com.stardust.scriptdroid.droid.assist.Assistant; +import com.stardust.scriptdroid.droid.assist.BoundsAssistant; import com.stardust.scriptdroid.droid.runtime.DroidRuntime; import com.stardust.view.accessibility.AccessibilityServiceUtils; @@ -53,7 +53,7 @@ public class ActionPerformService extends AccessibilityService { @Override public void onAccessibilityEvent(AccessibilityEvent event) { Log.v(TAG, "onAccessibilityEvent: state=" + state + " event=" + event); - Assistant.performAssistance(event); + BoundsAssistant.performAssistance(event); if (state == STATE_INACTIVE) return; AccessibilityNodeInfo root = getRootInActiveWindow(); @@ -103,8 +103,12 @@ public class ActionPerformService extends AccessibilityService { } public static void disable() { - if (instance != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { - instance.disableSelf(); + if (instance != null) { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { + instance.disableSelf(); + } else { + AccessibilityServiceUtils.goToAccessibilitySetting(App.getApp()); + } } } diff --git a/app/src/main/java/com/stardust/scriptdroid/droid/runtime/api/IDroidRuntime.java b/app/src/main/java/com/stardust/scriptdroid/droid/runtime/api/IDroidRuntime.java index 9b79b565..0def225f 100644 --- a/app/src/main/java/com/stardust/scriptdroid/droid/runtime/api/IDroidRuntime.java +++ b/app/src/main/java/com/stardust/scriptdroid/droid/runtime/api/IDroidRuntime.java @@ -42,5 +42,9 @@ public interface IDroidRuntime { void sleep(long millis); + boolean isStopped(); + + void stop(); + MaterialDialog.Builder dialog(); } diff --git a/app/src/main/java/com/stardust/scriptdroid/droid/script/DuktapeJavaScriptEngine.java b/app/src/main/java/com/stardust/scriptdroid/droid/script/DuktapeJavaScriptEngine.java index b7b97d65..b4ce7dc6 100644 --- a/app/src/main/java/com/stardust/scriptdroid/droid/script/DuktapeJavaScriptEngine.java +++ b/app/src/main/java/com/stardust/scriptdroid/droid/script/DuktapeJavaScriptEngine.java @@ -3,7 +3,7 @@ package com.stardust.scriptdroid.droid.script; import com.efurture.script.JSTransformer; import com.furture.react.DuktapeEngine; import com.stardust.scriptdroid.App; -import com.stardust.scriptdroid.R; +import com.stardust.scriptdroid.droid.Droid; import com.stardust.scriptdroid.droid.runtime.api.IDroidRuntime; import java.io.IOException; @@ -34,7 +34,6 @@ public class DuktapeJavaScriptEngine implements JavaScriptEngine { public DuktapeJavaScriptEngine(IDroidRuntime runtime) { setRuntime(runtime); - } private void setRuntime(IDroidRuntime runtime) { @@ -50,13 +49,15 @@ public class DuktapeJavaScriptEngine implements JavaScriptEngine { try { result = duktapeEngine.execute(JSTransformer.parse(new StringReader(script))); } catch (IOException e) { - remove(Thread.currentThread()); + removeAndStop(Thread.currentThread()); throw e; } - remove(Thread.currentThread()); + if (!script.startsWith(Droid.UI)) + removeAndDestroy(Thread.currentThread()); return result; } + private void init(DuktapeEngine duktapeEngine) { duktapeEngine.put("context", App.getApp()); duktapeEngine.execute(INIT_SCRIPT); @@ -66,13 +67,23 @@ public class DuktapeJavaScriptEngine implements JavaScriptEngine { } - private void remove(Thread thread) { + public void removeAndStop(Thread thread) { synchronized (mThreadDuktapeEngineMap) { DuktapeEngine engine = mThreadDuktapeEngineMap.remove(thread); stop(engine, thread); } } + + @Override + public void removeAndDestroy(Thread thread) { + synchronized (mThreadDuktapeEngineMap) { + DuktapeEngine engine = mThreadDuktapeEngineMap.remove(thread); + if (engine != null) + engine.destory(); + } + } + private void stop(DuktapeEngine engine, Thread thread) { if (engine != null) engine.destory(); @@ -107,10 +118,4 @@ public class DuktapeJavaScriptEngine implements JavaScriptEngine { return n; } - @Override - public void ensureNotStopped() { - if (!mThreadDuktapeEngineMap.containsKey(Thread.currentThread())) { - throw new RuntimeException(App.getApp().getString(R.string.text_script_stopped)); - } - } } diff --git a/app/src/main/java/com/stardust/scriptdroid/droid/script/JavaScriptEngine.java b/app/src/main/java/com/stardust/scriptdroid/droid/script/JavaScriptEngine.java index 37ee0ea0..8909a275 100644 --- a/app/src/main/java/com/stardust/scriptdroid/droid/script/JavaScriptEngine.java +++ b/app/src/main/java/com/stardust/scriptdroid/droid/script/JavaScriptEngine.java @@ -17,7 +17,7 @@ public interface JavaScriptEngine { int stopAll(); - void ensureNotStopped(); + void removeAndDestroy(Thread thread); class Init { public static final String INIT_SCRIPT = readInitScript(); diff --git a/app/src/main/java/com/stardust/scriptdroid/droid/script/ScriptExecuteActivity.java b/app/src/main/java/com/stardust/scriptdroid/droid/script/ScriptExecuteActivity.java new file mode 100644 index 00000000..0a1227b2 --- /dev/null +++ b/app/src/main/java/com/stardust/scriptdroid/droid/script/ScriptExecuteActivity.java @@ -0,0 +1,59 @@ +package com.stardust.scriptdroid.droid.script; + +import android.app.Activity; +import android.content.Intent; +import android.os.Bundle; + +import com.stardust.scriptdroid.App; +import com.stardust.scriptdroid.droid.Droid; +import com.stardust.scriptdroid.droid.RunningConfig; + +import static com.stardust.scriptdroid.droid.Droid.JAVA_SCRIPT_ENGINE; + +/** + * Created by Stardust on 2017/2/5. + */ + +public class ScriptExecuteActivity extends Activity { + + private static String script; + private static Droid.OnRunFinishedListener onRunFinishedListener; + private static RunningConfig runningConfig; + private Object mResult; + + + public static void runScript(String script, Droid.OnRunFinishedListener listener, RunningConfig config) { + ScriptExecuteActivity.script = script; + ScriptExecuteActivity.onRunFinishedListener = listener; + ScriptExecuteActivity.runningConfig = config; + App.getApp().startActivity(new Intent(App.getApp(), ScriptExecuteActivity.class)); + } + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + runScript(); + } + + private void runScript() { + JAVA_SCRIPT_ENGINE.set("activity", Activity.class, this); + try { + mResult = JAVA_SCRIPT_ENGINE.execute(script); + } catch (Exception e) { + onRunFinishedListener.onRunFinished(null, e); + finish(); + } + } + + @Override + public void finish() { + onRunFinishedListener.onRunFinished(mResult, null); + super.finish(); + } + + @Override + protected void onDestroy() { + super.onDestroy(); + JAVA_SCRIPT_ENGINE.removeAndDestroy(Thread.currentThread()); + } +} diff --git a/app/src/main/java/com/stardust/scriptdroid/droid/script/file/ScriptFileList.java b/app/src/main/java/com/stardust/scriptdroid/droid/script/file/ScriptFileList.java index 08c1cd95..55ac8080 100644 --- a/app/src/main/java/com/stardust/scriptdroid/droid/script/file/ScriptFileList.java +++ b/app/src/main/java/com/stardust/scriptdroid/droid/script/file/ScriptFileList.java @@ -25,4 +25,5 @@ public abstract class ScriptFileList { } + public abstract boolean containsPath(String path); } diff --git a/app/src/main/java/com/stardust/scriptdroid/droid/script/file/SharedPrefScriptFileList.java b/app/src/main/java/com/stardust/scriptdroid/droid/script/file/SharedPrefScriptFileList.java index 62a589cd..b2dea3aa 100644 --- a/app/src/main/java/com/stardust/scriptdroid/droid/script/file/SharedPrefScriptFileList.java +++ b/app/src/main/java/com/stardust/scriptdroid/droid/script/file/SharedPrefScriptFileList.java @@ -89,6 +89,11 @@ public class SharedPrefScriptFileList extends ScriptFileList { return mScriptPath.size(); } + @Override + public boolean containsPath(String path) { + return mScriptPath.contains(path); + } + protected void syncWithSharedPref() { SharedPreferences.Editor editor = mSharedPreferences.edit(); editor.putString(SP_KEY_SCRIPT_NAME, GSON.toJson(mScriptName)); diff --git a/app/src/main/java/com/stardust/scriptdroid/tile/BoundsAssistEnableTileService.java b/app/src/main/java/com/stardust/scriptdroid/tile/BoundsAssistEnableTileService.java index 0c71789b..e176a18c 100644 --- a/app/src/main/java/com/stardust/scriptdroid/tile/BoundsAssistEnableTileService.java +++ b/app/src/main/java/com/stardust/scriptdroid/tile/BoundsAssistEnableTileService.java @@ -5,7 +5,7 @@ import android.service.quicksettings.Tile; import android.service.quicksettings.TileService; import android.support.annotation.RequiresApi; -import com.stardust.scriptdroid.droid.assist.Assistant; +import com.stardust.scriptdroid.droid.assist.BoundsAssistant; /** * Created by Stardust on 2017/1/26. @@ -15,12 +15,12 @@ import com.stardust.scriptdroid.droid.assist.Assistant; public class BoundsAssistEnableTileService extends TileService { public void onClick() { - Assistant.setAssistModeEnable(!Assistant.isAssistModeEnable()); + BoundsAssistant.setAssistModeEnable(!BoundsAssistant.isAssistModeEnable()); updateTile(); } private void updateTile() { - getQsTile().setState(Assistant.isAssistModeEnable() ? Tile.STATE_ACTIVE : Tile.STATE_INACTIVE); + getQsTile().setState(BoundsAssistant.isAssistModeEnable() ? Tile.STATE_ACTIVE : Tile.STATE_INACTIVE); getQsTile().updateTile(); } diff --git a/app/src/main/java/com/stardust/scriptdroid/ui/AssistClipListRecyclerView.java b/app/src/main/java/com/stardust/scriptdroid/ui/AssistClipListRecyclerView.java index ffeb15ca..3bd7a963 100644 --- a/app/src/main/java/com/stardust/scriptdroid/ui/AssistClipListRecyclerView.java +++ b/app/src/main/java/com/stardust/scriptdroid/ui/AssistClipListRecyclerView.java @@ -11,8 +11,8 @@ import android.view.ViewGroup; import android.widget.TextView; import com.stardust.scriptdroid.R; -import com.stardust.scriptdroid.droid.assist.AssistClipList; -import com.stardust.scriptdroid.droid.assist.SharedPrefAssistClipList; +import com.stardust.scriptdroid.droid.assist.BoundsAssistClipList; +import com.stardust.scriptdroid.droid.assist.SharedPrefBoundsAssistClipList; import com.stardust.scriptdroid.widget.ExpandableRecyclerView; /** @@ -25,7 +25,7 @@ public class AssistClipListRecyclerView extends ExpandableRecyclerView { void onClick(String clip, int position); } - private AssistClipList mAssistClipList = SharedPrefAssistClipList.getInstance(); + private BoundsAssistClipList mBoundsAssistClipList = SharedPrefBoundsAssistClipList.getInstance(); private OnClipClickListener mOnClipClickListener; public AssistClipListRecyclerView(Context context) { @@ -55,7 +55,7 @@ public class AssistClipListRecyclerView extends ExpandableRecyclerView { } } }); - mAssistClipList.setOnClipChangedListener(new AssistClipList.OnClipChangedListener() { + mBoundsAssistClipList.setOnClipChangedListener(new BoundsAssistClipList.OnClipChangedListener() { @Override public void onClipRemove(int position) { getAdapter().notifyItemRemoved(position); @@ -82,7 +82,7 @@ public class AssistClipListRecyclerView extends ExpandableRecyclerView { protected void onDetachedFromWindow() { super.onDetachedFromWindow(); //防止因mAssistClipList持有OnClipChangedListener引用从而导致这个RecyclerView及其Context被引用,内存泄漏 - mAssistClipList.setOnClipChangedListener(null); + mBoundsAssistClipList.setOnClipChangedListener(null); } private class Adapter extends ExpandableRecyclerView.DefaultTitleAdapter { @@ -100,12 +100,12 @@ public class AssistClipListRecyclerView extends ExpandableRecyclerView { @Override protected void onBindChildViewHolder(RecyclerView.ViewHolder holder, int position) { ChildViewHolder viewHolder = (ChildViewHolder) holder; - viewHolder.mTextView.setText(mAssistClipList.get(position)); + viewHolder.mTextView.setText(mBoundsAssistClipList.get(position)); } @Override protected int getChildItemCount() { - return mAssistClipList.size(); + return mBoundsAssistClipList.size(); } @Override diff --git a/app/src/main/java/com/stardust/scriptdroid/ui/AssistModeSwitchNotification.java b/app/src/main/java/com/stardust/scriptdroid/ui/AssistModeSwitchNotification.java index b22512d9..4e4cd4e0 100644 --- a/app/src/main/java/com/stardust/scriptdroid/ui/AssistModeSwitchNotification.java +++ b/app/src/main/java/com/stardust/scriptdroid/ui/AssistModeSwitchNotification.java @@ -9,7 +9,7 @@ import android.support.v4.app.NotificationCompat; import com.stardust.scriptdroid.App; import com.stardust.scriptdroid.AssistModeSwitchService; import com.stardust.scriptdroid.R; -import com.stardust.scriptdroid.droid.assist.Assistant; +import com.stardust.scriptdroid.droid.assist.BoundsAssistant; import com.stardust.util.StateObserver; @@ -44,7 +44,7 @@ public class AssistModeSwitchNotification { } } }); - App.getStateObserver().register(Assistant.KEY_ASSIST_MODE_ENABLE, new StateObserver.OnBooleanStateChangedListener() { + App.getStateObserver().register(BoundsAssistant.KEY_ASSIST_MODE_ENABLE, new StateObserver.OnBooleanStateChangedListener() { @Override public void onStateChanged(Boolean newState) { if (enable) { @@ -78,7 +78,7 @@ public class AssistModeSwitchNotification { .setAutoCancel(false) .setSmallIcon(R.drawable.ic_robot_head) .setDeleteIntent(AssistModeSwitchService.getDeletePendingIntent()) - .setContentText(Assistant.isAssistModeEnable() ? + .setContentText(BoundsAssistant.isAssistModeEnable() ? App.getApp().getString(R.string.text_assist_mode_enabled) : App.getApp().getString(R.string.text_assist_mode_disabled)) .setContentIntent(AssistModeSwitchService.getStartIntent()) diff --git a/app/src/main/java/com/stardust/scriptdroid/ui/EditSideMenuFragment.java b/app/src/main/java/com/stardust/scriptdroid/ui/EditSideMenuFragment.java index be0e65e4..f31a0b09 100644 --- a/app/src/main/java/com/stardust/scriptdroid/ui/EditSideMenuFragment.java +++ b/app/src/main/java/com/stardust/scriptdroid/ui/EditSideMenuFragment.java @@ -12,7 +12,7 @@ import android.view.ViewGroup; import com.stardust.scriptdroid.App; import com.stardust.scriptdroid.DocumentActivity; import com.stardust.scriptdroid.R; -import com.stardust.scriptdroid.droid.assist.Assistant; +import com.stardust.scriptdroid.droid.assist.BoundsAssistant; import com.stardust.view.ViewBinder; import com.stardust.view.ViewBinding; @@ -70,14 +70,14 @@ public class EditSideMenuFragment extends com.stardust.app.Fragment { } private void syncSwitchState() { - mAssistServiceSwitch.setChecked(Assistant.isAssistModeEnable()); + mAssistServiceSwitch.setChecked(BoundsAssistant.isAssistModeEnable()); mAssistServiceNotificationSwitch.setChecked(AssistModeSwitchNotification.isEnable()); } private void setUpSwitchCompat() { mAssistServiceSwitch = $(R.id.sw_assist_service); mAssistServiceNotificationSwitch = $(R.id.sw_assist_service_notification); - App.getStateObserver().register(Assistant.KEY_ASSIST_MODE_ENABLE, mAssistServiceSwitch); + App.getStateObserver().register(BoundsAssistant.KEY_ASSIST_MODE_ENABLE, mAssistServiceSwitch); App.getStateObserver().register(KEY_ASSIST_MODE_NOTIFICATION, mAssistServiceNotificationSwitch); } @@ -88,7 +88,7 @@ public class EditSideMenuFragment extends com.stardust.app.Fragment { @ViewBinding.Check(R.id.sw_assist_service) private void setAssistServiceEnable(boolean enable) { - Assistant.setAssistModeEnable(enable); + BoundsAssistant.setAssistModeEnable(enable); } @ViewBinding.Click(R.id.assist_service) diff --git a/app/src/main/java/com/stardust/scriptdroid/ui/FunctionListRecyclerView.java b/app/src/main/java/com/stardust/scriptdroid/ui/FunctionListRecyclerView.java index 4353fb6a..d8342aee 100644 --- a/app/src/main/java/com/stardust/scriptdroid/ui/FunctionListRecyclerView.java +++ b/app/src/main/java/com/stardust/scriptdroid/ui/FunctionListRecyclerView.java @@ -15,7 +15,10 @@ import com.stardust.scriptdroid.R; import com.stardust.scriptdroid.file.FileUtils; import com.stardust.scriptdroid.widget.ExpandableRecyclerView; +import java.text.Collator; import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; import java.util.List; /** @@ -91,7 +94,7 @@ public class FunctionListRecyclerView extends ExpandableRecyclerView { Adapter() { setIcon(R.drawable.ic_function_mathematical_green); - setTitle(R.string.text_function); + setTitle(R.string.text_common_function); } @Override @@ -136,6 +139,12 @@ public class FunctionListRecyclerView extends ExpandableRecyclerView { String[] str = f.split(" "); FUNCTION_LIST.add(new Function(str[0], str[1])); } - + final Comparator cmp = Collator.getInstance(); + Collections.sort(FUNCTION_LIST, new Comparator() { + @Override + public int compare(Function f1, Function f2) { + return cmp.compare(f1.description, f2.description); + } + }); } } diff --git a/app/src/main/java/com/stardust/scriptdroid/ui/SlideMenuFragment.java b/app/src/main/java/com/stardust/scriptdroid/ui/SlideMenuFragment.java index 8d09933a..aeffd475 100644 --- a/app/src/main/java/com/stardust/scriptdroid/ui/SlideMenuFragment.java +++ b/app/src/main/java/com/stardust/scriptdroid/ui/SlideMenuFragment.java @@ -15,7 +15,7 @@ import com.stardust.scriptdroid.App; import com.stardust.scriptdroid.DocumentActivity; import com.stardust.scriptdroid.R; import com.stardust.scriptdroid.droid.Droid; -import com.stardust.scriptdroid.droid.assist.Assistant; +import com.stardust.scriptdroid.droid.assist.BoundsAssistant; import com.stardust.scriptdroid.droid.runtime.action.ActionPerformService; import com.stardust.view.ViewBinder; import com.stardust.view.ViewBinding; @@ -60,7 +60,7 @@ public class SlideMenuFragment extends Fragment { mAutoOperateServiceSwitch.setChecked(ActionPerformService.isEnable()); } }, 450); - mAssistServiceSwitch.setChecked(Assistant.isAssistModeEnable()); + mAssistServiceSwitch.setChecked(BoundsAssistant.isAssistModeEnable()); mAssistServiceNotificationSwitch.setChecked(AssistModeSwitchNotification.isEnable()); } @@ -68,7 +68,7 @@ public class SlideMenuFragment extends Fragment { mAutoOperateServiceSwitch = $(R.id.sw_auto_operate_service); mAssistServiceSwitch = $(R.id.sw_assist_service); mAssistServiceNotificationSwitch = $(R.id.sw_assist_service_notification); - App.getStateObserver().register(Assistant.KEY_ASSIST_MODE_ENABLE, mAssistServiceSwitch); + App.getStateObserver().register(BoundsAssistant.KEY_ASSIST_MODE_ENABLE, mAssistServiceSwitch); App.getStateObserver().register(KEY_ASSIST_MODE_NOTIFICATION, mAssistServiceNotificationSwitch); } @@ -85,7 +85,7 @@ public class SlideMenuFragment extends Fragment { @ViewBinding.Check(R.id.sw_auto_operate_service) private void setAutoOperateServiceEnable(boolean enable) { if (enable && !ActionPerformService.isEnable()) { - AccessibilityServiceUtils.goToPermissionSetting(getContext()); + AccessibilityServiceUtils.goToAccessibilitySetting(getContext()); } else if (!enable && ActionPerformService.isEnable()) { ActionPerformService.disable(); } @@ -93,7 +93,7 @@ public class SlideMenuFragment extends Fragment { @ViewBinding.Check(R.id.sw_assist_service) private void setAssistServiceEnable(boolean enable) { - Assistant.setAssistModeEnable(enable); + BoundsAssistant.setAssistModeEnable(enable); } @ViewBinding.Click(R.id.assist_service) diff --git a/app/src/main/java/com/stardust/scriptdroid/widget/ExpandableRecyclerView.java b/app/src/main/java/com/stardust/scriptdroid/widget/ExpandableRecyclerView.java index ff65e3bd..a2c5bcac 100644 --- a/app/src/main/java/com/stardust/scriptdroid/widget/ExpandableRecyclerView.java +++ b/app/src/main/java/com/stardust/scriptdroid/widget/ExpandableRecyclerView.java @@ -80,11 +80,15 @@ public class ExpandableRecyclerView extends RecyclerView { } public void expand() { + if (mExpanded) + return; mExpanded = true; ((Adapter) getAdapter()).notifyExpanded(); } public void collapse() { + if (!mExpanded) + return; mExpanded = false; ((Adapter) getAdapter()).notifyCollapsed(); } @@ -95,17 +99,11 @@ public class ExpandableRecyclerView extends RecyclerView { public void notifyExpanded() { notifyItemChanged(0); - int n = getItemCount(); - for (int i = 1; i < n; i++) { - notifyItemInserted(i); - } + notifyItemRangeInserted(1, getChildItemCount()); } public void notifyCollapsed() { - int n = getChildItemCount(); - for (int i = 0; i < n; i++) { - notifyItemRemoved(1); - } + notifyItemRangeRemoved(1, getChildItemCount()); notifyItemChanged(0); } diff --git a/app/src/main/java/com/stardust/util/CrashHandler.java b/app/src/main/java/com/stardust/util/CrashHandler.java index ce3274c7..8982ca2f 100644 --- a/app/src/main/java/com/stardust/util/CrashHandler.java +++ b/app/src/main/java/com/stardust/util/CrashHandler.java @@ -25,8 +25,7 @@ public class CrashHandler implements UncaughtExceptionHandler { public void uncaughtException(Thread thread, Throwable ex) { try { - Log.e("CrashHandler", "Uncaught Exception!!!"); - ex.printStackTrace(); + Log.e(TAG, "Uncaught Exception", ex); String t = App.getApp().getString(R.string.sorry_for_crash) + ex.toString(); Intent intent = new Intent(App.getApp(), this.mErrorReportClass); intent.putExtra("message", t); diff --git a/app/src/main/java/com/stardust/util/StateObserver.java b/app/src/main/java/com/stardust/util/StateObserver.java index 553b9940..30b4558a 100644 --- a/app/src/main/java/com/stardust/util/StateObserver.java +++ b/app/src/main/java/com/stardust/util/StateObserver.java @@ -4,10 +4,10 @@ import android.content.SharedPreferences; import android.support.v7.widget.SwitchCompat; import java.lang.ref.WeakReference; +import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; -import java.util.Vector; /** * Created by Stardust on 2017/2/3. @@ -70,7 +70,10 @@ public class StateObserver { if (initialState != null) listener.initState(initialState); synchronized (mKeyStateListenersMap) { - getListenerListOrCreateIfNotExists(key).add(listener); + List listeners = getListenerListOrCreateIfNotExists(key); + synchronized (listener) { + listeners.add(listener); + } } } @@ -81,19 +84,25 @@ public class StateObserver { if (listeners == null) { return; } - listeners.remove(stateChangedListener); + synchronized (listeners) { + listeners.remove(stateChangedListener); + } } } public void setState(String key, T state) { synchronized (mKeyStateListenersMap) { List listeners = mKeyStateListenersMap.get(key); - if (listeners == null || listeners.isEmpty()) { + if (listeners == null) return; - } - if (listeners.get(0) instanceof OnBooleanStateChangedListener) { - mSharedPreferences.edit().putBoolean(key, (Boolean) state).apply(); - notifyBooleanStateChanged(listeners, (Boolean) state); + synchronized (listeners) { + if (listeners.isEmpty()) { + return; + } + if (listeners.get(0) instanceof OnBooleanStateChangedListener) { + mSharedPreferences.edit().putBoolean(key, (Boolean) state).apply(); + notifyBooleanStateChanged(listeners, (Boolean) state); + } } } } @@ -115,7 +124,7 @@ public class StateObserver { private List getListenerListOrCreateIfNotExists(String key) { List listeners = mKeyStateListenersMap.get(key); if (listeners == null) { - listeners = new Vector<>(); + listeners = new ArrayList<>(); mKeyStateListenersMap.put(key, listeners); } return listeners; diff --git a/app/src/main/java/com/stardust/view/ViewBinder.java b/app/src/main/java/com/stardust/view/ViewBinder.java index 68886070..237b2c0b 100644 --- a/app/src/main/java/com/stardust/view/ViewBinder.java +++ b/app/src/main/java/com/stardust/view/ViewBinder.java @@ -40,8 +40,10 @@ public class ViewBinder { public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { try { method.invoke(o, isChecked); - } catch (IllegalAccessException | InvocationTargetException e) { + } catch (IllegalAccessException e) { e.printStackTrace(); + } catch (InvocationTargetException e) { + throw new RuntimeException(e); } } }); diff --git a/app/src/main/java/com/stardust/view/accessibility/AccessibilityServiceUtils.java b/app/src/main/java/com/stardust/view/accessibility/AccessibilityServiceUtils.java index 5d8c90d8..f1421694 100644 --- a/app/src/main/java/com/stardust/view/accessibility/AccessibilityServiceUtils.java +++ b/app/src/main/java/com/stardust/view/accessibility/AccessibilityServiceUtils.java @@ -5,6 +5,10 @@ import android.content.Context; import android.content.Intent; import android.provider.Settings; import android.text.TextUtils; +import android.widget.Toast; + +import com.stardust.scriptdroid.Pref; +import com.stardust.scriptdroid.R; /** * Created by Stardust on 2017/1/26. @@ -12,7 +16,10 @@ import android.text.TextUtils; public class AccessibilityServiceUtils { - public static void goToPermissionSetting(Context context) { + public static void goToAccessibilitySetting(Context context) { + if (Pref.isFirstGoToAccessibilitySetting()) { + Toast.makeText(context, context.getString(R.string.text_please_choose) + context.getString(R.string.app_name), Toast.LENGTH_LONG).show(); + } context.startActivity(new Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS)); } diff --git a/app/src/main/res/layout/activity_error_report.xml b/app/src/main/res/layout/activity_error_report.xml index 2a656d5f..29c80fe8 100644 --- a/app/src/main/res/layout/activity_error_report.xml +++ b/app/src/main/res/layout/activity_error_report.xml @@ -1,6 +1,7 @@ @@ -20,4 +21,13 @@ + \ No newline at end of file diff --git a/app/src/main/res/layout/fragment_edit_side_menu.xml b/app/src/main/res/layout/fragment_edit_side_menu.xml index e4e1b2b6..785c0600 100644 --- a/app/src/main/res/layout/fragment_edit_side_menu.xml +++ b/app/src/main/res/layout/fragment_edit_side_menu.xml @@ -40,7 +40,7 @@ android:layout_height="20dp" android:layout_alignParentLeft="true" android:layout_margin="16dp" - android:src="@drawable/ic_service_green"/> + android:src="@drawable/ic_robot_head_green"/> + android:src="@drawable/ic_robot_head_green"/> 文本所在区域指的是,从文本处向上寻找,直至发现一个可点击的部件为止。 -* `click(left, top, bottom, right)` 点击与长方形范围严格匹配的区域,并返回是否点击成功。其中left为长方形左边与屏幕左边的像素距离,top为上边与屏幕上边的像素距离,right为右边与**屏幕左边**的像素距离, bottom为下边与**屏幕下边**的距离。区域严格匹配,至于要确定要点击的区域在屏幕上的左边位置,可以在侧拉菜单开启"脚本辅助"(或者安卓7.0以上在通知栏点击"修改"添加脚本辅助快捷设定图标),之后每次点击或长按事件都会提示这次点击或长按的区域并自动保存,可以在编辑器中插入。 +> 文本所在区域指的是,从文本处向其父视图寻找,直至发现一个可点击的部件为止。 +* `click(left, top, bottom, right)` +> 有些按钮或者部件是图标而不是文字(例如发送朋友圈的照相机图标以及QQ下方的消息、联系人、动态图标),这时不能通过`click(text)`来点击,只能通过描述图标所在的区域来点击。left, bottom, top, right描述的就是点击的区域。至于要定位点击的区域,可以在侧拉菜单开启"点击区域辅助"(或者安卓7.0以上在通知栏点击"修改"添加点击区域辅助快捷设定图标),之后每次点击或长按都会提示这次点击或长按的区域并自动保存,可以在编辑器的右侧拉菜单中插入。 + + 点击与长方形范围严格匹配的区域,并返回是否点击成功。其中left为长方形左边与屏幕左边的像素距离,top为上边与屏幕上边的像素距离,right为右边与**屏幕左边**的像素距离, bottom为下边与**屏幕上边**的距离。区域严格匹配。 > 以下的longClick、select、scrollUp、scrollDown的参数均与click类似,不再赘述。 * `longClick` 长按 * `select` 选择 -* `scrollUp` 上滑。不加参数时会寻找"最大"的可滑动的控件下滑,例如微信消息列表等。 +* `scrollUp` 上滑。不加参数时会寻找"最大"的可滑动的控件上滑,例如微信消息列表等。 * `scrollDown` 下滑。不加参数时与scrollUp类似。 -* `input(string)` 把所有输入框的文本都置为string。 +* `input(text)` 把所有输入框的文本都置为text。例如input("测试")。 +* `input(i, text)` 把第i个输入框的文本设为text。i从0开始。 ###三、其他函数 * `sleep(n)` 暂停执行n**毫秒**时间。 -* `toast(string)` 显示提示文本。 +* `toast(text)` 显示提示文本。 * `launch(packageName)` 运行包名为packageName的应用。例如launch("com.tencent.mm")是运行微信,应用包名可以通过一些工具获取;获取通过函数launchApp代替 * `launch(packageName, className)` 运行包名为packageName,类名(Activity)为className的应用。 * `launchApp(appName)` 运存应用名称为appName的应用。例如launchApp("QQ")。不同应用名称可能相同,这时只运行其中某一个应用。 -###四、在脚本中调用安卓 +* `notStopped` 若当前脚本处于运行状态时返回`true`, 否则返回`false`。对于某些循环, 例如`while(true)`,请用`while(notStopped())`代替,以免死循环造成的脚本无法正常停止。 +* `isStoppd` 若当前脚本处于停止状态时返回`true`, 否则返回`false`。 +###四、全局变量 +* `context` ApplicationContext,参见安卓[android.content.Context](https://developer.android.com/reference/android/content/Context.html) +> 这里的context由于是ApplicationContext,是不可见的,不能用于dialog和其他UI相关。如果要显示弹窗或者视图,请启动UI模式(代码的第一行为`"ui";`既可)并使用activity代替。 +* `activity` UI模式下会启动一个Activity来运行脚本,并在UI线程下运行。可通过该变量来获取该activity。 +###五、在脚本中调用Java 使用importClass来引入要使用的库,例如: ```javascript importClass("android.view.View.OnClickListener") diff --git a/app/src/main/res/raw/edit_side_menu_functions.txt b/app/src/main/res/raw/edit_side_menu_functions.txt index 21dcfa65..1829558c 100644 --- a/app/src/main/res/raw/edit_side_menu_functions.txt +++ b/app/src/main/res/raw/edit_side_menu_functions.txt @@ -1,9 +1,11 @@ click 点击 longClick 长按 scrollUp 上滑 +scrollDown 下滑 toast 提示 launch 运行 launchApp 运行应用 select 选择 input 输入 -sleep 暂停运行 \ No newline at end of file +sleep 暂停运行 +notStopped 非暂停 \ No newline at end of file diff --git a/app/src/main/res/raw/licenses.xml b/app/src/main/res/raw/licenses.xml index 4e0bc1b2..6538ebf1 100644 --- a/app/src/main/res/raw/licenses.xml +++ b/app/src/main/res/raw/licenses.xml @@ -30,5 +30,11 @@ Copyright (c) 2015 zzhoujay MIT License + + Alipay ZeroSdk + Copyright 2016 Fung Go (fython) + https://github.com/fython/AlipayZeroSdk + Apache Software License 2.0 + \ No newline at end of file diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 3571a8ca..15ae26ed 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -51,17 +51,16 @@ 邮箱 https://github.com/hyb1996/NoRootScriptDroid [免Root脚本机器人]下载地址:https://github.com/hyb1996/NoRootScriptDroid/releases - 点击定位辅助服务 - 通知栏显示点击定位开关 - 通知栏显示点击定位开关 + 点击区域辅助服务 + 通知栏点击区域辅助开关 其他 - 点击定位辅助服务已开启(点击关闭) - 点击定位辅助服务已关闭(点击开启) + 点击区域辅助服务已开启(点击关闭) + 点击区域辅助服务已关闭(点击开启) 错误报告 - 大姐姐好 + 示例:QQ自动抢红包 再按一次退出程序 - 函数 - \"很抱歉,程序遇到未知错误,即将停止运行\\n错误代码:\" + 常用函数 + 很抱歉(ಥ _ ಥ)程序遇到未知错误,即将停止运行\n错误代码: 没有正在运行的脚本 已停止%d个正在运行的脚本 开始运行 @@ -85,4 +84,13 @@ 请选择邮件应用 点击定位剪贴板 脚本已停止 + \"点击区域辅助服务\"是在要点击的区域不是文本时使用的,参见\"语法与API\"。\"点击区域辅助服务\"只有在\"自动操作服务\"开启时才有效。 + 请选择 + 崩溃了o(≧口≦)o + 点击\"退出\"退出程序(ಥ _ ಥ)或者复制调试信息反馈给开发者(≧∇≦)ノ + 无法在后台显示弹框,脚本已停止运行 + 示例:QQ强制聊天 + 重新导入示例脚本文件 + 导入成功,重新打开应用生效 + 失败 diff --git a/app/src/main/res/xml/preferences.xml b/app/src/main/res/xml/preferences.xml index 759efdef..b688da75 100644 --- a/app/src/main/res/xml/preferences.xml +++ b/app/src/main/res/xml/preferences.xml @@ -1,6 +1,13 @@ + + + + +