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

No files matched your search

@@ -0,0 +1,93 @@
using System;
using System.IO;
namespace EarthModelStudio.Services;
/// <summary>
/// 目录探测。启动器本身不含任何模型数据,模型一律从外部模型库目录读取:
/// 1) 开发态:从 bin 目录向上找到 EarthModelStudio.sln,模型库用仓库根 model/
/// 2) 绿色态:可执行文件旁边有 model/ 目录(发布包默认只建空目录)
/// 3) 安装态:模型库放到用户数据目录
/// 也可用环境变量 EMS_HOME / EMS_MODELS 显式指定。
/// </summary>
public sealed class AppPaths
{
public string AppRoot { get; private init; } = "";
public string ModelRoot { get; private init; } = "";
public string DataRoot { get; private init; } = "";
public bool IsPortableModelRoot { get; private init; }
public string CacheRoot => Path.Combine(DataRoot, "cache");
public string SettingsFile => Path.Combine(DataRoot, "settings.json");
public static AppPaths Discover()
{
var baseDir = AppContext.BaseDirectory.TrimEnd(Path.DirectorySeparatorChar);
var dataRoot = Environment.GetEnvironmentVariable("EMS_DATA")
?? Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
"EarthModelStudio");
// 显式指定模型库(模型是外置数据,可放在任意磁盘/网络盘)
var envModels = Environment.GetEnvironmentVariable("EMS_MODELS");
if (!string.IsNullOrWhiteSpace(envModels))
{
return new AppPaths
{
AppRoot = baseDir,
ModelRoot = envModels!,
DataRoot = dataRoot,
IsPortableModelRoot = false
};
}
var repoRoot = Environment.GetEnvironmentVariable("EMS_HOME");
if (string.IsNullOrWhiteSpace(repoRoot) || !Directory.Exists(repoRoot))
repoRoot = FindRepoRoot(baseDir);
var exeModelDir = Path.Combine(baseDir, "model");
string appRoot, modelRoot;
bool portable = false;
if (!string.IsNullOrEmpty(repoRoot) && Directory.Exists(Path.Combine(repoRoot!, "model")))
{
appRoot = repoRoot!;
modelRoot = Path.Combine(appRoot, "model");
}
else if (Directory.Exists(exeModelDir))
{
appRoot = baseDir;
modelRoot = exeModelDir;
portable = true;
}
else
{
appRoot = baseDir;
modelRoot = Path.Combine(dataRoot, "model");
}
return new AppPaths
{
AppRoot = appRoot,
ModelRoot = modelRoot,
DataRoot = dataRoot,
IsPortableModelRoot = portable
};
}
private static string? FindRepoRoot(string start)
{
var dir = new DirectoryInfo(start);
for (var i = 0; i < 10 && dir != null; i++, dir = dir.Parent)
{
if (File.Exists(Path.Combine(dir.FullName, "EarthModelStudio.sln"))) return dir.FullName;
}
return null;
}
public void EnsureCreated()
{
Directory.CreateDirectory(DataRoot);
Directory.CreateDirectory(CacheRoot);
Directory.CreateDirectory(ModelRoot);
}
}
@@ -0,0 +1,49 @@
using System;
namespace EarthModelStudio.Services;
/// <summary>组合根:一处初始化所有服务。</summary>
public sealed class AppServices
{
public static AppServices Current { get; private set; } = null!;
public AppPaths Paths { get; }
public SettingsService Settings { get; }
public ModelRepository Models { get; }
public DownloadCenter Downloads { get; }
public MemoryBudget Memory { get; }
public ModelSourceClient Sources { get; }
/// <summary>模型加载器:只负责把模型程序集跑起来,不渲染。</summary>
public ModelHost ModelHost { get; }
private AppServices(AppPaths paths)
{
Paths = paths;
Settings = new SettingsService(paths);
Models = new ModelRepository(paths);
Sources = new ModelSourceClient(paths);
Downloads = new DownloadCenter(paths, Models);
Memory = new MemoryBudget();
ModelHost = new ModelHost(paths, Settings, Memory);
}
public static AppServices Create()
{
var paths = AppPaths.Discover();
paths.EnsureCreated();
var services = new AppServices(paths);
services.Settings.Load();
L.I.Initialize(services.Settings.Current.Language);
services.Memory.Apply(services.Settings.Current.MemoryMb);
Current = services;
return services;
}
public static AppServices Ensure()
{
if (Current == null) Create();
return Current;
}
}
@@ -0,0 +1,167 @@
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using CommunityToolkit.Mvvm.ComponentModel;
using EarthModelStudio.Models;
namespace EarthModelStudio.Services;
public enum DownloadState
{
Queued,
Running,
Completed,
Failed,
Canceled
}
/// <summary>一条下载任务(进入后台列表后一直保留,直到用户清除)。</summary>
public sealed partial class DownloadJob : ObservableObject
{
public RemoteModel Model { get; }
public string Id => Model.Id;
public string Name => Model.LocalizedName;
public string Version => Model.Manifest.Version;
public CancellationTokenSource Cts { get; } = new();
[ObservableProperty] private DownloadState _state = DownloadState.Queued;
[ObservableProperty] private double _progress;
[ObservableProperty] private string _statusText = "";
[ObservableProperty] private string _detailText = "";
[ObservableProperty] private string? _error;
public DownloadJob(RemoteModel model)
{
Model = model;
RefreshText();
}
public bool IsActive => State is DownloadState.Queued or DownloadState.Running;
public bool CanRetry => State is DownloadState.Failed or DownloadState.Canceled;
public bool IsDone => State == DownloadState.Completed;
public void RefreshText()
{
StatusText = State switch
{
DownloadState.Queued => L.I["dl.status.queued"],
DownloadState.Running => L.I["dl.status.downloading"],
DownloadState.Completed => L.I["dl.status.done"],
DownloadState.Failed => L.I["dl.status.failed"],
_ => L.I["dl.status.canceled"]
};
DetailText = State == DownloadState.Failed && !string.IsNullOrEmpty(Error)
? Error!
: ModelScanner.HumanSize(Model.SizeBytes);
OnPropertyChanged(nameof(IsActive));
OnPropertyChanged(nameof(CanRetry));
OnPropertyChanged(nameof(IsDone));
}
partial void OnStateChanged(DownloadState value) => RefreshText();
partial void OnErrorChanged(string? value) => RefreshText();
}
/// <summary>下载中心:最多 2 个并发,任务在「后台列表」里折叠展示。</summary>
public sealed class DownloadCenter
{
private readonly ModelRepository _repository;
private readonly AppPaths _paths;
private readonly SemaphoreSlim _slots = new(2);
public ObservableCollection<DownloadJob> Jobs { get; } = new();
public event Action? Installed;
public DownloadCenter(AppPaths paths, ModelRepository repository)
{
_paths = paths;
_repository = repository;
}
public DownloadJob Enqueue(RemoteModel model)
{
var running = Jobs.FirstOrDefault(j => j.Id.Equals(model.Id, StringComparison.OrdinalIgnoreCase) && j.IsActive);
if (running != null) return running;
var job = new DownloadJob(model);
Jobs.Insert(0, job);
_ = RunAsync(job);
return job;
}
private async Task RunAsync(DownloadJob job)
{
// 在 UI 线程构造,回调自动回到 UI 线程
var progress = new Progress<(long Done, long Total)>(p =>
{
job.Progress = p.Total > 0 ? Math.Clamp((double)p.Done / p.Total, 0, 1) : 0;
});
try
{
await _slots.WaitAsync(job.Cts.Token).ConfigureAwait(true);
}
catch (OperationCanceledException)
{
job.State = DownloadState.Canceled;
return;
}
try
{
job.State = DownloadState.Running;
await ModelInstaller.InstallAsync(job.Model, _paths.ModelRoot, progress, job.Cts.Token)
.ConfigureAwait(true);
job.Progress = 1;
job.State = DownloadState.Completed;
_repository.NotifyChanged();
Installed?.Invoke();
}
catch (OperationCanceledException)
{
job.State = DownloadState.Canceled;
}
catch (Exception ex)
{
job.Error = ex.Message;
job.State = DownloadState.Failed;
}
finally
{
_slots.Release();
}
}
public void Cancel(DownloadJob job)
{
try { job.Cts.Cancel(); } catch { }
if (job.State == DownloadState.Queued) job.State = DownloadState.Canceled;
}
public void Retry(DownloadJob job)
{
if (job.IsActive) return;
Jobs.Remove(job);
Enqueue(job.Model);
}
public void Remove(DownloadJob job)
{
Cancel(job);
Jobs.Remove(job);
}
public void ClearFinished()
{
for (var i = Jobs.Count - 1; i >= 0; i--)
{
if (Jobs[i].State is DownloadState.Completed or DownloadState.Canceled)
Jobs.RemoveAt(i);
}
}
public int ActiveCount => Jobs.Count(j => j.IsActive);
}
@@ -0,0 +1,34 @@
using System.Text.Encodings.Web;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace EarthModelStudio.Services;
public static class Json
{
public static readonly JsonSerializerOptions Options = new()
{
PropertyNameCaseInsensitive = true,
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
WriteIndented = true,
Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
AllowTrailingCommas = true,
ReadCommentHandling = JsonCommentHandling.Skip
};
public static T? Read<T>(string path)
{
if (!System.IO.File.Exists(path)) return default;
return JsonSerializer.Deserialize<T>(System.IO.File.ReadAllText(path), Options);
}
public static void Write<T>(string path, T value)
{
var dir = System.IO.Path.GetDirectoryName(path);
if (!string.IsNullOrEmpty(dir)) System.IO.Directory.CreateDirectory(dir);
var tmp = path + ".tmp";
System.IO.File.WriteAllText(tmp, JsonSerializer.Serialize(value, Options));
System.IO.File.Move(tmp, path, true);
}
}
@@ -0,0 +1,141 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.IO;
using System.Text.Json;
using Avalonia.Markup.Xaml;
using Avalonia.Data;
using Avalonia.Platform;
namespace EarthModelStudio.Services;
/// <summary>轻量 i18n:键值表 + 运行时切换(所有绑定自动刷新)。</summary>
public sealed class L : INotifyPropertyChanged
{
private static readonly L _instance = new();
public static L I => _instance;
private Dictionary<string, string> _map = new(StringComparer.OrdinalIgnoreCase);
private readonly List<WeakReference<LocalizedString>> _watchers = new();
public string Language { get; private set; } = "zh-CN";
public event PropertyChangedEventHandler? PropertyChanged;
public event Action? LanguageChanged;
public static readonly (string Code, string Label)[] Supported =
{
("zh-CN", "简体中文"),
("en", "English")
};
public void Initialize(string? preference)
{
var code = Resolve(preference);
LoadLanguage(code, force: true);
}
public static string Resolve(string? pref)
{
if (!string.IsNullOrWhiteSpace(pref) && !pref.Equals("auto", StringComparison.OrdinalIgnoreCase))
return pref!.StartsWith("en", StringComparison.OrdinalIgnoreCase) ? "en" : "zh-CN";
var ui = CultureInfo.CurrentUICulture;
return ui.TwoLetterISOLanguageName.Equals("zh", StringComparison.OrdinalIgnoreCase) ? "zh-CN" : "en";
}
public void SetLanguage(string code)
{
code = Resolve(code);
if (code == Language) return;
LoadLanguage(code, force: false);
}
private void LoadLanguage(string code, bool force)
{
var loaded = ReadTable(code) ?? ReadTable("en") ?? new Dictionary<string, string>();
if (code != "zh-CN")
{
// 中文兜底,避免缺键出现空白
foreach (var kv in ReadTable("zh-CN") ?? new Dictionary<string, string>())
loaded.TryAdd(kv.Key, kv.Value);
}
_map = loaded;
if (!force && code == Language) return;
Language = code;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("Item[]"));
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Language)));
foreach (var w in _watchers)
if (w.TryGetTarget(out var ls)) ls.Refresh();
LanguageChanged?.Invoke();
}
private static Dictionary<string, string>? ReadTable(string code)
{
try
{
var uri = new Uri($"avares://EarthModelStudio/Assets/i18n/{code}.json");
using var stream = AssetLoader.Open(uri);
using var reader = new StreamReader(stream);
return JsonSerializer.Deserialize<Dictionary<string, string>>(reader.ReadToEnd(),
new JsonSerializerOptions { ReadCommentHandling = JsonCommentHandling.Skip, AllowTrailingCommas = true });
}
catch
{
return null;
}
}
public string this[string key]
{
get
{
if (string.IsNullOrEmpty(key)) return "";
return _map.TryGetValue(key, out var v) ? v : key;
}
}
public string F(string key, params object?[] args)
{
var fmt = this[key];
try { return string.Format(fmt, args); }
catch (FormatException) { return fmt; }
}
public LocalizedString For(string key)
{
var ls = new LocalizedString(key);
_watchers.Add(new WeakReference<LocalizedString>(ls));
return ls;
}
/// <summary>按 i18n 字典取值:当前语言 -> 英文 -> zh-CN -> 默认名。</summary>
public string Pick(Dictionary<string, string>? dict, string fallback)
{
if (dict == null || dict.Count == 0) return fallback;
if (dict.TryGetValue(Language, out var v) && !string.IsNullOrWhiteSpace(v)) return v;
if (Language != "en" && dict.TryGetValue("en", out var en) && !string.IsNullOrWhiteSpace(en)) return en;
if (dict.TryGetValue("zh-CN", out var zh) && !string.IsNullOrWhiteSpace(zh)) return zh;
foreach (var kv in dict) if (!string.IsNullOrWhiteSpace(kv.Value)) return kv.Value;
return fallback;
}
}
public sealed class LocalizedString : INotifyPropertyChanged
{
public string Key { get; }
public LocalizedString(string key) => Key = key;
public string Value => L.I[Key];
public event PropertyChangedEventHandler? PropertyChanged;
internal void Refresh() => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Value)));
}
/// <summary>XAML 用法:Text="{loc:Loc nav.home}"</summary>
public sealed class LocExtension : MarkupExtension
{
public LocExtension() { }
public LocExtension(string key) => Key = key;
public string Key { get; set; } = "";
public override object ProvideValue(IServiceProvider serviceProvider)
=> new Binding(nameof(LocalizedString.Value)) { Source = L.I.For(Key) };
}
@@ -0,0 +1,30 @@
using System;
namespace EarthModelStudio.Services;
/// <summary>
/// 启动时运行内存分配(类似启动器的 -Xmx)。
/// 启动器只负责把这份预算通过 <c>IModelContext.MemoryBudgetMb</c> 交给模型,
/// 具体怎么用(贴图分辨率、缓存大小)由模型自己决定。
/// </summary>
public sealed class MemoryBudget
{
public int BudgetMb { get; private set; } = 2048;
public long BudgetBytes => (long)BudgetMb * 1024L * 1024L;
public long ManagedBytes => GC.GetTotalMemory(false);
public event Action? Changed;
public void Apply(int mb)
{
BudgetMb = Math.Clamp(mb, 256, 16384);
Changed?.Invoke();
}
/// <summary>内存情况变化(例如模型窗口开关)时刷新展示。</summary>
public void Refresh() => Changed?.Invoke();
public double UsageRatio => BudgetBytes <= 0 ? 0 : Math.Clamp((double)ManagedBytes / BudgetBytes, 0, 1);
public string UsageText => $"{ModelScanner.HumanSize(ManagedBytes)} / {BudgetMb} MB";
}
@@ -0,0 +1,233 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Runtime.Loader;
using System.Threading.Tasks;
using Avalonia.Controls;
using EarthModelStudio.Models;
using EarthModelStudio.ModelSdk;
namespace EarthModelStudio.Services;
/// <summary>
/// 模型宿主:按清单加载模型自己的程序集,拿到模型自带的界面。
/// 启动器对“场景 / 行星 / 节气”一无所知,只认契约。
/// </summary>
public sealed class ModelHost
{
public const int SupportedApiVersion = 1;
private readonly AppPaths _paths;
private readonly SettingsService _settings;
private readonly MemoryBudget _memory;
public ModelHost(AppPaths paths, SettingsService settings, MemoryBudget memory)
{
_paths = paths;
_settings = settings;
_memory = memory;
}
/// <summary>同步加载(全部在 UI 线程,用于自检 / 命令行)。</summary>
public LoadedModel Load(ModelPackage package, Action requestClose, Action<double, string?>? progress = null)
{
var session = CreateSession(package, requestClose, progress);
try
{
session.Runtime.Prepare(session.Context);
var view = session.Runtime.CreateView(session.Context)
?? throw new InvalidOperationException("模型没有返回界面");
return session.Complete(view);
}
catch
{
session.Dispose();
throw;
}
}
/// <summary>
/// 异步加载:数据准备放在后台线程(<see cref="IModelRuntime.Prepare"/>),
/// 界面构建回到 UI 线程,进度通过 <paramref name="progress"/> 实时汇报。
/// </summary>
public async Task<LoadedModel> LoadAsync(ModelPackage package, Action requestClose,
Action<double, string?>? progress = null)
{
var session = CreateSession(package, requestClose, progress);
try
{
await Task.Run(() => session.Runtime.Prepare(session.Context)).ConfigureAwait(true);
var view = session.Runtime.CreateView(session.Context)
?? throw new InvalidOperationException("模型没有返回界面");
return session.Complete(view);
}
catch
{
session.Dispose();
throw;
}
}
private Session CreateSession(ModelPackage package, Action requestClose, Action<double, string?>? progress)
{
var assemblyPath = package.AssemblyPath;
if (!File.Exists(assemblyPath))
throw new FileNotFoundException($"模型缺少功能程序集:{assemblyPath}", assemblyPath);
var directory = Path.GetDirectoryName(assemblyPath)!;
var context = new ModelLoadContext(directory);
try
{
var assembly = context.LoadFromAssemblyPath(assemblyPath);
var type = ResolveFactoryType(assembly, package.Manifest.Type);
if (type == null)
throw new InvalidOperationException("模型程序集里没有找到 IModelFactory 实现");
if (Activator.CreateInstance(type) is not IModelFactory factory)
throw new InvalidOperationException($"无法创建模型入口:{type.FullName}");
if (factory.ApiVersion != SupportedApiVersion)
throw new InvalidOperationException(
$"模型契约版本 {factory.ApiVersion} 与启动器 {SupportedApiVersion} 不一致");
var runtime = factory.Create();
var modelContext = new ModelContext(package, L.I.Language, _memory.BudgetMb, requestClose, progress);
return new Session(context, runtime, modelContext);
}
catch
{
context.Unload();
throw;
}
}
private static Type? ResolveFactoryType(Assembly assembly, string? typeName)
{
if (!string.IsNullOrWhiteSpace(typeName))
{
var exact = assembly.GetType(typeName!, throwOnError: false);
if (exact != null) return exact;
}
foreach (var type in assembly.GetTypes())
{
if (type.IsAbstract || type.IsInterface) continue;
if (typeof(IModelFactory).IsAssignableFrom(type)) return type;
}
return null;
}
private sealed class Session : IDisposable
{
private readonly ModelLoadContext _context;
public Session(ModelLoadContext context, IModelRuntime runtime, ModelContext modelContext)
{
_context = context;
Runtime = runtime;
Context = modelContext;
}
public IModelRuntime Runtime { get; }
public ModelContext Context { get; }
public LoadedModel Complete(Control view) => new(_context, Runtime, view);
public void Dispose()
{
try { Runtime.Dispose(); } catch (Exception ex) { Console.Error.WriteLine($"释放模型失败: {ex.Message}"); }
try { _context.Unload(); } catch (Exception ex) { Console.Error.WriteLine($"卸载模型程序集失败: {ex.Message}"); }
}
}
}
/// <summary>一次性模型实例:窗口关闭后释放视图、卸载程序集。</summary>
public sealed class LoadedModel : IDisposable
{
private readonly ModelLoadContext _context;
private readonly IModelRuntime _runtime;
private bool _disposed;
public LoadedModel(ModelLoadContext context, IModelRuntime runtime, Control view)
{
_context = context;
_runtime = runtime;
View = view;
}
public Control View { get; }
public void Dispose()
{
if (_disposed) return;
_disposed = true;
try { _runtime.Dispose(); } catch (Exception ex) { Console.Error.WriteLine($"释放模型失败: {ex.Message}"); }
try { _context.Unload(); } catch (Exception ex) { Console.Error.WriteLine($"卸载模型程序集失败: {ex.Message}"); }
}
}
/// <summary>模型程序集加载上下文:契约与 Avalonia 一律回到默认上下文,保证类型一致。</summary>
public sealed class ModelLoadContext : AssemblyLoadContext
{
private static readonly HashSet<string> Shared = new(StringComparer.OrdinalIgnoreCase)
{
"EarthModelStudio.ModelSdk",
"Avalonia",
"Avalonia.Base",
"Avalonia.Controls",
"Avalonia.Desktop",
"Avalonia.Skia",
"Avalonia.Themes.Fluent",
"SkiaSharp",
"HarfBuzzSharp"
};
private readonly string _directory;
public ModelLoadContext(string directory) : base("model:" + Path.GetFileName(directory), isCollectible: true)
=> _directory = directory;
protected override Assembly? Load(AssemblyName assemblyName)
{
var name = assemblyName.Name;
if (string.IsNullOrEmpty(name)) return null;
if (Shared.Contains(name)) return null; // 用启动器已加载的那份
if (name.StartsWith("System.", StringComparison.OrdinalIgnoreCase)) return null;
if (name is "System" or "netstandard" or "mscorlib") return null;
var candidate = Path.Combine(_directory, name + ".dll");
return File.Exists(candidate) ? LoadFromAssemblyPath(candidate) : null;
}
}
/// <summary>启动器提供给模型的环境。</summary>
public sealed class ModelContext : IModelContext
{
private readonly Action _requestClose;
private readonly Action<double, string?>? _progress;
public ModelContext(ModelPackage package, string language, int memoryMb, Action requestClose,
Action<double, string?>? progress)
{
_progress = progress;
ModelId = package.Id;
ModelDirectory = package.Directory;
DataDirectory = package.DataDirectory;
Language = language;
MemoryBudgetMb = memoryMb;
_requestClose = requestClose;
}
public string ModelId { get; }
public string ModelDirectory { get; }
public string DataDirectory { get; }
public string Language { get; }
public int MemoryBudgetMb { get; }
public void RequestClose() => _requestClose();
public void ReportProgress(double value, string? message = null) => _progress?.Invoke(value, message);
public void Log(string message) => Console.WriteLine(message);
}
@@ -0,0 +1,71 @@
using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using EarthModelStudio.Models;
namespace EarthModelStudio.Services;
public static class ModelInstaller
{
/// <summary>把源里的模型目录复制进本地模型库(先写临时目录再原子替换)。</summary>
public static async Task<string> InstallAsync(RemoteModel model, string modelRoot,
IProgress<(long Done, long Total)>? progress, CancellationToken ct)
{
var target = Path.Combine(modelRoot, model.Id);
var staging = target + ".installing";
if (Directory.Exists(staging)) Directory.Delete(staging, true);
Directory.CreateDirectory(staging);
long total = 0;
var files = Directory.GetFiles(model.Directory, "*", SearchOption.AllDirectories);
foreach (var file in files)
{
try { total += new FileInfo(file).Length; } catch { }
}
long done = 0;
try
{
foreach (var file in files)
{
ct.ThrowIfCancellationRequested();
var relative = Path.GetRelativePath(model.Directory, file);
var dest = Path.Combine(staging, relative);
var destDir = Path.GetDirectoryName(dest);
if (!string.IsNullOrEmpty(destDir)) Directory.CreateDirectory(destDir);
await using (var src = File.OpenRead(file))
await using (var dst = File.Create(dest))
{
await src.CopyToAsync(dst, 81920, ct);
}
long length = 0;
try { length = new FileInfo(dest).Length; } catch { }
done += length;
progress?.Report((done, total <= 0 ? done : total));
}
if (Directory.Exists(target))
{
var backup = target + ".old";
if (Directory.Exists(backup)) Directory.Delete(backup, true);
Directory.Move(target, backup);
Directory.Move(staging, target);
try { Directory.Delete(backup, true); } catch { }
}
else
{
Directory.Move(staging, target);
}
progress?.Report((total, total));
return target;
}
catch
{
try { if (Directory.Exists(staging)) Directory.Delete(staging, true); } catch { }
throw;
}
}
}
@@ -0,0 +1,56 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using EarthModelStudio.Models;
namespace EarthModelStudio.Services;
/// <summary>
/// 本地模型库。启动器只**扫描 / 删除**模型包,不再解析或缓存任何场景数据 ——
/// 场景、贴图、界面都由模型自己的程序集负责。
/// </summary>
public sealed class ModelRepository
{
private readonly AppPaths _paths;
public ModelRepository(AppPaths paths) => _paths = paths;
public event Action? Changed;
public IReadOnlyList<ModelPackage> Scan()
{
var result = new List<ModelPackage>();
foreach (var (manifest, dir) in ModelScanner.Scan(_paths.ModelRoot))
{
result.Add(new ModelPackage
{
Manifest = manifest,
Directory = dir,
SizeBytes = ModelScanner.DirectorySize(dir)
});
}
return result;
}
public ModelPackage? Find(string id) => Scan().FirstOrDefault(p => p.Id.Equals(id, StringComparison.OrdinalIgnoreCase));
public bool Delete(string id)
{
var package = Find(id);
if (package == null) return false;
try
{
Directory.Delete(package.Directory, true);
Changed?.Invoke();
return true;
}
catch (Exception ex)
{
Console.Error.WriteLine($"删除模型失败: {ex.Message}");
return false;
}
}
public void NotifyChanged() => Changed?.Invoke();
}
@@ -0,0 +1,70 @@
using System;
using System.Collections.Generic;
using System.IO;
using EarthModelStudio.Models;
namespace EarthModelStudio.Services;
public static class ModelScanner
{
/// <summary>扫描模型库:model/&lt;id&gt;/&lt;id&gt;.json + &lt;id&gt;.model/</summary>
public static List<(ModelManifest Manifest, string Dir)> Scan(string modelRoot)
{
var list = new List<(ModelManifest, string)>();
if (!Directory.Exists(modelRoot)) return list;
foreach (var dir in Directory.GetDirectories(modelRoot))
{
var folder = Path.GetFileName(dir);
if (folder.StartsWith(".")) continue;
var manifestPath = Path.Combine(dir, folder + ".json");
if (!File.Exists(manifestPath))
{
var candidates = Directory.GetFiles(dir, "*.json", SearchOption.TopDirectoryOnly);
if (candidates.Length == 0) continue;
manifestPath = candidates[0];
}
ModelManifest? manifest;
try { manifest = Json.Read<ModelManifest>(manifestPath); }
catch (Exception ex)
{
Console.Error.WriteLine($"模型清单解析失败 {manifestPath}: {ex.Message}");
continue;
}
if (manifest == null) continue;
if (string.IsNullOrWhiteSpace(manifest.Id)) manifest.Id = folder;
list.Add((manifest, dir));
}
list.Sort((a, b) => string.Compare(a.Item1.Id, b.Item1.Id, StringComparison.OrdinalIgnoreCase));
return list;
}
public static long DirectorySize(string dir)
{
if (!Directory.Exists(dir)) return 0;
long total = 0;
try
{
foreach (var file in Directory.EnumerateFiles(dir, "*", SearchOption.AllDirectories))
{
try { total += new FileInfo(file).Length; }
catch { /* 忽略被占用的文件 */ }
}
}
catch { /* 忽略权限问题 */ }
return total;
}
public static string HumanSize(long bytes)
{
string[] units = { "B", "KB", "MB", "GB" };
double value = bytes;
var unit = 0;
while (value >= 1024 && unit < units.Length - 1) { value /= 1024; unit++; }
return unit == 0 ? $"{bytes} B" : $"{value:0.#} {units[unit]}";
}
}
@@ -0,0 +1,252 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using EarthModelStudio.Models;
namespace EarthModelStudio.Services;
/// <summary>
/// 从链接导入模型源。
/// 支持:git 仓库地址(GitHub / GitLab / Gitee / 任意 git 地址)、zip 直链、本地目录。
/// 仓库里的 model/ 目录就是模型列表;下载后缓存到 cache/sources/&lt;id&gt;。
/// </summary>
public sealed class ModelSourceClient
{
private readonly AppPaths _paths;
private static readonly HttpClient Http = CreateHttp();
public ModelSourceClient(AppPaths paths) => _paths = paths;
private static HttpClient CreateHttp()
{
var client = new HttpClient { Timeout = TimeSpan.FromMinutes(5) };
client.DefaultRequestHeaders.UserAgent.ParseAdd("EarthModelStudio/1.0 (+model-source)");
return client;
}
public async Task<SourceIndex> FetchAsync(ModelSource source, bool force, IProgress<string>? log, CancellationToken ct)
{
if (string.IsNullOrWhiteSpace(source.Url))
return new SourceIndex { SourceId = source.Id, Error = "dl.error.emptyUrl" };
try
{
var (root, fromCache) = await ResolveRootAsync(source, force, log, ct);
var models = new List<RemoteModel>();
foreach (var (manifest, dir) in ModelScanner.Scan(Path.Combine(root, "model")))
{
models.Add(new RemoteModel
{
Manifest = manifest,
Directory = dir,
SizeBytes = ModelScanner.DirectorySize(dir),
SourceId = source.Id
});
}
return new SourceIndex
{
SourceId = source.Id,
Root = root,
Models = models,
FromCache = fromCache,
ResolvedFrom = root
};
}
catch (OperationCanceledException)
{
return new SourceIndex { SourceId = source.Id, Error = "dl.error.canceled" };
}
catch (Exception ex)
{
return new SourceIndex { SourceId = source.Id, Error = ex.Message };
}
}
private async Task<(string Root, bool FromCache)> ResolveRootAsync(ModelSource source, bool force,
IProgress<string>? log, CancellationToken ct)
{
var raw = source.Url.Trim();
// 1) 本地目录(开发模型源最方便)
var localPath = raw.StartsWith("file://", StringComparison.OrdinalIgnoreCase)
? new Uri(raw).LocalPath
: raw;
if (Directory.Exists(localPath))
{
log?.Report("local");
return (localPath, true);
}
var cacheDir = Path.Combine(_paths.CacheRoot, "sources", source.Id);
if (!force && Directory.Exists(Path.Combine(cacheDir, "model")))
{
log?.Report("cache");
return (cacheDir, true);
}
if (Directory.Exists(cacheDir)) Directory.Delete(cacheDir, true);
Directory.CreateDirectory(cacheDir);
// 2) zip 直链 / 托管平台归档
foreach (var url in ArchiveCandidates(raw, source.Branch))
{
ct.ThrowIfCancellationRequested();
try
{
log?.Report("zip:" + url);
await DownloadZipAsync(url, cacheDir, ct);
if (Directory.Exists(Path.Combine(cacheDir, "model")))
return (cacheDir, false);
}
catch (OperationCanceledException) { throw; }
catch (Exception ex)
{
log?.Report("zip-failed:" + ex.Message);
}
}
// 3) git clone(需要本机安装 git)
log?.Report("git");
if (await TryGitCloneAsync(raw, cacheDir, source.Branch, ct))
return (cacheDir, false);
throw new InvalidOperationException("dl.error.unreachable");
}
private static IEnumerable<string> ArchiveCandidates(string url, string? branch)
{
if (url.EndsWith(".zip", StringComparison.OrdinalIgnoreCase))
{
yield return url;
yield break;
}
if (!Uri.TryCreate(url, UriKind.Absolute, out var uri)) yield break;
var segments = uri.AbsolutePath.Trim('/').Split('/', StringSplitOptions.RemoveEmptyEntries);
if (segments.Length < 2) yield break;
var owner = segments[0];
var repo = segments[1].EndsWith(".git", StringComparison.OrdinalIgnoreCase)
? segments[1][..^4]
: segments[1];
var host = uri.Host.ToLowerInvariant();
var branches = new List<string>();
if (!string.IsNullOrWhiteSpace(branch)) branches.Add(branch!);
else if (host.Contains("gitee")) { branches.Add("master"); branches.Add("main"); }
else { branches.Add("main"); branches.Add("master"); }
foreach (var b in branches)
{
if (host.Contains("github.com"))
yield return $"https://codeload.github.com/{owner}/{repo}/zip/refs/heads/{b}";
else if (host.Contains("gitlab"))
yield return $"https://gitlab.com/{owner}/{repo}/-/archive/{b}/{repo}-{b}.zip";
else if (host.Contains("gitee.com"))
yield return $"https://gitee.com/{owner}/{repo}/repository/archive/{b}.zip";
else
yield break;
}
}
private async Task DownloadZipAsync(string url, string cacheDir, CancellationToken ct)
{
var tmpRoot = Path.Combine(_paths.CacheRoot, "tmp", Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(tmpRoot);
var zipPath = Path.Combine(tmpRoot, "source.zip");
try
{
using (var response = await Http.GetAsync(url, HttpCompletionOption.ResponseHeadersRead, ct))
{
response.EnsureSuccessStatusCode();
await using var input = await response.Content.ReadAsStreamAsync(ct);
await using var output = File.Create(zipPath);
await input.CopyToAsync(output, 81920, ct);
}
var extractDir = Path.Combine(tmpRoot, "extract");
Directory.CreateDirectory(extractDir);
ZipFile.ExtractToDirectory(zipPath, extractDir, true);
var root = FindModelRoot(extractDir) ?? extractDir;
foreach (var entry in Directory.GetFileSystemEntries(root))
{
var name = Path.GetFileName(entry);
var dest = Path.Combine(cacheDir, name);
if (Directory.Exists(dest)) Directory.Delete(dest, true);
else if (File.Exists(dest)) File.Delete(dest);
if (Directory.Exists(entry)) Directory.Move(entry, dest);
else File.Move(entry, dest);
}
}
finally
{
try { if (Directory.Exists(tmpRoot)) Directory.Delete(tmpRoot, true); } catch { }
}
}
private static string? FindModelRoot(string dir, int depth = 0)
{
if (Directory.Exists(Path.Combine(dir, "model"))) return dir;
if (depth >= 2) return null;
foreach (var child in Directory.GetDirectories(dir))
{
var found = FindModelRoot(child, depth + 1);
if (found != null) return found;
}
return null;
}
private static async Task<bool> TryGitCloneAsync(string url, string cacheDir, string? branch, CancellationToken ct)
{
if (cacheDir.Length > 0 && Directory.Exists(cacheDir))
{
foreach (var f in Directory.GetFileSystemEntries(cacheDir))
{
if (Directory.Exists(f)) Directory.Delete(f, true);
else File.Delete(f);
}
}
var args = new List<string> { "clone", "--depth", "1" };
if (!string.IsNullOrWhiteSpace(branch)) { args.Add("--branch"); args.Add(branch!); }
args.Add(url);
args.Add(cacheDir);
try
{
var psi = new ProcessStartInfo("git")
{
RedirectStandardOutput = true,
RedirectStandardError = true,
UseShellExecute = false,
CreateNoWindow = true
};
foreach (var a in args) psi.ArgumentList.Add(a);
using var process = Process.Start(psi);
if (process == null) return false;
var stderrTask = process.StandardError.ReadToEndAsync(ct);
await process.WaitForExitAsync(ct);
var stderr = await stderrTask;
if (process.ExitCode != 0)
{
Console.Error.WriteLine($"git clone 失败: {stderr}");
return false;
}
return Directory.Exists(Path.Combine(cacheDir, "model")) || Directory.Exists(cacheDir);
}
catch (Exception ex)
{
Console.Error.WriteLine($"git clone 异常: {ex.Message}");
return false;
}
}
}
@@ -0,0 +1,64 @@
using System;
using System.Collections.Generic;
using System.IO;
using EarthModelStudio.Models;
namespace EarthModelStudio.Services;
public sealed class SettingsService
{
private readonly AppPaths _paths;
public AppSettings Current { get; private set; } = new();
public event Action? Changed;
public SettingsService(AppPaths paths) => _paths = paths;
public void Load()
{
Current = Json.Read<AppSettings>(_paths.SettingsFile) ?? new AppSettings();
if (Current.Sources.Count == 0) SeedSources();
if (Current.MemoryMb < 256) Current.MemoryMb = 2048;
}
/// <summary>
/// 首次启动不预置任何模型源:启动器只做适配,模型内容由用户从链接导入。
/// 这里只给一条空的自定义源占位。
/// </summary>
private void SeedSources()
{
Current.Sources.Add(new ModelSource
{
Id = "custom",
Name = "自定义源",
Url = "",
Enabled = false
});
Save();
}
public void Save()
{
try
{
Json.Write(_paths.SettingsFile, Current);
}
catch (Exception ex)
{
Console.Error.WriteLine($"保存设置失败: {ex.Message}");
}
}
public void Apply(Action<AppSettings> mutate)
{
mutate(Current);
Save();
Changed?.Invoke();
}
public void Notify()
{
Save();
Changed?.Invoke();
}
}
@@ -0,0 +1,30 @@
using System;
using System.Diagnostics;
using System.IO;
namespace EarthModelStudio.Services;
public static class Shell
{
public static void OpenFolder(string path)
{
if (string.IsNullOrWhiteSpace(path)) return;
try
{
if (!Directory.Exists(path)) Directory.CreateDirectory(path);
var info = new ProcessStartInfo
{
FileName = OperatingSystem.IsWindows() ? "explorer.exe"
: OperatingSystem.IsMacOS() ? "open"
: "xdg-open",
UseShellExecute = false
};
info.ArgumentList.Add(path);
Process.Start(info);
}
catch (Exception ex)
{
Console.Error.WriteLine($"打开目录失败: {ex.Message}");
}
}
}