Browse Source

Merge pull request #13 from runhey/dev

Dev
huangrunheng 3 years ago
parent
commit
bdbc95dbc1
100 changed files with 3387 additions and 196 deletions
  1. 674 0
      LICENSE
  2. 2 2
      README.md
  3. 129 0
      config/template.json
  4. 3 0
      gui.py
  5. 5 1
      module/atom/click.py
  6. 9 3
      module/atom/image.py
  7. 4 2
      module/atom/long_click.py
  8. 5 1
      module/atom/swipe.py
  9. 103 0
      module/base/filter.py
  10. 30 0
      module/base/log_highlighter.py
  11. 16 0
      module/base/utils.py
  12. 122 5
      module/config/config.py
  13. 7 0
      module/config/config_manual.py
  14. 4 3
      module/config/config_menu.py
  15. 51 3
      module/config/config_model.py
  16. 3 2
      module/config/config_state.py
  17. BIN
      module/config/i18n/zh_CN.qm
  18. 72 0
      module/config/i18n/zh_CN.ts
  19. 37 16
      module/dev_tools/assets_extract.py
  20. 20 0
      module/dev_tools/template_update.py
  21. 1 1
      module/device/app_control.py
  22. 86 30
      module/device/control.py
  23. 1 0
      module/device/handle.py
  24. 12 0
      module/device/method/adb.py
  25. 12 9
      module/device/method/window.py
  26. 3 0
      module/exception.py
  27. 174 7
      module/gui/context/process_manager.py
  28. 31 0
      module/gui/context/utils.py
  29. 37 7
      module/gui/process/script_process.py
  30. 12 1
      module/gui/qml/Component/Args.qml
  31. 21 14
      module/gui/qml/Component/OverStatus.qml
  32. 261 30
      module/gui/qml/Component/Overview.qml
  33. 1 1
      module/gui/qml/Component/RuleFile.qml
  34. 4 0
      module/gui/qml/Component/RunStatusIcon.qml
  35. 16 1
      module/gui/qml/Component/SplitPanel.qml
  36. 20 1
      module/gui/qml/Component/Taskmini.qml
  37. 3 2
      module/gui/qml/Global/MainEvent.qml
  38. 8 8
      module/gui/qml/MainWindow.qml
  39. 20 6
      module/gui/qml/Page/ScriptView.qml
  40. 40 0
      module/handler/sensitive_info.py
  41. 70 24
      module/logger.py
  42. 3 1
      requirements-in.txt
  43. 1 0
      requirements.txt
  44. 317 4
      script.py
  45. 30 0
      tasks/AreaBoss/assets.py
  46. 14 0
      tasks/AreaBoss/config.py
  47. 12 0
      tasks/AreaBoss/config_boss.py
  48. 15 0
      tasks/AreaBoss/config_scheduler.py
  49. 1 0
      tasks/AreaBoss/res/image.json
  50. BIN
      tasks/AreaBoss/res/res_area_boss.png
  51. BIN
      tasks/AreaBoss/res/res_back_blue.png
  52. BIN
      tasks/AreaBoss/res/res_battle_1.png
  53. BIN
      tasks/AreaBoss/res/res_battle_2.png
  54. BIN
      tasks/AreaBoss/res/res_battle_3.png
  55. BIN
      tasks/AreaBoss/res/res_close_red.png
  56. BIN
      tasks/AreaBoss/res/res_explore.png
  57. BIN
      tasks/AreaBoss/res/res_filter.png
  58. BIN
      tasks/AreaBoss/res/res_fire.png
  59. 188 0
      tasks/AreaBoss/script_task.py
  60. 11 11
      tasks/CoinChallenge/assets.py
  61. 10 0
      tasks/DemonEncounter/assets.py
  62. 6 0
      tasks/DemonEncounter/config.py
  63. 15 0
      tasks/DemonEncounter/config_scheduler.py
  64. 10 0
      tasks/EternitySea/assets.py
  65. 10 0
      tasks/EternitySea/config.py
  66. 15 0
      tasks/EternitySea/config_scheduler.py
  67. 10 0
      tasks/ExperienceYoukai/assets.py
  68. 10 0
      tasks/ExperienceYoukai/config.py
  69. 15 0
      tasks/ExperienceYoukai/config_scheduler.py
  70. 10 0
      tasks/FallenSun/assets.py
  71. 11 0
      tasks/FallenSun/config.py
  72. 15 0
      tasks/FallenSun/config_scheduler.py
  73. 10 0
      tasks/General/assets.py
  74. 86 0
      tasks/GeneralBattle/assets.py
  75. 69 0
      tasks/GeneralBattle/config_general_battle.py
  76. 187 0
      tasks/GeneralBattle/general_battle.py
  77. 110 0
      tasks/GeneralBattle/res/click.json
  78. 0 0
      tasks/GeneralBattle/res/image.json
  79. BIN
      tasks/GeneralBattle/res/res_buff.png
  80. BIN
      tasks/GeneralBattle/res/res_buff_awaken.png
  81. BIN
      tasks/GeneralBattle/res/res_buff_exp_100.png
  82. BIN
      tasks/GeneralBattle/res/res_buff_exp_50.png
  83. BIN
      tasks/GeneralBattle/res/res_buff_gold_100.png
  84. BIN
      tasks/GeneralBattle/res/res_buff_gold_50.png
  85. BIN
      tasks/GeneralBattle/res/res_buff_soul.png
  86. BIN
      tasks/GeneralBattle/res/res_false.png
  87. BIN
      tasks/GeneralBattle/res/res_local.png
  88. BIN
      tasks/GeneralBattle/res/res_prepare_dark.png
  89. BIN
      tasks/GeneralBattle/res/res_prepare_highlight.png
  90. BIN
      tasks/GeneralBattle/res/res_preset.png
  91. BIN
      tasks/GeneralBattle/res/res_preset_ensure.png
  92. BIN
      tasks/GeneralBattle/res/res_reward.png
  93. BIN
      tasks/GeneralBattle/res/res_statistics.png
  94. BIN
      tasks/GeneralBattle/res/res_win.png
  95. 16 0
      tasks/GeneralBattle/res/swipe.json
  96. 10 0
      tasks/GlobalGame/assets.py
  97. 11 0
      tasks/GlobalGame/config.py
  98. 10 0
      tasks/GlobalGame/config_emergency.py
  99. 10 0
      tasks/GoldYoukai/assets.py
  100. 10 0
      tasks/GoldYoukai/config.py

+ 674 - 0
LICENSE

@@ -0,0 +1,674 @@
+                    GNU GENERAL PUBLIC LICENSE
+                       Version 3, 29 June 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+                            Preamble
+
+  The GNU General Public License is a free, copyleft license for
+software and other kinds of works.
+
+  The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works.  By contrast,
+the GNU General Public License is intended to guarantee your freedom to
+share and change all versions of a program--to make sure it remains free
+software for all its users.  We, the Free Software Foundation, use the
+GNU General Public License for most of our software; it applies also to
+any other work released this way by its authors.  You can apply it to
+your programs, too.
+
+  When we speak of free software, we are referring to freedom, not
+price.  Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+them if you wish), that you receive source code or can get it if you
+want it, that you can change the software or use pieces of it in new
+free programs, and that you know you can do these things.
+
+  To protect your rights, we need to prevent others from denying you
+these rights or asking you to surrender the rights.  Therefore, you have
+certain responsibilities if you distribute copies of the software, or if
+you modify it: responsibilities to respect the freedom of others.
+
+  For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must pass on to the recipients the same
+freedoms that you received.  You must make sure that they, too, receive
+or can get the source code.  And you must show them these terms so they
+know their rights.
+
+  Developers that use the GNU GPL protect your rights with two steps:
+(1) assert copyright on the software, and (2) offer you this License
+giving you legal permission to copy, distribute and/or modify it.
+
+  For the developers' and authors' protection, the GPL clearly explains
+that there is no warranty for this free software.  For both users' and
+authors' sake, the GPL requires that modified versions be marked as
+changed, so that their problems will not be attributed erroneously to
+authors of previous versions.
+
+  Some devices are designed to deny users access to install or run
+modified versions of the software inside them, although the manufacturer
+can do so.  This is fundamentally incompatible with the aim of
+protecting users' freedom to change the software.  The systematic
+pattern of such abuse occurs in the area of products for individuals to
+use, which is precisely where it is most unacceptable.  Therefore, we
+have designed this version of the GPL to prohibit the practice for those
+products.  If such problems arise substantially in other domains, we
+stand ready to extend this provision to those domains in future versions
+of the GPL, as needed to protect the freedom of users.
+
+  Finally, every program is threatened constantly by software patents.
+States should not allow patents to restrict development and use of
+software on general-purpose computers, but in those that do, we wish to
+avoid the special danger that patents applied to a free program could
+make it effectively proprietary.  To prevent this, the GPL assures that
+patents cannot be used to render the program non-free.
+
+  The precise terms and conditions for copying, distribution and
+modification follow.
+
+                       TERMS AND CONDITIONS
+
+  0. Definitions.
+
+  "This License" refers to version 3 of the GNU General Public License.
+
+  "Copyright" also means copyright-like laws that apply to other kinds of
+works, such as semiconductor masks.
+
+  "The Program" refers to any copyrightable work licensed under this
+License.  Each licensee is addressed as "you".  "Licensees" and
+"recipients" may be individuals or organizations.
+
+  To "modify" a work means to copy from or adapt all or part of the work
+in a fashion requiring copyright permission, other than the making of an
+exact copy.  The resulting work is called a "modified version" of the
+earlier work or a work "based on" the earlier work.
+
+  A "covered work" means either the unmodified Program or a work based
+on the Program.
+
+  To "propagate" a work means to do anything with it that, without
+permission, would make you directly or secondarily liable for
+infringement under applicable copyright law, except executing it on a
+computer or modifying a private copy.  Propagation includes copying,
+distribution (with or without modification), making available to the
+public, and in some countries other activities as well.
+
+  To "convey" a work means any kind of propagation that enables other
+parties to make or receive copies.  Mere interaction with a user through
+a computer network, with no transfer of a copy, is not conveying.
+
+  An interactive user interface displays "Appropriate Legal Notices"
+to the extent that it includes a convenient and prominently visible
+feature that (1) displays an appropriate copyright notice, and (2)
+tells the user that there is no warranty for the work (except to the
+extent that warranties are provided), that licensees may convey the
+work under this License, and how to view a copy of this License.  If
+the interface presents a list of user commands or options, such as a
+menu, a prominent item in the list meets this criterion.
+
+  1. Source Code.
+
+  The "source code" for a work means the preferred form of the work
+for making modifications to it.  "Object code" means any non-source
+form of a work.
+
+  A "Standard Interface" means an interface that either is an official
+standard defined by a recognized standards body, or, in the case of
+interfaces specified for a particular programming language, one that
+is widely used among developers working in that language.
+
+  The "System Libraries" of an executable work include anything, other
+than the work as a whole, that (a) is included in the normal form of
+packaging a Major Component, but which is not part of that Major
+Component, and (b) serves only to enable use of the work with that
+Major Component, or to implement a Standard Interface for which an
+implementation is available to the public in source code form.  A
+"Major Component", in this context, means a major essential component
+(kernel, window system, and so on) of the specific operating system
+(if any) on which the executable work runs, or a compiler used to
+produce the work, or an object code interpreter used to run it.
+
+  The "Corresponding Source" for a work in object code form means all
+the source code needed to generate, install, and (for an executable
+work) run the object code and to modify the work, including scripts to
+control those activities.  However, it does not include the work's
+System Libraries, or general-purpose tools or generally available free
+programs which are used unmodified in performing those activities but
+which are not part of the work.  For example, Corresponding Source
+includes interface definition files associated with source files for
+the work, and the source code for shared libraries and dynamically
+linked subprograms that the work is specifically designed to require,
+such as by intimate data communication or control flow between those
+subprograms and other parts of the work.
+
+  The Corresponding Source need not include anything that users
+can regenerate automatically from other parts of the Corresponding
+Source.
+
+  The Corresponding Source for a work in source code form is that
+same work.
+
+  2. Basic Permissions.
+
+  All rights granted under this License are granted for the term of
+copyright on the Program, and are irrevocable provided the stated
+conditions are met.  This License explicitly affirms your unlimited
+permission to run the unmodified Program.  The output from running a
+covered work is covered by this License only if the output, given its
+content, constitutes a covered work.  This License acknowledges your
+rights of fair use or other equivalent, as provided by copyright law.
+
+  You may make, run and propagate covered works that you do not
+convey, without conditions so long as your license otherwise remains
+in force.  You may convey covered works to others for the sole purpose
+of having them make modifications exclusively for you, or provide you
+with facilities for running those works, provided that you comply with
+the terms of this License in conveying all material for which you do
+not control copyright.  Those thus making or running the covered works
+for you must do so exclusively on your behalf, under your direction
+and control, on terms that prohibit them from making any copies of
+your copyrighted material outside their relationship with you.
+
+  Conveying under any other circumstances is permitted solely under
+the conditions stated below.  Sublicensing is not allowed; section 10
+makes it unnecessary.
+
+  3. Protecting Users' Legal Rights From Anti-Circumvention Law.
+
+  No covered work shall be deemed part of an effective technological
+measure under any applicable law fulfilling obligations under article
+11 of the WIPO copyright treaty adopted on 20 December 1996, or
+similar laws prohibiting or restricting circumvention of such
+measures.
+
+  When you convey a covered work, you waive any legal power to forbid
+circumvention of technological measures to the extent such circumvention
+is effected by exercising rights under this License with respect to
+the covered work, and you disclaim any intention to limit operation or
+modification of the work as a means of enforcing, against the work's
+users, your or third parties' legal rights to forbid circumvention of
+technological measures.
+
+  4. Conveying Verbatim Copies.
+
+  You may convey verbatim copies of the Program's source code as you
+receive it, in any medium, provided that you conspicuously and
+appropriately publish on each copy an appropriate copyright notice;
+keep intact all notices stating that this License and any
+non-permissive terms added in accord with section 7 apply to the code;
+keep intact all notices of the absence of any warranty; and give all
+recipients a copy of this License along with the Program.
+
+  You may charge any price or no price for each copy that you convey,
+and you may offer support or warranty protection for a fee.
+
+  5. Conveying Modified Source Versions.
+
+  You may convey a work based on the Program, or the modifications to
+produce it from the Program, in the form of source code under the
+terms of section 4, provided that you also meet all of these conditions:
+
+    a) The work must carry prominent notices stating that you modified
+    it, and giving a relevant date.
+
+    b) The work must carry prominent notices stating that it is
+    released under this License and any conditions added under section
+    7.  This requirement modifies the requirement in section 4 to
+    "keep intact all notices".
+
+    c) You must license the entire work, as a whole, under this
+    License to anyone who comes into possession of a copy.  This
+    License will therefore apply, along with any applicable section 7
+    additional terms, to the whole of the work, and all its parts,
+    regardless of how they are packaged.  This License gives no
+    permission to license the work in any other way, but it does not
+    invalidate such permission if you have separately received it.
+
+    d) If the work has interactive user interfaces, each must display
+    Appropriate Legal Notices; however, if the Program has interactive
+    interfaces that do not display Appropriate Legal Notices, your
+    work need not make them do so.
+
+  A compilation of a covered work with other separate and independent
+works, which are not by their nature extensions of the covered work,
+and which are not combined with it such as to form a larger program,
+in or on a volume of a storage or distribution medium, is called an
+"aggregate" if the compilation and its resulting copyright are not
+used to limit the access or legal rights of the compilation's users
+beyond what the individual works permit.  Inclusion of a covered work
+in an aggregate does not cause this License to apply to the other
+parts of the aggregate.
+
+  6. Conveying Non-Source Forms.
+
+  You may convey a covered work in object code form under the terms
+of sections 4 and 5, provided that you also convey the
+machine-readable Corresponding Source under the terms of this License,
+in one of these ways:
+
+    a) Convey the object code in, or embodied in, a physical product
+    (including a physical distribution medium), accompanied by the
+    Corresponding Source fixed on a durable physical medium
+    customarily used for software interchange.
+
+    b) Convey the object code in, or embodied in, a physical product
+    (including a physical distribution medium), accompanied by a
+    written offer, valid for at least three years and valid for as
+    long as you offer spare parts or customer support for that product
+    model, to give anyone who possesses the object code either (1) a
+    copy of the Corresponding Source for all the software in the
+    product that is covered by this License, on a durable physical
+    medium customarily used for software interchange, for a price no
+    more than your reasonable cost of physically performing this
+    conveying of source, or (2) access to copy the
+    Corresponding Source from a network server at no charge.
+
+    c) Convey individual copies of the object code with a copy of the
+    written offer to provide the Corresponding Source.  This
+    alternative is allowed only occasionally and noncommercially, and
+    only if you received the object code with such an offer, in accord
+    with subsection 6b.
+
+    d) Convey the object code by offering access from a designated
+    place (gratis or for a charge), and offer equivalent access to the
+    Corresponding Source in the same way through the same place at no
+    further charge.  You need not require recipients to copy the
+    Corresponding Source along with the object code.  If the place to
+    copy the object code is a network server, the Corresponding Source
+    may be on a different server (operated by you or a third party)
+    that supports equivalent copying facilities, provided you maintain
+    clear directions next to the object code saying where to find the
+    Corresponding Source.  Regardless of what server hosts the
+    Corresponding Source, you remain obligated to ensure that it is
+    available for as long as needed to satisfy these requirements.
+
+    e) Convey the object code using peer-to-peer transmission, provided
+    you inform other peers where the object code and Corresponding
+    Source of the work are being offered to the general public at no
+    charge under subsection 6d.
+
+  A separable portion of the object code, whose source code is excluded
+from the Corresponding Source as a System Library, need not be
+included in conveying the object code work.
+
+  A "User Product" is either (1) a "consumer product", which means any
+tangible personal property which is normally used for personal, family,
+or household purposes, or (2) anything designed or sold for incorporation
+into a dwelling.  In determining whether a product is a consumer product,
+doubtful cases shall be resolved in favor of coverage.  For a particular
+product received by a particular user, "normally used" refers to a
+typical or common use of that class of product, regardless of the status
+of the particular user or of the way in which the particular user
+actually uses, or expects or is expected to use, the product.  A product
+is a consumer product regardless of whether the product has substantial
+commercial, industrial or non-consumer uses, unless such uses represent
+the only significant mode of use of the product.
+
+  "Installation Information" for a User Product means any methods,
+procedures, authorization keys, or other information required to install
+and execute modified versions of a covered work in that User Product from
+a modified version of its Corresponding Source.  The information must
+suffice to ensure that the continued functioning of the modified object
+code is in no case prevented or interfered with solely because
+modification has been made.
+
+  If you convey an object code work under this section in, or with, or
+specifically for use in, a User Product, and the conveying occurs as
+part of a transaction in which the right of possession and use of the
+User Product is transferred to the recipient in perpetuity or for a
+fixed term (regardless of how the transaction is characterized), the
+Corresponding Source conveyed under this section must be accompanied
+by the Installation Information.  But this requirement does not apply
+if neither you nor any third party retains the ability to install
+modified object code on the User Product (for example, the work has
+been installed in ROM).
+
+  The requirement to provide Installation Information does not include a
+requirement to continue to provide support service, warranty, or updates
+for a work that has been modified or installed by the recipient, or for
+the User Product in which it has been modified or installed.  Access to a
+network may be denied when the modification itself materially and
+adversely affects the operation of the network or violates the rules and
+protocols for communication across the network.
+
+  Corresponding Source conveyed, and Installation Information provided,
+in accord with this section must be in a format that is publicly
+documented (and with an implementation available to the public in
+source code form), and must require no special password or key for
+unpacking, reading or copying.
+
+  7. Additional Terms.
+
+  "Additional permissions" are terms that supplement the terms of this
+License by making exceptions from one or more of its conditions.
+Additional permissions that are applicable to the entire Program shall
+be treated as though they were included in this License, to the extent
+that they are valid under applicable law.  If additional permissions
+apply only to part of the Program, that part may be used separately
+under those permissions, but the entire Program remains governed by
+this License without regard to the additional permissions.
+
+  When you convey a copy of a covered work, you may at your option
+remove any additional permissions from that copy, or from any part of
+it.  (Additional permissions may be written to require their own
+removal in certain cases when you modify the work.)  You may place
+additional permissions on material, added by you to a covered work,
+for which you have or can give appropriate copyright permission.
+
+  Notwithstanding any other provision of this License, for material you
+add to a covered work, you may (if authorized by the copyright holders of
+that material) supplement the terms of this License with terms:
+
+    a) Disclaiming warranty or limiting liability differently from the
+    terms of sections 15 and 16 of this License; or
+
+    b) Requiring preservation of specified reasonable legal notices or
+    author attributions in that material or in the Appropriate Legal
+    Notices displayed by works containing it; or
+
+    c) Prohibiting misrepresentation of the origin of that material, or
+    requiring that modified versions of such material be marked in
+    reasonable ways as different from the original version; or
+
+    d) Limiting the use for publicity purposes of names of licensors or
+    authors of the material; or
+
+    e) Declining to grant rights under trademark law for use of some
+    trade names, trademarks, or service marks; or
+
+    f) Requiring indemnification of licensors and authors of that
+    material by anyone who conveys the material (or modified versions of
+    it) with contractual assumptions of liability to the recipient, for
+    any liability that these contractual assumptions directly impose on
+    those licensors and authors.
+
+  All other non-permissive additional terms are considered "further
+restrictions" within the meaning of section 10.  If the Program as you
+received it, or any part of it, contains a notice stating that it is
+governed by this License along with a term that is a further
+restriction, you may remove that term.  If a license document contains
+a further restriction but permits relicensing or conveying under this
+License, you may add to a covered work material governed by the terms
+of that license document, provided that the further restriction does
+not survive such relicensing or conveying.
+
+  If you add terms to a covered work in accord with this section, you
+must place, in the relevant source files, a statement of the
+additional terms that apply to those files, or a notice indicating
+where to find the applicable terms.
+
+  Additional terms, permissive or non-permissive, may be stated in the
+form of a separately written license, or stated as exceptions;
+the above requirements apply either way.
+
+  8. Termination.
+
+  You may not propagate or modify a covered work except as expressly
+provided under this License.  Any attempt otherwise to propagate or
+modify it is void, and will automatically terminate your rights under
+this License (including any patent licenses granted under the third
+paragraph of section 11).
+
+  However, if you cease all violation of this License, then your
+license from a particular copyright holder is reinstated (a)
+provisionally, unless and until the copyright holder explicitly and
+finally terminates your license, and (b) permanently, if the copyright
+holder fails to notify you of the violation by some reasonable means
+prior to 60 days after the cessation.
+
+  Moreover, your license from a particular copyright holder is
+reinstated permanently if the copyright holder notifies you of the
+violation by some reasonable means, this is the first time you have
+received notice of violation of this License (for any work) from that
+copyright holder, and you cure the violation prior to 30 days after
+your receipt of the notice.
+
+  Termination of your rights under this section does not terminate the
+licenses of parties who have received copies or rights from you under
+this License.  If your rights have been terminated and not permanently
+reinstated, you do not qualify to receive new licenses for the same
+material under section 10.
+
+  9. Acceptance Not Required for Having Copies.
+
+  You are not required to accept this License in order to receive or
+run a copy of the Program.  Ancillary propagation of a covered work
+occurring solely as a consequence of using peer-to-peer transmission
+to receive a copy likewise does not require acceptance.  However,
+nothing other than this License grants you permission to propagate or
+modify any covered work.  These actions infringe copyright if you do
+not accept this License.  Therefore, by modifying or propagating a
+covered work, you indicate your acceptance of this License to do so.
+
+  10. Automatic Licensing of Downstream Recipients.
+
+  Each time you convey a covered work, the recipient automatically
+receives a license from the original licensors, to run, modify and
+propagate that work, subject to this License.  You are not responsible
+for enforcing compliance by third parties with this License.
+
+  An "entity transaction" is a transaction transferring control of an
+organization, or substantially all assets of one, or subdividing an
+organization, or merging organizations.  If propagation of a covered
+work results from an entity transaction, each party to that
+transaction who receives a copy of the work also receives whatever
+licenses to the work the party's predecessor in interest had or could
+give under the previous paragraph, plus a right to possession of the
+Corresponding Source of the work from the predecessor in interest, if
+the predecessor has it or can get it with reasonable efforts.
+
+  You may not impose any further restrictions on the exercise of the
+rights granted or affirmed under this License.  For example, you may
+not impose a license fee, royalty, or other charge for exercise of
+rights granted under this License, and you may not initiate litigation
+(including a cross-claim or counterclaim in a lawsuit) alleging that
+any patent claim is infringed by making, using, selling, offering for
+sale, or importing the Program or any portion of it.
+
+  11. Patents.
+
+  A "contributor" is a copyright holder who authorizes use under this
+License of the Program or a work on which the Program is based.  The
+work thus licensed is called the contributor's "contributor version".
+
+  A contributor's "essential patent claims" are all patent claims
+owned or controlled by the contributor, whether already acquired or
+hereafter acquired, that would be infringed by some manner, permitted
+by this License, of making, using, or selling its contributor version,
+but do not include claims that would be infringed only as a
+consequence of further modification of the contributor version.  For
+purposes of this definition, "control" includes the right to grant
+patent sublicenses in a manner consistent with the requirements of
+this License.
+
+  Each contributor grants you a non-exclusive, worldwide, royalty-free
+patent license under the contributor's essential patent claims, to
+make, use, sell, offer for sale, import and otherwise run, modify and
+propagate the contents of its contributor version.
+
+  In the following three paragraphs, a "patent license" is any express
+agreement or commitment, however denominated, not to enforce a patent
+(such as an express permission to practice a patent or covenant not to
+sue for patent infringement).  To "grant" such a patent license to a
+party means to make such an agreement or commitment not to enforce a
+patent against the party.
+
+  If you convey a covered work, knowingly relying on a patent license,
+and the Corresponding Source of the work is not available for anyone
+to copy, free of charge and under the terms of this License, through a
+publicly available network server or other readily accessible means,
+then you must either (1) cause the Corresponding Source to be so
+available, or (2) arrange to deprive yourself of the benefit of the
+patent license for this particular work, or (3) arrange, in a manner
+consistent with the requirements of this License, to extend the patent
+license to downstream recipients.  "Knowingly relying" means you have
+actual knowledge that, but for the patent license, your conveying the
+covered work in a country, or your recipient's use of the covered work
+in a country, would infringe one or more identifiable patents in that
+country that you have reason to believe are valid.
+
+  If, pursuant to or in connection with a single transaction or
+arrangement, you convey, or propagate by procuring conveyance of, a
+covered work, and grant a patent license to some of the parties
+receiving the covered work authorizing them to use, propagate, modify
+or convey a specific copy of the covered work, then the patent license
+you grant is automatically extended to all recipients of the covered
+work and works based on it.
+
+  A patent license is "discriminatory" if it does not include within
+the scope of its coverage, prohibits the exercise of, or is
+conditioned on the non-exercise of one or more of the rights that are
+specifically granted under this License.  You may not convey a covered
+work if you are a party to an arrangement with a third party that is
+in the business of distributing software, under which you make payment
+to the third party based on the extent of your activity of conveying
+the work, and under which the third party grants, to any of the
+parties who would receive the covered work from you, a discriminatory
+patent license (a) in connection with copies of the covered work
+conveyed by you (or copies made from those copies), or (b) primarily
+for and in connection with specific products or compilations that
+contain the covered work, unless you entered into that arrangement,
+or that patent license was granted, prior to 28 March 2007.
+
+  Nothing in this License shall be construed as excluding or limiting
+any implied license or other defenses to infringement that may
+otherwise be available to you under applicable patent law.
+
+  12. No Surrender of Others' Freedom.
+
+  If conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License.  If you cannot convey a
+covered work so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you may
+not convey it at all.  For example, if you agree to terms that obligate you
+to collect a royalty for further conveying from those to whom you convey
+the Program, the only way you could satisfy both those terms and this
+License would be to refrain entirely from conveying the Program.
+
+  13. Use with the GNU Affero General Public License.
+
+  Notwithstanding any other provision of this License, you have
+permission to link or combine any covered work with a work licensed
+under version 3 of the GNU Affero General Public License into a single
+combined work, and to convey the resulting work.  The terms of this
+License will continue to apply to the part which is the covered work,
+but the special requirements of the GNU Affero General Public License,
+section 13, concerning interaction through a network will apply to the
+combination as such.
+
+  14. Revised Versions of this License.
+
+  The Free Software Foundation may publish revised and/or new versions of
+the GNU General Public License from time to time.  Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+  Each version is given a distinguishing version number.  If the
+Program specifies that a certain numbered version of the GNU General
+Public License "or any later version" applies to it, you have the
+option of following the terms and conditions either of that numbered
+version or of any later version published by the Free Software
+Foundation.  If the Program does not specify a version number of the
+GNU General Public License, you may choose any version ever published
+by the Free Software Foundation.
+
+  If the Program specifies that a proxy can decide which future
+versions of the GNU General Public License can be used, that proxy's
+public statement of acceptance of a version permanently authorizes you
+to choose that version for the Program.
+
+  Later license versions may give you additional or different
+permissions.  However, no additional obligations are imposed on any
+author or copyright holder as a result of your choosing to follow a
+later version.
+
+  15. Disclaimer of Warranty.
+
+  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
+APPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
+IS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+  16. Limitation of Liability.
+
+  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
+SUCH DAMAGES.
+
+  17. Interpretation of Sections 15 and 16.
+
+  If the disclaimer of warranty and limitation of liability provided
+above cannot be given local legal effect according to their terms,
+reviewing courts shall apply local law that most closely approximates
+an absolute waiver of all civil liability in connection with the
+Program, unless a warranty or assumption of liability accompanies a
+copy of the Program in return for a fee.
+
+                     END OF TERMS AND CONDITIONS
+
+            How to Apply These Terms to Your New Programs
+
+  If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+  To do so, attach the following notices to the program.  It is safest
+to attach them to the start of each source file to most effectively
+state the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+    <one line to give the program's name and a brief idea of what it does.>
+    Copyright (C) <year>  <name of author>
+
+    This program is free software: you can redistribute it and/or modify
+    it under the terms of the GNU General Public License as published by
+    the Free Software Foundation, either version 3 of the License, or
+    (at your option) any later version.
+
+    This program is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+    GNU General Public License for more details.
+
+    You should have received a copy of the GNU General Public License
+    along with this program.  If not, see <https://www.gnu.org/licenses/>.
+
+Also add information on how to contact you by electronic and paper mail.
+
+  If the program does terminal interaction, make it output a short
+notice like this when it starts in an interactive mode:
+
+    <program>  Copyright (C) <year>  <name of author>
+    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+    This is free software, and you are welcome to redistribute it
+    under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License.  Of course, your program's commands
+might be different; for a GUI interface, you would use an "about box".
+
+  You should also get your employer (if you work as a programmer) or school,
+if any, to sign a "copyright disclaimer" for the program, if necessary.
+For more information on this, and how to apply and follow the GNU GPL, see
+<https://www.gnu.org/licenses/>.
+
+  The GNU General Public License does not permit incorporating your program
+into proprietary programs.  If your program is a subroutine library, you
+may consider it more useful to permit linking proprietary applications with
+the library.  If this is what you want to do, use the GNU Lesser General
+Public License instead of this License.  But first, please read
+<https://www.gnu.org/licenses/why-not-lgpl.html>.

+ 2 - 2
README.md

@@ -99,9 +99,9 @@ oas目前还在开发中,我们期待你的加入,Q群: 465946275
 | ✔优化window截图+控制                                         |
 | ✔优化window截图+控制                                         |
 | ✔投屏到OAS                                                   |
 | ✔投屏到OAS                                                   |
 | 🔨操作格式化json生成工具:可以从用户界面简单操作生成维护数据(包括✔图片匹配,✔点击操作,✔长按操作,✔滑动操作,ocr识别等等) |
 | 🔨操作格式化json生成工具:可以从用户界面简单操作生成维护数据(包括✔图片匹配,✔点击操作,✔长按操作,✔滑动操作,ocr识别等等) |
-| 📆Atom: 对于上一条数据的接口                                  |
+| ✔Atom: 对于上一条数据的接口                                  |
 | 📆实现ocr单独进程                                             |
 | 📆实现ocr单独进程                                             |
-| 📆到此我们可以(读参数)、(对游戏截屏控制)、(操控数据)。实现第一个脚本任务如挖土 |
+| 🔨到此我们可以(读参数)、(对游戏截屏控制)、(操控数据)。实现第一个脚本任务如挖土 |
 | 📆重写device(从alas复制过来需要解耦)                          |
 | 📆重写device(从alas复制过来需要解耦)                          |
 |                                                              |
 |                                                              |
 
 

+ 129 - 0
config/template.json

@@ -0,0 +1,129 @@
+{
+  "config_name": "oas",
+  "script": {
+    "device": {
+      "serial": "auto",
+      "handle": "auto",
+      "package_name": "auto",
+      "screenshot_method": "window_background",
+      "control_method": "window_message",
+      "adb_restart": false
+    },
+    "error": {
+      "handle_error": false,
+      "save_error": false,
+      "screenshot_length": 1
+    },
+    "optimization": {
+      "screenshot_interval": 0.3,
+      "combat_screenshot_interval": 1.0,
+      "task_hoarding_duration": 0,
+      "when_task_queue_empty": "goto_home"
+    }
+  },
+  "restart": {
+    "scheduler": {
+      "enable": false,
+      "next_run": "2023-01-01 00:00:00",
+      "priority": 0,
+      "command": "Restart",
+      "success_interval": 0,
+      "failure_interval": 0,
+      "server_update": "00:00"
+    }
+  },
+  "global_game": {
+    "emergency": {
+      "accept_friend_invitation": true
+    }
+  },
+  "area_boss": {
+    "scheduler": {
+      "enable": false,
+      "next_run": "2023-01-01 00:00:00",
+      "priority": 3
+    },
+    "general_battle": {
+      "lock_team_enable": false,
+      "preset_enable": false,
+      "preset_group": 1,
+      "preset_team": 1,
+      "buff_enable": false,
+      "buff_awake_click": false,
+      "buff_soul_click": false,
+      "buff_gold_50_click": false,
+      "buff_gold_100_click": false,
+      "buff_exp_50_click": false,
+      "buff_exp_100_click": false,
+      "green_enable": false,
+      "green_mark": "green_left1",
+      "random_click_swipt_enable": false
+    },
+    "boss": {
+      "boss_number": 3
+    }
+  },
+  "experience_youkai": {
+    "scheduler": {
+      "enable": false,
+      "next_run": "2023-01-01 00:00:00",
+      "priority": 3
+    }
+  },
+  "gold_youkai": {
+    "scheduler": {
+      "enable": false,
+      "next_run": "2023-01-01 00:00:00",
+      "priority": 3
+    }
+  },
+  "nian": {
+    "scheduler": {
+      "enable": false,
+      "next_run": "2023-01-01 00:00:00",
+      "priority": 3
+    }
+  },
+  "orochi": {
+    "scheduler": {
+      "enable": false,
+      "next_run": "2023-01-01 00:00:00",
+      "priority": 3
+    }
+  },
+  "orochi_moans": {
+    "scheduler": {
+      "enable": false,
+      "next_run": "2023-01-01 00:00:00",
+      "priority": 3
+    }
+  },
+  "orochi_judgement": {
+    "scheduler": {
+      "enable": false,
+      "next_run": "2023-01-01 00:00:00",
+      "priority": 3
+    }
+  },
+  "sougenbi": {
+    "scheduler": {
+      "enable": false,
+      "next_run": "2023-01-01 00:00:00",
+      "priority": 3
+    }
+  },
+  "fallen_sun": {
+    "scheduler": {
+      "enable": false,
+      "next_run": "2023-01-01 00:00:00",
+      "priority": 3
+    }
+  },
+  "eternity_sea": {
+    "scheduler": {
+      "enable": false,
+      "next_run": "2023-01-01 00:00:00",
+      "priority": 3
+    }
+  }
+}

+ 3 - 0
gui.py

@@ -6,6 +6,7 @@ from module.gui.utils import check_admin
 from module.gui.context.add import Add
 from module.gui.context.add import Add
 from module.gui.context.settings import Setting
 from module.gui.context.settings import Setting
 from module.gui.context.process_manager import ProcessManager
 from module.gui.context.process_manager import ProcessManager
+from module.gui.context.utils import Utils
 from module.gui.register_type.paint_image import PaintImage
 from module.gui.register_type.paint_image import PaintImage
 from module.gui.register_type.rule_file import RuleFile
 from module.gui.register_type.rule_file import RuleFile
 from module.gui.fluent_app import FluentApp
 from module.gui.fluent_app import FluentApp
@@ -20,10 +21,12 @@ if __name__ == "__main__":
     add_config = Add()
     add_config = Add()
     setting = Setting()
     setting = Setting()
     process_manager = ProcessManager()
     process_manager = ProcessManager()
+    utils = Utils()
 
 
     app.set_context_property(setting, 'setting')
     app.set_context_property(setting, 'setting')
     app.set_context_property(add_config, 'add_config')
     app.set_context_property(add_config, 'add_config')
     app.set_context_property(process_manager, 'process_manager')
     app.set_context_property(process_manager, 'process_manager')
+    app.set_context_property(utils, 'utils')
     app.qml_register_type(PaintImage, 'PaintImage')
     app.qml_register_type(PaintImage, 'PaintImage')
     app.qml_register_type(RuleFile, 'RuleFile')
     app.qml_register_type(RuleFile, 'RuleFile')
     # 启动一个GUI
     # 启动一个GUI

+ 5 - 1
module/atom/click.py

@@ -8,7 +8,7 @@ from module.logger import logger
 
 
 class RuleClick:
 class RuleClick:
 
 
-    def __init__(self, roi_front: tuple, roi_back: tuple) -> None:
+    def __init__(self, roi_front: tuple, roi_back: tuple, name: str=None) -> None:
         """
         """
         初始化
         初始化
         :param roi_front:
         :param roi_front:
@@ -16,6 +16,10 @@ class RuleClick:
         """
         """
         self.roi_front = roi_front
         self.roi_front = roi_front
         self.roi_back = roi_back
         self.roi_back = roi_back
+        if name:
+            self.name = name
+        else:
+            self.name = 'click'
 
 
     def coord(self) -> tuple:
     def coord(self) -> tuple:
         """
         """

+ 9 - 3
module/atom/image.py

@@ -21,12 +21,14 @@ class RuleImage:
         :param threshold: 阈值
         :param threshold: 阈值
         :param file: 相对路径, 带后缀
         :param file: 相对路径, 带后缀
         """
         """
-        self.roi_front = roi_front
+        self.roi_front: list = list(roi_front)
         self.roi_back = roi_back
         self.roi_back = roi_back
         self.method = method
         self.method = method
         self.threshold = threshold
         self.threshold = threshold
         self.file = file
         self.file = file
 
 
+        self._match_init = False  # 这个是给后面的 等待图片稳定
+
         self._image = None  # 这个是匹配的目标
         self._image = None  # 这个是匹配的目标
 
 
     @cached_property
     @cached_property
@@ -61,7 +63,7 @@ class RuleImage:
         if self._image is not None:
         if self._image is not None:
             return
             return
         img = cv2.imdecode(fromfile(self.file, dtype=uint8), -1)
         img = cv2.imdecode(fromfile(self.file, dtype=uint8), -1)
-        # self._image = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
+        img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
         self._image = img
         self._image = img
 
 
         height, width, channels = self._image.shape
         height, width, channels = self._image.shape
@@ -117,6 +119,8 @@ class RuleImage:
         res = cv2.matchTemplate(source, mat, cv2.TM_CCOEFF_NORMED)
         res = cv2.matchTemplate(source, mat, cv2.TM_CCOEFF_NORMED)
         min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)  # 最小匹配度,最大匹配度,最小匹配度的坐标,最大匹配度的坐标
         min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)  # 最小匹配度,最大匹配度,最小匹配度的坐标,最大匹配度的坐标
         if max_val > threshold:
         if max_val > threshold:
+            self.roi_front[0] = max_loc[0] + self.roi_back[0]
+            self.roi_front[1] = max_loc[1] + self.roi_back[1]
             return True
             return True
         else:
         else:
             return False
             return False
@@ -139,4 +143,6 @@ class RuleImage:
 
 
 
 
 if __name__ == "__main__":
 if __name__ == "__main__":
-    pass
+    image = cv2.imread("D:/4713.jpg")
+    mat = RuleImage(roi_front=(758,122,66,77), roi_back=(339,104,836,120), threshold=0.8, method="Template matching", file="./tasks/AreaBoss/res/res_explore.png")
+    print(mat.match(image))

+ 4 - 2
module/atom/long_click.py

@@ -10,14 +10,16 @@ from module.atom.click import RuleClick
 
 
 class RuleLongClick(RuleClick):
 class RuleLongClick(RuleClick):
 
 
-    def __init__(self, roi_front: tuple, roi_back: tuple, duration: int = 1000) -> None:
+    def __init__(self, roi_front: tuple, roi_back: tuple, duration: int = 1000, name: str=None) -> None:
         """
         """
         初始化
         初始化
         :param roi_front:
         :param roi_front:
         :param roi_back:
         :param roi_back:
         :param duration:
         :param duration:
         """
         """
-        super().__init__(roi_front, roi_back)
+        if not name:
+            name = 'long_click'
+        super().__init__(roi_front, roi_back, name=name)
         self.duration = duration
         self.duration = duration
 
 
 
 

+ 5 - 1
module/atom/swipe.py

@@ -13,7 +13,7 @@ from module.logger import logger
 
 
 class RuleSwipe:
 class RuleSwipe:
 
 
-    def __init__(self, roi_front: tuple, roi_back: tuple, mode: str) -> None:
+    def __init__(self, roi_front: tuple, roi_back: tuple, mode: str, name: str =None) -> None:
         """
         """
         初始化
         初始化
         :param roi_front:
         :param roi_front:
@@ -23,6 +23,10 @@ class RuleSwipe:
         self.roi_front = roi_front
         self.roi_front = roi_front
         self.roi_back = roi_back
         self.roi_back = roi_back
         self.mode = mode
         self.mode = mode
+        if name:
+            self.name = name
+        else:
+            self.name = 'swipe'
 
 
         self.interval: int = 8  # 每次移动的间隔时间
         self.interval: int = 8  # 每次移动的间隔时间
 
 

+ 103 - 0
module/base/filter.py

@@ -0,0 +1,103 @@
+import re
+
+from module.logger import logger
+
+
+class Filter:
+    def __init__(self, regex, attr, preset=()):
+        """
+        Args:
+            regex: Regular expression.
+            attr: Attribute name.
+            preset: Build-in string preset.
+        """
+        if isinstance(regex, str):
+            regex = re.compile(regex)
+        self.regex = regex
+        self.attr = attr
+        self.preset = tuple(list(p.lower() for p in preset))
+        self.filter_raw = []
+        self.filter = []
+
+    def load(self, string):
+        string = str(string)
+        self.filter_raw = [f.strip(' \t\r\n') for f in string.split('>')]
+        self.filter = [self.parse_filter(f) for f in self.filter_raw]
+
+    def is_preset(self, filter):
+        return len(filter) and filter.lower() in self.preset
+
+    def apply(self, objs, func=None):
+        """
+        Args:
+            objs (list): List of objects and strings
+            func (callable): A function to filter object.
+                Function should receive an object as arguments, and return a bool.
+                True means add it to output.
+
+        Returns:
+            list: A list of objects and preset strings, such as [object, object, object, 'reset']
+        """
+        out = []
+        for raw, filter in zip(self.filter_raw, self.filter):
+            if self.is_preset(raw):
+                raw = raw.lower()
+                if raw not in out:
+                    out.append(raw)
+            else:
+                for index, obj in enumerate(objs):
+                    if self.apply_filter_to_obj(obj=obj, filter=filter) and obj not in out:
+                        out.append(obj)
+
+        if func is not None:
+            objs, out = out, []
+            for obj in objs:
+                if isinstance(obj, str):
+                    out.append(obj)
+                elif func(obj):
+                    out.append(obj)
+                else:
+                    # Drop this object
+                    pass
+
+        return out
+
+    def apply_filter_to_obj(self, obj, filter):
+        """
+        Args:
+            obj (object):
+            filter (list[str]):
+
+        Returns:
+            bool: If an object satisfy a filter.
+        """
+
+        for attr, value in zip(self.attr, filter):
+            if not value:
+                continue
+            if str(obj.__getattribute__(attr)).lower() != str(value):
+                return False
+
+        return True
+
+    def parse_filter(self, string):
+        """
+        Args:
+            string (str):
+
+        Returns:
+            list[strNone]:
+        """
+        string = string.replace(' ', '').lower()
+        result = re.search(self.regex, string)
+
+        if self.is_preset(string):
+            return [string]
+
+        if result and len(string) and result.span()[1]:
+            return [result.group(index + 1) for index, attr in enumerate(self.attr)]
+        else:
+            logger.warning(f'Invalid filter: "{string}". This selector does not match the regex, nor a preset.')
+            # Invalid filter will be ignored.
+            # Return strange things and make it impossible to match
+            return ['1nVa1d'] + [None] * (len(self.attr) - 1)

+ 30 - 0
module/base/log_highlighter.py

@@ -0,0 +1,30 @@
+# This Python file uses the following encoding: utf-8
+# @author runhey
+# github https://github.com/runhey
+import re
+from html import escape
+
+def highlight_text(input_text):
+    color_mapping = {
+        r'\d{2}:\d{2}:\d{2}\.\d{3}': 'cyan',
+        r'\bTrue\b': 'lime',
+        r'\bFalse\b': 'red',
+        r'DEBUG': 'cyan',
+        r'INFO': 'green',
+        r'WARNING': 'yellow',
+        r'ERROR': 'red',
+        r'CRITICAL': 'darkred'
+    }
+
+    for pattern, color in color_mapping.items():
+        input_text = re.sub(pattern, f'<span style="color: {color}">\\g<0></span>', input_text)
+
+    return input_text + '<br>'
+
+# 测试
+# input_string = 'The time is 13:20:36.411. Is it True or False? DEBUG: This is a debug message. INFO: This is an info message. WARNING: This is a warning message. ERROR: This is an error message. CRITICAL: This is a critical message.'
+# highlighted_text = highlight_text(input_string)
+# html_text = f'<html><body>{highlighted_text}</body></html>'
+# print(html_text)
+
+

+ 16 - 0
module/base/utils.py

@@ -1,7 +1,9 @@
 import re
 import re
 
 
 import cv2
 import cv2
+import sys
 import numpy as np
 import numpy as np
+import importlib
 from PIL import Image
 from PIL import Image
 
 
 REGEX_NODE = re.compile(r'(-?[A-Za-z]+)(-?\d+)')
 REGEX_NODE = re.compile(r'(-?[A-Za-z]+)(-?\d+)')
@@ -884,3 +886,17 @@ def color_bar_percentage(image, area, prev_color, reverse=False, starter=0, thre
         prev_color = np.mean(image[:, prev_index], axis=0)
         prev_color = np.mean(image[:, prev_index], axis=0)
 
 
     return 0.
     return 0.
+
+
+def load_module(moduleName :str, moduleFile :str):
+    """
+    加载模块
+    :param moduleName:
+    :param moduleFile: 文件路径带py
+    :return:
+    """
+    spec = importlib.util.spec_from_file_location(moduleName, moduleFile)
+    module = importlib.util.module_from_spec(spec)
+    spec.loader.exec_module(module)
+    sys.modules[moduleName] = module
+    return module

+ 122 - 5
module/config/config.py

@@ -6,6 +6,9 @@ import datetime
 import operator
 import operator
 import threading
 import threading
 
 
+from datetime import datetime
+
+from module.base.filter import Filter
 from module.config.config_updater import ConfigUpdater
 from module.config.config_updater import ConfigUpdater
 from module.config.config_manual import ConfigManual
 from module.config.config_manual import ConfigManual
 from module.config.config_watcher import ConfigWatcher
 from module.config.config_watcher import ConfigWatcher
@@ -14,8 +17,65 @@ from module.config.config_model import ConfigModel
 from module.config.config_state import ConfigState
 from module.config.config_state import ConfigState
 from module.config.utils import *
 from module.config.utils import *
 
 
+from module.exception import RequestHumanTakeover, ScriptError
 from module.logger import logger
 from module.logger import logger
 
 
+
+
+class Function:
+    def __init__(self, key: str, data: dict):
+        """
+        输入的是每一个ConfigModel的一个字段对象
+        :param data:
+        """
+        if isinstance(data, dict) is False:
+            self.enable = False
+            self.command = "Unknown"
+            self.next_run = DEFAULT_TIME
+            return
+        if data.get("scheduler") is None:
+            self.enable = False
+            self.command = "Unknown"
+            self.next_run = DEFAULT_TIME
+            return
+
+        self.enable: bool = data['scheduler']['enable']
+        self.command: str = ConfigModel.type(key)
+        self.next_run: datetime = data['scheduler']['next_run']
+        # self.enable = deep_get(data, keys="Scheduler.Enable", default=False)
+        # self.command = deep_get(data, keys="Scheduler.Command", default="Unknown")
+        # self.next_run = deep_get(data, keys="Scheduler.NextRun", default=DEFAULT_TIME)
+
+    def __str__(self):
+        enable = "Enable" if self.enable else "Disable"
+        return f"{self.command} ({enable}, {str(self.next_run)})"
+
+    __repr__ = __str__
+
+    def __eq__(self, other):
+        if not isinstance(other, Function):
+            return False
+
+        if self.command == other.command and self.next_run == other.next_run:
+            return True
+        else:
+            return False
+
+
+def name_to_function(name):
+    """
+    Args:
+        name (str):
+
+    Returns:
+        Function:
+    """
+    function = Function({})
+    function.command = name
+    function.enable = True
+    return function
+
+
 class Config(ConfigState, ConfigManual, ConfigWatcher, ConfigMenu):
 class Config(ConfigState, ConfigManual, ConfigWatcher, ConfigMenu):
 
 
     def __init__(self, config_name: str, task=None) -> None:
     def __init__(self, config_name: str, task=None) -> None:
@@ -84,11 +144,68 @@ class Config(ConfigState, ConfigManual, ConfigWatcher, ConfigMenu):
         """
         """
         self.model.write_json(self.config_name, self.model.dict())
         self.model.write_json(self.config_name, self.model.dict())
 
 
+    def update_scheduler(self) -> None:
+        """
+        更新调度器, 设置pending_task and waiting_task
+        :return:
+        """
+        pending_task = []
+        waiting_task = []
+        error = []
+        now = datetime.now()
+        for key, value in self.model.dict().items():
+            func = Function(key, value)
+            if not func.enable:
+                continue
+            if not isinstance(func.next_run, datetime):
+                error.append(func)
+            elif func.next_run < now:
+                pending_task.append(func)
+            else:
+                waiting_task.append(func)
+
+        f = Filter(regex=r"(.*)", attr=["command"])
+        f.load(self.SCHEDULER_PRIORITY)
+        if pending_task:
+            pending_task = f.apply(pending_task)
+        if waiting_task:
+            waiting_task = f.apply(waiting_task)
+            waiting_task = sorted(waiting_task, key=operator.attrgetter("next_run"))
+        if error:
+            pending_task = error + pending_task
+
+        self.pending_task = pending_task
+        self.waiting_task = waiting_task
+
+    def get_next(self) -> Function:
+        """
+        获取下一个要执行的任务
+        :return:
+        """
+        self.update_scheduler()
+
+        if self.pending_task:
+            logger.info(f"Pending tasks: {[f.command for f in self.pending_task]}")
+            task = self.pending_task[0]
+            logger.attr("Task", task)
+            return task
+
+        # 哪怕是没有任务,也要返回一个任务,这样才能保证调度器正常运行
+        if self.waiting_task:
+            logger.info("No task pending")
+            task = copy.deepcopy(self.waiting_task[0])
+            # task.next_run = (task.next_run + self.hoarding).replace(microsecond=0)
+            logger.attr("Task", task)
+            return task
+        else:
+            logger.critical("No task waiting or pending")
+            logger.critical("Please enable at least one task")
+            raise RequestHumanTakeover
+
+
+
 if __name__ == '__main__':
 if __name__ == '__main__':
-    config = Config(config_name='pydantic')
-    print(config.menu)
-    print(config.config_name)
+    config = Config(config_name='oas1')
+    print(config.get_next())
 
 
-    config.script.device.serial = 123
-    print(config.script.device.serial)
 
 

+ 7 - 0
module/config/config_manual.py

@@ -6,6 +6,13 @@ class ConfigManual:
     """
     """
     module.device
     module.device
     """
     """
+
+    SCHEDULER_PRIORITY = """
+        Restart
+        > AreaBoss > GoldYoukai > ExperienceYoukai > Nian
+        > Orochi > OrochiMoans > OrochiJudgement > Sougenbi > FallenSun > EternitySea
+        """
+
     DEVICE_OVER_HTTP = False
     DEVICE_OVER_HTTP = False
     FORWARD_PORT_RANGE = (20000, 21000)
     FORWARD_PORT_RANGE = (20000, 21000)
     REVERSE_SERVER_PORT = 7903
     REVERSE_SERVER_PORT = 7903

+ 4 - 3
module/config/config_menu.py

@@ -15,12 +15,13 @@ class ConfigMenu:
         # 总览
         # 总览
         self.menu["Overview"] = []
         self.menu["Overview"] = []
         # 脚本设置
         # 脚本设置
-        self.menu['Script'] = ['Script', 'General', 'Restart']
+        self.menu['Script'] = ['Script', 'General', 'Restart', 'GlobalGame']
         # 开发工具
         # 开发工具
         self.menu["Tools"] = ['Image Rule', 'Ocr Rule', 'Click Rule', 'Long Click Rule', 'Swipe Rule']
         self.menu["Tools"] = ['Image Rule', 'Ocr Rule', 'Click Rule', 'Long Click Rule', 'Swipe Rule']
+        # 刷御魂
+        self.menu["Soul Zones"] = ['Orochi', 'OrochiMoans', 'OrochiJudgement', 'Sougenbi', 'FallenSun', 'EternitySea']
         # 日常的任务
         # 日常的任务
-        self.menu["Daily Task"] = ['Territorial Demon', 'Coin Challenge']
-
+        self.menu["Daily Task"] = ['AreaBoss', 'GoldYoukai', 'ExperienceYoukai', 'Nian']
     @cached_property
     @cached_property
     def gui_menu(self) -> str:
     def gui_menu(self) -> str:
         """
         """

+ 51 - 3
module/config/config_model.py

@@ -1,6 +1,7 @@
 # This Python file uses the following encoding: utf-8
 # This Python file uses the following encoding: utf-8
 # @author runhey
 # @author runhey
 # github https://github.com/runhey
 # github https://github.com/runhey
+import re
 
 
 from pathlib import Path
 from pathlib import Path
 from pydantic import BaseModel, ValidationError, Field
 from pydantic import BaseModel, ValidationError, Field
@@ -11,7 +12,17 @@ from module.logger import logger
 # 导入配置的Python文件
 # 导入配置的Python文件
 from tasks.Script.config import Script
 from tasks.Script.config import Script
 from tasks.Restart.config import Restart
 from tasks.Restart.config import Restart
-
+from tasks.GlobalGame.config import GlobalGame
+from tasks.AreaBoss.config import AreaBoss
+from tasks.ExperienceYoukai.config import ExperienceYoukai
+from tasks.GoldYoukai.config import GoldYoukai
+from tasks.Nian.config import Nian
+from tasks.Orochi.config import Orochi
+from tasks.OrochiMoans.config import OrochiMoans
+from tasks.OrochiJudgement.config import OrochiJudgement
+from tasks.Sougenbi.config import Sougenbi
+from tasks.FallenSun.config import FallenSun
+from tasks.EternitySea.config import EternitySea
 
 
 
 
 
 
@@ -21,17 +32,36 @@ class ConfigModel(BaseModel):
     config_name: str = "oas"
     config_name: str = "oas"
     script: Script = Field(default_factory=Script)
     script: Script = Field(default_factory=Script)
     restart: Restart = Field(default_factory=Restart)
     restart: Restart = Field(default_factory=Restart)
+    global_game: GlobalGame = Field(default_factory=GlobalGame)
+
+    # 这些是每日人物的
+    area_boss: AreaBoss = Field(default_factory=AreaBoss)
+    experience_youkai: ExperienceYoukai = Field(default_factory=ExperienceYoukai)
+    gold_youkai: GoldYoukai = Field(default_factory=GoldYoukai)
+    nian: Nian = Field(default_factory=Nian)
+
+    # 这些是刷御魂的
+    orochi: Orochi = Field(default_factory=Orochi)
+    orochi_moans: OrochiMoans = Field(default_factory=OrochiMoans)
+    orochi_judgement: OrochiJudgement = Field(default_factory=OrochiJudgement)
+    sougenbi: Sougenbi = Field(default_factory=Sougenbi)
+    fallen_sun: FallenSun = Field(default_factory=FallenSun)
+    eternity_sea: EternitySea = Field(default_factory=EternitySea)
+
 
 
     # @validator('script')
     # @validator('script')
     # def script_validator(cls, v):
     # def script_validator(cls, v):
     #     if v is None:
     #     if v is None:
     #         return Script()
     #         return Script()
 
 
-    def __init__(self, config_name: str) -> None:
+    def __init__(self, config_name: str=None) -> None:
         """
         """
 
 
         :param config_name:
         :param config_name:
         """
         """
+        if not config_name:
+            super().__init__()
+            return
         data = self.read_json(config_name)
         data = self.read_json(config_name)
         data["config_name"] = config_name
         data["config_name"] = config_name
         super().__init__(**data)
         super().__init__(**data)
@@ -103,6 +133,21 @@ class ConfigModel(BaseModel):
         """
         """
         self.write_json(self.config_name, self.dict())
         self.write_json(self.config_name, self.dict())
 
 
+    @staticmethod
+    def type(key: str) -> str:
+        """
+        输入模型的键值,获取这个字段对象的类型 比如输入是orochi输出是Orochi
+        :param key:
+        :return:
+        """
+        field_type: str = str(ConfigModel.__annotations__[key])
+        # return field_type
+        if '.' in field_type:
+            classname = field_type.split('.')[-1][:-2]
+            return classname
+        else:
+            classname = re.findall(r"'([^']*)'", field_type)[0]
+            return classname
 
 
     # @root_validator
     # @root_validator
     # def on_on_property_change(cls, values):
     # def on_on_property_change(cls, values):
@@ -123,4 +168,7 @@ if __name__ == "__main__":
         c = ConfigModel()
         c = ConfigModel()
     # c.write_json('oas1', c.dict())
     # c.write_json('oas1', c.dict())
     # c.write_json('oas1', c.schema())
     # c.write_json('oas1', c.schema())
-    c.script.device.serial = "5555"
+    # for key, value in c.dict().items():
+    #     print(ConfigModel.type(key))
+
+

+ 3 - 2
module/config/config_state.py

@@ -9,5 +9,6 @@ class ConfigState:
     """
     """
     def __init__(self, config_name: str) -> None:
     def __init__(self, config_name: str) -> None:
         self.config_name = config_name
         self.config_name = config_name
-        self.pending_task = []
-        self.waiting_task = []
+        self.pending_task: list["Function"] = []
+        self.waiting_task: list["Function"] = []
+        self.task: str = None  # 任务名大驼峰

BIN
module/config/i18n/zh_CN.qm


+ 72 - 0
module/config/i18n/zh_CN.ts

@@ -142,5 +142,77 @@
         <source>Restart</source>
         <source>Restart</source>
         <translation>重启</translation>
         <translation>重启</translation>
     </message>
     </message>
+	<message>
+        <source>Tools</source>
+        <translation>工具</translation>
+    </message>
+	<message>
+        <source>Image Rule</source>
+        <translation>截图规范</translation>
+    </message>
+	<message>
+        <source>Ocr Rule</source>
+        <translation>OCR规范</translation>
+    </message>
+	<message>
+        <source>Click Rule</source>
+        <translation>点击规范</translation>
+    </message>
+	<message>
+        <source>Long Click Rule</source>
+        <translation>长按规范</translation>
+    </message>
+	<message>
+        <source>Swipe Rule</source>
+        <translation>滑动规范</translation>
+    </message>
+	<message>
+        <source>Daily Task</source>
+        <translation>日常任务</translation>
+    </message>
+	<message>
+        <source>AreaBoss</source>
+        <translation>地狱鬼王</translation>
+    </message>
+	<message>
+        <source>GoldYoukai</source>
+        <translation>金币妖怪</translation>
+    </message>
+	<message>
+        <source>ExperienceYoukai</source>
+        <translation>经验妖怪</translation>
+    </message>
+	<message>
+        <source>Nian</source>
+        <translation>年兽</translation>
+    </message>
+	<message>
+        <source>Soul Zones</source>
+        <translation>御魂副本</translation>
+    </message>
+	<message>
+        <source>Orochi</source>
+        <translation>八岐大蛇</translation>
+    </message>
+	<message>
+        <source>OrochiMoans</source>
+        <translation>御魂悲鸣</translation>
+    </message>
+	<message>
+        <source>OrochiJudgement</source>
+        <translation>御魂神罚</translation>
+    </message>
+	<message>
+        <source>Sougenbi</source>
+        <translation>业原火</translation>
+    </message>
+	<message>
+        <source>FallenSun</source>
+        <translation>日轮之城</translation>
+    </message>
+	<message>
+        <source>EternitySea</source>
+        <translation>永生之海</translation>
+    </message>
 </context>
 </context>
 </TS>
 </TS>

+ 37 - 16
module/dev_tools/assets_extract.py

@@ -4,7 +4,7 @@
 import json
 import json
 import numpy as np
 import numpy as np
 
 
-# from tqdm.contrib.concurrent import process_map
+from tqdm.contrib.concurrent import process_map
 from pathlib import Path
 from pathlib import Path
 
 
 from module.logger import logger
 from module.logger import logger
@@ -97,7 +97,8 @@ class ClickExtractor:
         description: str = f'\t# {item["description"]} \n'
         description: str = f'\t# {item["description"]} \n'
         name: str = f'\tC_{name_transform(item["itemName"])} = RuleClick(' \
         name: str = f'\tC_{name_transform(item["itemName"])} = RuleClick(' \
                     f'roi_front=({item["roiFront"]}), ' \
                     f'roi_front=({item["roiFront"]}), ' \
-                    f'roi_back=({item["roiBack"]}))\n'
+                    f'roi_back=({item["roiBack"]}), ' \
+                    f'name="{item["itemName"]}")\n'
         return description + name
         return description + name
 
 
 class LongClickExtractor:
 class LongClickExtractor:
@@ -125,7 +126,8 @@ class LongClickExtractor:
         name: str = f'\tL_{name_transform(item["itemName"])} = RuleLongClick(' \
         name: str = f'\tL_{name_transform(item["itemName"])} = RuleLongClick(' \
                     f'roi_front=({item["roiFront"]}), ' \
                     f'roi_front=({item["roiFront"]}), ' \
                     f'roi_back=({item["roiBack"]}), ' \
                     f'roi_back=({item["roiBack"]}), ' \
-                    f'duration={item["duration"]})\n'
+                    f'duration={item["duration"]}, ' \
+                    f'name="{item["itemName"]}")\n'
         return description + name
         return description + name
 
 
 class SwipeExtractor:
 class SwipeExtractor:
@@ -153,7 +155,8 @@ class SwipeExtractor:
         name: str = f'\tS_{name_transform(item["itemName"])} = RuleSwipe(' \
         name: str = f'\tS_{name_transform(item["itemName"])} = RuleSwipe(' \
                     f'roi_front=({item["roiFront"]}), ' \
                     f'roi_front=({item["roiFront"]}), ' \
                     f'roi_back=({item["roiBack"]}), ' \
                     f'roi_back=({item["roiBack"]}), ' \
-                    f'mode="{item["mode"]}")\n'
+                    f'mode="{item["mode"]}", ' \
+                    f'name="{item["itemName"]}")\n'
         return description + name
         return description + name
 
 
 
 
@@ -168,10 +171,12 @@ class AssetsExtractor:
         self.task_path = Path.cwd() / MODULE_FOLDER / task_name
         self.task_path = Path.cwd() / MODULE_FOLDER / task_name
         self.assets_file = Path.cwd() / MODULE_FOLDER / task_name / ASSETS_FILE
         self.assets_file = Path.cwd() / MODULE_FOLDER / task_name / ASSETS_FILE
 
 
+        self.class_name = f'\nclass {task_name}Assets: \n'
+
         self._result = ''
         self._result = ''
         for import_exp in IMPORT_EXP:
         for import_exp in IMPORT_EXP:
             self._result += import_exp
             self._result += import_exp
-        self._result += ASSETS_CLASS
+        self._result += self.class_name
 
 
 
 
     def all_json_file(self) -> list:
     def all_json_file(self) -> list:
@@ -254,31 +259,47 @@ class AssetsExtractor:
         生成一个assets.py文件
         生成一个assets.py文件
         :return:
         :return:
         """
         """
+        result = ''
         for file in self.all_json_file():
         for file in self.all_json_file():
             data = self.read_file(file)
             data = self.read_file(file)
             if not data:
             if not data:
                 continue
                 continue
             if self.is_image_file(data):
             if self.is_image_file(data):
-                self._result += ImageExtractor(file, data).result
+                result += ImageExtractor(file, data).result
             elif self.is_click_file(data):
             elif self.is_click_file(data):
-                self._result += ClickExtractor(file, data).result
+                result += ClickExtractor(file, data).result
             elif self.is_long_click_file(data):
             elif self.is_long_click_file(data):
-                self._result += LongClickExtractor(file, data).result
+                result += LongClickExtractor(file, data).result
             elif self.is_swipe_file(data):
             elif self.is_swipe_file(data):
-                self._result += SwipeExtractor(file, data).result
+                result += SwipeExtractor(file, data).result
 
 
+        if result == '':
+            logger.error(f'There are no resource files under the {self.task_name} task')
+            self._result += '\tpass'
+        else:
+            self._result += result
         self._result += '\n\n'
         self._result += '\n\n'
         self.write_file()
         self.write_file()
 
 
 
 
 class AllAssetsExtractor:
 class AllAssetsExtractor:
-    pass
+    def __init__(self):
+        """
+        获取./tasks目录下的所有任务文件夹,遍历每一个任务文件夹提取assets
+        """
+        logger.info('All assets extract')
+        self.task_path = Path.cwd() / MODULE_FOLDER
+        self.task_list = [x.name for x in self.task_path.iterdir() if x.is_dir()]
+        process_map(self.work, self.task_list, max_workers=4)
+
+    @staticmethod
+    def work(task_name: str):
+        me = AssetsExtractor(task_name)
+        me.extract()
 
 
 
 
-if __name__ == "__main__":
-    c = AssetsExtractor('CoinChallenge')
-    # print(c.assets_file)
-    # print(c.task_path)
-    # print(c.all_json_file())
 
 
-    c.extract()
+if __name__ == "__main__":
+    # c = AssetsExtractor('GeneralBattle')
+    # c.extract()
+    AllAssetsExtractor()

+ 20 - 0
module/dev_tools/template_update.py

@@ -0,0 +1,20 @@
+# This Python file uses the following encoding: utf-8
+# @author runhey
+# github https://github.com/runhey
+import json
+
+from pathlib import Path
+
+from module.config.config_model import ConfigModel
+from module.config.config import Config
+from module.logger import logger
+
+
+
+
+
+if __name__ == "__main__":
+    # ConfigModel对象并更新保存
+    config = ConfigModel()
+    config_path = Path("./config/template.json")
+    config.write_json("template", config.dict())

+ 1 - 1
module/device/app_control.py

@@ -12,7 +12,7 @@ class AppControl(Adb, Uiautomator2):
     _app_u2_family = ['uiautomator2', 'minitouch', 'scrcpy']
     _app_u2_family = ['uiautomator2', 'minitouch', 'scrcpy']
 
 
     def app_is_running(self) -> bool:
     def app_is_running(self) -> bool:
-        method = self.config.script.emulator.control_method
+        method = self.config.script.device.control_method
         # if self.is_wsa:
         # if self.is_wsa:
         #     package = self.app_current_wsa()
         #     package = self.app_current_wsa()
         if method in AppControl._app_u2_family:
         if method in AppControl._app_u2_family:

+ 86 - 30
module/device/control.py

@@ -11,7 +11,7 @@ from module.device.method.window import Window
 from module.logger import logger
 from module.logger import logger
 
 
 
 
-class Control(Minitouch, Scrcpy, Window):
+class Control(Minitouch, Adb, Scrcpy, Window):
     def handle_control_check(self, button):
     def handle_control_check(self, button):
         # Will be overridden in Device
         # Will be overridden in Device
         pass
         pass
@@ -27,26 +27,60 @@ class Control(Minitouch, Scrcpy, Window):
             # 'MaaTouch': self.click_maatouch,
             # 'MaaTouch': self.click_maatouch,
         }
         }
 
 
-    def click(self, button, control_check=True):
+    @cached_property
+    def long_click_methods(self):
+        return {
+            'ADB': self.long_click_adb,
+            'uiautomator2': self.long_click_uiautomator2,
+            'minitouch': self.long_click_minitouch,
+            'window_message': self.long_click_window_message,
+            'scrcpy': self.long_click_scrcpy
+            # 'Hermit': self.click_hermit,
+            # 'MaaTouch': self.click_maatouch,
+        }
+
+    # def click(self, button, control_check=True):
+    #     """
+    #     后面改一改  不用用button的逻辑
+    #     :param button:
+    #     :param control_check:
+    #     :return:
+    #     """
+    #     if control_check:
+    #         self.handle_control_check(button)
+    #     x, y = random_rectangle_point(button.button)
+    #     x, y = ensure_int(x, y)
+    #     logger.info(
+    #         'Click %s @ %s' % (point2str(x, y), button)
+    #     )
+    #     method = self.click_methods.get(
+    #         self.config.script.emulator.control_method,
+    #         self.click_adb
+    #     )
+    #     method(x, y)
+
+    def click(self, x: int, y: int, control_check=True, control_name='Click') -> None:
         """
         """
-        后面改一改  不用用button的逻辑
-        :param button:
+
+        :param control_name:
+        :param x:
+        :param y:
         :param control_check:
         :param control_check:
         :return:
         :return:
         """
         """
         if control_check:
         if control_check:
-            self.handle_control_check(button)
-        x, y = random_rectangle_point(button.button)
+            self.handle_control_check(control_name)
         x, y = ensure_int(x, y)
         x, y = ensure_int(x, y)
         logger.info(
         logger.info(
-            'Click %s @ %s' % (point2str(x, y), button)
+            'Click %s ' % (point2str(x, y))
         )
         )
         method = self.click_methods.get(
         method = self.click_methods.get(
-            self.config.script.emulator.control_method,
+            self.config.script.device.control_method,
             self.click_adb
             self.click_adb
         )
         )
         method(x, y)
         method(x, y)
 
 
+
     def multi_click(self, button, n, interval=(0.1, 0.2)):
     def multi_click(self, button, n, interval=(0.1, 0.2)):
         """
         """
         也是不能用button的逻辑
         也是不能用button的逻辑
@@ -65,39 +99,61 @@ class Control(Minitouch, Scrcpy, Window):
 
 
             self.click(button, control_check=False)
             self.click(button, control_check=False)
 
 
-    def long_click(self, button, duration=(1, 1.2)):
+    # def long_click(self, button, duration=(1, 1.2)):
+    #     """
+    #
+    #     :param button:
+    #     :param duration:
+    #     :return:
+    #     """
+    #     self.handle_control_check(button)
+    #     x, y = random_rectangle_point(button.button)
+    #     x, y = ensure_int(x, y)
+    #     duration = ensure_time(duration)
+    #     logger.info(
+    #         'Click %s @ %s, %s' % (point2str(x, y), button, duration)
+    #     )
+    #     method = self.config.script.emulator.control_method
+    #     if method == 'minitouch':
+    #         self.long_click_minitouch(x, y, duration)
+    #     elif method == 'window_message':
+    #         self.long_click_window_message(x, y, duration)
+    #     elif method == 'uiautomator2':
+    #         self.long_click_uiautomator2(x, y, duration)
+    #     elif method == 'scrcpy':
+    #         self.long_click_scrcpy(x, y, duration)
+    #     # elif method == 'MaaTouch':
+    #     #     self.long_click_maatouch(x, y, duration)
+    #     else:
+    #         self.swipe_adb((x, y), (x, y), duration)
+
+    def long_click(self, x: int, y: int, duration=(0.5, 2), control_name='LongClick') -> None:
         """
         """
 
 
-        :param button:
-        :param duration:
+        :param control_name:
+        :param x:
+        :param y:
+        :param duration: 单位是s
         :return:
         :return:
         """
         """
-        self.handle_control_check(button)
-        x, y = random_rectangle_point(button.button)
+        self.handle_control_check(control_name)
         x, y = ensure_int(x, y)
         x, y = ensure_int(x, y)
+        if duration is None:
+            duration = 0.8
         duration = ensure_time(duration)
         duration = ensure_time(duration)
         logger.info(
         logger.info(
-            'Click %s @ %s, %s' % (point2str(x, y), button, duration)
+            'Click %s @ %s' % (point2str(x, y), duration)
         )
         )
-        method = self.config.script.emulator.control_method
-        if method == 'minitouch':
-            self.long_click_minitouch(x, y, duration)
-        elif method == 'window_message':
-            self.long_click_window_message(x, y, duration)
-        elif method == 'uiautomator2':
-            self.long_click_uiautomator2(x, y, duration)
-        elif method == 'scrcpy':
-            self.long_click_scrcpy(x, y, duration)
-        # elif method == 'MaaTouch':
-        #     self.long_click_maatouch(x, y, duration)
-        else:
-            self.swipe_adb((x, y), (x, y), duration)
+        method = self.long_click_methods.get(
+            self.config.script.emulator.control_method,
+            self.long_click_adb)
+        method(x, y, duration)
 
 
-    def swipe(self, p1, p2, duration=(0.1, 0.2), name='SWIPE', distance_check=True):
-        self.handle_control_check(name)
+    def swipe(self, p1, p2, duration=(0.1, 0.2), control_name='SWIPE', distance_check=True):
+        self.handle_control_check(control_name)
         p1, p2 = ensure_int(p1, p2)
         p1, p2 = ensure_int(p1, p2)
         duration = ensure_time(duration)
         duration = ensure_time(duration)
-        method = self.config.script.emulator.control_method
+        method = self.config.script.device.control_method
         if method == 'minitouch':
         if method == 'minitouch':
             logger.info('Swipe %s -> %s' % (point2str(*p1), point2str(*p2)))
             logger.info('Swipe %s -> %s' % (point2str(*p1), point2str(*p2)))
         elif method == 'window_message':
         elif method == 'window_message':

+ 1 - 0
module/device/handle.py

@@ -105,6 +105,7 @@ class Handle:
         'bluestacks_5': ['root_handle_title'],
         'bluestacks_5': ['root_handle_title'],
         'bluestacks_family': ['root_handle_title']
         'bluestacks_family': ['root_handle_title']
     }
     }
+    config: Config = None
 
 
     def __init__(self, config) -> None:
     def __init__(self, config) -> None:
         """
         """

+ 12 - 0
module/device/method/adb.py

@@ -186,6 +186,18 @@ class Adb(Connection):
         duration = int(duration * 1000)
         duration = int(duration * 1000)
         self.adb_shell(['input', 'swipe', *p1, *p2, duration])
         self.adb_shell(['input', 'swipe', *p1, *p2, duration])
 
 
+    def long_click_adb(self, x: float, y: float, duration: float):
+        """
+
+        :param x:
+        :param y:
+        :param duration: 单位是s
+        :return:
+        """
+        if not 0 < duration < 3:
+            duration = duration / 1000
+        self.adb_shell(['input', 'swipe', x, y, x, y, int(duration*1000)])
+
     @retry
     @retry
     def app_current_adb(self):
     def app_current_adb(self):
         """
         """

+ 12 - 9
module/device/method/window.py

@@ -29,9 +29,9 @@ from module.device.handle import Handle, window_scale_rate
 
 
 class Window(Handle):
 class Window(Handle):
 
 
-    def __init__(self):
+    def __init__(self, *args, **kwargs):
         logger.info("Window init")
         logger.info("Window init")
-        super().__init__()
+        super().__init__(*args, **kwargs)
 
 
     def screenshot_window_background(self):
     def screenshot_window_background(self):
         """
         """
@@ -61,11 +61,12 @@ class Window(Handle):
         signedIntsArray = saveBitMap.GetBitmapBits(True)
         signedIntsArray = saveBitMap.GetBitmapBits(True)
         imgSrceen = frombuffer(signedIntsArray, dtype='uint8')
         imgSrceen = frombuffer(signedIntsArray, dtype='uint8')
         imgSrceen.shape = (heightScreen, widthScreen, 4)
         imgSrceen.shape = (heightScreen, widthScreen, 4)
-        # imgSrceen = cv2.cvtColor(imgSrceen, cv2.COLOR_BGRA2GRAY)
+        # 这点很重要 在alas中图片以np.ndarray(RGB)的顺序存储。但是opencv是以BGR
+        imgSrceen = cv2.cvtColor(imgSrceen, cv2.COLOR_BGR2RGB)
         # imgSrceen = cv2.resize(imgSrceen, (win_size[0], win_size[1]))
         # imgSrceen = cv2.resize(imgSrceen, (win_size[0], win_size[1]))
         # 很奇怪的
         # 很奇怪的
 
 
-        # 测试显示截图图片
+        # # 测试显示截图图片
         # cv2.namedWindow('imgSrceen')  # 命名窗口
         # cv2.namedWindow('imgSrceen')  # 命名窗口
         # cv2.imshow("imgSrceen", imgSrceen)  # 显示
         # cv2.imshow("imgSrceen", imgSrceen)  # 显示
         # cv2.waitKey(0)
         # cv2.waitKey(0)
@@ -127,25 +128,27 @@ class Window(Handle):
         #     y = 0
         #     y = 0
         # 我不知道为什么的使用的pywin32==306的版本会导致获取的图片的是(1024, 576)
         # 我不知道为什么的使用的pywin32==306的版本会导致获取的图片的是(1024, 576)
         # 所有我在点击的时候会除以这个缩放比例
         # 所有我在点击的时候会除以这个缩放比例
+        # 但是后面发现又不是影响的很奇怪
+
         x = int(x / self.window_scale_rate)
         x = int(x / self.window_scale_rate)
         y = int(y / self.window_scale_rate)
         y = int(y / self.window_scale_rate)
-        logger.info(self.control_handle_list)
+        # print(f"我点击的x:{x}, y:{y}")
         emulator_type = len(self.control_handle_list)
         emulator_type = len(self.control_handle_list)
         if emulator_type == 2:  # mumu模拟器
         if emulator_type == 2:  # mumu模拟器
             SendMessage(self.control_handle_list[0], WM_LBUTTONDOWN, 0, MAKELONG(x, y))  # 模拟鼠标按下 先是父窗口 上面的框高度是57
             SendMessage(self.control_handle_list[0], WM_LBUTTONDOWN, 0, MAKELONG(x, y))  # 模拟鼠标按下 先是父窗口 上面的框高度是57
-            time.sleep((random.randint(100, 200)) / 1000.0)  # 点击弹起改为随机,时间100ms-200ms
+            time.sleep((random.randint(200, 400)) / 1000.0)  # 点击弹起改为随机,时间100ms-200ms
             SendMessage(self.control_handle_list[1], WM_LBUTTONUP, 0, MAKELONG(x, y))  # 模拟鼠标弹起 后是子窗口
             SendMessage(self.control_handle_list[1], WM_LBUTTONUP, 0, MAKELONG(x, y))  # 模拟鼠标弹起 后是子窗口
         elif emulator_type > 2:  # 夜神模拟器
         elif emulator_type > 2:  # 夜神模拟器
             SendMessage(self.control_handle_list[0], WM_LBUTTONDOWN, 0, MAKELONG(x, y))  # 模拟鼠标按下 先是父窗口 上面的框高度是57
             SendMessage(self.control_handle_list[0], WM_LBUTTONDOWN, 0, MAKELONG(x, y))  # 模拟鼠标按下 先是父窗口 上面的框高度是57
             SendMessage(self.control_handle_list[1], WM_LBUTTONDOWN, 0, MAKELONG(x, y))
             SendMessage(self.control_handle_list[1], WM_LBUTTONDOWN, 0, MAKELONG(x, y))
             SendMessage(self.control_handle_list[2], WM_LBUTTONDOWN, 0, MAKELONG(x, y))
             SendMessage(self.control_handle_list[2], WM_LBUTTONDOWN, 0, MAKELONG(x, y))
             SendMessage(self.control_handle_list[3], WM_LBUTTONDOWN, 0, MAKELONG(x, y))
             SendMessage(self.control_handle_list[3], WM_LBUTTONDOWN, 0, MAKELONG(x, y))
-            time.sleep((random.randint(100, 200)) / 1000.0)  # 点击弹起改为随机,时间100ms-200ms
+            time.sleep((random.randint(200, 400)) / 1000.0)  # 点击弹起改为随机,时间100ms-200ms
             SendMessage(self.control_handle_list[3], WM_LBUTTONUP, 0, MAKELONG(x, y))  # 模拟鼠标弹起 后是子窗口
             SendMessage(self.control_handle_list[3], WM_LBUTTONUP, 0, MAKELONG(x, y))  # 模拟鼠标弹起 后是子窗口
         elif emulator_type == 1:  # 雷电模拟器
         elif emulator_type == 1:  # 雷电模拟器
             clickPos = MAKELONG(x, y)
             clickPos = MAKELONG(x, y)
             SendMessage(self.control_handle_list[0], WM_LBUTTONDOWN, 0, clickPos)  # 模拟鼠标按下
             SendMessage(self.control_handle_list[0], WM_LBUTTONDOWN, 0, clickPos)  # 模拟鼠标按下
-            time.sleep((random.randint(100, 200)) / 1000.0)  # 点击弹起改为随机,时间100ms-200ms
+            time.sleep((random.randint(200, 400)) / 1000.0)  # 点击弹起改为随机,时间100ms-200ms
             SendMessage(self.control_handle_list[0], WM_LBUTTONUP, 0, clickPos)  # 模拟鼠标弹起
             SendMessage(self.control_handle_list[0], WM_LBUTTONUP, 0, clickPos)  # 模拟鼠标弹起
 
 
     def long_click_window_message(self, x: int, y: int, duration: float):
     def long_click_window_message(self, x: int, y: int, duration: float):
@@ -282,5 +285,5 @@ if __name__ == "__main__":
     w = Window(config='oas1')
     w = Window(config='oas1')
     img = w.screenshot_window_background()
     img = w.screenshot_window_background()
     logger.info(img.shape)
     logger.info(img.shape)
-    # w.click_window_message(x=350, y=220)
+    w.click_window_message(x=759, y=184)
     # w.swipe_window_message(startPos=[200, 5], endPos=[300, 300])
     # w.swipe_window_message(startPos=[200, 5], endPos=[300, 300])

+ 3 - 0
module/exception.py

@@ -57,3 +57,6 @@ class RequestHumanTakeover(Exception):
     # Request human takeover
     # Request human takeover
     # Alas is unable to handle such error, probably because of wrong settings.
     # Alas is unable to handle such error, probably because of wrong settings.
     pass
     pass
+
+class TaskEnd(Exception):
+    pass

+ 174 - 7
module/gui/context/process_manager.py

@@ -4,16 +4,24 @@
 import socket
 import socket
 import random
 import random
 import zerorpc
 import zerorpc
+import asyncio
 import cv2
 import cv2
 import msgpack
 import msgpack
 import numpy as np
 import numpy as np
 import io
 import io
+import json
 
 
-from typing import Union, Any
+from typing import Union, Any, Dict
 from cached_property import cached_property
 from cached_property import cached_property
 from PySide6.QtCore import QObject, Slot, Signal, Property
 from PySide6.QtCore import QObject, Slot, Signal, Property
 from PySide6.QtGui import QImage
 from PySide6.QtGui import QImage
+from queue import Queue, Empty
+from rich.console import Console
+from multiprocessing.managers import SyncManager
+# from multiprocessing import Queue
+from threading import Thread
 
 
+from module.base.log_highlighter import highlight_text
 from module.gui.process.script_process import ScriptProcess
 from module.gui.process.script_process import ScriptProcess
 from module.config.config_menu import ConfigMenu
 from module.config.config_menu import ConfigMenu
 from module.gui.context.add import Add
 from module.gui.context.add import Add
@@ -44,16 +52,31 @@ class ProcessManager(QObject):
     """
     """
     进程管理
     进程管理
     """
     """
+    log_signal = Signal(str, str)  # 日志信号
+    sig_update_task = Signal(str, str)  # 更新当前运行的任务任务信号
+    sig_update_pending = Signal(str, str)  # 更新等待运行的任务信号
+    sig_update_waiting = Signal(str, str)  # 更新等待运行的任务信号
 
 
     def __init__(self) -> None:
     def __init__(self) -> None:
         """
         """
         init
         init
         """
         """
         super().__init__()
         super().__init__()
-        self.processes = {}  # 持有所有的进程
-        self.ports = {}  # 持有所有的端口
+        self.processes: Dict[str, ScriptProcess] = {}  # 持有所有的进程
+        self.ports: Dict[str, int] = {}  # 持有所有的端口
         self.clients = {}  # zerorpc连接的客户端
         self.clients = {}  # zerorpc连接的客户端
 
 
+        self.manager = SyncManager()  # 管理器
+        self.manager.start()
+        self.log_queue: Dict[str, Queue] = {}  # 日志队列
+        self.log_thread: Dict[str, Thread] = {}  # 日志线程
+
+        self.update_queue: Queue = None  # 每次更新任务的时候push进来给gui显示
+        self.update_thread: Thread = None  # 更新线程
+        self.start_update_tasks()  # 启动更新线程
+
+        self.event_loop = asyncio.get_event_loop()  # 事件循环
+
     @Slot()
     @Slot()
     def create_all(self) -> None:
     def create_all(self) -> None:
         """
         """
@@ -64,18 +87,27 @@ class ProcessManager(QObject):
         for config in configs:
         for config in configs:
             self.add(config)
             self.add(config)
 
 
+    @Slot(str)
     def add(self, config: str) -> None:
     def add(self, config: str) -> None:
         """
         """
         add
         add
-        :param config:
+        :param config: 如oas1
         :return:
         :return:
         """
         """
         if config not in self.processes:
         if config not in self.processes:
+            # 初始化端口
             port = 40000 + random.randint(0, 200)
             port = 40000 + random.randint(0, 200)
             while is_port_in_use('127.0.0.1', port):
             while is_port_in_use('127.0.0.1', port):
                 port = 40000 + random.randint(0, 200)
                 port = 40000 + random.randint(0, 200)
             self.ports[config] = port
             self.ports[config] = port
-            self.processes[config] = ScriptProcess(config, port)
+            # 初始化日志队列
+            q = self.start_log(config)
+
+            # 初始化启动进程
+            self.processes[config] = ScriptProcess(config, port, q, update_queue=self.update_queue)
+            self.log_thread[config].start()
+
+            # 下面是启动 zerorpc 客户端
             logger.info(f'create script {config} on port {port}')
             logger.info(f'create script {config} on port {port}')
             try:
             try:
                 self.clients[config] = zerorpc.Client()
                 self.clients[config] = zerorpc.Client()
@@ -104,14 +136,34 @@ class ProcessManager(QObject):
         else:
         else:
             logger.info(f'script {config} is not running')
             logger.info(f'script {config} is not running')
 
 
+    @Slot(str)
     def restart(self, config: str) -> None:
     def restart(self, config: str) -> None:
         """
         """
-        restart
+        restart  重启某个进程(会重启zerorpc),但是ports、clients、log_queue、log_thread不会重启
         :param config:
         :param config:
         :return:
         :return:
         """
         """
         if config in self.processes:
         if config in self.processes:
-            self.processes[config].restart()
+            if not self.processes[config].is_alive():  # 如果进程已经死亡,那么就重新启动
+                logger.info(f'restart script {config}')
+
+
+            self.processes[config].terminate()  # 强制结束进程
+            if self.ports[config] is None:
+                logger.error(f'{config} port {config} is None')
+            if self.clients[config] is None:
+                logger.error(f'{config} client {config} is None')
+            if self.log_queue[config] is None:
+                logger.info(f'{config} log_queue {config} is None')
+                self.log_queue[config] = self.manager.Queue()
+            if self.log_thread[config] is None or self.log_thread[config].is_alive() is False:
+                logger.info(f'{config} log_thread {config} is None')
+
+            self.processes[config] = ScriptProcess(config=config,
+                                                   port=self.ports[config],
+                                                   log_queue=self.log_queue[config],
+                                                   update_queue=self.update_queue)
+            self.processes[config].start()
             logger.info(f'restart script {config}')
             logger.info(f'restart script {config}')
         else:
         else:
             logger.info(f'script {config} is not running')
             logger.info(f'script {config} is not running')
@@ -277,3 +329,118 @@ class ProcessManager(QObject):
         else:
         else:
             logger.info(f'script {config} is not running')
             logger.info(f'script {config} is not running')
             return None
             return None
+
+    def start_log(self, config_name: str) -> Queue:
+        """
+        启动某个脚本实例config_name的log: 具体为创建一个queue信息队列,然后创建一个log线程,将queue传入log线程
+        :param config_name:
+        :return:
+        """
+        # if config_name not in self.processes:
+        #     logger.error(f'Process manager has no config {config_name}')
+        #     logger.info(f'Script {config_name} is not running')
+        #     return None
+
+        if config_name not in self.log_queue:
+            self.log_queue[config_name] = self.manager.Queue()
+
+
+        if config_name not in self.log_thread:
+            self.log_thread[config_name] = Thread(target=self.log_thread_func, args=(config_name,), daemon=True)
+
+        return self.log_queue[config_name]
+
+    def log_thread_func(self, config_name: str) -> None:
+        """
+        log线程函数,将queue中的信息解析
+        :param config_name:
+        :return:
+        """
+        q = self.log_queue[config_name] if config_name in self.log_queue else None
+        if q is None:
+            logger.error(f'Process manager has no config {config_name}')
+            logger.info(f'Script {config_name} is not running')
+            return
+
+        while self.log_thread[config_name].is_alive():
+            try:
+                log = q.get(timeout=1)
+                if log is None:
+                    continue
+                log = highlight_text(str(log))
+                self.log_signal.emit(config_name, log)
+
+            except Empty:
+                continue
+            except Exception as e:
+                logger.error(f'Log thread of {config_name} error: {e}')
+                break
+
+    def start_update_tasks(self) -> None:
+        """
+        启动更新任务的线程
+        :return:
+        """
+        if self.update_queue is not None and self.update_thread is not None:
+            logger.error(f'Update thread has already started')
+
+        self.update_queue = self.manager.Queue()
+        self.update_thread = Thread(target=self.update_thread_func, daemon=True)
+        self.update_thread.start()
+
+    def update_thread_func(self) -> None:
+        """
+        更新 任务的 线程函数
+        从self.update_queue中获取信息,然后解析, 推送到gui
+        :return:
+        """
+        logger.info(f'Update thread start')
+        while self.update_thread.is_alive():
+            try:
+                update = self.update_queue.get(timeout=1)
+                if update is None:
+                    continue
+                if not isinstance(update, dict):
+                    continue
+
+                logger.info(f'Update thread get')
+                for key, value in update.items():
+                    if "task" and "pending" and "waiting" in value:
+                        self.sig_update_task.emit(key, json.dumps(value["task"]))
+                        self.sig_update_pending.emit(key, json.dumps(value["pending"]))
+                        self.sig_update_waiting.emit(key, json.dumps(value["waiting"]))
+
+            except Empty:
+                continue
+            except Exception as e:
+                logger.error(f'Update thread error: {e}')
+                break
+
+    @Slot(str)
+    def start_script(self, config: str) -> None:
+        """
+        启动脚本的loop
+        :param config:
+        :return:
+        """
+        if not self.processes[config].is_alive():
+            logger.info(f'Start script {config}')
+            return self.restart(config)
+
+        logger.info(f'Script {config} is already running')
+
+        self.clients[config].start_loop()
+
+    @Slot(str)
+    def stop_script(self, config: str) -> None:
+        """
+        停止脚本的loop
+        :param config:
+        :return:
+        """
+        if config in self.processes:
+            logger.info(f'Stop script {config}')
+            self.processes[config].stop()
+        else:
+            logger.info(f'Script {config} is not running')
+

+ 31 - 0
module/gui/context/utils.py

@@ -0,0 +1,31 @@
+# This Python file uses the following encoding: utf-8
+# @author runhey
+# github https://github.com/runhey
+import re
+from pathlib import Path
+from datetime import datetime
+from PySide6.QtCore import QObject, Slot, Signal
+
+from module.logger import logger
+
+
+class Utils(QObject):
+
+    def __init__(self) -> None:
+        super(Utils, self).__init__()
+
+    @Slot(result="QString")
+    def current_datetime(self) -> str:
+        """
+        获取当前的时间
+        :return:
+        """
+        return datetime.now().strftime("%Y-%m-%d %H:%M:%S")
+
+
+
+
+
+if __name__ == "__main__":
+    u = Utils()
+    print(u.current_datetime())

+ 37 - 7
module/gui/process/script_process.py

@@ -1,7 +1,7 @@
 # This Python file uses the following encoding: utf-8
 # This Python file uses the following encoding: utf-8
 # @author runhey
 # @author runhey
 # github https://github.com/runhey
 # github https://github.com/runhey
-
+from queue import Queue
 from multiprocessing import Process
 from multiprocessing import Process
 
 
 from module.logger import logger
 from module.logger import logger
@@ -9,18 +9,23 @@ from module.logger import logger
 
 
 class ScriptProcess(Process):
 class ScriptProcess(Process):
 
 
-    def __init__(self, config: str, port: int) -> None:
+    def __init__(self, config: str, port: int, log_queue: Queue, update_queue: Queue) -> None:
         """
         """
 
 
         :param port: 端口 tcp 127.0.0.1:port
         :param port: 端口 tcp 127.0.0.1:port
         :param config: 如oas1
         :param config: 如oas1
+        :param log_queue: 一个输出到gui的Log队列
         """
         """
         super().__init__()
         super().__init__()
         self.config = config
         self.config = config
         self.port = port
         self.port = port
         self.name = config
         self.name = config
+        self.log_queue = log_queue
+        self.update_queue = update_queue
         self.daemon = True  # 设置为守护进程,主进程结束,子进程也结束
         self.daemon = True  # 设置为守护进程,主进程结束,子进程也结束
 
 
+
+
     @property
     @property
     def alive(self) -> bool:
     def alive(self) -> bool:
         """
         """
@@ -34,9 +39,11 @@ class ScriptProcess(Process):
         run
         run
         :return:
         :return:
         """
         """
+        self.start_log()
         try:
         try:
             from script import Script
             from script import Script
             script = Script(config_name=self.config)
             script = Script(config_name=self.config)
+            script.gui_update_task = self.update_tasks
             script.init_server(self.port)
             script.init_server(self.port)
             script.run_server()
             script.run_server()
         except:
         except:
@@ -53,11 +60,34 @@ class ScriptProcess(Process):
         self.join()
         self.join()
         logger.info(f'stop script {self.config}')
         logger.info(f'stop script {self.config}')
 
 
-    def restart(self) -> None:
+    # def restart(self) -> None:
+    #     """
+    #     restart the process
+    #     :return:
+    #     """
+    #     super().restart()
+    #     logger.info(f'restart script {self.config}')
+
+    def start_log(self) -> None:
+        """
+
+        :return:
+        """
+        try:
+            from module.logger import set_file_logger, set_func_logger
+            set_file_logger(name=self.config)
+            set_func_logger(self.log_queue.put)
+        except:
+            logger.exception(f'start log error')
+            raise
+
+
+    def update_tasks(self, data) -> None:
         """
         """
-        restart the process
+        update tasks
         :return:
         :return:
         """
         """
-        self.stop()
-        self.start()
-        logger.info(f'restart script {self.config}')
+        msg = {self.config: data}
+        self.update_queue.put(msg)
+        logger.info(f'Update tasks {self.config}')
+

+ 12 - 1
module/gui/qml/Component/Args.qml

@@ -29,7 +29,7 @@ Item {
             expand: true
             expand: true
             headerText: qsTr(groupTitle) +" "+ qsTr("Setting")
             headerText: qsTr(groupTitle) +" "+ qsTr("Setting")
             width: contentScrollable.width
             width: contentScrollable.width
-            contentHeight: group_column.height
+            contentHeight: group_column.height + 20
             Column{
             Column{
                 id: group_column
                 id: group_column
                 spacing: 4
                 spacing: 4
@@ -123,6 +123,7 @@ Item {
         Item{
         Item{
             id: stringItem
             id: stringItem
             property var modelData: null
             property var modelData: null
+            property bool isDateTime: false
             width: parent.width
             width: parent.width
             implicitHeight: string_title.implicitHeight + string_description.implicitHeight
             implicitHeight: string_title.implicitHeight + string_description.implicitHeight
             Layout.fillHeight: true
             Layout.fillHeight: true
@@ -135,6 +136,12 @@ Item {
                 }
                 }
                 placeholderText: ""
                 placeholderText: ""
                 onEditingFinished: {
                 onEditingFinished: {
+                    if(stringItem.isDateTime){
+                        if(string_text.text === ""){
+                            string_text.text = utils.current_datetime()
+                        }
+                    }
+
                     if(set_task(stringItem.parent.parent.parent.groupName, modelData.name, text)){
                     if(set_task(stringItem.parent.parent.parent.groupName, modelData.name, text)){
                         showSuccess( qsTr("Successful setting"))
                         showSuccess( qsTr("Successful setting"))
                     }
                     }
@@ -173,6 +180,10 @@ Item {
                 }
                 }
                 string_text.text = modelData.value
                 string_text.text = modelData.value
                 string_text.placeholderText = modelData["default"]
                 string_text.placeholderText = modelData["default"]
+                if(string_text.placeholderText.startsWith("2023-01-01")){
+                    //判断是不是时间类型的变量2023-01-01
+                    stringItem.isDateTime = true
+                }
                 string_title.text = modelData.title
                 string_title.text = modelData.title
                 if( typeof modelData.description === 'undefined'){
                 if( typeof modelData.description === 'undefined'){
                     return
                     return

+ 21 - 14
module/gui/qml/Component/OverStatus.qml

@@ -8,6 +8,10 @@ Item{
 
 
 //    width: 200
 //    width: 200
     height: 40
     height: 40
+
+    id: root
+    property int runStatus: MainEvent.RunStatus.Init
+
     RowLayout{
     RowLayout{
         anchors.fill: parent
         anchors.fill: parent
         spacing: 0
         spacing: 0
@@ -21,24 +25,27 @@ Item{
             id: runStatusIcon
             id: runStatusIcon
             Layout.alignment: Qt.AlignVCenter
             Layout.alignment: Qt.AlignVCenter
             Layout.leftMargin: 20
             Layout.leftMargin: 20
-            runStatus: MainEvent.runStatus
+            runStatus: root.runStatus
         }
         }
         FluText{
         FluText{
             id:runStatusText
             id:runStatusText
-            property int runStatus: MainEvent.runStatus
             Layout.alignment: Qt.AlignVCenter
             Layout.alignment: Qt.AlignVCenter
-            text: ""
-            onRunStatusChanged: {
-                if(runStatus === MainEvent.RunStatus.Empty){
-                    text= ""
-                }else if(runStatus === MainEvent.RunStatus.Free){
-                    text= "闲置"
-                }else if(runStatus === MainEvent.RunStatus.Run){
-                    text= "运行中"
-                }else if(runStatus === MainEvent.RunStatus.Error){
-                    text= "发生错误"
-                }
-            }
+            text: "初始化"
+
+        }
+    }
+
+    onRunStatusChanged: {
+        if(root.runStatus === MainEvent.RunStatus.Empty){
+            runStatusText.text= ""
+        }else if(root.runStatus === MainEvent.RunStatus.Free){
+            runStatusText.text= "闲置"
+        }else if(root.runStatus === MainEvent.RunStatus.Run){
+            runStatusText.text= "运行中"
+        }else if(root.runStatus === MainEvent.RunStatus.Error){
+            runStatusText.text= "发生错误"
+        }else if(root.runStatus === MainEvent.RunStatus.Init){
+            runStatusText.text= "初始化"
         }
         }
     }
     }
 }
 }

+ 261 - 30
module/gui/qml/Component/Overview.qml

@@ -1,9 +1,23 @@
 import QtQuick
 import QtQuick
+import QtQuick.Controls
 import QtQuick.Layouts
 import QtQuick.Layouts
 import FluentUI
 import FluentUI
+import "../Global"
 
 
 Item {
 Item {
+    id: root
+    property string configName: ""
+    property var splitPanel: null  // 传入一个主控制的引用
 
 
+    Timer{
+        id: startInit
+        interval: 2500 // 定时器间隔为一秒
+        repeat: false // 设置为一次性定时器
+        onTriggered: {
+            // 停止定时器
+            setStatus(MainEvent.RunStatus.Free)
+        }
+    }
 
 
 
 
     Item{
     Item{
@@ -27,16 +41,32 @@ Item {
                     font: FluTextStyle.Subtitle
                     font: FluTextStyle.Subtitle
                     Layout.alignment: Qt.AlignVCenter | Qt.AlignLeft
                     Layout.alignment: Qt.AlignVCenter | Qt.AlignLeft
                 }
                 }
+                FluIconButton{
+                     Layout.alignment: Qt.AlignVCenter | Qt.AlignRight
+                    text: "Restart"
+                    iconSource: FluentIcons.RepeatAll
+                    onClicked: {
+                        showSuccess("Restart"+" "+configName)
+                        process_manager.restart(configName)
+                        startStart.selected = true
+                        textLog.text = ""
+                    }
+                }
                 FluToggleButton{
                 FluToggleButton{
+                    id: startStart
                     Layout.alignment: Qt.AlignVCenter | Qt.AlignRight
                     Layout.alignment: Qt.AlignVCenter | Qt.AlignRight
                     Layout.rightMargin: 16
                     Layout.rightMargin: 16
                     text:"Start"
                     text:"Start"
+                    selected: true
                     onClicked: {
                     onClicked: {
                         selected = !selected
                         selected = !selected
                         if(selected){
                         if(selected){
-                            text = "Start"
+                            text = "Start"                          
+                            process_manager.stop_script(root.configName)
                         }else{
                         }else{
+                            // 如果按键颜色变灰色
                             text = "Stop"
                             text = "Stop"
+                            process_manager.start_script(root.configName)
                         }
                         }
                     }
                     }
                 }
                 }
@@ -47,7 +77,7 @@ Item {
             anchors.top: schedulerOpen.bottom
             anchors.top: schedulerOpen.bottom
             anchors.topMargin: 10
             anchors.topMargin: 10
             width: parent.width
             width: parent.width
-            height: 120
+            height: 100
             ColumnLayout{
             ColumnLayout{
                 width: parent.width
                 width: parent.width
                 spacing: 8
                 spacing: 8
@@ -65,7 +95,12 @@ Item {
                     radius: 2
                     radius: 2
                 }
                 }
                 Taskmini{
                 Taskmini{
+                    id: task_running
+                    visible: false
                     Layout.leftMargin: 16
                     Layout.leftMargin: 16
+                    onClick: {
+                        root.splitPanel.title = task_running.name
+                    }
                 }
                 }
             }
             }
         }
         }
@@ -75,35 +110,93 @@ Item {
             anchors.topMargin: 10
             anchors.topMargin: 10
             width: parent.width
             width: parent.width
             height: 240
             height: 240
-            ColumnLayout{
-                width: parent.width
-                spacing: 8
-                FluText{
-                    text: 'Pending'
-                    Layout.leftMargin: 16
-                    Layout.topMargin: 6
-                    font: FluTextStyle.Subtitle
-                }
-                Rectangle{
-                    width: schedulerRunning.width - 20
-                    height: 2
-                    Layout.alignment: Qt.AlignHCenter
-                    color: FluTheme.dark ? Qt.rgba(64/255, 68/255, 75/255, 1) : Qt.rgba(234/255, 236/255, 239/255, 1)
-                    radius: 2
+            FluText{
+                id: pendingText
+                anchors{
+                    top: parent.top
+                    topMargin: 6
+
                 }
                 }
-                Taskmini{
-                    Layout.leftMargin: 16
+                width: parent.width
+                text: 'Pending'
+                leftPadding: 16
+                font: FluTextStyle.Subtitle
+            }
+            Rectangle{
+                // 这个是一条横线
+                id: linePending
+                anchors{
+                    top: pendingText.bottom
+                    topMargin: 8
+                    horizontalCenter: parent.horizontalCenter
                 }
                 }
-                Taskmini{
-                    Layout.leftMargin: 16
+                width: schedulerRunning.width - 20
+                height: 2
+                color: FluTheme.dark ? Qt.rgba(64/255, 68/255, 75/255, 1) : Qt.rgba(234/255, 236/255, 239/255, 1)
+                radius: 2
+            }
+            ListView{
+                id: pendingListView
+                anchors{
+                    top: linePending.bottom
+                    topMargin: 8
+                    bottom: parent.bottom
+                    bottomMargin: 8
+                    horizontalCenter: parent.horizontalCenter
                 }
                 }
-                Taskmini{
-                    Layout.leftMargin: 16
+
+                width: 225
+                height: 200
+                clip: true
+                spacing: 8
+                model: ListModel{
+                    id: pendingListModel
                 }
                 }
-                Taskmini{
-                    Layout.leftMargin: 16
+                delegate: Component{
+                    Taskmini{
+                        name: model.name
+                        nextRun: model.next_run
+                        onClick: {
+                            root.splitPanel.title = model.name
+                        }
+                    }
                 }
                 }
             }
             }
+
+//            ColumnLayout{
+//                width: parent.width
+//                spacing: 8
+//                FluText{
+//                    text: 'Pending'
+//                    Layout.leftMargin: 16
+//                    Layout.topMargin: 6
+//                    font: FluTextStyle.Subtitle
+//                }
+//                Rectangle{
+//                    // 这个是一条横线
+//                    width: schedulerRunning.width - 20
+//                    height: 2
+//                    Layout.alignment: Qt.AlignHCenter
+//                    color: FluTheme.dark ? Qt.rgba(64/255, 68/255, 75/255, 1) : Qt.rgba(234/255, 236/255, 239/255, 1)
+//                    radius: 2
+//                }
+//                ListView{
+//                    id: pendingListView
+//                    Layout.alignment: Qt.AlignHCenter
+//                    width: 225
+//                    height: 200
+//                    spacing: 8
+//                    model: ListModel{
+//                        id: pendingListModel
+//                    }
+//                    delegate: Component{
+//                        Taskmini{
+//                            name: model.name
+//                            nextRun: model.next_run
+//                        }
+//                    }
+//                }
+//            }
         }
         }
         FluArea{
         FluArea{
             id: schedulerWaiting
             id: schedulerWaiting
@@ -111,7 +204,8 @@ Item {
             anchors.topMargin: 10
             anchors.topMargin: 10
             anchors.bottom: parent.bottom
             anchors.bottom: parent.bottom
             anchors.bottomMargin: 0
             anchors.bottomMargin: 0
-            width: parent.width
+            width: parent.width                  
+
             ColumnLayout{
             ColumnLayout{
                 width: parent.width
                 width: parent.width
                 spacing: 8
                 spacing: 8
@@ -130,17 +224,154 @@ Item {
                     color: FluTheme.dark ? Qt.rgba(64/255, 68/255, 75/255, 1) : Qt.rgba(234/255, 236/255, 239/255, 1)
                     color: FluTheme.dark ? Qt.rgba(64/255, 68/255, 75/255, 1) : Qt.rgba(234/255, 236/255, 239/255, 1)
                     radius: 2
                     radius: 2
                 }
                 }
-                Taskmini{
-                    Layout.leftMargin: 16
-                    Layout.fillHeight: false
+                ListView{
+                    id: waitingListView
+                    Layout.fillHeight: true
+                    Layout.alignment: Qt.AlignHCenter
+                    width: 225
+                    clip: true
+                    spacing: 8
+                    model: ListModel{
+                        id: waitingListModel
+                    }
+                    delegate: Component{
+                        Taskmini{
+                            name: model.name
+                            nextRun: model.next_run
+                            onClick: {
+                                root.splitPanel.title = model.name
+                            }
+                        }
+                    }
                 }
                 }
             }
             }
         }
         }
     }
     }
+
     FluArea{
     FluArea{
+        id: logHeader
+        anchors.top: parent.top
         anchors.left: leftScheduler.right
         anchors.left: leftScheduler.right
         anchors.leftMargin: 10
         anchors.leftMargin: 10
-        height: parent.height
         anchors.right: parent.right
         anchors.right: parent.right
+        height: 50
+        RowLayout{
+            anchors.fill: parent
+            RowLayout.alignment: Qt.AlignRight | Qt.AlignVCenter
+            FluText{
+                text: 'Log'
+                Layout.leftMargin: 16
+                font: FluTextStyle.Subtitle
+                Layout.alignment: Qt.AlignVCenter | Qt.AlignLeft
+            }
+            OverStatus{
+                id: overStatus
+                Layout.alignment: Qt.AlignVCenter | Qt.AlignRight
+            }
+            FluToggleButton{
+                Layout.alignment: Qt.AlignVCenter | Qt.AlignRight
+                Layout.rightMargin: 16
+                text:"Auto Scroll On"
+                selected: true
+                onClicked: {
+                    selected = !selected
+                    if(selected){
+                        text = "Auto Scroll On"
+                    }else{
+                        text = "Auto Scroll Off"
+                    }
+                }
+            }
+        }
+    }
+
+    FluArea{
+        anchors.top: logHeader.bottom
+        anchors.topMargin: 10
+        anchors.bottom: parent.bottom
+        anchors.left: leftScheduler.right
+        anchors.leftMargin: 10
+        anchors.right: parent.right
+        FluScrollablePage{
+            anchors.fill: parent
+        FluText{
+            id: textLog
+            width: parent.width
+            padding: 10
+            clip: true
+            wrapMode: Text.WordWrap // 设置自动换行模式
+            textFormat: Text.RichText
+            text: ''
+
+            function add_log(config, log){
+                if(config !== root.configName){
+                    return
+                }
+                textLog.text += log
+            }
+
+            Component.onCompleted:{
+                process_manager.log_signal.connect(textLog.add_log)
+            }
+
+
+        }}
+    }
+
+    Component.onCompleted:{
+        process_manager.sig_update_task.connect(update_task)
+        process_manager.sig_update_pending.connect(update_pending)
+        process_manager.sig_update_waiting.connect(update_waiting)
+        startInit.start()
+    }
+    function update_task(config, data){
+        if(typeof data !== "string"){
+            console.error("Pass an incorrect type")
+            return
+        }
+
+        if(config !== configName){
+            return
+        }
+        task_running.setData(data)
+    }
+    function update_pending(config, data){
+        if(typeof data !== "string"){
+            console.error("Pass an incorrect type")
+            return
+        }
+        if(config !== configName){
+            return
+        }
+        if(data === "[]"){
+            pendingListModel.clear()
+            return
+        }
+        pendingListModel.clear()
+        const d = JSON.parse(data)
+        for(var item of d){
+            pendingListModel.append(item)
+        }
+    }
+    function update_waiting(config, data){
+        if(typeof data !== "string"){
+            console.error("Pass an incorrect type")
+            return
+        }
+        if(config !== configName){
+            return
+        }
+        if(data === "[]"){
+            waitingListModel.clear()
+            return
+        }
+        waitingListModel.clear()
+        const d = JSON.parse(data)
+        for(var item of d){
+            waitingListModel.append(item)
+        }
+    }
+    function setStatus(s){
+        overStatus.runStatus = s
     }
     }
 }
 }

+ 1 - 1
module/gui/qml/Component/RuleFile.qml

@@ -181,7 +181,7 @@ FluArea {
                     }
                     }
                     placeholderText:"item name"
                     placeholderText:"item name"
                     text: model.itemName
                     text: model.itemName
-                    validator: RegularExpressionValidator { regularExpression: /^[a-zA-Z0-9]*$/ }
+                    validator: RegularExpressionValidator { regularExpression: /^[a-z0-9_]*$/ }
                     onActiveFocusChanged: {
                     onActiveFocusChanged: {
                         if(activeFocus){
                         if(activeFocus){
                             currentItem = listModel.get(index)
                             currentItem = listModel.get(index)

+ 4 - 0
module/gui/qml/Component/RunStatusIcon.qml

@@ -60,6 +60,10 @@ Item {
             runError.visible = true
             runError.visible = true
             runProgress.visible = false
             runProgress.visible = false
             runProgress.progress = 0
             runProgress.progress = 0
+        }else if(runStatus === MainEvent.RunStatus.Init){
+            runError.visible = false
+            runProgress.visible = true
+            runProgress.progress = 0.25
         }
         }
     }
     }
 
 

+ 16 - 1
module/gui/qml/Component/SplitPanel.qml

@@ -35,6 +35,15 @@ Item {
         anchors.top: parent.top
         anchors.top: parent.top
         anchors.bottom: parent.bottom
         anchors.bottom: parent.bottom
         anchors.bottomMargin: 12
         anchors.bottomMargin: 12
+
+        onLoaded: {
+            if(typeof contentDefalut.item.splitPanel === "undefined"){
+                console.debug('还没有属性')
+                return
+            }
+
+            contentDefalut.item.splitPanel = menuArea.parent
+        }
     }
     }
     Loader{
     Loader{
         id: contentLoader
         id: contentLoader
@@ -83,8 +92,9 @@ Item {
 
 
     //设置固定的部分的具体内容  主要是传一个组件
     //设置固定的部分的具体内容  主要是传一个组件
     function setDefalut(component){
     function setDefalut(component){
-        contentDefalut.sourceComponent = component
+        contentDefalut.sourceComponent = component 
         showDefalut()
         showDefalut()
+
     }
     }
     //
     //
     function setLoader(component){
     function setLoader(component){
@@ -113,5 +123,10 @@ Item {
         contentLoader.item.taskName = taskName
         contentLoader.item.taskName = taskName
     }
     }
 
 
+    //设置配置的名称
+    function setDefalutConfig(name){
+        contentDefalut.item.configName = name
+    }
+
 
 
 }
 }

+ 20 - 1
module/gui/qml/Component/Taskmini.qml

@@ -5,8 +5,15 @@ import FluentUI
 // 任务的名称 + 时间 以及一个设置的入口
 // 任务的名称 + 时间 以及一个设置的入口
 
 
 Item {
 Item {
+    id: root
     width: 225
     width: 225
     height: 40
     height: 40
+    visible: true
+
+    property alias name: taskName.text
+    property alias nextRun: taskTime.text
+    signal click(string title)
+
     FluText{
     FluText{
         id: taskName
         id: taskName
         anchors{
         anchors{
@@ -38,7 +45,19 @@ Item {
         }
         }
         text:"setting"
         text:"setting"
         onClicked: {
         onClicked: {
-             showSuccess("setting")
+            showSuccess(name)
+            root.click(configName)
+        }
+    }
+    // 使用这个的前提是 data 是字符串
+    function  setData(data){
+        if(data === "{}"){  // 这个表示没有数据,是空的
+            root.visible = false
+            return
         }
         }
+        root.visible = true
+        const d = JSON.parse(data)
+        task_running.name = d["name"]
+        task_running.nextRun = d["next_run"]
     }
     }
 }
 }

+ 3 - 2
module/gui/qml/Global/MainEvent.qml

@@ -11,7 +11,8 @@ QtObject {
         Error,
         Error,
         Run,
         Run,
         Free, //空闲
         Free, //空闲
-        Empty //不显示
+        Empty, //不显示
+        Init  //初始化
     }
     }
 
 
     // 界面的自定义设置
     // 界面的自定义设置
@@ -27,7 +28,7 @@ QtObject {
     property int runStatus: MainEvent.RunStatus.Empty
     property int runStatus: MainEvent.RunStatus.Empty
     property string menuTitle: ""
     property string menuTitle: ""
     property bool addOpen: false
     property bool addOpen: false
-    property string scriptName: ""
+    property string scriptName: ""  // 是设置脚本的名字
 
 
     //切换语言中文是"zh_CN" 英文是"en_US"
     //切换语言中文是"zh_CN" 英文是"en_US"
     function switchLocale(locale) {
     function switchLocale(locale) {

+ 8 - 8
module/gui/qml/MainWindow.qml

@@ -23,12 +23,12 @@ FluWindow {
        z:9
        z:9
        width: parent.width
        width: parent.width
     }
     }
-    OverStatus{
-        anchors{
-            top: parent.top
-            horizontalCenter: parent.horizontalCenter
-        }
-    }
+//    OverStatus{
+//        anchors{
+//            top: parent.top
+//            horizontalCenter: parent.horizontalCenter
+//        }
+//    }
 
 
 
 
 // 任务栏的右边边系统图标
 // 任务栏的右边边系统图标
@@ -65,7 +65,7 @@ FluWindow {
         }
         }
         onUpdateScriptItems: {
         onUpdateScriptItems: {
             nav_view.items.addFluPaneItems()
             nav_view.items.addFluPaneItems()
-            process_manager.create_all()
+//            process_manager.create_all()
         }
         }
     }
     }
 
 
@@ -86,7 +86,7 @@ FluWindow {
         }
         }
     }
     }
     Component.onCompleted:{
     Component.onCompleted:{
-        process_manager.create_all()
+//        process_manager.create_all()
     }
     }
 
 
 }
 }

+ 20 - 6
module/gui/qml/Page/ScriptView.qml

@@ -5,8 +5,20 @@ import "../Component"
 import "../Global"
 import "../Global"
 
 
 SplitPanel{
 SplitPanel{
+    id: root
 
 
-    property string configName: ""
+    property string configName: ""  //这个东西会在Nav内部赋值
+
+    Timer{
+        id: startPython
+        interval: 400 // 定时器间隔为一秒
+        repeat: false // 设置为一次性定时器
+        onTriggered: {
+            // 停止定时器
+            process_manager.add(root.configName)
+            startPython.stop()
+        }
+    }
 
 
     onTitleChanged: {
     onTitleChanged: {
         // 如果是总览
         // 如果是总览
@@ -74,21 +86,23 @@ SplitPanel{
             console.info('configname is emtry')
             console.info('configname is emtry')
             return
             return
         }
         }
-        console.debug(process_manager.gui_menu)
+
+        //创建左边的菜单
         const data = JSON.parse(process_manager.gui_menu())
         const data = JSON.parse(process_manager.gui_menu())
         create(data)
         create(data)
+
+        // 点击的时候顺带创建 python 进程
+        setDefalutConfig(configName)
+        startPython.start()
     }
     }
 
 
 
 
     Component.onCompleted:{
     Component.onCompleted:{
 
 
-
-//        var data = {'Overview':[], 'Script': ['Script', 'General', 'Restart']}
-
-
         const component = Qt.createComponent("../../qml/Component/Overview.qml")
         const component = Qt.createComponent("../../qml/Component/Overview.qml")
         if (component.status === Component.Ready) {
         if (component.status === Component.Ready) {
             setDefalut(component)
             setDefalut(component)
+
         } else {
         } else {
             // 组件加载失败
             // 组件加载失败
             console.debug('组件!加载失败')
             console.debug('组件!加载失败')

+ 40 - 0
module/handler/sensitive_info.py

@@ -0,0 +1,40 @@
+import re
+
+# from module.base.mask import Mask
+# from module.ui.page import *
+#
+# MASK_MAIN = Mask('./assets/mask/MASK_MAIN.png')
+# MASK_PLAYER = Mask('./assets/mask/MASK_PLAYER.png')
+
+
+def handle_sensitive_image(image):
+    """
+    Args:
+        image:
+
+    Returns:
+        np.ndarray:
+    """
+    # if PLAYER_CHECK.match(image, offset=(30, 30)):
+    #     image = MASK_PLAYER.apply(image)
+    # if MAIN_CHECK.match(image, offset=(30, 30)):
+    #     image = MASK_MAIN.apply(image)
+
+    return image
+
+
+def handle_sensitive_text(text):
+    """
+    Args:
+        text (str):
+
+    Returns:
+        str:
+    """
+    text = re.sub('File \"(.*?)AzurLaneAutoScript', 'File \"C:\\\\fakepath\\\\AzurLaneAutoScript', text)
+    text = re.sub('\[Adb_binary\] (.*?)AzurLaneAutoScript', '[Adb_binary] C:\\\\fakepath\\\\AzurLaneAutoScript', text)
+    return text
+
+
+def handle_sensitive_logs(logs):
+    return [handle_sensitive_text(line) for line in logs]

+ 70 - 24
module/logger.py

@@ -5,11 +5,15 @@ import datetime
 import logging
 import logging
 import os
 import os
 import sys
 import sys
+import traceback
+
+from io import TextIOBase
 from typing import Callable, List
 from typing import Callable, List
 
 
 from rich.console import Console, ConsoleOptions, ConsoleRenderable, NewLine
 from rich.console import Console, ConsoleOptions, ConsoleRenderable, NewLine
 from rich.highlighter import RegexHighlighter, NullHighlighter
 from rich.highlighter import RegexHighlighter, NullHighlighter
 from rich.logging import RichHandler
 from rich.logging import RichHandler
+from rich.text import Text
 from rich.rule import Rule
 from rich.rule import Rule
 from rich.style import Style
 from rich.style import Style
 from rich.theme import Theme
 from rich.theme import Theme
@@ -33,10 +37,25 @@ class RichFileHandler(RichHandler):
     # Rename
     # Rename
     pass
     pass
 
 
+class LogStream(TextIOBase):
+    def __init__(self, *args, func: Callable[[ConsoleRenderable], None] = None, **kwargs):
+        super().__init__(*args, **kwargs)
+        self._func = func
+
+    def write(self, msg: str) -> int:
+        if isinstance(msg, bytes):
+            msg = msg.decode("utf-8")
+        self._func(msg)
+        return len(msg)
+    
+class RichStreamHandler(RichHandler):
+    pass
+
 
 
 class RichRenderableHandler(RichHandler):
 class RichRenderableHandler(RichHandler):
     """
     """
     Pass renderable into a function
     Pass renderable into a function
+    主要是传入一个回调函数
     """
     """
 
 
     def __init__(self, *args, func: Callable[[ConsoleRenderable], None] = None, **kwargs):
     def __init__(self, *args, func: Callable[[ConsoleRenderable], None] = None, **kwargs):
@@ -45,16 +64,18 @@ class RichRenderableHandler(RichHandler):
 
 
     def emit(self, record: logging.LogRecord) -> None:
     def emit(self, record: logging.LogRecord) -> None:
         message = self.format(record)
         message = self.format(record)
-        traceback = None
+        tb = None
         if (
         if (
             self.rich_tracebacks
             self.rich_tracebacks
             and record.exc_info
             and record.exc_info
             and record.exc_info != (None, None, None)
             and record.exc_info != (None, None, None)
         ):
         ):
             exc_type, exc_value, exc_traceback = record.exc_info
             exc_type, exc_value, exc_traceback = record.exc_info
+            traceback.print_tb(exc_traceback)
+            self._func(exc_traceback)
             assert exc_type is not None
             assert exc_type is not None
             assert exc_value is not None
             assert exc_value is not None
-            traceback = Traceback.from_exception(
+            tb = Traceback.from_exception(
                 exc_type,
                 exc_type,
                 exc_value,
                 exc_value,
                 exc_traceback,
                 exc_traceback,
@@ -66,6 +87,7 @@ class RichRenderableHandler(RichHandler):
                 locals_max_length=self.locals_max_length,
                 locals_max_length=self.locals_max_length,
                 locals_max_string=self.locals_max_string,
                 locals_max_string=self.locals_max_string,
             )
             )
+            # 这个好理解转化为特定格式, getMessage()返回寸str
             message = record.getMessage()
             message = record.getMessage()
             if self.formatter:
             if self.formatter:
                 record.message = record.getMessage()
                 record.message = record.getMessage()
@@ -75,13 +97,18 @@ class RichRenderableHandler(RichHandler):
                         record, formatter.datefmt)
                         record, formatter.datefmt)
                 message = formatter.formatMessage(record)
                 message = formatter.formatMessage(record)
 
 
+        # 这个message_renderable是一个Text对象
         message_renderable = self.render_message(record, message)
         message_renderable = self.render_message(record, message)
-        log_renderable = self.render(
-            record=record, traceback=traceback, message_renderable=message_renderable
+        log_renderable: ConsoleRenderable = self.render(
+            record=record, traceback=tb, message_renderable=message_renderable
         )
         )
 
 
+        # msg2 = Text.from_markup(message).markup
+
+        # 这个message_renderable是一个Text对象
+        # traceback是表示异常的对象
         # Directly put renderable into function
         # Directly put renderable into function
-        self._func(log_renderable)
+        self._func(message_renderable)
 
 
     def handle(self, record: logging.LogRecord) -> bool:
     def handle(self, record: logging.LogRecord) -> bool:
         if not self._func:
         if not self._func:
@@ -135,9 +162,32 @@ WEB_THEME = Theme({
 })
 })
 
 
 
 
+
+
+def show_handlers(handlers):
+    # 获取并打印日志记录器中处理器的信息
+    for handler in logger.handlers:
+        # 获取处理器的类名
+        handler_class = handler.__class__.__name__
+        print(f"Handler class: {handler_class}")
+
+        # 获取处理器的级别
+        handler_level = logging.getLevelName(handler.level)
+        print(f"Handler level: {handler_level}")
+
+        # 获取处理器的格式化器
+        formatter = handler.formatter
+        if formatter is not None:
+            formatter_class = formatter.__class__.__name__
+            print(f"Formatter class: {formatter_class}")
+
+        # 其他处理器的属性和方法,根据需要进行获取和打印
+
+        print()  # 打印空行,用于分隔处理器的信息
+
 # Logger init
 # Logger init
 logger_debug = False
 logger_debug = False
-logger = logging.getLogger('alas')
+logger = logging.getLogger('oas')
 logger.setLevel(logging.DEBUG if logger_debug else logging.INFO)
 logger.setLevel(logging.DEBUG if logger_debug else logging.INFO)
 file_formatter = logging.Formatter(
 file_formatter = logging.Formatter(
     fmt='%(asctime)s.%(msecs)03d | %(levelname)s | %(message)s', datefmt='%Y-%m-%d %H:%M:%S')
     fmt='%(asctime)s.%(msecs)03d | %(levelname)s | %(message)s', datefmt='%Y-%m-%d %H:%M:%S')
@@ -170,7 +220,7 @@ os.chdir(os.path.join(os.path.dirname(__file__), '../'))
 # Add file logger
 # Add file logger
 pyw_name = os.path.splitext(os.path.basename(sys.argv[0]))[0]
 pyw_name = os.path.splitext(os.path.basename(sys.argv[0]))[0]
 
 
-
+# 这个函数貌似没有用到
 def _set_file_logger(name=pyw_name):
 def _set_file_logger(name=pyw_name):
     if '_' in name:
     if '_' in name:
         name = name.split('_', 1)[0]
         name = name.split('_', 1)[0]
@@ -222,32 +272,27 @@ def set_file_logger(name=pyw_name):
     logger.addHandler(hdlr)
     logger.addHandler(hdlr)
     logger.log_file = log_file
     logger.log_file = log_file
 
 
-
+# 给web设置
 def set_func_logger(func):
 def set_func_logger(func):
-    console = HTMLConsole(
-        force_terminal=False,
-        force_interactive=False,
-        width=80,
-        color_system='truecolor',
-        markup=False,
-        safe_box=False,
-        highlighter=Highlighter(),
-        theme=WEB_THEME
+
+    stream = LogStream(func=func)
+    file_console = Console(
+        file=stream,
+        no_color=True,
+        highlight=False,
+        width=160,
     )
     )
-    hdlr = RichRenderableHandler(
-        func=func,
-        console=console,
+    hdlr = RichStreamHandler(
+        console=file_console,
         show_path=False,
         show_path=False,
         show_time=False,
         show_time=False,
         show_level=True,
         show_level=True,
         rich_tracebacks=True,
         rich_tracebacks=True,
         tracebacks_show_locals=True,
         tracebacks_show_locals=True,
-        tracebacks_extra_lines=2,
-        highlighter=Highlighter(),
+        tracebacks_extra_lines=3,
+        highlighter=NullHighlighter(),
     )
     )
     hdlr.setFormatter(web_formatter)
     hdlr.setFormatter(web_formatter)
-    logger.handlers = [h for h in logger.handlers if not isinstance(
-        h, RichRenderableHandler)]
     logger.addHandler(hdlr)
     logger.addHandler(hdlr)
 
 
 
 
@@ -358,3 +403,4 @@ logger.log_file: str
 
 
 logger.set_file_logger()
 logger.set_file_logger()
 logger.hr('Start', level=0)
 logger.hr('Start', level=0)
+

+ 3 - 1
requirements-in.txt

@@ -11,4 +11,6 @@ anytree==2.8.0
 pywin32==306
 pywin32==306
 zerorpc==0.6.3
 zerorpc==0.6.3
 wrapt==1.15.0
 wrapt==1.15.0
-pydantic==1.10.7
+pydantic==1.10.7
+inflection==0.5.1
+tqdm==4.65.0

+ 1 - 0
requirements.txt

@@ -24,6 +24,7 @@ future==0.18.3            # via zerorpc
 gevent==22.10.2           # via zerorpc
 gevent==22.10.2           # via zerorpc
 greenlet==2.0.2           # via gevent
 greenlet==2.0.2           # via gevent
 idna==3.4                 # via requests
 idna==3.4                 # via requests
+inflection==0.5.1         # via -r requirements-in.txt
 logzero==1.7.0            # via uiautomator2
 logzero==1.7.0            # via uiautomator2
 lxml==4.9.2               # via uiautomator2
 lxml==4.9.2               # via uiautomator2
 markdown-it-py==2.2.0     # via rich
 markdown-it-py==2.2.0     # via rich

+ 317 - 4
script.py

@@ -5,22 +5,43 @@ import zerorpc
 import zmq
 import zmq
 import msgpack
 import msgpack
 import random
 import random
+import re
 import cv2
 import cv2
+import time
+import os
+import inflection
+import asyncio
+
+from typing import Callable
+from datetime import datetime, timedelta
+from pathlib import Path
 from cached_property import cached_property
 from cached_property import cached_property
 from pydantic import BaseModel, ValidationError
 from pydantic import BaseModel, ValidationError
 from PySide6.QtGui import QImage
 from PySide6.QtGui import QImage
+from threading import Thread
 
 
 
 
 from module.config.utils import convert_to_underscore
 from module.config.utils import convert_to_underscore
+from module.config.config import Config
+from module.device.device import Device
+from module.base.utils import load_module
+from module.base.decorator import del_cached_property
 from module.logger import logger
 from module.logger import logger
 from module.exception import *
 from module.exception import *
 
 
 class Script:
 class Script:
     def __init__(self, config_name: str ='oas') -> None:
     def __init__(self, config_name: str ='oas') -> None:
+        logger.hr('Start', level=0)
         self.server = None
         self.server = None
+        self.gui_update_task: Callable = None  # 回调函数, gui进程注册当每次config更新任务的时候更新gui的信息
         self.config_name = config_name
         self.config_name = config_name
-
-
+        # Skip first restart
+        self.is_first_task = True
+        # Failure count of tasks
+        # Key: str, task name, value: int, failure count
+        self.failure_record = {}
+        # 运行loop的线程
+        self.loop_thread: Thread = None
 
 
     @cached_property
     @cached_property
     def config(self) -> "Config":
     def config(self) -> "Config":
@@ -48,6 +69,46 @@ class Script:
             logger.exception(e)
             logger.exception(e)
             exit(1)
             exit(1)
 
 
+
+
+    @cached_property
+    def checker(self):
+        """
+        占位函数,在alas中是检查服务器是否正常的
+        :return:
+        """
+        return None
+
+    def save_error_log(self):
+        """
+        Save last 60 screenshots in ./log/error/<timestamp>
+        Save logs to ./log/error/<timestamp>/log.txt
+        """
+        from module.base.utils import save_image
+        from module.handler.sensitive_info import (handle_sensitive_image,
+                                                   handle_sensitive_logs)
+        if self.config.Error_SaveError:
+            if not os.path.exists('./log/error'):
+                os.mkdir('./log/error')
+            folder = f'./log/error/{int(time.time() * 1000)}'
+            logger.warning(f'Saving error: {folder}')
+            os.mkdir(folder)
+            for data in self.device.screenshot_deque:
+                image_time = datetime.strftime(data['time'], '%Y-%m-%d_%H-%M-%S-%f')
+                image = handle_sensitive_image(data['image'])
+                save_image(image, f'{folder}/{image_time}.png')
+            with open(logger.log_file, 'r', encoding='utf-8') as f:
+                lines = f.readlines()
+                start = 0
+                for index, line in enumerate(lines):
+                    line = line.strip(' \r\t\n')
+                    if re.match('^═{15,}$', line):
+                        start = index
+                lines = lines[start - 2:]
+                lines = handle_sensitive_logs(lines)
+            with open(f'{folder}/log.txt', 'w', encoding='utf-8') as f:
+                f.writelines(lines)
+
     def init_server(self, port: int) -> int:
     def init_server(self, port: int) -> int:
         """
         """
         初始化zerorpc服务,返回端口号
         初始化zerorpc服务,返回端口号
@@ -61,7 +122,6 @@ class Script:
             logger.error(f"Ocr server cannot bind on port {port}")
             logger.error(f"Ocr server cannot bind on port {port}")
             return None
             return None
 
 
-
     def run_server(self) -> None:
     def run_server(self) -> None:
         """
         """
         启动zerorpc服务
         启动zerorpc服务
@@ -125,10 +185,263 @@ class Script:
         :return: cv2的对象将 numpy 数组转换为字节串。接下来MsgPack 进行序列化发送方将图像数据转换为字节串
         :return: cv2的对象将 numpy 数组转换为字节串。接下来MsgPack 进行序列化发送方将图像数据转换为字节串
         """
         """
         # return msgpack.packb(cv2.imencode('.jpg', self.device.screenshot())[1].tobytes())
         # return msgpack.packb(cv2.imencode('.jpg', self.device.screenshot())[1].tobytes())
-        ret, buffer = cv2.imencode('.jpg', self.device.screenshot())
+        img = cv2.cvtColor(self.device.screenshot(), cv2.COLOR_RGB2BGR)
+        ret, buffer = cv2.imencode('.jpg', img)
         yield buffer.tobytes()
         yield buffer.tobytes()
 
 
+    def _gui_update_tasks(self) -> None:
+        """
+        获取更新任务后 pending waiting 的任务 和 当前的任务的数据。打包给gui显示
+        :return:
+        """
+        data = {}
+        pending = []
+        waiting = []
+        task = {}
+        if self.config.task is not None and self.config.task.next_run < datetime.now():
+            task["name"] = self.config.task.command
+            task["next_run"] = str(self.config.task.next_run)
+        data["task"] = task
+
+        for p in self.config.pending_task:
+            item = {"name": p.command, "next_run": str(p.next_run)}
+            pending.append(item)
+
+        for w in self.config.waiting_task:
+            item = {"name": w.command, "next_run": str(w.next_run)}
+            waiting.append(item)
+
+
+        data["pending"] = pending
+        data["waiting"] = waiting
+
+        if self.gui_update_task is not None:
+            self.gui_update_task(data)
+
+    def _gui_set_status(self, status: str) -> None:
+        """
+        设置给gui显示的状态
+        :param status: 可以在gui中显示的状态 有 "Init", "Empty"(不显示), "Run"(运行中), "Error", "Free"(空闲)
+        :return:
+        """
+        data = {"status": status}
+        if self.gui_update_task is not None:
+            self.gui_update_task(data)
+
+    def wait_until(self, future):
+        """
+        Wait until a specific time.
+
+        Args:
+            future (datetime):
+
+        Returns:
+            bool: True if wait finished, False if config changed.
+        """
+        future = future + timedelta(seconds=1)
+        self.config.start_watching()
+        while 1:
+            if datetime.now() > future:
+                return True
+            # if self.stop_event is not None:
+            #     if self.stop_event.is_set():
+            #         logger.info("Update event detected")
+            #         logger.info(f"[{self.config_name}] exited. Reason: Update")
+            #         exit(0)
+
+            time.sleep(5)
+
+            if self.config.should_reload():
+                return False
+
+    def get_next_task(self) -> str:
+        """
+        获取下一个任务的名字, 大驼峰。
+        :return:
+        """
+        while 1:
+            task = self.config.get_next()
+            self.config.task = task
+            self._gui_update_tasks()
+
+            # from module.base.resource import release_resources
+            # if self.config.task.command != 'Alas':
+            #     release_resources(next_task=task.command)
+
+            if task.next_run > datetime.now():
+                logger.info(f'Wait until {task.next_run} for task `{task.command}`')
+                # self.is_first_task = False
+                method = self.config.optimization.when_task_queue_empty
+                if method == 'close_game':
+                    logger.info('Close game during wait')
+                    self.device.app_stop()
+                    self.device.release_during_wait()
+                    if not self.wait_until(task.next_run):
+                        del_cached_property(self, 'config')
+                        continue
+                    self.run('start')
+                elif method == 'goto_main':
+                    logger.info('Goto main page during wait')
+                    self.run('goto_main')
+                    self.device.release_during_wait()
+                    if not self.wait_until(task.next_run):
+                        del_cached_property(self, 'config')
+                        continue
+                else:
+                    logger.warning(f'Invalid Optimization_WhenTaskQueueEmpty: {method}, fallback to stay_there')
+                    self.device.release_during_wait()
+                    if not self.wait_until(task.next_run):
+                        del_cached_property(self, 'config')
+                        continue
+            break
+
+        return task.command
+
+    def run(self, command: str) -> bool:
+        """
+
+        :param command:
+        :return:
+        """
+        if command == 'start' and command == 'goto_main':
+            logger.error(f'Invalid command `{command}`')
+
+        try:
+            self.device.screenshot()
+            module_name = 'script_task'
+            module_path = str(Path.cwd() / 'tasks' / command / (module_name+'.py'))
+            logger.info(f'module_path: {module_path}, module_name: {module_name}')
+            task_module = load_module(module_name, module_path)
+            task_module.ScriptTask(config=self.config, device=self.device).run()
+        except TaskEnd:
+            return True
+        except GameNotRunningError as e:
+            logger.warning(e)
+            self.config.task_call('Restart')
+            return True
+        except (GameStuckError, GameTooManyClickError) as e:
+            logger.error(e)
+            self.save_error_log()
+            logger.warning(f'Game stuck, {self.device.package} will be restarted in 10 seconds')
+            logger.warning('If you are playing by hand, please stop Alas')
+            self.config.task_call('Restart')
+            self.device.sleep(10)
+            return False
+        except GameBugError as e:
+            logger.warning(e)
+            self.save_error_log()
+            logger.warning('An error has occurred in Azur Lane game client, Alas is unable to handle')
+            logger.warning(f'Restarting {self.device.package} to fix it')
+            self.config.task_call('Restart')
+            self.device.sleep(10)
+            return False
+        except GamePageUnknownError:
+            logger.info('Game server may be under maintenance or network may be broken, check server status now')
+            self.checker.check_now()
+            if self.checker.is_available():
+                logger.critical('Game page unknown')
+                self.save_error_log()
+                exit(1)
+            else:
+                self.checker.wait_until_available()
+                return False
+        except ScriptError as e:
+            logger.critical(e)
+            logger.critical('This is likely to be a mistake of developers, but sometimes just random issues')
+            exit(1)
+        except RequestHumanTakeover:
+            logger.critical('Request human takeover')
+            exit(1)
+        except Exception as e:
+            logger.exception(e)
+            self.save_error_log()
+            exit(1)
+
+    def loop(self):
+        """
+        Main loop of scheduler.
+        :return:
+        """
+        logger.set_file_logger(self.config_name)
+        logger.info(f'Start scheduler loop: {self.config_name}')
+
+        while 1:
+            # Check update event from GUI
+            # if self.stop_event is not None:
+            #     if self.stop_event.is_set():
+            #         logger.info("Update event detected")
+            #         logger.info(f"Alas [{self.config_name}] exited.")
+            #         break
+
+            # Check game server maintenance
+            # self.checker.wait_until_available()
+            # if self.checker.is_recovered():
+            #     # There is an accidental bug hard to reproduce
+            #     # Sometimes, config won't be updated due to blocking
+            #     # even though it has been changed
+            #     # So update it once recovered
+            #     del_cached_property(self, 'config')
+            #     logger.info('Server or network is recovered. Restart game client')
+            #     self.config.task_call('Restart')
+
+            # Get task
+            task = self.get_next_task()
+            # 更新 gui的任务
+            # Init device and change server
+            _ = self.device
+            # Skip first restart
+            if self.is_first_task and task == 'Restart':
+                logger.info('Skip task `Restart` at scheduler start')
+                self.config.task_delay(server_update=True)
+                del_cached_property(self, 'config')
+                continue
+
+            # Run
+            logger.info(f'Scheduler: Start task `{task}`')
+            self.device.stuck_record_clear()
+            self.device.click_record_clear()
+            logger.hr(task, level=0)
+            success = self.run(inflection.camelize(task))
+            logger.info(f'Scheduler: End task `{task}`')
+            self.is_first_task = False
+
+            # Check failures
+            # failed = deep_get(self.failure_record, keys=task, default=0)
+            failed = self.failure_record[task] if task in self.failure_record else 0
+            failed = 0 if success else failed + 1
+            # deep_set(self.failure_record, keys=task, value=failed)
+            self.failure_record[task] = failed
+            if failed >= 3:
+                logger.critical(f"Task `{task}` failed 3 or more times.")
+                logger.critical("Possible reason #1: You haven't used it correctly. "
+                                "Please read the help text of the options.")
+                logger.critical("Possible reason #2: There is a problem with this task. "
+                                "Please contact developers or try to fix it yourself.")
+                logger.critical('Request human takeover')
+                exit(1)
+
+            if success:
+                del_cached_property(self, 'config')
+                continue
+            elif self.config.error.handle.error:
+                # self.config.task_delay(success=False)
+                del_cached_property(self, 'config')
+                self.checker.check_now()
+                continue
+            else:
+                break
+
+    def start_loop(self) -> None:
+        """
+        创建一个线程,运行loop
+        :return:
+        """
+        if self.loop_thread is None:
+            self.loop_thread = Thread(target=self.loop, name='Script_loop')
+            self.loop_thread.start()
 
 
 
 
 if __name__ == "__main__":
 if __name__ == "__main__":
     script = Script("oas1")
     script = Script("oas1")
+    print(script.get_next_task())
+    script.run("AreaBoss")

+ 30 - 0
tasks/AreaBoss/assets.py

@@ -0,0 +1,30 @@
+from module.atom.image import RuleImage
+from module.atom.click import RuleClick
+from module.atom.long_click import RuleLongClick
+from module.atom.swipe import RuleSwipe
+
+# This file was automatically generated by module/dev_tools/assets_extract.py.
+# Don't modify it manually.
+class AreaBossAssets: 
+
+	# Image Rule Assets
+	# 探索图标 
+	I_EXPLORE = RuleImage(roi_front=(758,122,66,77), roi_back=(339,104,836,120), threshold=0.8, method="Template matching", file="./tasks/AreaBoss/res/res_explore.png")
+	# 地狱鬼王图标 
+	I_AREA_BOSS = RuleImage(roi_front=(639,636,65,68), roi_back=(606,619,145,100), threshold=0.8, method="Template matching", file="./tasks/AreaBoss/res/res_area_boss.png")
+	# 蓝色的返回 
+	I_BACK_BLUE = RuleImage(roi_front=(51,30,51,52), roi_back=(4,1,128,110), threshold=0.8, method="Template matching", file="./tasks/AreaBoss/res/res_back_blue.png")
+	# 右上边选中鬼王的 
+	I_FILTER = RuleImage(roi_front=(1106,29,48,49), roi_back=(1106,29,48,49), threshold=0.8, method="Template matching", file="./tasks/AreaBoss/res/res_filter.png")
+	# 选中第一个鬼王的 
+	I_BATTLE_1 = RuleImage(roi_front=(1066,210,100,100), roi_back=(1066,210,100,100), threshold=0.8, method="Template matching", file="./tasks/AreaBoss/res/res_battle_1.png")
+	# 选中第二个鬼王的 
+	I_BATTLE_2 = RuleImage(roi_front=(1068,364,100,100), roi_back=(1068,364,100,100), threshold=0.8, method="Template matching", file="./tasks/AreaBoss/res/res_battle_2.png")
+	# 选中第三个鬼王的 
+	I_BATTLE_3 = RuleImage(roi_front=(1071,521,100,100), roi_back=(1071,521,100,100), threshold=0.8, method="Template matching", file="./tasks/AreaBoss/res/res_battle_3.png")
+	# 点击挑战 
+	I_FIRE = RuleImage(roi_front=(1108,492,100,100), roi_back=(1108,492,100,100), threshold=0.8, method="Template matching", file="./tasks/AreaBoss/res/res_fire.png")
+	# 红色的关闭 
+	I_CLOSE_RED = RuleImage(roi_front=(1190,24,37,38), roi_back=(1190,24,37,38), threshold=0.8, method="Template matching", file="./tasks/AreaBoss/res/res_close_red.png")
+
+

+ 14 - 0
tasks/AreaBoss/config.py

@@ -0,0 +1,14 @@
+# This Python file uses the following encoding: utf-8
+# @author runhey
+# github https://github.com/runhey
+from pydantic import BaseModel, Field
+
+from tasks.AreaBoss.config_scheduler import Scheduler
+from tasks.GeneralBattle.config_general_battle import GeneralBattleConfig
+from tasks.AreaBoss.config_boss import Boss
+
+
+class AreaBoss(BaseModel):
+    scheduler: Scheduler = Field(default_factory=Scheduler)
+    general_battle: GeneralBattleConfig = Field(default_factory=GeneralBattleConfig)
+    boss: Boss = Field(default_factory=Boss)

+ 12 - 0
tasks/AreaBoss/config_boss.py

@@ -0,0 +1,12 @@
+# This Python file uses the following encoding: utf-8
+# @author runhey
+# github https://github.com/runhey
+from enum import Enum
+from datetime import datetime, time
+from pydantic import BaseModel, ValidationError, validator, Field
+
+class Boss(BaseModel):
+    boss_number: int = Field(title='Boss Number',
+                             default=3,
+                             description='只可选范围1~3',
+                             ge=1, le=3)

+ 15 - 0
tasks/AreaBoss/config_scheduler.py

@@ -0,0 +1,15 @@
+# This Python file uses the following encoding: utf-8
+# @author runhey
+# github https://github.com/runhey
+from enum import Enum
+from datetime import datetime, time
+from pydantic import BaseModel, ValidationError, validator, Field
+
+class Scheduler(BaseModel):
+    enable: bool = Field(default=False,
+                         description='none')
+    next_run: datetime = Field(default="2023-01-01 00:00:00",
+                               description='none')
+    priority: int = Field(default=3,
+                          description='已经弃置,不生效')
+

+ 1 - 0
tasks/AreaBoss/res/image.json

@@ -0,0 +1 @@
+[{"itemName":"explore","imageName":"res_explore.png","roiFront":"758,122,66,77","roiBack":"339,104,836,120","method":"Template matching","threshold":0.8,"description":"探索图标"},{"itemName":"area_boss","imageName":"res_area_boss.png","roiFront":"639,636,65,68","roiBack":"606,619,145,100","method":"Template matching","threshold":0.8,"description":"地狱鬼王图标"},{"itemName":"back_blue","imageName":"res_back_blue.png","roiFront":"51,30,51,52","roiBack":"4,1,128,110","method":"Template matching","threshold":0.8,"description":"蓝色的返回"},{"itemName":"filter","imageName":"res_filter.png","roiFront":"1106,29,48,49","roiBack":"1106,29,48,49","method":"Template matching","threshold":0.8,"description":"右上边选中鬼王的"},{"itemName":"battle_1","imageName":"res_battle_1.png","roiFront":"1066,210,100,100","roiBack":"1066,210,100,100","method":"Template matching","threshold":0.8,"description":"选中第一个鬼王的"},{"itemName":"battle_2","imageName":"res_battle_2.png","roiFront":"1068,364,100,100","roiBack":"1068,364,100,100","method":"Template matching","threshold":0.8,"description":"选中第二个鬼王的"},{"itemName":"battle_3","imageName":"res_battle_3.png","roiFront":"1071,521,100,100","roiBack":"1071,521,100,100","method":"Template matching","threshold":0.8,"description":"选中第三个鬼王的"},{"itemName":"fire","imageName":"res_fire.png","roiFront":"1108,492,100,100","roiBack":"1108,492,100,100","method":"Template matching","threshold":0.8,"description":"点击挑战"},{"itemName":"close_red","imageName":"res_close_red.png","roiFront":"1190,24,37,38","roiBack":"1190,24,37,38","method":"Template matching","threshold":0.8,"description":"红色的关闭"}]

BIN
tasks/AreaBoss/res/res_area_boss.png


BIN
tasks/AreaBoss/res/res_back_blue.png


BIN
tasks/AreaBoss/res/res_battle_1.png


BIN
tasks/AreaBoss/res/res_battle_2.png


BIN
tasks/AreaBoss/res/res_battle_3.png


BIN
tasks/AreaBoss/res/res_close_red.png


BIN
tasks/AreaBoss/res/res_explore.png


BIN
tasks/AreaBoss/res/res_filter.png


BIN
tasks/AreaBoss/res/res_fire.png


+ 188 - 0
tasks/AreaBoss/script_task.py

@@ -0,0 +1,188 @@
+# This Python file uses the following encoding: utf-8
+# @author runhey
+# github https://github.com/runhey
+import time
+
+from tasks.base_task import BaseTask
+from tasks.GeneralBattle.general_battle import GeneralBattle
+from tasks.AreaBoss.assets import AreaBossAssets
+from module.logger import logger
+from module.exception import TaskEnd
+
+
+class ScriptTask(GeneralBattle, AreaBossAssets):
+
+    def run(self) -> bool:
+        """
+        运行脚本
+        :return:
+        """
+        # 直接手动关闭这个锁定阵容的设置
+        self.config.area_boss.general_battle.lock_team_enable = False
+
+        # 点击探索
+        logger.info("Click explore")
+        while 1:
+            self.screenshot()
+            if self.appear_then_click(self.I_EXPLORE, threshold=0.6, interval=2):
+                continue
+            if self.appear(self.I_AREA_BOSS, threshold=0.6):
+                break
+
+        # 点击地狱鬼王
+        logger.info("Click area boss")
+        while 1:
+            self.screenshot()
+            if self.appear_then_click(self.I_AREA_BOSS, threshold=0.6, interval=2):
+                continue
+            if self.appear(self.I_FILTER, threshold=0.6):
+                break
+
+        # 点击右上角的鬼王选择
+        logger.info("Click filter")
+        while 1:
+            self.screenshot()
+            if self.appear_then_click(self.I_FILTER, threshold=0.8, interval=2):
+                continue
+            if self.appear(self.I_BATTLE_1):
+                break
+
+        # 点击第一个鬼王
+        logger.info("Click battle 1")
+        while 1:
+            self.screenshot()
+            if self.appear_then_click(self.I_BATTLE_1, threshold=0.8, interval=1):
+                continue
+            if self.appear(self.I_CLOSE_RED):
+                break
+
+        # 点击挑战
+        logger.info("Script fire")
+        while 1:
+            self.screenshot()
+            if self.appear_then_click(self.I_FIRE, interval=1):
+                continue
+            if not self.appear(self.I_CLOSE_RED):  # 如果这个红色的关闭不见了才可以进行继续
+                break
+        logger.info("Script general battle")
+        if not self.run_general_battle(self.config.area_boss.general_battle):
+            logger.info("地狱鬼王第一只战斗失败")
+
+        # 红色关闭
+        logger.info("Script close red")
+        self.wait_until_appear(self.I_CLOSE_RED)
+        while 1:
+            self.screenshot()
+            if self.appear_then_click(self.I_CLOSE_RED, interval=1):
+                continue
+            if self.appear(self.I_FILTER):
+                break
+        # 只挑战一只, 退出
+        if self.config.area_boss.boss.boss_number == 1:
+            self.go_back()
+            return True
+
+        # 点击右上角的鬼王选择
+        logger.info("Script filter")
+        while 1:
+            self.screenshot()
+            if self.appear_then_click(self.I_FILTER, threshold=0.8, interval=2):
+                continue
+            if self.appear(self.I_BATTLE_2):
+                break
+
+        # 点击第2个鬼王
+        logger.info("Script area boss 2")
+        while 1:
+            self.screenshot()
+            if self.appear_then_click(self.I_BATTLE_2, threshold=0.8, interval=1):
+                continue
+            if self.appear(self.I_CLOSE_RED):
+                break
+
+        # 点击挑战
+        logger.info("Script fire ")
+        while 1:
+            self.screenshot()
+            if self.appear_then_click(self.I_FIRE, interval=1):
+                continue
+            if not self.appear(self.I_CLOSE_RED):  # 如果这个红色的关闭不见了才可以进行继续
+                break
+
+        if not self.run_general_battle(self.config.area_boss.general_battle):
+            logger.info("地狱鬼王第2只战斗失败")
+
+        # 红色关闭
+        logger.info("Script close red")
+        self.wait_until_appear(self.I_CLOSE_RED)
+        while 1:
+            self.screenshot()
+            if self.appear_then_click(self.I_CLOSE_RED, interval=1):
+                continue
+            if self.appear(self.I_FILTER):
+                break
+        # 只挑战2只, 退出
+        if self.config.area_boss.boss.boss_number == 2:
+            self.go_back()
+            return True
+
+
+        #---------------------------------------------第三只
+        # 点击右上角的鬼王选择
+        logger.info("Script filter")
+        while 1:
+            self.screenshot()
+            if self.appear_then_click(self.I_FILTER, threshold=0.8, interval=2):
+                continue
+            if self.appear(self.I_BATTLE_3):
+                break
+        # 点击第3个鬼王
+        logger.info("Script area boss 3")
+        while 1:
+            self.screenshot()
+            if self.appear_then_click(self.I_BATTLE_3, threshold=0.8, interval=1):
+                continue
+            if self.appear(self.I_CLOSE_RED):
+                break
+        # 点击挑战
+        logger.info("Script fire ")
+        while 1:
+            self.screenshot()
+            if self.appear_then_click(self.I_FIRE, interval=1):
+                continue
+            if not self.appear(self.I_CLOSE_RED):  # 如果这个红色的关闭不见了才可以进行继续
+                break
+        if not self.run_general_battle(self.config.area_boss.general_battle):
+            logger.info("地狱鬼王第2只战斗失败")
+        # 红色关闭
+        logger.info("Script close red")
+        self.wait_until_appear(self.I_CLOSE_RED)
+        while 1:
+            self.screenshot()
+            if self.appear_then_click(self.I_CLOSE_RED, interval=1):
+                continue
+            if self.appear(self.I_FILTER):
+                break
+
+        # 退出
+        self.go_back()
+
+        # 以抛出异常的形式结束
+        raise TaskEnd
+
+    def go_back(self) -> None:
+        """
+        返回, 要求这个时候是出现在  地狱鬼王的主界面
+        :return:
+        """
+        # 点击返回
+        logger.info("Script back home")
+        while 1:
+            self.screenshot()
+            if self.appear_then_click(self.I_BACK_BLUE, threshold=0.6, interval=2):
+                continue
+            if self.appear(self.I_EXPLORE, threshold=0.6):
+                break
+
+
+

+ 11 - 11
tasks/CoinChallenge/assets.py

@@ -5,7 +5,7 @@ from module.atom.swipe import RuleSwipe
 
 
 # This file was automatically generated by module/dev_tools/assets_extract.py.
 # This file was automatically generated by module/dev_tools/assets_extract.py.
 # Don't modify it manually.
 # Don't modify it manually.
-class Assets: 
+class CoinChallengeAssets: 
 
 
 	# Image Rule Assets
 	# Image Rule Assets
 	# description 
 	# description 
@@ -16,26 +16,26 @@ class Assets:
 	I_NEW3 = RuleImage(roi_front=(568,212,240,220), roi_back=(0,0,100,100), threshold=0.9, method="Template matching", file="./tasks/CoinChallenge/res/res_new3.png")
 	I_NEW3 = RuleImage(roi_front=(568,212,240,220), roi_back=(0,0,100,100), threshold=0.9, method="Template matching", file="./tasks/CoinChallenge/res/res_new3.png")
 	# Click Rule Assets
 	# Click Rule Assets
 	# description 
 	# description 
-	C_NEW1 = RuleClick(roi_front=(268,268,100,100), roi_back=(614,214,100,100))
+	C_NEW1 = RuleClick(roi_front=(268,268,100,100), roi_back=(614,214,100,100), name="new1")
 	# description 
 	# description 
-	C_NEW2 = RuleClick(roi_front=(171,236,100,100), roi_back=(554,225,100,100))
+	C_NEW2 = RuleClick(roi_front=(171,236,100,100), roi_back=(554,225,100,100), name="new2")
 	# desc444n 
 	# desc444n 
-	C_NEW3 = RuleClick(roi_front=(180,150,100,100), roi_back=(596,247,100,100))
+	C_NEW3 = RuleClick(roi_front=(180,150,100,100), roi_back=(596,247,100,100), name="new3")
 	# Long Click Rule Assets
 	# Long Click Rule Assets
 	# description 
 	# description 
-	L_NEW1 = RuleLongClick(roi_front=(208,151,100,100), roi_back=(542,279,100,100), duration=1500)
+	L_NEW1 = RuleLongClick(roi_front=(208,151,100,100), roi_back=(542,279,100,100), duration=1500, name="new1")
 	# description 
 	# description 
-	L_NEW2 = RuleLongClick(roi_front=(355,191,100,100), roi_back=(526,323,100,100), duration=1500)
+	L_NEW2 = RuleLongClick(roi_front=(355,191,100,100), roi_back=(526,323,100,100), duration=1500, name="new2")
 	# de66666n 
 	# de66666n 
-	L_NEW3 = RuleLongClick(roi_front=(112,156,100,100), roi_back=(469,200,100,100), duration=1000)
+	L_NEW3 = RuleLongClick(roi_front=(112,156,100,100), roi_back=(469,200,100,100), duration=1000, name="new3")
 	# Swipe Rule Assets
 	# Swipe Rule Assets
 	# description 
 	# description 
-	S_NEW1 = RuleSwipe(roi_front=(253,212,100,100), roi_back=(652,292,100,100), mode="default")
+	S_NEW1 = RuleSwipe(roi_front=(253,212,100,100), roi_back=(652,292,100,100), mode="default", name="new1")
 	# description 
 	# description 
-	S_NEW2 = RuleSwipe(roi_front=(265,272,100,100), roi_back=(622,338,100,100), mode="default")
+	S_NEW2 = RuleSwipe(roi_front=(265,272,100,100), roi_back=(622,338,100,100), mode="default", name="new2")
 	# description 
 	# description 
-	S_NEW3 = RuleSwipe(roi_front=(198,160,100,100), roi_back=(626,305,100,100), mode="default")
+	S_NEW3 = RuleSwipe(roi_front=(198,160,100,100), roi_back=(626,305,100,100), mode="default", name="new3")
 	# description 
 	# description 
-	S_NEW4 = RuleSwipe(roi_front=(150,145,100,100), roi_back=(535,199,100,100), mode="vector")
+	S_NEW4 = RuleSwipe(roi_front=(150,145,100,100), roi_back=(535,199,100,100), mode="vector", name="new4")
 
 
 
 

+ 10 - 0
tasks/DemonEncounter/assets.py

@@ -0,0 +1,10 @@
+from module.atom.image import RuleImage
+from module.atom.click import RuleClick
+from module.atom.long_click import RuleLongClick
+from module.atom.swipe import RuleSwipe
+
+# This file was automatically generated by module/dev_tools/assets_extract.py.
+# Don't modify it manually.
+class DemonEncounterAssets: 
+	pass
+

+ 6 - 0
tasks/DemonEncounter/config.py

@@ -0,0 +1,6 @@
+# This Python file uses the following encoding: utf-8
+# @author runhey
+# github https://github.com/runhey
+from pydantic import BaseModel, Field
+
+from tasks.DemonEncounter.config_scheduler import Scheduler

+ 15 - 0
tasks/DemonEncounter/config_scheduler.py

@@ -0,0 +1,15 @@
+# This Python file uses the following encoding: utf-8
+# @author runhey
+# github https://github.com/runhey
+from enum import Enum
+from datetime import datetime, time
+from pydantic import BaseModel, ValidationError, validator, Field
+
+class Scheduler(BaseModel):
+    enable: bool = Field(default=False,
+                         description='none')
+    next_run: datetime = Field(default="2023-01-01 00:00:00",
+                               description='none')
+    priority: int = Field(default=3,
+                          description='default 3')
+

+ 10 - 0
tasks/EternitySea/assets.py

@@ -0,0 +1,10 @@
+from module.atom.image import RuleImage
+from module.atom.click import RuleClick
+from module.atom.long_click import RuleLongClick
+from module.atom.swipe import RuleSwipe
+
+# This file was automatically generated by module/dev_tools/assets_extract.py.
+# Don't modify it manually.
+class EternitySeaAssets: 
+	pass
+

+ 10 - 0
tasks/EternitySea/config.py

@@ -0,0 +1,10 @@
+# This Python file uses the following encoding: utf-8
+# @author runhey
+# github https://github.com/runhey
+from pydantic import BaseModel, Field
+
+from tasks.EternitySea.config_scheduler import Scheduler
+
+
+class EternitySea(BaseModel):
+    scheduler: Scheduler = Field(default_factory=Scheduler)

+ 15 - 0
tasks/EternitySea/config_scheduler.py

@@ -0,0 +1,15 @@
+# This Python file uses the following encoding: utf-8
+# @author runhey
+# github https://github.com/runhey
+from enum import Enum
+from datetime import datetime, time
+from pydantic import BaseModel, ValidationError, validator, Field
+
+class Scheduler(BaseModel):
+    enable: bool = Field(default=False,
+                         description='none')
+    next_run: datetime = Field(default="2023-01-01 00:00:00",
+                               description='none')
+    priority: int = Field(default=3,
+                          description='default 3')
+

+ 10 - 0
tasks/ExperienceYoukai/assets.py

@@ -0,0 +1,10 @@
+from module.atom.image import RuleImage
+from module.atom.click import RuleClick
+from module.atom.long_click import RuleLongClick
+from module.atom.swipe import RuleSwipe
+
+# This file was automatically generated by module/dev_tools/assets_extract.py.
+# Don't modify it manually.
+class ExperienceYoukaiAssets: 
+	pass
+

+ 10 - 0
tasks/ExperienceYoukai/config.py

@@ -0,0 +1,10 @@
+# This Python file uses the following encoding: utf-8
+# @author runhey
+# github https://github.com/runhey
+from pydantic import BaseModel, Field
+
+from tasks.ExperienceYoukai.config_scheduler import Scheduler
+
+class ExperienceYoukai(BaseModel):
+    scheduler: Scheduler = Field(default_factory=Scheduler)
+

+ 15 - 0
tasks/ExperienceYoukai/config_scheduler.py

@@ -0,0 +1,15 @@
+# This Python file uses the following encoding: utf-8
+# @author runhey
+# github https://github.com/runhey
+from enum import Enum
+from datetime import datetime, time
+from pydantic import BaseModel, ValidationError, validator, Field
+
+class Scheduler(BaseModel):
+    enable: bool = Field(default=False,
+                         description='none')
+    next_run: datetime = Field(default="2023-01-01 00:00:00",
+                               description='none')
+    priority: int = Field(default=3,
+                          description='default 3')
+

+ 10 - 0
tasks/FallenSun/assets.py

@@ -0,0 +1,10 @@
+from module.atom.image import RuleImage
+from module.atom.click import RuleClick
+from module.atom.long_click import RuleLongClick
+from module.atom.swipe import RuleSwipe
+
+# This file was automatically generated by module/dev_tools/assets_extract.py.
+# Don't modify it manually.
+class FallenSunAssets: 
+	pass
+

+ 11 - 0
tasks/FallenSun/config.py

@@ -0,0 +1,11 @@
+# This Python file uses the following encoding: utf-8
+# @author runhey
+# github https://github.com/runhey
+from pydantic import BaseModel, Field
+
+from tasks.FallenSun.config_scheduler import Scheduler
+
+
+class FallenSun(BaseModel):
+    scheduler: Scheduler = Field(default_factory=Scheduler)
+

+ 15 - 0
tasks/FallenSun/config_scheduler.py

@@ -0,0 +1,15 @@
+# This Python file uses the following encoding: utf-8
+# @author runhey
+# github https://github.com/runhey
+from enum import Enum
+from datetime import datetime, time
+from pydantic import BaseModel, ValidationError, validator, Field
+
+class Scheduler(BaseModel):
+    enable: bool = Field(default=False,
+                         description='none')
+    next_run: datetime = Field(default="2023-01-01 00:00:00",
+                               description='none')
+    priority: int = Field(default=3,
+                          description='default 3')
+

+ 10 - 0
tasks/General/assets.py

@@ -0,0 +1,10 @@
+from module.atom.image import RuleImage
+from module.atom.click import RuleClick
+from module.atom.long_click import RuleLongClick
+from module.atom.swipe import RuleSwipe
+
+# This file was automatically generated by module/dev_tools/assets_extract.py.
+# Don't modify it manually.
+class GeneralAssets: 
+	pass
+

+ 86 - 0
tasks/GeneralBattle/assets.py

@@ -0,0 +1,86 @@
+from module.atom.image import RuleImage
+from module.atom.click import RuleClick
+from module.atom.long_click import RuleLongClick
+from module.atom.swipe import RuleSwipe
+
+# This file was automatically generated by module/dev_tools/assets_extract.py.
+# Don't modify it manually.
+class GeneralBattleAssets: 
+	# Click Rule Assets
+	# 预设队伍1 
+	C_PRESET_TEAM_1 = RuleClick(roi_front=(196,234,464,114), roi_back=(196,234,464,114), name="preset_team_1")
+	# 预设队伍2 
+	C_PRESET_TEAM_2 = RuleClick(roi_front=(197,358,465,103), roi_back=(197,358,465,103), name="preset_team_2")
+	# 预设队伍3 
+	C_PRESET_TEAM_3 = RuleClick(roi_front=(195,480,462,100), roi_back=(195,480,462,100), name="preset_team_3")
+	# 预设队伍4 
+	C_PRESET_TEAM_4 = RuleClick(roi_front=(193,596,464,35), roi_back=(193,596,464,35), name="preset_team_4")
+	# 预设组1 
+	C_PRESET_GROUP_1 = RuleClick(roi_front=(28,238,134,56), roi_back=(28,238,134,56), name="preset_group_1")
+	# 预设组2 
+	C_PRESET_GROUP_2 = RuleClick(roi_front=(31,298,132,60), roi_back=(31,298,132,60), name="preset_group_2")
+	# 预设组3 
+	C_PRESET_GROUP_3 = RuleClick(roi_front=(31,362,135,59), roi_back=(31,362,135,59), name="preset_group_3")
+	# 预设组4 
+	C_PRESET_GROUP_4 = RuleClick(roi_front=(29,427,133,57), roi_back=(29,427,133,57), name="preset_group_4")
+	# 预设组5 
+	C_PRESET_GROUP_5 = RuleClick(roi_front=(31,489,133,60), roi_back=(31,489,133,60), name="preset_group_5")
+	# 预设组6 
+	C_PRESET_GROUP_6 = RuleClick(roi_front=(31,549,132,63), roi_back=(31,549,132,63), name="preset_group_6")
+	# 预设组7 
+	C_PRESET_GROUP_7 = RuleClick(roi_front=(29,615,137,63), roi_back=(29,615,137,63), name="preset_group_7")
+	# 从左开始第一个绿标 
+	C_GREEN_LEFT_1 = RuleClick(roi_front=(128,433,90,150), roi_back=(128,433,90,150), name="green_left_1")
+	# 从左开始第二个绿标 
+	C_GREEN_LEFT_2 = RuleClick(roi_front=(371,385,81,145), roi_back=(371,385,81,145), name="green_left_2")
+	# 从左开始第三个绿标 
+	C_GREEN_LEFT_3 = RuleClick(roi_front=(586,328,100,76), roi_back=(586,328,100,76), name="green_left_3")
+	# 从左开始第四个绿标 
+	C_GREEN_LEFT_4 = RuleClick(roi_front=(817,379,77,133), roi_back=(817,379,77,133), name="green_left_4")
+	# 从左开始第五个绿标 
+	C_GREEN_LEFT_5 = RuleClick(roi_front=(1059,416,85,145), roi_back=(1059,416,85,145), name="green_left_5")
+	# 绿标阴阳师 
+	C_GREEN_MAIN = RuleClick(roi_front=(590,454,88,178), roi_back=(590,454,88,178), name="green_main")
+	# 战斗的时候有一定的概率随机点击 
+	C_RANDOM_CLICK = RuleClick(roi_front=(104,79,1050,507), roi_back=(255,65,100,100), name="random_click")
+
+	# Image Rule Assets
+	# 奖励,就是那个魂 
+	I_REWARD = RuleImage(roi_front=(547,518,172,96), roi_back=(547,518,172,96), threshold=0.8, method="Template matching", file="./tasks/GeneralBattle/res/res_reward.png")
+	# 预设的小图标 
+	I_PRESET = RuleImage(roi_front=(32,650,47,45), roi_back=(32,650,47,45), threshold=0.8, method="Template matching", file="./tasks/GeneralBattle/res/res_preset.png")
+	# 准备 
+	I_PREPARE_HIGHLIGHT = RuleImage(roi_front=(1128,536,100,100), roi_back=(1128,536,100,100), threshold=0.8, method="Template matching", file="./tasks/GeneralBattle/res/res_prepare_highlight.png")
+	# 战斗胜利 
+	I_WIN = RuleImage(roi_front=(427,135,100,100), roi_back=(427,135,100,100), threshold=0.8, method="Template matching", file="./tasks/GeneralBattle/res/res_win.png")
+	# 准备但是界面还未加载这个时候是黑色的 
+	I_PREPARE_DARK = RuleImage(roi_front=(1131,538,100,100), roi_back=(1131,538,100,100), threshold=0.8, method="Template matching", file="./tasks/GeneralBattle/res/res_prepare_dark.png")
+	# 失败 
+	I_FALSE = RuleImage(roi_front=(413,124,100,100), roi_back=(413,124,100,100), threshold=0.8, method="Template matching", file="./tasks/GeneralBattle/res/res_false.png")
+	# 确认预设的队伍 
+	I_PRESET_ENSURE = RuleImage(roi_front=(354,641,141,50), roi_back=(354,641,141,50), threshold=0.8, method="Template matching", file="./tasks/GeneralBattle/res/res_preset_ensure.png")
+	# 选择buff 
+	I_BUFF = RuleImage(roi_front=(113,653,44,62), roi_back=(113,653,44,62), threshold=0.8, method="Template matching", file="./tasks/GeneralBattle/res/res_buff.png")
+	# 觉醒加成 
+	I_BUFF_AWAKEN = RuleImage(roi_front=(373,126,383,53), roi_back=(373,126,383,53), threshold=0.8, method="Template matching", file="./tasks/GeneralBattle/res/res_buff_awaken.png")
+	# 御魂加成 
+	I_BUFF_SOUL = RuleImage(roi_front=(377,192,371,56), roi_back=(377,192,371,56), threshold=0.8, method="Template matching", file="./tasks/GeneralBattle/res/res_buff_soul.png")
+	# 金币加成50 
+	I_BUFF_GOLD_50 = RuleImage(roi_front=(375,259,373,56), roi_back=(375,259,373,56), threshold=0.8, method="Template matching", file="./tasks/GeneralBattle/res/res_buff_gold_50.png")
+	# 金币加成100 
+	I_BUFF_GOLD_100 = RuleImage(roi_front=(371,329,389,54), roi_back=(371,329,389,54), threshold=0.8, method="Template matching", file="./tasks/GeneralBattle/res/res_buff_gold_100.png")
+	# 经验加成50 
+	I_BUFF_EXP_50 = RuleImage(roi_front=(378,400,370,50), roi_back=(378,400,370,50), threshold=0.8, method="Template matching", file="./tasks/GeneralBattle/res/res_buff_exp_50.png")
+	# 经验加成100 
+	I_BUFF_EXP_100 = RuleImage(roi_front=(372,463,386,50), roi_back=(372,463,386,50), threshold=0.8, method="Template matching", file="./tasks/GeneralBattle/res/res_buff_exp_100.png")
+	# 左下角的位置指针 
+	I_LOCAL = RuleImage(roi_front=(25,563,30,34), roi_back=(25,563,30,34), threshold=0.8, method="Template matching", file="./tasks/GeneralBattle/res/res_local.png")
+	# description 
+	I_STATISTICS = RuleImage(roi_front=(61,644,33,28), roi_back=(61,644,33,28), threshold=0.8, method="Template matching", file="./tasks/GeneralBattle/res/res_statistics.png")
+	# Swipe Rule Assets
+	# description 
+	S_BATTLE_RANDOM_LEFT = RuleSwipe(roi_front=(122,155,480,426), roi_back=(667,147,461,427), mode="default", name="battle_random_left")
+	# description 
+	S_BATTLE_RANDOM_RIGHT = RuleSwipe(roi_front=(719,138,417,392), roi_back=(237,163,387,394), mode="default", name="battle_random_right")
+
+

+ 69 - 0
tasks/GeneralBattle/config_general_battle.py

@@ -0,0 +1,69 @@
+# This Python file uses the following encoding: utf-8
+# @author runhey
+# github https://github.com/runhey
+from enum import Enum
+from datetime import datetime, time
+from pydantic import BaseModel, ValidationError, validator, Field
+
+class GreenMarkType(str, Enum):
+    GREEN_LEFT1 = 'green_left1'
+    GREEN_LEFT2 = 'green_left2'
+    GREEN_LEFT3 = 'green_left3'
+    GREEN_LEFT4 = 'green_left4'
+    GREEN_LEFT5 = 'green_left5'
+    GREEN_MAIN = 'green_main'
+
+class GeneralBattleConfig(BaseModel):
+
+    # 是否锁定阵容, 有些的战斗是外边的锁定阵容甚至有些的战斗没有锁定阵容的
+    lock_team_enable: bool = Field(default=False,
+                                   description='default is false')
+
+    # 是否启动 预设队伍
+    preset_enable: bool = Field(default=False,
+                                description='default is false')
+    # 选哪一个预设组
+    preset_group: int = Field(default=1,
+                              description='default is 1, max is 7, min is 1',
+                              ge=1, le=7)
+    # 选哪一个队伍
+    preset_team: int = Field(default=1,
+                             description='default is 1, min is 1, max is 4',
+                             ge=1, le=4)
+
+    # 是否启动开启buff
+    buff_enable: bool = Field(default=False,
+                               description='default is false')
+    # 是否点击觉醒Buff
+    buff_awake_click: bool = Field(default=False,
+                                   description='default is false')
+    # 是否点击御魂buff
+    buff_soul_click: bool = Field(default=False,
+                                  description='default is false')
+    # 是否点击金币50buff
+    buff_gold_50_click: bool = Field(default=False,
+                                    description='default is false')
+    # 是否点击金币100buff
+    buff_gold_100_click: bool = Field(default=False,
+                                        description='default is false')
+    # 是否点击经验50buff
+    buff_exp_50_click: bool = Field(default=False,
+                                    description='default is false')
+    # 是否点击经验100buff
+    buff_exp_100_click: bool = Field(default=False,
+                                    description='default is false')
+
+    # 是否开启绿标
+    green_enable: bool = Field(default=False,
+                                 description='default is false')
+    # 选哪一个绿标
+    green_mark: GreenMarkType = Field(default=GreenMarkType.GREEN_LEFT1,
+                                        description='default is GREEN_LEFT1')
+
+    # 是否启动战斗时随机点击或者随机滑动
+    random_click_swipt_enable: bool = Field(default=False,
+                                        description='default is false')
+    # 是否启动战斗时随机滑动
+    # random_swipe_enable: bool = Field(default=False,
+    #                                     description='default is false')
+

+ 187 - 0
tasks/GeneralBattle/general_battle.py

@@ -0,0 +1,187 @@
+# This Python file uses the following encoding: utf-8
+# @author runhey
+# github https://github.com/runhey
+import time
+import random
+
+from tasks.base_task import BaseTask
+from tasks.GeneralBattle.config_general_battle import GreenMarkType, GeneralBattleConfig
+from tasks.GeneralBattle.assets import GeneralBattleAssets
+from module.logger import logger
+
+
+
+class GeneralBattle(BaseTask, GeneralBattleAssets):
+    """
+    使用这个通用的战斗必须要求这个任务的config有config_general_battle
+    """
+
+    def run_general_battle(self, config: dict=None) -> bool:
+        """
+        运行脚本
+        :return:
+        """
+        if config is None:
+            config = GeneralBattleConfig().dict()
+
+        # if isinstance(config, GeneralBattle):
+        #     logger.error(f"config is not GeneralBattle type, config: {config}")
+        #     config = GeneralBattle().dict()
+
+        # 如果没有锁定队伍。那么可以根据配置设定队伍
+        if not config.lock_team_enable:
+            logger.info("lock team is not enable")
+            # 如果启动更换队伍
+            if config.preset_enable:
+                logger.info("preset is enable")
+                # 点击预设按钮
+                logger.info("click preset button")
+                while 1:
+                    self.screenshot()
+                    if self.appear_then_click(self.I_PRESET, threshold=0.8):
+                        continue
+                    if self.appear(self.I_PRESET_ENSURE):
+                        break
+                # 选择预设组
+                logger.info("select preset group")
+                x, y = None, None
+                match config.preset_group:
+                    case 1: x, y = self.C_PRESET_GROUP_1.coord()
+                    case 2: x, y = self.C_PRESET_GROUP_2.coord()
+                    case 3: x, y = self.C_PRESET_GROUP_3.coord()
+                    case 4: x, y = self.C_PRESET_GROUP_4.coord()
+                    case 5: x, y = self.C_PRESET_GROUP_5.coord()
+                    case 6: x, y = self.C_PRESET_GROUP_6.coord()
+                    case 7: x, y = self.C_PRESET_GROUP_7.coord()
+                    case _: x, y = self.C_PRESET_GROUP_1.coord()
+                self.device.click(x, y)
+
+                # 选择预设的队伍
+                logger.info("select preset team")
+                time.sleep(0.5)
+                match config.preset_team:
+                    case 1: x, y = self.C_PRESET_TEAM_1.coord()
+                    case 2: x, y = self.C_PRESET_TEAM_2.coord()
+                    case 3: x, y = self.C_PRESET_TEAM_3.coord()
+                    case 4: x, y = self.C_PRESET_TEAM_4.coord()
+                    case _: x, y = self.C_PRESET_TEAM_1.coord()
+                self.device.click(x, y)
+
+                # 点击预设确认
+                logger.info("click preset ensure")
+                while 1:
+                    self.screenshot()
+                    if self.appear_then_click(self.I_PRESET_ENSURE, threshold=0.8):
+                        continue
+                    if not self.appear(self.I_PRESET_ENSURE):
+                        break
+
+            # 点击buff按钮
+            if config.buff_enable:
+                logger.info("buff is enable")
+                logger.info("click buff button")
+                while 1:
+                    self.screenshot()
+                    if self.appear_then_click(self.I_BUFF, interval=1.5):
+                        continue
+                    if self.appear(self.I_BUFF_AWAKEN) or self.appear(self.I_BUFF_SOUL):
+                        break
+
+
+            # 点击准备按钮
+            self.wait_until_appear(self.I_PREPARE_HIGHLIGHT)
+            logger.info("click prepare button")
+            while 1:
+                self.screenshot()
+                if self.appear_then_click(self.I_PREPARE_HIGHLIGHT, interval=1.5):
+                    continue
+                if not self.appear(self.I_PRESET):
+                    break
+
+            # 照顾一下某些模拟器慢的
+            time.sleep(0.1)
+
+        # 绿标
+        if config.green_enable:
+            logger.info("green is enable")
+            x, y = None, None
+            match config.green_mark:
+                case GreenMarkType.GREEN_LEFT1: x, y = self.C_GREEN_LEFT_1.coord()
+                case GreenMarkType.GREEN_LEFT2: x, y = self.C_GREEN_LEFT_2.coord()
+                case GreenMarkType.GREEN_LEFT3: x, y = self.C_GREEN_LEFT_3.coord()
+                case GreenMarkType.GREEN_LEFT4: x, y = self.C_GREEN_LEFT_4.coord()
+                case GreenMarkType.GREEN_LEFT5: x, y = self.C_GREEN_LEFT_5.coord()
+                case GreenMarkType.GREEN_MAIN: x, y = self.C_GREEN_MAIN.coord()
+
+            # 判断有无坐标的偏移
+            self.appear_then_click(self.I_LOCAL)
+            time.sleep(0.3)
+            # 点击绿标
+            self.device.click(x, y)
+
+        # 战斗过程 随机点击和滑动 防封
+        logger.info("battle process")
+        win: bool = False
+        while 1:
+            self.screenshot()
+            # 如果出现赢 就点击
+            if self.appear(self.I_WIN, threshold=0.6):
+                logger.info("Battle result is win")
+                win = True
+                break
+
+            # 如果出现失败 就点击,返回False
+            if self.appear(self.I_FALSE, threshold=0.6):
+                logger.info("Battle result is false")
+                win = False
+                break
+
+            # 如果领奖励
+            if self.appear(self.I_REWARD, threshold=0.6):
+                win = True
+                break
+            # 如果开启战斗过程随机滑动
+            if config.random_click_swipt_enable:
+                time.sleep(0.4)  # 这样的好像不对
+                if 0 <= random.randint(0, 500) <= 3:  # 百分之4的概率
+                    rand_type = random.randint(0, 2)
+                    match rand_type:
+                        case 0:
+                            self.click(self.C_RANDOM_CLICK, interval=20)
+                        case 1:
+                            self.swipe(self.S_BATTLE_RANDOM_LEFT, interval=20)
+                        case 2:
+                            self.swipe(self.S_BATTLE_RANDOM_RIGHT, interval=20)
+
+        # 再次确认战斗结果
+        logger.info("reconfirm the results of the battle")
+        while 1:
+            self.screenshot()
+            if win:
+                # 点击赢了
+                if self.appear_then_click(self.I_WIN):
+                    continue
+                if not self.appear(self.I_WIN):
+                    break
+            else:
+                # 如果失败且 点击失败后
+                if self.appear_then_click(self.I_FALSE, threshold=0.6):
+                    continue
+                if not self.appear(self.I_FALSE, threshold=0.6):
+                    return False
+        # 最后保证能点击 获得奖励
+        self.wait_until_appear(self.I_REWARD)
+        logger.info("get reward")
+        while 1:
+            self.screenshot()
+            # 如果出现领奖励
+            if self.appear_then_click(self.I_REWARD, interval=1.5):
+                continue
+            if not self.appear(self.I_REWARD):
+                break
+
+        if win:
+            return True
+        else:
+            return False
+

+ 110 - 0
tasks/GeneralBattle/res/click.json

@@ -0,0 +1,110 @@
+[
+    {
+        "itemName": "preset_team_1",
+        "roiFront": "196,234,464,114",
+        "roiBack": "196,234,464,114",
+        "description": "预设队伍1"
+    },
+    {
+        "itemName": "preset_team_2",
+        "roiFront": "197,358,465,103",
+        "roiBack": "197,358,465,103",
+        "description": "预设队伍2"
+    },
+    {
+        "itemName": "preset_team_3",
+        "roiFront": "195,480,462,100",
+        "roiBack": "195,480,462,100",
+        "description": "预设队伍3"
+    },
+    {
+        "itemName": "preset_team_4",
+        "roiFront": "193,596,464,35",
+        "roiBack": "193,596,464,35",
+        "description": "预设队伍4"
+    },
+    {
+        "itemName": "preset_group_1",
+        "roiFront": "28,238,134,56",
+        "roiBack": "28,238,134,56",
+        "description": "预设组1"
+    },
+    {
+        "itemName": "preset_group_2",
+        "roiFront": "31,298,132,60",
+        "roiBack": "31,298,132,60",
+        "description": "预设组2"
+    },
+    {
+        "itemName": "preset_group_3",
+        "roiFront": "31,362,135,59",
+        "roiBack": "31,362,135,59",
+        "description": "预设组3"
+    },
+    {
+        "itemName": "preset_group_4",
+        "roiFront": "29,427,133,57",
+        "roiBack": "29,427,133,57",
+        "description": "预设组4"
+    },
+    {
+        "itemName": "preset_group_5",
+        "roiFront": "31,489,133,60",
+        "roiBack": "31,489,133,60",
+        "description": "预设组5"
+    },
+    {
+        "itemName": "preset_group_6",
+        "roiFront": "31,549,132,63",
+        "roiBack": "31,549,132,63",
+        "description": "预设组6"
+    },
+    {
+        "itemName": "preset_group_7",
+        "roiFront": "29,615,137,63",
+        "roiBack": "29,615,137,63",
+        "description": "预设组7"
+    },
+    {
+        "itemName": "green_left_1",
+        "roiFront": "128,433,90,150",
+        "roiBack": "128,433,90,150",
+        "description": "从左开始第一个绿标"
+    },
+    {
+        "itemName": "green_left_2",
+        "roiFront": "371,385,81,145",
+        "roiBack": "371,385,81,145",
+        "description": "从左开始第二个绿标"
+    },
+    {
+        "itemName": "green_left_3",
+        "roiFront": "586,328,100,76",
+        "roiBack": "586,328,100,76",
+        "description": "从左开始第三个绿标"
+    },
+    {
+        "itemName": "green_left_4",
+        "roiFront": "817,379,77,133",
+        "roiBack": "817,379,77,133",
+        "description": "从左开始第四个绿标"
+    },
+    {
+        "itemName": "green_left_5",
+        "roiFront": "1059,416,85,145",
+        "roiBack": "1059,416,85,145",
+        "description": "从左开始第五个绿标"
+    },
+    {
+        "itemName": "green_main",
+        "roiFront": "590,454,88,178",
+        "roiBack": "590,454,88,178",
+        "description": "绿标阴阳师"
+    },
+    {
+        "itemName": "random_click",
+        "roiFront": "104,79,1050,507",
+        "roiBack": "255,65,100,100",
+        "description": "战斗的时候有一定的概率随机点击"
+    }
+]

File diff suppressed because it is too large
+ 0 - 0
tasks/GeneralBattle/res/image.json


BIN
tasks/GeneralBattle/res/res_buff.png


BIN
tasks/GeneralBattle/res/res_buff_awaken.png


BIN
tasks/GeneralBattle/res/res_buff_exp_100.png


BIN
tasks/GeneralBattle/res/res_buff_exp_50.png


BIN
tasks/GeneralBattle/res/res_buff_gold_100.png


BIN
tasks/GeneralBattle/res/res_buff_gold_50.png


BIN
tasks/GeneralBattle/res/res_buff_soul.png


BIN
tasks/GeneralBattle/res/res_false.png


BIN
tasks/GeneralBattle/res/res_local.png


BIN
tasks/GeneralBattle/res/res_prepare_dark.png


BIN
tasks/GeneralBattle/res/res_prepare_highlight.png


BIN
tasks/GeneralBattle/res/res_preset.png


BIN
tasks/GeneralBattle/res/res_preset_ensure.png


BIN
tasks/GeneralBattle/res/res_reward.png


BIN
tasks/GeneralBattle/res/res_statistics.png


BIN
tasks/GeneralBattle/res/res_win.png


+ 16 - 0
tasks/GeneralBattle/res/swipe.json

@@ -0,0 +1,16 @@
+[
+    {
+        "itemName": "battle_random_left",
+        "roiFront": "122,155,480,426",
+        "roiBack": "667,147,461,427",
+        "mode": "default",
+        "description": "description"
+    },
+    {
+        "itemName": "battle_random_right",
+        "roiFront": "719,138,417,392",
+        "roiBack": "237,163,387,394",
+        "mode": "default",
+        "description": "description"
+    }
+]

+ 10 - 0
tasks/GlobalGame/assets.py

@@ -0,0 +1,10 @@
+from module.atom.image import RuleImage
+from module.atom.click import RuleClick
+from module.atom.long_click import RuleLongClick
+from module.atom.swipe import RuleSwipe
+
+# This file was automatically generated by module/dev_tools/assets_extract.py.
+# Don't modify it manually.
+class GlobalGameAssets: 
+	pass
+

+ 11 - 0
tasks/GlobalGame/config.py

@@ -0,0 +1,11 @@
+# This Python file uses the following encoding: utf-8
+# @author runhey
+# github https://github.com/runhey
+from pydantic import BaseModel, Field
+
+from tasks.GlobalGame.config_emergency import Emergency
+
+
+class GlobalGame(BaseModel):
+    emergency: Emergency = Field(default_factory=Emergency)
+

+ 10 - 0
tasks/GlobalGame/config_emergency.py

@@ -0,0 +1,10 @@
+# This Python file uses the following encoding: utf-8
+# @author runhey
+# github https://github.com/runhey
+from datetime import datetime, time
+from pydantic import BaseModel, ValidationError, validator, Field
+
+
+class Emergency(BaseModel):
+    accept_friend_invitation: bool = Field(default=True,
+                                           description="default is true")

+ 10 - 0
tasks/GoldYoukai/assets.py

@@ -0,0 +1,10 @@
+from module.atom.image import RuleImage
+from module.atom.click import RuleClick
+from module.atom.long_click import RuleLongClick
+from module.atom.swipe import RuleSwipe
+
+# This file was automatically generated by module/dev_tools/assets_extract.py.
+# Don't modify it manually.
+class GoldYoukaiAssets: 
+	pass
+

+ 10 - 0
tasks/GoldYoukai/config.py

@@ -0,0 +1,10 @@
+# This Python file uses the following encoding: utf-8
+# @author runhey
+# github https://github.com/runhey
+from pydantic import BaseModel, Field
+
+from tasks.GoldYoukai.config_scheduler import Scheduler
+
+
+class GoldYoukai(BaseModel):
+    scheduler: Scheduler = Field(default_factory=Scheduler)

Some files were not shown because too many files changed in this diff