Compare commits

...
Author SHA1 Message Date
Morris a361c889f8 修复审计发现的问题,默认构建即带 Flutter 前端
P0
- GC-SAVEDOG:更新改为整目录替换(旧文件备份到 .GC/update/backup,
  失败可完整回滚),不再只搬一个 exe;回滚会删掉新包独有文件
- GC-SAVEDOG:包名校验放宽为单文件名模式,Linux 启动器(无扩展名)可更新
- GC-DOWNLOAD:测速全失败时不再回退 GitCode,改为返回「不可用」并保留上次可用源
- GC-DOWNLOAD:识别并赋予 Linux 无扩展名启动器可执行位;兼容脚本清理旧版时
  也覆盖无扩展名产物
- CI:删除 nightly-prerelease(绕开 build.sh,产出无前端空壳);alpha 工作流
  去掉非法 cron,只保留手动触发

P1
- 前端:主题设置真正生效(深色/浅色/跟随系统 + 持久化),去掉死字段
- 前端:下载页轮询改为自适应单次链,页面不可见或任务结束后降频/停止
- 前端:下载完成 / 删除模型后首页列表自动刷新
- 前端:复用 http.Client,不再每次轮询新建连接
- 后端:/api/models 走缓存,不再每次全盘递归统计体积
- 设置页:外部改动能同步进表单,不再只同步一次

P2
- 错误响应统一为 ErrorDto,不再复用 LaunchResultDto
- 限流桶定期清理,避免无限增长
- 播放器窗口去重,避免同一模型重复开窗
- 封面按实际格式返回,去掉错误的 image/png 与 no-store
- 端口集中到 GcUiContract,前端可用 GC_UI_PORT 或 ui-backend.json 发现后端
- 构建:Windows 包改为散开发布,与后端共用运行时(体积约 109MB -> 72MB)
- 文档:更新仓库地址与更新流程说明

测试:dotnet build 全绿;GC.Tests 更新链路全通过;flutter analyze 无问题;
flutter test 11 项全通过。
2026-11-18 20:10:03 +08:00
Morris 461e79aa7f Merge pull request 'build: 默认编 Flutter 前端,补 Linux 目标并按主机选择产物' (#9) from feat/flutter-default into main
Reviewed-on: Morris/GC#9
2026-11-18 11:23:16 +00:00
Morris d7f6d8de9f build: 默认编 Flutter 前端,补 Linux 目标并按主机选择产物
此前 build.sh 在非 Windows 宿主上把前端当「可选项」:flutter 缺失只告警、
交叉编译失败只告警、macOS 前端在 Linux 上直接跳过。结果是包照出,用户拿到
的是 Avalonia 回退界面,而构建日志里一行红字很容易被忽略。

改为默认必需:
- build_flutter_ui / build_flutter_ui_cross 缺 flutter 或编译失败一律返回非 0,
  build.sh 立即中断并给出原因(交叉编译失败时带日志尾巴)
- 确实要出降级包时显式声明 ./build.sh build --allow-no-ui

目标平台按构建主机决定,每条产物都带 Flutter:
  macOS 主机 → mac-arm64(Xcode 原生)+ win-amd64/win-arm64(mingw 交叉)
  Linux 主机 → linux-amd64(原生)+ win-amd64/win-arm64(mingw 交叉)
  Windows 主机 → win-amd64/win-arm64(原生)

Linux 目标此前根本不存在,这次一并补上:
- GC-UI/frontend/linux/ 由 flutter create 生成,BINARY_NAME=GC-UI、
  APPLICATION_ID=com.xhmcl.GC、窗口标题 "Morris GC"
- build_flutter_ui 增加 linux 分支,bundle(GC-UI + lib/ + data/)铺进
  dist/linux-amd64/,pack_launcher 增加 Linux 整目录打包
- linux/CMakeLists.txt 强制 CMAKE_INSTALL_PREFIX 指向 build/.../bundle:
  某些环境下它会被初始化成 /usr/local,导致 flutter 报「构建成功」但
  bundle 是空的、产物装进了系统目录(本机实测踩到)

顺带修正两处:
- 生成 settings.json 的默认 updateRepository 还是 gitcode 地址,与只保留
  xhmcl 源的现状不符
- 进度条权重改为按实际目标动态计算,新平台不会再把总进度算过 100%

验证(Linux 主机,flutter 3.24.5):
- ./build.sh build 出 win-amd64 109 MB、win-arm64 105 MB、linux-amd64 65 MB,
  三份均含 Flutter 前端,清单签名 Verified
- Linux 包在 Xvfb + llvmpipe 下实跑:后端 /api/health 返回 ok,GC-UI 窗口
  正常渲染出模型库首页
- macOS 目标在 Linux 上不再产出 Avalonia 空壳包(要它得回 macOS 编)
2026-11-18 19:15:05 +08:00
Morris 7e34cb0467 Merge pull request 'fix(update): 换发清单签名密钥,补齐 1.0.9 已签名清单' (#8) from feat/manifest-signing into main
Reviewed-on: Morris/GC#8
2026-11-18 10:41:20 +00:00
Morris e327a56421 fix(update): 换发清单签名密钥,补齐 1.0.9 已签名清单
仓库里硬编码的公钥 gc-2026-11 没有对应的私钥(.signing/ 在 .gitignore 里,
私钥从来没入过库,也无法找回),导致 build.sh 每次签名都失败,version.json
始终是「未签名」。而客户端默认 RequireSignedManifest=true,未签名清单一律
拒绝更新 —— 自动更新实际上完全不可用。

改动:
- keygen 生成新密钥 gc-2026-12(指纹 ee6083be47a87907),公钥写进
  SignatureKeyring;旧 gc-2026-11 保留一个版本周期,标注为「私钥遗失、已停用」
- GC-SAVEDOG 的 DefaultKeyId 与 build_funcs.sh 的 GC_SIGNING_KEY_ID 默认值
  同步改为 gc-2026-12,避免 keyId 与私钥不匹配又签出 Invalid
- GC.Tests 构造可信清单时用的 keyId 改为 gc-2026-12(原来硬编码旧 keyId,
  换钥匙后会判成 Invalid)
- README 补上密钥轮换的实际步骤与「换钥匙老客户端就更新不了」的代价
- Directory.Build.props 版本 1.0.7 → 1.0.9(此前只靠 -version 传参,
  仓库里一直停在 1.0.7,与实际发布脱节)
- version.json / model/version.json 换成 1.0.9 且带 gc-2026-12 签名,
  两份字节一致

验证:
- GC.Tests --update-test 全通过,日志里是「清单验签通过(gc-2026-12)」,
  篡改清单被判 Invalid 并拒绝更新
- GC-SAVEDOG verify --manifest version.json → Verified
- 三平台重新出包:win-amd64 109 MB、win-arm64 105 MB、mac-arm64 57 MB

注意:1.0.8 及更早的客户端只认识旧公钥,这份清单在它们眼里是「签名无效」,
与之前的「未签名」等价 —— 都不会自动更新。要让自动更新真正生效,需要把
带新公钥的 1.0.9 发出去。
2026-11-18 18:20:32 +08:00
Morris 40e72957e3 Merge pull request 'build: 支持在 Linux/macOS 上交叉编译 Windows 前端' (#7) from feat/win-cross-compile into main
Reviewed-on: Morris/GC#7
2026-11-18 10:09:49 +00:00
Morris fdbf3160e8 fix(update): 更新清单指向 xhmcl 仓库,下载地址与 tag 对齐
VersionStamp 里硬编码的仓库地址还是 gitcode.com/Morris_1/GC,与启动器
AppSettings.UpdateRepository 的默认值(git.xhmcl.com/Morris/GC)不一致,
导致生成的 version.json 把客户端导到一个没有对应 Release 的仓库。

同时下载地址拼的是 /download/v{版本}/,而实际 tag 没有 v 前缀
(1.0.7、1.0.8),两者对不上会 404。

改为读同一仓库地址并去掉 v 前缀,同时把当前 1.0.8 的清单同步过来
(sha256 沿用本次构建产物,未重算)。
2026-11-18 13:54:15 +08:00
Morris 2cc862a8da Merge pull request '启动器接入 Flutter 前端 · 公司信息统一 Morris · 模型版本 +1' (#6) from feat/flutter-ui into main
Reviewed-on: Morris/GC#6
2026-11-18 05:47:39 +00:00
Morris 2c0c566c81 build: 支持在 Linux/macOS 上交叉编译 Windows 前端
此前 Windows 包内不含 Flutter 界面,只能回退到内置 Avalonia 界面,
原因是 Flutter 官方不支持在非 Windows 主机上执行 flutter build windows。

实际上 Windows 嵌入层(windows/runner + cpp_client_wrapper)是纯 Win32
加标准 C++,只通过 C ABI 调用 flutter_windows.dll,因此用 mingw-w64 即可
编译。整条链路上唯一必须执行的 Windows 二进制是 AOT 快照生成器
gen_snapshot.exe,交给 wine 运行即可。全流程不需要 Windows 机器或 MSVC。

实现:
- buildsh/cross/toolchain-mingw.cmake  CMake 交叉工具链,posix 线程模型,
  静态链接 libstdc++/libgcc,产物只依赖系统 DLL 和 flutter_windows.dll
- buildsh/cross/CMakeLists.txt         只编 C++ 外壳,绕开 tool_backend.bat
  与 MSVC 专用编译参数
- buildsh/cross/build-ui-win-cross.sh  拉取引擎产物、为 gen_snapshot 装 wine
  包装、生成 AOT 快照、组装出与官方 toolchain 一致的目录结构
- build_flutter_ui_cross / build.sh    非 Windows 主机走交叉编译分支,
  x64 产物同时放进 win-amd64 与 win-arm64 两个包

顺带修掉 shell.dart 的常量求值错误:强调色改为跟随设置的动态 getter 后,
const Text 里引用 GcColors.accent 会让编译器报错。

已在 Linux 上用 wine 验证产物:Flutter 引擎正常初始化,Dart AOT 快照加载
并执行到业务代码,后端 /api/health 正常返回。
2026-11-18 13:29:53 +08:00
50 changed files with 2140 additions and 526 deletions

No files matched your search

+10 -14
View File
@@ -1,9 +1,9 @@
# GC-UI 夜间 alpha 构建(Gitea Actions)
# GC-UI alpha 构建(Gitea Actions)
#
# 触发:每天 21:00(Asia/Shanghai)自动跑一次,产出 Windows 与 macOS 的 Flutter 前端产物,
# 发布为一个「预览版(prerelease)」Release —— 不占用 latest。
# 手动:Actions 页面点 Run workflow(Gitea 的 workflow_dispatch),用于验证 runner 是否就绪;
# 也可以从命令行调 POST /api/v1/repos/{owner}/{repo}/actions/workflows/{file}/dispatches。
# 触发:**仅手动**。定时任务已取消(不再每天自动构建),需要时在 Actions 页面点
# Run workflow,或从命令行调
# POST /api/v1/repos/{owner}/{repo}/actions/workflows/{file}/dispatches。
# 产物:Windows 与 macOS 的 Flutter 前端,发布为一个「预览版(prerelease)」Release —— 不占用 latest。
#
# 为什么是 .gitea/workflows/:本仓库是自建 Gitea,不是 GitHub。Gitea Actions 语法与
# GitHub Actions 基本一致,但工作流目录是 .gitea/workflows/,API 前缀是 /api/v1,
@@ -16,12 +16,8 @@
name: GC-UI Alpha
on:
schedule:
# 每天晚上 21:00,北京时间。
# Gitea 1.23 起 Actions 的 cron 默认按 UTC 解释,这里显式带 TZ= 前缀(robfig/cron 支持的
# 时区前缀语法),这样不依赖服务器自身时区设置。
# 如果所在实例不认 TZ= 前缀,改用等效的 UTC 写法 '0 13 * * *'。
- cron: 'TZ=Asia/Shanghai 0 21 * * *'
# 定时触发已取消:夜间构建会绕开 build.sh,产出不含后端/前端的空壳包,
# 且 cron 的 TZ= 前缀在部分 Gitea 版本上非法。需要时手动 dispatch。
workflow_dispatch:
inputs:
note:
@@ -67,7 +63,7 @@ jobs:
exit 1
fi
# 北京时间当天日期,让产物名和 tag 与「每晚 9 点」对得上
# 北京时间当天日期,让同一天的多次手动构建落在同一个日期前缀下
DATE=$(TZ=Asia/Shanghai date +%Y%m%d)
# 同一天重跑时用 run_number 区分,tag 不重复
VERSION="${BASE}-alpha.${DATE}.${{ github.run_number }}"
@@ -122,11 +118,11 @@ jobs:
tag, version, sha, server = sys.argv[1:5]
short = sha[:7]
body = (
"GC-UI 夜间 alpha 构建(自动生成,**预览版 / prerelease**)。\n\n"
"GC-UI alpha 构建(手动触发,**预览版 / prerelease**)。\n\n"
"- 版本:`%s`\n"
"- 提交:`%s`\n"
"- 构建来源:%s/commit/%s\n"
"- 通道:alpha —— 每晚 21:00(Asia/Shanghai)自动构建\n\n"
"- 通道:alpha —— 手动触发(定时任务已取消)\n\n"
"产物说明:\n\n"
"| 文件 | 平台 | 内容 |\n"
"|---|---|---|\n"
-115
View File
@@ -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
+3
View File
@@ -51,3 +51,6 @@ GC-UI/frontend/**/DebugProfile.entitlements.bak
GC-UI/frontend/**/*.iml
GC-UI/frontend/test/shots/
# GC.Tests 离屏渲染输出(dotnet run ... GC.Tests 默认写到仓库根 screenshots/)
screenshots/
+1 -1
View File
@@ -22,7 +22,7 @@
-->
<AvaloniaVersion>11.3.9</AvaloniaVersion>
<MvvmVersion>8.2.2</MvvmVersion>
<Version>1.0.7</Version>
<Version>1.0.9</Version>
<Company>Morris</Company>
<Product>GC</Product>
<NeutralLanguage>zh-Hans</NeutralLanguage>
+36 -18
View File
@@ -21,8 +21,8 @@ namespace GC;
/// </summary>
internal static class FlutterShell
{
/// <summary>与 GC-UI/frontend 的默认 baseUrl 保持一致,前端不需要额外配置。</summary>
private const int Port = 17890;
/// <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 Process? _backend;
@@ -35,23 +35,36 @@ internal static class FlutterShell
if (backendPath == null || uiPath == null) return false;
// 用户可能重复启动:已有后端在跑就直接复用,退出时也不要关掉别人的进程。
var reused = IsHealthy();
if (!reused)
{
_backend = Start(backendPath, $"--port {Port}", dir);
if (_backend == null) return false;
var port = Port;
if (!WaitHealthy(TimeSpan.FromSeconds(25)))
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++)
{
Stop(_backend);
_backend = null;
return false;
var process = Start(backendPath, $"--port {candidate}", dir);
if (process == null) continue;
if (WaitHealthy(candidate, process, TimeSpan.FromSeconds(25)))
{
port = candidate;
_backend = process;
break;
}
Stop(process);
}
if (_backend == null) return false;
}
AppDomain.CurrentDomain.ProcessExit += (_, _) => Stop(_backend);
var ui = Start(uiPath, null, dir);
var ui = Start(uiPath, null, dir, port);
if (ui == null)
{
Stop(_backend);
@@ -102,7 +115,7 @@ internal static class FlutterShell
// ---------------------------------------------------------------- 进程管理
private static Process? Start(string fileName, string? arguments, string workingDirectory)
private static Process? Start(string fileName, string? arguments, string workingDirectory, int port = 0)
{
try
{
@@ -114,6 +127,11 @@ internal static class FlutterShell
};
if (!string.IsNullOrEmpty(arguments)) info.Arguments = arguments;
// 把实际端口传给子进程:后端读它监听,前端读它拼 baseUrl。
// 这样换端口不需要重新编译前端。
if (port > 0)
info.Environment[Services.GcUiContract.PortEnvVar] = port.ToString();
// macOS .app 内的二进制也需要可执行位;发布包由 zip 解开时可能丢失。
if (!OperatingSystem.IsWindows())
{
@@ -149,11 +167,11 @@ internal static class FlutterShell
// ---------------------------------------------------------------- 健康检查
private static bool IsHealthy()
private static bool IsHealthy(int port)
{
try
{
using var response = Http.GetAsync($"http://127.0.0.1:{Port}/api/health")
using var response = Http.GetAsync($"http://127.0.0.1:{port}/api/health")
.GetAwaiter().GetResult();
return response.IsSuccessStatusCode;
}
@@ -163,15 +181,15 @@ internal static class FlutterShell
}
}
private static bool WaitHealthy(TimeSpan timeout)
private static bool WaitHealthy(int port, Process backend, TimeSpan timeout)
{
var deadline = DateTime.UtcNow + timeout;
while (DateTime.UtcNow < deadline)
{
// 后端进程已经退出就没必要再等:端口被占、依赖缺失都会走这里。
if (_backend is { HasExited: true }) return false;
if (backend.HasExited) return false;
if (IsHealthy()) return true;
if (IsHealthy(port)) return true;
Thread.Sleep(250);
}
return false;
+44 -4
View File
@@ -367,8 +367,12 @@ public static class LauncherUpdater
else if (File.Exists(manifestCopy))
File.Delete(manifestCopy);
// 包名:GC-<版本>-<平台标签>.app/.exe(SAVEDOG 找不到时会自行扫描包内顶层)
var packageName = $"GC-{latest}-{PlatformLabel}" + (OperatingSystem.IsMacOS() ? ".app" : ".exe");
// 包名:GC-<版本>-<平台标签>.app/.exe(SAVEDOG 找不到时会自行扫描包内顶层)。
// Linux 的启动器没有扩展名,别硬加 .exe —— 那会让按包名查找永远落空。
var packageName = $"GC-{latest}-{PlatformLabel}" +
(OperatingSystem.IsMacOS() ? ".app"
: OperatingSystem.IsWindows() ? ".exe"
: "");
var request = new SavedogRequest
{
@@ -447,7 +451,8 @@ public static class LauncherUpdater
/// 找不到 SAVEDOG 时退回旧脚本流程(只用于从老版本升级的过渡)。
/// 返回 true 表示调用方应立即退出进程。
/// </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")))
@@ -484,6 +489,8 @@ public static class LauncherUpdater
catch { }
}
if (!execute) return true;
var psi = isWin
? new System.Diagnostics.ProcessStartInfo("cmd.exe")
{ UseShellExecute = false, CreateNoWindow = true }
@@ -576,7 +583,10 @@ public static class LauncherUpdater
s.AppendLine();
s.AppendLine("# delete old GC-* files: SAME platform only, version != latest");
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(" [ \"$item\" = \"$NEW\" ] && continue");
s.AppendLine(" base=$(basename \"$item\")");
@@ -584,6 +594,10 @@ public static class LauncherUpdater
s.AppendLine(" case \"$base\" in");
s.AppendLine(" *.app) stem=${stem%.app} ;;");
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(" esac");
s.AppendLine(" ver=${stem%%-*}");
@@ -711,6 +725,16 @@ public static class LauncherUpdater
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.EndsWith("-" + PlatformLabel, StringComparison.OrdinalIgnoreCase))
{
TryMarkExecutable(dest);
return name;
}
}
}
catch (Exception ex)
@@ -720,6 +744,22 @@ public static class LauncherUpdater
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)
{
try
+12 -3
View File
@@ -40,7 +40,8 @@ public sealed class SourceSelector : ISourceSelector
/// <summary>
/// 探测两个源并返回最快的。force=true 时忽略缓存。
/// 两个都失败时返回 GitCode(默认源)。
/// 两个都失败时退回主源(Xhmcl):GitCode 镜像已停更,用它兜底只会拿到过期的
/// version.json —— 反而让人以为「没有更新」。
/// </summary>
public async Task<SourcePreset> PickFastestAsync(bool force = false, CancellationToken ct = default)
{
@@ -64,12 +65,20 @@ public sealed class SourceSelector : ISourceSelector
LastLatency = latencies;
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)
{
_cached = chosen;
_cachedAt = DateTime.UtcNow;
// 全部探测失败的结果不缓存:网络刚恢复时应该立刻重新测速,
// 而不是被一次失败的探测锁住 3 分钟。
_cachedAt = usable.Count > 0 ? DateTime.UtcNow : DateTime.MinValue;
}
Console.WriteLine("[selector] 测速:" + string.Join(" ",
+277 -84
View File
@@ -26,13 +26,14 @@ internal sealed class ApplyOptions
/// </summary>
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 Log _log;
/// <summary>发布包里的启动器文件名:GC-1.0.9-win-amd64.exe。</summary>
private static readonly Regex VersionedExePattern = new(
@"^GC-\d+(?:\.\d+)+-[A-Za-z0-9]+-[A-Za-z0-9]+\.exe$",
RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.Compiled);
public Applier(ApplyOptions options, Log log)
{
_options = options;
@@ -136,20 +137,25 @@ internal sealed class Applier
return Fail(updateDir, "更新包里没有找到新版程序(" + request.PackageName + ")", 6);
}
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)
{
_log.Info($"[dry-run] 校验全部通过,将安装到 {target}");
_log.Info($"[dry-run] 校验全部通过,将整目录安装到 {installDir}" +
$"({Directory.GetFileSystemEntries(stage).Length} 个顶层条目)");
ClearDirectory(stage);
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} 已安装且上次启动正常,视为已安装");
ClearDirectory(stage);
TryDelete(zipPath);
TryDelete(requestPath);
@@ -157,35 +163,31 @@ internal sealed class Applier
{
Status = "applied",
Version = request.Version,
PackageName = Path.GetFileName(artifact),
PackageName = mainName,
Verified = true,
Message = "目标版本已存在,无需替换"
});
return 0;
}
// 6. 移入安装目录(不覆盖任何已有文件)
try
{
Directory.CreateDirectory(installDir);
if (Directory.Exists(artifact)) Directory.Move(artifact, target);
else File.Move(artifact, target);
_log.Info("新版已就位: " + Path.GetFileName(target));
}
catch (Exception ex)
// 6. 整目录替换:旧内容先搬到 backup,新内容就位;失败可原样还原。
// 只动程序文件,.GC(模型库 / 设置 / 更新目录)永远不碰。
var replaced = new List<(string Name, string? BackupPath)>();
if (!ReplaceInstallDirectory(stage, installDir, updateDir, replaced, out var replaceError))
{
RestoreFromBackup(installDir, replaced);
ClearDirectory(stage);
return Fail(updateDir, "移动到安装目录失败: " + ex.Message, 7);
return Fail(updateDir, "安装失败: " + replaceError, 7);
}
_log.Info($"新版已就位:{mainName}(替换 {replaced.Count} 个条目)");
// 7. 启动并看护
var previous = ReadLastGood(updateDir);
StartupHealth.Clear(updateDir);
Process? child;
try
{
child = Launch(target);
child = Launch(mainTarget);
}
catch (Exception ex)
{
@@ -199,14 +201,14 @@ internal sealed class Applier
if (healthy)
{
_log.Info($"v{request.Version} 启动正常,更新完成");
CleanupOldVersions(installDir, Path.GetFileName(target), request.PlatformLabel);
WriteLastGood(updateDir, request.Version, Path.GetFileName(target));
CleanupBackup(updateDir);
WriteLastGood(updateDir, request.Version, mainName);
WriteState(updateDir, new SavedogState
{
Status = "applied",
Version = request.Version,
PreviousVersion = previous?.Version,
PackageName = Path.GetFileName(target),
PackageName = mainName,
Verified = true,
Message = "更新已应用"
});
@@ -216,21 +218,21 @@ internal sealed class Applier
return 0;
}
// 8. 回滚
// 8. 回滚:撤掉新装的文件,把备份原样搬回
_log.Error($"v{request.Version} 启动后未通过健康检查({_options.TimeoutSeconds}s),开始回滚");
TryKill(child);
var removed = RemoveNewVersion(target);
_log.Info(removed ? "已移除未通过检查的新版" : "新版文件被占用,未能完全移除");
var restored = RestoreFromBackup(installDir, replaced);
_log.Info(restored ? "已还原为更新前的文件" : "部分文件未能还原,请手动重新安装");
var restored = TryLaunchPrevious(installDir, updateDir, previous, request.PlatformLabel);
var relaunched = restored && TryLaunchPrevious(installDir, updateDir, previous, request.PlatformLabel);
WriteState(updateDir, new SavedogState
{
Status = "rolledback",
Version = request.Version,
PreviousVersion = previous?.Version,
PackageName = Path.GetFileName(target),
PackageName = mainName,
Verified = true,
Message = restored
Message = relaunched
? "新版本未通过启动检查,已回滚到上一个版本"
: "新版本未通过启动检查,已移除;未找到可回滚的旧版本,请手动重新安装"
});
@@ -243,11 +245,18 @@ internal sealed class Applier
// ------------------------------------------------------------------ 校验辅助
/// <summary>
/// 包名合法性:只允许「一个文件名」,杜绝 `../` 之类的路径穿越。
///
/// 不能只认 .app / .exe —— Linux 的启动器没有扩展名
/// (GC-1.0.9-linux-amd64),按旧规则会被直接判成非法包名、更新永远失败。
/// </summary>
private static bool ValidName(string name)
=> name.Length > 0 && name.Length < 200 &&
name.IndexOfAny(new[] { '/', '\\', ':', '\0' }) < 0 &&
(name.EndsWith(".app", StringComparison.OrdinalIgnoreCase) ||
name.EndsWith(".exe", StringComparison.OrdinalIgnoreCase));
=> SafeNamePattern.IsMatch(name);
private static readonly Regex SafeNamePattern = new(
@"^[A-Za-z0-9][A-Za-z0-9._-]{0,198}$",
RegexOptions.CultureInvariant | RegexOptions.Compiled);
private static bool WaitForExit(int pid, TimeSpan timeout)
{
@@ -280,22 +289,64 @@ internal sealed class Applier
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)
{
var direct = Path.Combine(stage, packageName);
if (File.Exists(direct) || Directory.Exists(direct)) return direct;
foreach (var entry in Directory.GetFileSystemEntries(stage))
if (!string.IsNullOrWhiteSpace(packageName))
{
var name = Path.GetFileName(entry);
if (name.EndsWith(".app", StringComparison.OrdinalIgnoreCase) && Directory.Exists(entry))
return entry;
if (name.EndsWith(".exe", StringComparison.OrdinalIgnoreCase) && File.Exists(entry))
var named = Path.Combine(stage, packageName);
if (File.Exists(named) || Directory.Exists(named)) return named;
}
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 null;
}
/// <summary>主程序优先级:数字越大越优先,0 表示不是主程序。</summary>
private static int MainExecutablePriority(string fileName)
{
if (!fileName.EndsWith(".exe", StringComparison.OrdinalIgnoreCase)) return 0;
// 发布包把启动器改名成 GC-<版本>-<系统>-<架构>.exe,先按这个模式认出来。
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)
@@ -410,57 +461,199 @@ internal sealed class Applier
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`、更新目录自身、正在运行的 GC-SAVEDOG.exe 一律跳过。
///
/// 返回 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))
{
var name = Path.GetFileName(entry);
if (string.Equals(name, keepName, StringComparison.OrdinalIgnoreCase)) continue;
error = null;
var backupDir = Path.Combine(updateDir, "backup");
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
{
if (Directory.Exists(target)) Directory.Delete(target, true);
else if (File.Exists(target)) File.Delete(target);
Directory.CreateDirectory(installDir);
ClearDirectory(backupDir);
Directory.CreateDirectory(backupDir);
var incoming = new List<string>();
foreach (var entry in Directory.GetFileSystemEntries(stage))
{
var name = Path.GetFileName(entry);
if (IsProtected(name))
{
// 例如 GC-SAVEDOG.exe:本进程正在运行,Windows 上无法替换。
// 保留旧版守护进程即可,它下次启动会随包里的新版本一起被更新。
_log.Warn($"跳过受保护文件,保留旧版本:{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);
}
// 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;
}
catch (Exception ex)
{
_log.Warn("移除新版失败: " + ex.Message);
error = ex.Message;
return false;
}
}
/// <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);
}
catch (Exception ex)
{
ok = false;
_log.Warn($"还原 {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);
}
}
/// <summary>
/// 安装目录里不该被更新碰的东西:
/// · .GC —— 模型库、设置、日志、更新目录本身都在这里;
/// · 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,
string platformLabel)
{
// 优先用上次成功的版本;否则挑一个同平台的其它版本
// 优先用上次成功启动的主程序;否则按优先级在安装目录里找
var candidates = new List<string>();
if (lastGood != null && !string.IsNullOrWhiteSpace(lastGood.PackageName))
candidates.Add(Path.Combine(installDir, lastGood.PackageName));
@@ -468,14 +661,14 @@ internal sealed class Applier
foreach (var entry in Directory.GetFileSystemEntries(installDir))
{
var name = Path.GetFileName(entry);
var match = ArtifactPattern.Match(name);
if (!match.Success) continue;
if (!string.Equals(match.Groups["plat"].Value, platformLabel, StringComparison.OrdinalIgnoreCase))
continue;
candidates.Add(entry);
if (IsProtected(name)) continue;
if (MainExecutablePriority(name) > 0) candidates.Add(entry);
else if (Directory.Exists(entry) &&
name.EndsWith(".app", StringComparison.OrdinalIgnoreCase))
candidates.Add(entry);
}
foreach (var candidate in candidates)
foreach (var candidate in candidates.Distinct(StringComparer.OrdinalIgnoreCase))
{
if (!File.Exists(candidate) && !Directory.Exists(candidate)) continue;
try
+1 -1
View File
@@ -23,7 +23,7 @@ namespace GC.Savedog;
/// </summary>
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 static int Main(string[] args)
+72 -3
View File
@@ -1,6 +1,9 @@
# 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 基本一致,
差异集中在 **runner 标签** 和 **API 前缀** 两处。
@@ -64,9 +67,75 @@ Windows 还需要 **VS Build Tools 的「使用 C++ 的桌面开发」工作负
## 本地构建(不经 CI)
```bash
# macOS
# 按构建主机自动选目标,每条产物都带 Flutter 前端:
# macOS 主机 → mac-arm64(原生)+ win-amd64 / win-arm64(mingw 交叉)
# Linux 主机 → linux-amd64(原生)+ win-amd64 / win-arm64(mingw 交叉)
# Windows 主机 → win-amd64 / win-arm64(原生)
./build.sh build
# 前端是必需项:flutter 缺失或编译失败会直接中断,
# 确需降级成只有 Avalonia 回退界面的包时才用:
./build.sh build --allow-no-ui
# 只编 macOS 前端
./GC-UI/build-ui.sh macos
# Windows
# Windows 主机原生构建
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-amd64/`。
### 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 副本再编译。
`.gitea/workflows` 里的 `windows` 任务仍然跑在 `windows-latest` 上;若手头只有 macOS/Linux
构建机,可以把该任务的 `runs-on` 换成对应标签,直接复用这套交叉编译脚本,
不再需要 VS Build Tools。
+5 -1
View File
@@ -65,7 +65,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-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. 启动前端
+9
View File
@@ -133,6 +133,15 @@ public sealed record AboutDto(
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 PathRequest(string Path);
+29 -3
View File
@@ -28,7 +28,7 @@ public sealed class AvaloniaHost
{
private readonly AppServices _services;
private readonly object _gate = new();
private readonly List<PlayerWindow> _windows = new();
private readonly Dictionary<string, PlayerWindow> _windows = new(StringComparer.OrdinalIgnoreCase);
private Task<bool>? _startTask;
public AvaloniaHost(AppServices services) => _services = services;
@@ -98,6 +98,27 @@ public sealed class AvaloniaHost
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;
LoadedModel? loaded = null;
try
@@ -111,13 +132,18 @@ public sealed class AvaloniaHost
window = new PlayerWindow(package, loaded);
var captured = loaded;
var id = package.Id;
window.Closed += (_, _) =>
{
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();
return $"已启动模型 {package.Id}";
}
+53 -28
View File
@@ -127,6 +127,17 @@ app.Use(async (context, next) =>
{
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),
@@ -135,8 +146,7 @@ app.Use(async (context, next) =>
if (bucket.Count > 40)
{
context.Response.StatusCode = StatusCodes.Status429TooManyRequests;
await context.Response.WriteAsJsonAsync(
new LaunchResultDto(false, "请求过于频繁,请稍后再试"));
await context.Response.WriteAsJsonAsync(ErrorDto.Of("请求过于频繁,请稍后再试"));
return;
}
}
@@ -158,12 +168,16 @@ app.MapGet("/api/health", () => Results.Ok(new HealthDto(
app.MapGet("/api/models", () =>
Results.Ok(services.Models.Scan().Select(ToModelDto).ToList()));
app.MapGet("/api/models/{id}/preview", (string id) =>
app.MapGet("/api/models/{id}/preview", (string id, HttpResponse response) =>
{
if (!IsSafeId(id)) return Results.BadRequest();
if (!IsSafeId(id)) return Results.BadRequest(ErrorDto.Of("模型标识无效"));
var package = services.Models.Find(id);
if (package == null || !File.Exists(package.PreviewPath)) return Results.NotFound();
return Results.File(package.PreviewPath, "image/png");
// 封面是静态图,允许前端缓存:默认全局中间件写的 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) =>
@@ -188,12 +202,12 @@ app.MapPost("/api/models/{id}/launch", async (string id) =>
app.MapDelete("/api/models/{id}", (string id) =>
{
if (!IsSafeId(id)) return Results.BadRequest(new LaunchResultDto(false, "模型标识无效"));
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(new LaunchResultDto(false, $"没有找到模型 {id}"));
: Results.NotFound(ErrorDto.Of($"没有找到模型 {id}"));
});
// ---- 设置 -----------------------------------------------------------------
@@ -202,17 +216,17 @@ app.MapGet("/api/settings", () => Results.Ok(ToSettingsDto()));
app.MapPost("/api/settings", (SettingsPatch? patch) =>
{
if (patch == null) return Results.BadRequest(new LaunchResultDto(false, "缺少设置内容"));
if (patch == null) return Results.BadRequest(ErrorDto.Of("缺少设置内容"));
// 白名单校验:设置项会写进磁盘并被前端直接使用,不接受任意字符串。
if (patch.Language != null && !allowedLanguages.Contains(patch.Language))
return Results.BadRequest(new LaunchResultDto(false, "不支持的界面语言"));
return Results.BadRequest(ErrorDto.Of("不支持的界面语言"));
if (patch.Theme != null && !allowedThemes.Contains(patch.Theme))
return Results.BadRequest(new LaunchResultDto(false, "不支持的主题"));
return Results.BadRequest(ErrorDto.Of("不支持的主题"));
if (patch.AccentColor != null && !accentHexRegex.IsMatch(patch.AccentColor))
return Results.BadRequest(new LaunchResultDto(false, "主题色需为 #RRGGBB"));
return Results.BadRequest(ErrorDto.Of("主题色需为 #RRGGBB"));
if (patch.UpdateRepository != null && !IsAllowedRepository(patch.UpdateRepository))
return Results.BadRequest(new LaunchResultDto(false, "更新仓库地址不受信任"));
return Results.BadRequest(ErrorDto.Of("更新仓库地址不受信任"));
services.Settings.Apply(s =>
{
@@ -255,14 +269,14 @@ app.MapPost("/api/sources/select", async (ForceRequest? request) =>
catch (Exception ex)
{
Console.Error.WriteLine($"[sources] 切换模型源失败: {ex}");
return Results.Json(new LaunchResultDto(false, "模型源切换失败"), statusCode: 503);
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(new LaunchResultDto(false, "没有可用的模型源"));
if (source == null) return Results.NotFound(ErrorDto.Of("没有可用的模型源"));
var index = await services.Sources.FetchAsync(source, force, null, CancellationToken.None);
var installed = services.Models.Scan()
@@ -291,16 +305,16 @@ app.MapGet("/api/remote/models", async (string? sourceId, bool force) =>
app.MapPost("/api/download", async (DownloadRequest? request) =>
{
if (request == null || string.IsNullOrWhiteSpace(request.ModelId))
return Results.BadRequest(new LaunchResultDto(false, "缺少 modelId"));
return Results.BadRequest(ErrorDto.Of("缺少 modelId"));
var source = ResolveSource(request.SourceId);
if (source == null) return Results.NotFound(new LaunchResultDto(false, "没有可用的模型源"));
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(new LaunchResultDto(false, $"源里没有模型 {request.ModelId}"));
return Results.NotFound(ErrorDto.Of($"源里没有模型 {request.ModelId}"));
var job = services.Downloads.Enqueue(model);
return Results.Ok(ToJobDto(job));
@@ -409,11 +423,11 @@ app.MapPost("/api/shell/open-folder", (PathRequest? request) =>
{
var path = request?.Path;
if (string.IsNullOrWhiteSpace(path))
return Results.BadRequest(new LaunchResultDto(false, "缺少 path"));
return Results.BadRequest(ErrorDto.Of("缺少 path"));
// 只允许打开启动器自己的目录,避免前端被当成任意路径执行器
if (!IsInsideKnownRoot(path!))
return Results.BadRequest(new LaunchResultDto(false, "只允许打开启动器自己的目录"));
return Results.BadRequest(ErrorDto.Of("只允许打开启动器自己的目录"));
Shell.OpenFolder(path!);
return Results.Ok(new LaunchResultDto(true, "已打开目录"));
@@ -424,13 +438,13 @@ 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 无效"));
return Results.BadRequest(ErrorDto.Of("URL 无效"));
if (uri.Scheme != Uri.UriSchemeHttp && uri.Scheme != Uri.UriSchemeHttps)
return Results.BadRequest(new LaunchResultDto(false, "只允许 http/https 链接"));
return Results.BadRequest(ErrorDto.Of("只允许 http/https 链接"));
if (!string.IsNullOrEmpty(uri.UserInfo))
return Results.BadRequest(new LaunchResultDto(false, "URL 不允许携带账号密码"));
return Results.BadRequest(ErrorDto.Of("URL 不允许携带账号密码"));
Shell.OpenUrl(url!);
return Results.Ok(new LaunchResultDto(true, "已打开链接"));
@@ -450,7 +464,8 @@ app.Run();
static int ResolvePort(string[] args)
{
var env = Environment.GetEnvironmentVariable("GC_UI_PORT");
// 优先用启动器传来的端口(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++)
@@ -465,7 +480,7 @@ static int ResolvePort(string[] args)
return inline;
}
return 17890;
return GcUiContract.DefaultPort;
}
static void WriteEndpointFile(AppServices services, int port)
@@ -491,8 +506,18 @@ static void WriteEndpointFile(AppServices services, int port)
}
}
ModelDto ToModelDto(ModelPackage package) => new(
package.Id,
/// <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,
@@ -565,10 +590,10 @@ ModelSource? ResolveSource(string? sourceId)
IResult ActOnJob(string id, Action<IDownloadJob> action)
{
if (!IsSafeId(id)) return Results.BadRequest(new LaunchResultDto(false, "任务标识无效"));
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(new LaunchResultDto(false, $"没有找到任务 {id}"));
if (job == null) return Results.NotFound(ErrorDto.Of($"没有找到任务 {id}"));
action(job);
return Results.Ok(ToJobDto(job));
+3
View File
@@ -15,6 +15,9 @@ migration:
- platform: root
create_revision: dec2ee5c1f98f8e84a7d5380c05eb8a3d0a81668
base_revision: dec2ee5c1f98f8e84a7d5380c05eb8a3d0a81668
- platform: linux
create_revision: dec2ee5c1f98f8e84a7d5380c05eb8a3d0a81668
base_revision: dec2ee5c1f98f8e84a7d5380c05eb8a3d0a81668
- platform: macos
create_revision: dec2ee5c1f98f8e84a7d5380c05eb8a3d0a81668
base_revision: dec2ee5c1f98f8e84a7d5380c05eb8a3d0a81668
+59 -9
View File
@@ -1,4 +1,5 @@
import 'dart:convert';
import 'dart:io';
import 'package:http/http.dart' as http;
@@ -334,16 +335,65 @@ List<String> _stringList(dynamic value) =>
/// GC-UI 后端客户端。
///
/// 后端是本地伴随进程,默认监听 127.0.0.1:17890;端口可用
/// `--dart-define=GC_UI_BASE_URL=http://127.0.0.1:12345` 覆盖。
/// 后端是本地伴随进程,端口由启动器(GC-BOOT)选定后通过 `GC_UI_PORT`
/// 环境变量传进来 —— 这样端口被占用时换端口不用重新编译前端。
/// 也可用 `--dart-define=GC_UI_BASE_URL=http://127.0.0.1:12345` 强制指定。
class GcApi {
GcApi({String? baseUrl})
: baseUrl = baseUrl ?? defaultBaseUrl;
static const String defaultBaseUrl = String.fromEnvironment(
'GC_UI_BASE_URL',
defaultValue: 'http://127.0.0.1:17890',
);
/// 复用同一个 HTTP 连接:轮询(下载任务每秒一次)时每次都新建连接
/// 会不断握手,桌面端也能明显看到延迟抖动。
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;
@@ -357,17 +407,17 @@ class GcApi {
try {
switch (method) {
case 'GET':
response = await http.get(uri).timeout(const Duration(seconds: 30));
response = await _client.get(uri).timeout(const Duration(seconds: 30));
break;
case 'POST':
response = await http
response = await _client
.post(uri,
headers: const {'Content-Type': 'application/json'},
body: body == null ? null : jsonEncode(body))
.timeout(const Duration(seconds: 120));
break;
case 'DELETE':
response = await http.delete(uri).timeout(const Duration(seconds: 30));
response = await _client.delete(uri).timeout(const Duration(seconds: 30));
break;
default:
throw ApiException('不支持的方法 $method');
+74 -10
View File
@@ -1,3 +1,5 @@
import 'dart:async';
import 'package:flutter/foundation.dart';
import 'api_client.dart';
@@ -24,26 +26,75 @@ class ShellController extends ChangeNotifier {
String updateDetail = '';
String launcherNotice = '';
/// 模型库版本号:安装 / 删除 / 下载完成后自增,首页据此重新拉列表。
///
/// 首页被 `Offstage` 保活,切走再切回不会重建;没有这个信号时,
/// 下载完模型回到首页仍然显示旧的空列表。
int modelsRevision = 0;
Timer? _retryTimer;
int _retryAttempt = 0;
bool get backendReady => settings != null;
Future<void> bootstrap() async {
try {
// 健康检查与设置并行请求:两者互不依赖,串行会白白多等一次网络往返。
final healthFuture = api.health();
final settingsFuture = api.settings();
health = await healthFuture;
settings = await settingsFuture;
loadError = null;
_applySettings(settings!);
} catch (error) {
loadError = error.toString();
_retryTimer?.cancel();
HealthInfo? healthResult;
SettingsInfo? settingsResult;
Object? firstError;
// 两个请求互不依赖,并行发;各自捕获异常,避免一方失败时
// 另一个的 Future 抛成未处理异常(Flutter 会在控制台打出恶性警告)。
await Future.wait<void>(<Future<void>>[
() 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();
}
/// 后端没起来时自动重试(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) {
I18n.setLanguage(value.language);
GcPalette.apply(value.accentColor);
GcPalette.applyTheme(value.theme);
}
void goTo(int value) {
@@ -52,6 +103,12 @@ class ShellController extends ChangeNotifier {
notifyListeners();
}
/// 模型库有变化(安装 / 删除 / 下载完成):通知首页刷新。
void modelsChanged() {
modelsRevision++;
notifyListeners();
}
Future<void> reloadSettings() async {
try {
settings = await api.settings();
@@ -112,6 +169,7 @@ class ShellController extends ChangeNotifier {
detail: result.error ?? '',
notice: result.launcherMessage ?? '',
);
if (result.updatedModels > 0) modelsChanged();
} catch (error) {
setUpdateStatus(
busy: false,
@@ -120,4 +178,10 @@ class ShellController extends ChangeNotifier {
);
}
}
@override
void dispose() {
_retryTimer?.cancel();
super.dispose();
}
}
+10
View File
@@ -64,6 +64,11 @@ class I18n {
'set.subtitle': '模型源、启动时内存分配与本地存储。',
'set.general': '通用',
'set.appearance': '外观',
'set.theme': '主题模式',
'set.theme.desc': '深色、浅色,或跟随系统设置。',
'set.theme.dark': '深色',
'set.theme.light': '浅色',
'set.theme.system': '跟随系统',
'set.accent': '主题颜色',
'set.accent.desc': '选择启动器的主色调,按钮、滑块与高亮会同步换色。',
'set.accent.custom': '自定义颜色',
@@ -189,6 +194,11 @@ class I18n {
'set.subtitle': 'Model sources, startup memory allocation and local storage.',
'set.general': 'General',
'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.desc': 'Pick the launcher accent color; buttons, sliders and highlights follow it.',
'set.accent.custom': 'Custom color',
+24 -7
View File
@@ -12,7 +12,7 @@ void main() {
runApp(const GcUiApp());
}
/// GC-UI 前端:Flutter 桌面应用(Windows / macOS)。
/// GC-UI 前端:Flutter 桌面应用(Windows / macOS / Linux)。
///
/// 界面全部在这里;模型扫描、下载、更新、设置、模型窗口宿主都在后端
/// (GC-UI/backend/GC.UI.Server,本地 HTTP 服务)。
@@ -28,7 +28,7 @@ class _GcUiAppState extends State<GcUiApp> {
@override
Widget build(BuildContext context) {
// 语言与强调色都会触发重建:只重建 MaterialApp 的主题层,
// 语言、强调色、主题模式都会触发重建:只重建 MaterialApp 的主题层,
// 不触碰页面状态(页面由 ShellPage 自己持有)。
return ValueListenableBuilder<String>(
valueListenable: I18n.language,
@@ -36,11 +36,28 @@ class _GcUiAppState extends State<GcUiApp> {
return ValueListenableBuilder<Color>(
valueListenable: GcPalette.accent,
builder: (context, accent, _) {
return MaterialApp(
title: 'Morris GC',
debugShowCheckedModeBanner: false,
theme: buildGcTheme(),
home: ShellPage(controller: _controller),
return ValueListenableBuilder<ThemeMode>(
valueListenable: GcPalette.mode,
builder: (context, mode, _) {
return MaterialApp(
title: 'Morris GC',
debugShowCheckedModeBanner: false,
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),
);
},
);
},
);
+148 -49
View File
@@ -28,10 +28,14 @@ class _HomePageViewState extends State<HomePageView> {
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;
@@ -41,6 +45,22 @@ class _HomePageViewState extends State<HomePageView> {
}
}
@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;
@@ -128,7 +148,7 @@ class _HomePageViewState extends State<HomePageView> {
Expanded(
child: Text(
T('home.installed'),
style: const TextStyle(
style: TextStyle(
fontSize: 15,
fontWeight: FontWeight.w600,
color: GcColors.ink,
@@ -151,7 +171,7 @@ class _HomePageViewState extends State<HomePageView> {
padding: const EdgeInsets.all(12),
child: Text(
_notice!,
style: const TextStyle(fontSize: 12, color: GcColors.warn),
style: TextStyle(fontSize: 12, color: GcColors.warn),
),
),
],
@@ -167,7 +187,7 @@ class _HomePageViewState extends State<HomePageView> {
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(T('common.error'),
style: const TextStyle(color: GcColors.danger)),
style: TextStyle(color: GcColors.danger)),
const SizedBox(height: 8),
GcHint(_error!),
],
@@ -314,7 +334,7 @@ class _HomePageViewState extends State<HomePageView> {
children: <Widget>[
Text(
T('home.empty'),
style: const TextStyle(
style: TextStyle(
fontSize: 15,
fontWeight: FontWeight.w600,
color: GcColors.ink,
@@ -326,7 +346,7 @@ class _HomePageViewState extends State<HomePageView> {
child: Text(
T('home.emptyHint'),
textAlign: TextAlign.center,
style: const TextStyle(
style: TextStyle(
fontSize: 12,
color: GcColors.faint,
height: 1.5,
@@ -488,7 +508,7 @@ class _ModelCardState extends State<_ModelCard> {
child: Text(
model.name,
overflow: TextOverflow.ellipsis,
style: const TextStyle(
style: TextStyle(
fontSize: 14.5,
fontWeight: FontWeight.w700,
color: GcColors.ink,
@@ -498,7 +518,7 @@ class _ModelCardState extends State<_ModelCard> {
const SizedBox(width: 8),
Text(
model.sizeText,
style: const TextStyle(
style: TextStyle(
fontSize: 10.5,
color: GcColors.faint,
),
@@ -664,6 +684,12 @@ class _DownloadPageViewState extends State<DownloadPageView> {
String? _error;
Timer? _poll;
/// 页面是否可见(被切走后仍保活,但没必要继续请求后端)。
bool _visible = true;
/// 上一次轮询时是否有活跃任务,用来判断「刚刚全部结束」。
bool _hadActive = false;
@override
void initState() {
super.initState();
@@ -677,7 +703,14 @@ class _DownloadPageViewState extends State<DownloadPageView> {
return;
}
_load();
_poll = Timer.periodic(const Duration(seconds: 1), (_) => _refreshJobs());
_schedulePoll(const Duration(seconds: 2));
}
@override
void didChangeDependencies() {
super.didChangeDependencies();
// TickerMode 由外壳的 Offstage 控制:切到别的页时变 false。
_visible = TickerMode.of(context);
}
@override
@@ -686,6 +719,35 @@ class _DownloadPageViewState extends State<DownloadPageView> {
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;
@@ -818,7 +880,7 @@ class _DownloadPageViewState extends State<DownloadPageView> {
Expanded(
child: Text(
source.name,
style: const TextStyle(
style: TextStyle(
fontSize: 12.5,
fontWeight: FontWeight.w600,
color: GcColors.ink,
@@ -826,7 +888,7 @@ class _DownloadPageViewState extends State<DownloadPageView> {
),
),
if (!source.enabled)
const Text(
Text(
'off',
style: TextStyle(
fontSize: 10, color: GcColors.faint),
@@ -836,7 +898,7 @@ class _DownloadPageViewState extends State<DownloadPageView> {
const SizedBox(height: 2),
Text(
source.host,
style: const TextStyle(
style: TextStyle(
fontSize: 10.5, color: GcColors.faint),
),
],
@@ -867,7 +929,7 @@ class _DownloadPageViewState extends State<DownloadPageView> {
Expanded(
child: Text(
T('dl.available'),
style: const TextStyle(
style: TextStyle(
fontSize: 15,
fontWeight: FontWeight.w600,
color: GcColors.ink,
@@ -896,7 +958,7 @@ class _DownloadPageViewState extends State<DownloadPageView> {
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(T('common.error'),
style: const TextStyle(color: GcColors.danger)),
style: TextStyle(color: GcColors.danger)),
const SizedBox(height: 8),
GcHint(_error!),
],
@@ -908,7 +970,7 @@ class _DownloadPageViewState extends State<DownloadPageView> {
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(T('dl.empty'),
style: const TextStyle(color: GcColors.ink)),
style: TextStyle(color: GcColors.ink)),
const SizedBox(height: 8),
GcHint(T('dl.emptyHint')),
],
@@ -930,7 +992,7 @@ class _DownloadPageViewState extends State<DownloadPageView> {
children: <Widget>[
Text(
model.name,
style: const TextStyle(
style: TextStyle(
fontSize: 13,
fontWeight: FontWeight.w600,
color: GcColors.ink,
@@ -939,7 +1001,7 @@ class _DownloadPageViewState extends State<DownloadPageView> {
const SizedBox(width: 8),
Text(
'v${model.version} · ${model.sizeText}',
style: const TextStyle(
style: TextStyle(
fontSize: 10.5,
color: GcColors.faint),
),
@@ -956,7 +1018,7 @@ class _DownloadPageViewState extends State<DownloadPageView> {
),
child: Text(
T('dl.installed'),
style: const TextStyle(
style: TextStyle(
fontSize: 10,
color: GcColors.ok),
),
@@ -969,7 +1031,7 @@ class _DownloadPageViewState extends State<DownloadPageView> {
model.description,
maxLines: 2,
overflow: TextOverflow.ellipsis,
style: const TextStyle(
style: TextStyle(
fontSize: 11.5,
color: GcColors.muted,
height: 1.4,
@@ -1032,7 +1094,7 @@ class _DownloadPageViewState extends State<DownloadPageView> {
Expanded(
child: Text(
'${job.name} v${job.version}',
style: const TextStyle(
style: TextStyle(
fontSize: 12.5,
fontWeight: FontWeight.w600,
color: GcColors.ink,
@@ -1079,7 +1141,7 @@ class _DownloadPageViewState extends State<DownloadPageView> {
const SizedBox(height: 4),
Text(
job.error ?? job.detailText,
style: const TextStyle(
style: TextStyle(
fontSize: 10.5, color: GcColors.faint),
),
],
@@ -1127,7 +1189,11 @@ class _SettingsPageViewState extends State<SettingsPageView> {
int _fps = 120;
bool _autoUpdate = true;
String _language = 'auto';
bool _synced = false;
ThemeMode _themeMode = ThemeMode.dark;
/// 上一次同步所用的设置对象。以前用的是 `bool _synced` —— 只同步一次,
/// 之后外部(更新状态条、其它页面)改了设置,本页仍显示旧值。
SettingsInfo? _syncedFrom;
String? _status;
@override
@@ -1137,13 +1203,14 @@ class _SettingsPageViewState extends State<SettingsPageView> {
}
void _syncFrom(SettingsInfo settings) {
if (_synced) return;
if (identical(_syncedFrom, settings)) return;
_syncedFrom = settings;
_memory = settings.memoryMb.toDouble();
_memoryAuto = settings.memoryAuto;
_fps = settings.renderFps;
_autoUpdate = settings.autoUpdateOnStartup;
_language = settings.language;
_synced = true;
_themeMode = GcPalette.parseMode(settings.theme);
}
@override
@@ -1159,7 +1226,7 @@ class _SettingsPageViewState extends State<SettingsPageView> {
children: <Widget>[
Text(
T('set.title'),
style: const TextStyle(
style: TextStyle(
fontSize: 20,
fontWeight: FontWeight.w700,
color: GcColors.ink,
@@ -1199,7 +1266,7 @@ class _SettingsPageViewState extends State<SettingsPageView> {
Row(
children: <Widget>[
SizedBox(width: 160, child: Text(T('set.language'),
style: const TextStyle(fontSize: 12.5, color: GcColors.muted))),
style: TextStyle(fontSize: 12.5, color: GcColors.muted))),
DropdownButton<String>(
value: _language,
dropdownColor: GcColors.surfaceAlt,
@@ -1228,7 +1295,7 @@ class _SettingsPageViewState extends State<SettingsPageView> {
Row(
children: <Widget>[
SizedBox(width: 160, child: Text(T('set.fps'),
style: const TextStyle(fontSize: 12.5, color: GcColors.muted))),
style: TextStyle(fontSize: 12.5, color: GcColors.muted))),
Expanded(
child: Slider(
value: _fps.toDouble(),
@@ -1247,7 +1314,7 @@ class _SettingsPageViewState extends State<SettingsPageView> {
SizedBox(
width: 46,
child: Text('$_fps',
style: const TextStyle(
style: TextStyle(
fontSize: 12.5, color: GcColors.ink)),
),
],
@@ -1267,6 +1334,38 @@ class _SettingsPageViewState extends State<SettingsPageView> {
children: <Widget>[
GcSectionTitle(T('set.appearance')),
const SizedBox(height: 8),
GcHint(T('set.theme.desc')),
const SizedBox(height: 10),
SegmentedButton<ThemeMode>(
segments: <ButtonSegment<ThemeMode>>[
ButtonSegment<ThemeMode>(
value: ThemeMode.dark,
label: Text(T('set.theme.dark')),
icon: const Icon(Icons.dark_mode_outlined, size: 15),
),
ButtonSegment<ThemeMode>(
value: ThemeMode.light,
label: Text(T('set.theme.light')),
icon: const Icon(Icons.light_mode_outlined, size: 15),
),
ButtonSegment<ThemeMode>(
value: ThemeMode.system,
label: Text(T('set.theme.system')),
icon: const Icon(Icons.brightness_auto_outlined, size: 15),
),
],
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: 16),
GcHint(T('set.accent.desc')),
const SizedBox(height: 14),
Wrap(
@@ -1281,7 +1380,7 @@ class _SettingsPageViewState extends State<SettingsPageView> {
const SizedBox(height: 12),
Text(
'${T('set.accent')}: ${GcPalette.toHex(current)}',
style: const TextStyle(fontSize: 11.5, color: GcColors.faint),
style: TextStyle(fontSize: 11.5, color: GcColors.faint),
),
],
),
@@ -1337,12 +1436,12 @@ class _SettingsPageViewState extends State<SettingsPageView> {
child: Row(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
const Icon(Icons.colorize_rounded,
Icon(Icons.colorize_rounded,
size: 16, color: GcColors.faint),
const SizedBox(width: 6),
Text(
T('set.accent.custom'),
style: const TextStyle(fontSize: 11.5, color: GcColors.muted),
style: TextStyle(fontSize: 11.5, color: GcColors.muted),
),
],
),
@@ -1363,12 +1462,12 @@ class _SettingsPageViewState extends State<SettingsPageView> {
content: TextField(
controller: controller,
autofocus: true,
style: const TextStyle(color: GcColors.ink),
style: TextStyle(color: GcColors.ink),
decoration: InputDecoration(
hintText: '#8FB6FF',
hintStyle: const TextStyle(color: GcColors.faint),
hintStyle: TextStyle(color: GcColors.faint),
helperText: T('set.accent.hexHint'),
helperStyle: const TextStyle(color: GcColors.faint, fontSize: 11),
helperStyle: TextStyle(color: GcColors.faint, fontSize: 11),
),
onSubmitted: (value) => Navigator.of(context).pop(value),
),
@@ -1424,7 +1523,7 @@ class _SettingsPageViewState extends State<SettingsPageView> {
Expanded(
child: Text(
T('set.memory.auto'),
style: const TextStyle(fontSize: 12.5, color: GcColors.muted),
style: TextStyle(fontSize: 12.5, color: GcColors.muted),
),
),
],
@@ -1453,7 +1552,7 @@ class _SettingsPageViewState extends State<SettingsPageView> {
width: 96,
child: Text(
'${_memory.round()} MB',
style: const TextStyle(fontSize: 12.5, color: GcColors.ink),
style: TextStyle(fontSize: 12.5, color: GcColors.ink),
),
),
],
@@ -1463,7 +1562,7 @@ class _SettingsPageViewState extends State<SettingsPageView> {
children: <Widget>[
Text(
'${T('set.memory.current')}: ${settings.memoryUsageText}',
style: const TextStyle(fontSize: 11.5, color: GcColors.faint),
style: TextStyle(fontSize: 11.5, color: GcColors.faint),
),
],
),
@@ -1494,7 +1593,7 @@ class _SettingsPageViewState extends State<SettingsPageView> {
children: <Widget>[
Text(
source.name,
style: const TextStyle(
style: TextStyle(
fontSize: 12.5,
fontWeight: FontWeight.w600,
color: GcColors.ink,
@@ -1503,7 +1602,7 @@ class _SettingsPageViewState extends State<SettingsPageView> {
const SizedBox(height: 2),
Text(
source.url,
style: const TextStyle(
style: TextStyle(
fontSize: 10.5, color: GcColors.faint),
),
],
@@ -1511,7 +1610,7 @@ class _SettingsPageViewState extends State<SettingsPageView> {
),
Text(
source.enabled ? T('set.sourceEnabled') : '—',
style: const TextStyle(fontSize: 11, color: GcColors.faint),
style: TextStyle(fontSize: 11, color: GcColors.faint),
),
],
),
@@ -1566,12 +1665,12 @@ class _SettingsPageViewState extends State<SettingsPageView> {
SizedBox(
width: 160,
child: Text(label,
style: const TextStyle(fontSize: 12.5, color: GcColors.muted)),
style: TextStyle(fontSize: 12.5, color: GcColors.muted)),
),
Expanded(
child: SelectableText(
value,
style: const TextStyle(fontSize: 11.5, color: GcColors.faint),
style: TextStyle(fontSize: 11.5, color: GcColors.faint),
),
),
],
@@ -1601,7 +1700,7 @@ class _SettingsPageViewState extends State<SettingsPageView> {
Expanded(
child: Text(
T('update.auto'),
style: const TextStyle(fontSize: 12.5, color: GcColors.muted),
style: TextStyle(fontSize: 12.5, color: GcColors.muted),
),
),
],
@@ -1709,7 +1808,7 @@ class _AboutPageViewState extends State<AboutPageView> {
children: <Widget>[
Text(
T('nav.about'),
style: const TextStyle(
style: TextStyle(
fontSize: 20,
fontWeight: FontWeight.w700,
color: GcColors.ink,
@@ -1727,7 +1826,7 @@ class _AboutPageViewState extends State<AboutPageView> {
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(T('common.error'),
style: const TextStyle(color: GcColors.danger)),
style: TextStyle(color: GcColors.danger)),
const SizedBox(height: 8),
GcHint(_error!),
const SizedBox(height: 12),
@@ -1745,7 +1844,7 @@ class _AboutPageViewState extends State<AboutPageView> {
children: <Widget>[
Text(
_about?.appName ?? 'Morris GC',
style: const TextStyle(
style: TextStyle(
fontSize: 18,
fontWeight: FontWeight.w700,
color: GcColors.ink,
@@ -1815,7 +1914,7 @@ class _AboutPageViewState extends State<AboutPageView> {
Expanded(
child: Text(
contributor.name,
style: const TextStyle(
style: TextStyle(
fontSize: 12.5,
fontWeight: FontWeight.w600,
color: GcColors.ink,
@@ -1825,7 +1924,7 @@ class _AboutPageViewState extends State<AboutPageView> {
Text(
T('about.contributions',
<Object?>[contributor.contributions]),
style: const TextStyle(
style: TextStyle(
fontSize: 11, color: GcColors.faint),
),
],
@@ -1846,12 +1945,12 @@ class _AboutPageViewState extends State<AboutPageView> {
SizedBox(
width: 160,
child: Text(label,
style: const TextStyle(fontSize: 12.5, color: GcColors.muted)),
style: TextStyle(fontSize: 12.5, color: GcColors.muted)),
),
Expanded(
child: SelectableText(
value,
style: const TextStyle(fontSize: 12, color: GcColors.ink),
style: TextStyle(fontSize: 12, color: GcColors.ink),
),
),
],
+8 -8
View File
@@ -140,13 +140,13 @@ class _Sidebar extends StatelessWidget {
borderRadius: BorderRadius.circular(8),
),
alignment: Alignment.center,
child: const Text(
child: Text(
'◎',
style: TextStyle(fontSize: 14, color: GcColors.accent),
),
),
const SizedBox(width: 10),
const Expanded(
Expanded(
child: Text(
'Morris GC',
style: TextStyle(
@@ -186,7 +186,7 @@ class _Sidebar extends StatelessWidget {
padding: const EdgeInsets.only(left: 14),
child: Text(
'v${settings?.version ?? '—'}',
style: const TextStyle(fontSize: 10.5, color: GcColors.faint),
style: TextStyle(fontSize: 10.5, color: GcColors.faint),
),
),
Padding(
@@ -258,7 +258,7 @@ class _UpdateBar extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Container(
decoration: const BoxDecoration(
decoration: BoxDecoration(
color: GcColors.surface,
border: Border(top: BorderSide(color: GcColors.line)),
),
@@ -274,7 +274,7 @@ class _UpdateBar extends StatelessWidget {
children: <Widget>[
Text(
controller.updateStatus,
style: const TextStyle(
style: TextStyle(
fontSize: 12.5,
fontWeight: FontWeight.w600,
color: GcColors.ink,
@@ -284,13 +284,13 @@ class _UpdateBar extends StatelessWidget {
if (controller.updateDetail.isNotEmpty)
Text(
controller.updateDetail,
style: const TextStyle(fontSize: 11, color: GcColors.faint),
style: TextStyle(fontSize: 11, color: GcColors.faint),
overflow: TextOverflow.ellipsis,
),
if (controller.launcherNotice.isNotEmpty)
Text(
controller.launcherNotice,
style: const TextStyle(fontSize: 11, color: GcColors.warn),
style: TextStyle(fontSize: 11, color: GcColors.warn),
),
],
),
@@ -331,7 +331,7 @@ class _BackendDown extends StatelessWidget {
children: <Widget>[
Text(
T('common.error'),
style: const TextStyle(
style: TextStyle(
fontSize: 17,
fontWeight: FontWeight.w600,
color: GcColors.ink,
+113 -41
View File
@@ -1,9 +1,9 @@
import 'package:flutter/material.dart';
/// 主题强调色(可在设置页自定义,并持久化到后端 settings.accentColor)。
/// 主题偏好(可在设置页切换,并持久化到后端 settings.theme)。
///
/// 用 [ValueNotifier] 持有当前颜色:设置页改色后,`main.dart` 监听到变化
/// 会重建 `MaterialApp.theme`,所有引用 [GcColors.accent] 的组件随之换色。
/// 支持深色 / 浅色 / 跟随系统三种;[mode] 变化会让 `main.dart` 重建
/// `MaterialApp`,`themeMode` 交给 Flutter 决定实际亮度。
class GcPalette {
GcPalette._();
@@ -13,6 +13,9 @@ class GcPalette {
static final ValueNotifier<Color> accent =
ValueNotifier<Color>(defaultAccent);
/// 当前主题模式(dark / light / system)。
static final ValueNotifier<ThemeMode> mode = ValueNotifier<ThemeMode>(ThemeMode.dark);
/// 设置页可选的预设色板。
static const List<Color> presets = <Color>[
Color(0xFF8FB6FF), // 极光蓝(默认)
@@ -25,6 +28,37 @@ class GcPalette {
Color(0xFFB0BEC5), // 石墨灰
];
/// 把后端设置里的 `theme` 字符串转成 [ThemeMode](未知值按深色处理)。
static ThemeMode parseMode(String? value) {
switch ((value ?? '').trim().toLowerCase()) {
case 'light':
return ThemeMode.light;
case 'system':
return ThemeMode.system;
case 'dark':
default:
return ThemeMode.dark;
}
}
/// 把 [ThemeMode] 转回后端设置的字符串。
static String modeToName(ThemeMode value) {
switch (value) {
case ThemeMode.light:
return 'light';
case ThemeMode.system:
return 'system';
case ThemeMode.dark:
return 'dark';
}
}
/// 应用主题模式(来自后端设置)。
static void applyTheme(String? value) {
final next = parseMode(value);
if (mode.value != next) mode.value = next;
}
/// 把 `#RRGGBB` / `RRGGBB` 解析为颜色;非法返回 null。
static Color? parseHex(String? value) {
if (value == null) return null;
@@ -53,86 +87,124 @@ class GcPalette {
}
}
/// 与 Avalonia 启动器一致的深色配色。
/// 配色:浅色 / 深色两套,按当前 [Brightness] 取值。
///
/// 以前这里是 const 常量,主题只能是深色 —— 设置里的 `theme` 字段写了也没人读。
/// 改成 getter 后,所有引用点自动跟随主题;代价是不能再放进 const 上下文。
class GcColors {
GcColors._();
static const Color appBg = Color(0xFF0A1226);
static const Color sideBg = Color(0xFF0C1529);
static const Color surface = Color(0xFF111C33);
static const Color surfaceAlt = Color(0xFF16233C);
static const Color line = Color(0xFF1B2740);
static const Color ink = Color(0xFFF2F6FF);
static const Color muted = Color(0xFFA9B8D4);
static const Color faint = Color(0xFF7C90B4);
static const Color warn = Color(0xFFFFC46B);
static const Color danger = Color(0xFFFF7A7A);
static const Color ok = Color(0xFF6BE3A2);
static bool _dark = true;
static bool get isDark => _dark;
/// 由 `MaterialApp.builder` 在每次构建前按实际亮度绑定。
static void bind(Brightness brightness) => _dark = brightness == Brightness.dark;
static Color _pick(int dark, int light) => Color(_dark ? dark : light);
static Color get appBg => _pick(0xFF0A1226, 0xFFF3F6FB);
static Color get sideBg => _pick(0xFF0C1529, 0xFFFFFFFF);
static Color get surface => _pick(0xFF111C33, 0xFFFFFFFF);
static Color get surfaceAlt => _pick(0xFF16233C, 0xFFE9EFFA);
static Color get line => _pick(0xFF1B2740, 0xFFD8E2F2);
static Color get ink => _pick(0xFFF2F6FF, 0xFF0F1B2D);
static Color get muted => _pick(0xFFA9B8D4, 0xFF46587A);
static Color get faint => _pick(0xFF7C90B4, 0xFF7286A6);
static Color get warn => _pick(0xFFFFC46B, 0xFFB26A00);
static Color get danger => _pick(0xFFFF7A7A, 0xFFC0392B);
static Color get ok => _pick(0xFF6BE3A2, 0xFF1E8E5A);
/// 侧栏「MENU」一类最弱的说明文字。
static Color get ghost => _pick(0xFF4C5F80, 0xFF97A8C4);
/// 当前强调色(动态,跟随设置)。
static Color get accent => GcPalette.accent.value;
/// 强调色的加深版本,用于主按钮 / 轨道。
/// 强调色的加深版本,用于主按钮 / 轨道。浅色主题下需要反向调整,
/// 否则强调色在浅背景上对比度不足。
static Color get accentStrong => _strongen(accent);
static Color _strongen(Color color) {
final hsl = HSLColor.fromColor(color);
final lightness = _dark ? hsl.lightness - 0.10 : hsl.lightness - 0.22;
return hsl
.withSaturation((hsl.saturation + 0.12).clamp(0.0, 1.0))
.withLightness((hsl.lightness - 0.10).clamp(0.0, 1.0))
.withLightness(lightness.clamp(0.0, 1.0))
.toColor();
}
}
ThemeData buildGcTheme() {
final base = ThemeData.dark(useMaterial3: true);
final accent = GcColors.accent;
final accentStrong = GcColors.accentStrong;
/// 按指定亮度构建主题。
///
/// 注意:不要在这里改 [GcColors] 的全局状态 —— MaterialApp 会同时构建
/// theme 与 darkTheme,后构建的那个会把状态写脏。亮度绑定由 `main.dart`
/// 的 builder 统一完成。
ThemeData buildGcTheme(Brightness brightness) {
final isDark = brightness == Brightness.dark;
final base = isDark
? ThemeData.dark(useMaterial3: true)
: ThemeData.light(useMaterial3: true);
Color pick(int dark, int light) => Color(isDark ? dark : light);
final appBg = pick(0xFF0A1226, 0xFFF3F6FB);
final surface = pick(0xFF111C33, 0xFFFFFFFF);
final surfaceAlt = pick(0xFF16233C, 0xFFE9EFFA);
final line = pick(0xFF1B2740, 0xFFD8E2F2);
final ink = pick(0xFFF2F6FF, 0xFF0F1B2D);
final danger = pick(0xFFFF7A7A, 0xFFC0392B);
final accent = GcPalette.accent.value;
final hsl = HSLColor.fromColor(accent);
final accentStrong = hsl
.withSaturation((hsl.saturation + 0.12).clamp(0.0, 1.0))
.withLightness((hsl.lightness - (isDark ? 0.10 : 0.22)).clamp(0.0, 1.0))
.toColor();
return base.copyWith(
scaffoldBackgroundColor: GcColors.appBg,
scaffoldBackgroundColor: appBg,
colorScheme: base.colorScheme.copyWith(
brightness: brightness,
primary: accentStrong,
secondary: accent,
surface: GcColors.surface,
error: GcColors.danger,
surface: surface,
error: danger,
),
textTheme: base.textTheme.apply(
bodyColor: GcColors.ink,
displayColor: GcColors.ink,
bodyColor: ink,
displayColor: ink,
),
dividerColor: GcColors.line,
cardTheme: const CardTheme(
color: GcColors.surface,
dividerColor: line,
cardTheme: CardTheme(
color: surface,
elevation: 0,
margin: EdgeInsets.zero,
),
sliderTheme: base.sliderTheme.copyWith(
activeTrackColor: accentStrong,
thumbColor: accent,
inactiveTrackColor: GcColors.line,
inactiveTrackColor: line,
),
switchTheme: SwitchThemeData(
thumbColor: WidgetStateProperty.resolveWith(
(states) => states.contains(WidgetState.selected)
? accent
: GcColors.faint,
(states) => states.contains(WidgetState.selected) ? accent : GcColors.faint,
),
trackColor: WidgetStateProperty.resolveWith(
(states) => states.contains(WidgetState.selected)
? accentStrong.withOpacity(0.45)
: GcColors.line,
: line,
),
),
progressIndicatorTheme: ProgressIndicatorThemeData(
color: accent,
linearTrackColor: GcColors.line,
linearTrackColor: line,
),
tooltipTheme: const TooltipThemeData(
tooltipTheme: TooltipThemeData(
decoration: BoxDecoration(
color: GcColors.surfaceAlt,
borderRadius: BorderRadius.all(Radius.circular(6)),
color: surfaceAlt,
borderRadius: const BorderRadius.all(Radius.circular(6)),
),
textStyle: TextStyle(color: GcColors.ink, fontSize: 12),
textStyle: TextStyle(color: ink, fontSize: 12),
),
);
}
@@ -174,7 +246,7 @@ class GcSectionTitle extends StatelessWidget {
Expanded(
child: Text(
text,
style: const TextStyle(
style: TextStyle(
fontSize: 15,
fontWeight: FontWeight.w600,
color: GcColors.ink,
@@ -196,6 +268,6 @@ class GcHint extends StatelessWidget {
@override
Widget build(BuildContext context) => Text(
text,
style: const TextStyle(fontSize: 12, color: GcColors.faint, height: 1.5),
style: TextStyle(fontSize: 12, color: GcColors.faint, height: 1.5),
);
}
+1
View File
@@ -0,0 +1 @@
flutter/ephemeral
+146
View File
@@ -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}
)
+6
View File
@@ -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);
}
+124
View File
@@ -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));
}
+18
View File
@@ -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_
+1 -1
View File
@@ -73,7 +73,7 @@ void main() {
testWidgets('renders a card with its child', (tester) async {
await tester.pumpWidget(
MaterialApp(
theme: buildGcTheme(),
theme: buildGcTheme(Brightness.dark),
home: const Scaffold(
body: GcCard(child: Text('hello')),
),
+27 -3
View File
@@ -123,17 +123,21 @@ void main() {
'uiAvailable': true,
});
Future<void> shoot(WidgetTester tester, String name, Widget page) async {
Future<void> shoot(WidgetTester tester, String name, Widget page,
{Brightness brightness = Brightness.dark}) async {
tester.view.physicalSize = const Size(1280, 820);
tester.view.devicePixelRatio = 1.0;
addTearDown(tester.view.reset);
// GcColors 是静态取值,截图前先按目标亮度绑定,否则浅色截图仍是深色配色。
GcColors.bind(brightness);
final key = GlobalKey();
await tester.pumpWidget(
MaterialApp(
debugShowCheckedModeBanner: false,
theme: buildGcTheme().copyWith(
textTheme: buildGcTheme().textTheme.apply(
theme: buildGcTheme(brightness).copyWith(
textTheme: buildGcTheme(brightness).textTheme.apply(
fontFamily: 'Noto Sans CJK SC',
),
),
@@ -290,4 +294,24 @@ void main() {
I18n.language.value = 'zh-CN';
await shoot(tester, 'shell', ShellPage(controller: sampleController()));
});
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,
);
});
}
+11 -2
View File
@@ -20,12 +20,21 @@ public static class SignatureKeyring
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(
"gc-2026-11",
"MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEny5YKVBZUzOyRcSiuutlGmBb4+xm" +
"PrNDGshilBlpmFyWu5Atq+FGP2tn+8Or8V7OH+/7lhCmXu8jZuC5/5CWSw==",
"GC 主发布密钥")
"已停用:私钥遗失")
};
static SignatureKeyring() => LoadFromEnvironment();
+27 -1
View File
@@ -115,7 +115,6 @@ public static class DownloadModuleHost
public static class LauncherRuntimeInfo
{
private static string? _versionOverride;
public static string CurrentLauncherVersion
{
get
@@ -155,3 +154,30 @@ public static class LauncherRuntimeInfo
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;
}
}
+68 -3
View File
@@ -9,10 +9,26 @@ namespace GC.Services;
/// <summary>
/// 本地模型库。启动器只**扫描 / 删除**模型包,不再解析或缓存任何场景数据 ——
/// 场景、贴图、界面都由模型自己的程序集负责。
///
/// 扫描结果与目录体积都做短时缓存:前端(首页 / 下载页)会频繁轮询
/// <c>/api/models</c>,而每个模型的体积要递归遍历整棵目录。没有缓存时
/// 一次刷新就是成千上万次 stat,低配机器上会明显卡顿。
/// </summary>
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 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;
@@ -20,7 +36,13 @@ public sealed class ModelRepository
public IReadOnlyList<ModelPackage> Scan()
{
lock (_gate)
{
if (_cache != null && DateTime.UtcNow - _cacheAt < ScanTtl) return _cache;
}
_paths.WaitForDevelopmentModels();
var result = new List<ModelPackage>();
foreach (var (manifest, dir) in ModelScanner.Scan(_paths.ModelRoot))
{
@@ -28,13 +50,20 @@ public sealed class ModelRepository
{
Manifest = manifest,
Directory = dir,
SizeBytes = ModelScanner.DirectorySize(dir)
SizeBytes = SizeOf(dir)
});
}
lock (_gate)
{
_cache = result;
_cacheAt = DateTime.UtcNow;
}
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)
{
@@ -43,6 +72,7 @@ public sealed class ModelRepository
try
{
Directory.Delete(package.Directory, true);
Invalidate();
Changed?.Invoke();
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;
}
}
+9 -4
View File
@@ -193,7 +193,9 @@ internal static class Program
Console.WriteLine($"当前平台: {rid},启动器版本: {LauncherRuntimeInfo.CurrentLauncherVersion}");
var stage = Path.Combine(tmp, "launcher-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, "GC-9.9.9-" + LauncherUpdater.PlatformLabel + launcherExt),
"new launcher");
var zip = Path.Combine(tmp, "GC-" + rid + ".zip");
ZipFile.CreateFromDirectory(stage, zip);
@@ -207,7 +209,7 @@ internal static class Program
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");
var dl = Task.Run(() => LauncherUpdater.DownloadAsync(paths, updater.Remote, null))
@@ -227,7 +229,8 @@ internal static class Program
// 5) 校验标记文件与替换脚本(相对路径,无绝对路径)
var marker = Path.Combine(paths.UpdateRoot, "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,
OperatingSystem.IsWindows() ? "apply.bat" : "apply.sh");
Check(scheduled && File.Exists(scriptPath), "替换脚本可生成");
@@ -310,8 +313,10 @@ internal static class Program
/// <summary>序列化清单并用私钥签名(测试里模拟一次正式发布)。</summary>
private static void WriteSigned(string path, RepoVersion version, ECDsa key)
{
// keyId 必须与 .signing/ 里的私钥对应的公钥条目一致,否则客户端按 keyId
// 查不到受信任公钥,会判成 Invalid 而不是 Verified。
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)
+25 -10
View File
@@ -11,8 +11,8 @@
- UI:C# + .NET 8(可切 .NET 10)+ Avalonia,跨平台
- 模型加载:`AssemblyLoadContext` 加载模型自带 dll,契约与 Avalonia 走默认上下文,关窗即卸载
- 目标平台:**macOS arm64 / Windows x64 / Windows arm64**(Linux 可自行编译,未列入发布矩阵)
- 更新仓库:<https://gitcode.com/Morris_1/GC>,模型目录 <https://gitcode.com/Morris_1/GC/tree/main/model>
- 目标平台:**Windows x64 / Windows arm64 / macOS arm64 / Linux x64**
- 更新仓库:<https://git.xhmcl.com/Morris/GC>,模型目录 <https://git.xhmcl.com/Morris/GC/src/branch/main/model>
## GC-UI:前后端分离版(Flutter 前端)
@@ -85,16 +85,20 @@ Windows 用 `.\build.ps1`,参数相同(`build / check / models / stamp / run
```
启动器下载 zip -> 校验 sha256 -> 写 apply-request.json -> 启动 GC-SAVEDOG -> 自己退出
GC-SAVEDOG: 二次验签 -> 检查 zip 安全性 -> 解压到 .GC/update/stage
-> 移入安装目录(绝不覆盖已有版本)
-> 整目录替换:旧文件搬到 .GC/update/backup,新文件就位(保留 .GC 不动)
-> 启动新版,等 .GC/update/health.json
-> 收到:删同平台旧版本,写 last-good.json
-> 没收到/进程退出:删新版、重启旧版,写 state.json = rolledback
-> 收到:删备份、写 last-good.json
-> 没收到/进程退出:撤掉新文件、把备份搬回、重启旧版,写 state.json = rolledback
```
发布包是**整目录**(启动器 + 后端运行时 + Flutter 前端资源),所以更新必须整目录替换:
只替换一个 exe 会留下旧后端 / 旧界面,新前端调不通接口。替换只动程序文件,
`.GC`(模型库、设置、日志、更新目录)和正在运行的 `GC-SAVEDOG.exe` 一律跳过。
也就是说:**新版本起不来,用户不会被卡死**。找不到 `GC-SAVEDOG` 的旧安装会退回脚本流程(过渡用)。
- 默认更新仓库写在 `.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`、下载失败:**一律保留本地模型,绝不清空模型库**,底部状态条说明原因
- 首次启动断网且本地无模型:状态条会明确提示「去下载页重试 / 手动放入 `.GC/model/`」,不会白屏干等
- 离线教室:把仓库(含 `version.json` + `model/`)拷到 U 盘,在 `settings.json` 填
@@ -135,12 +139,23 @@ Windows 用 `.\build.ps1`,参数相同(`build / check / models / stamp / run
### 签名密钥
- 私钥:`.signing/gc-signing.pem`(**已在 `.gitignore`,永不入库**;请自行备份)
- 公钥:硬编码在 `GC/src/Security/SignatureKeyring.cs`,指纹 `b41b1dd6259ea9ed`
- 生成新密钥:`dotnet run --project GC-SAVEDOG -- keygen`
- 轮换:把新公钥追加进 `SignatureKeyring.Keys`(保留旧公钥一个版本周期),再重新签名清单
- 公钥:硬编码在 `GC/src/Security/SignatureKeyring.cs`
- 当前生效:`gc-2026-12`,指纹 `ee6083be47a87907`
- 已停用:`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`
`build.sh` 在刷新清单后自动调用 `sign_manifest` 签名并同步 `model/version.json`;
`.signing/gc-signing.pem` 不存在时只告警,清单不带签名(客户端会拒绝更新)。
> 换钥匙的代价:老客户端只认识编译进去的那份公钥,所以**用新密钥签出的清单
> 在旧版本上会判成「签名无效」**。密钥一旦丢失,只能靠发一个新版本把新公钥带出去,
> 中间这段时间老客户端无法自动更新 —— 私钥务必备份两处以上。
### zip 解压加固
更新包和模型源 zip 一律当成不可信输入:拒绝 `../`、绝对路径、盘符、UNC、符号链接;
@@ -237,7 +252,7 @@ Repository/
会被挪到 `build/trash/`,下次构建时移出,不做递归删除)。
发新版:`./build.sh build -version=1.0.8` → 把 `dist/<平台>/GC-1.0.8-<平台>.zip`
上传到 gitcode Release(tag `v1.0.8`),**或者**直接提交/上传到仓库的
上传到 Gitea Release(tag `v1.0.8`),**或者**直接提交/上传到仓库的
`dist/<平台>/` 目录 → 提交并推送 `version.json` / `model/version.json`。
两种都能被客户端识别,客户端下次启动就会看到更新。
+3 -1
View File
@@ -3,6 +3,7 @@
# GC 构建入口(薄封装)
#
# ./build.sh build 完整发布(原 publish),带 apt 风格进度条
# 默认要求每个平台都带 Flutter 前端;--allow-no-ui 允许降级
# ./build.sh check 验证:编译 + 自检 + 离屏渲染 + 产物
# ./build.sh models 编译模型 dll + 封面 + 版本戳
# ./build.sh stamp 重新生成 version.json
@@ -33,11 +34,12 @@ VERSION=$(sed -n 's/.*<Version>\(.*\)<\/Version>.*/\1/p' Directory.Build.props |
TASK="${1:-build}"
shift 2>/dev/null || true
# 解析 -version=<版本号>(也接受 --version=)
# 解析 -version=<版本号>(也接受 --version=)与 --allow-no-ui
CLI_VERSION=""
for arg in "$@"; do
case "$arg" in
-version=*|--version=*) CLI_VERSION="${arg#*=}" ;;
-allow-no-ui|--allow-no-ui) export GC_ALLOW_NO_UI=1 ;;
esac
done
if [ -n "$CLI_VERSION" ]; then
+2 -2
View File
@@ -324,8 +324,8 @@ function Invoke-FullBuild {
Start-BuildStep '版本戳'; Invoke-VersionStamp; Complete-BuildStep
Start-BuildStep '编译 Mac'; Publish-Rid 'osx-arm64' 'dist/mac-arm64' $false; 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-x64'; Publish-Rid 'win-x64' 'dist/win-amd64' $false; Complete-BuildStep
Start-BuildStep '编译 Win-arm64'; Publish-Rid 'win-arm64' 'dist/win-arm64' $false; Complete-BuildStep
Start-BuildStep '运行骨架'
New-MacAppBundle
+74 -23
View File
@@ -1,13 +1,41 @@
#!/bin/sh
# 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 主机 : linux-amd64(原生)+ win-amd64 / win-arm64(mingw 交叉)
# Windows 主机: win-amd64 / win-arm64(原生)
#
# 前端是默认必需项:flutter 缺失或编译失败一律中断,不再悄悄产出只带 Avalonia
# 回退界面的包。确实要降级时用 ./build.sh build --allow-no-ui。
#
# 进度权重按实测耗时设定,供进度条估算总进度与剩余时间。
bs_build() {
ROOT_DIR="$1"
: "${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
# 显式降级:允许在没有该平台 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
rm -rf "$ROOT_DIR/dist"; mkdir -p "$ROOT_DIR/dist"
@@ -37,39 +65,62 @@ bs_build() {
progress_tick 100
}
progress_step "编译 Mac"
_run_publish mac 90 publish_rid "osx-arm64" "dist/mac-arm64" false || return 1
publish_backend "osx-arm64" "dist/mac-arm64" || return 1
# Flutter 的 macOS 产物只能在 macOS 上编;交叉构建时跳过,包内回退内置界面
if [ "$(uname -s)" = "Darwin" ]; then
build_flutter_ui macos "dist/mac-arm64" || return 1
if [ "$BUILD_MAC" = 1 ]; then
progress_step "编译 Mac"
_run_publish mac 90 publish_rid "osx-arm64" "dist/mac-arm64" false || return 1
publish_backend "osx-arm64" "dist/mac-arm64" || 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" false || return 1
publish_backend "osx-arm64" "dist/mac-arm64" || return 1
echo "!! --allow-no-ui:macOS 包内不含 Flutter 前端,启动器将回退 Avalonia"
fi
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" false || return 1
publish_backend "win-x64" "dist/win-amd64" || return 1
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" false || return 1
publish_backend "win-arm64" "dist/win-arm64" || return 1
# Windows 版 Flutter 只能在 Windows 上编;x64 产物同时放进两个 Windows 包
# (ARM64 上由系统模拟 x64 进程运行前端)。
case "$(uname -s)" in
MINGW*|MSYS*|CYGWIN*)
build_flutter_ui windows "dist/win-flutter" || return 1
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"
;;
if [ "$BUILD_LINUX" = 1 ]; then
progress_step "编译 Linux"
_run_publish linux 70 publish_rid "linux-x64" "dist/linux-amd64" false || return 1
publish_backend "linux-x64" "dist/linux-amd64" || return 1
build_flutter_ui linux "dist/linux-amd64" || 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
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-arm64"
prepare_runtime_layout "dist/mac-arm64/GC.app/Contents/MacOS"
if [ "$BUILD_LINUX" = 1 ]; then
prepare_runtime_layout "dist/linux-amd64"
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
pack_launcher
+108
View File
@@ -0,0 +1,108 @@
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}")
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"
)
+221
View File
@@ -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
+36
View File
@@ -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++")
+73 -10
View File
@@ -24,7 +24,7 @@ stamp_launcher_only() {
# 没有私钥时只警告:清单不带 signature,客户端会按「未签名」处理。
sign_manifest() {
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
echo "!! 未找到签名私钥 ${KEY},本次 version.json 未签名(客户端会拒绝更新)"
echo " 生成密钥:dotnet run --project GC-SAVEDOG -- keygen"
@@ -94,7 +94,7 @@ TXT
"memoryMb": 2048,
"autoUpdateOnStartup": true,
"requireSignedManifest": true,
"updateRepository": "https://gitcode.com/Morris_1/GC",
"updateRepository": "https://git.xhmcl.com/Morris/GC",
"updateManifestUrl": "",
"updateLocalRoot": "",
"installedModelVersions": {},
@@ -190,19 +190,24 @@ publish_backend() {
-o "$ROOT_DIR/$OUT" || return 1
}
# 构建 Flutter 前端并把桌面产物放进平台目录。
# Flutter 桌面只能在对应宿主平台上构建:Windows 产物必须在 Windows 上编,
# macOS 产物必须在 macOS 上编。交叉构建时这里只警告,包内不含前端,
# 启动器会自动回退到内置 Avalonia 界面。
# 当前主机原生构建 Flutter 前端(Windows 主机编 Windows,macOS 主机编 macOS,
# 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"
[ -d "$UI_SRC" ] || return 0
if [ ! -d "$UI_SRC" ]; then
echo "!! 找不到 Flutter 工程:$UI_SRC"
return 1
fi
FLUTTER_BIN="${FLUTTER_BIN:-flutter}"
if ! command -v "$FLUTTER_BIN" >/dev/null 2>&1; then
echo "!! 未找到 flutter(可用 FLUTTER_BIN=<路径> 指定),本次包内不含 Flutter 界面"
return 0
echo "!! 未找到 flutter(可用 FLUTTER_BIN=<路径> 指定)"
return 1
fi
echo "==> 构建 Flutter 前端 (${PLAT})"
@@ -218,10 +223,47 @@ build_flutter_ui() {
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/,整体铺到包的根目录
cp -R "$UI_SRC/build/linux/x64/release/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 "==> 生成启动器产物(GC-<版本>-<系统>-<架构>)"
@@ -257,6 +299,27 @@ pack_launcher() {
echo " -> dist/$LABEL/GC-${VERSION}-${LABEL}.zip"
done
# --- Linux:整目录打包(启动器 + 守护 + 后端 + Flutter 前端)---
SRC="$ROOT_DIR/dist/linux-amd64"
if [ -d "$SRC" ]; then
TMP="$ROOT_DIR/dist/.linuxpkg"
rm -rf "$TMP"; mkdir -p "$TMP"
cp -R "$SRC"/. "$TMP"/
rm -f "$TMP"/*.zip
if [ -f "$TMP/GC" ]; then
mv "$TMP/GC" "$TMP/GC-${VERSION}-linux-amd64"
chmod +x "$TMP/GC-${VERSION}-linux-amd64" 2>/dev/null || true
fi
if [ ! -f "$TMP/GC-UI" ]; then
echo " !! 包内没有 Flutter 前端,启动器将使用内置 Avalonia 界面"
fi
ZIP="$ROOT_DIR/dist/linux-amd64/GC-${VERSION}-linux-amd64.zip"
rm -f "$ZIP"
( cd "$TMP" && zip -qry "$ZIP" . )
rm -rf "$TMP"
echo " -> dist/linux-amd64/GC-${VERSION}-linux-amd64.zip"
fi
# --- macOS:先得到真实 .app 目录(改名 + 同步 Info.plist)---
MACAPP="$ROOT_DIR/dist/mac-arm64/GC.app"
if [ -d "$MACAPP" ]; then
@@ -317,7 +380,7 @@ pack_launcher() {
# 删除 publish 过程中的中间目录:平台目录里只留最终 zip
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-amd64 linux-x64; do
[ -d "$ROOT_DIR/dist/$d" ] || continue
find "$ROOT_DIR/dist/$d" -mindepth 1 -maxdepth 1 \
! -name "GC-${VERSION}-*.zip" -exec rm -rf {} + 2>/dev/null || true
+2 -2
View File
@@ -11,7 +11,7 @@ using GC.Services;
// 仓库根 version.json 与 model/version.json(内容相同,便于两种源地址读取)。
// 仓库地址(编译产物的 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.packages(构建脚本在打完 zip 之后再调一次),
@@ -150,7 +150,7 @@ var packages = new Dictionary<string, Dictionary<string, object>>();
// 2) 仓库里的编译产物 dist/<系统>-<架构>/GC-<版本>-<系统>-<架构>.zip ——
// 不发 Release、只提交产物也能更新(用户明确要求支持这种布局)。
// 两种都写: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" })
{
var label = LauncherArtifacts.LabelOf(rid);
+1 -1
View File
@@ -26,5 +26,5 @@
"frame": "#0A1524"
},
"build": "773ab2161d",
"updatedAt": "2026-11-18T04:35:15Z"
"updatedAt": "2026-11-18T10:16:41Z"
}
+1 -1
View File
@@ -26,5 +26,5 @@
"frame": "#0A1524"
},
"build": "cc68b8863b",
"updatedAt": "2026-11-18T04:35:15Z"
"updatedAt": "2026-11-18T10:16:41Z"
}
+1 -1
View File
@@ -32,5 +32,5 @@
"frame": "#0A1524"
},
"build": "53b7a0fbc3",
"updatedAt": "2026-11-18T04:35:15Z"
"updatedAt": "2026-11-18T10:16:41Z"
}
+1 -1
View File
@@ -32,5 +32,5 @@
"frame": "#0A1524"
},
"build": "ecd52665f9",
"updatedAt": "2026-11-18T04:35:15Z"
"updatedAt": "2026-11-18T10:16:41Z"
}
+1 -1
View File
@@ -33,5 +33,5 @@
"frame": "#F4F6FB"
},
"build": "105653737d",
"updatedAt": "2026-11-18T04:35:15Z"
"updatedAt": "2026-11-18T10:16:41Z"
}
+37 -30
View File
@@ -1,48 +1,48 @@
{
"schema": 1,
"generated": "2026-11-18T04:35:15Z",
"repository": "https://gitcode.com/Morris_1/GC",
"generated": "2026-11-18T10:16:41Z",
"repository": "https://git.xhmcl.com/Morris/GC",
"branch": "main",
"modelDir": "model",
"launcher": {
"version": "1.0.7",
"version": "1.0.9",
"revision": "",
"packages": {
"win-x64": {
"path": "dist/win-amd64/GC-1.0.7-win-amd64.zip",
"path": "dist/win-amd64/GC-1.0.9-win-amd64.zip",
"dir": "dist/win-amd64",
"name": "GC-1.0.7-win-amd64.zip",
"url": "https://gitcode.com/Morris_1/GC/releases/download/v1.0.7/GC-1.0.7-win-amd64.zip",
"sha256": "e9e0794206c6a0dfb8449ac30390ed788da72a5661d362af9f9a6e489cad0aad",
"size": 102382195
"name": "GC-1.0.9-win-amd64.zip",
"url": "https://git.xhmcl.com/Morris/GC/releases/download/1.0.9/GC-1.0.9-win-amd64.zip",
"sha256": "0807f1005e2d8bd54316529670cf1c3c89a2df07bd39297145f21c9a0aae5f04",
"size": 114372206
},
"win-arm64": {
"path": "dist/win-arm64/GC-1.0.7-win-arm64.zip",
"path": "dist/win-arm64/GC-1.0.9-win-arm64.zip",
"dir": "dist/win-arm64",
"name": "GC-1.0.7-win-arm64.zip",
"url": "https://gitcode.com/Morris_1/GC/releases/download/v1.0.7/GC-1.0.7-win-arm64.zip",
"sha256": "11dd6aea480b7eb9d5d0e40c6e8ac7733b83756e37ec924cb98f5e46a531def1",
"size": 98435968
"name": "GC-1.0.9-win-arm64.zip",
"url": "https://git.xhmcl.com/Morris/GC/releases/download/1.0.9/GC-1.0.9-win-arm64.zip",
"sha256": "ffdc37f8ea5041d69be88ffbcbf9ba5d80f7fb97c6b3debc5a918ff89f9e7f60",
"size": 110425463
},
"osx-arm64": {
"path": "dist/mac-arm64/GC-1.0.7-mac-arm64.zip",
"path": "dist/mac-arm64/GC-1.0.9-mac-arm64.zip",
"dir": "dist/mac-arm64",
"name": "GC-1.0.7-mac-arm64.zip",
"url": "https://gitcode.com/Morris_1/GC/releases/download/v1.0.7/GC-1.0.7-mac-arm64.zip",
"sha256": "b085ffabf764ab57cc69a0192b47069479170f9494fb9f447230e74028794982",
"size": 60065859
"name": "GC-1.0.9-mac-arm64.zip",
"url": "https://git.xhmcl.com/Morris/GC/releases/download/1.0.9/GC-1.0.9-mac-arm64.zip",
"sha256": "e62bbc8c9925d8158f850440600b5d16af7539c85651a5ebcc5f9a85d4c9bb01",
"size": 60066040
},
"osx-x64": {
"path": "dist/mac-x64/GC-1.0.7-mac-x64.zip",
"path": "dist/mac-x64/GC-1.0.9-mac-x64.zip",
"dir": "dist/mac-x64",
"name": "GC-1.0.7-mac-x64.zip",
"url": "https://gitcode.com/Morris_1/GC/releases/download/v1.0.7/GC-1.0.7-mac-x64.zip"
"name": "GC-1.0.9-mac-x64.zip",
"url": "https://git.xhmcl.com/Morris/GC/releases/download/1.0.9/GC-1.0.9-mac-x64.zip"
},
"linux-x64": {
"path": "dist/linux-amd64/GC-1.0.7-linux-amd64.zip",
"path": "dist/linux-amd64/GC-1.0.9-linux-amd64.zip",
"dir": "dist/linux-amd64",
"name": "GC-1.0.7-linux-amd64.zip",
"url": "https://gitcode.com/Morris_1/GC/releases/download/v1.0.7/GC-1.0.7-linux-amd64.zip"
"name": "GC-1.0.9-linux-amd64.zip",
"url": "https://git.xhmcl.com/Morris/GC/releases/download/1.0.9/GC-1.0.9-linux-amd64.zip"
}
}
},
@@ -51,7 +51,7 @@
"id": "contour-map",
"version": "1.1",
"build": "773ab2161d",
"manifestSha256": "c71ea15b519feb47a4fd33288fb92f2dcd40202fb2ce0a771fa408f9b4fbaf41",
"manifestSha256": "f86a3f83d5953cafc333585da3009d8846448f6a8a9df13b39cde57b36037733",
"filesSha256": "a6bdf9b4273aabee50c3c94ceab4d0abee15f0df1af90c58bdbb796e0d2d5699",
"files": 5,
"dir": "model/contour-map"
@@ -60,7 +60,7 @@
"id": "earth-geography",
"version": "1.9",
"build": "cc68b8863b",
"manifestSha256": "ae64033c7b46c51eb9c5f3dfb70a5491068c6cd608dec953eb34311cb8045d60",
"manifestSha256": "448f050fded46d7bfc8f0c3856e741c4a4f82523c8e012dd846ddcd400ff394a",
"filesSha256": "c018ba481831e23d3183a38ac47251f19754c7464baa5d85b47cea7a49fcfa95",
"files": 11,
"dir": "model/earth-geography"
@@ -69,7 +69,7 @@
"id": "earth-revolution",
"version": "1.7",
"build": "53b7a0fbc3",
"manifestSha256": "88e6f2f1bd2f7654d169745b96fa85aaea37671b6cdf8ed4fc05f7f259ae90bc",
"manifestSha256": "c69fc53f50213c6ab7658e1a761a20d2c55a7a344beb3c75a30393c26fa40167",
"filesSha256": "4cd45b0324a77574a0da3a939c2a6faebc785c5a24cb50136d62a78a6ea2e9b1",
"files": 7,
"dir": "model/earth-revolution"
@@ -78,7 +78,7 @@
"id": "earth-rotation",
"version": "1.7",
"build": "ecd52665f9",
"manifestSha256": "9ac0050f65eedc833dd8daa8eb3b18400540269fd1a4b764ef771a357fb1cf0a",
"manifestSha256": "cbf12a47747a331c9980260f39169b1813bb4b52a8916995fda05755267bddca",
"filesSha256": "594b005a6a9f36cd0b5d4e4a7a0b1ab42d53c8032832545b71c3915493d56c8e",
"files": 7,
"dir": "model/earth-rotation"
@@ -87,10 +87,17 @@
"id": "scale-calculator",
"version": "1.6",
"build": "105653737d",
"manifestSha256": "05dcb4ec0a4a0cda66dbb633b8ea58e4f4f2de47b5c9557799ac317de874f2af",
"manifestSha256": "fc6f7deb1efb076cc0bbee732e7de8f007ed74bc837dba2268be1e0adc1839d3",
"filesSha256": "732dd26406e0f1e836970499d7ea644def332ce909d7f8aa0a403bbe7337e604",
"files": 6,
"dir": "model/scale-calculator"
}
]
],
"signature": {
"alg": "ECDSA-P256-SHA256",
"keyId": "gc-2026-12",
"value": "A2jaSxRK1B43k8uOWmC/8diYG6JYUncGgjXW8B1ntO5Ag5rsG7Pb2gMz5ad6AcwjZ9zs8qtsSxJv8vLsUNXtWw==",
"contentSha256": "3bf738a164537e5d575e75c314f0ac01af1cb5d4d7cb882489d8dedeb73f51e9",
"signedAt": "2026-11-18T10:18:01Z"
}
}
+37 -30
View File
@@ -1,48 +1,48 @@
{
"schema": 1,
"generated": "2026-11-18T04:35:15Z",
"repository": "https://gitcode.com/Morris_1/GC",
"generated": "2026-11-18T10:16:41Z",
"repository": "https://git.xhmcl.com/Morris/GC",
"branch": "main",
"modelDir": "model",
"launcher": {
"version": "1.0.7",
"version": "1.0.9",
"revision": "",
"packages": {
"win-x64": {
"path": "dist/win-amd64/GC-1.0.7-win-amd64.zip",
"path": "dist/win-amd64/GC-1.0.9-win-amd64.zip",
"dir": "dist/win-amd64",
"name": "GC-1.0.7-win-amd64.zip",
"url": "https://gitcode.com/Morris_1/GC/releases/download/v1.0.7/GC-1.0.7-win-amd64.zip",
"sha256": "e9e0794206c6a0dfb8449ac30390ed788da72a5661d362af9f9a6e489cad0aad",
"size": 102382195
"name": "GC-1.0.9-win-amd64.zip",
"url": "https://git.xhmcl.com/Morris/GC/releases/download/1.0.9/GC-1.0.9-win-amd64.zip",
"sha256": "0807f1005e2d8bd54316529670cf1c3c89a2df07bd39297145f21c9a0aae5f04",
"size": 114372206
},
"win-arm64": {
"path": "dist/win-arm64/GC-1.0.7-win-arm64.zip",
"path": "dist/win-arm64/GC-1.0.9-win-arm64.zip",
"dir": "dist/win-arm64",
"name": "GC-1.0.7-win-arm64.zip",
"url": "https://gitcode.com/Morris_1/GC/releases/download/v1.0.7/GC-1.0.7-win-arm64.zip",
"sha256": "11dd6aea480b7eb9d5d0e40c6e8ac7733b83756e37ec924cb98f5e46a531def1",
"size": 98435968
"name": "GC-1.0.9-win-arm64.zip",
"url": "https://git.xhmcl.com/Morris/GC/releases/download/1.0.9/GC-1.0.9-win-arm64.zip",
"sha256": "ffdc37f8ea5041d69be88ffbcbf9ba5d80f7fb97c6b3debc5a918ff89f9e7f60",
"size": 110425463
},
"osx-arm64": {
"path": "dist/mac-arm64/GC-1.0.7-mac-arm64.zip",
"path": "dist/mac-arm64/GC-1.0.9-mac-arm64.zip",
"dir": "dist/mac-arm64",
"name": "GC-1.0.7-mac-arm64.zip",
"url": "https://gitcode.com/Morris_1/GC/releases/download/v1.0.7/GC-1.0.7-mac-arm64.zip",
"sha256": "b085ffabf764ab57cc69a0192b47069479170f9494fb9f447230e74028794982",
"size": 60065859
"name": "GC-1.0.9-mac-arm64.zip",
"url": "https://git.xhmcl.com/Morris/GC/releases/download/1.0.9/GC-1.0.9-mac-arm64.zip",
"sha256": "e62bbc8c9925d8158f850440600b5d16af7539c85651a5ebcc5f9a85d4c9bb01",
"size": 60066040
},
"osx-x64": {
"path": "dist/mac-x64/GC-1.0.7-mac-x64.zip",
"path": "dist/mac-x64/GC-1.0.9-mac-x64.zip",
"dir": "dist/mac-x64",
"name": "GC-1.0.7-mac-x64.zip",
"url": "https://gitcode.com/Morris_1/GC/releases/download/v1.0.7/GC-1.0.7-mac-x64.zip"
"name": "GC-1.0.9-mac-x64.zip",
"url": "https://git.xhmcl.com/Morris/GC/releases/download/1.0.9/GC-1.0.9-mac-x64.zip"
},
"linux-x64": {
"path": "dist/linux-amd64/GC-1.0.7-linux-amd64.zip",
"path": "dist/linux-amd64/GC-1.0.9-linux-amd64.zip",
"dir": "dist/linux-amd64",
"name": "GC-1.0.7-linux-amd64.zip",
"url": "https://gitcode.com/Morris_1/GC/releases/download/v1.0.7/GC-1.0.7-linux-amd64.zip"
"name": "GC-1.0.9-linux-amd64.zip",
"url": "https://git.xhmcl.com/Morris/GC/releases/download/1.0.9/GC-1.0.9-linux-amd64.zip"
}
}
},
@@ -51,7 +51,7 @@
"id": "contour-map",
"version": "1.1",
"build": "773ab2161d",
"manifestSha256": "c71ea15b519feb47a4fd33288fb92f2dcd40202fb2ce0a771fa408f9b4fbaf41",
"manifestSha256": "f86a3f83d5953cafc333585da3009d8846448f6a8a9df13b39cde57b36037733",
"filesSha256": "a6bdf9b4273aabee50c3c94ceab4d0abee15f0df1af90c58bdbb796e0d2d5699",
"files": 5,
"dir": "model/contour-map"
@@ -60,7 +60,7 @@
"id": "earth-geography",
"version": "1.9",
"build": "cc68b8863b",
"manifestSha256": "ae64033c7b46c51eb9c5f3dfb70a5491068c6cd608dec953eb34311cb8045d60",
"manifestSha256": "448f050fded46d7bfc8f0c3856e741c4a4f82523c8e012dd846ddcd400ff394a",
"filesSha256": "c018ba481831e23d3183a38ac47251f19754c7464baa5d85b47cea7a49fcfa95",
"files": 11,
"dir": "model/earth-geography"
@@ -69,7 +69,7 @@
"id": "earth-revolution",
"version": "1.7",
"build": "53b7a0fbc3",
"manifestSha256": "88e6f2f1bd2f7654d169745b96fa85aaea37671b6cdf8ed4fc05f7f259ae90bc",
"manifestSha256": "c69fc53f50213c6ab7658e1a761a20d2c55a7a344beb3c75a30393c26fa40167",
"filesSha256": "4cd45b0324a77574a0da3a939c2a6faebc785c5a24cb50136d62a78a6ea2e9b1",
"files": 7,
"dir": "model/earth-revolution"
@@ -78,7 +78,7 @@
"id": "earth-rotation",
"version": "1.7",
"build": "ecd52665f9",
"manifestSha256": "9ac0050f65eedc833dd8daa8eb3b18400540269fd1a4b764ef771a357fb1cf0a",
"manifestSha256": "cbf12a47747a331c9980260f39169b1813bb4b52a8916995fda05755267bddca",
"filesSha256": "594b005a6a9f36cd0b5d4e4a7a0b1ab42d53c8032832545b71c3915493d56c8e",
"files": 7,
"dir": "model/earth-rotation"
@@ -87,10 +87,17 @@
"id": "scale-calculator",
"version": "1.6",
"build": "105653737d",
"manifestSha256": "05dcb4ec0a4a0cda66dbb633b8ea58e4f4f2de47b5c9557799ac317de874f2af",
"manifestSha256": "fc6f7deb1efb076cc0bbee732e7de8f007ed74bc837dba2268be1e0adc1839d3",
"filesSha256": "732dd26406e0f1e836970499d7ea644def332ce909d7f8aa0a403bbe7337e604",
"files": 6,
"dir": "model/scale-calculator"
}
]
],
"signature": {
"alg": "ECDSA-P256-SHA256",
"keyId": "gc-2026-12",
"value": "A2jaSxRK1B43k8uOWmC/8diYG6JYUncGgjXW8B1ntO5Ag5rsG7Pb2gMz5ad6AcwjZ9zs8qtsSxJv8vLsUNXtWw==",
"contentSha256": "3bf738a164537e5d575e75c314f0ac01af1cb5d4d7cb882489d8dedeb73f51e9",
"signedAt": "2026-11-18T10:18:01Z"
}
}