From 719cb4bda24d3e2d82e3827242c92305fd0f9c61 Mon Sep 17 00:00:00 2001
From: li-xiaochen <397721316@qq.com>
Date: Sat, 30 Nov 2024 20:54:48 +0800
Subject: [PATCH 01/45] =?UTF-8?q?exe=E8=87=AA=E6=9B=B4=E6=96=B0?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
launcher.py | 82 ++++++++++++++++++++++++++++++++++--
ui/src/App.vue | 33 ++++++++++++++-
ui/src/pages/Settings.vue | 88 +++++++++++++++++++++++++++++++++++++++
3 files changed, 198 insertions(+), 5 deletions(-)
create mode 100644 ui/src/pages/Settings.vue
diff --git a/launcher.py b/launcher.py
index b09ed77..845b934 100644
--- a/launcher.py
+++ b/launcher.py
@@ -1,15 +1,22 @@
import json
import mimetypes
+import platform
+import sys
from pathlib import Path
from shutil import rmtree
from subprocess import PIPE, STDOUT, Popen
+
+import requests
import webview
+from log import logger
+from python.Lib import shutil, os, subprocess
+
mimetypes.add_type("text/html", ".html")
mimetypes.add_type("text/css", ".css")
mimetypes.add_type("application/javascript", ".js")
-version = "2024-11-28"
+version = "V0.2"
config = {
"page": "init",
@@ -18,6 +25,8 @@ config = {
}
config_path = Path("launcher.json")
+get_new_version_url = "https://git-cf.zhaozuohong.vip/api/v1/repos/mower-ng/launcher/releases/latest"
+
try:
with config_path.open("r") as f:
user_config = json.load(f)
@@ -31,6 +40,41 @@ def custom_event(data):
js = f"var event = new CustomEvent('log', {{detail: {data}}}); window.dispatchEvent(event);"
window.evaluate_js(js)
+def replace_restart(exename, new_exename):
+ script_name = "upgrade.sh" if platform.system() != "Windows" else "upgrade.bat"
+ script_path = os.path.join(os.getcwd(), script_name)
+
+ with open(script_path, 'w') as b:
+ if platform.system() == "Windows":
+ TempList = f"@echo off\n"
+ TempList += f"timeout /t 3 /nobreak\n" # 等待进程退出
+ TempList += f"del {exename}\n" # 删除旧程序
+ TempList += f"move {new_exename} {exename}\n" # 复制新版本程序
+ TempList += f"timeout /t 1 /nobreak\n" # 等待复制完成
+ TempList += f"start {exename}\n" # 启动新程序
+ TempList += f"exit"
+ else:
+ TempList = f"#!/bin/sh\n"
+ TempList += f"EXENAME={exename}\n"
+ TempList += f"NEW_EXENAME={new_exename}\n"
+ TempList += f"sleep 3\n"
+ TempList += f"rm \"$EXENAME\"\n"
+ TempList += f"mv \"$NEW_EXENAME\" \"$EXENAME\"\n"
+ TempList += f"sleep 1\n"
+ TempList += f"nohup ./{exename} &\n"
+ TempList += f"exit 0\n"
+ b.write(TempList)
+
+ if platform.system() != "Windows":
+ os.chmod(script_path, 0o755) # 设置脚本可执行权限
+
+ if platform.system() == "Windows":
+ # 不显示cmd窗口
+ subprocess.Popen([script_path], creationflags=subprocess.CREATE_NO_WINDOW)
+ else:
+ subprocess.Popen([script_path, exename, new_exename])
+
+ os._exit(0)
mirror_list = {
"pypi": "https://pypi.org/simple",
@@ -72,9 +116,34 @@ class Api:
def set_mirror(self, mirror):
config["mirror"] = mirror
- def update_self(self):
- # 更新启动器本身
- pass
+ def get_version(self):
+ return version
+
+ def get_new_version(self):
+ logger.info("获取最新版本号")
+ response = requests.get(get_new_version_url)
+ return response.json()
+
+ # 更新启动器本身
+ def update_self(self,download_url):
+ # 获取当前启动器的路径
+ current_path = sys.argv[0]
+ # 如果current_path是以py结尾,则将其转换为.exe
+ if current_path.endswith(".py"):
+ current_path = current_path[:-3] + ".exe"
+ temp_path = current_path + '.tmp'
+
+ logger.info(f"下载新版本: {download_url}")
+ response = requests.get(download_url, stream=True)
+ if response.status_code == 200:
+ with open(temp_path, 'wb') as file:
+ shutil.copyfileobj(response.raw, file)
+ else:
+ logger.error(f"下载新版本失败: {response.status_code}")
+ return f"下载新版本: {response.status_code}"
+
+ logger.info(f"替换旧版本,{temp_path} -> {current_path}")
+ replace_restart(current_path,temp_path)
def rm_site_packages(self):
site_packages_path = Path("./python/Lib/site-packages")
@@ -111,8 +180,13 @@ class Api:
custom_event(str(e))
return "failed"
+script_name = "upgrade.sh" if platform.system() != "Windows" else "upgrade.bat"
+# 如果当前路径存在更新脚本,则删除
+if Path(script_name).exists():
+ os.remove(script_name)
window = webview.create_window(f"mower-ng launcher {version}", "ui/dist/index.html", js_api=Api())
+#window = webview.create_window(f"mower-ng launcher {version}", "http://localhost:5173/", js_api=Api())
webview.start()
with config_path.open("w") as f:
diff --git a/ui/src/App.vue b/ui/src/App.vue
index 5d09561..85435b9 100644
--- a/ui/src/App.vue
+++ b/ui/src/App.vue
@@ -4,6 +4,7 @@ import Launch from '@/pages/Launch.vue'
import Update from '@/pages/Update.vue'
import Fix from '@/pages/Fix.vue'
import { dateZhCN, zhCN } from 'naive-ui'
+import Settings from '@/pages/Settings.vue'
const loading = ref(true)
const page = ref(null)
@@ -15,6 +16,14 @@ function load_config() {
})
}
+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
+ }
+}
+
const log = ref('')
provide('log', log)
const log_ele = ref(null)
@@ -28,8 +37,12 @@ watch(log, () => {
onMounted(() => {
if (window.pywebview && pywebview.api) {
load_config()
+ init_version()
} else {
- window.addEventListener('pywebviewready', load_config)
+ window.addEventListener('pywebviewready', () => {
+ load_config()
+ init_version()
+ })
}
window.addEventListener('log', (e) => {
log.value += e.detail.log
@@ -46,6 +59,15 @@ provide('running', running)
const steps = ref([])
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)
@@ -65,6 +87,15 @@ provide('steps', steps)
+
+
+
+ 设置
+ 新
+
+
+
+
diff --git a/ui/src/pages/Settings.vue b/ui/src/pages/Settings.vue
new file mode 100644
index 0000000..6cb3b07
--- /dev/null
+++ b/ui/src/pages/Settings.vue
@@ -0,0 +1,88 @@
+
+
+
+
+
+
+
+ {{version}}
+
+
+
+
+ 检查更新
+
+
+
+
+
+ 最新版本:{{new_version.name}}
+ 了解此版本
+
+
+
+ 立即更新
+
+
+
+
+
+
From 8fd5b4c6e5c8a09a3cca11c73292df00c9e80a0d Mon Sep 17 00:00:00 2001
From: li-xiaochen <397721316@qq.com>
Date: Sat, 30 Nov 2024 20:57:17 +0800
Subject: [PATCH 02/45] =?UTF-8?q?gitignore=E6=B7=BB=E5=8A=A0.idea=E5=92=8C?=
=?UTF-8?q?=E5=85=B6=E4=BB=96=E6=96=87=E4=BB=B6=E5=A4=B9?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
.gitignore | 7 ++++++-
1 file changed, 6 insertions(+), 1 deletion(-)
diff --git a/.gitignore b/.gitignore
index 3eab2be..4a61a32 100644
--- a/.gitignore
+++ b/.gitignore
@@ -162,4 +162,9 @@ cython_debug/
# 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
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
-#.idea/
+.idea/
+
+# Mower-ng
+git/
+python/
+mower-ng/
From d1b3d34c7af07b6c77ec388c1bfb516905aa39e6 Mon Sep 17 00:00:00 2001
From: li-xiaochen <397721316@qq.com>
Date: Sat, 30 Nov 2024 20:59:05 +0800
Subject: [PATCH 03/45] prettier format
---
ui/src/pages/Fix.vue | 55 ++++++++++++++----------
ui/src/pages/Settings.vue | 88 +++++++++++++++++++++------------------
2 files changed, 80 insertions(+), 63 deletions(-)
diff --git a/ui/src/pages/Fix.vue b/ui/src/pages/Fix.vue
index 73f5757..50190e8 100644
--- a/ui/src/pages/Fix.vue
+++ b/ui/src/pages/Fix.vue
@@ -3,39 +3,48 @@ const running = inject('running')
const notification = useNotification()
async function rm_site_packages_and_python_scripts() {
- running.value = true
- notification['info']({
- content: '提示',
- meta: '开始移除site-packages和python/Script目录',
- duration: 3000
- })
- const response = await pywebview.api.rm_site_packages()
- notification['info']({
- content: '提示',
- meta: response,
- duration: 3000
- })
- const response2 = await pywebview.api.rm_python_scripts()
- notification['info']({
- content: '提示',
- meta: response2,
- duration: 3000
- })
- running.value = false
+ running.value = true
+ notification['info']({
+ content: '提示',
+ meta: '开始移除site-packages和python/Script目录',
+ duration: 3000
+ })
+ const response = await pywebview.api.rm_site_packages()
+ notification['info']({
+ content: '提示',
+ meta: response,
+ duration: 3000
+ })
+ const response2 = await pywebview.api.rm_python_scripts()
+ notification['info']({
+ content: '提示',
+ meta: response2,
+ duration: 3000
+ })
+ running.value = false
}
-
-
- 移除 site-packages 和 python/Scripts 目录
+ "
+ >
+
+ 移除 site-packages 和 python/Scripts 目录
diff --git a/ui/src/pages/Settings.vue b/ui/src/pages/Settings.vue
index 6cb3b07..4798723 100644
--- a/ui/src/pages/Settings.vue
+++ b/ui/src/pages/Settings.vue
@@ -14,43 +14,45 @@ 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
+ 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'])
+ 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
+ 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
}
@@ -59,8 +61,13 @@ async function check_update() {
- {{version}}
-
+ {{ version }}
+
@@ -68,17 +75,18 @@ async function check_update() {
-
+
- 最新版本:{{new_version.name}}
+ 最新版本:{{ new_version.name }}
了解此版本
-
+
立即更新
From 7fbbc088aef4aad6c9636460cee8869e1aabd580 Mon Sep 17 00:00:00 2001
From: li-xiaochen <397721316@qq.com>
Date: Sun, 1 Dec 2024 17:54:09 +0800
Subject: [PATCH 04/45] =?UTF-8?q?=E5=88=A0=E9=99=A4=E8=87=AA=E6=9B=B4?=
=?UTF-8?q?=E6=96=B0=E5=A4=9A=E4=BD=99=E4=BB=A3=E7=A0=81=EF=BC=8Cruff?=
=?UTF-8?q?=E6=A0=BC=E5=BC=8F=E5=8C=96=E4=BB=A3=E7=A0=81?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
launcher.py | 61 ++++++++++++++-------------------------
ui/src/pages/Settings.vue | 2 --
2 files changed, 21 insertions(+), 42 deletions(-)
diff --git a/launcher.py b/launcher.py
index 845b934..8df7c24 100644
--- a/launcher.py
+++ b/launcher.py
@@ -1,6 +1,5 @@
import json
import mimetypes
-import platform
import sys
from pathlib import Path
from shutil import rmtree
@@ -27,6 +26,8 @@ config_path = Path("launcher.json")
get_new_version_url = "https://git-cf.zhaozuohong.vip/api/v1/repos/mower-ng/launcher/releases/latest"
+upgrade_script_name = "upgrade.bat"
+
try:
with config_path.open("r") as f:
user_config = json.load(f)
@@ -40,42 +41,23 @@ def custom_event(data):
js = f"var event = new CustomEvent('log', {{detail: {data}}}); window.dispatchEvent(event);"
window.evaluate_js(js)
+
def replace_restart(exename, new_exename):
- script_name = "upgrade.sh" if platform.system() != "Windows" else "upgrade.bat"
- script_path = os.path.join(os.getcwd(), script_name)
-
+ script_path = os.path.join(os.getcwd(), upgrade_script_name)
with open(script_path, 'w') as b:
- if platform.system() == "Windows":
- TempList = f"@echo off\n"
- TempList += f"timeout /t 3 /nobreak\n" # 等待进程退出
- TempList += f"del {exename}\n" # 删除旧程序
- TempList += f"move {new_exename} {exename}\n" # 复制新版本程序
- TempList += f"timeout /t 1 /nobreak\n" # 等待复制完成
- TempList += f"start {exename}\n" # 启动新程序
- TempList += f"exit"
- else:
- TempList = f"#!/bin/sh\n"
- TempList += f"EXENAME={exename}\n"
- TempList += f"NEW_EXENAME={new_exename}\n"
- TempList += f"sleep 3\n"
- TempList += f"rm \"$EXENAME\"\n"
- TempList += f"mv \"$NEW_EXENAME\" \"$EXENAME\"\n"
- TempList += f"sleep 1\n"
- TempList += f"nohup ./{exename} &\n"
- TempList += f"exit 0\n"
+ TempList = f"@echo off\n"
+ TempList += f"timeout /t 3 /nobreak\n" # 等待进程退出
+ TempList += f"del {exename}\n" # 删除旧程序
+ TempList += f"move {new_exename} {exename}\n" # 复制新版本程序
+ TempList += f"timeout /t 1 /nobreak\n" # 等待复制完成
+ TempList += f"start {exename}\n" # 启动新程序
+ TempList += f"exit"
b.write(TempList)
-
- if platform.system() != "Windows":
- os.chmod(script_path, 0o755) # 设置脚本可执行权限
-
- if platform.system() == "Windows":
- # 不显示cmd窗口
- subprocess.Popen([script_path], creationflags=subprocess.CREATE_NO_WINDOW)
- else:
- subprocess.Popen([script_path, exename, new_exename])
-
+ # 不显示cmd窗口
+ subprocess.Popen([script_path], creationflags=subprocess.CREATE_NO_WINDOW)
os._exit(0)
+
mirror_list = {
"pypi": "https://pypi.org/simple",
"aliyun": "https://mirrors.aliyun.com/pypi/simple/",
@@ -83,7 +65,6 @@ mirror_list = {
"sjtu": "https://mirror.sjtu.edu.cn/pypi/web/simple",
}
-
command_list = {
"lfs": "git\\bin\\git lfs install",
"ensurepip": "python\\python -m ensurepip --default-pip",
@@ -125,7 +106,7 @@ class Api:
return response.json()
# 更新启动器本身
- def update_self(self,download_url):
+ def update_self(self, download_url):
# 获取当前启动器的路径
current_path = sys.argv[0]
# 如果current_path是以py结尾,则将其转换为.exe
@@ -143,7 +124,7 @@ class Api:
return f"下载新版本: {response.status_code}"
logger.info(f"替换旧版本,{temp_path} -> {current_path}")
- replace_restart(current_path,temp_path)
+ replace_restart(current_path, temp_path)
def rm_site_packages(self):
site_packages_path = Path("./python/Lib/site-packages")
@@ -166,7 +147,7 @@ class Api:
custom_event(command + "\n")
try:
with Popen(
- command, stdout=PIPE, stderr=STDOUT, shell=True, cwd=cwd, bufsize=0
+ command, stdout=PIPE, stderr=STDOUT, shell=True, cwd=cwd, bufsize=0
) as p:
for data in p.stdout:
try:
@@ -180,13 +161,13 @@ class Api:
custom_event(str(e))
return "failed"
-script_name = "upgrade.sh" if platform.system() != "Windows" else "upgrade.bat"
+
# 如果当前路径存在更新脚本,则删除
-if Path(script_name).exists():
- os.remove(script_name)
+if Path(upgrade_script_name).exists():
+ os.remove(upgrade_script_name)
window = webview.create_window(f"mower-ng launcher {version}", "ui/dist/index.html", js_api=Api())
-#window = webview.create_window(f"mower-ng launcher {version}", "http://localhost:5173/", js_api=Api())
+# window = webview.create_window(f"mower-ng launcher {version}", "http://localhost:5173/", js_api=Api())
webview.start()
with config_path.open("w") as f:
diff --git a/ui/src/pages/Settings.vue b/ui/src/pages/Settings.vue
index 4798723..cfe9d61 100644
--- a/ui/src/pages/Settings.vue
+++ b/ui/src/pages/Settings.vue
@@ -8,8 +8,6 @@ const running = inject('running')
const version = inject('version')
const new_version = inject('new_version')
-const branch = ref(null)
-const mirror = ref(null)
const check_running = ref(false)
const update_self_running = ref(false)
From 988924ed3a2bd769a34231fa555a7236347e1a30 Mon Sep 17 00:00:00 2001
From: li-xiaochen <397721316@qq.com>
Date: Sun, 1 Dec 2024 19:56:55 +0800
Subject: [PATCH 05/45] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E6=89=93=E5=8C=85?=
=?UTF-8?q?=E6=96=B9=E5=BC=8F=E4=B8=BAonedir=EF=BC=8C=E8=87=AA=E6=9B=B4?=
=?UTF-8?q?=E6=96=B0=E9=80=82=E9=85=8D=E6=96=B0=E6=89=93=E5=8C=85=E6=96=B9?=
=?UTF-8?q?=E5=BC=8F?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
.gitignore | 1 +
README.md | 8 +++++-
launcher.py | 54 +++++++++++++++++----------------------
ui/src/pages/Settings.vue | 2 +-
4 files changed, 33 insertions(+), 32 deletions(-)
diff --git a/.gitignore b/.gitignore
index 4a61a32..e32caef 100644
--- a/.gitignore
+++ b/.gitignore
@@ -163,6 +163,7 @@ cython_debug/
# 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.
.idea/
+launcher.iml
# Mower-ng
git/
diff --git a/README.md b/README.md
index a43125d..5f04d6a 100644
--- a/README.md
+++ b/README.md
@@ -9,5 +9,11 @@
前端运行 `npm run build` 生成 `ui/dist`,之后安装 PyInstaller,运行
```bash
-pyinstaller -w -F --add-data ui/dist:ui/dist launcher.py
+pyinstaller -w --add-data ui/dist:ui/dist launcher.py
+```
+
+在dist文件夹生成launcher文件夹,切到dist文件夹下运行
+
+```bash
+tar -cf launcher.tar launcher
```
diff --git a/launcher.py b/launcher.py
index 8df7c24..700b7cc 100644
--- a/launcher.py
+++ b/launcher.py
@@ -1,6 +1,5 @@
import json
import mimetypes
-import sys
from pathlib import Path
from shutil import rmtree
from subprocess import PIPE, STDOUT, Popen
@@ -15,7 +14,7 @@ mimetypes.add_type("text/html", ".html")
mimetypes.add_type("text/css", ".css")
mimetypes.add_type("application/javascript", ".js")
-version = "V0.2"
+version = "v0.2"
config = {
"page": "init",
@@ -42,22 +41,6 @@ def custom_event(data):
window.evaluate_js(js)
-def replace_restart(exename, new_exename):
- script_path = os.path.join(os.getcwd(), upgrade_script_name)
- with open(script_path, 'w') as b:
- TempList = f"@echo off\n"
- TempList += f"timeout /t 3 /nobreak\n" # 等待进程退出
- TempList += f"del {exename}\n" # 删除旧程序
- TempList += f"move {new_exename} {exename}\n" # 复制新版本程序
- TempList += f"timeout /t 1 /nobreak\n" # 等待复制完成
- TempList += f"start {exename}\n" # 启动新程序
- TempList += f"exit"
- b.write(TempList)
- # 不显示cmd窗口
- subprocess.Popen([script_path], creationflags=subprocess.CREATE_NO_WINDOW)
- os._exit(0)
-
-
mirror_list = {
"pypi": "https://pypi.org/simple",
"aliyun": "https://mirrors.aliyun.com/pypi/simple/",
@@ -107,24 +90,35 @@ class Api:
# 更新启动器本身
def update_self(self, download_url):
- # 获取当前启动器的路径
- current_path = sys.argv[0]
- # 如果current_path是以py结尾,则将其转换为.exe
- if current_path.endswith(".py"):
- current_path = current_path[:-3] + ".exe"
- temp_path = current_path + '.tmp'
-
- logger.info(f"下载新版本: {download_url}")
+ # 下载压缩包的全路径
+ download_path = os.path.join(os.getcwd(), os.path.basename(download_url))
+ logger.info(f"下载新版本: {download_url}到{download_path}")
response = requests.get(download_url, stream=True)
if response.status_code == 200:
- with open(temp_path, 'wb') as file:
+ with open(download_path, 'wb') as file:
shutil.copyfileobj(response.raw, file)
+ logger.info("下载完成")
else:
logger.error(f"下载新版本失败: {response.status_code}")
- return f"下载新版本: {response.status_code}"
+ return f"下载新版本失败: {response.status_code}"
- logger.info(f"替换旧版本,{temp_path} -> {current_path}")
- replace_restart(current_path, temp_path)
+ script_path = os.path.join(os.getcwd(), upgrade_script_name)
+ folder_path = os.path.join(os.getcwd(), "_internal")
+ exe_path = os.path.join(os.getcwd(), "launcher.exe")
+ with open(script_path, 'w') as b:
+ TempList = f"@echo off\n"
+ TempList += f"timeout /t 3 /nobreak\n" # 等待进程退出
+ TempList += f"rmdir {folder_path}\n" # 删除_internal
+ TempList += f"del {exe_path}\n" # 删除exe
+ TempList += f"tar -xf {download_path} -C ..\n" # 解压压缩包
+ TempList += f"timeout /t 1 /nobreak\n" # 等待解压
+ TempList += f"start {exe_path}\n" # 启动新程序
+ TempList += f"del {download_path}\n" # 删除压缩包
+ TempList += f"exit"
+ b.write(TempList)
+ # 不显示cmd窗口
+ subprocess.Popen([script_path], creationflags=subprocess.CREATE_NO_WINDOW)
+ os._exit(0)
def rm_site_packages(self):
site_packages_path = Path("./python/Lib/site-packages")
diff --git a/ui/src/pages/Settings.vue b/ui/src/pages/Settings.vue
index cfe9d61..cd21d17 100644
--- a/ui/src/pages/Settings.vue
+++ b/ui/src/pages/Settings.vue
@@ -75,7 +75,7 @@ async function check_update() {
- 最新版本:{{ new_version.name }}
+ 最新版本:{{ `${new_version.tag_name} ${new_version.name}` }}
了解此版本
From 01c4bee95e6a949dfb67f064fe6bf27728f0bc8e Mon Sep 17 00:00:00 2001
From: EightyDollars
Date: Mon, 2 Dec 2024 12:04:08 +0800
Subject: [PATCH 06/45] =?UTF-8?q?=E6=A0=BC=E5=BC=8F=E5=8C=96=E9=83=A8?=
=?UTF-8?q?=E5=88=86=E4=BB=A3=E7=A0=81?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
launcher.py | 21 +++++++++++++--------
1 file changed, 13 insertions(+), 8 deletions(-)
diff --git a/launcher.py b/launcher.py
index 700b7cc..27c42a5 100644
--- a/launcher.py
+++ b/launcher.py
@@ -2,13 +2,14 @@ import json
import mimetypes
from pathlib import Path
from shutil import rmtree
-from subprocess import PIPE, STDOUT, Popen
+from subprocess import CREATE_NO_WINDOW, PIPE, STDOUT, Popen
import requests
import webview
from log import logger
-from python.Lib import shutil, os, subprocess
+import shutil
+import os
mimetypes.add_type("text/html", ".html")
mimetypes.add_type("text/css", ".css")
@@ -23,7 +24,9 @@ config = {
}
config_path = Path("launcher.json")
-get_new_version_url = "https://git-cf.zhaozuohong.vip/api/v1/repos/mower-ng/launcher/releases/latest"
+get_new_version_url = (
+ "https://git-cf.zhaozuohong.vip/api/v1/repos/mower-ng/launcher/releases/latest"
+)
upgrade_script_name = "upgrade.bat"
@@ -95,7 +98,7 @@ class Api:
logger.info(f"下载新版本: {download_url}到{download_path}")
response = requests.get(download_url, stream=True)
if response.status_code == 200:
- with open(download_path, 'wb') as file:
+ with open(download_path, "wb") as file:
shutil.copyfileobj(response.raw, file)
logger.info("下载完成")
else:
@@ -105,7 +108,7 @@ class Api:
script_path = os.path.join(os.getcwd(), upgrade_script_name)
folder_path = os.path.join(os.getcwd(), "_internal")
exe_path = os.path.join(os.getcwd(), "launcher.exe")
- with open(script_path, 'w') as b:
+ with open(script_path, "w") as b:
TempList = f"@echo off\n"
TempList += f"timeout /t 3 /nobreak\n" # 等待进程退出
TempList += f"rmdir {folder_path}\n" # 删除_internal
@@ -117,7 +120,7 @@ class Api:
TempList += f"exit"
b.write(TempList)
# 不显示cmd窗口
- subprocess.Popen([script_path], creationflags=subprocess.CREATE_NO_WINDOW)
+ Popen([script_path], creationflags=CREATE_NO_WINDOW)
os._exit(0)
def rm_site_packages(self):
@@ -141,7 +144,7 @@ class Api:
custom_event(command + "\n")
try:
with Popen(
- command, stdout=PIPE, stderr=STDOUT, shell=True, cwd=cwd, bufsize=0
+ command, stdout=PIPE, stderr=STDOUT, shell=True, cwd=cwd, bufsize=0
) as p:
for data in p.stdout:
try:
@@ -160,7 +163,9 @@ class Api:
if Path(upgrade_script_name).exists():
os.remove(upgrade_script_name)
-window = webview.create_window(f"mower-ng launcher {version}", "ui/dist/index.html", js_api=Api())
+window = webview.create_window(
+ f"mower-ng launcher {version}", "ui/dist/index.html", js_api=Api()
+)
# window = webview.create_window(f"mower-ng launcher {version}", "http://localhost:5173/", js_api=Api())
webview.start()
From 3aad1fe8ffc41bb5c50521f05e3eefd3f5a15ba7 Mon Sep 17 00:00:00 2001
From: li-xiaochen <397721316@qq.com>
Date: Mon, 2 Dec 2024 22:34:54 +0800
Subject: [PATCH 07/45] =?UTF-8?q?=E5=8F=82=E8=80=83mower=E7=9A=84conf?=
=?UTF-8?q?=E9=85=8D=E7=BD=AE?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
.gitignore | 2 +-
launcher.py | 47 ++++++++-----------------------
launcher/__init__.py | 0
launcher/config/__init__.py | 40 ++++++++++++++++++++++++++
launcher/config/conf.py | 36 ++++++++++++++++++++++++
ui/package-lock.json | 56 +++++++++++++++++++++++++++++++++++++
ui/package.json | 1 +
ui/src/App.vue | 25 ++++++++---------
ui/src/main.js | 4 +++
ui/src/pages/Update.vue | 23 ++++-----------
ui/src/stores/config.js | 32 +++++++++++++++++++++
11 files changed, 199 insertions(+), 67 deletions(-)
create mode 100644 launcher/__init__.py
create mode 100644 launcher/config/__init__.py
create mode 100644 launcher/config/conf.py
create mode 100644 ui/src/stores/config.js
diff --git a/.gitignore b/.gitignore
index e32caef..cec6701 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,4 +1,4 @@
-/launcher.json
+/conf.yml
/dist
# Byte-compiled / optimized / DLL files
diff --git a/launcher.py b/launcher.py
index 27c42a5..d4cbeea 100644
--- a/launcher.py
+++ b/launcher.py
@@ -7,6 +7,7 @@ from subprocess import CREATE_NO_WINDOW, PIPE, STDOUT, Popen
import requests
import webview
+from launcher import config
from log import logger
import shutil
import os
@@ -17,26 +18,12 @@ mimetypes.add_type("application/javascript", ".js")
version = "v0.2"
-config = {
- "page": "init",
- "branch": "slow",
- "mirror": "aliyun",
-}
-config_path = Path("launcher.json")
-
get_new_version_url = (
"https://git-cf.zhaozuohong.vip/api/v1/repos/mower-ng/launcher/releases/latest"
)
upgrade_script_name = "upgrade.bat"
-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})
@@ -65,23 +52,15 @@ command_list = {
class Api:
- def get_branch(self):
- return config["branch"]
- def set_branch(self, branch):
- config["branch"] = branch
+ def load_config(self):
+ logger.info("读取配置文件")
+ return config.conf.model_dump()
- 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 save_config(self, conf):
+ logger.info(f"更新配置文件{conf}")
+ config.conf = config.Conf(**conf)
+ config.save_conf()
def get_version(self):
return version
@@ -144,7 +123,7 @@ class Api:
custom_event(command + "\n")
try:
with Popen(
- command, stdout=PIPE, stderr=STDOUT, shell=True, cwd=cwd, bufsize=0
+ command, stdout=PIPE, stderr=STDOUT, shell=True, cwd=cwd, bufsize=0
) as p:
for data in p.stdout:
try:
@@ -163,11 +142,9 @@ class Api:
if Path(upgrade_script_name).exists():
os.remove(upgrade_script_name)
+# url = "ui/dist/index.html"
+url = "http://localhost:5173/"
window = webview.create_window(
- f"mower-ng launcher {version}", "ui/dist/index.html", js_api=Api()
+ f"mower-ng launcher {version}", url, js_api=Api()
)
-# window = webview.create_window(f"mower-ng launcher {version}", "http://localhost:5173/", js_api=Api())
webview.start()
-
-with config_path.open("w") as f:
- json.dump(config, f)
diff --git a/launcher/__init__.py b/launcher/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/launcher/config/__init__.py b/launcher/config/__init__.py
new file mode 100644
index 0000000..c2dbc6e
--- /dev/null
+++ b/launcher/config/__init__.py
@@ -0,0 +1,40 @@
+import os
+
+import yaml
+from yamlcore import CoreDumper, CoreLoader
+
+from launcher.config.conf import Conf
+from python.Lib.pathlib import Path
+
+conf_path = Path(os.path.join(os.getcwd(), "conf.yml"))
+
+
+def save_conf():
+ with conf_path.open("w", encoding="utf8") as f:
+ # json.dump(conf.model_dump(), f, ensure_ascii=False, indent=4) # Use json.dump
+ yaml.dump(
+ conf.model_dump(),
+ f,
+ Dumper=CoreDumper,
+ encoding="utf-8",
+ default_flow_style=False,
+ allow_unicode=True,
+ )
+
+
+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 f:
+ data = yaml.load(f, Loader=CoreLoader)
+ if data is None:
+ data = {}
+ conf = Conf(**data)
+
+
+conf: Conf
+load_conf()
diff --git a/launcher/config/conf.py b/launcher/config/conf.py
new file mode 100644
index 0000000..0f60eec
--- /dev/null
+++ b/launcher/config/conf.py
@@ -0,0 +1,36 @@
+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():
+ if name not in data:
+ if field.default is PydanticUndefined:
+ data[name] = field.annotation()
+ else:
+ data[name] = field.default
+ return data
+
+
+class Total(ConfModel):
+ """整体"""
+ # 所在页面
+ page: str = "init"
+
+
+class UpdatePart(ConfModel):
+ """更新代码"""
+ # mower-ng 代码分支
+ branch: str = "slow"
+ # PyPI 仓库镜像
+ mirror: str = "aliyun"
+
+
+class Conf(
+ Total,
+ UpdatePart,
+):
+ pass
diff --git a/ui/package-lock.json b/ui/package-lock.json
index bc18944..3e30e87 100644
--- a/ui/package-lock.json
+++ b/ui/package-lock.json
@@ -8,6 +8,7 @@
"name": "ui",
"version": "0.0.0",
"dependencies": {
+ "pinia": "^2.2.8",
"vue": "^3.5.11"
},
"devDependencies": {
@@ -1131,6 +1132,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": {
"version": "10.0.0",
"resolved": "https://registry.npmjs.org/@vue/eslint-config-prettier/-/eslint-config-prettier-10.0.0.tgz",
@@ -2534,6 +2540,56 @@
"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": {
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/pkg-types/-/pkg-types-1.2.0.tgz",
diff --git a/ui/package.json b/ui/package.json
index cec47a3..4e707b9 100644
--- a/ui/package.json
+++ b/ui/package.json
@@ -11,6 +11,7 @@
"format": "prettier --write src/"
},
"dependencies": {
+ "pinia": "^2.2.8",
"vue": "^3.5.11"
},
"devDependencies": {
diff --git a/ui/src/App.vue b/ui/src/App.vue
index 85435b9..be241cb 100644
--- a/ui/src/App.vue
+++ b/ui/src/App.vue
@@ -5,16 +5,12 @@ import Update from '@/pages/Update.vue'
import Fix from '@/pages/Fix.vue'
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 page = ref(null)
-
-function load_config() {
- pywebview.api.get_page().then((value) => {
- page.value = value
- loading.value = false
- })
-}
+let conf
async function init_version() {
version.value = await pywebview.api.get_version()
@@ -23,6 +19,12 @@ async function init_version() {
update_able.value = true
}
}
+async function initialize_config() {
+ await configStore.load_config()
+ conf = configStore.config
+ await init_version()
+ loading.value = false
+}
const log = ref('')
provide('log', log)
@@ -36,12 +38,10 @@ watch(log, () => {
onMounted(() => {
if (window.pywebview && pywebview.api) {
- load_config()
- init_version()
+ initialize_config()
} else {
window.addEventListener('pywebviewready', () => {
- load_config()
- init_version()
+ initialize_config()
})
}
window.addEventListener('log', (e) => {
@@ -51,7 +51,6 @@ onMounted(() => {
function set_page(value) {
log.value = ''
- pywebview.api.set_page(value)
}
const running = ref(false)
@@ -80,7 +79,7 @@ provide('new_version', new_version)
type="card"
placement="left"
class="container"
- :default-value="page"
+ v-model:value="conf.page"
@update:value="set_page"
>
diff --git a/ui/src/main.js b/ui/src/main.js
index 1877952..e8343a7 100644
--- a/ui/src/main.js
+++ b/ui/src/main.js
@@ -2,6 +2,10 @@ import 'vfonts/Lato.css'
import 'vfonts/FiraCode.css'
import { createApp } from 'vue'
+import { createPinia } from 'pinia'
import App from './App.vue'
+
const app = createApp(App)
+const pinia = createPinia()
+app.use(pinia)
app.mount('#app')
diff --git a/ui/src/pages/Update.vue b/ui/src/pages/Update.vue
index 448108a..1d7019a 100644
--- a/ui/src/pages/Update.vue
+++ b/ui/src/pages/Update.vue
@@ -1,23 +1,10 @@
-
+
-
+
@@ -23,10 +49,27 @@ const log_ele = inject('log_ele')
height: 100% !important;
box-sizing: border-box;
}
+
+.selectable-log {
+ user-select: text;
+}
From 478bcd5f434c9742c423facd265b122edeec003f Mon Sep 17 00:00:00 2001
From: li-xiaochen <397721316@qq.com>
Date: Sat, 28 Dec 2024 20:14:01 +0800
Subject: [PATCH 26/45] =?UTF-8?q?=E6=96=B0=E5=A2=9E=E5=8A=9F=E8=83=BD?=
=?UTF-8?q?=EF=BC=9A=E6=89=A7=E8=A1=8C=E5=91=BD=E4=BB=A4=E6=97=B6=E6=A0=B9?=
=?UTF-8?q?=E6=8D=AE=E5=91=BD=E4=BB=A4=E8=BE=93=E5=87=BA=E8=BF=94=E5=9B=9E?=
=?UTF-8?q?=E9=94=99=E8=AF=AF=E6=8F=90=E7=A4=BA=E4=BF=A1=E6=81=AF?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
launcher/file/utils.py | 14 ++++++++++++++
launcher/webview/api.py | 42 +++++++++++++++++++++++++++++++++--------
2 files changed, 48 insertions(+), 8 deletions(-)
diff --git a/launcher/file/utils.py b/launcher/file/utils.py
index cd8a378..9bb040b 100644
--- a/launcher/file/utils.py
+++ b/launcher/file/utils.py
@@ -14,3 +14,17 @@ 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_path = command.split(" ")[0]
+ if command_path == "start":
+ 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_path)) + ".exe"
+ return os.path.exists(full_command_path), full_command_path
diff --git a/launcher/webview/api.py b/launcher/webview/api.py
index c67ee37..ac440c8 100644
--- a/launcher/webview/api.py
+++ b/launcher/webview/api.py
@@ -14,7 +14,7 @@ from launcher.constants import download_git_url, download_python_url, get_new_ve
mirror_list
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
+from launcher.file.utils import ensure_directory_exists, check_command_path
from launcher.log import logger
from launcher.sys_config import sys_config
from launcher.webview.events import custom_event, LogType
@@ -35,11 +35,27 @@ command_list = {
}
-def read_stream(stream, log_type):
+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 read_stream(stream, log_type, output_list=None):
def process_lines(text_io):
for line in iter(text_io.readline, ''):
- text = line.rstrip('\n')
- custom_event(log_type, f"{text.strip()}")
+ text = line.rstrip('\n').strip()
+ custom_event(log_type, text)
+ if output_list is not None:
+ output_list.append(text)
detected_encoding = 'utf-8'
text_io = io.TextIOWrapper(stream, encoding=detected_encoding, errors='replace')
@@ -129,26 +145,36 @@ class Api:
if callable(command):
return "success" if command() else "failed"
if cwd is not None:
- custom_event(LogType.execute_command, f"路径:{cwd}")
+ 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.PIPE, shell=True, cwd=cwd, bufsize=0,
universal_newlines=False
) as p:
stdout_thread = threading.Thread(target=read_stream, args=(p.stdout, LogType.command_out))
- stderr_thread = threading.Thread(target=read_stream, args=(p.stderr, LogType.command_out))
+ stderr_thread = threading.Thread(target=read_stream,
+ args=(p.stderr, LogType.command_out, stdout_stderr))
stdout_thread.start()
stderr_thread.start()
stdout_thread.join()
stderr_thread.join()
+
if p.returncode == 0:
return "success"
else:
- logger.error(f"{command} 运行失败")
+ 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, repr(e))
+ custom_event(LogType.error, str(e))
+ return "failed"
From 5cdf9d752fe0aa2ba1326150cd241d2ecfb9d4b4 Mon Sep 17 00:00:00 2001
From: li-xiaochen <397721316@qq.com>
Date: Sat, 28 Dec 2024 20:15:04 +0800
Subject: [PATCH 27/45] =?UTF-8?q?=E5=8A=9F=E8=83=BD=E4=BF=AE=E5=A4=8D?=
=?UTF-8?q?=EF=BC=9A=E4=BF=AE=E5=A4=8D=E4=BE=9D=E8=B5=96=E6=97=B6=E5=BC=82?=
=?UTF-8?q?=E5=B8=B8=E5=8D=A1=E6=AD=BB?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
launcher/webview/api.py | 26 ++++++++++++++++----------
1 file changed, 16 insertions(+), 10 deletions(-)
diff --git a/launcher/webview/api.py b/launcher/webview/api.py
index ac440c8..a869430 100644
--- a/launcher/webview/api.py
+++ b/launcher/webview/api.py
@@ -125,18 +125,24 @@ class Api:
os._exit(0)
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目录不存在"
+ 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):
- python_scripts_path = Path("./python/Scripts")
- if python_scripts_path.exists():
- rmtree(python_scripts_path)
- return "Scripts目录移除成功"
- return "python\\Scripts目录不存在"
+ 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, cwd=None):
command = command_list[command]
From 8ed883202b8555d1addaf0193eee79cdbebdac1d Mon Sep 17 00:00:00 2001
From: li-xiaochen <397721316@qq.com>
Date: Sat, 28 Dec 2024 21:05:28 +0800
Subject: [PATCH 28/45] =?UTF-8?q?=E6=9E=84=E5=BB=BA=EF=BC=9Arequirements?=
=?UTF-8?q?=E6=B7=BB=E5=8A=A0pyinstaller?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
requirements.in | 1 +
requirements.txt | 17 +++++++++++++++++
2 files changed, 18 insertions(+)
diff --git a/requirements.in b/requirements.in
index 6e921b6..e8f09e4 100644
--- a/requirements.in
+++ b/requirements.in
@@ -2,3 +2,4 @@ pywebview==5.1
requests==2.32.3
py7zr==0.22.0
pydantic==2.10.3
+pyinstaller==6.11.1
diff --git a/requirements.txt b/requirements.txt
index f44f0c6..7dbbb07 100644
--- a/requirements.txt
+++ b/requirements.txt
@@ -6,6 +6,8 @@
#
--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
@@ -26,6 +28,12 @@ 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
@@ -42,12 +50,18 @@ 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
@@ -61,3 +75,6 @@ typing-extensions==4.12.2
# pywebview
urllib3==2.2.3
# via requests
+
+# The following packages are considered to be unsafe in a requirements file:
+# setuptools
From 0661b6bbc31d02ab2798fc99b1bb89c578e258f0 Mon Sep 17 00:00:00 2001
From: li-xiaochen <397721316@qq.com>
Date: Sat, 28 Dec 2024 21:05:35 +0800
Subject: [PATCH 29/45] =?UTF-8?q?=E5=8F=91=E5=B8=83v0.5=E7=89=88=E6=9C=AC?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
launcher/sys_config/config_dist.json | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/launcher/sys_config/config_dist.json b/launcher/sys_config/config_dist.json
index a9c2eb5..b382c15 100644
--- a/launcher/sys_config/config_dist.json
+++ b/launcher/sys_config/config_dist.json
@@ -1,5 +1,5 @@
{
- "version": "v0.4",
+ "version": "v0.5",
"url": "ui/dist/index.html",
"log_level": "ERROR",
"debug": false
From 9295d9f2cfcd6f775d5976c97801c54029caab04 Mon Sep 17 00:00:00 2001
From: li-xiaochen <397721316@qq.com>
Date: Tue, 7 Jan 2025 13:29:00 +0800
Subject: [PATCH 30/45] =?UTF-8?q?=E7=95=8C=E9=9D=A2=E4=BC=98=E5=8C=96=201.?=
=?UTF-8?q?=E6=97=A5=E5=BF=97=E7=9A=84=E4=B8=AD=E6=96=87=E5=AD=97=E4=BD=93?=
=?UTF-8?q?=E6=94=B9=E4=B8=BA=E5=BE=AE=E8=BD=AF=E9=9B=85=E9=BB=91=202.?=
=?UTF-8?q?=E5=B8=AE=E5=8A=A9=E6=96=87=E6=A1=A3=E6=8C=89=E9=92=AE=E5=A4=96?=
=?UTF-8?q?=E8=BE=B9=E8=B7=9D=E8=B0=83=E6=95=B4=E5=88=B0=E5=92=8C=E6=97=A5?=
=?UTF-8?q?=E5=BF=97=E7=AA=97=E5=B7=A6=E8=BE=B9=E8=B7=9D=E4=B8=80=E8=87=B4?=
=?UTF-8?q?=203.=E6=89=A9=E5=A4=A7=E9=BB=98=E8=AE=A4=E7=AA=97=E5=8F=A3?=
=?UTF-8?q?=E5=A4=A7=E5=B0=8F=EF=BC=8C=E4=BD=BF=E5=BE=97PyPI=E5=8F=AF?=
=?UTF-8?q?=E4=BB=A5=E5=88=9D=E5=A7=8B=E5=B1=95=E7=A4=BA=E5=88=B0=E4=B8=80?=
=?UTF-8?q?=E8=A1=8C=204.=E8=A1=A8=E5=8D=95label=E6=94=B9=E4=B8=BA?=
=?UTF-8?q?=E5=9E=82=E7=9B=B4=E5=B1=85=E4=B8=AD=205.=E8=AE=BE=E7=BD=AEtab?=
=?UTF-8?q?=E9=A1=B5=E7=9A=84=E2=80=9C=E6=96=B0=E2=80=9D=E6=A0=87=E7=AD=BE?=
=?UTF-8?q?=E8=AE=BE=E7=BD=AE=E5=9E=82=E7=9B=B4=E5=B1=85=E4=B8=AD=EF=BC=8C?=
=?UTF-8?q?=E5=B9=B6=E4=B8=94=E4=B8=8D=E8=83=BD=E5=BD=B1=E5=93=8D=E8=8F=9C?=
=?UTF-8?q?=E5=8D=95=E6=A0=8F=E7=9A=84=E9=AB=98=E5=BA=A6?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
launcher/webview/__init__.py | 2 +-
ui/src/App.vue | 26 ++++++++++++---
ui/src/components/LogComponent.vue | 52 ++++++++++++++----------------
ui/src/main.js | 1 +
ui/src/pages/Settings.vue | 3 +-
ui/src/pages/Update.vue | 5 +--
ui/src/styles/global.css | 43 ++++++++++++++++++++++++
ui/src/styles/styles.js | 3 ++
8 files changed, 99 insertions(+), 36 deletions(-)
create mode 100644 ui/src/styles/global.css
create mode 100644 ui/src/styles/styles.js
diff --git a/launcher/webview/__init__.py b/launcher/webview/__init__.py
index 1129706..f450a28 100644
--- a/launcher/webview/__init__.py
+++ b/launcher/webview/__init__.py
@@ -9,5 +9,5 @@ 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())
+ js_api=Api(), width=850, height=600)
webview.start(debug=sys_config.get('debug'))
diff --git a/ui/src/App.vue b/ui/src/App.vue
index 06d73a2..cffa4df 100644
--- a/ui/src/App.vue
+++ b/ui/src/App.vue
@@ -89,6 +89,7 @@ provide('new_version', new_version)
class="container"
v-model:value="conf.page"
@update:value="set_page"
+ justify-content="center"
>
@@ -96,15 +97,17 @@ provide('new_version', new_version)
-
- 设置
- 新
-
+
+ 设置
+ 新
+
- 帮助文档
+
+ 帮助文档
+
@@ -117,4 +120,17 @@ provide('new_version', new_version)
width: 100vw;
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%);
+}
diff --git a/ui/src/components/LogComponent.vue b/ui/src/components/LogComponent.vue
index 7fc5d72..47d1339 100644
--- a/ui/src/components/LogComponent.vue
+++ b/ui/src/components/LogComponent.vue
@@ -5,27 +5,44 @@ import hljs from 'highlight.js/lib/core'
const log = inject('log')
const log_ele = inject('log_ele')
+const chinesePattern = {
+ className: 'chinese',
+ begin: /[\u4e00-\u9fa5]+/
+}
+
hljs.registerLanguage('naive-log', () => ({
contains: [
{
className: 'info',
- begin: /\[信息\]/,
- end: /$/
+ begin: /^\[信息\]/,
+ end: /$/,
+ returnBegin: true,
+ returnEnd: true,
+ contains: [chinesePattern]
},
{
className: 'error',
- begin: /\[错误\]/,
- end: /$/
+ begin: /^\[错误\]/,
+ end: /$/,
+ returnBegin: true,
+ returnEnd: true,
+ contains: [chinesePattern]
},
{
className: 'execute_command',
- begin: /\[执行命令\]/,
- end: /$/
+ begin: /^\[执行命令\]/,
+ end: /$/,
+ returnBegin: true,
+ returnEnd: true,
+ contains: [chinesePattern]
},
{
className: 'command_out',
- begin: /\[命令输出\]/,
- end: /$/
+ begin: /^\[命令输出\]/,
+ end: /$/,
+ returnBegin: true,
+ returnEnd: true,
+ contains: [chinesePattern]
}
]
}))
@@ -54,22 +71,3 @@ hljs.registerLanguage('naive-log', () => ({
user-select: text;
}
-
-
diff --git a/ui/src/main.js b/ui/src/main.js
index e8343a7..132098e 100644
--- a/ui/src/main.js
+++ b/ui/src/main.js
@@ -1,5 +1,6 @@
import 'vfonts/Lato.css'
import 'vfonts/FiraCode.css'
+import './styles/global.css'
import { createApp } from 'vue'
import { createPinia } from 'pinia'
diff --git a/ui/src/pages/Settings.vue b/ui/src/pages/Settings.vue
index cd21d17..120ff2c 100644
--- a/ui/src/pages/Settings.vue
+++ b/ui/src/pages/Settings.vue
@@ -1,5 +1,6 @@
-
-
- 单开运行
-
-
- 多开器
-
+
+
+
+
+ 单开运行
+ 多开器
+
+
+
+
@@ -34,4 +31,4 @@ function manager() {
width: 120px;
height: 48px;
}
-
+
\ No newline at end of file
diff --git a/ui/src/pages/Settings.vue b/ui/src/pages/Settings.vue
index 120ff2c..5428726 100644
--- a/ui/src/pages/Settings.vue
+++ b/ui/src/pages/Settings.vue
@@ -91,5 +91,6 @@ async function check_update() {
+
diff --git a/ui/src/stores/config.js b/ui/src/stores/config.js
index f20625c..e33269a 100644
--- a/ui/src/stores/config.js
+++ b/ui/src/stores/config.js
@@ -3,10 +3,12 @@ import { defineStore } from 'pinia'
export const useConfigStore = defineStore('config', () => {
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
- this.is_already_show_doc = conf.is_already_show_doc
}
}
From 25f9915fccb31544a3f2bd06013f072bd20fc7f5 Mon Sep 17 00:00:00 2001
From: li-xiaochen <397721316@qq.com>
Date: Sat, 25 Jan 2025 17:49:17 +0800
Subject: [PATCH 32/45] =?UTF-8?q?ruff=E6=A0=BC=E5=BC=8F=E5=8C=96=E4=BB=A3?=
=?UTF-8?q?=E7=A0=81?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
launcher.py | 3 +--
launcher/config/conf.py | 2 ++
launcher/constants.py | 4 ++-
launcher/file/download.py | 22 ++++++++++-----
launcher/file/extract.py | 12 ++++++---
launcher/file/utils.py | 6 +++--
launcher/log.py | 6 ++---
launcher/sys_config/__init__.py | 13 ++++-----
launcher/webview/__init__.py | 11 +++++---
launcher/webview/api.py | 48 ++++++++++++++++++++++-----------
10 files changed, 84 insertions(+), 43 deletions(-)
diff --git a/launcher.py b/launcher.py
index 115cc4f..5e92a69 100644
--- a/launcher.py
+++ b/launcher.py
@@ -9,8 +9,7 @@ mimetypes.add_type("text/html", ".html")
mimetypes.add_type("text/css", ".css")
mimetypes.add_type("application/javascript", ".js")
-if __name__ == '__main__':
-
+if __name__ == "__main__":
# 如果当前路径存在临时文件夹,则删除
if Path(update_tmp_folder).exists():
shutil.rmtree(update_tmp_folder)
diff --git a/launcher/config/conf.py b/launcher/config/conf.py
index e411765..3f9eff2 100644
--- a/launcher/config/conf.py
+++ b/launcher/config/conf.py
@@ -17,6 +17,7 @@ class ConfModel(BaseModel):
class Total(ConfModel):
"""整体"""
+
# 所在页面
page: str = "init"
# 是否已展示帮助文档
@@ -25,6 +26,7 @@ class Total(ConfModel):
class UpdatePart(ConfModel):
"""更新代码"""
+
# mower-ng 代码分支
branch: str = "slow"
# PyPI 仓库镜像
diff --git a/launcher/constants.py b/launcher/constants.py
index 213679a..8d9d0d4 100644
--- a/launcher/constants.py
+++ b/launcher/constants.py
@@ -10,7 +10,9 @@ update_tmp_folder = "download_tmp"
upgrade_script_name = "upgrade.bat"
# 获取最新版本发布信息
-get_new_version_url = "https://git-cf.zhaozuohong.vip/api/v1/repos/mower-ng/launcher/releases/latest"
+get_new_version_url = (
+ "https://git-cf.zhaozuohong.vip/api/v1/repos/mower-ng/launcher/releases/latest"
+)
# 下载新版本压缩包名
file_name = "launcher.7z"
diff --git a/launcher/file/download.py b/launcher/file/download.py
index 2acf26a..03825f8 100644
--- a/launcher/file/download.py
+++ b/launcher/file/download.py
@@ -25,7 +25,7 @@ def download_file(download_name, download_url, destination_folder):
response = requests.get(download_url, stream=True)
if response.status_code == 200:
- total_size = int(response.headers.get('content-length', 0))
+ total_size = int(response.headers.get("content-length", 0))
downloaded_size = 0
start_time = time.time()
last_update_time = time.time() # 记录上次更新时间
@@ -43,7 +43,9 @@ def download_file(download_name, download_url, destination_folder):
else:
download_speed = 0
- progress_percent = (downloaded_size / total_size) * 100 if total_size != 0 else 0
+ progress_percent = (
+ (downloaded_size / total_size) * 100 if total_size != 0 else 0
+ )
# 检查是否需要更新进度信息,每1秒更新一次
if current_time - last_update_time >= 1:
@@ -52,19 +54,25 @@ def download_file(download_name, download_url, destination_folder):
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}")
+ 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
+ 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}")
+ 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
diff --git a/launcher/file/extract.py b/launcher/file/extract.py
index 1588c41..a1c523c 100644
--- a/launcher/file/extract.py
+++ b/launcher/file/extract.py
@@ -37,7 +37,9 @@ class MyExtractCallback(ExtractCallback):
pass
-def extract_7z_file(file_name, file_path, destination_folder, delete_after_extract=True):
+def extract_7z_file(
+ file_name, file_path, destination_folder, delete_after_extract=True
+):
"""
解压7z文件到指定文件夹
:param file_name: 7z文件的名称
@@ -52,14 +54,16 @@ def extract_7z_file(file_name, file_path, destination_folder, delete_after_extra
custom_event(LogType.info, f"开始解压文件: {file_name}")
try:
start_time = time.time()
- with py7zr.SevenZipFile(file_path, mode='r') as z:
+ 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}")
+ 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
diff --git a/launcher/file/utils.py b/launcher/file/utils.py
index 9bb040b..5ab58dc 100644
--- a/launcher/file/utils.py
+++ b/launcher/file/utils.py
@@ -3,7 +3,7 @@ import os
def format_size(size_bytes):
"""格式化文件大小为人类可读的形式"""
- for unit in ['B', 'KB', 'MB', 'GB', 'TB']:
+ for unit in ["B", "KB", "MB", "GB", "TB"]:
if size_bytes < 1024:
return f"{size_bytes:.2f} {unit}"
size_bytes /= 1024
@@ -26,5 +26,7 @@ def check_command_path(command, cwd=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_path)) + ".exe"
+ full_command_path = (
+ os.path.abspath(os.path.join(exec_command_path, command_path)) + ".exe"
+ )
return os.path.exists(full_command_path), full_command_path
diff --git a/launcher/log.py b/launcher/log.py
index 1797c98..7588b05 100644
--- a/launcher/log.py
+++ b/launcher/log.py
@@ -9,13 +9,13 @@ from launcher.sys_config import sys_config
# 配置日志
def setup_logger():
- log_level = sys_config.get('log_level')
+ log_level = sys_config.get("log_level")
logger = logging.getLogger("launcher.log")
logger.setLevel(log_level)
# 设置标准输出编码为 UTF-8
- sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
+ sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding="utf-8")
# 控制台输出
console_handler = logging.StreamHandler()
@@ -24,7 +24,7 @@ def setup_logger():
# 文件输出
file_path = os.path.join(os.getcwd(), "launcher.log")
file_handler = RotatingFileHandler(
- file_path, maxBytes=5 * 1024 * 1024, backupCount=3, encoding='utf-8'
+ file_path, maxBytes=5 * 1024 * 1024, backupCount=3, encoding="utf-8"
)
file_handler.setLevel(logging.INFO)
diff --git a/launcher/sys_config/__init__.py b/launcher/sys_config/__init__.py
index 94853c0..b7be326 100644
--- a/launcher/sys_config/__init__.py
+++ b/launcher/sys_config/__init__.py
@@ -7,6 +7,7 @@ class SysConfig:
"""
读取系统配置文件
"""
+
# 版本
version: str
# ui路径
@@ -22,25 +23,25 @@ class SysConfig:
self.load_config()
def get_config_path(self):
- if getattr(sys, 'frozen', False):
+ if getattr(sys, "frozen", False):
# logger.error("打包配置")
# 如果是打包后的可执行文件
base_path = sys._MEIPASS
- config_subdir = 'launcher/sys_config' # 添加子目录
- config_filename = 'config_dist.json'
+ 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_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:
+ with open(self.config_path, "r", encoding="utf-8") as file:
self.config = json.load(file)
except FileNotFoundError:
pass
diff --git a/launcher/webview/__init__.py b/launcher/webview/__init__.py
index f450a28..09ae4d6 100644
--- a/launcher/webview/__init__.py
+++ b/launcher/webview/__init__.py
@@ -8,6 +8,11 @@ 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'))
+ 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"))
diff --git a/launcher/webview/api.py b/launcher/webview/api.py
index bee397a..1960b38 100644
--- a/launcher/webview/api.py
+++ b/launcher/webview/api.py
@@ -9,8 +9,14 @@ 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
+from launcher.constants import (
+ download_git_url,
+ download_python_url,
+ get_new_version_url,
+ upgrade_script_name,
+ mirror_list,
+ file_name,
+)
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
@@ -20,7 +26,9 @@ from launcher.webview.events import custom_event, LogType
command_list = {
"download_git": lambda: init_download("git", download_git_url, os.getcwd()),
- "download_python": lambda: init_download("python", download_python_url, os.getcwd()),
+ "download_python": lambda: init_download(
+ "python", download_python_url, os.getcwd()
+ ),
"lfs": "git\\bin\\git lfs install",
"ensurepip": "python\\python -m ensurepip --default-pip",
"clone": "git\\bin\\git -c lfs.concurrenttransfers=100 clone https://git-cf.zhaozuohong.vip/mower-ng/mower-ng.git --branch slow",
@@ -49,9 +57,7 @@ def parse_stderr(stderr_output):
def check_command_end(command_key, output):
- end_keywords = {
- "webview": {"WebSocket客户端建立连接": "mower_ng已成功运行"}
- }
+ end_keywords = {"webview": {"WebSocket客户端建立连接": "mower_ng已成功运行"}}
if command_key in end_keywords:
keywords = end_keywords[command_key]
for keyword in keywords:
@@ -62,7 +68,6 @@ def check_command_end(command_key, output):
class Api:
-
def load_config(self):
logger.info("读取配置文件")
return config.conf.model_dump()
@@ -146,30 +151,43 @@ class Api:
# 执行命令前先判断命令路径是否存在
exist, command_path = check_command_path(command, cwd)
if not exist:
- custom_event(LogType.error, f"命令路径不存在:{command_path} 请尝试依赖修复并重新初始化。")
+ 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
+ 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()
+ 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')
+ 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')
+ text_io = io.TextIOWrapper(
+ p.stdout, encoding="gbk", errors="replace"
+ )
process_lines(text_io)
finally:
text_io.close()
From 942d93417b79c2b0415dc66631d0373176d65bf8 Mon Sep 17 00:00:00 2001
From: li-xiaochen <397721316@qq.com>
Date: Tue, 28 Jan 2025 16:13:53 +0800
Subject: [PATCH 33/45] =?UTF-8?q?=E6=97=A5=E5=BF=97=E6=9C=80=E5=A4=9A?=
=?UTF-8?q?=E4=BF=9D=E7=95=99200=E8=A1=8C?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
ui/src/App.vue | 23 +++++++++++++++--------
ui/src/components/FloatButton.vue | 2 +-
ui/src/components/LogComponent.vue | 2 +-
3 files changed, 17 insertions(+), 10 deletions(-)
diff --git a/ui/src/App.vue b/ui/src/App.vue
index cffa4df..eb2e815 100644
--- a/ui/src/App.vue
+++ b/ui/src/App.vue
@@ -34,15 +34,19 @@ async function initialize_config() {
await init_version()
}
-const log = ref('')
+const log = ref([])
provide('log', log)
const log_ele = ref(null)
provide('log_ele', log_ele)
-watch(log, () => {
- nextTick(() => {
- log_ele.value?.scrollTo({ position: 'bottom' })
- })
-})
+watch(
+ log,
+ () => {
+ nextTick(() => {
+ log_ele.value?.scrollTo({ position: 'bottom' })
+ })
+ },
+ { deep: true }
+)
onMounted(() => {
if (window.pywebview && pywebview.api) {
@@ -53,12 +57,15 @@ onMounted(() => {
})
}
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) {
- log.value = ''
+ log.value.splice(0)
}
const running = ref(false)
diff --git a/ui/src/components/FloatButton.vue b/ui/src/components/FloatButton.vue
index 06f16c1..de0ff86 100644
--- a/ui/src/components/FloatButton.vue
+++ b/ui/src/components/FloatButton.vue
@@ -11,7 +11,7 @@ const current_state = inject('current_state')
const notification = useNotification()
async function start() {
- log.value = ''
+ log.value = []
running.value = true
for (const [i, step] of steps.value.entries()) {
current_step.value = i + 1
diff --git a/ui/src/components/LogComponent.vue b/ui/src/components/LogComponent.vue
index 47d1339..b16c676 100644
--- a/ui/src/components/LogComponent.vue
+++ b/ui/src/components/LogComponent.vue
@@ -51,7 +51,7 @@ hljs.registerLanguage('naive-log', () => ({
-
+
From dc32d7e53e30384b2b36b08c0d42811ec7e231aa Mon Sep 17 00:00:00 2001
From: li-xiaochen <397721316@qq.com>
Date: Sun, 23 Feb 2025 18:11:26 +0800
Subject: [PATCH 34/45] =?UTF-8?q?=E6=96=B0=E5=A2=9E=E5=8A=9F=E8=83=BD?=
=?UTF-8?q?=EF=BC=9A=E5=90=88=E5=B9=B6=E5=A4=9A=E5=BC=80=E5=99=A8?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
.gitignore | 2 +-
launcher/config/conf.py | 25 ++-
launcher/constants.py | 3 +
launcher/file/utils.py | 7 +-
launcher/instances/__init__.py | 0
launcher/instances/manager.py | 129 ++++++++++++++
launcher/sys_config/config_dist.json | 2 +-
launcher/sys_config/config_local.json | 2 +-
launcher/webview/api.py | 62 ++++++-
ui/src/pages/Launch.vue | 238 ++++++++++++++++++++++++--
ui/src/stores/config.js | 20 ++-
11 files changed, 456 insertions(+), 34 deletions(-)
create mode 100644 launcher/instances/__init__.py
create mode 100644 launcher/instances/manager.py
diff --git a/.gitignore b/.gitignore
index 768ee45..7ccfbfe 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,6 +1,7 @@
/conf.yml
/conf.json
/dist
+/instances/
# Byte-compiled / optimized / DLL files
__pycache__/
@@ -66,7 +67,6 @@ db.sqlite3
db.sqlite3-journal
# Flask stuff:
-instance/
.webassets-cache
# Scrapy stuff:
diff --git a/launcher/config/conf.py b/launcher/config/conf.py
index 3f9eff2..a5df264 100644
--- a/launcher/config/conf.py
+++ b/launcher/config/conf.py
@@ -1,3 +1,5 @@
+from typing import List
+
from pydantic import BaseModel, model_validator
from pydantic_core import PydanticUndefined
@@ -7,9 +9,10 @@ class ConfModel(BaseModel):
@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] = field.annotation()
+ data[name] = expected_type
else:
data[name] = field.default
return data
@@ -33,8 +36,28 @@ class UpdatePart(ConfModel):
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 Conf(
Total,
UpdatePart,
+ LaunchPart,
):
pass
diff --git a/launcher/constants.py b/launcher/constants.py
index 8d9d0d4..3e519e2 100644
--- a/launcher/constants.py
+++ b/launcher/constants.py
@@ -27,3 +27,6 @@ mirror_list = {
"tuna": "https://mirrors.tuna.tsinghua.edu.cn/pypi/web/simple",
"sjtu": "https://mirror.sjtu.edu.cn/pypi/web/simple",
}
+
+# 实例文件夹名
+instances_folder_name = "instances"
diff --git a/launcher/file/utils.py b/launcher/file/utils.py
index 5ab58dc..b9dd968 100644
--- a/launcher/file/utils.py
+++ b/launcher/file/utils.py
@@ -20,13 +20,14 @@ def check_command_path(command, cwd=None):
"""检查命令路径是否存在exe文件
:return 是否存在,命令exe文件全路径
"""
- command_path = command.split(" ")[0]
- if command_path == "start":
+ 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_path)) + ".exe"
+ os.path.abspath(os.path.join(exec_command_path, command_name)) + ".exe"
)
return os.path.exists(full_command_path), full_command_path
diff --git a/launcher/instances/__init__.py b/launcher/instances/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/launcher/instances/manager.py b/launcher/instances/manager.py
new file mode 100644
index 0000000..f0ff759
--- /dev/null
+++ b/launcher/instances/manager.py
@@ -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)}
diff --git a/launcher/sys_config/config_dist.json b/launcher/sys_config/config_dist.json
index b382c15..1764210 100644
--- a/launcher/sys_config/config_dist.json
+++ b/launcher/sys_config/config_dist.json
@@ -1,6 +1,6 @@
{
"version": "v0.5",
"url": "ui/dist/index.html",
- "log_level": "ERROR",
+ "log_level": "INFO",
"debug": false
}
\ No newline at end of file
diff --git a/launcher/sys_config/config_local.json b/launcher/sys_config/config_local.json
index d74400e..e42e05a 100644
--- a/launcher/sys_config/config_local.json
+++ b/launcher/sys_config/config_local.json
@@ -1,6 +1,6 @@
{
"version": "dev",
"url": "http://localhost:5173/",
- "log_level": "INFO",
+ "log_level": "DEBUG",
"debug": true
}
\ No newline at end of file
diff --git a/launcher/webview/api.py b/launcher/webview/api.py
index 1960b38..b24ab1d 100644
--- a/launcher/webview/api.py
+++ b/launcher/webview/api.py
@@ -1,6 +1,8 @@
import io
import os
+import shutil
import subprocess
+import threading
from _winapi import CREATE_NO_WINDOW
from pathlib import Path
from shutil import rmtree
@@ -9,6 +11,7 @@ from subprocess import Popen
import requests
from launcher import config
+from launcher.config.conf import LaunchPart
from launcher.constants import (
download_git_url,
download_python_url,
@@ -16,10 +19,12 @@ from launcher.constants import (
upgrade_script_name,
mirror_list,
file_name,
+ instances_folder_name,
)
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.webview.events import custom_event, LogType
@@ -37,8 +42,8 @@ command_list = {
"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": "..\\python\\pythonw webview_ui.py",
- "manager": "start ..\\python\\pythonw manager.py",
+ "webview": lambda instance_path="": f'..\\python\\pythonw webview_ui.py "{instance_path}"',
+ "open_folder": lambda folder_path: f"explorer {folder_path}",
}
@@ -69,11 +74,11 @@ def check_command_end(command_key, output):
class Api:
def load_config(self):
- logger.info("读取配置文件")
+ logger.debug("读取配置文件")
return config.conf.model_dump()
def save_config(self, conf):
- logger.info(f"更新配置文件{conf}")
+ logger.debug(f"更新配置文件{conf}")
config.conf = config.Conf(**conf)
config.save_conf()
@@ -139,10 +144,13 @@ class Api:
except Exception as e:
return repr(e)
- def run(self, command_key, cwd=None):
+ def run(self, command_key, cwd=None, params={}):
command = command_list[command_key]
if callable(command):
- command = command()
+ try:
+ command = command(**params)
+ except TypeError:
+ command = command()
if callable(command):
return "success" if command() else "failed"
if cwd is not None:
@@ -202,3 +210,45 @@ class Api:
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 start_checked_instance(self):
+ 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"}]
+
+ def _run_instance(instance: LaunchPart.Instance):
+ self.run(
+ "webview",
+ "mower-ng",
+ {"instance_path": instance.path},
+ )
+
+ # 创建并启动线程 目前进程依然有阻塞,待优化
+ for instance in checked_instances:
+ thread = threading.Thread(
+ target=_run_instance, args=(instance,), daemon=True
+ )
+ thread.start()
+
+ 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()
diff --git a/ui/src/pages/Launch.vue b/ui/src/pages/Launch.vue
index c84940c..3c15f37 100644
--- a/ui/src/pages/Launch.vue
+++ b/ui/src/pages/Launch.vue
@@ -1,34 +1,238 @@
-
-
-
- 单开运行
- 多开器
+
+
+
+
+
+
+ 添加实例
+
+
+
+
+
+ 启动所选实例
+
+
+
+
+
+
+ 迁移配置
+
+
+
+
+
+
+ 显示日志
+
+
+
+
+
+ 全选
+
+
+
+
+
+
+
+
+ {{ item.name }}
+
+
+
+
+
+
+
+
+
+
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ 删除操作将导致实例配置丢失,请谨慎操作。
+
+
+
+
+
+
\ No newline at end of file
+.instance-list {
+ overflow: auto;
+}
+.log {
+ min-height: 40vh;
+ max-height: 40vh;
+ margin-top: auto;
+}
+.top {
+ align-items: center;
+}
+.is_show_log_switch {
+ margin-right: 20px;
+}
+
diff --git a/ui/src/stores/config.js b/ui/src/stores/config.js
index e33269a..80484fe 100644
--- a/ui/src/stores/config.js
+++ b/ui/src/stores/config.js
@@ -1,6 +1,14 @@
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
@@ -9,21 +17,25 @@ export const useConfigStore = defineStore('config', () => {
// 更新代码 UpdatePart
this.branch = conf.branch
this.mirror = conf.mirror
+ // 启动程序 LaunchPart
+ this.instances = []
+ this.is_show_log = conf.is_show_log
+ Object.assign(this, conf)
}
}
- const config = ref({})
+ const config = reactive({})
async function load_config() {
const conf = await pywebview.api.load_config()
- config.value = new Config(conf)
- console.log('config.value', config.value)
+ Object.assign(config, new Config(conf))
+ console.log('响应式配置已更新', config)
}
watch(
config,
() => {
- pywebview.api.save_config(config.value)
+ pywebview.api.save_config(config)
},
{ deep: true }
)
From 4153164c4994b7ff08b85d1d52e44cb803144647 Mon Sep 17 00:00:00 2001
From: li-xiaochen <397721316@qq.com>
Date: Sun, 23 Feb 2025 18:11:58 +0800
Subject: [PATCH 35/45] =?UTF-8?q?=E5=8F=91=E5=B8=83v0.6=E7=89=88=E6=9C=AC?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
launcher/sys_config/config_dist.json | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/launcher/sys_config/config_dist.json b/launcher/sys_config/config_dist.json
index 1764210..9c9c5fd 100644
--- a/launcher/sys_config/config_dist.json
+++ b/launcher/sys_config/config_dist.json
@@ -1,5 +1,5 @@
{
- "version": "v0.5",
+ "version": "v0.6",
"url": "ui/dist/index.html",
"log_level": "INFO",
"debug": false
From c94d6d5494e2a550990260fb5e9fa20a42547e32 Mon Sep 17 00:00:00 2001
From: li-xiaochen <397721316@qq.com>
Date: Sun, 23 Feb 2025 20:09:32 +0800
Subject: [PATCH 36/45] =?UTF-8?q?=E5=8A=9F=E8=83=BD=E4=BF=AE=E5=A4=8D?=
=?UTF-8?q?=EF=BC=9A=E6=89=93=E5=8C=85=E5=90=8E=E8=BF=90=E8=A1=8C=E5=AE=9E?=
=?UTF-8?q?=E4=BE=8B=E6=97=B6=E7=BC=96=E7=A0=81=E5=BC=82=E5=B8=B8?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
launcher/webview/api.py | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/launcher/webview/api.py b/launcher/webview/api.py
index b24ab1d..5842e9f 100644
--- a/launcher/webview/api.py
+++ b/launcher/webview/api.py
@@ -42,7 +42,7 @@ command_list = {
"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 webview_ui.py "{instance_path}"',
+ "webview": lambda instance_path="": f'..\\python\\pythonw -X utf8 webview_ui.py "{instance_path}"',
"open_folder": lambda folder_path: f"explorer {folder_path}",
}
From f5011e00513e0400a44d3a3c18472c2a87c6324e Mon Sep 17 00:00:00 2001
From: li-xiaochen <397721316@qq.com>
Date: Sun, 23 Feb 2025 20:28:31 +0800
Subject: [PATCH 37/45] =?UTF-8?q?=E5=8A=9F=E8=83=BD=E4=BF=AE=E5=A4=8D?=
=?UTF-8?q?=EF=BC=9A=E6=89=93=E5=BC=80=E5=AE=9E=E4=BE=8B=E6=96=87=E4=BB=B6?=
=?UTF-8?q?=E5=A4=B9=E6=97=B6=E5=BC=82=E5=B8=B8=E6=8A=A5=E9=94=99?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
launcher/webview/api.py | 8 +++++++-
ui/src/pages/Launch.vue | 2 +-
2 files changed, 8 insertions(+), 2 deletions(-)
diff --git a/launcher/webview/api.py b/launcher/webview/api.py
index 5842e9f..227f82e 100644
--- a/launcher/webview/api.py
+++ b/launcher/webview/api.py
@@ -43,7 +43,6 @@ command_list = {
"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}"',
- "open_folder": lambda folder_path: f"explorer {folder_path}",
}
@@ -252,3 +251,10 @@ class Api:
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}")
diff --git a/ui/src/pages/Launch.vue b/ui/src/pages/Launch.vue
index 3c15f37..faaacff 100644
--- a/ui/src/pages/Launch.vue
+++ b/ui/src/pages/Launch.vue
@@ -62,7 +62,7 @@ function end_update_instance_name() {
update_instance_name_index.value = null
}
function open_folder(path) {
- pywebview.api.run('open_folder', null, { folder_path: path })
+ pywebview.api.open_folder(path)
}
function start_instance(instance) {
pywebview.api.run('webview', 'mower-ng', {
From 501259b420c6994c3502cfefa930b4926ffa1b54 Mon Sep 17 00:00:00 2001
From: li-xiaochen <397721316@qq.com>
Date: Sun, 23 Feb 2025 21:00:43 +0800
Subject: [PATCH 38/45] =?UTF-8?q?=E5=8F=91=E5=B8=83v0.6.1=E7=89=88?=
=?UTF-8?q?=E6=9C=AC?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
launcher/sys_config/config_dist.json | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/launcher/sys_config/config_dist.json b/launcher/sys_config/config_dist.json
index 9c9c5fd..2649876 100644
--- a/launcher/sys_config/config_dist.json
+++ b/launcher/sys_config/config_dist.json
@@ -1,5 +1,5 @@
{
- "version": "v0.6",
+ "version": "v0.6.1",
"url": "ui/dist/index.html",
"log_level": "INFO",
"debug": false
From de2c2af2bd8abda93167a680bd2b0f32b9b48ffc Mon Sep 17 00:00:00 2001
From: li-xiaochen <397721316@qq.com>
Date: Sat, 8 Mar 2025 11:28:22 +0800
Subject: [PATCH 39/45] =?UTF-8?q?=E6=96=B0=E5=A2=9E=E5=8A=9F=E8=83=BD?=
=?UTF-8?q?=EF=BC=9A=E6=B7=BB=E5=8A=A0zhaozuohong.vip=E9=95=9C=E5=83=8F?=
=?UTF-8?q?=E9=80=89=E9=A1=B9?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
launcher/config/conf.py | 22 ++++++++++++++-
launcher/constants.py | 7 +++--
launcher/utils.py | 12 +++++++++
launcher/webview/api.py | 37 ++++++++++++++++++++++----
ui/src/components/BaseMirrorOption.vue | 30 +++++++++++++++++++++
ui/src/pages/Init.vue | 5 ++++
ui/src/pages/Settings.vue | 13 ++++++---
ui/src/pages/Update.vue | 9 ++++---
ui/src/stores/config.js | 2 ++
9 files changed, 123 insertions(+), 14 deletions(-)
create mode 100644 launcher/utils.py
create mode 100644 ui/src/components/BaseMirrorOption.vue
diff --git a/launcher/config/conf.py b/launcher/config/conf.py
index a5df264..cfeca5c 100644
--- a/launcher/config/conf.py
+++ b/launcher/config/conf.py
@@ -1,4 +1,4 @@
-from typing import List
+from typing import List, Literal, get_args, get_origin
from pydantic import BaseModel, model_validator
from pydantic_core import PydanticUndefined
@@ -15,6 +15,18 @@ class ConfModel(BaseModel):
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
@@ -55,9 +67,17 @@ class LaunchPart(ConfModel):
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
diff --git a/launcher/constants.py b/launcher/constants.py
index 3e519e2..507139e 100644
--- a/launcher/constants.py
+++ b/launcher/constants.py
@@ -8,18 +8,21 @@ constants.py
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"
)
-# 下载新版本压缩包名
-file_name = "launcher.7z"
# 下载地址
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",
diff --git a/launcher/utils.py b/launcher/utils.py
new file mode 100644
index 0000000..bb56ecc
--- /dev/null
+++ b/launcher/utils.py
@@ -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
diff --git a/launcher/webview/api.py b/launcher/webview/api.py
index 227f82e..f7769f2 100644
--- a/launcher/webview/api.py
+++ b/launcher/webview/api.py
@@ -3,6 +3,7 @@ import os
import shutil
import subprocess
import threading
+import time
from _winapi import CREATE_NO_WINDOW
from pathlib import Path
from shutil import rmtree
@@ -20,6 +21,7 @@ from launcher.constants import (
mirror_list,
file_name,
instances_folder_name,
+ mower_ng_git_url,
)
from launcher.file.download import init_download, download_file
from launcher.file.extract import extract_7z_file
@@ -27,17 +29,22 @@ 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", download_git_url, os.getcwd()),
+ "download_git": lambda: init_download(
+ "git", build_base_url(download_git_url), os.getcwd()
+ ),
"download_python": lambda: init_download(
- "python", download_python_url, os.getcwd()
+ "python", build_base_url(download_python_url), os.getcwd()
),
"lfs": "git\\bin\\git lfs install",
"ensurepip": "python\\python -m ensurepip --default-pip",
- "clone": "git\\bin\\git -c lfs.concurrenttransfers=100 clone https://git-cf.zhaozuohong.vip/mower-ng/mower-ng.git --branch slow",
- "fetch": lambda: f"..\\git\\bin\\git fetch origin {config.conf.branch} --progress",
+ "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 {build_base_url(mower_ng_git_url)} {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",
@@ -86,11 +93,12 @@ class Api:
def get_new_version(self):
logger.info("获取最新版本号")
- response = requests.get(get_new_version_url)
+ 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")
@@ -258,3 +266,22 @@ class Api:
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}")
diff --git a/ui/src/components/BaseMirrorOption.vue b/ui/src/components/BaseMirrorOption.vue
new file mode 100644
index 0000000..8d1037d
--- /dev/null
+++ b/ui/src/components/BaseMirrorOption.vue
@@ -0,0 +1,30 @@
+
+
+
+
+
+
+ 默认模式
+ 镜像模式(-cf后缀)
+
+
+ 测试连接
+
+
+
+
diff --git a/ui/src/pages/Init.vue b/ui/src/pages/Init.vue
index ac577ad..0120bfe 100644
--- a/ui/src/pages/Init.vue
+++ b/ui/src/pages/Init.vue
@@ -1,4 +1,6 @@