Compare commits

...

46 commits
V0.2 ... main

Author SHA1 Message Date
06fab427aa 界面优化
1.启动程序界面字体对齐
2.编辑实例名称时保持行高和实例名称位置不变
3.修改实例名称输入框添加可清除选项
4.打开配置路径按钮移到右侧按钮处
2025-03-22 20:39:56 +08:00
e3c2627fc5 发布v0.7.1版本 2025-03-10 01:00:49 +08:00
e4b93b94b1 新增功能:启动实例后自动打开网页面板 2025-03-10 00:59:58 +08:00
6e235a28c1 功能修复:更新源码时没有指定为远程分支 2025-03-10 00:04:46 +08:00
e3457c1081 发布v0.7.0版本 2025-03-09 22:26:54 +08:00
5576f8de39 新增功能:使用cli控制实例启停、在浏览器中打开网页面板 2025-03-09 21:29:33 +08:00
de2c2af2bd 新增功能:添加zhaozuohong.vip镜像选项 2025-03-08 11:28:22 +08:00
501259b420 发布v0.6.1版本 2025-02-23 21:00:43 +08:00
f5011e0051 功能修复:打开实例文件夹时异常报错 2025-02-23 20:28:31 +08:00
c94d6d5494 功能修复:打包后运行实例时编码异常 2025-02-23 20:09:32 +08:00
4153164c49 发布v0.6版本 2025-02-23 18:11:58 +08:00
dc32d7e53e 新增功能:合并多开器 2025-02-23 18:11:26 +08:00
942d93417b 日志最多保留200行 2025-01-28 16:13:53 +08:00
25f9915fcc ruff格式化代码 2025-01-25 17:49:17 +08:00
cae312a272 新增功能:启动程序和设置页面添加日志窗口 2025-01-25 17:41:01 +08:00
9295d9f2cf 界面优化
1.日志的中文字体改为微软雅黑
2.帮助文档按钮外边距调整到和日志窗左边距一致
3.扩大默认窗口大小,使得PyPI可以初始展示到一行
4.表单label改为垂直居中
5.设置tab页的“新”标签设置垂直居中,并且不能影响菜单栏的高度
2025-01-07 13:29:00 +08:00
0661b6bbc3 发布v0.5版本 2024-12-28 21:05:35 +08:00
8ed883202b 构建:requirements添加pyinstaller 2024-12-28 21:05:28 +08:00
5cdf9d752f 功能修复:修复依赖时异常卡死 2024-12-28 20:15:04 +08:00
478bcd5f43 新增功能:执行命令时根据命令输出返回错误提示信息 2024-12-28 20:14:01 +08:00
60f43d42be 新增功能:界面输出分类并使用不同颜色显示 2024-12-28 11:29:58 +08:00
1c484d3f77 功能修复:在无网络情况下启动器无法使用
在加载配置完成后取消加载中状态,把一些不影响功能使用的操作后置
2024-12-26 08:57:15 +08:00
f22594a260 新增功能:添加帮助文档入口,首次启动启动器时自动打开帮助文档 2024-12-26 08:41:33 +08:00
92ef815d0d 使用pip-tools安装mower-ng的依赖 2024-12-19 08:07:32 +08:00
ffc2ff6808 使用pip-tools管理python依赖 2024-12-15 23:23:13 +08:00
bcbd556e7d 系统配置文件改为json类型,移除yaml的使用 2024-12-15 21:57:17 +08:00
987f1b6929 发布v0.4版本 2024-12-14 22:15:00 +08:00
04218f40f7 发布包从tar修改为7z,自更新适配新发包方式 2024-12-14 22:14:10 +08:00
94009c8136 ruff检查问题修复 2024-12-14 20:52:05 +08:00
effcc2874e 按功能拆分代码 2024-12-14 19:54:21 +08:00
d687e0426a 修复README的打包命令 2024-12-14 19:49:55 +08:00
f604e8ac99 构建:打包和开发时使用不同的配置文件 2024-12-14 12:37:52 +08:00
89c4121f61 代码样式调整:去除没有变量引用的字符串的f前缀,修改变量为下划线风格命名 2024-12-12 13:14:54 +08:00
8a9b8d1c47 新增功能:初始化时下载python和git 2024-12-12 07:46:08 +08:00
00212e447b 发版v0.3 2024-12-08 20:46:44 +08:00
383bed2a9d 初始化和更新代码时的命令添加参数提升速度、回显更多输出,拆分stdout和stderr分别输出 2024-12-08 11:58:31 +08:00
23f551fe18 conf使用json存储 2024-12-04 19:05:49 +08:00
a2726b465d 修改命令列表读取的配置方式 2024-12-02 22:55:39 +08:00
3aad1fe8ff 参考mower的conf配置 2024-12-02 22:34:54 +08:00
01c4bee95e 格式化部分代码 2024-12-02 12:04:08 +08:00
988924ed3a 修改打包方式为onedir,自更新适配新打包方式 2024-12-01 19:56:55 +08:00
7fbbc088ae 删除自更新多余代码,ruff格式化代码 2024-12-01 17:54:09 +08:00
d1b3d34c7a prettier format 2024-11-30 20:59:05 +08:00
8fd5b4c6e5 gitignore添加.idea和其他文件夹 2024-11-30 20:57:17 +08:00
719cb4bda2 exe自更新 2024-11-30 20:54:48 +08:00
1b4ce1966f 窗口名恢复版本号显示,修改readme中的打包命令 2024-11-28 22:00:49 +08:00
38 changed files with 1834 additions and 219 deletions

13
.gitignore vendored
View file

@ -1,5 +1,7 @@
/launcher.json /conf.yml
/conf.json
/dist /dist
/instances/
# Byte-compiled / optimized / DLL files # Byte-compiled / optimized / DLL files
__pycache__/ __pycache__/
@ -65,7 +67,6 @@ db.sqlite3
db.sqlite3-journal db.sqlite3-journal
# Flask stuff: # Flask stuff:
instance/
.webassets-cache .webassets-cache
# Scrapy stuff: # Scrapy stuff:
@ -162,4 +163,10 @@ cython_debug/
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
# and can be added to the global gitignore or merged into this file. For a more nuclear # and can be added to the global gitignore or merged into this file. For a more nuclear
# option (not recommended) you can uncomment the following to ignore the entire idea folder. # option (not recommended) you can uncomment the following to ignore the entire idea folder.
#.idea/ .idea/
launcher.iml
# Mower-ng
git/
python/
mower-ng/

View file

@ -2,12 +2,29 @@
## 开发环境 ## 开发环境
目前只有 `pywebview` 一个依赖。 安装 `pip-tools`
```bash
pip install pip-tools
```
安装依赖
```bash
pip-sync requirements.txt
```
## 打包 ## 打包
前端运行 `npm run build` 生成 `ui/dist`,之后安装 PyInstaller,运行 前端运行 `npm run build` 生成 `ui/dist`,之后安装 PyInstaller,运行
```bash ```bash
pyinstaller -w -F --add-data ui/dist:ui/dist main.py pyinstaller -w --add-data "ui/dist:ui/dist" --add-data "launcher/sys_config/config_dist.json:launcher/sys_config" launcher.py
```
在dist文件夹生成launcher文件夹
```bash
cd dist
py7zr c launcher.7z launcher
``` ```

View file

@ -1,119 +1,17 @@
import json
import mimetypes import mimetypes
import shutil
from pathlib import Path from pathlib import Path
from shutil import rmtree
from subprocess import PIPE, STDOUT, Popen from launcher.constants import update_tmp_folder
import webview from launcher.webview import start_webview
mimetypes.add_type("text/html", ".html") mimetypes.add_type("text/html", ".html")
mimetypes.add_type("text/css", ".css") mimetypes.add_type("text/css", ".css")
mimetypes.add_type("application/javascript", ".js") mimetypes.add_type("application/javascript", ".js")
version = "2024-11-28" if __name__ == "__main__":
# 如果当前路径存在临时文件夹,则删除
if Path(update_tmp_folder).exists():
shutil.rmtree(update_tmp_folder)
config = { start_webview()
"page": "init",
"branch": "slow",
"mirror": "aliyun",
}
config_path = Path("launcher.json")
try:
with config_path.open("r") as f:
user_config = json.load(f)
config.update(user_config)
except Exception:
pass
def custom_event(data):
data = json.dumps({"log": data})
js = f"var event = new CustomEvent('log', {{detail: {data}}}); window.dispatchEvent(event);"
window.evaluate_js(js)
mirror_list = {
"pypi": "https://pypi.org/simple",
"aliyun": "https://mirrors.aliyun.com/pypi/simple/",
"tuna": "https://mirrors.tuna.tsinghua.edu.cn/pypi/web/simple",
"sjtu": "https://mirror.sjtu.edu.cn/pypi/web/simple",
}
command_list = {
"lfs": "git\\bin\\git lfs install",
"ensurepip": "python\\python -m ensurepip --default-pip",
"clone": "git\\bin\\git clone https://git-cf.zhaozuohong.vip/mower-ng/mower-ng.git --branch slow",
"fetch": lambda: f"..\\git\\bin\\git fetch origin {config['branch']}",
"switch": lambda: f"..\\git\\bin\\git switch -f {config['branch']}",
"reset": lambda: f"..\\git\\bin\\git reset --hard origin/{config['branch']}",
"pip_install": lambda: f"..\\python\\Scripts\\pip install --no-cache-dir -i {mirror_list[config['mirror']]} -r requirements.txt --no-warn-script-location",
"webview": "start ..\\python\\pythonw webview_ui.py",
"manager": "start ..\\python\\pythonw manager.py",
}
class Api:
def get_branch(self):
return config["branch"]
def set_branch(self, branch):
config["branch"] = branch
def get_page(self):
return config["page"]
def set_page(self, page):
config["page"] = page
def get_mirror(self):
return config["mirror"]
def set_mirror(self, mirror):
config["mirror"] = mirror
def update_self(self):
# 更新启动器本身
pass
def rm_site_packages(self):
site_packages_path = Path("./python/Lib/site-packages")
if site_packages_path.exists():
rmtree(site_packages_path)
return "site-packages目录移除成功"
return "python\\Lib\\site-packages目录不存在"
def rm_python_scripts(self):
python_scripts_path = Path("./python/Scripts")
if python_scripts_path.exists():
rmtree(python_scripts_path)
return "Scripts目录移除成功"
return "python\\Scripts目录不存在"
def run(self, command, cwd=None):
command = command_list[command]
if callable(command):
command = command()
custom_event(command + "\n")
try:
with Popen(
command, stdout=PIPE, stderr=STDOUT, shell=True, cwd=cwd, bufsize=0
) as p:
for data in p.stdout:
try:
text = data.decode("utf-8")
except Exception:
text = data.decode("gbk")
custom_event(text)
if p.returncode == 0:
return "success"
except Exception as e:
custom_event(str(e))
return "failed"
window = webview.create_window("mower-ng launcher", "ui/dist/index.html", js_api=Api())
webview.start()
with config_path.open("w") as f:
json.dump(config, f)

0
launcher/__init__.py Normal file
View file

View file

@ -0,0 +1,30 @@
import json
import os
from pathlib import Path
from launcher.config.conf import Conf
conf_path = Path(os.path.join(os.getcwd(), "conf.json"))
def save_conf():
with conf_path.open("w", encoding="utf8") as f:
json.dump(conf.model_dump(), f, ensure_ascii=False, indent=4)
def load_conf():
global conf
if not conf_path.is_file():
conf_path.parent.mkdir(exist_ok=True)
conf = Conf()
save_conf()
return
with conf_path.open("r", encoding="utf-8") as file:
data = json.load(file)
if data is None:
data = {}
conf = Conf(**data)
conf: Conf
load_conf()

83
launcher/config/conf.py Normal file
View file

@ -0,0 +1,83 @@
from typing import List, Literal, get_args, get_origin
from pydantic import BaseModel, model_validator
from pydantic_core import PydanticUndefined
class ConfModel(BaseModel):
@model_validator(mode="before")
@classmethod
def nested_defaults(cls, data):
for name, field in cls.model_fields.items():
expected_type = field.annotation
if name not in data:
if field.default is PydanticUndefined:
data[name] = expected_type
else:
data[name] = field.default
value = data[name]
# 检查 Literal 类型并修正
if get_origin(expected_type) is Literal:
valid_literals = get_args(expected_type)
if value not in valid_literals:
# 修正为默认值
data[name] = (
field.default
if field.default is not PydanticUndefined
else None
)
return data
class Total(ConfModel):
"""整体"""
# 所在页面
page: str = "init"
# 是否已展示帮助文档
is_already_show_doc: bool = False
class UpdatePart(ConfModel):
"""更新代码"""
# mower-ng 代码分支
branch: str = "slow"
# PyPI 仓库镜像
mirror: str = "aliyun"
class LaunchPart(ConfModel):
"""启动程序"""
class Instance(ConfModel):
"""实例"""
# 是否选中
checked: bool = False
# 实例名
name: str = ""
# 实例路径
path: str = ""
# 实例列表
instances: List[Instance] = []
# 是否展示日志窗口
is_show_log: bool = False
class OtherPart(ConfModel):
"""其他配置"""
# xx.zhaozuohong.vip镜像 (访问xx.zhaozuohong.vip url时,0=原路径 1=在.zhaozuohong.vip前添加-cf前缀)
base_mirror: Literal["0", "1"] = "0"
class Conf(
Total,
UpdatePart,
LaunchPart,
OtherPart,
):
pass

47
launcher/constants.py Normal file
View file

@ -0,0 +1,47 @@
"""
constants.py
该模块定义了应用程序中使用的各种常量这些常量包括API URL和其他配置参数
"""
# 更新临时文件夹名
update_tmp_folder = "download_tmp"
# 更新脚本名
upgrade_script_name = "upgrade.bat"
# 下载新版本压缩包名
file_name = "launcher.7z"
# 获取最新版本发布信息
get_new_version_url = (
"https://git-cf.zhaozuohong.vip/api/v1/repos/mower-ng/launcher/releases/latest"
)
# 下载地址
download_git_url = "https://list.zhaozuohong.vip/mower-ng/git.7z"
download_python_url = "https://list.zhaozuohong.vip/mower-ng/python.7z"
# mower-ng git链接
mower_ng_git_url = "https://git-cf.zhaozuohong.vip/mower-ng/mower-ng.git"
# pip镜像地址
mirror_list = {
"pypi": "https://pypi.org/simple",
"aliyun": "https://mirrors.aliyun.com/pypi/simple/",
"tuna": "https://mirrors.tuna.tsinghua.edu.cn/pypi/web/simple",
"sjtu": "https://mirror.sjtu.edu.cn/pypi/web/simple",
}
# 实例文件夹名
instances_folder_name = "instances"
# cli命令
cli_command = {
"status": "获取mower-ng实例状态",
"launch": "启动mower-ng进程",
"exit": "停止mower-ng进程",
"kill": "强制退出mower-ng进程",
"start": "开始运行调度器",
"stop": "停止运行调度器",
"webui": "在浏览器中打开网页面板",
"log": "通过WebSocket获取日志",
}

View file

108
launcher/file/download.py Normal file
View file

@ -0,0 +1,108 @@
import os
import time
import requests
from launcher.file.extract import extract_7z_file
from launcher.file.utils import format_size
from launcher.webview.events import custom_event, LogType
def download_file(download_name, download_url, destination_folder):
"""
下载文件到指定文件夹
:param download_name: 下载内容名
:param download_url: 文件的下载 URL
:param destination_folder: 保存下载文件的目标文件夹
:return: 下载是否成功
"""
if not os.path.exists(destination_folder):
os.makedirs(destination_folder)
filename = os.path.basename(download_url)
download_path = os.path.join(destination_folder, filename)
custom_event(LogType.info, f"开始下载: {download_name}")
response = requests.get(download_url, stream=True)
if response.status_code == 200:
total_size = int(response.headers.get("content-length", 0))
downloaded_size = 0
start_time = time.time()
last_update_time = time.time() # 记录上次更新时间
block_size = 4096 # 每次读取的数据块大小
with open(download_path, "wb") as file:
for data in response.iter_content(chunk_size=block_size):
file.write(data)
downloaded_size += len(data)
current_time = time.time()
elapsed_time = current_time - start_time
if elapsed_time > 0:
download_speed = downloaded_size / elapsed_time # 字节/秒
else:
download_speed = 0
progress_percent = (
(downloaded_size / total_size) * 100 if total_size != 0 else 0
)
# 检查是否需要更新进度信息,每1秒更新一次
if current_time - last_update_time >= 1:
# 格式化输出
formatted_downloaded_size = format_size(downloaded_size)
formatted_total_size = format_size(total_size)
formatted_speed = format_size(download_speed) + "/s"
custom_event(
LogType.info,
f"下载进度: {progress_percent:.2f}% ({formatted_downloaded_size}/{formatted_total_size}), 下载速度: {formatted_speed}",
)
last_update_time = current_time # 更新上次更新时间
end_time = time.time()
total_elapsed_time = end_time - start_time
average_download_speed = (
downloaded_size / total_elapsed_time if total_elapsed_time != 0 else 0
)
# 格式化输出
formatted_total_elapsed_time = f"{total_elapsed_time:.2f}"
formatted_average_download_speed = format_size(average_download_speed) + "/s"
custom_event(
LogType.info,
f"下载完成: {filename}, 耗时: {formatted_total_elapsed_time}, 下载速度: {formatted_average_download_speed}",
)
else:
custom_event(LogType.error, f"下载失败: {response.status_code}")
return False
return True
def init_download(download_name, download_url, destination_folder):
"""
初始化中的下载任务返回一个函数用于执行下载任务
:param download_name: 下载任务的名称用于在日志中记录
:param download_url: 下载文件的 URL
:param destination_folder: 下载文件的目标文件夹
:return: 一个函数用于执行下载任务
"""
def download():
target_folder = os.path.join(download_name)
if os.path.exists(target_folder):
custom_event(LogType.info, f"{download_name} 文件夹已存在,跳过下载")
return True
filename = os.path.basename(download_url)
if not download_file(filename, download_url, destination_folder):
return False
download_path = os.path.join(destination_folder, filename)
if not extract_7z_file(filename, download_path, destination_folder, True):
return False
return True
return download

78
launcher/file/extract.py Normal file
View file

@ -0,0 +1,78 @@
import os
import time
from py7zr import py7zr
from py7zr.callbacks import ExtractCallback
from launcher.file.utils import format_size
from launcher.webview.events import custom_event, LogType
class MyExtractCallback(ExtractCallback):
def __init__(self):
super().__init__()
self.total_size = 0
self.last_print_time = time.time()
def report_start(self, archive_name, archive_format):
pass
def report_start_preparation(self):
pass
def report_end(self, processing_file_path, wrote_bytes):
self.total_size += int(wrote_bytes)
current_time = time.time()
if current_time - self.last_print_time >= 1.0: # 至少每隔1秒输出一次
custom_event(LogType.info, f"已解压: {format_size(self.total_size)}")
self.last_print_time = current_time
def report_postprocess(self):
pass
def report_update(self, message):
pass
def report_warning(self, message):
pass
def extract_7z_file(
file_name, file_path, destination_folder, delete_after_extract=True
):
"""
解压7z文件到指定文件夹
:param file_name: 7z文件的名称
:param file_path: 7z文件的路径
:param destination_folder: 解压目标文件夹
:param delete_after_extract: 解压后删除压缩文件默认删除
:return: 解压是否成功
"""
if not os.path.exists(destination_folder):
os.makedirs(destination_folder)
custom_event(LogType.info, f"开始解压文件: {file_name}")
try:
start_time = time.time()
with py7zr.SevenZipFile(file_path, mode="r") as z:
callback = MyExtractCallback()
z.extractall(path=destination_folder, callback=callback)
end_time = time.time()
total_elapsed_time = end_time - start_time
formatted_total_elapsed_time = f"{total_elapsed_time:.2f}"
custom_event(
LogType.info,
f"解压完成: {file_name}, 总大小: {format_size(callback.total_size)}, 耗时: {formatted_total_elapsed_time}",
)
except Exception as e:
custom_event(LogType.error, f"解压失败: {repr(e)}")
return False
if delete_after_extract:
try:
os.remove(file_path)
custom_event(LogType.info, f"删除{file_path}成功")
except OSError as e:
custom_event(LogType.error, f"删除{file_path}失败: {repr(e)}")
return True

33
launcher/file/utils.py Normal file
View file

@ -0,0 +1,33 @@
import os
def format_size(size_bytes):
"""格式化文件大小为人类可读的形式"""
for unit in ["B", "KB", "MB", "GB", "TB"]:
if size_bytes < 1024:
return f"{size_bytes:.2f} {unit}"
size_bytes /= 1024
return f"{size_bytes:.2f} PB"
def ensure_directory_exists(directory):
"""确保目录存在,如果不存在则创建"""
if not os.path.exists(directory):
os.makedirs(directory)
def check_command_path(command, cwd=None):
"""检查命令路径是否存在exe文件
:return 是否存在,命令exe文件全路径
"""
command_name = command.split(" ")[0]
system_command = ["start", "explorer"]
if command_name in system_command:
return True, None
exec_command_path = os.getcwd()
if cwd:
exec_command_path = os.path.join(exec_command_path, cwd)
full_command_path = (
os.path.abspath(os.path.join(exec_command_path, command_name)) + ".exe"
)
return os.path.exists(full_command_path), full_command_path

View file

View file

@ -0,0 +1,129 @@
import json
import os
import shutil
import uuid
from launcher import config
from launcher.config.conf import LaunchPart
from launcher.constants import instances_folder_name
from launcher.webview.events import custom_event, LogType
def add_instance():
instances_path = os.path.join(os.getcwd(), instances_folder_name)
if not os.path.exists(instances_path):
os.makedirs(instances_path)
instance_folder_name = str(uuid.uuid4())
instance_folder_path = os.path.join(instances_path, instance_folder_name)
if os.path.exists(instance_folder_path):
raise Exception("创建实例目录失败")
os.makedirs(instance_folder_path)
custom_event(LogType.info, f"创建实例目录成功: {instance_folder_path}")
return instance_folder_path
def migrate_instance(source_folder):
"""通用配置迁移方法
Args:
source_folder: 源配置目录路径
target_folder: 目标配置目录路径
"""
try:
if not os.path.exists(source_folder):
custom_event(LogType.error, f"源配置目录不存在: {source_folder}")
return {"status": False, "message": f"源配置目录不存在{source_folder}"}
target_folder = add_instance()
# 需要复制的目录和文件列表
copy_items = [("tmp", True), ("conf.yml", False), ("plan.json", False)]
for item, is_dir in copy_items:
src = os.path.join(source_folder, item)
dst = os.path.join(target_folder, item)
if is_dir:
if os.path.exists(src):
shutil.copytree(src, dst, dirs_exist_ok=True)
else:
if os.path.exists(src):
shutil.copy2(src, dst)
custom_event(LogType.info, f"{source_folder} 配置成功迁移至 {target_folder}")
return {"status": True, "data": target_folder, "message": "配置迁移成功"}
except Exception as e:
custom_event(LogType.error, f"配置迁移失败: {str(e)}")
return {"status": False, "message": str(e)}
def migrate_instances_config():
try:
config_path = os.path.join(os.getcwd(), "mower-ng", "instances.json")
if not os.path.exists(config_path):
custom_event(LogType.error, f"多开配置文件不存在{config_path}")
return {"status": False, "message": "多开配置文件不存在"}
with open(config_path, "r", encoding="utf-8") as f:
instances_data = json.loads(f.read())
custom_event(LogType.info, f"读取多开配置: {instances_data}")
valid_instances = []
error_messages = []
for index, item in enumerate(instances_data, 1):
try:
# 基础结构验证
if not isinstance(item, dict):
raise ValueError("配置项必须是字典类型")
# 必填字段检查
required_fields = ["name", "path"]
for field in required_fields:
if field not in item:
raise ValueError(f"缺少必要字段: {field}")
# 路径有效性验证
if not os.path.exists(item["path"]):
raise ValueError(f"配置路径不存在{item['path']}")
# 执行配置迁移
migration_result = migrate_instance(item["path"])
if not migration_result["status"]:
raise Exception(f"路径迁移失败: {migration_result['message']}")
# 转换为实例模型
instance = LaunchPart.Instance(
name=item["name"].strip(), path=migration_result["data"]
)
valid_instances.append(instance)
except Exception as e:
error_msg = f"{index}项: {str(e)}"
error_messages.append(error_msg)
custom_event(LogType.error, error_msg)
# 保存有效配置
if valid_instances:
config.conf.instances.extend(valid_instances)
config.save_conf()
message = f"成功导入{len(valid_instances)}个实例" + (
f",存在{len(error_messages)}个错误项" if error_messages else ""
)
custom_event(LogType.info, message)
return {
"status": not bool(error_messages),
"data": len(valid_instances),
"message": message,
}
except json.JSONDecodeError as e:
custom_event(LogType.error, f"JSON解析失败: {str(e)}")
return {"status": False, "message": "配置文件格式错误"}
except Exception as e:
custom_event(LogType.error, f"迁移多开配置失败: {str(e)}")
return {"status": False, "message": str(e)}

View file

@ -1,19 +1,30 @@
import io
import logging import logging
import os
import sys
from logging.handlers import RotatingFileHandler from logging.handlers import RotatingFileHandler
from launcher.sys_config import sys_config
# 配置日志 # 配置日志
def setup_logger(): def setup_logger():
log_level = sys_config.get("log_level")
logger = logging.getLogger("launcher.log") logger = logging.getLogger("launcher.log")
logger.setLevel(logging.DEBUG) logger.setLevel(log_level)
# 设置标准输出编码为 UTF-8
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding="utf-8")
# 控制台输出 # 控制台输出
console_handler = logging.StreamHandler() console_handler = logging.StreamHandler()
console_handler.setLevel(logging.DEBUG) console_handler.setLevel(log_level)
# 文件输出 # 文件输出
file_path = os.path.join(os.getcwd(), "launcher.log")
file_handler = RotatingFileHandler( file_handler = RotatingFileHandler(
"launcher.log", maxBytes=5 * 1024 * 1024, backupCount=3 file_path, maxBytes=5 * 1024 * 1024, backupCount=3, encoding="utf-8"
) )
file_handler.setLevel(logging.INFO) file_handler.setLevel(logging.INFO)

View file

@ -0,0 +1,58 @@
import json
import os
import sys
class SysConfig:
"""
读取系统配置文件
"""
# 版本
version: str
# ui路径
url: str
# 日志输出级别
log_level: str
# 是否开启ui调试
debug: bool
def __init__(self):
self.config = {}
self.config_path = self.get_config_path()
self.load_config()
def get_config_path(self):
if getattr(sys, "frozen", False):
# logger.error("打包配置")
# 如果是打包后的可执行文件
base_path = sys._MEIPASS
config_subdir = "launcher/sys_config" # 添加子目录
config_filename = "config_dist.json"
else:
# logger.error("本地配置")
# 如果是本地开发环境
base_path = os.path.dirname(__file__)
config_subdir = "" # 本地开发环境不需要子目录
config_filename = "config_local.json"
config_path = os.path.join(base_path, config_subdir, config_filename)
return config_path
def load_config(self):
try:
with open(self.config_path, "r", encoding="utf-8") as file:
self.config = json.load(file)
except FileNotFoundError:
pass
# logger.error(f"配置文件未找到: {self.config_path}")
except Exception:
pass
# logger.error(f"加载配置文件时出错: {repr(e)}")
def get(self, key):
return self.config.get(key)
# 创建一个全局配置实例
sys_config = SysConfig()

View file

@ -0,0 +1,6 @@
{
"version": "v0.7.1",
"url": "ui/dist/index.html",
"log_level": "INFO",
"debug": false
}

View file

@ -0,0 +1,6 @@
{
"version": "dev",
"url": "http://localhost:5173/",
"log_level": "DEBUG",
"debug": true
}

12
launcher/utils.py Normal file
View file

@ -0,0 +1,12 @@
from launcher import config
def build_base_url(url: str) -> str:
"""
构建xx.zhaozuohong.vip如果配置base_mirror是1.zhaozuohong.vip前添加-cf前缀
:param url: 带有xx.zhaozuohong.vip的url字符串
:return: 构建完成的url
"""
if config.conf.base_mirror == "1":
url = url.replace(".zhaozuohong.vip", "-cf.zhaozuohong.vip")
return url

View file

@ -0,0 +1,18 @@
import webview
from launcher.sys_config import sys_config
from launcher.webview.api import Api
window = None
def start_webview():
global window
window = webview.create_window(
f"mower-ng launcher {sys_config.get('version')}",
sys_config.get("url"),
js_api=Api(),
width=850,
height=600,
)
webview.start(debug=sys_config.get("debug"))

307
launcher/webview/api.py Normal file
View file

@ -0,0 +1,307 @@
import io
import os
import shutil
import subprocess
import time
from _winapi import CREATE_NO_WINDOW
from pathlib import Path
from shutil import rmtree
from subprocess import Popen
import requests
from launcher import config
from launcher.constants import (
download_git_url,
download_python_url,
get_new_version_url,
upgrade_script_name,
mirror_list,
file_name,
instances_folder_name,
mower_ng_git_url,
cli_command,
)
from launcher.file.download import init_download, download_file
from launcher.file.extract import extract_7z_file
from launcher.file.utils import ensure_directory_exists, check_command_path
from launcher.instances import manager
from launcher.log import logger
from launcher.sys_config import sys_config
from launcher.utils import build_base_url
from launcher.webview.events import custom_event, LogType
command_list = {
"download_git": lambda: init_download(
"git", build_base_url(download_git_url), os.getcwd()
),
"download_python": lambda: init_download(
"python", build_base_url(download_python_url), os.getcwd()
),
"lfs": "git\\bin\\git lfs install",
"ensurepip": "python\\python -m ensurepip --default-pip",
"clone": lambda: f"git\\bin\\git -c lfs.concurrenttransfers=100 clone {build_base_url(mower_ng_git_url)} --branch slow",
"set_remote": lambda: f"..\\git\\bin\\git remote set-url origin {build_base_url(mower_ng_git_url)}",
"set_lfs": lambda: f"..\\git\\bin\\git config lfs.url {build_base_url(mower_ng_git_url)}/info/lfs",
"fetch": lambda: f"..\\git\\bin\\git fetch origin {config.conf.branch} --progress",
"switch": lambda: f"..\\git\\bin\\git -c lfs.concurrenttransfers=100 switch -f {config.conf.branch} --progress",
"reset": lambda: f"..\\git\\bin\\git -c lfs.concurrenttransfers=200 reset --hard origin/{config.conf.branch}",
"pip_tools_install": lambda: f"..\\python\\Scripts\\pip install --no-cache-dir -i {mirror_list[config.conf.mirror]} pip-tools --no-warn-script-location",
"pip_sync": lambda: f"..\\python\\Scripts\\pip-sync -i {mirror_list[config.conf.mirror]} requirements.txt",
"webview": lambda instance_path="": f'..\\python\\pythonw -X utf8 webview_ui.py "{instance_path}"',
"cli": lambda path,
command: f'..\\python\\pythonw -X utf8 cli.py -p "{path}" {command}',
}
def parse_stderr(stderr_output):
error_keywords = {
"fatal: destination path 'mower-ng' already exists and is not an empty directory.": "mower-ng文件夹已存在并且非空。",
"index.lock': File exists": "上一个git命令正在执行,请等待执行结束或在任务管理器中杀掉git进程,并确保上方提示的index.lock文件删除后再次运行。",
"Could not resolve host": "网络出现错误,请检查网络是否通畅。",
"ReadTimeoutError": "网络连接超时,请检查网络连接或尝试更换镜像源。",
"No space left on device": "磁盘空间不足。",
}
for keyword, message in error_keywords.items():
if keyword in stderr_output:
return message
return "未定义的错误"
def check_command_end(command_key, output):
end_keywords = {"webview": {"WebSocket客户端建立连接": "mower_ng已成功运行"}}
if command_key in end_keywords:
keywords = end_keywords[command_key]
for keyword in keywords:
if keyword in output:
custom_event(LogType.info, keywords[keyword])
return True
return False
class Api:
def load_config(self):
logger.debug("读取配置文件")
return config.conf.model_dump()
def save_config(self, conf):
logger.debug(f"更新配置文件{conf}")
config.conf = config.Conf(**conf)
config.save_conf()
def get_version(self):
return sys_config.get("version")
def get_new_version(self):
logger.info("获取最新版本号")
response = requests.get(build_base_url(get_new_version_url))
return response.json()
# 更新启动器本身
def update_self(self, download_url):
download_url = build_base_url(download_url)
logger.info(f"开始更新启动器 {download_url}")
current_path = os.getcwd()
download_tmp_folder = os.path.join(current_path, "download_tmp")
# 确保 download_tmp 文件夹存在
ensure_directory_exists(download_tmp_folder)
if not download_file("launcher", download_url, download_tmp_folder):
return "下载新版本失败"
download_path = os.path.join(download_tmp_folder, file_name)
if not extract_7z_file("launcher", download_path, download_tmp_folder, True):
return "解压新版本失败"
exe_path = os.path.join(current_path, "launcher.exe")
folder_path = os.path.join(current_path, "_internal")
new_exe_path = os.path.join(download_tmp_folder, "launcher", "launcher.exe")
new_folder_path = os.path.join(download_tmp_folder, "launcher", "_internal")
script_path = os.path.join(download_tmp_folder, upgrade_script_name)
with open(script_path, "w") as b:
temp_list = "@echo off\n"
temp_list += "timeout /t 3 /nobreak\n" # 等待进程退出
temp_list += f"rmdir {folder_path}\n" # 删除_internal
temp_list += f"del {exe_path}\n" # 删除exe
temp_list += f"xcopy /e /i /y {new_folder_path} {folder_path}\n"
temp_list += f"move {new_exe_path} {exe_path}\n"
temp_list += "timeout /t 1 /nobreak\n" # 等待操作完成
temp_list += f"start {exe_path}\n" # 启动新程序
temp_list += "exit"
b.write(temp_list)
# 不显示cmd窗口
Popen([script_path], creationflags=CREATE_NO_WINDOW)
os._exit(0)
def rm_site_packages(self):
try:
site_packages_path = Path("./python/Lib/site-packages")
if site_packages_path.exists():
rmtree(site_packages_path)
return "site-packages目录移除成功"
return "python\\Lib\\site-packages目录不存在"
except Exception as e:
return repr(e)
def rm_python_scripts(self):
try:
python_scripts_path = Path("./python/Scripts")
if python_scripts_path.exists():
rmtree(python_scripts_path)
return "Scripts目录移除成功"
return "python\\Scripts目录不存在"
except Exception as e:
return repr(e)
def run(self, command_key, cwd=None, params={}):
command = command_list[command_key]
if callable(command):
try:
command = command(**params)
except TypeError:
command = command()
if callable(command):
return "success" if command() else "failed"
if cwd is not None:
custom_event(LogType.info, f"命令执行目录:{cwd}")
custom_event(LogType.execute_command, command)
# 执行命令前先判断命令路径是否存在
exist, command_path = check_command_path(command, cwd)
if not exist:
custom_event(
LogType.error,
f"命令路径不存在:{command_path} 请尝试依赖修复并重新初始化。",
)
return "failed"
try:
stdout_stderr = []
with subprocess.Popen(
command,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
shell=True,
cwd=cwd,
bufsize=0,
universal_newlines=False,
) as p:
def process_lines(text_io):
for line in iter(text_io.readline, ""):
text = line.rstrip("\n").strip()
custom_event(LogType.command_out, text)
if stdout_stderr is not None:
stdout_stderr.append(text)
if check_command_end(command_key, text):
break
detected_encoding = "utf-8"
text_io = io.TextIOWrapper(
p.stdout, encoding=detected_encoding, errors="replace"
)
try:
process_lines(text_io)
except UnicodeDecodeError:
p.stdout.seek(0) # 重新将流指针重置到开头
text_io = io.TextIOWrapper(
p.stdout, encoding="gbk", errors="replace"
)
process_lines(text_io)
finally:
text_io.close()
if p.returncode == 0:
return "success"
else:
error_message = parse_stderr("\n".join(stdout_stderr))
custom_event(LogType.error, f"命令执行失败,{error_message}")
return "failed"
except Exception as e:
logger.exception(e)
custom_event(LogType.error, str(e))
return "failed"
def add_instance(self):
return manager.add_instance()
def delete_instance(self, path):
instances_dir = os.path.join(os.getcwd(), instances_folder_name)
abs_path = os.path.abspath(path)
if os.path.commonpath(
[abs_path, instances_dir]
) == instances_dir and os.path.exists(abs_path):
shutil.rmtree(abs_path)
def migrate_default_instance(self):
"""迁移默认实例文件到新实例"""
source_path = os.path.join(os.getcwd(), "mower-ng")
return manager.migrate_instance(source_path)
def migrate_instances_config(self):
"""迁移多开配置"""
return manager.migrate_instances_config()
def open_folder(self, path):
if not os.path.exists(path):
custom_event(LogType.error, f"路径不存在:{path}")
else:
os.startfile(path)
custom_event(LogType.info, f"成功打开文件夹:{path}")
def test_base_url_connect(self):
url = build_base_url(get_new_version_url)
custom_event(LogType.info, f"开始测试URL连接:{url}")
try:
start_time = time.time()
response = requests.get(url)
end_time = time.time()
if response.status_code == 200:
elapsed_time_ms = (end_time - start_time) * 1000
custom_event(
LogType.info, f"测试成功,响应时间为 {elapsed_time_ms:.2f} 毫秒"
)
else:
custom_event(
LogType.error, f"测试失败: HTTP状态码 {response.status_code}"
)
except requests.exceptions.RequestException as e:
custom_event(LogType.error, f"发生错误: {e}")
def cli_control(self, command: str, path: str):
"""
统一的CLI控制接口用于执行指定命令并可选地指定工作目录
:param command_str: 要执行的命令字符串或命令键 "status", "launch"
:param path: 实例路径
"""
if command not in cli_command:
custom_event(
LogType.error,
f"无效的命令字符串或命令键:{command},请检查输入。",
)
return
try:
ret = self.run("cli", "mower-ng", {"command": command, "path": path})
if command == "launch" and ret == "success":
self.run("cli", "mower-ng", {"command": "webui", "path": path})
except Exception as e:
custom_event(LogType.error, f"{cli_command[command]} 失败 {repr(e)}")
def batch_cli_control(self, command):
checked_instances = [
instance for instance in config.conf.instances if instance.checked
]
if not checked_instances:
custom_event(LogType.warning, "没有选中的实例")
return [{"status": False, "message": "No checked instances"}]
for instance in checked_instances:
try:
custom_event(LogType.info, f"{instance.name} {cli_command[command]}")
self.cli_control(command, instance.path)
custom_event(
LogType.info, f"{instance.name} {cli_command[command]} 完成"
)
except Exception as e:
custom_event(
LogType.error,
f"{instance.name} {cli_command[command]} 失败 {repr(e)}",
)

View file

@ -0,0 +1,32 @@
import json
from enum import Enum
import launcher
from launcher.log import logger
class LogType(Enum):
info = "信息"
error = "错误"
execute_command = "执行命令"
command_out = "命令输出"
def custom_event(log_type, data):
data = f"[{log_type.value}] {data}"
match log_type:
case LogType.info:
logger.info(data)
case LogType.error:
logger.error(data)
case LogType.execute_command:
logger.info(data)
case LogType.command_out:
logger.info(data)
case _:
logger.info(data)
data = json.dumps({"log": data + "\n"})
js = f"var event = new CustomEvent('log', {{detail: {data}}}); window.dispatchEvent(event);"
launcher.webview.window.evaluate_js(js)

5
requirements.in Normal file
View file

@ -0,0 +1,5 @@
pywebview==5.1
requests==2.32.3
py7zr==0.22.0
pydantic==2.10.3
pyinstaller==6.11.1

80
requirements.txt Normal file
View file

@ -0,0 +1,80 @@
#
# This file is autogenerated by pip-compile with Python 3.12
# by the following command:
#
# pip-compile requirements.in
#
--index-url https://pypi.tuna.tsinghua.edu.cn/simple
altgraph==0.17.4
# via pyinstaller
annotated-types==0.7.0
# via pydantic
bottle==0.13.2
# via pywebview
brotli==1.1.0
# via py7zr
certifi==2024.12.14
# via requests
cffi==1.17.1
# via clr-loader
charset-normalizer==3.4.0
# via requests
clr-loader==0.2.7.post0
# via pythonnet
idna==3.10
# via requests
inflate64==1.0.0
# via py7zr
multivolumefile==0.2.3
# via py7zr
packaging==24.2
# via
# pyinstaller
# pyinstaller-hooks-contrib
pefile==2023.2.7
# via pyinstaller
proxy-tools==0.1.0
# via pywebview
psutil==6.1.0
# via py7zr
py7zr==0.22.0
# via -r requirements.in
pybcj==1.0.2
# via py7zr
pycparser==2.22
# via cffi
pycryptodomex==3.21.0
# via py7zr
pydantic==2.10.3
# via -r requirements.in
pydantic-core==2.27.1
# via pydantic
pyinstaller==6.11.1
# via -r requirements.in
pyinstaller-hooks-contrib==2024.11
# via pyinstaller
pyppmd==1.1.0
# via py7zr
pythonnet==3.0.5
# via pywebview
pywebview==5.1
# via -r requirements.in
pywin32-ctypes==0.2.3
# via pyinstaller
pyzstd==0.16.2
# via py7zr
requests==2.32.3
# via -r requirements.in
texttable==1.7.0
# via py7zr
typing-extensions==4.12.2
# via
# pydantic
# pydantic-core
# pywebview
urllib3==2.2.3
# via requests
# The following packages are considered to be unsafe in a requirements file:
# setuptools

65
ui/package-lock.json generated
View file

@ -8,6 +8,8 @@
"name": "ui", "name": "ui",
"version": "0.0.0", "version": "0.0.0",
"dependencies": { "dependencies": {
"highlight.js": "^11.11.1",
"pinia": "^2.2.8",
"vue": "^3.5.11" "vue": "^3.5.11"
}, },
"devDependencies": { "devDependencies": {
@ -1131,6 +1133,11 @@
"@vue/shared": "3.5.11" "@vue/shared": "3.5.11"
} }
}, },
"node_modules/@vue/devtools-api": {
"version": "6.6.4",
"resolved": "https://registry.npmmirror.com/@vue/devtools-api/-/devtools-api-6.6.4.tgz",
"integrity": "sha512-sGhTPMuXqZ1rVOk32RylztWkfXTRhuS7vgAKv0zjqk8gbsHkJ7xfFf+jbySxt7tWObEJwyKaHMikV/WGDiQm8g=="
},
"node_modules/@vue/eslint-config-prettier": { "node_modules/@vue/eslint-config-prettier": {
"version": "10.0.0", "version": "10.0.0",
"resolved": "https://registry.npmjs.org/@vue/eslint-config-prettier/-/eslint-config-prettier-10.0.0.tgz", "resolved": "https://registry.npmjs.org/@vue/eslint-config-prettier/-/eslint-config-prettier-10.0.0.tgz",
@ -2069,11 +2076,9 @@
} }
}, },
"node_modules/highlight.js": { "node_modules/highlight.js": {
"version": "11.10.0", "version": "11.11.1",
"resolved": "https://registry.npmjs.org/highlight.js/-/highlight.js-11.10.0.tgz", "resolved": "https://registry.npmmirror.com/highlight.js/-/highlight.js-11.11.1.tgz",
"integrity": "sha512-SYVnVFswQER+zu1laSya563s+F8VDGt7o35d4utbamowvUNLLMovFqwCLSocpZTz3MgaSRA1IbqRWZv97dtErQ==", "integrity": "sha512-Xwwo44whKBVCYoliBQwaPvtd/2tYFkRQtXDWj1nackaV2JPXx3L0+Jvd8/qCJ2p+ML0/XVkJ2q+Mr+UVdpJK5w==",
"dev": true,
"license": "BSD-3-Clause",
"engines": { "engines": {
"node": ">=12.0.0" "node": ">=12.0.0"
} }
@ -2534,6 +2539,56 @@
"url": "https://github.com/sponsors/jonschlinkert" "url": "https://github.com/sponsors/jonschlinkert"
} }
}, },
"node_modules/pinia": {
"version": "2.2.8",
"resolved": "https://registry.npmmirror.com/pinia/-/pinia-2.2.8.tgz",
"integrity": "sha512-NRTYy2g+kju5tBRe0oNlriZIbMNvma8ZJrpHsp3qudyiMEA8jMmPPKQ2QMHg0Oc4BkUyQYWagACabrwriCK9HQ==",
"dependencies": {
"@vue/devtools-api": "^6.6.3",
"vue-demi": "^0.14.10"
},
"funding": {
"url": "https://github.com/sponsors/posva"
},
"peerDependencies": {
"@vue/composition-api": "^1.4.0",
"typescript": ">=4.4.4",
"vue": "^2.6.14 || ^3.5.11"
},
"peerDependenciesMeta": {
"@vue/composition-api": {
"optional": true
},
"typescript": {
"optional": true
}
}
},
"node_modules/pinia/node_modules/vue-demi": {
"version": "0.14.10",
"resolved": "https://registry.npmmirror.com/vue-demi/-/vue-demi-0.14.10.tgz",
"integrity": "sha512-nMZBOwuzabUO0nLgIcc6rycZEebF6eeUfaiQx9+WSk8e29IbLvPU9feI6tqW4kTo3hvoYAJkMh8n8D0fuISphg==",
"hasInstallScript": true,
"bin": {
"vue-demi-fix": "bin/vue-demi-fix.js",
"vue-demi-switch": "bin/vue-demi-switch.js"
},
"engines": {
"node": ">=12"
},
"funding": {
"url": "https://github.com/sponsors/antfu"
},
"peerDependencies": {
"@vue/composition-api": "^1.0.0-rc.1",
"vue": "^3.0.0-0 || ^2.6.0"
},
"peerDependenciesMeta": {
"@vue/composition-api": {
"optional": true
}
}
},
"node_modules/pkg-types": { "node_modules/pkg-types": {
"version": "1.2.0", "version": "1.2.0",
"resolved": "https://registry.npmjs.org/pkg-types/-/pkg-types-1.2.0.tgz", "resolved": "https://registry.npmjs.org/pkg-types/-/pkg-types-1.2.0.tgz",

View file

@ -11,6 +11,8 @@
"format": "prettier --write src/" "format": "prettier --write src/"
}, },
"dependencies": { "dependencies": {
"highlight.js": "^11.11.1",
"pinia": "^2.2.8",
"vue": "^3.5.11" "vue": "^3.5.11"
}, },
"devDependencies": { "devDependencies": {

View file

@ -4,41 +4,68 @@ import Launch from '@/pages/Launch.vue'
import Update from '@/pages/Update.vue' import Update from '@/pages/Update.vue'
import Fix from '@/pages/Fix.vue' import Fix from '@/pages/Fix.vue'
import { dateZhCN, zhCN } from 'naive-ui' import { dateZhCN, zhCN } from 'naive-ui'
import Settings from '@/pages/Settings.vue'
import { useConfigStore } from '@/stores/config.js'
const configStore = useConfigStore()
const loading = ref(true) const loading = ref(true)
const page = ref(null) const page = ref(null)
let conf
function load_config() { function show_doc() {
pywebview.api.get_page().then((value) => { window.open('https://hedgedoc.zhaozuohong.vip/s/LfSzK2n0K', '_blank')
page.value = value
loading.value = false
})
} }
const log = ref('') async function init_version() {
version.value = await pywebview.api.get_version()
new_version.value = await pywebview.api.get_new_version()
if (new_version.value.tag_name > version.value) {
update_able.value = true
}
}
async function initialize_config() {
await configStore.load_config()
conf = configStore.config
loading.value = false
if (!conf.is_already_show_doc) {
show_doc()
conf.is_already_show_doc = true
}
await init_version()
}
const log = ref([])
provide('log', log) provide('log', log)
const log_ele = ref(null) const log_ele = ref(null)
provide('log_ele', log_ele) provide('log_ele', log_ele)
watch(log, () => { watch(
log,
() => {
nextTick(() => { nextTick(() => {
log_ele.value?.scrollTo({ position: 'bottom' }) log_ele.value?.scrollTo({ position: 'bottom' })
}) })
}) },
{ deep: true }
)
onMounted(() => { onMounted(() => {
if (window.pywebview && pywebview.api) { if (window.pywebview && pywebview.api) {
load_config() initialize_config()
} else { } else {
window.addEventListener('pywebviewready', load_config) window.addEventListener('pywebviewready', () => {
initialize_config()
})
} }
window.addEventListener('log', (e) => { window.addEventListener('log', (e) => {
log.value += e.detail.log log.value.push(e.detail.log)
if (log.value.length > 200) {
log.value.shift()
}
}) })
}) })
function set_page(value) { function set_page(value) {
log.value = '' log.value.splice(0)
pywebview.api.set_page(value)
} }
const running = ref(false) const running = ref(false)
@ -46,6 +73,15 @@ provide('running', running)
const steps = ref([]) const steps = ref([])
provide('steps', steps) provide('steps', steps)
const update_able = ref(false)
provide('update_able', update_able)
const version = ref('')
provide('version', version)
const new_version = ref({})
provide('new_version', new_version)
</script> </script>
<template> <template>
@ -58,13 +94,28 @@ provide('steps', steps)
type="card" type="card"
placement="left" placement="left"
class="container" class="container"
:default-value="page" v-model:value="conf.page"
@update:value="set_page" @update:value="set_page"
justify-content="center"
> >
<n-tab-pane :disabled="running" name="init" tab="初始化"><init /></n-tab-pane> <n-tab-pane :disabled="running" name="init" tab="初始化"><init /></n-tab-pane>
<n-tab-pane :disabled="running" name="update" tab="更新代码"><update /></n-tab-pane> <n-tab-pane :disabled="running" name="update" tab="更新代码"><update /></n-tab-pane>
<n-tab-pane :disabled="running" name="launch" tab="启动程序"><launch /></n-tab-pane> <n-tab-pane :disabled="running" name="launch" tab="启动程序"><launch /></n-tab-pane>
<n-tab-pane :disabled="running" name="fix" tab="依赖修复"><fix /></n-tab-pane> <n-tab-pane :disabled="running" name="fix" tab="依赖修复"><fix /></n-tab-pane>
<n-tab-pane :disabled="running" name="settings">
<template #tab>
<div class="tab-content">
<span>设置</span>
<n-tag v-if="update_able" class="tag" round type="success"></n-tag>
</div>
</template>
<settings />
</n-tab-pane>
<template #suffix>
<div class="suffix-container">
<n-button type="primary" secondary size="small" @click="show_doc">帮助文档</n-button>
</div>
</template>
</n-tabs> </n-tabs>
</n-notification-provider> </n-notification-provider>
<n-global-style /> <n-global-style />
@ -76,4 +127,17 @@ provide('steps', steps)
width: 100vw; width: 100vw;
height: 100vh; height: 100vh;
} }
.suffix-container {
margin: 0 4px 6px 4px;
}
.tab-content {
position: relative;
}
.tag {
margin-left: 4px;
position: absolute;
top: 50%;
left: 100%;
transform: translateY(-50%);
}
</style> </style>

View file

@ -0,0 +1,30 @@
<script setup>
import { form_item_label_style } from '@/styles/styles.js'
import { useConfigStore } from '@/stores/config.js'
const conf = useConfigStore().config
const running = inject('running')
async function test_connect() {
running.value = true
await pywebview.api.test_base_url_connect()
running.value = false
}
</script>
<template>
<n-form-item label="镜像模式" :label-style="form_item_label_style">
<n-radio-group v-model:value="conf.base_mirror" :disabled="running">
<n-flex>
<n-radio value="0">默认模式</n-radio>
<n-radio value="1">镜像模式-cf后缀</n-radio>
</n-flex>
</n-radio-group>
<n-button strong secondary type="primary" size="small" @click="test_connect" :disabled="running"
>测试连接</n-button
>
</n-form-item>
</template>
<style scoped></style>

View file

@ -11,7 +11,7 @@ const current_state = inject('current_state')
const notification = useNotification() const notification = useNotification()
async function start() { async function start() {
log.value = '' log.value = []
running.value = true running.value = true
for (const [i, step] of steps.value.entries()) { for (const [i, step] of steps.value.entries()) {
current_step.value = i + 1 current_step.value = i + 1

View file

@ -1,14 +1,57 @@
<script setup> <script setup>
import { darkTheme } from 'naive-ui' import { darkTheme } from 'naive-ui'
import hljs from 'highlight.js/lib/core'
const log = inject('log') const log = inject('log')
const log_ele = inject('log_ele') const log_ele = inject('log_ele')
const chinesePattern = {
className: 'chinese',
begin: /[\u4e00-\u9fa5]+/
}
hljs.registerLanguage('naive-log', () => ({
contains: [
{
className: 'info',
begin: /^\[信息\]/,
end: /$/,
returnBegin: true,
returnEnd: true,
contains: [chinesePattern]
},
{
className: 'error',
begin: /^\[错误\]/,
end: /$/,
returnBegin: true,
returnEnd: true,
contains: [chinesePattern]
},
{
className: 'execute_command',
begin: /^\[执行命令\]/,
end: /$/,
returnBegin: true,
returnEnd: true,
contains: [chinesePattern]
},
{
className: 'command_out',
begin: /^\[命令输出\]/,
end: /$/,
returnBegin: true,
returnEnd: true,
contains: [chinesePattern]
}
]
}))
</script> </script>
<template> <template>
<n-config-provider :theme="darkTheme" class="provider"> <n-config-provider :theme="darkTheme" class="provider" :hljs="hljs">
<n-card class="full" content-style="height: 100%"> <n-card class="full" content-style="height: 100%">
<n-log :log="log" class="full" ref="log_ele" /> <n-log :lines="log" class="full selectable-log" ref="log_ele" language="naive-log" />
</n-card> </n-card>
</n-config-provider> </n-config-provider>
</template> </template>
@ -23,10 +66,8 @@ const log_ele = inject('log_ele')
height: 100% !important; height: 100% !important;
box-sizing: border-box; box-sizing: border-box;
} }
</style>
<style> .selectable-log {
pre { user-select: text;
word-break: break-all !important;
} }
</style> </style>

View file

@ -1,7 +1,11 @@
import 'vfonts/Lato.css'
import 'vfonts/FiraCode.css' import 'vfonts/FiraCode.css'
import './styles/global.css'
import { createApp } from 'vue' import { createApp } from 'vue'
import { createPinia } from 'pinia'
import App from './App.vue' import App from './App.vue'
const app = createApp(App) const app = createApp(App)
const pinia = createPinia()
app.use(pinia)
app.mount('#app') app.mount('#app')

View file

@ -26,15 +26,24 @@ async function rm_site_packages_and_python_scripts() {
</script> </script>
<template> <template>
<n-flex vertical style=" <n-flex
vertical
style="
gap: 16px; gap: 16px;
height: 100%; height: 100%;
padding: 16px; padding: 16px;
box-sizing: border-box; box-sizing: border-box;
justify-content: center; justify-content: center;
align-items: center; align-items: center;
"> "
<n-button class="fix-btn" type="error" secondary size="large" @click="rm_site_packages_and_python_scripts"> >
<n-button
class="fix-btn"
type="error"
secondary
size="large"
@click="rm_site_packages_and_python_scripts"
>
移除 site-packages python/Scripts 目录 移除 site-packages python/Scripts 目录
</n-button> </n-button>
</n-flex> </n-flex>

View file

@ -1,13 +1,18 @@
<script setup> <script setup>
import BaseMirrorOption from '@/components/BaseMirrorOption.vue'
const steps = ref([ const steps = ref([
{ title: '设置 Git LFS', command: ['lfs'] }, {
title: '下载 git、python',
command: ['download_git', 'download_python']
},
{ {
title: '安装 pip', title: '安装 pip',
command: ['ensurepip'] command: ['ensurepip']
}, },
{ {
title: '下载 mower-ng 代码', title: '下载 mower-ng 代码',
command: ['clone'] command: ['lfs', 'clone']
} }
]) ])
provide('steps', steps) provide('steps', steps)
@ -19,6 +24,9 @@ provide('current_state', current_state)
<template> <template>
<n-flex vertical style="gap: 16px; height: 100%; padding: 16px; box-sizing: border-box"> <n-flex vertical style="gap: 16px; height: 100%; padding: 16px; box-sizing: border-box">
<n-form label-placement="left" :show-feedback="false" label-width="auto" label-align="left">
<base-mirror-option />
</n-form>
<n-alert title="以下步骤仅需运行一次" type="warning" /> <n-alert title="以下步骤仅需运行一次" type="warning" />
<n-steps :current="current_step" :status="current_state" size="small"> <n-steps :current="current_step" :status="current_state" size="small">
<n-step v-for="step in steps" :title="step.title" /> <n-step v-for="step in steps" :title="step.title" />

View file

@ -1,37 +1,285 @@
<script setup> <script setup>
function webview() { import { useConfigStore } from '@/stores/config.js'
pywebview.api.run('webview', 'mower-ng') import { NButton } from 'naive-ui'
import {
Add,
Pencil,
Play,
Folder,
TrashOutline,
Archive,
Browsers,
Stop,
Search
} from '@vicons/ionicons5'
const notification = useNotification()
const config_store = useConfigStore()
const conf = config_store.config
const instance_name_input_refs = ref([])
const update_instance_name_index = ref(null)
const migrate_options = [
{
label: '迁移单开配置',
key: 'default'
},
{
label: '迁移多开配置',
key: 'instances'
}
]
const check_all = computed(
() => conf.instances.length > 0 && conf.instances.every((item) => item.checked)
)
const check_part = computed(() => !check_all.value && conf.instances.some((item) => item.checked))
function click_check_all(ckecked) {
if (ckecked) {
conf.instances.forEach((item) => {
item.checked = true
})
} else {
conf.instances.forEach((item) => {
item.checked = false
})
}
}
function setInstanceNameInputRef(el, index) {
if (el) {
instance_name_input_refs.value[index] = el
}
}
async function add_instance() {
const instance_path = await pywebview.api.add_instance()
conf.instances.push({
checked: false,
name: '新实例',
path: instance_path
})
}
async function delete_instance(index, path) {
await pywebview.api.delete_instance(path)
conf.instances.splice(index, 1)
} }
function manager() { function start_update_instance_name(index) {
pywebview.api.run('manager', 'mower-ng') update_instance_name_index.value = index
nextTick(() => {
instance_name_input_refs.value[index]?.focus()
})
}
function end_update_instance_name() {
update_instance_name_index.value = null
}
function open_folder(path) {
pywebview.api.open_folder(path)
}
function cli(command, instance) {
pywebview.api.cli_control(command, instance.path)
}
function batch_cli_control(command) {
pywebview.api.batch_cli_control(command)
}
async function handle_migrate(key) {
if (key == 'default') {
const response = await pywebview.api.migrate_default_instance()
console.log(response)
if (response.status) {
conf.instances.push({
checked: false,
name: '默认实例',
path: response.data
})
notification['success']({
content: '信息',
meta: response.message,
duration: 3000
})
} else {
notification['error']({
content: '错误',
meta: response.message,
duration: 3000
})
}
} else {
const response = await pywebview.api.migrate_instances_config()
console.log('多开配置内容:', response)
if (response.data) {
await config_store.load_config()
conf.instances = [...config_store.config.instances]
}
if (response.status) {
notification['info']({
title: '信息',
content: response.message,
duration: 3000
})
} else {
notification['error']({
title: '错误',
content: response.message,
duration: 3000
})
}
}
} }
</script> </script>
<template> <template>
<n-flex <n-flex vertical style="gap: 16px; height: 100%; padding: 16px; box-sizing: border-box">
vertical <n-space class="top" justify="space-between">
style=" <n-space>
gap: 16px; <n-button class="launch-btn" type="primary" secondary @click="add_instance">
height: 100%; <template #icon>
padding: 16px; <n-icon :component="Add"></n-icon>
box-sizing: border-box; </template>
justify-content: center; 添加实例
align-items: center; </n-button>
" <n-button
class="launch-btn"
type="primary"
secondary
@click="batch_cli_control('launch')"
:disabled="!check_all && !check_part"
> >
<n-button class="launch-btn" type="primary" secondary size="large" @click="webview"> <template #icon>
单开运行 <n-icon :component="Play"></n-icon>
</template>
启动所选实例
</n-button> </n-button>
<n-button class="launch-btn" type="primary" secondary size="large" @click="manager"> <n-button
多开器 class="launch-btn"
type="error"
secondary
@click="batch_cli_control('exit')"
:disabled="!check_all && !check_part"
>
<template #icon>
<n-icon :component="Stop"></n-icon>
</template>
停止所选实例
</n-button> </n-button>
<n-dropdown trigger="click" :options="migrate_options" @select="handle_migrate">
<n-button class="launch-btn" type="primary" secondary>
<template #icon>
<n-icon :component="Archive"></n-icon>
</template>
迁移配置
</n-button>
</n-dropdown>
</n-space>
<div class="is_show_log_switch">
<n-switch v-model:value="conf.is_show_log" />
显示日志
</div>
</n-space>
<n-list class="instance_list" bordered>
<n-list-item class="instance_list_item">
<template #prefix>
<n-checkbox
v-model:checked="check_all"
:indeterminate="check_part"
style="white-space: nowrap"
@update:checked="click_check_all"
>全选</n-checkbox
>
</template>
</n-list-item>
<n-list-item class="instance_list_item" v-for="(item, index) in conf.instances" :key="index">
<template #prefix>
<n-checkbox v-model:checked="item.checked"></n-checkbox>
</template>
<n-space vertical>
<n-space v-if="update_instance_name_index != index">
<n-text class="instance_name">{{ item.name }}</n-text>
<n-button size="tiny" @click="start_update_instance_name(index)">
<template #icon>
<n-icon :component="Pencil"></n-icon>
</template>
</n-button>
</n-space>
<n-input
v-else
class="instance_name_input"
:ref="(el) => setInstanceNameInputRef(el, index)"
v-model:value="item.name"
@blur="end_update_instance_name"
clearable
></n-input>
</n-space>
<template #suffix>
<n-space :wrap="false">
<n-button type="primary" ghost size="small" @click="cli('status', item)">
<template #icon>
<n-icon :component="Search"></n-icon>
</template>
</n-button>
<n-button type="primary" size="small" @click="cli('launch', item)">
<template #icon>
<n-icon :component="Play"></n-icon>
</template>
</n-button>
<n-button type="primary" ghost size="small" @click="cli('webui', item)">
<template #icon>
<n-icon :component="Browsers"></n-icon>
</template>
</n-button>
<n-button type="error" ghost size="small" @click="cli('exit', item)">
<template #icon>
<n-icon :component="Stop"></n-icon>
</template>
</n-button>
<n-button type="primary" ghost size="small" @click="open_folder(item.path)">
<template #icon>
<n-icon :component="Folder"></n-icon>
</template>
</n-button>
<n-popconfirm @positive-click="delete_instance(index, item.path)">
<template #trigger>
<n-button type="error" ghost size="small">
<template #icon>
<n-icon :component="TrashOutline"></n-icon>
</template>
</n-button>
</template>
删除操作将导致实例配置丢失请谨慎操作
</n-popconfirm>
</n-space>
</template>
</n-list-item>
</n-list>
<log-component v-show="conf.is_show_log" class="log" />
</n-flex> </n-flex>
</template> </template>
<style scoped> <style scoped>
.launch-btn { .launch-btn {
width: 120px; height: 38px;
height: 48px; }
.instance_list {
overflow: auto;
}
.instance_list_item {
height: 50px;
}
.instance_name {
margin-left: 12px;
}
.instance_name_input {
height: 35px;
}
.log {
min-height: 40vh;
max-height: 40vh;
margin-top: auto;
}
.top {
align-items: center;
}
.is_show_log_switch {
margin-right: 20px;
text-align: center;
} }
</style> </style>

103
ui/src/pages/Settings.vue Normal file
View file

@ -0,0 +1,103 @@
<script setup>
import { Sync } from '@vicons/ionicons5'
import { form_item_label_style } from '@/styles/styles.js'
import BaseMirrorOption from '@/components/BaseMirrorOption.vue'
const notification = useNotification()
const update_able = inject('update_able')
const running = inject('running')
const version = inject('version')
const new_version = inject('new_version')
const check_running = ref(false)
const update_self_running = ref(false)
async function update_self() {
running.value = true
update_self_running.value = true
const response = await pywebview.api.update_self(
new_version.value['assets'][0]['browser_download_url']
)
notification['error']({
content: '错误',
meta: response,
duration: 3000
})
update_self_running.value = false
running.value = false
}
async function open_new_version_html() {
window.open(new_version.value['html_url'])
}
async function check_update() {
running.value = true
check_running.value = true
new_version.value = await pywebview.api.get_new_version()
if (new_version.value.tag_name > version.value) {
update_able.value = true
notification['info']({
content: '提示',
meta: '有新版本可更新',
duration: 3000
})
} else {
update_able.value = false
notification['info']({
content: '提示',
meta: '当前已是最新版本',
duration: 3000
})
}
check_running.value = false
running.value = false
}
</script>
<template>
<n-flex vertical style="gap: 16px; height: 100%; padding: 16px; box-sizing: border-box">
<n-form label-placement="left" :show-feedback="false" label-width="auto" label-align="left">
<base-mirror-option />
<n-form-item label="版本" :label-style="form_item_label_style">
<n-space align="center">
{{ version }}
<n-button
type="success"
secondary
size="small"
:loading="check_running"
:disabled="running"
@click="check_update"
>
<template #icon>
<n-icon :component="Sync"></n-icon>
</template>
检查更新
</n-button>
</n-space>
</n-form-item>
<n-alert style="margin: 8px 0" type="success" v-if="update_able">
<template #header>
最新版本{{ `${new_version.tag_name} ${new_version.name}` }}
<n-button type="success" secondary style="float: right" @click="open_new_version_html">
了解此版本
</n-button>
</template>
<n-space>
<n-button
type="success"
secondary
:loading="update_self_running"
:disabled="running"
@click="update_self"
>
立即更新
</n-button>
</n-space>
</n-alert>
</n-form>
<log-component />
</n-flex>
</template>

View file

@ -1,32 +1,22 @@
<script setup> <script setup>
import { useConfigStore } from '@/stores/config.js'
import { form_item_label_style } from '@/styles/styles.js'
import BaseMirrorOption from '@/components/BaseMirrorOption.vue'
const conf = useConfigStore().config
const branch = ref(null) const branch = ref(null)
const mirror = ref(null) const mirror = ref(null)
const running = inject('running')
onMounted(() => {
pywebview.api.get_branch().then((value) => {
branch.value = value
})
pywebview.api.get_mirror().then((value) => {
mirror.value = value
})
})
watch(branch, () => {
pywebview.api.set_branch(branch.value)
})
watch(mirror, () => {
pywebview.api.set_mirror(mirror.value)
})
const steps = computed(() => [ const steps = computed(() => [
{ {
title: '更新源码', title: '更新源码',
command: ['fetch', 'switch', 'reset'], command: ['set_remote', 'set_lfs', 'fetch', 'switch', 'reset'],
cwd: 'mower-ng' cwd: 'mower-ng'
}, },
{ {
title: '安装依赖', title: '安装依赖',
command: ['pip_install'], command: ['pip_tools_install', 'pip_sync'],
cwd: 'mower-ng' cwd: 'mower-ng'
} }
]) ])
@ -40,16 +30,17 @@ provide('current_state', current_state)
<template> <template>
<n-flex vertical style="gap: 16px; height: 100%; padding: 16px; box-sizing: border-box"> <n-flex vertical style="gap: 16px; height: 100%; padding: 16px; box-sizing: border-box">
<n-form label-placement="left" :show-feedback="false" label-width="auto" label-align="left"> <n-form label-placement="left" :show-feedback="false" label-width="auto" label-align="left">
<n-form-item label="mower-ng 代码分支"> <base-mirror-option />
<n-radio-group v-model:value="branch"> <n-form-item label="mower-ng 代码分支" :label-style="form_item_label_style">
<n-radio-group v-model:value="conf.branch" :disabled="running">
<n-flex> <n-flex>
<n-radio value="fast">测试版</n-radio> <n-radio value="fast">测试版</n-radio>
<n-radio value="slow">稳定版</n-radio> <n-radio value="slow">稳定版</n-radio>
</n-flex> </n-flex>
</n-radio-group> </n-radio-group>
</n-form-item> </n-form-item>
<n-form-item label="PyPI 仓库镜像"> <n-form-item label="PyPI 仓库镜像" :label-style="form_item_label_style">
<n-radio-group v-model:value="mirror"> <n-radio-group v-model:value="conf.mirror" :disabled="running">
<n-flex> <n-flex>
<n-radio value="pypi">PyPI</n-radio> <n-radio value="pypi">PyPI</n-radio>
<n-radio value="aliyun">阿里云镜像站</n-radio> <n-radio value="aliyun">阿里云镜像站</n-radio>

49
ui/src/stores/config.js Normal file
View file

@ -0,0 +1,49 @@
import { defineStore } from 'pinia'
export const useConfigStore = defineStore('config', () => {
class Instance {
constructor(instance) {
this.checked = instance.checked
this.name = instance.name
this.path = instance.path
}
}
class Config {
constructor(conf) {
// 整体 Total
this.page = conf.page
this.is_already_show_doc = conf.is_already_show_doc
// 更新代码 UpdatePart
this.branch = conf.branch
this.mirror = conf.mirror
// 启动程序 LaunchPart
this.instances = []
this.is_show_log = conf.is_show_log
// 其他部分 OtherPart
this.base_mirror = conf.base_mirror
Object.assign(this, conf)
}
}
const config = reactive({})
async function load_config() {
const conf = await pywebview.api.load_config()
Object.assign(config, new Config(conf))
console.log('响应式配置已更新', config)
}
watch(
config,
() => {
pywebview.api.save_config(config)
},
{ deep: true }
)
return {
load_config,
config
}
})

43
ui/src/styles/global.css Normal file
View file

@ -0,0 +1,43 @@
/* src/assets/styles/global.css */
/* 日志样式 */
.n-code pre {
word-break: break-all !important;
}
.n-code pre .hljs-info {
color: #33ff33;
}
.n-code pre .hljs-error {
color: #ff0000;
}
.n-code pre .hljs-execute_command {
color: #edaf1f;
}
.n-code pre .hljs-command_out {
color: #ffffff;
}
.n-code pre .hljs-chinese {
font-family: '微软雅黑', sans-serif;
}
/* 确保 chinese 类在所有父级类下生效 */
.n-code pre .hljs-info .hljs-chinese {
color: #33ff33;
}
.n-code pre .hljs-error .hljs-chinese {
color: #ff0000;
}
.n-code pre .hljs-execute_command .hljs-chinese {
color: #edaf1f;
}
.n-code pre .hljs-command_out .hljs-chinese {
color: #ffffff;
}

3
ui/src/styles/styles.js Normal file
View file

@ -0,0 +1,3 @@
export const form_item_label_style = {
alignSelf: 'center'
}