Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2f3a8682c9 | ||
|
|
791db4fe12 | ||
|
|
c95dfaf9f3 | ||
|
|
0ddee422ab | ||
|
|
a1211521eb | ||
|
|
512b1814e1 | ||
|
|
663efa5c75 | ||
|
|
8dcbd6f9d7 | ||
|
|
1cca045f08 | ||
|
|
4f5beb5109 | ||
|
|
6d4d098681 | ||
|
|
9293fee3bf | ||
|
|
f1787dff9d | ||
|
|
b6dc5649d6 | ||
|
|
4b5aa7799f | ||
|
|
0f19921dd4 | ||
|
|
0e86c17056 | ||
|
|
7de92a25f5 | ||
|
|
874c97ee27 | ||
|
|
936aec8185 | ||
|
|
f69a8fbb7f | ||
|
|
5e0b46b3f3 | ||
|
|
22e1b8fbb9 | ||
|
|
e9c8952481 | ||
|
|
1ee49b8966 |
No files matched your search
@@ -1,20 +1,25 @@
|
||||
# 运行数据目录(settings/model/cache/update),绝不入库
|
||||
.GC/
|
||||
|
||||
# 签名私钥:绝对不入库(公钥写在 GC/src/Security/SignatureKeyring.cs 里)
|
||||
.signing/
|
||||
|
||||
# .NET 构建中间产物(已跟踪的历史文件不动,只防新增)
|
||||
bin/
|
||||
obj/
|
||||
dist/
|
||||
build/
|
||||
.GC/
|
||||
*.user
|
||||
.DS_Store
|
||||
.vs/
|
||||
|
||||
.venv/
|
||||
venv/
|
||||
env/
|
||||
.idea/
|
||||
.vscode/
|
||||
.DS_Store
|
||||
__pycache__/
|
||||
*.pyc
|
||||
*.pyo
|
||||
*.log
|
||||
node_modules/
|
||||
dist/
|
||||
build/
|
||||
.pytest_cache/
|
||||
.mypy_cache/
|
||||
@@ -1,40 +0,0 @@
|
||||
# 2026-11-07
|
||||
|
||||
## Earth Model Studio(新建项目)
|
||||
- 用户要求:C#/.NET8(可切10),多目录结构(曾要求 gradle 命名,后明确改为标准 .NET 命名,勿再用 gradle 字样)
|
||||
- 结构:src/main/dotnet + src/test/dotnet + src/main/resources + model/ + examples/ + dist/ + Directory.Build.props + build.sh/build.ps1
|
||||
- 三平台一次性编译:`./build.sh publish` → dist/{mac-arm64(.app),win-x64,win-arm64},自包含单文件 + 内置 model/ + examples/
|
||||
- 技术栈:Avalonia 11.3.9 + CommunityToolkit.Mvvm 8.2.2(本地 NuGet 已缓存);纯 CPU 球面像素渲染(SphereRaster + CelestialView)
|
||||
- 模型格式:model/<id>/<id>.json + <id>.model/scene.json + land.json;模型源=git 仓库根的 model/ 目录(支持 github/gitlab/gitee zip 归档、git clone、本地目录)
|
||||
- 内置模型:earth-rotation(自转)、earth-revolution(公转),land.json 手绘大陆轮廓已校验
|
||||
- 校验:src/test/dotnet 用 Avalonia.Headless 渲染截图到 build/screenshots(页面+场景全通过,HUD 重叠已修)
|
||||
- 已知小问题:RadialGradientBrush.Radius 过时警告;发布后 mac 单文件在沙箱内需 DOTNET_BUNDLE_EXTRACT_BASE_DIR 可写
|
||||
|
||||
## 修改(14:10 之后)
|
||||
- 模型启动改为独立窗口:新增 Views/PlayerWindow.axaml(.cs),MainViewModel 只抛 PlayerRequested 事件,MainWindow 负责 Show(owner) 并维护 PlayerWindows 列表;PlayerViewModel 去掉 MainViewModel 依赖,改 CloseRequested + IDisposable;Esc/空格/F11 快捷键
|
||||
- 分层:src=启动器(无模型数据、无预置模型源),model/=模型数据。移除 examples/,SettingsService 不再种内置源,AppPaths 去掉 ExamplesRoot 并新增 EMS_MODELS
|
||||
- build.sh/build.ps1:publish 只建空 model/(仅 README),新增 pack-models → dist/models-1.0.0.zip
|
||||
- model/README.md 写清模型格式规范
|
||||
- 验证:离屏截图 page-player.png / page-main-while-playing.png,双窗口计数 2→关一个→1→0;三平台重新发布 + 模型 zip
|
||||
|
||||
## 架构重构(14:30 之后):启动器不再渲染,模型自带功能代码
|
||||
- 新分层:src=启动器(扫描/下载/开窗,零渲染);model-sdk=契约;model-src=模型源码+封面工具;model=模型包(数据+dll+preview.png+i18n)
|
||||
- 契约:IModelFactory(ApiVersion/Create) / IModelRuntime.CreateView(IModelContext) / IModelContext(ModelId/ModelDirectory/DataDirectory/Language/MemoryBudgetMb/RequestClose/Log)
|
||||
- 加载:ModelHost + 可收集 AssemblyLoadContext,Sdk/Avalonia 走默认上下文,关窗 Unload
|
||||
- 迁移:CelestialView/SphereRaster/LandMask/SceneDefinition/SceneRuntime → model-src/EarthModels(命名空间 NeoRF.EarthModels);PlayerView+PlayerViewModel 换成模型内 EarthModelView(C# 构建 UI)
|
||||
- 模型包新增清单字段 assembly/type/preview/apiVersion;封面由 model-src/tools/PreviewGen 用模型渲染器生成
|
||||
- 自转模型 views=["rotation"] → 无节气定位/无视图切换;公转 views=["revolution"] → 有节气、封面是公转场景
|
||||
- 构建:./build.sh models 编译模型 dll + 生成封面;pack-models 先编译再打包
|
||||
- 验证:EMS_SELFTEST=1 自检(dev + 发布包 /tmp 部署)两个模型均 OK;离屏截图含插件加载真实窗口
|
||||
|
||||
## 六项改动(15:00–15:35):真实贴图 / 缩放 / 拖动 / 动画 / 代码归位 / 进度条
|
||||
- 目录:删除 model-src,根目录 model-sdk -> model/_sdk;现在根目录只有 src/ 与 model/。模型源码在 model/<id>/src/,共享引擎在 model/_engine/,契约在 model/_sdk/
|
||||
- 清单 assembly 改为各模型自己的 dll:EarthRotationModel.dll / EarthRevolutionModel.dll(工厂仍是 NeoRF.EarthModels.*ModelFactory)
|
||||
- 贴图:PlanetTexture 烘焙 1024×512 等经纬度纹理(海洋深度、沙漠/雨林/针叶林/苔原、极地冰盖、云层模糊、夜间辉光);反照率打包 uint[] Albedo
|
||||
- 性能:地形梯度 SlopeEast/SlopeNorth 预烘焙(去掉每像素 4 次 SampleHeight + 6 次三角函数);海面高光 Pow 改乘法;运动时降分辨率 460 + 按帧耗时自适应 320–460,静止补 820 高清帧。实测公转播放 6ms、自转播放 ~18ms
|
||||
- 交互:滚轮/工具栏 −100%+/⟲ 缩放 0.6–6×(缓动),暂停后拖动旋转地球或沿轨道移动、松手惯性;云层播放/暂停都缓慢漂移
|
||||
- 动画:模型窗口淡入、按钮悬停 BrushTransition、教学面板滑入淡出;启动器页面切换淡入、按钮/卡片悬停过渡、进度条 DoubleTransition 平滑
|
||||
- 进度条:契约新增 IModelRuntime.Prepare(后台)+ IModelContext.ReportProgress;ModelHost.LoadAsync 两阶段;LoadingWindow 显示真实阶段(读场景→烘焙纹理→构建界面)
|
||||
- 打包:pack-models 排除 */bin/* */obj/*,避免把 107MB SkiaSharp native 打进包;模型包 356KB(含源码+dll+封面+i18n)
|
||||
- 验证:离屏截图全部正常;反射校验缩放 1.00→1.25→1.00、暂停拖动=True、交互提示=True;自转无节气;发布包复制到 /tmp 自检两个模型 OK
|
||||
- 产物:dist/mac-arm64 97M、win-x64 88M、win-arm64 94M(model/ 仅 README),dist/models-1.0.0.zip 356K
|
||||
@@ -0,0 +1,29 @@
|
||||
# 2026-11-14
|
||||
|
||||
## GC 启动器安全加固(补完)
|
||||
|
||||
- **GC-SAVEDOG 裁剪发布**:`PublishTrimmed=true` + `TrimMode=full` +
|
||||
`JsonSerializerIsReflectionEnabledByDefault=false`(已写进 csproj 与两套构建脚本)。
|
||||
体积 70MB → 14MB。裁剪后反射式 JSON 会失效,因此新增
|
||||
`GC-SAVEDOG/SavedogJson.cs`(`JsonSerializerContext` 源生成)并通过
|
||||
`Json.TypeInfoProvider` 钩子接进共享的 `GC.Download/GC.Services.Json`。
|
||||
→ 新增 JSON 类型必须登记到 `SavedogJsonContext`,否则只有发布产物会炸。
|
||||
- **构建产物布局改为 `dist/<系统>-<架构>/`**(mac-arm64 / win-amd64 / win-arm64),
|
||||
更新包路径 `dist/<平台>/GC-<版本>-<平台>.zip`;`pack_launcher` 之后调
|
||||
`VersionStamp --launcher-only` 把 `path/dir/name/sha256/size` 写进清单并重新签名。
|
||||
原始 `.app`/`.exe` 移到 `build/trash/`(避免递归删除几百个文件)。
|
||||
- **启动器更新支持「只发产物、不发 Release」**:新增 `GC-DOWNLOAD/LauncherArtifacts.cs`
|
||||
(平台标签/别名、候选目录与文件名推导,构建端 VersionStamp 也链接同一份)。
|
||||
`GitCodeRemote/GiteaRemote/DirectoryRemote.DownloadPackageAsync` 改成
|
||||
多候选尝试:url → 清单 path → `dist/<系统>-<架构>/` 目录扫描 → dist 根目录命名,
|
||||
每个候选都必须匹配已签名清单的 sha256。
|
||||
`GitCodeReleaseRemote` 在「没有 Release」时不再清空 launcher 字段(清单已签名)。
|
||||
- **测试**:`--update-test` 新增两条用例(dist 目录能找到并下载 / dist 目录里哈希不符被拒绝),
|
||||
当前 33 项全部通过。
|
||||
- 触发过的坑:`rm -rf` 大批文件被沙箱批量删除保护拦截 → 构建脚本改用 `mv` 到 `build/trash`。
|
||||
- **收尾验证(19:35–19:37)**:`./build.sh pack-launcher` 24s 完成三平台打包,
|
||||
清单已写入真实 `sha256/size`(win-amd64 44MB / win-arm64 42MB / mac-arm64 8.7MB,
|
||||
osx-x64 与 linux-amd64 无产物故留空,下载端会跳过)。根 `version.json` 与
|
||||
`model/version.json` 字节一致、签名 `gc-2026-11` 校验 Verified。
|
||||
从 mac 包里解出的 GC-SAVEDOG(14MB 裁剪版)实跑 `verify` / `status` 正常;
|
||||
`./build.sh check` 全流程通过。
|
||||
@@ -1,8 +1,9 @@
|
||||
<Project>
|
||||
<!--
|
||||
多目录结构公共属性:
|
||||
src/main/dotnet/<module> 生产代码
|
||||
src/test/dotnet/<module> 测试 / 离屏渲染校验
|
||||
GC-BOOT 启动入口
|
||||
GC/src/ 启动器核心代码
|
||||
GC/src/test/dotnet/<module> 测试 / 离屏渲染校验
|
||||
TargetFramework 可由命令行覆盖:dotnet build -p:TargetFramework=net10.0
|
||||
-->
|
||||
<PropertyGroup Condition="'$(TargetFramework)' == ''">
|
||||
@@ -21,9 +22,9 @@
|
||||
-->
|
||||
<AvaloniaVersion>11.3.9</AvaloniaVersion>
|
||||
<MvvmVersion>8.2.2</MvvmVersion>
|
||||
<Version>1.0.0</Version>
|
||||
<Version>1.0.7</Version>
|
||||
<Company>NeoRF</Company>
|
||||
<Product>Earth Model Studio</Product>
|
||||
<Product>GC</Product>
|
||||
<NeutralLanguage>zh-Hans</NeutralLanguage>
|
||||
</PropertyGroup>
|
||||
</Project>
|
||||
@@ -0,0 +1,25 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<OutputType>WinExe</OutputType>
|
||||
<Nullable>enable</Nullable>
|
||||
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
|
||||
<RootNamespace>GC.Boot</RootNamespace>
|
||||
<AssemblyName>GC</AssemblyName>
|
||||
<ApplicationManifest>app.manifest</ApplicationManifest>
|
||||
<!-- 应用图标(Windows exe / 任务栏) -->
|
||||
<ApplicationIcon>..\GC\src\Assets\icon.ico</ApplicationIcon>
|
||||
<BuiltInComInteropSupport>true</BuiltInComInteropSupport>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" />
|
||||
<PackageReference Include="Avalonia.Desktop" Version="$(AvaloniaVersion)" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\GC\src\GC.Core.csproj" />
|
||||
<ProjectReference Include="..\GC-DOWNLOAD\GC-DOWNLOAD.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -1,20 +1,22 @@
|
||||
using System;
|
||||
using Avalonia;
|
||||
using EarthModelStudio.Services;
|
||||
using GC.Services;
|
||||
using GC.Download;
|
||||
|
||||
namespace EarthModelStudio;
|
||||
namespace GC;
|
||||
|
||||
internal static class Program
|
||||
{
|
||||
[STAThread]
|
||||
public static void Main(string[] args)
|
||||
{
|
||||
DownloadModuleHost.Factory = new DownloadModuleFactory();
|
||||
// 运行目录:可执行文件旁 .GC/(settings.json + model/ + cache/ + update/)
|
||||
var paths = AppPaths.Discover();
|
||||
paths.EnsureCreated();
|
||||
|
||||
// 上次下载的启动器新版,到这次启动才应用:交给独立脚本覆盖文件并重启
|
||||
if (LauncherUpdate.TryApplyPending(paths)) return;
|
||||
// 上次下载的启动器新版,到这次启动才应用
|
||||
if (DownloadModuleHost.Factory.TryApplyPending(paths)) return;
|
||||
|
||||
BuildAvaloniaApp().StartWithClassicDesktopLifetime(args);
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<assembly manifestVersion="1.0" xmlns="urn:schemas-microsoft-com:asm.v1">
|
||||
<assemblyIdentity version="1.0.0.0" name="EarthModelStudio.Desktop" />
|
||||
<assemblyIdentity version="1.0.0.0" name="GC.Desktop" />
|
||||
<application xmlns="urn:schemas-microsoft-com:asm.v3">
|
||||
<windowsSettings>
|
||||
<dpiAware xmlns="http://schemas.microsoft.com/SMI/2005/WindowsSettings">true/pm</dpiAware>
|
||||
@@ -5,7 +5,7 @@ using System.Net.Http;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace EarthModelStudio.Services;
|
||||
namespace GC.Services;
|
||||
|
||||
/// <summary>
|
||||
/// 本地目录源:用于离线教学(U 盘 / 共享盘里的仓库副本)与自动化测试。
|
||||
@@ -15,6 +15,8 @@ public sealed class DirectoryRemote : IModelRemote
|
||||
{
|
||||
private readonly string _root;
|
||||
private static readonly HttpClient Http = new() { Timeout = TimeSpan.FromMinutes(5) };
|
||||
private string? _rawManifest;
|
||||
private string _launcherVersion = "";
|
||||
|
||||
public DirectoryRemote(string root) => _root = Path.GetFullPath(root);
|
||||
|
||||
@@ -26,9 +28,20 @@ public sealed class DirectoryRemote : IModelRemote
|
||||
var fallback = SafePath(Path.Combine("model", "version.json"));
|
||||
var file = File.Exists(primary) ? primary : fallback;
|
||||
if (!File.Exists(file)) return Task.FromResult<RepoVersion?>(null);
|
||||
return Task.FromResult(Json.Read<RepoVersion>(file));
|
||||
|
||||
// 离线目录同样验签:U 盘 / 共享盘里的清单也可能是被替换过的
|
||||
var text = File.ReadAllText(file);
|
||||
_rawManifest = text;
|
||||
var version = ManifestLoader.Parse(text, out _);
|
||||
if (version != null && !string.IsNullOrWhiteSpace(version.Launcher.Version))
|
||||
_launcherVersion = version.Launcher.Version.Trim();
|
||||
return Task.FromResult(version);
|
||||
}
|
||||
|
||||
/// <summary>最近一次读到的清单原文(SAVEDOG 二次验签用)。</summary>
|
||||
public Task<string?> GetRawVersionTextAsync(CancellationToken ct)
|
||||
=> Task.FromResult(_rawManifest);
|
||||
|
||||
public Task<IReadOnlyList<RepoEntry>> ListTreeAsync(string rootPath, CancellationToken ct)
|
||||
{
|
||||
var baseDir = SafePath(rootPath ?? "model");
|
||||
@@ -76,11 +89,21 @@ public sealed class DirectoryRemote : IModelRemote
|
||||
|
||||
public async Task<byte[]?> DownloadPackageAsync(RepoPackage package, CancellationToken ct)
|
||||
{
|
||||
if (!string.IsNullOrWhiteSpace(package.Path))
|
||||
// 清单路径 / dist 根目录命名:按仓库内相对路径直接找
|
||||
foreach (var rel in LauncherArtifacts.CandidateFiles(
|
||||
package.Rid, package.Dir, package.Path, package.Name, _launcherVersion))
|
||||
{
|
||||
var local = SafePath(package.Path!);
|
||||
if (File.Exists(local)) return await File.ReadAllBytesAsync(local, ct);
|
||||
string full;
|
||||
try { full = SafePath(rel); }
|
||||
catch (InvalidOperationException) { continue; }
|
||||
if (File.Exists(full)) return await File.ReadAllBytesAsync(full, ct);
|
||||
}
|
||||
|
||||
// dist/<系统>-<架构>/ 里放着的编译产物(与远端同一套查找规则):
|
||||
// 本地源同样要能跑通「只发产物、不发 Release」的更新方式。
|
||||
var fromDist = FindInDist(package);
|
||||
if (fromDist != null) return await File.ReadAllBytesAsync(fromDist, ct);
|
||||
|
||||
var url = package.Url;
|
||||
if (string.IsNullOrWhiteSpace(url)) return null;
|
||||
// 离线 U 盘源与 ./build.sh update-test 都会用本地 zip 路径,必须保持兼容。
|
||||
@@ -93,6 +116,27 @@ public sealed class DirectoryRemote : IModelRemote
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>在 dist/<系统>-<架构>/ 里找这个平台的启动器包;找不到返回 null。</summary>
|
||||
private string? FindInDist(RepoPackage package)
|
||||
{
|
||||
foreach (var dir in LauncherArtifacts.CandidateDirs(package.Rid, package.Dir))
|
||||
{
|
||||
string full;
|
||||
try { full = SafePath(dir); }
|
||||
catch (InvalidOperationException) { continue; }
|
||||
if (!Directory.Exists(full)) continue;
|
||||
|
||||
var zips = Directory.GetFiles(full, "*.zip");
|
||||
if (zips.Length == 0) continue;
|
||||
|
||||
foreach (var zip in zips)
|
||||
if (LauncherArtifacts.LooksLikePackage(Path.GetFileName(zip), _launcherVersion, package.Rid))
|
||||
return zip;
|
||||
if (zips.Length == 1) return zips[0];
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private string SafePath(string relative)
|
||||
{
|
||||
var full = Path.GetFullPath(Path.Combine(_root, relative));
|
||||
@@ -5,21 +5,12 @@ using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
using EarthModelStudio.Models;
|
||||
using GC.Models;
|
||||
|
||||
namespace EarthModelStudio.Services;
|
||||
|
||||
public enum DownloadState
|
||||
{
|
||||
Queued,
|
||||
Running,
|
||||
Completed,
|
||||
Failed,
|
||||
Canceled
|
||||
}
|
||||
namespace GC.Services;
|
||||
|
||||
/// <summary>一条下载任务(进入后台列表后一直保留,直到用户清除)。</summary>
|
||||
public sealed partial class DownloadJob : ObservableObject
|
||||
public sealed partial class DownloadJob : ObservableObject, IDownloadJob
|
||||
{
|
||||
public RemoteModel Model { get; }
|
||||
public string Id => Model.Id;
|
||||
@@ -66,13 +57,13 @@ public sealed partial class DownloadJob : ObservableObject
|
||||
}
|
||||
|
||||
/// <summary>下载中心:最多 2 个并发,任务在「后台列表」里折叠展示。</summary>
|
||||
public sealed class DownloadCenter
|
||||
public sealed class DownloadCenter : IDownloadCenter
|
||||
{
|
||||
private readonly ModelRepository _repository;
|
||||
private readonly AppPaths _paths;
|
||||
private readonly SemaphoreSlim _slots = new(2);
|
||||
|
||||
public ObservableCollection<DownloadJob> Jobs { get; } = new();
|
||||
public ObservableCollection<IDownloadJob> Jobs { get; } = new();
|
||||
public event Action? Installed;
|
||||
|
||||
public DownloadCenter(AppPaths paths, ModelRepository repository)
|
||||
@@ -81,7 +72,7 @@ public sealed class DownloadCenter
|
||||
_repository = repository;
|
||||
}
|
||||
|
||||
public DownloadJob Enqueue(RemoteModel model)
|
||||
public IDownloadJob Enqueue(RemoteModel model)
|
||||
{
|
||||
var running = Jobs.FirstOrDefault(j => j.Id.Equals(model.Id, StringComparison.OrdinalIgnoreCase) && j.IsActive);
|
||||
if (running != null) return running;
|
||||
@@ -92,7 +83,7 @@ public sealed class DownloadCenter
|
||||
return job;
|
||||
}
|
||||
|
||||
private async Task RunAsync(DownloadJob job)
|
||||
private async Task RunAsync(IDownloadJob job)
|
||||
{
|
||||
// 在 UI 线程构造,回调自动回到 UI 线程
|
||||
var progress = new Progress<(long Done, long Total)>(p =>
|
||||
@@ -135,20 +126,20 @@ public sealed class DownloadCenter
|
||||
}
|
||||
}
|
||||
|
||||
public void Cancel(DownloadJob job)
|
||||
public void Cancel(IDownloadJob job)
|
||||
{
|
||||
try { job.Cts.Cancel(); } catch { }
|
||||
if (job.State == DownloadState.Queued) job.State = DownloadState.Canceled;
|
||||
}
|
||||
|
||||
public void Retry(DownloadJob job)
|
||||
public void Retry(IDownloadJob job)
|
||||
{
|
||||
if (job.IsActive) return;
|
||||
Jobs.Remove(job);
|
||||
Enqueue(job.Model);
|
||||
}
|
||||
|
||||
public void Remove(DownloadJob job)
|
||||
public void Remove(IDownloadJob job)
|
||||
{
|
||||
Cancel(job);
|
||||
Jobs.Remove(job);
|
||||
@@ -0,0 +1,50 @@
|
||||
using System;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using GC.Models;
|
||||
using GC.Services;
|
||||
|
||||
namespace GC.Download;
|
||||
|
||||
public sealed class DownloadModuleFactory : IDownloadModuleFactory
|
||||
{
|
||||
public IDownloadModule Create(AppPaths paths, SettingsService settings, ModelRepository models) =>
|
||||
new DownloadModule(paths, settings, models);
|
||||
|
||||
public bool TryApplyPending(AppPaths paths) => LauncherUpdater.TryApplyPending(paths);
|
||||
}
|
||||
|
||||
internal sealed class DownloadModule : IDownloadModule
|
||||
{
|
||||
public IDownloadCenter Downloads { get; }
|
||||
public IModelSourceClient Sources { get; }
|
||||
public IUpdateService Updates { get; }
|
||||
public ISourceSelector Selector { get; }
|
||||
public ILauncherUpdateService LauncherUpdates { get; }
|
||||
|
||||
public DownloadModule(AppPaths paths, SettingsService settings, ModelRepository models)
|
||||
{
|
||||
Sources = new ModelSourceClient(paths);
|
||||
Downloads = new DownloadCenter(paths, models);
|
||||
Selector = new SourceSelector();
|
||||
Updates = new UpdateService(paths, settings, UpdateService.CreateRemote(settings.Current));
|
||||
LauncherUpdates = new LauncherUpdateService();
|
||||
}
|
||||
|
||||
public IModelRemote CreateRemote(SourcePreset preset) => SourceSelector.CreateRemote(preset);
|
||||
}
|
||||
|
||||
internal sealed class LauncherUpdateService : ILauncherUpdateService
|
||||
{
|
||||
public Task<string?> CheckAsync(IModelRemote remote, CancellationToken ct = default) =>
|
||||
LauncherUpdater.CheckAsync(remote, ct);
|
||||
|
||||
public Task<UpdateRunResult> DownloadAsync(AppPaths paths, IModelRemote remote,
|
||||
IProgress<UpdateProgressInfo>? progress = null, CancellationToken ct = default) =>
|
||||
LauncherUpdater.DownloadAsync(paths, remote, progress, ct);
|
||||
|
||||
public bool ScheduleApply(AppPaths paths, string packageName) =>
|
||||
LauncherUpdater.ScheduleApply(paths, packageName);
|
||||
|
||||
public bool TryApplyPending(AppPaths paths) => LauncherUpdater.TryApplyPending(paths);
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<Nullable>enable</Nullable>
|
||||
<RootNamespace>GC.Download</RootNamespace>
|
||||
<AssemblyName>GC.Download</AssemblyName>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="CommunityToolkit.Mvvm" Version="$(MvvmVersion)" />
|
||||
<ProjectReference Include="..\GC\src\GC.Core.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -1,12 +1,11 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Net.Http;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace EarthModelStudio.Services;
|
||||
namespace GC.Services;
|
||||
|
||||
/// <summary>
|
||||
/// 启动器更新走 GitCode Release,模型仍走仓库 contents API 的远端源。
|
||||
@@ -23,18 +22,26 @@ namespace EarthModelStudio.Services;
|
||||
public sealed class GitCodeReleaseRemote : IModelRemote
|
||||
{
|
||||
private readonly GitCodeRemote _content;
|
||||
private readonly HttpClient _http;
|
||||
private readonly string _releasesUrl;
|
||||
private readonly Dictionary<string, (string Url, string? Sha256, long Size)> _assets = new();
|
||||
private readonly Dictionary<string, (string Url, string? Sha256, long Size, string Name)> _assets = new();
|
||||
|
||||
public GitCodeReleaseRemote(string? manifestUrl, string? repository, HttpClient? http = null)
|
||||
// 共享静态 HttpClient:避免每次检查更新都创建新实例导致端口耗尽;
|
||||
// headers 只在一处设置,多个线程并发读取是线程安全的。
|
||||
private static readonly HttpClient Http = CreateHttp();
|
||||
|
||||
private static HttpClient CreateHttp()
|
||||
{
|
||||
var client = new HttpClient { Timeout = TimeSpan.FromSeconds(15) };
|
||||
client.DefaultRequestHeaders.UserAgent.ParseAdd("GC-Updater/1.0");
|
||||
client.DefaultRequestHeaders.Accept.ParseAdd("application/json");
|
||||
return client;
|
||||
}
|
||||
|
||||
public GitCodeReleaseRemote(string? manifestUrl, string? repository)
|
||||
{
|
||||
_content = new GitCodeRemote(manifestUrl, repository);
|
||||
var (owner, repo) = ParseOwnerRepo(repository);
|
||||
_releasesUrl = $"https://api.gitcode.com/api/v5/repos/{owner}/{repo}/releases";
|
||||
_http = http ?? new HttpClient { Timeout = TimeSpan.FromSeconds(15) };
|
||||
_http.DefaultRequestHeaders.UserAgent.ParseAdd("EarthModelStudio-Updater/1.0");
|
||||
_http.DefaultRequestHeaders.Accept.ParseAdd("application/json");
|
||||
DisplayName = (string.IsNullOrWhiteSpace(repository)
|
||||
? GitCodeRemote.DefaultRepository : repository!.TrimEnd('/')) + " (Release)";
|
||||
}
|
||||
@@ -43,43 +50,69 @@ public sealed class GitCodeReleaseRemote : IModelRemote
|
||||
{
|
||||
var raw = string.IsNullOrWhiteSpace(url) ? GitCodeRemote.DefaultRepository : url!.Trim();
|
||||
if (!Uri.TryCreate(raw, UriKind.Absolute, out var uri))
|
||||
return ("2509_92447106", "GC");
|
||||
return ("Morris_1", "GC");
|
||||
var parts = uri.AbsolutePath.Trim('/').Split('/', StringSplitOptions.RemoveEmptyEntries);
|
||||
if (parts.Length < 2) return ("2509_92447106", "GC");
|
||||
if (parts.Length < 2) return ("Morris_1", "GC");
|
||||
var repo = parts[1].EndsWith(".git", StringComparison.OrdinalIgnoreCase)
|
||||
? parts[1][..^4] : parts[1];
|
||||
return (parts[0], repo);
|
||||
}
|
||||
|
||||
public string DisplayName { get; }
|
||||
public string SourceId => SourcePreset.Detect(_content.DisplayName).Id;
|
||||
|
||||
/// <summary>
|
||||
/// 模型部分照旧读仓库 version.json;成功拿到 Release 时,用 tag/附件覆盖启动器字段。
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
/// 只认 Release:拿不到任何 Release 就返回 null,由上层去问另一个源。
|
||||
/// 仓库里的 version.json 只用来补全「模型清单」与平台包兜底地址,
|
||||
/// 不再用它充当版本号来源。
|
||||
/// </summary>
|
||||
public async Task<RepoVersion?> GetVersionAsync(CancellationToken ct)
|
||||
{
|
||||
var version = await _content.GetVersionAsync(ct);
|
||||
|
||||
bool gotRelease;
|
||||
try
|
||||
{
|
||||
await ApplyReleaseAsync(version, ct);
|
||||
gotRelease = await ApplyReleaseAsync(version, ct);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
// 没有 Release / 断网 / 格式不符:回退到 version.json,不影响模型更新
|
||||
Console.Error.WriteLine($"读取 Release 失败,回退仓库清单: {ex.Message}");
|
||||
Console.Error.WriteLine($"[gitcode] 读取 Release 失败: {ex.Message}");
|
||||
gotRelease = false;
|
||||
}
|
||||
|
||||
if (!gotRelease)
|
||||
{
|
||||
// 没有 Release ≠ 不能更新:清单已签名,且每个平台包都写了 sha256,
|
||||
// 走「仓库 dist/<系统>-<架构>/ 里的编译产物」同样可信。
|
||||
// 这里保留清单里的 launcher 版本与包信息,让下载端去 dist 目录找包。
|
||||
var v = (version?.Launcher.Version ?? "").Trim();
|
||||
var n = version?.Launcher.Packages.Count ?? 0;
|
||||
if (v.Length == 0 || n == 0)
|
||||
{
|
||||
Console.WriteLine($"[gitcode] {DisplayName}: 没有 Release,清单里也没有启动器包");
|
||||
}
|
||||
else
|
||||
{
|
||||
Console.WriteLine(
|
||||
$"[gitcode] {DisplayName}: 没有 Release,改用清单声明的 v{v}({n} 个平台包,去 dist/ 找产物)");
|
||||
}
|
||||
}
|
||||
return version;
|
||||
}
|
||||
|
||||
private async Task ApplyReleaseAsync(RepoVersion? version, CancellationToken ct)
|
||||
private async Task<bool> ApplyReleaseAsync(RepoVersion? version, CancellationToken ct)
|
||||
{
|
||||
if (version == null) return;
|
||||
if (version == null) return false;
|
||||
|
||||
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(ct);
|
||||
timeout.CancelAfter(TimeSpan.FromSeconds(12));
|
||||
var text = await _http.GetStringAsync(_releasesUrl, timeout.Token);
|
||||
var text = await Http.GetStringAsync(_releasesUrl, timeout.Token);
|
||||
var trimmed = text.TrimStart();
|
||||
if (trimmed.Length == 0 || trimmed[0] != '[') return; // 可能是错误页/对象
|
||||
if (trimmed.Length == 0 || trimmed[0] != '[') return false; // 可能是错误页/对象
|
||||
|
||||
using var doc = JsonDocument.Parse(text);
|
||||
ReleaseInfo? latest = null;
|
||||
@@ -90,9 +123,10 @@ public sealed class GitCodeReleaseRemote : IModelRemote
|
||||
// 取版本号最大的一条(API 通常已按时间倒序,这里再兜一层)
|
||||
if (latest == null || CompareVersion(info.Version, latest.Version) > 0) latest = info;
|
||||
}
|
||||
if (latest == null || string.IsNullOrWhiteSpace(latest.Version)) return;
|
||||
if (latest == null || string.IsNullOrWhiteSpace(latest.Version)) return false;
|
||||
|
||||
version.Launcher.Version = latest.Version;
|
||||
_content.SetLauncherVersion(latest.Version);
|
||||
|
||||
_assets.Clear();
|
||||
foreach (var asset in latest.Assets)
|
||||
@@ -101,7 +135,7 @@ public sealed class GitCodeReleaseRemote : IModelRemote
|
||||
if (rid == null || string.IsNullOrWhiteSpace(asset.Url)) continue;
|
||||
// 同名平台取第一个有效附件
|
||||
if (!_assets.ContainsKey(rid))
|
||||
_assets[rid] = (asset.Url, asset.Sha256, asset.Size);
|
||||
_assets[rid] = (asset.Url, asset.Sha256, asset.Size, asset.Name);
|
||||
}
|
||||
|
||||
// 把附件地址写回 packages:有附件就用附件的直链与校验值,
|
||||
@@ -114,9 +148,11 @@ public sealed class GitCodeReleaseRemote : IModelRemote
|
||||
version.Launcher.Packages[rid] = pkg;
|
||||
}
|
||||
pkg.Url = info.Url;
|
||||
pkg.AssetName = info.Name;
|
||||
if (!string.IsNullOrWhiteSpace(info.Sha256)) pkg.Sha256 = info.Sha256;
|
||||
if (info.Size > 0) pkg.Size = info.Size;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private static int CompareVersion(string a, string b)
|
||||
@@ -141,13 +177,17 @@ public sealed class GitCodeReleaseRemote : IModelRemote
|
||||
{
|
||||
foreach (var a in assets.EnumerateArray())
|
||||
{
|
||||
// 跳过 GitCode 自动生成的源码包(type=source),只取真正的发布附件
|
||||
var type = Str(a, "type");
|
||||
if (string.Equals(type, "source", StringComparison.OrdinalIgnoreCase)) continue;
|
||||
info.Assets.Add(new ReleaseAsset
|
||||
{
|
||||
Name = Str(a, "name") ?? Str(a, "file_name") ?? "",
|
||||
BrowserDownloadUrl = Str(a, "browser_download_url"),
|
||||
DownloadUrl = Str(a, "download_url") ?? Str(a, "url"),
|
||||
Size = Num(a, "size"),
|
||||
Sha256 = Str(a, "sha256") ?? Str(a, "digest")
|
||||
Sha256 = Str(a, "sha256") ?? Str(a, "digest"),
|
||||
Type = type
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,451 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Net.Http;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace GC.Services;
|
||||
|
||||
/// <summary>
|
||||
/// gitcode 仓库源。默认地址来自 AppSettings.UpdateRepository
|
||||
/// (https://gitcode.com/Morris_1/GC),可改成任意 gitcode 仓库或
|
||||
/// https://gitcode.com/<owner>/<repo>/tree/<branch>/model 这样的地址。
|
||||
/// 匿名访问 v5 contents API:目录 -> 数组,文件 -> { content: base64 };
|
||||
/// 文件项自带 download_url(raw.gitcode.com/blobs/<sha>/...),可直接下载二进制。
|
||||
/// </summary>
|
||||
public sealed class GitCodeRemote : IModelRemote
|
||||
{
|
||||
public const string DefaultRepository = "https://gitcode.com/Morris_1/GC";
|
||||
|
||||
private readonly HttpClient _http;
|
||||
private readonly string _api;
|
||||
private readonly string _branch;
|
||||
private readonly string _versionUrl;
|
||||
private readonly string? _fallbackUrl;
|
||||
private readonly string _displayName;
|
||||
private string _modelDir = "model";
|
||||
private string? _rawManifest;
|
||||
/// <summary>最近一次读到的启动器版本号,用于推导 dist 目录里的包名。</summary>
|
||||
private string _launcherVersion = "";
|
||||
|
||||
public string DisplayName => _displayName;
|
||||
|
||||
public GitCodeRemote(string? manifestUrl = null, string? repository = null)
|
||||
{
|
||||
var (owner, repo, branch) = ParseRepository(repository);
|
||||
_branch = branch;
|
||||
_api = $"https://api.gitcode.com/api/v5/repos/{owner}/{repo}/contents/";
|
||||
_displayName = string.IsNullOrWhiteSpace(repository)
|
||||
? DefaultRepository : repository!.TrimEnd('/');
|
||||
|
||||
_http = new HttpClient { Timeout = TimeSpan.FromMinutes(2) };
|
||||
_http.DefaultRequestHeaders.UserAgent.ParseAdd("GC-Updater/1.0");
|
||||
_http.DefaultRequestHeaders.Accept.ParseAdd("application/json");
|
||||
|
||||
if (string.IsNullOrWhiteSpace(manifestUrl))
|
||||
{
|
||||
_versionUrl = _api + "version.json?ref=" + _branch;
|
||||
_fallbackUrl = _api + "model/version.json?ref=" + _branch;
|
||||
}
|
||||
else
|
||||
{
|
||||
_versionUrl = manifestUrl!;
|
||||
_fallbackUrl = null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>从仓库 URL 解析 owner / repo / branch,解析失败回退到默认仓库。</summary>
|
||||
private static (string Owner, string Repo, string Branch) ParseRepository(string? url)
|
||||
{
|
||||
var raw = string.IsNullOrWhiteSpace(url) ? DefaultRepository : url!.Trim();
|
||||
if (!Uri.TryCreate(raw, UriKind.Absolute, out var uri))
|
||||
return ("Morris_1", "GC", "main");
|
||||
var parts = uri.AbsolutePath.Trim('/').Split('/', StringSplitOptions.RemoveEmptyEntries);
|
||||
if (parts.Length < 2) return ("Morris_1", "GC", "main");
|
||||
var owner = parts[0];
|
||||
var repo = parts[1].EndsWith(".git", StringComparison.OrdinalIgnoreCase)
|
||||
? parts[1][..^4] : parts[1];
|
||||
var branch = parts.Length >= 4 && parts[2].Equals("tree", StringComparison.OrdinalIgnoreCase)
|
||||
? parts[3] : "main";
|
||||
return (owner, repo, branch);
|
||||
}
|
||||
|
||||
public async Task<RepoVersion?> GetVersionAsync(CancellationToken ct)
|
||||
{
|
||||
RepoVersion? version = await ReadVersionFromAsync(_versionUrl, ct);
|
||||
if (version == null && _fallbackUrl != null)
|
||||
version = await ReadVersionFromAsync(_fallbackUrl, ct);
|
||||
if (version != null && !string.IsNullOrWhiteSpace(version.ModelDir))
|
||||
_modelDir = version.ModelDir.Trim('/');
|
||||
if (version != null && !string.IsNullOrWhiteSpace(version.Launcher.Version))
|
||||
_launcherVersion = version.Launcher.Version.Trim();
|
||||
return version;
|
||||
}
|
||||
|
||||
/// <summary>最近一次读到的清单原文(SAVEDOG 二次验签用)。</summary>
|
||||
public Task<string?> GetRawVersionTextAsync(CancellationToken ct)
|
||||
=> Task.FromResult(_rawManifest);
|
||||
|
||||
/// <summary>
|
||||
/// 由 Release 覆盖版本号后同步一次,保证 dist 目录里的包名推导用的是
|
||||
/// 「真正要装的那个版本」,而不是仓库清单里可能滞后的版本号。
|
||||
/// </summary>
|
||||
internal void SetLauncherVersion(string? version)
|
||||
{
|
||||
if (!string.IsNullOrWhiteSpace(version)) _launcherVersion = version!.Trim();
|
||||
}
|
||||
|
||||
private async Task<RepoVersion?> ReadVersionFromAsync(string url, CancellationToken ct)
|
||||
{
|
||||
string text;
|
||||
try
|
||||
{
|
||||
// 离线 / 网络不通时最多等 10 秒,不能让启动界面一直卡在「检查更新」
|
||||
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(ct);
|
||||
timeout.CancelAfter(TimeSpan.FromSeconds(10));
|
||||
text = await _http.GetStringAsync(url, timeout.Token);
|
||||
}
|
||||
catch (HttpRequestException) { return null; }
|
||||
catch (OperationCanceledException) when (!ct.IsCancellationRequested) { return null; }
|
||||
|
||||
var trimmed = text.TrimStart();
|
||||
if (trimmed.Length == 0 || trimmed[0] != '{') return null;
|
||||
|
||||
try
|
||||
{
|
||||
using var doc = JsonDocument.Parse(text);
|
||||
var payload = text;
|
||||
if (doc.RootElement.TryGetProperty("encoding", out _) &&
|
||||
doc.RootElement.TryGetProperty("content", out var content))
|
||||
{
|
||||
var raw = Convert.FromBase64String(content.GetString() ?? "");
|
||||
payload = Encoding.UTF8.GetString(raw);
|
||||
}
|
||||
if (!payload.TrimStart().StartsWith("{", StringComparison.Ordinal)) return null;
|
||||
|
||||
// 验签与解析一起做:拿到的清单必须能说明「它是不是可信的」
|
||||
var version = ManifestLoader.Parse(payload, out var verification);
|
||||
if (version == null) return null;
|
||||
|
||||
// 404 / 错误页也可能返回一个 JSON 对象,用 generated 确认这确实是版本清单
|
||||
if (string.IsNullOrWhiteSpace(version.Generated)) return null;
|
||||
|
||||
if (verification.Trust == ManifestTrust.Invalid)
|
||||
Console.Error.WriteLine($"[gitcode] 清单验签失败: {verification.Error}");
|
||||
|
||||
if (version != null && !string.IsNullOrWhiteSpace(version.Generated))
|
||||
_rawManifest = payload;
|
||||
return version;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.Error.WriteLine($"版本清单解析失败 {url}: {ex.Message}");
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 递归列出目录树(含目录项与文件项)。
|
||||
/// 每个子目录一次 HTTP 请求,因此并行展开同一层的所有目录,
|
||||
/// 否则 3 个模型、十几个目录串行请求会非常慢。
|
||||
/// </summary>
|
||||
public async Task<IReadOnlyList<RepoEntry>> ListTreeAsync(string rootPath, CancellationToken ct)
|
||||
{
|
||||
var result = new List<RepoEntry>();
|
||||
var bag = new System.Collections.Concurrent.ConcurrentBag<RepoEntry>();
|
||||
var repoPath = (rootPath ?? _modelDir).Trim('/');
|
||||
await WalkParallelAsync(repoPath, "", 0, bag, ct);
|
||||
|
||||
// 稳定排序:目录在前、按路径字典序,保证调用方拿到确定顺序
|
||||
result = bag.OrderBy(e => e.IsDirectory ? 0 : 1)
|
||||
.ThenBy(e => e.RelativePath, StringComparer.Ordinal)
|
||||
.ToList();
|
||||
return result;
|
||||
}
|
||||
|
||||
private async Task WalkParallelAsync(string repoPath, string relative, int depth,
|
||||
System.Collections.Concurrent.ConcurrentBag<RepoEntry> bag, CancellationToken ct)
|
||||
{
|
||||
if (depth > 8) return;
|
||||
var url = _api + repoPath + "?ref=" + _branch;
|
||||
string text;
|
||||
try { text = await GetWithRetryAsync(url, ct); }
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.Error.WriteLine($"列目录失败 {repoPath}: {ex.Message}");
|
||||
return;
|
||||
}
|
||||
if (!text.TrimStart().StartsWith("[", StringComparison.Ordinal)) return;
|
||||
|
||||
var subDirs = new List<(string Path, string Relative)>();
|
||||
|
||||
using (var doc = JsonDocument.Parse(text))
|
||||
{
|
||||
foreach (var item in doc.RootElement.EnumerateArray())
|
||||
{
|
||||
ct.ThrowIfCancellationRequested();
|
||||
var name = Str(item, "name");
|
||||
if (string.IsNullOrEmpty(name) || name.StartsWith('.')) continue;
|
||||
// 这些目录不是模型运行数据,跳过可显著减少请求
|
||||
// (模型目录里常见的 src/ bin/ obj/ 是源码与构建产物)
|
||||
if (IsIgnoredDir(name)) continue;
|
||||
var path = Str(item, "path");
|
||||
if (string.IsNullOrWhiteSpace(path)) path = repoPath + "/" + name;
|
||||
var isDir = Str(item, "type") == "dir";
|
||||
var childRelative = relative.Length == 0 ? name : relative + "/" + name;
|
||||
|
||||
bag.Add(new RepoEntry
|
||||
{
|
||||
Name = name,
|
||||
Path = path!,
|
||||
RelativePath = childRelative,
|
||||
IsDirectory = isDir,
|
||||
DownloadUrl = NullableStr(item, "download_url"),
|
||||
Sha = NullableStr(item, "sha"),
|
||||
Size = Num(item, "size")
|
||||
});
|
||||
|
||||
if (isDir) subDirs.Add((path!, childRelative));
|
||||
}
|
||||
}
|
||||
|
||||
if (subDirs.Count == 0) return;
|
||||
|
||||
// 同层并行;并发保持很低——GitCode API 对突发请求会返回 429
|
||||
using var gate = new SemaphoreSlim(2);
|
||||
var tasks = subDirs.Select(async d =>
|
||||
{
|
||||
await gate.WaitAsync(ct);
|
||||
try { await WalkParallelAsync(d.Path, d.Relative, depth + 1, bag, ct); }
|
||||
finally { gate.Release(); }
|
||||
});
|
||||
await Task.WhenAll(tasks);
|
||||
}
|
||||
|
||||
private async Task WalkAsync(string repoPath, string relative, int depth,
|
||||
List<RepoEntry> result, CancellationToken ct)
|
||||
{
|
||||
if (depth > 8) return;
|
||||
var url = _api + repoPath + "?ref=" + _branch;
|
||||
var text = await _http.GetStringAsync(url, ct);
|
||||
if (!text.TrimStart().StartsWith("[", StringComparison.Ordinal)) return;
|
||||
|
||||
using var doc = JsonDocument.Parse(text);
|
||||
foreach (var item in doc.RootElement.EnumerateArray())
|
||||
{
|
||||
ct.ThrowIfCancellationRequested();
|
||||
var name = Str(item, "name");
|
||||
if (string.IsNullOrEmpty(name) || name.StartsWith('.')) continue;
|
||||
var path = Str(item, "path");
|
||||
if (string.IsNullOrWhiteSpace(path)) path = repoPath + "/" + name;
|
||||
var isDir = Str(item, "type") == "dir";
|
||||
var childRelative = relative.Length == 0 ? name : relative + "/" + name;
|
||||
|
||||
result.Add(new RepoEntry
|
||||
{
|
||||
Name = name,
|
||||
Path = path!,
|
||||
RelativePath = childRelative,
|
||||
IsDirectory = isDir,
|
||||
DownloadUrl = NullableStr(item, "download_url"),
|
||||
Sha = NullableStr(item, "sha"),
|
||||
Size = Num(item, "size")
|
||||
});
|
||||
|
||||
if (isDir) await WalkAsync(path!, childRelative, depth + 1, result, ct);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>遍历时忽略的目录:源码与构建产物不属于模型运行数据。</summary>
|
||||
private static bool IsIgnoredDir(string name) => name switch
|
||||
{
|
||||
"src" => true,
|
||||
"bin" => true,
|
||||
"obj" => true,
|
||||
"node_modules" => true,
|
||||
".git" => true,
|
||||
".vs" => true,
|
||||
_ => false
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// 带退避重试的 GET。GitCode API 对突发请求返回 429,
|
||||
/// 这里做 3 次指数退避,避免并行遍历时直接失败。
|
||||
/// </summary>
|
||||
private async Task<string> GetWithRetryAsync(string url, CancellationToken ct,
|
||||
int maxAttempts = 3)
|
||||
{
|
||||
for (var attempt = 1; ; attempt++)
|
||||
{
|
||||
try
|
||||
{
|
||||
return await _http.GetStringAsync(url, ct);
|
||||
}
|
||||
catch (HttpRequestException ex) when (attempt < maxAttempts)
|
||||
{
|
||||
// 429 / 5xx 才重试,其余直接抛
|
||||
var retriable = ex.StatusCode is null ||
|
||||
(int)ex.StatusCode == 429 ||
|
||||
(int)ex.StatusCode >= 500;
|
||||
if (!retriable) throw;
|
||||
await Task.Delay(TimeSpan.FromMilliseconds(400 * attempt * attempt), ct);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<byte[]> DownloadAsync(RepoEntry entry, CancellationToken ct)
|
||||
{
|
||||
if (!string.IsNullOrWhiteSpace(entry.DownloadUrl))
|
||||
return await _http.GetByteArrayAsync(entry.DownloadUrl!, ct);
|
||||
|
||||
var url = _api + entry.Path.Trim('/') + "?ref=" + _branch;
|
||||
var text = await _http.GetStringAsync(url, ct);
|
||||
using var doc = JsonDocument.Parse(text);
|
||||
if (!doc.RootElement.TryGetProperty("content", out var content))
|
||||
throw new InvalidOperationException($"远端文件没有内容: {entry.Path}");
|
||||
return Convert.FromBase64String(content.GetString() ?? "");
|
||||
}
|
||||
|
||||
public async Task<byte[]?> DownloadPackageAsync(RepoPackage package, CancellationToken ct)
|
||||
{
|
||||
// 先试清单直给的 url(Release 附件):命中的情况下不多发任何一次 API 请求。
|
||||
var direct = await TryFetchAsync(package.Url, package.Sha256, ct);
|
||||
if (direct != null) return direct;
|
||||
|
||||
// url 不可用或校验不符:再去找仓库里的编译产物。
|
||||
// 顺序:清单 path → dist/<系统>-<架构>/ 里的 zip → dist 根目录命名。
|
||||
// 每个候选都要和已签名清单的 sha256 对一遍,对不上就换下一个,
|
||||
// 因此「多来源」不放宽校验,只是让「不发 Release 也能更新」成立。
|
||||
foreach (var path in LauncherArtifacts.CandidateFiles(
|
||||
package.Rid, package.Dir, package.Path, package.Name, _launcherVersion))
|
||||
{
|
||||
var url = await ResolveFileUrlAsync(path, ct);
|
||||
var bytes = await TryFetchAsync(url, package.Sha256, ct);
|
||||
if (bytes != null) return bytes;
|
||||
}
|
||||
|
||||
foreach (var dir in LauncherArtifacts.CandidateDirs(package.Rid, package.Dir))
|
||||
{
|
||||
var url = await FindZipInDirAsync(dir, package, ct);
|
||||
var bytes = await TryFetchAsync(url, package.Sha256, ct);
|
||||
if (bytes != null) return bytes;
|
||||
}
|
||||
|
||||
Console.Error.WriteLine("[gitcode] 找不到可用的启动器包(Release 附件与 dist 目录都没对上)");
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>下载一个候选地址;<paramref name="sha256"/> 非空时必须与内容一致。</summary>
|
||||
private async Task<byte[]?> TryFetchAsync(string? url, string? sha256, CancellationToken ct)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(url)) return null;
|
||||
|
||||
byte[] bytes;
|
||||
try { bytes = await _http.GetByteArrayAsync(url!, ct); }
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.Error.WriteLine($"[gitcode] 下载失败 {Short(url!)}: {ex.Message}");
|
||||
return null;
|
||||
}
|
||||
if (bytes.Length == 0) return null;
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(sha256))
|
||||
{
|
||||
var actual = Convert.ToHexString(SHA256.HashData(bytes)).ToLowerInvariant();
|
||||
if (!string.Equals(actual, sha256.Trim(), StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
Console.Error.WriteLine($"[gitcode] 包校验不符,换下一个来源: {Short(url!)}");
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
Console.WriteLine($"[gitcode] 启动器包来源: {Short(url!)}");
|
||||
return bytes;
|
||||
}
|
||||
|
||||
private static string Short(string url)
|
||||
=> url.Length <= 96 ? url : url[..60] + "…" + url[^24..];
|
||||
|
||||
/// <summary>把仓库内路径解析成直链;路径不存在或其实是目录时返回 null。</summary>
|
||||
private async Task<string?> ResolveFileUrlAsync(string path, CancellationToken ct)
|
||||
{
|
||||
try
|
||||
{
|
||||
var url = _api + path.Trim('/') + "?ref=" + _branch;
|
||||
var text = await _http.GetStringAsync(url, ct);
|
||||
if (!text.TrimStart().StartsWith("{", StringComparison.Ordinal)) return null;
|
||||
|
||||
using var doc = JsonDocument.Parse(text);
|
||||
if (doc.RootElement.TryGetProperty("type", out var type) &&
|
||||
string.Equals(type.GetString(), "dir", StringComparison.OrdinalIgnoreCase))
|
||||
return null;
|
||||
return doc.RootElement.TryGetProperty("download_url", out var dl)
|
||||
? dl.GetString() : null;
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
return null; // 404 / 网络问题都当作「这个路径没有」
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 在 <paramref name="dir"/> 里找启动器包。
|
||||
/// 先按「版本 + 平台」精确筛,其次接受目录里唯一的 zip(发布者可能改了命名规则),
|
||||
/// 最终仍由 sha256 兜底。
|
||||
/// </summary>
|
||||
private async Task<string?> FindZipInDirAsync(string dir, RepoPackage package, CancellationToken ct)
|
||||
{
|
||||
try
|
||||
{
|
||||
var url = _api + dir.Trim('/') + "?ref=" + _branch;
|
||||
var text = await _http.GetStringAsync(url, ct);
|
||||
if (!text.TrimStart().StartsWith("[", StringComparison.Ordinal)) return null;
|
||||
|
||||
var zips = new List<(string Path, string Name)>();
|
||||
using (var doc = JsonDocument.Parse(text))
|
||||
{
|
||||
foreach (var item in doc.RootElement.EnumerateArray())
|
||||
{
|
||||
if (Str(item, "type") != "file") continue;
|
||||
var name = Str(item, "name");
|
||||
if (!name.EndsWith(".zip", StringComparison.OrdinalIgnoreCase)) continue;
|
||||
var path = Str(item, "path");
|
||||
zips.Add((path.Length > 0 ? path : dir + "/" + name, name));
|
||||
}
|
||||
}
|
||||
if (zips.Count == 0) return null;
|
||||
|
||||
var version = _launcherVersion;
|
||||
var match = zips.FindIndex(z =>
|
||||
LauncherArtifacts.LooksLikePackage(z.Name, version, package.Rid));
|
||||
if (match < 0)
|
||||
{
|
||||
if (zips.Count != 1) return null;
|
||||
match = 0;
|
||||
}
|
||||
|
||||
Console.WriteLine($"[gitcode] 在 {dir} 找到编译产物: {zips[match].Name}");
|
||||
return await ResolveFileUrlAsync(zips[match].Path, ct);
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static string Str(JsonElement item, string name)
|
||||
=> item.TryGetProperty(name, out var v) && v.ValueKind == JsonValueKind.String
|
||||
? v.GetString() ?? "" : "";
|
||||
|
||||
private static string? NullableStr(JsonElement item, string name)
|
||||
=> item.TryGetProperty(name, out var v) && v.ValueKind == JsonValueKind.String
|
||||
? v.GetString() : null;
|
||||
|
||||
private static long Num(JsonElement item, string name)
|
||||
=> item.TryGetProperty(name, out var v) && v.ValueKind == JsonValueKind.Number
|
||||
&& v.TryGetInt64(out var n) ? n : 0;
|
||||
}
|
||||
@@ -0,0 +1,338 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Net.Http;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace GC.Services;
|
||||
|
||||
/// <summary>
|
||||
/// Gitea / Forgejo 后端(Xhmcl 用的就是这个)。
|
||||
///
|
||||
/// · 目录:GET /api/v1/repos/{owner}/{repo}/contents/{path}
|
||||
/// 返回数组(目录)或对象(单文件),带 name/path/size/type/download_url
|
||||
/// · 原始文件:GET {host}/{owner}/{repo}/raw/branch/{branch}/{path}
|
||||
/// · Release:GET /api/v1/repos/{owner}/{repo}/releases
|
||||
/// 版本取 tag_name;附件取 assets[].browser_download_url
|
||||
///
|
||||
/// Release 为空时(仓库还没发布),回退到仓库里的 version.json,保证只推仓库也能更新。
|
||||
/// </summary>
|
||||
public sealed class GiteaRemote : IModelRemote
|
||||
{
|
||||
private readonly SourcePreset _preset;
|
||||
private static readonly HttpClient Http = CreateHttp();
|
||||
private string? _rawManifest;
|
||||
|
||||
private static HttpClient CreateHttp()
|
||||
{
|
||||
var c = new HttpClient { Timeout = TimeSpan.FromSeconds(20) };
|
||||
c.DefaultRequestHeaders.UserAgent.ParseAdd("GC-Updater/1.0");
|
||||
c.DefaultRequestHeaders.Accept.ParseAdd("application/json");
|
||||
return c;
|
||||
}
|
||||
|
||||
public GiteaRemote(SourcePreset preset)
|
||||
{
|
||||
_preset = preset;
|
||||
DisplayName = preset.Name;
|
||||
}
|
||||
|
||||
public string DisplayName { get; }
|
||||
public string SourceId => _preset.Id;
|
||||
|
||||
private string RepoApi => $"{_preset.ApiBase}/repos/{_preset.Owner}/{_preset.Repo}";
|
||||
|
||||
// ---------------------------------------------------------------- 清单
|
||||
|
||||
/// <summary>
|
||||
/// 两件事分开取:
|
||||
/// · **模型清单**永远来自仓库 version.json(模型不需要发 Release)
|
||||
/// · **启动器版本**只认 Release;没有 Release 时把版本号留空,
|
||||
/// 由上层去问另一个源(LeaderUpdater 会横向比较)。
|
||||
/// 以前把两者绑在一起,导致没有 Release 时连模型都同步不了。
|
||||
/// </summary>
|
||||
public async Task<RepoVersion?> GetVersionAsync(CancellationToken ct)
|
||||
{
|
||||
var fromRepo = await TryGetVersionFromRepoAsync(ct);
|
||||
var fromRelease = await TryGetVersionFromReleasesAsync(ct);
|
||||
|
||||
// 模型清单:仓库里有就用仓库的(保证模型能更新)
|
||||
var result = fromRepo ?? new RepoVersion
|
||||
{
|
||||
Repository = _preset.HomeUrl,
|
||||
Branch = _preset.Branch
|
||||
};
|
||||
|
||||
if (fromRelease != null)
|
||||
{
|
||||
// Release 提供启动器版本与平台附件
|
||||
result.Launcher.Version = fromRelease.Launcher.Version;
|
||||
foreach (var kv in fromRelease.Launcher.Packages)
|
||||
{
|
||||
// Release 只能说明"哪个附件",完整性必须回到已签名清单取 sha256,
|
||||
// 否则「有仓库写权限的人发个 Release」就能绕过验签。
|
||||
if (fromRepo != null &&
|
||||
fromRepo.Launcher.Packages.TryGetValue(kv.Key, out var signed) &&
|
||||
!string.IsNullOrWhiteSpace(signed?.Sha256))
|
||||
{
|
||||
kv.Value.Sha256 = signed!.Sha256;
|
||||
if (signed.Size > 0) kv.Value.Size = signed.Size;
|
||||
}
|
||||
result.Launcher.Packages[kv.Key] = kv.Value;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
// 没有 Release:清空启动器版本,让上层知道"这个源没有可升级的启动器"
|
||||
Console.WriteLine($"[gitea] {_preset.Name}: Release 为空(模型清单仍可用)");
|
||||
result.Launcher.Version = "";
|
||||
result.Launcher.Packages.Clear();
|
||||
|
||||
// 只有模型清单时也返回,保证模型能同步;启动器版本为空表示无升级
|
||||
return result.Models.Count > 0 ? result : null;
|
||||
}
|
||||
/// <summary>最近一次读到的清单原文(SAVEDOG 二次验签用)。</summary>
|
||||
public Task<string?> GetRawVersionTextAsync(CancellationToken ct)
|
||||
=> Task.FromResult(_rawManifest);
|
||||
|
||||
/// <summary>读仓库里的 version.json(模型清单 + 兜底信息)。</summary>
|
||||
private async Task<RepoVersion?> TryGetVersionFromRepoAsync(CancellationToken ct)
|
||||
{
|
||||
foreach (var url in new[] { _preset.RawUrl("version.json"), _preset.RawUrl("model/version.json") })
|
||||
{
|
||||
try
|
||||
{
|
||||
var text = await Http.GetStringAsync(url, ct);
|
||||
if (!text.TrimStart().StartsWith('{')) continue; // 可能返回 HTML
|
||||
var doc = ManifestLoader.Parse(text, out var verification);
|
||||
if (verification.Trust == ManifestTrust.Invalid)
|
||||
Console.Error.WriteLine($"[gitea] 清单验签失败: {verification.Error}");
|
||||
if (doc != null)
|
||||
{
|
||||
_rawManifest = text;
|
||||
return doc;
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.Error.WriteLine($"[gitea] version.json 读取失败 {url}: {ex.Message}");
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 从 Release 列表里挑**版本号最高**的一个(不是最新发布时间的那个),
|
||||
/// 并把它对应平台的附件填进 packages。
|
||||
/// </summary>
|
||||
private async Task<RepoVersion?> TryGetVersionFromReleasesAsync(CancellationToken ct)
|
||||
{
|
||||
try
|
||||
{
|
||||
var json = await Http.GetStringAsync($"{RepoApi}/releases", ct);
|
||||
using var doc = JsonDocument.Parse(json);
|
||||
if (doc.RootElement.ValueKind != JsonValueKind.Array) return null;
|
||||
|
||||
var candidates = new List<(string Version, JsonElement Node)>();
|
||||
foreach (var rel in doc.RootElement.EnumerateArray())
|
||||
{
|
||||
if (rel.TryGetProperty("draft", out var draft) && draft.ValueKind == JsonValueKind.True)
|
||||
continue; // 草稿不算发布
|
||||
var tag = rel.TryGetProperty("tag_name", out var t) ? t.GetString() ?? "" : "";
|
||||
var ver = VersionUtil.Normalize(tag);
|
||||
if (string.IsNullOrWhiteSpace(ver)) continue;
|
||||
candidates.Add((ver, rel));
|
||||
}
|
||||
if (candidates.Count == 0)
|
||||
{
|
||||
// 还没发布 Release 是正常状态:交给上层去问另一个源
|
||||
Console.WriteLine($"[gitea] {_preset.Name}: Release 列表为空");
|
||||
return null;
|
||||
}
|
||||
|
||||
var best = candidates
|
||||
.OrderByDescending(c => VersionUtil.Parse(c.Version))
|
||||
.First();
|
||||
|
||||
var result = new RepoVersion
|
||||
{
|
||||
Repository = _preset.HomeUrl,
|
||||
Branch = _preset.Branch,
|
||||
Launcher = new RepoLauncher { Version = best.Version }
|
||||
};
|
||||
|
||||
// 附件:按文件名识别平台
|
||||
if (best.Node.TryGetProperty("assets", out var assets) &&
|
||||
assets.ValueKind == JsonValueKind.Array)
|
||||
{
|
||||
foreach (var a in assets.EnumerateArray())
|
||||
{
|
||||
var name = a.TryGetProperty("name", out var n) ? n.GetString() ?? "" : "";
|
||||
var url = a.TryGetProperty("browser_download_url", out var u) ? u.GetString() ?? "" : "";
|
||||
if (string.IsNullOrWhiteSpace(name) || string.IsNullOrWhiteSpace(url)) continue;
|
||||
|
||||
var rid = PlatformFromAssetName(name);
|
||||
if (rid == null) continue;
|
||||
|
||||
var size = a.TryGetProperty("size", out var s) && s.TryGetInt64(out var sz) ? sz : 0;
|
||||
result.Launcher.Packages[rid] = new RepoPackage
|
||||
{
|
||||
Url = url,
|
||||
AssetName = name,
|
||||
Size = size
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
return result.Launcher.Packages.Count > 0 ? result : null;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.Error.WriteLine($"[gitea] Release 读取失败({_preset.Name}): {ex.Message}");
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>从附件名推断 RID:GC-1.0.6-win-amd64.zip → win-x64</summary>
|
||||
private static string? PlatformFromAssetName(string name)
|
||||
{
|
||||
var n = name.ToLowerInvariant();
|
||||
if (!n.EndsWith(".zip")) return null;
|
||||
if (n.Contains("win") && n.Contains("arm64")) return "win-arm64";
|
||||
if (n.Contains("win") && (n.Contains("amd64") || n.Contains("x64"))) return "win-x64";
|
||||
if (n.Contains("mac") && n.Contains("arm64")) return "osx-arm64";
|
||||
if (n.Contains("mac") && n.Contains("x64")) return "osx-x64";
|
||||
if (n.Contains("linux") && n.Contains("x64")) return "linux-x64";
|
||||
return null;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- 目录
|
||||
|
||||
public async Task<IReadOnlyList<RepoEntry>> ListTreeAsync(string rootPath, CancellationToken ct)
|
||||
{
|
||||
var result = new List<RepoEntry>();
|
||||
await WalkAsync(rootPath.Trim('/'), "", result, ct, depth: 0);
|
||||
return result;
|
||||
}
|
||||
|
||||
private async Task WalkAsync(string apiPath, string relPrefix, List<RepoEntry> sink,
|
||||
CancellationToken ct, int depth)
|
||||
{
|
||||
if (depth > 8) return;
|
||||
|
||||
var url = $"{RepoRepoContentsUrl()}/{apiPath}";
|
||||
string json;
|
||||
try { json = await Http.GetStringAsync(url, ct); }
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.Error.WriteLine($"[gitea] 列目录失败 {apiPath}: {ex.Message}");
|
||||
return;
|
||||
}
|
||||
|
||||
using var doc = JsonDocument.Parse(json);
|
||||
var root = doc.RootElement;
|
||||
|
||||
// 单文件
|
||||
if (root.ValueKind == JsonValueKind.Object)
|
||||
{
|
||||
AddFile(root, relPrefix, sink);
|
||||
return;
|
||||
}
|
||||
if (root.ValueKind != JsonValueKind.Array) return;
|
||||
|
||||
var subdirs = new List<(string Path, string Rel)>();
|
||||
foreach (var item in root.EnumerateArray())
|
||||
{
|
||||
var type = item.TryGetProperty("type", out var ty) ? ty.GetString() ?? "" : "";
|
||||
var name = item.TryGetProperty("name", out var nm) ? nm.GetString() ?? "" : "";
|
||||
if (string.IsNullOrEmpty(name)) continue;
|
||||
// 跳过构建产物与源码,模型包只需要清单与数据
|
||||
if (type == "dir")
|
||||
{
|
||||
if (IsIgnoredDir(name)) continue;
|
||||
subdirs.Add((apiPath + "/" + name, relPrefix + name + "/"));
|
||||
}
|
||||
else
|
||||
{
|
||||
AddFile(item, relPrefix, sink);
|
||||
}
|
||||
}
|
||||
|
||||
foreach (var (p, rel) in subdirs)
|
||||
await WalkAsync(p, rel, sink, ct, depth + 1);
|
||||
}
|
||||
|
||||
private string RepoRepoContentsUrl() => $"{RepoApi}/contents";
|
||||
|
||||
private static void AddFile(JsonElement item, string relPrefix, List<RepoEntry> sink)
|
||||
{
|
||||
var name = item.TryGetProperty("name", out var n) ? n.GetString() ?? "" : "";
|
||||
var path = item.TryGetProperty("path", out var p) ? p.GetString() ?? "" : name;
|
||||
var size = item.TryGetProperty("size", out var s) && s.TryGetInt64(out var sz) ? sz : 0;
|
||||
var dl = item.TryGetProperty("download_url", out var d) ? d.GetString() : null;
|
||||
var sha = item.TryGetProperty("sha", out var sh) ? sh.GetString() : null;
|
||||
|
||||
sink.Add(new RepoEntry
|
||||
{
|
||||
Name = name,
|
||||
Path = path,
|
||||
RelativePath = relPrefix + name,
|
||||
IsDirectory = false,
|
||||
DownloadUrl = dl,
|
||||
Size = size,
|
||||
Sha = sha
|
||||
});
|
||||
}
|
||||
|
||||
private static bool IsIgnoredDir(string name) =>
|
||||
name is "src" or "bin" or "obj" or "node_modules" or ".git" or ".vs"
|
||||
or ".idea" or ".vscode";
|
||||
|
||||
// ---------------------------------------------------------------- 下载
|
||||
|
||||
public async Task<byte[]> DownloadAsync(RepoEntry entry, CancellationToken ct)
|
||||
{
|
||||
// 优先用 API 提供的 download_url;没有就按 raw 规约拼
|
||||
var url = entry.DownloadUrl;
|
||||
if (string.IsNullOrWhiteSpace(url))
|
||||
url = _preset.RawUrl(entry.Path);
|
||||
|
||||
return await Http.GetByteArrayAsync(url, ct);
|
||||
}
|
||||
|
||||
public async Task<byte[]?> DownloadPackageAsync(RepoPackage package, CancellationToken ct)
|
||||
{
|
||||
// 与 GitCode 一致的策略:Release 附件 → 清单路径 → dist/<系统>-<架构>/ 里的编译产物。
|
||||
// 每个来源都要过 sha256(来自已签名清单),所以多来源不降低安全性。
|
||||
var candidates = new List<string>();
|
||||
if (!string.IsNullOrWhiteSpace(package.Url)) candidates.Add(package.Url!.Trim());
|
||||
foreach (var path in LauncherArtifacts.CandidateFiles(
|
||||
package.Rid, package.Dir, package.Path, package.Name, ""))
|
||||
candidates.Add(_preset.RawUrl(path));
|
||||
|
||||
foreach (var candidate in candidates)
|
||||
{
|
||||
byte[] bytes;
|
||||
try { bytes = await Http.GetByteArrayAsync(candidate, ct); }
|
||||
catch (Exception) { continue; }
|
||||
if (bytes.Length == 0) continue;
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(package.Sha256))
|
||||
{
|
||||
var actual = Convert.ToHexString(
|
||||
System.Security.Cryptography.SHA256.HashData(bytes)).ToLowerInvariant();
|
||||
if (!string.Equals(actual, package.Sha256.Trim(), StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
Console.Error.WriteLine($"[gitea] 包校验不符,换下一个来源: {candidate}");
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
Console.WriteLine($"[gitea] 启动器包来源: {candidate}");
|
||||
return bytes;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace GC.Services;
|
||||
|
||||
/// <summary>
|
||||
/// 平台标签与「仓库里的编译产物位置」的推导规则。
|
||||
///
|
||||
/// 历史背景:启动器更新原本只认 GitCode Release 的附件。但发布者往往只是把编译产物
|
||||
/// 提交(或上传)到仓库的 <c>dist/<系统>-<架构></c> 目录,例如
|
||||
/// <c>dist/mac-arm64/GC-1.0.7-mac-arm64.zip</c>,根本没有发 Release。
|
||||
/// 于是下载端需要一套「同一个平台有哪几种叫法」的映射,才能把这些目录找出来。
|
||||
///
|
||||
/// 安全性说明:多来源尝试**不会**降低安全性——每个候选下载完都要和已签名清单里的
|
||||
/// sha256 对一遍,对不上就换下一个来源,全都不对就失败。sha256 来自签名清单,
|
||||
/// 攻击者即使往 dist/ 里塞包也拿不到匹配的哈希。
|
||||
///
|
||||
/// 本文件同时被启动器(GC-DOWNLOAD)与构建端(VersionStamp)链接编译,
|
||||
/// 保证「写进清单的路径」与「运行时找的路径」永远一致。
|
||||
/// </summary>
|
||||
public static class LauncherArtifacts
|
||||
{
|
||||
/// <summary>
|
||||
/// RID → 文件名里的「系统-架构」标签(与 <c>LauncherUpdater.PlatformLabel</c> 一致)。
|
||||
/// </summary>
|
||||
public static string LabelOf(string rid) => rid switch
|
||||
{
|
||||
"win-x64" => "win-amd64",
|
||||
"win-arm64" => "win-arm64",
|
||||
"osx-arm64" => "mac-arm64",
|
||||
"osx-x64" => "mac-x64",
|
||||
"linux-x64" => "linux-amd64",
|
||||
_ => rid
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// 同一平台在仓库里可能用的目录名(按优先级)。
|
||||
/// 既接受 <c>mac-arm64</c> 这种标签,也接受 <c>osx-arm64</c> 这种 RID,
|
||||
/// 因为 dist 目录名历史上两种写法都出现过。
|
||||
/// </summary>
|
||||
public static IReadOnlyList<string> PlatformAliases(string rid)
|
||||
{
|
||||
var label = LabelOf(rid);
|
||||
if (string.Equals(label, rid, StringComparison.OrdinalIgnoreCase))
|
||||
return new[] { rid };
|
||||
return new[] { label, rid };
|
||||
}
|
||||
|
||||
/// <summary>启动器包应有的文件名,如 <c>GC-1.0.7-mac-arm64.zip</c>。</summary>
|
||||
public static string PackageFileName(string version, string rid)
|
||||
=> $"GC-{version.Trim().TrimStart('v', 'V')}-{LabelOf(rid)}.zip";
|
||||
|
||||
/// <summary>
|
||||
/// 判断某个 zip 名是不是「这个版本 + 这个平台」的启动器包。
|
||||
/// 只做粗筛(版本串 + 平台别名),最终仍以 sha256 为准。
|
||||
/// </summary>
|
||||
public static bool LooksLikePackage(string fileName, string version, string rid)
|
||||
{
|
||||
if (!fileName.EndsWith(".zip", StringComparison.OrdinalIgnoreCase)) return false;
|
||||
if (!fileName.StartsWith("GC-", StringComparison.OrdinalIgnoreCase)) return false;
|
||||
|
||||
var v = version.Trim().TrimStart('v', 'V');
|
||||
if (v.Length > 0 && fileName.IndexOf(v, StringComparison.OrdinalIgnoreCase) < 0) return false;
|
||||
|
||||
var haystack = fileName.ToLowerInvariant();
|
||||
foreach (var alias in PlatformAliases(rid))
|
||||
if (haystack.Contains(alias.ToLowerInvariant(), StringComparison.Ordinal))
|
||||
return true;
|
||||
|
||||
return haystack.Contains(rid.ToLowerInvariant(), StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 候选目录:清单显式给的 dir 优先,其次是 <c>dist/<标签></c> 与 <c>dist/<RID></c>。
|
||||
/// </summary>
|
||||
public static IReadOnlyList<string> CandidateDirs(string rid, string? declaredDir)
|
||||
{
|
||||
var dirs = new List<string>();
|
||||
if (!string.IsNullOrWhiteSpace(declaredDir))
|
||||
dirs.Add(declaredDir!.Trim().Trim('/'));
|
||||
|
||||
foreach (var alias in PlatformAliases(rid))
|
||||
dirs.Add("dist/" + alias);
|
||||
|
||||
var seen = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
|
||||
var result = new List<string>();
|
||||
foreach (var dir in dirs)
|
||||
if (dir.Length > 0 && seen.Add(dir)) result.Add(dir);
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 候选文件路径(不含目录扫描):清单给的 path / name,以及 dist 根目录里的两种命名。
|
||||
/// </summary>
|
||||
public static IReadOnlyList<string> CandidateFiles(string rid, string? declaredDir,
|
||||
string? declaredPath, string? declaredName, string version)
|
||||
{
|
||||
var files = new List<string>();
|
||||
if (!string.IsNullOrWhiteSpace(declaredPath))
|
||||
files.Add(declaredPath!.Trim().Trim('/'));
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(declaredName))
|
||||
foreach (var dir in CandidateDirs(rid, declaredDir))
|
||||
files.Add(dir + "/" + declaredName!.Trim());
|
||||
|
||||
if (version.Length > 0)
|
||||
{
|
||||
files.Add("dist/" + PackageFileName(version, rid));
|
||||
foreach (var alias in PlatformAliases(rid))
|
||||
files.Add($"dist/GC-{version.Trim().TrimStart('v', 'V')}-{alias}.zip");
|
||||
}
|
||||
|
||||
var seen = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
|
||||
var result = new List<string>();
|
||||
foreach (var file in files)
|
||||
if (file.Length > 0 && seen.Add(file)) result.Add(file);
|
||||
return result;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,742 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.IO.Compression;
|
||||
using System.Linq;
|
||||
using System.Security.Cryptography;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace GC.Services;
|
||||
|
||||
// ===========================================================================
|
||||
// 启动器更新模块(唯一实现)
|
||||
//
|
||||
// 需求(按用户):
|
||||
// · 只认 GitCode Release 的 latest 版本号(tag),文件名格式:
|
||||
// GC-<版本>-<系统>-<架构>.exe / .app
|
||||
// 例 GC-1.0.3-win-amd64.exe / GC-1.0.3-mac-arm64.app
|
||||
// · 当前运行版本与 latest 不同 => 提示更新;相同 => 无需更新
|
||||
// · 下载的新版解压到「当前运行目录」,与旧版并列;.GC 完全不动
|
||||
// · 更新完成后:删除同系统同架构、版本号 != latest 的其它 GC-* 文件;
|
||||
// 异系统 / 异架构的文件一律不碰
|
||||
// · 一切落盘内容(脚本、标记)只用相对路径,绝不写绝对路径
|
||||
// ===========================================================================
|
||||
|
||||
/// <summary>下载 / 检查 / 应用启动器更新的唯一入口。</summary>
|
||||
public static class LauncherUpdater
|
||||
{
|
||||
/// <summary>当前运行程序的版本号(来自程序集)。</summary>
|
||||
public static string RunningVersion => LauncherRuntimeInfo.CurrentLauncherVersion;
|
||||
|
||||
/// <summary>当前 RID,如 osx-arm64。</summary>
|
||||
public static string CurrentRid => LauncherRuntimeInfo.CurrentRid;
|
||||
|
||||
/// <summary>文件名里用的「系统-架构」标签,如 mac-arm64 / win-amd64。</summary>
|
||||
public static string PlatformLabel => CurrentRid switch
|
||||
{
|
||||
"win-x64" => "win-amd64",
|
||||
"win-arm64" => "win-arm64",
|
||||
"osx-arm64" => "mac-arm64",
|
||||
"osx-x64" => "mac-x64",
|
||||
"linux-x64" => "linux-amd64",
|
||||
_ => CurrentRid
|
||||
};
|
||||
|
||||
// ---------------------------------------------------------------- 检查
|
||||
|
||||
/// <summary>
|
||||
/// 检查 Release latest 版本。返回 latest 版本号;若与当前运行版本相同返回 null。
|
||||
/// 只比版本号,不比 sha256。
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
/// 检查启动器新版本:**两个源(Xhmcl / GitCode)的 Release 都要查**,
|
||||
/// 取版本号最高的那个作为最新版。任何一个源失败不影响另一个。
|
||||
/// </summary>
|
||||
public static async Task<string?> CheckAsync(CancellationToken ct = default)
|
||||
=> await CheckAllAsync(null, ct);
|
||||
|
||||
/// <summary>兼容旧调用:优先用给定 remote,同时仍会比对另一个源。</summary>
|
||||
public static async Task<string?> CheckAsync(IModelRemote remote, CancellationToken ct = default)
|
||||
=> await CheckAllAsync(remote, ct);
|
||||
|
||||
private static async Task<string?> CheckAllAsync(IModelRemote? preferred, CancellationToken ct)
|
||||
{
|
||||
var candidates = new List<(string Source, string Version)>();
|
||||
|
||||
foreach (var preset in SourcePreset.All)
|
||||
{
|
||||
try
|
||||
{
|
||||
// 优先复用调用方已建好的 remote(避免重复建实例)
|
||||
var remote = preferred != null &&
|
||||
SourcePreset.Detect(preferred.DisplayName).Id == preset.Id
|
||||
? preferred
|
||||
: SourceSelector.CreateRemote(preset);
|
||||
|
||||
var version = await remote.GetVersionAsync(ct);
|
||||
var v = (version?.Launcher.Version ?? "").Trim();
|
||||
if (v.Length == 0)
|
||||
{
|
||||
Console.WriteLine($"[update] {preset.Name}: 没有版本信息(可能还没发 Release)");
|
||||
continue;
|
||||
}
|
||||
Console.WriteLine($"[update] {preset.Name}: {v}");
|
||||
candidates.Add((preset.Name, v));
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.Error.WriteLine($"[update] {preset.Name} 检查失败: {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
if (candidates.Count == 0) return null;
|
||||
|
||||
// 取版本号最高的(第 7 项)
|
||||
var best = candidates.OrderByDescending(c => VersionUtil.Parse(c.Version)).First();
|
||||
Console.WriteLine($"[update] 最新版:{best.Version}(来自 {best.Source})");
|
||||
|
||||
var cmp = VersionUtil.Compare(best.Version, RunningVersion);
|
||||
|
||||
// 远端版本更新 → 提示更新
|
||||
if (cmp > 0)
|
||||
{
|
||||
Console.WriteLine($"[update] 远端 {best.Version} > 本地 {RunningVersion},提示更新");
|
||||
return best.Version;
|
||||
}
|
||||
|
||||
// 远端版本更旧 → 不提示
|
||||
if (cmp < 0)
|
||||
{
|
||||
Console.WriteLine($"[update] 远端 {best.Version} < 本地 {RunningVersion},不提示");
|
||||
return null;
|
||||
}
|
||||
|
||||
// 版本号相同:比对当前程序的 sha256 与 Release 包
|
||||
// 相符 → 视为最新,不提示
|
||||
// 不相符 → 说明是重新编译的同版本程序,必须提示下载
|
||||
var same = await SameFingerprintAsync(best.Source, best.Version, ct);
|
||||
if (same == null)
|
||||
{
|
||||
Console.WriteLine("[update] 版本相同但无法比对 sha256,按最新处理");
|
||||
return null;
|
||||
}
|
||||
if (same.Value)
|
||||
{
|
||||
Console.WriteLine("[update] 版本相同且 sha256 一致,已是最新");
|
||||
return null;
|
||||
}
|
||||
|
||||
// 版本相同但指纹不同:是自行编译的构建,不提示更新
|
||||
Console.WriteLine("[update] 版本相同但 sha256 不一致,不提示更新");
|
||||
return null;
|
||||
}
|
||||
/// <summary>
|
||||
/// 比对「当前运行程序」与「Release 平台包」的 sha256。
|
||||
/// 返回 true=一致(确属同一份构建)、false=不一致(需重新下载)、null=无法比对。
|
||||
/// </summary>
|
||||
private static async Task<bool?> SameFingerprintAsync(string sourceName, string version,
|
||||
CancellationToken ct)
|
||||
{
|
||||
try
|
||||
{
|
||||
var preset = SourcePreset.All.FirstOrDefault(p =>
|
||||
string.Equals(p.Name, sourceName, StringComparison.OrdinalIgnoreCase));
|
||||
if (preset == null) return null;
|
||||
|
||||
var rid = CurrentRid;
|
||||
Console.WriteLine($"[update] 抓取 {preset.Name} 的 {rid} 发布包用于比对…");
|
||||
|
||||
// 定位进程对应的可执行文件 / .app
|
||||
var self = Environment.ProcessPath;
|
||||
if (string.IsNullOrWhiteSpace(self)) return null;
|
||||
var selfPath = self!;
|
||||
// 单文件 / dotnet 宿主时退回到程序集位置
|
||||
if (Path.GetFileNameWithoutExtension(selfPath).Equals("dotnet", StringComparison.OrdinalIgnoreCase))
|
||||
selfPath = typeof(LauncherUpdater).Assembly.Location;
|
||||
|
||||
var selfHash = await HashFileAsync(selfPath, ct);
|
||||
Console.WriteLine($"[update] 本地程序 sha256 = {selfHash[..16]}…");
|
||||
|
||||
// 下载 Release 对应平台包,取包内主程序再算
|
||||
var remote = SourceSelector.CreateRemote(preset);
|
||||
var v = await remote.GetVersionAsync(ct);
|
||||
if (v == null || !v.Launcher.Packages.TryGetValue(rid, out var pkg) || pkg == null)
|
||||
return null;
|
||||
|
||||
var bytes = await remote.DownloadPackageAsync(pkg, ct);
|
||||
if (bytes == null || bytes.Length == 0) return null;
|
||||
|
||||
var remoteHash = await HashZipPayloadAsync(bytes, ct);
|
||||
if (remoteHash == null) return null;
|
||||
Console.WriteLine($"[update] 远端包 sha256 = {remoteHash[..16]}…");
|
||||
|
||||
return string.Equals(selfHash, remoteHash, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.WriteLine($"[update] sha256 比对失败: {ex.Message}");
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static async Task<string> HashFileAsync(string path, CancellationToken ct)
|
||||
{
|
||||
await using var fs = File.OpenRead(path);
|
||||
var hash = await System.Security.Cryptography.SHA256.HashDataAsync(fs, ct);
|
||||
return Convert.ToHexString(hash);
|
||||
}
|
||||
|
||||
/// <summary>从发布包(zip)里取出主程序并算 sha256。</summary>
|
||||
private static async Task<string?> HashZipPayloadAsync(byte[] zip, CancellationToken ct)
|
||||
{
|
||||
try
|
||||
{
|
||||
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 =>
|
||||
e.Name.Equals("GC.dll", StringComparison.OrdinalIgnoreCase))
|
||||
?? archive.Entries.FirstOrDefault(e =>
|
||||
e.Name.Equals("GC", StringComparison.OrdinalIgnoreCase))
|
||||
?? archive.Entries.FirstOrDefault(e =>
|
||||
e.Name.EndsWith(".dll", StringComparison.OrdinalIgnoreCase) &&
|
||||
e.Name.StartsWith("GC", StringComparison.OrdinalIgnoreCase));
|
||||
if (entry == null) return null;
|
||||
|
||||
await using var es = entry.Open();
|
||||
using var buf = new MemoryStream();
|
||||
await es.CopyToAsync(buf, ct);
|
||||
var hash = System.Security.Cryptography.SHA256.HashData(buf.ToArray());
|
||||
return Convert.ToHexString(hash);
|
||||
}
|
||||
catch { return null; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 遍历所有源的 Release,取**版本号最高且包含本平台发布包**的那个。
|
||||
/// 某个源没有 Release(返回 null)时自动跳过。
|
||||
/// </summary>
|
||||
private static async Task<(RepoVersion Version, IModelRemote Remote)?> GetBestReleaseAsync(
|
||||
IModelRemote fallback, CancellationToken ct)
|
||||
{
|
||||
var rid = CurrentRid;
|
||||
var found = new List<(string Source, RepoVersion Version, IModelRemote Remote)>();
|
||||
|
||||
foreach (var preset in SourcePreset.All)
|
||||
{
|
||||
try
|
||||
{
|
||||
var remote = SourceSelector.CreateRemote(preset);
|
||||
var v = await remote.GetVersionAsync(ct);
|
||||
if (v == null)
|
||||
{
|
||||
Console.WriteLine($"[update] {preset.Name}: 无 Release");
|
||||
continue;
|
||||
}
|
||||
if (string.IsNullOrWhiteSpace(v.Launcher.Version) || v.Launcher.Packages.Count == 0)
|
||||
{
|
||||
Console.WriteLine($"[update] {preset.Name}: 没有可用的启动器发布包");
|
||||
continue;
|
||||
}
|
||||
var hasPkg = v.Launcher.Packages.ContainsKey(rid) ||
|
||||
v.Launcher.Packages.ContainsKey("default");
|
||||
if (!hasPkg)
|
||||
{
|
||||
Console.WriteLine($"[update] {preset.Name}: v{v.Launcher.Version} 缺少 {rid} 发布包");
|
||||
continue;
|
||||
}
|
||||
Console.WriteLine($"[update] {preset.Name}: v{v.Launcher.Version} 可用");
|
||||
found.Add((preset.Name, v, remote));
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.Error.WriteLine($"[update] {preset.Name} 读取失败: {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
if (found.Count == 0) return null;
|
||||
|
||||
var best = found.OrderByDescending(f => VersionUtil.Parse(f.Version.Launcher.Version)).First();
|
||||
Console.WriteLine($"[update] 选中最新的可用发布包:v{best.Version.Launcher.Version}({best.Source})");
|
||||
return (best.Version, best.Remote);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- 下载
|
||||
|
||||
/// <summary>
|
||||
/// 下载 latest 版本到当前运行目录(与旧版并列)。
|
||||
/// 返回新版包名,供后续替换脚本使用。
|
||||
/// </summary>
|
||||
public static async Task<UpdateRunResult> DownloadAsync(
|
||||
AppPaths paths, IModelRemote remote,
|
||||
IProgress<UpdateProgressInfo>? progress = null,
|
||||
CancellationToken ct = default)
|
||||
{
|
||||
try
|
||||
{
|
||||
progress?.Report(new UpdateProgressInfo { Value = 0.05, Stage = "正在读取最新版本" });
|
||||
|
||||
// 两个源都问一遍:某个源没发 Release 时自动换另一个,
|
||||
// 与「检查更新」保持同一套规则,避免检查通过、下载却报无法读取。
|
||||
var version = await remote.GetVersionAsync(ct);
|
||||
|
||||
// 当前源没有可用的启动器版本(没发 Release / 版本号为空)→ 换另一个源。
|
||||
// 注意:模型清单可能仍然有效,但启动器升级必须有 Release。
|
||||
var hasUsable = version != null &&
|
||||
!string.IsNullOrWhiteSpace(version.Launcher.Version) &&
|
||||
version.Launcher.Packages.Count > 0;
|
||||
|
||||
if (!hasUsable)
|
||||
{
|
||||
var tried = SourcePreset.Find(remote.SourceId)?.Name ?? remote.DisplayName;
|
||||
Console.WriteLine($"[update] {tried} 没有可用的启动器发布包,换另一个源");
|
||||
var pick = await GetBestReleaseAsync(remote, ct);
|
||||
if (pick == null) return Fail("两个源都没有可用的 Release 发布包");
|
||||
version = pick.Value.Version;
|
||||
remote = pick.Value.Remote; // 后续下载必须用这个源的 remote
|
||||
}
|
||||
|
||||
var latest = (version!.Launcher.Version ?? "").Trim();
|
||||
var rid = CurrentRid;
|
||||
if (!version.Launcher.Packages.TryGetValue(rid, out var pkg) &&
|
||||
!version.Launcher.Packages.TryGetValue("default", out pkg))
|
||||
return Fail($"该平台({rid})没有对应发布包");
|
||||
|
||||
// ---- 信任闸门 ---------------------------------------------------
|
||||
// 启动器更新会替换可执行文件,风险最高:清单没签名就一律不动。
|
||||
// 只有显式设置 GC_ALLOW_UNSIGNED_MANIFEST=1(自建私有构建)才放行。
|
||||
var allowUnsigned =
|
||||
Environment.GetEnvironmentVariable("GC_ALLOW_UNSIGNED_MANIFEST") == "1";
|
||||
|
||||
if (!version.IsTrusted && !allowUnsigned)
|
||||
{
|
||||
var reason = version.SignatureTrust == nameof(ManifestTrust.Invalid)
|
||||
? "清单签名无效"
|
||||
: "清单未签名";
|
||||
Console.Error.WriteLine($"[update] 启动器更新被拒绝:{reason}");
|
||||
return Fail($"{reason},已拒绝下载启动器更新");
|
||||
}
|
||||
|
||||
if (string.IsNullOrWhiteSpace(pkg!.Sha256))
|
||||
{
|
||||
Console.Error.WriteLine("[update] 清单没有提供 sha256,拒绝下载启动器更新");
|
||||
return Fail("清单缺少该平台的 sha256,已拒绝下载(无法校验完整性)");
|
||||
}
|
||||
|
||||
progress?.Report(new UpdateProgressInfo { Value = 0.20, Stage = $"正在下载 v{latest}" });
|
||||
|
||||
var bytes = await remote.DownloadPackageAsync(pkg!, ct);
|
||||
if (bytes == null || bytes.Length == 0) return Fail("下载失败:发布包为空");
|
||||
|
||||
// sha256 校验(清单已验签,这里的 sha256 就是"正版"的定义)
|
||||
{
|
||||
var actual = Convert.ToHexString(SHA256.HashData(bytes)).ToLowerInvariant();
|
||||
if (!string.Equals(actual, pkg.Sha256!.Trim(), StringComparison.OrdinalIgnoreCase))
|
||||
return Fail("下载文件校验失败(sha256 与已签名清单不符)");
|
||||
}
|
||||
|
||||
progress?.Report(new UpdateProgressInfo { Value = 0.55, Stage = "正在校验更新包" });
|
||||
|
||||
var updateRoot = paths.UpdateRoot;
|
||||
Directory.CreateDirectory(updateRoot);
|
||||
|
||||
// 更新包留在 .GC/update,交给 SAVEDOG 自己解压 —— 不信任"预解压目录",
|
||||
// 避免「解压后被替换」的中间窗口。
|
||||
var zip = Path.Combine(updateRoot, "package.zip");
|
||||
if (File.Exists(zip)) File.Delete(zip);
|
||||
await File.WriteAllBytesAsync(zip, bytes, ct);
|
||||
|
||||
try
|
||||
{
|
||||
var inspection = SafeArchive.Inspect(zip);
|
||||
Console.WriteLine($"[update] 更新包检查通过:{inspection.Entries} 个条目," +
|
||||
$"{inspection.UncompressedBytes / 1024 / 1024} MB");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
try { File.Delete(zip); } catch { }
|
||||
return Fail("更新包安全性检查失败: " + ex.Message);
|
||||
}
|
||||
|
||||
// 二次验签用的清单副本:SAVEDOG 不信任"启动器说它验过了"
|
||||
var rawManifest = await remote.GetRawVersionTextAsync(ct);
|
||||
var manifestCopy = Path.Combine(updateRoot, "version.json");
|
||||
if (!string.IsNullOrWhiteSpace(rawManifest))
|
||||
File.WriteAllText(manifestCopy, rawManifest!);
|
||||
else if (File.Exists(manifestCopy))
|
||||
File.Delete(manifestCopy);
|
||||
|
||||
// 包名:GC-<版本>-<平台标签>.app/.exe(SAVEDOG 找不到时会自行扫描包内顶层)
|
||||
var packageName = $"GC-{latest}-{PlatformLabel}" + (OperatingSystem.IsMacOS() ? ".app" : ".exe");
|
||||
|
||||
var request = new SavedogRequest
|
||||
{
|
||||
Version = latest,
|
||||
Rid = rid,
|
||||
PlatformLabel = PlatformLabel,
|
||||
PackageName = packageName,
|
||||
PackageZip = "package.zip",
|
||||
PayloadDir = "payload",
|
||||
ManifestPath = "version.json",
|
||||
PackageSha256 = pkg.Sha256!.Trim().ToLowerInvariant(),
|
||||
PackageSize = bytes.LongLength,
|
||||
RequireSignature = version.IsTrusted,
|
||||
InstallRelative = Path.GetRelativePath(updateRoot, paths.InstallDirectory),
|
||||
CreatedAt = DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ssZ")
|
||||
};
|
||||
Json.Write(Path.Combine(updateRoot, SavedogFiles.ApplyRequest), request);
|
||||
|
||||
// 兼容兜底:没有 SAVEDOG 的旧安装,仍然按老方式预解压 + 脚本替换
|
||||
string? legacyPath = null;
|
||||
if (SavedogLauncher.Find(paths) == null)
|
||||
{
|
||||
Console.WriteLine("[update] 未找到 GC-SAVEDOG,使用兼容脚本流程");
|
||||
progress?.Report(new UpdateProgressInfo { Value = 0.7, Stage = "正在解压更新包" });
|
||||
|
||||
var staging = Path.Combine(paths.CacheRoot, "launcher-staging");
|
||||
if (Directory.Exists(staging)) Directory.Delete(staging, true);
|
||||
Directory.CreateDirectory(staging);
|
||||
SafeArchive.ExtractToDirectory(zip, staging);
|
||||
FlattenStaging(staging);
|
||||
|
||||
var payload = Path.Combine(updateRoot, "payload");
|
||||
if (Directory.Exists(payload)) Directory.Delete(payload, true);
|
||||
Directory.CreateDirectory(payload);
|
||||
var legacyName = MoveToPayload(staging, payload);
|
||||
try { Directory.Delete(staging, true); } catch { }
|
||||
if (legacyName == null) return Fail("解压结果里没有找到新版启动器");
|
||||
|
||||
packageName = legacyName;
|
||||
request.PackageName = legacyName;
|
||||
Json.Write(Path.Combine(updateRoot, SavedogFiles.ApplyRequest), request);
|
||||
legacyPath = Path.Combine(payload, legacyName);
|
||||
|
||||
// 老脚本读这个纯文本标记,只含相对信息
|
||||
File.WriteAllText(Path.Combine(updateRoot, "update.txt"),
|
||||
$"NAME={legacyName}\nVERSION={latest}\nPLATFORM={PlatformLabel}\n" +
|
||||
$"INSTALL_REL={request.InstallRelative}\n");
|
||||
}
|
||||
|
||||
progress?.Report(new UpdateProgressInfo { Value = 1.0, Stage = "下载完成" });
|
||||
|
||||
return new UpdateRunResult
|
||||
{
|
||||
State = UpdateRunState.Ready,
|
||||
Version = latest,
|
||||
Message = $"v{latest} 已暂存到 .GC/update",
|
||||
PackageName = packageName,
|
||||
NewAppPath = legacyPath
|
||||
};
|
||||
}
|
||||
catch (OperationCanceledException) { return Fail("已取消"); }
|
||||
catch (Exception ex) { return Fail(ex.Message); }
|
||||
}
|
||||
|
||||
private static UpdateRunResult Fail(string msg) => new()
|
||||
{
|
||||
State = UpdateRunState.Failed,
|
||||
Message = msg
|
||||
};
|
||||
|
||||
// ---------------------------------------------------------------- 应用(下次启动)
|
||||
|
||||
/// <summary>
|
||||
/// 安排应用已下载的新版。
|
||||
/// 首选 <b>GC-SAVEDOG</b>:二次验签、原子替换、启动后健康检查、失败自动回滚;
|
||||
/// 找不到 SAVEDOG 时退回旧脚本流程(只用于从老版本升级的过渡)。
|
||||
/// 返回 true 表示调用方应立即退出进程。
|
||||
/// </summary>
|
||||
public static bool ScheduleApply(AppPaths paths, string packageName)
|
||||
{
|
||||
// 安全阀:绝不在源码目录执行替换(防止误删源码)
|
||||
if (File.Exists(Path.Combine(paths.InstallDirectory, "GC.sln")))
|
||||
{
|
||||
Console.Error.WriteLine("源码版:新版已下载,但拒绝在源码目录执行替换");
|
||||
return false;
|
||||
}
|
||||
|
||||
if (File.Exists(Path.Combine(paths.UpdateRoot, SavedogFiles.ApplyRequest)))
|
||||
{
|
||||
string? savedogError = null;
|
||||
if (SavedogLauncher.TryStart(paths, Environment.ProcessId, out savedogError))
|
||||
return true;
|
||||
Console.Error.WriteLine($"[update] {savedogError},改用兼容脚本");
|
||||
}
|
||||
|
||||
var marker = Path.Combine(paths.UpdateRoot, "update.txt");
|
||||
if (!File.Exists(marker)) return false;
|
||||
|
||||
try
|
||||
{
|
||||
var isWin = OperatingSystem.IsWindows();
|
||||
var script = Path.Combine(paths.UpdateRoot, isWin ? "apply.bat" : "apply.sh");
|
||||
var content = isWin ? WindowsScript() : UnixScript();
|
||||
File.WriteAllText(script, content, new System.Text.UTF8Encoding(false));
|
||||
|
||||
if (!isWin)
|
||||
{
|
||||
try
|
||||
{
|
||||
File.SetUnixFileMode(script,
|
||||
UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute);
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
|
||||
var psi = isWin
|
||||
? new System.Diagnostics.ProcessStartInfo("cmd.exe")
|
||||
{ UseShellExecute = false, CreateNoWindow = true }
|
||||
: new System.Diagnostics.ProcessStartInfo("/bin/sh")
|
||||
{ UseShellExecute = false, CreateNoWindow = true };
|
||||
if (isWin) psi.ArgumentList.Add("/c");
|
||||
psi.ArgumentList.Add(script);
|
||||
System.Diagnostics.Process.Start(psi);
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.Error.WriteLine($"启动替换脚本失败: {ex.Message}");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>启动时若有待应用更新:交给 SAVEDOG,由调用方退出进程。</summary>
|
||||
public static bool TryApplyPending(AppPaths paths)
|
||||
{
|
||||
if (paths.IsDevelopment) return false;
|
||||
if (Environment.GetEnvironmentVariable("EMS_SELFTEST") == "1") return false;
|
||||
if (Environment.GetEnvironmentVariable("EMS_NO_SELF_UPDATE") == "1") return false;
|
||||
|
||||
// 新协议:apply-request.json + package.zip(SAVEDOG 自己解压 + 验签)
|
||||
var requestPath = Path.Combine(paths.UpdateRoot, SavedogFiles.ApplyRequest);
|
||||
if (File.Exists(requestPath))
|
||||
{
|
||||
var request = Json.Read<SavedogRequest>(requestPath);
|
||||
var zipPath = request == null
|
||||
? null
|
||||
: Path.Combine(paths.UpdateRoot, request.PackageZip);
|
||||
|
||||
if (request != null && zipPath != null && File.Exists(zipPath))
|
||||
return ScheduleApply(paths, request.PackageName);
|
||||
|
||||
Console.Error.WriteLine("[update] 更新申请不完整,已清理");
|
||||
try { File.Delete(requestPath); } catch { }
|
||||
}
|
||||
|
||||
// 旧协议:update.txt + payload(从老版本升级时仍可能遇到)
|
||||
var marker = Path.Combine(paths.UpdateRoot, "update.txt");
|
||||
if (!File.Exists(marker)) return false;
|
||||
|
||||
var name = ReadMarker(marker, "NAME");
|
||||
if (string.IsNullOrWhiteSpace(name)) return false;
|
||||
var payloadPath = Path.Combine(paths.UpdateRoot, "payload", name!);
|
||||
if (!File.Exists(payloadPath) && !Directory.Exists(payloadPath))
|
||||
return false; // 新版本不在了,放弃
|
||||
|
||||
return ScheduleApply(paths, name!);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- 脚本(全部相对路径)
|
||||
|
||||
private static string UnixScript()
|
||||
{
|
||||
var s = new System.Text.StringBuilder();
|
||||
s.AppendLine("#!/bin/sh");
|
||||
s.AppendLine("# script lives in .GC/update/ ; install path is recorded relatively");
|
||||
s.AppendLine("HERE=$(CDPATH= cd -- \"$(dirname -- \"$0\")\" && pwd)");
|
||||
s.AppendLine("MARKER=\"$HERE/update.txt\"");
|
||||
s.AppendLine();
|
||||
s.AppendLine("# read marker");
|
||||
s.AppendLine("NEWNAME=$(sed -n 's/^NAME=//p' \"$MARKER\" 2>/dev/null | head -1)");
|
||||
s.AppendLine("NEWVER=$(sed -n 's/^VERSION=//p' \"$MARKER\" 2>/dev/null | head -1)");
|
||||
s.AppendLine("NEWPLAT=$(sed -n 's/^PLATFORM=//p' \"$MARKER\" 2>/dev/null | head -1)");
|
||||
s.AppendLine("INSTALLREL=$(sed -n 's/^INSTALL_REL=//p' \"$MARKER\" 2>/dev/null | head -1)");
|
||||
s.AppendLine("if [ -z \"$NEWNAME\" ] || [ -z \"$NEWVER\" ] || [ -z \"$INSTALLREL\" ]; then");
|
||||
s.AppendLine(" echo \"marker incomplete, abort\"; rm -f \"$HERE\"/*.sh 2>/dev/null; exit 1");
|
||||
s.AppendLine("fi");
|
||||
s.AppendLine("DST=$(CDPATH= cd -- \"$HERE/$INSTALLREL\" && pwd)");
|
||||
s.AppendLine("PAYLOAD=\"$HERE/payload/$NEWNAME\"");
|
||||
s.AppendLine("if [ ! -e \"$PAYLOAD\" ]; then");
|
||||
s.AppendLine(" echo \"new package missing, abort\"; rm -f \"$HERE\"/*.sh 2>/dev/null; exit 1");
|
||||
s.AppendLine("fi");
|
||||
s.AppendLine();
|
||||
s.AppendLine("# wait for old process to exit (this script is started by it)");
|
||||
s.AppendLine("sleep 2");
|
||||
s.AppendLine();
|
||||
s.AppendLine("# move the staged package into the install directory");
|
||||
s.AppendLine("NEW=\"$DST/$NEWNAME\"");
|
||||
s.AppendLine("rm -rf \"$NEW\"");
|
||||
s.AppendLine("mv \"$PAYLOAD\" \"$NEW\"");
|
||||
s.AppendLine();
|
||||
s.AppendLine("# launch new version");
|
||||
s.AppendLine("if [ -d \"$NEW\" ]; then open \"$NEW\" 2>/dev/null &");
|
||||
s.AppendLine("elif [ -x \"$NEW\" ]; then \"$NEW\" >/dev/null 2>&1 &");
|
||||
s.AppendLine("fi");
|
||||
s.AppendLine();
|
||||
s.AppendLine("# delete old GC-* files: SAME platform only, version != latest");
|
||||
s.AppendLine("# files of OTHER platforms are NEVER touched");
|
||||
s.AppendLine("for item in \"$DST\"/GC-*.app \"$DST\"/GC-*.exe; do");
|
||||
s.AppendLine(" [ -e \"$item\" ] || continue");
|
||||
s.AppendLine(" [ \"$item\" = \"$NEW\" ] && continue");
|
||||
s.AppendLine(" base=$(basename \"$item\")");
|
||||
s.AppendLine(" stem=${base#GC-}");
|
||||
s.AppendLine(" case \"$base\" in");
|
||||
s.AppendLine(" *.app) stem=${stem%.app} ;;");
|
||||
s.AppendLine(" *.exe) stem=${stem%.exe} ;;");
|
||||
s.AppendLine(" *) continue ;;");
|
||||
s.AppendLine(" esac");
|
||||
s.AppendLine(" ver=${stem%%-*}");
|
||||
s.AppendLine(" rest=${stem#*-}");
|
||||
s.AppendLine(" plat=\"${rest%-*}-${rest##*-}\"");
|
||||
s.AppendLine(" # skip other platforms entirely");
|
||||
s.AppendLine(" [ \"$plat\" != \"$NEWPLAT\" ] && continue");
|
||||
s.AppendLine(" # same platform: keep only latest version");
|
||||
s.AppendLine(" if [ \"$ver\" = \"$NEWVER\" ]; then");
|
||||
s.AppendLine(" echo \"keep: $base\"");
|
||||
s.AppendLine(" else");
|
||||
s.AppendLine(" echo \"remove (version $ver != $NEWVER): $base\"");
|
||||
s.AppendLine(" rm -rf \"$item\" 2>/dev/null");
|
||||
s.AppendLine(" fi");
|
||||
s.AppendLine("done");
|
||||
s.AppendLine();
|
||||
s.AppendLine("rm -f \"$MARKER\"");
|
||||
s.AppendLine("rm -f \"$HERE\"/*.sh 2>/dev/null");
|
||||
return s.ToString();
|
||||
}
|
||||
|
||||
private static string WindowsScript()
|
||||
{
|
||||
var s = new System.Text.StringBuilder();
|
||||
s.AppendLine("@echo off");
|
||||
s.AppendLine("chcp 65001 >nul 2>&1");
|
||||
s.AppendLine("set \"HERE=%~dp0\"");
|
||||
s.AppendLine("set \"MARKER=%~dp0update.txt\"");
|
||||
s.AppendLine("timeout /t 2 /nobreak >nul");
|
||||
s.AppendLine();
|
||||
s.AppendLine("set \"NEWNAME=\"");
|
||||
s.AppendLine("set \"NEWVER=\"");
|
||||
s.AppendLine("set \"NEWPLAT=\"");
|
||||
s.AppendLine("set \"INSTALLREL=\"");
|
||||
s.AppendLine("for /f \"tokens=2 delims==\" %%A in ('findstr /b \"NAME=\" \"%MARKER%\" 2^>nul') do set \"NEWNAME=%%A\"");
|
||||
s.AppendLine("for /f \"tokens=2 delims==\" %%A in ('findstr /b \"VERSION=\" \"%MARKER%\" 2^>nul') do set \"NEWVER=%%A\"");
|
||||
s.AppendLine("for /f \"tokens=2 delims==\" %%A in ('findstr /b \"PLATFORM=\" \"%MARKER%\" 2^>nul') do set \"NEWPLAT=%%A\"");
|
||||
s.AppendLine("for /f \"tokens=2 delims==\" %%A in ('findstr /b \"INSTALL_REL=\" \"%MARKER%\" 2^>nul') do set \"INSTALLREL=%%A\"");
|
||||
s.AppendLine("if \"%NEWNAME%\"==\"\" (echo marker incomplete, abort & del /Q \"%~f0\" >nul 2>&1 & exit /b 1)");
|
||||
s.AppendLine("if \"%INSTALLREL%\"==\"\" (echo install path missing, abort & del /Q \"%~f0\" >nul 2>&1 & exit /b 1)");
|
||||
s.AppendLine("for %%I in (\"%HERE%%INSTALLREL%\") do set \"DST=%%~fI\"");
|
||||
s.AppendLine("set \"PAYLOAD=%HERE%payload\\%NEWNAME%\"");
|
||||
s.AppendLine("if not exist \"%PAYLOAD%\" (echo new package missing, abort & del /Q \"%~f0\" >nul 2>&1 & exit /b 1)");
|
||||
s.AppendLine();
|
||||
s.AppendLine("rem move the staged package into the install directory");
|
||||
s.AppendLine("if exist \"%DST%\\%NEWNAME%\" rmdir /S /Q \"%DST%\\%NEWNAME%\" 2>nul");
|
||||
s.AppendLine("if exist \"%DST%\\%NEWNAME%\" del /Q \"%DST%\\%NEWNAME%\" 2>nul");
|
||||
s.AppendLine("move \"%PAYLOAD%\" \"%DST%\\%NEWNAME%\" >nul");
|
||||
s.AppendLine("if errorlevel 1 (echo failed to install update & exit /b 1)");
|
||||
s.AppendLine();
|
||||
s.AppendLine("rem launch new version");
|
||||
s.AppendLine("start \"\" \"%DST%\\%NEWNAME%\"");
|
||||
s.AppendLine();
|
||||
s.AppendLine("rem delete old GC-* files: SAME platform only, version != latest");
|
||||
s.AppendLine("powershell -NoProfile -ExecutionPolicy Bypass -Command \"^");
|
||||
s.AppendLine("$dst='%DST%'; $new='%NEWNAME%'; $ver='%NEWVER%'; $plat='%NEWPLAT%';^");
|
||||
s.AppendLine("Get-ChildItem -LiteralPath $dst -Filter 'GC-*' | ForEach-Object {^");
|
||||
s.AppendLine(" $n=$_.Name; if($n -eq $new){return};^");
|
||||
s.AppendLine(" $m=[regex]::Match($n,'^GC-(.+?)-([^-]+)-([^-]+)\\.(app|exe)$');^");
|
||||
s.AppendLine(" if(-not $m.Success){return};^");
|
||||
s.AppendLine(" $fver=$m.Groups[1].Value; $fplat=$m.Groups[2].Value+'-'+$m.Groups[3].Value;^");
|
||||
s.AppendLine(" if($fplat -ne $plat){return};^");
|
||||
s.AppendLine(" if($fver -eq $ver){ Write-Host \\\"keep: $n\\\" }^");
|
||||
s.AppendLine(" else { Write-Host \\\"remove: $n\\\"; Remove-Item -LiteralPath $_.FullName -Recurse -Force -ErrorAction SilentlyContinue }^");
|
||||
s.AppendLine("}\"");
|
||||
s.AppendLine();
|
||||
s.AppendLine("del /Q \"%MARKER%\" >nul 2>&1");
|
||||
s.AppendLine("del /Q \"%~f0\" >nul 2>&1");
|
||||
return s.ToString();
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- 内部工具
|
||||
|
||||
/// <summary>展平只有一个顶层目录、且不是 .app 的 zip。</summary>
|
||||
private static void FlattenStaging(string dir)
|
||||
{
|
||||
var entries = Directory.GetFileSystemEntries(dir);
|
||||
if (entries.Length != 1 || !Directory.Exists(entries[0])) return;
|
||||
var inner = entries[0];
|
||||
if (Path.GetFileName(inner).EndsWith(".app", StringComparison.OrdinalIgnoreCase)) return;
|
||||
|
||||
var flat = dir + "-flat";
|
||||
if (Directory.Exists(flat)) Directory.Delete(flat, true);
|
||||
Directory.Move(inner, flat);
|
||||
Directory.Delete(dir, true);
|
||||
Directory.Move(flat, dir);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 把 staging 里的新版搬入下载目录的 payload。
|
||||
/// 返回新版包名(GC-<版本>-<平台>.app/.exe)。
|
||||
/// </summary>
|
||||
private static string? MoveToPayload(string staging, string payload)
|
||||
{
|
||||
try
|
||||
{
|
||||
foreach (var entry in Directory.GetFileSystemEntries(staging))
|
||||
{
|
||||
var name = Path.GetFileName(entry);
|
||||
if (string.Equals(name, ".GC", StringComparison.OrdinalIgnoreCase)) continue;
|
||||
var dest = Path.Combine(payload, name);
|
||||
|
||||
if (Directory.Exists(dest)) Directory.Delete(dest, true);
|
||||
else if (File.Exists(dest)) File.Delete(dest);
|
||||
|
||||
if (Directory.Exists(entry)) Directory.Move(entry, dest);
|
||||
else File.Move(entry, dest);
|
||||
|
||||
// 保证 .app 里可执行文件可执行
|
||||
if (name.EndsWith(".app", StringComparison.OrdinalIgnoreCase) && Directory.Exists(dest))
|
||||
{
|
||||
var macOs = Path.Combine(dest, "Contents", "MacOS");
|
||||
if (Directory.Exists(macOs))
|
||||
{
|
||||
try
|
||||
{
|
||||
foreach (var f in Directory.GetFiles(macOs, "*", SearchOption.TopDirectoryOnly))
|
||||
{
|
||||
var mode = File.GetUnixFileMode(f);
|
||||
File.SetUnixFileMode(f, mode | UnixFileMode.UserExecute);
|
||||
}
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
return name;
|
||||
}
|
||||
if (name.EndsWith(".exe", StringComparison.OrdinalIgnoreCase)) return name;
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.Error.WriteLine($"安装新版失败: {ex.Message}");
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private static string? ReadMarker(string file, string key)
|
||||
{
|
||||
try
|
||||
{
|
||||
foreach (var line in File.ReadAllLines(file))
|
||||
{
|
||||
if (line.StartsWith(key + "=", StringComparison.Ordinal))
|
||||
return line[(key.Length + 1)..].Trim();
|
||||
}
|
||||
}
|
||||
catch { }
|
||||
return null;
|
||||
}
|
||||
|
||||
private static string Safe(string value)
|
||||
{
|
||||
foreach (var c in Path.GetInvalidFileNameChars()) value = value.Replace(c, '-');
|
||||
return value.Replace('/', '-').Replace(' ', '-');
|
||||
}
|
||||
}
|
||||
@@ -2,9 +2,9 @@ using System;
|
||||
using System.IO;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using EarthModelStudio.Models;
|
||||
using GC.Models;
|
||||
|
||||
namespace EarthModelStudio.Services;
|
||||
namespace GC.Services;
|
||||
|
||||
public static class ModelInstaller
|
||||
{
|
||||
@@ -7,16 +7,16 @@ using System.Linq;
|
||||
using System.Net.Http;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using EarthModelStudio.Models;
|
||||
using GC.Models;
|
||||
|
||||
namespace EarthModelStudio.Services;
|
||||
namespace GC.Services;
|
||||
|
||||
/// <summary>
|
||||
/// 从链接导入模型源。
|
||||
/// 支持:git 仓库地址(GitHub / GitLab / Gitee / 任意 git 地址)、zip 直链、本地目录。
|
||||
/// 仓库里的 model/ 目录就是模型列表;下载后缓存到 cache/sources/<id>。
|
||||
/// 仓库里的 model/ 目录就是模型列表;下载后缓存在应用缓存目录。
|
||||
/// </summary>
|
||||
public sealed class ModelSourceClient
|
||||
public sealed class ModelSourceClient : IModelSourceClient
|
||||
{
|
||||
private readonly AppPaths _paths;
|
||||
private static readonly HttpClient Http = CreateHttp();
|
||||
@@ -26,7 +26,7 @@ public sealed class ModelSourceClient
|
||||
private static HttpClient CreateHttp()
|
||||
{
|
||||
var client = new HttpClient { Timeout = TimeSpan.FromMinutes(5) };
|
||||
client.DefaultRequestHeaders.UserAgent.ParseAdd("EarthModelStudio/1.0 (+model-source)");
|
||||
client.DefaultRequestHeaders.UserAgent.ParseAdd("GC/1.0 (+model-source)");
|
||||
return client;
|
||||
}
|
||||
|
||||
@@ -215,11 +215,64 @@ public sealed class ModelSourceClient
|
||||
}
|
||||
}
|
||||
|
||||
var args = new List<string> { "clone", "--depth", "1" };
|
||||
if (!string.IsNullOrWhiteSpace(branch)) { args.Add("--branch"); args.Add(branch!); }
|
||||
args.Add(url);
|
||||
args.Add(cacheDir);
|
||||
// 只拉取 model/ 目录:整仓 clone 会把 .git / src / dist 一起拖下来
|
||||
// (实测 700MB+),既慢又容易超时,表现就是「读不到模型源」。
|
||||
// 先浅克隆到临时目录,再用 sparse-checkout 只检出 model/。
|
||||
var tmpDir = cacheDir + ".tmp";
|
||||
try
|
||||
{
|
||||
if (Directory.Exists(tmpDir)) Directory.Delete(tmpDir, true);
|
||||
|
||||
// 1) 初始化 + 加远程(比 clone 更快,避免先拉全量)
|
||||
var initArgs = new List<string> { "init", "--quiet", tmpDir };
|
||||
if (!await RunGitAsync(initArgs, ct)) return false;
|
||||
|
||||
var remoteArgs = new List<string> { "-C", tmpDir, "remote", "add", "origin", url };
|
||||
if (!await RunGitAsync(remoteArgs, ct)) return false;
|
||||
|
||||
// 2) 只允许 model 目录参与检出
|
||||
await RunGitAsync(new List<string> { "-C", tmpDir, "config", "core.sparseCheckout", "true" }, ct);
|
||||
var sparseFile = Path.Combine(tmpDir, ".git", "info", "sparse-checkout");
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(sparseFile)!);
|
||||
File.WriteAllText(sparseFile, "model/\n");
|
||||
|
||||
// 3) 浅拉指定分支
|
||||
var branchName = string.IsNullOrWhiteSpace(branch) ? "main" : branch!;
|
||||
var fetchArgs = new List<string>
|
||||
{
|
||||
"-C", tmpDir, "fetch", "--depth", "1", "--filter=blob:none", "origin", branchName
|
||||
};
|
||||
if (!await RunGitAsync(fetchArgs, ct)) return false;
|
||||
|
||||
await RunGitAsync(new List<string> { "-C", tmpDir, "checkout", "FETCH_HEAD" }, ct);
|
||||
|
||||
// 4) 把 model/ 移到缓存根,与原有目录结构一致
|
||||
var modelDir = Path.Combine(tmpDir, "model");
|
||||
if (!Directory.Exists(modelDir))
|
||||
{
|
||||
Console.Error.WriteLine("git sparse-checkout 后未找到 model/ 目录");
|
||||
return false;
|
||||
}
|
||||
|
||||
if (Directory.Exists(cacheDir)) Directory.Delete(cacheDir, true);
|
||||
Directory.CreateDirectory(cacheDir);
|
||||
Directory.Move(modelDir, Path.Combine(cacheDir, "model"));
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.Error.WriteLine($"git 拉取异常: {ex.Message}");
|
||||
return false;
|
||||
}
|
||||
finally
|
||||
{
|
||||
try { if (Directory.Exists(tmpDir)) Directory.Delete(tmpDir, true); } catch { }
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>安静地跑一条 git 命令,返回是否成功。</summary>
|
||||
private static async Task<bool> RunGitAsync(List<string> args, CancellationToken ct)
|
||||
{
|
||||
try
|
||||
{
|
||||
var psi = new ProcessStartInfo("git")
|
||||
@@ -233,19 +286,16 @@ public sealed class ModelSourceClient
|
||||
|
||||
using var process = Process.Start(psi);
|
||||
if (process == null) return false;
|
||||
var stderrTask = process.StandardError.ReadToEndAsync(ct);
|
||||
var errTask = process.StandardError.ReadToEndAsync(ct);
|
||||
await process.WaitForExitAsync(ct);
|
||||
var stderr = await stderrTask;
|
||||
var err = await errTask;
|
||||
if (process.ExitCode != 0)
|
||||
{
|
||||
Console.Error.WriteLine($"git clone 失败: {stderr}");
|
||||
return false;
|
||||
}
|
||||
return Directory.Exists(Path.Combine(cacheDir, "model")) || Directory.Exists(cacheDir);
|
||||
Console.Error.WriteLine($"git {string.Join(' ', args)} 失败: {err.Trim()}");
|
||||
return process.ExitCode == 0;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.Error.WriteLine($"git clone 异常: {ex.Message}");
|
||||
Console.Error.WriteLine($"git 执行失败: {ex.Message}");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
|
||||
namespace GC.Services;
|
||||
|
||||
/// <summary>
|
||||
/// 找到并启动 GC-SAVEDOG(启动器更新的守护进程)。
|
||||
///
|
||||
/// 为什么要独立进程:启动器正在运行时无法安全覆盖自己;一旦覆盖失败,
|
||||
/// 启动器已退出,就没人能回滚。把"替换 + 看护"交给一个只做这件事的小程序,
|
||||
/// 风险面被压缩到最小,也便于审计。
|
||||
/// </summary>
|
||||
public static class SavedogLauncher
|
||||
{
|
||||
/// <summary>在安装目录里寻找 SAVEDOG 可执行文件。</summary>
|
||||
public static string? Find(AppPaths paths)
|
||||
{
|
||||
var name = SavedogFiles.ExecutableName;
|
||||
var install = paths.InstallDirectory;
|
||||
|
||||
var direct = Path.Combine(install, name);
|
||||
if (File.Exists(direct)) return direct;
|
||||
|
||||
// macOS:可能放在 .app 内部
|
||||
try
|
||||
{
|
||||
foreach (var app in Directory.GetDirectories(install, "*.app"))
|
||||
{
|
||||
var inside = Path.Combine(app, "Contents", "MacOS", name);
|
||||
if (File.Exists(inside)) return inside;
|
||||
}
|
||||
}
|
||||
catch { }
|
||||
|
||||
var bin = Path.Combine(paths.HomeRoot, "bin", name);
|
||||
if (File.Exists(bin)) return bin;
|
||||
|
||||
try
|
||||
{
|
||||
var exe = Environment.ProcessPath;
|
||||
if (!string.IsNullOrWhiteSpace(exe))
|
||||
{
|
||||
var beside = Path.Combine(Path.GetDirectoryName(exe)!, name);
|
||||
if (File.Exists(beside)) return beside;
|
||||
}
|
||||
}
|
||||
catch { }
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 启动 SAVEDOG 应用更新。<paramref name="waitForPid"/> 是当前启动器进程,
|
||||
/// SAVEDOG 会等它退出后再动文件。
|
||||
/// </summary>
|
||||
public static bool TryStart(AppPaths paths, int waitForPid, out string? error)
|
||||
{
|
||||
error = null;
|
||||
var exe = Find(paths);
|
||||
if (exe == null)
|
||||
{
|
||||
error = "未找到 GC-SAVEDOG";
|
||||
return false;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
var requestPath = Path.Combine(paths.UpdateRoot, SavedogFiles.ApplyRequest);
|
||||
if (!File.Exists(requestPath))
|
||||
{
|
||||
error = "缺少 apply-request.json";
|
||||
return false;
|
||||
}
|
||||
|
||||
var psi = new ProcessStartInfo(exe)
|
||||
{
|
||||
UseShellExecute = false,
|
||||
CreateNoWindow = true,
|
||||
WorkingDirectory = paths.InstallDirectory
|
||||
};
|
||||
psi.ArgumentList.Add("apply");
|
||||
psi.ArgumentList.Add("--update");
|
||||
psi.ArgumentList.Add(paths.UpdateRoot);
|
||||
psi.ArgumentList.Add("--install");
|
||||
psi.ArgumentList.Add(paths.InstallDirectory);
|
||||
psi.ArgumentList.Add("--wait-pid");
|
||||
psi.ArgumentList.Add(waitForPid.ToString());
|
||||
psi.ArgumentList.Add("--timeout");
|
||||
psi.ArgumentList.Add("45");
|
||||
|
||||
if (!OperatingSystem.IsWindows())
|
||||
{
|
||||
try
|
||||
{
|
||||
var mode = File.GetUnixFileMode(exe);
|
||||
File.SetUnixFileMode(exe, mode | UnixFileMode.UserExecute);
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
|
||||
Process.Start(psi);
|
||||
Console.WriteLine($"[update] GC-SAVEDOG 已启动: {exe}");
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
error = ex.Message;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>读取 SAVEDOG 最近一次的执行结果(供界面展示)。</summary>
|
||||
public static SavedogState? ReadState(AppPaths paths)
|
||||
=> Json.Read<SavedogState>(Path.Combine(paths.UpdateRoot, SavedogFiles.State));
|
||||
|
||||
/// <summary>上次成功启动的版本(回滚依据)。</summary>
|
||||
public static LastGoodVersion? ReadLastGood(AppPaths paths)
|
||||
=> Json.Read<LastGoodVersion>(Path.Combine(paths.UpdateRoot, SavedogFiles.LastGood));
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.Linq;
|
||||
using System.Net.Http;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace GC.Services;
|
||||
|
||||
/// <summary>
|
||||
/// 双源选择:Xhmcl 与 GitCode 是同一份仓库的两个镜像。
|
||||
///
|
||||
/// 启动更新 / 下载页面 / 检查更新时,先并发探测两边的 version.json 响应时间,
|
||||
/// 取**最快且内容可用**的那个作为本次下载源;探测结果缓存一段时间,
|
||||
/// 避免每次点下载都重新测速。
|
||||
/// </summary>
|
||||
public sealed class SourceSelector : ISourceSelector
|
||||
{
|
||||
private static readonly HttpClient Http = CreateHttp();
|
||||
|
||||
private static HttpClient CreateHttp()
|
||||
{
|
||||
var c = new HttpClient { Timeout = TimeSpan.FromSeconds(6) };
|
||||
c.DefaultRequestHeaders.UserAgent.ParseAdd("GC-Probe/1.0");
|
||||
return c;
|
||||
}
|
||||
|
||||
private readonly object _lock = new();
|
||||
private SourcePreset? _cached;
|
||||
private DateTime _cachedAt = DateTime.MinValue;
|
||||
private readonly TimeSpan _ttl = TimeSpan.FromMinutes(3);
|
||||
|
||||
/// <summary>最近一次选中的源(未探测时为空)。</summary>
|
||||
public SourcePreset? Current { get { lock (_lock) return _cached; } }
|
||||
|
||||
/// <summary>每个源的探测耗时(毫秒),供界面展示。</summary>
|
||||
public IReadOnlyDictionary<string, long> LastLatency { get; private set; } =
|
||||
new Dictionary<string, long>();
|
||||
|
||||
/// <summary>
|
||||
/// 探测两个源并返回最快的。force=true 时忽略缓存。
|
||||
/// 两个都失败时返回 GitCode(默认源)。
|
||||
/// </summary>
|
||||
public async Task<SourcePreset> PickFastestAsync(bool force = false, CancellationToken ct = default)
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
if (!force && _cached != null && DateTime.UtcNow - _cachedAt < _ttl)
|
||||
return _cached;
|
||||
}
|
||||
|
||||
var probes = SourcePreset.All.Select(async p =>
|
||||
{
|
||||
var sw = Stopwatch.StartNew();
|
||||
var ok = await ProbeAsync(p, ct);
|
||||
sw.Stop();
|
||||
return (Preset: p, Ok: ok, Ms: sw.ElapsedMilliseconds);
|
||||
});
|
||||
|
||||
var results = await Task.WhenAll(probes);
|
||||
|
||||
var latencies = results.ToDictionary(r => r.Preset.Id, r => r.Ms);
|
||||
LastLatency = latencies;
|
||||
|
||||
var usable = results.Where(r => r.Ok).OrderBy(r => r.Ms).ToList();
|
||||
var chosen = usable.Count > 0 ? usable[0].Preset : SourcePreset.GitCode;
|
||||
|
||||
lock (_lock)
|
||||
{
|
||||
_cached = chosen;
|
||||
_cachedAt = DateTime.UtcNow;
|
||||
}
|
||||
|
||||
Console.WriteLine("[selector] 测速:" + string.Join(" ",
|
||||
results.Select(r => $"{r.Preset.Name}={r.Ms}ms{(r.Ok ? "" : "(不可用)")}"))
|
||||
+ $" → 选择 {chosen.Name}");
|
||||
|
||||
return chosen;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 探测:能拿到合法 JSON 才算可用。
|
||||
/// 注意两个平台取文件的方式不同:
|
||||
/// · Gitea(Xhmcl):raw/branch/{b}/{path} 直接返回文件内容
|
||||
/// · GitCode:raw 地址返回的是 HTML 页面,必须走 API(内容为 base64)
|
||||
/// 因此 GitCode 用 api/v5 contents + Accept: application/json 探测。
|
||||
/// </summary>
|
||||
private static async Task<bool> ProbeAsync(SourcePreset preset, CancellationToken ct)
|
||||
{
|
||||
if (preset.Kind == "gitcode")
|
||||
{
|
||||
try
|
||||
{
|
||||
using var cts = CancellationTokenSource.CreateLinkedTokenSource(ct);
|
||||
cts.CancelAfter(TimeSpan.FromSeconds(5));
|
||||
var api = $"{preset.ApiBase}/repos/{preset.Owner}/{preset.Repo}/contents/version.json?ref={preset.Branch}";
|
||||
using var req = new HttpRequestMessage(HttpMethod.Get, api);
|
||||
req.Headers.Accept.ParseAdd("application/json");
|
||||
using var resp = await Http.SendAsync(req, cts.Token);
|
||||
if (!resp.IsSuccessStatusCode) return false;
|
||||
var text = await resp.Content.ReadAsStringAsync(cts.Token);
|
||||
return text.TrimStart().StartsWith('{');
|
||||
}
|
||||
catch { return false; }
|
||||
}
|
||||
|
||||
var urls = new[] { preset.RawUrl("version.json"), preset.RawUrl("model/version.json") };
|
||||
|
||||
foreach (var url in urls)
|
||||
{
|
||||
try
|
||||
{
|
||||
using var cts = CancellationTokenSource.CreateLinkedTokenSource(ct);
|
||||
cts.CancelAfter(TimeSpan.FromSeconds(5));
|
||||
var text = await Http.GetStringAsync(url, cts.Token);
|
||||
if (text.TrimStart().StartsWith('{')) return true;
|
||||
}
|
||||
catch { /* 换下一个地址 */ }
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>为指定源创建对应的 remote 实现。</summary>
|
||||
public static IModelRemote CreateRemote(SourcePreset preset) => preset.Kind switch
|
||||
{
|
||||
"gitea" => new GiteaRemote(preset),
|
||||
_ => new GitCodeReleaseRemote(null, preset.HomeUrl)
|
||||
};
|
||||
}
|
||||
@@ -8,22 +8,20 @@ using System.Runtime.InteropServices;
|
||||
using System.Security.Cryptography;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using EarthModelStudio.Models;
|
||||
using GC.Models;
|
||||
|
||||
namespace EarthModelStudio.Services;
|
||||
namespace GC.Services;
|
||||
|
||||
/// <summary>
|
||||
/// 启动时的自动更新:
|
||||
/// · 读远端 version.json,和 .GC/settings.json 里记录的版本比较;
|
||||
/// · 模型:下载到 cache 后原子替换 .GC/model/<id>,结果立刻刷新列表(本次启动生效);
|
||||
/// · 启动器:下载到 .GC/update/payload 并写 pending.json,下次启动才应用;
|
||||
/// · 任何失败都保留本地已装模型,绝不把模型库清空。
|
||||
/// 模型自动更新:读远端版本清单,把缺失/过期的模型下载到 cache 后原子替换
|
||||
/// .GC/model/<id>,本次启动立即生效。任何失败都保留本地已装模型。
|
||||
/// 启动器更新由 LauncherUpdater / LauncherUpdateFlow 独立负责,不在这里。
|
||||
/// </summary>
|
||||
public sealed class UpdateService
|
||||
public sealed class UpdateService : IUpdateService
|
||||
{
|
||||
private readonly AppPaths _paths;
|
||||
private readonly SettingsService _settings;
|
||||
private readonly IModelRemote _remote;
|
||||
private IModelRemote _remote;
|
||||
|
||||
public UpdateService(AppPaths paths, SettingsService settings, IModelRemote remote)
|
||||
{
|
||||
@@ -34,54 +32,44 @@ public sealed class UpdateService
|
||||
|
||||
public IModelRemote Remote => _remote;
|
||||
|
||||
public static string CurrentLauncherVersion
|
||||
{
|
||||
get
|
||||
{
|
||||
var v = Assembly.GetEntryAssembly()?.GetName().Version;
|
||||
if (v == null) return "0.0.0";
|
||||
return $"{Math.Max(0, v.Major)}.{Math.Max(0, v.Minor)}.{Math.Max(0, v.Build)}";
|
||||
}
|
||||
}
|
||||
|
||||
public static string CurrentRid
|
||||
{
|
||||
get
|
||||
{
|
||||
var arch = RuntimeInformation.OSArchitecture switch
|
||||
{
|
||||
Architecture.Arm64 => "arm64",
|
||||
Architecture.X86 => "x86",
|
||||
_ => "x64"
|
||||
};
|
||||
if (OperatingSystem.IsWindows()) return "win-" + arch;
|
||||
if (OperatingSystem.IsMacOS()) return "osx-" + arch;
|
||||
if (OperatingSystem.IsLinux()) return "linux-" + arch;
|
||||
return RuntimeInformation.RuntimeIdentifier;
|
||||
}
|
||||
}
|
||||
/// <summary>换源:测速选出最快的一个后,用它的 remote 覆盖当前实例。</summary>
|
||||
public void UseRemote(IModelRemote remote) => _remote = remote;
|
||||
|
||||
/// <summary>
|
||||
/// 同步版本(无法测速时用):按设置里的仓库地址映射到内置源。
|
||||
/// 真正带测速的入口是 <see cref="CreateRemoteAsync"/>。
|
||||
/// </summary>
|
||||
public static IModelRemote CreateRemote(AppSettings settings)
|
||||
{
|
||||
if (!string.IsNullOrWhiteSpace(settings.UpdateLocalRoot) &&
|
||||
Directory.Exists(settings.UpdateLocalRoot!))
|
||||
return new DirectoryRemote(settings.UpdateLocalRoot!); // 离线 U 盘源:仍读本地 version.json
|
||||
// 在线源:启动器版本与发布包走 GitCode Release(tag + 附件),
|
||||
// 模型清单/文件仍走仓库 contents API;无 Release 时自动回退仓库 version.json。
|
||||
return new GitCodeReleaseRemote(settings.UpdateManifestUrl, settings.UpdateRepository);
|
||||
return new DirectoryRemote(settings.UpdateLocalRoot!);
|
||||
return SourceSelector.CreateRemote(SourcePreset.Detect(settings.UpdateRepository));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 异步版本:先探测 Xhmcl / GitCode 两个源,取最快的那个。
|
||||
/// 启动更新、下载页、检查更新统一走这里,保证「用同一个源、同一种下载方式」。
|
||||
/// </summary>
|
||||
public static async Task<IModelRemote> CreateRemoteAsync(AppSettings settings,
|
||||
SourceSelector selector, bool forceProbe = false, CancellationToken ct = default)
|
||||
{
|
||||
if (!string.IsNullOrWhiteSpace(settings.UpdateLocalRoot) &&
|
||||
Directory.Exists(settings.UpdateLocalRoot!))
|
||||
return new DirectoryRemote(settings.UpdateLocalRoot!);
|
||||
|
||||
var preset = await selector.PickFastestAsync(forceProbe, ct);
|
||||
return SourceSelector.CreateRemote(preset);
|
||||
}
|
||||
|
||||
public async Task<UpdateResult> RunAsync(bool force,
|
||||
IProgress<UpdateProgress>? progress, CancellationToken ct = default)
|
||||
{
|
||||
// 开发态的 model/ 里有源码与工程文件,自动更新一律跳过,避免把源码目录整体替换掉。
|
||||
// 需要验证更新链路请用 ./build.sh update-test(它使用临时目录,不碰仓库)。
|
||||
if (_paths.IsDevelopment && Environment.GetEnvironmentVariable("EMS_DEV_UPDATE") != "1")
|
||||
return new UpdateResult
|
||||
{
|
||||
Outcome = UpdateOutcome.Disabled,
|
||||
Message = "开发态跳过自动更新(保护仓库内模型源码)"
|
||||
};
|
||||
// 开发态的 model/ 里有源码与工程文件,模型自动替换会破坏源码目录,
|
||||
// 因此开发态只做「启动器版本检查」(下载到 .GC/update 暂存,可验证链路),
|
||||
// 跳过模型替换。要用正式流程验证请跑 ./build.sh update-test。
|
||||
var devMode = _paths.IsDevelopment &&
|
||||
Environment.GetEnvironmentVariable("EMS_DEV_UPDATE") != "1";
|
||||
|
||||
if (!force && !_settings.Current.AutoUpdateOnStartup)
|
||||
return new UpdateResult { Outcome = UpdateOutcome.Disabled, Message = L.I["update.disabled"] };
|
||||
@@ -116,10 +104,49 @@ public sealed class UpdateService
|
||||
Message = L.I["update.noManifest"]
|
||||
};
|
||||
|
||||
// ---- 清单信任策略 --------------------------------------------------
|
||||
// 签名有效 → 通过;没有签名 / 签名不符 → 默认拒绝(可用设置或环境变量放开)。
|
||||
// 这一道闸门挡住的是「仓库被改、模型 dll 被换成木马」这类攻击。
|
||||
var allowUnsigned = devMode ||
|
||||
!_settings.Current.RequireSignedManifest ||
|
||||
Environment.GetEnvironmentVariable("GC_ALLOW_UNSIGNED_MANIFEST") == "1";
|
||||
|
||||
if (!remote.IsTrusted)
|
||||
{
|
||||
var reason = remote.SignatureTrust == nameof(ManifestTrust.Invalid)
|
||||
? "清单签名无效(内容可能被篡改)"
|
||||
: "清单未签名";
|
||||
|
||||
if (!allowUnsigned)
|
||||
{
|
||||
Console.Error.WriteLine($"[update] {reason},已拒绝本次更新");
|
||||
return new UpdateResult
|
||||
{
|
||||
Outcome = UpdateOutcome.Unavailable,
|
||||
Message = $"{reason},已拒绝更新",
|
||||
Error = remote.SignatureError
|
||||
};
|
||||
}
|
||||
|
||||
Console.Error.WriteLine($"[update] {reason},当前为开发/放宽模式,继续");
|
||||
}
|
||||
else
|
||||
{
|
||||
Console.WriteLine($"[update] 清单验签通过({remote.SignatureKeyId})");
|
||||
}
|
||||
|
||||
_settings.Current.LastUpdateCheck = DateTime.UtcNow.ToString("O");
|
||||
_settings.Save();
|
||||
|
||||
var needed = remote.Models.Where(NeedsModel).ToList();
|
||||
// 启动器更新由 LauncherUpdater / LauncherUpdateFlow 独立负责,
|
||||
// 这里只做「模型同步到最新版」。
|
||||
string? launcherMessage = null;
|
||||
|
||||
// ---- 同步所有模型到最新版 ----
|
||||
// 开发态跳过:仓库 model/ 里有源码,整体替换会破坏工程目录。
|
||||
var needed = devMode
|
||||
? new List<RepoModel>()
|
||||
: remote.Models.Where(NeedsModel).ToList();
|
||||
var updated = new List<string>();
|
||||
var errors = new List<string>();
|
||||
|
||||
@@ -147,18 +174,6 @@ public sealed class UpdateService
|
||||
}
|
||||
}
|
||||
|
||||
string? launcherMessage = null;
|
||||
try
|
||||
{
|
||||
launcherMessage = await StageLauncherAsync(remote.Launcher, progress, ct);
|
||||
}
|
||||
catch (OperationCanceledException) { throw; }
|
||||
catch (Exception ex)
|
||||
{
|
||||
launcherMessage = L.I.F("update.launcherFailed", ex.Message);
|
||||
errors.Add("launcher: " + ex.Message);
|
||||
}
|
||||
|
||||
progress?.Report(new UpdateProgress { Value = 1, Message = L.I["update.done"] });
|
||||
|
||||
var outcome = errors.Count > 0
|
||||
@@ -169,7 +184,11 @@ public sealed class UpdateService
|
||||
|
||||
var message = updated.Count > 0
|
||||
? L.I.F("update.applied", updated.Count)
|
||||
: launcherMessage != null ? L.I["update.modelsLatest"] : L.I["update.noChange"];
|
||||
: launcherMessage != null
|
||||
? L.I["update.modelsLatest"]
|
||||
: devMode
|
||||
? "开发态:已检查启动器,模型替换已跳过(保护仓库源码)"
|
||||
: L.I["update.noChange"];
|
||||
if (errors.Count > 0) message += L.I.F("update.partial", errors.Count);
|
||||
|
||||
return new UpdateResult
|
||||
@@ -222,30 +241,59 @@ public sealed class UpdateService
|
||||
try
|
||||
{
|
||||
var total = files.Sum(f => Math.Max(1L, f.Size));
|
||||
// 并行下载:模型包通常有几十个文件,串行下载会明显拖慢启动。
|
||||
// 并发上限 6,避免被服务端限流;进度用原子计数汇总。
|
||||
long done = 0;
|
||||
foreach (var entry in files)
|
||||
var stagingFull = Path.GetFullPath(staging)
|
||||
.TrimEnd(Path.DirectorySeparatorChar) + Path.DirectorySeparatorChar;
|
||||
using var gate = new SemaphoreSlim(6);
|
||||
|
||||
var tasks = files.Select(async entry =>
|
||||
{
|
||||
await gate.WaitAsync(ct);
|
||||
try
|
||||
{
|
||||
ct.ThrowIfCancellationRequested();
|
||||
var bytes = await _remote.DownloadAsync(entry, ct);
|
||||
// 路径穿越防护:规范化后必须仍落在 staging 目录内,
|
||||
// 防止远端清单里的 "../" 或绝对路径写进安装目录之外。
|
||||
|
||||
// 路径穿越防护
|
||||
var dest = Path.GetFullPath(Path.Combine(staging,
|
||||
entry.RelativePath.Replace('/', Path.DirectorySeparatorChar)));
|
||||
var stagingFull = Path.GetFullPath(staging)
|
||||
.TrimEnd(Path.DirectorySeparatorChar) + Path.DirectorySeparatorChar;
|
||||
if (!dest.StartsWith(stagingFull, StringComparison.OrdinalIgnoreCase))
|
||||
throw new InvalidOperationException($"非法的模型文件路径: {entry.RelativePath}");
|
||||
|
||||
var destDir = Path.GetDirectoryName(dest);
|
||||
if (!string.IsNullOrEmpty(destDir)) Directory.CreateDirectory(destDir);
|
||||
await File.WriteAllBytesAsync(dest, bytes, ct);
|
||||
done += bytes.Length;
|
||||
|
||||
var now = Interlocked.Add(ref done, bytes.Length);
|
||||
progress?.Report(new UpdateProgress
|
||||
{
|
||||
Value = 0.05 + 0.72 * (index + Math.Min(1, (double)done / Math.Max(1, total))) / Math.Max(1, count),
|
||||
Value = 0.05 + 0.72 * (index + Math.Min(1, (double)now / Math.Max(1, total))) / Math.Max(1, count),
|
||||
Message = L.I.F("update.downloadingModel", model.Id),
|
||||
Detail = entry.RelativePath
|
||||
});
|
||||
}
|
||||
finally { gate.Release(); }
|
||||
});
|
||||
|
||||
await Task.WhenAll(tasks);
|
||||
|
||||
// ---- 完整性校验:清单是签过名的,里面的哈希就是"正版"的定义 --------
|
||||
// 下载到暂存目录后按同一算法复算,不一致直接丢弃,绝不安装。
|
||||
var computed = ModelIntegrity.Compute(staging, model.Id);
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(model.ManifestSha256) &&
|
||||
!string.Equals(computed.ManifestSha256, model.ManifestSha256,
|
||||
StringComparison.OrdinalIgnoreCase))
|
||||
throw new InvalidOperationException(
|
||||
$"模型清单哈希不符(期望 {Short(model.ManifestSha256)},实际 {Short(computed.ManifestSha256)})");
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(model.FilesSha256) &&
|
||||
!string.Equals(computed.FilesSha256, model.FilesSha256,
|
||||
StringComparison.OrdinalIgnoreCase))
|
||||
throw new InvalidOperationException(
|
||||
$"模型文件哈希不符(期望 {Short(model.FilesSha256)},实际 {Short(computed.FilesSha256)}),已丢弃");
|
||||
|
||||
// 原子替换:先备份旧目录,成功后再删备份;失败自动回滚
|
||||
Directory.CreateDirectory(_paths.ModelRoot);
|
||||
@@ -269,6 +317,25 @@ public sealed class UpdateService
|
||||
{
|
||||
try { Directory.Delete(backup, true); } catch { /* 占用时留到下次 */ }
|
||||
}
|
||||
|
||||
// 安装成功:把完整性记录写进模型目录,加载 dll 前会再抽查一次
|
||||
try
|
||||
{
|
||||
ModelIntegrity.Write(target, model.Id, new ModelIntegrityFile
|
||||
{
|
||||
Id = model.Id,
|
||||
Version = model.Version,
|
||||
ManifestSha256 = computed.ManifestSha256,
|
||||
FilesSha256 = computed.FilesSha256,
|
||||
Files = computed.Files,
|
||||
InstalledAt = DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ssZ"),
|
||||
Source = _remote.DisplayName
|
||||
});
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.Error.WriteLine($"写入完整性记录失败 {model.Id}: {ex.Message}");
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
@@ -277,91 +344,12 @@ public sealed class UpdateService
|
||||
}
|
||||
}
|
||||
|
||||
private async Task<string?> StageLauncherAsync(RepoLauncher launcher,
|
||||
IProgress<UpdateProgress>? progress, CancellationToken ct)
|
||||
{
|
||||
var current = CurrentLauncherVersion;
|
||||
var pending = _settings.Current.PendingLauncherVersion;
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(pending) &&
|
||||
string.Equals(pending, launcher.Version, StringComparison.OrdinalIgnoreCase))
|
||||
return L.I.F("update.pendingReady", launcher.Version);
|
||||
|
||||
if (!IsNewer(launcher.Version, current)) return null;
|
||||
|
||||
var rid = CurrentRid;
|
||||
if (!launcher.Packages.TryGetValue(rid, out var package) &&
|
||||
!launcher.Packages.TryGetValue("default", out package))
|
||||
return L.I.F("update.noRidPackage", launcher.Version, rid);
|
||||
|
||||
progress?.Report(new UpdateProgress
|
||||
{
|
||||
Value = 0.85,
|
||||
Message = L.I.F("update.downloadingLauncher", launcher.Version)
|
||||
});
|
||||
|
||||
var bytes = await _remote.DownloadPackageAsync(package!, ct);
|
||||
if (bytes == null || bytes.Length == 0)
|
||||
return L.I.F("update.noPackageUrl", launcher.Version);
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(package!.Sha256))
|
||||
{
|
||||
var actual = Convert.ToHexString(SHA256.HashData(bytes)).ToLowerInvariant();
|
||||
if (!string.Equals(actual, package.Sha256!.Trim(), StringComparison.OrdinalIgnoreCase))
|
||||
throw new InvalidOperationException("启动器包校验失败(sha256 不符)");
|
||||
}
|
||||
|
||||
Directory.CreateDirectory(_paths.UpdateRoot);
|
||||
var payload = Path.Combine(_paths.UpdateRoot, "payload");
|
||||
if (Directory.Exists(payload)) Directory.Delete(payload, true);
|
||||
var zip = Path.Combine(_paths.CacheRoot, "launcher-" + Safe(launcher.Version) + ".zip");
|
||||
await File.WriteAllBytesAsync(zip, bytes, ct);
|
||||
try
|
||||
{
|
||||
ZipSafety.ExtractToDirectory(zip, payload);
|
||||
}
|
||||
finally
|
||||
{
|
||||
try { File.Delete(zip); } catch { }
|
||||
}
|
||||
FlattenPayload(payload);
|
||||
|
||||
Json.Write(Path.Combine(_paths.UpdateRoot, "pending.json"), new PendingUpdate
|
||||
{
|
||||
Version = launcher.Version,
|
||||
Rid = rid,
|
||||
InstallDirectory = _paths.InstallDirectory,
|
||||
Executable = Path.GetFileName(Environment.ProcessPath ?? ""),
|
||||
Payload = "payload",
|
||||
DownloadedAt = DateTime.UtcNow.ToString("O")
|
||||
});
|
||||
|
||||
_settings.Current.PendingLauncherVersion = launcher.Version;
|
||||
_settings.Save();
|
||||
return L.I.F("update.pendingDownloaded", launcher.Version);
|
||||
}
|
||||
|
||||
private static void FlattenPayload(string dir)
|
||||
{
|
||||
var entries = Directory.GetFileSystemEntries(dir);
|
||||
if (entries.Length != 1 || !Directory.Exists(entries[0])) return;
|
||||
var inner = entries[0];
|
||||
var flat = dir + "-flat";
|
||||
if (Directory.Exists(flat)) Directory.Delete(flat, true);
|
||||
Directory.Move(inner, flat);
|
||||
Directory.Delete(dir, true);
|
||||
Directory.Move(flat, dir);
|
||||
}
|
||||
|
||||
private static bool IsNewer(string remote, string local)
|
||||
{
|
||||
if (Version.TryParse(remote, out var r) && Version.TryParse(local, out var l)) return r > l;
|
||||
return !string.Equals(remote, local, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
private static string Safe(string value)
|
||||
{
|
||||
foreach (var c in Path.GetInvalidFileNameChars()) value = value.Replace(c, '-');
|
||||
return value.Replace('/', '-').Replace(' ', '-');
|
||||
}
|
||||
|
||||
private static string Short(string? hash)
|
||||
=> string.IsNullOrEmpty(hash) ? "(空)" : hash!.Length <= 8 ? hash : hash[..8];
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
using System;
|
||||
using System.Globalization;
|
||||
|
||||
namespace GC.Services;
|
||||
|
||||
/// <summary>
|
||||
/// 版本号工具:Release tag 有 v1.0.6 / GC-1.0.6 / 1.0.6 等写法,
|
||||
/// 统一成可比较的 Version 再排序,挑**版本号最高**的那个。
|
||||
/// </summary>
|
||||
public static class VersionUtil
|
||||
{
|
||||
/// <summary>把 tag 规整成 "1.0.6" 这样的纯数字版本。</summary>
|
||||
public static string Normalize(string? tag)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(tag)) return "";
|
||||
var s = tag!.Trim();
|
||||
|
||||
// 去掉前缀:v / V / GC- / release-
|
||||
if (s.StartsWith("GC-", StringComparison.OrdinalIgnoreCase)) s = s[3..];
|
||||
else if (s.StartsWith("release-", StringComparison.OrdinalIgnoreCase)) s = s[8..];
|
||||
s = s.TrimStart('v', 'V');
|
||||
|
||||
// 只保留开头的 数字与点
|
||||
var end = 0;
|
||||
while (end < s.Length && (char.IsDigit(s[end]) || s[end] == '.')) end++;
|
||||
s = s[..end].Trim('.');
|
||||
|
||||
return s;
|
||||
}
|
||||
|
||||
/// <summary>解析成 Version;无法解析时返回 0.0。</summary>
|
||||
public static Version Parse(string? tag)
|
||||
{
|
||||
var n = Normalize(tag);
|
||||
if (string.IsNullOrWhiteSpace(n)) return new Version(0, 0);
|
||||
return Version.TryParse(n, out var v) ? v : new Version(0, 0);
|
||||
}
|
||||
|
||||
/// <summary>比较两个版本号,a>b 返回正、a<b 返回负、相等返回 0。</summary>
|
||||
public static int Compare(string? a, string? b) => Parse(a).CompareTo(Parse(b));
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
|
||||
namespace GC.Services;
|
||||
|
||||
/// <summary>
|
||||
/// 安全解压的统一入口(实现在 <see cref="SafeArchive"/>)。
|
||||
/// 保留这个名字是因为模型源导入 / 启动器更新两处都在用,
|
||||
/// 真正的校验逻辑集中在一处,避免两套实现走偏。
|
||||
/// </summary>
|
||||
public static class ZipSafety
|
||||
{
|
||||
public static void ExtractToDirectory(string zipPath, string destination)
|
||||
{
|
||||
if (!File.Exists(zipPath))
|
||||
throw new FileNotFoundException("压缩包不存在", zipPath);
|
||||
SafeArchive.ExtractToDirectory(zipPath, destination);
|
||||
}
|
||||
|
||||
/// <summary>只检查不落盘:给下载完成后的预检用。</summary>
|
||||
public static SafeArchive.Inspection Inspect(string zipPath) => SafeArchive.Inspect(zipPath);
|
||||
}
|
||||
@@ -0,0 +1,642 @@
|
||||
using System;
|
||||
using System.Threading.Tasks;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Text.Json;
|
||||
using Avalonia;
|
||||
using Avalonia.Animation;
|
||||
using Avalonia.Animation.Easings;
|
||||
using Avalonia.Controls;
|
||||
using Avalonia.Input;
|
||||
using Avalonia.Layout;
|
||||
using Avalonia.Media;
|
||||
using Shapes = Avalonia.Controls.Shapes;
|
||||
using Avalonia.VisualTree;
|
||||
using GC.Models;
|
||||
using GC.Services;
|
||||
|
||||
namespace GC.Views;
|
||||
|
||||
/// <summary>
|
||||
/// 模型窗口:**只做窗口宿主**。
|
||||
/// 内容完全来自模型程序集(<see cref="LoadedModel.View"/>),启动器不渲染任何东西。
|
||||
/// 快捷键:Esc 关闭窗口,F11 全屏。
|
||||
/// </summary>
|
||||
public sealed class PlayerWindow : Window
|
||||
{
|
||||
private LoadedModel? _model;
|
||||
private bool _closing;
|
||||
private Button? _maximizeButton;
|
||||
private Border? _frame;
|
||||
private TextBlock? _titleText;
|
||||
private Border? _titleBar;
|
||||
private readonly List<Button> _titleButtons = new();
|
||||
private readonly List<Shapes.Path> _titleGlyphs = new();
|
||||
private Shapes.Path? _maximizeGlyph;
|
||||
private Shapes.Path? _restoreGlyph;
|
||||
private string _maxMaxPath = "";
|
||||
private string _maxRestorePath = "";
|
||||
private Button? _helpButton;
|
||||
/// <summary>基准尺寸(1240×820 时的标题栏高度与按钮尺寸)。</summary>
|
||||
private const double BaseWidth = 1240;
|
||||
private const double BaseTitleBarHeight = 34;
|
||||
private const double BaseButtonWidth = 38;
|
||||
private const double BaseButtonHeight = 28;
|
||||
private const double BaseTitleFont = 11.5;
|
||||
private const double BaseHelpFont = 11.5;
|
||||
|
||||
public PlayerWindow(ModelPackage package, LoadedModel model)
|
||||
{
|
||||
_model = model;
|
||||
Title = package.LocalizedName;
|
||||
Width = 1240;
|
||||
Height = 820;
|
||||
MinWidth = 1000;
|
||||
MinHeight = 680;
|
||||
Background = Brushes.Transparent;
|
||||
TransparencyLevelHint = new[] { WindowTransparencyLevel.Transparent };
|
||||
WindowStartupLocation = WindowStartupLocation.CenterOwner;
|
||||
// 与启动器一致:去掉系统标题栏,自己做一个极简顶栏(否则 Esc 之外无法关闭)
|
||||
SystemDecorations = Avalonia.Controls.SystemDecorations.None;
|
||||
|
||||
// 标题栏配色来自模型清单,跟随模型自己的界面风格:
|
||||
// 地球模型是深色舞台,比例尺计算器是浅色卡片,两者不能共用一套深色。
|
||||
var chrome = package.Manifest.Chrome;
|
||||
var barBg = ParseColor(chrome?.TitleBar, "#0C1828");
|
||||
var barBorder = ParseColor(chrome?.TitleBorder, "#1B2740");
|
||||
var barText = ParseColor(chrome?.TitleText, "#EAF2FF");
|
||||
var btnText = ParseColor(chrome?.Button, "#9FB4D4");
|
||||
var frameBg = ParseColor(chrome?.Frame, "#0A1524");
|
||||
|
||||
var titleText = new TextBlock
|
||||
{
|
||||
Text = package.LocalizedName,
|
||||
Foreground = new SolidColorBrush(barText),
|
||||
FontSize = 11.5,
|
||||
Margin = new Thickness(14, 0, 0, 0),
|
||||
VerticalAlignment = VerticalAlignment.Center,
|
||||
[Grid.ColumnProperty] = 0
|
||||
};
|
||||
_titleText = titleText;
|
||||
|
||||
var helpButton = new Button
|
||||
{
|
||||
Content = IsEnglish() ? "How to use?" : "如何使用?",
|
||||
Height = 26,
|
||||
Padding = new Thickness(12, 0),
|
||||
Background = Brushes.Transparent,
|
||||
Foreground = new SolidColorBrush(btnText),
|
||||
BorderThickness = new Thickness(0),
|
||||
FontSize = 11.5,
|
||||
CornerRadius = new CornerRadius(7),
|
||||
Margin = new Thickness(0, 0, 6, 0),
|
||||
HorizontalContentAlignment = HorizontalAlignment.Center,
|
||||
VerticalContentAlignment = VerticalAlignment.Center,
|
||||
Cursor = new Cursor(StandardCursorType.Hand),
|
||||
[Grid.ColumnProperty] = 1
|
||||
};
|
||||
helpButton.Click += (_, _) => ShowHelp(package, barBg, barBorder, barText, btnText, frameBg);
|
||||
|
||||
// 标题栏三键:最小化 / 最大化 / 关闭 —— 卡通画风。
|
||||
// 每颗按钮 = 彩色实心圆底 + 粗圆头描边图标,像一颗小糖豆。
|
||||
(Button Btn, Shapes.Path Icon) MakeBadge(int column, string iconPath)
|
||||
{
|
||||
// 纯矢量图标,没有彩色圆圈
|
||||
var icon = new Shapes.Path
|
||||
{
|
||||
Data = Geometry.Parse(iconPath),
|
||||
Stroke = new SolidColorBrush(btnText),
|
||||
StrokeThickness = 1.5,
|
||||
StrokeLineCap = PenLineCap.Round,
|
||||
StrokeJoin = PenLineJoin.Round,
|
||||
Fill = null,
|
||||
Stretch = Stretch.None,
|
||||
Width = 10,
|
||||
Height = 10,
|
||||
HorizontalAlignment = HorizontalAlignment.Center,
|
||||
VerticalAlignment = VerticalAlignment.Center
|
||||
};
|
||||
var layer = new Grid
|
||||
{
|
||||
HorizontalAlignment = HorizontalAlignment.Center,
|
||||
VerticalAlignment = VerticalAlignment.Center
|
||||
};
|
||||
layer.Children.Add(icon);
|
||||
|
||||
var b = new Button
|
||||
{
|
||||
Width = 38,
|
||||
Height = 28,
|
||||
Background = Brushes.Transparent,
|
||||
BorderThickness = new Thickness(0),
|
||||
CornerRadius = new CornerRadius(9),
|
||||
Padding = new Thickness(0),
|
||||
Margin = new Thickness(2, 0, 0, 0),
|
||||
Content = layer,
|
||||
HorizontalContentAlignment = HorizontalAlignment.Center,
|
||||
VerticalContentAlignment = VerticalAlignment.Center,
|
||||
Cursor = new Cursor(StandardCursorType.Hand),
|
||||
[Grid.ColumnProperty] = column
|
||||
};
|
||||
var hoverBg = IsLight(barBg)
|
||||
? new SolidColorBrush(Color.Parse("#EEF1F7"))
|
||||
: new SolidColorBrush(Color.Parse("#1E2C46"));
|
||||
var isCloseBtn = column == 4;
|
||||
b.PointerEntered += (_, _) =>
|
||||
{
|
||||
b.Background = hoverBg;
|
||||
icon.Stroke = new SolidColorBrush(isCloseBtn ? Colors.White
|
||||
: IsLight(barBg) ? Color.Parse("#111A2E") : Colors.White);
|
||||
};
|
||||
b.PointerExited += (_, _) =>
|
||||
{
|
||||
b.Background = Brushes.Transparent;
|
||||
icon.Stroke = new SolidColorBrush(btnText);
|
||||
};
|
||||
b.Classes.Add("model-titlebtn");
|
||||
_titleButtons.Add(b);
|
||||
_titleGlyphs.Add(icon);
|
||||
return (b, icon);
|
||||
}
|
||||
|
||||
// 卡通配色:暖黄 / 薄荷绿 / 珊瑚红
|
||||
var minBadge = MakeBadge(2, "M1.5,5 L8.5,5");
|
||||
var maxBadge = MakeBadge(3, "M2.2,2.2 L7.8,2.2 L7.8,7.8 L2.2,7.8 Z");
|
||||
var closeBadge = MakeBadge(4, "M2,2 L8,8 M8,2 L2,8");
|
||||
|
||||
var minimizeButton = minBadge.Btn;
|
||||
var maximizeButton = maxBadge.Btn;
|
||||
var closeButton = closeBadge.Btn;
|
||||
|
||||
minimizeButton.Click += (_, _) => WindowState = WindowState.Minimized;
|
||||
maximizeButton.Click += (_, _) => ToggleMaximize();
|
||||
closeButton.Click += (_, _) => _ = CloseWithAnimationAsync();
|
||||
_maximizeGlyph = maxBadge.Icon;
|
||||
_restoreGlyph = maxBadge.Icon;
|
||||
_maxRestorePath = "M2.6,3.6 L7.4,3.6 L7.4,8.4 L2.6,8.4 Z M2.6,3.6 L2.6,1.6 L7.4,1.6 L7.4,6.4";
|
||||
_maxMaxPath = "M2.2,2.2 L7.8,2.2 L7.8,7.8 L2.2,7.8 Z";
|
||||
|
||||
var titleBar = new Border
|
||||
{
|
||||
Height = 34,
|
||||
Background = new SolidColorBrush(barBg),
|
||||
BorderBrush = new SolidColorBrush(barBorder),
|
||||
BorderThickness = new Thickness(0, 0, 0, 1),
|
||||
Child = new Grid
|
||||
{
|
||||
ColumnDefinitions = new ColumnDefinitions("*,Auto,Auto,Auto,Auto,Auto"),
|
||||
Margin = new Thickness(0, 0, 10, 0),
|
||||
Children = { titleText, helpButton, minimizeButton, maximizeButton, closeButton }
|
||||
}
|
||||
};
|
||||
titleBar.PointerPressed += OnTitleBarPointerPressed;
|
||||
// 双击标题栏 = 最大化 / 还原(与系统标题栏一致)
|
||||
titleBar.DoubleTapped += (_, e) =>
|
||||
{
|
||||
if (e.Source is Button) return;
|
||||
ToggleMaximize();
|
||||
};
|
||||
_maximizeButton = maximizeButton;
|
||||
_titleBar = titleBar;
|
||||
_helpButton = helpButton;
|
||||
_titleButtons.Add(minimizeButton);
|
||||
_titleButtons.Add(maximizeButton);
|
||||
_titleButtons.Add(closeButton);
|
||||
|
||||
var dock = new DockPanel { LastChildFill = true };
|
||||
DockPanel.SetDock(titleBar, Dock.Top);
|
||||
dock.Children.Add(titleBar);
|
||||
dock.Children.Add(model.View);
|
||||
|
||||
Content = new Border
|
||||
{
|
||||
CornerRadius = new CornerRadius(16),
|
||||
Background = new SolidColorBrush(frameBg),
|
||||
ClipToBounds = true,
|
||||
Child = dock
|
||||
};
|
||||
_frame = (Border)Content;
|
||||
|
||||
// 最大化 / 还原时同步圆角与按钮图标
|
||||
PropertyChanged += (_, e) =>
|
||||
{
|
||||
if (e.Property == WindowStateProperty) UpdateMaximizeVisual();
|
||||
};
|
||||
|
||||
// 窗口随心拉大 / 拉小时,标题栏文字与按钮同比缩放。
|
||||
// 同时监听 Bounds 属性(不只是 SizeChanged),保证最大化/还原也立刻生效。
|
||||
SizeChanged += (_, _) => ApplyChromeScale();
|
||||
PropertyChanged += (_, e) =>
|
||||
{
|
||||
if (e.Property == BoundsProperty) ApplyChromeScale();
|
||||
};
|
||||
ApplyChromeScale();
|
||||
|
||||
KeyDown += OnKeyDown;
|
||||
Closed += OnClosed;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 让标题栏的文字与按钮尺寸跟随窗口大小。
|
||||
/// 以 1240px 宽为基准线性缩放,限制在 0.85–1.9 倍,
|
||||
/// 避免最大化到 4K 时按钮大得离谱、缩到最小又点不中。
|
||||
/// </summary>
|
||||
private void ApplyChromeScale()
|
||||
{
|
||||
if (Bounds.Width < 100) return;
|
||||
var scale = Math.Clamp(Bounds.Width / BaseWidth, 0.85, 1.9);
|
||||
|
||||
if (_titleBar != null) _titleBar.Height = Math.Round(BaseTitleBarHeight * scale);
|
||||
foreach (var b in _titleButtons)
|
||||
{
|
||||
b.Width = Math.Round(BaseButtonWidth * scale);
|
||||
b.Height = Math.Round(BaseButtonHeight * scale);
|
||||
b.FontSize = Math.Round(13 * scale, 1);
|
||||
b.CornerRadius = new CornerRadius(Math.Round(7 * scale, 1));
|
||||
}
|
||||
if (_helpButton != null)
|
||||
{
|
||||
_helpButton.Height = Math.Round(26 * scale);
|
||||
_helpButton.FontSize = Math.Round(BaseHelpFont * scale, 1);
|
||||
_helpButton.Padding = new Thickness(Math.Round(12 * scale), 0);
|
||||
_helpButton.CornerRadius = new CornerRadius(Math.Round(7 * scale, 1));
|
||||
}
|
||||
foreach (var g in _titleGlyphs)
|
||||
{
|
||||
g.Width = Math.Round(10 * scale, 1);
|
||||
g.Height = Math.Round(10 * scale, 1);
|
||||
g.StrokeThickness = Math.Round(1.5 * scale, 2);
|
||||
}
|
||||
if (_titleText != null)
|
||||
{
|
||||
_titleText.FontSize = Math.Round(BaseTitleFont * scale, 1);
|
||||
_titleText.Margin = new Thickness(Math.Round(14 * scale), 0, 0, 0);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>判断颜色是否属于浅色系(用于决定悬停用深色还是浅色)。</summary>
|
||||
private static bool IsLight(Color c)
|
||||
{
|
||||
// 相对亮度(sRGB 近似)
|
||||
var lum = (0.299 * c.R + 0.587 * c.G + 0.114 * c.B) / 255.0;
|
||||
return lum > 0.6;
|
||||
}
|
||||
|
||||
private void ToggleMaximize()
|
||||
{
|
||||
WindowState = WindowState == WindowState.Maximized
|
||||
? WindowState.Normal
|
||||
: WindowState.Maximized;
|
||||
}
|
||||
|
||||
private void UpdateMaximizeVisual()
|
||||
{
|
||||
var max = WindowState == WindowState.Maximized || WindowState == WindowState.FullScreen;
|
||||
if (_maximizeGlyph != null)
|
||||
{
|
||||
// 只换 Data,不换控件对象(换对象会触发 "already has a parent")
|
||||
_maximizeGlyph.Data = Geometry.Parse(max ? _maxRestorePath : _maxMaxPath);
|
||||
}
|
||||
if (_maximizeButton != null)
|
||||
{
|
||||
Avalonia.Controls.ToolTip.SetTip(_maximizeButton, max
|
||||
? (IsEnglish() ? "Restore" : "还原")
|
||||
: (IsEnglish() ? "Maximize" : "最大化"));
|
||||
}
|
||||
// 最大化后同样保留圆角(用户要求:任何状态都要圆角)
|
||||
if (_frame != null) _frame.CornerRadius = new CornerRadius(16);
|
||||
}
|
||||
|
||||
private static Color ParseColor(string? hex, string fallback)
|
||||
{
|
||||
if (!string.IsNullOrWhiteSpace(hex))
|
||||
{
|
||||
try { return Color.Parse(hex!); }
|
||||
catch { /* 模型写错颜色时退回默认 */ }
|
||||
}
|
||||
return Color.Parse(fallback);
|
||||
}
|
||||
|
||||
private static bool IsEnglish() => L.I.Language.StartsWith("en", StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
/// <summary>
|
||||
/// 「如何使用?」:读取模型自带数据目录里的 help.json(中英双语),
|
||||
/// 用与标题栏一致的配色弹出一个独立小窗。说明内容完全由模型提供,启动器不内置文案。
|
||||
/// </summary>
|
||||
private void ShowHelp(ModelPackage package, Color barBg, Color barBorder, Color barText,
|
||||
Color btnText, Color frameBg)
|
||||
{
|
||||
var lang = IsEnglish() ? "en" : "zh-CN";
|
||||
var file = Path.Combine(package.DataDirectory, "help.json");
|
||||
string title = IsEnglish() ? "How to use" : "如何使用";
|
||||
// 分节内容:每节一个标题 + 若干条说明;兼容旧的扁平 lines 格式
|
||||
var sections = new List<(string Heading, List<string> Lines)>();
|
||||
|
||||
if (File.Exists(file))
|
||||
{
|
||||
try
|
||||
{
|
||||
using var doc = JsonDocument.Parse(File.ReadAllText(file));
|
||||
var root = doc.RootElement;
|
||||
var node = root.TryGetProperty(lang, out var exact) ? exact
|
||||
: root.TryGetProperty("zh-CN", out var zh) ? zh : root;
|
||||
if (node.TryGetProperty("title", out var t)) title = t.GetString() ?? title;
|
||||
|
||||
if (node.TryGetProperty("sections", out var arr) && arr.ValueKind == JsonValueKind.Array)
|
||||
{
|
||||
foreach (var sec in arr.EnumerateArray())
|
||||
{
|
||||
var heading = sec.TryGetProperty("h", out var h) ? h.GetString() ?? "" : "";
|
||||
var items = new List<string>();
|
||||
if (sec.TryGetProperty("lines", out var ls) && ls.ValueKind == JsonValueKind.Array)
|
||||
foreach (var item in ls.EnumerateArray())
|
||||
if (item.ValueKind == JsonValueKind.String) items.Add(item.GetString() ?? "");
|
||||
if (items.Count > 0) sections.Add((heading, items));
|
||||
}
|
||||
}
|
||||
else if (node.TryGetProperty("lines", out var flat) && flat.ValueKind == JsonValueKind.Array)
|
||||
{
|
||||
var items = new List<string>();
|
||||
foreach (var item in flat.EnumerateArray())
|
||||
if (item.ValueKind == JsonValueKind.String) items.Add(item.GetString() ?? "");
|
||||
if (items.Count > 0) sections.Add(("", items));
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.Error.WriteLine($"读取模型帮助失败 {file}: {ex.Message}");
|
||||
}
|
||||
}
|
||||
if (sections.Count == 0)
|
||||
sections.Add(("", new List<string>
|
||||
{
|
||||
IsEnglish() ? "This model has no usage notes yet." : "该模型暂未提供使用说明。"
|
||||
}));
|
||||
|
||||
var body = new StackPanel { Spacing = 6 };
|
||||
foreach (var (heading, items) in sections)
|
||||
{
|
||||
if (!string.IsNullOrWhiteSpace(heading))
|
||||
body.Children.Add(new TextBlock
|
||||
{
|
||||
Text = heading,
|
||||
Foreground = new SolidColorBrush(barText),
|
||||
FontSize = 13.5,
|
||||
FontWeight = FontWeight.SemiBold,
|
||||
Margin = new Thickness(0, 12, 0, 2)
|
||||
});
|
||||
foreach (var line in items)
|
||||
body.Children.Add(new TextBlock
|
||||
{
|
||||
Text = "• " + line,
|
||||
Foreground = new SolidColorBrush(btnText),
|
||||
FontSize = 12.5,
|
||||
TextWrapping = TextWrapping.Wrap,
|
||||
LineHeight = 19
|
||||
});
|
||||
}
|
||||
|
||||
// ── 帮助窗口自建标题栏(带 ✕),与模型窗口同款配色 ──
|
||||
// 纯矢量图标,无彩色圆底(与三个窗口按钮保持一致)
|
||||
var helpCross = new Shapes.Path
|
||||
{
|
||||
Data = Geometry.Parse("M2,2 L8,8 M8,2 L2,8"),
|
||||
Stroke = new SolidColorBrush(btnText),
|
||||
StrokeThickness = 1.5,
|
||||
StrokeLineCap = PenLineCap.Round,
|
||||
Fill = null,
|
||||
Stretch = Stretch.None,
|
||||
Width = 10, Height = 10,
|
||||
HorizontalAlignment = HorizontalAlignment.Center,
|
||||
VerticalAlignment = VerticalAlignment.Center
|
||||
};
|
||||
|
||||
var helpClose = new Button
|
||||
{
|
||||
Content = helpCross,
|
||||
Width = 34,
|
||||
Height = 26,
|
||||
Background = Brushes.Transparent,
|
||||
BorderThickness = new Thickness(0),
|
||||
CornerRadius = new CornerRadius(9),
|
||||
Padding = new Thickness(0),
|
||||
Margin = new Thickness(6, 0, 0, 0),
|
||||
HorizontalContentAlignment = HorizontalAlignment.Center,
|
||||
VerticalContentAlignment = VerticalAlignment.Center,
|
||||
Cursor = new Cursor(StandardCursorType.Hand)
|
||||
};
|
||||
helpClose.PointerEntered += (_, _) =>
|
||||
{
|
||||
helpClose.Background = new SolidColorBrush(IsLight(frameBg)
|
||||
? Color.Parse("#EEF1F7") : Color.Parse("#1E2C46"));
|
||||
helpCross.Stroke = new SolidColorBrush(Colors.White);
|
||||
};
|
||||
helpClose.PointerExited += (_, _) =>
|
||||
{
|
||||
helpClose.Background = Brushes.Transparent;
|
||||
helpCross.Stroke = new SolidColorBrush(btnText);
|
||||
};
|
||||
|
||||
var helpTitle = new TextBlock
|
||||
{
|
||||
Text = title,
|
||||
Foreground = new SolidColorBrush(barText),
|
||||
FontSize = 16,
|
||||
FontWeight = FontWeight.SemiBold,
|
||||
VerticalAlignment = VerticalAlignment.Center
|
||||
};
|
||||
|
||||
var helpBarGrid = new Grid
|
||||
{
|
||||
ColumnDefinitions = new ColumnDefinitions("*,Auto"),
|
||||
Margin = new Thickness(22, 0, 14, 0)
|
||||
};
|
||||
helpBarGrid.Children.Add(helpTitle);
|
||||
Grid.SetColumn(helpClose, 1);
|
||||
helpBarGrid.Children.Add(helpClose);
|
||||
|
||||
var helpTitleBar = new Border
|
||||
{
|
||||
Height = 48,
|
||||
Background = new SolidColorBrush(barBg),
|
||||
BorderBrush = new SolidColorBrush(barBorder),
|
||||
BorderThickness = new Thickness(0, 0, 0, 1),
|
||||
Child = helpBarGrid
|
||||
};
|
||||
helpTitleBar.PointerPressed += (_, e) =>
|
||||
{
|
||||
if (e.GetCurrentPoint(helpTitleBar).Properties.IsLeftButtonPressed)
|
||||
helpClose.FindAncestorOfType<Window>()?.BeginMoveDrag(e);
|
||||
};
|
||||
|
||||
// ── 底部固定操作条:无论正文多长,「知道了」始终可见 ──
|
||||
var ok = new Button
|
||||
{
|
||||
Content = IsEnglish() ? "Got it" : "知道了",
|
||||
HorizontalAlignment = HorizontalAlignment.Right,
|
||||
Padding = new Thickness(20, 8),
|
||||
Background = new SolidColorBrush(Color.Parse("#2F6BFF")),
|
||||
Foreground = new SolidColorBrush(Colors.White),
|
||||
BorderThickness = new Thickness(0),
|
||||
CornerRadius = new CornerRadius(8),
|
||||
Cursor = new Cursor(StandardCursorType.Hand)
|
||||
};
|
||||
var footer = new Border
|
||||
{
|
||||
Padding = new Thickness(24, 10, 24, 14),
|
||||
BorderBrush = new SolidColorBrush(barBorder),
|
||||
BorderThickness = new Thickness(0, 1, 0, 0),
|
||||
Child = ok
|
||||
};
|
||||
|
||||
// 标题栏(顶) + 正文(中,滚动) + 操作条(底,固定)
|
||||
var rootPanel = new DockPanel { LastChildFill = true };
|
||||
DockPanel.SetDock(helpTitleBar, Dock.Top);
|
||||
rootPanel.Children.Add(helpTitleBar);
|
||||
DockPanel.SetDock(footer, Dock.Bottom);
|
||||
rootPanel.Children.Add(footer);
|
||||
var scroll = new ScrollViewer
|
||||
{
|
||||
Content = new Border
|
||||
{
|
||||
Margin = new Thickness(24, 14, 24, 10),
|
||||
Child = body
|
||||
},
|
||||
VerticalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Auto,
|
||||
HorizontalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Disabled
|
||||
};
|
||||
rootPanel.Children.Add(scroll);
|
||||
|
||||
var win = new Window
|
||||
{
|
||||
Title = title,
|
||||
Width = 660,
|
||||
Height = Math.Min(760, 230 + sections.Sum(s => s.Lines.Count * 24 + 40)),
|
||||
MinWidth = 480,
|
||||
MinHeight = 320,
|
||||
Background = Brushes.Transparent,
|
||||
TransparencyLevelHint = new[] { WindowTransparencyLevel.Transparent },
|
||||
SystemDecorations = SystemDecorations.None,
|
||||
WindowStartupLocation = WindowStartupLocation.CenterOwner,
|
||||
Content = new Border
|
||||
{
|
||||
CornerRadius = new CornerRadius(16),
|
||||
Background = new SolidColorBrush(frameBg),
|
||||
BorderBrush = new SolidColorBrush(barBorder),
|
||||
BorderThickness = new Thickness(1),
|
||||
ClipToBounds = true,
|
||||
Child = rootPanel
|
||||
}
|
||||
};
|
||||
ok.Click += (_, _) => win.Close();
|
||||
helpClose.Click += (_, _) => win.Close();
|
||||
win.Show(this);
|
||||
}
|
||||
|
||||
private void OnTitleBarPointerPressed(object? sender, PointerPressedEventArgs e)
|
||||
{
|
||||
if (e.GetCurrentPoint(this).Properties.IsLeftButtonPressed)
|
||||
BeginMoveDrag(e);
|
||||
}
|
||||
|
||||
private void OnKeyDown(object? sender, KeyEventArgs e)
|
||||
{
|
||||
switch (e.Key)
|
||||
{
|
||||
case Key.Escape:
|
||||
_ = CloseWithAnimationAsync();
|
||||
e.Handled = true;
|
||||
break;
|
||||
case Key.F11:
|
||||
WindowState = WindowState == WindowState.FullScreen
|
||||
? WindowState.Normal
|
||||
: WindowState.FullScreen;
|
||||
e.Handled = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 关闭动画:淡出 + 轻微缩小,动画结束后再真正关闭窗口。
|
||||
/// 与主窗口的关闭动画保持同一节奏(180ms)。
|
||||
/// </summary>
|
||||
private async Task CloseWithAnimationAsync()
|
||||
{
|
||||
if (_closing) return;
|
||||
_closing = true;
|
||||
|
||||
Transitions = new Transitions
|
||||
{
|
||||
new DoubleTransition
|
||||
{
|
||||
Property = OpacityProperty,
|
||||
Duration = TimeSpan.FromMilliseconds(180),
|
||||
Easing = new CubicEaseIn()
|
||||
}
|
||||
};
|
||||
Opacity = 0;
|
||||
|
||||
await Task.Delay(190);
|
||||
Close();
|
||||
}
|
||||
|
||||
private void OnClosed(object? sender, EventArgs e)
|
||||
{
|
||||
Content = null;
|
||||
_model?.Dispose();
|
||||
_model = null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>模型加载失败时显示的提示窗口(不含任何渲染逻辑)。</summary>
|
||||
public sealed class ModelErrorWindow : Window
|
||||
{
|
||||
public ModelErrorWindow(string title, string message)
|
||||
{
|
||||
Title = title;
|
||||
Width = 560;
|
||||
Height = 340;
|
||||
Background = Brushes.Transparent;
|
||||
TransparencyLevelHint = new[] { WindowTransparencyLevel.Transparent };
|
||||
WindowStartupLocation = WindowStartupLocation.CenterOwner;
|
||||
|
||||
var lines = new List<Control>
|
||||
{
|
||||
new TextBlock
|
||||
{
|
||||
Text = title,
|
||||
Foreground = new SolidColorBrush(Color.Parse("#F2F6FF")),
|
||||
FontSize = 16,
|
||||
FontWeight = FontWeight.SemiBold
|
||||
},
|
||||
new TextBlock
|
||||
{
|
||||
Text = message,
|
||||
Foreground = new SolidColorBrush(Color.Parse("#8CA0C4")),
|
||||
FontSize = 12,
|
||||
TextWrapping = TextWrapping.Wrap
|
||||
},
|
||||
new Button
|
||||
{
|
||||
Content = "确定",
|
||||
HorizontalAlignment = Avalonia.Layout.HorizontalAlignment.Right,
|
||||
Padding = new Thickness(18, 6)
|
||||
}
|
||||
};
|
||||
|
||||
var panel = new StackPanel
|
||||
{
|
||||
Margin = new Thickness(24),
|
||||
Spacing = 14
|
||||
};
|
||||
foreach (var line in lines) panel.Children.Add(line);
|
||||
if (lines[^1] is Button ok) ok.Click += (_, _) => Close();
|
||||
Content = new Border
|
||||
{
|
||||
CornerRadius = new CornerRadius(12),
|
||||
Background = new SolidColorBrush(Color.Parse("#0B1226")),
|
||||
Child = panel
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,552 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Text.RegularExpressions;
|
||||
using System.Threading;
|
||||
using GC.Services;
|
||||
|
||||
namespace GC.Savedog;
|
||||
|
||||
internal sealed class ApplyOptions
|
||||
{
|
||||
public string UpdateDir { get; set; } = "";
|
||||
public string? InstallDir { get; set; }
|
||||
public int WaitPid { get; set; }
|
||||
public int TimeoutSeconds { get; set; } = 45;
|
||||
public bool RequireSignature { get; set; } = true;
|
||||
public bool DryRun { get; set; }
|
||||
public bool Force { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 应用一次启动器更新:验签 → 校验 → 原子替换 → 启动 → 看护 → 成功清场 / 失败回滚。
|
||||
/// 任何一步失败都不会留下「删了旧版又没有新版」的状态。
|
||||
/// </summary>
|
||||
internal sealed class Applier
|
||||
{
|
||||
private static readonly Regex ArtifactPattern = new(
|
||||
@"^GC-(?<ver>.+?)-(?<plat>[^\-]+-[^\-]+)\.(app|exe)$",
|
||||
RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);
|
||||
|
||||
private readonly ApplyOptions _options;
|
||||
private readonly Log _log;
|
||||
|
||||
public Applier(ApplyOptions options, Log log)
|
||||
{
|
||||
_options = options;
|
||||
_log = log;
|
||||
}
|
||||
|
||||
public int Run()
|
||||
{
|
||||
var updateDir = Path.GetFullPath(_options.UpdateDir);
|
||||
var requestPath = Path.Combine(updateDir, SavedogFiles.ApplyRequest);
|
||||
|
||||
if (!File.Exists(requestPath))
|
||||
return Fail(updateDir, "找不到更新申请 " + SavedogFiles.ApplyRequest, 3);
|
||||
|
||||
var request = Json.Read<SavedogRequest>(requestPath);
|
||||
if (request == null || string.IsNullOrWhiteSpace(request.Version))
|
||||
return Fail(updateDir, "更新申请内容不完整", 3);
|
||||
|
||||
if (!ValidName(request.PackageName))
|
||||
return Fail(updateDir, "更新包名不合法: " + request.PackageName, 3);
|
||||
|
||||
_log.Info($"开始应用 v{request.Version}({request.Rid},{request.PackageName})");
|
||||
|
||||
// 1. 等旧进程退出(否则 Windows 上文件还被占用)
|
||||
if (_options.WaitPid > 0 && !WaitForExit(_options.WaitPid, TimeSpan.FromSeconds(60)))
|
||||
_log.Warn($"等待进程 {_options.WaitPid} 退出超时,继续尝试");
|
||||
|
||||
// 2. 安装目录定位与安全检查
|
||||
var installDir = string.IsNullOrWhiteSpace(_options.InstallDir)
|
||||
? Path.GetFullPath(Path.Combine(updateDir, request.InstallRelative))
|
||||
: Path.GetFullPath(_options.InstallDir!);
|
||||
|
||||
if (!Directory.Exists(installDir))
|
||||
return Fail(updateDir, "安装目录不存在: " + installDir, 4);
|
||||
|
||||
if (!_options.Force && File.Exists(Path.Combine(installDir, "GC.sln")))
|
||||
return Fail(updateDir, "检测到源码目录,拒绝在源码树里替换程序", 4);
|
||||
|
||||
// 3. 二次验签:不信任「启动器说它验过了」
|
||||
var require = request.RequireSignature && SignatureKeyring.Enforced;
|
||||
var manifestPath = Path.Combine(updateDir, request.ManifestPath);
|
||||
var manifestText = File.Exists(manifestPath) ? File.ReadAllText(manifestPath) : null;
|
||||
var verification = ManifestSignature.Verify(manifestText, require);
|
||||
|
||||
if (verification.IsRejected)
|
||||
{
|
||||
_log.Error($"清单验签失败({verification.Trust}):{verification.Error}");
|
||||
return Refuse(updateDir, request, verification);
|
||||
}
|
||||
_log.Info($"清单可信度:{verification.Trust}" +
|
||||
(verification.KeyId != null ? $"({verification.KeyId})" : ""));
|
||||
|
||||
// 4. 校验更新包
|
||||
var zipPath = Path.Combine(updateDir, request.PackageZip);
|
||||
if (!File.Exists(zipPath))
|
||||
return Fail(updateDir, "更新包不存在: " + request.PackageZip, 5);
|
||||
|
||||
var zipInfo = new FileInfo(zipPath);
|
||||
if (request.PackageSize > 0 && zipInfo.Length != request.PackageSize)
|
||||
return Fail(updateDir, $"更新包体积不符(期望 {request.PackageSize},实际 {zipInfo.Length})", 5);
|
||||
|
||||
var actualSha = ContentHash.Sha256File(zipPath);
|
||||
if (!string.IsNullOrWhiteSpace(request.PackageSha256) &&
|
||||
!string.Equals(actualSha, request.PackageSha256, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return Fail(updateDir, "更新包 sha256 与清单不符,已丢弃", 5);
|
||||
}
|
||||
if (string.IsNullOrWhiteSpace(request.PackageSha256))
|
||||
_log.Warn("清单没有提供 sha256,仅依赖签名与解压校验");
|
||||
|
||||
SafeArchive.Inspection inspection;
|
||||
try
|
||||
{
|
||||
inspection = SafeArchive.Inspect(zipPath);
|
||||
_log.Info($"更新包检查通过:{inspection.Entries} 个条目," +
|
||||
$"{inspection.UncompressedBytes / 1024 / 1024} MB,压缩比 {inspection.Ratio:0.0}:1");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
return Fail(updateDir, "更新包安全性检查失败: " + ex.Message, 5);
|
||||
}
|
||||
|
||||
// 5. 解压到暂存区(与安装目录同卷,后续 rename 才是原子的)
|
||||
var stage = Path.Combine(updateDir, "stage");
|
||||
ClearDirectory(stage);
|
||||
try
|
||||
{
|
||||
SafeArchive.ExtractToDirectory(zipPath, stage);
|
||||
FlattenSingleDirectory(stage);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
ClearDirectory(stage);
|
||||
return Fail(updateDir, "解压失败: " + ex.Message, 6);
|
||||
}
|
||||
|
||||
var artifact = FindArtifact(stage, request.PackageName);
|
||||
if (artifact == null)
|
||||
{
|
||||
ClearDirectory(stage);
|
||||
return Fail(updateDir, "更新包里没有找到新版程序(" + request.PackageName + ")", 6);
|
||||
}
|
||||
|
||||
var target = Path.Combine(installDir, Path.GetFileName(artifact));
|
||||
var alreadyInstalled = File.Exists(target) || Directory.Exists(target);
|
||||
|
||||
if (_options.DryRun)
|
||||
{
|
||||
_log.Info($"[dry-run] 校验全部通过,将安装到 {target}");
|
||||
ClearDirectory(stage);
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (alreadyInstalled)
|
||||
{
|
||||
// 同一版本重复下发:当成已安装,避免反复覆盖正在运行的文件
|
||||
_log.Info("目标版本已存在,视为已安装");
|
||||
ClearDirectory(stage);
|
||||
TryDelete(zipPath);
|
||||
TryDelete(requestPath);
|
||||
WriteState(updateDir, new SavedogState
|
||||
{
|
||||
Status = "applied",
|
||||
Version = request.Version,
|
||||
PackageName = Path.GetFileName(artifact),
|
||||
Verified = true,
|
||||
Message = "目标版本已存在,无需替换"
|
||||
});
|
||||
return 0;
|
||||
}
|
||||
|
||||
// 6. 移入安装目录(不覆盖任何已有文件)
|
||||
try
|
||||
{
|
||||
Directory.CreateDirectory(installDir);
|
||||
if (Directory.Exists(artifact)) Directory.Move(artifact, target);
|
||||
else File.Move(artifact, target);
|
||||
_log.Info("新版已就位: " + Path.GetFileName(target));
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
ClearDirectory(stage);
|
||||
return Fail(updateDir, "移动到安装目录失败: " + ex.Message, 7);
|
||||
}
|
||||
|
||||
// 7. 启动并看护
|
||||
var previous = ReadLastGood(updateDir);
|
||||
StartupHealth.Clear(updateDir);
|
||||
|
||||
Process? child;
|
||||
try
|
||||
{
|
||||
child = Launch(target);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
child = null;
|
||||
_log.Error("启动新版失败: " + ex.Message);
|
||||
}
|
||||
|
||||
var healthy = child != null && WaitForHealth(updateDir, request.Version, child,
|
||||
TimeSpan.FromSeconds(_options.TimeoutSeconds));
|
||||
|
||||
if (healthy)
|
||||
{
|
||||
_log.Info($"v{request.Version} 启动正常,更新完成");
|
||||
CleanupOldVersions(installDir, Path.GetFileName(target), request.PlatformLabel);
|
||||
WriteLastGood(updateDir, request.Version, Path.GetFileName(target));
|
||||
WriteState(updateDir, new SavedogState
|
||||
{
|
||||
Status = "applied",
|
||||
Version = request.Version,
|
||||
PreviousVersion = previous?.Version,
|
||||
PackageName = Path.GetFileName(target),
|
||||
Verified = true,
|
||||
Message = "更新已应用"
|
||||
});
|
||||
ClearDirectory(stage);
|
||||
TryDelete(zipPath);
|
||||
TryDelete(requestPath);
|
||||
return 0;
|
||||
}
|
||||
|
||||
// 8. 回滚
|
||||
_log.Error($"v{request.Version} 启动后未通过健康检查({_options.TimeoutSeconds}s),开始回滚");
|
||||
TryKill(child);
|
||||
var removed = RemoveNewVersion(target);
|
||||
_log.Info(removed ? "已移除未通过检查的新版" : "新版文件被占用,未能完全移除");
|
||||
|
||||
var restored = TryLaunchPrevious(installDir, updateDir, previous, request.PlatformLabel);
|
||||
WriteState(updateDir, new SavedogState
|
||||
{
|
||||
Status = "rolledback",
|
||||
Version = request.Version,
|
||||
PreviousVersion = previous?.Version,
|
||||
PackageName = Path.GetFileName(target),
|
||||
Verified = true,
|
||||
Message = restored
|
||||
? "新版本未通过启动检查,已回滚到上一个版本"
|
||||
: "新版本未通过启动检查,已移除;未找到可回滚的旧版本,请手动重新安装"
|
||||
});
|
||||
|
||||
ClearDirectory(stage);
|
||||
TryDelete(zipPath);
|
||||
TryDelete(requestPath);
|
||||
return 8;
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ 校验辅助
|
||||
|
||||
private static bool ValidName(string name)
|
||||
=> name.Length > 0 && name.Length < 200 &&
|
||||
name.IndexOfAny(new[] { '/', '\\', ':', '\0' }) < 0 &&
|
||||
(name.EndsWith(".app", StringComparison.OrdinalIgnoreCase) ||
|
||||
name.EndsWith(".exe", StringComparison.OrdinalIgnoreCase));
|
||||
|
||||
private static bool WaitForExit(int pid, TimeSpan timeout)
|
||||
{
|
||||
var deadline = DateTime.UtcNow + timeout;
|
||||
while (DateTime.UtcNow < deadline)
|
||||
{
|
||||
try
|
||||
{
|
||||
using var process = Process.GetProcessById(pid);
|
||||
if (process.HasExited) return true;
|
||||
}
|
||||
catch (ArgumentException) { return true; } // 进程已不存在
|
||||
catch { return true; }
|
||||
Thread.Sleep(200);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private static void FlattenSingleDirectory(string stage)
|
||||
{
|
||||
var entries = Directory.GetFileSystemEntries(stage);
|
||||
if (entries.Length != 1 || !Directory.Exists(entries[0])) return;
|
||||
var inner = entries[0];
|
||||
if (Path.GetFileName(inner).EndsWith(".app", StringComparison.OrdinalIgnoreCase)) return;
|
||||
|
||||
var temp = stage + "-flat";
|
||||
if (Directory.Exists(temp)) Directory.Delete(temp, true);
|
||||
Directory.Move(inner, temp);
|
||||
Directory.Delete(stage, true);
|
||||
Directory.Move(temp, stage);
|
||||
}
|
||||
|
||||
private static string? FindArtifact(string stage, string packageName)
|
||||
{
|
||||
var direct = Path.Combine(stage, packageName);
|
||||
if (File.Exists(direct) || Directory.Exists(direct)) return direct;
|
||||
|
||||
foreach (var entry in Directory.GetFileSystemEntries(stage))
|
||||
{
|
||||
var name = Path.GetFileName(entry);
|
||||
if (name.EndsWith(".app", StringComparison.OrdinalIgnoreCase) && Directory.Exists(entry))
|
||||
return entry;
|
||||
if (name.EndsWith(".exe", StringComparison.OrdinalIgnoreCase) && File.Exists(entry))
|
||||
return entry;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ 启动与看护
|
||||
|
||||
private Process? Launch(string target)
|
||||
{
|
||||
if (Directory.Exists(target))
|
||||
{
|
||||
// .app:优先直接启动内部可执行文件,这样才能拿到 pid 做看护
|
||||
var macOs = Path.Combine(target, "Contents", "MacOS");
|
||||
if (Directory.Exists(macOs))
|
||||
{
|
||||
var exe = Directory.GetFiles(macOs)
|
||||
.OrderByDescending(f => Path.GetFileName(f) == "GC")
|
||||
.FirstOrDefault();
|
||||
if (exe != null)
|
||||
{
|
||||
MakeExecutable(exe);
|
||||
return StartProcess(exe, Path.GetDirectoryName(exe)!);
|
||||
}
|
||||
}
|
||||
MakeExecutable(Path.Combine(target, "Contents", "MacOS", "GC"));
|
||||
var psi = new ProcessStartInfo("open") { UseShellExecute = false };
|
||||
psi.ArgumentList.Add("-n");
|
||||
psi.ArgumentList.Add(target);
|
||||
return Process.Start(psi);
|
||||
}
|
||||
|
||||
if (OperatingSystem.IsWindows() || OperatingSystem.IsLinux() || OperatingSystem.IsMacOS())
|
||||
{
|
||||
if (!OperatingSystem.IsWindows()) MakeExecutable(target);
|
||||
return StartProcess(target, Path.GetDirectoryName(target)!);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private static Process? StartProcess(string exe, string workingDirectory)
|
||||
{
|
||||
var psi = new ProcessStartInfo(exe)
|
||||
{
|
||||
UseShellExecute = false,
|
||||
WorkingDirectory = workingDirectory
|
||||
};
|
||||
return Process.Start(psi);
|
||||
}
|
||||
|
||||
private static void MakeExecutable(string path)
|
||||
{
|
||||
if (OperatingSystem.IsWindows()) return;
|
||||
try
|
||||
{
|
||||
if (!File.Exists(path)) return;
|
||||
var mode = File.GetUnixFileMode(path);
|
||||
File.SetUnixFileMode(path, mode | UnixFileMode.UserExecute |
|
||||
UnixFileMode.GroupExecute |
|
||||
UnixFileMode.OtherExecute);
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
|
||||
private bool WaitForHealth(string updateDir, string version, Process child, TimeSpan timeout)
|
||||
{
|
||||
var deadline = DateTime.UtcNow + timeout;
|
||||
while (DateTime.UtcNow < deadline)
|
||||
{
|
||||
var health = StartupHealth.Read(updateDir);
|
||||
if (health != null && health.Ok && SameVersion(health.Version, version))
|
||||
{
|
||||
_log.Info($"收到健康标记(pid {health.Pid})");
|
||||
return true;
|
||||
}
|
||||
|
||||
if (child.HasExited)
|
||||
{
|
||||
_log.Error($"新版进程已退出(退出码 {child.ExitCode})");
|
||||
return false;
|
||||
}
|
||||
Thread.Sleep(250);
|
||||
}
|
||||
|
||||
// 超时但进程还活着:可能是尚未写入健康标记的旧构建,谨慎放行
|
||||
if (!child.HasExited)
|
||||
{
|
||||
_log.Warn("未收到健康标记,但进程仍在运行,按成功处理");
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private static bool SameVersion(string a, string b)
|
||||
=> string.Equals(Normalize(a), Normalize(b), StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
private static string Normalize(string version)
|
||||
{
|
||||
var trimmed = version.Trim().TrimStart('v', 'V');
|
||||
var parts = trimmed.Split('.');
|
||||
var numbers = new List<string>();
|
||||
foreach (var part in parts)
|
||||
{
|
||||
if (!int.TryParse(part, out var n)) break;
|
||||
numbers.Add(n.ToString());
|
||||
}
|
||||
while (numbers.Count > 0 && numbers[^1] == "0") numbers.RemoveAt(numbers.Count - 1);
|
||||
return numbers.Count == 0 ? trimmed : string.Join('.', numbers);
|
||||
}
|
||||
|
||||
private static void TryKill(Process? process)
|
||||
{
|
||||
if (process == null) return;
|
||||
try
|
||||
{
|
||||
if (!process.HasExited) process.Kill(entireProcessTree: true);
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ 清理 / 回滚
|
||||
|
||||
private void CleanupOldVersions(string installDir, string keepName, string platformLabel)
|
||||
{
|
||||
foreach (var entry in Directory.GetFileSystemEntries(installDir))
|
||||
{
|
||||
var name = Path.GetFileName(entry);
|
||||
if (string.Equals(name, keepName, StringComparison.OrdinalIgnoreCase)) continue;
|
||||
|
||||
var match = ArtifactPattern.Match(name);
|
||||
if (!match.Success) continue;
|
||||
|
||||
var platform = match.Groups["plat"].Value;
|
||||
if (!string.Equals(platform, platformLabel, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
_log.Info($"保留其它平台版本: {name}");
|
||||
continue;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
if (Directory.Exists(entry)) Directory.Delete(entry, true);
|
||||
else File.Delete(entry);
|
||||
_log.Info("清理旧版本: " + name);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_log.Warn($"清理旧版本失败 {name}: {ex.Message}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private bool RemoveNewVersion(string target)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (Directory.Exists(target)) Directory.Delete(target, true);
|
||||
else if (File.Exists(target)) File.Delete(target);
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_log.Warn("移除新版失败: " + ex.Message);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private bool TryLaunchPrevious(string installDir, string updateDir, LastGoodVersion? lastGood,
|
||||
string platformLabel)
|
||||
{
|
||||
// 优先用上次成功的版本;否则挑一个同平台的其它版本
|
||||
var candidates = new List<string>();
|
||||
if (lastGood != null && !string.IsNullOrWhiteSpace(lastGood.PackageName))
|
||||
candidates.Add(Path.Combine(installDir, lastGood.PackageName));
|
||||
|
||||
foreach (var entry in Directory.GetFileSystemEntries(installDir))
|
||||
{
|
||||
var name = Path.GetFileName(entry);
|
||||
var match = ArtifactPattern.Match(name);
|
||||
if (!match.Success) continue;
|
||||
if (!string.Equals(match.Groups["plat"].Value, platformLabel, StringComparison.OrdinalIgnoreCase))
|
||||
continue;
|
||||
candidates.Add(entry);
|
||||
}
|
||||
|
||||
foreach (var candidate in candidates)
|
||||
{
|
||||
if (!File.Exists(candidate) && !Directory.Exists(candidate)) continue;
|
||||
try
|
||||
{
|
||||
Launch(candidate);
|
||||
_log.Info("已回滚启动: " + Path.GetFileName(candidate));
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_log.Warn($"回滚启动失败 {Path.GetFileName(candidate)}: {ex.Message}");
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ 状态文件
|
||||
|
||||
private void WriteState(string updateDir, SavedogState state)
|
||||
{
|
||||
try { Json.Write(Path.Combine(updateDir, SavedogFiles.State), state); }
|
||||
catch (Exception ex) { _log.Warn("写状态失败: " + ex.Message); }
|
||||
}
|
||||
|
||||
private int Fail(string updateDir, string message, int code)
|
||||
{
|
||||
_log.Error(message);
|
||||
WriteState(updateDir, new SavedogState { Status = "failed", Message = message });
|
||||
return code;
|
||||
}
|
||||
|
||||
private int Refuse(string updateDir, SavedogRequest request, ManifestVerification verification)
|
||||
{
|
||||
WriteState(updateDir, new SavedogState
|
||||
{
|
||||
Status = "refused",
|
||||
Version = request.Version,
|
||||
PackageName = request.PackageName,
|
||||
Verified = false,
|
||||
Message = $"清单验签失败:{verification.Error}"
|
||||
});
|
||||
return 2;
|
||||
}
|
||||
|
||||
private static LastGoodVersion? ReadLastGood(string updateDir)
|
||||
=> Json.Read<LastGoodVersion>(Path.Combine(updateDir, SavedogFiles.LastGood));
|
||||
|
||||
private static void WriteLastGood(string updateDir, string version, string packageName)
|
||||
{
|
||||
try
|
||||
{
|
||||
Json.Write(Path.Combine(updateDir, SavedogFiles.LastGood), new LastGoodVersion
|
||||
{
|
||||
Version = version,
|
||||
PackageName = packageName
|
||||
});
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
|
||||
private static void ClearDirectory(string dir)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (Directory.Exists(dir)) Directory.Delete(dir, true);
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
|
||||
private static void TryDelete(string path)
|
||||
{
|
||||
try { if (File.Exists(path)) File.Delete(path); } catch { }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<!--
|
||||
GC-SAVEDOG —— 启动器更新守护进程。
|
||||
|
||||
为什么不把替换逻辑留在启动器里:
|
||||
· 启动器正在运行,Windows 上无法覆盖自己的 exe;
|
||||
· 覆盖失败(断电 / 占用 / 权限)时启动器已经退出,没人能回滚;
|
||||
· 更新逻辑需要访问私钥验签,放在独立的最小进程里更容易审计。
|
||||
|
||||
本进程只做四件事:验签 → 校验 → 替换 → 看护(不健康就回滚)。
|
||||
它不引用 Avalonia,也不引用启动器程序集,源码里只链接 GC/src/Security/ 下的
|
||||
安全原语,保证「校验逻辑与启动器完全同一份实现」。
|
||||
-->
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<Nullable>enable</Nullable>
|
||||
<RootNamespace>GC.Savedog</RootNamespace>
|
||||
<AssemblyName>GC-SAVEDOG</AssemblyName>
|
||||
<InvariantGlobalization>true</InvariantGlobalization>
|
||||
|
||||
<!--
|
||||
裁剪发布:自包含单文件不裁剪约 70MB,裁剪后 14MB 左右。
|
||||
守护进程要跟着更新包一起下发,体积直接影响下载与校验时间。
|
||||
|
||||
裁剪的前提是**不用运行时反射**:JSON 全部走 SavedogJsonContext 的源生成类型信息
|
||||
(见 SavedogJson.cs)。若给这里新加类型却忘了注册,未裁剪的调试构建看不出来,
|
||||
只有发布产物会在运行时报 NotSupportedException —— 测试用例里有一次真实 apply,
|
||||
会覆盖到。
|
||||
-->
|
||||
<PublishTrimmed>true</PublishTrimmed>
|
||||
<TrimMode>full</TrimMode>
|
||||
<JsonSerializerIsReflectionEnabledByDefault>false</JsonSerializerIsReflectionEnabledByDefault>
|
||||
|
||||
<!-- 只保留必要的卫星资源,裁剪后再压一层体积 -->
|
||||
<SatelliteResourceLanguages>en</SatelliteResourceLanguages>
|
||||
<DebugType>none</DebugType>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<!-- 与启动器共用同一份安全实现,避免两套逻辑各说各话。
|
||||
ManifestLoader 依赖启动器的 RepoVersion 模型,守护进程不需要,排除。 -->
|
||||
<Compile Include="..\GC\src\Security\**\*.cs" Exclude="..\GC\src\Security\ManifestLoader.cs" LinkBase="Security" />
|
||||
<Compile Include="..\GC\src\Services\Json.cs" Link="Shared\Json.cs" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -0,0 +1,34 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
|
||||
namespace GC.Savedog;
|
||||
|
||||
/// <summary>同时写 stdout 与 .GC/update/savedog.log,便于用户离线排查。</summary>
|
||||
internal sealed class Log
|
||||
{
|
||||
private readonly string? _path;
|
||||
private readonly object _gate = new();
|
||||
|
||||
public Log(string? path) => _path = path;
|
||||
|
||||
public void Info(string message) => Write("INFO ", message);
|
||||
public void Warn(string message) => Write("WARN ", message);
|
||||
public void Error(string message) => Write("ERROR", message);
|
||||
|
||||
private void Write(string level, string message)
|
||||
{
|
||||
var line = $"{DateTime.Now:yyyy-MM-dd HH:mm:ss} [{level}] {message}";
|
||||
Console.WriteLine(line);
|
||||
if (string.IsNullOrWhiteSpace(_path)) return;
|
||||
try
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
var dir = Path.GetDirectoryName(_path!);
|
||||
if (!string.IsNullOrEmpty(dir)) Directory.CreateDirectory(dir);
|
||||
File.AppendAllText(_path!, line + "\n");
|
||||
}
|
||||
}
|
||||
catch { /* 日志失败不能影响更新 */ }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,347 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using GC.Services;
|
||||
|
||||
namespace GC.Savedog;
|
||||
|
||||
/// <summary>
|
||||
/// GC-SAVEDOG 命令行。
|
||||
///
|
||||
/// GC-SAVEDOG apply --update <.GC/update> [--install <dir>] [--wait-pid N]
|
||||
/// [--timeout 45] [--dry-run] [--json]
|
||||
/// GC-SAVEDOG verify --manifest <version.json> [--require 1] [--json]
|
||||
/// GC-SAVEDOG verify-model --dir <model/<id>> --id <id> [--json]
|
||||
/// GC-SAVEDOG keygen [--out .signing] [--key-id gc-2026-11]
|
||||
/// GC-SAVEDOG sign --manifest <version.json> [--key .signing/gc-signing.pem]
|
||||
/// [--key-id ...] [--out <file>]
|
||||
/// GC-SAVEDOG status --update <.GC/update> [--json]
|
||||
/// </summary>
|
||||
internal static class Program
|
||||
{
|
||||
private const string DefaultKeyId = "gc-2026-11";
|
||||
private const string DefaultKeyPath = ".signing/gc-signing.pem";
|
||||
|
||||
private static int Main(string[] args)
|
||||
{
|
||||
try { Console.OutputEncoding = Encoding.UTF8; } catch { }
|
||||
|
||||
// 必须在任何 Json.Read/Write 之前接上源生成上下文(裁剪构建必需)
|
||||
SavedogJson.Initialize();
|
||||
|
||||
if (args.Length == 0 || args[0] is "-h" or "--help" or "help")
|
||||
{
|
||||
Help();
|
||||
return 0;
|
||||
}
|
||||
|
||||
var command = args[0].ToLowerInvariant();
|
||||
var rest = args.Skip(1).ToArray();
|
||||
var options = Parse(rest);
|
||||
|
||||
return command switch
|
||||
{
|
||||
"apply" => Apply(options),
|
||||
"verify" => Verify(options),
|
||||
"verify-model" => VerifyModel(options),
|
||||
"keygen" => Keygen(options),
|
||||
"sign" => Sign(options),
|
||||
"status" => Status(options),
|
||||
"version" or "--version" => PrintVersion(),
|
||||
_ => Unknown(command)
|
||||
};
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ apply
|
||||
|
||||
private static int Apply(Dictionary<string, string> options)
|
||||
{
|
||||
var updateDir = Option(options, "update", "");
|
||||
if (string.IsNullOrWhiteSpace(updateDir))
|
||||
{
|
||||
Console.Error.WriteLine("apply 需要 --update <.GC/update>");
|
||||
return 3;
|
||||
}
|
||||
|
||||
var log = new Log(Path.Combine(Path.GetFullPath(updateDir), SavedogFiles.Log));
|
||||
var applyOptions = new ApplyOptions
|
||||
{
|
||||
UpdateDir = updateDir,
|
||||
InstallDir = Option(options, "install", null),
|
||||
WaitPid = Int(options, "wait-pid", 0),
|
||||
TimeoutSeconds = Int(options, "timeout", 45),
|
||||
DryRun = Flag(options, "dry-run"),
|
||||
Force = Flag(options, "force"),
|
||||
RequireSignature = Int(options, "require-signature", 1) != 0
|
||||
};
|
||||
|
||||
var applier = new Applier(applyOptions, log);
|
||||
var code = applier.Run();
|
||||
if (Flag(options, "json"))
|
||||
{
|
||||
if (applyOptions.DryRun)
|
||||
{
|
||||
// dry-run 不落盘,state.json 里是上一次的真实结果,直接打印会误导调用方
|
||||
var request = Json.Read<SavedogRequest>(
|
||||
Path.Combine(Path.GetFullPath(updateDir), SavedogFiles.ApplyRequest));
|
||||
Console.WriteLine(Json.Serialize(new SavedogState
|
||||
{
|
||||
Status = code == 0 ? "checked" : "failed",
|
||||
Version = request?.Version ?? "",
|
||||
PackageName = request?.PackageName ?? "",
|
||||
Verified = code == 0,
|
||||
Message = code == 0 ? "校验全部通过(未安装,dry-run)" : "校验未通过(dry-run)"
|
||||
}));
|
||||
}
|
||||
else
|
||||
{
|
||||
var state = Json.Read<SavedogState>(
|
||||
Path.Combine(Path.GetFullPath(updateDir), SavedogFiles.State));
|
||||
Console.WriteLine(Json.Serialize(state));
|
||||
}
|
||||
}
|
||||
return code;
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ verify
|
||||
|
||||
private static int Verify(Dictionary<string, string> options)
|
||||
{
|
||||
var manifest = Option(options, "manifest", "");
|
||||
if (string.IsNullOrWhiteSpace(manifest) || !File.Exists(manifest))
|
||||
{
|
||||
Console.Error.WriteLine("verify 需要 --manifest <version.json>");
|
||||
return 3;
|
||||
}
|
||||
|
||||
var require = Int(options, "require", 1) != 0;
|
||||
var text = File.ReadAllText(manifest);
|
||||
var result = ManifestSignature.Verify(text, require);
|
||||
|
||||
if (Flag(options, "json"))
|
||||
{
|
||||
var report = new VerifyReport
|
||||
{
|
||||
Trust = result.Trust.ToString(),
|
||||
KeyId = result.KeyId,
|
||||
Error = result.Error
|
||||
};
|
||||
foreach (var key in SignatureKeyring.Keys)
|
||||
report.TrustedKeys.Add(new TrustedKey
|
||||
{
|
||||
KeyId = key.KeyId,
|
||||
Fingerprint = ManifestSignature.PublicKeyFingerprint(key.PublicKeyBase64)
|
||||
});
|
||||
Console.WriteLine(Json.Serialize(report));
|
||||
}
|
||||
else
|
||||
{
|
||||
Console.WriteLine($"信任状态: {result.Trust}");
|
||||
if (result.KeyId != null) Console.WriteLine($"密钥: {result.KeyId}");
|
||||
if (result.Error != null) Console.WriteLine($"说明: {result.Error}");
|
||||
foreach (var key in SignatureKeyring.Keys)
|
||||
Console.WriteLine($"受信任公钥: {key.KeyId} ({ManifestSignature.PublicKeyFingerprint(key.PublicKeyBase64)})");
|
||||
}
|
||||
|
||||
return result.IsTrusted ? 0 : 2;
|
||||
}
|
||||
|
||||
private static int VerifyModel(Dictionary<string, string> options)
|
||||
{
|
||||
var dir = Option(options, "dir", "");
|
||||
var id = Option(options, "id", "");
|
||||
if (string.IsNullOrWhiteSpace(dir) || string.IsNullOrWhiteSpace(id))
|
||||
{
|
||||
Console.Error.WriteLine("verify-model 需要 --dir <model 目录> --id <模型 id>");
|
||||
return 3;
|
||||
}
|
||||
|
||||
var result = ModelIntegrity.VerifyForLoad(Path.GetFullPath(dir), id);
|
||||
if (Flag(options, "json"))
|
||||
Console.WriteLine(Json.Serialize(new VerifyModelReport
|
||||
{
|
||||
Ok = result.Ok,
|
||||
Present = result.Present,
|
||||
Message = result.Message
|
||||
}));
|
||||
else
|
||||
Console.WriteLine($"{(result.Ok ? "OK" : "FAIL")} 记录={(result.Present ? "有" : "无")} {result.Message}");
|
||||
|
||||
return result.Ok ? 0 : 2;
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ keygen / sign
|
||||
|
||||
private static int Keygen(Dictionary<string, string> options)
|
||||
{
|
||||
var outDir = Option(options, "out", ".signing")!;
|
||||
var keyId = Option(options, "key-id", DefaultKeyId)!;
|
||||
Directory.CreateDirectory(outDir);
|
||||
|
||||
using var key = ECDsa.Create(ECCurve.NamedCurves.nistP256);
|
||||
var privatePath = Path.Combine(outDir, "gc-signing.pem");
|
||||
var publicPath = Path.Combine(outDir, "gc-signing.pub");
|
||||
|
||||
File.WriteAllText(privatePath, key.ExportPkcs8PrivateKeyPem());
|
||||
var publicBase64 = ManifestSignature.ExportPublicKeyBase64(key);
|
||||
File.WriteAllText(publicPath, publicBase64 + "\n");
|
||||
|
||||
try
|
||||
{
|
||||
if (!OperatingSystem.IsWindows())
|
||||
File.SetUnixFileMode(privatePath, UnixFileMode.UserRead | UnixFileMode.UserWrite);
|
||||
}
|
||||
catch { }
|
||||
|
||||
Console.WriteLine("已生成 ECDSA P-256 密钥对:");
|
||||
Console.WriteLine(" 私钥(绝不要提交): " + privatePath);
|
||||
Console.WriteLine(" 公钥(写进源码) : " + publicPath);
|
||||
Console.WriteLine(" keyId : " + keyId);
|
||||
Console.WriteLine(" 公钥 Base64 : " + publicBase64);
|
||||
Console.WriteLine(" 公钥指纹 : " + ManifestSignature.PublicKeyFingerprint(publicBase64));
|
||||
Console.WriteLine();
|
||||
Console.WriteLine("把下面一行加进 GC/src/Security/SignatureKeyring.cs 的 Keys 列表:");
|
||||
Console.WriteLine($" new KeyEntry(\"{keyId}\", \"{publicBase64}\"),");
|
||||
return 0;
|
||||
}
|
||||
|
||||
private static int Sign(Dictionary<string, string> options)
|
||||
{
|
||||
var manifest = Option(options, "manifest", "");
|
||||
var keyPath = Option(options, "key", DefaultKeyPath)!;
|
||||
var keyId = Option(options, "key-id",
|
||||
Environment.GetEnvironmentVariable("GC_SIGNING_KEY_ID") ?? DefaultKeyId)!;
|
||||
|
||||
if (string.IsNullOrWhiteSpace(manifest) || !File.Exists(manifest))
|
||||
{
|
||||
Console.Error.WriteLine("sign 需要 --manifest <version.json>");
|
||||
return 3;
|
||||
}
|
||||
|
||||
using var key = ManifestSignature.TryLoadPrivateKey(keyPath);
|
||||
if (key == null)
|
||||
{
|
||||
Console.Error.WriteLine($"找不到可用的签名私钥: {Path.GetFullPath(keyPath)}");
|
||||
return 4;
|
||||
}
|
||||
|
||||
var text = File.ReadAllText(manifest);
|
||||
var signed = ManifestSignature.SignDocument(text, key, keyId);
|
||||
var output = Option(options, "out", manifest)!;
|
||||
File.WriteAllText(output, signed);
|
||||
|
||||
var check = ManifestSignature.Verify(signed, requireSignature: true);
|
||||
Console.WriteLine($"已签名: {output}({check.Trust})");
|
||||
return check.Trust == ManifestTrust.Verified ? 0 : 5;
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ status
|
||||
|
||||
private static int Status(Dictionary<string, string> options)
|
||||
{
|
||||
var updateDir = Path.GetFullPath(Option(options, "update", ".GC/update")!);
|
||||
var state = Json.Read<SavedogState>(Path.Combine(updateDir, SavedogFiles.State));
|
||||
var lastGood = Json.Read<LastGoodVersion>(Path.Combine(updateDir, SavedogFiles.LastGood));
|
||||
var health = StartupHealth.Read(updateDir);
|
||||
|
||||
if (Flag(options, "json"))
|
||||
{
|
||||
Console.WriteLine(Json.Serialize(new StatusReport
|
||||
{
|
||||
State = state,
|
||||
LastGood = lastGood,
|
||||
Health = health
|
||||
}));
|
||||
return 0;
|
||||
}
|
||||
|
||||
Console.WriteLine(state == null
|
||||
? "没有更新记录"
|
||||
: $"最近更新: {state.Status} v{state.Version} -> {state.Message}({state.At})");
|
||||
Console.WriteLine(lastGood == null
|
||||
? "上次成功版本: 未知"
|
||||
: $"上次成功版本: v{lastGood.Version}({lastGood.PackageName})");
|
||||
Console.WriteLine(health == null
|
||||
? "健康标记: 无"
|
||||
: $"健康标记: v{health.Version} pid={health.Pid} ok={health.Ok}");
|
||||
return 0;
|
||||
}
|
||||
|
||||
private static int PrintVersion()
|
||||
{
|
||||
Console.WriteLine("GC-SAVEDOG 1.0.0");
|
||||
Console.WriteLine("签名算法: " + ManifestSignature.Algorithm);
|
||||
return 0;
|
||||
}
|
||||
|
||||
private static int Unknown(string command)
|
||||
{
|
||||
Console.Error.WriteLine($"未知命令: {command}");
|
||||
Help();
|
||||
return 3;
|
||||
}
|
||||
|
||||
private static void Help()
|
||||
{
|
||||
Console.WriteLine("""
|
||||
GC-SAVEDOG —— 启动器更新守护进程
|
||||
|
||||
apply --update <.GC/update> [--install <dir>] [--wait-pid N]
|
||||
[--timeout 45] [--dry-run] [--force] [--json]
|
||||
verify --manifest <version.json> [--require 1] [--json]
|
||||
verify-model --dir <model/ID> --id <ID> [--json]
|
||||
keygen [--out .signing] [--key-id gc-2026-11]
|
||||
sign --manifest <version.json> [--key .signing/gc-signing.pem] [--out <file>]
|
||||
status --update <.GC/update> [--json]
|
||||
|
||||
退出码:0 成功 / 2 验签失败(拒绝) / 3 参数或申请错误 / 5 包校验失败 / 8 已回滚
|
||||
""");
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ 参数
|
||||
|
||||
private static Dictionary<string, string> Parse(string[] args)
|
||||
{
|
||||
var map = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
|
||||
for (var i = 0; i < args.Length; i++)
|
||||
{
|
||||
var arg = args[i];
|
||||
if (!arg.StartsWith("--", StringComparison.Ordinal))
|
||||
{
|
||||
map[arg] = "1";
|
||||
continue;
|
||||
}
|
||||
|
||||
var name = arg[2..];
|
||||
var eq = name.IndexOf('=');
|
||||
if (eq > 0)
|
||||
{
|
||||
map[name[..eq]] = name[(eq + 1)..];
|
||||
continue;
|
||||
}
|
||||
|
||||
if (i + 1 < args.Length && !args[i + 1].StartsWith("--", StringComparison.Ordinal))
|
||||
{
|
||||
map[name] = args[++i];
|
||||
continue;
|
||||
}
|
||||
map[name] = "1";
|
||||
}
|
||||
return map;
|
||||
}
|
||||
|
||||
private static string? Option(Dictionary<string, string> options, string name, string? fallback)
|
||||
=> options.TryGetValue(name, out var value) ? value : fallback;
|
||||
|
||||
private static int Int(Dictionary<string, string> options, string name, int fallback)
|
||||
=> options.TryGetValue(name, out var value) && int.TryParse(value, out var parsed)
|
||||
? parsed : fallback;
|
||||
|
||||
private static bool Flag(Dictionary<string, string> options, string name)
|
||||
=> options.TryGetValue(name, out var value) &&
|
||||
(value == "1" || value.Equals("true", StringComparison.OrdinalIgnoreCase));
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using GC.Services;
|
||||
|
||||
namespace GC.Savedog;
|
||||
|
||||
/// <summary>
|
||||
/// GC-SAVEDOG 是裁剪发布的(PublishTrimmed),反射式序列化在裁剪后会失效:
|
||||
/// trimmer 认为「没人 new 过」的构造函数会被删掉,运行时反序列化直接抛
|
||||
/// <c>NotSupportedException</c>。因此守护进程把所有 JSON 类型都注册进源生成上下文,
|
||||
/// 编译期生成类型信息,运行时零反射。
|
||||
///
|
||||
/// 新增需要读写的 JSON 类型时,记得在这里补一行 <c>[JsonSerializable]</c>,
|
||||
/// 否则会在裁剪产物里报错(未裁剪的调试构建看不出问题)。
|
||||
/// </summary>
|
||||
[JsonSourceGenerationOptions(
|
||||
PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase,
|
||||
PropertyNameCaseInsensitive = true,
|
||||
WriteIndented = true,
|
||||
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
|
||||
AllowTrailingCommas = true,
|
||||
ReadCommentHandling = JsonCommentHandling.Skip)]
|
||||
[JsonSerializable(typeof(SavedogRequest))]
|
||||
[JsonSerializable(typeof(SavedogState))]
|
||||
[JsonSerializable(typeof(LastGoodVersion))]
|
||||
[JsonSerializable(typeof(StartupHealth.HealthRecord))]
|
||||
[JsonSerializable(typeof(ModelIntegrityFile))]
|
||||
[JsonSerializable(typeof(VerifyReport))]
|
||||
[JsonSerializable(typeof(StatusReport))]
|
||||
[JsonSerializable(typeof(VerifyModelReport))]
|
||||
internal partial class SavedogJsonContext : JsonSerializerContext
|
||||
{
|
||||
// 源生成器已提供 (JsonSerializerOptions) 构造函数;实例化时传入启动器的那套选项,
|
||||
// 让两边写出的 JSON 完全同款(中文不转成 \uXXXX、缩进一致),便于直接 diff 排查。
|
||||
}
|
||||
|
||||
/// <summary><c>verify --json</c> 的输出。</summary>
|
||||
internal sealed class VerifyReport
|
||||
{
|
||||
public string Trust { get; set; } = "";
|
||||
public string? KeyId { get; set; }
|
||||
public string? Error { get; set; }
|
||||
public List<TrustedKey> TrustedKeys { get; set; } = new();
|
||||
}
|
||||
|
||||
internal sealed class TrustedKey
|
||||
{
|
||||
public string KeyId { get; set; } = "";
|
||||
public string Fingerprint { get; set; } = "";
|
||||
}
|
||||
|
||||
/// <summary><c>status --json</c> 的输出。</summary>
|
||||
internal sealed class StatusReport
|
||||
{
|
||||
public SavedogState? State { get; set; }
|
||||
public LastGoodVersion? LastGood { get; set; }
|
||||
public StartupHealth.HealthRecord? Health { get; set; }
|
||||
}
|
||||
|
||||
/// <summary><c>verify-model --json</c> 的输出。</summary>
|
||||
internal sealed class VerifyModelReport
|
||||
{
|
||||
public bool Ok { get; set; }
|
||||
public bool Present { get; set; }
|
||||
public string Message { get; set; } = "";
|
||||
}
|
||||
|
||||
/// <summary>把共享的 <see cref="Json"/> 接到源生成上下文上。</summary>
|
||||
internal static class SavedogJson
|
||||
{
|
||||
private static readonly SavedogJsonContext Context = new(new JsonSerializerOptions(Json.Options));
|
||||
|
||||
public static void Initialize()
|
||||
{
|
||||
Json.TypeInfoProvider = type => Context.GetTypeInfo(type);
|
||||
}
|
||||
}
|
||||
@@ -3,23 +3,21 @@ Microsoft Visual Studio Solution File, Format Version 12.00
|
||||
# Visual Studio Version 17
|
||||
VisualStudioVersion = 17.0.31903.59
|
||||
MinimumVisualStudioVersion = 10.0.40219.1
|
||||
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{827E0CD3-B72D-47B6-A68D-7590B98EB39B}"
|
||||
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "GC-BOOT", "GC-BOOT", "{827E0CD3-B72D-47B6-A68D-7590B98EB39B}"
|
||||
EndProject
|
||||
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "main", "main", "{ABAA6554-252E-13CE-1B40-0464A7DBA771}"
|
||||
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "GC-DOWNLOAD", "GC-DOWNLOAD", "{BCA2AA3E-F98F-43A1-9D31-239103C303F7}"
|
||||
EndProject
|
||||
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "dotnet", "dotnet", "{F2BBD9FE-F148-5687-ED21-3ABA515A9B22}"
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GC-BOOT", "GC-BOOT\GC-BOOT.csproj", "{2E3BE2DB-1C4B-4EA0-9523-43EE910BD54C}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EarthModelStudio", "src\main\dotnet\EarthModelStudio\EarthModelStudio.csproj", "{2E3BE2DB-1C4B-4EA0-9523-43EE910BD54C}"
|
||||
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "GC", "GC", "{3E72BF5C-0B5E-D5BD-DCAE-6B991004B4A5}"
|
||||
EndProject
|
||||
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "test", "test", "{3E72BF5C-0B5E-D5BD-DCAE-6B991004B4A5}"
|
||||
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{09578AA7-0862-3E52-D2AA-D8F7E863B74B}"
|
||||
EndProject
|
||||
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "dotnet", "dotnet", "{09578AA7-0862-3E52-D2AA-D8F7E863B74B}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EarthModelStudio.Tests", "src\test\dotnet\EarthModelStudio.Tests\EarthModelStudio.Tests.csproj", "{D15CB92F-5E5C-4516-8D07-C244FC0CD113}"
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GC.Tests", "GC\src\test\dotnet\GC.Tests\GC.Tests.csproj", "{D15CB92F-5E5C-4516-8D07-C244FC0CD113}"
|
||||
EndProject
|
||||
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "_sdk", "_sdk", "{26AABC0C-8B8D-F9B8-86B4-01B1A96D59F4}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EarthModelStudio.ModelSdk", "model\_sdk\EarthModelStudio.ModelSdk\EarthModelStudio.ModelSdk.csproj", "{C8FAB8D5-CAB7-42D7-8A1F-4B79771A2CE0}"
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GC.ModelSdk", "model\_sdk\GC.ModelSdk\GC.ModelSdk.csproj", "{C8FAB8D5-CAB7-42D7-8A1F-4B79771A2CE0}"
|
||||
EndProject
|
||||
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "model", "model", "{62B8A37E-7066-D91A-6443-87D4E6CE63FE}"
|
||||
EndProject
|
||||
@@ -35,6 +33,14 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{EADF0841-BEC
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EarthRevolutionModel", "model\earth-revolution\src\EarthRevolutionModel.csproj", "{6BD9C21B-8F06-4F60-A087-696B6F03CC25}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GC.Core", "GC\src\GC.Core.csproj", "{AB63C416-5783-4FB9-A162-5BBA32E8BFCC}"
|
||||
EndProject
|
||||
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "_sdk", "_sdk", "{6C38EF76-7D14-0C76-0B88-84F29EAA96CD}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GC-DOWNLOAD", "GC-DOWNLOAD\GC-DOWNLOAD.csproj", "{98F52FEA-43B5-4FE1-97A9-AF644AAFEFA3}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GC-SAVEDOG", "GC-SAVEDOG\GC-SAVEDOG.csproj", "{B169F2BF-9E60-40BF-824E-0486573DA65E}"
|
||||
EndProject
|
||||
Global
|
||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||
Debug|Any CPU = Debug|Any CPU
|
||||
@@ -105,15 +111,48 @@ Global
|
||||
{6BD9C21B-8F06-4F60-A087-696B6F03CC25}.Release|x64.Build.0 = Release|Any CPU
|
||||
{6BD9C21B-8F06-4F60-A087-696B6F03CC25}.Release|x86.ActiveCfg = Release|Any CPU
|
||||
{6BD9C21B-8F06-4F60-A087-696B6F03CC25}.Release|x86.Build.0 = Release|Any CPU
|
||||
{AB63C416-5783-4FB9-A162-5BBA32E8BFCC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{AB63C416-5783-4FB9-A162-5BBA32E8BFCC}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{AB63C416-5783-4FB9-A162-5BBA32E8BFCC}.Debug|x64.ActiveCfg = Debug|Any CPU
|
||||
{AB63C416-5783-4FB9-A162-5BBA32E8BFCC}.Debug|x64.Build.0 = Debug|Any CPU
|
||||
{AB63C416-5783-4FB9-A162-5BBA32E8BFCC}.Debug|x86.ActiveCfg = Debug|Any CPU
|
||||
{AB63C416-5783-4FB9-A162-5BBA32E8BFCC}.Debug|x86.Build.0 = Debug|Any CPU
|
||||
{AB63C416-5783-4FB9-A162-5BBA32E8BFCC}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{AB63C416-5783-4FB9-A162-5BBA32E8BFCC}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{AB63C416-5783-4FB9-A162-5BBA32E8BFCC}.Release|x64.ActiveCfg = Release|Any CPU
|
||||
{AB63C416-5783-4FB9-A162-5BBA32E8BFCC}.Release|x64.Build.0 = Release|Any CPU
|
||||
{AB63C416-5783-4FB9-A162-5BBA32E8BFCC}.Release|x86.ActiveCfg = Release|Any CPU
|
||||
{AB63C416-5783-4FB9-A162-5BBA32E8BFCC}.Release|x86.Build.0 = Release|Any CPU
|
||||
{98F52FEA-43B5-4FE1-97A9-AF644AAFEFA3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{98F52FEA-43B5-4FE1-97A9-AF644AAFEFA3}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{98F52FEA-43B5-4FE1-97A9-AF644AAFEFA3}.Debug|x64.ActiveCfg = Debug|Any CPU
|
||||
{98F52FEA-43B5-4FE1-97A9-AF644AAFEFA3}.Debug|x64.Build.0 = Debug|Any CPU
|
||||
{98F52FEA-43B5-4FE1-97A9-AF644AAFEFA3}.Debug|x86.ActiveCfg = Debug|Any CPU
|
||||
{98F52FEA-43B5-4FE1-97A9-AF644AAFEFA3}.Debug|x86.Build.0 = Debug|Any CPU
|
||||
{98F52FEA-43B5-4FE1-97A9-AF644AAFEFA3}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{98F52FEA-43B5-4FE1-97A9-AF644AAFEFA3}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{98F52FEA-43B5-4FE1-97A9-AF644AAFEFA3}.Release|x64.ActiveCfg = Release|Any CPU
|
||||
{98F52FEA-43B5-4FE1-97A9-AF644AAFEFA3}.Release|x64.Build.0 = Release|Any CPU
|
||||
{98F52FEA-43B5-4FE1-97A9-AF644AAFEFA3}.Release|x86.ActiveCfg = Release|Any CPU
|
||||
{98F52FEA-43B5-4FE1-97A9-AF644AAFEFA3}.Release|x86.Build.0 = Release|Any CPU
|
||||
{B169F2BF-9E60-40BF-824E-0486573DA65E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{B169F2BF-9E60-40BF-824E-0486573DA65E}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{B169F2BF-9E60-40BF-824E-0486573DA65E}.Debug|x64.ActiveCfg = Debug|Any CPU
|
||||
{B169F2BF-9E60-40BF-824E-0486573DA65E}.Debug|x64.Build.0 = Debug|Any CPU
|
||||
{B169F2BF-9E60-40BF-824E-0486573DA65E}.Debug|x86.ActiveCfg = Debug|Any CPU
|
||||
{B169F2BF-9E60-40BF-824E-0486573DA65E}.Debug|x86.Build.0 = Debug|Any CPU
|
||||
{B169F2BF-9E60-40BF-824E-0486573DA65E}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{B169F2BF-9E60-40BF-824E-0486573DA65E}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{B169F2BF-9E60-40BF-824E-0486573DA65E}.Release|x64.ActiveCfg = Release|Any CPU
|
||||
{B169F2BF-9E60-40BF-824E-0486573DA65E}.Release|x64.Build.0 = Release|Any CPU
|
||||
{B169F2BF-9E60-40BF-824E-0486573DA65E}.Release|x86.ActiveCfg = Release|Any CPU
|
||||
{B169F2BF-9E60-40BF-824E-0486573DA65E}.Release|x86.Build.0 = Release|Any CPU
|
||||
EndGlobalSection
|
||||
GlobalSection(SolutionProperties) = preSolution
|
||||
HideSolutionNode = FALSE
|
||||
EndGlobalSection
|
||||
GlobalSection(NestedProjects) = preSolution
|
||||
{ABAA6554-252E-13CE-1B40-0464A7DBA771} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B}
|
||||
{F2BBD9FE-F148-5687-ED21-3ABA515A9B22} = {ABAA6554-252E-13CE-1B40-0464A7DBA771}
|
||||
{2E3BE2DB-1C4B-4EA0-9523-43EE910BD54C} = {F2BBD9FE-F148-5687-ED21-3ABA515A9B22}
|
||||
{3E72BF5C-0B5E-D5BD-DCAE-6B991004B4A5} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B}
|
||||
{2E3BE2DB-1C4B-4EA0-9523-43EE910BD54C} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B}
|
||||
{09578AA7-0862-3E52-D2AA-D8F7E863B74B} = {3E72BF5C-0B5E-D5BD-DCAE-6B991004B4A5}
|
||||
{D15CB92F-5E5C-4516-8D07-C244FC0CD113} = {09578AA7-0862-3E52-D2AA-D8F7E863B74B}
|
||||
{C8FAB8D5-CAB7-42D7-8A1F-4B79771A2CE0} = {26AABC0C-8B8D-F9B8-86B4-01B1A96D59F4}
|
||||
@@ -123,5 +162,8 @@ Global
|
||||
{0B92F86C-37C2-3C12-904C-85123CE34F4C} = {62B8A37E-7066-D91A-6443-87D4E6CE63FE}
|
||||
{EADF0841-BEC2-9A74-4322-069D7B5A6EBB} = {0B92F86C-37C2-3C12-904C-85123CE34F4C}
|
||||
{6BD9C21B-8F06-4F60-A087-696B6F03CC25} = {EADF0841-BEC2-9A74-4322-069D7B5A6EBB}
|
||||
{AB63C416-5783-4FB9-A162-5BBA32E8BFCC} = {09578AA7-0862-3E52-D2AA-D8F7E863B74B}
|
||||
{6C38EF76-7D14-0C76-0B88-84F29EAA96CD} = {62B8A37E-7066-D91A-6443-87D4E6CE63FE}
|
||||
{98F52FEA-43B5-4FE1-97A9-AF644AAFEFA3} = {BCA2AA3E-F98F-43A1-9D31-239103C303F7}
|
||||
EndGlobalSection
|
||||
EndGlobal
|
||||
@@ -0,0 +1,48 @@
|
||||
<Application xmlns="https://github.com/avaloniaui"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:vm="using:GC.ViewModels"
|
||||
xmlns:views="using:GC.Views"
|
||||
x:Class="GC.App"
|
||||
RequestedThemeVariant="Light">
|
||||
|
||||
<Application.DataTemplates>
|
||||
<DataTemplate DataType="{x:Type vm:HomeViewModel}">
|
||||
<views:HomeView />
|
||||
</DataTemplate>
|
||||
<DataTemplate DataType="{x:Type vm:DownloadViewModel}">
|
||||
<views:DownloadView />
|
||||
</DataTemplate>
|
||||
<DataTemplate DataType="{x:Type vm:SettingsViewModel}">
|
||||
<views:SettingsView />
|
||||
</DataTemplate>
|
||||
<DataTemplate DataType="{x:Type vm:AboutViewModel}">
|
||||
<views:AboutView />
|
||||
</DataTemplate>
|
||||
</Application.DataTemplates>
|
||||
|
||||
<Application.Resources>
|
||||
<Color x:Key="SystemAccentColor">#2F6BFF</Color>
|
||||
|
||||
<!--
|
||||
FluentTheme 的按钮模板在 :pointerover / :pressed 时会用这些主题资源
|
||||
覆盖 ContentPresenter 的画刷。若与 AppTheme.axaml 里通过 Button 属性
|
||||
设置的 hover 颜色不一致,两套机制会互相覆盖,导致光标移动时渲染错乱。
|
||||
这里把它们统一指向与按钮样式相同的颜色。
|
||||
-->
|
||||
<SolidColorBrush x:Key="ButtonBackgroundPointerOver">#EDF2FC</SolidColorBrush>
|
||||
<SolidColorBrush x:Key="ButtonBackgroundPressed">#DDE7F8</SolidColorBrush>
|
||||
<SolidColorBrush x:Key="ButtonBorderBrushPointerOver">#BAC9E6</SolidColorBrush>
|
||||
<SolidColorBrush x:Key="ButtonBorderBrushPressed">#9FB4DD</SolidColorBrush>
|
||||
<SolidColorBrush x:Key="ButtonForegroundPointerOver">#111A2E</SolidColorBrush>
|
||||
<SolidColorBrush x:Key="ButtonForegroundPressed">#111A2E</SolidColorBrush>
|
||||
|
||||
<SolidColorBrush x:Key="AccentButtonBackground">#2F6BFF</SolidColorBrush>
|
||||
<SolidColorBrush x:Key="AccentButtonBackgroundPointerOver">#1F4FD0</SolidColorBrush>
|
||||
<SolidColorBrush x:Key="AccentButtonBackgroundPressed">#183FA8</SolidColorBrush>
|
||||
</Application.Resources>
|
||||
|
||||
<Application.Styles>
|
||||
<FluentTheme />
|
||||
<StyleInclude Source="avares://GC.Core/Styles/AppTheme.axaml" />
|
||||
</Application.Styles>
|
||||
</Application>
|
||||
@@ -0,0 +1,134 @@
|
||||
using System;
|
||||
using System.Threading.Tasks;
|
||||
using Avalonia;
|
||||
using Avalonia.Controls;
|
||||
using Avalonia.Controls.ApplicationLifetimes;
|
||||
using Avalonia.Markup.Xaml;
|
||||
using GC.Services;
|
||||
using GC.ViewModels;
|
||||
using GC.Views;
|
||||
|
||||
namespace GC;
|
||||
|
||||
public partial class App : Application
|
||||
{
|
||||
public override void Initialize() => AvaloniaXamlLoader.Load(this);
|
||||
|
||||
public override void OnFrameworkInitializationCompleted()
|
||||
{
|
||||
if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
|
||||
{
|
||||
var services = AppServices.Create();
|
||||
|
||||
// 诊断模式:只验证模型程序集能否加载(发布包里也用它做冒烟测试)
|
||||
if (Environment.GetEnvironmentVariable("EMS_SELFTEST") == "1")
|
||||
{
|
||||
var code = SelfTest(services);
|
||||
Avalonia.Threading.Dispatcher.UIThread.Post(
|
||||
() => desktop.Shutdown(code), Avalonia.Threading.DispatcherPriority.Background);
|
||||
return;
|
||||
}
|
||||
|
||||
// 启动加速:先建空窗口并显示,再在首帧之后构造 ViewModel。
|
||||
// MainViewModel 会扫描模型、加载封面、读设置,同步做会让
|
||||
// 「双击到看见窗口」明显变慢;先出窗口,内容随后填充。
|
||||
var window = new MainWindow();
|
||||
window.Show();
|
||||
|
||||
// 健康标记:GC-SAVEDOG 正在等这个文件。主窗口能显示出来,
|
||||
// 就说明「新版本确实能启动」,它据此决定保留新版还是回滚。
|
||||
StartupHealth.MarkHealthy(services.Paths.UpdateRoot,
|
||||
LauncherRuntimeInfo.CurrentLauncherVersion);
|
||||
|
||||
// 首帧之后再构造 ViewModel:Post 而非依赖 Opened,
|
||||
// 因为 Opened 在某些情况下不触发(headless / 部分平台),
|
||||
// 会导致 DataContext 一直是 null、主页面白屏。
|
||||
// 扫描模型 / 加载封面在后台线程做,UI 线程只负责赋值,
|
||||
// 这样窗口能立刻响应,不会卡在白屏。
|
||||
MainViewModel vm = null!;
|
||||
Task.Run(() => new MainViewModel(services))
|
||||
.ContinueWith(t =>
|
||||
{
|
||||
vm = t.Result;
|
||||
Avalonia.Threading.Dispatcher.UIThread.Post(() =>
|
||||
{
|
||||
window.DataContext = vm;
|
||||
WireMainViewModel(vm, window, services, desktop);
|
||||
}, Avalonia.Threading.DispatcherPriority.Background);
|
||||
}, System.Threading.Tasks.TaskScheduler.Default);
|
||||
|
||||
// 应用图标不依赖 ViewModel,先设好让窗口一出现就有图标
|
||||
try
|
||||
{
|
||||
using var iconStream = Avalonia.Platform.AssetLoader.Open(
|
||||
new Uri("avares://GC.Core/Assets/icon.png"));
|
||||
window.Icon = new Avalonia.Controls.WindowIcon(iconStream);
|
||||
}
|
||||
catch { /* 图标缺失不影响启动 */ }
|
||||
|
||||
desktop.MainWindow = window;
|
||||
desktop.ShutdownMode = ShutdownMode.OnMainWindowClose;
|
||||
}
|
||||
|
||||
base.OnFrameworkInitializationCompleted();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 主窗口显示后再接上 ViewModel:绑定对话框、启动后台更新检查。
|
||||
/// 拆出来是为了让窗口先出现,模型扫描不影响「双击到出窗口」。
|
||||
/// </summary>
|
||||
private static void WireMainViewModel(MainViewModel vm, MainWindow window,
|
||||
AppServices services, IClassicDesktopStyleApplicationLifetime desktop)
|
||||
{
|
||||
_ = desktop;
|
||||
vm.ConfirmHandler = async message =>
|
||||
{
|
||||
var dialog = new ConfirmWindow(message);
|
||||
return await dialog.ShowDialog<bool>(window);
|
||||
};
|
||||
|
||||
// 发现启动器新版本:弹窗询问,用户选「更新」才下载并安排替换
|
||||
vm.LauncherUpdateHandler = async newVersion =>
|
||||
{
|
||||
var dialog = new ConfirmWindow(
|
||||
title: "发现新版本",
|
||||
message: $"启动器有新版本 v{newVersion},是否立即更新?\n\n" +
|
||||
"更新会下载新版程序,下次启动时自动替换当前版本;" +
|
||||
"选择取消则继续使用当前版本,但模型仍会更新到最新。",
|
||||
confirmText: "更新",
|
||||
cancelText: "取消");
|
||||
return await dialog.ShowDialog<bool>(window);
|
||||
};
|
||||
|
||||
// 主窗口已显示,后台检查模型 / 启动器更新,不阻塞界面
|
||||
if (Environment.GetEnvironmentVariable("EMS_NO_UPDATE") != "1")
|
||||
{
|
||||
Avalonia.Threading.Dispatcher.UIThread.Post(
|
||||
() => _ = vm.RunStartupUpdateAsync(),
|
||||
Avalonia.Threading.DispatcherPriority.Background);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>逐个加载模型,打印结果;返回退出码(0 = 全部成功)。</summary>
|
||||
private static int SelfTest(AppServices services)
|
||||
{
|
||||
var packages = services.Models.Scan();
|
||||
Console.WriteLine($"模型库: {services.Paths.ModelRoot}");
|
||||
Console.WriteLine($"模型数: {packages.Count}");
|
||||
var failed = 0;
|
||||
foreach (var package in packages)
|
||||
{
|
||||
try
|
||||
{
|
||||
using var loaded = services.ModelHost.Load(package, () => { });
|
||||
Console.WriteLine($"OK {package.Id} -> {loaded.View.GetType().FullName}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
failed++;
|
||||
Console.WriteLine($"FAIL {package.Id}: {ex.Message}");
|
||||
}
|
||||
}
|
||||
return failed == 0 ? 0 : 1;
|
||||
}
|
||||
}
|
||||
@@ -1,11 +1,12 @@
|
||||
{
|
||||
"app.name": "Earth Model Studio",
|
||||
"app.name": "Morris GC",
|
||||
"app.tagline": "Astronomy teaching models · visual launcher",
|
||||
"app.version": "Version",
|
||||
"app.platform": "Platform",
|
||||
"nav.home": "Home",
|
||||
"nav.download": "Download",
|
||||
"nav.settings": "Settings",
|
||||
"nav.about": "About",
|
||||
"home.title": "Model library",
|
||||
"home.subtitle": "Pick a model and explain rotation, revolution and the seasons with an interactive 3D scene.",
|
||||
"home.launch": "Launch model",
|
||||
@@ -14,7 +15,7 @@
|
||||
"home.installed": "Installed models",
|
||||
"home.count": "{0} models",
|
||||
"home.empty": "No models yet",
|
||||
"home.emptyHint": "Models download from gitcode on startup; offline you can drop them into .GC/model/ or import a source on the Download page.",
|
||||
"home.emptyHint": "Models are checked and downloaded on startup. Offline: drop model folders into .GC/model/ and reopen, or retry from the Download page once online.",
|
||||
"home.emptyAction": "Get models",
|
||||
"home.open": "Open folder",
|
||||
"home.delete": "Delete",
|
||||
@@ -74,6 +75,7 @@
|
||||
"set.memory.current": "In use",
|
||||
"set.memory.unit": "MB",
|
||||
"set.memory.hint": "2048 MB or more is recommended; 1024 MB for low-end devices.",
|
||||
"set.memory.auto": "Auto (allocate based on device memory)",
|
||||
"set.preallocate": "Preload land data at startup",
|
||||
"set.preallocate.desc": "Faster first frame, slightly slower startup.",
|
||||
"set.sources": "Model sources",
|
||||
@@ -1,11 +1,12 @@
|
||||
{
|
||||
"app.name": "地球模型工作室",
|
||||
"app.name": "Morris GC",
|
||||
"app.tagline": "天文教学模型 · 可视化启动器",
|
||||
"app.version": "版本",
|
||||
"app.platform": "平台",
|
||||
"nav.home": "主页",
|
||||
"nav.download": "下载",
|
||||
"nav.settings": "设置",
|
||||
"nav.about": "关于",
|
||||
"home.title": "模型库",
|
||||
"home.subtitle": "选择模型,用可交互的三维演示讲清自转、公转与四季成因。",
|
||||
"home.launch": "启动模型",
|
||||
@@ -14,7 +15,7 @@
|
||||
"home.installed": "已安装模型",
|
||||
"home.count": "{0} 个模型",
|
||||
"home.empty": "模型库还是空的",
|
||||
"home.emptyHint": "启动时会从 gitcode 自动下载模型;离线可把模型放进 .GC/model/,或在「下载」页导入模型源。",
|
||||
"home.emptyHint": "启动时会自动检查并下载模型。若当前断网:可把模型文件夹放进 .GC/model/ 后重新打开,或联网后在「下载」页点重试。",
|
||||
"home.emptyAction": "去下载模型",
|
||||
"home.open": "打开目录",
|
||||
"home.delete": "删除",
|
||||
@@ -74,6 +75,7 @@
|
||||
"set.memory.current": "当前占用",
|
||||
"set.memory.unit": "MB",
|
||||
"set.memory.hint": "建议 2048 MB 以上,低配设备可选 1024 MB。",
|
||||
"set.memory.auto": "自动(根据设备内存分配)",
|
||||
"set.preallocate": "启动时预加载模型地表数据",
|
||||
"set.preallocate.desc": "打开后首帧更快,启动耗时略增。",
|
||||
"set.sources": "模型源",
|
||||
|
After Width: | Height: | Size: 350 KiB |
|
After Width: | Height: | Size: 18 KiB |
|
After Width: | Height: | Size: 51 KiB |
|
After Width: | Height: | Size: 2.4 KiB |
|
After Width: | Height: | Size: 136 KiB |
|
After Width: | Height: | Size: 6.5 KiB |
|
After Width: | Height: | Size: 88 KiB |
|
After Width: | Height: | Size: 51 KiB |
@@ -1,19 +1,18 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<OutputType>WinExe</OutputType>
|
||||
<Nullable>enable</Nullable>
|
||||
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
|
||||
<RootNamespace>EarthModelStudio</RootNamespace>
|
||||
<AssemblyName>EarthModelStudio</AssemblyName>
|
||||
<ApplicationManifest>app.manifest</ApplicationManifest>
|
||||
<RootNamespace>GC</RootNamespace>
|
||||
<AssemblyName>GC.Core</AssemblyName>
|
||||
<AvaloniaUseCompiledBindingsByDefault>false</AvaloniaUseCompiledBindingsByDefault>
|
||||
<BuiltInComInteropSupport>true</BuiltInComInteropSupport>
|
||||
<InvariantGlobalization>false</InvariantGlobalization>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<AvaloniaResource Include="Assets\**" />
|
||||
<Compile Include="..\..\GC-DRAW\PlayerWindow.cs" />
|
||||
<Compile Remove="test\**\*.cs" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
@@ -23,9 +22,8 @@
|
||||
<PackageReference Include="CommunityToolkit.Mvvm" Version="$(MvvmVersion)" />
|
||||
</ItemGroup>
|
||||
|
||||
<!-- 模型契约:启动器与模型唯一的共享代码(不含任何渲染/业务) -->
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\..\..\model\_sdk\EarthModelStudio.ModelSdk\EarthModelStudio.ModelSdk.csproj" />
|
||||
<ProjectReference Include="..\..\model\_sdk\GC.ModelSdk\GC.ModelSdk.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -2,7 +2,7 @@ using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace EarthModelStudio.Models;
|
||||
namespace GC.Models;
|
||||
|
||||
/// <summary>应用设置,持久化到 data/settings.json。</summary>
|
||||
public sealed class AppSettings
|
||||
@@ -13,12 +13,15 @@ public sealed class AppSettings
|
||||
/// <summary>light | dark</summary>
|
||||
public string Theme { get; set; } = "light";
|
||||
|
||||
/// <summary>渲染帧率:24 / 30 / 60</summary>
|
||||
public int RenderFps { get; set; } = 30;
|
||||
/// <summary>渲染帧率:24 / 30 / 60 / 90 / 120(上限 120,关闭 VSync 同步)</summary>
|
||||
public int RenderFps { get; set; } = 120;
|
||||
|
||||
/// <summary>启动时运行内存分配(MB)——决定场景缓存/纹理预算。</summary>
|
||||
public int MemoryMb { get; set; } = 2048;
|
||||
|
||||
/// <summary>自动模式:根据设备可用内存自动计算预算(忽略 MemoryMb)。</summary>
|
||||
public bool MemoryAuto { get; set; } = true;
|
||||
|
||||
/// <summary>启动时检查模型源更新。</summary>
|
||||
public bool CheckSourceOnStartup { get; set; }
|
||||
|
||||
@@ -35,7 +38,7 @@ public sealed class AppSettings
|
||||
public bool AutoUpdateOnStartup { get; set; } = true;
|
||||
|
||||
/// <summary>默认更新仓库地址。</summary>
|
||||
public string UpdateRepository { get; set; } = "https://gitcode.com/2509_92447106/GC";
|
||||
public string UpdateRepository { get; set; } = "https://gitcode.com/Morris_1/GC";
|
||||
|
||||
/// <summary>版本清单地址覆盖(留空则按 UpdateRepository 拼接)。</summary>
|
||||
public string? UpdateManifestUrl { get; set; }
|
||||
@@ -43,6 +46,12 @@ public sealed class AppSettings
|
||||
/// <summary>本地模型源目录(离线教学场景可指向 U 盘 / 共享盘里的仓库)。</summary>
|
||||
public string? UpdateLocalRoot { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 要求版本清单必须带**有效签名**。默认开启:关闭后只警告不拦截,
|
||||
/// 等于放弃「清单被篡改」的防护,只建议在自建私有构建里临时关闭。
|
||||
/// </summary>
|
||||
public bool RequireSignedManifest { get; set; } = true;
|
||||
|
||||
/// <summary>已安装的模型版本:id -> version.json 里的版本。</summary>
|
||||
public Dictionary<string, string> InstalledModelVersions { get; set; } = new();
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
using System.Collections.Generic;
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace EarthModelStudio.Models;
|
||||
namespace GC.Models;
|
||||
|
||||
/// <summary>model/<id>/<id>.json 的内容。</summary>
|
||||
public sealed class ModelManifest
|
||||
@@ -28,6 +28,18 @@ public sealed class ModelManifest
|
||||
public string? License { get; set; }
|
||||
public string? UpdatedAt { get; set; }
|
||||
public string? MinAppVersion { get; set; }
|
||||
/// <summary>模型窗口标题栏配色(模型自带,跟随模型界面风格);缺省时用深色。</summary>
|
||||
public WindowChrome? Chrome { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>模型窗口自建标题栏的颜色,由模型清单提供。</summary>
|
||||
public sealed class WindowChrome
|
||||
{
|
||||
public string? TitleBar { get; set; }
|
||||
public string? TitleBorder { get; set; }
|
||||
public string? TitleText { get; set; }
|
||||
public string? Button { get; set; }
|
||||
public string? Frame { get; set; }
|
||||
}
|
||||
|
||||
public sealed class ModelPackage
|
||||
@@ -0,0 +1,67 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Text.Encodings.Web;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Nodes;
|
||||
|
||||
namespace GC.Services;
|
||||
|
||||
/// <summary>
|
||||
/// 规范化 JSON:签名与验签必须对完全相同的字节做运算,
|
||||
/// 否则「同一份内容、不同缩进/键序」会得出不同签名。
|
||||
///
|
||||
/// 规则(写进 README,第三方可复现):
|
||||
/// 1. 对象键按 Unicode 码点升序递归排序
|
||||
/// 2. 无缩进、无多余空白,UTF-8 编码,不带 BOM
|
||||
/// 3. 数字沿用源文本(不做浮点重排)
|
||||
/// 4. 非 ASCII 字符不转义(Encoder = UnsafeRelaxedJsonEscaping)
|
||||
/// 5. 签名时先移除根级 <c>signature</c> 字段
|
||||
/// </summary>
|
||||
public static class CanonicalJson
|
||||
{
|
||||
private static readonly JsonSerializerOptions Options = new()
|
||||
{
|
||||
WriteIndented = false,
|
||||
Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping
|
||||
};
|
||||
|
||||
/// <summary>把 JSON 文本规范化;解析失败返回 null。</summary>
|
||||
public static byte[]? Normalize(string text, bool dropSignatureField)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(text)) return null;
|
||||
try
|
||||
{
|
||||
var node = JsonNode.Parse(text);
|
||||
if (node is not JsonObject obj) return null;
|
||||
if (dropSignatureField) obj.Remove("signature");
|
||||
var sorted = SortNode(obj);
|
||||
return Encoding.UTF8.GetBytes(sorted?.ToJsonString(Options) ?? "{}");
|
||||
}
|
||||
catch (JsonException)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static JsonNode? SortNode(JsonNode? node)
|
||||
{
|
||||
switch (node)
|
||||
{
|
||||
case JsonObject obj:
|
||||
var result = new JsonObject();
|
||||
foreach (var pair in obj.OrderBy(p => p.Key, StringComparer.Ordinal))
|
||||
result[pair.Key] = SortNode(pair.Value);
|
||||
return result;
|
||||
|
||||
case JsonArray array:
|
||||
var list = new JsonArray();
|
||||
foreach (var item in array) list.Add(SortNode(item));
|
||||
return list;
|
||||
|
||||
default:
|
||||
return node?.DeepClone();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
|
||||
namespace GC.Services;
|
||||
|
||||
/// <summary>
|
||||
/// 内容哈希(可复现的指纹算法)。
|
||||
///
|
||||
/// 算法固定如下,构建端与客户端必须完全一致,否则会误判为「被篡改」:
|
||||
/// <code>
|
||||
/// fileHash = SHA256(文件字节)
|
||||
/// dirHash = SHA256( 按相对路径 ordinal 升序,对每个文件拼接
|
||||
/// "<相对路径>\0<fileHash>\n" )
|
||||
/// </code>
|
||||
/// 相对路径统一用 <c>/</c> 分隔;跳过以 <c>.</c> 开头的文件、<c>bin/</c>、<c>obj/</c>、
|
||||
/// <c>*.user</c>;不包含时间戳、权限位、文件顺序等元数据 —— 同样内容必然同样哈希。
|
||||
/// </summary>
|
||||
public static class ContentHash
|
||||
{
|
||||
public static string Sha256Hex(byte[] data)
|
||||
=> Convert.ToHexString(SHA256.HashData(data)).ToLowerInvariant();
|
||||
|
||||
public static string Sha256Hex(string text)
|
||||
=> Sha256Hex(Encoding.UTF8.GetBytes(text));
|
||||
|
||||
public static string Sha256File(string path)
|
||||
{
|
||||
using var stream = File.OpenRead(path);
|
||||
return Convert.ToHexString(SHA256.HashData(stream)).ToLowerInvariant();
|
||||
}
|
||||
|
||||
/// <summary>目录内所有参与分发的文件 -> { 相对路径 : sha256 }。</summary>
|
||||
public static Dictionary<string, string> MapFiles(string directory)
|
||||
{
|
||||
var map = new Dictionary<string, string>(StringComparer.Ordinal);
|
||||
if (!Directory.Exists(directory)) return map;
|
||||
|
||||
foreach (var file in Directory.GetFiles(directory, "*", SearchOption.AllDirectories))
|
||||
{
|
||||
var rel = Path.GetRelativePath(directory, file).Replace('\\', '/');
|
||||
if (!Distributable(rel)) continue;
|
||||
map[rel] = Sha256File(file);
|
||||
}
|
||||
return map;
|
||||
}
|
||||
|
||||
/// <summary>按上述算法计算目录指纹。</summary>
|
||||
public static string DirectoryHash(string directory)
|
||||
=> DirectoryHash(MapFiles(directory));
|
||||
|
||||
public static string DirectoryHash(IReadOnlyDictionary<string, string> files)
|
||||
{
|
||||
var builder = new StringBuilder();
|
||||
foreach (var pair in files.OrderBy(p => p.Key, StringComparer.Ordinal))
|
||||
builder.Append(pair.Key).Append('\0').Append(pair.Value).Append('\n');
|
||||
|
||||
return Sha256Hex(Encoding.UTF8.GetBytes(builder.ToString()));
|
||||
}
|
||||
|
||||
/// <summary>目录指纹;目录不存在时返回空串(区别于空目录的哈希)。</summary>
|
||||
public static string DirectoryHashOrEmpty(string directory)
|
||||
=> Directory.Exists(directory) ? DirectoryHash(directory) : "";
|
||||
|
||||
public static bool Distributable(string relativePath)
|
||||
{
|
||||
var rel = relativePath.Replace('\\', '/');
|
||||
if (rel.StartsWith('.')) return false;
|
||||
if (rel.Contains("/.")) return false;
|
||||
if (rel.StartsWith("bin/", StringComparison.OrdinalIgnoreCase)) return false;
|
||||
if (rel.StartsWith("obj/", StringComparison.OrdinalIgnoreCase)) return false;
|
||||
if (rel.Contains("/bin/", StringComparison.OrdinalIgnoreCase)) return false;
|
||||
if (rel.Contains("/obj/", StringComparison.OrdinalIgnoreCase)) return false;
|
||||
if (rel.EndsWith(".user", StringComparison.OrdinalIgnoreCase)) return false;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
using System;
|
||||
using System.Text.Json;
|
||||
|
||||
namespace GC.Services;
|
||||
|
||||
/// <summary>
|
||||
/// 把「远端拿到的清单文本」变成 <see cref="RepoVersion"/>,同时带上验签结论。
|
||||
///
|
||||
/// 设计上把「验签」和「允不允许用」分开:
|
||||
/// · 本方法只负责**如实报告**信任状态;
|
||||
/// · 允不允许安装由 <c>UpdateService</c> / <c>LauncherUpdater</c> 按策略决定。
|
||||
/// 这样开发态可以「警告但继续」,发布版可以「直接拒绝」,而解析逻辑只有一份。
|
||||
/// </summary>
|
||||
public static class ManifestLoader
|
||||
{
|
||||
public static RepoVersion? Parse(string? text, out ManifestVerification verification)
|
||||
{
|
||||
verification = ManifestSignature.Verify(text, requireSignature: true);
|
||||
if (string.IsNullOrWhiteSpace(text)) return null;
|
||||
|
||||
RepoVersion? version;
|
||||
try
|
||||
{
|
||||
version = JsonSerializer.Deserialize<RepoVersion>(text!, Json.Options);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.Error.WriteLine($"版本清单解析失败: {ex.Message}");
|
||||
return null;
|
||||
}
|
||||
|
||||
if (version == null) return null;
|
||||
|
||||
// 平台键回填:RepoPackage 自己要能说出「我属于哪个 RID」,
|
||||
// 否则下载端无法推导 dist/<系统>-<架构> 这类兜底路径。
|
||||
foreach (var pair in version.Launcher.Packages)
|
||||
if (pair.Value != null) pair.Value.Rid = pair.Key;
|
||||
|
||||
version.SignatureTrust = verification.Trust.ToString();
|
||||
version.SignatureKeyId = verification.KeyId;
|
||||
version.SignatureError = verification.Error;
|
||||
return version;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,172 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using System.Text.Encodings.Web;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Nodes;
|
||||
|
||||
namespace GC.Services;
|
||||
|
||||
/// <summary>清单可信度。</summary>
|
||||
public enum ManifestTrust
|
||||
{
|
||||
/// <summary>签名有效,且密钥在受信任列表里。</summary>
|
||||
Verified,
|
||||
/// <summary>本机构建没有配置受信任密钥 —— 只能跳过验签(会打警告)。</summary>
|
||||
Skipped,
|
||||
/// <summary>清单没有签名,但客户端要求签名。</summary>
|
||||
Unsigned,
|
||||
/// <summary>有签名但验证失败:内容被改过 / 密钥不对 / 结构损坏。</summary>
|
||||
Invalid
|
||||
}
|
||||
|
||||
public sealed record ManifestVerification(ManifestTrust Trust, string? KeyId, string? Error)
|
||||
{
|
||||
public bool IsTrusted => Trust is ManifestTrust.Verified or ManifestTrust.Skipped;
|
||||
public bool IsRejected => Trust is ManifestTrust.Unsigned or ManifestTrust.Invalid;
|
||||
|
||||
public static ManifestVerification Ok(string keyId) => new(ManifestTrust.Verified, keyId, null);
|
||||
public static ManifestVerification Skip() => new(ManifestTrust.Skipped, null,
|
||||
"未配置受信任公钥,已跳过验签");
|
||||
public static ManifestVerification Bad(string error) => new(ManifestTrust.Invalid, null, error);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 版本清单签名(ECDSA P-256 / SHA-256)。
|
||||
///
|
||||
/// 为什么不用 sha256 了事:sha256 只能证明「下载没坏」,不能证明「这份清单是我发的」。
|
||||
/// 仓库被入侵时攻击者可以同时改清单和 sha256 —— 只有签名需要**没有放进仓库**的私钥,
|
||||
/// 才能把「篡改清单」这条路堵死。
|
||||
///
|
||||
/// 为什么不自己实现 Ed25519:手写椭圆曲线实现出错就是静默失效。.NET 8 自带
|
||||
/// ECDSA P-256,跨平台、无第三方依赖,安全性等价于工程需要。
|
||||
///
|
||||
/// 信任链:内置公钥 → 验证 version.json → 得到各发布包的 sha256 → 校验下载到的 zip
|
||||
/// → 校验解压出的模型文件 → 加载 dll。
|
||||
/// </summary>
|
||||
public static class ManifestSignature
|
||||
{
|
||||
public const string Algorithm = "ECDSA-P256-SHA256";
|
||||
|
||||
private static readonly JsonSerializerOptions WriteOptions = new()
|
||||
{
|
||||
WriteIndented = true,
|
||||
Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping
|
||||
};
|
||||
|
||||
// ------------------------------------------------------------------ 验签
|
||||
|
||||
/// <summary>
|
||||
/// 校验清单文本的签名。<paramref name="requireSignature"/> 为 true 时,
|
||||
/// 无签名视为失败;为 false 时无签名只返回 <see cref="ManifestTrust.Unsigned"/>,
|
||||
/// 由调用方决定是否放行(开发态用)。
|
||||
/// </summary>
|
||||
public static ManifestVerification Verify(string? text, bool requireSignature)
|
||||
{
|
||||
if (SignatureKeyring.Keys.Count == 0) return ManifestVerification.Skip();
|
||||
if (string.IsNullOrWhiteSpace(text)) return ManifestVerification.Bad("清单内容为空");
|
||||
|
||||
JsonObject root;
|
||||
try
|
||||
{
|
||||
root = JsonNode.Parse(text!) as JsonObject ?? throw new JsonException("根节点不是对象");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
return ManifestVerification.Bad("清单不是合法 JSON: " + ex.Message);
|
||||
}
|
||||
|
||||
if (root["signature"] is not JsonObject signature)
|
||||
return requireSignature
|
||||
? new ManifestVerification(ManifestTrust.Unsigned, null, "清单缺少签名")
|
||||
: new ManifestVerification(ManifestTrust.Unsigned, null, "清单未签名");
|
||||
|
||||
var keyId = signature["keyId"]?.GetValue<string>() ?? "";
|
||||
var value = signature["value"]?.GetValue<string>() ?? "";
|
||||
var alg = signature["alg"]?.GetValue<string>() ?? Algorithm;
|
||||
|
||||
if (!string.Equals(alg, Algorithm, StringComparison.OrdinalIgnoreCase))
|
||||
return new ManifestVerification(ManifestTrust.Invalid, keyId, $"不支持的签名算法: {alg}");
|
||||
if (value.Length == 0)
|
||||
return new ManifestVerification(ManifestTrust.Invalid, keyId, "签名为空");
|
||||
|
||||
var key = SignatureKeyring.Find(keyId);
|
||||
if (key == null)
|
||||
return new ManifestVerification(ManifestTrust.Invalid, keyId, $"未知签名密钥: {keyId}");
|
||||
|
||||
var payload = CanonicalJson.Normalize(text!, dropSignatureField: true);
|
||||
if (payload == null)
|
||||
return new ManifestVerification(ManifestTrust.Invalid, keyId, "无法规范化清单");
|
||||
|
||||
try
|
||||
{
|
||||
var sig = Convert.FromBase64String(value);
|
||||
using var ecdsa = ECDsa.Create();
|
||||
ecdsa.ImportSubjectPublicKeyInfo(Convert.FromBase64String(key.PublicKeyBase64), out _);
|
||||
var ok = ecdsa.VerifyData(payload, sig, HashAlgorithmName.SHA256,
|
||||
DSASignatureFormat.IeeeP1363FixedFieldConcatenation);
|
||||
return ok
|
||||
? ManifestVerification.Ok(key.KeyId)
|
||||
: new ManifestVerification(ManifestTrust.Invalid, keyId, "签名与内容不符");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
return new ManifestVerification(ManifestTrust.Invalid, keyId, "验签异常: " + ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ 签名
|
||||
|
||||
/// <summary>用私钥给清单签名,返回写入了 <c>signature</c> 字段的新清单文本。</summary>
|
||||
public static string SignDocument(string text, ECDsa key, string keyId)
|
||||
{
|
||||
var payload = CanonicalJson.Normalize(text, dropSignatureField: true)
|
||||
?? throw new InvalidOperationException("清单不是合法 JSON,无法签名");
|
||||
|
||||
var signature = key.SignData(payload, HashAlgorithmName.SHA256,
|
||||
DSASignatureFormat.IeeeP1363FixedFieldConcatenation);
|
||||
var contentHash = Convert.ToHexString(SHA256.HashData(payload)).ToLowerInvariant();
|
||||
|
||||
var root = JsonNode.Parse(text) as JsonObject
|
||||
?? throw new InvalidOperationException("清单根节点不是对象");
|
||||
|
||||
root["signature"] = new JsonObject
|
||||
{
|
||||
["alg"] = Algorithm,
|
||||
["keyId"] = keyId,
|
||||
["value"] = Convert.ToBase64String(signature),
|
||||
["contentSha256"] = contentHash,
|
||||
["signedAt"] = DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ssZ")
|
||||
};
|
||||
|
||||
return root.ToJsonString(WriteOptions) + "\n";
|
||||
}
|
||||
|
||||
/// <summary>从 PEM 文件加载私钥(PKCS#8 或 SEC1 均可)。</summary>
|
||||
public static ECDsa? TryLoadPrivateKey(string path)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (!File.Exists(path)) return null;
|
||||
var pem = File.ReadAllText(path);
|
||||
if (pem.Contains("BEGIN", StringComparison.Ordinal) == false) return null;
|
||||
var key = ECDsa.Create();
|
||||
key.ImportFromPem(pem);
|
||||
return key;
|
||||
}
|
||||
catch
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>导出公钥(SPKI / Base64),用于写入客户端受信任列表。</summary>
|
||||
public static string ExportPublicKeyBase64(ECDsa key)
|
||||
=> Convert.ToBase64String(key.ExportSubjectPublicKeyInfo());
|
||||
|
||||
/// <summary>公钥指纹,便于人工核对两边的公钥是否一致。</summary>
|
||||
public static string PublicKeyFingerprint(string publicKeyBase64)
|
||||
=> Convert.ToHexString(SHA256.HashData(Convert.FromBase64String(publicKeyBase64)))
|
||||
.ToLowerInvariant()[..16];
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
|
||||
namespace GC.Services;
|
||||
|
||||
/// <summary>模型安装后落盘的完整性记录。</summary>
|
||||
public sealed class ModelIntegrityFile
|
||||
{
|
||||
public int Schema { get; set; } = 1;
|
||||
public string Id { get; set; } = "";
|
||||
public string Version { get; set; } = "";
|
||||
/// <summary>模型清单文件的 sha256。</summary>
|
||||
public string ManifestSha256 { get; set; } = "";
|
||||
/// <summary><id>.model 目录的目录指纹。</summary>
|
||||
public string FilesSha256 { get; set; } = "";
|
||||
/// <summary>关键文件(dll / json)逐文件哈希,用于加载前快速校验。</summary>
|
||||
public Dictionary<string, string> Files { get; set; } = new();
|
||||
public string InstalledAt { get; set; } = "";
|
||||
/// <summary>来源(远端源名 / 本地目录),便于排查。</summary>
|
||||
public string Source { get; set; } = "";
|
||||
}
|
||||
|
||||
public sealed record IntegrityResult(bool Ok, bool Present, string Message)
|
||||
{
|
||||
public static readonly IntegrityResult Missing =
|
||||
new(true, false, "没有完整性记录(本地/开发模型),跳过校验");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 模型包完整性校验:下载后复算、安装后落盘、加载前抽查。
|
||||
///
|
||||
/// 威胁模型:模型 dll 会被 <c>AssemblyLoadContext</c> 直接执行,等于任意代码。
|
||||
/// 如果版本清单被篡改(或本地文件被替换),攻击者就能让启动器加载他的 dll。
|
||||
/// 因此:
|
||||
/// 1. version.json(已签名)里带 manifestSha256 / filesSha256;
|
||||
/// 2. 下载到暂存目录后按同一算法复算,不一致直接丢弃,绝不安装;
|
||||
/// 3. 安装成功后写 <c><id>.integrity.json</c>;
|
||||
/// 4. 每次加载 dll 前抽查 dll / json 的哈希。
|
||||
/// </summary>
|
||||
public static class ModelIntegrity
|
||||
{
|
||||
public const string FileNameSuffix = ".integrity.json";
|
||||
|
||||
public static string IntegrityPath(string modelDirectory, string id)
|
||||
=> Path.Combine(modelDirectory, id + FileNameSuffix);
|
||||
|
||||
public static ModelIntegrityFile? Read(string modelDirectory, string id)
|
||||
=> Json.Read<ModelIntegrityFile>(IntegrityPath(modelDirectory, id));
|
||||
|
||||
public static void Write(string modelDirectory, string id, ModelIntegrityFile data)
|
||||
=> Json.Write(IntegrityPath(modelDirectory, id), data);
|
||||
|
||||
/// <summary>
|
||||
/// 计算某个模型包(清单 + 数据目录)的哈希。
|
||||
/// <paramref name="packageDirectory"/> 是包含 <c><id>.json</c> 与
|
||||
/// <c><id>.model/</c> 的那一层。
|
||||
/// </summary>
|
||||
public static (string ManifestSha256, string FilesSha256, Dictionary<string, string> Files)
|
||||
Compute(string packageDirectory, string id)
|
||||
{
|
||||
var manifestPath = Path.Combine(packageDirectory, id + ".json");
|
||||
var dataDir = Path.Combine(packageDirectory, id + ".model");
|
||||
|
||||
var manifestSha = File.Exists(manifestPath) ? ContentHash.Sha256File(manifestPath) : "";
|
||||
var files = ContentHash.MapFiles(dataDir);
|
||||
var filesSha = ContentHash.DirectoryHash(files);
|
||||
|
||||
var critical = new Dictionary<string, string>(StringComparer.Ordinal);
|
||||
foreach (var pair in files)
|
||||
{
|
||||
if (!IsCritical(pair.Key)) continue;
|
||||
critical[id + ".model/" + pair.Key] = pair.Value;
|
||||
}
|
||||
if (manifestSha.Length > 0) critical[id + ".json"] = manifestSha;
|
||||
|
||||
return (manifestSha, filesSha, critical);
|
||||
}
|
||||
|
||||
/// <summary>加载前校验:只查会被执行 / 解析的文件,保证 <c>OpenModel</c> 不被明显拖慢。</summary>
|
||||
public static IntegrityResult VerifyForLoad(string packageDirectory, string id)
|
||||
{
|
||||
var record = Read(packageDirectory, id);
|
||||
if (record == null) return IntegrityResult.Missing;
|
||||
|
||||
if (!string.Equals(record.Id, id, StringComparison.Ordinal))
|
||||
return new IntegrityResult(false, true, $"完整性记录与模型 id 不符: {record.Id}");
|
||||
|
||||
foreach (var pair in record.Files)
|
||||
{
|
||||
var path = Path.Combine(packageDirectory, pair.Key.Replace('/', Path.DirectorySeparatorChar));
|
||||
if (!File.Exists(path))
|
||||
return new IntegrityResult(false, true, $"缺少文件: {pair.Key}");
|
||||
|
||||
var actual = ContentHash.Sha256File(path);
|
||||
if (!string.Equals(actual, pair.Value, StringComparison.OrdinalIgnoreCase))
|
||||
return new IntegrityResult(false, true, $"文件已被修改: {pair.Key}");
|
||||
}
|
||||
|
||||
return new IntegrityResult(true, true, "完整性校验通过");
|
||||
}
|
||||
|
||||
private static bool IsCritical(string relativePath)
|
||||
{
|
||||
var rel = relativePath.Replace('\\', '/');
|
||||
return rel.EndsWith(".dll", StringComparison.OrdinalIgnoreCase) ||
|
||||
rel.EndsWith(".json", StringComparison.OrdinalIgnoreCase) ||
|
||||
rel.EndsWith(".dylib", StringComparison.OrdinalIgnoreCase) ||
|
||||
rel.EndsWith(".so", StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.IO.Compression;
|
||||
|
||||
namespace GC.Services;
|
||||
|
||||
/// <summary>
|
||||
/// 安全解压:更新包来自网络,必须当成不可信输入处理。
|
||||
///
|
||||
/// 拦截:
|
||||
/// · zip slip(<c>../</c>、绝对路径、盘符、UNC)
|
||||
/// · 符号链接 / 硬链接条目(解压后可指向系统任意文件)
|
||||
/// · zip 炸弹(条目数过多、解压后总体积过大、压缩比异常)
|
||||
/// 逐条校验通过后**自己写文件**,不使用 <see cref="ZipFile.ExtractToDirectory(string,string)"/>,
|
||||
/// 避免框架在写入阶段才发现问题、留下半成品。
|
||||
/// </summary>
|
||||
public static class SafeArchive
|
||||
{
|
||||
/// <summary>单个包最多条目数。</summary>
|
||||
public const int MaxEntries = 20000;
|
||||
|
||||
/// <summary>解压后总体积上限(2 GiB)。</summary>
|
||||
public const long MaxUncompressedBytes = 2L * 1024 * 1024 * 1024;
|
||||
|
||||
/// <summary>单个条目解压上限(1 GiB)。</summary>
|
||||
public const long MaxSingleEntryBytes = 1L * 1024 * 1024 * 1024;
|
||||
|
||||
/// <summary>压缩比上限:超过视为 zip 炸弹。</summary>
|
||||
public const int MaxCompressionRatio = 200;
|
||||
|
||||
public sealed record Inspection(int Entries, long UncompressedBytes, long CompressedBytes)
|
||||
{
|
||||
public double Ratio => CompressedBytes <= 0 ? 0 : (double)UncompressedBytes / CompressedBytes;
|
||||
}
|
||||
|
||||
/// <summary>只检查不解压:条目数、体积、路径、链接。发现问题抛异常。</summary>
|
||||
public static Inspection Inspect(string zipPath)
|
||||
{
|
||||
using var archive = ZipFile.OpenRead(zipPath);
|
||||
long total = 0;
|
||||
var count = 0;
|
||||
|
||||
foreach (var entry in archive.Entries)
|
||||
{
|
||||
count++;
|
||||
if (count > MaxEntries)
|
||||
throw new InvalidOperationException($"压缩包条目过多(>{MaxEntries}),疑似恶意包");
|
||||
|
||||
ValidateName(entry.FullName);
|
||||
AssertNotLink(entry);
|
||||
|
||||
if (entry.Length > MaxSingleEntryBytes)
|
||||
throw new InvalidOperationException($"条目过大: {entry.FullName}");
|
||||
|
||||
total += entry.Length;
|
||||
if (total > MaxUncompressedBytes)
|
||||
throw new InvalidOperationException("解压后体积超出上限,疑似 zip 炸弹");
|
||||
}
|
||||
|
||||
var compressed = new FileInfo(zipPath).Length;
|
||||
var inspection = new Inspection(count, total, compressed);
|
||||
if (compressed > 0 && inspection.Ratio > MaxCompressionRatio && total > 64L * 1024 * 1024)
|
||||
throw new InvalidOperationException($"压缩比异常({inspection.Ratio:0.#}:1),疑似 zip 炸弹");
|
||||
|
||||
return inspection;
|
||||
}
|
||||
|
||||
public static void ExtractToDirectory(string zipPath, string destination)
|
||||
{
|
||||
Inspect(zipPath);
|
||||
|
||||
Directory.CreateDirectory(destination);
|
||||
var destFull = Path.GetFullPath(destination)
|
||||
.TrimEnd(Path.DirectorySeparatorChar) + Path.DirectorySeparatorChar;
|
||||
|
||||
using var archive = ZipFile.OpenRead(zipPath);
|
||||
foreach (var entry in archive.Entries)
|
||||
{
|
||||
var name = entry.FullName.Replace('\\', '/');
|
||||
if (name.EndsWith("/", StringComparison.Ordinal))
|
||||
{
|
||||
Directory.CreateDirectory(Path.GetFullPath(Path.Combine(destFull, name)));
|
||||
continue;
|
||||
}
|
||||
|
||||
var target = Path.GetFullPath(Path.Combine(destFull, name));
|
||||
if (!target.StartsWith(destFull, StringComparison.Ordinal))
|
||||
throw new InvalidOperationException($"压缩包条目越界: {entry.FullName}");
|
||||
|
||||
var dir = Path.GetDirectoryName(target);
|
||||
if (!string.IsNullOrEmpty(dir)) Directory.CreateDirectory(dir);
|
||||
|
||||
using (var source = entry.Open())
|
||||
using (var output = new FileStream(target, FileMode.Create, FileAccess.Write,
|
||||
FileShare.None, 81920, FileOptions.None))
|
||||
{
|
||||
source.CopyTo(output);
|
||||
}
|
||||
|
||||
TryApplyUnixMode(entry, target);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>校验条目名,拒绝一切能逃出目标目录的写法。</summary>
|
||||
public static void ValidateName(string fullName)
|
||||
{
|
||||
var name = fullName.Replace('\\', '/');
|
||||
if (name.Length == 0) throw new InvalidOperationException("压缩包含空文件名条目");
|
||||
if (name.StartsWith('/')) throw new InvalidOperationException($"压缩包含绝对路径: {fullName}");
|
||||
if (name.StartsWith("//")) throw new InvalidOperationException($"压缩包含 UNC 路径: {fullName}");
|
||||
if (name.Length >= 2 && name[1] == ':')
|
||||
throw new InvalidOperationException($"压缩包含盘符路径: {fullName}");
|
||||
|
||||
foreach (var segment in name.Split('/'))
|
||||
{
|
||||
if (segment == "..")
|
||||
throw new InvalidOperationException($"压缩包含父目录穿越: {fullName}");
|
||||
}
|
||||
|
||||
if (name.Contains('\0'))
|
||||
throw new InvalidOperationException($"压缩包含非法字符: {fullName}");
|
||||
}
|
||||
|
||||
/// <summary>Unix 模式下 S_IFLNK = 0xA000,符号链接条目一律拒绝。</summary>
|
||||
private static void AssertNotLink(ZipArchiveEntry entry)
|
||||
{
|
||||
var mode = (entry.ExternalAttributes >> 16) & 0xF000;
|
||||
if (mode == 0xA000)
|
||||
throw new InvalidOperationException($"压缩包含符号链接条目: {entry.FullName}");
|
||||
}
|
||||
|
||||
private static void TryApplyUnixMode(ZipArchiveEntry entry, string target)
|
||||
{
|
||||
if (OperatingSystem.IsWindows()) return;
|
||||
try
|
||||
{
|
||||
var mode = (UnixFileMode)((entry.ExternalAttributes >> 16) & 0x1FF);
|
||||
if (mode == 0) return;
|
||||
File.SetUnixFileMode(target, mode);
|
||||
}
|
||||
catch { /* 权限位设置失败不影响文件内容 */ }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
using System;
|
||||
|
||||
namespace GC.Services;
|
||||
|
||||
/// <summary>
|
||||
/// 启动器 ↔ GC-SAVEDOG 的握手协议(都在 <c>.GC/update/</c> 下,全部相对路径)。
|
||||
///
|
||||
/// 流程:
|
||||
/// <code>
|
||||
/// launcher 下载并校验更新包
|
||||
/// -> 解压到 update/payload/
|
||||
/// -> 写 apply-request.json + 已验签的 version.json 副本
|
||||
/// -> 启动 GC-SAVEDOG apply --wait-pid <自己>
|
||||
/// -> 自己退出
|
||||
///
|
||||
/// GC-SAVEDOG
|
||||
/// -> 等父进程退出
|
||||
/// -> 重验签名 + 包 sha256 + 解压安全性
|
||||
/// -> 把 payload 移到安装目录(绝不覆盖已有版本)
|
||||
/// -> 启动新版,等 update/health.json
|
||||
/// -> 健康:删同平台旧版本;不健康:删新版、重启旧版
|
||||
/// -> 写 state.json(applied / rolledback / failed)
|
||||
/// </code>
|
||||
/// </summary>
|
||||
public static class SavedogFiles
|
||||
{
|
||||
public const string ApplyRequest = "apply-request.json";
|
||||
public const string State = "state.json";
|
||||
public const string Log = "savedog.log";
|
||||
public const string Health = StartupHealth.FileName;
|
||||
public const string LastGood = "last-good.json";
|
||||
|
||||
/// <summary>SAVEDOG 可执行文件名(各平台一致,Windows 带 .exe)。</summary>
|
||||
public static string ExecutableName =>
|
||||
OperatingSystem.IsWindows() ? "GC-SAVEDOG.exe" : "GC-SAVEDOG";
|
||||
}
|
||||
|
||||
/// <summary>启动器写入的更新申请。</summary>
|
||||
public sealed class SavedogRequest
|
||||
{
|
||||
public int Schema { get; set; } = 1;
|
||||
|
||||
/// <summary>新版本号,如 1.0.8。</summary>
|
||||
public string Version { get; set; } = "";
|
||||
|
||||
public string Rid { get; set; } = "";
|
||||
|
||||
/// <summary>文件名里的平台标签,如 mac-arm64。</summary>
|
||||
public string PlatformLabel { get; set; } = "";
|
||||
|
||||
/// <summary>payload 里的新版本包名(GC-1.0.8-mac-arm64.app / .exe)。</summary>
|
||||
public string PackageName { get; set; } = "";
|
||||
|
||||
/// <summary>payload 目录(相对 update 目录)。</summary>
|
||||
public string PayloadDir { get; set; } = "payload";
|
||||
|
||||
/// <summary>已验签清单的副本(相对 update 目录),用于二次验签。</summary>
|
||||
public string ManifestPath { get; set; } = "version.json";
|
||||
|
||||
/// <summary>更新包 zip 路径(相对 update 目录),SAVEDOG 自己解压,不信任预解压目录。</summary>
|
||||
public string PackageZip { get; set; } = "package.zip";
|
||||
|
||||
/// <summary>更新包 sha256(来自已验签清单)。</summary>
|
||||
public string? PackageSha256 { get; set; }
|
||||
|
||||
public long PackageSize { get; set; }
|
||||
|
||||
/// <summary>是否强制要求清单签名。</summary>
|
||||
public bool RequireSignature { get; set; } = true;
|
||||
|
||||
/// <summary>安装目录(相对 update 目录),由启动器按实际路径算出。</summary>
|
||||
public string InstallRelative { get; set; } = "../..";
|
||||
|
||||
public string CreatedAt { get; set; } = DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ssZ");
|
||||
}
|
||||
|
||||
/// <summary>SAVEDOG 的执行结果,写入 state.json 供界面显示。</summary>
|
||||
public sealed class SavedogState
|
||||
{
|
||||
public string Status { get; set; } = "unknown"; // applied | rolledback | failed | refused
|
||||
public string Version { get; set; } = "";
|
||||
public string? PreviousVersion { get; set; }
|
||||
public string PackageName { get; set; } = "";
|
||||
public string Message { get; set; } = "";
|
||||
public string At { get; set; } = DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ssZ");
|
||||
public bool Verified { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>上次成功启动的版本信息,回滚时用。</summary>
|
||||
public sealed class LastGoodVersion
|
||||
{
|
||||
public string Version { get; set; } = "";
|
||||
public string PackageName { get; set; } = "";
|
||||
public string At { get; set; } = DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ssZ");
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace GC.Services;
|
||||
|
||||
/// <summary>
|
||||
/// 受信任的签名公钥。
|
||||
///
|
||||
/// 公钥是公开的,写在源码里没有问题;**私钥永远不进仓库**
|
||||
/// (放在仓库根 <c>.signing/</c>,已在 .gitignore 中)。
|
||||
///
|
||||
/// 轮换密钥:用 <c>GC-SAVEDOG keygen</c> 生成新的一对,把新公钥追加到这里,
|
||||
/// 旧公钥保留一个版本周期,避免老客户端直接失效。
|
||||
/// 也可用环境变量临时注入(测试 / 私有构建):
|
||||
/// <c>GC_TRUSTED_KEYS="id1:base64;id2:base64"</c>
|
||||
/// </summary>
|
||||
public static class SignatureKeyring
|
||||
{
|
||||
public sealed record KeyEntry(string KeyId, string PublicKeyBase64, string? Note = null);
|
||||
|
||||
private static readonly List<KeyEntry> KeysInternal = new()
|
||||
{
|
||||
// 生产密钥(2026-11 生成)。指纹 b41b1dd6259ea9ed
|
||||
new KeyEntry(
|
||||
"gc-2026-11",
|
||||
"MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEny5YKVBZUzOyRcSiuutlGmBb4+xm" +
|
||||
"PrNDGshilBlpmFyWu5Atq+FGP2tn+8Or8V7OH+/7lhCmXu8jZuC5/5CWSw==",
|
||||
"GC 主发布密钥")
|
||||
};
|
||||
|
||||
static SignatureKeyring() => LoadFromEnvironment();
|
||||
|
||||
public static IReadOnlyList<KeyEntry> Keys => KeysInternal;
|
||||
|
||||
/// <summary>是否配置了受信任密钥(配置了就必须验签)。</summary>
|
||||
public static bool Enforced => KeysInternal.Count > 0;
|
||||
|
||||
public static KeyEntry? Find(string? keyId)
|
||||
{
|
||||
if (KeysInternal.Count == 0) return null;
|
||||
foreach (var key in KeysInternal)
|
||||
if (string.Equals(key.KeyId, keyId, StringComparison.Ordinal))
|
||||
return key;
|
||||
// 未写 keyId 且只有一个密钥时容忍(早期构建产物)
|
||||
if (string.IsNullOrWhiteSpace(keyId) && KeysInternal.Count == 1) return KeysInternal[0];
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>测试 / 私有分发用:追加一个受信任公钥。</summary>
|
||||
public static void Add(KeyEntry key)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(key.KeyId) || string.IsNullOrWhiteSpace(key.PublicKeyBase64)) return;
|
||||
if (Find(key.KeyId) != null) return;
|
||||
KeysInternal.Add(key);
|
||||
}
|
||||
|
||||
/// <summary>测试用:替换整个密钥环。</summary>
|
||||
public static void ReplaceAll(IEnumerable<KeyEntry> keys)
|
||||
{
|
||||
KeysInternal.Clear();
|
||||
foreach (var key in keys) KeysInternal.Add(key);
|
||||
}
|
||||
|
||||
private static void LoadFromEnvironment()
|
||||
{
|
||||
var raw = Environment.GetEnvironmentVariable("GC_TRUSTED_KEYS");
|
||||
if (string.IsNullOrWhiteSpace(raw)) return;
|
||||
foreach (var part in raw!.Split(';', StringSplitOptions.RemoveEmptyEntries))
|
||||
{
|
||||
var idx = part.IndexOf(':');
|
||||
if (idx <= 0 || idx >= part.Length - 1) continue;
|
||||
var keyId = part[..idx].Trim();
|
||||
var value = part[(idx + 1)..].Trim();
|
||||
if (keyId.Length == 0 || value.Length == 0) continue;
|
||||
if (Find(keyId) != null) continue;
|
||||
KeysInternal.Add(new KeyEntry(keyId, value, "来自 GC_TRUSTED_KEYS"));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
|
||||
namespace GC.Services;
|
||||
|
||||
/// <summary>
|
||||
/// 启动成功的健康标记。
|
||||
///
|
||||
/// 新版启动器启动后写这个文件;GC-SAVEDOG 在替换完程序后会等它出现,
|
||||
/// 等不到就回滚到旧版本 —— 这样「新版本一启动就崩」不会把用户卡死。
|
||||
/// </summary>
|
||||
public static class StartupHealth
|
||||
{
|
||||
public const string FileName = "health.json";
|
||||
|
||||
public static string PathFor(string updateRoot) => Path.Combine(updateRoot, FileName);
|
||||
|
||||
/// <summary>主窗口显示后调用:证明本次启动真的跑起来了。</summary>
|
||||
public static void MarkHealthy(string updateRoot, string version)
|
||||
{
|
||||
try
|
||||
{
|
||||
Directory.CreateDirectory(updateRoot);
|
||||
Json.Write(PathFor(updateRoot), new HealthRecord
|
||||
{
|
||||
Version = version,
|
||||
Pid = Environment.ProcessId,
|
||||
At = DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ssZ"),
|
||||
Ok = true
|
||||
});
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.Error.WriteLine($"写入健康标记失败: {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
public static HealthRecord? Read(string updateRoot)
|
||||
=> Json.Read<HealthRecord>(PathFor(updateRoot));
|
||||
|
||||
public static void Clear(string updateRoot)
|
||||
{
|
||||
try
|
||||
{
|
||||
var path = PathFor(updateRoot);
|
||||
if (File.Exists(path)) File.Delete(path);
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
|
||||
public sealed class HealthRecord
|
||||
{
|
||||
public string Version { get; set; } = "";
|
||||
public int Pid { get; set; }
|
||||
public string At { get; set; } = "";
|
||||
public bool Ok { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,331 @@
|
||||
using System;
|
||||
using System.Threading.Tasks;
|
||||
using System.IO;
|
||||
|
||||
namespace GC.Services;
|
||||
|
||||
/// <summary>
|
||||
/// 运行目录约定(可执行文件旁边,不内置任何模型):
|
||||
/// <code>
|
||||
/// <安装目录>/
|
||||
/// GC(.exe | .app/...)
|
||||
/// .GC/
|
||||
/// settings.json 设置与已安装版本记录
|
||||
/// model/ 模型(启动时下载)
|
||||
/// cache/ 下载缓存 / 原子替换暂存
|
||||
/// update/ 待下次启动应用的启动器更新包
|
||||
/// </code>
|
||||
/// 开发态同样使用仓库根 .GC/model,并自动同步仓库 model/ 的可分发部分。
|
||||
/// EMS_MODELS / EMS_DATA / EMS_HOME 可显式覆盖。
|
||||
/// </summary>
|
||||
public sealed class AppPaths
|
||||
{
|
||||
private Task _developmentModelsSync = Task.CompletedTask;
|
||||
|
||||
/// <summary>安装目录(开发态为仓库根)。</summary>
|
||||
public string AppRoot { get; private init; } = "";
|
||||
|
||||
/// <summary>可执行文件真正所在目录:启动器自更新时要覆盖这里。</summary>
|
||||
public string InstallDirectory { get; private init; } = "";
|
||||
|
||||
/// <summary>.GC 目录。</summary>
|
||||
public string HomeRoot { get; private init; } = "";
|
||||
|
||||
/// <summary>模型库。</summary>
|
||||
public string ModelRoot { get; private init; } = "";
|
||||
|
||||
/// <summary>兼容旧代码:数据目录即 .GC。</summary>
|
||||
public string DataRoot => HomeRoot;
|
||||
|
||||
public string CacheRoot => Path.Combine(HomeRoot, "cache");
|
||||
public string UpdateRoot => Path.Combine(HomeRoot, "update");
|
||||
|
||||
/// <summary>用户配置目录(与可重建的缓存分开,删 cache 不会丢设置)。</summary>
|
||||
public string ConfigRoot => Path.Combine(HomeRoot, "config");
|
||||
|
||||
public string SettingsFile => Path.Combine(ConfigRoot, "settings.json");
|
||||
|
||||
public bool IsDevelopment { get; private init; }
|
||||
public bool IsPortableModelRoot { get; private init; }
|
||||
|
||||
public static AppPaths Discover()
|
||||
{
|
||||
var baseDir = AppContext.BaseDirectory.TrimEnd(Path.DirectorySeparatorChar);
|
||||
|
||||
// 判定「当前目录」:程序实际所在的位置。
|
||||
// · 发布版:可执行文件所在目录(单文件时为 exe 旁,否则为 apphost 目录)
|
||||
// · 源码版:仓库根(含 GC.sln 的目录)
|
||||
//
|
||||
// 重要:源码版由 `dotnet run` 启动时 Environment.ProcessPath 指向 dotnet 宿主,
|
||||
// 直接用它会把 .GC 与更新包写到 dotnet 安装目录去,所以必须先识别源码版。
|
||||
var explicitHome = Environment.GetEnvironmentVariable("EMS_HOME");
|
||||
var repoRoot = explicitHome;
|
||||
if (string.IsNullOrWhiteSpace(repoRoot) || !Directory.Exists(repoRoot))
|
||||
repoRoot = FindRepoRoot(baseDir);
|
||||
var isDev = !string.IsNullOrEmpty(repoRoot) &&
|
||||
File.Exists(Path.Combine(repoRoot!, "GC.sln"));
|
||||
|
||||
string installDir;
|
||||
if (isDev)
|
||||
{
|
||||
// 源码版:安装目录 = 仓库根
|
||||
installDir = repoRoot!;
|
||||
}
|
||||
else if (!string.IsNullOrWhiteSpace(explicitHome) && Directory.Exists(explicitHome))
|
||||
{
|
||||
installDir = explicitHome;
|
||||
}
|
||||
else
|
||||
{
|
||||
// 发布版:运行目录 = **放着 .app / .exe 的那一层**,不是 .app 内部的 Contents/MacOS。
|
||||
//
|
||||
// <运行目录>/ ← 要的就是这一层
|
||||
// GC-1.0.3-mac-arm64.app/ ← 程序包
|
||||
// .GC/ ← 用户数据放这里
|
||||
//
|
||||
// 若直接返回 Contents/MacOS,.GC 会被塞进 app 包内部,
|
||||
// 用户看不到,重装/替换时也会跟着包一起被删。
|
||||
installDir = baseDir;
|
||||
try
|
||||
{
|
||||
var exe = Environment.ProcessPath;
|
||||
if (!string.IsNullOrWhiteSpace(exe))
|
||||
{
|
||||
var exeName = Path.GetFileNameWithoutExtension(exe);
|
||||
var isDotnetHost = string.Equals(exeName, "dotnet", StringComparison.OrdinalIgnoreCase);
|
||||
var exeDir = Path.GetDirectoryName(exe);
|
||||
|
||||
if (!isDotnetHost && !string.IsNullOrWhiteSpace(exeDir) && Directory.Exists(exeDir))
|
||||
{
|
||||
// 从可执行文件所在目录向上找:如果处在 Xxx.app/Contents/MacOS,
|
||||
// 则运行目录是 Xxx.app 的**父目录**。
|
||||
installDir = ResolveRunDirectory(exeDir!);
|
||||
}
|
||||
}
|
||||
}
|
||||
catch { /* 取不到就沿用 BaseDirectory */ }
|
||||
}
|
||||
|
||||
// 运行目录 = 程序所在目录。.GC 永远紧挨着程序,不往系统目录放。
|
||||
var appRoot = installDir;
|
||||
|
||||
// 只读安装位置(如 Program Files / /Applications)才回退到用户数据目录;
|
||||
// 正常可写时一律用当前目录下的 .GC。
|
||||
var explicitData = Environment.GetEnvironmentVariable("EMS_DATA");
|
||||
string home;
|
||||
if (!string.IsNullOrWhiteSpace(explicitData))
|
||||
{
|
||||
home = explicitData!;
|
||||
}
|
||||
else
|
||||
{
|
||||
var portableHome = Path.Combine(appRoot, ".GC");
|
||||
home = CanWrite(portableHome)
|
||||
? portableHome
|
||||
: Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
|
||||
"GC", ".GC");
|
||||
}
|
||||
|
||||
var envModels = Environment.GetEnvironmentVariable("EMS_MODELS");
|
||||
var modelRoot = !string.IsNullOrWhiteSpace(envModels)
|
||||
? envModels!
|
||||
: Path.Combine(home, "model");
|
||||
|
||||
return new AppPaths
|
||||
{
|
||||
AppRoot = appRoot,
|
||||
InstallDirectory = installDir,
|
||||
HomeRoot = home,
|
||||
ModelRoot = modelRoot,
|
||||
IsDevelopment = isDev,
|
||||
IsPortableModelRoot = string.IsNullOrWhiteSpace(envModels)
|
||||
};
|
||||
}
|
||||
|
||||
private static bool CanWrite(string dir)
|
||||
{
|
||||
try
|
||||
{
|
||||
Directory.CreateDirectory(dir);
|
||||
var probe = Path.Combine(dir, ".write-test");
|
||||
File.WriteAllText(probe, "ok");
|
||||
return true;
|
||||
}
|
||||
catch
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 从程序所在位置向上找仓库根(含 GC.sln 的目录)。
|
||||
///
|
||||
/// 关键:程序若位于 .app 包内(或 dist/ 等发布产物目录),**不算开发态**。
|
||||
/// 否则把 .app 放在仓库的 dist/ 下运行时,会一路向上命中仓库根的 .sln,
|
||||
/// 被误判为开发态,导致 .GC 跑到仓库根而不是程序旁边。
|
||||
/// </summary>
|
||||
private static string? FindRepoRoot(string start)
|
||||
{
|
||||
// 在 .app 包内(.../Xxx.app/Contents/MacOS)直接视为发布版
|
||||
if (IsInsideAppBundle(start)) return null;
|
||||
|
||||
var dir = new DirectoryInfo(start);
|
||||
for (var i = 0; i < 10 && dir != null; i++, dir = dir.Parent)
|
||||
{
|
||||
// 碰到发布产物目录也停下:dist/ 输出、或带 .GC 的运行目录都不是源码树
|
||||
var name = dir.Name;
|
||||
if (string.Equals(name, "dist", StringComparison.OrdinalIgnoreCase)) return null;
|
||||
|
||||
if (File.Exists(Path.Combine(dir.FullName, "GC.sln")))
|
||||
{
|
||||
// 再确认不是从「发布输出目录」里往上找来的
|
||||
if (IsUnderPublishOutput(start, dir.FullName)) return null;
|
||||
return dir.FullName;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 求「运行目录」:程序包所在的父目录。
|
||||
/// · 若路径处在 Xxx.app/Contents/MacOS 里,返回 Xxx.app 的父目录
|
||||
/// · 其它情况(Windows exe 目录)原样返回
|
||||
/// </summary>
|
||||
private static string ResolveRunDirectory(string exeDir)
|
||||
{
|
||||
var dir = new DirectoryInfo(exeDir);
|
||||
|
||||
// 走到 app 包根:.../Xxx.app
|
||||
string? appRoot = null;
|
||||
for (var cur = dir; cur != null; cur = cur.Parent)
|
||||
{
|
||||
if (cur.Name.EndsWith(".app", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
appRoot = cur.FullName;
|
||||
break;
|
||||
}
|
||||
if (cur.Parent == null) break;
|
||||
}
|
||||
|
||||
if (appRoot != null)
|
||||
{
|
||||
// 返回 .app 的父目录(即用户双击时看到的那一层)
|
||||
var parent = Path.GetDirectoryName(appRoot);
|
||||
if (!string.IsNullOrWhiteSpace(parent) && Directory.Exists(parent))
|
||||
return parent!;
|
||||
return appRoot;
|
||||
}
|
||||
|
||||
return exeDir;
|
||||
}
|
||||
|
||||
/// <summary>路径是否位于某个 .app 包内部。</summary>
|
||||
private static bool IsInsideAppBundle(string path)
|
||||
{
|
||||
var p = path.Replace('\\', '/');
|
||||
var idx = p.IndexOf(".app/", StringComparison.OrdinalIgnoreCase);
|
||||
return idx >= 0;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 从 start 到 repoRoot 之间是否经过了发布输出目录(dist / bin / publish)。
|
||||
/// 经过则说明程序是打包产物,而非源码树里直接运行的进程。
|
||||
/// </summary>
|
||||
private static bool IsUnderPublishOutput(string start, string repoRoot)
|
||||
{
|
||||
try
|
||||
{
|
||||
var rel = Path.GetRelativePath(repoRoot, start).Replace('\\', '/');
|
||||
foreach (var seg in rel.Split('/', StringSplitOptions.RemoveEmptyEntries))
|
||||
{
|
||||
if (string.Equals(seg, "dist", StringComparison.OrdinalIgnoreCase) ||
|
||||
string.Equals(seg, "publish", StringComparison.OrdinalIgnoreCase) ||
|
||||
string.Equals(seg, "Release", StringComparison.OrdinalIgnoreCase))
|
||||
return true;
|
||||
}
|
||||
}
|
||||
catch { }
|
||||
return false;
|
||||
}
|
||||
|
||||
public void EnsureCreated()
|
||||
{
|
||||
Directory.CreateDirectory(HomeRoot);
|
||||
Directory.CreateDirectory(ConfigRoot);
|
||||
Directory.CreateDirectory(CacheRoot);
|
||||
Directory.CreateDirectory(ModelRoot);
|
||||
Directory.CreateDirectory(UpdateRoot);
|
||||
|
||||
MigrateLegacySettings();
|
||||
|
||||
// 开发态:让 .GC/model 与仓库里的模型保持一致(只同步清单 + 数据,不含 src 源码)。
|
||||
// 放到后台线程:这一步要复制 coastline.json 等大文件,同步做会拖慢启动。
|
||||
if (IsDevelopment && string.IsNullOrWhiteSpace(Environment.GetEnvironmentVariable("EMS_MODELS")))
|
||||
{
|
||||
var modelRoot = ModelRoot;
|
||||
var source = Path.Combine(AppRoot, "model");
|
||||
if (Directory.Exists(source))
|
||||
_developmentModelsSync = Task.Run(() => SyncDevelopmentModels(modelRoot, source));
|
||||
}
|
||||
}
|
||||
|
||||
public void WaitForDevelopmentModels() => _developmentModelsSync.GetAwaiter().GetResult();
|
||||
|
||||
/// <summary>
|
||||
/// 老版本把设置放在 .GC/settings.json。现在设置归到 .GC/config/,
|
||||
/// 与 cache/ 分开(清缓存不会连带清掉语言、内存预算、离线源等配置)。
|
||||
/// 迁移只做一次:新位置不存在时才搬旧的。
|
||||
/// </summary>
|
||||
private void MigrateLegacySettings()
|
||||
{
|
||||
try
|
||||
{
|
||||
var legacy = Path.Combine(HomeRoot, "settings.json");
|
||||
if (!File.Exists(legacy) || File.Exists(SettingsFile)) return;
|
||||
Directory.CreateDirectory(ConfigRoot);
|
||||
File.Move(legacy, SettingsFile);
|
||||
Console.WriteLine("[paths] 设置已迁移到 .GC/config/settings.json");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.Error.WriteLine($"迁移旧设置失败: {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
private static void SyncDevelopmentModels(string modelRoot, string source)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (!Directory.Exists(source)) return;
|
||||
foreach (var dir in Directory.GetDirectories(source))
|
||||
{
|
||||
var id = Path.GetFileName(dir);
|
||||
if (id.StartsWith('_')) continue;
|
||||
var manifest = Path.Combine(dir, id + ".json");
|
||||
var data = Path.Combine(dir, id + ".model");
|
||||
if (!File.Exists(manifest) || !Directory.Exists(data)) continue;
|
||||
var dest = Path.Combine(modelRoot, id);
|
||||
Directory.CreateDirectory(dest);
|
||||
File.Copy(manifest, Path.Combine(dest, id + ".json"), true);
|
||||
CopyTree(data, Path.Combine(dest, id + ".model"));
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.Error.WriteLine($"同步开发模型失败: {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
private static void CopyTree(string src, string dst)
|
||||
{
|
||||
Directory.CreateDirectory(dst);
|
||||
foreach (var file in Directory.GetFiles(src, "*", SearchOption.AllDirectories))
|
||||
{
|
||||
if (Path.GetFileName(file).StartsWith('.')) continue;
|
||||
var to = Path.Combine(dst, Path.GetRelativePath(src, file));
|
||||
var parent = Path.GetDirectoryName(to);
|
||||
if (!string.IsNullOrEmpty(parent)) Directory.CreateDirectory(parent);
|
||||
File.Copy(file, to, true);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
using System;
|
||||
|
||||
namespace EarthModelStudio.Services;
|
||||
namespace GC.Services;
|
||||
|
||||
/// <summary>组合根:一处初始化所有服务。</summary>
|
||||
public sealed class AppServices
|
||||
@@ -10,13 +10,17 @@ public sealed class AppServices
|
||||
public AppPaths Paths { get; }
|
||||
public SettingsService Settings { get; }
|
||||
public ModelRepository Models { get; }
|
||||
public DownloadCenter Downloads { get; }
|
||||
public IDownloadCenter Downloads { get; }
|
||||
public MemoryBudget Memory { get; }
|
||||
public ModelSourceClient Sources { get; }
|
||||
public IModelSourceClient Sources { get; }
|
||||
/// <summary>模型加载器:只负责把模型程序集跑起来,不渲染。</summary>
|
||||
public ModelHost ModelHost { get; }
|
||||
/// <summary>启动时检查模型 / 启动器更新。</summary>
|
||||
public UpdateService Updates { get; }
|
||||
public IUpdateService Updates { get; }
|
||||
/// <summary>双源测速选择器(Xhmcl / GitCode 取最快)。</summary>
|
||||
public ISourceSelector Selector { get; }
|
||||
public ILauncherUpdateService LauncherUpdates { get; }
|
||||
public IDownloadModule DownloadModule { get; }
|
||||
|
||||
private AppServices(AppPaths paths)
|
||||
{
|
||||
@@ -24,11 +28,16 @@ public sealed class AppServices
|
||||
Settings = new SettingsService(paths);
|
||||
Settings.Load(); // 先读设置,才知道用在线源还是本地离线源
|
||||
Models = new ModelRepository(paths);
|
||||
Sources = new ModelSourceClient(paths);
|
||||
Downloads = new DownloadCenter(paths, Models);
|
||||
var factory = DownloadModuleHost.Factory
|
||||
?? throw new InvalidOperationException("GC-DOWNLOAD 模块尚未注册");
|
||||
DownloadModule = factory.Create(paths, Settings, Models);
|
||||
Sources = DownloadModule.Sources;
|
||||
Downloads = DownloadModule.Downloads;
|
||||
Memory = new MemoryBudget();
|
||||
ModelHost = new ModelHost(paths, Settings, Memory);
|
||||
Updates = new UpdateService(paths, Settings, UpdateService.CreateRemote(Settings.Current));
|
||||
Selector = DownloadModule.Selector;
|
||||
Updates = DownloadModule.Updates;
|
||||
LauncherUpdates = DownloadModule.LauncherUpdates;
|
||||
}
|
||||
|
||||
public static AppServices Create()
|
||||
@@ -38,7 +47,8 @@ public sealed class AppServices
|
||||
|
||||
var services = new AppServices(paths);
|
||||
L.I.Initialize(services.Settings.Current.Language);
|
||||
services.Memory.Apply(services.Settings.Current.MemoryMb);
|
||||
services.Memory.ApplyAuto(services.Settings.Current.MemoryAuto,
|
||||
services.Settings.Current.MemoryMb);
|
||||
|
||||
Current = services;
|
||||
return services;
|
||||
@@ -0,0 +1,106 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Net.Http;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace GC.Services;
|
||||
|
||||
/// <summary>GitCode 仓库的一位贡献者。</summary>
|
||||
public sealed class Contributor
|
||||
{
|
||||
public string Name { get; set; } = "";
|
||||
public string? Email { get; set; }
|
||||
/// <summary>提交次数(API 里的 contributions)。</summary>
|
||||
public int Contributions { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 登录名 -> 展示名。GitCode 的 contributors 接口只返回账号登录名,
|
||||
/// 不返回真实姓名,这里做一层映射,让关于页显示作者想展示的名字。
|
||||
/// </summary>
|
||||
private static readonly Dictionary<string, string> DisplayNames = new(StringComparer.OrdinalIgnoreCase)
|
||||
{
|
||||
["Morris_1"] = "Morris"
|
||||
};
|
||||
|
||||
/// <summary>头像地址:GitCode 用邮箱哈希拼头像,取不到时返回 null。</summary>
|
||||
public string? AvatarUrl =>
|
||||
string.IsNullOrWhiteSpace(Email)
|
||||
? null
|
||||
: $"https://cdn-img.gitcode.com/avatar/{Convert.ToHexString(
|
||||
System.Security.Cryptography.MD5.HashData(
|
||||
System.Text.Encoding.UTF8.GetBytes(Email!.Trim().ToLowerInvariant())))
|
||||
.ToLowerInvariant()}";
|
||||
|
||||
public string DisplayName
|
||||
{
|
||||
get
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(Name)) return "匿名";
|
||||
return DisplayNames.TryGetValue(Name.Trim(), out var mapped) ? mapped : Name;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 读取 GitCode 仓库的贡献者列表(用于「关于」页面展示开发者)。
|
||||
/// 失败时静默返回空列表,不影响关于页其它内容。
|
||||
/// </summary>
|
||||
public static class ContributorsService
|
||||
{
|
||||
private static readonly HttpClient Http = CreateHttp();
|
||||
|
||||
private static HttpClient CreateHttp()
|
||||
{
|
||||
var c = new HttpClient { Timeout = TimeSpan.FromSeconds(10) };
|
||||
c.DefaultRequestHeaders.UserAgent.ParseAdd("GC/1.0");
|
||||
c.DefaultRequestHeaders.Accept.ParseAdd("application/json");
|
||||
return c;
|
||||
}
|
||||
|
||||
/// <summary>默认仓库的 contributors 接口地址。</summary>
|
||||
public static string BuildUrl(string repository)
|
||||
{
|
||||
var raw = string.IsNullOrWhiteSpace(repository)
|
||||
? SourcePreset.GitCode.HomeUrl : repository.Trim();
|
||||
if (!Uri.TryCreate(raw, UriKind.Absolute, out var uri))
|
||||
return "https://api.gitcode.com/api/v5/repos/Morris_1/GC/contributors";
|
||||
|
||||
var parts = uri.AbsolutePath.Trim('/').Split('/', StringSplitOptions.RemoveEmptyEntries);
|
||||
if (parts.Length < 2)
|
||||
return "https://api.gitcode.com/api/v5/repos/Morris_1/GC/contributors";
|
||||
|
||||
var repo = parts[1].EndsWith(".git", StringComparison.OrdinalIgnoreCase)
|
||||
? parts[1][..^4] : parts[1];
|
||||
return $"https://api.gitcode.com/api/v5/repos/{parts[0]}/{repo}/contributors";
|
||||
}
|
||||
|
||||
public static async Task<List<Contributor>> FetchAsync(string repository, CancellationToken ct = default)
|
||||
{
|
||||
var url = BuildUrl(repository);
|
||||
try
|
||||
{
|
||||
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(ct);
|
||||
timeout.CancelAfter(TimeSpan.FromSeconds(10));
|
||||
|
||||
var text = await Http.GetStringAsync(url, timeout.Token);
|
||||
var trimmed = text.TrimStart();
|
||||
if (trimmed.Length == 0 || trimmed[0] != '[') return new List<Contributor>();
|
||||
|
||||
var list = JsonSerializer.Deserialize<List<Contributor>>(text, new JsonSerializerOptions
|
||||
{
|
||||
PropertyNameCaseInsensitive = true
|
||||
}) ?? new List<Contributor>();
|
||||
|
||||
// 按提交数从多到少,贡献最多的排最前
|
||||
list.Sort((a, b) => b.Contributions.CompareTo(a.Contributions));
|
||||
return list;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.Error.WriteLine($"读取贡献者失败: {ex.Message}");
|
||||
return new List<Contributor>();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,157 @@
|
||||
using System;
|
||||
using System.Collections.ObjectModel;
|
||||
using System.ComponentModel;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using GC.Models;
|
||||
|
||||
namespace GC.Services;
|
||||
|
||||
public enum DownloadState
|
||||
{
|
||||
Queued,
|
||||
Running,
|
||||
Completed,
|
||||
Failed,
|
||||
Canceled
|
||||
}
|
||||
|
||||
public interface IDownloadJob : INotifyPropertyChanged
|
||||
{
|
||||
RemoteModel Model { get; }
|
||||
string Id { get; }
|
||||
string Name { get; }
|
||||
string Version { get; }
|
||||
CancellationTokenSource Cts { get; }
|
||||
DownloadState State { get; set; }
|
||||
double Progress { get; set; }
|
||||
string StatusText { get; }
|
||||
string DetailText { get; }
|
||||
string? Error { get; set; }
|
||||
bool IsActive { get; }
|
||||
bool CanRetry { get; }
|
||||
bool IsDone { get; }
|
||||
void RefreshText();
|
||||
}
|
||||
|
||||
public interface IDownloadCenter
|
||||
{
|
||||
ObservableCollection<IDownloadJob> Jobs { get; }
|
||||
event Action? Installed;
|
||||
IDownloadJob Enqueue(RemoteModel model);
|
||||
void Cancel(IDownloadJob job);
|
||||
void Retry(IDownloadJob job);
|
||||
void Remove(IDownloadJob job);
|
||||
void ClearFinished();
|
||||
int ActiveCount { get; }
|
||||
}
|
||||
|
||||
public interface IModelSourceClient
|
||||
{
|
||||
Task<SourceIndex> FetchAsync(ModelSource source, bool force, IProgress<string>? log, CancellationToken ct);
|
||||
}
|
||||
|
||||
public interface IUpdateService
|
||||
{
|
||||
IModelRemote Remote { get; }
|
||||
void UseRemote(IModelRemote remote);
|
||||
Task<UpdateResult> RunAsync(bool force, IProgress<UpdateProgress>? progress, CancellationToken ct = default);
|
||||
}
|
||||
|
||||
public interface ISourceSelector
|
||||
{
|
||||
SourcePreset? Current { get; }
|
||||
System.Collections.Generic.IReadOnlyDictionary<string, long> LastLatency { get; }
|
||||
Task<SourcePreset> PickFastestAsync(bool force = false, CancellationToken ct = default);
|
||||
}
|
||||
|
||||
public interface ILauncherUpdateService
|
||||
{
|
||||
Task<string?> CheckAsync(IModelRemote remote, CancellationToken ct = default);
|
||||
Task<UpdateRunResult> DownloadAsync(AppPaths paths, IModelRemote remote,
|
||||
IProgress<UpdateProgressInfo>? progress = null, CancellationToken ct = default);
|
||||
bool ScheduleApply(AppPaths paths, string packageName);
|
||||
bool TryApplyPending(AppPaths paths);
|
||||
}
|
||||
|
||||
public enum UpdateRunState { UpToDate, Ready, Failed }
|
||||
|
||||
public sealed class UpdateProgressInfo
|
||||
{
|
||||
public double Value { get; init; }
|
||||
public string Stage { get; init; } = "";
|
||||
}
|
||||
|
||||
public sealed class UpdateRunResult
|
||||
{
|
||||
public UpdateRunState State { get; init; }
|
||||
public string Version { get; init; } = "";
|
||||
public string Message { get; init; } = "";
|
||||
public string? PackageName { get; init; }
|
||||
public string? NewAppPath { get; init; }
|
||||
}
|
||||
|
||||
public interface IDownloadModule
|
||||
{
|
||||
IDownloadCenter Downloads { get; }
|
||||
IModelSourceClient Sources { get; }
|
||||
IUpdateService Updates { get; }
|
||||
ISourceSelector Selector { get; }
|
||||
ILauncherUpdateService LauncherUpdates { get; }
|
||||
IModelRemote CreateRemote(SourcePreset preset);
|
||||
}
|
||||
|
||||
public interface IDownloadModuleFactory
|
||||
{
|
||||
IDownloadModule Create(AppPaths paths, SettingsService settings, ModelRepository models);
|
||||
bool TryApplyPending(AppPaths paths);
|
||||
}
|
||||
|
||||
public static class DownloadModuleHost
|
||||
{
|
||||
public static IDownloadModuleFactory? Factory { get; set; }
|
||||
}
|
||||
|
||||
public static class LauncherRuntimeInfo
|
||||
{
|
||||
private static string? _versionOverride;
|
||||
|
||||
public static string CurrentLauncherVersion
|
||||
{
|
||||
get
|
||||
{
|
||||
if (!string.IsNullOrWhiteSpace(_versionOverride)) return _versionOverride!;
|
||||
var assembly = typeof(AppServices).Assembly;
|
||||
var version = assembly.GetName().Version;
|
||||
if (version == null || (version.Major == 0 && version.Minor == 0 && version.Build == 0))
|
||||
{
|
||||
var info = System.Reflection.CustomAttributeExtensions.GetCustomAttribute<
|
||||
System.Reflection.AssemblyInformationalVersionAttribute>(assembly)?.InformationalVersion;
|
||||
if (!string.IsNullOrWhiteSpace(info) && Version.TryParse(info.Split('+')[0].Trim(), out var parsed))
|
||||
version = parsed;
|
||||
}
|
||||
return version == null
|
||||
? "0.0.0"
|
||||
: $"{Math.Max(0, version.Major)}.{Math.Max(0, version.Minor)}.{Math.Max(0, version.Build)}";
|
||||
}
|
||||
}
|
||||
|
||||
public static string CurrentRid
|
||||
{
|
||||
get
|
||||
{
|
||||
var architecture = System.Runtime.InteropServices.RuntimeInformation.OSArchitecture switch
|
||||
{
|
||||
System.Runtime.InteropServices.Architecture.Arm64 => "arm64",
|
||||
System.Runtime.InteropServices.Architecture.X86 => "x86",
|
||||
_ => "x64"
|
||||
};
|
||||
if (OperatingSystem.IsWindows()) return "win-" + architecture;
|
||||
if (OperatingSystem.IsMacOS()) return "osx-" + architecture;
|
||||
if (OperatingSystem.IsLinux()) return "linux-" + architecture;
|
||||
return System.Runtime.InteropServices.RuntimeInformation.RuntimeIdentifier;
|
||||
}
|
||||
}
|
||||
|
||||
public static void OverrideLauncherVersion(string? version) => _versionOverride = version;
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
using System;
|
||||
using System.Text.Encodings.Web;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using System.Text.Json.Serialization.Metadata;
|
||||
|
||||
namespace GC.Services;
|
||||
|
||||
public static class Json
|
||||
{
|
||||
public static readonly JsonSerializerOptions Options = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true,
|
||||
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
|
||||
WriteIndented = true,
|
||||
Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
|
||||
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
|
||||
AllowTrailingCommas = true,
|
||||
ReadCommentHandling = JsonCommentHandling.Skip
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// 源生成类型信息的提供者(可选)。
|
||||
///
|
||||
/// 启动器本身不做裁剪,走默认的反射序列化即可;GC-SAVEDOG 会被 PublishTrimmed
|
||||
/// 裁掉无参构造,反射序列化在运行时直接抛 <c>NotSupportedException</c>。
|
||||
/// 因此守护进程在启动时把本钩子指向 <c>JsonSerializerContext</c>,
|
||||
/// 让所有读写都走编译期生成的 <see cref="JsonTypeInfo{T}"/>。
|
||||
/// 这样「安全模块只有一份实现」的前提没有被破坏,只是换了元数据来源。
|
||||
/// </summary>
|
||||
public static Func<Type, JsonTypeInfo?>? TypeInfoProvider { get; set; }
|
||||
|
||||
public static T? Read<T>(string path)
|
||||
{
|
||||
if (!System.IO.File.Exists(path)) return default;
|
||||
return Deserialize<T>(System.IO.File.ReadAllText(path));
|
||||
}
|
||||
|
||||
public static void Write<T>(string path, T value)
|
||||
{
|
||||
var dir = System.IO.Path.GetDirectoryName(path);
|
||||
if (!string.IsNullOrEmpty(dir)) System.IO.Directory.CreateDirectory(dir);
|
||||
var tmp = path + ".tmp";
|
||||
System.IO.File.WriteAllText(tmp, Serialize(value));
|
||||
System.IO.File.Move(tmp, path, true);
|
||||
}
|
||||
|
||||
public static T? Deserialize<T>(string text)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(text)) return default;
|
||||
var info = TypeInfoProvider?.Invoke(typeof(T)) as JsonTypeInfo<T>;
|
||||
return info != null
|
||||
? JsonSerializer.Deserialize(text, info)
|
||||
: JsonSerializer.Deserialize<T>(text, Options);
|
||||
}
|
||||
|
||||
public static string Serialize<T>(T value)
|
||||
{
|
||||
var info = TypeInfoProvider?.Invoke(typeof(T)) as JsonTypeInfo<T>;
|
||||
return info != null
|
||||
? JsonSerializer.Serialize(value, info)
|
||||
: JsonSerializer.Serialize(value, Options);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
using Avalonia;
|
||||
using Avalonia.Controls;
|
||||
using Avalonia.Controls.ApplicationLifetimes;
|
||||
using Avalonia.Threading;
|
||||
using GC.Views;
|
||||
|
||||
namespace GC.Services;
|
||||
|
||||
/// <summary>
|
||||
/// 启动器更新的完整交互流程(「检查更新」与「重新下载启动器」共用):
|
||||
/// 1. 关闭主窗口与所有模型窗口;
|
||||
/// 2. 弹出圆角进度窗;
|
||||
/// 3. 下载最新版到当前目录(与旧版并列);
|
||||
/// 4. 安排替换脚本、关进度窗、退出进程。
|
||||
/// 失败时恢复主窗口,继续使用当前版本。
|
||||
/// </summary>
|
||||
public static class LauncherUpdateFlow
|
||||
{
|
||||
private static bool _running;
|
||||
public static bool IsRunning => _running;
|
||||
|
||||
public static async Task RunAsync(AppServices services, string title)
|
||||
{
|
||||
if (_running) return;
|
||||
_running = true;
|
||||
|
||||
var desktop = Application.Current?.ApplicationLifetime
|
||||
as IClassicDesktopStyleApplicationLifetime;
|
||||
var mainWindow = desktop?.MainWindow;
|
||||
var progressWindow = new UpdaterWindow(title);
|
||||
|
||||
try
|
||||
{
|
||||
// 1. 关闭所有窗口
|
||||
if (desktop != null) desktop.MainWindow = null;
|
||||
try { mainWindow?.Close(); } catch { }
|
||||
foreach (var w in OpenWindows().ToList())
|
||||
{
|
||||
try { w.Close(); } catch { }
|
||||
}
|
||||
|
||||
// 2. 进度窗
|
||||
progressWindow.Show();
|
||||
progressWindow.Report(0, "准备更新…");
|
||||
await Dispatcher.UIThread.InvokeAsync(() => { }, DispatcherPriority.Render);
|
||||
|
||||
// 3. 下载
|
||||
var progress = new Progress<UpdateProgressInfo>(p =>
|
||||
progressWindow.Report(p.Value, p.Stage));
|
||||
|
||||
var result = await services.LauncherUpdates.DownloadAsync(
|
||||
services.Paths, services.Updates.Remote, progress);
|
||||
|
||||
if (result.State == UpdateRunState.Failed)
|
||||
{
|
||||
progressWindow.Report(0, "更新失败", result.Message);
|
||||
await Task.Delay(2200);
|
||||
_running = false;
|
||||
progressWindow.Close();
|
||||
RestoreMainWindow(desktop, mainWindow);
|
||||
return;
|
||||
}
|
||||
|
||||
progressWindow.Report(1, $"v{result.Version} 下载完成,正在重启…");
|
||||
|
||||
// 4. 安排替换(下次启动生效 / 脚本接管重启)
|
||||
var scheduled = services.LauncherUpdates.ScheduleApply(
|
||||
services.Paths, result.PackageName ?? "");
|
||||
|
||||
if (!scheduled)
|
||||
{
|
||||
progressWindow.Report(0, "无法安排更新", "请检查安装目录是否可写");
|
||||
await Task.Delay(2200);
|
||||
_running = false;
|
||||
progressWindow.Close();
|
||||
RestoreMainWindow(desktop, mainWindow);
|
||||
return;
|
||||
}
|
||||
|
||||
await Task.Delay(400);
|
||||
progressWindow.Close();
|
||||
desktop?.Shutdown();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.Error.WriteLine($"更新流程异常: {ex}");
|
||||
_running = false;
|
||||
try { progressWindow.Close(); } catch { }
|
||||
RestoreMainWindow(desktop, mainWindow);
|
||||
}
|
||||
}
|
||||
|
||||
private static void RestoreMainWindow(
|
||||
IClassicDesktopStyleApplicationLifetime? desktop, Window? mainWindow)
|
||||
{
|
||||
if (desktop == null || mainWindow == null) return;
|
||||
try
|
||||
{
|
||||
desktop.MainWindow = mainWindow;
|
||||
mainWindow.Show();
|
||||
mainWindow.Activate();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.Error.WriteLine($"恢复主窗口失败: {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
private static IEnumerable<Window> OpenWindows()
|
||||
{
|
||||
if (Application.Current?.ApplicationLifetime
|
||||
is not IClassicDesktopStyleApplicationLifetime d)
|
||||
yield break;
|
||||
foreach (var w in d.Windows)
|
||||
{
|
||||
if (w is UpdaterWindow) continue;
|
||||
yield return w;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -8,7 +8,7 @@ using Avalonia.Markup.Xaml;
|
||||
using Avalonia.Data;
|
||||
using Avalonia.Platform;
|
||||
|
||||
namespace EarthModelStudio.Services;
|
||||
namespace GC.Services;
|
||||
|
||||
/// <summary>轻量 i18n:键值表 + 运行时切换(所有绑定自动刷新)。</summary>
|
||||
public sealed class L : INotifyPropertyChanged
|
||||
@@ -75,7 +75,7 @@ public sealed class L : INotifyPropertyChanged
|
||||
{
|
||||
try
|
||||
{
|
||||
var uri = new Uri($"avares://EarthModelStudio/Assets/i18n/{code}.json");
|
||||
var uri = new Uri($"avares://GC.Core/Assets/i18n/{code}.json");
|
||||
using var stream = AssetLoader.Open(uri);
|
||||
using var reader = new StreamReader(stream);
|
||||
return JsonSerializer.Deserialize<Dictionary<string, string>>(reader.ReadToEnd(),
|
||||
@@ -1,6 +1,6 @@
|
||||
using System;
|
||||
|
||||
namespace EarthModelStudio.Services;
|
||||
namespace GC.Services;
|
||||
|
||||
/// <summary>
|
||||
/// 启动时运行内存分配(类似启动器的 -Xmx)。
|
||||
@@ -11,7 +11,7 @@ public sealed class MemoryBudget
|
||||
{
|
||||
public int BudgetMb { get; private set; } = 2048;
|
||||
public long BudgetBytes => (long)BudgetMb * 1024L * 1024L;
|
||||
public long ManagedBytes => GC.GetTotalMemory(false);
|
||||
public long ManagedBytes => System.GC.GetTotalMemory(false);
|
||||
|
||||
public event Action? Changed;
|
||||
|
||||
@@ -21,6 +21,27 @@ public sealed class MemoryBudget
|
||||
Changed?.Invoke();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 自动预算:取设备可用物理内存的一部分(约 1/4),
|
||||
/// 夹在 512–8192 MB 之间,低配设备也不会因为预算过大而卡顿。
|
||||
/// </summary>
|
||||
public static int AutoComputeMb()
|
||||
{
|
||||
try
|
||||
{
|
||||
var info = System.GC.GetGCMemoryInfo();
|
||||
var totalMb = info.TotalAvailableMemoryBytes / (1024.0 * 1024.0);
|
||||
if (totalMb > 0)
|
||||
return (int)Math.Clamp(Math.Round(totalMb / 4.0 / 256.0) * 256, 512, 8192);
|
||||
}
|
||||
catch { /* 平台不支持时回退默认值 */ }
|
||||
return 2048;
|
||||
}
|
||||
|
||||
/// <summary>按设置应用:auto 时自动计算,否则用手动值。</summary>
|
||||
public void ApplyAuto(bool auto, int manualMb)
|
||||
=> Apply(auto ? AutoComputeMb() : manualMb);
|
||||
|
||||
/// <summary>内存情况变化(例如模型窗口开关)时刷新展示。</summary>
|
||||
public void Refresh() => Changed?.Invoke();
|
||||
|
||||
@@ -5,10 +5,10 @@ using System.Reflection;
|
||||
using System.Runtime.Loader;
|
||||
using System.Threading.Tasks;
|
||||
using Avalonia.Controls;
|
||||
using EarthModelStudio.Models;
|
||||
using EarthModelStudio.ModelSdk;
|
||||
using GC.Models;
|
||||
using GC.ModelSdk;
|
||||
|
||||
namespace EarthModelStudio.Services;
|
||||
namespace GC.Services;
|
||||
|
||||
/// <summary>
|
||||
/// 模型宿主:按清单加载模型自己的程序集,拿到模型自带的界面。
|
||||
@@ -71,6 +71,40 @@ public sealed class ModelHost
|
||||
|
||||
private Session CreateSession(ModelPackage package, Action requestClose, Action<double, string?>? progress)
|
||||
{
|
||||
// ---- 契约协商 -------------------------------------------------------
|
||||
// 先做廉价检查:不满足就直接拒绝,避免加载了才发现不兼容。
|
||||
var declaredApi = package.Manifest.ApiVersion;
|
||||
if (declaredApi < 1)
|
||||
throw new InvalidOperationException($"模型清单的 apiVersion 非法: {declaredApi}");
|
||||
|
||||
if (declaredApi > SupportedApiVersion)
|
||||
throw new InvalidOperationException(
|
||||
$"该模型需要更新的启动器(模型契约 v{declaredApi},当前支持 v{SupportedApiVersion})。" +
|
||||
"请先更新启动器,或让模型作者发布兼容版本。");
|
||||
|
||||
var minApp = package.Manifest.MinAppVersion;
|
||||
if (!string.IsNullOrWhiteSpace(minApp) &&
|
||||
CompareVersions(LauncherRuntimeInfo.CurrentLauncherVersion, minApp!) < 0)
|
||||
throw new InvalidOperationException(
|
||||
$"该模型要求启动器 ≥ v{minApp},当前为 v{LauncherRuntimeInfo.CurrentLauncherVersion}");
|
||||
|
||||
// ---- 完整性:dll 会被直接执行,加载前必须确认它没被改过 ----------------
|
||||
var integrity = ModelIntegrity.VerifyForLoad(package.Directory, package.Id);
|
||||
if (!integrity.Ok)
|
||||
{
|
||||
var message = $"模型完整性校验失败({package.Id}):{integrity.Message}。" +
|
||||
"请删除该模型目录让启动器重新下载。";
|
||||
if (Environment.GetEnvironmentVariable("GC_ALLOW_TAMPERED_MODELS") == "1")
|
||||
Console.Error.WriteLine("[warn] " + message + "(已按 GC_ALLOW_TAMPERED_MODELS 放行)");
|
||||
else
|
||||
throw new InvalidOperationException(message);
|
||||
}
|
||||
else if (!integrity.Present && Environment.GetEnvironmentVariable("GC_STRICT_MODELS") == "1")
|
||||
{
|
||||
throw new InvalidOperationException(
|
||||
$"模型缺少完整性记录({package.Id}),严格模式下拒绝加载");
|
||||
}
|
||||
|
||||
var assemblyPath = package.AssemblyPath;
|
||||
if (!File.Exists(assemblyPath))
|
||||
throw new FileNotFoundException($"模型缺少功能程序集:{assemblyPath}", assemblyPath);
|
||||
@@ -89,7 +123,8 @@ public sealed class ModelHost
|
||||
|
||||
if (factory.ApiVersion != SupportedApiVersion)
|
||||
throw new InvalidOperationException(
|
||||
$"模型契约版本 {factory.ApiVersion} 与启动器 {SupportedApiVersion} 不一致");
|
||||
$"模型程序集的契约版本为 v{factory.ApiVersion},启动器支持 v{SupportedApiVersion};" +
|
||||
"请更新到匹配的版本");
|
||||
|
||||
var runtime = factory.Create();
|
||||
var modelContext = new ModelContext(package, L.I.Language, _memory.BudgetMb, requestClose, progress);
|
||||
@@ -118,6 +153,34 @@ public sealed class ModelHost
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>比较 1.0.10 与 1.0.9 这类版本号(按数字段比较,不按字符串)。</summary>
|
||||
private static int CompareVersions(string left, string right)
|
||||
{
|
||||
static int[] Parts(string value)
|
||||
{
|
||||
var text = value.Trim().TrimStart('v', 'V');
|
||||
var pieces = text.Split('.');
|
||||
var numbers = new int[Math.Max(4, pieces.Length)];
|
||||
for (var i = 0; i < pieces.Length; i++)
|
||||
{
|
||||
var digits = new string(Array.FindAll(pieces[i].ToCharArray(), char.IsDigit));
|
||||
if (digits.Length > 6) digits = digits[..6];
|
||||
numbers[i] = int.TryParse(digits, out var n) ? n : 0;
|
||||
}
|
||||
return numbers;
|
||||
}
|
||||
|
||||
var a = Parts(left);
|
||||
var b = Parts(right);
|
||||
for (var i = 0; i < Math.Max(a.Length, b.Length); i++)
|
||||
{
|
||||
var x = i < a.Length ? a[i] : 0;
|
||||
var y = i < b.Length ? b[i] : 0;
|
||||
if (x != y) return x < y ? -1 : 1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
private sealed class Session : IDisposable
|
||||
{
|
||||
private readonly ModelLoadContext _context;
|
||||
@@ -176,7 +239,7 @@ public sealed class ModelLoadContext : AssemblyLoadContext
|
||||
{
|
||||
private static readonly HashSet<string> Shared = new(StringComparer.OrdinalIgnoreCase)
|
||||
{
|
||||
"EarthModelStudio.ModelSdk",
|
||||
"GC.ModelSdk",
|
||||
"Avalonia",
|
||||
"Avalonia.Base",
|
||||
"Avalonia.Controls",
|
||||
@@ -2,9 +2,9 @@ using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using EarthModelStudio.Models;
|
||||
using GC.Models;
|
||||
|
||||
namespace EarthModelStudio.Services;
|
||||
namespace GC.Services;
|
||||
|
||||
/// <summary>
|
||||
/// 本地模型库。启动器只**扫描 / 删除**模型包,不再解析或缓存任何场景数据 ——
|
||||
@@ -20,6 +20,7 @@ public sealed class ModelRepository
|
||||
|
||||
public IReadOnlyList<ModelPackage> Scan()
|
||||
{
|
||||
_paths.WaitForDevelopmentModels();
|
||||
var result = new List<ModelPackage>();
|
||||
foreach (var (manifest, dir) in ModelScanner.Scan(_paths.ModelRoot))
|
||||
{
|
||||
@@ -1,9 +1,9 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using EarthModelStudio.Models;
|
||||
using GC.Models;
|
||||
|
||||
namespace EarthModelStudio.Services;
|
||||
namespace GC.Services;
|
||||
|
||||
public static class ModelScanner
|
||||
{
|
||||
@@ -0,0 +1,122 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace GC.Services;
|
||||
|
||||
/// <summary>
|
||||
/// GitCode/Gitee v5 releases API 的一条 Release(字段做宽松解析,兼容多种返回格式)。
|
||||
/// </summary>
|
||||
public sealed class ReleaseInfo
|
||||
{
|
||||
public string TagName { get; set; } = "";
|
||||
public string Name { get; set; } = "";
|
||||
public bool Draft { get; set; }
|
||||
public bool Prerelease { get; set; }
|
||||
public string? PublishedAt { get; set; }
|
||||
public List<ReleaseAsset> Assets { get; set; } = new();
|
||||
|
||||
/// <summary>从 tag_name / name 里抽出的版本号(去掉前缀 v、GC- 等)。</summary>
|
||||
public string Version => NormalizeVersion(TagName, Name);
|
||||
|
||||
private static readonly string[] VersionPrefixes =
|
||||
{ "v", "V", "GC-", "gc-", "release-", "Release-" };
|
||||
|
||||
private static readonly string[] PrereleaseTags =
|
||||
{ "alpha", "beta", "rc", "pre", "dev", "snapshot" };
|
||||
|
||||
public static string NormalizeVersion(string tag, string name)
|
||||
{
|
||||
var raw = !string.IsNullOrWhiteSpace(tag) ? tag : name;
|
||||
if (string.IsNullOrWhiteSpace(raw)) return "";
|
||||
raw = raw!.Trim();
|
||||
// "v1.0.1" / "GC-1.0.1" / "release-1.0.1" -> 取第一段像版本号的部分
|
||||
foreach (var prefix in VersionPrefixes)
|
||||
if (raw.StartsWith(prefix, StringComparison.Ordinal)) { raw = raw[prefix.Length..]; break; }
|
||||
// 形如 GC-1.0.1-Win-amd64 时只取版本段;但 2.3.0-beta 这类预发布串要保留完整。
|
||||
// 用「后缀是否常见预发布标签」区分,避免把 "-Win" 误当成预发布。
|
||||
var dash = raw.IndexOf('-');
|
||||
if (dash > 0 && System.Version.TryParse(raw[..dash], out _))
|
||||
{
|
||||
var tail = raw[(dash + 1)..].ToLowerInvariant();
|
||||
var isPrerelease = Array.Exists(PrereleaseTags, p => tail.StartsWith(p, StringComparison.Ordinal));
|
||||
if (!isPrerelease) raw = raw[..dash];
|
||||
}
|
||||
return raw;
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class ReleaseAsset
|
||||
{
|
||||
public string Name { get; set; } = "";
|
||||
public string? BrowserDownloadUrl { get; set; }
|
||||
public string? DownloadUrl { get; set; }
|
||||
public long Size { get; set; }
|
||||
/// <summary>附件类型:GitCode 用 "source" 表示自动生成的源码压缩包,需跳过。</summary>
|
||||
public string? Type { get; set; }
|
||||
|
||||
private string? _sha256;
|
||||
/// <summary>
|
||||
/// 校验值。真实 Release 的 digest 形如 "sha256:899fc1...",
|
||||
/// 这里统一剥掉算法前缀,只留 hex,便于与 SHA256.HashData 结果比较。
|
||||
/// </summary>
|
||||
public string? Sha256
|
||||
{
|
||||
get => _sha256;
|
||||
set
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(value)) { _sha256 = null; return; }
|
||||
var v = value!.Trim();
|
||||
var colon = v.IndexOf(':');
|
||||
if (colon > 0 && v[..colon].Equals("sha256", StringComparison.OrdinalIgnoreCase))
|
||||
v = v[(colon + 1)..];
|
||||
_sha256 = v.Trim();
|
||||
}
|
||||
}
|
||||
|
||||
[JsonIgnore]
|
||||
public string Url => BrowserDownloadUrl ?? DownloadUrl ?? "";
|
||||
|
||||
/// <summary>单文件发布包(.exe 等)不能走解压,需要直接作为 payload 内容。</summary>
|
||||
public bool IsSingleFile
|
||||
{
|
||||
get
|
||||
{
|
||||
var n = Name.ToLowerInvariant();
|
||||
// macOS 的 .app 以 zip 分发(.app 或 .app.zip),内含 .app 目录,需要解压
|
||||
if (n.EndsWith(".app", StringComparison.Ordinal) ||
|
||||
n.EndsWith(".app.zip", StringComparison.Ordinal)) return false;
|
||||
return !n.EndsWith(".zip", StringComparison.Ordinal) &&
|
||||
!n.EndsWith(".tar.gz", StringComparison.Ordinal) &&
|
||||
!n.EndsWith(".tgz", StringComparison.Ordinal);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>解析附件名里的系统/架构,映射到 .NET RID。</summary>
|
||||
/// <returns>如 win-x64 / win-arm64 / osx-arm64;无法识别返回 null。</returns>
|
||||
public string? RidFromName(string fullName)
|
||||
{
|
||||
var n = fullName ?? "";
|
||||
// 统一大小写与分隔符后再判断,兼容 "GC-1.0.1-Win-amd64.zip"
|
||||
var lower = n.ToLowerInvariant().Replace('_', '-');
|
||||
|
||||
bool win = lower.Contains("win") || lower.Contains("windows");
|
||||
bool mac = lower.Contains("osx") || lower.Contains("mac") || lower.Contains("darwin");
|
||||
bool linux = lower.Contains("linux");
|
||||
if (!win && !mac && !linux) return null;
|
||||
|
||||
bool arm64 = lower.Contains("arm64") || lower.Contains("aarch64") || lower.Contains("win-arm");
|
||||
// x86_64 / x86-64 / amd64 / x64 都是 64 位;只有裸 "x86"/"win-x86" 才是 32 位
|
||||
bool is64 = lower.Contains("x64") || lower.Contains("amd64") ||
|
||||
lower.Contains("x86-64") || lower.Contains("x86_64");
|
||||
bool x86 = !is64 && !arm64 &&
|
||||
(lower.Contains("x86") || lower.Contains("win32") || lower.Contains("i386"));
|
||||
// 其余(未显式标注 32 位)一律按 64 位处理,覆盖 "GC-1.0.1-Windows.zip" 这类简写
|
||||
var arch = arm64 ? "arm64" : x86 ? "x86" : "x64";
|
||||
|
||||
if (win) return "win-" + arch;
|
||||
if (mac) return "osx-" + arch;
|
||||
return "linux-" + arch;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using GC.Models;
|
||||
|
||||
namespace GC.Services;
|
||||
|
||||
public sealed class SettingsService
|
||||
{
|
||||
private readonly AppPaths _paths;
|
||||
|
||||
public AppSettings Current { get; private set; } = new();
|
||||
public event Action? Changed;
|
||||
|
||||
public SettingsService(AppPaths paths) => _paths = paths;
|
||||
|
||||
public void Load()
|
||||
{
|
||||
Current = Json.Read<AppSettings>(_paths.SettingsFile) ?? new AppSettings();
|
||||
if (Current.UpdateRepository.Contains("gitcode.com/2509_92447106/GC", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
Current.UpdateRepository = Current.UpdateRepository.Replace(
|
||||
"2509_92447106", "Morris_1", StringComparison.OrdinalIgnoreCase);
|
||||
Save();
|
||||
}
|
||||
SeedDefaultSource();
|
||||
if (Current.MemoryMb < 256) Current.MemoryMb = 2048;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 只允许两个内置源:Xhmcl 与 GitCode(同一份仓库的两个镜像)。
|
||||
/// 不再支持用户自定义源 —— 每次加载都把 Sources 规整成这两条,
|
||||
/// 老配置里的自定义源会被清理掉。
|
||||
/// </summary>
|
||||
public const string DefaultSourceId = "gitcode";
|
||||
public const string DefaultSourceUrl = "https://gitcode.com/Morris_1/GC";
|
||||
|
||||
private void SeedDefaultSource()
|
||||
{
|
||||
var rebuilt = new List<ModelSource>();
|
||||
foreach (var preset in SourcePreset.All)
|
||||
{
|
||||
// 保留用户对「启用/停用」的选择,其余字段以内置定义为准
|
||||
var old = Current.Sources.FirstOrDefault(s =>
|
||||
SourcePreset.Detect(s.Url).Id == preset.Id);
|
||||
rebuilt.Add(new ModelSource
|
||||
{
|
||||
Id = preset.Id,
|
||||
Name = preset.Name,
|
||||
Url = preset.HomeUrl,
|
||||
Enabled = old?.Enabled ?? true,
|
||||
BuiltIn = true
|
||||
});
|
||||
}
|
||||
|
||||
var changed = Current.Sources.Count != rebuilt.Count ||
|
||||
Current.Sources.Any(s => !s.BuiltIn);
|
||||
Current.Sources = rebuilt;
|
||||
if (changed) Save();
|
||||
}
|
||||
|
||||
public void Save()
|
||||
{
|
||||
try
|
||||
{
|
||||
Json.Write(_paths.SettingsFile, Current);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.Error.WriteLine($"保存设置失败: {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
public void Apply(Action<AppSettings> mutate)
|
||||
{
|
||||
mutate(Current);
|
||||
Save();
|
||||
Changed?.Invoke();
|
||||
}
|
||||
|
||||
public void Notify()
|
||||
{
|
||||
Save();
|
||||
Changed?.Invoke();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
|
||||
namespace GC.Services;
|
||||
|
||||
public static class Shell
|
||||
{
|
||||
public static void OpenFolder(string path)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(path)) return;
|
||||
try
|
||||
{
|
||||
if (!Directory.Exists(path)) Directory.CreateDirectory(path);
|
||||
StartWith(path);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.Error.WriteLine($"打开目录失败: {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>用系统默认浏览器打开一个 URL。</summary>
|
||||
public static void OpenUrl(string url)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(url)) return;
|
||||
try
|
||||
{
|
||||
StartWith(url);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.Error.WriteLine($"打开链接失败: {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
private static void StartWith(string argument)
|
||||
{
|
||||
var info = new ProcessStartInfo
|
||||
{
|
||||
FileName = OperatingSystem.IsWindows() ? "explorer.exe"
|
||||
: OperatingSystem.IsMacOS() ? "open"
|
||||
: "xdg-open",
|
||||
UseShellExecute = false
|
||||
};
|
||||
info.ArgumentList.Add(argument);
|
||||
Process.Start(info);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
|
||||
namespace GC.Services;
|
||||
|
||||
/// <summary>
|
||||
/// 内置下载源。只允许这两个,不再支持用户自定义源。
|
||||
///
|
||||
/// 两个源的内容是同一份仓库(同一个 version.json、同一批模型),
|
||||
/// 区别只是**托管在哪台服务器**上;启动时探测两者延迟,取快的那个下载。
|
||||
/// </summary>
|
||||
public sealed class SourcePreset
|
||||
{
|
||||
public string Id { get; init; } = "";
|
||||
public string Name { get; init; } = "";
|
||||
/// <summary>仓库主页(用于展示与打开)。</summary>
|
||||
public string HomeUrl { get; init; } = "";
|
||||
/// <summary>API 根地址(Gitea: /api/v1,GitCode: /api/v5)。</summary>
|
||||
public string ApiBase { get; init; } = "";
|
||||
/// <summary>原始文件下载前缀(用于拼 raw 地址)。</summary>
|
||||
public string RawBase { get; init; } = "";
|
||||
/// <summary>后端类型:gitea / gitcode。</summary>
|
||||
public string Kind { get; init; } = "";
|
||||
public string Owner { get; init; } = "";
|
||||
public string Repo { get; init; } = "";
|
||||
public string Branch { get; init; } = "main";
|
||||
/// <summary>raw 地址风格:gitea 用 raw/branch/{b},gitcode 用 raw/{b}。</summary>
|
||||
public string RawStyle { get; init; } = "branch";
|
||||
|
||||
public string Repository => HomeUrl;
|
||||
|
||||
/// <summary>拼 raw 文件下载地址(两个平台的 URL 结构不同)。</summary>
|
||||
public string RawUrl(string path) => RawStyle == "plain"
|
||||
? $"{RawBase}/{Owner}/{Repo}/raw/{Branch}/{path.TrimStart('/')}"
|
||||
: $"{RawBase}/{Owner}/{Repo}/raw/branch/{Branch}/{path.TrimStart('/')}";
|
||||
|
||||
public static readonly SourcePreset Xhmcl = new()
|
||||
{
|
||||
Id = "xhmcl",
|
||||
Name = "Xhmcl",
|
||||
HomeUrl = "https://git.xhmcl.com/Morris/GC",
|
||||
ApiBase = "https://git.xhmcl.com/api/v1",
|
||||
RawBase = "https://git.xhmcl.com",
|
||||
Kind = "gitea",
|
||||
RawStyle = "branch",
|
||||
Owner = "Morris",
|
||||
Repo = "GC",
|
||||
Branch = "main"
|
||||
};
|
||||
|
||||
public static readonly SourcePreset GitCode = new()
|
||||
{
|
||||
Id = "gitcode",
|
||||
Name = "GitCode",
|
||||
HomeUrl = "https://gitcode.com/Morris_1/GC",
|
||||
ApiBase = "https://api.gitcode.com/api/v5",
|
||||
RawBase = "https://gitcode.com",
|
||||
Kind = "gitcode",
|
||||
RawStyle = "plain",
|
||||
Owner = "Morris_1",
|
||||
Repo = "GC",
|
||||
Branch = "main"
|
||||
};
|
||||
|
||||
public static readonly SourcePreset[] All = { Xhmcl, GitCode };
|
||||
|
||||
public static SourcePreset? Find(string? id) =>
|
||||
All.FirstOrDefault(p => string.Equals(p.Id, id, StringComparison.OrdinalIgnoreCase));
|
||||
|
||||
/// <summary>把任意仓库地址映射到这两个内置源之一(用于兼容旧配置)。</summary>
|
||||
public static SourcePreset Detect(string? url)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(url)) return GitCode;
|
||||
var u = url!.ToLowerInvariant();
|
||||
if (u.Contains("xhmcl.com")) return Xhmcl;
|
||||
return GitCode;
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,10 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text.Json.Serialization;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace EarthModelStudio.Services;
|
||||
namespace GC.Services;
|
||||
|
||||
/// <summary>仓库根 version.json:由构建脚本 VersionStamp 自动生成,模型一改版本就变。</summary>
|
||||
public sealed class RepoVersion
|
||||
@@ -15,6 +16,20 @@ public sealed class RepoVersion
|
||||
public string ModelDir { get; set; } = "model";
|
||||
public RepoLauncher Launcher { get; set; } = new();
|
||||
public List<RepoModel> Models { get; set; } = new();
|
||||
|
||||
// ---- 验签结论(解析时填入,不参与序列化) ----------------------------
|
||||
|
||||
/// <summary>Verified / Skipped / Unsigned / Invalid。</summary>
|
||||
[JsonIgnore] public string SignatureTrust { get; set; } = "";
|
||||
|
||||
[JsonIgnore] public string? SignatureKeyId { get; set; }
|
||||
|
||||
[JsonIgnore] public string? SignatureError { get; set; }
|
||||
|
||||
/// <summary>清单是否可用:签名有效,或本机没有配置公钥(兼容期)。</summary>
|
||||
[JsonIgnore]
|
||||
public bool IsTrusted =>
|
||||
SignatureTrust is nameof(ManifestTrust.Verified) or nameof(ManifestTrust.Skipped);
|
||||
}
|
||||
|
||||
public sealed class RepoLauncher
|
||||
@@ -32,6 +47,21 @@ public sealed class RepoPackage
|
||||
public string? Path { get; set; }
|
||||
public string? Sha256 { get; set; }
|
||||
public long Size { get; set; }
|
||||
/// <summary>Release 附件名(用于判断是 zip 还是单文件 exe / .app.zip)。</summary>
|
||||
public string? AssetName { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 仓库里的平台产物目录,如 <c>dist/mac-arm64</c>。
|
||||
/// 不发 Release、只把编译产物提交进仓库时,更新包就在这里找。
|
||||
/// 清单没写时由 <see cref="Rid"/> 推导。
|
||||
/// </summary>
|
||||
public string? Dir { get; set; }
|
||||
|
||||
/// <summary>包文件名,如 <c>GC-1.0.7-mac-arm64.zip</c>;清单没写时按版本与平台标签拼。</summary>
|
||||
public string? Name { get; set; }
|
||||
|
||||
/// <summary>所属平台键(win-x64 / win-arm64 / osx-arm64 …),解析清单时按字典键填入。</summary>
|
||||
[JsonIgnore] public string Rid { get; set; } = "";
|
||||
}
|
||||
|
||||
public sealed class RepoModel
|
||||
@@ -40,6 +70,20 @@ public sealed class RepoModel
|
||||
public string Version { get; set; } = "";
|
||||
/// <summary>模型在仓库里的目录,如 model/earth-rotation。</summary>
|
||||
public string Dir { get; set; } = "";
|
||||
|
||||
// ---- 完整性(由 VersionStamp 计算,签名覆盖这几个字段) ----------------
|
||||
|
||||
/// <summary>内容指纹(构建溯源,不参与版本比较)。</summary>
|
||||
public string? Build { get; set; }
|
||||
|
||||
/// <summary>模型清单 <id>.json 的 sha256。</summary>
|
||||
public string? ManifestSha256 { get; set; }
|
||||
|
||||
/// <summary><id>.model 目录的目录指纹(算法见 ContentHash)。</summary>
|
||||
public string? FilesSha256 { get; set; }
|
||||
|
||||
/// <summary>参与分发的文件数。</summary>
|
||||
public int Files { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>远端目录树里的一个条目。</summary>
|
||||
@@ -62,10 +106,19 @@ public sealed class RepoEntry
|
||||
public interface IModelRemote
|
||||
{
|
||||
string DisplayName { get; }
|
||||
|
||||
/// <summary>源标识(xhmcl / gitcode / local),用于判断当前是哪个源。</summary>
|
||||
string SourceId => SourcePreset.Detect(DisplayName).Id;
|
||||
Task<RepoVersion?> GetVersionAsync(CancellationToken ct);
|
||||
Task<IReadOnlyList<RepoEntry>> ListTreeAsync(string rootPath, CancellationToken ct);
|
||||
Task<byte[]> DownloadAsync(RepoEntry entry, CancellationToken ct);
|
||||
Task<byte[]?> DownloadPackageAsync(RepoPackage package, CancellationToken ct);
|
||||
|
||||
/// <summary>
|
||||
/// 最近一次读到的清单**原始文本**(含 signature 字段),供 SAVEDOG 二次验签。
|
||||
/// 默认返回 null,表示该源不支持(调用方会退化为单次验签)。
|
||||
/// </summary>
|
||||
Task<string?> GetRawVersionTextAsync(CancellationToken ct) => Task.FromResult<string?>(null);
|
||||
}
|
||||
|
||||
public sealed class UpdateProgress
|
||||
@@ -25,6 +25,16 @@
|
||||
<GradientStop Color="#1A3057" Offset="0.55" />
|
||||
<GradientStop Color="#0E1A31" Offset="1" />
|
||||
</LinearGradientBrush>
|
||||
|
||||
<LinearGradientBrush x:Key="TitleBarBg" StartPoint="0%,0%" EndPoint="100%,100%">
|
||||
<GradientStop Color="#101C33" Offset="0" />
|
||||
<GradientStop Color="#0B1322" Offset="1" />
|
||||
</LinearGradientBrush>
|
||||
|
||||
<LinearGradientBrush x:Key="SideBgBrush" StartPoint="0%,0%" EndPoint="0%,100%">
|
||||
<GradientStop Color="#0E1729" Offset="0" />
|
||||
<GradientStop Color="#0A1120" Offset="1" />
|
||||
</LinearGradientBrush>
|
||||
</Styles.Resources>
|
||||
|
||||
<Style Selector="Window">
|
||||
@@ -110,17 +120,15 @@
|
||||
<Setter Property="Padding" Value="7,2" />
|
||||
</Style>
|
||||
|
||||
<!-- 按钮 -->
|
||||
<!-- 全局过渡:悬停、选中、进度都不再「啪」地跳变 -->
|
||||
<Style Selector="Button /template/ ContentPresenter#PART_ContentPresenter">
|
||||
<Setter Property="Transitions">
|
||||
<Transitions>
|
||||
<BrushTransition Property="Background" Duration="0:0:0.14" />
|
||||
<BrushTransition Property="BorderBrush" Duration="0:0:0.14" />
|
||||
<BrushTransition Property="Foreground" Duration="0:0:0.14" />
|
||||
</Transitions>
|
||||
</Setter>
|
||||
</Style>
|
||||
<!-- ===================================================================
|
||||
按钮(重写版)
|
||||
原则:只通过 Button 自身的 Background/Foreground/BorderBrush + 伪类
|
||||
设置来换色,一律不覆盖 /template/ ContentPresenter 的属性,也不使用
|
||||
RenderTransform 动画。FluentTheme 的按钮模板通过 TemplateBinding 读取
|
||||
这些属性,混用「Button 属性」与「模板内部元素属性」会在 hover 状态
|
||||
切换时互相覆盖,造成光标移动时的渲染错乱。
|
||||
所有过渡都是纯画刷过渡(BrushTransition),类型固定,不会转换失败。
|
||||
=================================================================== -->
|
||||
<Style Selector="Button">
|
||||
<Setter Property="FontSize" Value="13" />
|
||||
<Setter Property="Padding" Value="14,7" />
|
||||
@@ -135,73 +143,99 @@
|
||||
<Setter Property="Cursor" Value="Hand" />
|
||||
<Setter Property="Transitions">
|
||||
<Transitions>
|
||||
<TransformOperationsTransition Property="RenderTransform" Duration="0:0:0.12" />
|
||||
<BrushTransition Property="Background" Duration="0:0:0.13" />
|
||||
<BrushTransition Property="BorderBrush" Duration="0:0:0.13" />
|
||||
<BrushTransition Property="Foreground" Duration="0:0:0.13" />
|
||||
</Transitions>
|
||||
</Setter>
|
||||
</Style>
|
||||
|
||||
<!-- 通用 hover / pressed(纯色,无变换) -->
|
||||
<Style Selector="Button:pointerover">
|
||||
<Setter Property="RenderTransform" Value="translateY(-1px)" />
|
||||
<Setter Property="Background" Value="#EDF2FC" />
|
||||
<Setter Property="BorderBrush" Value="#BAC9E6" />
|
||||
</Style>
|
||||
<Style Selector="Button:pressed">
|
||||
<Setter Property="RenderTransform" Value="translateY(1px)" />
|
||||
<Setter Property="Background" Value="#DDE7F8" />
|
||||
<Setter Property="BorderBrush" Value="#9FB4DD" />
|
||||
</Style>
|
||||
|
||||
<!-- 主要按钮 -->
|
||||
<Style Selector="Button.primary">
|
||||
<Setter Property="Foreground" Value="White" />
|
||||
</Style>
|
||||
<Style Selector="Button.primary /template/ ContentPresenter#PART_ContentPresenter">
|
||||
<Setter Property="Background" Value="{DynamicResource Accent}" />
|
||||
<Setter Property="BorderBrush" Value="{DynamicResource Accent}" />
|
||||
<Setter Property="Foreground" Value="White" />
|
||||
<Setter Property="CornerRadius" Value="9" />
|
||||
</Style>
|
||||
<Style Selector="Button.primary:pointerover /template/ ContentPresenter#PART_ContentPresenter">
|
||||
<Style Selector="Button.primary:pointerover">
|
||||
<Setter Property="Background" Value="{DynamicResource AccentDark}" />
|
||||
<Setter Property="BorderBrush" Value="{DynamicResource AccentDark}" />
|
||||
<Setter Property="Foreground" Value="White" />
|
||||
</Style>
|
||||
<Style Selector="Button.primary:pressed">
|
||||
<Setter Property="Background" Value="#183FA8" />
|
||||
<Setter Property="BorderBrush" Value="#183FA8" />
|
||||
<Setter Property="Foreground" Value="White" />
|
||||
</Style>
|
||||
|
||||
<!-- 幽灵按钮 -->
|
||||
<Style Selector="Button.ghost">
|
||||
<Setter Property="Background" Value="Transparent" />
|
||||
<Setter Property="BorderThickness" Value="0" />
|
||||
<Setter Property="BorderBrush" Value="Transparent" />
|
||||
<Setter Property="Foreground" Value="{DynamicResource InkDim}" />
|
||||
</Style>
|
||||
<Style Selector="Button.ghost /template/ ContentPresenter#PART_ContentPresenter">
|
||||
<Setter Property="Background" Value="Transparent" />
|
||||
<Setter Property="BorderThickness" Value="0" />
|
||||
</Style>
|
||||
<Style Selector="Button.ghost:pointerover /template/ ContentPresenter#PART_ContentPresenter">
|
||||
<Style Selector="Button.ghost:pointerover">
|
||||
<Setter Property="Background" Value="#EEF2FA" />
|
||||
<Setter Property="Foreground" Value="{DynamicResource Ink}" />
|
||||
</Style>
|
||||
<Style Selector="Button.ghost:pressed">
|
||||
<Setter Property="Background" Value="#E2E9F6" />
|
||||
</Style>
|
||||
|
||||
<!-- 危险按钮 -->
|
||||
<Style Selector="Button.danger">
|
||||
<Setter Property="Foreground" Value="{DynamicResource Danger}" />
|
||||
</Style>
|
||||
<Style Selector="Button.danger:pointerover /template/ ContentPresenter#PART_ContentPresenter">
|
||||
<Style Selector="Button.danger:pointerover">
|
||||
<Setter Property="Background" Value="#FDECEC" />
|
||||
<Setter Property="Foreground" Value="{DynamicResource Danger}" />
|
||||
</Style>
|
||||
<Style Selector="Button.danger:pressed">
|
||||
<Setter Property="Background" Value="#F8DADA" />
|
||||
</Style>
|
||||
|
||||
<!-- 深色背景上的按钮 -->
|
||||
<Style Selector="Button.onDark">
|
||||
<Setter Property="Background" Value="#1B2740" />
|
||||
<Setter Property="BorderBrush" Value="#2A3A57" />
|
||||
<Setter Property="Foreground" Value="#DCE7FA" />
|
||||
</Style>
|
||||
<Style Selector="Button.onDark:pointerover">
|
||||
<Setter Property="Background" Value="#233351" />
|
||||
<Setter Property="BorderBrush" Value="#3A4E75" />
|
||||
</Style>
|
||||
<Style Selector="Button.onDark:pressed">
|
||||
<Setter Property="Background" Value="#2B3D60" />
|
||||
</Style>
|
||||
<Style Selector="Button.onDark.active">
|
||||
<Setter Property="Background" Value="{DynamicResource Accent}" />
|
||||
<Setter Property="BorderBrush" Value="{DynamicResource Accent}" />
|
||||
<Setter Property="Foreground" Value="White" />
|
||||
</Style>
|
||||
|
||||
<Style Selector="Button.small">
|
||||
<Setter Property="FontSize" Value="12" />
|
||||
<Setter Property="Padding" Value="10,4" />
|
||||
<Setter Property="MinHeight" Value="28" />
|
||||
<Setter Property="CornerRadius" Value="8" />
|
||||
</Style>
|
||||
<Style Selector="Button.onDark">
|
||||
<Setter Property="Background" Value="#1B2740" />
|
||||
<Setter Property="BorderBrush" Value="#2A3A57" />
|
||||
<Setter Property="Foreground" Value="#DCE7FA" />
|
||||
</Style>
|
||||
<Style Selector="Button.onDark:pointerover /template/ ContentPresenter#PART_ContentPresenter">
|
||||
<Setter Property="Background" Value="#233351" />
|
||||
</Style>
|
||||
<Style Selector="Button.onDark.active /template/ ContentPresenter#PART_ContentPresenter">
|
||||
<Setter Property="Background" Value="{DynamicResource Accent}" />
|
||||
<Setter Property="Foreground" Value="White" />
|
||||
</Style>
|
||||
|
||||
<!-- 侧栏 -->
|
||||
<!-- 侧栏导航(主页 / 下载 / 设置) -->
|
||||
<Style Selector="Button.nav">
|
||||
<Setter Property="HorizontalAlignment" Value="Stretch" />
|
||||
<Setter Property="HorizontalContentAlignment" Value="Left" />
|
||||
<Setter Property="Background" Value="Transparent" />
|
||||
<Setter Property="BorderBrush" Value="Transparent" />
|
||||
<Setter Property="BorderThickness" Value="0" />
|
||||
<Setter Property="Foreground" Value="{DynamicResource SideInk}" />
|
||||
<Setter Property="Padding" Value="14,10" />
|
||||
@@ -209,17 +243,22 @@
|
||||
<Setter Property="FontSize" Value="13.5" />
|
||||
<Setter Property="MinHeight" Value="40" />
|
||||
</Style>
|
||||
<Style Selector="Button.nav /template/ ContentPresenter#PART_ContentPresenter">
|
||||
<Setter Property="Background" Value="Transparent" />
|
||||
<Setter Property="BorderThickness" Value="0" />
|
||||
</Style>
|
||||
<Style Selector="Button.nav:pointerover /template/ ContentPresenter#PART_ContentPresenter">
|
||||
<Style Selector="Button.nav:pointerover">
|
||||
<Setter Property="Background" Value="#16213A" />
|
||||
<Setter Property="Foreground" Value="#E8EFFF" />
|
||||
</Style>
|
||||
<Style Selector="Button.nav.active /template/ ContentPresenter#PART_ContentPresenter">
|
||||
<Style Selector="Button.nav:pressed">
|
||||
<Setter Property="Background" Value="#1E2C49" />
|
||||
</Style>
|
||||
<Style Selector="Button.nav.active">
|
||||
<Setter Property="Background" Value="#1C2C4C" />
|
||||
<Setter Property="Foreground" Value="#FFFFFF" />
|
||||
<Setter Property="BorderBrush" Value="{DynamicResource Accent}" />
|
||||
<Setter Property="BorderThickness" Value="3,0,0,0" />
|
||||
</Style>
|
||||
<Style Selector="Button.nav.active:pointerover">
|
||||
<Setter Property="Background" Value="#22355A" />
|
||||
<Setter Property="Foreground" Value="#FFFFFF" />
|
||||
</Style>
|
||||
|
||||
<!-- 输入 -->
|
||||
@@ -246,4 +285,41 @@
|
||||
<Setter Property="FontSize" Value="12.5" />
|
||||
</Style>
|
||||
|
||||
<!-- ===================================================================
|
||||
自建标题栏按钮(最小化 − / 关闭 ✕)
|
||||
同样只用纯画刷换色,绝不设置 RenderTransform;
|
||||
且用更高优先级覆盖上面通用的 :pointerover / :pressed,
|
||||
避免深色标题栏上出现浅色 hover 背景。
|
||||
=================================================================== -->
|
||||
<Style Selector="Button.titlebtn">
|
||||
<Setter Property="Width" Value="38" />
|
||||
<Setter Property="Height" Value="30" />
|
||||
<Setter Property="Background" Value="Transparent" />
|
||||
<Setter Property="Foreground" Value="#A9B8D4" />
|
||||
<Setter Property="BorderThickness" Value="0" />
|
||||
<Setter Property="BorderBrush" Value="Transparent" />
|
||||
<Setter Property="FontSize" Value="13" />
|
||||
<Setter Property="HorizontalContentAlignment" Value="Center" />
|
||||
<Setter Property="VerticalContentAlignment" Value="Center" />
|
||||
<Setter Property="CornerRadius" Value="7" />
|
||||
<Setter Property="Margin" Value="2,0" />
|
||||
</Style>
|
||||
<Style Selector="Button.titlebtn:pointerover">
|
||||
<Setter Property="Background" Value="#223252" />
|
||||
<Setter Property="BorderBrush" Value="Transparent" />
|
||||
<Setter Property="Foreground" Value="#FFFFFF" />
|
||||
</Style>
|
||||
<Style Selector="Button.titlebtn:pressed">
|
||||
<Setter Property="Background" Value="#2C4270" />
|
||||
<Setter Property="Foreground" Value="#FFFFFF" />
|
||||
</Style>
|
||||
<Style Selector="Button.titlebtn.close:pointerover">
|
||||
<Setter Property="Background" Value="#D64545" />
|
||||
<Setter Property="Foreground" Value="#FFFFFF" />
|
||||
</Style>
|
||||
<Style Selector="Button.titlebtn.close:pressed">
|
||||
<Setter Property="Background" Value="#B93737" />
|
||||
<Setter Property="Foreground" Value="#FFFFFF" />
|
||||
</Style>
|
||||
|
||||
</Styles>
|
||||
@@ -0,0 +1,104 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.ObjectModel;
|
||||
using System.Threading.Tasks;
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
using CommunityToolkit.Mvvm.Input;
|
||||
using GC.Services;
|
||||
|
||||
namespace GC.ViewModels;
|
||||
|
||||
/// <summary>「关于」页面:版本号 + 开发者(读取仓库 contributors)。</summary>
|
||||
public partial class AboutViewModel : ObservableObject
|
||||
{
|
||||
private readonly AppServices _services;
|
||||
private bool _loaded;
|
||||
|
||||
public ObservableCollection<ContributorItem> Contributors { get; } = new();
|
||||
|
||||
[ObservableProperty] private bool _isLoading = true;
|
||||
[ObservableProperty] private string _statusText = "";
|
||||
[ObservableProperty] private bool _hasContributors;
|
||||
|
||||
public AboutViewModel(AppServices services)
|
||||
{
|
||||
_services = services;
|
||||
LoadCommand = new AsyncRelayCommand(() => LoadAsync(force: true));
|
||||
}
|
||||
|
||||
public string AppName => "Morris GC";
|
||||
|
||||
/// <summary>启动器版本号,如 v1.0.2。</summary>
|
||||
public string VersionText => "v" + LauncherRuntimeInfo.CurrentLauncherVersion;
|
||||
|
||||
/// <summary>当前平台标识,如 win-x64 / osx-arm64。</summary>
|
||||
public string PlatformText => LauncherRuntimeInfo.CurrentRid;
|
||||
|
||||
public string RepositoryText => _services.Settings.Current.UpdateRepository;
|
||||
|
||||
public string ContributorsTitle => "开发者";
|
||||
|
||||
public IAsyncRelayCommand LoadCommand { get; }
|
||||
|
||||
/// <summary>每次进入页面时调用(首次才真正联网拉取)。</summary>
|
||||
public void OnShown()
|
||||
{
|
||||
if (_loaded) return;
|
||||
_ = LoadAsync(force: false);
|
||||
}
|
||||
|
||||
private async Task LoadAsync(bool force)
|
||||
{
|
||||
if (_loaded && !force) return;
|
||||
_loaded = true;
|
||||
|
||||
IsLoading = true;
|
||||
StatusText = "正在读取贡献者…";
|
||||
try
|
||||
{
|
||||
var list = await ContributorsService.FetchAsync(_services.Settings.Current.UpdateRepository);
|
||||
Contributors.Clear();
|
||||
foreach (var c in list)
|
||||
Contributors.Add(new ContributorItem(c));
|
||||
|
||||
HasContributors = Contributors.Count > 0;
|
||||
StatusText = HasContributors ? $"{Contributors.Count} 位贡献者" : "暂无贡献者信息";
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
StatusText = "读取失败:" + ex.Message;
|
||||
}
|
||||
finally
|
||||
{
|
||||
IsLoading = false;
|
||||
}
|
||||
}
|
||||
|
||||
[RelayCommand]
|
||||
private void OpenRepository() => Shell.OpenUrl(RepositoryText);
|
||||
|
||||
/// <summary>重新下载启动器:关闭所有窗口,进度窗下载新版,完成后重启。</summary>
|
||||
[RelayCommand]
|
||||
private async System.Threading.Tasks.Task ReinstallLauncher()
|
||||
{
|
||||
if (LauncherUpdateFlow.IsRunning) return;
|
||||
await LauncherUpdateFlow.RunAsync(_services, "正在重新下载启动器");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>一位贡献者的展示项。</summary>
|
||||
public sealed class ContributorItem
|
||||
{
|
||||
public ContributorItem(Contributor c)
|
||||
{
|
||||
Name = c.DisplayName;
|
||||
Contributions = c.Contributions;
|
||||
AvatarUrl = c.AvatarUrl;
|
||||
}
|
||||
|
||||
public string Name { get; }
|
||||
public int Contributions { get; }
|
||||
public string? AvatarUrl { get; }
|
||||
public string ContributionsText => $"{Contributions} 次提交";
|
||||
public bool HasAvatar => !string.IsNullOrWhiteSpace(AvatarUrl);
|
||||
}
|
||||
@@ -9,10 +9,10 @@ using System.Threading.Tasks;
|
||||
using System.Windows.Input;
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
using CommunityToolkit.Mvvm.Input;
|
||||
using EarthModelStudio.Models;
|
||||
using EarthModelStudio.Services;
|
||||
using GC.Models;
|
||||
using GC.Services;
|
||||
|
||||
namespace EarthModelStudio.ViewModels;
|
||||
namespace GC.ViewModels;
|
||||
|
||||
public partial class DownloadViewModel : ObservableObject
|
||||
{
|
||||
@@ -25,7 +25,7 @@ public partial class DownloadViewModel : ObservableObject
|
||||
|
||||
public ObservableCollection<SourceItemViewModel> Sources { get; } = new();
|
||||
public ObservableCollection<RemoteModelRowViewModel> Models { get; } = new();
|
||||
public ObservableCollection<DownloadJob> Jobs => _services.Downloads.Jobs;
|
||||
public ObservableCollection<IDownloadJob> Jobs => _services.Downloads.Jobs;
|
||||
|
||||
[ObservableProperty] private SourceItemViewModel? _selectedSource;
|
||||
[ObservableProperty] private string _importUrl = "";
|
||||
@@ -93,6 +93,7 @@ public partial class DownloadViewModel : ObservableObject
|
||||
|
||||
internal void RemoveSource(SourceItemViewModel source)
|
||||
{
|
||||
if (source.Model.BuiltIn) return; // 内置默认源不允许删除
|
||||
_services.Settings.Current.Sources.Remove(source.Model);
|
||||
_services.Settings.Save();
|
||||
var wasSelected = SelectedSource == source;
|
||||
@@ -108,30 +109,30 @@ public partial class DownloadViewModel : ObservableObject
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 只允许两个内置源(Xhmcl / GitCode),不再接受任意地址。
|
||||
/// 旧的「自定义源」入口统一改为:按测速结果切换到更快的那个源。
|
||||
/// </summary>
|
||||
[RelayCommand]
|
||||
private async Task ImportAsync()
|
||||
{
|
||||
var url = ImportUrl.Trim();
|
||||
if (string.IsNullOrWhiteSpace(url))
|
||||
var fastest = await _services.Selector.PickFastestAsync(force: true);
|
||||
var target = Sources.FirstOrDefault(x =>
|
||||
SourcePreset.Find(fastest.Id) != null &&
|
||||
SourcePreset.Detect(x.Model.Url).Id == fastest.Id);
|
||||
|
||||
if (target == null)
|
||||
{
|
||||
StatusMessage = L.I["dl.error.emptyUrl"];
|
||||
StatusMessage = "没有可用的下载源";
|
||||
return;
|
||||
}
|
||||
|
||||
var source = new ModelSource
|
||||
{
|
||||
Name = DeriveName(url),
|
||||
Url = url,
|
||||
Enabled = true
|
||||
};
|
||||
_services.Settings.Current.Sources.Add(source);
|
||||
_services.Settings.Save();
|
||||
|
||||
var item = new SourceItemViewModel(source, this, _services);
|
||||
Sources.Add(item);
|
||||
ImportUrl = "";
|
||||
SelectedSource = item;
|
||||
await LoadAsync(item, force: true);
|
||||
SelectedSource = target;
|
||||
var lat = _services.Selector.LastLatency;
|
||||
StatusMessage = $"已切换到 {fastest.Name}" +
|
||||
(lat.Count > 0 ? "(" + string.Join(",", lat.Select(kv =>
|
||||
$"{SourcePreset.Find(kv.Key)?.Name ?? kv.Key} {kv.Value}ms")) + ")" : "");
|
||||
await LoadAsync(target, force: true);
|
||||
}
|
||||
|
||||
private static string DeriveName(string url)
|
||||
@@ -172,6 +173,24 @@ public partial class DownloadViewModel : ObservableObject
|
||||
StatusMessage = L.I["dl.syncing"];
|
||||
try
|
||||
{
|
||||
// 第 6 项:下载页与启动更新用同一个源、同一种下载方式。
|
||||
// 每次加载前先让选择器给出最快源(有缓存,不会真的每次都测)。
|
||||
try
|
||||
{
|
||||
var fastest = await _services.Selector.PickFastestAsync(false, ct);
|
||||
if (fastest.Id != SourcePreset.Detect(source.Model.Url).Id)
|
||||
{
|
||||
var prefer = Sources.FirstOrDefault(x =>
|
||||
SourcePreset.Detect(x.Model.Url).Id == fastest.Id && x.Model.Enabled);
|
||||
if (prefer != null && prefer != source)
|
||||
{
|
||||
SelectedSource = prefer;
|
||||
source = prefer;
|
||||
}
|
||||
}
|
||||
}
|
||||
catch { /* 测速失败就沿用当前源 */ }
|
||||
|
||||
var index = await _services.Sources.FetchAsync(source.Model, force, null, ct);
|
||||
// 只有「仍是当前选中源 + 仍是最新一次加载」才可以写 UI 集合
|
||||
if (ct.IsCancellationRequested || generation != _loadGeneration || SelectedSource != source)
|
||||
@@ -245,19 +264,19 @@ public partial class DownloadViewModel : ObservableObject
|
||||
}
|
||||
|
||||
[RelayCommand]
|
||||
private void CancelJob(DownloadJob? job)
|
||||
private void CancelJob(IDownloadJob? job)
|
||||
{
|
||||
if (job != null) _services.Downloads.Cancel(job);
|
||||
}
|
||||
|
||||
[RelayCommand]
|
||||
private void RetryJob(DownloadJob? job)
|
||||
private void RetryJob(IDownloadJob? job)
|
||||
{
|
||||
if (job != null) _services.Downloads.Retry(job);
|
||||
}
|
||||
|
||||
[RelayCommand]
|
||||
private void RemoveJob(DownloadJob? job)
|
||||
private void RemoveJob(IDownloadJob? job)
|
||||
{
|
||||
if (job != null) _services.Downloads.Remove(job);
|
||||
}
|
||||
@@ -272,17 +291,17 @@ public partial class DownloadViewModel : ObservableObject
|
||||
private void OnJobsChanged(object? sender, NotifyCollectionChangedEventArgs e)
|
||||
{
|
||||
if (e.NewItems != null)
|
||||
foreach (DownloadJob job in e.NewItems) job.PropertyChanged += OnJobPropertyChanged;
|
||||
foreach (IDownloadJob job in e.NewItems) job.PropertyChanged += OnJobPropertyChanged;
|
||||
if (e.OldItems != null)
|
||||
foreach (DownloadJob job in e.OldItems) job.PropertyChanged -= OnJobPropertyChanged;
|
||||
foreach (IDownloadJob job in e.OldItems) job.PropertyChanged -= OnJobPropertyChanged;
|
||||
UpdateJobState();
|
||||
}
|
||||
|
||||
private void OnJobPropertyChanged(object? sender, PropertyChangedEventArgs e)
|
||||
{
|
||||
if (e.PropertyName == nameof(DownloadJob.State))
|
||||
if (e.PropertyName == nameof(IDownloadJob.State))
|
||||
{
|
||||
if (sender is DownloadJob { State: DownloadState.Completed })
|
||||
if (sender is IDownloadJob { State: DownloadState.Completed })
|
||||
_services.Models.NotifyChanged();
|
||||
}
|
||||
UpdateJobState();
|
||||
@@ -325,6 +344,8 @@ public partial class SourceItemViewModel : ObservableObject
|
||||
public string Name => string.IsNullOrWhiteSpace(Model.Name) ? Model.Id : Model.Name;
|
||||
public string HostText => string.IsNullOrWhiteSpace(Model.Url) ? L.I["dl.noSource"] : Model.DisplayHost;
|
||||
public bool HasUrl => !string.IsNullOrWhiteSpace(Model.Url);
|
||||
/// <summary>内置默认源不可删除(下载页隐藏删除按钮)。</summary>
|
||||
public bool CanRemove => !Model.BuiltIn;
|
||||
|
||||
public bool Enabled
|
||||
{
|
||||
@@ -6,11 +6,11 @@ using System.Threading.Tasks;
|
||||
using System.Windows.Input;
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
using CommunityToolkit.Mvvm.Input;
|
||||
using EarthModelStudio.Models;
|
||||
using GC.Models;
|
||||
using Avalonia.Media.Imaging;
|
||||
using EarthModelStudio.Services;
|
||||
using GC.Services;
|
||||
|
||||
namespace EarthModelStudio.ViewModels;
|
||||
namespace GC.ViewModels;
|
||||
|
||||
public partial class HomeViewModel : ObservableObject
|
||||
{
|
||||
@@ -1,11 +1,12 @@
|
||||
using System;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
using CommunityToolkit.Mvvm.Input;
|
||||
using EarthModelStudio.Models;
|
||||
using EarthModelStudio.Services;
|
||||
using GC.Models;
|
||||
using GC.Services;
|
||||
|
||||
namespace EarthModelStudio.ViewModels;
|
||||
namespace GC.ViewModels;
|
||||
|
||||
public partial class MainViewModel : ObservableObject
|
||||
{
|
||||
@@ -15,6 +16,7 @@ public partial class MainViewModel : ObservableObject
|
||||
public HomeViewModel Home { get; }
|
||||
public DownloadViewModel Download { get; }
|
||||
public SettingsViewModel Settings { get; }
|
||||
public AboutViewModel About { get; }
|
||||
|
||||
/// <summary>模型宿主:按清单加载模型自带的功能程序集。</summary>
|
||||
public ModelHost Models { get; }
|
||||
@@ -23,6 +25,7 @@ public partial class MainViewModel : ObservableObject
|
||||
[ObservableProperty] private bool _isHomeActive = true;
|
||||
[ObservableProperty] private bool _isDownloadActive;
|
||||
[ObservableProperty] private bool _isSettingsActive;
|
||||
[ObservableProperty] private bool _isAboutActive;
|
||||
|
||||
// 启动更新状态条
|
||||
[ObservableProperty] private bool _updateBarVisible;
|
||||
@@ -35,10 +38,16 @@ public partial class MainViewModel : ObservableObject
|
||||
/// <summary>由主窗口注入的确认对话框。</summary>
|
||||
public Func<string, Task<bool>>? ConfirmHandler { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 由主窗口注入的「发现启动器新版本」对话框。
|
||||
/// 参数为新版本号,返回 true 表示用户选择更新。
|
||||
/// </summary>
|
||||
public Func<string, Task<bool>>? LauncherUpdateHandler { get; set; }
|
||||
|
||||
public event Action<ModelPackage>? PlayerRequested;
|
||||
|
||||
public string VersionText => "v" + UpdateService.CurrentLauncherVersion;
|
||||
public string PlatformText => UpdateService.CurrentRid;
|
||||
public string VersionText => "v" + LauncherRuntimeInfo.CurrentLauncherVersion;
|
||||
public string PlatformText => LauncherRuntimeInfo.CurrentRid;
|
||||
|
||||
public MainViewModel(AppServices services)
|
||||
{
|
||||
@@ -47,6 +56,7 @@ public partial class MainViewModel : ObservableObject
|
||||
Home = new HomeViewModel(services, this);
|
||||
Download = new DownloadViewModel(services, this);
|
||||
Settings = new SettingsViewModel(services);
|
||||
About = new AboutViewModel(services);
|
||||
Current = Home;
|
||||
}
|
||||
|
||||
@@ -55,6 +65,7 @@ public partial class MainViewModel : ObservableObject
|
||||
IsHomeActive = value is HomeViewModel;
|
||||
IsDownloadActive = value is DownloadViewModel;
|
||||
IsSettingsActive = value is SettingsViewModel;
|
||||
IsAboutActive = value is AboutViewModel;
|
||||
}
|
||||
|
||||
[RelayCommand]
|
||||
@@ -78,6 +89,13 @@ public partial class MainViewModel : ObservableObject
|
||||
Current = Settings;
|
||||
}
|
||||
|
||||
[RelayCommand]
|
||||
public void GoAbout()
|
||||
{
|
||||
About.OnShown();
|
||||
Current = About;
|
||||
}
|
||||
|
||||
/// <summary>启动模型:交给模型自己的程序集,在独立窗口中运行。</summary>
|
||||
public void PlayModel(ModelPackage package)
|
||||
{
|
||||
@@ -118,12 +136,60 @@ public partial class MainViewModel : ObservableObject
|
||||
UpdateDetail = p.Detail ?? "";
|
||||
});
|
||||
|
||||
var result = await _services.Updates.RunAsync(force, progress);
|
||||
// 双源测速:Xhmcl / GitCode 取快的那个(第 5 项)。
|
||||
// 启动更新与下载页共用同一个选择器,保证两处用同一个源、同一种下载方式。
|
||||
UpdateStatus = "正在选择最快的下载源…";
|
||||
try
|
||||
{
|
||||
var fastest = await _services.Selector.PickFastestAsync(
|
||||
force, default);
|
||||
_services.Updates.UseRemote(_services.DownloadModule.CreateRemote(fastest));
|
||||
var lat = _services.Selector.LastLatency;
|
||||
UpdateDetail = "源:" + fastest.Name +
|
||||
(lat.Count > 0 ? "(" + string.Join(",", lat.Select(kv =>
|
||||
$"{SourcePreset.Find(kv.Key)?.Name ?? kv.Key} {kv.Value}ms")) + ")" : "");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.Error.WriteLine($"[update] 测速失败,沿用当前源: {ex.Message}");
|
||||
}
|
||||
|
||||
// 启动器:读 Release latest 版本号,与当前运行版本不同就弹窗询问
|
||||
var latest = await _services.LauncherUpdates.CheckAsync(_services.Updates.Remote);
|
||||
if (latest != null)
|
||||
{
|
||||
var agreed = LauncherUpdateHandler != null &&
|
||||
await LauncherUpdateHandler(latest);
|
||||
if (agreed)
|
||||
{
|
||||
// 走完整更新流程(关窗 -> 进度窗下载 -> 重启)
|
||||
UpdateBusy = false;
|
||||
_updateRunning = false;
|
||||
UpdateBarVisible = false;
|
||||
await LauncherUpdateFlow.RunAsync(_services, "正在更新启动器");
|
||||
return;
|
||||
}
|
||||
|
||||
UpdateStatus = $"启动器有新版本 v{latest}(已跳过)";
|
||||
UpdateDetail = "点击「检查更新」可再次更新,模型仍会同步到最新";
|
||||
}
|
||||
|
||||
// 模型:同步到最新版
|
||||
var result = await _services.Updates.RunAsync(force, progress, default);
|
||||
|
||||
UpdateStatus = result.Message;
|
||||
UpdateDetail = result.Error ?? "";
|
||||
LauncherNotice = result.LauncherMessage ?? "";
|
||||
|
||||
// 首次启动 + 断网:本地一个模型都没有,这时候不能只留一个空页面。
|
||||
// 明确告诉用户「没坏、可以怎么办」,并保留状态条(不自动隐藏)。
|
||||
if (result.Outcome == UpdateOutcome.Unavailable && Home.Models.Count == 0)
|
||||
{
|
||||
UpdateStatus = "暂时连不上模型源,模型库为空";
|
||||
UpdateDetail = "可以到「下载」页点重试,或把模型文件夹放进 .GC/model/ 后重新打开";
|
||||
return;
|
||||
}
|
||||
|
||||
// 模型下载完成后本次启动就刷新列表,立刻可用
|
||||
if (result.UpdatedModels > 0) Home.Refresh();
|
||||
|
||||
@@ -5,10 +5,10 @@ using System.Runtime.InteropServices;
|
||||
using System.Windows.Input;
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
using CommunityToolkit.Mvvm.Input;
|
||||
using EarthModelStudio.Models;
|
||||
using EarthModelStudio.Services;
|
||||
using GC.Models;
|
||||
using GC.Services;
|
||||
|
||||
namespace EarthModelStudio.ViewModels;
|
||||
namespace GC.ViewModels;
|
||||
|
||||
public sealed class LanguageOption
|
||||
{
|
||||
@@ -24,11 +24,12 @@ public partial class SettingsViewModel : ObservableObject
|
||||
|
||||
public ObservableCollection<SettingsSourceViewModel> Sources { get; } = new();
|
||||
public ObservableCollection<LanguageOption> Languages { get; } = new();
|
||||
public int[] FrameRates { get; } = { 24, 30, 60 };
|
||||
public int[] FrameRates { get; } = { 24, 30, 60, 90, 120 };
|
||||
|
||||
[ObservableProperty] private LanguageOption? _selectedLanguage;
|
||||
[ObservableProperty] private int _selectedFps = 30;
|
||||
[ObservableProperty] private int _selectedFps = 120;
|
||||
[ObservableProperty] private double _memoryValue = 2048;
|
||||
[ObservableProperty] private bool _memoryAuto = true;
|
||||
[ObservableProperty] private string _statusMessage = "";
|
||||
[ObservableProperty] private bool _autoUpdate = true;
|
||||
|
||||
@@ -46,7 +47,9 @@ public partial class SettingsViewModel : ObservableObject
|
||||
public string PendingText => string.IsNullOrWhiteSpace(_services.Settings.Current.PendingLauncherVersion)
|
||||
? L.I["update.none"] : _services.Settings.Current.PendingLauncherVersion!;
|
||||
|
||||
public string MemoryValueText => $"{(int)Math.Round(MemoryValue)} MB";
|
||||
public string MemoryValueText => MemoryAuto
|
||||
? $"{L.I["set.memory.auto"]} ({_services.Memory.BudgetMb} MB)"
|
||||
: $"{(int)Math.Round(MemoryValue)} MB";
|
||||
public string UsageText => _services.Memory.UsageText;
|
||||
public string ModelRoot => _services.Paths.ModelRoot;
|
||||
public string DataRoot => _services.Paths.DataRoot;
|
||||
@@ -69,6 +72,7 @@ public partial class SettingsViewModel : ObservableObject
|
||||
var settings = _services.Settings.Current;
|
||||
SelectedFps = settings.RenderFps;
|
||||
MemoryValue = settings.MemoryMb;
|
||||
MemoryAuto = settings.MemoryAuto;
|
||||
AutoUpdate = settings.AutoUpdateOnStartup;
|
||||
|
||||
Sources.Clear();
|
||||
@@ -133,6 +137,15 @@ public partial class SettingsViewModel : ObservableObject
|
||||
OnPropertyChanged(nameof(UsageText));
|
||||
}
|
||||
|
||||
partial void OnMemoryAutoChanged(bool value)
|
||||
{
|
||||
if (_loading) return;
|
||||
_services.Settings.Apply(s => s.MemoryAuto = value);
|
||||
_services.Memory.ApplyAuto(value, (int)Math.Round(MemoryValue));
|
||||
OnPropertyChanged(nameof(MemoryValueText));
|
||||
OnPropertyChanged(nameof(UsageText));
|
||||
}
|
||||
|
||||
[RelayCommand]
|
||||
private void OpenModelFolder() => Shell.OpenFolder(_services.Paths.ModelRoot);
|
||||
|
||||
@@ -143,8 +156,8 @@ public partial class SettingsViewModel : ObservableObject
|
||||
private void ClearCache()
|
||||
{
|
||||
// 模型数据由模型自己管理;这里只回收启动器侧托管内存
|
||||
GC.Collect();
|
||||
GC.WaitForPendingFinalizers();
|
||||
System.GC.Collect();
|
||||
System.GC.WaitForPendingFinalizers();
|
||||
_services.Memory.Refresh();
|
||||
StatusMessage = L.I["set.cacheCleared"];
|
||||
OnPropertyChanged(nameof(UsageText));
|
||||
@@ -160,6 +173,7 @@ public partial class SettingsViewModel : ObservableObject
|
||||
|
||||
internal void RemoveSource(SettingsSourceViewModel source)
|
||||
{
|
||||
if (source.Model.BuiltIn) return; // 内置默认源不允许删除
|
||||
_services.Settings.Current.Sources.Remove(source.Model);
|
||||
_services.Settings.Save();
|
||||
Sources.Remove(source);
|
||||
@@ -184,6 +198,8 @@ public partial class SettingsSourceViewModel : ObservableObject
|
||||
|
||||
public string Name => string.IsNullOrWhiteSpace(Model.Name) ? Model.Id : Model.Name;
|
||||
public string UrlText => string.IsNullOrWhiteSpace(Model.Url) ? L.I["dl.noSource"] : Model.Url;
|
||||
/// <summary>内置默认源不可删除。</summary>
|
||||
public bool CanRemove => !Model.BuiltIn;
|
||||
|
||||
public bool Enabled
|
||||
{
|
||||
@@ -0,0 +1,127 @@
|
||||
<UserControl xmlns="https://github.com/avaloniaui"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:loc="using:GC.Services"
|
||||
xmlns:vm="using:GC.ViewModels"
|
||||
x:Class="GC.Views.AboutView"
|
||||
x:DataType="vm:AboutViewModel">
|
||||
|
||||
<ScrollViewer>
|
||||
<StackPanel Margin="28,24" Spacing="16" MaxWidth="880" HorizontalAlignment="Left">
|
||||
|
||||
<StackPanel Spacing="4">
|
||||
<TextBlock Classes="h1" Text="关于" />
|
||||
<TextBlock Classes="muted" Text="版本信息与开发者" />
|
||||
</StackPanel>
|
||||
|
||||
<!-- 应用信息 -->
|
||||
<Border Classes="card" Padding="22,20">
|
||||
<Grid ColumnDefinitions="Auto,*">
|
||||
<Border Width="62" Height="62" CornerRadius="16" Background="#1C2C4C"
|
||||
VerticalAlignment="Top">
|
||||
<TextBlock Text="◎" FontSize="32" Foreground="#8FB6FF"
|
||||
HorizontalAlignment="Center" VerticalAlignment="Center" />
|
||||
</Border>
|
||||
|
||||
<StackPanel Grid.Column="1" Margin="18,0,0,0" Spacing="10">
|
||||
<StackPanel Spacing="2">
|
||||
<TextBlock Text="{Binding AppName}" FontSize="19" FontWeight="SemiBold" />
|
||||
<TextBlock Classes="faint" Text="{Binding PlatformText}" />
|
||||
</StackPanel>
|
||||
|
||||
<Grid ColumnDefinitions="96,*" RowDefinitions="Auto,Auto">
|
||||
<TextBlock Classes="h3" Text="版本" />
|
||||
<TextBlock Grid.Column="1" Classes="muted" Text="{Binding VersionText}"
|
||||
FontWeight="SemiBold" />
|
||||
|
||||
<TextBlock Grid.Row="1" Classes="h3" Text="仓库" Margin="0,8,0,0" />
|
||||
<Button Grid.Row="1" Grid.Column="1" Classes="ghost small" Margin="0,6,0,0"
|
||||
HorizontalAlignment="Left" Padding="0"
|
||||
Command="{Binding OpenRepositoryCommand}"
|
||||
Content="{Binding RepositoryText}" />
|
||||
</Grid>
|
||||
</StackPanel>
|
||||
</Grid>
|
||||
</Border>
|
||||
|
||||
<!-- 维护 -->
|
||||
<Border Classes="card" Padding="22,20">
|
||||
<StackPanel Spacing="12">
|
||||
<TextBlock Classes="h2" Text="启动器维护" />
|
||||
<TextBlock Classes="muted" TextWrapping="Wrap"
|
||||
Text="重新下载会关闭所有窗口,显示下载进度,完成后自动启动新版本并删除旧版本。" />
|
||||
<Button Classes="primary" Content="重新下载启动器"
|
||||
HorizontalAlignment="Left" Padding="18,8"
|
||||
Command="{Binding ReinstallLauncherCommand}" />
|
||||
</StackPanel>
|
||||
</Border>
|
||||
|
||||
<!-- 感谢(样式抄「开发者」卡片,内容写死,不读取数据) -->
|
||||
<Border Classes="card" Padding="22,20">
|
||||
<StackPanel Spacing="14">
|
||||
<TextBlock Classes="h2" Text="感谢" />
|
||||
|
||||
<StackPanel Orientation="Horizontal" Spacing="10">
|
||||
<Border Background="{DynamicResource SurfaceAlt}"
|
||||
BorderBrush="{DynamicResource Line}" BorderThickness="1"
|
||||
CornerRadius="12" Padding="12,10" MinWidth="190">
|
||||
<StackPanel Orientation="Horizontal" Spacing="10">
|
||||
<Border Width="34" Height="34" CornerRadius="17"
|
||||
Background="{DynamicResource AccentSoft}">
|
||||
<TextBlock Text="◉" FontSize="15" Foreground="{DynamicResource Accent}"
|
||||
HorizontalAlignment="Center" VerticalAlignment="Center" />
|
||||
</Border>
|
||||
<StackPanel VerticalAlignment="Center" Spacing="1">
|
||||
<TextBlock Text="地理洪老师" FontSize="12.5" FontWeight="SemiBold" />
|
||||
<TextBlock Classes="faint" Text="地理学科内容指导" />
|
||||
</StackPanel>
|
||||
</StackPanel>
|
||||
</Border>
|
||||
</StackPanel>
|
||||
</StackPanel>
|
||||
</Border>
|
||||
|
||||
<!-- 开发者 -->
|
||||
<Border Classes="card" Padding="22,20">
|
||||
<StackPanel Spacing="14">
|
||||
<Grid ColumnDefinitions="*,Auto">
|
||||
<TextBlock Classes="h2" Text="{Binding ContributorsTitle}" />
|
||||
<Button Grid.Column="1" Classes="ghost small" Content="刷新"
|
||||
Command="{Binding LoadCommand}" IsEnabled="{Binding !IsLoading}" />
|
||||
</Grid>
|
||||
|
||||
<TextBlock Classes="faint" Text="{Binding StatusText}" />
|
||||
|
||||
<ProgressBar IsIndeterminate="True" Height="3" IsVisible="{Binding IsLoading}" />
|
||||
|
||||
<ItemsControl ItemsSource="{Binding Contributors}" IsVisible="{Binding HasContributors}">
|
||||
<ItemsControl.ItemsPanel>
|
||||
<ItemsPanelTemplate>
|
||||
<WrapPanel Orientation="Horizontal" />
|
||||
</ItemsPanelTemplate>
|
||||
</ItemsControl.ItemsPanel>
|
||||
<ItemsControl.ItemTemplate>
|
||||
<DataTemplate>
|
||||
<Border Background="{DynamicResource SurfaceAlt}"
|
||||
BorderBrush="{DynamicResource Line}" BorderThickness="1"
|
||||
CornerRadius="12" Padding="12,10" Margin="0,0,10,10" MinWidth="190">
|
||||
<StackPanel Orientation="Horizontal" Spacing="10">
|
||||
<Border Width="34" Height="34" CornerRadius="17"
|
||||
Background="{DynamicResource AccentSoft}">
|
||||
<TextBlock Text="◉" FontSize="15" Foreground="{DynamicResource Accent}"
|
||||
HorizontalAlignment="Center" VerticalAlignment="Center" />
|
||||
</Border>
|
||||
<StackPanel VerticalAlignment="Center" Spacing="1">
|
||||
<TextBlock Text="{Binding Name}" FontSize="12.5" FontWeight="SemiBold" />
|
||||
<TextBlock Classes="faint" Text="{Binding ContributionsText}" />
|
||||
</StackPanel>
|
||||
</StackPanel>
|
||||
</Border>
|
||||
</DataTemplate>
|
||||
</ItemsControl.ItemTemplate>
|
||||
</ItemsControl>
|
||||
</StackPanel>
|
||||
</Border>
|
||||
|
||||
</StackPanel>
|
||||
</ScrollViewer>
|
||||
</UserControl>
|
||||
@@ -0,0 +1,11 @@
|
||||
using Avalonia.Controls;
|
||||
using Avalonia.Markup.Xaml;
|
||||
|
||||
namespace GC.Views;
|
||||
|
||||
public partial class AboutView : UserControl
|
||||
{
|
||||
public AboutView() => InitializeComponent();
|
||||
|
||||
private void InitializeComponent() => AvaloniaXamlLoader.Load(this);
|
||||
}
|
||||
@@ -1,19 +1,21 @@
|
||||
<Window xmlns="https://github.com/avaloniaui"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:loc="using:EarthModelStudio.Services"
|
||||
x:Class="EarthModelStudio.Views.ConfirmWindow"
|
||||
xmlns:loc="using:GC.Services"
|
||||
x:Class="GC.Views.ConfirmWindow"
|
||||
Title="{loc:Loc app.name}"
|
||||
Width="440" SizeToContent="Height"
|
||||
CanResize="False" ShowInTaskbar="False"
|
||||
WindowStartupLocation="CenterOwner"
|
||||
Background="{DynamicResource Surface}">
|
||||
Background="Transparent"
|
||||
SystemDecorations="None"
|
||||
TransparencyLevelHint="Transparent">
|
||||
|
||||
<StackPanel Margin="24,20,24,20" Spacing="14">
|
||||
<TextBlock Classes="h2" Text="{loc:Loc common.confirmTitle}" />
|
||||
<TextBlock x:Name="TitleText" Classes="h2" Text="{loc:Loc common.confirmTitle}" />
|
||||
<TextBlock x:Name="MessageText" Classes="muted" TextWrapping="Wrap" />
|
||||
<StackPanel Orientation="Horizontal" HorizontalAlignment="Right" Spacing="8" Margin="0,6,0,0">
|
||||
<Button Content="{loc:Loc common.cancel}" Click="OnCancel" />
|
||||
<Button Classes="primary" Content="{loc:Loc common.confirm}" Click="OnConfirm" />
|
||||
<Button x:Name="CancelButton" Content="{loc:Loc common.cancel}" Click="OnCancel" />
|
||||
<Button x:Name="ConfirmButton" Classes="primary" Content="{loc:Loc common.confirm}" Click="OnConfirm" />
|
||||
</StackPanel>
|
||||
</StackPanel>
|
||||
</Window>
|
||||
@@ -0,0 +1,66 @@
|
||||
using Avalonia;
|
||||
using Avalonia.Controls;
|
||||
using Avalonia.Interactivity;
|
||||
using Avalonia.Markup.Xaml;
|
||||
using Avalonia.Media;
|
||||
|
||||
namespace GC.Views;
|
||||
|
||||
public partial class ConfirmWindow : Window
|
||||
{
|
||||
public ConfirmWindow() : this("") { }
|
||||
|
||||
public ConfirmWindow(string message) : this(null, message, null, null) { }
|
||||
|
||||
/// <summary>
|
||||
/// 可定制标题与按钮文案的确认窗。
|
||||
/// </summary>
|
||||
public ConfirmWindow(string? title, string message, string? confirmText, string? cancelText)
|
||||
{
|
||||
AvaloniaXamlLoader.Load(this);
|
||||
|
||||
TransparencyLevelHint = new[] { WindowTransparencyLevel.Transparent };
|
||||
Background = Brushes.Transparent;
|
||||
if (this.Content is Control content)
|
||||
{
|
||||
// 先把 content 从 Window 上摘下来,否则再赋给 Border.Child 会抛
|
||||
// "The Control already has a parent."
|
||||
this.Content = null;
|
||||
this.Content = new Border
|
||||
{
|
||||
CornerRadius = new CornerRadius(14),
|
||||
BorderBrush = (this.FindResource("Line") as IBrush) ?? Brushes.Gray,
|
||||
BorderThickness = new Thickness(1),
|
||||
Background = (this.FindResource("Surface") as IBrush) ?? Brushes.White,
|
||||
ClipToBounds = true,
|
||||
Child = content
|
||||
};
|
||||
}
|
||||
|
||||
var text = this.FindControl<TextBlock>("MessageText");
|
||||
if (text != null) text.Text = message;
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(title))
|
||||
{
|
||||
var titleBlock = this.FindControl<TextBlock>("TitleText");
|
||||
if (titleBlock != null) titleBlock.Text = title;
|
||||
}
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(confirmText))
|
||||
{
|
||||
var ok = this.FindControl<Button>("ConfirmButton");
|
||||
if (ok != null) ok.Content = confirmText;
|
||||
}
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(cancelText))
|
||||
{
|
||||
// 取消按钮是第一个("取消"),这里按名查找更稳
|
||||
var cancel = this.FindControl<Button>("CancelButton");
|
||||
if (cancel != null) cancel.Content = cancelText;
|
||||
}
|
||||
}
|
||||
|
||||
private void OnCancel(object? sender, RoutedEventArgs e) => Close(false);
|
||||
|
||||
private void OnConfirm(object? sender, RoutedEventArgs e) => Close(true);
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
<UserControl xmlns="https://github.com/avaloniaui"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:loc="using:EarthModelStudio.Services"
|
||||
x:Class="EarthModelStudio.Views.DownloadView">
|
||||
xmlns:loc="using:GC.Services"
|
||||
x:Class="GC.Views.DownloadView">
|
||||
|
||||
<Grid ColumnDefinitions="316,*" Margin="24,22,24,24">
|
||||
|
||||
@@ -11,9 +11,9 @@
|
||||
|
||||
<TextBlock Classes="h2" Text="{loc:Loc dl.sources}" />
|
||||
|
||||
<!-- 只允许 Xhmcl / GitCode 两个内置源;这里是对比测速并自动切换 -->
|
||||
<StackPanel Grid.Row="1" Margin="0,12,0,0" Spacing="8">
|
||||
<TextBox Text="{Binding ImportUrl}" Watermark="{loc:Loc dl.importPlaceholder}" />
|
||||
<Button Classes="primary" Content="{loc:Loc dl.import}"
|
||||
<Button Classes="primary" Content="测速并切换到最快源"
|
||||
Command="{Binding ImportCommand}" HorizontalAlignment="Stretch" />
|
||||
</StackPanel>
|
||||
|
||||
@@ -31,8 +31,7 @@
|
||||
TextTrimming="CharacterEllipsis" />
|
||||
<TextBlock Text="{Binding HostText}" Classes="faint" TextTrimming="CharacterEllipsis" />
|
||||
</StackPanel>
|
||||
<Button Grid.Column="1" Classes="ghost small" Content="✕"
|
||||
Command="{Binding RemoveCommand}" VerticalAlignment="Center" />
|
||||
|
||||
</Grid>
|
||||
</DataTemplate>
|
||||
</ListBox.ItemTemplate>
|
||||
@@ -1,7 +1,7 @@
|
||||
using Avalonia.Controls;
|
||||
using Avalonia.Markup.Xaml;
|
||||
|
||||
namespace EarthModelStudio.Views;
|
||||
namespace GC.Views;
|
||||
|
||||
public partial class DownloadView : UserControl
|
||||
{
|
||||
@@ -1,8 +1,8 @@
|
||||
<UserControl xmlns="https://github.com/avaloniaui"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:loc="using:EarthModelStudio.Services"
|
||||
xmlns:controls="using:EarthModelStudio.Controls"
|
||||
x:Class="EarthModelStudio.Views.HomeView">
|
||||
xmlns:loc="using:GC.Services"
|
||||
xmlns:controls="using:GC.Controls"
|
||||
x:Class="GC.Views.HomeView">
|
||||
|
||||
<ScrollViewer VerticalScrollBarVisibility="Auto">
|
||||
<StackPanel Margin="26,24,26,28" Spacing="18">
|
||||
@@ -1,7 +1,7 @@
|
||||
using Avalonia.Controls;
|
||||
using Avalonia.Markup.Xaml;
|
||||
|
||||
namespace EarthModelStudio.Views;
|
||||
namespace GC.Views;
|
||||
|
||||
public partial class HomeView : UserControl
|
||||
{
|
||||
@@ -8,7 +8,7 @@ using Avalonia.Layout;
|
||||
using Avalonia.Media;
|
||||
using Avalonia.Threading;
|
||||
|
||||
namespace EarthModelStudio.Views;
|
||||
namespace GC.Views;
|
||||
|
||||
/// <summary>
|
||||
/// 模型启动进度窗:加载模型程序集、生成地表纹理、构建界面的真实进度。
|
||||
@@ -0,0 +1,119 @@
|
||||
<Window xmlns="https://github.com/avaloniaui"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:loc="using:GC.Services"
|
||||
x:Class="GC.Views.MainWindow"
|
||||
Title="{loc:Loc app.name}"
|
||||
Width="1220" Height="800"
|
||||
MinWidth="1040" MinHeight="700"
|
||||
Background="Transparent"
|
||||
TransparencyLevelHint="Transparent"
|
||||
SystemDecorations="None"
|
||||
WindowStartupLocation="CenterScreen">
|
||||
|
||||
<!-- 禁用系统标题栏,改用自建标题栏。
|
||||
窗口本身透明(四角露出桌面 => 圆角可见),内容 Border 自己不透明并
|
||||
用 CornerRadius + ClipToBounds 裁出圆角;AcrylicBlur 会引入系统白色,
|
||||
所以这里用纯 Transparent 避免白边。 -->
|
||||
<Border CornerRadius="16" ClipToBounds="True"
|
||||
Background="{DynamicResource AppBg}"
|
||||
BorderBrush="#1B2740" BorderThickness="1"
|
||||
BoxShadow="0 18 50 0 #400A1226">
|
||||
<Grid RowDefinitions="44,*">
|
||||
<!-- 自建标题栏 -->
|
||||
<Border x:Name="TitleBar" Grid.Row="0" Background="{DynamicResource TitleBarBg}"
|
||||
PointerPressed="OnTitleBarPointerPressed">
|
||||
<Grid ColumnDefinitions="*,Auto,Auto,Auto" Margin="16,0,10,0">
|
||||
<StackPanel Orientation="Horizontal" Spacing="10" VerticalAlignment="Center">
|
||||
<Border Width="22" Height="22" CornerRadius="7" Background="#1C2C4C">
|
||||
<TextBlock Text="◎" FontSize="13" Foreground="#8FB6FF"
|
||||
HorizontalAlignment="Center" VerticalAlignment="Center" />
|
||||
</Border>
|
||||
<TextBlock Text="{loc:Loc app.name}" Foreground="#F2F6FF" FontSize="12.5"
|
||||
FontWeight="SemiBold" VerticalAlignment="Center" />
|
||||
</StackPanel>
|
||||
<!-- 与模型窗口一致的纯矢量图标:无圆圈 -->
|
||||
<Button x:Name="MinimizeButton" Grid.Column="1" Classes="titlebtn"
|
||||
Click="OnMinimizeClick">
|
||||
<Path Data="M1.5,5 L8.5,5" Stroke="#A9B8D4" StrokeThickness="1.5"
|
||||
StrokeLineCap="Round" Stretch="None" Width="10" Height="10"
|
||||
HorizontalAlignment="Center" VerticalAlignment="Center" />
|
||||
</Button>
|
||||
<Button x:Name="MaximizeButton" Grid.Column="2" Classes="titlebtn"
|
||||
Click="OnMaximizeClick">
|
||||
<Path x:Name="MaximizeGlyph" Data="M2.2,2.2 L7.8,2.2 L7.8,7.8 L2.2,7.8 Z"
|
||||
Stroke="#A9B8D4" StrokeThickness="1.5" StrokeLineCap="Round"
|
||||
StrokeJoin="Round" Stretch="None" Width="10" Height="10"
|
||||
HorizontalAlignment="Center" VerticalAlignment="Center" />
|
||||
</Button>
|
||||
<Button x:Name="CloseButton" Grid.Column="3" Classes="titlebtn close"
|
||||
Click="OnCloseClick">
|
||||
<Path Data="M2,2 L8,8 M8,2 L2,8" Stroke="#A9B8D4" StrokeThickness="1.5"
|
||||
StrokeLineCap="Round" Stretch="None" Width="10" Height="10"
|
||||
HorizontalAlignment="Center" VerticalAlignment="Center" />
|
||||
</Button>
|
||||
</Grid>
|
||||
</Border>
|
||||
|
||||
<!-- 原内容整体下移一行 -->
|
||||
<Grid Grid.Row="1" ColumnDefinitions="236,*" RowDefinitions="*,Auto">
|
||||
|
||||
<!-- 侧栏:品牌已在标题栏展示,这里只留一句副标题,避免重复 -->
|
||||
<Border Grid.Column="0" Grid.RowSpan="2" Background="{DynamicResource SideBgBrush}">
|
||||
<Grid RowDefinitions="Auto,*,Auto" Margin="16,20,16,18">
|
||||
|
||||
<StackPanel Spacing="3" Margin="2,0,0,0">
|
||||
<TextBlock Text="{loc:Loc app.tagline}" Foreground="#7C90B4" FontSize="10.5"
|
||||
TextWrapping="Wrap" />
|
||||
</StackPanel>
|
||||
|
||||
<StackPanel Grid.Row="1" Margin="0,26,0,0" Spacing="6">
|
||||
<TextBlock Text="MENU" Foreground="#4C5F80" FontSize="9.5" FontWeight="SemiBold" Margin="14,0,0,4" />
|
||||
<Button Classes="nav" Classes.active="{Binding IsHomeActive}"
|
||||
Command="{Binding GoHomeCommand}" Content="{loc:Loc nav.home}" />
|
||||
<Button Classes="nav" Classes.active="{Binding IsDownloadActive}"
|
||||
Command="{Binding GoDownloadCommand}" Content="{loc:Loc nav.download}" />
|
||||
<Button Classes="nav" Classes.active="{Binding IsSettingsActive}"
|
||||
Command="{Binding GoSettingsCommand}" Content="{loc:Loc nav.settings}" />
|
||||
<Button Classes="nav" Classes.active="{Binding IsAboutActive}"
|
||||
Command="{Binding GoAboutCommand}" Content="{loc:Loc nav.about}" />
|
||||
</StackPanel>
|
||||
|
||||
<StackPanel Grid.Row="2" Spacing="4">
|
||||
<Border Height="1" Background="{DynamicResource SideLine}" Margin="0,0,0,10" />
|
||||
<TextBlock Text="{Binding VersionText}" Foreground="#6F82A6" FontSize="10.5" Margin="14,0,0,0" />
|
||||
<TextBlock Text="{Binding PlatformText}" Foreground="#4F6080" FontSize="10" Margin="14,0,0,0" />
|
||||
</StackPanel>
|
||||
|
||||
</Grid>
|
||||
</Border>
|
||||
|
||||
<!-- 内容:页面切换由 MainWindow 做淡入过渡,避免硬切 -->
|
||||
<ContentControl x:Name="PageHost" Grid.Column="1" Grid.Row="0" Content="{Binding Current}" />
|
||||
|
||||
<!-- 启动更新状态条:模型立即生效,启动器下次启动生效 -->
|
||||
<Border Grid.Column="1" Grid.Row="1"
|
||||
Background="{DynamicResource Surface}"
|
||||
BorderBrush="{DynamicResource Line}" BorderThickness="0,1,0,0"
|
||||
Padding="20,9" IsVisible="{Binding UpdateBarVisible}">
|
||||
<Grid ColumnDefinitions="Auto,*,Auto,Auto">
|
||||
<TextBlock Grid.Column="0" Text="⟳" FontSize="16" Foreground="{DynamicResource Accent}"
|
||||
VerticalAlignment="Center" Margin="0,0,12,0" />
|
||||
<StackPanel Grid.Column="1" Spacing="2" VerticalAlignment="Center">
|
||||
<TextBlock Text="{Binding UpdateStatus}" FontSize="12.5" FontWeight="SemiBold"
|
||||
Foreground="{DynamicResource Ink}" TextTrimming="CharacterEllipsis" />
|
||||
<TextBlock Text="{Binding UpdateDetail}" Classes="faint" TextTrimming="CharacterEllipsis" />
|
||||
<TextBlock Text="{Binding LauncherNotice}" FontSize="11" Foreground="{DynamicResource Warn}"
|
||||
TextWrapping="Wrap" />
|
||||
</StackPanel>
|
||||
<ProgressBar Grid.Column="2" Width="130" Minimum="0" Maximum="1"
|
||||
Value="{Binding UpdateProgress}" IsVisible="{Binding UpdateBusy}"
|
||||
VerticalAlignment="Center" Margin="14,0" />
|
||||
<Button Grid.Column="3" Classes="ghost small" Content="{loc:Loc update.checkNow}"
|
||||
Command="{Binding CheckUpdateCommand}" IsEnabled="{Binding !UpdateBusy}"
|
||||
VerticalAlignment="Center" />
|
||||
</Grid>
|
||||
</Border>
|
||||
</Grid>
|
||||
</Grid>
|
||||
</Border>
|
||||
</Window>
|
||||
@@ -8,12 +8,13 @@ using Avalonia.Animation.Easings;
|
||||
using Avalonia.Threading;
|
||||
using System.Linq;
|
||||
using Avalonia.Controls;
|
||||
using Avalonia.Input;
|
||||
using Avalonia.Markup.Xaml;
|
||||
using EarthModelStudio.Models;
|
||||
using EarthModelStudio.Services;
|
||||
using EarthModelStudio.ViewModels;
|
||||
using GC.Models;
|
||||
using GC.Services;
|
||||
using GC.ViewModels;
|
||||
|
||||
namespace EarthModelStudio.Views;
|
||||
namespace GC.Views;
|
||||
|
||||
public partial class MainWindow : Window
|
||||
{
|
||||
@@ -39,8 +40,21 @@ public partial class MainWindow : Window
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
DataContextChanged += OnDataContextChanged;
|
||||
Closed += OnClosed;
|
||||
|
||||
// 最大化 / 还原:切换图标(单框 ⇄ 双框),圆角始终保持
|
||||
PropertyChanged += (_, e) =>
|
||||
{
|
||||
if (e.Property != WindowStateProperty) return;
|
||||
var max = WindowState == WindowState.Maximized;
|
||||
if (this.FindControl<Avalonia.Controls.Shapes.Path>("MaximizeGlyph") is { } glyph)
|
||||
glyph.Data = Avalonia.Media.Geometry.Parse(max
|
||||
? "M2.6,3.4 L7.4,3.4 L7.4,8.4 L2.6,8.4 Z M2.6,3.4 L2.6,1.6 L7.4,1.6 L7.4,6.6"
|
||||
: "M2.2,2.2 L7.8,2.2 L7.8,7.8 L2.2,7.8 Z");
|
||||
if (Content is Border frame) frame.CornerRadius = new Avalonia.CornerRadius(16);
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>当前打开的模型窗口(每个模型一个独立窗口)。</summary>
|
||||
@@ -144,6 +158,48 @@ public partial class MainWindow : Window
|
||||
window.Activate();
|
||||
}
|
||||
|
||||
// ---- 自建标题栏 ------------------------------------------------------
|
||||
private void OnTitleBarPointerPressed(object? sender, PointerPressedEventArgs e)
|
||||
{
|
||||
// 双击标题栏 = 最大化 / 还原
|
||||
if (e.ClickCount == 2)
|
||||
{
|
||||
WindowState = WindowState == WindowState.Maximized
|
||||
? WindowState.Normal
|
||||
: WindowState.Maximized;
|
||||
return;
|
||||
}
|
||||
if (e.GetCurrentPoint(this).Properties.IsLeftButtonPressed)
|
||||
BeginMoveDrag(e);
|
||||
}
|
||||
|
||||
private void OnMinimizeClick(object? sender, global::Avalonia.Interactivity.RoutedEventArgs e)
|
||||
=> WindowState = WindowState.Minimized;
|
||||
|
||||
private void OnMaximizeClick(object? sender, global::Avalonia.Interactivity.RoutedEventArgs e)
|
||||
=> WindowState = WindowState == WindowState.Maximized
|
||||
? WindowState.Normal
|
||||
: WindowState.Maximized;
|
||||
|
||||
// 关闭动画:先淡出再真正 Close(第 4 项)
|
||||
private async void OnCloseClick(object? sender, global::Avalonia.Interactivity.RoutedEventArgs e)
|
||||
{
|
||||
if (_isClosing) return;
|
||||
Opacity = 1;
|
||||
Transitions = new Transitions
|
||||
{
|
||||
new DoubleTransition
|
||||
{
|
||||
Property = OpacityProperty,
|
||||
Duration = TimeSpan.FromMilliseconds(180),
|
||||
Easing = new CubicEaseIn()
|
||||
}
|
||||
};
|
||||
Opacity = 0;
|
||||
await Task.Delay(190);
|
||||
Close();
|
||||
}
|
||||
|
||||
private void OnClosed(object? sender, EventArgs e)
|
||||
{
|
||||
_isClosing = true;
|
||||
@@ -1,7 +1,7 @@
|
||||
<UserControl xmlns="https://github.com/avaloniaui"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:loc="using:EarthModelStudio.Services"
|
||||
x:Class="EarthModelStudio.Views.SettingsView">
|
||||
xmlns:loc="using:GC.Services"
|
||||
x:Class="GC.Views.SettingsView">
|
||||
|
||||
<ScrollViewer VerticalScrollBarVisibility="Auto">
|
||||
<StackPanel Margin="26,24,26,32" Spacing="16" MaxWidth="880" HorizontalAlignment="Left">
|
||||
@@ -50,7 +50,10 @@
|
||||
Foreground="{DynamicResource Accent}" VerticalAlignment="Center" />
|
||||
</Grid>
|
||||
<TextBlock Classes="muted" Text="{loc:Loc set.memory.desc}" TextWrapping="Wrap" />
|
||||
<CheckBox Content="{loc:Loc set.memory.auto}" IsChecked="{Binding MemoryAuto}"
|
||||
Margin="0,2,0,0" />
|
||||
<Slider Minimum="512" Maximum="8192" TickFrequency="256" IsSnapToTickEnabled="False"
|
||||
IsEnabled="{Binding !MemoryAuto}"
|
||||
Value="{Binding MemoryValue}" Margin="0,4,0,0" />
|
||||
<Grid ColumnDefinitions="*,Auto">
|
||||
<TextBlock Classes="faint" Text="{loc:Loc set.memory.hint}" TextWrapping="Wrap" />
|
||||
@@ -75,7 +78,7 @@
|
||||
<TextBlock Text="{Binding UrlText}" Classes="faint" TextTrimming="CharacterEllipsis" MaxWidth="520" />
|
||||
</StackPanel>
|
||||
<Button Grid.Column="2" Classes="ghost small" Content="✕"
|
||||
Command="{Binding RemoveCommand}" VerticalAlignment="Center" />
|
||||
IsVisible="{Binding CanRemove}" Command="{Binding RemoveCommand}" VerticalAlignment="Center" />
|
||||
</Grid>
|
||||
</Border>
|
||||
</DataTemplate>
|
||||
@@ -135,29 +138,6 @@
|
||||
</StackPanel>
|
||||
</Border>
|
||||
|
||||
<!-- 关于 -->
|
||||
<Border Classes="card" Padding="20,18">
|
||||
<StackPanel Spacing="12">
|
||||
<TextBlock Classes="h2" Text="{loc:Loc set.about}" />
|
||||
<Grid ColumnDefinitions="200,*">
|
||||
<TextBlock Classes="h3" Text="{loc:Loc set.version}" />
|
||||
<TextBlock Grid.Column="1" Classes="muted" Text="{Binding VersionText}" />
|
||||
</Grid>
|
||||
<Grid ColumnDefinitions="200,*">
|
||||
<TextBlock Classes="h3" Text="{loc:Loc set.platform}" />
|
||||
<TextBlock Grid.Column="1" Classes="muted" Text="{Binding PlatformText}" TextWrapping="Wrap" />
|
||||
</Grid>
|
||||
<Grid ColumnDefinitions="200,*">
|
||||
<TextBlock Classes="h3" Text="{loc:Loc set.modelFormat}" />
|
||||
<TextBlock Grid.Column="1" Classes="muted" Text="{loc:Loc set.modelFormat.desc}" TextWrapping="Wrap" />
|
||||
</Grid>
|
||||
<Grid ColumnDefinitions="200,*">
|
||||
<TextBlock Classes="h3" Text="{loc:Loc set.license}" />
|
||||
<TextBlock Grid.Column="1" Classes="muted" Text="{loc:Loc set.licenseValue}" />
|
||||
</Grid>
|
||||
</StackPanel>
|
||||
</Border>
|
||||
|
||||
</StackPanel>
|
||||
</ScrollViewer>
|
||||
</UserControl>
|
||||
@@ -1,7 +1,7 @@
|
||||
using Avalonia.Controls;
|
||||
using Avalonia.Markup.Xaml;
|
||||
|
||||
namespace EarthModelStudio.Views;
|
||||
namespace GC.Views;
|
||||
|
||||
public partial class SettingsView : UserControl
|
||||
{
|
||||
@@ -0,0 +1,109 @@
|
||||
using System;
|
||||
using Avalonia;
|
||||
using Avalonia.Controls;
|
||||
using Avalonia.Layout;
|
||||
using Avalonia.Media;
|
||||
using Avalonia.Threading;
|
||||
using GC.Services;
|
||||
|
||||
namespace GC.Views;
|
||||
|
||||
/// <summary>
|
||||
/// 启动器更新进度窗:更新期间主窗口已关闭,由这个独立小窗展示下载进度。
|
||||
/// 窗口本身透明,圆角由内部 Border 裁出。
|
||||
/// </summary>
|
||||
public sealed class UpdaterWindow : Window
|
||||
{
|
||||
private readonly ProgressBar _bar;
|
||||
private readonly TextBlock _stage;
|
||||
private readonly TextBlock _detail;
|
||||
private readonly TextBlock _percent;
|
||||
|
||||
public UpdaterWindow(string title)
|
||||
{
|
||||
Title = title;
|
||||
Width = 460;
|
||||
Height = 210;
|
||||
CanResize = false;
|
||||
ShowInTaskbar = false;
|
||||
WindowStartupLocation = WindowStartupLocation.CenterScreen;
|
||||
// 必须透明,否则会把内部 Border 的圆角填平
|
||||
Background = Brushes.Transparent;
|
||||
TransparencyLevelHint = new[] { WindowTransparencyLevel.Transparent };
|
||||
SystemDecorations = SystemDecorations.None;
|
||||
|
||||
var titleBlock = new TextBlock
|
||||
{
|
||||
Text = title,
|
||||
Foreground = new SolidColorBrush(Color.Parse("#F2F6FF")),
|
||||
FontSize = 15,
|
||||
FontWeight = FontWeight.SemiBold
|
||||
};
|
||||
|
||||
_stage = new TextBlock
|
||||
{
|
||||
Text = "正在准备…",
|
||||
Foreground = new SolidColorBrush(Color.Parse("#8CA0C4")),
|
||||
FontSize = 12
|
||||
};
|
||||
|
||||
_bar = new ProgressBar
|
||||
{
|
||||
Minimum = 0,
|
||||
Maximum = 1,
|
||||
Value = 0,
|
||||
Height = 6,
|
||||
CornerRadius = new CornerRadius(3),
|
||||
Foreground = new SolidColorBrush(Color.Parse("#3B7BFF")),
|
||||
Background = new SolidColorBrush(Color.Parse("#1B2740"))
|
||||
};
|
||||
|
||||
_percent = new TextBlock
|
||||
{
|
||||
Text = "0%",
|
||||
Foreground = new SolidColorBrush(Color.Parse("#6E86AD")),
|
||||
FontSize = 11,
|
||||
HorizontalAlignment = HorizontalAlignment.Right
|
||||
};
|
||||
|
||||
_detail = new TextBlock
|
||||
{
|
||||
Text = "",
|
||||
Foreground = new SolidColorBrush(Color.Parse("#4F6382")),
|
||||
FontSize = 10.5
|
||||
};
|
||||
|
||||
var panel = new StackPanel { Margin = new Thickness(24, 22), Spacing = 12 };
|
||||
panel.Children.Add(titleBlock);
|
||||
panel.Children.Add(_bar);
|
||||
panel.Children.Add(_stage);
|
||||
panel.Children.Add(_percent);
|
||||
panel.Children.Add(_detail);
|
||||
|
||||
Content = new Border
|
||||
{
|
||||
CornerRadius = new CornerRadius(16),
|
||||
Background = new SolidColorBrush(Color.Parse("#0B1226")),
|
||||
BorderBrush = new SolidColorBrush(Color.Parse("#223252")),
|
||||
BorderThickness = new Thickness(1),
|
||||
ClipToBounds = true,
|
||||
Child = panel
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>任意线程调用都可以。</summary>
|
||||
public void Report(double value, string? stage, string? detail = null)
|
||||
{
|
||||
if (!Dispatcher.UIThread.CheckAccess())
|
||||
{
|
||||
Dispatcher.UIThread.Post(() => Report(value, stage, detail));
|
||||
return;
|
||||
}
|
||||
|
||||
var clamped = Math.Clamp(value, 0, 1);
|
||||
_bar.Value = clamped;
|
||||
_percent.Text = $"{clamped * 100:0}%";
|
||||
if (!string.IsNullOrWhiteSpace(stage)) _stage.Text = stage;
|
||||
if (!string.IsNullOrWhiteSpace(detail)) _detail.Text = detail;
|
||||
}
|
||||
}
|
||||
@@ -4,8 +4,8 @@
|
||||
<OutputType>Exe</OutputType>
|
||||
<Nullable>enable</Nullable>
|
||||
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
|
||||
<RootNamespace>EarthModelStudio.Tests</RootNamespace>
|
||||
<AssemblyName>EarthModelStudio.Tests</AssemblyName>
|
||||
<RootNamespace>GC.Tests</RootNamespace>
|
||||
<AssemblyName>GC.Tests</AssemblyName>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
@@ -14,7 +14,8 @@
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="../../../main/dotnet/EarthModelStudio/EarthModelStudio.csproj" />
|
||||
<ProjectReference Include="../../../GC.Core.csproj" />
|
||||
<ProjectReference Include="../../../../../GC-DOWNLOAD/GC-DOWNLOAD.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -2,25 +2,29 @@ using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using System.IO;
|
||||
using System.IO.Compression;
|
||||
using System.Linq;
|
||||
using EarthModelStudio.Models;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text.Json;
|
||||
using GC.Models;
|
||||
using Avalonia;
|
||||
using Avalonia.Controls;
|
||||
using Avalonia.Headless;
|
||||
using Avalonia.Threading;
|
||||
using Avalonia.VisualTree;
|
||||
using EarthModelStudio;
|
||||
using EarthModelStudio.Services;
|
||||
using EarthModelStudio.ViewModels;
|
||||
using EarthModelStudio.Views;
|
||||
using GC;
|
||||
using GC.Download;
|
||||
using GC.Services;
|
||||
using GC.ViewModels;
|
||||
using GC.Views;
|
||||
|
||||
namespace EarthModelStudio.Tests;
|
||||
namespace GC.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// 离屏校验工具:把启动器页面和模型窗口渲染成 PNG。
|
||||
/// 用法:dotnet run --project src/test/dotnet/EarthModelStudio.Tests -- build/screenshots
|
||||
/// 用法:dotnet run --project GC/src/test/dotnet/GC.Tests -- build/screenshots
|
||||
/// </summary>
|
||||
internal static class Program
|
||||
{
|
||||
@@ -29,6 +33,7 @@ internal static class Program
|
||||
[STAThread]
|
||||
public static int Main(string[] args)
|
||||
{
|
||||
DownloadModuleHost.Factory = new DownloadModuleFactory();
|
||||
if (args.Length > 0 && args[0] == "--update-test")
|
||||
return RunUpdateTest(args.Length > 1 ? args[1] : FindRepoRoot());
|
||||
|
||||
@@ -76,7 +81,9 @@ internal static class Program
|
||||
|
||||
// 模拟远端仓库:version.json + 每个模型的 <id>.json / <id>.model/
|
||||
Directory.CreateDirectory(Path.Combine(remote, "model"));
|
||||
File.Copy(versionFile, Path.Combine(remote, "version.json"), true);
|
||||
var fixtureVersion = Json.Read<RepoVersion>(versionFile)!;
|
||||
fixtureVersion.Models.RemoveAll(model =>
|
||||
model.Id is not "earth-rotation" and not "earth-revolution");
|
||||
foreach (var dir in Directory.GetDirectories(Path.Combine(repoRoot, "model")))
|
||||
{
|
||||
var id = Path.GetFileName(dir);
|
||||
@@ -90,10 +97,32 @@ internal static class Program
|
||||
CopyTree(data, Path.Combine(dest, id + ".model"));
|
||||
}
|
||||
|
||||
// 按远端实际内容重算完整性哈希(与 VersionStamp 同一算法),然后签名。
|
||||
// 客户端会复算这两项,不一致就拒绝安装 —— 这一步必须与构建端一致。
|
||||
foreach (var m in fixtureVersion.Models)
|
||||
{
|
||||
var computed = ModelIntegrity.Compute(Path.Combine(remote, "model", m.Id), m.Id);
|
||||
m.ManifestSha256 = computed.ManifestSha256;
|
||||
m.FilesSha256 = computed.FilesSha256;
|
||||
m.Files = computed.Files.Count;
|
||||
}
|
||||
|
||||
var signer = ManifestSignature.TryLoadPrivateKey(
|
||||
Path.Combine(repoRoot, ".signing", "gc-signing.pem"));
|
||||
if (signer == null)
|
||||
{
|
||||
Console.WriteLine("FAIL: 缺少签名私钥 .signing/gc-signing.pem,无法构造可信清单");
|
||||
return 1;
|
||||
}
|
||||
|
||||
var remoteManifest = Path.Combine(remote, "version.json");
|
||||
WriteSigned(remoteManifest, fixtureVersion, signer);
|
||||
Console.WriteLine($"远端清单已签名({ManifestSignature.Algorithm})");
|
||||
|
||||
// EMS_HOME 指向不含 .sln 的临时目录 -> 非开发态,走真实 .GC 布局
|
||||
Environment.SetEnvironmentVariable("EMS_HOME", tmp);
|
||||
Environment.SetEnvironmentVariable("EMS_DATA", home);
|
||||
Environment.SetEnvironmentVariable("EMS_MODELS", modelRoot);
|
||||
Environment.SetEnvironmentVariable("EMS_MODELS", null);
|
||||
Environment.SetEnvironmentVariable("EMS_NO_SELF_UPDATE", "1");
|
||||
|
||||
var paths = AppPaths.Discover();
|
||||
@@ -111,11 +140,13 @@ internal static class Program
|
||||
|
||||
Console.WriteLine($"运行目录: {paths.HomeRoot}");
|
||||
Console.WriteLine($"模型库: {paths.ModelRoot}");
|
||||
Check(paths.ModelRoot == modelRoot, ".GC/model 是下载目标");
|
||||
Check(File.Exists(paths.SettingsFile), ".GC/settings.json 已创建");
|
||||
Check(paths.ModelRoot == modelRoot, "模型安装目录位于 .GC/model");
|
||||
Check(paths.CacheRoot.StartsWith(paths.HomeRoot, StringComparison.Ordinal), "模型与启动器下载暂存位于 .GC/cache");
|
||||
Check(paths.UpdateRoot.StartsWith(paths.HomeRoot, StringComparison.Ordinal), "启动器更新位于 .GC/update");
|
||||
Check(File.Exists(paths.SettingsFile), ".GC/config/settings.json 已创建");
|
||||
|
||||
// 1) 首次启动:模型全部下载并立即落地
|
||||
var r1 = updater.RunAsync(true, null).GetAwaiter().GetResult();
|
||||
var r1 = Task.Run(() => updater.RunAsync(true, null)).GetAwaiter().GetResult();
|
||||
Console.WriteLine($"首次启动: {r1.Message} 更新数={r1.UpdatedModels}");
|
||||
Check(r1.UpdatedModels == 2, "首次启动下载 2 个模型");
|
||||
foreach (var id in new[] { "earth-rotation", "earth-revolution" })
|
||||
@@ -128,12 +159,12 @@ internal static class Program
|
||||
}
|
||||
|
||||
// 2) 版本没变:不重复下载
|
||||
var r2 = updater.RunAsync(true, null).GetAwaiter().GetResult();
|
||||
var r2 = Task.Run(() => updater.RunAsync(true, null)).GetAwaiter().GetResult();
|
||||
Console.WriteLine($"二次检查: {r2.Message} 更新数={r2.UpdatedModels}");
|
||||
Check(r2.UpdatedModels == 0, "版本未变时不重复下载");
|
||||
|
||||
// 3) 远端模型改版:只更新这一个,并且本次启动立即生效
|
||||
var rv = Json.Read<RepoVersion>(Path.Combine(remote, "version.json"))!;
|
||||
var rv = Json.Read<RepoVersion>(remoteManifest)!;
|
||||
Check(rv.Models.Count == 2 && !string.IsNullOrWhiteSpace(rv.Models[0].Version),
|
||||
"version.json 里模型版本由构建自动生成");
|
||||
var changed = rv.Models[0];
|
||||
@@ -141,48 +172,129 @@ internal static class Program
|
||||
var stampName = "_version-stamp.txt";
|
||||
File.WriteAllText(Path.Combine(remote, "model", changed.Id,
|
||||
changed.Id + ".model", stampName), "new content");
|
||||
Json.Write(Path.Combine(remote, "version.json"), rv);
|
||||
var r3 = updater.RunAsync(true, null).GetAwaiter().GetResult();
|
||||
|
||||
// 内容变了 → 指纹必须跟着变,并且清单要重新签名,否则客户端会(正确地)拒绝
|
||||
var changedHash = ModelIntegrity.Compute(Path.Combine(remote, "model", changed.Id), changed.Id);
|
||||
changed.ManifestSha256 = changedHash.ManifestSha256;
|
||||
changed.FilesSha256 = changedHash.FilesSha256;
|
||||
changed.Files = changedHash.Files.Count;
|
||||
WriteSigned(remoteManifest, rv, signer);
|
||||
|
||||
var r3 = Task.Run(() => updater.RunAsync(true, null)).GetAwaiter().GetResult();
|
||||
Console.WriteLine($"模型改版: {r3.Message} 更新数={r3.UpdatedModels}");
|
||||
Check(r3.UpdatedModels == 1, "模型版本变化只更新 1 个模型");
|
||||
Check(File.Exists(Path.Combine(modelRoot, changed.Id, changed.Id + ".model", stampName)),
|
||||
"新版本本次启动立即生效");
|
||||
Check(File.Exists(Path.Combine(modelRoot, changed.Id, changed.Id + ".integrity.json")),
|
||||
"安装后写入完整性记录");
|
||||
|
||||
// 4) 启动器新版:下载到 update/ 并写 pending,不立刻替换程序
|
||||
var rid = UpdateService.CurrentRid;
|
||||
Console.WriteLine($"当前平台: {rid},启动器版本: {UpdateService.CurrentLauncherVersion}");
|
||||
// 4) 启动器新版:用 LauncherUpdater 下载到当前目录(与旧版并列)
|
||||
var rid = LauncherRuntimeInfo.CurrentRid;
|
||||
Console.WriteLine($"当前平台: {rid},启动器版本: {LauncherRuntimeInfo.CurrentLauncherVersion}");
|
||||
var stage = Path.Combine(tmp, "launcher-stage");
|
||||
Directory.CreateDirectory(stage);
|
||||
File.WriteAllText(Path.Combine(stage, "EarthModelStudio.fake"), "new launcher");
|
||||
File.WriteAllText(Path.Combine(stage, "GC-9.9.9-" + LauncherUpdater.PlatformLabel + ".exe"),
|
||||
"new launcher");
|
||||
var zip = Path.Combine(tmp, "GC-" + rid + ".zip");
|
||||
ZipFile.CreateFromDirectory(stage, zip);
|
||||
rv.Launcher.Version = "9.9.9";
|
||||
rv.Launcher.Packages[rid] = new RepoPackage { Url = zip, Path = "dist/GC-" + rid + ".zip" };
|
||||
Json.Write(Path.Combine(remote, "version.json"), rv);
|
||||
var r4 = updater.RunAsync(true, null).GetAwaiter().GetResult();
|
||||
Console.WriteLine($"启动器新版: {r4.LauncherMessage}");
|
||||
Check(File.Exists(Path.Combine(paths.UpdateRoot, "pending.json")), "启动器更新写入 pending.json");
|
||||
Check(File.Exists(Path.Combine(paths.UpdateRoot, "payload", "EarthModelStudio.fake")),
|
||||
"更新包已解压到 update/payload");
|
||||
Check(settings.Current.PendingLauncherVersion == "9.9.9", "settings 记录待应用版本");
|
||||
Check((r4.LauncherMessage ?? "").Contains("下次启动"), "提示下次启动才生效");
|
||||
rv.Launcher.Packages[rid] = new RepoPackage
|
||||
{
|
||||
Url = zip,
|
||||
Sha256 = Convert.ToHexString(SHA256.HashData(File.ReadAllBytes(zip))).ToLowerInvariant(),
|
||||
Size = new FileInfo(zip).Length
|
||||
};
|
||||
WriteSigned(remoteManifest, rv, signer);
|
||||
|
||||
// 5) dry-run:验证下次启动的替换脚本能正确生成(不真的启动进程)
|
||||
Environment.SetEnvironmentVariable("EMS_NO_SELF_UPDATE", "");
|
||||
var scripted = LauncherUpdate.TryApplyPending(paths, launch: false);
|
||||
// 造一个旧版在当前目录
|
||||
var oldName = "GC-1.0.0-" + LauncherUpdater.PlatformLabel + ".exe";
|
||||
File.WriteAllText(Path.Combine(paths.InstallDirectory, oldName), "old launcher");
|
||||
|
||||
var dl = Task.Run(() => LauncherUpdater.DownloadAsync(paths, updater.Remote, null))
|
||||
.GetAwaiter().GetResult();
|
||||
Console.WriteLine($"启动器下载: {dl.Message}");
|
||||
Check(dl.State == UpdateRunState.Ready, "启动器下载成功");
|
||||
Check(!string.IsNullOrWhiteSpace(dl.PackageName), "得到新版包名");
|
||||
Check(File.Exists(Path.Combine(paths.UpdateRoot, "payload", dl.PackageName ?? "")) ||
|
||||
Directory.Exists(Path.Combine(paths.UpdateRoot, "payload", dl.PackageName ?? "")),
|
||||
"新版暂存于 .GC/update/payload");
|
||||
Check(!File.Exists(Path.Combine(paths.InstallDirectory, dl.PackageName ?? "")) &&
|
||||
!Directory.Exists(Path.Combine(paths.InstallDirectory, dl.PackageName ?? "")),
|
||||
"下载阶段不会把新版写入安装目录");
|
||||
Check(File.Exists(Path.Combine(paths.InstallDirectory, oldName)),
|
||||
"旧版仍在(删除由替换脚本在重启后做)");
|
||||
|
||||
// 5) 校验标记文件与替换脚本(相对路径,无绝对路径)
|
||||
var marker = Path.Combine(paths.UpdateRoot, "update.txt");
|
||||
Check(File.Exists(marker), "写出更新标记 update.txt");
|
||||
var scheduled = LauncherUpdater.ScheduleApply(paths, dl.PackageName ?? "");
|
||||
var scriptPath = Path.Combine(paths.UpdateRoot,
|
||||
OperatingSystem.IsWindows() ? "apply-update.bat" : "apply-update.sh");
|
||||
Check(scripted && File.Exists(scriptPath), "下次启动的替换脚本可生成");
|
||||
OperatingSystem.IsWindows() ? "apply.bat" : "apply.sh");
|
||||
Check(scheduled && File.Exists(scriptPath), "替换脚本可生成");
|
||||
if (File.Exists(scriptPath))
|
||||
{
|
||||
var script = File.ReadAllText(scriptPath);
|
||||
Check(script.Contains(paths.InstallDirectory), "脚本包含正确的安装目录");
|
||||
Check(!script.Contains(tmp), "脚本不含绝对路径");
|
||||
Check(script.Contains("GC-*.app") || script.Contains("GC-*"), "脚本按 GC-* 匹配删除");
|
||||
}
|
||||
|
||||
// 6) 断网兜底:保留本地模型,不清空
|
||||
// 5b) 只发产物、不发 Release:更新包只存在于仓库 dist/<系统>-<架构>/ 目录里。
|
||||
// 清单不写 url、不写 path,只给 dir + name + sha256,客户端要能自己找过去。
|
||||
var distDir = Path.Combine(remote, "dist", LauncherUpdater.PlatformLabel);
|
||||
Directory.CreateDirectory(distDir);
|
||||
var distName = "GC-9.9.10-" + LauncherUpdater.PlatformLabel + ".zip";
|
||||
var distZip = Path.Combine(distDir, distName);
|
||||
File.Copy(zip, distZip, true);
|
||||
|
||||
string Sha(string file) =>
|
||||
Convert.ToHexString(SHA256.HashData(File.ReadAllBytes(file))).ToLowerInvariant();
|
||||
|
||||
rv.Launcher.Version = "9.9.10";
|
||||
rv.Launcher.Packages[rid] = new RepoPackage
|
||||
{
|
||||
Dir = "dist/" + LauncherUpdater.PlatformLabel,
|
||||
Name = distName,
|
||||
Sha256 = Sha(distZip),
|
||||
Size = new FileInfo(distZip).Length
|
||||
};
|
||||
WriteSigned(remoteManifest, rv, signer);
|
||||
|
||||
var dlDist = Task.Run(() => LauncherUpdater.DownloadAsync(paths, updater.Remote, null))
|
||||
.GetAwaiter().GetResult();
|
||||
Console.WriteLine($"dist 目录更新: {dlDist.Message}");
|
||||
Check(dlDist.State == UpdateRunState.Ready, "仓库 dist/<系统>-<架构>/ 里的产物能找到并下载");
|
||||
// 包名来自 zip 内容(这里仍是 9.9.9 的文件),所以要断言清单版本
|
||||
Check(dlDist.Version == "9.9.10", "下载的确实是 dist 目录里声明的那个版本");
|
||||
|
||||
// 5c) 往 dist/ 里塞一个哈希不匹配的包:必须拒绝(sha256 来自已签名清单)
|
||||
File.WriteAllText(distZip, "evil payload");
|
||||
var dlEvil = Task.Run(() => LauncherUpdater.DownloadAsync(paths, updater.Remote, null))
|
||||
.GetAwaiter().GetResult();
|
||||
Check(dlEvil.State == UpdateRunState.Failed, "dist 目录里哈希不符的包被拒绝");
|
||||
|
||||
// 还原到 9.9.9,后面的篡改 / 断网用例继续用这份清单
|
||||
rv.Launcher.Version = "9.9.9";
|
||||
rv.Launcher.Packages[rid] = new RepoPackage
|
||||
{
|
||||
Url = zip,
|
||||
Sha256 = Sha(zip),
|
||||
Size = new FileInfo(zip).Length
|
||||
};
|
||||
WriteSigned(remoteManifest, rv, signer);
|
||||
|
||||
// 6) 篡改检测:改一个字节但不重新签名 -> 必须判为不可信
|
||||
var tampered = File.ReadAllText(remoteManifest).Replace("\"9.9.9\"", "\"9.9.8\"");
|
||||
var tamperResult = ManifestSignature.Verify(tampered, requireSignature: true);
|
||||
Check(tamperResult.Trust == ManifestTrust.Invalid, "被篡改的清单验签失败");
|
||||
File.WriteAllText(remoteManifest, tampered);
|
||||
var r6 = Task.Run(() => updater.RunAsync(true, null)).GetAwaiter().GetResult();
|
||||
Check(r6.Outcome == UpdateOutcome.Unavailable, "清单被篡改时拒绝更新");
|
||||
WriteSigned(remoteManifest, rv, signer);
|
||||
|
||||
// 7) 断网兜底:保留本地模型,不清空
|
||||
var offline = new UpdateService(paths, settings, new GitCodeRemote("http://127.0.0.1:1/nope"));
|
||||
var beforeCount = settings.Current.InstalledModelVersions.Count;
|
||||
var r5 = offline.RunAsync(true, null).GetAwaiter().GetResult();
|
||||
var r5 = Task.Run(() => offline.RunAsync(true, null)).GetAwaiter().GetResult();
|
||||
Check(r5.Outcome == UpdateOutcome.Unavailable &&
|
||||
settings.Current.InstalledModelVersions.Count == beforeCount &&
|
||||
Directory.Exists(Path.Combine(modelRoot, "earth-rotation")),
|
||||
@@ -195,6 +307,13 @@ internal static class Program
|
||||
return failures == 0 ? 0 : 1;
|
||||
}
|
||||
|
||||
/// <summary>序列化清单并用私钥签名(测试里模拟一次正式发布)。</summary>
|
||||
private static void WriteSigned(string path, RepoVersion version, ECDsa key)
|
||||
{
|
||||
var text = JsonSerializer.Serialize(version, Json.Options) + "\n";
|
||||
File.WriteAllText(path, ManifestSignature.SignDocument(text, key, "gc-2026-11"));
|
||||
}
|
||||
|
||||
private static void CopyTree(string src, string dst)
|
||||
{
|
||||
Directory.CreateDirectory(dst);
|
||||
@@ -212,7 +331,7 @@ internal static class Program
|
||||
var dir = new DirectoryInfo(AppContext.BaseDirectory);
|
||||
for (var i = 0; i < 10 && dir != null; i++, dir = dir.Parent)
|
||||
{
|
||||
if (File.Exists(Path.Combine(dir.FullName, "EarthModelStudio.sln"))) return dir.FullName;
|
||||
if (File.Exists(Path.Combine(dir.FullName, "GC.sln"))) return dir.FullName;
|
||||
}
|
||||
return Directory.GetCurrentDirectory();
|
||||
}
|
||||
@@ -1,110 +1,216 @@
|
||||
# Earth Model Studio
|
||||
# GC
|
||||
|
||||
天文教学模型**启动器**:管理/启动模型、启动时自动检查并下载最新版模型与启动器、设置语言与内存。
|
||||
|
||||
> **分层约定(重要)**
|
||||
> - `src/` = 启动器:扫描、下载、开窗口、显示加载进度、自检更新。**不渲染、不含任何模型内容、发布包不内置模型**。
|
||||
> - `GC/` = 启动器:扫描、下载、开窗口、显示加载进度。**不渲染、不含任何模型内容、发布包不内置模型**。
|
||||
> - `model/` = 模型的一切:**源码、编译后的 dll、场景数据、封面、语言包、共享引擎、契约**,独立分发、独立版本。
|
||||
> - 模型相关代码全部直接存在模型目录里,仓库根没有 `model-src/` / `model-sdk/` 这类旁路目录。
|
||||
> - 想加新内容 = 在 `model/<id>/` 里放模型并推送仓库,`src` 一行都不用改,客户端启动自动更新。
|
||||
> - 想加新内容 = 在 `model/<id>/` 里放模型并推送仓库,启动器一行都不用改,客户端启动自动更新。
|
||||
> - `GC-SAVEDOG/` = 更新守护进程:验签、原子替换、启动后健康检查、失败回滚。
|
||||
|
||||
- UI:C# + .NET 8(可切 .NET 10)+ Avalonia,跨平台
|
||||
- 模型加载:`AssemblyLoadContext` 加载模型自带 dll,契约与 Avalonia 走默认上下文,关窗即卸载
|
||||
- 目标平台:**macOS arm64 / Windows x64 / Windows arm64**,一条命令全部编译
|
||||
- 更新仓库:<https://gitcode.com/2509_92447106/GC>,模型目录 <https://gitcode.com/2509_92447106/GC/tree/main/model>
|
||||
- 目标平台:**macOS arm64 / Windows x64 / Windows arm64**(Linux 可自行编译,未列入发布矩阵)
|
||||
- 更新仓库:<https://gitcode.com/Morris_1/GC>,模型目录 <https://gitcode.com/Morris_1/GC/tree/main/model>
|
||||
|
||||
## 快速开始
|
||||
|
||||
```bash
|
||||
# 依赖:.NET 8 SDK(macOS 另需 Xcode Command Line Tools,用于 .icns / ditto)
|
||||
dotnet --version # 8.0.x
|
||||
./build.sh build # 三平台完整发布 -> dist/
|
||||
./build.sh run # 开发态直接运行(读仓库 model/,跳过在线替换)
|
||||
./build.sh check # 编译 + 自检 + 离屏渲染 + 产物检查
|
||||
```
|
||||
|
||||
Windows 用 `.\build.ps1`,参数相同(`build / check / models / stamp / run / test / update-test / pack-models / clean / doctor`)。
|
||||
`build.sh test` 的离屏渲染需要图形栈:Linux CI 上用 `xvfb-run ./build.sh test`。
|
||||
|
||||
## 运行目录(发布包里就长这样)
|
||||
|
||||
```
|
||||
<安装目录>/
|
||||
EarthModelStudio.exe | EarthModelStudio.app/
|
||||
GC.exe | GC.app/
|
||||
GC-SAVEDOG[.exe] 更新守护进程(与主程序同目录,macOS 在 .app/Contents/MacOS 内)
|
||||
.GC/
|
||||
settings.json 设置 + 已安装版本记录
|
||||
config/settings.json 用户设置(与缓存分开:删 cache 不会丢配置)
|
||||
model/ 启动时下载的模型
|
||||
cache/ 下载暂存 / 原子替换
|
||||
update/ 待下次启动应用的启动器更新
|
||||
update/ 待应用的启动器更新(apply-request.json + package.zip)
|
||||
```
|
||||
|
||||
**发布包不含任何模型**。首次启动联网检查后把模型下载到 `.GC/model/` 并立刻显示;
|
||||
安装目录不可写时自动退回用户数据目录。`.GC/` 可以随程序一起搬迁,也可以整个删掉重新下载。
|
||||
安装目录不可写时自动退回用户数据目录。`.GC/cache` 与 `.GC/model` 随时可删,程序会重新下载;
|
||||
`.GC/config/settings.json` 删掉等于恢复出厂设置。
|
||||
|
||||
## 自动更新
|
||||
|
||||
| 检查项 | 不是最新版时 | 生效时机 |
|
||||
| --- | --- | --- |
|
||||
| 模型 | 从 gitcode 下载到 `cache/`,校验后原子替换 `.GC/model/<id>` | **下载后立即应用**(本次启动首页就刷新) |
|
||||
| 启动器 | 下载对应平台 zip 到 `.GC/update/payload`,写 `pending.json` | **下次启动时应用**(独立脚本覆盖程序并重启) |
|
||||
| 模型 | 按文件清单下载到 `cache/`,校验哈希后原子替换 `.GC/model/<id>` | **下载后立即应用**(本次启动首页就刷新) |
|
||||
| 启动器 | 下载对应平台 zip 到 `.GC/update/`,交给 `GC-SAVEDOG` | **下次启动时应用**(重启后自动替换) |
|
||||
|
||||
- 默认更新仓库写在 `.GC/settings.json` 的 `updateRepository`:
|
||||
`https://gitcode.com/2509_92447106/GC`(也可换成自己的仓库或 `.../tree/main/model` 地址)
|
||||
- 版本来自仓库根 `version.json`(由 `./build.sh stamp` 生成):模型版本 = **模型包内容指纹**,
|
||||
所以**改了模型文件,版本号自动变**;启动器版本 = 构建版本。
|
||||
- `settings.json` 记录 `installedModelVersions` / `pendingLauncherVersion` / `lastUpdateCheck`。
|
||||
- 断网、仓库还没推 `version.json`、下载失败:**一律保留本地模型,绝不把模型库清空**,底部状态条说明原因。
|
||||
- 设置页可关闭自动更新;状态条可手动「检查更新」(忽略开关强制检查)。
|
||||
启动器更新的完整流程:
|
||||
|
||||
```
|
||||
启动器下载 zip -> 校验 sha256 -> 写 apply-request.json -> 启动 GC-SAVEDOG -> 自己退出
|
||||
GC-SAVEDOG: 二次验签 -> 检查 zip 安全性 -> 解压到 .GC/update/stage
|
||||
-> 移入安装目录(绝不覆盖已有版本)
|
||||
-> 启动新版,等 .GC/update/health.json
|
||||
-> 收到:删同平台旧版本,写 last-good.json
|
||||
-> 没收到/进程退出:删新版、重启旧版,写 state.json = rolledback
|
||||
```
|
||||
|
||||
也就是说:**新版本起不来,用户不会被卡死**。找不到 `GC-SAVEDOG` 的旧安装会退回脚本流程(过渡用)。
|
||||
|
||||
- 默认更新仓库写在 `.GC/config/settings.json` 的 `updateRepository`:
|
||||
`https://gitcode.com/Morris_1/GC`(也可换成自己的仓库或 `.../tree/main/model` 地址)
|
||||
- 断网、仓库没推 `version.json`、下载失败:**一律保留本地模型,绝不清空模型库**,底部状态条说明原因
|
||||
- 首次启动断网且本地无模型:状态条会明确提示「去下载页重试 / 手动放入 `.GC/model/`」,不会白屏干等
|
||||
- 离线教室:把仓库(含 `version.json` + `model/`)拷到 U 盘,在 `settings.json` 填
|
||||
`updateLocalRoot` 指向它,即可完全离线更新。
|
||||
- 发新版:把 `dist/GC-<rid>.zip` 上传到 Release / 仓库 `dist/`,把直链填进 `version.json`
|
||||
对应平台的 `url`(`./build.sh publish` 会生成 zip 并自动写入 `sha256` / `size`)。
|
||||
更新包只含程序文件,**不会覆盖 `.GC/` 里的模型与设置**。
|
||||
`updateLocalRoot` 指向它,即可完全离线更新(同样会验签)
|
||||
|
||||
## 安全模型
|
||||
|
||||
威胁模型很直接:**模型 dll 会被 `AssemblyLoadContext` 直接执行**,启动器更新包会替换可执行文件。
|
||||
只要仓库被入侵,攻击者就能让所有客户端跑他的代码。因此信任链是:
|
||||
|
||||
```
|
||||
内置公钥(源码)
|
||||
└─ 验证 version.json 的 ECDSA P-256 签名
|
||||
├─ 得到启动器包 sha256 → 校验下载到的 zip
|
||||
│ └─ GC-SAVEDOG 再次验签 + 复算 sha256 + 检查 zip 结构 → 原子替换
|
||||
└─ 得到每个模型的 manifestSha256 / filesSha256
|
||||
└─ 下载后复算,比对通过才安装
|
||||
└─ 加载 dll 前抽查 dll / json 哈希(.integrity.json)
|
||||
```
|
||||
|
||||
要点:
|
||||
|
||||
| 机制 | 防的是什么 | 代码位置 |
|
||||
| --- | --- | --- |
|
||||
| 清单签名(ECDSA P-256 / SHA-256) | 仓库被改、清单被替换 | `GC/src/Security/ManifestSignature.cs` |
|
||||
| 规范化 JSON(键排序、去 signature) | 「同内容不同字节」导致签名不可复现 | `GC/src/Security/CanonicalJson.cs` |
|
||||
| 包 sha256(取自已签名清单) | 下载被替换 / 传输损坏 | `GC/src/Security/ContentHash.cs` |
|
||||
| 模型 manifestSha256 / filesSha256 | 下载后、安装前被掉包 | `GC/src/Security/ModelIntegrity.cs` |
|
||||
| 加载前抽查 dll 哈希 | 本地模型文件被替换 | `GC/src/Services/ModelHost.cs` |
|
||||
| `SafeArchive`(条目数/体积/压缩比/符号链接/穿越) | zip 炸弹、zip slip、链接攻击 | `GC/src/Security/SafeArchive.cs` |
|
||||
| `GC-SAVEDOG` 独立进程 | 覆盖失败、断电、新版本起不来 | `GC-SAVEDOG/Applier.cs` |
|
||||
| 健康标记 + 回滚 | 新版启动即崩 | `GC/src/Security/StartupHealth.cs` |
|
||||
|
||||
默认策略:**清单没签名或签名不符一律拒绝更新**。
|
||||
自建私有构建可临时放开:`settings.json` 里 `requireSignedManifest: false`,
|
||||
或环境变量 `GC_ALLOW_UNSIGNED_MANIFEST=1`(只建议调试用)。
|
||||
|
||||
### 签名密钥
|
||||
|
||||
- 私钥:`.signing/gc-signing.pem`(**已在 `.gitignore`,永不入库**;请自行备份)
|
||||
- 公钥:硬编码在 `GC/src/Security/SignatureKeyring.cs`,指纹 `b41b1dd6259ea9ed`
|
||||
- 生成新密钥:`dotnet run --project GC-SAVEDOG -- keygen`
|
||||
- 轮换:把新公钥追加进 `SignatureKeyring.Keys`(保留旧公钥一个版本周期),再重新签名清单
|
||||
- 部署前核对两边公钥一致:
|
||||
`dotnet run --project GC-SAVEDOG -- verify --manifest version.json`
|
||||
|
||||
### zip 解压加固
|
||||
|
||||
更新包和模型源 zip 一律当成不可信输入:拒绝 `../`、绝对路径、盘符、UNC、符号链接;
|
||||
条目数 ≤ 20000、解压后 ≤ 2 GiB、压缩比异常(>200:1 且体积较大)直接判为 zip 炸弹。
|
||||
|
||||
## 版本与指纹
|
||||
|
||||
- **启动器版本**:`Directory.Build.props` 的 `<Version>`;`./build.sh build -version=1.0.8` 可覆盖,
|
||||
只影响启动器(程序集版本、关于页、`version.json` 的 `launcher.version`)。
|
||||
- **模型版本**:模型清单里**作者手写**的 `version`(如 `1.6`),`./build.sh stamp` 不会改它。
|
||||
客户端按字符串比较是否变化,所以改模型内容后必须手动升版本号,否则用户不会更新。
|
||||
- **`build` 字段**:模型内容的构建指纹,只用于溯源;`updatedAt` / `build` 都不参与指纹计算,
|
||||
保证「同一份内容重复构建得到同一个值」。
|
||||
- **内容哈希算法**(构建端与客户端必须一致):
|
||||
|
||||
```
|
||||
fileHash = SHA256(文件字节)
|
||||
dirHash = SHA256( 按相对路径 ordinal 升序,对每个文件拼接 "<相对路径>\0<fileHash>\n" )
|
||||
```
|
||||
|
||||
相对路径统一 `/` 分隔,跳过 `.` 开头的文件、`bin/`、`obj/`、`*.user`;
|
||||
不含时间戳、权限位、文件顺序。实现见 `GC/src/Security/ContentHash.cs`,构建端由
|
||||
`VersionStamp` 直接链接同一份源码,不会出现两套算法。
|
||||
|
||||
## 目录结构
|
||||
|
||||
```
|
||||
EarthModelStudio/
|
||||
├── EarthModelStudio.sln
|
||||
├── Directory.Build.props # 公共构建属性
|
||||
├── version.json # ★ 自动生成的版本清单(推送到仓库后才生效)
|
||||
├── build.sh / build.ps1 # 构建脚本
|
||||
├── src/ # ★ 启动器(没有渲染逻辑)
|
||||
│ └── main/dotnet/EarthModelStudio/
|
||||
│ ├── Models/ Services/ # 清单/设置/目录探测/i18n/模型库/下载/自动更新
|
||||
│ │ # UpdateService · GitCodeRemote · DirectoryRemote · LauncherUpdate
|
||||
│ ├── ViewModels/ Views/ # 主页、下载、设置、模型窗口壳、启动更新状态条
|
||||
│ └── Assets/i18n/ # 启动器界面语言包
|
||||
├── src/test/dotnet/…Tests/ # 离屏校验 + --update-test 离线更新链路验证
|
||||
Repository/
|
||||
├── GC.sln
|
||||
├── Directory.Build.props # 公共构建属性(版本号在这里)
|
||||
├── version.json # ★ 自动生成并签名的版本清单(推送到仓库后才生效)
|
||||
├── build.sh / build.ps1 # 构建脚本(实际实现在 buildsh/ 与 buildps1/)
|
||||
├── GC/ # 启动器
|
||||
│ └── src/
|
||||
│ ├── GC.Core.csproj
|
||||
│ ├── Security/ # ★ 验签、哈希、安全解压、完整性、健康标记
|
||||
│ ├── Models/ Services/
|
||||
│ ├── ViewModels/ Views/
|
||||
│ ├── Assets/i18n/ # 界面语言包
|
||||
│ └── test/dotnet/GC.Tests/ # 离屏校验 + --update-test 离线更新链路验证
|
||||
├── GC-BOOT/ # 轻量启动入口
|
||||
├── GC-DOWNLOAD/ # 源仓库 / 模型 / 启动器下载更新
|
||||
├── GC-DRAW/PlayerWindow.cs # 模型窗口宿主;绘制由模型提供
|
||||
├── GC-SAVEDOG/ # ★ 更新守护进程(apply / verify / keygen / sign / status)
|
||||
├── model/ # ★ 模型的一切
|
||||
│ ├── version.json # 与根 version.json 相同(便于按 model/ 地址读取)
|
||||
│ ├── _sdk/EarthModelStudio.ModelSdk/
|
||||
│ ├── _engine/
|
||||
│ │ ├── src/ # CelestialView / PlanetTexture / EarthModelView …
|
||||
│ │ ├── PreviewGen/ # 用模型渲染器生成封面
|
||||
│ │ └── VersionStamp/ # 按内容指纹自动打版本、生成 version.json
|
||||
│ ├── earth-rotation/
|
||||
│ │ ├── earth-rotation.json
|
||||
│ │ ├── src/ # 本模型源码
|
||||
│ │ └── earth-rotation.model/ # dll + scene.json/land.json + preview.png + i18n
|
||||
│ ├── version.json # 与根 version.json 完全相同(同一份签名)
|
||||
│ ├── _sdk/GC.ModelSdk/
|
||||
│ ├── _engine/{src,PreviewGen,VersionStamp}/
|
||||
│ ├── earth-rotation/{earth-rotation.json,src/,earth-rotation.model/}
|
||||
│ └── earth-revolution/
|
||||
└── dist/ # 发布产物(只有启动器 + .GC 骨架)
|
||||
├── dist/ # 发布产物(.gitignore,只通过 Release 分发)
|
||||
└── .signing/ # 签名私钥(.gitignore,绝不入库)
|
||||
```
|
||||
|
||||
模型库位置:`EMS_MODELS` 覆盖 → 开发态仓库根 `model/` → **发布态 `<可执行文件>/.GC/model/`**。
|
||||
|
||||
`dist/` 不进仓库:二进制放 Git 会让 clone 变慢,也会让「仓库被改」的爆炸半径变大。
|
||||
发布有两种方式,`version.json` 里两条路都写清楚了:
|
||||
|
||||
| 方式 | 清单字段 | 说明 |
|
||||
| --- | --- | --- |
|
||||
| Release 附件(推荐) | `url` | `.../releases/download/v<版本>/GC-<版本>-<系统>-<架构>.zip` |
|
||||
| 仓库编译产物 | `path` / `dir` / `name` | `dist/<系统>-<架构>/GC-<版本>-<系统>-<架构>.zip` |
|
||||
|
||||
下载端按 `url` → `path` → `dist/<系统>-<架构>/` 目录扫描的顺序尝试,
|
||||
**每个候选都必须与清单里的 `sha256` 一致**(`sha256` 由签名保护),
|
||||
所以「多发一个地方」不会放宽校验,只是让「只提交产物、不发 Release」也能更新。
|
||||
清单缺 `sha256` 的平台会被直接跳过,不再退化成「只校验非空」。
|
||||
|
||||
## 构建与运行
|
||||
|
||||
```bash
|
||||
./build.sh build # 编译整个解决方案
|
||||
./build.sh models # 编译模型 dll + 生成封面 + 自动打版本
|
||||
./build.sh stamp # 只重新生成 version.json 与模型版本
|
||||
./build.sh run # 运行
|
||||
./build.sh test # 离屏校验:页面 + 真实加载模型窗口截图
|
||||
./build.sh update-test # 离线验证自动更新链路(不联网、不替换程序)
|
||||
./build.sh publish # 三平台发布(不内置模型)+ 建 .GC 骨架 + 生成更新包
|
||||
./build.sh pack-models # 单独打包模型 -> dist/models-<version>.zip
|
||||
./build.sh pack-launcher # 生成三个平台的启动器更新包 zip
|
||||
./build.sh clean
|
||||
./build.sh build # 三平台完整发布:启动器 + SAVEDOG + 运行骨架 + 更新包 ZIP
|
||||
./build.sh check # 编译、自检、离屏渲染及发布 ZIP 完整性检查
|
||||
./build.sh models # 编译模型 dll、生成封面、更新并签名版本清单
|
||||
./build.sh stamp # 只重新生成 + 签名 version.json
|
||||
./build.sh run # Debug 运行启动器
|
||||
./build.sh test # 离屏校验,截图写入 build/screenshots/
|
||||
./build.sh update-test # 离线验证自动更新链路(验签 / 立即生效 / 篡改拒绝 / 断网兜底)
|
||||
./build.sh pack-models # 编译模型并打包 dist/models-<版本>.zip
|
||||
./build.sh pack-launcher # 把已有平台发布目录打成启动器更新 ZIP
|
||||
./build.sh doctor # dotnet 环境信息
|
||||
./build.sh dist # 列出 dist/ 产物
|
||||
./build.sh clean # 清理 build/ 与 dist/
|
||||
```
|
||||
|
||||
Windows 用 `.\build.ps1`(参数相同)。
|
||||
|
||||
| 产物 | 平台 |
|
||||
| --- | --- |
|
||||
| `dist/mac-arm64/EarthModelStudio.app` | macOS Apple Silicon |
|
||||
| `dist/win-x64/EarthModelStudio.exe` | Windows x64 |
|
||||
| `dist/win-arm64/EarthModelStudio.exe` | Windows on ARM |
|
||||
| `dist/mac-arm64/GC-<版本>-mac-arm64.zip` | macOS Apple Silicon 应用包(含 GC-SAVEDOG) |
|
||||
| `dist/win-amd64/GC-<版本>-win-amd64.zip` | Windows x64 单文件启动器 + `GC-SAVEDOG.exe` |
|
||||
| `dist/win-arm64/GC-<版本>-win-arm64.zip` | Windows on ARM 同上 |
|
||||
|
||||
均为自包含单文件启动器,**发布包内不含模型**。改完模型:
|
||||
`./build.sh models` → 把 `version.json` 和 `model/` 推送到 gitcode → 客户端下次启动自动更新。
|
||||
平台目录就是「该平台的编译产物目录」:打包完成后只留最终 zip(原始 `.app` / `.exe`
|
||||
会被挪到 `build/trash/`,下次构建时移出,不做递归删除)。
|
||||
|
||||
发新版:`./build.sh build -version=1.0.8` → 把 `dist/<平台>/GC-1.0.8-<平台>.zip`
|
||||
上传到 gitcode Release(tag `v1.0.8`),**或者**直接提交/上传到仓库的
|
||||
`dist/<平台>/` 目录 → 提交并推送 `version.json` / `model/version.json`。
|
||||
两种都能被客户端识别,客户端下次启动就会看到更新。
|
||||
|
||||
## 模型契约
|
||||
|
||||
@@ -134,8 +240,25 @@ public interface IModelContext
|
||||
}
|
||||
```
|
||||
|
||||
启动器先弹进度窗,在后台调用 `Prepare`(模型用 `ReportProgress` 汇报真实进度),
|
||||
再在 UI 线程调用 `CreateView`,把返回的控件直接铺满窗口 —— 除此之外什么都不做。
|
||||
**线程约定**
|
||||
|
||||
| 成员 | 允许的线程 | 说明 |
|
||||
| --- | --- | --- |
|
||||
| `Prepare` | 后台线程(调用一次) | 可耗时;用 `ReportProgress` 汇报真实进度;此时**不要**创建控件 |
|
||||
| `CreateView` | UI 线程(`Prepare` 之后调用一次) | 只在这里创建/操作 Avalonia 控件 |
|
||||
| `ReportProgress` / `Log` | 任意线程 | 线程安全,内部自行封送到 UI |
|
||||
| `RequestClose` | 任意线程 | 线程安全,等价于点窗口关闭按钮 |
|
||||
| `Dispose` | UI 线程 | 释放后不要再调用 `Log` / `ReportProgress` |
|
||||
|
||||
**契约版本协商**
|
||||
|
||||
- `IModelFactory.ApiVersion` 与启动器支持的版本(当前 `1`)必须相等,否则拒绝加载并提示更新启动器。
|
||||
- 模型清单可写 `minAppVersion`(如 `"1.0.8"`):启动器版本更低时直接拒绝,并给出明确提示。
|
||||
- 提升契约版本时必须保留旧接口的适配层,或在启动器里明确「最低启动器版本」,避免老客户端加载新模型后崩溃。
|
||||
|
||||
**卸载注意**:关窗即 `Unload()` 收集式 AssemblyLoadContext。只要有静态字段、未解绑的事件、
|
||||
或缓存里还拿着模型内的类型/控件,程序集就回收不掉(内存持续增长)。
|
||||
模型作者应避免静态持有 `Control` / `IModelContext`,并在 `Dispose` 里解绑事件。
|
||||
|
||||
详细清单字段、数据格式、封面生成见 [`model/README.md`](model/README.md)。
|
||||
|
||||
@@ -143,7 +266,7 @@ public interface IModelContext
|
||||
|
||||
- 启动模型 → **带进度条的加载窗**(读取数据 → 生成地表纹理 → 构建界面,真实进度)→ 新开独立窗口
|
||||
- 主界面保持原页面,可同时开多个模型窗口;关窗即卸载模型程序集
|
||||
- 启动器快捷键 `Esc` 关闭、`F11` 全屏;模型窗口内的快捷键由模型自己定义
|
||||
- 所有由启动器打开的窗口(模型窗、加载窗、确认框、更新窗)都是 16px 圆角
|
||||
|
||||
## 地球模型(model/_engine + model/<id>/src)
|
||||
|
||||
@@ -155,20 +278,12 @@ public interface IModelContext
|
||||
**没有节气定位**(节气属于公转)
|
||||
- **公转**:太阳—轨道—地球全景、地轴方向空间固定、二分二至标记与一键定格、HUD(角度 / 直射纬度 / 日期)
|
||||
- **触控一体机**:双指捏合缩放(跟手)、滚轮缩放、画布左下角大号 + / − / 复位按钮;
|
||||
所有工具栏按钮 ≥ 40px。单指或鼠标拖动可直接转动地球,**拖动时画面定格但视角俯仰与轨道平面始终不变**,
|
||||
俯视角只由「俯视」按钮显式切换
|
||||
所有工具栏按钮 ≥ 40px。单指或鼠标拖动可直接转动地球,**拖动时画面定格但视角俯仰与轨道平面始终不变**
|
||||
- **课堂演示**:点二分二至自动暂停定格并显示节气、教材日期、直射纬度与现象说明;
|
||||
右侧课堂卡含可放大观察到的「地球特写」;`◀ ▶` 步进 5°、教学要点点击自动定格定位;
|
||||
快捷键 `空格` 播放/暂停、`← →` 步进、`1–4` 二分二至、`F` 全屏、`+ -` 缩放、`0` 复位视角
|
||||
- 节气日期、直射纬度、现象说明、教学要点全部写在 `scene.json` 里;夸张倾角只改示意图形,不改教学读数
|
||||
|
||||
## 模型源(手动导入)
|
||||
|
||||
除了启动时自动更新,「下载」页还支持手动导入普通 git 仓库:
|
||||
**仓库根目录下的 `model/` 文件夹即模型列表**。支持 GitHub / GitLab / Gitee(zip 归档,
|
||||
失败回退 `git clone --depth 1`)、zip 直链、本地目录。导入后缓存在 `数据目录/cache/sources/<id>`。
|
||||
|
||||
## 启动时运行内存分配
|
||||
|
||||
设置页的「启动时运行内存分配」类似启动器的 -Xmx:启动器把这份预算通过 `IModelContext.MemoryBudgetMb`
|
||||
设置页的「启动时运行内存分配」类似启动器的 `-Xmx`:启动器把这份预算通过 `IModelContext.MemoryBudgetMb`
|
||||
交给模型,具体怎么用(掩膜分辨率、缓存)由模型自己决定。
|
||||
@@ -0,0 +1,78 @@
|
||||
# GC v1.0.6
|
||||
|
||||
## 新模型:等高线地形图
|
||||
|
||||
依据人教版七年级上册「地形图的判读」制作,把课本最难讲清的一件事——**立体地形如何转成平面等高线图**——变成可交互的双图联动。
|
||||
|
||||
- **左右双图联动**:左边是三维地形块(斜视图),右边是等比例的分层设色等高线图。鼠标移到任一侧,两侧同步标出该点位置、海拔、相对高度和地形部位。
|
||||
- **五种地形部位判读**:山峰、山脊、山谷、鞍部、陡崖。鼠标停在哪里,底部就实时显示该处属于哪种部位,并给出对应颜色。
|
||||
- **等高线自动生成**:Marching Squares 算法从 192×192 高度场实时提取,等高距 100 m,共 14 条;每 5 条加粗为计曲线并标注海拔。
|
||||
- **分层设色**:绿 → 黄绿 → 土黄 → 棕 → 雪白,与课本配色一致。
|
||||
- **判读要点面板**:右侧列出五种部位的特征(如「山脊:等高线凸向低处,脊线是分水线」)和四条核心规则(等高距、疏密与坡度、计曲线、海拔与相对高度)。
|
||||
- 地形本身包含主峰、次峰(之间形成鞍部)、两条山脊、一条河谷、一侧陡坡、一侧缓坡和一处陡崖,海拔 0~1322 m。
|
||||
|
||||
## 更新系统:双源支持
|
||||
|
||||
启动器现在同时对接 **Xhmcl** 和 **GitCode** 两个仓库(同一份内容的镜像)。
|
||||
|
||||
- **自动测速选源**:检查更新与下载前并发探测两边的 `version.json` 响应时间,自动选用更快的那一个。结果缓存 3 分钟,不会每次都测。
|
||||
- **Release 交叉检查**:两个源的 Release 都会查询,取版本号最高且包含当前平台发布包的那个。某个源没发 Release 时自动跳到另一个,不影响使用。
|
||||
- **版本号优先于发布时间**:Release 列表按版本号数值比较(`1.0.10 > 1.0.9`),不受发布时间顺序影响。草稿状态(draft)的 Release 不计入。
|
||||
- **模型与启动器分开取**:模型清单始终读仓库里的 `version.json`(模型不需要发 Release),启动器版本只认 Release。这样即使某个源没发 Release,模型仍能正常更新。
|
||||
- **同版本比对指纹**:远端版本与本地相同时,下载对应平台的发布包比对 sha256。一致则视为最新;不一致说明是自行编译的构建,不打扰用户。
|
||||
- **修复版本读取**:此前 `Assembly.GetEntryAssembly()` 在某些宿主下会返回 `1.0.0`,导致明明是最新版却一直提示更新;现在改为读取本程序集版本。
|
||||
|
||||
## 下载页面
|
||||
|
||||
- **取消自定义模型源**:不再接受任意仓库地址,只保留 Xhmcl 与 GitCode 两个内置源,避免来源不明的模型。
|
||||
- **一键测速切换**:原来的「导入模型源」输入框改为「测速并切换到最快源」按钮,点击后自动比对并切到更快的那个源。
|
||||
- **下载与更新统一**:下载页面和启动更新现在共用同一个源选择器,不再出现两处下载速度不一致的情况。
|
||||
|
||||
## 窗口标题栏
|
||||
|
||||
- **去掉彩色圆圈**:最小化 / 最大化 / 关闭三个按钮改回纯矢量图标,不再有黄、绿、红圆底。
|
||||
- **主窗口补齐最大化**:此前主窗口只有最小化和关闭,现在补上最大化,并支持双击标题栏切换。
|
||||
- **图标随状态切换**:最大化后图标变为两个重叠小方框(还原),还原后变回单方框。
|
||||
- **圆角始终保留**:任何窗口状态下都保持 16px 圆角,不再最大化后变成直角贴边。
|
||||
- **尺寸自适应**:标题栏文字、按钮、图标随窗口宽度同比缩放(0.85–1.9 倍),全屏时不会小得点不中。
|
||||
|
||||
## 缩放动画
|
||||
|
||||
- **地理模型**:此前滚轮缩放直接跳变,现在改为指数逼近的平滑动画(60Hz),差值小于阈值自动停下,不空转耗 CPU。
|
||||
- **地球模型**:本就带平滑缩放,保持原样。
|
||||
|
||||
## 关于页面
|
||||
|
||||
- 新增「**感谢**」卡片,样式与「开发者」卡片一致:**地理洪老师 — 地理学科内容指导**。
|
||||
|
||||
## 开发者工具
|
||||
|
||||
新增 `git.sh` / `git.bat` 与 `gitshell/` 目录,把仓库操作从手动命令变成可交互流程:
|
||||
|
||||
- **`./git.sh autogit`**:交互式提交。依次询问①选哪个仓库(支持多选、可选全部、可连续输入多个新地址)②确认仓库地址③确认提交分支④输入提交信息⑤最终确认,然后逐个推送并汇总结果。
|
||||
- **自动排除构建产物**:`dist/` `build/` `bin/` `obj/` `.GC/` 无论是否被跟踪都不会提交,历史上被跟踪的会先从索引移出(本地文件保留)。
|
||||
- **`./git.sh status`**:一眼看清当前分支、改动数量、最近提交,以及每个远程仓库的领先/落后情况。
|
||||
|
||||
## 模型版本
|
||||
|
||||
| 模型 | 版本 |
|
||||
| --- | --- |
|
||||
| 等高线地形图 contour-map | **1.0**(新) |
|
||||
| 地球地理 earth-geography | 1.8 |
|
||||
| 地球自转 earth-rotation | 1.6 |
|
||||
| 地球公转 earth-revolution | 1.6 |
|
||||
| 比例尺计算器 scale-calculator | 1.5 |
|
||||
|
||||
---
|
||||
|
||||
**安装包**
|
||||
|
||||
| 平台 | 文件 |
|
||||
| --- | --- |
|
||||
| Windows x64 | `GC-win-x64.zip` |
|
||||
| Windows ARM64 | `GC-win-arm64.zip` |
|
||||
| macOS Apple Silicon | `GC-osx-arm64.zip` |
|
||||
| macOS Intel | `GC-osx-x64.zip` |
|
||||
| Linux x64 | `GC-linux-x64.zip` |
|
||||
|
||||
下载后解压即可运行。模型会在首次启动时自动下载到程序目录旁的 `.GC/model/`。
|
||||
@@ -1,220 +1,8 @@
|
||||
# ---------------------------------------------------------------------------
|
||||
# Earth Model Studio 构建脚本(Windows PowerShell)
|
||||
#
|
||||
# .\build.ps1 编译
|
||||
# .\build.ps1 run 运行
|
||||
# .\build.ps1 test 离屏渲染校验
|
||||
# .\build.ps1 models 编译模型 dll + 生成封面 + 自动打版本
|
||||
# .\build.ps1 stamp 只重新生成 version.json 与模型版本
|
||||
# .\build.ps1 publish 编译三个平台启动器(不内置模型)+ 建立 .GC 运行目录
|
||||
# .\build.ps1 pack-models 单独打包模型数据(含 version.json)
|
||||
# .\build.ps1 pack-launcher 生成三个平台的启动器更新包 zip
|
||||
# .\build.ps1 update-test 离线验证自动更新链路
|
||||
# .\build.ps1 clean 清理
|
||||
#
|
||||
# 分层:src\ 只是启动器;模型全部在 model\;**发布包不内置模型**。
|
||||
#
|
||||
# 运行目录(发布包里就长这样):
|
||||
# <安装目录>\
|
||||
# EarthModelStudio.exe
|
||||
# .GC\settings.json
|
||||
# .GC\model\ 启动时从 gitcode 下载的模型
|
||||
# .GC\cache\ 下载暂存
|
||||
# .GC\update\ 待下次启动应用的启动器更新
|
||||
# ---------------------------------------------------------------------------
|
||||
param(
|
||||
[Parameter(Position = 0)]
|
||||
[ValidateSet('build', 'run', 'test', 'publish', 'models', 'stamp', 'pack-models',
|
||||
'pack-launcher', 'update-test', 'bundle', 'clean', 'doctor')]
|
||||
[string]$Task = 'build'
|
||||
)
|
||||
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$Root = $PSScriptRoot
|
||||
Set-Location $Root
|
||||
|
||||
# Avalonia 遥测任务在只读用户目录/CI/沙箱会因写日志失败而中断编译(MSB4018)。
|
||||
# 官方 opt-out;Directory.Build.targets 里还有一层项目内的兜底。
|
||||
$env:AVALONIA_TELEMETRY_OPTOUT = '1'
|
||||
|
||||
$AppProj = 'src/main/dotnet/EarthModelStudio/EarthModelStudio.csproj'
|
||||
$TestProj = 'src/test/dotnet/EarthModelStudio.Tests/EarthModelStudio.Tests.csproj'
|
||||
$PreviewProj = 'model/_engine/PreviewGen/PreviewGen.csproj'
|
||||
$StampProj = 'model/_engine/VersionStamp/VersionStamp.csproj'
|
||||
$Sln = 'EarthModelStudio.sln'
|
||||
$Version = '1.0.0'
|
||||
|
||||
function Stamp-Versions {
|
||||
Write-Host '==> 自动计算模型版本并生成 version.json'
|
||||
dotnet run --project $StampProj -c Release -- $Root $Version
|
||||
try {
|
||||
& (Join-Path $PSScriptRoot 'buildps1/build.ps1') @args
|
||||
exit 0
|
||||
}
|
||||
|
||||
function Build-Models {
|
||||
Write-Host '==> 编译模型功能程序集(源码就在各模型目录的 src\ 里)'
|
||||
Get-ChildItem "$Root/model" -Directory | ForEach-Object {
|
||||
$id = $_.Name
|
||||
$src = Join-Path $_.FullName 'src'
|
||||
if (-not (Test-Path $src)) { return }
|
||||
$proj = Get-ChildItem $src -Filter *.csproj | Select-Object -First 1
|
||||
if ($null -eq $proj) { return }
|
||||
dotnet build $proj.FullName -c Release
|
||||
$data = Join-Path $_.FullName "$id.model"
|
||||
if (Test-Path $data) {
|
||||
Get-ChildItem (Join-Path $src 'bin/Release/net8.0') -Filter *.dll | ForEach-Object {
|
||||
if ($_.Name -eq 'EarthModelStudio.ModelSdk.dll') { return }
|
||||
Copy-Item -Force $_.FullName $data
|
||||
Write-Host " -> model/$id/$id.model/$($_.Name)"
|
||||
}
|
||||
}
|
||||
}
|
||||
Write-Host '==> 用模型自己的渲染器生成封面'
|
||||
dotnet run --project $PreviewProj -c Release -- $Root
|
||||
Stamp-Versions
|
||||
}
|
||||
|
||||
# 发布目录只放启动器 + 空的 .GC 运行骨架,绝不放模型
|
||||
function Prepare-RuntimeLayout([string]$RelDir) {
|
||||
$dest = "$Root/$RelDir"
|
||||
if (-not (Test-Path $dest)) { return }
|
||||
foreach ($old in @("$dest/model", "$dest/examples")) {
|
||||
if (Test-Path $old) { Remove-Item -Recurse -Force $old }
|
||||
}
|
||||
foreach ($dir in @("$dest/.GC/model", "$dest/.GC/cache", "$dest/.GC/update")) {
|
||||
New-Item -ItemType Directory -Force -Path $dir | Out-Null
|
||||
}
|
||||
$readme = @'
|
||||
模型库目录(.GC/model/)
|
||||
启动时程序会读取 gitcode 仓库的 version.json,把最新版模型下载到这里。
|
||||
离线使用也可以手动放入 <模型id>/<模型id>.json + <模型id>/<模型id>.model/。
|
||||
|
||||
运行目录:
|
||||
<可执行文件>
|
||||
.GC/settings.json
|
||||
.GC/model/ 本目录(下载的模型)
|
||||
.GC/cache/ 下载暂存
|
||||
.GC/update/ 待下次启动应用的启动器更新
|
||||
'@
|
||||
Set-Content -Path "$dest/.GC/model/README.txt" -Value $readme -Encoding UTF8
|
||||
|
||||
$settingsPath = "$dest/.GC/settings.json"
|
||||
if (-not (Test-Path $settingsPath)) {
|
||||
$json = @'
|
||||
{
|
||||
"language": "auto",
|
||||
"theme": "light",
|
||||
"renderFps": 30,
|
||||
"memoryMb": 2048,
|
||||
"autoUpdateOnStartup": true,
|
||||
"updateRepository": "https://gitcode.com/2509_92447106/GC",
|
||||
"updateManifestUrl": "",
|
||||
"updateLocalRoot": "",
|
||||
"installedModelVersions": {},
|
||||
"launcherVersion": "",
|
||||
"pendingLauncherVersion": "",
|
||||
"lastUpdateCheck": "",
|
||||
"sources": [],
|
||||
"recentModels": []
|
||||
}
|
||||
'@
|
||||
Set-Content -Path $settingsPath -Value $json -Encoding UTF8
|
||||
}
|
||||
Write-Host " 运行目录 -> $RelDir/.GC (settings.json + model/ + cache/ + update/)"
|
||||
}
|
||||
|
||||
function Publish-Rid([string]$Rid, [string]$OutDir) {
|
||||
Write-Host "==> 编译 $Rid -> $OutDir"
|
||||
dotnet publish $AppProj -c Release -r $Rid --self-contained true `
|
||||
-p:Version=$Version -p:DebugType=none -p:PublishSingleFile=true `
|
||||
-p:IncludeNativeLibrariesForSelfExtract=true -p:PublishTrimmed=false -o "$Root/$OutDir"
|
||||
foreach ($old in @("$Root/$OutDir/model", "$Root/$OutDir/examples")) {
|
||||
if (Test-Path $old) { Remove-Item -Recurse -Force $old }
|
||||
}
|
||||
}
|
||||
|
||||
function Pack-Models {
|
||||
New-Item -ItemType Directory -Force -Path "$Root/dist" | Out-Null
|
||||
$zip = "$Root/dist/models-$Version.zip"
|
||||
if (Test-Path $zip) { Remove-Item -Force $zip }
|
||||
Write-Host "==> 打包模型数据 -> dist/models-$Version.zip"
|
||||
$stage = Join-Path $env:TEMP "ems-models-stage"
|
||||
if (Test-Path $stage) { Remove-Item -Recurse -Force $stage }
|
||||
New-Item -ItemType Directory -Force -Path $stage | Out-Null
|
||||
Get-ChildItem "$Root/model" -Recurse -File | Where-Object {
|
||||
$_.FullName -notmatch '\\(bin|obj)\\' -and $_.Extension -ne '.user'
|
||||
} | ForEach-Object {
|
||||
$rel = $_.FullName.Substring("$Root/model".Length + 1)
|
||||
$dest = Join-Path $stage $rel
|
||||
New-Item -ItemType Directory -Force -Path (Split-Path $dest) | Out-Null
|
||||
Copy-Item -Force $_.FullName $dest
|
||||
}
|
||||
Compress-Archive -Path "$stage/*" -DestinationPath $zip -Force
|
||||
Remove-Item -Recurse -Force $stage
|
||||
}
|
||||
|
||||
# 启动器更新包:只包含程序文件,排除 .GC(否则会覆盖用户模型与设置)
|
||||
function Pack-Launcher {
|
||||
Write-Host '==> 生成启动器更新包(不含 .GC)'
|
||||
$targets = @{
|
||||
'GC-win-x64.zip' = "$Root/dist/win-x64"
|
||||
'GC-win-arm64.zip' = "$Root/dist/win-arm64"
|
||||
'GC-osx-arm64.zip' = "$Root/dist/mac-arm64/EarthModelStudio.app/Contents/MacOS"
|
||||
}
|
||||
if (-not (Test-Path $targets['GC-osx-arm64.zip'])) {
|
||||
$targets['GC-osx-arm64.zip'] = "$Root/dist/mac-arm64"
|
||||
}
|
||||
foreach ($name in $targets.Keys) {
|
||||
$src = $targets[$name]
|
||||
if (-not (Test-Path $src)) { continue }
|
||||
$stage = Join-Path $env:TEMP ("ems-launcher-" + [IO.Path]::GetFileNameWithoutExtension($name))
|
||||
if (Test-Path $stage) { Remove-Item -Recurse -Force $stage }
|
||||
New-Item -ItemType Directory -Force -Path $stage | Out-Null
|
||||
Get-ChildItem $src -Recurse -File | Where-Object {
|
||||
$_.FullName -notmatch '\\\.GC\\' -and $_.Name -ne '.DS_Store'
|
||||
} | ForEach-Object {
|
||||
$rel = $_.FullName.Substring($src.Length).TrimStart('\', '/')
|
||||
$dest = Join-Path $stage $rel
|
||||
New-Item -ItemType Directory -Force -Path (Split-Path $dest) | Out-Null
|
||||
Copy-Item -Force $_.FullName $dest
|
||||
}
|
||||
$zip = "$Root/dist/$name"
|
||||
if (Test-Path $zip) { Remove-Item -Force $zip }
|
||||
Compress-Archive -Path "$stage/*" -DestinationPath $zip -Force
|
||||
Remove-Item -Recurse -Force $stage
|
||||
}
|
||||
Stamp-Versions
|
||||
Get-ChildItem "$Root/dist/GC-*.zip" | Select-Object Name, Length
|
||||
}
|
||||
|
||||
switch ($Task) {
|
||||
'build' { dotnet build $Sln -c Debug }
|
||||
'run' { dotnet run --project $AppProj -c Debug }
|
||||
'test' { dotnet run --project $TestProj -c Debug -- "$Root/build/screenshots" }
|
||||
'publish' {
|
||||
New-Item -ItemType Directory -Force -Path "$Root/dist" | Out-Null
|
||||
Stamp-Versions
|
||||
Publish-Rid 'osx-arm64' 'dist/mac-arm64'
|
||||
Publish-Rid 'win-x64' 'dist/win-x64'
|
||||
Publish-Rid 'win-arm64' 'dist/win-arm64'
|
||||
Prepare-RuntimeLayout 'dist/win-x64'
|
||||
Prepare-RuntimeLayout 'dist/win-arm64'
|
||||
Prepare-RuntimeLayout 'dist/mac-arm64'
|
||||
Pack-Launcher
|
||||
Write-Host '==> 三个平台编译完成(发布包不含模型,首次启动自动下载),见 dist\' -ForegroundColor Green
|
||||
Write-Host ' 把 version.json / model/ 推送到 gitcode,启动器就会自动检查更新'
|
||||
}
|
||||
'models' { Build-Models }
|
||||
'stamp' { Stamp-Versions }
|
||||
'bundle' { Write-Host '已弃用:发布包不再内置模型。请改用 .\build.ps1 stamp 与 gitcode 自动更新。' }
|
||||
'pack-models' {
|
||||
Build-Models
|
||||
Pack-Models
|
||||
}
|
||||
'pack-launcher' { Pack-Launcher }
|
||||
'update-test' { dotnet run --project $TestProj -c Debug -- '--update-test' $Root }
|
||||
'clean' {
|
||||
Remove-Item -Recurse -Force "$Root/build", "$Root/dist" -ErrorAction SilentlyContinue
|
||||
Get-ChildItem "$Root/src" -Recurse -Directory -Include bin, obj |
|
||||
Remove-Item -Recurse -Force -ErrorAction SilentlyContinue
|
||||
}
|
||||
'doctor' { dotnet --info }
|
||||
catch {
|
||||
[Console]::Error.WriteLine($_)
|
||||
exit 1
|
||||
}
|
||||
@@ -1,251 +1,65 @@
|
||||
#!/bin/sh
|
||||
# ---------------------------------------------------------------------------
|
||||
# Earth Model Studio 构建脚本(macOS / Linux)
|
||||
# GC 构建入口(薄封装)
|
||||
#
|
||||
# ./build.sh build 编译(Debug)
|
||||
# ./build.sh run 本机运行
|
||||
# ./build.sh test 离屏渲染校验,截图输出到 build/screenshots
|
||||
# ./build.sh models 编译模型 dll + 生成封面 + 自动打版本
|
||||
# ./build.sh stamp 只重新生成 version.json 与模型版本
|
||||
# ./build.sh publish 编译三个平台启动器(不内置模型)+ 建立 .GC 运行目录
|
||||
# ./build.sh pack-models 单独打包模型数据(含 version.json)
|
||||
# ./build.sh pack-launcher 生成三个平台的启动器更新包 zip
|
||||
# ./build.sh update-test 离线验证自动更新链路
|
||||
# ./build.sh build 完整发布(原 publish),带 apt 风格进度条
|
||||
# ./build.sh check 验证:编译 + 自检 + 离屏渲染 + 产物
|
||||
# ./build.sh models 编译模型 dll + 封面 + 版本戳
|
||||
# ./build.sh stamp 重新生成 version.json
|
||||
# ./build.sh run / test / update-test / pack-models / pack-launcher
|
||||
# ./build.sh clean 清理
|
||||
# ./build.sh doctor dotnet 信息
|
||||
# ./build.sh dist 列出产物
|
||||
#
|
||||
# 分层:src/ 只是启动器;模型全部在 model/;**发布包不内置模型**。
|
||||
#
|
||||
# 运行目录(发布包里就长这样):
|
||||
# <安装目录>/
|
||||
# EarthModelStudio(.exe | .app/...)
|
||||
# .GC/
|
||||
# settings.json 设置与已安装版本
|
||||
# model/ 启动时从 gitcode 下载的模型
|
||||
# cache/ 下载暂存
|
||||
# update/ 待下次启动应用的启动器更新
|
||||
# 实际代码都在 buildsh/ 里,本文件只负责加载模块与分发。
|
||||
# ---------------------------------------------------------------------------
|
||||
set -eu
|
||||
|
||||
# Avalonia 遥测任务在只读用户目录/CI/沙箱会因写日志失败而中断编译(MSB4018)。
|
||||
# 官方 opt-out;Directory.Build.targets 里还有一层项目内的兜底。
|
||||
# Avalonia 遥测任务在只读用户目录/CI/沙箱会因写日志失败中断编译(MSB4018)
|
||||
export AVALONIA_TELEMETRY_OPTOUT=1
|
||||
|
||||
ROOT_DIR=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
|
||||
cd "$ROOT_DIR"
|
||||
|
||||
APP_PROJ="src/main/dotnet/EarthModelStudio/EarthModelStudio.csproj"
|
||||
APP_PROJ="GC-BOOT/GC-BOOT.csproj"
|
||||
SAVEDOG_PROJ="GC-SAVEDOG/GC-SAVEDOG.csproj"
|
||||
PREVIEW_PROJ="model/_engine/PreviewGen/PreviewGen.csproj"
|
||||
STAMP_PROJ="model/_engine/VersionStamp/VersionStamp.csproj"
|
||||
TEST_PROJ="src/test/dotnet/EarthModelStudio.Tests/EarthModelStudio.Tests.csproj"
|
||||
SLN="EarthModelStudio.sln"
|
||||
VERSION="1.0.0"
|
||||
TEST_PROJ="GC/src/test/dotnet/GC.Tests/GC.Tests.csproj"
|
||||
SLN="GC.sln"
|
||||
VERSION=$(sed -n 's/.*<Version>\(.*\)<\/Version>.*/\1/p' Directory.Build.props | head -1)
|
||||
[ -n "$VERSION" ] || VERSION="1.0.0"
|
||||
|
||||
TASK="${1:-build}"
|
||||
shift 2>/dev/null || true
|
||||
|
||||
# 按模型包内容指纹自动写回 <id>.json 的 version,并生成 version.json
|
||||
stamp_versions() {
|
||||
echo "==> 自动计算模型版本并生成 version.json"
|
||||
dotnet run --project "$STAMP_PROJ" -c Release -- "$ROOT_DIR" "$VERSION"
|
||||
}
|
||||
|
||||
# 编译模型自己的功能程序集,并把 dll / 封面直接写进模型包
|
||||
build_models() {
|
||||
echo "==> 编译模型功能程序集(源码就在各模型目录的 src/ 里)"
|
||||
for DIR in "$ROOT_DIR"/model/*/; do
|
||||
ID=$(basename "$DIR")
|
||||
[ -d "$DIR/src" ] || continue
|
||||
PROJ=$(ls "$DIR"src/*.csproj 2>/dev/null | head -1)
|
||||
[ -n "$PROJ" ] || continue
|
||||
dotnet build "$PROJ" -c Release
|
||||
if [ -d "$DIR$ID.model" ]; then
|
||||
for DLL in "$DIR"src/bin/Release/net8.0/*.dll; do
|
||||
[ -f "$DLL" ] || continue
|
||||
NAME=$(basename "$DLL")
|
||||
[ "$NAME" = "EarthModelStudio.ModelSdk.dll" ] && continue
|
||||
cp "$DLL" "$DIR$ID.model/"
|
||||
echo " -> model/$ID/$ID.model/$NAME"
|
||||
# 解析 -version=<版本号>(也接受 --version=)
|
||||
CLI_VERSION=""
|
||||
for arg in "$@"; do
|
||||
case "$arg" in
|
||||
-version=*|--version=*) CLI_VERSION="${arg#*=}" ;;
|
||||
esac
|
||||
done
|
||||
if [ -n "$CLI_VERSION" ]; then
|
||||
VERSION="$CLI_VERSION"
|
||||
# 写回 Directory.Build.props,让程序集版本与关于页显示一致
|
||||
if [ -f Directory.Build.props ]; then
|
||||
sed -i.bak "s|<Version>[^<]*</Version>|<Version>${VERSION}</Version>|" Directory.Build.props
|
||||
rm -f Directory.Build.props.bak
|
||||
fi
|
||||
done
|
||||
echo "==> 用模型自己的渲染器生成封面"
|
||||
dotnet run --project "$PREVIEW_PROJ" -c Release -- "$ROOT_DIR"
|
||||
stamp_versions
|
||||
}
|
||||
|
||||
# 发布目录只放启动器 + 空的 .GC 运行骨架,绝不放模型
|
||||
prepare_runtime_layout() {
|
||||
REL="$1"
|
||||
DEST="$ROOT_DIR/$REL"
|
||||
[ -d "$DEST" ] || return 0
|
||||
rm -rf "$DEST/model" "$DEST/examples"
|
||||
mkdir -p "$DEST/.GC/model" "$DEST/.GC/cache" "$DEST/.GC/update"
|
||||
cat > "$DEST/.GC/model/README.txt" <<'TXT'
|
||||
模型库目录(.GC/model/)
|
||||
启动时程序会读取 gitcode 仓库的 version.json,把最新版模型下载到这里。
|
||||
离线使用也可以手动放入 <模型id>/<模型id>.json + <模型id>/<模型id>.model/。
|
||||
|
||||
运行目录:
|
||||
<可执行文件>
|
||||
.GC/settings.json
|
||||
.GC/model/ 本目录(下载的模型)
|
||||
.GC/cache/ 下载暂存
|
||||
.GC/update/ 待下次启动应用的启动器更新
|
||||
TXT
|
||||
if [ ! -f "$DEST/.GC/settings.json" ]; then
|
||||
cat > "$DEST/.GC/settings.json" <<'JSON'
|
||||
{
|
||||
"language": "auto",
|
||||
"theme": "light",
|
||||
"renderFps": 30,
|
||||
"memoryMb": 2048,
|
||||
"autoUpdateOnStartup": true,
|
||||
"updateRepository": "https://gitcode.com/2509_92447106/GC",
|
||||
"updateManifestUrl": "",
|
||||
"updateLocalRoot": "",
|
||||
"installedModelVersions": {},
|
||||
"launcherVersion": "",
|
||||
"pendingLauncherVersion": "",
|
||||
"lastUpdateCheck": "",
|
||||
"sources": [],
|
||||
"recentModels": []
|
||||
}
|
||||
JSON
|
||||
echo "==> 版本号设为 ${VERSION}"
|
||||
fi
|
||||
echo " 运行目录 -> $REL/.GC (settings.json + model/ + cache/ + update/)"
|
||||
}
|
||||
mkdir -p "$ROOT_DIR/build/logs"
|
||||
|
||||
publish_rid() {
|
||||
RID="$1"; OUT="$2"
|
||||
echo ""
|
||||
echo "==> 编译 ${RID} -> ${OUT}"
|
||||
dotnet publish "$APP_PROJ" \
|
||||
-c Release \
|
||||
-r "$RID" \
|
||||
--self-contained true \
|
||||
-p:Version="$VERSION" \
|
||||
-p:DebugType=none \
|
||||
-p:PublishSingleFile=true \
|
||||
-p:IncludeNativeLibrariesForSelfExtract=true \
|
||||
-p:PublishTrimmed=false \
|
||||
-o "$ROOT_DIR/$OUT"
|
||||
rm -rf "$ROOT_DIR/$OUT/model" "$ROOT_DIR/$OUT/examples"
|
||||
}
|
||||
|
||||
# 把 model/ 里的模型数据单独打包(与启动器分开分发)
|
||||
pack_models() {
|
||||
mkdir -p "$ROOT_DIR/dist"
|
||||
ZIP="$ROOT_DIR/dist/models-$VERSION.zip"
|
||||
rm -f "$ZIP"
|
||||
echo "==> 打包模型数据 -> dist/models-$VERSION.zip"
|
||||
( cd "$ROOT_DIR" && zip -qr "$ZIP" model \
|
||||
-x "*.DS_Store" "*/bin/*" "*/obj/*" "*.user" )
|
||||
du -sh "$ZIP"
|
||||
}
|
||||
|
||||
# 启动器更新包:只包含程序文件,排除 .GC(否则会覆盖用户已下载的模型与设置)
|
||||
pack_launcher() {
|
||||
echo "==> 生成启动器更新包(不含 .GC)"
|
||||
WIN64="$ROOT_DIR/dist/win-x64"
|
||||
WINARM="$ROOT_DIR/dist/win-arm64"
|
||||
MACBIN="$ROOT_DIR/dist/mac-arm64/EarthModelStudio.app/Contents/MacOS"
|
||||
[ -d "$MACBIN" ] || MACBIN="$ROOT_DIR/dist/mac-arm64"
|
||||
[ -d "$WIN64" ] && ( cd "$WIN64" && zip -qr "$ROOT_DIR/dist/GC-win-x64.zip" . \
|
||||
-x "./.GC" "./.GC/*" "*.DS_Store" )
|
||||
[ -d "$WINARM" ] && ( cd "$WINARM" && zip -qr "$ROOT_DIR/dist/GC-win-arm64.zip" . \
|
||||
-x "./.GC" "./.GC/*" "*.DS_Store" )
|
||||
[ -d "$MACBIN" ] && ( cd "$MACBIN" && zip -qr "$ROOT_DIR/dist/GC-osx-arm64.zip" . \
|
||||
-x "./.GC" "./.GC/*" "*.DS_Store" )
|
||||
stamp_versions
|
||||
ls -lh "$ROOT_DIR"/dist/GC-*.zip 2>/dev/null || true
|
||||
}
|
||||
|
||||
package_mac_app() {
|
||||
DIST="$ROOT_DIR/dist/mac-arm64"
|
||||
APP="$DIST/EarthModelStudio.app"
|
||||
rm -rf "$APP"
|
||||
mkdir -p "$APP/Contents/MacOS" "$APP/Contents/Resources"
|
||||
cat > "$APP/Contents/Info.plist" <<PLIST
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>CFBundleName</key><string>Earth Model Studio</string>
|
||||
<key>CFBundleDisplayName</key><string>Earth Model Studio</string>
|
||||
<key>CFBundleIdentifier</key><string>cn.neorf.earthmodelstudio</string>
|
||||
<key>CFBundleVersion</key><string>${VERSION}</string>
|
||||
<key>CFBundleShortVersionString</key><string>${VERSION}</string>
|
||||
<key>CFBundlePackageType</key><string>APPL</string>
|
||||
<key>CFBundleExecutable</key><string>EarthModelStudio</string>
|
||||
<key>CFBundleInfoDictionaryVersion</key><string>6.0</string>
|
||||
<key>LSMinimumSystemVersion</key><string>11.0</string>
|
||||
<key>NSHighResolutionCapable</key><true/>
|
||||
</dict>
|
||||
</plist>
|
||||
PLIST
|
||||
for f in "$DIST"/*; do
|
||||
base=$(basename "$f")
|
||||
[ "$base" = "EarthModelStudio.app" ] && continue
|
||||
mv "$f" "$APP/Contents/MacOS/"
|
||||
done
|
||||
chmod +x "$APP/Contents/MacOS/EarthModelStudio"
|
||||
echo "==> 已打包 $APP"
|
||||
}
|
||||
# 加载 buildsh 模块
|
||||
. "$ROOT_DIR/buildsh/lib/progress.sh"
|
||||
. "$ROOT_DIR/buildsh/lib/build_funcs.sh"
|
||||
. "$ROOT_DIR/buildsh/build.sh"
|
||||
. "$ROOT_DIR/buildsh/check.sh"
|
||||
. "$ROOT_DIR/buildsh/tools.sh"
|
||||
|
||||
case "$TASK" in
|
||||
build)
|
||||
dotnet build "$SLN" -c Debug
|
||||
;;
|
||||
run)
|
||||
dotnet run --project "$APP_PROJ" -c Debug
|
||||
;;
|
||||
test)
|
||||
dotnet run --project "$TEST_PROJ" -c Debug -- "$ROOT_DIR/build/screenshots"
|
||||
;;
|
||||
publish)
|
||||
mkdir -p "$ROOT_DIR/dist"
|
||||
stamp_versions
|
||||
publish_rid "osx-arm64" "dist/mac-arm64"
|
||||
publish_rid "win-x64" "dist/win-x64"
|
||||
publish_rid "win-arm64" "dist/win-arm64"
|
||||
package_mac_app
|
||||
prepare_runtime_layout "dist/win-x64"
|
||||
prepare_runtime_layout "dist/win-arm64"
|
||||
prepare_runtime_layout "dist/mac-arm64/EarthModelStudio.app/Contents/MacOS"
|
||||
pack_launcher
|
||||
echo ""
|
||||
echo "==> 三个平台编译完成(发布包不含模型,首次启动自动下载):"
|
||||
du -sh "$ROOT_DIR/dist"/* 2>/dev/null || true
|
||||
echo " 把 version.json / model/ 推送到 gitcode,启动器就会自动检查更新"
|
||||
;;
|
||||
models)
|
||||
build_models
|
||||
;;
|
||||
stamp)
|
||||
stamp_versions
|
||||
;;
|
||||
bundle)
|
||||
echo "已弃用:发布包不再内置模型。请改用 ./build.sh stamp 与 gitcode 自动更新。"
|
||||
;;
|
||||
pack-models)
|
||||
build_models
|
||||
pack_models
|
||||
;;
|
||||
pack-launcher)
|
||||
pack_launcher
|
||||
;;
|
||||
update-test)
|
||||
dotnet run --project "$TEST_PROJ" -c Debug -- --update-test "$ROOT_DIR"
|
||||
;;
|
||||
clean)
|
||||
rm -rf "$ROOT_DIR/build" "$ROOT_DIR/dist"
|
||||
find "$ROOT_DIR/src" -type d \( -name bin -o -name obj \) -prune -exec rm -rf {} + 2>/dev/null || true
|
||||
echo "==> 已清理"
|
||||
;;
|
||||
doctor)
|
||||
dotnet --info | head -20
|
||||
;;
|
||||
*)
|
||||
echo "未知任务: $TASK"
|
||||
echo "可用: build | run | test | publish | models | stamp | pack-models | pack-launcher | update-test | clean | doctor"
|
||||
exit 1
|
||||
;;
|
||||
build) bs_build "$ROOT_DIR" ;;
|
||||
check) bs_check "$ROOT_DIR" ;;
|
||||
*) bs_tools "$ROOT_DIR" "$TASK" ;;
|
||||
esac
|
||||
@@ -0,0 +1,45 @@
|
||||
function Invoke-BuildCheck {
|
||||
Initialize-BuildProgress @('编译检查', '模型自检', '离屏渲染', '产物检查')
|
||||
$failures = [System.Collections.Generic.List[string]]::new()
|
||||
try {
|
||||
Start-BuildStep '编译检查'
|
||||
try { Invoke-LoggedDotNet -Name 'check-build' -Arguments @('build', $script:Solution, '-c', 'Debug', '-v', 'quiet') }
|
||||
catch { $failures.Add('编译失败,见 build/logs/check-build.log'); Write-Host "!! $($failures[-1])" }
|
||||
Complete-BuildStep
|
||||
|
||||
Start-BuildStep '模型自检'
|
||||
$previousSelfTest = $env:EMS_SELFTEST
|
||||
try {
|
||||
$env:EMS_SELFTEST = '1'
|
||||
Invoke-LoggedDotNet -Name 'check-selftest' -Arguments @('run', '--project', $script:AppProject, '-c', 'Debug', '--no-build')
|
||||
if (Select-String -Path 'build/logs/check-selftest.log' -Pattern 'FAIL' -Quiet) {
|
||||
$failures.Add('模型自检有失败项')
|
||||
Write-Host "!! $($failures[-1])"
|
||||
}
|
||||
}
|
||||
catch { $failures.Add('模型自检异常'); Write-Host "!! $($failures[-1])" }
|
||||
finally { $env:EMS_SELFTEST = $previousSelfTest }
|
||||
Complete-BuildStep
|
||||
|
||||
Start-BuildStep '离屏渲染'
|
||||
try {
|
||||
New-Item -ItemType Directory -Force -Path 'build/screenshots' | Out-Null
|
||||
Invoke-LoggedDotNet -Name 'check-render' -Arguments @('run', '--project', $script:TestProject, '-c', 'Debug', '--no-build', '--', (Join-Path $script:BuildRoot 'build/screenshots'))
|
||||
}
|
||||
catch { $failures.Add('离屏渲染失败,见 build/logs/check-render.log'); Write-Host "!! $($failures[-1])" }
|
||||
Complete-BuildStep
|
||||
|
||||
Start-BuildStep '产物检查'
|
||||
$packageCount = @(Get-ChildItem 'dist' -Filter "GC-$script:BuildVersion-*.zip" -ErrorAction SilentlyContinue).Count
|
||||
if ($packageCount -lt 3) {
|
||||
$failures.Add("产物不足 3 个(当前 $packageCount)")
|
||||
Write-Host "!! $($failures[-1])"
|
||||
}
|
||||
Complete-BuildStep
|
||||
}
|
||||
finally { Complete-BuildProgress }
|
||||
|
||||
if ($failures.Count -eq 0) { Write-Host '==> 全部通过'; return }
|
||||
Write-Host '==> 有失败项'
|
||||
throw ($failures -join "`n")
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
function Invoke-BuildTool {
|
||||
param([Parameter(Mandatory)][string]$Name)
|
||||
switch ($Name) {
|
||||
'models' { Build-Models }
|
||||
'stamp' { Invoke-VersionStamp }
|
||||
'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" } }
|
||||
'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
|
||||
foreach ($projectRoot in @('GC', 'GC-BOOT', 'GC-DRAW', 'model')) {
|
||||
$path = Join-Path $script:BuildRoot $projectRoot
|
||||
if (Test-Path $path) {
|
||||
Get-ChildItem $path -Directory -Recurse -Force | Where-Object Name -in @('bin', 'obj') | Sort-Object FullName -Descending | Remove-Item -Recurse -Force -ErrorAction SilentlyContinue
|
||||
}
|
||||
}
|
||||
Write-Host '==> 已清理'
|
||||
}
|
||||
'doctor' { & dotnet --info | Select-Object -First 20; if ($LASTEXITCODE -ne 0) { throw "dotnet --info 失败,退出码 $LASTEXITCODE" } }
|
||||
'dist' {
|
||||
Write-Host '==> dist 产物:'
|
||||
Get-ChildItem (Join-Path $script:BuildRoot 'dist') -ErrorAction SilentlyContinue | Select-Object Name, Length
|
||||
}
|
||||
default { throw "未知任务:$Name" }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
param(
|
||||
[Parameter(Position = 0)]
|
||||
[ValidateSet('build','check','models','stamp','pack-models','pack-launcher',
|
||||
'run','test','update-test','clean','doctor','dist')]
|
||||
[string]$Task = 'build',
|
||||
[string]$Version = ''
|
||||
)
|
||||
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$script:BuildRoot = (Resolve-Path (Join-Path $PSScriptRoot '..')).Path
|
||||
$script:AppProject = 'GC-BOOT/GC-BOOT.csproj'
|
||||
$script:PreviewProject = 'model/_engine/PreviewGen/PreviewGen.csproj'
|
||||
$script:StampProject = 'model/_engine/VersionStamp/VersionStamp.csproj'
|
||||
$script:TestProject = 'GC/src/test/dotnet/GC.Tests/GC.Tests.csproj'
|
||||
$script:Solution = 'GC.sln'
|
||||
$env:AVALONIA_TELEMETRY_OPTOUT = '1'
|
||||
|
||||
Push-Location $script:BuildRoot
|
||||
try {
|
||||
$props = [xml](Get-Content 'Directory.Build.props' -Raw)
|
||||
$versionNode = $props.SelectSingleNode('/Project/PropertyGroup/Version')
|
||||
if (-not $Version) { $Version = $versionNode.InnerText }
|
||||
if (-not $Version) { $Version = '1.0.0' }
|
||||
$script:BuildVersion = $Version
|
||||
|
||||
if ($PSBoundParameters.ContainsKey('Version')) {
|
||||
if ($null -eq $versionNode) { throw 'Directory.Build.props 中找不到 Version 节点。' }
|
||||
$versionNode.InnerText = $Version
|
||||
$props.Save((Join-Path $script:BuildRoot 'Directory.Build.props'))
|
||||
Write-Host "==> 版本号设为 $Version"
|
||||
}
|
||||
|
||||
New-Item -ItemType Directory -Force -Path 'build/logs' | Out-Null
|
||||
. (Join-Path $PSScriptRoot 'lib/Progress.ps1')
|
||||
. (Join-Path $PSScriptRoot 'lib/Build-Funcs.ps1')
|
||||
. (Join-Path $PSScriptRoot 'Build-Check.ps1')
|
||||
. (Join-Path $PSScriptRoot 'Build-Tools.ps1')
|
||||
|
||||
switch ($Task) {
|
||||
'build' { Invoke-FullBuild }
|
||||
'check' { Invoke-BuildCheck }
|
||||
default { Invoke-BuildTool $Task }
|
||||
}
|
||||
}
|
||||
finally {
|
||||
Pop-Location
|
||||
}
|
||||
@@ -0,0 +1,343 @@
|
||||
function Invoke-LoggedDotNet {
|
||||
param(
|
||||
[Parameter(Mandatory)][string]$Name,
|
||||
[Parameter(Mandatory)][string[]]$Arguments
|
||||
)
|
||||
$logPath = Join-Path $script:BuildRoot "build/logs/$Name.log"
|
||||
& dotnet @Arguments *> $logPath
|
||||
$exitCode = $LASTEXITCODE
|
||||
if ($exitCode -ne 0) {
|
||||
Get-Content $logPath | Write-Host
|
||||
throw "dotnet $($Arguments -join ' ') 失败,退出码 $exitCode;日志:$logPath"
|
||||
}
|
||||
}
|
||||
|
||||
function Invoke-ManifestSign {
|
||||
$key = Join-Path $script:BuildRoot '.signing/gc-signing.pem'
|
||||
if (-not (Test-Path $key)) {
|
||||
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' }
|
||||
Write-Host "==> 签名 version.json ($keyId)"
|
||||
Invoke-LoggedDotNet -Name 'sign' -Arguments @(
|
||||
'run', '--project', (Join-Path $script:BuildRoot 'GC-SAVEDOG/GC-SAVEDOG.csproj'),
|
||||
'-c', 'Release', '--', 'sign',
|
||||
'--manifest', (Join-Path $script:BuildRoot 'version.json'),
|
||||
'--key', $key, '--key-id', $keyId
|
||||
)
|
||||
Copy-Item (Join-Path $script:BuildRoot 'version.json') (Join-Path $script:BuildRoot 'model/version.json') -Force
|
||||
}
|
||||
|
||||
function Invoke-VersionStamp {
|
||||
param([switch]$LauncherOnly)
|
||||
if ($LauncherOnly) {
|
||||
Write-Host '==> 刷新启动器包信息(sha256 / 体积 / dist 路径)'
|
||||
Invoke-LoggedDotNet -Name 'stamp' -Arguments @(
|
||||
'run', '--project', $script:StampProject, '-c', 'Release', '--',
|
||||
$script:BuildRoot, $script:BuildVersion, '--launcher-only'
|
||||
)
|
||||
}
|
||||
else {
|
||||
Write-Host '==> 自动计算模型版本并生成 version.json'
|
||||
Invoke-LoggedDotNet -Name 'stamp' -Arguments @(
|
||||
'run', '--project', $script:StampProject, '-c', 'Release', '--',
|
||||
$script:BuildRoot, $script:BuildVersion
|
||||
)
|
||||
}
|
||||
Invoke-ManifestSign
|
||||
}
|
||||
|
||||
function Build-Models {
|
||||
Write-Host '==> 编译模型功能程序集(源码位于各模型目录的 src/)'
|
||||
Get-ChildItem (Join-Path $script:BuildRoot 'model') -Directory | ForEach-Object {
|
||||
$modelId = $_.Name
|
||||
$sourceDir = Join-Path $_.FullName 'src'
|
||||
if (-not (Test-Path $sourceDir)) { return }
|
||||
$project = Get-ChildItem $sourceDir -Filter '*.csproj' | Select-Object -First 1
|
||||
if ($null -eq $project) { return }
|
||||
|
||||
Invoke-LoggedDotNet -Name "model-$modelId" -Arguments @('build', $project.FullName, '-c', 'Release')
|
||||
$packageDir = Join-Path $_.FullName "$modelId.model"
|
||||
$outputDir = Join-Path $sourceDir 'bin/Release/net8.0'
|
||||
if (Test-Path $packageDir) {
|
||||
Get-ChildItem $outputDir -Filter '*.dll' -ErrorAction SilentlyContinue | Where-Object Name -ne 'GC.ModelSdk.dll' | ForEach-Object {
|
||||
Copy-Item $_.FullName (Join-Path $packageDir $_.Name) -Force
|
||||
Write-Host " -> model/$modelId/$modelId.model/$($_.Name)"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Write-Host '==> 用模型自己的渲染器生成封面'
|
||||
Invoke-LoggedDotNet -Name 'preview' -Arguments @('run', '--project', $script:PreviewProject, '-c', 'Release', '--', $script:BuildRoot)
|
||||
Invoke-VersionStamp
|
||||
}
|
||||
|
||||
function Prepare-RuntimeLayout {
|
||||
param([Parameter(Mandatory)][string]$RelativePath)
|
||||
$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": []
|
||||
}
|
||||
'@
|
||||
}
|
||||
Write-Host " 运行目录 -> $RelativePath/.GC"
|
||||
}
|
||||
|
||||
function Publish-Rid {
|
||||
param(
|
||||
[Parameter(Mandatory)][string]$Rid,
|
||||
[Parameter(Mandatory)][string]$Output,
|
||||
[bool]$SingleFile = $true
|
||||
)
|
||||
$outputPath = Join-Path $script:BuildRoot $Output
|
||||
Remove-Item $outputPath -Recurse -Force -ErrorAction SilentlyContinue
|
||||
$singleValue = $SingleFile.ToString().ToLowerInvariant()
|
||||
Write-Host "==> 编译 $Rid (single-file=$singleValue) -> $Output"
|
||||
Invoke-LoggedDotNet -Name "publish-$($Rid -replace '-', '')" -Arguments @(
|
||||
'publish', $script:AppProject, '-c', 'Release', '-r', $Rid,
|
||||
'--self-contained', 'true', "-p:Version=$script:BuildVersion", '-p:DebugType=none',
|
||||
"-p:PublishSingleFile=$singleValue", "-p:IncludeNativeLibrariesForSelfExtract=$singleValue",
|
||||
'-p:PublishTrimmed=false', '-o', $outputPath
|
||||
)
|
||||
|
||||
# 更新守护进程:与主程序同目录(裁剪单文件,70MB -> 14MB)
|
||||
# 裁剪的前提是 JSON 全部走源生成上下文(GC-SAVEDOG/SavedogJson.cs)
|
||||
$savedogProj = Join-Path $script:BuildRoot 'GC-SAVEDOG/GC-SAVEDOG.csproj'
|
||||
if (Test-Path $savedogProj) {
|
||||
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:PublishTrimmed=true', '-p:TrimMode=full',
|
||||
'-p:JsonSerializerIsReflectionEnabledByDefault=false', '-o', $outputPath
|
||||
)
|
||||
}
|
||||
|
||||
Remove-Item (Join-Path $outputPath 'model'), (Join-Path $outputPath 'examples') -Recurse -Force -ErrorAction SilentlyContinue
|
||||
}
|
||||
|
||||
function Pack-Models {
|
||||
$zipPath = Join-Path $script:BuildRoot "dist/models-$script:BuildVersion.zip"
|
||||
Remove-Item $zipPath -Force -ErrorAction SilentlyContinue
|
||||
Write-Host "==> 打包模型数据 -> dist/models-$script:BuildVersion.zip"
|
||||
Add-Type -AssemblyName System.IO.Compression.FileSystem
|
||||
$modelRoot = Join-Path $script:BuildRoot 'model'
|
||||
$archive = [System.IO.Compression.ZipFile]::Open($zipPath, [System.IO.Compression.ZipArchiveMode]::Create)
|
||||
try {
|
||||
Get-ChildItem $modelRoot -File -Recurse | Where-Object {
|
||||
$relativePath = $_.FullName.Substring($modelRoot.Length).TrimStart([IO.Path]::DirectorySeparatorChar, [IO.Path]::AltDirectorySeparatorChar).Replace('\', '/')
|
||||
$_.Name -ne '.DS_Store' -and
|
||||
$_.Extension -ne '.user' -and
|
||||
$relativePath -notmatch '(^|/)(bin|obj)/'
|
||||
} | ForEach-Object {
|
||||
$relativePath = $_.FullName.Substring($modelRoot.Length).TrimStart([IO.Path]::DirectorySeparatorChar, [IO.Path]::AltDirectorySeparatorChar).Replace('\', '/')
|
||||
[System.IO.Compression.ZipFileExtensions]::CreateEntryFromFile(
|
||||
$archive, $_.FullName, "model/$relativePath", [System.IO.Compression.CompressionLevel]::Optimal
|
||||
) | Out-Null
|
||||
}
|
||||
}
|
||||
finally { $archive.Dispose() }
|
||||
Get-Item $zipPath | Select-Object Name, Length
|
||||
}
|
||||
|
||||
function Pack-Launcher {
|
||||
$dist = Join-Path $script:BuildRoot 'dist'
|
||||
Write-Host "==> 生成启动器产物(GC-$script:BuildVersion-<平台>)"
|
||||
|
||||
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 }
|
||||
|
||||
$temp = Join-Path $dist ".winpkg-$($platform.Label)"
|
||||
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 }
|
||||
|
||||
$zipPath = Join-Path $dist "$($platform.Label)/GC-$script:BuildVersion-$($platform.Label).zip"
|
||||
Remove-Item $zipPath -Force -ErrorAction SilentlyContinue
|
||||
Compress-Archive -Path (Join-Path $temp '*') -DestinationPath $zipPath -CompressionLevel Optimal
|
||||
Remove-Item $temp -Recurse -Force -ErrorAction SilentlyContinue
|
||||
Write-Host " -> dist/$($platform.Label)/GC-$script:BuildVersion-$($platform.Label).zip"
|
||||
}
|
||||
|
||||
$macApp = Join-Path $dist 'mac-arm64/GC.app'
|
||||
if (Test-Path $macApp) {
|
||||
$finalApp = Join-Path $dist "GC-$script:BuildVersion-mac-arm64.app"
|
||||
Remove-Item $finalApp -Recurse -Force -ErrorAction SilentlyContinue
|
||||
Move-Item $macApp $finalApp
|
||||
$binary = Join-Path $finalApp 'Contents/MacOS/GC'
|
||||
if ((Test-Path $binary) -and (Get-Command chmod -ErrorAction SilentlyContinue)) { & chmod +x $binary }
|
||||
$plist = Join-Path $finalApp 'Contents/Info.plist'
|
||||
if ((Test-Path $plist) -and (Test-Path '/usr/libexec/PlistBuddy')) {
|
||||
& /usr/libexec/PlistBuddy -c 'Set :CFBundleName Morris GC' $plist 2>$null
|
||||
& /usr/libexec/PlistBuddy -c 'Set :CFBundleDisplayName Morris GC' $plist 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))-", ''
|
||||
$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)) {
|
||||
& ditto -c -k --sequesterRsrc --keepParent $_.FullName $zipPath
|
||||
if ($LASTEXITCODE -ne 0) { throw "ditto 压缩失败:$($_.Name)" }
|
||||
}
|
||||
else {
|
||||
Compress-Archive -Path $_.FullName -DestinationPath $zipPath -CompressionLevel Optimal
|
||||
}
|
||||
Write-Host " -> dist/$label/$($_.BaseName).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"
|
||||
} | 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
|
||||
}
|
||||
|
||||
function Remove-IntermediateDirectories {
|
||||
# 平台目录里只留最终 zip(其它都是 publish 中间产物)
|
||||
foreach ($name in @('win-amd64', 'win-x64', 'win-arm64', 'mac-arm64')) {
|
||||
$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" } |
|
||||
Remove-Item -Recurse -Force -ErrorAction SilentlyContinue
|
||||
}
|
||||
Get-ChildItem (Join-Path $script:BuildRoot 'dist') -Filter '.DS_Store' -Recurse -Force -ErrorAction SilentlyContinue | Remove-Item -Force
|
||||
}
|
||||
|
||||
function New-MacAppBundle {
|
||||
$dist = Join-Path $script:BuildRoot 'dist/mac-arm64'
|
||||
$app = Join-Path $dist 'GC.app'
|
||||
Remove-Item $app -Recurse -Force -ErrorAction SilentlyContinue
|
||||
New-Item -ItemType Directory -Force -Path (Join-Path $app 'Contents/MacOS'), (Join-Path $app 'Contents/Resources') | Out-Null
|
||||
$plist = @"
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0"><dict>
|
||||
<key>CFBundleName</key><string>GC</string>
|
||||
<key>CFBundleDisplayName</key><string>GC</string>
|
||||
<key>CFBundleIdentifier</key><string>cn.neorf.GC</string>
|
||||
<key>CFBundleVersion</key><string>$script:BuildVersion</string>
|
||||
<key>CFBundleShortVersionString</key><string>$script:BuildVersion</string>
|
||||
<key>CFBundlePackageType</key><string>APPL</string>
|
||||
<key>CFBundleExecutable</key><string>GC</string>
|
||||
<key>CFBundleInfoDictionaryVersion</key><string>6.0</string>
|
||||
<key>LSMinimumSystemVersion</key><string>11.0</string>
|
||||
<key>NSHighResolutionCapable</key><true/>
|
||||
</dict></plist>
|
||||
"@
|
||||
Set-Content -Path (Join-Path $app 'Contents/Info.plist') -Encoding UTF8 -Value $plist
|
||||
Get-ChildItem $dist -Force | Where-Object Name -notin @('GC.app', '.DS_Store') | Move-Item -Destination (Join-Path $app 'Contents/MacOS')
|
||||
Remove-Item (Join-Path $app 'Contents/MacOS/.GC') -Recurse -Force -ErrorAction SilentlyContinue
|
||||
$binary = Join-Path $app 'Contents/MacOS/GC'
|
||||
if ((Test-Path $binary) -and (Get-Command chmod -ErrorAction SilentlyContinue)) { & chmod +x $binary }
|
||||
|
||||
$iconSource = Join-Path $script:BuildRoot 'GC/src/Assets/icon-1024.png'
|
||||
if ((Test-Path $iconSource) -and (Get-Command iconutil -ErrorAction SilentlyContinue) -and (Get-Command sips -ErrorAction SilentlyContinue)) {
|
||||
$iconset = Join-Path $dist 'AppIcon.iconset'
|
||||
Remove-Item $iconset -Recurse -Force -ErrorAction SilentlyContinue
|
||||
New-Item -ItemType Directory -Force -Path $iconset | Out-Null
|
||||
foreach ($size in @(16, 32, 64, 128, 256, 512)) {
|
||||
& sips -z $size $size $iconSource --out (Join-Path $iconset "icon_${size}x${size}.png") *> $null
|
||||
$doubleSize = $size * 2
|
||||
& sips -z $doubleSize $doubleSize $iconSource --out (Join-Path $iconset "icon_${size}x${size}@2x.png") *> $null
|
||||
}
|
||||
$iconFile = Join-Path $app 'Contents/Resources/AppIcon.icns'
|
||||
& iconutil -c icns $iconset -o $iconFile
|
||||
if ($LASTEXITCODE -eq 0) {
|
||||
$infoPlist = Join-Path $app 'Contents/Info.plist'
|
||||
if (Test-Path '/usr/libexec/PlistBuddy') {
|
||||
& /usr/libexec/PlistBuddy -c 'Add :CFBundleIconFile string AppIcon' $infoPlist 2>$null
|
||||
}
|
||||
}
|
||||
Remove-Item $iconset -Recurse -Force -ErrorAction SilentlyContinue
|
||||
}
|
||||
Write-Host "==> 已打包 $app"
|
||||
}
|
||||
|
||||
function Invoke-FullBuild {
|
||||
Initialize-BuildProgress @('清理旧产物', '版本戳', '编译 Mac', '编译 Win-x64', '编译 Win-arm64', '运行骨架', '打包 zip', '收尾')
|
||||
try {
|
||||
Start-BuildStep '清理旧产物'
|
||||
Remove-Item (Join-Path $script:BuildRoot 'dist') -Recurse -Force -ErrorAction SilentlyContinue
|
||||
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' $true; Complete-BuildStep
|
||||
Start-BuildStep '编译 Win-arm64'; Publish-Rid 'win-arm64' 'dist/win-arm64' $true; Complete-BuildStep
|
||||
|
||||
Start-BuildStep '运行骨架'
|
||||
New-MacAppBundle
|
||||
Prepare-RuntimeLayout 'dist/win-amd64'
|
||||
Prepare-RuntimeLayout 'dist/win-arm64'
|
||||
Prepare-RuntimeLayout 'dist/mac-arm64/GC.app/Contents/MacOS'
|
||||
Complete-BuildStep
|
||||
|
||||
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
|
||||
}
|
||||
finally { Complete-BuildProgress }
|
||||
}
|
||||