feat: 全面迁移到 Flutter + 新增 GitHub 源与 CI 流水线

前端
- 移除全部 Avalonia 依赖,模型渲染与界面统一改用 Flutter
- 新增用户页:登录/注册(SHA-512 + 盐)、签到积分(30 天一循环)、
  主题色积分购买、二选一随机、今日人品
- 新增百宝箱页、模型内嵌渲染页、自绘标题栏(最小化/最大化/关闭)
- 下载页显示模型下载进度条,下载源读取加速
- 关于页新增「重新下载启动器」并在下载后做 sha256 完整性校验
- 修复浅色主题下标题栏不跟随主题色、无法连接后端等问题

后端
- 新增 UserService:.GC/user/<用户名>.yaml 存用户名/积分/SHA-512 口令,
  登录返回 session token,本地 .GC/user/user.yaml 保存登录态
- 新增 /api/user/{register,login,me,signin,theme} 接口
- 去掉 Avalonia 窗口宿主,后端只提供 HTTP API

下载源
- 新增 GitHub 镜像源(Morris-morris-cloud/GC),与 Xhmcl 并发测速
- 单源探测超时收紧到 2 秒,取最快且可用的源;GitHub 复用 GiteaRemote
  (contents 带 ref、releases 带 per_page=100)

构建与 CI
- macOS 上默认只出 macOS 包,Windows 交给原生 Windows 构建
- 修复 Windows 交叉编译中 flutter-cpp-client-wrapper 双层目录嵌套
- 新增 GitHub Actions:
  · nightly-prerelease:每天 21:00 编译三平台,发布 nightly 预发布
  · build-bot:Issue/PR 评论 @build-bot build <mac|win-amd|win-arm|all>,
    发布 ip-prerelease 预发布
  · pr-review:检查能否编译、静态分析、合并冲突、是否落后 main
- 忽略 79MB 课件产物等高线.html 与工具链临时备份
This commit is contained in:
Morris committed 2026-11-21 19:18:58 +08:00
1 parent b9cb56cb8b
commit ea1fa6b6d1
134 files changed
+4309 -16614

No files matched your search

-48
View File
@@ -1,48 +0,0 @@
<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>
-134
View File
@@ -1,134 +0,0 @@
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;
}
}
+5 -10
View File
@@ -5,25 +5,20 @@
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<RootNamespace>GC</RootNamespace>
<AssemblyName>GC.Core</AssemblyName>
<AvaloniaUseCompiledBindingsByDefault>false</AvaloniaUseCompiledBindingsByDefault>
<InvariantGlobalization>false</InvariantGlobalization>
</PropertyGroup>
<ItemGroup>
<AvaloniaResource Include="Assets\**" />
<Compile Include="..\..\GC-DRAW\PlayerWindow.cs" />
<!-- 界面与模型渲染都已迁到 Flutter,这里只剩纯服务代码:
不再引用 Avalonia / MVVM / GC.ModelSdk -->
<Compile Remove="test\**\*.cs" />
<!-- 多语言表原先通过 Avalonia 的 avares:// 读取,改为嵌入资源 -->
<EmbeddedResource Include="Assets\i18n\*.json"
LogicalName="GC.Core.Assets.i18n.%(Filename)%(Extension)" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" />
<PackageReference Include="Avalonia.Desktop" Version="$(AvaloniaVersion)" />
<PackageReference Include="Avalonia.Themes.Fluent" Version="$(AvaloniaVersion)" />
<PackageReference Include="CommunityToolkit.Mvvm" Version="$(MvvmVersion)" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\model\_sdk\GC.ModelSdk\GC.ModelSdk.csproj" />
</ItemGroup>
</Project>
-3
View File
@@ -13,8 +13,6 @@ public sealed class AppServices
public IDownloadCenter Downloads { get; }
public MemoryBudget Memory { get; }
public IModelSourceClient Sources { get; }
/// <summary>模型加载器:只负责把模型程序集跑起来,不渲染。</summary>
public ModelHost ModelHost { get; }
/// <summary>启动时检查模型 / 启动器更新。</summary>
public IUpdateService Updates { get; }
/// <summary>双源测速选择器(Xhmcl / GitCode 取最快)。</summary>
@@ -34,7 +32,6 @@ public sealed class AppServices
Sources = DownloadModule.Sources;
Downloads = DownloadModule.Downloads;
Memory = new MemoryBudget();
ModelHost = new ModelHost(paths, Settings, Memory);
Selector = DownloadModule.Selector;
Updates = DownloadModule.Updates;
LauncherUpdates = DownloadModule.LauncherUpdates;
+5 -9
View File
@@ -51,7 +51,8 @@ public static class ContributorsService
private const int MaxShown = 8;
private static readonly TimeSpan CacheTtl = TimeSpan.FromMinutes(10);
private static readonly HttpClient Http = CreateHttp();
// 使用共享 HttpClient
private static readonly HttpClient Http = SharedHttpClientFactory.GetDefault();
/// <summary>同一作者的多个 git 身份 -> 统一展示名。</summary>
private static readonly Dictionary<string, string> Aliases = new(StringComparer.OrdinalIgnoreCase)
@@ -61,6 +62,9 @@ public static class ContributorsService
["2509_92447106"] = "Morris",
["chenmoyuan1214@qq.com"] = "Morris",
["morris@xhmcl.com"] = "Morris",
// 远影科技是 Morris 的另一个 git 身份(同一邮箱),归并到 Morris
["远影科技"] = "Morris",
["yuanying@yuanying.tech"] = "Morris",
// 早期提交用的是 xhgit 这个账号,展示名统一成 itxiaohui
["xhgit"] = "itxiaohui",
["itxiaohui"] = "itxiaohui",
@@ -75,14 +79,6 @@ public static class ContributorsService
private static readonly object Gate = new();
private static (DateTimeOffset At, string Key, List<Contributor> Items)? _cache;
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>按仓库地址推导接口:Xhmcl(Gitea) 与 GitCode 结构不同。</summary>
public static string BuildUrl(string repository)
{
-124
View File
@@ -1,124 +0,0 @@
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;
}
}
}
+4 -15
View File
@@ -4,9 +4,6 @@ using System.ComponentModel;
using System.Globalization;
using System.IO;
using System.Text.Json;
using Avalonia.Markup.Xaml;
using Avalonia.Data;
using Avalonia.Platform;
namespace GC.Services;
@@ -75,8 +72,10 @@ public sealed class L : INotifyPropertyChanged
{
try
{
var uri = new Uri($"avares://GC.Core/Assets/i18n/{code}.json");
using var stream = AssetLoader.Open(uri);
// 界面已迁到 Flutter,这里不能再依赖 Avalonia 的 avares:// 资源加载
var asm = typeof(L).Assembly;
using var stream = asm.GetManifestResourceStream($"GC.Core.Assets.i18n.{code}.json");
if (stream == null) return null;
using var reader = new StreamReader(stream);
return JsonSerializer.Deserialize<Dictionary<string, string>>(reader.ReadToEnd(),
new JsonSerializerOptions { ReadCommentHandling = JsonCommentHandling.Skip, AllowTrailingCommas = true });
@@ -131,13 +130,3 @@ public sealed class LocalizedString : INotifyPropertyChanged
internal void Refresh() => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Value)));
}
/// <summary>XAML 用法:Text="{loc:Loc nav.home}"</summary>
public sealed class LocExtension : MarkupExtension
{
public LocExtension() { }
public LocExtension(string key) => Key = key;
public string Key { get; set; } = "";
public override object ProvideValue(IServiceProvider serviceProvider)
=> new Binding(nameof(LocalizedString.Value)) { Source = L.I.For(Key) };
}
-300
View File
@@ -1,300 +0,0 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Runtime.Loader;
using System.Threading.Tasks;
using Avalonia.Controls;
using GC.Models;
using GC.ModelSdk;
namespace GC.Services;
/// <summary>
/// 模型宿主:按清单加载模型自己的程序集,拿到模型自带的界面。
/// 启动器对“场景 / 行星 / 节气”一无所知,只认契约。
/// </summary>
public sealed class ModelHost
{
public const int SupportedApiVersion = 1;
private readonly AppPaths _paths;
private readonly SettingsService _settings;
private readonly MemoryBudget _memory;
public ModelHost(AppPaths paths, SettingsService settings, MemoryBudget memory)
{
_paths = paths;
_settings = settings;
_memory = memory;
}
/// <summary>同步加载(全部在 UI 线程,用于自检 / 命令行)。</summary>
public LoadedModel Load(ModelPackage package, Action requestClose, Action<double, string?>? progress = null)
{
var session = CreateSession(package, requestClose, progress);
try
{
session.Runtime.Prepare(session.Context);
var view = session.Runtime.CreateView(session.Context)
?? throw new InvalidOperationException("模型没有返回界面");
return session.Complete(view);
}
catch
{
session.Dispose();
throw;
}
}
/// <summary>
/// 异步加载:数据准备放在后台线程(<see cref="IModelRuntime.Prepare"/>),
/// 界面构建回到 UI 线程,进度通过 <paramref name="progress"/> 实时汇报。
/// </summary>
public async Task<LoadedModel> LoadAsync(ModelPackage package, Action requestClose,
Action<double, string?>? progress = null)
{
var session = CreateSession(package, requestClose, progress);
try
{
await Task.Run(() => session.Runtime.Prepare(session.Context)).ConfigureAwait(true);
var view = session.Runtime.CreateView(session.Context)
?? throw new InvalidOperationException("模型没有返回界面");
return session.Complete(view);
}
catch
{
session.Dispose();
throw;
}
}
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);
var directory = Path.GetDirectoryName(assemblyPath)!;
var context = new ModelLoadContext(directory);
try
{
var assembly = context.LoadFromAssemblyPath(assemblyPath);
var type = ResolveFactoryType(assembly, package.Manifest.Type);
if (type == null)
throw new InvalidOperationException("模型程序集里没有找到 IModelFactory 实现");
if (Activator.CreateInstance(type) is not IModelFactory factory)
throw new InvalidOperationException($"无法创建模型入口:{type.FullName}");
if (factory.ApiVersion != SupportedApiVersion)
throw new InvalidOperationException(
$"模型程序集的契约版本为 v{factory.ApiVersion},启动器支持 v{SupportedApiVersion};" +
"请更新到匹配的版本");
var runtime = factory.Create();
var modelContext = new ModelContext(package, L.I.Language, _memory.BudgetMb, requestClose, progress);
return new Session(context, runtime, modelContext);
}
catch
{
context.Unload();
throw;
}
}
private static Type? ResolveFactoryType(Assembly assembly, string? typeName)
{
if (!string.IsNullOrWhiteSpace(typeName))
{
var exact = assembly.GetType(typeName!, throwOnError: false);
if (exact != null) return exact;
}
foreach (var type in assembly.GetTypes())
{
if (type.IsAbstract || type.IsInterface) continue;
if (typeof(IModelFactory).IsAssignableFrom(type)) return type;
}
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;
public Session(ModelLoadContext context, IModelRuntime runtime, ModelContext modelContext)
{
_context = context;
Runtime = runtime;
Context = modelContext;
}
public IModelRuntime Runtime { get; }
public ModelContext Context { get; }
public LoadedModel Complete(Control view) => new(_context, Runtime, view);
public void Dispose()
{
try { Runtime.Dispose(); } catch (Exception ex) { Console.Error.WriteLine($"释放模型失败: {ex.Message}"); }
try { _context.Unload(); } catch (Exception ex) { Console.Error.WriteLine($"卸载模型程序集失败: {ex.Message}"); }
}
}
}
/// <summary>一次性模型实例:窗口关闭后释放视图、卸载程序集。</summary>
public sealed class LoadedModel : IDisposable
{
private readonly ModelLoadContext _context;
private readonly IModelRuntime _runtime;
private bool _disposed;
public LoadedModel(ModelLoadContext context, IModelRuntime runtime, Control view)
{
_context = context;
_runtime = runtime;
View = view;
}
public Control View { get; }
public void Dispose()
{
if (_disposed) return;
_disposed = true;
// 顺序:先释放视图(停计时器/Dispose 位图),再释放运行时,最后卸载程序集。
// 否则视图里的事件订阅会继续持有 ALC 内的类型,collectible 上下文无法回收。
try { (View as IDisposable)?.Dispose(); }
catch (Exception ex) { Console.Error.WriteLine($"释放模型视图失败: {ex.Message}"); }
try { _runtime.Dispose(); } catch (Exception ex) { Console.Error.WriteLine($"释放模型失败: {ex.Message}"); }
try { _context.Unload(); } catch (Exception ex) { Console.Error.WriteLine($"卸载模型程序集失败: {ex.Message}"); }
}
}
/// <summary>模型程序集加载上下文:契约与 Avalonia 一律回到默认上下文,保证类型一致。</summary>
public sealed class ModelLoadContext : AssemblyLoadContext
{
private static readonly HashSet<string> Shared = new(StringComparer.OrdinalIgnoreCase)
{
"GC.ModelSdk",
"Avalonia",
"Avalonia.Base",
"Avalonia.Controls",
"Avalonia.Desktop",
"Avalonia.Skia",
"Avalonia.Themes.Fluent",
"SkiaSharp",
"HarfBuzzSharp"
};
private readonly string _directory;
public ModelLoadContext(string directory) : base("model:" + Path.GetFileName(directory), isCollectible: true)
=> _directory = directory;
protected override Assembly? Load(AssemblyName assemblyName)
{
var name = assemblyName.Name;
if (string.IsNullOrEmpty(name)) return null;
if (Shared.Contains(name)) return null; // 用启动器已加载的那份
if (name.StartsWith("System.", StringComparison.OrdinalIgnoreCase)) return null;
if (name is "System" or "netstandard" or "mscorlib") return null;
var candidate = Path.Combine(_directory, name + ".dll");
return File.Exists(candidate) ? LoadFromAssemblyPath(candidate) : null;
}
}
/// <summary>启动器提供给模型的环境。</summary>
public sealed class ModelContext : IModelContext
{
private readonly Action _requestClose;
private readonly Action<double, string?>? _progress;
public ModelContext(ModelPackage package, string language, int memoryMb, Action requestClose,
Action<double, string?>? progress)
{
_progress = progress;
ModelId = package.Id;
ModelDirectory = package.Directory;
DataDirectory = package.DataDirectory;
Language = language;
MemoryBudgetMb = memoryMb;
_requestClose = requestClose;
}
public string ModelId { get; }
public string ModelDirectory { get; }
public string DataDirectory { get; }
public string Language { get; }
public int MemoryBudgetMb { get; }
public void RequestClose() => _requestClose();
public void ReportProgress(double value, string? message = null) => _progress?.Invoke(value, message);
public void Log(string message) => Console.WriteLine(message);
}
@@ -0,0 +1,47 @@
using System;
using System.Net;
using System.Net.Http;
namespace GC.Services;
/// <summary>
/// 共享 HttpClient 工厂:统一管理连接池,避免每个类创建独立的 HttpClient 实例。
///
/// .NET Core 3.1+ 的 HttpClientHandler 内部使用连接池,但每个 HttpClient 实例仍会创建
/// 独立的 Socket 连接池。多个静态 HttpClient 实例(尤其是不同超时配置)会导致端口耗尽
/// 或连接无法及时释放。通过单一实例 + 共享 Handler 解决此问题。
///
/// 注意:不同场景对超时要求差异较大(探测 6s、下载 5min),通过构造参数传递超时,
/// 但底层 Handler 共享,避免重复创建 Socket。
/// </summary>
public static class SharedHttpClientFactory
{
/// <summary>默认 HTTP 客户端(短超时,用于探测和快速请求)。</summary>
private static readonly HttpClient DefaultClient = CreateClient(TimeSpan.FromSeconds(20));
/// <summary>长超时 HTTP 客户端(用于大文件下载)。</summary>
private static readonly HttpClient LongTimeoutClient = CreateClient(TimeSpan.FromMinutes(5));
private static HttpClient CreateClient(TimeSpan timeout)
{
var handler = new HttpClientHandler
{
AutomaticDecompression = DecompressionMethods.GZip |
DecompressionMethods.Deflate,
// 限制最大重定向次数,防止重定向循环
MaxAutomaticRedirections = 5
};
var client = new HttpClient(handler, disposeHandler: false)
{
Timeout = timeout
};
client.DefaultRequestHeaders.UserAgent.ParseAdd("GC/1.0");
return client;
}
/// <summary>获取默认超时(20秒)的 HttpClient,用于常规 API 请求。</summary>
public static HttpClient GetDefault() => DefaultClient;
/// <summary>获取长超时(5分钟)的 HttpClient,用于大文件下载。</summary>
public static HttpClient GetLongTimeout() => LongTimeoutClient;
}
+48 -14
View File
@@ -7,9 +7,9 @@ namespace GC.Services;
/// <summary>
/// 内置下载源。
///
/// 目前只启用 Xhmcl;GitCode 的 preset 与下载实现仍保留在代码中,
/// 但不参与测速 / 下载 / 更新。两个源本来指向同一份仓库内容,
/// 区别只是托管服务器;恢复双源时把 GitCode 加回 <see cref="All"/>。
/// 当前启用 Xhmcl(Gitea)与 GitHub 两个镜像,指向同一份仓库内容;
/// 启动 / 下载 / 更新前并发测速(2 秒超时),取最快且可用的那个。
/// GitCode 的 preset 与下载实现仍保留在代码中,但不参与测速 / 下载 / 更新。
/// </summary>
public sealed class SourcePreset
{
@@ -31,10 +31,16 @@ public sealed class SourcePreset
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('/')}";
/// <summary>拼 raw 文件下载地址(各平台的 URL 结构不同)。</summary>
public string RawUrl(string path) => RawStyle switch
{
// GitHub:raw.githubusercontent.com/{owner}/{repo}/{branch}/{path}
"raw" => $"{RawBase}/{Owner}/{Repo}/{Branch}/{path.TrimStart('/')}",
// GitCode:raw/{branch}/{path}
"plain" => $"{RawBase}/{Owner}/{Repo}/raw/{Branch}/{path.TrimStart('/')}",
// Gitea:raw/branch/{branch}/{path}
_ => $"{RawBase}/{Owner}/{Repo}/raw/branch/{Branch}/{path.TrimStart('/')}"
};
public static readonly SourcePreset Xhmcl = new()
{
@@ -50,6 +56,25 @@ public sealed class SourcePreset
Branch = "main"
};
/// <summary>
/// GitHub 镜像:与 Xhmcl 指向同一份仓库内容(模型清单 + Release 附件)。
/// API 与 Gitea 高度兼容(contents / releases 同构),因此复用同一个 remote 实现,
/// 仅在 URL 拼装与分页参数上区分。
/// </summary>
public static readonly SourcePreset GitHub = new()
{
Id = "github",
Name = "GitHub",
HomeUrl = "https://github.com/Morris-morris-cloud/GC",
ApiBase = "https://api.github.com",
RawBase = "https://raw.githubusercontent.com",
Kind = "github",
RawStyle = "raw",
Owner = "Morris-morris-cloud",
Repo = "GC",
Branch = "main"
};
public static readonly SourcePreset GitCode = new()
{
Id = "gitcode",
@@ -65,20 +90,29 @@ public sealed class SourcePreset
};
/// <summary>
/// 当前启用的源:暂时只保留 Xhmcl。GitCode 的定义与实现仍保留在代码里,
/// 但不参与测速、下载与更新(需要恢复时把 GitCode 加回这个数组即可)。
/// 当前启用的源:Xhmcl 与 GitHub 是同一份仓库的两个镜像,启动时并发测速取最快。
/// GitCode 的定义与实现仍保留在代码里,但不参与测速、下载与更新
/// (需要恢复时把 GitCode 加回这个数组即可)。
/// </summary>
public static readonly SourcePreset[] All = { Xhmcl };
public static readonly SourcePreset[] All = { Xhmcl, GitHub };
public static SourcePreset? Find(string? id) =>
All.FirstOrDefault(p => string.Equals(p.Id, id, StringComparison.OrdinalIgnoreCase));
/// <summary>把任意仓库地址映射到启用的内置源(用于兼容旧配置)。</summary>
/// <summary>把任意仓库地址 / 源名映射到启用的内置源(用于兼容旧配置与调用方取值)。</summary>
public static SourcePreset Detect(string? url)
{
if (!string.IsNullOrWhiteSpace(url) &&
url!.Contains("xhmcl.com", StringComparison.OrdinalIgnoreCase))
return Xhmcl;
if (!string.IsNullOrWhiteSpace(url))
{
if (url!.Contains("github.com", StringComparison.OrdinalIgnoreCase) ||
url.Equals("GitHub", StringComparison.OrdinalIgnoreCase) ||
url.Equals("github", StringComparison.OrdinalIgnoreCase))
return GitHub;
if (url.Contains("xhmcl.com", StringComparison.OrdinalIgnoreCase) ||
url.Equals("Xhmcl", StringComparison.OrdinalIgnoreCase) ||
url.Equals("xhmcl", StringComparison.OrdinalIgnoreCase))
return Xhmcl;
}
// 旧配置里的 GitCode 地址不再作为下载源,统一落到 Xhmcl。
return Xhmcl;
+42
View File
@@ -0,0 +1,42 @@
using System;
using System.Globalization;
namespace GC.Services;
/// <summary>
/// 版本号工具:Release tag 有 v1.0.6 / GCL-1.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- / GCL- / release-
if (s.StartsWith("GCL-", StringComparison.OrdinalIgnoreCase)) s = s[4..];
else 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&lt;b 返回负、相等返回 0。</summary>
public static int Compare(string? a, string? b) => Parse(a).CompareTo(Parse(b));
}
-325
View File
@@ -1,325 +0,0 @@
<Styles xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Styles.Resources>
<SolidColorBrush x:Key="AppBg" Color="#F4F6FB" />
<SolidColorBrush x:Key="Surface" Color="#FFFFFF" />
<SolidColorBrush x:Key="SurfaceAlt" Color="#F7F9FE" />
<SolidColorBrush x:Key="Line" Color="#E3E8F3" />
<SolidColorBrush x:Key="LineStrong" Color="#D2DAEA" />
<SolidColorBrush x:Key="Ink" Color="#111A2E" />
<SolidColorBrush x:Key="InkDim" Color="#5B6A86" />
<SolidColorBrush x:Key="InkFaint" Color="#8A97B1" />
<SolidColorBrush x:Key="Accent" Color="#2F6BFF" />
<SolidColorBrush x:Key="AccentDark" Color="#1F4FD0" />
<SolidColorBrush x:Key="AccentSoft" Color="#EAF1FF" />
<SolidColorBrush x:Key="SideBg" Color="#0D1526" />
<SolidColorBrush x:Key="SideLine" Color="#1B2740" />
<SolidColorBrush x:Key="SideInk" Color="#A9B8D4" />
<SolidColorBrush x:Key="Success" Color="#1F9D6B" />
<SolidColorBrush x:Key="Danger" Color="#D64545" />
<SolidColorBrush x:Key="Warn" Color="#D98613" />
<LinearGradientBrush x:Key="HeroBg" StartPoint="0%,0%" EndPoint="100%,100%">
<GradientStop Color="#12203C" Offset="0" />
<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">
<Setter Property="FontSize" Value="13" />
<Setter Property="Foreground" Value="{DynamicResource Ink}" />
</Style>
<!-- 文本 -->
<Style Selector="TextBlock.h1">
<Setter Property="FontSize" Value="26" />
<Setter Property="FontWeight" Value="SemiBold" />
<Setter Property="Foreground" Value="{DynamicResource Ink}" />
</Style>
<Style Selector="TextBlock.h2">
<Setter Property="FontSize" Value="16" />
<Setter Property="FontWeight" Value="SemiBold" />
<Setter Property="Foreground" Value="{DynamicResource Ink}" />
</Style>
<Style Selector="TextBlock.h3">
<Setter Property="FontSize" Value="13.5" />
<Setter Property="FontWeight" Value="SemiBold" />
<Setter Property="Foreground" Value="{DynamicResource Ink}" />
</Style>
<Style Selector="TextBlock.muted">
<Setter Property="FontSize" Value="12" />
<Setter Property="Foreground" Value="{DynamicResource InkDim}" />
</Style>
<Style Selector="TextBlock.faint">
<Setter Property="FontSize" Value="11.5" />
<Setter Property="Foreground" Value="{DynamicResource InkFaint}" />
</Style>
<Style Selector="TextBlock.eyebrow">
<Setter Property="FontSize" Value="11" />
<Setter Property="FontWeight" Value="SemiBold" />
<Setter Property="Foreground" Value="{DynamicResource InkFaint}" />
</Style>
<Style Selector="TextBlock.onDark">
<Setter Property="Foreground" Value="#EAF1FF" />
</Style>
<Style Selector="TextBlock.onDarkDim">
<Setter Property="Foreground" Value="#9DB0D0" />
</Style>
<!-- 容器 -->
<!-- 容器:卡片悬停浮起,阴影与位移都有过渡 -->
<Style Selector="Border.card">
<Setter Property="Background" Value="{DynamicResource Surface}" />
<Setter Property="BorderBrush" Value="{DynamicResource Line}" />
<Setter Property="BorderThickness" Value="1" />
<Setter Property="CornerRadius" Value="16" />
<Setter Property="Transitions">
<Transitions>
<BoxShadowsTransition Property="BoxShadow" Duration="0:0:0.2" />
<BrushTransition Property="BorderBrush" Duration="0:0:0.2" />
<TransformOperationsTransition Property="RenderTransform" Duration="0:0:0.2" />
</Transitions>
</Setter>
</Style>
<Style Selector="Border.card:pointerover">
<Setter Property="BoxShadow" Value="0 10 26 0 #1A213C70" />
<Setter Property="BorderBrush" Value="{DynamicResource LineStrong}" />
<Setter Property="RenderTransform" Value="translateY(-2px)" />
</Style>
<Style Selector="Border.panel">
<Setter Property="Background" Value="{DynamicResource SurfaceAlt}" />
<Setter Property="BorderBrush" Value="{DynamicResource Line}" />
<Setter Property="BorderThickness" Value="1" />
<Setter Property="CornerRadius" Value="12" />
</Style>
<Style Selector="Border.hero">
<Setter Property="Background" Value="{DynamicResource HeroBg}" />
<Setter Property="CornerRadius" Value="20" />
<Setter Property="BoxShadow" Value="0 12 32 0 #1A0B1A3A" />
</Style>
<Style Selector="Border.chip">
<Setter Property="Background" Value="{DynamicResource AccentSoft}" />
<Setter Property="CornerRadius" Value="999" />
<Setter Property="Padding" Value="8,2" />
</Style>
<Style Selector="Border.tag">
<Setter Property="Background" Value="#F0F3FA" />
<Setter Property="CornerRadius" Value="6" />
<Setter Property="Padding" Value="7,2" />
</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" />
<Setter Property="MinHeight" Value="34" />
<Setter Property="CornerRadius" Value="9" />
<Setter Property="Background" Value="{DynamicResource Surface}" />
<Setter Property="BorderBrush" Value="{DynamicResource LineStrong}" />
<Setter Property="BorderThickness" Value="1" />
<Setter Property="Foreground" Value="{DynamicResource Ink}" />
<Setter Property="HorizontalContentAlignment" Value="Center" />
<Setter Property="VerticalContentAlignment" Value="Center" />
<Setter Property="Cursor" Value="Hand" />
<Setter Property="Transitions">
<Transitions>
<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="Background" Value="#EDF2FC" />
<Setter Property="BorderBrush" Value="#BAC9E6" />
</Style>
<Style Selector="Button:pressed">
<Setter Property="Background" Value="#DDE7F8" />
<Setter Property="BorderBrush" Value="#9FB4DD" />
</Style>
<!-- 主要按钮 -->
<Style Selector="Button.primary">
<Setter Property="Background" Value="{DynamicResource Accent}" />
<Setter Property="BorderBrush" Value="{DynamicResource Accent}" />
<Setter Property="Foreground" Value="White" />
</Style>
<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: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">
<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.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" />
<Setter Property="CornerRadius" Value="10" />
<Setter Property="FontSize" Value="13.5" />
<Setter Property="MinHeight" Value="40" />
</Style>
<Style Selector="Button.nav:pointerover">
<Setter Property="Background" Value="#16213A" />
<Setter Property="Foreground" Value="#E8EFFF" />
</Style>
<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>
<!-- 输入 -->
<Style Selector="TextBox">
<Setter Property="CornerRadius" Value="9" />
<Setter Property="Padding" Value="11,8" />
<Setter Property="MinHeight" Value="36" />
<Setter Property="FontSize" Value="12.5" />
<Setter Property="Background" Value="{DynamicResource Surface}" />
<Setter Property="BorderBrush" Value="{DynamicResource LineStrong}" />
</Style>
<Style Selector="ComboBox">
<Setter Property="CornerRadius" Value="9" />
<Setter Property="MinHeight" Value="34" />
<Setter Property="FontSize" Value="12.5" />
<Setter Property="Padding" Value="10,4" />
</Style>
<Style Selector="ProgressBar">
<Setter Property="Height" Value="5" />
<Setter Property="CornerRadius" Value="3" />
<Setter Property="MinHeight" Value="5" />
</Style>
<Style Selector="CheckBox">
<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>
-104
View File
@@ -1,104 +0,0 @@
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);
}
-411
View File
@@ -1,411 +0,0 @@
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Input;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using GC.Models;
using GC.Services;
namespace GC.ViewModels;
public partial class DownloadViewModel : ObservableObject
{
private readonly AppServices _services;
private readonly MainViewModel _main;
private bool _initialized;
// 每次切源取消上一次加载,并用 generation 序号丢弃过期结果,避免并发写 Models 集合
private CancellationTokenSource? _loadCts;
private int _loadGeneration;
public ObservableCollection<SourceItemViewModel> Sources { get; } = new();
public ObservableCollection<RemoteModelRowViewModel> Models { get; } = new();
public ObservableCollection<IDownloadJob> Jobs => _services.Downloads.Jobs;
[ObservableProperty] private SourceItemViewModel? _selectedSource;
[ObservableProperty] private string _importUrl = "";
[ObservableProperty] private bool _isBusy;
[ObservableProperty] private string _statusMessage = "";
[ObservableProperty] private bool _hasModels;
[ObservableProperty] private bool _isBackgroundOpen = true;
[ObservableProperty] private string _jobSummary = "";
[ObservableProperty] private bool _hasJobs;
[ObservableProperty] private bool _isSourceEmpty;
public DownloadViewModel(AppServices services, MainViewModel main)
{
_services = services;
_main = main;
Jobs.CollectionChanged += OnJobsChanged;
foreach (var job in Jobs) job.PropertyChanged += OnJobPropertyChanged;
L.I.LanguageChanged += RefreshLanguage;
RebuildSources();
UpdateJobState();
}
public string BackgroundTitle => L.I["dl.background"];
public string ImportHint => L.I["dl.hint"];
// ------------------------------------------------------------ 页面生命周期
public void OnShown()
{
if (_initialized) return;
_initialized = true;
if (SelectedSource == null)
SelectedSource = Sources.FirstOrDefault(s => s.Model.Enabled && !string.IsNullOrWhiteSpace(s.Model.Url))
?? Sources.FirstOrDefault();
}
// ------------------------------------------------------------ 模型源
private void RebuildSources()
{
var keepId = SelectedSource?.Model.Id;
Sources.Clear();
foreach (var source in _services.Settings.Current.Sources)
Sources.Add(new SourceItemViewModel(source, this, _services));
SelectedSource = Sources.FirstOrDefault(s => s.Model.Id == keepId) ?? SelectedSource;
}
partial void OnSelectedSourceChanged(SourceItemViewModel? value)
{
if (value == null) return;
if (string.IsNullOrWhiteSpace(value.Model.Url))
{
Models.Clear();
HasModels = false;
IsSourceEmpty = true;
StatusMessage = L.I["dl.pickSource"];
return;
}
_ = LoadAsync(value, force: false);
}
internal void OnSourceEnabledChanged(SourceItemViewModel source)
{
if (!source.Model.Enabled && SelectedSource == source) Models.Clear();
}
internal void RemoveSource(SourceItemViewModel source)
{
if (source.Model.BuiltIn) return; // 内置默认源不允许删除
_services.Settings.Current.Sources.Remove(source.Model);
_services.Settings.Save();
var wasSelected = SelectedSource == source;
Sources.Remove(source);
if (wasSelected)
{
SelectedSource = Sources.FirstOrDefault();
if (SelectedSource == null)
{
Models.Clear();
HasModels = false;
}
}
}
/// <summary>
/// 只允许两个内置源(Xhmcl / GitCode),不再接受任意地址。
/// 旧的「自定义源」入口统一改为:按测速结果切换到更快的那个源。
/// </summary>
[RelayCommand]
private async Task ImportAsync()
{
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 = "没有可用的下载源";
return;
}
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)
{
var trimmed = url.TrimEnd('/', '\\');
var slash = trimmed.LastIndexOfAny(new[] { '/', '\\' });
var name = slash >= 0 ? trimmed[(slash + 1)..] : trimmed;
if (name.EndsWith(".git", StringComparison.OrdinalIgnoreCase)) name = name[..^4];
if (name.EndsWith(".zip", StringComparison.OrdinalIgnoreCase)) name = name[..^4];
return string.IsNullOrWhiteSpace(name) ? url : name;
}
[RelayCommand]
private async Task RefreshAsync()
{
if (SelectedSource == null) return;
await LoadAsync(SelectedSource, force: true);
}
internal async Task RefreshFromSource(SourceItemViewModel source)
{
SelectedSource = source;
await LoadAsync(source, force: true);
}
private async Task LoadAsync(SourceItemViewModel source, bool force)
{
if (!source.Model.Enabled) return;
// 取消上一次尚未完成的加载,避免快速切换源时并发 Clear/写入同一集合
_loadCts?.Cancel();
_loadCts?.Dispose();
_loadCts = new CancellationTokenSource();
var ct = _loadCts.Token;
var generation = ++_loadGeneration;
IsBusy = true;
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)
return;
if (index.Error != null)
{
Models.Clear();
HasModels = false;
IsSourceEmpty = true;
StatusMessage = DescribeError(index.Error);
return;
}
var installedIds = new HashSet<string>(
_services.Models.Scan().Select(p => p.Id), StringComparer.OrdinalIgnoreCase);
Models.Clear();
foreach (var model in index.Models)
{
Models.Add(new RemoteModelRowViewModel(model, source,
installedIds.Contains(model.Id), DownloadCommand));
}
HasModels = Models.Count > 0;
IsSourceEmpty = Models.Count == 0;
StatusMessage = index.FromCache
? $"{L.I.F("dl.ready", Models.Count)} · {L.I["dl.fromCache"]}"
: L.I.F("dl.ready", Models.Count);
}
catch (OperationCanceledException)
{
// 被更新的加载取代或页面关闭:忽略,不覆盖新结果
}
catch (Exception ex)
{
if (!ct.IsCancellationRequested) StatusMessage = ex.Message;
}
finally
{
// 只有最后一次加载才复位 Busy,避免旧任务把新任务的忙碌状态清掉
if (generation == _loadGeneration) IsBusy = false;
}
}
private static string DescribeError(string error)
{
if (error.StartsWith("dl.", StringComparison.Ordinal))
{
var text = L.I[error];
return text == error ? error : text;
}
return error;
}
// ------------------------------------------------------------ 下载
[RelayCommand]
private async Task DownloadAsync(RemoteModelRowViewModel row)
{
if (row == null) return;
row.RowOpacity = 0;
row.RowHeight = 0;
IsBackgroundOpen = true;
_services.Downloads.Enqueue(row.Model);
await Task.Delay(240);
Models.Remove(row);
HasModels = Models.Count > 0;
IsSourceEmpty = Models.Count == 0;
}
[RelayCommand]
private void CancelJob(IDownloadJob? job)
{
if (job != null) _services.Downloads.Cancel(job);
}
[RelayCommand]
private void RetryJob(IDownloadJob? job)
{
if (job != null) _services.Downloads.Retry(job);
}
[RelayCommand]
private void RemoveJob(IDownloadJob? job)
{
if (job != null) _services.Downloads.Remove(job);
}
[RelayCommand]
private void ClearFinished() => _services.Downloads.ClearFinished();
[RelayCommand]
private void ToggleBackground() => IsBackgroundOpen = !IsBackgroundOpen;
// ------------------------------------------------------------ 任务展示
private void OnJobsChanged(object? sender, NotifyCollectionChangedEventArgs e)
{
if (e.NewItems != null)
foreach (IDownloadJob job in e.NewItems) job.PropertyChanged += OnJobPropertyChanged;
if (e.OldItems != null)
foreach (IDownloadJob job in e.OldItems) job.PropertyChanged -= OnJobPropertyChanged;
UpdateJobState();
}
private void OnJobPropertyChanged(object? sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == nameof(IDownloadJob.State))
{
if (sender is IDownloadJob { State: DownloadState.Completed })
_services.Models.NotifyChanged();
}
UpdateJobState();
}
private void UpdateJobState()
{
HasJobs = Jobs.Count > 0;
JobSummary = $"{L.I["dl.background"]} ({Jobs.Count})";
OnPropertyChanged(nameof(JobSummary));
}
private void RefreshLanguage()
{
foreach (var source in Sources) source.RefreshLanguage();
foreach (var model in Models) model.RefreshLanguage();
foreach (var job in Jobs) job.RefreshText();
OnPropertyChanged(nameof(BackgroundTitle));
OnPropertyChanged(nameof(ImportHint));
UpdateJobState();
}
}
public partial class SourceItemViewModel : ObservableObject
{
private readonly DownloadViewModel _owner;
private readonly AppServices _services;
public ModelSource Model { get; }
public SourceItemViewModel(ModelSource model, DownloadViewModel owner, AppServices services)
{
Model = model;
_owner = owner;
_services = services;
RemoveCommand = new RelayCommand(() => _owner.RemoveSource(this));
RefreshCommand = new AsyncRelayCommand(async () => await _owner.RefreshFromSource(this));
}
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
{
get => Model.Enabled;
set
{
if (Model.Enabled == value) return;
Model.Enabled = value;
_services.Settings.Save();
OnPropertyChanged();
_owner.OnSourceEnabledChanged(this);
}
}
public ICommand RemoveCommand { get; }
public ICommand RefreshCommand { get; }
public void RefreshLanguage()
{
OnPropertyChanged(nameof(Name));
OnPropertyChanged(nameof(HostText));
}
}
public partial class RemoteModelRowViewModel : ObservableObject
{
public RemoteModel Model { get; }
public SourceItemViewModel Source { get; }
public RemoteModelRowViewModel(RemoteModel model, SourceItemViewModel source, bool installed, ICommand downloadCommand)
{
Model = model;
Source = source;
Installed = installed;
DownloadCommand = downloadCommand;
}
public string Name => Model.LocalizedName;
public string Description => Model.LocalizedDescription;
public string VersionText => "v" + Model.Manifest.Version;
public string SizeText => ModelScanner.HumanSize(Model.SizeBytes);
public string MetaText => $"{VersionText} · {SizeText}";
public string TagsText => string.Join(" · ", Model.Manifest.Tags ?? new List<string>());
public bool HasTags => !string.IsNullOrWhiteSpace(TagsText);
[ObservableProperty] private bool _installed;
[ObservableProperty] private double _rowHeight = 92;
[ObservableProperty] private double _rowOpacity = 1;
public string ButtonText => Installed ? L.I["dl.reinstall"] : L.I["dl.download"];
public ICommand DownloadCommand { get; }
partial void OnInstalledChanged(bool value) => OnPropertyChanged(nameof(ButtonText));
public void RefreshLanguage()
{
OnPropertyChanged(nameof(Name));
OnPropertyChanged(nameof(Description));
OnPropertyChanged(nameof(MetaText));
OnPropertyChanged(nameof(TagsText));
OnPropertyChanged(nameof(ButtonText));
}
}
-148
View File
@@ -1,148 +0,0 @@
using System;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Input;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using GC.Models;
using Avalonia.Media.Imaging;
using GC.Services;
namespace GC.ViewModels;
public partial class HomeViewModel : ObservableObject
{
private readonly AppServices _services;
private readonly MainViewModel _main;
public ObservableCollection<ModelCardViewModel> Models { get; } = new();
[ObservableProperty] private ModelCardViewModel? _selected;
[ObservableProperty] private bool _isEmpty;
public string CountText => L.I.F("home.count", Models.Count);
public string SourceCountText => _services.Settings.Current.Sources
.Count(s => s.Enabled && !string.IsNullOrWhiteSpace(s.Url)).ToString();
public string MemoryText => $"{_services.Memory.BudgetMb} MB";
public string SelectedHint => Selected == null ? L.I["home.recent"] : L.I["home.launchHint"];
public HomeViewModel(AppServices services, MainViewModel main)
{
_services = services;
_main = main;
_services.Models.Changed += Refresh;
L.I.LanguageChanged += RefreshLanguage;
Refresh();
}
public void Refresh()
{
var keepId = Selected?.Package.Id;
Models.Clear();
foreach (var package in _services.Models.Scan())
Models.Add(new ModelCardViewModel(package, _services, this));
Selected = Models.FirstOrDefault(m => m.Package.Id == keepId) ?? Models.FirstOrDefault();
IsEmpty = Models.Count == 0;
RefreshLanguage();
}
private void RefreshLanguage()
{
OnPropertyChanged(nameof(CountText));
OnPropertyChanged(nameof(SourceCountText));
OnPropertyChanged(nameof(MemoryText));
OnPropertyChanged(nameof(SelectedHint));
foreach (var model in Models) model.RefreshLanguage();
}
public void LaunchModel(ModelCardViewModel card)
{
Selected = card;
_main.PlayModel(card.Package);
}
public async Task DeleteAsync(ModelCardViewModel card)
{
if (!await _main.ConfirmAsync(L.I.F("home.deleteConfirm", card.Name))) return;
_services.Models.Delete(card.Package.Id);
_services.Models.NotifyChanged();
Refresh();
}
[RelayCommand]
private void Launch()
{
var card = Selected ?? Models.FirstOrDefault();
if (card != null) _main.PlayModel(card.Package);
}
[RelayCommand]
private void OpenDownload() => _main.GoDownload();
[RelayCommand]
private void OpenSettings() => _main.GoSettings();
[RelayCommand]
private void OpenFolder() => Shell.OpenFolder(_services.Paths.ModelRoot);
}
public partial class ModelCardViewModel : ObservableObject
{
private readonly AppServices _services;
private Bitmap? _preview;
public ModelPackage Package { get; }
public ModelCardViewModel(ModelPackage package, AppServices services, HomeViewModel home)
{
Package = package;
_services = services;
LaunchCommand = new RelayCommand(() => home.LaunchModel(this));
DeleteCommand = new AsyncRelayCommand(() => home.DeleteAsync(this));
OpenFolderCommand = new RelayCommand(() => Shell.OpenFolder(package.Directory));
}
public string Name => Package.LocalizedName;
public string Description => Package.LocalizedDescription;
public string VersionText => "v" + Package.Manifest.Version;
public string SizeText => ModelScanner.HumanSize(Package.SizeBytes);
public string MetaText => $"{VersionText} · {SizeText}";
public string TagsText => string.Join(" · ", Package.Manifest.Tags ?? new());
public bool HasTags => !string.IsNullOrWhiteSpace(TagsText);
public string AuthorText => string.IsNullOrWhiteSpace(Package.Manifest.Author) ? "" : Package.Manifest.Author;
/// <summary>封面图来自模型包自带的 preview.png —— 启动器只显示,不渲染。</summary>
public Bitmap? Preview
{
get
{
if (_preview != null) return _preview;
try
{
if (File.Exists(Package.PreviewPath)) _preview = new Bitmap(Package.PreviewPath);
}
catch (Exception ex)
{
Console.Error.WriteLine($"读取模型封面失败 {Package.Id}: {ex.Message}");
}
return _preview;
}
}
public bool HasPreview => Preview != null;
public ICommand LaunchCommand { get; }
public ICommand DeleteCommand { get; }
public ICommand OpenFolderCommand { get; }
public void RefreshLanguage()
{
OnPropertyChanged(nameof(Name));
OnPropertyChanged(nameof(Description));
OnPropertyChanged(nameof(MetaText));
OnPropertyChanged(nameof(TagsText));
}
}
-221
View File
@@ -1,221 +0,0 @@
using System;
using System.Linq;
using System.Threading.Tasks;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using GC.Models;
using GC.Services;
namespace GC.ViewModels;
public partial class MainViewModel : ObservableObject
{
private readonly AppServices _services;
private bool _updateRunning;
public HomeViewModel Home { get; }
public DownloadViewModel Download { get; }
public SettingsViewModel Settings { get; }
public AboutViewModel About { get; }
/// <summary>模型宿主:按清单加载模型自带的功能程序集。</summary>
public ModelHost Models { get; }
[ObservableProperty] private ObservableObject _current = null!;
[ObservableProperty] private bool _isHomeActive = true;
[ObservableProperty] private bool _isDownloadActive;
[ObservableProperty] private bool _isSettingsActive;
[ObservableProperty] private bool _isAboutActive;
// 启动更新状态条
[ObservableProperty] private bool _updateBarVisible;
[ObservableProperty] private bool _updateBusy;
[ObservableProperty] private double _updateProgress;
[ObservableProperty] private string _updateStatus = "";
[ObservableProperty] private string _updateDetail = "";
[ObservableProperty] private string _launcherNotice = "";
/// <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" + LauncherRuntimeInfo.CurrentLauncherVersion;
public string PlatformText => LauncherRuntimeInfo.CurrentRid;
public MainViewModel(AppServices services)
{
_services = services;
Models = services.ModelHost;
Home = new HomeViewModel(services, this);
Download = new DownloadViewModel(services, this);
Settings = new SettingsViewModel(services);
About = new AboutViewModel(services);
Current = Home;
}
partial void OnCurrentChanged(ObservableObject value)
{
IsHomeActive = value is HomeViewModel;
IsDownloadActive = value is DownloadViewModel;
IsSettingsActive = value is SettingsViewModel;
IsAboutActive = value is AboutViewModel;
}
[RelayCommand]
public void GoHome()
{
Home.Refresh();
Current = Home;
}
[RelayCommand]
public void GoDownload()
{
Current = Download;
Download.OnShown();
}
[RelayCommand]
public void GoSettings()
{
Settings.Refresh();
Current = Settings;
}
[RelayCommand]
public void GoAbout()
{
About.OnShown();
Current = About;
}
/// <summary>启动模型:交给模型自己的程序集,在独立窗口中运行。</summary>
public void PlayModel(ModelPackage package)
{
_services.Memory.Refresh();
PlayerRequested?.Invoke(package);
}
public async Task<bool> ConfirmAsync(string message)
=> ConfirmHandler == null || await ConfirmHandler(message);
// ---- 自动更新 ----------------------------------------------------------
/// <summary>启动后由 App 调用:后台检查更新,不阻塞主界面。</summary>
public Task RunStartupUpdateAsync() => RunUpdateAsync(false);
/// <summary>状态条 / 设置页的「检查更新」,忽略自动开关强制检查。</summary>
[RelayCommand]
private Task CheckUpdate() => RunUpdateAsync(true);
private async Task RunUpdateAsync(bool force)
{
if (_updateRunning) return;
_updateRunning = true;
try
{
UpdateBarVisible = true;
UpdateBusy = true;
UpdateProgress = 0;
UpdateStatus = L.I["update.checking"];
UpdateDetail = "";
LauncherNotice = "";
// 在 UI 线程构造,进度回调自动回到 UI 线程
var progress = new Progress<UpdateProgress>(p =>
{
UpdateProgress = Math.Clamp(p.Value, 0, 1);
UpdateStatus = p.Message;
UpdateDetail = p.Detail ?? "";
});
// 双源测速: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();
if ((result.Outcome == UpdateOutcome.NoChange || result.Outcome == UpdateOutcome.Applied) &&
string.IsNullOrEmpty(LauncherNotice))
_ = AutoHideAsync();
}
catch (Exception ex)
{
UpdateStatus = L.I["update.offline"];
UpdateDetail = ex.Message;
}
finally
{
UpdateBusy = false;
_updateRunning = false;
}
}
private async Task AutoHideAsync()
{
try
{
await Task.Delay(6000);
if (!_updateRunning && string.IsNullOrEmpty(LauncherNotice)) UpdateBarVisible = false;
}
catch { /* 忽略 */ }
}
}
-217
View File
@@ -1,217 +0,0 @@
using System;
using System.Collections.ObjectModel;
using System.Linq;
using System.Runtime.InteropServices;
using System.Windows.Input;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using GC.Models;
using GC.Services;
namespace GC.ViewModels;
public sealed class LanguageOption
{
public string Code { get; init; } = "auto";
public string Label { get; set; } = "";
public override string ToString() => Label;
}
public partial class SettingsViewModel : ObservableObject
{
private readonly AppServices _services;
private bool _loading = true;
public ObservableCollection<SettingsSourceViewModel> Sources { get; } = new();
public ObservableCollection<LanguageOption> Languages { get; } = new();
public int[] FrameRates { get; } = { 24, 30, 60, 90, 120 };
[ObservableProperty] private LanguageOption? _selectedLanguage;
[ObservableProperty] private int _selectedFps = 120;
[ObservableProperty] private double _memoryValue = 2048;
[ObservableProperty] private bool _memoryAuto = true;
[ObservableProperty] private string _statusMessage = "";
[ObservableProperty] private bool _autoUpdate = true;
public string UpdateSourceText => _services.Updates.Remote.DisplayName;
public string LastCheckText
{
get
{
var value = _services.Settings.Current.LastUpdateCheck;
if (string.IsNullOrWhiteSpace(value)) return L.I["update.never"];
return DateTimeOffset.TryParse(value, out var time)
? time.ToLocalTime().ToString("yyyy-MM-dd HH:mm") : value!;
}
}
public string PendingText => string.IsNullOrWhiteSpace(_services.Settings.Current.PendingLauncherVersion)
? L.I["update.none"] : _services.Settings.Current.PendingLauncherVersion!;
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;
public string PlatformText => $"{RuntimeInformation.OSDescription} · {RuntimeInformation.RuntimeIdentifier}";
public string VersionText => "v1.0.0";
public string MemoryHint => L.I["set.memory.hint"];
public SettingsViewModel(AppServices services)
{
_services = services;
L.I.LanguageChanged += OnLanguageChanged;
Refresh();
_loading = false;
}
public void Refresh()
{
_loading = true;
BuildLanguages();
var settings = _services.Settings.Current;
SelectedFps = settings.RenderFps;
MemoryValue = settings.MemoryMb;
MemoryAuto = settings.MemoryAuto;
AutoUpdate = settings.AutoUpdateOnStartup;
Sources.Clear();
foreach (var source in settings.Sources)
Sources.Add(new SettingsSourceViewModel(source, _services, this));
_loading = false;
OnPropertyChanged(nameof(UsageText));
OnPropertyChanged(nameof(MemoryValueText));
OnPropertyChanged(nameof(MemoryHint));
OnPropertyChanged(nameof(ModelRoot));
OnPropertyChanged(nameof(DataRoot));
OnPropertyChanged(nameof(UpdateSourceText));
OnPropertyChanged(nameof(LastCheckText));
OnPropertyChanged(nameof(PendingText));
}
partial void OnAutoUpdateChanged(bool value)
{
if (_loading) return;
_services.Settings.Apply(s => s.AutoUpdateOnStartup = value);
}
private void BuildLanguages()
{
var current = _services.Settings.Current.Language;
Languages.Clear();
Languages.Add(new LanguageOption { Code = "auto", Label = L.I["set.language.auto"] });
foreach (var (code, label) in L.Supported)
Languages.Add(new LanguageOption { Code = code, Label = label });
SelectedLanguage = Languages.FirstOrDefault(l => l.Code == current) ?? Languages[0];
}
private void OnLanguageChanged()
{
_loading = true;
BuildLanguages();
_loading = false;
Refresh();
}
partial void OnSelectedLanguageChanged(LanguageOption? value)
{
if (_loading || value == null) return;
_services.Settings.Apply(s => s.Language = value.Code);
L.I.SetLanguage(value.Code);
}
partial void OnSelectedFpsChanged(int value)
{
if (_loading) return;
_services.Settings.Apply(s => s.RenderFps = Math.Clamp(value, 12, 120));
}
partial void OnMemoryValueChanged(double value)
{
if (_loading) return;
var mb = (int)Math.Round(value);
_services.Settings.Apply(s => s.MemoryMb = mb);
_services.Memory.Apply(mb);
OnPropertyChanged(nameof(MemoryValueText));
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);
[RelayCommand]
private void OpenDataFolder() => Shell.OpenFolder(_services.Paths.DataRoot);
[RelayCommand]
private void ClearCache()
{
// 模型数据由模型自己管理;这里只回收启动器侧托管内存
System.GC.Collect();
System.GC.WaitForPendingFinalizers();
_services.Memory.Refresh();
StatusMessage = L.I["set.cacheCleared"];
OnPropertyChanged(nameof(UsageText));
}
[RelayCommand]
private void ApplyMemory()
{
_services.Memory.Apply((int)Math.Round(MemoryValue));
StatusMessage = L.I["common.applied"];
OnPropertyChanged(nameof(UsageText));
}
internal void RemoveSource(SettingsSourceViewModel source)
{
if (source.Model.BuiltIn) return; // 内置默认源不允许删除
_services.Settings.Current.Sources.Remove(source.Model);
_services.Settings.Save();
Sources.Remove(source);
_services.Settings.Notify();
}
}
public partial class SettingsSourceViewModel : ObservableObject
{
private readonly AppServices _services;
private readonly SettingsViewModel _owner;
public ModelSource Model { get; }
public SettingsSourceViewModel(ModelSource model, AppServices services, SettingsViewModel owner)
{
Model = model;
_services = services;
_owner = owner;
RemoveCommand = new RelayCommand(() => _owner.RemoveSource(this));
}
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
{
get => Model.Enabled;
set
{
if (Model.Enabled == value) return;
Model.Enabled = value;
_services.Settings.Save();
OnPropertyChanged();
}
}
public ICommand RemoveCommand { get; }
}
-147
View File
@@ -1,147 +0,0 @@
<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,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}" />
<TextBlock Grid.Row="2" Classes="h3" Text="Git 服务" Margin="0,8,0,0" />
<TextBlock Grid.Row="2" Grid.Column="1" Classes="muted" Text="itxiaohui"
FontWeight="SemiBold" Margin="0,8,0,0" />
</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>
<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="itxiaohui" FontSize="12.5" FontWeight="SemiBold" />
<TextBlock Classes="faint" Text="Git 服务与部署支持" />
</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>
-11
View File
@@ -1,11 +0,0 @@
using Avalonia.Controls;
using Avalonia.Markup.Xaml;
namespace GC.Views;
public partial class AboutView : UserControl
{
public AboutView() => InitializeComponent();
private void InitializeComponent() => AvaloniaXamlLoader.Load(this);
}
-21
View File
@@ -1,21 +0,0 @@
<Window xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
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="Transparent"
SystemDecorations="None"
TransparencyLevelHint="Transparent">
<StackPanel Margin="24,20,24,20" Spacing="14">
<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 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>
-66
View File
@@ -1,66 +0,0 @@
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);
}
-154
View File
@@ -1,154 +0,0 @@
<UserControl xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:loc="using:GC.Services"
x:Class="GC.Views.DownloadView">
<Grid ColumnDefinitions="316,*" Margin="24,22,24,24">
<!-- 模型源 -->
<Border Grid.Column="0" Classes="card" Padding="18" Margin="0,0,16,0">
<Grid RowDefinitions="Auto,Auto,Auto,*,Auto">
<TextBlock Classes="h2" Text="{loc:Loc dl.sources}" />
<!-- 只允许 Xhmcl / GitCode 两个内置源;这里是对比测速并自动切换 -->
<StackPanel Grid.Row="1" Margin="0,12,0,0" Spacing="8">
<Button Classes="primary" Content="测速并切换到最快源"
Command="{Binding ImportCommand}" HorizontalAlignment="Stretch" />
</StackPanel>
<TextBlock Grid.Row="2" Classes="faint" Text="{loc:Loc dl.hint}"
TextWrapping="Wrap" Margin="0,9,0,12" />
<ScrollViewer Grid.Row="3" VerticalScrollBarVisibility="Auto">
<ListBox ItemsSource="{Binding Sources}" SelectedItem="{Binding SelectedSource}"
Background="Transparent" BorderThickness="0" Padding="0">
<ListBox.ItemTemplate>
<DataTemplate>
<Grid ColumnDefinitions="*,Auto" Margin="0,3">
<StackPanel Spacing="2" VerticalAlignment="Center">
<TextBlock Text="{Binding Name}" FontSize="12.5" FontWeight="SemiBold"
TextTrimming="CharacterEllipsis" />
<TextBlock Text="{Binding HostText}" Classes="faint" TextTrimming="CharacterEllipsis" />
</StackPanel>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</ScrollViewer>
<Border Grid.Row="4" Classes="panel" Padding="12,9" Margin="0,10,0,0">
<StackPanel Spacing="3">
<TextBlock Classes="eyebrow" Text="{loc:Loc dl.available}" />
<TextBlock Classes="faint" Text="{Binding StatusMessage}" TextWrapping="Wrap" />
</StackPanel>
</Border>
</Grid>
</Border>
<!-- 可用模型 + 后台任务 -->
<Border Grid.Column="1" Classes="card" Padding="20">
<Grid RowDefinitions="Auto,*,Auto">
<Grid ColumnDefinitions="*,Auto,Auto">
<StackPanel>
<TextBlock Classes="h2" Text="{loc:Loc dl.available}" />
<TextBlock Classes="muted" Text="{Binding StatusMessage}" Margin="0,3,0,0" />
</StackPanel>
<ProgressBar Grid.Column="1" IsIndeterminate="True" Width="90" Height="4"
IsVisible="{Binding IsBusy}" VerticalAlignment="Center" Margin="12,0" />
<Button Grid.Column="2" Classes="small" Content="{loc:Loc dl.refresh}"
Command="{Binding RefreshCommand}" VerticalAlignment="Center" />
</Grid>
<ScrollViewer Grid.Row="1" Margin="0,14,0,0" VerticalScrollBarVisibility="Auto">
<ItemsControl ItemsSource="{Binding Models}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Border Height="{Binding RowHeight}" Opacity="{Binding RowOpacity}"
ClipToBounds="True" Margin="0,0,0,10">
<Border.Transitions>
<Transitions>
<DoubleTransition Property="Height" Duration="0:0:0.24" Easing="CubicEaseOut" />
<DoubleTransition Property="Opacity" Duration="0:0:0.18" />
</Transitions>
</Border.Transitions>
<Border Classes="panel" Padding="14,11">
<Grid ColumnDefinitions="*,Auto">
<StackPanel Spacing="3" VerticalAlignment="Center">
<StackPanel Orientation="Horizontal" Spacing="8">
<TextBlock Text="{Binding Name}" FontSize="13" FontWeight="SemiBold" />
<Border Classes="tag" VerticalAlignment="Center">
<TextBlock Text="{Binding VersionText}" Classes="faint" />
</Border>
<TextBlock Text="{Binding SizeText}" Classes="faint" VerticalAlignment="Center" />
</StackPanel>
<TextBlock Text="{Binding Description}" Classes="muted"
MaxLines="1" TextTrimming="CharacterEllipsis" MaxWidth="520" />
<TextBlock Text="{Binding TagsText}" Classes="faint" IsVisible="{Binding HasTags}" />
</StackPanel>
<Button Grid.Column="1" Classes="primary small" Content="{Binding ButtonText}"
Command="{Binding DownloadCommand}" CommandParameter="{Binding}"
VerticalAlignment="Center" Margin="12,0,0,0" />
</Grid>
</Border>
</Border>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</ScrollViewer>
<!-- 后台任务(下载时折叠到这里) -->
<Border Grid.Row="2" Classes="panel" Margin="0,12,0,0" Padding="6" IsVisible="{Binding HasJobs}">
<StackPanel>
<Grid ColumnDefinitions="*,Auto">
<Button Classes="ghost" Content="{Binding JobSummary}" Command="{Binding ToggleBackgroundCommand}"
HorizontalContentAlignment="Left" FontSize="12" FontWeight="SemiBold" Padding="10,7" />
<Button Grid.Column="1" Classes="ghost small" Content="{loc:Loc dl.clearDone}"
Command="{Binding ClearFinishedCommand}" VerticalAlignment="Center" Margin="0,0,6,0" />
</Grid>
<ScrollViewer MaxHeight="200" IsVisible="{Binding IsBackgroundOpen}">
<ItemsControl ItemsSource="{Binding Jobs}" Margin="6,0,6,6">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Border Background="{DynamicResource Surface}" CornerRadius="9" Padding="10,8" Margin="0,4,0,0">
<Grid ColumnDefinitions="*,Auto">
<StackPanel Spacing="4">
<Grid ColumnDefinitions="*,Auto">
<TextBlock Text="{Binding Name}" FontSize="12" FontWeight="SemiBold" />
<TextBlock Grid.Column="1" Text="{Binding StatusText}" Classes="faint" />
</Grid>
<ProgressBar Value="{Binding Progress}" Maximum="1" IsVisible="{Binding IsActive}" />
<TextBlock Text="{Binding DetailText}" Classes="faint" TextTrimming="CharacterEllipsis" />
</StackPanel>
<StackPanel Grid.Column="1" Orientation="Horizontal" Spacing="2"
VerticalAlignment="Center" Margin="10,0,0,0">
<Button Classes="ghost small" Content="{loc:Loc dl.cancel}"
IsVisible="{Binding IsActive}"
Command="{Binding $parent[ItemsControl].DataContext.CancelJobCommand}"
CommandParameter="{Binding}" />
<Button Classes="ghost small" Content="{loc:Loc dl.retry}"
IsVisible="{Binding CanRetry}"
Command="{Binding $parent[ItemsControl].DataContext.RetryJobCommand}"
CommandParameter="{Binding}" />
<Button Classes="ghost small" Content="{loc:Loc dl.removeTask}"
Command="{Binding $parent[ItemsControl].DataContext.RemoveJobCommand}"
CommandParameter="{Binding}" />
</StackPanel>
</Grid>
</Border>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</ScrollViewer>
</StackPanel>
</Border>
</Grid>
</Border>
</Grid>
</UserControl>
-9
View File
@@ -1,9 +0,0 @@
using Avalonia.Controls;
using Avalonia.Markup.Xaml;
namespace GC.Views;
public partial class DownloadView : UserControl
{
public DownloadView() => AvaloniaXamlLoader.Load(this);
}
-111
View File
@@ -1,111 +0,0 @@
<UserControl xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
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">
<!-- 主视觉 -->
<Border Classes="hero" Padding="26,24">
<Grid ColumnDefinitions="*,Auto">
<StackPanel Spacing="9" MaxWidth="560">
<TextBlock Classes="h1 onDark" Text="{loc:Loc home.title}" />
<TextBlock Text="{loc:Loc home.subtitle}" Foreground="#A9BEDF" FontSize="12.5"
TextWrapping="Wrap" MaxWidth="500" />
<StackPanel Orientation="Horizontal" Spacing="10" Margin="0,12,0,0">
<Button Classes="primary" Content="{loc:Loc home.launch}" Command="{Binding LaunchCommand}" />
<Button Classes="onDark" Content="{loc:Loc home.download}" Command="{Binding OpenDownloadCommand}" />
<Button Classes="onDark" Content="{loc:Loc home.settings}" Command="{Binding OpenSettingsCommand}" />
</StackPanel>
<TextBlock Text="{Binding SelectedHint}" Foreground="#7E93B8" FontSize="11" Margin="2,2,0,0" />
</StackPanel>
<StackPanel Grid.Column="1" Orientation="Horizontal" Spacing="10" VerticalAlignment="Center">
<Border Background="#16233C" CornerRadius="14" Padding="16,12" Width="96">
<StackPanel Spacing="2">
<TextBlock Text="{Binding Models.Count}" Foreground="#FFFFFF" FontSize="22" FontWeight="SemiBold" />
<TextBlock Text="{loc:Loc home.stats.models}" Foreground="#7E93B8" FontSize="10.5" />
</StackPanel>
</Border>
<Border Background="#16233C" CornerRadius="14" Padding="16,12" Width="96">
<StackPanel Spacing="2">
<TextBlock Text="{Binding SourceCountText}" Foreground="#FFFFFF" FontSize="22" FontWeight="SemiBold" />
<TextBlock Text="{loc:Loc home.stats.sources}" Foreground="#7E93B8" FontSize="10.5" />
</StackPanel>
</Border>
<Border Background="#16233C" CornerRadius="14" Padding="16,12" Width="112">
<StackPanel Spacing="2">
<TextBlock Text="{Binding MemoryText}" Foreground="#FFFFFF" FontSize="16" FontWeight="SemiBold" />
<TextBlock Text="{loc:Loc home.stats.memory}" Foreground="#7E93B8" FontSize="10.5" />
</StackPanel>
</Border>
</StackPanel>
</Grid>
</Border>
<!-- 列表标题 -->
<Grid ColumnDefinitions="*,Auto" Margin="2,4,2,0">
<TextBlock Classes="h2" Text="{loc:Loc home.installed}" />
<TextBlock Grid.Column="1" Classes="muted" Text="{Binding CountText}" VerticalAlignment="Center" />
</Grid>
<!-- 模型卡片 -->
<ItemsControl ItemsSource="{Binding Models}" IsVisible="{Binding !IsEmpty}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel Orientation="Horizontal" />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Border Classes="card" Width="336" Margin="0,0,16,16" ClipToBounds="True">
<StackPanel>
<Border Height="138" Background="#0B1226" ClipToBounds="True">
<Panel>
<TextBlock Text="◎" FontSize="34" Foreground="#1B2A47"
HorizontalAlignment="Center" VerticalAlignment="Center" />
<Image Source="{Binding Preview}" Stretch="UniformToFill" />
</Panel>
</Border>
<StackPanel Margin="16,13,16,15" Spacing="7">
<Grid ColumnDefinitions="*,Auto">
<TextBlock Classes="h3" Text="{Binding Name}" TextTrimming="CharacterEllipsis" />
<TextBlock Grid.Column="1" Classes="faint" Text="{Binding MetaText}"
VerticalAlignment="Center" Margin="8,0,0,0" />
</Grid>
<TextBlock Classes="muted" Text="{Binding Description}" TextWrapping="Wrap"
MaxLines="2" Height="32" TextTrimming="CharacterEllipsis" />
<TextBlock Classes="faint" Text="{Binding TagsText}" IsVisible="{Binding HasTags}" />
<Grid ColumnDefinitions="Auto,*,Auto,Auto" Margin="0,6,0,0">
<Button Classes="primary small" Content="{loc:Loc home.launch}"
Command="{Binding LaunchCommand}" />
<Button Grid.Column="2" Classes="ghost small" Content="{loc:Loc home.open}"
Command="{Binding OpenFolderCommand}" Margin="0,0,4,0" />
<Button Grid.Column="3" Classes="ghost small danger" Content="{loc:Loc home.delete}"
Command="{Binding DeleteCommand}" />
</Grid>
</StackPanel>
</StackPanel>
</Border>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
<!-- 空状态 -->
<Border Classes="card" Padding="30,34" IsVisible="{Binding IsEmpty}">
<StackPanel Spacing="10" HorizontalAlignment="Center">
<TextBlock Classes="h2" Text="{loc:Loc home.empty}" HorizontalAlignment="Center" />
<TextBlock Classes="muted" Text="{loc:Loc home.emptyHint}" TextWrapping="Wrap"
MaxWidth="420" TextAlignment="Center" />
<Button Classes="primary" Content="{loc:Loc home.emptyAction}"
Command="{Binding OpenDownloadCommand}" HorizontalAlignment="Center" Margin="0,6,0,0" />
</StackPanel>
</Border>
</StackPanel>
</ScrollViewer>
</UserControl>
-9
View File
@@ -1,9 +0,0 @@
using Avalonia.Controls;
using Avalonia.Markup.Xaml;
namespace GC.Views;
public partial class HomeView : UserControl
{
public HomeView() => AvaloniaXamlLoader.Load(this);
}
-107
View File
@@ -1,107 +0,0 @@
using System;
using Avalonia;
using Avalonia.Animation;
using Avalonia.Animation.Easings;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Avalonia.Layout;
using Avalonia.Media;
using Avalonia.Threading;
namespace GC.Views;
/// <summary>
/// 模型启动进度窗:加载模型程序集、生成地表纹理、构建界面的真实进度。
/// 只显示进度,不做任何渲染。
/// </summary>
public sealed class LoadingWindow : Window
{
private readonly ProgressBar _bar;
private readonly TextBlock _stage;
private readonly TextBlock _percent;
public LoadingWindow(string modelName)
{
Title = modelName;
Width = 460;
Height = 172;
CanResize = false;
ShowInTaskbar = false;
WindowStartupLocation = WindowStartupLocation.CenterOwner;
Background = new SolidColorBrush(Color.Parse("#0B1226"));
SystemDecorations = SystemDecorations.BorderOnly;
var title = new TextBlock
{
Text = modelName,
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,
IsIndeterminate = true,
CornerRadius = new CornerRadius(3),
Foreground = new SolidColorBrush(Color.Parse("#3B7BFF")),
Background = new SolidColorBrush(Color.Parse("#1B2740")),
Transitions = new Transitions
{
// 进度平滑增长,不会一跳一跳
new DoubleTransition
{
Property = RangeBase.ValueProperty,
Duration = TimeSpan.FromMilliseconds(240),
Easing = new CubicEaseOut()
}
}
};
_percent = new TextBlock
{
Text = "",
Foreground = new SolidColorBrush(Color.Parse("#6E86AD")),
FontSize = 11,
HorizontalAlignment = HorizontalAlignment.Right
};
var panel = new StackPanel
{
Margin = new Thickness(22, 20),
Spacing = 12
};
panel.Children.Add(title);
panel.Children.Add(_bar);
panel.Children.Add(_stage);
panel.Children.Add(_percent);
Content = panel;
}
/// <summary>任意线程调用都可以。</summary>
public void Report(double value, string? message)
{
if (!Dispatcher.UIThread.CheckAccess())
{
Dispatcher.UIThread.Post(() => Report(value, message));
return;
}
var clamped = Math.Clamp(value, 0, 1);
_bar.IsIndeterminate = false;
_bar.Value = clamped;
_percent.Text = $"{clamped * 100:0}%";
if (!string.IsNullOrWhiteSpace(message)) _stage.Text = message;
}
}
-119
View File
@@ -1,119 +0,0 @@
<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>
-216
View File
@@ -1,216 +0,0 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Threading.Tasks;
using Avalonia;
using Avalonia.Animation;
using Avalonia.Animation.Easings;
using Avalonia.Threading;
using System.Linq;
using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Markup.Xaml;
using GC.Models;
using GC.Services;
using GC.ViewModels;
namespace GC.Views;
public partial class MainWindow : Window
{
private readonly List<PlayerWindow> _players = new();
private MainViewModel? _viewModel;
private ContentControl? _pageHost;
private bool _isClosing;
public MainWindow()
{
InitializeComponent();
_pageHost = this.FindControl<ContentControl>("PageHost");
if (_pageHost != null)
{
// 页面切换:淡入过渡,避免瞬间硬切
_pageHost.Transitions = new Transitions
{
new DoubleTransition
{
Property = Visual.OpacityProperty,
Duration = TimeSpan.FromMilliseconds(200),
Easing = new CubicEaseOut()
}
};
}
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>
public IReadOnlyList<PlayerWindow> PlayerWindows => _players;
private void InitializeComponent() => AvaloniaXamlLoader.Load(this);
private void OnDataContextChanged(object? sender, EventArgs e)
{
if (_viewModel != null)
{
_viewModel.PlayerRequested -= OpenPlayerWindow;
_viewModel.PropertyChanged -= OnViewModelPropertyChanged;
}
_viewModel = DataContext as MainViewModel;
if (_viewModel != null)
{
_viewModel.PlayerRequested += OpenPlayerWindow;
_viewModel.PropertyChanged += OnViewModelPropertyChanged;
}
}
/// <summary>切换页面时让内容淡入,避免「一卡一卡」的硬切。</summary>
private void OnViewModelPropertyChanged(object? sender, PropertyChangedEventArgs e)
{
if (e.PropertyName != nameof(MainViewModel.Current) || _pageHost == null) return;
_pageHost.Opacity = 0.55;
// 下一帧回到 1,OpacityTransition 会自动插值
Dispatcher.UIThread.Post(() =>
{
if (_pageHost != null) _pageHost.Opacity = 1;
}, DispatcherPriority.Render);
}
// 事件处理器必须是 void,因此包一层可观察异常的入口:
// fire-and-forget 的 Task 也要观察异常,绝不外泄到 Avalonia 事件循环导致进程崩溃。
private void OpenPlayerWindow(ModelPackage package) => _ = OpenPlayerWindowSafeAsync(package);
private async Task OpenPlayerWindowSafeAsync(ModelPackage package)
{
try { await OpenPlayerWindowAsync(package); }
catch (Exception ex) { Console.Error.WriteLine($"打开模型窗口失败: {ex}"); }
}
private async Task OpenPlayerWindowAsync(ModelPackage package)
{
if (_viewModel == null || _isClosing) return;
// 启动进度窗:模型加载、地表纹理生成、界面构建的真实进度
var loading = new LoadingWindow(package.LocalizedName);
loading.Show(this);
loading.Report(0, "正在加载模型…");
// 让进度窗先画出来(用调度器让出一帧,测试环境也能推进)
await Dispatcher.UIThread.InvokeAsync(() => { }, DispatcherPriority.Render);
PlayerWindow? window = null;
LoadedModel? loaded = null;
Exception? error = null;
// 关键修复:requestClose 过去捕获的是「尚未赋值的 window」,加载期恒为 null,
// 模型在 Prepare/CreateView 里调用 context.RequestClose() 会静默失效。
// 改为关闭当前存在的窗口(加载期=进度窗,加载完成=模型窗),统一走 UI 线程。
void RequestClose() => Dispatcher.UIThread.Post(() =>
{
(window ?? (Window?)loading)?.Close();
});
try
{
loaded = await _viewModel.Models.LoadAsync(package, RequestClose,
(value, message) => loading.Report(value, message));
}
catch (Exception ex)
{
error = ex;
}
loading.Close();
// 加载期间用户关掉了主窗口:不要再弹出幽灵模型窗口,直接释放已加载模型
if (_isClosing)
{
loaded?.Dispose();
return;
}
if (loaded == null || error != null)
{
var message = error?.Message ?? L.I["player.errorHint"];
var dialog = new ModelErrorWindow(
L.I.F("player.errorTitle", package.LocalizedName),
$"{message}\n\n{L.I["player.errorHint"]}");
dialog.Show(this);
return;
}
window = new PlayerWindow(package, loaded);
window.Closed += (_, _) => _players.Remove(window);
_players.Add(window);
window.Show(this);
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;
if (_viewModel != null)
{
_viewModel.PlayerRequested -= OpenPlayerWindow;
_viewModel.PropertyChanged -= OnViewModelPropertyChanged;
}
// 先取快照再关闭:PlayerWindow.Closed 回调会 _players.Remove,
// 直接遍历原集合会在 foreach 期间修改底层导致异常。
foreach (var window in _players.ToList()) window.Close();
_players.Clear();
}
}
-143
View File
@@ -1,143 +0,0 @@
<UserControl xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
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">
<StackPanel Spacing="4">
<TextBlock Classes="h1" Text="{loc:Loc set.title}" />
<TextBlock Classes="muted" Text="{loc:Loc set.subtitle}" />
</StackPanel>
<!-- 通用 -->
<Border Classes="card" Padding="20,18">
<StackPanel Spacing="16">
<TextBlock Classes="h2" Text="{loc:Loc set.general}" />
<Grid ColumnDefinitions="200,*">
<StackPanel VerticalAlignment="Center" Spacing="2">
<TextBlock Classes="h3" Text="{loc:Loc set.language}" />
</StackPanel>
<ComboBox Grid.Column="1" ItemsSource="{Binding Languages}"
SelectedItem="{Binding SelectedLanguage}" Width="220" HorizontalAlignment="Left">
<ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Label}" />
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
</Grid>
<Grid ColumnDefinitions="200,*">
<StackPanel VerticalAlignment="Center" Spacing="2">
<TextBlock Classes="h3" Text="{loc:Loc set.fps}" />
<TextBlock Classes="faint" Text="{loc:Loc set.fps.desc}" TextWrapping="Wrap" />
</StackPanel>
<ComboBox Grid.Column="1" ItemsSource="{Binding FrameRates}"
SelectedItem="{Binding SelectedFps}" Width="120" HorizontalAlignment="Left" />
</Grid>
</StackPanel>
</Border>
<!-- 内存 -->
<Border Classes="card" Padding="20,18">
<StackPanel Spacing="12">
<Grid ColumnDefinitions="*,Auto">
<TextBlock Classes="h2" Text="{loc:Loc set.memory}" />
<TextBlock Grid.Column="1" Text="{Binding MemoryValueText}" Classes="h3"
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" />
<TextBlock Grid.Column="1" Classes="faint" Text="{Binding UsageText}" Margin="16,0,0,0" />
</Grid>
</StackPanel>
</Border>
<!-- 模型源 -->
<Border Classes="card" Padding="20,18">
<StackPanel Spacing="10">
<TextBlock Classes="h2" Text="{loc:Loc set.sources}" />
<TextBlock Classes="muted" Text="{loc:Loc set.sources.desc}" TextWrapping="Wrap" />
<ItemsControl ItemsSource="{Binding Sources}" Margin="0,4,0,0">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Border Classes="panel" Padding="12,9" Margin="0,0,0,8">
<Grid ColumnDefinitions="Auto,*,Auto">
<CheckBox IsChecked="{Binding Enabled}" VerticalAlignment="Center" Margin="0,0,10,0" />
<StackPanel Grid.Column="1" Spacing="2" VerticalAlignment="Center">
<TextBlock Text="{Binding Name}" FontSize="12.5" FontWeight="SemiBold" />
<TextBlock Text="{Binding UrlText}" Classes="faint" TextTrimming="CharacterEllipsis" MaxWidth="520" />
</StackPanel>
<Button Grid.Column="2" Classes="ghost small" Content="✕"
IsVisible="{Binding CanRemove}" Command="{Binding RemoveCommand}" VerticalAlignment="Center" />
</Grid>
</Border>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</StackPanel>
</Border>
<!-- 自动更新 -->
<Border Classes="card" Padding="20,18">
<StackPanel Spacing="12">
<TextBlock Classes="h2" Text="{loc:Loc update.title}" />
<TextBlock Classes="muted" Text="{loc:Loc update.desc}" TextWrapping="Wrap" />
<CheckBox IsChecked="{Binding AutoUpdate}" Content="{loc:Loc update.auto}" />
<Grid ColumnDefinitions="200,*">
<TextBlock Classes="h3" Text="{loc:Loc update.source}" VerticalAlignment="Center" />
<TextBlock Grid.Column="1" Classes="muted" Text="{Binding UpdateSourceText}"
TextTrimming="CharacterEllipsis" VerticalAlignment="Center" />
</Grid>
<Grid ColumnDefinitions="200,*">
<TextBlock Classes="h3" Text="{loc:Loc update.lastCheck}" />
<TextBlock Grid.Column="1" Classes="muted" Text="{Binding LastCheckText}" />
</Grid>
<Grid ColumnDefinitions="200,*">
<TextBlock Classes="h3" Text="{loc:Loc update.pending}" />
<TextBlock Grid.Column="1" Classes="muted" Text="{Binding PendingText}" />
</Grid>
</StackPanel>
</Border>
<!-- 存储 -->
<Border Classes="card" Padding="20,18">
<StackPanel Spacing="14">
<TextBlock Classes="h2" Text="{loc:Loc set.storage}" />
<Grid ColumnDefinitions="200,*,Auto">
<TextBlock Classes="h3" Text="{loc:Loc set.modelDir}" VerticalAlignment="Center" />
<TextBlock Grid.Column="1" Classes="muted" Text="{Binding ModelRoot}"
TextTrimming="CharacterEllipsis" VerticalAlignment="Center" Margin="0,0,10,0" />
<Button Grid.Column="2" Classes="small" Content="{loc:Loc set.openFolder}"
Command="{Binding OpenModelFolderCommand}" />
</Grid>
<Grid ColumnDefinitions="200,*,Auto">
<TextBlock Classes="h3" Text="{loc:Loc set.dataDir}" VerticalAlignment="Center" />
<TextBlock Grid.Column="1" Classes="muted" Text="{Binding DataRoot}"
TextTrimming="CharacterEllipsis" VerticalAlignment="Center" Margin="0,0,10,0" />
<Button Grid.Column="2" Classes="small" Content="{loc:Loc set.openFolder}"
Command="{Binding OpenDataFolderCommand}" />
</Grid>
<Grid ColumnDefinitions="*,Auto">
<TextBlock Classes="faint" Text="{Binding StatusMessage}" VerticalAlignment="Center" />
<Button Grid.Column="1" Classes="small" Content="{loc:Loc set.clearCache}"
Command="{Binding ClearCacheCommand}" />
</Grid>
</StackPanel>
</Border>
</StackPanel>
</ScrollViewer>
</UserControl>
-9
View File
@@ -1,9 +0,0 @@
using Avalonia.Controls;
using Avalonia.Markup.Xaml;
namespace GC.Views;
public partial class SettingsView : UserControl
{
public SettingsView() => AvaloniaXamlLoader.Load(this);
}
-109
View File
@@ -1,109 +0,0 @@
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;
}
}
@@ -1,21 +0,0 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<Nullable>enable</Nullable>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<RootNamespace>GC.Tests</RootNamespace>
<AssemblyName>GC.Tests</AssemblyName>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Avalonia.Headless" Version="$(AvaloniaVersion)" />
<PackageReference Include="Avalonia.Skia" Version="$(AvaloniaVersion)" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="../../../GC.Core.csproj" />
<ProjectReference Include="../../../../../GC-DOWNLOAD/GC-DOWNLOAD.csproj" />
</ItemGroup>
</Project>
-67
View File
@@ -1,67 +0,0 @@
using System;
using System.IO;
using System.Linq;
using GC.Services;
namespace GC.Tests;
/// <summary>
/// 日志模块的用例:双语写入、跨天文件命名、旧日志清理、不误删用户文件。
///
/// 这些看起来是小事,但 <c>.GC/logs</c> 会随程序跑很久:写入路径每行开两个文件句柄,
/// 或者完全不清理,都会在几个月后变成用户磁盘上的几 GB。用例锁住这两个行为。
/// </summary>
internal static class LogTests
{
private static int _failed;
public static int Run()
{
var dir = Path.Combine(Path.GetTempPath(), "gc-log-" + Guid.NewGuid().ToString("N")[..8]);
Directory.CreateDirectory(dir);
try
{
// 过期日志(2000 年)+ 用户自己的文件
var oldZh = Path.Combine(dir, "gc-20000101.log");
var oldEn = Path.Combine(dir, "gc-20000101.en.log");
var userFile = Path.Combine(dir, "keep-me.txt");
File.WriteAllText(oldZh, "old");
File.WriteAllText(oldEn, "old");
File.WriteAllText(userFile, "user data");
GcLog.Init(dir);
GcLog.Info("测试中文", "test english");
var day = DateTime.Now.ToString("yyyyMMdd");
var zhPath = Path.Combine(dir, $"gc-{day}.log");
var enPath = Path.Combine(dir, $"gc-{day}.en.log");
Check("中文日志写入", File.Exists(zhPath) && File.ReadAllText(zhPath).Contains("测试中文"), "中文日志缺失");
Check("英文日志写入", File.Exists(enPath) && File.ReadAllText(enPath).Contains("test english"), "英文日志缺失");
Check("过期日志被清理", !File.Exists(oldZh) && !File.Exists(oldEn), "2000 年的日志还在");
Check("目录里的用户文件不被误删", File.Exists(userFile), "keep-me.txt 被删了");
var names = Directory.GetFiles(dir).Select(Path.GetFileName).OrderBy(n => n).ToArray();
Check("日志目录只剩当天两份 + 用户文件",
names.Length == 3, "目录内容: " + string.Join(", ", names));
}
finally
{
try { Directory.Delete(dir, true); } catch { }
}
Console.WriteLine(_failed == 0 ? "日志测试全部通过" : $"日志测试失败 {_failed} 项");
return _failed;
}
private static void Check(string label, bool ok, string detail)
{
if (ok)
{
Console.WriteLine(" ✓ " + label);
return;
}
_failed++;
Console.WriteLine($" ✗ {label} —— {detail}");
}
}
-562
View File
@@ -1,562 +0,0 @@
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 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 GC;
using GC.Download;
using GC.Services;
using GC.ViewModels;
using GC.Views;
namespace GC.Tests;
/// <summary>
/// 离屏校验工具:把启动器页面和模型窗口渲染成 PNG。
/// 用法:dotnet run --project GC/src/test/dotnet/GC.Tests -- build/screenshots
/// </summary>
internal static class Program
{
private static string _outDir = "screenshots";
[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());
_outDir = args.Length > 0 ? args[0] : "screenshots";
Directory.CreateDirectory(_outDir);
Environment.SetEnvironmentVariable("EMS_HOME", FindRepoRoot());
Environment.SetEnvironmentVariable("EMS_DATA", Path.Combine(_outDir, ".data"));
AppBuilder.Configure<App>()
.UseSkia()
.UseHeadless(new AvaloniaHeadlessPlatformOptions { UseHeadlessDrawing = false })
.SetupWithoutStarting();
var services = AppServices.Create();
RenderPages(services);
Console.WriteLine("截图输出: " + Path.GetFullPath(_outDir));
// 日志模块的用例放在渲染之后:它会切换 GcLog 的输出目录
return LogTests.Run() == 0 ? 0 : 1;
}
/// <summary>
/// 离线验证自动更新完整链路:用本地目录冒充 gitcode 仓库,不访问网络、不替换真实程序。
/// </summary>
private static int RunUpdateTest(string repoRoot)
{
Console.WriteLine("=== 离线自动更新链路验证 ===");
AppBuilder.Configure<App>()
.UseSkia()
.UseHeadless(new AvaloniaHeadlessPlatformOptions { UseHeadlessDrawing = false })
.SetupWithoutStarting();
L.I.Initialize("zh-CN");
var versionFile = Path.Combine(repoRoot, "version.json");
if (!File.Exists(versionFile))
{
Console.WriteLine("FAIL: 缺少 version.json,请先执行 ./build.sh stamp");
return 1;
}
var tmp = Path.Combine(Path.GetTempPath(), "ems-update-" + Guid.NewGuid().ToString("N")[..8]);
var remote = Path.Combine(tmp, "remote");
var home = Path.Combine(tmp, ".GC");
var modelRoot = Path.Combine(home, "model");
Directory.CreateDirectory(modelRoot);
// 模拟远端仓库:version.json + 每个模型的 <id>.json / <id>.model/
Directory.CreateDirectory(Path.Combine(remote, "model"));
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);
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(remote, "model", id);
Directory.CreateDirectory(dest);
File.Copy(manifest, Path.Combine(dest, id + ".json"), true);
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", null);
Environment.SetEnvironmentVariable("EMS_NO_SELF_UPDATE", "1");
var paths = AppPaths.Discover();
paths.EnsureCreated();
var settings = new SettingsService(paths);
settings.Load();
var updater = new UpdateService(paths, settings, new DirectoryRemote(remote));
var failures = 0;
void Check(bool ok, string label)
{
Console.WriteLine($" {(ok ? "OK " : "FAIL")} {label}");
if (!ok) failures++;
}
Console.WriteLine($"运行目录: {paths.HomeRoot}");
Console.WriteLine($"模型库: {paths.ModelRoot}");
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 = 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" })
{
var dir = Path.Combine(modelRoot, id);
Check(File.Exists(Path.Combine(dir, id + ".json")), id + " 清单已落地");
Check(File.Exists(Path.Combine(dir, id + ".model", "scene.json")), id + " 场景数据已落地");
Check(!Directory.Exists(Path.Combine(dir, "src")), id + " 源码没有下到运行目录");
Check(settings.Current.InstalledModelVersions.ContainsKey(id), id + " 版本已记录到 settings");
}
// 2) 版本没变:不重复下载
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>(remoteManifest)!;
Check(rv.Models.Count == 2 && !string.IsNullOrWhiteSpace(rv.Models[0].Version),
"version.json 里模型版本由构建自动生成");
var changed = rv.Models[0];
changed.Version += "-changed";
var stampName = "_version-stamp.txt";
File.WriteAllText(Path.Combine(remote, "model", changed.Id,
changed.Id + ".model", stampName), "new content");
// 内容变了 → 指纹必须跟着变,并且清单要重新签名,否则客户端会(正确地)拒绝
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) 启动器新版:用 LauncherUpdater 下载到当前目录(与旧版并列)
var rid = LauncherRuntimeInfo.CurrentRid;
Console.WriteLine($"当前平台: {rid},启动器版本: {LauncherRuntimeInfo.CurrentLauncherVersion}");
var stage = Path.Combine(tmp, "launcher-stage");
Directory.CreateDirectory(stage);
// Linux 的启动器没有扩展名,测试包名要跟着平台走
var launcherExt = OperatingSystem.IsWindows() ? ".exe" : "";
File.WriteAllText(Path.Combine(stage, "GCL-9.9.9-" + LauncherUpdater.PlatformLabel + launcherExt),
"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,
Sha256 = Convert.ToHexString(SHA256.HashData(File.ReadAllBytes(zip))).ToLowerInvariant(),
Size = new FileInfo(zip).Length
};
WriteSigned(remoteManifest, rv, signer);
// 造一个旧版在当前目录
var oldName = "GC-1.0.0-" + LauncherUpdater.PlatformLabel + launcherExt;
File.WriteAllText(Path.Combine(paths.InstallDirectory, oldName), "old launcher");
var dl = Task.Run(() => LauncherUpdater.DownloadAsync(paths, updater.Remote, null))
.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 ?? "", execute: false);
var scriptPath = Path.Combine(paths.UpdateRoot,
OperatingSystem.IsWindows() ? "apply.bat" : "apply.sh");
Check(scheduled && File.Exists(scriptPath), "替换脚本可生成");
if (File.Exists(scriptPath))
{
var script = File.ReadAllText(scriptPath);
Check(!script.Contains(tmp), "脚本不含绝对路径");
Check(script.Contains("GC-*") || script.Contains("GCL-*"), "脚本按 GC-*/GCL-* 匹配删除");
}
// 5b) 只发产物、不发 Release:更新包只存在于仓库 dist/<系统>-<架构>/ 目录里。
// 清单不写 url、不写 path,只给 dir + name + sha256,客户端要能自己找过去。
var distDir = Path.Combine(remote, "dist", LauncherUpdater.PlatformLabel);
Directory.CreateDirectory(distDir);
var distName = "GCL-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 = 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")),
"断网时保留本地模型、不清空模型库");
try { Directory.Delete(tmp, true); } catch { }
Console.WriteLine(failures == 0
? "=== 自动更新链路全部通过 ==="
: $"=== 有 {failures} 项失败 ===");
return failures == 0 ? 0 : 1;
}
/// <summary>序列化清单并用私钥签名(测试里模拟一次正式发布)。</summary>
private static void WriteSigned(string path, RepoVersion version, ECDsa key)
{
// keyId 必须与 .signing/ 里的私钥对应的公钥条目一致,否则客户端按 keyId
// 查不到受信任公钥,会判成 Invalid 而不是 Verified。
var text = JsonSerializer.Serialize(version, Json.Options) + "\n";
File.WriteAllText(path, ManifestSignature.SignDocument(text, key, "gc-2026-12"));
}
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 dest = Path.Combine(dst, Path.GetRelativePath(src, file));
Directory.CreateDirectory(Path.GetDirectoryName(dest)!);
File.Copy(file, dest, true);
}
}
private static string FindRepoRoot()
{
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, "GC.sln"))) return dir.FullName;
}
return Directory.GetCurrentDirectory();
}
private static void RenderPages(AppServices services)
{
var vm = new MainViewModel(services);
var window = new MainWindow { DataContext = vm };
window.Show();
Dispatcher.UIThread.RunJobs();
Capture(window, "page-home.png");
vm.GoDownloadCommand.Execute(null);
Dispatcher.UIThread.RunJobs();
Capture(window, "page-download.png");
vm.GoSettingsCommand.Execute(null);
Dispatcher.UIThread.RunJobs();
Capture(window, "page-settings.png");
// 启动进度窗(单独截图)
var demoLoading = new LoadingWindow("地球自转");
demoLoading.Show(window);
demoLoading.Report(0.42, "生成地表纹理");
Dispatcher.UIThread.RunJobs();
Capture(demoLoading, "page-loading.png");
demoLoading.Close();
var packages = services.Models.Scan();
Console.WriteLine($"模型数: {packages.Count}");
foreach (var p in packages)
Console.WriteLine($" {p.Id}: 程序集={Path.GetFileName(p.AssemblyPath)} 存在={File.Exists(p.AssemblyPath)} 封面={File.Exists(p.PreviewPath)}");
// 启动模型:应当新开窗口,主窗口保持原页面
for (var i = 0; i < packages.Count && i < 2; i++)
{
var before = window.PlayerWindows.Count;
vm.PlayModel(packages[i]);
// 加载是异步的(带进度窗),这里泵一下调度器等它完成
var appeared = WaitFor(() => window.PlayerWindows.Count > before);
var player = window.PlayerWindows.LastOrDefault();
Console.WriteLine($"player windows = {window.PlayerWindows.Count} ({packages[i].Id}) appeared={appeared}");
if (player == null) continue;
if (i == 0)
{
Dispatcher.UIThread.RunJobs();
Capture(player, "page-player.png");
}
else
{
Capture(player, "page-player-rotation.png");
}
// 节气定位 / 视图切换只属于公转模型;自转模型不该出现
var hasSeasons = Descendants(player).OfType<TextBlock>()
.Any(t => (t.Text ?? "").Contains("节气定位", StringComparison.Ordinal) && ShownInTree(t));
var hasViewSwitch = Descendants(player).OfType<Button>()
.Any(b => b.Tag is string tag && (tag == "rotation" || tag == "revolution") && ShownInTree(b));
Console.WriteLine($" {packages[i].Id}: 节气定位={hasSeasons} 视图切换={hasViewSwitch}");
// 缩放 / 触控 / 教学能力:模型画布由模型程序集提供,这里用反射逐项校验
var canvases = Descendants(player).Where(c => c.GetType().Name == "CelestialView").ToList();
var canvas = canvases.FirstOrDefault(c => Prop(c, "InsetMode") is bool inset && !inset)
?? canvases.FirstOrDefault();
var isRevolution = packages[i].Id.Contains("revolution", StringComparison.OrdinalIgnoreCase);
Console.WriteLine($" {packages[i].Id}: 画布数={canvases.Count}(含课堂特写)");
if (canvas != null)
{
var type = canvas.GetType();
var zoomProp = type.GetProperty("Zoom");
var zoomBy = type.GetMethod("ZoomBy");
var resetView = type.GetMethod("ResetView");
var beforeZoom = (double)(zoomProp?.GetValue(canvas) ?? 0d);
zoomBy?.Invoke(canvas, new object[] { 1.25 });
var afterZoom = (double)(zoomProp?.GetValue(canvas) ?? 0d);
resetView?.Invoke(canvas, null);
var resetZoom = (double)(zoomProp?.GetValue(canvas) ?? 0d);
var hasPointerOverride = type.GetMethod("OnPointerMoved",
System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic) != null;
var hasMultiTouch = type.GetField("_pointers",
System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic) != null;
Console.WriteLine($" {packages[i].Id}: 缩放={beforeZoom:0.00}→{afterZoom:0.00}→{resetZoom:0.00} 拖动={hasPointerOverride} 多指跟踪={hasMultiTouch}");
// 双指捏合:两指间距 100→150,缩放应当 1.00→1.50
var pinch = type.GetMethod("PinchZoom",
System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static);
var pinchZoom = (double)(pinch?.Invoke(null, new object[] { 1.0, 100.0, 150.0 }) ?? 0d);
Console.WriteLine($" {packages[i].Id}: 捏合 100→150px = {pinchZoom:0.00}×");
// 手动转动:竖直拖动 300px 也不能改变视角平面
var elevBefore = Field(canvas, "_camElevTarget");
var angleBefore = (double)(Prop(canvas, isRevolution ? "OrbitAngle" : "SpinAngle") ?? 0d);
type.GetMethod("DragBy")?.Invoke(canvas, new object[] { 40.0, 300.0 });
var elevAfter = Field(canvas, "_camElevTarget");
var angleAfter = (double)(Prop(canvas, isRevolution ? "OrbitAngle" : "SpinAngle") ?? 0d);
Console.WriteLine($" {packages[i].Id}: 拖动 视角={elevBefore}→{elevAfter} 地球角度={angleBefore:0.0}→{angleAfter:0.0} 平面不变={Equals(elevBefore, elevAfter)}");
if (isRevolution)
{
// 两至日的直射点必须是教材值 23.5°
foreach (var (angle, expect) in new[] { (0d, 0d), (90d, 23.5d), (180d, 0d), (270d, -23.5d) })
{
type.GetMethod("JumpToOrbit")?.Invoke(canvas, new object[] { angle });
var decl = (double)(Prop(canvas, "SubsolarLatitude") ?? double.NaN);
Console.WriteLine($" 直射点 {angle:0}° => {decl:0.00}° (应 {expect:0.0}°,误差 {Math.Abs(decl - expect):0.000})");
}
// 点「夏至」应自动定格,并显示 23.5°N 的课堂读数
var summer = Descendants(player).OfType<Button>()
.FirstOrDefault(b => (b.Content as TextBlock)?.Text == "夏至" && ShownInTree(b));
summer?.RaiseEvent(new Avalonia.Interactivity.RoutedEventArgs(Button.ClickEvent));
Dispatcher.UIThread.RunJobs();
var frozen = Prop(canvas, "IsPlaying") is bool play && !play;
var frozenAngle = (double)(Prop(canvas, "OrbitAngle") ?? -1d);
var cardReadout = Descendants(player).OfType<TextBlock>()
.Any(t => (t.Text ?? "") == "23.5°N" && ShownInTree(t));
Console.WriteLine($" 夏至按钮: 已定格={frozen} 角度={frozenAngle:0} 课堂卡显示 23.5°N={cardReadout}");
Capture(player, "page-player-solstice.png");
}
}
// 课堂演示卡 / 底部触控提示
var hasCard = Descendants(player).OfType<TextBlock>()
.Any(t => (t.Text ?? "").Contains("课堂演示", StringComparison.Ordinal) && ShownInTree(t));
var hasHint = Descendants(player).OfType<TextBlock>()
.Any(t => (t.Text ?? "").Contains("拖动", StringComparison.Ordinal) && ShownInTree(t));
Console.WriteLine($" {packages[i].Id}: 课堂演示卡={hasCard} 交互提示={hasHint}");
}
// 关掉第二个窗口,只留一个继续验证主窗口
var second = window.PlayerWindows.LastOrDefault();
if (second != null) second.Close();
Dispatcher.UIThread.RunJobs();
Console.WriteLine($"window after closing second = {window.PlayerWindows.Count}");
// 主窗口仍停留在设置页 —— 说明没有被模型画面覆盖
Capture(window, "page-main-while-playing.png");
foreach (var player in window.PlayerWindows.ToList()) player.Close();
Dispatcher.UIThread.RunJobs();
window.Close();
}
private static object? Prop(Control control, string name)
=> control.GetType().GetProperty(name)?.GetValue(control);
private static object? Field(Control control, string name)
=> control.GetType().GetField(name,
System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic)?.GetValue(control);
private static bool WaitFor(Func<bool> condition, int timeoutMs = 20000)
{
var watch = Stopwatch.StartNew();
while (watch.ElapsedMilliseconds < timeoutMs)
{
Dispatcher.UIThread.RunJobs();
if (condition()) return true;
Thread.Sleep(15);
}
return condition();
}
private static bool ShownInTree(Control control)
{
Visual? current = control;
while (current != null)
{
if (current is Control c && !c.IsVisible) return false;
current = current.GetVisualParent();
}
return true;
}
private static IEnumerable<Control> Descendants(Control root)
{
var stack = new Stack<Control>();
stack.Push(root);
while (stack.Count > 0)
{
var current = stack.Pop();
yield return current;
switch (current)
{
case Panel panel:
foreach (var child in panel.Children) stack.Push(child);
break;
case Border { Child: Control only }:
stack.Push(only);
break;
case ScrollViewer { Content: Control scrolled }:
stack.Push(scrolled);
break;
case ContentControl { Content: Control content }:
stack.Push(content);
break;
}
}
}
private static void Capture(Window window, string fileName)
{
try
{
var frame = window.CaptureRenderedFrame();
if (frame == null)
{
Console.WriteLine("capture failed: " + fileName);
return;
}
var path = Path.Combine(_outDir, fileName);
frame.Save(path);
Console.WriteLine($"page -> {path}");
}
catch (Exception ex)
{
Console.WriteLine($"capture error {fileName}: {ex.Message}");
}
}
}