diff --git a/.gitea/workflows/gc-ui-alpha.yml b/.gitea/workflows/gc-ui-alpha.yml
index b6e233b..a00b20d 100644
--- a/.gitea/workflows/gc-ui-alpha.yml
+++ b/.gitea/workflows/gc-ui-alpha.yml
@@ -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"
diff --git a/.gitea/workflows/nightly-prerelease.yml b/.gitea/workflows/nightly-prerelease.yml
deleted file mode 100644
index 2ffadb7..0000000
--- a/.gitea/workflows/nightly-prerelease.yml
+++ /dev/null
@@ -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
diff --git a/.gitignore b/.gitignore
index dfb5c1c..c491818 100644
--- a/.gitignore
+++ b/.gitignore
@@ -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/
+
diff --git a/GC-BOOT/FlutterShell.cs b/GC-BOOT/FlutterShell.cs
index 352696d..8c725aa 100644
--- a/GC-BOOT/FlutterShell.cs
+++ b/GC-BOOT/FlutterShell.cs
@@ -21,8 +21,8 @@ namespace GC;
///
internal static class FlutterShell
{
- /// 与 GC-UI/frontend 的默认 baseUrl 保持一致,前端不需要额外配置。
- private const int Port = 17890;
+ /// 与前端、后端共用的默认端口(定义在 GC.Services.GcUiContract)。
+ 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;
diff --git a/GC-DOWNLOAD/LauncherUpdater.cs b/GC-DOWNLOAD/LauncherUpdater.cs
index 93be0a8..a3e3113 100644
--- a/GC-DOWNLOAD/LauncherUpdater.cs
+++ b/GC-DOWNLOAD/LauncherUpdater.cs
@@ -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 表示调用方应立即退出进程。
///
- public static bool ScheduleApply(AppPaths paths, string packageName)
+ /// 只写脚本不执行(测试用,避免真的搬动文件)。
+ 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;
}
+ /// 给 Linux/macOS 上的可执行文件补上执行位(zip 不保留权限)。
+ 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
diff --git a/GC-DOWNLOAD/SourceSelector.cs b/GC-DOWNLOAD/SourceSelector.cs
index a976cab..4544e63 100644
--- a/GC-DOWNLOAD/SourceSelector.cs
+++ b/GC-DOWNLOAD/SourceSelector.cs
@@ -40,7 +40,8 @@ public sealed class SourceSelector : ISourceSelector
///
/// 探测两个源并返回最快的。force=true 时忽略缓存。
- /// 两个都失败时返回 GitCode(默认源)。
+ /// 两个都失败时退回主源(Xhmcl):GitCode 镜像已停更,用它兜底只会拿到过期的
+ /// version.json —— 反而让人以为「没有更新」。
///
public async Task 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(" ",
diff --git a/GC-SAVEDOG/Applier.cs b/GC-SAVEDOG/Applier.cs
index 3b2d5b4..2745fde 100644
--- a/GC-SAVEDOG/Applier.cs
+++ b/GC-SAVEDOG/Applier.cs
@@ -26,13 +26,14 @@ internal sealed class ApplyOptions
///
internal sealed class Applier
{
- private static readonly Regex ArtifactPattern = new(
- @"^GC-(?.+?)-(?[^\-]+-[^\-]+)\.(app|exe)$",
- RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);
-
private readonly ApplyOptions _options;
private readonly Log _log;
+ /// 发布包里的启动器文件名:GC-1.0.9-win-amd64.exe。
+ 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
// ------------------------------------------------------------------ 校验辅助
+ ///
+ /// 包名合法性:只允许「一个文件名」,杜绝 `../` 之类的路径穿越。
+ ///
+ /// 不能只认 .app / .exe —— Linux 的启动器没有扩展名
+ /// (GC-1.0.9-linux-amd64),按旧规则会被直接判成非法包名、更新永远失败。
+ ///
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);
}
+ ///
+ /// 在解压结果里找主程序。
+ ///
+ /// 发布包是「整目录」结构(exe + dll + data/),同一层可能有好几个 exe
+ /// (GC-UI / GC.UI.Server / GC-SAVEDOG / createdump),必须按固定优先级挑,
+ /// 不能取第一个 —— 否则会把守护进程或调试辅助程序当成启动器拉起来。
+ ///
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;
}
+ /// 主程序优先级:数字越大越优先,0 表示不是主程序。
+ 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)
+ ///
+ /// 把 的内容替换进 。
+ ///
+ /// 发布包是「整目录」(启动器 + 后端运行时 + Flutter 前端资源),只搬一个 exe 会留下
+ /// 旧后端 / 旧界面,所以这里按目录整体替换:
+ /// 1. 安装目录里「新版没有」的条目 → 移到 backup(旧版本残留,如上一版的旧文件名);
+ /// 2. 与新版同名的条目 → 先移到 backup,再把新版放进来(覆盖正在被占用的文件会失败,
+ /// 这种情况直接报错并还原,绝不留下半新半旧的目录);
+ /// 3. `.GC`、更新目录自身、正在运行的 GC-SAVEDOG.exe 一律跳过。
+ ///
+ /// 返回 false 时调用方应调用 还原。
+ ///
+ 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();
+ 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(
+ 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;
}
}
+ ///
+ /// 把备份里的条目原样搬回安装目录,撤掉新装的内容。
+ /// 为 null 表示这一项是新包里独有的(没有旧版本),
+ /// 回滚时只需要删掉。
+ ///
+ 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;
+ }
+
+ /// 更新成功:删掉整份备份,不再占用磁盘。
+ 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);
+ }
+ }
+
+ ///
+ /// 安装目录里不该被更新碰的东西:
+ /// · .GC —— 模型库、设置、日志、更新目录本身都在这里;
+ /// · GC-SAVEDOG.exe —— 本进程正在运行,Windows 上无法替换。
+ ///
+ 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; }
+ }
+
+ /// 移动条目;跨卷或目标占用时退回「复制 + 删除」。
+ 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);
+ }
+ }
+
+ /// 删除文件或目录,失败时抛出(由调用方决定是否回滚)。
+ 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();
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
diff --git a/GC-UI/CI.md b/GC-UI/CI.md
index 4512829..a742b9c 100644
--- a/GC-UI/CI.md
+++ b/GC-UI/CI.md
@@ -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 前缀** 两处。
diff --git a/GC-UI/README.md b/GC-UI/README.md
index 1c7e675..8247733 100644
--- a/GC-UI/README.md
+++ b/GC-UI/README.md
@@ -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. 启动前端
diff --git a/GC-UI/backend/GC.UI.Server/ApiModels.cs b/GC-UI/backend/GC.UI.Server/ApiModels.cs
index 3678c6b..869b1b7 100644
--- a/GC-UI/backend/GC.UI.Server/ApiModels.cs
+++ b/GC-UI/backend/GC.UI.Server/ApiModels.cs
@@ -133,6 +133,15 @@ public sealed record AboutDto(
public sealed record LaunchResultDto(bool Ok, string Message);
+///
+/// 通用错误响应。限流 / 参数校验这类与具体业务无关的失败用它,
+/// 不要复用 —— 那会让前端误以为「启动模型」有结果。
+///
+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);
diff --git a/GC-UI/backend/GC.UI.Server/AvaloniaHost.cs b/GC-UI/backend/GC.UI.Server/AvaloniaHost.cs
index e6c346f..0b83d6b 100644
--- a/GC-UI/backend/GC.UI.Server/AvaloniaHost.cs
+++ b/GC-UI/backend/GC.UI.Server/AvaloniaHost.cs
@@ -28,7 +28,7 @@ public sealed class AvaloniaHost
{
private readonly AppServices _services;
private readonly object _gate = new();
- private readonly List _windows = new();
+ private readonly Dictionary _windows = new(StringComparer.OrdinalIgnoreCase);
private Task? _startTask;
public AvaloniaHost(AppServices services) => _services = services;
@@ -98,6 +98,27 @@ public sealed class AvaloniaHost
return await Dispatcher.UIThread.InvokeAsync(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}";
}
diff --git a/GC-UI/backend/GC.UI.Server/Program.cs b/GC-UI/backend/GC.UI.Server/Program.cs
index 71407f2..76d3efc 100644
--- a/GC-UI/backend/GC.UI.Server/Program.cs
+++ b/GC-UI/backend/GC.UI.Server/Program.cs
@@ -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,
+/// 按扩展名推断图片 MIME;模型封面允许 png / jpg / webp / gif。
+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 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));
diff --git a/GC-UI/frontend/lib/api_client.dart b/GC-UI/frontend/lib/api_client.dart
index 164a1a8..28e976e 100644
--- a/GC-UI/frontend/lib/api_client.dart
+++ b/GC-UI/frontend/lib/api_client.dart
@@ -1,4 +1,5 @@
import 'dart:convert';
+import 'dart:io';
import 'package:http/http.dart' as http;
@@ -334,16 +335,65 @@ List _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) 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');
diff --git a/GC-UI/frontend/lib/controller.dart b/GC-UI/frontend/lib/controller.dart
index 4451dea..29ebd9b 100644
--- a/GC-UI/frontend/lib/controller.dart
+++ b/GC-UI/frontend/lib/controller.dart
@@ -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 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(>[
+ () 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 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();
+ }
}
diff --git a/GC-UI/frontend/lib/i18n.dart b/GC-UI/frontend/lib/i18n.dart
index 88ebf21..3229e05 100644
--- a/GC-UI/frontend/lib/i18n.dart
+++ b/GC-UI/frontend/lib/i18n.dart
@@ -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',
diff --git a/GC-UI/frontend/lib/main.dart b/GC-UI/frontend/lib/main.dart
index c4cd7bf..db9e56e 100644
--- a/GC-UI/frontend/lib/main.dart
+++ b/GC-UI/frontend/lib/main.dart
@@ -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 {
@override
Widget build(BuildContext context) {
- // 语言与强调色都会触发重建:只重建 MaterialApp 的主题层,
+ // 语言、强调色、主题模式都会触发重建:只重建 MaterialApp 的主题层,
// 不触碰页面状态(页面由 ShellPage 自己持有)。
return ValueListenableBuilder(
valueListenable: I18n.language,
@@ -36,11 +36,28 @@ class _GcUiAppState extends State {
return ValueListenableBuilder(
valueListenable: GcPalette.accent,
builder: (context, accent, _) {
- return MaterialApp(
- title: 'Morris GC',
- debugShowCheckedModeBanner: false,
- theme: buildGcTheme(),
- home: ShellPage(controller: _controller),
+ return ValueListenableBuilder(
+ 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(brightness == Brightness.dark),
+ child: child ?? const SizedBox.shrink(),
+ );
+ },
+ home: ShellPage(controller: _controller),
+ );
+ },
);
},
);
diff --git a/GC-UI/frontend/lib/pages.dart b/GC-UI/frontend/lib/pages.dart
index 1b43e7c..5f0ef66 100644
--- a/GC-UI/frontend/lib/pages.dart
+++ b/GC-UI/frontend/lib/pages.dart
@@ -28,10 +28,14 @@ class _HomePageViewState extends State {
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 {
}
}
+ @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 _load() async {
setState(() {
_loading = true;
@@ -128,7 +148,7 @@ class _HomePageViewState extends State {
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 {
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 {
crossAxisAlignment: CrossAxisAlignment.start,
children: [
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 {
children: [
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 {
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 {
String? _error;
Timer? _poll;
+ /// 页面是否可见(被切走后仍保活,但没必要继续请求后端)。
+ bool _visible = true;
+
+ /// 上一次轮询时是否有活跃任务,用来判断「刚刚全部结束」。
+ bool _hadActive = false;
+
@override
void initState() {
super.initState();
@@ -677,7 +703,14 @@ class _DownloadPageViewState extends State {
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 {
super.dispose();
}
+ /// 单次 Timer 链:有活跃任务时 1 秒一次,空闲时降到 5 秒,不可见时 10 秒。
+ ///
+ /// 以前是 `Timer.periodic(1s)` 且永不停止 —— 只要进过下载页,之后每秒都
+ /// 在请求 `/api/download/jobs`,哪怕没有任何任务、页面也早就切走了。
+ void _schedulePoll(Duration delay) {
+ _poll?.cancel();
+ _poll = Timer(delay, _pollOnce);
+ }
+
+ Future _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 _load() async {
setState(() {
_loading = true;
@@ -818,7 +880,7 @@ class _DownloadPageViewState extends State {
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 {
),
),
if (!source.enabled)
- const Text(
+ Text(
'off',
style: TextStyle(
fontSize: 10, color: GcColors.faint),
@@ -836,7 +898,7 @@ class _DownloadPageViewState extends State {
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 {
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 {
crossAxisAlignment: CrossAxisAlignment.start,
children: [
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 {
crossAxisAlignment: CrossAxisAlignment.start,
children: [
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 {
children: [
Text(
model.name,
- style: const TextStyle(
+ style: TextStyle(
fontSize: 13,
fontWeight: FontWeight.w600,
color: GcColors.ink,
@@ -939,7 +1001,7 @@ class _DownloadPageViewState extends State {
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 {
),
child: Text(
T('dl.installed'),
- style: const TextStyle(
+ style: TextStyle(
fontSize: 10,
color: GcColors.ok),
),
@@ -969,7 +1031,7 @@ class _DownloadPageViewState extends State {
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 {
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 {
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 {
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 {
}
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 {
children: [
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 {
Row(
children: [
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(
value: _language,
dropdownColor: GcColors.surfaceAlt,
@@ -1228,7 +1295,7 @@ class _SettingsPageViewState extends State {
Row(
children: [
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 {
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 {
children: [
GcSectionTitle(T('set.appearance')),
const SizedBox(height: 8),
+ GcHint(T('set.theme.desc')),
+ const SizedBox(height: 10),
+ SegmentedButton(
+ segments: >[
+ ButtonSegment(
+ value: ThemeMode.dark,
+ label: Text(T('set.theme.dark')),
+ icon: const Icon(Icons.dark_mode_outlined, size: 15),
+ ),
+ ButtonSegment(
+ value: ThemeMode.light,
+ label: Text(T('set.theme.light')),
+ icon: const Icon(Icons.light_mode_outlined, size: 15),
+ ),
+ ButtonSegment(
+ value: ThemeMode.system,
+ label: Text(T('set.theme.system')),
+ icon: const Icon(Icons.brightness_auto_outlined, size: 15),
+ ),
+ ],
+ selected: {_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 {
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 {
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
- 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 {
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 {
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 {
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 {
children: [
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 {
children: [
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 {
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 {
),
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 {
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 {
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 {
children: [
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 {
crossAxisAlignment: CrossAxisAlignment.start,
children: [
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 {
children: [
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 {
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 {
Text(
T('about.contributions',