添加GC-DOWNLOAD项目
This commit is contained in:
1 parent
c95dfaf9f3
commit
791db4fe12
47 files changed
+869
-313
No files matched your search
@@ -19,6 +19,7 @@
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\GC\src\GC.Core.csproj" />
|
||||
<ProjectReference Include="..\GC-DOWNLOAD\GC-DOWNLOAD.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
+3
-1
@@ -1,6 +1,7 @@
|
||||
using System;
|
||||
using Avalonia;
|
||||
using GC.Services;
|
||||
using GC.Download;
|
||||
|
||||
namespace GC;
|
||||
|
||||
@@ -9,12 +10,13 @@ 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 (LauncherUpdater.TryApplyPending(paths)) return;
|
||||
if (DownloadModuleHost.Factory.TryApplyPending(paths)) return;
|
||||
|
||||
BuildAvaloniaApp().StartWithClassicDesktopLifetime(args);
|
||||
}
|
||||
|
||||
File renamed without changes.
@@ -9,17 +9,8 @@ using GC.Models;
|
||||
|
||||
namespace GC.Services;
|
||||
|
||||
public enum DownloadState
|
||||
{
|
||||
Queued,
|
||||
Running,
|
||||
Completed,
|
||||
Failed,
|
||||
Canceled
|
||||
}
|
||||
|
||||
/// <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>
|
||||
@@ -50,9 +50,9 @@ 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);
|
||||
@@ -11,14 +11,14 @@ namespace GC.Services;
|
||||
|
||||
/// <summary>
|
||||
/// gitcode 仓库源。默认地址来自 AppSettings.UpdateRepository
|
||||
/// (https://gitcode.com/2509_92447106/GC),可改成任意 gitcode 仓库或
|
||||
/// (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/2509_92447106/GC";
|
||||
public const string DefaultRepository = "https://gitcode.com/Morris_1/GC";
|
||||
|
||||
private readonly HttpClient _http;
|
||||
private readonly string _api;
|
||||
@@ -59,9 +59,9 @@ public sealed class GitCodeRemote : IModelRemote
|
||||
{
|
||||
var raw = string.IsNullOrWhiteSpace(url) ? DefaultRepository : url!.Trim();
|
||||
if (!Uri.TryCreate(raw, UriKind.Absolute, out var uri))
|
||||
return ("2509_92447106", "GC", "main");
|
||||
return ("Morris_1", "GC", "main");
|
||||
var parts = uri.AbsolutePath.Trim('/').Split('/', StringSplitOptions.RemoveEmptyEntries);
|
||||
if (parts.Length < 2) return ("2509_92447106", "GC", "main");
|
||||
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];
|
||||
File renamed without changes.
@@ -23,31 +23,14 @@ namespace GC.Services;
|
||||
// · 一切落盘内容(脚本、标记)只用相对路径,绝不写绝对路径
|
||||
// ===========================================================================
|
||||
|
||||
public sealed class UpdateProgressInfo
|
||||
{
|
||||
public double Value { get; init; }
|
||||
public string Stage { get; init; } = "";
|
||||
}
|
||||
|
||||
public enum UpdateRunState { UpToDate, Ready, Failed }
|
||||
|
||||
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; }
|
||||
}
|
||||
|
||||
/// <summary>下载 / 检查 / 应用启动器更新的唯一入口。</summary>
|
||||
public static class LauncherUpdater
|
||||
{
|
||||
/// <summary>当前运行程序的版本号(来自程序集)。</summary>
|
||||
public static string RunningVersion => UpdateService.CurrentLauncherVersion;
|
||||
public static string RunningVersion => LauncherRuntimeInfo.CurrentLauncherVersion;
|
||||
|
||||
/// <summary>当前 RID,如 osx-arm64。</summary>
|
||||
public static string CurrentRid => UpdateService.CurrentRid;
|
||||
public static string CurrentRid => LauncherRuntimeInfo.CurrentRid;
|
||||
|
||||
/// <summary>文件名里用的「系统-架构」标签,如 mac-arm64 / win-amd64。</summary>
|
||||
public static string PlatformLabel => CurrentRid switch
|
||||
@@ -333,11 +316,9 @@ public static class LauncherUpdater
|
||||
return Fail("下载文件校验失败(sha256 不符)");
|
||||
}
|
||||
|
||||
progress?.Report(new UpdateProgressInfo { Value = 0.60, Stage = "正在解压到当前目录" });
|
||||
progress?.Report(new UpdateProgressInfo { Value = 0.60, Stage = "正在解压更新包" });
|
||||
|
||||
// 解压到临时中转目录,再搬到当前运行目录
|
||||
var installDir = paths.InstallDirectory;
|
||||
Directory.CreateDirectory(installDir);
|
||||
// 更新包先完整保存在下载目录,重启替换脚本再移入安装目录。
|
||||
var staging = Path.Combine(paths.CacheRoot, "launcher-staging");
|
||||
if (Directory.Exists(staging)) Directory.Delete(staging, true);
|
||||
Directory.CreateDirectory(staging);
|
||||
@@ -350,16 +331,20 @@ public static class LauncherUpdater
|
||||
// 只展平「单个非 .app 顶层目录」的 zip
|
||||
FlattenStaging(staging);
|
||||
|
||||
progress?.Report(new UpdateProgressInfo { Value = 0.80, Stage = "正在安装新版本" });
|
||||
progress?.Report(new UpdateProgressInfo { Value = 0.80, Stage = "正在暂存新版本" });
|
||||
|
||||
var packageName = MoveToInstallDir(staging, installDir, latest);
|
||||
var payload = Path.Combine(paths.UpdateRoot, "payload");
|
||||
if (Directory.Exists(payload)) Directory.Delete(payload, true);
|
||||
Directory.CreateDirectory(payload);
|
||||
var packageName = MoveToPayload(staging, payload);
|
||||
try { Directory.Delete(staging, true); } catch { }
|
||||
if (packageName == null) return Fail("解压结果里没有找到新版启动器");
|
||||
|
||||
// 写标记(纯文本,脚本读它):只含相对信息,无绝对路径
|
||||
Directory.CreateDirectory(paths.UpdateRoot);
|
||||
File.WriteAllText(Path.Combine(paths.UpdateRoot, "update.txt"),
|
||||
$"NAME={packageName}\nVERSION={latest}\nPLATFORM={PlatformLabel}\n");
|
||||
$"NAME={packageName}\nVERSION={latest}\nPLATFORM={PlatformLabel}\n" +
|
||||
$"INSTALL_REL={Path.GetRelativePath(paths.UpdateRoot, paths.InstallDirectory)}\n");
|
||||
|
||||
progress?.Report(new UpdateProgressInfo { Value = 1.0, Stage = "下载完成" });
|
||||
|
||||
@@ -367,9 +352,9 @@ public static class LauncherUpdater
|
||||
{
|
||||
State = UpdateRunState.Ready,
|
||||
Version = latest,
|
||||
Message = $"v{latest} 已下载到当前目录",
|
||||
Message = $"v{latest} 已暂存到 .GC/update",
|
||||
PackageName = packageName,
|
||||
NewAppPath = Path.Combine(installDir, packageName)
|
||||
NewAppPath = Path.Combine(payload, packageName)
|
||||
};
|
||||
}
|
||||
catch (OperationCanceledException) { return Fail("已取消"); }
|
||||
@@ -447,8 +432,8 @@ public static class LauncherUpdater
|
||||
|
||||
var name = ReadMarker(marker, "NAME");
|
||||
if (string.IsNullOrWhiteSpace(name)) return false;
|
||||
if (!File.Exists(Path.Combine(paths.InstallDirectory, name!)) &&
|
||||
!Directory.Exists(Path.Combine(paths.InstallDirectory, name!)))
|
||||
var payloadPath = Path.Combine(paths.UpdateRoot, "payload", name!);
|
||||
if (!File.Exists(payloadPath) && !Directory.Exists(payloadPath))
|
||||
return false; // 新版本不在了,放弃
|
||||
|
||||
return ScheduleApply(paths, name!);
|
||||
@@ -460,27 +445,33 @@ public static class LauncherUpdater
|
||||
{
|
||||
var s = new System.Text.StringBuilder();
|
||||
s.AppendLine("#!/bin/sh");
|
||||
s.AppendLine("# script lives in .GC/update/ ; install dir is two levels up");
|
||||
s.AppendLine("# script lives in .GC/update/ ; install path is recorded relatively");
|
||||
s.AppendLine("HERE=$(CDPATH= cd -- \"$(dirname -- \"$0\")\" && pwd)");
|
||||
s.AppendLine("DST=$(CDPATH= cd -- \"$HERE/../..\" && 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("if [ -z \"$NEWNAME\" ] || [ -z \"$NEWVER\" ]; then");
|
||||
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("NEW=\"$DST/$NEWNAME\"");
|
||||
s.AppendLine("if [ ! -e \"$NEW\" ]; then");
|
||||
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("# launch new version first");
|
||||
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");
|
||||
@@ -522,18 +513,28 @@ public static class LauncherUpdater
|
||||
s.AppendLine("@echo off");
|
||||
s.AppendLine("chcp 65001 >nul 2>&1");
|
||||
s.AppendLine("set \"HERE=%~dp0\"");
|
||||
s.AppendLine("set \"DST=%~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 not exist \"%DST%\\%NEWNAME%\" (echo new package missing, 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%\"");
|
||||
@@ -574,10 +575,10 @@ public static class LauncherUpdater
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 把 staging 里的新版搬到当前目录,与旧版并列。
|
||||
/// 返回新版包名(GC-<版本>-<平台>.app/.exe)。.GC 绝不覆盖。
|
||||
/// 把 staging 里的新版搬入下载目录的 payload。
|
||||
/// 返回新版包名(GC-<版本>-<平台>.app/.exe)。
|
||||
/// </summary>
|
||||
private static string? MoveToInstallDir(string staging, string installDir, string latest)
|
||||
private static string? MoveToPayload(string staging, string payload)
|
||||
{
|
||||
try
|
||||
{
|
||||
@@ -585,7 +586,7 @@ public static class LauncherUpdater
|
||||
{
|
||||
var name = Path.GetFileName(entry);
|
||||
if (string.Equals(name, ".GC", StringComparison.OrdinalIgnoreCase)) continue;
|
||||
var dest = Path.Combine(installDir, name);
|
||||
var dest = Path.Combine(payload, name);
|
||||
|
||||
if (Directory.Exists(dest)) Directory.Delete(dest, true);
|
||||
else if (File.Exists(dest)) File.Delete(dest);
|
||||
File renamed without changes.
@@ -14,9 +14,9 @@ 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();
|
||||
@@ -15,7 +15,7 @@ namespace GC.Services;
|
||||
/// 取**最快且内容可用**的那个作为本次下载源;探测结果缓存一段时间,
|
||||
/// 避免每次点下载都重新测速。
|
||||
/// </summary>
|
||||
public sealed class SourceSelector
|
||||
public sealed class SourceSelector : ISourceSelector
|
||||
{
|
||||
private static readonly HttpClient Http = CreateHttp();
|
||||
|
||||
@@ -17,7 +17,7 @@ namespace GC.Services;
|
||||
/// .GC/model/<id>,本次启动立即生效。任何失败都保留本地已装模型。
|
||||
/// 启动器更新由 LauncherUpdater / LauncherUpdateFlow 独立负责,不在这里。
|
||||
/// </summary>
|
||||
public sealed class UpdateService
|
||||
public sealed class UpdateService : IUpdateService
|
||||
{
|
||||
private readonly AppPaths _paths;
|
||||
private readonly SettingsService _settings;
|
||||
@@ -35,55 +35,6 @@ public sealed class UpdateService
|
||||
/// <summary>换源:测速选出最快的一个后,用它的 remote 覆盖当前实例。</summary>
|
||||
public void UseRemote(IModelRemote remote) => _remote = remote;
|
||||
|
||||
private static string? _versionOverride;
|
||||
|
||||
public static string CurrentLauncherVersion
|
||||
{
|
||||
get
|
||||
{
|
||||
if (!string.IsNullOrWhiteSpace(_versionOverride)) return _versionOverride!;
|
||||
|
||||
// 用**本程序集**的版本,而不是 GetEntryAssembly()。
|
||||
// EntryAssembly 在宿主(dotnet run / 测试宿主 / 单文件解包)下可能指向别的程序,
|
||||
// 读出来会变成 1.0.0,导致「明明是最新版却一直提示有更新」。
|
||||
var asm = typeof(UpdateService).Assembly;
|
||||
var v = asm.GetName().Version;
|
||||
if (v == null || (v.Major == 0 && v.Minor == 0 && v.Build == 0))
|
||||
{
|
||||
// 兜底:读 InformationalVersion(Directory.Build.props 里的 <Version>)
|
||||
var info = asm.GetCustomAttribute<AssemblyInformationalVersionAttribute>()?.InformationalVersion;
|
||||
if (!string.IsNullOrWhiteSpace(info))
|
||||
{
|
||||
var core = info!.Split('+')[0].Trim();
|
||||
if (Version.TryParse(core, out var iv))
|
||||
v = iv;
|
||||
}
|
||||
}
|
||||
if (v == null) return "0.0.0";
|
||||
return $"{Math.Max(0, v.Major)}.{Math.Max(0, v.Minor)}.{Math.Max(0, v.Build)}";
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>测试 / 自检时临时指定版本号。</summary>
|
||||
public static void OverrideLauncherVersion(string? version) => _versionOverride = version;
|
||||
|
||||
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>
|
||||
/// 同步版本(无法测速时用):按设置里的仓库地址映射到内置源。
|
||||
/// 真正带测速的入口是 <see cref="CreateRemoteAsync"/>。
|
||||
File renamed without changes.
File renamed without changes.
@@ -5,7 +5,9 @@ VisualStudioVersion = 17.0.31903.59
|
||||
MinimumVisualStudioVersion = 10.0.40219.1
|
||||
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "GC-BOOT", "GC-BOOT", "{827E0CD3-B72D-47B6-A68D-7590B98EB39B}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GC", "GC-BOOT\GC-BOOT.csproj", "{2E3BE2DB-1C4B-4EA0-9523-43EE910BD54C}"
|
||||
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "GC-DOWNLOAD", "GC-DOWNLOAD", "{BCA2AA3E-F98F-43A1-9D31-239103C303F7}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GC-BOOT", "GC-BOOT\GC-BOOT.csproj", "{2E3BE2DB-1C4B-4EA0-9523-43EE910BD54C}"
|
||||
EndProject
|
||||
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "GC", "GC", "{3E72BF5C-0B5E-D5BD-DCAE-6B991004B4A5}"
|
||||
EndProject
|
||||
@@ -35,6 +37,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GC.Core", "GC\src\GC.Core.c
|
||||
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
|
||||
Global
|
||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||
Debug|Any CPU = Debug|Any CPU
|
||||
@@ -117,18 +121,18 @@ Global
|
||||
{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
|
||||
{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
|
||||
EndGlobalSection
|
||||
GlobalSection(SolutionProperties) = preSolution
|
||||
HideSolutionNode = FALSE
|
||||
@@ -145,6 +149,7 @@ Global
|
||||
{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}
|
||||
{98F52FEA-43B5-4FE1-97A9-AF644AAFEFA3} = {BCA2AA3E-F98F-43A1-9D31-239103C303F7}
|
||||
{6C38EF76-7D14-0C76-0B88-84F29EAA96CD} = {62B8A37E-7066-D91A-6443-87D4E6CE63FE}
|
||||
EndGlobalSection
|
||||
EndGlobal
|
||||
@@ -38,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; }
|
||||
|
||||
@@ -11,11 +11,11 @@ namespace GC.Services;
|
||||
/// GC(.exe | .app/...)
|
||||
/// .GC/
|
||||
/// settings.json 设置与已安装版本记录
|
||||
/// model/ 模型(启动时下载;model 目录也在 .GC 里)
|
||||
/// model/ 模型(启动时下载)
|
||||
/// cache/ 下载缓存 / 原子替换暂存
|
||||
/// update/ 待下次启动应用的启动器更新包
|
||||
/// </code>
|
||||
/// 开发态同样使用 .GC/model,并自动把仓库 model/ 的可分发部分同步进去。
|
||||
/// 开发态同样使用仓库根 .GC/model,并自动同步仓库 model/ 的可分发部分。
|
||||
/// EMS_MODELS / EMS_DATA / EMS_HOME 可显式覆盖。
|
||||
/// </summary>
|
||||
public sealed class AppPaths
|
||||
@@ -31,7 +31,7 @@ public sealed class AppPaths
|
||||
/// <summary>.GC 目录。</summary>
|
||||
public string HomeRoot { get; private init; } = "";
|
||||
|
||||
/// <summary>模型库,恒为 <HomeRoot>/model。</summary>
|
||||
/// <summary>模型库。</summary>
|
||||
public string ModelRoot { get; private init; } = "";
|
||||
|
||||
/// <summary>兼容旧代码:数据目录即 .GC。</summary>
|
||||
@@ -54,7 +54,8 @@ public sealed class AppPaths
|
||||
//
|
||||
// 重要:源码版由 `dotnet run` 启动时 Environment.ProcessPath 指向 dotnet 宿主,
|
||||
// 直接用它会把 .GC 与更新包写到 dotnet 安装目录去,所以必须先识别源码版。
|
||||
var repoRoot = Environment.GetEnvironmentVariable("EMS_HOME");
|
||||
var explicitHome = Environment.GetEnvironmentVariable("EMS_HOME");
|
||||
var repoRoot = explicitHome;
|
||||
if (string.IsNullOrWhiteSpace(repoRoot) || !Directory.Exists(repoRoot))
|
||||
repoRoot = FindRepoRoot(baseDir);
|
||||
var isDev = !string.IsNullOrEmpty(repoRoot) &&
|
||||
@@ -63,9 +64,13 @@ public sealed class AppPaths
|
||||
string installDir;
|
||||
if (isDev)
|
||||
{
|
||||
// 源码版:安装目录 = 仓库根,.GC 与更新都放这里
|
||||
// 源码版:安装目录 = 仓库根
|
||||
installDir = repoRoot!;
|
||||
}
|
||||
else if (!string.IsNullOrWhiteSpace(explicitHome) && Directory.Exists(explicitHome))
|
||||
{
|
||||
installDir = explicitHome;
|
||||
}
|
||||
else
|
||||
{
|
||||
// 发布版:运行目录 = **放着 .app / .exe 的那一层**,不是 .app 内部的 Contents/MacOS。
|
||||
@@ -120,7 +125,7 @@ public sealed class AppPaths
|
||||
var envModels = Environment.GetEnvironmentVariable("EMS_MODELS");
|
||||
var modelRoot = !string.IsNullOrWhiteSpace(envModels)
|
||||
? envModels!
|
||||
: Path.Combine(home, "model"); // 统一:model 目录在 .GC 里
|
||||
: Path.Combine(home, "model");
|
||||
|
||||
return new AppPaths
|
||||
{
|
||||
@@ -140,7 +145,6 @@ public sealed class AppPaths
|
||||
Directory.CreateDirectory(dir);
|
||||
var probe = Path.Combine(dir, ".write-test");
|
||||
File.WriteAllText(probe, "ok");
|
||||
File.Delete(probe);
|
||||
return true;
|
||||
}
|
||||
catch
|
||||
|
||||
@@ -10,15 +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 SourceSelector Selector { get; }
|
||||
public ISourceSelector Selector { get; }
|
||||
public ILauncherUpdateService LauncherUpdates { get; }
|
||||
public IDownloadModule DownloadModule { get; }
|
||||
|
||||
private AppServices(AppPaths paths)
|
||||
{
|
||||
@@ -26,12 +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);
|
||||
Selector = new SourceSelector();
|
||||
Updates = new UpdateService(paths, Settings, UpdateService.CreateRemote(Settings.Current));
|
||||
Selector = DownloadModule.Selector;
|
||||
Updates = DownloadModule.Updates;
|
||||
LauncherUpdates = DownloadModule.LauncherUpdates;
|
||||
}
|
||||
|
||||
public static AppServices Create()
|
||||
|
||||
@@ -21,7 +21,7 @@ public sealed class Contributor
|
||||
/// </summary>
|
||||
private static readonly Dictionary<string, string> DisplayNames = new(StringComparer.OrdinalIgnoreCase)
|
||||
{
|
||||
["2509_92447106"] = "Morris"
|
||||
["Morris_1"] = "Morris"
|
||||
};
|
||||
|
||||
/// <summary>头像地址:GitCode 用邮箱哈希拼头像,取不到时返回 null。</summary>
|
||||
@@ -63,13 +63,13 @@ public static class ContributorsService
|
||||
public static string BuildUrl(string repository)
|
||||
{
|
||||
var raw = string.IsNullOrWhiteSpace(repository)
|
||||
? GitCodeRemote.DefaultRepository : repository.Trim();
|
||||
? SourcePreset.GitCode.HomeUrl : repository.Trim();
|
||||
if (!Uri.TryCreate(raw, UriKind.Absolute, out var uri))
|
||||
return "https://api.gitcode.com/api/v5/repos/2509_92447106/GC/contributors";
|
||||
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/2509_92447106/GC/contributors";
|
||||
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];
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
@@ -52,7 +52,7 @@ public static class LauncherUpdateFlow
|
||||
var progress = new Progress<UpdateProgressInfo>(p =>
|
||||
progressWindow.Report(p.Value, p.Stage));
|
||||
|
||||
var result = await LauncherUpdater.DownloadAsync(
|
||||
var result = await services.LauncherUpdates.DownloadAsync(
|
||||
services.Paths, services.Updates.Remote, progress);
|
||||
|
||||
if (result.State == UpdateRunState.Failed)
|
||||
@@ -68,7 +68,7 @@ public static class LauncherUpdateFlow
|
||||
progressWindow.Report(1, $"v{result.Version} 下载完成,正在重启…");
|
||||
|
||||
// 4. 安排替换(下次启动生效 / 脚本接管重启)
|
||||
var scheduled = LauncherUpdater.ScheduleApply(
|
||||
var scheduled = services.LauncherUpdates.ScheduleApply(
|
||||
services.Paths, result.PackageName ?? "");
|
||||
|
||||
if (!scheduled)
|
||||
|
||||
@@ -18,6 +18,12 @@ public sealed class SettingsService
|
||||
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;
|
||||
}
|
||||
@@ -28,7 +34,7 @@ public sealed class SettingsService
|
||||
/// 老配置里的自定义源会被清理掉。
|
||||
/// </summary>
|
||||
public const string DefaultSourceId = "gitcode";
|
||||
public const string DefaultSourceUrl = "https://gitcode.com/2509_92447106/GC";
|
||||
public const string DefaultSourceUrl = "https://gitcode.com/Morris_1/GC";
|
||||
|
||||
private void SeedDefaultSource()
|
||||
{
|
||||
|
||||
@@ -53,12 +53,12 @@ public sealed class SourcePreset
|
||||
{
|
||||
Id = "gitcode",
|
||||
Name = "GitCode",
|
||||
HomeUrl = "https://gitcode.com/2509_92447106/GC",
|
||||
HomeUrl = "https://gitcode.com/Morris_1/GC",
|
||||
ApiBase = "https://api.gitcode.com/api/v5",
|
||||
RawBase = "https://gitcode.com",
|
||||
Kind = "gitcode",
|
||||
RawStyle = "plain",
|
||||
Owner = "2509_92447106",
|
||||
Owner = "Morris_1",
|
||||
Repo = "GC",
|
||||
Branch = "main"
|
||||
};
|
||||
|
||||
@@ -29,10 +29,10 @@ public partial class AboutViewModel : ObservableObject
|
||||
public string AppName => "Morris GC";
|
||||
|
||||
/// <summary>启动器版本号,如 v1.0.2。</summary>
|
||||
public string VersionText => "v" + UpdateService.CurrentLauncherVersion;
|
||||
public string VersionText => "v" + LauncherRuntimeInfo.CurrentLauncherVersion;
|
||||
|
||||
/// <summary>当前平台标识,如 win-x64 / osx-arm64。</summary>
|
||||
public string PlatformText => UpdateService.CurrentRid;
|
||||
public string PlatformText => LauncherRuntimeInfo.CurrentRid;
|
||||
|
||||
public string RepositoryText => _services.Settings.Current.UpdateRepository;
|
||||
|
||||
|
||||
@@ -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 = "";
|
||||
@@ -264,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);
|
||||
}
|
||||
@@ -291,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();
|
||||
|
||||
@@ -46,8 +46,8 @@ public partial class MainViewModel : ObservableObject
|
||||
|
||||
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)
|
||||
{
|
||||
@@ -143,7 +143,7 @@ public partial class MainViewModel : ObservableObject
|
||||
{
|
||||
var fastest = await _services.Selector.PickFastestAsync(
|
||||
force, default);
|
||||
_services.Updates.UseRemote(SourceSelector.CreateRemote(fastest));
|
||||
_services.Updates.UseRemote(_services.DownloadModule.CreateRemote(fastest));
|
||||
var lat = _services.Selector.LastLatency;
|
||||
UpdateDetail = "源:" + fastest.Name +
|
||||
(lat.Count > 0 ? "(" + string.Join(",", lat.Select(kv =>
|
||||
@@ -155,7 +155,7 @@ public partial class MainViewModel : ObservableObject
|
||||
}
|
||||
|
||||
// 启动器:读 Release latest 版本号,与当前运行版本不同就弹窗询问
|
||||
var latest = await LauncherUpdater.CheckAsync(_services.Updates.Remote);
|
||||
var latest = await _services.LauncherUpdates.CheckAsync(_services.Updates.Remote);
|
||||
if (latest != null)
|
||||
{
|
||||
var agreed = LauncherUpdateHandler != null &&
|
||||
|
||||
@@ -15,6 +15,7 @@
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="../../../GC.Core.csproj" />
|
||||
<ProjectReference Include="../../../../../GC-DOWNLOAD/GC-DOWNLOAD.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -12,6 +12,7 @@ using Avalonia.Headless;
|
||||
using Avalonia.Threading;
|
||||
using Avalonia.VisualTree;
|
||||
using GC;
|
||||
using GC.Download;
|
||||
using GC.Services;
|
||||
using GC.ViewModels;
|
||||
using GC.Views;
|
||||
@@ -29,6 +30,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 +78,10 @@ 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");
|
||||
Json.Write(Path.Combine(remote, "version.json"), fixtureVersion);
|
||||
foreach (var dir in Directory.GetDirectories(Path.Combine(repoRoot, "model")))
|
||||
{
|
||||
var id = Path.GetFileName(dir);
|
||||
@@ -93,7 +98,7 @@ internal static class Program
|
||||
// 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 +116,13 @@ internal static class Program
|
||||
|
||||
Console.WriteLine($"运行目录: {paths.HomeRoot}");
|
||||
Console.WriteLine($"模型库: {paths.ModelRoot}");
|
||||
Check(paths.ModelRoot == modelRoot, ".GC/model 是下载目标");
|
||||
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/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,7 +135,7 @@ 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, "版本未变时不重复下载");
|
||||
|
||||
@@ -142,15 +149,15 @@ internal static class Program
|
||||
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 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)),
|
||||
"新版本本次启动立即生效");
|
||||
|
||||
// 4) 启动器新版:用 LauncherUpdater 下载到当前目录(与旧版并列)
|
||||
var rid = UpdateService.CurrentRid;
|
||||
Console.WriteLine($"当前平台: {rid},启动器版本: {UpdateService.CurrentLauncherVersion}");
|
||||
var rid = LauncherRuntimeInfo.CurrentRid;
|
||||
Console.WriteLine($"当前平台: {rid},启动器版本: {LauncherRuntimeInfo.CurrentLauncherVersion}");
|
||||
var stage = Path.Combine(tmp, "launcher-stage");
|
||||
Directory.CreateDirectory(stage);
|
||||
File.WriteAllText(Path.Combine(stage, "GC-9.9.9-" + LauncherUpdater.PlatformLabel + ".exe"),
|
||||
@@ -165,12 +172,17 @@ internal static class Program
|
||||
var oldName = "GC-1.0.0-" + LauncherUpdater.PlatformLabel + ".exe";
|
||||
File.WriteAllText(Path.Combine(paths.InstallDirectory, oldName), "old launcher");
|
||||
|
||||
var dl = LauncherUpdater.DownloadAsync(paths, updater.Remote, null).GetAwaiter().GetResult();
|
||||
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.InstallDirectory, 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)),
|
||||
"旧版仍在(删除由替换脚本在重启后做)");
|
||||
|
||||
@@ -191,7 +203,7 @@ internal static class Program
|
||||
// 6) 断网兜底:保留本地模型,不清空
|
||||
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")),
|
||||
|
||||
@@ -11,10 +11,10 @@
|
||||
- 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>
|
||||
- 更新仓库:<https://gitcode.com/Morris_1/GC>,模型目录 <https://gitcode.com/Morris_1/GC/tree/main/model>
|
||||
|
||||
## 运行目录(发布包里就长这样)
|
||||
|
||||
Windows 用 `.\build.ps1`(参数相同);PowerShell 实现位于 `buildps1/`,不依赖 Git Bash 或 WSL。
|
||||
```
|
||||
<安装目录>/
|
||||
GC.exe | GC.app/
|
||||
@@ -36,7 +36,7 @@
|
||||
| 启动器 | 下载对应平台 zip 到 `.GC/update/payload`,写 `pending.json` | **下次启动时应用**(独立脚本覆盖程序并重启) |
|
||||
|
||||
- 默认更新仓库写在 `.GC/settings.json` 的 `updateRepository`:
|
||||
`https://gitcode.com/2509_92447106/GC`(也可换成自己的仓库或 `.../tree/main/model` 地址)
|
||||
`https://gitcode.com/Morris_1/GC`(也可换成自己的仓库或 `.../tree/main/model` 地址)
|
||||
- 版本来自仓库根 `version.json`(由 `./build.sh stamp` 生成):模型版本 = **模型包内容指纹**,
|
||||
所以**改了模型文件,版本号自动变**;启动器版本 = 构建版本。
|
||||
- `settings.json` 记录 `installedModelVersions` / `pendingLauncherVersion` / `lastUpdateCheck`。
|
||||
@@ -44,8 +44,8 @@
|
||||
- 设置页可关闭自动更新;状态条可手动「检查更新」(忽略开关强制检查)。
|
||||
- 离线教室:把仓库(含 `version.json` + `model/`)拷到 U 盘,在 `settings.json` 填
|
||||
`updateLocalRoot` 指向它,即可完全离线更新。
|
||||
- 发新版:把 `dist/GC-<rid>.zip` 上传到 Release / 仓库 `dist/`,把直链填进 `version.json`
|
||||
对应平台的 `url`(`./build.sh publish` 会生成 zip 并自动写入 `sha256` / `size`)。
|
||||
- 发新版:运行 `./build.sh build`,把生成的 `dist/GC-<版本>-*.zip` 上传到 Release / 仓库 `dist/`,
|
||||
把直链填进 `version.json` 对应平台的 `url`(构建会生成 zip 并自动写入 `sha256` / `size`)。
|
||||
更新包只含程序文件,**不会覆盖 `.GC/` 里的模型与设置**。
|
||||
|
||||
## 目录结构
|
||||
@@ -56,6 +56,8 @@ Repository/
|
||||
├── Directory.Build.props # 公共构建属性
|
||||
├── version.json # ★ 自动生成的版本清单(推送到仓库后才生效)
|
||||
├── build.sh / build.ps1 # 构建脚本
|
||||
├── buildsh/ # POSIX shell 构建实现
|
||||
├── buildps1/ # 原生 PowerShell 构建实现
|
||||
├── GC/ # 启动器主要代码
|
||||
│ └── src/
|
||||
│ ├── GC.Core.csproj
|
||||
@@ -67,6 +69,8 @@ Repository/
|
||||
│ ├── GC-BOOT.csproj
|
||||
│ ├── Program.cs
|
||||
│ └── app.manifest
|
||||
├── GC-DOWNLOAD/ # 模型、源仓库与启动器下载更新实现
|
||||
│ └── GC-DOWNLOAD.csproj
|
||||
├── GC-DRAW/PlayerWindow.cs # 通用模型窗口宿主;实际绘制由模型提供
|
||||
├── model/ # ★ 模型的一切
|
||||
│ ├── version.json # 与根 version.json 相同(便于按 model/ 地址读取)
|
||||
@@ -88,28 +92,32 @@ Repository/
|
||||
## 构建与运行
|
||||
|
||||
```bash
|
||||
./build.sh build # 编译整个解决方案
|
||||
./build.sh models # 编译模型 dll + 生成封面 + 自动打版本
|
||||
./build.sh stamp # 只重新生成 version.json 与模型版本
|
||||
./build.sh run # 运行
|
||||
./build.sh test # 离屏校验:页面 + 真实加载模型窗口截图
|
||||
./build.sh build # 完整三平台发布:编译启动器、准备运行目录并生成更新包 ZIP
|
||||
./build.sh check # 编译、自检、离屏渲染及发布 ZIP 完整性检查;通常在 build 后运行
|
||||
./build.sh models # 编译模型 dll、生成封面并更新版本清单
|
||||
./build.sh stamp # 只重新生成根目录与 model/ 下的 version.json
|
||||
./build.sh run # 以 Debug 配置运行启动器
|
||||
./build.sh test # 运行离屏校验并将截图写入 build/screenshots/
|
||||
./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 pack-models # 编译模型并打包到 dist/models-<版本>.zip
|
||||
./build.sh pack-launcher # 将已有平台发布目录打成启动器更新 ZIP
|
||||
./build.sh doctor # 显示 dotnet 环境信息
|
||||
./build.sh dist # 列出 dist/ 中的产物
|
||||
./build.sh clean # 清理 build/ 与 dist/ 等构建产物
|
||||
```
|
||||
|
||||
`build` 是完整发布入口,不是单纯的解决方案编译;`check` 会检查至少三个版本化发布 ZIP。
|
||||
需要指定版本时,可追加 `-version=<版本>`(或 `--version=<版本>`),脚本会同步更新 `Directory.Build.props`。
|
||||
Windows 用 `.\build.ps1`(参数相同)。
|
||||
|
||||
| 产物 | 平台 |
|
||||
| --- | --- |
|
||||
| `dist/mac-arm64/GC.app` | macOS Apple Silicon |
|
||||
| `dist/win-x64/GC.exe` | Windows x64 |
|
||||
| `dist/win-arm64/GC.exe` | Windows on ARM |
|
||||
| `dist/GC-<版本>-mac-arm64.zip` | macOS Apple Silicon 应用包 |
|
||||
| `dist/GC-<版本>-win-amd64.zip` | Windows x64 单文件启动器 |
|
||||
| `dist/GC-<版本>-win-arm64.zip` | Windows on ARM 单文件启动器 |
|
||||
|
||||
均为自包含单文件启动器,**发布包内不含模型**。改完模型:
|
||||
`./build.sh models` → 把 `version.json` 和 `model/` 推送到 gitcode → 客户端下次启动自动更新。
|
||||
Windows 产物是自包含单文件启动器;macOS 产物是 `.app` 的 ZIP。**发布包内不含模型**。
|
||||
改完模型后运行 `./build.sh models`,再把根目录 `version.json` 和 `model/` 推送到 gitcode,客户端下次启动时自动更新。
|
||||
|
||||
## 模型契约
|
||||
|
||||
|
||||
@@ -1,75 +1,8 @@
|
||||
# ---------------------------------------------------------------------------
|
||||
# GC 构建入口(Windows PowerShell,薄封装)
|
||||
# 实际代码在 buildsh/ 里。Windows 上若无 sh,则走内置的最小实现。
|
||||
# .\build.ps1 build | check | models | stamp | run | test | clean | doctor
|
||||
# ---------------------------------------------------------------------------
|
||||
param(
|
||||
[Parameter(Position = 0)]
|
||||
[ValidateSet('build','check','models','stamp','pack-models','pack-launcher',
|
||||
'run','test','update-test','clean','doctor','dist')]
|
||||
[string]$Task = 'build'
|
||||
)
|
||||
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$Root = $PSScriptRoot
|
||||
Set-Location $Root
|
||||
$env:AVALONIA_TELEMETRY_OPTOUT = '1'
|
||||
|
||||
$AppProj = 'GC-BOOT/GC-BOOT.csproj'
|
||||
$TestProj = 'GC/src/test/dotnet/GC.Tests/GC.Tests.csproj'
|
||||
$StampProj= 'model/_engine/VersionStamp/VersionStamp.csproj'
|
||||
$Sln = 'GC.sln'
|
||||
$Version = ([regex]::Match((Get-Content Directory.Build.props -Raw), '<Version>(.*?)</Version>')).Groups[1].Value
|
||||
if (-not $Version) { $Version = '1.0.0' }
|
||||
New-Item -ItemType Directory -Force -Path "$Root/build/logs" | Out-Null
|
||||
|
||||
# 优先复用 buildsh 的 shell 实现(Git Bash / WSL / sh 可用时)
|
||||
$sh = Get-Command sh -ErrorAction SilentlyContinue
|
||||
if ($sh) {
|
||||
& $sh.Source "$Root/build.sh" $Task
|
||||
exit $LASTEXITCODE
|
||||
try {
|
||||
& (Join-Path $PSScriptRoot 'buildps1/build.ps1') @args
|
||||
exit 0
|
||||
}
|
||||
|
||||
function Stamp { dotnet run --project $StampProj -c Release -- $Root $Version }
|
||||
function Build-Models {
|
||||
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 (-not $proj) { return }
|
||||
dotnet build $proj.FullName -c Release
|
||||
}
|
||||
Stamp
|
||||
}
|
||||
|
||||
switch ($Task) {
|
||||
'build' {
|
||||
Write-Host '==> 编译三平台(进度见 buildsh/lib/progress.sh,建议用 Git Bash 运行 ./build.sh build)'
|
||||
Remove-Item -Recurse -Force "$Root/dist" -ErrorAction SilentlyContinue
|
||||
New-Item -ItemType Directory -Force -Path "$Root/dist" | Out-Null
|
||||
Stamp
|
||||
foreach ($rid in @('osx-arm64','win-x64','win-arm64')) {
|
||||
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/dist/$rid"
|
||||
}
|
||||
Write-Host '==> 完成(详细打包请用 ./build.sh build)'
|
||||
}
|
||||
'check' {
|
||||
dotnet build $Sln -c Debug
|
||||
$env:EMS_SELFTEST = '1'; dotnet run --project $AppProj -c Debug --no-build; Remove-Item Env:\EMS_SELFTEST
|
||||
dotnet run --project $TestProj -c Debug --no-build -- "$Root/build/screenshots"
|
||||
}
|
||||
'models' { Build-Models }
|
||||
'stamp' { Stamp }
|
||||
'pack-models' { Build-Models }
|
||||
'pack-launcher' { Write-Host '请用 ./build.sh pack-launcher' }
|
||||
'run' { dotnet run --project $AppProj -c Debug }
|
||||
'test' { dotnet run --project $TestProj -c Debug -- "$Root/build/screenshots" }
|
||||
'update-test' { dotnet run --project $TestProj -c Debug -- '--update-test' $Root }
|
||||
'clean' { Remove-Item -Recurse -Force "$Root/build","$Root/dist" -ErrorAction SilentlyContinue; Write-Host '==> 已清理' }
|
||||
'doctor' { dotnet --info | Select-Object -First 20 }
|
||||
'dist' { Get-ChildItem "$Root/dist" -ErrorAction SilentlyContinue }
|
||||
catch {
|
||||
[Console]::Error.WriteLine($_)
|
||||
exit 1
|
||||
}
|
||||
@@ -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,267 @@
|
||||
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-VersionStamp {
|
||||
Write-Host '==> 自动计算模型版本并生成 version.json'
|
||||
Invoke-LoggedDotNet -Name 'stamp' -Arguments @(
|
||||
'run', '--project', $script:StampProject, '-c', 'Release', '--',
|
||||
$script:BuildRoot, $script:BuildVersion
|
||||
)
|
||||
}
|
||||
|
||||
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') | 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/settings.json
|
||||
.GC/model/ 本目录(下载的模型)
|
||||
.GC/cache/ 下载暂存
|
||||
.GC/update/ 待下次启动应用的启动器更新
|
||||
'@
|
||||
$settingsPath = Join-Path $destination '.GC/settings.json'
|
||||
if (-not (Test-Path $settingsPath)) {
|
||||
Set-Content -Path $settingsPath -Encoding UTF8 -Value @'
|
||||
{
|
||||
"language": "auto",
|
||||
"theme": "light",
|
||||
"renderFps": 30,
|
||||
"memoryMb": 2048,
|
||||
"autoUpdateOnStartup": 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
|
||||
)
|
||||
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' })) {
|
||||
$sourceDir = Join-Path $dist $platform.Rid
|
||||
if (-not (Test-Path $sourceDir)) { continue }
|
||||
$executable = Get-ChildItem $sourceDir -Filter '*.exe' | Select-Object -First 1
|
||||
if ($null -eq $executable) { continue }
|
||||
Copy-Item $executable.FullName (Join-Path $dist "GC-$script:BuildVersion-$($platform.Label).exe") -Force
|
||||
}
|
||||
|
||||
$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 }
|
||||
}
|
||||
|
||||
Get-ChildItem $dist | Where-Object { $_.Name -like "GC-$script:BuildVersion-*.exe" -or $_.Name -like "GC-$script:BuildVersion-*.app" } | ForEach-Object {
|
||||
$zipPath = Join-Path $dist ($_.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
|
||||
}
|
||||
}
|
||||
|
||||
Remove-Item (Join-Path $dist "GC-$script:BuildVersion-*.exe") -Force -ErrorAction SilentlyContinue
|
||||
Remove-Item (Join-Path $dist "GC-$script:BuildVersion-*.app") -Recurse -Force -ErrorAction SilentlyContinue
|
||||
Remove-IntermediateDirectories
|
||||
Invoke-VersionStamp
|
||||
Write-Host '==> dist 可发布 zip:'
|
||||
Get-ChildItem $dist -Filter "GC-$script:BuildVersion-*.zip" | Select-Object Name, Length
|
||||
}
|
||||
|
||||
function Remove-IntermediateDirectories {
|
||||
foreach ($name in @('win-x64', 'win-arm64', 'mac-arm64')) {
|
||||
Remove-Item (Join-Path $script:BuildRoot "dist/$name") -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-x64' $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-x64'
|
||||
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') -Filter "GC-$script:BuildVersion-*.zip" | Select-Object Name, Length
|
||||
}
|
||||
finally { Complete-BuildProgress }
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
$script:ProgressSteps = @()
|
||||
$script:ProgressIndex = 0
|
||||
$script:ProgressActivity = 'GC 构建'
|
||||
|
||||
function Initialize-BuildProgress {
|
||||
param([string[]]$Steps)
|
||||
$script:ProgressSteps = $Steps
|
||||
$script:ProgressIndex = 0
|
||||
Write-Progress -Activity $script:ProgressActivity -Status '准备' -PercentComplete 0
|
||||
}
|
||||
|
||||
function Start-BuildStep {
|
||||
param([string]$Name)
|
||||
$script:ProgressIndex++
|
||||
$percent = [math]::Min(99, [int](($script:ProgressIndex - 1) * 100 / [math]::Max(1, $script:ProgressSteps.Count)))
|
||||
Write-Progress -Activity $script:ProgressActivity -Status $Name -PercentComplete $percent
|
||||
Write-Host "==> $Name"
|
||||
}
|
||||
|
||||
function Complete-BuildStep {
|
||||
$percent = [int]($script:ProgressIndex * 100 / [math]::Max(1, $script:ProgressSteps.Count))
|
||||
Write-Progress -Activity $script:ProgressActivity -Status '进行中' -PercentComplete $percent
|
||||
}
|
||||
|
||||
function Complete-BuildProgress {
|
||||
Write-Progress -Activity $script:ProgressActivity -Completed
|
||||
}
|
||||
@@ -44,7 +44,7 @@ prepare_runtime_layout() {
|
||||
mkdir -p "$DEST/.GC/model" "$DEST/.GC/cache" "$DEST/.GC/update"
|
||||
cat > "$DEST/.GC/model/README.txt" <<'TXT'
|
||||
模型库目录(.GC/model/)
|
||||
启动时程序会读取 gitcode 仓库的 version.json,把最新版模型下载到这里。
|
||||
启动时程序会读取 GitCode 仓库的 version.json,把最新版模型下载到这里。
|
||||
离线使用也可以手动放入 <模型id>/<模型id>.json + <模型id>/<模型id>.model/。
|
||||
|
||||
运行目录:
|
||||
@@ -62,7 +62,7 @@ TXT
|
||||
"renderFps": 30,
|
||||
"memoryMb": 2048,
|
||||
"autoUpdateOnStartup": true,
|
||||
"updateRepository": "https://gitcode.com/2509_92447106/GC",
|
||||
"updateRepository": "https://gitcode.com/Morris_1/GC",
|
||||
"updateManifestUrl": "",
|
||||
"updateLocalRoot": "",
|
||||
"installedModelVersions": {},
|
||||
|
||||
+1
-1
@@ -5,7 +5,7 @@
|
||||
|
||||
> 模型相关的一切都在 `model/` 里:共享引擎源码 `model/_engine/`、契约源码 `model/_sdk/`、
|
||||
> 每个模型自己的源码 `model/<id>/src/`,编译产物与数据 `model/<id>/<id>.model/`。
|
||||
> 仓库根目录只有 `src/`(启动器)和 `model/`,没有任何旁路目录。
|
||||
> 仓库根还包含 `GC-DOWNLOAD/` 下载更新项目;这里的 `model/` 仍独立保存模型源码与可分发内容。
|
||||
|
||||
- 发布态模型库在 **`<可执行文件>/.GC/model/`**;开发态直接用仓库根 `model/`
|
||||
- 优先级:`EMS_MODELS` 环境变量 → 开发态仓库根 `model/` → 发布态 `.GC/model/`
|
||||
|
||||
@@ -10,7 +10,7 @@ using System.Text.Json.Nodes;
|
||||
// 仓库根 version.json 与 model/version.json(内容相同,便于两种源地址读取)。
|
||||
|
||||
// 仓库地址(编译产物的 Release 也发在这里):与启动器默认 updateRepository 保持一致。
|
||||
const string Repository = "https://gitcode.com/2509_92447106/GC";
|
||||
const string Repository = "https://gitcode.com/Morris_1/GC";
|
||||
|
||||
var root = args.Length > 0 ? Path.GetFullPath(args[0]) : Directory.GetCurrentDirectory();
|
||||
var launcherVersion = args.Length > 1 && !string.IsNullOrWhiteSpace(args[1]) ? args[1] : "1.0.0";
|
||||
|
||||
@@ -25,6 +25,6 @@
|
||||
"button": "#9FB4D4",
|
||||
"frame": "#0A1524"
|
||||
},
|
||||
"updatedAt": "2026-11-14T05:09:30Z",
|
||||
"build": "257dcfd58f"
|
||||
"updatedAt": "2026-11-14T10:53:39Z",
|
||||
"build": "d3eb662a36"
|
||||
}
|
||||
@@ -18,7 +18,7 @@
|
||||
],
|
||||
"dataDir": "earth-geography.model",
|
||||
"version": "1.8",
|
||||
"updatedAt": "2026-11-14T05:09:30Z",
|
||||
"updatedAt": "2026-11-14T10:53:39Z",
|
||||
"chrome": {
|
||||
"titleBar": "#0C1828",
|
||||
"titleBorder": "#1B2740",
|
||||
@@ -26,5 +26,5 @@
|
||||
"button": "#9FB4D4",
|
||||
"frame": "#0A1524"
|
||||
},
|
||||
"build": "3a10607730"
|
||||
"build": "d5ad961ed1"
|
||||
}
|
||||
@@ -24,7 +24,7 @@
|
||||
"preview": "preview.png",
|
||||
"apiVersion": 1,
|
||||
"version": "1.6",
|
||||
"updatedAt": "2026-11-14T05:09:30Z",
|
||||
"updatedAt": "2026-11-14T10:53:39Z",
|
||||
"chrome": {
|
||||
"titleBar": "#0C1828",
|
||||
"titleBorder": "#1B2740",
|
||||
@@ -32,5 +32,5 @@
|
||||
"button": "#9FB4D4",
|
||||
"frame": "#0A1524"
|
||||
},
|
||||
"build": "30d5d835df"
|
||||
"build": "287b1d86af"
|
||||
}
|
||||
@@ -24,7 +24,7 @@
|
||||
"preview": "preview.png",
|
||||
"apiVersion": 1,
|
||||
"version": "1.6",
|
||||
"updatedAt": "2026-11-14T05:09:30Z",
|
||||
"updatedAt": "2026-11-14T10:53:39Z",
|
||||
"chrome": {
|
||||
"titleBar": "#0C1828",
|
||||
"titleBorder": "#1B2740",
|
||||
@@ -32,5 +32,5 @@
|
||||
"button": "#9FB4D4",
|
||||
"frame": "#0A1524"
|
||||
},
|
||||
"build": "aaeef1614c"
|
||||
"build": "83124cb2ac"
|
||||
}
|
||||
@@ -25,7 +25,7 @@
|
||||
"preview": "preview.png",
|
||||
"apiVersion": 1,
|
||||
"version": "1.5",
|
||||
"updatedAt": "2026-11-14T05:09:30Z",
|
||||
"updatedAt": "2026-11-14T10:53:39Z",
|
||||
"chrome": {
|
||||
"titleBar": "#FFFFFF",
|
||||
"titleBorder": "#E3E8F3",
|
||||
@@ -33,5 +33,5 @@
|
||||
"button": "#5B6A86",
|
||||
"frame": "#F4F6FB"
|
||||
},
|
||||
"build": "c41765488d"
|
||||
"build": "b8930576fd"
|
||||
}
|
||||
+12
-12
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"schema": 1,
|
||||
"generated": "2026-11-14T05:09:30Z",
|
||||
"repository": "https://gitcode.com/2509_92447106/GC",
|
||||
"generated": "2026-11-14T10:53:39Z",
|
||||
"repository": "https://gitcode.com/Morris_1/GC",
|
||||
"branch": "main",
|
||||
"modelDir": "model",
|
||||
"launcher": {
|
||||
@@ -10,23 +10,23 @@
|
||||
"packages": {
|
||||
"win-x64": {
|
||||
"path": "dist/GC-win-x64.zip",
|
||||
"url": "https://gitcode.com/2509_92447106/GC/releases/download/v1.0.7/GC-win-x64.zip"
|
||||
"url": "https://gitcode.com/Morris_1/GC/releases/download/v1.0.7/GC-win-x64.zip"
|
||||
},
|
||||
"win-arm64": {
|
||||
"path": "dist/GC-win-arm64.zip",
|
||||
"url": "https://gitcode.com/2509_92447106/GC/releases/download/v1.0.7/GC-win-arm64.zip"
|
||||
"url": "https://gitcode.com/Morris_1/GC/releases/download/v1.0.7/GC-win-arm64.zip"
|
||||
},
|
||||
"osx-arm64": {
|
||||
"path": "dist/GC-osx-arm64.zip",
|
||||
"url": "https://gitcode.com/2509_92447106/GC/releases/download/v1.0.7/GC-osx-arm64.zip"
|
||||
"url": "https://gitcode.com/Morris_1/GC/releases/download/v1.0.7/GC-osx-arm64.zip"
|
||||
},
|
||||
"osx-x64": {
|
||||
"path": "dist/GC-osx-x64.zip",
|
||||
"url": "https://gitcode.com/2509_92447106/GC/releases/download/v1.0.7/GC-osx-x64.zip"
|
||||
"url": "https://gitcode.com/Morris_1/GC/releases/download/v1.0.7/GC-osx-x64.zip"
|
||||
},
|
||||
"linux-x64": {
|
||||
"path": "dist/GC-linux-x64.zip",
|
||||
"url": "https://gitcode.com/2509_92447106/GC/releases/download/v1.0.7/GC-linux-x64.zip"
|
||||
"url": "https://gitcode.com/Morris_1/GC/releases/download/v1.0.7/GC-linux-x64.zip"
|
||||
}
|
||||
}
|
||||
},
|
||||
@@ -34,31 +34,31 @@
|
||||
{
|
||||
"id": "contour-map",
|
||||
"version": "1.0",
|
||||
"build": "257dcfd58f",
|
||||
"build": "d3eb662a36",
|
||||
"dir": "model/contour-map"
|
||||
},
|
||||
{
|
||||
"id": "earth-geography",
|
||||
"version": "1.8",
|
||||
"build": "3a10607730",
|
||||
"build": "d5ad961ed1",
|
||||
"dir": "model/earth-geography"
|
||||
},
|
||||
{
|
||||
"id": "earth-revolution",
|
||||
"version": "1.6",
|
||||
"build": "30d5d835df",
|
||||
"build": "287b1d86af",
|
||||
"dir": "model/earth-revolution"
|
||||
},
|
||||
{
|
||||
"id": "earth-rotation",
|
||||
"version": "1.6",
|
||||
"build": "aaeef1614c",
|
||||
"build": "83124cb2ac",
|
||||
"dir": "model/earth-rotation"
|
||||
},
|
||||
{
|
||||
"id": "scale-calculator",
|
||||
"version": "1.5",
|
||||
"build": "c41765488d",
|
||||
"build": "b8930576fd",
|
||||
"dir": "model/scale-calculator"
|
||||
}
|
||||
]
|
||||
|
||||
+12
-12
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"schema": 1,
|
||||
"generated": "2026-11-14T05:09:30Z",
|
||||
"repository": "https://gitcode.com/2509_92447106/GC",
|
||||
"generated": "2026-11-14T10:53:39Z",
|
||||
"repository": "https://gitcode.com/Morris_1/GC",
|
||||
"branch": "main",
|
||||
"modelDir": "model",
|
||||
"launcher": {
|
||||
@@ -10,23 +10,23 @@
|
||||
"packages": {
|
||||
"win-x64": {
|
||||
"path": "dist/GC-win-x64.zip",
|
||||
"url": "https://gitcode.com/2509_92447106/GC/releases/download/v1.0.7/GC-win-x64.zip"
|
||||
"url": "https://gitcode.com/Morris_1/GC/releases/download/v1.0.7/GC-win-x64.zip"
|
||||
},
|
||||
"win-arm64": {
|
||||
"path": "dist/GC-win-arm64.zip",
|
||||
"url": "https://gitcode.com/2509_92447106/GC/releases/download/v1.0.7/GC-win-arm64.zip"
|
||||
"url": "https://gitcode.com/Morris_1/GC/releases/download/v1.0.7/GC-win-arm64.zip"
|
||||
},
|
||||
"osx-arm64": {
|
||||
"path": "dist/GC-osx-arm64.zip",
|
||||
"url": "https://gitcode.com/2509_92447106/GC/releases/download/v1.0.7/GC-osx-arm64.zip"
|
||||
"url": "https://gitcode.com/Morris_1/GC/releases/download/v1.0.7/GC-osx-arm64.zip"
|
||||
},
|
||||
"osx-x64": {
|
||||
"path": "dist/GC-osx-x64.zip",
|
||||
"url": "https://gitcode.com/2509_92447106/GC/releases/download/v1.0.7/GC-osx-x64.zip"
|
||||
"url": "https://gitcode.com/Morris_1/GC/releases/download/v1.0.7/GC-osx-x64.zip"
|
||||
},
|
||||
"linux-x64": {
|
||||
"path": "dist/GC-linux-x64.zip",
|
||||
"url": "https://gitcode.com/2509_92447106/GC/releases/download/v1.0.7/GC-linux-x64.zip"
|
||||
"url": "https://gitcode.com/Morris_1/GC/releases/download/v1.0.7/GC-linux-x64.zip"
|
||||
}
|
||||
}
|
||||
},
|
||||
@@ -34,31 +34,31 @@
|
||||
{
|
||||
"id": "contour-map",
|
||||
"version": "1.0",
|
||||
"build": "257dcfd58f",
|
||||
"build": "d3eb662a36",
|
||||
"dir": "model/contour-map"
|
||||
},
|
||||
{
|
||||
"id": "earth-geography",
|
||||
"version": "1.8",
|
||||
"build": "3a10607730",
|
||||
"build": "d5ad961ed1",
|
||||
"dir": "model/earth-geography"
|
||||
},
|
||||
{
|
||||
"id": "earth-revolution",
|
||||
"version": "1.6",
|
||||
"build": "30d5d835df",
|
||||
"build": "287b1d86af",
|
||||
"dir": "model/earth-revolution"
|
||||
},
|
||||
{
|
||||
"id": "earth-rotation",
|
||||
"version": "1.6",
|
||||
"build": "aaeef1614c",
|
||||
"build": "83124cb2ac",
|
||||
"dir": "model/earth-rotation"
|
||||
},
|
||||
{
|
||||
"id": "scale-calculator",
|
||||
"version": "1.5",
|
||||
"build": "c41765488d",
|
||||
"build": "b8930576fd",
|
||||
"dir": "model/scale-calculator"
|
||||
}
|
||||
]
|
||||
|
||||
Reference in new issue
Block a user