Przeglądaj źródła

feat(gui): can make changes from the gui and save parameters automatically

runhey 3 lat temu
rodzic
commit
6f543d9642

+ 29 - 43
config/template.json

@@ -1,47 +1,33 @@
 {
-    "Script":{
-        "Device":{
-            "Serial": "127.0.0.1:7555",
-            "Handle":"auto",
-            "PackageName":"auto",
-            "ScreenshotMethod": "ADB",
-            "ControlMethod": "minitouch",
-            "AdbRestart": false
-        },
-        "Error": {
-            "HandleError": true,
-            "SaveError": true,
-            "ScreenshotLength": 1
-          },
-        "Optimization": {
-              "ScreenshotInterval": 0.3,
-              "CombatScreenshotInterval": 1.0,
-              "TaskHoardingDuration": 0,
-              "WhenTaskQueueEmpty": "goto_home"
-    	}
+  "script": {
+    "device": {
+      "serial": "127.0.0.1:7555",
+      "handle": "auto",
+      "package_name": "auto",
+      "screenshot_method": "window_background",
+      "control_method": "window_message",
+      "adb_restart": false
     },
-    "General": {
-        "Retirement": {
-          "Enable": true,
-          "RetireMode": "one_click_retire",
-          "RetireAmount": "retire_all",
-          "EnhanceFavourite": false,
-          "EnhanceFilter": null,
-          "EnhanceCheckPerCategory": 2,
-          "OldRetireN": true,
-          "OldRetireR": true,
-          "OldRetireSR": false,
-          "OldRetireSSR": false
-        }
-      },
-    "Restart": {
-        "Scheduler": {
-            "Enable": false,
-            "NextRun": "2021-01-01 00:00:00",
-            "Command": "Restart",
-            "SuccessInterval": 0,
-            "FailureInterval": 0,
-            "ServerUpdate": "00:00"
-        }
+    "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",
+      "command": "Restart",
+      "success_interval": 0,
+      "failure_interval": 0,
+      "server_update": "00:00"
     }
+  }
 }

+ 7 - 0
module/config/config.py

@@ -77,6 +77,13 @@ class Config(ConfigState, ConfigManual, ConfigWatcher, ConfigMenu):
         except:
             logger.exception(f'have no arg {task}.{group}.{argument}')
 
+    def save(self) -> None:
+        """
+        保存配置文件
+        :return:
+        """
+        self.model.write_json(self.config_name, self.model.dict())
+
 if __name__ == '__main__':
     config = Config(config_name='pydantic')
     print(config.menu)

+ 37 - 4
module/config/config_model.py

@@ -4,7 +4,7 @@
 import json
 
 from pathlib import Path
-from pydantic import BaseModel, ValidationError, validator, Field
+from pydantic import BaseModel, ValidationError, validator, Field, root_validator
 
 from module.config.utils import *
 from module.logger import logger
@@ -19,6 +19,7 @@ from module.tasks.Restart.config import Restart
 
 
 class ConfigModel(BaseModel):
+    config_name: str = "oas"
     script: Script = Field(default_factory=Script)
     restart: Restart = Field(default_factory=Restart)
 
@@ -33,8 +34,20 @@ class ConfigModel(BaseModel):
         :param config_name:
         """
         data = self.read_json(config_name)
+        data["config_name"] = config_name
         super().__init__(**data)
 
+    def __setattr__(self, key, value):
+        """
+        只要修改属性就会触发这个函数 自动保存
+        :param key:
+        :param value:
+        :return:
+        """
+        super().__setattr__(key, value)
+        logger.info("auto save config")
+        self.save()
+
 
 
     @staticmethod
@@ -84,11 +97,31 @@ class ConfigModel(BaseModel):
             return ''
         return task.json()
 
+    def save(self) -> None:
+        """
+
+        :return:
+        """
+        self.write_json(self.config_name, self.dict())
+
+
+    # @root_validator
+    # def on_on_property_change(cls, values):
+    #     """
+    #     当属性改变时保存
+    #     :param values:
+    #     :return:
+    #     """
+    #     logger.info(f'property change auto save')
+    #     cls.save()
+
+
 if __name__ == "__main__":
     try:
-        c = ConfigModel("oas3")
+        c = ConfigModel("oas1")
     except ValidationError as e:
         print(e)
         c = ConfigModel()
-    print(c.json())
-    # c.write_json('pydantic', c.schema())
+    # c.write_json('oas1', c.dict())
+    # c.write_json('oas1', c.schema())
+    c.script.device.serial = "5555"

+ 64 - 0
module/gui/context/process_manager.py

@@ -5,6 +5,7 @@ import socket
 import random
 import zerorpc
 
+from typing import Union, Any
 from PySide6.QtCore import QObject, Slot, Signal
 
 from module.gui.process.script_process import ScriptProcess
@@ -182,3 +183,66 @@ class ProcessManager(QObject):
         else:
             logger.info(f'script {config} is not running')
             return None
+
+    @Slot(str, str, str, str, str, result="bool")
+    def gui_set_task(self, config: str, task: str, group: str, arg: str, value) -> bool:
+        """
+        设置task的gui   是string类型的
+        :param config:
+        :param task:
+        :param group:
+        :param arg:
+        :param value:
+        :return:
+        """
+        if config in self.clients:
+            logger.info(f'gui set value of {config} {task}')
+            if self.clients[config].gui_set_task(task, group, arg, value):
+                return True
+            else:
+                return False
+        else:
+            logger.info(f'script {config} is not running')
+            return False
+
+    @Slot(str, str, str, str, bool, result="bool")
+    def gui_set_task_bool(self, config: str, task: str, group: str, arg: str, value: bool) -> bool:
+        """
+        设置task的gui   是bool类型的
+        :param config:
+        :param task:
+        :param group:
+        :param arg:
+        :param value:
+        :return:
+        """
+        if config in self.clients:
+            logger.info(f'gui set value of {config} {task}')
+            if self.clients[config].gui_set_task(task, group, arg, value):
+                return True
+            else:
+                return False
+        else:
+            logger.info(f'script {config} is not running')
+            return False
+
+    @Slot(str, str, str, str, float, result="bool")
+    def gui_set_task_number(self, config: str, task: str, group: str, arg: str, value) -> bool:
+        """
+        设置task的gui   是float类型的或者是int
+        :param config:
+        :param task:
+        :param group:
+        :param arg:
+        :param value:
+        :return:
+        """
+        if config in self.clients:
+            logger.info(f'gui set value of {config} {task}')
+            if self.clients[config].gui_set_task(task, group, arg, value):
+                return True
+            else:
+                return False
+        else:
+            logger.info(f'script {config} is not running')
+            return False

+ 67 - 5
module/gui/qml/Component/Args.qml

@@ -7,6 +7,9 @@ import "./ModelParse.js" as MP
 Item {
     property string argsData: ""
     property string valueData: ""
+    // 存入 配置名和 任务名两个 上下文
+    property string configName: ""
+    property string taskName: ""
     signal updataData
     FluScrollablePage{
         id: contentScrollable
@@ -23,6 +26,7 @@ Item {
             property string groupName: ""
             property string groupTitle: ""
             property var argumentValue: {""}
+            expand: true
             headerText: qsTr(groupTitle) +" "+ qsTr("Setting")
             width: contentScrollable.width
             contentHeight: group_column.height
@@ -130,6 +134,11 @@ Item {
                     right: parent.right
                 }
                 placeholderText: ""
+                onEditingFinished: {
+                    if(set_task(stringItem.parent.parent.parent.groupName, modelData.name, text)){
+                        showSuccess( qsTr("Successful setting"))
+                    }
+                }
             }
 
             FluText{
@@ -144,7 +153,7 @@ Item {
                 wrapMode: Text.WrapAnywhere
                 topPadding: 6
             }
-            FluText{
+            FluCopyableText{
                 id: string_description
                 anchors{
                     top: string_title.bottom
@@ -187,7 +196,13 @@ Item {
                     topMargin: 2
                     right: parent.right
                 }
+                validator: IntValidator {}
                 placeholderText: ""
+                onEditingFinished: {
+                    if(set_task(itemArg.parent.parent.parent.groupName, modelData.name, parseInt(text))){
+                        showSuccess( qsTr("Successful setting"))
+                    }
+                }
             }
 
             FluText{
@@ -202,7 +217,7 @@ Item {
                 wrapMode: Text.WrapAnywhere
                 topPadding: 6
             }
-            FluText{
+            FluCopyableText{
                 id: itemArg_description
                 anchors{
                     top: itemArg_title.bottom
@@ -245,7 +260,13 @@ Item {
                     topMargin: 2
                     right: parent.right
                 }
+                validator: DoubleValidator {}
                 placeholderText: ""
+                onEditingFinished: {
+                    if(set_task(itemArg.parent.parent.parent.groupName, modelData.name, parseFloat(text))){
+                        showSuccess( qsTr("Successful setting"))
+                    }
+                }
             }
 
             FluText{
@@ -260,7 +281,7 @@ Item {
                 wrapMode: Text.WrapAnywhere
                 topPadding: 6
             }
-            FluText{
+            FluCopyableText{
                 id: itemArg_description
                 anchors{
                     top: itemArg_title.bottom
@@ -305,6 +326,12 @@ Item {
                     rightMargin: 300 - 24
                 }
                 selected: true
+                clickFunc: function click_func(){
+                    selected = !selected
+                    if(set_task(itemArg.parent.parent.parent.groupName, modelData.name, selected)){
+                        showSuccess( qsTr("Successful setting"))
+                    }
+                }
             }
 
             FluText{
@@ -319,7 +346,7 @@ Item {
                 wrapMode: Text.WrapAnywhere
                 topPadding: 6
             }
-            FluText{
+            FluCopyableText{
                 id: itemArg_description
                 anchors{
                     top: itemArg_title.bottom
@@ -363,6 +390,11 @@ Item {
                     right: parent.right
                 }
                 model: ["0", "1", "2"]
+                onActivated: {
+                    if(set_task(itemArg.parent.parent.parent.groupName, modelData.name, currentText)){
+                        showSuccess( qsTr("Successful setting"))
+                    }
+                }
             }
 
             FluText{
@@ -377,7 +409,7 @@ Item {
                 wrapMode: Text.WrapAnywhere
                 topPadding: 6
             }
-            FluText{
+            FluCopyableText{
                 id: itemArg_description
                 anchors{
                     top: itemArg_title.bottom
@@ -466,5 +498,35 @@ Item {
         }
     }
 
+    function set_task(group, arg, value){
+        //如果是字符串
+        if( typeof value == "string" ){
+        if(process_manager.gui_set_task(configName, taskName, group, arg, value)){
+            return true
+        }
+        else{
+            return false
+        }}
+
+        //如果是整形的
+        else if(typeof value == "number"){
+        if(process_manager.gui_set_task_number(configName, taskName, group, arg, value)){
+            return true
+        }
+        else{
+            return false
+        }}
 
+
+        //如果是bool的
+        else if(typeof value == "boolean"){
+        if(process_manager.gui_set_task_bool(configName, taskName, group, arg, value)){
+            return true
+        }
+        else{
+            return false
+        }}
+
+
+    }
 }

+ 6 - 0
module/gui/qml/Component/SplitPanel.qml

@@ -107,5 +107,11 @@ Item {
         contentLoader.item.updataData()
     }
 
+    //设置上下文
+    function setLoaderContext(configName, taskName){
+        contentLoader.item.configName = configName
+        contentLoader.item.taskName = taskName
+    }
+
 
 }

+ 1 - 0
module/gui/qml/Page/ScriptView.qml

@@ -19,6 +19,7 @@ SplitPanel{
                 var args = process_manager.gui_args(configName, title)
                 var value = process_manager.gui_task(configName, title)
                 setLoaderData(args, value)
+                setLoaderContext(configName, title)
             }else{
                 // 组件加载失败
             }

+ 35 - 0
script.py

@@ -5,7 +5,9 @@ import zerorpc
 import zmq
 import random
 from cached_property import cached_property
+from pydantic import BaseModel, ValidationError
 
+from module.config.utils import convert_to_underscore
 from module.logger import logger
 from module.exception import *
 
@@ -82,4 +84,37 @@ class Script:
         """
         return self.config.model.gui_task(task=task)
 
+    def gui_set_task(self, task: str, group: str, argument: str, value) -> bool:
+        """
+        设置给gui显示的任务 的参数的具体值
+        :return:
+        """
+        task = convert_to_underscore(task)
+        group = convert_to_underscore(group)
+        argument = convert_to_underscore(argument)
+
+        path = f'{task}.{group}.{argument}'
+        task_object = getattr(self.config.model, task, None)
+        group_object = getattr(task_object, group, None)
+        argument_object = getattr(group_object, argument, None)
+
+        if argument_object is None:
+            logger.error(f'gui_set_task {task}.{group}.{argument}.{value} failed')
+            return False
+
+        try:
+            setattr(group_object, argument, value)
+            argument_object = getattr(group_object, argument, None)
+            logger.info(f'gui_set_task {task}.{group}.{argument}.{argument_object}')
+            self.config.save()  # 我是没有想到什么方法可以使得属性改变自动保存的
+            return True
+        except ValidationError as e:
+            logger.error(e)
+            return False
+
 
+if __name__ == "__main__":
+    script = Script("oas1")
+    print(script.config.model.json())
+    script.gui_set_task("Script", "device", "serial", "175")
+    print(script.config.script.device.serial)