Compare commits
15
Commits
1.1.0
...
4ef291568a
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4ef291568a | ||
|
|
5b628971a9 | ||
|
|
faaee9abe2 | ||
|
|
ead63e8ffe | ||
|
|
01c2d017c6 | ||
|
|
3efdf74258 | ||
|
|
3c74effb4c | ||
|
|
f03046bffd | ||
|
|
2cd18b4e5f | ||
|
|
023e9468db | ||
|
|
5e5d84856a | ||
|
|
b4724d7ca0 | ||
|
|
9a911089bf | ||
|
|
4bdfb49600 | ||
|
|
59a66c8fa8 |
No files matched your search
@@ -57,9 +57,12 @@ jobs:
|
||||
with:
|
||||
dotnet-version: '8.0.x'
|
||||
|
||||
- name: 运行 GC.Tests(含离屏渲染 / 清单校验)
|
||||
- name: 运行 GC.Tests(含离屏渲染 / 清单校验 / 日志用例)
|
||||
run: dotnet run --project GC/src/test/dotnet/GC.Tests/GC.Tests.csproj -c Release
|
||||
|
||||
- name: 运行应用器测试(整目录替换 / .GC/bin 合并 / 回滚)
|
||||
run: dotnet run --project GC/src/test/dotnet/GC.Savedog.Tests/GC.Savedog.Tests.csproj -c Release
|
||||
|
||||
frontend:
|
||||
name: 前端检查(Flutter)
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
# ---------------------------------------------------------------------------
|
||||
# 发布一致性核对(Gitea Actions)
|
||||
#
|
||||
# 触发:仅手动。发布前跑一次确认「tag / 清单 / 资产」互相对得上,发布后再跑一次
|
||||
# 确认线上资产就是清单里那两份。
|
||||
#
|
||||
# 为什么不用 pull_request 触发:这里要下载几百 MB 的发布包,PR 阶段跑太贵;
|
||||
# 需要时点 Run workflow 即可,本地也有等价命令:./build.sh release-verify <tag>
|
||||
# ---------------------------------------------------------------------------
|
||||
name: 发布核对
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
tag:
|
||||
description: '要核对的 tag(如 1.1.0)'
|
||||
required: true
|
||||
skip_download:
|
||||
description: '只比对体积、不下载校验 sha256(快,输入 1 开启)'
|
||||
required: false
|
||||
default: ''
|
||||
|
||||
env:
|
||||
DOTNET_NOLOGO: '1'
|
||||
DOTNET_CLI_TELEMETRY_OPTOUT: '1'
|
||||
|
||||
jobs:
|
||||
verify:
|
||||
name: 核对 Release 与清单
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: 检出代码
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: 安装 .NET 8
|
||||
uses: actions/setup-dotnet@v4
|
||||
with:
|
||||
dotnet-version: '8.0.x'
|
||||
|
||||
- name: 核对
|
||||
env:
|
||||
GC_GITEA_TOKEN: ${{ secrets.GC_GITEA_TOKEN }}
|
||||
run: |
|
||||
set -eu
|
||||
EXTRA=""
|
||||
if [ -n "${{ github.event.inputs.skip_download }}" ]; then
|
||||
EXTRA="--skip-download"
|
||||
fi
|
||||
chmod +x buildsh/lib/verify_release.py
|
||||
./build.sh release-verify "${{ github.event.inputs.tag }}" $EXTRA
|
||||
@@ -22,7 +22,7 @@
|
||||
-->
|
||||
<AvaloniaVersion>11.3.9</AvaloniaVersion>
|
||||
<MvvmVersion>8.2.2</MvvmVersion>
|
||||
<Version>1.1.0</Version>
|
||||
<Version>1.1.1</Version>
|
||||
<Company>Morris</Company>
|
||||
<Product>GC</Product>
|
||||
<NeutralLanguage>zh-Hans</NeutralLanguage>
|
||||
|
||||
+31
-4
@@ -39,6 +39,7 @@ internal static class FlutterShell
|
||||
if (uiPath == null) return false;
|
||||
|
||||
var port = Port;
|
||||
AvaloniaHost? uiHost = null;
|
||||
|
||||
// 用户可能重复启动:已有后端在跑就直接复用,退出时也不要关掉别人的进程。
|
||||
if (!IsHealthy(port))
|
||||
@@ -50,13 +51,14 @@ internal static class FlutterShell
|
||||
|
||||
for (var candidate = start; candidate < start + Services.GcUiContract.PortScanRange; candidate++)
|
||||
{
|
||||
var app = TryStartBackend(args, candidate);
|
||||
var app = TryStartBackend(args, candidate, out var host);
|
||||
if (app == null) continue;
|
||||
|
||||
if (WaitHealthy(candidate, TimeSpan.FromSeconds(25)))
|
||||
{
|
||||
port = candidate;
|
||||
_backend = app;
|
||||
uiHost = host;
|
||||
break;
|
||||
}
|
||||
|
||||
@@ -76,7 +78,29 @@ internal static class FlutterShell
|
||||
return false;
|
||||
}
|
||||
|
||||
ui.WaitForExit();
|
||||
// 前端窗口已拉起。模型窗口由 Avalonia 承载,而 macOS 的 AppKit 要求
|
||||
// NSApplication 必须在**主线程**——所以事件循环要跑在这里(当前正是主线程),
|
||||
// 不能再丢到副线程,否则一点「启动模型」就会把整个后端带崩。
|
||||
ui.EnableRaisingEvents = true;
|
||||
var closed = 0;
|
||||
void RequestClose()
|
||||
{
|
||||
if (Interlocked.Exchange(ref closed, 1) == 1) return;
|
||||
uiHost?.Shutdown();
|
||||
}
|
||||
|
||||
ui.Exited += (_, _) => RequestClose();
|
||||
if (ui.HasExited) RequestClose();
|
||||
|
||||
if (!ui.HasExited && uiHost != null)
|
||||
{
|
||||
// 阻塞直到界面退出(或图形环境初始化失败)。
|
||||
uiHost.RunOnCurrentThread();
|
||||
}
|
||||
|
||||
// Avalonia 起不来(无桌面会话)时仍要等界面退出,避免后端被提前收掉。
|
||||
if (!ui.HasExited) ui.WaitForExit();
|
||||
|
||||
StopBackend(_backend);
|
||||
_backend = null;
|
||||
return true;
|
||||
@@ -108,11 +132,14 @@ internal static class FlutterShell
|
||||
// ---------------------------------------------------------------- 进程管理
|
||||
|
||||
/// <summary>在本进程内启动后端;端口被占用等失败情况返回 null。</summary>
|
||||
private static WebApplication? TryStartBackend(string[] args, int port)
|
||||
/// <param name="uiHost">成功时交出模型窗口宿主,由调用方在主线程跑事件循环。</param>
|
||||
private static WebApplication? TryStartBackend(string[] args, int port, out AvaloniaHost? uiHost)
|
||||
{
|
||||
uiHost = null;
|
||||
try
|
||||
{
|
||||
var app = BackendServer.Start(args, port);
|
||||
var app = BackendServer.Start(args, port, out var host);
|
||||
uiHost = host;
|
||||
app.StartAsync().GetAwaiter().GetResult();
|
||||
return app;
|
||||
}
|
||||
|
||||
@@ -56,12 +56,14 @@ public sealed partial class DownloadJob : ObservableObject, IDownloadJob
|
||||
partial void OnErrorChanged(string? value) => RefreshText();
|
||||
}
|
||||
|
||||
/// <summary>下载中心:最多 2 个并发,任务在「后台列表」里折叠展示。</summary>
|
||||
/// <summary>下载中心:最多 4 个并发,任务在「后台列表」里折叠展示。</summary>
|
||||
public sealed class DownloadCenter : IDownloadCenter
|
||||
{
|
||||
private readonly ModelRepository _repository;
|
||||
private readonly AppPaths _paths;
|
||||
private readonly SemaphoreSlim _slots = new(2);
|
||||
// 断点续传后单任务失败重来的代价小了很多,可以适当提高并发;
|
||||
// 更新服务那边已是 6,模型下载保持 4,兼顾弱网吞吐与源站压力。
|
||||
private readonly SemaphoreSlim _slots = new(4);
|
||||
|
||||
public ObservableCollection<IDownloadJob> Jobs { get; } = new();
|
||||
public event Action? Installed;
|
||||
|
||||
@@ -194,8 +194,26 @@ public static class LauncherUpdater
|
||||
{
|
||||
using var ms = new MemoryStream(zip);
|
||||
using var archive = new System.IO.Compression.ZipArchive(ms, System.IO.Compression.ZipArchiveMode.Read);
|
||||
// 找主程序:app 内的可执行文件 / GC.dll / 单文件 exe
|
||||
var entry = archive.Entries.FirstOrDefault(e =>
|
||||
|
||||
// 发布包从 1.0.10 起改为 GCL 命名 + 单文件 + 单顶层目录,主程序是
|
||||
// <顶层>/GCL-<版本>-<平台>.exe (Windows)
|
||||
// <顶层>/GCL-<版本>-<平台> (Linux,无扩展名)
|
||||
// <顶层>/GCL-<版本>-mac-arm64.app/... (macOS)
|
||||
// 旧布局则是 GC.dll / GC / GC*.dll。先找新名,再退回旧名,兼容老发布包。
|
||||
// 注意排除 GC-UI / GC-SAVEDOG / .GC/bin 里的附属程序,它们不是启动器本体。
|
||||
bool IsLauncher(System.IO.Compression.ZipArchiveEntry e)
|
||||
{
|
||||
var n = e.Name;
|
||||
if (n.Length == 0) return false; // 目录条目
|
||||
if (n.StartsWith("GC-UI", StringComparison.OrdinalIgnoreCase) ||
|
||||
n.StartsWith("GC-SAVEDOG", StringComparison.OrdinalIgnoreCase)) return false;
|
||||
if (e.FullName.Replace('\\', '/').Contains("/.GC/")) return false;
|
||||
if (n.StartsWith("GCL-", StringComparison.OrdinalIgnoreCase)) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
var entry = archive.Entries.FirstOrDefault(IsLauncher)
|
||||
?? archive.Entries.FirstOrDefault(e =>
|
||||
e.Name.Equals("GC.dll", StringComparison.OrdinalIgnoreCase))
|
||||
?? archive.Entries.FirstOrDefault(e =>
|
||||
e.Name.Equals("GC", StringComparison.OrdinalIgnoreCase))
|
||||
|
||||
@@ -5,6 +5,8 @@ using System.IO;
|
||||
using System.IO.Compression;
|
||||
using System.Linq;
|
||||
using System.Net.Http;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using GC.Models;
|
||||
@@ -152,24 +154,33 @@ public sealed class ModelSourceClient : IModelSourceClient
|
||||
else if (host.Contains("gitee.com"))
|
||||
yield return $"https://gitee.com/{owner}/{repo}/repository/archive/{b}.zip";
|
||||
else
|
||||
yield break;
|
||||
{
|
||||
// 自托管 Gitea(如 git.xhmcl.com):用 archive/<branch>.zip 拉源码归档。
|
||||
// 关键:不能在这里 yield break —— 那样就只剩 git clone 一条路,
|
||||
// 用户机器没装 git 时「检测模型 / 下载 / 自动更新」会全部失效。
|
||||
// 归档下载走 ResumableDownloader,无需系统 git。
|
||||
yield return $"{uri.GetLeftPart(UriPartial.Authority)}/{owner}/{repo}/archive/{b}.zip";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async Task DownloadZipAsync(string url, string cacheDir, CancellationToken ct)
|
||||
{
|
||||
// .part 用 URL 哈希做稳定文件名:同一个源重试时命中同一份半成品,
|
||||
// 断点续传才有意义(用 GUID 的话每次重试都是新文件,等于从零开始)。
|
||||
// 解压目录仍用 GUID —— 它只是中间产物,成功后整块移走或失败即删。
|
||||
var key = Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(url)))[..16].ToLowerInvariant();
|
||||
var partPath = Path.Combine(_paths.CacheRoot, "tmp", "downloads", key + ".part");
|
||||
var tmpRoot = Path.Combine(_paths.CacheRoot, "tmp", Guid.NewGuid().ToString("N"));
|
||||
Directory.CreateDirectory(tmpRoot);
|
||||
var zipPath = Path.Combine(tmpRoot, "source.zip");
|
||||
try
|
||||
{
|
||||
using (var response = await Http.GetAsync(url, HttpCompletionOption.ResponseHeadersRead, ct))
|
||||
{
|
||||
response.EnsureSuccessStatusCode();
|
||||
await using var input = await response.Content.ReadAsStreamAsync(ct);
|
||||
await using var output = File.Create(zipPath);
|
||||
await input.CopyToAsync(output, 81920, ct);
|
||||
}
|
||||
// 带断点续传的流式下载;网络中断时 .part 保留,下次从这里接上。
|
||||
await ResumableDownloader.DownloadAsync(Http, url, partPath, null, ct)
|
||||
.ConfigureAwait(false);
|
||||
// 下载完整,.part 转正。转正成功即代表这份 zip 已完整,删掉 .part 避免重复下载。
|
||||
File.Move(partPath, zipPath, overwrite: true);
|
||||
|
||||
var extractDir = Path.Combine(tmpRoot, "extract");
|
||||
Directory.CreateDirectory(extractDir);
|
||||
|
||||
@@ -0,0 +1,100 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace GC.Services;
|
||||
|
||||
/// <summary>
|
||||
/// 带断点续传的流式下载器。已下载的部分写在 <c>*.part</c> 文件里,
|
||||
/// 完整下载后由调用方把 .part 改成正式文件名。
|
||||
///
|
||||
/// 为什么需要它:模型源码 zip 可能有上百 MB,弱网中断后如果每次都从头下,
|
||||
/// 用户会反复卡在同一个地方。这里用 HTTP Range 从已下载的字节接着下。
|
||||
///
|
||||
/// 兼容性:服务器不支持 Range(忽略请求、返回 200)时自动退化为整段下载,
|
||||
/// 不会卡死或拿到半截文件。<see cref="Content-Range"/> 起始位置不符时也从头下。
|
||||
///
|
||||
/// .part 文件只有在"续传"场景才复用;一旦下载完整、调用方改名为正式文件,
|
||||
/// 下次就是全新下载,不会把旧内容接在新内容后面。
|
||||
/// </summary>
|
||||
public static class ResumableDownloader
|
||||
{
|
||||
/// <summary>
|
||||
/// 下载 <paramref name="url"/>,数据写入 <paramref name="partPath"/>。
|
||||
/// 返回最终 .part 文件的字节数。下载完整后由调用方负责改名 / 校验。
|
||||
/// </summary>
|
||||
public static async Task<long> DownloadAsync(
|
||||
HttpClient http,
|
||||
string url,
|
||||
string partPath,
|
||||
IProgress<(long Done, long Total)>? progress,
|
||||
CancellationToken ct)
|
||||
{
|
||||
// 已有 .part 就尝试从断点续传;没有则从头下
|
||||
long resumeFrom = 0;
|
||||
if (File.Exists(partPath))
|
||||
{
|
||||
try { resumeFrom = new FileInfo(partPath).Length; }
|
||||
catch { resumeFrom = 0; }
|
||||
}
|
||||
|
||||
using var req = new HttpRequestMessage(HttpMethod.Get, url);
|
||||
if (resumeFrom > 0)
|
||||
req.Headers.Range = new RangeHeaderValue(resumeFrom, null);
|
||||
|
||||
using var response = await http.SendAsync(req, HttpCompletionOption.ResponseHeadersRead, ct)
|
||||
.ConfigureAwait(false);
|
||||
response.EnsureSuccessStatusCode();
|
||||
|
||||
var canResume = response.StatusCode == HttpStatusCode.PartialContent && resumeFrom > 0;
|
||||
long? total = response.Content.Headers.ContentLength;
|
||||
|
||||
if (canResume)
|
||||
{
|
||||
// 校验服务器确实从我们要的位置开始返回:Content-Range: bytes START-END/TOTAL
|
||||
var range = response.Content.Headers.ContentRange;
|
||||
if (range?.HasRange == true && range.From == resumeFrom && range.Length.HasValue)
|
||||
{
|
||||
total = range.Length.Value;
|
||||
}
|
||||
else
|
||||
{
|
||||
// 服务器忽略了 Range 或给出的范围对不上:从头覆盖,避免拼接出损坏的文件
|
||||
canResume = false;
|
||||
resumeFrom = 0;
|
||||
}
|
||||
}
|
||||
|
||||
var mode = canResume ? FileMode.Append : FileMode.Create;
|
||||
var dir = Path.GetDirectoryName(partPath);
|
||||
if (!string.IsNullOrEmpty(dir)) Directory.CreateDirectory(dir);
|
||||
|
||||
await using (var input = await response.Content.ReadAsStreamAsync(ct).ConfigureAwait(false))
|
||||
await using (var output = new FileStream(partPath, mode, FileAccess.Write, FileShare.Read,
|
||||
81920, useAsync: true))
|
||||
{
|
||||
var buffer = new byte[81920];
|
||||
long done = resumeFrom;
|
||||
int read;
|
||||
while ((read = await input.ReadAsync(buffer.AsMemory(), ct).ConfigureAwait(false)) > 0)
|
||||
{
|
||||
await output.WriteAsync(buffer.AsMemory(0, read), ct).ConfigureAwait(false);
|
||||
done += read;
|
||||
// Total 未知时用已下载量当分母,进度条会停在 100% 之前但不报错
|
||||
progress?.Report((done, total ?? done));
|
||||
}
|
||||
}
|
||||
|
||||
return SafeLength(partPath);
|
||||
}
|
||||
|
||||
private static long SafeLength(string path)
|
||||
{
|
||||
try { return new FileInfo(path).Length; }
|
||||
catch { return 0; }
|
||||
}
|
||||
}
|
||||
+10
-1
@@ -84,12 +84,21 @@ internal sealed class Applier
|
||||
var manifestText = File.Exists(manifestPath) ? File.ReadAllText(manifestPath) : null;
|
||||
var verification = ManifestSignature.Verify(manifestText, require);
|
||||
|
||||
if (verification.IsRejected)
|
||||
// 签名不对(被改过 / 密钥不认识)永远拒绝;仅「没有签名」在明确不强制时放行。
|
||||
// 之前这里不看 require:即使调用方声明 requireSignature=false(开发态、测试),
|
||||
// 未签名清单也会被当成验签失败直接拒掉。
|
||||
var hostile = verification.Trust == ManifestTrust.Invalid;
|
||||
if (hostile || (verification.IsRejected && require))
|
||||
{
|
||||
_log.Error($"清单验签失败({verification.Trust}):{verification.Error}",
|
||||
$"Manifest signature check failed ({verification.Trust}): {verification.Error}");
|
||||
return Refuse(updateDir, request, verification);
|
||||
}
|
||||
if (verification.IsRejected)
|
||||
{
|
||||
_log.Warn($"清单未签名,按调用方要求放行:{verification.Error}",
|
||||
$"Manifest is unsigned; continuing as requested: {verification.Error}");
|
||||
}
|
||||
_log.Info($"清单可信度:{verification.Trust}" +
|
||||
(verification.KeyId != null ? $"({verification.KeyId})" : ""),
|
||||
$"Manifest trust: {verification.Trust}" +
|
||||
|
||||
@@ -37,6 +37,11 @@
|
||||
<DebugType>none</DebugType>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<!-- 应用器测试要直接构造 Applier(internal):只对测试程序集放开可见性 -->
|
||||
<InternalsVisibleTo Include="GC.Savedog.Tests" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<!-- 与启动器共用同一份安全实现,避免两套逻辑各说各话。
|
||||
ManifestLoader 依赖启动器的 RepoVersion 模型,守护进程不需要,排除。 -->
|
||||
|
||||
@@ -29,7 +29,9 @@ public sealed class AvaloniaHost
|
||||
private readonly AppServices _services;
|
||||
private readonly object _gate = new();
|
||||
private readonly Dictionary<string, PlayerWindow> _windows = new(StringComparer.OrdinalIgnoreCase);
|
||||
private Task<bool>? _startTask;
|
||||
private readonly TaskCompletionSource<bool> _ready =
|
||||
new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
private int _started;
|
||||
|
||||
public AvaloniaHost(AppServices services) => _services = services;
|
||||
|
||||
@@ -37,56 +39,60 @@ public sealed class AvaloniaHost
|
||||
|
||||
public string? LastError { get; private set; }
|
||||
|
||||
public Task<bool> EnsureStartedAsync()
|
||||
/// <summary>
|
||||
/// 后端线程调用:等待「主线程已把 Avalonia 事件循环跑起来」。
|
||||
///
|
||||
/// 关键点:macOS 的 AppKit 要求 NSApplication 在**主线程**。以前这里把
|
||||
/// <c>StartWithClassicDesktopLifetime</c> 丢到一个新建的后台线程里跑,在 macOS 上
|
||||
/// 会直接崩掉整个后端进程(表现为点「启动模型」界面无反应、随后后端消失)。
|
||||
/// 现在改为由启动器在主线程调用 <see cref="RunOnCurrentThread"/>,
|
||||
/// 这里只等待就绪信号。
|
||||
/// </summary>
|
||||
public Task<bool> EnsureStartedAsync() => _ready.Task;
|
||||
|
||||
/// <summary>
|
||||
/// 必须在 UI 主线程调用。启动 Avalonia 桌面生命周期并阻塞,直到 <see cref="Shutdown"/>。
|
||||
/// 返回后(或初始化失败后)调用方负责收尾。
|
||||
/// </summary>
|
||||
public void RunOnCurrentThread()
|
||||
{
|
||||
lock (_gate)
|
||||
if (Interlocked.Exchange(ref _started, 1) == 1) return;
|
||||
|
||||
try
|
||||
{
|
||||
_startTask ??= Task.Run(StartCore);
|
||||
return _startTask;
|
||||
AppBuilder.Configure<HostApp>()
|
||||
.UsePlatformDetect()
|
||||
.AfterSetup(_ =>
|
||||
{
|
||||
IsAvailable = true;
|
||||
_ready.TrySetResult(true);
|
||||
})
|
||||
.StartWithClassicDesktopLifetime(Array.Empty<string>());
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
// 无桌面会话(CI / 无头环境):模型窗口不可用,但后端其余接口照常。
|
||||
LastError = ex.Message;
|
||||
_ready.TrySetResult(false);
|
||||
}
|
||||
}
|
||||
|
||||
private bool StartCore()
|
||||
/// <summary>从任意线程请求结束事件循环,使 <see cref="RunOnCurrentThread"/> 返回。</summary>
|
||||
public void Shutdown()
|
||||
{
|
||||
var ready = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
|
||||
var thread = new Thread(() =>
|
||||
if (_started == 0) return;
|
||||
try
|
||||
{
|
||||
try
|
||||
Dispatcher.UIThread.Post(() =>
|
||||
{
|
||||
AppBuilder.Configure<HostApp>()
|
||||
.UsePlatformDetect()
|
||||
.AfterSetup(_ => ready.TrySetResult(true))
|
||||
.StartWithClassicDesktopLifetime(Array.Empty<string>());
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
LastError = ex.Message;
|
||||
ready.TrySetResult(false);
|
||||
}
|
||||
})
|
||||
{
|
||||
IsBackground = true,
|
||||
Name = "gc-ui-avalonia"
|
||||
};
|
||||
|
||||
// Windows 上 Avalonia 需要 STA 线程;macOS / Linux 不支持也不必要。
|
||||
if (OperatingSystem.IsWindows())
|
||||
{
|
||||
try { thread.SetApartmentState(ApartmentState.STA); }
|
||||
catch { /* 忽略:部分运行时不允许设置 */ }
|
||||
if (Application.Current?.ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
|
||||
desktop.Shutdown();
|
||||
});
|
||||
}
|
||||
|
||||
thread.Start();
|
||||
|
||||
if (!ready.Task.Wait(TimeSpan.FromSeconds(30)))
|
||||
catch
|
||||
{
|
||||
LastError = "图形环境初始化超时";
|
||||
return false;
|
||||
// 事件循环尚未建立或已退出:无需处理
|
||||
}
|
||||
|
||||
IsAvailable = ready.Task.Result;
|
||||
return IsAvailable;
|
||||
}
|
||||
|
||||
/// <summary>在 Avalonia UI 线程上加载模型并打开它自己的窗口。</summary>
|
||||
|
||||
@@ -30,19 +30,33 @@ public static class BackendServer
|
||||
{
|
||||
/// <summary>按命令行 / GC_UI_PORT 解析端口并构建(未启动)的后端。</summary>
|
||||
public static WebApplication StartFromCommandLine(string[] args)
|
||||
=> Start(args, ResolvePort(args));
|
||||
=> Start(args, ResolvePort(args), out _);
|
||||
|
||||
/// <summary>同上,并交出模型窗口宿主(独立进程入口用:主线程留给 Avalonia)。</summary>
|
||||
public static WebApplication StartFromCommandLine(string[] args, out AvaloniaHost uiHost)
|
||||
=> Start(args, ResolvePort(args), out uiHost);
|
||||
|
||||
/// <summary>
|
||||
/// 构建后端。返回的 <see cref="WebApplication"/> 尚未启动:
|
||||
/// 独立进程直接 <c>Run()</c>,启动器用 <c>StartAsync()</c> 之后继续拉起界面。
|
||||
/// </summary>
|
||||
public static WebApplication Start(string[] args, int port)
|
||||
=> Start(args, port, out _);
|
||||
|
||||
/// <summary>
|
||||
/// 构建后端,并通过 <paramref name="uiHost"/> 交出模型窗口宿主。
|
||||
///
|
||||
/// 调用方(启动器)必须在**主线程**调用 <see cref="AvaloniaHost.RunOnCurrentThread"/>:
|
||||
/// macOS 的 AppKit 要求 NSApplication 运行在主线程,否则打开模型窗口时整个进程会崩溃。
|
||||
/// </summary>
|
||||
public static WebApplication Start(string[] args, int port, out AvaloniaHost uiHost)
|
||||
{
|
||||
// 下载模块(GC-DOWNLOAD)通过宿主钩子注入,和 GC-BOOT 的做法一致。
|
||||
DownloadModuleHost.Factory = new DownloadModuleFactory();
|
||||
|
||||
var services = AppServices.Create();
|
||||
var uiHost = new AvaloniaHost(services);
|
||||
var host = new AvaloniaHost(services);
|
||||
uiHost = host;
|
||||
|
||||
var builder = WebApplication.CreateBuilder(new WebApplicationOptions { Args = args });
|
||||
builder.Logging.ClearProviders();
|
||||
@@ -161,8 +175,8 @@ public static class BackendServer
|
||||
true,
|
||||
LauncherRuntimeInfo.CurrentLauncherVersion,
|
||||
LauncherRuntimeInfo.CurrentRid,
|
||||
uiHost.IsAvailable,
|
||||
uiHost.LastError)));
|
||||
host.IsAvailable,
|
||||
host.LastError)));
|
||||
|
||||
// ---- 已安装模型 -----------------------------------------------------------
|
||||
|
||||
@@ -190,7 +204,7 @@ public static class BackendServer
|
||||
try
|
||||
{
|
||||
services.Memory.Refresh();
|
||||
var message = await uiHost.LaunchAsync(package);
|
||||
var message = await host.LaunchAsync(package);
|
||||
return Results.Ok(new LaunchResultDto(true, message));
|
||||
}
|
||||
catch (Exception ex)
|
||||
|
||||
@@ -1,6 +1,22 @@
|
||||
using GC.UI.Server;
|
||||
using Microsoft.Extensions.Hosting;
|
||||
|
||||
// 独立进程入口:`GC.UI.Server --port 17890`
|
||||
// 启动器在进程内直接调用 BackendServer.Start,不会走到这里。
|
||||
var app = BackendServer.StartFromCommandLine(args);
|
||||
app.Run();
|
||||
var app = BackendServer.StartFromCommandLine(args, out var host);
|
||||
|
||||
// 模型窗口由 Avalonia 承载,macOS 的 AppKit 要求 NSApplication 在主线程。
|
||||
// 所以后端交给 Kestrel 自己的线程池在后台跑,主线程留给 Avalonia 事件循环。
|
||||
app.StartAsync().GetAwaiter().GetResult();
|
||||
host.RunOnCurrentThread();
|
||||
|
||||
if (host.IsAvailable)
|
||||
{
|
||||
// 事件循环结束 → 收尾后端
|
||||
app.StopAsync().GetAwaiter().GetResult();
|
||||
}
|
||||
else
|
||||
{
|
||||
// 无图形环境(无头调试):退化为纯后端常驻
|
||||
app.WaitForShutdown();
|
||||
}
|
||||
+6
-2332
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,405 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../api_client.dart';
|
||||
import '../controller.dart';
|
||||
import '../i18n.dart';
|
||||
import '../theme.dart';
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 关于页(从原 pages.dart 拆出,公开类名不变)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 关于页
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
class AboutPageView extends StatefulWidget {
|
||||
const AboutPageView({super.key, required this.controller, this.initialAbout});
|
||||
|
||||
final ShellController controller;
|
||||
|
||||
/// 预置数据(仅用于测试 / 截图,正常运行时为 null,由后端提供)。
|
||||
final AboutInfo? initialAbout;
|
||||
|
||||
@override
|
||||
State<AboutPageView> createState() => _AboutPageViewState();
|
||||
}
|
||||
|
||||
class _AboutPageViewState extends State<AboutPageView> {
|
||||
AboutInfo? _about;
|
||||
bool _loading = true;
|
||||
String? _error;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
final preset = widget.initialAbout;
|
||||
if (preset != null) {
|
||||
_about = preset;
|
||||
_loading = false;
|
||||
return;
|
||||
}
|
||||
_load();
|
||||
}
|
||||
|
||||
Future<void> _load() async {
|
||||
setState(() {
|
||||
_loading = true;
|
||||
_error = null;
|
||||
});
|
||||
try {
|
||||
final about = await widget.controller.api.about();
|
||||
if (!mounted) return;
|
||||
setState(() {
|
||||
_about = about;
|
||||
_loading = false;
|
||||
});
|
||||
} catch (error) {
|
||||
if (!mounted) return;
|
||||
setState(() {
|
||||
_error = error.toString();
|
||||
_loading = false;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return ListView(
|
||||
padding: const EdgeInsets.fromLTRB(
|
||||
GcSpace.xxl,
|
||||
GcSpace.xxl,
|
||||
GcSpace.xxl,
|
||||
GcSpace.xxxl,
|
||||
),
|
||||
children: <Widget>[
|
||||
GcPageHeader(
|
||||
title: T('nav.about'),
|
||||
subtitle: T('app.tagline'),
|
||||
),
|
||||
const SizedBox(height: GcSpace.xxl),
|
||||
if (_loading)
|
||||
const Padding(
|
||||
padding: EdgeInsets.symmetric(vertical: 48),
|
||||
child: Center(
|
||||
child: SizedBox(
|
||||
width: 22,
|
||||
height: 22,
|
||||
child: CircularProgressIndicator(strokeWidth: 2),
|
||||
),
|
||||
),
|
||||
)
|
||||
else if (_error != null)
|
||||
GcMessage(
|
||||
title: T('common.error'),
|
||||
message: _error,
|
||||
icon: Icons.error_outline_rounded,
|
||||
color: GcColors.danger,
|
||||
action: OutlinedButton(
|
||||
onPressed: _load,
|
||||
child: Text(T('common.retry')),
|
||||
),
|
||||
)
|
||||
else ...<Widget>[
|
||||
_versionCard(),
|
||||
const SizedBox(height: GcSpace.lg),
|
||||
_contributorsCard(),
|
||||
const SizedBox(height: GcSpace.lg),
|
||||
_thanksCard(),
|
||||
],
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
Widget _versionCard() {
|
||||
final about = _about;
|
||||
|
||||
// 左边身份卡、右边信息表:宽屏两栏,窄屏自动堆叠。
|
||||
final identity = Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: <Widget>[
|
||||
Row(
|
||||
children: <Widget>[
|
||||
Container(
|
||||
width: 44,
|
||||
height: 44,
|
||||
alignment: Alignment.center,
|
||||
decoration: BoxDecoration(
|
||||
color: GcColors.accentSoft,
|
||||
borderRadius: BorderRadius.circular(GcRadius.card),
|
||||
),
|
||||
child: Text(
|
||||
'◎',
|
||||
style: TextStyle(
|
||||
fontSize: 22, height: 1.1, color: GcColors.accent),
|
||||
),
|
||||
),
|
||||
const SizedBox(width: GcSpace.lg),
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: <Widget>[
|
||||
Text(
|
||||
about?.appName ?? 'Morris GC',
|
||||
style: TextStyle(
|
||||
fontSize: 20,
|
||||
height: 1.3,
|
||||
fontWeight: FontWeight.w600,
|
||||
color: GcColors.ink,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 2),
|
||||
Text(
|
||||
T('app.tagline'),
|
||||
style: TextStyle(
|
||||
fontSize: 12.5,
|
||||
height: 1.5,
|
||||
color: GcColors.faint,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: GcSpace.lg),
|
||||
Wrap(
|
||||
spacing: GcSpace.sm,
|
||||
runSpacing: GcSpace.sm,
|
||||
children: <Widget>[
|
||||
GcPill('v${about?.version ?? '—'}', color: GcColors.accent),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: GcSpace.lg),
|
||||
OutlinedButton(
|
||||
onPressed: () async {
|
||||
final url = about?.repository;
|
||||
if (url == null || url.isEmpty) return;
|
||||
try {
|
||||
await widget.controller.api.openUrl(url);
|
||||
} catch (_) {
|
||||
// 忽略
|
||||
}
|
||||
},
|
||||
child: Text(T('about.openRepository')),
|
||||
),
|
||||
],
|
||||
);
|
||||
|
||||
final details = Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: <Widget>[
|
||||
GcFieldRow(
|
||||
label: T('set.platform'),
|
||||
value: about?.platform ?? '—',
|
||||
),
|
||||
GcFieldRow(
|
||||
label: T('about.architecture'),
|
||||
value: T('about.architectureValue'),
|
||||
),
|
||||
GcFieldRow(
|
||||
label: T('about.sourceLanguage'),
|
||||
value: about?.sourceLanguage ?? 'C#',
|
||||
),
|
||||
GcFieldRow(
|
||||
label: T('about.frontend'),
|
||||
value: about?.frontend ?? 'Flutter',
|
||||
),
|
||||
GcFieldRow(
|
||||
label: T('about.gitService'),
|
||||
value: 'itxiaohui',
|
||||
),
|
||||
GcFieldRow(
|
||||
label: T('set.license'),
|
||||
value: T('set.licenseValue'),
|
||||
),
|
||||
],
|
||||
);
|
||||
|
||||
return GcCard(
|
||||
padding: const EdgeInsets.all(GcSpace.xxl),
|
||||
child: LayoutBuilder(
|
||||
builder: (context, constraints) {
|
||||
if (constraints.maxWidth < 720) {
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: <Widget>[
|
||||
identity,
|
||||
const GcDivider(verticalPadding: GcSpace.lg),
|
||||
details,
|
||||
],
|
||||
);
|
||||
}
|
||||
return Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: <Widget>[
|
||||
Expanded(flex: 4, child: identity),
|
||||
const SizedBox(width: GcSpace.xxxl),
|
||||
Expanded(flex: 5, child: details),
|
||||
],
|
||||
);
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _contributorsCard() {
|
||||
final contributors = _about?.contributors ?? const <ContributorInfo>[];
|
||||
return GcCard(
|
||||
padding: const EdgeInsets.all(GcSpace.xxl),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: <Widget>[
|
||||
GcSectionTitle(
|
||||
T('about.developers'),
|
||||
subtitle: T('about.contributorsHint'),
|
||||
),
|
||||
const SizedBox(height: GcSpace.lg),
|
||||
if (contributors.isEmpty)
|
||||
GcHint(T('about.noContributors'))
|
||||
else
|
||||
Wrap(
|
||||
spacing: GcSpace.xl,
|
||||
runSpacing: GcSpace.md,
|
||||
children: <Widget>[
|
||||
for (final contributor in contributors)
|
||||
SizedBox(
|
||||
width: 220,
|
||||
child: Row(
|
||||
children: <Widget>[
|
||||
CircleAvatar(
|
||||
radius: 18,
|
||||
backgroundColor: GcColors.surfaceAlt,
|
||||
backgroundImage: contributor.avatarUrl == null
|
||||
? null
|
||||
: NetworkImage(contributor.avatarUrl!),
|
||||
child: contributor.avatarUrl == null
|
||||
? Text(
|
||||
'◎',
|
||||
style: TextStyle(
|
||||
fontSize: 14,
|
||||
color: GcColors.accent,
|
||||
),
|
||||
)
|
||||
: null,
|
||||
),
|
||||
const SizedBox(width: GcSpace.md),
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: <Widget>[
|
||||
Text(
|
||||
contributor.name,
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: TextStyle(
|
||||
fontSize: 13,
|
||||
height: 1.4,
|
||||
fontWeight: FontWeight.w600,
|
||||
color: GcColors.ink,
|
||||
),
|
||||
),
|
||||
Text(
|
||||
T(
|
||||
'about.contributions',
|
||||
<Object?>[contributor.contributions],
|
||||
),
|
||||
style: TextStyle(
|
||||
fontSize: 11.5,
|
||||
height: 1.4,
|
||||
color: GcColors.faint,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/// 特别感谢:与「开发者」分开列 —— 提供 Git 服务不等于往仓库提交代码,
|
||||
/// 混进贡献者列表会让提交数失去意义。
|
||||
Widget _thanksCard() {
|
||||
return GcCard(
|
||||
padding: const EdgeInsets.all(GcSpace.xxl),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: <Widget>[
|
||||
GcSectionTitle(
|
||||
T('about.thanks'),
|
||||
subtitle: T('about.thanksHint'),
|
||||
),
|
||||
const SizedBox(height: GcSpace.lg),
|
||||
Wrap(
|
||||
spacing: GcSpace.xl,
|
||||
runSpacing: GcSpace.md,
|
||||
children: <Widget>[
|
||||
_creditTile('地理洪老师', 'about.thanksGeo'),
|
||||
_creditTile('itxiaohui', 'about.thanksGit'),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _creditTile(String name, String roleKey) {
|
||||
return SizedBox(
|
||||
width: 220,
|
||||
child: Row(
|
||||
children: <Widget>[
|
||||
CircleAvatar(
|
||||
radius: 18,
|
||||
backgroundColor: GcColors.surfaceAlt,
|
||||
child: Text(
|
||||
'◎',
|
||||
style: TextStyle(fontSize: 14, color: GcColors.accent),
|
||||
),
|
||||
),
|
||||
const SizedBox(width: GcSpace.md),
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: <Widget>[
|
||||
Text(
|
||||
name,
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: TextStyle(
|
||||
fontSize: 13,
|
||||
height: 1.4,
|
||||
fontWeight: FontWeight.w600,
|
||||
color: GcColors.ink,
|
||||
),
|
||||
),
|
||||
Text(
|
||||
T(roleKey),
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: TextStyle(
|
||||
fontSize: 11.5,
|
||||
height: 1.4,
|
||||
color: GcColors.faint,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,579 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../api_client.dart';
|
||||
import '../controller.dart';
|
||||
import '../i18n.dart';
|
||||
import '../theme.dart';
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 下载页(从原 pages.dart 拆出,公开类名不变)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 下载页
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
class DownloadPageView extends StatefulWidget {
|
||||
const DownloadPageView({
|
||||
super.key,
|
||||
required this.controller,
|
||||
this.initialSources,
|
||||
this.initialIndex,
|
||||
this.initialJobs,
|
||||
});
|
||||
|
||||
final ShellController controller;
|
||||
|
||||
/// 预置数据(仅用于测试 / 截图,正常运行时为 null,由后端提供)。
|
||||
final List<SourceInfo>? initialSources;
|
||||
final SourceIndexInfo? initialIndex;
|
||||
final List<JobInfo>? initialJobs;
|
||||
|
||||
@override
|
||||
State<DownloadPageView> createState() => _DownloadPageViewState();
|
||||
}
|
||||
|
||||
class _DownloadPageViewState extends State<DownloadPageView> {
|
||||
List<SourceInfo> _sources = const <SourceInfo>[];
|
||||
SourceIndexInfo? _index;
|
||||
List<JobInfo> _jobs = const <JobInfo>[];
|
||||
String? _selectedSourceId;
|
||||
bool _loading = true;
|
||||
String? _error;
|
||||
Timer? _poll;
|
||||
|
||||
/// 页面是否可见(被切走后仍保活,但没必要继续请求后端)。
|
||||
bool _visible = true;
|
||||
|
||||
/// 上一次轮询时是否有活跃任务,用来判断「刚刚全部结束」。
|
||||
bool _hadActive = false;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
final presetSources = widget.initialSources;
|
||||
if (presetSources != null) {
|
||||
_sources = presetSources;
|
||||
_index = widget.initialIndex;
|
||||
_jobs = widget.initialJobs ?? const <JobInfo>[];
|
||||
_selectedSourceId = presetSources.isEmpty ? null : presetSources.first.id;
|
||||
_loading = false;
|
||||
return;
|
||||
}
|
||||
_load();
|
||||
_schedulePoll(const Duration(seconds: 2));
|
||||
}
|
||||
|
||||
@override
|
||||
void didChangeDependencies() {
|
||||
super.didChangeDependencies();
|
||||
// TickerMode 由外壳的 Offstage 控制:切到别的页时变 false。
|
||||
_visible = TickerMode.of(context);
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_poll?.cancel();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
/// 单次 Timer 链:有活跃任务时 1 秒一次,空闲时降到 5 秒,不可见时 10 秒。
|
||||
///
|
||||
/// 以前是 `Timer.periodic(1s)` 且永不停止 —— 只要进过下载页,之后每秒都
|
||||
/// 在请求 `/api/download/jobs`,哪怕没有任何任务、页面也早就切走了。
|
||||
void _schedulePoll(Duration delay) {
|
||||
_poll?.cancel();
|
||||
_poll = Timer(delay, _pollOnce);
|
||||
}
|
||||
|
||||
Future<void> _pollOnce() async {
|
||||
if (!mounted) return;
|
||||
|
||||
if (!_visible) {
|
||||
_schedulePoll(const Duration(seconds: 10));
|
||||
return;
|
||||
}
|
||||
|
||||
_hadActive = _jobs.any((job) => job.isActive);
|
||||
await _refreshJobs();
|
||||
if (!mounted) return;
|
||||
|
||||
final active = _jobs.any((job) => job.isActive);
|
||||
// 活跃 → 空闲:这一轮里下载结束了,首页的模型列表已经过期。
|
||||
if (_hadActive && !active) widget.controller.modelsChanged();
|
||||
_hadActive = active;
|
||||
|
||||
_schedulePoll(Duration(seconds: active ? 1 : 5));
|
||||
}
|
||||
|
||||
Future<void> _load() async {
|
||||
setState(() {
|
||||
_loading = true;
|
||||
_error = null;
|
||||
});
|
||||
try {
|
||||
final sources = await widget.controller.api.sources();
|
||||
final preferred = sources.where((s) => s.enabled).toList();
|
||||
final selected = _selectedSourceId ??
|
||||
(preferred.isNotEmpty
|
||||
? preferred.first.id
|
||||
: (sources.isNotEmpty ? sources.first.id : ''));
|
||||
|
||||
final index = selected.isEmpty
|
||||
? null
|
||||
: await widget.controller.api.remoteModels(sourceId: selected);
|
||||
|
||||
if (!mounted) return;
|
||||
setState(() {
|
||||
_sources = sources;
|
||||
_selectedSourceId = selected;
|
||||
_index = index;
|
||||
_loading = false;
|
||||
});
|
||||
await _refreshJobs();
|
||||
} catch (error) {
|
||||
if (!mounted) return;
|
||||
setState(() {
|
||||
_error = error.toString();
|
||||
_loading = false;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _refreshJobs() async {
|
||||
try {
|
||||
final jobs = await widget.controller.api.jobs();
|
||||
if (!mounted) return;
|
||||
setState(() => _jobs = jobs);
|
||||
} catch (_) {
|
||||
// 轮询失败不打扰用户,下一次再试
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _selectSource(String id) async {
|
||||
setState(() {
|
||||
_selectedSourceId = id;
|
||||
_loading = true;
|
||||
_error = null;
|
||||
});
|
||||
try {
|
||||
final index = await widget.controller.api.remoteModels(sourceId: id);
|
||||
if (!mounted) return;
|
||||
setState(() {
|
||||
_index = index;
|
||||
_loading = false;
|
||||
});
|
||||
} catch (error) {
|
||||
if (!mounted) return;
|
||||
setState(() {
|
||||
_error = error.toString();
|
||||
_loading = false;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _download(RemoteModelInfo model) async {
|
||||
final sourceId = _selectedSourceId;
|
||||
if (sourceId == null) return;
|
||||
try {
|
||||
await widget.controller.api.startDownload(sourceId, model.id);
|
||||
await _refreshJobs();
|
||||
} catch (error) {
|
||||
if (!mounted) return;
|
||||
setState(() => _error = error.toString());
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _jobAction(
|
||||
Future<JobInfo> Function(String id) action, String id) async {
|
||||
try {
|
||||
await action(id);
|
||||
await _refreshJobs();
|
||||
} catch (error) {
|
||||
if (!mounted) return;
|
||||
setState(() => _error = error.toString());
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Padding(
|
||||
padding: const EdgeInsets.fromLTRB(
|
||||
GcSpace.xxl, GcSpace.xxl, GcSpace.xxl, GcSpace.xl),
|
||||
child: Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: <Widget>[
|
||||
SizedBox(width: 268, child: _sourcePanel()),
|
||||
const SizedBox(width: GcSpace.xl),
|
||||
Expanded(child: _modelPanel()),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _sourcePanel() {
|
||||
return GcCard(
|
||||
padding: const EdgeInsets.all(GcSpace.lg),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: <Widget>[
|
||||
GcSectionTitle(T('dl.sources')),
|
||||
const SizedBox(height: GcSpace.xs + 2),
|
||||
GcHint(T('dl.subtitle')),
|
||||
const SizedBox(height: GcSpace.md),
|
||||
for (final source in _sources)
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(bottom: GcSpace.xs + 2),
|
||||
child: _sourceTile(source),
|
||||
),
|
||||
const SizedBox(height: GcSpace.sm),
|
||||
SizedBox(
|
||||
width: double.infinity,
|
||||
child: OutlinedButton.icon(
|
||||
onPressed: _load,
|
||||
icon: const Icon(Icons.refresh_rounded, size: 18),
|
||||
label: Text(T('dl.refresh')),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _sourceTile(SourceInfo source) {
|
||||
final selected = source.id == _selectedSourceId;
|
||||
return Material(
|
||||
color: selected ? GcColors.accentSoft : Colors.transparent,
|
||||
borderRadius: BorderRadius.circular(GcRadius.control),
|
||||
child: InkWell(
|
||||
borderRadius: BorderRadius.circular(GcRadius.control),
|
||||
hoverColor: GcColors.surfaceAlt,
|
||||
onTap: () => _selectSource(source.id),
|
||||
child: Container(
|
||||
padding: const EdgeInsets.symmetric(
|
||||
horizontal: GcSpace.md,
|
||||
vertical: GcSpace.md - 2,
|
||||
),
|
||||
decoration: BoxDecoration(
|
||||
borderRadius: BorderRadius.circular(GcRadius.control),
|
||||
border: Border.all(
|
||||
color: selected
|
||||
? GcColors.accent.withOpacity(0.45)
|
||||
: Colors.transparent,
|
||||
),
|
||||
),
|
||||
child: Row(
|
||||
children: <Widget>[
|
||||
Icon(
|
||||
selected
|
||||
? Icons.radio_button_checked_rounded
|
||||
: Icons.radio_button_unchecked_rounded,
|
||||
size: 16,
|
||||
color: selected ? GcColors.accent : GcColors.ghost,
|
||||
),
|
||||
const SizedBox(width: GcSpace.sm + 2),
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: <Widget>[
|
||||
Text(
|
||||
source.name,
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: TextStyle(
|
||||
fontSize: 13,
|
||||
height: 1.35,
|
||||
fontWeight: FontWeight.w600,
|
||||
color: selected ? GcColors.accent : GcColors.ink,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 1),
|
||||
Text(
|
||||
source.host,
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: TextStyle(
|
||||
fontSize: 11.5,
|
||||
height: 1.35,
|
||||
color: GcColors.faint,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
if (!source.enabled) const GcPill('off', subtle: true),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _modelPanel() {
|
||||
final models = _index?.models ?? const <RemoteModelInfo>[];
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: <Widget>[
|
||||
GcPageHeader(
|
||||
title: T('dl.available'),
|
||||
subtitle: _index == null
|
||||
? null
|
||||
: (_index!.fromCache
|
||||
? '${T('dl.ready', <Object?>[
|
||||
models.length
|
||||
])} · ${T('dl.fromCache')}'
|
||||
: T('dl.ready', <Object?>[models.length])),
|
||||
trailing: IconButton(
|
||||
tooltip: T('common.refresh'),
|
||||
onPressed: _load,
|
||||
icon: const Icon(Icons.refresh_rounded, size: 18),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: GcSpace.lg),
|
||||
Expanded(
|
||||
child: ListView(
|
||||
padding: const EdgeInsets.only(bottom: GcSpace.sm),
|
||||
children: <Widget>[
|
||||
if (_loading)
|
||||
const Padding(
|
||||
padding: EdgeInsets.symmetric(vertical: 48),
|
||||
child: Center(
|
||||
child: SizedBox(
|
||||
width: 22,
|
||||
height: 22,
|
||||
child: CircularProgressIndicator(strokeWidth: 2),
|
||||
),
|
||||
),
|
||||
)
|
||||
else if (_error != null)
|
||||
GcMessage(
|
||||
title: T('common.error'),
|
||||
message: _error,
|
||||
icon: Icons.cloud_off_rounded,
|
||||
color: GcColors.danger,
|
||||
action: OutlinedButton(
|
||||
onPressed: _load,
|
||||
child: Text(T('common.retry')),
|
||||
),
|
||||
)
|
||||
else if (models.isEmpty)
|
||||
GcMessage(
|
||||
title: T('dl.empty'),
|
||||
message: T('dl.emptyHint'),
|
||||
icon: Icons.inbox_rounded,
|
||||
)
|
||||
else
|
||||
for (final model in models)
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(bottom: GcSpace.md),
|
||||
child: _remoteRow(model),
|
||||
),
|
||||
const SizedBox(height: GcSpace.sm),
|
||||
_jobsPanel(),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
Widget _remoteRow(RemoteModelInfo model) {
|
||||
return GcCard(
|
||||
padding: const EdgeInsets.fromLTRB(
|
||||
GcSpace.lg,
|
||||
GcSpace.md + 2,
|
||||
GcSpace.lg,
|
||||
GcSpace.md + 2,
|
||||
),
|
||||
child: Row(
|
||||
children: <Widget>[
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: <Widget>[
|
||||
Row(
|
||||
children: <Widget>[
|
||||
Flexible(
|
||||
child: Text(
|
||||
model.name,
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: TextStyle(
|
||||
fontSize: 14,
|
||||
height: 1.35,
|
||||
fontWeight: FontWeight.w600,
|
||||
color: GcColors.ink,
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(width: GcSpace.sm),
|
||||
Text(
|
||||
'v${model.version} · ${model.sizeText}',
|
||||
style: TextStyle(
|
||||
fontSize: 12,
|
||||
height: 1.35,
|
||||
color: GcColors.faint,
|
||||
),
|
||||
),
|
||||
if (model.installed) ...<Widget>[
|
||||
const SizedBox(width: GcSpace.sm),
|
||||
GcPill(T('dl.installed'), color: GcColors.ok),
|
||||
],
|
||||
],
|
||||
),
|
||||
const SizedBox(height: GcSpace.xs + 1),
|
||||
Text(
|
||||
model.description,
|
||||
maxLines: 2,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: TextStyle(
|
||||
fontSize: 12.5,
|
||||
height: 1.5,
|
||||
color: GcColors.muted,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
const SizedBox(width: GcSpace.lg),
|
||||
if (model.installed)
|
||||
OutlinedButton(
|
||||
onPressed: () => _download(model),
|
||||
child: Text(T('dl.reinstall')),
|
||||
)
|
||||
else
|
||||
FilledButton(
|
||||
onPressed: () => _download(model),
|
||||
child: Text(T('dl.download')),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _jobsPanel() {
|
||||
return GcCard(
|
||||
padding: const EdgeInsets.all(GcSpace.lg),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: <Widget>[
|
||||
GcSectionTitle(
|
||||
T('dl.background'),
|
||||
trailing: TextButton(
|
||||
onPressed: () async {
|
||||
try {
|
||||
await widget.controller.api.clearFinished();
|
||||
await _refreshJobs();
|
||||
} catch (_) {
|
||||
// 忽略
|
||||
}
|
||||
},
|
||||
child: Text(T('dl.clearDone')),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: GcSpace.md),
|
||||
if (_jobs.isEmpty)
|
||||
GcHint(T('dl.bgEmpty'))
|
||||
else
|
||||
for (final job in _jobs)
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(bottom: GcSpace.md),
|
||||
child: _jobRow(job),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _jobRow(JobInfo job) {
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: <Widget>[
|
||||
Row(
|
||||
children: <Widget>[
|
||||
Expanded(
|
||||
child: Text(
|
||||
'${job.name} v${job.version}',
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: TextStyle(
|
||||
fontSize: 13,
|
||||
height: 1.35,
|
||||
fontWeight: FontWeight.w600,
|
||||
color: GcColors.ink,
|
||||
),
|
||||
),
|
||||
),
|
||||
GcPill(
|
||||
_stateLabel(job.state),
|
||||
color: job.state == 'Failed'
|
||||
? GcColors.danger
|
||||
: job.state == 'Completed'
|
||||
? GcColors.ok
|
||||
: GcColors.accent,
|
||||
),
|
||||
const SizedBox(width: GcSpace.sm),
|
||||
if (job.isActive)
|
||||
TextButton(
|
||||
onPressed: () =>
|
||||
_jobAction(widget.controller.api.cancelJob, job.id),
|
||||
child: Text(T('dl.cancel')),
|
||||
)
|
||||
else if (job.canRetry)
|
||||
TextButton(
|
||||
onPressed: () =>
|
||||
_jobAction(widget.controller.api.retryJob, job.id),
|
||||
child: Text(T('dl.retry')),
|
||||
)
|
||||
else
|
||||
TextButton(
|
||||
onPressed: () =>
|
||||
_jobAction(widget.controller.api.removeJob, job.id),
|
||||
child: Text(T('dl.removeTask')),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: GcSpace.sm - 2),
|
||||
ClipRRect(
|
||||
borderRadius: BorderRadius.circular(2),
|
||||
child: LinearProgressIndicator(
|
||||
value: job.progress.clamp(0, 1).toDouble(),
|
||||
minHeight: 4,
|
||||
backgroundColor: GcColors.surfaceAlt,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: GcSpace.xs + 1),
|
||||
Text(
|
||||
job.error ?? job.detailText,
|
||||
style: TextStyle(
|
||||
fontSize: 11.5,
|
||||
height: 1.4,
|
||||
color: GcColors.faint,
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
String _stateLabel(String state) {
|
||||
switch (state) {
|
||||
case 'Queued':
|
||||
return T('dl.status.queued');
|
||||
case 'Running':
|
||||
case 'Downloading':
|
||||
return T('dl.status.downloading');
|
||||
case 'Completed':
|
||||
return T('dl.status.done');
|
||||
case 'Failed':
|
||||
return T('dl.status.failed');
|
||||
case 'Canceled':
|
||||
return T('dl.status.canceled');
|
||||
default:
|
||||
return state;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,690 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../api_client.dart';
|
||||
import '../controller.dart';
|
||||
import '../i18n.dart';
|
||||
import '../theme.dart';
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 首页:模型库(从原 pages.dart 拆出,公开类名不变)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 首页:模型库
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
class HomePageView extends StatefulWidget {
|
||||
const HomePageView({super.key, required this.controller, this.initialModels});
|
||||
|
||||
final ShellController controller;
|
||||
|
||||
/// 预置模型列表(仅用于测试 / 截图,正常运行时为 null,由后端提供)。
|
||||
final List<ModelInfo>? initialModels;
|
||||
|
||||
@override
|
||||
State<HomePageView> createState() => _HomePageViewState();
|
||||
}
|
||||
|
||||
class _HomePageViewState extends State<HomePageView> {
|
||||
List<ModelInfo> _models = const <ModelInfo>[];
|
||||
bool _loading = true;
|
||||
String? _error;
|
||||
String? _notice;
|
||||
int _lastRevision = 0;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
widget.controller.addListener(_onControllerChanged);
|
||||
_lastRevision = widget.controller.modelsRevision;
|
||||
|
||||
final preset = widget.initialModels;
|
||||
if (preset != null) {
|
||||
_models = preset;
|
||||
_loading = false;
|
||||
} else {
|
||||
_load();
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
widget.controller.removeListener(_onControllerChanged);
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
/// 下载完成 / 删除模型后重新拉列表:页面被 Offstage 保活,不会自己重建。
|
||||
void _onControllerChanged() {
|
||||
if (!mounted) return;
|
||||
final revision = widget.controller.modelsRevision;
|
||||
if (revision == _lastRevision) return;
|
||||
_lastRevision = revision;
|
||||
if (widget.initialModels != null) return; // 截图 / 测试用的预置数据
|
||||
_load();
|
||||
}
|
||||
|
||||
Future<void> _load() async {
|
||||
setState(() {
|
||||
_loading = true;
|
||||
_error = null;
|
||||
});
|
||||
try {
|
||||
final models = await widget.controller.api.models();
|
||||
if (!mounted) return;
|
||||
setState(() {
|
||||
_models = models;
|
||||
_loading = false;
|
||||
});
|
||||
} catch (error) {
|
||||
if (!mounted) return;
|
||||
setState(() {
|
||||
_error = error.toString();
|
||||
_loading = false;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _launch(ModelInfo model) async {
|
||||
setState(() => _notice = null);
|
||||
try {
|
||||
final result = await widget.controller.api.launchModel(model.id);
|
||||
if (!mounted) return;
|
||||
setState(() => _notice = result.message);
|
||||
} catch (error) {
|
||||
if (!mounted) return;
|
||||
setState(() => _notice = error.toString());
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _delete(ModelInfo model) async {
|
||||
final confirmed = await showDialog<bool>(
|
||||
context: context,
|
||||
builder: (context) => AlertDialog(
|
||||
backgroundColor: GcColors.surface,
|
||||
title: Text(T('common.confirmTitle')),
|
||||
content: Text(T('home.deleteConfirm', <Object?>[model.name])),
|
||||
actions: <Widget>[
|
||||
TextButton(
|
||||
onPressed: () => Navigator.of(context).pop(false),
|
||||
child: Text(T('common.cancel')),
|
||||
),
|
||||
FilledButton(
|
||||
onPressed: () => Navigator.of(context).pop(true),
|
||||
child: Text(T('common.delete')),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
if (confirmed != true) return;
|
||||
|
||||
try {
|
||||
await widget.controller.api.deleteModel(model.id);
|
||||
await _load();
|
||||
} catch (error) {
|
||||
if (!mounted) return;
|
||||
setState(() => _notice = error.toString());
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _openFolder(String path) async {
|
||||
try {
|
||||
await widget.controller.api.openFolder(path);
|
||||
} catch (error) {
|
||||
if (!mounted) return;
|
||||
setState(() => _notice = error.toString());
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final settings = widget.controller.settings;
|
||||
return RefreshIndicator(
|
||||
onRefresh: _load,
|
||||
color: GcColors.accent,
|
||||
backgroundColor: GcColors.surface,
|
||||
child: ListView(
|
||||
physics: const AlwaysScrollableScrollPhysics(),
|
||||
padding: const EdgeInsets.fromLTRB(
|
||||
GcSpace.xxl, GcSpace.xxl, GcSpace.xxl, GcSpace.xxxl),
|
||||
children: <Widget>[
|
||||
_hero(settings),
|
||||
const SizedBox(height: GcSpace.xxl),
|
||||
_sectionHeader(),
|
||||
if (_notice != null) ...<Widget>[
|
||||
const SizedBox(height: GcSpace.md),
|
||||
GcMessage(
|
||||
title: _notice!,
|
||||
icon: Icons.info_outline_rounded,
|
||||
color: GcColors.warn,
|
||||
),
|
||||
],
|
||||
const SizedBox(height: GcSpace.lg),
|
||||
if (_loading)
|
||||
const Padding(
|
||||
padding: EdgeInsets.symmetric(vertical: 48),
|
||||
child: Center(
|
||||
child: SizedBox(
|
||||
width: 22,
|
||||
height: 22,
|
||||
child: CircularProgressIndicator(strokeWidth: 2),
|
||||
),
|
||||
),
|
||||
)
|
||||
else if (_error != null)
|
||||
GcMessage(
|
||||
title: T('common.error'),
|
||||
message: _error,
|
||||
icon: Icons.cloud_off_rounded,
|
||||
color: GcColors.danger,
|
||||
action: OutlinedButton(
|
||||
onPressed: _load,
|
||||
child: Text(T('common.retry')),
|
||||
),
|
||||
)
|
||||
else if (_models.isEmpty)
|
||||
_emptyState()
|
||||
else
|
||||
LayoutBuilder(
|
||||
builder: (context, constraints) {
|
||||
const spacing = GcSpace.lg;
|
||||
final columns =
|
||||
(constraints.maxWidth / 320).floor().clamp(1, 4);
|
||||
final cardWidth =
|
||||
(constraints.maxWidth - spacing * (columns - 1)) / columns;
|
||||
return Wrap(
|
||||
spacing: spacing,
|
||||
runSpacing: spacing,
|
||||
children: <Widget>[
|
||||
for (final model in _models)
|
||||
SizedBox(
|
||||
width: cardWidth,
|
||||
child: _ModelCard(
|
||||
model: model,
|
||||
previewUrl: widget.controller.api.previewUrl(model),
|
||||
onLaunch: () => _launch(model),
|
||||
onOpenFolder: () => _openFolder(model.directory),
|
||||
onDelete: () => _delete(model),
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
},
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/// 顶部横幅:产品定位 + 主操作 + 关键指标。
|
||||
///
|
||||
/// 不用渐变:深色主题下的低对比渐变会让整块区域发灰,看起来就是「糊」。
|
||||
Widget _hero(SettingsInfo? settings) {
|
||||
final enabledSources =
|
||||
settings?.sources.where((s) => s.enabled).length ?? 0;
|
||||
return GcCard(
|
||||
padding: const EdgeInsets.all(GcSpace.xxl + 2),
|
||||
child: Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: <Widget>[
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: <Widget>[
|
||||
Text(
|
||||
'MODEL LIBRARY',
|
||||
style: TextStyle(
|
||||
fontSize: 11,
|
||||
height: 1.2,
|
||||
letterSpacing: 1.4,
|
||||
fontWeight: FontWeight.w600,
|
||||
color: GcColors.accent,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: GcSpace.md),
|
||||
Text(
|
||||
T('home.title'),
|
||||
style: TextStyle(
|
||||
fontSize: 26,
|
||||
height: 1.25,
|
||||
fontWeight: FontWeight.w600,
|
||||
letterSpacing: -0.2,
|
||||
color: GcColors.ink,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: GcSpace.sm),
|
||||
ConstrainedBox(
|
||||
constraints: const BoxConstraints(maxWidth: 460),
|
||||
child: Text(
|
||||
T('home.subtitle'),
|
||||
style: TextStyle(
|
||||
fontSize: 13,
|
||||
height: 1.65,
|
||||
color: GcColors.muted,
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: GcSpace.xl),
|
||||
Row(
|
||||
children: <Widget>[
|
||||
FilledButton.icon(
|
||||
onPressed:
|
||||
_models.isEmpty ? null : () => _launch(_models.first),
|
||||
icon: const Icon(Icons.play_arrow_rounded, size: 18),
|
||||
label: Text(T('home.launch')),
|
||||
),
|
||||
const SizedBox(width: GcSpace.md),
|
||||
OutlinedButton(
|
||||
onPressed: () => widget.controller.goTo(1),
|
||||
child: Text(T('home.download')),
|
||||
),
|
||||
const SizedBox(width: GcSpace.xs),
|
||||
TextButton(
|
||||
onPressed: () => widget.controller.goTo(2),
|
||||
child: Text(T('home.settings')),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: GcSpace.md),
|
||||
Text(
|
||||
T('home.launchHint'),
|
||||
style: TextStyle(
|
||||
fontSize: 12,
|
||||
height: 1.55,
|
||||
color: GcColors.faint,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
const SizedBox(width: GcSpace.xxl),
|
||||
Container(
|
||||
padding: const EdgeInsets.symmetric(
|
||||
horizontal: GcSpace.xl,
|
||||
vertical: GcSpace.lg,
|
||||
),
|
||||
decoration: BoxDecoration(
|
||||
color: GcColors.surfaceAlt,
|
||||
borderRadius: BorderRadius.circular(GcRadius.control),
|
||||
border: Border.all(color: GcColors.line),
|
||||
),
|
||||
child: Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: <Widget>[
|
||||
GcMetric(
|
||||
value: '${_models.length}',
|
||||
label: T('home.stats.models'),
|
||||
),
|
||||
_metricDivider(),
|
||||
GcMetric(
|
||||
value: '$enabledSources',
|
||||
label: T('home.stats.sources'),
|
||||
),
|
||||
_metricDivider(),
|
||||
GcMetric(
|
||||
value: '${settings?.memoryBudgetMb ?? 0}',
|
||||
label: T('home.stats.memory'),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _metricDivider() {
|
||||
return Container(
|
||||
width: 1,
|
||||
height: 34,
|
||||
margin: const EdgeInsets.symmetric(horizontal: GcSpace.xl),
|
||||
color: GcColors.line,
|
||||
);
|
||||
}
|
||||
|
||||
Widget _sectionHeader() {
|
||||
return Row(
|
||||
children: <Widget>[
|
||||
Text(
|
||||
T('home.installed'),
|
||||
style: TextStyle(
|
||||
fontSize: 16,
|
||||
height: 1.4,
|
||||
fontWeight: FontWeight.w600,
|
||||
color: GcColors.ink,
|
||||
),
|
||||
),
|
||||
const SizedBox(width: GcSpace.sm),
|
||||
GcPill(T('home.count', <Object?>[_models.length]), subtle: true),
|
||||
const Spacer(),
|
||||
IconButton(
|
||||
tooltip: T('common.refresh'),
|
||||
onPressed: _load,
|
||||
icon: const Icon(Icons.refresh_rounded, size: 18),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
Widget _emptyState() {
|
||||
return GcCard(
|
||||
padding: const EdgeInsets.symmetric(
|
||||
horizontal: GcSpace.xxxl,
|
||||
vertical: 40,
|
||||
),
|
||||
child: Column(
|
||||
children: <Widget>[
|
||||
Container(
|
||||
width: 52,
|
||||
height: 52,
|
||||
alignment: Alignment.center,
|
||||
decoration: BoxDecoration(
|
||||
color: GcColors.accentSoft,
|
||||
borderRadius: BorderRadius.circular(GcRadius.panel),
|
||||
),
|
||||
child: Icon(
|
||||
Icons.travel_explore_rounded,
|
||||
size: 26,
|
||||
color: GcColors.accent,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: GcSpace.lg),
|
||||
Text(
|
||||
T('home.empty'),
|
||||
style: TextStyle(
|
||||
fontSize: 16,
|
||||
height: 1.4,
|
||||
fontWeight: FontWeight.w600,
|
||||
color: GcColors.ink,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: GcSpace.sm),
|
||||
ConstrainedBox(
|
||||
constraints: const BoxConstraints(maxWidth: 420),
|
||||
child: Text(
|
||||
T('home.emptyHint'),
|
||||
textAlign: TextAlign.center,
|
||||
style: TextStyle(
|
||||
fontSize: 12.5,
|
||||
height: 1.7,
|
||||
color: GcColors.muted,
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: GcSpace.xl),
|
||||
FilledButton(
|
||||
onPressed: () => widget.controller.goTo(1),
|
||||
child: Text(T('home.emptyAction')),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _ModelCard extends StatefulWidget {
|
||||
const _ModelCard({
|
||||
required this.model,
|
||||
required this.previewUrl,
|
||||
required this.onLaunch,
|
||||
required this.onOpenFolder,
|
||||
required this.onDelete,
|
||||
});
|
||||
|
||||
final ModelInfo model;
|
||||
final String previewUrl;
|
||||
final VoidCallback onLaunch;
|
||||
final VoidCallback onOpenFolder;
|
||||
final VoidCallback onDelete;
|
||||
|
||||
@override
|
||||
State<_ModelCard> createState() => _ModelCardState();
|
||||
}
|
||||
|
||||
class _ModelCardState extends State<_ModelCard> {
|
||||
bool _hover = false;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final model = widget.model;
|
||||
return MouseRegion(
|
||||
onEnter: (_) => setState(() => _hover = true),
|
||||
onExit: (_) => setState(() => _hover = false),
|
||||
cursor: SystemMouseCursors.click,
|
||||
child: GcCard(
|
||||
padding: EdgeInsets.zero,
|
||||
clip: true,
|
||||
borderColor: _hover ? GcColors.lineStrong : GcColors.line,
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: <Widget>[
|
||||
_cover(model),
|
||||
Padding(
|
||||
padding: const EdgeInsets.fromLTRB(
|
||||
GcSpace.lg,
|
||||
GcSpace.md + 2,
|
||||
GcSpace.lg,
|
||||
GcSpace.md,
|
||||
),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: <Widget>[
|
||||
Row(
|
||||
children: <Widget>[
|
||||
Expanded(
|
||||
child: Text(
|
||||
model.name,
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: TextStyle(
|
||||
fontSize: 14.5,
|
||||
height: 1.35,
|
||||
fontWeight: FontWeight.w600,
|
||||
color: GcColors.ink,
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(width: GcSpace.sm),
|
||||
Text(
|
||||
model.sizeText,
|
||||
style: TextStyle(
|
||||
fontSize: 12,
|
||||
height: 1.35,
|
||||
color: GcColors.faint,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: GcSpace.sm - 2),
|
||||
SizedBox(
|
||||
height: 36,
|
||||
child: Text(
|
||||
model.description.isEmpty
|
||||
? T('home.noDescription')
|
||||
: model.description,
|
||||
maxLines: 2,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: TextStyle(
|
||||
fontSize: 12.5,
|
||||
height: 1.45,
|
||||
color: model.description.isEmpty
|
||||
? GcColors.faint
|
||||
: GcColors.muted,
|
||||
),
|
||||
),
|
||||
),
|
||||
if (model.tags.isNotEmpty) ...<Widget>[
|
||||
const SizedBox(height: GcSpace.sm + 2),
|
||||
SizedBox(
|
||||
height: 20,
|
||||
child: Wrap(
|
||||
spacing: 6,
|
||||
runSpacing: 6,
|
||||
children: <Widget>[
|
||||
for (final tag in model.tags.take(3))
|
||||
GcPill(tag, subtle: true),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
const SizedBox(height: GcSpace.md + 2),
|
||||
Row(
|
||||
children: <Widget>[
|
||||
FilledButton.icon(
|
||||
onPressed: widget.onLaunch,
|
||||
icon: const Icon(Icons.play_arrow_rounded, size: 18),
|
||||
label: Text(T('home.launch')),
|
||||
),
|
||||
const Spacer(),
|
||||
IconButton(
|
||||
tooltip: T('home.open'),
|
||||
onPressed: widget.onOpenFolder,
|
||||
icon: const Icon(Icons.folder_open_rounded, size: 18),
|
||||
),
|
||||
IconButton(
|
||||
tooltip: T('home.delete'),
|
||||
onPressed: widget.onDelete,
|
||||
icon:
|
||||
const Icon(Icons.delete_outline_rounded, size: 18),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/// 封面:按卡片宽度和屏幕像素比解码,避免被放大后发虚。
|
||||
Widget _cover(ModelInfo model) {
|
||||
final dpr = MediaQuery.devicePixelRatioOf(context);
|
||||
final decodeWidth =
|
||||
(MediaQuery.sizeOf(context).width * dpr).clamp(320, 900).round();
|
||||
return SizedBox(
|
||||
height: 156,
|
||||
width: double.infinity,
|
||||
child: Stack(
|
||||
fit: StackFit.expand,
|
||||
children: <Widget>[
|
||||
_PreviewFallback(model: model),
|
||||
if (model.hasPreview)
|
||||
Image.network(
|
||||
widget.previewUrl,
|
||||
fit: BoxFit.cover,
|
||||
cacheWidth: decodeWidth,
|
||||
filterQuality: FilterQuality.medium,
|
||||
gaplessPlayback: true,
|
||||
errorBuilder: (context, error, stack) => const SizedBox.shrink(),
|
||||
),
|
||||
DecoratedBox(
|
||||
decoration: BoxDecoration(
|
||||
// 只用「透明 → 深色」的遮罩,别用 alphaBlend:叠加不透明底色
|
||||
// 会把整张封面盖平,占位字母也跟着消失。
|
||||
gradient: LinearGradient(
|
||||
begin: Alignment.topCenter,
|
||||
end: Alignment.bottomCenter,
|
||||
colors: <Color>[
|
||||
GcColors.appBg.withOpacity(0.0),
|
||||
GcColors.appBg.withOpacity(0.32),
|
||||
GcColors.appBg.withOpacity(0.88),
|
||||
],
|
||||
stops: const <double>[0.42, 0.72, 1.0],
|
||||
),
|
||||
),
|
||||
),
|
||||
Positioned(
|
||||
left: GcSpace.md,
|
||||
right: GcSpace.sm,
|
||||
bottom: GcSpace.sm,
|
||||
child: Row(
|
||||
children: <Widget>[
|
||||
if (model.version.isNotEmpty)
|
||||
GcPill('v${model.version}', color: GcColors.accent),
|
||||
if (model.author.isNotEmpty) ...<Widget>[
|
||||
const SizedBox(width: GcSpace.sm),
|
||||
Flexible(
|
||||
child: Text(
|
||||
model.author,
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: TextStyle(
|
||||
fontSize: 11.5,
|
||||
height: 1.3,
|
||||
color: GcColors.muted,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
const Spacer(),
|
||||
AnimatedOpacity(
|
||||
opacity: _hover ? 1 : 0,
|
||||
duration: const Duration(milliseconds: 140),
|
||||
child: Container(
|
||||
width: 26,
|
||||
height: 26,
|
||||
decoration: BoxDecoration(
|
||||
color: GcColors.accentFill,
|
||||
shape: BoxShape.circle,
|
||||
),
|
||||
child: Icon(
|
||||
Icons.play_arrow_rounded,
|
||||
size: 18,
|
||||
color: GcColors.onAccent,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// 没有封面时的占位:型号首字 + 淡淡的网格感,比一个大「◎」更像封面。
|
||||
class _PreviewFallback extends StatelessWidget {
|
||||
const _PreviewFallback({this.model});
|
||||
|
||||
final ModelInfo? model;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final label = (model?.name ?? '').characters.isEmpty
|
||||
? '◎'
|
||||
: model!.name.characters.first;
|
||||
return DecoratedBox(
|
||||
decoration: BoxDecoration(
|
||||
gradient: LinearGradient(
|
||||
begin: Alignment.topLeft,
|
||||
end: Alignment.bottomRight,
|
||||
colors: <Color>[
|
||||
Color.alphaBlend(
|
||||
GcColors.accent.withOpacity(0.22),
|
||||
GcColors.surfaceAlt,
|
||||
),
|
||||
GcColors.surfaceAlt,
|
||||
],
|
||||
),
|
||||
),
|
||||
child: Center(
|
||||
child: Text(
|
||||
label,
|
||||
style: TextStyle(
|
||||
fontSize: 46,
|
||||
height: 1.0,
|
||||
fontWeight: FontWeight.w600,
|
||||
color: Color.alphaBlend(
|
||||
GcColors.accent.withOpacity(0.55),
|
||||
GcColors.surfaceAlt,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,699 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../api_client.dart';
|
||||
import '../controller.dart';
|
||||
import '../i18n.dart';
|
||||
import '../theme.dart';
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 设置页(从原 pages.dart 拆出,公开类名不变)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 设置页
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
class SettingsPageView extends StatefulWidget {
|
||||
const SettingsPageView({super.key, required this.controller});
|
||||
|
||||
final ShellController controller;
|
||||
|
||||
@override
|
||||
State<SettingsPageView> createState() => _SettingsPageViewState();
|
||||
}
|
||||
|
||||
class _SettingsPageViewState extends State<SettingsPageView> {
|
||||
double _memory = 2048;
|
||||
bool _memoryAuto = true;
|
||||
int _fps = 120;
|
||||
bool _autoUpdate = true;
|
||||
String _language = 'auto';
|
||||
ThemeMode _themeMode = ThemeMode.dark;
|
||||
|
||||
/// 上一次同步所用的设置对象。以前用的是 `bool _synced` —— 只同步一次,
|
||||
/// 之后外部(更新状态条、其它页面)改了设置,本页仍显示旧值。
|
||||
SettingsInfo? _syncedFrom;
|
||||
String? _status;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
widget.controller.reloadSettings();
|
||||
}
|
||||
|
||||
void _syncFrom(SettingsInfo settings) {
|
||||
if (identical(_syncedFrom, settings)) return;
|
||||
_syncedFrom = settings;
|
||||
_memory = settings.memoryMb.toDouble();
|
||||
_memoryAuto = settings.memoryAuto;
|
||||
_fps = settings.renderFps;
|
||||
_autoUpdate = settings.autoUpdateOnStartup;
|
||||
_language = settings.language;
|
||||
_themeMode = GcPalette.parseMode(settings.theme);
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final settings = widget.controller.settings;
|
||||
if (settings == null) {
|
||||
return const Center(
|
||||
child: SizedBox(
|
||||
width: 22,
|
||||
height: 22,
|
||||
child: CircularProgressIndicator(strokeWidth: 2),
|
||||
),
|
||||
);
|
||||
}
|
||||
_syncFrom(settings);
|
||||
|
||||
return LayoutBuilder(
|
||||
builder: (context, constraints) {
|
||||
final twoColumns = constraints.maxWidth >= 960;
|
||||
final cards = <Widget>[
|
||||
_generalCard(settings),
|
||||
_appearanceCard(settings),
|
||||
_memoryCard(settings),
|
||||
_sourcesCard(settings),
|
||||
_storageCard(settings),
|
||||
_updateCard(settings),
|
||||
_backendCard(settings),
|
||||
];
|
||||
|
||||
Widget column(List<Widget> items) => Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: <Widget>[
|
||||
for (var i = 0; i < items.length; i++) ...<Widget>[
|
||||
if (i > 0) const SizedBox(height: GcSpace.lg),
|
||||
items[i],
|
||||
],
|
||||
],
|
||||
);
|
||||
|
||||
final left = <Widget>[];
|
||||
final right = <Widget>[];
|
||||
for (var i = 0; i < cards.length; i++) {
|
||||
if (twoColumns && i.isOdd) {
|
||||
right.add(cards[i]);
|
||||
} else {
|
||||
left.add(cards[i]);
|
||||
}
|
||||
}
|
||||
|
||||
return SingleChildScrollView(
|
||||
padding: const EdgeInsets.fromLTRB(
|
||||
GcSpace.xxl,
|
||||
GcSpace.xxl,
|
||||
GcSpace.xxl,
|
||||
GcSpace.xxxl,
|
||||
),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: <Widget>[
|
||||
GcPageHeader(
|
||||
title: T('set.title'),
|
||||
subtitle: T('set.subtitle'),
|
||||
trailing: _status == null
|
||||
? null
|
||||
: GcPill(
|
||||
_status!,
|
||||
color: GcColors.ok,
|
||||
icon: Icons.check_rounded,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: GcSpace.xxl),
|
||||
if (twoColumns)
|
||||
Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: <Widget>[
|
||||
Expanded(child: column(left)),
|
||||
const SizedBox(width: GcSpace.lg),
|
||||
Expanded(child: column(right)),
|
||||
],
|
||||
)
|
||||
else
|
||||
column(cards),
|
||||
],
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
Widget _label(String text) {
|
||||
return Text(
|
||||
text,
|
||||
style: TextStyle(fontSize: 13, height: 1.5, color: GcColors.muted),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _cardRow(String label, Widget control) {
|
||||
return Padding(
|
||||
padding: const EdgeInsets.symmetric(vertical: GcSpace.sm),
|
||||
child: Row(
|
||||
children: <Widget>[
|
||||
SizedBox(width: 124, child: _label(label)),
|
||||
Expanded(child: control),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _generalCard(SettingsInfo settings) {
|
||||
return GcCard(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: <Widget>[
|
||||
GcSectionTitle(T('set.general')),
|
||||
const SizedBox(height: GcSpace.lg),
|
||||
_cardRow(
|
||||
T('set.language'),
|
||||
Align(
|
||||
alignment: Alignment.centerLeft,
|
||||
child: DropdownButton<String>(
|
||||
value: _language,
|
||||
dropdownColor: GcColors.surfaceAlt,
|
||||
underline: const SizedBox.shrink(),
|
||||
borderRadius: BorderRadius.circular(GcRadius.control),
|
||||
// 从主题样式派生,才能继承字体族(自建 TextStyle 会丢掉
|
||||
// fontFamily,中文就回退成系统兜底字体)。
|
||||
style: Theme.of(context).textTheme.bodyLarge!.copyWith(
|
||||
fontSize: 13,
|
||||
height: 1.4,
|
||||
fontWeight: FontWeight.w400,
|
||||
color: GcColors.ink,
|
||||
),
|
||||
items: <DropdownMenuItem<String>>[
|
||||
DropdownMenuItem<String>(
|
||||
value: 'auto',
|
||||
child: Text(T('set.language.auto')),
|
||||
),
|
||||
for (final language in settings.languages)
|
||||
DropdownMenuItem<String>(
|
||||
value: language.code,
|
||||
child: Text(language.label),
|
||||
),
|
||||
],
|
||||
onChanged: (value) async {
|
||||
if (value == null) return;
|
||||
setState(() => _language = value);
|
||||
await widget.controller
|
||||
.saveSettings(SettingsPatch(language: value));
|
||||
},
|
||||
),
|
||||
),
|
||||
),
|
||||
_cardRow(
|
||||
T('set.fps'),
|
||||
Row(
|
||||
children: <Widget>[
|
||||
Expanded(
|
||||
child: Slider(
|
||||
value: _fps.toDouble(),
|
||||
min: 24,
|
||||
max: 120,
|
||||
divisions: 4,
|
||||
label: '$_fps',
|
||||
onChanged: (value) => setState(() => _fps = value.round()),
|
||||
onChangeEnd: (value) async {
|
||||
await widget.controller.saveSettings(
|
||||
SettingsPatch(renderFps: value.round()));
|
||||
if (mounted) {
|
||||
setState(() => _status = T('common.applied'));
|
||||
}
|
||||
},
|
||||
),
|
||||
),
|
||||
SizedBox(
|
||||
width: 48,
|
||||
child: Text(
|
||||
'$_fps',
|
||||
textAlign: TextAlign.end,
|
||||
style: TextStyle(
|
||||
fontSize: 13,
|
||||
height: 1.4,
|
||||
fontWeight: FontWeight.w600,
|
||||
color: GcColors.ink,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
GcHint(T('set.fps.desc')),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _appearanceCard(SettingsInfo settings) {
|
||||
final current =
|
||||
GcPalette.parseHex(settings.accentColor) ?? GcPalette.defaultAccent;
|
||||
return GcCard(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: <Widget>[
|
||||
GcSectionTitle(T('set.appearance')),
|
||||
const SizedBox(height: GcSpace.md),
|
||||
GcHint(T('set.theme.desc')),
|
||||
const SizedBox(height: GcSpace.md),
|
||||
SegmentedButton<ThemeMode>(
|
||||
segments: <ButtonSegment<ThemeMode>>[
|
||||
ButtonSegment<ThemeMode>(
|
||||
value: ThemeMode.dark,
|
||||
label: Text(T('set.theme.dark')),
|
||||
icon: const Icon(Icons.dark_mode_outlined, size: 16),
|
||||
),
|
||||
ButtonSegment<ThemeMode>(
|
||||
value: ThemeMode.light,
|
||||
label: Text(T('set.theme.light')),
|
||||
icon: const Icon(Icons.light_mode_outlined, size: 16),
|
||||
),
|
||||
ButtonSegment<ThemeMode>(
|
||||
value: ThemeMode.system,
|
||||
label: Text(T('set.theme.system')),
|
||||
icon: const Icon(Icons.brightness_auto_outlined, size: 16),
|
||||
),
|
||||
],
|
||||
selected: <ThemeMode>{_themeMode},
|
||||
showSelectedIcon: false,
|
||||
onSelectionChanged: (selection) async {
|
||||
final mode = selection.first;
|
||||
setState(() => _themeMode = mode);
|
||||
GcPalette.mode.value = mode; // 立即预览
|
||||
await widget.controller.saveSettings(
|
||||
SettingsPatch(theme: GcPalette.modeToName(mode)));
|
||||
if (mounted) setState(() => _status = T('common.applied'));
|
||||
},
|
||||
),
|
||||
const SizedBox(height: GcSpace.xl),
|
||||
GcHint(T('set.accent.desc')),
|
||||
const SizedBox(height: GcSpace.md + 2),
|
||||
Wrap(
|
||||
spacing: GcSpace.sm + 2,
|
||||
runSpacing: GcSpace.sm + 2,
|
||||
children: <Widget>[
|
||||
for (final color in GcPalette.presets)
|
||||
_accentSwatch(color, current),
|
||||
_customAccentChip(),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: GcSpace.md),
|
||||
Text(
|
||||
'${T('set.accent')}: ${GcPalette.toHex(current)}',
|
||||
style: TextStyle(
|
||||
fontSize: 11.5,
|
||||
height: 1.4,
|
||||
color: GcColors.faint,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _accentSwatch(Color color, Color current) {
|
||||
final selected = color.value == current.value;
|
||||
return Tooltip(
|
||||
message: GcPalette.toHex(color),
|
||||
child: GestureDetector(
|
||||
onTap: () => _applyAccent(GcPalette.toHex(color)),
|
||||
child: Container(
|
||||
width: 34,
|
||||
height: 34,
|
||||
decoration: BoxDecoration(
|
||||
color: color,
|
||||
borderRadius: BorderRadius.circular(GcRadius.control),
|
||||
border: Border.all(
|
||||
color: selected ? GcColors.ink : Colors.transparent,
|
||||
width: 2,
|
||||
),
|
||||
),
|
||||
child: selected
|
||||
? Icon(
|
||||
Icons.check_rounded,
|
||||
size: 18,
|
||||
color: color.computeLuminance() > 0.42
|
||||
? const Color(0xFF0A1226)
|
||||
: Colors.white,
|
||||
)
|
||||
: null,
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _customAccentChip() {
|
||||
return MouseRegion(
|
||||
cursor: SystemMouseCursors.click,
|
||||
child: GestureDetector(
|
||||
onTap: _pickCustomAccent,
|
||||
child: Container(
|
||||
height: 34,
|
||||
padding: const EdgeInsets.symmetric(horizontal: GcSpace.md),
|
||||
decoration: BoxDecoration(
|
||||
color: GcColors.surfaceAlt,
|
||||
borderRadius: BorderRadius.circular(GcRadius.control),
|
||||
border: Border.all(color: GcColors.line),
|
||||
),
|
||||
child: Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: <Widget>[
|
||||
Icon(Icons.colorize_rounded, size: 16, color: GcColors.faint),
|
||||
const SizedBox(width: GcSpace.xs + 2),
|
||||
Text(
|
||||
T('set.accent.custom'),
|
||||
style: TextStyle(
|
||||
fontSize: 12,
|
||||
height: 1.3,
|
||||
color: GcColors.muted,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> _pickCustomAccent() async {
|
||||
final controller = TextEditingController(
|
||||
text: GcPalette.toHex(GcPalette.accent.value),
|
||||
);
|
||||
final hex = await showDialog<String>(
|
||||
context: context,
|
||||
builder: (context) => AlertDialog(
|
||||
backgroundColor: GcColors.surface,
|
||||
title: Text(T('set.accent.custom')),
|
||||
content: TextField(
|
||||
controller: controller,
|
||||
autofocus: true,
|
||||
style: Theme.of(context).textTheme.bodyLarge!.copyWith(fontSize: 13),
|
||||
decoration: InputDecoration(
|
||||
hintText: '#8FB6FF',
|
||||
helperText: T('set.accent.hexHint'),
|
||||
),
|
||||
onSubmitted: (value) => Navigator.of(context).pop(value),
|
||||
),
|
||||
actions: <Widget>[
|
||||
TextButton(
|
||||
onPressed: () => Navigator.of(context).pop(),
|
||||
child: Text(T('common.cancel')),
|
||||
),
|
||||
FilledButton(
|
||||
onPressed: () => Navigator.of(context).pop(controller.text),
|
||||
child: Text(T('common.confirm')),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
controller.dispose();
|
||||
if (hex != null) await _applyAccent(hex);
|
||||
}
|
||||
|
||||
Future<void> _applyAccent(String hex) async {
|
||||
final parsed = GcPalette.parseHex(hex);
|
||||
if (parsed == null) {
|
||||
if (mounted) setState(() => _status = T('set.accent.invalid'));
|
||||
return;
|
||||
}
|
||||
final normalized = GcPalette.toHex(parsed);
|
||||
GcPalette.apply(normalized); // 立即预览
|
||||
await widget.controller
|
||||
.saveSettings(SettingsPatch(accentColor: normalized));
|
||||
if (mounted) setState(() => _status = T('common.applied'));
|
||||
}
|
||||
|
||||
Widget _memoryCard(SettingsInfo settings) {
|
||||
return GcCard(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: <Widget>[
|
||||
GcSectionTitle(T('set.memory')),
|
||||
const SizedBox(height: GcSpace.md),
|
||||
GcHint(T('set.memory.desc')),
|
||||
const SizedBox(height: GcSpace.lg),
|
||||
Row(
|
||||
children: <Widget>[
|
||||
Switch(
|
||||
value: _memoryAuto,
|
||||
onChanged: (value) async {
|
||||
setState(() => _memoryAuto = value);
|
||||
await widget.controller
|
||||
.saveSettings(SettingsPatch(memoryAuto: value));
|
||||
},
|
||||
),
|
||||
const SizedBox(width: GcSpace.md),
|
||||
Expanded(
|
||||
child: Text(
|
||||
T('set.memory.auto'),
|
||||
style: TextStyle(
|
||||
fontSize: 13,
|
||||
height: 1.5,
|
||||
color: GcColors.muted,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: GcSpace.xs),
|
||||
Row(
|
||||
children: <Widget>[
|
||||
Expanded(
|
||||
child: Slider(
|
||||
value: _memory,
|
||||
min: 512,
|
||||
max: 16384,
|
||||
divisions: 62,
|
||||
label: '${_memory.round()} MB',
|
||||
onChanged: _memoryAuto
|
||||
? null
|
||||
: (value) => setState(() => _memory = value),
|
||||
onChangeEnd: (value) async {
|
||||
await widget.controller
|
||||
.saveSettings(SettingsPatch(memoryMb: value.round()));
|
||||
if (mounted) setState(() => _status = T('common.applied'));
|
||||
},
|
||||
),
|
||||
),
|
||||
SizedBox(
|
||||
width: 104,
|
||||
child: Text(
|
||||
'${_memory.round()} MB',
|
||||
textAlign: TextAlign.end,
|
||||
style: TextStyle(
|
||||
fontSize: 13,
|
||||
height: 1.4,
|
||||
fontWeight: FontWeight.w600,
|
||||
color: GcColors.ink,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: GcSpace.xs),
|
||||
GcHint('${T('set.memory.current')}: ${settings.memoryUsageText}'),
|
||||
const SizedBox(height: GcSpace.xs),
|
||||
GcHint(T('set.memory.hint')),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _sourcesCard(SettingsInfo settings) {
|
||||
return GcCard(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: <Widget>[
|
||||
GcSectionTitle(T('set.sources')),
|
||||
const SizedBox(height: GcSpace.md),
|
||||
GcHint(T('set.sources.desc')),
|
||||
const SizedBox(height: GcSpace.md),
|
||||
for (final source in settings.sources)
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(bottom: GcSpace.md),
|
||||
child: Row(
|
||||
children: <Widget>[
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: <Widget>[
|
||||
Text(
|
||||
source.name,
|
||||
style: TextStyle(
|
||||
fontSize: 13,
|
||||
height: 1.4,
|
||||
fontWeight: FontWeight.w600,
|
||||
color: GcColors.ink,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 1),
|
||||
Text(
|
||||
source.url,
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: TextStyle(
|
||||
fontSize: 11.5,
|
||||
height: 1.4,
|
||||
color: GcColors.faint,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
const SizedBox(width: GcSpace.sm),
|
||||
if (source.enabled)
|
||||
GcPill(T('set.sourceEnabled'), color: GcColors.ok)
|
||||
else
|
||||
const GcPill('—', subtle: true),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _storageCard(SettingsInfo settings) {
|
||||
return GcCard(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: <Widget>[
|
||||
GcSectionTitle(T('set.storage')),
|
||||
const SizedBox(height: GcSpace.md),
|
||||
GcFieldRow(
|
||||
label: T('set.modelDir'),
|
||||
value: settings.modelRoot,
|
||||
selectable: true,
|
||||
valueColor: GcColors.muted,
|
||||
),
|
||||
GcFieldRow(
|
||||
label: T('set.dataDir'),
|
||||
value: settings.dataRoot,
|
||||
selectable: true,
|
||||
valueColor: GcColors.muted,
|
||||
),
|
||||
const SizedBox(height: GcSpace.md),
|
||||
Wrap(
|
||||
spacing: GcSpace.sm + 2,
|
||||
runSpacing: GcSpace.sm + 2,
|
||||
children: <Widget>[
|
||||
OutlinedButton(
|
||||
onPressed: () async {
|
||||
try {
|
||||
await widget.controller.api.openFolder(settings.modelRoot);
|
||||
} catch (error) {
|
||||
if (mounted) setState(() => _status = error.toString());
|
||||
}
|
||||
},
|
||||
child: Text(T('set.openFolder')),
|
||||
),
|
||||
OutlinedButton(
|
||||
onPressed: () async {
|
||||
await widget.controller.checkUpdate(force: true);
|
||||
if (mounted) setState(() => _status = T('set.cacheCleared'));
|
||||
},
|
||||
child: Text(T('set.clearCache')),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _updateCard(SettingsInfo settings) {
|
||||
return GcCard(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: <Widget>[
|
||||
GcSectionTitle(T('update.title')),
|
||||
const SizedBox(height: GcSpace.md),
|
||||
GcHint(T('set.checkUpdate.desc')),
|
||||
const SizedBox(height: GcSpace.md),
|
||||
Row(
|
||||
children: <Widget>[
|
||||
Switch(
|
||||
value: _autoUpdate,
|
||||
onChanged: (value) async {
|
||||
setState(() => _autoUpdate = value);
|
||||
await widget.controller
|
||||
.saveSettings(SettingsPatch(autoUpdateOnStartup: value));
|
||||
},
|
||||
),
|
||||
const SizedBox(width: GcSpace.md),
|
||||
Expanded(
|
||||
child: Text(
|
||||
T('update.auto'),
|
||||
style: TextStyle(
|
||||
fontSize: 13,
|
||||
height: 1.5,
|
||||
color: GcColors.muted,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: GcSpace.sm),
|
||||
GcFieldRow(
|
||||
label: T('update.source'),
|
||||
value: settings.updateRepository,
|
||||
selectable: true,
|
||||
valueColor: GcColors.muted,
|
||||
),
|
||||
const SizedBox(height: GcSpace.md),
|
||||
FilledButton(
|
||||
onPressed: () => widget.controller.checkUpdate(force: true),
|
||||
child: Text(T('update.checkNow')),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _backendCard(SettingsInfo settings) {
|
||||
final health = widget.controller.health;
|
||||
return GcCard(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: <Widget>[
|
||||
GcSectionTitle(T('set.backend')),
|
||||
const SizedBox(height: GcSpace.md),
|
||||
GcHint(T('set.backend.desc')),
|
||||
const SizedBox(height: GcSpace.md),
|
||||
GcFieldRow(
|
||||
label: 'API',
|
||||
value: widget.controller.api.baseUrl,
|
||||
selectable: true,
|
||||
valueColor: GcColors.muted,
|
||||
),
|
||||
GcFieldRow(
|
||||
label: T('set.version'),
|
||||
value: settings.version,
|
||||
valueColor: GcColors.muted,
|
||||
),
|
||||
GcFieldRow(
|
||||
label: T('set.platform'),
|
||||
value: settings.platform,
|
||||
valueColor: GcColors.muted,
|
||||
),
|
||||
GcFieldRow(
|
||||
label: T('set.backend.ui'),
|
||||
value: health == null
|
||||
? '—'
|
||||
: health.uiAvailable
|
||||
? T('set.backend.uiOk')
|
||||
: '${T('set.backend.uiBad')}${health.uiError == null ? '' : ' · ${health.uiError}'}',
|
||||
valueColor: health == null
|
||||
? GcColors.muted
|
||||
: health.uiAvailable
|
||||
? GcColors.ok
|
||||
: GcColors.danger,
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -461,7 +461,7 @@
|
||||
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
|
||||
GCC_WARN_UNUSED_FUNCTION = YES;
|
||||
GCC_WARN_UNUSED_VARIABLE = YES;
|
||||
MACOSX_DEPLOYMENT_TARGET = 10.14;
|
||||
MACOSX_DEPLOYMENT_TARGET = 12.0;
|
||||
MTL_ENABLE_DEBUG_INFO = NO;
|
||||
SDKROOT = macosx;
|
||||
SWIFT_COMPILATION_MODE = wholemodule;
|
||||
@@ -543,7 +543,7 @@
|
||||
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
|
||||
GCC_WARN_UNUSED_FUNCTION = YES;
|
||||
GCC_WARN_UNUSED_VARIABLE = YES;
|
||||
MACOSX_DEPLOYMENT_TARGET = 10.14;
|
||||
MACOSX_DEPLOYMENT_TARGET = 12.0;
|
||||
MTL_ENABLE_DEBUG_INFO = YES;
|
||||
ONLY_ACTIVE_ARCH = YES;
|
||||
SDKROOT = macosx;
|
||||
@@ -593,7 +593,7 @@
|
||||
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
|
||||
GCC_WARN_UNUSED_FUNCTION = YES;
|
||||
GCC_WARN_UNUSED_VARIABLE = YES;
|
||||
MACOSX_DEPLOYMENT_TARGET = 10.14;
|
||||
MACOSX_DEPLOYMENT_TARGET = 12.0;
|
||||
MTL_ENABLE_DEBUG_INFO = NO;
|
||||
SDKROOT = macosx;
|
||||
SWIFT_COMPILATION_MODE = wholemodule;
|
||||
|
||||
@@ -4,5 +4,9 @@
|
||||
<dict>
|
||||
<key>com.apple.security.app-sandbox</key>
|
||||
<true/>
|
||||
<key>com.apple.security.network.client</key>
|
||||
<true/>
|
||||
<key>com.apple.security.network.server</key>
|
||||
<true/>
|
||||
</dict>
|
||||
</plist>
|
||||
@@ -16,7 +16,7 @@ publish_to: 'none' # Remove this line if you wish to publish to pub.dev
|
||||
# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
|
||||
# In Windows, build-name is used as the major, minor, and patch parts
|
||||
# of the product and file versions while build-number is used as the build suffix.
|
||||
version: 1.1.0+1
|
||||
version: 1.1.1+1
|
||||
|
||||
environment:
|
||||
sdk: ^3.5.4
|
||||
|
||||
+124
-12
@@ -1,4 +1,5 @@
|
||||
using System;
|
||||
using System.Globalization;
|
||||
using System.IO;
|
||||
using System.Text;
|
||||
|
||||
@@ -15,15 +16,30 @@ namespace GC.Services;
|
||||
/// 中英分开而不是写在一个文件里:用户排查时不用在一行里找自己看得懂的那半句;
|
||||
/// 也给反馈问题时直接发对应语言的文件即可。
|
||||
///
|
||||
/// 写入方式:常驻 <see cref="StreamWriter"/>(<c>AutoFlush</c> 打开,崩溃也不丢最后几行),
|
||||
/// 不再每行 open/append/close 一遍 —— 那条路径每写一行要开两个文件句柄,
|
||||
/// 在下载 / 启动高峰期会明显拖慢调用方。
|
||||
///
|
||||
/// 保留策略:<see cref="RetentionDays"/> 天之前的日志在初始化与跨天滚动时删除;
|
||||
/// 总量超过 <see cref="MaxTotalBytes"/> 时从最旧的开始删。日志目录不会无限长。
|
||||
///
|
||||
/// 日志失败绝不影响主流程(磁盘满、只读目录都只是少一份日志)。
|
||||
/// </summary>
|
||||
public static class GcLog
|
||||
{
|
||||
/// <summary>日志保留天数。</summary>
|
||||
public const int RetentionDays = 14;
|
||||
|
||||
/// <summary>日志目录总量上限(中英两份合计)。</summary>
|
||||
public const long MaxTotalBytes = 64L * 1024 * 1024;
|
||||
|
||||
private static readonly object Gate = new();
|
||||
private const string FilePrefix = "gc-";
|
||||
|
||||
private static string? _dir;
|
||||
private static string _day = "";
|
||||
private static string _zhPath = "";
|
||||
private static string _enPath = "";
|
||||
private static StreamWriter? _zh;
|
||||
private static StreamWriter? _en;
|
||||
|
||||
public static bool Enabled
|
||||
{
|
||||
@@ -45,8 +61,10 @@ public static class GcLog
|
||||
|
||||
lock (Gate)
|
||||
{
|
||||
CloseWriters();
|
||||
_dir = dir;
|
||||
_day = "";
|
||||
PruneOldFiles(dir);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -58,10 +76,8 @@ public static class GcLog
|
||||
{
|
||||
var now = DateTime.Now;
|
||||
var prefix = $"{now:yyyy-MM-dd HH:mm:ss} [{level}] ";
|
||||
var lineZh = prefix + zh;
|
||||
var lineEn = prefix + en;
|
||||
|
||||
try { Console.WriteLine(lineZh); } catch { /* 无控制台 */ }
|
||||
try { Console.WriteLine(prefix + zh); } catch { /* 无控制台 */ }
|
||||
|
||||
lock (Gate)
|
||||
{
|
||||
@@ -70,25 +86,121 @@ public static class GcLog
|
||||
var day = now.ToString("yyyyMMdd");
|
||||
if (day != _day)
|
||||
{
|
||||
// 跨天换文件;顺便清一次旧日志,长时间挂机的进程也不会攒满磁盘
|
||||
CloseWriters();
|
||||
_day = day;
|
||||
_zhPath = Path.Combine(_dir, $"gc-{day}.log");
|
||||
_enPath = Path.Combine(_dir, $"gc-{day}.en.log");
|
||||
PruneOldFiles(_dir);
|
||||
}
|
||||
|
||||
Append(_zhPath, lineZh);
|
||||
Append(_enPath, lineEn);
|
||||
if (_zh == null)
|
||||
{
|
||||
_zh = OpenWriter(Path.Combine(_dir, $"{FilePrefix}{day}.log"));
|
||||
_en = OpenWriter(Path.Combine(_dir, $"{FilePrefix}{day}.en.log"));
|
||||
}
|
||||
|
||||
Append(_zh, prefix + zh);
|
||||
Append(_en, prefix + en);
|
||||
}
|
||||
}
|
||||
|
||||
private static void Append(string path, string line)
|
||||
private static StreamWriter? OpenWriter(string path)
|
||||
{
|
||||
try
|
||||
{
|
||||
File.AppendAllText(path, line + Environment.NewLine, new UTF8Encoding(false));
|
||||
var stream = new FileStream(path, FileMode.Append, FileAccess.Write, FileShare.ReadWrite);
|
||||
return new StreamWriter(stream, new UTF8Encoding(false)) { AutoFlush = true };
|
||||
}
|
||||
catch
|
||||
{
|
||||
// 日志失败不能影响程序
|
||||
// 写不了就不写;下一次跨天会再试一次
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static void Append(StreamWriter? writer, string line)
|
||||
{
|
||||
if (writer == null) return;
|
||||
try
|
||||
{
|
||||
writer.WriteLine(line);
|
||||
}
|
||||
catch
|
||||
{
|
||||
// 磁盘满 / 文件被删:关掉写入器,下次跨天重建
|
||||
try { writer.Dispose(); } catch { }
|
||||
if (ReferenceEquals(writer, _zh)) _zh = null; else _en = null;
|
||||
}
|
||||
}
|
||||
|
||||
private static void CloseWriters()
|
||||
{
|
||||
try { _zh?.Dispose(); } catch { }
|
||||
try { _en?.Dispose(); } catch { }
|
||||
_zh = null;
|
||||
_en = null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 清理过期与超量日志。只动本模块自己写的 <c>gc-YYYYMMDD[.en].log</c>,
|
||||
/// 目录里用户放的其他文件一概不碰。
|
||||
/// </summary>
|
||||
private static void PruneOldFiles(string dir)
|
||||
{
|
||||
try
|
||||
{
|
||||
var files = new DirectoryInfo(dir).GetFiles(FilePrefix + "*.log");
|
||||
if (files.Length == 0) return;
|
||||
|
||||
var cutoff = DateTime.Now.Date.AddDays(-RetentionDays);
|
||||
var alive = new System.Collections.Generic.List<FileInfo>(files.Length);
|
||||
foreach (var file in files)
|
||||
{
|
||||
if (!TryReadDate(file.Name, out var date))
|
||||
{
|
||||
// 名字不是我们的格式,忽略(既不删也不计入配额)
|
||||
continue;
|
||||
}
|
||||
|
||||
if (date < cutoff)
|
||||
{
|
||||
try { file.Delete(); } catch { }
|
||||
continue;
|
||||
}
|
||||
|
||||
alive.Add(file);
|
||||
}
|
||||
|
||||
long total = 0;
|
||||
foreach (var file in alive) total += file.Length;
|
||||
if (total <= MaxTotalBytes) return;
|
||||
|
||||
alive.Sort((a, b) => a.LastWriteTimeUtc.CompareTo(b.LastWriteTimeUtc));
|
||||
foreach (var file in alive)
|
||||
{
|
||||
if (total <= MaxTotalBytes) break;
|
||||
try
|
||||
{
|
||||
total -= file.Length;
|
||||
file.Delete();
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
// 清理失败不影响写日志
|
||||
}
|
||||
}
|
||||
|
||||
private static bool TryReadDate(string name, out DateTime date)
|
||||
{
|
||||
date = default;
|
||||
// gc-20261118.log / gc-20261118.en.log
|
||||
if (!name.StartsWith(FilePrefix, StringComparison.Ordinal)) return false;
|
||||
var rest = name.Substring(FilePrefix.Length);
|
||||
var dot = rest.IndexOf('.');
|
||||
if (dot != 8) return false;
|
||||
return DateTime.TryParseExact(rest.Substring(0, 8), "yyyyMMdd",
|
||||
CultureInfo.InvariantCulture, DateTimeStyles.None, out date);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,293 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.IO.Compression;
|
||||
using System.Linq;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using GC.Savedog;
|
||||
|
||||
namespace GC.Savedog.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// GC-SAVEDOG 的应用器测试:更新真正落盘的那一段(整目录替换 / .GC/bin 合并 / 失败回滚)。
|
||||
///
|
||||
/// 为什么单独一个工程:<c>GC.Tests</c> 引用的是启动器程序集,而 GC-SAVEDOG 为了保持
|
||||
/// 「安全逻辑只有一份实现」把 <c>GC/src/Security</c> 与 <c>Json.cs</c> 以源码链接的方式
|
||||
/// 编进了自己 —— 两个程序集里存在同名类型。同一个测试工程里同时引用两者会撞类型,
|
||||
/// 所以应用器测试单独放这里,只引用守护进程。
|
||||
///
|
||||
/// 为什么需要这组用例:<c>--update-test</c> 覆盖的是「怎么判断该不该更新」,
|
||||
/// <see cref="Applier"/> 才是会动用户安装目录的代码 —— 它出错就是用户目录被删空。
|
||||
/// 全部在临时目录里跑,不碰真实安装、不联网。
|
||||
/// </summary>
|
||||
internal static class ApplierTests
|
||||
{
|
||||
private static int _failed;
|
||||
private static string _root = "";
|
||||
|
||||
public static int Main()
|
||||
{
|
||||
_root = Path.Combine(Path.GetTempPath(), "gc-applier-" + Guid.NewGuid().ToString("N")[..8]);
|
||||
Directory.CreateDirectory(_root);
|
||||
Console.WriteLine("Applier 测试目录: " + _root);
|
||||
|
||||
try
|
||||
{
|
||||
CaseRefusesTraversalPackageName();
|
||||
CaseRefusesShaMismatch();
|
||||
CaseRefusesSourceTree();
|
||||
CaseDryRunKeepsInstallUntouched();
|
||||
CaseRollbackRestoresOldFiles();
|
||||
CaseSuccessMergesGcBinAndKeepsUserData();
|
||||
}
|
||||
finally
|
||||
{
|
||||
try { Directory.Delete(_root, true); } catch { }
|
||||
}
|
||||
|
||||
Console.WriteLine(_failed == 0
|
||||
? "Applier 测试全部通过"
|
||||
: $"Applier 测试失败 {_failed} 项");
|
||||
return _failed == 0 ? 0 : 1;
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ 用例
|
||||
|
||||
/// <summary>包名带 ../ 时必须拒绝(路径穿越的第一道闸)。</summary>
|
||||
private static void CaseRefusesTraversalPackageName()
|
||||
{
|
||||
var (install, update) = Sandbox("traversal");
|
||||
WritePackage(update, new Dictionary<string, string>
|
||||
{
|
||||
["GCL-9.9.9-test-amd64.exe"] = "new"
|
||||
});
|
||||
WriteRequest(update, "../evil.exe", sha: null);
|
||||
|
||||
var code = Apply(update, install, dryRun: true);
|
||||
Check("路径穿越的包名被拒绝", code == 3, $"exit={code}(期望 3)");
|
||||
}
|
||||
|
||||
/// <summary>zip 内容与清单 sha256 不符时必须丢弃。</summary>
|
||||
private static void CaseRefusesShaMismatch()
|
||||
{
|
||||
var (install, update) = Sandbox("sha");
|
||||
WritePackage(update, new Dictionary<string, string>
|
||||
{
|
||||
["GCL-9.9.9-test-amd64.exe"] = "new"
|
||||
});
|
||||
WriteRequest(update, "GCL-9.9.9-test-amd64.exe", sha: new string('a', 64));
|
||||
|
||||
var code = Apply(update, install, dryRun: true);
|
||||
Check("sha256 不符的包被丢弃", code == 5, $"exit={code}(期望 5)");
|
||||
}
|
||||
|
||||
/// <summary>安装目录里有 GC.sln 时拒绝替换 —— 防止误在源码树里跑更新。</summary>
|
||||
private static void CaseRefusesSourceTree()
|
||||
{
|
||||
var (install, update) = Sandbox("srctree");
|
||||
File.WriteAllText(Path.Combine(install, "GC.sln"), "fake solution");
|
||||
var zip = WritePackage(update, new Dictionary<string, string>
|
||||
{
|
||||
["GCL-9.9.9-test-amd64.exe"] = "new"
|
||||
});
|
||||
WriteRequest(update, "GCL-9.9.9-test-amd64.exe", Sha256File(zip));
|
||||
|
||||
var code = Apply(update, install, dryRun: false);
|
||||
Check("源码目录被拒绝替换", code == 4, $"exit={code}(期望 4)");
|
||||
Check("源码目录里的文件没被动过",
|
||||
File.ReadAllText(Path.Combine(install, "GC.sln")) == "fake solution",
|
||||
"GC.sln 内容变了");
|
||||
}
|
||||
|
||||
/// <summary>dry-run 只校验不落盘:安装目录必须一个字节都不变。</summary>
|
||||
private static void CaseDryRunKeepsInstallUntouched()
|
||||
{
|
||||
var (install, update) = Sandbox("dryrun");
|
||||
File.WriteAllText(Path.Combine(install, "GCL-1.0.0-test-amd64.exe"), "old");
|
||||
File.WriteAllText(Path.Combine(install, "only-in-old.txt"), "keep me");
|
||||
|
||||
var zip = WritePackage(update, new Dictionary<string, string>
|
||||
{
|
||||
["GCL-9.9.9-test-amd64.exe"] = "new",
|
||||
["GC-UI.exe"] = "ui"
|
||||
});
|
||||
WriteRequest(update, "GCL-9.9.9-test-amd64.exe", Sha256File(zip));
|
||||
|
||||
var code = Apply(update, install, dryRun: true);
|
||||
var names = Directory.GetFileSystemEntries(install).Select(Path.GetFileName).OrderBy(n => n).ToArray();
|
||||
Check("dry-run 返回 0", code == 0, $"exit={code}");
|
||||
Check("dry-run 不改安装目录",
|
||||
names.SequenceEqual(new[] { "GCL-1.0.0-test-amd64.exe", "only-in-old.txt" }),
|
||||
"安装目录变成: " + string.Join(", ", names));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 新版本启动不健康 → 回滚:旧文件原样回来,新包独有的文件被删掉,zip 与申请被清理。
|
||||
/// </summary>
|
||||
private static void CaseRollbackRestoresOldFiles()
|
||||
{
|
||||
var (install, update) = Sandbox("rollback");
|
||||
var oldExe = Path.Combine(install, "GCL-1.0.0-test-amd64.exe");
|
||||
var oldOnly = Path.Combine(install, "only-in-old.txt");
|
||||
File.WriteAllText(oldExe, "old-binary");
|
||||
File.WriteAllText(oldOnly, "old-only");
|
||||
|
||||
// 新版什么都不做直接退出:健康标记不会出现,必然回滚
|
||||
var zip = WritePackage(update, new Dictionary<string, string>
|
||||
{
|
||||
["GCL-9.9.9-test-amd64.exe"] = "#!/bin/sh\nexit 1\n",
|
||||
["only-in-new.txt"] = "new-only"
|
||||
});
|
||||
WriteRequest(update, "GCL-9.9.9-test-amd64.exe", Sha256File(zip));
|
||||
|
||||
var code = Apply(update, install, dryRun: false, timeoutSeconds: 5);
|
||||
Check("启动失败后回滚(exit=8)", code == 8, $"exit={code}(期望 8)");
|
||||
Check("旧启动器被还原",
|
||||
File.Exists(oldExe) && File.ReadAllText(oldExe) == "old-binary",
|
||||
"旧启动器没回来");
|
||||
Check("旧版独有文件被还原",
|
||||
File.Exists(oldOnly) && File.ReadAllText(oldOnly) == "old-only",
|
||||
"旧版独有文件没回来");
|
||||
Check("新包独有文件被删除", !File.Exists(Path.Combine(install, "only-in-new.txt")),
|
||||
"only-in-new.txt 残留");
|
||||
Check("更新包与申请已清理",
|
||||
!File.Exists(Path.Combine(update, "package.zip")) &&
|
||||
!File.Exists(Path.Combine(update, "apply-request.json")),
|
||||
"update 目录里还有残留");
|
||||
}
|
||||
|
||||
/// <summary>正常路径:新文件就位、.GC/bin 被合并、.GC 下的用户数据原地不动。</summary>
|
||||
private static void CaseSuccessMergesGcBinAndKeepsUserData()
|
||||
{
|
||||
var (install, update) = Sandbox("success");
|
||||
var updateDirFull = Path.GetFullPath(update);
|
||||
|
||||
// 用户数据:设置、模型、守护进程源文件
|
||||
Directory.CreateDirectory(Path.Combine(install, ".GC", "config"));
|
||||
Directory.CreateDirectory(Path.Combine(install, ".GC", "model", "earth-rotation"));
|
||||
Directory.CreateDirectory(Path.Combine(install, ".GC", "bin"));
|
||||
File.WriteAllText(Path.Combine(install, ".GC", "config", "settings.json"), "{\"theme\":\"dark\"}");
|
||||
File.WriteAllText(Path.Combine(install, ".GC", "model", "earth-rotation", "a.bin"), "model");
|
||||
File.WriteAllText(Path.Combine(install, ".GC", "bin", "GC-SAVEDOG.exe"), "old-savedog");
|
||||
|
||||
// 假启动器:写健康标记后退出,模拟「新版本起来了」
|
||||
var launcher =
|
||||
"#!/bin/sh\n" +
|
||||
"cat > '" + Path.Combine(updateDirFull, "health.json") + "' <<'JSON'\n" +
|
||||
"{\"version\":\"9.9.9\",\"pid\":4242,\"at\":\"2026-01-01T00:00:00Z\",\"ok\":true}\n" +
|
||||
"JSON\n" +
|
||||
"exit 0\n";
|
||||
|
||||
var zip = WritePackage(update, new Dictionary<string, string>
|
||||
{
|
||||
["GCL-9.9.9-test-amd64.exe"] = launcher,
|
||||
[".GC/bin/GC-SAVEDOG.exe"] = "new-savedog",
|
||||
["GC-UI.exe"] = "ui"
|
||||
});
|
||||
WriteRequest(update, "GCL-9.9.9-test-amd64.exe", Sha256File(zip));
|
||||
|
||||
var code = Apply(update, install, dryRun: false, timeoutSeconds: 10);
|
||||
Check("启动健康后更新成功(exit=0)", code == 0, $"exit={code}");
|
||||
Check("新启动器就位",
|
||||
File.Exists(Path.Combine(install, "GCL-9.9.9-test-amd64.exe")), "新启动器缺失");
|
||||
Check("新前端就位", File.Exists(Path.Combine(install, "GC-UI.exe")), "GC-UI.exe 缺失");
|
||||
Check(".GC/bin 被合并",
|
||||
File.ReadAllText(Path.Combine(install, ".GC", "bin", "GC-SAVEDOG.exe")) == "new-savedog",
|
||||
".GC/bin/GC-SAVEDOG.exe 没被替换");
|
||||
Check("用户设置原样保留",
|
||||
File.ReadAllText(Path.Combine(install, ".GC", "config", "settings.json")) == "{\"theme\":\"dark\"}",
|
||||
"settings.json 被覆盖");
|
||||
Check("模型目录原样保留",
|
||||
File.Exists(Path.Combine(install, ".GC", "model", "earth-rotation", "a.bin")),
|
||||
"模型文件被删除");
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ 辅助
|
||||
|
||||
private static int Apply(string updateDir, string installDir, bool dryRun, int timeoutSeconds = 10)
|
||||
{
|
||||
var log = new Log(Path.Combine(updateDir, "logs"));
|
||||
var applier = new Applier(new ApplyOptions
|
||||
{
|
||||
UpdateDir = updateDir,
|
||||
InstallDir = installDir,
|
||||
DryRun = dryRun,
|
||||
TimeoutSeconds = timeoutSeconds,
|
||||
RequireSignature = false, // 用例不生成签名清单;验签本身由 --update-test 覆盖
|
||||
Force = false
|
||||
}, log);
|
||||
return applier.Run();
|
||||
}
|
||||
|
||||
private static (string Install, string Update) Sandbox(string name)
|
||||
{
|
||||
var baseDir = Path.Combine(_root, name);
|
||||
var install = Path.Combine(baseDir, "app");
|
||||
var update = Path.Combine(baseDir, "update");
|
||||
Directory.CreateDirectory(install);
|
||||
Directory.CreateDirectory(update);
|
||||
File.WriteAllText(Path.Combine(update, "version.json"), "{\"launcher\":{\"version\":\"9.9.9\"}}");
|
||||
return (install, update);
|
||||
}
|
||||
|
||||
private static string WritePackage(string updateDir, IDictionary<string, string> files)
|
||||
{
|
||||
var zipPath = Path.Combine(updateDir, "package.zip");
|
||||
try { File.Delete(zipPath); } catch { }
|
||||
using (var archive = ZipFile.Open(zipPath, ZipArchiveMode.Create))
|
||||
{
|
||||
foreach (var (name, text) in files)
|
||||
{
|
||||
var entry = archive.CreateEntry(name.Replace('\\', '/'), CompressionLevel.Fastest);
|
||||
using var stream = entry.Open();
|
||||
var bytes = Encoding.UTF8.GetBytes(text);
|
||||
stream.Write(bytes, 0, bytes.Length);
|
||||
}
|
||||
}
|
||||
return zipPath;
|
||||
}
|
||||
|
||||
/// <summary>手写申请文件:不引用 Json 序列化助手(同名类型在两个程序集里都有)。</summary>
|
||||
private static void WriteRequest(string updateDir, string packageName, string? sha)
|
||||
{
|
||||
var zipPath = Path.Combine(updateDir, "package.zip");
|
||||
var size = File.Exists(zipPath) ? new FileInfo(zipPath).Length : 0;
|
||||
var json = new StringBuilder()
|
||||
.Append("{\n")
|
||||
.Append(" \"schema\": 1,\n")
|
||||
.Append(" \"version\": \"9.9.9\",\n")
|
||||
.Append(" \"rid\": \"test-amd64\",\n")
|
||||
.Append(" \"platformLabel\": \"test-amd64\",\n")
|
||||
.Append(" \"packageName\": ").Append(Quote(packageName)).Append(",\n")
|
||||
.Append(" \"payloadDir\": \"payload\",\n")
|
||||
.Append(" \"installRelative\": \"../app\",\n")
|
||||
.Append(" \"manifestPath\": \"version.json\",\n")
|
||||
.Append(" \"packageZip\": \"package.zip\",\n")
|
||||
.Append(" \"packageSha256\": ").Append(sha == null ? "null" : Quote(sha)).Append(",\n")
|
||||
.Append(" \"packageSize\": ").Append(size).Append(",\n")
|
||||
.Append(" \"requireSignature\": false\n")
|
||||
.Append("}\n")
|
||||
.ToString();
|
||||
File.WriteAllText(Path.Combine(updateDir, "apply-request.json"), json);
|
||||
}
|
||||
|
||||
private static string Quote(string value) => "\"" + value.Replace("\\", "\\\\").Replace("\"", "\\\"") + "\"";
|
||||
|
||||
private static string Sha256File(string path)
|
||||
{
|
||||
using var stream = File.OpenRead(path);
|
||||
return Convert.ToHexString(SHA256.HashData(stream)).ToLowerInvariant();
|
||||
}
|
||||
|
||||
private static void Check(string label, bool ok, string detail)
|
||||
{
|
||||
if (ok)
|
||||
{
|
||||
Console.WriteLine(" ✓ " + label);
|
||||
return;
|
||||
}
|
||||
_failed++;
|
||||
Console.WriteLine($" ✗ {label} —— {detail}");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<!--
|
||||
应用器测试:只引用 GC-SAVEDOG。
|
||||
|
||||
不并入 GC.Tests 的原因见 ApplierTests.cs 顶部注释 —— 守护进程把 GC/src/Security
|
||||
以源码链接编进了自己,与启动器程序集存在同名类型,同一工程内同时引用会撞类型。
|
||||
-->
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<Nullable>enable</Nullable>
|
||||
<RootNamespace>GC.Savedog.Tests</RootNamespace>
|
||||
<AssemblyName>GC.Savedog.Tests</AssemblyName>
|
||||
<InvariantGlobalization>true</InvariantGlobalization>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="../../../../../GC-SAVEDOG/GC-SAVEDOG.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -0,0 +1,67 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using GC.Services;
|
||||
|
||||
namespace GC.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// 日志模块的用例:双语写入、跨天文件命名、旧日志清理、不误删用户文件。
|
||||
///
|
||||
/// 这些看起来是小事,但 <c>.GC/logs</c> 会随程序跑很久:写入路径每行开两个文件句柄,
|
||||
/// 或者完全不清理,都会在几个月后变成用户磁盘上的几 GB。用例锁住这两个行为。
|
||||
/// </summary>
|
||||
internal static class LogTests
|
||||
{
|
||||
private static int _failed;
|
||||
|
||||
public static int Run()
|
||||
{
|
||||
var dir = Path.Combine(Path.GetTempPath(), "gc-log-" + Guid.NewGuid().ToString("N")[..8]);
|
||||
Directory.CreateDirectory(dir);
|
||||
try
|
||||
{
|
||||
// 过期日志(2000 年)+ 用户自己的文件
|
||||
var oldZh = Path.Combine(dir, "gc-20000101.log");
|
||||
var oldEn = Path.Combine(dir, "gc-20000101.en.log");
|
||||
var userFile = Path.Combine(dir, "keep-me.txt");
|
||||
File.WriteAllText(oldZh, "old");
|
||||
File.WriteAllText(oldEn, "old");
|
||||
File.WriteAllText(userFile, "user data");
|
||||
|
||||
GcLog.Init(dir);
|
||||
GcLog.Info("测试中文", "test english");
|
||||
|
||||
var day = DateTime.Now.ToString("yyyyMMdd");
|
||||
var zhPath = Path.Combine(dir, $"gc-{day}.log");
|
||||
var enPath = Path.Combine(dir, $"gc-{day}.en.log");
|
||||
|
||||
Check("中文日志写入", File.Exists(zhPath) && File.ReadAllText(zhPath).Contains("测试中文"), "中文日志缺失");
|
||||
Check("英文日志写入", File.Exists(enPath) && File.ReadAllText(enPath).Contains("test english"), "英文日志缺失");
|
||||
Check("过期日志被清理", !File.Exists(oldZh) && !File.Exists(oldEn), "2000 年的日志还在");
|
||||
Check("目录里的用户文件不被误删", File.Exists(userFile), "keep-me.txt 被删了");
|
||||
|
||||
var names = Directory.GetFiles(dir).Select(Path.GetFileName).OrderBy(n => n).ToArray();
|
||||
Check("日志目录只剩当天两份 + 用户文件",
|
||||
names.Length == 3, "目录内容: " + string.Join(", ", names));
|
||||
}
|
||||
finally
|
||||
{
|
||||
try { Directory.Delete(dir, true); } catch { }
|
||||
}
|
||||
|
||||
Console.WriteLine(_failed == 0 ? "日志测试全部通过" : $"日志测试失败 {_failed} 项");
|
||||
return _failed;
|
||||
}
|
||||
|
||||
private static void Check(string label, bool ok, string detail)
|
||||
{
|
||||
if (ok)
|
||||
{
|
||||
Console.WriteLine(" ✓ " + label);
|
||||
return;
|
||||
}
|
||||
_failed++;
|
||||
Console.WriteLine($" ✗ {label} —— {detail}");
|
||||
}
|
||||
}
|
||||
@@ -51,7 +51,9 @@ internal static class Program
|
||||
RenderPages(services);
|
||||
|
||||
Console.WriteLine("截图输出: " + Path.GetFullPath(_outDir));
|
||||
return 0;
|
||||
|
||||
// 日志模块的用例放在渲染之后:它会切换 GcLog 的输出目录
|
||||
return LogTests.Run() == 0 ? 0 : 1;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
@@ -59,9 +59,11 @@ mkdir -p "$ROOT_DIR/build/logs"
|
||||
. "$ROOT_DIR/buildsh/build.sh"
|
||||
. "$ROOT_DIR/buildsh/check.sh"
|
||||
. "$ROOT_DIR/buildsh/tools.sh"
|
||||
. "$ROOT_DIR/buildsh/release.sh"
|
||||
|
||||
case "$TASK" in
|
||||
build) bs_build "$ROOT_DIR" ;;
|
||||
check) bs_check "$ROOT_DIR" ;;
|
||||
build) bs_build "$ROOT_DIR" ;;
|
||||
check) bs_check "$ROOT_DIR" ;;
|
||||
release-verify) bs_verify_release "$ROOT_DIR" "$@" ;;
|
||||
*) bs_tools "$ROOT_DIR" "$TASK" ;;
|
||||
esac
|
||||
@@ -6,7 +6,12 @@ function Invoke-BuildTool {
|
||||
'pack-models' { Build-Models; Pack-Models }
|
||||
'pack-launcher'{ Pack-Launcher }
|
||||
'run' { & dotnet run --project $script:AppProject -c Debug; if ($LASTEXITCODE -ne 0) { throw "dotnet run 失败,退出码 $LASTEXITCODE" } }
|
||||
'test' { & dotnet run --project $script:TestProject -c Debug -- (Join-Path $script:BuildRoot 'build/screenshots'); if ($LASTEXITCODE -ne 0) { throw "测试失败,退出码 $LASTEXITCODE" } }
|
||||
'test' {
|
||||
& dotnet run --project $script:TestProject -c Debug -- (Join-Path $script:BuildRoot 'build/screenshots')
|
||||
if ($LASTEXITCODE -ne 0) { throw "测试失败,退出码 $LASTEXITCODE" }
|
||||
# 与 pr-check.yml 一致:应用器测试单独跑(它与启动器有同名类型,不能并入 GC.Tests)
|
||||
Invoke-SavedogTests
|
||||
}
|
||||
'update-test' { & dotnet run --project $script:TestProject -c Debug -- --update-test $script:BuildRoot; if ($LASTEXITCODE -ne 0) { throw "更新测试失败,退出码 $LASTEXITCODE" } }
|
||||
'clean' {
|
||||
Remove-Item (Join-Path $script:BuildRoot 'build'), (Join-Path $script:BuildRoot 'dist') -Recurse -Force -ErrorAction SilentlyContinue
|
||||
|
||||
+7
-5
@@ -1,7 +1,7 @@
|
||||
param(
|
||||
[Parameter(Position = 0)]
|
||||
[ValidateSet('build','check','models','stamp','pack-models','pack-launcher',
|
||||
'run','test','update-test','clean','doctor','dist')]
|
||||
'release-verify','run','test','update-test','clean','doctor','dist')]
|
||||
[string]$Task = 'build',
|
||||
[string]$Version = ''
|
||||
)
|
||||
@@ -23,7 +23,8 @@ try {
|
||||
if (-not $Version) { $Version = '1.0.0' }
|
||||
$script:BuildVersion = $Version
|
||||
|
||||
if ($PSBoundParameters.ContainsKey('Version')) {
|
||||
# release-verify 的 -Version 是「要核对的 tag」,不是改版本号:绝不能改写清单
|
||||
if ($PSBoundParameters.ContainsKey('Version') -and $Task -ne 'release-verify') {
|
||||
if ($null -eq $versionNode) { throw 'Directory.Build.props 中找不到 Version 节点。' }
|
||||
$versionNode.InnerText = $Version
|
||||
$props.Save((Join-Path $script:BuildRoot 'Directory.Build.props'))
|
||||
@@ -37,9 +38,10 @@ try {
|
||||
. (Join-Path $PSScriptRoot 'Build-Tools.ps1')
|
||||
|
||||
switch ($Task) {
|
||||
'build' { Invoke-FullBuild }
|
||||
'check' { Invoke-BuildCheck }
|
||||
default { Invoke-BuildTool $Task }
|
||||
'build' { Invoke-FullBuild }
|
||||
'check' { Invoke-BuildCheck }
|
||||
'release-verify' { Invoke-ReleaseVerify -Tag $Version }
|
||||
default { Invoke-BuildTool $Task }
|
||||
}
|
||||
}
|
||||
finally {
|
||||
|
||||
+145
-73
@@ -18,7 +18,9 @@ function Invoke-ManifestSign {
|
||||
Write-Host '!! 未找到签名私钥 .signing/gc-signing.pem,version.json 未签名(客户端会拒绝更新)'
|
||||
return
|
||||
}
|
||||
$keyId = if ($env:GC_SIGNING_KEY_ID) { $env:GC_SIGNING_KEY_ID } else { 'gc-2026-11' }
|
||||
# 与 buildsh/lib/build_funcs.sh 保持一致:当前生效的密钥是 gc-2026-12。
|
||||
# gc-2026-11 的私钥没有留存,用它签出来的清单客户端永远验不过。
|
||||
$keyId = if ($env:GC_SIGNING_KEY_ID) { $env:GC_SIGNING_KEY_ID } else { 'gc-2026-12' }
|
||||
Write-Host "==> 签名 version.json ($keyId)"
|
||||
Invoke-LoggedDotNet -Name 'sign' -Arguments @(
|
||||
'run', '--project', (Join-Path $script:BuildRoot 'GC-SAVEDOG/GC-SAVEDOG.csproj'),
|
||||
@@ -30,7 +32,7 @@ function Invoke-ManifestSign {
|
||||
}
|
||||
|
||||
function Invoke-VersionStamp {
|
||||
param([switch]$LauncherOnly)
|
||||
param([switch]$LauncherOnly, [switch]$NoSign)
|
||||
if ($LauncherOnly) {
|
||||
Write-Host '==> 刷新启动器包信息(sha256 / 体积 / dist 路径)'
|
||||
Invoke-LoggedDotNet -Name 'stamp' -Arguments @(
|
||||
@@ -45,7 +47,14 @@ function Invoke-VersionStamp {
|
||||
$script:BuildRoot, $script:BuildVersion
|
||||
)
|
||||
}
|
||||
Invoke-ManifestSign
|
||||
# 完整 build 末尾 Pack-Launcher 会统一签一次(末次签名);中间这次是浪费的。
|
||||
# 单独的 stamp / models 工具没有后续打包,仍走默认签名。
|
||||
if ($NoSign) {
|
||||
Write-Host ' (跳过签名,打包结束后统一签一次)'
|
||||
}
|
||||
else {
|
||||
Invoke-ManifestSign
|
||||
}
|
||||
}
|
||||
|
||||
function Build-Models {
|
||||
@@ -78,44 +87,41 @@ function Prepare-RuntimeLayout {
|
||||
$destination = Join-Path $script:BuildRoot $RelativePath
|
||||
if (-not (Test-Path $destination)) { return }
|
||||
|
||||
Remove-Item (Join-Path $destination 'model'), (Join-Path $destination 'examples') -Recurse -Force -ErrorAction SilentlyContinue
|
||||
New-Item -ItemType Directory -Force -Path (Join-Path $destination '.GC/model'), (Join-Path $destination '.GC/cache'), (Join-Path $destination '.GC/update'), (Join-Path $destination '.GC/config') | Out-Null
|
||||
Set-Content -Path (Join-Path $destination '.GC/model/README.txt') -Encoding UTF8 -Value @'
|
||||
模型库目录(.GC/model/)
|
||||
启动时程序会读取 GitCode 仓库的 version.json,把最新版模型下载到这里。
|
||||
离线使用也可以手动放入 <模型id>/<模型id>.json + <模型id>/<模型id>.model/。
|
||||
|
||||
运行目录:
|
||||
<可执行文件>
|
||||
GC-SAVEDOG 更新守护进程(验签 + 原子替换 + 失败回滚)
|
||||
.GC/config/settings.json 用户设置(删 .GC/cache 不会丢配置)
|
||||
.GC/model/ 本目录(下载的模型)
|
||||
.GC/cache/ 下载暂存
|
||||
.GC/update/ 待下次启动应用的启动器更新
|
||||
'@
|
||||
$settingsPath = Join-Path $destination '.GC/config/settings.json'
|
||||
if (-not (Test-Path $settingsPath)) {
|
||||
Set-Content -Path $settingsPath -Encoding UTF8 -Value @'
|
||||
{
|
||||
"language": "auto",
|
||||
"theme": "light",
|
||||
"renderFps": 30,
|
||||
"memoryMb": 2048,
|
||||
"autoUpdateOnStartup": true,
|
||||
"requireSignedManifest": true,
|
||||
"updateRepository": "https://gitcode.com/Morris_1/GC",
|
||||
"updateManifestUrl": "",
|
||||
"updateLocalRoot": "",
|
||||
"installedModelVersions": {},
|
||||
"launcherVersion": "",
|
||||
"pendingLauncherVersion": "",
|
||||
"lastUpdateCheck": "",
|
||||
"sources": [],
|
||||
"recentModels": []
|
||||
# 与 buildsh/lib/build_funcs.sh 一致:发布目录只放程序本体,不预置 .GC。
|
||||
# .GC(config / model / cache / update / safedog / logs)一律在首次启动时
|
||||
# 由 AppPaths.EnsureCreated + RuntimeLayout 创建,压缩包里只有 GC 本体。
|
||||
Remove-Item (Join-Path $destination 'model'), (Join-Path $destination 'examples'), (Join-Path $destination '.GC') -Recurse -Force -ErrorAction SilentlyContinue
|
||||
Write-Host " 运行目录 -> $RelativePath(首次启动后生成 .GC/:config model cache update safedog logs)"
|
||||
}
|
||||
'@
|
||||
|
||||
function Prune-Package {
|
||||
param(
|
||||
[Parameter(Mandatory)][string]$Destination,
|
||||
[Parameter(Mandatory)][ValidateSet('win', 'linux')][string]$Platform
|
||||
)
|
||||
if (-not (Test-Path $Destination)) { return }
|
||||
$junk = @(
|
||||
'mscordaccore.dll', 'mscordbi.dll', 'web.config',
|
||||
'aspnetcorev2_inprocess.dll',
|
||||
'Microsoft.AspNetCore.Server.IIS.dll',
|
||||
'Microsoft.AspNetCore.Server.IISIntegration.dll',
|
||||
'Microsoft.AspNetCore.Server.HttpSys.dll',
|
||||
'Microsoft.DiaSymReader.Native.dll'
|
||||
)
|
||||
if ($Platform -eq 'win') {
|
||||
# 后端已编入启动器,ProjectReference 残留的独立 exe / runtimeconfig 没有用
|
||||
$junk += @('GC.UI.Server.exe', 'GC.UI.Server.dll', 'GC.UI.Server.deps.json', 'GC.UI.Server.runtimeconfig.json')
|
||||
$junk += @('Avalonia.X11.dll', 'Avalonia.Native.dll', 'Avalonia.FreeDesktop.dll', 'Tmds.DBus.Protocol.dll')
|
||||
}
|
||||
Write-Host " 运行目录 -> $RelativePath/.GC"
|
||||
else {
|
||||
$junk += @('Avalonia.Win32.dll', 'Avalonia.Win32.Automation.dll')
|
||||
}
|
||||
foreach ($name in $junk) {
|
||||
Get-ChildItem $Destination -Filter $name -File -ErrorAction SilentlyContinue | Remove-Item -Force -ErrorAction SilentlyContinue
|
||||
}
|
||||
# mscordaccore*.dll / Microsoft.DiaSymReader.Native*.dll 是带版本号通配的
|
||||
Get-ChildItem $Destination -Filter 'mscordaccore*.dll' -File -ErrorAction SilentlyContinue | Remove-Item -Force -ErrorAction SilentlyContinue
|
||||
Get-ChildItem $Destination -Filter 'Microsoft.DiaSymReader.Native*.dll' -File -ErrorAction SilentlyContinue | Remove-Item -Force -ErrorAction SilentlyContinue
|
||||
}
|
||||
|
||||
function Publish-Rid {
|
||||
@@ -132,18 +138,22 @@ function Publish-Rid {
|
||||
'publish', $script:AppProject, '-c', 'Release', '-r', $Rid,
|
||||
'--self-contained', 'true', "-p:Version=$script:BuildVersion", '-p:DebugType=none',
|
||||
"-p:PublishSingleFile=$singleValue", "-p:IncludeNativeLibrariesForSelfExtract=$singleValue",
|
||||
"-p:EnableCompressionInSingleFile=$singleValue",
|
||||
'-p:PublishTrimmed=false', '-o', $outputPath
|
||||
)
|
||||
|
||||
# 更新守护进程:与主程序同目录(裁剪单文件,70MB -> 14MB)
|
||||
# 裁剪的前提是 JSON 全部走源生成上下文(GC-SAVEDOG/SavedogJson.cs)
|
||||
# 更新守护进程:与主程序同目录(裁剪 + 压缩单文件,70MB -> 14MB)
|
||||
# 裁剪的前提是 JSON 全部走源生成上下文(GC-SAVEDOG/SavedogJson.cs)。
|
||||
# EnableCompressionInSingleFile:守护进程不常驻,只在更新时跑一次,
|
||||
# 解压一次换来更小的包,对「只在更新时下载」的场景很划算。
|
||||
$savedogProj = Join-Path $script:BuildRoot 'GC-SAVEDOG/GC-SAVEDOG.csproj'
|
||||
if (Test-Path $savedogProj) {
|
||||
Write-Host "==> 编译 GC-SAVEDOG ($Rid)(裁剪单文件)"
|
||||
Write-Host "==> 编译 GC-SAVEDOG ($Rid)(裁剪 + 压缩单文件)"
|
||||
Invoke-LoggedDotNet -Name "savedog-$($Rid -replace '-', '')" -Arguments @(
|
||||
'publish', $savedogProj, '-c', 'Release', '-r', $Rid,
|
||||
'--self-contained', 'true', "-p:Version=$script:BuildVersion", '-p:DebugType=none',
|
||||
'-p:PublishSingleFile=true', '-p:IncludeNativeLibrariesForSelfExtract=true',
|
||||
'-p:EnableCompressionInSingleFile=true',
|
||||
'-p:PublishTrimmed=true', '-p:TrimMode=full',
|
||||
'-p:JsonSerializerIsReflectionEnabledByDefault=false', '-o', $outputPath
|
||||
)
|
||||
@@ -178,35 +188,60 @@ function Pack-Models {
|
||||
|
||||
function Pack-Launcher {
|
||||
$dist = Join-Path $script:BuildRoot 'dist'
|
||||
Write-Host "==> 生成启动器产物(GC-$script:BuildVersion-<平台>)"
|
||||
Write-Host "==> 生成启动器产物(GCL-$script:BuildVersion-<系统>-<架构>)"
|
||||
|
||||
# 与 buildsh/lib/build_funcs.sh 的 pack_launcher 对齐:
|
||||
# 1) 包名统一 GCL- 前缀;
|
||||
# 2) zip 内只有一个顶层目录(GCL-<版本>-<平台>),不散落一屏 dll;
|
||||
# 3) 非本体文件(守护进程)收进 .GC/bin,安装目录根只留 GC 本体;
|
||||
# 4) 剔除调试 / 无关平台的组件(prune)。
|
||||
|
||||
# --- Windows:启动器 + 守护进程 + 前端,整目录打进单顶层目录 ---
|
||||
foreach ($platform in @(@{ Rid = 'win-x64'; Label = 'win-amd64' }, @{ Rid = 'win-arm64'; Label = 'win-arm64' })) {
|
||||
# 产物落点 dist/<系统>-<架构>/,与 dist/mac-arm64 一致
|
||||
$sourceDir = Join-Path $dist $platform.Label
|
||||
if (-not (Test-Path $sourceDir)) { $sourceDir = Join-Path $dist $platform.Rid }
|
||||
if (-not (Test-Path $sourceDir)) { continue }
|
||||
# 注意排除守护进程:GC-SAVEDOG.exe 在字典序里排在 GC.exe 前面
|
||||
$executable = Get-ChildItem $sourceDir -Filter '*.exe' |
|
||||
Where-Object { $_.Name -notlike 'GC-SAVEDOG*' } | Select-Object -First 1
|
||||
if ($null -eq $executable) { continue }
|
||||
|
||||
# 启动器固定是 GC.exe;后端与前端是可选的随包产物,不能当成启动器
|
||||
$exe = Join-Path $sourceDir 'GC.exe'
|
||||
if (-not (Test-Path $exe)) {
|
||||
$exe = (Get-ChildItem $sourceDir -Filter '*.exe' | Where-Object {
|
||||
$_.Name -notlike 'GC-SAVEDOG*' -and $_.Name -notlike 'GC.UI.Server*' -and $_.Name -notlike 'GC-UI*'
|
||||
} | Select-Object -First 1).FullName
|
||||
}
|
||||
if (-not $exe) { continue }
|
||||
|
||||
$pkgName = "GCL-$script:BuildVersion-$($platform.Label)"
|
||||
$temp = Join-Path $dist ".winpkg-$($platform.Label)"
|
||||
$pkg = Join-Path $temp $pkgName
|
||||
Remove-Item $temp -Recurse -Force -ErrorAction SilentlyContinue
|
||||
New-Item -ItemType Directory -Force -Path $temp | Out-Null
|
||||
Copy-Item $executable.FullName (Join-Path $temp "GC-$script:BuildVersion-$($platform.Label).exe") -Force
|
||||
$savedogExe = Join-Path $sourceDir 'GC-SAVEDOG.exe'
|
||||
if (Test-Path $savedogExe) { Copy-Item $savedogExe (Join-Path $temp 'GC-SAVEDOG.exe') -Force }
|
||||
New-Item -ItemType Directory -Force -Path $pkg | Out-Null
|
||||
Get-ChildItem $sourceDir -Force | Where-Object { $_.Extension -ne '.zip' } | Copy-Item -Destination $pkg -Recurse -Force
|
||||
Prune-Package -Destination $pkg -Platform 'win'
|
||||
Move-Item (Join-Path $pkg (Split-Path $exe -Leaf)) (Join-Path $pkg "$pkgName.exe") -Force
|
||||
if (Get-Command chmod -ErrorAction SilentlyContinue) { & chmod +x (Join-Path $pkg "$pkgName.exe") 2>$null }
|
||||
|
||||
$zipPath = Join-Path $dist "$($platform.Label)/GC-$script:BuildVersion-$($platform.Label).zip"
|
||||
$savedogExe = Join-Path $pkg 'GC-SAVEDOG.exe'
|
||||
if (Test-Path $savedogExe) {
|
||||
$binDir = Join-Path $pkg '.GC/bin'
|
||||
New-Item -ItemType Directory -Force -Path $binDir | Out-Null
|
||||
Move-Item $savedogExe (Join-Path $binDir 'GC-SAVEDOG.exe') -Force
|
||||
}
|
||||
else {
|
||||
Write-Host " !! 缺少 GC-SAVEDOG.exe,该平台将退回旧脚本更新"
|
||||
}
|
||||
|
||||
$zipPath = Join-Path $dist "$($platform.Label)/$pkgName.zip"
|
||||
Remove-Item $zipPath -Force -ErrorAction SilentlyContinue
|
||||
Compress-Archive -Path (Join-Path $temp '*') -DestinationPath $zipPath -CompressionLevel Optimal
|
||||
Compress-Archive -Path $pkg -DestinationPath $zipPath -CompressionLevel Optimal
|
||||
Remove-Item $temp -Recurse -Force -ErrorAction SilentlyContinue
|
||||
Write-Host " -> dist/$($platform.Label)/GC-$script:BuildVersion-$($platform.Label).zip"
|
||||
Write-Host " -> dist/$($platform.Label)/$pkgName.zip"
|
||||
}
|
||||
|
||||
# --- macOS:先得到真实 .app 目录(改名 + 同步 Info.plist + 守护进程入 .GC/bin) ---
|
||||
$macApp = Join-Path $dist 'mac-arm64/GC.app'
|
||||
if (Test-Path $macApp) {
|
||||
$finalApp = Join-Path $dist "GC-$script:BuildVersion-mac-arm64.app"
|
||||
$finalApp = Join-Path $dist "GCL-$script:BuildVersion-mac-arm64.app"
|
||||
Remove-Item $finalApp -Recurse -Force -ErrorAction SilentlyContinue
|
||||
Move-Item $macApp $finalApp
|
||||
$binary = Join-Path $finalApp 'Contents/MacOS/GC'
|
||||
@@ -216,20 +251,25 @@ function Pack-Launcher {
|
||||
& /usr/libexec/PlistBuddy -c 'Set :CFBundleName Morris GC' $plist 2>$null
|
||||
& /usr/libexec/PlistBuddy -c 'Set :CFBundleDisplayName Morris GC' $plist 2>$null
|
||||
}
|
||||
# 非本体文件收进 .GC/bin(与 Windows 布局一致):.GC 位置不变,仍在 .app/Contents/MacOS/
|
||||
$savedog = Join-Path $finalApp 'Contents/MacOS/GC-SAVEDOG'
|
||||
if (Test-Path $savedog) {
|
||||
$binDir = Join-Path $finalApp 'Contents/MacOS/.GC/bin'
|
||||
New-Item -ItemType Directory -Force -Path $binDir | Out-Null
|
||||
Move-Item $savedog (Join-Path $binDir 'GC-SAVEDOG') -Force
|
||||
if (Get-Command chmod -ErrorAction SilentlyContinue) { & chmod +x (Join-Path $binDir 'GC-SAVEDOG') 2>$null }
|
||||
}
|
||||
if (Get-Command xattr -ErrorAction SilentlyContinue) { & xattr -cr $finalApp 2>$null }
|
||||
}
|
||||
|
||||
# Windows 的 zip 已在上面的循环里生成(含 GC-SAVEDOG.exe),这里只处理 .app
|
||||
Get-ChildItem $dist | Where-Object { $_.Name -like "GC-$script:BuildVersion-*.app" } | ForEach-Object {
|
||||
$label = $_.BaseName -replace "^GC-$([regex]::Escape($script:BuildVersion))-", ''
|
||||
# --- 统一压缩:.app -> 同名 .zip,放进平台目录 ---
|
||||
Get-ChildItem $dist | Where-Object { $_.Name -like "GCL-$script:BuildVersion-*.app" } | ForEach-Object {
|
||||
$label = $_.BaseName -replace "^GCL-$([regex]::Escape($script:BuildVersion))-", ''
|
||||
$targetDir = Join-Path $dist $label
|
||||
New-Item -ItemType Directory -Force -Path $targetDir | Out-Null
|
||||
$zipPath = Join-Path $targetDir ($_.BaseName + '.zip')
|
||||
Remove-Item $zipPath -Force -ErrorAction SilentlyContinue
|
||||
if ($_.PSIsContainer) {
|
||||
Remove-Item (Join-Path $_.FullName 'Contents/MacOS/.GC') -Recurse -Force -ErrorAction SilentlyContinue
|
||||
}
|
||||
if ($_.PSIsContainer -and (Get-Command ditto -ErrorAction SilentlyContinue)) {
|
||||
if (Get-Command ditto -ErrorAction SilentlyContinue) {
|
||||
& ditto -c -k --sequesterRsrc --keepParent $_.FullName $zipPath
|
||||
if ($LASTEXITCODE -ne 0) { throw "ditto 压缩失败:$($_.Name)" }
|
||||
}
|
||||
@@ -239,26 +279,26 @@ function Pack-Launcher {
|
||||
Write-Host " -> dist/$label/$($_.BaseName).zip"
|
||||
}
|
||||
|
||||
# 原始产物(.exe / .app 目录)不再保留:只发布 zip
|
||||
# 原始产物(.exe / .app 目录)不再保留:只发布 zip(移入暂存区,不做递归删除)
|
||||
$trash = Join-Path $script:BuildRoot 'build/trash'
|
||||
New-Item -ItemType Directory -Force -Path $trash | Out-Null
|
||||
Get-ChildItem $dist -Force | Where-Object {
|
||||
$_.Name -like "GC-$script:BuildVersion-*.exe" -or $_.Name -like "GC-$script:BuildVersion-*.app"
|
||||
$_.Name -like "GCL-$script:BuildVersion-*.exe" -or $_.Name -like "GCL-$script:BuildVersion-*.app"
|
||||
} | ForEach-Object {
|
||||
Move-Item $_.FullName (Join-Path $trash "$($_.Name)-$([DateTime]::Now.Ticks)") -Force -ErrorAction SilentlyContinue
|
||||
}
|
||||
Remove-IntermediateDirectories
|
||||
Invoke-VersionStamp -LauncherOnly
|
||||
Write-Host '==> dist 可发布 zip:'
|
||||
Get-ChildItem $dist -Recurse -Filter "GC-$script:BuildVersion-*.zip" | Select-Object FullName, Length
|
||||
Get-ChildItem $dist -Recurse -Filter "GCL-$script:BuildVersion-*.zip" | Select-Object FullName, Length
|
||||
}
|
||||
|
||||
function Remove-IntermediateDirectories {
|
||||
# 平台目录里只留最终 zip(其它都是 publish 中间产物)
|
||||
foreach ($name in @('win-amd64', 'win-x64', 'win-arm64', 'mac-arm64')) {
|
||||
foreach ($name in @('win-amd64', 'win-x64', 'win-arm64', 'mac-arm64', 'linux-arm64', 'linux-x64')) {
|
||||
$dir = Join-Path $script:BuildRoot "dist/$name"
|
||||
if (-not (Test-Path $dir)) { continue }
|
||||
Get-ChildItem $dir -Force | Where-Object { $_.Name -notlike "GC-$script:BuildVersion-*.zip" } |
|
||||
Get-ChildItem $dir -Force | Where-Object { $_.Name -notlike "GCL-$script:BuildVersion-*.zip" } |
|
||||
Remove-Item -Recurse -Force -ErrorAction SilentlyContinue
|
||||
}
|
||||
Get-ChildItem (Join-Path $script:BuildRoot 'dist') -Filter '.DS_Store' -Recurse -Force -ErrorAction SilentlyContinue | Remove-Item -Force
|
||||
@@ -314,6 +354,36 @@ function New-MacAppBundle {
|
||||
Write-Host "==> 已打包 $app"
|
||||
}
|
||||
|
||||
function Invoke-SavedogTests {
|
||||
$proj = Join-Path $script:BuildRoot 'GC/src/test/dotnet/GC.Savedog.Tests/GC.Savedog.Tests.csproj'
|
||||
Write-Host '==> 运行应用器测试(整目录替换 / .GC/bin 合并 / 回滚)'
|
||||
& dotnet run --project $proj -c Debug
|
||||
if ($LASTEXITCODE -ne 0) { throw "应用器测试失败,退出码 $LASTEXITCODE" }
|
||||
}
|
||||
|
||||
function Invoke-ReleaseVerify {
|
||||
param([string]$Tag = '')
|
||||
$root = $script:BuildRoot
|
||||
$verifyTag = if ($Tag) { $Tag } else { $script:BuildVersion }
|
||||
$work = Join-Path $root 'build/release-verify'
|
||||
New-Item -ItemType Directory -Force -Path $work | Out-Null
|
||||
|
||||
Write-Host "==> 核对 Release $verifyTag"
|
||||
$dump = Join-Path $work "$verifyTag.json"
|
||||
& python3 (Join-Path $root 'buildsh/lib/verify_release.py') `
|
||||
--tag $verifyTag `
|
||||
--manifest (Join-Path $root 'version.json') `
|
||||
--dump-manifest $dump
|
||||
if ($LASTEXITCODE -ne 0) { throw "发布一致性核对未通过(tag $verifyTag)" }
|
||||
|
||||
Write-Host ''
|
||||
Write-Host '==> 校验 tag 清单签名'
|
||||
& dotnet run --project (Join-Path $root 'GC-SAVEDOG/GC-SAVEDOG.csproj') -c Release -- `
|
||||
verify --manifest $dump
|
||||
if ($LASTEXITCODE -ne 0) { throw '清单签名校验未通过,客户端会拒绝这次更新' }
|
||||
Write-Host '结论: 签名可信,可以发布 / 已经发布正确'
|
||||
}
|
||||
|
||||
function Invoke-FullBuild {
|
||||
Initialize-BuildProgress @('清理旧产物', '版本戳', '编译 Mac', '编译 Win-x64', '编译 Win-arm64', '运行骨架', '打包 zip', '收尾')
|
||||
try {
|
||||
@@ -322,10 +392,12 @@ function Invoke-FullBuild {
|
||||
New-Item -ItemType Directory -Force -Path (Join-Path $script:BuildRoot 'dist') | Out-Null
|
||||
Complete-BuildStep
|
||||
|
||||
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' $false; Complete-BuildStep
|
||||
Start-BuildStep '编译 Win-arm64'; Publish-Rid 'win-arm64' 'dist/win-arm64' $false; Complete-BuildStep
|
||||
# 末次签名:这里只生成清单不签名,Pack-Launcher 打完包后统一签一次
|
||||
Start-BuildStep '版本戳'; Invoke-VersionStamp -NoSign; Complete-BuildStep
|
||||
# 与 buildsh 一致:启动器与守护进程都发布为压缩单文件,非本体文件在打包时收进 .GC/bin
|
||||
Start-BuildStep '编译 Mac'; Publish-Rid 'osx-arm64' 'dist/mac-arm64' $true; Complete-BuildStep
|
||||
Start-BuildStep '编译 Win-x64'; Publish-Rid 'win-x64' 'dist/win-amd64' $true; Complete-BuildStep
|
||||
Start-BuildStep '编译 Win-arm64'; Publish-Rid 'win-arm64' 'dist/win-arm64' $true; Complete-BuildStep
|
||||
|
||||
Start-BuildStep '运行骨架'
|
||||
New-MacAppBundle
|
||||
@@ -337,7 +409,7 @@ function Invoke-FullBuild {
|
||||
Start-BuildStep '打包 zip'; Pack-Launcher; Complete-BuildStep
|
||||
Start-BuildStep '收尾'; Complete-BuildStep
|
||||
Write-Host '==> 完成,产物:'
|
||||
Get-ChildItem (Join-Path $script:BuildRoot 'dist') -Recurse -Filter "GC-$script:BuildVersion-*.zip" | Select-Object FullName, Length
|
||||
Get-ChildItem (Join-Path $script:BuildRoot 'dist') -Recurse -Filter "GCL-$script:BuildVersion-*.zip" | Select-Object FullName, Length
|
||||
}
|
||||
finally { Complete-BuildProgress }
|
||||
}
|
||||
+3
-1
@@ -71,7 +71,9 @@ bs_build() {
|
||||
fi
|
||||
|
||||
progress_step "版本戳"; progress_tick 100
|
||||
stamp_versions
|
||||
# 末次签名:这里只生成清单不签名,等 pack_launcher 打完 zip、刷新完包信息后统一签一次。
|
||||
# 避免 ECDSA 随机签名 + 时间戳导致清单在中间反复变化。
|
||||
stamp_versions --no-sign
|
||||
|
||||
# 每个 publish 用后台任务包裹,边跑边按「已用时/预估用时」推进当前步骤进度
|
||||
_run_publish() {
|
||||
|
||||
+13
-24
@@ -6,10 +6,17 @@
|
||||
if ! type step >/dev/null 2>&1; then step() { echo "==> $1"; }; fi
|
||||
if ! type progress >/dev/null 2>&1; then progress() { :; }; fi
|
||||
|
||||
# $1=--no-sign 时只生成清单、不签名。
|
||||
# 完整 build 会在 pack_launcher 末尾统一签一次(末次签名),中间这次签名是浪费的:
|
||||
# ECDSA 用随机 nonce + signedAt 时间戳,每次签名字节都不同,白白多一次全量签名,
|
||||
# 也让中间产物反复抖动。单独的 stamp / models 工具没有后续打包,仍走默认签名。
|
||||
stamp_versions() {
|
||||
echo "==> 自动计算模型版本并生成 version.json"
|
||||
dotnet run --project "$STAMP_PROJ" -c Release -- "$ROOT_DIR" "$VERSION"
|
||||
sign_manifest
|
||||
case "${1:-}" in
|
||||
--no-sign) echo " (跳过签名,打包结束后统一签一次)" ;;
|
||||
*) sign_manifest ;;
|
||||
esac
|
||||
}
|
||||
|
||||
# 打完 zip 之后刷新 launcher.packages(写入 path / dir / name / sha256 / size)。
|
||||
@@ -168,7 +175,7 @@ pack_models() {
|
||||
ZIP="$ROOT_DIR/dist/models-$VERSION.zip"
|
||||
rm -f "$ZIP"
|
||||
echo "==> 打包模型数据 -> dist/models-$VERSION.zip"
|
||||
( cd "$ROOT_DIR" && zip -qr "$ZIP" model \
|
||||
( cd "$ROOT_DIR" && zip -qrX "$ZIP" model \
|
||||
-x "*.DS_Store" "*/bin/*" "*/obj/*" "*.user" )
|
||||
du -sh "$ZIP"
|
||||
}
|
||||
@@ -188,24 +195,6 @@ pack_models() {
|
||||
# macOS: .app 必须打成 zip 才能作为单文件分发;文件名用 .app.zip,
|
||||
# 这样 macOS 双击会用归档工具解压出可运行的 .app。
|
||||
# 若直接命名 .app,系统会把 zip 当成应用包解析 => 报「已损坏/打不开」。
|
||||
# 发布本地 UI 后端(GC.UI.Server)。启动器会拉起它并等待 /api/health,
|
||||
# 模型窗口也由它承载,所以必须和启动器放在同一目录。
|
||||
publish_backend() {
|
||||
RID="$1"; OUT="$2"
|
||||
echo "==> 编译 UI 后端 (${RID}) -> ${OUT}"
|
||||
dotnet publish "$ROOT_DIR/GC-UI/backend/GC.UI.Server/GC.UI.Server.csproj" \
|
||||
-c Release \
|
||||
-r "$RID" \
|
||||
--self-contained true \
|
||||
-p:Version="$VERSION" \
|
||||
-p:DebugType=none \
|
||||
-p:PublishSingleFile=true \
|
||||
-p:IncludeNativeLibrariesForSelfExtract=true \
|
||||
-p:EnableCompressionInSingleFile=true \
|
||||
-p:PublishTrimmed=false \
|
||||
-o "$ROOT_DIR/$OUT" || return 1
|
||||
}
|
||||
|
||||
# 当前主机原生构建 Flutter 前端(Windows 主机编 Windows,macOS 主机编 macOS,
|
||||
# Linux 主机编 Linux)。跨平台的 Windows 版由 build_flutter_ui_cross 负责。
|
||||
#
|
||||
@@ -339,7 +328,7 @@ pack_launcher() {
|
||||
|
||||
ZIP="$ROOT_DIR/dist/$LABEL/$PKGNAME.zip"
|
||||
rm -f "$ZIP"
|
||||
( cd "$TMP" && zip -qr "$ZIP" "$PKGNAME" )
|
||||
( cd "$TMP" && zip -qrX "$ZIP" "$PKGNAME" )
|
||||
rm -rf "$TMP"
|
||||
echo " -> dist/$LABEL/$PKGNAME.zip"
|
||||
done
|
||||
@@ -367,7 +356,7 @@ pack_launcher() {
|
||||
fi
|
||||
ZIP="$ROOT_DIR/dist/linux-arm64/$PKGNAME.zip"
|
||||
rm -f "$ZIP"
|
||||
( cd "$TMP" && zip -qry "$ZIP" "$PKGNAME" )
|
||||
( cd "$TMP" && zip -qryX "$ZIP" "$PKGNAME" )
|
||||
rm -rf "$TMP"
|
||||
echo " -> dist/linux-arm64/$PKGNAME.zip"
|
||||
fi
|
||||
@@ -412,10 +401,10 @@ pack_launcher() {
|
||||
if command -v ditto >/dev/null 2>&1; then
|
||||
ditto -c -k --sequesterRsrc --keepParent "$art" "$ZIP"
|
||||
else
|
||||
( cd "$(dirname "$art")" && zip -qry "$ZIP" "$base" -x "*.DS_Store" )
|
||||
( cd "$(dirname "$art")" && zip -qryX "$ZIP" "$base" -x "*.DS_Store" )
|
||||
fi
|
||||
else
|
||||
( cd "$(dirname "$art")" && zip -q "$ZIP" "$base" )
|
||||
( cd "$(dirname "$art")" && zip -qX "$ZIP" "$base" )
|
||||
fi
|
||||
echo " -> dist/${label}/${name}.zip"
|
||||
done
|
||||
|
||||
Executable
+211
@@ -0,0 +1,211 @@
|
||||
#!/usr/bin/env python3
|
||||
"""核对「仓库清单 ↔ Release 资产」是否对得上。
|
||||
|
||||
为什么需要它:清单里的 sha256 是客户端验证下载包的唯一依据。一旦 Release 上的资产
|
||||
和清单不是同一份(换过一次构建、上传了别的产物、tag 指到了旧提交),客户端会验签
|
||||
失败或直接回滚 —— 用户看到的是「更新失败了」,而服务端一切正常。
|
||||
|
||||
检查项:
|
||||
1. tag 指向的 version.json 里的 launcher.version 等于 tag 名;
|
||||
2. 清单里带 sha256 的平台,Release 上有同名资产,且体积 / sha256 完全一致;
|
||||
3. 清单里没有 sha256 的平台(本次没构建)不要求有资产,但会列出;
|
||||
4. Release 上多出来的资产(清单里没有)单独提示;
|
||||
5. 本地清单与 tag 上的清单是否字节一致。
|
||||
|
||||
只用标准库,Linux / macOS / Windows 上都能跑。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
|
||||
DEFAULT_BASE = os.environ.get("GC_GITEA_URL", "https://git.xhmcl.com")
|
||||
DEFAULT_REPO = os.environ.get("GC_GITEA_REPO", "Morris/GC")
|
||||
|
||||
|
||||
def log(msg: str = "") -> None:
|
||||
print(msg, flush=True)
|
||||
|
||||
|
||||
def http_json(url: str, token: str | None) -> dict:
|
||||
req = urllib.request.Request(url)
|
||||
req.add_header("Accept", "application/json")
|
||||
if token:
|
||||
req.add_header("Authorization", "token " + token)
|
||||
with urllib.request.urlopen(req, timeout=60) as resp:
|
||||
return json.loads(resp.read().decode("utf-8"))
|
||||
|
||||
|
||||
def download_sha256(url: str, token: str | None, dest: str) -> tuple[int, str]:
|
||||
req = urllib.request.Request(url)
|
||||
if token:
|
||||
req.add_header("Authorization", "token " + token)
|
||||
digest = hashlib.sha256()
|
||||
size = 0
|
||||
with urllib.request.urlopen(req, timeout=600) as resp, open(dest, "wb") as out:
|
||||
while True:
|
||||
chunk = resp.read(1 << 20)
|
||||
if not chunk:
|
||||
break
|
||||
size += len(chunk)
|
||||
digest.update(chunk)
|
||||
out.write(chunk)
|
||||
return size, digest.hexdigest()
|
||||
|
||||
|
||||
def main() -> int:
|
||||
parser = argparse.ArgumentParser(description="核对清单与 Release 资产")
|
||||
parser.add_argument("--tag", required=True, help="要核对的 tag,例如 1.1.0")
|
||||
parser.add_argument("--manifest", default="version.json", help="本地清单路径(用于对比)")
|
||||
parser.add_argument("--base-url", default=DEFAULT_BASE)
|
||||
parser.add_argument("--repo", default=DEFAULT_REPO)
|
||||
parser.add_argument("--token", default=os.environ.get("GC_GITEA_TOKEN"))
|
||||
parser.add_argument("--workdir", default=None, help="下载临时目录(默认系统临时目录)")
|
||||
parser.add_argument("--skip-download", action="store_true",
|
||||
help="只核对清单体积与资产列表,不下载算哈希")
|
||||
parser.add_argument("--dump-manifest", default=None,
|
||||
help="把 tag 上的清单原样写到这个路径(供 GC-SAVEDOG verify 验签)")
|
||||
args = parser.parse_args()
|
||||
|
||||
tag = args.tag.strip()
|
||||
if tag.startswith("v"):
|
||||
tag = tag[1:]
|
||||
|
||||
api = f"{args.base_url}/api/v1/repos/{args.repo}"
|
||||
workdir = args.workdir or os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "..", "build", "release-verify")
|
||||
workdir = os.path.abspath(workdir)
|
||||
os.makedirs(workdir, exist_ok=True)
|
||||
|
||||
failures: list[str] = []
|
||||
warnings: list[str] = []
|
||||
|
||||
# ---- 1. tag 上的清单 ----
|
||||
try:
|
||||
remote = http_json(f"{api}/raw/version.json?ref={tag}", args.token)
|
||||
except urllib.error.HTTPError as exc:
|
||||
log(f"!! 取不到 tag {tag} 的 version.json(HTTP {exc.code})")
|
||||
return 1
|
||||
|
||||
if args.dump_manifest:
|
||||
os.makedirs(os.path.dirname(os.path.abspath(args.dump_manifest)), exist_ok=True)
|
||||
with open(args.dump_manifest, "w", encoding="utf-8") as fh:
|
||||
json.dump(remote, fh, ensure_ascii=False, indent=2)
|
||||
|
||||
launcher = remote.get("launcher") or {}
|
||||
remote_version = str(launcher.get("version") or "")
|
||||
log(f"tag : {tag}")
|
||||
log(f"清单版本 : {remote_version or '(空)'}")
|
||||
if remote_version != tag:
|
||||
failures.append(f"tag 指向的清单版本是 {remote_version!r},与 tag {tag} 不一致")
|
||||
|
||||
# 签名状态:交给 GC-SAVEDOG verify 判定(这里只提示有没有签名段)
|
||||
if not remote.get("signature"):
|
||||
failures.append("tag 上的清单没有签名段")
|
||||
else:
|
||||
log(f"清单签名 : {remote['signature'].get('keyId', '?')}")
|
||||
|
||||
# ---- 2. Release 与资产 ----
|
||||
try:
|
||||
release = http_json(f"{api}/releases/tags/{tag}", args.token)
|
||||
except urllib.error.HTTPError as exc:
|
||||
log(f"!! 取不到 Release {tag}(HTTP {exc.code})")
|
||||
return 1
|
||||
|
||||
assets = {a["name"]: a for a in release.get("assets") or []}
|
||||
log(f"Release : id={release.get('id')} prerelease={release.get('prerelease')}")
|
||||
log(f"资产数量 : {len(assets)}")
|
||||
|
||||
packages = launcher.get("packages") or {}
|
||||
declared: set[str] = set()
|
||||
|
||||
log("")
|
||||
log(f"{'平台':<12} {'包':<32} {'结果'}")
|
||||
log("-" * 78)
|
||||
|
||||
for rid, pkg in packages.items():
|
||||
name = str(pkg.get("name") or "")
|
||||
want_sha = str(pkg.get("sha256") or "")
|
||||
want_size = int(pkg.get("size") or 0)
|
||||
if not name:
|
||||
warnings.append(f"{rid}: 清单条目没有 name")
|
||||
continue
|
||||
declared.add(name)
|
||||
|
||||
asset = assets.get(name)
|
||||
if not want_sha:
|
||||
log(f"{rid:<12} {name:<32} 未构建(清单无 sha256)")
|
||||
if asset:
|
||||
warnings.append(f"{rid}: 清单没记录哈希,但 Release 上有 {name}")
|
||||
continue
|
||||
|
||||
if not asset:
|
||||
log(f"{rid:<12} {name:<32} ✗ 资产缺失")
|
||||
failures.append(f"{rid}: Release 上找不到 {name}")
|
||||
continue
|
||||
|
||||
if int(asset.get("size") or 0) != want_size:
|
||||
log(f"{rid:<12} {name:<32} ✗ 体积不符 {asset.get('size')} != {want_size}")
|
||||
failures.append(f"{rid}: {name} 体积 {asset.get('size')},清单 {want_size}")
|
||||
continue
|
||||
|
||||
if args.skip_download:
|
||||
log(f"{rid:<12} {name:<32} ✓ 体积一致(未下载)")
|
||||
continue
|
||||
|
||||
url = asset.get("browser_download_url") or f"{args.base_url}/{args.repo}/releases/download/{tag}/{name}"
|
||||
dest = os.path.join(workdir, name)
|
||||
try:
|
||||
size, sha = download_sha256(url, args.token, dest)
|
||||
os.remove(dest)
|
||||
except Exception as exc: # noqa: BLE001 - 下载失败一律按失败上报
|
||||
log(f"{rid:<12} {name:<32} ✗ 下载失败: {exc}")
|
||||
failures.append(f"{rid}: 下载 {name} 失败: {exc}")
|
||||
continue
|
||||
|
||||
if size != want_size or sha != want_sha:
|
||||
log(f"{rid:<12} {name:<32} ✗ sha256 不符")
|
||||
log(f" 期望 {want_sha}")
|
||||
log(f" 实际 {sha}")
|
||||
failures.append(f"{rid}: {name} sha256 与清单不符")
|
||||
else:
|
||||
log(f"{rid:<12} {name:<32} ✓ {size:,} B sha {sha[:16]}…")
|
||||
|
||||
extra = sorted(set(assets) - declared)
|
||||
if extra:
|
||||
warnings.append("Release 上有清单未声明的资产: " + ", ".join(extra))
|
||||
|
||||
# ---- 3. 本地清单对比 ----
|
||||
if os.path.isfile(args.manifest):
|
||||
with open(args.manifest, "rb") as fh:
|
||||
local_raw = fh.read()
|
||||
local = json.loads(local_raw.decode("utf-8"))
|
||||
local_packages = (local.get("launcher") or {}).get("packages") or {}
|
||||
if local_packages != packages:
|
||||
warnings.append("本地清单的 packages 与 tag 上的不一致(本地可能是未发布的构建)")
|
||||
else:
|
||||
log("")
|
||||
log("本地清单与 tag 上的 packages 一致")
|
||||
|
||||
# ---- 汇总 ----
|
||||
log("")
|
||||
for w in warnings:
|
||||
log("警告: " + w)
|
||||
if failures:
|
||||
for f in failures:
|
||||
log("失败: " + f)
|
||||
log("")
|
||||
log("结论: 不一致 —— 客户端会拒绝或回滚这次更新")
|
||||
return 1
|
||||
|
||||
log("结论: 一致 —— 清单、tag、资产三者对得上")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,42 @@
|
||||
#!/bin/sh
|
||||
# buildsh/release.sh —— 发布一致性核对
|
||||
#
|
||||
# ./build.sh release-verify # 核对当前版本号对应的 tag
|
||||
# ./build.sh release-verify 1.1.0 # 核对指定 tag
|
||||
# ./build.sh release-verify 1.1.0 --skip-download # 只看体积,不下载
|
||||
#
|
||||
# 检查的是「tag 指向的清单 / Release 上的资产 / 清单里的 sha256」三者是否互相对得上。
|
||||
# 客户端的升级判断完全依赖这三者:任何一处错位,用户侧就是验签失败或安全回滚。
|
||||
|
||||
bs_verify_release() {
|
||||
ROOT_DIR="$1"; shift
|
||||
TAG="${1:-$VERSION}"
|
||||
if [ "$#" -gt 0 ]; then shift; fi
|
||||
|
||||
WORK="$ROOT_DIR/build/release-verify"
|
||||
mkdir -p "$WORK"
|
||||
|
||||
echo "==> 核对 Release ${TAG}"
|
||||
rc=0
|
||||
python3 "$ROOT_DIR/buildsh/lib/verify_release.py" \
|
||||
--tag "$TAG" \
|
||||
--manifest "$ROOT_DIR/version.json" \
|
||||
--dump-manifest "$WORK/$TAG.json" \
|
||||
"$@" || rc=$?
|
||||
|
||||
if [ "$rc" -ne 0 ]; then
|
||||
return "$rc"
|
||||
fi
|
||||
|
||||
# 资产对得上还不够:清单本身必须是我签的,否则客户端一样会拒
|
||||
echo ""
|
||||
echo "==> 校验 tag 清单签名"
|
||||
if dotnet run --project "$ROOT_DIR/GC-SAVEDOG/GC-SAVEDOG.csproj" -c Release -- \
|
||||
verify --manifest "$WORK/$TAG.json"; then
|
||||
echo "结论: 签名可信,可以发布 / 已经发布正确"
|
||||
return 0
|
||||
fi
|
||||
|
||||
echo "!! 签名校验未通过,客户端会拒绝这次更新"
|
||||
return 1
|
||||
}
|
||||
+1
-1
@@ -26,7 +26,7 @@ bs_tools() {
|
||||
dotnet --info | head -20 ;;
|
||||
dist)
|
||||
echo "==> dist 产物:"
|
||||
ls -lh "$ROOT_DIR"/dist/*/GC-*.zip 2>/dev/null || ls -lh "$ROOT_DIR"/dist 2>/dev/null || true ;;
|
||||
ls -lh "$ROOT_DIR"/dist/*/GCL-*.zip 2>/dev/null || ls -lh "$ROOT_DIR"/dist 2>/dev/null || true ;;
|
||||
*)
|
||||
echo "未知工具: $TASK"; return 1 ;;
|
||||
esac
|
||||
|
||||
@@ -5,8 +5,8 @@
|
||||
"en": "Contour Map"
|
||||
},
|
||||
"descriptionI18n": {
|
||||
"zh-CN": "立体地形与平面等高线联动,判读山峰、山脊、山谷、鞍部、陡崖五种部位。",
|
||||
"en": "Link 3D relief with contour lines; identify peaks, ridges, valleys, saddles and cliffs."
|
||||
"zh-CN": "可旋转 3D 地形 + 等高切割/交线/投影/判坡四步动画,判读山峰、山脊、山谷、鞍部、陡崖五大典型地貌。",
|
||||
"en": "Rotatable 3D terrain with a four-step animation of contour cutting, lines, projection and slope; identify five classic landforms."
|
||||
},
|
||||
"author": "Morris GC",
|
||||
"tags": [
|
||||
@@ -17,7 +17,7 @@
|
||||
],
|
||||
"assembly": "ContourMapModel.dll",
|
||||
"type": "GC.ContourMap.ContourMapFactory",
|
||||
"version": "1.1",
|
||||
"version": "1.2",
|
||||
"chrome": {
|
||||
"titleBar": "#0C1828",
|
||||
"titleBorder": "#1B2740",
|
||||
@@ -26,5 +26,5 @@
|
||||
"frame": "#0A1524"
|
||||
},
|
||||
"build": "773ab2161d",
|
||||
"updatedAt": "2026-11-18T10:16:41Z"
|
||||
"updatedAt": "2026-11-19T10:20:00Z"
|
||||
}
|
||||
Binary file not shown.
@@ -1,130 +1,116 @@
|
||||
{
|
||||
"zh-CN": {
|
||||
"title": "如何使用 · 等高线地形图",
|
||||
"title": "如何使用 · 等高线地形与五大典型地貌",
|
||||
"sections": [
|
||||
{
|
||||
"h": "开始使用(跟着做)",
|
||||
"lines": [
|
||||
"第 1 步:顶部选一种地形(山地 / 盆地 / 丘陵 / 高原 / 平原),画面会换成对应的等高线图。",
|
||||
"第 2 步:把鼠标移到图上任意位置,底部会显示该点的海拔、相对高度和地形部位。",
|
||||
"第 3 步:观察左边的立体地形与右边的等高线图,找出同一个山峰,看它在两张图上分别长什么样。",
|
||||
"第 4 步:点右下角「取消上色」,只留等高线;再点一次恢复分层设色,对比哪种更便于判读。",
|
||||
"第 5 步:对着右侧的判读要点,依次在图上找出一个山峰、一条山脊、一条山谷、一处鞍部和一处陡崖。"
|
||||
"第 1 步:点右下角「开始实验」,在立体地形里观察水平切面下降、交线形成、垂直投影与疏密判坡四步动画。",
|
||||
"第 2 步:在立体地形上按住鼠标拖动可旋转视角,滚轮缩放;这是可交互的 3D 地形。",
|
||||
"第 3 步:点画布上方「五大典型地貌」标签(山峰/山脊/山谷/鞍部/陡崖),画面换成对应的专门地形并叠加完整等高线,观察各自的等高线特征。",
|
||||
"第 4 步:点底部「俯视图 / 立体图」在等高线地图与 3D 地形间切换;鼠标悬停任意位置,底部显示该点海拔与地形部位。",
|
||||
"第 5 步:点「上色 / 取消上色」对比分层设色与纯等高线;点「全屏」进入全屏演示。"
|
||||
]
|
||||
},
|
||||
{
|
||||
"h": "等高线是什么",
|
||||
"h": "键盘快捷键",
|
||||
"lines": [
|
||||
"在地图上,把海拔相同的点用线连起来,这条线就叫等高线。",
|
||||
"相邻两条等高线之间的高差叫等高距:本图山地、高原、盆地用 100 米,丘陵用 10 米,平原用 5 米。",
|
||||
"等高线的闭合圈,数值由中心向四周递减的是山峰;四周高中间低的是盆地。",
|
||||
"等高线向海拔低处凸出的是山脊(分水线);向海拔高处凸出的是山谷(集水线)。",
|
||||
"两个山峰之间低下去的地方叫鞍部;等高线重叠或挤成一团的地方是陡崖。",
|
||||
"等高线越密,坡度越陡;越疏,坡度越缓。",
|
||||
"每 5 条等高线加粗一条叫计曲线,上面标着海拔,方便读数。"
|
||||
"空格:播放 / 暂停实验。",
|
||||
"数字 1 – 5:依次切换到山峰、山脊、山谷、鞍部、陡崖。"
|
||||
]
|
||||
},
|
||||
{
|
||||
"h": "海拔与相对高度",
|
||||
"h": "四步实验流程",
|
||||
"lines": [
|
||||
"海拔:地面某一点高出海平面的垂直距离。",
|
||||
"相对高度:两个地点海拔的差值,也就是图上两点的落差。",
|
||||
"底部读数里的「相对高度」是本图最低点到该点的高差。"
|
||||
"等高切割:一个水平面从山顶向下移动,与山体在同一海拔相交。",
|
||||
"形成交线:每个水平切面留下一条闭合交线,多层交线共同描述山体起伏。",
|
||||
"投影成图:各高度的交线沿垂线投影到同一平面,累积成完整等高线图。",
|
||||
"疏密判坡:坡度着色叠加等高线,陡处线密、缓处线疏。"
|
||||
]
|
||||
},
|
||||
{
|
||||
"h": "五种地体的等高线特征",
|
||||
"h": "五大典型地貌的判读",
|
||||
"lines": [
|
||||
"山地:海拔高、起伏大,等高线密集且数值跨度大。",
|
||||
"盆地:四周高、中间低,等高线由外向内数值递减,常有河流发育。",
|
||||
"丘陵:海拔不高、坡度和缓,等高线稀疏弯曲。",
|
||||
"高原:海拔高而顶面平坦,等高线中部稀疏、边缘密集。",
|
||||
"平原:海拔低、地面平坦,等高线很少甚至没有。"
|
||||
"山峰:等高线闭合,数值由中心向四周递减(若向内降低则为洼地)。",
|
||||
"山脊:等高线向海拔低处凸出(凸低为脊),脊线是分水线。",
|
||||
"山谷:等高线向海拔高处凸出(凸高为谷),谷线是集水线,常发育河流。",
|
||||
"鞍部:两座山峰之间相对低洼,俯视轮廓呈马鞍状收腰。",
|
||||
"陡崖:等高线密集甚至重合,近乎垂直;n 条线重合时 (n−1)d ≤ ΔH < (n+1)d。"
|
||||
]
|
||||
},
|
||||
{
|
||||
"h": "地图上的教科书符号",
|
||||
"h": "等高线基础",
|
||||
"lines": [
|
||||
"分层设色:按固定高程档位套固定色阶(深绿→浅绿→绿→浅黄→黄→浅褐→褐→白),同一档内颜色完全相同。",
|
||||
"山峰用 ▲ 加高程数字标注。",
|
||||
"河流用蓝色线表示,沿谷底(等高线凸向高处的一侧)流。",
|
||||
"陡崖用红色锯齿线表示。",
|
||||
"指北针在图幅右上角,比例尺在左下角,分层设色图例在右下角。",
|
||||
"地形剖面图在图幅底部:沿南北中线剖开地面,标出各点海拔,看清起伏。"
|
||||
"同一条等高线上各点海拔相等;相邻等高线之间的高差叫等高距(本图 100 米)。",
|
||||
"等高线越密坡越陡,越疏坡越缓。",
|
||||
"每 5 条加粗一条叫计曲线,标注海拔便于读数。",
|
||||
"海拔:某地高出海平面的垂直距离;相对高度:两点海拔之差。"
|
||||
]
|
||||
},
|
||||
{
|
||||
"h": "容易出错的地方",
|
||||
"h": "地图符号",
|
||||
"lines": [
|
||||
"把「等高线密集 = 陡」记反:密集是陡,稀疏是缓。",
|
||||
"把山脊和山谷看反:看凸出的方向 —— 凸向低处是山脊,凸向高处是山谷。",
|
||||
"忽视等高距:等高距变了,同样的等高线密度代表的坡度就不同。",
|
||||
"把计曲线当成普通等高线:计曲线加粗并标了数值,读高程要看它。"
|
||||
"分层设色按固定高程档位套固定色阶(深绿→浅绿→绿→浅黄→黄→浅褐→褐→白)。",
|
||||
"山峰用 ▲ 加高程数字标注;河流用蓝色线沿谷底绘制;陡崖用红色锯齿线表示。",
|
||||
"指北针在图幅右上,比例尺在左下,分层设色图例在右下,地形剖面图在底部。"
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
"en": {
|
||||
"title": "How to use · Contour Map",
|
||||
"title": "How to use · Contour Lines & Five Landforms",
|
||||
"sections": [
|
||||
{
|
||||
"h": "Getting started (follow along)",
|
||||
"lines": [
|
||||
"Step 1: pick a terrain type at the top (mountains / basin / hills / plateau / plain) — the map switches to its contour map.",
|
||||
"Step 2: move the pointer anywhere on the map; the footer shows elevation, relative height and the terrain feature.",
|
||||
"Step 3: compare the 3D block on the left with the contour map on the right — find the same peak in both.",
|
||||
"Step 4: click “No colour” at the bottom right to keep only the contour lines; click again to restore the colour fill.",
|
||||
"Step 5: using the panel on the right, find one peak, one ridge, one valley, one saddle and one cliff."
|
||||
"Step 1: press Start to watch the four-step animation — contour cutting, line formation, vertical projection and slope reading.",
|
||||
"Step 2: drag with the mouse to rotate the 3D terrain, scroll to zoom; it is fully interactive.",
|
||||
"Step 3: click a landform tab above the canvas (peak / ridge / valley / saddle / cliff) to load its dedicated terrain with its full contour pattern.",
|
||||
"Step 4: toggle Top view / 3D view at the bottom; hover anywhere to read elevation and terrain feature.",
|
||||
"Step 5: use Colour / No colour to compare hypsometric tint with pure contour lines; use Fullscreen for presentation."
|
||||
]
|
||||
},
|
||||
{
|
||||
"h": "What contour lines are",
|
||||
"h": "Keyboard shortcuts",
|
||||
"lines": [
|
||||
"Connect points of equal elevation on a map and you get a contour line.",
|
||||
"The height gap between neighbouring contours is the contour interval: 100 m for mountains, plateau and basin; 10 m for hills; 5 m for plain.",
|
||||
"A closed loop whose values decrease outward is a peak; high ground around a low centre is a basin.",
|
||||
"Contours bulging toward lower ground form a ridge (watershed); bulging toward higher ground form a valley (drainage).",
|
||||
"The low ground between two peaks is a saddle; overlapping or tightly crowded contours mark a cliff.",
|
||||
"The closer the contours, the steeper the slope; the wider apart, the gentler.",
|
||||
"Every 5th contour is bolded as an index contour and labelled with its elevation."
|
||||
"Space: play / pause the experiment.",
|
||||
"Numbers 1 – 5: switch to peak, ridge, valley, saddle, cliff."
|
||||
]
|
||||
},
|
||||
{
|
||||
"h": "Elevation and relative height",
|
||||
"h": "The four experiment steps",
|
||||
"lines": [
|
||||
"Elevation is the vertical height of a point above sea level.",
|
||||
"Relative height is the difference between two elevations — the drop between two points on the map.",
|
||||
"The relative height in the footer is measured from the lowest point of this map."
|
||||
"Contour cutting: a horizontal plane descends from the summit and intersects the mountain at one elevation.",
|
||||
"Forming lines: each slice leaves a closed intersection line; stacked lines describe the relief.",
|
||||
"Projection: intersection lines are projected vertically onto one plane, building the contour map.",
|
||||
"Slope density: slope shading over contours — dense lines mean steep, sparse lines mean gentle."
|
||||
]
|
||||
},
|
||||
{
|
||||
"h": "Contour patterns of the five terrains",
|
||||
"h": "Reading the five landforms",
|
||||
"lines": [
|
||||
"Mountains: high elevation, large relief, dense contours over a wide value range.",
|
||||
"Basin: high rim, low centre; values decrease inward, often with a river.",
|
||||
"Hills: low elevation, gentle slopes, sparse winding contours.",
|
||||
"Plateau: high but flat on top — contours sparse in the middle and crowded at the edges.",
|
||||
"Plain: low and flat — few or no contour lines at all."
|
||||
"Peak: closed contours, values decrease outward (if they decrease inward it is a depression).",
|
||||
"Ridge: contours bulge toward lower ground; a watershed line.",
|
||||
"Valley: contours bulge toward higher ground; a drainage line, often a stream.",
|
||||
"Saddle: low ground between two peaks, pinched like a saddle in plan view.",
|
||||
"Cliff: contours crowd or overlap, nearly vertical; n overlapping lines: (n−1)d ≤ ΔH < (n+1)d."
|
||||
]
|
||||
},
|
||||
{
|
||||
"h": "Textbook map symbols",
|
||||
"h": "Contour basics",
|
||||
"lines": [
|
||||
"Hypsometric tint: fixed colour bands by elevation (dark green → light green → green → pale yellow → yellow → light brown → brown → white); each band is a flat colour.",
|
||||
"Peaks are marked with a ▲ and their elevation.",
|
||||
"Rivers are drawn in blue along the valley floor (where contours bulge uphill).",
|
||||
"Cliffs are marked with a red saw-tooth line.",
|
||||
"A north arrow sits top-right, a scale bar bottom-left, and the tint legend bottom-right.",
|
||||
"The terrain profile along the bottom cuts the ground open and labels elevations, showing the relief at a glance."
|
||||
"All points on one contour share the same elevation; the gap between neighbours is the contour interval (100 m here).",
|
||||
"Closer contours mean steeper slopes; wider spacing means gentler slopes.",
|
||||
"Every 5th contour is bolded as an index contour and labelled with elevation.",
|
||||
"Elevation is height above sea level; relative height is the difference between two elevations."
|
||||
]
|
||||
},
|
||||
{
|
||||
"h": "Common mistakes",
|
||||
"h": "Map symbols",
|
||||
"lines": [
|
||||
"Reversing dense and sparse: dense means steep, sparse means gentle.",
|
||||
"Mixing up ridge and valley — look which way the bulge points: toward lower ground is a ridge, toward higher ground is a valley.",
|
||||
"Ignoring the contour interval: change it and the same spacing means a different slope.",
|
||||
"Treating index contours as ordinary ones — they are bold and labelled, so read elevations off them."
|
||||
"Hypsometric tint uses fixed colour bands (dark green → light green → green → pale yellow → yellow → light brown → brown → white).",
|
||||
"Peaks are marked with ▲ plus elevation; rivers are blue lines along valleys; cliffs use a red saw-tooth line.",
|
||||
"North arrow top-right, scale bar bottom-left, tint legend bottom-right, terrain profile along the bottom."
|
||||
]
|
||||
}
|
||||
]
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
{
|
||||
"app.title": "Contour Map",
|
||||
"app.subtitle": "Grade 7 · Reading terrain maps: from 3D relief to contour lines"
|
||||
"app.title": "Contour Lines · Five Classic Landforms",
|
||||
"app.subtitle": "Grade 7 · From 3D relief to contour maps: peaks, ridges, valleys, saddles and cliffs"
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
{
|
||||
"app.title": "等高线地形图",
|
||||
"app.subtitle": "七年级上册 · 地形图的判读:从立体地形到平面等高线"
|
||||
"app.title": "等高线地形 · 五大典型地貌判读",
|
||||
"app.subtitle": "七年级上册 · 从立体地形到平面等高线,判读山峰/山脊/山谷/鞍部/陡崖"
|
||||
}
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 90 KiB After Width: | Height: | Size: 65 KiB |
@@ -24,6 +24,7 @@ public sealed class ContourMapRuntime : IModelRuntime
|
||||
{
|
||||
private TerrainField? _field;
|
||||
private Dictionary<string, string>? _texts;
|
||||
private ContourPage? _page;
|
||||
|
||||
public void Prepare(IModelContext context)
|
||||
{
|
||||
@@ -41,22 +42,55 @@ public sealed class ContourMapRuntime : IModelRuntime
|
||||
public Control CreateView(IModelContext context)
|
||||
{
|
||||
_texts ??= LoadTexts(context.DataDirectory, context.Language);
|
||||
// 五种地体都在界面里现场生成(切换很快,不必预先生成全部)
|
||||
return new ContourPage(_texts).Build();
|
||||
// 实验地形 + 五大地貌都在界面里现场生成(切换很快,不必预先生成全部)
|
||||
_page = new ContourPage(_texts);
|
||||
return _page.Build();
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
_page?.Dispose();
|
||||
_page = null;
|
||||
_field = null;
|
||||
_texts = null;
|
||||
System.GC.SuppressFinalize(this);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 文案 = 内置默认(保证任何语言都有词)+ dataDir/i18n/<lang>.json 覆盖。
|
||||
/// 语言包缺失或某条没翻译时自动退回内置默认,不会露出裸 key。
|
||||
/// </summary>
|
||||
private static Dictionary<string, string> LoadTexts(string dataDir, string language)
|
||||
{
|
||||
var map = new Dictionary<string, string>(DefaultTexts.Zh);
|
||||
var isEn = language.StartsWith("en", StringComparison.OrdinalIgnoreCase);
|
||||
var map = new Dictionary<string, string>(DefaultTexts.Zh);
|
||||
if (isEn) foreach (var kv in DefaultTexts.En) map[kv.Key] = kv.Value;
|
||||
|
||||
var candidates = new List<string>();
|
||||
if (!string.IsNullOrWhiteSpace(language)) candidates.Add(language);
|
||||
candidates.Add(isEn ? "en" : "zh-CN");
|
||||
|
||||
foreach (var lang in candidates)
|
||||
{
|
||||
var path = System.IO.Path.Combine(dataDir, "i18n", lang + ".json");
|
||||
if (!System.IO.File.Exists(path)) continue;
|
||||
try
|
||||
{
|
||||
using var doc = System.Text.Json.JsonDocument.Parse(System.IO.File.ReadAllText(path));
|
||||
if (doc.RootElement.ValueKind != System.Text.Json.JsonValueKind.Object) continue;
|
||||
foreach (var p in doc.RootElement.EnumerateObject())
|
||||
{
|
||||
if (p.Value.ValueKind != System.Text.Json.JsonValueKind.String) continue;
|
||||
var v = p.Value.GetString();
|
||||
if (!string.IsNullOrWhiteSpace(v)) map[p.Name] = v!;
|
||||
}
|
||||
break;
|
||||
}
|
||||
catch
|
||||
{
|
||||
// 语言包损坏不影响开课,继续用内置默认
|
||||
}
|
||||
}
|
||||
return map;
|
||||
}
|
||||
}
|
||||
@@ -2,16 +2,22 @@ using System;
|
||||
using System.Collections.Generic;
|
||||
using Avalonia;
|
||||
using Avalonia.Controls;
|
||||
using Avalonia.Input;
|
||||
using Avalonia.Layout;
|
||||
using Avalonia.Media;
|
||||
|
||||
namespace GC.ContourMap;
|
||||
|
||||
/// <summary>等高线模型的界面:顶部标题、中间双图联动、右侧判读要点、底部实时读数。</summary>
|
||||
/// <summary>
|
||||
/// 等高线模型界面(完整复刻 HTML 课件功能):
|
||||
/// 顶部标题 + 全屏;左侧可交互 3D 画布;右侧实验流程/五大地貌/判读要点观察面板;
|
||||
/// 底部播放控制、俯视切换、上色开关、实时读数;支持键盘 1-5 / 空格快捷键。
|
||||
/// </summary>
|
||||
public sealed class ContourPage
|
||||
{
|
||||
private static readonly Color CAppBg = Color.Parse("#0B1524");
|
||||
private static readonly Color CPanel = Color.Parse("#101E31");
|
||||
private static readonly Color CPanel2 = Color.Parse("#16263C");
|
||||
private static readonly Color CLine = Color.Parse("#1E3350");
|
||||
private static readonly Color CInk = Color.Parse("#EAF2FF");
|
||||
private static readonly Color CInkDim = Color.Parse("#93A8C6");
|
||||
@@ -20,37 +26,61 @@ public sealed class ContourPage
|
||||
private static readonly Color CWarn = Color.Parse("#FFB454");
|
||||
private static readonly Color CGood = Color.Parse("#5FD69B");
|
||||
|
||||
private TerrainField _field;
|
||||
private readonly Dictionary<string, string> _texts;
|
||||
private readonly Dictionary<TerrainKind, TerrainField> _cache = new();
|
||||
private Border? _colorBtn;
|
||||
private TextBlock? _colorBtnText;
|
||||
private TerrainKind _kind = TerrainKind.Mountain;
|
||||
private readonly Dictionary<LandformKind, TerrainField> _landformCache = new();
|
||||
private TerrainField _experimentField;
|
||||
|
||||
private ContourView? _view;
|
||||
private TextBlock? _readout;
|
||||
private TextBlock? _featureText;
|
||||
private TextBlock? _hintText;
|
||||
private TextBlock? _playLabel;
|
||||
private TextBlock? _observeHeading;
|
||||
private TextBlock? _observeSummary;
|
||||
private StackPanel? _featureList;
|
||||
private TextBlock? _viewToggleLabel;
|
||||
|
||||
private readonly List<Border> _flowButtons = new();
|
||||
private readonly List<Border> _landformButtons = new();
|
||||
private Border? _playBtn;
|
||||
private Border? _backBtn;
|
||||
private Border? _colorBtn;
|
||||
private TextBlock? _colorBtnText;
|
||||
private ProgressBar? _progress;
|
||||
|
||||
private int _step = 0;
|
||||
private LandformKind? _selectedLandform;
|
||||
private bool _disposed;
|
||||
private TopLevel? _topLevel;
|
||||
|
||||
private static readonly LandformKind[] LandformOrder =
|
||||
{ LandformKind.Peak, LandformKind.Ridge, LandformKind.Valley, LandformKind.Saddle, LandformKind.Cliff };
|
||||
|
||||
public ContourPage(Dictionary<string, string> texts)
|
||||
{
|
||||
_texts = texts;
|
||||
_field = GetField(TerrainKind.Mountain);
|
||||
}
|
||||
|
||||
/// <summary>取(并缓存)某类地体的高度场,切换时不重复计算。</summary>
|
||||
private TerrainField GetField(TerrainKind kind)
|
||||
{
|
||||
if (!_cache.TryGetValue(kind, out var f))
|
||||
{
|
||||
f = new TerrainField(kind, 192);
|
||||
_cache[kind] = f;
|
||||
}
|
||||
return f;
|
||||
_experimentField = new TerrainField(TerrainKind.Mountain, 192);
|
||||
}
|
||||
|
||||
private string T(string key) => _texts.TryGetValue(key, out var v) ? v : key;
|
||||
|
||||
private string T(string key, params object[] args)
|
||||
{
|
||||
var s = T(key);
|
||||
try { return string.Format(System.Globalization.CultureInfo.InvariantCulture, s, args); }
|
||||
catch { return s; }
|
||||
}
|
||||
private static SolidColorBrush B(Color c) => new(c);
|
||||
|
||||
private TerrainField GetLandformField(LandformKind kind)
|
||||
{
|
||||
if (!_landformCache.TryGetValue(kind, out var f))
|
||||
{
|
||||
f = new TerrainField(kind, 192);
|
||||
_landformCache[kind] = f;
|
||||
}
|
||||
return f;
|
||||
}
|
||||
|
||||
public Control Build()
|
||||
{
|
||||
var root = new Grid { Background = B(CAppBg) };
|
||||
@@ -60,12 +90,18 @@ public sealed class ContourPage
|
||||
|
||||
root.Children.Add(BuildHeader());
|
||||
|
||||
var body = new Grid { Margin = new Thickness(14, 8, 14, 6) };
|
||||
var body = new Grid { Margin = new Thickness(12, 8, 12, 6) };
|
||||
body.ColumnDefinitions.Add(new ColumnDefinition(GridLength.Star));
|
||||
body.ColumnDefinitions.Add(new ColumnDefinition(new GridLength(288)));
|
||||
body.ColumnDefinitions.Add(new ColumnDefinition(new GridLength(344)));
|
||||
body.RowDefinitions.Add(new RowDefinition(GridLength.Auto));
|
||||
body.RowDefinitions.Add(new RowDefinition(GridLength.Star));
|
||||
|
||||
_view = new ContourView(_field, T);
|
||||
_view = new ContourView(_experimentField, T);
|
||||
_view.HoverChanged += OnHover;
|
||||
_view.StepChanged += OnStepChanged;
|
||||
_view.ProgressChanged += OnProgressChanged;
|
||||
_view.PlaybackFinished += OnPlaybackFinished;
|
||||
|
||||
var canvasHolder = new Border
|
||||
{
|
||||
Background = B(Color.Parse("#08111E")),
|
||||
@@ -75,66 +111,103 @@ public sealed class ContourPage
|
||||
ClipToBounds = true,
|
||||
Child = _view
|
||||
};
|
||||
Grid.SetColumn(canvasHolder, 0);
|
||||
Grid.SetRow(canvasHolder, 1);
|
||||
body.Children.Add(canvasHolder);
|
||||
|
||||
// ── 五大典型地貌标签(横向,像课件的选项卡)──
|
||||
var tabs = new WrapPanel
|
||||
{
|
||||
Orientation = Orientation.Horizontal,
|
||||
Margin = new Thickness(0, 0, 0, 8)
|
||||
};
|
||||
_backBtn = MakePillButton(T("btn.backExperiment"), CAccent);
|
||||
_backBtn.IsVisible = false;
|
||||
_backBtn.PointerPressed += (_, _) => BackToExperiment();
|
||||
tabs.Children.Add(_backBtn);
|
||||
foreach (var kind in LandformOrder)
|
||||
{
|
||||
var btn = MakeLandformButton(kind);
|
||||
_landformButtons.Add(btn);
|
||||
tabs.Children.Add(btn);
|
||||
}
|
||||
body.Children.Add(tabs);
|
||||
|
||||
var side = BuildSidePanel();
|
||||
Grid.SetColumn(side, 1);
|
||||
Grid.SetRow(side, 0);
|
||||
Grid.SetRowSpan(side, 2);
|
||||
body.Children.Add(side);
|
||||
|
||||
// 窄窗口(封面缩略图、小屏)隐藏右侧栏,画布优先;宽窗口才展示流程与观察面板
|
||||
void ApplyResponsive(double width)
|
||||
{
|
||||
var narrow = width < 980;
|
||||
side.IsVisible = !narrow;
|
||||
body.ColumnDefinitions[1].Width = narrow ? new GridLength(0) : new GridLength(344);
|
||||
}
|
||||
root.SizeChanged += (_, e) => ApplyResponsive(e.NewSize.Width);
|
||||
|
||||
Grid.SetRow(body, 1);
|
||||
root.Children.Add(body);
|
||||
|
||||
root.Children.Add(BuildFooter());
|
||||
Grid.SetRow(root.Children[^1], 2);
|
||||
var footer = BuildFooter();
|
||||
Grid.SetRow(footer, 2);
|
||||
root.Children.Add(footer);
|
||||
|
||||
root.AttachedToVisualTree += (_, _) =>
|
||||
{
|
||||
_topLevel = TopLevel.GetTopLevel(root);
|
||||
};
|
||||
root.KeyDown += OnKeyDown;
|
||||
root.Focusable = true;
|
||||
|
||||
return root;
|
||||
}
|
||||
|
||||
/// <summary>窗口关闭时释放视图计时器,避免持有控件。</summary>
|
||||
public void Dispose()
|
||||
{
|
||||
if (_disposed) return;
|
||||
_disposed = true;
|
||||
_view?.DisposeView();
|
||||
}
|
||||
|
||||
private Control BuildHeader()
|
||||
{
|
||||
var title = new TextBlock
|
||||
{
|
||||
Text = T("app.title"),
|
||||
Foreground = B(CInk),
|
||||
FontSize = 16,
|
||||
FontSize = 18,
|
||||
FontWeight = FontWeight.SemiBold
|
||||
};
|
||||
var sub = new TextBlock
|
||||
{
|
||||
Text = T("app.subtitle"),
|
||||
Foreground = B(CInkFaint),
|
||||
FontSize = 10.5
|
||||
Foreground = B(CInkDim),
|
||||
FontSize = 11.5
|
||||
};
|
||||
var stack = new StackPanel { Spacing = 2 };
|
||||
stack.Children.Add(title);
|
||||
stack.Children.Add(sub);
|
||||
|
||||
// 地体类型选择:教科书里的五种基本地形
|
||||
var kinds = new (TerrainKind Kind, string Key)[]
|
||||
var fsLabel = new TextBlock { Text = T("btn.fullscreen"), Foreground = B(CInk), FontSize = 11.5 };
|
||||
var fsBtn = new Border
|
||||
{
|
||||
(TerrainKind.Mountain, "kind.mountain"),
|
||||
(TerrainKind.Basin, "kind.basin"),
|
||||
(TerrainKind.Hill, "kind.hill"),
|
||||
(TerrainKind.Plateau, "kind.plateau"),
|
||||
(TerrainKind.Plain, "kind.plain"),
|
||||
Background = B(CPanel2),
|
||||
BorderBrush = B(CLine),
|
||||
BorderThickness = new Thickness(1),
|
||||
CornerRadius = new CornerRadius(8),
|
||||
Padding = new Thickness(12, 6),
|
||||
Cursor = new Avalonia.Input.Cursor(Avalonia.Input.StandardCursorType.Hand),
|
||||
Child = fsLabel
|
||||
};
|
||||
fsBtn.PointerPressed += (_, _) => ToggleFullscreen(fsLabel);
|
||||
|
||||
var tabs = new StackPanel
|
||||
{
|
||||
Orientation = Orientation.Horizontal,
|
||||
Spacing = 6,
|
||||
Margin = new Thickness(0, 9, 0, 0)
|
||||
};
|
||||
foreach (var (kind, key) in kinds)
|
||||
{
|
||||
var btn = MakeKindTab(kind, T(key));
|
||||
tabs.Children.Add(btn);
|
||||
}
|
||||
|
||||
var header = new StackPanel();
|
||||
header.Children.Add(stack);
|
||||
header.Children.Add(tabs);
|
||||
var grid = new Grid { ColumnDefinitions = new ColumnDefinitions("*,Auto") };
|
||||
grid.Children.Add(stack);
|
||||
Grid.SetColumn(fsBtn, 1);
|
||||
grid.Children.Add(fsBtn);
|
||||
|
||||
return new Border
|
||||
{
|
||||
@@ -142,70 +215,49 @@ public sealed class ContourPage
|
||||
BorderBrush = B(CLine),
|
||||
BorderThickness = new Thickness(0, 0, 0, 1),
|
||||
Padding = new Thickness(18, 11, 18, 12),
|
||||
Child = header
|
||||
Child = grid
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>地体类型按钮:选中高亮。</summary>
|
||||
private Button MakeKindTab(TerrainKind kind, string label)
|
||||
{
|
||||
var b = new Button
|
||||
{
|
||||
Content = label,
|
||||
FontSize = 11.5,
|
||||
Padding = new Thickness(13, 5),
|
||||
CornerRadius = new CornerRadius(8),
|
||||
BorderThickness = new Thickness(1),
|
||||
Cursor = new Avalonia.Input.Cursor(Avalonia.Input.StandardCursorType.Hand),
|
||||
Tag = kind
|
||||
};
|
||||
|
||||
void Style()
|
||||
{
|
||||
var on = _kind == kind;
|
||||
b.Background = B(on ? CAccent : Color.Parse("#16263C"));
|
||||
b.BorderBrush = B(on ? CAccent : Color.Parse("#263A56"));
|
||||
b.Foreground = B(on ? Colors.White : CInkDim);
|
||||
}
|
||||
Style();
|
||||
|
||||
b.Click += (_, _) =>
|
||||
{
|
||||
_kind = kind;
|
||||
_field = GetField(kind);
|
||||
_view?.SetField(_field);
|
||||
// 重新刷新所有 tab 的选中态
|
||||
if (b.Parent is StackPanel sp)
|
||||
foreach (var c in sp.Children)
|
||||
if (c is Button sib && sib.Tag is TerrainKind)
|
||||
{
|
||||
var on = (TerrainKind)sib.Tag == _kind;
|
||||
sib.Background = B(on ? CAccent : Color.Parse("#16263C"));
|
||||
sib.BorderBrush = B(on ? CAccent : Color.Parse("#263A56"));
|
||||
sib.Foreground = B(on ? Colors.White : CInkDim);
|
||||
}
|
||||
};
|
||||
return b;
|
||||
}
|
||||
|
||||
private Control BuildSidePanel()
|
||||
{
|
||||
var panel = new StackPanel { Spacing = 10, Margin = new Thickness(12, 0, 0, 0) };
|
||||
var panel = new StackPanel { Spacing = 8, Margin = new Thickness(12, 0, 0, 0) };
|
||||
|
||||
panel.Children.Add(Section(T("side.features")));
|
||||
|
||||
foreach (var (titleKey, descKey) in new[]
|
||||
{
|
||||
("feature.peak", "feature.peakDesc"),
|
||||
("feature.ridge", "feature.ridgeDesc"),
|
||||
("feature.valley", "feature.valleyDesc"),
|
||||
("feature.saddle", "feature.saddleDesc"),
|
||||
("feature.cliff", "feature.cliffDesc")
|
||||
})
|
||||
// ── 实验流程四步 ──
|
||||
panel.Children.Add(Section(T("flow.title")));
|
||||
for (var i = 0; i < 4; i++)
|
||||
{
|
||||
panel.Children.Add(FeatureRow(T(titleKey), T(descKey)));
|
||||
var btn = MakeFlowButton(i);
|
||||
_flowButtons.Add(btn);
|
||||
panel.Children.Add(btn);
|
||||
}
|
||||
|
||||
panel.Children.Add(Divider());
|
||||
|
||||
// ── 观察面板 ──
|
||||
_observeHeading = new TextBlock
|
||||
{
|
||||
Text = T("observe.title"),
|
||||
Foreground = B(CWarn),
|
||||
FontSize = 12.5,
|
||||
FontWeight = FontWeight.SemiBold
|
||||
};
|
||||
_observeSummary = new TextBlock
|
||||
{
|
||||
Text = T("observe.default"),
|
||||
Foreground = B(CInkDim),
|
||||
FontSize = 10.5,
|
||||
TextWrapping = TextWrapping.Wrap,
|
||||
LineHeight = 16
|
||||
};
|
||||
_featureList = new StackPanel { Spacing = 3 };
|
||||
RenderObservation(null);
|
||||
|
||||
panel.Children.Add(_observeHeading);
|
||||
panel.Children.Add(_observeSummary);
|
||||
panel.Children.Add(_featureList);
|
||||
|
||||
// ── 判读要点 ──
|
||||
panel.Children.Add(Section(T("side.rules")));
|
||||
panel.Children.Add(Bullet(T("rule.interval")));
|
||||
panel.Children.Add(Bullet(T("rule.dense")));
|
||||
@@ -228,55 +280,221 @@ public sealed class ContourPage
|
||||
return scroll;
|
||||
}
|
||||
|
||||
private Control Section(string text) => new TextBlock
|
||||
private Border MakeFlowButton(int index)
|
||||
{
|
||||
Text = text,
|
||||
Foreground = B(CInkDim),
|
||||
FontSize = 11.5,
|
||||
FontWeight = FontWeight.SemiBold,
|
||||
Margin = new Thickness(0, 4, 0, 0)
|
||||
};
|
||||
|
||||
private Control Bullet(string text) => new TextBlock
|
||||
{
|
||||
Text = "• " + text,
|
||||
Foreground = B(CInkDim),
|
||||
FontSize = 11,
|
||||
TextWrapping = TextWrapping.Wrap,
|
||||
LineHeight = 17
|
||||
};
|
||||
|
||||
private Control FeatureRow(string name, string desc)
|
||||
{
|
||||
var title = new TextBlock
|
||||
var name = new TextBlock
|
||||
{
|
||||
Text = name,
|
||||
Foreground = B(CWarn),
|
||||
FontSize = 12,
|
||||
Text = $"{index + 1}. {T("flow.step." + index)}",
|
||||
Foreground = B(CInk),
|
||||
FontSize = 12.5,
|
||||
FontWeight = FontWeight.SemiBold
|
||||
};
|
||||
var d = new TextBlock
|
||||
var desc = new TextBlock
|
||||
{
|
||||
Text = desc,
|
||||
Text = T("flow.desc." + index),
|
||||
Foreground = B(CInkFaint),
|
||||
FontSize = 10.5,
|
||||
FontSize = 11,
|
||||
TextWrapping = TextWrapping.Wrap,
|
||||
LineHeight = 16
|
||||
LineHeight = 15
|
||||
};
|
||||
var stack = new StackPanel { Spacing = 1 };
|
||||
stack.Children.Add(title);
|
||||
stack.Children.Add(d);
|
||||
return stack;
|
||||
stack.Children.Add(name);
|
||||
stack.Children.Add(desc);
|
||||
var border = new Border
|
||||
{
|
||||
Background = B(CPanel2),
|
||||
BorderBrush = B(CLine),
|
||||
BorderThickness = new Thickness(1),
|
||||
CornerRadius = new CornerRadius(8),
|
||||
Padding = new Thickness(9, 6),
|
||||
Cursor = new Avalonia.Input.Cursor(Avalonia.Input.StandardCursorType.Hand),
|
||||
Child = stack,
|
||||
Tag = index
|
||||
};
|
||||
border.PointerPressed += (_, _) =>
|
||||
{
|
||||
BackToExperiment();
|
||||
_view?.SetStep((ExperimentStep)index);
|
||||
UpdateFlowStyles();
|
||||
};
|
||||
return border;
|
||||
}
|
||||
|
||||
private Border MakeLandformButton(LandformKind kind)
|
||||
{
|
||||
var key = kind.ToString().ToLowerInvariant();
|
||||
var name = new TextBlock
|
||||
{
|
||||
Text = T("landform." + key),
|
||||
Foreground = B(CInk),
|
||||
FontSize = 12.5,
|
||||
FontWeight = FontWeight.SemiBold
|
||||
};
|
||||
var sub = new TextBlock
|
||||
{
|
||||
Text = T("landform." + key + ".sub"),
|
||||
Foreground = B(CInkFaint),
|
||||
FontSize = 10.5,
|
||||
VerticalAlignment = VerticalAlignment.Center
|
||||
};
|
||||
var stack = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 7 };
|
||||
stack.Children.Add(name);
|
||||
stack.Children.Add(sub);
|
||||
var border = new Border
|
||||
{
|
||||
Background = B(CPanel2),
|
||||
BorderBrush = B(CLine),
|
||||
BorderThickness = new Thickness(1),
|
||||
CornerRadius = new CornerRadius(18),
|
||||
Padding = new Thickness(14, 7),
|
||||
Margin = new Thickness(0, 0, 8, 4),
|
||||
Cursor = new Avalonia.Input.Cursor(Avalonia.Input.StandardCursorType.Hand),
|
||||
Child = stack,
|
||||
Tag = kind
|
||||
};
|
||||
border.PointerPressed += (_, _) => SelectLandform(kind);
|
||||
return border;
|
||||
}
|
||||
|
||||
private void SelectLandform(LandformKind kind)
|
||||
{
|
||||
_selectedLandform = kind;
|
||||
_view?.Pause();
|
||||
_view?.SetField(GetLandformField(kind));
|
||||
_view?.SetMode(ViewMode.Perspective);
|
||||
_view?.ShowContourPattern(); // 地貌专题先看完整的等高线形态
|
||||
UpdateLandformStyles();
|
||||
UpdateViewToggleLabel();
|
||||
|
||||
var key = kind.ToString().ToLowerInvariant();
|
||||
if (_observeHeading != null) _observeHeading.Text = T("landform." + key) + " · " + T("landform." + key + ".sub");
|
||||
if (_observeSummary != null) _observeSummary.Text = T("landform." + key + ".summary");
|
||||
RenderFeatureList(key);
|
||||
if (_backBtn != null) _backBtn.IsVisible = true;
|
||||
if (_hintText != null) _hintText.Text = T("landform." + key + ".hint");
|
||||
SetPlayLabel(T("btn.replay"));
|
||||
}
|
||||
|
||||
private void BackToExperiment()
|
||||
{
|
||||
if (_selectedLandform == null) return;
|
||||
_selectedLandform = null;
|
||||
_view?.SetField(_experimentField);
|
||||
_view?.SetMode(ViewMode.Perspective);
|
||||
_view?.Reset();
|
||||
UpdateLandformStyles();
|
||||
UpdateViewToggleLabel();
|
||||
RenderObservation(null);
|
||||
if (_backBtn != null) _backBtn.IsVisible = false;
|
||||
if (_hintText != null) _hintText.Text = T("hint.play");
|
||||
SetPlayLabel(T("btn.play"));
|
||||
}
|
||||
|
||||
private void RenderObservation(LandformKind? kind)
|
||||
{
|
||||
if (_observeHeading == null || _observeSummary == null || _featureList == null) return;
|
||||
if (kind == null)
|
||||
{
|
||||
_observeHeading.Text = T("observe.title");
|
||||
_observeSummary.Text = T("observe.default");
|
||||
_featureList.Children.Clear();
|
||||
_featureList.Children.Add(Bullet(T("observe.default.f1")));
|
||||
_featureList.Children.Add(Bullet(T("observe.default.f2")));
|
||||
}
|
||||
else
|
||||
{
|
||||
var key = kind.Value.ToString().ToLowerInvariant();
|
||||
_observeHeading.Text = T("landform." + key) + " · " + T("landform." + key + ".sub");
|
||||
_observeSummary.Text = T("landform." + key + ".summary");
|
||||
RenderFeatureList(key);
|
||||
}
|
||||
}
|
||||
|
||||
private void RenderFeatureList(string key)
|
||||
{
|
||||
if (_featureList == null) return;
|
||||
_featureList.Children.Clear();
|
||||
for (var i = 1; i <= 3; i++)
|
||||
{
|
||||
var k = $"landform.{key}.f{i}";
|
||||
if (_texts.ContainsKey(k)) _featureList.Children.Add(Bullet(T(k)));
|
||||
}
|
||||
}
|
||||
|
||||
private Control BuildFooter()
|
||||
{
|
||||
_readout = new TextBlock
|
||||
// 播放 / 重置
|
||||
_playLabel = new TextBlock { Text = T("btn.play"), Foreground = B(Colors.White), FontSize = 11.5, FontWeight = FontWeight.SemiBold };
|
||||
_playBtn = new Border
|
||||
{
|
||||
Text = T("footer.hint"),
|
||||
Foreground = B(CInkDim),
|
||||
FontSize = 11.5
|
||||
Background = B(CAccent),
|
||||
CornerRadius = new CornerRadius(8),
|
||||
Padding = new Thickness(14, 7),
|
||||
Cursor = new Avalonia.Input.Cursor(Avalonia.Input.StandardCursorType.Hand),
|
||||
Child = _playLabel
|
||||
};
|
||||
_playBtn.PointerPressed += (_, _) => TogglePlay();
|
||||
|
||||
var resetBtn = MakePillButton(T("btn.reset"), Color.Parse("#2A3B55"));
|
||||
resetBtn.PointerPressed += (_, _) =>
|
||||
{
|
||||
BackToExperiment();
|
||||
_view?.Reset();
|
||||
if (_progress != null) _progress.Value = 0;
|
||||
if (_hintText != null) _hintText.Text = T("hint.play");
|
||||
SetPlayLabel(T("btn.play"));
|
||||
};
|
||||
|
||||
// 俯视 / 立体切换
|
||||
_viewToggleLabel = new TextBlock { Text = T("btn.viewTop"), Foreground = B(CInk), FontSize = 11.5 };
|
||||
var viewBtn = new Border
|
||||
{
|
||||
Background = B(CPanel2),
|
||||
BorderBrush = B(CLine),
|
||||
BorderThickness = new Thickness(1),
|
||||
CornerRadius = new CornerRadius(8),
|
||||
Padding = new Thickness(11, 6),
|
||||
Cursor = new Avalonia.Input.Cursor(Avalonia.Input.StandardCursorType.Hand),
|
||||
Child = _viewToggleLabel
|
||||
};
|
||||
viewBtn.PointerPressed += (_, _) =>
|
||||
{
|
||||
_view?.ToggleMode();
|
||||
UpdateViewToggleLabel();
|
||||
};
|
||||
|
||||
// 上色开关
|
||||
_colorBtnText = new TextBlock { Text = T("btn.colorOn"), Foreground = B(Colors.White), FontSize = 11.5 };
|
||||
_colorBtn = new Border
|
||||
{
|
||||
Background = B(CAccent),
|
||||
CornerRadius = new CornerRadius(8),
|
||||
Padding = new Thickness(11, 6),
|
||||
Cursor = new Avalonia.Input.Cursor(Avalonia.Input.StandardCursorType.Hand),
|
||||
Child = _colorBtnText
|
||||
};
|
||||
_colorBtn.PointerPressed += (_, _) => ToggleColor();
|
||||
|
||||
var controls = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 8 };
|
||||
controls.Children.Add(_playBtn);
|
||||
controls.Children.Add(resetBtn);
|
||||
controls.Children.Add(viewBtn);
|
||||
controls.Children.Add(_colorBtn);
|
||||
|
||||
_progress = new ProgressBar
|
||||
{
|
||||
Minimum = 0,
|
||||
Maximum = 100,
|
||||
Value = 0,
|
||||
Height = 4,
|
||||
VerticalAlignment = VerticalAlignment.Center,
|
||||
Foreground = B(CAccent),
|
||||
Background = B(Color.Parse("#1E3350"))
|
||||
};
|
||||
|
||||
_hintText = new TextBlock { Text = T("hint.play"), Foreground = B(CInkDim), FontSize = 11.5 };
|
||||
|
||||
_readout = new TextBlock { Text = T("footer.hint"), Foreground = B(CInk), FontSize = 11.5 };
|
||||
_featureText = new TextBlock
|
||||
{
|
||||
Text = "",
|
||||
@@ -286,64 +504,115 @@ public sealed class ContourPage
|
||||
HorizontalAlignment = HorizontalAlignment.Right
|
||||
};
|
||||
|
||||
// 右下角「上色」开关:点击一次去掉分层设色,只显示线稿,再点恢复
|
||||
_colorBtnText = new TextBlock
|
||||
{
|
||||
Text = T("btn.color"),
|
||||
FontSize = 11.5,
|
||||
Foreground = B(Colors.White)
|
||||
};
|
||||
_colorBtn = new Border
|
||||
{
|
||||
Background = B(CAccent),
|
||||
CornerRadius = new CornerRadius(8),
|
||||
Padding = new Thickness(13, 6),
|
||||
Margin = new Thickness(0, 0, 12, 0),
|
||||
Cursor = new Avalonia.Input.Cursor(Avalonia.Input.StandardCursorType.Hand),
|
||||
Child = _colorBtnText
|
||||
};
|
||||
_colorBtn.PointerPressed += (_, _) => ToggleColor();
|
||||
var info = new Grid { ColumnDefinitions = new ColumnDefinitions("*,Auto") };
|
||||
info.Children.Add(_readout);
|
||||
Grid.SetColumn(_featureText, 1);
|
||||
info.Children.Add(_featureText);
|
||||
|
||||
var left = new Grid { ColumnDefinitions = new ColumnDefinitions("*,Auto") };
|
||||
left.Children.Add(_readout);
|
||||
Grid.SetColumn(_colorBtn, 1);
|
||||
left.Children.Add(_colorBtn);
|
||||
var leftStack = new StackPanel { Spacing = 4, VerticalAlignment = VerticalAlignment.Center };
|
||||
leftStack.Children.Add(_hintText);
|
||||
leftStack.Children.Add(info);
|
||||
|
||||
var progStack = new StackPanel { Spacing = 6, VerticalAlignment = VerticalAlignment.Center };
|
||||
progStack.Children.Add(leftStack);
|
||||
progStack.Children.Add(_progress);
|
||||
|
||||
var row = new Grid { ColumnDefinitions = new ColumnDefinitions("*,Auto") };
|
||||
row.Children.Add(left);
|
||||
Grid.SetColumn(_featureText, 1);
|
||||
row.Children.Add(_featureText);
|
||||
row.Children.Add(progStack);
|
||||
Grid.SetColumn(controls, 1);
|
||||
row.Children.Add(controls);
|
||||
|
||||
return new Border
|
||||
{
|
||||
Background = B(CPanel),
|
||||
BorderBrush = B(CLine),
|
||||
BorderThickness = new Thickness(0, 1, 0, 0),
|
||||
Padding = new Thickness(18, 9),
|
||||
Padding = new Thickness(16, 9),
|
||||
Child = row
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>切换分层设色。</summary>
|
||||
private void TogglePlay()
|
||||
{
|
||||
if (_view == null) return;
|
||||
if (_selectedLandform != null) BackToExperiment();
|
||||
_view.TogglePlay();
|
||||
SetPlayLabel(_view.IsPlaying ? T("btn.pause") : T("btn.play"));
|
||||
if (_hintText != null)
|
||||
_hintText.Text = _view.IsPlaying ? T("hint.playing") : T("hint.paused");
|
||||
}
|
||||
|
||||
private void ToggleColor()
|
||||
{
|
||||
if (_view == null) return;
|
||||
_view.Colored = !_view.Colored;
|
||||
if (_colorBtn != null)
|
||||
_colorBtn.Background = B(_view.Colored ? CAccent : Color.Parse("#2A3B55"));
|
||||
if (_colorBtnText != null)
|
||||
_colorBtnText.Text = _view.Colored ? T("btn.colorOn") : T("btn.color");
|
||||
if (_colorBtn != null) _colorBtn.Background = B(_view.Colored ? CAccent : Color.Parse("#2A3B55"));
|
||||
if (_colorBtnText != null) _colorBtnText.Text = _view.Colored ? T("btn.colorOn") : T("btn.color");
|
||||
}
|
||||
|
||||
private void SetPlayLabel(string text) { if (_playLabel != null) _playLabel.Text = text; }
|
||||
|
||||
private void UpdateViewToggleLabel()
|
||||
{
|
||||
if (_viewToggleLabel == null || _view == null) return;
|
||||
_viewToggleLabel.Text = _view.Mode == ViewMode.Top ? T("btn.view3d") : T("btn.viewTop");
|
||||
}
|
||||
|
||||
private void UpdateFlowStyles()
|
||||
{
|
||||
for (var i = 0; i < _flowButtons.Count; i++)
|
||||
{
|
||||
var b = _flowButtons[i];
|
||||
var active = i == _step && _selectedLandform == null;
|
||||
var done = i < _step && _selectedLandform == null;
|
||||
StylePill(b, active ? CAccent : done ? Color.Parse("#1C3A5E") : CPanel2,
|
||||
active ? Colors.White : done ? CGood : CInkDim);
|
||||
}
|
||||
}
|
||||
|
||||
private void UpdateLandformStyles()
|
||||
{
|
||||
for (var i = 0; i < _landformButtons.Count; i++)
|
||||
{
|
||||
var b = _landformButtons[i];
|
||||
var kind = LandformOrder[i];
|
||||
var active = _selectedLandform == kind;
|
||||
StylePill(b, active ? CAccent : CPanel2, active ? Colors.White : CInkDim);
|
||||
}
|
||||
}
|
||||
|
||||
private static void StylePill(Border b, Color bg, Color fg)
|
||||
{
|
||||
b.Background = B(bg);
|
||||
if (b.Child is TextBlock tb) tb.Foreground = B(fg);
|
||||
else if (b.Child is StackPanel sp)
|
||||
foreach (var c in sp.Children)
|
||||
if (c is TextBlock t) t.Foreground = B(fg);
|
||||
}
|
||||
|
||||
private void OnStepChanged(ExperimentStep step)
|
||||
{
|
||||
_step = (int)step;
|
||||
UpdateFlowStyles();
|
||||
if (_selectedLandform == null && _observeSummary != null)
|
||||
_observeSummary.Text = T("flow.desc." + _step);
|
||||
}
|
||||
|
||||
private void OnProgressChanged(ExperimentStep step, double value)
|
||||
=> _progress?.Value = value * 100;
|
||||
|
||||
private void OnPlaybackFinished()
|
||||
{
|
||||
SetPlayLabel(T("btn.replay"));
|
||||
if (_hintText != null) _hintText.Text = T("hint.done");
|
||||
}
|
||||
|
||||
private void OnHover(double u, double v, float height, TerrainFeature feature)
|
||||
{
|
||||
if (_readout == null || _featureText == null) return;
|
||||
|
||||
var relative = height - _field.MinHeight;
|
||||
_readout.Text = string.Format(
|
||||
System.Globalization.CultureInfo.InvariantCulture,
|
||||
T("footer.readout"), (int)height, (int)relative);
|
||||
|
||||
var field = _view?.Field ?? _experimentField;
|
||||
var relative = height - field.MinHeight;
|
||||
_readout.Text = T("footer.readout", (int)height, (int)relative);
|
||||
_featureText.Text = FeatureName(feature);
|
||||
_featureText.Foreground = B(feature switch
|
||||
{
|
||||
@@ -366,4 +635,87 @@ public sealed class ContourPage
|
||||
TerrainFeature.Slope => T("feature.slope"),
|
||||
_ => ""
|
||||
};
|
||||
|
||||
private void OnKeyDown(object? sender, KeyEventArgs e)
|
||||
{
|
||||
// 空格:播放/暂停
|
||||
if (e.Key == Key.Space)
|
||||
{
|
||||
e.Handled = true;
|
||||
TogglePlay();
|
||||
return;
|
||||
}
|
||||
// 1-5:切换五大地貌
|
||||
var idx = -1;
|
||||
switch (e.Key)
|
||||
{
|
||||
case Key.D1: case Key.NumPad1: idx = 0; break;
|
||||
case Key.D2: case Key.NumPad2: idx = 1; break;
|
||||
case Key.D3: case Key.NumPad3: idx = 2; break;
|
||||
case Key.D4: case Key.NumPad4: idx = 3; break;
|
||||
case Key.D5: case Key.NumPad5: idx = 4; break;
|
||||
}
|
||||
if (idx >= 0 && idx < LandformOrder.Length)
|
||||
{
|
||||
e.Handled = true;
|
||||
SelectLandform(LandformOrder[idx]);
|
||||
}
|
||||
}
|
||||
|
||||
private void ToggleFullscreen(TextBlock label)
|
||||
{
|
||||
if (_topLevel is not Window window) return;
|
||||
if (window.WindowState == WindowState.FullScreen)
|
||||
{
|
||||
window.WindowState = WindowState.Normal;
|
||||
label.Text = T("btn.fullscreen");
|
||||
}
|
||||
else
|
||||
{
|
||||
window.WindowState = WindowState.FullScreen;
|
||||
label.Text = T("btn.exitFullscreen");
|
||||
}
|
||||
}
|
||||
|
||||
// ── 控件工厂
|
||||
|
||||
private static TextBlock Section(string text) => new()
|
||||
{
|
||||
Text = text,
|
||||
Foreground = BConst(CInk),
|
||||
FontSize = 12.5,
|
||||
FontWeight = FontWeight.SemiBold,
|
||||
Margin = new Thickness(0, 2, 0, 2)
|
||||
};
|
||||
|
||||
private static Border Divider() => new()
|
||||
{
|
||||
Height = 1,
|
||||
Background = BConst(CLine),
|
||||
Margin = new Thickness(0, 4, 0, 2)
|
||||
};
|
||||
|
||||
private static TextBlock Bullet(string text) => new()
|
||||
{
|
||||
Text = "• " + text,
|
||||
Foreground = BConst(CInkDim),
|
||||
FontSize = 11.5,
|
||||
TextWrapping = TextWrapping.Wrap,
|
||||
LineHeight = 17
|
||||
};
|
||||
|
||||
private Border MakePillButton(string label, Color bg)
|
||||
{
|
||||
var tb = new TextBlock { Text = label, Foreground = B(Colors.White), FontSize = 11.5, HorizontalAlignment = HorizontalAlignment.Center };
|
||||
return new Border
|
||||
{
|
||||
Background = B(bg),
|
||||
CornerRadius = new CornerRadius(8),
|
||||
Padding = new Thickness(11, 6),
|
||||
Cursor = new Avalonia.Input.Cursor(Avalonia.Input.StandardCursorType.Hand),
|
||||
Child = tb
|
||||
};
|
||||
}
|
||||
|
||||
private static SolidColorBrush BConst(Color c) => new(c);
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -2,24 +2,88 @@ using System.Collections.Generic;
|
||||
|
||||
namespace GC.ContourMap;
|
||||
|
||||
/// <summary>内置全量文案兜底:没有语言包也能完整显示。</summary>
|
||||
/// <summary>内置全量文案兜底:没有语言包也能完整显示(复刻 HTML 课件全部文案)。</summary>
|
||||
internal static class DefaultTexts
|
||||
{
|
||||
public static readonly Dictionary<string, string> Zh = new()
|
||||
{
|
||||
["app.title"] = "等高线地形图",
|
||||
["app.subtitle"] = "七年级上册 · 地形图的判读:从立体地形到平面等高线",
|
||||
// 标题
|
||||
["app.title"] = "等高线地形 · 五大典型地貌判读",
|
||||
["app.subtitle"] = "七年级上册 · 从立体地形到平面等高线,判读山峰/山脊/山谷/鞍部/陡崖",
|
||||
|
||||
["kind.mountain"] = "山地",
|
||||
["kind.basin"] = "盆地",
|
||||
["kind.hill"] = "丘陵",
|
||||
["kind.plateau"] = "高原",
|
||||
["kind.plain"] = "平原",
|
||||
["legend.title"] = "分层设色",
|
||||
["profile.title"] = "地形剖面图",
|
||||
// 实验流程四步
|
||||
["flow.title"] = "实验流程",
|
||||
["flow.step.0"] = "等高切割",
|
||||
["flow.step.1"] = "形成交线",
|
||||
["flow.step.2"] = "投影成图",
|
||||
["flow.step.3"] = "疏密判坡",
|
||||
["flow.desc.0"] = "观察水平面与山体在同一海拔相交,形成连续闭合线。",
|
||||
["flow.desc.1"] = "每个水平切面都会留下同高交线,多层交线共同描述山体起伏。",
|
||||
["flow.desc.2"] = "把各高度交线垂直投影到同一平面,得到完整等高线地形图。",
|
||||
["flow.desc.3"] = "等高线越密,坡度越陡;等高线越疏,坡度越缓。",
|
||||
|
||||
// 观察面板
|
||||
["observe.title"] = "实验演示",
|
||||
["observe.default"] = "点击开始实验,在立体地形中观察等高切割与交线形成,再通过四步图解理解投影与判坡。",
|
||||
["observe.features"] = "判读要点",
|
||||
["observe.default.f1"] = "同一条等高线上海拔相等",
|
||||
["observe.default.f2"] = "相邻等高线高差保持一致",
|
||||
|
||||
// 五大典型地貌
|
||||
["side.landforms"] = "五大典型地貌",
|
||||
["landform.peak"] = "山峰",
|
||||
["landform.ridge"] = "山脊",
|
||||
["landform.valley"] = "山谷",
|
||||
["landform.saddle"] = "鞍部",
|
||||
["landform.cliff"] = "陡崖",
|
||||
["landform.peak.sub"] = "闭合等高线",
|
||||
["landform.ridge.sub"] = "凸低为脊",
|
||||
["landform.valley.sub"] = "凸高为谷",
|
||||
["landform.saddle.sub"] = "两峰之间",
|
||||
["landform.cliff.sub"] = "密集或重合",
|
||||
|
||||
["landform.peak.summary"] = "山峰四周较低、中心突起;等高线闭合成环,海拔数值由外向内逐渐升高。",
|
||||
["landform.ridge.summary"] = "等高线弯曲部分向海拔低处凸出,脊线常成为两侧水系的分水岭。",
|
||||
["landform.valley.summary"] = "等高线弯曲部分向海拔高处凸出,谷底低洼并容易汇水形成河流。",
|
||||
["landform.saddle.summary"] = "鞍部位于相邻两座山峰之间,是沿山脊方向相对低洼的过渡地带。",
|
||||
["landform.cliff.summary"] = "陡崖坡面近直立,不同高程的等高线会高度密集,局部可投影到同一位置而重合。",
|
||||
|
||||
["landform.peak.f1"] = "中心海拔高、四周海拔低",
|
||||
["landform.peak.f2"] = "闭合线越向内,数值越大",
|
||||
["landform.peak.f3"] = "若数值向内降低,则应判为洼地",
|
||||
["landform.ridge.f1"] = "等高线凸向低值方向",
|
||||
["landform.ridge.f2"] = "脊线由高处向低处延伸",
|
||||
["landform.ridge.f3"] = "雨水沿脊线两侧分流",
|
||||
["landform.valley.f1"] = "等高线凸向高值方向",
|
||||
["landform.valley.f2"] = "V 形尖端指向上游高处",
|
||||
["landform.valley.f3"] = "谷底常发育河流",
|
||||
["landform.saddle.f1"] = "两组闭合等高线相邻",
|
||||
["landform.saddle.f2"] = "中部线条收窄,形似马鞍",
|
||||
["landform.saddle.f3"] = "常是翻越山岭的低垭口",
|
||||
["landform.cliff.f1"] = "密集表示陡坡,重合才是陡崖特征",
|
||||
["landform.cliff.f2"] = "单位水平距离内高差很大",
|
||||
["landform.cliff.f3"] = "n 条线重合时:(n−1)d ≤ ΔH < (n+1)d",
|
||||
|
||||
["landform.peak.hint"] = "山峰:闭合曲线,数值向中心升高",
|
||||
["landform.ridge.hint"] = "山脊:等高线向低处凸出,凸低为脊",
|
||||
["landform.valley.hint"] = "山谷:等高线向高处凸出,凸高为谷",
|
||||
["landform.saddle.hint"] = "鞍部:两峰之间相对低洼,俯视轮廓呈收腰形",
|
||||
["landform.cliff.hint"] = "陡崖:等高线密集或重合,坡度极陡",
|
||||
|
||||
// 按钮
|
||||
["btn.play"] = "开始实验",
|
||||
["btn.pause"] = "暂停实验",
|
||||
["btn.replay"] = "重新实验",
|
||||
["btn.reset"] = "重置",
|
||||
["btn.view3d"] = "立体图",
|
||||
["btn.viewTop"] = "俯视图",
|
||||
["btn.color"] = "上色",
|
||||
["btn.colorOn"] = "取消上色",
|
||||
["btn.fullscreen"] = "全屏",
|
||||
["btn.exitFullscreen"] = "退出全屏",
|
||||
["btn.backExperiment"] = "返回实验",
|
||||
|
||||
// 侧栏判读要点(通用地形)
|
||||
["side.features"] = "五种地形部位",
|
||||
["feature.peak"] = "山峰",
|
||||
["feature.peakDesc"] = "等高线闭合,数值由中心向四周递减。",
|
||||
@@ -33,30 +97,99 @@ internal static class DefaultTexts
|
||||
["feature.cliffDesc"] = "等高线重叠或非常密集,近乎垂直。",
|
||||
["feature.slope"] = "坡面",
|
||||
|
||||
// 判读规则
|
||||
["side.rules"] = "判读要点",
|
||||
["rule.interval"] = "等高距:相邻两条等高线的高度差,本图 100 米。",
|
||||
["rule.dense"] = "等高线越密坡越陡,越疏坡越缓。",
|
||||
["rule.index"] = "每 5 条加粗一条计曲线,标注海拔便于读数。",
|
||||
["rule.height"] = "海拔:某地高出海平面的垂直距离;相对高度:两点海拔之差。",
|
||||
|
||||
["footer.hint"] = "把鼠标移到任意一侧,可查看该点的海拔与地形部位",
|
||||
["footer.readout"] = "海拔 {0} m 相对高度 {1} m"
|
||||
// 底部读数 / 图例
|
||||
["footer.hint"] = "拖动立体地形旋转、滚轮缩放;鼠标悬停可查看该点海拔与地形部位",
|
||||
["footer.readout"] = "海拔 {0} m 相对高度 {1} m",
|
||||
["legend.title"] = "分层设色",
|
||||
["profile.title"] = "地形剖面图",
|
||||
["slope.gentle"] = "缓坡(线疏)",
|
||||
["slope.steep"] = "陡坡(线密)",
|
||||
|
||||
["hint.play"] = "点击“开始实验”,观察等高切割与交线形成",
|
||||
["hint.playing"] = "实验播放中",
|
||||
["hint.paused"] = "实验已暂停 · 点击继续恢复播放",
|
||||
["hint.done"] = "实验流程播放完成 · 可重新实验或选择典型地貌观察"
|
||||
};
|
||||
|
||||
public static readonly Dictionary<string, string> En = new()
|
||||
{
|
||||
["app.title"] = "Contour Map",
|
||||
["app.subtitle"] = "Grade 7 · Reading terrain maps: from 3D relief to contour lines",
|
||||
["app.title"] = "Contour Lines · Five Classic Landforms",
|
||||
["app.subtitle"] = "Grade 7 · From 3D relief to contour maps: peaks, ridges, valleys, saddles and cliffs",
|
||||
|
||||
["kind.mountain"] = "Mountains",
|
||||
["kind.basin"] = "Basin",
|
||||
["kind.hill"] = "Hills",
|
||||
["kind.plateau"] = "Plateau",
|
||||
["kind.plain"] = "Plain",
|
||||
["legend.title"] = "Hypsometric tint",
|
||||
["profile.title"] = "Terrain profile",
|
||||
["flow.title"] = "Experiment flow",
|
||||
["flow.step.0"] = "Contour cutting",
|
||||
["flow.step.1"] = "Forming lines",
|
||||
["flow.step.2"] = "Projection",
|
||||
["flow.step.3"] = "Slope density",
|
||||
["flow.desc.0"] = "Watch a horizontal plane intersect the mountain at one elevation, forming closed lines.",
|
||||
["flow.desc.1"] = "Each horizontal slice leaves an equal-height line; stacked lines describe the relief.",
|
||||
["flow.desc.2"] = "Project every intersection line vertically onto one plane to build the contour map.",
|
||||
["flow.desc.3"] = "Contours closer together mean a steeper slope; wider apart mean a gentler one.",
|
||||
|
||||
["observe.title"] = "Experiment demo",
|
||||
["observe.default"] = "Press play to watch contour cutting and line formation, then use the four steps to learn projection and slope reading.",
|
||||
["observe.features"] = "Key points",
|
||||
["observe.default.f1"] = "All points on one contour share the same elevation",
|
||||
["observe.default.f2"] = "Neighbouring contours keep a constant height interval",
|
||||
|
||||
["side.landforms"] = "Five classic landforms",
|
||||
["landform.peak"] = "Peak",
|
||||
["landform.ridge"] = "Ridge",
|
||||
["landform.valley"] = "Valley",
|
||||
["landform.saddle"] = "Saddle",
|
||||
["landform.cliff"] = "Cliff",
|
||||
["landform.peak.sub"] = "Closed contours",
|
||||
["landform.ridge.sub"] = "Bulges toward low ground",
|
||||
["landform.valley.sub"] = "Bulges toward high ground",
|
||||
["landform.saddle.sub"] = "Between two peaks",
|
||||
["landform.cliff.sub"] = "Dense or overlapping",
|
||||
|
||||
["landform.peak.summary"] = "A peak rises in the centre with lower ground around it; contours close into rings and values increase inward.",
|
||||
["landform.ridge.summary"] = "Contours bulge toward lower ground; a ridge line often divides two drainage systems.",
|
||||
["landform.valley.summary"] = "Contours bulge toward higher ground; valleys are low and collect water into streams.",
|
||||
["landform.saddle.summary"] = "A saddle lies between two adjacent peaks, a relatively low pass along the ridge.",
|
||||
["landform.cliff.summary"] = "A cliff face is nearly vertical, so contours crowd tightly or even overlap.",
|
||||
|
||||
["landform.peak.f1"] = "High centre, low surroundings",
|
||||
["landform.peak.f2"] = "Closed lines grow in value inward",
|
||||
["landform.peak.f3"] = "If values drop inward, it is a depression",
|
||||
["landform.ridge.f1"] = "Contours bulge toward lower values",
|
||||
["landform.ridge.f2"] = "Ridge line runs from high to low",
|
||||
["landform.ridge.f3"] = "Rain drains to either side of the ridge",
|
||||
["landform.valley.f1"] = "Contours bulge toward higher values",
|
||||
["landform.valley.f2"] = "V tip points upstream to high ground",
|
||||
["landform.valley.f3"] = "Streams often form along the valley floor",
|
||||
["landform.saddle.f1"] = "Two neighbouring closed contour groups",
|
||||
["landform.saddle.f2"] = "Contours pinch in the middle like a saddle",
|
||||
["landform.saddle.f3"] = "Often a low mountain pass",
|
||||
["landform.cliff.f1"] = "Dense means steep; overlap means cliff",
|
||||
["landform.cliff.f2"] = "Large elevation change over a short distance",
|
||||
["landform.cliff.f3"] = "n overlapping lines: (n−1)d ≤ ΔH < (n+1)d",
|
||||
|
||||
["landform.peak.hint"] = "Peak: closed curves, values rise toward the centre",
|
||||
["landform.ridge.hint"] = "Ridge: contours bulge toward low ground",
|
||||
["landform.valley.hint"] = "Valley: contours bulge toward high ground",
|
||||
["landform.saddle.hint"] = "Saddle: low ground between two peaks",
|
||||
["landform.cliff.hint"] = "Cliff: contours dense or overlapping, very steep",
|
||||
|
||||
["btn.play"] = "Start experiment",
|
||||
["btn.pause"] = "Pause experiment",
|
||||
["btn.replay"] = "Replay experiment",
|
||||
["btn.reset"] = "Reset",
|
||||
["btn.view3d"] = "3D view",
|
||||
["btn.viewTop"] = "Top view",
|
||||
["btn.color"] = "Colour",
|
||||
["btn.colorOn"] = "No colour",
|
||||
["btn.fullscreen"] = "Fullscreen",
|
||||
["btn.exitFullscreen"] = "Exit fullscreen",
|
||||
["btn.backExperiment"] = "Back to experiment",
|
||||
|
||||
["side.features"] = "Five terrain features",
|
||||
["feature.peak"] = "Peak",
|
||||
@@ -77,7 +210,16 @@ internal static class DefaultTexts
|
||||
["rule.index"] = "Every 5th contour is bolded and labelled as an index contour.",
|
||||
["rule.height"] = "Elevation above sea level; relative height is the difference of two elevations.",
|
||||
|
||||
["footer.hint"] = "Move the pointer over either side to read elevation and terrain feature",
|
||||
["footer.readout"] = "Elevation {0} m Relative height {1} m"
|
||||
["footer.hint"] = "Drag the 3D terrain to rotate, scroll to zoom; hover to read elevation and terrain feature",
|
||||
["footer.readout"] = "Elevation {0} m Relative height {1} m",
|
||||
["legend.title"] = "Hypsometric tint",
|
||||
["profile.title"] = "Terrain profile",
|
||||
["slope.gentle"] = "Gentle (sparse lines)",
|
||||
["slope.steep"] = "Steep (dense lines)",
|
||||
|
||||
["hint.play"] = "Press start to watch contour cutting and line formation",
|
||||
["hint.playing"] = "Experiment playing",
|
||||
["hint.paused"] = "Experiment paused · press to resume",
|
||||
["hint.done"] = "Experiment finished · replay or choose a landform"
|
||||
};
|
||||
}
|
||||
@@ -123,8 +123,6 @@ public static class TerrainAnalyzer
|
||||
public static (byte R, byte G, byte B) ColorForHeight(float h, float min, float max)
|
||||
{
|
||||
// 按绝对高程分档(教科书就是这么画的:看的是海拔,不是相对高度)
|
||||
const float band = 200f; // 每 200 米一档
|
||||
|
||||
if (h < 200) return (0x1E, 0x6B, 0x3A); // 深绿:< 200 m
|
||||
if (h < 400) return (0x4E, 0x9E, 0x4E); // 浅绿:200–400
|
||||
if (h < 600) return (0xA8, 0xC6, 0x66); // 绿:400–600
|
||||
@@ -136,6 +134,31 @@ public static class TerrainAnalyzer
|
||||
return (0xF5, 0xF5, 0xF0); // 白:> 1600(雪线以上)
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 3D 立体视图用的连续设色:与俯视图同一套色阶,但在档位之间线性过渡。
|
||||
/// 立体视图的色块是按三角面着色的,直接用硬分档会在坡面上切出锯齿状阶梯,
|
||||
/// 看起来像渲染错误;俯视图仍保留硬分档(那才是课本的分层设色)。
|
||||
/// </summary>
|
||||
public static (byte R, byte G, byte B) ColorForHeightSmooth(float h)
|
||||
{
|
||||
// 每个档位的代表色(取档位中心),由低到高
|
||||
(byte R, byte G, byte B)[] stops =
|
||||
{
|
||||
(0x1E, 0x6B, 0x3A), (0x4E, 0x9E, 0x4E), (0xA8, 0xC6, 0x66),
|
||||
(0xE8, 0xE2, 0x9A), (0xE0, 0xC0, 0x5A), (0xC8, 0x9A, 0x63),
|
||||
(0xA8, 0x74, 0x4C), (0xC8, 0xA8, 0x8C), (0xF5, 0xF5, 0xF0)
|
||||
};
|
||||
const float band = 200f;
|
||||
var p = Math.Clamp(h / band - 0.5f, 0f, stops.Length - 1f); // 0 => 档心 100 m
|
||||
var i = (int)Math.Floor(p);
|
||||
var j = Math.Min(i + 1, stops.Length - 1);
|
||||
var t = p - i;
|
||||
t = t * t * (3 - 2 * t); // 平滑过渡
|
||||
return (Lerp(stops[i].R, stops[j].R, t),
|
||||
Lerp(stops[i].G, stops[j].G, t),
|
||||
Lerp(stops[i].B, stops[j].B, t));
|
||||
}
|
||||
|
||||
/// <summary>该颜色属于哪一档(用于图例)。</summary>
|
||||
public static string BandName(float h) => h switch
|
||||
{
|
||||
@@ -152,4 +175,20 @@ public static class TerrainAnalyzer
|
||||
|
||||
private static byte Lerp(byte a, byte b, double k)
|
||||
=> (byte)Math.Clamp(a + (b - a) * k, 0, 255);
|
||||
|
||||
/// <summary>
|
||||
/// 归一化坡度(0=平缓,1=陡峭),用于「疏密判坡」着色。
|
||||
/// 以有限差分求地面梯度,并按本模型的典型高差归一化。
|
||||
/// </summary>
|
||||
public static double SlopeAt(TerrainField f, double u, double v)
|
||||
{
|
||||
const double h = 0.006;
|
||||
var du = (f.SampleSmooth(u + h, v) - f.SampleSmooth(u - h, v)) / (2 * h);
|
||||
var dv = (f.SampleSmooth(u, v + h) - f.SampleSmooth(u, v - h)) / (2 * h);
|
||||
var grad = Math.Sqrt(du * du + dv * dv); // 米 / 归一化距离
|
||||
// 按本图实际起伏自适应归一化:跨度越大,同样的相对坡度对应更大的梯度。
|
||||
// 固定阈值会让所有山体都顶到 1(整片红),判坡就失效了。
|
||||
var span = Math.Max(60f, f.MaxHeight - f.MinHeight);
|
||||
return Math.Clamp(grad / (span * 2.6), 0, 1);
|
||||
}
|
||||
}
|
||||
@@ -13,6 +13,16 @@ public enum TerrainKind
|
||||
Plain // 平原:海拔低、地面平坦
|
||||
}
|
||||
|
||||
/// <summary>五大典型地貌部位(等高线判读的核心对象)。</summary>
|
||||
public enum LandformKind
|
||||
{
|
||||
Peak, // 山峰:闭合等高线,数值向内升高
|
||||
Ridge, // 山脊:等高线凸向低处,凸低为脊
|
||||
Valley, // 山谷:等高线凸向高处,凸高为谷
|
||||
Saddle, // 鞍部:两峰之间相对低洼,俯视收腰
|
||||
Cliff // 陡崖:等高线密集甚至重合
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 地形高度场(等高线模型的数据核心)。
|
||||
///
|
||||
@@ -42,6 +52,9 @@ public sealed class TerrainField
|
||||
/// <summary>这块地形属于哪种类型(决定界面标题与说明)。</summary>
|
||||
public TerrainKind Kind { get; }
|
||||
|
||||
/// <summary>若这块地形是某个典型地貌部位,则记录其种类;否则为 null。</summary>
|
||||
public LandformKind? Landform { get; }
|
||||
|
||||
public TerrainField(TerrainKind kind = TerrainKind.Mountain, int size = 192)
|
||||
{
|
||||
Size = size;
|
||||
@@ -50,6 +63,16 @@ public sealed class TerrainField
|
||||
Build(kind);
|
||||
}
|
||||
|
||||
/// <summary>创建一个专门表现某种典型地貌部位的高度场。</summary>
|
||||
public TerrainField(LandformKind landform, int size = 192)
|
||||
{
|
||||
Size = size;
|
||||
Kind = TerrainKind.Mountain;
|
||||
Landform = landform;
|
||||
Heights = new float[size, size];
|
||||
BuildLandform(landform);
|
||||
}
|
||||
|
||||
/// <summary>该类型对应的等高距:平原/丘陵用 20m,山地/高原/盆地用 100m。</summary>
|
||||
public float EffectiveInterval => Kind switch
|
||||
{
|
||||
@@ -266,6 +289,157 @@ public sealed class TerrainField
|
||||
MinHeight = min; MaxHeight = max;
|
||||
}
|
||||
|
||||
// ───────────────────────── 五大典型地貌部位 ─────────────────────────
|
||||
|
||||
private void BuildLandform(LandformKind landform)
|
||||
{
|
||||
switch (landform)
|
||||
{
|
||||
case LandformKind.Peak: BuildPeak(); break;
|
||||
case LandformKind.Ridge: BuildRidge(); break;
|
||||
case LandformKind.Valley: BuildValley(); break;
|
||||
case LandformKind.Saddle: BuildSaddle(); break;
|
||||
case LandformKind.Cliff: BuildCliff(); break;
|
||||
}
|
||||
BuildFeatures();
|
||||
}
|
||||
|
||||
/// <summary>山峰:单峰为主、层层闭合,四周逐级降低。配一处小侧峰便于读鞍部。</summary>
|
||||
private void BuildPeak()
|
||||
{
|
||||
var min = double.MaxValue; var max = double.MinValue;
|
||||
for (var y = 0; y < Size; y++)
|
||||
for (var x = 0; x < Size; x++)
|
||||
{
|
||||
var u = (double)x / (Size - 1);
|
||||
var v = (double)y / (Size - 1);
|
||||
var du = u - 0.5; var dv = (v - 0.5) / 0.94;
|
||||
var r = Math.Sqrt(du * du + dv * dv);
|
||||
// 主峰:宽阔的穹状山体(半径约占图幅 8 成),层层闭合的等高线才画得开
|
||||
var core = Math.Exp(-Math.Pow(r / 0.36, 1.85));
|
||||
var rim = 1 - SmoothStep(0.36, 0.50, r); // 山脚过渡到平地
|
||||
var h = 65 + 1230 * core * rim;
|
||||
// 东南侧肩部,让等高线不是完美同心圆
|
||||
h += 120 * Math.Exp(-(Math.Pow(u - 0.72, 2) + Math.Pow(v - 0.66, 2)) / 0.016) * rim;
|
||||
h += 22 * Math.Sin(u * 7.3 + 0.6) * Math.Cos(v * 6.1) * rim;
|
||||
h = Math.Max(0, h);
|
||||
Heights[y, x] = (float)h;
|
||||
if (h < min) min = h; if (h > max) max = h;
|
||||
}
|
||||
MinHeight = (float)min; MaxHeight = (float)max;
|
||||
Tags.Clear();
|
||||
Tags.Add((0.5, 0.5, 0.09, TerrainFeature.Peak));
|
||||
}
|
||||
|
||||
/// <summary>山脊:一条狭长高地,等高线沿脊线向低处凸出(凸低为脊)。</summary>
|
||||
private void BuildRidge()
|
||||
{
|
||||
var min = double.MaxValue; var max = double.MinValue;
|
||||
for (var y = 0; y < Size; y++)
|
||||
for (var x = 0; x < Size; x++)
|
||||
{
|
||||
var u = (double)x / (Size - 1);
|
||||
var v = (double)y / (Size - 1);
|
||||
// 脊线沿 u 方向(西高东低),东西向是长坡,南北向是宽缓的两翼
|
||||
var crestV = 0.5 + 0.10 * Math.Sin(u * 3.1); // 脊线轻微弯曲
|
||||
var across = v - crestV;
|
||||
var crest = 1150 - 380 * u; // 脊线海拔由西向东降低
|
||||
var lateral = Math.Exp(-Math.Pow(Math.Abs(across) / 0.27, 1.55));
|
||||
var h = 85 + (crest - 85) * lateral;
|
||||
// 两翼的次级起伏,避免像一堵直墙
|
||||
h += 60 * Math.Exp(-Math.Pow(Math.Abs(across) - 0.30, 2) / 0.010) * (0.4 + 0.6 * (1 - u));
|
||||
h += 24 * Math.Sin(u * 8.0) * Math.Cos(v * 5.6);
|
||||
h = Math.Max(0, h);
|
||||
Heights[y, x] = (float)h;
|
||||
if (h < min) min = h; if (h > max) max = h;
|
||||
}
|
||||
MinHeight = (float)min; MaxHeight = (float)max;
|
||||
Tags.Clear();
|
||||
Tags.Add((0.30, 0.50, 0.09, TerrainFeature.Ridge));
|
||||
Tags.Add((0.70, 0.50, 0.09, TerrainFeature.Ridge));
|
||||
}
|
||||
|
||||
/// <summary>山谷:两侧高地夹持的低槽,等高线形成 V 形指向上游(凸高为谷)。</summary>
|
||||
private void BuildValley()
|
||||
{
|
||||
var min = double.MaxValue; var max = double.MinValue;
|
||||
for (var y = 0; y < Size; y++)
|
||||
for (var x = 0; x < Size; x++)
|
||||
{
|
||||
var u = (double)x / (Size - 1);
|
||||
var v = (double)y / (Size - 1);
|
||||
// 谷轴沿 v 方向:两侧高、中间是 V 形谷底;北侧(v 小)为上游更高
|
||||
var side = Math.Pow(Math.Abs(u - 0.5) / 0.5, 1.5); // 0=谷心 1=图边
|
||||
var downhill = 1 - v; // 上游 1 → 下游 0
|
||||
var h = 90 + 760 * downhill + 585 * side * (0.30 + 0.70 * downhill);
|
||||
// 谷底再切深一点,形成明显的集水线
|
||||
h -= 70 * Math.Exp(-Math.Pow(u - 0.5, 2) / 0.0022);
|
||||
h += 18 * Math.Sin(u * 6.5) * Math.Cos(v * 7.2);
|
||||
h = Math.Max(0, h);
|
||||
Heights[y, x] = (float)h;
|
||||
if (h < min) min = h; if (h > max) max = h;
|
||||
}
|
||||
MinHeight = (float)min; MaxHeight = (float)max;
|
||||
Tags.Clear();
|
||||
Tags.Add((0.50, 0.40, 0.075, TerrainFeature.Valley));
|
||||
Tags.Add((0.50, 0.68, 0.075, TerrainFeature.Valley));
|
||||
}
|
||||
|
||||
/// <summary>鞍部:两座山峰之间相对低洼、俯视轮廓收腰的过渡地带。</summary>
|
||||
private void BuildSaddle()
|
||||
{
|
||||
var min = double.MaxValue; var max = double.MinValue;
|
||||
for (var y = 0; y < Size; y++)
|
||||
for (var x = 0; x < Size; x++)
|
||||
{
|
||||
var u = (double)x / (Size - 1);
|
||||
var v = (double)y / (Size - 1);
|
||||
// 两峰在 v≈0.5 的连线上,u=0.27 与 u=0.73;中间 u=0.5 为垭口
|
||||
var d1 = Math.Sqrt(Math.Pow((u - 0.27) / 0.30, 2) + Math.Pow((v - 0.52) / 0.28, 2));
|
||||
var d2 = Math.Sqrt(Math.Pow((u - 0.73) / 0.30, 2) + Math.Pow((v - 0.48) / 0.28, 2));
|
||||
var p1 = 1140 * Math.Exp(-Math.Pow(d1, 2.2));
|
||||
var p2 = 1060 * Math.Exp(-Math.Pow(d2, 2.2));
|
||||
// 南北两侧缓慢降低,把两峰连成一条东西向的山梁
|
||||
var bench = 330 * Math.Exp(-Math.Pow((v - 0.5) / 0.34, 2));
|
||||
var h = 65 + bench + Math.Max(p1, p2);
|
||||
h += 20 * Math.Sin(u * 8.0) * Math.Cos(v * 7.0);
|
||||
h = Math.Max(0, h);
|
||||
Heights[y, x] = (float)h;
|
||||
if (h < min) min = h; if (h > max) max = h;
|
||||
}
|
||||
MinHeight = (float)min; MaxHeight = (float)max;
|
||||
Tags.Clear();
|
||||
Tags.Add((0.28, 0.50, 0.05, TerrainFeature.Peak));
|
||||
Tags.Add((0.72, 0.50, 0.05, TerrainFeature.Peak));
|
||||
Tags.Add((0.50, 0.50, 0.045, TerrainFeature.Saddle));
|
||||
}
|
||||
|
||||
/// <summary>陡崖:一侧近乎直立的高差带,等高线在崖壁处高度密集甚至重合。</summary>
|
||||
private void BuildCliff()
|
||||
{
|
||||
var min = double.MaxValue; var max = double.MinValue;
|
||||
for (var y = 0; y < Size; y++)
|
||||
for (var x = 0; x < Size; x++)
|
||||
{
|
||||
var u = (double)x / (Size - 1);
|
||||
var v = (double)y / (Size - 1);
|
||||
// 西侧低台地、东侧高台地,中间一条近乎直立的高差带形成陡崖
|
||||
// 崖线略呈波状(真实崖壁不是一条直线),过渡带留出 2~3 个采样格
|
||||
var edge = SmoothStep(0.50, 0.62, u + 0.045 * Math.Sin(v * 5.2) + 0.02 * Math.Sin(v * 11.0));
|
||||
var h = 210 + 940 * edge;
|
||||
// 高台地北高南低、顶面起伏,低台地保持缓坡
|
||||
h += 170 * (1 - v) * edge;
|
||||
h += 55 * Math.Sin(v * 5.4) * Math.Cos(u * 4.2) * (0.4 + 0.6 * edge);
|
||||
h += 26 * Math.Sin(u * 9.0); // 顶面轻微起伏
|
||||
h = Math.Max(0, h);
|
||||
Heights[y, x] = (float)h;
|
||||
if (h < min) min = h; if (h > max) max = h;
|
||||
}
|
||||
MinHeight = (float)min; MaxHeight = (float)max;
|
||||
Tags.Clear();
|
||||
Tags.Add((0.50, 0.50, 0.035, TerrainFeature.Cliff));
|
||||
}
|
||||
|
||||
private static double SmoothStep(double a, double b, double x)
|
||||
{
|
||||
var t = Math.Clamp((x - a) / (b - a), 0, 1);
|
||||
@@ -452,46 +626,77 @@ public sealed class TerrainField
|
||||
private static double Lerp(double a, double b, double t)
|
||||
=> a + (b - a) * Math.Clamp(double.IsNaN(t) ? 0.5 : t, 0, 1);
|
||||
|
||||
/// <summary>把零散线段按端点邻近关系串成折线。</summary>
|
||||
/// <summary>
|
||||
/// 把零散线段按端点串成完整折线。
|
||||
/// 关键点:必须**两端都延伸**。只往尾部延伸时,起点落在曲线中段就会把一条等高线
|
||||
/// 切成许多短链,渲染出来是断续的虚线(学生看到的就是“虚线等高线”)。
|
||||
/// </summary>
|
||||
private static List<List<(double U, double V)>> Chain(
|
||||
List<(double U1, double V1, double U2, double V2)> segments)
|
||||
{
|
||||
const double Eps = 0.004;
|
||||
var result = new List<List<(double, double)>>();
|
||||
// 量化到 1e-4 的网格做端点索引:共享边上的交点由同一次插值算出,
|
||||
// 端点值完全一致;网格远小于采样间距(1/192≈0.0052),不会误并。
|
||||
const double Q = 1e4;
|
||||
static (long, long) Key(double u, double v)
|
||||
=> ((long)Math.Round(u * Q), (long)Math.Round(v * Q));
|
||||
|
||||
var index = new Dictionary<(long, long), List<int>>();
|
||||
void Register(double u, double v, int seg)
|
||||
{
|
||||
var k = Key(u, v);
|
||||
if (!index.TryGetValue(k, out var list)) index[k] = list = new List<int>();
|
||||
list.Add(seg);
|
||||
}
|
||||
|
||||
for (var i = 0; i < segments.Count; i++)
|
||||
{
|
||||
Register(segments[i].U1, segments[i].V1, i);
|
||||
Register(segments[i].U2, segments[i].V2, i);
|
||||
}
|
||||
|
||||
var used = new bool[segments.Count];
|
||||
var result = new List<List<(double, double)>>();
|
||||
|
||||
int NextAt(double u, double v)
|
||||
{
|
||||
if (!index.TryGetValue(Key(u, v), out var list)) return -1;
|
||||
foreach (var j in list) if (!used[j]) return j;
|
||||
return -1;
|
||||
}
|
||||
|
||||
for (var i = 0; i < segments.Count; i++)
|
||||
{
|
||||
if (used[i]) continue;
|
||||
used[i] = true;
|
||||
var line = new List<(double, double)>
|
||||
var line = new List<(double U, double V)>
|
||||
{
|
||||
(segments[i].U1, segments[i].V1),
|
||||
(segments[i].U2, segments[i].V2)
|
||||
};
|
||||
|
||||
// 向两端延伸
|
||||
var grown = true;
|
||||
while (grown)
|
||||
// 向尾部延伸
|
||||
while (true)
|
||||
{
|
||||
grown = false;
|
||||
var (tailU, tailV) = line[^1];
|
||||
for (var j = 0; j < segments.Count; j++)
|
||||
{
|
||||
if (used[j]) continue;
|
||||
var s = segments[j];
|
||||
if (Near(tailU, tailV, s.U1, s.V1, Eps))
|
||||
{
|
||||
line.Add((s.U2, s.V2)); used[j] = true; grown = true; break;
|
||||
}
|
||||
if (Near(tailU, tailV, s.U2, s.V2, Eps))
|
||||
{
|
||||
line.Add((s.U1, s.V1)); used[j] = true; grown = true; break;
|
||||
}
|
||||
}
|
||||
var (tu, tv) = line[^1];
|
||||
var j = NextAt(tu, tv);
|
||||
if (j < 0) break;
|
||||
used[j] = true;
|
||||
var s = segments[j];
|
||||
line.Add(Key(s.U1, s.V1) == Key(tu, tv) ? (s.U2, s.V2) : (s.U1, s.V1));
|
||||
}
|
||||
|
||||
if (line.Count >= 4) result.Add(line);
|
||||
// 向头部延伸
|
||||
while (true)
|
||||
{
|
||||
var (hu, hv) = line[0];
|
||||
var j = NextAt(hu, hv);
|
||||
if (j < 0) break;
|
||||
used[j] = true;
|
||||
var s = segments[j];
|
||||
line.Insert(0, Key(s.U1, s.V1) == Key(hu, hv) ? (s.U2, s.V2) : (s.U1, s.V1));
|
||||
}
|
||||
|
||||
if (line.Count >= 3) result.Add(line);
|
||||
}
|
||||
|
||||
return result;
|
||||
|
||||
@@ -26,5 +26,5 @@
|
||||
"frame": "#0A1524"
|
||||
},
|
||||
"build": "cc68b8863b",
|
||||
"updatedAt": "2026-11-18T10:16:41Z"
|
||||
"updatedAt": "2026-11-19T10:20:00Z"
|
||||
}
|
||||
@@ -32,5 +32,5 @@
|
||||
"frame": "#0A1524"
|
||||
},
|
||||
"build": "53b7a0fbc3",
|
||||
"updatedAt": "2026-11-18T10:16:41Z"
|
||||
"updatedAt": "2026-11-19T10:20:00Z"
|
||||
}
|
||||
@@ -32,5 +32,5 @@
|
||||
"frame": "#0A1524"
|
||||
},
|
||||
"build": "ecd52665f9",
|
||||
"updatedAt": "2026-11-18T10:16:41Z"
|
||||
"updatedAt": "2026-11-19T10:20:00Z"
|
||||
}
|
||||
@@ -33,5 +33,5 @@
|
||||
"frame": "#F4F6FB"
|
||||
},
|
||||
"build": "105653737d",
|
||||
"updatedAt": "2026-11-18T10:16:41Z"
|
||||
"updatedAt": "2026-11-19T10:20:00Z"
|
||||
}
|
||||
+29
-29
@@ -1,46 +1,46 @@
|
||||
{
|
||||
"schema": 1,
|
||||
"generated": "2026-11-18T13:05:57Z",
|
||||
"generated": "2026-11-19T10:20:00Z",
|
||||
"repository": "https://git.xhmcl.com/Morris/GC",
|
||||
"branch": "main",
|
||||
"modelDir": "model",
|
||||
"launcher": {
|
||||
"version": "1.1.0",
|
||||
"version": "1.1.1",
|
||||
"revision": "",
|
||||
"packages": {
|
||||
"win-x64": {
|
||||
"path": "dist/win-amd64/GCL-1.1.0-win-amd64.zip",
|
||||
"path": "dist/win-amd64/GCL-1.1.1-win-amd64.zip",
|
||||
"dir": "dist/win-amd64",
|
||||
"name": "GCL-1.1.0-win-amd64.zip",
|
||||
"url": "https://git.xhmcl.com/Morris/GC/releases/download/1.1.0/GCL-1.1.0-win-amd64.zip",
|
||||
"sha256": "adfdca03bd84ad1a831da4925795dd4ee5b9f79f654a7a8208abcb6f3dbc4f3b",
|
||||
"size": 74984771
|
||||
"name": "GCL-1.1.1-win-amd64.zip",
|
||||
"url": "https://git.xhmcl.com/Morris/GC/releases/download/1.1.1/GCL-1.1.1-win-amd64.zip",
|
||||
"sha256": "a03532606121280a1553ea73e56d6f9e8cc6cd9eefaf49f8c62857733199c10f",
|
||||
"size": 74993562
|
||||
},
|
||||
"win-arm64": {
|
||||
"path": "dist/win-arm64/GCL-1.1.0-win-arm64.zip",
|
||||
"path": "dist/win-arm64/GCL-1.1.1-win-arm64.zip",
|
||||
"dir": "dist/win-arm64",
|
||||
"name": "GCL-1.1.0-win-arm64.zip",
|
||||
"url": "https://git.xhmcl.com/Morris/GC/releases/download/1.1.0/GCL-1.1.0-win-arm64.zip",
|
||||
"sha256": "2ef3f657a4ff61d9cc62100daed8d399ad0635f120c5f38589a4efd3a8e76d9a",
|
||||
"size": 72527477
|
||||
"name": "GCL-1.1.1-win-arm64.zip",
|
||||
"url": "https://git.xhmcl.com/Morris/GC/releases/download/1.1.1/GCL-1.1.1-win-arm64.zip",
|
||||
"sha256": "0cd3e045fbc2415bb170e545bb720841eb4c5ebc01a98e03105618a2b7bace46",
|
||||
"size": 72535103
|
||||
},
|
||||
"osx-arm64": {
|
||||
"path": "dist/mac-arm64/GCL-1.1.0-mac-arm64.zip",
|
||||
"path": "dist/mac-arm64/GCL-1.1.1-mac-arm64.zip",
|
||||
"dir": "dist/mac-arm64",
|
||||
"name": "GCL-1.1.0-mac-arm64.zip",
|
||||
"url": "https://git.xhmcl.com/Morris/GC/releases/download/1.1.0/GCL-1.1.0-mac-arm64.zip"
|
||||
"name": "GCL-1.1.1-mac-arm64.zip",
|
||||
"url": "https://git.xhmcl.com/Morris/GC/releases/download/1.1.1/GCL-1.1.1-mac-arm64.zip"
|
||||
},
|
||||
"osx-x64": {
|
||||
"path": "dist/mac-x64/GCL-1.1.0-mac-x64.zip",
|
||||
"path": "dist/mac-x64/GCL-1.1.1-mac-x64.zip",
|
||||
"dir": "dist/mac-x64",
|
||||
"name": "GCL-1.1.0-mac-x64.zip",
|
||||
"url": "https://git.xhmcl.com/Morris/GC/releases/download/1.1.0/GCL-1.1.0-mac-x64.zip"
|
||||
"name": "GCL-1.1.1-mac-x64.zip",
|
||||
"url": "https://git.xhmcl.com/Morris/GC/releases/download/1.1.1/GCL-1.1.1-mac-x64.zip"
|
||||
},
|
||||
"linux-arm64": {
|
||||
"path": "dist/linux-arm64/GCL-1.1.0-linux-arm64.zip",
|
||||
"path": "dist/linux-arm64/GCL-1.1.1-linux-arm64.zip",
|
||||
"dir": "dist/linux-arm64",
|
||||
"name": "GCL-1.1.0-linux-arm64.zip",
|
||||
"url": "https://git.xhmcl.com/Morris/GC/releases/download/1.1.0/GCL-1.1.0-linux-arm64.zip"
|
||||
"name": "GCL-1.1.1-linux-arm64.zip",
|
||||
"url": "https://git.xhmcl.com/Morris/GC/releases/download/1.1.1/GCL-1.1.1-linux-arm64.zip"
|
||||
}
|
||||
}
|
||||
},
|
||||
@@ -49,7 +49,7 @@
|
||||
"id": "contour-map",
|
||||
"version": "1.1",
|
||||
"build": "773ab2161d",
|
||||
"manifestSha256": "f673521f7462324a2a461253ed975c9f89abc4df34b937cad70a2a134623456d",
|
||||
"manifestSha256": "ac3231d55175757b4c477ad6a3c398c041db9511061f0c650d2c10efca881103",
|
||||
"filesSha256": "a6bdf9b4273aabee50c3c94ceab4d0abee15f0df1af90c58bdbb796e0d2d5699",
|
||||
"files": 5,
|
||||
"dir": "model/contour-map"
|
||||
@@ -58,7 +58,7 @@
|
||||
"id": "earth-geography",
|
||||
"version": "1.9",
|
||||
"build": "cc68b8863b",
|
||||
"manifestSha256": "89e3afa8843fb080c81e062967790cddba54665b182e4a0819c8c1fd737d5189",
|
||||
"manifestSha256": "f69ceb758c643701480af441da26dfa64e190c9e583073deba211bac3e2a6e1a",
|
||||
"filesSha256": "c018ba481831e23d3183a38ac47251f19754c7464baa5d85b47cea7a49fcfa95",
|
||||
"files": 11,
|
||||
"dir": "model/earth-geography"
|
||||
@@ -67,7 +67,7 @@
|
||||
"id": "earth-revolution",
|
||||
"version": "1.7",
|
||||
"build": "53b7a0fbc3",
|
||||
"manifestSha256": "31f20837131573957101f7fba9a653c8785f6dbda5fd678862148a9f7f87e841",
|
||||
"manifestSha256": "ab257669cd2bc57289d7e86b361064034d6040e85603b65069a93aec8d457b0b",
|
||||
"filesSha256": "4cd45b0324a77574a0da3a939c2a6faebc785c5a24cb50136d62a78a6ea2e9b1",
|
||||
"files": 7,
|
||||
"dir": "model/earth-revolution"
|
||||
@@ -76,7 +76,7 @@
|
||||
"id": "earth-rotation",
|
||||
"version": "1.7",
|
||||
"build": "ecd52665f9",
|
||||
"manifestSha256": "caa89497a70b29db87e67d35cd7d3e27a18306646209b2178cfb71b73cfca8ba",
|
||||
"manifestSha256": "d463d85e08fd7f0525f8e08a5e9ec49c0005b3d8ca97a7f9497e95bdbb0697cb",
|
||||
"filesSha256": "594b005a6a9f36cd0b5d4e4a7a0b1ab42d53c8032832545b71c3915493d56c8e",
|
||||
"files": 7,
|
||||
"dir": "model/earth-rotation"
|
||||
@@ -85,7 +85,7 @@
|
||||
"id": "scale-calculator",
|
||||
"version": "1.6",
|
||||
"build": "105653737d",
|
||||
"manifestSha256": "952d2529f3b62f6703456ae9bc6f867edac148b7ec9963444c426d26aa35208d",
|
||||
"manifestSha256": "2ac714eafb9acb4e4f11567b61848441de0f65ac41eb4260bc2d868c9500f56d",
|
||||
"filesSha256": "732dd26406e0f1e836970499d7ea644def332ce909d7f8aa0a403bbe7337e604",
|
||||
"files": 6,
|
||||
"dir": "model/scale-calculator"
|
||||
@@ -94,8 +94,8 @@
|
||||
"signature": {
|
||||
"alg": "ECDSA-P256-SHA256",
|
||||
"keyId": "gc-2026-12",
|
||||
"value": "A/A7GQ2muXgqhtG+HVKkAvs0cAX90TXDgXOtxWCr8VTQW10FPUUroUSdmp4x5FUT7KNnrs1wIoz4/YSJspv9oQ==",
|
||||
"contentSha256": "84488b35a9f45f44c3b6c21c400f6c0d0a26b5f0f045a696afd889cf5af6f2f1",
|
||||
"signedAt": "2026-11-18T14:46:36Z"
|
||||
"value": "U6j86/9PIUe5ZIqLRUlSIFf6EhODc7Dar1KvL7MecYujzNJ+ZnRrUg7aUT1rvktVwz4nyRacf9RYM2JQFb+qKw==",
|
||||
"contentSha256": "585f22236fa1a50d4e99581c676b8ad694c5e352b12fe1bfed30c342b1f38690",
|
||||
"signedAt": "2026-11-19T10:21:32Z"
|
||||
}
|
||||
}
|
||||
+29
-29
@@ -1,46 +1,46 @@
|
||||
{
|
||||
"schema": 1,
|
||||
"generated": "2026-11-18T13:05:57Z",
|
||||
"generated": "2026-11-19T10:20:00Z",
|
||||
"repository": "https://git.xhmcl.com/Morris/GC",
|
||||
"branch": "main",
|
||||
"modelDir": "model",
|
||||
"launcher": {
|
||||
"version": "1.1.0",
|
||||
"version": "1.1.1",
|
||||
"revision": "",
|
||||
"packages": {
|
||||
"win-x64": {
|
||||
"path": "dist/win-amd64/GCL-1.1.0-win-amd64.zip",
|
||||
"path": "dist/win-amd64/GCL-1.1.1-win-amd64.zip",
|
||||
"dir": "dist/win-amd64",
|
||||
"name": "GCL-1.1.0-win-amd64.zip",
|
||||
"url": "https://git.xhmcl.com/Morris/GC/releases/download/1.1.0/GCL-1.1.0-win-amd64.zip",
|
||||
"sha256": "adfdca03bd84ad1a831da4925795dd4ee5b9f79f654a7a8208abcb6f3dbc4f3b",
|
||||
"size": 74984771
|
||||
"name": "GCL-1.1.1-win-amd64.zip",
|
||||
"url": "https://git.xhmcl.com/Morris/GC/releases/download/1.1.1/GCL-1.1.1-win-amd64.zip",
|
||||
"sha256": "a03532606121280a1553ea73e56d6f9e8cc6cd9eefaf49f8c62857733199c10f",
|
||||
"size": 74993562
|
||||
},
|
||||
"win-arm64": {
|
||||
"path": "dist/win-arm64/GCL-1.1.0-win-arm64.zip",
|
||||
"path": "dist/win-arm64/GCL-1.1.1-win-arm64.zip",
|
||||
"dir": "dist/win-arm64",
|
||||
"name": "GCL-1.1.0-win-arm64.zip",
|
||||
"url": "https://git.xhmcl.com/Morris/GC/releases/download/1.1.0/GCL-1.1.0-win-arm64.zip",
|
||||
"sha256": "2ef3f657a4ff61d9cc62100daed8d399ad0635f120c5f38589a4efd3a8e76d9a",
|
||||
"size": 72527477
|
||||
"name": "GCL-1.1.1-win-arm64.zip",
|
||||
"url": "https://git.xhmcl.com/Morris/GC/releases/download/1.1.1/GCL-1.1.1-win-arm64.zip",
|
||||
"sha256": "0cd3e045fbc2415bb170e545bb720841eb4c5ebc01a98e03105618a2b7bace46",
|
||||
"size": 72535103
|
||||
},
|
||||
"osx-arm64": {
|
||||
"path": "dist/mac-arm64/GCL-1.1.0-mac-arm64.zip",
|
||||
"path": "dist/mac-arm64/GCL-1.1.1-mac-arm64.zip",
|
||||
"dir": "dist/mac-arm64",
|
||||
"name": "GCL-1.1.0-mac-arm64.zip",
|
||||
"url": "https://git.xhmcl.com/Morris/GC/releases/download/1.1.0/GCL-1.1.0-mac-arm64.zip"
|
||||
"name": "GCL-1.1.1-mac-arm64.zip",
|
||||
"url": "https://git.xhmcl.com/Morris/GC/releases/download/1.1.1/GCL-1.1.1-mac-arm64.zip"
|
||||
},
|
||||
"osx-x64": {
|
||||
"path": "dist/mac-x64/GCL-1.1.0-mac-x64.zip",
|
||||
"path": "dist/mac-x64/GCL-1.1.1-mac-x64.zip",
|
||||
"dir": "dist/mac-x64",
|
||||
"name": "GCL-1.1.0-mac-x64.zip",
|
||||
"url": "https://git.xhmcl.com/Morris/GC/releases/download/1.1.0/GCL-1.1.0-mac-x64.zip"
|
||||
"name": "GCL-1.1.1-mac-x64.zip",
|
||||
"url": "https://git.xhmcl.com/Morris/GC/releases/download/1.1.1/GCL-1.1.1-mac-x64.zip"
|
||||
},
|
||||
"linux-arm64": {
|
||||
"path": "dist/linux-arm64/GCL-1.1.0-linux-arm64.zip",
|
||||
"path": "dist/linux-arm64/GCL-1.1.1-linux-arm64.zip",
|
||||
"dir": "dist/linux-arm64",
|
||||
"name": "GCL-1.1.0-linux-arm64.zip",
|
||||
"url": "https://git.xhmcl.com/Morris/GC/releases/download/1.1.0/GCL-1.1.0-linux-arm64.zip"
|
||||
"name": "GCL-1.1.1-linux-arm64.zip",
|
||||
"url": "https://git.xhmcl.com/Morris/GC/releases/download/1.1.1/GCL-1.1.1-linux-arm64.zip"
|
||||
}
|
||||
}
|
||||
},
|
||||
@@ -49,7 +49,7 @@
|
||||
"id": "contour-map",
|
||||
"version": "1.1",
|
||||
"build": "773ab2161d",
|
||||
"manifestSha256": "f673521f7462324a2a461253ed975c9f89abc4df34b937cad70a2a134623456d",
|
||||
"manifestSha256": "ac3231d55175757b4c477ad6a3c398c041db9511061f0c650d2c10efca881103",
|
||||
"filesSha256": "a6bdf9b4273aabee50c3c94ceab4d0abee15f0df1af90c58bdbb796e0d2d5699",
|
||||
"files": 5,
|
||||
"dir": "model/contour-map"
|
||||
@@ -58,7 +58,7 @@
|
||||
"id": "earth-geography",
|
||||
"version": "1.9",
|
||||
"build": "cc68b8863b",
|
||||
"manifestSha256": "89e3afa8843fb080c81e062967790cddba54665b182e4a0819c8c1fd737d5189",
|
||||
"manifestSha256": "f69ceb758c643701480af441da26dfa64e190c9e583073deba211bac3e2a6e1a",
|
||||
"filesSha256": "c018ba481831e23d3183a38ac47251f19754c7464baa5d85b47cea7a49fcfa95",
|
||||
"files": 11,
|
||||
"dir": "model/earth-geography"
|
||||
@@ -67,7 +67,7 @@
|
||||
"id": "earth-revolution",
|
||||
"version": "1.7",
|
||||
"build": "53b7a0fbc3",
|
||||
"manifestSha256": "31f20837131573957101f7fba9a653c8785f6dbda5fd678862148a9f7f87e841",
|
||||
"manifestSha256": "ab257669cd2bc57289d7e86b361064034d6040e85603b65069a93aec8d457b0b",
|
||||
"filesSha256": "4cd45b0324a77574a0da3a939c2a6faebc785c5a24cb50136d62a78a6ea2e9b1",
|
||||
"files": 7,
|
||||
"dir": "model/earth-revolution"
|
||||
@@ -76,7 +76,7 @@
|
||||
"id": "earth-rotation",
|
||||
"version": "1.7",
|
||||
"build": "ecd52665f9",
|
||||
"manifestSha256": "caa89497a70b29db87e67d35cd7d3e27a18306646209b2178cfb71b73cfca8ba",
|
||||
"manifestSha256": "d463d85e08fd7f0525f8e08a5e9ec49c0005b3d8ca97a7f9497e95bdbb0697cb",
|
||||
"filesSha256": "594b005a6a9f36cd0b5d4e4a7a0b1ab42d53c8032832545b71c3915493d56c8e",
|
||||
"files": 7,
|
||||
"dir": "model/earth-rotation"
|
||||
@@ -85,7 +85,7 @@
|
||||
"id": "scale-calculator",
|
||||
"version": "1.6",
|
||||
"build": "105653737d",
|
||||
"manifestSha256": "952d2529f3b62f6703456ae9bc6f867edac148b7ec9963444c426d26aa35208d",
|
||||
"manifestSha256": "2ac714eafb9acb4e4f11567b61848441de0f65ac41eb4260bc2d868c9500f56d",
|
||||
"filesSha256": "732dd26406e0f1e836970499d7ea644def332ce909d7f8aa0a403bbe7337e604",
|
||||
"files": 6,
|
||||
"dir": "model/scale-calculator"
|
||||
@@ -94,8 +94,8 @@
|
||||
"signature": {
|
||||
"alg": "ECDSA-P256-SHA256",
|
||||
"keyId": "gc-2026-12",
|
||||
"value": "A/A7GQ2muXgqhtG+HVKkAvs0cAX90TXDgXOtxWCr8VTQW10FPUUroUSdmp4x5FUT7KNnrs1wIoz4/YSJspv9oQ==",
|
||||
"contentSha256": "84488b35a9f45f44c3b6c21c400f6c0d0a26b5f0f045a696afd889cf5af6f2f1",
|
||||
"signedAt": "2026-11-18T14:46:36Z"
|
||||
"value": "U6j86/9PIUe5ZIqLRUlSIFf6EhODc7Dar1KvL7MecYujzNJ+ZnRrUg7aUT1rvktVwz4nyRacf9RYM2JQFb+qKw==",
|
||||
"contentSha256": "585f22236fa1a50d4e99581c676b8ad694c5e352b12fe1bfed30c342b1f38690",
|
||||
"signedAt": "2026-11-19T10:21:32Z"
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user