y
This commit is contained in:
commit
1ee49b8966
1125 files changed
+32542
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:EarthModelStudio.ViewModels"
|
||||
xmlns:views="using:EarthModelStudio.Views"
|
||||
x:Class="EarthModelStudio.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://EarthModelStudio/Styles/AppTheme.axaml" />
|
||||
</Application.Styles>
|
||||
</Application>
|
||||
@@ -0,0 +1,91 @@
|
||||
using System;
|
||||
using System.Threading.Tasks;
|
||||
using Avalonia;
|
||||
using Avalonia.Controls;
|
||||
using Avalonia.Controls.ApplicationLifetimes;
|
||||
using Avalonia.Markup.Xaml;
|
||||
using EarthModelStudio.Services;
|
||||
using EarthModelStudio.ViewModels;
|
||||
using EarthModelStudio.Views;
|
||||
|
||||
namespace EarthModelStudio;
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
var vm = new MainViewModel(services);
|
||||
var window = new MainWindow { DataContext = vm };
|
||||
|
||||
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);
|
||||
};
|
||||
|
||||
desktop.MainWindow = window;
|
||||
desktop.ShutdownMode = ShutdownMode.OnMainWindowClose;
|
||||
|
||||
// 主窗口已建好,后台检查模型 / 启动器更新,不阻塞界面
|
||||
if (Environment.GetEnvironmentVariable("EMS_NO_UPDATE") != "1")
|
||||
{
|
||||
Avalonia.Threading.Dispatcher.UIThread.Post(
|
||||
() => _ = vm.RunStartupUpdateAsync(),
|
||||
Avalonia.Threading.DispatcherPriority.Background);
|
||||
}
|
||||
}
|
||||
|
||||
base.OnFrameworkInitializationCompleted();
|
||||
}
|
||||
|
||||
/// <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,或重新下载该模型。"
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<OutputType>WinExe</OutputType>
|
||||
<Nullable>enable</Nullable>
|
||||
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
|
||||
<RootNamespace>EarthModelStudio</RootNamespace>
|
||||
<AssemblyName>EarthModelStudio</AssemblyName>
|
||||
<ApplicationManifest>app.manifest</ApplicationManifest>
|
||||
<AvaloniaUseCompiledBindingsByDefault>false</AvaloniaUseCompiledBindingsByDefault>
|
||||
<BuiltInComInteropSupport>true</BuiltInComInteropSupport>
|
||||
<InvariantGlobalization>false</InvariantGlobalization>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<AvaloniaResource Include="Assets\**" />
|
||||
</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\EarthModelStudio.ModelSdk\EarthModelStudio.ModelSdk.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -0,0 +1,84 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace EarthModelStudio.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,98 @@
|
||||
using System.Collections.Generic;
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace EarthModelStudio.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; }
|
||||
}
|
||||
|
||||
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,26 @@
|
||||
using System;
|
||||
using Avalonia;
|
||||
using EarthModelStudio.Services;
|
||||
|
||||
namespace EarthModelStudio;
|
||||
|
||||
internal static class Program
|
||||
{
|
||||
[STAThread]
|
||||
public static void Main(string[] args)
|
||||
{
|
||||
// 运行目录:可执行文件旁 .GC/(settings.json + model/ + cache/ + update/)
|
||||
var paths = AppPaths.Discover();
|
||||
paths.EnsureCreated();
|
||||
|
||||
// 上次下载的启动器新版,到这次启动才应用
|
||||
if (LauncherUpdater.TryApplyPending(paths)) return;
|
||||
|
||||
BuildAvaloniaApp().StartWithClassicDesktopLifetime(args);
|
||||
}
|
||||
|
||||
public static AppBuilder BuildAvaloniaApp()
|
||||
=> AppBuilder.Configure<App>()
|
||||
.UsePlatformDetect()
|
||||
.LogToTrace();
|
||||
}
|
||||
@@ -0,0 +1,289 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
|
||||
namespace EarthModelStudio.Services;
|
||||
|
||||
/// <summary>
|
||||
/// 运行目录约定(可执行文件旁边,不内置任何模型):
|
||||
/// <code>
|
||||
/// <安装目录>/
|
||||
/// EarthModelStudio(.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
|
||||
{
|
||||
/// <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 目录)
|
||||
// · 源码版:仓库根(含 EarthModelStudio.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!, "EarthModelStudio.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),
|
||||
"EarthModelStudio", ".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>
|
||||
/// 从程序所在位置向上找仓库根(含 EarthModelStudio.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, "EarthModelStudio.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 源码)
|
||||
if (IsDevelopment && string.IsNullOrWhiteSpace(Environment.GetEnvironmentVariable("EMS_MODELS")))
|
||||
SyncDevelopmentModels();
|
||||
}
|
||||
|
||||
private void SyncDevelopmentModels()
|
||||
{
|
||||
try
|
||||
{
|
||||
var source = Path.Combine(AppRoot, "model");
|
||||
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,49 @@
|
||||
using System;
|
||||
|
||||
namespace EarthModelStudio.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; }
|
||||
|
||||
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);
|
||||
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 EarthModelStudio.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("EarthModelStudio/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 EarthModelStudio.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 EarthModelStudio.Models;
|
||||
|
||||
namespace EarthModelStudio.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,206 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Net.Http;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace EarthModelStudio.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("EarthModelStudio-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; }
|
||||
|
||||
/// <summary>
|
||||
/// 模型部分照旧读仓库 version.json;成功拿到 Release 时,用 tag/附件覆盖启动器字段。
|
||||
/// </summary>
|
||||
public async Task<RepoVersion?> GetVersionAsync(CancellationToken ct)
|
||||
{
|
||||
var version = await _content.GetVersionAsync(ct);
|
||||
try
|
||||
{
|
||||
await ApplyReleaseAsync(version, ct);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
// 没有 Release / 断网 / 格式不符:回退到 version.json,不影响模型更新
|
||||
Console.Error.WriteLine($"读取 Release 失败,回退仓库清单: {ex.Message}");
|
||||
}
|
||||
return version;
|
||||
}
|
||||
|
||||
private async Task ApplyReleaseAsync(RepoVersion? version, CancellationToken ct)
|
||||
{
|
||||
if (version == null) return;
|
||||
|
||||
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; // 可能是错误页/对象
|
||||
|
||||
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;
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
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,211 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Net.Http;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace EarthModelStudio.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("EarthModelStudio-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, EarthModelStudio.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>递归列出目录树(含目录项与文件项)。</summary>
|
||||
public async Task<IReadOnlyList<RepoEntry>> ListTreeAsync(string rootPath, CancellationToken ct)
|
||||
{
|
||||
var result = new List<RepoEntry>();
|
||||
var repoPath = (rootPath ?? _modelDir).Trim('/');
|
||||
await WalkAsync(repoPath, "", 0, result, ct);
|
||||
return result;
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
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,34 @@
|
||||
using System.Text.Encodings.Web;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace EarthModelStudio.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 EarthModelStudio.Views;
|
||||
|
||||
namespace EarthModelStudio.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,431 @@
|
||||
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 EarthModelStudio.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>
|
||||
public static async Task<string?> CheckAsync(IModelRemote remote, CancellationToken ct = default)
|
||||
{
|
||||
try
|
||||
{
|
||||
var version = await remote.GetVersionAsync(ct);
|
||||
if (version == null) return null;
|
||||
var latest = (version.Launcher.Version ?? "").Trim();
|
||||
if (latest.Length == 0) return null;
|
||||
return string.Equals(latest, RunningVersion, StringComparison.OrdinalIgnoreCase)
|
||||
? null
|
||||
: latest;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.Error.WriteLine($"检查更新失败: {ex.Message}");
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- 下载
|
||||
|
||||
/// <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 = "正在读取最新版本" });
|
||||
var version = await remote.GetVersionAsync(ct);
|
||||
if (version == null) return Fail("无法读取 Release 版本清单");
|
||||
|
||||
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, "EarthModelStudio.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 EarthModelStudio.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://EarthModelStudio/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 EarthModelStudio.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 => 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 = 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 EarthModelStudio.Models;
|
||||
using EarthModelStudio.ModelSdk;
|
||||
|
||||
namespace EarthModelStudio.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)
|
||||
{
|
||||
"EarthModelStudio.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 EarthModelStudio.Models;
|
||||
|
||||
namespace EarthModelStudio.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,56 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using EarthModelStudio.Models;
|
||||
|
||||
namespace EarthModelStudio.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()
|
||||
{
|
||||
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 EarthModelStudio.Models;
|
||||
|
||||
namespace EarthModelStudio.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,252 @@
|
||||
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 EarthModelStudio.Models;
|
||||
|
||||
namespace EarthModelStudio.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("EarthModelStudio/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);
|
||||
}
|
||||
}
|
||||
|
||||
var args = new List<string> { "clone", "--depth", "1" };
|
||||
if (!string.IsNullOrWhiteSpace(branch)) { args.Add("--branch"); args.Add(branch!); }
|
||||
args.Add(url);
|
||||
args.Add(cacheDir);
|
||||
|
||||
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 stderrTask = process.StandardError.ReadToEndAsync(ct);
|
||||
await process.WaitForExitAsync(ct);
|
||||
var stderr = await stderrTask;
|
||||
if (process.ExitCode != 0)
|
||||
{
|
||||
Console.Error.WriteLine($"git clone 失败: {stderr}");
|
||||
return false;
|
||||
}
|
||||
return Directory.Exists(Path.Combine(cacheDir, "model")) || Directory.Exists(cacheDir);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.Error.WriteLine($"git clone 异常: {ex.Message}");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace EarthModelStudio.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 EarthModelStudio.Models;
|
||||
|
||||
namespace EarthModelStudio.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>
|
||||
/// 默认下载源(gitcode 官方仓库)始终内置在列表里,且不允许删除:
|
||||
/// 它是启动器自动更新的同源仓库,用户清掉会导致模型无法回退。
|
||||
/// 老配置里没有这条时自动补上;已有的用户自定义源保持不变。
|
||||
/// </summary>
|
||||
public const string DefaultSourceId = "gitcode-official";
|
||||
public const string DefaultSourceUrl = "https://gitcode.com/2509_92447106/GC";
|
||||
|
||||
private void SeedDefaultSource()
|
||||
{
|
||||
var existing = Current.Sources.FirstOrDefault(s =>
|
||||
string.Equals(s.Id, DefaultSourceId, StringComparison.OrdinalIgnoreCase));
|
||||
if (existing == null)
|
||||
{
|
||||
Current.Sources.Insert(0, new ModelSource
|
||||
{
|
||||
Id = DefaultSourceId,
|
||||
Name = "Morris GC (GitCode)",
|
||||
Url = DefaultSourceUrl,
|
||||
Enabled = true,
|
||||
BuiltIn = true
|
||||
});
|
||||
Save();
|
||||
}
|
||||
else
|
||||
{
|
||||
// 强制保证内置标记与地址,避免旧配置被用户改坏后失去保护
|
||||
existing.BuiltIn = true;
|
||||
if (string.IsNullOrWhiteSpace(existing.Url)) existing.Url = DefaultSourceUrl;
|
||||
}
|
||||
}
|
||||
|
||||
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 EarthModelStudio.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,97 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace EarthModelStudio.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; }
|
||||
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,280 @@
|
||||
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 EarthModelStudio.Models;
|
||||
|
||||
namespace EarthModelStudio.Services;
|
||||
|
||||
/// <summary>
|
||||
/// 模型自动更新:读远端版本清单,把缺失/过期的模型下载到 cache 后原子替换
|
||||
/// .GC/model/<id>,本次启动立即生效。任何失败都保留本地已装模型。
|
||||
/// 启动器更新由 LauncherUpdater / LauncherUpdateFlow 独立负责,不在这里。
|
||||
/// </summary>
|
||||
public sealed class UpdateService
|
||||
{
|
||||
private readonly AppPaths _paths;
|
||||
private readonly SettingsService _settings;
|
||||
private readonly IModelRemote _remote;
|
||||
|
||||
public UpdateService(AppPaths paths, SettingsService settings, IModelRemote remote)
|
||||
{
|
||||
_paths = paths;
|
||||
_settings = settings;
|
||||
_remote = remote;
|
||||
}
|
||||
|
||||
public IModelRemote Remote => _remote;
|
||||
|
||||
public static string CurrentLauncherVersion
|
||||
{
|
||||
get
|
||||
{
|
||||
var v = Assembly.GetEntryAssembly()?.GetName().Version;
|
||||
if (v == null) return "0.0.0";
|
||||
return $"{Math.Max(0, v.Major)}.{Math.Max(0, v.Minor)}.{Math.Max(0, v.Build)}";
|
||||
}
|
||||
}
|
||||
|
||||
public static string CurrentRid
|
||||
{
|
||||
get
|
||||
{
|
||||
var arch = RuntimeInformation.OSArchitecture switch
|
||||
{
|
||||
Architecture.Arm64 => "arm64",
|
||||
Architecture.X86 => "x86",
|
||||
_ => "x64"
|
||||
};
|
||||
if (OperatingSystem.IsWindows()) return "win-" + arch;
|
||||
if (OperatingSystem.IsMacOS()) return "osx-" + arch;
|
||||
if (OperatingSystem.IsLinux()) return "linux-" + arch;
|
||||
return RuntimeInformation.RuntimeIdentifier;
|
||||
}
|
||||
}
|
||||
|
||||
public static IModelRemote CreateRemote(AppSettings settings)
|
||||
{
|
||||
if (!string.IsNullOrWhiteSpace(settings.UpdateLocalRoot) &&
|
||||
Directory.Exists(settings.UpdateLocalRoot!))
|
||||
return new DirectoryRemote(settings.UpdateLocalRoot!); // 离线 U 盘源:仍读本地 version.json
|
||||
// 在线源:启动器版本与发布包走 GitCode Release(tag + 附件),
|
||||
// 模型清单/文件仍走仓库 contents API;无 Release 时自动回退仓库 version.json。
|
||||
return new GitCodeReleaseRemote(settings.UpdateManifestUrl, settings.UpdateRepository);
|
||||
}
|
||||
|
||||
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));
|
||||
long done = 0;
|
||||
foreach (var entry in files)
|
||||
{
|
||||
ct.ThrowIfCancellationRequested();
|
||||
var bytes = await _remote.DownloadAsync(entry, ct);
|
||||
// 路径穿越防护:规范化后必须仍落在 staging 目录内,
|
||||
// 防止远端清单里的 "../" 或绝对路径写进安装目录之外。
|
||||
var dest = Path.GetFullPath(Path.Combine(staging,
|
||||
entry.RelativePath.Replace('/', Path.DirectorySeparatorChar)));
|
||||
var stagingFull = Path.GetFullPath(staging)
|
||||
.TrimEnd(Path.DirectorySeparatorChar) + Path.DirectorySeparatorChar;
|
||||
if (!dest.StartsWith(stagingFull, StringComparison.OrdinalIgnoreCase))
|
||||
throw new InvalidOperationException($"非法的模型文件路径: {entry.RelativePath}");
|
||||
var destDir = Path.GetDirectoryName(dest);
|
||||
if (!string.IsNullOrEmpty(destDir)) Directory.CreateDirectory(destDir);
|
||||
await File.WriteAllBytesAsync(dest, bytes, ct);
|
||||
done += bytes.Length;
|
||||
progress?.Report(new UpdateProgress
|
||||
{
|
||||
Value = 0.05 + 0.72 * (index + Math.Min(1, (double)done / Math.Max(1, total))) / Math.Max(1, count),
|
||||
Message = L.I.F("update.downloadingModel", model.Id),
|
||||
Detail = entry.RelativePath
|
||||
});
|
||||
}
|
||||
|
||||
// 原子替换:先备份旧目录,成功后再删备份;失败自动回滚
|
||||
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,36 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.IO.Compression;
|
||||
|
||||
namespace EarthModelStudio.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 EarthModelStudio.Services;
|
||||
|
||||
namespace EarthModelStudio.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,393 @@
|
||||
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 EarthModelStudio.Models;
|
||||
using EarthModelStudio.Services;
|
||||
|
||||
namespace EarthModelStudio.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;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[RelayCommand]
|
||||
private async Task ImportAsync()
|
||||
{
|
||||
var url = ImportUrl.Trim();
|
||||
if (string.IsNullOrWhiteSpace(url))
|
||||
{
|
||||
StatusMessage = L.I["dl.error.emptyUrl"];
|
||||
return;
|
||||
}
|
||||
|
||||
var source = new ModelSource
|
||||
{
|
||||
Name = DeriveName(url),
|
||||
Url = url,
|
||||
Enabled = true
|
||||
};
|
||||
_services.Settings.Current.Sources.Add(source);
|
||||
_services.Settings.Save();
|
||||
|
||||
var item = new SourceItemViewModel(source, this, _services);
|
||||
Sources.Add(item);
|
||||
ImportUrl = "";
|
||||
SelectedSource = item;
|
||||
await LoadAsync(item, force: true);
|
||||
}
|
||||
|
||||
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
|
||||
{
|
||||
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 EarthModelStudio.Models;
|
||||
using Avalonia.Media.Imaging;
|
||||
using EarthModelStudio.Services;
|
||||
|
||||
namespace EarthModelStudio.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,193 @@
|
||||
using System;
|
||||
using System.Threading.Tasks;
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
using CommunityToolkit.Mvvm.Input;
|
||||
using EarthModelStudio.Models;
|
||||
using EarthModelStudio.Services;
|
||||
|
||||
namespace EarthModelStudio.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 ?? "";
|
||||
});
|
||||
|
||||
// 启动器:读 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 EarthModelStudio.Models;
|
||||
using EarthModelStudio.Services;
|
||||
|
||||
namespace EarthModelStudio.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()
|
||||
{
|
||||
// 模型数据由模型自己管理;这里只回收启动器侧托管内存
|
||||
GC.Collect();
|
||||
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,102 @@
|
||||
<UserControl xmlns="https://github.com/avaloniaui"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:loc="using:EarthModelStudio.Services"
|
||||
xmlns:vm="using:EarthModelStudio.ViewModels"
|
||||
x:Class="EarthModelStudio.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">
|
||||
<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 EarthModelStudio.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:EarthModelStudio.Services"
|
||||
x:Class="EarthModelStudio.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 EarthModelStudio.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,155 @@
|
||||
<UserControl xmlns="https://github.com/avaloniaui"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:loc="using:EarthModelStudio.Services"
|
||||
x:Class="EarthModelStudio.Views.DownloadView">
|
||||
|
||||
<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}" />
|
||||
|
||||
<StackPanel Grid.Row="1" Margin="0,12,0,0" Spacing="8">
|
||||
<TextBox Text="{Binding ImportUrl}" Watermark="{loc:Loc dl.importPlaceholder}" />
|
||||
<Button Classes="primary" Content="{loc:Loc dl.import}"
|
||||
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>
|
||||
<Button Grid.Column="1" Classes="ghost small" Content="✕"
|
||||
IsVisible="{Binding CanRemove}" Command="{Binding RemoveCommand}" VerticalAlignment="Center" />
|
||||
</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 EarthModelStudio.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:EarthModelStudio.Services"
|
||||
xmlns:controls="using:EarthModelStudio.Controls"
|
||||
x:Class="EarthModelStudio.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 EarthModelStudio.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 EarthModelStudio.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,103 @@
|
||||
<Window xmlns="https://github.com/avaloniaui"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:loc="using:EarthModelStudio.Services"
|
||||
x:Class="EarthModelStudio.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" Margin="16,0,8,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"
|
||||
Content="—" Click="OnMinimizeClick" />
|
||||
<Button x:Name="CloseButton" Grid.Column="2" Classes="titlebtn close"
|
||||
Content="✕" Click="OnCloseClick" />
|
||||
</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,190 @@
|
||||
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 EarthModelStudio.Models;
|
||||
using EarthModelStudio.Services;
|
||||
using EarthModelStudio.ViewModels;
|
||||
|
||||
namespace EarthModelStudio.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;
|
||||
}
|
||||
|
||||
/// <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.GetCurrentPoint(this).Properties.IsLeftButtonPressed)
|
||||
BeginMoveDrag(e);
|
||||
}
|
||||
|
||||
private void OnMinimizeClick(object? sender, global::Avalonia.Interactivity.RoutedEventArgs e)
|
||||
=> WindowState = WindowState.Minimized;
|
||||
|
||||
// 关闭动画:先淡出再真正 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,175 @@
|
||||
using System;
|
||||
using Avalonia;
|
||||
using Avalonia.Controls;
|
||||
using Avalonia.Input;
|
||||
using Avalonia.Layout;
|
||||
using Avalonia.Media;
|
||||
using System.Collections.Generic;
|
||||
using EarthModelStudio.Models;
|
||||
using EarthModelStudio.Services;
|
||||
|
||||
namespace EarthModelStudio.Views;
|
||||
|
||||
/// <summary>
|
||||
/// 模型窗口:**只做窗口宿主**。
|
||||
/// 内容完全来自模型程序集(<see cref="LoadedModel.View"/>),启动器不渲染任何东西。
|
||||
/// 快捷键:Esc 关闭窗口,F11 全屏。
|
||||
/// </summary>
|
||||
public sealed class PlayerWindow : Window
|
||||
{
|
||||
private LoadedModel? _model;
|
||||
|
||||
public PlayerWindow(ModelPackage package, LoadedModel model)
|
||||
{
|
||||
_model = model;
|
||||
Title = package.LocalizedName;
|
||||
Width = 1240;
|
||||
Height = 820;
|
||||
MinWidth = 1000;
|
||||
MinHeight = 680;
|
||||
Background = Brushes.Transparent;
|
||||
TransparencyLevelHint = new[] { WindowTransparencyLevel.Transparent };
|
||||
WindowStartupLocation = WindowStartupLocation.CenterOwner;
|
||||
// 与启动器一致:去掉系统标题栏,自己做一个极简顶栏(否则 Esc 之外无法关闭)
|
||||
SystemDecorations = Avalonia.Controls.SystemDecorations.None;
|
||||
|
||||
var titleBar = new Border
|
||||
{
|
||||
Height = 34,
|
||||
Background = new SolidColorBrush(Color.Parse("#0A1120")),
|
||||
Child = new Grid
|
||||
{
|
||||
ColumnDefinitions = new ColumnDefinitions("*,Auto"),
|
||||
Children =
|
||||
{
|
||||
new TextBlock
|
||||
{
|
||||
Text = package.LocalizedName,
|
||||
Foreground = new SolidColorBrush(Color.Parse("#A9B8D4")),
|
||||
FontSize = 11.5,
|
||||
Margin = new Thickness(14, 0, 0, 0),
|
||||
VerticalAlignment = VerticalAlignment.Center,
|
||||
[Grid.ColumnProperty] = 0
|
||||
},
|
||||
new Button
|
||||
{
|
||||
Content = "✕",
|
||||
Width = 40,
|
||||
Height = 28,
|
||||
Background = Brushes.Transparent,
|
||||
Foreground = new SolidColorBrush(Color.Parse("#A9B8D4")),
|
||||
BorderThickness = new Thickness(0),
|
||||
FontSize = 13,
|
||||
CornerRadius = new CornerRadius(7),
|
||||
Margin = new Thickness(0, 0, 8, 0),
|
||||
HorizontalContentAlignment = HorizontalAlignment.Center,
|
||||
VerticalContentAlignment = VerticalAlignment.Center,
|
||||
[Grid.ColumnProperty] = 1
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
titleBar.PointerPressed += OnTitleBarPointerPressed;
|
||||
if (titleBar.Child is Grid g)
|
||||
foreach (var child in g.Children)
|
||||
if (child is Button b) b.Click += (_, _) => Close();
|
||||
|
||||
var dock = new DockPanel { LastChildFill = true };
|
||||
DockPanel.SetDock(titleBar, Dock.Top);
|
||||
dock.Children.Add(titleBar);
|
||||
dock.Children.Add(model.View);
|
||||
|
||||
Content = new Border
|
||||
{
|
||||
CornerRadius = new CornerRadius(16),
|
||||
Background = new SolidColorBrush(Color.Parse("#05070F")),
|
||||
ClipToBounds = true,
|
||||
Child = dock
|
||||
};
|
||||
|
||||
KeyDown += OnKeyDown;
|
||||
Closed += OnClosed;
|
||||
}
|
||||
|
||||
private void OnTitleBarPointerPressed(object? sender, PointerPressedEventArgs e)
|
||||
{
|
||||
if (e.GetCurrentPoint(this).Properties.IsLeftButtonPressed)
|
||||
BeginMoveDrag(e);
|
||||
}
|
||||
|
||||
private void OnKeyDown(object? sender, KeyEventArgs e)
|
||||
{
|
||||
switch (e.Key)
|
||||
{
|
||||
case Key.Escape:
|
||||
Close();
|
||||
e.Handled = true;
|
||||
break;
|
||||
case Key.F11:
|
||||
WindowState = WindowState == WindowState.FullScreen
|
||||
? WindowState.Normal
|
||||
: WindowState.FullScreen;
|
||||
e.Handled = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
private void OnClosed(object? sender, EventArgs e)
|
||||
{
|
||||
Content = null;
|
||||
_model?.Dispose();
|
||||
_model = null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>模型加载失败时显示的提示窗口(不含任何渲染逻辑)。</summary>
|
||||
public sealed class ModelErrorWindow : Window
|
||||
{
|
||||
public ModelErrorWindow(string title, string message)
|
||||
{
|
||||
Title = title;
|
||||
Width = 560;
|
||||
Height = 340;
|
||||
Background = Brushes.Transparent;
|
||||
TransparencyLevelHint = new[] { WindowTransparencyLevel.Transparent };
|
||||
WindowStartupLocation = WindowStartupLocation.CenterOwner;
|
||||
|
||||
var lines = new List<Control>
|
||||
{
|
||||
new TextBlock
|
||||
{
|
||||
Text = title,
|
||||
Foreground = new SolidColorBrush(Color.Parse("#F2F6FF")),
|
||||
FontSize = 16,
|
||||
FontWeight = FontWeight.SemiBold
|
||||
},
|
||||
new TextBlock
|
||||
{
|
||||
Text = message,
|
||||
Foreground = new SolidColorBrush(Color.Parse("#8CA0C4")),
|
||||
FontSize = 12,
|
||||
TextWrapping = TextWrapping.Wrap
|
||||
},
|
||||
new Button
|
||||
{
|
||||
Content = "确定",
|
||||
HorizontalAlignment = Avalonia.Layout.HorizontalAlignment.Right,
|
||||
Padding = new Thickness(18, 6)
|
||||
}
|
||||
};
|
||||
|
||||
var panel = new StackPanel
|
||||
{
|
||||
Margin = new Thickness(24),
|
||||
Spacing = 14
|
||||
};
|
||||
foreach (var line in lines) panel.Children.Add(line);
|
||||
if (lines[^1] is Button ok) ok.Click += (_, _) => Close();
|
||||
Content = new Border
|
||||
{
|
||||
CornerRadius = new CornerRadius(12),
|
||||
Background = new SolidColorBrush(Color.Parse("#0B1226")),
|
||||
Child = panel
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
<UserControl xmlns="https://github.com/avaloniaui"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:loc="using:EarthModelStudio.Services"
|
||||
x:Class="EarthModelStudio.Views.SettingsView">
|
||||
|
||||
<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 EarthModelStudio.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 EarthModelStudio.Services;
|
||||
|
||||
namespace EarthModelStudio.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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<assembly manifestVersion="1.0" xmlns="urn:schemas-microsoft-com:asm.v1">
|
||||
<assemblyIdentity version="1.0.0.0" name="EarthModelStudio.Desktop" />
|
||||
<application xmlns="urn:schemas-microsoft-com:asm.v3">
|
||||
<windowsSettings>
|
||||
<dpiAware xmlns="http://schemas.microsoft.com/SMI/2005/WindowsSettings">true/pm</dpiAware>
|
||||
<dpiAwareness xmlns="http://schemas.microsoft.com/SMI/2016/WindowsSettings">permonitorv2,permonitor</dpiAwareness>
|
||||
</windowsSettings>
|
||||
</application>
|
||||
<compatibility xmlns="urn:schemas-microsoft-com:compatibility.v1">
|
||||
<application>
|
||||
<!-- Windows 10 / 11 -->
|
||||
<supportedOS Id="{8e0f7a12-bfb3-4fe8-b9a5-48fd50a15a9a}" />
|
||||
</application>
|
||||
</compatibility>
|
||||
</assembly>
|
||||
Binary file not shown.
Binary file not shown.
BIN
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
BIN
Binary file not shown.
Binary file not shown.
BIN
Binary file not shown.
Binary file not shown.
BIN
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
BIN
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,580 @@
|
||||
{
|
||||
"runtimeTarget": {
|
||||
"name": ".NETCoreApp,Version=v8.0",
|
||||
"signature": ""
|
||||
},
|
||||
"compilationOptions": {},
|
||||
"targets": {
|
||||
".NETCoreApp,Version=v8.0": {
|
||||
"EarthModelStudio/1.0.3": {
|
||||
"dependencies": {
|
||||
"Avalonia": "11.3.9",
|
||||
"Avalonia.Desktop": "11.3.9",
|
||||
"Avalonia.Themes.Fluent": "11.3.9",
|
||||
"CommunityToolkit.Mvvm": "8.2.2",
|
||||
"EarthModelStudio.ModelSdk": "1.0.3"
|
||||
},
|
||||
"runtime": {
|
||||
"EarthModelStudio.dll": {}
|
||||
}
|
||||
},
|
||||
"Avalonia/11.3.9": {
|
||||
"dependencies": {
|
||||
"Avalonia.Remote.Protocol": "11.3.9",
|
||||
"MicroCom.Runtime": "0.11.0"
|
||||
},
|
||||
"runtime": {
|
||||
"lib/net8.0/Avalonia.Base.dll": {
|
||||
"assemblyVersion": "11.3.9.0",
|
||||
"fileVersion": "11.3.9.0"
|
||||
},
|
||||
"lib/net8.0/Avalonia.Controls.dll": {
|
||||
"assemblyVersion": "11.3.9.0",
|
||||
"fileVersion": "11.3.9.0"
|
||||
},
|
||||
"lib/net8.0/Avalonia.DesignerSupport.dll": {
|
||||
"assemblyVersion": "0.7.0.0",
|
||||
"fileVersion": "0.7.0.0"
|
||||
},
|
||||
"lib/net8.0/Avalonia.Dialogs.dll": {
|
||||
"assemblyVersion": "11.3.9.0",
|
||||
"fileVersion": "11.3.9.0"
|
||||
},
|
||||
"lib/net8.0/Avalonia.Markup.Xaml.dll": {
|
||||
"assemblyVersion": "11.3.9.0",
|
||||
"fileVersion": "11.3.9.0"
|
||||
},
|
||||
"lib/net8.0/Avalonia.Markup.dll": {
|
||||
"assemblyVersion": "11.3.9.0",
|
||||
"fileVersion": "11.3.9.0"
|
||||
},
|
||||
"lib/net8.0/Avalonia.Metal.dll": {
|
||||
"assemblyVersion": "11.3.9.0",
|
||||
"fileVersion": "11.3.9.0"
|
||||
},
|
||||
"lib/net8.0/Avalonia.MicroCom.dll": {
|
||||
"assemblyVersion": "11.3.9.0",
|
||||
"fileVersion": "11.3.9.0"
|
||||
},
|
||||
"lib/net8.0/Avalonia.OpenGL.dll": {
|
||||
"assemblyVersion": "11.3.9.0",
|
||||
"fileVersion": "11.3.9.0"
|
||||
},
|
||||
"lib/net8.0/Avalonia.Vulkan.dll": {
|
||||
"assemblyVersion": "11.3.9.0",
|
||||
"fileVersion": "11.3.9.0"
|
||||
},
|
||||
"lib/net8.0/Avalonia.dll": {
|
||||
"assemblyVersion": "11.3.9.0",
|
||||
"fileVersion": "11.3.9.0"
|
||||
}
|
||||
}
|
||||
},
|
||||
"Avalonia.Angle.Windows.Natives/2.1.25547.20250602": {
|
||||
"runtimeTargets": {
|
||||
"runtimes/win-arm64/native/av_libglesv2.dll": {
|
||||
"rid": "win-arm64",
|
||||
"assetType": "native",
|
||||
"fileVersion": "0.0.0.0"
|
||||
},
|
||||
"runtimes/win-x64/native/av_libglesv2.dll": {
|
||||
"rid": "win-x64",
|
||||
"assetType": "native",
|
||||
"fileVersion": "0.0.0.0"
|
||||
},
|
||||
"runtimes/win-x86/native/av_libglesv2.dll": {
|
||||
"rid": "win-x86",
|
||||
"assetType": "native",
|
||||
"fileVersion": "0.0.0.0"
|
||||
}
|
||||
}
|
||||
},
|
||||
"Avalonia.Desktop/11.3.9": {
|
||||
"dependencies": {
|
||||
"Avalonia": "11.3.9",
|
||||
"Avalonia.Native": "11.3.9",
|
||||
"Avalonia.Skia": "11.3.9",
|
||||
"Avalonia.Win32": "11.3.9",
|
||||
"Avalonia.X11": "11.3.9"
|
||||
},
|
||||
"runtime": {
|
||||
"lib/net8.0/Avalonia.Desktop.dll": {
|
||||
"assemblyVersion": "11.3.9.0",
|
||||
"fileVersion": "11.3.9.0"
|
||||
}
|
||||
}
|
||||
},
|
||||
"Avalonia.FreeDesktop/11.3.9": {
|
||||
"dependencies": {
|
||||
"Avalonia": "11.3.9",
|
||||
"Tmds.DBus.Protocol": "0.21.2"
|
||||
},
|
||||
"runtime": {
|
||||
"lib/net8.0/Avalonia.FreeDesktop.dll": {
|
||||
"assemblyVersion": "11.3.9.0",
|
||||
"fileVersion": "11.3.9.0"
|
||||
}
|
||||
}
|
||||
},
|
||||
"Avalonia.Native/11.3.9": {
|
||||
"dependencies": {
|
||||
"Avalonia": "11.3.9"
|
||||
},
|
||||
"runtime": {
|
||||
"lib/net8.0/Avalonia.Native.dll": {
|
||||
"assemblyVersion": "11.3.9.0",
|
||||
"fileVersion": "11.3.9.0"
|
||||
}
|
||||
},
|
||||
"runtimeTargets": {
|
||||
"runtimes/osx/native/libAvaloniaNative.dylib": {
|
||||
"rid": "osx",
|
||||
"assetType": "native",
|
||||
"fileVersion": "0.0.0.0"
|
||||
}
|
||||
}
|
||||
},
|
||||
"Avalonia.Remote.Protocol/11.3.9": {
|
||||
"runtime": {
|
||||
"lib/net8.0/Avalonia.Remote.Protocol.dll": {
|
||||
"assemblyVersion": "11.3.9.0",
|
||||
"fileVersion": "11.3.9.0"
|
||||
}
|
||||
}
|
||||
},
|
||||
"Avalonia.Skia/11.3.9": {
|
||||
"dependencies": {
|
||||
"Avalonia": "11.3.9",
|
||||
"HarfBuzzSharp": "8.3.1.1",
|
||||
"HarfBuzzSharp.NativeAssets.Linux": "8.3.1.1",
|
||||
"SkiaSharp": "2.88.9",
|
||||
"SkiaSharp.NativeAssets.Linux": "2.88.9"
|
||||
},
|
||||
"runtime": {
|
||||
"lib/net8.0/Avalonia.Skia.dll": {
|
||||
"assemblyVersion": "11.3.9.0",
|
||||
"fileVersion": "11.3.9.0"
|
||||
}
|
||||
}
|
||||
},
|
||||
"Avalonia.Themes.Fluent/11.3.9": {
|
||||
"dependencies": {
|
||||
"Avalonia": "11.3.9"
|
||||
},
|
||||
"runtime": {
|
||||
"lib/net8.0/Avalonia.Themes.Fluent.dll": {
|
||||
"assemblyVersion": "11.3.9.0",
|
||||
"fileVersion": "11.3.9.0"
|
||||
}
|
||||
}
|
||||
},
|
||||
"Avalonia.Win32/11.3.9": {
|
||||
"dependencies": {
|
||||
"Avalonia": "11.3.9",
|
||||
"Avalonia.Angle.Windows.Natives": "2.1.25547.20250602"
|
||||
},
|
||||
"runtime": {
|
||||
"lib/net8.0/Avalonia.Win32.Automation.dll": {
|
||||
"assemblyVersion": "11.3.9.0",
|
||||
"fileVersion": "11.3.9.0"
|
||||
},
|
||||
"lib/net8.0/Avalonia.Win32.dll": {
|
||||
"assemblyVersion": "11.3.9.0",
|
||||
"fileVersion": "11.3.9.0"
|
||||
}
|
||||
}
|
||||
},
|
||||
"Avalonia.X11/11.3.9": {
|
||||
"dependencies": {
|
||||
"Avalonia": "11.3.9",
|
||||
"Avalonia.FreeDesktop": "11.3.9",
|
||||
"Avalonia.Skia": "11.3.9"
|
||||
},
|
||||
"runtime": {
|
||||
"lib/net8.0/Avalonia.X11.dll": {
|
||||
"assemblyVersion": "11.3.9.0",
|
||||
"fileVersion": "11.3.9.0"
|
||||
}
|
||||
}
|
||||
},
|
||||
"CommunityToolkit.Mvvm/8.2.2": {
|
||||
"runtime": {
|
||||
"lib/net6.0/CommunityToolkit.Mvvm.dll": {
|
||||
"assemblyVersion": "8.2.0.0",
|
||||
"fileVersion": "8.2.2.1"
|
||||
}
|
||||
}
|
||||
},
|
||||
"HarfBuzzSharp/8.3.1.1": {
|
||||
"dependencies": {
|
||||
"HarfBuzzSharp.NativeAssets.Win32": "8.3.1.1",
|
||||
"HarfBuzzSharp.NativeAssets.macOS": "8.3.1.1"
|
||||
},
|
||||
"runtime": {
|
||||
"lib/net8.0/HarfBuzzSharp.dll": {
|
||||
"assemblyVersion": "1.0.0.0",
|
||||
"fileVersion": "8.3.1.1"
|
||||
}
|
||||
}
|
||||
},
|
||||
"HarfBuzzSharp.NativeAssets.Linux/8.3.1.1": {
|
||||
"runtimeTargets": {
|
||||
"runtimes/linux-arm/native/libHarfBuzzSharp.so": {
|
||||
"rid": "linux-arm",
|
||||
"assetType": "native",
|
||||
"fileVersion": "0.0.0.0"
|
||||
},
|
||||
"runtimes/linux-arm64/native/libHarfBuzzSharp.so": {
|
||||
"rid": "linux-arm64",
|
||||
"assetType": "native",
|
||||
"fileVersion": "0.0.0.0"
|
||||
},
|
||||
"runtimes/linux-loongarch64/native/libHarfBuzzSharp.so": {
|
||||
"rid": "linux-loongarch64",
|
||||
"assetType": "native",
|
||||
"fileVersion": "0.0.0.0"
|
||||
},
|
||||
"runtimes/linux-musl-arm/native/libHarfBuzzSharp.so": {
|
||||
"rid": "linux-musl-arm",
|
||||
"assetType": "native",
|
||||
"fileVersion": "0.0.0.0"
|
||||
},
|
||||
"runtimes/linux-musl-arm64/native/libHarfBuzzSharp.so": {
|
||||
"rid": "linux-musl-arm64",
|
||||
"assetType": "native",
|
||||
"fileVersion": "0.0.0.0"
|
||||
},
|
||||
"runtimes/linux-musl-loongarch64/native/libHarfBuzzSharp.so": {
|
||||
"rid": "linux-musl-loongarch64",
|
||||
"assetType": "native",
|
||||
"fileVersion": "0.0.0.0"
|
||||
},
|
||||
"runtimes/linux-musl-riscv64/native/libHarfBuzzSharp.so": {
|
||||
"rid": "linux-musl-riscv64",
|
||||
"assetType": "native",
|
||||
"fileVersion": "0.0.0.0"
|
||||
},
|
||||
"runtimes/linux-musl-x64/native/libHarfBuzzSharp.so": {
|
||||
"rid": "linux-musl-x64",
|
||||
"assetType": "native",
|
||||
"fileVersion": "0.0.0.0"
|
||||
},
|
||||
"runtimes/linux-riscv64/native/libHarfBuzzSharp.so": {
|
||||
"rid": "linux-riscv64",
|
||||
"assetType": "native",
|
||||
"fileVersion": "0.0.0.0"
|
||||
},
|
||||
"runtimes/linux-x64/native/libHarfBuzzSharp.so": {
|
||||
"rid": "linux-x64",
|
||||
"assetType": "native",
|
||||
"fileVersion": "0.0.0.0"
|
||||
},
|
||||
"runtimes/linux-x86/native/libHarfBuzzSharp.so": {
|
||||
"rid": "linux-x86",
|
||||
"assetType": "native",
|
||||
"fileVersion": "0.0.0.0"
|
||||
}
|
||||
}
|
||||
},
|
||||
"HarfBuzzSharp.NativeAssets.macOS/8.3.1.1": {
|
||||
"runtimeTargets": {
|
||||
"runtimes/osx/native/libHarfBuzzSharp.dylib": {
|
||||
"rid": "osx",
|
||||
"assetType": "native",
|
||||
"fileVersion": "0.0.0.0"
|
||||
}
|
||||
}
|
||||
},
|
||||
"HarfBuzzSharp.NativeAssets.Win32/8.3.1.1": {
|
||||
"runtimeTargets": {
|
||||
"runtimes/win-arm64/native/libHarfBuzzSharp.dll": {
|
||||
"rid": "win-arm64",
|
||||
"assetType": "native",
|
||||
"fileVersion": "0.0.0.0"
|
||||
},
|
||||
"runtimes/win-x64/native/libHarfBuzzSharp.dll": {
|
||||
"rid": "win-x64",
|
||||
"assetType": "native",
|
||||
"fileVersion": "0.0.0.0"
|
||||
},
|
||||
"runtimes/win-x86/native/libHarfBuzzSharp.dll": {
|
||||
"rid": "win-x86",
|
||||
"assetType": "native",
|
||||
"fileVersion": "0.0.0.0"
|
||||
}
|
||||
}
|
||||
},
|
||||
"MicroCom.Runtime/0.11.0": {
|
||||
"runtime": {
|
||||
"lib/net5.0/MicroCom.Runtime.dll": {
|
||||
"assemblyVersion": "0.11.0.0",
|
||||
"fileVersion": "0.11.0.0"
|
||||
}
|
||||
}
|
||||
},
|
||||
"SkiaSharp/2.88.9": {
|
||||
"dependencies": {
|
||||
"SkiaSharp.NativeAssets.Win32": "2.88.9",
|
||||
"SkiaSharp.NativeAssets.macOS": "2.88.9"
|
||||
},
|
||||
"runtime": {
|
||||
"lib/net6.0/SkiaSharp.dll": {
|
||||
"assemblyVersion": "2.88.0.0",
|
||||
"fileVersion": "2.88.9.0"
|
||||
}
|
||||
}
|
||||
},
|
||||
"SkiaSharp.NativeAssets.Linux/2.88.9": {
|
||||
"dependencies": {
|
||||
"SkiaSharp": "2.88.9"
|
||||
},
|
||||
"runtimeTargets": {
|
||||
"runtimes/linux-arm/native/libSkiaSharp.so": {
|
||||
"rid": "linux-arm",
|
||||
"assetType": "native",
|
||||
"fileVersion": "0.0.0.0"
|
||||
},
|
||||
"runtimes/linux-arm64/native/libSkiaSharp.so": {
|
||||
"rid": "linux-arm64",
|
||||
"assetType": "native",
|
||||
"fileVersion": "0.0.0.0"
|
||||
},
|
||||
"runtimes/linux-musl-x64/native/libSkiaSharp.so": {
|
||||
"rid": "linux-musl-x64",
|
||||
"assetType": "native",
|
||||
"fileVersion": "0.0.0.0"
|
||||
},
|
||||
"runtimes/linux-x64/native/libSkiaSharp.so": {
|
||||
"rid": "linux-x64",
|
||||
"assetType": "native",
|
||||
"fileVersion": "0.0.0.0"
|
||||
}
|
||||
}
|
||||
},
|
||||
"SkiaSharp.NativeAssets.macOS/2.88.9": {
|
||||
"runtimeTargets": {
|
||||
"runtimes/osx/native/libSkiaSharp.dylib": {
|
||||
"rid": "osx",
|
||||
"assetType": "native",
|
||||
"fileVersion": "0.0.0.0"
|
||||
}
|
||||
}
|
||||
},
|
||||
"SkiaSharp.NativeAssets.Win32/2.88.9": {
|
||||
"runtimeTargets": {
|
||||
"runtimes/win-arm64/native/libSkiaSharp.dll": {
|
||||
"rid": "win-arm64",
|
||||
"assetType": "native",
|
||||
"fileVersion": "0.0.0.0"
|
||||
},
|
||||
"runtimes/win-x64/native/libSkiaSharp.dll": {
|
||||
"rid": "win-x64",
|
||||
"assetType": "native",
|
||||
"fileVersion": "0.0.0.0"
|
||||
},
|
||||
"runtimes/win-x86/native/libSkiaSharp.dll": {
|
||||
"rid": "win-x86",
|
||||
"assetType": "native",
|
||||
"fileVersion": "0.0.0.0"
|
||||
}
|
||||
}
|
||||
},
|
||||
"System.IO.Pipelines/8.0.0": {
|
||||
"runtime": {
|
||||
"lib/net8.0/System.IO.Pipelines.dll": {
|
||||
"assemblyVersion": "8.0.0.0",
|
||||
"fileVersion": "8.0.23.53103"
|
||||
}
|
||||
}
|
||||
},
|
||||
"Tmds.DBus.Protocol/0.21.2": {
|
||||
"dependencies": {
|
||||
"System.IO.Pipelines": "8.0.0"
|
||||
},
|
||||
"runtime": {
|
||||
"lib/net8.0/Tmds.DBus.Protocol.dll": {
|
||||
"assemblyVersion": "0.21.2.0",
|
||||
"fileVersion": "0.21.2.0"
|
||||
}
|
||||
}
|
||||
},
|
||||
"EarthModelStudio.ModelSdk/1.0.3": {
|
||||
"dependencies": {
|
||||
"Avalonia": "11.3.9"
|
||||
},
|
||||
"runtime": {
|
||||
"EarthModelStudio.ModelSdk.dll": {
|
||||
"assemblyVersion": "1.0.3.0",
|
||||
"fileVersion": "1.0.3.0"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"libraries": {
|
||||
"EarthModelStudio/1.0.3": {
|
||||
"type": "project",
|
||||
"serviceable": false,
|
||||
"sha512": ""
|
||||
},
|
||||
"Avalonia/11.3.9": {
|
||||
"type": "package",
|
||||
"serviceable": true,
|
||||
"sha512": "sha512-YfaTrUxcmVTsGOw2YqdZyunHqZArK16m1pYfNIBvyvAgX89Pzd3A1PgoMkf64u7scL23IN6HkfqhZeFcbYWLoA==",
|
||||
"path": "avalonia/11.3.9",
|
||||
"hashPath": "avalonia.11.3.9.nupkg.sha512"
|
||||
},
|
||||
"Avalonia.Angle.Windows.Natives/2.1.25547.20250602": {
|
||||
"type": "package",
|
||||
"serviceable": true,
|
||||
"sha512": "sha512-ZL0VLc4s9rvNNFt19Pxm5UNAkmKNylugAwJPX9ulXZ6JWs/l6XZihPWWTyezaoNOVyEPU8YbURtW7XMAtqXH5A==",
|
||||
"path": "avalonia.angle.windows.natives/2.1.25547.20250602",
|
||||
"hashPath": "avalonia.angle.windows.natives.2.1.25547.20250602.nupkg.sha512"
|
||||
},
|
||||
"Avalonia.Desktop/11.3.9": {
|
||||
"type": "package",
|
||||
"serviceable": true,
|
||||
"sha512": "sha512-zOHbAssjjLz85a2RONK2UMfV/uqMtot9lxcUrSrwa3SneEm8ALeg6Pewc0u/YqvVRI5pyTm4HCtN9w5yRK0uZg==",
|
||||
"path": "avalonia.desktop/11.3.9",
|
||||
"hashPath": "avalonia.desktop.11.3.9.nupkg.sha512"
|
||||
},
|
||||
"Avalonia.FreeDesktop/11.3.9": {
|
||||
"type": "package",
|
||||
"serviceable": true,
|
||||
"sha512": "sha512-PLFQTyzo9T7PpFgE0vYgWjxOXAKwStUxMDdLZAw3vaczKBheUNj2sINiFo60dYPMbW9f2yAVHfHcnReRsjuLDg==",
|
||||
"path": "avalonia.freedesktop/11.3.9",
|
||||
"hashPath": "avalonia.freedesktop.11.3.9.nupkg.sha512"
|
||||
},
|
||||
"Avalonia.Native/11.3.9": {
|
||||
"type": "package",
|
||||
"serviceable": true,
|
||||
"sha512": "sha512-l8hIlbLOMRVPM0RPX1Er+qnhoGi8TcfTe60f7sxsAbVbvVFC1hdzCya0SyU+F2nWLoFH8AF2/KRPbkM2f4OjXw==",
|
||||
"path": "avalonia.native/11.3.9",
|
||||
"hashPath": "avalonia.native.11.3.9.nupkg.sha512"
|
||||
},
|
||||
"Avalonia.Remote.Protocol/11.3.9": {
|
||||
"type": "package",
|
||||
"serviceable": true,
|
||||
"sha512": "sha512-2XVLTSNa+Nvwu4D8NqqdudhllTaCRA9ZKlLZZvYLZeuLlzg7OcAV+df/biHQc6AqOv7iMFR9K5Zt3wG0EF4KfQ==",
|
||||
"path": "avalonia.remote.protocol/11.3.9",
|
||||
"hashPath": "avalonia.remote.protocol.11.3.9.nupkg.sha512"
|
||||
},
|
||||
"Avalonia.Skia/11.3.9": {
|
||||
"type": "package",
|
||||
"serviceable": true,
|
||||
"sha512": "sha512-8Jg1D9RxL377uUz8kiJcgvTfc/jQKF1jvNTkih+lRFmjMA8ZdLt4ZB5E6Yd6lIRH25DbE/4+oHe8pKHey3LfgQ==",
|
||||
"path": "avalonia.skia/11.3.9",
|
||||
"hashPath": "avalonia.skia.11.3.9.nupkg.sha512"
|
||||
},
|
||||
"Avalonia.Themes.Fluent/11.3.9": {
|
||||
"type": "package",
|
||||
"serviceable": true,
|
||||
"sha512": "sha512-XSgQxSRKgK/yNhkKa1rGuEUDISi+VNxwoj1pq4JUhFd1XXk/dqGsc4MfESItwTyGEYJH+HDbWfWEPVDDxAfUJg==",
|
||||
"path": "avalonia.themes.fluent/11.3.9",
|
||||
"hashPath": "avalonia.themes.fluent.11.3.9.nupkg.sha512"
|
||||
},
|
||||
"Avalonia.Win32/11.3.9": {
|
||||
"type": "package",
|
||||
"serviceable": true,
|
||||
"sha512": "sha512-gWOlzYCO1278eRwnvlmGd346nUgWu30MetwfMmBZ4flQrjoQNXB5rUrpQxLS1egyvpupkeUSFDuyJSK/qqcX/g==",
|
||||
"path": "avalonia.win32/11.3.9",
|
||||
"hashPath": "avalonia.win32.11.3.9.nupkg.sha512"
|
||||
},
|
||||
"Avalonia.X11/11.3.9": {
|
||||
"type": "package",
|
||||
"serviceable": true,
|
||||
"sha512": "sha512-YurSHKV585ydR7CaifcHroY2ujZJR4LZpDtHW9KOCowMcFhbzXNSI0unxAyF5nMQbzg96Itl4gopDX7LulzuLg==",
|
||||
"path": "avalonia.x11/11.3.9",
|
||||
"hashPath": "avalonia.x11.11.3.9.nupkg.sha512"
|
||||
},
|
||||
"CommunityToolkit.Mvvm/8.2.2": {
|
||||
"type": "package",
|
||||
"serviceable": true,
|
||||
"sha512": "sha512-r0g0k9tGYdrnz8R7T3x5UiokDffeevzK/2P/9SBL6fqLgN8B157MIi/bVUWI1KAz6ZorZrK9AdABCWUeXZZsvA==",
|
||||
"path": "communitytoolkit.mvvm/8.2.2",
|
||||
"hashPath": "communitytoolkit.mvvm.8.2.2.nupkg.sha512"
|
||||
},
|
||||
"HarfBuzzSharp/8.3.1.1": {
|
||||
"type": "package",
|
||||
"serviceable": true,
|
||||
"sha512": "sha512-tLZN66oe/uiRPTZfrCU4i8ScVGwqHNh5MHrXj0yVf4l7Mz0FhTGnQ71RGySROTmdognAs0JtluHkL41pIabWuQ==",
|
||||
"path": "harfbuzzsharp/8.3.1.1",
|
||||
"hashPath": "harfbuzzsharp.8.3.1.1.nupkg.sha512"
|
||||
},
|
||||
"HarfBuzzSharp.NativeAssets.Linux/8.3.1.1": {
|
||||
"type": "package",
|
||||
"serviceable": true,
|
||||
"sha512": "sha512-3EZ1mpIiKWRLL5hUYA82ZHteeDIVaEA/Z0rA/wU6tjx6crcAkJnBPwDXZugBSfo8+J3EznvRJf49uMsqYfKrHg==",
|
||||
"path": "harfbuzzsharp.nativeassets.linux/8.3.1.1",
|
||||
"hashPath": "harfbuzzsharp.nativeassets.linux.8.3.1.1.nupkg.sha512"
|
||||
},
|
||||
"HarfBuzzSharp.NativeAssets.macOS/8.3.1.1": {
|
||||
"type": "package",
|
||||
"serviceable": true,
|
||||
"sha512": "sha512-jbtCsgftcaFLCA13tVKo5iWdElJScrulLTKJre36O4YQTIlwDtPPqhRZNk+Y0vv4D1gxbscasGRucUDfS44ofQ==",
|
||||
"path": "harfbuzzsharp.nativeassets.macos/8.3.1.1",
|
||||
"hashPath": "harfbuzzsharp.nativeassets.macos.8.3.1.1.nupkg.sha512"
|
||||
},
|
||||
"HarfBuzzSharp.NativeAssets.Win32/8.3.1.1": {
|
||||
"type": "package",
|
||||
"serviceable": true,
|
||||
"sha512": "sha512-UsJtQsfAJoFDZrXc4hCUfRPMqccfKZ0iumJ/upcUjz/cmsTgVFGNEL5yaJWmkqsuFYdMWbj/En5/kS4PFl9hBA==",
|
||||
"path": "harfbuzzsharp.nativeassets.win32/8.3.1.1",
|
||||
"hashPath": "harfbuzzsharp.nativeassets.win32.8.3.1.1.nupkg.sha512"
|
||||
},
|
||||
"MicroCom.Runtime/0.11.0": {
|
||||
"type": "package",
|
||||
"serviceable": true,
|
||||
"sha512": "sha512-MEnrZ3UIiH40hjzMDsxrTyi8dtqB5ziv3iBeeU4bXsL/7NLSal9F1lZKpK+tfBRnUoDSdtcW3KufE4yhATOMCA==",
|
||||
"path": "microcom.runtime/0.11.0",
|
||||
"hashPath": "microcom.runtime.0.11.0.nupkg.sha512"
|
||||
},
|
||||
"SkiaSharp/2.88.9": {
|
||||
"type": "package",
|
||||
"serviceable": true,
|
||||
"sha512": "sha512-3MD5VHjXXieSHCleRLuaTXmL2pD0mB7CcOB1x2kA1I4bhptf4e3R27iM93264ZYuAq6mkUyX5XbcxnZvMJYc1Q==",
|
||||
"path": "skiasharp/2.88.9",
|
||||
"hashPath": "skiasharp.2.88.9.nupkg.sha512"
|
||||
},
|
||||
"SkiaSharp.NativeAssets.Linux/2.88.9": {
|
||||
"type": "package",
|
||||
"serviceable": true,
|
||||
"sha512": "sha512-cWSaJKVPWAaT/WIn9c8T5uT/l4ETwHxNJTkEOtNKjphNo8AW6TF9O32aRkxqw3l8GUdUo66Bu7EiqtFh/XG0Zg==",
|
||||
"path": "skiasharp.nativeassets.linux/2.88.9",
|
||||
"hashPath": "skiasharp.nativeassets.linux.2.88.9.nupkg.sha512"
|
||||
},
|
||||
"SkiaSharp.NativeAssets.macOS/2.88.9": {
|
||||
"type": "package",
|
||||
"serviceable": true,
|
||||
"sha512": "sha512-Nv5spmKc4505Ep7oUoJ5vp3KweFpeNqxpyGDWyeEPTX2uR6S6syXIm3gj75dM0YJz7NPvcix48mR5laqs8dPuA==",
|
||||
"path": "skiasharp.nativeassets.macos/2.88.9",
|
||||
"hashPath": "skiasharp.nativeassets.macos.2.88.9.nupkg.sha512"
|
||||
},
|
||||
"SkiaSharp.NativeAssets.Win32/2.88.9": {
|
||||
"type": "package",
|
||||
"serviceable": true,
|
||||
"sha512": "sha512-wb2kYgU7iy84nQLYZwMeJXixvK++GoIuECjU4ECaUKNuflyRlJKyiRhN1MAHswvlvzuvkrjRWlK0Za6+kYQK7w==",
|
||||
"path": "skiasharp.nativeassets.win32/2.88.9",
|
||||
"hashPath": "skiasharp.nativeassets.win32.2.88.9.nupkg.sha512"
|
||||
},
|
||||
"System.IO.Pipelines/8.0.0": {
|
||||
"type": "package",
|
||||
"serviceable": true,
|
||||
"sha512": "sha512-FHNOatmUq0sqJOkTx+UF/9YK1f180cnW5FVqnQMvYUN0elp6wFzbtPSiqbo1/ru8ICp43JM1i7kKkk6GsNGHlA==",
|
||||
"path": "system.io.pipelines/8.0.0",
|
||||
"hashPath": "system.io.pipelines.8.0.0.nupkg.sha512"
|
||||
},
|
||||
"Tmds.DBus.Protocol/0.21.2": {
|
||||
"type": "package",
|
||||
"serviceable": true,
|
||||
"sha512": "sha512-ScSMrUrrw8px4kK1Glh0fZv/HQUlg1078bNXNPfRPKQ3WbRzV9HpsydYEOgSoMK5LWICMf2bMwIFH0pGjxjcMA==",
|
||||
"path": "tmds.dbus.protocol/0.21.2",
|
||||
"hashPath": "tmds.dbus.protocol.0.21.2.nupkg.sha512"
|
||||
},
|
||||
"EarthModelStudio.ModelSdk/1.0.3": {
|
||||
"type": "project",
|
||||
"serviceable": false,
|
||||
"sha512": ""
|
||||
}
|
||||
}
|
||||
}
|
||||
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"runtimeOptions": {
|
||||
"tfm": "net8.0",
|
||||
"framework": {
|
||||
"name": "Microsoft.NETCore.App",
|
||||
"version": "8.0.0"
|
||||
},
|
||||
"configProperties": {
|
||||
"System.Globalization.Invariant": false,
|
||||
"System.Runtime.InteropServices.BuiltInComInterop.IsSupported": true,
|
||||
"System.Runtime.Serialization.EnableUnsafeBinaryFormatterSerialization": false
|
||||
}
|
||||
}
|
||||
}
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Executable
BIN
Binary file not shown.
Executable
BIN
Binary file not shown.
Executable
BIN
Binary file not shown.
Executable
BIN
Binary file not shown.
BIN
Binary file not shown.
src/main/dotnet/EarthModelStudio/bin/Debug/net8.0/runtimes/linux-musl-arm/native/libHarfBuzzSharp.so
Executable
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
src/main/dotnet/EarthModelStudio/bin/Debug/net8.0/runtimes/linux-musl-x64/native/libHarfBuzzSharp.so
Executable
BIN
Binary file not shown.
Executable
BIN
Binary file not shown.
Executable
BIN
Binary file not shown.
Executable
BIN
Binary file not shown.
Executable
BIN
Binary file not shown.
Loaded 100 of 1125 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user