This commit is contained in:
2509_92447106 committed 2026-11-07 16:05:56 +08:00
commit 60113ab76e
81 files changed
+8520

No files matched your search

@@ -0,0 +1,28 @@
<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>
</Application.DataTemplates>
<Application.Resources>
<Color x:Key="SystemAccentColor">#2F6BFF</Color>
</Application.Resources>
<Application.Styles>
<FluentTheme />
<StyleInclude Source="avares://EarthModelStudio/Styles/AppTheme.axaml" />
</Application.Styles>
</Application>
@@ -0,0 +1,70 @@
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);
};
desktop.MainWindow = window;
desktop.ShutdownMode = ShutdownMode.OnMainWindowClose;
}
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,139 @@
{
"app.name": "Earth Model Studio",
"app.tagline": "Astronomy teaching models · visual launcher",
"app.version": "Version",
"app.platform": "Platform",
"nav.home": "Home",
"nav.download": "Download",
"nav.settings": "Settings",
"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": "Import a model source on the Download page, or drop a model folder into model/.",
"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.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": "Offline build — update by replacing the app folder.",
"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,139 @@
{
"app.name": "地球模型工作室",
"app.tagline": "天文教学模型 · 可视化启动器",
"app.version": "版本",
"app.platform": "平台",
"nav.home": "主页",
"nav.download": "下载",
"nav.settings": "设置",
"home.title": "模型库",
"home.subtitle": "选择模型,用可交互的三维演示讲清自转、公转与四季成因。",
"home.launch": "启动模型",
"home.download": "下载模型",
"home.settings": "设置",
"home.installed": "已安装模型",
"home.count": "{0} 个模型",
"home.empty": "模型库还是空的",
"home.emptyHint": "在「下载」页从链接导入模型源,或把模型直接放进 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.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": "当前为离线构建,更新请替换程序目录。",
"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,55 @@
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</summary>
public int RenderFps { get; set; } = 30;
/// <summary>启动时运行内存分配(MB)——决定场景缓存/纹理预算。</summary>
public int MemoryMb { get; set; } = 2048;
/// <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>模型源:一个满足 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/&lt;id&gt;/&lt;id&gt;.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>相对 &lt;id&gt;.model 目录的入口文件,默认 scene.json</summary>
public string? Entry { get; set; }
/// <summary>模型自带的界面程序集(相对 &lt;id&gt;.model),默认 &lt;id&gt;.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,15 @@
using System;
using Avalonia;
namespace EarthModelStudio;
internal static class Program
{
[STAThread]
public static void Main(string[] args) => BuildAvaloniaApp().StartWithClassicDesktopLifetime(args);
public static AppBuilder BuildAvaloniaApp()
=> AppBuilder.Configure<App>()
.UsePlatformDetect()
.LogToTrace();
}
@@ -0,0 +1,93 @@
using System;
using System.IO;
namespace EarthModelStudio.Services;
/// <summary>
/// 目录探测。启动器本身不含任何模型数据,模型一律从外部模型库目录读取:
/// 1) 开发态:从 bin 目录向上找到 EarthModelStudio.sln,模型库用仓库根 model/
/// 2) 绿色态:可执行文件旁边有 model/ 目录(发布包默认只建空目录)
/// 3) 安装态:模型库放到用户数据目录
/// 也可用环境变量 EMS_HOME / EMS_MODELS 显式指定。
/// </summary>
public sealed class AppPaths
{
public string AppRoot { get; private init; } = "";
public string ModelRoot { get; private init; } = "";
public string DataRoot { get; private init; } = "";
public bool IsPortableModelRoot { get; private init; }
public string CacheRoot => Path.Combine(DataRoot, "cache");
public string SettingsFile => Path.Combine(DataRoot, "settings.json");
public static AppPaths Discover()
{
var baseDir = AppContext.BaseDirectory.TrimEnd(Path.DirectorySeparatorChar);
var dataRoot = Environment.GetEnvironmentVariable("EMS_DATA")
?? Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
"EarthModelStudio");
// 显式指定模型库(模型是外置数据,可放在任意磁盘/网络盘)
var envModels = Environment.GetEnvironmentVariable("EMS_MODELS");
if (!string.IsNullOrWhiteSpace(envModels))
{
return new AppPaths
{
AppRoot = baseDir,
ModelRoot = envModels!,
DataRoot = dataRoot,
IsPortableModelRoot = false
};
}
var repoRoot = Environment.GetEnvironmentVariable("EMS_HOME");
if (string.IsNullOrWhiteSpace(repoRoot) || !Directory.Exists(repoRoot))
repoRoot = FindRepoRoot(baseDir);
var exeModelDir = Path.Combine(baseDir, "model");
string appRoot, modelRoot;
bool portable = false;
if (!string.IsNullOrEmpty(repoRoot) && Directory.Exists(Path.Combine(repoRoot!, "model")))
{
appRoot = repoRoot!;
modelRoot = Path.Combine(appRoot, "model");
}
else if (Directory.Exists(exeModelDir))
{
appRoot = baseDir;
modelRoot = exeModelDir;
portable = true;
}
else
{
appRoot = baseDir;
modelRoot = Path.Combine(dataRoot, "model");
}
return new AppPaths
{
AppRoot = appRoot,
ModelRoot = modelRoot,
DataRoot = dataRoot,
IsPortableModelRoot = portable
};
}
private static string? FindRepoRoot(string start)
{
var dir = new DirectoryInfo(start);
for (var i = 0; i < 10 && dir != null; i++, dir = dir.Parent)
{
if (File.Exists(Path.Combine(dir.FullName, "EarthModelStudio.sln"))) return dir.FullName;
}
return null;
}
public void EnsureCreated()
{
Directory.CreateDirectory(DataRoot);
Directory.CreateDirectory(CacheRoot);
Directory.CreateDirectory(ModelRoot);
}
}
@@ -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; }
private AppServices(AppPaths paths)
{
Paths = paths;
Settings = new SettingsService(paths);
Models = new ModelRepository(paths);
Sources = new ModelSourceClient(paths);
Downloads = new DownloadCenter(paths, Models);
Memory = new MemoryBudget();
ModelHost = new ModelHost(paths, Settings, Memory);
}
public static AppServices Create()
{
var paths = AppPaths.Discover();
paths.EnsureCreated();
var services = new AppServices(paths);
services.Settings.Load();
L.I.Initialize(services.Settings.Current.Language);
services.Memory.Apply(services.Settings.Current.MemoryMb);
Current = services;
return services;
}
public static AppServices Ensure()
{
if (Current == null) Create();
return Current;
}
}
@@ -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,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,141 @@
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)));
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,30 @@
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>内存情况变化(例如模型窗口开关)时刷新展示。</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,233 @@
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;
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,71 @@
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);
var dest = Path.Combine(staging, 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));
}
if (Directory.Exists(target))
{
var backup = target + ".old";
if (Directory.Exists(backup)) Directory.Delete(backup, true);
Directory.Move(target, backup);
Directory.Move(staging, target);
try { Directory.Delete(backup, true); } catch { }
}
else
{
Directory.Move(staging, target);
}
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/&lt;id&gt;/&lt;id&gt;.json + &lt;id&gt;.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/&lt;id&gt;。
/// </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);
ZipFile.ExtractToDirectory(zipPath, extractDir, true);
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,64 @@
using System;
using System.Collections.Generic;
using System.IO;
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();
if (Current.Sources.Count == 0) SeedSources();
if (Current.MemoryMb < 256) Current.MemoryMb = 2048;
}
/// <summary>
/// 首次启动不预置任何模型源:启动器只做适配,模型内容由用户从链接导入。
/// 这里只给一条空的自定义源占位。
/// </summary>
private void SeedSources()
{
Current.Sources.Add(new ModelSource
{
Id = "custom",
Name = "自定义源",
Url = "",
Enabled = false
});
Save();
}
public void Save()
{
try
{
Json.Write(_paths.SettingsFile, Current);
}
catch (Exception ex)
{
Console.Error.WriteLine($"保存设置失败: {ex.Message}");
}
}
public void Apply(Action<AppSettings> mutate)
{
mutate(Current);
Save();
Changed?.Invoke();
}
public void Notify()
{
Save();
Changed?.Invoke();
}
}
@@ -0,0 +1,30 @@
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);
var info = new ProcessStartInfo
{
FileName = OperatingSystem.IsWindows() ? "explorer.exe"
: OperatingSystem.IsMacOS() ? "open"
: "xdg-open",
UseShellExecute = false
};
info.ArgumentList.Add(path);
Process.Start(info);
}
catch (Exception ex)
{
Console.Error.WriteLine($"打开目录失败: {ex.Message}");
}
}
}
@@ -0,0 +1,249 @@
<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>
</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>
<!-- 按钮 -->
<!-- 全局过渡:悬停、选中、进度都不再「啪」地跳变 -->
<Style Selector="Button /template/ ContentPresenter#PART_ContentPresenter">
<Setter Property="Transitions">
<Transitions>
<BrushTransition Property="Background" Duration="0:0:0.14" />
<BrushTransition Property="BorderBrush" Duration="0:0:0.14" />
<BrushTransition Property="Foreground" Duration="0:0:0.14" />
</Transitions>
</Setter>
</Style>
<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>
<TransformOperationsTransition Property="RenderTransform" Duration="0:0:0.12" />
</Transitions>
</Setter>
</Style>
<Style Selector="Button:pointerover">
<Setter Property="RenderTransform" Value="translateY(-1px)" />
</Style>
<Style Selector="Button:pressed">
<Setter Property="RenderTransform" Value="translateY(1px)" />
</Style>
<Style Selector="Button.primary">
<Setter Property="Foreground" Value="White" />
</Style>
<Style Selector="Button.primary /template/ ContentPresenter#PART_ContentPresenter">
<Setter Property="Background" Value="{DynamicResource Accent}" />
<Setter Property="BorderBrush" Value="{DynamicResource Accent}" />
<Setter Property="Foreground" Value="White" />
<Setter Property="CornerRadius" Value="9" />
</Style>
<Style Selector="Button.primary:pointerover /template/ ContentPresenter#PART_ContentPresenter">
<Setter Property="Background" Value="{DynamicResource AccentDark}" />
<Setter Property="BorderBrush" Value="{DynamicResource AccentDark}" />
<Setter Property="Foreground" Value="White" />
</Style>
<Style Selector="Button.ghost">
<Setter Property="Background" Value="Transparent" />
<Setter Property="BorderThickness" Value="0" />
<Setter Property="Foreground" Value="{DynamicResource InkDim}" />
</Style>
<Style Selector="Button.ghost /template/ ContentPresenter#PART_ContentPresenter">
<Setter Property="Background" Value="Transparent" />
<Setter Property="BorderThickness" Value="0" />
</Style>
<Style Selector="Button.ghost:pointerover /template/ ContentPresenter#PART_ContentPresenter">
<Setter Property="Background" Value="#EEF2FA" />
</Style>
<Style Selector="Button.danger">
<Setter Property="Foreground" Value="{DynamicResource Danger}" />
</Style>
<Style Selector="Button.danger:pointerover /template/ ContentPresenter#PART_ContentPresenter">
<Setter Property="Background" Value="#FDECEC" />
<Setter Property="Foreground" Value="{DynamicResource Danger}" />
</Style>
<Style Selector="Button.small">
<Setter Property="FontSize" Value="12" />
<Setter Property="Padding" Value="10,4" />
<Setter Property="MinHeight" Value="28" />
<Setter Property="CornerRadius" Value="8" />
</Style>
<Style Selector="Button.onDark">
<Setter Property="Background" Value="#1B2740" />
<Setter Property="BorderBrush" Value="#2A3A57" />
<Setter Property="Foreground" Value="#DCE7FA" />
</Style>
<Style Selector="Button.onDark:pointerover /template/ ContentPresenter#PART_ContentPresenter">
<Setter Property="Background" Value="#233351" />
</Style>
<Style Selector="Button.onDark.active /template/ ContentPresenter#PART_ContentPresenter">
<Setter Property="Background" Value="{DynamicResource Accent}" />
<Setter Property="Foreground" Value="White" />
</Style>
<!-- 侧栏 -->
<Style Selector="Button.nav">
<Setter Property="HorizontalAlignment" Value="Stretch" />
<Setter Property="HorizontalContentAlignment" Value="Left" />
<Setter Property="Background" Value="Transparent" />
<Setter Property="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 /template/ ContentPresenter#PART_ContentPresenter">
<Setter Property="Background" Value="Transparent" />
<Setter Property="BorderThickness" Value="0" />
</Style>
<Style Selector="Button.nav:pointerover /template/ ContentPresenter#PART_ContentPresenter">
<Setter Property="Background" Value="#16213A" />
<Setter Property="Foreground" Value="#E8EFFF" />
</Style>
<Style Selector="Button.nav.active /template/ ContentPresenter#PART_ContentPresenter">
<Setter Property="Background" Value="#1C2C4C" />
<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>
</Styles>
@@ -0,0 +1,372 @@
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;
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)
{
_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;
IsBusy = true;
StatusMessage = L.I["dl.syncing"];
try
{
var index = await _services.Sources.FetchAsync(source.Model, force, null, CancellationToken.None);
if (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 (Exception ex)
{
StatusMessage = ex.Message;
}
finally
{
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);
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,87 @@
using System;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using EarthModelStudio.Models;
using EarthModelStudio.Services;
using EarthModelStudio.ViewModels;
namespace EarthModelStudio.ViewModels;
public partial class MainViewModel : ObservableObject
{
private readonly AppServices _services;
public HomeViewModel Home { get; }
public DownloadViewModel Download { get; }
public SettingsViewModel Settings { 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;
/// <summary>由主窗口注入的确认对话框。</summary>
public Func<string, Task<bool>>? ConfirmHandler { get; set; }
/// <summary>
/// 请求为新模型开一个独立窗口。真正创建窗口的是主窗口,
/// 因此同一个模型可以同时开多份,主界面也不会被替换。
/// </summary>
public event Action<ModelPackage>? PlayerRequested;
public string VersionText => "v1.0.0";
public string PlatformText => RuntimeInformation.RuntimeIdentifier;
public MainViewModel(AppServices services)
{
_services = services;
Models = services.ModelHost;
Home = new HomeViewModel(services, this);
Download = new DownloadViewModel(services, this);
Settings = new SettingsViewModel(services);
Current = Home;
}
partial void OnCurrentChanged(ObservableObject value)
{
IsHomeActive = value is HomeViewModel;
IsDownloadActive = value is DownloadViewModel;
IsSettingsActive = value is SettingsViewModel;
}
[RelayCommand]
public void GoHome()
{
Home.Refresh();
Current = Home;
}
[RelayCommand]
public void GoDownload()
{
Current = Download;
Download.OnShown();
}
[RelayCommand]
public void GoSettings()
{
Settings.Refresh();
Current = Settings;
}
/// <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);
}
@@ -0,0 +1,176 @@
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 };
[ObservableProperty] private LanguageOption? _selectedLanguage;
[ObservableProperty] private int _selectedFps = 30;
[ObservableProperty] private double _memoryValue = 2048;
[ObservableProperty] private string _statusMessage = "";
public string MemoryValueText => $"{(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;
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));
}
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));
}
[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)
{
_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;
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,19 @@
<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="{DynamicResource Surface}">
<StackPanel Margin="24,20,24,20" Spacing="14">
<TextBlock Classes="h2" Text="{loc:Loc common.confirmTitle}" />
<TextBlock x:Name="MessageText" Classes="muted" TextWrapping="Wrap" />
<StackPanel Orientation="Horizontal" HorizontalAlignment="Right" Spacing="8" Margin="0,6,0,0">
<Button Content="{loc:Loc common.cancel}" Click="OnCancel" />
<Button Classes="primary" Content="{loc:Loc common.confirm}" Click="OnConfirm" />
</StackPanel>
</StackPanel>
</Window>
@@ -0,0 +1,21 @@
using Avalonia.Controls;
using Avalonia.Interactivity;
using Avalonia.Markup.Xaml;
namespace EarthModelStudio.Views;
public partial class ConfirmWindow : Window
{
public ConfirmWindow() : this("") { }
public ConfirmWindow(string message)
{
AvaloniaXamlLoader.Load(this);
var text = this.FindControl<TextBlock>("MessageText");
if (text != null) text.Text = message;
}
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="✕"
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,50 @@
<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="{DynamicResource AppBg}"
WindowStartupLocation="CenterScreen">
<Grid ColumnDefinitions="236,*">
<!-- 侧栏 -->
<Border Grid.Column="0" Background="{DynamicResource SideBg}">
<Grid RowDefinitions="Auto,*,Auto" Margin="16,22,16,18">
<StackPanel Orientation="Horizontal" Spacing="11">
<Border Width="38" Height="38" CornerRadius="12" Background="#1C2C4C">
<TextBlock Text="◎" FontSize="20" Foreground="#8FB6FF"
HorizontalAlignment="Center" VerticalAlignment="Center" />
</Border>
<StackPanel VerticalAlignment="Center" Spacing="1">
<TextBlock Text="{loc:Loc app.name}" Foreground="#F2F6FF" FontSize="13.5" FontWeight="SemiBold" />
<TextBlock Text="{loc:Loc app.tagline}" Foreground="#7C90B4" FontSize="10" />
</StackPanel>
</StackPanel>
<StackPanel Grid.Row="1" Margin="0,30,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}" />
</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" Content="{Binding Current}" />
</Grid>
</Window>
@@ -0,0 +1,130 @@
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.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;
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);
}
private async void OpenPlayerWindow(ModelPackage package)
{
if (_viewModel == null) 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;
try
{
loaded = await _viewModel.Models.LoadAsync(package, () => window?.Close(),
(value, message) => loading.Report(value, message));
}
catch (Exception ex)
{
error = ex;
}
loading.Close();
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 OnClosed(object? sender, EventArgs e)
{
if (_viewModel != null)
{
_viewModel.PlayerRequested -= OpenPlayerWindow;
_viewModel.PropertyChanged -= OnViewModelPropertyChanged;
}
foreach (var window in _players.ToList()) window.Close();
_players.Clear();
}
}
@@ -0,0 +1,106 @@
using System;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Input;
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 = new SolidColorBrush(Color.Parse("#05070F"));
WindowStartupLocation = WindowStartupLocation.CenterOwner;
Content = model.View;
KeyDown += OnKeyDown;
Closed += OnClosed;
}
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 = new SolidColorBrush(Color.Parse("#0B1226"));
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 = panel;
}
}
@@ -0,0 +1,141 @@
<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" />
<Slider Minimum="512" Maximum="8192" TickFrequency="256" IsSnapToTickEnabled="False"
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="✕"
Command="{Binding RemoveCommand}" VerticalAlignment="Center" />
</Grid>
</Border>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</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>
<!-- 关于 -->
<Border Classes="card" Padding="20,18">
<StackPanel Spacing="12">
<TextBlock Classes="h2" Text="{loc:Loc set.about}" />
<Grid ColumnDefinitions="200,*">
<TextBlock Classes="h3" Text="{loc:Loc set.version}" />
<TextBlock Grid.Column="1" Classes="muted" Text="{Binding VersionText}" />
</Grid>
<Grid ColumnDefinitions="200,*">
<TextBlock Classes="h3" Text="{loc:Loc set.platform}" />
<TextBlock Grid.Column="1" Classes="muted" Text="{Binding PlatformText}" TextWrapping="Wrap" />
</Grid>
<Grid ColumnDefinitions="200,*">
<TextBlock Classes="h3" Text="{loc:Loc set.modelFormat}" />
<TextBlock Grid.Column="1" Classes="muted" Text="{loc:Loc set.modelFormat.desc}" TextWrapping="Wrap" />
</Grid>
<Grid ColumnDefinitions="200,*">
<TextBlock Classes="h3" Text="{loc:Loc set.license}" />
<TextBlock Grid.Column="1" Classes="muted" Text="{loc:Loc set.licenseValue}" />
</Grid>
</StackPanel>
</Border>
</StackPanel>
</ScrollViewer>
</UserControl>
@@ -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,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>
@@ -0,0 +1,20 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<Nullable>enable</Nullable>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<RootNamespace>EarthModelStudio.Tests</RootNamespace>
<AssemblyName>EarthModelStudio.Tests</AssemblyName>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Avalonia.Headless" Version="$(AvaloniaVersion)" />
<PackageReference Include="Avalonia.Skia" Version="$(AvaloniaVersion)" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="../../../main/dotnet/EarthModelStudio/EarthModelStudio.csproj" />
</ItemGroup>
</Project>
@@ -0,0 +1,221 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
using System.IO;
using System.Linq;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Headless;
using Avalonia.Threading;
using Avalonia.VisualTree;
using EarthModelStudio;
using EarthModelStudio.Services;
using EarthModelStudio.ViewModels;
using EarthModelStudio.Views;
namespace EarthModelStudio.Tests;
/// <summary>
/// 离屏校验工具:把启动器页面和模型窗口渲染成 PNG。
/// 用法:dotnet run --project src/test/dotnet/EarthModelStudio.Tests -- build/screenshots
/// </summary>
internal static class Program
{
private static string _outDir = "screenshots";
[STAThread]
public static int Main(string[] args)
{
_outDir = args.Length > 0 ? args[0] : "screenshots";
Directory.CreateDirectory(_outDir);
Environment.SetEnvironmentVariable("EMS_HOME", FindRepoRoot());
Environment.SetEnvironmentVariable("EMS_DATA", Path.Combine(_outDir, ".data"));
AppBuilder.Configure<App>()
.UseSkia()
.UseHeadless(new AvaloniaHeadlessPlatformOptions { UseHeadlessDrawing = false })
.SetupWithoutStarting();
var services = AppServices.Create();
RenderPages(services);
Console.WriteLine("截图输出: " + Path.GetFullPath(_outDir));
return 0;
}
private static string FindRepoRoot()
{
var dir = new DirectoryInfo(AppContext.BaseDirectory);
for (var i = 0; i < 10 && dir != null; i++, dir = dir.Parent)
{
if (File.Exists(Path.Combine(dir.FullName, "EarthModelStudio.sln"))) return dir.FullName;
}
return Directory.GetCurrentDirectory();
}
private static void RenderPages(AppServices services)
{
var vm = new MainViewModel(services);
var window = new MainWindow { DataContext = vm };
window.Show();
Dispatcher.UIThread.RunJobs();
Capture(window, "page-home.png");
vm.GoDownloadCommand.Execute(null);
Dispatcher.UIThread.RunJobs();
Capture(window, "page-download.png");
vm.GoSettingsCommand.Execute(null);
Dispatcher.UIThread.RunJobs();
Capture(window, "page-settings.png");
// 启动进度窗(单独截图)
var demoLoading = new LoadingWindow("地球自转");
demoLoading.Show(window);
demoLoading.Report(0.42, "生成地表纹理");
Dispatcher.UIThread.RunJobs();
Capture(demoLoading, "page-loading.png");
demoLoading.Close();
var packages = services.Models.Scan();
Console.WriteLine($"模型数: {packages.Count}");
foreach (var p in packages)
Console.WriteLine($" {p.Id}: 程序集={Path.GetFileName(p.AssemblyPath)} 存在={File.Exists(p.AssemblyPath)} 封面={File.Exists(p.PreviewPath)}");
// 启动模型:应当新开窗口,主窗口保持原页面
for (var i = 0; i < packages.Count && i < 2; i++)
{
var before = window.PlayerWindows.Count;
vm.PlayModel(packages[i]);
// 加载是异步的(带进度窗),这里泵一下调度器等它完成
var appeared = WaitFor(() => window.PlayerWindows.Count > before);
var player = window.PlayerWindows.LastOrDefault();
Console.WriteLine($"player windows = {window.PlayerWindows.Count} ({packages[i].Id}) appeared={appeared}");
if (player == null) continue;
if (i == 0)
{
Dispatcher.UIThread.RunJobs();
Capture(player, "page-player.png");
}
else
{
Capture(player, "page-player-rotation.png");
}
// 节气定位 / 视图切换只属于公转模型;自转模型不该出现
var hasSeasons = Descendants(player).OfType<TextBlock>()
.Any(t => (t.Text ?? "").Contains("节气定位", StringComparison.Ordinal) && ShownInTree(t));
var hasViewSwitch = Descendants(player).OfType<Button>()
.Any(b => b.Tag is string tag && (tag == "rotation" || tag == "revolution") && ShownInTree(b));
Console.WriteLine($" {packages[i].Id}: 节气定位={hasSeasons} 视图切换={hasViewSwitch}");
// 缩放 / 拖动能力:模型画布由模型程序集提供,这里用反射验证接口存在且可用
var canvas = Descendants(player).FirstOrDefault(c => c.GetType().Name == "CelestialView");
if (canvas != null)
{
var type = canvas.GetType();
var zoomProp = type.GetProperty("Zoom");
var zoomBy = type.GetMethod("ZoomBy");
var resetView = type.GetMethod("ResetView");
var beforeZoom = (double)(zoomProp?.GetValue(canvas) ?? 0d);
zoomBy?.Invoke(canvas, new object[] { 1.25 });
var afterZoom = (double)(zoomProp?.GetValue(canvas) ?? 0d);
resetView?.Invoke(canvas, null);
var resetZoom = (double)(zoomProp?.GetValue(canvas) ?? 0d);
var hasPointerOverride = type.GetMethod("OnPointerMoved",
System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic) != null;
Console.WriteLine($" {packages[i].Id}: 缩放={beforeZoom:0.00}→{afterZoom:0.00}→{resetZoom:0.00} 暂停拖动={hasPointerOverride}");
}
// 底部提示:滚轮缩放 / 暂停后可拖动
var hasHint = Descendants(player).OfType<TextBlock>()
.Any(t => (t.Text ?? "").Contains("拖动", StringComparison.Ordinal) && ShownInTree(t));
Console.WriteLine($" {packages[i].Id}: 交互提示={hasHint}");
}
// 关掉第二个窗口,只留一个继续验证主窗口
var second = window.PlayerWindows.LastOrDefault();
if (second != null) second.Close();
Dispatcher.UIThread.RunJobs();
Console.WriteLine($"window after closing second = {window.PlayerWindows.Count}");
// 主窗口仍停留在设置页 —— 说明没有被模型画面覆盖
Capture(window, "page-main-while-playing.png");
foreach (var player in window.PlayerWindows.ToList()) player.Close();
Dispatcher.UIThread.RunJobs();
window.Close();
}
private static bool WaitFor(Func<bool> condition, int timeoutMs = 20000)
{
var watch = Stopwatch.StartNew();
while (watch.ElapsedMilliseconds < timeoutMs)
{
Dispatcher.UIThread.RunJobs();
if (condition()) return true;
Thread.Sleep(15);
}
return condition();
}
private static bool ShownInTree(Control control)
{
Visual? current = control;
while (current != null)
{
if (current is Control c && !c.IsVisible) return false;
current = current.GetVisualParent();
}
return true;
}
private static IEnumerable<Control> Descendants(Control root)
{
var stack = new Stack<Control>();
stack.Push(root);
while (stack.Count > 0)
{
var current = stack.Pop();
yield return current;
switch (current)
{
case Panel panel:
foreach (var child in panel.Children) stack.Push(child);
break;
case Border { Child: Control only }:
stack.Push(only);
break;
case ScrollViewer { Content: Control scrolled }:
stack.Push(scrolled);
break;
case ContentControl { Content: Control content }:
stack.Push(content);
break;
}
}
}
private static void Capture(Window window, string fileName)
{
try
{
var frame = window.CaptureRenderedFrame();
if (frame == null)
{
Console.WriteLine("capture failed: " + fileName);
return;
}
var path = Path.Combine(_outDir, fileName);
frame.Save(path);
Console.WriteLine($"page -> {path}");
}
catch (Exception ex)
{
Console.WriteLine($"capture error {fileName}: {ex.Message}");
}
}
}