Просмотр исходного кода

feat(gui): gui can parse args from python

runhey 3 лет назад
Родитель
Сommit
ccb200e143

+ 1 - 1
module/config/config.py

@@ -48,7 +48,7 @@ class Config(ConfigState, ConfigManual, ConfigWatcher, ConfigMenu):
         获取给gui显示的参数
         :return:
         """
-        return self.model.gui_task(task=task)
+        return self.model.gui_args(task=task)
 
     def get_arg(self, task: str, group: str, argument: str):
         """

+ 1 - 1
module/config/config_menu.py

@@ -17,7 +17,7 @@ class ConfigMenu:
         # 脚本设置
         self.menu['Script'] = ['Script', 'General', 'Restart']
         # 日常的任务
-        self.menu["DailyTask"] = ['TerritorialDemon', 'CoinChallenge']
+        self.menu["Daily Task"] = ['Territorial Demon', 'Coin Challenge']
 
     @cached_property
     def gui_menu(self) -> str:

+ 14 - 1
module/config/config_model.py

@@ -58,7 +58,7 @@ class ConfigModel(BaseModel):
         filepath = Path.cwd() / "config" / f"{config_name}.json"
         write_file(filepath, data)
 
-    def gui_task(self, task: str) -> str:
+    def gui_args(self, task: str) -> str:
         """
         返回提供给gui显示的参数
         :param task: 输入的是任务的名称英文 如'Script' 或者是'script'都是可以的
@@ -71,6 +71,19 @@ class ConfigModel(BaseModel):
             return ''
         return task_gui.schema_json()
 
+    def gui_task(self, task: str) -> str:
+        """
+        返回提供给gui显示的参数
+        :param task:
+        :return:
+        """
+        task_name = convert_to_underscore(task)
+        task = getattr(self, task_name, None)
+        if task is None:
+            logger.error(f'{task_name} is no inexistence')
+            return ''
+        return task.json()
+
 if __name__ == "__main__":
     try:
         c = ConfigModel("oas3")

BIN
module/config/i18n/zh_CN.qm


+ 1 - 1
module/config/i18n/zh_CN.ts

@@ -93,7 +93,7 @@
     </message>
 </context>
 <context>
-    <name>SplitPanel</name>
+    <name>FluTreeView</name>
     <message>
         <source>Home</source>
         <translation>主页</translation>

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

@@ -166,3 +166,16 @@ class ProcessManager(QObject):
             logger.info(f'script {config} is not running')
             return None
 
+    @Slot(str, str, result="QString")
+    def gui_task(self, config: str, task: str) -> str:
+        """
+        获取显示task的gui
+        :param config:
+        :param task:
+        :return:
+        """
+        if config in self.clients:
+            return self.clients[config].gui_task(task)
+        else:
+            logger.info(f'script {config} is not running')
+            return None

+ 1 - 0
module/gui/qml.qrc

@@ -22,5 +22,6 @@
         <file>qml/Page/Update.qml</file>
         <file>qml/Component/Args.qml</file>
         <file>qml/Component/Taskmini.qml</file>
+        <file>qml/Component/ModelParse.js</file>
     </qresource>
 </RCC>

+ 141 - 0
module/gui/qml/Component/Args.qml

@@ -1,8 +1,149 @@
 import QtQuick
+import QtQuick.Controls
 import FluentUI
+import "./ModelParse.js" as MP
 
 Item {
+    property string argsData: ""
+    property string valueData: ""
+    signal updataData
+
     FluText{
         text: 'this args '
     }
+    FluScrollablePage{
+        id: contentScrollable
+        width: 700
+        height: parent.height
+        anchors.horizontalCenter: parent.horizontalCenter
+    }
+
+    Component{
+        id: group_item
+        property string groupName: ""
+        property string groupTitle: ""
+        property var argumentValue: {""}
+        FluExpander{
+            headerText: group_item.groupTitle
+            width: contentScrollable.width
+            Column{
+                id: group_column
+                anchors.fill: parent
+                spacing: 4
+
+                FluTextBox{
+                    placeholderText:"单行输入框"
+                }
+
+                FluTextBox{
+                    placeholderText:"单行输入框"
+                }
+
+                FluTextBox{
+                    placeholderText:"单行输入框"
+                }
+
+            }
+        }
+
+    }
+
+//    Component{
+//        id: string_item
+//        property var modelData: {""}
+
+//        Item{
+//            width: contentScrollable.width
+//            FluTextBox{
+//                id: string_text
+//                anchors{
+//                    top: parent.top
+//                    right: parent.right
+//                }
+//                placeholderText: modelData.default
+//            }
+
+//            FluText{
+//                id: string_title
+//                anchors{
+//                    top: parent.top
+//                    left: parent.left
+//                    right: string_text.left
+//                }
+//                text: modelData.title
+//                font: FluTextStyle.BodyStrong
+//                wrapMode: Text.WrapAnywhere
+//                padding: 6
+//            }
+//            FluText{
+//                id: string_description
+//                anchors{
+//                    top: string_title.bottom
+//                }
+//                width: string_title.width
+//                text: modelData.description
+//                font: FluTextStyle.Caption
+//                wrapMode: Text.WrapAnywhere
+//                padding: 6
+//            }
+//        }
+//    }
+//    Component{
+//        id: int_item
+//    }
+//    Component{
+//        id: float_item
+//    }
+//    Component{
+//        id: bool_item
+//    }
+//    Compoenent{
+//        id: enum_item
+//    }
+
+    onArgsDataChanged: {
+
+    }
+    onValueDataChanged: {
+
+    }
+    onUpdataData: {
+        if(argsData === ""){
+            console.error("解析 顺序出问题了")
+            return
+        }
+        if(valueData === ""){
+            console.debug("没有数据")
+        }
+
+        var args = JSON.parse(argsData)
+        var values = JSON.parse(valueData)
+        var group = MP.parseGroup(args["properties"])
+        var groups = MP.parseGroups(args["properties"])
+
+        for(let task in group){
+            var argument = MP.parseArgument(args.definitions, group[task])
+            const groupLetter = groups[group[task]]
+            var argumentVuale = MP.mergeArgument(argument, values[groupLetter])
+            console.debug(JSON.stringify( argumentVuale ))
+            console.debug("---------------------------------------------------------------")
+//            createGroup(groupLetter, group[task], argumentVuale)
+        }
+    }
+
+    /**
+     * 创建某个组 的显示组件并显示
+     * @param {Object} groupName 变量的名字 是小写的
+     * @param {Object} groupTitle 用于向用户显示的名字 大写的
+     * @param {Object} argumentVaule 总的显示的参数
+     * @returns {Object}
+     */
+//    function createGroup(groupName, groupTitle, argumentValue){
+//        var object = group_item.createObject(contentScrollable)
+//        if(object !== null){
+//            object.groupName = groupName
+//            object.groupTitle = groupTitle
+//            object.argumentVale = argumentValue
+//        }
+//    }
 }

+ 133 - 0
module/gui/qml/Component/ModelParse.js

@@ -0,0 +1,133 @@
+.pragma library
+
+
+//
+//*****************************请注意下面的函数只适用与pydantic生成的task的参数
+//
+
+/**
+ * 解析出group的数组,
+ * @param {Object} data.properties
+ * @returns {Array} 类似这样:[Device,Error,Optimization]
+ */
+function parseGroup(properties) {
+    var result = []
+    for(const key in properties){
+        if(!('$ref' in properties[key])){
+            continue
+        }
+        const value = properties[key]['$ref'];
+        const lastPart = value.substring(value.lastIndexOf('/') + 1);
+        result.push(lastPart)
+    }
+    return result
+}
+
+/**
+ * 解析出group一一对应的的数组,
+ * @param {Object} data.properties
+ * @returns {Object} 类似这样:{"Device":"device", "Error":"error", "Optimization":"optimization"}
+ */
+function parseGroups(properties) {
+    var result = {}
+    for(const key in properties){
+        if(!('$ref' in properties[key])){
+            continue
+        }
+        const value = properties[key]['$ref'];
+        const lastPart = value.substring(value.lastIndexOf('/') + 1);
+        result[lastPart] = key
+    }
+    return result
+}
+
+
+/**
+ * 解析ref的最后一个Name
+ * @param {String} ref
+ * @returns {String}
+ */
+function parseRef(ref){
+    return ref.substring(ref.lastIndexOf('/') + 1)
+}
+
+
+/**
+ * 解析出某个group的参数组,
+ * @param {Object} definitions
+ * @param {string} group
+ * @returns {Array} -
+ */
+function parseArgument(definitions, group){
+    if(!(group in definitions)){
+        return null
+    }
+    var result = []
+    var pro = definitions[group]["properties"]
+    for(const key in pro){
+        var arg = {}
+        var argName = pro[key]
+
+        arg["name"] = key
+
+        if("title" in argName){
+            arg["title"] = argName.title
+        }else{
+
+        }
+
+        //如果有allOf表示这个配置字段是一个枚举的, 一般枚举的就是string
+        if("allOf" in argName){
+            const ref = argName.allOf[0]["$ref"]
+            arg["title"] = parseRef(ref)
+            arg["type"] = "enum"
+        }
+
+        if("description" in argName){
+            arg["description"] = argName.description
+        }else{
+            // 没有帮助就没有帮助
+        }
+
+        if("default" in argName){
+            arg["default"] = argName["default"]
+        }else{
+            console.error(arg["title"], 'have not default')
+        }
+
+        if("type" in argName){
+            arg["type"] = argName.type
+        }
+
+        if(arg["type"] === "enum"){
+            arg["options"] = definitions[arg.title]["enum"]
+        }
+
+        result.push(arg)
+
+    }
+    return result
+}
+
+/**
+ * 合并某个group的参数组,
+ * @param {Object} argument
+ * @param {Object} values
+ * @returns {Object} - 就是添加了value这个一个值
+ */
+function mergeArgument(argument, values){
+//    for(let arg in argument){
+//        for(let vname in values){
+//            if(arg.name === vname){
+//                arg["value"] = values[vname]
+//            }
+//        }
+//    }
+    for(let key in argument){
+        const name = argument[key].name
+        if(name in values){
+            argument[key]["value"] = values[name]
+        }
+    }
+    return argument
+}

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

@@ -14,7 +14,7 @@ Item{
         FluText{
             id: menuName
             Layout.alignment: Qt.AlignVCenter
-            text: MainEvent.menuTitle
+            text: qsTr(MainEvent.menuTitle)
             font: FluTextStyle.BodyStrong
         }
         RunStatusIcon{

+ 10 - 4
module/gui/qml/Component/SplitPanel.qml

@@ -53,16 +53,16 @@ Item {
         var datas = []
         for(var items in data){
             if(items.length === 0){
-                datas.push(menu_tree.createItem(qsTr(items),false))
+                datas.push(menu_tree.createItem(items,false))
             }else{
                 var da = []
                 for(var item in data[items]){
                     if (typeof data[items][item] !== "string") {
                       continue
                     }
-                    da.push(menu_tree.createItem(qsTr(data[items][item]), false))
+                    da.push(menu_tree.createItem(data[items][item], false))
                 }
-                datas.push(menu_tree.createItem(qsTr(items), true, da))
+                datas.push(menu_tree.createItem(items, true, da))
             }
         }
         menu_tree.updateData(datas)
@@ -96,10 +96,16 @@ Item {
 //    function getDefalut(){
 //        return contentDefalut.item
 //    }
-//    //方便更改属性
+    //方便更改属性
 //    function getDefalut(){
 //        return contentLoader.item
 //    }
+    //设置右边显示的参数项,输入的序列的字符串
+    function setLoaderData(args, value){
+        contentLoader.item.argsData = args
+        contentLoader.item.valueData = value
+        contentLoader.item.updataData()
+    }
 
 
 }

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

@@ -9,13 +9,16 @@ SplitPanel{
     property string configName: ""
 
     onTitleChanged: {
-        if(title === qsTr("Overview")){
+        if(title === "Overview"){
             showDefalut()
         }
         else{
             var component = Qt.createComponent("../../qml/Component/Args.qml")
             if (component.status === Component.Ready) {
                 setLoader(component)
+                var args = process_manager.gui_args(configName, title)
+                var value = process_manager.gui_task(configName, title)
+                setLoaderData(args, value)
             }else{
                 // 组件加载失败
             }

+ 7 - 0
script.py

@@ -75,4 +75,11 @@ class Script:
         """
         return self.config.gui_menu
 
+    def gui_task(self, task: str) -> str:
+        """
+        获取给gui显示的任务 的参数的具体值
+        :return:
+        """
+        return self.config.model.gui_task(task=task)
+