diff --git a/Directory.Build.props b/Directory.Build.props index 77b9071..8a4e0d9 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -12,6 +12,13 @@ latest enable disable + 11.3.9 8.2.2 1.0.0 diff --git a/Directory.Build.targets b/Directory.Build.targets new file mode 100644 index 0000000..d376c3a --- /dev/null +++ b/Directory.Build.targets @@ -0,0 +1,10 @@ + + + + diff --git a/build.ps1 b/build.ps1 index 9f1c9c0..0275287 100644 --- a/build.ps1 +++ b/build.ps1 @@ -33,6 +33,10 @@ $ErrorActionPreference = 'Stop' $Root = $PSScriptRoot Set-Location $Root +# Avalonia 遥测任务在只读用户目录/CI/沙箱会因写日志失败而中断编译(MSB4018)。 +# 官方 opt-out;Directory.Build.targets 里还有一层项目内的兜底。 +$env:AVALONIA_TELEMETRY_OPTOUT = '1' + $AppProj = 'src/main/dotnet/EarthModelStudio/EarthModelStudio.csproj' $TestProj = 'src/test/dotnet/EarthModelStudio.Tests/EarthModelStudio.Tests.csproj' $PreviewProj = 'model/_engine/PreviewGen/PreviewGen.csproj' diff --git a/build.sh b/build.sh index efc27e3..a91d883 100755 --- a/build.sh +++ b/build.sh @@ -24,7 +24,11 @@ # cache/ 下载暂存 # update/ 待下次启动应用的启动器更新 # --------------------------------------------------------------------------- -set -e +set -eu + +# Avalonia 遥测任务在只读用户目录/CI/沙箱会因写日志失败而中断编译(MSB4018)。 +# 官方 opt-out;Directory.Build.targets 里还有一层项目内的兜底。 +export AVALONIA_TELEMETRY_OPTOUT=1 ROOT_DIR=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd) cd "$ROOT_DIR" diff --git a/model/_engine/src/CelestialView.cs b/model/_engine/src/CelestialView.cs index f9f7cf5..4ec8104 100644 --- a/model/_engine/src/CelestialView.cs +++ b/model/_engine/src/CelestialView.cs @@ -25,7 +25,7 @@ public enum SceneView /// 纯 CPU 像素着色 + 矢量标注,无外部贴图依赖,三平台表现一致。 /// 交互约定:单指/鼠标拖动只改变地球自身的角度,视角平面保持不变;双指捏合缩放。 /// -public class CelestialView : Control +public class CelestialView : Control, IDisposable { // ---------------------------------------------------------------- 属性 public static readonly StyledProperty SceneProperty = @@ -391,6 +391,20 @@ public class CelestialView : Control _timer = null; } + /// + /// 窗口关闭时释放计时器与 WriteableBitmap:DispatcherTimer 的 Tick 事件会持有本控件实例, + /// 不置空会让 collectible 的 ModelLoadContext 无法回收(模型卸载不干净)。 + /// + public void Dispose() + { + _timer?.Stop(); + _timer = null; + _sphere?.Dispose(); + _sphere = null; + _sphereSize = 0; + GC.SuppressFinalize(this); + } + private void OnTick(object? sender, EventArgs e) { var now = Stopwatch.GetTimestamp(); @@ -531,20 +545,66 @@ public class CelestialView : Control else RenderRotation(ctx, size, runtime); } + // 每帧 Render 都会调用:渐变画刷改成静态只读,避免在热路径反复分配。 + // 全部使用相对坐标,可安全共享;Radius -> RadiusX/RadiusY(旧 API 已过时)。 + private static readonly IBrush SpaceBg = new LinearGradientBrush + { + StartPoint = new RelativePoint(0.15, 0, RelativeUnit.Relative), + EndPoint = new RelativePoint(0.85, 1, RelativeUnit.Relative), + GradientStops = + { + new GradientStop(Color.Parse("#080D1C"), 0), + new GradientStop(Color.Parse("#0B1226"), 0.55), + new GradientStop(Color.Parse("#04060E"), 1) + } + }; + + private static readonly IBrush SpaceBand = new RadialGradientBrush + { + Center = new RelativePoint(0.72, 0.18, RelativeUnit.Relative), + GradientOrigin = new RelativePoint(0.72, 0.18, RelativeUnit.Relative), + RadiusX = new RelativeScalar(1.1, RelativeUnit.Relative), + RadiusY = new RelativeScalar(1.1, RelativeUnit.Relative), + GradientStops = + { + new GradientStop(Color.FromArgb(26, 120, 150, 255), 0), + new GradientStop(Color.FromArgb(0, 120, 150, 255), 1) + } + }; + + private static readonly IBrush AtmosphereGlow = new RadialGradientBrush + { + Center = new RelativePoint(0.5, 0.5, RelativeUnit.Relative), + GradientOrigin = new RelativePoint(0.5, 0.5, RelativeUnit.Relative), + RadiusX = new RelativeScalar(0.5, RelativeUnit.Relative), + RadiusY = new RelativeScalar(0.5, RelativeUnit.Relative), + GradientStops = + { + new GradientStop(Color.FromArgb(90, 70, 140, 235), 0.60), + new GradientStop(Color.FromArgb(34, 80, 150, 240), 0.80), + new GradientStop(Color.FromArgb(0, 80, 150, 240), 1.0) + } + }; + + private static readonly IBrush SunGlow = new RadialGradientBrush + { + Center = new RelativePoint(0.5, 0.5, RelativeUnit.Relative), + GradientOrigin = new RelativePoint(0.5, 0.5, RelativeUnit.Relative), + RadiusX = new RelativeScalar(0.5, RelativeUnit.Relative), + RadiusY = new RelativeScalar(0.5, RelativeUnit.Relative), + GradientStops = + { + new GradientStop(Color.FromArgb(120, 255, 196, 92), 0.10), + new GradientStop(Color.FromArgb(48, 255, 168, 60), 0.34), + new GradientStop(Color.FromArgb(0, 255, 150, 40), 1.0) + } + }; + + private static readonly IBrush EarthHalo = new SolidColorBrush(Color.FromArgb(56, 70, 140, 235)); + private void DrawSpace(DrawingContext ctx, Size size) { - var bg = new LinearGradientBrush - { - StartPoint = new RelativePoint(0.15, 0, RelativeUnit.Relative), - EndPoint = new RelativePoint(0.85, 1, RelativeUnit.Relative), - GradientStops = - { - new GradientStop(Color.Parse("#080D1C"), 0), - new GradientStop(Color.Parse("#0B1226"), 0.55), - new GradientStop(Color.Parse("#04060E"), 1) - } - }; - ctx.FillRectangle(bg, new Rect(size)); + ctx.FillRectangle(SpaceBg, new Rect(size)); foreach (var star in Stars) { @@ -557,18 +617,7 @@ public class CelestialView : Control ctx.DrawEllipse(brush, null, new Point(star.X * size.Width, star.Y * size.Height), star.R, star.R); } - var band = new RadialGradientBrush - { - Center = new RelativePoint(0.72, 0.18, RelativeUnit.Relative), - GradientOrigin = new RelativePoint(0.72, 0.18, RelativeUnit.Relative), - Radius = 1.1, - GradientStops = - { - new GradientStop(Color.FromArgb(26, 120, 150, 255), 0), - new GradientStop(Color.FromArgb(0, 120, 150, 255), 1) - } - }; - ctx.FillRectangle(band, new Rect(size)); + ctx.FillRectangle(SpaceBand, new Rect(size)); } private void DrawLoading(DrawingContext ctx, Size size) @@ -594,19 +643,7 @@ public class CelestialView : Control // 太阳光由「直射纬度」反推:直射点严格落在对应纬线上,且始终朝向右前方可见半球 var light = RotationLight(cam, tilt); - var glow = new RadialGradientBrush - { - Center = new RelativePoint(0.5, 0.5, RelativeUnit.Relative), - GradientOrigin = new RelativePoint(0.5, 0.5, RelativeUnit.Relative), - Radius = 0.5, - GradientStops = - { - new GradientStop(Color.FromArgb(90, 70, 140, 235), 0.60), - new GradientStop(Color.FromArgb(34, 80, 150, 240), 0.80), - new GradientStop(Color.FromArgb(0, 80, 150, 240), 1.0) - } - }; - ctx.DrawEllipse(glow, null, center, radius * 1.16, radius * 1.16); + ctx.DrawEllipse(AtmosphereGlow, null, center, radius * 1.16, radius * 1.16); var px = PixelSizeFor(radius); if (px > 8 && runtime.Texture != null) @@ -841,25 +878,15 @@ public class CelestialView : Control var lightWorld = Vector3.Normalize(-earthPos); var lightCam = Vector3.TransformNormal(lightWorld, cam); - var sunGlow = new RadialGradientBrush - { - Center = new RelativePoint(0.5, 0.5, RelativeUnit.Relative), - GradientOrigin = new RelativePoint(0.5, 0.5, RelativeUnit.Relative), - Radius = 0.5, - GradientStops = - { - new GradientStop(Color.FromArgb(120, 255, 196, 92), 0.10), - new GradientStop(Color.FromArgb(48, 255, 168, 60), 0.34), - new GradientStop(Color.FromArgb(0, 255, 150, 40), 1.0) - } - }; - ctx.DrawEllipse(sunGlow, null, center, sunR * 6.2, sunR * 6.2); + ctx.DrawEllipse(SunGlow, null, center, sunR * 6.2, sunR * 6.2); + // sunBody 依赖场景里的 runtime.Star,不能静态化;仅把过时 API 换成 RadiusX/Y var sunBody = new RadialGradientBrush { Center = new RelativePoint(0.42, 0.38, RelativeUnit.Relative), GradientOrigin = new RelativePoint(0.42, 0.38, RelativeUnit.Relative), - Radius = 0.62, + RadiusX = new RelativeScalar(0.62, RelativeUnit.Relative), + RadiusY = new RelativeScalar(0.62, RelativeUnit.Relative), GradientStops = { new GradientStop(Color.Parse("#FFF3D0"), 0), @@ -877,7 +904,7 @@ public class CelestialView : Control var px = PixelSizeFor(earthR); if (px > 8) { - ctx.DrawEllipse(new SolidColorBrush(Color.FromArgb(56, 70, 140, 235)), null, + ctx.DrawEllipse(EarthHalo, null, earthScreen, earthR * 1.35, earthR * 1.35); var bmp = EnsureSphereBitmap(px); if (runtime.Texture != null) @@ -1002,6 +1029,8 @@ public class CelestialView : Control private WriteableBitmap EnsureSphereBitmap(int px) { if (_sphere != null && _sphereSize == px) return _sphere; + // 自适应分辨率会频繁改 px,旧位图必须先释放,否则每帧都可能泄漏一张 ~0.8MB 位图 + _sphere?.Dispose(); _sphere = new WriteableBitmap(new PixelSize(px, px), new Avalonia.Vector(96, 96), PixelFormat.Bgra8888, AlphaFormat.Premul); _sphereSize = px; diff --git a/model/_engine/src/EarthModelView.cs b/model/_engine/src/EarthModelView.cs index 5f42697..7111372 100644 --- a/model/_engine/src/EarthModelView.cs +++ b/model/_engine/src/EarthModelView.cs @@ -17,7 +17,7 @@ namespace NeoRF.EarthModels; /// 模型自己的界面:画布 + 触控友好工具栏 + 课堂演示卡 + 节气定格与步进。 /// 启动器只负责下载、开窗口和进度条,不参与任何模型渲染或教学交互。 /// -public sealed class EarthModelView : UserControl +public sealed class EarthModelView : UserControl, IDisposable { private static readonly IBrush PanelBg = new SolidColorBrush(Color.Parse("#C40A1020")); private static readonly IBrush ControlBg = new SolidColorBrush(Color.Parse("#16233C")); @@ -155,15 +155,42 @@ public sealed class EarthModelView : UserControl { Opacity = 1; _uiTimer.Start(); - if (TopLevel.GetTopLevel(this) is Window window) window.KeyDown += OnKeyDown; + if (TopLevel.GetTopLevel(this) is Window window) + { + _hostWindow = window; + window.KeyDown += OnKeyDown; + } }; DetachedFromVisualTree += (_, _) => { _uiTimer.Stop(); - if (TopLevel.GetTopLevel(this) is Window window) window.KeyDown -= OnKeyDown; + if (_hostWindow != null) + { + _hostWindow.KeyDown -= OnKeyDown; + _hostWindow = null; + } }; } + private Window? _hostWindow; + + /// + /// 窗口关闭时释放计时器、解绑窗口事件并释放两块球面位图, + /// 否则 DispatcherTimer / KeyDown 会持有控件,使 collectible ALC 无法卸载。 + /// + public void Dispose() + { + _uiTimer.Stop(); + if (_hostWindow != null) + { + _hostWindow.KeyDown -= OnKeyDown; + _hostWindow = null; + } + _canvas.Dispose(); + _closeup.Dispose(); + GC.SuppressFinalize(this); + } + private string CurrentView { get; set; } = "rotation"; private double StartAngle => IsRevolution ? 60 : 0; private bool IsRevolution => string.Equals(CurrentView, "revolution", StringComparison.OrdinalIgnoreCase); diff --git a/model/_engine/src/EngineEntry.cs b/model/_engine/src/EngineEntry.cs index a074ec2..dc45319 100644 --- a/model/_engine/src/EngineEntry.cs +++ b/model/_engine/src/EngineEntry.cs @@ -33,5 +33,13 @@ public sealed class EarthModelRuntime : IModelRuntime return view; } - public void Dispose() => GC.SuppressFinalize(this); + /// + /// 释放预烘焙纹理(约 3MB 托管数组)与场景引用。窗口关闭时由启动器调用, + /// 避免 collectible ALC 里的类型被长生命周期引用拖住而无法卸载。 + /// + public void Dispose() + { + _scene = null; + GC.SuppressFinalize(this); + } } diff --git a/model/earth-revolution/earth-revolution.json b/model/earth-revolution/earth-revolution.json index 92bc579..b990a34 100644 --- a/model/earth-revolution/earth-revolution.json +++ b/model/earth-revolution/earth-revolution.json @@ -23,6 +23,6 @@ "type": "NeoRF.EarthModels.RevolutionModelFactory", "preview": "preview.png", "apiVersion": 1, - "version": "1.0-b8139bb568", - "updatedAt": "2026-11-07T09:23:04Z" + "version": "1.0-0a73a257ec", + "updatedAt": "2026-11-07T10:46:02Z" } diff --git a/model/earth-revolution/earth-revolution.model/EarthRevolutionModel.dll b/model/earth-revolution/earth-revolution.model/EarthRevolutionModel.dll index af6c2b7..8f274b8 100644 Binary files a/model/earth-revolution/earth-revolution.model/EarthRevolutionModel.dll and b/model/earth-revolution/earth-revolution.model/EarthRevolutionModel.dll differ diff --git a/model/earth-rotation/earth-rotation.json b/model/earth-rotation/earth-rotation.json index 1408b78..fe8598a 100644 --- a/model/earth-rotation/earth-rotation.json +++ b/model/earth-rotation/earth-rotation.json @@ -23,6 +23,6 @@ "type": "NeoRF.EarthModels.RotationModelFactory", "preview": "preview.png", "apiVersion": 1, - "version": "1.0-52ac06496e", - "updatedAt": "2026-11-07T09:23:04Z" + "version": "1.0-6c97454f58", + "updatedAt": "2026-11-07T10:46:02Z" } diff --git a/model/earth-rotation/earth-rotation.model/EarthRotationModel.dll b/model/earth-rotation/earth-rotation.model/EarthRotationModel.dll index a359323..f43430b 100644 Binary files a/model/earth-rotation/earth-rotation.model/EarthRotationModel.dll and b/model/earth-rotation/earth-rotation.model/EarthRotationModel.dll differ diff --git a/model/version.json b/model/version.json index dc9c665..aea4750 100644 --- a/model/version.json +++ b/model/version.json @@ -1,30 +1,30 @@ { "schema": 1, - "generated": "2026-11-07T09:23:04Z", + "generated": "2026-11-07T10:46:02Z", "repository": "https://gitcode.com/2509_92447106/GC", "branch": "main", "modelDir": "model", "launcher": { "version": "1.0.0", - "revision": "eee4fbbfbc", + "revision": "0d59eff631", "packages": { "win-x64": { "path": "dist/GC-win-x64.zip", "url": "", - "sha256": "dbd4997d111c4a60c5d06eadaf0962f41750bafa5b26946e216200ddf7d6c1cf", - "size": 39378935 + "sha256": "7bfb1cfab07934642eff4c52078a8f5f034f1d2432a7613f04674403c70f2b6d", + "size": 78755039 }, "win-arm64": { "path": "dist/GC-win-arm64.zip", "url": "", - "sha256": "662589f9b315357702d855c46b12c1d088475bdf160c0c042793f2af404f8cb7", - "size": 37679907 + "sha256": "9fddf07fa18cbdb368e37204cfb96f5828207e5fe74ecb31fa66b61fa400fd1c", + "size": 75360988 }, "osx-arm64": { "path": "dist/GC-osx-arm64.zip", "url": "", - "sha256": "01dbf8b4787717aeb804a157ebaf0a75b8fffb1e9ab5e3fb0279fa9299ebee0a", - "size": 39853456 + "sha256": "3517548b598eda62c92d873528f39e305c52c6fb246fa5ba5f3613f8b8cb315a", + "size": 39847910 }, "osx-x64": { "path": "dist/GC-osx-x64.zip", @@ -39,12 +39,12 @@ "models": [ { "id": "earth-revolution", - "version": "1.0-b8139bb568", + "version": "1.0-0a73a257ec", "dir": "model/earth-revolution" }, { "id": "earth-rotation", - "version": "1.0-52ac06496e", + "version": "1.0-6c97454f58", "dir": "model/earth-rotation" } ] diff --git a/src/main/dotnet/EarthModelStudio/Services/DirectoryRemote.cs b/src/main/dotnet/EarthModelStudio/Services/DirectoryRemote.cs index 1a15a40..a634021 100644 --- a/src/main/dotnet/EarthModelStudio/Services/DirectoryRemote.cs +++ b/src/main/dotnet/EarthModelStudio/Services/DirectoryRemote.cs @@ -83,6 +83,7 @@ public sealed class DirectoryRemote : IModelRemote } var url = package.Url; if (string.IsNullOrWhiteSpace(url)) return null; + // 离线 U 盘源与 ./build.sh update-test 都会用本地 zip 路径,必须保持兼容。 if (url!.StartsWith("file://", StringComparison.OrdinalIgnoreCase)) return await File.ReadAllBytesAsync(new Uri(url).LocalPath, ct); if (Path.IsPathRooted(url) && File.Exists(url)) diff --git a/src/main/dotnet/EarthModelStudio/Services/Localization.cs b/src/main/dotnet/EarthModelStudio/Services/Localization.cs index bb391b9..d6755a0 100644 --- a/src/main/dotnet/EarthModelStudio/Services/Localization.cs +++ b/src/main/dotnet/EarthModelStudio/Services/Localization.cs @@ -64,6 +64,8 @@ public sealed class L : INotifyPropertyChanged Language = code; PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("Item[]")); PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Language))); + // 顺带清理已回收的弱引用,避免 _watchers 只增不减 + _watchers.RemoveAll(w => !w.TryGetTarget(out _)); foreach (var w in _watchers) if (w.TryGetTarget(out var ls)) ls.Refresh(); LanguageChanged?.Invoke(); diff --git a/src/main/dotnet/EarthModelStudio/Services/ModelHost.cs b/src/main/dotnet/EarthModelStudio/Services/ModelHost.cs index 2508940..5241211 100644 --- a/src/main/dotnet/EarthModelStudio/Services/ModelHost.cs +++ b/src/main/dotnet/EarthModelStudio/Services/ModelHost.cs @@ -162,6 +162,10 @@ public sealed class LoadedModel : IDisposable { if (_disposed) return; _disposed = true; + // 顺序:先释放视图(停计时器/Dispose 位图),再释放运行时,最后卸载程序集。 + // 否则视图里的事件订阅会继续持有 ALC 内的类型,collectible 上下文无法回收。 + try { (View as IDisposable)?.Dispose(); } + catch (Exception ex) { Console.Error.WriteLine($"释放模型视图失败: {ex.Message}"); } try { _runtime.Dispose(); } catch (Exception ex) { Console.Error.WriteLine($"释放模型失败: {ex.Message}"); } try { _context.Unload(); } catch (Exception ex) { Console.Error.WriteLine($"卸载模型程序集失败: {ex.Message}"); } } diff --git a/src/main/dotnet/EarthModelStudio/Services/ModelInstaller.cs b/src/main/dotnet/EarthModelStudio/Services/ModelInstaller.cs index 11d9c69..d7336df 100644 --- a/src/main/dotnet/EarthModelStudio/Services/ModelInstaller.cs +++ b/src/main/dotnet/EarthModelStudio/Services/ModelInstaller.cs @@ -31,7 +31,12 @@ public static class ModelInstaller { ct.ThrowIfCancellationRequested(); var relative = Path.GetRelativePath(model.Directory, file); - var dest = Path.Combine(staging, relative); + // 路径穿越防护:相对路径必须完整落在 staging 目录内 + var dest = Path.GetFullPath(Path.Combine(staging, relative)); + var stagingFull = Path.GetFullPath(staging) + .TrimEnd(Path.DirectorySeparatorChar) + Path.DirectorySeparatorChar; + if (!dest.StartsWith(stagingFull, StringComparison.OrdinalIgnoreCase)) + throw new InvalidOperationException($"非法的模型文件路径: {relative}"); var destDir = Path.GetDirectoryName(dest); if (!string.IsNullOrEmpty(destDir)) Directory.CreateDirectory(destDir); @@ -46,17 +51,29 @@ public static class ModelInstaller progress?.Report((done, total <= 0 ? done : total)); } - if (Directory.Exists(target)) + // 原子替换:先备份旧目录,第二次 Move 失败时完整回滚,绝不把模型库清空 + var backup = target + ".old"; + if (Directory.Exists(backup)) Directory.Delete(backup, true); + var hasBackup = false; + try { - var backup = target + ".old"; - if (Directory.Exists(backup)) Directory.Delete(backup, true); - Directory.Move(target, backup); + if (Directory.Exists(target)) + { + Directory.Move(target, backup); + hasBackup = true; + } Directory.Move(staging, target); - try { Directory.Delete(backup, true); } catch { } } - else + catch { - Directory.Move(staging, target); + // 新目录尚未就位时把旧目录还原;staging 由外层 catch 清理 + if (hasBackup && !Directory.Exists(target) && Directory.Exists(backup)) + Directory.Move(backup, target); + throw; + } + if (hasBackup) + { + try { Directory.Delete(backup, true); } catch { /* 占用时留到下次 */ } } progress?.Report((total, total)); diff --git a/src/main/dotnet/EarthModelStudio/Services/ModelSourceClient.cs b/src/main/dotnet/EarthModelStudio/Services/ModelSourceClient.cs index b0e2fc8..057f28a 100644 --- a/src/main/dotnet/EarthModelStudio/Services/ModelSourceClient.cs +++ b/src/main/dotnet/EarthModelStudio/Services/ModelSourceClient.cs @@ -173,7 +173,7 @@ public sealed class ModelSourceClient var extractDir = Path.Combine(tmpRoot, "extract"); Directory.CreateDirectory(extractDir); - ZipFile.ExtractToDirectory(zipPath, extractDir, true); + ZipSafety.ExtractToDirectory(zipPath, extractDir); var root = FindModelRoot(extractDir) ?? extractDir; foreach (var entry in Directory.GetFileSystemEntries(root)) diff --git a/src/main/dotnet/EarthModelStudio/Services/UpdateService.cs b/src/main/dotnet/EarthModelStudio/Services/UpdateService.cs index 82cd2c9..f961a15 100644 --- a/src/main/dotnet/EarthModelStudio/Services/UpdateService.cs +++ b/src/main/dotnet/EarthModelStudio/Services/UpdateService.cs @@ -195,6 +195,8 @@ public sealed class UpdateService private static bool IsPayload(string id, string relative) { var rel = relative.Replace('\\', '/'); + // 拒绝任何形式的父目录穿越与绝对路径 + if (rel.StartsWith('/') || rel.Contains("..", StringComparison.Ordinal)) return false; return rel.Equals(id + ".json", StringComparison.OrdinalIgnoreCase) || rel.StartsWith(id + ".model/", StringComparison.OrdinalIgnoreCase); } @@ -223,7 +225,14 @@ public sealed class UpdateService { ct.ThrowIfCancellationRequested(); var bytes = await _remote.DownloadAsync(entry, ct); - var dest = Path.Combine(staging, entry.RelativePath.Replace('/', Path.DirectorySeparatorChar)); + // 路径穿越防护:规范化后必须仍落在 staging 目录内, + // 防止远端清单里的 "../" 或绝对路径写进安装目录之外。 + var dest = Path.GetFullPath(Path.Combine(staging, + entry.RelativePath.Replace('/', Path.DirectorySeparatorChar))); + var stagingFull = Path.GetFullPath(staging) + .TrimEnd(Path.DirectorySeparatorChar) + Path.DirectorySeparatorChar; + if (!dest.StartsWith(stagingFull, StringComparison.OrdinalIgnoreCase)) + throw new InvalidOperationException($"非法的模型文件路径: {entry.RelativePath}"); var destDir = Path.GetDirectoryName(dest); if (!string.IsNullOrEmpty(destDir)) Directory.CreateDirectory(destDir); await File.WriteAllBytesAsync(dest, bytes, ct); @@ -307,7 +316,7 @@ public sealed class UpdateService await File.WriteAllBytesAsync(zip, bytes, ct); try { - ZipFile.ExtractToDirectory(zip, payload, true); + ZipSafety.ExtractToDirectory(zip, payload); } finally { diff --git a/src/main/dotnet/EarthModelStudio/Services/ZipSafety.cs b/src/main/dotnet/EarthModelStudio/Services/ZipSafety.cs new file mode 100644 index 0000000..7a638a8 --- /dev/null +++ b/src/main/dotnet/EarthModelStudio/Services/ZipSafety.cs @@ -0,0 +1,36 @@ +using System; +using System.IO; +using System.IO.Compression; + +namespace EarthModelStudio.Services; + +/// +/// 安全解压:拒绝 zip slip(条目名含 ../、绝对路径、盘符), +/// 并在解压前逐条校验目标路径完整落在目标目录内。 +/// +public static class ZipSafety +{ + public static void ExtractToDirectory(string zipPath, string destination) + { + var destFull = Path.GetFullPath(destination) + .TrimEnd(Path.DirectorySeparatorChar) + Path.DirectorySeparatorChar; + + using (var archive = ZipFile.OpenRead(zipPath)) + { + foreach (var entry in archive.Entries) + { + var name = entry.FullName.Replace('\\', '/'); + if (name.StartsWith('/') || name.Contains("..", StringComparison.Ordinal) || + (name.Length >= 2 && name[1] == ':')) + throw new InvalidOperationException($"压缩包含非法路径条目: {entry.FullName}"); + + var target = Path.GetFullPath(Path.Combine(destFull, name)); + if (!target.StartsWith(destFull, StringComparison.OrdinalIgnoreCase)) + throw new InvalidOperationException($"压缩包条目越界: {entry.FullName}"); + } + } + + // 校验通过后交给框架解压(保留 overwrite 语义) + ZipFile.ExtractToDirectory(zipPath, destination, true); + } +} diff --git a/src/main/dotnet/EarthModelStudio/ViewModels/DownloadViewModel.cs b/src/main/dotnet/EarthModelStudio/ViewModels/DownloadViewModel.cs index 7928908..0e0089f 100644 --- a/src/main/dotnet/EarthModelStudio/ViewModels/DownloadViewModel.cs +++ b/src/main/dotnet/EarthModelStudio/ViewModels/DownloadViewModel.cs @@ -19,6 +19,9 @@ public partial class DownloadViewModel : ObservableObject private readonly AppServices _services; private readonly MainViewModel _main; private bool _initialized; + // 每次切源取消上一次加载,并用 generation 序号丢弃过期结果,避免并发写 Models 集合 + private CancellationTokenSource? _loadCts; + private int _loadGeneration; public ObservableCollection Sources { get; } = new(); public ObservableCollection Models { get; } = new(); @@ -157,12 +160,22 @@ public partial class DownloadViewModel : ObservableObject private async Task LoadAsync(SourceItemViewModel source, bool force) { if (!source.Model.Enabled) return; + + // 取消上一次尚未完成的加载,避免快速切换源时并发 Clear/写入同一集合 + _loadCts?.Cancel(); + _loadCts?.Dispose(); + _loadCts = new CancellationTokenSource(); + var ct = _loadCts.Token; + var generation = ++_loadGeneration; + IsBusy = true; StatusMessage = L.I["dl.syncing"]; try { - var index = await _services.Sources.FetchAsync(source.Model, force, null, CancellationToken.None); - if (SelectedSource != source) return; + var index = await _services.Sources.FetchAsync(source.Model, force, null, ct); + // 只有「仍是当前选中源 + 仍是最新一次加载」才可以写 UI 集合 + if (ct.IsCancellationRequested || generation != _loadGeneration || SelectedSource != source) + return; if (index.Error != null) { @@ -189,13 +202,18 @@ public partial class DownloadViewModel : ObservableObject ? $"{L.I.F("dl.ready", Models.Count)} · {L.I["dl.fromCache"]}" : L.I.F("dl.ready", Models.Count); } + catch (OperationCanceledException) + { + // 被更新的加载取代或页面关闭:忽略,不覆盖新结果 + } catch (Exception ex) { - StatusMessage = ex.Message; + if (!ct.IsCancellationRequested) StatusMessage = ex.Message; } finally { - IsBusy = false; + // 只有最后一次加载才复位 Busy,避免旧任务把新任务的忙碌状态清掉 + if (generation == _loadGeneration) IsBusy = false; } } diff --git a/src/main/dotnet/EarthModelStudio/Views/MainWindow.axaml.cs b/src/main/dotnet/EarthModelStudio/Views/MainWindow.axaml.cs index e991bcf..43c7f29 100644 --- a/src/main/dotnet/EarthModelStudio/Views/MainWindow.axaml.cs +++ b/src/main/dotnet/EarthModelStudio/Views/MainWindow.axaml.cs @@ -20,6 +20,7 @@ public partial class MainWindow : Window private readonly List _players = new(); private MainViewModel? _viewModel; private ContentControl? _pageHost; + private bool _isClosing; public MainWindow() { @@ -74,9 +75,19 @@ public partial class MainWindow : Window }, DispatcherPriority.Render); } - private async void OpenPlayerWindow(ModelPackage package) + // 事件处理器必须是 void,因此包一层可观察异常的入口: + // fire-and-forget 的 Task 也要观察异常,绝不外泄到 Avalonia 事件循环导致进程崩溃。 + private void OpenPlayerWindow(ModelPackage package) => _ = OpenPlayerWindowSafeAsync(package); + + private async Task OpenPlayerWindowSafeAsync(ModelPackage package) { - if (_viewModel == null) return; + try { await OpenPlayerWindowAsync(package); } + catch (Exception ex) { Console.Error.WriteLine($"打开模型窗口失败: {ex}"); } + } + + private async Task OpenPlayerWindowAsync(ModelPackage package) + { + if (_viewModel == null || _isClosing) return; // 启动进度窗:模型加载、地表纹理生成、界面构建的真实进度 var loading = new LoadingWindow(package.LocalizedName); @@ -88,9 +99,18 @@ public partial class MainWindow : Window PlayerWindow? window = null; LoadedModel? loaded = null; Exception? error = null; + + // 关键修复:requestClose 过去捕获的是「尚未赋值的 window」,加载期恒为 null, + // 模型在 Prepare/CreateView 里调用 context.RequestClose() 会静默失效。 + // 改为关闭当前存在的窗口(加载期=进度窗,加载完成=模型窗),统一走 UI 线程。 + void RequestClose() => Dispatcher.UIThread.Post(() => + { + (window ?? (Window?)loading)?.Close(); + }); + try { - loaded = await _viewModel.Models.LoadAsync(package, () => window?.Close(), + loaded = await _viewModel.Models.LoadAsync(package, RequestClose, (value, message) => loading.Report(value, message)); } catch (Exception ex) @@ -100,6 +120,13 @@ public partial class MainWindow : Window loading.Close(); + // 加载期间用户关掉了主窗口:不要再弹出幽灵模型窗口,直接释放已加载模型 + if (_isClosing) + { + loaded?.Dispose(); + return; + } + if (loaded == null || error != null) { var message = error?.Message ?? L.I["player.errorHint"]; @@ -119,11 +146,14 @@ public partial class MainWindow : Window private void OnClosed(object? sender, EventArgs e) { + _isClosing = true; if (_viewModel != null) { _viewModel.PlayerRequested -= OpenPlayerWindow; _viewModel.PropertyChanged -= OnViewModelPropertyChanged; } + // 先取快照再关闭:PlayerWindow.Closed 回调会 _players.Remove, + // 直接遍历原集合会在 foreach 期间修改底层导致异常。 foreach (var window in _players.ToList()) window.Close(); _players.Clear(); } diff --git a/version.json b/version.json index dc9c665..aea4750 100644 --- a/version.json +++ b/version.json @@ -1,30 +1,30 @@ { "schema": 1, - "generated": "2026-11-07T09:23:04Z", + "generated": "2026-11-07T10:46:02Z", "repository": "https://gitcode.com/2509_92447106/GC", "branch": "main", "modelDir": "model", "launcher": { "version": "1.0.0", - "revision": "eee4fbbfbc", + "revision": "0d59eff631", "packages": { "win-x64": { "path": "dist/GC-win-x64.zip", "url": "", - "sha256": "dbd4997d111c4a60c5d06eadaf0962f41750bafa5b26946e216200ddf7d6c1cf", - "size": 39378935 + "sha256": "7bfb1cfab07934642eff4c52078a8f5f034f1d2432a7613f04674403c70f2b6d", + "size": 78755039 }, "win-arm64": { "path": "dist/GC-win-arm64.zip", "url": "", - "sha256": "662589f9b315357702d855c46b12c1d088475bdf160c0c042793f2af404f8cb7", - "size": 37679907 + "sha256": "9fddf07fa18cbdb368e37204cfb96f5828207e5fe74ecb31fa66b61fa400fd1c", + "size": 75360988 }, "osx-arm64": { "path": "dist/GC-osx-arm64.zip", "url": "", - "sha256": "01dbf8b4787717aeb804a157ebaf0a75b8fffb1e9ab5e3fb0279fa9299ebee0a", - "size": 39853456 + "sha256": "3517548b598eda62c92d873528f39e305c52c6fb246fa5ba5f3613f8b8cb315a", + "size": 39847910 }, "osx-x64": { "path": "dist/GC-osx-x64.zip", @@ -39,12 +39,12 @@ "models": [ { "id": "earth-revolution", - "version": "1.0-b8139bb568", + "version": "1.0-0a73a257ec", "dir": "model/earth-revolution" }, { "id": "earth-rotation", - "version": "1.0-52ac06496e", + "version": "1.0-6c97454f58", "dir": "model/earth-rotation" } ]