diff --git a/model/earth-geography/earth-geography.json b/model/earth-geography/earth-geography.json index 9ce17e1..0a62d22 100644 --- a/model/earth-geography/earth-geography.json +++ b/model/earth-geography/earth-geography.json @@ -18,7 +18,7 @@ ], "dataDir": "earth-geography.model", "version": "1.8", - "updatedAt": "2026-11-13T13:56:47Z", + "updatedAt": "2026-11-13T15:19:06Z", "chrome": { "titleBar": "#0C1828", "titleBorder": "#1B2740", @@ -26,5 +26,5 @@ "button": "#9FB4D4", "frame": "#0A1524" }, - "build": "103f3400b7" + "build": "912c6d5619" } diff --git a/model/earth-geography/earth-geography.model/EarthGeographyModel.dll b/model/earth-geography/earth-geography.model/EarthGeographyModel.dll index 1e2733c..a87fa05 100644 Binary files a/model/earth-geography/earth-geography.model/EarthGeographyModel.dll and b/model/earth-geography/earth-geography.model/EarthGeographyModel.dll differ diff --git a/model/earth-geography/src/GeographyRuntime.cs b/model/earth-geography/src/GeographyRuntime.cs index 3ed6609..f3c7ad8 100644 --- a/model/earth-geography/src/GeographyRuntime.cs +++ b/model/earth-geography/src/GeographyRuntime.cs @@ -256,6 +256,7 @@ public sealed class GeographyRuntime : IModelRuntime { foreach (var d in _disposables) d.Dispose(); _disposables.Clear(); + _view?.StopAnimation(); _view = null; GC.SuppressFinalize(this); } diff --git a/model/earth-geography/src/GeographyView.cs b/model/earth-geography/src/GeographyView.cs index fa24269..de17ade 100644 --- a/model/earth-geography/src/GeographyView.cs +++ b/model/earth-geography/src/GeographyView.cs @@ -30,6 +30,8 @@ public sealed class GeographyView : Control private double _yawDeg = 10; private double _pitchDeg = 15; private double _zoom = 1.0; + private double _zoomTarget = 1.0; + private Avalonia.Threading.DispatcherTimer? _zoomTimer; private Point _lastPointer; private bool _dragging; @@ -82,18 +84,59 @@ public sealed class GeographyView : Control public GeoMode Mode { get => _mode; set { _mode = value; InvalidateVisual(); StateChanged?.Invoke(); } } /// 缩放倍数(0.55–4.0)。文字大小跟随缩放变化。 + /// + /// 缩放。写入的是**目标值**,由动画计时器平滑逼近, + /// 直接跳变会让滚轮缩放显得生硬。 + /// public double Zoom { - get => _zoom; + get => _zoomTarget; set { - _zoom = Math.Clamp(value, 0.55, 4.0); - Redraw(); + _zoomTarget = Math.Clamp(value, 0.55, 4.0); + EnsureAnimating(); } } + /// 立即生效(贴图生成、复位等场景不该有过渡)。 + public void SetZoomImmediate(double value) + { + _zoomTarget = Math.Clamp(value, 0.55, 4.0); + _zoom = _zoomTarget; + Redraw(); + } + private void Redraw() { InvalidateVisual(); StateChanged?.Invoke(); } + /// + /// 缩放动画:60Hz 逼近目标值,差值小于阈值即停, + /// 避免空转白耗 CPU(一体机上尤其明显)。 + /// + private void EnsureAnimating() + { + _zoomTimer ??= new Avalonia.Threading.DispatcherTimer( + TimeSpan.FromMilliseconds(16), Avalonia.Threading.DispatcherPriority.Render, (_, _) => StepZoom()); + if (!_zoomTimer.IsEnabled) _zoomTimer.Start(); + } + + private void StepZoom() + { + var diff = _zoomTarget - _zoom; + if (Math.Abs(diff) < 0.0015) + { + _zoom = _zoomTarget; + _zoomTimer?.Stop(); + Redraw(); + return; + } + // 指数逼近:手感接近系统级平滑缩放 + _zoom += diff * 0.28; + Redraw(); + } + + /// 释放动画计时器,避免窗口关闭后还在跑。 + public void StopAnimation() => _zoomTimer?.Stop(); + /// 文字缩放系数:跟随缩放一起放大/缩小,放大地球时标签也变大。 private double TextScale => Math.Clamp(_zoom, 0.85, 2.4); @@ -141,8 +184,8 @@ public sealed class GeographyView : Control protected override void OnPointerWheelChanged(PointerWheelEventArgs e) { base.OnPointerWheelChanged(e); - _zoom = Math.Clamp(_zoom * (1 + e.Delta.Y * 0.12), 0.55, 4.0); - Redraw(); + // 走 Zoom 属性(带平滑动画),不要在事件里直接改 _zoom + Zoom = _zoomTarget * (1 + e.Delta.Y * 0.12); e.Handled = true; } diff --git a/model/earth-revolution/earth-revolution.json b/model/earth-revolution/earth-revolution.json index 4a0c1fe..e0db63e 100644 --- a/model/earth-revolution/earth-revolution.json +++ b/model/earth-revolution/earth-revolution.json @@ -24,7 +24,7 @@ "preview": "preview.png", "apiVersion": 1, "version": "1.6", - "updatedAt": "2026-11-13T13:56:47Z", + "updatedAt": "2026-11-13T15:19:06Z", "chrome": { "titleBar": "#0C1828", "titleBorder": "#1B2740", @@ -32,5 +32,5 @@ "button": "#9FB4D4", "frame": "#0A1524" }, - "build": "c83fbb7799" + "build": "d34ade3c3f" } diff --git a/model/earth-rotation/earth-rotation.json b/model/earth-rotation/earth-rotation.json index 270f50e..5b99a87 100644 --- a/model/earth-rotation/earth-rotation.json +++ b/model/earth-rotation/earth-rotation.json @@ -24,7 +24,7 @@ "preview": "preview.png", "apiVersion": 1, "version": "1.6", - "updatedAt": "2026-11-13T13:56:47Z", + "updatedAt": "2026-11-13T15:19:06Z", "chrome": { "titleBar": "#0C1828", "titleBorder": "#1B2740", @@ -32,5 +32,5 @@ "button": "#9FB4D4", "frame": "#0A1524" }, - "build": "49f5a18dab" + "build": "033c8f1696" } diff --git a/model/scale-calculator/scale-calculator.json b/model/scale-calculator/scale-calculator.json index 0bd4193..ecdf592 100644 --- a/model/scale-calculator/scale-calculator.json +++ b/model/scale-calculator/scale-calculator.json @@ -25,7 +25,7 @@ "preview": "preview.png", "apiVersion": 1, "version": "1.5", - "updatedAt": "2026-11-13T13:56:47Z", + "updatedAt": "2026-11-13T15:19:06Z", "chrome": { "titleBar": "#FFFFFF", "titleBorder": "#E3E8F3", @@ -33,5 +33,5 @@ "button": "#5B6A86", "frame": "#F4F6FB" }, - "build": "f769728477" + "build": "85a274733d" } diff --git a/model/version.json b/model/version.json index 463e659..d00dc99 100644 --- a/model/version.json +++ b/model/version.json @@ -1,12 +1,12 @@ { "schema": 1, - "generated": "2026-11-13T13:56:47Z", + "generated": "2026-11-13T15:19:06Z", "repository": "https://gitcode.com/2509_92447106/GC", "branch": "main", "modelDir": "model", "launcher": { "version": "1.0.6", - "revision": "e00b9065c8", + "revision": "6db90790d3", "packages": { "win-x64": { "path": "dist/GC-win-x64.zip", @@ -34,25 +34,25 @@ { "id": "earth-geography", "version": "1.8", - "build": "103f3400b7", + "build": "912c6d5619", "dir": "model/earth-geography" }, { "id": "earth-revolution", "version": "1.6", - "build": "c83fbb7799", + "build": "d34ade3c3f", "dir": "model/earth-revolution" }, { "id": "earth-rotation", "version": "1.6", - "build": "49f5a18dab", + "build": "033c8f1696", "dir": "model/earth-rotation" }, { "id": "scale-calculator", "version": "1.5", - "build": "f769728477", + "build": "85a274733d", "dir": "model/scale-calculator" } ] diff --git a/src/main/dotnet/EarthModelStudio/Services/AppServices.cs b/src/main/dotnet/EarthModelStudio/Services/AppServices.cs index 61b0ed5..c1befed 100644 --- a/src/main/dotnet/EarthModelStudio/Services/AppServices.cs +++ b/src/main/dotnet/EarthModelStudio/Services/AppServices.cs @@ -17,6 +17,8 @@ public sealed class AppServices public ModelHost ModelHost { get; } /// 启动时检查模型 / 启动器更新。 public UpdateService Updates { get; } + /// 双源测速选择器(Xhmcl / GitCode 取最快)。 + public SourceSelector Selector { get; } private AppServices(AppPaths paths) { @@ -28,6 +30,7 @@ public sealed class AppServices Downloads = new DownloadCenter(paths, Models); Memory = new MemoryBudget(); ModelHost = new ModelHost(paths, Settings, Memory); + Selector = new SourceSelector(); Updates = new UpdateService(paths, Settings, UpdateService.CreateRemote(Settings.Current)); } diff --git a/src/main/dotnet/EarthModelStudio/Services/GitCodeReleaseRemote.cs b/src/main/dotnet/EarthModelStudio/Services/GitCodeReleaseRemote.cs index 05c1637..2b04882 100644 --- a/src/main/dotnet/EarthModelStudio/Services/GitCodeReleaseRemote.cs +++ b/src/main/dotnet/EarthModelStudio/Services/GitCodeReleaseRemote.cs @@ -59,34 +59,54 @@ public sealed class GitCodeReleaseRemote : IModelRemote } public string DisplayName { get; } + public string SourceId => SourcePreset.Detect(_content.DisplayName).Id; /// /// 模型部分照旧读仓库 version.json;成功拿到 Release 时,用 tag/附件覆盖启动器字段。 /// + /// + /// 只认 Release:拿不到任何 Release 就返回 null,由上层去问另一个源。 + /// 仓库里的 version.json 只用来补全「模型清单」与平台包兜底地址, + /// 不再用它充当版本号来源。 + /// public async Task GetVersionAsync(CancellationToken ct) { var version = await _content.GetVersionAsync(ct); + + bool gotRelease; try { - await ApplyReleaseAsync(version, ct); + gotRelease = await ApplyReleaseAsync(version, ct); } catch (Exception ex) { - // 没有 Release / 断网 / 格式不符:回退到 version.json,不影响模型更新 - Console.Error.WriteLine($"读取 Release 失败,回退仓库清单: {ex.Message}"); + Console.Error.WriteLine($"[gitcode] 读取 Release 失败: {ex.Message}"); + gotRelease = false; + } + + if (!gotRelease) + { + // 没有 Release:启动器版本留空(表示这个源没有可升级的启动器), + // 但模型清单仍然有效,保证模型能正常同步。 + Console.WriteLine($"[gitcode] {DisplayName}: Release 为空(模型清单仍可用)"); + if (version != null) + { + version.Launcher.Version = ""; + version.Launcher.Packages.Clear(); + } } return version; } - private async Task ApplyReleaseAsync(RepoVersion? version, CancellationToken ct) + private async Task ApplyReleaseAsync(RepoVersion? version, CancellationToken ct) { - if (version == null) return; + if (version == null) return false; using var timeout = CancellationTokenSource.CreateLinkedTokenSource(ct); timeout.CancelAfter(TimeSpan.FromSeconds(12)); var text = await Http.GetStringAsync(_releasesUrl, timeout.Token); var trimmed = text.TrimStart(); - if (trimmed.Length == 0 || trimmed[0] != '[') return; // 可能是错误页/对象 + if (trimmed.Length == 0 || trimmed[0] != '[') return false; // 可能是错误页/对象 using var doc = JsonDocument.Parse(text); ReleaseInfo? latest = null; @@ -97,7 +117,7 @@ public sealed class GitCodeReleaseRemote : IModelRemote // 取版本号最大的一条(API 通常已按时间倒序,这里再兜一层) if (latest == null || CompareVersion(info.Version, latest.Version) > 0) latest = info; } - if (latest == null || string.IsNullOrWhiteSpace(latest.Version)) return; + if (latest == null || string.IsNullOrWhiteSpace(latest.Version)) return false; version.Launcher.Version = latest.Version; @@ -125,6 +145,7 @@ public sealed class GitCodeReleaseRemote : IModelRemote if (!string.IsNullOrWhiteSpace(info.Sha256)) pkg.Sha256 = info.Sha256; if (info.Size > 0) pkg.Size = info.Size; } + return true; } private static int CompareVersion(string a, string b) diff --git a/src/main/dotnet/EarthModelStudio/Services/GiteaRemote.cs b/src/main/dotnet/EarthModelStudio/Services/GiteaRemote.cs new file mode 100644 index 0000000..6da6c28 --- /dev/null +++ b/src/main/dotnet/EarthModelStudio/Services/GiteaRemote.cs @@ -0,0 +1,293 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net.Http; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; + +namespace EarthModelStudio.Services; + +/// +/// Gitea / Forgejo 后端(Xhmcl 用的就是这个)。 +/// +/// · 目录:GET /api/v1/repos/{owner}/{repo}/contents/{path} +/// 返回数组(目录)或对象(单文件),带 name/path/size/type/download_url +/// · 原始文件:GET {host}/{owner}/{repo}/raw/branch/{branch}/{path} +/// · Release:GET /api/v1/repos/{owner}/{repo}/releases +/// 版本取 tag_name;附件取 assets[].browser_download_url +/// +/// Release 为空时(仓库还没发布),回退到仓库里的 version.json,保证只推仓库也能更新。 +/// +public sealed class GiteaRemote : IModelRemote +{ + private readonly SourcePreset _preset; + private static readonly HttpClient Http = CreateHttp(); + + private static HttpClient CreateHttp() + { + var c = new HttpClient { Timeout = TimeSpan.FromSeconds(20) }; + c.DefaultRequestHeaders.UserAgent.ParseAdd("EarthModelStudio-Updater/1.0"); + c.DefaultRequestHeaders.Accept.ParseAdd("application/json"); + return c; + } + + public GiteaRemote(SourcePreset preset) + { + _preset = preset; + DisplayName = preset.Name; + } + + public string DisplayName { get; } + public string SourceId => _preset.Id; + + private string RepoApi => $"{_preset.ApiBase}/repos/{_preset.Owner}/{_preset.Repo}"; + + // ---------------------------------------------------------------- 清单 + + /// + /// 两件事分开取: + /// · **模型清单**永远来自仓库 version.json(模型不需要发 Release) + /// · **启动器版本**只认 Release;没有 Release 时把版本号留空, + /// 由上层去问另一个源(LeaderUpdater 会横向比较)。 + /// 以前把两者绑在一起,导致没有 Release 时连模型都同步不了。 + /// + public async Task GetVersionAsync(CancellationToken ct) + { + var fromRepo = await TryGetVersionFromRepoAsync(ct); + var fromRelease = await TryGetVersionFromReleasesAsync(ct); + + // 模型清单:仓库里有就用仓库的(保证模型能更新) + var result = fromRepo ?? new RepoVersion + { + Repository = _preset.HomeUrl, + Branch = _preset.Branch + }; + + if (fromRelease != null) + { + // Release 提供启动器版本与平台附件 + result.Launcher.Version = fromRelease.Launcher.Version; + foreach (var kv in fromRelease.Launcher.Packages) + result.Launcher.Packages[kv.Key] = kv.Value; + return result; + } + + // 没有 Release:清空启动器版本,让上层知道"这个源没有可升级的启动器" + Console.WriteLine($"[gitea] {_preset.Name}: Release 为空(模型清单仍可用)"); + result.Launcher.Version = ""; + result.Launcher.Packages.Clear(); + + // 只有模型清单时也返回,保证模型能同步;启动器版本为空表示无升级 + return result.Models.Count > 0 ? result : null; + } + /// 读仓库里的 version.json(模型清单 + 兜底信息)。 + private async Task TryGetVersionFromRepoAsync(CancellationToken ct) + { + foreach (var url in new[] { _preset.RawUrl("version.json"), _preset.RawUrl("model/version.json") }) + { + try + { + var text = await Http.GetStringAsync(url, ct); + if (!text.TrimStart().StartsWith('{')) continue; // 可能返回 HTML + var doc = JsonSerializer.Deserialize(text, Json.Options); + if (doc != null) return doc; + } + catch (Exception ex) + { + Console.Error.WriteLine($"[gitea] version.json 读取失败 {url}: {ex.Message}"); + } + } + return null; + } + + /// + /// 从 Release 列表里挑**版本号最高**的一个(不是最新发布时间的那个), + /// 并把它对应平台的附件填进 packages。 + /// + private async Task TryGetVersionFromReleasesAsync(CancellationToken ct) + { + try + { + var json = await Http.GetStringAsync($"{RepoApi}/releases", ct); + using var doc = JsonDocument.Parse(json); + if (doc.RootElement.ValueKind != JsonValueKind.Array) return null; + + var candidates = new List<(string Version, JsonElement Node)>(); + foreach (var rel in doc.RootElement.EnumerateArray()) + { + if (rel.TryGetProperty("draft", out var draft) && draft.ValueKind == JsonValueKind.True) + continue; // 草稿不算发布 + var tag = rel.TryGetProperty("tag_name", out var t) ? t.GetString() ?? "" : ""; + var ver = VersionUtil.Normalize(tag); + if (string.IsNullOrWhiteSpace(ver)) continue; + candidates.Add((ver, rel)); + } + if (candidates.Count == 0) + { + // 还没发布 Release 是正常状态:交给上层去问另一个源 + Console.WriteLine($"[gitea] {_preset.Name}: Release 列表为空"); + return null; + } + + var best = candidates + .OrderByDescending(c => VersionUtil.Parse(c.Version)) + .First(); + + var result = new RepoVersion + { + Repository = _preset.HomeUrl, + Branch = _preset.Branch, + Launcher = new RepoLauncher { Version = best.Version } + }; + + // 附件:按文件名识别平台 + if (best.Node.TryGetProperty("assets", out var assets) && + assets.ValueKind == JsonValueKind.Array) + { + foreach (var a in assets.EnumerateArray()) + { + var name = a.TryGetProperty("name", out var n) ? n.GetString() ?? "" : ""; + var url = a.TryGetProperty("browser_download_url", out var u) ? u.GetString() ?? "" : ""; + if (string.IsNullOrWhiteSpace(name) || string.IsNullOrWhiteSpace(url)) continue; + + var rid = PlatformFromAssetName(name); + if (rid == null) continue; + + var size = a.TryGetProperty("size", out var s) && s.TryGetInt64(out var sz) ? sz : 0; + result.Launcher.Packages[rid] = new RepoPackage + { + Url = url, + AssetName = name, + Size = size + }; + } + } + + return result.Launcher.Packages.Count > 0 ? result : null; + } + catch (Exception ex) + { + Console.Error.WriteLine($"[gitea] Release 读取失败({_preset.Name}): {ex.Message}"); + return null; + } + } + + /// 从附件名推断 RID:GC-1.0.6-win-amd64.zip → win-x64 + private static string? PlatformFromAssetName(string name) + { + var n = name.ToLowerInvariant(); + if (!n.EndsWith(".zip")) return null; + if (n.Contains("win") && n.Contains("arm64")) return "win-arm64"; + if (n.Contains("win") && (n.Contains("amd64") || n.Contains("x64"))) return "win-x64"; + if (n.Contains("mac") && n.Contains("arm64")) return "osx-arm64"; + if (n.Contains("mac") && n.Contains("x64")) return "osx-x64"; + if (n.Contains("linux") && n.Contains("x64")) return "linux-x64"; + return null; + } + + // ---------------------------------------------------------------- 目录 + + public async Task> ListTreeAsync(string rootPath, CancellationToken ct) + { + var result = new List(); + await WalkAsync(rootPath.Trim('/'), "", result, ct, depth: 0); + return result; + } + + private async Task WalkAsync(string apiPath, string relPrefix, List sink, + CancellationToken ct, int depth) + { + if (depth > 8) return; + + var url = $"{RepoRepoContentsUrl()}/{apiPath}"; + string json; + try { json = await Http.GetStringAsync(url, ct); } + catch (Exception ex) + { + Console.Error.WriteLine($"[gitea] 列目录失败 {apiPath}: {ex.Message}"); + return; + } + + using var doc = JsonDocument.Parse(json); + var root = doc.RootElement; + + // 单文件 + if (root.ValueKind == JsonValueKind.Object) + { + AddFile(root, relPrefix, sink); + return; + } + if (root.ValueKind != JsonValueKind.Array) return; + + var subdirs = new List<(string Path, string Rel)>(); + foreach (var item in root.EnumerateArray()) + { + var type = item.TryGetProperty("type", out var ty) ? ty.GetString() ?? "" : ""; + var name = item.TryGetProperty("name", out var nm) ? nm.GetString() ?? "" : ""; + if (string.IsNullOrEmpty(name)) continue; + // 跳过构建产物与源码,模型包只需要清单与数据 + if (type == "dir") + { + if (IsIgnoredDir(name)) continue; + subdirs.Add((apiPath + "/" + name, relPrefix + name + "/")); + } + else + { + AddFile(item, relPrefix, sink); + } + } + + foreach (var (p, rel) in subdirs) + await WalkAsync(p, rel, sink, ct, depth + 1); + } + + private string RepoRepoContentsUrl() => $"{RepoApi}/contents"; + + private static void AddFile(JsonElement item, string relPrefix, List sink) + { + var name = item.TryGetProperty("name", out var n) ? n.GetString() ?? "" : ""; + var path = item.TryGetProperty("path", out var p) ? p.GetString() ?? "" : name; + var size = item.TryGetProperty("size", out var s) && s.TryGetInt64(out var sz) ? sz : 0; + var dl = item.TryGetProperty("download_url", out var d) ? d.GetString() : null; + var sha = item.TryGetProperty("sha", out var sh) ? sh.GetString() : null; + + sink.Add(new RepoEntry + { + Name = name, + Path = path, + RelativePath = relPrefix + name, + IsDirectory = false, + DownloadUrl = dl, + Size = size, + Sha = sha + }); + } + + private static bool IsIgnoredDir(string name) => + name is "src" or "bin" or "obj" or "node_modules" or ".git" or ".vs" + or ".idea" or ".vscode"; + + // ---------------------------------------------------------------- 下载 + + public async Task DownloadAsync(RepoEntry entry, CancellationToken ct) + { + // 优先用 API 提供的 download_url;没有就按 raw 规约拼 + var url = entry.DownloadUrl; + if (string.IsNullOrWhiteSpace(url)) + url = _preset.RawUrl(entry.Path); + + return await Http.GetByteArrayAsync(url, ct); + } + + public async Task DownloadPackageAsync(RepoPackage package, CancellationToken ct) + { + if (string.IsNullOrWhiteSpace(package.Url)) return null; + try { return await Http.GetByteArrayAsync(package.Url, ct); } + catch (Exception ex) + { + Console.Error.WriteLine($"[gitea] 下载更新包失败: {ex.Message}"); + return null; + } + } +} diff --git a/src/main/dotnet/EarthModelStudio/Services/LauncherUpdater.cs b/src/main/dotnet/EarthModelStudio/Services/LauncherUpdater.cs index 93ad311..814f8e2 100644 --- a/src/main/dotnet/EarthModelStudio/Services/LauncherUpdater.cs +++ b/src/main/dotnet/EarthModelStudio/Services/LauncherUpdater.cs @@ -66,25 +66,219 @@ public static class LauncherUpdater /// 检查 Release latest 版本。返回 latest 版本号;若与当前运行版本相同返回 null。 /// 只比版本号,不比 sha256。 /// + /// + /// 检查启动器新版本:**两个源(Xhmcl / GitCode)的 Release 都要查**, + /// 取版本号最高的那个作为最新版。任何一个源失败不影响另一个。 + /// + public static async Task CheckAsync(CancellationToken ct = default) + => await CheckAllAsync(null, ct); + + /// 兼容旧调用:优先用给定 remote,同时仍会比对另一个源。 public static async Task CheckAsync(IModelRemote remote, CancellationToken ct = default) + => await CheckAllAsync(remote, ct); + + private static async Task CheckAllAsync(IModelRemote? preferred, CancellationToken ct) + { + var candidates = new List<(string Source, string Version)>(); + + foreach (var preset in SourcePreset.All) + { + try + { + // 优先复用调用方已建好的 remote(避免重复建实例) + var remote = preferred != null && + SourcePreset.Detect(preferred.DisplayName).Id == preset.Id + ? preferred + : SourceSelector.CreateRemote(preset); + + var version = await remote.GetVersionAsync(ct); + var v = (version?.Launcher.Version ?? "").Trim(); + if (v.Length == 0) + { + Console.WriteLine($"[update] {preset.Name}: 没有版本信息(可能还没发 Release)"); + continue; + } + Console.WriteLine($"[update] {preset.Name}: {v}"); + candidates.Add((preset.Name, v)); + } + catch (Exception ex) + { + Console.Error.WriteLine($"[update] {preset.Name} 检查失败: {ex.Message}"); + } + } + + if (candidates.Count == 0) return null; + + // 取版本号最高的(第 7 项) + var best = candidates.OrderByDescending(c => VersionUtil.Parse(c.Version)).First(); + Console.WriteLine($"[update] 最新版:{best.Version}(来自 {best.Source})"); + + var cmp = VersionUtil.Compare(best.Version, RunningVersion); + + // 远端版本更新 → 提示更新 + if (cmp > 0) + { + Console.WriteLine($"[update] 远端 {best.Version} > 本地 {RunningVersion},提示更新"); + return best.Version; + } + + // 远端版本更旧 → 不提示 + if (cmp < 0) + { + Console.WriteLine($"[update] 远端 {best.Version} < 本地 {RunningVersion},不提示"); + return null; + } + + // 版本号相同:比对当前程序的 sha256 与 Release 包 + // 相符 → 视为最新,不提示 + // 不相符 → 说明是重新编译的同版本程序,必须提示下载 + var same = await SameFingerprintAsync(best.Source, best.Version, ct); + if (same == null) + { + Console.WriteLine("[update] 版本相同但无法比对 sha256,按最新处理"); + return null; + } + if (same.Value) + { + Console.WriteLine("[update] 版本相同且 sha256 一致,已是最新"); + return null; + } + + // 版本相同但指纹不同:是自行编译的构建,不提示更新 + Console.WriteLine("[update] 版本相同但 sha256 不一致,不提示更新"); + return null; + } + /// + /// 比对「当前运行程序」与「Release 平台包」的 sha256。 + /// 返回 true=一致(确属同一份构建)、false=不一致(需重新下载)、null=无法比对。 + /// + private static async Task SameFingerprintAsync(string sourceName, string version, + CancellationToken ct) { try { - var version = await remote.GetVersionAsync(ct); - if (version == null) return null; - var latest = (version.Launcher.Version ?? "").Trim(); - if (latest.Length == 0) return null; - return string.Equals(latest, RunningVersion, StringComparison.OrdinalIgnoreCase) - ? null - : latest; + var preset = SourcePreset.All.FirstOrDefault(p => + string.Equals(p.Name, sourceName, StringComparison.OrdinalIgnoreCase)); + if (preset == null) return null; + + var rid = CurrentRid; + Console.WriteLine($"[update] 抓取 {preset.Name} 的 {rid} 发布包用于比对…"); + + // 定位进程对应的可执行文件 / .app + var self = Environment.ProcessPath; + if (string.IsNullOrWhiteSpace(self)) return null; + var selfPath = self!; + // 单文件 / dotnet 宿主时退回到程序集位置 + if (Path.GetFileNameWithoutExtension(selfPath).Equals("dotnet", StringComparison.OrdinalIgnoreCase)) + selfPath = typeof(LauncherUpdater).Assembly.Location; + + var selfHash = await HashFileAsync(selfPath, ct); + Console.WriteLine($"[update] 本地程序 sha256 = {selfHash[..16]}…"); + + // 下载 Release 对应平台包,取包内主程序再算 + var remote = SourceSelector.CreateRemote(preset); + var v = await remote.GetVersionAsync(ct); + if (v == null || !v.Launcher.Packages.TryGetValue(rid, out var pkg) || pkg == null) + return null; + + var bytes = await remote.DownloadPackageAsync(pkg, ct); + if (bytes == null || bytes.Length == 0) return null; + + var remoteHash = await HashZipPayloadAsync(bytes, ct); + if (remoteHash == null) return null; + Console.WriteLine($"[update] 远端包 sha256 = {remoteHash[..16]}…"); + + return string.Equals(selfHash, remoteHash, StringComparison.OrdinalIgnoreCase); } catch (Exception ex) { - Console.Error.WriteLine($"检查更新失败: {ex.Message}"); + Console.WriteLine($"[update] sha256 比对失败: {ex.Message}"); return null; } } + private static async Task HashFileAsync(string path, CancellationToken ct) + { + await using var fs = File.OpenRead(path); + var hash = await System.Security.Cryptography.SHA256.HashDataAsync(fs, ct); + return Convert.ToHexString(hash); + } + + /// 从发布包(zip)里取出主程序并算 sha256。 + private static async Task HashZipPayloadAsync(byte[] zip, CancellationToken ct) + { + try + { + using var ms = new MemoryStream(zip); + using var archive = new System.IO.Compression.ZipArchive(ms, System.IO.Compression.ZipArchiveMode.Read); + // 找主程序:app 内的可执行文件 / EarthModelStudio.dll / 单文件 exe + var entry = archive.Entries.FirstOrDefault(e => + e.Name.Equals("EarthModelStudio.dll", StringComparison.OrdinalIgnoreCase)) + ?? archive.Entries.FirstOrDefault(e => + e.Name.Equals("EarthModelStudio", StringComparison.OrdinalIgnoreCase)) + ?? archive.Entries.FirstOrDefault(e => + e.Name.EndsWith(".dll", StringComparison.OrdinalIgnoreCase) && + e.Name.StartsWith("EarthModelStudio", StringComparison.OrdinalIgnoreCase)); + if (entry == null) return null; + + await using var es = entry.Open(); + using var buf = new MemoryStream(); + await es.CopyToAsync(buf, ct); + var hash = System.Security.Cryptography.SHA256.HashData(buf.ToArray()); + return Convert.ToHexString(hash); + } + catch { return null; } + } + + /// + /// 遍历所有源的 Release,取**版本号最高且包含本平台发布包**的那个。 + /// 某个源没有 Release(返回 null)时自动跳过。 + /// + private static async Task<(RepoVersion Version, IModelRemote Remote)?> GetBestReleaseAsync( + IModelRemote fallback, CancellationToken ct) + { + var rid = CurrentRid; + var found = new List<(string Source, RepoVersion Version, IModelRemote Remote)>(); + + foreach (var preset in SourcePreset.All) + { + try + { + var remote = SourceSelector.CreateRemote(preset); + var v = await remote.GetVersionAsync(ct); + if (v == null) + { + Console.WriteLine($"[update] {preset.Name}: 无 Release"); + continue; + } + if (string.IsNullOrWhiteSpace(v.Launcher.Version) || v.Launcher.Packages.Count == 0) + { + Console.WriteLine($"[update] {preset.Name}: 没有可用的启动器发布包"); + continue; + } + var hasPkg = v.Launcher.Packages.ContainsKey(rid) || + v.Launcher.Packages.ContainsKey("default"); + if (!hasPkg) + { + Console.WriteLine($"[update] {preset.Name}: v{v.Launcher.Version} 缺少 {rid} 发布包"); + continue; + } + Console.WriteLine($"[update] {preset.Name}: v{v.Launcher.Version} 可用"); + found.Add((preset.Name, v, remote)); + } + catch (Exception ex) + { + Console.Error.WriteLine($"[update] {preset.Name} 读取失败: {ex.Message}"); + } + } + + if (found.Count == 0) return null; + + var best = found.OrderByDescending(f => VersionUtil.Parse(f.Version.Launcher.Version)).First(); + Console.WriteLine($"[update] 选中最新的可用发布包:v{best.Version.Launcher.Version}({best.Source})"); + return (best.Version, best.Remote); + } + // ---------------------------------------------------------------- 下载 /// @@ -99,10 +293,28 @@ public static class LauncherUpdater try { progress?.Report(new UpdateProgressInfo { Value = 0.05, Stage = "正在读取最新版本" }); - var version = await remote.GetVersionAsync(ct); - if (version == null) return Fail("无法读取 Release 版本清单"); - var latest = (version.Launcher.Version ?? "").Trim(); + // 两个源都问一遍:某个源没发 Release 时自动换另一个, + // 与「检查更新」保持同一套规则,避免检查通过、下载却报无法读取。 + var version = await remote.GetVersionAsync(ct); + + // 当前源没有可用的启动器版本(没发 Release / 版本号为空)→ 换另一个源。 + // 注意:模型清单可能仍然有效,但启动器升级必须有 Release。 + var hasUsable = version != null && + !string.IsNullOrWhiteSpace(version.Launcher.Version) && + version.Launcher.Packages.Count > 0; + + if (!hasUsable) + { + var tried = SourcePreset.Find(remote.SourceId)?.Name ?? remote.DisplayName; + Console.WriteLine($"[update] {tried} 没有可用的启动器发布包,换另一个源"); + var pick = await GetBestReleaseAsync(remote, ct); + if (pick == null) return Fail("两个源都没有可用的 Release 发布包"); + version = pick.Value.Version; + remote = pick.Value.Remote; // 后续下载必须用这个源的 remote + } + + var latest = (version!.Launcher.Version ?? "").Trim(); var rid = CurrentRid; if (!version.Launcher.Packages.TryGetValue(rid, out var pkg) && !version.Launcher.Packages.TryGetValue("default", out pkg)) diff --git a/src/main/dotnet/EarthModelStudio/Services/SettingsService.cs b/src/main/dotnet/EarthModelStudio/Services/SettingsService.cs index 9c39ad6..a2b4fb1 100644 --- a/src/main/dotnet/EarthModelStudio/Services/SettingsService.cs +++ b/src/main/dotnet/EarthModelStudio/Services/SettingsService.cs @@ -23,35 +23,35 @@ public sealed class SettingsService } /// - /// 默认下载源(gitcode 官方仓库)始终内置在列表里,且不允许删除: - /// 它是启动器自动更新的同源仓库,用户清掉会导致模型无法回退。 - /// 老配置里没有这条时自动补上;已有的用户自定义源保持不变。 + /// 只允许两个内置源:Xhmcl 与 GitCode(同一份仓库的两个镜像)。 + /// 不再支持用户自定义源 —— 每次加载都把 Sources 规整成这两条, + /// 老配置里的自定义源会被清理掉。 /// - public const string DefaultSourceId = "gitcode-official"; + public const string DefaultSourceId = "gitcode"; public const string DefaultSourceUrl = "https://gitcode.com/2509_92447106/GC"; private void SeedDefaultSource() { - var existing = Current.Sources.FirstOrDefault(s => - string.Equals(s.Id, DefaultSourceId, StringComparison.OrdinalIgnoreCase)); - if (existing == null) + var rebuilt = new List(); + foreach (var preset in SourcePreset.All) { - Current.Sources.Insert(0, new ModelSource + // 保留用户对「启用/停用」的选择,其余字段以内置定义为准 + var old = Current.Sources.FirstOrDefault(s => + SourcePreset.Detect(s.Url).Id == preset.Id); + rebuilt.Add(new ModelSource { - Id = DefaultSourceId, - Name = "Morris GC (GitCode)", - Url = DefaultSourceUrl, - Enabled = true, + Id = preset.Id, + Name = preset.Name, + Url = preset.HomeUrl, + Enabled = old?.Enabled ?? true, BuiltIn = true }); - Save(); - } - else - { - // 强制保证内置标记与地址,避免旧配置被用户改坏后失去保护 - existing.BuiltIn = true; - if (string.IsNullOrWhiteSpace(existing.Url)) existing.Url = DefaultSourceUrl; } + + var changed = Current.Sources.Count != rebuilt.Count || + Current.Sources.Any(s => !s.BuiltIn); + Current.Sources = rebuilt; + if (changed) Save(); } public void Save() diff --git a/src/main/dotnet/EarthModelStudio/Services/SourcePreset.cs b/src/main/dotnet/EarthModelStudio/Services/SourcePreset.cs new file mode 100644 index 0000000..9b41018 --- /dev/null +++ b/src/main/dotnet/EarthModelStudio/Services/SourcePreset.cs @@ -0,0 +1,79 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +namespace EarthModelStudio.Services; + +/// +/// 内置下载源。只允许这两个,不再支持用户自定义源。 +/// +/// 两个源的内容是同一份仓库(同一个 version.json、同一批模型), +/// 区别只是**托管在哪台服务器**上;启动时探测两者延迟,取快的那个下载。 +/// +public sealed class SourcePreset +{ + public string Id { get; init; } = ""; + public string Name { get; init; } = ""; + /// 仓库主页(用于展示与打开)。 + public string HomeUrl { get; init; } = ""; + /// API 根地址(Gitea: /api/v1,GitCode: /api/v5)。 + public string ApiBase { get; init; } = ""; + /// 原始文件下载前缀(用于拼 raw 地址)。 + public string RawBase { get; init; } = ""; + /// 后端类型:gitea / gitcode。 + public string Kind { get; init; } = ""; + public string Owner { get; init; } = ""; + public string Repo { get; init; } = ""; + public string Branch { get; init; } = "main"; + /// raw 地址风格:gitea 用 raw/branch/{b},gitcode 用 raw/{b}。 + public string RawStyle { get; init; } = "branch"; + + public string Repository => HomeUrl; + + /// 拼 raw 文件下载地址(两个平台的 URL 结构不同)。 + public string RawUrl(string path) => RawStyle == "plain" + ? $"{RawBase}/{Owner}/{Repo}/raw/{Branch}/{path.TrimStart('/')}" + : $"{RawBase}/{Owner}/{Repo}/raw/branch/{Branch}/{path.TrimStart('/')}"; + + public static readonly SourcePreset Xhmcl = new() + { + Id = "xhmcl", + Name = "Xhmcl", + HomeUrl = "https://git.xhmcl.com/Morris/GC", + ApiBase = "https://git.xhmcl.com/api/v1", + RawBase = "https://git.xhmcl.com", + Kind = "gitea", + RawStyle = "branch", + Owner = "Morris", + Repo = "GC", + Branch = "main" + }; + + public static readonly SourcePreset GitCode = new() + { + Id = "gitcode", + Name = "GitCode", + HomeUrl = "https://gitcode.com/2509_92447106/GC", + ApiBase = "https://api.gitcode.com/api/v5", + RawBase = "https://gitcode.com", + Kind = "gitcode", + RawStyle = "plain", + Owner = "2509_92447106", + Repo = "GC", + Branch = "main" + }; + + public static readonly SourcePreset[] All = { Xhmcl, GitCode }; + + public static SourcePreset? Find(string? id) => + All.FirstOrDefault(p => string.Equals(p.Id, id, StringComparison.OrdinalIgnoreCase)); + + /// 把任意仓库地址映射到这两个内置源之一(用于兼容旧配置)。 + public static SourcePreset Detect(string? url) + { + if (string.IsNullOrWhiteSpace(url)) return GitCode; + var u = url!.ToLowerInvariant(); + if (u.Contains("xhmcl.com")) return Xhmcl; + return GitCode; + } +} diff --git a/src/main/dotnet/EarthModelStudio/Services/SourceSelector.cs b/src/main/dotnet/EarthModelStudio/Services/SourceSelector.cs new file mode 100644 index 0000000..08a430e --- /dev/null +++ b/src/main/dotnet/EarthModelStudio/Services/SourceSelector.cs @@ -0,0 +1,130 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Linq; +using System.Net.Http; +using System.Threading; +using System.Threading.Tasks; + +namespace EarthModelStudio.Services; + +/// +/// 双源选择:Xhmcl 与 GitCode 是同一份仓库的两个镜像。 +/// +/// 启动更新 / 下载页面 / 检查更新时,先并发探测两边的 version.json 响应时间, +/// 取**最快且内容可用**的那个作为本次下载源;探测结果缓存一段时间, +/// 避免每次点下载都重新测速。 +/// +public sealed class SourceSelector +{ + private static readonly HttpClient Http = CreateHttp(); + + private static HttpClient CreateHttp() + { + var c = new HttpClient { Timeout = TimeSpan.FromSeconds(6) }; + c.DefaultRequestHeaders.UserAgent.ParseAdd("EarthModelStudio-Probe/1.0"); + return c; + } + + private readonly object _lock = new(); + private SourcePreset? _cached; + private DateTime _cachedAt = DateTime.MinValue; + private readonly TimeSpan _ttl = TimeSpan.FromMinutes(3); + + /// 最近一次选中的源(未探测时为空)。 + public SourcePreset? Current { get { lock (_lock) return _cached; } } + + /// 每个源的探测耗时(毫秒),供界面展示。 + public IReadOnlyDictionary LastLatency { get; private set; } = + new Dictionary(); + + /// + /// 探测两个源并返回最快的。force=true 时忽略缓存。 + /// 两个都失败时返回 GitCode(默认源)。 + /// + public async Task PickFastestAsync(bool force = false, CancellationToken ct = default) + { + lock (_lock) + { + if (!force && _cached != null && DateTime.UtcNow - _cachedAt < _ttl) + return _cached; + } + + var probes = SourcePreset.All.Select(async p => + { + var sw = Stopwatch.StartNew(); + var ok = await ProbeAsync(p, ct); + sw.Stop(); + return (Preset: p, Ok: ok, Ms: sw.ElapsedMilliseconds); + }); + + var results = await Task.WhenAll(probes); + + var latencies = results.ToDictionary(r => r.Preset.Id, r => r.Ms); + LastLatency = latencies; + + var usable = results.Where(r => r.Ok).OrderBy(r => r.Ms).ToList(); + var chosen = usable.Count > 0 ? usable[0].Preset : SourcePreset.GitCode; + + lock (_lock) + { + _cached = chosen; + _cachedAt = DateTime.UtcNow; + } + + Console.WriteLine("[selector] 测速:" + string.Join(" ", + results.Select(r => $"{r.Preset.Name}={r.Ms}ms{(r.Ok ? "" : "(不可用)")}")) + + $" → 选择 {chosen.Name}"); + + return chosen; + } + + /// + /// 探测:能拿到合法 JSON 才算可用。 + /// 注意两个平台取文件的方式不同: + /// · Gitea(Xhmcl):raw/branch/{b}/{path} 直接返回文件内容 + /// · GitCode:raw 地址返回的是 HTML 页面,必须走 API(内容为 base64) + /// 因此 GitCode 用 api/v5 contents + Accept: application/json 探测。 + /// + private static async Task ProbeAsync(SourcePreset preset, CancellationToken ct) + { + if (preset.Kind == "gitcode") + { + try + { + using var cts = CancellationTokenSource.CreateLinkedTokenSource(ct); + cts.CancelAfter(TimeSpan.FromSeconds(5)); + var api = $"{preset.ApiBase}/repos/{preset.Owner}/{preset.Repo}/contents/version.json?ref={preset.Branch}"; + using var req = new HttpRequestMessage(HttpMethod.Get, api); + req.Headers.Accept.ParseAdd("application/json"); + using var resp = await Http.SendAsync(req, cts.Token); + if (!resp.IsSuccessStatusCode) return false; + var text = await resp.Content.ReadAsStringAsync(cts.Token); + return text.TrimStart().StartsWith('{'); + } + catch { return false; } + } + + var urls = new[] { preset.RawUrl("version.json"), preset.RawUrl("model/version.json") }; + + foreach (var url in urls) + { + try + { + using var cts = CancellationTokenSource.CreateLinkedTokenSource(ct); + cts.CancelAfter(TimeSpan.FromSeconds(5)); + var text = await Http.GetStringAsync(url, cts.Token); + if (text.TrimStart().StartsWith('{')) return true; + } + catch { /* 换下一个地址 */ } + } + return false; + } + + /// 为指定源创建对应的 remote 实现。 + public static IModelRemote CreateRemote(SourcePreset preset) => preset.Kind switch + { + "gitea" => new GiteaRemote(preset), + _ => new GitCodeReleaseRemote(null, preset.HomeUrl) + }; +} diff --git a/src/main/dotnet/EarthModelStudio/Services/UpdateModels.cs b/src/main/dotnet/EarthModelStudio/Services/UpdateModels.cs index 56d3b1e..be88e6d 100644 --- a/src/main/dotnet/EarthModelStudio/Services/UpdateModels.cs +++ b/src/main/dotnet/EarthModelStudio/Services/UpdateModels.cs @@ -64,6 +64,9 @@ public sealed class RepoEntry public interface IModelRemote { string DisplayName { get; } + + /// 源标识(xhmcl / gitcode / local),用于判断当前是哪个源。 + string SourceId => SourcePreset.Detect(DisplayName).Id; Task GetVersionAsync(CancellationToken ct); Task> ListTreeAsync(string rootPath, CancellationToken ct); Task DownloadAsync(RepoEntry entry, CancellationToken ct); diff --git a/src/main/dotnet/EarthModelStudio/Services/UpdateService.cs b/src/main/dotnet/EarthModelStudio/Services/UpdateService.cs index 5e46b52..cdd425d 100644 --- a/src/main/dotnet/EarthModelStudio/Services/UpdateService.cs +++ b/src/main/dotnet/EarthModelStudio/Services/UpdateService.cs @@ -21,7 +21,7 @@ public sealed class UpdateService { private readonly AppPaths _paths; private readonly SettingsService _settings; - private readonly IModelRemote _remote; + private IModelRemote _remote; public UpdateService(AppPaths paths, SettingsService settings, IModelRemote remote) { @@ -32,16 +32,41 @@ public sealed class UpdateService public IModelRemote Remote => _remote; + /// 换源:测速选出最快的一个后,用它的 remote 覆盖当前实例。 + public void UseRemote(IModelRemote remote) => _remote = remote; + + private static string? _versionOverride; + public static string CurrentLauncherVersion { get { - var v = Assembly.GetEntryAssembly()?.GetName().Version; + if (!string.IsNullOrWhiteSpace(_versionOverride)) return _versionOverride!; + + // 用**本程序集**的版本,而不是 GetEntryAssembly()。 + // EntryAssembly 在宿主(dotnet run / 测试宿主 / 单文件解包)下可能指向别的程序, + // 读出来会变成 1.0.0,导致「明明是最新版却一直提示有更新」。 + var asm = typeof(UpdateService).Assembly; + var v = asm.GetName().Version; + if (v == null || (v.Major == 0 && v.Minor == 0 && v.Build == 0)) + { + // 兜底:读 InformationalVersion(Directory.Build.props 里的 ) + var info = asm.GetCustomAttribute()?.InformationalVersion; + if (!string.IsNullOrWhiteSpace(info)) + { + var core = info!.Split('+')[0].Trim(); + if (Version.TryParse(core, out var iv)) + v = iv; + } + } if (v == null) return "0.0.0"; return $"{Math.Max(0, v.Major)}.{Math.Max(0, v.Minor)}.{Math.Max(0, v.Build)}"; } } + /// 测试 / 自检时临时指定版本号。 + public static void OverrideLauncherVersion(string? version) => _versionOverride = version; + public static string CurrentRid { get @@ -59,14 +84,31 @@ public sealed class UpdateService } } + /// + /// 同步版本(无法测速时用):按设置里的仓库地址映射到内置源。 + /// 真正带测速的入口是 。 + /// public static IModelRemote CreateRemote(AppSettings settings) { if (!string.IsNullOrWhiteSpace(settings.UpdateLocalRoot) && Directory.Exists(settings.UpdateLocalRoot!)) - return new DirectoryRemote(settings.UpdateLocalRoot!); // 离线 U 盘源:仍读本地 version.json - // 在线源:启动器版本与发布包走 GitCode Release(tag + 附件), - // 模型清单/文件仍走仓库 contents API;无 Release 时自动回退仓库 version.json。 - return new GitCodeReleaseRemote(settings.UpdateManifestUrl, settings.UpdateRepository); + return new DirectoryRemote(settings.UpdateLocalRoot!); + return SourceSelector.CreateRemote(SourcePreset.Detect(settings.UpdateRepository)); + } + + /// + /// 异步版本:先探测 Xhmcl / GitCode 两个源,取最快的那个。 + /// 启动更新、下载页、检查更新统一走这里,保证「用同一个源、同一种下载方式」。 + /// + public static async Task CreateRemoteAsync(AppSettings settings, + SourceSelector selector, bool forceProbe = false, CancellationToken ct = default) + { + if (!string.IsNullOrWhiteSpace(settings.UpdateLocalRoot) && + Directory.Exists(settings.UpdateLocalRoot!)) + return new DirectoryRemote(settings.UpdateLocalRoot!); + + var preset = await selector.PickFastestAsync(forceProbe, ct); + return SourceSelector.CreateRemote(preset); } public async Task RunAsync(bool force, diff --git a/src/main/dotnet/EarthModelStudio/Services/VersionUtil.cs b/src/main/dotnet/EarthModelStudio/Services/VersionUtil.cs new file mode 100644 index 0000000..9a5d8a1 --- /dev/null +++ b/src/main/dotnet/EarthModelStudio/Services/VersionUtil.cs @@ -0,0 +1,41 @@ +using System; +using System.Globalization; + +namespace EarthModelStudio.Services; + +/// +/// 版本号工具:Release tag 有 v1.0.6 / GC-1.0.6 / 1.0.6 等写法, +/// 统一成可比较的 Version 再排序,挑**版本号最高**的那个。 +/// +public static class VersionUtil +{ + /// 把 tag 规整成 "1.0.6" 这样的纯数字版本。 + public static string Normalize(string? tag) + { + if (string.IsNullOrWhiteSpace(tag)) return ""; + var s = tag!.Trim(); + + // 去掉前缀:v / V / GC- / release- + if (s.StartsWith("GC-", StringComparison.OrdinalIgnoreCase)) s = s[3..]; + else if (s.StartsWith("release-", StringComparison.OrdinalIgnoreCase)) s = s[8..]; + s = s.TrimStart('v', 'V'); + + // 只保留开头的 数字与点 + var end = 0; + while (end < s.Length && (char.IsDigit(s[end]) || s[end] == '.')) end++; + s = s[..end].Trim('.'); + + return s; + } + + /// 解析成 Version;无法解析时返回 0.0。 + public static Version Parse(string? tag) + { + var n = Normalize(tag); + if (string.IsNullOrWhiteSpace(n)) return new Version(0, 0); + return Version.TryParse(n, out var v) ? v : new Version(0, 0); + } + + /// 比较两个版本号,a>b 返回正、a<b 返回负、相等返回 0。 + public static int Compare(string? a, string? b) => Parse(a).CompareTo(Parse(b)); +} diff --git a/src/main/dotnet/EarthModelStudio/ViewModels/DownloadViewModel.cs b/src/main/dotnet/EarthModelStudio/ViewModels/DownloadViewModel.cs index d68264e..bef5f9f 100644 --- a/src/main/dotnet/EarthModelStudio/ViewModels/DownloadViewModel.cs +++ b/src/main/dotnet/EarthModelStudio/ViewModels/DownloadViewModel.cs @@ -109,30 +109,30 @@ public partial class DownloadViewModel : ObservableObject } } + /// + /// 只允许两个内置源(Xhmcl / GitCode),不再接受任意地址。 + /// 旧的「自定义源」入口统一改为:按测速结果切换到更快的那个源。 + /// [RelayCommand] private async Task ImportAsync() { - var url = ImportUrl.Trim(); - if (string.IsNullOrWhiteSpace(url)) + var fastest = await _services.Selector.PickFastestAsync(force: true); + var target = Sources.FirstOrDefault(x => + SourcePreset.Find(fastest.Id) != null && + SourcePreset.Detect(x.Model.Url).Id == fastest.Id); + + if (target == null) { - StatusMessage = L.I["dl.error.emptyUrl"]; + StatusMessage = "没有可用的下载源"; 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); + SelectedSource = target; + var lat = _services.Selector.LastLatency; + StatusMessage = $"已切换到 {fastest.Name}" + + (lat.Count > 0 ? "(" + string.Join(",", lat.Select(kv => + $"{SourcePreset.Find(kv.Key)?.Name ?? kv.Key} {kv.Value}ms")) + ")" : ""); + await LoadAsync(target, force: true); } private static string DeriveName(string url) @@ -173,6 +173,24 @@ public partial class DownloadViewModel : ObservableObject StatusMessage = L.I["dl.syncing"]; try { + // 第 6 项:下载页与启动更新用同一个源、同一种下载方式。 + // 每次加载前先让选择器给出最快源(有缓存,不会真的每次都测)。 + try + { + var fastest = await _services.Selector.PickFastestAsync(false, ct); + if (fastest.Id != SourcePreset.Detect(source.Model.Url).Id) + { + var prefer = Sources.FirstOrDefault(x => + SourcePreset.Detect(x.Model.Url).Id == fastest.Id && x.Model.Enabled); + if (prefer != null && prefer != source) + { + SelectedSource = prefer; + source = prefer; + } + } + } + catch { /* 测速失败就沿用当前源 */ } + var index = await _services.Sources.FetchAsync(source.Model, force, null, ct); // 只有「仍是当前选中源 + 仍是最新一次加载」才可以写 UI 集合 if (ct.IsCancellationRequested || generation != _loadGeneration || SelectedSource != source) diff --git a/src/main/dotnet/EarthModelStudio/ViewModels/MainViewModel.cs b/src/main/dotnet/EarthModelStudio/ViewModels/MainViewModel.cs index c3673ab..885f8f1 100644 --- a/src/main/dotnet/EarthModelStudio/ViewModels/MainViewModel.cs +++ b/src/main/dotnet/EarthModelStudio/ViewModels/MainViewModel.cs @@ -1,4 +1,5 @@ using System; +using System.Linq; using System.Threading.Tasks; using CommunityToolkit.Mvvm.ComponentModel; using CommunityToolkit.Mvvm.Input; @@ -135,6 +136,24 @@ public partial class MainViewModel : ObservableObject UpdateDetail = p.Detail ?? ""; }); + // 双源测速:Xhmcl / GitCode 取快的那个(第 5 项)。 + // 启动更新与下载页共用同一个选择器,保证两处用同一个源、同一种下载方式。 + UpdateStatus = "正在选择最快的下载源…"; + try + { + var fastest = await _services.Selector.PickFastestAsync( + force, default); + _services.Updates.UseRemote(SourceSelector.CreateRemote(fastest)); + var lat = _services.Selector.LastLatency; + UpdateDetail = "源:" + fastest.Name + + (lat.Count > 0 ? "(" + string.Join(",", lat.Select(kv => + $"{SourcePreset.Find(kv.Key)?.Name ?? kv.Key} {kv.Value}ms")) + ")" : ""); + } + catch (Exception ex) + { + Console.Error.WriteLine($"[update] 测速失败,沿用当前源: {ex.Message}"); + } + // 启动器:读 Release latest 版本号,与当前运行版本不同就弹窗询问 var latest = await LauncherUpdater.CheckAsync(_services.Updates.Remote); if (latest != null) diff --git a/src/main/dotnet/EarthModelStudio/Views/DownloadView.axaml b/src/main/dotnet/EarthModelStudio/Views/DownloadView.axaml index 4c08d47..e81b3c8 100644 --- a/src/main/dotnet/EarthModelStudio/Views/DownloadView.axaml +++ b/src/main/dotnet/EarthModelStudio/Views/DownloadView.axaml @@ -11,9 +11,9 @@ + - -