Compare commits
41
Commits
1.0.7
..
faaee9abe2
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
faaee9abe2 | ||
|
|
ead63e8ffe | ||
|
|
01c2d017c6 | ||
|
|
3efdf74258 | ||
|
|
3c74effb4c | ||
|
|
f03046bffd | ||
|
|
2cd18b4e5f | ||
|
|
023e9468db | ||
|
|
5e5d84856a | ||
|
|
b4724d7ca0 | ||
|
|
9a911089bf | ||
|
|
4bdfb49600 | ||
|
|
59a66c8fa8 | ||
|
|
a5fcaeb658 | ||
|
|
fcaacf3b33 | ||
|
|
0997de514e | ||
|
|
192f2a63e9 | ||
|
|
a1a14f106b | ||
|
|
e67cc63998 | ||
|
|
2ba4789c95 | ||
|
|
22baa6fda9 | ||
|
|
6ee2e8bead | ||
|
|
daf218ce71 | ||
|
|
631a90e862 | ||
|
|
40af11f78a | ||
|
|
4bcffa782d | ||
|
|
097bfd198e | ||
|
|
31b0c93b25 | ||
|
|
39dc23cb57 | ||
|
|
a361c889f8 | ||
|
|
461e79aa7f | ||
|
|
d7f6d8de9f | ||
|
|
7e34cb0467 | ||
|
|
e327a56421 | ||
|
|
40e72957e3 | ||
|
|
fdbf3160e8 | ||
|
|
2cc862a8da | ||
|
|
2c0c566c81 | ||
|
|
926a568dc0 | ||
|
|
cd44c7ecff | ||
|
|
aeab68d421 |
No files matched your search
@@ -1,9 +1,9 @@
|
|||||||
# GC-UI 夜间 alpha 构建(Gitea Actions)
|
# GC-UI alpha 构建(Gitea Actions)
|
||||||
#
|
#
|
||||||
# 触发:每天 21:00(Asia/Shanghai)自动跑一次,产出 Windows 与 macOS 的 Flutter 前端产物,
|
# 触发:**仅手动**。定时任务已取消(不再每天自动构建),需要时在 Actions 页面点
|
||||||
# 发布为一个「预览版(prerelease)」Release —— 不占用 latest。
|
# Run workflow,或从命令行调
|
||||||
# 手动:Actions 页面点 Run workflow(Gitea 的 workflow_dispatch),用于验证 runner 是否就绪;
|
# POST /api/v1/repos/{owner}/{repo}/actions/workflows/{file}/dispatches。
|
||||||
# 也可以从命令行调 POST /api/v1/repos/{owner}/{repo}/actions/workflows/{file}/dispatches。
|
# 产物:Windows 与 macOS 的 Flutter 前端,发布为一个「预览版(prerelease)」Release —— 不占用 latest。
|
||||||
#
|
#
|
||||||
# 为什么是 .gitea/workflows/:本仓库是自建 Gitea,不是 GitHub。Gitea Actions 语法与
|
# 为什么是 .gitea/workflows/:本仓库是自建 Gitea,不是 GitHub。Gitea Actions 语法与
|
||||||
# GitHub Actions 基本一致,但工作流目录是 .gitea/workflows/,API 前缀是 /api/v1,
|
# GitHub Actions 基本一致,但工作流目录是 .gitea/workflows/,API 前缀是 /api/v1,
|
||||||
@@ -16,12 +16,8 @@
|
|||||||
name: GC-UI Alpha
|
name: GC-UI Alpha
|
||||||
|
|
||||||
on:
|
on:
|
||||||
schedule:
|
# 定时触发已取消:夜间构建会绕开 build.sh,产出不含后端/前端的空壳包,
|
||||||
# 每天晚上 21:00,北京时间。
|
# 且 cron 的 TZ= 前缀在部分 Gitea 版本上非法。需要时手动 dispatch。
|
||||||
# Gitea 1.23 起 Actions 的 cron 默认按 UTC 解释,这里显式带 TZ= 前缀(robfig/cron 支持的
|
|
||||||
# 时区前缀语法),这样不依赖服务器自身时区设置。
|
|
||||||
# 如果所在实例不认 TZ= 前缀,改用等效的 UTC 写法 '0 13 * * *'。
|
|
||||||
- cron: 'TZ=Asia/Shanghai 0 21 * * *'
|
|
||||||
workflow_dispatch:
|
workflow_dispatch:
|
||||||
inputs:
|
inputs:
|
||||||
note:
|
note:
|
||||||
@@ -67,7 +63,7 @@ jobs:
|
|||||||
exit 1
|
exit 1
|
||||||
fi
|
fi
|
||||||
|
|
||||||
# 北京时间当天日期,让产物名和 tag 与「每晚 9 点」对得上
|
# 北京时间当天日期,让同一天的多次手动构建落在同一个日期前缀下
|
||||||
DATE=$(TZ=Asia/Shanghai date +%Y%m%d)
|
DATE=$(TZ=Asia/Shanghai date +%Y%m%d)
|
||||||
# 同一天重跑时用 run_number 区分,tag 不重复
|
# 同一天重跑时用 run_number 区分,tag 不重复
|
||||||
VERSION="${BASE}-alpha.${DATE}.${{ github.run_number }}"
|
VERSION="${BASE}-alpha.${DATE}.${{ github.run_number }}"
|
||||||
@@ -122,11 +118,11 @@ jobs:
|
|||||||
tag, version, sha, server = sys.argv[1:5]
|
tag, version, sha, server = sys.argv[1:5]
|
||||||
short = sha[:7]
|
short = sha[:7]
|
||||||
body = (
|
body = (
|
||||||
"GC-UI 夜间 alpha 构建(自动生成,**预览版 / prerelease**)。\n\n"
|
"GC-UI alpha 构建(手动触发,**预览版 / prerelease**)。\n\n"
|
||||||
"- 版本:`%s`\n"
|
"- 版本:`%s`\n"
|
||||||
"- 提交:`%s`\n"
|
"- 提交:`%s`\n"
|
||||||
"- 构建来源:%s/commit/%s\n"
|
"- 构建来源:%s/commit/%s\n"
|
||||||
"- 通道:alpha —— 每晚 21:00(Asia/Shanghai)自动构建\n\n"
|
"- 通道:alpha —— 手动触发(定时任务已取消)\n\n"
|
||||||
"产物说明:\n\n"
|
"产物说明:\n\n"
|
||||||
"| 文件 | 平台 | 内容 |\n"
|
"| 文件 | 平台 | 内容 |\n"
|
||||||
"|---|---|---|\n"
|
"|---|---|---|\n"
|
||||||
|
|||||||
@@ -1,115 +0,0 @@
|
|||||||
# ---------------------------------------------------------------------------
|
|
||||||
# 每晚预发布(Gitea Actions)
|
|
||||||
#
|
|
||||||
# 触发:每天 UTC 13:00(北京时间 21:00)定时执行,也可手动触发。
|
|
||||||
# 行为:
|
|
||||||
# 1. 编译并发布 Linux / Windows 启动器,打成 zip;
|
|
||||||
# 2. 先删除仓库里所有旧的 nightly-* 预发布(Release 与 tag);
|
|
||||||
# 3. 创建当天的新 Release:prerelease=true(不会成为 Latest),
|
|
||||||
# tag 形如 nightly-20261117,并上传构建产物。
|
|
||||||
#
|
|
||||||
# 注意:Gitea Actions 的 cron 按 UTC 计算,故 13:00 UTC = 21:00 Asia/Shanghai。
|
|
||||||
# ---------------------------------------------------------------------------
|
|
||||||
name: 每晚预发布
|
|
||||||
|
|
||||||
on:
|
|
||||||
schedule:
|
|
||||||
- cron: '0 13 * * *'
|
|
||||||
workflow_dispatch:
|
|
||||||
|
|
||||||
concurrency:
|
|
||||||
group: nightly-prerelease
|
|
||||||
cancel-in-progress: false
|
|
||||||
|
|
||||||
env:
|
|
||||||
AVALONIA_TELEMETRY_OPTOUT: '1'
|
|
||||||
DOTNET_NOLOGO: '1'
|
|
||||||
DOTNET_CLI_TELEMETRY_OPTOUT: '1'
|
|
||||||
|
|
||||||
jobs:
|
|
||||||
nightly:
|
|
||||||
name: 构建并发布预发布
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
env:
|
|
||||||
# 优先用仓库 Secret;未配置时回退到 Actions 内置令牌。
|
|
||||||
GITEA_TOKEN: ${{ secrets.GITEA_TOKEN || github.token }}
|
|
||||||
API: ${{ github.server_url }}/api/v1/repos/${{ github.repository }}
|
|
||||||
steps:
|
|
||||||
- name: 检出代码
|
|
||||||
uses: actions/checkout@v4
|
|
||||||
|
|
||||||
- name: 安装 .NET 8
|
|
||||||
uses: actions/setup-dotnet@v4
|
|
||||||
with:
|
|
||||||
dotnet-version: '8.0.x'
|
|
||||||
|
|
||||||
- name: 发布启动器(linux-x64 / win-x64)
|
|
||||||
run: |
|
|
||||||
set -eu
|
|
||||||
mkdir -p dist
|
|
||||||
dotnet publish GC-BOOT/GC-BOOT.csproj -c Release -r linux-x64 \
|
|
||||||
--self-contained true -p:PublishTrimmed=false -p:EnableWindowsTargeting=true \
|
|
||||||
-o dist/nightly/linux-x64
|
|
||||||
dotnet publish GC-BOOT/GC-BOOT.csproj -c Release -r win-x64 \
|
|
||||||
--self-contained true -p:PublishTrimmed=false -p:EnableWindowsTargeting=true \
|
|
||||||
-o dist/nightly/win-x64
|
|
||||||
(cd dist/nightly && zip -qr ../GC-nightly-linux-x64.zip linux-x64)
|
|
||||||
(cd dist/nightly && zip -qr ../GC-nightly-win-x64.zip win-x64)
|
|
||||||
ls -lh dist/*.zip
|
|
||||||
|
|
||||||
- name: 删除旧的 nightly 预发布
|
|
||||||
run: |
|
|
||||||
set -eu
|
|
||||||
echo "读取现有 Release…"
|
|
||||||
RELEASES=$(curl -sf -H "Authorization: token $GITEA_TOKEN" "$API/releases?limit=100" || echo '[]')
|
|
||||||
echo "$RELEASES" | jq -r '.[] | select(.prerelease == true and (.tag_name | startswith("nightly-"))) | "\(.id) \(.tag_name)"' |
|
|
||||||
while read -r id tag; do
|
|
||||||
[ -z "${id:-}" ] && continue
|
|
||||||
echo "删除旧预发布: $tag (id=$id)"
|
|
||||||
curl -sf -X DELETE -H "Authorization: token $GITEA_TOKEN" "$API/releases/$id" || true
|
|
||||||
curl -sf -X DELETE -H "Authorization: token $GITEA_TOKEN" "$API/tags/$tag" || true
|
|
||||||
done
|
|
||||||
|
|
||||||
- name: 创建当天预发布并上传产物
|
|
||||||
run: |
|
|
||||||
set -eu
|
|
||||||
TAG="nightly-$(date -u +%Y%m%d)"
|
|
||||||
NOW="$(date -u '+%Y-%m-%d %H:%M UTC')"
|
|
||||||
BODY="自动构建 · ${NOW}
|
|
||||||
基于提交 ${GITHUB_SHA}
|
|
||||||
产物:Linux x64 / Windows x64 启动器(未签名,仅供测试)"
|
|
||||||
echo "创建预发布 $TAG"
|
|
||||||
|
|
||||||
PAYLOAD=$(jq -n \
|
|
||||||
--arg tag "$TAG" \
|
|
||||||
--arg sha "${GITHUB_SHA}" \
|
|
||||||
--arg name "Nightly ${TAG}" \
|
|
||||||
--arg body "$BODY" \
|
|
||||||
'{tag_name:$tag, target_commitish:$sha, name:$name, body:$body, prerelease:true, draft:false}')
|
|
||||||
|
|
||||||
RESP=$(curl -sf -X POST \
|
|
||||||
-H "Authorization: token $GITEA_TOKEN" \
|
|
||||||
-H 'Content-Type: application/json' \
|
|
||||||
-d "$PAYLOAD" "$API/releases")
|
|
||||||
ID=$(echo "$RESP" | jq -r '.id')
|
|
||||||
echo "Release id=$ID"
|
|
||||||
|
|
||||||
for f in dist/GC-nightly-*.zip; do
|
|
||||||
[ -e "$f" ] || continue
|
|
||||||
echo "上传 $(basename "$f")"
|
|
||||||
curl -sf -X POST \
|
|
||||||
-H "Authorization: token $GITEA_TOKEN" \
|
|
||||||
-F "attachment=@$f" \
|
|
||||||
"$API/releases/$ID/assets?name=$(basename "$f")" || echo "⚠ 上传失败: $f"
|
|
||||||
done
|
|
||||||
|
|
||||||
echo "完成:$TAG 已作为预发布创建(Latest 仍是最近一次正式版)。"
|
|
||||||
|
|
||||||
- name: 保存构建产物(便于排查)
|
|
||||||
if: always()
|
|
||||||
uses: actions/upload-artifact@v3
|
|
||||||
with:
|
|
||||||
name: nightly-build
|
|
||||||
path: dist/*.zip
|
|
||||||
if-no-files-found: ignore
|
|
||||||
retention-days: 7
|
|
||||||
@@ -57,9 +57,12 @@ jobs:
|
|||||||
with:
|
with:
|
||||||
dotnet-version: '8.0.x'
|
dotnet-version: '8.0.x'
|
||||||
|
|
||||||
- name: 运行 GC.Tests(含离屏渲染 / 清单校验)
|
- name: 运行 GC.Tests(含离屏渲染 / 清单校验 / 日志用例)
|
||||||
run: dotnet run --project GC/src/test/dotnet/GC.Tests/GC.Tests.csproj -c Release
|
run: dotnet run --project GC/src/test/dotnet/GC.Tests/GC.Tests.csproj -c Release
|
||||||
|
|
||||||
|
- name: 运行应用器测试(整目录替换 / .GC/bin 合并 / 回滚)
|
||||||
|
run: dotnet run --project GC/src/test/dotnet/GC.Savedog.Tests/GC.Savedog.Tests.csproj -c Release
|
||||||
|
|
||||||
frontend:
|
frontend:
|
||||||
name: 前端检查(Flutter)
|
name: 前端检查(Flutter)
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
|
|||||||
@@ -0,0 +1,50 @@
|
|||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# 发布一致性核对(Gitea Actions)
|
||||||
|
#
|
||||||
|
# 触发:仅手动。发布前跑一次确认「tag / 清单 / 资产」互相对得上,发布后再跑一次
|
||||||
|
# 确认线上资产就是清单里那两份。
|
||||||
|
#
|
||||||
|
# 为什么不用 pull_request 触发:这里要下载几百 MB 的发布包,PR 阶段跑太贵;
|
||||||
|
# 需要时点 Run workflow 即可,本地也有等价命令:./build.sh release-verify <tag>
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
name: 发布核对
|
||||||
|
|
||||||
|
on:
|
||||||
|
workflow_dispatch:
|
||||||
|
inputs:
|
||||||
|
tag:
|
||||||
|
description: '要核对的 tag(如 1.1.0)'
|
||||||
|
required: true
|
||||||
|
skip_download:
|
||||||
|
description: '只比对体积、不下载校验 sha256(快,输入 1 开启)'
|
||||||
|
required: false
|
||||||
|
default: ''
|
||||||
|
|
||||||
|
env:
|
||||||
|
DOTNET_NOLOGO: '1'
|
||||||
|
DOTNET_CLI_TELEMETRY_OPTOUT: '1'
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
verify:
|
||||||
|
name: 核对 Release 与清单
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- name: 检出代码
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
|
||||||
|
- name: 安装 .NET 8
|
||||||
|
uses: actions/setup-dotnet@v4
|
||||||
|
with:
|
||||||
|
dotnet-version: '8.0.x'
|
||||||
|
|
||||||
|
- name: 核对
|
||||||
|
env:
|
||||||
|
GC_GITEA_TOKEN: ${{ secrets.GC_GITEA_TOKEN }}
|
||||||
|
run: |
|
||||||
|
set -eu
|
||||||
|
EXTRA=""
|
||||||
|
if [ -n "${{ github.event.inputs.skip_download }}" ]; then
|
||||||
|
EXTRA="--skip-download"
|
||||||
|
fi
|
||||||
|
chmod +x buildsh/lib/verify_release.py
|
||||||
|
./build.sh release-verify "${{ github.event.inputs.tag }}" $EXTRA
|
||||||
@@ -51,3 +51,6 @@ GC-UI/frontend/**/DebugProfile.entitlements.bak
|
|||||||
GC-UI/frontend/**/*.iml
|
GC-UI/frontend/**/*.iml
|
||||||
GC-UI/frontend/test/shots/
|
GC-UI/frontend/test/shots/
|
||||||
|
|
||||||
|
# GC.Tests 离屏渲染输出(dotnet run ... GC.Tests 默认写到仓库根 screenshots/)
|
||||||
|
screenshots/
|
||||||
|
|
||||||
@@ -22,7 +22,7 @@
|
|||||||
-->
|
-->
|
||||||
<AvaloniaVersion>11.3.9</AvaloniaVersion>
|
<AvaloniaVersion>11.3.9</AvaloniaVersion>
|
||||||
<MvvmVersion>8.2.2</MvvmVersion>
|
<MvvmVersion>8.2.2</MvvmVersion>
|
||||||
<Version>1.0.7</Version>
|
<Version>1.1.1</Version>
|
||||||
<Company>Morris</Company>
|
<Company>Morris</Company>
|
||||||
<Product>GC</Product>
|
<Product>GC</Product>
|
||||||
<NeutralLanguage>zh-Hans</NeutralLanguage>
|
<NeutralLanguage>zh-Hans</NeutralLanguage>
|
||||||
|
|||||||
@@ -0,0 +1,214 @@
|
|||||||
|
using System;
|
||||||
|
using System.Diagnostics;
|
||||||
|
using System.IO;
|
||||||
|
using System.Net.Http;
|
||||||
|
using System.Threading;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
using GC.UI.Server;
|
||||||
|
using Microsoft.AspNetCore.Builder;
|
||||||
|
|
||||||
|
namespace GC;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 新界面启动壳。
|
||||||
|
///
|
||||||
|
/// 发布包带 <c>GC-UI</c>(Flutter 前端)时,启动器只做三件事:
|
||||||
|
/// 1. 在自己的进程里起后端(本地 HTTP API + 模型窗口宿主),等 <c>/api/health</c> 就绪;
|
||||||
|
/// 2. 拉起 Flutter 窗口;
|
||||||
|
/// 3. 界面退出后关掉后端。
|
||||||
|
///
|
||||||
|
/// 后端跑在进程内而不是单独一个 exe:两者用的是同一套 .NET 运行时,
|
||||||
|
/// 拆成两个自包含进程等于把 60MB 运行时复制两份,发布包会白白大一倍。
|
||||||
|
///
|
||||||
|
/// 缺 Flutter 前端时返回 <c>false</c>,由调用方回退到内置 Avalonia 界面——
|
||||||
|
/// 这样 `dotnet run`、只编了启动器的开发场景都能正常打开。
|
||||||
|
/// </summary>
|
||||||
|
internal static class FlutterShell
|
||||||
|
{
|
||||||
|
/// <summary>与前端、后端共用的默认端口(定义在 GC.Services.GcUiContract)。</summary>
|
||||||
|
private const int Port = Services.GcUiContract.DefaultPort;
|
||||||
|
|
||||||
|
private static readonly HttpClient Http = new() { Timeout = TimeSpan.FromSeconds(1.5) };
|
||||||
|
|
||||||
|
private static WebApplication? _backend;
|
||||||
|
|
||||||
|
public static bool TryRun(string[] args)
|
||||||
|
{
|
||||||
|
var dir = AppContext.BaseDirectory;
|
||||||
|
var uiPath = FindUi(dir);
|
||||||
|
if (uiPath == null) return false;
|
||||||
|
|
||||||
|
var port = Port;
|
||||||
|
AvaloniaHost? uiHost = null;
|
||||||
|
|
||||||
|
// 用户可能重复启动:已有后端在跑就直接复用,退出时也不要关掉别人的进程。
|
||||||
|
if (!IsHealthy(port))
|
||||||
|
{
|
||||||
|
// 端口可能被别的程序占用:17890 起向后试几个,选第一个能起来且健康的。
|
||||||
|
var start = Environment.GetEnvironmentVariable(Services.GcUiContract.PortEnvVar) is { Length: > 0 }
|
||||||
|
? Services.GcUiContract.PortFromEnvironment()
|
||||||
|
: Port;
|
||||||
|
|
||||||
|
for (var candidate = start; candidate < start + Services.GcUiContract.PortScanRange; candidate++)
|
||||||
|
{
|
||||||
|
var app = TryStartBackend(args, candidate, out var host);
|
||||||
|
if (app == null) continue;
|
||||||
|
|
||||||
|
if (WaitHealthy(candidate, TimeSpan.FromSeconds(25)))
|
||||||
|
{
|
||||||
|
port = candidate;
|
||||||
|
_backend = app;
|
||||||
|
uiHost = host;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
StopBackend(app);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (_backend == null) return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
AppDomain.CurrentDomain.ProcessExit += (_, _) => StopBackend(_backend);
|
||||||
|
|
||||||
|
var ui = Start(uiPath, dir, port);
|
||||||
|
if (ui == null)
|
||||||
|
{
|
||||||
|
StopBackend(_backend);
|
||||||
|
_backend = null;
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 前端窗口已拉起。模型窗口由 Avalonia 承载,而 macOS 的 AppKit 要求
|
||||||
|
// NSApplication 必须在**主线程**——所以事件循环要跑在这里(当前正是主线程),
|
||||||
|
// 不能再丢到副线程,否则一点「启动模型」就会把整个后端带崩。
|
||||||
|
ui.EnableRaisingEvents = true;
|
||||||
|
var closed = 0;
|
||||||
|
void RequestClose()
|
||||||
|
{
|
||||||
|
if (Interlocked.Exchange(ref closed, 1) == 1) return;
|
||||||
|
uiHost?.Shutdown();
|
||||||
|
}
|
||||||
|
|
||||||
|
ui.Exited += (_, _) => RequestClose();
|
||||||
|
if (ui.HasExited) RequestClose();
|
||||||
|
|
||||||
|
if (!ui.HasExited && uiHost != null)
|
||||||
|
{
|
||||||
|
// 阻塞直到界面退出(或图形环境初始化失败)。
|
||||||
|
uiHost.RunOnCurrentThread();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Avalonia 起不来(无桌面会话)时仍要等界面退出,避免后端被提前收掉。
|
||||||
|
if (!ui.HasExited) ui.WaitForExit();
|
||||||
|
|
||||||
|
StopBackend(_backend);
|
||||||
|
_backend = null;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------- 产物定位
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Flutter 桌面产物。
|
||||||
|
/// macOS 是 <c>GC-UI.app/Contents/MacOS/GC-UI</c>;Windows 是 <c>GC-UI.exe</c>;
|
||||||
|
/// Linux 是 <c>GC-UI</c>。
|
||||||
|
/// </summary>
|
||||||
|
private static string? FindUi(string dir)
|
||||||
|
{
|
||||||
|
if (OperatingSystem.IsMacOS())
|
||||||
|
{
|
||||||
|
var exe = Path.Combine(dir, "GC-UI.app", "Contents", "MacOS", "GC-UI");
|
||||||
|
if (File.Exists(exe)) return exe;
|
||||||
|
}
|
||||||
|
|
||||||
|
foreach (var name in OperatingSystem.IsWindows() ? new[] { "GC-UI.exe" } : new[] { "GC-UI" })
|
||||||
|
{
|
||||||
|
var path = Path.Combine(dir, name);
|
||||||
|
if (File.Exists(path)) return path;
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------- 进程管理
|
||||||
|
|
||||||
|
/// <summary>在本进程内启动后端;端口被占用等失败情况返回 null。</summary>
|
||||||
|
/// <param name="uiHost">成功时交出模型窗口宿主,由调用方在主线程跑事件循环。</param>
|
||||||
|
private static WebApplication? TryStartBackend(string[] args, int port, out AvaloniaHost? uiHost)
|
||||||
|
{
|
||||||
|
uiHost = null;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var app = BackendServer.Start(args, port, out var host);
|
||||||
|
uiHost = host;
|
||||||
|
app.StartAsync().GetAwaiter().GetResult();
|
||||||
|
return app;
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
Console.Error.WriteLine($"[shell] 后端启动失败(端口 {port}): {ex.Message}");
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void StopBackend(WebApplication? app)
|
||||||
|
{
|
||||||
|
if (app == null) return;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(3));
|
||||||
|
app.StopAsync(cts.Token).GetAwaiter().GetResult();
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
Console.Error.WriteLine($"[shell] 关闭后端失败: {ex.Message}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Process Start(string fileName, string workingDirectory, int port)
|
||||||
|
{
|
||||||
|
var info = new ProcessStartInfo(fileName)
|
||||||
|
{
|
||||||
|
WorkingDirectory = workingDirectory,
|
||||||
|
UseShellExecute = false,
|
||||||
|
};
|
||||||
|
|
||||||
|
// 把实际端口传给前端:它读这个环境变量拼 baseUrl,换端口不需要重新编译界面。
|
||||||
|
info.Environment[Services.GcUiContract.PortEnvVar] = port.ToString();
|
||||||
|
|
||||||
|
// macOS .app 内的二进制也需要可执行位;发布包由 zip 解开时可能丢失。
|
||||||
|
if (!OperatingSystem.IsWindows())
|
||||||
|
{
|
||||||
|
try { File.SetUnixFileMode(fileName, UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute); }
|
||||||
|
catch { /* 权限不足时交给系统判断 */ }
|
||||||
|
}
|
||||||
|
|
||||||
|
return Process.Start(info)!;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------- 健康检查
|
||||||
|
|
||||||
|
private static bool IsHealthy(int port)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
using var response = Http.GetAsync($"http://127.0.0.1:{port}/api/health")
|
||||||
|
.GetAwaiter().GetResult();
|
||||||
|
return response.IsSuccessStatusCode;
|
||||||
|
}
|
||||||
|
catch
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static bool WaitHealthy(int port, TimeSpan timeout)
|
||||||
|
{
|
||||||
|
var deadline = DateTime.UtcNow + timeout;
|
||||||
|
while (DateTime.UtcNow < deadline)
|
||||||
|
{
|
||||||
|
if (IsHealthy(port)) return true;
|
||||||
|
Thread.Sleep(250);
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -17,9 +17,15 @@
|
|||||||
<PackageReference Include="Avalonia.Desktop" Version="$(AvaloniaVersion)" />
|
<PackageReference Include="Avalonia.Desktop" Version="$(AvaloniaVersion)" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<!-- 后端以库的方式编进启动器:发布包只需要一个 exe,不用再带一份运行时 -->
|
||||||
|
<FrameworkReference Include="Microsoft.AspNetCore.App" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<ProjectReference Include="..\GC\src\GC.Core.csproj" />
|
<ProjectReference Include="..\GC\src\GC.Core.csproj" />
|
||||||
<ProjectReference Include="..\GC-DOWNLOAD\GC-DOWNLOAD.csproj" />
|
<ProjectReference Include="..\GC-DOWNLOAD\GC-DOWNLOAD.csproj" />
|
||||||
|
<ProjectReference Include="..\GC-UI\backend\GC.UI.Server\GC.UI.Server.csproj" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
</Project>
|
</Project>
|
||||||
@@ -15,9 +15,15 @@ internal static class Program
|
|||||||
var paths = AppPaths.Discover();
|
var paths = AppPaths.Discover();
|
||||||
paths.EnsureCreated();
|
paths.EnsureCreated();
|
||||||
|
|
||||||
|
// 目录约定 + 双语日志 + 把包里的守护进程落到 .GC/safedog
|
||||||
|
RuntimeLayout.Ensure(paths);
|
||||||
|
|
||||||
// 上次下载的启动器新版,到这次启动才应用
|
// 上次下载的启动器新版,到这次启动才应用
|
||||||
if (DownloadModuleHost.Factory.TryApplyPending(paths)) return;
|
if (DownloadModuleHost.Factory.TryApplyPending(paths)) return;
|
||||||
|
|
||||||
|
// 发布包带 Flutter 前端时,界面交给它;没带则回退到内置 Avalonia 界面。
|
||||||
|
if (FlutterShell.TryRun(args)) return;
|
||||||
|
|
||||||
BuildAvaloniaApp().StartWithClassicDesktopLifetime(args);
|
BuildAvaloniaApp().StartWithClassicDesktopLifetime(args);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -56,12 +56,14 @@ public sealed partial class DownloadJob : ObservableObject, IDownloadJob
|
|||||||
partial void OnErrorChanged(string? value) => RefreshText();
|
partial void OnErrorChanged(string? value) => RefreshText();
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>下载中心:最多 2 个并发,任务在「后台列表」里折叠展示。</summary>
|
/// <summary>下载中心:最多 4 个并发,任务在「后台列表」里折叠展示。</summary>
|
||||||
public sealed class DownloadCenter : IDownloadCenter
|
public sealed class DownloadCenter : IDownloadCenter
|
||||||
{
|
{
|
||||||
private readonly ModelRepository _repository;
|
private readonly ModelRepository _repository;
|
||||||
private readonly AppPaths _paths;
|
private readonly AppPaths _paths;
|
||||||
private readonly SemaphoreSlim _slots = new(2);
|
// 断点续传后单任务失败重来的代价小了很多,可以适当提高并发;
|
||||||
|
// 更新服务那边已是 6,模型下载保持 4,兼顾弱网吞吐与源站压力。
|
||||||
|
private readonly SemaphoreSlim _slots = new(4);
|
||||||
|
|
||||||
public ObservableCollection<IDownloadJob> Jobs { get; } = new();
|
public ObservableCollection<IDownloadJob> Jobs { get; } = new();
|
||||||
public event Action? Installed;
|
public event Action? Installed;
|
||||||
|
|||||||
@@ -29,7 +29,8 @@ public static class LauncherArtifacts
|
|||||||
"win-arm64" => "win-arm64",
|
"win-arm64" => "win-arm64",
|
||||||
"osx-arm64" => "mac-arm64",
|
"osx-arm64" => "mac-arm64",
|
||||||
"osx-x64" => "mac-x64",
|
"osx-x64" => "mac-x64",
|
||||||
"linux-x64" => "linux-amd64",
|
"linux-x64" => "linux-amd64", // 旧产物目录名,仍能读
|
||||||
|
"linux-arm64" => "linux-arm64",
|
||||||
_ => rid
|
_ => rid
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -46,9 +47,9 @@ public static class LauncherArtifacts
|
|||||||
return new[] { label, rid };
|
return new[] { label, rid };
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>启动器包应有的文件名,如 <c>GC-1.0.7-mac-arm64.zip</c>。</summary>
|
/// <summary>启动器包应有的文件名,如 <c>GCL-1.0.10-mac-arm64.zip</c>。</summary>
|
||||||
public static string PackageFileName(string version, string rid)
|
public static string PackageFileName(string version, string rid)
|
||||||
=> $"GC-{version.Trim().TrimStart('v', 'V')}-{LabelOf(rid)}.zip";
|
=> $"GCL-{version.Trim().TrimStart('v', 'V')}-{LabelOf(rid)}.zip";
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 判断某个 zip 名是不是「这个版本 + 这个平台」的启动器包。
|
/// 判断某个 zip 名是不是「这个版本 + 这个平台」的启动器包。
|
||||||
@@ -57,7 +58,10 @@ public static class LauncherArtifacts
|
|||||||
public static bool LooksLikePackage(string fileName, string version, string rid)
|
public static bool LooksLikePackage(string fileName, string version, string rid)
|
||||||
{
|
{
|
||||||
if (!fileName.EndsWith(".zip", StringComparison.OrdinalIgnoreCase)) return false;
|
if (!fileName.EndsWith(".zip", StringComparison.OrdinalIgnoreCase)) return false;
|
||||||
if (!fileName.StartsWith("GC-", StringComparison.OrdinalIgnoreCase)) return false;
|
// 1.0.10 起发布包统一叫 GCL-<版本>-<平台>.zip;GC- 是老命名,
|
||||||
|
// 一并认,装过 1.0.9 及更早版本的机器才不会把新包当成「不是启动器包」。
|
||||||
|
if (!fileName.StartsWith("GCL-", StringComparison.OrdinalIgnoreCase) &&
|
||||||
|
!fileName.StartsWith("GC-", StringComparison.OrdinalIgnoreCase)) return false;
|
||||||
|
|
||||||
var v = version.Trim().TrimStart('v', 'V');
|
var v = version.Trim().TrimStart('v', 'V');
|
||||||
if (v.Length > 0 && fileName.IndexOf(v, StringComparison.OrdinalIgnoreCase) < 0) return false;
|
if (v.Length > 0 && fileName.IndexOf(v, StringComparison.OrdinalIgnoreCase) < 0) return false;
|
||||||
|
|||||||
@@ -194,8 +194,26 @@ public static class LauncherUpdater
|
|||||||
{
|
{
|
||||||
using var ms = new MemoryStream(zip);
|
using var ms = new MemoryStream(zip);
|
||||||
using var archive = new System.IO.Compression.ZipArchive(ms, System.IO.Compression.ZipArchiveMode.Read);
|
using var archive = new System.IO.Compression.ZipArchive(ms, System.IO.Compression.ZipArchiveMode.Read);
|
||||||
// 找主程序:app 内的可执行文件 / GC.dll / 单文件 exe
|
|
||||||
var entry = archive.Entries.FirstOrDefault(e =>
|
// 发布包从 1.0.10 起改为 GCL 命名 + 单文件 + 单顶层目录,主程序是
|
||||||
|
// <顶层>/GCL-<版本>-<平台>.exe (Windows)
|
||||||
|
// <顶层>/GCL-<版本>-<平台> (Linux,无扩展名)
|
||||||
|
// <顶层>/GCL-<版本>-mac-arm64.app/... (macOS)
|
||||||
|
// 旧布局则是 GC.dll / GC / GC*.dll。先找新名,再退回旧名,兼容老发布包。
|
||||||
|
// 注意排除 GC-UI / GC-SAVEDOG / .GC/bin 里的附属程序,它们不是启动器本体。
|
||||||
|
bool IsLauncher(System.IO.Compression.ZipArchiveEntry e)
|
||||||
|
{
|
||||||
|
var n = e.Name;
|
||||||
|
if (n.Length == 0) return false; // 目录条目
|
||||||
|
if (n.StartsWith("GC-UI", StringComparison.OrdinalIgnoreCase) ||
|
||||||
|
n.StartsWith("GC-SAVEDOG", StringComparison.OrdinalIgnoreCase)) return false;
|
||||||
|
if (e.FullName.Replace('\\', '/').Contains("/.GC/")) return false;
|
||||||
|
if (n.StartsWith("GCL-", StringComparison.OrdinalIgnoreCase)) return true;
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
var entry = archive.Entries.FirstOrDefault(IsLauncher)
|
||||||
|
?? archive.Entries.FirstOrDefault(e =>
|
||||||
e.Name.Equals("GC.dll", StringComparison.OrdinalIgnoreCase))
|
e.Name.Equals("GC.dll", StringComparison.OrdinalIgnoreCase))
|
||||||
?? archive.Entries.FirstOrDefault(e =>
|
?? archive.Entries.FirstOrDefault(e =>
|
||||||
e.Name.Equals("GC", StringComparison.OrdinalIgnoreCase))
|
e.Name.Equals("GC", StringComparison.OrdinalIgnoreCase))
|
||||||
@@ -367,8 +385,12 @@ public static class LauncherUpdater
|
|||||||
else if (File.Exists(manifestCopy))
|
else if (File.Exists(manifestCopy))
|
||||||
File.Delete(manifestCopy);
|
File.Delete(manifestCopy);
|
||||||
|
|
||||||
// 包名:GC-<版本>-<平台标签>.app/.exe(SAVEDOG 找不到时会自行扫描包内顶层)
|
// 包名:GCL-<版本>-<平台标签>.app/.exe(SAVEDOG 找不到时会自行扫描包内顶层)。
|
||||||
var packageName = $"GC-{latest}-{PlatformLabel}" + (OperatingSystem.IsMacOS() ? ".app" : ".exe");
|
// Linux 的启动器没有扩展名,别硬加 .exe —— 那会让按包名查找永远落空。
|
||||||
|
var packageName = $"GCL-{latest}-{PlatformLabel}" +
|
||||||
|
(OperatingSystem.IsMacOS() ? ".app"
|
||||||
|
: OperatingSystem.IsWindows() ? ".exe"
|
||||||
|
: "");
|
||||||
|
|
||||||
var request = new SavedogRequest
|
var request = new SavedogRequest
|
||||||
{
|
{
|
||||||
@@ -447,7 +469,8 @@ public static class LauncherUpdater
|
|||||||
/// 找不到 SAVEDOG 时退回旧脚本流程(只用于从老版本升级的过渡)。
|
/// 找不到 SAVEDOG 时退回旧脚本流程(只用于从老版本升级的过渡)。
|
||||||
/// 返回 true 表示调用方应立即退出进程。
|
/// 返回 true 表示调用方应立即退出进程。
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public static bool ScheduleApply(AppPaths paths, string packageName)
|
/// <param name="execute">只写脚本不执行(测试用,避免真的搬动文件)。</param>
|
||||||
|
public static bool ScheduleApply(AppPaths paths, string packageName, bool execute = true)
|
||||||
{
|
{
|
||||||
// 安全阀:绝不在源码目录执行替换(防止误删源码)
|
// 安全阀:绝不在源码目录执行替换(防止误删源码)
|
||||||
if (File.Exists(Path.Combine(paths.InstallDirectory, "GC.sln")))
|
if (File.Exists(Path.Combine(paths.InstallDirectory, "GC.sln")))
|
||||||
@@ -484,6 +507,8 @@ public static class LauncherUpdater
|
|||||||
catch { }
|
catch { }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (!execute) return true;
|
||||||
|
|
||||||
var psi = isWin
|
var psi = isWin
|
||||||
? new System.Diagnostics.ProcessStartInfo("cmd.exe")
|
? new System.Diagnostics.ProcessStartInfo("cmd.exe")
|
||||||
{ UseShellExecute = false, CreateNoWindow = true }
|
{ UseShellExecute = false, CreateNoWindow = true }
|
||||||
@@ -576,7 +601,10 @@ public static class LauncherUpdater
|
|||||||
s.AppendLine();
|
s.AppendLine();
|
||||||
s.AppendLine("# delete old GC-* files: SAME platform only, version != latest");
|
s.AppendLine("# delete old GC-* files: SAME platform only, version != latest");
|
||||||
s.AppendLine("# files of OTHER platforms are NEVER touched");
|
s.AppendLine("# files of OTHER platforms are NEVER touched");
|
||||||
s.AppendLine("for item in \"$DST\"/GC-*.app \"$DST\"/GC-*.exe; do");
|
// Linux 的启动器没有扩展名(GC-1.0.9-linux-amd64),只匹配 *.app/*.exe 会漏掉,
|
||||||
|
// 结果是每次更新都在安装目录里多留一个旧版本。这里统一按 GC- 前缀扫,
|
||||||
|
// 再用「版本号-平台」的形态兜底,避免误删同目录的其它文件。
|
||||||
|
s.AppendLine("for item in \"$DST\"/GC-*; do");
|
||||||
s.AppendLine(" [ -e \"$item\" ] || continue");
|
s.AppendLine(" [ -e \"$item\" ] || continue");
|
||||||
s.AppendLine(" [ \"$item\" = \"$NEW\" ] && continue");
|
s.AppendLine(" [ \"$item\" = \"$NEW\" ] && continue");
|
||||||
s.AppendLine(" base=$(basename \"$item\")");
|
s.AppendLine(" base=$(basename \"$item\")");
|
||||||
@@ -584,6 +612,10 @@ public static class LauncherUpdater
|
|||||||
s.AppendLine(" case \"$base\" in");
|
s.AppendLine(" case \"$base\" in");
|
||||||
s.AppendLine(" *.app) stem=${stem%.app} ;;");
|
s.AppendLine(" *.app) stem=${stem%.app} ;;");
|
||||||
s.AppendLine(" *.exe) stem=${stem%.exe} ;;");
|
s.AppendLine(" *.exe) stem=${stem%.exe} ;;");
|
||||||
|
s.AppendLine(" esac");
|
||||||
|
s.AppendLine(" # 只认 <版本>-<系统>-<架构>,其它名字一律不动");
|
||||||
|
s.AppendLine(" case \"$stem\" in");
|
||||||
|
s.AppendLine(" [0-9]*-*-*) ;;");
|
||||||
s.AppendLine(" *) continue ;;");
|
s.AppendLine(" *) continue ;;");
|
||||||
s.AppendLine(" esac");
|
s.AppendLine(" esac");
|
||||||
s.AppendLine(" ver=${stem%%-*}");
|
s.AppendLine(" ver=${stem%%-*}");
|
||||||
@@ -711,6 +743,17 @@ public static class LauncherUpdater
|
|||||||
return name;
|
return name;
|
||||||
}
|
}
|
||||||
if (name.EndsWith(".exe", StringComparison.OrdinalIgnoreCase)) return name;
|
if (name.EndsWith(".exe", StringComparison.OrdinalIgnoreCase)) return name;
|
||||||
|
|
||||||
|
// Linux 的启动器没有扩展名(GC-1.0.9-linux-amd64),以前只认 .app/.exe,
|
||||||
|
// 结果解压完判定「没找到新版启动器」,Linux 更新永远失败。
|
||||||
|
// 注意不能用 Path.HasExtension:版本号 9.9.9 里的点会让它误判成有扩展名。
|
||||||
|
if ((name.StartsWith("GC-", StringComparison.OrdinalIgnoreCase) ||
|
||||||
|
name.StartsWith("GCL-", StringComparison.OrdinalIgnoreCase)) &&
|
||||||
|
name.EndsWith("-" + PlatformLabel, StringComparison.OrdinalIgnoreCase))
|
||||||
|
{
|
||||||
|
TryMarkExecutable(dest);
|
||||||
|
return name;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
catch (Exception ex)
|
catch (Exception ex)
|
||||||
@@ -720,6 +763,22 @@ public static class LauncherUpdater
|
|||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>给 Linux/macOS 上的可执行文件补上执行位(zip 不保留权限)。</summary>
|
||||||
|
private static void TryMarkExecutable(string path)
|
||||||
|
{
|
||||||
|
if (OperatingSystem.IsWindows() || !File.Exists(path)) return;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var mode = File.GetUnixFileMode(path);
|
||||||
|
File.SetUnixFileMode(path, mode | UnixFileMode.UserExecute |
|
||||||
|
UnixFileMode.GroupExecute | UnixFileMode.OtherExecute);
|
||||||
|
}
|
||||||
|
catch
|
||||||
|
{
|
||||||
|
// 权限设置失败不影响后续流程,用户可手动 chmod
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private static string? ReadMarker(string file, string key)
|
private static string? ReadMarker(string file, string key)
|
||||||
{
|
{
|
||||||
try
|
try
|
||||||
|
|||||||
@@ -5,6 +5,8 @@ using System.IO;
|
|||||||
using System.IO.Compression;
|
using System.IO.Compression;
|
||||||
using System.Linq;
|
using System.Linq;
|
||||||
using System.Net.Http;
|
using System.Net.Http;
|
||||||
|
using System.Security.Cryptography;
|
||||||
|
using System.Text;
|
||||||
using System.Threading;
|
using System.Threading;
|
||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
using GC.Models;
|
using GC.Models;
|
||||||
@@ -152,24 +154,33 @@ public sealed class ModelSourceClient : IModelSourceClient
|
|||||||
else if (host.Contains("gitee.com"))
|
else if (host.Contains("gitee.com"))
|
||||||
yield return $"https://gitee.com/{owner}/{repo}/repository/archive/{b}.zip";
|
yield return $"https://gitee.com/{owner}/{repo}/repository/archive/{b}.zip";
|
||||||
else
|
else
|
||||||
yield break;
|
{
|
||||||
|
// 自托管 Gitea(如 git.xhmcl.com):用 archive/<branch>.zip 拉源码归档。
|
||||||
|
// 关键:不能在这里 yield break —— 那样就只剩 git clone 一条路,
|
||||||
|
// 用户机器没装 git 时「检测模型 / 下载 / 自动更新」会全部失效。
|
||||||
|
// 归档下载走 ResumableDownloader,无需系统 git。
|
||||||
|
yield return $"{uri.GetLeftPart(UriPartial.Authority)}/{owner}/{repo}/archive/{b}.zip";
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private async Task DownloadZipAsync(string url, string cacheDir, CancellationToken ct)
|
private async Task DownloadZipAsync(string url, string cacheDir, CancellationToken ct)
|
||||||
{
|
{
|
||||||
|
// .part 用 URL 哈希做稳定文件名:同一个源重试时命中同一份半成品,
|
||||||
|
// 断点续传才有意义(用 GUID 的话每次重试都是新文件,等于从零开始)。
|
||||||
|
// 解压目录仍用 GUID —— 它只是中间产物,成功后整块移走或失败即删。
|
||||||
|
var key = Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(url)))[..16].ToLowerInvariant();
|
||||||
|
var partPath = Path.Combine(_paths.CacheRoot, "tmp", "downloads", key + ".part");
|
||||||
var tmpRoot = Path.Combine(_paths.CacheRoot, "tmp", Guid.NewGuid().ToString("N"));
|
var tmpRoot = Path.Combine(_paths.CacheRoot, "tmp", Guid.NewGuid().ToString("N"));
|
||||||
Directory.CreateDirectory(tmpRoot);
|
Directory.CreateDirectory(tmpRoot);
|
||||||
var zipPath = Path.Combine(tmpRoot, "source.zip");
|
var zipPath = Path.Combine(tmpRoot, "source.zip");
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
using (var response = await Http.GetAsync(url, HttpCompletionOption.ResponseHeadersRead, ct))
|
// 带断点续传的流式下载;网络中断时 .part 保留,下次从这里接上。
|
||||||
{
|
await ResumableDownloader.DownloadAsync(Http, url, partPath, null, ct)
|
||||||
response.EnsureSuccessStatusCode();
|
.ConfigureAwait(false);
|
||||||
await using var input = await response.Content.ReadAsStreamAsync(ct);
|
// 下载完整,.part 转正。转正成功即代表这份 zip 已完整,删掉 .part 避免重复下载。
|
||||||
await using var output = File.Create(zipPath);
|
File.Move(partPath, zipPath, overwrite: true);
|
||||||
await input.CopyToAsync(output, 81920, ct);
|
|
||||||
}
|
|
||||||
|
|
||||||
var extractDir = Path.Combine(tmpRoot, "extract");
|
var extractDir = Path.Combine(tmpRoot, "extract");
|
||||||
Directory.CreateDirectory(extractDir);
|
Directory.CreateDirectory(extractDir);
|
||||||
|
|||||||
@@ -0,0 +1,100 @@
|
|||||||
|
using System;
|
||||||
|
using System.IO;
|
||||||
|
using System.Net;
|
||||||
|
using System.Net.Http;
|
||||||
|
using System.Net.Http.Headers;
|
||||||
|
using System.Threading;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
|
||||||
|
namespace GC.Services;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 带断点续传的流式下载器。已下载的部分写在 <c>*.part</c> 文件里,
|
||||||
|
/// 完整下载后由调用方把 .part 改成正式文件名。
|
||||||
|
///
|
||||||
|
/// 为什么需要它:模型源码 zip 可能有上百 MB,弱网中断后如果每次都从头下,
|
||||||
|
/// 用户会反复卡在同一个地方。这里用 HTTP Range 从已下载的字节接着下。
|
||||||
|
///
|
||||||
|
/// 兼容性:服务器不支持 Range(忽略请求、返回 200)时自动退化为整段下载,
|
||||||
|
/// 不会卡死或拿到半截文件。<see cref="Content-Range"/> 起始位置不符时也从头下。
|
||||||
|
///
|
||||||
|
/// .part 文件只有在"续传"场景才复用;一旦下载完整、调用方改名为正式文件,
|
||||||
|
/// 下次就是全新下载,不会把旧内容接在新内容后面。
|
||||||
|
/// </summary>
|
||||||
|
public static class ResumableDownloader
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// 下载 <paramref name="url"/>,数据写入 <paramref name="partPath"/>。
|
||||||
|
/// 返回最终 .part 文件的字节数。下载完整后由调用方负责改名 / 校验。
|
||||||
|
/// </summary>
|
||||||
|
public static async Task<long> DownloadAsync(
|
||||||
|
HttpClient http,
|
||||||
|
string url,
|
||||||
|
string partPath,
|
||||||
|
IProgress<(long Done, long Total)>? progress,
|
||||||
|
CancellationToken ct)
|
||||||
|
{
|
||||||
|
// 已有 .part 就尝试从断点续传;没有则从头下
|
||||||
|
long resumeFrom = 0;
|
||||||
|
if (File.Exists(partPath))
|
||||||
|
{
|
||||||
|
try { resumeFrom = new FileInfo(partPath).Length; }
|
||||||
|
catch { resumeFrom = 0; }
|
||||||
|
}
|
||||||
|
|
||||||
|
using var req = new HttpRequestMessage(HttpMethod.Get, url);
|
||||||
|
if (resumeFrom > 0)
|
||||||
|
req.Headers.Range = new RangeHeaderValue(resumeFrom, null);
|
||||||
|
|
||||||
|
using var response = await http.SendAsync(req, HttpCompletionOption.ResponseHeadersRead, ct)
|
||||||
|
.ConfigureAwait(false);
|
||||||
|
response.EnsureSuccessStatusCode();
|
||||||
|
|
||||||
|
var canResume = response.StatusCode == HttpStatusCode.PartialContent && resumeFrom > 0;
|
||||||
|
long? total = response.Content.Headers.ContentLength;
|
||||||
|
|
||||||
|
if (canResume)
|
||||||
|
{
|
||||||
|
// 校验服务器确实从我们要的位置开始返回:Content-Range: bytes START-END/TOTAL
|
||||||
|
var range = response.Content.Headers.ContentRange;
|
||||||
|
if (range?.HasRange == true && range.From == resumeFrom && range.Length.HasValue)
|
||||||
|
{
|
||||||
|
total = range.Length.Value;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
// 服务器忽略了 Range 或给出的范围对不上:从头覆盖,避免拼接出损坏的文件
|
||||||
|
canResume = false;
|
||||||
|
resumeFrom = 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var mode = canResume ? FileMode.Append : FileMode.Create;
|
||||||
|
var dir = Path.GetDirectoryName(partPath);
|
||||||
|
if (!string.IsNullOrEmpty(dir)) Directory.CreateDirectory(dir);
|
||||||
|
|
||||||
|
await using (var input = await response.Content.ReadAsStreamAsync(ct).ConfigureAwait(false))
|
||||||
|
await using (var output = new FileStream(partPath, mode, FileAccess.Write, FileShare.Read,
|
||||||
|
81920, useAsync: true))
|
||||||
|
{
|
||||||
|
var buffer = new byte[81920];
|
||||||
|
long done = resumeFrom;
|
||||||
|
int read;
|
||||||
|
while ((read = await input.ReadAsync(buffer.AsMemory(), ct).ConfigureAwait(false)) > 0)
|
||||||
|
{
|
||||||
|
await output.WriteAsync(buffer.AsMemory(0, read), ct).ConfigureAwait(false);
|
||||||
|
done += read;
|
||||||
|
// Total 未知时用已下载量当分母,进度条会停在 100% 之前但不报错
|
||||||
|
progress?.Report((done, total ?? done));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return SafeLength(partPath);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static long SafeLength(string path)
|
||||||
|
{
|
||||||
|
try { return new FileInfo(path).Length; }
|
||||||
|
catch { return 0; }
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -20,9 +20,21 @@ public static class SavedogLauncher
|
|||||||
var name = SavedogFiles.ExecutableName;
|
var name = SavedogFiles.ExecutableName;
|
||||||
var install = paths.InstallDirectory;
|
var install = paths.InstallDirectory;
|
||||||
|
|
||||||
|
// 首选 .GC/safedog:更新时整目录替换不会碰这里,正在运行的守护进程也安全。
|
||||||
|
var home = Path.Combine(paths.SafedogRoot, name);
|
||||||
|
if (File.Exists(home)) return home;
|
||||||
|
|
||||||
|
// 包内 payload:非本体文件统一收在 .GC/bin
|
||||||
|
var payload = Path.Combine(install, ".GC", "bin", name);
|
||||||
|
if (File.Exists(payload)) return payload;
|
||||||
|
|
||||||
var direct = Path.Combine(install, name);
|
var direct = Path.Combine(install, name);
|
||||||
if (File.Exists(direct)) return direct;
|
if (File.Exists(direct)) return direct;
|
||||||
|
|
||||||
|
// 1.0.10 及更早的包把守护进程放在 safedog/ 子目录
|
||||||
|
var packaged = Path.Combine(install, "safedog", name);
|
||||||
|
if (File.Exists(packaged)) return packaged;
|
||||||
|
|
||||||
// macOS:可能放在 .app 内部
|
// macOS:可能放在 .app 内部
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -40,7 +40,8 @@ public sealed class SourceSelector : ISourceSelector
|
|||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 探测两个源并返回最快的。force=true 时忽略缓存。
|
/// 探测两个源并返回最快的。force=true 时忽略缓存。
|
||||||
/// 两个都失败时返回 GitCode(默认源)。
|
/// 两个都失败时退回主源(Xhmcl):GitCode 镜像已停更,用它兜底只会拿到过期的
|
||||||
|
/// version.json —— 反而让人以为「没有更新」。
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public async Task<SourcePreset> PickFastestAsync(bool force = false, CancellationToken ct = default)
|
public async Task<SourcePreset> PickFastestAsync(bool force = false, CancellationToken ct = default)
|
||||||
{
|
{
|
||||||
@@ -64,12 +65,20 @@ public sealed class SourceSelector : ISourceSelector
|
|||||||
LastLatency = latencies;
|
LastLatency = latencies;
|
||||||
|
|
||||||
var usable = results.Where(r => r.Ok).OrderBy(r => r.Ms).ToList();
|
var usable = results.Where(r => r.Ok).OrderBy(r => r.Ms).ToList();
|
||||||
var chosen = usable.Count > 0 ? usable[0].Preset : SourcePreset.GitCode;
|
// 全部探测失败时退回主源(SourcePreset.All 的第一项 = Xhmcl),
|
||||||
|
// 不要退回已停更的 GitCode 镜像。
|
||||||
|
var fallback = SourcePreset.All.Length > 0 ? SourcePreset.All[0] : SourcePreset.Xhmcl;
|
||||||
|
var chosen = usable.Count > 0 ? usable[0].Preset : fallback;
|
||||||
|
|
||||||
|
if (usable.Count == 0)
|
||||||
|
Console.WriteLine($"[selector] 所有源探测失败,退回主源 {chosen.Name}(稍后由实际请求再判定)");
|
||||||
|
|
||||||
lock (_lock)
|
lock (_lock)
|
||||||
{
|
{
|
||||||
_cached = chosen;
|
_cached = chosen;
|
||||||
_cachedAt = DateTime.UtcNow;
|
// 全部探测失败的结果不缓存:网络刚恢复时应该立刻重新测速,
|
||||||
|
// 而不是被一次失败的探测锁住 3 分钟。
|
||||||
|
_cachedAt = usable.Count > 0 ? DateTime.UtcNow : DateTime.MinValue;
|
||||||
}
|
}
|
||||||
|
|
||||||
Console.WriteLine("[selector] 测速:" + string.Join(" ",
|
Console.WriteLine("[selector] 测速:" + string.Join(" ",
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ using System.Globalization;
|
|||||||
namespace GC.Services;
|
namespace GC.Services;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 版本号工具:Release tag 有 v1.0.6 / GC-1.0.6 / 1.0.6 等写法,
|
/// 版本号工具:Release tag 有 v1.0.6 / GCL-1.0.6 / GC-1.0.6 / 1.0.6 等写法,
|
||||||
/// 统一成可比较的 Version 再排序,挑**版本号最高**的那个。
|
/// 统一成可比较的 Version 再排序,挑**版本号最高**的那个。
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public static class VersionUtil
|
public static class VersionUtil
|
||||||
@@ -15,8 +15,9 @@ public static class VersionUtil
|
|||||||
if (string.IsNullOrWhiteSpace(tag)) return "";
|
if (string.IsNullOrWhiteSpace(tag)) return "";
|
||||||
var s = tag!.Trim();
|
var s = tag!.Trim();
|
||||||
|
|
||||||
// 去掉前缀:v / V / GC- / release-
|
// 去掉前缀:v / V / GC- / GCL- / release-
|
||||||
if (s.StartsWith("GC-", StringComparison.OrdinalIgnoreCase)) s = s[3..];
|
if (s.StartsWith("GCL-", StringComparison.OrdinalIgnoreCase)) s = s[4..];
|
||||||
|
else if (s.StartsWith("GC-", StringComparison.OrdinalIgnoreCase)) s = s[3..];
|
||||||
else if (s.StartsWith("release-", StringComparison.OrdinalIgnoreCase)) s = s[8..];
|
else if (s.StartsWith("release-", StringComparison.OrdinalIgnoreCase)) s = s[8..];
|
||||||
s = s.TrimStart('v', 'V');
|
s = s.TrimStart('v', 'V');
|
||||||
|
|
||||||
|
|||||||
+399
-113
@@ -26,13 +26,14 @@ internal sealed class ApplyOptions
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
internal sealed class Applier
|
internal sealed class Applier
|
||||||
{
|
{
|
||||||
private static readonly Regex ArtifactPattern = new(
|
|
||||||
@"^GC-(?<ver>.+?)-(?<plat>[^\-]+-[^\-]+)\.(app|exe)$",
|
|
||||||
RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);
|
|
||||||
|
|
||||||
private readonly ApplyOptions _options;
|
private readonly ApplyOptions _options;
|
||||||
private readonly Log _log;
|
private readonly Log _log;
|
||||||
|
|
||||||
|
/// <summary>发布包里的启动器文件名:GC-1.0.9-win-amd64.exe。</summary>
|
||||||
|
private static readonly Regex VersionedExePattern = new(
|
||||||
|
@"^(?:GC|GCL)-\d+(?:\.\d+)+-[A-Za-z0-9]+-[A-Za-z0-9]+\.exe$",
|
||||||
|
RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.Compiled);
|
||||||
|
|
||||||
public Applier(ApplyOptions options, Log log)
|
public Applier(ApplyOptions options, Log log)
|
||||||
{
|
{
|
||||||
_options = options;
|
_options = options;
|
||||||
@@ -45,20 +46,24 @@ internal sealed class Applier
|
|||||||
var requestPath = Path.Combine(updateDir, SavedogFiles.ApplyRequest);
|
var requestPath = Path.Combine(updateDir, SavedogFiles.ApplyRequest);
|
||||||
|
|
||||||
if (!File.Exists(requestPath))
|
if (!File.Exists(requestPath))
|
||||||
return Fail(updateDir, "找不到更新申请 " + SavedogFiles.ApplyRequest, 3);
|
return Fail(updateDir, "找不到更新申请 " + SavedogFiles.ApplyRequest, 3,
|
||||||
|
"Update request not found: " + SavedogFiles.ApplyRequest);
|
||||||
|
|
||||||
var request = Json.Read<SavedogRequest>(requestPath);
|
var request = Json.Read<SavedogRequest>(requestPath);
|
||||||
if (request == null || string.IsNullOrWhiteSpace(request.Version))
|
if (request == null || string.IsNullOrWhiteSpace(request.Version))
|
||||||
return Fail(updateDir, "更新申请内容不完整", 3);
|
return Fail(updateDir, "更新申请内容不完整", 3, "The update request is incomplete");
|
||||||
|
|
||||||
if (!ValidName(request.PackageName))
|
if (!ValidName(request.PackageName))
|
||||||
return Fail(updateDir, "更新包名不合法: " + request.PackageName, 3);
|
return Fail(updateDir, "更新包名不合法: " + request.PackageName, 3,
|
||||||
|
"Invalid package name: " + request.PackageName);
|
||||||
|
|
||||||
_log.Info($"开始应用 v{request.Version}({request.Rid},{request.PackageName})");
|
_log.Info($"开始应用 v{request.Version}({request.Rid},{request.PackageName})",
|
||||||
|
$"Starting apply of v{request.Version} ({request.Rid}, {request.PackageName})");
|
||||||
|
|
||||||
// 1. 等旧进程退出(否则 Windows 上文件还被占用)
|
// 1. 等旧进程退出(否则 Windows 上文件还被占用)
|
||||||
if (_options.WaitPid > 0 && !WaitForExit(_options.WaitPid, TimeSpan.FromSeconds(60)))
|
if (_options.WaitPid > 0 && !WaitForExit(_options.WaitPid, TimeSpan.FromSeconds(60)))
|
||||||
_log.Warn($"等待进程 {_options.WaitPid} 退出超时,继续尝试");
|
_log.Warn($"等待进程 {_options.WaitPid} 退出超时,继续尝试",
|
||||||
|
$"Timed out waiting for process {_options.WaitPid} to exit; continuing anyway");
|
||||||
|
|
||||||
// 2. 安装目录定位与安全检查
|
// 2. 安装目录定位与安全检查
|
||||||
var installDir = string.IsNullOrWhiteSpace(_options.InstallDir)
|
var installDir = string.IsNullOrWhiteSpace(_options.InstallDir)
|
||||||
@@ -66,10 +71,12 @@ internal sealed class Applier
|
|||||||
: Path.GetFullPath(_options.InstallDir!);
|
: Path.GetFullPath(_options.InstallDir!);
|
||||||
|
|
||||||
if (!Directory.Exists(installDir))
|
if (!Directory.Exists(installDir))
|
||||||
return Fail(updateDir, "安装目录不存在: " + installDir, 4);
|
return Fail(updateDir, "安装目录不存在: " + installDir, 4,
|
||||||
|
"Install directory does not exist: " + installDir);
|
||||||
|
|
||||||
if (!_options.Force && File.Exists(Path.Combine(installDir, "GC.sln")))
|
if (!_options.Force && File.Exists(Path.Combine(installDir, "GC.sln")))
|
||||||
return Fail(updateDir, "检测到源码目录,拒绝在源码树里替换程序", 4);
|
return Fail(updateDir, "检测到源码目录,拒绝在源码树里替换程序", 4,
|
||||||
|
"Source tree detected; refusing to replace files inside it");
|
||||||
|
|
||||||
// 3. 二次验签:不信任「启动器说它验过了」
|
// 3. 二次验签:不信任「启动器说它验过了」
|
||||||
var require = request.RequireSignature && SignatureKeyring.Enforced;
|
var require = request.RequireSignature && SignatureKeyring.Enforced;
|
||||||
@@ -77,42 +84,61 @@ internal sealed class Applier
|
|||||||
var manifestText = File.Exists(manifestPath) ? File.ReadAllText(manifestPath) : null;
|
var manifestText = File.Exists(manifestPath) ? File.ReadAllText(manifestPath) : null;
|
||||||
var verification = ManifestSignature.Verify(manifestText, require);
|
var verification = ManifestSignature.Verify(manifestText, require);
|
||||||
|
|
||||||
if (verification.IsRejected)
|
// 签名不对(被改过 / 密钥不认识)永远拒绝;仅「没有签名」在明确不强制时放行。
|
||||||
|
// 之前这里不看 require:即使调用方声明 requireSignature=false(开发态、测试),
|
||||||
|
// 未签名清单也会被当成验签失败直接拒掉。
|
||||||
|
var hostile = verification.Trust == ManifestTrust.Invalid;
|
||||||
|
if (hostile || (verification.IsRejected && require))
|
||||||
{
|
{
|
||||||
_log.Error($"清单验签失败({verification.Trust}):{verification.Error}");
|
_log.Error($"清单验签失败({verification.Trust}):{verification.Error}",
|
||||||
|
$"Manifest signature check failed ({verification.Trust}): {verification.Error}");
|
||||||
return Refuse(updateDir, request, verification);
|
return Refuse(updateDir, request, verification);
|
||||||
}
|
}
|
||||||
|
if (verification.IsRejected)
|
||||||
|
{
|
||||||
|
_log.Warn($"清单未签名,按调用方要求放行:{verification.Error}",
|
||||||
|
$"Manifest is unsigned; continuing as requested: {verification.Error}");
|
||||||
|
}
|
||||||
_log.Info($"清单可信度:{verification.Trust}" +
|
_log.Info($"清单可信度:{verification.Trust}" +
|
||||||
(verification.KeyId != null ? $"({verification.KeyId})" : ""));
|
(verification.KeyId != null ? $"({verification.KeyId})" : ""),
|
||||||
|
$"Manifest trust: {verification.Trust}" +
|
||||||
|
(verification.KeyId != null ? $" ({verification.KeyId})" : ""));
|
||||||
|
|
||||||
// 4. 校验更新包
|
// 4. 校验更新包
|
||||||
var zipPath = Path.Combine(updateDir, request.PackageZip);
|
var zipPath = Path.Combine(updateDir, request.PackageZip);
|
||||||
if (!File.Exists(zipPath))
|
if (!File.Exists(zipPath))
|
||||||
return Fail(updateDir, "更新包不存在: " + request.PackageZip, 5);
|
return Fail(updateDir, "更新包不存在: " + request.PackageZip, 5,
|
||||||
|
"Package not found: " + request.PackageZip);
|
||||||
|
|
||||||
var zipInfo = new FileInfo(zipPath);
|
var zipInfo = new FileInfo(zipPath);
|
||||||
if (request.PackageSize > 0 && zipInfo.Length != request.PackageSize)
|
if (request.PackageSize > 0 && zipInfo.Length != request.PackageSize)
|
||||||
return Fail(updateDir, $"更新包体积不符(期望 {request.PackageSize},实际 {zipInfo.Length})", 5);
|
return Fail(updateDir, $"更新包体积不符(期望 {request.PackageSize},实际 {zipInfo.Length})", 5,
|
||||||
|
$"Package size mismatch (expected {request.PackageSize}, got {zipInfo.Length})");
|
||||||
|
|
||||||
var actualSha = ContentHash.Sha256File(zipPath);
|
var actualSha = ContentHash.Sha256File(zipPath);
|
||||||
if (!string.IsNullOrWhiteSpace(request.PackageSha256) &&
|
if (!string.IsNullOrWhiteSpace(request.PackageSha256) &&
|
||||||
!string.Equals(actualSha, request.PackageSha256, StringComparison.OrdinalIgnoreCase))
|
!string.Equals(actualSha, request.PackageSha256, StringComparison.OrdinalIgnoreCase))
|
||||||
{
|
{
|
||||||
return Fail(updateDir, "更新包 sha256 与清单不符,已丢弃", 5);
|
return Fail(updateDir, "更新包 sha256 与清单不符,已丢弃", 5,
|
||||||
|
"Package sha256 does not match the manifest; discarded");
|
||||||
}
|
}
|
||||||
if (string.IsNullOrWhiteSpace(request.PackageSha256))
|
if (string.IsNullOrWhiteSpace(request.PackageSha256))
|
||||||
_log.Warn("清单没有提供 sha256,仅依赖签名与解压校验");
|
_log.Warn("清单没有提供 sha256,仅依赖签名与解压校验",
|
||||||
|
"Manifest has no sha256; relying on the signature and extraction checks only");
|
||||||
|
|
||||||
SafeArchive.Inspection inspection;
|
SafeArchive.Inspection inspection;
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
inspection = SafeArchive.Inspect(zipPath);
|
inspection = SafeArchive.Inspect(zipPath);
|
||||||
_log.Info($"更新包检查通过:{inspection.Entries} 个条目," +
|
_log.Info($"更新包检查通过:{inspection.Entries} 个条目," +
|
||||||
$"{inspection.UncompressedBytes / 1024 / 1024} MB,压缩比 {inspection.Ratio:0.0}:1");
|
$"{inspection.UncompressedBytes / 1024 / 1024} MB,压缩比 {inspection.Ratio:0.0}:1",
|
||||||
|
$"Package inspection passed: {inspection.Entries} entries, " +
|
||||||
|
$"{inspection.UncompressedBytes / 1024 / 1024} MB, ratio {inspection.Ratio:0.0}:1");
|
||||||
}
|
}
|
||||||
catch (Exception ex)
|
catch (Exception ex)
|
||||||
{
|
{
|
||||||
return Fail(updateDir, "更新包安全性检查失败: " + ex.Message, 5);
|
return Fail(updateDir, "更新包安全性检查失败: " + ex.Message, 5,
|
||||||
|
"Package safety check failed: " + ex.Message);
|
||||||
}
|
}
|
||||||
|
|
||||||
// 5. 解压到暂存区(与安装目录同卷,后续 rename 才是原子的)
|
// 5. 解压到暂存区(与安装目录同卷,后续 rename 才是原子的)
|
||||||
@@ -126,30 +152,39 @@ internal sealed class Applier
|
|||||||
catch (Exception ex)
|
catch (Exception ex)
|
||||||
{
|
{
|
||||||
ClearDirectory(stage);
|
ClearDirectory(stage);
|
||||||
return Fail(updateDir, "解压失败: " + ex.Message, 6);
|
return Fail(updateDir, "解压失败: " + ex.Message, 6, "Extraction failed: " + ex.Message);
|
||||||
}
|
}
|
||||||
|
|
||||||
var artifact = FindArtifact(stage, request.PackageName);
|
var artifact = FindArtifact(stage, request.PackageName);
|
||||||
if (artifact == null)
|
if (artifact == null)
|
||||||
{
|
{
|
||||||
ClearDirectory(stage);
|
ClearDirectory(stage);
|
||||||
return Fail(updateDir, "更新包里没有找到新版程序(" + request.PackageName + ")", 6);
|
return Fail(updateDir, "更新包里没有找到新版程序(" + request.PackageName + ")", 6,
|
||||||
|
"No new launcher found in the package (" + request.PackageName + ")");
|
||||||
}
|
}
|
||||||
|
|
||||||
var target = Path.Combine(installDir, Path.GetFileName(artifact));
|
// 主程序:优先用清单里的包名,否则按已知名字挑一个(发布包是整目录,
|
||||||
var alreadyInstalled = File.Exists(target) || Directory.Exists(target);
|
// 里面同时有 GC-UI.exe / GC.UI.Server.exe / GC-SAVEDOG.exe,不能瞎猜第一个)。
|
||||||
|
var mainName = Path.GetFileName(artifact);
|
||||||
|
var mainTarget = Path.Combine(installDir, mainName);
|
||||||
|
|
||||||
if (_options.DryRun)
|
if (_options.DryRun)
|
||||||
{
|
{
|
||||||
_log.Info($"[dry-run] 校验全部通过,将安装到 {target}");
|
_log.Info($"[dry-run] 校验全部通过,将整目录安装到 {installDir}" +
|
||||||
|
$"({Directory.GetFileSystemEntries(stage).Length} 个顶层条目)",
|
||||||
|
$"[dry-run] All checks passed; would install the whole directory to {installDir} " +
|
||||||
|
$"({Directory.GetFileSystemEntries(stage).Length} top-level entries)");
|
||||||
ClearDirectory(stage);
|
ClearDirectory(stage);
|
||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (alreadyInstalled)
|
var previous = ReadLastGood(updateDir);
|
||||||
|
if (previous != null && SameVersion(previous.Version, request.Version) &&
|
||||||
|
(File.Exists(mainTarget) || Directory.Exists(mainTarget)))
|
||||||
{
|
{
|
||||||
// 同一版本重复下发:当成已安装,避免反复覆盖正在运行的文件
|
// 同一版本重复下发:当成已安装,避免反复覆盖正在运行的文件
|
||||||
_log.Info("目标版本已存在,视为已安装");
|
_log.Info($"v{request.Version} 已安装且上次启动正常,视为已安装",
|
||||||
|
$"v{request.Version} is already installed and started fine last time; treating as installed");
|
||||||
ClearDirectory(stage);
|
ClearDirectory(stage);
|
||||||
TryDelete(zipPath);
|
TryDelete(zipPath);
|
||||||
TryDelete(requestPath);
|
TryDelete(requestPath);
|
||||||
@@ -157,40 +192,38 @@ internal sealed class Applier
|
|||||||
{
|
{
|
||||||
Status = "applied",
|
Status = "applied",
|
||||||
Version = request.Version,
|
Version = request.Version,
|
||||||
PackageName = Path.GetFileName(artifact),
|
PackageName = mainName,
|
||||||
Verified = true,
|
Verified = true,
|
||||||
Message = "目标版本已存在,无需替换"
|
Message = "目标版本已存在,无需替换"
|
||||||
});
|
});
|
||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
// 6. 移入安装目录(不覆盖任何已有文件)
|
// 6. 整目录替换:旧内容先搬到 backup,新内容就位;失败可原样还原。
|
||||||
try
|
// 只动程序文件,.GC(模型库 / 设置 / 更新目录)永远不碰。
|
||||||
{
|
var replaced = new List<(string Name, string? BackupPath)>();
|
||||||
Directory.CreateDirectory(installDir);
|
if (!ReplaceInstallDirectory(stage, installDir, updateDir, replaced, out var replaceError))
|
||||||
if (Directory.Exists(artifact)) Directory.Move(artifact, target);
|
|
||||||
else File.Move(artifact, target);
|
|
||||||
_log.Info("新版已就位: " + Path.GetFileName(target));
|
|
||||||
}
|
|
||||||
catch (Exception ex)
|
|
||||||
{
|
{
|
||||||
|
RestoreFromBackup(installDir, replaced);
|
||||||
ClearDirectory(stage);
|
ClearDirectory(stage);
|
||||||
return Fail(updateDir, "移动到安装目录失败: " + ex.Message, 7);
|
return Fail(updateDir, "安装失败: " + replaceError, 7, "Installation failed: " + replaceError);
|
||||||
}
|
}
|
||||||
|
_log.Info($"新版已就位:{mainName}(替换 {replaced.Count} 个条目)",
|
||||||
|
$"New version in place: {mainName} (replaced {replaced.Count} entries)");
|
||||||
|
|
||||||
// 7. 启动并看护
|
// 7. 启动并看护
|
||||||
var previous = ReadLastGood(updateDir);
|
|
||||||
StartupHealth.Clear(updateDir);
|
StartupHealth.Clear(updateDir);
|
||||||
|
|
||||||
Process? child;
|
Process? child;
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
child = Launch(target);
|
child = Launch(mainTarget);
|
||||||
}
|
}
|
||||||
catch (Exception ex)
|
catch (Exception ex)
|
||||||
{
|
{
|
||||||
child = null;
|
child = null;
|
||||||
_log.Error("启动新版失败: " + ex.Message);
|
_log.Error("启动新版失败: " + ex.Message,
|
||||||
|
"Failed to start the new version: " + ex.Message);
|
||||||
}
|
}
|
||||||
|
|
||||||
var healthy = child != null && WaitForHealth(updateDir, request.Version, child,
|
var healthy = child != null && WaitForHealth(updateDir, request.Version, child,
|
||||||
@@ -198,15 +231,16 @@ internal sealed class Applier
|
|||||||
|
|
||||||
if (healthy)
|
if (healthy)
|
||||||
{
|
{
|
||||||
_log.Info($"v{request.Version} 启动正常,更新完成");
|
_log.Info($"v{request.Version} 启动正常,更新完成",
|
||||||
CleanupOldVersions(installDir, Path.GetFileName(target), request.PlatformLabel);
|
$"v{request.Version} started successfully; update complete");
|
||||||
WriteLastGood(updateDir, request.Version, Path.GetFileName(target));
|
CleanupBackup(updateDir);
|
||||||
|
WriteLastGood(updateDir, request.Version, mainName);
|
||||||
WriteState(updateDir, new SavedogState
|
WriteState(updateDir, new SavedogState
|
||||||
{
|
{
|
||||||
Status = "applied",
|
Status = "applied",
|
||||||
Version = request.Version,
|
Version = request.Version,
|
||||||
PreviousVersion = previous?.Version,
|
PreviousVersion = previous?.Version,
|
||||||
PackageName = Path.GetFileName(target),
|
PackageName = mainName,
|
||||||
Verified = true,
|
Verified = true,
|
||||||
Message = "更新已应用"
|
Message = "更新已应用"
|
||||||
});
|
});
|
||||||
@@ -216,21 +250,23 @@ internal sealed class Applier
|
|||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
// 8. 回滚
|
// 8. 回滚:撤掉新装的文件,把备份原样搬回
|
||||||
_log.Error($"v{request.Version} 启动后未通过健康检查({_options.TimeoutSeconds}s),开始回滚");
|
_log.Error($"v{request.Version} 启动后未通过健康检查({_options.TimeoutSeconds}s),开始回滚",
|
||||||
|
$"v{request.Version} did not pass the health check after {_options.TimeoutSeconds}s; rolling back");
|
||||||
TryKill(child);
|
TryKill(child);
|
||||||
var removed = RemoveNewVersion(target);
|
var restored = RestoreFromBackup(installDir, replaced);
|
||||||
_log.Info(removed ? "已移除未通过检查的新版" : "新版文件被占用,未能完全移除");
|
_log.Info(restored ? "已还原为更新前的文件" : "部分文件未能还原,请手动重新安装",
|
||||||
|
restored ? "Restored the pre-update files" : "Some files could not be restored; please reinstall manually");
|
||||||
|
|
||||||
var restored = TryLaunchPrevious(installDir, updateDir, previous, request.PlatformLabel);
|
var relaunched = restored && TryLaunchPrevious(installDir, updateDir, previous, request.PlatformLabel);
|
||||||
WriteState(updateDir, new SavedogState
|
WriteState(updateDir, new SavedogState
|
||||||
{
|
{
|
||||||
Status = "rolledback",
|
Status = "rolledback",
|
||||||
Version = request.Version,
|
Version = request.Version,
|
||||||
PreviousVersion = previous?.Version,
|
PreviousVersion = previous?.Version,
|
||||||
PackageName = Path.GetFileName(target),
|
PackageName = mainName,
|
||||||
Verified = true,
|
Verified = true,
|
||||||
Message = restored
|
Message = relaunched
|
||||||
? "新版本未通过启动检查,已回滚到上一个版本"
|
? "新版本未通过启动检查,已回滚到上一个版本"
|
||||||
: "新版本未通过启动检查,已移除;未找到可回滚的旧版本,请手动重新安装"
|
: "新版本未通过启动检查,已移除;未找到可回滚的旧版本,请手动重新安装"
|
||||||
});
|
});
|
||||||
@@ -243,11 +279,18 @@ internal sealed class Applier
|
|||||||
|
|
||||||
// ------------------------------------------------------------------ 校验辅助
|
// ------------------------------------------------------------------ 校验辅助
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 包名合法性:只允许「一个文件名」,杜绝 `../` 之类的路径穿越。
|
||||||
|
///
|
||||||
|
/// 不能只认 .app / .exe —— Linux 的启动器没有扩展名
|
||||||
|
/// (GC-1.0.9-linux-amd64),按旧规则会被直接判成非法包名、更新永远失败。
|
||||||
|
/// </summary>
|
||||||
private static bool ValidName(string name)
|
private static bool ValidName(string name)
|
||||||
=> name.Length > 0 && name.Length < 200 &&
|
=> SafeNamePattern.IsMatch(name);
|
||||||
name.IndexOfAny(new[] { '/', '\\', ':', '\0' }) < 0 &&
|
|
||||||
(name.EndsWith(".app", StringComparison.OrdinalIgnoreCase) ||
|
private static readonly Regex SafeNamePattern = new(
|
||||||
name.EndsWith(".exe", StringComparison.OrdinalIgnoreCase));
|
@"^[A-Za-z0-9][A-Za-z0-9._-]{0,198}$",
|
||||||
|
RegexOptions.CultureInvariant | RegexOptions.Compiled);
|
||||||
|
|
||||||
private static bool WaitForExit(int pid, TimeSpan timeout)
|
private static bool WaitForExit(int pid, TimeSpan timeout)
|
||||||
{
|
{
|
||||||
@@ -280,22 +323,64 @@ internal sealed class Applier
|
|||||||
Directory.Move(temp, stage);
|
Directory.Move(temp, stage);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 在解压结果里找主程序。
|
||||||
|
///
|
||||||
|
/// 发布包是「整目录」结构(exe + dll + data/),同一层可能有好几个 exe
|
||||||
|
/// (GC-UI / GC.UI.Server / GC-SAVEDOG / createdump),必须按固定优先级挑,
|
||||||
|
/// 不能取第一个 —— 否则会把守护进程或调试辅助程序当成启动器拉起来。
|
||||||
|
/// </summary>
|
||||||
private static string? FindArtifact(string stage, string packageName)
|
private static string? FindArtifact(string stage, string packageName)
|
||||||
{
|
{
|
||||||
var direct = Path.Combine(stage, packageName);
|
if (!string.IsNullOrWhiteSpace(packageName))
|
||||||
if (File.Exists(direct) || Directory.Exists(direct)) return direct;
|
|
||||||
|
|
||||||
foreach (var entry in Directory.GetFileSystemEntries(stage))
|
|
||||||
{
|
{
|
||||||
var name = Path.GetFileName(entry);
|
var named = Path.Combine(stage, packageName);
|
||||||
if (name.EndsWith(".app", StringComparison.OrdinalIgnoreCase) && Directory.Exists(entry))
|
if (File.Exists(named) || Directory.Exists(named)) return named;
|
||||||
return entry;
|
}
|
||||||
if (name.EndsWith(".exe", StringComparison.OrdinalIgnoreCase) && File.Exists(entry))
|
|
||||||
|
var entries = Directory.GetFileSystemEntries(stage);
|
||||||
|
var byName = entries
|
||||||
|
.Where(e => File.Exists(e))
|
||||||
|
.OrderByDescending(e => MainExecutablePriority(Path.GetFileName(e)))
|
||||||
|
.ThenBy(e => Path.GetFileName(e), StringComparer.OrdinalIgnoreCase)
|
||||||
|
.ToList();
|
||||||
|
|
||||||
|
var best = byName.FirstOrDefault(e => MainExecutablePriority(Path.GetFileName(e)) > 0);
|
||||||
|
if (best != null) return best;
|
||||||
|
|
||||||
|
// macOS:.app 目录本身就是「可执行单元」
|
||||||
|
foreach (var entry in entries)
|
||||||
|
{
|
||||||
|
if (Directory.Exists(entry) &&
|
||||||
|
Path.GetFileName(entry).EndsWith(".app", StringComparison.OrdinalIgnoreCase))
|
||||||
return entry;
|
return entry;
|
||||||
}
|
}
|
||||||
|
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>主程序优先级:数字越大越优先,0 表示不是主程序。</summary>
|
||||||
|
private static int MainExecutablePriority(string fileName)
|
||||||
|
{
|
||||||
|
if (!fileName.EndsWith(".exe", StringComparison.OrdinalIgnoreCase)) return 0;
|
||||||
|
|
||||||
|
// 发布包把启动器改名成 GCL-<版本>-<系统>-<架构>.exe(旧包是 GC-),先按这个模式认出来。
|
||||||
|
if (VersionedExePattern.IsMatch(fileName)) return 110;
|
||||||
|
|
||||||
|
var name = Path.GetFileNameWithoutExtension(fileName);
|
||||||
|
return name switch
|
||||||
|
{
|
||||||
|
"GC-UI" => 100,
|
||||||
|
"GC" => 90,
|
||||||
|
"GC.UI.Server" => 80,
|
||||||
|
// 守护进程 / 调试辅助 / 运行时工具:永远不当主程序
|
||||||
|
"GC-SAVEDOG" => 0,
|
||||||
|
"createdump" => 0,
|
||||||
|
"singlefilehost" => 0,
|
||||||
|
_ => 10
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
// ------------------------------------------------------------------ 启动与看护
|
// ------------------------------------------------------------------ 启动与看护
|
||||||
|
|
||||||
private Process? Launch(string target)
|
private Process? Launch(string target)
|
||||||
@@ -362,13 +447,14 @@ internal sealed class Applier
|
|||||||
var health = StartupHealth.Read(updateDir);
|
var health = StartupHealth.Read(updateDir);
|
||||||
if (health != null && health.Ok && SameVersion(health.Version, version))
|
if (health != null && health.Ok && SameVersion(health.Version, version))
|
||||||
{
|
{
|
||||||
_log.Info($"收到健康标记(pid {health.Pid})");
|
_log.Info($"收到健康标记(pid {health.Pid})", $"Health marker received (pid {health.Pid})");
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (child.HasExited)
|
if (child.HasExited)
|
||||||
{
|
{
|
||||||
_log.Error($"新版进程已退出(退出码 {child.ExitCode})");
|
_log.Error($"新版进程已退出(退出码 {child.ExitCode})",
|
||||||
|
$"The new process exited (code {child.ExitCode})");
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
Thread.Sleep(250);
|
Thread.Sleep(250);
|
||||||
@@ -377,7 +463,8 @@ internal sealed class Applier
|
|||||||
// 超时但进程还活着:可能是尚未写入健康标记的旧构建,谨慎放行
|
// 超时但进程还活着:可能是尚未写入健康标记的旧构建,谨慎放行
|
||||||
if (!child.HasExited)
|
if (!child.HasExited)
|
||||||
{
|
{
|
||||||
_log.Warn("未收到健康标记,但进程仍在运行,按成功处理");
|
_log.Warn("未收到健康标记,但进程仍在运行,按成功处理",
|
||||||
|
"No health marker, but the process is still running; treating as success");
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
return false;
|
return false;
|
||||||
@@ -410,57 +497,254 @@ internal sealed class Applier
|
|||||||
catch { }
|
catch { }
|
||||||
}
|
}
|
||||||
|
|
||||||
// ------------------------------------------------------------------ 清理 / 回滚
|
// ------------------------------------------------------------------ 整目录安装 / 回滚
|
||||||
|
|
||||||
private void CleanupOldVersions(string installDir, string keepName, string platformLabel)
|
/// <summary>
|
||||||
|
/// 把 <paramref name="stage"/> 的内容替换进 <paramref name="installDir"/>。
|
||||||
|
///
|
||||||
|
/// 发布包是「整目录」(启动器 + 后端运行时 + Flutter 前端资源),只搬一个 exe 会留下
|
||||||
|
/// 旧后端 / 旧界面,所以这里按目录整体替换:
|
||||||
|
/// 1. 安装目录里「新版没有」的条目 → 移到 backup(旧版本残留,如上一版的旧文件名);
|
||||||
|
/// 2. 与新版同名的条目 → 先移到 backup,再把新版放进来(覆盖正在被占用的文件会失败,
|
||||||
|
/// 这种情况直接报错并还原,绝不留下半新半旧的目录);
|
||||||
|
/// 3. `.GC` 只合并 `bin/`(非本体文件),其余子目录与更新目录自身一律跳过。
|
||||||
|
///
|
||||||
|
/// 返回 false 时调用方应调用 <see cref="RestoreFromBackup"/> 还原。
|
||||||
|
/// </summary>
|
||||||
|
private bool ReplaceInstallDirectory(string stage, string installDir, string updateDir,
|
||||||
|
List<(string Name, string? BackupPath)> replaced, out string? error)
|
||||||
{
|
{
|
||||||
foreach (var entry in Directory.GetFileSystemEntries(installDir))
|
error = null;
|
||||||
{
|
var backupDir = Path.Combine(updateDir, "backup");
|
||||||
var name = Path.GetFileName(entry);
|
|
||||||
if (string.Equals(name, keepName, StringComparison.OrdinalIgnoreCase)) continue;
|
|
||||||
|
|
||||||
var match = ArtifactPattern.Match(name);
|
|
||||||
if (!match.Success) continue;
|
|
||||||
|
|
||||||
var platform = match.Groups["plat"].Value;
|
|
||||||
if (!string.Equals(platform, platformLabel, StringComparison.OrdinalIgnoreCase))
|
|
||||||
{
|
|
||||||
_log.Info($"保留其它平台版本: {name}");
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
try
|
|
||||||
{
|
|
||||||
if (Directory.Exists(entry)) Directory.Delete(entry, true);
|
|
||||||
else File.Delete(entry);
|
|
||||||
_log.Info("清理旧版本: " + name);
|
|
||||||
}
|
|
||||||
catch (Exception ex)
|
|
||||||
{
|
|
||||||
_log.Warn($"清理旧版本失败 {name}: {ex.Message}");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private bool RemoveNewVersion(string target)
|
|
||||||
{
|
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
if (Directory.Exists(target)) Directory.Delete(target, true);
|
Directory.CreateDirectory(installDir);
|
||||||
else if (File.Exists(target)) File.Delete(target);
|
ClearDirectory(backupDir);
|
||||||
|
Directory.CreateDirectory(backupDir);
|
||||||
|
|
||||||
|
var incoming = new List<string>();
|
||||||
|
foreach (var entry in Directory.GetFileSystemEntries(stage))
|
||||||
|
{
|
||||||
|
var name = Path.GetFileName(entry);
|
||||||
|
if (string.Equals(name, ".GC", StringComparison.OrdinalIgnoreCase))
|
||||||
|
{
|
||||||
|
// .GC 里只有 bin/ 属于程序本体(守护进程这类「非本体」文件),
|
||||||
|
// 其余(config / model / cache / update / logs / safedog)是用户数据,
|
||||||
|
// 整目录替换时必须原地不动。
|
||||||
|
MergeGcBin(entry, installDir, backupDir, replaced);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (IsProtected(name))
|
||||||
|
{
|
||||||
|
// 例如 GC-SAVEDOG.exe:本进程正在运行,Windows 上无法替换。
|
||||||
|
// 保留旧版守护进程即可,它下次启动会随包里的新版本一起被更新。
|
||||||
|
_log.Warn($"跳过受保护文件,保留旧版本:{name}",
|
||||||
|
$"Skipping protected file, keeping the old one: {name}");
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
incoming.Add(entry);
|
||||||
|
}
|
||||||
|
var incomingNames = new HashSet<string>(
|
||||||
|
incoming.Select(e => Path.GetFileName(e)), StringComparer.OrdinalIgnoreCase);
|
||||||
|
|
||||||
|
// 1. 旧版独有的条目先清走(保留在 backup 里以便回滚)
|
||||||
|
foreach (var entry in Directory.GetFileSystemEntries(installDir))
|
||||||
|
{
|
||||||
|
var name = Path.GetFileName(entry);
|
||||||
|
if (incomingNames.Contains(name)) continue;
|
||||||
|
if (IsProtected(name)) continue;
|
||||||
|
if (IsSameOrInside(entry, updateDir)) continue;
|
||||||
|
|
||||||
|
var target = Path.Combine(backupDir, name);
|
||||||
|
MoveEntry(entry, target);
|
||||||
|
replaced.Add((name, target));
|
||||||
|
_log.Info("旧版残留已备份: " + name, "Old leftover backed up: " + name);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. 同名条目:旧 → backup,新 → 安装目录
|
||||||
|
foreach (var entry in incoming)
|
||||||
|
{
|
||||||
|
var name = Path.GetFileName(entry);
|
||||||
|
var target = Path.Combine(installDir, name);
|
||||||
|
var backup = Path.Combine(backupDir, name);
|
||||||
|
|
||||||
|
if (File.Exists(target) || Directory.Exists(target))
|
||||||
|
{
|
||||||
|
MoveEntry(target, backup);
|
||||||
|
replaced.Add((name, backup));
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
// 纯新增:回滚时直接删掉,没有备份可还原
|
||||||
|
replaced.Add((name, null));
|
||||||
|
}
|
||||||
|
|
||||||
|
MoveEntry(entry, target);
|
||||||
|
}
|
||||||
|
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
catch (Exception ex)
|
catch (Exception ex)
|
||||||
{
|
{
|
||||||
_log.Warn("移除新版失败: " + ex.Message);
|
error = ex.Message;
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 合并新包里的 <c>.GC/bin</c>:只搬这一层文件,不动 .GC 下的用户数据。
|
||||||
|
///
|
||||||
|
/// 守护进程放在这里(而不是安装目录根)是为了「非本体文件全部收进 .GC/bin」;
|
||||||
|
/// 但正在运行的是 <c>.GC/safedog</c> 里的副本,所以这里的文件可以安全替换。
|
||||||
|
/// </summary>
|
||||||
|
private void MergeGcBin(string stageGc, string installDir, string backupDir,
|
||||||
|
List<(string Name, string? BackupPath)> replaced)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var bin = Path.Combine(stageGc, "bin");
|
||||||
|
if (!Directory.Exists(bin)) return;
|
||||||
|
|
||||||
|
var relBin = Path.Combine(".GC", "bin");
|
||||||
|
var targetBin = Path.Combine(installDir, relBin);
|
||||||
|
Directory.CreateDirectory(targetBin);
|
||||||
|
|
||||||
|
foreach (var file in Directory.GetFiles(bin))
|
||||||
|
{
|
||||||
|
var name = Path.GetFileName(file);
|
||||||
|
var rel = Path.Combine(relBin, name);
|
||||||
|
var target = Path.Combine(targetBin, name);
|
||||||
|
var backup = Path.Combine(backupDir, ".GC-bin", name);
|
||||||
|
|
||||||
|
if (File.Exists(target))
|
||||||
|
{
|
||||||
|
MoveEntry(target, backup);
|
||||||
|
replaced.Add((rel, backup));
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
replaced.Add((rel, null));
|
||||||
|
}
|
||||||
|
|
||||||
|
MoveEntry(file, target);
|
||||||
|
_log.Info("已更新非本体文件: " + rel, "Updated non-core file: " + rel);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
_log.Warn($"合并 .GC/bin 失败(继续使用已有版本):{ex.Message}",
|
||||||
|
$"Failed to merge .GC/bin (keeping the existing one): {ex.Message}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 把备份里的条目原样搬回安装目录,撤掉新装的内容。
|
||||||
|
/// <paramref name="BackupPath"/> 为 null 表示这一项是新包里独有的(没有旧版本),
|
||||||
|
/// 回滚时只需要删掉。
|
||||||
|
/// </summary>
|
||||||
|
private bool RestoreFromBackup(string installDir, List<(string Name, string? BackupPath)> replaced)
|
||||||
|
{
|
||||||
|
var ok = true;
|
||||||
|
foreach (var (name, backup) in replaced)
|
||||||
|
{
|
||||||
|
var target = Path.Combine(installDir, name);
|
||||||
|
try
|
||||||
|
{
|
||||||
|
// 先撤掉新版(新包里独有的文件也要删干净,否则回滚后目录里新旧混杂)
|
||||||
|
DeleteEntry(target);
|
||||||
|
|
||||||
|
if (string.IsNullOrWhiteSpace(backup) ||
|
||||||
|
(!File.Exists(backup) && !Directory.Exists(backup)))
|
||||||
|
continue;
|
||||||
|
|
||||||
|
MoveEntry(backup, target);
|
||||||
|
_log.Info("已还原: " + name, "Restored: " + name);
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
ok = false;
|
||||||
|
_log.Warn($"还原 {name} 失败: {ex.Message}", $"Failed to restore {name}: {ex.Message}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return ok;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>更新成功:删掉整份备份,不再占用磁盘。</summary>
|
||||||
|
private void CleanupBackup(string updateDir)
|
||||||
|
{
|
||||||
|
var backupDir = Path.Combine(updateDir, "backup");
|
||||||
|
try
|
||||||
|
{
|
||||||
|
if (Directory.Exists(backupDir)) Directory.Delete(backupDir, true);
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
_log.Warn("清理备份失败: " + ex.Message, "Failed to clean up the backup: " + ex.Message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 安装目录里不该被更新碰的东西:
|
||||||
|
/// · .GC —— 模型库、设置、日志、更新目录本身都在这里(只有 bin/ 由 MergeGcBin 单独处理);
|
||||||
|
/// · GC-SAVEDOG.exe —— 本进程正在运行,Windows 上无法替换。
|
||||||
|
/// </summary>
|
||||||
|
private static bool IsProtected(string name)
|
||||||
|
{
|
||||||
|
if (string.Equals(name, ".GC", StringComparison.OrdinalIgnoreCase)) return true;
|
||||||
|
var self = Environment.ProcessPath;
|
||||||
|
if (!string.IsNullOrWhiteSpace(self) &&
|
||||||
|
string.Equals(name, Path.GetFileName(self!), StringComparison.OrdinalIgnoreCase))
|
||||||
|
return true;
|
||||||
|
return string.Equals(name, "backup", StringComparison.OrdinalIgnoreCase);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static bool IsSameOrInside(string path, string root)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var full = Path.GetFullPath(path).TrimEnd(Path.DirectorySeparatorChar);
|
||||||
|
var rootFull = Path.GetFullPath(root).TrimEnd(Path.DirectorySeparatorChar);
|
||||||
|
return full.Equals(rootFull, StringComparison.OrdinalIgnoreCase) ||
|
||||||
|
full.StartsWith(rootFull + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase);
|
||||||
|
}
|
||||||
|
catch { return false; }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>移动条目;跨卷或目标占用时退回「复制 + 删除」。</summary>
|
||||||
|
private static void MoveEntry(string from, string to)
|
||||||
|
{
|
||||||
|
var parent = Path.GetDirectoryName(to);
|
||||||
|
if (!string.IsNullOrWhiteSpace(parent)) Directory.CreateDirectory(parent);
|
||||||
|
|
||||||
|
if (Directory.Exists(from))
|
||||||
|
{
|
||||||
|
Directory.Move(from, to);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
File.Move(from, to, overwrite: true);
|
||||||
|
}
|
||||||
|
catch (IOException)
|
||||||
|
{
|
||||||
|
File.Copy(from, to, overwrite: true);
|
||||||
|
File.Delete(from);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>删除文件或目录,失败时抛出(由调用方决定是否回滚)。</summary>
|
||||||
|
private static void DeleteEntry(string path)
|
||||||
|
{
|
||||||
|
if (Directory.Exists(path)) Directory.Delete(path, true);
|
||||||
|
else if (File.Exists(path)) File.Delete(path);
|
||||||
|
}
|
||||||
|
|
||||||
private bool TryLaunchPrevious(string installDir, string updateDir, LastGoodVersion? lastGood,
|
private bool TryLaunchPrevious(string installDir, string updateDir, LastGoodVersion? lastGood,
|
||||||
string platformLabel)
|
string platformLabel)
|
||||||
{
|
{
|
||||||
// 优先用上次成功的版本;否则挑一个同平台的其它版本
|
// 优先用上次成功启动的主程序;否则按优先级在安装目录里找
|
||||||
var candidates = new List<string>();
|
var candidates = new List<string>();
|
||||||
if (lastGood != null && !string.IsNullOrWhiteSpace(lastGood.PackageName))
|
if (lastGood != null && !string.IsNullOrWhiteSpace(lastGood.PackageName))
|
||||||
candidates.Add(Path.Combine(installDir, lastGood.PackageName));
|
candidates.Add(Path.Combine(installDir, lastGood.PackageName));
|
||||||
@@ -468,25 +752,27 @@ internal sealed class Applier
|
|||||||
foreach (var entry in Directory.GetFileSystemEntries(installDir))
|
foreach (var entry in Directory.GetFileSystemEntries(installDir))
|
||||||
{
|
{
|
||||||
var name = Path.GetFileName(entry);
|
var name = Path.GetFileName(entry);
|
||||||
var match = ArtifactPattern.Match(name);
|
if (IsProtected(name)) continue;
|
||||||
if (!match.Success) continue;
|
if (MainExecutablePriority(name) > 0) candidates.Add(entry);
|
||||||
if (!string.Equals(match.Groups["plat"].Value, platformLabel, StringComparison.OrdinalIgnoreCase))
|
else if (Directory.Exists(entry) &&
|
||||||
continue;
|
name.EndsWith(".app", StringComparison.OrdinalIgnoreCase))
|
||||||
candidates.Add(entry);
|
candidates.Add(entry);
|
||||||
}
|
}
|
||||||
|
|
||||||
foreach (var candidate in candidates)
|
foreach (var candidate in candidates.Distinct(StringComparer.OrdinalIgnoreCase))
|
||||||
{
|
{
|
||||||
if (!File.Exists(candidate) && !Directory.Exists(candidate)) continue;
|
if (!File.Exists(candidate) && !Directory.Exists(candidate)) continue;
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
Launch(candidate);
|
Launch(candidate);
|
||||||
_log.Info("已回滚启动: " + Path.GetFileName(candidate));
|
_log.Info("已回滚启动: " + Path.GetFileName(candidate),
|
||||||
|
"Rolled back and started: " + Path.GetFileName(candidate));
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
catch (Exception ex)
|
catch (Exception ex)
|
||||||
{
|
{
|
||||||
_log.Warn($"回滚启动失败 {Path.GetFileName(candidate)}: {ex.Message}");
|
_log.Warn($"回滚启动失败 {Path.GetFileName(candidate)}: {ex.Message}",
|
||||||
|
$"Failed to start rollback candidate {Path.GetFileName(candidate)}: {ex.Message}");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return false;
|
return false;
|
||||||
@@ -497,12 +783,12 @@ internal sealed class Applier
|
|||||||
private void WriteState(string updateDir, SavedogState state)
|
private void WriteState(string updateDir, SavedogState state)
|
||||||
{
|
{
|
||||||
try { Json.Write(Path.Combine(updateDir, SavedogFiles.State), state); }
|
try { Json.Write(Path.Combine(updateDir, SavedogFiles.State), state); }
|
||||||
catch (Exception ex) { _log.Warn("写状态失败: " + ex.Message); }
|
catch (Exception ex) { _log.Warn("写状态失败: " + ex.Message, "Failed to write state: " + ex.Message); }
|
||||||
}
|
}
|
||||||
|
|
||||||
private int Fail(string updateDir, string message, int code)
|
private int Fail(string updateDir, string message, int code, string? messageEn = null)
|
||||||
{
|
{
|
||||||
_log.Error(message);
|
_log.Error(message, messageEn ?? message);
|
||||||
WriteState(updateDir, new SavedogState { Status = "failed", Message = message });
|
WriteState(updateDir, new SavedogState { Status = "failed", Message = message });
|
||||||
return code;
|
return code;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -37,11 +37,18 @@
|
|||||||
<DebugType>none</DebugType>
|
<DebugType>none</DebugType>
|
||||||
</PropertyGroup>
|
</PropertyGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<!-- 应用器测试要直接构造 Applier(internal):只对测试程序集放开可见性 -->
|
||||||
|
<InternalsVisibleTo Include="GC.Savedog.Tests" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<!-- 与启动器共用同一份安全实现,避免两套逻辑各说各话。
|
<!-- 与启动器共用同一份安全实现,避免两套逻辑各说各话。
|
||||||
ManifestLoader 依赖启动器的 RepoVersion 模型,守护进程不需要,排除。 -->
|
ManifestLoader 依赖启动器的 RepoVersion 模型,守护进程不需要,排除。 -->
|
||||||
<Compile Include="..\GC\src\Security\**\*.cs" Exclude="..\GC\src\Security\ManifestLoader.cs" LinkBase="Security" />
|
<Compile Include="..\GC\src\Security\**\*.cs" Exclude="..\GC\src\Security\ManifestLoader.cs" LinkBase="Security" />
|
||||||
<Compile Include="..\GC\src\Services\Json.cs" Link="Shared\Json.cs" />
|
<Compile Include="..\GC\src\Services\Json.cs" Link="Shared\Json.cs" />
|
||||||
|
<!-- 与启动器共用同一份双语日志实现,保证 .GC/logs 里格式一致 -->
|
||||||
|
<Compile Include="..\GC\src\Services\GcLog.cs" Link="Shared\GcLog.cs" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
</Project>
|
</Project>
|
||||||
+13
-25
@@ -1,34 +1,22 @@
|
|||||||
using System;
|
using System;
|
||||||
using System.IO;
|
using GC.Services;
|
||||||
|
|
||||||
namespace GC.Savedog;
|
namespace GC.Savedog;
|
||||||
|
|
||||||
/// <summary>同时写 stdout 与 .GC/update/savedog.log,便于用户离线排查。</summary>
|
/// <summary>
|
||||||
|
/// 守护进程的日志入口,实际写入 <see cref="GcLog"/>:控制台 + <c>.GC/logs</c> 下的
|
||||||
|
/// <c>gc-YYYYMMDD.log</c>(中文)与 <c>gc-YYYYMMDD.en.log</c>(英文)。
|
||||||
|
///
|
||||||
|
/// 每条日志都必须同时给中英两份文案 —— 用户反馈问题时直接发对应语言的文件。
|
||||||
|
/// </summary>
|
||||||
internal sealed class Log
|
internal sealed class Log
|
||||||
{
|
{
|
||||||
private readonly string? _path;
|
public Log(string? dir)
|
||||||
private readonly object _gate = new();
|
|
||||||
|
|
||||||
public Log(string? path) => _path = path;
|
|
||||||
|
|
||||||
public void Info(string message) => Write("INFO ", message);
|
|
||||||
public void Warn(string message) => Write("WARN ", message);
|
|
||||||
public void Error(string message) => Write("ERROR", message);
|
|
||||||
|
|
||||||
private void Write(string level, string message)
|
|
||||||
{
|
{
|
||||||
var line = $"{DateTime.Now:yyyy-MM-dd HH:mm:ss} [{level}] {message}";
|
if (!string.IsNullOrWhiteSpace(dir)) GcLog.Init(dir);
|
||||||
Console.WriteLine(line);
|
|
||||||
if (string.IsNullOrWhiteSpace(_path)) return;
|
|
||||||
try
|
|
||||||
{
|
|
||||||
lock (_gate)
|
|
||||||
{
|
|
||||||
var dir = Path.GetDirectoryName(_path!);
|
|
||||||
if (!string.IsNullOrEmpty(dir)) Directory.CreateDirectory(dir);
|
|
||||||
File.AppendAllText(_path!, line + "\n");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
catch { /* 日志失败不能影响更新 */ }
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public void Info(string zh, string en) => GcLog.Info(zh, en);
|
||||||
|
public void Warn(string zh, string en) => GcLog.Warn(zh, en);
|
||||||
|
public void Error(string zh, string en) => GcLog.Error(zh, en);
|
||||||
}
|
}
|
||||||
@@ -23,7 +23,7 @@ namespace GC.Savedog;
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
internal static class Program
|
internal static class Program
|
||||||
{
|
{
|
||||||
private const string DefaultKeyId = "gc-2026-11";
|
private const string DefaultKeyId = "gc-2026-12";
|
||||||
private const string DefaultKeyPath = ".signing/gc-signing.pem";
|
private const string DefaultKeyPath = ".signing/gc-signing.pem";
|
||||||
|
|
||||||
private static int Main(string[] args)
|
private static int Main(string[] args)
|
||||||
@@ -67,7 +67,10 @@ internal static class Program
|
|||||||
return 3;
|
return 3;
|
||||||
}
|
}
|
||||||
|
|
||||||
var log = new Log(Path.Combine(Path.GetFullPath(updateDir), SavedogFiles.Log));
|
// 日志统一放 .GC/logs(update 目录的上一层),不再塞在 update/ 里
|
||||||
|
var updateRoot = Path.GetFullPath(updateDir);
|
||||||
|
var home = Path.GetDirectoryName(updateRoot) ?? updateRoot;
|
||||||
|
var log = new Log(Path.Combine(home, "logs"));
|
||||||
var applyOptions = new ApplyOptions
|
var applyOptions = new ApplyOptions
|
||||||
{
|
{
|
||||||
UpdateDir = updateDir,
|
UpdateDir = updateDir,
|
||||||
|
|||||||
+92
-3
@@ -1,6 +1,9 @@
|
|||||||
# GC-UI 持续集成
|
# GC-UI 持续集成
|
||||||
|
|
||||||
夜间 alpha 构建的工作流在 [`.gitea/workflows/gc-ui-alpha.yml`](../.gitea/workflows/gc-ui-alpha.yml)。
|
alpha 构建的工作流在 [`.gitea/workflows/gc-ui-alpha.yml`](../.gitea/workflows/gc-ui-alpha.yml),
|
||||||
|
**只支持手动触发**(定时任务已取消:它绕开 build.sh,产出的包没有后端、没有前端,跑起来只是个空壳;
|
||||||
|
另外 `cron` 里的 `TZ=` 前缀在部分 Gitea 版本上是非法表达式)。
|
||||||
|
PR 审核流水线在 [`.gitea/workflows/pr-check.yml`](../.gitea/workflows/pr-check.yml)。
|
||||||
本仓库是自建 Gitea(不是 GitHub),所以目录是 `.gitea/workflows/`,语法与 GitHub Actions 基本一致,
|
本仓库是自建 Gitea(不是 GitHub),所以目录是 `.gitea/workflows/`,语法与 GitHub Actions 基本一致,
|
||||||
差异集中在 **runner 标签** 和 **API 前缀** 两处。
|
差异集中在 **runner 标签** 和 **API 前缀** 两处。
|
||||||
|
|
||||||
@@ -64,9 +67,95 @@ Windows 还需要 **VS Build Tools 的「使用 C++ 的桌面开发」工作负
|
|||||||
## 本地构建(不经 CI)
|
## 本地构建(不经 CI)
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
# macOS
|
# 按构建主机自动选目标,每条产物都带 Flutter 前端:
|
||||||
|
# macOS 主机 → mac-arm64(原生)+ win-amd64 / win-arm64(mingw 交叉)
|
||||||
|
# Linux 主机 → win-amd64 / win-arm64(mingw 交叉)
|
||||||
|
# Linux 产物默认不出:需 aarch64 主机 + GC_BUILD_LINUX=1
|
||||||
|
# Windows 主机 → win-amd64 / win-arm64(原生)
|
||||||
|
./build.sh build
|
||||||
|
|
||||||
|
# 前端是必需项:flutter 缺失或编译失败会直接中断,
|
||||||
|
# 确需降级成只有 Avalonia 回退界面的包时才用:
|
||||||
|
./build.sh build --allow-no-ui
|
||||||
|
|
||||||
|
# 只编 macOS 前端
|
||||||
./GC-UI/build-ui.sh macos
|
./GC-UI/build-ui.sh macos
|
||||||
|
|
||||||
# Windows
|
# Windows 主机原生构建
|
||||||
GC-UI\build-ui.cmd
|
GC-UI\build-ui.cmd
|
||||||
```
|
```
|
||||||
|
|
||||||
|
### Linux 前端(原生)
|
||||||
|
|
||||||
|
Flutter 的 Linux 桌面端只能在 Linux 上编,需要 GTK3 开发库与 C++ 工具链:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
sudo apt install clang cmake ninja-build pkg-config libgtk-3-dev libstdc++-14-dev
|
||||||
|
```
|
||||||
|
|
||||||
|
`libstdc++-14-dev` 容易漏:clang 18 会去 `/usr/lib/gcc/x86_64-linux-gnu/14/` 找
|
||||||
|
`-lstdc++`,系统只装了 gcc-13 的开发包时链接会失败,报 `cannot find -lstdc++`。
|
||||||
|
|
||||||
|
产物布局:`GC-UI` + `lib/libflutter_linux_gtk.so` + `data/`,与官方 `flutter build
|
||||||
|
linux` 的 bundle 一致,直接铺进 `dist/linux-arm64/`。
|
||||||
|
|
||||||
|
### Windows 前端交叉编译
|
||||||
|
|
||||||
|
Flutter 官方不支持在非 Windows 主机上 `flutter build windows`,但 Windows 嵌入层
|
||||||
|
(`windows/runner/*.cpp` + `cpp_client_wrapper`)是纯 Win32 + 标准 C++,只通过 C ABI
|
||||||
|
调用 `flutter_windows.dll`,所以 mingw-w64 就能编译。整条链路上唯一必须执行的
|
||||||
|
Windows 二进制是 AOT 快照生成器 `gen_snapshot.exe`,交给 wine 跑即可。
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 依赖
|
||||||
|
sudo apt install mingw-w64 cmake ninja-build wine # Linux
|
||||||
|
brew install mingw-w64 cmake ninja # macOS
|
||||||
|
brew install --cask wine-stable # macOS 的 wine
|
||||||
|
|
||||||
|
# 单独构建(默认输出到 GC-UI/frontend/build/windows/x64/runner/Release)
|
||||||
|
./buildsh/cross/build-ui-win-cross.sh [输出目录]
|
||||||
|
```
|
||||||
|
|
||||||
|
产物与官方 toolchain 完全一致,可直接拷到 Windows 运行:
|
||||||
|
|
||||||
|
```
|
||||||
|
GC-UI.exe flutter_windows.dll data/{icudtl.dat, app.so, flutter_assets/}
|
||||||
|
```
|
||||||
|
|
||||||
|
实现分三层:
|
||||||
|
|
||||||
|
| 文件 | 职责 |
|
||||||
|
|---|---|
|
||||||
|
| `buildsh/cross/toolchain-mingw.cmake` | CMake 交叉工具链(posix 线程模型,静态链接 libstdc++,产物只依赖系统 DLL) |
|
||||||
|
| `buildsh/cross/CMakeLists.txt` | 只编 C++ 外壳;绕开 `tool_backend.bat` 与 MSVC 专用参数 |
|
||||||
|
| `buildsh/cross/build-ui-win-cross.sh` | 拉引擎产物、装 `gen_snapshot` 的 wine 包装、生成 AOT 快照、组装 |
|
||||||
|
|
||||||
|
两个容易踩的坑,脚本里已处理:
|
||||||
|
|
||||||
|
- `flutter_tools` 会 exec 路径为 `.../windows-x64-release/gen_snapshot`(**没有 `.exe`**)
|
||||||
|
的文件,所以脚本在原 `.exe` 旁边放一个同名 shell 脚本转调 wine。
|
||||||
|
- `Runner.rc` 在 windres 下有两处不兼容:图标用反斜杠相对路径、`VERSION_AS_STRING`
|
||||||
|
依赖命令行传 `-D` 的转义字符串。脚本生成一份路径与宏都已规整的 rc 副本再编译。
|
||||||
|
|
||||||
|
### 交叉编译必须自己嵌 DPI 清单
|
||||||
|
|
||||||
|
`windows/runner/CMakeLists.txt` 把 `runner.exe.manifest` 当**源文件**列进 target,
|
||||||
|
Visual Studio 生成器会把它交给链接器(`/MANIFESTINPUT`)自动嵌入 exe;
|
||||||
|
但 `buildsh/cross/CMakeLists.txt` 只用 windres 编 `Runner.rc`,CMake 不会做这一步。
|
||||||
|
结果就是交叉编出来的 `GC-UI.exe` **完全没有清单**:Windows 认为它「DPI 不感知」,
|
||||||
|
在 125% / 150% 缩放的屏幕上把整块窗口当位图拉伸 —— 界面整体发虚,中文小字最明显。
|
||||||
|
|
||||||
|
现在两处都已加固,改这块代码时不要拆掉任何一处:
|
||||||
|
|
||||||
|
| 位置 | 做法 |
|
||||||
|
|---|---|
|
||||||
|
| `buildsh/cross/CMakeLists.txt` | 往 `Runner.cross.rc` 追加 `1 24 "<abs>/runner.exe.manifest"`(id 1 = CREATEPROCESS_MANIFEST_RESOURCE_ID,type 24 = RT_MANIFEST) |
|
||||||
|
| `windows/runner/main.cpp` | 建窗之前调 `SetProcessDpiAwarenessContext(PER_MONITOR_AWARE_V2)`,失败依次退到 `SetProcessDpiAwareness` / `SetProcessDPIAware` |
|
||||||
|
|
||||||
|
`main.cpp` 那层是兜底:即使清单因为工具链原因没嵌进去,程序自己也会声明 DPI 感知。
|
||||||
|
验证办法(Windows):`GC-UI.exe` 属性 →「兼容性」里不该出现「替代高 DPI 缩放行为」,
|
||||||
|
或在 125% 缩放下截图,文字边缘应是锐利的 1.25 倍像素,而不是模糊的插值。
|
||||||
|
|
||||||
|
`.gitea/workflows` 里的 `windows` 任务仍然跑在 `windows-latest` 上;若手头只有 macOS/Linux
|
||||||
|
构建机,可以把该任务的 `runs-on` 换成对应标签,直接复用这套交叉编译脚本,
|
||||||
|
不再需要 VS Build Tools。
|
||||||
+35
-6
@@ -55,6 +55,10 @@ Windows 与 macOS 用**同一套 Flutter 代码 + 各自的原生 runner**:
|
|||||||
|
|
||||||
### 1. 启动后端
|
### 1. 启动后端
|
||||||
|
|
||||||
|
发布版里后端不走独立进程:`GC-BOOT` 直接引用本工程,调用
|
||||||
|
`BackendServer.Start(args, port)` 在自己进程内托管,发布包因此只有一个 exe
|
||||||
|
(两个自包含进程会把 60MB 运行时复制两份)。下面的独立运行方式只用于开发调试。
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
# 仓库根目录
|
# 仓库根目录
|
||||||
dotnet run --project GC-UI/backend/GC.UI.Server
|
dotnet run --project GC-UI/backend/GC.UI.Server
|
||||||
@@ -65,7 +69,11 @@ dotnet run --project GC-UI/backend/GC.UI.Server -- --port 17890
|
|||||||
GC_UI_PORT=17890 dotnet run --project GC-UI/backend/GC.UI.Server
|
GC_UI_PORT=17890 dotnet run --project GC-UI/backend/GC.UI.Server
|
||||||
```
|
```
|
||||||
|
|
||||||
启动后会在 `~/.GC/ui-backend.json` 写入 `{ port, pid, url, version, platform }`,前端可据此发现端口。
|
端口约定集中在 `GC.Services.GcUiContract`(`DefaultPort` / `PortEnvVar`):
|
||||||
|
正式启动时由 GC-BOOT 选端口(17890 被占用就往后试 9 个),再通过 `GC_UI_PORT`
|
||||||
|
环境变量同时传给后端和前端,所以**不需要为了换端口重新编译前端**。
|
||||||
|
启动后后端会在 `~/.GC/ui-backend.json` 写入 `{ port, pid, url, version, platform }`,
|
||||||
|
排查问题时可以据此确认实际端口。
|
||||||
|
|
||||||
### 2. 启动前端
|
### 2. 启动前端
|
||||||
|
|
||||||
@@ -141,14 +149,35 @@ flutter test
|
|||||||
# 前后端联调(需要后端正在运行;后端没起时自动跳过)
|
# 前后端联调(需要后端正在运行;后端没起时自动跳过)
|
||||||
flutter test test/backend_contract_test.dart
|
flutter test test/backend_contract_test.dart
|
||||||
|
|
||||||
# 生成界面截图到 test/shots/(视觉检查用)
|
# 生成界面截图到 test/shots/(视觉检查用,不需要后端)
|
||||||
flutter test tool/render_shots_test.dart
|
flutter test tool/render_shots_test.dart
|
||||||
```
|
```
|
||||||
|
|
||||||
截图脚本覆盖四个页面(首页 / 下载 / 设置 / 关于)再加一整套外壳:
|
截图脚本覆盖四个页面(首页 / 下载 / 设置 / 关于),再加一整套外壳与 1024×680 小窗回归:
|
||||||
`test/shots/home.png`、`download.png`、`settings.png`、`about.png`、`shell.png`。
|
`test/shots/home.png`、`download.png`、`settings.png`、`about.png`、`shell.png`、
|
||||||
需要先在本机 17890 端口跑起后端;脚本用 `runAsync` 给真实 HTTP 留出时间,
|
`home-small.png`、`download-small.png`、`settings-small.png`,以及浅色主题的
|
||||||
否则 `flutter_test` 的假时钟会让页面停在加载态。
|
`home-light.png`、`settings-light.png`。小窗用例会顺带抓布局溢出(RenderFlex overflow)。
|
||||||
|
|
||||||
|
四个页面都用预置数据(`initialModels` / `initialSources` / `initialAbout` 等)渲染,
|
||||||
|
所以**不需要先起后端**。测试环境的字体是 Ahem(所有字都是方块),脚本会显式加载
|
||||||
|
系统里的 Noto Sans SC / 微软雅黑 / 苹方,并顺带加载 Material 图标字体,中文和图标才正常。
|
||||||
|
截图必须放在 `runAsync` 里取像素(`toImage` / `toByteData` 走真实引擎管线),
|
||||||
|
否则 fake async 时钟不推进,每个用例会卡满 10 分钟才超时。
|
||||||
|
|
||||||
|
## 界面清晰度(DPI)
|
||||||
|
|
||||||
|
`GC-UI.exe` 必须在启动时就声明 DPI 感知,否则 Windows 在 125% / 150% 缩放下会把
|
||||||
|
整块窗口当位图拉伸,界面看起来「糊」—— 中文小字最先糊。两处保证:
|
||||||
|
|
||||||
|
- `windows/runner/runner.exe.manifest`:PerMonitorV2(原生 MSVC 构建由 CMake 自动嵌入)
|
||||||
|
- `windows/runner/main.cpp`:建窗前再声明一次,依次尝试
|
||||||
|
`SetProcessDpiAwarenessContext` → `SetProcessDpiAwareness` → `SetProcessDPIAware`
|
||||||
|
- `buildsh/cross/CMakeLists.txt`:交叉编译时把清单写进 `.rc`(windres 不会自动嵌入)
|
||||||
|
|
||||||
|
另外主题里做了两件跟「清晰」有关的事:字体族走
|
||||||
|
`Segoe UI + Microsoft YaHei UI`(macOS 走苹方)而不是让引擎随意回退;
|
||||||
|
正文最小 12px、行高固定,中文不再挤成一片。详见
|
||||||
|
[CI.md 的「交叉编译必须自己嵌 DPI 清单」](CI.md#交叉编译必须自己嵌-dpi-清单)。
|
||||||
|
|
||||||
## 「关于」页展示的技术栈
|
## 「关于」页展示的技术栈
|
||||||
|
|
||||||
|
|||||||
@@ -133,6 +133,15 @@ public sealed record AboutDto(
|
|||||||
|
|
||||||
public sealed record LaunchResultDto(bool Ok, string Message);
|
public sealed record LaunchResultDto(bool Ok, string Message);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 通用错误响应。限流 / 参数校验这类与具体业务无关的失败用它,
|
||||||
|
/// 不要复用 <see cref="LaunchResultDto"/> —— 那会让前端误以为「启动模型」有结果。
|
||||||
|
/// </summary>
|
||||||
|
public sealed record ErrorDto(bool Ok, string Message)
|
||||||
|
{
|
||||||
|
public static ErrorDto Of(string message) => new(false, message);
|
||||||
|
}
|
||||||
|
|
||||||
public sealed record DownloadRequest(string SourceId, string ModelId);
|
public sealed record DownloadRequest(string SourceId, string ModelId);
|
||||||
|
|
||||||
public sealed record PathRequest(string Path);
|
public sealed record PathRequest(string Path);
|
||||||
|
|||||||
@@ -28,8 +28,10 @@ public sealed class AvaloniaHost
|
|||||||
{
|
{
|
||||||
private readonly AppServices _services;
|
private readonly AppServices _services;
|
||||||
private readonly object _gate = new();
|
private readonly object _gate = new();
|
||||||
private readonly List<PlayerWindow> _windows = new();
|
private readonly Dictionary<string, PlayerWindow> _windows = new(StringComparer.OrdinalIgnoreCase);
|
||||||
private Task<bool>? _startTask;
|
private readonly TaskCompletionSource<bool> _ready =
|
||||||
|
new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||||
|
private int _started;
|
||||||
|
|
||||||
public AvaloniaHost(AppServices services) => _services = services;
|
public AvaloniaHost(AppServices services) => _services = services;
|
||||||
|
|
||||||
@@ -37,56 +39,60 @@ public sealed class AvaloniaHost
|
|||||||
|
|
||||||
public string? LastError { get; private set; }
|
public string? LastError { get; private set; }
|
||||||
|
|
||||||
public Task<bool> EnsureStartedAsync()
|
/// <summary>
|
||||||
|
/// 后端线程调用:等待「主线程已把 Avalonia 事件循环跑起来」。
|
||||||
|
///
|
||||||
|
/// 关键点:macOS 的 AppKit 要求 NSApplication 在**主线程**。以前这里把
|
||||||
|
/// <c>StartWithClassicDesktopLifetime</c> 丢到一个新建的后台线程里跑,在 macOS 上
|
||||||
|
/// 会直接崩掉整个后端进程(表现为点「启动模型」界面无反应、随后后端消失)。
|
||||||
|
/// 现在改为由启动器在主线程调用 <see cref="RunOnCurrentThread"/>,
|
||||||
|
/// 这里只等待就绪信号。
|
||||||
|
/// </summary>
|
||||||
|
public Task<bool> EnsureStartedAsync() => _ready.Task;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 必须在 UI 主线程调用。启动 Avalonia 桌面生命周期并阻塞,直到 <see cref="Shutdown"/>。
|
||||||
|
/// 返回后(或初始化失败后)调用方负责收尾。
|
||||||
|
/// </summary>
|
||||||
|
public void RunOnCurrentThread()
|
||||||
{
|
{
|
||||||
lock (_gate)
|
if (Interlocked.Exchange(ref _started, 1) == 1) return;
|
||||||
|
|
||||||
|
try
|
||||||
{
|
{
|
||||||
_startTask ??= Task.Run(StartCore);
|
AppBuilder.Configure<HostApp>()
|
||||||
return _startTask;
|
.UsePlatformDetect()
|
||||||
|
.AfterSetup(_ =>
|
||||||
|
{
|
||||||
|
IsAvailable = true;
|
||||||
|
_ready.TrySetResult(true);
|
||||||
|
})
|
||||||
|
.StartWithClassicDesktopLifetime(Array.Empty<string>());
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
// 无桌面会话(CI / 无头环境):模型窗口不可用,但后端其余接口照常。
|
||||||
|
LastError = ex.Message;
|
||||||
|
_ready.TrySetResult(false);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private bool StartCore()
|
/// <summary>从任意线程请求结束事件循环,使 <see cref="RunOnCurrentThread"/> 返回。</summary>
|
||||||
|
public void Shutdown()
|
||||||
{
|
{
|
||||||
var ready = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
|
if (_started == 0) return;
|
||||||
|
try
|
||||||
var thread = new Thread(() =>
|
|
||||||
{
|
{
|
||||||
try
|
Dispatcher.UIThread.Post(() =>
|
||||||
{
|
{
|
||||||
AppBuilder.Configure<HostApp>()
|
if (Application.Current?.ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
|
||||||
.UsePlatformDetect()
|
desktop.Shutdown();
|
||||||
.AfterSetup(_ => ready.TrySetResult(true))
|
});
|
||||||
.StartWithClassicDesktopLifetime(Array.Empty<string>());
|
|
||||||
}
|
|
||||||
catch (Exception ex)
|
|
||||||
{
|
|
||||||
LastError = ex.Message;
|
|
||||||
ready.TrySetResult(false);
|
|
||||||
}
|
|
||||||
})
|
|
||||||
{
|
|
||||||
IsBackground = true,
|
|
||||||
Name = "gc-ui-avalonia"
|
|
||||||
};
|
|
||||||
|
|
||||||
// Windows 上 Avalonia 需要 STA 线程;macOS / Linux 不支持也不必要。
|
|
||||||
if (OperatingSystem.IsWindows())
|
|
||||||
{
|
|
||||||
try { thread.SetApartmentState(ApartmentState.STA); }
|
|
||||||
catch { /* 忽略:部分运行时不允许设置 */ }
|
|
||||||
}
|
}
|
||||||
|
catch
|
||||||
thread.Start();
|
|
||||||
|
|
||||||
if (!ready.Task.Wait(TimeSpan.FromSeconds(30)))
|
|
||||||
{
|
{
|
||||||
LastError = "图形环境初始化超时";
|
// 事件循环尚未建立或已退出:无需处理
|
||||||
return false;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
IsAvailable = ready.Task.Result;
|
|
||||||
return IsAvailable;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>在 Avalonia UI 线程上加载模型并打开它自己的窗口。</summary>
|
/// <summary>在 Avalonia UI 线程上加载模型并打开它自己的窗口。</summary>
|
||||||
@@ -98,6 +104,27 @@ public sealed class AvaloniaHost
|
|||||||
|
|
||||||
return await Dispatcher.UIThread.InvokeAsync<string>(async () =>
|
return await Dispatcher.UIThread.InvokeAsync<string>(async () =>
|
||||||
{
|
{
|
||||||
|
// 同一个模型已经在运行:把已有窗口提到前台,不再加载第二份实例
|
||||||
|
// (连点「启动模型」会各占一份内存与显存,低配机器直接卡死)。
|
||||||
|
lock (_gate)
|
||||||
|
{
|
||||||
|
if (_windows.TryGetValue(package.Id, out var existing))
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
if (existing.WindowState == WindowState.Minimized)
|
||||||
|
existing.WindowState = WindowState.Normal;
|
||||||
|
existing.Activate();
|
||||||
|
return $"模型 {package.Id} 已在运行";
|
||||||
|
}
|
||||||
|
catch
|
||||||
|
{
|
||||||
|
// 窗口已失效:清掉记录,按新窗口重新打开
|
||||||
|
_windows.Remove(package.Id);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
PlayerWindow? window = null;
|
PlayerWindow? window = null;
|
||||||
LoadedModel? loaded = null;
|
LoadedModel? loaded = null;
|
||||||
try
|
try
|
||||||
@@ -111,13 +138,18 @@ public sealed class AvaloniaHost
|
|||||||
|
|
||||||
window = new PlayerWindow(package, loaded);
|
window = new PlayerWindow(package, loaded);
|
||||||
var captured = loaded;
|
var captured = loaded;
|
||||||
|
var id = package.Id;
|
||||||
window.Closed += (_, _) =>
|
window.Closed += (_, _) =>
|
||||||
{
|
{
|
||||||
try { captured.Dispose(); } catch { /* 释放失败不影响退出 */ }
|
try { captured.Dispose(); } catch { /* 释放失败不影响退出 */ }
|
||||||
lock (_gate) _windows.Remove(window!);
|
lock (_gate)
|
||||||
|
{
|
||||||
|
if (_windows.TryGetValue(id, out var current) && ReferenceEquals(current, window))
|
||||||
|
_windows.Remove(id);
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
lock (_gate) _windows.Add(window);
|
lock (_gate) _windows[id] = window;
|
||||||
window.Show();
|
window.Show();
|
||||||
return $"已启动模型 {package.Id}";
|
return $"已启动模型 {package.Id}";
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,678 @@
|
|||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.IO;
|
||||||
|
using System.Linq;
|
||||||
|
using System.Text.Json;
|
||||||
|
using System.Threading;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
using GC.Download;
|
||||||
|
using GC.Models;
|
||||||
|
using GC.Services;
|
||||||
|
using GC.UI.Server;
|
||||||
|
using Microsoft.AspNetCore.Builder;
|
||||||
|
using Microsoft.AspNetCore.Hosting;
|
||||||
|
using Microsoft.AspNetCore.Http;
|
||||||
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
|
using Microsoft.Extensions.Hosting;
|
||||||
|
using Microsoft.Extensions.Logging;
|
||||||
|
|
||||||
|
namespace GC.UI.Server;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// GC-UI 后端(本地 HTTP 服务:模型扫描 / 下载 / 更新 / 设置 / 模型窗口宿主)。
|
||||||
|
///
|
||||||
|
/// 两种跑法共用同一份代码:
|
||||||
|
/// · 独立进程:<c>GC.UI.Server</c> 可执行文件(开发调试 / 旧包兼容);
|
||||||
|
/// · 进程内:启动器直接调用 <see cref="Start"/>,把后端跑在自己的进程里 ——
|
||||||
|
/// 发布包因此只需要一个 exe,不必再复制一份完整的 .NET 运行时。
|
||||||
|
/// </summary>
|
||||||
|
public static class BackendServer
|
||||||
|
{
|
||||||
|
/// <summary>按命令行 / GC_UI_PORT 解析端口并构建(未启动)的后端。</summary>
|
||||||
|
public static WebApplication StartFromCommandLine(string[] args)
|
||||||
|
=> Start(args, ResolvePort(args), out _);
|
||||||
|
|
||||||
|
/// <summary>同上,并交出模型窗口宿主(独立进程入口用:主线程留给 Avalonia)。</summary>
|
||||||
|
public static WebApplication StartFromCommandLine(string[] args, out AvaloniaHost uiHost)
|
||||||
|
=> Start(args, ResolvePort(args), out uiHost);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 构建后端。返回的 <see cref="WebApplication"/> 尚未启动:
|
||||||
|
/// 独立进程直接 <c>Run()</c>,启动器用 <c>StartAsync()</c> 之后继续拉起界面。
|
||||||
|
/// </summary>
|
||||||
|
public static WebApplication Start(string[] args, int port)
|
||||||
|
=> Start(args, port, out _);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 构建后端,并通过 <paramref name="uiHost"/> 交出模型窗口宿主。
|
||||||
|
///
|
||||||
|
/// 调用方(启动器)必须在**主线程**调用 <see cref="AvaloniaHost.RunOnCurrentThread"/>:
|
||||||
|
/// macOS 的 AppKit 要求 NSApplication 运行在主线程,否则打开模型窗口时整个进程会崩溃。
|
||||||
|
/// </summary>
|
||||||
|
public static WebApplication Start(string[] args, int port, out AvaloniaHost uiHost)
|
||||||
|
{
|
||||||
|
// 下载模块(GC-DOWNLOAD)通过宿主钩子注入,和 GC-BOOT 的做法一致。
|
||||||
|
DownloadModuleHost.Factory = new DownloadModuleFactory();
|
||||||
|
|
||||||
|
var services = AppServices.Create();
|
||||||
|
var host = new AvaloniaHost(services);
|
||||||
|
uiHost = host;
|
||||||
|
|
||||||
|
var builder = WebApplication.CreateBuilder(new WebApplicationOptions { Args = args });
|
||||||
|
builder.Logging.ClearProviders();
|
||||||
|
builder.WebHost.UseUrls($"http://127.0.0.1:{port}");
|
||||||
|
|
||||||
|
// 本地伴随进程:限制请求体大小、关闭 Server 头、收紧超时,减少被本地恶意页面
|
||||||
|
// 或异常客户端拖垮的攻击面。
|
||||||
|
builder.WebHost.ConfigureKestrel(options =>
|
||||||
|
{
|
||||||
|
options.AddServerHeader = false;
|
||||||
|
options.Limits.MaxRequestBodySize = 2 * 1024 * 1024;
|
||||||
|
options.Limits.RequestHeadersTimeout = TimeSpan.FromSeconds(15);
|
||||||
|
options.Limits.KeepAliveTimeout = TimeSpan.FromMinutes(2);
|
||||||
|
options.Limits.MaxConcurrentConnections = 64;
|
||||||
|
});
|
||||||
|
|
||||||
|
// 桌面端(Windows/macOS)走原生 HTTP,不需要 CORS;
|
||||||
|
// 这里放开本机回环来源,方便用 `flutter run -d chrome` 调试界面。
|
||||||
|
builder.Services.AddCors(options => options.AddDefaultPolicy(policy => policy
|
||||||
|
.SetIsOriginAllowed(origin =>
|
||||||
|
Uri.TryCreate(origin, UriKind.Absolute, out var uri) &&
|
||||||
|
(uri.Host == "127.0.0.1" || uri.Host == "localhost" || uri.Host == "::1"))
|
||||||
|
.AllowAnyHeader()
|
||||||
|
.AllowAnyMethod()));
|
||||||
|
|
||||||
|
var app = builder.Build();
|
||||||
|
app.UseCors();
|
||||||
|
|
||||||
|
// 日志与启动器共用 .GC/logs,整条启动链路(启动器 → 后端 → 守护进程)都在同一组文件里。
|
||||||
|
var logPaths = AppPaths.Discover();
|
||||||
|
GcLog.Init(logPaths.LogsRoot);
|
||||||
|
GcLog.Info($"GC-UI 后端启动,监听 127.0.0.1:{port}",
|
||||||
|
$"GC-UI backend started on 127.0.0.1:{port}");
|
||||||
|
|
||||||
|
// 设置白名单 / 标识校验用到的规则(只在本进程内使用)。
|
||||||
|
var allowedLanguages = new HashSet<string>(StringComparer.OrdinalIgnoreCase)
|
||||||
|
{ "auto", "zh-CN", "en" };
|
||||||
|
var allowedThemes = new HashSet<string>(StringComparer.OrdinalIgnoreCase)
|
||||||
|
{ "light", "dark", "system" };
|
||||||
|
var accentHexRegex = new System.Text.RegularExpressions.Regex(
|
||||||
|
"^#(?:[0-9A-Fa-f]{6})$", System.Text.RegularExpressions.RegexOptions.Compiled);
|
||||||
|
var safeIdRegex = new System.Text.RegularExpressions.Regex(
|
||||||
|
"^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$", System.Text.RegularExpressions.RegexOptions.Compiled);
|
||||||
|
|
||||||
|
// 安全响应头 + Host/Origin 校验(抵御 DNS rebinding 与跨站调用)。
|
||||||
|
app.Use(async (context, next) =>
|
||||||
|
{
|
||||||
|
var headers = context.Response.Headers;
|
||||||
|
headers["X-Content-Type-Options"] = "nosniff";
|
||||||
|
headers["X-Frame-Options"] = "DENY";
|
||||||
|
headers["Referrer-Policy"] = "no-referrer";
|
||||||
|
headers["Content-Security-Policy"] = "default-src 'none'; frame-ancestors 'none'";
|
||||||
|
headers["Cache-Control"] = "no-store";
|
||||||
|
|
||||||
|
var host = context.Request.Host.Host;
|
||||||
|
if (!string.Equals(host, "127.0.0.1", StringComparison.OrdinalIgnoreCase) &&
|
||||||
|
!string.Equals(host, "localhost", StringComparison.OrdinalIgnoreCase) &&
|
||||||
|
!string.Equals(host, "::1", StringComparison.OrdinalIgnoreCase))
|
||||||
|
{
|
||||||
|
context.Response.StatusCode = StatusCodes.Status403Forbidden;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
var origin = context.Request.Headers.Origin.ToString();
|
||||||
|
if (!string.IsNullOrEmpty(origin) &&
|
||||||
|
!(Uri.TryCreate(origin, UriKind.Absolute, out var parsed) &&
|
||||||
|
(parsed.Host == "127.0.0.1" || parsed.Host == "localhost" || parsed.Host == "::1")))
|
||||||
|
{
|
||||||
|
context.Response.StatusCode = StatusCodes.Status403Forbidden;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
await next();
|
||||||
|
});
|
||||||
|
|
||||||
|
// 写入类接口做简单限流:单 IP 每秒最多 40 次,防止本地脚本刷爆下载/更新。
|
||||||
|
var writeBuckets =
|
||||||
|
new System.Collections.Concurrent.ConcurrentDictionary<string, (long Window, int Count)>();
|
||||||
|
app.Use(async (context, next) =>
|
||||||
|
{
|
||||||
|
if (HttpMethods.IsPost(context.Request.Method) ||
|
||||||
|
HttpMethods.IsDelete(context.Request.Method))
|
||||||
|
{
|
||||||
|
var key = context.Connection.RemoteIpAddress?.ToString() ?? "local";
|
||||||
|
var now = Environment.TickCount64;
|
||||||
|
|
||||||
|
// 定期丢弃过期窗口:本机连接数不多,但长时间运行后桶只增不减会缓慢泄漏。
|
||||||
|
if (writeBuckets.Count > 256)
|
||||||
|
{
|
||||||
|
foreach (var entry in writeBuckets)
|
||||||
|
{
|
||||||
|
if (now - entry.Value.Window > 60_000)
|
||||||
|
writeBuckets.TryRemove(entry.Key, out _);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var bucket = writeBuckets.AddOrUpdate(
|
||||||
|
key,
|
||||||
|
_ => (now, 1),
|
||||||
|
(_, old) => now - old.Window > 1000 ? (now, 1) : (old.Window, old.Count + 1));
|
||||||
|
|
||||||
|
if (bucket.Count > 40)
|
||||||
|
{
|
||||||
|
context.Response.StatusCode = StatusCodes.Status429TooManyRequests;
|
||||||
|
await context.Response.WriteAsJsonAsync(ErrorDto.Of("请求过于频繁,请稍后再试"));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
await next();
|
||||||
|
});
|
||||||
|
|
||||||
|
// ---- 健康检查 -------------------------------------------------------------
|
||||||
|
|
||||||
|
app.MapGet("/api/health", () => Results.Ok(new HealthDto(
|
||||||
|
true,
|
||||||
|
LauncherRuntimeInfo.CurrentLauncherVersion,
|
||||||
|
LauncherRuntimeInfo.CurrentRid,
|
||||||
|
host.IsAvailable,
|
||||||
|
host.LastError)));
|
||||||
|
|
||||||
|
// ---- 已安装模型 -----------------------------------------------------------
|
||||||
|
|
||||||
|
app.MapGet("/api/models", () =>
|
||||||
|
Results.Ok(services.Models.Scan().Select(ToModelDto).ToList()));
|
||||||
|
|
||||||
|
app.MapGet("/api/models/{id}/preview", (string id, HttpResponse response) =>
|
||||||
|
{
|
||||||
|
if (!IsSafeId(id)) return Results.BadRequest(ErrorDto.Of("模型标识无效"));
|
||||||
|
var package = services.Models.Find(id);
|
||||||
|
if (package == null || !File.Exists(package.PreviewPath)) return Results.NotFound();
|
||||||
|
|
||||||
|
// 封面是静态图,允许前端缓存:默认全局中间件写的 no-store 会让每次滚动都重新请求。
|
||||||
|
// 按扩展名给准确的 MIME —— 统一写 image/png 时,WebP / JPEG 封面在部分平台显示不出来。
|
||||||
|
response.Headers.CacheControl = "private, max-age=300";
|
||||||
|
return Results.File(package.PreviewPath, GuessImageContentType(package.PreviewPath));
|
||||||
|
});
|
||||||
|
|
||||||
|
app.MapPost("/api/models/{id}/launch", async (string id) =>
|
||||||
|
{
|
||||||
|
if (!IsSafeId(id)) return Results.BadRequest(new LaunchResultDto(false, "模型标识无效"));
|
||||||
|
var package = services.Models.Find(id);
|
||||||
|
if (package == null) return Results.NotFound(new LaunchResultDto(false, $"没有找到模型 {id}"));
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
services.Memory.Refresh();
|
||||||
|
var message = await host.LaunchAsync(package);
|
||||||
|
return Results.Ok(new LaunchResultDto(true, message));
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
// 细节只写日志,不回显给调用方,避免泄漏本机路径等内部信息。
|
||||||
|
Console.Error.WriteLine($"[launch] 启动模型 {id} 失败: {ex}");
|
||||||
|
return Results.Json(new LaunchResultDto(false, "模型启动失败,请查看后端日志"), statusCode: 503);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
app.MapDelete("/api/models/{id}", (string id) =>
|
||||||
|
{
|
||||||
|
if (!IsSafeId(id)) return Results.BadRequest(ErrorDto.Of("模型标识无效"));
|
||||||
|
var ok = services.Models.Delete(id);
|
||||||
|
if (ok) services.Models.NotifyChanged();
|
||||||
|
return ok
|
||||||
|
? Results.Ok(new LaunchResultDto(true, $"已删除模型 {id}"))
|
||||||
|
: Results.NotFound(ErrorDto.Of($"没有找到模型 {id}"));
|
||||||
|
});
|
||||||
|
|
||||||
|
// ---- 设置 -----------------------------------------------------------------
|
||||||
|
|
||||||
|
app.MapGet("/api/settings", () => Results.Ok(ToSettingsDto()));
|
||||||
|
|
||||||
|
app.MapPost("/api/settings", (SettingsPatch? patch) =>
|
||||||
|
{
|
||||||
|
if (patch == null) return Results.BadRequest(ErrorDto.Of("缺少设置内容"));
|
||||||
|
|
||||||
|
// 白名单校验:设置项会写进磁盘并被前端直接使用,不接受任意字符串。
|
||||||
|
if (patch.Language != null && !allowedLanguages.Contains(patch.Language))
|
||||||
|
return Results.BadRequest(ErrorDto.Of("不支持的界面语言"));
|
||||||
|
if (patch.Theme != null && !allowedThemes.Contains(patch.Theme))
|
||||||
|
return Results.BadRequest(ErrorDto.Of("不支持的主题"));
|
||||||
|
if (patch.AccentColor != null && !accentHexRegex.IsMatch(patch.AccentColor))
|
||||||
|
return Results.BadRequest(ErrorDto.Of("主题色需为 #RRGGBB"));
|
||||||
|
if (patch.UpdateRepository != null && !IsAllowedRepository(patch.UpdateRepository))
|
||||||
|
return Results.BadRequest(ErrorDto.Of("更新仓库地址不受信任"));
|
||||||
|
|
||||||
|
services.Settings.Apply(s =>
|
||||||
|
{
|
||||||
|
if (patch.Language != null) s.Language = patch.Language;
|
||||||
|
if (patch.Theme != null) s.Theme = patch.Theme;
|
||||||
|
if (patch.AccentColor != null) s.AccentColor = patch.AccentColor.ToUpperInvariant();
|
||||||
|
if (patch.RenderFps.HasValue) s.RenderFps = Math.Clamp(patch.RenderFps.Value, 12, 120);
|
||||||
|
if (patch.MemoryMb.HasValue) s.MemoryMb = Math.Clamp(patch.MemoryMb.Value, 256, 16384);
|
||||||
|
if (patch.MemoryAuto.HasValue) s.MemoryAuto = patch.MemoryAuto.Value;
|
||||||
|
if (patch.AutoUpdateOnStartup.HasValue) s.AutoUpdateOnStartup = patch.AutoUpdateOnStartup.Value;
|
||||||
|
if (patch.RequireSignedManifest.HasValue) s.RequireSignedManifest = patch.RequireSignedManifest.Value;
|
||||||
|
if (patch.UpdateRepository != null) s.UpdateRepository = patch.UpdateRepository;
|
||||||
|
if (patch.UpdateLocalRoot != null) s.UpdateLocalRoot = patch.UpdateLocalRoot;
|
||||||
|
if (patch.ModelRootOverride != null) s.ModelRootOverride = patch.ModelRootOverride;
|
||||||
|
});
|
||||||
|
|
||||||
|
if (patch.Language != null) L.I.SetLanguage(patch.Language);
|
||||||
|
if (patch.MemoryMb.HasValue || patch.MemoryAuto.HasValue)
|
||||||
|
services.Memory.ApplyAuto(services.Settings.Current.MemoryAuto, services.Settings.Current.MemoryMb);
|
||||||
|
|
||||||
|
return Results.Ok(ToSettingsDto());
|
||||||
|
});
|
||||||
|
|
||||||
|
// ---- 模型源 ---------------------------------------------------------------
|
||||||
|
|
||||||
|
app.MapGet("/api/sources", () =>
|
||||||
|
Results.Ok(services.Settings.Current.Sources.Select(ToSourceDto).ToList()));
|
||||||
|
|
||||||
|
app.MapPost("/api/sources/select", async (ForceRequest? request) =>
|
||||||
|
{
|
||||||
|
var force = request?.Force ?? false;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var fastest = await services.Selector.PickFastestAsync(force, CancellationToken.None);
|
||||||
|
services.Updates.UseRemote(services.DownloadModule.CreateRemote(fastest));
|
||||||
|
return Results.Ok(new LatencyDto(
|
||||||
|
fastest.Id, fastest.Name,
|
||||||
|
services.Selector.LastLatency.TryGetValue(fastest.Id, out var ms) ? ms : 0));
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
Console.Error.WriteLine($"[sources] 切换模型源失败: {ex}");
|
||||||
|
return Results.Json(ErrorDto.Of("模型源切换失败"), statusCode: 503);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
app.MapGet("/api/remote/models", async (string? sourceId, bool force) =>
|
||||||
|
{
|
||||||
|
var source = ResolveSource(sourceId);
|
||||||
|
if (source == null) return Results.NotFound(ErrorDto.Of("没有可用的模型源"));
|
||||||
|
|
||||||
|
var index = await services.Sources.FetchAsync(source, force, null, CancellationToken.None);
|
||||||
|
var installed = services.Models.Scan()
|
||||||
|
.ToDictionary(p => p.Id, p => p.Manifest.Version, StringComparer.OrdinalIgnoreCase);
|
||||||
|
|
||||||
|
return Results.Ok(new SourceIndexDto(
|
||||||
|
index.SourceId,
|
||||||
|
index.Root,
|
||||||
|
index.FromCache,
|
||||||
|
index.Error,
|
||||||
|
index.ResolvedFrom,
|
||||||
|
index.Models.Select(m => new RemoteModelDto(
|
||||||
|
m.Id,
|
||||||
|
m.LocalizedName,
|
||||||
|
m.LocalizedDescription,
|
||||||
|
m.Manifest.Version,
|
||||||
|
m.SizeBytes,
|
||||||
|
ModelScanner.HumanSize(m.SizeBytes),
|
||||||
|
m.SourceId,
|
||||||
|
installed.ContainsKey(m.Id),
|
||||||
|
installed.TryGetValue(m.Id, out var v) ? v : null)).ToList()));
|
||||||
|
});
|
||||||
|
|
||||||
|
// ---- 下载 -----------------------------------------------------------------
|
||||||
|
|
||||||
|
app.MapPost("/api/download", async (DownloadRequest? request) =>
|
||||||
|
{
|
||||||
|
if (request == null || string.IsNullOrWhiteSpace(request.ModelId))
|
||||||
|
return Results.BadRequest(ErrorDto.Of("缺少 modelId"));
|
||||||
|
|
||||||
|
var source = ResolveSource(request.SourceId);
|
||||||
|
if (source == null) return Results.NotFound(ErrorDto.Of("没有可用的模型源"));
|
||||||
|
|
||||||
|
var index = await services.Sources.FetchAsync(source, false, null, CancellationToken.None);
|
||||||
|
var model = index.Models.FirstOrDefault(m =>
|
||||||
|
m.Id.Equals(request.ModelId, StringComparison.OrdinalIgnoreCase));
|
||||||
|
if (model == null)
|
||||||
|
return Results.NotFound(ErrorDto.Of($"源里没有模型 {request.ModelId}"));
|
||||||
|
|
||||||
|
var job = services.Downloads.Enqueue(model);
|
||||||
|
return Results.Ok(ToJobDto(job));
|
||||||
|
});
|
||||||
|
|
||||||
|
app.MapGet("/api/download/jobs", () =>
|
||||||
|
Results.Ok(services.Downloads.Jobs.Select(ToJobDto).ToList()));
|
||||||
|
|
||||||
|
app.MapPost("/api/download/{id}/cancel", (string id) =>
|
||||||
|
ActOnJob(id, job => services.Downloads.Cancel(job)));
|
||||||
|
|
||||||
|
app.MapPost("/api/download/{id}/retry", (string id) =>
|
||||||
|
ActOnJob(id, job => services.Downloads.Retry(job)));
|
||||||
|
|
||||||
|
app.MapPost("/api/download/{id}/remove", (string id) =>
|
||||||
|
ActOnJob(id, job => services.Downloads.Remove(job)));
|
||||||
|
|
||||||
|
app.MapPost("/api/download/clear-finished", () =>
|
||||||
|
{
|
||||||
|
services.Downloads.ClearFinished();
|
||||||
|
return Results.Ok(new LaunchResultDto(true, "已清除完成的任务"));
|
||||||
|
});
|
||||||
|
|
||||||
|
// ---- 更新 -----------------------------------------------------------------
|
||||||
|
|
||||||
|
app.MapPost("/api/update/check", async (ForceRequest? request) =>
|
||||||
|
{
|
||||||
|
var force = request?.Force ?? true;
|
||||||
|
var messages = new List<string>();
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var fastest = await services.Selector.PickFastestAsync(force, CancellationToken.None);
|
||||||
|
services.Updates.UseRemote(services.DownloadModule.CreateRemote(fastest));
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
Console.Error.WriteLine($"[update] 测速失败,沿用当前源: {ex.Message}");
|
||||||
|
}
|
||||||
|
|
||||||
|
string? launcherLatest = null;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
launcherLatest = await services.LauncherUpdates.CheckAsync(
|
||||||
|
services.Updates.Remote, CancellationToken.None);
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
Console.Error.WriteLine($"[update] 启动器版本检查失败: {ex.Message}");
|
||||||
|
}
|
||||||
|
|
||||||
|
var progress = new Progress<UpdateProgress>(p =>
|
||||||
|
{
|
||||||
|
if (!string.IsNullOrWhiteSpace(p.Message)) messages.Add(p.Message);
|
||||||
|
});
|
||||||
|
|
||||||
|
var result = await services.Updates.RunAsync(force, progress, CancellationToken.None);
|
||||||
|
|
||||||
|
return Results.Ok(new UpdateCheckDto(
|
||||||
|
result.Outcome.ToString(),
|
||||||
|
result.Message,
|
||||||
|
result.UpdatedModels,
|
||||||
|
result.ModelNames,
|
||||||
|
result.LauncherMessage,
|
||||||
|
result.Error,
|
||||||
|
launcherLatest,
|
||||||
|
services.Updates.Remote.DisplayName,
|
||||||
|
services.Selector.LastLatency
|
||||||
|
.Select(kv => new LatencyDto(
|
||||||
|
kv.Key,
|
||||||
|
SourcePreset.Find(kv.Key)?.Name ?? kv.Key,
|
||||||
|
kv.Value))
|
||||||
|
.ToList()));
|
||||||
|
});
|
||||||
|
|
||||||
|
// ---- 关于 -----------------------------------------------------------------
|
||||||
|
|
||||||
|
app.MapGet("/api/about", async () =>
|
||||||
|
{
|
||||||
|
var repository = services.Settings.Current.UpdateRepository;
|
||||||
|
var contributors = new List<ContributorDto>();
|
||||||
|
try
|
||||||
|
{
|
||||||
|
foreach (var c in await ContributorsService.FetchAsync(repository, CancellationToken.None))
|
||||||
|
contributors.Add(new ContributorDto(c.DisplayName, c.Contributions, c.AvatarUrl));
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
Console.Error.WriteLine($"[about] 读取贡献者失败: {ex.Message}");
|
||||||
|
}
|
||||||
|
|
||||||
|
return Results.Ok(new AboutDto(
|
||||||
|
"Morris GC",
|
||||||
|
LauncherRuntimeInfo.CurrentLauncherVersion,
|
||||||
|
LauncherRuntimeInfo.CurrentRid,
|
||||||
|
repository,
|
||||||
|
contributors,
|
||||||
|
// 「关于」页展示的技术栈信息:源码语言与前端框架。
|
||||||
|
SourceLanguage: "C#",
|
||||||
|
Frontend: "Flutter"));
|
||||||
|
});
|
||||||
|
|
||||||
|
// ---- 系统集成 -------------------------------------------------------------
|
||||||
|
|
||||||
|
app.MapPost("/api/shell/open-folder", (PathRequest? request) =>
|
||||||
|
{
|
||||||
|
var path = request?.Path;
|
||||||
|
if (string.IsNullOrWhiteSpace(path))
|
||||||
|
return Results.BadRequest(ErrorDto.Of("缺少 path"));
|
||||||
|
|
||||||
|
// 只允许打开启动器自己的目录,避免前端被当成任意路径执行器
|
||||||
|
if (!IsInsideKnownRoot(path!))
|
||||||
|
return Results.BadRequest(ErrorDto.Of("只允许打开启动器自己的目录"));
|
||||||
|
|
||||||
|
Shell.OpenFolder(path!);
|
||||||
|
return Results.Ok(new LaunchResultDto(true, "已打开目录"));
|
||||||
|
});
|
||||||
|
|
||||||
|
app.MapPost("/api/shell/open-url", (UrlRequest? request) =>
|
||||||
|
{
|
||||||
|
var url = request?.Url;
|
||||||
|
if (string.IsNullOrWhiteSpace(url) || url.Length > 2048 ||
|
||||||
|
!Uri.TryCreate(url, UriKind.Absolute, out var uri))
|
||||||
|
return Results.BadRequest(ErrorDto.Of("URL 无效"));
|
||||||
|
|
||||||
|
if (uri.Scheme != Uri.UriSchemeHttp && uri.Scheme != Uri.UriSchemeHttps)
|
||||||
|
return Results.BadRequest(ErrorDto.Of("只允许 http/https 链接"));
|
||||||
|
|
||||||
|
if (!string.IsNullOrEmpty(uri.UserInfo))
|
||||||
|
return Results.BadRequest(ErrorDto.Of("URL 不允许携带账号密码"));
|
||||||
|
|
||||||
|
Shell.OpenUrl(url!);
|
||||||
|
return Results.Ok(new LaunchResultDto(true, "已打开链接"));
|
||||||
|
});
|
||||||
|
|
||||||
|
// ---- 启动 -----------------------------------------------------------------
|
||||||
|
|
||||||
|
WriteEndpointFile(services, port);
|
||||||
|
Console.WriteLine($"[GC-UI] 后端已启动: http://127.0.0.1:{port}");
|
||||||
|
Console.WriteLine($"[GC-UI] 模型库: {services.Paths.ModelRoot}");
|
||||||
|
|
||||||
|
return app;
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// 局部辅助
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
static void WriteEndpointFile(AppServices services, int port)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var file = Path.Combine(services.Paths.HomeRoot, "ui-backend.json");
|
||||||
|
var payload = JsonSerializer.Serialize(new
|
||||||
|
{
|
||||||
|
port,
|
||||||
|
pid = Environment.ProcessId,
|
||||||
|
url = $"http://127.0.0.1:{port}",
|
||||||
|
version = LauncherRuntimeInfo.CurrentLauncherVersion,
|
||||||
|
platform = LauncherRuntimeInfo.CurrentRid,
|
||||||
|
startedAt = DateTimeOffset.UtcNow.ToString("o")
|
||||||
|
}, new JsonSerializerOptions { WriteIndented = true });
|
||||||
|
|
||||||
|
File.WriteAllText(file, payload);
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
Console.Error.WriteLine($"[GC-UI] 写入端点文件失败: {ex.Message}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>按扩展名推断图片 MIME;模型封面允许 png / jpg / webp / gif。</summary>
|
||||||
|
static string GuessImageContentType(string path) => Path.GetExtension(path).ToLowerInvariant() switch
|
||||||
|
{
|
||||||
|
".jpg" or ".jpeg" => "image/jpeg",
|
||||||
|
".webp" => "image/webp",
|
||||||
|
".gif" => "image/gif",
|
||||||
|
".bmp" => "image/bmp",
|
||||||
|
".svg" => "image/svg+xml",
|
||||||
|
_ => "image/png"
|
||||||
|
};
|
||||||
|
|
||||||
|
ModelDto ToModelDto(ModelPackage package) => new( package.Id,
|
||||||
|
package.LocalizedName,
|
||||||
|
package.LocalizedDescription,
|
||||||
|
package.Manifest.Version,
|
||||||
|
package.Manifest.Author,
|
||||||
|
package.SizeBytes,
|
||||||
|
ModelScanner.HumanSize(package.SizeBytes),
|
||||||
|
package.Manifest.Tags ?? new List<string>(),
|
||||||
|
File.Exists(package.PreviewPath),
|
||||||
|
$"/api/models/{package.Id}/preview",
|
||||||
|
package.Directory,
|
||||||
|
package.DataDirectory);
|
||||||
|
|
||||||
|
SourceDto ToSourceDto(ModelSource source) => new(
|
||||||
|
source.Id,
|
||||||
|
string.IsNullOrWhiteSpace(source.Name) ? source.Id : source.Name,
|
||||||
|
source.Url,
|
||||||
|
source.Enabled,
|
||||||
|
source.BuiltIn,
|
||||||
|
source.DisplayHost);
|
||||||
|
|
||||||
|
SettingsDto ToSettingsDto() => new(
|
||||||
|
services.Settings.Current.Language,
|
||||||
|
services.Settings.Current.Theme,
|
||||||
|
services.Settings.Current.AccentColor,
|
||||||
|
services.Settings.Current.RenderFps,
|
||||||
|
services.Settings.Current.MemoryMb,
|
||||||
|
services.Settings.Current.MemoryAuto,
|
||||||
|
services.Settings.Current.AutoUpdateOnStartup,
|
||||||
|
services.Settings.Current.RequireSignedManifest,
|
||||||
|
services.Settings.Current.UpdateRepository,
|
||||||
|
services.Settings.Current.UpdateLocalRoot,
|
||||||
|
services.Settings.Current.ModelRootOverride,
|
||||||
|
services.Memory.BudgetMb,
|
||||||
|
services.Memory.UsageText,
|
||||||
|
services.Paths.ModelRoot,
|
||||||
|
services.Paths.DataRoot,
|
||||||
|
services.Paths.SettingsFile,
|
||||||
|
LauncherRuntimeInfo.CurrentLauncherVersion,
|
||||||
|
LauncherRuntimeInfo.CurrentRid,
|
||||||
|
services.Settings.Current.Sources.Select(ToSourceDto).ToList(),
|
||||||
|
L.Supported.Select(s => new LanguageDto(s.Code, s.Label)).ToList());
|
||||||
|
|
||||||
|
JobDto ToJobDto(IDownloadJob job) => new(
|
||||||
|
job.Id,
|
||||||
|
job.Model.Id,
|
||||||
|
job.Name,
|
||||||
|
job.Version,
|
||||||
|
job.State.ToString(),
|
||||||
|
job.Progress,
|
||||||
|
job.StatusText,
|
||||||
|
job.DetailText,
|
||||||
|
job.Error,
|
||||||
|
job.IsActive,
|
||||||
|
job.CanRetry,
|
||||||
|
job.IsDone);
|
||||||
|
|
||||||
|
ModelSource? ResolveSource(string? sourceId)
|
||||||
|
{
|
||||||
|
var sources = services.Settings.Current.Sources;
|
||||||
|
if (!string.IsNullOrWhiteSpace(sourceId))
|
||||||
|
{
|
||||||
|
var exact = sources.FirstOrDefault(s =>
|
||||||
|
s.Id.Equals(sourceId, StringComparison.OrdinalIgnoreCase));
|
||||||
|
if (exact != null) return exact;
|
||||||
|
}
|
||||||
|
|
||||||
|
return sources.FirstOrDefault(s => s.Enabled && !string.IsNullOrWhiteSpace(s.Url))
|
||||||
|
?? sources.FirstOrDefault();
|
||||||
|
}
|
||||||
|
|
||||||
|
IResult ActOnJob(string id, Action<IDownloadJob> action)
|
||||||
|
{
|
||||||
|
if (!IsSafeId(id)) return Results.BadRequest(ErrorDto.Of("任务标识无效"));
|
||||||
|
var job = services.Downloads.Jobs.FirstOrDefault(j =>
|
||||||
|
j.Id.Equals(id, StringComparison.OrdinalIgnoreCase));
|
||||||
|
if (job == null) return Results.NotFound(ErrorDto.Of($"没有找到任务 {id}"));
|
||||||
|
|
||||||
|
action(job);
|
||||||
|
return Results.Ok(ToJobDto(job));
|
||||||
|
}
|
||||||
|
|
||||||
|
bool IsInsideKnownRoot(string path)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var full = Path.GetFullPath(path);
|
||||||
|
var roots = new[]
|
||||||
|
{
|
||||||
|
services.Paths.ModelRoot,
|
||||||
|
services.Paths.DataRoot,
|
||||||
|
services.Paths.HomeRoot,
|
||||||
|
services.Paths.AppRoot
|
||||||
|
};
|
||||||
|
|
||||||
|
foreach (var root in roots)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrWhiteSpace(root)) continue;
|
||||||
|
var rootFull = Path.GetFullPath(root);
|
||||||
|
if (full.Equals(rootFull, StringComparison.OrdinalIgnoreCase)) return true;
|
||||||
|
if (full.StartsWith(rootFull + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase))
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 路由标识:只允许字母数字开头,后接字母数字/点/下划线/短横线,长度上限 64。
|
||||||
|
// 用于模型 id、任务 id,杜绝 `../` 之类的路径穿越尝试。
|
||||||
|
bool IsSafeId(string? id) => !string.IsNullOrEmpty(id) && safeIdRegex.IsMatch(id);
|
||||||
|
|
||||||
|
// 更新仓库地址:必须是 https、不带账号密码、不是回环/内网 IP。
|
||||||
|
// 防止把本地后端当成 SSRF 跳板去访问内网服务。
|
||||||
|
bool IsAllowedRepository(string value)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrWhiteSpace(value)) return false;
|
||||||
|
if (!Uri.TryCreate(value, UriKind.Absolute, out var uri)) return false;
|
||||||
|
if (uri.Scheme != Uri.UriSchemeHttps) return false;
|
||||||
|
if (!string.IsNullOrEmpty(uri.UserInfo)) return false;
|
||||||
|
if (string.Equals(uri.Host, "localhost", StringComparison.OrdinalIgnoreCase)) return false;
|
||||||
|
if (System.Net.IPAddress.TryParse(uri.Host, out var ip) &&
|
||||||
|
(System.Net.IPAddress.IsLoopback(ip) || IsPrivateAddress(ip)))
|
||||||
|
return false;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
static bool IsPrivateAddress(System.Net.IPAddress ip)
|
||||||
|
{
|
||||||
|
var bytes = ip.GetAddressBytes();
|
||||||
|
if (bytes.Length != 4) return false;
|
||||||
|
return bytes[0] == 10
|
||||||
|
|| (bytes[0] == 172 && bytes[1] >= 16 && bytes[1] <= 31)
|
||||||
|
|| (bytes[0] == 192 && bytes[1] == 168)
|
||||||
|
|| (bytes[0] == 169 && bytes[1] == 254);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static int ResolvePort(string[] args)
|
||||||
|
{
|
||||||
|
// 优先用启动器传来的端口(GC_UI_PORT),保证前端拼出来的 baseUrl 和这里一致。
|
||||||
|
var env = Environment.GetEnvironmentVariable(GcUiContract.PortEnvVar);
|
||||||
|
if (int.TryParse(env, out var fromEnv) && fromEnv > 0 && fromEnv < 65536) return fromEnv;
|
||||||
|
|
||||||
|
for (var i = 0; i < args.Length; i++)
|
||||||
|
{
|
||||||
|
if (args[i] == "--port" && i + 1 < args.Length &&
|
||||||
|
int.TryParse(args[i + 1], out var next) && next > 0 && next < 65536)
|
||||||
|
return next;
|
||||||
|
|
||||||
|
const string prefix = "--port=";
|
||||||
|
if (args[i].StartsWith(prefix, StringComparison.Ordinal) &&
|
||||||
|
int.TryParse(args[i][prefix.Length..], out var inline) && inline > 0 && inline < 65536)
|
||||||
|
return inline;
|
||||||
|
}
|
||||||
|
|
||||||
|
return GcUiContract.DefaultPort;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,634 +1,22 @@
|
|||||||
using System;
|
|
||||||
using System.Collections.Generic;
|
|
||||||
using System.IO;
|
|
||||||
using System.Linq;
|
|
||||||
using System.Text.Json;
|
|
||||||
using System.Threading;
|
|
||||||
using System.Threading.Tasks;
|
|
||||||
using GC.Download;
|
|
||||||
using GC.Models;
|
|
||||||
using GC.Services;
|
|
||||||
using GC.UI.Server;
|
using GC.UI.Server;
|
||||||
using Microsoft.AspNetCore.Builder;
|
|
||||||
using Microsoft.AspNetCore.Hosting;
|
|
||||||
using Microsoft.AspNetCore.Http;
|
|
||||||
using Microsoft.Extensions.DependencyInjection;
|
|
||||||
using Microsoft.Extensions.Hosting;
|
using Microsoft.Extensions.Hosting;
|
||||||
using Microsoft.Extensions.Logging;
|
|
||||||
|
|
||||||
// ---------------------------------------------------------------------------
|
// 独立进程入口:`GC.UI.Server --port 17890`
|
||||||
// GC-UI 后端:本地 HTTP 服务(只监听 127.0.0.1)。
|
// 启动器在进程内直接调用 BackendServer.Start,不会走到这里。
|
||||||
//
|
var app = BackendServer.StartFromCommandLine(args, out var host);
|
||||||
// 它把原来 GC 启动器里的服务层原样复用(GC.Core / GC-DOWNLOAD),
|
|
||||||
// 只是把「界面」从 Avalonia 换成 Flutter —— 前端通过下面这些接口驱动后端。
|
|
||||||
//
|
|
||||||
// GET /api/health 健康检查 + 图形环境是否可用
|
|
||||||
// GET /api/models 已安装模型
|
|
||||||
// GET /api/models/{id}/preview 模型封面图
|
|
||||||
// POST /api/models/{id}/launch 启动模型(打开模型自己的窗口)
|
|
||||||
// DELETE /api/models/{id} 删除模型
|
|
||||||
// GET /api/settings 读取设置
|
|
||||||
// POST /api/settings 修改设置(补丁式)
|
|
||||||
// GET /api/sources 模型源列表
|
|
||||||
// POST /api/sources/select 双源测速并切到最快
|
|
||||||
// GET /api/remote/models 远端可下载模型
|
|
||||||
// POST /api/download 入队下载
|
|
||||||
// GET /api/download/jobs 下载任务
|
|
||||||
// POST /api/download/{id}/cancel|retry|remove
|
|
||||||
// POST /api/download/clear-finished 清除已完成
|
|
||||||
// POST /api/update/check 检查模型 / 启动器更新
|
|
||||||
// GET /api/about 版本 + 贡献者
|
|
||||||
// POST /api/shell/open-folder|open-url 打开目录 / 链接
|
|
||||||
// ---------------------------------------------------------------------------
|
|
||||||
|
|
||||||
var port = ResolvePort(args);
|
// 模型窗口由 Avalonia 承载,macOS 的 AppKit 要求 NSApplication 在主线程。
|
||||||
|
// 所以后端交给 Kestrel 自己的线程池在后台跑,主线程留给 Avalonia 事件循环。
|
||||||
|
app.StartAsync().GetAwaiter().GetResult();
|
||||||
|
host.RunOnCurrentThread();
|
||||||
|
|
||||||
// 下载模块(GC-DOWNLOAD)通过宿主钩子注入,和 GC-BOOT 的做法一致。
|
if (host.IsAvailable)
|
||||||
DownloadModuleHost.Factory = new DownloadModuleFactory();
|
|
||||||
|
|
||||||
var services = AppServices.Create();
|
|
||||||
var uiHost = new AvaloniaHost(services);
|
|
||||||
|
|
||||||
var builder = WebApplication.CreateBuilder(new WebApplicationOptions { Args = args });
|
|
||||||
builder.Logging.ClearProviders();
|
|
||||||
builder.WebHost.UseUrls($"http://127.0.0.1:{port}");
|
|
||||||
|
|
||||||
// 本地伴随进程:限制请求体大小、关闭 Server 头、收紧超时,减少被本地恶意页面
|
|
||||||
// 或异常客户端拖垮的攻击面。
|
|
||||||
builder.WebHost.ConfigureKestrel(options =>
|
|
||||||
{
|
{
|
||||||
options.AddServerHeader = false;
|
// 事件循环结束 → 收尾后端
|
||||||
options.Limits.MaxRequestBodySize = 2 * 1024 * 1024;
|
app.StopAsync().GetAwaiter().GetResult();
|
||||||
options.Limits.RequestHeadersTimeout = TimeSpan.FromSeconds(15);
|
|
||||||
options.Limits.KeepAliveTimeout = TimeSpan.FromMinutes(2);
|
|
||||||
options.Limits.MaxConcurrentConnections = 64;
|
|
||||||
});
|
|
||||||
|
|
||||||
// 桌面端(Windows/macOS)走原生 HTTP,不需要 CORS;
|
|
||||||
// 这里放开本机回环来源,方便用 `flutter run -d chrome` 调试界面。
|
|
||||||
builder.Services.AddCors(options => options.AddDefaultPolicy(policy => policy
|
|
||||||
.SetIsOriginAllowed(origin =>
|
|
||||||
Uri.TryCreate(origin, UriKind.Absolute, out var uri) &&
|
|
||||||
(uri.Host == "127.0.0.1" || uri.Host == "localhost" || uri.Host == "::1"))
|
|
||||||
.AllowAnyHeader()
|
|
||||||
.AllowAnyMethod()));
|
|
||||||
|
|
||||||
var app = builder.Build();
|
|
||||||
app.UseCors();
|
|
||||||
|
|
||||||
// 设置白名单 / 标识校验用到的规则(只在本进程内使用)。
|
|
||||||
var allowedLanguages = new HashSet<string>(StringComparer.OrdinalIgnoreCase)
|
|
||||||
{ "auto", "zh-CN", "en" };
|
|
||||||
var allowedThemes = new HashSet<string>(StringComparer.OrdinalIgnoreCase)
|
|
||||||
{ "light", "dark", "system" };
|
|
||||||
var accentHexRegex = new System.Text.RegularExpressions.Regex(
|
|
||||||
"^#(?:[0-9A-Fa-f]{6})$", System.Text.RegularExpressions.RegexOptions.Compiled);
|
|
||||||
var safeIdRegex = new System.Text.RegularExpressions.Regex(
|
|
||||||
"^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$", System.Text.RegularExpressions.RegexOptions.Compiled);
|
|
||||||
|
|
||||||
// 安全响应头 + Host/Origin 校验(抵御 DNS rebinding 与跨站调用)。
|
|
||||||
app.Use(async (context, next) =>
|
|
||||||
{
|
|
||||||
var headers = context.Response.Headers;
|
|
||||||
headers["X-Content-Type-Options"] = "nosniff";
|
|
||||||
headers["X-Frame-Options"] = "DENY";
|
|
||||||
headers["Referrer-Policy"] = "no-referrer";
|
|
||||||
headers["Content-Security-Policy"] = "default-src 'none'; frame-ancestors 'none'";
|
|
||||||
headers["Cache-Control"] = "no-store";
|
|
||||||
|
|
||||||
var host = context.Request.Host.Host;
|
|
||||||
if (!string.Equals(host, "127.0.0.1", StringComparison.OrdinalIgnoreCase) &&
|
|
||||||
!string.Equals(host, "localhost", StringComparison.OrdinalIgnoreCase) &&
|
|
||||||
!string.Equals(host, "::1", StringComparison.OrdinalIgnoreCase))
|
|
||||||
{
|
|
||||||
context.Response.StatusCode = StatusCodes.Status403Forbidden;
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
var origin = context.Request.Headers.Origin.ToString();
|
|
||||||
if (!string.IsNullOrEmpty(origin) &&
|
|
||||||
!(Uri.TryCreate(origin, UriKind.Absolute, out var parsed) &&
|
|
||||||
(parsed.Host == "127.0.0.1" || parsed.Host == "localhost" || parsed.Host == "::1")))
|
|
||||||
{
|
|
||||||
context.Response.StatusCode = StatusCodes.Status403Forbidden;
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
await next();
|
|
||||||
});
|
|
||||||
|
|
||||||
// 写入类接口做简单限流:单 IP 每秒最多 40 次,防止本地脚本刷爆下载/更新。
|
|
||||||
var writeBuckets =
|
|
||||||
new System.Collections.Concurrent.ConcurrentDictionary<string, (long Window, int Count)>();
|
|
||||||
app.Use(async (context, next) =>
|
|
||||||
{
|
|
||||||
if (HttpMethods.IsPost(context.Request.Method) ||
|
|
||||||
HttpMethods.IsDelete(context.Request.Method))
|
|
||||||
{
|
|
||||||
var key = context.Connection.RemoteIpAddress?.ToString() ?? "local";
|
|
||||||
var now = Environment.TickCount64;
|
|
||||||
var bucket = writeBuckets.AddOrUpdate(
|
|
||||||
key,
|
|
||||||
_ => (now, 1),
|
|
||||||
(_, old) => now - old.Window > 1000 ? (now, 1) : (old.Window, old.Count + 1));
|
|
||||||
|
|
||||||
if (bucket.Count > 40)
|
|
||||||
{
|
|
||||||
context.Response.StatusCode = StatusCodes.Status429TooManyRequests;
|
|
||||||
await context.Response.WriteAsJsonAsync(
|
|
||||||
new LaunchResultDto(false, "请求过于频繁,请稍后再试"));
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
await next();
|
|
||||||
});
|
|
||||||
|
|
||||||
// ---- 健康检查 -------------------------------------------------------------
|
|
||||||
|
|
||||||
app.MapGet("/api/health", () => Results.Ok(new HealthDto(
|
|
||||||
true,
|
|
||||||
LauncherRuntimeInfo.CurrentLauncherVersion,
|
|
||||||
LauncherRuntimeInfo.CurrentRid,
|
|
||||||
uiHost.IsAvailable,
|
|
||||||
uiHost.LastError)));
|
|
||||||
|
|
||||||
// ---- 已安装模型 -----------------------------------------------------------
|
|
||||||
|
|
||||||
app.MapGet("/api/models", () =>
|
|
||||||
Results.Ok(services.Models.Scan().Select(ToModelDto).ToList()));
|
|
||||||
|
|
||||||
app.MapGet("/api/models/{id}/preview", (string id) =>
|
|
||||||
{
|
|
||||||
if (!IsSafeId(id)) return Results.BadRequest();
|
|
||||||
var package = services.Models.Find(id);
|
|
||||||
if (package == null || !File.Exists(package.PreviewPath)) return Results.NotFound();
|
|
||||||
return Results.File(package.PreviewPath, "image/png");
|
|
||||||
});
|
|
||||||
|
|
||||||
app.MapPost("/api/models/{id}/launch", async (string id) =>
|
|
||||||
{
|
|
||||||
if (!IsSafeId(id)) return Results.BadRequest(new LaunchResultDto(false, "模型标识无效"));
|
|
||||||
var package = services.Models.Find(id);
|
|
||||||
if (package == null) return Results.NotFound(new LaunchResultDto(false, $"没有找到模型 {id}"));
|
|
||||||
|
|
||||||
try
|
|
||||||
{
|
|
||||||
services.Memory.Refresh();
|
|
||||||
var message = await uiHost.LaunchAsync(package);
|
|
||||||
return Results.Ok(new LaunchResultDto(true, message));
|
|
||||||
}
|
|
||||||
catch (Exception ex)
|
|
||||||
{
|
|
||||||
// 细节只写日志,不回显给调用方,避免泄漏本机路径等内部信息。
|
|
||||||
Console.Error.WriteLine($"[launch] 启动模型 {id} 失败: {ex}");
|
|
||||||
return Results.Json(new LaunchResultDto(false, "模型启动失败,请查看后端日志"), statusCode: 503);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
app.MapDelete("/api/models/{id}", (string id) =>
|
|
||||||
{
|
|
||||||
if (!IsSafeId(id)) return Results.BadRequest(new LaunchResultDto(false, "模型标识无效"));
|
|
||||||
var ok = services.Models.Delete(id);
|
|
||||||
if (ok) services.Models.NotifyChanged();
|
|
||||||
return ok
|
|
||||||
? Results.Ok(new LaunchResultDto(true, $"已删除模型 {id}"))
|
|
||||||
: Results.NotFound(new LaunchResultDto(false, $"没有找到模型 {id}"));
|
|
||||||
});
|
|
||||||
|
|
||||||
// ---- 设置 -----------------------------------------------------------------
|
|
||||||
|
|
||||||
app.MapGet("/api/settings", () => Results.Ok(ToSettingsDto()));
|
|
||||||
|
|
||||||
app.MapPost("/api/settings", (SettingsPatch? patch) =>
|
|
||||||
{
|
|
||||||
if (patch == null) return Results.BadRequest(new LaunchResultDto(false, "缺少设置内容"));
|
|
||||||
|
|
||||||
// 白名单校验:设置项会写进磁盘并被前端直接使用,不接受任意字符串。
|
|
||||||
if (patch.Language != null && !allowedLanguages.Contains(patch.Language))
|
|
||||||
return Results.BadRequest(new LaunchResultDto(false, "不支持的界面语言"));
|
|
||||||
if (patch.Theme != null && !allowedThemes.Contains(patch.Theme))
|
|
||||||
return Results.BadRequest(new LaunchResultDto(false, "不支持的主题"));
|
|
||||||
if (patch.AccentColor != null && !accentHexRegex.IsMatch(patch.AccentColor))
|
|
||||||
return Results.BadRequest(new LaunchResultDto(false, "主题色需为 #RRGGBB"));
|
|
||||||
if (patch.UpdateRepository != null && !IsAllowedRepository(patch.UpdateRepository))
|
|
||||||
return Results.BadRequest(new LaunchResultDto(false, "更新仓库地址不受信任"));
|
|
||||||
|
|
||||||
services.Settings.Apply(s =>
|
|
||||||
{
|
|
||||||
if (patch.Language != null) s.Language = patch.Language;
|
|
||||||
if (patch.Theme != null) s.Theme = patch.Theme;
|
|
||||||
if (patch.AccentColor != null) s.AccentColor = patch.AccentColor.ToUpperInvariant();
|
|
||||||
if (patch.RenderFps.HasValue) s.RenderFps = Math.Clamp(patch.RenderFps.Value, 12, 120);
|
|
||||||
if (patch.MemoryMb.HasValue) s.MemoryMb = Math.Clamp(patch.MemoryMb.Value, 256, 16384);
|
|
||||||
if (patch.MemoryAuto.HasValue) s.MemoryAuto = patch.MemoryAuto.Value;
|
|
||||||
if (patch.AutoUpdateOnStartup.HasValue) s.AutoUpdateOnStartup = patch.AutoUpdateOnStartup.Value;
|
|
||||||
if (patch.RequireSignedManifest.HasValue) s.RequireSignedManifest = patch.RequireSignedManifest.Value;
|
|
||||||
if (patch.UpdateRepository != null) s.UpdateRepository = patch.UpdateRepository;
|
|
||||||
if (patch.UpdateLocalRoot != null) s.UpdateLocalRoot = patch.UpdateLocalRoot;
|
|
||||||
if (patch.ModelRootOverride != null) s.ModelRootOverride = patch.ModelRootOverride;
|
|
||||||
});
|
|
||||||
|
|
||||||
if (patch.Language != null) L.I.SetLanguage(patch.Language);
|
|
||||||
if (patch.MemoryMb.HasValue || patch.MemoryAuto.HasValue)
|
|
||||||
services.Memory.ApplyAuto(services.Settings.Current.MemoryAuto, services.Settings.Current.MemoryMb);
|
|
||||||
|
|
||||||
return Results.Ok(ToSettingsDto());
|
|
||||||
});
|
|
||||||
|
|
||||||
// ---- 模型源 ---------------------------------------------------------------
|
|
||||||
|
|
||||||
app.MapGet("/api/sources", () =>
|
|
||||||
Results.Ok(services.Settings.Current.Sources.Select(ToSourceDto).ToList()));
|
|
||||||
|
|
||||||
app.MapPost("/api/sources/select", async (ForceRequest? request) =>
|
|
||||||
{
|
|
||||||
var force = request?.Force ?? false;
|
|
||||||
try
|
|
||||||
{
|
|
||||||
var fastest = await services.Selector.PickFastestAsync(force, CancellationToken.None);
|
|
||||||
services.Updates.UseRemote(services.DownloadModule.CreateRemote(fastest));
|
|
||||||
return Results.Ok(new LatencyDto(
|
|
||||||
fastest.Id, fastest.Name,
|
|
||||||
services.Selector.LastLatency.TryGetValue(fastest.Id, out var ms) ? ms : 0));
|
|
||||||
}
|
|
||||||
catch (Exception ex)
|
|
||||||
{
|
|
||||||
Console.Error.WriteLine($"[sources] 切换模型源失败: {ex}");
|
|
||||||
return Results.Json(new LaunchResultDto(false, "模型源切换失败"), statusCode: 503);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
app.MapGet("/api/remote/models", async (string? sourceId, bool force) =>
|
|
||||||
{
|
|
||||||
var source = ResolveSource(sourceId);
|
|
||||||
if (source == null) return Results.NotFound(new LaunchResultDto(false, "没有可用的模型源"));
|
|
||||||
|
|
||||||
var index = await services.Sources.FetchAsync(source, force, null, CancellationToken.None);
|
|
||||||
var installed = services.Models.Scan()
|
|
||||||
.ToDictionary(p => p.Id, p => p.Manifest.Version, StringComparer.OrdinalIgnoreCase);
|
|
||||||
|
|
||||||
return Results.Ok(new SourceIndexDto(
|
|
||||||
index.SourceId,
|
|
||||||
index.Root,
|
|
||||||
index.FromCache,
|
|
||||||
index.Error,
|
|
||||||
index.ResolvedFrom,
|
|
||||||
index.Models.Select(m => new RemoteModelDto(
|
|
||||||
m.Id,
|
|
||||||
m.LocalizedName,
|
|
||||||
m.LocalizedDescription,
|
|
||||||
m.Manifest.Version,
|
|
||||||
m.SizeBytes,
|
|
||||||
ModelScanner.HumanSize(m.SizeBytes),
|
|
||||||
m.SourceId,
|
|
||||||
installed.ContainsKey(m.Id),
|
|
||||||
installed.TryGetValue(m.Id, out var v) ? v : null)).ToList()));
|
|
||||||
});
|
|
||||||
|
|
||||||
// ---- 下载 -----------------------------------------------------------------
|
|
||||||
|
|
||||||
app.MapPost("/api/download", async (DownloadRequest? request) =>
|
|
||||||
{
|
|
||||||
if (request == null || string.IsNullOrWhiteSpace(request.ModelId))
|
|
||||||
return Results.BadRequest(new LaunchResultDto(false, "缺少 modelId"));
|
|
||||||
|
|
||||||
var source = ResolveSource(request.SourceId);
|
|
||||||
if (source == null) return Results.NotFound(new LaunchResultDto(false, "没有可用的模型源"));
|
|
||||||
|
|
||||||
var index = await services.Sources.FetchAsync(source, false, null, CancellationToken.None);
|
|
||||||
var model = index.Models.FirstOrDefault(m =>
|
|
||||||
m.Id.Equals(request.ModelId, StringComparison.OrdinalIgnoreCase));
|
|
||||||
if (model == null)
|
|
||||||
return Results.NotFound(new LaunchResultDto(false, $"源里没有模型 {request.ModelId}"));
|
|
||||||
|
|
||||||
var job = services.Downloads.Enqueue(model);
|
|
||||||
return Results.Ok(ToJobDto(job));
|
|
||||||
});
|
|
||||||
|
|
||||||
app.MapGet("/api/download/jobs", () =>
|
|
||||||
Results.Ok(services.Downloads.Jobs.Select(ToJobDto).ToList()));
|
|
||||||
|
|
||||||
app.MapPost("/api/download/{id}/cancel", (string id) =>
|
|
||||||
ActOnJob(id, job => services.Downloads.Cancel(job)));
|
|
||||||
|
|
||||||
app.MapPost("/api/download/{id}/retry", (string id) =>
|
|
||||||
ActOnJob(id, job => services.Downloads.Retry(job)));
|
|
||||||
|
|
||||||
app.MapPost("/api/download/{id}/remove", (string id) =>
|
|
||||||
ActOnJob(id, job => services.Downloads.Remove(job)));
|
|
||||||
|
|
||||||
app.MapPost("/api/download/clear-finished", () =>
|
|
||||||
{
|
|
||||||
services.Downloads.ClearFinished();
|
|
||||||
return Results.Ok(new LaunchResultDto(true, "已清除完成的任务"));
|
|
||||||
});
|
|
||||||
|
|
||||||
// ---- 更新 -----------------------------------------------------------------
|
|
||||||
|
|
||||||
app.MapPost("/api/update/check", async (ForceRequest? request) =>
|
|
||||||
{
|
|
||||||
var force = request?.Force ?? true;
|
|
||||||
var messages = new List<string>();
|
|
||||||
|
|
||||||
try
|
|
||||||
{
|
|
||||||
var fastest = await services.Selector.PickFastestAsync(force, CancellationToken.None);
|
|
||||||
services.Updates.UseRemote(services.DownloadModule.CreateRemote(fastest));
|
|
||||||
}
|
|
||||||
catch (Exception ex)
|
|
||||||
{
|
|
||||||
Console.Error.WriteLine($"[update] 测速失败,沿用当前源: {ex.Message}");
|
|
||||||
}
|
|
||||||
|
|
||||||
string? launcherLatest = null;
|
|
||||||
try
|
|
||||||
{
|
|
||||||
launcherLatest = await services.LauncherUpdates.CheckAsync(
|
|
||||||
services.Updates.Remote, CancellationToken.None);
|
|
||||||
}
|
|
||||||
catch (Exception ex)
|
|
||||||
{
|
|
||||||
Console.Error.WriteLine($"[update] 启动器版本检查失败: {ex.Message}");
|
|
||||||
}
|
|
||||||
|
|
||||||
var progress = new Progress<UpdateProgress>(p =>
|
|
||||||
{
|
|
||||||
if (!string.IsNullOrWhiteSpace(p.Message)) messages.Add(p.Message);
|
|
||||||
});
|
|
||||||
|
|
||||||
var result = await services.Updates.RunAsync(force, progress, CancellationToken.None);
|
|
||||||
|
|
||||||
return Results.Ok(new UpdateCheckDto(
|
|
||||||
result.Outcome.ToString(),
|
|
||||||
result.Message,
|
|
||||||
result.UpdatedModels,
|
|
||||||
result.ModelNames,
|
|
||||||
result.LauncherMessage,
|
|
||||||
result.Error,
|
|
||||||
launcherLatest,
|
|
||||||
services.Updates.Remote.DisplayName,
|
|
||||||
services.Selector.LastLatency
|
|
||||||
.Select(kv => new LatencyDto(
|
|
||||||
kv.Key,
|
|
||||||
SourcePreset.Find(kv.Key)?.Name ?? kv.Key,
|
|
||||||
kv.Value))
|
|
||||||
.ToList()));
|
|
||||||
});
|
|
||||||
|
|
||||||
// ---- 关于 -----------------------------------------------------------------
|
|
||||||
|
|
||||||
app.MapGet("/api/about", async () =>
|
|
||||||
{
|
|
||||||
var repository = services.Settings.Current.UpdateRepository;
|
|
||||||
var contributors = new List<ContributorDto>();
|
|
||||||
try
|
|
||||||
{
|
|
||||||
foreach (var c in await ContributorsService.FetchAsync(repository, CancellationToken.None))
|
|
||||||
contributors.Add(new ContributorDto(c.DisplayName, c.Contributions, c.AvatarUrl));
|
|
||||||
}
|
|
||||||
catch (Exception ex)
|
|
||||||
{
|
|
||||||
Console.Error.WriteLine($"[about] 读取贡献者失败: {ex.Message}");
|
|
||||||
}
|
|
||||||
|
|
||||||
return Results.Ok(new AboutDto(
|
|
||||||
"Morris GC",
|
|
||||||
LauncherRuntimeInfo.CurrentLauncherVersion,
|
|
||||||
LauncherRuntimeInfo.CurrentRid,
|
|
||||||
repository,
|
|
||||||
contributors,
|
|
||||||
// 「关于」页展示的技术栈信息:源码语言与前端框架。
|
|
||||||
SourceLanguage: "C#",
|
|
||||||
Frontend: "Flutter"));
|
|
||||||
});
|
|
||||||
|
|
||||||
// ---- 系统集成 -------------------------------------------------------------
|
|
||||||
|
|
||||||
app.MapPost("/api/shell/open-folder", (PathRequest? request) =>
|
|
||||||
{
|
|
||||||
var path = request?.Path;
|
|
||||||
if (string.IsNullOrWhiteSpace(path))
|
|
||||||
return Results.BadRequest(new LaunchResultDto(false, "缺少 path"));
|
|
||||||
|
|
||||||
// 只允许打开启动器自己的目录,避免前端被当成任意路径执行器
|
|
||||||
if (!IsInsideKnownRoot(path!))
|
|
||||||
return Results.BadRequest(new LaunchResultDto(false, "只允许打开启动器自己的目录"));
|
|
||||||
|
|
||||||
Shell.OpenFolder(path!);
|
|
||||||
return Results.Ok(new LaunchResultDto(true, "已打开目录"));
|
|
||||||
});
|
|
||||||
|
|
||||||
app.MapPost("/api/shell/open-url", (UrlRequest? request) =>
|
|
||||||
{
|
|
||||||
var url = request?.Url;
|
|
||||||
if (string.IsNullOrWhiteSpace(url) || url.Length > 2048 ||
|
|
||||||
!Uri.TryCreate(url, UriKind.Absolute, out var uri))
|
|
||||||
return Results.BadRequest(new LaunchResultDto(false, "URL 无效"));
|
|
||||||
|
|
||||||
if (uri.Scheme != Uri.UriSchemeHttp && uri.Scheme != Uri.UriSchemeHttps)
|
|
||||||
return Results.BadRequest(new LaunchResultDto(false, "只允许 http/https 链接"));
|
|
||||||
|
|
||||||
if (!string.IsNullOrEmpty(uri.UserInfo))
|
|
||||||
return Results.BadRequest(new LaunchResultDto(false, "URL 不允许携带账号密码"));
|
|
||||||
|
|
||||||
Shell.OpenUrl(url!);
|
|
||||||
return Results.Ok(new LaunchResultDto(true, "已打开链接"));
|
|
||||||
});
|
|
||||||
|
|
||||||
// ---- 启动 -----------------------------------------------------------------
|
|
||||||
|
|
||||||
WriteEndpointFile(services, port);
|
|
||||||
Console.WriteLine($"[GC-UI] 后端已启动: http://127.0.0.1:{port}");
|
|
||||||
Console.WriteLine($"[GC-UI] 模型库: {services.Paths.ModelRoot}");
|
|
||||||
|
|
||||||
app.Run();
|
|
||||||
|
|
||||||
// ---------------------------------------------------------------------------
|
|
||||||
// 局部辅助
|
|
||||||
// ---------------------------------------------------------------------------
|
|
||||||
|
|
||||||
static int ResolvePort(string[] args)
|
|
||||||
{
|
|
||||||
var env = Environment.GetEnvironmentVariable("GC_UI_PORT");
|
|
||||||
if (int.TryParse(env, out var fromEnv) && fromEnv > 0 && fromEnv < 65536) return fromEnv;
|
|
||||||
|
|
||||||
for (var i = 0; i < args.Length; i++)
|
|
||||||
{
|
|
||||||
if (args[i] == "--port" && i + 1 < args.Length &&
|
|
||||||
int.TryParse(args[i + 1], out var next) && next > 0 && next < 65536)
|
|
||||||
return next;
|
|
||||||
|
|
||||||
const string prefix = "--port=";
|
|
||||||
if (args[i].StartsWith(prefix, StringComparison.Ordinal) &&
|
|
||||||
int.TryParse(args[i][prefix.Length..], out var inline) && inline > 0 && inline < 65536)
|
|
||||||
return inline;
|
|
||||||
}
|
|
||||||
|
|
||||||
return 17890;
|
|
||||||
}
|
}
|
||||||
|
else
|
||||||
static void WriteEndpointFile(AppServices services, int port)
|
|
||||||
{
|
{
|
||||||
try
|
// 无图形环境(无头调试):退化为纯后端常驻
|
||||||
{
|
app.WaitForShutdown();
|
||||||
var file = Path.Combine(services.Paths.HomeRoot, "ui-backend.json");
|
|
||||||
var payload = JsonSerializer.Serialize(new
|
|
||||||
{
|
|
||||||
port,
|
|
||||||
pid = Environment.ProcessId,
|
|
||||||
url = $"http://127.0.0.1:{port}",
|
|
||||||
version = LauncherRuntimeInfo.CurrentLauncherVersion,
|
|
||||||
platform = LauncherRuntimeInfo.CurrentRid,
|
|
||||||
startedAt = DateTimeOffset.UtcNow.ToString("o")
|
|
||||||
}, new JsonSerializerOptions { WriteIndented = true });
|
|
||||||
|
|
||||||
File.WriteAllText(file, payload);
|
|
||||||
}
|
|
||||||
catch (Exception ex)
|
|
||||||
{
|
|
||||||
Console.Error.WriteLine($"[GC-UI] 写入端点文件失败: {ex.Message}");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
ModelDto ToModelDto(ModelPackage package) => new(
|
|
||||||
package.Id,
|
|
||||||
package.LocalizedName,
|
|
||||||
package.LocalizedDescription,
|
|
||||||
package.Manifest.Version,
|
|
||||||
package.Manifest.Author,
|
|
||||||
package.SizeBytes,
|
|
||||||
ModelScanner.HumanSize(package.SizeBytes),
|
|
||||||
package.Manifest.Tags ?? new List<string>(),
|
|
||||||
File.Exists(package.PreviewPath),
|
|
||||||
$"/api/models/{package.Id}/preview",
|
|
||||||
package.Directory,
|
|
||||||
package.DataDirectory);
|
|
||||||
|
|
||||||
SourceDto ToSourceDto(ModelSource source) => new(
|
|
||||||
source.Id,
|
|
||||||
string.IsNullOrWhiteSpace(source.Name) ? source.Id : source.Name,
|
|
||||||
source.Url,
|
|
||||||
source.Enabled,
|
|
||||||
source.BuiltIn,
|
|
||||||
source.DisplayHost);
|
|
||||||
|
|
||||||
SettingsDto ToSettingsDto() => new(
|
|
||||||
services.Settings.Current.Language,
|
|
||||||
services.Settings.Current.Theme,
|
|
||||||
services.Settings.Current.AccentColor,
|
|
||||||
services.Settings.Current.RenderFps,
|
|
||||||
services.Settings.Current.MemoryMb,
|
|
||||||
services.Settings.Current.MemoryAuto,
|
|
||||||
services.Settings.Current.AutoUpdateOnStartup,
|
|
||||||
services.Settings.Current.RequireSignedManifest,
|
|
||||||
services.Settings.Current.UpdateRepository,
|
|
||||||
services.Settings.Current.UpdateLocalRoot,
|
|
||||||
services.Settings.Current.ModelRootOverride,
|
|
||||||
services.Memory.BudgetMb,
|
|
||||||
services.Memory.UsageText,
|
|
||||||
services.Paths.ModelRoot,
|
|
||||||
services.Paths.DataRoot,
|
|
||||||
services.Paths.SettingsFile,
|
|
||||||
LauncherRuntimeInfo.CurrentLauncherVersion,
|
|
||||||
LauncherRuntimeInfo.CurrentRid,
|
|
||||||
services.Settings.Current.Sources.Select(ToSourceDto).ToList(),
|
|
||||||
L.Supported.Select(s => new LanguageDto(s.Code, s.Label)).ToList());
|
|
||||||
|
|
||||||
JobDto ToJobDto(IDownloadJob job) => new(
|
|
||||||
job.Id,
|
|
||||||
job.Model.Id,
|
|
||||||
job.Name,
|
|
||||||
job.Version,
|
|
||||||
job.State.ToString(),
|
|
||||||
job.Progress,
|
|
||||||
job.StatusText,
|
|
||||||
job.DetailText,
|
|
||||||
job.Error,
|
|
||||||
job.IsActive,
|
|
||||||
job.CanRetry,
|
|
||||||
job.IsDone);
|
|
||||||
|
|
||||||
ModelSource? ResolveSource(string? sourceId)
|
|
||||||
{
|
|
||||||
var sources = services.Settings.Current.Sources;
|
|
||||||
if (!string.IsNullOrWhiteSpace(sourceId))
|
|
||||||
{
|
|
||||||
var exact = sources.FirstOrDefault(s =>
|
|
||||||
s.Id.Equals(sourceId, StringComparison.OrdinalIgnoreCase));
|
|
||||||
if (exact != null) return exact;
|
|
||||||
}
|
|
||||||
|
|
||||||
return sources.FirstOrDefault(s => s.Enabled && !string.IsNullOrWhiteSpace(s.Url))
|
|
||||||
?? sources.FirstOrDefault();
|
|
||||||
}
|
|
||||||
|
|
||||||
IResult ActOnJob(string id, Action<IDownloadJob> action)
|
|
||||||
{
|
|
||||||
if (!IsSafeId(id)) return Results.BadRequest(new LaunchResultDto(false, "任务标识无效"));
|
|
||||||
var job = services.Downloads.Jobs.FirstOrDefault(j =>
|
|
||||||
j.Id.Equals(id, StringComparison.OrdinalIgnoreCase));
|
|
||||||
if (job == null) return Results.NotFound(new LaunchResultDto(false, $"没有找到任务 {id}"));
|
|
||||||
|
|
||||||
action(job);
|
|
||||||
return Results.Ok(ToJobDto(job));
|
|
||||||
}
|
|
||||||
|
|
||||||
bool IsInsideKnownRoot(string path)
|
|
||||||
{
|
|
||||||
try
|
|
||||||
{
|
|
||||||
var full = Path.GetFullPath(path);
|
|
||||||
var roots = new[]
|
|
||||||
{
|
|
||||||
services.Paths.ModelRoot,
|
|
||||||
services.Paths.DataRoot,
|
|
||||||
services.Paths.HomeRoot,
|
|
||||||
services.Paths.AppRoot
|
|
||||||
};
|
|
||||||
|
|
||||||
foreach (var root in roots)
|
|
||||||
{
|
|
||||||
if (string.IsNullOrWhiteSpace(root)) continue;
|
|
||||||
var rootFull = Path.GetFullPath(root);
|
|
||||||
if (full.Equals(rootFull, StringComparison.OrdinalIgnoreCase)) return true;
|
|
||||||
if (full.StartsWith(rootFull + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase))
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
catch
|
|
||||||
{
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
// 路由标识:只允许字母数字开头,后接字母数字/点/下划线/短横线,长度上限 64。
|
|
||||||
// 用于模型 id、任务 id,杜绝 `../` 之类的路径穿越尝试。
|
|
||||||
bool IsSafeId(string? id) => !string.IsNullOrEmpty(id) && safeIdRegex.IsMatch(id);
|
|
||||||
|
|
||||||
// 更新仓库地址:必须是 https、不带账号密码、不是回环/内网 IP。
|
|
||||||
// 防止把本地后端当成 SSRF 跳板去访问内网服务。
|
|
||||||
bool IsAllowedRepository(string value)
|
|
||||||
{
|
|
||||||
if (string.IsNullOrWhiteSpace(value)) return false;
|
|
||||||
if (!Uri.TryCreate(value, UriKind.Absolute, out var uri)) return false;
|
|
||||||
if (uri.Scheme != Uri.UriSchemeHttps) return false;
|
|
||||||
if (!string.IsNullOrEmpty(uri.UserInfo)) return false;
|
|
||||||
if (string.Equals(uri.Host, "localhost", StringComparison.OrdinalIgnoreCase)) return false;
|
|
||||||
if (System.Net.IPAddress.TryParse(uri.Host, out var ip) &&
|
|
||||||
(System.Net.IPAddress.IsLoopback(ip) || IsPrivateAddress(ip)))
|
|
||||||
return false;
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
static bool IsPrivateAddress(System.Net.IPAddress ip)
|
|
||||||
{
|
|
||||||
var bytes = ip.GetAddressBytes();
|
|
||||||
if (bytes.Length != 4) return false;
|
|
||||||
return bytes[0] == 10
|
|
||||||
|| (bytes[0] == 172 && bytes[1] >= 16 && bytes[1] <= 31)
|
|
||||||
|| (bytes[0] == 192 && bytes[1] == 168)
|
|
||||||
|| (bytes[0] == 169 && bytes[1] == 254);
|
|
||||||
}
|
}
|
||||||
@@ -15,6 +15,9 @@ migration:
|
|||||||
- platform: root
|
- platform: root
|
||||||
create_revision: dec2ee5c1f98f8e84a7d5380c05eb8a3d0a81668
|
create_revision: dec2ee5c1f98f8e84a7d5380c05eb8a3d0a81668
|
||||||
base_revision: dec2ee5c1f98f8e84a7d5380c05eb8a3d0a81668
|
base_revision: dec2ee5c1f98f8e84a7d5380c05eb8a3d0a81668
|
||||||
|
- platform: linux
|
||||||
|
create_revision: dec2ee5c1f98f8e84a7d5380c05eb8a3d0a81668
|
||||||
|
base_revision: dec2ee5c1f98f8e84a7d5380c05eb8a3d0a81668
|
||||||
- platform: macos
|
- platform: macos
|
||||||
create_revision: dec2ee5c1f98f8e84a7d5380c05eb8a3d0a81668
|
create_revision: dec2ee5c1f98f8e84a7d5380c05eb8a3d0a81668
|
||||||
base_revision: dec2ee5c1f98f8e84a7d5380c05eb8a3d0a81668
|
base_revision: dec2ee5c1f98f8e84a7d5380c05eb8a3d0a81668
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import 'dart:convert';
|
import 'dart:convert';
|
||||||
|
import 'dart:io';
|
||||||
|
|
||||||
import 'package:http/http.dart' as http;
|
import 'package:http/http.dart' as http;
|
||||||
|
|
||||||
@@ -334,16 +335,65 @@ List<String> _stringList(dynamic value) =>
|
|||||||
|
|
||||||
/// GC-UI 后端客户端。
|
/// GC-UI 后端客户端。
|
||||||
///
|
///
|
||||||
/// 后端是本地伴随进程,默认监听 127.0.0.1:17890;端口可用
|
/// 后端是本地伴随进程,端口由启动器(GC-BOOT)选定后通过 `GC_UI_PORT`
|
||||||
/// `--dart-define=GC_UI_BASE_URL=http://127.0.0.1:12345` 覆盖。
|
/// 环境变量传进来 —— 这样端口被占用时换端口不用重新编译前端。
|
||||||
|
/// 也可用 `--dart-define=GC_UI_BASE_URL=http://127.0.0.1:12345` 强制指定。
|
||||||
class GcApi {
|
class GcApi {
|
||||||
GcApi({String? baseUrl})
|
GcApi({String? baseUrl})
|
||||||
: baseUrl = baseUrl ?? defaultBaseUrl;
|
: baseUrl = baseUrl ?? defaultBaseUrl;
|
||||||
|
|
||||||
static const String defaultBaseUrl = String.fromEnvironment(
|
/// 复用同一个 HTTP 连接:轮询(下载任务每秒一次)时每次都新建连接
|
||||||
'GC_UI_BASE_URL',
|
/// 会不断握手,桌面端也能明显看到延迟抖动。
|
||||||
defaultValue: 'http://127.0.0.1:17890',
|
static final http.Client _client = http.Client();
|
||||||
);
|
|
||||||
|
/// 兜底默认端口,与后端 GC.Services.GcUiContract.DefaultPort 保持一致。
|
||||||
|
static const int fallbackPort = 17890;
|
||||||
|
|
||||||
|
static String get defaultBaseUrl {
|
||||||
|
const fromDefine = String.fromEnvironment('GC_UI_BASE_URL');
|
||||||
|
if (fromDefine.isNotEmpty) return fromDefine;
|
||||||
|
|
||||||
|
final fromEnvUrl = Platform.environment['GC_UI_BASE_URL'];
|
||||||
|
if (fromEnvUrl != null && fromEnvUrl.isNotEmpty) return fromEnvUrl;
|
||||||
|
|
||||||
|
// 启动器通过 GC_UI_PORT 传端口(主路径)。
|
||||||
|
final port = int.tryParse(Platform.environment['GC_UI_PORT'] ?? '');
|
||||||
|
if (port != null) return 'http://127.0.0.1:$port';
|
||||||
|
|
||||||
|
// 手动起后端 / 前端调试时没有环境变量:读后端写的 .GC/ui-backend.json。
|
||||||
|
final discovered = _endpointFileUrl();
|
||||||
|
if (discovered != null) return discovered;
|
||||||
|
|
||||||
|
return 'http://127.0.0.1:$fallbackPort';
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 从运行目录下的 `.GC/ui-backend.json` 发现后端地址。
|
||||||
|
///
|
||||||
|
/// 后端每次启动都会写这个文件(port / pid / url)。只认 24 小时内的记录:
|
||||||
|
/// 更早的多半是上次遗留的,连过去只会得到一个「无法连接」。
|
||||||
|
static String? _endpointFileUrl() {
|
||||||
|
try {
|
||||||
|
final file = File('${Directory.current.path}/.GC/ui-backend.json');
|
||||||
|
if (!file.existsSync()) return null;
|
||||||
|
|
||||||
|
final age = DateTime.now().difference(file.lastModifiedSync());
|
||||||
|
if (age.inHours >= 24) return null;
|
||||||
|
|
||||||
|
final decoded = jsonDecode(file.readAsStringSync());
|
||||||
|
if (decoded is! Map<String, dynamic>) return null;
|
||||||
|
|
||||||
|
final url = decoded['url'];
|
||||||
|
if (url is String && url.startsWith('http://127.0.0.1:')) return url;
|
||||||
|
|
||||||
|
final port = (decoded['port'] as num?)?.toInt();
|
||||||
|
if (port != null && port > 0 && port < 65536) {
|
||||||
|
return 'http://127.0.0.1:$port';
|
||||||
|
}
|
||||||
|
} catch (_) {
|
||||||
|
// 文件损坏 / 无权限:退回默认端口即可
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
final String baseUrl;
|
final String baseUrl;
|
||||||
|
|
||||||
@@ -357,17 +407,17 @@ class GcApi {
|
|||||||
try {
|
try {
|
||||||
switch (method) {
|
switch (method) {
|
||||||
case 'GET':
|
case 'GET':
|
||||||
response = await http.get(uri).timeout(const Duration(seconds: 30));
|
response = await _client.get(uri).timeout(const Duration(seconds: 30));
|
||||||
break;
|
break;
|
||||||
case 'POST':
|
case 'POST':
|
||||||
response = await http
|
response = await _client
|
||||||
.post(uri,
|
.post(uri,
|
||||||
headers: const {'Content-Type': 'application/json'},
|
headers: const {'Content-Type': 'application/json'},
|
||||||
body: body == null ? null : jsonEncode(body))
|
body: body == null ? null : jsonEncode(body))
|
||||||
.timeout(const Duration(seconds: 120));
|
.timeout(const Duration(seconds: 120));
|
||||||
break;
|
break;
|
||||||
case 'DELETE':
|
case 'DELETE':
|
||||||
response = await http.delete(uri).timeout(const Duration(seconds: 30));
|
response = await _client.delete(uri).timeout(const Duration(seconds: 30));
|
||||||
break;
|
break;
|
||||||
default:
|
default:
|
||||||
throw ApiException('不支持的方法 $method');
|
throw ApiException('不支持的方法 $method');
|
||||||
|
|||||||
@@ -1,3 +1,5 @@
|
|||||||
|
import 'dart:async';
|
||||||
|
|
||||||
import 'package:flutter/foundation.dart';
|
import 'package:flutter/foundation.dart';
|
||||||
|
|
||||||
import 'api_client.dart';
|
import 'api_client.dart';
|
||||||
@@ -24,26 +26,75 @@ class ShellController extends ChangeNotifier {
|
|||||||
String updateDetail = '';
|
String updateDetail = '';
|
||||||
String launcherNotice = '';
|
String launcherNotice = '';
|
||||||
|
|
||||||
|
/// 模型库版本号:安装 / 删除 / 下载完成后自增,首页据此重新拉列表。
|
||||||
|
///
|
||||||
|
/// 首页被 `Offstage` 保活,切走再切回不会重建;没有这个信号时,
|
||||||
|
/// 下载完模型回到首页仍然显示旧的空列表。
|
||||||
|
int modelsRevision = 0;
|
||||||
|
|
||||||
|
Timer? _retryTimer;
|
||||||
|
int _retryAttempt = 0;
|
||||||
|
|
||||||
bool get backendReady => settings != null;
|
bool get backendReady => settings != null;
|
||||||
|
|
||||||
Future<void> bootstrap() async {
|
Future<void> bootstrap() async {
|
||||||
try {
|
_retryTimer?.cancel();
|
||||||
// 健康检查与设置并行请求:两者互不依赖,串行会白白多等一次网络往返。
|
|
||||||
final healthFuture = api.health();
|
HealthInfo? healthResult;
|
||||||
final settingsFuture = api.settings();
|
SettingsInfo? settingsResult;
|
||||||
health = await healthFuture;
|
Object? firstError;
|
||||||
settings = await settingsFuture;
|
|
||||||
loadError = null;
|
// 两个请求互不依赖,并行发;各自捕获异常,避免一方失败时
|
||||||
_applySettings(settings!);
|
// 另一个的 Future 抛成未处理异常(Flutter 会在控制台打出恶性警告)。
|
||||||
} catch (error) {
|
await Future.wait<void>(<Future<void>>[
|
||||||
loadError = error.toString();
|
() async {
|
||||||
|
try {
|
||||||
|
healthResult = await api.health();
|
||||||
|
} catch (error) {
|
||||||
|
firstError ??= error;
|
||||||
|
}
|
||||||
|
}(),
|
||||||
|
() async {
|
||||||
|
try {
|
||||||
|
settingsResult = await api.settings();
|
||||||
|
} catch (error) {
|
||||||
|
firstError ??= error;
|
||||||
|
}
|
||||||
|
}(),
|
||||||
|
]);
|
||||||
|
|
||||||
|
if (healthResult != null) health = healthResult;
|
||||||
|
if (settingsResult != null) {
|
||||||
|
settings = settingsResult;
|
||||||
|
_applySettings(settingsResult!);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (firstError != null && settingsResult == null) {
|
||||||
|
loadError = firstError.toString();
|
||||||
|
_scheduleRetry();
|
||||||
|
} else {
|
||||||
|
loadError = null;
|
||||||
|
_retryAttempt = 0;
|
||||||
|
}
|
||||||
|
|
||||||
notifyListeners();
|
notifyListeners();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// 后端没起来时自动重试(2s、4s、8s…最多 5 次),不必让用户手动点。
|
||||||
|
void _scheduleRetry() {
|
||||||
|
if (_retryAttempt >= 5) return;
|
||||||
|
final seconds = 1 << _retryAttempt; // 1,2,4,8,16
|
||||||
|
_retryAttempt++;
|
||||||
|
_retryTimer?.cancel();
|
||||||
|
_retryTimer = Timer(Duration(seconds: seconds), () {
|
||||||
|
if (settings == null) bootstrap();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
void _applySettings(SettingsInfo value) {
|
void _applySettings(SettingsInfo value) {
|
||||||
I18n.setLanguage(value.language);
|
I18n.setLanguage(value.language);
|
||||||
GcPalette.apply(value.accentColor);
|
GcPalette.apply(value.accentColor);
|
||||||
|
GcPalette.applyTheme(value.theme);
|
||||||
}
|
}
|
||||||
|
|
||||||
void goTo(int value) {
|
void goTo(int value) {
|
||||||
@@ -52,6 +103,12 @@ class ShellController extends ChangeNotifier {
|
|||||||
notifyListeners();
|
notifyListeners();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// 模型库有变化(安装 / 删除 / 下载完成):通知首页刷新。
|
||||||
|
void modelsChanged() {
|
||||||
|
modelsRevision++;
|
||||||
|
notifyListeners();
|
||||||
|
}
|
||||||
|
|
||||||
Future<void> reloadSettings() async {
|
Future<void> reloadSettings() async {
|
||||||
try {
|
try {
|
||||||
settings = await api.settings();
|
settings = await api.settings();
|
||||||
@@ -112,6 +169,7 @@ class ShellController extends ChangeNotifier {
|
|||||||
detail: result.error ?? '',
|
detail: result.error ?? '',
|
||||||
notice: result.launcherMessage ?? '',
|
notice: result.launcherMessage ?? '',
|
||||||
);
|
);
|
||||||
|
if (result.updatedModels > 0) modelsChanged();
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
setUpdateStatus(
|
setUpdateStatus(
|
||||||
busy: false,
|
busy: false,
|
||||||
@@ -120,4 +178,10 @@ class ShellController extends ChangeNotifier {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
void dispose() {
|
||||||
|
_retryTimer?.cancel();
|
||||||
|
super.dispose();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -64,6 +64,11 @@ class I18n {
|
|||||||
'set.subtitle': '模型源、启动时内存分配与本地存储。',
|
'set.subtitle': '模型源、启动时内存分配与本地存储。',
|
||||||
'set.general': '通用',
|
'set.general': '通用',
|
||||||
'set.appearance': '外观',
|
'set.appearance': '外观',
|
||||||
|
'set.theme': '主题模式',
|
||||||
|
'set.theme.desc': '深色、浅色,或跟随系统设置。',
|
||||||
|
'set.theme.dark': '深色',
|
||||||
|
'set.theme.light': '浅色',
|
||||||
|
'set.theme.system': '跟随系统',
|
||||||
'set.accent': '主题颜色',
|
'set.accent': '主题颜色',
|
||||||
'set.accent.desc': '选择启动器的主色调,按钮、滑块与高亮会同步换色。',
|
'set.accent.desc': '选择启动器的主色调,按钮、滑块与高亮会同步换色。',
|
||||||
'set.accent.custom': '自定义颜色',
|
'set.accent.custom': '自定义颜色',
|
||||||
@@ -133,6 +138,11 @@ class I18n {
|
|||||||
'about.architectureValue': 'Flutter 前端 + .NET 后端(本地 HTTP)',
|
'about.architectureValue': 'Flutter 前端 + .NET 后端(本地 HTTP)',
|
||||||
'about.sourceLanguage': '源码语言',
|
'about.sourceLanguage': '源码语言',
|
||||||
'about.frontend': '前端',
|
'about.frontend': '前端',
|
||||||
|
'about.gitService': 'Git 服务',
|
||||||
|
'about.thanks': '感谢',
|
||||||
|
'about.thanksHint': '特别感谢以下朋友的支持',
|
||||||
|
'about.thanksGit': 'Git 服务与部署支持',
|
||||||
|
'about.thanksGeo': '地理学科内容指导',
|
||||||
},
|
},
|
||||||
'en': <String, String>{
|
'en': <String, String>{
|
||||||
'app.name': 'Morris GC',
|
'app.name': 'Morris GC',
|
||||||
@@ -189,6 +199,11 @@ class I18n {
|
|||||||
'set.subtitle': 'Model sources, startup memory allocation and local storage.',
|
'set.subtitle': 'Model sources, startup memory allocation and local storage.',
|
||||||
'set.general': 'General',
|
'set.general': 'General',
|
||||||
'set.appearance': 'Appearance',
|
'set.appearance': 'Appearance',
|
||||||
|
'set.theme': 'Theme mode',
|
||||||
|
'set.theme.desc': 'Dark, light, or follow the system setting.',
|
||||||
|
'set.theme.dark': 'Dark',
|
||||||
|
'set.theme.light': 'Light',
|
||||||
|
'set.theme.system': 'System',
|
||||||
'set.accent': 'Theme color',
|
'set.accent': 'Theme color',
|
||||||
'set.accent.desc': 'Pick the launcher accent color; buttons, sliders and highlights follow it.',
|
'set.accent.desc': 'Pick the launcher accent color; buttons, sliders and highlights follow it.',
|
||||||
'set.accent.custom': 'Custom color',
|
'set.accent.custom': 'Custom color',
|
||||||
@@ -258,6 +273,11 @@ class I18n {
|
|||||||
'about.architectureValue': 'Flutter frontend + .NET backend (local HTTP)',
|
'about.architectureValue': 'Flutter frontend + .NET backend (local HTTP)',
|
||||||
'about.sourceLanguage': 'Source language',
|
'about.sourceLanguage': 'Source language',
|
||||||
'about.frontend': 'Frontend',
|
'about.frontend': 'Frontend',
|
||||||
|
'about.gitService': 'Git hosting',
|
||||||
|
'about.thanks': 'Thanks',
|
||||||
|
'about.thanksHint': 'Special thanks to',
|
||||||
|
'about.thanksGit': 'Git hosting and deployment',
|
||||||
|
'about.thanksGeo': 'Geography content guidance',
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -12,7 +12,7 @@ void main() {
|
|||||||
runApp(const GcUiApp());
|
runApp(const GcUiApp());
|
||||||
}
|
}
|
||||||
|
|
||||||
/// GC-UI 前端:Flutter 桌面应用(Windows / macOS)。
|
/// GC-UI 前端:Flutter 桌面应用(Windows / macOS / Linux)。
|
||||||
///
|
///
|
||||||
/// 界面全部在这里;模型扫描、下载、更新、设置、模型窗口宿主都在后端
|
/// 界面全部在这里;模型扫描、下载、更新、设置、模型窗口宿主都在后端
|
||||||
/// (GC-UI/backend/GC.UI.Server,本地 HTTP 服务)。
|
/// (GC-UI/backend/GC.UI.Server,本地 HTTP 服务)。
|
||||||
@@ -28,7 +28,7 @@ class _GcUiAppState extends State<GcUiApp> {
|
|||||||
|
|
||||||
@override
|
@override
|
||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
// 语言与强调色都会触发重建:只重建 MaterialApp 的主题层,
|
// 语言、强调色、主题模式都会触发重建:只重建 MaterialApp 的主题层,
|
||||||
// 不触碰页面状态(页面由 ShellPage 自己持有)。
|
// 不触碰页面状态(页面由 ShellPage 自己持有)。
|
||||||
return ValueListenableBuilder<String>(
|
return ValueListenableBuilder<String>(
|
||||||
valueListenable: I18n.language,
|
valueListenable: I18n.language,
|
||||||
@@ -36,11 +36,30 @@ class _GcUiAppState extends State<GcUiApp> {
|
|||||||
return ValueListenableBuilder<Color>(
|
return ValueListenableBuilder<Color>(
|
||||||
valueListenable: GcPalette.accent,
|
valueListenable: GcPalette.accent,
|
||||||
builder: (context, accent, _) {
|
builder: (context, accent, _) {
|
||||||
return MaterialApp(
|
return ValueListenableBuilder<ThemeMode>(
|
||||||
title: 'Morris GC',
|
valueListenable: GcPalette.mode,
|
||||||
debugShowCheckedModeBanner: false,
|
builder: (context, mode, _) {
|
||||||
theme: buildGcTheme(),
|
return MaterialApp(
|
||||||
home: ShellPage(controller: _controller),
|
title: 'Morris GC',
|
||||||
|
debugShowCheckedModeBanner: false,
|
||||||
|
// 桌面端不要移动端那套拉伸回弹和边缘光晕。
|
||||||
|
scrollBehavior: const GcScrollBehavior(),
|
||||||
|
theme: buildGcTheme(Brightness.light),
|
||||||
|
darkTheme: buildGcTheme(Brightness.dark),
|
||||||
|
themeMode: mode,
|
||||||
|
// GcColors 是静态取值,必须按当前实际亮度(含跟随系统)绑定,
|
||||||
|
// 再用 key 强制子树重建,否则切主题后颜色仍是上一套。
|
||||||
|
builder: (context, child) {
|
||||||
|
final brightness = Theme.of(context).brightness;
|
||||||
|
GcColors.bind(brightness);
|
||||||
|
return KeyedSubtree(
|
||||||
|
key: ValueKey<bool>(brightness == Brightness.dark),
|
||||||
|
child: child ?? const SizedBox.shrink(),
|
||||||
|
);
|
||||||
|
},
|
||||||
|
home: ShellPage(controller: _controller),
|
||||||
|
);
|
||||||
|
},
|
||||||
);
|
);
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|||||||
+6
-1859
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,405 @@
|
|||||||
|
import 'dart:async';
|
||||||
|
|
||||||
|
import 'package:flutter/material.dart';
|
||||||
|
|
||||||
|
import '../api_client.dart';
|
||||||
|
import '../controller.dart';
|
||||||
|
import '../i18n.dart';
|
||||||
|
import '../theme.dart';
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// 关于页(从原 pages.dart 拆出,公开类名不变)
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// 关于页
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
class AboutPageView extends StatefulWidget {
|
||||||
|
const AboutPageView({super.key, required this.controller, this.initialAbout});
|
||||||
|
|
||||||
|
final ShellController controller;
|
||||||
|
|
||||||
|
/// 预置数据(仅用于测试 / 截图,正常运行时为 null,由后端提供)。
|
||||||
|
final AboutInfo? initialAbout;
|
||||||
|
|
||||||
|
@override
|
||||||
|
State<AboutPageView> createState() => _AboutPageViewState();
|
||||||
|
}
|
||||||
|
|
||||||
|
class _AboutPageViewState extends State<AboutPageView> {
|
||||||
|
AboutInfo? _about;
|
||||||
|
bool _loading = true;
|
||||||
|
String? _error;
|
||||||
|
|
||||||
|
@override
|
||||||
|
void initState() {
|
||||||
|
super.initState();
|
||||||
|
final preset = widget.initialAbout;
|
||||||
|
if (preset != null) {
|
||||||
|
_about = preset;
|
||||||
|
_loading = false;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
_load();
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _load() async {
|
||||||
|
setState(() {
|
||||||
|
_loading = true;
|
||||||
|
_error = null;
|
||||||
|
});
|
||||||
|
try {
|
||||||
|
final about = await widget.controller.api.about();
|
||||||
|
if (!mounted) return;
|
||||||
|
setState(() {
|
||||||
|
_about = about;
|
||||||
|
_loading = false;
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
if (!mounted) return;
|
||||||
|
setState(() {
|
||||||
|
_error = error.toString();
|
||||||
|
_loading = false;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
return ListView(
|
||||||
|
padding: const EdgeInsets.fromLTRB(
|
||||||
|
GcSpace.xxl,
|
||||||
|
GcSpace.xxl,
|
||||||
|
GcSpace.xxl,
|
||||||
|
GcSpace.xxxl,
|
||||||
|
),
|
||||||
|
children: <Widget>[
|
||||||
|
GcPageHeader(
|
||||||
|
title: T('nav.about'),
|
||||||
|
subtitle: T('app.tagline'),
|
||||||
|
),
|
||||||
|
const SizedBox(height: GcSpace.xxl),
|
||||||
|
if (_loading)
|
||||||
|
const Padding(
|
||||||
|
padding: EdgeInsets.symmetric(vertical: 48),
|
||||||
|
child: Center(
|
||||||
|
child: SizedBox(
|
||||||
|
width: 22,
|
||||||
|
height: 22,
|
||||||
|
child: CircularProgressIndicator(strokeWidth: 2),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
else if (_error != null)
|
||||||
|
GcMessage(
|
||||||
|
title: T('common.error'),
|
||||||
|
message: _error,
|
||||||
|
icon: Icons.error_outline_rounded,
|
||||||
|
color: GcColors.danger,
|
||||||
|
action: OutlinedButton(
|
||||||
|
onPressed: _load,
|
||||||
|
child: Text(T('common.retry')),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
else ...<Widget>[
|
||||||
|
_versionCard(),
|
||||||
|
const SizedBox(height: GcSpace.lg),
|
||||||
|
_contributorsCard(),
|
||||||
|
const SizedBox(height: GcSpace.lg),
|
||||||
|
_thanksCard(),
|
||||||
|
],
|
||||||
|
],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Widget _versionCard() {
|
||||||
|
final about = _about;
|
||||||
|
|
||||||
|
// 左边身份卡、右边信息表:宽屏两栏,窄屏自动堆叠。
|
||||||
|
final identity = Column(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
|
mainAxisSize: MainAxisSize.min,
|
||||||
|
children: <Widget>[
|
||||||
|
Row(
|
||||||
|
children: <Widget>[
|
||||||
|
Container(
|
||||||
|
width: 44,
|
||||||
|
height: 44,
|
||||||
|
alignment: Alignment.center,
|
||||||
|
decoration: BoxDecoration(
|
||||||
|
color: GcColors.accentSoft,
|
||||||
|
borderRadius: BorderRadius.circular(GcRadius.card),
|
||||||
|
),
|
||||||
|
child: Text(
|
||||||
|
'◎',
|
||||||
|
style: TextStyle(
|
||||||
|
fontSize: 22, height: 1.1, color: GcColors.accent),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
const SizedBox(width: GcSpace.lg),
|
||||||
|
Expanded(
|
||||||
|
child: Column(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
|
mainAxisSize: MainAxisSize.min,
|
||||||
|
children: <Widget>[
|
||||||
|
Text(
|
||||||
|
about?.appName ?? 'Morris GC',
|
||||||
|
style: TextStyle(
|
||||||
|
fontSize: 20,
|
||||||
|
height: 1.3,
|
||||||
|
fontWeight: FontWeight.w600,
|
||||||
|
color: GcColors.ink,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
const SizedBox(height: 2),
|
||||||
|
Text(
|
||||||
|
T('app.tagline'),
|
||||||
|
style: TextStyle(
|
||||||
|
fontSize: 12.5,
|
||||||
|
height: 1.5,
|
||||||
|
color: GcColors.faint,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
const SizedBox(height: GcSpace.lg),
|
||||||
|
Wrap(
|
||||||
|
spacing: GcSpace.sm,
|
||||||
|
runSpacing: GcSpace.sm,
|
||||||
|
children: <Widget>[
|
||||||
|
GcPill('v${about?.version ?? '—'}', color: GcColors.accent),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
const SizedBox(height: GcSpace.lg),
|
||||||
|
OutlinedButton(
|
||||||
|
onPressed: () async {
|
||||||
|
final url = about?.repository;
|
||||||
|
if (url == null || url.isEmpty) return;
|
||||||
|
try {
|
||||||
|
await widget.controller.api.openUrl(url);
|
||||||
|
} catch (_) {
|
||||||
|
// 忽略
|
||||||
|
}
|
||||||
|
},
|
||||||
|
child: Text(T('about.openRepository')),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
|
||||||
|
final details = Column(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||||
|
mainAxisSize: MainAxisSize.min,
|
||||||
|
children: <Widget>[
|
||||||
|
GcFieldRow(
|
||||||
|
label: T('set.platform'),
|
||||||
|
value: about?.platform ?? '—',
|
||||||
|
),
|
||||||
|
GcFieldRow(
|
||||||
|
label: T('about.architecture'),
|
||||||
|
value: T('about.architectureValue'),
|
||||||
|
),
|
||||||
|
GcFieldRow(
|
||||||
|
label: T('about.sourceLanguage'),
|
||||||
|
value: about?.sourceLanguage ?? 'C#',
|
||||||
|
),
|
||||||
|
GcFieldRow(
|
||||||
|
label: T('about.frontend'),
|
||||||
|
value: about?.frontend ?? 'Flutter',
|
||||||
|
),
|
||||||
|
GcFieldRow(
|
||||||
|
label: T('about.gitService'),
|
||||||
|
value: 'itxiaohui',
|
||||||
|
),
|
||||||
|
GcFieldRow(
|
||||||
|
label: T('set.license'),
|
||||||
|
value: T('set.licenseValue'),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
|
||||||
|
return GcCard(
|
||||||
|
padding: const EdgeInsets.all(GcSpace.xxl),
|
||||||
|
child: LayoutBuilder(
|
||||||
|
builder: (context, constraints) {
|
||||||
|
if (constraints.maxWidth < 720) {
|
||||||
|
return Column(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
|
children: <Widget>[
|
||||||
|
identity,
|
||||||
|
const GcDivider(verticalPadding: GcSpace.lg),
|
||||||
|
details,
|
||||||
|
],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return Row(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
|
children: <Widget>[
|
||||||
|
Expanded(flex: 4, child: identity),
|
||||||
|
const SizedBox(width: GcSpace.xxxl),
|
||||||
|
Expanded(flex: 5, child: details),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
},
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Widget _contributorsCard() {
|
||||||
|
final contributors = _about?.contributors ?? const <ContributorInfo>[];
|
||||||
|
return GcCard(
|
||||||
|
padding: const EdgeInsets.all(GcSpace.xxl),
|
||||||
|
child: Column(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
|
children: <Widget>[
|
||||||
|
GcSectionTitle(
|
||||||
|
T('about.developers'),
|
||||||
|
subtitle: T('about.contributorsHint'),
|
||||||
|
),
|
||||||
|
const SizedBox(height: GcSpace.lg),
|
||||||
|
if (contributors.isEmpty)
|
||||||
|
GcHint(T('about.noContributors'))
|
||||||
|
else
|
||||||
|
Wrap(
|
||||||
|
spacing: GcSpace.xl,
|
||||||
|
runSpacing: GcSpace.md,
|
||||||
|
children: <Widget>[
|
||||||
|
for (final contributor in contributors)
|
||||||
|
SizedBox(
|
||||||
|
width: 220,
|
||||||
|
child: Row(
|
||||||
|
children: <Widget>[
|
||||||
|
CircleAvatar(
|
||||||
|
radius: 18,
|
||||||
|
backgroundColor: GcColors.surfaceAlt,
|
||||||
|
backgroundImage: contributor.avatarUrl == null
|
||||||
|
? null
|
||||||
|
: NetworkImage(contributor.avatarUrl!),
|
||||||
|
child: contributor.avatarUrl == null
|
||||||
|
? Text(
|
||||||
|
'◎',
|
||||||
|
style: TextStyle(
|
||||||
|
fontSize: 14,
|
||||||
|
color: GcColors.accent,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
: null,
|
||||||
|
),
|
||||||
|
const SizedBox(width: GcSpace.md),
|
||||||
|
Expanded(
|
||||||
|
child: Column(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
|
mainAxisSize: MainAxisSize.min,
|
||||||
|
children: <Widget>[
|
||||||
|
Text(
|
||||||
|
contributor.name,
|
||||||
|
maxLines: 1,
|
||||||
|
overflow: TextOverflow.ellipsis,
|
||||||
|
style: TextStyle(
|
||||||
|
fontSize: 13,
|
||||||
|
height: 1.4,
|
||||||
|
fontWeight: FontWeight.w600,
|
||||||
|
color: GcColors.ink,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
Text(
|
||||||
|
T(
|
||||||
|
'about.contributions',
|
||||||
|
<Object?>[contributor.contributions],
|
||||||
|
),
|
||||||
|
style: TextStyle(
|
||||||
|
fontSize: 11.5,
|
||||||
|
height: 1.4,
|
||||||
|
color: GcColors.faint,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 特别感谢:与「开发者」分开列 —— 提供 Git 服务不等于往仓库提交代码,
|
||||||
|
/// 混进贡献者列表会让提交数失去意义。
|
||||||
|
Widget _thanksCard() {
|
||||||
|
return GcCard(
|
||||||
|
padding: const EdgeInsets.all(GcSpace.xxl),
|
||||||
|
child: Column(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
|
children: <Widget>[
|
||||||
|
GcSectionTitle(
|
||||||
|
T('about.thanks'),
|
||||||
|
subtitle: T('about.thanksHint'),
|
||||||
|
),
|
||||||
|
const SizedBox(height: GcSpace.lg),
|
||||||
|
Wrap(
|
||||||
|
spacing: GcSpace.xl,
|
||||||
|
runSpacing: GcSpace.md,
|
||||||
|
children: <Widget>[
|
||||||
|
_creditTile('地理洪老师', 'about.thanksGeo'),
|
||||||
|
_creditTile('itxiaohui', 'about.thanksGit'),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Widget _creditTile(String name, String roleKey) {
|
||||||
|
return SizedBox(
|
||||||
|
width: 220,
|
||||||
|
child: Row(
|
||||||
|
children: <Widget>[
|
||||||
|
CircleAvatar(
|
||||||
|
radius: 18,
|
||||||
|
backgroundColor: GcColors.surfaceAlt,
|
||||||
|
child: Text(
|
||||||
|
'◎',
|
||||||
|
style: TextStyle(fontSize: 14, color: GcColors.accent),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
const SizedBox(width: GcSpace.md),
|
||||||
|
Expanded(
|
||||||
|
child: Column(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
|
mainAxisSize: MainAxisSize.min,
|
||||||
|
children: <Widget>[
|
||||||
|
Text(
|
||||||
|
name,
|
||||||
|
maxLines: 1,
|
||||||
|
overflow: TextOverflow.ellipsis,
|
||||||
|
style: TextStyle(
|
||||||
|
fontSize: 13,
|
||||||
|
height: 1.4,
|
||||||
|
fontWeight: FontWeight.w600,
|
||||||
|
color: GcColors.ink,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
Text(
|
||||||
|
T(roleKey),
|
||||||
|
maxLines: 1,
|
||||||
|
overflow: TextOverflow.ellipsis,
|
||||||
|
style: TextStyle(
|
||||||
|
fontSize: 11.5,
|
||||||
|
height: 1.4,
|
||||||
|
color: GcColors.faint,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,579 @@
|
|||||||
|
import 'dart:async';
|
||||||
|
|
||||||
|
import 'package:flutter/material.dart';
|
||||||
|
|
||||||
|
import '../api_client.dart';
|
||||||
|
import '../controller.dart';
|
||||||
|
import '../i18n.dart';
|
||||||
|
import '../theme.dart';
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// 下载页(从原 pages.dart 拆出,公开类名不变)
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// 下载页
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
class DownloadPageView extends StatefulWidget {
|
||||||
|
const DownloadPageView({
|
||||||
|
super.key,
|
||||||
|
required this.controller,
|
||||||
|
this.initialSources,
|
||||||
|
this.initialIndex,
|
||||||
|
this.initialJobs,
|
||||||
|
});
|
||||||
|
|
||||||
|
final ShellController controller;
|
||||||
|
|
||||||
|
/// 预置数据(仅用于测试 / 截图,正常运行时为 null,由后端提供)。
|
||||||
|
final List<SourceInfo>? initialSources;
|
||||||
|
final SourceIndexInfo? initialIndex;
|
||||||
|
final List<JobInfo>? initialJobs;
|
||||||
|
|
||||||
|
@override
|
||||||
|
State<DownloadPageView> createState() => _DownloadPageViewState();
|
||||||
|
}
|
||||||
|
|
||||||
|
class _DownloadPageViewState extends State<DownloadPageView> {
|
||||||
|
List<SourceInfo> _sources = const <SourceInfo>[];
|
||||||
|
SourceIndexInfo? _index;
|
||||||
|
List<JobInfo> _jobs = const <JobInfo>[];
|
||||||
|
String? _selectedSourceId;
|
||||||
|
bool _loading = true;
|
||||||
|
String? _error;
|
||||||
|
Timer? _poll;
|
||||||
|
|
||||||
|
/// 页面是否可见(被切走后仍保活,但没必要继续请求后端)。
|
||||||
|
bool _visible = true;
|
||||||
|
|
||||||
|
/// 上一次轮询时是否有活跃任务,用来判断「刚刚全部结束」。
|
||||||
|
bool _hadActive = false;
|
||||||
|
|
||||||
|
@override
|
||||||
|
void initState() {
|
||||||
|
super.initState();
|
||||||
|
final presetSources = widget.initialSources;
|
||||||
|
if (presetSources != null) {
|
||||||
|
_sources = presetSources;
|
||||||
|
_index = widget.initialIndex;
|
||||||
|
_jobs = widget.initialJobs ?? const <JobInfo>[];
|
||||||
|
_selectedSourceId = presetSources.isEmpty ? null : presetSources.first.id;
|
||||||
|
_loading = false;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
_load();
|
||||||
|
_schedulePoll(const Duration(seconds: 2));
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
void didChangeDependencies() {
|
||||||
|
super.didChangeDependencies();
|
||||||
|
// TickerMode 由外壳的 Offstage 控制:切到别的页时变 false。
|
||||||
|
_visible = TickerMode.of(context);
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
void dispose() {
|
||||||
|
_poll?.cancel();
|
||||||
|
super.dispose();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 单次 Timer 链:有活跃任务时 1 秒一次,空闲时降到 5 秒,不可见时 10 秒。
|
||||||
|
///
|
||||||
|
/// 以前是 `Timer.periodic(1s)` 且永不停止 —— 只要进过下载页,之后每秒都
|
||||||
|
/// 在请求 `/api/download/jobs`,哪怕没有任何任务、页面也早就切走了。
|
||||||
|
void _schedulePoll(Duration delay) {
|
||||||
|
_poll?.cancel();
|
||||||
|
_poll = Timer(delay, _pollOnce);
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _pollOnce() async {
|
||||||
|
if (!mounted) return;
|
||||||
|
|
||||||
|
if (!_visible) {
|
||||||
|
_schedulePoll(const Duration(seconds: 10));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
_hadActive = _jobs.any((job) => job.isActive);
|
||||||
|
await _refreshJobs();
|
||||||
|
if (!mounted) return;
|
||||||
|
|
||||||
|
final active = _jobs.any((job) => job.isActive);
|
||||||
|
// 活跃 → 空闲:这一轮里下载结束了,首页的模型列表已经过期。
|
||||||
|
if (_hadActive && !active) widget.controller.modelsChanged();
|
||||||
|
_hadActive = active;
|
||||||
|
|
||||||
|
_schedulePoll(Duration(seconds: active ? 1 : 5));
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _load() async {
|
||||||
|
setState(() {
|
||||||
|
_loading = true;
|
||||||
|
_error = null;
|
||||||
|
});
|
||||||
|
try {
|
||||||
|
final sources = await widget.controller.api.sources();
|
||||||
|
final preferred = sources.where((s) => s.enabled).toList();
|
||||||
|
final selected = _selectedSourceId ??
|
||||||
|
(preferred.isNotEmpty
|
||||||
|
? preferred.first.id
|
||||||
|
: (sources.isNotEmpty ? sources.first.id : ''));
|
||||||
|
|
||||||
|
final index = selected.isEmpty
|
||||||
|
? null
|
||||||
|
: await widget.controller.api.remoteModels(sourceId: selected);
|
||||||
|
|
||||||
|
if (!mounted) return;
|
||||||
|
setState(() {
|
||||||
|
_sources = sources;
|
||||||
|
_selectedSourceId = selected;
|
||||||
|
_index = index;
|
||||||
|
_loading = false;
|
||||||
|
});
|
||||||
|
await _refreshJobs();
|
||||||
|
} catch (error) {
|
||||||
|
if (!mounted) return;
|
||||||
|
setState(() {
|
||||||
|
_error = error.toString();
|
||||||
|
_loading = false;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _refreshJobs() async {
|
||||||
|
try {
|
||||||
|
final jobs = await widget.controller.api.jobs();
|
||||||
|
if (!mounted) return;
|
||||||
|
setState(() => _jobs = jobs);
|
||||||
|
} catch (_) {
|
||||||
|
// 轮询失败不打扰用户,下一次再试
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _selectSource(String id) async {
|
||||||
|
setState(() {
|
||||||
|
_selectedSourceId = id;
|
||||||
|
_loading = true;
|
||||||
|
_error = null;
|
||||||
|
});
|
||||||
|
try {
|
||||||
|
final index = await widget.controller.api.remoteModels(sourceId: id);
|
||||||
|
if (!mounted) return;
|
||||||
|
setState(() {
|
||||||
|
_index = index;
|
||||||
|
_loading = false;
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
if (!mounted) return;
|
||||||
|
setState(() {
|
||||||
|
_error = error.toString();
|
||||||
|
_loading = false;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _download(RemoteModelInfo model) async {
|
||||||
|
final sourceId = _selectedSourceId;
|
||||||
|
if (sourceId == null) return;
|
||||||
|
try {
|
||||||
|
await widget.controller.api.startDownload(sourceId, model.id);
|
||||||
|
await _refreshJobs();
|
||||||
|
} catch (error) {
|
||||||
|
if (!mounted) return;
|
||||||
|
setState(() => _error = error.toString());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _jobAction(
|
||||||
|
Future<JobInfo> Function(String id) action, String id) async {
|
||||||
|
try {
|
||||||
|
await action(id);
|
||||||
|
await _refreshJobs();
|
||||||
|
} catch (error) {
|
||||||
|
if (!mounted) return;
|
||||||
|
setState(() => _error = error.toString());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
return Padding(
|
||||||
|
padding: const EdgeInsets.fromLTRB(
|
||||||
|
GcSpace.xxl, GcSpace.xxl, GcSpace.xxl, GcSpace.xl),
|
||||||
|
child: Row(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
|
children: <Widget>[
|
||||||
|
SizedBox(width: 268, child: _sourcePanel()),
|
||||||
|
const SizedBox(width: GcSpace.xl),
|
||||||
|
Expanded(child: _modelPanel()),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Widget _sourcePanel() {
|
||||||
|
return GcCard(
|
||||||
|
padding: const EdgeInsets.all(GcSpace.lg),
|
||||||
|
child: Column(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
|
mainAxisSize: MainAxisSize.min,
|
||||||
|
children: <Widget>[
|
||||||
|
GcSectionTitle(T('dl.sources')),
|
||||||
|
const SizedBox(height: GcSpace.xs + 2),
|
||||||
|
GcHint(T('dl.subtitle')),
|
||||||
|
const SizedBox(height: GcSpace.md),
|
||||||
|
for (final source in _sources)
|
||||||
|
Padding(
|
||||||
|
padding: const EdgeInsets.only(bottom: GcSpace.xs + 2),
|
||||||
|
child: _sourceTile(source),
|
||||||
|
),
|
||||||
|
const SizedBox(height: GcSpace.sm),
|
||||||
|
SizedBox(
|
||||||
|
width: double.infinity,
|
||||||
|
child: OutlinedButton.icon(
|
||||||
|
onPressed: _load,
|
||||||
|
icon: const Icon(Icons.refresh_rounded, size: 18),
|
||||||
|
label: Text(T('dl.refresh')),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Widget _sourceTile(SourceInfo source) {
|
||||||
|
final selected = source.id == _selectedSourceId;
|
||||||
|
return Material(
|
||||||
|
color: selected ? GcColors.accentSoft : Colors.transparent,
|
||||||
|
borderRadius: BorderRadius.circular(GcRadius.control),
|
||||||
|
child: InkWell(
|
||||||
|
borderRadius: BorderRadius.circular(GcRadius.control),
|
||||||
|
hoverColor: GcColors.surfaceAlt,
|
||||||
|
onTap: () => _selectSource(source.id),
|
||||||
|
child: Container(
|
||||||
|
padding: const EdgeInsets.symmetric(
|
||||||
|
horizontal: GcSpace.md,
|
||||||
|
vertical: GcSpace.md - 2,
|
||||||
|
),
|
||||||
|
decoration: BoxDecoration(
|
||||||
|
borderRadius: BorderRadius.circular(GcRadius.control),
|
||||||
|
border: Border.all(
|
||||||
|
color: selected
|
||||||
|
? GcColors.accent.withOpacity(0.45)
|
||||||
|
: Colors.transparent,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
child: Row(
|
||||||
|
children: <Widget>[
|
||||||
|
Icon(
|
||||||
|
selected
|
||||||
|
? Icons.radio_button_checked_rounded
|
||||||
|
: Icons.radio_button_unchecked_rounded,
|
||||||
|
size: 16,
|
||||||
|
color: selected ? GcColors.accent : GcColors.ghost,
|
||||||
|
),
|
||||||
|
const SizedBox(width: GcSpace.sm + 2),
|
||||||
|
Expanded(
|
||||||
|
child: Column(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
|
mainAxisSize: MainAxisSize.min,
|
||||||
|
children: <Widget>[
|
||||||
|
Text(
|
||||||
|
source.name,
|
||||||
|
maxLines: 1,
|
||||||
|
overflow: TextOverflow.ellipsis,
|
||||||
|
style: TextStyle(
|
||||||
|
fontSize: 13,
|
||||||
|
height: 1.35,
|
||||||
|
fontWeight: FontWeight.w600,
|
||||||
|
color: selected ? GcColors.accent : GcColors.ink,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
const SizedBox(height: 1),
|
||||||
|
Text(
|
||||||
|
source.host,
|
||||||
|
maxLines: 1,
|
||||||
|
overflow: TextOverflow.ellipsis,
|
||||||
|
style: TextStyle(
|
||||||
|
fontSize: 11.5,
|
||||||
|
height: 1.35,
|
||||||
|
color: GcColors.faint,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
if (!source.enabled) const GcPill('off', subtle: true),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Widget _modelPanel() {
|
||||||
|
final models = _index?.models ?? const <RemoteModelInfo>[];
|
||||||
|
return Column(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
|
children: <Widget>[
|
||||||
|
GcPageHeader(
|
||||||
|
title: T('dl.available'),
|
||||||
|
subtitle: _index == null
|
||||||
|
? null
|
||||||
|
: (_index!.fromCache
|
||||||
|
? '${T('dl.ready', <Object?>[
|
||||||
|
models.length
|
||||||
|
])} · ${T('dl.fromCache')}'
|
||||||
|
: T('dl.ready', <Object?>[models.length])),
|
||||||
|
trailing: IconButton(
|
||||||
|
tooltip: T('common.refresh'),
|
||||||
|
onPressed: _load,
|
||||||
|
icon: const Icon(Icons.refresh_rounded, size: 18),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
const SizedBox(height: GcSpace.lg),
|
||||||
|
Expanded(
|
||||||
|
child: ListView(
|
||||||
|
padding: const EdgeInsets.only(bottom: GcSpace.sm),
|
||||||
|
children: <Widget>[
|
||||||
|
if (_loading)
|
||||||
|
const Padding(
|
||||||
|
padding: EdgeInsets.symmetric(vertical: 48),
|
||||||
|
child: Center(
|
||||||
|
child: SizedBox(
|
||||||
|
width: 22,
|
||||||
|
height: 22,
|
||||||
|
child: CircularProgressIndicator(strokeWidth: 2),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
else if (_error != null)
|
||||||
|
GcMessage(
|
||||||
|
title: T('common.error'),
|
||||||
|
message: _error,
|
||||||
|
icon: Icons.cloud_off_rounded,
|
||||||
|
color: GcColors.danger,
|
||||||
|
action: OutlinedButton(
|
||||||
|
onPressed: _load,
|
||||||
|
child: Text(T('common.retry')),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
else if (models.isEmpty)
|
||||||
|
GcMessage(
|
||||||
|
title: T('dl.empty'),
|
||||||
|
message: T('dl.emptyHint'),
|
||||||
|
icon: Icons.inbox_rounded,
|
||||||
|
)
|
||||||
|
else
|
||||||
|
for (final model in models)
|
||||||
|
Padding(
|
||||||
|
padding: const EdgeInsets.only(bottom: GcSpace.md),
|
||||||
|
child: _remoteRow(model),
|
||||||
|
),
|
||||||
|
const SizedBox(height: GcSpace.sm),
|
||||||
|
_jobsPanel(),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Widget _remoteRow(RemoteModelInfo model) {
|
||||||
|
return GcCard(
|
||||||
|
padding: const EdgeInsets.fromLTRB(
|
||||||
|
GcSpace.lg,
|
||||||
|
GcSpace.md + 2,
|
||||||
|
GcSpace.lg,
|
||||||
|
GcSpace.md + 2,
|
||||||
|
),
|
||||||
|
child: Row(
|
||||||
|
children: <Widget>[
|
||||||
|
Expanded(
|
||||||
|
child: Column(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
|
children: <Widget>[
|
||||||
|
Row(
|
||||||
|
children: <Widget>[
|
||||||
|
Flexible(
|
||||||
|
child: Text(
|
||||||
|
model.name,
|
||||||
|
maxLines: 1,
|
||||||
|
overflow: TextOverflow.ellipsis,
|
||||||
|
style: TextStyle(
|
||||||
|
fontSize: 14,
|
||||||
|
height: 1.35,
|
||||||
|
fontWeight: FontWeight.w600,
|
||||||
|
color: GcColors.ink,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
const SizedBox(width: GcSpace.sm),
|
||||||
|
Text(
|
||||||
|
'v${model.version} · ${model.sizeText}',
|
||||||
|
style: TextStyle(
|
||||||
|
fontSize: 12,
|
||||||
|
height: 1.35,
|
||||||
|
color: GcColors.faint,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
if (model.installed) ...<Widget>[
|
||||||
|
const SizedBox(width: GcSpace.sm),
|
||||||
|
GcPill(T('dl.installed'), color: GcColors.ok),
|
||||||
|
],
|
||||||
|
],
|
||||||
|
),
|
||||||
|
const SizedBox(height: GcSpace.xs + 1),
|
||||||
|
Text(
|
||||||
|
model.description,
|
||||||
|
maxLines: 2,
|
||||||
|
overflow: TextOverflow.ellipsis,
|
||||||
|
style: TextStyle(
|
||||||
|
fontSize: 12.5,
|
||||||
|
height: 1.5,
|
||||||
|
color: GcColors.muted,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
const SizedBox(width: GcSpace.lg),
|
||||||
|
if (model.installed)
|
||||||
|
OutlinedButton(
|
||||||
|
onPressed: () => _download(model),
|
||||||
|
child: Text(T('dl.reinstall')),
|
||||||
|
)
|
||||||
|
else
|
||||||
|
FilledButton(
|
||||||
|
onPressed: () => _download(model),
|
||||||
|
child: Text(T('dl.download')),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Widget _jobsPanel() {
|
||||||
|
return GcCard(
|
||||||
|
padding: const EdgeInsets.all(GcSpace.lg),
|
||||||
|
child: Column(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
|
children: <Widget>[
|
||||||
|
GcSectionTitle(
|
||||||
|
T('dl.background'),
|
||||||
|
trailing: TextButton(
|
||||||
|
onPressed: () async {
|
||||||
|
try {
|
||||||
|
await widget.controller.api.clearFinished();
|
||||||
|
await _refreshJobs();
|
||||||
|
} catch (_) {
|
||||||
|
// 忽略
|
||||||
|
}
|
||||||
|
},
|
||||||
|
child: Text(T('dl.clearDone')),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
const SizedBox(height: GcSpace.md),
|
||||||
|
if (_jobs.isEmpty)
|
||||||
|
GcHint(T('dl.bgEmpty'))
|
||||||
|
else
|
||||||
|
for (final job in _jobs)
|
||||||
|
Padding(
|
||||||
|
padding: const EdgeInsets.only(bottom: GcSpace.md),
|
||||||
|
child: _jobRow(job),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Widget _jobRow(JobInfo job) {
|
||||||
|
return Column(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
|
children: <Widget>[
|
||||||
|
Row(
|
||||||
|
children: <Widget>[
|
||||||
|
Expanded(
|
||||||
|
child: Text(
|
||||||
|
'${job.name} v${job.version}',
|
||||||
|
maxLines: 1,
|
||||||
|
overflow: TextOverflow.ellipsis,
|
||||||
|
style: TextStyle(
|
||||||
|
fontSize: 13,
|
||||||
|
height: 1.35,
|
||||||
|
fontWeight: FontWeight.w600,
|
||||||
|
color: GcColors.ink,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
GcPill(
|
||||||
|
_stateLabel(job.state),
|
||||||
|
color: job.state == 'Failed'
|
||||||
|
? GcColors.danger
|
||||||
|
: job.state == 'Completed'
|
||||||
|
? GcColors.ok
|
||||||
|
: GcColors.accent,
|
||||||
|
),
|
||||||
|
const SizedBox(width: GcSpace.sm),
|
||||||
|
if (job.isActive)
|
||||||
|
TextButton(
|
||||||
|
onPressed: () =>
|
||||||
|
_jobAction(widget.controller.api.cancelJob, job.id),
|
||||||
|
child: Text(T('dl.cancel')),
|
||||||
|
)
|
||||||
|
else if (job.canRetry)
|
||||||
|
TextButton(
|
||||||
|
onPressed: () =>
|
||||||
|
_jobAction(widget.controller.api.retryJob, job.id),
|
||||||
|
child: Text(T('dl.retry')),
|
||||||
|
)
|
||||||
|
else
|
||||||
|
TextButton(
|
||||||
|
onPressed: () =>
|
||||||
|
_jobAction(widget.controller.api.removeJob, job.id),
|
||||||
|
child: Text(T('dl.removeTask')),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
const SizedBox(height: GcSpace.sm - 2),
|
||||||
|
ClipRRect(
|
||||||
|
borderRadius: BorderRadius.circular(2),
|
||||||
|
child: LinearProgressIndicator(
|
||||||
|
value: job.progress.clamp(0, 1).toDouble(),
|
||||||
|
minHeight: 4,
|
||||||
|
backgroundColor: GcColors.surfaceAlt,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
const SizedBox(height: GcSpace.xs + 1),
|
||||||
|
Text(
|
||||||
|
job.error ?? job.detailText,
|
||||||
|
style: TextStyle(
|
||||||
|
fontSize: 11.5,
|
||||||
|
height: 1.4,
|
||||||
|
color: GcColors.faint,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
String _stateLabel(String state) {
|
||||||
|
switch (state) {
|
||||||
|
case 'Queued':
|
||||||
|
return T('dl.status.queued');
|
||||||
|
case 'Running':
|
||||||
|
case 'Downloading':
|
||||||
|
return T('dl.status.downloading');
|
||||||
|
case 'Completed':
|
||||||
|
return T('dl.status.done');
|
||||||
|
case 'Failed':
|
||||||
|
return T('dl.status.failed');
|
||||||
|
case 'Canceled':
|
||||||
|
return T('dl.status.canceled');
|
||||||
|
default:
|
||||||
|
return state;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,690 @@
|
|||||||
|
import 'dart:async';
|
||||||
|
|
||||||
|
import 'package:flutter/material.dart';
|
||||||
|
|
||||||
|
import '../api_client.dart';
|
||||||
|
import '../controller.dart';
|
||||||
|
import '../i18n.dart';
|
||||||
|
import '../theme.dart';
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// 首页:模型库(从原 pages.dart 拆出,公开类名不变)
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// 首页:模型库
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
class HomePageView extends StatefulWidget {
|
||||||
|
const HomePageView({super.key, required this.controller, this.initialModels});
|
||||||
|
|
||||||
|
final ShellController controller;
|
||||||
|
|
||||||
|
/// 预置模型列表(仅用于测试 / 截图,正常运行时为 null,由后端提供)。
|
||||||
|
final List<ModelInfo>? initialModels;
|
||||||
|
|
||||||
|
@override
|
||||||
|
State<HomePageView> createState() => _HomePageViewState();
|
||||||
|
}
|
||||||
|
|
||||||
|
class _HomePageViewState extends State<HomePageView> {
|
||||||
|
List<ModelInfo> _models = const <ModelInfo>[];
|
||||||
|
bool _loading = true;
|
||||||
|
String? _error;
|
||||||
|
String? _notice;
|
||||||
|
int _lastRevision = 0;
|
||||||
|
|
||||||
|
@override
|
||||||
|
void initState() {
|
||||||
|
super.initState();
|
||||||
|
widget.controller.addListener(_onControllerChanged);
|
||||||
|
_lastRevision = widget.controller.modelsRevision;
|
||||||
|
|
||||||
|
final preset = widget.initialModels;
|
||||||
|
if (preset != null) {
|
||||||
|
_models = preset;
|
||||||
|
_loading = false;
|
||||||
|
} else {
|
||||||
|
_load();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
void dispose() {
|
||||||
|
widget.controller.removeListener(_onControllerChanged);
|
||||||
|
super.dispose();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 下载完成 / 删除模型后重新拉列表:页面被 Offstage 保活,不会自己重建。
|
||||||
|
void _onControllerChanged() {
|
||||||
|
if (!mounted) return;
|
||||||
|
final revision = widget.controller.modelsRevision;
|
||||||
|
if (revision == _lastRevision) return;
|
||||||
|
_lastRevision = revision;
|
||||||
|
if (widget.initialModels != null) return; // 截图 / 测试用的预置数据
|
||||||
|
_load();
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _load() async {
|
||||||
|
setState(() {
|
||||||
|
_loading = true;
|
||||||
|
_error = null;
|
||||||
|
});
|
||||||
|
try {
|
||||||
|
final models = await widget.controller.api.models();
|
||||||
|
if (!mounted) return;
|
||||||
|
setState(() {
|
||||||
|
_models = models;
|
||||||
|
_loading = false;
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
if (!mounted) return;
|
||||||
|
setState(() {
|
||||||
|
_error = error.toString();
|
||||||
|
_loading = false;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _launch(ModelInfo model) async {
|
||||||
|
setState(() => _notice = null);
|
||||||
|
try {
|
||||||
|
final result = await widget.controller.api.launchModel(model.id);
|
||||||
|
if (!mounted) return;
|
||||||
|
setState(() => _notice = result.message);
|
||||||
|
} catch (error) {
|
||||||
|
if (!mounted) return;
|
||||||
|
setState(() => _notice = error.toString());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _delete(ModelInfo model) async {
|
||||||
|
final confirmed = await showDialog<bool>(
|
||||||
|
context: context,
|
||||||
|
builder: (context) => AlertDialog(
|
||||||
|
backgroundColor: GcColors.surface,
|
||||||
|
title: Text(T('common.confirmTitle')),
|
||||||
|
content: Text(T('home.deleteConfirm', <Object?>[model.name])),
|
||||||
|
actions: <Widget>[
|
||||||
|
TextButton(
|
||||||
|
onPressed: () => Navigator.of(context).pop(false),
|
||||||
|
child: Text(T('common.cancel')),
|
||||||
|
),
|
||||||
|
FilledButton(
|
||||||
|
onPressed: () => Navigator.of(context).pop(true),
|
||||||
|
child: Text(T('common.delete')),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
);
|
||||||
|
if (confirmed != true) return;
|
||||||
|
|
||||||
|
try {
|
||||||
|
await widget.controller.api.deleteModel(model.id);
|
||||||
|
await _load();
|
||||||
|
} catch (error) {
|
||||||
|
if (!mounted) return;
|
||||||
|
setState(() => _notice = error.toString());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _openFolder(String path) async {
|
||||||
|
try {
|
||||||
|
await widget.controller.api.openFolder(path);
|
||||||
|
} catch (error) {
|
||||||
|
if (!mounted) return;
|
||||||
|
setState(() => _notice = error.toString());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
final settings = widget.controller.settings;
|
||||||
|
return RefreshIndicator(
|
||||||
|
onRefresh: _load,
|
||||||
|
color: GcColors.accent,
|
||||||
|
backgroundColor: GcColors.surface,
|
||||||
|
child: ListView(
|
||||||
|
physics: const AlwaysScrollableScrollPhysics(),
|
||||||
|
padding: const EdgeInsets.fromLTRB(
|
||||||
|
GcSpace.xxl, GcSpace.xxl, GcSpace.xxl, GcSpace.xxxl),
|
||||||
|
children: <Widget>[
|
||||||
|
_hero(settings),
|
||||||
|
const SizedBox(height: GcSpace.xxl),
|
||||||
|
_sectionHeader(),
|
||||||
|
if (_notice != null) ...<Widget>[
|
||||||
|
const SizedBox(height: GcSpace.md),
|
||||||
|
GcMessage(
|
||||||
|
title: _notice!,
|
||||||
|
icon: Icons.info_outline_rounded,
|
||||||
|
color: GcColors.warn,
|
||||||
|
),
|
||||||
|
],
|
||||||
|
const SizedBox(height: GcSpace.lg),
|
||||||
|
if (_loading)
|
||||||
|
const Padding(
|
||||||
|
padding: EdgeInsets.symmetric(vertical: 48),
|
||||||
|
child: Center(
|
||||||
|
child: SizedBox(
|
||||||
|
width: 22,
|
||||||
|
height: 22,
|
||||||
|
child: CircularProgressIndicator(strokeWidth: 2),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
else if (_error != null)
|
||||||
|
GcMessage(
|
||||||
|
title: T('common.error'),
|
||||||
|
message: _error,
|
||||||
|
icon: Icons.cloud_off_rounded,
|
||||||
|
color: GcColors.danger,
|
||||||
|
action: OutlinedButton(
|
||||||
|
onPressed: _load,
|
||||||
|
child: Text(T('common.retry')),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
else if (_models.isEmpty)
|
||||||
|
_emptyState()
|
||||||
|
else
|
||||||
|
LayoutBuilder(
|
||||||
|
builder: (context, constraints) {
|
||||||
|
const spacing = GcSpace.lg;
|
||||||
|
final columns =
|
||||||
|
(constraints.maxWidth / 320).floor().clamp(1, 4);
|
||||||
|
final cardWidth =
|
||||||
|
(constraints.maxWidth - spacing * (columns - 1)) / columns;
|
||||||
|
return Wrap(
|
||||||
|
spacing: spacing,
|
||||||
|
runSpacing: spacing,
|
||||||
|
children: <Widget>[
|
||||||
|
for (final model in _models)
|
||||||
|
SizedBox(
|
||||||
|
width: cardWidth,
|
||||||
|
child: _ModelCard(
|
||||||
|
model: model,
|
||||||
|
previewUrl: widget.controller.api.previewUrl(model),
|
||||||
|
onLaunch: () => _launch(model),
|
||||||
|
onOpenFolder: () => _openFolder(model.directory),
|
||||||
|
onDelete: () => _delete(model),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
},
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 顶部横幅:产品定位 + 主操作 + 关键指标。
|
||||||
|
///
|
||||||
|
/// 不用渐变:深色主题下的低对比渐变会让整块区域发灰,看起来就是「糊」。
|
||||||
|
Widget _hero(SettingsInfo? settings) {
|
||||||
|
final enabledSources =
|
||||||
|
settings?.sources.where((s) => s.enabled).length ?? 0;
|
||||||
|
return GcCard(
|
||||||
|
padding: const EdgeInsets.all(GcSpace.xxl + 2),
|
||||||
|
child: Row(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
|
children: <Widget>[
|
||||||
|
Expanded(
|
||||||
|
child: Column(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
|
children: <Widget>[
|
||||||
|
Text(
|
||||||
|
'MODEL LIBRARY',
|
||||||
|
style: TextStyle(
|
||||||
|
fontSize: 11,
|
||||||
|
height: 1.2,
|
||||||
|
letterSpacing: 1.4,
|
||||||
|
fontWeight: FontWeight.w600,
|
||||||
|
color: GcColors.accent,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
const SizedBox(height: GcSpace.md),
|
||||||
|
Text(
|
||||||
|
T('home.title'),
|
||||||
|
style: TextStyle(
|
||||||
|
fontSize: 26,
|
||||||
|
height: 1.25,
|
||||||
|
fontWeight: FontWeight.w600,
|
||||||
|
letterSpacing: -0.2,
|
||||||
|
color: GcColors.ink,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
const SizedBox(height: GcSpace.sm),
|
||||||
|
ConstrainedBox(
|
||||||
|
constraints: const BoxConstraints(maxWidth: 460),
|
||||||
|
child: Text(
|
||||||
|
T('home.subtitle'),
|
||||||
|
style: TextStyle(
|
||||||
|
fontSize: 13,
|
||||||
|
height: 1.65,
|
||||||
|
color: GcColors.muted,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
const SizedBox(height: GcSpace.xl),
|
||||||
|
Row(
|
||||||
|
children: <Widget>[
|
||||||
|
FilledButton.icon(
|
||||||
|
onPressed:
|
||||||
|
_models.isEmpty ? null : () => _launch(_models.first),
|
||||||
|
icon: const Icon(Icons.play_arrow_rounded, size: 18),
|
||||||
|
label: Text(T('home.launch')),
|
||||||
|
),
|
||||||
|
const SizedBox(width: GcSpace.md),
|
||||||
|
OutlinedButton(
|
||||||
|
onPressed: () => widget.controller.goTo(1),
|
||||||
|
child: Text(T('home.download')),
|
||||||
|
),
|
||||||
|
const SizedBox(width: GcSpace.xs),
|
||||||
|
TextButton(
|
||||||
|
onPressed: () => widget.controller.goTo(2),
|
||||||
|
child: Text(T('home.settings')),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
const SizedBox(height: GcSpace.md),
|
||||||
|
Text(
|
||||||
|
T('home.launchHint'),
|
||||||
|
style: TextStyle(
|
||||||
|
fontSize: 12,
|
||||||
|
height: 1.55,
|
||||||
|
color: GcColors.faint,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
const SizedBox(width: GcSpace.xxl),
|
||||||
|
Container(
|
||||||
|
padding: const EdgeInsets.symmetric(
|
||||||
|
horizontal: GcSpace.xl,
|
||||||
|
vertical: GcSpace.lg,
|
||||||
|
),
|
||||||
|
decoration: BoxDecoration(
|
||||||
|
color: GcColors.surfaceAlt,
|
||||||
|
borderRadius: BorderRadius.circular(GcRadius.control),
|
||||||
|
border: Border.all(color: GcColors.line),
|
||||||
|
),
|
||||||
|
child: Row(
|
||||||
|
mainAxisSize: MainAxisSize.min,
|
||||||
|
children: <Widget>[
|
||||||
|
GcMetric(
|
||||||
|
value: '${_models.length}',
|
||||||
|
label: T('home.stats.models'),
|
||||||
|
),
|
||||||
|
_metricDivider(),
|
||||||
|
GcMetric(
|
||||||
|
value: '$enabledSources',
|
||||||
|
label: T('home.stats.sources'),
|
||||||
|
),
|
||||||
|
_metricDivider(),
|
||||||
|
GcMetric(
|
||||||
|
value: '${settings?.memoryBudgetMb ?? 0}',
|
||||||
|
label: T('home.stats.memory'),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Widget _metricDivider() {
|
||||||
|
return Container(
|
||||||
|
width: 1,
|
||||||
|
height: 34,
|
||||||
|
margin: const EdgeInsets.symmetric(horizontal: GcSpace.xl),
|
||||||
|
color: GcColors.line,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Widget _sectionHeader() {
|
||||||
|
return Row(
|
||||||
|
children: <Widget>[
|
||||||
|
Text(
|
||||||
|
T('home.installed'),
|
||||||
|
style: TextStyle(
|
||||||
|
fontSize: 16,
|
||||||
|
height: 1.4,
|
||||||
|
fontWeight: FontWeight.w600,
|
||||||
|
color: GcColors.ink,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
const SizedBox(width: GcSpace.sm),
|
||||||
|
GcPill(T('home.count', <Object?>[_models.length]), subtle: true),
|
||||||
|
const Spacer(),
|
||||||
|
IconButton(
|
||||||
|
tooltip: T('common.refresh'),
|
||||||
|
onPressed: _load,
|
||||||
|
icon: const Icon(Icons.refresh_rounded, size: 18),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Widget _emptyState() {
|
||||||
|
return GcCard(
|
||||||
|
padding: const EdgeInsets.symmetric(
|
||||||
|
horizontal: GcSpace.xxxl,
|
||||||
|
vertical: 40,
|
||||||
|
),
|
||||||
|
child: Column(
|
||||||
|
children: <Widget>[
|
||||||
|
Container(
|
||||||
|
width: 52,
|
||||||
|
height: 52,
|
||||||
|
alignment: Alignment.center,
|
||||||
|
decoration: BoxDecoration(
|
||||||
|
color: GcColors.accentSoft,
|
||||||
|
borderRadius: BorderRadius.circular(GcRadius.panel),
|
||||||
|
),
|
||||||
|
child: Icon(
|
||||||
|
Icons.travel_explore_rounded,
|
||||||
|
size: 26,
|
||||||
|
color: GcColors.accent,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
const SizedBox(height: GcSpace.lg),
|
||||||
|
Text(
|
||||||
|
T('home.empty'),
|
||||||
|
style: TextStyle(
|
||||||
|
fontSize: 16,
|
||||||
|
height: 1.4,
|
||||||
|
fontWeight: FontWeight.w600,
|
||||||
|
color: GcColors.ink,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
const SizedBox(height: GcSpace.sm),
|
||||||
|
ConstrainedBox(
|
||||||
|
constraints: const BoxConstraints(maxWidth: 420),
|
||||||
|
child: Text(
|
||||||
|
T('home.emptyHint'),
|
||||||
|
textAlign: TextAlign.center,
|
||||||
|
style: TextStyle(
|
||||||
|
fontSize: 12.5,
|
||||||
|
height: 1.7,
|
||||||
|
color: GcColors.muted,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
const SizedBox(height: GcSpace.xl),
|
||||||
|
FilledButton(
|
||||||
|
onPressed: () => widget.controller.goTo(1),
|
||||||
|
child: Text(T('home.emptyAction')),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class _ModelCard extends StatefulWidget {
|
||||||
|
const _ModelCard({
|
||||||
|
required this.model,
|
||||||
|
required this.previewUrl,
|
||||||
|
required this.onLaunch,
|
||||||
|
required this.onOpenFolder,
|
||||||
|
required this.onDelete,
|
||||||
|
});
|
||||||
|
|
||||||
|
final ModelInfo model;
|
||||||
|
final String previewUrl;
|
||||||
|
final VoidCallback onLaunch;
|
||||||
|
final VoidCallback onOpenFolder;
|
||||||
|
final VoidCallback onDelete;
|
||||||
|
|
||||||
|
@override
|
||||||
|
State<_ModelCard> createState() => _ModelCardState();
|
||||||
|
}
|
||||||
|
|
||||||
|
class _ModelCardState extends State<_ModelCard> {
|
||||||
|
bool _hover = false;
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
final model = widget.model;
|
||||||
|
return MouseRegion(
|
||||||
|
onEnter: (_) => setState(() => _hover = true),
|
||||||
|
onExit: (_) => setState(() => _hover = false),
|
||||||
|
cursor: SystemMouseCursors.click,
|
||||||
|
child: GcCard(
|
||||||
|
padding: EdgeInsets.zero,
|
||||||
|
clip: true,
|
||||||
|
borderColor: _hover ? GcColors.lineStrong : GcColors.line,
|
||||||
|
child: Column(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
|
children: <Widget>[
|
||||||
|
_cover(model),
|
||||||
|
Padding(
|
||||||
|
padding: const EdgeInsets.fromLTRB(
|
||||||
|
GcSpace.lg,
|
||||||
|
GcSpace.md + 2,
|
||||||
|
GcSpace.lg,
|
||||||
|
GcSpace.md,
|
||||||
|
),
|
||||||
|
child: Column(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
|
children: <Widget>[
|
||||||
|
Row(
|
||||||
|
children: <Widget>[
|
||||||
|
Expanded(
|
||||||
|
child: Text(
|
||||||
|
model.name,
|
||||||
|
maxLines: 1,
|
||||||
|
overflow: TextOverflow.ellipsis,
|
||||||
|
style: TextStyle(
|
||||||
|
fontSize: 14.5,
|
||||||
|
height: 1.35,
|
||||||
|
fontWeight: FontWeight.w600,
|
||||||
|
color: GcColors.ink,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
const SizedBox(width: GcSpace.sm),
|
||||||
|
Text(
|
||||||
|
model.sizeText,
|
||||||
|
style: TextStyle(
|
||||||
|
fontSize: 12,
|
||||||
|
height: 1.35,
|
||||||
|
color: GcColors.faint,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
const SizedBox(height: GcSpace.sm - 2),
|
||||||
|
SizedBox(
|
||||||
|
height: 36,
|
||||||
|
child: Text(
|
||||||
|
model.description.isEmpty
|
||||||
|
? T('home.noDescription')
|
||||||
|
: model.description,
|
||||||
|
maxLines: 2,
|
||||||
|
overflow: TextOverflow.ellipsis,
|
||||||
|
style: TextStyle(
|
||||||
|
fontSize: 12.5,
|
||||||
|
height: 1.45,
|
||||||
|
color: model.description.isEmpty
|
||||||
|
? GcColors.faint
|
||||||
|
: GcColors.muted,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
if (model.tags.isNotEmpty) ...<Widget>[
|
||||||
|
const SizedBox(height: GcSpace.sm + 2),
|
||||||
|
SizedBox(
|
||||||
|
height: 20,
|
||||||
|
child: Wrap(
|
||||||
|
spacing: 6,
|
||||||
|
runSpacing: 6,
|
||||||
|
children: <Widget>[
|
||||||
|
for (final tag in model.tags.take(3))
|
||||||
|
GcPill(tag, subtle: true),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
const SizedBox(height: GcSpace.md + 2),
|
||||||
|
Row(
|
||||||
|
children: <Widget>[
|
||||||
|
FilledButton.icon(
|
||||||
|
onPressed: widget.onLaunch,
|
||||||
|
icon: const Icon(Icons.play_arrow_rounded, size: 18),
|
||||||
|
label: Text(T('home.launch')),
|
||||||
|
),
|
||||||
|
const Spacer(),
|
||||||
|
IconButton(
|
||||||
|
tooltip: T('home.open'),
|
||||||
|
onPressed: widget.onOpenFolder,
|
||||||
|
icon: const Icon(Icons.folder_open_rounded, size: 18),
|
||||||
|
),
|
||||||
|
IconButton(
|
||||||
|
tooltip: T('home.delete'),
|
||||||
|
onPressed: widget.onDelete,
|
||||||
|
icon:
|
||||||
|
const Icon(Icons.delete_outline_rounded, size: 18),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 封面:按卡片宽度和屏幕像素比解码,避免被放大后发虚。
|
||||||
|
Widget _cover(ModelInfo model) {
|
||||||
|
final dpr = MediaQuery.devicePixelRatioOf(context);
|
||||||
|
final decodeWidth =
|
||||||
|
(MediaQuery.sizeOf(context).width * dpr).clamp(320, 900).round();
|
||||||
|
return SizedBox(
|
||||||
|
height: 156,
|
||||||
|
width: double.infinity,
|
||||||
|
child: Stack(
|
||||||
|
fit: StackFit.expand,
|
||||||
|
children: <Widget>[
|
||||||
|
_PreviewFallback(model: model),
|
||||||
|
if (model.hasPreview)
|
||||||
|
Image.network(
|
||||||
|
widget.previewUrl,
|
||||||
|
fit: BoxFit.cover,
|
||||||
|
cacheWidth: decodeWidth,
|
||||||
|
filterQuality: FilterQuality.medium,
|
||||||
|
gaplessPlayback: true,
|
||||||
|
errorBuilder: (context, error, stack) => const SizedBox.shrink(),
|
||||||
|
),
|
||||||
|
DecoratedBox(
|
||||||
|
decoration: BoxDecoration(
|
||||||
|
// 只用「透明 → 深色」的遮罩,别用 alphaBlend:叠加不透明底色
|
||||||
|
// 会把整张封面盖平,占位字母也跟着消失。
|
||||||
|
gradient: LinearGradient(
|
||||||
|
begin: Alignment.topCenter,
|
||||||
|
end: Alignment.bottomCenter,
|
||||||
|
colors: <Color>[
|
||||||
|
GcColors.appBg.withOpacity(0.0),
|
||||||
|
GcColors.appBg.withOpacity(0.32),
|
||||||
|
GcColors.appBg.withOpacity(0.88),
|
||||||
|
],
|
||||||
|
stops: const <double>[0.42, 0.72, 1.0],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
Positioned(
|
||||||
|
left: GcSpace.md,
|
||||||
|
right: GcSpace.sm,
|
||||||
|
bottom: GcSpace.sm,
|
||||||
|
child: Row(
|
||||||
|
children: <Widget>[
|
||||||
|
if (model.version.isNotEmpty)
|
||||||
|
GcPill('v${model.version}', color: GcColors.accent),
|
||||||
|
if (model.author.isNotEmpty) ...<Widget>[
|
||||||
|
const SizedBox(width: GcSpace.sm),
|
||||||
|
Flexible(
|
||||||
|
child: Text(
|
||||||
|
model.author,
|
||||||
|
maxLines: 1,
|
||||||
|
overflow: TextOverflow.ellipsis,
|
||||||
|
style: TextStyle(
|
||||||
|
fontSize: 11.5,
|
||||||
|
height: 1.3,
|
||||||
|
color: GcColors.muted,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
const Spacer(),
|
||||||
|
AnimatedOpacity(
|
||||||
|
opacity: _hover ? 1 : 0,
|
||||||
|
duration: const Duration(milliseconds: 140),
|
||||||
|
child: Container(
|
||||||
|
width: 26,
|
||||||
|
height: 26,
|
||||||
|
decoration: BoxDecoration(
|
||||||
|
color: GcColors.accentFill,
|
||||||
|
shape: BoxShape.circle,
|
||||||
|
),
|
||||||
|
child: Icon(
|
||||||
|
Icons.play_arrow_rounded,
|
||||||
|
size: 18,
|
||||||
|
color: GcColors.onAccent,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 没有封面时的占位:型号首字 + 淡淡的网格感,比一个大「◎」更像封面。
|
||||||
|
class _PreviewFallback extends StatelessWidget {
|
||||||
|
const _PreviewFallback({this.model});
|
||||||
|
|
||||||
|
final ModelInfo? model;
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
final label = (model?.name ?? '').characters.isEmpty
|
||||||
|
? '◎'
|
||||||
|
: model!.name.characters.first;
|
||||||
|
return DecoratedBox(
|
||||||
|
decoration: BoxDecoration(
|
||||||
|
gradient: LinearGradient(
|
||||||
|
begin: Alignment.topLeft,
|
||||||
|
end: Alignment.bottomRight,
|
||||||
|
colors: <Color>[
|
||||||
|
Color.alphaBlend(
|
||||||
|
GcColors.accent.withOpacity(0.22),
|
||||||
|
GcColors.surfaceAlt,
|
||||||
|
),
|
||||||
|
GcColors.surfaceAlt,
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
child: Center(
|
||||||
|
child: Text(
|
||||||
|
label,
|
||||||
|
style: TextStyle(
|
||||||
|
fontSize: 46,
|
||||||
|
height: 1.0,
|
||||||
|
fontWeight: FontWeight.w600,
|
||||||
|
color: Color.alphaBlend(
|
||||||
|
GcColors.accent.withOpacity(0.55),
|
||||||
|
GcColors.surfaceAlt,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,699 @@
|
|||||||
|
import 'dart:async';
|
||||||
|
|
||||||
|
import 'package:flutter/material.dart';
|
||||||
|
|
||||||
|
import '../api_client.dart';
|
||||||
|
import '../controller.dart';
|
||||||
|
import '../i18n.dart';
|
||||||
|
import '../theme.dart';
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// 设置页(从原 pages.dart 拆出,公开类名不变)
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// 设置页
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
class SettingsPageView extends StatefulWidget {
|
||||||
|
const SettingsPageView({super.key, required this.controller});
|
||||||
|
|
||||||
|
final ShellController controller;
|
||||||
|
|
||||||
|
@override
|
||||||
|
State<SettingsPageView> createState() => _SettingsPageViewState();
|
||||||
|
}
|
||||||
|
|
||||||
|
class _SettingsPageViewState extends State<SettingsPageView> {
|
||||||
|
double _memory = 2048;
|
||||||
|
bool _memoryAuto = true;
|
||||||
|
int _fps = 120;
|
||||||
|
bool _autoUpdate = true;
|
||||||
|
String _language = 'auto';
|
||||||
|
ThemeMode _themeMode = ThemeMode.dark;
|
||||||
|
|
||||||
|
/// 上一次同步所用的设置对象。以前用的是 `bool _synced` —— 只同步一次,
|
||||||
|
/// 之后外部(更新状态条、其它页面)改了设置,本页仍显示旧值。
|
||||||
|
SettingsInfo? _syncedFrom;
|
||||||
|
String? _status;
|
||||||
|
|
||||||
|
@override
|
||||||
|
void initState() {
|
||||||
|
super.initState();
|
||||||
|
widget.controller.reloadSettings();
|
||||||
|
}
|
||||||
|
|
||||||
|
void _syncFrom(SettingsInfo settings) {
|
||||||
|
if (identical(_syncedFrom, settings)) return;
|
||||||
|
_syncedFrom = settings;
|
||||||
|
_memory = settings.memoryMb.toDouble();
|
||||||
|
_memoryAuto = settings.memoryAuto;
|
||||||
|
_fps = settings.renderFps;
|
||||||
|
_autoUpdate = settings.autoUpdateOnStartup;
|
||||||
|
_language = settings.language;
|
||||||
|
_themeMode = GcPalette.parseMode(settings.theme);
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
final settings = widget.controller.settings;
|
||||||
|
if (settings == null) {
|
||||||
|
return const Center(
|
||||||
|
child: SizedBox(
|
||||||
|
width: 22,
|
||||||
|
height: 22,
|
||||||
|
child: CircularProgressIndicator(strokeWidth: 2),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
_syncFrom(settings);
|
||||||
|
|
||||||
|
return LayoutBuilder(
|
||||||
|
builder: (context, constraints) {
|
||||||
|
final twoColumns = constraints.maxWidth >= 960;
|
||||||
|
final cards = <Widget>[
|
||||||
|
_generalCard(settings),
|
||||||
|
_appearanceCard(settings),
|
||||||
|
_memoryCard(settings),
|
||||||
|
_sourcesCard(settings),
|
||||||
|
_storageCard(settings),
|
||||||
|
_updateCard(settings),
|
||||||
|
_backendCard(settings),
|
||||||
|
];
|
||||||
|
|
||||||
|
Widget column(List<Widget> items) => Column(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||||
|
children: <Widget>[
|
||||||
|
for (var i = 0; i < items.length; i++) ...<Widget>[
|
||||||
|
if (i > 0) const SizedBox(height: GcSpace.lg),
|
||||||
|
items[i],
|
||||||
|
],
|
||||||
|
],
|
||||||
|
);
|
||||||
|
|
||||||
|
final left = <Widget>[];
|
||||||
|
final right = <Widget>[];
|
||||||
|
for (var i = 0; i < cards.length; i++) {
|
||||||
|
if (twoColumns && i.isOdd) {
|
||||||
|
right.add(cards[i]);
|
||||||
|
} else {
|
||||||
|
left.add(cards[i]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return SingleChildScrollView(
|
||||||
|
padding: const EdgeInsets.fromLTRB(
|
||||||
|
GcSpace.xxl,
|
||||||
|
GcSpace.xxl,
|
||||||
|
GcSpace.xxl,
|
||||||
|
GcSpace.xxxl,
|
||||||
|
),
|
||||||
|
child: Column(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||||
|
children: <Widget>[
|
||||||
|
GcPageHeader(
|
||||||
|
title: T('set.title'),
|
||||||
|
subtitle: T('set.subtitle'),
|
||||||
|
trailing: _status == null
|
||||||
|
? null
|
||||||
|
: GcPill(
|
||||||
|
_status!,
|
||||||
|
color: GcColors.ok,
|
||||||
|
icon: Icons.check_rounded,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
const SizedBox(height: GcSpace.xxl),
|
||||||
|
if (twoColumns)
|
||||||
|
Row(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
|
children: <Widget>[
|
||||||
|
Expanded(child: column(left)),
|
||||||
|
const SizedBox(width: GcSpace.lg),
|
||||||
|
Expanded(child: column(right)),
|
||||||
|
],
|
||||||
|
)
|
||||||
|
else
|
||||||
|
column(cards),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Widget _label(String text) {
|
||||||
|
return Text(
|
||||||
|
text,
|
||||||
|
style: TextStyle(fontSize: 13, height: 1.5, color: GcColors.muted),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Widget _cardRow(String label, Widget control) {
|
||||||
|
return Padding(
|
||||||
|
padding: const EdgeInsets.symmetric(vertical: GcSpace.sm),
|
||||||
|
child: Row(
|
||||||
|
children: <Widget>[
|
||||||
|
SizedBox(width: 124, child: _label(label)),
|
||||||
|
Expanded(child: control),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Widget _generalCard(SettingsInfo settings) {
|
||||||
|
return GcCard(
|
||||||
|
child: Column(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
|
children: <Widget>[
|
||||||
|
GcSectionTitle(T('set.general')),
|
||||||
|
const SizedBox(height: GcSpace.lg),
|
||||||
|
_cardRow(
|
||||||
|
T('set.language'),
|
||||||
|
Align(
|
||||||
|
alignment: Alignment.centerLeft,
|
||||||
|
child: DropdownButton<String>(
|
||||||
|
value: _language,
|
||||||
|
dropdownColor: GcColors.surfaceAlt,
|
||||||
|
underline: const SizedBox.shrink(),
|
||||||
|
borderRadius: BorderRadius.circular(GcRadius.control),
|
||||||
|
// 从主题样式派生,才能继承字体族(自建 TextStyle 会丢掉
|
||||||
|
// fontFamily,中文就回退成系统兜底字体)。
|
||||||
|
style: Theme.of(context).textTheme.bodyLarge!.copyWith(
|
||||||
|
fontSize: 13,
|
||||||
|
height: 1.4,
|
||||||
|
fontWeight: FontWeight.w400,
|
||||||
|
color: GcColors.ink,
|
||||||
|
),
|
||||||
|
items: <DropdownMenuItem<String>>[
|
||||||
|
DropdownMenuItem<String>(
|
||||||
|
value: 'auto',
|
||||||
|
child: Text(T('set.language.auto')),
|
||||||
|
),
|
||||||
|
for (final language in settings.languages)
|
||||||
|
DropdownMenuItem<String>(
|
||||||
|
value: language.code,
|
||||||
|
child: Text(language.label),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
onChanged: (value) async {
|
||||||
|
if (value == null) return;
|
||||||
|
setState(() => _language = value);
|
||||||
|
await widget.controller
|
||||||
|
.saveSettings(SettingsPatch(language: value));
|
||||||
|
},
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
_cardRow(
|
||||||
|
T('set.fps'),
|
||||||
|
Row(
|
||||||
|
children: <Widget>[
|
||||||
|
Expanded(
|
||||||
|
child: Slider(
|
||||||
|
value: _fps.toDouble(),
|
||||||
|
min: 24,
|
||||||
|
max: 120,
|
||||||
|
divisions: 4,
|
||||||
|
label: '$_fps',
|
||||||
|
onChanged: (value) => setState(() => _fps = value.round()),
|
||||||
|
onChangeEnd: (value) async {
|
||||||
|
await widget.controller.saveSettings(
|
||||||
|
SettingsPatch(renderFps: value.round()));
|
||||||
|
if (mounted) {
|
||||||
|
setState(() => _status = T('common.applied'));
|
||||||
|
}
|
||||||
|
},
|
||||||
|
),
|
||||||
|
),
|
||||||
|
SizedBox(
|
||||||
|
width: 48,
|
||||||
|
child: Text(
|
||||||
|
'$_fps',
|
||||||
|
textAlign: TextAlign.end,
|
||||||
|
style: TextStyle(
|
||||||
|
fontSize: 13,
|
||||||
|
height: 1.4,
|
||||||
|
fontWeight: FontWeight.w600,
|
||||||
|
color: GcColors.ink,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
GcHint(T('set.fps.desc')),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Widget _appearanceCard(SettingsInfo settings) {
|
||||||
|
final current =
|
||||||
|
GcPalette.parseHex(settings.accentColor) ?? GcPalette.defaultAccent;
|
||||||
|
return GcCard(
|
||||||
|
child: Column(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
|
children: <Widget>[
|
||||||
|
GcSectionTitle(T('set.appearance')),
|
||||||
|
const SizedBox(height: GcSpace.md),
|
||||||
|
GcHint(T('set.theme.desc')),
|
||||||
|
const SizedBox(height: GcSpace.md),
|
||||||
|
SegmentedButton<ThemeMode>(
|
||||||
|
segments: <ButtonSegment<ThemeMode>>[
|
||||||
|
ButtonSegment<ThemeMode>(
|
||||||
|
value: ThemeMode.dark,
|
||||||
|
label: Text(T('set.theme.dark')),
|
||||||
|
icon: const Icon(Icons.dark_mode_outlined, size: 16),
|
||||||
|
),
|
||||||
|
ButtonSegment<ThemeMode>(
|
||||||
|
value: ThemeMode.light,
|
||||||
|
label: Text(T('set.theme.light')),
|
||||||
|
icon: const Icon(Icons.light_mode_outlined, size: 16),
|
||||||
|
),
|
||||||
|
ButtonSegment<ThemeMode>(
|
||||||
|
value: ThemeMode.system,
|
||||||
|
label: Text(T('set.theme.system')),
|
||||||
|
icon: const Icon(Icons.brightness_auto_outlined, size: 16),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
selected: <ThemeMode>{_themeMode},
|
||||||
|
showSelectedIcon: false,
|
||||||
|
onSelectionChanged: (selection) async {
|
||||||
|
final mode = selection.first;
|
||||||
|
setState(() => _themeMode = mode);
|
||||||
|
GcPalette.mode.value = mode; // 立即预览
|
||||||
|
await widget.controller.saveSettings(
|
||||||
|
SettingsPatch(theme: GcPalette.modeToName(mode)));
|
||||||
|
if (mounted) setState(() => _status = T('common.applied'));
|
||||||
|
},
|
||||||
|
),
|
||||||
|
const SizedBox(height: GcSpace.xl),
|
||||||
|
GcHint(T('set.accent.desc')),
|
||||||
|
const SizedBox(height: GcSpace.md + 2),
|
||||||
|
Wrap(
|
||||||
|
spacing: GcSpace.sm + 2,
|
||||||
|
runSpacing: GcSpace.sm + 2,
|
||||||
|
children: <Widget>[
|
||||||
|
for (final color in GcPalette.presets)
|
||||||
|
_accentSwatch(color, current),
|
||||||
|
_customAccentChip(),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
const SizedBox(height: GcSpace.md),
|
||||||
|
Text(
|
||||||
|
'${T('set.accent')}: ${GcPalette.toHex(current)}',
|
||||||
|
style: TextStyle(
|
||||||
|
fontSize: 11.5,
|
||||||
|
height: 1.4,
|
||||||
|
color: GcColors.faint,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Widget _accentSwatch(Color color, Color current) {
|
||||||
|
final selected = color.value == current.value;
|
||||||
|
return Tooltip(
|
||||||
|
message: GcPalette.toHex(color),
|
||||||
|
child: GestureDetector(
|
||||||
|
onTap: () => _applyAccent(GcPalette.toHex(color)),
|
||||||
|
child: Container(
|
||||||
|
width: 34,
|
||||||
|
height: 34,
|
||||||
|
decoration: BoxDecoration(
|
||||||
|
color: color,
|
||||||
|
borderRadius: BorderRadius.circular(GcRadius.control),
|
||||||
|
border: Border.all(
|
||||||
|
color: selected ? GcColors.ink : Colors.transparent,
|
||||||
|
width: 2,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
child: selected
|
||||||
|
? Icon(
|
||||||
|
Icons.check_rounded,
|
||||||
|
size: 18,
|
||||||
|
color: color.computeLuminance() > 0.42
|
||||||
|
? const Color(0xFF0A1226)
|
||||||
|
: Colors.white,
|
||||||
|
)
|
||||||
|
: null,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Widget _customAccentChip() {
|
||||||
|
return MouseRegion(
|
||||||
|
cursor: SystemMouseCursors.click,
|
||||||
|
child: GestureDetector(
|
||||||
|
onTap: _pickCustomAccent,
|
||||||
|
child: Container(
|
||||||
|
height: 34,
|
||||||
|
padding: const EdgeInsets.symmetric(horizontal: GcSpace.md),
|
||||||
|
decoration: BoxDecoration(
|
||||||
|
color: GcColors.surfaceAlt,
|
||||||
|
borderRadius: BorderRadius.circular(GcRadius.control),
|
||||||
|
border: Border.all(color: GcColors.line),
|
||||||
|
),
|
||||||
|
child: Row(
|
||||||
|
mainAxisSize: MainAxisSize.min,
|
||||||
|
children: <Widget>[
|
||||||
|
Icon(Icons.colorize_rounded, size: 16, color: GcColors.faint),
|
||||||
|
const SizedBox(width: GcSpace.xs + 2),
|
||||||
|
Text(
|
||||||
|
T('set.accent.custom'),
|
||||||
|
style: TextStyle(
|
||||||
|
fontSize: 12,
|
||||||
|
height: 1.3,
|
||||||
|
color: GcColors.muted,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _pickCustomAccent() async {
|
||||||
|
final controller = TextEditingController(
|
||||||
|
text: GcPalette.toHex(GcPalette.accent.value),
|
||||||
|
);
|
||||||
|
final hex = await showDialog<String>(
|
||||||
|
context: context,
|
||||||
|
builder: (context) => AlertDialog(
|
||||||
|
backgroundColor: GcColors.surface,
|
||||||
|
title: Text(T('set.accent.custom')),
|
||||||
|
content: TextField(
|
||||||
|
controller: controller,
|
||||||
|
autofocus: true,
|
||||||
|
style: Theme.of(context).textTheme.bodyLarge!.copyWith(fontSize: 13),
|
||||||
|
decoration: InputDecoration(
|
||||||
|
hintText: '#8FB6FF',
|
||||||
|
helperText: T('set.accent.hexHint'),
|
||||||
|
),
|
||||||
|
onSubmitted: (value) => Navigator.of(context).pop(value),
|
||||||
|
),
|
||||||
|
actions: <Widget>[
|
||||||
|
TextButton(
|
||||||
|
onPressed: () => Navigator.of(context).pop(),
|
||||||
|
child: Text(T('common.cancel')),
|
||||||
|
),
|
||||||
|
FilledButton(
|
||||||
|
onPressed: () => Navigator.of(context).pop(controller.text),
|
||||||
|
child: Text(T('common.confirm')),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
);
|
||||||
|
controller.dispose();
|
||||||
|
if (hex != null) await _applyAccent(hex);
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _applyAccent(String hex) async {
|
||||||
|
final parsed = GcPalette.parseHex(hex);
|
||||||
|
if (parsed == null) {
|
||||||
|
if (mounted) setState(() => _status = T('set.accent.invalid'));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
final normalized = GcPalette.toHex(parsed);
|
||||||
|
GcPalette.apply(normalized); // 立即预览
|
||||||
|
await widget.controller
|
||||||
|
.saveSettings(SettingsPatch(accentColor: normalized));
|
||||||
|
if (mounted) setState(() => _status = T('common.applied'));
|
||||||
|
}
|
||||||
|
|
||||||
|
Widget _memoryCard(SettingsInfo settings) {
|
||||||
|
return GcCard(
|
||||||
|
child: Column(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
|
children: <Widget>[
|
||||||
|
GcSectionTitle(T('set.memory')),
|
||||||
|
const SizedBox(height: GcSpace.md),
|
||||||
|
GcHint(T('set.memory.desc')),
|
||||||
|
const SizedBox(height: GcSpace.lg),
|
||||||
|
Row(
|
||||||
|
children: <Widget>[
|
||||||
|
Switch(
|
||||||
|
value: _memoryAuto,
|
||||||
|
onChanged: (value) async {
|
||||||
|
setState(() => _memoryAuto = value);
|
||||||
|
await widget.controller
|
||||||
|
.saveSettings(SettingsPatch(memoryAuto: value));
|
||||||
|
},
|
||||||
|
),
|
||||||
|
const SizedBox(width: GcSpace.md),
|
||||||
|
Expanded(
|
||||||
|
child: Text(
|
||||||
|
T('set.memory.auto'),
|
||||||
|
style: TextStyle(
|
||||||
|
fontSize: 13,
|
||||||
|
height: 1.5,
|
||||||
|
color: GcColors.muted,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
const SizedBox(height: GcSpace.xs),
|
||||||
|
Row(
|
||||||
|
children: <Widget>[
|
||||||
|
Expanded(
|
||||||
|
child: Slider(
|
||||||
|
value: _memory,
|
||||||
|
min: 512,
|
||||||
|
max: 16384,
|
||||||
|
divisions: 62,
|
||||||
|
label: '${_memory.round()} MB',
|
||||||
|
onChanged: _memoryAuto
|
||||||
|
? null
|
||||||
|
: (value) => setState(() => _memory = value),
|
||||||
|
onChangeEnd: (value) async {
|
||||||
|
await widget.controller
|
||||||
|
.saveSettings(SettingsPatch(memoryMb: value.round()));
|
||||||
|
if (mounted) setState(() => _status = T('common.applied'));
|
||||||
|
},
|
||||||
|
),
|
||||||
|
),
|
||||||
|
SizedBox(
|
||||||
|
width: 104,
|
||||||
|
child: Text(
|
||||||
|
'${_memory.round()} MB',
|
||||||
|
textAlign: TextAlign.end,
|
||||||
|
style: TextStyle(
|
||||||
|
fontSize: 13,
|
||||||
|
height: 1.4,
|
||||||
|
fontWeight: FontWeight.w600,
|
||||||
|
color: GcColors.ink,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
const SizedBox(height: GcSpace.xs),
|
||||||
|
GcHint('${T('set.memory.current')}: ${settings.memoryUsageText}'),
|
||||||
|
const SizedBox(height: GcSpace.xs),
|
||||||
|
GcHint(T('set.memory.hint')),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Widget _sourcesCard(SettingsInfo settings) {
|
||||||
|
return GcCard(
|
||||||
|
child: Column(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
|
children: <Widget>[
|
||||||
|
GcSectionTitle(T('set.sources')),
|
||||||
|
const SizedBox(height: GcSpace.md),
|
||||||
|
GcHint(T('set.sources.desc')),
|
||||||
|
const SizedBox(height: GcSpace.md),
|
||||||
|
for (final source in settings.sources)
|
||||||
|
Padding(
|
||||||
|
padding: const EdgeInsets.only(bottom: GcSpace.md),
|
||||||
|
child: Row(
|
||||||
|
children: <Widget>[
|
||||||
|
Expanded(
|
||||||
|
child: Column(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
|
mainAxisSize: MainAxisSize.min,
|
||||||
|
children: <Widget>[
|
||||||
|
Text(
|
||||||
|
source.name,
|
||||||
|
style: TextStyle(
|
||||||
|
fontSize: 13,
|
||||||
|
height: 1.4,
|
||||||
|
fontWeight: FontWeight.w600,
|
||||||
|
color: GcColors.ink,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
const SizedBox(height: 1),
|
||||||
|
Text(
|
||||||
|
source.url,
|
||||||
|
maxLines: 1,
|
||||||
|
overflow: TextOverflow.ellipsis,
|
||||||
|
style: TextStyle(
|
||||||
|
fontSize: 11.5,
|
||||||
|
height: 1.4,
|
||||||
|
color: GcColors.faint,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
const SizedBox(width: GcSpace.sm),
|
||||||
|
if (source.enabled)
|
||||||
|
GcPill(T('set.sourceEnabled'), color: GcColors.ok)
|
||||||
|
else
|
||||||
|
const GcPill('—', subtle: true),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Widget _storageCard(SettingsInfo settings) {
|
||||||
|
return GcCard(
|
||||||
|
child: Column(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
|
children: <Widget>[
|
||||||
|
GcSectionTitle(T('set.storage')),
|
||||||
|
const SizedBox(height: GcSpace.md),
|
||||||
|
GcFieldRow(
|
||||||
|
label: T('set.modelDir'),
|
||||||
|
value: settings.modelRoot,
|
||||||
|
selectable: true,
|
||||||
|
valueColor: GcColors.muted,
|
||||||
|
),
|
||||||
|
GcFieldRow(
|
||||||
|
label: T('set.dataDir'),
|
||||||
|
value: settings.dataRoot,
|
||||||
|
selectable: true,
|
||||||
|
valueColor: GcColors.muted,
|
||||||
|
),
|
||||||
|
const SizedBox(height: GcSpace.md),
|
||||||
|
Wrap(
|
||||||
|
spacing: GcSpace.sm + 2,
|
||||||
|
runSpacing: GcSpace.sm + 2,
|
||||||
|
children: <Widget>[
|
||||||
|
OutlinedButton(
|
||||||
|
onPressed: () async {
|
||||||
|
try {
|
||||||
|
await widget.controller.api.openFolder(settings.modelRoot);
|
||||||
|
} catch (error) {
|
||||||
|
if (mounted) setState(() => _status = error.toString());
|
||||||
|
}
|
||||||
|
},
|
||||||
|
child: Text(T('set.openFolder')),
|
||||||
|
),
|
||||||
|
OutlinedButton(
|
||||||
|
onPressed: () async {
|
||||||
|
await widget.controller.checkUpdate(force: true);
|
||||||
|
if (mounted) setState(() => _status = T('set.cacheCleared'));
|
||||||
|
},
|
||||||
|
child: Text(T('set.clearCache')),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Widget _updateCard(SettingsInfo settings) {
|
||||||
|
return GcCard(
|
||||||
|
child: Column(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
|
children: <Widget>[
|
||||||
|
GcSectionTitle(T('update.title')),
|
||||||
|
const SizedBox(height: GcSpace.md),
|
||||||
|
GcHint(T('set.checkUpdate.desc')),
|
||||||
|
const SizedBox(height: GcSpace.md),
|
||||||
|
Row(
|
||||||
|
children: <Widget>[
|
||||||
|
Switch(
|
||||||
|
value: _autoUpdate,
|
||||||
|
onChanged: (value) async {
|
||||||
|
setState(() => _autoUpdate = value);
|
||||||
|
await widget.controller
|
||||||
|
.saveSettings(SettingsPatch(autoUpdateOnStartup: value));
|
||||||
|
},
|
||||||
|
),
|
||||||
|
const SizedBox(width: GcSpace.md),
|
||||||
|
Expanded(
|
||||||
|
child: Text(
|
||||||
|
T('update.auto'),
|
||||||
|
style: TextStyle(
|
||||||
|
fontSize: 13,
|
||||||
|
height: 1.5,
|
||||||
|
color: GcColors.muted,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
const SizedBox(height: GcSpace.sm),
|
||||||
|
GcFieldRow(
|
||||||
|
label: T('update.source'),
|
||||||
|
value: settings.updateRepository,
|
||||||
|
selectable: true,
|
||||||
|
valueColor: GcColors.muted,
|
||||||
|
),
|
||||||
|
const SizedBox(height: GcSpace.md),
|
||||||
|
FilledButton(
|
||||||
|
onPressed: () => widget.controller.checkUpdate(force: true),
|
||||||
|
child: Text(T('update.checkNow')),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Widget _backendCard(SettingsInfo settings) {
|
||||||
|
final health = widget.controller.health;
|
||||||
|
return GcCard(
|
||||||
|
child: Column(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
|
children: <Widget>[
|
||||||
|
GcSectionTitle(T('set.backend')),
|
||||||
|
const SizedBox(height: GcSpace.md),
|
||||||
|
GcHint(T('set.backend.desc')),
|
||||||
|
const SizedBox(height: GcSpace.md),
|
||||||
|
GcFieldRow(
|
||||||
|
label: 'API',
|
||||||
|
value: widget.controller.api.baseUrl,
|
||||||
|
selectable: true,
|
||||||
|
valueColor: GcColors.muted,
|
||||||
|
),
|
||||||
|
GcFieldRow(
|
||||||
|
label: T('set.version'),
|
||||||
|
value: settings.version,
|
||||||
|
valueColor: GcColors.muted,
|
||||||
|
),
|
||||||
|
GcFieldRow(
|
||||||
|
label: T('set.platform'),
|
||||||
|
value: settings.platform,
|
||||||
|
valueColor: GcColors.muted,
|
||||||
|
),
|
||||||
|
GcFieldRow(
|
||||||
|
label: T('set.backend.ui'),
|
||||||
|
value: health == null
|
||||||
|
? '—'
|
||||||
|
: health.uiAvailable
|
||||||
|
? T('set.backend.uiOk')
|
||||||
|
: '${T('set.backend.uiBad')}${health.uiError == null ? '' : ' · ${health.uiError}'}',
|
||||||
|
valueColor: health == null
|
||||||
|
? GcColors.muted
|
||||||
|
: health.uiAvailable
|
||||||
|
? GcColors.ok
|
||||||
|
: GcColors.danger,
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
+186
-88
@@ -14,12 +14,31 @@ class _NavItem {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const List<_NavItem> _navItems = <_NavItem>[
|
const List<_NavItem> _navItems = <_NavItem>[
|
||||||
_NavItem(Icons.grid_view_rounded, 'nav.home'),
|
_NavItem(Icons.dashboard_rounded, 'nav.home'),
|
||||||
_NavItem(Icons.download_rounded, 'nav.download'),
|
_NavItem(Icons.download_rounded, 'nav.download'),
|
||||||
_NavItem(Icons.tune_rounded, 'nav.settings'),
|
_NavItem(Icons.tune_rounded, 'nav.settings'),
|
||||||
_NavItem(Icons.info_outline_rounded, 'nav.about'),
|
_NavItem(Icons.info_outline_rounded, 'nav.about'),
|
||||||
];
|
];
|
||||||
|
|
||||||
|
/// 桌面端滚动行为:去掉移动端的拉伸回弹和边缘光晕,滚轮更跟手。
|
||||||
|
class GcScrollBehavior extends MaterialScrollBehavior {
|
||||||
|
const GcScrollBehavior();
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget buildOverscrollIndicator(
|
||||||
|
BuildContext context,
|
||||||
|
Widget child,
|
||||||
|
ScrollableDetails details,
|
||||||
|
) {
|
||||||
|
return child;
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
ScrollPhysics getScrollPhysics(BuildContext context) {
|
||||||
|
return const ClampingScrollPhysics(parent: AlwaysScrollableScrollPhysics());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// 应用外壳:左侧导航 + 右侧内容 + 底部更新状态条。
|
/// 应用外壳:左侧导航 + 右侧内容 + 底部更新状态条。
|
||||||
class ShellPage extends StatefulWidget {
|
class ShellPage extends StatefulWidget {
|
||||||
const ShellPage({super.key, required this.controller});
|
const ShellPage({super.key, required this.controller});
|
||||||
@@ -52,6 +71,7 @@ class _ShellPageState extends State<ShellPage> {
|
|||||||
body: Row(
|
body: Row(
|
||||||
children: <Widget>[
|
children: <Widget>[
|
||||||
_Sidebar(controller: controller),
|
_Sidebar(controller: controller),
|
||||||
|
Container(width: 1, color: GcColors.line),
|
||||||
Expanded(
|
Expanded(
|
||||||
child: Column(
|
child: Column(
|
||||||
children: <Widget>[
|
children: <Widget>[
|
||||||
@@ -75,9 +95,9 @@ class _ShellPageState extends State<ShellPage> {
|
|||||||
}
|
}
|
||||||
return const Center(
|
return const Center(
|
||||||
child: SizedBox(
|
child: SizedBox(
|
||||||
width: 26,
|
width: 22,
|
||||||
height: 26,
|
height: 22,
|
||||||
child: CircularProgressIndicator(strokeWidth: 2.4),
|
child: CircularProgressIndicator(strokeWidth: 2),
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -124,52 +144,25 @@ class _Sidebar extends StatelessWidget {
|
|||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
final settings = controller.settings;
|
final settings = controller.settings;
|
||||||
return Container(
|
return Container(
|
||||||
width: 236,
|
width: GcSize.sidebar,
|
||||||
color: GcColors.sideBg,
|
color: GcColors.sideBg,
|
||||||
padding: const EdgeInsets.fromLTRB(16, 20, 16, 18),
|
padding: const EdgeInsets.fromLTRB(
|
||||||
|
GcSpace.xl, GcSpace.xxl, GcSpace.lg, GcSpace.lg),
|
||||||
child: Column(
|
child: Column(
|
||||||
crossAxisAlignment: CrossAxisAlignment.start,
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
children: <Widget>[
|
children: <Widget>[
|
||||||
Row(
|
_brand(),
|
||||||
children: <Widget>[
|
const SizedBox(height: GcSpace.xxxl),
|
||||||
Container(
|
|
||||||
width: 26,
|
|
||||||
height: 26,
|
|
||||||
decoration: BoxDecoration(
|
|
||||||
color: GcColors.surfaceAlt,
|
|
||||||
borderRadius: BorderRadius.circular(8),
|
|
||||||
),
|
|
||||||
alignment: Alignment.center,
|
|
||||||
child: const Text(
|
|
||||||
'◎',
|
|
||||||
style: TextStyle(fontSize: 14, color: GcColors.accent),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
const SizedBox(width: 10),
|
|
||||||
const Expanded(
|
|
||||||
child: Text(
|
|
||||||
'Morris GC',
|
|
||||||
style: TextStyle(
|
|
||||||
fontSize: 13,
|
|
||||||
fontWeight: FontWeight.w600,
|
|
||||||
color: GcColors.ink,
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
],
|
|
||||||
),
|
|
||||||
const SizedBox(height: 6),
|
|
||||||
GcHint(T('app.tagline')),
|
|
||||||
const SizedBox(height: 26),
|
|
||||||
const Padding(
|
const Padding(
|
||||||
padding: EdgeInsets.only(left: 14, bottom: 6),
|
padding: EdgeInsets.only(left: 10, bottom: GcSpace.sm),
|
||||||
child: Text(
|
child: Text(
|
||||||
'MENU',
|
'MENU',
|
||||||
style: TextStyle(
|
style: TextStyle(
|
||||||
fontSize: 9.5,
|
fontSize: 11,
|
||||||
letterSpacing: 1.2,
|
height: 1.2,
|
||||||
|
letterSpacing: 1.4,
|
||||||
fontWeight: FontWeight.w600,
|
fontWeight: FontWeight.w600,
|
||||||
color: Color(0xFF4C5F80),
|
color: Color(0xFF5C6A80),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
@@ -181,25 +174,91 @@ class _Sidebar extends StatelessWidget {
|
|||||||
),
|
),
|
||||||
const Spacer(),
|
const Spacer(),
|
||||||
Container(height: 1, color: GcColors.line),
|
Container(height: 1, color: GcColors.line),
|
||||||
const SizedBox(height: 10),
|
const SizedBox(height: GcSpace.md),
|
||||||
Padding(
|
Padding(
|
||||||
padding: const EdgeInsets.only(left: 14),
|
padding: const EdgeInsets.only(left: 10),
|
||||||
child: Text(
|
child: Column(
|
||||||
'v${settings?.version ?? '—'}',
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
style: const TextStyle(fontSize: 10.5, color: GcColors.faint),
|
children: <Widget>[
|
||||||
),
|
Text(
|
||||||
),
|
'v${settings?.version ?? '—'}',
|
||||||
Padding(
|
style: TextStyle(
|
||||||
padding: const EdgeInsets.only(left: 14, top: 2),
|
fontSize: 12,
|
||||||
child: Text(
|
height: 1.4,
|
||||||
settings?.platform ?? '—',
|
fontWeight: FontWeight.w600,
|
||||||
style: const TextStyle(fontSize: 10, color: Color(0xFF4F6080)),
|
color: GcColors.muted,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
const SizedBox(height: 2),
|
||||||
|
Text(
|
||||||
|
settings?.platform ?? '—',
|
||||||
|
style: TextStyle(
|
||||||
|
fontSize: 11.5,
|
||||||
|
height: 1.4,
|
||||||
|
color: GcColors.ghost,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// 品牌区:一个渐变圆角标 + 名称 + 一句定位。
|
||||||
|
Widget _brand() {
|
||||||
|
return Row(
|
||||||
|
children: <Widget>[
|
||||||
|
Container(
|
||||||
|
width: 32,
|
||||||
|
height: 32,
|
||||||
|
alignment: Alignment.center,
|
||||||
|
decoration: BoxDecoration(
|
||||||
|
color: GcColors.accentSoft,
|
||||||
|
borderRadius: BorderRadius.circular(9),
|
||||||
|
border: Border.all(
|
||||||
|
color: Color.alphaBlend(
|
||||||
|
GcColors.accent.withOpacity(0.35), GcColors.sideBg),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
child: Text(
|
||||||
|
'◎',
|
||||||
|
style: TextStyle(fontSize: 16, height: 1.1, color: GcColors.accent),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
const SizedBox(width: GcSpace.md),
|
||||||
|
Expanded(
|
||||||
|
child: Column(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
|
mainAxisSize: MainAxisSize.min,
|
||||||
|
children: <Widget>[
|
||||||
|
Text(
|
||||||
|
'Morris GC',
|
||||||
|
style: TextStyle(
|
||||||
|
fontSize: 14,
|
||||||
|
height: 1.3,
|
||||||
|
fontWeight: FontWeight.w600,
|
||||||
|
color: GcColors.ink,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
const SizedBox(height: 1),
|
||||||
|
Text(
|
||||||
|
'SCIENCE · CLASSROOM',
|
||||||
|
style: TextStyle(
|
||||||
|
fontSize: 10,
|
||||||
|
height: 1.3,
|
||||||
|
letterSpacing: 0.9,
|
||||||
|
fontWeight: FontWeight.w600,
|
||||||
|
color: GcColors.ghost,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
class _NavButton extends StatelessWidget {
|
class _NavButton extends StatelessWidget {
|
||||||
@@ -216,29 +275,34 @@ class _NavButton extends StatelessWidget {
|
|||||||
@override
|
@override
|
||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
return Padding(
|
return Padding(
|
||||||
padding: const EdgeInsets.only(bottom: 4),
|
padding: const EdgeInsets.only(bottom: GcSpace.xs),
|
||||||
child: Material(
|
child: Material(
|
||||||
color: active ? GcColors.surfaceAlt : Colors.transparent,
|
color: active ? GcColors.accentSoft : Colors.transparent,
|
||||||
borderRadius: BorderRadius.circular(9),
|
borderRadius: BorderRadius.circular(GcRadius.control),
|
||||||
child: InkWell(
|
child: InkWell(
|
||||||
borderRadius: BorderRadius.circular(9),
|
borderRadius: BorderRadius.circular(GcRadius.control),
|
||||||
onTap: onTap,
|
onTap: onTap,
|
||||||
|
hoverColor: GcColors.surfaceHover,
|
||||||
child: Padding(
|
child: Padding(
|
||||||
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10),
|
padding: const EdgeInsets.symmetric(
|
||||||
|
horizontal: GcSpace.md,
|
||||||
|
vertical: 11,
|
||||||
|
),
|
||||||
child: Row(
|
child: Row(
|
||||||
children: <Widget>[
|
children: <Widget>[
|
||||||
Icon(
|
Icon(
|
||||||
item.icon,
|
item.icon,
|
||||||
size: 16,
|
size: 17,
|
||||||
color: active ? GcColors.accent : GcColors.faint,
|
color: active ? GcColors.accent : GcColors.faint,
|
||||||
),
|
),
|
||||||
const SizedBox(width: 10),
|
const SizedBox(width: GcSpace.md),
|
||||||
Text(
|
Text(
|
||||||
T(item.labelKey),
|
T(item.labelKey),
|
||||||
style: TextStyle(
|
style: TextStyle(
|
||||||
fontSize: 12.5,
|
fontSize: 13.5,
|
||||||
|
height: 1.2,
|
||||||
fontWeight: active ? FontWeight.w600 : FontWeight.w400,
|
fontWeight: active ? FontWeight.w600 : FontWeight.w400,
|
||||||
color: active ? GcColors.ink : GcColors.muted,
|
color: active ? GcColors.accent : GcColors.muted,
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
],
|
],
|
||||||
@@ -258,24 +322,32 @@ class _UpdateBar extends StatelessWidget {
|
|||||||
@override
|
@override
|
||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
return Container(
|
return Container(
|
||||||
decoration: const BoxDecoration(
|
decoration: BoxDecoration(
|
||||||
color: GcColors.surface,
|
color: GcColors.surface,
|
||||||
border: Border(top: BorderSide(color: GcColors.line)),
|
border: Border(top: BorderSide(color: GcColors.line)),
|
||||||
),
|
),
|
||||||
padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 9),
|
padding: const EdgeInsets.symmetric(
|
||||||
|
horizontal: GcSpace.xxl,
|
||||||
|
vertical: GcSpace.md,
|
||||||
|
),
|
||||||
child: Row(
|
child: Row(
|
||||||
children: <Widget>[
|
children: <Widget>[
|
||||||
Text('⟳',
|
Icon(
|
||||||
style: TextStyle(fontSize: 16, color: GcColors.accent)),
|
Icons.sync_rounded,
|
||||||
const SizedBox(width: 12),
|
size: 18,
|
||||||
|
color: GcColors.accent,
|
||||||
|
),
|
||||||
|
const SizedBox(width: GcSpace.md),
|
||||||
Expanded(
|
Expanded(
|
||||||
child: Column(
|
child: Column(
|
||||||
crossAxisAlignment: CrossAxisAlignment.start,
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
|
mainAxisSize: MainAxisSize.min,
|
||||||
children: <Widget>[
|
children: <Widget>[
|
||||||
Text(
|
Text(
|
||||||
controller.updateStatus,
|
controller.updateStatus,
|
||||||
style: const TextStyle(
|
style: TextStyle(
|
||||||
fontSize: 12.5,
|
fontSize: 13,
|
||||||
|
height: 1.35,
|
||||||
fontWeight: FontWeight.w600,
|
fontWeight: FontWeight.w600,
|
||||||
color: GcColors.ink,
|
color: GcColors.ink,
|
||||||
),
|
),
|
||||||
@@ -284,23 +356,41 @@ class _UpdateBar extends StatelessWidget {
|
|||||||
if (controller.updateDetail.isNotEmpty)
|
if (controller.updateDetail.isNotEmpty)
|
||||||
Text(
|
Text(
|
||||||
controller.updateDetail,
|
controller.updateDetail,
|
||||||
style: const TextStyle(fontSize: 11, color: GcColors.faint),
|
style: TextStyle(
|
||||||
|
fontSize: 12,
|
||||||
|
height: 1.4,
|
||||||
|
color: GcColors.faint,
|
||||||
|
),
|
||||||
overflow: TextOverflow.ellipsis,
|
overflow: TextOverflow.ellipsis,
|
||||||
),
|
),
|
||||||
if (controller.launcherNotice.isNotEmpty)
|
if (controller.launcherNotice.isNotEmpty)
|
||||||
Text(
|
Text(
|
||||||
controller.launcherNotice,
|
controller.launcherNotice,
|
||||||
style: const TextStyle(fontSize: 11, color: GcColors.warn),
|
style: TextStyle(
|
||||||
|
fontSize: 12,
|
||||||
|
height: 1.4,
|
||||||
|
color: GcColors.warn,
|
||||||
|
),
|
||||||
),
|
),
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
if (controller.updateBusy)
|
if (controller.updateBusy) ...<Widget>[
|
||||||
const SizedBox(
|
const SizedBox(width: GcSpace.lg),
|
||||||
width: 130,
|
SizedBox(
|
||||||
child: LinearProgressIndicator(minHeight: 4),
|
width: 140,
|
||||||
|
child: ClipRRect(
|
||||||
|
borderRadius: BorderRadius.circular(3),
|
||||||
|
child: LinearProgressIndicator(
|
||||||
|
value: controller.updateProgress > 0
|
||||||
|
? controller.updateProgress.clamp(0, 1).toDouble()
|
||||||
|
: null,
|
||||||
|
minHeight: 4,
|
||||||
|
),
|
||||||
|
),
|
||||||
),
|
),
|
||||||
const SizedBox(width: 14),
|
],
|
||||||
|
const SizedBox(width: GcSpace.lg),
|
||||||
TextButton(
|
TextButton(
|
||||||
onPressed: controller.updateBusy
|
onPressed: controller.updateBusy
|
||||||
? null
|
? null
|
||||||
@@ -324,24 +414,32 @@ class _BackendDown extends StatelessWidget {
|
|||||||
child: ConstrainedBox(
|
child: ConstrainedBox(
|
||||||
constraints: const BoxConstraints(maxWidth: 520),
|
constraints: const BoxConstraints(maxWidth: 520),
|
||||||
child: GcCard(
|
child: GcCard(
|
||||||
padding: const EdgeInsets.all(28),
|
padding: const EdgeInsets.all(GcSpace.xxl),
|
||||||
child: Column(
|
child: Column(
|
||||||
mainAxisSize: MainAxisSize.min,
|
mainAxisSize: MainAxisSize.min,
|
||||||
crossAxisAlignment: CrossAxisAlignment.start,
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
children: <Widget>[
|
children: <Widget>[
|
||||||
Text(
|
Row(
|
||||||
T('common.error'),
|
children: <Widget>[
|
||||||
style: const TextStyle(
|
Icon(Icons.error_outline_rounded,
|
||||||
fontSize: 17,
|
size: 20, color: GcColors.danger),
|
||||||
fontWeight: FontWeight.w600,
|
const SizedBox(width: GcSpace.sm),
|
||||||
color: GcColors.ink,
|
Text(
|
||||||
),
|
T('common.error'),
|
||||||
|
style: TextStyle(
|
||||||
|
fontSize: 16,
|
||||||
|
height: 1.35,
|
||||||
|
fontWeight: FontWeight.w600,
|
||||||
|
color: GcColors.ink,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
),
|
),
|
||||||
const SizedBox(height: 10),
|
const SizedBox(height: GcSpace.md),
|
||||||
GcHint(controller.loadError ?? ''),
|
GcHint(controller.loadError ?? ''),
|
||||||
const SizedBox(height: 6),
|
const SizedBox(height: GcSpace.xs),
|
||||||
GcHint('后端地址:${controller.api.baseUrl}'),
|
GcHint('${T('set.backend')}: ${controller.api.baseUrl}'),
|
||||||
const SizedBox(height: 16),
|
const SizedBox(height: GcSpace.lg),
|
||||||
FilledButton(
|
FilledButton(
|
||||||
onPressed: controller.bootstrap,
|
onPressed: controller.bootstrap,
|
||||||
child: Text(T('common.retry')),
|
child: Text(T('common.retry')),
|
||||||
|
|||||||
+914
-66
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1 @@
|
|||||||
|
flutter/ephemeral
|
||||||
@@ -0,0 +1,146 @@
|
|||||||
|
# Project-level configuration.
|
||||||
|
cmake_minimum_required(VERSION 3.10)
|
||||||
|
project(runner LANGUAGES CXX)
|
||||||
|
|
||||||
|
# The name of the executable created for the application. Change this to change
|
||||||
|
# the on-disk name of your application.
|
||||||
|
set(BINARY_NAME "GC-UI")
|
||||||
|
# The unique GTK application identifier for this application. See:
|
||||||
|
# https://wiki.gnome.org/HowDoI/ChooseApplicationID
|
||||||
|
set(APPLICATION_ID "com.xhmcl.GC")
|
||||||
|
|
||||||
|
# Explicitly opt in to modern CMake behaviors to avoid warnings with recent
|
||||||
|
# versions of CMake.
|
||||||
|
cmake_policy(SET CMP0063 NEW)
|
||||||
|
|
||||||
|
# Load bundled libraries from the lib/ directory relative to the binary.
|
||||||
|
set(CMAKE_INSTALL_RPATH "$ORIGIN/lib")
|
||||||
|
|
||||||
|
# Root filesystem for cross-building.
|
||||||
|
if(FLUTTER_TARGET_PLATFORM_SYSROOT)
|
||||||
|
set(CMAKE_SYSROOT ${FLUTTER_TARGET_PLATFORM_SYSROOT})
|
||||||
|
set(CMAKE_FIND_ROOT_PATH ${CMAKE_SYSROOT})
|
||||||
|
set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER)
|
||||||
|
set(CMAKE_FIND_ROOT_PATH_MODE_PACKAGE ONLY)
|
||||||
|
set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY)
|
||||||
|
set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY)
|
||||||
|
endif()
|
||||||
|
|
||||||
|
# Define build configuration options.
|
||||||
|
if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES)
|
||||||
|
set(CMAKE_BUILD_TYPE "Debug" CACHE
|
||||||
|
STRING "Flutter build mode" FORCE)
|
||||||
|
set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS
|
||||||
|
"Debug" "Profile" "Release")
|
||||||
|
endif()
|
||||||
|
|
||||||
|
# Compilation settings that should be applied to most targets.
|
||||||
|
#
|
||||||
|
# Be cautious about adding new options here, as plugins use this function by
|
||||||
|
# default. In most cases, you should add new options to specific targets instead
|
||||||
|
# of modifying this function.
|
||||||
|
function(APPLY_STANDARD_SETTINGS TARGET)
|
||||||
|
target_compile_features(${TARGET} PUBLIC cxx_std_14)
|
||||||
|
target_compile_options(${TARGET} PRIVATE -Wall -Werror)
|
||||||
|
target_compile_options(${TARGET} PRIVATE "$<$<NOT:$<CONFIG:Debug>>:-O3>")
|
||||||
|
target_compile_definitions(${TARGET} PRIVATE "$<$<NOT:$<CONFIG:Debug>>:NDEBUG>")
|
||||||
|
endfunction()
|
||||||
|
|
||||||
|
# Flutter library and tool build rules.
|
||||||
|
set(FLUTTER_MANAGED_DIR "${CMAKE_CURRENT_SOURCE_DIR}/flutter")
|
||||||
|
add_subdirectory(${FLUTTER_MANAGED_DIR})
|
||||||
|
|
||||||
|
# System-level dependencies.
|
||||||
|
find_package(PkgConfig REQUIRED)
|
||||||
|
pkg_check_modules(GTK REQUIRED IMPORTED_TARGET gtk+-3.0)
|
||||||
|
|
||||||
|
add_definitions(-DAPPLICATION_ID="${APPLICATION_ID}")
|
||||||
|
|
||||||
|
# Define the application target. To change its name, change BINARY_NAME above,
|
||||||
|
# not the value here, or `flutter run` will no longer work.
|
||||||
|
#
|
||||||
|
# Any new source files that you add to the application should be added here.
|
||||||
|
add_executable(${BINARY_NAME}
|
||||||
|
"main.cc"
|
||||||
|
"my_application.cc"
|
||||||
|
"${FLUTTER_MANAGED_DIR}/generated_plugin_registrant.cc"
|
||||||
|
)
|
||||||
|
|
||||||
|
# Apply the standard set of build settings. This can be removed for applications
|
||||||
|
# that need different build settings.
|
||||||
|
apply_standard_settings(${BINARY_NAME})
|
||||||
|
|
||||||
|
# Add dependency libraries. Add any application-specific dependencies here.
|
||||||
|
target_link_libraries(${BINARY_NAME} PRIVATE flutter)
|
||||||
|
target_link_libraries(${BINARY_NAME} PRIVATE PkgConfig::GTK)
|
||||||
|
|
||||||
|
# Run the Flutter tool portions of the build. This must not be removed.
|
||||||
|
add_dependencies(${BINARY_NAME} flutter_assemble)
|
||||||
|
|
||||||
|
# Only the install-generated bundle's copy of the executable will launch
|
||||||
|
# correctly, since the resources must in the right relative locations. To avoid
|
||||||
|
# people trying to run the unbundled copy, put it in a subdirectory instead of
|
||||||
|
# the default top-level location.
|
||||||
|
set_target_properties(${BINARY_NAME}
|
||||||
|
PROPERTIES
|
||||||
|
RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/intermediates_do_not_run"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
# Generated plugin build rules, which manage building the plugins and adding
|
||||||
|
# them to the application.
|
||||||
|
include(flutter/generated_plugins.cmake)
|
||||||
|
|
||||||
|
|
||||||
|
# === Installation ===
|
||||||
|
# By default, "installing" just makes a relocatable bundle in the build
|
||||||
|
# directory.
|
||||||
|
set(BUILD_BUNDLE_DIR "${PROJECT_BINARY_DIR}/bundle")
|
||||||
|
# 无条件强制安装到 build 目录下的 bundle:某些环境下 CMAKE_INSTALL_PREFIX
|
||||||
|
# 会被初始化成 /usr/local,导致 flutter build linux 声称成功、却把产物装进
|
||||||
|
# 系统目录,build/.../bundle 是空的。
|
||||||
|
set(CMAKE_INSTALL_PREFIX "${BUILD_BUNDLE_DIR}" CACHE PATH "Flutter bundle 输出目录" FORCE)
|
||||||
|
|
||||||
|
# Start with a clean build bundle directory every time.
|
||||||
|
install(CODE "
|
||||||
|
file(REMOVE_RECURSE \"${BUILD_BUNDLE_DIR}/\")
|
||||||
|
" COMPONENT Runtime)
|
||||||
|
|
||||||
|
set(INSTALL_BUNDLE_DATA_DIR "${CMAKE_INSTALL_PREFIX}/data")
|
||||||
|
set(INSTALL_BUNDLE_LIB_DIR "${CMAKE_INSTALL_PREFIX}/lib")
|
||||||
|
|
||||||
|
install(TARGETS ${BINARY_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}"
|
||||||
|
COMPONENT Runtime)
|
||||||
|
|
||||||
|
install(FILES "${FLUTTER_ICU_DATA_FILE}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}"
|
||||||
|
COMPONENT Runtime)
|
||||||
|
|
||||||
|
install(FILES "${FLUTTER_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}"
|
||||||
|
COMPONENT Runtime)
|
||||||
|
|
||||||
|
foreach(bundled_library ${PLUGIN_BUNDLED_LIBRARIES})
|
||||||
|
install(FILES "${bundled_library}"
|
||||||
|
DESTINATION "${INSTALL_BUNDLE_LIB_DIR}"
|
||||||
|
COMPONENT Runtime)
|
||||||
|
endforeach(bundled_library)
|
||||||
|
|
||||||
|
# Copy the native assets provided by the build.dart from all packages.
|
||||||
|
set(NATIVE_ASSETS_DIR "${PROJECT_BUILD_DIR}native_assets/linux/")
|
||||||
|
install(DIRECTORY "${NATIVE_ASSETS_DIR}"
|
||||||
|
DESTINATION "${INSTALL_BUNDLE_LIB_DIR}"
|
||||||
|
COMPONENT Runtime)
|
||||||
|
|
||||||
|
# Fully re-copy the assets directory on each build to avoid having stale files
|
||||||
|
# from a previous install.
|
||||||
|
set(FLUTTER_ASSET_DIR_NAME "flutter_assets")
|
||||||
|
install(CODE "
|
||||||
|
file(REMOVE_RECURSE \"${INSTALL_BUNDLE_DATA_DIR}/${FLUTTER_ASSET_DIR_NAME}\")
|
||||||
|
" COMPONENT Runtime)
|
||||||
|
install(DIRECTORY "${PROJECT_BUILD_DIR}/${FLUTTER_ASSET_DIR_NAME}"
|
||||||
|
DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime)
|
||||||
|
|
||||||
|
# Install the AOT library on non-Debug builds only.
|
||||||
|
if(NOT CMAKE_BUILD_TYPE MATCHES "Debug")
|
||||||
|
install(FILES "${AOT_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}"
|
||||||
|
COMPONENT Runtime)
|
||||||
|
endif()
|
||||||
@@ -0,0 +1,88 @@
|
|||||||
|
# This file controls Flutter-level build steps. It should not be edited.
|
||||||
|
cmake_minimum_required(VERSION 3.10)
|
||||||
|
|
||||||
|
set(EPHEMERAL_DIR "${CMAKE_CURRENT_SOURCE_DIR}/ephemeral")
|
||||||
|
|
||||||
|
# Configuration provided via flutter tool.
|
||||||
|
include(${EPHEMERAL_DIR}/generated_config.cmake)
|
||||||
|
|
||||||
|
# TODO: Move the rest of this into files in ephemeral. See
|
||||||
|
# https://github.com/flutter/flutter/issues/57146.
|
||||||
|
|
||||||
|
# Serves the same purpose as list(TRANSFORM ... PREPEND ...),
|
||||||
|
# which isn't available in 3.10.
|
||||||
|
function(list_prepend LIST_NAME PREFIX)
|
||||||
|
set(NEW_LIST "")
|
||||||
|
foreach(element ${${LIST_NAME}})
|
||||||
|
list(APPEND NEW_LIST "${PREFIX}${element}")
|
||||||
|
endforeach(element)
|
||||||
|
set(${LIST_NAME} "${NEW_LIST}" PARENT_SCOPE)
|
||||||
|
endfunction()
|
||||||
|
|
||||||
|
# === Flutter Library ===
|
||||||
|
# System-level dependencies.
|
||||||
|
find_package(PkgConfig REQUIRED)
|
||||||
|
pkg_check_modules(GTK REQUIRED IMPORTED_TARGET gtk+-3.0)
|
||||||
|
pkg_check_modules(GLIB REQUIRED IMPORTED_TARGET glib-2.0)
|
||||||
|
pkg_check_modules(GIO REQUIRED IMPORTED_TARGET gio-2.0)
|
||||||
|
|
||||||
|
set(FLUTTER_LIBRARY "${EPHEMERAL_DIR}/libflutter_linux_gtk.so")
|
||||||
|
|
||||||
|
# Published to parent scope for install step.
|
||||||
|
set(FLUTTER_LIBRARY ${FLUTTER_LIBRARY} PARENT_SCOPE)
|
||||||
|
set(FLUTTER_ICU_DATA_FILE "${EPHEMERAL_DIR}/icudtl.dat" PARENT_SCOPE)
|
||||||
|
set(PROJECT_BUILD_DIR "${PROJECT_DIR}/build/" PARENT_SCOPE)
|
||||||
|
set(AOT_LIBRARY "${PROJECT_DIR}/build/lib/libapp.so" PARENT_SCOPE)
|
||||||
|
|
||||||
|
list(APPEND FLUTTER_LIBRARY_HEADERS
|
||||||
|
"fl_basic_message_channel.h"
|
||||||
|
"fl_binary_codec.h"
|
||||||
|
"fl_binary_messenger.h"
|
||||||
|
"fl_dart_project.h"
|
||||||
|
"fl_engine.h"
|
||||||
|
"fl_json_message_codec.h"
|
||||||
|
"fl_json_method_codec.h"
|
||||||
|
"fl_message_codec.h"
|
||||||
|
"fl_method_call.h"
|
||||||
|
"fl_method_channel.h"
|
||||||
|
"fl_method_codec.h"
|
||||||
|
"fl_method_response.h"
|
||||||
|
"fl_plugin_registrar.h"
|
||||||
|
"fl_plugin_registry.h"
|
||||||
|
"fl_standard_message_codec.h"
|
||||||
|
"fl_standard_method_codec.h"
|
||||||
|
"fl_string_codec.h"
|
||||||
|
"fl_value.h"
|
||||||
|
"fl_view.h"
|
||||||
|
"flutter_linux.h"
|
||||||
|
)
|
||||||
|
list_prepend(FLUTTER_LIBRARY_HEADERS "${EPHEMERAL_DIR}/flutter_linux/")
|
||||||
|
add_library(flutter INTERFACE)
|
||||||
|
target_include_directories(flutter INTERFACE
|
||||||
|
"${EPHEMERAL_DIR}"
|
||||||
|
)
|
||||||
|
target_link_libraries(flutter INTERFACE "${FLUTTER_LIBRARY}")
|
||||||
|
target_link_libraries(flutter INTERFACE
|
||||||
|
PkgConfig::GTK
|
||||||
|
PkgConfig::GLIB
|
||||||
|
PkgConfig::GIO
|
||||||
|
)
|
||||||
|
add_dependencies(flutter flutter_assemble)
|
||||||
|
|
||||||
|
# === Flutter tool backend ===
|
||||||
|
# _phony_ is a non-existent file to force this command to run every time,
|
||||||
|
# since currently there's no way to get a full input/output list from the
|
||||||
|
# flutter tool.
|
||||||
|
add_custom_command(
|
||||||
|
OUTPUT ${FLUTTER_LIBRARY} ${FLUTTER_LIBRARY_HEADERS}
|
||||||
|
${CMAKE_CURRENT_BINARY_DIR}/_phony_
|
||||||
|
COMMAND ${CMAKE_COMMAND} -E env
|
||||||
|
${FLUTTER_TOOL_ENVIRONMENT}
|
||||||
|
"${FLUTTER_ROOT}/packages/flutter_tools/bin/tool_backend.sh"
|
||||||
|
${FLUTTER_TARGET_PLATFORM} ${CMAKE_BUILD_TYPE}
|
||||||
|
VERBATIM
|
||||||
|
)
|
||||||
|
add_custom_target(flutter_assemble DEPENDS
|
||||||
|
"${FLUTTER_LIBRARY}"
|
||||||
|
${FLUTTER_LIBRARY_HEADERS}
|
||||||
|
)
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
#include "my_application.h"
|
||||||
|
|
||||||
|
int main(int argc, char** argv) {
|
||||||
|
g_autoptr(MyApplication) app = my_application_new();
|
||||||
|
return g_application_run(G_APPLICATION(app), argc, argv);
|
||||||
|
}
|
||||||
@@ -0,0 +1,124 @@
|
|||||||
|
#include "my_application.h"
|
||||||
|
|
||||||
|
#include <flutter_linux/flutter_linux.h>
|
||||||
|
#ifdef GDK_WINDOWING_X11
|
||||||
|
#include <gdk/gdkx.h>
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#include "flutter/generated_plugin_registrant.h"
|
||||||
|
|
||||||
|
struct _MyApplication {
|
||||||
|
GtkApplication parent_instance;
|
||||||
|
char** dart_entrypoint_arguments;
|
||||||
|
};
|
||||||
|
|
||||||
|
G_DEFINE_TYPE(MyApplication, my_application, GTK_TYPE_APPLICATION)
|
||||||
|
|
||||||
|
// Implements GApplication::activate.
|
||||||
|
static void my_application_activate(GApplication* application) {
|
||||||
|
MyApplication* self = MY_APPLICATION(application);
|
||||||
|
GtkWindow* window =
|
||||||
|
GTK_WINDOW(gtk_application_window_new(GTK_APPLICATION(application)));
|
||||||
|
|
||||||
|
// Use a header bar when running in GNOME as this is the common style used
|
||||||
|
// by applications and is the setup most users will be using (e.g. Ubuntu
|
||||||
|
// desktop).
|
||||||
|
// If running on X and not using GNOME then just use a traditional title bar
|
||||||
|
// in case the window manager does more exotic layout, e.g. tiling.
|
||||||
|
// If running on Wayland assume the header bar will work (may need changing
|
||||||
|
// if future cases occur).
|
||||||
|
gboolean use_header_bar = TRUE;
|
||||||
|
#ifdef GDK_WINDOWING_X11
|
||||||
|
GdkScreen* screen = gtk_window_get_screen(window);
|
||||||
|
if (GDK_IS_X11_SCREEN(screen)) {
|
||||||
|
const gchar* wm_name = gdk_x11_screen_get_window_manager_name(screen);
|
||||||
|
if (g_strcmp0(wm_name, "GNOME Shell") != 0) {
|
||||||
|
use_header_bar = FALSE;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
if (use_header_bar) {
|
||||||
|
GtkHeaderBar* header_bar = GTK_HEADER_BAR(gtk_header_bar_new());
|
||||||
|
gtk_widget_show(GTK_WIDGET(header_bar));
|
||||||
|
gtk_header_bar_set_title(header_bar, "Morris GC");
|
||||||
|
gtk_header_bar_set_show_close_button(header_bar, TRUE);
|
||||||
|
gtk_window_set_titlebar(window, GTK_WIDGET(header_bar));
|
||||||
|
} else {
|
||||||
|
gtk_window_set_title(window, "Morris GC");
|
||||||
|
}
|
||||||
|
|
||||||
|
gtk_window_set_default_size(window, 1280, 720);
|
||||||
|
gtk_widget_show(GTK_WIDGET(window));
|
||||||
|
|
||||||
|
g_autoptr(FlDartProject) project = fl_dart_project_new();
|
||||||
|
fl_dart_project_set_dart_entrypoint_arguments(project, self->dart_entrypoint_arguments);
|
||||||
|
|
||||||
|
FlView* view = fl_view_new(project);
|
||||||
|
gtk_widget_show(GTK_WIDGET(view));
|
||||||
|
gtk_container_add(GTK_CONTAINER(window), GTK_WIDGET(view));
|
||||||
|
|
||||||
|
fl_register_plugins(FL_PLUGIN_REGISTRY(view));
|
||||||
|
|
||||||
|
gtk_widget_grab_focus(GTK_WIDGET(view));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Implements GApplication::local_command_line.
|
||||||
|
static gboolean my_application_local_command_line(GApplication* application, gchar*** arguments, int* exit_status) {
|
||||||
|
MyApplication* self = MY_APPLICATION(application);
|
||||||
|
// Strip out the first argument as it is the binary name.
|
||||||
|
self->dart_entrypoint_arguments = g_strdupv(*arguments + 1);
|
||||||
|
|
||||||
|
g_autoptr(GError) error = nullptr;
|
||||||
|
if (!g_application_register(application, nullptr, &error)) {
|
||||||
|
g_warning("Failed to register: %s", error->message);
|
||||||
|
*exit_status = 1;
|
||||||
|
return TRUE;
|
||||||
|
}
|
||||||
|
|
||||||
|
g_application_activate(application);
|
||||||
|
*exit_status = 0;
|
||||||
|
|
||||||
|
return TRUE;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Implements GApplication::startup.
|
||||||
|
static void my_application_startup(GApplication* application) {
|
||||||
|
//MyApplication* self = MY_APPLICATION(object);
|
||||||
|
|
||||||
|
// Perform any actions required at application startup.
|
||||||
|
|
||||||
|
G_APPLICATION_CLASS(my_application_parent_class)->startup(application);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Implements GApplication::shutdown.
|
||||||
|
static void my_application_shutdown(GApplication* application) {
|
||||||
|
//MyApplication* self = MY_APPLICATION(object);
|
||||||
|
|
||||||
|
// Perform any actions required at application shutdown.
|
||||||
|
|
||||||
|
G_APPLICATION_CLASS(my_application_parent_class)->shutdown(application);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Implements GObject::dispose.
|
||||||
|
static void my_application_dispose(GObject* object) {
|
||||||
|
MyApplication* self = MY_APPLICATION(object);
|
||||||
|
g_clear_pointer(&self->dart_entrypoint_arguments, g_strfreev);
|
||||||
|
G_OBJECT_CLASS(my_application_parent_class)->dispose(object);
|
||||||
|
}
|
||||||
|
|
||||||
|
static void my_application_class_init(MyApplicationClass* klass) {
|
||||||
|
G_APPLICATION_CLASS(klass)->activate = my_application_activate;
|
||||||
|
G_APPLICATION_CLASS(klass)->local_command_line = my_application_local_command_line;
|
||||||
|
G_APPLICATION_CLASS(klass)->startup = my_application_startup;
|
||||||
|
G_APPLICATION_CLASS(klass)->shutdown = my_application_shutdown;
|
||||||
|
G_OBJECT_CLASS(klass)->dispose = my_application_dispose;
|
||||||
|
}
|
||||||
|
|
||||||
|
static void my_application_init(MyApplication* self) {}
|
||||||
|
|
||||||
|
MyApplication* my_application_new() {
|
||||||
|
return MY_APPLICATION(g_object_new(my_application_get_type(),
|
||||||
|
"application-id", APPLICATION_ID,
|
||||||
|
"flags", G_APPLICATION_NON_UNIQUE,
|
||||||
|
nullptr));
|
||||||
|
}
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
#ifndef FLUTTER_MY_APPLICATION_H_
|
||||||
|
#define FLUTTER_MY_APPLICATION_H_
|
||||||
|
|
||||||
|
#include <gtk/gtk.h>
|
||||||
|
|
||||||
|
G_DECLARE_FINAL_TYPE(MyApplication, my_application, MY, APPLICATION,
|
||||||
|
GtkApplication)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* my_application_new:
|
||||||
|
*
|
||||||
|
* Creates a new Flutter-based application.
|
||||||
|
*
|
||||||
|
* Returns: a new #MyApplication.
|
||||||
|
*/
|
||||||
|
MyApplication* my_application_new();
|
||||||
|
|
||||||
|
#endif // FLUTTER_MY_APPLICATION_H_
|
||||||
@@ -461,7 +461,7 @@
|
|||||||
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
|
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
|
||||||
GCC_WARN_UNUSED_FUNCTION = YES;
|
GCC_WARN_UNUSED_FUNCTION = YES;
|
||||||
GCC_WARN_UNUSED_VARIABLE = YES;
|
GCC_WARN_UNUSED_VARIABLE = YES;
|
||||||
MACOSX_DEPLOYMENT_TARGET = 10.14;
|
MACOSX_DEPLOYMENT_TARGET = 12.0;
|
||||||
MTL_ENABLE_DEBUG_INFO = NO;
|
MTL_ENABLE_DEBUG_INFO = NO;
|
||||||
SDKROOT = macosx;
|
SDKROOT = macosx;
|
||||||
SWIFT_COMPILATION_MODE = wholemodule;
|
SWIFT_COMPILATION_MODE = wholemodule;
|
||||||
@@ -543,7 +543,7 @@
|
|||||||
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
|
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
|
||||||
GCC_WARN_UNUSED_FUNCTION = YES;
|
GCC_WARN_UNUSED_FUNCTION = YES;
|
||||||
GCC_WARN_UNUSED_VARIABLE = YES;
|
GCC_WARN_UNUSED_VARIABLE = YES;
|
||||||
MACOSX_DEPLOYMENT_TARGET = 10.14;
|
MACOSX_DEPLOYMENT_TARGET = 12.0;
|
||||||
MTL_ENABLE_DEBUG_INFO = YES;
|
MTL_ENABLE_DEBUG_INFO = YES;
|
||||||
ONLY_ACTIVE_ARCH = YES;
|
ONLY_ACTIVE_ARCH = YES;
|
||||||
SDKROOT = macosx;
|
SDKROOT = macosx;
|
||||||
@@ -593,7 +593,7 @@
|
|||||||
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
|
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
|
||||||
GCC_WARN_UNUSED_FUNCTION = YES;
|
GCC_WARN_UNUSED_FUNCTION = YES;
|
||||||
GCC_WARN_UNUSED_VARIABLE = YES;
|
GCC_WARN_UNUSED_VARIABLE = YES;
|
||||||
MACOSX_DEPLOYMENT_TARGET = 10.14;
|
MACOSX_DEPLOYMENT_TARGET = 12.0;
|
||||||
MTL_ENABLE_DEBUG_INFO = NO;
|
MTL_ENABLE_DEBUG_INFO = NO;
|
||||||
SDKROOT = macosx;
|
SDKROOT = macosx;
|
||||||
SWIFT_COMPILATION_MODE = wholemodule;
|
SWIFT_COMPILATION_MODE = wholemodule;
|
||||||
|
|||||||
@@ -5,10 +5,10 @@
|
|||||||
// 'flutter create' template.
|
// 'flutter create' template.
|
||||||
|
|
||||||
// The application's name. By default this is also the title of the Flutter window.
|
// The application's name. By default this is also the title of the Flutter window.
|
||||||
PRODUCT_NAME = gc_ui
|
PRODUCT_NAME = GC-UI
|
||||||
|
|
||||||
// The application's bundle identifier
|
// The application's bundle identifier
|
||||||
PRODUCT_BUNDLE_IDENTIFIER = com.morris.gc.gcUi
|
PRODUCT_BUNDLE_IDENTIFIER = com.morris.gc.gcUi
|
||||||
|
|
||||||
// The copyright displayed in application information
|
// The copyright displayed in application information
|
||||||
PRODUCT_COPYRIGHT = Copyright © 2026 com.morris.gc. All rights reserved.
|
PRODUCT_COPYRIGHT = Copyright © 2026 Morris. All rights reserved.
|
||||||
@@ -4,5 +4,9 @@
|
|||||||
<dict>
|
<dict>
|
||||||
<key>com.apple.security.app-sandbox</key>
|
<key>com.apple.security.app-sandbox</key>
|
||||||
<true/>
|
<true/>
|
||||||
|
<key>com.apple.security.network.client</key>
|
||||||
|
<true/>
|
||||||
|
<key>com.apple.security.network.server</key>
|
||||||
|
<true/>
|
||||||
</dict>
|
</dict>
|
||||||
</plist>
|
</plist>
|
||||||
@@ -16,7 +16,7 @@ publish_to: 'none' # Remove this line if you wish to publish to pub.dev
|
|||||||
# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
|
# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
|
||||||
# In Windows, build-name is used as the major, minor, and patch parts
|
# In Windows, build-name is used as the major, minor, and patch parts
|
||||||
# of the product and file versions while build-number is used as the build suffix.
|
# of the product and file versions while build-number is used as the build suffix.
|
||||||
version: 1.0.0+1
|
version: 1.1.1+1
|
||||||
|
|
||||||
environment:
|
environment:
|
||||||
sdk: ^3.5.4
|
sdk: ^3.5.4
|
||||||
|
|||||||
@@ -73,7 +73,7 @@ void main() {
|
|||||||
testWidgets('renders a card with its child', (tester) async {
|
testWidgets('renders a card with its child', (tester) async {
|
||||||
await tester.pumpWidget(
|
await tester.pumpWidget(
|
||||||
MaterialApp(
|
MaterialApp(
|
||||||
theme: buildGcTheme(),
|
theme: buildGcTheme(Brightness.dark),
|
||||||
home: const Scaffold(
|
home: const Scaffold(
|
||||||
body: GcCard(child: Text('hello')),
|
body: GcCard(child: Text('hello')),
|
||||||
),
|
),
|
||||||
|
|||||||
@@ -21,9 +21,18 @@ import 'package:gc_ui/theme.dart';
|
|||||||
/// flutter test tool/render_shots_test.dart
|
/// flutter test tool/render_shots_test.dart
|
||||||
void main() {
|
void main() {
|
||||||
setUpAll(() async {
|
setUpAll(() async {
|
||||||
HttpOverrides.global = null;
|
// 不要设置 HttpOverrides.global = null:那会打开真实网络,
|
||||||
|
// flutter_test 的假时钟下 HTTP 定时器永远悬着,用例结束时
|
||||||
|
// 会撞上「!timersPending」断言。保持 flutter_test 默认的 FakeHttpClient
|
||||||
|
// (所有请求立即返回 400),页面本身都用预置数据渲染,不需要后端。
|
||||||
|
// 测试环境默认用 Ahem 占位字体(所有字都是方块),必须显式加载一套真字体:
|
||||||
|
// Linux CI 用 Noto CJK,Windows 本机用 Noto Sans SC / 微软雅黑,macOS 用苹方。
|
||||||
const candidates = <String>[
|
const candidates = <String>[
|
||||||
|
r'C:\Windows\Fonts\Deng.ttf',
|
||||||
|
r'C:\Windows\Fonts\NotoSansSC-VF.ttf',
|
||||||
|
r'C:\Windows\Fonts\msyh.ttc',
|
||||||
|
r'C:\Windows\Fonts\simhei.ttf',
|
||||||
|
'/System/Library/Fonts/PingFang.ttc',
|
||||||
'/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc',
|
'/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc',
|
||||||
'/usr/share/fonts/truetype/noto/NotoSansCJK-Regular.ttc',
|
'/usr/share/fonts/truetype/noto/NotoSansCJK-Regular.ttc',
|
||||||
];
|
];
|
||||||
@@ -36,6 +45,22 @@ void main() {
|
|||||||
await loader.load();
|
await loader.load();
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Material 图标字体:flutter_test 不会自动加载,不加载的话所有 Icon
|
||||||
|
// 都是方框,截图就没法检查图标。SDK 缓存里那份由 flutter test 通过
|
||||||
|
// FLUTTER_ROOT 指过来。
|
||||||
|
final flutterRoot = Platform.environment['FLUTTER_ROOT'];
|
||||||
|
if (flutterRoot != null) {
|
||||||
|
final icons = File(
|
||||||
|
'$flutterRoot/bin/cache/artifacts/material_fonts/materialicons-regular.otf',
|
||||||
|
);
|
||||||
|
if (icons.existsSync()) {
|
||||||
|
final bytes = icons.readAsBytesSync();
|
||||||
|
final loader = FontLoader('MaterialIcons')
|
||||||
|
..addFont(Future<ByteData>.value(ByteData.view(bytes.buffer)));
|
||||||
|
await loader.load();
|
||||||
|
}
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
SettingsInfo sampleSettings() => SettingsInfo.fromJson(<String, dynamic>{
|
SettingsInfo sampleSettings() => SettingsInfo.fromJson(<String, dynamic>{
|
||||||
@@ -123,19 +148,43 @@ void main() {
|
|||||||
'uiAvailable': true,
|
'uiAvailable': true,
|
||||||
});
|
});
|
||||||
|
|
||||||
Future<void> shoot(WidgetTester tester, String name, Widget page) async {
|
/// 外壳用的 controller:bootstrap 直接返回,不去连后端。
|
||||||
tester.view.physicalSize = const Size(1280, 820);
|
///
|
||||||
|
/// 真 ShellPage 会在 initState 里 bootstrap,后端不在时会挂重试定时器,
|
||||||
|
/// 用例结束时报「!timersPending」。这里只把 bootstrap 换成空实现,
|
||||||
|
/// 页面里的数据请求仍会走 flutter_test 的假 HTTP(立即 400)。
|
||||||
|
ShellController shellController() => _StubShellController()
|
||||||
|
..settings = sampleSettings()
|
||||||
|
..health = HealthInfo.fromJson(<String, dynamic>{
|
||||||
|
'ok': true,
|
||||||
|
'version': '1.0.7',
|
||||||
|
'platform': 'osx-arm64',
|
||||||
|
'uiAvailable': true,
|
||||||
|
});
|
||||||
|
|
||||||
|
Future<void> shoot(WidgetTester tester, String name, Widget page,
|
||||||
|
{Brightness brightness = Brightness.dark,
|
||||||
|
Size size = const Size(1280, 860)}) async {
|
||||||
|
// 1280×860:与发布包窗口默认尺寸(1280×720)接近,再多留一点高度看得到
|
||||||
|
// 底部状态条。像素比 1.0,方便逐像素检查描边和文字。
|
||||||
|
tester.view.physicalSize = size;
|
||||||
tester.view.devicePixelRatio = 1.0;
|
tester.view.devicePixelRatio = 1.0;
|
||||||
addTearDown(tester.view.reset);
|
addTearDown(tester.view.reset);
|
||||||
|
|
||||||
|
// GcColors 是静态取值,截图前先按目标亮度绑定,否则浅色截图仍是深色配色。
|
||||||
|
GcColors.bind(brightness);
|
||||||
|
|
||||||
final key = GlobalKey();
|
final key = GlobalKey();
|
||||||
await tester.pumpWidget(
|
await tester.pumpWidget(
|
||||||
MaterialApp(
|
MaterialApp(
|
||||||
debugShowCheckedModeBanner: false,
|
debugShowCheckedModeBanner: false,
|
||||||
theme: buildGcTheme().copyWith(
|
// 四个页面都用预置数据渲染,不需要后端;字体统一换成测试里加载的
|
||||||
textTheme: buildGcTheme().textTheme.apply(
|
// 那一套,并且清空 fallback —— 否则主题里的按钮 / 输入框样式会去
|
||||||
fontFamily: 'Noto Sans CJK SC',
|
// 找系统字体(测试环境没有),缺字处就画成方块。
|
||||||
),
|
theme: buildGcTheme(
|
||||||
|
brightness,
|
||||||
|
fontFamily: 'Noto Sans CJK SC',
|
||||||
|
fontFamilyFallback: const <String>[],
|
||||||
),
|
),
|
||||||
home: RepaintBoundary(
|
home: RepaintBoundary(
|
||||||
key: key,
|
key: key,
|
||||||
@@ -144,25 +193,27 @@ void main() {
|
|||||||
),
|
),
|
||||||
);
|
);
|
||||||
await tester.pump(const Duration(milliseconds: 200));
|
await tester.pump(const Duration(milliseconds: 200));
|
||||||
// 页面里的数据来自真实后端(/api/about、/api/sources 等)。
|
|
||||||
// flutter_test 默认用假时钟,真实 HTTP 永远不会完成,所以这里用 runAsync
|
|
||||||
// 让出真实时间,等请求回来后再 pump 出最终画面。
|
|
||||||
await tester.runAsync(() async {
|
|
||||||
await Future<void>.delayed(const Duration(milliseconds: 1200));
|
|
||||||
});
|
|
||||||
await tester.pump(const Duration(milliseconds: 300));
|
|
||||||
await tester.runAsync(() async {
|
|
||||||
await Future<void>.delayed(const Duration(milliseconds: 600));
|
|
||||||
});
|
|
||||||
await tester.pump(const Duration(milliseconds: 300));
|
await tester.pump(const Duration(milliseconds: 300));
|
||||||
|
|
||||||
final boundary =
|
final boundary =
|
||||||
key.currentContext!.findRenderObject()! as RenderRepaintBoundary;
|
key.currentContext!.findRenderObject()! as RenderRepaintBoundary;
|
||||||
final image = await boundary.toImage(pixelRatio: 1.0);
|
// toImage / toByteData 要走真实引擎的异步管线,必须放在 runAsync 里,
|
||||||
final bytes = await image.toByteData(format: ui.ImageByteFormat.png);
|
// 否则 fake async 时钟不会推进,Future 一直不完成(表现为每个用例卡
|
||||||
|
// 满 10 分钟超时才返回)。
|
||||||
|
final stopwatch = Stopwatch()..start();
|
||||||
|
final image = await tester.runAsync(
|
||||||
|
() => boundary.toImage(pixelRatio: 1.0),
|
||||||
|
);
|
||||||
|
final bytes = await tester.runAsync(
|
||||||
|
() => image!.toByteData(format: ui.ImageByteFormat.png),
|
||||||
|
);
|
||||||
|
|
||||||
final dir = Directory('test/shots')..createSync(recursive: true);
|
final dir = Directory('test/shots')..createSync(recursive: true);
|
||||||
File('${dir.path}/$name.png').writeAsBytesSync(bytes!.buffer.asUint8List());
|
File('${dir.path}/$name.png').writeAsBytesSync(bytes!.buffer.asUint8List());
|
||||||
|
stopwatch.stop();
|
||||||
|
// ignore: avoid_print
|
||||||
|
print(
|
||||||
|
'[shots] $name (${brightness.name}) 耗时 ${stopwatch.elapsedMilliseconds} ms');
|
||||||
}
|
}
|
||||||
|
|
||||||
testWidgets('home', (tester) async {
|
testWidgets('home', (tester) async {
|
||||||
@@ -170,7 +221,8 @@ void main() {
|
|||||||
await shoot(
|
await shoot(
|
||||||
tester,
|
tester,
|
||||||
'home',
|
'home',
|
||||||
HomePageView(controller: sampleController(), initialModels: sampleModels()),
|
HomePageView(
|
||||||
|
controller: sampleController(), initialModels: sampleModels()),
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -257,7 +309,8 @@ void main() {
|
|||||||
|
|
||||||
testWidgets('settings', (tester) async {
|
testWidgets('settings', (tester) async {
|
||||||
I18n.language.value = 'zh-CN';
|
I18n.language.value = 'zh-CN';
|
||||||
await shoot(tester, 'settings', SettingsPageView(controller: sampleController()));
|
await shoot(
|
||||||
|
tester, 'settings', SettingsPageView(controller: sampleController()));
|
||||||
});
|
});
|
||||||
|
|
||||||
testWidgets('about', (tester) async {
|
testWidgets('about', (tester) async {
|
||||||
@@ -288,6 +341,103 @@ void main() {
|
|||||||
|
|
||||||
testWidgets('shell', (tester) async {
|
testWidgets('shell', (tester) async {
|
||||||
I18n.language.value = 'zh-CN';
|
I18n.language.value = 'zh-CN';
|
||||||
await shoot(tester, 'shell', ShellPage(controller: sampleController()));
|
final controller = shellController()
|
||||||
|
..setUpdateStatus(
|
||||||
|
visible: true,
|
||||||
|
busy: false,
|
||||||
|
progress: 1,
|
||||||
|
status: '已更新 2 个模型,立即生效',
|
||||||
|
detail: '模型与启动器均为最新版',
|
||||||
|
notice: '',
|
||||||
|
);
|
||||||
|
await shoot(tester, 'shell', ShellPage(controller: controller));
|
||||||
|
});
|
||||||
|
|
||||||
|
/// 小窗口回归:1024×680 下不应出现溢出条纹或卡片挤压。
|
||||||
|
testWidgets('home-small', (tester) async {
|
||||||
|
I18n.language.value = 'zh-CN';
|
||||||
|
await shoot(
|
||||||
|
tester,
|
||||||
|
'home-small',
|
||||||
|
HomePageView(
|
||||||
|
controller: sampleController(), initialModels: sampleModels()),
|
||||||
|
size: const Size(1024, 680),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('download-small', (tester) async {
|
||||||
|
I18n.language.value = 'zh-CN';
|
||||||
|
await shoot(
|
||||||
|
tester,
|
||||||
|
'download-small',
|
||||||
|
DownloadPageView(
|
||||||
|
controller: sampleController(),
|
||||||
|
initialSources: <SourceInfo>[
|
||||||
|
SourceInfo.fromJson(<String, dynamic>{
|
||||||
|
'id': 'github',
|
||||||
|
'name': 'GitHub',
|
||||||
|
'url': 'https://github.com/Morris-GC/GC',
|
||||||
|
'enabled': true,
|
||||||
|
'builtIn': true,
|
||||||
|
'host': 'github.com',
|
||||||
|
}),
|
||||||
|
],
|
||||||
|
initialIndex: SourceIndexInfo.fromJson(<String, dynamic>{
|
||||||
|
'sourceId': 'github',
|
||||||
|
'root': 'https://github.com/Morris-GC/GC',
|
||||||
|
'fromCache': false,
|
||||||
|
'resolvedFrom': 'version.json',
|
||||||
|
'models': <dynamic>[
|
||||||
|
<String, dynamic>{
|
||||||
|
'id': 'sun',
|
||||||
|
'name': '太阳系',
|
||||||
|
'description': '观察八大行星的公转轨道与相对大小。',
|
||||||
|
'version': '1.2',
|
||||||
|
'sizeText': '2.3 MB',
|
||||||
|
'installed': true,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
}),
|
||||||
|
initialJobs: const <JobInfo>[],
|
||||||
|
),
|
||||||
|
size: const Size(1024, 680),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('settings-small', (tester) async {
|
||||||
|
I18n.language.value = 'zh-CN';
|
||||||
|
await shoot(
|
||||||
|
tester,
|
||||||
|
'settings-small',
|
||||||
|
SettingsPageView(controller: sampleController()),
|
||||||
|
size: const Size(1024, 680),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('home-light', (tester) async {
|
||||||
|
I18n.language.value = 'zh-CN';
|
||||||
|
await shoot(
|
||||||
|
tester,
|
||||||
|
'home-light',
|
||||||
|
HomePageView(
|
||||||
|
controller: sampleController(), initialModels: sampleModels()),
|
||||||
|
brightness: Brightness.light,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('settings-light', (tester) async {
|
||||||
|
I18n.language.value = 'zh-CN';
|
||||||
|
await shoot(
|
||||||
|
tester,
|
||||||
|
'settings-light',
|
||||||
|
SettingsPageView(controller: sampleController()),
|
||||||
|
brightness: Brightness.light,
|
||||||
|
);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// 只用于截图的 controller:不连后端,避免挂上重试定时器。
|
||||||
|
class _StubShellController extends ShellController {
|
||||||
|
@override
|
||||||
|
Future<void> bootstrap() async {}
|
||||||
|
}
|
||||||
@@ -4,7 +4,7 @@ project(gc_ui LANGUAGES CXX)
|
|||||||
|
|
||||||
# The name of the executable created for the application. Change this to change
|
# The name of the executable created for the application. Change this to change
|
||||||
# the on-disk name of your application.
|
# the on-disk name of your application.
|
||||||
set(BINARY_NAME "gc_ui")
|
set(BINARY_NAME "GC-UI")
|
||||||
|
|
||||||
# Explicitly opt in to modern CMake behaviors to avoid warnings with recent
|
# Explicitly opt in to modern CMake behaviors to avoid warnings with recent
|
||||||
# versions of CMake.
|
# versions of CMake.
|
||||||
|
|||||||
@@ -89,13 +89,13 @@ BEGIN
|
|||||||
BEGIN
|
BEGIN
|
||||||
BLOCK "040904e4"
|
BLOCK "040904e4"
|
||||||
BEGIN
|
BEGIN
|
||||||
VALUE "CompanyName", "com.morris.gc" "\0"
|
VALUE "CompanyName", "Morris" "\0"
|
||||||
VALUE "FileDescription", "gc_ui" "\0"
|
VALUE "FileDescription", "GC UI" "\0"
|
||||||
VALUE "FileVersion", VERSION_AS_STRING "\0"
|
VALUE "FileVersion", VERSION_AS_STRING "\0"
|
||||||
VALUE "InternalName", "gc_ui" "\0"
|
VALUE "InternalName", "GC-UI" "\0"
|
||||||
VALUE "LegalCopyright", "Copyright (C) 2026 com.morris.gc. All rights reserved." "\0"
|
VALUE "LegalCopyright", "Copyright (C) 2026 Morris. All rights reserved." "\0"
|
||||||
VALUE "OriginalFilename", "gc_ui.exe" "\0"
|
VALUE "OriginalFilename", "GC-UI.exe" "\0"
|
||||||
VALUE "ProductName", "gc_ui" "\0"
|
VALUE "ProductName", "Morris GC" "\0"
|
||||||
VALUE "ProductVersion", VERSION_AS_STRING "\0"
|
VALUE "ProductVersion", VERSION_AS_STRING "\0"
|
||||||
END
|
END
|
||||||
END
|
END
|
||||||
|
|||||||
@@ -5,8 +5,81 @@
|
|||||||
#include "flutter_window.h"
|
#include "flutter_window.h"
|
||||||
#include "utils.h"
|
#include "utils.h"
|
||||||
|
|
||||||
|
namespace {
|
||||||
|
|
||||||
|
// Enable DPI awareness (Per-Monitor V2 when available).
|
||||||
|
//
|
||||||
|
// The runner.exe.manifest normally declares this, but the mingw/windres cross
|
||||||
|
// build does not embed the manifest the way the Visual Studio generator does.
|
||||||
|
// A DPI-unaware process gets bitmap-stretched by Windows on a 125% / 150%
|
||||||
|
// scaled display, which makes the whole UI (especially small CJK text) look
|
||||||
|
// blurry. Declaring it again before any window exists costs nothing and does
|
||||||
|
// not depend on the manifest being present.
|
||||||
|
//
|
||||||
|
// Every API is resolved through GetProcAddress: it keeps the binary working on
|
||||||
|
// older systems and does not require the current SDK / mingw headers to declare
|
||||||
|
// DPI_AWARENESS_CONTEXT.
|
||||||
|
#if defined(_MSC_VER)
|
||||||
|
#pragma warning(push)
|
||||||
|
#pragma warning(disable : 4191) // FARPROC to typed function pointer, on purpose
|
||||||
|
#endif
|
||||||
|
|
||||||
|
BOOL TryPerMonitorV2() {
|
||||||
|
// DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2 == (HANDLE)-4
|
||||||
|
using Fn = BOOL(WINAPI*)(HANDLE);
|
||||||
|
HMODULE user32 = ::GetModuleHandleW(L"user32.dll");
|
||||||
|
if (user32 == nullptr) return FALSE;
|
||||||
|
auto set_context = reinterpret_cast<Fn>(
|
||||||
|
::GetProcAddress(user32, "SetProcessDpiAwarenessContext"));
|
||||||
|
if (set_context == nullptr) return FALSE;
|
||||||
|
// Cast through INT_PTR: plain -4 to pointer is C4312 at /W4.
|
||||||
|
return set_context(reinterpret_cast<HANDLE>(static_cast<INT_PTR>(-4)));
|
||||||
|
}
|
||||||
|
|
||||||
|
void TryPerMonitor() {
|
||||||
|
// Windows 8.1+: PROCESS_PER_MONITOR_DPI_AWARE == 2
|
||||||
|
using Fn = HRESULT(WINAPI*)(int);
|
||||||
|
HMODULE shcore = ::LoadLibraryW(L"shcore.dll");
|
||||||
|
if (shcore == nullptr) return;
|
||||||
|
auto set_awareness =
|
||||||
|
reinterpret_cast<Fn>(::GetProcAddress(shcore, "SetProcessDpiAwareness"));
|
||||||
|
if (set_awareness != nullptr) {
|
||||||
|
// E_ACCESSDENIED means the manifest already set awareness: still fine.
|
||||||
|
set_awareness(2);
|
||||||
|
}
|
||||||
|
::FreeLibrary(shcore);
|
||||||
|
}
|
||||||
|
|
||||||
|
void TrySystemDpiAware() {
|
||||||
|
// Windows Vista+: system DPI awareness, better than nothing.
|
||||||
|
using Fn = BOOL(WINAPI*)();
|
||||||
|
HMODULE user32 = ::GetModuleHandleW(L"user32.dll");
|
||||||
|
if (user32 == nullptr) return;
|
||||||
|
auto set_aware =
|
||||||
|
reinterpret_cast<Fn>(::GetProcAddress(user32, "SetProcessDPIAware"));
|
||||||
|
if (set_aware != nullptr) set_aware();
|
||||||
|
}
|
||||||
|
|
||||||
|
#if defined(_MSC_VER)
|
||||||
|
#pragma warning(pop)
|
||||||
|
#endif
|
||||||
|
|
||||||
|
void EnableDpiAwareness() {
|
||||||
|
// When the manifest already declared awareness, SetProcessDpiAwarenessContext
|
||||||
|
// returns FALSE; fall back to the 8.1 and Vista entry points. All three
|
||||||
|
// failing is harmless: the app still starts, it just scales blurrily.
|
||||||
|
if (TryPerMonitorV2()) return;
|
||||||
|
TryPerMonitor();
|
||||||
|
TrySystemDpiAware();
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace
|
||||||
|
|
||||||
int APIENTRY wWinMain(_In_ HINSTANCE instance, _In_opt_ HINSTANCE prev,
|
int APIENTRY wWinMain(_In_ HINSTANCE instance, _In_opt_ HINSTANCE prev,
|
||||||
_In_ wchar_t *command_line, _In_ int show_command) {
|
_In_ wchar_t *command_line, _In_ int show_command) {
|
||||||
|
// Must run before the first window is created to take effect.
|
||||||
|
EnableDpiAwareness();
|
||||||
|
|
||||||
// Attach to console when present (e.g., 'flutter run') or create a
|
// Attach to console when present (e.g., 'flutter run') or create a
|
||||||
// new console when running with a debugger.
|
// new console when running with a debugger.
|
||||||
if (!::AttachConsole(ATTACH_PARENT_PROCESS) && ::IsDebuggerPresent()) {
|
if (!::AttachConsole(ATTACH_PARENT_PROCESS) && ::IsDebuggerPresent()) {
|
||||||
@@ -27,7 +100,7 @@ int APIENTRY wWinMain(_In_ HINSTANCE instance, _In_opt_ HINSTANCE prev,
|
|||||||
FlutterWindow window(project);
|
FlutterWindow window(project);
|
||||||
Win32Window::Point origin(10, 10);
|
Win32Window::Point origin(10, 10);
|
||||||
Win32Window::Size size(1280, 720);
|
Win32Window::Size size(1280, 720);
|
||||||
if (!window.Create(L"gc_ui", origin, size)) {
|
if (!window.Create(L"Morris GC", origin, size)) {
|
||||||
return EXIT_FAILURE;
|
return EXIT_FAILURE;
|
||||||
}
|
}
|
||||||
window.SetQuitOnClose(true);
|
window.SetQuitOnClose(true);
|
||||||
|
|||||||
@@ -134,11 +134,27 @@ bool Win32Window::Create(const std::wstring& title,
|
|||||||
UINT dpi = FlutterDesktopGetDpiForMonitor(monitor);
|
UINT dpi = FlutterDesktopGetDpiForMonitor(monitor);
|
||||||
double scale_factor = dpi / 96.0;
|
double scale_factor = dpi / 96.0;
|
||||||
|
|
||||||
|
// Cap the initial size to the monitor work area. 1280x720 logical is
|
||||||
|
// 1920x1080 physical at 150% scaling, which no longer fits on a 1080p
|
||||||
|
// screen; clamping keeps the window usable instead of hanging off-screen.
|
||||||
|
int physical_width = Scale(size.width, scale_factor);
|
||||||
|
int physical_height = Scale(size.height, scale_factor);
|
||||||
|
MONITORINFO monitor_info{};
|
||||||
|
monitor_info.cbSize = sizeof(MONITORINFO);
|
||||||
|
if (::GetMonitorInfoW(monitor, &monitor_info)) {
|
||||||
|
const int max_width =
|
||||||
|
(monitor_info.rcWork.right - monitor_info.rcWork.left) * 92 / 100;
|
||||||
|
const int max_height =
|
||||||
|
(monitor_info.rcWork.bottom - monitor_info.rcWork.top) * 92 / 100;
|
||||||
|
if (physical_width > max_width) physical_width = max_width;
|
||||||
|
if (physical_height > max_height) physical_height = max_height;
|
||||||
|
}
|
||||||
|
|
||||||
HWND window = CreateWindow(
|
HWND window = CreateWindow(
|
||||||
window_class, title.c_str(), WS_OVERLAPPEDWINDOW,
|
window_class, title.c_str(), WS_OVERLAPPEDWINDOW,
|
||||||
Scale(origin.x, scale_factor), Scale(origin.y, scale_factor),
|
Scale(origin.x, scale_factor), Scale(origin.y, scale_factor),
|
||||||
Scale(size.width, scale_factor), Scale(size.height, scale_factor),
|
physical_width, physical_height, nullptr, nullptr,
|
||||||
nullptr, nullptr, GetModuleHandle(nullptr), this);
|
GetModuleHandle(nullptr), this);
|
||||||
|
|
||||||
if (!window) {
|
if (!window) {
|
||||||
return false;
|
return false;
|
||||||
|
|||||||
@@ -20,12 +20,21 @@ public static class SignatureKeyring
|
|||||||
|
|
||||||
private static readonly List<KeyEntry> KeysInternal = new()
|
private static readonly List<KeyEntry> KeysInternal = new()
|
||||||
{
|
{
|
||||||
// 生产密钥(2026-11 生成)。指纹 b41b1dd6259ea9ed
|
// 生产密钥(2026-12 换发)。指纹 ee6083be47a87907
|
||||||
|
// 上一代 gc-2026-11 的私钥没有留存,无法再签出可通过校验的清单,
|
||||||
|
// 因此新增这一把;旧公钥保留一个版本周期,方便过渡期排查。
|
||||||
|
new KeyEntry(
|
||||||
|
"gc-2026-12",
|
||||||
|
"MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE4R+R2Pvinsu/xdaUu5mATPyYoEpL6" +
|
||||||
|
"cyugSVKAVMz6yY15SjkgEvdosfWuQJBbrPOOgGulE6Jht6v7FZx1dQguQ==",
|
||||||
|
"GC 主发布密钥"),
|
||||||
|
|
||||||
|
// 已停用(私钥遗失):保留仅为兼容历史诊断输出,不能用于验签新清单。
|
||||||
new KeyEntry(
|
new KeyEntry(
|
||||||
"gc-2026-11",
|
"gc-2026-11",
|
||||||
"MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEny5YKVBZUzOyRcSiuutlGmBb4+xm" +
|
"MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEny5YKVBZUzOyRcSiuutlGmBb4+xm" +
|
||||||
"PrNDGshilBlpmFyWu5Atq+FGP2tn+8Or8V7OH+/7lhCmXu8jZuC5/5CWSw==",
|
"PrNDGshilBlpmFyWu5Atq+FGP2tn+8Or8V7OH+/7lhCmXu8jZuC5/5CWSw==",
|
||||||
"GC 主发布密钥")
|
"已停用:私钥遗失")
|
||||||
};
|
};
|
||||||
|
|
||||||
static SignatureKeyring() => LoadFromEnvironment();
|
static SignatureKeyring() => LoadFromEnvironment();
|
||||||
|
|||||||
@@ -8,12 +8,15 @@ namespace GC.Services;
|
|||||||
/// 运行目录约定(可执行文件旁边,不内置任何模型):
|
/// 运行目录约定(可执行文件旁边,不内置任何模型):
|
||||||
/// <code>
|
/// <code>
|
||||||
/// <安装目录>/
|
/// <安装目录>/
|
||||||
/// GC(.exe | .app/...)
|
/// GCL(.exe | .app/...)
|
||||||
/// .GC/
|
/// .GC/
|
||||||
/// settings.json 设置与已安装版本记录
|
/// bin/ 非本体文件(守护进程等,随包分发,更新时整目录替换)
|
||||||
|
/// config/ 设置与已安装版本记录(settings.json)
|
||||||
/// model/ 模型(启动时下载)
|
/// model/ 模型(启动时下载)
|
||||||
/// cache/ 下载缓存 / 原子替换暂存
|
/// cache/ 下载缓存 / 原子替换暂存
|
||||||
/// update/ 待下次启动应用的启动器更新包
|
/// update/ 待下次启动应用的启动器更新包
|
||||||
|
/// safedog/ 更新守护进程的运行副本(首次启动从 .GC/bin 复制过来)
|
||||||
|
/// logs/ 日志,按天分中英两份:gc-YYYYMMDD.log / .en.log
|
||||||
/// </code>
|
/// </code>
|
||||||
/// 开发态同样使用仓库根 .GC/model,并自动同步仓库 model/ 的可分发部分。
|
/// 开发态同样使用仓库根 .GC/model,并自动同步仓库 model/ 的可分发部分。
|
||||||
/// EMS_MODELS / EMS_DATA / EMS_HOME 可显式覆盖。
|
/// EMS_MODELS / EMS_DATA / EMS_HOME 可显式覆盖。
|
||||||
@@ -40,6 +43,12 @@ public sealed class AppPaths
|
|||||||
public string CacheRoot => Path.Combine(HomeRoot, "cache");
|
public string CacheRoot => Path.Combine(HomeRoot, "cache");
|
||||||
public string UpdateRoot => Path.Combine(HomeRoot, "update");
|
public string UpdateRoot => Path.Combine(HomeRoot, "update");
|
||||||
|
|
||||||
|
/// <summary>日志目录:<c>.GC/logs</c>,里面按天放中英两份日志。</summary>
|
||||||
|
public string LogsRoot => Path.Combine(HomeRoot, "logs");
|
||||||
|
|
||||||
|
/// <summary>守护进程目录:<c>.GC/safedog</c>(程序本体与用户数据分开)。</summary>
|
||||||
|
public string SafedogRoot => Path.Combine(HomeRoot, "safedog");
|
||||||
|
|
||||||
/// <summary>用户配置目录(与可重建的缓存分开,删 cache 不会丢设置)。</summary>
|
/// <summary>用户配置目录(与可重建的缓存分开,删 cache 不会丢设置)。</summary>
|
||||||
public string ConfigRoot => Path.Combine(HomeRoot, "config");
|
public string ConfigRoot => Path.Combine(HomeRoot, "config");
|
||||||
|
|
||||||
@@ -255,6 +264,8 @@ public sealed class AppPaths
|
|||||||
Directory.CreateDirectory(CacheRoot);
|
Directory.CreateDirectory(CacheRoot);
|
||||||
Directory.CreateDirectory(ModelRoot);
|
Directory.CreateDirectory(ModelRoot);
|
||||||
Directory.CreateDirectory(UpdateRoot);
|
Directory.CreateDirectory(UpdateRoot);
|
||||||
|
Directory.CreateDirectory(LogsRoot);
|
||||||
|
Directory.CreateDirectory(SafedogRoot);
|
||||||
|
|
||||||
MigrateLegacySettings();
|
MigrateLegacySettings();
|
||||||
|
|
||||||
|
|||||||
@@ -61,6 +61,9 @@ public static class ContributorsService
|
|||||||
["2509_92447106"] = "Morris",
|
["2509_92447106"] = "Morris",
|
||||||
["chenmoyuan1214@qq.com"] = "Morris",
|
["chenmoyuan1214@qq.com"] = "Morris",
|
||||||
["morris@xhmcl.com"] = "Morris",
|
["morris@xhmcl.com"] = "Morris",
|
||||||
|
// 早期提交用的是 xhgit 这个账号,展示名统一成 itxiaohui
|
||||||
|
["xhgit"] = "itxiaohui",
|
||||||
|
["itxiaohui"] = "itxiaohui",
|
||||||
};
|
};
|
||||||
|
|
||||||
/// <summary>自动化提交(CI / 助手账号),不计入开发者。</summary>
|
/// <summary>自动化提交(CI / 助手账号),不计入开发者。</summary>
|
||||||
|
|||||||
@@ -115,7 +115,6 @@ public static class DownloadModuleHost
|
|||||||
public static class LauncherRuntimeInfo
|
public static class LauncherRuntimeInfo
|
||||||
{
|
{
|
||||||
private static string? _versionOverride;
|
private static string? _versionOverride;
|
||||||
|
|
||||||
public static string CurrentLauncherVersion
|
public static string CurrentLauncherVersion
|
||||||
{
|
{
|
||||||
get
|
get
|
||||||
@@ -155,3 +154,30 @@ public static class LauncherRuntimeInfo
|
|||||||
|
|
||||||
public static void OverrideLauncherVersion(string? version) => _versionOverride = version;
|
public static void OverrideLauncherVersion(string? version) => _versionOverride = version;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 界面(Flutter)与后端(GC.UI.Server)之间的约定:端口、环境变量名。
|
||||||
|
///
|
||||||
|
/// 之前这个端口在 GC-BOOT、后端、Flutter 前端各写了一遍 17890,改一处就断链;
|
||||||
|
/// 现在统一由这里定义,启动器选好端口后通过环境变量传给另外两边。
|
||||||
|
/// </summary>
|
||||||
|
public static class GcUiContract
|
||||||
|
{
|
||||||
|
/// <summary>默认端口(与历史版本保持一致,便于复用已在运行的后端)。</summary>
|
||||||
|
public const int DefaultPort = 17890;
|
||||||
|
|
||||||
|
/// <summary>端口被占用时最多向后尝试几个。</summary>
|
||||||
|
public const int PortScanRange = 10;
|
||||||
|
|
||||||
|
/// <summary>传给后端与前端的环境变量名。</summary>
|
||||||
|
public const string PortEnvVar = "GC_UI_PORT";
|
||||||
|
|
||||||
|
/// <summary>读取环境变量里指定的端口;非法或未设置时返回 <see cref="DefaultPort"/>。</summary>
|
||||||
|
public static int PortFromEnvironment()
|
||||||
|
{
|
||||||
|
var value = Environment.GetEnvironmentVariable(PortEnvVar);
|
||||||
|
return int.TryParse(value, out var port) && port > 0 && port < 65536
|
||||||
|
? port
|
||||||
|
: DefaultPort;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,206 @@
|
|||||||
|
using System;
|
||||||
|
using System.Globalization;
|
||||||
|
using System.IO;
|
||||||
|
using System.Text;
|
||||||
|
|
||||||
|
namespace GC.Services;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 双语文件日志。
|
||||||
|
///
|
||||||
|
/// 每条记录同时写两个文件(都在 <c>.GC/logs</c> 下,按天滚动):
|
||||||
|
/// <code>
|
||||||
|
/// gc-20261118.log 中文
|
||||||
|
/// gc-20261118.en.log 英文
|
||||||
|
/// </code>
|
||||||
|
/// 中英分开而不是写在一个文件里:用户排查时不用在一行里找自己看得懂的那半句;
|
||||||
|
/// 也给反馈问题时直接发对应语言的文件即可。
|
||||||
|
///
|
||||||
|
/// 写入方式:常驻 <see cref="StreamWriter"/>(<c>AutoFlush</c> 打开,崩溃也不丢最后几行),
|
||||||
|
/// 不再每行 open/append/close 一遍 —— 那条路径每写一行要开两个文件句柄,
|
||||||
|
/// 在下载 / 启动高峰期会明显拖慢调用方。
|
||||||
|
///
|
||||||
|
/// 保留策略:<see cref="RetentionDays"/> 天之前的日志在初始化与跨天滚动时删除;
|
||||||
|
/// 总量超过 <see cref="MaxTotalBytes"/> 时从最旧的开始删。日志目录不会无限长。
|
||||||
|
///
|
||||||
|
/// 日志失败绝不影响主流程(磁盘满、只读目录都只是少一份日志)。
|
||||||
|
/// </summary>
|
||||||
|
public static class GcLog
|
||||||
|
{
|
||||||
|
/// <summary>日志保留天数。</summary>
|
||||||
|
public const int RetentionDays = 14;
|
||||||
|
|
||||||
|
/// <summary>日志目录总量上限(中英两份合计)。</summary>
|
||||||
|
public const long MaxTotalBytes = 64L * 1024 * 1024;
|
||||||
|
|
||||||
|
private static readonly object Gate = new();
|
||||||
|
private const string FilePrefix = "gc-";
|
||||||
|
|
||||||
|
private static string? _dir;
|
||||||
|
private static string _day = "";
|
||||||
|
private static StreamWriter? _zh;
|
||||||
|
private static StreamWriter? _en;
|
||||||
|
|
||||||
|
public static bool Enabled
|
||||||
|
{
|
||||||
|
get { lock (Gate) return _dir != null; }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>绑定日志目录(通常是 <c>.GC/logs</c>)。重复调用会切到新目录。</summary>
|
||||||
|
public static void Init(string dir)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
Directory.CreateDirectory(dir);
|
||||||
|
}
|
||||||
|
catch
|
||||||
|
{
|
||||||
|
// 目录都建不了就退化成只写控制台
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
lock (Gate)
|
||||||
|
{
|
||||||
|
CloseWriters();
|
||||||
|
_dir = dir;
|
||||||
|
_day = "";
|
||||||
|
PruneOldFiles(dir);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void Info(string zh, string en) => Write("INFO ", zh, en);
|
||||||
|
public static void Warn(string zh, string en) => Write("WARN ", zh, en);
|
||||||
|
public static void Error(string zh, string en) => Write("ERROR", zh, en);
|
||||||
|
|
||||||
|
private static void Write(string level, string zh, string en)
|
||||||
|
{
|
||||||
|
var now = DateTime.Now;
|
||||||
|
var prefix = $"{now:yyyy-MM-dd HH:mm:ss} [{level}] ";
|
||||||
|
|
||||||
|
try { Console.WriteLine(prefix + zh); } catch { /* 无控制台 */ }
|
||||||
|
|
||||||
|
lock (Gate)
|
||||||
|
{
|
||||||
|
if (_dir == null) return;
|
||||||
|
|
||||||
|
var day = now.ToString("yyyyMMdd");
|
||||||
|
if (day != _day)
|
||||||
|
{
|
||||||
|
// 跨天换文件;顺便清一次旧日志,长时间挂机的进程也不会攒满磁盘
|
||||||
|
CloseWriters();
|
||||||
|
_day = day;
|
||||||
|
PruneOldFiles(_dir);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (_zh == null)
|
||||||
|
{
|
||||||
|
_zh = OpenWriter(Path.Combine(_dir, $"{FilePrefix}{day}.log"));
|
||||||
|
_en = OpenWriter(Path.Combine(_dir, $"{FilePrefix}{day}.en.log"));
|
||||||
|
}
|
||||||
|
|
||||||
|
Append(_zh, prefix + zh);
|
||||||
|
Append(_en, prefix + en);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static StreamWriter? OpenWriter(string path)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var stream = new FileStream(path, FileMode.Append, FileAccess.Write, FileShare.ReadWrite);
|
||||||
|
return new StreamWriter(stream, new UTF8Encoding(false)) { AutoFlush = true };
|
||||||
|
}
|
||||||
|
catch
|
||||||
|
{
|
||||||
|
// 写不了就不写;下一次跨天会再试一次
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void Append(StreamWriter? writer, string line)
|
||||||
|
{
|
||||||
|
if (writer == null) return;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
writer.WriteLine(line);
|
||||||
|
}
|
||||||
|
catch
|
||||||
|
{
|
||||||
|
// 磁盘满 / 文件被删:关掉写入器,下次跨天重建
|
||||||
|
try { writer.Dispose(); } catch { }
|
||||||
|
if (ReferenceEquals(writer, _zh)) _zh = null; else _en = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void CloseWriters()
|
||||||
|
{
|
||||||
|
try { _zh?.Dispose(); } catch { }
|
||||||
|
try { _en?.Dispose(); } catch { }
|
||||||
|
_zh = null;
|
||||||
|
_en = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 清理过期与超量日志。只动本模块自己写的 <c>gc-YYYYMMDD[.en].log</c>,
|
||||||
|
/// 目录里用户放的其他文件一概不碰。
|
||||||
|
/// </summary>
|
||||||
|
private static void PruneOldFiles(string dir)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var files = new DirectoryInfo(dir).GetFiles(FilePrefix + "*.log");
|
||||||
|
if (files.Length == 0) return;
|
||||||
|
|
||||||
|
var cutoff = DateTime.Now.Date.AddDays(-RetentionDays);
|
||||||
|
var alive = new System.Collections.Generic.List<FileInfo>(files.Length);
|
||||||
|
foreach (var file in files)
|
||||||
|
{
|
||||||
|
if (!TryReadDate(file.Name, out var date))
|
||||||
|
{
|
||||||
|
// 名字不是我们的格式,忽略(既不删也不计入配额)
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (date < cutoff)
|
||||||
|
{
|
||||||
|
try { file.Delete(); } catch { }
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
alive.Add(file);
|
||||||
|
}
|
||||||
|
|
||||||
|
long total = 0;
|
||||||
|
foreach (var file in alive) total += file.Length;
|
||||||
|
if (total <= MaxTotalBytes) return;
|
||||||
|
|
||||||
|
alive.Sort((a, b) => a.LastWriteTimeUtc.CompareTo(b.LastWriteTimeUtc));
|
||||||
|
foreach (var file in alive)
|
||||||
|
{
|
||||||
|
if (total <= MaxTotalBytes) break;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
total -= file.Length;
|
||||||
|
file.Delete();
|
||||||
|
}
|
||||||
|
catch { }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch
|
||||||
|
{
|
||||||
|
// 清理失败不影响写日志
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static bool TryReadDate(string name, out DateTime date)
|
||||||
|
{
|
||||||
|
date = default;
|
||||||
|
// gc-20261118.log / gc-20261118.en.log
|
||||||
|
if (!name.StartsWith(FilePrefix, StringComparison.Ordinal)) return false;
|
||||||
|
var rest = name.Substring(FilePrefix.Length);
|
||||||
|
var dot = rest.IndexOf('.');
|
||||||
|
if (dot != 8) return false;
|
||||||
|
return DateTime.TryParseExact(rest.Substring(0, 8), "yyyyMMdd",
|
||||||
|
CultureInfo.InvariantCulture, DateTimeStyles.None, out date);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -9,10 +9,26 @@ namespace GC.Services;
|
|||||||
/// <summary>
|
/// <summary>
|
||||||
/// 本地模型库。启动器只**扫描 / 删除**模型包,不再解析或缓存任何场景数据 ——
|
/// 本地模型库。启动器只**扫描 / 删除**模型包,不再解析或缓存任何场景数据 ——
|
||||||
/// 场景、贴图、界面都由模型自己的程序集负责。
|
/// 场景、贴图、界面都由模型自己的程序集负责。
|
||||||
|
///
|
||||||
|
/// 扫描结果与目录体积都做短时缓存:前端(首页 / 下载页)会频繁轮询
|
||||||
|
/// <c>/api/models</c>,而每个模型的体积要递归遍历整棵目录。没有缓存时
|
||||||
|
/// 一次刷新就是成千上万次 stat,低配机器上会明显卡顿。
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public sealed class ModelRepository
|
public sealed class ModelRepository
|
||||||
{
|
{
|
||||||
|
/// <summary>扫描结果缓存时长:够挡住连点刷新,又不会让手动放进来的模型等太久。</summary>
|
||||||
|
private static readonly TimeSpan ScanTtl = TimeSpan.FromSeconds(2);
|
||||||
|
|
||||||
|
/// <summary>目录体积缓存时长(目录 mtime 变了会提前失效)。</summary>
|
||||||
|
private static readonly TimeSpan SizeTtl = TimeSpan.FromMinutes(1);
|
||||||
|
|
||||||
private readonly AppPaths _paths;
|
private readonly AppPaths _paths;
|
||||||
|
private readonly object _gate = new();
|
||||||
|
private readonly Dictionary<string, (long Size, DateTime Stamp, DateTime At)> _sizes =
|
||||||
|
new(StringComparer.OrdinalIgnoreCase);
|
||||||
|
|
||||||
|
private List<ModelPackage>? _cache;
|
||||||
|
private DateTime _cacheAt = DateTime.MinValue;
|
||||||
|
|
||||||
public ModelRepository(AppPaths paths) => _paths = paths;
|
public ModelRepository(AppPaths paths) => _paths = paths;
|
||||||
|
|
||||||
@@ -20,7 +36,13 @@ public sealed class ModelRepository
|
|||||||
|
|
||||||
public IReadOnlyList<ModelPackage> Scan()
|
public IReadOnlyList<ModelPackage> Scan()
|
||||||
{
|
{
|
||||||
|
lock (_gate)
|
||||||
|
{
|
||||||
|
if (_cache != null && DateTime.UtcNow - _cacheAt < ScanTtl) return _cache;
|
||||||
|
}
|
||||||
|
|
||||||
_paths.WaitForDevelopmentModels();
|
_paths.WaitForDevelopmentModels();
|
||||||
|
|
||||||
var result = new List<ModelPackage>();
|
var result = new List<ModelPackage>();
|
||||||
foreach (var (manifest, dir) in ModelScanner.Scan(_paths.ModelRoot))
|
foreach (var (manifest, dir) in ModelScanner.Scan(_paths.ModelRoot))
|
||||||
{
|
{
|
||||||
@@ -28,13 +50,20 @@ public sealed class ModelRepository
|
|||||||
{
|
{
|
||||||
Manifest = manifest,
|
Manifest = manifest,
|
||||||
Directory = dir,
|
Directory = dir,
|
||||||
SizeBytes = ModelScanner.DirectorySize(dir)
|
SizeBytes = SizeOf(dir)
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
lock (_gate)
|
||||||
|
{
|
||||||
|
_cache = result;
|
||||||
|
_cacheAt = DateTime.UtcNow;
|
||||||
|
}
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
public ModelPackage? Find(string id) => Scan().FirstOrDefault(p => p.Id.Equals(id, StringComparison.OrdinalIgnoreCase));
|
public ModelPackage? Find(string id)
|
||||||
|
=> Scan().FirstOrDefault(p => p.Id.Equals(id, StringComparison.OrdinalIgnoreCase));
|
||||||
|
|
||||||
public bool Delete(string id)
|
public bool Delete(string id)
|
||||||
{
|
{
|
||||||
@@ -43,6 +72,7 @@ public sealed class ModelRepository
|
|||||||
try
|
try
|
||||||
{
|
{
|
||||||
Directory.Delete(package.Directory, true);
|
Directory.Delete(package.Directory, true);
|
||||||
|
Invalidate();
|
||||||
Changed?.Invoke();
|
Changed?.Invoke();
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
@@ -53,5 +83,40 @@ public sealed class ModelRepository
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public void NotifyChanged() => Changed?.Invoke();
|
public void NotifyChanged()
|
||||||
|
{
|
||||||
|
Invalidate();
|
||||||
|
Changed?.Invoke();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>清空缓存:模型被安装 / 删除 / 覆盖后必须调用。</summary>
|
||||||
|
private void Invalidate()
|
||||||
|
{
|
||||||
|
lock (_gate)
|
||||||
|
{
|
||||||
|
_cache = null;
|
||||||
|
_cacheAt = DateTime.MinValue;
|
||||||
|
}
|
||||||
|
lock (_sizes) _sizes.Clear();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>目录体积,按「目录 mtime + TTL」缓存。</summary>
|
||||||
|
private long SizeOf(string dir)
|
||||||
|
{
|
||||||
|
DateTime stamp;
|
||||||
|
try { stamp = Directory.GetLastWriteTimeUtc(dir); }
|
||||||
|
catch { stamp = DateTime.MinValue; }
|
||||||
|
|
||||||
|
lock (_sizes)
|
||||||
|
{
|
||||||
|
if (_sizes.TryGetValue(dir, out var cached) &&
|
||||||
|
cached.Stamp == stamp &&
|
||||||
|
DateTime.UtcNow - cached.At < SizeTtl)
|
||||||
|
return cached.Size;
|
||||||
|
}
|
||||||
|
|
||||||
|
var size = ModelScanner.DirectorySize(dir);
|
||||||
|
lock (_sizes) _sizes[dir] = (size, stamp, DateTime.UtcNow);
|
||||||
|
return size;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -21,7 +21,7 @@ public sealed class ReleaseInfo
|
|||||||
public string Version => NormalizeVersion(TagName, Name);
|
public string Version => NormalizeVersion(TagName, Name);
|
||||||
|
|
||||||
private static readonly string[] VersionPrefixes =
|
private static readonly string[] VersionPrefixes =
|
||||||
{ "v", "V", "GC-", "gc-", "release-", "Release-" };
|
{ "v", "V", "GCL-", "gcl-", "GC-", "gc-", "release-", "Release-" };
|
||||||
|
|
||||||
private static readonly string[] PrereleaseTags =
|
private static readonly string[] PrereleaseTags =
|
||||||
{ "alpha", "beta", "rc", "pre", "dev", "snapshot" };
|
{ "alpha", "beta", "rc", "pre", "dev", "snapshot" };
|
||||||
@@ -31,7 +31,7 @@ public sealed class ReleaseInfo
|
|||||||
var raw = !string.IsNullOrWhiteSpace(tag) ? tag : name;
|
var raw = !string.IsNullOrWhiteSpace(tag) ? tag : name;
|
||||||
if (string.IsNullOrWhiteSpace(raw)) return "";
|
if (string.IsNullOrWhiteSpace(raw)) return "";
|
||||||
raw = raw!.Trim();
|
raw = raw!.Trim();
|
||||||
// "v1.0.1" / "GC-1.0.1" / "release-1.0.1" -> 取第一段像版本号的部分
|
// "v1.0.1" / "GCL-1.0.1" / "GC-1.0.1" / "release-1.0.1" -> 取第一段像版本号的部分
|
||||||
foreach (var prefix in VersionPrefixes)
|
foreach (var prefix in VersionPrefixes)
|
||||||
if (raw.StartsWith(prefix, StringComparison.Ordinal)) { raw = raw[prefix.Length..]; break; }
|
if (raw.StartsWith(prefix, StringComparison.Ordinal)) { raw = raw[prefix.Length..]; break; }
|
||||||
// 形如 GC-1.0.1-Win-amd64 时只取版本段;但 2.3.0-beta 这类预发布串要保留完整。
|
// 形如 GC-1.0.1-Win-amd64 时只取版本段;但 2.3.0-beta 这类预发布串要保留完整。
|
||||||
|
|||||||
@@ -0,0 +1,124 @@
|
|||||||
|
using System;
|
||||||
|
using System.IO;
|
||||||
|
|
||||||
|
namespace GC.Services;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 运行期目录准备:
|
||||||
|
/// <list type="number">
|
||||||
|
/// <item>创建 <c>.GC/logs</c> 与 <c>.GC/safedog</c>;</item>
|
||||||
|
/// <item>把包内 <c>.GC/bin</c> 里的守护进程复制到 <c>.GC/safedog</c>(非本体文件不散落在安装目录);</item>
|
||||||
|
/// <item>初始化双语日志并写一条启动记录。</item>
|
||||||
|
/// </list>
|
||||||
|
///
|
||||||
|
/// 为什么要复制而不是直接用包里的:更新时会整目录替换程序文件,
|
||||||
|
/// 正在运行的守护进程无法被覆盖。放到 .GC 后,整目录替换永远不碰它,
|
||||||
|
/// 新版守护进程在下一次启动时复制进来即可。
|
||||||
|
/// </summary>
|
||||||
|
public static class RuntimeLayout
|
||||||
|
{
|
||||||
|
/// <summary>准备目录与日志,返回实际使用的守护进程路径(可能为 null)。</summary>
|
||||||
|
public static string? Ensure(AppPaths paths)
|
||||||
|
{
|
||||||
|
try { Directory.CreateDirectory(paths.LogsRoot); } catch { }
|
||||||
|
try { Directory.CreateDirectory(paths.SafedogRoot); } catch { }
|
||||||
|
|
||||||
|
GcLog.Init(paths.LogsRoot);
|
||||||
|
|
||||||
|
var safedog = InstallSafedog(paths);
|
||||||
|
|
||||||
|
GcLog.Info(
|
||||||
|
$"启动 GC {LauncherRuntimeInfo.CurrentLauncherVersion}({LauncherRuntimeInfo.CurrentRid})," +
|
||||||
|
$"数据目录 {paths.HomeRoot},守护进程 {(safedog == null ? "未找到" : Path.GetFileName(safedog))}",
|
||||||
|
$"Starting GC {LauncherRuntimeInfo.CurrentLauncherVersion} ({LauncherRuntimeInfo.CurrentRid}), " +
|
||||||
|
$"data directory {paths.HomeRoot}, safedog {(safedog == null ? "not found" : Path.GetFileName(safedog))}");
|
||||||
|
|
||||||
|
return safedog;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>把包内 <c>.GC/bin</c> 的守护进程同步到 <c>.GC/safedog</c>。已是最新则不动。</summary>
|
||||||
|
private static string? InstallSafedog(AppPaths paths)
|
||||||
|
{
|
||||||
|
var name = SavedogFiles.ExecutableName;
|
||||||
|
var target = Path.Combine(paths.SafedogRoot, name);
|
||||||
|
|
||||||
|
var source = FindPackaged(paths, name);
|
||||||
|
if (source != null && NeedsCopy(source, target))
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
Directory.CreateDirectory(paths.SafedogRoot);
|
||||||
|
File.Copy(source, target, overwrite: true);
|
||||||
|
MarkExecutable(target);
|
||||||
|
GcLog.Info($"已更新守护进程到 {target}", $"Safedog updated at {target}");
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
GcLog.Warn($"复制守护进程失败(继续使用已有版本):{ex.Message}",
|
||||||
|
$"Failed to copy safedog (falling back to the existing one): {ex.Message}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return File.Exists(target) ? target : source;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string? FindPackaged(AppPaths paths, string name)
|
||||||
|
{
|
||||||
|
// 包内非本体文件统一收在 .GC/bin;后面几项兼容 1.0.10 及更早的包布局
|
||||||
|
var candidates = new[]
|
||||||
|
{
|
||||||
|
Path.Combine(paths.HomeRoot, "bin", name),
|
||||||
|
Path.Combine(paths.InstallDirectory, ".GC", "bin", name),
|
||||||
|
Path.Combine(paths.InstallDirectory, "safedog", name),
|
||||||
|
Path.Combine(paths.InstallDirectory, name),
|
||||||
|
Path.Combine(paths.AppRoot, ".GC", "bin", name),
|
||||||
|
Path.Combine(paths.AppRoot, "safedog", name),
|
||||||
|
Path.Combine(paths.AppRoot, name),
|
||||||
|
};
|
||||||
|
|
||||||
|
foreach (var candidate in candidates)
|
||||||
|
{
|
||||||
|
if (File.Exists(candidate)) return candidate;
|
||||||
|
}
|
||||||
|
|
||||||
|
// macOS:可能在 .app/Contents/MacOS 里
|
||||||
|
try
|
||||||
|
{
|
||||||
|
foreach (var app in Directory.GetDirectories(paths.InstallDirectory, "*.app"))
|
||||||
|
{
|
||||||
|
var inside = Path.Combine(app, "Contents", "MacOS", name);
|
||||||
|
if (File.Exists(inside)) return inside;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch { }
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static bool NeedsCopy(string source, string target)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
if (!File.Exists(target)) return true;
|
||||||
|
var a = new FileInfo(source);
|
||||||
|
var b = new FileInfo(target);
|
||||||
|
return a.Length != b.Length || a.LastWriteTimeUtc > b.LastWriteTimeUtc;
|
||||||
|
}
|
||||||
|
catch
|
||||||
|
{
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void MarkExecutable(string path)
|
||||||
|
{
|
||||||
|
if (OperatingSystem.IsWindows()) return;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var mode = File.GetUnixFileMode(path);
|
||||||
|
File.SetUnixFileMode(path, mode | UnixFileMode.UserExecute |
|
||||||
|
UnixFileMode.GroupExecute | UnixFileMode.OtherExecute);
|
||||||
|
}
|
||||||
|
catch { }
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -28,7 +28,7 @@
|
|||||||
<TextBlock Classes="faint" Text="{Binding PlatformText}" />
|
<TextBlock Classes="faint" Text="{Binding PlatformText}" />
|
||||||
</StackPanel>
|
</StackPanel>
|
||||||
|
|
||||||
<Grid ColumnDefinitions="96,*" RowDefinitions="Auto,Auto">
|
<Grid ColumnDefinitions="96,*" RowDefinitions="Auto,Auto,Auto">
|
||||||
<TextBlock Classes="h3" Text="版本" />
|
<TextBlock Classes="h3" Text="版本" />
|
||||||
<TextBlock Grid.Column="1" Classes="muted" Text="{Binding VersionText}"
|
<TextBlock Grid.Column="1" Classes="muted" Text="{Binding VersionText}"
|
||||||
FontWeight="SemiBold" />
|
FontWeight="SemiBold" />
|
||||||
@@ -38,6 +38,10 @@
|
|||||||
HorizontalAlignment="Left" Padding="0"
|
HorizontalAlignment="Left" Padding="0"
|
||||||
Command="{Binding OpenRepositoryCommand}"
|
Command="{Binding OpenRepositoryCommand}"
|
||||||
Content="{Binding RepositoryText}" />
|
Content="{Binding RepositoryText}" />
|
||||||
|
|
||||||
|
<TextBlock Grid.Row="2" Classes="h3" Text="Git 服务" Margin="0,8,0,0" />
|
||||||
|
<TextBlock Grid.Row="2" Grid.Column="1" Classes="muted" Text="itxiaohui"
|
||||||
|
FontWeight="SemiBold" Margin="0,8,0,0" />
|
||||||
</Grid>
|
</Grid>
|
||||||
</StackPanel>
|
</StackPanel>
|
||||||
</Grid>
|
</Grid>
|
||||||
@@ -76,6 +80,22 @@
|
|||||||
</StackPanel>
|
</StackPanel>
|
||||||
</StackPanel>
|
</StackPanel>
|
||||||
</Border>
|
</Border>
|
||||||
|
|
||||||
|
<Border Background="{DynamicResource SurfaceAlt}"
|
||||||
|
BorderBrush="{DynamicResource Line}" BorderThickness="1"
|
||||||
|
CornerRadius="12" Padding="12,10" MinWidth="190">
|
||||||
|
<StackPanel Orientation="Horizontal" Spacing="10">
|
||||||
|
<Border Width="34" Height="34" CornerRadius="17"
|
||||||
|
Background="{DynamicResource AccentSoft}">
|
||||||
|
<TextBlock Text="◉" FontSize="15" Foreground="{DynamicResource Accent}"
|
||||||
|
HorizontalAlignment="Center" VerticalAlignment="Center" />
|
||||||
|
</Border>
|
||||||
|
<StackPanel VerticalAlignment="Center" Spacing="1">
|
||||||
|
<TextBlock Text="itxiaohui" FontSize="12.5" FontWeight="SemiBold" />
|
||||||
|
<TextBlock Classes="faint" Text="Git 服务与部署支持" />
|
||||||
|
</StackPanel>
|
||||||
|
</StackPanel>
|
||||||
|
</Border>
|
||||||
</StackPanel>
|
</StackPanel>
|
||||||
</StackPanel>
|
</StackPanel>
|
||||||
</Border>
|
</Border>
|
||||||
|
|||||||
@@ -0,0 +1,293 @@
|
|||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.IO;
|
||||||
|
using System.IO.Compression;
|
||||||
|
using System.Linq;
|
||||||
|
using System.Security.Cryptography;
|
||||||
|
using System.Text;
|
||||||
|
using GC.Savedog;
|
||||||
|
|
||||||
|
namespace GC.Savedog.Tests;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// GC-SAVEDOG 的应用器测试:更新真正落盘的那一段(整目录替换 / .GC/bin 合并 / 失败回滚)。
|
||||||
|
///
|
||||||
|
/// 为什么单独一个工程:<c>GC.Tests</c> 引用的是启动器程序集,而 GC-SAVEDOG 为了保持
|
||||||
|
/// 「安全逻辑只有一份实现」把 <c>GC/src/Security</c> 与 <c>Json.cs</c> 以源码链接的方式
|
||||||
|
/// 编进了自己 —— 两个程序集里存在同名类型。同一个测试工程里同时引用两者会撞类型,
|
||||||
|
/// 所以应用器测试单独放这里,只引用守护进程。
|
||||||
|
///
|
||||||
|
/// 为什么需要这组用例:<c>--update-test</c> 覆盖的是「怎么判断该不该更新」,
|
||||||
|
/// <see cref="Applier"/> 才是会动用户安装目录的代码 —— 它出错就是用户目录被删空。
|
||||||
|
/// 全部在临时目录里跑,不碰真实安装、不联网。
|
||||||
|
/// </summary>
|
||||||
|
internal static class ApplierTests
|
||||||
|
{
|
||||||
|
private static int _failed;
|
||||||
|
private static string _root = "";
|
||||||
|
|
||||||
|
public static int Main()
|
||||||
|
{
|
||||||
|
_root = Path.Combine(Path.GetTempPath(), "gc-applier-" + Guid.NewGuid().ToString("N")[..8]);
|
||||||
|
Directory.CreateDirectory(_root);
|
||||||
|
Console.WriteLine("Applier 测试目录: " + _root);
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
CaseRefusesTraversalPackageName();
|
||||||
|
CaseRefusesShaMismatch();
|
||||||
|
CaseRefusesSourceTree();
|
||||||
|
CaseDryRunKeepsInstallUntouched();
|
||||||
|
CaseRollbackRestoresOldFiles();
|
||||||
|
CaseSuccessMergesGcBinAndKeepsUserData();
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
try { Directory.Delete(_root, true); } catch { }
|
||||||
|
}
|
||||||
|
|
||||||
|
Console.WriteLine(_failed == 0
|
||||||
|
? "Applier 测试全部通过"
|
||||||
|
: $"Applier 测试失败 {_failed} 项");
|
||||||
|
return _failed == 0 ? 0 : 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------------ 用例
|
||||||
|
|
||||||
|
/// <summary>包名带 ../ 时必须拒绝(路径穿越的第一道闸)。</summary>
|
||||||
|
private static void CaseRefusesTraversalPackageName()
|
||||||
|
{
|
||||||
|
var (install, update) = Sandbox("traversal");
|
||||||
|
WritePackage(update, new Dictionary<string, string>
|
||||||
|
{
|
||||||
|
["GCL-9.9.9-test-amd64.exe"] = "new"
|
||||||
|
});
|
||||||
|
WriteRequest(update, "../evil.exe", sha: null);
|
||||||
|
|
||||||
|
var code = Apply(update, install, dryRun: true);
|
||||||
|
Check("路径穿越的包名被拒绝", code == 3, $"exit={code}(期望 3)");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>zip 内容与清单 sha256 不符时必须丢弃。</summary>
|
||||||
|
private static void CaseRefusesShaMismatch()
|
||||||
|
{
|
||||||
|
var (install, update) = Sandbox("sha");
|
||||||
|
WritePackage(update, new Dictionary<string, string>
|
||||||
|
{
|
||||||
|
["GCL-9.9.9-test-amd64.exe"] = "new"
|
||||||
|
});
|
||||||
|
WriteRequest(update, "GCL-9.9.9-test-amd64.exe", sha: new string('a', 64));
|
||||||
|
|
||||||
|
var code = Apply(update, install, dryRun: true);
|
||||||
|
Check("sha256 不符的包被丢弃", code == 5, $"exit={code}(期望 5)");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>安装目录里有 GC.sln 时拒绝替换 —— 防止误在源码树里跑更新。</summary>
|
||||||
|
private static void CaseRefusesSourceTree()
|
||||||
|
{
|
||||||
|
var (install, update) = Sandbox("srctree");
|
||||||
|
File.WriteAllText(Path.Combine(install, "GC.sln"), "fake solution");
|
||||||
|
var zip = WritePackage(update, new Dictionary<string, string>
|
||||||
|
{
|
||||||
|
["GCL-9.9.9-test-amd64.exe"] = "new"
|
||||||
|
});
|
||||||
|
WriteRequest(update, "GCL-9.9.9-test-amd64.exe", Sha256File(zip));
|
||||||
|
|
||||||
|
var code = Apply(update, install, dryRun: false);
|
||||||
|
Check("源码目录被拒绝替换", code == 4, $"exit={code}(期望 4)");
|
||||||
|
Check("源码目录里的文件没被动过",
|
||||||
|
File.ReadAllText(Path.Combine(install, "GC.sln")) == "fake solution",
|
||||||
|
"GC.sln 内容变了");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>dry-run 只校验不落盘:安装目录必须一个字节都不变。</summary>
|
||||||
|
private static void CaseDryRunKeepsInstallUntouched()
|
||||||
|
{
|
||||||
|
var (install, update) = Sandbox("dryrun");
|
||||||
|
File.WriteAllText(Path.Combine(install, "GCL-1.0.0-test-amd64.exe"), "old");
|
||||||
|
File.WriteAllText(Path.Combine(install, "only-in-old.txt"), "keep me");
|
||||||
|
|
||||||
|
var zip = WritePackage(update, new Dictionary<string, string>
|
||||||
|
{
|
||||||
|
["GCL-9.9.9-test-amd64.exe"] = "new",
|
||||||
|
["GC-UI.exe"] = "ui"
|
||||||
|
});
|
||||||
|
WriteRequest(update, "GCL-9.9.9-test-amd64.exe", Sha256File(zip));
|
||||||
|
|
||||||
|
var code = Apply(update, install, dryRun: true);
|
||||||
|
var names = Directory.GetFileSystemEntries(install).Select(Path.GetFileName).OrderBy(n => n).ToArray();
|
||||||
|
Check("dry-run 返回 0", code == 0, $"exit={code}");
|
||||||
|
Check("dry-run 不改安装目录",
|
||||||
|
names.SequenceEqual(new[] { "GCL-1.0.0-test-amd64.exe", "only-in-old.txt" }),
|
||||||
|
"安装目录变成: " + string.Join(", ", names));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 新版本启动不健康 → 回滚:旧文件原样回来,新包独有的文件被删掉,zip 与申请被清理。
|
||||||
|
/// </summary>
|
||||||
|
private static void CaseRollbackRestoresOldFiles()
|
||||||
|
{
|
||||||
|
var (install, update) = Sandbox("rollback");
|
||||||
|
var oldExe = Path.Combine(install, "GCL-1.0.0-test-amd64.exe");
|
||||||
|
var oldOnly = Path.Combine(install, "only-in-old.txt");
|
||||||
|
File.WriteAllText(oldExe, "old-binary");
|
||||||
|
File.WriteAllText(oldOnly, "old-only");
|
||||||
|
|
||||||
|
// 新版什么都不做直接退出:健康标记不会出现,必然回滚
|
||||||
|
var zip = WritePackage(update, new Dictionary<string, string>
|
||||||
|
{
|
||||||
|
["GCL-9.9.9-test-amd64.exe"] = "#!/bin/sh\nexit 1\n",
|
||||||
|
["only-in-new.txt"] = "new-only"
|
||||||
|
});
|
||||||
|
WriteRequest(update, "GCL-9.9.9-test-amd64.exe", Sha256File(zip));
|
||||||
|
|
||||||
|
var code = Apply(update, install, dryRun: false, timeoutSeconds: 5);
|
||||||
|
Check("启动失败后回滚(exit=8)", code == 8, $"exit={code}(期望 8)");
|
||||||
|
Check("旧启动器被还原",
|
||||||
|
File.Exists(oldExe) && File.ReadAllText(oldExe) == "old-binary",
|
||||||
|
"旧启动器没回来");
|
||||||
|
Check("旧版独有文件被还原",
|
||||||
|
File.Exists(oldOnly) && File.ReadAllText(oldOnly) == "old-only",
|
||||||
|
"旧版独有文件没回来");
|
||||||
|
Check("新包独有文件被删除", !File.Exists(Path.Combine(install, "only-in-new.txt")),
|
||||||
|
"only-in-new.txt 残留");
|
||||||
|
Check("更新包与申请已清理",
|
||||||
|
!File.Exists(Path.Combine(update, "package.zip")) &&
|
||||||
|
!File.Exists(Path.Combine(update, "apply-request.json")),
|
||||||
|
"update 目录里还有残留");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>正常路径:新文件就位、.GC/bin 被合并、.GC 下的用户数据原地不动。</summary>
|
||||||
|
private static void CaseSuccessMergesGcBinAndKeepsUserData()
|
||||||
|
{
|
||||||
|
var (install, update) = Sandbox("success");
|
||||||
|
var updateDirFull = Path.GetFullPath(update);
|
||||||
|
|
||||||
|
// 用户数据:设置、模型、守护进程源文件
|
||||||
|
Directory.CreateDirectory(Path.Combine(install, ".GC", "config"));
|
||||||
|
Directory.CreateDirectory(Path.Combine(install, ".GC", "model", "earth-rotation"));
|
||||||
|
Directory.CreateDirectory(Path.Combine(install, ".GC", "bin"));
|
||||||
|
File.WriteAllText(Path.Combine(install, ".GC", "config", "settings.json"), "{\"theme\":\"dark\"}");
|
||||||
|
File.WriteAllText(Path.Combine(install, ".GC", "model", "earth-rotation", "a.bin"), "model");
|
||||||
|
File.WriteAllText(Path.Combine(install, ".GC", "bin", "GC-SAVEDOG.exe"), "old-savedog");
|
||||||
|
|
||||||
|
// 假启动器:写健康标记后退出,模拟「新版本起来了」
|
||||||
|
var launcher =
|
||||||
|
"#!/bin/sh\n" +
|
||||||
|
"cat > '" + Path.Combine(updateDirFull, "health.json") + "' <<'JSON'\n" +
|
||||||
|
"{\"version\":\"9.9.9\",\"pid\":4242,\"at\":\"2026-01-01T00:00:00Z\",\"ok\":true}\n" +
|
||||||
|
"JSON\n" +
|
||||||
|
"exit 0\n";
|
||||||
|
|
||||||
|
var zip = WritePackage(update, new Dictionary<string, string>
|
||||||
|
{
|
||||||
|
["GCL-9.9.9-test-amd64.exe"] = launcher,
|
||||||
|
[".GC/bin/GC-SAVEDOG.exe"] = "new-savedog",
|
||||||
|
["GC-UI.exe"] = "ui"
|
||||||
|
});
|
||||||
|
WriteRequest(update, "GCL-9.9.9-test-amd64.exe", Sha256File(zip));
|
||||||
|
|
||||||
|
var code = Apply(update, install, dryRun: false, timeoutSeconds: 10);
|
||||||
|
Check("启动健康后更新成功(exit=0)", code == 0, $"exit={code}");
|
||||||
|
Check("新启动器就位",
|
||||||
|
File.Exists(Path.Combine(install, "GCL-9.9.9-test-amd64.exe")), "新启动器缺失");
|
||||||
|
Check("新前端就位", File.Exists(Path.Combine(install, "GC-UI.exe")), "GC-UI.exe 缺失");
|
||||||
|
Check(".GC/bin 被合并",
|
||||||
|
File.ReadAllText(Path.Combine(install, ".GC", "bin", "GC-SAVEDOG.exe")) == "new-savedog",
|
||||||
|
".GC/bin/GC-SAVEDOG.exe 没被替换");
|
||||||
|
Check("用户设置原样保留",
|
||||||
|
File.ReadAllText(Path.Combine(install, ".GC", "config", "settings.json")) == "{\"theme\":\"dark\"}",
|
||||||
|
"settings.json 被覆盖");
|
||||||
|
Check("模型目录原样保留",
|
||||||
|
File.Exists(Path.Combine(install, ".GC", "model", "earth-rotation", "a.bin")),
|
||||||
|
"模型文件被删除");
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------------ 辅助
|
||||||
|
|
||||||
|
private static int Apply(string updateDir, string installDir, bool dryRun, int timeoutSeconds = 10)
|
||||||
|
{
|
||||||
|
var log = new Log(Path.Combine(updateDir, "logs"));
|
||||||
|
var applier = new Applier(new ApplyOptions
|
||||||
|
{
|
||||||
|
UpdateDir = updateDir,
|
||||||
|
InstallDir = installDir,
|
||||||
|
DryRun = dryRun,
|
||||||
|
TimeoutSeconds = timeoutSeconds,
|
||||||
|
RequireSignature = false, // 用例不生成签名清单;验签本身由 --update-test 覆盖
|
||||||
|
Force = false
|
||||||
|
}, log);
|
||||||
|
return applier.Run();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static (string Install, string Update) Sandbox(string name)
|
||||||
|
{
|
||||||
|
var baseDir = Path.Combine(_root, name);
|
||||||
|
var install = Path.Combine(baseDir, "app");
|
||||||
|
var update = Path.Combine(baseDir, "update");
|
||||||
|
Directory.CreateDirectory(install);
|
||||||
|
Directory.CreateDirectory(update);
|
||||||
|
File.WriteAllText(Path.Combine(update, "version.json"), "{\"launcher\":{\"version\":\"9.9.9\"}}");
|
||||||
|
return (install, update);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string WritePackage(string updateDir, IDictionary<string, string> files)
|
||||||
|
{
|
||||||
|
var zipPath = Path.Combine(updateDir, "package.zip");
|
||||||
|
try { File.Delete(zipPath); } catch { }
|
||||||
|
using (var archive = ZipFile.Open(zipPath, ZipArchiveMode.Create))
|
||||||
|
{
|
||||||
|
foreach (var (name, text) in files)
|
||||||
|
{
|
||||||
|
var entry = archive.CreateEntry(name.Replace('\\', '/'), CompressionLevel.Fastest);
|
||||||
|
using var stream = entry.Open();
|
||||||
|
var bytes = Encoding.UTF8.GetBytes(text);
|
||||||
|
stream.Write(bytes, 0, bytes.Length);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return zipPath;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>手写申请文件:不引用 Json 序列化助手(同名类型在两个程序集里都有)。</summary>
|
||||||
|
private static void WriteRequest(string updateDir, string packageName, string? sha)
|
||||||
|
{
|
||||||
|
var zipPath = Path.Combine(updateDir, "package.zip");
|
||||||
|
var size = File.Exists(zipPath) ? new FileInfo(zipPath).Length : 0;
|
||||||
|
var json = new StringBuilder()
|
||||||
|
.Append("{\n")
|
||||||
|
.Append(" \"schema\": 1,\n")
|
||||||
|
.Append(" \"version\": \"9.9.9\",\n")
|
||||||
|
.Append(" \"rid\": \"test-amd64\",\n")
|
||||||
|
.Append(" \"platformLabel\": \"test-amd64\",\n")
|
||||||
|
.Append(" \"packageName\": ").Append(Quote(packageName)).Append(",\n")
|
||||||
|
.Append(" \"payloadDir\": \"payload\",\n")
|
||||||
|
.Append(" \"installRelative\": \"../app\",\n")
|
||||||
|
.Append(" \"manifestPath\": \"version.json\",\n")
|
||||||
|
.Append(" \"packageZip\": \"package.zip\",\n")
|
||||||
|
.Append(" \"packageSha256\": ").Append(sha == null ? "null" : Quote(sha)).Append(",\n")
|
||||||
|
.Append(" \"packageSize\": ").Append(size).Append(",\n")
|
||||||
|
.Append(" \"requireSignature\": false\n")
|
||||||
|
.Append("}\n")
|
||||||
|
.ToString();
|
||||||
|
File.WriteAllText(Path.Combine(updateDir, "apply-request.json"), json);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string Quote(string value) => "\"" + value.Replace("\\", "\\\\").Replace("\"", "\\\"") + "\"";
|
||||||
|
|
||||||
|
private static string Sha256File(string path)
|
||||||
|
{
|
||||||
|
using var stream = File.OpenRead(path);
|
||||||
|
return Convert.ToHexString(SHA256.HashData(stream)).ToLowerInvariant();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void Check(string label, bool ok, string detail)
|
||||||
|
{
|
||||||
|
if (ok)
|
||||||
|
{
|
||||||
|
Console.WriteLine(" ✓ " + label);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
_failed++;
|
||||||
|
Console.WriteLine($" ✗ {label} —— {detail}");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
<Project Sdk="Microsoft.NET.Sdk">
|
||||||
|
|
||||||
|
<!--
|
||||||
|
应用器测试:只引用 GC-SAVEDOG。
|
||||||
|
|
||||||
|
不并入 GC.Tests 的原因见 ApplierTests.cs 顶部注释 —— 守护进程把 GC/src/Security
|
||||||
|
以源码链接编进了自己,与启动器程序集存在同名类型,同一工程内同时引用会撞类型。
|
||||||
|
-->
|
||||||
|
<PropertyGroup>
|
||||||
|
<OutputType>Exe</OutputType>
|
||||||
|
<Nullable>enable</Nullable>
|
||||||
|
<RootNamespace>GC.Savedog.Tests</RootNamespace>
|
||||||
|
<AssemblyName>GC.Savedog.Tests</AssemblyName>
|
||||||
|
<InvariantGlobalization>true</InvariantGlobalization>
|
||||||
|
</PropertyGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<ProjectReference Include="../../../../../GC-SAVEDOG/GC-SAVEDOG.csproj" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
</Project>
|
||||||
@@ -0,0 +1,67 @@
|
|||||||
|
using System;
|
||||||
|
using System.IO;
|
||||||
|
using System.Linq;
|
||||||
|
using GC.Services;
|
||||||
|
|
||||||
|
namespace GC.Tests;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 日志模块的用例:双语写入、跨天文件命名、旧日志清理、不误删用户文件。
|
||||||
|
///
|
||||||
|
/// 这些看起来是小事,但 <c>.GC/logs</c> 会随程序跑很久:写入路径每行开两个文件句柄,
|
||||||
|
/// 或者完全不清理,都会在几个月后变成用户磁盘上的几 GB。用例锁住这两个行为。
|
||||||
|
/// </summary>
|
||||||
|
internal static class LogTests
|
||||||
|
{
|
||||||
|
private static int _failed;
|
||||||
|
|
||||||
|
public static int Run()
|
||||||
|
{
|
||||||
|
var dir = Path.Combine(Path.GetTempPath(), "gc-log-" + Guid.NewGuid().ToString("N")[..8]);
|
||||||
|
Directory.CreateDirectory(dir);
|
||||||
|
try
|
||||||
|
{
|
||||||
|
// 过期日志(2000 年)+ 用户自己的文件
|
||||||
|
var oldZh = Path.Combine(dir, "gc-20000101.log");
|
||||||
|
var oldEn = Path.Combine(dir, "gc-20000101.en.log");
|
||||||
|
var userFile = Path.Combine(dir, "keep-me.txt");
|
||||||
|
File.WriteAllText(oldZh, "old");
|
||||||
|
File.WriteAllText(oldEn, "old");
|
||||||
|
File.WriteAllText(userFile, "user data");
|
||||||
|
|
||||||
|
GcLog.Init(dir);
|
||||||
|
GcLog.Info("测试中文", "test english");
|
||||||
|
|
||||||
|
var day = DateTime.Now.ToString("yyyyMMdd");
|
||||||
|
var zhPath = Path.Combine(dir, $"gc-{day}.log");
|
||||||
|
var enPath = Path.Combine(dir, $"gc-{day}.en.log");
|
||||||
|
|
||||||
|
Check("中文日志写入", File.Exists(zhPath) && File.ReadAllText(zhPath).Contains("测试中文"), "中文日志缺失");
|
||||||
|
Check("英文日志写入", File.Exists(enPath) && File.ReadAllText(enPath).Contains("test english"), "英文日志缺失");
|
||||||
|
Check("过期日志被清理", !File.Exists(oldZh) && !File.Exists(oldEn), "2000 年的日志还在");
|
||||||
|
Check("目录里的用户文件不被误删", File.Exists(userFile), "keep-me.txt 被删了");
|
||||||
|
|
||||||
|
var names = Directory.GetFiles(dir).Select(Path.GetFileName).OrderBy(n => n).ToArray();
|
||||||
|
Check("日志目录只剩当天两份 + 用户文件",
|
||||||
|
names.Length == 3, "目录内容: " + string.Join(", ", names));
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
try { Directory.Delete(dir, true); } catch { }
|
||||||
|
}
|
||||||
|
|
||||||
|
Console.WriteLine(_failed == 0 ? "日志测试全部通过" : $"日志测试失败 {_failed} 项");
|
||||||
|
return _failed;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void Check(string label, bool ok, string detail)
|
||||||
|
{
|
||||||
|
if (ok)
|
||||||
|
{
|
||||||
|
Console.WriteLine(" ✓ " + label);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
_failed++;
|
||||||
|
Console.WriteLine($" ✗ {label} —— {detail}");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -51,7 +51,9 @@ internal static class Program
|
|||||||
RenderPages(services);
|
RenderPages(services);
|
||||||
|
|
||||||
Console.WriteLine("截图输出: " + Path.GetFullPath(_outDir));
|
Console.WriteLine("截图输出: " + Path.GetFullPath(_outDir));
|
||||||
return 0;
|
|
||||||
|
// 日志模块的用例放在渲染之后:它会切换 GcLog 的输出目录
|
||||||
|
return LogTests.Run() == 0 ? 0 : 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@@ -193,7 +195,9 @@ internal static class Program
|
|||||||
Console.WriteLine($"当前平台: {rid},启动器版本: {LauncherRuntimeInfo.CurrentLauncherVersion}");
|
Console.WriteLine($"当前平台: {rid},启动器版本: {LauncherRuntimeInfo.CurrentLauncherVersion}");
|
||||||
var stage = Path.Combine(tmp, "launcher-stage");
|
var stage = Path.Combine(tmp, "launcher-stage");
|
||||||
Directory.CreateDirectory(stage);
|
Directory.CreateDirectory(stage);
|
||||||
File.WriteAllText(Path.Combine(stage, "GC-9.9.9-" + LauncherUpdater.PlatformLabel + ".exe"),
|
// Linux 的启动器没有扩展名,测试包名要跟着平台走
|
||||||
|
var launcherExt = OperatingSystem.IsWindows() ? ".exe" : "";
|
||||||
|
File.WriteAllText(Path.Combine(stage, "GCL-9.9.9-" + LauncherUpdater.PlatformLabel + launcherExt),
|
||||||
"new launcher");
|
"new launcher");
|
||||||
var zip = Path.Combine(tmp, "GC-" + rid + ".zip");
|
var zip = Path.Combine(tmp, "GC-" + rid + ".zip");
|
||||||
ZipFile.CreateFromDirectory(stage, zip);
|
ZipFile.CreateFromDirectory(stage, zip);
|
||||||
@@ -207,7 +211,7 @@ internal static class Program
|
|||||||
WriteSigned(remoteManifest, rv, signer);
|
WriteSigned(remoteManifest, rv, signer);
|
||||||
|
|
||||||
// 造一个旧版在当前目录
|
// 造一个旧版在当前目录
|
||||||
var oldName = "GC-1.0.0-" + LauncherUpdater.PlatformLabel + ".exe";
|
var oldName = "GC-1.0.0-" + LauncherUpdater.PlatformLabel + launcherExt;
|
||||||
File.WriteAllText(Path.Combine(paths.InstallDirectory, oldName), "old launcher");
|
File.WriteAllText(Path.Combine(paths.InstallDirectory, oldName), "old launcher");
|
||||||
|
|
||||||
var dl = Task.Run(() => LauncherUpdater.DownloadAsync(paths, updater.Remote, null))
|
var dl = Task.Run(() => LauncherUpdater.DownloadAsync(paths, updater.Remote, null))
|
||||||
@@ -227,7 +231,8 @@ internal static class Program
|
|||||||
// 5) 校验标记文件与替换脚本(相对路径,无绝对路径)
|
// 5) 校验标记文件与替换脚本(相对路径,无绝对路径)
|
||||||
var marker = Path.Combine(paths.UpdateRoot, "update.txt");
|
var marker = Path.Combine(paths.UpdateRoot, "update.txt");
|
||||||
Check(File.Exists(marker), "写出更新标记 update.txt");
|
Check(File.Exists(marker), "写出更新标记 update.txt");
|
||||||
var scheduled = LauncherUpdater.ScheduleApply(paths, dl.PackageName ?? "");
|
// 只验证脚本内容,不真的执行(否则脚本会在临时目录被删掉后搬文件、刷错误)
|
||||||
|
var scheduled = LauncherUpdater.ScheduleApply(paths, dl.PackageName ?? "", execute: false);
|
||||||
var scriptPath = Path.Combine(paths.UpdateRoot,
|
var scriptPath = Path.Combine(paths.UpdateRoot,
|
||||||
OperatingSystem.IsWindows() ? "apply.bat" : "apply.sh");
|
OperatingSystem.IsWindows() ? "apply.bat" : "apply.sh");
|
||||||
Check(scheduled && File.Exists(scriptPath), "替换脚本可生成");
|
Check(scheduled && File.Exists(scriptPath), "替换脚本可生成");
|
||||||
@@ -235,14 +240,14 @@ internal static class Program
|
|||||||
{
|
{
|
||||||
var script = File.ReadAllText(scriptPath);
|
var script = File.ReadAllText(scriptPath);
|
||||||
Check(!script.Contains(tmp), "脚本不含绝对路径");
|
Check(!script.Contains(tmp), "脚本不含绝对路径");
|
||||||
Check(script.Contains("GC-*.app") || script.Contains("GC-*"), "脚本按 GC-* 匹配删除");
|
Check(script.Contains("GC-*") || script.Contains("GCL-*"), "脚本按 GC-*/GCL-* 匹配删除");
|
||||||
}
|
}
|
||||||
|
|
||||||
// 5b) 只发产物、不发 Release:更新包只存在于仓库 dist/<系统>-<架构>/ 目录里。
|
// 5b) 只发产物、不发 Release:更新包只存在于仓库 dist/<系统>-<架构>/ 目录里。
|
||||||
// 清单不写 url、不写 path,只给 dir + name + sha256,客户端要能自己找过去。
|
// 清单不写 url、不写 path,只给 dir + name + sha256,客户端要能自己找过去。
|
||||||
var distDir = Path.Combine(remote, "dist", LauncherUpdater.PlatformLabel);
|
var distDir = Path.Combine(remote, "dist", LauncherUpdater.PlatformLabel);
|
||||||
Directory.CreateDirectory(distDir);
|
Directory.CreateDirectory(distDir);
|
||||||
var distName = "GC-9.9.10-" + LauncherUpdater.PlatformLabel + ".zip";
|
var distName = "GCL-9.9.10-" + LauncherUpdater.PlatformLabel + ".zip";
|
||||||
var distZip = Path.Combine(distDir, distName);
|
var distZip = Path.Combine(distDir, distName);
|
||||||
File.Copy(zip, distZip, true);
|
File.Copy(zip, distZip, true);
|
||||||
|
|
||||||
@@ -310,8 +315,10 @@ internal static class Program
|
|||||||
/// <summary>序列化清单并用私钥签名(测试里模拟一次正式发布)。</summary>
|
/// <summary>序列化清单并用私钥签名(测试里模拟一次正式发布)。</summary>
|
||||||
private static void WriteSigned(string path, RepoVersion version, ECDsa key)
|
private static void WriteSigned(string path, RepoVersion version, ECDsa key)
|
||||||
{
|
{
|
||||||
|
// keyId 必须与 .signing/ 里的私钥对应的公钥条目一致,否则客户端按 keyId
|
||||||
|
// 查不到受信任公钥,会判成 Invalid 而不是 Verified。
|
||||||
var text = JsonSerializer.Serialize(version, Json.Options) + "\n";
|
var text = JsonSerializer.Serialize(version, Json.Options) + "\n";
|
||||||
File.WriteAllText(path, ManifestSignature.SignDocument(text, key, "gc-2026-11"));
|
File.WriteAllText(path, ManifestSignature.SignDocument(text, key, "gc-2026-12"));
|
||||||
}
|
}
|
||||||
|
|
||||||
private static void CopyTree(string src, string dst)
|
private static void CopyTree(string src, string dst)
|
||||||
|
|||||||
@@ -11,8 +11,8 @@
|
|||||||
|
|
||||||
- UI:C# + .NET 8(可切 .NET 10)+ Avalonia,跨平台
|
- UI:C# + .NET 8(可切 .NET 10)+ Avalonia,跨平台
|
||||||
- 模型加载:`AssemblyLoadContext` 加载模型自带 dll,契约与 Avalonia 走默认上下文,关窗即卸载
|
- 模型加载:`AssemblyLoadContext` 加载模型自带 dll,契约与 Avalonia 走默认上下文,关窗即卸载
|
||||||
- 目标平台:**macOS arm64 / Windows x64 / Windows arm64**(Linux 可自行编译,未列入发布矩阵)
|
- 目标平台:**Windows x64 / Windows arm64 / macOS arm64 / Linux x64**
|
||||||
- 更新仓库:<https://gitcode.com/Morris_1/GC>,模型目录 <https://gitcode.com/Morris_1/GC/tree/main/model>
|
- 更新仓库:<https://git.xhmcl.com/Morris/GC>,模型目录 <https://git.xhmcl.com/Morris/GC/src/branch/main/model>
|
||||||
|
|
||||||
## GC-UI:前后端分离版(Flutter 前端)
|
## GC-UI:前后端分离版(Flutter 前端)
|
||||||
|
|
||||||
@@ -59,16 +59,37 @@ Windows 用 `.\build.ps1`,参数相同(`build / check / models / stamp / run
|
|||||||
## 运行目录(发布包里就长这样)
|
## 运行目录(发布包里就长这样)
|
||||||
|
|
||||||
```
|
```
|
||||||
<安装目录>/
|
<解压出来的目录>/ ← 压缩包里只有这一个文件夹
|
||||||
GC.exe | GC.app/
|
GCL-<版本>-<平台>.exe 启动器(单文件:服务层 + 本地后端 + .NET 运行时都在里面)
|
||||||
GC-SAVEDOG[.exe] 更新守护进程(与主程序同目录,macOS 在 .app/Contents/MacOS 内)
|
GC-UI.exe Flutter 前端
|
||||||
.GC/
|
flutter_windows.dll Flutter 引擎(引擎自带,不在 .NET 单文件里)
|
||||||
config/settings.json 用户设置(与缓存分开:删 cache 不会丢配置)
|
data/app.so, data/flutter_assets/ Flutter 资源与 AOT 快照
|
||||||
model/ 启动时下载的模型
|
.GC/bin/GC-SAVEDOG[.exe] 非本体文件:更新守护进程
|
||||||
cache/ 下载暂存 / 原子替换
|
|
||||||
update/ 待应用的启动器更新(apply-request.json + package.zip)
|
|
||||||
```
|
```
|
||||||
|
|
||||||
|
就这些,没有一屏 dll。安装目录根只放 GC 本体,非本体文件(守护进程)一律收在 `.GC/bin`。
|
||||||
|
macOS 是同一个单文件启动器,只是被放进 `GCL-<版本>-mac-arm64.app/Contents/MacOS/`,
|
||||||
|
Flutter 前端作为 `GC-UI.app` 放在同一层;`.GC` 位置不变,仍在启动器同级
|
||||||
|
(`.app/Contents/MacOS/`),守护进程同样收在 `.app/Contents/MacOS/.GC/bin/`。
|
||||||
|
|
||||||
|
首次启动后 `.GC` 补齐成:
|
||||||
|
|
||||||
|
```
|
||||||
|
.GC/
|
||||||
|
bin/ 非本体文件(随包分发,更新时按文件替换)
|
||||||
|
config/settings.json 用户设置(与缓存分开:删 cache 不会丢配置)
|
||||||
|
model/ 启动时下载的模型
|
||||||
|
cache/ 下载暂存 / 原子替换
|
||||||
|
update/ 待应用的启动器更新(apply-request.json + package.zip)
|
||||||
|
safedog/GC-SAVEDOG[.exe] 守护进程的运行副本(首次启动从 .GC/bin 复制)
|
||||||
|
logs/gc-YYYYMMDD.log 日志(中文)
|
||||||
|
logs/gc-YYYYMMDD.en.log 日志(English)
|
||||||
|
```
|
||||||
|
|
||||||
|
`.GC` 紧挨着主程序,装在哪都便携 —— 整个目录复制走,模型、设置、日志跟着走。
|
||||||
|
守护进程「`.GC/bin` 放源、`.GC/safedog` 放运行副本」是因为更新要整目录替换:
|
||||||
|
正在运行的 exe 在 Windows 上换不掉,所以跑副本、换源文件,下次启动再同步。
|
||||||
|
|
||||||
**发布包不含任何模型**。首次启动联网检查后把模型下载到 `.GC/model/` 并立刻显示;
|
**发布包不含任何模型**。首次启动联网检查后把模型下载到 `.GC/model/` 并立刻显示;
|
||||||
安装目录不可写时自动退回用户数据目录。`.GC/cache` 与 `.GC/model` 随时可删,程序会重新下载;
|
安装目录不可写时自动退回用户数据目录。`.GC/cache` 与 `.GC/model` 随时可删,程序会重新下载;
|
||||||
`.GC/config/settings.json` 删掉等于恢复出厂设置。
|
`.GC/config/settings.json` 删掉等于恢复出厂设置。
|
||||||
@@ -83,18 +104,23 @@ Windows 用 `.\build.ps1`,参数相同(`build / check / models / stamp / run
|
|||||||
启动器更新的完整流程:
|
启动器更新的完整流程:
|
||||||
|
|
||||||
```
|
```
|
||||||
启动器下载 zip -> 校验 sha256 -> 写 apply-request.json -> 启动 GC-SAVEDOG -> 自己退出
|
启动器下载 zip -> 校验 sha256 -> 写 apply-request.json -> 启动 .GC/safedog/GC-SAVEDOG -> 自己退出
|
||||||
GC-SAVEDOG: 二次验签 -> 检查 zip 安全性 -> 解压到 .GC/update/stage
|
GC-SAVEDOG: 二次验签 -> 检查 zip 安全性 -> 解压到 .GC/update/stage
|
||||||
-> 移入安装目录(绝不覆盖已有版本)
|
-> 整目录替换:旧文件搬到 .GC/update/backup,新文件就位
|
||||||
|
(.GC 只合并 bin/,config/model/cache/update/logs/safedog 原地不动)
|
||||||
-> 启动新版,等 .GC/update/health.json
|
-> 启动新版,等 .GC/update/health.json
|
||||||
-> 收到:删同平台旧版本,写 last-good.json
|
-> 收到:删备份、写 last-good.json
|
||||||
-> 没收到/进程退出:删新版、重启旧版,写 state.json = rolledback
|
-> 没收到/进程退出:撤掉新文件、把备份搬回、重启旧版,写 state.json = rolledback
|
||||||
```
|
```
|
||||||
|
|
||||||
|
发布包是**整目录**(启动器 + 后端运行时 + Flutter 前端资源),所以更新必须整目录替换:
|
||||||
|
只替换一个 exe 会留下旧后端 / 旧界面,新前端调不通接口。替换只动程序文件,
|
||||||
|
`.GC`(模型库、设置、日志、更新目录)和正在运行的 `GC-SAVEDOG.exe` 一律跳过。
|
||||||
|
|
||||||
也就是说:**新版本起不来,用户不会被卡死**。找不到 `GC-SAVEDOG` 的旧安装会退回脚本流程(过渡用)。
|
也就是说:**新版本起不来,用户不会被卡死**。找不到 `GC-SAVEDOG` 的旧安装会退回脚本流程(过渡用)。
|
||||||
|
|
||||||
- 默认更新仓库写在 `.GC/config/settings.json` 的 `updateRepository`:
|
- 默认更新仓库写在 `.GC/config/settings.json` 的 `updateRepository`:
|
||||||
`https://gitcode.com/Morris_1/GC`(也可换成自己的仓库或 `.../tree/main/model` 地址)
|
`https://git.xhmcl.com/Morris/GC`(也可换成自己的仓库或 `.../src/branch/main/model` 地址)
|
||||||
- 断网、仓库没推 `version.json`、下载失败:**一律保留本地模型,绝不清空模型库**,底部状态条说明原因
|
- 断网、仓库没推 `version.json`、下载失败:**一律保留本地模型,绝不清空模型库**,底部状态条说明原因
|
||||||
- 首次启动断网且本地无模型:状态条会明确提示「去下载页重试 / 手动放入 `.GC/model/`」,不会白屏干等
|
- 首次启动断网且本地无模型:状态条会明确提示「去下载页重试 / 手动放入 `.GC/model/`」,不会白屏干等
|
||||||
- 离线教室:把仓库(含 `version.json` + `model/`)拷到 U 盘,在 `settings.json` 填
|
- 离线教室:把仓库(含 `version.json` + `model/`)拷到 U 盘,在 `settings.json` 填
|
||||||
@@ -135,12 +161,23 @@ Windows 用 `.\build.ps1`,参数相同(`build / check / models / stamp / run
|
|||||||
### 签名密钥
|
### 签名密钥
|
||||||
|
|
||||||
- 私钥:`.signing/gc-signing.pem`(**已在 `.gitignore`,永不入库**;请自行备份)
|
- 私钥:`.signing/gc-signing.pem`(**已在 `.gitignore`,永不入库**;请自行备份)
|
||||||
- 公钥:硬编码在 `GC/src/Security/SignatureKeyring.cs`,指纹 `b41b1dd6259ea9ed`
|
- 公钥:硬编码在 `GC/src/Security/SignatureKeyring.cs`
|
||||||
- 生成新密钥:`dotnet run --project GC-SAVEDOG -- keygen`
|
- 当前生效:`gc-2026-12`,指纹 `ee6083be47a87907`
|
||||||
- 轮换:把新公钥追加进 `SignatureKeyring.Keys`(保留旧公钥一个版本周期),再重新签名清单
|
- 已停用:`gc-2026-11`,指纹 `b41b1dd6259ea9ed`(私钥遗失,仅保留占位)
|
||||||
|
- 生成新密钥:`dotnet run --project GC-SAVEDOG -- keygen --key-id gc-YYYY-MM`
|
||||||
|
- 轮换:把新公钥追加进 `SignatureKeyring.Keys`(保留旧公钥一个版本周期),
|
||||||
|
同时把 `GC_SIGNING_KEY_ID`(默认值在 `buildsh/lib/build_funcs.sh`)改成新 keyId,
|
||||||
|
再重新签名清单
|
||||||
- 部署前核对两边公钥一致:
|
- 部署前核对两边公钥一致:
|
||||||
`dotnet run --project GC-SAVEDOG -- verify --manifest version.json`
|
`dotnet run --project GC-SAVEDOG -- verify --manifest version.json`
|
||||||
|
|
||||||
|
`build.sh` 在刷新清单后自动调用 `sign_manifest` 签名并同步 `model/version.json`;
|
||||||
|
`.signing/gc-signing.pem` 不存在时只告警,清单不带签名(客户端会拒绝更新)。
|
||||||
|
|
||||||
|
> 换钥匙的代价:老客户端只认识编译进去的那份公钥,所以**用新密钥签出的清单
|
||||||
|
> 在旧版本上会判成「签名无效」**。密钥一旦丢失,只能靠发一个新版本把新公钥带出去,
|
||||||
|
> 中间这段时间老客户端无法自动更新 —— 私钥务必备份两处以上。
|
||||||
|
|
||||||
### zip 解压加固
|
### zip 解压加固
|
||||||
|
|
||||||
更新包和模型源 zip 一律当成不可信输入:拒绝 `../`、绝对路径、盘符、UNC、符号链接;
|
更新包和模型源 zip 一律当成不可信输入:拒绝 `../`、绝对路径、盘符、UNC、符号链接;
|
||||||
@@ -202,8 +239,8 @@ Repository/
|
|||||||
|
|
||||||
| 方式 | 清单字段 | 说明 |
|
| 方式 | 清单字段 | 说明 |
|
||||||
| --- | --- | --- |
|
| --- | --- | --- |
|
||||||
| Release 附件(推荐) | `url` | `.../releases/download/v<版本>/GC-<版本>-<系统>-<架构>.zip` |
|
| Release 附件(推荐) | `url` | `.../releases/download/<版本>/GCL-<版本>-<系统>-<架构>.zip` |
|
||||||
| 仓库编译产物 | `path` / `dir` / `name` | `dist/<系统>-<架构>/GC-<版本>-<系统>-<架构>.zip` |
|
| 仓库编译产物 | `path` / `dir` / `name` | `dist/<系统>-<架构>/GCL-<版本>-<系统>-<架构>.zip` |
|
||||||
|
|
||||||
下载端按 `url` → `path` → `dist/<系统>-<架构>/` 目录扫描的顺序尝试,
|
下载端按 `url` → `path` → `dist/<系统>-<架构>/` 目录扫描的顺序尝试,
|
||||||
**每个候选都必须与清单里的 `sha256` 一致**(`sha256` 由签名保护),
|
**每个候选都必须与清单里的 `sha256` 一致**(`sha256` 由签名保护),
|
||||||
@@ -229,15 +266,16 @@ Repository/
|
|||||||
|
|
||||||
| 产物 | 平台 |
|
| 产物 | 平台 |
|
||||||
| --- | --- |
|
| --- | --- |
|
||||||
| `dist/mac-arm64/GC-<版本>-mac-arm64.zip` | macOS Apple Silicon 应用包(含 GC-SAVEDOG) |
|
| `dist/mac-arm64/GCL-<版本>-mac-arm64.zip` | macOS Apple Silicon(单顶层 `GCL-….app`) |
|
||||||
| `dist/win-amd64/GC-<版本>-win-amd64.zip` | Windows x64 单文件启动器 + `GC-SAVEDOG.exe` |
|
| `dist/win-amd64/GCL-<版本>-win-amd64.zip` | Windows x64(单顶层 `GCL-…/`,含 Flutter 前端,非本体文件在 `.GC/bin/`) |
|
||||||
| `dist/win-arm64/GC-<版本>-win-arm64.zip` | Windows on ARM 同上 |
|
| `dist/win-arm64/GCL-<版本>-win-arm64.zip` | Windows on ARM 同上 |
|
||||||
|
| `dist/linux-arm64/GCL-<版本>-linux-arm64.zip` | Linux ARM64 同上(启动器无扩展名;默认不构建,需 aarch64 主机 + `GC_BUILD_LINUX=1`) |
|
||||||
|
|
||||||
平台目录就是「该平台的编译产物目录」:打包完成后只留最终 zip(原始 `.app` / `.exe`
|
平台目录就是「该平台的编译产物目录」:打包完成后只留最终 zip(原始 `.app` / `.exe`
|
||||||
会被挪到 `build/trash/`,下次构建时移出,不做递归删除)。
|
会被挪到 `build/trash/`,下次构建时移出,不做递归删除)。
|
||||||
|
|
||||||
发新版:`./build.sh build -version=1.0.8` → 把 `dist/<平台>/GC-1.0.8-<平台>.zip`
|
发新版:`./build.sh build` → 把 `dist/<平台>/GCL-<版本>-<平台>.zip`
|
||||||
上传到 gitcode Release(tag `v1.0.8`),**或者**直接提交/上传到仓库的
|
上传到 Gitea Release(tag `v1.0.8`),**或者**直接提交/上传到仓库的
|
||||||
`dist/<平台>/` 目录 → 提交并推送 `version.json` / `model/version.json`。
|
`dist/<平台>/` 目录 → 提交并推送 `version.json` / `model/version.json`。
|
||||||
两种都能被客户端识别,客户端下次启动就会看到更新。
|
两种都能被客户端识别,客户端下次启动就会看到更新。
|
||||||
|
|
||||||
|
|||||||
@@ -3,6 +3,7 @@
|
|||||||
# GC 构建入口(薄封装)
|
# GC 构建入口(薄封装)
|
||||||
#
|
#
|
||||||
# ./build.sh build 完整发布(原 publish),带 apt 风格进度条
|
# ./build.sh build 完整发布(原 publish),带 apt 风格进度条
|
||||||
|
# 默认要求每个平台都带 Flutter 前端;--allow-no-ui 允许降级
|
||||||
# ./build.sh check 验证:编译 + 自检 + 离屏渲染 + 产物
|
# ./build.sh check 验证:编译 + 自检 + 离屏渲染 + 产物
|
||||||
# ./build.sh models 编译模型 dll + 封面 + 版本戳
|
# ./build.sh models 编译模型 dll + 封面 + 版本戳
|
||||||
# ./build.sh stamp 重新生成 version.json
|
# ./build.sh stamp 重新生成 version.json
|
||||||
@@ -33,11 +34,12 @@ VERSION=$(sed -n 's/.*<Version>\(.*\)<\/Version>.*/\1/p' Directory.Build.props |
|
|||||||
TASK="${1:-build}"
|
TASK="${1:-build}"
|
||||||
shift 2>/dev/null || true
|
shift 2>/dev/null || true
|
||||||
|
|
||||||
# 解析 -version=<版本号>(也接受 --version=)
|
# 解析 -version=<版本号>(也接受 --version=)与 --allow-no-ui
|
||||||
CLI_VERSION=""
|
CLI_VERSION=""
|
||||||
for arg in "$@"; do
|
for arg in "$@"; do
|
||||||
case "$arg" in
|
case "$arg" in
|
||||||
-version=*|--version=*) CLI_VERSION="${arg#*=}" ;;
|
-version=*|--version=*) CLI_VERSION="${arg#*=}" ;;
|
||||||
|
-allow-no-ui|--allow-no-ui) export GC_ALLOW_NO_UI=1 ;;
|
||||||
esac
|
esac
|
||||||
done
|
done
|
||||||
if [ -n "$CLI_VERSION" ]; then
|
if [ -n "$CLI_VERSION" ]; then
|
||||||
@@ -57,9 +59,11 @@ mkdir -p "$ROOT_DIR/build/logs"
|
|||||||
. "$ROOT_DIR/buildsh/build.sh"
|
. "$ROOT_DIR/buildsh/build.sh"
|
||||||
. "$ROOT_DIR/buildsh/check.sh"
|
. "$ROOT_DIR/buildsh/check.sh"
|
||||||
. "$ROOT_DIR/buildsh/tools.sh"
|
. "$ROOT_DIR/buildsh/tools.sh"
|
||||||
|
. "$ROOT_DIR/buildsh/release.sh"
|
||||||
|
|
||||||
case "$TASK" in
|
case "$TASK" in
|
||||||
build) bs_build "$ROOT_DIR" ;;
|
build) bs_build "$ROOT_DIR" ;;
|
||||||
check) bs_check "$ROOT_DIR" ;;
|
check) bs_check "$ROOT_DIR" ;;
|
||||||
|
release-verify) bs_verify_release "$ROOT_DIR" "$@" ;;
|
||||||
*) bs_tools "$ROOT_DIR" "$TASK" ;;
|
*) bs_tools "$ROOT_DIR" "$TASK" ;;
|
||||||
esac
|
esac
|
||||||
@@ -6,7 +6,12 @@ function Invoke-BuildTool {
|
|||||||
'pack-models' { Build-Models; Pack-Models }
|
'pack-models' { Build-Models; Pack-Models }
|
||||||
'pack-launcher'{ Pack-Launcher }
|
'pack-launcher'{ Pack-Launcher }
|
||||||
'run' { & dotnet run --project $script:AppProject -c Debug; if ($LASTEXITCODE -ne 0) { throw "dotnet run 失败,退出码 $LASTEXITCODE" } }
|
'run' { & dotnet run --project $script:AppProject -c Debug; if ($LASTEXITCODE -ne 0) { throw "dotnet run 失败,退出码 $LASTEXITCODE" } }
|
||||||
'test' { & dotnet run --project $script:TestProject -c Debug -- (Join-Path $script:BuildRoot 'build/screenshots'); if ($LASTEXITCODE -ne 0) { throw "测试失败,退出码 $LASTEXITCODE" } }
|
'test' {
|
||||||
|
& dotnet run --project $script:TestProject -c Debug -- (Join-Path $script:BuildRoot 'build/screenshots')
|
||||||
|
if ($LASTEXITCODE -ne 0) { throw "测试失败,退出码 $LASTEXITCODE" }
|
||||||
|
# 与 pr-check.yml 一致:应用器测试单独跑(它与启动器有同名类型,不能并入 GC.Tests)
|
||||||
|
Invoke-SavedogTests
|
||||||
|
}
|
||||||
'update-test' { & dotnet run --project $script:TestProject -c Debug -- --update-test $script:BuildRoot; if ($LASTEXITCODE -ne 0) { throw "更新测试失败,退出码 $LASTEXITCODE" } }
|
'update-test' { & dotnet run --project $script:TestProject -c Debug -- --update-test $script:BuildRoot; if ($LASTEXITCODE -ne 0) { throw "更新测试失败,退出码 $LASTEXITCODE" } }
|
||||||
'clean' {
|
'clean' {
|
||||||
Remove-Item (Join-Path $script:BuildRoot 'build'), (Join-Path $script:BuildRoot 'dist') -Recurse -Force -ErrorAction SilentlyContinue
|
Remove-Item (Join-Path $script:BuildRoot 'build'), (Join-Path $script:BuildRoot 'dist') -Recurse -Force -ErrorAction SilentlyContinue
|
||||||
|
|||||||
+7
-5
@@ -1,7 +1,7 @@
|
|||||||
param(
|
param(
|
||||||
[Parameter(Position = 0)]
|
[Parameter(Position = 0)]
|
||||||
[ValidateSet('build','check','models','stamp','pack-models','pack-launcher',
|
[ValidateSet('build','check','models','stamp','pack-models','pack-launcher',
|
||||||
'run','test','update-test','clean','doctor','dist')]
|
'release-verify','run','test','update-test','clean','doctor','dist')]
|
||||||
[string]$Task = 'build',
|
[string]$Task = 'build',
|
||||||
[string]$Version = ''
|
[string]$Version = ''
|
||||||
)
|
)
|
||||||
@@ -23,7 +23,8 @@ try {
|
|||||||
if (-not $Version) { $Version = '1.0.0' }
|
if (-not $Version) { $Version = '1.0.0' }
|
||||||
$script:BuildVersion = $Version
|
$script:BuildVersion = $Version
|
||||||
|
|
||||||
if ($PSBoundParameters.ContainsKey('Version')) {
|
# release-verify 的 -Version 是「要核对的 tag」,不是改版本号:绝不能改写清单
|
||||||
|
if ($PSBoundParameters.ContainsKey('Version') -and $Task -ne 'release-verify') {
|
||||||
if ($null -eq $versionNode) { throw 'Directory.Build.props 中找不到 Version 节点。' }
|
if ($null -eq $versionNode) { throw 'Directory.Build.props 中找不到 Version 节点。' }
|
||||||
$versionNode.InnerText = $Version
|
$versionNode.InnerText = $Version
|
||||||
$props.Save((Join-Path $script:BuildRoot 'Directory.Build.props'))
|
$props.Save((Join-Path $script:BuildRoot 'Directory.Build.props'))
|
||||||
@@ -37,9 +38,10 @@ try {
|
|||||||
. (Join-Path $PSScriptRoot 'Build-Tools.ps1')
|
. (Join-Path $PSScriptRoot 'Build-Tools.ps1')
|
||||||
|
|
||||||
switch ($Task) {
|
switch ($Task) {
|
||||||
'build' { Invoke-FullBuild }
|
'build' { Invoke-FullBuild }
|
||||||
'check' { Invoke-BuildCheck }
|
'check' { Invoke-BuildCheck }
|
||||||
default { Invoke-BuildTool $Task }
|
'release-verify' { Invoke-ReleaseVerify -Tag $Version }
|
||||||
|
default { Invoke-BuildTool $Task }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
finally {
|
finally {
|
||||||
|
|||||||
+143
-71
@@ -18,7 +18,9 @@ function Invoke-ManifestSign {
|
|||||||
Write-Host '!! 未找到签名私钥 .signing/gc-signing.pem,version.json 未签名(客户端会拒绝更新)'
|
Write-Host '!! 未找到签名私钥 .signing/gc-signing.pem,version.json 未签名(客户端会拒绝更新)'
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
$keyId = if ($env:GC_SIGNING_KEY_ID) { $env:GC_SIGNING_KEY_ID } else { 'gc-2026-11' }
|
# 与 buildsh/lib/build_funcs.sh 保持一致:当前生效的密钥是 gc-2026-12。
|
||||||
|
# gc-2026-11 的私钥没有留存,用它签出来的清单客户端永远验不过。
|
||||||
|
$keyId = if ($env:GC_SIGNING_KEY_ID) { $env:GC_SIGNING_KEY_ID } else { 'gc-2026-12' }
|
||||||
Write-Host "==> 签名 version.json ($keyId)"
|
Write-Host "==> 签名 version.json ($keyId)"
|
||||||
Invoke-LoggedDotNet -Name 'sign' -Arguments @(
|
Invoke-LoggedDotNet -Name 'sign' -Arguments @(
|
||||||
'run', '--project', (Join-Path $script:BuildRoot 'GC-SAVEDOG/GC-SAVEDOG.csproj'),
|
'run', '--project', (Join-Path $script:BuildRoot 'GC-SAVEDOG/GC-SAVEDOG.csproj'),
|
||||||
@@ -30,7 +32,7 @@ function Invoke-ManifestSign {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function Invoke-VersionStamp {
|
function Invoke-VersionStamp {
|
||||||
param([switch]$LauncherOnly)
|
param([switch]$LauncherOnly, [switch]$NoSign)
|
||||||
if ($LauncherOnly) {
|
if ($LauncherOnly) {
|
||||||
Write-Host '==> 刷新启动器包信息(sha256 / 体积 / dist 路径)'
|
Write-Host '==> 刷新启动器包信息(sha256 / 体积 / dist 路径)'
|
||||||
Invoke-LoggedDotNet -Name 'stamp' -Arguments @(
|
Invoke-LoggedDotNet -Name 'stamp' -Arguments @(
|
||||||
@@ -45,7 +47,14 @@ function Invoke-VersionStamp {
|
|||||||
$script:BuildRoot, $script:BuildVersion
|
$script:BuildRoot, $script:BuildVersion
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
Invoke-ManifestSign
|
# 完整 build 末尾 Pack-Launcher 会统一签一次(末次签名);中间这次是浪费的。
|
||||||
|
# 单独的 stamp / models 工具没有后续打包,仍走默认签名。
|
||||||
|
if ($NoSign) {
|
||||||
|
Write-Host ' (跳过签名,打包结束后统一签一次)'
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
Invoke-ManifestSign
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function Build-Models {
|
function Build-Models {
|
||||||
@@ -78,44 +87,41 @@ function Prepare-RuntimeLayout {
|
|||||||
$destination = Join-Path $script:BuildRoot $RelativePath
|
$destination = Join-Path $script:BuildRoot $RelativePath
|
||||||
if (-not (Test-Path $destination)) { return }
|
if (-not (Test-Path $destination)) { return }
|
||||||
|
|
||||||
Remove-Item (Join-Path $destination 'model'), (Join-Path $destination 'examples') -Recurse -Force -ErrorAction SilentlyContinue
|
# 与 buildsh/lib/build_funcs.sh 一致:发布目录只放程序本体,不预置 .GC。
|
||||||
New-Item -ItemType Directory -Force -Path (Join-Path $destination '.GC/model'), (Join-Path $destination '.GC/cache'), (Join-Path $destination '.GC/update'), (Join-Path $destination '.GC/config') | Out-Null
|
# .GC(config / model / cache / update / safedog / logs)一律在首次启动时
|
||||||
Set-Content -Path (Join-Path $destination '.GC/model/README.txt') -Encoding UTF8 -Value @'
|
# 由 AppPaths.EnsureCreated + RuntimeLayout 创建,压缩包里只有 GC 本体。
|
||||||
模型库目录(.GC/model/)
|
Remove-Item (Join-Path $destination 'model'), (Join-Path $destination 'examples'), (Join-Path $destination '.GC') -Recurse -Force -ErrorAction SilentlyContinue
|
||||||
启动时程序会读取 GitCode 仓库的 version.json,把最新版模型下载到这里。
|
Write-Host " 运行目录 -> $RelativePath(首次启动后生成 .GC/:config model cache update safedog logs)"
|
||||||
离线使用也可以手动放入 <模型id>/<模型id>.json + <模型id>/<模型id>.model/。
|
|
||||||
|
|
||||||
运行目录:
|
|
||||||
<可执行文件>
|
|
||||||
GC-SAVEDOG 更新守护进程(验签 + 原子替换 + 失败回滚)
|
|
||||||
.GC/config/settings.json 用户设置(删 .GC/cache 不会丢配置)
|
|
||||||
.GC/model/ 本目录(下载的模型)
|
|
||||||
.GC/cache/ 下载暂存
|
|
||||||
.GC/update/ 待下次启动应用的启动器更新
|
|
||||||
'@
|
|
||||||
$settingsPath = Join-Path $destination '.GC/config/settings.json'
|
|
||||||
if (-not (Test-Path $settingsPath)) {
|
|
||||||
Set-Content -Path $settingsPath -Encoding UTF8 -Value @'
|
|
||||||
{
|
|
||||||
"language": "auto",
|
|
||||||
"theme": "light",
|
|
||||||
"renderFps": 30,
|
|
||||||
"memoryMb": 2048,
|
|
||||||
"autoUpdateOnStartup": true,
|
|
||||||
"requireSignedManifest": true,
|
|
||||||
"updateRepository": "https://gitcode.com/Morris_1/GC",
|
|
||||||
"updateManifestUrl": "",
|
|
||||||
"updateLocalRoot": "",
|
|
||||||
"installedModelVersions": {},
|
|
||||||
"launcherVersion": "",
|
|
||||||
"pendingLauncherVersion": "",
|
|
||||||
"lastUpdateCheck": "",
|
|
||||||
"sources": [],
|
|
||||||
"recentModels": []
|
|
||||||
}
|
}
|
||||||
'@
|
|
||||||
|
function Prune-Package {
|
||||||
|
param(
|
||||||
|
[Parameter(Mandatory)][string]$Destination,
|
||||||
|
[Parameter(Mandatory)][ValidateSet('win', 'linux')][string]$Platform
|
||||||
|
)
|
||||||
|
if (-not (Test-Path $Destination)) { return }
|
||||||
|
$junk = @(
|
||||||
|
'mscordaccore.dll', 'mscordbi.dll', 'web.config',
|
||||||
|
'aspnetcorev2_inprocess.dll',
|
||||||
|
'Microsoft.AspNetCore.Server.IIS.dll',
|
||||||
|
'Microsoft.AspNetCore.Server.IISIntegration.dll',
|
||||||
|
'Microsoft.AspNetCore.Server.HttpSys.dll',
|
||||||
|
'Microsoft.DiaSymReader.Native.dll'
|
||||||
|
)
|
||||||
|
if ($Platform -eq 'win') {
|
||||||
|
# 后端已编入启动器,ProjectReference 残留的独立 exe / runtimeconfig 没有用
|
||||||
|
$junk += @('GC.UI.Server.exe', 'GC.UI.Server.dll', 'GC.UI.Server.deps.json', 'GC.UI.Server.runtimeconfig.json')
|
||||||
|
$junk += @('Avalonia.X11.dll', 'Avalonia.Native.dll', 'Avalonia.FreeDesktop.dll', 'Tmds.DBus.Protocol.dll')
|
||||||
}
|
}
|
||||||
Write-Host " 运行目录 -> $RelativePath/.GC"
|
else {
|
||||||
|
$junk += @('Avalonia.Win32.dll', 'Avalonia.Win32.Automation.dll')
|
||||||
|
}
|
||||||
|
foreach ($name in $junk) {
|
||||||
|
Get-ChildItem $Destination -Filter $name -File -ErrorAction SilentlyContinue | Remove-Item -Force -ErrorAction SilentlyContinue
|
||||||
|
}
|
||||||
|
# mscordaccore*.dll / Microsoft.DiaSymReader.Native*.dll 是带版本号通配的
|
||||||
|
Get-ChildItem $Destination -Filter 'mscordaccore*.dll' -File -ErrorAction SilentlyContinue | Remove-Item -Force -ErrorAction SilentlyContinue
|
||||||
|
Get-ChildItem $Destination -Filter 'Microsoft.DiaSymReader.Native*.dll' -File -ErrorAction SilentlyContinue | Remove-Item -Force -ErrorAction SilentlyContinue
|
||||||
}
|
}
|
||||||
|
|
||||||
function Publish-Rid {
|
function Publish-Rid {
|
||||||
@@ -132,18 +138,22 @@ function Publish-Rid {
|
|||||||
'publish', $script:AppProject, '-c', 'Release', '-r', $Rid,
|
'publish', $script:AppProject, '-c', 'Release', '-r', $Rid,
|
||||||
'--self-contained', 'true', "-p:Version=$script:BuildVersion", '-p:DebugType=none',
|
'--self-contained', 'true', "-p:Version=$script:BuildVersion", '-p:DebugType=none',
|
||||||
"-p:PublishSingleFile=$singleValue", "-p:IncludeNativeLibrariesForSelfExtract=$singleValue",
|
"-p:PublishSingleFile=$singleValue", "-p:IncludeNativeLibrariesForSelfExtract=$singleValue",
|
||||||
|
"-p:EnableCompressionInSingleFile=$singleValue",
|
||||||
'-p:PublishTrimmed=false', '-o', $outputPath
|
'-p:PublishTrimmed=false', '-o', $outputPath
|
||||||
)
|
)
|
||||||
|
|
||||||
# 更新守护进程:与主程序同目录(裁剪单文件,70MB -> 14MB)
|
# 更新守护进程:与主程序同目录(裁剪 + 压缩单文件,70MB -> 14MB)
|
||||||
# 裁剪的前提是 JSON 全部走源生成上下文(GC-SAVEDOG/SavedogJson.cs)
|
# 裁剪的前提是 JSON 全部走源生成上下文(GC-SAVEDOG/SavedogJson.cs)。
|
||||||
|
# EnableCompressionInSingleFile:守护进程不常驻,只在更新时跑一次,
|
||||||
|
# 解压一次换来更小的包,对「只在更新时下载」的场景很划算。
|
||||||
$savedogProj = Join-Path $script:BuildRoot 'GC-SAVEDOG/GC-SAVEDOG.csproj'
|
$savedogProj = Join-Path $script:BuildRoot 'GC-SAVEDOG/GC-SAVEDOG.csproj'
|
||||||
if (Test-Path $savedogProj) {
|
if (Test-Path $savedogProj) {
|
||||||
Write-Host "==> 编译 GC-SAVEDOG ($Rid)(裁剪单文件)"
|
Write-Host "==> 编译 GC-SAVEDOG ($Rid)(裁剪 + 压缩单文件)"
|
||||||
Invoke-LoggedDotNet -Name "savedog-$($Rid -replace '-', '')" -Arguments @(
|
Invoke-LoggedDotNet -Name "savedog-$($Rid -replace '-', '')" -Arguments @(
|
||||||
'publish', $savedogProj, '-c', 'Release', '-r', $Rid,
|
'publish', $savedogProj, '-c', 'Release', '-r', $Rid,
|
||||||
'--self-contained', 'true', "-p:Version=$script:BuildVersion", '-p:DebugType=none',
|
'--self-contained', 'true', "-p:Version=$script:BuildVersion", '-p:DebugType=none',
|
||||||
'-p:PublishSingleFile=true', '-p:IncludeNativeLibrariesForSelfExtract=true',
|
'-p:PublishSingleFile=true', '-p:IncludeNativeLibrariesForSelfExtract=true',
|
||||||
|
'-p:EnableCompressionInSingleFile=true',
|
||||||
'-p:PublishTrimmed=true', '-p:TrimMode=full',
|
'-p:PublishTrimmed=true', '-p:TrimMode=full',
|
||||||
'-p:JsonSerializerIsReflectionEnabledByDefault=false', '-o', $outputPath
|
'-p:JsonSerializerIsReflectionEnabledByDefault=false', '-o', $outputPath
|
||||||
)
|
)
|
||||||
@@ -178,35 +188,60 @@ function Pack-Models {
|
|||||||
|
|
||||||
function Pack-Launcher {
|
function Pack-Launcher {
|
||||||
$dist = Join-Path $script:BuildRoot 'dist'
|
$dist = Join-Path $script:BuildRoot 'dist'
|
||||||
Write-Host "==> 生成启动器产物(GC-$script:BuildVersion-<平台>)"
|
Write-Host "==> 生成启动器产物(GCL-$script:BuildVersion-<系统>-<架构>)"
|
||||||
|
|
||||||
|
# 与 buildsh/lib/build_funcs.sh 的 pack_launcher 对齐:
|
||||||
|
# 1) 包名统一 GCL- 前缀;
|
||||||
|
# 2) zip 内只有一个顶层目录(GCL-<版本>-<平台>),不散落一屏 dll;
|
||||||
|
# 3) 非本体文件(守护进程)收进 .GC/bin,安装目录根只留 GC 本体;
|
||||||
|
# 4) 剔除调试 / 无关平台的组件(prune)。
|
||||||
|
|
||||||
|
# --- Windows:启动器 + 守护进程 + 前端,整目录打进单顶层目录 ---
|
||||||
foreach ($platform in @(@{ Rid = 'win-x64'; Label = 'win-amd64' }, @{ Rid = 'win-arm64'; Label = 'win-arm64' })) {
|
foreach ($platform in @(@{ Rid = 'win-x64'; Label = 'win-amd64' }, @{ Rid = 'win-arm64'; Label = 'win-arm64' })) {
|
||||||
# 产物落点 dist/<系统>-<架构>/,与 dist/mac-arm64 一致
|
|
||||||
$sourceDir = Join-Path $dist $platform.Label
|
$sourceDir = Join-Path $dist $platform.Label
|
||||||
if (-not (Test-Path $sourceDir)) { $sourceDir = Join-Path $dist $platform.Rid }
|
if (-not (Test-Path $sourceDir)) { $sourceDir = Join-Path $dist $platform.Rid }
|
||||||
if (-not (Test-Path $sourceDir)) { continue }
|
if (-not (Test-Path $sourceDir)) { continue }
|
||||||
# 注意排除守护进程:GC-SAVEDOG.exe 在字典序里排在 GC.exe 前面
|
|
||||||
$executable = Get-ChildItem $sourceDir -Filter '*.exe' |
|
|
||||||
Where-Object { $_.Name -notlike 'GC-SAVEDOG*' } | Select-Object -First 1
|
|
||||||
if ($null -eq $executable) { continue }
|
|
||||||
|
|
||||||
|
# 启动器固定是 GC.exe;后端与前端是可选的随包产物,不能当成启动器
|
||||||
|
$exe = Join-Path $sourceDir 'GC.exe'
|
||||||
|
if (-not (Test-Path $exe)) {
|
||||||
|
$exe = (Get-ChildItem $sourceDir -Filter '*.exe' | Where-Object {
|
||||||
|
$_.Name -notlike 'GC-SAVEDOG*' -and $_.Name -notlike 'GC.UI.Server*' -and $_.Name -notlike 'GC-UI*'
|
||||||
|
} | Select-Object -First 1).FullName
|
||||||
|
}
|
||||||
|
if (-not $exe) { continue }
|
||||||
|
|
||||||
|
$pkgName = "GCL-$script:BuildVersion-$($platform.Label)"
|
||||||
$temp = Join-Path $dist ".winpkg-$($platform.Label)"
|
$temp = Join-Path $dist ".winpkg-$($platform.Label)"
|
||||||
|
$pkg = Join-Path $temp $pkgName
|
||||||
Remove-Item $temp -Recurse -Force -ErrorAction SilentlyContinue
|
Remove-Item $temp -Recurse -Force -ErrorAction SilentlyContinue
|
||||||
New-Item -ItemType Directory -Force -Path $temp | Out-Null
|
New-Item -ItemType Directory -Force -Path $pkg | Out-Null
|
||||||
Copy-Item $executable.FullName (Join-Path $temp "GC-$script:BuildVersion-$($platform.Label).exe") -Force
|
Get-ChildItem $sourceDir -Force | Where-Object { $_.Extension -ne '.zip' } | Copy-Item -Destination $pkg -Recurse -Force
|
||||||
$savedogExe = Join-Path $sourceDir 'GC-SAVEDOG.exe'
|
Prune-Package -Destination $pkg -Platform 'win'
|
||||||
if (Test-Path $savedogExe) { Copy-Item $savedogExe (Join-Path $temp 'GC-SAVEDOG.exe') -Force }
|
Move-Item (Join-Path $pkg (Split-Path $exe -Leaf)) (Join-Path $pkg "$pkgName.exe") -Force
|
||||||
|
if (Get-Command chmod -ErrorAction SilentlyContinue) { & chmod +x (Join-Path $pkg "$pkgName.exe") 2>$null }
|
||||||
|
|
||||||
$zipPath = Join-Path $dist "$($platform.Label)/GC-$script:BuildVersion-$($platform.Label).zip"
|
$savedogExe = Join-Path $pkg 'GC-SAVEDOG.exe'
|
||||||
|
if (Test-Path $savedogExe) {
|
||||||
|
$binDir = Join-Path $pkg '.GC/bin'
|
||||||
|
New-Item -ItemType Directory -Force -Path $binDir | Out-Null
|
||||||
|
Move-Item $savedogExe (Join-Path $binDir 'GC-SAVEDOG.exe') -Force
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
Write-Host " !! 缺少 GC-SAVEDOG.exe,该平台将退回旧脚本更新"
|
||||||
|
}
|
||||||
|
|
||||||
|
$zipPath = Join-Path $dist "$($platform.Label)/$pkgName.zip"
|
||||||
Remove-Item $zipPath -Force -ErrorAction SilentlyContinue
|
Remove-Item $zipPath -Force -ErrorAction SilentlyContinue
|
||||||
Compress-Archive -Path (Join-Path $temp '*') -DestinationPath $zipPath -CompressionLevel Optimal
|
Compress-Archive -Path $pkg -DestinationPath $zipPath -CompressionLevel Optimal
|
||||||
Remove-Item $temp -Recurse -Force -ErrorAction SilentlyContinue
|
Remove-Item $temp -Recurse -Force -ErrorAction SilentlyContinue
|
||||||
Write-Host " -> dist/$($platform.Label)/GC-$script:BuildVersion-$($platform.Label).zip"
|
Write-Host " -> dist/$($platform.Label)/$pkgName.zip"
|
||||||
}
|
}
|
||||||
|
|
||||||
|
# --- macOS:先得到真实 .app 目录(改名 + 同步 Info.plist + 守护进程入 .GC/bin) ---
|
||||||
$macApp = Join-Path $dist 'mac-arm64/GC.app'
|
$macApp = Join-Path $dist 'mac-arm64/GC.app'
|
||||||
if (Test-Path $macApp) {
|
if (Test-Path $macApp) {
|
||||||
$finalApp = Join-Path $dist "GC-$script:BuildVersion-mac-arm64.app"
|
$finalApp = Join-Path $dist "GCL-$script:BuildVersion-mac-arm64.app"
|
||||||
Remove-Item $finalApp -Recurse -Force -ErrorAction SilentlyContinue
|
Remove-Item $finalApp -Recurse -Force -ErrorAction SilentlyContinue
|
||||||
Move-Item $macApp $finalApp
|
Move-Item $macApp $finalApp
|
||||||
$binary = Join-Path $finalApp 'Contents/MacOS/GC'
|
$binary = Join-Path $finalApp 'Contents/MacOS/GC'
|
||||||
@@ -216,20 +251,25 @@ function Pack-Launcher {
|
|||||||
& /usr/libexec/PlistBuddy -c 'Set :CFBundleName Morris GC' $plist 2>$null
|
& /usr/libexec/PlistBuddy -c 'Set :CFBundleName Morris GC' $plist 2>$null
|
||||||
& /usr/libexec/PlistBuddy -c 'Set :CFBundleDisplayName Morris GC' $plist 2>$null
|
& /usr/libexec/PlistBuddy -c 'Set :CFBundleDisplayName Morris GC' $plist 2>$null
|
||||||
}
|
}
|
||||||
|
# 非本体文件收进 .GC/bin(与 Windows 布局一致):.GC 位置不变,仍在 .app/Contents/MacOS/
|
||||||
|
$savedog = Join-Path $finalApp 'Contents/MacOS/GC-SAVEDOG'
|
||||||
|
if (Test-Path $savedog) {
|
||||||
|
$binDir = Join-Path $finalApp 'Contents/MacOS/.GC/bin'
|
||||||
|
New-Item -ItemType Directory -Force -Path $binDir | Out-Null
|
||||||
|
Move-Item $savedog (Join-Path $binDir 'GC-SAVEDOG') -Force
|
||||||
|
if (Get-Command chmod -ErrorAction SilentlyContinue) { & chmod +x (Join-Path $binDir 'GC-SAVEDOG') 2>$null }
|
||||||
|
}
|
||||||
if (Get-Command xattr -ErrorAction SilentlyContinue) { & xattr -cr $finalApp 2>$null }
|
if (Get-Command xattr -ErrorAction SilentlyContinue) { & xattr -cr $finalApp 2>$null }
|
||||||
}
|
}
|
||||||
|
|
||||||
# Windows 的 zip 已在上面的循环里生成(含 GC-SAVEDOG.exe),这里只处理 .app
|
# --- 统一压缩:.app -> 同名 .zip,放进平台目录 ---
|
||||||
Get-ChildItem $dist | Where-Object { $_.Name -like "GC-$script:BuildVersion-*.app" } | ForEach-Object {
|
Get-ChildItem $dist | Where-Object { $_.Name -like "GCL-$script:BuildVersion-*.app" } | ForEach-Object {
|
||||||
$label = $_.BaseName -replace "^GC-$([regex]::Escape($script:BuildVersion))-", ''
|
$label = $_.BaseName -replace "^GCL-$([regex]::Escape($script:BuildVersion))-", ''
|
||||||
$targetDir = Join-Path $dist $label
|
$targetDir = Join-Path $dist $label
|
||||||
New-Item -ItemType Directory -Force -Path $targetDir | Out-Null
|
New-Item -ItemType Directory -Force -Path $targetDir | Out-Null
|
||||||
$zipPath = Join-Path $targetDir ($_.BaseName + '.zip')
|
$zipPath = Join-Path $targetDir ($_.BaseName + '.zip')
|
||||||
Remove-Item $zipPath -Force -ErrorAction SilentlyContinue
|
Remove-Item $zipPath -Force -ErrorAction SilentlyContinue
|
||||||
if ($_.PSIsContainer) {
|
if (Get-Command ditto -ErrorAction SilentlyContinue) {
|
||||||
Remove-Item (Join-Path $_.FullName 'Contents/MacOS/.GC') -Recurse -Force -ErrorAction SilentlyContinue
|
|
||||||
}
|
|
||||||
if ($_.PSIsContainer -and (Get-Command ditto -ErrorAction SilentlyContinue)) {
|
|
||||||
& ditto -c -k --sequesterRsrc --keepParent $_.FullName $zipPath
|
& ditto -c -k --sequesterRsrc --keepParent $_.FullName $zipPath
|
||||||
if ($LASTEXITCODE -ne 0) { throw "ditto 压缩失败:$($_.Name)" }
|
if ($LASTEXITCODE -ne 0) { throw "ditto 压缩失败:$($_.Name)" }
|
||||||
}
|
}
|
||||||
@@ -239,26 +279,26 @@ function Pack-Launcher {
|
|||||||
Write-Host " -> dist/$label/$($_.BaseName).zip"
|
Write-Host " -> dist/$label/$($_.BaseName).zip"
|
||||||
}
|
}
|
||||||
|
|
||||||
# 原始产物(.exe / .app 目录)不再保留:只发布 zip
|
# 原始产物(.exe / .app 目录)不再保留:只发布 zip(移入暂存区,不做递归删除)
|
||||||
$trash = Join-Path $script:BuildRoot 'build/trash'
|
$trash = Join-Path $script:BuildRoot 'build/trash'
|
||||||
New-Item -ItemType Directory -Force -Path $trash | Out-Null
|
New-Item -ItemType Directory -Force -Path $trash | Out-Null
|
||||||
Get-ChildItem $dist -Force | Where-Object {
|
Get-ChildItem $dist -Force | Where-Object {
|
||||||
$_.Name -like "GC-$script:BuildVersion-*.exe" -or $_.Name -like "GC-$script:BuildVersion-*.app"
|
$_.Name -like "GCL-$script:BuildVersion-*.exe" -or $_.Name -like "GCL-$script:BuildVersion-*.app"
|
||||||
} | ForEach-Object {
|
} | ForEach-Object {
|
||||||
Move-Item $_.FullName (Join-Path $trash "$($_.Name)-$([DateTime]::Now.Ticks)") -Force -ErrorAction SilentlyContinue
|
Move-Item $_.FullName (Join-Path $trash "$($_.Name)-$([DateTime]::Now.Ticks)") -Force -ErrorAction SilentlyContinue
|
||||||
}
|
}
|
||||||
Remove-IntermediateDirectories
|
Remove-IntermediateDirectories
|
||||||
Invoke-VersionStamp -LauncherOnly
|
Invoke-VersionStamp -LauncherOnly
|
||||||
Write-Host '==> dist 可发布 zip:'
|
Write-Host '==> dist 可发布 zip:'
|
||||||
Get-ChildItem $dist -Recurse -Filter "GC-$script:BuildVersion-*.zip" | Select-Object FullName, Length
|
Get-ChildItem $dist -Recurse -Filter "GCL-$script:BuildVersion-*.zip" | Select-Object FullName, Length
|
||||||
}
|
}
|
||||||
|
|
||||||
function Remove-IntermediateDirectories {
|
function Remove-IntermediateDirectories {
|
||||||
# 平台目录里只留最终 zip(其它都是 publish 中间产物)
|
# 平台目录里只留最终 zip(其它都是 publish 中间产物)
|
||||||
foreach ($name in @('win-amd64', 'win-x64', 'win-arm64', 'mac-arm64')) {
|
foreach ($name in @('win-amd64', 'win-x64', 'win-arm64', 'mac-arm64', 'linux-arm64', 'linux-x64')) {
|
||||||
$dir = Join-Path $script:BuildRoot "dist/$name"
|
$dir = Join-Path $script:BuildRoot "dist/$name"
|
||||||
if (-not (Test-Path $dir)) { continue }
|
if (-not (Test-Path $dir)) { continue }
|
||||||
Get-ChildItem $dir -Force | Where-Object { $_.Name -notlike "GC-$script:BuildVersion-*.zip" } |
|
Get-ChildItem $dir -Force | Where-Object { $_.Name -notlike "GCL-$script:BuildVersion-*.zip" } |
|
||||||
Remove-Item -Recurse -Force -ErrorAction SilentlyContinue
|
Remove-Item -Recurse -Force -ErrorAction SilentlyContinue
|
||||||
}
|
}
|
||||||
Get-ChildItem (Join-Path $script:BuildRoot 'dist') -Filter '.DS_Store' -Recurse -Force -ErrorAction SilentlyContinue | Remove-Item -Force
|
Get-ChildItem (Join-Path $script:BuildRoot 'dist') -Filter '.DS_Store' -Recurse -Force -ErrorAction SilentlyContinue | Remove-Item -Force
|
||||||
@@ -314,6 +354,36 @@ function New-MacAppBundle {
|
|||||||
Write-Host "==> 已打包 $app"
|
Write-Host "==> 已打包 $app"
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function Invoke-SavedogTests {
|
||||||
|
$proj = Join-Path $script:BuildRoot 'GC/src/test/dotnet/GC.Savedog.Tests/GC.Savedog.Tests.csproj'
|
||||||
|
Write-Host '==> 运行应用器测试(整目录替换 / .GC/bin 合并 / 回滚)'
|
||||||
|
& dotnet run --project $proj -c Debug
|
||||||
|
if ($LASTEXITCODE -ne 0) { throw "应用器测试失败,退出码 $LASTEXITCODE" }
|
||||||
|
}
|
||||||
|
|
||||||
|
function Invoke-ReleaseVerify {
|
||||||
|
param([string]$Tag = '')
|
||||||
|
$root = $script:BuildRoot
|
||||||
|
$verifyTag = if ($Tag) { $Tag } else { $script:BuildVersion }
|
||||||
|
$work = Join-Path $root 'build/release-verify'
|
||||||
|
New-Item -ItemType Directory -Force -Path $work | Out-Null
|
||||||
|
|
||||||
|
Write-Host "==> 核对 Release $verifyTag"
|
||||||
|
$dump = Join-Path $work "$verifyTag.json"
|
||||||
|
& python3 (Join-Path $root 'buildsh/lib/verify_release.py') `
|
||||||
|
--tag $verifyTag `
|
||||||
|
--manifest (Join-Path $root 'version.json') `
|
||||||
|
--dump-manifest $dump
|
||||||
|
if ($LASTEXITCODE -ne 0) { throw "发布一致性核对未通过(tag $verifyTag)" }
|
||||||
|
|
||||||
|
Write-Host ''
|
||||||
|
Write-Host '==> 校验 tag 清单签名'
|
||||||
|
& dotnet run --project (Join-Path $root 'GC-SAVEDOG/GC-SAVEDOG.csproj') -c Release -- `
|
||||||
|
verify --manifest $dump
|
||||||
|
if ($LASTEXITCODE -ne 0) { throw '清单签名校验未通过,客户端会拒绝这次更新' }
|
||||||
|
Write-Host '结论: 签名可信,可以发布 / 已经发布正确'
|
||||||
|
}
|
||||||
|
|
||||||
function Invoke-FullBuild {
|
function Invoke-FullBuild {
|
||||||
Initialize-BuildProgress @('清理旧产物', '版本戳', '编译 Mac', '编译 Win-x64', '编译 Win-arm64', '运行骨架', '打包 zip', '收尾')
|
Initialize-BuildProgress @('清理旧产物', '版本戳', '编译 Mac', '编译 Win-x64', '编译 Win-arm64', '运行骨架', '打包 zip', '收尾')
|
||||||
try {
|
try {
|
||||||
@@ -322,8 +392,10 @@ function Invoke-FullBuild {
|
|||||||
New-Item -ItemType Directory -Force -Path (Join-Path $script:BuildRoot 'dist') | Out-Null
|
New-Item -ItemType Directory -Force -Path (Join-Path $script:BuildRoot 'dist') | Out-Null
|
||||||
Complete-BuildStep
|
Complete-BuildStep
|
||||||
|
|
||||||
Start-BuildStep '版本戳'; Invoke-VersionStamp; Complete-BuildStep
|
# 末次签名:这里只生成清单不签名,Pack-Launcher 打完包后统一签一次
|
||||||
Start-BuildStep '编译 Mac'; Publish-Rid 'osx-arm64' 'dist/mac-arm64' $false; Complete-BuildStep
|
Start-BuildStep '版本戳'; Invoke-VersionStamp -NoSign; Complete-BuildStep
|
||||||
|
# 与 buildsh 一致:启动器与守护进程都发布为压缩单文件,非本体文件在打包时收进 .GC/bin
|
||||||
|
Start-BuildStep '编译 Mac'; Publish-Rid 'osx-arm64' 'dist/mac-arm64' $true; Complete-BuildStep
|
||||||
Start-BuildStep '编译 Win-x64'; Publish-Rid 'win-x64' 'dist/win-amd64' $true; Complete-BuildStep
|
Start-BuildStep '编译 Win-x64'; Publish-Rid 'win-x64' 'dist/win-amd64' $true; Complete-BuildStep
|
||||||
Start-BuildStep '编译 Win-arm64'; Publish-Rid 'win-arm64' 'dist/win-arm64' $true; Complete-BuildStep
|
Start-BuildStep '编译 Win-arm64'; Publish-Rid 'win-arm64' 'dist/win-arm64' $true; Complete-BuildStep
|
||||||
|
|
||||||
@@ -337,7 +409,7 @@ function Invoke-FullBuild {
|
|||||||
Start-BuildStep '打包 zip'; Pack-Launcher; Complete-BuildStep
|
Start-BuildStep '打包 zip'; Pack-Launcher; Complete-BuildStep
|
||||||
Start-BuildStep '收尾'; Complete-BuildStep
|
Start-BuildStep '收尾'; Complete-BuildStep
|
||||||
Write-Host '==> 完成,产物:'
|
Write-Host '==> 完成,产物:'
|
||||||
Get-ChildItem (Join-Path $script:BuildRoot 'dist') -Recurse -Filter "GC-$script:BuildVersion-*.zip" | Select-Object FullName, Length
|
Get-ChildItem (Join-Path $script:BuildRoot 'dist') -Recurse -Filter "GCL-$script:BuildVersion-*.zip" | Select-Object FullName, Length
|
||||||
}
|
}
|
||||||
finally { Complete-BuildProgress }
|
finally { Complete-BuildProgress }
|
||||||
}
|
}
|
||||||
+101
-9
@@ -1,13 +1,66 @@
|
|||||||
#!/bin/sh
|
#!/bin/sh
|
||||||
# buildsh/build.sh —— 完整发布(原 publish)
|
# buildsh/build.sh —— 完整发布(原 publish)
|
||||||
# 步骤及权重按实测耗时设定,供进度条估算总进度与剩余时间:
|
#
|
||||||
# 清理(2) 版本(3) Mac(35) WinX64(25) WinArm(25) 骨架(3) 打包(5) 收尾(2) = 100
|
# 目标平台按构建主机决定,每条产物都带 Flutter 前端:
|
||||||
|
# macOS 主机 : mac-arm64(原生)+ win-amd64 / win-arm64(mingw 交叉)
|
||||||
|
# Linux 主机 : win-amd64 / win-arm64(mingw 交叉)
|
||||||
|
# Linux 产物默认不构建:目标为 linux-arm64,官方 Flutter 引擎只有
|
||||||
|
# x64 产物,必须在 aarch64 主机上编。需要时用 GC_BUILD_LINUX=1 显式开启
|
||||||
|
# (云端 aarch64 runner 就是这么用的)。
|
||||||
|
# Windows 主机: win-amd64 / win-arm64(原生)
|
||||||
|
#
|
||||||
|
# 前端是默认必需项:flutter 缺失或编译失败一律中断,不再悄悄产出只带 Avalonia
|
||||||
|
# 回退界面的包。确实要降级时用 ./build.sh build --allow-no-ui。
|
||||||
|
#
|
||||||
|
# 进度权重按实测耗时设定,供进度条估算总进度与剩余时间。
|
||||||
|
|
||||||
bs_build() {
|
bs_build() {
|
||||||
ROOT_DIR="$1"
|
ROOT_DIR="$1"
|
||||||
: "${APP_PROJ:?}" "${SLN:?}" "${VERSION:?}"
|
: "${APP_PROJ:?}" "${SLN:?}" "${VERSION:?}"
|
||||||
|
|
||||||
progress_init 100 2 3 35 25 25 3 5 2
|
HOST=$(uname -s)
|
||||||
|
BUILD_MAC=0
|
||||||
|
BUILD_LINUX=0
|
||||||
|
case "$HOST" in
|
||||||
|
Darwin) BUILD_MAC=1 ;;
|
||||||
|
MINGW*|MSYS*|CYGWIN*) : ;; # Windows 主机只能编 Windows
|
||||||
|
*) BUILD_LINUX=1 ;;
|
||||||
|
esac
|
||||||
|
# Linux 产物默认不出:目标平台是 linux-arm64,而官方 Flutter 引擎只发 x64 产物,
|
||||||
|
# x64 主机上编出来的是 x64 二进制,装到 arm 机器上跑不起来。
|
||||||
|
# 需要时显式开启(云端 aarch64 runner):GC_BUILD_LINUX=1 ./build.sh build
|
||||||
|
if [ "$BUILD_LINUX" = 1 ]; then
|
||||||
|
case "${GC_BUILD_LINUX:-0}" in
|
||||||
|
1|true|yes)
|
||||||
|
case "$(uname -m)" in
|
||||||
|
aarch64|arm64) ;;
|
||||||
|
*)
|
||||||
|
BUILD_LINUX=0
|
||||||
|
echo "!! 已请求 Linux 产物,但当前主机是 $(uname -m)"
|
||||||
|
echo " (linux-arm64 需要有 aarch64 主机,Flutter 引擎只有 x64 官方产物)"
|
||||||
|
;;
|
||||||
|
esac
|
||||||
|
;;
|
||||||
|
*)
|
||||||
|
BUILD_LINUX=0
|
||||||
|
echo "==> 跳过 Linux 产物(默认不构建;需要时用 GC_BUILD_LINUX=1 显式开启)"
|
||||||
|
;;
|
||||||
|
esac
|
||||||
|
fi
|
||||||
|
|
||||||
|
# 显式降级:允许在没有该平台 Flutter 宿主的情况下仍出 Avalonia 版包
|
||||||
|
ALLOW_NO_UI="${GC_ALLOW_NO_UI:-0}"
|
||||||
|
|
||||||
|
# 权重:清理 版本 Mac WinX64 WinArm64 Linux 前端 骨架 打包 收尾
|
||||||
|
WEIGHTS="2 3"
|
||||||
|
[ "$BUILD_MAC" = 1 ] && WEIGHTS="$WEIGHTS 35"
|
||||||
|
WEIGHTS="$WEIGHTS 25 25"
|
||||||
|
[ "$BUILD_LINUX" = 1 ] && WEIGHTS="$WEIGHTS 30"
|
||||||
|
WEIGHTS="$WEIGHTS 25 3 5 2"
|
||||||
|
TOTAL=0
|
||||||
|
for _w in $WEIGHTS; do TOTAL=$((TOTAL + _w)); done
|
||||||
|
|
||||||
|
progress_init "$TOTAL" $WEIGHTS
|
||||||
|
|
||||||
progress_step "清理旧产物"; progress_tick 100
|
progress_step "清理旧产物"; progress_tick 100
|
||||||
rm -rf "$ROOT_DIR/dist"; mkdir -p "$ROOT_DIR/dist"
|
rm -rf "$ROOT_DIR/dist"; mkdir -p "$ROOT_DIR/dist"
|
||||||
@@ -18,7 +71,9 @@ bs_build() {
|
|||||||
fi
|
fi
|
||||||
|
|
||||||
progress_step "版本戳"; progress_tick 100
|
progress_step "版本戳"; progress_tick 100
|
||||||
stamp_versions
|
# 末次签名:这里只生成清单不签名,等 pack_launcher 打完 zip、刷新完包信息后统一签一次。
|
||||||
|
# 避免 ECDSA 随机签名 + 时间戳导致清单在中间反复变化。
|
||||||
|
stamp_versions --no-sign
|
||||||
|
|
||||||
# 每个 publish 用后台任务包裹,边跑边按「已用时/预估用时」推进当前步骤进度
|
# 每个 publish 用后台任务包裹,边跑边按「已用时/预估用时」推进当前步骤进度
|
||||||
_run_publish() {
|
_run_publish() {
|
||||||
@@ -37,8 +92,19 @@ bs_build() {
|
|||||||
progress_tick 100
|
progress_tick 100
|
||||||
}
|
}
|
||||||
|
|
||||||
progress_step "编译 Mac"
|
if [ "$BUILD_MAC" = 1 ]; then
|
||||||
_run_publish mac 90 publish_rid "osx-arm64" "dist/mac-arm64" false || return 1
|
progress_step "编译 Mac"
|
||||||
|
_run_publish mac 90 publish_rid "osx-arm64" "dist/mac-arm64" true || return 1
|
||||||
|
# Flutter 的 macOS 产物必须用 Xcode 在本机编,Linux 上无法替代
|
||||||
|
build_flutter_ui macos "dist/mac-arm64" || {
|
||||||
|
echo "!! macOS 前端编译失败。macOS 版 Flutter 只能在 macOS 上编。"
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
elif [ "$ALLOW_NO_UI" = 1 ]; then
|
||||||
|
progress_step "编译 Mac"
|
||||||
|
_run_publish mac 90 publish_rid "osx-arm64" "dist/mac-arm64" true || return 1
|
||||||
|
echo "!! --allow-no-ui:macOS 包内不含 Flutter 前端,启动器将回退 Avalonia"
|
||||||
|
fi
|
||||||
|
|
||||||
progress_step "编译 Win-x64"
|
progress_step "编译 Win-x64"
|
||||||
_run_publish winx64 70 publish_rid "win-x64" "dist/win-amd64" true || return 1
|
_run_publish winx64 70 publish_rid "win-x64" "dist/win-amd64" true || return 1
|
||||||
@@ -46,11 +112,37 @@ bs_build() {
|
|||||||
progress_step "编译 Win-arm64"
|
progress_step "编译 Win-arm64"
|
||||||
_run_publish winarm 70 publish_rid "win-arm64" "dist/win-arm64" true || return 1
|
_run_publish winarm 70 publish_rid "win-arm64" "dist/win-arm64" true || return 1
|
||||||
|
|
||||||
|
if [ "$BUILD_LINUX" = 1 ]; then
|
||||||
|
progress_step "编译 Linux"
|
||||||
|
_run_publish linux 70 publish_rid "linux-arm64" "dist/linux-arm64" true || return 1
|
||||||
|
build_flutter_ui linux "dist/linux-arm64" || return 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Windows 前端:Windows 主机走官方 toolchain;Linux/macOS 主机用 mingw-w64 +
|
||||||
|
# wine 交叉编译(buildsh/cross)。只产出 x64 一份,两个包共用,
|
||||||
|
# ARM64 上由系统模拟 x64 进程运行前端。
|
||||||
|
progress_step "编译 Win 前端"
|
||||||
|
case "$HOST" in
|
||||||
|
MINGW*|MSYS*|CYGWIN*) build_flutter_ui windows "dist/win-flutter" || return 1 ;;
|
||||||
|
*) build_flutter_ui_cross "dist/win-flutter" || return 1 ;;
|
||||||
|
esac
|
||||||
|
for label in win-amd64 win-arm64; do
|
||||||
|
cp -R "$ROOT_DIR/dist/win-flutter/." "$ROOT_DIR/dist/$label/"
|
||||||
|
done
|
||||||
|
rm -rf "$ROOT_DIR/dist/win-flutter"
|
||||||
|
|
||||||
progress_step "运行骨架"; progress_tick 100
|
progress_step "运行骨架"; progress_tick 100
|
||||||
package_mac_app
|
if [ -d "$ROOT_DIR/dist/mac-arm64" ]; then
|
||||||
|
package_mac_app
|
||||||
|
fi
|
||||||
prepare_runtime_layout "dist/win-amd64"
|
prepare_runtime_layout "dist/win-amd64"
|
||||||
prepare_runtime_layout "dist/win-arm64"
|
prepare_runtime_layout "dist/win-arm64"
|
||||||
prepare_runtime_layout "dist/mac-arm64/GC.app/Contents/MacOS"
|
if [ "$BUILD_LINUX" = 1 ]; then
|
||||||
|
prepare_runtime_layout "dist/linux-arm64"
|
||||||
|
fi
|
||||||
|
if [ -d "$ROOT_DIR/dist/mac-arm64/GC.app/Contents/MacOS" ]; then
|
||||||
|
prepare_runtime_layout "dist/mac-arm64/GC.app/Contents/MacOS"
|
||||||
|
fi
|
||||||
|
|
||||||
progress_step "打包 zip"; progress_tick 100
|
progress_step "打包 zip"; progress_tick 100
|
||||||
pack_launcher
|
pack_launcher
|
||||||
@@ -58,5 +150,5 @@ bs_build() {
|
|||||||
progress_step "收尾"; progress_tick 100
|
progress_step "收尾"; progress_tick 100
|
||||||
progress_done
|
progress_done
|
||||||
echo "==> 完成,产物:"
|
echo "==> 完成,产物:"
|
||||||
ls -lh "$ROOT_DIR"/dist/*/GC-"$VERSION"-*.zip 2>/dev/null || true
|
ls -lh "$ROOT_DIR"/dist/*/GCL-"$VERSION"-*.zip 2>/dev/null || true
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,121 @@
|
|||||||
|
cmake_minimum_required(VERSION 3.14)
|
||||||
|
|
||||||
|
# 交叉编译 Flutter Windows 桌面外壳。
|
||||||
|
#
|
||||||
|
# 只编译 C++ 层:runner(Win32 窗口)+ cpp_client_wrapper(Dart 互操作)。
|
||||||
|
# Dart 侧的 flutter_assets 由 flutter assemble 单独产出,最后与
|
||||||
|
# flutter_windows.dll 一起摆进同一个目录就是完整的可运行包。
|
||||||
|
#
|
||||||
|
# 与 windows/CMakeLists.txt 的区别:不调用 tool_backend.bat(它在非 Windows
|
||||||
|
# 上不可执行),也不依赖 Visual Studio 生成器。
|
||||||
|
|
||||||
|
project(gc_ui_cross LANGUAGES CXX RC)
|
||||||
|
|
||||||
|
get_filename_component(APP_DIR "${CMAKE_CURRENT_LIST_DIR}/../../GC-UI/frontend" ABSOLUTE)
|
||||||
|
|
||||||
|
set(WIN_DIR "${APP_DIR}/windows")
|
||||||
|
set(RUN_DIR "${WIN_DIR}/runner")
|
||||||
|
set(EPHEMERAL "${WIN_DIR}/flutter/ephemeral")
|
||||||
|
set(WRAPPER "${EPHEMERAL}/cpp_client_wrapper")
|
||||||
|
set(DLL_LIB "${EPHEMERAL}/flutter_windows.dll.lib")
|
||||||
|
|
||||||
|
foreach(required
|
||||||
|
"${EPHEMERAL}/flutter_windows.dll"
|
||||||
|
"${DLL_LIB}"
|
||||||
|
"${WRAPPER}/core_implementations.cc")
|
||||||
|
if(NOT EXISTS "${required}")
|
||||||
|
message(FATAL_ERROR
|
||||||
|
"缺少 Flutter Windows 引擎产物:${required}\n"
|
||||||
|
"先运行 buildsh/cross/build-ui-win-cross.sh 里的 fetch_engine 步骤。")
|
||||||
|
endif()
|
||||||
|
endforeach()
|
||||||
|
|
||||||
|
set(FLUTTER_VERSION "1.0.0" CACHE STRING "写入 exe 版本资源")
|
||||||
|
|
||||||
|
# windres 在非 Windows 主机上不按 rc 文件所在目录解析图标路径,
|
||||||
|
# 这里把 resources\\app_icon.ico 换成绝对路径再交给 windres。
|
||||||
|
# 注意只替换这一处:rc 里其它 "\0" 是字符串转义,不能动。
|
||||||
|
file(READ "${RUN_DIR}/Runner.rc" _rc_text)
|
||||||
|
string(REPLACE "resources\\\\app_icon.ico" "${RUN_DIR}/resources/app_icon.ico" _rc_text "${_rc_text}")
|
||||||
|
# windres 收到 -DFLUTTER_VERSION=\"1.0.0\" 时会把反斜杠留在宏值里,展开成非法 token。
|
||||||
|
# 直接把宏定义成字面量,绕开命令行转义。
|
||||||
|
string(REPLACE "#define VERSION_AS_STRING FLUTTER_VERSION"
|
||||||
|
"#define VERSION_AS_STRING \"${FLUTTER_VERSION}\""
|
||||||
|
_rc_text "${_rc_text}")
|
||||||
|
file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/Runner.cross.rc" "${_rc_text}")
|
||||||
|
|
||||||
|
# ★ DPI 清单必须自己嵌进去。
|
||||||
|
#
|
||||||
|
# windows/runner/CMakeLists.txt 把 runner.exe.manifest 当源文件列进 target,
|
||||||
|
# Visual Studio 生成器会把它交给链接器(/MANIFESTINPUT)自动嵌入;
|
||||||
|
# 但这里的交叉编译只用 windres 编 Runner.rc,CMake 不会做这一步,
|
||||||
|
# 编出来的 GC-UI.exe 就完全没有清单 —— Windows 当它「DPI 不感知」,
|
||||||
|
# 在 125% / 150% 缩放的屏幕上整体位图拉伸,界面全是糊的。
|
||||||
|
#
|
||||||
|
# 因此把清单直接写成资源条目:id 1 = CREATEPROCESS_MANIFEST_RESOURCE_ID,
|
||||||
|
# type 24 = RT_MANIFEST。windres 不按相对路径解析,这里给绝对路径。
|
||||||
|
file(APPEND "${CMAKE_CURRENT_BINARY_DIR}/Runner.cross.rc"
|
||||||
|
"\n1 24 \"${RUN_DIR}/runner.exe.manifest\"\n")
|
||||||
|
|
||||||
|
add_executable(${BINARY_NAME} WIN32
|
||||||
|
"${RUN_DIR}/main.cpp"
|
||||||
|
"${RUN_DIR}/flutter_window.cpp"
|
||||||
|
"${RUN_DIR}/utils.cpp"
|
||||||
|
"${RUN_DIR}/win32_window.cpp"
|
||||||
|
"${WIN_DIR}/flutter/generated_plugin_registrant.cc"
|
||||||
|
"${WRAPPER}/core_implementations.cc"
|
||||||
|
"${WRAPPER}/standard_codec.cc"
|
||||||
|
"${WRAPPER}/plugin_registrar.cc"
|
||||||
|
"${WRAPPER}/flutter_engine.cc"
|
||||||
|
"${WRAPPER}/flutter_view_controller.cc"
|
||||||
|
"${CMAKE_CURRENT_BINARY_DIR}/Runner.cross.rc"
|
||||||
|
)
|
||||||
|
|
||||||
|
target_include_directories(${BINARY_NAME} PRIVATE
|
||||||
|
"${RUN_DIR}"
|
||||||
|
"${WIN_DIR}"
|
||||||
|
"${EPHEMERAL}"
|
||||||
|
"${EPHEMERAL}/include"
|
||||||
|
"${WRAPPER}/include"
|
||||||
|
)
|
||||||
|
|
||||||
|
target_compile_features(${BINARY_NAME} PRIVATE cxx_std_17)
|
||||||
|
|
||||||
|
# Flutter 的 C++ wrapper 需要 RTTI 与异常;线程安全相关的锁依赖 posix 线程模型。
|
||||||
|
target_compile_options(${BINARY_NAME} PRIVATE
|
||||||
|
-fexceptions
|
||||||
|
-frtti
|
||||||
|
-Wall
|
||||||
|
-Wno-unused-parameter
|
||||||
|
-Wno-missing-field-initializers
|
||||||
|
)
|
||||||
|
|
||||||
|
# Runner.rc 里的 #include "resource.h" / runner.exe.manifest 都是相对路径,
|
||||||
|
# windres 不按源文件目录解析,必须显式给 -I。
|
||||||
|
set_source_files_properties("${RUN_DIR}/Runner.rc" PROPERTIES
|
||||||
|
COMPILE_FLAGS "-I\"${RUN_DIR}\"")
|
||||||
|
|
||||||
|
target_compile_definitions(${BINARY_NAME} PRIVATE
|
||||||
|
"FLUTTER_VERSION=\"${FLUTTER_VERSION}\""
|
||||||
|
"FLUTTER_VERSION_MAJOR=${FLUTTER_VERSION_MAJOR}"
|
||||||
|
"FLUTTER_VERSION_MINOR=${FLUTTER_VERSION_MINOR}"
|
||||||
|
"FLUTTER_VERSION_PATCH=${FLUTTER_VERSION_PATCH}"
|
||||||
|
"FLUTTER_VERSION_BUILD=${FLUTTER_VERSION_BUILD}"
|
||||||
|
"NOMINMAX"
|
||||||
|
)
|
||||||
|
|
||||||
|
target_link_libraries(${BINARY_NAME} PRIVATE
|
||||||
|
"${DLL_LIB}"
|
||||||
|
dwmapi
|
||||||
|
ole32
|
||||||
|
uuid
|
||||||
|
)
|
||||||
|
|
||||||
|
# runner 的入口是 wWinMain(宽字符版);MSVC 自动处理,mingw 需要 -municode
|
||||||
|
# 才会链接 wWinMainCRTStartup,否则报 undefined reference to `WinMain'。
|
||||||
|
target_link_options(${BINARY_NAME} PRIVATE -municode)
|
||||||
|
|
||||||
|
set_target_properties(${BINARY_NAME} PROPERTIES
|
||||||
|
OUTPUT_NAME "GC-UI"
|
||||||
|
SUFFIX ".exe"
|
||||||
|
)
|
||||||
Executable
+221
@@ -0,0 +1,221 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
#
|
||||||
|
# 在 Linux / macOS 上交叉编译 Flutter Windows 桌面界面(GC-UI)。
|
||||||
|
#
|
||||||
|
# ./buildsh/cross/build-ui-win-cross.sh [输出目录]
|
||||||
|
#
|
||||||
|
# 产物目录是可直接拷到 Windows 上运行的一整套:
|
||||||
|
# GC-UI.exe flutter_windows.dll data/{icudtl.dat,app.so,flutter_assets/}
|
||||||
|
#
|
||||||
|
# 原理:
|
||||||
|
# Flutter 的 Windows 外壳(runner + cpp_client_wrapper)是纯 Win32 + 标准 C++,
|
||||||
|
# 只通过 C ABI 调 flutter_windows.dll,所以 mingw-w64 就能编译。
|
||||||
|
# 唯一的 Windows 专属步骤是 AOT 快照生成(gen_snapshot.exe 是 PE 文件),
|
||||||
|
# 用 wine 执行即可,全流程不需要 Windows 机器或 MSVC。
|
||||||
|
#
|
||||||
|
# 依赖:
|
||||||
|
# Linux sudo apt install mingw-w64 cmake ninja-build wine unzip curl
|
||||||
|
# macOS brew install mingw-w64 cmake ninja && brew install --cask wine-stable
|
||||||
|
#
|
||||||
|
# 环境变量:
|
||||||
|
# FLUTTER_BIN flutter 可执行文件(默认 PATH 中的 flutter,要求 3.24+)
|
||||||
|
# WIN_ENGINE_MIRROR 引擎产物来源(默认官方 GCS,国内可换 storage.flutter-io.cn)
|
||||||
|
#
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
|
ROOT_DIR=$(cd "$(dirname "$0")/../.." && pwd)
|
||||||
|
UI_DIR="$ROOT_DIR/GC-UI/frontend"
|
||||||
|
OUT_DIR="${1:-$UI_DIR/build/windows/x64/runner/Release}"
|
||||||
|
BUILD_DIR="$UI_DIR/build/windows/x64/cross"
|
||||||
|
|
||||||
|
say() { printf '\033[36m==>\033[0m %s\n' "$*"; }
|
||||||
|
warn() { printf '\033[33m!!\033[0m %s\n' "$*"; }
|
||||||
|
die() { printf '\033[31mxx\033[0m %s\n' "$*" >&2; exit 1; }
|
||||||
|
|
||||||
|
need() { command -v "$1" >/dev/null 2>&1 || die "缺少 $1($2)"; }
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------- 工具链
|
||||||
|
|
||||||
|
MINGW_CXX=""
|
||||||
|
check_toolchain() {
|
||||||
|
need cmake "Linux: apt install cmake;macOS: brew install cmake"
|
||||||
|
need ninja "Linux: apt install ninja-build;macOS: brew install ninja"
|
||||||
|
need unzip "Linux: apt install unzip"
|
||||||
|
need curl "Linux: apt install curl"
|
||||||
|
|
||||||
|
for c in x86_64-w64-mingw32-g++-posix x86_64-w64-mingw32-g++; do
|
||||||
|
if command -v "$c" >/dev/null 2>&1; then MINGW_CXX="$c"; break; fi
|
||||||
|
done
|
||||||
|
[ -n "$MINGW_CXX" ] || die "缺少 mingw-w64 C++ 编译器
|
||||||
|
Linux: sudo apt install g++-mingw-w64-x86-64-posix
|
||||||
|
macOS: brew install mingw-w64"
|
||||||
|
|
||||||
|
command -v x86_64-w64-mingw32-windres >/dev/null 2>&1 || die "缺少 mingw-w64 资源编译器"
|
||||||
|
|
||||||
|
# gen_snapshot.exe 靠 wine 执行;没有 wine 就只能出 debug 版(JIT)
|
||||||
|
if command -v wine >/dev/null 2>&1 || command -v wine64 >/dev/null 2>&1; then
|
||||||
|
WINE_BIN=$(command -v wine 2>/dev/null || command -v wine64)
|
||||||
|
else
|
||||||
|
die "缺少 wine(AOT 快照需要执行 Windows 版 gen_snapshot.exe)
|
||||||
|
Linux: sudo apt install wine
|
||||||
|
macOS: brew install --cask wine-stable"
|
||||||
|
fi
|
||||||
|
}
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------- Flutter
|
||||||
|
|
||||||
|
resolve_flutter() {
|
||||||
|
FLUTTER_BIN="${FLUTTER_BIN:-flutter}"
|
||||||
|
command -v "$FLUTTER_BIN" >/dev/null 2>&1 || die "未找到 flutter,可设置 FLUTTER_BIN=/path/to/flutter"
|
||||||
|
|
||||||
|
local bin_path root target
|
||||||
|
bin_path=$(command -v "$FLUTTER_BIN")
|
||||||
|
while [ -L "$bin_path" ]; do
|
||||||
|
target=$(readlink "$bin_path")
|
||||||
|
case "$target" in
|
||||||
|
/*) bin_path="$target" ;;
|
||||||
|
*) bin_path="$(cd "$(dirname "$bin_path")" && pwd)/$target" ;;
|
||||||
|
esac
|
||||||
|
done
|
||||||
|
root=$(cd "$(dirname "$bin_path")/.." && pwd)
|
||||||
|
|
||||||
|
[ -f "$root/bin/internal/engine.version" ] || die "$root 不像 Flutter SDK 根目录"
|
||||||
|
FLUTTER_ROOT="$root"
|
||||||
|
ENGINE_DIR="$root/bin/cache/artifacts/engine"
|
||||||
|
ENGINE_HASH=$(tr -d '[:space:]' < "$root/bin/internal/engine.version")
|
||||||
|
|
||||||
|
# pubspec 要求 Dart 3.5+(Flutter 3.24+),版本不对直接提醒
|
||||||
|
local dart_ver
|
||||||
|
dart_ver=$("$root/bin/cache/dart-sdk/bin/dart" --version 2>/dev/null | grep -oE '[0-9]+\.[0-9]+\.[0-9]+' | head -1) || dart_ver=""
|
||||||
|
say "Flutter SDK: $root(engine ${ENGINE_HASH:0:10}${dart_ver:+, dart $dart_ver})"
|
||||||
|
}
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------- 引擎产物
|
||||||
|
|
||||||
|
ENGINE_DIR="" # 由 resolve_flutter 填充
|
||||||
|
|
||||||
|
fetch_engine() {
|
||||||
|
local base="$MIRROR/flutter/$ENGINE_HASH"
|
||||||
|
local cache="${TMPDIR:-/tmp}/gc-win-engine"
|
||||||
|
mkdir -p "$cache"
|
||||||
|
|
||||||
|
# 每个条目:远端相对路径 | 落地目录 | 落地后的标志文件
|
||||||
|
local -a items=(
|
||||||
|
"windows-x64-release/windows-x64-flutter.zip|$ENGINE_DIR/windows-x64-release|flutter_windows.dll.lib"
|
||||||
|
"windows-x64/artifacts.zip|$ENGINE_DIR/windows-x64|frontend_server_aot.dart.snapshot"
|
||||||
|
"windows-x64/flutter-cpp-client-wrapper.zip|$ENGINE_DIR/windows-x64/cpp_client_wrapper|core_implementations.cc"
|
||||||
|
)
|
||||||
|
|
||||||
|
local item remote dest marker zip
|
||||||
|
for item in "${items[@]}"; do
|
||||||
|
IFS='|' read -r remote dest marker <<<"$item"
|
||||||
|
[ -f "$dest/$marker" ] && continue
|
||||||
|
|
||||||
|
zip="$cache/$(echo "$remote" | tr '/' '_')"
|
||||||
|
if [ ! -s "$zip" ]; then
|
||||||
|
say "下载 $(basename "$remote")"
|
||||||
|
curl -fL --retry 3 --retry-delay 2 -o "$zip.part" "$base/$remote" \
|
||||||
|
|| die "下载失败:$base/$remote
|
||||||
|
可设置 WIN_ENGINE_MIRROR=https://storage.flutter-io.cn/flutter_infra_release 走国内镜像"
|
||||||
|
mv "$zip.part" "$zip"
|
||||||
|
fi
|
||||||
|
mkdir -p "$dest"
|
||||||
|
unzip -oq "$zip" -d "$dest"
|
||||||
|
done
|
||||||
|
|
||||||
|
install_gen_snapshot_shim
|
||||||
|
}
|
||||||
|
|
||||||
|
# flutter_tools 会直接 exec $ENGINE_DIR/*/gen_snapshot(无 .exe 后缀)。
|
||||||
|
# 这里放一个调用 wine 的同名脚本,并给原本的 exe 加上 .win 后缀避免混淆。
|
||||||
|
install_gen_snapshot_shim() {
|
||||||
|
local dirs=("$ENGINE_DIR/windows-x64-release" "$ENGINE_DIR/windows-x64")
|
||||||
|
local dir shim
|
||||||
|
for dir in "${dirs[@]}"; do
|
||||||
|
[ -f "$dir/gen_snapshot.exe" ] || continue
|
||||||
|
[ -f "$dir/gen_snapshot.exe.win" ] || mv "$dir/gen_snapshot.exe" "$dir/gen_snapshot.exe.win"
|
||||||
|
|
||||||
|
shim="$dir/gen_snapshot"
|
||||||
|
cat > "$shim" <<EOF
|
||||||
|
#!/bin/sh
|
||||||
|
# 由 buildsh/cross/build-ui-win-cross.sh 生成:用 wine 执行 Windows 版 gen_snapshot。
|
||||||
|
export WINEPREFIX="\${WINEPREFIX:-\$HOME/.wine64}"
|
||||||
|
export WINEDEBUG=-all
|
||||||
|
exec "$WINE_BIN" "$dir/gen_snapshot.exe.win" "\$@"
|
||||||
|
EOF
|
||||||
|
chmod +x "$shim"
|
||||||
|
done
|
||||||
|
}
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------- 构建
|
||||||
|
|
||||||
|
build_assets_and_aot() {
|
||||||
|
say "生成 Dart 资源与 AOT 快照"
|
||||||
|
( cd "$UI_DIR" && "$FLUTTER_BIN" --no-version-check --suppress-analytics pub get >/dev/null )
|
||||||
|
|
||||||
|
local dart="$FLUTTER_ROOT/bin/cache/dart-sdk/bin/dart"
|
||||||
|
local tool="$FLUTTER_ROOT/packages/flutter_tools/bin/tool_backend.dart"
|
||||||
|
|
||||||
|
# tool_backend 是官方 CMake 调用的同一入口:解包引擎产物到 ephemeral、
|
||||||
|
# 生成 flutter_assets、aot_elf_release。它末尾的收尾步骤在非 Windows host
|
||||||
|
# 上可能非零退出,所以只校验产物是否齐备。
|
||||||
|
( cd "$UI_DIR" && \
|
||||||
|
FLUTTER_ROOT="$FLUTTER_ROOT" \
|
||||||
|
PROJECT_DIR="$UI_DIR" \
|
||||||
|
FLUTTER_STORAGE_BASE_URL="${FLUTTER_STORAGE_BASE_URL:-$MIRROR}" \
|
||||||
|
"$dart" "$tool" windows-x64 release ) || true
|
||||||
|
|
||||||
|
[ -f "$UI_DIR/build/windows/app.so" ] || die "AOT 快照未生成(wine 执行 gen_snapshot 失败?)"
|
||||||
|
[ -d "$UI_DIR/build/flutter_assets" ] || die "flutter_assets 未生成"
|
||||||
|
say "AOT 快照 $(du -h "$UI_DIR/build/windows/app.so" | cut -f1),资源 $(du -sh "$UI_DIR/build/flutter_assets" | cut -f1)"
|
||||||
|
}
|
||||||
|
|
||||||
|
build_cpp() {
|
||||||
|
local ver major minor patch build_no
|
||||||
|
read -r major minor patch build_no <<<"$(sed -n 's/^version:[[:space:]]*//p' "$UI_DIR/pubspec.yaml" \
|
||||||
|
| head -1 | awk -F'[.+]' '{print $1+0, $2+0, $3+0, ($4==""?0:$4+0)}')"
|
||||||
|
ver="${major}.${minor}.${patch}"
|
||||||
|
|
||||||
|
say "编译 C++ 外壳($(basename "$MINGW_CXX"))"
|
||||||
|
cmake -S "$ROOT_DIR/buildsh/cross" -B "$BUILD_DIR" -G Ninja \
|
||||||
|
-DCMAKE_TOOLCHAIN_FILE="$ROOT_DIR/buildsh/cross/toolchain-mingw.cmake" \
|
||||||
|
-DCMAKE_BUILD_TYPE=Release \
|
||||||
|
-DBINARY_NAME=GC-UI \
|
||||||
|
-DFLUTTER_VERSION="$ver" \
|
||||||
|
-DFLUTTER_VERSION_MAJOR="$major" \
|
||||||
|
-DFLUTTER_VERSION_MINOR="$minor" \
|
||||||
|
-DFLUTTER_VERSION_PATCH="$patch" \
|
||||||
|
-DFLUTTER_VERSION_BUILD="$build_no" >/dev/null
|
||||||
|
|
||||||
|
cmake --build "$BUILD_DIR" -- -j "$(getconf _NPROCESSORS_ONLN 2>/dev/null || echo 4)" \
|
||||||
|
|| die "C++ 编译失败"
|
||||||
|
|
||||||
|
[ -f "$BUILD_DIR/GC-UI.exe" ] || die "未产出 GC-UI.exe"
|
||||||
|
}
|
||||||
|
|
||||||
|
stage() {
|
||||||
|
local eph="$UI_DIR/windows/flutter/ephemeral"
|
||||||
|
say "组装到 $OUT_DIR"
|
||||||
|
rm -rf "$OUT_DIR"
|
||||||
|
mkdir -p "$OUT_DIR/data"
|
||||||
|
|
||||||
|
cp "$BUILD_DIR/GC-UI.exe" "$OUT_DIR/"
|
||||||
|
cp "$eph/flutter_windows.dll" "$OUT_DIR/"
|
||||||
|
cp "$eph/icudtl.dat" "$OUT_DIR/data/"
|
||||||
|
cp "$UI_DIR/build/windows/app.so" "$OUT_DIR/data/"
|
||||||
|
cp -R "$UI_DIR/build/flutter_assets/." "$OUT_DIR/data/flutter_assets/"
|
||||||
|
|
||||||
|
say "完成:$(du -sh "$OUT_DIR" | cut -f1)"
|
||||||
|
find "$OUT_DIR" -maxdepth 2 -mindepth 1 | sed "s|$OUT_DIR| .|"
|
||||||
|
}
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------- main
|
||||||
|
|
||||||
|
MIRROR="${WIN_ENGINE_MIRROR:-https://storage.googleapis.com/flutter_infra_release}"
|
||||||
|
|
||||||
|
check_toolchain
|
||||||
|
resolve_flutter
|
||||||
|
fetch_engine
|
||||||
|
build_assets_and_aot
|
||||||
|
build_cpp
|
||||||
|
stage
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
# 在 Linux / macOS 上交叉编译 Flutter Windows 桌面应用的 CMake 工具链。
|
||||||
|
#
|
||||||
|
# 原理:Flutter 的 Windows 嵌入层(windows/runner/*.cpp + cpp_client_wrapper)
|
||||||
|
# 是纯 Win32 + 标准 C++,只通过 C ABI 调用 flutter_windows.dll。因此用
|
||||||
|
# mingw-w64(GCC,posix 线程模型)即可产出与官方 toolchain 等价的 PE 产物,
|
||||||
|
# 不需要 Windows 机器,也不需要 MSVC。
|
||||||
|
#
|
||||||
|
# 用法:
|
||||||
|
# cmake -B build -G Ninja -DCMAKE_TOOLCHAIN_FILE=.../toolchain-mingw.cmake ...
|
||||||
|
|
||||||
|
set(CMAKE_SYSTEM_NAME Windows)
|
||||||
|
set(CMAKE_SYSTEM_VERSION 10.0)
|
||||||
|
set(CMAKE_SYSTEM_PROCESSOR x86_64)
|
||||||
|
|
||||||
|
set(MINGW_PREFIX "x86_64-w64-mingw32" CACHE STRING "目标三元组前缀")
|
||||||
|
|
||||||
|
# 必须用 posix 线程模型:Flutter 的 C++ wrapper 依赖 std::mutex / std::thread,
|
||||||
|
# win32 线程模型下的 libstdc++ 不提供这些类型。
|
||||||
|
find_program(MINGW_C NAMES ${MINGW_PREFIX}-gcc-posix ${MINGW_PREFIX}-gcc REQUIRED)
|
||||||
|
find_program(MINGW_CXX NAMES ${MINGW_PREFIX}-g++-posix ${MINGW_PREFIX}-g++ REQUIRED)
|
||||||
|
find_program(MINGW_RC NAMES ${MINGW_PREFIX}-windres REQUIRED)
|
||||||
|
|
||||||
|
set(CMAKE_C_COMPILER "${MINGW_C}")
|
||||||
|
set(CMAKE_CXX_COMPILER "${MINGW_CXX}")
|
||||||
|
set(CMAKE_RC_COMPILER "${MINGW_RC}")
|
||||||
|
|
||||||
|
set(CMAKE_FIND_ROOT_PATH "/usr/${MINGW_PREFIX}")
|
||||||
|
set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER)
|
||||||
|
set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY)
|
||||||
|
set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY)
|
||||||
|
set(CMAKE_FIND_ROOT_PATH_MODE_PACKAGE ONLY)
|
||||||
|
|
||||||
|
# 静态链接 libgcc / libstdc++ / winpthread,产物只依赖 flutter_windows.dll
|
||||||
|
# 和系统 DLL,拷到干净机器上也能跑。
|
||||||
|
set(CMAKE_CXX_FLAGS_INIT "-DUNICODE -D_UNICODE -DNOMINMAX -D_HAS_EXCEPTIONS=1")
|
||||||
|
set(CMAKE_EXE_LINKER_FLAGS_INIT "-static -static-libgcc -static-libstdc++")
|
||||||
+236
-71
@@ -6,10 +6,17 @@
|
|||||||
if ! type step >/dev/null 2>&1; then step() { echo "==> $1"; }; fi
|
if ! type step >/dev/null 2>&1; then step() { echo "==> $1"; }; fi
|
||||||
if ! type progress >/dev/null 2>&1; then progress() { :; }; fi
|
if ! type progress >/dev/null 2>&1; then progress() { :; }; fi
|
||||||
|
|
||||||
|
# $1=--no-sign 时只生成清单、不签名。
|
||||||
|
# 完整 build 会在 pack_launcher 末尾统一签一次(末次签名),中间这次签名是浪费的:
|
||||||
|
# ECDSA 用随机 nonce + signedAt 时间戳,每次签名字节都不同,白白多一次全量签名,
|
||||||
|
# 也让中间产物反复抖动。单独的 stamp / models 工具没有后续打包,仍走默认签名。
|
||||||
stamp_versions() {
|
stamp_versions() {
|
||||||
echo "==> 自动计算模型版本并生成 version.json"
|
echo "==> 自动计算模型版本并生成 version.json"
|
||||||
dotnet run --project "$STAMP_PROJ" -c Release -- "$ROOT_DIR" "$VERSION"
|
dotnet run --project "$STAMP_PROJ" -c Release -- "$ROOT_DIR" "$VERSION"
|
||||||
sign_manifest
|
case "${1:-}" in
|
||||||
|
--no-sign) echo " (跳过签名,打包结束后统一签一次)" ;;
|
||||||
|
*) sign_manifest ;;
|
||||||
|
esac
|
||||||
}
|
}
|
||||||
|
|
||||||
# 打完 zip 之后刷新 launcher.packages(写入 path / dir / name / sha256 / size)。
|
# 打完 zip 之后刷新 launcher.packages(写入 path / dir / name / sha256 / size)。
|
||||||
@@ -24,7 +31,7 @@ stamp_launcher_only() {
|
|||||||
# 没有私钥时只警告:清单不带 signature,客户端会按「未签名」处理。
|
# 没有私钥时只警告:清单不带 signature,客户端会按「未签名」处理。
|
||||||
sign_manifest() {
|
sign_manifest() {
|
||||||
KEY="$ROOT_DIR/.signing/gc-signing.pem"
|
KEY="$ROOT_DIR/.signing/gc-signing.pem"
|
||||||
KEYID="${GC_SIGNING_KEY_ID:-gc-2026-11}"
|
KEYID="${GC_SIGNING_KEY_ID:-gc-2026-12}"
|
||||||
if [ ! -f "$KEY" ]; then
|
if [ ! -f "$KEY" ]; then
|
||||||
echo "!! 未找到签名私钥 ${KEY},本次 version.json 未签名(客户端会拒绝更新)"
|
echo "!! 未找到签名私钥 ${KEY},本次 version.json 未签名(客户端会拒绝更新)"
|
||||||
echo " 生成密钥:dotnet run --project GC-SAVEDOG -- keygen"
|
echo " 生成密钥:dotnet run --project GC-SAVEDOG -- keygen"
|
||||||
@@ -65,48 +72,56 @@ build_models() {
|
|||||||
stamp_versions
|
stamp_versions
|
||||||
}
|
}
|
||||||
|
|
||||||
# 发布目录只放启动器 + 空的 .GC 运行骨架,绝不放模型
|
# 发布目录只放程序本体:不预置 .GC,也不放模型。
|
||||||
|
# .GC(config / model / cache / update / safedog / logs)一律在首次启动时
|
||||||
|
# 由 AppPaths.EnsureCreated + RuntimeLayout 创建,压缩包里只有 GC 本体。
|
||||||
prepare_runtime_layout() {
|
prepare_runtime_layout() {
|
||||||
REL="$1"
|
REL="$1"
|
||||||
DEST="$ROOT_DIR/$REL"
|
DEST="$ROOT_DIR/$REL"
|
||||||
[ -d "$DEST" ] || return 0
|
[ -d "$DEST" ] || return 0
|
||||||
rm -rf "$DEST/model" "$DEST/examples"
|
rm -rf "$DEST/model" "$DEST/examples" "$DEST/.GC"
|
||||||
mkdir -p "$DEST/.GC/model" "$DEST/.GC/cache" "$DEST/.GC/update" "$DEST/.GC/config"
|
echo " 运行目录 -> $REL(首次启动后生成 .GC/:config model cache update safedog logs)"
|
||||||
cat > "$DEST/.GC/model/README.txt" <<'TXT'
|
|
||||||
模型库目录(.GC/model/)
|
|
||||||
启动时程序会读取 GitCode 仓库的 version.json,把最新版模型下载到这里。
|
|
||||||
离线使用也可以手动放入 <模型id>/<模型id>.json + <模型id>/<模型id>.model/。
|
|
||||||
|
|
||||||
运行目录:
|
|
||||||
<可执行文件>
|
|
||||||
GC-SAVEDOG 更新守护进程(验签 + 原子替换 + 失败回滚)
|
|
||||||
.GC/config/settings.json 用户设置(删 .GC/cache 不会丢配置)
|
|
||||||
.GC/model/ 本目录(下载的模型)
|
|
||||||
.GC/cache/ 下载暂存
|
|
||||||
.GC/update/ 待下次启动应用的启动器更新
|
|
||||||
TXT
|
|
||||||
if [ ! -f "$DEST/.GC/config/settings.json" ]; then
|
|
||||||
cat > "$DEST/.GC/config/settings.json" <<'JSON'
|
|
||||||
{
|
|
||||||
"language": "auto",
|
|
||||||
"theme": "light",
|
|
||||||
"renderFps": 30,
|
|
||||||
"memoryMb": 2048,
|
|
||||||
"autoUpdateOnStartup": true,
|
|
||||||
"requireSignedManifest": true,
|
|
||||||
"updateRepository": "https://gitcode.com/Morris_1/GC",
|
|
||||||
"updateManifestUrl": "",
|
|
||||||
"updateLocalRoot": "",
|
|
||||||
"installedModelVersions": {},
|
|
||||||
"launcherVersion": "",
|
|
||||||
"pendingLauncherVersion": "",
|
|
||||||
"lastUpdateCheck": "",
|
|
||||||
"sources": [],
|
|
||||||
"recentModels": []
|
|
||||||
}
|
}
|
||||||
JSON
|
|
||||||
fi
|
# 剔除与目标平台无关 / 只在调试诊断时才会加载的组件。
|
||||||
echo " 运行目录 -> $REL/.GC (config/settings.json + model/ + cache/ + update/)"
|
# 判定依据:Windows 包用 Kestrel 自托管,不经过 IIS/HttpSys;Avalonia 在 Windows
|
||||||
|
# 上只用 Win32 后端;DAC/DBI/DiaSymReader 只有调试器与读 PDB 时才需要,
|
||||||
|
# 而发布包 DebugType=none、不带 PDB。全都不在启动与正常运行路径上。
|
||||||
|
prune_package() {
|
||||||
|
DEST="$1"; PLAT="$2"
|
||||||
|
[ -d "$DEST" ] || return 0
|
||||||
|
case "$PLAT" in
|
||||||
|
win)
|
||||||
|
# ProjectReference 会把后端 exe 的 runtimeconfig 一起拷过来;后端已编入启动器,
|
||||||
|
# 这些残留没有用。
|
||||||
|
rm -f "$DEST"/GC.UI.Server.exe "$DEST"/GC.UI.Server.dll \
|
||||||
|
"$DEST"/GC.UI.Server.deps.json "$DEST"/GC.UI.Server.runtimeconfig.json
|
||||||
|
rm -f "$DEST"/mscordaccore*.dll \
|
||||||
|
"$DEST"/mscordbi.dll \
|
||||||
|
"$DEST"/Microsoft.DiaSymReader.Native*.dll \
|
||||||
|
"$DEST"/web.config \
|
||||||
|
"$DEST"/aspnetcorev2_inprocess.dll \
|
||||||
|
"$DEST"/Microsoft.AspNetCore.Server.IIS.dll \
|
||||||
|
"$DEST"/Microsoft.AspNetCore.Server.IISIntegration.dll \
|
||||||
|
"$DEST"/Microsoft.AspNetCore.Server.HttpSys.dll \
|
||||||
|
"$DEST"/Avalonia.X11.dll \
|
||||||
|
"$DEST"/Avalonia.Native.dll \
|
||||||
|
"$DEST"/Avalonia.FreeDesktop.dll \
|
||||||
|
"$DEST"/Tmds.DBus.Protocol.dll
|
||||||
|
;;
|
||||||
|
linux)
|
||||||
|
rm -f "$DEST"/mscordaccore*.dll \
|
||||||
|
"$DEST"/mscordbi.dll \
|
||||||
|
"$DEST"/Microsoft.DiaSymReader.Native*.dll \
|
||||||
|
"$DEST"/web.config \
|
||||||
|
"$DEST"/aspnetcorev2_inprocess.dll \
|
||||||
|
"$DEST"/Microsoft.AspNetCore.Server.IIS.dll \
|
||||||
|
"$DEST"/Microsoft.AspNetCore.Server.IISIntegration.dll \
|
||||||
|
"$DEST"/Microsoft.AspNetCore.Server.HttpSys.dll \
|
||||||
|
"$DEST"/Avalonia.Win32.dll \
|
||||||
|
"$DEST"/Avalonia.Win32.Automation.dll
|
||||||
|
;;
|
||||||
|
esac
|
||||||
}
|
}
|
||||||
|
|
||||||
# $1=RID $2=输出目录 $3=singlefile(true/false)
|
# $1=RID $2=输出目录 $3=singlefile(true/false)
|
||||||
@@ -124,15 +139,18 @@ publish_rid() {
|
|||||||
-p:DebugType=none \
|
-p:DebugType=none \
|
||||||
-p:PublishSingleFile="$SINGLE" \
|
-p:PublishSingleFile="$SINGLE" \
|
||||||
-p:IncludeNativeLibrariesForSelfExtract="$SINGLE" \
|
-p:IncludeNativeLibrariesForSelfExtract="$SINGLE" \
|
||||||
|
-p:EnableCompressionInSingleFile="$SINGLE" \
|
||||||
-p:PublishTrimmed=false \
|
-p:PublishTrimmed=false \
|
||||||
-o "$ROOT_DIR/$OUT"
|
-o "$ROOT_DIR/$OUT" || return 1
|
||||||
|
|
||||||
# 更新守护进程:与主程序同目录(macOS 打包时会被一起移入 Contents/MacOS)
|
# 更新守护进程:与主程序同目录(macOS 打包时会被一起移入 Contents/MacOS)
|
||||||
if [ -n "${SAVEDOG_PROJ:-}" ] && [ -f "$ROOT_DIR/$SAVEDOG_PROJ" ]; then
|
if [ -n "${SAVEDOG_PROJ:-}" ] && [ -f "$ROOT_DIR/$SAVEDOG_PROJ" ]; then
|
||||||
echo "==> 编译 GC-SAVEDOG (${RID}) -> ${OUT}(裁剪单文件)"
|
echo "==> 编译 GC-SAVEDOG (${RID}) -> ${OUT}(裁剪 + 压缩单文件)"
|
||||||
# 守护进程不引用 Avalonia,可以安全裁剪:70MB -> 14MB。
|
# 守护进程不引用 Avalonia,可以安全裁剪:70MB -> 14MB。
|
||||||
# 前提是 JSON 全部走源生成上下文(GC-SAVEDOG/SavedogJson.cs),新增 JSON 类型
|
# 前提是 JSON 全部走源生成上下文(GC-SAVEDOG/SavedogJson.cs),新增 JSON 类型
|
||||||
# 忘了注册只会在发布产物里炸,所以 update-test 会跑一次真实 apply 兜底。
|
# 忘了注册只会在发布产物里炸,所以 update-test 会跑一次真实 apply 兜底。
|
||||||
|
# EnableCompressionInSingleFile:运行时不常驻,启动时解压一次即可,
|
||||||
|
# 换来包内少 4MB 左右,对「下载一次、只在更新时跑」的守护进程很划算。
|
||||||
dotnet publish "$SAVEDOG_PROJ" \
|
dotnet publish "$SAVEDOG_PROJ" \
|
||||||
-c Release \
|
-c Release \
|
||||||
-r "$RID" \
|
-r "$RID" \
|
||||||
@@ -141,6 +159,7 @@ publish_rid() {
|
|||||||
-p:DebugType=none \
|
-p:DebugType=none \
|
||||||
-p:PublishSingleFile=true \
|
-p:PublishSingleFile=true \
|
||||||
-p:IncludeNativeLibrariesForSelfExtract=true \
|
-p:IncludeNativeLibrariesForSelfExtract=true \
|
||||||
|
-p:EnableCompressionInSingleFile=true \
|
||||||
-p:PublishTrimmed=true \
|
-p:PublishTrimmed=true \
|
||||||
-p:TrimMode=full \
|
-p:TrimMode=full \
|
||||||
-p:JsonSerializerIsReflectionEnabledByDefault=false \
|
-p:JsonSerializerIsReflectionEnabledByDefault=false \
|
||||||
@@ -156,17 +175,19 @@ pack_models() {
|
|||||||
ZIP="$ROOT_DIR/dist/models-$VERSION.zip"
|
ZIP="$ROOT_DIR/dist/models-$VERSION.zip"
|
||||||
rm -f "$ZIP"
|
rm -f "$ZIP"
|
||||||
echo "==> 打包模型数据 -> dist/models-$VERSION.zip"
|
echo "==> 打包模型数据 -> dist/models-$VERSION.zip"
|
||||||
( cd "$ROOT_DIR" && zip -qr "$ZIP" model \
|
( cd "$ROOT_DIR" && zip -qrX "$ZIP" model \
|
||||||
-x "*.DS_Store" "*/bin/*" "*/obj/*" "*.user" )
|
-x "*.DS_Store" "*/bin/*" "*/obj/*" "*.user" )
|
||||||
du -sh "$ZIP"
|
du -sh "$ZIP"
|
||||||
}
|
}
|
||||||
|
|
||||||
# 启动器更新包:只包含程序文件,排除 .GC(否则会覆盖用户已下载的模型与设置)
|
# 启动器更新包:安装目录根只放 GC 本体;非本体文件(守护进程等)收进 .GC/bin。
|
||||||
|
# .GC 下的用户数据(config / model / cache / update / logs / safedog)不进包。
|
||||||
#
|
#
|
||||||
# 产物落点遵循「仓库 dist/<系统>-<架构>/」布局:
|
# 产物落点遵循「仓库 dist/<系统>-<架构>/」布局:
|
||||||
# dist/mac-arm64/GC-<版本>-mac-arm64.zip
|
# dist/mac-arm64/GCL-<版本>-mac-arm64.zip
|
||||||
# dist/win-amd64/GC-<版本>-win-amd64.zip
|
# dist/win-amd64/GCL-<版本>-win-amd64.zip
|
||||||
# dist/win-arm64/GC-<版本>-win-arm64.zip
|
# dist/win-arm64/GCL-<版本>-win-arm64.zip
|
||||||
|
# dist/linux-arm64/GCL-<版本>-linux-arm64.zip
|
||||||
# 启动器更新时既可以从 Release 附件下载,也会到这些目录里找编译产物
|
# 启动器更新时既可以从 Release 附件下载,也会到这些目录里找编译产物
|
||||||
# (见 GC-DOWNLOAD/LauncherArtifacts.cs),所以两种发布方式都能用。
|
# (见 GC-DOWNLOAD/LauncherArtifacts.cs),所以两种发布方式都能用。
|
||||||
#
|
#
|
||||||
@@ -174,40 +195,176 @@ pack_models() {
|
|||||||
# macOS: .app 必须打成 zip 才能作为单文件分发;文件名用 .app.zip,
|
# macOS: .app 必须打成 zip 才能作为单文件分发;文件名用 .app.zip,
|
||||||
# 这样 macOS 双击会用归档工具解压出可运行的 .app。
|
# 这样 macOS 双击会用归档工具解压出可运行的 .app。
|
||||||
# 若直接命名 .app,系统会把 zip 当成应用包解析 => 报「已损坏/打不开」。
|
# 若直接命名 .app,系统会把 zip 当成应用包解析 => 报「已损坏/打不开」。
|
||||||
pack_launcher() {
|
# 当前主机原生构建 Flutter 前端(Windows 主机编 Windows,macOS 主机编 macOS,
|
||||||
echo "==> 生成启动器产物(GC-<版本>-<系统>-<架构>)"
|
# Linux 主机编 Linux)。跨平台的 Windows 版由 build_flutter_ui_cross 负责。
|
||||||
|
#
|
||||||
|
# 默认「必须有前端」:缺 flutter 或编译失败直接返回非 0,让 build.sh 停下来说明
|
||||||
|
# 原因,而不是悄悄出一个只有 Avalonia 回退界面的包。确实需要降级时用
|
||||||
|
# ./build.sh build --allow-no-ui 显式声明。
|
||||||
|
build_flutter_ui() {
|
||||||
|
PLAT="$1"; DEST="$2"
|
||||||
|
UI_SRC="$ROOT_DIR/GC-UI/frontend"
|
||||||
|
if [ ! -d "$UI_SRC" ]; then
|
||||||
|
echo "!! 找不到 Flutter 工程:$UI_SRC"
|
||||||
|
return 1
|
||||||
|
fi
|
||||||
|
|
||||||
# --- Windows:exe 单文件(连同 GC-SAVEDOG.exe 一起打进 zip)---
|
FLUTTER_BIN="${FLUTTER_BIN:-flutter}"
|
||||||
|
if ! command -v "$FLUTTER_BIN" >/dev/null 2>&1; then
|
||||||
|
echo "!! 未找到 flutter(可用 FLUTTER_BIN=<路径> 指定)"
|
||||||
|
return 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
echo "==> 构建 Flutter 前端 (${PLAT})"
|
||||||
|
( cd "$UI_SRC" && "$FLUTTER_BIN" pub get && "$FLUTTER_BIN" build "$PLAT" --release ) || return 1
|
||||||
|
|
||||||
|
mkdir -p "$ROOT_DIR/$DEST"
|
||||||
|
case "$PLAT" in
|
||||||
|
windows)
|
||||||
|
# Release/ 里含 GC-UI.exe、flutter_windows.dll 和 data/
|
||||||
|
cp -R "$UI_SRC/build/windows/x64/runner/Release/." "$ROOT_DIR/$DEST/"
|
||||||
|
;;
|
||||||
|
macos)
|
||||||
|
rm -rf "$ROOT_DIR/$DEST/GC-UI.app"
|
||||||
|
cp -R "$UI_SRC/build/macos/Build/Products/Release/GC-UI.app" "$ROOT_DIR/$DEST/"
|
||||||
|
;;
|
||||||
|
linux)
|
||||||
|
# bundle/ 里是 GC-UI、lib/*.so 与 data/,整体铺到包的根目录。
|
||||||
|
# 目录名跟着目标架构走:aarch64 主机在 build/linux/arm64/,x64 在 build/linux/x64/。
|
||||||
|
BUNDLE=""
|
||||||
|
for cand in "$UI_SRC/build/linux/arm64/release/bundle" \
|
||||||
|
"$UI_SRC/build/linux/x64/release/bundle"; do
|
||||||
|
[ -d "$cand" ] && BUNDLE="$cand" && break
|
||||||
|
done
|
||||||
|
if [ -z "$BUNDLE" ]; then
|
||||||
|
echo "!! 找不到 Flutter Linux bundle(期望 build/linux/{arm64,x64}/release/bundle)"
|
||||||
|
return 1
|
||||||
|
fi
|
||||||
|
# 目标包是 arm64,却只编出 x64 bundle:说明主机架构不对,宁可失败也不出坏包
|
||||||
|
case "$BUNDLE" in
|
||||||
|
*/arm64/*) ;;
|
||||||
|
*)
|
||||||
|
if [ "$(uname -m)" != "aarch64" ] && [ "$(uname -m)" != "arm64" ]; then
|
||||||
|
echo "!! Linux 包目标为 arm64,但当前主机 $(uname -m) 只能编出 x64 前端"
|
||||||
|
return 1
|
||||||
|
fi
|
||||||
|
;;
|
||||||
|
esac
|
||||||
|
cp -R "$BUNDLE/." "$ROOT_DIR/$DEST/"
|
||||||
|
;;
|
||||||
|
*)
|
||||||
|
echo "!! 不支持的 Flutter 目标平台:$PLAT"
|
||||||
|
return 1
|
||||||
|
;;
|
||||||
|
esac
|
||||||
|
echo " -> $DEST(Flutter ${PLAT})"
|
||||||
|
}
|
||||||
|
|
||||||
|
# 在 Linux / macOS 上交叉编译 Windows 前端:mingw-w64 编 C++ 外壳,
|
||||||
|
# wine 跑 Windows 版 gen_snapshot 生成 AOT 快照,无需 Windows 机器。
|
||||||
|
# 产物布局与官方 toolchain 完全一致(GC-UI.exe + flutter_windows.dll + data/)。
|
||||||
|
build_flutter_ui_cross() {
|
||||||
|
DEST="$1"
|
||||||
|
UI_SRC="$ROOT_DIR/GC-UI/frontend"
|
||||||
|
[ -d "$UI_SRC" ] || return 0
|
||||||
|
|
||||||
|
FLUTTER_BIN="${FLUTTER_BIN:-flutter}"
|
||||||
|
if ! command -v "$FLUTTER_BIN" >/dev/null 2>&1; then
|
||||||
|
echo "!! 未找到 flutter(可用 FLUTTER_BIN=<路径> 指定)"
|
||||||
|
return 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
mkdir -p "$ROOT_DIR/build/logs"
|
||||||
|
echo "==> 交叉编译 Windows 前端(mingw-w64 + wine)"
|
||||||
|
if ! FLUTTER_BIN="$FLUTTER_BIN" bash "$ROOT_DIR/buildsh/cross/build-ui-win-cross.sh" \
|
||||||
|
"$UI_SRC/build/windows/x64/runner/Release" \
|
||||||
|
>"$ROOT_DIR/build/logs/flutter-win-cross.log" 2>&1; then
|
||||||
|
echo "!! 交叉编译失败(日志:build/logs/flutter-win-cross.log)"
|
||||||
|
tail -5 "$ROOT_DIR/build/logs/flutter-win-cross.log" 2>/dev/null | sed 's/^/ /'
|
||||||
|
return 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
mkdir -p "$ROOT_DIR/$DEST"
|
||||||
|
cp -R "$UI_SRC/build/windows/x64/runner/Release/." "$ROOT_DIR/$DEST/"
|
||||||
|
echo " -> $DEST(Flutter windows,交叉编译)"
|
||||||
|
}
|
||||||
|
|
||||||
|
pack_launcher() {
|
||||||
|
echo "==> 生成启动器产物(GCL-<版本>-<系统>-<架构>)"
|
||||||
|
|
||||||
|
# --- Windows:启动器 + 守护进程 + UI 后端 + Flutter 前端,整目录打包 ---
|
||||||
for pair in "win-x64:win-amd64" "win-arm64:win-arm64"; do
|
for pair in "win-x64:win-amd64" "win-arm64:win-arm64"; do
|
||||||
RID="${pair%%:*}"; LABEL="${pair##*:}"
|
RID="${pair%%:*}"; LABEL="${pair##*:}"
|
||||||
SRC="$ROOT_DIR/dist/$LABEL"
|
SRC="$ROOT_DIR/dist/$LABEL"
|
||||||
[ -d "$SRC" ] || SRC="$ROOT_DIR/dist/$RID" # 兼容旧布局
|
[ -d "$SRC" ] || SRC="$ROOT_DIR/dist/$RID" # 兼容旧布局
|
||||||
[ -d "$SRC" ] || continue
|
[ -d "$SRC" ] || continue
|
||||||
# 注意排除守护进程:GC-SAVEDOG.exe 在字典序里排在 GC.exe 前面
|
|
||||||
EXE=$(ls "$SRC"/*.exe 2>/dev/null | grep -v 'GC-SAVEDOG' | head -1)
|
# 启动器固定是 GC.exe;后端与前端是可选的随包产物,不能当成启动器。
|
||||||
|
EXE="$SRC/GC.exe"
|
||||||
|
[ -f "$EXE" ] || EXE=$(ls "$SRC"/*.exe 2>/dev/null | grep -v 'GC-SAVEDOG\|GC.UI.Server\|GC-UI' | head -1)
|
||||||
[ -n "$EXE" ] || continue
|
[ -n "$EXE" ] || continue
|
||||||
|
|
||||||
|
# 包内只有一个顶层目录(GCL-<版本>-<平台>),解压后不会散落一屏 dll。
|
||||||
TMP="$ROOT_DIR/dist/.winpkg-$LABEL"
|
TMP="$ROOT_DIR/dist/.winpkg-$LABEL"
|
||||||
rm -rf "$TMP"; mkdir -p "$TMP"
|
PKGNAME="GCL-${VERSION}-${LABEL}"
|
||||||
cp "$EXE" "$TMP/GC-${VERSION}-${LABEL}.exe"
|
PKG="$TMP/$PKGNAME"
|
||||||
chmod +x "$TMP/GC-${VERSION}-${LABEL}.exe" 2>/dev/null || true
|
rm -rf "$TMP"; mkdir -p "$PKG"
|
||||||
if [ -f "$SRC/GC-SAVEDOG.exe" ]; then
|
cp -R "$SRC"/. "$PKG"/
|
||||||
cp "$SRC/GC-SAVEDOG.exe" "$TMP/GC-SAVEDOG.exe"
|
rm -f "$PKG"/*.zip
|
||||||
else
|
prune_package "$PKG" win
|
||||||
|
mv "$PKG/$(basename "$EXE")" "$PKG/$PKGNAME.exe"
|
||||||
|
chmod +x "$PKG/$PKGNAME.exe" 2>/dev/null || true
|
||||||
|
if [ ! -f "$PKG/GC-SAVEDOG.exe" ]; then
|
||||||
echo " !! 缺少 GC-SAVEDOG.exe,该平台将退回旧脚本更新"
|
echo " !! 缺少 GC-SAVEDOG.exe,该平台将退回旧脚本更新"
|
||||||
|
else
|
||||||
|
# 非本体文件统一收进 .GC/bin:安装目录根只留 GC 本体。
|
||||||
|
# 首次启动复制到 .GC/safedog 再运行,所以这里的源文件更新时可安全替换。
|
||||||
|
mkdir -p "$PKG/.GC/bin"
|
||||||
|
mv "$PKG/GC-SAVEDOG.exe" "$PKG/.GC/bin/"
|
||||||
|
fi
|
||||||
|
if [ ! -f "$PKG/GC-UI.exe" ]; then
|
||||||
|
echo " !! 包内没有 Flutter 前端,启动器将使用内置 Avalonia 界面"
|
||||||
fi
|
fi
|
||||||
|
|
||||||
ZIP="$ROOT_DIR/dist/$LABEL/GC-${VERSION}-${LABEL}.zip"
|
ZIP="$ROOT_DIR/dist/$LABEL/$PKGNAME.zip"
|
||||||
rm -f "$ZIP"
|
rm -f "$ZIP"
|
||||||
( cd "$TMP" && zip -q "$ZIP" ./* )
|
( cd "$TMP" && zip -qrX "$ZIP" "$PKGNAME" )
|
||||||
rm -rf "$TMP"
|
rm -rf "$TMP"
|
||||||
echo " -> dist/$LABEL/GC-${VERSION}-${LABEL}.zip"
|
echo " -> dist/$LABEL/$PKGNAME.zip"
|
||||||
done
|
done
|
||||||
|
|
||||||
|
# --- Linux:整目录打包(启动器 + 守护 + 后端 + Flutter 前端)---
|
||||||
|
SRC="$ROOT_DIR/dist/linux-arm64"
|
||||||
|
if [ -d "$SRC" ]; then
|
||||||
|
TMP="$ROOT_DIR/dist/.linuxpkg"
|
||||||
|
PKGNAME="GCL-${VERSION}-linux-arm64"
|
||||||
|
PKG="$TMP/$PKGNAME"
|
||||||
|
rm -rf "$TMP"; mkdir -p "$PKG"
|
||||||
|
cp -R "$SRC"/. "$PKG"/
|
||||||
|
rm -f "$PKG"/*.zip
|
||||||
|
prune_package "$PKG" linux
|
||||||
|
if [ -f "$PKG/GC" ]; then
|
||||||
|
mv "$PKG/GC" "$PKG/$PKGNAME"
|
||||||
|
chmod +x "$PKG/$PKGNAME" 2>/dev/null || true
|
||||||
|
fi
|
||||||
|
if [ -f "$PKG/GC-SAVEDOG" ]; then
|
||||||
|
mkdir -p "$PKG/.GC/bin"
|
||||||
|
mv "$PKG/GC-SAVEDOG" "$PKG/.GC/bin/"
|
||||||
|
fi
|
||||||
|
if [ ! -f "$PKG/GC-UI" ]; then
|
||||||
|
echo " !! 包内没有 Flutter 前端,启动器将使用内置 Avalonia 界面"
|
||||||
|
fi
|
||||||
|
ZIP="$ROOT_DIR/dist/linux-arm64/$PKGNAME.zip"
|
||||||
|
rm -f "$ZIP"
|
||||||
|
( cd "$TMP" && zip -qryX "$ZIP" "$PKGNAME" )
|
||||||
|
rm -rf "$TMP"
|
||||||
|
echo " -> dist/linux-arm64/$PKGNAME.zip"
|
||||||
|
fi
|
||||||
|
|
||||||
# --- macOS:先得到真实 .app 目录(改名 + 同步 Info.plist)---
|
# --- macOS:先得到真实 .app 目录(改名 + 同步 Info.plist)---
|
||||||
MACAPP="$ROOT_DIR/dist/mac-arm64/GC.app"
|
MACAPP="$ROOT_DIR/dist/mac-arm64/GC.app"
|
||||||
if [ -d "$MACAPP" ]; then
|
if [ -d "$MACAPP" ]; then
|
||||||
FINAL="$ROOT_DIR/dist/GC-${VERSION}-mac-arm64.app"
|
FINAL="$ROOT_DIR/dist/GCL-${VERSION}-mac-arm64.app"
|
||||||
rm -rf "$FINAL"
|
rm -rf "$FINAL"
|
||||||
mv "$MACAPP" "$FINAL"
|
mv "$MACAPP" "$FINAL"
|
||||||
chmod +x "$FINAL/Contents/MacOS/GC" 2>/dev/null || true
|
chmod +x "$FINAL/Contents/MacOS/GC" 2>/dev/null || true
|
||||||
@@ -216,19 +373,26 @@ pack_launcher() {
|
|||||||
/usr/libexec/PlistBuddy -c "Set :CFBundleName Morris GC" "$PLIST" 2>/dev/null || true
|
/usr/libexec/PlistBuddy -c "Set :CFBundleName Morris GC" "$PLIST" 2>/dev/null || true
|
||||||
/usr/libexec/PlistBuddy -c "Set :CFBundleDisplayName Morris GC" "$PLIST" 2>/dev/null || true
|
/usr/libexec/PlistBuddy -c "Set :CFBundleDisplayName Morris GC" "$PLIST" 2>/dev/null || true
|
||||||
fi
|
fi
|
||||||
|
# 非本体文件收进 .GC/bin(与 Windows 布局一致):.GC 位置不变,仍在启动器同级
|
||||||
|
# (也就是 .app/Contents/MacOS/),首次启动复制到 .GC/safedog 再运行。
|
||||||
|
if [ -f "$FINAL/Contents/MacOS/GC-SAVEDOG" ]; then
|
||||||
|
mkdir -p "$FINAL/Contents/MacOS/.GC/bin"
|
||||||
|
mv "$FINAL/Contents/MacOS/GC-SAVEDOG" "$FINAL/Contents/MacOS/.GC/bin/"
|
||||||
|
chmod +x "$FINAL/Contents/MacOS/.GC/bin/GC-SAVEDOG" 2>/dev/null || true
|
||||||
|
fi
|
||||||
xattr -cr "$FINAL" 2>/dev/null || true
|
xattr -cr "$FINAL" 2>/dev/null || true
|
||||||
echo " -> $(basename "$FINAL")/"
|
echo " -> $(basename "$FINAL")/"
|
||||||
fi
|
fi
|
||||||
|
|
||||||
# --- 统一压缩:每个产物都打成同名 .zip,放进自己的平台目录 ---
|
# --- 统一压缩:每个产物都打成同名 .zip,放进自己的平台目录 ---
|
||||||
# GC-1.0.3-mac-arm64.app -> dist/mac-arm64/GC-1.0.3-mac-arm64.zip
|
# GCL-1.0.3-mac-arm64.app -> dist/mac-arm64/GCL-1.0.3-mac-arm64.zip
|
||||||
# 客户端下载时按「原名去掉扩展名 + .zip」取包,再解压回原名。
|
# 客户端下载时按「原名去掉扩展名 + .zip」取包,再解压回原名。
|
||||||
echo "==> 压缩为 zip"
|
echo "==> 压缩为 zip"
|
||||||
for art in "$ROOT_DIR"/dist/GC-"$VERSION"-*.exe "$ROOT_DIR"/dist/GC-"$VERSION"-*.app; do
|
for art in "$ROOT_DIR"/dist/GCL-"$VERSION"-*.exe "$ROOT_DIR"/dist/GCL-"$VERSION"-*.app; do
|
||||||
[ -e "$art" ] || continue
|
[ -e "$art" ] || continue
|
||||||
base=$(basename "$art")
|
base=$(basename "$art")
|
||||||
name="${base%.*}" # 去掉 .exe / .app
|
name="${base%.*}" # 去掉 .exe / .app
|
||||||
label="${name#GC-${VERSION}-}" # mac-arm64 / win-amd64
|
label="${name#GCL-${VERSION}-}" # mac-arm64 / win-amd64
|
||||||
ZIP="$ROOT_DIR/dist/${label}/${name}.zip"
|
ZIP="$ROOT_DIR/dist/${label}/${name}.zip"
|
||||||
mkdir -p "$ROOT_DIR/dist/${label}"
|
mkdir -p "$ROOT_DIR/dist/${label}"
|
||||||
rm -f "$ZIP"
|
rm -f "$ZIP"
|
||||||
@@ -237,10 +401,10 @@ pack_launcher() {
|
|||||||
if command -v ditto >/dev/null 2>&1; then
|
if command -v ditto >/dev/null 2>&1; then
|
||||||
ditto -c -k --sequesterRsrc --keepParent "$art" "$ZIP"
|
ditto -c -k --sequesterRsrc --keepParent "$art" "$ZIP"
|
||||||
else
|
else
|
||||||
( cd "$(dirname "$art")" && zip -qry "$ZIP" "$base" -x "*.DS_Store" )
|
( cd "$(dirname "$art")" && zip -qryX "$ZIP" "$base" -x "*.DS_Store" )
|
||||||
fi
|
fi
|
||||||
else
|
else
|
||||||
( cd "$(dirname "$art")" && zip -q "$ZIP" "$base" )
|
( cd "$(dirname "$art")" && zip -qX "$ZIP" "$base" )
|
||||||
fi
|
fi
|
||||||
echo " -> dist/${label}/${name}.zip"
|
echo " -> dist/${label}/${name}.zip"
|
||||||
done
|
done
|
||||||
@@ -250,7 +414,7 @@ pack_launcher() {
|
|||||||
# 一次性删除又慢又不可逆,先挪走更安全(暂存区在下次构建开始时挪出 dist)。
|
# 一次性删除又慢又不可逆,先挪走更安全(暂存区在下次构建开始时挪出 dist)。
|
||||||
TRASH="$ROOT_DIR/build/trash"
|
TRASH="$ROOT_DIR/build/trash"
|
||||||
mkdir -p "$TRASH"
|
mkdir -p "$TRASH"
|
||||||
for leftover in "$ROOT_DIR"/dist/GC-"$VERSION"-*.exe "$ROOT_DIR"/dist/GC-"$VERSION"-*.app; do
|
for leftover in "$ROOT_DIR"/dist/GCL-"$VERSION"-*.exe "$ROOT_DIR"/dist/GCL-"$VERSION"-*.app; do
|
||||||
[ -e "$leftover" ] || continue
|
[ -e "$leftover" ] || continue
|
||||||
mv "$leftover" "$TRASH/$(basename "$leftover")-$(date +%s)" 2>/dev/null || true
|
mv "$leftover" "$TRASH/$(basename "$leftover")-$(date +%s)" 2>/dev/null || true
|
||||||
done
|
done
|
||||||
@@ -259,15 +423,15 @@ pack_launcher() {
|
|||||||
stamp_launcher_only
|
stamp_launcher_only
|
||||||
echo ""
|
echo ""
|
||||||
echo "==> dist 里可发布的 zip:"
|
echo "==> dist 里可发布的 zip:"
|
||||||
ls -lh "$ROOT_DIR"/dist/*/GC-"$VERSION"-*.zip 2>/dev/null || true
|
ls -lh "$ROOT_DIR"/dist/*/GCL-"$VERSION"-*.zip 2>/dev/null || true
|
||||||
}
|
}
|
||||||
|
|
||||||
# 删除 publish 过程中的中间目录:平台目录里只留最终 zip
|
# 删除 publish 过程中的中间目录:平台目录里只留最终 zip
|
||||||
strip_intermediate_dirs() {
|
strip_intermediate_dirs() {
|
||||||
for d in win-amd64 win-x64 win-arm64 mac-arm64; do
|
for d in win-amd64 win-x64 win-arm64 mac-arm64 linux-arm64 linux-x64; do
|
||||||
[ -d "$ROOT_DIR/dist/$d" ] || continue
|
[ -d "$ROOT_DIR/dist/$d" ] || continue
|
||||||
find "$ROOT_DIR/dist/$d" -mindepth 1 -maxdepth 1 \
|
find "$ROOT_DIR/dist/$d" -mindepth 1 -maxdepth 1 \
|
||||||
! -name "GC-${VERSION}-*.zip" -exec rm -rf {} + 2>/dev/null || true
|
! -name "GCL-${VERSION}-*.zip" -exec rm -rf {} + 2>/dev/null || true
|
||||||
done
|
done
|
||||||
find "$ROOT_DIR/dist" -name ".DS_Store" -delete 2>/dev/null || true
|
find "$ROOT_DIR/dist" -name ".DS_Store" -delete 2>/dev/null || true
|
||||||
}
|
}
|
||||||
@@ -321,7 +485,8 @@ PLIST
|
|||||||
fi
|
fi
|
||||||
fi
|
fi
|
||||||
|
|
||||||
# 发布包不带 .GC 运行骨架(用户首次启动自行创建),避免覆盖用户数据
|
# 清掉模板类 .GC(config / model / cache / update / logs):首次启动自行创建,
|
||||||
|
# 包里只保留 .GC/bin 这一个由 pack_launcher 补上的非本体文件目录。
|
||||||
rm -rf "$APP/Contents/MacOS/.GC"
|
rm -rf "$APP/Contents/MacOS/.GC"
|
||||||
chmod +x "$APP/Contents/MacOS/GC"
|
chmod +x "$APP/Contents/MacOS/GC"
|
||||||
echo "==> 已打包 $APP"
|
echo "==> 已打包 $APP"
|
||||||
|
|||||||
Executable
+211
@@ -0,0 +1,211 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""核对「仓库清单 ↔ Release 资产」是否对得上。
|
||||||
|
|
||||||
|
为什么需要它:清单里的 sha256 是客户端验证下载包的唯一依据。一旦 Release 上的资产
|
||||||
|
和清单不是同一份(换过一次构建、上传了别的产物、tag 指到了旧提交),客户端会验签
|
||||||
|
失败或直接回滚 —— 用户看到的是「更新失败了」,而服务端一切正常。
|
||||||
|
|
||||||
|
检查项:
|
||||||
|
1. tag 指向的 version.json 里的 launcher.version 等于 tag 名;
|
||||||
|
2. 清单里带 sha256 的平台,Release 上有同名资产,且体积 / sha256 完全一致;
|
||||||
|
3. 清单里没有 sha256 的平台(本次没构建)不要求有资产,但会列出;
|
||||||
|
4. Release 上多出来的资产(清单里没有)单独提示;
|
||||||
|
5. 本地清单与 tag 上的清单是否字节一致。
|
||||||
|
|
||||||
|
只用标准库,Linux / macOS / Windows 上都能跑。
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import argparse
|
||||||
|
import hashlib
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
import urllib.error
|
||||||
|
import urllib.request
|
||||||
|
|
||||||
|
DEFAULT_BASE = os.environ.get("GC_GITEA_URL", "https://git.xhmcl.com")
|
||||||
|
DEFAULT_REPO = os.environ.get("GC_GITEA_REPO", "Morris/GC")
|
||||||
|
|
||||||
|
|
||||||
|
def log(msg: str = "") -> None:
|
||||||
|
print(msg, flush=True)
|
||||||
|
|
||||||
|
|
||||||
|
def http_json(url: str, token: str | None) -> dict:
|
||||||
|
req = urllib.request.Request(url)
|
||||||
|
req.add_header("Accept", "application/json")
|
||||||
|
if token:
|
||||||
|
req.add_header("Authorization", "token " + token)
|
||||||
|
with urllib.request.urlopen(req, timeout=60) as resp:
|
||||||
|
return json.loads(resp.read().decode("utf-8"))
|
||||||
|
|
||||||
|
|
||||||
|
def download_sha256(url: str, token: str | None, dest: str) -> tuple[int, str]:
|
||||||
|
req = urllib.request.Request(url)
|
||||||
|
if token:
|
||||||
|
req.add_header("Authorization", "token " + token)
|
||||||
|
digest = hashlib.sha256()
|
||||||
|
size = 0
|
||||||
|
with urllib.request.urlopen(req, timeout=600) as resp, open(dest, "wb") as out:
|
||||||
|
while True:
|
||||||
|
chunk = resp.read(1 << 20)
|
||||||
|
if not chunk:
|
||||||
|
break
|
||||||
|
size += len(chunk)
|
||||||
|
digest.update(chunk)
|
||||||
|
out.write(chunk)
|
||||||
|
return size, digest.hexdigest()
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> int:
|
||||||
|
parser = argparse.ArgumentParser(description="核对清单与 Release 资产")
|
||||||
|
parser.add_argument("--tag", required=True, help="要核对的 tag,例如 1.1.0")
|
||||||
|
parser.add_argument("--manifest", default="version.json", help="本地清单路径(用于对比)")
|
||||||
|
parser.add_argument("--base-url", default=DEFAULT_BASE)
|
||||||
|
parser.add_argument("--repo", default=DEFAULT_REPO)
|
||||||
|
parser.add_argument("--token", default=os.environ.get("GC_GITEA_TOKEN"))
|
||||||
|
parser.add_argument("--workdir", default=None, help="下载临时目录(默认系统临时目录)")
|
||||||
|
parser.add_argument("--skip-download", action="store_true",
|
||||||
|
help="只核对清单体积与资产列表,不下载算哈希")
|
||||||
|
parser.add_argument("--dump-manifest", default=None,
|
||||||
|
help="把 tag 上的清单原样写到这个路径(供 GC-SAVEDOG verify 验签)")
|
||||||
|
args = parser.parse_args()
|
||||||
|
|
||||||
|
tag = args.tag.strip()
|
||||||
|
if tag.startswith("v"):
|
||||||
|
tag = tag[1:]
|
||||||
|
|
||||||
|
api = f"{args.base_url}/api/v1/repos/{args.repo}"
|
||||||
|
workdir = args.workdir or os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "..", "build", "release-verify")
|
||||||
|
workdir = os.path.abspath(workdir)
|
||||||
|
os.makedirs(workdir, exist_ok=True)
|
||||||
|
|
||||||
|
failures: list[str] = []
|
||||||
|
warnings: list[str] = []
|
||||||
|
|
||||||
|
# ---- 1. tag 上的清单 ----
|
||||||
|
try:
|
||||||
|
remote = http_json(f"{api}/raw/version.json?ref={tag}", args.token)
|
||||||
|
except urllib.error.HTTPError as exc:
|
||||||
|
log(f"!! 取不到 tag {tag} 的 version.json(HTTP {exc.code})")
|
||||||
|
return 1
|
||||||
|
|
||||||
|
if args.dump_manifest:
|
||||||
|
os.makedirs(os.path.dirname(os.path.abspath(args.dump_manifest)), exist_ok=True)
|
||||||
|
with open(args.dump_manifest, "w", encoding="utf-8") as fh:
|
||||||
|
json.dump(remote, fh, ensure_ascii=False, indent=2)
|
||||||
|
|
||||||
|
launcher = remote.get("launcher") or {}
|
||||||
|
remote_version = str(launcher.get("version") or "")
|
||||||
|
log(f"tag : {tag}")
|
||||||
|
log(f"清单版本 : {remote_version or '(空)'}")
|
||||||
|
if remote_version != tag:
|
||||||
|
failures.append(f"tag 指向的清单版本是 {remote_version!r},与 tag {tag} 不一致")
|
||||||
|
|
||||||
|
# 签名状态:交给 GC-SAVEDOG verify 判定(这里只提示有没有签名段)
|
||||||
|
if not remote.get("signature"):
|
||||||
|
failures.append("tag 上的清单没有签名段")
|
||||||
|
else:
|
||||||
|
log(f"清单签名 : {remote['signature'].get('keyId', '?')}")
|
||||||
|
|
||||||
|
# ---- 2. Release 与资产 ----
|
||||||
|
try:
|
||||||
|
release = http_json(f"{api}/releases/tags/{tag}", args.token)
|
||||||
|
except urllib.error.HTTPError as exc:
|
||||||
|
log(f"!! 取不到 Release {tag}(HTTP {exc.code})")
|
||||||
|
return 1
|
||||||
|
|
||||||
|
assets = {a["name"]: a for a in release.get("assets") or []}
|
||||||
|
log(f"Release : id={release.get('id')} prerelease={release.get('prerelease')}")
|
||||||
|
log(f"资产数量 : {len(assets)}")
|
||||||
|
|
||||||
|
packages = launcher.get("packages") or {}
|
||||||
|
declared: set[str] = set()
|
||||||
|
|
||||||
|
log("")
|
||||||
|
log(f"{'平台':<12} {'包':<32} {'结果'}")
|
||||||
|
log("-" * 78)
|
||||||
|
|
||||||
|
for rid, pkg in packages.items():
|
||||||
|
name = str(pkg.get("name") or "")
|
||||||
|
want_sha = str(pkg.get("sha256") or "")
|
||||||
|
want_size = int(pkg.get("size") or 0)
|
||||||
|
if not name:
|
||||||
|
warnings.append(f"{rid}: 清单条目没有 name")
|
||||||
|
continue
|
||||||
|
declared.add(name)
|
||||||
|
|
||||||
|
asset = assets.get(name)
|
||||||
|
if not want_sha:
|
||||||
|
log(f"{rid:<12} {name:<32} 未构建(清单无 sha256)")
|
||||||
|
if asset:
|
||||||
|
warnings.append(f"{rid}: 清单没记录哈希,但 Release 上有 {name}")
|
||||||
|
continue
|
||||||
|
|
||||||
|
if not asset:
|
||||||
|
log(f"{rid:<12} {name:<32} ✗ 资产缺失")
|
||||||
|
failures.append(f"{rid}: Release 上找不到 {name}")
|
||||||
|
continue
|
||||||
|
|
||||||
|
if int(asset.get("size") or 0) != want_size:
|
||||||
|
log(f"{rid:<12} {name:<32} ✗ 体积不符 {asset.get('size')} != {want_size}")
|
||||||
|
failures.append(f"{rid}: {name} 体积 {asset.get('size')},清单 {want_size}")
|
||||||
|
continue
|
||||||
|
|
||||||
|
if args.skip_download:
|
||||||
|
log(f"{rid:<12} {name:<32} ✓ 体积一致(未下载)")
|
||||||
|
continue
|
||||||
|
|
||||||
|
url = asset.get("browser_download_url") or f"{args.base_url}/{args.repo}/releases/download/{tag}/{name}"
|
||||||
|
dest = os.path.join(workdir, name)
|
||||||
|
try:
|
||||||
|
size, sha = download_sha256(url, args.token, dest)
|
||||||
|
os.remove(dest)
|
||||||
|
except Exception as exc: # noqa: BLE001 - 下载失败一律按失败上报
|
||||||
|
log(f"{rid:<12} {name:<32} ✗ 下载失败: {exc}")
|
||||||
|
failures.append(f"{rid}: 下载 {name} 失败: {exc}")
|
||||||
|
continue
|
||||||
|
|
||||||
|
if size != want_size or sha != want_sha:
|
||||||
|
log(f"{rid:<12} {name:<32} ✗ sha256 不符")
|
||||||
|
log(f" 期望 {want_sha}")
|
||||||
|
log(f" 实际 {sha}")
|
||||||
|
failures.append(f"{rid}: {name} sha256 与清单不符")
|
||||||
|
else:
|
||||||
|
log(f"{rid:<12} {name:<32} ✓ {size:,} B sha {sha[:16]}…")
|
||||||
|
|
||||||
|
extra = sorted(set(assets) - declared)
|
||||||
|
if extra:
|
||||||
|
warnings.append("Release 上有清单未声明的资产: " + ", ".join(extra))
|
||||||
|
|
||||||
|
# ---- 3. 本地清单对比 ----
|
||||||
|
if os.path.isfile(args.manifest):
|
||||||
|
with open(args.manifest, "rb") as fh:
|
||||||
|
local_raw = fh.read()
|
||||||
|
local = json.loads(local_raw.decode("utf-8"))
|
||||||
|
local_packages = (local.get("launcher") or {}).get("packages") or {}
|
||||||
|
if local_packages != packages:
|
||||||
|
warnings.append("本地清单的 packages 与 tag 上的不一致(本地可能是未发布的构建)")
|
||||||
|
else:
|
||||||
|
log("")
|
||||||
|
log("本地清单与 tag 上的 packages 一致")
|
||||||
|
|
||||||
|
# ---- 汇总 ----
|
||||||
|
log("")
|
||||||
|
for w in warnings:
|
||||||
|
log("警告: " + w)
|
||||||
|
if failures:
|
||||||
|
for f in failures:
|
||||||
|
log("失败: " + f)
|
||||||
|
log("")
|
||||||
|
log("结论: 不一致 —— 客户端会拒绝或回滚这次更新")
|
||||||
|
return 1
|
||||||
|
|
||||||
|
log("结论: 一致 —— 清单、tag、资产三者对得上")
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
sys.exit(main())
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
# buildsh/release.sh —— 发布一致性核对
|
||||||
|
#
|
||||||
|
# ./build.sh release-verify # 核对当前版本号对应的 tag
|
||||||
|
# ./build.sh release-verify 1.1.0 # 核对指定 tag
|
||||||
|
# ./build.sh release-verify 1.1.0 --skip-download # 只看体积,不下载
|
||||||
|
#
|
||||||
|
# 检查的是「tag 指向的清单 / Release 上的资产 / 清单里的 sha256」三者是否互相对得上。
|
||||||
|
# 客户端的升级判断完全依赖这三者:任何一处错位,用户侧就是验签失败或安全回滚。
|
||||||
|
|
||||||
|
bs_verify_release() {
|
||||||
|
ROOT_DIR="$1"; shift
|
||||||
|
TAG="${1:-$VERSION}"
|
||||||
|
if [ "$#" -gt 0 ]; then shift; fi
|
||||||
|
|
||||||
|
WORK="$ROOT_DIR/build/release-verify"
|
||||||
|
mkdir -p "$WORK"
|
||||||
|
|
||||||
|
echo "==> 核对 Release ${TAG}"
|
||||||
|
rc=0
|
||||||
|
python3 "$ROOT_DIR/buildsh/lib/verify_release.py" \
|
||||||
|
--tag "$TAG" \
|
||||||
|
--manifest "$ROOT_DIR/version.json" \
|
||||||
|
--dump-manifest "$WORK/$TAG.json" \
|
||||||
|
"$@" || rc=$?
|
||||||
|
|
||||||
|
if [ "$rc" -ne 0 ]; then
|
||||||
|
return "$rc"
|
||||||
|
fi
|
||||||
|
|
||||||
|
# 资产对得上还不够:清单本身必须是我签的,否则客户端一样会拒
|
||||||
|
echo ""
|
||||||
|
echo "==> 校验 tag 清单签名"
|
||||||
|
if dotnet run --project "$ROOT_DIR/GC-SAVEDOG/GC-SAVEDOG.csproj" -c Release -- \
|
||||||
|
verify --manifest "$WORK/$TAG.json"; then
|
||||||
|
echo "结论: 签名可信,可以发布 / 已经发布正确"
|
||||||
|
return 0
|
||||||
|
fi
|
||||||
|
|
||||||
|
echo "!! 签名校验未通过,客户端会拒绝这次更新"
|
||||||
|
return 1
|
||||||
|
}
|
||||||
+1
-1
@@ -26,7 +26,7 @@ bs_tools() {
|
|||||||
dotnet --info | head -20 ;;
|
dotnet --info | head -20 ;;
|
||||||
dist)
|
dist)
|
||||||
echo "==> dist 产物:"
|
echo "==> dist 产物:"
|
||||||
ls -lh "$ROOT_DIR"/dist/*/GC-*.zip 2>/dev/null || ls -lh "$ROOT_DIR"/dist 2>/dev/null || true ;;
|
ls -lh "$ROOT_DIR"/dist/*/GCL-*.zip 2>/dev/null || ls -lh "$ROOT_DIR"/dist 2>/dev/null || true ;;
|
||||||
*)
|
*)
|
||||||
echo "未知工具: $TASK"; return 1 ;;
|
echo "未知工具: $TASK"; return 1 ;;
|
||||||
esac
|
esac
|
||||||
|
|||||||
@@ -11,7 +11,7 @@ using GC.Services;
|
|||||||
// 仓库根 version.json 与 model/version.json(内容相同,便于两种源地址读取)。
|
// 仓库根 version.json 与 model/version.json(内容相同,便于两种源地址读取)。
|
||||||
|
|
||||||
// 仓库地址(编译产物的 Release 也发在这里):与启动器默认 updateRepository 保持一致。
|
// 仓库地址(编译产物的 Release 也发在这里):与启动器默认 updateRepository 保持一致。
|
||||||
const string Repository = "https://gitcode.com/Morris_1/GC";
|
const string Repository = "https://git.xhmcl.com/Morris/GC";
|
||||||
|
|
||||||
// 位置参数:<仓库根> <启动器版本>;开关:--launcher-only
|
// 位置参数:<仓库根> <启动器版本>;开关:--launcher-only
|
||||||
// --launcher-only 只刷新 launcher.packages(构建脚本在打完 zip 之后再调一次),
|
// --launcher-only 只刷新 launcher.packages(构建脚本在打完 zip 之后再调一次),
|
||||||
@@ -150,8 +150,8 @@ var packages = new Dictionary<string, Dictionary<string, object>>();
|
|||||||
// 2) 仓库里的编译产物 dist/<系统>-<架构>/GC-<版本>-<系统>-<架构>.zip ——
|
// 2) 仓库里的编译产物 dist/<系统>-<架构>/GC-<版本>-<系统>-<架构>.zip ——
|
||||||
// 不发 Release、只提交产物也能更新(用户明确要求支持这种布局)。
|
// 不发 Release、只提交产物也能更新(用户明确要求支持这种布局)。
|
||||||
// 两种都写:url 只是「去哪儿找」,真正的完整性凭据是下面的 sha256(受签名保护)。
|
// 两种都写:url 只是「去哪儿找」,真正的完整性凭据是下面的 sha256(受签名保护)。
|
||||||
var releaseBase = $"{Repository}/releases/download/v{launcherVersion}";
|
var releaseBase = $"{Repository}/releases/download/{launcherVersion}";
|
||||||
foreach (var rid in new[] { "win-x64", "win-arm64", "osx-arm64", "osx-x64", "linux-x64" })
|
foreach (var rid in new[] { "win-x64", "win-arm64", "osx-arm64", "osx-x64", "linux-arm64" })
|
||||||
{
|
{
|
||||||
var label = LauncherArtifacts.LabelOf(rid);
|
var label = LauncherArtifacts.LabelOf(rid);
|
||||||
var fileName = LauncherArtifacts.PackageFileName(launcherVersion, rid);
|
var fileName = LauncherArtifacts.PackageFileName(launcherVersion, rid);
|
||||||
|
|||||||
@@ -17,7 +17,7 @@
|
|||||||
],
|
],
|
||||||
"assembly": "ContourMapModel.dll",
|
"assembly": "ContourMapModel.dll",
|
||||||
"type": "GC.ContourMap.ContourMapFactory",
|
"type": "GC.ContourMap.ContourMapFactory",
|
||||||
"version": "1.0",
|
"version": "1.1",
|
||||||
"chrome": {
|
"chrome": {
|
||||||
"titleBar": "#0C1828",
|
"titleBar": "#0C1828",
|
||||||
"titleBorder": "#1B2740",
|
"titleBorder": "#1B2740",
|
||||||
@@ -25,6 +25,6 @@
|
|||||||
"button": "#9FB4D4",
|
"button": "#9FB4D4",
|
||||||
"frame": "#0A1524"
|
"frame": "#0A1524"
|
||||||
},
|
},
|
||||||
"build": "43dcb6dc63",
|
"build": "773ab2161d",
|
||||||
"updatedAt": "2026-11-17T22:53:52Z"
|
"updatedAt": "2026-11-19T10:20:00Z"
|
||||||
}
|
}
|
||||||
@@ -17,7 +17,7 @@
|
|||||||
"atlas"
|
"atlas"
|
||||||
],
|
],
|
||||||
"dataDir": "earth-geography.model",
|
"dataDir": "earth-geography.model",
|
||||||
"version": "1.8",
|
"version": "1.9",
|
||||||
"chrome": {
|
"chrome": {
|
||||||
"titleBar": "#0C1828",
|
"titleBar": "#0C1828",
|
||||||
"titleBorder": "#1B2740",
|
"titleBorder": "#1B2740",
|
||||||
@@ -25,6 +25,6 @@
|
|||||||
"button": "#9FB4D4",
|
"button": "#9FB4D4",
|
||||||
"frame": "#0A1524"
|
"frame": "#0A1524"
|
||||||
},
|
},
|
||||||
"build": "16eaf4110f",
|
"build": "cc68b8863b",
|
||||||
"updatedAt": "2026-11-17T22:53:52Z"
|
"updatedAt": "2026-11-19T10:20:00Z"
|
||||||
}
|
}
|
||||||
@@ -23,7 +23,7 @@
|
|||||||
"type": "GC.EarthModels.RevolutionModelFactory",
|
"type": "GC.EarthModels.RevolutionModelFactory",
|
||||||
"preview": "preview.png",
|
"preview": "preview.png",
|
||||||
"apiVersion": 1,
|
"apiVersion": 1,
|
||||||
"version": "1.6",
|
"version": "1.7",
|
||||||
"chrome": {
|
"chrome": {
|
||||||
"titleBar": "#0C1828",
|
"titleBar": "#0C1828",
|
||||||
"titleBorder": "#1B2740",
|
"titleBorder": "#1B2740",
|
||||||
@@ -31,6 +31,6 @@
|
|||||||
"button": "#9FB4D4",
|
"button": "#9FB4D4",
|
||||||
"frame": "#0A1524"
|
"frame": "#0A1524"
|
||||||
},
|
},
|
||||||
"build": "bd57e6ed67",
|
"build": "53b7a0fbc3",
|
||||||
"updatedAt": "2026-11-17T22:53:52Z"
|
"updatedAt": "2026-11-19T10:20:00Z"
|
||||||
}
|
}
|
||||||
@@ -23,7 +23,7 @@
|
|||||||
"type": "GC.EarthModels.RotationModelFactory",
|
"type": "GC.EarthModels.RotationModelFactory",
|
||||||
"preview": "preview.png",
|
"preview": "preview.png",
|
||||||
"apiVersion": 1,
|
"apiVersion": 1,
|
||||||
"version": "1.6",
|
"version": "1.7",
|
||||||
"chrome": {
|
"chrome": {
|
||||||
"titleBar": "#0C1828",
|
"titleBar": "#0C1828",
|
||||||
"titleBorder": "#1B2740",
|
"titleBorder": "#1B2740",
|
||||||
@@ -31,6 +31,6 @@
|
|||||||
"button": "#9FB4D4",
|
"button": "#9FB4D4",
|
||||||
"frame": "#0A1524"
|
"frame": "#0A1524"
|
||||||
},
|
},
|
||||||
"build": "a79f660ec2",
|
"build": "ecd52665f9",
|
||||||
"updatedAt": "2026-11-17T22:53:52Z"
|
"updatedAt": "2026-11-19T10:20:00Z"
|
||||||
}
|
}
|
||||||
@@ -24,7 +24,7 @@
|
|||||||
"type": "GC.ScaleCalculator.ScaleCalculatorFactory",
|
"type": "GC.ScaleCalculator.ScaleCalculatorFactory",
|
||||||
"preview": "preview.png",
|
"preview": "preview.png",
|
||||||
"apiVersion": 1,
|
"apiVersion": 1,
|
||||||
"version": "1.5",
|
"version": "1.6",
|
||||||
"chrome": {
|
"chrome": {
|
||||||
"titleBar": "#FFFFFF",
|
"titleBar": "#FFFFFF",
|
||||||
"titleBorder": "#E3E8F3",
|
"titleBorder": "#E3E8F3",
|
||||||
@@ -32,6 +32,6 @@
|
|||||||
"button": "#5B6A86",
|
"button": "#5B6A86",
|
||||||
"frame": "#F4F6FB"
|
"frame": "#F4F6FB"
|
||||||
},
|
},
|
||||||
"build": "ec6119e3f4",
|
"build": "105653737d",
|
||||||
"updatedAt": "2026-11-17T22:53:52Z"
|
"updatedAt": "2026-11-19T10:20:00Z"
|
||||||
}
|
}
|
||||||
+47
-42
@@ -1,96 +1,101 @@
|
|||||||
{
|
{
|
||||||
"schema": 1,
|
"schema": 1,
|
||||||
"generated": "2026-11-17T22:53:52Z",
|
"generated": "2026-11-19T10:20:00Z",
|
||||||
"repository": "https://gitcode.com/Morris_1/GC",
|
"repository": "https://git.xhmcl.com/Morris/GC",
|
||||||
"branch": "main",
|
"branch": "main",
|
||||||
"modelDir": "model",
|
"modelDir": "model",
|
||||||
"launcher": {
|
"launcher": {
|
||||||
"version": "1.0.7",
|
"version": "1.1.1",
|
||||||
"revision": "",
|
"revision": "",
|
||||||
"packages": {
|
"packages": {
|
||||||
"win-x64": {
|
"win-x64": {
|
||||||
"path": "dist/win-amd64/GC-1.0.7-win-amd64.zip",
|
"path": "dist/win-amd64/GCL-1.1.1-win-amd64.zip",
|
||||||
"dir": "dist/win-amd64",
|
"dir": "dist/win-amd64",
|
||||||
"name": "GC-1.0.7-win-amd64.zip",
|
"name": "GCL-1.1.1-win-amd64.zip",
|
||||||
"url": "https://gitcode.com/Morris_1/GC/releases/download/v1.0.7/GC-1.0.7-win-amd64.zip",
|
"url": "https://git.xhmcl.com/Morris/GC/releases/download/1.1.1/GCL-1.1.1-win-amd64.zip",
|
||||||
"sha256": "f90ff51ac6b041ae238cbeb4672622b0d029142a9d8b0705f08e654336512308",
|
"sha256": "a03532606121280a1553ea73e56d6f9e8cc6cd9eefaf49f8c62857733199c10f",
|
||||||
"size": 46363183
|
"size": 74993562
|
||||||
},
|
},
|
||||||
"win-arm64": {
|
"win-arm64": {
|
||||||
"path": "dist/win-arm64/GC-1.0.7-win-arm64.zip",
|
"path": "dist/win-arm64/GCL-1.1.1-win-arm64.zip",
|
||||||
"dir": "dist/win-arm64",
|
"dir": "dist/win-arm64",
|
||||||
"name": "GC-1.0.7-win-arm64.zip",
|
"name": "GCL-1.1.1-win-arm64.zip",
|
||||||
"url": "https://gitcode.com/Morris_1/GC/releases/download/v1.0.7/GC-1.0.7-win-arm64.zip",
|
"url": "https://git.xhmcl.com/Morris/GC/releases/download/1.1.1/GCL-1.1.1-win-arm64.zip",
|
||||||
"sha256": "0b2bab2c3ac7e6223d8dd0b0faf9a0994319fa5ad13826addf7b402619b812e0",
|
"sha256": "0cd3e045fbc2415bb170e545bb720841eb4c5ebc01a98e03105618a2b7bace46",
|
||||||
"size": 44390354
|
"size": 72535103
|
||||||
},
|
},
|
||||||
"osx-arm64": {
|
"osx-arm64": {
|
||||||
"path": "dist/mac-arm64/GC-1.0.7-mac-arm64.zip",
|
"path": "dist/mac-arm64/GCL-1.1.1-mac-arm64.zip",
|
||||||
"dir": "dist/mac-arm64",
|
"dir": "dist/mac-arm64",
|
||||||
"name": "GC-1.0.7-mac-arm64.zip",
|
"name": "GCL-1.1.1-mac-arm64.zip",
|
||||||
"url": "https://gitcode.com/Morris_1/GC/releases/download/v1.0.7/GC-1.0.7-mac-arm64.zip",
|
"url": "https://git.xhmcl.com/Morris/GC/releases/download/1.1.1/GCL-1.1.1-mac-arm64.zip"
|
||||||
"sha256": "e5fd355bace68dc0794eb3e049cbef63c952a60a765ab3806adaf1199e1b09ab",
|
|
||||||
"size": 9178314
|
|
||||||
},
|
},
|
||||||
"osx-x64": {
|
"osx-x64": {
|
||||||
"path": "dist/mac-x64/GC-1.0.7-mac-x64.zip",
|
"path": "dist/mac-x64/GCL-1.1.1-mac-x64.zip",
|
||||||
"dir": "dist/mac-x64",
|
"dir": "dist/mac-x64",
|
||||||
"name": "GC-1.0.7-mac-x64.zip",
|
"name": "GCL-1.1.1-mac-x64.zip",
|
||||||
"url": "https://gitcode.com/Morris_1/GC/releases/download/v1.0.7/GC-1.0.7-mac-x64.zip"
|
"url": "https://git.xhmcl.com/Morris/GC/releases/download/1.1.1/GCL-1.1.1-mac-x64.zip"
|
||||||
},
|
},
|
||||||
"linux-x64": {
|
"linux-arm64": {
|
||||||
"path": "dist/linux-amd64/GC-1.0.7-linux-amd64.zip",
|
"path": "dist/linux-arm64/GCL-1.1.1-linux-arm64.zip",
|
||||||
"dir": "dist/linux-amd64",
|
"dir": "dist/linux-arm64",
|
||||||
"name": "GC-1.0.7-linux-amd64.zip",
|
"name": "GCL-1.1.1-linux-arm64.zip",
|
||||||
"url": "https://gitcode.com/Morris_1/GC/releases/download/v1.0.7/GC-1.0.7-linux-amd64.zip"
|
"url": "https://git.xhmcl.com/Morris/GC/releases/download/1.1.1/GCL-1.1.1-linux-arm64.zip"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"models": [
|
"models": [
|
||||||
{
|
{
|
||||||
"id": "contour-map",
|
"id": "contour-map",
|
||||||
"version": "1.0",
|
"version": "1.1",
|
||||||
"build": "43dcb6dc63",
|
"build": "773ab2161d",
|
||||||
"manifestSha256": "f7896a85d5f9e9f10e021c07931dee51f0ef86151a6a89e2ed39e37cb7f996a6",
|
"manifestSha256": "ac3231d55175757b4c477ad6a3c398c041db9511061f0c650d2c10efca881103",
|
||||||
"filesSha256": "a6bdf9b4273aabee50c3c94ceab4d0abee15f0df1af90c58bdbb796e0d2d5699",
|
"filesSha256": "a6bdf9b4273aabee50c3c94ceab4d0abee15f0df1af90c58bdbb796e0d2d5699",
|
||||||
"files": 5,
|
"files": 5,
|
||||||
"dir": "model/contour-map"
|
"dir": "model/contour-map"
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"id": "earth-geography",
|
"id": "earth-geography",
|
||||||
"version": "1.8",
|
"version": "1.9",
|
||||||
"build": "16eaf4110f",
|
"build": "cc68b8863b",
|
||||||
"manifestSha256": "0b8dd41e8535284576873956ed1db8755097649fe801d887b65ca5ac369f267c",
|
"manifestSha256": "f69ceb758c643701480af441da26dfa64e190c9e583073deba211bac3e2a6e1a",
|
||||||
"filesSha256": "c018ba481831e23d3183a38ac47251f19754c7464baa5d85b47cea7a49fcfa95",
|
"filesSha256": "c018ba481831e23d3183a38ac47251f19754c7464baa5d85b47cea7a49fcfa95",
|
||||||
"files": 11,
|
"files": 11,
|
||||||
"dir": "model/earth-geography"
|
"dir": "model/earth-geography"
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"id": "earth-revolution",
|
"id": "earth-revolution",
|
||||||
"version": "1.6",
|
"version": "1.7",
|
||||||
"build": "bd57e6ed67",
|
"build": "53b7a0fbc3",
|
||||||
"manifestSha256": "2d05234ea0d4de5ac55b7a076085ccfbb94ed107cce2b2d40e56d45bc3b37f3e",
|
"manifestSha256": "ab257669cd2bc57289d7e86b361064034d6040e85603b65069a93aec8d457b0b",
|
||||||
"filesSha256": "4cd45b0324a77574a0da3a939c2a6faebc785c5a24cb50136d62a78a6ea2e9b1",
|
"filesSha256": "4cd45b0324a77574a0da3a939c2a6faebc785c5a24cb50136d62a78a6ea2e9b1",
|
||||||
"files": 7,
|
"files": 7,
|
||||||
"dir": "model/earth-revolution"
|
"dir": "model/earth-revolution"
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"id": "earth-rotation",
|
"id": "earth-rotation",
|
||||||
"version": "1.6",
|
"version": "1.7",
|
||||||
"build": "a79f660ec2",
|
"build": "ecd52665f9",
|
||||||
"manifestSha256": "cb4ec5f310e7f05235042180dfdb1d8904c37b2d67b06a174f55589eed1652b9",
|
"manifestSha256": "d463d85e08fd7f0525f8e08a5e9ec49c0005b3d8ca97a7f9497e95bdbb0697cb",
|
||||||
"filesSha256": "594b005a6a9f36cd0b5d4e4a7a0b1ab42d53c8032832545b71c3915493d56c8e",
|
"filesSha256": "594b005a6a9f36cd0b5d4e4a7a0b1ab42d53c8032832545b71c3915493d56c8e",
|
||||||
"files": 7,
|
"files": 7,
|
||||||
"dir": "model/earth-rotation"
|
"dir": "model/earth-rotation"
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"id": "scale-calculator",
|
"id": "scale-calculator",
|
||||||
"version": "1.5",
|
"version": "1.6",
|
||||||
"build": "ec6119e3f4",
|
"build": "105653737d",
|
||||||
"manifestSha256": "54cf496553d11b704abfa06588ffccfed3f881a3b919d0e2304c18e157fd1f0a",
|
"manifestSha256": "2ac714eafb9acb4e4f11567b61848441de0f65ac41eb4260bc2d868c9500f56d",
|
||||||
"filesSha256": "732dd26406e0f1e836970499d7ea644def332ce909d7f8aa0a403bbe7337e604",
|
"filesSha256": "732dd26406e0f1e836970499d7ea644def332ce909d7f8aa0a403bbe7337e604",
|
||||||
"files": 6,
|
"files": 6,
|
||||||
"dir": "model/scale-calculator"
|
"dir": "model/scale-calculator"
|
||||||
}
|
}
|
||||||
]
|
],
|
||||||
|
"signature": {
|
||||||
|
"alg": "ECDSA-P256-SHA256",
|
||||||
|
"keyId": "gc-2026-12",
|
||||||
|
"value": "U6j86/9PIUe5ZIqLRUlSIFf6EhODc7Dar1KvL7MecYujzNJ+ZnRrUg7aUT1rvktVwz4nyRacf9RYM2JQFb+qKw==",
|
||||||
|
"contentSha256": "585f22236fa1a50d4e99581c676b8ad694c5e352b12fe1bfed30c342b1f38690",
|
||||||
|
"signedAt": "2026-11-19T10:21:32Z"
|
||||||
|
}
|
||||||
}
|
}
|
||||||
+47
-42
@@ -1,96 +1,101 @@
|
|||||||
{
|
{
|
||||||
"schema": 1,
|
"schema": 1,
|
||||||
"generated": "2026-11-17T22:53:52Z",
|
"generated": "2026-11-19T10:20:00Z",
|
||||||
"repository": "https://gitcode.com/Morris_1/GC",
|
"repository": "https://git.xhmcl.com/Morris/GC",
|
||||||
"branch": "main",
|
"branch": "main",
|
||||||
"modelDir": "model",
|
"modelDir": "model",
|
||||||
"launcher": {
|
"launcher": {
|
||||||
"version": "1.0.7",
|
"version": "1.1.1",
|
||||||
"revision": "",
|
"revision": "",
|
||||||
"packages": {
|
"packages": {
|
||||||
"win-x64": {
|
"win-x64": {
|
||||||
"path": "dist/win-amd64/GC-1.0.7-win-amd64.zip",
|
"path": "dist/win-amd64/GCL-1.1.1-win-amd64.zip",
|
||||||
"dir": "dist/win-amd64",
|
"dir": "dist/win-amd64",
|
||||||
"name": "GC-1.0.7-win-amd64.zip",
|
"name": "GCL-1.1.1-win-amd64.zip",
|
||||||
"url": "https://gitcode.com/Morris_1/GC/releases/download/v1.0.7/GC-1.0.7-win-amd64.zip",
|
"url": "https://git.xhmcl.com/Morris/GC/releases/download/1.1.1/GCL-1.1.1-win-amd64.zip",
|
||||||
"sha256": "f90ff51ac6b041ae238cbeb4672622b0d029142a9d8b0705f08e654336512308",
|
"sha256": "a03532606121280a1553ea73e56d6f9e8cc6cd9eefaf49f8c62857733199c10f",
|
||||||
"size": 46363183
|
"size": 74993562
|
||||||
},
|
},
|
||||||
"win-arm64": {
|
"win-arm64": {
|
||||||
"path": "dist/win-arm64/GC-1.0.7-win-arm64.zip",
|
"path": "dist/win-arm64/GCL-1.1.1-win-arm64.zip",
|
||||||
"dir": "dist/win-arm64",
|
"dir": "dist/win-arm64",
|
||||||
"name": "GC-1.0.7-win-arm64.zip",
|
"name": "GCL-1.1.1-win-arm64.zip",
|
||||||
"url": "https://gitcode.com/Morris_1/GC/releases/download/v1.0.7/GC-1.0.7-win-arm64.zip",
|
"url": "https://git.xhmcl.com/Morris/GC/releases/download/1.1.1/GCL-1.1.1-win-arm64.zip",
|
||||||
"sha256": "0b2bab2c3ac7e6223d8dd0b0faf9a0994319fa5ad13826addf7b402619b812e0",
|
"sha256": "0cd3e045fbc2415bb170e545bb720841eb4c5ebc01a98e03105618a2b7bace46",
|
||||||
"size": 44390354
|
"size": 72535103
|
||||||
},
|
},
|
||||||
"osx-arm64": {
|
"osx-arm64": {
|
||||||
"path": "dist/mac-arm64/GC-1.0.7-mac-arm64.zip",
|
"path": "dist/mac-arm64/GCL-1.1.1-mac-arm64.zip",
|
||||||
"dir": "dist/mac-arm64",
|
"dir": "dist/mac-arm64",
|
||||||
"name": "GC-1.0.7-mac-arm64.zip",
|
"name": "GCL-1.1.1-mac-arm64.zip",
|
||||||
"url": "https://gitcode.com/Morris_1/GC/releases/download/v1.0.7/GC-1.0.7-mac-arm64.zip",
|
"url": "https://git.xhmcl.com/Morris/GC/releases/download/1.1.1/GCL-1.1.1-mac-arm64.zip"
|
||||||
"sha256": "e5fd355bace68dc0794eb3e049cbef63c952a60a765ab3806adaf1199e1b09ab",
|
|
||||||
"size": 9178314
|
|
||||||
},
|
},
|
||||||
"osx-x64": {
|
"osx-x64": {
|
||||||
"path": "dist/mac-x64/GC-1.0.7-mac-x64.zip",
|
"path": "dist/mac-x64/GCL-1.1.1-mac-x64.zip",
|
||||||
"dir": "dist/mac-x64",
|
"dir": "dist/mac-x64",
|
||||||
"name": "GC-1.0.7-mac-x64.zip",
|
"name": "GCL-1.1.1-mac-x64.zip",
|
||||||
"url": "https://gitcode.com/Morris_1/GC/releases/download/v1.0.7/GC-1.0.7-mac-x64.zip"
|
"url": "https://git.xhmcl.com/Morris/GC/releases/download/1.1.1/GCL-1.1.1-mac-x64.zip"
|
||||||
},
|
},
|
||||||
"linux-x64": {
|
"linux-arm64": {
|
||||||
"path": "dist/linux-amd64/GC-1.0.7-linux-amd64.zip",
|
"path": "dist/linux-arm64/GCL-1.1.1-linux-arm64.zip",
|
||||||
"dir": "dist/linux-amd64",
|
"dir": "dist/linux-arm64",
|
||||||
"name": "GC-1.0.7-linux-amd64.zip",
|
"name": "GCL-1.1.1-linux-arm64.zip",
|
||||||
"url": "https://gitcode.com/Morris_1/GC/releases/download/v1.0.7/GC-1.0.7-linux-amd64.zip"
|
"url": "https://git.xhmcl.com/Morris/GC/releases/download/1.1.1/GCL-1.1.1-linux-arm64.zip"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"models": [
|
"models": [
|
||||||
{
|
{
|
||||||
"id": "contour-map",
|
"id": "contour-map",
|
||||||
"version": "1.0",
|
"version": "1.1",
|
||||||
"build": "43dcb6dc63",
|
"build": "773ab2161d",
|
||||||
"manifestSha256": "f7896a85d5f9e9f10e021c07931dee51f0ef86151a6a89e2ed39e37cb7f996a6",
|
"manifestSha256": "ac3231d55175757b4c477ad6a3c398c041db9511061f0c650d2c10efca881103",
|
||||||
"filesSha256": "a6bdf9b4273aabee50c3c94ceab4d0abee15f0df1af90c58bdbb796e0d2d5699",
|
"filesSha256": "a6bdf9b4273aabee50c3c94ceab4d0abee15f0df1af90c58bdbb796e0d2d5699",
|
||||||
"files": 5,
|
"files": 5,
|
||||||
"dir": "model/contour-map"
|
"dir": "model/contour-map"
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"id": "earth-geography",
|
"id": "earth-geography",
|
||||||
"version": "1.8",
|
"version": "1.9",
|
||||||
"build": "16eaf4110f",
|
"build": "cc68b8863b",
|
||||||
"manifestSha256": "0b8dd41e8535284576873956ed1db8755097649fe801d887b65ca5ac369f267c",
|
"manifestSha256": "f69ceb758c643701480af441da26dfa64e190c9e583073deba211bac3e2a6e1a",
|
||||||
"filesSha256": "c018ba481831e23d3183a38ac47251f19754c7464baa5d85b47cea7a49fcfa95",
|
"filesSha256": "c018ba481831e23d3183a38ac47251f19754c7464baa5d85b47cea7a49fcfa95",
|
||||||
"files": 11,
|
"files": 11,
|
||||||
"dir": "model/earth-geography"
|
"dir": "model/earth-geography"
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"id": "earth-revolution",
|
"id": "earth-revolution",
|
||||||
"version": "1.6",
|
"version": "1.7",
|
||||||
"build": "bd57e6ed67",
|
"build": "53b7a0fbc3",
|
||||||
"manifestSha256": "2d05234ea0d4de5ac55b7a076085ccfbb94ed107cce2b2d40e56d45bc3b37f3e",
|
"manifestSha256": "ab257669cd2bc57289d7e86b361064034d6040e85603b65069a93aec8d457b0b",
|
||||||
"filesSha256": "4cd45b0324a77574a0da3a939c2a6faebc785c5a24cb50136d62a78a6ea2e9b1",
|
"filesSha256": "4cd45b0324a77574a0da3a939c2a6faebc785c5a24cb50136d62a78a6ea2e9b1",
|
||||||
"files": 7,
|
"files": 7,
|
||||||
"dir": "model/earth-revolution"
|
"dir": "model/earth-revolution"
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"id": "earth-rotation",
|
"id": "earth-rotation",
|
||||||
"version": "1.6",
|
"version": "1.7",
|
||||||
"build": "a79f660ec2",
|
"build": "ecd52665f9",
|
||||||
"manifestSha256": "cb4ec5f310e7f05235042180dfdb1d8904c37b2d67b06a174f55589eed1652b9",
|
"manifestSha256": "d463d85e08fd7f0525f8e08a5e9ec49c0005b3d8ca97a7f9497e95bdbb0697cb",
|
||||||
"filesSha256": "594b005a6a9f36cd0b5d4e4a7a0b1ab42d53c8032832545b71c3915493d56c8e",
|
"filesSha256": "594b005a6a9f36cd0b5d4e4a7a0b1ab42d53c8032832545b71c3915493d56c8e",
|
||||||
"files": 7,
|
"files": 7,
|
||||||
"dir": "model/earth-rotation"
|
"dir": "model/earth-rotation"
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"id": "scale-calculator",
|
"id": "scale-calculator",
|
||||||
"version": "1.5",
|
"version": "1.6",
|
||||||
"build": "ec6119e3f4",
|
"build": "105653737d",
|
||||||
"manifestSha256": "54cf496553d11b704abfa06588ffccfed3f881a3b919d0e2304c18e157fd1f0a",
|
"manifestSha256": "2ac714eafb9acb4e4f11567b61848441de0f65ac41eb4260bc2d868c9500f56d",
|
||||||
"filesSha256": "732dd26406e0f1e836970499d7ea644def332ce909d7f8aa0a403bbe7337e604",
|
"filesSha256": "732dd26406e0f1e836970499d7ea644def332ce909d7f8aa0a403bbe7337e604",
|
||||||
"files": 6,
|
"files": 6,
|
||||||
"dir": "model/scale-calculator"
|
"dir": "model/scale-calculator"
|
||||||
}
|
}
|
||||||
]
|
],
|
||||||
|
"signature": {
|
||||||
|
"alg": "ECDSA-P256-SHA256",
|
||||||
|
"keyId": "gc-2026-12",
|
||||||
|
"value": "U6j86/9PIUe5ZIqLRUlSIFf6EhODc7Dar1KvL7MecYujzNJ+ZnRrUg7aUT1rvktVwz4nyRacf9RYM2JQFb+qKw==",
|
||||||
|
"contentSha256": "585f22236fa1a50d4e99581c676b8ad694c5e352b12fe1bfed30c342b1f38690",
|
||||||
|
"signedAt": "2026-11-19T10:21:32Z"
|
||||||
|
}
|
||||||
}
|
}
|
||||||
Reference in new issue
Block a user