ソースを参照

feat(gui): show log

runhey 3 年 前
親
コミット
b3709aaf4f

+ 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
+    }
+  }
+}

+ 4 - 1
module/config/config_model.py

@@ -54,11 +54,14 @@ class ConfigModel(BaseModel):
     #     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)

+ 10 - 4
module/dev_tools/assets_extract.py

@@ -259,19 +259,25 @@ 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()
 
 

+ 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())

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

@@ -9,10 +9,15 @@ import msgpack
 import numpy as np
 import numpy as np
 import io
 import io
 
 
-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.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
@@ -44,16 +49,26 @@ class ProcessManager(QObject):
     """
     """
     进程管理
     进程管理
     """
     """
+    log_signal = 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()  # 启动更新线程
+
     @Slot()
     @Slot()
     def create_all(self) -> None:
     def create_all(self) -> None:
         """
         """
@@ -64,18 +79,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 +128,35 @@ 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():
+                self.processes[config].start()
+                logger.info(f'restart script {config}')
+                return None
+
+            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 +322,88 @@ 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
+
+        console = Console()
+        # while self.processes[config_name].is_alive():
+        while True:
+            try:
+                log = q.get(timeout=1)
+                if log is None:
+                    continue
+                self.log_signal.emit(config_name, str(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
+                logger.info(f'Update thread get')
+
+            except Empty:
+                continue
+            except Exception as e:
+                logger.error(f'Update thread error: {e}')
+                break
+
+
+
+

+ 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}')
+

+ 77 - 2
module/gui/qml/Component/Overview.qml

@@ -1,9 +1,11 @@
 import QtQuick
 import QtQuick
+import QtQuick.Controls
 import QtQuick.Layouts
 import QtQuick.Layouts
 import FluentUI
 import FluentUI
 
 
 Item {
 Item {
-
+    id: root
+    property string configName: ""
 
 
 
 
     Item{
     Item{
@@ -27,16 +29,29 @@ 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)
+                        textLog.text = ""
+                    }
+                }
                 FluToggleButton{
                 FluToggleButton{
                     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"
+                            textLog.text = ""
                         }else{
                         }else{
                             text = "Stop"
                             text = "Stop"
+
                         }
                         }
                     }
                     }
                 }
                 }
@@ -137,10 +152,70 @@ Item {
             }
             }
         }
         }
     }
     }
+
+    FluArea{
+        id: logHeader
+        anchors.top: parent.top
+        anchors.left: leftScheduler.right
+        anchors.leftMargin: 10
+        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
+            }
+            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{
     FluArea{
+        anchors.top: logHeader.bottom
+        anchors.topMargin: 10
+        anchors.bottom: parent.bottom
         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
+        FluScrollablePage{
+            anchors.fill: parent
+        FluText{
+            id: textLog
+            width: parent.width
+            padding: 10
+            clip: true
+            wrapMode: Text.WordWrap // 设置自动换行模式
+            text: ""
+
+            function add_log(config, log){
+                if(config !== root.configName){
+                    return
+                }
+                textLog.text += log
+            }
+
+            Component.onCompleted:{
+                process_manager.log_signal.connect(textLog.add_log)
+            }
+
+
+        }}
     }
     }
+
 }
 }

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

@@ -113,5 +113,10 @@ Item {
         contentLoader.item.taskName = taskName
         contentLoader.item.taskName = taskName
     }
     }
 
 
+    //设置配置的名称
+    function setDefalutConfig(name){
+        contentDefalut.item.configName = name
+    }
+
 
 
 }
 }

+ 1 - 1
module/gui/qml/Global/MainEvent.qml

@@ -27,7 +27,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) {

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

@@ -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('组件!加载失败')

+ 67 - 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,22 @@ 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 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 +61,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 +84,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 +94,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 +159,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 +217,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 +269,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 = RichFileHandler(
+        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 +400,4 @@ logger.log_file: str
 
 
 logger.set_file_logger()
 logger.set_file_logger()
 logger.hr('Start', level=0)
 logger.hr('Start', level=0)
+

+ 6 - 0
script.py

@@ -11,6 +11,7 @@ import time
 import os
 import os
 import inflection
 import inflection
 
 
+from typing import Callable
 from datetime import datetime, timedelta
 from datetime import datetime, timedelta
 from pathlib import Path
 from pathlib import Path
 from cached_property import cached_property
 from cached_property import cached_property
@@ -30,6 +31,7 @@ class Script:
     def __init__(self, config_name: str ='oas') -> None:
     def __init__(self, config_name: str ='oas') -> None:
         logger.hr('Start', level=0)
         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
         # Skip first restart
         self.is_first_task = True
         self.is_first_task = True
@@ -63,6 +65,8 @@ class Script:
             logger.exception(e)
             logger.exception(e)
             exit(1)
             exit(1)
 
 
+
+
     @cached_property
     @cached_property
     def checker(self):
     def checker(self):
         """
         """
@@ -119,6 +123,8 @@ class Script:
         启动zerorpc服务
         启动zerorpc服务
         :return:
         :return:
         """
         """
+        if self.gui_update_task:
+            self.gui_update_task("yyyy")
         self.server.run()
         self.server.run()
 
 
     def gui_args(self, task: str) -> str:
     def gui_args(self, task: str) -> str:

+ 1 - 1
tasks/DemonEncounter/assets.py

@@ -6,5 +6,5 @@ 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 DemonEncounterAssets: 
 class DemonEncounterAssets: 
-
+	pass
 
 

+ 1 - 1
tasks/EternitySea/assets.py

@@ -6,5 +6,5 @@ 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 EternitySeaAssets: 
 class EternitySeaAssets: 
-
+	pass
 
 

+ 1 - 1
tasks/ExperienceYoukai/assets.py

@@ -6,5 +6,5 @@ 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 ExperienceYoukaiAssets: 
 class ExperienceYoukaiAssets: 
-
+	pass
 
 

+ 1 - 1
tasks/FallenSun/assets.py

@@ -6,5 +6,5 @@ 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 FallenSunAssets: 
 class FallenSunAssets: 
-
+	pass
 
 

+ 1 - 1
tasks/General/assets.py

@@ -6,5 +6,5 @@ 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 GeneralAssets: 
 class GeneralAssets: 
-
+	pass
 
 

+ 1 - 1
tasks/GlobalGame/assets.py

@@ -6,5 +6,5 @@ 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 GlobalGameAssets: 
 class GlobalGameAssets: 
-
+	pass
 
 

+ 1 - 1
tasks/GoldYoukai/assets.py

@@ -6,5 +6,5 @@ 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 GoldYoukaiAssets: 
 class GoldYoukaiAssets: 
-
+	pass
 
 

+ 1 - 1
tasks/Hunt/assets.py

@@ -6,5 +6,5 @@ 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 HuntAssets: 
 class HuntAssets: 
-
+	pass
 
 

+ 1 - 1
tasks/Nian/assets.py

@@ -6,5 +6,5 @@ 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 NianAssets: 
 class NianAssets: 
-
+	pass
 
 

+ 1 - 1
tasks/Orochi/assets.py

@@ -6,5 +6,5 @@ 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 OrochiAssets: 
 class OrochiAssets: 
-
+	pass
 
 

+ 1 - 1
tasks/OrochiJudgement/assets.py

@@ -6,5 +6,5 @@ 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 OrochiJudgementAssets: 
 class OrochiJudgementAssets: 
-
+	pass
 
 

+ 1 - 1
tasks/OrochiMoans/assets.py

@@ -6,5 +6,5 @@ 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 OrochiMoansAssets: 
 class OrochiMoansAssets: 
-
+	pass
 
 

+ 1 - 1
tasks/RealmRaid/assets.py

@@ -6,5 +6,5 @@ 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 RealmRaidAssets: 
 class RealmRaidAssets: 
-
+	pass
 
 

+ 1 - 1
tasks/Restart/assets.py

@@ -6,5 +6,5 @@ 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 RestartAssets: 
 class RestartAssets: 
-
+	pass
 
 

+ 1 - 1
tasks/Script/assets.py

@@ -6,5 +6,5 @@ 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 ScriptAssets: 
 class ScriptAssets: 
-
+	pass
 
 

+ 1 - 1
tasks/Script/config_device.py

@@ -27,7 +27,7 @@ class ControlMethod(str, Enum):
 
 
 
 
 class Device(BaseModel):
 class Device(BaseModel):
-    serial: str = Field(default="127.0.0.1:7555",
+    serial: str = Field(default="auto",
                         description='Common emulator Serial can be queried in the list belowUse "auto" to auto-detect emulators, but if multiple emulators are running or use emulators that do not support auto-detect, "auto" cannot be used and serial must be filled in manually')
                         description='Common emulator Serial can be queried in the list belowUse "auto" to auto-detect emulators, but if multiple emulators are running or use emulators that do not support auto-detect, "auto" cannot be used and serial must be filled in manually')
     handle: str = Field(default='auto',
     handle: str = Field(default='auto',
                         description='you can use auto or your emulator title')
                         description='you can use auto or your emulator title')

+ 1 - 1
tasks/Sougenbi/assets.py

@@ -6,5 +6,5 @@ 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 SougenbiAssets: 
 class SougenbiAssets: 
-
+	pass