feat:修复部分问题

This commit is contained in:
2509_92447106 committed 2026-11-07 17:23:41 +08:00
1 parent 153ea88f4f
commit 5760fb77b0
38 files changed
+2273 -200

No files matched your search

@@ -40,6 +40,14 @@ public partial class App : Application
desktop.MainWindow = window;
desktop.ShutdownMode = ShutdownMode.OnMainWindowClose;
// 主窗口已建好,后台检查模型 / 启动器更新,不阻塞界面
if (Environment.GetEnvironmentVariable("EMS_NO_UPDATE") != "1")
{
Avalonia.Threading.Dispatcher.UIThread.Post(
() => _ = vm.RunStartupUpdateAsync(),
Avalonia.Threading.DispatcherPriority.Background);
}
}
base.OnFrameworkInitializationCompleted();
@@ -14,7 +14,7 @@
"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.emptyHint": "Models download from gitcode on startup; offline you can drop them into .GC/model/ or import a source on the Download page.",
"home.emptyAction": "Get models",
"home.open": "Open folder",
"home.delete": "Delete",
@@ -93,7 +93,32 @@
"set.license": "License",
"set.licenseValue": "MIT",
"set.checkUpdate": "Check for updates",
"set.checkUpdate.desc": "Offline build — update by replacing the app folder.",
"set.checkUpdate.desc": "Check on startup whether models and the launcher are up to date.",
"update.title": "Auto update",
"update.desc": "Models take effect immediately after download; launcher updates apply on the next start.",
"update.auto": "Check for updates on startup",
"update.checkNow": "Check now",
"update.source": "Update source",
"update.lastCheck": "Last check",
"update.pending": "Pending version",
"update.never": "Never",
"update.none": "None",
"update.checking": "Checking for updates…",
"update.disabled": "Auto update is off",
"update.offline": "Update server unavailable — continuing with local models",
"update.noManifest": "No remote version manifest — continuing with local models",
"update.noChange": "Models and launcher are up to date",
"update.modelsLatest": "Models are up to date",
"update.applied": "Updated {0} models, applied now",
"update.partial": " ({0} item(s) incomplete)",
"update.downloadingModel": "Downloading model {0}…",
"update.downloadingLauncher": "Downloading launcher {0}…",
"update.done": "Update check complete",
"update.pendingReady": "Launcher {0} is ready, applies on next start",
"update.pendingDownloaded": "Launcher {0} downloaded, applies on next start",
"update.noRidPackage": "Launcher {0} found (no package for {1})",
"update.noPackageUrl": "Launcher {0} found, but no download address",
"update.launcherFailed": "Launcher update failed: {0}",
"set.modelFormat": "Model format",
"set.modelFormat.desc": "model/<model-id>/<model-id>.json + <model-id>.model/ scene data",
"player.back": "Close window",
@@ -14,7 +14,7 @@
"home.installed": "已安装模型",
"home.count": "{0} 个模型",
"home.empty": "模型库还是空的",
"home.emptyHint": "在「下载」页从链接导入模型源,或把模型直接放进 model 目录。",
"home.emptyHint": "启动时会从 gitcode 自动下载模型;离线可把模型放进 .GC/model/,或在「下载」页导入模型源。",
"home.emptyAction": "去下载模型",
"home.open": "打开目录",
"home.delete": "删除",
@@ -93,7 +93,32 @@
"set.license": "许可",
"set.licenseValue": "MIT",
"set.checkUpdate": "检查更新",
"set.checkUpdate.desc": "当前为离线构建,更新请替换程序目录。",
"set.checkUpdate.desc": "启动时自动检查模型与启动器是否为最新版。",
"update.title": "自动更新",
"update.desc": "启动时检查模型与启动器是否为最新版;模型下载后立即生效,启动器在下次启动时应用。",
"update.auto": "启动时自动检查更新",
"update.checkNow": "检查更新",
"update.source": "更新源",
"update.lastCheck": "上次检查",
"update.pending": "待应用版本",
"update.never": "尚未检查",
"update.none": "无",
"update.checking": "正在检查更新…",
"update.disabled": "自动更新已关闭",
"update.offline": "暂时无法连接更新服务器,继续使用本地模型",
"update.noManifest": "远端还没有版本清单,继续使用本地模型",
"update.noChange": "模型与启动器均为最新版",
"update.modelsLatest": "模型已是最新版",
"update.applied": "已更新 {0} 个模型,立即生效",
"update.partial": "({0} 项未完成)",
"update.downloadingModel": "正在下载模型 {0}…",
"update.downloadingLauncher": "正在下载启动器新版 {0}…",
"update.done": "更新检查完成",
"update.pendingReady": "启动器新版 {0} 已就绪,下次启动生效",
"update.pendingDownloaded": "启动器新版 {0} 已下载,下次启动生效",
"update.noRidPackage": "发现启动器新版 {0}({1} 暂无安装包)",
"update.noPackageUrl": "发现启动器新版 {0},但下载地址不可用",
"update.launcherFailed": "启动器更新失败:{0}",
"set.modelFormat": "模型格式",
"set.modelFormat.desc": "model/<模型ID>/<模型ID>.json + <模型ID>.model/ 场景数据",
"player.back": "关闭窗口",
@@ -28,6 +28,32 @@ public sealed class AppSettings
public List<ModelSource> Sources { get; set; } = new();
public List<string> RecentModels { get; set; } = new();
// ---- 自动更新 ----------------------------------------------------------
/// <summary>启动时检查模型 / 启动器是否为最新版。</summary>
public bool AutoUpdateOnStartup { get; set; } = true;
/// <summary>默认更新仓库地址。</summary>
public string UpdateRepository { get; set; } = "https://gitcode.com/2509_92447106/GC";
/// <summary>版本清单地址覆盖(留空则按 UpdateRepository 拼接)。</summary>
public string? UpdateManifestUrl { get; set; }
/// <summary>本地模型源目录(离线教学场景可指向 U 盘 / 共享盘里的仓库)。</summary>
public string? UpdateLocalRoot { get; set; }
/// <summary>已安装的模型版本:id -> version.json 里的版本。</summary>
public Dictionary<string, string> InstalledModelVersions { get; set; } = new();
/// <summary>当前已经应用过的启动器版本。</summary>
public string? LauncherVersion { get; set; }
/// <summary>已下载、等待下次启动应用的启动器版本。</summary>
public string? PendingLauncherVersion { get; set; }
/// <summary>最近一次更新检查时间(ISO 8601)。</summary>
public string? LastUpdateCheck { get; set; }
}
/// <summary>模型源:一个满足 Earth Model 规范的 git 仓库 / zip / 本地目录。</summary>
+12 -1
View File
@@ -1,12 +1,23 @@
using System;
using Avalonia;
using EarthModelStudio.Services;
namespace EarthModelStudio;
internal static class Program
{
[STAThread]
public static void Main(string[] args) => BuildAvaloniaApp().StartWithClassicDesktopLifetime(args);
public static void Main(string[] args)
{
// 运行目录:可执行文件旁 .GC/(settings.json + model/ + cache/ + update/)
var paths = AppPaths.Discover();
paths.EnsureCreated();
// 上次下载的启动器新版,到这次启动才应用:交给独立脚本覆盖文件并重启
if (LauncherUpdate.TryApplyPending(paths)) return;
BuildAvaloniaApp().StartWithClassicDesktopLifetime(args);
}
public static AppBuilder BuildAvaloniaApp()
=> AppBuilder.Configure<App>()
@@ -4,76 +4,102 @@ using System.IO;
namespace EarthModelStudio.Services;
/// <summary>
/// 目录探测。启动器本身不含任何模型数据,模型一律从外部模型库目录读取:
/// 1) 开发态:从 bin 目录向上找到 EarthModelStudio.sln,模型库用仓库根 model/
/// 2) 绿色态:可执行文件旁边有 model/ 目录(发布包默认只建空目录)
/// 3) 安装态:模型库放到用户数据目录
/// 也可用环境变量 EMS_HOME / EMS_MODELS 显式指定。
/// 运行目录约定(可执行文件旁边,不内置任何模型):
/// <code>
/// &lt;安装目录&gt;/
/// EarthModelStudio(.exe | .app/...)
/// .GC/
/// settings.json 设置与已安装版本记录
/// model/ 模型(启动时下载;model 目录也在 .GC 里)
/// cache/ 下载缓存 / 原子替换暂存
/// update/ 待下次启动应用的启动器更新包
/// </code>
/// 开发态同样使用 .GC/model,并自动把仓库 model/ 的可分发部分同步进去。
/// EMS_MODELS / EMS_DATA / EMS_HOME 可显式覆盖。
/// </summary>
public sealed class AppPaths
{
/// <summary>安装目录(开发态为仓库根)。</summary>
public string AppRoot { get; private init; } = "";
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");
/// <summary>可执行文件真正所在目录:启动器自更新时要覆盖这里。</summary>
public string InstallDirectory { get; private init; } = "";
/// <summary>.GC 目录。</summary>
public string HomeRoot { get; private init; } = "";
/// <summary>模型库,恒为 &lt;HomeRoot&gt;/model。</summary>
public string ModelRoot { get; private init; } = "";
/// <summary>兼容旧代码:数据目录即 .GC。</summary>
public string DataRoot => HomeRoot;
public string CacheRoot => Path.Combine(HomeRoot, "cache");
public string UpdateRoot => Path.Combine(HomeRoot, "update");
public string SettingsFile => Path.Combine(HomeRoot, "settings.json");
public bool IsDevelopment { get; private init; }
public bool IsPortableModelRoot { get; private init; }
public static AppPaths Discover()
{
var baseDir = AppContext.BaseDirectory.TrimEnd(Path.DirectorySeparatorChar);
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 isDev = !string.IsNullOrEmpty(repoRoot) &&
File.Exists(Path.Combine(repoRoot!, "EarthModelStudio.sln"));
var appRoot = isDev ? repoRoot! : baseDir;
var exeModelDir = Path.Combine(baseDir, "model");
string appRoot, modelRoot;
bool portable = false;
if (!string.IsNullOrEmpty(repoRoot) && Directory.Exists(Path.Combine(repoRoot!, "model")))
// 只读安装位置(如 Program Files / /Applications)自动退回用户数据目录
var explicitData = Environment.GetEnvironmentVariable("EMS_DATA");
string home;
if (!string.IsNullOrWhiteSpace(explicitData))
{
appRoot = repoRoot!;
modelRoot = Path.Combine(appRoot, "model");
}
else if (Directory.Exists(exeModelDir))
{
appRoot = baseDir;
modelRoot = exeModelDir;
portable = true;
home = explicitData!;
}
else
{
appRoot = baseDir;
modelRoot = Path.Combine(dataRoot, "model");
var portableHome = Path.Combine(appRoot, ".GC");
home = CanWrite(portableHome)
? portableHome
: Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
"EarthModelStudio", ".GC");
}
var envModels = Environment.GetEnvironmentVariable("EMS_MODELS");
var modelRoot = !string.IsNullOrWhiteSpace(envModels)
? envModels!
: Path.Combine(home, "model"); // 统一:model 目录在 .GC 里
return new AppPaths
{
AppRoot = appRoot,
InstallDirectory = baseDir,
HomeRoot = home,
ModelRoot = modelRoot,
DataRoot = dataRoot,
IsPortableModelRoot = portable
IsDevelopment = isDev,
IsPortableModelRoot = string.IsNullOrWhiteSpace(envModels)
};
}
private static bool CanWrite(string dir)
{
try
{
Directory.CreateDirectory(dir);
var probe = Path.Combine(dir, ".write-test");
File.WriteAllText(probe, "ok");
File.Delete(probe);
return true;
}
catch
{
return false;
}
}
private static string? FindRepoRoot(string start)
{
var dir = new DirectoryInfo(start);
@@ -86,8 +112,51 @@ public sealed class AppPaths
public void EnsureCreated()
{
Directory.CreateDirectory(DataRoot);
Directory.CreateDirectory(HomeRoot);
Directory.CreateDirectory(CacheRoot);
Directory.CreateDirectory(ModelRoot);
Directory.CreateDirectory(UpdateRoot);
// 开发态:让 .GC/model 与仓库里的模型保持一致(只同步清单 + 数据,不含 src 源码)
if (IsDevelopment && string.IsNullOrWhiteSpace(Environment.GetEnvironmentVariable("EMS_MODELS")))
SyncDevelopmentModels();
}
private void SyncDevelopmentModels()
{
try
{
var source = Path.Combine(AppRoot, "model");
if (!Directory.Exists(source)) return;
foreach (var dir in Directory.GetDirectories(source))
{
var id = Path.GetFileName(dir);
if (id.StartsWith('_')) continue;
var manifest = Path.Combine(dir, id + ".json");
var data = Path.Combine(dir, id + ".model");
if (!File.Exists(manifest) || !Directory.Exists(data)) continue;
var dest = Path.Combine(ModelRoot, id);
Directory.CreateDirectory(dest);
File.Copy(manifest, Path.Combine(dest, id + ".json"), true);
CopyTree(data, Path.Combine(dest, id + ".model"));
}
}
catch (Exception ex)
{
Console.Error.WriteLine($"同步开发模型失败: {ex.Message}");
}
}
private static void CopyTree(string src, string dst)
{
Directory.CreateDirectory(dst);
foreach (var file in Directory.GetFiles(src, "*", SearchOption.AllDirectories))
{
if (Path.GetFileName(file).StartsWith('.')) continue;
var to = Path.Combine(dst, Path.GetRelativePath(src, file));
var parent = Path.GetDirectoryName(to);
if (!string.IsNullOrEmpty(parent)) Directory.CreateDirectory(parent);
File.Copy(file, to, true);
}
}
}
@@ -15,16 +15,20 @@ public sealed class AppServices
public ModelSourceClient Sources { get; }
/// <summary>模型加载器:只负责把模型程序集跑起来,不渲染。</summary>
public ModelHost ModelHost { get; }
/// <summary>启动时检查模型 / 启动器更新。</summary>
public UpdateService Updates { get; }
private AppServices(AppPaths paths)
{
Paths = paths;
Settings = new SettingsService(paths);
Settings.Load(); // 先读设置,才知道用在线源还是本地离线源
Models = new ModelRepository(paths);
Sources = new ModelSourceClient(paths);
Downloads = new DownloadCenter(paths, Models);
Memory = new MemoryBudget();
ModelHost = new ModelHost(paths, Settings, Memory);
Updates = new UpdateService(paths, Settings, UpdateService.CreateRemote(Settings.Current));
}
public static AppServices Create()
@@ -33,7 +37,6 @@ public sealed class AppServices
paths.EnsureCreated();
var services = new AppServices(paths);
services.Settings.Load();
L.I.Initialize(services.Settings.Current.Language);
services.Memory.Apply(services.Settings.Current.MemoryMb);
@@ -41,9 +44,5 @@ public sealed class AppServices
return services;
}
public static AppServices Ensure()
{
if (Current == null) Create();
return Current;
}
public static AppServices Ensure() => Current ?? Create();
}
@@ -0,0 +1,107 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
namespace EarthModelStudio.Services;
/// <summary>
/// 本地目录源:用于离线教学(U 盘 / 共享盘里的仓库副本)与自动化测试。
/// 目录结构与远端仓库一致:version.json + model/&lt;id&gt;/...
/// </summary>
public sealed class DirectoryRemote : IModelRemote
{
private readonly string _root;
private static readonly HttpClient Http = new() { Timeout = TimeSpan.FromMinutes(5) };
public DirectoryRemote(string root) => _root = Path.GetFullPath(root);
public string DisplayName => _root;
public Task<RepoVersion?> GetVersionAsync(CancellationToken ct)
{
var primary = SafePath("version.json");
var fallback = SafePath(Path.Combine("model", "version.json"));
var file = File.Exists(primary) ? primary : fallback;
if (!File.Exists(file)) return Task.FromResult<RepoVersion?>(null);
return Task.FromResult(Json.Read<RepoVersion>(file));
}
public Task<IReadOnlyList<RepoEntry>> ListTreeAsync(string rootPath, CancellationToken ct)
{
var baseDir = SafePath(rootPath ?? "model");
var result = new List<RepoEntry>();
if (!Directory.Exists(baseDir)) return Task.FromResult<IReadOnlyList<RepoEntry>>(result);
Walk(baseDir, baseDir, 0, result);
return Task.FromResult<IReadOnlyList<RepoEntry>>(result);
}
private void Walk(string dir, string baseDir, int depth, List<RepoEntry> result)
{
if (depth > 8) return;
foreach (var sub in Directory.GetDirectories(dir))
{
var name = Path.GetFileName(sub);
if (name.StartsWith('.')) continue;
var rel = Relative(baseDir, sub);
result.Add(new RepoEntry
{
Name = name,
Path = Relative(_root, sub),
RelativePath = rel,
IsDirectory = true
});
Walk(sub, baseDir, depth + 1, result);
}
foreach (var file in Directory.GetFiles(dir))
{
var name = Path.GetFileName(file);
if (name.StartsWith('.')) continue;
result.Add(new RepoEntry
{
Name = name,
Path = Relative(_root, file),
RelativePath = Relative(baseDir, file),
IsDirectory = false,
Size = new FileInfo(file).Length
});
}
}
public async Task<byte[]> DownloadAsync(RepoEntry entry, CancellationToken ct)
=> await File.ReadAllBytesAsync(SafePath(entry.Path), ct);
public async Task<byte[]?> DownloadPackageAsync(RepoPackage package, CancellationToken ct)
{
if (!string.IsNullOrWhiteSpace(package.Path))
{
var local = SafePath(package.Path!);
if (File.Exists(local)) return await File.ReadAllBytesAsync(local, ct);
}
var url = package.Url;
if (string.IsNullOrWhiteSpace(url)) return null;
if (url!.StartsWith("file://", StringComparison.OrdinalIgnoreCase))
return await File.ReadAllBytesAsync(new Uri(url).LocalPath, ct);
if (Path.IsPathRooted(url) && File.Exists(url))
return await File.ReadAllBytesAsync(url, ct);
if (Uri.TryCreate(url, UriKind.Absolute, out _))
return await Http.GetByteArrayAsync(url, ct);
return null;
}
private string SafePath(string relative)
{
var full = Path.GetFullPath(Path.Combine(_root, relative));
var prefix = _root.TrimEnd(Path.DirectorySeparatorChar) + Path.DirectorySeparatorChar;
if (!full.Equals(_root, StringComparison.OrdinalIgnoreCase) &&
!full.StartsWith(prefix, StringComparison.OrdinalIgnoreCase))
throw new InvalidOperationException($"路径越界: {relative}");
return full;
}
private static string Relative(string baseDir, string file) =>
Path.GetRelativePath(baseDir, file).Replace('\\', '/');
}
@@ -0,0 +1,211 @@
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
namespace EarthModelStudio.Services;
/// <summary>
/// gitcode 仓库源。默认地址来自 AppSettings.UpdateRepository
/// (https://gitcode.com/2509_92447106/GC),可改成任意 gitcode 仓库或
/// https://gitcode.com/&lt;owner&gt;/&lt;repo&gt;/tree/&lt;branch&gt;/model 这样的地址。
/// 匿名访问 v5 contents API:目录 -> 数组,文件 -> { content: base64 };
/// 文件项自带 download_url(raw.gitcode.com/blobs/&lt;sha&gt;/...),可直接下载二进制。
/// </summary>
public sealed class GitCodeRemote : IModelRemote
{
public const string DefaultRepository = "https://gitcode.com/2509_92447106/GC";
private readonly HttpClient _http;
private readonly string _api;
private readonly string _branch;
private readonly string _versionUrl;
private readonly string? _fallbackUrl;
private readonly string _displayName;
private string _modelDir = "model";
public string DisplayName => _displayName;
public GitCodeRemote(string? manifestUrl = null, string? repository = null)
{
var (owner, repo, branch) = ParseRepository(repository);
_branch = branch;
_api = $"https://api.gitcode.com/api/v5/repos/{owner}/{repo}/contents/";
_displayName = string.IsNullOrWhiteSpace(repository)
? DefaultRepository : repository!.TrimEnd('/');
_http = new HttpClient { Timeout = TimeSpan.FromMinutes(2) };
_http.DefaultRequestHeaders.UserAgent.ParseAdd("EarthModelStudio-Updater/1.0");
_http.DefaultRequestHeaders.Accept.ParseAdd("application/json");
if (string.IsNullOrWhiteSpace(manifestUrl))
{
_versionUrl = _api + "version.json?ref=" + _branch;
_fallbackUrl = _api + "model/version.json?ref=" + _branch;
}
else
{
_versionUrl = manifestUrl!;
_fallbackUrl = null;
}
}
/// <summary>从仓库 URL 解析 owner / repo / branch,解析失败回退到默认仓库。</summary>
private static (string Owner, string Repo, string Branch) ParseRepository(string? url)
{
var raw = string.IsNullOrWhiteSpace(url) ? DefaultRepository : url!.Trim();
if (!Uri.TryCreate(raw, UriKind.Absolute, out var uri))
return ("2509_92447106", "GC", "main");
var parts = uri.AbsolutePath.Trim('/').Split('/', StringSplitOptions.RemoveEmptyEntries);
if (parts.Length < 2) return ("2509_92447106", "GC", "main");
var owner = parts[0];
var repo = parts[1].EndsWith(".git", StringComparison.OrdinalIgnoreCase)
? parts[1][..^4] : parts[1];
var branch = parts.Length >= 4 && parts[2].Equals("tree", StringComparison.OrdinalIgnoreCase)
? parts[3] : "main";
return (owner, repo, branch);
}
public async Task<RepoVersion?> GetVersionAsync(CancellationToken ct)
{
RepoVersion? version = await ReadVersionFromAsync(_versionUrl, ct);
if (version == null && _fallbackUrl != null)
version = await ReadVersionFromAsync(_fallbackUrl, ct);
if (version != null && !string.IsNullOrWhiteSpace(version.ModelDir))
_modelDir = version.ModelDir.Trim('/');
return version;
}
private async Task<RepoVersion?> ReadVersionFromAsync(string url, CancellationToken ct)
{
string text;
try
{
// 离线 / 网络不通时最多等 10 秒,不能让启动界面一直卡在「检查更新」
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(ct);
timeout.CancelAfter(TimeSpan.FromSeconds(10));
text = await _http.GetStringAsync(url, timeout.Token);
}
catch (HttpRequestException) { return null; }
catch (OperationCanceledException) when (!ct.IsCancellationRequested) { return null; }
var trimmed = text.TrimStart();
if (trimmed.Length == 0 || trimmed[0] != '{') return null;
try
{
using var doc = JsonDocument.Parse(text);
var payload = text;
if (doc.RootElement.TryGetProperty("encoding", out _) &&
doc.RootElement.TryGetProperty("content", out var content))
{
var raw = Convert.FromBase64String(content.GetString() ?? "");
payload = Encoding.UTF8.GetString(raw);
}
if (!payload.TrimStart().StartsWith("{", StringComparison.Ordinal)) return null;
var version = System.Text.Json.JsonSerializer.Deserialize<RepoVersion>(
payload, EarthModelStudio.Services.Json.Options);
// 404 / 错误页也可能返回一个 JSON 对象,用 generated 确认这确实是版本清单
return version != null && !string.IsNullOrWhiteSpace(version.Generated) ? version : null;
}
catch (Exception ex)
{
Console.Error.WriteLine($"版本清单解析失败 {url}: {ex.Message}");
return null;
}
}
/// <summary>递归列出目录树(含目录项与文件项)。</summary>
public async Task<IReadOnlyList<RepoEntry>> ListTreeAsync(string rootPath, CancellationToken ct)
{
var result = new List<RepoEntry>();
var repoPath = (rootPath ?? _modelDir).Trim('/');
await WalkAsync(repoPath, "", 0, result, ct);
return result;
}
private async Task WalkAsync(string repoPath, string relative, int depth,
List<RepoEntry> result, CancellationToken ct)
{
if (depth > 8) return;
var url = _api + repoPath + "?ref=" + _branch;
var text = await _http.GetStringAsync(url, ct);
if (!text.TrimStart().StartsWith("[", StringComparison.Ordinal)) return;
using var doc = JsonDocument.Parse(text);
foreach (var item in doc.RootElement.EnumerateArray())
{
ct.ThrowIfCancellationRequested();
var name = Str(item, "name");
if (string.IsNullOrEmpty(name) || name.StartsWith('.')) continue;
var path = Str(item, "path");
if (string.IsNullOrWhiteSpace(path)) path = repoPath + "/" + name;
var isDir = Str(item, "type") == "dir";
var childRelative = relative.Length == 0 ? name : relative + "/" + name;
result.Add(new RepoEntry
{
Name = name,
Path = path!,
RelativePath = childRelative,
IsDirectory = isDir,
DownloadUrl = NullableStr(item, "download_url"),
Sha = NullableStr(item, "sha"),
Size = Num(item, "size")
});
if (isDir) await WalkAsync(path!, childRelative, depth + 1, result, ct);
}
}
public async Task<byte[]> DownloadAsync(RepoEntry entry, CancellationToken ct)
{
if (!string.IsNullOrWhiteSpace(entry.DownloadUrl))
return await _http.GetByteArrayAsync(entry.DownloadUrl!, ct);
var url = _api + entry.Path.Trim('/') + "?ref=" + _branch;
var text = await _http.GetStringAsync(url, ct);
using var doc = JsonDocument.Parse(text);
if (!doc.RootElement.TryGetProperty("content", out var content))
throw new InvalidOperationException($"远端文件没有内容: {entry.Path}");
return Convert.FromBase64String(content.GetString() ?? "");
}
public async Task<byte[]?> DownloadPackageAsync(RepoPackage package, CancellationToken ct)
{
string? url = string.IsNullOrWhiteSpace(package.Url) ? null : package.Url!.Trim();
if (url == null && !string.IsNullOrWhiteSpace(package.Path))
{
try
{
var apiUrl = _api + package.Path!.Trim('/') + "?ref=" + _branch;
var text = await _http.GetStringAsync(apiUrl, ct);
using var doc = JsonDocument.Parse(text);
if (doc.RootElement.TryGetProperty("download_url", out var dl))
url = dl.GetString();
}
catch (Exception ex)
{
Console.Error.WriteLine($"解析启动器包地址失败: {ex.Message}");
return null;
}
}
if (string.IsNullOrWhiteSpace(url)) return null;
return await _http.GetByteArrayAsync(url!, ct);
}
private static string Str(JsonElement item, string name)
=> item.TryGetProperty(name, out var v) && v.ValueKind == JsonValueKind.String
? v.GetString() ?? "" : "";
private static string? NullableStr(JsonElement item, string name)
=> item.TryGetProperty(name, out var v) && v.ValueKind == JsonValueKind.String
? v.GetString() : null;
private static long Num(JsonElement item, string name)
=> item.TryGetProperty(name, out var v) && v.ValueKind == JsonValueKind.Number
&& v.TryGetInt64(out var n) ? n : 0;
}
@@ -0,0 +1,176 @@
using System;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using EarthModelStudio.Models;
namespace EarthModelStudio.Services;
/// <summary>.GC/update/pending.json:已下载、等待下次启动应用的启动器版本。</summary>
public sealed class PendingUpdate
{
public string Version { get; set; } = "";
public string Rid { get; set; } = "";
public string InstallDirectory { get; set; } = "";
public string Executable { get; set; } = "";
public string Payload { get; set; } = "payload";
public string? DownloadedAt { get; set; }
}
/// <summary>
/// 「下次启动时应用」:主进程刚进 Main、还没建窗口时,交给一个独立脚本进程,
/// 脚本等主进程退出后覆盖可执行文件并重启。这样 Windows 上也不会碰到文件占用。
/// </summary>
public static class LauncherUpdate
{
public static bool TryApplyPending(AppPaths paths) => TryApplyPending(paths, launch: true);
/// <summary>launch=false 只生成脚本、不启动进程,供离线自动更新测试使用。</summary>
public static bool TryApplyPending(AppPaths paths, bool launch)
{
// 开发态、自检、显式关闭时一律不替换正在运行的程序
if (paths.IsDevelopment) return false;
if (Environment.GetEnvironmentVariable("EMS_SELFTEST") == "1") return false;
if (Environment.GetEnvironmentVariable("EMS_NO_SELF_UPDATE") == "1") return false;
var pendingFile = Path.Combine(paths.UpdateRoot, "pending.json");
if (!File.Exists(pendingFile))
{
ClearPendingSetting(paths);
return false;
}
PendingUpdate? pending;
try { pending = Json.Read<PendingUpdate>(pendingFile); }
catch { pending = null; }
var payload = Path.Combine(paths.UpdateRoot,
string.IsNullOrWhiteSpace(pending?.Payload) ? "payload" : pending!.Payload!);
var installDir = string.IsNullOrWhiteSpace(pending?.InstallDirectory)
? paths.InstallDirectory : pending!.InstallDirectory!;
// 版本已经生效,或包不完整:清掉标记后正常启动
if (pending == null || string.IsNullOrWhiteSpace(pending.Version) ||
string.Equals(pending.Version, UpdateService.CurrentLauncherVersion,
StringComparison.OrdinalIgnoreCase) || !Directory.Exists(payload))
{
TryDelete(pendingFile);
ClearPendingSetting(paths);
return false;
}
var exeName = string.IsNullOrWhiteSpace(pending.Executable)
? (OperatingSystem.IsWindows() ? "EarthModelStudio.exe" : "EarthModelStudio")
: pending.Executable!;
var exePath = Path.Combine(installDir, exeName);
var isWindows = OperatingSystem.IsWindows();
var script = Path.Combine(paths.UpdateRoot, isWindows ? "apply-update.bat" : "apply-update.sh");
var content = isWindows
? WindowsScript(payload, installDir, exePath, pendingFile, script)
: UnixScript(payload, installDir, exePath, pendingFile, script);
try
{
File.WriteAllText(script, content, new UTF8Encoding(false));
if (!launch)
{
Console.WriteLine($"(dry-run) 更新脚本已生成: {script}");
return true;
}
ProcessStartInfo psi;
if (isWindows)
{
psi = new ProcessStartInfo("cmd.exe")
{
UseShellExecute = false,
CreateNoWindow = true
};
psi.ArgumentList.Add("/c");
psi.ArgumentList.Add(script);
}
else
{
try
{
File.SetUnixFileMode(script,
UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute);
}
catch { /* 某些文件系统不支持 */ }
psi = new ProcessStartInfo("/bin/sh")
{
UseShellExecute = false,
CreateNoWindow = true
};
psi.ArgumentList.Add(script);
}
Process.Start(psi);
Console.WriteLine($"启动器更新 {pending.Version} 已安排,重启后生效");
return true; // Main 直接返回,进程退出后由脚本接管
}
catch (Exception ex)
{
Console.Error.WriteLine($"应用启动器更新失败(保留待更新包,下次再试): {ex.Message}");
return false;
}
}
private static string WindowsScript(string payload, string installDir,
string exePath, string pendingFile, string script)
{
var text = new StringBuilder();
text.AppendLine("@echo off");
text.AppendLine("chcp 65001 >nul 2>&1");
text.AppendLine($"set \"SRC={payload}\"");
text.AppendLine($"set \"DST={installDir}\"");
text.AppendLine($"set \"EXE={exePath}\"");
text.AppendLine($"set \"PENDING={pendingFile}\"");
text.AppendLine("timeout /t 2 /nobreak >nul");
text.AppendLine("xcopy /E /Y /I /Q \"%SRC%\\*\" \"%DST%\\\" >nul 2>&1");
text.AppendLine("if exist \"%PENDING%\" del /Q \"%PENDING%\" >nul 2>&1");
text.AppendLine("if exist \"%EXE%\" start \"\" \"%EXE%\"");
text.AppendLine($"del /Q \"{script}\" >nul 2>&1");
return text.ToString();
}
private static string UnixScript(string payload, string installDir,
string exePath, string pendingFile, string script)
{
static string Q(string value) => "\"" + value
.Replace("\\", "\\\\")
.Replace("\"", "\\\"")
.Replace("$", "\\$")
.Replace("`", "\\`") + "\"";
var text = new StringBuilder();
text.AppendLine("#!/bin/sh");
text.AppendLine("sleep 2");
text.AppendLine($"cp -R {Q(payload + "/.")} {Q(installDir + "/")}");
text.AppendLine($"chmod +x {Q(exePath)} 2>/dev/null");
text.AppendLine($"rm -f {Q(pendingFile)}");
text.AppendLine($"{Q(exePath)} >/dev/null 2>&1 &");
text.AppendLine($"rm -f {Q(script)}");
return text.ToString();
}
private static void ClearPendingSetting(AppPaths paths)
{
try
{
var settings = Json.Read<AppSettings>(paths.SettingsFile);
if (settings == null || string.IsNullOrEmpty(settings.PendingLauncherVersion)) return;
settings.PendingLauncherVersion = null;
settings.LauncherVersion = UpdateService.CurrentLauncherVersion;
Json.Write(paths.SettingsFile, settings);
}
catch { /* 设置文件不可写时忽略 */ }
}
private static void TryDelete(string file)
{
try { if (File.Exists(file)) File.Delete(file); } catch { }
}
}
@@ -22,8 +22,8 @@ public sealed class SettingsService
}
/// <summary>
/// 首次启动不预置任何模型源:启动器只做适配,模型内容由用户从链接导入。
/// 这里只给一条空的自定义源占位。
/// 自动更新由 UpdateService 负责(版本清单 version.json),这里不预置任何在线源;
/// 只给「下载」页留一条空的自定义源占位。
/// </summary>
private void SeedSources()
{
@@ -0,0 +1,95 @@
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
namespace EarthModelStudio.Services;
/// <summary>仓库根 version.json:由构建脚本 VersionStamp 自动生成,模型一改版本就变。</summary>
public sealed class RepoVersion
{
public int Schema { get; set; } = 1;
public string Generated { get; set; } = "";
public string Repository { get; set; } = "";
public string Branch { get; set; } = "main";
public string ModelDir { get; set; } = "model";
public RepoLauncher Launcher { get; set; } = new();
public List<RepoModel> Models { get; set; } = new();
}
public sealed class RepoLauncher
{
public string Version { get; set; } = "1.0.0";
/// <summary>启动器源码指纹(自动算,仅展示,不触发升级)。</summary>
public string Revision { get; set; } = "";
public Dictionary<string, RepoPackage> Packages { get; set; } = new();
}
/// <summary>某个平台的启动器发布包;url 优先,否则用 path 去仓库里解析下载地址。</summary>
public sealed class RepoPackage
{
public string? Url { get; set; }
public string? Path { get; set; }
public string? Sha256 { get; set; }
public long Size { get; set; }
}
public sealed class RepoModel
{
public string Id { get; set; } = "";
public string Version { get; set; } = "";
/// <summary>模型在仓库里的目录,如 model/earth-rotation。</summary>
public string Dir { get; set; } = "";
}
/// <summary>远端目录树里的一个条目。</summary>
public sealed class RepoEntry
{
public string Name { get; init; } = "";
/// <summary>仓库内完整路径。</summary>
public string Path { get; init; } = "";
/// <summary>相对所请求根目录的路径,统一用 / 分隔。</summary>
public string RelativePath { get; init; } = "";
public bool IsDirectory { get; init; }
public string? DownloadUrl { get; init; }
public long Size { get; init; }
public string? Sha { get; init; }
}
/// <summary>
/// 远端源抽象:gitcode 是默认实现,本地目录实现用于离线教学与自动化测试。
/// </summary>
public interface IModelRemote
{
string DisplayName { get; }
Task<RepoVersion?> GetVersionAsync(CancellationToken ct);
Task<IReadOnlyList<RepoEntry>> ListTreeAsync(string rootPath, CancellationToken ct);
Task<byte[]> DownloadAsync(RepoEntry entry, CancellationToken ct);
Task<byte[]?> DownloadPackageAsync(RepoPackage package, CancellationToken ct);
}
public sealed class UpdateProgress
{
public double Value { get; init; }
public string Message { get; init; } = "";
public string? Detail { get; init; }
}
public enum UpdateOutcome
{
NoChange,
Applied,
Partial,
Unavailable,
Disabled
}
public sealed class UpdateResult
{
public UpdateOutcome Outcome { get; init; }
public string Message { get; init; } = "";
public int UpdatedModels { get; init; }
public List<string> ModelNames { get; init; } = new();
public string? LauncherMessage { get; init; }
public string? Error { get; init; }
}
@@ -0,0 +1,356 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Threading;
using System.Threading.Tasks;
using EarthModelStudio.Models;
namespace EarthModelStudio.Services;
/// <summary>
/// 启动时的自动更新:
/// · 读远端 version.json,和 .GC/settings.json 里记录的版本比较;
/// · 模型:下载到 cache 后原子替换 .GC/model/&lt;id&gt;,结果立刻刷新列表(本次启动生效);
/// · 启动器:下载到 .GC/update/payload 并写 pending.json,下次启动才应用;
/// · 任何失败都保留本地已装模型,绝不把模型库清空。
/// </summary>
public sealed class UpdateService
{
private readonly AppPaths _paths;
private readonly SettingsService _settings;
private readonly IModelRemote _remote;
public UpdateService(AppPaths paths, SettingsService settings, IModelRemote remote)
{
_paths = paths;
_settings = settings;
_remote = remote;
}
public IModelRemote Remote => _remote;
public static string CurrentLauncherVersion
{
get
{
var v = Assembly.GetEntryAssembly()?.GetName().Version;
if (v == null) return "0.0.0";
return $"{Math.Max(0, v.Major)}.{Math.Max(0, v.Minor)}.{Math.Max(0, v.Build)}";
}
}
public static string CurrentRid
{
get
{
var arch = RuntimeInformation.OSArchitecture switch
{
Architecture.Arm64 => "arm64",
Architecture.X86 => "x86",
_ => "x64"
};
if (OperatingSystem.IsWindows()) return "win-" + arch;
if (OperatingSystem.IsMacOS()) return "osx-" + arch;
if (OperatingSystem.IsLinux()) return "linux-" + arch;
return RuntimeInformation.RuntimeIdentifier;
}
}
public static IModelRemote CreateRemote(AppSettings settings)
{
if (!string.IsNullOrWhiteSpace(settings.UpdateLocalRoot) &&
Directory.Exists(settings.UpdateLocalRoot!))
return new DirectoryRemote(settings.UpdateLocalRoot!);
return new GitCodeRemote(settings.UpdateManifestUrl, settings.UpdateRepository);
}
public async Task<UpdateResult> RunAsync(bool force,
IProgress<UpdateProgress>? progress, CancellationToken ct = default)
{
// 开发态的 model/ 里有源码与工程文件,自动更新一律跳过,避免把源码目录整体替换掉。
// 需要验证更新链路请用 ./build.sh update-test(它使用临时目录,不碰仓库)。
if (_paths.IsDevelopment && Environment.GetEnvironmentVariable("EMS_DEV_UPDATE") != "1")
return new UpdateResult
{
Outcome = UpdateOutcome.Disabled,
Message = "开发态跳过自动更新(保护仓库内模型源码)"
};
if (!force && !_settings.Current.AutoUpdateOnStartup)
return new UpdateResult { Outcome = UpdateOutcome.Disabled, Message = L.I["update.disabled"] };
progress?.Report(new UpdateProgress
{
Value = 0.02,
Message = L.I["update.checking"],
Detail = _remote.DisplayName
});
RepoVersion? remote;
try
{
remote = await _remote.GetVersionAsync(ct);
}
catch (OperationCanceledException) { throw; }
catch (Exception ex)
{
return new UpdateResult
{
Outcome = UpdateOutcome.Unavailable,
Message = L.I["update.offline"],
Error = ex.Message
};
}
if (remote == null)
return new UpdateResult
{
Outcome = UpdateOutcome.Unavailable,
Message = L.I["update.noManifest"]
};
_settings.Current.LastUpdateCheck = DateTime.UtcNow.ToString("O");
_settings.Save();
var needed = remote.Models.Where(NeedsModel).ToList();
var updated = new List<string>();
var errors = new List<string>();
for (var i = 0; i < needed.Count; i++)
{
var model = needed[i];
progress?.Report(new UpdateProgress
{
Value = 0.05 + 0.72 * i / Math.Max(1, needed.Count),
Message = L.I.F("update.downloadingModel", model.Id),
Detail = model.Version
});
try
{
await InstallModelAsync(model, progress, i, needed.Count, ct);
_settings.Current.InstalledModelVersions[model.Id] = model.Version;
_settings.Save();
updated.Add(model.Id);
}
catch (OperationCanceledException) { throw; }
catch (Exception ex)
{
errors.Add($"{model.Id}: {ex.Message}");
Console.Error.WriteLine($"模型更新失败 {model.Id}: {ex.Message}");
}
}
string? launcherMessage = null;
try
{
launcherMessage = await StageLauncherAsync(remote.Launcher, progress, ct);
}
catch (OperationCanceledException) { throw; }
catch (Exception ex)
{
launcherMessage = L.I.F("update.launcherFailed", ex.Message);
errors.Add("launcher: " + ex.Message);
}
progress?.Report(new UpdateProgress { Value = 1, Message = L.I["update.done"] });
var outcome = errors.Count > 0
? UpdateOutcome.Partial
: (updated.Count > 0 || launcherMessage != null)
? UpdateOutcome.Applied
: UpdateOutcome.NoChange;
var message = updated.Count > 0
? L.I.F("update.applied", updated.Count)
: launcherMessage != null ? L.I["update.modelsLatest"] : L.I["update.noChange"];
if (errors.Count > 0) message += L.I.F("update.partial", errors.Count);
return new UpdateResult
{
Outcome = outcome,
Message = message,
UpdatedModels = updated.Count,
ModelNames = updated,
LauncherMessage = launcherMessage,
Error = errors.Count > 0 ? string.Join("; ", errors) : null
};
}
private bool NeedsModel(RepoModel model)
{
if (string.IsNullOrWhiteSpace(model.Id) || string.IsNullOrWhiteSpace(model.Version)) return false;
var dir = Path.Combine(_paths.ModelRoot, model.Id);
if (!Directory.Exists(dir)) return true;
if (!File.Exists(Path.Combine(dir, model.Id + ".json"))) return true;
return !_settings.Current.InstalledModelVersions.TryGetValue(model.Id, out var local) ||
!string.Equals(local, model.Version, StringComparison.OrdinalIgnoreCase);
}
/// <summary>只下载模型清单与模型数据目录,源码 / 文档不进运行目录。</summary>
private static bool IsPayload(string id, string relative)
{
var rel = relative.Replace('\\', '/');
return rel.Equals(id + ".json", StringComparison.OrdinalIgnoreCase) ||
rel.StartsWith(id + ".model/", StringComparison.OrdinalIgnoreCase);
}
private async Task InstallModelAsync(RepoModel model, IProgress<UpdateProgress>? progress,
int index, int count, CancellationToken ct)
{
var rootPath = string.IsNullOrWhiteSpace(model.Dir) ? "model/" + model.Id : model.Dir;
var entries = await _remote.ListTreeAsync(rootPath, ct);
var files = entries.Where(e => !e.IsDirectory && IsPayload(model.Id, e.RelativePath)).ToList();
if (!files.Any(e => e.RelativePath.Equals(model.Id + ".json", StringComparison.OrdinalIgnoreCase)))
throw new InvalidOperationException($"远端缺少模型清单 {model.Id}.json");
if (!files.Any(e => e.RelativePath.StartsWith(model.Id + ".model/", StringComparison.OrdinalIgnoreCase)))
throw new InvalidOperationException($"远端缺少模型数据 {model.Id}.model/");
var staging = Path.Combine(_paths.CacheRoot, "models", model.Id + "-" + Safe(model.Version));
if (Directory.Exists(staging)) Directory.Delete(staging, true);
Directory.CreateDirectory(staging);
try
{
var total = files.Sum(f => Math.Max(1L, f.Size));
long done = 0;
foreach (var entry in files)
{
ct.ThrowIfCancellationRequested();
var bytes = await _remote.DownloadAsync(entry, ct);
var dest = Path.Combine(staging, entry.RelativePath.Replace('/', Path.DirectorySeparatorChar));
var destDir = Path.GetDirectoryName(dest);
if (!string.IsNullOrEmpty(destDir)) Directory.CreateDirectory(destDir);
await File.WriteAllBytesAsync(dest, bytes, ct);
done += bytes.Length;
progress?.Report(new UpdateProgress
{
Value = 0.05 + 0.72 * (index + Math.Min(1, (double)done / Math.Max(1, total))) / Math.Max(1, count),
Message = L.I.F("update.downloadingModel", model.Id),
Detail = entry.RelativePath
});
}
// 原子替换:先备份旧目录,成功后再删备份;失败自动回滚
Directory.CreateDirectory(_paths.ModelRoot);
var target = Path.Combine(_paths.ModelRoot, model.Id);
// 双保险:任何情况下都不允许把含 src/ 源码的模型目录整体换掉
if (Directory.Exists(Path.Combine(target, "src")))
throw new InvalidOperationException($"目标目录含模型源码 src/,拒绝覆盖: {target}");
var backup = target + ".old";
if (Directory.Exists(backup)) Directory.Delete(backup, true);
if (Directory.Exists(target)) Directory.Move(target, backup);
try
{
Directory.Move(staging, target);
}
catch
{
if (Directory.Exists(backup) && !Directory.Exists(target)) Directory.Move(backup, target);
throw;
}
if (Directory.Exists(backup))
{
try { Directory.Delete(backup, true); } catch { /* 占用时留到下次 */ }
}
}
catch
{
try { if (Directory.Exists(staging)) Directory.Delete(staging, true); } catch { }
throw;
}
}
private async Task<string?> StageLauncherAsync(RepoLauncher launcher,
IProgress<UpdateProgress>? progress, CancellationToken ct)
{
var current = CurrentLauncherVersion;
var pending = _settings.Current.PendingLauncherVersion;
if (!string.IsNullOrWhiteSpace(pending) &&
string.Equals(pending, launcher.Version, StringComparison.OrdinalIgnoreCase))
return L.I.F("update.pendingReady", launcher.Version);
if (!IsNewer(launcher.Version, current)) return null;
var rid = CurrentRid;
if (!launcher.Packages.TryGetValue(rid, out var package) &&
!launcher.Packages.TryGetValue("default", out package))
return L.I.F("update.noRidPackage", launcher.Version, rid);
progress?.Report(new UpdateProgress
{
Value = 0.85,
Message = L.I.F("update.downloadingLauncher", launcher.Version)
});
var bytes = await _remote.DownloadPackageAsync(package!, ct);
if (bytes == null || bytes.Length == 0)
return L.I.F("update.noPackageUrl", launcher.Version);
if (!string.IsNullOrWhiteSpace(package!.Sha256))
{
var actual = Convert.ToHexString(SHA256.HashData(bytes)).ToLowerInvariant();
if (!string.Equals(actual, package.Sha256!.Trim(), StringComparison.OrdinalIgnoreCase))
throw new InvalidOperationException("启动器包校验失败(sha256 不符)");
}
Directory.CreateDirectory(_paths.UpdateRoot);
var payload = Path.Combine(_paths.UpdateRoot, "payload");
if (Directory.Exists(payload)) Directory.Delete(payload, true);
var zip = Path.Combine(_paths.CacheRoot, "launcher-" + Safe(launcher.Version) + ".zip");
await File.WriteAllBytesAsync(zip, bytes, ct);
try
{
ZipFile.ExtractToDirectory(zip, payload, true);
}
finally
{
try { File.Delete(zip); } catch { }
}
FlattenPayload(payload);
Json.Write(Path.Combine(_paths.UpdateRoot, "pending.json"), new PendingUpdate
{
Version = launcher.Version,
Rid = rid,
InstallDirectory = _paths.InstallDirectory,
Executable = Path.GetFileName(Environment.ProcessPath ?? ""),
Payload = "payload",
DownloadedAt = DateTime.UtcNow.ToString("O")
});
_settings.Current.PendingLauncherVersion = launcher.Version;
_settings.Save();
return L.I.F("update.pendingDownloaded", launcher.Version);
}
private static void FlattenPayload(string dir)
{
var entries = Directory.GetFileSystemEntries(dir);
if (entries.Length != 1 || !Directory.Exists(entries[0])) return;
var inner = entries[0];
var flat = dir + "-flat";
if (Directory.Exists(flat)) Directory.Delete(flat, true);
Directory.Move(inner, flat);
Directory.Delete(dir, true);
Directory.Move(flat, dir);
}
private static bool IsNewer(string remote, string local)
{
if (Version.TryParse(remote, out var r) && Version.TryParse(local, out var l)) return r > l;
return !string.Equals(remote, local, StringComparison.OrdinalIgnoreCase);
}
private static string Safe(string value)
{
foreach (var c in Path.GetInvalidFileNameChars()) value = value.Replace(c, '-');
return value.Replace('/', '-').Replace(' ', '-');
}
}
@@ -1,17 +1,16 @@
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;
private bool _updateRunning;
public HomeViewModel Home { get; }
public DownloadViewModel Download { get; }
@@ -25,17 +24,21 @@ public partial class MainViewModel : ObservableObject
[ObservableProperty] private bool _isDownloadActive;
[ObservableProperty] private bool _isSettingsActive;
// 启动更新状态条
[ObservableProperty] private bool _updateBarVisible;
[ObservableProperty] private bool _updateBusy;
[ObservableProperty] private double _updateProgress;
[ObservableProperty] private string _updateStatus = "";
[ObservableProperty] private string _updateDetail = "";
[ObservableProperty] private string _launcherNotice = "";
/// <summary>由主窗口注入的确认对话框。</summary>
public Func<string, Task<bool>>? ConfirmHandler { get; set; }
/// <summary>
/// 请求为新模型开一个独立窗口。真正创建窗口的是主窗口,
/// 因此同一个模型可以同时开多份,主界面也不会被替换。
/// </summary>
public event Action<ModelPackage>? PlayerRequested;
public string VersionText => "v1.0.0";
public string PlatformText => RuntimeInformation.RuntimeIdentifier;
public string VersionText => "v" + UpdateService.CurrentLauncherVersion;
public string PlatformText => UpdateService.CurrentRid;
public MainViewModel(AppServices services)
{
@@ -84,4 +87,69 @@ public partial class MainViewModel : ObservableObject
public async Task<bool> ConfirmAsync(string message)
=> ConfirmHandler == null || await ConfirmHandler(message);
// ---- 自动更新 ----------------------------------------------------------
/// <summary>启动后由 App 调用:后台检查更新,不阻塞主界面。</summary>
public Task RunStartupUpdateAsync() => RunUpdateAsync(false);
/// <summary>状态条 / 设置页的「检查更新」,忽略自动开关强制检查。</summary>
[RelayCommand]
private Task CheckUpdate() => RunUpdateAsync(true);
private async Task RunUpdateAsync(bool force)
{
if (_updateRunning) return;
_updateRunning = true;
try
{
UpdateBarVisible = true;
UpdateBusy = true;
UpdateProgress = 0;
UpdateStatus = L.I["update.checking"];
UpdateDetail = "";
LauncherNotice = "";
// 在 UI 线程构造,进度回调自动回到 UI 线程
var progress = new Progress<UpdateProgress>(p =>
{
UpdateProgress = Math.Clamp(p.Value, 0, 1);
UpdateStatus = p.Message;
UpdateDetail = p.Detail ?? "";
});
var result = await _services.Updates.RunAsync(force, progress);
UpdateStatus = result.Message;
UpdateDetail = result.Error ?? "";
LauncherNotice = result.LauncherMessage ?? "";
// 模型下载完成后本次启动就刷新列表,立刻可用
if (result.UpdatedModels > 0) Home.Refresh();
if ((result.Outcome == UpdateOutcome.NoChange || result.Outcome == UpdateOutcome.Applied) &&
string.IsNullOrEmpty(LauncherNotice))
_ = AutoHideAsync();
}
catch (Exception ex)
{
UpdateStatus = L.I["update.offline"];
UpdateDetail = ex.Message;
}
finally
{
UpdateBusy = false;
_updateRunning = false;
}
}
private async Task AutoHideAsync()
{
try
{
await Task.Delay(6000);
if (!_updateRunning && string.IsNullOrEmpty(LauncherNotice)) UpdateBarVisible = false;
}
catch { /* 忽略 */ }
}
}
@@ -30,6 +30,21 @@ public partial class SettingsViewModel : ObservableObject
[ObservableProperty] private int _selectedFps = 30;
[ObservableProperty] private double _memoryValue = 2048;
[ObservableProperty] private string _statusMessage = "";
[ObservableProperty] private bool _autoUpdate = true;
public string UpdateSourceText => _services.Updates.Remote.DisplayName;
public string LastCheckText
{
get
{
var value = _services.Settings.Current.LastUpdateCheck;
if (string.IsNullOrWhiteSpace(value)) return L.I["update.never"];
return DateTimeOffset.TryParse(value, out var time)
? time.ToLocalTime().ToString("yyyy-MM-dd HH:mm") : value!;
}
}
public string PendingText => string.IsNullOrWhiteSpace(_services.Settings.Current.PendingLauncherVersion)
? L.I["update.none"] : _services.Settings.Current.PendingLauncherVersion!;
public string MemoryValueText => $"{(int)Math.Round(MemoryValue)} MB";
public string UsageText => _services.Memory.UsageText;
@@ -54,6 +69,7 @@ public partial class SettingsViewModel : ObservableObject
var settings = _services.Settings.Current;
SelectedFps = settings.RenderFps;
MemoryValue = settings.MemoryMb;
AutoUpdate = settings.AutoUpdateOnStartup;
Sources.Clear();
foreach (var source in settings.Sources)
@@ -65,6 +81,15 @@ public partial class SettingsViewModel : ObservableObject
OnPropertyChanged(nameof(MemoryHint));
OnPropertyChanged(nameof(ModelRoot));
OnPropertyChanged(nameof(DataRoot));
OnPropertyChanged(nameof(UpdateSourceText));
OnPropertyChanged(nameof(LastCheckText));
OnPropertyChanged(nameof(PendingText));
}
partial void OnAutoUpdateChanged(bool value)
{
if (_loading) return;
_services.Settings.Apply(s => s.AutoUpdateOnStartup = value);
}
private void BuildLanguages()
@@ -8,10 +8,10 @@
Background="{DynamicResource AppBg}"
WindowStartupLocation="CenterScreen">
<Grid ColumnDefinitions="236,*">
<Grid ColumnDefinitions="236,*" RowDefinitions="*,Auto">
<!-- 侧栏 -->
<Border Grid.Column="0" Background="{DynamicResource SideBg}">
<Border Grid.Column="0" Grid.RowSpan="2" Background="{DynamicResource SideBg}">
<Grid RowDefinitions="Auto,*,Auto" Margin="16,22,16,18">
<StackPanel Orientation="Horizontal" Spacing="11">
@@ -45,6 +45,30 @@
</Border>
<!-- 内容:页面切换由 MainWindow 做淡入过渡,避免硬切 -->
<ContentControl x:Name="PageHost" Grid.Column="1" Content="{Binding Current}" />
<ContentControl x:Name="PageHost" Grid.Column="1" Grid.Row="0" Content="{Binding Current}" />
<!-- 启动更新状态条:模型立即生效,启动器下次启动生效 -->
<Border Grid.Column="1" Grid.Row="1"
Background="{DynamicResource Surface}"
BorderBrush="{DynamicResource Line}" BorderThickness="0,1,0,0"
Padding="20,9" IsVisible="{Binding UpdateBarVisible}">
<Grid ColumnDefinitions="Auto,*,Auto,Auto">
<TextBlock Grid.Column="0" Text="⟳" FontSize="16" Foreground="{DynamicResource Accent}"
VerticalAlignment="Center" Margin="0,0,12,0" />
<StackPanel Grid.Column="1" Spacing="2" VerticalAlignment="Center">
<TextBlock Text="{Binding UpdateStatus}" FontSize="12.5" FontWeight="SemiBold"
Foreground="{DynamicResource Ink}" TextTrimming="CharacterEllipsis" />
<TextBlock Text="{Binding UpdateDetail}" Classes="faint" TextTrimming="CharacterEllipsis" />
<TextBlock Text="{Binding LauncherNotice}" FontSize="11" Foreground="{DynamicResource Warn}"
TextWrapping="Wrap" />
</StackPanel>
<ProgressBar Grid.Column="2" Width="130" Minimum="0" Maximum="1"
Value="{Binding UpdateProgress}" IsVisible="{Binding UpdateBusy}"
VerticalAlignment="Center" Margin="14,0" />
<Button Grid.Column="3" Classes="ghost small" Content="{loc:Loc update.checkNow}"
Command="{Binding CheckUpdateCommand}" IsEnabled="{Binding !UpdateBusy}"
VerticalAlignment="Center" />
</Grid>
</Border>
</Grid>
</Window>
@@ -84,6 +84,28 @@
</StackPanel>
</Border>
<!-- 自动更新 -->
<Border Classes="card" Padding="20,18">
<StackPanel Spacing="12">
<TextBlock Classes="h2" Text="{loc:Loc update.title}" />
<TextBlock Classes="muted" Text="{loc:Loc update.desc}" TextWrapping="Wrap" />
<CheckBox IsChecked="{Binding AutoUpdate}" Content="{loc:Loc update.auto}" />
<Grid ColumnDefinitions="200,*">
<TextBlock Classes="h3" Text="{loc:Loc update.source}" VerticalAlignment="Center" />
<TextBlock Grid.Column="1" Classes="muted" Text="{Binding UpdateSourceText}"
TextTrimming="CharacterEllipsis" VerticalAlignment="Center" />
</Grid>
<Grid ColumnDefinitions="200,*">
<TextBlock Classes="h3" Text="{loc:Loc update.lastCheck}" />
<TextBlock Grid.Column="1" Classes="muted" Text="{Binding LastCheckText}" />
</Grid>
<Grid ColumnDefinitions="200,*">
<TextBlock Classes="h3" Text="{loc:Loc update.pending}" />
<TextBlock Grid.Column="1" Classes="muted" Text="{Binding PendingText}" />
</Grid>
</StackPanel>
</Border>
<!-- 存储 -->
<Border Classes="card" Padding="20,18">
<StackPanel Spacing="14">