移动部分文件
No files matched your search
@@ -0,0 +1,48 @@
|
||||
<Application xmlns="https://github.com/avaloniaui"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:vm="using:GC.ViewModels"
|
||||
xmlns:views="using:GC.Views"
|
||||
x:Class="GC.App"
|
||||
RequestedThemeVariant="Light">
|
||||
|
||||
<Application.DataTemplates>
|
||||
<DataTemplate DataType="{x:Type vm:HomeViewModel}">
|
||||
<views:HomeView />
|
||||
</DataTemplate>
|
||||
<DataTemplate DataType="{x:Type vm:DownloadViewModel}">
|
||||
<views:DownloadView />
|
||||
</DataTemplate>
|
||||
<DataTemplate DataType="{x:Type vm:SettingsViewModel}">
|
||||
<views:SettingsView />
|
||||
</DataTemplate>
|
||||
<DataTemplate DataType="{x:Type vm:AboutViewModel}">
|
||||
<views:AboutView />
|
||||
</DataTemplate>
|
||||
</Application.DataTemplates>
|
||||
|
||||
<Application.Resources>
|
||||
<Color x:Key="SystemAccentColor">#2F6BFF</Color>
|
||||
|
||||
<!--
|
||||
FluentTheme 的按钮模板在 :pointerover / :pressed 时会用这些主题资源
|
||||
覆盖 ContentPresenter 的画刷。若与 AppTheme.axaml 里通过 Button 属性
|
||||
设置的 hover 颜色不一致,两套机制会互相覆盖,导致光标移动时渲染错乱。
|
||||
这里把它们统一指向与按钮样式相同的颜色。
|
||||
-->
|
||||
<SolidColorBrush x:Key="ButtonBackgroundPointerOver">#EDF2FC</SolidColorBrush>
|
||||
<SolidColorBrush x:Key="ButtonBackgroundPressed">#DDE7F8</SolidColorBrush>
|
||||
<SolidColorBrush x:Key="ButtonBorderBrushPointerOver">#BAC9E6</SolidColorBrush>
|
||||
<SolidColorBrush x:Key="ButtonBorderBrushPressed">#9FB4DD</SolidColorBrush>
|
||||
<SolidColorBrush x:Key="ButtonForegroundPointerOver">#111A2E</SolidColorBrush>
|
||||
<SolidColorBrush x:Key="ButtonForegroundPressed">#111A2E</SolidColorBrush>
|
||||
|
||||
<SolidColorBrush x:Key="AccentButtonBackground">#2F6BFF</SolidColorBrush>
|
||||
<SolidColorBrush x:Key="AccentButtonBackgroundPointerOver">#1F4FD0</SolidColorBrush>
|
||||
<SolidColorBrush x:Key="AccentButtonBackgroundPressed">#183FA8</SolidColorBrush>
|
||||
</Application.Resources>
|
||||
|
||||
<Application.Styles>
|
||||
<FluentTheme />
|
||||
<StyleInclude Source="avares://GC.Core/Styles/AppTheme.axaml" />
|
||||
</Application.Styles>
|
||||
</Application>
|
||||
@@ -0,0 +1,129 @@
|
||||
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();
|
||||
|
||||
// 首帧之后再构造 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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,166 @@
|
||||
{
|
||||
"app.name": "Morris GC",
|
||||
"app.tagline": "Astronomy teaching models · visual launcher",
|
||||
"app.version": "Version",
|
||||
"app.platform": "Platform",
|
||||
"nav.home": "Home",
|
||||
"nav.download": "Download",
|
||||
"nav.settings": "Settings",
|
||||
"nav.about": "About",
|
||||
"home.title": "Model library",
|
||||
"home.subtitle": "Pick a model and explain rotation, revolution and the seasons with an interactive 3D scene.",
|
||||
"home.launch": "Launch model",
|
||||
"home.download": "Get models",
|
||||
"home.settings": "Settings",
|
||||
"home.installed": "Installed models",
|
||||
"home.count": "{0} models",
|
||||
"home.empty": "No models yet",
|
||||
"home.emptyHint": "Models download from gitcode on startup; offline you can drop them into .GC/model/ or import a source on the Download page.",
|
||||
"home.emptyAction": "Get models",
|
||||
"home.open": "Open folder",
|
||||
"home.delete": "Delete",
|
||||
"home.deleteConfirm": "Delete the model \"{0}\"? Its files will be removed from the local library.",
|
||||
"home.size": "Size",
|
||||
"home.stats.models": "Installed",
|
||||
"home.stats.sources": "Sources",
|
||||
"home.stats.memory": "Memory budget",
|
||||
"home.recent": "Select a model, then press Launch",
|
||||
"home.getMore": "Get more models",
|
||||
"home.launchHint": "Models open in their own window with play/pause, view controls and teaching notes.",
|
||||
"dl.title": "Download",
|
||||
"dl.subtitle": "Import a model source: git repository, zip archive or local folder. The model/ folder in the repo is the model list.",
|
||||
"dl.import": "Import source",
|
||||
"dl.importPlaceholder": "https://github.com/user/repo.git or /path/to/model-repo",
|
||||
"dl.sources": "Sources",
|
||||
"dl.refresh": "Refresh",
|
||||
"dl.remove": "Remove",
|
||||
"dl.noSource": "No sources yet",
|
||||
"dl.pickSource": "Select a source to see available models",
|
||||
"dl.available": "Available models",
|
||||
"dl.download": "Download",
|
||||
"dl.installed": "Installed",
|
||||
"dl.reinstall": "Re-download",
|
||||
"dl.background": "Background tasks",
|
||||
"dl.bgEmpty": "No background tasks",
|
||||
"dl.cancel": "Cancel",
|
||||
"dl.retry": "Retry",
|
||||
"dl.clearDone": "Clear finished",
|
||||
"dl.removeTask": "Remove",
|
||||
"dl.status.queued": "Queued",
|
||||
"dl.status.downloading": "Downloading",
|
||||
"dl.status.done": "Completed",
|
||||
"dl.status.failed": "Failed",
|
||||
"dl.status.canceled": "Canceled",
|
||||
"dl.hint": "GitHub / GitLab / Gitee repository URLs, zip links and local folders are supported",
|
||||
"dl.empty": "No models in this source",
|
||||
"dl.emptyHint": "A source needs model/<model-id>/<model-id>.json layout",
|
||||
"dl.syncing": "Reading model source…",
|
||||
"dl.ready": "{0} models",
|
||||
"dl.fromCache": "cached",
|
||||
"dl.imported": "Source imported",
|
||||
"dl.importFailed": "Import failed: {0}",
|
||||
"dl.error.emptyUrl": "Please enter a source URL",
|
||||
"dl.error.canceled": "Canceled",
|
||||
"dl.error.unreachable": "Cannot reach this source, check the URL or network",
|
||||
"dl.sourceDefault": "Source",
|
||||
"set.title": "Settings",
|
||||
"set.subtitle": "Model sources, startup memory allocation and local storage.",
|
||||
"set.general": "General",
|
||||
"set.language": "Language",
|
||||
"set.language.auto": "System",
|
||||
"set.fps": "Render frame rate",
|
||||
"set.fps.desc": "Higher is smoother but uses more CPU.",
|
||||
"set.memory": "Startup memory allocation",
|
||||
"set.memory.desc": "The launcher hands this budget to each model; models decide how much data to cache with it.",
|
||||
"set.memory.current": "In use",
|
||||
"set.memory.unit": "MB",
|
||||
"set.memory.hint": "2048 MB or more is recommended; 1024 MB for low-end devices.",
|
||||
"set.memory.auto": "Auto (allocate based on device memory)",
|
||||
"set.preallocate": "Preload land data at startup",
|
||||
"set.preallocate.desc": "Faster first frame, slightly slower startup.",
|
||||
"set.sources": "Model sources",
|
||||
"set.sources.desc": "Disabled sources are hidden from the Download page.",
|
||||
"set.sourceEnabled": "Enabled",
|
||||
"set.addSource": "Add source",
|
||||
"set.sourceName": "Name",
|
||||
"set.storage": "Storage",
|
||||
"set.modelDir": "Model library",
|
||||
"set.dataDir": "Data folder",
|
||||
"set.openFolder": "Open folder",
|
||||
"set.clearCache": "Clear cache",
|
||||
"set.cacheCleared": "Cache cleared",
|
||||
"set.about": "About",
|
||||
"set.version": "Version",
|
||||
"set.platform": "Platform",
|
||||
"set.license": "License",
|
||||
"set.licenseValue": "MIT",
|
||||
"set.checkUpdate": "Check for updates",
|
||||
"set.checkUpdate.desc": "Check on startup whether models and the launcher are up to date.",
|
||||
"update.title": "Auto update",
|
||||
"update.desc": "Models take effect immediately after download; launcher updates apply on the next start.",
|
||||
"update.auto": "Check for updates on startup",
|
||||
"update.checkNow": "Check now",
|
||||
"update.source": "Update source",
|
||||
"update.lastCheck": "Last check",
|
||||
"update.pending": "Pending version",
|
||||
"update.never": "Never",
|
||||
"update.none": "None",
|
||||
"update.checking": "Checking for updates…",
|
||||
"update.disabled": "Auto update is off",
|
||||
"update.offline": "Update server unavailable — continuing with local models",
|
||||
"update.noManifest": "No remote version manifest — continuing with local models",
|
||||
"update.noChange": "Models and launcher are up to date",
|
||||
"update.modelsLatest": "Models are up to date",
|
||||
"update.applied": "Updated {0} models, applied now",
|
||||
"update.partial": " ({0} item(s) incomplete)",
|
||||
"update.downloadingModel": "Downloading model {0}…",
|
||||
"update.downloadingLauncher": "Downloading launcher {0}…",
|
||||
"update.done": "Update check complete",
|
||||
"update.pendingReady": "Launcher {0} is ready, applies on next start",
|
||||
"update.pendingDownloaded": "Launcher {0} downloaded, applies on next start",
|
||||
"update.noRidPackage": "Launcher {0} found (no package for {1})",
|
||||
"update.noPackageUrl": "Launcher {0} found, but no download address",
|
||||
"update.launcherFailed": "Launcher update failed: {0}",
|
||||
"set.modelFormat": "Model format",
|
||||
"set.modelFormat.desc": "model/<model-id>/<model-id>.json + <model-id>.model/ scene data",
|
||||
"player.back": "Close window",
|
||||
"player.view.rotation": "Rotation",
|
||||
"player.view.revolution": "Revolution",
|
||||
"player.play": "Play",
|
||||
"player.pause": "Pause",
|
||||
"player.speed": "Speed",
|
||||
"player.reset": "Reset",
|
||||
"player.labels": "Labels",
|
||||
"player.orbit": "Orbit",
|
||||
"player.grid": "Graticule",
|
||||
"player.tilt": "Exaggerate tilt",
|
||||
"player.lessons": "Teaching notes",
|
||||
"player.seasons": "Solstices & equinoxes",
|
||||
"player.loading": "Preparing scene…",
|
||||
"player.subsolar": "Subsolar point",
|
||||
"player.north": "North pole",
|
||||
"player.south": "South pole",
|
||||
"player.northShort": "N",
|
||||
"player.southShort": "S",
|
||||
"player.spinInfo": "Rotation {0}° · period {1} h",
|
||||
"player.orbitInfo": "Orbit {0}°",
|
||||
"player.declinationInfo": "Subsolar {0}",
|
||||
"player.dateInfo": "Date {0}",
|
||||
"player.paused": "Paused",
|
||||
"star.sun": "Sun",
|
||||
"planet.earth": "Earth",
|
||||
"season.springEquinox": "Spring equinox",
|
||||
"season.summerSolstice": "Summer solstice",
|
||||
"season.autumnEquinox": "Autumn equinox",
|
||||
"season.winterSolstice": "Winter solstice",
|
||||
"common.cancel": "Cancel",
|
||||
"common.confirm": "Confirm",
|
||||
"common.delete": "Delete",
|
||||
"common.close": "Close",
|
||||
"common.open": "Open",
|
||||
"common.applied": "Applied",
|
||||
"common.confirmTitle": "Please confirm",
|
||||
"player.windowHint": "The model runs in its own window; close it to exit",
|
||||
"player.errorTitle": "Failed to launch \"{0}\"",
|
||||
"player.errorHint": "The model package has no usable assembly. Make sure <id>.model contains the model dll, or re-download it."
|
||||
}
|
||||
@@ -0,0 +1,166 @@
|
||||
{
|
||||
"app.name": "Morris GC",
|
||||
"app.tagline": "天文教学模型 · 可视化启动器",
|
||||
"app.version": "版本",
|
||||
"app.platform": "平台",
|
||||
"nav.home": "主页",
|
||||
"nav.download": "下载",
|
||||
"nav.settings": "设置",
|
||||
"nav.about": "关于",
|
||||
"home.title": "模型库",
|
||||
"home.subtitle": "选择模型,用可交互的三维演示讲清自转、公转与四季成因。",
|
||||
"home.launch": "启动模型",
|
||||
"home.download": "下载模型",
|
||||
"home.settings": "设置",
|
||||
"home.installed": "已安装模型",
|
||||
"home.count": "{0} 个模型",
|
||||
"home.empty": "模型库还是空的",
|
||||
"home.emptyHint": "启动时会从 gitcode 自动下载模型;离线可把模型放进 .GC/model/,或在「下载」页导入模型源。",
|
||||
"home.emptyAction": "去下载模型",
|
||||
"home.open": "打开目录",
|
||||
"home.delete": "删除",
|
||||
"home.deleteConfirm": "删除模型「{0}」?模型文件会从本地模型库移除。",
|
||||
"home.size": "体积",
|
||||
"home.stats.models": "已安装",
|
||||
"home.stats.sources": "模型源",
|
||||
"home.stats.memory": "内存预算",
|
||||
"home.recent": "选择模型后点击「启动模型」",
|
||||
"home.getMore": "获取更多模型",
|
||||
"home.launchHint": "模型在自己的窗口里运行,可播放/暂停、切换视角并使用教学要点。",
|
||||
"dl.title": "下载模型",
|
||||
"dl.subtitle": "从链接导入模型源:git 仓库、zip 压缩包或本地目录。仓库里的 model/ 文件夹就是模型列表。",
|
||||
"dl.import": "导入模型源",
|
||||
"dl.importPlaceholder": "https://github.com/user/repo.git 或 /本地/模型仓库",
|
||||
"dl.sources": "模型源",
|
||||
"dl.refresh": "刷新",
|
||||
"dl.remove": "移除",
|
||||
"dl.noSource": "还没有模型源",
|
||||
"dl.pickSource": "选择一个模型源,查看可下载的模型",
|
||||
"dl.available": "可用模型",
|
||||
"dl.download": "下载",
|
||||
"dl.installed": "已安装",
|
||||
"dl.reinstall": "重新下载",
|
||||
"dl.background": "后台任务",
|
||||
"dl.bgEmpty": "暂无后台任务",
|
||||
"dl.cancel": "取消",
|
||||
"dl.retry": "重试",
|
||||
"dl.clearDone": "清除已完成",
|
||||
"dl.removeTask": "移除",
|
||||
"dl.status.queued": "排队中",
|
||||
"dl.status.downloading": "下载中",
|
||||
"dl.status.done": "已完成",
|
||||
"dl.status.failed": "失败",
|
||||
"dl.status.canceled": "已取消",
|
||||
"dl.hint": "支持 GitHub / GitLab / Gitee 仓库地址、zip 直链、本地目录",
|
||||
"dl.empty": "这个源里没有模型",
|
||||
"dl.emptyHint": "仓库需要包含 model/<模型ID>/<模型ID>.json 结构",
|
||||
"dl.syncing": "正在读取模型源…",
|
||||
"dl.ready": "共 {0} 个模型",
|
||||
"dl.fromCache": "本地缓存",
|
||||
"dl.imported": "已导入模型源",
|
||||
"dl.importFailed": "导入失败:{0}",
|
||||
"dl.error.emptyUrl": "请填写模型源链接",
|
||||
"dl.error.canceled": "已取消",
|
||||
"dl.error.unreachable": "无法访问该模型源,请检查链接或网络",
|
||||
"dl.sourceDefault": "模型源",
|
||||
"set.title": "设置",
|
||||
"set.subtitle": "模型源、启动时内存分配与本地存储。",
|
||||
"set.general": "通用",
|
||||
"set.language": "界面语言",
|
||||
"set.language.auto": "跟随系统",
|
||||
"set.fps": "渲染帧率",
|
||||
"set.fps.desc": "越高越顺滑,CPU 占用也越高。",
|
||||
"set.memory": "启动时运行内存分配",
|
||||
"set.memory.desc": "启动器把这份预算交给模型:模型自己决定用它缓存多少数据(贴图分辨率、缓冲等)。",
|
||||
"set.memory.current": "当前占用",
|
||||
"set.memory.unit": "MB",
|
||||
"set.memory.hint": "建议 2048 MB 以上,低配设备可选 1024 MB。",
|
||||
"set.memory.auto": "自动(根据设备内存分配)",
|
||||
"set.preallocate": "启动时预加载模型地表数据",
|
||||
"set.preallocate.desc": "打开后首帧更快,启动耗时略增。",
|
||||
"set.sources": "模型源",
|
||||
"set.sources.desc": "停用的模型源不会出现在下载页。",
|
||||
"set.sourceEnabled": "启用",
|
||||
"set.addSource": "添加模型源",
|
||||
"set.sourceName": "名称",
|
||||
"set.storage": "存储",
|
||||
"set.modelDir": "模型库目录",
|
||||
"set.dataDir": "数据目录",
|
||||
"set.openFolder": "打开文件夹",
|
||||
"set.clearCache": "清理缓存",
|
||||
"set.cacheCleared": "缓存已清理",
|
||||
"set.about": "关于",
|
||||
"set.version": "版本",
|
||||
"set.platform": "平台",
|
||||
"set.license": "许可",
|
||||
"set.licenseValue": "MIT",
|
||||
"set.checkUpdate": "检查更新",
|
||||
"set.checkUpdate.desc": "启动时自动检查模型与启动器是否为最新版。",
|
||||
"update.title": "自动更新",
|
||||
"update.desc": "启动时检查模型与启动器是否为最新版;模型下载后立即生效,启动器在下次启动时应用。",
|
||||
"update.auto": "启动时自动检查更新",
|
||||
"update.checkNow": "检查更新",
|
||||
"update.source": "更新源",
|
||||
"update.lastCheck": "上次检查",
|
||||
"update.pending": "待应用版本",
|
||||
"update.never": "尚未检查",
|
||||
"update.none": "无",
|
||||
"update.checking": "正在检查更新…",
|
||||
"update.disabled": "自动更新已关闭",
|
||||
"update.offline": "暂时无法连接更新服务器,继续使用本地模型",
|
||||
"update.noManifest": "远端还没有版本清单,继续使用本地模型",
|
||||
"update.noChange": "模型与启动器均为最新版",
|
||||
"update.modelsLatest": "模型已是最新版",
|
||||
"update.applied": "已更新 {0} 个模型,立即生效",
|
||||
"update.partial": "({0} 项未完成)",
|
||||
"update.downloadingModel": "正在下载模型 {0}…",
|
||||
"update.downloadingLauncher": "正在下载启动器新版 {0}…",
|
||||
"update.done": "更新检查完成",
|
||||
"update.pendingReady": "启动器新版 {0} 已就绪,下次启动生效",
|
||||
"update.pendingDownloaded": "启动器新版 {0} 已下载,下次启动生效",
|
||||
"update.noRidPackage": "发现启动器新版 {0}({1} 暂无安装包)",
|
||||
"update.noPackageUrl": "发现启动器新版 {0},但下载地址不可用",
|
||||
"update.launcherFailed": "启动器更新失败:{0}",
|
||||
"set.modelFormat": "模型格式",
|
||||
"set.modelFormat.desc": "model/<模型ID>/<模型ID>.json + <模型ID>.model/ 场景数据",
|
||||
"player.back": "关闭窗口",
|
||||
"player.view.rotation": "自转",
|
||||
"player.view.revolution": "公转",
|
||||
"player.play": "播放",
|
||||
"player.pause": "暂停",
|
||||
"player.speed": "速度",
|
||||
"player.reset": "重置",
|
||||
"player.labels": "标注",
|
||||
"player.orbit": "轨道",
|
||||
"player.grid": "经纬网",
|
||||
"player.tilt": "夸张倾角",
|
||||
"player.lessons": "教学要点",
|
||||
"player.seasons": "节气定位",
|
||||
"player.loading": "正在准备场景…",
|
||||
"player.subsolar": "太阳直射点",
|
||||
"player.north": "北极",
|
||||
"player.south": "南极",
|
||||
"player.northShort": "N",
|
||||
"player.southShort": "S",
|
||||
"player.spinInfo": "自转 {0}° · 周期 {1} 小时",
|
||||
"player.orbitInfo": "公转 {0}°",
|
||||
"player.declinationInfo": "太阳直射 {0}",
|
||||
"player.dateInfo": "日期 {0}",
|
||||
"player.paused": "已暂停",
|
||||
"star.sun": "太阳",
|
||||
"planet.earth": "地球",
|
||||
"season.springEquinox": "春分",
|
||||
"season.summerSolstice": "夏至",
|
||||
"season.autumnEquinox": "秋分",
|
||||
"season.winterSolstice": "冬至",
|
||||
"common.cancel": "取消",
|
||||
"common.confirm": "确定",
|
||||
"common.delete": "删除",
|
||||
"common.close": "关闭",
|
||||
"common.open": "打开",
|
||||
"common.applied": "已应用",
|
||||
"common.confirmTitle": "请确认",
|
||||
"player.windowHint": "模型在独立窗口中运行,关闭窗口即退出模型",
|
||||
"player.errorTitle": "模型「{0}」启动失败",
|
||||
"player.errorHint": "模型包里没有可用的功能程序集。请确认 <id>.model 目录内有模型 dll,或重新下载该模型。"
|
||||
}
|
||||
|
After Width: | Height: | Size: 350 KiB |
|
After Width: | Height: | Size: 18 KiB |
|
After Width: | Height: | Size: 51 KiB |
|
After Width: | Height: | Size: 2.4 KiB |
|
After Width: | Height: | Size: 136 KiB |
|
After Width: | Height: | Size: 6.5 KiB |
|
After Width: | Height: | Size: 88 KiB |
|
After Width: | Height: | Size: 51 KiB |
@@ -0,0 +1,29 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<Nullable>enable</Nullable>
|
||||
<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" />
|
||||
<Compile Remove="test\**\*.cs" />
|
||||
</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>
|
||||
@@ -0,0 +1,84 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace GC.Models;
|
||||
|
||||
/// <summary>应用设置,持久化到 data/settings.json。</summary>
|
||||
public sealed class AppSettings
|
||||
{
|
||||
/// <summary>auto | zh-CN | en</summary>
|
||||
public string Language { get; set; } = "auto";
|
||||
|
||||
/// <summary>light | dark</summary>
|
||||
public string Theme { get; set; } = "light";
|
||||
|
||||
/// <summary>渲染帧率:24 / 30 / 60 / 90 / 120(上限 120,关闭 VSync 同步)</summary>
|
||||
public int RenderFps { get; set; } = 120;
|
||||
|
||||
/// <summary>启动时运行内存分配(MB)——决定场景缓存/纹理预算。</summary>
|
||||
public int MemoryMb { get; set; } = 2048;
|
||||
|
||||
/// <summary>自动模式:根据设备可用内存自动计算预算(忽略 MemoryMb)。</summary>
|
||||
public bool MemoryAuto { get; set; } = true;
|
||||
|
||||
/// <summary>启动时检查模型源更新。</summary>
|
||||
public bool CheckSourceOnStartup { get; set; }
|
||||
|
||||
/// <summary>模型库目录覆盖(留空则自动探测)。</summary>
|
||||
public string? ModelRootOverride { get; set; }
|
||||
|
||||
public List<ModelSource> Sources { get; set; } = new();
|
||||
|
||||
public List<string> RecentModels { get; set; } = new();
|
||||
|
||||
// ---- 自动更新 ----------------------------------------------------------
|
||||
|
||||
/// <summary>启动时检查模型 / 启动器是否为最新版。</summary>
|
||||
public bool AutoUpdateOnStartup { get; set; } = true;
|
||||
|
||||
/// <summary>默认更新仓库地址。</summary>
|
||||
public string UpdateRepository { get; set; } = "https://gitcode.com/2509_92447106/GC";
|
||||
|
||||
/// <summary>版本清单地址覆盖(留空则按 UpdateRepository 拼接)。</summary>
|
||||
public string? UpdateManifestUrl { get; set; }
|
||||
|
||||
/// <summary>本地模型源目录(离线教学场景可指向 U 盘 / 共享盘里的仓库)。</summary>
|
||||
public string? UpdateLocalRoot { get; set; }
|
||||
|
||||
/// <summary>已安装的模型版本:id -> version.json 里的版本。</summary>
|
||||
public Dictionary<string, string> InstalledModelVersions { get; set; } = new();
|
||||
|
||||
/// <summary>当前已经应用过的启动器版本。</summary>
|
||||
public string? LauncherVersion { get; set; }
|
||||
|
||||
/// <summary>已下载、等待下次启动应用的启动器版本。</summary>
|
||||
public string? PendingLauncherVersion { get; set; }
|
||||
|
||||
/// <summary>最近一次更新检查时间(ISO 8601)。</summary>
|
||||
public string? LastUpdateCheck { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>模型源:一个满足 Earth Model 规范的 git 仓库 / zip / 本地目录。</summary>
|
||||
public sealed class ModelSource
|
||||
{
|
||||
public string Id { get; set; } = Guid.NewGuid().ToString("N")[..8];
|
||||
public string Name { get; set; } = "";
|
||||
public string Url { get; set; } = "";
|
||||
public string? Branch { get; set; }
|
||||
public bool Enabled { get; set; } = true;
|
||||
public bool BuiltIn { get; set; }
|
||||
public string? LastSynced { get; set; }
|
||||
|
||||
[JsonIgnore]
|
||||
public string DisplayHost
|
||||
{
|
||||
get
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(Url)) return "";
|
||||
if (Url.StartsWith("file:", StringComparison.OrdinalIgnoreCase) || System.IO.Path.IsPathRooted(Url))
|
||||
return "local";
|
||||
return Uri.TryCreate(Url, UriKind.Absolute, out var u) ? u.Host : Url;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
using System.Collections.Generic;
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace GC.Models;
|
||||
|
||||
/// <summary>model/<id>/<id>.json 的内容。</summary>
|
||||
public sealed class ModelManifest
|
||||
{
|
||||
public int SchemaVersion { get; set; } = 1;
|
||||
public string Id { get; set; } = "";
|
||||
public string Name { get; set; } = "";
|
||||
public Dictionary<string, string>? NameI18n { get; set; }
|
||||
public string Version { get; set; } = "1.0.0";
|
||||
public string Author { get; set; } = "";
|
||||
public string Description { get; set; } = "";
|
||||
public Dictionary<string, string>? DescriptionI18n { get; set; }
|
||||
public List<string>? Tags { get; set; }
|
||||
/// <summary>相对 <id>.model 目录的入口文件,默认 scene.json</summary>
|
||||
public string? Entry { get; set; }
|
||||
/// <summary>模型自带的界面程序集(相对 <id>.model),默认 <id>.dll</summary>
|
||||
public string? Assembly { get; set; }
|
||||
/// <summary>实现 IModelFactory 的类型全名;留空则自动查找</summary>
|
||||
public string? Type { get; set; }
|
||||
/// <summary>封面图文件名,默认 preview.png</summary>
|
||||
public string? Preview { get; set; }
|
||||
/// <summary>模型契约版本</summary>
|
||||
public int ApiVersion { get; set; } = 1;
|
||||
public string? License { get; set; }
|
||||
public string? UpdatedAt { get; set; }
|
||||
public string? MinAppVersion { get; set; }
|
||||
/// <summary>模型窗口标题栏配色(模型自带,跟随模型界面风格);缺省时用深色。</summary>
|
||||
public WindowChrome? Chrome { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>模型窗口自建标题栏的颜色,由模型清单提供。</summary>
|
||||
public sealed class WindowChrome
|
||||
{
|
||||
public string? TitleBar { get; set; }
|
||||
public string? TitleBorder { get; set; }
|
||||
public string? TitleText { get; set; }
|
||||
public string? Button { get; set; }
|
||||
public string? Frame { get; set; }
|
||||
}
|
||||
|
||||
public sealed class ModelPackage
|
||||
{
|
||||
public ModelManifest Manifest { get; init; } = new();
|
||||
public string Directory { get; init; } = "";
|
||||
public long SizeBytes { get; set; }
|
||||
|
||||
public string Id => Manifest.Id;
|
||||
public string DataDirectory => System.IO.Path.Combine(Directory, Id + ".model");
|
||||
public string ScenePath
|
||||
{
|
||||
get
|
||||
{
|
||||
var entry = string.IsNullOrWhiteSpace(Manifest.Entry) ? "scene.json" : Manifest.Entry!;
|
||||
if (entry.StartsWith(Id + ".model")) return System.IO.Path.Combine(Directory, entry);
|
||||
return System.IO.Path.Combine(DataDirectory, entry);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>模型自带的界面程序集路径。</summary>
|
||||
public string AssemblyPath
|
||||
{
|
||||
get
|
||||
{
|
||||
var file = string.IsNullOrWhiteSpace(Manifest.Assembly) ? Id + ".dll" : Manifest.Assembly!;
|
||||
return System.IO.Path.IsPathRooted(file) ? file : System.IO.Path.Combine(DataDirectory, file);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>封面图路径(launcher 只显示,不渲染)。</summary>
|
||||
public string PreviewPath
|
||||
{
|
||||
get
|
||||
{
|
||||
var file = string.IsNullOrWhiteSpace(Manifest.Preview) ? "preview.png" : Manifest.Preview!;
|
||||
return System.IO.Path.IsPathRooted(file) ? file : System.IO.Path.Combine(DataDirectory, file);
|
||||
}
|
||||
}
|
||||
|
||||
public string LocalizedName => Services.L.I.Pick(Manifest.NameI18n,
|
||||
string.IsNullOrWhiteSpace(Manifest.Name) ? Id : Manifest.Name);
|
||||
|
||||
public string LocalizedDescription => Services.L.I.Pick(Manifest.DescriptionI18n, Manifest.Description);
|
||||
}
|
||||
|
||||
public sealed class RemoteModel
|
||||
{
|
||||
public ModelManifest Manifest { get; init; } = new();
|
||||
public string Directory { get; init; } = "";
|
||||
public long SizeBytes { get; init; }
|
||||
public string SourceId { get; init; } = "";
|
||||
|
||||
public string Id => Manifest.Id;
|
||||
public string LocalizedName => Services.L.I.Pick(Manifest.NameI18n,
|
||||
string.IsNullOrWhiteSpace(Manifest.Name) ? Id : Manifest.Name);
|
||||
public string LocalizedDescription => Services.L.I.Pick(Manifest.DescriptionI18n, Manifest.Description);
|
||||
}
|
||||
|
||||
public sealed class SourceIndex
|
||||
{
|
||||
public string SourceId { get; init; } = "";
|
||||
public string Root { get; init; } = "";
|
||||
public bool FromCache { get; init; }
|
||||
public List<RemoteModel> Models { get; init; } = new();
|
||||
public string? Error { get; init; }
|
||||
public string ResolvedFrom { get; init; } = "";
|
||||
}
|
||||
@@ -0,0 +1,299 @@
|
||||
using System;
|
||||
using System.Threading.Tasks;
|
||||
using System.IO;
|
||||
|
||||
namespace GC.Services;
|
||||
|
||||
/// <summary>
|
||||
/// 运行目录约定(可执行文件旁边,不内置任何模型):
|
||||
/// <code>
|
||||
/// <安装目录>/
|
||||
/// GC(.exe | .app/...)
|
||||
/// .GC/
|
||||
/// settings.json 设置与已安装版本记录
|
||||
/// model/ 模型(启动时下载;model 目录也在 .GC 里)
|
||||
/// cache/ 下载缓存 / 原子替换暂存
|
||||
/// update/ 待下次启动应用的启动器更新包
|
||||
/// </code>
|
||||
/// 开发态同样使用 .GC/model,并自动把仓库 model/ 的可分发部分同步进去。
|
||||
/// EMS_MODELS / EMS_DATA / EMS_HOME 可显式覆盖。
|
||||
/// </summary>
|
||||
public sealed class AppPaths
|
||||
{
|
||||
private Task _developmentModelsSync = Task.CompletedTask;
|
||||
|
||||
/// <summary>安装目录(开发态为仓库根)。</summary>
|
||||
public string AppRoot { get; private init; } = "";
|
||||
|
||||
/// <summary>可执行文件真正所在目录:启动器自更新时要覆盖这里。</summary>
|
||||
public string InstallDirectory { get; private init; } = "";
|
||||
|
||||
/// <summary>.GC 目录。</summary>
|
||||
public string HomeRoot { get; private init; } = "";
|
||||
|
||||
/// <summary>模型库,恒为 <HomeRoot>/model。</summary>
|
||||
public string ModelRoot { get; private init; } = "";
|
||||
|
||||
/// <summary>兼容旧代码:数据目录即 .GC。</summary>
|
||||
public string DataRoot => HomeRoot;
|
||||
|
||||
public string CacheRoot => Path.Combine(HomeRoot, "cache");
|
||||
public string UpdateRoot => Path.Combine(HomeRoot, "update");
|
||||
public string SettingsFile => Path.Combine(HomeRoot, "settings.json");
|
||||
|
||||
public bool IsDevelopment { get; private init; }
|
||||
public bool IsPortableModelRoot { get; private init; }
|
||||
|
||||
public static AppPaths Discover()
|
||||
{
|
||||
var baseDir = AppContext.BaseDirectory.TrimEnd(Path.DirectorySeparatorChar);
|
||||
|
||||
// 判定「当前目录」:程序实际所在的位置。
|
||||
// · 发布版:可执行文件所在目录(单文件时为 exe 旁,否则为 apphost 目录)
|
||||
// · 源码版:仓库根(含 GC.sln 的目录)
|
||||
//
|
||||
// 重要:源码版由 `dotnet run` 启动时 Environment.ProcessPath 指向 dotnet 宿主,
|
||||
// 直接用它会把 .GC 与更新包写到 dotnet 安装目录去,所以必须先识别源码版。
|
||||
var repoRoot = Environment.GetEnvironmentVariable("EMS_HOME");
|
||||
if (string.IsNullOrWhiteSpace(repoRoot) || !Directory.Exists(repoRoot))
|
||||
repoRoot = FindRepoRoot(baseDir);
|
||||
var isDev = !string.IsNullOrEmpty(repoRoot) &&
|
||||
File.Exists(Path.Combine(repoRoot!, "GC.sln"));
|
||||
|
||||
string installDir;
|
||||
if (isDev)
|
||||
{
|
||||
// 源码版:安装目录 = 仓库根,.GC 与更新都放这里
|
||||
installDir = repoRoot!;
|
||||
}
|
||||
else
|
||||
{
|
||||
// 发布版:运行目录 = **放着 .app / .exe 的那一层**,不是 .app 内部的 Contents/MacOS。
|
||||
//
|
||||
// <运行目录>/ ← 要的就是这一层
|
||||
// GC-1.0.3-mac-arm64.app/ ← 程序包
|
||||
// .GC/ ← 用户数据放这里
|
||||
//
|
||||
// 若直接返回 Contents/MacOS,.GC 会被塞进 app 包内部,
|
||||
// 用户看不到,重装/替换时也会跟着包一起被删。
|
||||
installDir = baseDir;
|
||||
try
|
||||
{
|
||||
var exe = Environment.ProcessPath;
|
||||
if (!string.IsNullOrWhiteSpace(exe))
|
||||
{
|
||||
var exeName = Path.GetFileNameWithoutExtension(exe);
|
||||
var isDotnetHost = string.Equals(exeName, "dotnet", StringComparison.OrdinalIgnoreCase);
|
||||
var exeDir = Path.GetDirectoryName(exe);
|
||||
|
||||
if (!isDotnetHost && !string.IsNullOrWhiteSpace(exeDir) && Directory.Exists(exeDir))
|
||||
{
|
||||
// 从可执行文件所在目录向上找:如果处在 Xxx.app/Contents/MacOS,
|
||||
// 则运行目录是 Xxx.app 的**父目录**。
|
||||
installDir = ResolveRunDirectory(exeDir!);
|
||||
}
|
||||
}
|
||||
}
|
||||
catch { /* 取不到就沿用 BaseDirectory */ }
|
||||
}
|
||||
|
||||
// 运行目录 = 程序所在目录。.GC 永远紧挨着程序,不往系统目录放。
|
||||
var appRoot = installDir;
|
||||
|
||||
// 只读安装位置(如 Program Files / /Applications)才回退到用户数据目录;
|
||||
// 正常可写时一律用当前目录下的 .GC。
|
||||
var explicitData = Environment.GetEnvironmentVariable("EMS_DATA");
|
||||
string home;
|
||||
if (!string.IsNullOrWhiteSpace(explicitData))
|
||||
{
|
||||
home = explicitData!;
|
||||
}
|
||||
else
|
||||
{
|
||||
var portableHome = Path.Combine(appRoot, ".GC");
|
||||
home = CanWrite(portableHome)
|
||||
? portableHome
|
||||
: Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
|
||||
"GC", ".GC");
|
||||
}
|
||||
|
||||
var envModels = Environment.GetEnvironmentVariable("EMS_MODELS");
|
||||
var modelRoot = !string.IsNullOrWhiteSpace(envModels)
|
||||
? envModels!
|
||||
: Path.Combine(home, "model"); // 统一:model 目录在 .GC 里
|
||||
|
||||
return new AppPaths
|
||||
{
|
||||
AppRoot = appRoot,
|
||||
InstallDirectory = installDir,
|
||||
HomeRoot = home,
|
||||
ModelRoot = modelRoot,
|
||||
IsDevelopment = isDev,
|
||||
IsPortableModelRoot = string.IsNullOrWhiteSpace(envModels)
|
||||
};
|
||||
}
|
||||
|
||||
private static bool CanWrite(string dir)
|
||||
{
|
||||
try
|
||||
{
|
||||
Directory.CreateDirectory(dir);
|
||||
var probe = Path.Combine(dir, ".write-test");
|
||||
File.WriteAllText(probe, "ok");
|
||||
File.Delete(probe);
|
||||
return true;
|
||||
}
|
||||
catch
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 从程序所在位置向上找仓库根(含 GC.sln 的目录)。
|
||||
///
|
||||
/// 关键:程序若位于 .app 包内(或 dist/ 等发布产物目录),**不算开发态**。
|
||||
/// 否则把 .app 放在仓库的 dist/ 下运行时,会一路向上命中仓库根的 .sln,
|
||||
/// 被误判为开发态,导致 .GC 跑到仓库根而不是程序旁边。
|
||||
/// </summary>
|
||||
private static string? FindRepoRoot(string start)
|
||||
{
|
||||
// 在 .app 包内(.../Xxx.app/Contents/MacOS)直接视为发布版
|
||||
if (IsInsideAppBundle(start)) return null;
|
||||
|
||||
var dir = new DirectoryInfo(start);
|
||||
for (var i = 0; i < 10 && dir != null; i++, dir = dir.Parent)
|
||||
{
|
||||
// 碰到发布产物目录也停下:dist/ 输出、或带 .GC 的运行目录都不是源码树
|
||||
var name = dir.Name;
|
||||
if (string.Equals(name, "dist", StringComparison.OrdinalIgnoreCase)) return null;
|
||||
|
||||
if (File.Exists(Path.Combine(dir.FullName, "GC.sln")))
|
||||
{
|
||||
// 再确认不是从「发布输出目录」里往上找来的
|
||||
if (IsUnderPublishOutput(start, dir.FullName)) return null;
|
||||
return dir.FullName;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 求「运行目录」:程序包所在的父目录。
|
||||
/// · 若路径处在 Xxx.app/Contents/MacOS 里,返回 Xxx.app 的父目录
|
||||
/// · 其它情况(Windows exe 目录)原样返回
|
||||
/// </summary>
|
||||
private static string ResolveRunDirectory(string exeDir)
|
||||
{
|
||||
var dir = new DirectoryInfo(exeDir);
|
||||
|
||||
// 走到 app 包根:.../Xxx.app
|
||||
string? appRoot = null;
|
||||
for (var cur = dir; cur != null; cur = cur.Parent)
|
||||
{
|
||||
if (cur.Name.EndsWith(".app", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
appRoot = cur.FullName;
|
||||
break;
|
||||
}
|
||||
if (cur.Parent == null) break;
|
||||
}
|
||||
|
||||
if (appRoot != null)
|
||||
{
|
||||
// 返回 .app 的父目录(即用户双击时看到的那一层)
|
||||
var parent = Path.GetDirectoryName(appRoot);
|
||||
if (!string.IsNullOrWhiteSpace(parent) && Directory.Exists(parent))
|
||||
return parent!;
|
||||
return appRoot;
|
||||
}
|
||||
|
||||
return exeDir;
|
||||
}
|
||||
|
||||
/// <summary>路径是否位于某个 .app 包内部。</summary>
|
||||
private static bool IsInsideAppBundle(string path)
|
||||
{
|
||||
var p = path.Replace('\\', '/');
|
||||
var idx = p.IndexOf(".app/", StringComparison.OrdinalIgnoreCase);
|
||||
return idx >= 0;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 从 start 到 repoRoot 之间是否经过了发布输出目录(dist / bin / publish)。
|
||||
/// 经过则说明程序是打包产物,而非源码树里直接运行的进程。
|
||||
/// </summary>
|
||||
private static bool IsUnderPublishOutput(string start, string repoRoot)
|
||||
{
|
||||
try
|
||||
{
|
||||
var rel = Path.GetRelativePath(repoRoot, start).Replace('\\', '/');
|
||||
foreach (var seg in rel.Split('/', StringSplitOptions.RemoveEmptyEntries))
|
||||
{
|
||||
if (string.Equals(seg, "dist", StringComparison.OrdinalIgnoreCase) ||
|
||||
string.Equals(seg, "publish", StringComparison.OrdinalIgnoreCase) ||
|
||||
string.Equals(seg, "Release", StringComparison.OrdinalIgnoreCase))
|
||||
return true;
|
||||
}
|
||||
}
|
||||
catch { }
|
||||
return false;
|
||||
}
|
||||
|
||||
public void EnsureCreated()
|
||||
{
|
||||
Directory.CreateDirectory(HomeRoot);
|
||||
Directory.CreateDirectory(CacheRoot);
|
||||
Directory.CreateDirectory(ModelRoot);
|
||||
Directory.CreateDirectory(UpdateRoot);
|
||||
|
||||
// 开发态:让 .GC/model 与仓库里的模型保持一致(只同步清单 + 数据,不含 src 源码)。
|
||||
// 放到后台线程:这一步要复制 coastline.json 等大文件,同步做会拖慢启动。
|
||||
if (IsDevelopment && string.IsNullOrWhiteSpace(Environment.GetEnvironmentVariable("EMS_MODELS")))
|
||||
{
|
||||
var modelRoot = ModelRoot;
|
||||
var source = Path.Combine(AppRoot, "model");
|
||||
if (Directory.Exists(source))
|
||||
_developmentModelsSync = Task.Run(() => SyncDevelopmentModels(modelRoot, source));
|
||||
}
|
||||
}
|
||||
|
||||
public void WaitForDevelopmentModels() => _developmentModelsSync.GetAwaiter().GetResult();
|
||||
|
||||
private static void SyncDevelopmentModels(string modelRoot, string source)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (!Directory.Exists(source)) return;
|
||||
foreach (var dir in Directory.GetDirectories(source))
|
||||
{
|
||||
var id = Path.GetFileName(dir);
|
||||
if (id.StartsWith('_')) continue;
|
||||
var manifest = Path.Combine(dir, id + ".json");
|
||||
var data = Path.Combine(dir, id + ".model");
|
||||
if (!File.Exists(manifest) || !Directory.Exists(data)) continue;
|
||||
var dest = Path.Combine(modelRoot, id);
|
||||
Directory.CreateDirectory(dest);
|
||||
File.Copy(manifest, Path.Combine(dest, id + ".json"), true);
|
||||
CopyTree(data, Path.Combine(dest, id + ".model"));
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.Error.WriteLine($"同步开发模型失败: {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
private static void CopyTree(string src, string dst)
|
||||
{
|
||||
Directory.CreateDirectory(dst);
|
||||
foreach (var file in Directory.GetFiles(src, "*", SearchOption.AllDirectories))
|
||||
{
|
||||
if (Path.GetFileName(file).StartsWith('.')) continue;
|
||||
var to = Path.Combine(dst, Path.GetRelativePath(src, file));
|
||||
var parent = Path.GetDirectoryName(to);
|
||||
if (!string.IsNullOrEmpty(parent)) Directory.CreateDirectory(parent);
|
||||
File.Copy(file, to, true);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
using System;
|
||||
|
||||
namespace GC.Services;
|
||||
|
||||
/// <summary>组合根:一处初始化所有服务。</summary>
|
||||
public sealed class AppServices
|
||||
{
|
||||
public static AppServices Current { get; private set; } = null!;
|
||||
|
||||
public AppPaths Paths { get; }
|
||||
public SettingsService Settings { get; }
|
||||
public ModelRepository Models { get; }
|
||||
public DownloadCenter Downloads { get; }
|
||||
public MemoryBudget Memory { get; }
|
||||
public ModelSourceClient Sources { get; }
|
||||
/// <summary>模型加载器:只负责把模型程序集跑起来,不渲染。</summary>
|
||||
public ModelHost ModelHost { get; }
|
||||
/// <summary>启动时检查模型 / 启动器更新。</summary>
|
||||
public UpdateService Updates { get; }
|
||||
/// <summary>双源测速选择器(Xhmcl / GitCode 取最快)。</summary>
|
||||
public SourceSelector Selector { get; }
|
||||
|
||||
private AppServices(AppPaths paths)
|
||||
{
|
||||
Paths = paths;
|
||||
Settings = new SettingsService(paths);
|
||||
Settings.Load(); // 先读设置,才知道用在线源还是本地离线源
|
||||
Models = new ModelRepository(paths);
|
||||
Sources = new ModelSourceClient(paths);
|
||||
Downloads = new DownloadCenter(paths, Models);
|
||||
Memory = new MemoryBudget();
|
||||
ModelHost = new ModelHost(paths, Settings, Memory);
|
||||
Selector = new SourceSelector();
|
||||
Updates = new UpdateService(paths, Settings, UpdateService.CreateRemote(Settings.Current));
|
||||
}
|
||||
|
||||
public static AppServices Create()
|
||||
{
|
||||
var paths = AppPaths.Discover();
|
||||
paths.EnsureCreated();
|
||||
|
||||
var services = new AppServices(paths);
|
||||
L.I.Initialize(services.Settings.Current.Language);
|
||||
services.Memory.ApplyAuto(services.Settings.Current.MemoryAuto,
|
||||
services.Settings.Current.MemoryMb);
|
||||
|
||||
Current = services;
|
||||
return services;
|
||||
}
|
||||
|
||||
public static AppServices Ensure() => Current ?? Create();
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Net.Http;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace GC.Services;
|
||||
|
||||
/// <summary>GitCode 仓库的一位贡献者。</summary>
|
||||
public sealed class Contributor
|
||||
{
|
||||
public string Name { get; set; } = "";
|
||||
public string? Email { get; set; }
|
||||
/// <summary>提交次数(API 里的 contributions)。</summary>
|
||||
public int Contributions { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 登录名 -> 展示名。GitCode 的 contributors 接口只返回账号登录名,
|
||||
/// 不返回真实姓名,这里做一层映射,让关于页显示作者想展示的名字。
|
||||
/// </summary>
|
||||
private static readonly Dictionary<string, string> DisplayNames = new(StringComparer.OrdinalIgnoreCase)
|
||||
{
|
||||
["2509_92447106"] = "Morris"
|
||||
};
|
||||
|
||||
/// <summary>头像地址:GitCode 用邮箱哈希拼头像,取不到时返回 null。</summary>
|
||||
public string? AvatarUrl =>
|
||||
string.IsNullOrWhiteSpace(Email)
|
||||
? null
|
||||
: $"https://cdn-img.gitcode.com/avatar/{Convert.ToHexString(
|
||||
System.Security.Cryptography.MD5.HashData(
|
||||
System.Text.Encoding.UTF8.GetBytes(Email!.Trim().ToLowerInvariant())))
|
||||
.ToLowerInvariant()}";
|
||||
|
||||
public string DisplayName
|
||||
{
|
||||
get
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(Name)) return "匿名";
|
||||
return DisplayNames.TryGetValue(Name.Trim(), out var mapped) ? mapped : Name;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 读取 GitCode 仓库的贡献者列表(用于「关于」页面展示开发者)。
|
||||
/// 失败时静默返回空列表,不影响关于页其它内容。
|
||||
/// </summary>
|
||||
public static class ContributorsService
|
||||
{
|
||||
private static readonly HttpClient Http = CreateHttp();
|
||||
|
||||
private static HttpClient CreateHttp()
|
||||
{
|
||||
var c = new HttpClient { Timeout = TimeSpan.FromSeconds(10) };
|
||||
c.DefaultRequestHeaders.UserAgent.ParseAdd("GC/1.0");
|
||||
c.DefaultRequestHeaders.Accept.ParseAdd("application/json");
|
||||
return c;
|
||||
}
|
||||
|
||||
/// <summary>默认仓库的 contributors 接口地址。</summary>
|
||||
public static string BuildUrl(string repository)
|
||||
{
|
||||
var raw = string.IsNullOrWhiteSpace(repository)
|
||||
? GitCodeRemote.DefaultRepository : repository.Trim();
|
||||
if (!Uri.TryCreate(raw, UriKind.Absolute, out var uri))
|
||||
return "https://api.gitcode.com/api/v5/repos/2509_92447106/GC/contributors";
|
||||
|
||||
var parts = uri.AbsolutePath.Trim('/').Split('/', StringSplitOptions.RemoveEmptyEntries);
|
||||
if (parts.Length < 2)
|
||||
return "https://api.gitcode.com/api/v5/repos/2509_92447106/GC/contributors";
|
||||
|
||||
var repo = parts[1].EndsWith(".git", StringComparison.OrdinalIgnoreCase)
|
||||
? parts[1][..^4] : parts[1];
|
||||
return $"https://api.gitcode.com/api/v5/repos/{parts[0]}/{repo}/contributors";
|
||||
}
|
||||
|
||||
public static async Task<List<Contributor>> FetchAsync(string repository, CancellationToken ct = default)
|
||||
{
|
||||
var url = BuildUrl(repository);
|
||||
try
|
||||
{
|
||||
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(ct);
|
||||
timeout.CancelAfter(TimeSpan.FromSeconds(10));
|
||||
|
||||
var text = await Http.GetStringAsync(url, timeout.Token);
|
||||
var trimmed = text.TrimStart();
|
||||
if (trimmed.Length == 0 || trimmed[0] != '[') return new List<Contributor>();
|
||||
|
||||
var list = JsonSerializer.Deserialize<List<Contributor>>(text, new JsonSerializerOptions
|
||||
{
|
||||
PropertyNameCaseInsensitive = true
|
||||
}) ?? new List<Contributor>();
|
||||
|
||||
// 按提交数从多到少,贡献最多的排最前
|
||||
list.Sort((a, b) => b.Contributions.CompareTo(a.Contributions));
|
||||
return list;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.Error.WriteLine($"读取贡献者失败: {ex.Message}");
|
||||
return new List<Contributor>();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Net.Http;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace GC.Services;
|
||||
|
||||
/// <summary>
|
||||
/// 本地目录源:用于离线教学(U 盘 / 共享盘里的仓库副本)与自动化测试。
|
||||
/// 目录结构与远端仓库一致:version.json + model/<id>/...
|
||||
/// </summary>
|
||||
public sealed class DirectoryRemote : IModelRemote
|
||||
{
|
||||
private readonly string _root;
|
||||
private static readonly HttpClient Http = new() { Timeout = TimeSpan.FromMinutes(5) };
|
||||
|
||||
public DirectoryRemote(string root) => _root = Path.GetFullPath(root);
|
||||
|
||||
public string DisplayName => _root;
|
||||
|
||||
public Task<RepoVersion?> GetVersionAsync(CancellationToken ct)
|
||||
{
|
||||
var primary = SafePath("version.json");
|
||||
var fallback = SafePath(Path.Combine("model", "version.json"));
|
||||
var file = File.Exists(primary) ? primary : fallback;
|
||||
if (!File.Exists(file)) return Task.FromResult<RepoVersion?>(null);
|
||||
return Task.FromResult(Json.Read<RepoVersion>(file));
|
||||
}
|
||||
|
||||
public Task<IReadOnlyList<RepoEntry>> ListTreeAsync(string rootPath, CancellationToken ct)
|
||||
{
|
||||
var baseDir = SafePath(rootPath ?? "model");
|
||||
var result = new List<RepoEntry>();
|
||||
if (!Directory.Exists(baseDir)) return Task.FromResult<IReadOnlyList<RepoEntry>>(result);
|
||||
|
||||
Walk(baseDir, baseDir, 0, result);
|
||||
return Task.FromResult<IReadOnlyList<RepoEntry>>(result);
|
||||
}
|
||||
|
||||
private void Walk(string dir, string baseDir, int depth, List<RepoEntry> result)
|
||||
{
|
||||
if (depth > 8) return;
|
||||
foreach (var sub in Directory.GetDirectories(dir))
|
||||
{
|
||||
var name = Path.GetFileName(sub);
|
||||
if (name.StartsWith('.')) continue;
|
||||
var rel = Relative(baseDir, sub);
|
||||
result.Add(new RepoEntry
|
||||
{
|
||||
Name = name,
|
||||
Path = Relative(_root, sub),
|
||||
RelativePath = rel,
|
||||
IsDirectory = true
|
||||
});
|
||||
Walk(sub, baseDir, depth + 1, result);
|
||||
}
|
||||
foreach (var file in Directory.GetFiles(dir))
|
||||
{
|
||||
var name = Path.GetFileName(file);
|
||||
if (name.StartsWith('.')) continue;
|
||||
result.Add(new RepoEntry
|
||||
{
|
||||
Name = name,
|
||||
Path = Relative(_root, file),
|
||||
RelativePath = Relative(baseDir, file),
|
||||
IsDirectory = false,
|
||||
Size = new FileInfo(file).Length
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<byte[]> DownloadAsync(RepoEntry entry, CancellationToken ct)
|
||||
=> await File.ReadAllBytesAsync(SafePath(entry.Path), ct);
|
||||
|
||||
public async Task<byte[]?> DownloadPackageAsync(RepoPackage package, CancellationToken ct)
|
||||
{
|
||||
if (!string.IsNullOrWhiteSpace(package.Path))
|
||||
{
|
||||
var local = SafePath(package.Path!);
|
||||
if (File.Exists(local)) return await File.ReadAllBytesAsync(local, ct);
|
||||
}
|
||||
var url = package.Url;
|
||||
if (string.IsNullOrWhiteSpace(url)) return null;
|
||||
// 离线 U 盘源与 ./build.sh update-test 都会用本地 zip 路径,必须保持兼容。
|
||||
if (url!.StartsWith("file://", StringComparison.OrdinalIgnoreCase))
|
||||
return await File.ReadAllBytesAsync(new Uri(url).LocalPath, ct);
|
||||
if (Path.IsPathRooted(url) && File.Exists(url))
|
||||
return await File.ReadAllBytesAsync(url, ct);
|
||||
if (Uri.TryCreate(url, UriKind.Absolute, out _))
|
||||
return await Http.GetByteArrayAsync(url, ct);
|
||||
return null;
|
||||
}
|
||||
|
||||
private string SafePath(string relative)
|
||||
{
|
||||
var full = Path.GetFullPath(Path.Combine(_root, relative));
|
||||
var prefix = _root.TrimEnd(Path.DirectorySeparatorChar) + Path.DirectorySeparatorChar;
|
||||
if (!full.Equals(_root, StringComparison.OrdinalIgnoreCase) &&
|
||||
!full.StartsWith(prefix, StringComparison.OrdinalIgnoreCase))
|
||||
throw new InvalidOperationException($"路径越界: {relative}");
|
||||
return full;
|
||||
}
|
||||
|
||||
private static string Relative(string baseDir, string file) =>
|
||||
Path.GetRelativePath(baseDir, file).Replace('\\', '/');
|
||||
}
|
||||
@@ -0,0 +1,167 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.ObjectModel;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
using GC.Models;
|
||||
|
||||
namespace GC.Services;
|
||||
|
||||
public enum DownloadState
|
||||
{
|
||||
Queued,
|
||||
Running,
|
||||
Completed,
|
||||
Failed,
|
||||
Canceled
|
||||
}
|
||||
|
||||
/// <summary>一条下载任务(进入后台列表后一直保留,直到用户清除)。</summary>
|
||||
public sealed partial class DownloadJob : ObservableObject
|
||||
{
|
||||
public RemoteModel Model { get; }
|
||||
public string Id => Model.Id;
|
||||
public string Name => Model.LocalizedName;
|
||||
public string Version => Model.Manifest.Version;
|
||||
public CancellationTokenSource Cts { get; } = new();
|
||||
|
||||
[ObservableProperty] private DownloadState _state = DownloadState.Queued;
|
||||
[ObservableProperty] private double _progress;
|
||||
[ObservableProperty] private string _statusText = "";
|
||||
[ObservableProperty] private string _detailText = "";
|
||||
[ObservableProperty] private string? _error;
|
||||
|
||||
public DownloadJob(RemoteModel model)
|
||||
{
|
||||
Model = model;
|
||||
RefreshText();
|
||||
}
|
||||
|
||||
public bool IsActive => State is DownloadState.Queued or DownloadState.Running;
|
||||
public bool CanRetry => State is DownloadState.Failed or DownloadState.Canceled;
|
||||
public bool IsDone => State == DownloadState.Completed;
|
||||
|
||||
public void RefreshText()
|
||||
{
|
||||
StatusText = State switch
|
||||
{
|
||||
DownloadState.Queued => L.I["dl.status.queued"],
|
||||
DownloadState.Running => L.I["dl.status.downloading"],
|
||||
DownloadState.Completed => L.I["dl.status.done"],
|
||||
DownloadState.Failed => L.I["dl.status.failed"],
|
||||
_ => L.I["dl.status.canceled"]
|
||||
};
|
||||
DetailText = State == DownloadState.Failed && !string.IsNullOrEmpty(Error)
|
||||
? Error!
|
||||
: ModelScanner.HumanSize(Model.SizeBytes);
|
||||
OnPropertyChanged(nameof(IsActive));
|
||||
OnPropertyChanged(nameof(CanRetry));
|
||||
OnPropertyChanged(nameof(IsDone));
|
||||
}
|
||||
|
||||
partial void OnStateChanged(DownloadState value) => RefreshText();
|
||||
partial void OnErrorChanged(string? value) => RefreshText();
|
||||
}
|
||||
|
||||
/// <summary>下载中心:最多 2 个并发,任务在「后台列表」里折叠展示。</summary>
|
||||
public sealed class DownloadCenter
|
||||
{
|
||||
private readonly ModelRepository _repository;
|
||||
private readonly AppPaths _paths;
|
||||
private readonly SemaphoreSlim _slots = new(2);
|
||||
|
||||
public ObservableCollection<DownloadJob> Jobs { get; } = new();
|
||||
public event Action? Installed;
|
||||
|
||||
public DownloadCenter(AppPaths paths, ModelRepository repository)
|
||||
{
|
||||
_paths = paths;
|
||||
_repository = repository;
|
||||
}
|
||||
|
||||
public DownloadJob Enqueue(RemoteModel model)
|
||||
{
|
||||
var running = Jobs.FirstOrDefault(j => j.Id.Equals(model.Id, StringComparison.OrdinalIgnoreCase) && j.IsActive);
|
||||
if (running != null) return running;
|
||||
|
||||
var job = new DownloadJob(model);
|
||||
Jobs.Insert(0, job);
|
||||
_ = RunAsync(job);
|
||||
return job;
|
||||
}
|
||||
|
||||
private async Task RunAsync(DownloadJob job)
|
||||
{
|
||||
// 在 UI 线程构造,回调自动回到 UI 线程
|
||||
var progress = new Progress<(long Done, long Total)>(p =>
|
||||
{
|
||||
job.Progress = p.Total > 0 ? Math.Clamp((double)p.Done / p.Total, 0, 1) : 0;
|
||||
});
|
||||
|
||||
try
|
||||
{
|
||||
await _slots.WaitAsync(job.Cts.Token).ConfigureAwait(true);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
job.State = DownloadState.Canceled;
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
job.State = DownloadState.Running;
|
||||
await ModelInstaller.InstallAsync(job.Model, _paths.ModelRoot, progress, job.Cts.Token)
|
||||
.ConfigureAwait(true);
|
||||
job.Progress = 1;
|
||||
job.State = DownloadState.Completed;
|
||||
_repository.NotifyChanged();
|
||||
Installed?.Invoke();
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
job.State = DownloadState.Canceled;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
job.Error = ex.Message;
|
||||
job.State = DownloadState.Failed;
|
||||
}
|
||||
finally
|
||||
{
|
||||
_slots.Release();
|
||||
}
|
||||
}
|
||||
|
||||
public void Cancel(DownloadJob job)
|
||||
{
|
||||
try { job.Cts.Cancel(); } catch { }
|
||||
if (job.State == DownloadState.Queued) job.State = DownloadState.Canceled;
|
||||
}
|
||||
|
||||
public void Retry(DownloadJob job)
|
||||
{
|
||||
if (job.IsActive) return;
|
||||
Jobs.Remove(job);
|
||||
Enqueue(job.Model);
|
||||
}
|
||||
|
||||
public void Remove(DownloadJob job)
|
||||
{
|
||||
Cancel(job);
|
||||
Jobs.Remove(job);
|
||||
}
|
||||
|
||||
public void ClearFinished()
|
||||
{
|
||||
for (var i = Jobs.Count - 1; i >= 0; i--)
|
||||
{
|
||||
if (Jobs[i].State is DownloadState.Completed or DownloadState.Canceled)
|
||||
Jobs.RemoveAt(i);
|
||||
}
|
||||
}
|
||||
|
||||
public int ActiveCount => Jobs.Count(j => j.IsActive);
|
||||
}
|
||||
@@ -0,0 +1,227 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Net.Http;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace GC.Services;
|
||||
|
||||
/// <summary>
|
||||
/// 启动器更新走 GitCode Release,模型仍走仓库 contents API 的远端源。
|
||||
///
|
||||
/// · 版本判定:最新 Release 的 tag_name(如 v1.0.1 / GC-1.0.1)与本地程序集版本比较;
|
||||
/// · 发布包:按附件名识别平台(如 GC-1.0.1-Win-amd64.zip),用 browser_download_url 下载;
|
||||
/// · 校验:附件自带的 sha256/size(Gitee/GitCode 的 assets 可能没有 sha256,
|
||||
/// 此时退回 version.json 里同名 RID 条目的 sha256,两者都没有则只校验非空);
|
||||
/// · 模型清单与模型文件:完全委托给内部 GitCodeRemote,保持原有链路不变。
|
||||
///
|
||||
/// Release API 失败(仓库还没有 Release / 断网)时静默回退到 version.json 的
|
||||
/// launcher 字段,保证「只发仓库、不发 Release」的旧发布方式仍然可用。
|
||||
/// </summary>
|
||||
public sealed class GitCodeReleaseRemote : IModelRemote
|
||||
{
|
||||
private readonly GitCodeRemote _content;
|
||||
private readonly string _releasesUrl;
|
||||
private readonly Dictionary<string, (string Url, string? Sha256, long Size, string Name)> _assets = new();
|
||||
|
||||
// 共享静态 HttpClient:避免每次检查更新都创建新实例导致端口耗尽;
|
||||
// headers 只在一处设置,多个线程并发读取是线程安全的。
|
||||
private static readonly HttpClient Http = CreateHttp();
|
||||
|
||||
private static HttpClient CreateHttp()
|
||||
{
|
||||
var client = new HttpClient { Timeout = TimeSpan.FromSeconds(15) };
|
||||
client.DefaultRequestHeaders.UserAgent.ParseAdd("GC-Updater/1.0");
|
||||
client.DefaultRequestHeaders.Accept.ParseAdd("application/json");
|
||||
return client;
|
||||
}
|
||||
|
||||
public GitCodeReleaseRemote(string? manifestUrl, string? repository)
|
||||
{
|
||||
_content = new GitCodeRemote(manifestUrl, repository);
|
||||
var (owner, repo) = ParseOwnerRepo(repository);
|
||||
_releasesUrl = $"https://api.gitcode.com/api/v5/repos/{owner}/{repo}/releases";
|
||||
DisplayName = (string.IsNullOrWhiteSpace(repository)
|
||||
? GitCodeRemote.DefaultRepository : repository!.TrimEnd('/')) + " (Release)";
|
||||
}
|
||||
|
||||
private static (string Owner, string Repo) ParseOwnerRepo(string? url)
|
||||
{
|
||||
var raw = string.IsNullOrWhiteSpace(url) ? GitCodeRemote.DefaultRepository : url!.Trim();
|
||||
if (!Uri.TryCreate(raw, UriKind.Absolute, out var uri))
|
||||
return ("2509_92447106", "GC");
|
||||
var parts = uri.AbsolutePath.Trim('/').Split('/', StringSplitOptions.RemoveEmptyEntries);
|
||||
if (parts.Length < 2) return ("2509_92447106", "GC");
|
||||
var repo = parts[1].EndsWith(".git", StringComparison.OrdinalIgnoreCase)
|
||||
? parts[1][..^4] : parts[1];
|
||||
return (parts[0], repo);
|
||||
}
|
||||
|
||||
public string DisplayName { get; }
|
||||
public string SourceId => SourcePreset.Detect(_content.DisplayName).Id;
|
||||
|
||||
/// <summary>
|
||||
/// 模型部分照旧读仓库 version.json;成功拿到 Release 时,用 tag/附件覆盖启动器字段。
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
/// 只认 Release:拿不到任何 Release 就返回 null,由上层去问另一个源。
|
||||
/// 仓库里的 version.json 只用来补全「模型清单」与平台包兜底地址,
|
||||
/// 不再用它充当版本号来源。
|
||||
/// </summary>
|
||||
public async Task<RepoVersion?> GetVersionAsync(CancellationToken ct)
|
||||
{
|
||||
var version = await _content.GetVersionAsync(ct);
|
||||
|
||||
bool gotRelease;
|
||||
try
|
||||
{
|
||||
gotRelease = await ApplyReleaseAsync(version, ct);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.Error.WriteLine($"[gitcode] 读取 Release 失败: {ex.Message}");
|
||||
gotRelease = false;
|
||||
}
|
||||
|
||||
if (!gotRelease)
|
||||
{
|
||||
// 没有 Release:启动器版本留空(表示这个源没有可升级的启动器),
|
||||
// 但模型清单仍然有效,保证模型能正常同步。
|
||||
Console.WriteLine($"[gitcode] {DisplayName}: Release 为空(模型清单仍可用)");
|
||||
if (version != null)
|
||||
{
|
||||
version.Launcher.Version = "";
|
||||
version.Launcher.Packages.Clear();
|
||||
}
|
||||
}
|
||||
return version;
|
||||
}
|
||||
|
||||
private async Task<bool> ApplyReleaseAsync(RepoVersion? version, CancellationToken ct)
|
||||
{
|
||||
if (version == null) return false;
|
||||
|
||||
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(ct);
|
||||
timeout.CancelAfter(TimeSpan.FromSeconds(12));
|
||||
var text = await Http.GetStringAsync(_releasesUrl, timeout.Token);
|
||||
var trimmed = text.TrimStart();
|
||||
if (trimmed.Length == 0 || trimmed[0] != '[') return false; // 可能是错误页/对象
|
||||
|
||||
using var doc = JsonDocument.Parse(text);
|
||||
ReleaseInfo? latest = null;
|
||||
foreach (var el in doc.RootElement.EnumerateArray())
|
||||
{
|
||||
var info = ParseRelease(el);
|
||||
if (info == null || info.Draft || info.Prerelease) continue;
|
||||
// 取版本号最大的一条(API 通常已按时间倒序,这里再兜一层)
|
||||
if (latest == null || CompareVersion(info.Version, latest.Version) > 0) latest = info;
|
||||
}
|
||||
if (latest == null || string.IsNullOrWhiteSpace(latest.Version)) return false;
|
||||
|
||||
version.Launcher.Version = latest.Version;
|
||||
|
||||
_assets.Clear();
|
||||
foreach (var asset in latest.Assets)
|
||||
{
|
||||
var rid = asset.RidFromName(asset.Name);
|
||||
if (rid == null || string.IsNullOrWhiteSpace(asset.Url)) continue;
|
||||
// 同名平台取第一个有效附件
|
||||
if (!_assets.ContainsKey(rid))
|
||||
_assets[rid] = (asset.Url, asset.Sha256, asset.Size, asset.Name);
|
||||
}
|
||||
|
||||
// 把附件地址写回 packages:有附件就用附件的直链与校验值,
|
||||
// 没有对应平台附件时保留 version.json 里原来的 path/url 兜底。
|
||||
foreach (var (rid, info) in _assets)
|
||||
{
|
||||
if (!version.Launcher.Packages.TryGetValue(rid, out var pkg))
|
||||
{
|
||||
pkg = new RepoPackage();
|
||||
version.Launcher.Packages[rid] = pkg;
|
||||
}
|
||||
pkg.Url = info.Url;
|
||||
pkg.AssetName = info.Name;
|
||||
if (!string.IsNullOrWhiteSpace(info.Sha256)) pkg.Sha256 = info.Sha256;
|
||||
if (info.Size > 0) pkg.Size = info.Size;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private static int CompareVersion(string a, string b)
|
||||
{
|
||||
if (Version.TryParse(a, out var va) && Version.TryParse(b, out var vb)) return va.CompareTo(vb);
|
||||
return string.Compare(a, b, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
private static ReleaseInfo? ParseRelease(JsonElement el)
|
||||
{
|
||||
try
|
||||
{
|
||||
var info = new ReleaseInfo
|
||||
{
|
||||
TagName = Str(el, "tag_name") ?? Str(el, "tag") ?? "",
|
||||
Name = Str(el, "name") ?? "",
|
||||
Draft = Bool(el, "draft") ?? false,
|
||||
Prerelease = Bool(el, "prerelease") ?? Bool(el, "pre_release") ?? false,
|
||||
PublishedAt = Str(el, "published_at") ?? Str(el, "created_at")
|
||||
};
|
||||
if (el.TryGetProperty("assets", out var assets) && assets.ValueKind == JsonValueKind.Array)
|
||||
{
|
||||
foreach (var a in assets.EnumerateArray())
|
||||
{
|
||||
// 跳过 GitCode 自动生成的源码包(type=source),只取真正的发布附件
|
||||
var type = Str(a, "type");
|
||||
if (string.Equals(type, "source", StringComparison.OrdinalIgnoreCase)) continue;
|
||||
info.Assets.Add(new ReleaseAsset
|
||||
{
|
||||
Name = Str(a, "name") ?? Str(a, "file_name") ?? "",
|
||||
BrowserDownloadUrl = Str(a, "browser_download_url"),
|
||||
DownloadUrl = Str(a, "download_url") ?? Str(a, "url"),
|
||||
Size = Num(a, "size"),
|
||||
Sha256 = Str(a, "sha256") ?? Str(a, "digest"),
|
||||
Type = type
|
||||
});
|
||||
}
|
||||
}
|
||||
// 有些平台把附件放在顶层 assets_link / attachments
|
||||
if (info.Assets.Count == 0 &&
|
||||
el.TryGetProperty("attachments", out var att) && att.ValueKind == JsonValueKind.Array)
|
||||
{
|
||||
foreach (var a in att.EnumerateArray())
|
||||
info.Assets.Add(new ReleaseAsset
|
||||
{
|
||||
Name = Str(a, "name") ?? "",
|
||||
BrowserDownloadUrl = Str(a, "browser_download_url") ?? Str(a, "url"),
|
||||
Size = Num(a, "size")
|
||||
});
|
||||
}
|
||||
return info;
|
||||
}
|
||||
catch { return null; }
|
||||
}
|
||||
|
||||
private static string? Str(JsonElement el, string name)
|
||||
=> el.TryGetProperty(name, out var v) && v.ValueKind == JsonValueKind.String
|
||||
? v.GetString() : null;
|
||||
|
||||
private static bool? Bool(JsonElement el, string name)
|
||||
=> el.TryGetProperty(name, out var v) &&
|
||||
(v.ValueKind == JsonValueKind.True || v.ValueKind == JsonValueKind.False)
|
||||
? v.GetBoolean() : null;
|
||||
|
||||
private static long Num(JsonElement el, string name)
|
||||
=> el.TryGetProperty(name, out var v) && v.ValueKind == JsonValueKind.Number
|
||||
&& v.TryGetInt64(out var n) ? n : 0;
|
||||
|
||||
// ---- 模型链路:原样委托,不做任何改动 ----
|
||||
public Task<IReadOnlyList<RepoEntry>> ListTreeAsync(string rootPath, CancellationToken ct)
|
||||
=> _content.ListTreeAsync(rootPath, ct);
|
||||
|
||||
public Task<byte[]> DownloadAsync(RepoEntry entry, CancellationToken ct)
|
||||
=> _content.DownloadAsync(entry, ct);
|
||||
|
||||
/// <summary>启动器包:优先用 Release 附件直链下载(url 已被 ApplyReleaseAsync 覆盖)。</summary>
|
||||
public Task<byte[]?> DownloadPackageAsync(RepoPackage package, CancellationToken ct)
|
||||
=> _content.DownloadPackageAsync(package, ct);
|
||||
}
|
||||
@@ -0,0 +1,318 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Net.Http;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace GC.Services;
|
||||
|
||||
/// <summary>
|
||||
/// gitcode 仓库源。默认地址来自 AppSettings.UpdateRepository
|
||||
/// (https://gitcode.com/2509_92447106/GC),可改成任意 gitcode 仓库或
|
||||
/// https://gitcode.com/<owner>/<repo>/tree/<branch>/model 这样的地址。
|
||||
/// 匿名访问 v5 contents API:目录 -> 数组,文件 -> { content: base64 };
|
||||
/// 文件项自带 download_url(raw.gitcode.com/blobs/<sha>/...),可直接下载二进制。
|
||||
/// </summary>
|
||||
public sealed class GitCodeRemote : IModelRemote
|
||||
{
|
||||
public const string DefaultRepository = "https://gitcode.com/2509_92447106/GC";
|
||||
|
||||
private readonly HttpClient _http;
|
||||
private readonly string _api;
|
||||
private readonly string _branch;
|
||||
private readonly string _versionUrl;
|
||||
private readonly string? _fallbackUrl;
|
||||
private readonly string _displayName;
|
||||
private string _modelDir = "model";
|
||||
|
||||
public string DisplayName => _displayName;
|
||||
|
||||
public GitCodeRemote(string? manifestUrl = null, string? repository = null)
|
||||
{
|
||||
var (owner, repo, branch) = ParseRepository(repository);
|
||||
_branch = branch;
|
||||
_api = $"https://api.gitcode.com/api/v5/repos/{owner}/{repo}/contents/";
|
||||
_displayName = string.IsNullOrWhiteSpace(repository)
|
||||
? DefaultRepository : repository!.TrimEnd('/');
|
||||
|
||||
_http = new HttpClient { Timeout = TimeSpan.FromMinutes(2) };
|
||||
_http.DefaultRequestHeaders.UserAgent.ParseAdd("GC-Updater/1.0");
|
||||
_http.DefaultRequestHeaders.Accept.ParseAdd("application/json");
|
||||
|
||||
if (string.IsNullOrWhiteSpace(manifestUrl))
|
||||
{
|
||||
_versionUrl = _api + "version.json?ref=" + _branch;
|
||||
_fallbackUrl = _api + "model/version.json?ref=" + _branch;
|
||||
}
|
||||
else
|
||||
{
|
||||
_versionUrl = manifestUrl!;
|
||||
_fallbackUrl = null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>从仓库 URL 解析 owner / repo / branch,解析失败回退到默认仓库。</summary>
|
||||
private static (string Owner, string Repo, string Branch) ParseRepository(string? url)
|
||||
{
|
||||
var raw = string.IsNullOrWhiteSpace(url) ? DefaultRepository : url!.Trim();
|
||||
if (!Uri.TryCreate(raw, UriKind.Absolute, out var uri))
|
||||
return ("2509_92447106", "GC", "main");
|
||||
var parts = uri.AbsolutePath.Trim('/').Split('/', StringSplitOptions.RemoveEmptyEntries);
|
||||
if (parts.Length < 2) return ("2509_92447106", "GC", "main");
|
||||
var owner = parts[0];
|
||||
var repo = parts[1].EndsWith(".git", StringComparison.OrdinalIgnoreCase)
|
||||
? parts[1][..^4] : parts[1];
|
||||
var branch = parts.Length >= 4 && parts[2].Equals("tree", StringComparison.OrdinalIgnoreCase)
|
||||
? parts[3] : "main";
|
||||
return (owner, repo, branch);
|
||||
}
|
||||
|
||||
public async Task<RepoVersion?> GetVersionAsync(CancellationToken ct)
|
||||
{
|
||||
RepoVersion? version = await ReadVersionFromAsync(_versionUrl, ct);
|
||||
if (version == null && _fallbackUrl != null)
|
||||
version = await ReadVersionFromAsync(_fallbackUrl, ct);
|
||||
if (version != null && !string.IsNullOrWhiteSpace(version.ModelDir))
|
||||
_modelDir = version.ModelDir.Trim('/');
|
||||
return version;
|
||||
}
|
||||
|
||||
private async Task<RepoVersion?> ReadVersionFromAsync(string url, CancellationToken ct)
|
||||
{
|
||||
string text;
|
||||
try
|
||||
{
|
||||
// 离线 / 网络不通时最多等 10 秒,不能让启动界面一直卡在「检查更新」
|
||||
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(ct);
|
||||
timeout.CancelAfter(TimeSpan.FromSeconds(10));
|
||||
text = await _http.GetStringAsync(url, timeout.Token);
|
||||
}
|
||||
catch (HttpRequestException) { return null; }
|
||||
catch (OperationCanceledException) when (!ct.IsCancellationRequested) { return null; }
|
||||
|
||||
var trimmed = text.TrimStart();
|
||||
if (trimmed.Length == 0 || trimmed[0] != '{') return null;
|
||||
|
||||
try
|
||||
{
|
||||
using var doc = JsonDocument.Parse(text);
|
||||
var payload = text;
|
||||
if (doc.RootElement.TryGetProperty("encoding", out _) &&
|
||||
doc.RootElement.TryGetProperty("content", out var content))
|
||||
{
|
||||
var raw = Convert.FromBase64String(content.GetString() ?? "");
|
||||
payload = Encoding.UTF8.GetString(raw);
|
||||
}
|
||||
if (!payload.TrimStart().StartsWith("{", StringComparison.Ordinal)) return null;
|
||||
var version = System.Text.Json.JsonSerializer.Deserialize<RepoVersion>(
|
||||
payload, GC.Services.Json.Options);
|
||||
// 404 / 错误页也可能返回一个 JSON 对象,用 generated 确认这确实是版本清单
|
||||
return version != null && !string.IsNullOrWhiteSpace(version.Generated) ? version : null;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.Error.WriteLine($"版本清单解析失败 {url}: {ex.Message}");
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 递归列出目录树(含目录项与文件项)。
|
||||
/// 每个子目录一次 HTTP 请求,因此并行展开同一层的所有目录,
|
||||
/// 否则 3 个模型、十几个目录串行请求会非常慢。
|
||||
/// </summary>
|
||||
public async Task<IReadOnlyList<RepoEntry>> ListTreeAsync(string rootPath, CancellationToken ct)
|
||||
{
|
||||
var result = new List<RepoEntry>();
|
||||
var bag = new System.Collections.Concurrent.ConcurrentBag<RepoEntry>();
|
||||
var repoPath = (rootPath ?? _modelDir).Trim('/');
|
||||
await WalkParallelAsync(repoPath, "", 0, bag, ct);
|
||||
|
||||
// 稳定排序:目录在前、按路径字典序,保证调用方拿到确定顺序
|
||||
result = bag.OrderBy(e => e.IsDirectory ? 0 : 1)
|
||||
.ThenBy(e => e.RelativePath, StringComparer.Ordinal)
|
||||
.ToList();
|
||||
return result;
|
||||
}
|
||||
|
||||
private async Task WalkParallelAsync(string repoPath, string relative, int depth,
|
||||
System.Collections.Concurrent.ConcurrentBag<RepoEntry> bag, CancellationToken ct)
|
||||
{
|
||||
if (depth > 8) return;
|
||||
var url = _api + repoPath + "?ref=" + _branch;
|
||||
string text;
|
||||
try { text = await GetWithRetryAsync(url, ct); }
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.Error.WriteLine($"列目录失败 {repoPath}: {ex.Message}");
|
||||
return;
|
||||
}
|
||||
if (!text.TrimStart().StartsWith("[", StringComparison.Ordinal)) return;
|
||||
|
||||
var subDirs = new List<(string Path, string Relative)>();
|
||||
|
||||
using (var doc = JsonDocument.Parse(text))
|
||||
{
|
||||
foreach (var item in doc.RootElement.EnumerateArray())
|
||||
{
|
||||
ct.ThrowIfCancellationRequested();
|
||||
var name = Str(item, "name");
|
||||
if (string.IsNullOrEmpty(name) || name.StartsWith('.')) continue;
|
||||
// 这些目录不是模型运行数据,跳过可显著减少请求
|
||||
// (模型目录里常见的 src/ bin/ obj/ 是源码与构建产物)
|
||||
if (IsIgnoredDir(name)) continue;
|
||||
var path = Str(item, "path");
|
||||
if (string.IsNullOrWhiteSpace(path)) path = repoPath + "/" + name;
|
||||
var isDir = Str(item, "type") == "dir";
|
||||
var childRelative = relative.Length == 0 ? name : relative + "/" + name;
|
||||
|
||||
bag.Add(new RepoEntry
|
||||
{
|
||||
Name = name,
|
||||
Path = path!,
|
||||
RelativePath = childRelative,
|
||||
IsDirectory = isDir,
|
||||
DownloadUrl = NullableStr(item, "download_url"),
|
||||
Sha = NullableStr(item, "sha"),
|
||||
Size = Num(item, "size")
|
||||
});
|
||||
|
||||
if (isDir) subDirs.Add((path!, childRelative));
|
||||
}
|
||||
}
|
||||
|
||||
if (subDirs.Count == 0) return;
|
||||
|
||||
// 同层并行;并发保持很低——GitCode API 对突发请求会返回 429
|
||||
using var gate = new SemaphoreSlim(2);
|
||||
var tasks = subDirs.Select(async d =>
|
||||
{
|
||||
await gate.WaitAsync(ct);
|
||||
try { await WalkParallelAsync(d.Path, d.Relative, depth + 1, bag, ct); }
|
||||
finally { gate.Release(); }
|
||||
});
|
||||
await Task.WhenAll(tasks);
|
||||
}
|
||||
|
||||
private async Task WalkAsync(string repoPath, string relative, int depth,
|
||||
List<RepoEntry> result, CancellationToken ct)
|
||||
{
|
||||
if (depth > 8) return;
|
||||
var url = _api + repoPath + "?ref=" + _branch;
|
||||
var text = await _http.GetStringAsync(url, ct);
|
||||
if (!text.TrimStart().StartsWith("[", StringComparison.Ordinal)) return;
|
||||
|
||||
using var doc = JsonDocument.Parse(text);
|
||||
foreach (var item in doc.RootElement.EnumerateArray())
|
||||
{
|
||||
ct.ThrowIfCancellationRequested();
|
||||
var name = Str(item, "name");
|
||||
if (string.IsNullOrEmpty(name) || name.StartsWith('.')) continue;
|
||||
var path = Str(item, "path");
|
||||
if (string.IsNullOrWhiteSpace(path)) path = repoPath + "/" + name;
|
||||
var isDir = Str(item, "type") == "dir";
|
||||
var childRelative = relative.Length == 0 ? name : relative + "/" + name;
|
||||
|
||||
result.Add(new RepoEntry
|
||||
{
|
||||
Name = name,
|
||||
Path = path!,
|
||||
RelativePath = childRelative,
|
||||
IsDirectory = isDir,
|
||||
DownloadUrl = NullableStr(item, "download_url"),
|
||||
Sha = NullableStr(item, "sha"),
|
||||
Size = Num(item, "size")
|
||||
});
|
||||
|
||||
if (isDir) await WalkAsync(path!, childRelative, depth + 1, result, ct);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>遍历时忽略的目录:源码与构建产物不属于模型运行数据。</summary>
|
||||
private static bool IsIgnoredDir(string name) => name switch
|
||||
{
|
||||
"src" => true,
|
||||
"bin" => true,
|
||||
"obj" => true,
|
||||
"node_modules" => true,
|
||||
".git" => true,
|
||||
".vs" => true,
|
||||
_ => false
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// 带退避重试的 GET。GitCode API 对突发请求返回 429,
|
||||
/// 这里做 3 次指数退避,避免并行遍历时直接失败。
|
||||
/// </summary>
|
||||
private async Task<string> GetWithRetryAsync(string url, CancellationToken ct,
|
||||
int maxAttempts = 3)
|
||||
{
|
||||
for (var attempt = 1; ; attempt++)
|
||||
{
|
||||
try
|
||||
{
|
||||
return await _http.GetStringAsync(url, ct);
|
||||
}
|
||||
catch (HttpRequestException ex) when (attempt < maxAttempts)
|
||||
{
|
||||
// 429 / 5xx 才重试,其余直接抛
|
||||
var retriable = ex.StatusCode is null ||
|
||||
(int)ex.StatusCode == 429 ||
|
||||
(int)ex.StatusCode >= 500;
|
||||
if (!retriable) throw;
|
||||
await Task.Delay(TimeSpan.FromMilliseconds(400 * attempt * attempt), ct);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<byte[]> DownloadAsync(RepoEntry entry, CancellationToken ct)
|
||||
{
|
||||
if (!string.IsNullOrWhiteSpace(entry.DownloadUrl))
|
||||
return await _http.GetByteArrayAsync(entry.DownloadUrl!, ct);
|
||||
|
||||
var url = _api + entry.Path.Trim('/') + "?ref=" + _branch;
|
||||
var text = await _http.GetStringAsync(url, ct);
|
||||
using var doc = JsonDocument.Parse(text);
|
||||
if (!doc.RootElement.TryGetProperty("content", out var content))
|
||||
throw new InvalidOperationException($"远端文件没有内容: {entry.Path}");
|
||||
return Convert.FromBase64String(content.GetString() ?? "");
|
||||
}
|
||||
|
||||
public async Task<byte[]?> DownloadPackageAsync(RepoPackage package, CancellationToken ct)
|
||||
{
|
||||
string? url = string.IsNullOrWhiteSpace(package.Url) ? null : package.Url!.Trim();
|
||||
if (url == null && !string.IsNullOrWhiteSpace(package.Path))
|
||||
{
|
||||
try
|
||||
{
|
||||
var apiUrl = _api + package.Path!.Trim('/') + "?ref=" + _branch;
|
||||
var text = await _http.GetStringAsync(apiUrl, ct);
|
||||
using var doc = JsonDocument.Parse(text);
|
||||
if (doc.RootElement.TryGetProperty("download_url", out var dl))
|
||||
url = dl.GetString();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.Error.WriteLine($"解析启动器包地址失败: {ex.Message}");
|
||||
return null;
|
||||
}
|
||||
}
|
||||
if (string.IsNullOrWhiteSpace(url)) return null;
|
||||
return await _http.GetByteArrayAsync(url!, ct);
|
||||
}
|
||||
|
||||
private static string Str(JsonElement item, string name)
|
||||
=> item.TryGetProperty(name, out var v) && v.ValueKind == JsonValueKind.String
|
||||
? v.GetString() ?? "" : "";
|
||||
|
||||
private static string? NullableStr(JsonElement item, string name)
|
||||
=> item.TryGetProperty(name, out var v) && v.ValueKind == JsonValueKind.String
|
||||
? v.GetString() : null;
|
||||
|
||||
private static long Num(JsonElement item, string name)
|
||||
=> item.TryGetProperty(name, out var v) && v.ValueKind == JsonValueKind.Number
|
||||
&& v.TryGetInt64(out var n) ? n : 0;
|
||||
}
|
||||
@@ -0,0 +1,293 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Net.Http;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace GC.Services;
|
||||
|
||||
/// <summary>
|
||||
/// Gitea / Forgejo 后端(Xhmcl 用的就是这个)。
|
||||
///
|
||||
/// · 目录:GET /api/v1/repos/{owner}/{repo}/contents/{path}
|
||||
/// 返回数组(目录)或对象(单文件),带 name/path/size/type/download_url
|
||||
/// · 原始文件:GET {host}/{owner}/{repo}/raw/branch/{branch}/{path}
|
||||
/// · Release:GET /api/v1/repos/{owner}/{repo}/releases
|
||||
/// 版本取 tag_name;附件取 assets[].browser_download_url
|
||||
///
|
||||
/// Release 为空时(仓库还没发布),回退到仓库里的 version.json,保证只推仓库也能更新。
|
||||
/// </summary>
|
||||
public sealed class GiteaRemote : IModelRemote
|
||||
{
|
||||
private readonly SourcePreset _preset;
|
||||
private static readonly HttpClient Http = CreateHttp();
|
||||
|
||||
private static HttpClient CreateHttp()
|
||||
{
|
||||
var c = new HttpClient { Timeout = TimeSpan.FromSeconds(20) };
|
||||
c.DefaultRequestHeaders.UserAgent.ParseAdd("GC-Updater/1.0");
|
||||
c.DefaultRequestHeaders.Accept.ParseAdd("application/json");
|
||||
return c;
|
||||
}
|
||||
|
||||
public GiteaRemote(SourcePreset preset)
|
||||
{
|
||||
_preset = preset;
|
||||
DisplayName = preset.Name;
|
||||
}
|
||||
|
||||
public string DisplayName { get; }
|
||||
public string SourceId => _preset.Id;
|
||||
|
||||
private string RepoApi => $"{_preset.ApiBase}/repos/{_preset.Owner}/{_preset.Repo}";
|
||||
|
||||
// ---------------------------------------------------------------- 清单
|
||||
|
||||
/// <summary>
|
||||
/// 两件事分开取:
|
||||
/// · **模型清单**永远来自仓库 version.json(模型不需要发 Release)
|
||||
/// · **启动器版本**只认 Release;没有 Release 时把版本号留空,
|
||||
/// 由上层去问另一个源(LeaderUpdater 会横向比较)。
|
||||
/// 以前把两者绑在一起,导致没有 Release 时连模型都同步不了。
|
||||
/// </summary>
|
||||
public async Task<RepoVersion?> GetVersionAsync(CancellationToken ct)
|
||||
{
|
||||
var fromRepo = await TryGetVersionFromRepoAsync(ct);
|
||||
var fromRelease = await TryGetVersionFromReleasesAsync(ct);
|
||||
|
||||
// 模型清单:仓库里有就用仓库的(保证模型能更新)
|
||||
var result = fromRepo ?? new RepoVersion
|
||||
{
|
||||
Repository = _preset.HomeUrl,
|
||||
Branch = _preset.Branch
|
||||
};
|
||||
|
||||
if (fromRelease != null)
|
||||
{
|
||||
// Release 提供启动器版本与平台附件
|
||||
result.Launcher.Version = fromRelease.Launcher.Version;
|
||||
foreach (var kv in fromRelease.Launcher.Packages)
|
||||
result.Launcher.Packages[kv.Key] = kv.Value;
|
||||
return result;
|
||||
}
|
||||
|
||||
// 没有 Release:清空启动器版本,让上层知道"这个源没有可升级的启动器"
|
||||
Console.WriteLine($"[gitea] {_preset.Name}: Release 为空(模型清单仍可用)");
|
||||
result.Launcher.Version = "";
|
||||
result.Launcher.Packages.Clear();
|
||||
|
||||
// 只有模型清单时也返回,保证模型能同步;启动器版本为空表示无升级
|
||||
return result.Models.Count > 0 ? result : null;
|
||||
}
|
||||
/// <summary>读仓库里的 version.json(模型清单 + 兜底信息)。</summary>
|
||||
private async Task<RepoVersion?> TryGetVersionFromRepoAsync(CancellationToken ct)
|
||||
{
|
||||
foreach (var url in new[] { _preset.RawUrl("version.json"), _preset.RawUrl("model/version.json") })
|
||||
{
|
||||
try
|
||||
{
|
||||
var text = await Http.GetStringAsync(url, ct);
|
||||
if (!text.TrimStart().StartsWith('{')) continue; // 可能返回 HTML
|
||||
var doc = JsonSerializer.Deserialize<RepoVersion>(text, Json.Options);
|
||||
if (doc != null) return doc;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.Error.WriteLine($"[gitea] version.json 读取失败 {url}: {ex.Message}");
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 从 Release 列表里挑**版本号最高**的一个(不是最新发布时间的那个),
|
||||
/// 并把它对应平台的附件填进 packages。
|
||||
/// </summary>
|
||||
private async Task<RepoVersion?> TryGetVersionFromReleasesAsync(CancellationToken ct)
|
||||
{
|
||||
try
|
||||
{
|
||||
var json = await Http.GetStringAsync($"{RepoApi}/releases", ct);
|
||||
using var doc = JsonDocument.Parse(json);
|
||||
if (doc.RootElement.ValueKind != JsonValueKind.Array) return null;
|
||||
|
||||
var candidates = new List<(string Version, JsonElement Node)>();
|
||||
foreach (var rel in doc.RootElement.EnumerateArray())
|
||||
{
|
||||
if (rel.TryGetProperty("draft", out var draft) && draft.ValueKind == JsonValueKind.True)
|
||||
continue; // 草稿不算发布
|
||||
var tag = rel.TryGetProperty("tag_name", out var t) ? t.GetString() ?? "" : "";
|
||||
var ver = VersionUtil.Normalize(tag);
|
||||
if (string.IsNullOrWhiteSpace(ver)) continue;
|
||||
candidates.Add((ver, rel));
|
||||
}
|
||||
if (candidates.Count == 0)
|
||||
{
|
||||
// 还没发布 Release 是正常状态:交给上层去问另一个源
|
||||
Console.WriteLine($"[gitea] {_preset.Name}: Release 列表为空");
|
||||
return null;
|
||||
}
|
||||
|
||||
var best = candidates
|
||||
.OrderByDescending(c => VersionUtil.Parse(c.Version))
|
||||
.First();
|
||||
|
||||
var result = new RepoVersion
|
||||
{
|
||||
Repository = _preset.HomeUrl,
|
||||
Branch = _preset.Branch,
|
||||
Launcher = new RepoLauncher { Version = best.Version }
|
||||
};
|
||||
|
||||
// 附件:按文件名识别平台
|
||||
if (best.Node.TryGetProperty("assets", out var assets) &&
|
||||
assets.ValueKind == JsonValueKind.Array)
|
||||
{
|
||||
foreach (var a in assets.EnumerateArray())
|
||||
{
|
||||
var name = a.TryGetProperty("name", out var n) ? n.GetString() ?? "" : "";
|
||||
var url = a.TryGetProperty("browser_download_url", out var u) ? u.GetString() ?? "" : "";
|
||||
if (string.IsNullOrWhiteSpace(name) || string.IsNullOrWhiteSpace(url)) continue;
|
||||
|
||||
var rid = PlatformFromAssetName(name);
|
||||
if (rid == null) continue;
|
||||
|
||||
var size = a.TryGetProperty("size", out var s) && s.TryGetInt64(out var sz) ? sz : 0;
|
||||
result.Launcher.Packages[rid] = new RepoPackage
|
||||
{
|
||||
Url = url,
|
||||
AssetName = name,
|
||||
Size = size
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
return result.Launcher.Packages.Count > 0 ? result : null;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.Error.WriteLine($"[gitea] Release 读取失败({_preset.Name}): {ex.Message}");
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>从附件名推断 RID:GC-1.0.6-win-amd64.zip → win-x64</summary>
|
||||
private static string? PlatformFromAssetName(string name)
|
||||
{
|
||||
var n = name.ToLowerInvariant();
|
||||
if (!n.EndsWith(".zip")) return null;
|
||||
if (n.Contains("win") && n.Contains("arm64")) return "win-arm64";
|
||||
if (n.Contains("win") && (n.Contains("amd64") || n.Contains("x64"))) return "win-x64";
|
||||
if (n.Contains("mac") && n.Contains("arm64")) return "osx-arm64";
|
||||
if (n.Contains("mac") && n.Contains("x64")) return "osx-x64";
|
||||
if (n.Contains("linux") && n.Contains("x64")) return "linux-x64";
|
||||
return null;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- 目录
|
||||
|
||||
public async Task<IReadOnlyList<RepoEntry>> ListTreeAsync(string rootPath, CancellationToken ct)
|
||||
{
|
||||
var result = new List<RepoEntry>();
|
||||
await WalkAsync(rootPath.Trim('/'), "", result, ct, depth: 0);
|
||||
return result;
|
||||
}
|
||||
|
||||
private async Task WalkAsync(string apiPath, string relPrefix, List<RepoEntry> sink,
|
||||
CancellationToken ct, int depth)
|
||||
{
|
||||
if (depth > 8) return;
|
||||
|
||||
var url = $"{RepoRepoContentsUrl()}/{apiPath}";
|
||||
string json;
|
||||
try { json = await Http.GetStringAsync(url, ct); }
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.Error.WriteLine($"[gitea] 列目录失败 {apiPath}: {ex.Message}");
|
||||
return;
|
||||
}
|
||||
|
||||
using var doc = JsonDocument.Parse(json);
|
||||
var root = doc.RootElement;
|
||||
|
||||
// 单文件
|
||||
if (root.ValueKind == JsonValueKind.Object)
|
||||
{
|
||||
AddFile(root, relPrefix, sink);
|
||||
return;
|
||||
}
|
||||
if (root.ValueKind != JsonValueKind.Array) return;
|
||||
|
||||
var subdirs = new List<(string Path, string Rel)>();
|
||||
foreach (var item in root.EnumerateArray())
|
||||
{
|
||||
var type = item.TryGetProperty("type", out var ty) ? ty.GetString() ?? "" : "";
|
||||
var name = item.TryGetProperty("name", out var nm) ? nm.GetString() ?? "" : "";
|
||||
if (string.IsNullOrEmpty(name)) continue;
|
||||
// 跳过构建产物与源码,模型包只需要清单与数据
|
||||
if (type == "dir")
|
||||
{
|
||||
if (IsIgnoredDir(name)) continue;
|
||||
subdirs.Add((apiPath + "/" + name, relPrefix + name + "/"));
|
||||
}
|
||||
else
|
||||
{
|
||||
AddFile(item, relPrefix, sink);
|
||||
}
|
||||
}
|
||||
|
||||
foreach (var (p, rel) in subdirs)
|
||||
await WalkAsync(p, rel, sink, ct, depth + 1);
|
||||
}
|
||||
|
||||
private string RepoRepoContentsUrl() => $"{RepoApi}/contents";
|
||||
|
||||
private static void AddFile(JsonElement item, string relPrefix, List<RepoEntry> sink)
|
||||
{
|
||||
var name = item.TryGetProperty("name", out var n) ? n.GetString() ?? "" : "";
|
||||
var path = item.TryGetProperty("path", out var p) ? p.GetString() ?? "" : name;
|
||||
var size = item.TryGetProperty("size", out var s) && s.TryGetInt64(out var sz) ? sz : 0;
|
||||
var dl = item.TryGetProperty("download_url", out var d) ? d.GetString() : null;
|
||||
var sha = item.TryGetProperty("sha", out var sh) ? sh.GetString() : null;
|
||||
|
||||
sink.Add(new RepoEntry
|
||||
{
|
||||
Name = name,
|
||||
Path = path,
|
||||
RelativePath = relPrefix + name,
|
||||
IsDirectory = false,
|
||||
DownloadUrl = dl,
|
||||
Size = size,
|
||||
Sha = sha
|
||||
});
|
||||
}
|
||||
|
||||
private static bool IsIgnoredDir(string name) =>
|
||||
name is "src" or "bin" or "obj" or "node_modules" or ".git" or ".vs"
|
||||
or ".idea" or ".vscode";
|
||||
|
||||
// ---------------------------------------------------------------- 下载
|
||||
|
||||
public async Task<byte[]> DownloadAsync(RepoEntry entry, CancellationToken ct)
|
||||
{
|
||||
// 优先用 API 提供的 download_url;没有就按 raw 规约拼
|
||||
var url = entry.DownloadUrl;
|
||||
if (string.IsNullOrWhiteSpace(url))
|
||||
url = _preset.RawUrl(entry.Path);
|
||||
|
||||
return await Http.GetByteArrayAsync(url, ct);
|
||||
}
|
||||
|
||||
public async Task<byte[]?> DownloadPackageAsync(RepoPackage package, CancellationToken ct)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(package.Url)) return null;
|
||||
try { return await Http.GetByteArrayAsync(package.Url, ct); }
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.Error.WriteLine($"[gitea] 下载更新包失败: {ex.Message}");
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
using System.Text.Encodings.Web;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace GC.Services;
|
||||
|
||||
public static class Json
|
||||
{
|
||||
public static readonly JsonSerializerOptions Options = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true,
|
||||
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
|
||||
WriteIndented = true,
|
||||
Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
|
||||
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
|
||||
AllowTrailingCommas = true,
|
||||
ReadCommentHandling = JsonCommentHandling.Skip
|
||||
};
|
||||
|
||||
public static T? Read<T>(string path)
|
||||
{
|
||||
if (!System.IO.File.Exists(path)) return default;
|
||||
return JsonSerializer.Deserialize<T>(System.IO.File.ReadAllText(path), Options);
|
||||
}
|
||||
|
||||
public static void Write<T>(string path, T value)
|
||||
{
|
||||
var dir = System.IO.Path.GetDirectoryName(path);
|
||||
if (!string.IsNullOrEmpty(dir)) System.IO.Directory.CreateDirectory(dir);
|
||||
var tmp = path + ".tmp";
|
||||
System.IO.File.WriteAllText(tmp, JsonSerializer.Serialize(value, Options));
|
||||
System.IO.File.Move(tmp, path, true);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
using Avalonia;
|
||||
using Avalonia.Controls;
|
||||
using Avalonia.Controls.ApplicationLifetimes;
|
||||
using Avalonia.Threading;
|
||||
using GC.Views;
|
||||
|
||||
namespace GC.Services;
|
||||
|
||||
/// <summary>
|
||||
/// 启动器更新的完整交互流程(「检查更新」与「重新下载启动器」共用):
|
||||
/// 1. 关闭主窗口与所有模型窗口;
|
||||
/// 2. 弹出圆角进度窗;
|
||||
/// 3. 下载最新版到当前目录(与旧版并列);
|
||||
/// 4. 安排替换脚本、关进度窗、退出进程。
|
||||
/// 失败时恢复主窗口,继续使用当前版本。
|
||||
/// </summary>
|
||||
public static class LauncherUpdateFlow
|
||||
{
|
||||
private static bool _running;
|
||||
public static bool IsRunning => _running;
|
||||
|
||||
public static async Task RunAsync(AppServices services, string title)
|
||||
{
|
||||
if (_running) return;
|
||||
_running = true;
|
||||
|
||||
var desktop = Application.Current?.ApplicationLifetime
|
||||
as IClassicDesktopStyleApplicationLifetime;
|
||||
var mainWindow = desktop?.MainWindow;
|
||||
var progressWindow = new UpdaterWindow(title);
|
||||
|
||||
try
|
||||
{
|
||||
// 1. 关闭所有窗口
|
||||
if (desktop != null) desktop.MainWindow = null;
|
||||
try { mainWindow?.Close(); } catch { }
|
||||
foreach (var w in OpenWindows().ToList())
|
||||
{
|
||||
try { w.Close(); } catch { }
|
||||
}
|
||||
|
||||
// 2. 进度窗
|
||||
progressWindow.Show();
|
||||
progressWindow.Report(0, "准备更新…");
|
||||
await Dispatcher.UIThread.InvokeAsync(() => { }, DispatcherPriority.Render);
|
||||
|
||||
// 3. 下载
|
||||
var progress = new Progress<UpdateProgressInfo>(p =>
|
||||
progressWindow.Report(p.Value, p.Stage));
|
||||
|
||||
var result = await LauncherUpdater.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 = LauncherUpdater.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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,643 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.IO.Compression;
|
||||
using System.Linq;
|
||||
using System.Security.Cryptography;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace GC.Services;
|
||||
|
||||
// ===========================================================================
|
||||
// 启动器更新模块(唯一实现)
|
||||
//
|
||||
// 需求(按用户):
|
||||
// · 只认 GitCode Release 的 latest 版本号(tag),文件名格式:
|
||||
// GC-<版本>-<系统>-<架构>.exe / .app
|
||||
// 例 GC-1.0.3-win-amd64.exe / GC-1.0.3-mac-arm64.app
|
||||
// · 当前运行版本与 latest 不同 => 提示更新;相同 => 无需更新
|
||||
// · 下载的新版解压到「当前运行目录」,与旧版并列;.GC 完全不动
|
||||
// · 更新完成后:删除同系统同架构、版本号 != latest 的其它 GC-* 文件;
|
||||
// 异系统 / 异架构的文件一律不碰
|
||||
// · 一切落盘内容(脚本、标记)只用相对路径,绝不写绝对路径
|
||||
// ===========================================================================
|
||||
|
||||
public sealed class UpdateProgressInfo
|
||||
{
|
||||
public double Value { get; init; }
|
||||
public string Stage { get; init; } = "";
|
||||
}
|
||||
|
||||
public enum UpdateRunState { UpToDate, Ready, Failed }
|
||||
|
||||
public sealed class UpdateRunResult
|
||||
{
|
||||
public UpdateRunState State { get; init; }
|
||||
public string Version { get; init; } = "";
|
||||
public string Message { get; init; } = "";
|
||||
public string? PackageName { get; init; }
|
||||
public string? NewAppPath { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>下载 / 检查 / 应用启动器更新的唯一入口。</summary>
|
||||
public static class LauncherUpdater
|
||||
{
|
||||
/// <summary>当前运行程序的版本号(来自程序集)。</summary>
|
||||
public static string RunningVersion => UpdateService.CurrentLauncherVersion;
|
||||
|
||||
/// <summary>当前 RID,如 osx-arm64。</summary>
|
||||
public static string CurrentRid => UpdateService.CurrentRid;
|
||||
|
||||
/// <summary>文件名里用的「系统-架构」标签,如 mac-arm64 / win-amd64。</summary>
|
||||
public static string PlatformLabel => CurrentRid switch
|
||||
{
|
||||
"win-x64" => "win-amd64",
|
||||
"win-arm64" => "win-arm64",
|
||||
"osx-arm64" => "mac-arm64",
|
||||
"osx-x64" => "mac-x64",
|
||||
"linux-x64" => "linux-amd64",
|
||||
_ => CurrentRid
|
||||
};
|
||||
|
||||
// ---------------------------------------------------------------- 检查
|
||||
|
||||
/// <summary>
|
||||
/// 检查 Release latest 版本。返回 latest 版本号;若与当前运行版本相同返回 null。
|
||||
/// 只比版本号,不比 sha256。
|
||||
/// </summary>
|
||||
/// <summary>
|
||||
/// 检查启动器新版本:**两个源(Xhmcl / GitCode)的 Release 都要查**,
|
||||
/// 取版本号最高的那个作为最新版。任何一个源失败不影响另一个。
|
||||
/// </summary>
|
||||
public static async Task<string?> CheckAsync(CancellationToken ct = default)
|
||||
=> await CheckAllAsync(null, ct);
|
||||
|
||||
/// <summary>兼容旧调用:优先用给定 remote,同时仍会比对另一个源。</summary>
|
||||
public static async Task<string?> CheckAsync(IModelRemote remote, CancellationToken ct = default)
|
||||
=> await CheckAllAsync(remote, ct);
|
||||
|
||||
private static async Task<string?> CheckAllAsync(IModelRemote? preferred, CancellationToken ct)
|
||||
{
|
||||
var candidates = new List<(string Source, string Version)>();
|
||||
|
||||
foreach (var preset in SourcePreset.All)
|
||||
{
|
||||
try
|
||||
{
|
||||
// 优先复用调用方已建好的 remote(避免重复建实例)
|
||||
var remote = preferred != null &&
|
||||
SourcePreset.Detect(preferred.DisplayName).Id == preset.Id
|
||||
? preferred
|
||||
: SourceSelector.CreateRemote(preset);
|
||||
|
||||
var version = await remote.GetVersionAsync(ct);
|
||||
var v = (version?.Launcher.Version ?? "").Trim();
|
||||
if (v.Length == 0)
|
||||
{
|
||||
Console.WriteLine($"[update] {preset.Name}: 没有版本信息(可能还没发 Release)");
|
||||
continue;
|
||||
}
|
||||
Console.WriteLine($"[update] {preset.Name}: {v}");
|
||||
candidates.Add((preset.Name, v));
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.Error.WriteLine($"[update] {preset.Name} 检查失败: {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
if (candidates.Count == 0) return null;
|
||||
|
||||
// 取版本号最高的(第 7 项)
|
||||
var best = candidates.OrderByDescending(c => VersionUtil.Parse(c.Version)).First();
|
||||
Console.WriteLine($"[update] 最新版:{best.Version}(来自 {best.Source})");
|
||||
|
||||
var cmp = VersionUtil.Compare(best.Version, RunningVersion);
|
||||
|
||||
// 远端版本更新 → 提示更新
|
||||
if (cmp > 0)
|
||||
{
|
||||
Console.WriteLine($"[update] 远端 {best.Version} > 本地 {RunningVersion},提示更新");
|
||||
return best.Version;
|
||||
}
|
||||
|
||||
// 远端版本更旧 → 不提示
|
||||
if (cmp < 0)
|
||||
{
|
||||
Console.WriteLine($"[update] 远端 {best.Version} < 本地 {RunningVersion},不提示");
|
||||
return null;
|
||||
}
|
||||
|
||||
// 版本号相同:比对当前程序的 sha256 与 Release 包
|
||||
// 相符 → 视为最新,不提示
|
||||
// 不相符 → 说明是重新编译的同版本程序,必须提示下载
|
||||
var same = await SameFingerprintAsync(best.Source, best.Version, ct);
|
||||
if (same == null)
|
||||
{
|
||||
Console.WriteLine("[update] 版本相同但无法比对 sha256,按最新处理");
|
||||
return null;
|
||||
}
|
||||
if (same.Value)
|
||||
{
|
||||
Console.WriteLine("[update] 版本相同且 sha256 一致,已是最新");
|
||||
return null;
|
||||
}
|
||||
|
||||
// 版本相同但指纹不同:是自行编译的构建,不提示更新
|
||||
Console.WriteLine("[update] 版本相同但 sha256 不一致,不提示更新");
|
||||
return null;
|
||||
}
|
||||
/// <summary>
|
||||
/// 比对「当前运行程序」与「Release 平台包」的 sha256。
|
||||
/// 返回 true=一致(确属同一份构建)、false=不一致(需重新下载)、null=无法比对。
|
||||
/// </summary>
|
||||
private static async Task<bool?> SameFingerprintAsync(string sourceName, string version,
|
||||
CancellationToken ct)
|
||||
{
|
||||
try
|
||||
{
|
||||
var preset = SourcePreset.All.FirstOrDefault(p =>
|
||||
string.Equals(p.Name, sourceName, StringComparison.OrdinalIgnoreCase));
|
||||
if (preset == null) return null;
|
||||
|
||||
var rid = CurrentRid;
|
||||
Console.WriteLine($"[update] 抓取 {preset.Name} 的 {rid} 发布包用于比对…");
|
||||
|
||||
// 定位进程对应的可执行文件 / .app
|
||||
var self = Environment.ProcessPath;
|
||||
if (string.IsNullOrWhiteSpace(self)) return null;
|
||||
var selfPath = self!;
|
||||
// 单文件 / dotnet 宿主时退回到程序集位置
|
||||
if (Path.GetFileNameWithoutExtension(selfPath).Equals("dotnet", StringComparison.OrdinalIgnoreCase))
|
||||
selfPath = typeof(LauncherUpdater).Assembly.Location;
|
||||
|
||||
var selfHash = await HashFileAsync(selfPath, ct);
|
||||
Console.WriteLine($"[update] 本地程序 sha256 = {selfHash[..16]}…");
|
||||
|
||||
// 下载 Release 对应平台包,取包内主程序再算
|
||||
var remote = SourceSelector.CreateRemote(preset);
|
||||
var v = await remote.GetVersionAsync(ct);
|
||||
if (v == null || !v.Launcher.Packages.TryGetValue(rid, out var pkg) || pkg == null)
|
||||
return null;
|
||||
|
||||
var bytes = await remote.DownloadPackageAsync(pkg, ct);
|
||||
if (bytes == null || bytes.Length == 0) return null;
|
||||
|
||||
var remoteHash = await HashZipPayloadAsync(bytes, ct);
|
||||
if (remoteHash == null) return null;
|
||||
Console.WriteLine($"[update] 远端包 sha256 = {remoteHash[..16]}…");
|
||||
|
||||
return string.Equals(selfHash, remoteHash, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.WriteLine($"[update] sha256 比对失败: {ex.Message}");
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static async Task<string> HashFileAsync(string path, CancellationToken ct)
|
||||
{
|
||||
await using var fs = File.OpenRead(path);
|
||||
var hash = await System.Security.Cryptography.SHA256.HashDataAsync(fs, ct);
|
||||
return Convert.ToHexString(hash);
|
||||
}
|
||||
|
||||
/// <summary>从发布包(zip)里取出主程序并算 sha256。</summary>
|
||||
private static async Task<string?> HashZipPayloadAsync(byte[] zip, CancellationToken ct)
|
||||
{
|
||||
try
|
||||
{
|
||||
using var ms = new MemoryStream(zip);
|
||||
using var archive = new System.IO.Compression.ZipArchive(ms, System.IO.Compression.ZipArchiveMode.Read);
|
||||
// 找主程序:app 内的可执行文件 / GC.dll / 单文件 exe
|
||||
var entry = archive.Entries.FirstOrDefault(e =>
|
||||
e.Name.Equals("GC.dll", StringComparison.OrdinalIgnoreCase))
|
||||
?? archive.Entries.FirstOrDefault(e =>
|
||||
e.Name.Equals("GC", StringComparison.OrdinalIgnoreCase))
|
||||
?? archive.Entries.FirstOrDefault(e =>
|
||||
e.Name.EndsWith(".dll", StringComparison.OrdinalIgnoreCase) &&
|
||||
e.Name.StartsWith("GC", StringComparison.OrdinalIgnoreCase));
|
||||
if (entry == null) return null;
|
||||
|
||||
await using var es = entry.Open();
|
||||
using var buf = new MemoryStream();
|
||||
await es.CopyToAsync(buf, ct);
|
||||
var hash = System.Security.Cryptography.SHA256.HashData(buf.ToArray());
|
||||
return Convert.ToHexString(hash);
|
||||
}
|
||||
catch { return null; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 遍历所有源的 Release,取**版本号最高且包含本平台发布包**的那个。
|
||||
/// 某个源没有 Release(返回 null)时自动跳过。
|
||||
/// </summary>
|
||||
private static async Task<(RepoVersion Version, IModelRemote Remote)?> GetBestReleaseAsync(
|
||||
IModelRemote fallback, CancellationToken ct)
|
||||
{
|
||||
var rid = CurrentRid;
|
||||
var found = new List<(string Source, RepoVersion Version, IModelRemote Remote)>();
|
||||
|
||||
foreach (var preset in SourcePreset.All)
|
||||
{
|
||||
try
|
||||
{
|
||||
var remote = SourceSelector.CreateRemote(preset);
|
||||
var v = await remote.GetVersionAsync(ct);
|
||||
if (v == null)
|
||||
{
|
||||
Console.WriteLine($"[update] {preset.Name}: 无 Release");
|
||||
continue;
|
||||
}
|
||||
if (string.IsNullOrWhiteSpace(v.Launcher.Version) || v.Launcher.Packages.Count == 0)
|
||||
{
|
||||
Console.WriteLine($"[update] {preset.Name}: 没有可用的启动器发布包");
|
||||
continue;
|
||||
}
|
||||
var hasPkg = v.Launcher.Packages.ContainsKey(rid) ||
|
||||
v.Launcher.Packages.ContainsKey("default");
|
||||
if (!hasPkg)
|
||||
{
|
||||
Console.WriteLine($"[update] {preset.Name}: v{v.Launcher.Version} 缺少 {rid} 发布包");
|
||||
continue;
|
||||
}
|
||||
Console.WriteLine($"[update] {preset.Name}: v{v.Launcher.Version} 可用");
|
||||
found.Add((preset.Name, v, remote));
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.Error.WriteLine($"[update] {preset.Name} 读取失败: {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
if (found.Count == 0) return null;
|
||||
|
||||
var best = found.OrderByDescending(f => VersionUtil.Parse(f.Version.Launcher.Version)).First();
|
||||
Console.WriteLine($"[update] 选中最新的可用发布包:v{best.Version.Launcher.Version}({best.Source})");
|
||||
return (best.Version, best.Remote);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- 下载
|
||||
|
||||
/// <summary>
|
||||
/// 下载 latest 版本到当前运行目录(与旧版并列)。
|
||||
/// 返回新版包名,供后续替换脚本使用。
|
||||
/// </summary>
|
||||
public static async Task<UpdateRunResult> DownloadAsync(
|
||||
AppPaths paths, IModelRemote remote,
|
||||
IProgress<UpdateProgressInfo>? progress = null,
|
||||
CancellationToken ct = default)
|
||||
{
|
||||
try
|
||||
{
|
||||
progress?.Report(new UpdateProgressInfo { Value = 0.05, Stage = "正在读取最新版本" });
|
||||
|
||||
// 两个源都问一遍:某个源没发 Release 时自动换另一个,
|
||||
// 与「检查更新」保持同一套规则,避免检查通过、下载却报无法读取。
|
||||
var version = await remote.GetVersionAsync(ct);
|
||||
|
||||
// 当前源没有可用的启动器版本(没发 Release / 版本号为空)→ 换另一个源。
|
||||
// 注意:模型清单可能仍然有效,但启动器升级必须有 Release。
|
||||
var hasUsable = version != null &&
|
||||
!string.IsNullOrWhiteSpace(version.Launcher.Version) &&
|
||||
version.Launcher.Packages.Count > 0;
|
||||
|
||||
if (!hasUsable)
|
||||
{
|
||||
var tried = SourcePreset.Find(remote.SourceId)?.Name ?? remote.DisplayName;
|
||||
Console.WriteLine($"[update] {tried} 没有可用的启动器发布包,换另一个源");
|
||||
var pick = await GetBestReleaseAsync(remote, ct);
|
||||
if (pick == null) return Fail("两个源都没有可用的 Release 发布包");
|
||||
version = pick.Value.Version;
|
||||
remote = pick.Value.Remote; // 后续下载必须用这个源的 remote
|
||||
}
|
||||
|
||||
var latest = (version!.Launcher.Version ?? "").Trim();
|
||||
var rid = CurrentRid;
|
||||
if (!version.Launcher.Packages.TryGetValue(rid, out var pkg) &&
|
||||
!version.Launcher.Packages.TryGetValue("default", out pkg))
|
||||
return Fail($"该平台({rid})没有对应发布包");
|
||||
|
||||
progress?.Report(new UpdateProgressInfo { Value = 0.20, Stage = $"正在下载 v{latest}" });
|
||||
|
||||
var bytes = await remote.DownloadPackageAsync(pkg!, ct);
|
||||
if (bytes == null || bytes.Length == 0) return Fail("下载失败:发布包为空");
|
||||
|
||||
// sha256 校验(Release 提供时)
|
||||
if (!string.IsNullOrWhiteSpace(pkg!.Sha256))
|
||||
{
|
||||
var actual = Convert.ToHexString(SHA256.HashData(bytes)).ToLowerInvariant();
|
||||
if (!string.Equals(actual, pkg.Sha256!.Trim(), StringComparison.OrdinalIgnoreCase))
|
||||
return Fail("下载文件校验失败(sha256 不符)");
|
||||
}
|
||||
|
||||
progress?.Report(new UpdateProgressInfo { Value = 0.60, Stage = "正在解压到当前目录" });
|
||||
|
||||
// 解压到临时中转目录,再搬到当前运行目录
|
||||
var installDir = paths.InstallDirectory;
|
||||
Directory.CreateDirectory(installDir);
|
||||
var staging = Path.Combine(paths.CacheRoot, "launcher-staging");
|
||||
if (Directory.Exists(staging)) Directory.Delete(staging, true);
|
||||
Directory.CreateDirectory(staging);
|
||||
|
||||
var zip = Path.Combine(paths.CacheRoot, "launcher-" + Safe(latest) + ".zip");
|
||||
await File.WriteAllBytesAsync(zip, bytes, ct);
|
||||
try { ZipSafety.ExtractToDirectory(zip, staging); }
|
||||
finally { try { File.Delete(zip); } catch { } }
|
||||
|
||||
// 只展平「单个非 .app 顶层目录」的 zip
|
||||
FlattenStaging(staging);
|
||||
|
||||
progress?.Report(new UpdateProgressInfo { Value = 0.80, Stage = "正在安装新版本" });
|
||||
|
||||
var packageName = MoveToInstallDir(staging, installDir, latest);
|
||||
try { Directory.Delete(staging, true); } catch { }
|
||||
if (packageName == null) return Fail("解压结果里没有找到新版启动器");
|
||||
|
||||
// 写标记(纯文本,脚本读它):只含相对信息,无绝对路径
|
||||
Directory.CreateDirectory(paths.UpdateRoot);
|
||||
File.WriteAllText(Path.Combine(paths.UpdateRoot, "update.txt"),
|
||||
$"NAME={packageName}\nVERSION={latest}\nPLATFORM={PlatformLabel}\n");
|
||||
|
||||
progress?.Report(new UpdateProgressInfo { Value = 1.0, Stage = "下载完成" });
|
||||
|
||||
return new UpdateRunResult
|
||||
{
|
||||
State = UpdateRunState.Ready,
|
||||
Version = latest,
|
||||
Message = $"v{latest} 已下载到当前目录",
|
||||
PackageName = packageName,
|
||||
NewAppPath = Path.Combine(installDir, packageName)
|
||||
};
|
||||
}
|
||||
catch (OperationCanceledException) { return Fail("已取消"); }
|
||||
catch (Exception ex) { return Fail(ex.Message); }
|
||||
}
|
||||
|
||||
private static UpdateRunResult Fail(string msg) => new()
|
||||
{
|
||||
State = UpdateRunState.Failed,
|
||||
Message = msg
|
||||
};
|
||||
|
||||
// ---------------------------------------------------------------- 应用(下次启动)
|
||||
|
||||
/// <summary>
|
||||
/// 生成替换脚本并启动。脚本等本进程退出后:
|
||||
/// 启动新版 -> 删除同平台且版本号 != latest 的 GC-* 文件 -> 清理标记。
|
||||
/// 返回 true 表示调用方应立即退出进程。
|
||||
/// </summary>
|
||||
public static bool ScheduleApply(AppPaths paths, string packageName)
|
||||
{
|
||||
var marker = Path.Combine(paths.UpdateRoot, "update.txt");
|
||||
if (!File.Exists(marker)) return false;
|
||||
|
||||
// 安全阀:绝不在源码目录执行替换(防止误删源码)
|
||||
if (File.Exists(Path.Combine(paths.InstallDirectory, "GC.sln")))
|
||||
{
|
||||
Console.Error.WriteLine("源码版:新版已下载,但拒绝在源码目录执行替换");
|
||||
return false;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
var isWin = OperatingSystem.IsWindows();
|
||||
var script = Path.Combine(paths.UpdateRoot, isWin ? "apply.bat" : "apply.sh");
|
||||
var content = isWin ? WindowsScript() : UnixScript();
|
||||
File.WriteAllText(script, content, new System.Text.UTF8Encoding(false));
|
||||
|
||||
if (!isWin)
|
||||
{
|
||||
try
|
||||
{
|
||||
File.SetUnixFileMode(script,
|
||||
UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute);
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
|
||||
var psi = isWin
|
||||
? new System.Diagnostics.ProcessStartInfo("cmd.exe")
|
||||
{ UseShellExecute = false, CreateNoWindow = true }
|
||||
: new System.Diagnostics.ProcessStartInfo("/bin/sh")
|
||||
{ UseShellExecute = false, CreateNoWindow = true };
|
||||
if (isWin) psi.ArgumentList.Add("/c");
|
||||
psi.ArgumentList.Add(script);
|
||||
System.Diagnostics.Process.Start(psi);
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.Error.WriteLine($"启动替换脚本失败: {ex.Message}");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>启动时若有待应用更新,安排脚本并让 Main 直接退出。</summary>
|
||||
public static bool TryApplyPending(AppPaths paths)
|
||||
{
|
||||
if (paths.IsDevelopment) return false;
|
||||
if (Environment.GetEnvironmentVariable("EMS_SELFTEST") == "1") return false;
|
||||
if (Environment.GetEnvironmentVariable("EMS_NO_SELF_UPDATE") == "1") return false;
|
||||
|
||||
var marker = Path.Combine(paths.UpdateRoot, "update.txt");
|
||||
if (!File.Exists(marker)) return false;
|
||||
|
||||
var name = ReadMarker(marker, "NAME");
|
||||
if (string.IsNullOrWhiteSpace(name)) return false;
|
||||
if (!File.Exists(Path.Combine(paths.InstallDirectory, name!)) &&
|
||||
!Directory.Exists(Path.Combine(paths.InstallDirectory, name!)))
|
||||
return false; // 新版本不在了,放弃
|
||||
|
||||
return ScheduleApply(paths, name!);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- 脚本(全部相对路径)
|
||||
|
||||
private static string UnixScript()
|
||||
{
|
||||
var s = new System.Text.StringBuilder();
|
||||
s.AppendLine("#!/bin/sh");
|
||||
s.AppendLine("# script lives in .GC/update/ ; install dir is two levels up");
|
||||
s.AppendLine("HERE=$(CDPATH= cd -- \"$(dirname -- \"$0\")\" && pwd)");
|
||||
s.AppendLine("DST=$(CDPATH= cd -- \"$HERE/../..\" && pwd)");
|
||||
s.AppendLine("MARKER=\"$HERE/update.txt\"");
|
||||
s.AppendLine();
|
||||
s.AppendLine("# read marker");
|
||||
s.AppendLine("NEWNAME=$(sed -n 's/^NAME=//p' \"$MARKER\" 2>/dev/null | head -1)");
|
||||
s.AppendLine("NEWVER=$(sed -n 's/^VERSION=//p' \"$MARKER\" 2>/dev/null | head -1)");
|
||||
s.AppendLine("NEWPLAT=$(sed -n 's/^PLATFORM=//p' \"$MARKER\" 2>/dev/null | head -1)");
|
||||
s.AppendLine("if [ -z \"$NEWNAME\" ] || [ -z \"$NEWVER\" ]; then");
|
||||
s.AppendLine(" echo \"marker incomplete, abort\"; rm -f \"$HERE\"/*.sh 2>/dev/null; exit 1");
|
||||
s.AppendLine("fi");
|
||||
s.AppendLine("NEW=\"$DST/$NEWNAME\"");
|
||||
s.AppendLine("if [ ! -e \"$NEW\" ]; then");
|
||||
s.AppendLine(" echo \"new package missing, abort\"; rm -f \"$HERE\"/*.sh 2>/dev/null; exit 1");
|
||||
s.AppendLine("fi");
|
||||
s.AppendLine();
|
||||
s.AppendLine("# wait for old process to exit (this script is started by it)");
|
||||
s.AppendLine("sleep 2");
|
||||
s.AppendLine();
|
||||
s.AppendLine("# launch new version first");
|
||||
s.AppendLine("if [ -d \"$NEW\" ]; then open \"$NEW\" 2>/dev/null &");
|
||||
s.AppendLine("elif [ -x \"$NEW\" ]; then \"$NEW\" >/dev/null 2>&1 &");
|
||||
s.AppendLine("fi");
|
||||
s.AppendLine();
|
||||
s.AppendLine("# delete old GC-* files: SAME platform only, version != latest");
|
||||
s.AppendLine("# files of OTHER platforms are NEVER touched");
|
||||
s.AppendLine("for item in \"$DST\"/GC-*.app \"$DST\"/GC-*.exe; do");
|
||||
s.AppendLine(" [ -e \"$item\" ] || continue");
|
||||
s.AppendLine(" [ \"$item\" = \"$NEW\" ] && continue");
|
||||
s.AppendLine(" base=$(basename \"$item\")");
|
||||
s.AppendLine(" stem=${base#GC-}");
|
||||
s.AppendLine(" case \"$base\" in");
|
||||
s.AppendLine(" *.app) stem=${stem%.app} ;;");
|
||||
s.AppendLine(" *.exe) stem=${stem%.exe} ;;");
|
||||
s.AppendLine(" *) continue ;;");
|
||||
s.AppendLine(" esac");
|
||||
s.AppendLine(" ver=${stem%%-*}");
|
||||
s.AppendLine(" rest=${stem#*-}");
|
||||
s.AppendLine(" plat=\"${rest%-*}-${rest##*-}\"");
|
||||
s.AppendLine(" # skip other platforms entirely");
|
||||
s.AppendLine(" [ \"$plat\" != \"$NEWPLAT\" ] && continue");
|
||||
s.AppendLine(" # same platform: keep only latest version");
|
||||
s.AppendLine(" if [ \"$ver\" = \"$NEWVER\" ]; then");
|
||||
s.AppendLine(" echo \"keep: $base\"");
|
||||
s.AppendLine(" else");
|
||||
s.AppendLine(" echo \"remove (version $ver != $NEWVER): $base\"");
|
||||
s.AppendLine(" rm -rf \"$item\" 2>/dev/null");
|
||||
s.AppendLine(" fi");
|
||||
s.AppendLine("done");
|
||||
s.AppendLine();
|
||||
s.AppendLine("rm -f \"$MARKER\"");
|
||||
s.AppendLine("rm -f \"$HERE\"/*.sh 2>/dev/null");
|
||||
return s.ToString();
|
||||
}
|
||||
|
||||
private static string WindowsScript()
|
||||
{
|
||||
var s = new System.Text.StringBuilder();
|
||||
s.AppendLine("@echo off");
|
||||
s.AppendLine("chcp 65001 >nul 2>&1");
|
||||
s.AppendLine("set \"HERE=%~dp0\"");
|
||||
s.AppendLine("set \"DST=%~dp0..\\..\"");
|
||||
s.AppendLine("set \"MARKER=%~dp0update.txt\"");
|
||||
s.AppendLine("timeout /t 2 /nobreak >nul");
|
||||
s.AppendLine();
|
||||
s.AppendLine("set \"NEWNAME=\"");
|
||||
s.AppendLine("set \"NEWVER=\"");
|
||||
s.AppendLine("set \"NEWPLAT=\"");
|
||||
s.AppendLine("for /f \"tokens=2 delims==\" %%A in ('findstr /b \"NAME=\" \"%MARKER%\" 2^>nul') do set \"NEWNAME=%%A\"");
|
||||
s.AppendLine("for /f \"tokens=2 delims==\" %%A in ('findstr /b \"VERSION=\" \"%MARKER%\" 2^>nul') do set \"NEWVER=%%A\"");
|
||||
s.AppendLine("for /f \"tokens=2 delims==\" %%A in ('findstr /b \"PLATFORM=\" \"%MARKER%\" 2^>nul') do set \"NEWPLAT=%%A\"");
|
||||
s.AppendLine("if \"%NEWNAME%\"==\"\" (echo marker incomplete, abort & del /Q \"%~f0\" >nul 2>&1 & exit /b 1)");
|
||||
s.AppendLine("if not exist \"%DST%\\%NEWNAME%\" (echo new package missing, abort & del /Q \"%~f0\" >nul 2>&1 & exit /b 1)");
|
||||
s.AppendLine();
|
||||
s.AppendLine("rem launch new version");
|
||||
s.AppendLine("start \"\" \"%DST%\\%NEWNAME%\"");
|
||||
s.AppendLine();
|
||||
s.AppendLine("rem delete old GC-* files: SAME platform only, version != latest");
|
||||
s.AppendLine("powershell -NoProfile -ExecutionPolicy Bypass -Command \"^");
|
||||
s.AppendLine("$dst='%DST%'; $new='%NEWNAME%'; $ver='%NEWVER%'; $plat='%NEWPLAT%';^");
|
||||
s.AppendLine("Get-ChildItem -LiteralPath $dst -Filter 'GC-*' | ForEach-Object {^");
|
||||
s.AppendLine(" $n=$_.Name; if($n -eq $new){return};^");
|
||||
s.AppendLine(" $m=[regex]::Match($n,'^GC-(.+?)-([^-]+)-([^-]+)\\.(app|exe)$');^");
|
||||
s.AppendLine(" if(-not $m.Success){return};^");
|
||||
s.AppendLine(" $fver=$m.Groups[1].Value; $fplat=$m.Groups[2].Value+'-'+$m.Groups[3].Value;^");
|
||||
s.AppendLine(" if($fplat -ne $plat){return};^");
|
||||
s.AppendLine(" if($fver -eq $ver){ Write-Host \\\"keep: $n\\\" }^");
|
||||
s.AppendLine(" else { Write-Host \\\"remove: $n\\\"; Remove-Item -LiteralPath $_.FullName -Recurse -Force -ErrorAction SilentlyContinue }^");
|
||||
s.AppendLine("}\"");
|
||||
s.AppendLine();
|
||||
s.AppendLine("del /Q \"%MARKER%\" >nul 2>&1");
|
||||
s.AppendLine("del /Q \"%~f0\" >nul 2>&1");
|
||||
return s.ToString();
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- 内部工具
|
||||
|
||||
/// <summary>展平只有一个顶层目录、且不是 .app 的 zip。</summary>
|
||||
private static void FlattenStaging(string dir)
|
||||
{
|
||||
var entries = Directory.GetFileSystemEntries(dir);
|
||||
if (entries.Length != 1 || !Directory.Exists(entries[0])) return;
|
||||
var inner = entries[0];
|
||||
if (Path.GetFileName(inner).EndsWith(".app", StringComparison.OrdinalIgnoreCase)) return;
|
||||
|
||||
var flat = dir + "-flat";
|
||||
if (Directory.Exists(flat)) Directory.Delete(flat, true);
|
||||
Directory.Move(inner, flat);
|
||||
Directory.Delete(dir, true);
|
||||
Directory.Move(flat, dir);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 把 staging 里的新版搬到当前目录,与旧版并列。
|
||||
/// 返回新版包名(GC-<版本>-<平台>.app/.exe)。.GC 绝不覆盖。
|
||||
/// </summary>
|
||||
private static string? MoveToInstallDir(string staging, string installDir, string latest)
|
||||
{
|
||||
try
|
||||
{
|
||||
foreach (var entry in Directory.GetFileSystemEntries(staging))
|
||||
{
|
||||
var name = Path.GetFileName(entry);
|
||||
if (string.Equals(name, ".GC", StringComparison.OrdinalIgnoreCase)) continue;
|
||||
var dest = Path.Combine(installDir, name);
|
||||
|
||||
if (Directory.Exists(dest)) Directory.Delete(dest, true);
|
||||
else if (File.Exists(dest)) File.Delete(dest);
|
||||
|
||||
if (Directory.Exists(entry)) Directory.Move(entry, dest);
|
||||
else File.Move(entry, dest);
|
||||
|
||||
// 保证 .app 里可执行文件可执行
|
||||
if (name.EndsWith(".app", StringComparison.OrdinalIgnoreCase) && Directory.Exists(dest))
|
||||
{
|
||||
var macOs = Path.Combine(dest, "Contents", "MacOS");
|
||||
if (Directory.Exists(macOs))
|
||||
{
|
||||
try
|
||||
{
|
||||
foreach (var f in Directory.GetFiles(macOs, "*", SearchOption.TopDirectoryOnly))
|
||||
{
|
||||
var mode = File.GetUnixFileMode(f);
|
||||
File.SetUnixFileMode(f, mode | UnixFileMode.UserExecute);
|
||||
}
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
return name;
|
||||
}
|
||||
if (name.EndsWith(".exe", StringComparison.OrdinalIgnoreCase)) return name;
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.Error.WriteLine($"安装新版失败: {ex.Message}");
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private static string? ReadMarker(string file, string key)
|
||||
{
|
||||
try
|
||||
{
|
||||
foreach (var line in File.ReadAllLines(file))
|
||||
{
|
||||
if (line.StartsWith(key + "=", StringComparison.Ordinal))
|
||||
return line[(key.Length + 1)..].Trim();
|
||||
}
|
||||
}
|
||||
catch { }
|
||||
return null;
|
||||
}
|
||||
|
||||
private static string Safe(string value)
|
||||
{
|
||||
foreach (var c in Path.GetInvalidFileNameChars()) value = value.Replace(c, '-');
|
||||
return value.Replace('/', '-').Replace(' ', '-');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
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;
|
||||
|
||||
/// <summary>轻量 i18n:键值表 + 运行时切换(所有绑定自动刷新)。</summary>
|
||||
public sealed class L : INotifyPropertyChanged
|
||||
{
|
||||
private static readonly L _instance = new();
|
||||
public static L I => _instance;
|
||||
|
||||
private Dictionary<string, string> _map = new(StringComparer.OrdinalIgnoreCase);
|
||||
private readonly List<WeakReference<LocalizedString>> _watchers = new();
|
||||
|
||||
public string Language { get; private set; } = "zh-CN";
|
||||
public event PropertyChangedEventHandler? PropertyChanged;
|
||||
public event Action? LanguageChanged;
|
||||
|
||||
public static readonly (string Code, string Label)[] Supported =
|
||||
{
|
||||
("zh-CN", "简体中文"),
|
||||
("en", "English")
|
||||
};
|
||||
|
||||
public void Initialize(string? preference)
|
||||
{
|
||||
var code = Resolve(preference);
|
||||
LoadLanguage(code, force: true);
|
||||
}
|
||||
|
||||
public static string Resolve(string? pref)
|
||||
{
|
||||
if (!string.IsNullOrWhiteSpace(pref) && !pref.Equals("auto", StringComparison.OrdinalIgnoreCase))
|
||||
return pref!.StartsWith("en", StringComparison.OrdinalIgnoreCase) ? "en" : "zh-CN";
|
||||
var ui = CultureInfo.CurrentUICulture;
|
||||
return ui.TwoLetterISOLanguageName.Equals("zh", StringComparison.OrdinalIgnoreCase) ? "zh-CN" : "en";
|
||||
}
|
||||
|
||||
public void SetLanguage(string code)
|
||||
{
|
||||
code = Resolve(code);
|
||||
if (code == Language) return;
|
||||
LoadLanguage(code, force: false);
|
||||
}
|
||||
|
||||
private void LoadLanguage(string code, bool force)
|
||||
{
|
||||
var loaded = ReadTable(code) ?? ReadTable("en") ?? new Dictionary<string, string>();
|
||||
if (code != "zh-CN")
|
||||
{
|
||||
// 中文兜底,避免缺键出现空白
|
||||
foreach (var kv in ReadTable("zh-CN") ?? new Dictionary<string, string>())
|
||||
loaded.TryAdd(kv.Key, kv.Value);
|
||||
}
|
||||
_map = loaded;
|
||||
if (!force && code == Language) return;
|
||||
Language = code;
|
||||
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("Item[]"));
|
||||
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Language)));
|
||||
// 顺带清理已回收的弱引用,避免 _watchers 只增不减
|
||||
_watchers.RemoveAll(w => !w.TryGetTarget(out _));
|
||||
foreach (var w in _watchers)
|
||||
if (w.TryGetTarget(out var ls)) ls.Refresh();
|
||||
LanguageChanged?.Invoke();
|
||||
}
|
||||
|
||||
private static Dictionary<string, string>? ReadTable(string code)
|
||||
{
|
||||
try
|
||||
{
|
||||
var uri = new Uri($"avares://GC.Core/Assets/i18n/{code}.json");
|
||||
using var stream = AssetLoader.Open(uri);
|
||||
using var reader = new StreamReader(stream);
|
||||
return JsonSerializer.Deserialize<Dictionary<string, string>>(reader.ReadToEnd(),
|
||||
new JsonSerializerOptions { ReadCommentHandling = JsonCommentHandling.Skip, AllowTrailingCommas = true });
|
||||
}
|
||||
catch
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public string this[string key]
|
||||
{
|
||||
get
|
||||
{
|
||||
if (string.IsNullOrEmpty(key)) return "";
|
||||
return _map.TryGetValue(key, out var v) ? v : key;
|
||||
}
|
||||
}
|
||||
|
||||
public string F(string key, params object?[] args)
|
||||
{
|
||||
var fmt = this[key];
|
||||
try { return string.Format(fmt, args); }
|
||||
catch (FormatException) { return fmt; }
|
||||
}
|
||||
|
||||
public LocalizedString For(string key)
|
||||
{
|
||||
var ls = new LocalizedString(key);
|
||||
_watchers.Add(new WeakReference<LocalizedString>(ls));
|
||||
return ls;
|
||||
}
|
||||
|
||||
/// <summary>按 i18n 字典取值:当前语言 -> 英文 -> zh-CN -> 默认名。</summary>
|
||||
public string Pick(Dictionary<string, string>? dict, string fallback)
|
||||
{
|
||||
if (dict == null || dict.Count == 0) return fallback;
|
||||
if (dict.TryGetValue(Language, out var v) && !string.IsNullOrWhiteSpace(v)) return v;
|
||||
if (Language != "en" && dict.TryGetValue("en", out var en) && !string.IsNullOrWhiteSpace(en)) return en;
|
||||
if (dict.TryGetValue("zh-CN", out var zh) && !string.IsNullOrWhiteSpace(zh)) return zh;
|
||||
foreach (var kv in dict) if (!string.IsNullOrWhiteSpace(kv.Value)) return kv.Value;
|
||||
return fallback;
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class LocalizedString : INotifyPropertyChanged
|
||||
{
|
||||
public string Key { get; }
|
||||
public LocalizedString(string key) => Key = key;
|
||||
public string Value => L.I[Key];
|
||||
public event PropertyChangedEventHandler? PropertyChanged;
|
||||
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) };
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
using System;
|
||||
|
||||
namespace GC.Services;
|
||||
|
||||
/// <summary>
|
||||
/// 启动时运行内存分配(类似启动器的 -Xmx)。
|
||||
/// 启动器只负责把这份预算通过 <c>IModelContext.MemoryBudgetMb</c> 交给模型,
|
||||
/// 具体怎么用(贴图分辨率、缓存大小)由模型自己决定。
|
||||
/// </summary>
|
||||
public sealed class MemoryBudget
|
||||
{
|
||||
public int BudgetMb { get; private set; } = 2048;
|
||||
public long BudgetBytes => (long)BudgetMb * 1024L * 1024L;
|
||||
public long ManagedBytes => System.GC.GetTotalMemory(false);
|
||||
|
||||
public event Action? Changed;
|
||||
|
||||
public void Apply(int mb)
|
||||
{
|
||||
BudgetMb = Math.Clamp(mb, 256, 16384);
|
||||
Changed?.Invoke();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 自动预算:取设备可用物理内存的一部分(约 1/4),
|
||||
/// 夹在 512–8192 MB 之间,低配设备也不会因为预算过大而卡顿。
|
||||
/// </summary>
|
||||
public static int AutoComputeMb()
|
||||
{
|
||||
try
|
||||
{
|
||||
var info = System.GC.GetGCMemoryInfo();
|
||||
var totalMb = info.TotalAvailableMemoryBytes / (1024.0 * 1024.0);
|
||||
if (totalMb > 0)
|
||||
return (int)Math.Clamp(Math.Round(totalMb / 4.0 / 256.0) * 256, 512, 8192);
|
||||
}
|
||||
catch { /* 平台不支持时回退默认值 */ }
|
||||
return 2048;
|
||||
}
|
||||
|
||||
/// <summary>按设置应用:auto 时自动计算,否则用手动值。</summary>
|
||||
public void ApplyAuto(bool auto, int manualMb)
|
||||
=> Apply(auto ? AutoComputeMb() : manualMb);
|
||||
|
||||
/// <summary>内存情况变化(例如模型窗口开关)时刷新展示。</summary>
|
||||
public void Refresh() => Changed?.Invoke();
|
||||
|
||||
public double UsageRatio => BudgetBytes <= 0 ? 0 : Math.Clamp((double)ManagedBytes / BudgetBytes, 0, 1);
|
||||
|
||||
public string UsageText => $"{ModelScanner.HumanSize(ManagedBytes)} / {BudgetMb} MB";
|
||||
}
|
||||
@@ -0,0 +1,237 @@
|
||||
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 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(
|
||||
$"模型契约版本 {factory.ApiVersion} 与启动器 {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;
|
||||
}
|
||||
|
||||
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,88 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using GC.Models;
|
||||
|
||||
namespace GC.Services;
|
||||
|
||||
public static class ModelInstaller
|
||||
{
|
||||
/// <summary>把源里的模型目录复制进本地模型库(先写临时目录再原子替换)。</summary>
|
||||
public static async Task<string> InstallAsync(RemoteModel model, string modelRoot,
|
||||
IProgress<(long Done, long Total)>? progress, CancellationToken ct)
|
||||
{
|
||||
var target = Path.Combine(modelRoot, model.Id);
|
||||
var staging = target + ".installing";
|
||||
if (Directory.Exists(staging)) Directory.Delete(staging, true);
|
||||
Directory.CreateDirectory(staging);
|
||||
|
||||
long total = 0;
|
||||
var files = Directory.GetFiles(model.Directory, "*", SearchOption.AllDirectories);
|
||||
foreach (var file in files)
|
||||
{
|
||||
try { total += new FileInfo(file).Length; } catch { }
|
||||
}
|
||||
|
||||
long done = 0;
|
||||
try
|
||||
{
|
||||
foreach (var file in files)
|
||||
{
|
||||
ct.ThrowIfCancellationRequested();
|
||||
var relative = Path.GetRelativePath(model.Directory, file);
|
||||
// 路径穿越防护:相对路径必须完整落在 staging 目录内
|
||||
var dest = Path.GetFullPath(Path.Combine(staging, relative));
|
||||
var stagingFull = Path.GetFullPath(staging)
|
||||
.TrimEnd(Path.DirectorySeparatorChar) + Path.DirectorySeparatorChar;
|
||||
if (!dest.StartsWith(stagingFull, StringComparison.OrdinalIgnoreCase))
|
||||
throw new InvalidOperationException($"非法的模型文件路径: {relative}");
|
||||
var destDir = Path.GetDirectoryName(dest);
|
||||
if (!string.IsNullOrEmpty(destDir)) Directory.CreateDirectory(destDir);
|
||||
|
||||
await using (var src = File.OpenRead(file))
|
||||
await using (var dst = File.Create(dest))
|
||||
{
|
||||
await src.CopyToAsync(dst, 81920, ct);
|
||||
}
|
||||
long length = 0;
|
||||
try { length = new FileInfo(dest).Length; } catch { }
|
||||
done += length;
|
||||
progress?.Report((done, total <= 0 ? done : total));
|
||||
}
|
||||
|
||||
// 原子替换:先备份旧目录,第二次 Move 失败时完整回滚,绝不把模型库清空
|
||||
var backup = target + ".old";
|
||||
if (Directory.Exists(backup)) Directory.Delete(backup, true);
|
||||
var hasBackup = false;
|
||||
try
|
||||
{
|
||||
if (Directory.Exists(target))
|
||||
{
|
||||
Directory.Move(target, backup);
|
||||
hasBackup = true;
|
||||
}
|
||||
Directory.Move(staging, target);
|
||||
}
|
||||
catch
|
||||
{
|
||||
// 新目录尚未就位时把旧目录还原;staging 由外层 catch 清理
|
||||
if (hasBackup && !Directory.Exists(target) && Directory.Exists(backup))
|
||||
Directory.Move(backup, target);
|
||||
throw;
|
||||
}
|
||||
if (hasBackup)
|
||||
{
|
||||
try { Directory.Delete(backup, true); } catch { /* 占用时留到下次 */ }
|
||||
}
|
||||
|
||||
progress?.Report((total, total));
|
||||
return target;
|
||||
}
|
||||
catch
|
||||
{
|
||||
try { if (Directory.Exists(staging)) Directory.Delete(staging, true); } catch { }
|
||||
throw;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using GC.Models;
|
||||
|
||||
namespace GC.Services;
|
||||
|
||||
/// <summary>
|
||||
/// 本地模型库。启动器只**扫描 / 删除**模型包,不再解析或缓存任何场景数据 ——
|
||||
/// 场景、贴图、界面都由模型自己的程序集负责。
|
||||
/// </summary>
|
||||
public sealed class ModelRepository
|
||||
{
|
||||
private readonly AppPaths _paths;
|
||||
|
||||
public ModelRepository(AppPaths paths) => _paths = paths;
|
||||
|
||||
public event Action? Changed;
|
||||
|
||||
public IReadOnlyList<ModelPackage> Scan()
|
||||
{
|
||||
_paths.WaitForDevelopmentModels();
|
||||
var result = new List<ModelPackage>();
|
||||
foreach (var (manifest, dir) in ModelScanner.Scan(_paths.ModelRoot))
|
||||
{
|
||||
result.Add(new ModelPackage
|
||||
{
|
||||
Manifest = manifest,
|
||||
Directory = dir,
|
||||
SizeBytes = ModelScanner.DirectorySize(dir)
|
||||
});
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
public ModelPackage? Find(string id) => Scan().FirstOrDefault(p => p.Id.Equals(id, StringComparison.OrdinalIgnoreCase));
|
||||
|
||||
public bool Delete(string id)
|
||||
{
|
||||
var package = Find(id);
|
||||
if (package == null) return false;
|
||||
try
|
||||
{
|
||||
Directory.Delete(package.Directory, true);
|
||||
Changed?.Invoke();
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.Error.WriteLine($"删除模型失败: {ex.Message}");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public void NotifyChanged() => Changed?.Invoke();
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using GC.Models;
|
||||
|
||||
namespace GC.Services;
|
||||
|
||||
public static class ModelScanner
|
||||
{
|
||||
/// <summary>扫描模型库:model/<id>/<id>.json + <id>.model/</summary>
|
||||
public static List<(ModelManifest Manifest, string Dir)> Scan(string modelRoot)
|
||||
{
|
||||
var list = new List<(ModelManifest, string)>();
|
||||
if (!Directory.Exists(modelRoot)) return list;
|
||||
|
||||
foreach (var dir in Directory.GetDirectories(modelRoot))
|
||||
{
|
||||
var folder = Path.GetFileName(dir);
|
||||
if (folder.StartsWith(".")) continue;
|
||||
|
||||
var manifestPath = Path.Combine(dir, folder + ".json");
|
||||
if (!File.Exists(manifestPath))
|
||||
{
|
||||
var candidates = Directory.GetFiles(dir, "*.json", SearchOption.TopDirectoryOnly);
|
||||
if (candidates.Length == 0) continue;
|
||||
manifestPath = candidates[0];
|
||||
}
|
||||
|
||||
ModelManifest? manifest;
|
||||
try { manifest = Json.Read<ModelManifest>(manifestPath); }
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.Error.WriteLine($"模型清单解析失败 {manifestPath}: {ex.Message}");
|
||||
continue;
|
||||
}
|
||||
|
||||
if (manifest == null) continue;
|
||||
if (string.IsNullOrWhiteSpace(manifest.Id)) manifest.Id = folder;
|
||||
list.Add((manifest, dir));
|
||||
}
|
||||
|
||||
list.Sort((a, b) => string.Compare(a.Item1.Id, b.Item1.Id, StringComparison.OrdinalIgnoreCase));
|
||||
return list;
|
||||
}
|
||||
|
||||
public static long DirectorySize(string dir)
|
||||
{
|
||||
if (!Directory.Exists(dir)) return 0;
|
||||
long total = 0;
|
||||
try
|
||||
{
|
||||
foreach (var file in Directory.EnumerateFiles(dir, "*", SearchOption.AllDirectories))
|
||||
{
|
||||
try { total += new FileInfo(file).Length; }
|
||||
catch { /* 忽略被占用的文件 */ }
|
||||
}
|
||||
}
|
||||
catch { /* 忽略权限问题 */ }
|
||||
return total;
|
||||
}
|
||||
|
||||
public static string HumanSize(long bytes)
|
||||
{
|
||||
string[] units = { "B", "KB", "MB", "GB" };
|
||||
double value = bytes;
|
||||
var unit = 0;
|
||||
while (value >= 1024 && unit < units.Length - 1) { value /= 1024; unit++; }
|
||||
return unit == 0 ? $"{bytes} B" : $"{value:0.#} {units[unit]}";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,302 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
using System.IO.Compression;
|
||||
using System.Linq;
|
||||
using System.Net.Http;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using GC.Models;
|
||||
|
||||
namespace GC.Services;
|
||||
|
||||
/// <summary>
|
||||
/// 从链接导入模型源。
|
||||
/// 支持:git 仓库地址(GitHub / GitLab / Gitee / 任意 git 地址)、zip 直链、本地目录。
|
||||
/// 仓库里的 model/ 目录就是模型列表;下载后缓存到 cache/sources/<id>。
|
||||
/// </summary>
|
||||
public sealed class ModelSourceClient
|
||||
{
|
||||
private readonly AppPaths _paths;
|
||||
private static readonly HttpClient Http = CreateHttp();
|
||||
|
||||
public ModelSourceClient(AppPaths paths) => _paths = paths;
|
||||
|
||||
private static HttpClient CreateHttp()
|
||||
{
|
||||
var client = new HttpClient { Timeout = TimeSpan.FromMinutes(5) };
|
||||
client.DefaultRequestHeaders.UserAgent.ParseAdd("GC/1.0 (+model-source)");
|
||||
return client;
|
||||
}
|
||||
|
||||
public async Task<SourceIndex> FetchAsync(ModelSource source, bool force, IProgress<string>? log, CancellationToken ct)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(source.Url))
|
||||
return new SourceIndex { SourceId = source.Id, Error = "dl.error.emptyUrl" };
|
||||
|
||||
try
|
||||
{
|
||||
var (root, fromCache) = await ResolveRootAsync(source, force, log, ct);
|
||||
var models = new List<RemoteModel>();
|
||||
foreach (var (manifest, dir) in ModelScanner.Scan(Path.Combine(root, "model")))
|
||||
{
|
||||
models.Add(new RemoteModel
|
||||
{
|
||||
Manifest = manifest,
|
||||
Directory = dir,
|
||||
SizeBytes = ModelScanner.DirectorySize(dir),
|
||||
SourceId = source.Id
|
||||
});
|
||||
}
|
||||
|
||||
return new SourceIndex
|
||||
{
|
||||
SourceId = source.Id,
|
||||
Root = root,
|
||||
Models = models,
|
||||
FromCache = fromCache,
|
||||
ResolvedFrom = root
|
||||
};
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
return new SourceIndex { SourceId = source.Id, Error = "dl.error.canceled" };
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
return new SourceIndex { SourceId = source.Id, Error = ex.Message };
|
||||
}
|
||||
}
|
||||
|
||||
private async Task<(string Root, bool FromCache)> ResolveRootAsync(ModelSource source, bool force,
|
||||
IProgress<string>? log, CancellationToken ct)
|
||||
{
|
||||
var raw = source.Url.Trim();
|
||||
|
||||
// 1) 本地目录(开发模型源最方便)
|
||||
var localPath = raw.StartsWith("file://", StringComparison.OrdinalIgnoreCase)
|
||||
? new Uri(raw).LocalPath
|
||||
: raw;
|
||||
if (Directory.Exists(localPath))
|
||||
{
|
||||
log?.Report("local");
|
||||
return (localPath, true);
|
||||
}
|
||||
|
||||
var cacheDir = Path.Combine(_paths.CacheRoot, "sources", source.Id);
|
||||
if (!force && Directory.Exists(Path.Combine(cacheDir, "model")))
|
||||
{
|
||||
log?.Report("cache");
|
||||
return (cacheDir, true);
|
||||
}
|
||||
|
||||
if (Directory.Exists(cacheDir)) Directory.Delete(cacheDir, true);
|
||||
Directory.CreateDirectory(cacheDir);
|
||||
|
||||
// 2) zip 直链 / 托管平台归档
|
||||
foreach (var url in ArchiveCandidates(raw, source.Branch))
|
||||
{
|
||||
ct.ThrowIfCancellationRequested();
|
||||
try
|
||||
{
|
||||
log?.Report("zip:" + url);
|
||||
await DownloadZipAsync(url, cacheDir, ct);
|
||||
if (Directory.Exists(Path.Combine(cacheDir, "model")))
|
||||
return (cacheDir, false);
|
||||
}
|
||||
catch (OperationCanceledException) { throw; }
|
||||
catch (Exception ex)
|
||||
{
|
||||
log?.Report("zip-failed:" + ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
// 3) git clone(需要本机安装 git)
|
||||
log?.Report("git");
|
||||
if (await TryGitCloneAsync(raw, cacheDir, source.Branch, ct))
|
||||
return (cacheDir, false);
|
||||
|
||||
throw new InvalidOperationException("dl.error.unreachable");
|
||||
}
|
||||
|
||||
private static IEnumerable<string> ArchiveCandidates(string url, string? branch)
|
||||
{
|
||||
if (url.EndsWith(".zip", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
yield return url;
|
||||
yield break;
|
||||
}
|
||||
|
||||
if (!Uri.TryCreate(url, UriKind.Absolute, out var uri)) yield break;
|
||||
var segments = uri.AbsolutePath.Trim('/').Split('/', StringSplitOptions.RemoveEmptyEntries);
|
||||
if (segments.Length < 2) yield break;
|
||||
|
||||
var owner = segments[0];
|
||||
var repo = segments[1].EndsWith(".git", StringComparison.OrdinalIgnoreCase)
|
||||
? segments[1][..^4]
|
||||
: segments[1];
|
||||
var host = uri.Host.ToLowerInvariant();
|
||||
|
||||
var branches = new List<string>();
|
||||
if (!string.IsNullOrWhiteSpace(branch)) branches.Add(branch!);
|
||||
else if (host.Contains("gitee")) { branches.Add("master"); branches.Add("main"); }
|
||||
else { branches.Add("main"); branches.Add("master"); }
|
||||
|
||||
foreach (var b in branches)
|
||||
{
|
||||
if (host.Contains("github.com"))
|
||||
yield return $"https://codeload.github.com/{owner}/{repo}/zip/refs/heads/{b}";
|
||||
else if (host.Contains("gitlab"))
|
||||
yield return $"https://gitlab.com/{owner}/{repo}/-/archive/{b}/{repo}-{b}.zip";
|
||||
else if (host.Contains("gitee.com"))
|
||||
yield return $"https://gitee.com/{owner}/{repo}/repository/archive/{b}.zip";
|
||||
else
|
||||
yield break;
|
||||
}
|
||||
}
|
||||
|
||||
private async Task DownloadZipAsync(string url, string cacheDir, CancellationToken ct)
|
||||
{
|
||||
var tmpRoot = Path.Combine(_paths.CacheRoot, "tmp", Guid.NewGuid().ToString("N"));
|
||||
Directory.CreateDirectory(tmpRoot);
|
||||
var zipPath = Path.Combine(tmpRoot, "source.zip");
|
||||
try
|
||||
{
|
||||
using (var response = await Http.GetAsync(url, HttpCompletionOption.ResponseHeadersRead, ct))
|
||||
{
|
||||
response.EnsureSuccessStatusCode();
|
||||
await using var input = await response.Content.ReadAsStreamAsync(ct);
|
||||
await using var output = File.Create(zipPath);
|
||||
await input.CopyToAsync(output, 81920, ct);
|
||||
}
|
||||
|
||||
var extractDir = Path.Combine(tmpRoot, "extract");
|
||||
Directory.CreateDirectory(extractDir);
|
||||
ZipSafety.ExtractToDirectory(zipPath, extractDir);
|
||||
|
||||
var root = FindModelRoot(extractDir) ?? extractDir;
|
||||
foreach (var entry in Directory.GetFileSystemEntries(root))
|
||||
{
|
||||
var name = Path.GetFileName(entry);
|
||||
var dest = Path.Combine(cacheDir, name);
|
||||
if (Directory.Exists(dest)) Directory.Delete(dest, true);
|
||||
else if (File.Exists(dest)) File.Delete(dest);
|
||||
if (Directory.Exists(entry)) Directory.Move(entry, dest);
|
||||
else File.Move(entry, dest);
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
try { if (Directory.Exists(tmpRoot)) Directory.Delete(tmpRoot, true); } catch { }
|
||||
}
|
||||
}
|
||||
|
||||
private static string? FindModelRoot(string dir, int depth = 0)
|
||||
{
|
||||
if (Directory.Exists(Path.Combine(dir, "model"))) return dir;
|
||||
if (depth >= 2) return null;
|
||||
foreach (var child in Directory.GetDirectories(dir))
|
||||
{
|
||||
var found = FindModelRoot(child, depth + 1);
|
||||
if (found != null) return found;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private static async Task<bool> TryGitCloneAsync(string url, string cacheDir, string? branch, CancellationToken ct)
|
||||
{
|
||||
if (cacheDir.Length > 0 && Directory.Exists(cacheDir))
|
||||
{
|
||||
foreach (var f in Directory.GetFileSystemEntries(cacheDir))
|
||||
{
|
||||
if (Directory.Exists(f)) Directory.Delete(f, true);
|
||||
else File.Delete(f);
|
||||
}
|
||||
}
|
||||
|
||||
// 只拉取 model/ 目录:整仓 clone 会把 .git / src / dist 一起拖下来
|
||||
// (实测 700MB+),既慢又容易超时,表现就是「读不到模型源」。
|
||||
// 先浅克隆到临时目录,再用 sparse-checkout 只检出 model/。
|
||||
var tmpDir = cacheDir + ".tmp";
|
||||
try
|
||||
{
|
||||
if (Directory.Exists(tmpDir)) Directory.Delete(tmpDir, true);
|
||||
|
||||
// 1) 初始化 + 加远程(比 clone 更快,避免先拉全量)
|
||||
var initArgs = new List<string> { "init", "--quiet", tmpDir };
|
||||
if (!await RunGitAsync(initArgs, ct)) return false;
|
||||
|
||||
var remoteArgs = new List<string> { "-C", tmpDir, "remote", "add", "origin", url };
|
||||
if (!await RunGitAsync(remoteArgs, ct)) return false;
|
||||
|
||||
// 2) 只允许 model 目录参与检出
|
||||
await RunGitAsync(new List<string> { "-C", tmpDir, "config", "core.sparseCheckout", "true" }, ct);
|
||||
var sparseFile = Path.Combine(tmpDir, ".git", "info", "sparse-checkout");
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(sparseFile)!);
|
||||
File.WriteAllText(sparseFile, "model/\n");
|
||||
|
||||
// 3) 浅拉指定分支
|
||||
var branchName = string.IsNullOrWhiteSpace(branch) ? "main" : branch!;
|
||||
var fetchArgs = new List<string>
|
||||
{
|
||||
"-C", tmpDir, "fetch", "--depth", "1", "--filter=blob:none", "origin", branchName
|
||||
};
|
||||
if (!await RunGitAsync(fetchArgs, ct)) return false;
|
||||
|
||||
await RunGitAsync(new List<string> { "-C", tmpDir, "checkout", "FETCH_HEAD" }, ct);
|
||||
|
||||
// 4) 把 model/ 移到缓存根,与原有目录结构一致
|
||||
var modelDir = Path.Combine(tmpDir, "model");
|
||||
if (!Directory.Exists(modelDir))
|
||||
{
|
||||
Console.Error.WriteLine("git sparse-checkout 后未找到 model/ 目录");
|
||||
return false;
|
||||
}
|
||||
|
||||
if (Directory.Exists(cacheDir)) Directory.Delete(cacheDir, true);
|
||||
Directory.CreateDirectory(cacheDir);
|
||||
Directory.Move(modelDir, Path.Combine(cacheDir, "model"));
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.Error.WriteLine($"git 拉取异常: {ex.Message}");
|
||||
return false;
|
||||
}
|
||||
finally
|
||||
{
|
||||
try { if (Directory.Exists(tmpDir)) Directory.Delete(tmpDir, true); } catch { }
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>安静地跑一条 git 命令,返回是否成功。</summary>
|
||||
private static async Task<bool> RunGitAsync(List<string> args, CancellationToken ct)
|
||||
{
|
||||
try
|
||||
{
|
||||
var psi = new ProcessStartInfo("git")
|
||||
{
|
||||
RedirectStandardOutput = true,
|
||||
RedirectStandardError = true,
|
||||
UseShellExecute = false,
|
||||
CreateNoWindow = true
|
||||
};
|
||||
foreach (var a in args) psi.ArgumentList.Add(a);
|
||||
|
||||
using var process = Process.Start(psi);
|
||||
if (process == null) return false;
|
||||
var errTask = process.StandardError.ReadToEndAsync(ct);
|
||||
await process.WaitForExitAsync(ct);
|
||||
var err = await errTask;
|
||||
if (process.ExitCode != 0)
|
||||
Console.Error.WriteLine($"git {string.Join(' ', args)} 失败: {err.Trim()}");
|
||||
return process.ExitCode == 0;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.Error.WriteLine($"git 执行失败: {ex.Message}");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace GC.Services;
|
||||
|
||||
/// <summary>
|
||||
/// GitCode/Gitee v5 releases API 的一条 Release(字段做宽松解析,兼容多种返回格式)。
|
||||
/// </summary>
|
||||
public sealed class ReleaseInfo
|
||||
{
|
||||
public string TagName { get; set; } = "";
|
||||
public string Name { get; set; } = "";
|
||||
public bool Draft { get; set; }
|
||||
public bool Prerelease { get; set; }
|
||||
public string? PublishedAt { get; set; }
|
||||
public List<ReleaseAsset> Assets { get; set; } = new();
|
||||
|
||||
/// <summary>从 tag_name / name 里抽出的版本号(去掉前缀 v、GC- 等)。</summary>
|
||||
public string Version => NormalizeVersion(TagName, Name);
|
||||
|
||||
private static readonly string[] VersionPrefixes =
|
||||
{ "v", "V", "GC-", "gc-", "release-", "Release-" };
|
||||
|
||||
private static readonly string[] PrereleaseTags =
|
||||
{ "alpha", "beta", "rc", "pre", "dev", "snapshot" };
|
||||
|
||||
public static string NormalizeVersion(string tag, string name)
|
||||
{
|
||||
var raw = !string.IsNullOrWhiteSpace(tag) ? tag : name;
|
||||
if (string.IsNullOrWhiteSpace(raw)) return "";
|
||||
raw = raw!.Trim();
|
||||
// "v1.0.1" / "GC-1.0.1" / "release-1.0.1" -> 取第一段像版本号的部分
|
||||
foreach (var prefix in VersionPrefixes)
|
||||
if (raw.StartsWith(prefix, StringComparison.Ordinal)) { raw = raw[prefix.Length..]; break; }
|
||||
// 形如 GC-1.0.1-Win-amd64 时只取版本段;但 2.3.0-beta 这类预发布串要保留完整。
|
||||
// 用「后缀是否常见预发布标签」区分,避免把 "-Win" 误当成预发布。
|
||||
var dash = raw.IndexOf('-');
|
||||
if (dash > 0 && System.Version.TryParse(raw[..dash], out _))
|
||||
{
|
||||
var tail = raw[(dash + 1)..].ToLowerInvariant();
|
||||
var isPrerelease = Array.Exists(PrereleaseTags, p => tail.StartsWith(p, StringComparison.Ordinal));
|
||||
if (!isPrerelease) raw = raw[..dash];
|
||||
}
|
||||
return raw;
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class ReleaseAsset
|
||||
{
|
||||
public string Name { get; set; } = "";
|
||||
public string? BrowserDownloadUrl { get; set; }
|
||||
public string? DownloadUrl { get; set; }
|
||||
public long Size { get; set; }
|
||||
/// <summary>附件类型:GitCode 用 "source" 表示自动生成的源码压缩包,需跳过。</summary>
|
||||
public string? Type { get; set; }
|
||||
|
||||
private string? _sha256;
|
||||
/// <summary>
|
||||
/// 校验值。真实 Release 的 digest 形如 "sha256:899fc1...",
|
||||
/// 这里统一剥掉算法前缀,只留 hex,便于与 SHA256.HashData 结果比较。
|
||||
/// </summary>
|
||||
public string? Sha256
|
||||
{
|
||||
get => _sha256;
|
||||
set
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(value)) { _sha256 = null; return; }
|
||||
var v = value!.Trim();
|
||||
var colon = v.IndexOf(':');
|
||||
if (colon > 0 && v[..colon].Equals("sha256", StringComparison.OrdinalIgnoreCase))
|
||||
v = v[(colon + 1)..];
|
||||
_sha256 = v.Trim();
|
||||
}
|
||||
}
|
||||
|
||||
[JsonIgnore]
|
||||
public string Url => BrowserDownloadUrl ?? DownloadUrl ?? "";
|
||||
|
||||
/// <summary>单文件发布包(.exe 等)不能走解压,需要直接作为 payload 内容。</summary>
|
||||
public bool IsSingleFile
|
||||
{
|
||||
get
|
||||
{
|
||||
var n = Name.ToLowerInvariant();
|
||||
// macOS 的 .app 以 zip 分发(.app 或 .app.zip),内含 .app 目录,需要解压
|
||||
if (n.EndsWith(".app", StringComparison.Ordinal) ||
|
||||
n.EndsWith(".app.zip", StringComparison.Ordinal)) return false;
|
||||
return !n.EndsWith(".zip", StringComparison.Ordinal) &&
|
||||
!n.EndsWith(".tar.gz", StringComparison.Ordinal) &&
|
||||
!n.EndsWith(".tgz", StringComparison.Ordinal);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>解析附件名里的系统/架构,映射到 .NET RID。</summary>
|
||||
/// <returns>如 win-x64 / win-arm64 / osx-arm64;无法识别返回 null。</returns>
|
||||
public string? RidFromName(string fullName)
|
||||
{
|
||||
var n = fullName ?? "";
|
||||
// 统一大小写与分隔符后再判断,兼容 "GC-1.0.1-Win-amd64.zip"
|
||||
var lower = n.ToLowerInvariant().Replace('_', '-');
|
||||
|
||||
bool win = lower.Contains("win") || lower.Contains("windows");
|
||||
bool mac = lower.Contains("osx") || lower.Contains("mac") || lower.Contains("darwin");
|
||||
bool linux = lower.Contains("linux");
|
||||
if (!win && !mac && !linux) return null;
|
||||
|
||||
bool arm64 = lower.Contains("arm64") || lower.Contains("aarch64") || lower.Contains("win-arm");
|
||||
// x86_64 / x86-64 / amd64 / x64 都是 64 位;只有裸 "x86"/"win-x86" 才是 32 位
|
||||
bool is64 = lower.Contains("x64") || lower.Contains("amd64") ||
|
||||
lower.Contains("x86-64") || lower.Contains("x86_64");
|
||||
bool x86 = !is64 && !arm64 &&
|
||||
(lower.Contains("x86") || lower.Contains("win32") || lower.Contains("i386"));
|
||||
// 其余(未显式标注 32 位)一律按 64 位处理,覆盖 "GC-1.0.1-Windows.zip" 这类简写
|
||||
var arch = arm64 ? "arm64" : x86 ? "x86" : "x64";
|
||||
|
||||
if (win) return "win-" + arch;
|
||||
if (mac) return "osx-" + arch;
|
||||
return "linux-" + arch;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using GC.Models;
|
||||
|
||||
namespace GC.Services;
|
||||
|
||||
public sealed class SettingsService
|
||||
{
|
||||
private readonly AppPaths _paths;
|
||||
|
||||
public AppSettings Current { get; private set; } = new();
|
||||
public event Action? Changed;
|
||||
|
||||
public SettingsService(AppPaths paths) => _paths = paths;
|
||||
|
||||
public void Load()
|
||||
{
|
||||
Current = Json.Read<AppSettings>(_paths.SettingsFile) ?? new AppSettings();
|
||||
SeedDefaultSource();
|
||||
if (Current.MemoryMb < 256) Current.MemoryMb = 2048;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 只允许两个内置源:Xhmcl 与 GitCode(同一份仓库的两个镜像)。
|
||||
/// 不再支持用户自定义源 —— 每次加载都把 Sources 规整成这两条,
|
||||
/// 老配置里的自定义源会被清理掉。
|
||||
/// </summary>
|
||||
public const string DefaultSourceId = "gitcode";
|
||||
public const string DefaultSourceUrl = "https://gitcode.com/2509_92447106/GC";
|
||||
|
||||
private void SeedDefaultSource()
|
||||
{
|
||||
var rebuilt = new List<ModelSource>();
|
||||
foreach (var preset in SourcePreset.All)
|
||||
{
|
||||
// 保留用户对「启用/停用」的选择,其余字段以内置定义为准
|
||||
var old = Current.Sources.FirstOrDefault(s =>
|
||||
SourcePreset.Detect(s.Url).Id == preset.Id);
|
||||
rebuilt.Add(new ModelSource
|
||||
{
|
||||
Id = preset.Id,
|
||||
Name = preset.Name,
|
||||
Url = preset.HomeUrl,
|
||||
Enabled = old?.Enabled ?? true,
|
||||
BuiltIn = true
|
||||
});
|
||||
}
|
||||
|
||||
var changed = Current.Sources.Count != rebuilt.Count ||
|
||||
Current.Sources.Any(s => !s.BuiltIn);
|
||||
Current.Sources = rebuilt;
|
||||
if (changed) Save();
|
||||
}
|
||||
|
||||
public void Save()
|
||||
{
|
||||
try
|
||||
{
|
||||
Json.Write(_paths.SettingsFile, Current);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.Error.WriteLine($"保存设置失败: {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
public void Apply(Action<AppSettings> mutate)
|
||||
{
|
||||
mutate(Current);
|
||||
Save();
|
||||
Changed?.Invoke();
|
||||
}
|
||||
|
||||
public void Notify()
|
||||
{
|
||||
Save();
|
||||
Changed?.Invoke();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
|
||||
namespace GC.Services;
|
||||
|
||||
public static class Shell
|
||||
{
|
||||
public static void OpenFolder(string path)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(path)) return;
|
||||
try
|
||||
{
|
||||
if (!Directory.Exists(path)) Directory.CreateDirectory(path);
|
||||
StartWith(path);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.Error.WriteLine($"打开目录失败: {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>用系统默认浏览器打开一个 URL。</summary>
|
||||
public static void OpenUrl(string url)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(url)) return;
|
||||
try
|
||||
{
|
||||
StartWith(url);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.Error.WriteLine($"打开链接失败: {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
private static void StartWith(string argument)
|
||||
{
|
||||
var info = new ProcessStartInfo
|
||||
{
|
||||
FileName = OperatingSystem.IsWindows() ? "explorer.exe"
|
||||
: OperatingSystem.IsMacOS() ? "open"
|
||||
: "xdg-open",
|
||||
UseShellExecute = false
|
||||
};
|
||||
info.ArgumentList.Add(argument);
|
||||
Process.Start(info);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
|
||||
namespace GC.Services;
|
||||
|
||||
/// <summary>
|
||||
/// 内置下载源。只允许这两个,不再支持用户自定义源。
|
||||
///
|
||||
/// 两个源的内容是同一份仓库(同一个 version.json、同一批模型),
|
||||
/// 区别只是**托管在哪台服务器**上;启动时探测两者延迟,取快的那个下载。
|
||||
/// </summary>
|
||||
public sealed class SourcePreset
|
||||
{
|
||||
public string Id { get; init; } = "";
|
||||
public string Name { get; init; } = "";
|
||||
/// <summary>仓库主页(用于展示与打开)。</summary>
|
||||
public string HomeUrl { get; init; } = "";
|
||||
/// <summary>API 根地址(Gitea: /api/v1,GitCode: /api/v5)。</summary>
|
||||
public string ApiBase { get; init; } = "";
|
||||
/// <summary>原始文件下载前缀(用于拼 raw 地址)。</summary>
|
||||
public string RawBase { get; init; } = "";
|
||||
/// <summary>后端类型:gitea / gitcode。</summary>
|
||||
public string Kind { get; init; } = "";
|
||||
public string Owner { get; init; } = "";
|
||||
public string Repo { get; init; } = "";
|
||||
public string Branch { get; init; } = "main";
|
||||
/// <summary>raw 地址风格:gitea 用 raw/branch/{b},gitcode 用 raw/{b}。</summary>
|
||||
public string RawStyle { get; init; } = "branch";
|
||||
|
||||
public string Repository => HomeUrl;
|
||||
|
||||
/// <summary>拼 raw 文件下载地址(两个平台的 URL 结构不同)。</summary>
|
||||
public string RawUrl(string path) => RawStyle == "plain"
|
||||
? $"{RawBase}/{Owner}/{Repo}/raw/{Branch}/{path.TrimStart('/')}"
|
||||
: $"{RawBase}/{Owner}/{Repo}/raw/branch/{Branch}/{path.TrimStart('/')}";
|
||||
|
||||
public static readonly SourcePreset Xhmcl = new()
|
||||
{
|
||||
Id = "xhmcl",
|
||||
Name = "Xhmcl",
|
||||
HomeUrl = "https://git.xhmcl.com/Morris/GC",
|
||||
ApiBase = "https://git.xhmcl.com/api/v1",
|
||||
RawBase = "https://git.xhmcl.com",
|
||||
Kind = "gitea",
|
||||
RawStyle = "branch",
|
||||
Owner = "Morris",
|
||||
Repo = "GC",
|
||||
Branch = "main"
|
||||
};
|
||||
|
||||
public static readonly SourcePreset GitCode = new()
|
||||
{
|
||||
Id = "gitcode",
|
||||
Name = "GitCode",
|
||||
HomeUrl = "https://gitcode.com/2509_92447106/GC",
|
||||
ApiBase = "https://api.gitcode.com/api/v5",
|
||||
RawBase = "https://gitcode.com",
|
||||
Kind = "gitcode",
|
||||
RawStyle = "plain",
|
||||
Owner = "2509_92447106",
|
||||
Repo = "GC",
|
||||
Branch = "main"
|
||||
};
|
||||
|
||||
public static readonly SourcePreset[] All = { Xhmcl, GitCode };
|
||||
|
||||
public static SourcePreset? Find(string? id) =>
|
||||
All.FirstOrDefault(p => string.Equals(p.Id, id, StringComparison.OrdinalIgnoreCase));
|
||||
|
||||
/// <summary>把任意仓库地址映射到这两个内置源之一(用于兼容旧配置)。</summary>
|
||||
public static SourcePreset Detect(string? url)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(url)) return GitCode;
|
||||
var u = url!.ToLowerInvariant();
|
||||
if (u.Contains("xhmcl.com")) return Xhmcl;
|
||||
return GitCode;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.Linq;
|
||||
using System.Net.Http;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace GC.Services;
|
||||
|
||||
/// <summary>
|
||||
/// 双源选择:Xhmcl 与 GitCode 是同一份仓库的两个镜像。
|
||||
///
|
||||
/// 启动更新 / 下载页面 / 检查更新时,先并发探测两边的 version.json 响应时间,
|
||||
/// 取**最快且内容可用**的那个作为本次下载源;探测结果缓存一段时间,
|
||||
/// 避免每次点下载都重新测速。
|
||||
/// </summary>
|
||||
public sealed class SourceSelector
|
||||
{
|
||||
private static readonly HttpClient Http = CreateHttp();
|
||||
|
||||
private static HttpClient CreateHttp()
|
||||
{
|
||||
var c = new HttpClient { Timeout = TimeSpan.FromSeconds(6) };
|
||||
c.DefaultRequestHeaders.UserAgent.ParseAdd("GC-Probe/1.0");
|
||||
return c;
|
||||
}
|
||||
|
||||
private readonly object _lock = new();
|
||||
private SourcePreset? _cached;
|
||||
private DateTime _cachedAt = DateTime.MinValue;
|
||||
private readonly TimeSpan _ttl = TimeSpan.FromMinutes(3);
|
||||
|
||||
/// <summary>最近一次选中的源(未探测时为空)。</summary>
|
||||
public SourcePreset? Current { get { lock (_lock) return _cached; } }
|
||||
|
||||
/// <summary>每个源的探测耗时(毫秒),供界面展示。</summary>
|
||||
public IReadOnlyDictionary<string, long> LastLatency { get; private set; } =
|
||||
new Dictionary<string, long>();
|
||||
|
||||
/// <summary>
|
||||
/// 探测两个源并返回最快的。force=true 时忽略缓存。
|
||||
/// 两个都失败时返回 GitCode(默认源)。
|
||||
/// </summary>
|
||||
public async Task<SourcePreset> PickFastestAsync(bool force = false, CancellationToken ct = default)
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
if (!force && _cached != null && DateTime.UtcNow - _cachedAt < _ttl)
|
||||
return _cached;
|
||||
}
|
||||
|
||||
var probes = SourcePreset.All.Select(async p =>
|
||||
{
|
||||
var sw = Stopwatch.StartNew();
|
||||
var ok = await ProbeAsync(p, ct);
|
||||
sw.Stop();
|
||||
return (Preset: p, Ok: ok, Ms: sw.ElapsedMilliseconds);
|
||||
});
|
||||
|
||||
var results = await Task.WhenAll(probes);
|
||||
|
||||
var latencies = results.ToDictionary(r => r.Preset.Id, r => r.Ms);
|
||||
LastLatency = latencies;
|
||||
|
||||
var usable = results.Where(r => r.Ok).OrderBy(r => r.Ms).ToList();
|
||||
var chosen = usable.Count > 0 ? usable[0].Preset : SourcePreset.GitCode;
|
||||
|
||||
lock (_lock)
|
||||
{
|
||||
_cached = chosen;
|
||||
_cachedAt = DateTime.UtcNow;
|
||||
}
|
||||
|
||||
Console.WriteLine("[selector] 测速:" + string.Join(" ",
|
||||
results.Select(r => $"{r.Preset.Name}={r.Ms}ms{(r.Ok ? "" : "(不可用)")}"))
|
||||
+ $" → 选择 {chosen.Name}");
|
||||
|
||||
return chosen;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 探测:能拿到合法 JSON 才算可用。
|
||||
/// 注意两个平台取文件的方式不同:
|
||||
/// · Gitea(Xhmcl):raw/branch/{b}/{path} 直接返回文件内容
|
||||
/// · GitCode:raw 地址返回的是 HTML 页面,必须走 API(内容为 base64)
|
||||
/// 因此 GitCode 用 api/v5 contents + Accept: application/json 探测。
|
||||
/// </summary>
|
||||
private static async Task<bool> ProbeAsync(SourcePreset preset, CancellationToken ct)
|
||||
{
|
||||
if (preset.Kind == "gitcode")
|
||||
{
|
||||
try
|
||||
{
|
||||
using var cts = CancellationTokenSource.CreateLinkedTokenSource(ct);
|
||||
cts.CancelAfter(TimeSpan.FromSeconds(5));
|
||||
var api = $"{preset.ApiBase}/repos/{preset.Owner}/{preset.Repo}/contents/version.json?ref={preset.Branch}";
|
||||
using var req = new HttpRequestMessage(HttpMethod.Get, api);
|
||||
req.Headers.Accept.ParseAdd("application/json");
|
||||
using var resp = await Http.SendAsync(req, cts.Token);
|
||||
if (!resp.IsSuccessStatusCode) return false;
|
||||
var text = await resp.Content.ReadAsStringAsync(cts.Token);
|
||||
return text.TrimStart().StartsWith('{');
|
||||
}
|
||||
catch { return false; }
|
||||
}
|
||||
|
||||
var urls = new[] { preset.RawUrl("version.json"), preset.RawUrl("model/version.json") };
|
||||
|
||||
foreach (var url in urls)
|
||||
{
|
||||
try
|
||||
{
|
||||
using var cts = CancellationTokenSource.CreateLinkedTokenSource(ct);
|
||||
cts.CancelAfter(TimeSpan.FromSeconds(5));
|
||||
var text = await Http.GetStringAsync(url, cts.Token);
|
||||
if (text.TrimStart().StartsWith('{')) return true;
|
||||
}
|
||||
catch { /* 换下一个地址 */ }
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>为指定源创建对应的 remote 实现。</summary>
|
||||
public static IModelRemote CreateRemote(SourcePreset preset) => preset.Kind switch
|
||||
{
|
||||
"gitea" => new GiteaRemote(preset),
|
||||
_ => new GitCodeReleaseRemote(null, preset.HomeUrl)
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace GC.Services;
|
||||
|
||||
/// <summary>仓库根 version.json:由构建脚本 VersionStamp 自动生成,模型一改版本就变。</summary>
|
||||
public sealed class RepoVersion
|
||||
{
|
||||
public int Schema { get; set; } = 1;
|
||||
public string Generated { get; set; } = "";
|
||||
public string Repository { get; set; } = "";
|
||||
public string Branch { get; set; } = "main";
|
||||
public string ModelDir { get; set; } = "model";
|
||||
public RepoLauncher Launcher { get; set; } = new();
|
||||
public List<RepoModel> Models { get; set; } = new();
|
||||
}
|
||||
|
||||
public sealed class RepoLauncher
|
||||
{
|
||||
public string Version { get; set; } = "1.0.0";
|
||||
/// <summary>启动器源码指纹(自动算,仅展示,不触发升级)。</summary>
|
||||
public string Revision { get; set; } = "";
|
||||
public Dictionary<string, RepoPackage> Packages { get; set; } = new();
|
||||
}
|
||||
|
||||
/// <summary>某个平台的启动器发布包;url 优先,否则用 path 去仓库里解析下载地址。</summary>
|
||||
public sealed class RepoPackage
|
||||
{
|
||||
public string? Url { get; set; }
|
||||
public string? Path { get; set; }
|
||||
public string? Sha256 { get; set; }
|
||||
public long Size { get; set; }
|
||||
/// <summary>Release 附件名(用于判断是 zip 还是单文件 exe / .app.zip)。</summary>
|
||||
public string? AssetName { get; set; }
|
||||
}
|
||||
|
||||
public sealed class RepoModel
|
||||
{
|
||||
public string Id { get; set; } = "";
|
||||
public string Version { get; set; } = "";
|
||||
/// <summary>模型在仓库里的目录,如 model/earth-rotation。</summary>
|
||||
public string Dir { get; set; } = "";
|
||||
}
|
||||
|
||||
/// <summary>远端目录树里的一个条目。</summary>
|
||||
public sealed class RepoEntry
|
||||
{
|
||||
public string Name { get; init; } = "";
|
||||
/// <summary>仓库内完整路径。</summary>
|
||||
public string Path { get; init; } = "";
|
||||
/// <summary>相对所请求根目录的路径,统一用 / 分隔。</summary>
|
||||
public string RelativePath { get; init; } = "";
|
||||
public bool IsDirectory { get; init; }
|
||||
public string? DownloadUrl { get; init; }
|
||||
public long Size { get; init; }
|
||||
public string? Sha { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 远端源抽象:gitcode 是默认实现,本地目录实现用于离线教学与自动化测试。
|
||||
/// </summary>
|
||||
public interface IModelRemote
|
||||
{
|
||||
string DisplayName { get; }
|
||||
|
||||
/// <summary>源标识(xhmcl / gitcode / local),用于判断当前是哪个源。</summary>
|
||||
string SourceId => SourcePreset.Detect(DisplayName).Id;
|
||||
Task<RepoVersion?> GetVersionAsync(CancellationToken ct);
|
||||
Task<IReadOnlyList<RepoEntry>> ListTreeAsync(string rootPath, CancellationToken ct);
|
||||
Task<byte[]> DownloadAsync(RepoEntry entry, CancellationToken ct);
|
||||
Task<byte[]?> DownloadPackageAsync(RepoPackage package, CancellationToken ct);
|
||||
}
|
||||
|
||||
public sealed class UpdateProgress
|
||||
{
|
||||
public double Value { get; init; }
|
||||
public string Message { get; init; } = "";
|
||||
public string? Detail { get; init; }
|
||||
}
|
||||
|
||||
public enum UpdateOutcome
|
||||
{
|
||||
NoChange,
|
||||
Applied,
|
||||
Partial,
|
||||
Unavailable,
|
||||
Disabled
|
||||
}
|
||||
|
||||
public sealed class UpdateResult
|
||||
{
|
||||
public UpdateOutcome Outcome { get; init; }
|
||||
public string Message { get; init; } = "";
|
||||
public int UpdatedModels { get; init; }
|
||||
public List<string> ModelNames { get; init; } = new();
|
||||
public string? LauncherMessage { get; init; }
|
||||
public string? Error { get; init; }
|
||||
}
|
||||
@@ -0,0 +1,335 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.IO.Compression;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Security.Cryptography;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using GC.Models;
|
||||
|
||||
namespace GC.Services;
|
||||
|
||||
/// <summary>
|
||||
/// 模型自动更新:读远端版本清单,把缺失/过期的模型下载到 cache 后原子替换
|
||||
/// .GC/model/<id>,本次启动立即生效。任何失败都保留本地已装模型。
|
||||
/// 启动器更新由 LauncherUpdater / LauncherUpdateFlow 独立负责,不在这里。
|
||||
/// </summary>
|
||||
public sealed class UpdateService
|
||||
{
|
||||
private readonly AppPaths _paths;
|
||||
private readonly SettingsService _settings;
|
||||
private IModelRemote _remote;
|
||||
|
||||
public UpdateService(AppPaths paths, SettingsService settings, IModelRemote remote)
|
||||
{
|
||||
_paths = paths;
|
||||
_settings = settings;
|
||||
_remote = remote;
|
||||
}
|
||||
|
||||
public IModelRemote Remote => _remote;
|
||||
|
||||
/// <summary>换源:测速选出最快的一个后,用它的 remote 覆盖当前实例。</summary>
|
||||
public void UseRemote(IModelRemote remote) => _remote = remote;
|
||||
|
||||
private static string? _versionOverride;
|
||||
|
||||
public static string CurrentLauncherVersion
|
||||
{
|
||||
get
|
||||
{
|
||||
if (!string.IsNullOrWhiteSpace(_versionOverride)) return _versionOverride!;
|
||||
|
||||
// 用**本程序集**的版本,而不是 GetEntryAssembly()。
|
||||
// EntryAssembly 在宿主(dotnet run / 测试宿主 / 单文件解包)下可能指向别的程序,
|
||||
// 读出来会变成 1.0.0,导致「明明是最新版却一直提示有更新」。
|
||||
var asm = typeof(UpdateService).Assembly;
|
||||
var v = asm.GetName().Version;
|
||||
if (v == null || (v.Major == 0 && v.Minor == 0 && v.Build == 0))
|
||||
{
|
||||
// 兜底:读 InformationalVersion(Directory.Build.props 里的 <Version>)
|
||||
var info = asm.GetCustomAttribute<AssemblyInformationalVersionAttribute>()?.InformationalVersion;
|
||||
if (!string.IsNullOrWhiteSpace(info))
|
||||
{
|
||||
var core = info!.Split('+')[0].Trim();
|
||||
if (Version.TryParse(core, out var iv))
|
||||
v = iv;
|
||||
}
|
||||
}
|
||||
if (v == null) return "0.0.0";
|
||||
return $"{Math.Max(0, v.Major)}.{Math.Max(0, v.Minor)}.{Math.Max(0, v.Build)}";
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>测试 / 自检时临时指定版本号。</summary>
|
||||
public static void OverrideLauncherVersion(string? version) => _versionOverride = version;
|
||||
|
||||
public static string CurrentRid
|
||||
{
|
||||
get
|
||||
{
|
||||
var arch = RuntimeInformation.OSArchitecture switch
|
||||
{
|
||||
Architecture.Arm64 => "arm64",
|
||||
Architecture.X86 => "x86",
|
||||
_ => "x64"
|
||||
};
|
||||
if (OperatingSystem.IsWindows()) return "win-" + arch;
|
||||
if (OperatingSystem.IsMacOS()) return "osx-" + arch;
|
||||
if (OperatingSystem.IsLinux()) return "linux-" + arch;
|
||||
return RuntimeInformation.RuntimeIdentifier;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 同步版本(无法测速时用):按设置里的仓库地址映射到内置源。
|
||||
/// 真正带测速的入口是 <see cref="CreateRemoteAsync"/>。
|
||||
/// </summary>
|
||||
public static IModelRemote CreateRemote(AppSettings settings)
|
||||
{
|
||||
if (!string.IsNullOrWhiteSpace(settings.UpdateLocalRoot) &&
|
||||
Directory.Exists(settings.UpdateLocalRoot!))
|
||||
return new DirectoryRemote(settings.UpdateLocalRoot!);
|
||||
return SourceSelector.CreateRemote(SourcePreset.Detect(settings.UpdateRepository));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 异步版本:先探测 Xhmcl / GitCode 两个源,取最快的那个。
|
||||
/// 启动更新、下载页、检查更新统一走这里,保证「用同一个源、同一种下载方式」。
|
||||
/// </summary>
|
||||
public static async Task<IModelRemote> CreateRemoteAsync(AppSettings settings,
|
||||
SourceSelector selector, bool forceProbe = false, CancellationToken ct = default)
|
||||
{
|
||||
if (!string.IsNullOrWhiteSpace(settings.UpdateLocalRoot) &&
|
||||
Directory.Exists(settings.UpdateLocalRoot!))
|
||||
return new DirectoryRemote(settings.UpdateLocalRoot!);
|
||||
|
||||
var preset = await selector.PickFastestAsync(forceProbe, ct);
|
||||
return SourceSelector.CreateRemote(preset);
|
||||
}
|
||||
|
||||
public async Task<UpdateResult> RunAsync(bool force,
|
||||
IProgress<UpdateProgress>? progress, CancellationToken ct = default)
|
||||
{
|
||||
// 开发态的 model/ 里有源码与工程文件,模型自动替换会破坏源码目录,
|
||||
// 因此开发态只做「启动器版本检查」(下载到 .GC/update 暂存,可验证链路),
|
||||
// 跳过模型替换。要用正式流程验证请跑 ./build.sh update-test。
|
||||
var devMode = _paths.IsDevelopment &&
|
||||
Environment.GetEnvironmentVariable("EMS_DEV_UPDATE") != "1";
|
||||
|
||||
if (!force && !_settings.Current.AutoUpdateOnStartup)
|
||||
return new UpdateResult { Outcome = UpdateOutcome.Disabled, Message = L.I["update.disabled"] };
|
||||
|
||||
progress?.Report(new UpdateProgress
|
||||
{
|
||||
Value = 0.02,
|
||||
Message = L.I["update.checking"],
|
||||
Detail = _remote.DisplayName
|
||||
});
|
||||
|
||||
RepoVersion? remote;
|
||||
try
|
||||
{
|
||||
remote = await _remote.GetVersionAsync(ct);
|
||||
}
|
||||
catch (OperationCanceledException) { throw; }
|
||||
catch (Exception ex)
|
||||
{
|
||||
return new UpdateResult
|
||||
{
|
||||
Outcome = UpdateOutcome.Unavailable,
|
||||
Message = L.I["update.offline"],
|
||||
Error = ex.Message
|
||||
};
|
||||
}
|
||||
|
||||
if (remote == null)
|
||||
return new UpdateResult
|
||||
{
|
||||
Outcome = UpdateOutcome.Unavailable,
|
||||
Message = L.I["update.noManifest"]
|
||||
};
|
||||
|
||||
_settings.Current.LastUpdateCheck = DateTime.UtcNow.ToString("O");
|
||||
_settings.Save();
|
||||
|
||||
// 启动器更新由 LauncherUpdater / LauncherUpdateFlow 独立负责,
|
||||
// 这里只做「模型同步到最新版」。
|
||||
string? launcherMessage = null;
|
||||
|
||||
// ---- 同步所有模型到最新版 ----
|
||||
// 开发态跳过:仓库 model/ 里有源码,整体替换会破坏工程目录。
|
||||
var needed = devMode
|
||||
? new List<RepoModel>()
|
||||
: remote.Models.Where(NeedsModel).ToList();
|
||||
var updated = new List<string>();
|
||||
var errors = new List<string>();
|
||||
|
||||
for (var i = 0; i < needed.Count; i++)
|
||||
{
|
||||
var model = needed[i];
|
||||
progress?.Report(new UpdateProgress
|
||||
{
|
||||
Value = 0.05 + 0.72 * i / Math.Max(1, needed.Count),
|
||||
Message = L.I.F("update.downloadingModel", model.Id),
|
||||
Detail = model.Version
|
||||
});
|
||||
try
|
||||
{
|
||||
await InstallModelAsync(model, progress, i, needed.Count, ct);
|
||||
_settings.Current.InstalledModelVersions[model.Id] = model.Version;
|
||||
_settings.Save();
|
||||
updated.Add(model.Id);
|
||||
}
|
||||
catch (OperationCanceledException) { throw; }
|
||||
catch (Exception ex)
|
||||
{
|
||||
errors.Add($"{model.Id}: {ex.Message}");
|
||||
Console.Error.WriteLine($"模型更新失败 {model.Id}: {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
progress?.Report(new UpdateProgress { Value = 1, Message = L.I["update.done"] });
|
||||
|
||||
var outcome = errors.Count > 0
|
||||
? UpdateOutcome.Partial
|
||||
: (updated.Count > 0 || launcherMessage != null)
|
||||
? UpdateOutcome.Applied
|
||||
: UpdateOutcome.NoChange;
|
||||
|
||||
var message = updated.Count > 0
|
||||
? L.I.F("update.applied", updated.Count)
|
||||
: launcherMessage != null
|
||||
? L.I["update.modelsLatest"]
|
||||
: devMode
|
||||
? "开发态:已检查启动器,模型替换已跳过(保护仓库源码)"
|
||||
: L.I["update.noChange"];
|
||||
if (errors.Count > 0) message += L.I.F("update.partial", errors.Count);
|
||||
|
||||
return new UpdateResult
|
||||
{
|
||||
Outcome = outcome,
|
||||
Message = message,
|
||||
UpdatedModels = updated.Count,
|
||||
ModelNames = updated,
|
||||
LauncherMessage = launcherMessage,
|
||||
Error = errors.Count > 0 ? string.Join("; ", errors) : null
|
||||
};
|
||||
}
|
||||
|
||||
private bool NeedsModel(RepoModel model)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(model.Id) || string.IsNullOrWhiteSpace(model.Version)) return false;
|
||||
var dir = Path.Combine(_paths.ModelRoot, model.Id);
|
||||
if (!Directory.Exists(dir)) return true;
|
||||
if (!File.Exists(Path.Combine(dir, model.Id + ".json"))) return true;
|
||||
return !_settings.Current.InstalledModelVersions.TryGetValue(model.Id, out var local) ||
|
||||
!string.Equals(local, model.Version, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
/// <summary>只下载模型清单与模型数据目录,源码 / 文档不进运行目录。</summary>
|
||||
private static bool IsPayload(string id, string relative)
|
||||
{
|
||||
var rel = relative.Replace('\\', '/');
|
||||
// 拒绝任何形式的父目录穿越与绝对路径
|
||||
if (rel.StartsWith('/') || rel.Contains("..", StringComparison.Ordinal)) return false;
|
||||
return rel.Equals(id + ".json", StringComparison.OrdinalIgnoreCase) ||
|
||||
rel.StartsWith(id + ".model/", StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
private async Task InstallModelAsync(RepoModel model, IProgress<UpdateProgress>? progress,
|
||||
int index, int count, CancellationToken ct)
|
||||
{
|
||||
var rootPath = string.IsNullOrWhiteSpace(model.Dir) ? "model/" + model.Id : model.Dir;
|
||||
var entries = await _remote.ListTreeAsync(rootPath, ct);
|
||||
var files = entries.Where(e => !e.IsDirectory && IsPayload(model.Id, e.RelativePath)).ToList();
|
||||
|
||||
if (!files.Any(e => e.RelativePath.Equals(model.Id + ".json", StringComparison.OrdinalIgnoreCase)))
|
||||
throw new InvalidOperationException($"远端缺少模型清单 {model.Id}.json");
|
||||
if (!files.Any(e => e.RelativePath.StartsWith(model.Id + ".model/", StringComparison.OrdinalIgnoreCase)))
|
||||
throw new InvalidOperationException($"远端缺少模型数据 {model.Id}.model/");
|
||||
|
||||
var staging = Path.Combine(_paths.CacheRoot, "models", model.Id + "-" + Safe(model.Version));
|
||||
if (Directory.Exists(staging)) Directory.Delete(staging, true);
|
||||
Directory.CreateDirectory(staging);
|
||||
|
||||
try
|
||||
{
|
||||
var total = files.Sum(f => Math.Max(1L, f.Size));
|
||||
// 并行下载:模型包通常有几十个文件,串行下载会明显拖慢启动。
|
||||
// 并发上限 6,避免被服务端限流;进度用原子计数汇总。
|
||||
long done = 0;
|
||||
var stagingFull = Path.GetFullPath(staging)
|
||||
.TrimEnd(Path.DirectorySeparatorChar) + Path.DirectorySeparatorChar;
|
||||
using var gate = new SemaphoreSlim(6);
|
||||
|
||||
var tasks = files.Select(async entry =>
|
||||
{
|
||||
await gate.WaitAsync(ct);
|
||||
try
|
||||
{
|
||||
ct.ThrowIfCancellationRequested();
|
||||
var bytes = await _remote.DownloadAsync(entry, ct);
|
||||
|
||||
// 路径穿越防护
|
||||
var dest = Path.GetFullPath(Path.Combine(staging,
|
||||
entry.RelativePath.Replace('/', Path.DirectorySeparatorChar)));
|
||||
if (!dest.StartsWith(stagingFull, StringComparison.OrdinalIgnoreCase))
|
||||
throw new InvalidOperationException($"非法的模型文件路径: {entry.RelativePath}");
|
||||
|
||||
var destDir = Path.GetDirectoryName(dest);
|
||||
if (!string.IsNullOrEmpty(destDir)) Directory.CreateDirectory(destDir);
|
||||
await File.WriteAllBytesAsync(dest, bytes, ct);
|
||||
|
||||
var now = Interlocked.Add(ref done, bytes.Length);
|
||||
progress?.Report(new UpdateProgress
|
||||
{
|
||||
Value = 0.05 + 0.72 * (index + Math.Min(1, (double)now / Math.Max(1, total))) / Math.Max(1, count),
|
||||
Message = L.I.F("update.downloadingModel", model.Id),
|
||||
Detail = entry.RelativePath
|
||||
});
|
||||
}
|
||||
finally { gate.Release(); }
|
||||
});
|
||||
|
||||
await Task.WhenAll(tasks);
|
||||
|
||||
// 原子替换:先备份旧目录,成功后再删备份;失败自动回滚
|
||||
Directory.CreateDirectory(_paths.ModelRoot);
|
||||
var target = Path.Combine(_paths.ModelRoot, model.Id);
|
||||
// 双保险:任何情况下都不允许把含 src/ 源码的模型目录整体换掉
|
||||
if (Directory.Exists(Path.Combine(target, "src")))
|
||||
throw new InvalidOperationException($"目标目录含模型源码 src/,拒绝覆盖: {target}");
|
||||
var backup = target + ".old";
|
||||
if (Directory.Exists(backup)) Directory.Delete(backup, true);
|
||||
if (Directory.Exists(target)) Directory.Move(target, backup);
|
||||
try
|
||||
{
|
||||
Directory.Move(staging, target);
|
||||
}
|
||||
catch
|
||||
{
|
||||
if (Directory.Exists(backup) && !Directory.Exists(target)) Directory.Move(backup, target);
|
||||
throw;
|
||||
}
|
||||
if (Directory.Exists(backup))
|
||||
{
|
||||
try { Directory.Delete(backup, true); } catch { /* 占用时留到下次 */ }
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
try { if (Directory.Exists(staging)) Directory.Delete(staging, true); } catch { }
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
private static string Safe(string value)
|
||||
{
|
||||
foreach (var c in Path.GetInvalidFileNameChars()) value = value.Replace(c, '-');
|
||||
return value.Replace('/', '-').Replace(' ', '-');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
using System;
|
||||
using System.Globalization;
|
||||
|
||||
namespace GC.Services;
|
||||
|
||||
/// <summary>
|
||||
/// 版本号工具:Release tag 有 v1.0.6 / GC-1.0.6 / 1.0.6 等写法,
|
||||
/// 统一成可比较的 Version 再排序,挑**版本号最高**的那个。
|
||||
/// </summary>
|
||||
public static class VersionUtil
|
||||
{
|
||||
/// <summary>把 tag 规整成 "1.0.6" 这样的纯数字版本。</summary>
|
||||
public static string Normalize(string? tag)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(tag)) return "";
|
||||
var s = tag!.Trim();
|
||||
|
||||
// 去掉前缀:v / V / GC- / release-
|
||||
if (s.StartsWith("GC-", StringComparison.OrdinalIgnoreCase)) s = s[3..];
|
||||
else if (s.StartsWith("release-", StringComparison.OrdinalIgnoreCase)) s = s[8..];
|
||||
s = s.TrimStart('v', 'V');
|
||||
|
||||
// 只保留开头的 数字与点
|
||||
var end = 0;
|
||||
while (end < s.Length && (char.IsDigit(s[end]) || s[end] == '.')) end++;
|
||||
s = s[..end].Trim('.');
|
||||
|
||||
return s;
|
||||
}
|
||||
|
||||
/// <summary>解析成 Version;无法解析时返回 0.0。</summary>
|
||||
public static Version Parse(string? tag)
|
||||
{
|
||||
var n = Normalize(tag);
|
||||
if (string.IsNullOrWhiteSpace(n)) return new Version(0, 0);
|
||||
return Version.TryParse(n, out var v) ? v : new Version(0, 0);
|
||||
}
|
||||
|
||||
/// <summary>比较两个版本号,a>b 返回正、a<b 返回负、相等返回 0。</summary>
|
||||
public static int Compare(string? a, string? b) => Parse(a).CompareTo(Parse(b));
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.IO.Compression;
|
||||
|
||||
namespace GC.Services;
|
||||
|
||||
/// <summary>
|
||||
/// 安全解压:拒绝 zip slip(条目名含 ../、绝对路径、盘符),
|
||||
/// 并在解压前逐条校验目标路径完整落在目标目录内。
|
||||
/// </summary>
|
||||
public static class ZipSafety
|
||||
{
|
||||
public static void ExtractToDirectory(string zipPath, string destination)
|
||||
{
|
||||
var destFull = Path.GetFullPath(destination)
|
||||
.TrimEnd(Path.DirectorySeparatorChar) + Path.DirectorySeparatorChar;
|
||||
|
||||
using (var archive = ZipFile.OpenRead(zipPath))
|
||||
{
|
||||
foreach (var entry in archive.Entries)
|
||||
{
|
||||
var name = entry.FullName.Replace('\\', '/');
|
||||
if (name.StartsWith('/') || name.Contains("..", StringComparison.Ordinal) ||
|
||||
(name.Length >= 2 && name[1] == ':'))
|
||||
throw new InvalidOperationException($"压缩包含非法路径条目: {entry.FullName}");
|
||||
|
||||
var target = Path.GetFullPath(Path.Combine(destFull, name));
|
||||
if (!target.StartsWith(destFull, StringComparison.OrdinalIgnoreCase))
|
||||
throw new InvalidOperationException($"压缩包条目越界: {entry.FullName}");
|
||||
}
|
||||
}
|
||||
|
||||
// 校验通过后交给框架解压(保留 overwrite 语义)
|
||||
ZipFile.ExtractToDirectory(zipPath, destination, true);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,325 @@
|
||||
<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>
|
||||
@@ -0,0 +1,104 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.ObjectModel;
|
||||
using System.Threading.Tasks;
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
using CommunityToolkit.Mvvm.Input;
|
||||
using GC.Services;
|
||||
|
||||
namespace GC.ViewModels;
|
||||
|
||||
/// <summary>「关于」页面:版本号 + 开发者(读取仓库 contributors)。</summary>
|
||||
public partial class AboutViewModel : ObservableObject
|
||||
{
|
||||
private readonly AppServices _services;
|
||||
private bool _loaded;
|
||||
|
||||
public ObservableCollection<ContributorItem> Contributors { get; } = new();
|
||||
|
||||
[ObservableProperty] private bool _isLoading = true;
|
||||
[ObservableProperty] private string _statusText = "";
|
||||
[ObservableProperty] private bool _hasContributors;
|
||||
|
||||
public AboutViewModel(AppServices services)
|
||||
{
|
||||
_services = services;
|
||||
LoadCommand = new AsyncRelayCommand(() => LoadAsync(force: true));
|
||||
}
|
||||
|
||||
public string AppName => "Morris GC";
|
||||
|
||||
/// <summary>启动器版本号,如 v1.0.2。</summary>
|
||||
public string VersionText => "v" + UpdateService.CurrentLauncherVersion;
|
||||
|
||||
/// <summary>当前平台标识,如 win-x64 / osx-arm64。</summary>
|
||||
public string PlatformText => UpdateService.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);
|
||||
}
|
||||
@@ -0,0 +1,411 @@
|
||||
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<DownloadJob> 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(DownloadJob? job)
|
||||
{
|
||||
if (job != null) _services.Downloads.Cancel(job);
|
||||
}
|
||||
|
||||
[RelayCommand]
|
||||
private void RetryJob(DownloadJob? job)
|
||||
{
|
||||
if (job != null) _services.Downloads.Retry(job);
|
||||
}
|
||||
|
||||
[RelayCommand]
|
||||
private void RemoveJob(DownloadJob? 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 (DownloadJob job in e.NewItems) job.PropertyChanged += OnJobPropertyChanged;
|
||||
if (e.OldItems != null)
|
||||
foreach (DownloadJob job in e.OldItems) job.PropertyChanged -= OnJobPropertyChanged;
|
||||
UpdateJobState();
|
||||
}
|
||||
|
||||
private void OnJobPropertyChanged(object? sender, PropertyChangedEventArgs e)
|
||||
{
|
||||
if (e.PropertyName == nameof(DownloadJob.State))
|
||||
{
|
||||
if (sender is DownloadJob { 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));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,148 @@
|
||||
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));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,212 @@
|
||||
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" + UpdateService.CurrentLauncherVersion;
|
||||
public string PlatformText => UpdateService.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(SourceSelector.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 LauncherUpdater.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.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 { /* 忽略 */ }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,217 @@
|
||||
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; }
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
<UserControl xmlns="https://github.com/avaloniaui"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:loc="using:GC.Services"
|
||||
xmlns:vm="using:GC.ViewModels"
|
||||
x:Class="GC.Views.AboutView"
|
||||
x:DataType="vm:AboutViewModel">
|
||||
|
||||
<ScrollViewer>
|
||||
<StackPanel Margin="28,24" Spacing="16" MaxWidth="880" HorizontalAlignment="Left">
|
||||
|
||||
<StackPanel Spacing="4">
|
||||
<TextBlock Classes="h1" Text="关于" />
|
||||
<TextBlock Classes="muted" Text="版本信息与开发者" />
|
||||
</StackPanel>
|
||||
|
||||
<!-- 应用信息 -->
|
||||
<Border Classes="card" Padding="22,20">
|
||||
<Grid ColumnDefinitions="Auto,*">
|
||||
<Border Width="62" Height="62" CornerRadius="16" Background="#1C2C4C"
|
||||
VerticalAlignment="Top">
|
||||
<TextBlock Text="◎" FontSize="32" Foreground="#8FB6FF"
|
||||
HorizontalAlignment="Center" VerticalAlignment="Center" />
|
||||
</Border>
|
||||
|
||||
<StackPanel Grid.Column="1" Margin="18,0,0,0" Spacing="10">
|
||||
<StackPanel Spacing="2">
|
||||
<TextBlock Text="{Binding AppName}" FontSize="19" FontWeight="SemiBold" />
|
||||
<TextBlock Classes="faint" Text="{Binding PlatformText}" />
|
||||
</StackPanel>
|
||||
|
||||
<Grid ColumnDefinitions="96,*" RowDefinitions="Auto,Auto">
|
||||
<TextBlock Classes="h3" Text="版本" />
|
||||
<TextBlock Grid.Column="1" Classes="muted" Text="{Binding VersionText}"
|
||||
FontWeight="SemiBold" />
|
||||
|
||||
<TextBlock Grid.Row="1" Classes="h3" Text="仓库" Margin="0,8,0,0" />
|
||||
<Button Grid.Row="1" Grid.Column="1" Classes="ghost small" Margin="0,6,0,0"
|
||||
HorizontalAlignment="Left" Padding="0"
|
||||
Command="{Binding OpenRepositoryCommand}"
|
||||
Content="{Binding RepositoryText}" />
|
||||
</Grid>
|
||||
</StackPanel>
|
||||
</Grid>
|
||||
</Border>
|
||||
|
||||
<!-- 维护 -->
|
||||
<Border Classes="card" Padding="22,20">
|
||||
<StackPanel Spacing="12">
|
||||
<TextBlock Classes="h2" Text="启动器维护" />
|
||||
<TextBlock Classes="muted" TextWrapping="Wrap"
|
||||
Text="重新下载会关闭所有窗口,显示下载进度,完成后自动启动新版本并删除旧版本。" />
|
||||
<Button Classes="primary" Content="重新下载启动器"
|
||||
HorizontalAlignment="Left" Padding="18,8"
|
||||
Command="{Binding ReinstallLauncherCommand}" />
|
||||
</StackPanel>
|
||||
</Border>
|
||||
|
||||
<!-- 感谢(样式抄「开发者」卡片,内容写死,不读取数据) -->
|
||||
<Border Classes="card" Padding="22,20">
|
||||
<StackPanel Spacing="14">
|
||||
<TextBlock Classes="h2" Text="感谢" />
|
||||
|
||||
<StackPanel Orientation="Horizontal" Spacing="10">
|
||||
<Border Background="{DynamicResource SurfaceAlt}"
|
||||
BorderBrush="{DynamicResource Line}" BorderThickness="1"
|
||||
CornerRadius="12" Padding="12,10" MinWidth="190">
|
||||
<StackPanel Orientation="Horizontal" Spacing="10">
|
||||
<Border Width="34" Height="34" CornerRadius="17"
|
||||
Background="{DynamicResource AccentSoft}">
|
||||
<TextBlock Text="◉" FontSize="15" Foreground="{DynamicResource Accent}"
|
||||
HorizontalAlignment="Center" VerticalAlignment="Center" />
|
||||
</Border>
|
||||
<StackPanel VerticalAlignment="Center" Spacing="1">
|
||||
<TextBlock Text="地理洪老师" FontSize="12.5" FontWeight="SemiBold" />
|
||||
<TextBlock Classes="faint" Text="地理学科内容指导" />
|
||||
</StackPanel>
|
||||
</StackPanel>
|
||||
</Border>
|
||||
</StackPanel>
|
||||
</StackPanel>
|
||||
</Border>
|
||||
|
||||
<!-- 开发者 -->
|
||||
<Border Classes="card" Padding="22,20">
|
||||
<StackPanel Spacing="14">
|
||||
<Grid ColumnDefinitions="*,Auto">
|
||||
<TextBlock Classes="h2" Text="{Binding ContributorsTitle}" />
|
||||
<Button Grid.Column="1" Classes="ghost small" Content="刷新"
|
||||
Command="{Binding LoadCommand}" IsEnabled="{Binding !IsLoading}" />
|
||||
</Grid>
|
||||
|
||||
<TextBlock Classes="faint" Text="{Binding StatusText}" />
|
||||
|
||||
<ProgressBar IsIndeterminate="True" Height="3" IsVisible="{Binding IsLoading}" />
|
||||
|
||||
<ItemsControl ItemsSource="{Binding Contributors}" IsVisible="{Binding HasContributors}">
|
||||
<ItemsControl.ItemsPanel>
|
||||
<ItemsPanelTemplate>
|
||||
<WrapPanel Orientation="Horizontal" />
|
||||
</ItemsPanelTemplate>
|
||||
</ItemsControl.ItemsPanel>
|
||||
<ItemsControl.ItemTemplate>
|
||||
<DataTemplate>
|
||||
<Border Background="{DynamicResource SurfaceAlt}"
|
||||
BorderBrush="{DynamicResource Line}" BorderThickness="1"
|
||||
CornerRadius="12" Padding="12,10" Margin="0,0,10,10" MinWidth="190">
|
||||
<StackPanel Orientation="Horizontal" Spacing="10">
|
||||
<Border Width="34" Height="34" CornerRadius="17"
|
||||
Background="{DynamicResource AccentSoft}">
|
||||
<TextBlock Text="◉" FontSize="15" Foreground="{DynamicResource Accent}"
|
||||
HorizontalAlignment="Center" VerticalAlignment="Center" />
|
||||
</Border>
|
||||
<StackPanel VerticalAlignment="Center" Spacing="1">
|
||||
<TextBlock Text="{Binding Name}" FontSize="12.5" FontWeight="SemiBold" />
|
||||
<TextBlock Classes="faint" Text="{Binding ContributionsText}" />
|
||||
</StackPanel>
|
||||
</StackPanel>
|
||||
</Border>
|
||||
</DataTemplate>
|
||||
</ItemsControl.ItemTemplate>
|
||||
</ItemsControl>
|
||||
</StackPanel>
|
||||
</Border>
|
||||
|
||||
</StackPanel>
|
||||
</ScrollViewer>
|
||||
</UserControl>
|
||||
@@ -0,0 +1,11 @@
|
||||
using Avalonia.Controls;
|
||||
using Avalonia.Markup.Xaml;
|
||||
|
||||
namespace GC.Views;
|
||||
|
||||
public partial class AboutView : UserControl
|
||||
{
|
||||
public AboutView() => InitializeComponent();
|
||||
|
||||
private void InitializeComponent() => AvaloniaXamlLoader.Load(this);
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
<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>
|
||||
@@ -0,0 +1,66 @@
|
||||
using Avalonia;
|
||||
using Avalonia.Controls;
|
||||
using Avalonia.Interactivity;
|
||||
using Avalonia.Markup.Xaml;
|
||||
using Avalonia.Media;
|
||||
|
||||
namespace GC.Views;
|
||||
|
||||
public partial class ConfirmWindow : Window
|
||||
{
|
||||
public ConfirmWindow() : this("") { }
|
||||
|
||||
public ConfirmWindow(string message) : this(null, message, null, null) { }
|
||||
|
||||
/// <summary>
|
||||
/// 可定制标题与按钮文案的确认窗。
|
||||
/// </summary>
|
||||
public ConfirmWindow(string? title, string message, string? confirmText, string? cancelText)
|
||||
{
|
||||
AvaloniaXamlLoader.Load(this);
|
||||
|
||||
TransparencyLevelHint = new[] { WindowTransparencyLevel.Transparent };
|
||||
Background = Brushes.Transparent;
|
||||
if (this.Content is Control content)
|
||||
{
|
||||
// 先把 content 从 Window 上摘下来,否则再赋给 Border.Child 会抛
|
||||
// "The Control already has a parent."
|
||||
this.Content = null;
|
||||
this.Content = new Border
|
||||
{
|
||||
CornerRadius = new CornerRadius(14),
|
||||
BorderBrush = (this.FindResource("Line") as IBrush) ?? Brushes.Gray,
|
||||
BorderThickness = new Thickness(1),
|
||||
Background = (this.FindResource("Surface") as IBrush) ?? Brushes.White,
|
||||
ClipToBounds = true,
|
||||
Child = content
|
||||
};
|
||||
}
|
||||
|
||||
var text = this.FindControl<TextBlock>("MessageText");
|
||||
if (text != null) text.Text = message;
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(title))
|
||||
{
|
||||
var titleBlock = this.FindControl<TextBlock>("TitleText");
|
||||
if (titleBlock != null) titleBlock.Text = title;
|
||||
}
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(confirmText))
|
||||
{
|
||||
var ok = this.FindControl<Button>("ConfirmButton");
|
||||
if (ok != null) ok.Content = confirmText;
|
||||
}
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(cancelText))
|
||||
{
|
||||
// 取消按钮是第一个("取消"),这里按名查找更稳
|
||||
var cancel = this.FindControl<Button>("CancelButton");
|
||||
if (cancel != null) cancel.Content = cancelText;
|
||||
}
|
||||
}
|
||||
|
||||
private void OnCancel(object? sender, RoutedEventArgs e) => Close(false);
|
||||
|
||||
private void OnConfirm(object? sender, RoutedEventArgs e) => Close(true);
|
||||
}
|
||||
@@ -0,0 +1,154 @@
|
||||
<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>
|
||||
@@ -0,0 +1,9 @@
|
||||
using Avalonia.Controls;
|
||||
using Avalonia.Markup.Xaml;
|
||||
|
||||
namespace GC.Views;
|
||||
|
||||
public partial class DownloadView : UserControl
|
||||
{
|
||||
public DownloadView() => AvaloniaXamlLoader.Load(this);
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
<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>
|
||||
@@ -0,0 +1,9 @@
|
||||
using Avalonia.Controls;
|
||||
using Avalonia.Markup.Xaml;
|
||||
|
||||
namespace GC.Views;
|
||||
|
||||
public partial class HomeView : UserControl
|
||||
{
|
||||
public HomeView() => AvaloniaXamlLoader.Load(this);
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
<Window xmlns="https://github.com/avaloniaui"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:loc="using:GC.Services"
|
||||
x:Class="GC.Views.MainWindow"
|
||||
Title="{loc:Loc app.name}"
|
||||
Width="1220" Height="800"
|
||||
MinWidth="1040" MinHeight="700"
|
||||
Background="Transparent"
|
||||
TransparencyLevelHint="Transparent"
|
||||
SystemDecorations="None"
|
||||
WindowStartupLocation="CenterScreen">
|
||||
|
||||
<!-- 禁用系统标题栏,改用自建标题栏。
|
||||
窗口本身透明(四角露出桌面 => 圆角可见),内容 Border 自己不透明并
|
||||
用 CornerRadius + ClipToBounds 裁出圆角;AcrylicBlur 会引入系统白色,
|
||||
所以这里用纯 Transparent 避免白边。 -->
|
||||
<Border CornerRadius="16" ClipToBounds="True"
|
||||
Background="{DynamicResource AppBg}"
|
||||
BorderBrush="#1B2740" BorderThickness="1"
|
||||
BoxShadow="0 18 50 0 #400A1226">
|
||||
<Grid RowDefinitions="44,*">
|
||||
<!-- 自建标题栏 -->
|
||||
<Border x:Name="TitleBar" Grid.Row="0" Background="{DynamicResource TitleBarBg}"
|
||||
PointerPressed="OnTitleBarPointerPressed">
|
||||
<Grid ColumnDefinitions="*,Auto,Auto,Auto" Margin="16,0,10,0">
|
||||
<StackPanel Orientation="Horizontal" Spacing="10" VerticalAlignment="Center">
|
||||
<Border Width="22" Height="22" CornerRadius="7" Background="#1C2C4C">
|
||||
<TextBlock Text="◎" FontSize="13" Foreground="#8FB6FF"
|
||||
HorizontalAlignment="Center" VerticalAlignment="Center" />
|
||||
</Border>
|
||||
<TextBlock Text="{loc:Loc app.name}" Foreground="#F2F6FF" FontSize="12.5"
|
||||
FontWeight="SemiBold" VerticalAlignment="Center" />
|
||||
</StackPanel>
|
||||
<!-- 与模型窗口一致的纯矢量图标:无圆圈 -->
|
||||
<Button x:Name="MinimizeButton" Grid.Column="1" Classes="titlebtn"
|
||||
Click="OnMinimizeClick">
|
||||
<Path Data="M1.5,5 L8.5,5" Stroke="#A9B8D4" StrokeThickness="1.5"
|
||||
StrokeLineCap="Round" Stretch="None" Width="10" Height="10"
|
||||
HorizontalAlignment="Center" VerticalAlignment="Center" />
|
||||
</Button>
|
||||
<Button x:Name="MaximizeButton" Grid.Column="2" Classes="titlebtn"
|
||||
Click="OnMaximizeClick">
|
||||
<Path x:Name="MaximizeGlyph" Data="M2.2,2.2 L7.8,2.2 L7.8,7.8 L2.2,7.8 Z"
|
||||
Stroke="#A9B8D4" StrokeThickness="1.5" StrokeLineCap="Round"
|
||||
StrokeJoin="Round" Stretch="None" Width="10" Height="10"
|
||||
HorizontalAlignment="Center" VerticalAlignment="Center" />
|
||||
</Button>
|
||||
<Button x:Name="CloseButton" Grid.Column="3" Classes="titlebtn close"
|
||||
Click="OnCloseClick">
|
||||
<Path Data="M2,2 L8,8 M8,2 L2,8" Stroke="#A9B8D4" StrokeThickness="1.5"
|
||||
StrokeLineCap="Round" Stretch="None" Width="10" Height="10"
|
||||
HorizontalAlignment="Center" VerticalAlignment="Center" />
|
||||
</Button>
|
||||
</Grid>
|
||||
</Border>
|
||||
|
||||
<!-- 原内容整体下移一行 -->
|
||||
<Grid Grid.Row="1" ColumnDefinitions="236,*" RowDefinitions="*,Auto">
|
||||
|
||||
<!-- 侧栏:品牌已在标题栏展示,这里只留一句副标题,避免重复 -->
|
||||
<Border Grid.Column="0" Grid.RowSpan="2" Background="{DynamicResource SideBgBrush}">
|
||||
<Grid RowDefinitions="Auto,*,Auto" Margin="16,20,16,18">
|
||||
|
||||
<StackPanel Spacing="3" Margin="2,0,0,0">
|
||||
<TextBlock Text="{loc:Loc app.tagline}" Foreground="#7C90B4" FontSize="10.5"
|
||||
TextWrapping="Wrap" />
|
||||
</StackPanel>
|
||||
|
||||
<StackPanel Grid.Row="1" Margin="0,26,0,0" Spacing="6">
|
||||
<TextBlock Text="MENU" Foreground="#4C5F80" FontSize="9.5" FontWeight="SemiBold" Margin="14,0,0,4" />
|
||||
<Button Classes="nav" Classes.active="{Binding IsHomeActive}"
|
||||
Command="{Binding GoHomeCommand}" Content="{loc:Loc nav.home}" />
|
||||
<Button Classes="nav" Classes.active="{Binding IsDownloadActive}"
|
||||
Command="{Binding GoDownloadCommand}" Content="{loc:Loc nav.download}" />
|
||||
<Button Classes="nav" Classes.active="{Binding IsSettingsActive}"
|
||||
Command="{Binding GoSettingsCommand}" Content="{loc:Loc nav.settings}" />
|
||||
<Button Classes="nav" Classes.active="{Binding IsAboutActive}"
|
||||
Command="{Binding GoAboutCommand}" Content="{loc:Loc nav.about}" />
|
||||
</StackPanel>
|
||||
|
||||
<StackPanel Grid.Row="2" Spacing="4">
|
||||
<Border Height="1" Background="{DynamicResource SideLine}" Margin="0,0,0,10" />
|
||||
<TextBlock Text="{Binding VersionText}" Foreground="#6F82A6" FontSize="10.5" Margin="14,0,0,0" />
|
||||
<TextBlock Text="{Binding PlatformText}" Foreground="#4F6080" FontSize="10" Margin="14,0,0,0" />
|
||||
</StackPanel>
|
||||
|
||||
</Grid>
|
||||
</Border>
|
||||
|
||||
<!-- 内容:页面切换由 MainWindow 做淡入过渡,避免硬切 -->
|
||||
<ContentControl x:Name="PageHost" Grid.Column="1" Grid.Row="0" Content="{Binding Current}" />
|
||||
|
||||
<!-- 启动更新状态条:模型立即生效,启动器下次启动生效 -->
|
||||
<Border Grid.Column="1" Grid.Row="1"
|
||||
Background="{DynamicResource Surface}"
|
||||
BorderBrush="{DynamicResource Line}" BorderThickness="0,1,0,0"
|
||||
Padding="20,9" IsVisible="{Binding UpdateBarVisible}">
|
||||
<Grid ColumnDefinitions="Auto,*,Auto,Auto">
|
||||
<TextBlock Grid.Column="0" Text="⟳" FontSize="16" Foreground="{DynamicResource Accent}"
|
||||
VerticalAlignment="Center" Margin="0,0,12,0" />
|
||||
<StackPanel Grid.Column="1" Spacing="2" VerticalAlignment="Center">
|
||||
<TextBlock Text="{Binding UpdateStatus}" FontSize="12.5" FontWeight="SemiBold"
|
||||
Foreground="{DynamicResource Ink}" TextTrimming="CharacterEllipsis" />
|
||||
<TextBlock Text="{Binding UpdateDetail}" Classes="faint" TextTrimming="CharacterEllipsis" />
|
||||
<TextBlock Text="{Binding LauncherNotice}" FontSize="11" Foreground="{DynamicResource Warn}"
|
||||
TextWrapping="Wrap" />
|
||||
</StackPanel>
|
||||
<ProgressBar Grid.Column="2" Width="130" Minimum="0" Maximum="1"
|
||||
Value="{Binding UpdateProgress}" IsVisible="{Binding UpdateBusy}"
|
||||
VerticalAlignment="Center" Margin="14,0" />
|
||||
<Button Grid.Column="3" Classes="ghost small" Content="{loc:Loc update.checkNow}"
|
||||
Command="{Binding CheckUpdateCommand}" IsEnabled="{Binding !UpdateBusy}"
|
||||
VerticalAlignment="Center" />
|
||||
</Grid>
|
||||
</Border>
|
||||
</Grid>
|
||||
</Grid>
|
||||
</Border>
|
||||
</Window>
|
||||
@@ -0,0 +1,216 @@
|
||||
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();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
<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>
|
||||
@@ -0,0 +1,9 @@
|
||||
using Avalonia.Controls;
|
||||
using Avalonia.Markup.Xaml;
|
||||
|
||||
namespace GC.Views;
|
||||
|
||||
public partial class SettingsView : UserControl
|
||||
{
|
||||
public SettingsView() => AvaloniaXamlLoader.Load(this);
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
using System;
|
||||
using Avalonia;
|
||||
using Avalonia.Controls;
|
||||
using Avalonia.Layout;
|
||||
using Avalonia.Media;
|
||||
using Avalonia.Threading;
|
||||
using GC.Services;
|
||||
|
||||
namespace GC.Views;
|
||||
|
||||
/// <summary>
|
||||
/// 启动器更新进度窗:更新期间主窗口已关闭,由这个独立小窗展示下载进度。
|
||||
/// 窗口本身透明,圆角由内部 Border 裁出。
|
||||
/// </summary>
|
||||
public sealed class UpdaterWindow : Window
|
||||
{
|
||||
private readonly ProgressBar _bar;
|
||||
private readonly TextBlock _stage;
|
||||
private readonly TextBlock _detail;
|
||||
private readonly TextBlock _percent;
|
||||
|
||||
public UpdaterWindow(string title)
|
||||
{
|
||||
Title = title;
|
||||
Width = 460;
|
||||
Height = 210;
|
||||
CanResize = false;
|
||||
ShowInTaskbar = false;
|
||||
WindowStartupLocation = WindowStartupLocation.CenterScreen;
|
||||
// 必须透明,否则会把内部 Border 的圆角填平
|
||||
Background = Brushes.Transparent;
|
||||
TransparencyLevelHint = new[] { WindowTransparencyLevel.Transparent };
|
||||
SystemDecorations = SystemDecorations.None;
|
||||
|
||||
var titleBlock = new TextBlock
|
||||
{
|
||||
Text = title,
|
||||
Foreground = new SolidColorBrush(Color.Parse("#F2F6FF")),
|
||||
FontSize = 15,
|
||||
FontWeight = FontWeight.SemiBold
|
||||
};
|
||||
|
||||
_stage = new TextBlock
|
||||
{
|
||||
Text = "正在准备…",
|
||||
Foreground = new SolidColorBrush(Color.Parse("#8CA0C4")),
|
||||
FontSize = 12
|
||||
};
|
||||
|
||||
_bar = new ProgressBar
|
||||
{
|
||||
Minimum = 0,
|
||||
Maximum = 1,
|
||||
Value = 0,
|
||||
Height = 6,
|
||||
CornerRadius = new CornerRadius(3),
|
||||
Foreground = new SolidColorBrush(Color.Parse("#3B7BFF")),
|
||||
Background = new SolidColorBrush(Color.Parse("#1B2740"))
|
||||
};
|
||||
|
||||
_percent = new TextBlock
|
||||
{
|
||||
Text = "0%",
|
||||
Foreground = new SolidColorBrush(Color.Parse("#6E86AD")),
|
||||
FontSize = 11,
|
||||
HorizontalAlignment = HorizontalAlignment.Right
|
||||
};
|
||||
|
||||
_detail = new TextBlock
|
||||
{
|
||||
Text = "",
|
||||
Foreground = new SolidColorBrush(Color.Parse("#4F6382")),
|
||||
FontSize = 10.5
|
||||
};
|
||||
|
||||
var panel = new StackPanel { Margin = new Thickness(24, 22), Spacing = 12 };
|
||||
panel.Children.Add(titleBlock);
|
||||
panel.Children.Add(_bar);
|
||||
panel.Children.Add(_stage);
|
||||
panel.Children.Add(_percent);
|
||||
panel.Children.Add(_detail);
|
||||
|
||||
Content = new Border
|
||||
{
|
||||
CornerRadius = new CornerRadius(16),
|
||||
Background = new SolidColorBrush(Color.Parse("#0B1226")),
|
||||
BorderBrush = new SolidColorBrush(Color.Parse("#223252")),
|
||||
BorderThickness = new Thickness(1),
|
||||
ClipToBounds = true,
|
||||
Child = panel
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>任意线程调用都可以。</summary>
|
||||
public void Report(double value, string? stage, string? detail = null)
|
||||
{
|
||||
if (!Dispatcher.UIThread.CheckAccess())
|
||||
{
|
||||
Dispatcher.UIThread.Post(() => Report(value, stage, detail));
|
||||
return;
|
||||
}
|
||||
|
||||
var clamped = Math.Clamp(value, 0, 1);
|
||||
_bar.Value = clamped;
|
||||
_percent.Text = $"{clamped * 100:0}%";
|
||||
if (!string.IsNullOrWhiteSpace(stage)) _stage.Text = stage;
|
||||
if (!string.IsNullOrWhiteSpace(detail)) _detail.Text = detail;
|
||||
}
|
||||
}
|
||||
@@ -14,7 +14,7 @@
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="../../../../../GC-BOOT/GC.csproj" />
|
||||
<ProjectReference Include="../../../GC.Core.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||