添加部分功能,以及等高线模型
This commit is contained in:
1 parent
663efa5c75
commit
512b1814e1
108 files changed
+239
-240
No files matched your search
@@ -0,0 +1,104 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.ObjectModel;
|
||||
using System.Threading.Tasks;
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
using CommunityToolkit.Mvvm.Input;
|
||||
using GC.Services;
|
||||
|
||||
namespace GC.ViewModels;
|
||||
|
||||
/// <summary>「关于」页面:版本号 + 开发者(读取仓库 contributors)。</summary>
|
||||
public partial class AboutViewModel : ObservableObject
|
||||
{
|
||||
private readonly AppServices _services;
|
||||
private bool _loaded;
|
||||
|
||||
public ObservableCollection<ContributorItem> Contributors { get; } = new();
|
||||
|
||||
[ObservableProperty] private bool _isLoading = true;
|
||||
[ObservableProperty] private string _statusText = "";
|
||||
[ObservableProperty] private bool _hasContributors;
|
||||
|
||||
public AboutViewModel(AppServices services)
|
||||
{
|
||||
_services = services;
|
||||
LoadCommand = new AsyncRelayCommand(() => LoadAsync(force: true));
|
||||
}
|
||||
|
||||
public string AppName => "Morris GC";
|
||||
|
||||
/// <summary>启动器版本号,如 v1.0.2。</summary>
|
||||
public string VersionText => "v" + UpdateService.CurrentLauncherVersion;
|
||||
|
||||
/// <summary>当前平台标识,如 win-x64 / osx-arm64。</summary>
|
||||
public string PlatformText => UpdateService.CurrentRid;
|
||||
|
||||
public string RepositoryText => _services.Settings.Current.UpdateRepository;
|
||||
|
||||
public string ContributorsTitle => "开发者";
|
||||
|
||||
public IAsyncRelayCommand LoadCommand { get; }
|
||||
|
||||
/// <summary>每次进入页面时调用(首次才真正联网拉取)。</summary>
|
||||
public void OnShown()
|
||||
{
|
||||
if (_loaded) return;
|
||||
_ = LoadAsync(force: false);
|
||||
}
|
||||
|
||||
private async Task LoadAsync(bool force)
|
||||
{
|
||||
if (_loaded && !force) return;
|
||||
_loaded = true;
|
||||
|
||||
IsLoading = true;
|
||||
StatusText = "正在读取贡献者…";
|
||||
try
|
||||
{
|
||||
var list = await ContributorsService.FetchAsync(_services.Settings.Current.UpdateRepository);
|
||||
Contributors.Clear();
|
||||
foreach (var c in list)
|
||||
Contributors.Add(new ContributorItem(c));
|
||||
|
||||
HasContributors = Contributors.Count > 0;
|
||||
StatusText = HasContributors ? $"{Contributors.Count} 位贡献者" : "暂无贡献者信息";
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
StatusText = "读取失败:" + ex.Message;
|
||||
}
|
||||
finally
|
||||
{
|
||||
IsLoading = false;
|
||||
}
|
||||
}
|
||||
|
||||
[RelayCommand]
|
||||
private void OpenRepository() => Shell.OpenUrl(RepositoryText);
|
||||
|
||||
/// <summary>重新下载启动器:关闭所有窗口,进度窗下载新版,完成后重启。</summary>
|
||||
[RelayCommand]
|
||||
private async System.Threading.Tasks.Task ReinstallLauncher()
|
||||
{
|
||||
if (LauncherUpdateFlow.IsRunning) return;
|
||||
await LauncherUpdateFlow.RunAsync(_services, "正在重新下载启动器");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>一位贡献者的展示项。</summary>
|
||||
public sealed class ContributorItem
|
||||
{
|
||||
public ContributorItem(Contributor c)
|
||||
{
|
||||
Name = c.DisplayName;
|
||||
Contributions = c.Contributions;
|
||||
AvatarUrl = c.AvatarUrl;
|
||||
}
|
||||
|
||||
public string Name { get; }
|
||||
public int Contributions { get; }
|
||||
public string? AvatarUrl { get; }
|
||||
public string ContributionsText => $"{Contributions} 次提交";
|
||||
public bool HasAvatar => !string.IsNullOrWhiteSpace(AvatarUrl);
|
||||
}
|
||||
@@ -0,0 +1,411 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.ObjectModel;
|
||||
using System.Collections.Specialized;
|
||||
using System.ComponentModel;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using System.Windows.Input;
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
using CommunityToolkit.Mvvm.Input;
|
||||
using GC.Models;
|
||||
using GC.Services;
|
||||
|
||||
namespace GC.ViewModels;
|
||||
|
||||
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<SourceItemViewModel> Sources { get; } = new();
|
||||
public ObservableCollection<RemoteModelRowViewModel> Models { get; } = new();
|
||||
public ObservableCollection<DownloadJob> Jobs => _services.Downloads.Jobs;
|
||||
|
||||
[ObservableProperty] private SourceItemViewModel? _selectedSource;
|
||||
[ObservableProperty] private string _importUrl = "";
|
||||
[ObservableProperty] private bool _isBusy;
|
||||
[ObservableProperty] private string _statusMessage = "";
|
||||
[ObservableProperty] private bool _hasModels;
|
||||
[ObservableProperty] private bool _isBackgroundOpen = true;
|
||||
[ObservableProperty] private string _jobSummary = "";
|
||||
[ObservableProperty] private bool _hasJobs;
|
||||
[ObservableProperty] private bool _isSourceEmpty;
|
||||
|
||||
public DownloadViewModel(AppServices services, MainViewModel main)
|
||||
{
|
||||
_services = services;
|
||||
_main = main;
|
||||
Jobs.CollectionChanged += OnJobsChanged;
|
||||
foreach (var job in Jobs) job.PropertyChanged += OnJobPropertyChanged;
|
||||
L.I.LanguageChanged += RefreshLanguage;
|
||||
RebuildSources();
|
||||
UpdateJobState();
|
||||
}
|
||||
|
||||
public string BackgroundTitle => L.I["dl.background"];
|
||||
public string ImportHint => L.I["dl.hint"];
|
||||
|
||||
// ------------------------------------------------------------ 页面生命周期
|
||||
public void OnShown()
|
||||
{
|
||||
if (_initialized) return;
|
||||
_initialized = true;
|
||||
if (SelectedSource == null)
|
||||
SelectedSource = Sources.FirstOrDefault(s => s.Model.Enabled && !string.IsNullOrWhiteSpace(s.Model.Url))
|
||||
?? Sources.FirstOrDefault();
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------ 模型源
|
||||
private void RebuildSources()
|
||||
{
|
||||
var keepId = SelectedSource?.Model.Id;
|
||||
Sources.Clear();
|
||||
foreach (var source in _services.Settings.Current.Sources)
|
||||
Sources.Add(new SourceItemViewModel(source, this, _services));
|
||||
|
||||
SelectedSource = Sources.FirstOrDefault(s => s.Model.Id == keepId) ?? SelectedSource;
|
||||
}
|
||||
|
||||
partial void OnSelectedSourceChanged(SourceItemViewModel? value)
|
||||
{
|
||||
if (value == null) return;
|
||||
if (string.IsNullOrWhiteSpace(value.Model.Url))
|
||||
{
|
||||
Models.Clear();
|
||||
HasModels = false;
|
||||
IsSourceEmpty = true;
|
||||
StatusMessage = L.I["dl.pickSource"];
|
||||
return;
|
||||
}
|
||||
_ = LoadAsync(value, force: false);
|
||||
}
|
||||
|
||||
internal void OnSourceEnabledChanged(SourceItemViewModel source)
|
||||
{
|
||||
if (!source.Model.Enabled && SelectedSource == source) Models.Clear();
|
||||
}
|
||||
|
||||
internal void RemoveSource(SourceItemViewModel source)
|
||||
{
|
||||
if (source.Model.BuiltIn) return; // 内置默认源不允许删除
|
||||
_services.Settings.Current.Sources.Remove(source.Model);
|
||||
_services.Settings.Save();
|
||||
var wasSelected = SelectedSource == source;
|
||||
Sources.Remove(source);
|
||||
if (wasSelected)
|
||||
{
|
||||
SelectedSource = Sources.FirstOrDefault();
|
||||
if (SelectedSource == null)
|
||||
{
|
||||
Models.Clear();
|
||||
HasModels = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 只允许两个内置源(Xhmcl / GitCode),不再接受任意地址。
|
||||
/// 旧的「自定义源」入口统一改为:按测速结果切换到更快的那个源。
|
||||
/// </summary>
|
||||
[RelayCommand]
|
||||
private async Task ImportAsync()
|
||||
{
|
||||
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 = "没有可用的下载源";
|
||||
return;
|
||||
}
|
||||
|
||||
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)
|
||||
{
|
||||
var trimmed = url.TrimEnd('/', '\\');
|
||||
var slash = trimmed.LastIndexOfAny(new[] { '/', '\\' });
|
||||
var name = slash >= 0 ? trimmed[(slash + 1)..] : trimmed;
|
||||
if (name.EndsWith(".git", StringComparison.OrdinalIgnoreCase)) name = name[..^4];
|
||||
if (name.EndsWith(".zip", StringComparison.OrdinalIgnoreCase)) name = name[..^4];
|
||||
return string.IsNullOrWhiteSpace(name) ? url : name;
|
||||
}
|
||||
|
||||
[RelayCommand]
|
||||
private async Task RefreshAsync()
|
||||
{
|
||||
if (SelectedSource == null) return;
|
||||
await LoadAsync(SelectedSource, force: true);
|
||||
}
|
||||
|
||||
internal async Task RefreshFromSource(SourceItemViewModel source)
|
||||
{
|
||||
SelectedSource = source;
|
||||
await LoadAsync(source, force: true);
|
||||
}
|
||||
|
||||
private async Task LoadAsync(SourceItemViewModel source, bool force)
|
||||
{
|
||||
if (!source.Model.Enabled) return;
|
||||
|
||||
// 取消上一次尚未完成的加载,避免快速切换源时并发 Clear/写入同一集合
|
||||
_loadCts?.Cancel();
|
||||
_loadCts?.Dispose();
|
||||
_loadCts = new CancellationTokenSource();
|
||||
var ct = _loadCts.Token;
|
||||
var generation = ++_loadGeneration;
|
||||
|
||||
IsBusy = true;
|
||||
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)
|
||||
return;
|
||||
|
||||
if (index.Error != null)
|
||||
{
|
||||
Models.Clear();
|
||||
HasModels = false;
|
||||
IsSourceEmpty = true;
|
||||
StatusMessage = DescribeError(index.Error);
|
||||
return;
|
||||
}
|
||||
|
||||
var installedIds = new HashSet<string>(
|
||||
_services.Models.Scan().Select(p => p.Id), StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
Models.Clear();
|
||||
foreach (var model in index.Models)
|
||||
{
|
||||
Models.Add(new RemoteModelRowViewModel(model, source,
|
||||
installedIds.Contains(model.Id), DownloadCommand));
|
||||
}
|
||||
|
||||
HasModels = Models.Count > 0;
|
||||
IsSourceEmpty = Models.Count == 0;
|
||||
StatusMessage = index.FromCache
|
||||
? $"{L.I.F("dl.ready", Models.Count)} · {L.I["dl.fromCache"]}"
|
||||
: L.I.F("dl.ready", Models.Count);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
// 被更新的加载取代或页面关闭:忽略,不覆盖新结果
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
if (!ct.IsCancellationRequested) StatusMessage = ex.Message;
|
||||
}
|
||||
finally
|
||||
{
|
||||
// 只有最后一次加载才复位 Busy,避免旧任务把新任务的忙碌状态清掉
|
||||
if (generation == _loadGeneration) IsBusy = false;
|
||||
}
|
||||
}
|
||||
|
||||
private static string DescribeError(string error)
|
||||
{
|
||||
if (error.StartsWith("dl.", StringComparison.Ordinal))
|
||||
{
|
||||
var text = L.I[error];
|
||||
return text == error ? error : text;
|
||||
}
|
||||
return error;
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------ 下载
|
||||
[RelayCommand]
|
||||
private async Task DownloadAsync(RemoteModelRowViewModel row)
|
||||
{
|
||||
if (row == null) return;
|
||||
row.RowOpacity = 0;
|
||||
row.RowHeight = 0;
|
||||
IsBackgroundOpen = true;
|
||||
|
||||
_services.Downloads.Enqueue(row.Model);
|
||||
|
||||
await Task.Delay(240);
|
||||
Models.Remove(row);
|
||||
HasModels = Models.Count > 0;
|
||||
IsSourceEmpty = Models.Count == 0;
|
||||
}
|
||||
|
||||
[RelayCommand]
|
||||
private void CancelJob(DownloadJob? job)
|
||||
{
|
||||
if (job != null) _services.Downloads.Cancel(job);
|
||||
}
|
||||
|
||||
[RelayCommand]
|
||||
private void RetryJob(DownloadJob? job)
|
||||
{
|
||||
if (job != null) _services.Downloads.Retry(job);
|
||||
}
|
||||
|
||||
[RelayCommand]
|
||||
private void RemoveJob(DownloadJob? job)
|
||||
{
|
||||
if (job != null) _services.Downloads.Remove(job);
|
||||
}
|
||||
|
||||
[RelayCommand]
|
||||
private void ClearFinished() => _services.Downloads.ClearFinished();
|
||||
|
||||
[RelayCommand]
|
||||
private void ToggleBackground() => IsBackgroundOpen = !IsBackgroundOpen;
|
||||
|
||||
// ------------------------------------------------------------ 任务展示
|
||||
private void OnJobsChanged(object? sender, NotifyCollectionChangedEventArgs e)
|
||||
{
|
||||
if (e.NewItems != null)
|
||||
foreach (DownloadJob job in e.NewItems) job.PropertyChanged += OnJobPropertyChanged;
|
||||
if (e.OldItems != null)
|
||||
foreach (DownloadJob job in e.OldItems) job.PropertyChanged -= OnJobPropertyChanged;
|
||||
UpdateJobState();
|
||||
}
|
||||
|
||||
private void OnJobPropertyChanged(object? sender, PropertyChangedEventArgs e)
|
||||
{
|
||||
if (e.PropertyName == nameof(DownloadJob.State))
|
||||
{
|
||||
if (sender is DownloadJob { State: DownloadState.Completed })
|
||||
_services.Models.NotifyChanged();
|
||||
}
|
||||
UpdateJobState();
|
||||
}
|
||||
|
||||
private void UpdateJobState()
|
||||
{
|
||||
HasJobs = Jobs.Count > 0;
|
||||
JobSummary = $"{L.I["dl.background"]} ({Jobs.Count})";
|
||||
OnPropertyChanged(nameof(JobSummary));
|
||||
}
|
||||
|
||||
private void RefreshLanguage()
|
||||
{
|
||||
foreach (var source in Sources) source.RefreshLanguage();
|
||||
foreach (var model in Models) model.RefreshLanguage();
|
||||
foreach (var job in Jobs) job.RefreshText();
|
||||
OnPropertyChanged(nameof(BackgroundTitle));
|
||||
OnPropertyChanged(nameof(ImportHint));
|
||||
UpdateJobState();
|
||||
}
|
||||
}
|
||||
|
||||
public partial class SourceItemViewModel : ObservableObject
|
||||
{
|
||||
private readonly DownloadViewModel _owner;
|
||||
private readonly AppServices _services;
|
||||
|
||||
public ModelSource Model { get; }
|
||||
|
||||
public SourceItemViewModel(ModelSource model, DownloadViewModel owner, AppServices services)
|
||||
{
|
||||
Model = model;
|
||||
_owner = owner;
|
||||
_services = services;
|
||||
RemoveCommand = new RelayCommand(() => _owner.RemoveSource(this));
|
||||
RefreshCommand = new AsyncRelayCommand(async () => await _owner.RefreshFromSource(this));
|
||||
}
|
||||
|
||||
public string Name => string.IsNullOrWhiteSpace(Model.Name) ? Model.Id : Model.Name;
|
||||
public string HostText => string.IsNullOrWhiteSpace(Model.Url) ? L.I["dl.noSource"] : Model.DisplayHost;
|
||||
public bool HasUrl => !string.IsNullOrWhiteSpace(Model.Url);
|
||||
/// <summary>内置默认源不可删除(下载页隐藏删除按钮)。</summary>
|
||||
public bool CanRemove => !Model.BuiltIn;
|
||||
|
||||
public bool Enabled
|
||||
{
|
||||
get => Model.Enabled;
|
||||
set
|
||||
{
|
||||
if (Model.Enabled == value) return;
|
||||
Model.Enabled = value;
|
||||
_services.Settings.Save();
|
||||
OnPropertyChanged();
|
||||
_owner.OnSourceEnabledChanged(this);
|
||||
}
|
||||
}
|
||||
|
||||
public ICommand RemoveCommand { get; }
|
||||
public ICommand RefreshCommand { get; }
|
||||
|
||||
public void RefreshLanguage()
|
||||
{
|
||||
OnPropertyChanged(nameof(Name));
|
||||
OnPropertyChanged(nameof(HostText));
|
||||
}
|
||||
}
|
||||
|
||||
public partial class RemoteModelRowViewModel : ObservableObject
|
||||
{
|
||||
public RemoteModel Model { get; }
|
||||
public SourceItemViewModel Source { get; }
|
||||
|
||||
public RemoteModelRowViewModel(RemoteModel model, SourceItemViewModel source, bool installed, ICommand downloadCommand)
|
||||
{
|
||||
Model = model;
|
||||
Source = source;
|
||||
Installed = installed;
|
||||
DownloadCommand = downloadCommand;
|
||||
}
|
||||
|
||||
public string Name => Model.LocalizedName;
|
||||
public string Description => Model.LocalizedDescription;
|
||||
public string VersionText => "v" + Model.Manifest.Version;
|
||||
public string SizeText => ModelScanner.HumanSize(Model.SizeBytes);
|
||||
public string MetaText => $"{VersionText} · {SizeText}";
|
||||
public string TagsText => string.Join(" · ", Model.Manifest.Tags ?? new List<string>());
|
||||
public bool HasTags => !string.IsNullOrWhiteSpace(TagsText);
|
||||
|
||||
[ObservableProperty] private bool _installed;
|
||||
[ObservableProperty] private double _rowHeight = 92;
|
||||
[ObservableProperty] private double _rowOpacity = 1;
|
||||
|
||||
public string ButtonText => Installed ? L.I["dl.reinstall"] : L.I["dl.download"];
|
||||
public ICommand DownloadCommand { get; }
|
||||
|
||||
partial void OnInstalledChanged(bool value) => OnPropertyChanged(nameof(ButtonText));
|
||||
|
||||
public void RefreshLanguage()
|
||||
{
|
||||
OnPropertyChanged(nameof(Name));
|
||||
OnPropertyChanged(nameof(Description));
|
||||
OnPropertyChanged(nameof(MetaText));
|
||||
OnPropertyChanged(nameof(TagsText));
|
||||
OnPropertyChanged(nameof(ButtonText));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,148 @@
|
||||
using System;
|
||||
using System.Collections.ObjectModel;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
using System.Windows.Input;
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
using CommunityToolkit.Mvvm.Input;
|
||||
using GC.Models;
|
||||
using Avalonia.Media.Imaging;
|
||||
using GC.Services;
|
||||
|
||||
namespace GC.ViewModels;
|
||||
|
||||
public partial class HomeViewModel : ObservableObject
|
||||
{
|
||||
private readonly AppServices _services;
|
||||
private readonly MainViewModel _main;
|
||||
|
||||
public ObservableCollection<ModelCardViewModel> Models { get; } = new();
|
||||
|
||||
[ObservableProperty] private ModelCardViewModel? _selected;
|
||||
[ObservableProperty] private bool _isEmpty;
|
||||
|
||||
public string CountText => L.I.F("home.count", Models.Count);
|
||||
public string SourceCountText => _services.Settings.Current.Sources
|
||||
.Count(s => s.Enabled && !string.IsNullOrWhiteSpace(s.Url)).ToString();
|
||||
public string MemoryText => $"{_services.Memory.BudgetMb} MB";
|
||||
public string SelectedHint => Selected == null ? L.I["home.recent"] : L.I["home.launchHint"];
|
||||
|
||||
public HomeViewModel(AppServices services, MainViewModel main)
|
||||
{
|
||||
_services = services;
|
||||
_main = main;
|
||||
_services.Models.Changed += Refresh;
|
||||
L.I.LanguageChanged += RefreshLanguage;
|
||||
Refresh();
|
||||
}
|
||||
|
||||
public void Refresh()
|
||||
{
|
||||
var keepId = Selected?.Package.Id;
|
||||
Models.Clear();
|
||||
foreach (var package in _services.Models.Scan())
|
||||
Models.Add(new ModelCardViewModel(package, _services, this));
|
||||
|
||||
Selected = Models.FirstOrDefault(m => m.Package.Id == keepId) ?? Models.FirstOrDefault();
|
||||
IsEmpty = Models.Count == 0;
|
||||
RefreshLanguage();
|
||||
}
|
||||
|
||||
private void RefreshLanguage()
|
||||
{
|
||||
OnPropertyChanged(nameof(CountText));
|
||||
OnPropertyChanged(nameof(SourceCountText));
|
||||
OnPropertyChanged(nameof(MemoryText));
|
||||
OnPropertyChanged(nameof(SelectedHint));
|
||||
foreach (var model in Models) model.RefreshLanguage();
|
||||
}
|
||||
|
||||
public void LaunchModel(ModelCardViewModel card)
|
||||
{
|
||||
Selected = card;
|
||||
_main.PlayModel(card.Package);
|
||||
}
|
||||
|
||||
public async Task DeleteAsync(ModelCardViewModel card)
|
||||
{
|
||||
if (!await _main.ConfirmAsync(L.I.F("home.deleteConfirm", card.Name))) return;
|
||||
_services.Models.Delete(card.Package.Id);
|
||||
_services.Models.NotifyChanged();
|
||||
Refresh();
|
||||
}
|
||||
|
||||
[RelayCommand]
|
||||
private void Launch()
|
||||
{
|
||||
var card = Selected ?? Models.FirstOrDefault();
|
||||
if (card != null) _main.PlayModel(card.Package);
|
||||
}
|
||||
|
||||
[RelayCommand]
|
||||
private void OpenDownload() => _main.GoDownload();
|
||||
|
||||
[RelayCommand]
|
||||
private void OpenSettings() => _main.GoSettings();
|
||||
|
||||
[RelayCommand]
|
||||
private void OpenFolder() => Shell.OpenFolder(_services.Paths.ModelRoot);
|
||||
}
|
||||
|
||||
public partial class ModelCardViewModel : ObservableObject
|
||||
{
|
||||
private readonly AppServices _services;
|
||||
private Bitmap? _preview;
|
||||
|
||||
public ModelPackage Package { get; }
|
||||
|
||||
public ModelCardViewModel(ModelPackage package, AppServices services, HomeViewModel home)
|
||||
{
|
||||
Package = package;
|
||||
_services = services;
|
||||
LaunchCommand = new RelayCommand(() => home.LaunchModel(this));
|
||||
DeleteCommand = new AsyncRelayCommand(() => home.DeleteAsync(this));
|
||||
OpenFolderCommand = new RelayCommand(() => Shell.OpenFolder(package.Directory));
|
||||
}
|
||||
|
||||
public string Name => Package.LocalizedName;
|
||||
public string Description => Package.LocalizedDescription;
|
||||
public string VersionText => "v" + Package.Manifest.Version;
|
||||
public string SizeText => ModelScanner.HumanSize(Package.SizeBytes);
|
||||
public string MetaText => $"{VersionText} · {SizeText}";
|
||||
public string TagsText => string.Join(" · ", Package.Manifest.Tags ?? new());
|
||||
public bool HasTags => !string.IsNullOrWhiteSpace(TagsText);
|
||||
public string AuthorText => string.IsNullOrWhiteSpace(Package.Manifest.Author) ? "" : Package.Manifest.Author;
|
||||
|
||||
/// <summary>封面图来自模型包自带的 preview.png —— 启动器只显示,不渲染。</summary>
|
||||
public Bitmap? Preview
|
||||
{
|
||||
get
|
||||
{
|
||||
if (_preview != null) return _preview;
|
||||
try
|
||||
{
|
||||
if (File.Exists(Package.PreviewPath)) _preview = new Bitmap(Package.PreviewPath);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.Error.WriteLine($"读取模型封面失败 {Package.Id}: {ex.Message}");
|
||||
}
|
||||
return _preview;
|
||||
}
|
||||
}
|
||||
|
||||
public bool HasPreview => Preview != null;
|
||||
|
||||
public ICommand LaunchCommand { get; }
|
||||
public ICommand DeleteCommand { get; }
|
||||
public ICommand OpenFolderCommand { get; }
|
||||
|
||||
public void RefreshLanguage()
|
||||
{
|
||||
OnPropertyChanged(nameof(Name));
|
||||
OnPropertyChanged(nameof(Description));
|
||||
OnPropertyChanged(nameof(MetaText));
|
||||
OnPropertyChanged(nameof(TagsText));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,212 @@
|
||||
using System;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
using CommunityToolkit.Mvvm.Input;
|
||||
using GC.Models;
|
||||
using GC.Services;
|
||||
|
||||
namespace GC.ViewModels;
|
||||
|
||||
public partial class MainViewModel : ObservableObject
|
||||
{
|
||||
private readonly AppServices _services;
|
||||
private bool _updateRunning;
|
||||
|
||||
public HomeViewModel Home { get; }
|
||||
public DownloadViewModel Download { get; }
|
||||
public SettingsViewModel Settings { get; }
|
||||
public AboutViewModel About { get; }
|
||||
|
||||
/// <summary>模型宿主:按清单加载模型自带的功能程序集。</summary>
|
||||
public ModelHost Models { get; }
|
||||
|
||||
[ObservableProperty] private ObservableObject _current = null!;
|
||||
[ObservableProperty] private bool _isHomeActive = true;
|
||||
[ObservableProperty] private bool _isDownloadActive;
|
||||
[ObservableProperty] private bool _isSettingsActive;
|
||||
[ObservableProperty] private bool _isAboutActive;
|
||||
|
||||
// 启动更新状态条
|
||||
[ObservableProperty] private bool _updateBarVisible;
|
||||
[ObservableProperty] private bool _updateBusy;
|
||||
[ObservableProperty] private double _updateProgress;
|
||||
[ObservableProperty] private string _updateStatus = "";
|
||||
[ObservableProperty] private string _updateDetail = "";
|
||||
[ObservableProperty] private string _launcherNotice = "";
|
||||
|
||||
/// <summary>由主窗口注入的确认对话框。</summary>
|
||||
public Func<string, Task<bool>>? ConfirmHandler { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 由主窗口注入的「发现启动器新版本」对话框。
|
||||
/// 参数为新版本号,返回 true 表示用户选择更新。
|
||||
/// </summary>
|
||||
public Func<string, Task<bool>>? LauncherUpdateHandler { get; set; }
|
||||
|
||||
public event Action<ModelPackage>? PlayerRequested;
|
||||
|
||||
public string VersionText => "v" + UpdateService.CurrentLauncherVersion;
|
||||
public string PlatformText => UpdateService.CurrentRid;
|
||||
|
||||
public MainViewModel(AppServices services)
|
||||
{
|
||||
_services = services;
|
||||
Models = services.ModelHost;
|
||||
Home = new HomeViewModel(services, this);
|
||||
Download = new DownloadViewModel(services, this);
|
||||
Settings = new SettingsViewModel(services);
|
||||
About = new AboutViewModel(services);
|
||||
Current = Home;
|
||||
}
|
||||
|
||||
partial void OnCurrentChanged(ObservableObject value)
|
||||
{
|
||||
IsHomeActive = value is HomeViewModel;
|
||||
IsDownloadActive = value is DownloadViewModel;
|
||||
IsSettingsActive = value is SettingsViewModel;
|
||||
IsAboutActive = value is AboutViewModel;
|
||||
}
|
||||
|
||||
[RelayCommand]
|
||||
public void GoHome()
|
||||
{
|
||||
Home.Refresh();
|
||||
Current = Home;
|
||||
}
|
||||
|
||||
[RelayCommand]
|
||||
public void GoDownload()
|
||||
{
|
||||
Current = Download;
|
||||
Download.OnShown();
|
||||
}
|
||||
|
||||
[RelayCommand]
|
||||
public void GoSettings()
|
||||
{
|
||||
Settings.Refresh();
|
||||
Current = Settings;
|
||||
}
|
||||
|
||||
[RelayCommand]
|
||||
public void GoAbout()
|
||||
{
|
||||
About.OnShown();
|
||||
Current = About;
|
||||
}
|
||||
|
||||
/// <summary>启动模型:交给模型自己的程序集,在独立窗口中运行。</summary>
|
||||
public void PlayModel(ModelPackage package)
|
||||
{
|
||||
_services.Memory.Refresh();
|
||||
PlayerRequested?.Invoke(package);
|
||||
}
|
||||
|
||||
public async Task<bool> ConfirmAsync(string message)
|
||||
=> ConfirmHandler == null || await ConfirmHandler(message);
|
||||
|
||||
// ---- 自动更新 ----------------------------------------------------------
|
||||
|
||||
/// <summary>启动后由 App 调用:后台检查更新,不阻塞主界面。</summary>
|
||||
public Task RunStartupUpdateAsync() => RunUpdateAsync(false);
|
||||
|
||||
/// <summary>状态条 / 设置页的「检查更新」,忽略自动开关强制检查。</summary>
|
||||
[RelayCommand]
|
||||
private Task CheckUpdate() => RunUpdateAsync(true);
|
||||
|
||||
private async Task RunUpdateAsync(bool force)
|
||||
{
|
||||
if (_updateRunning) return;
|
||||
_updateRunning = true;
|
||||
try
|
||||
{
|
||||
UpdateBarVisible = true;
|
||||
UpdateBusy = true;
|
||||
UpdateProgress = 0;
|
||||
UpdateStatus = L.I["update.checking"];
|
||||
UpdateDetail = "";
|
||||
LauncherNotice = "";
|
||||
|
||||
// 在 UI 线程构造,进度回调自动回到 UI 线程
|
||||
var progress = new Progress<UpdateProgress>(p =>
|
||||
{
|
||||
UpdateProgress = Math.Clamp(p.Value, 0, 1);
|
||||
UpdateStatus = p.Message;
|
||||
UpdateDetail = p.Detail ?? "";
|
||||
});
|
||||
|
||||
// 双源测速: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)
|
||||
{
|
||||
var agreed = LauncherUpdateHandler != null &&
|
||||
await LauncherUpdateHandler(latest);
|
||||
if (agreed)
|
||||
{
|
||||
// 走完整更新流程(关窗 -> 进度窗下载 -> 重启)
|
||||
UpdateBusy = false;
|
||||
_updateRunning = false;
|
||||
UpdateBarVisible = false;
|
||||
await LauncherUpdateFlow.RunAsync(_services, "正在更新启动器");
|
||||
return;
|
||||
}
|
||||
|
||||
UpdateStatus = $"启动器有新版本 v{latest}(已跳过)";
|
||||
UpdateDetail = "点击「检查更新」可再次更新,模型仍会同步到最新";
|
||||
}
|
||||
|
||||
// 模型:同步到最新版
|
||||
var result = await _services.Updates.RunAsync(force, progress, default);
|
||||
|
||||
UpdateStatus = result.Message;
|
||||
UpdateDetail = result.Error ?? "";
|
||||
LauncherNotice = result.LauncherMessage ?? "";
|
||||
|
||||
// 模型下载完成后本次启动就刷新列表,立刻可用
|
||||
if (result.UpdatedModels > 0) Home.Refresh();
|
||||
|
||||
if ((result.Outcome == UpdateOutcome.NoChange || result.Outcome == UpdateOutcome.Applied) &&
|
||||
string.IsNullOrEmpty(LauncherNotice))
|
||||
_ = AutoHideAsync();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
UpdateStatus = L.I["update.offline"];
|
||||
UpdateDetail = ex.Message;
|
||||
}
|
||||
finally
|
||||
{
|
||||
UpdateBusy = false;
|
||||
_updateRunning = false;
|
||||
}
|
||||
}
|
||||
|
||||
private async Task AutoHideAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
await Task.Delay(6000);
|
||||
if (!_updateRunning && string.IsNullOrEmpty(LauncherNotice)) UpdateBarVisible = false;
|
||||
}
|
||||
catch { /* 忽略 */ }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,217 @@
|
||||
using System;
|
||||
using System.Collections.ObjectModel;
|
||||
using System.Linq;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Windows.Input;
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
using CommunityToolkit.Mvvm.Input;
|
||||
using GC.Models;
|
||||
using GC.Services;
|
||||
|
||||
namespace GC.ViewModels;
|
||||
|
||||
public sealed class LanguageOption
|
||||
{
|
||||
public string Code { get; init; } = "auto";
|
||||
public string Label { get; set; } = "";
|
||||
public override string ToString() => Label;
|
||||
}
|
||||
|
||||
public partial class SettingsViewModel : ObservableObject
|
||||
{
|
||||
private readonly AppServices _services;
|
||||
private bool _loading = true;
|
||||
|
||||
public ObservableCollection<SettingsSourceViewModel> Sources { get; } = new();
|
||||
public ObservableCollection<LanguageOption> Languages { get; } = new();
|
||||
public int[] FrameRates { get; } = { 24, 30, 60, 90, 120 };
|
||||
|
||||
[ObservableProperty] private LanguageOption? _selectedLanguage;
|
||||
[ObservableProperty] private int _selectedFps = 120;
|
||||
[ObservableProperty] private double _memoryValue = 2048;
|
||||
[ObservableProperty] private bool _memoryAuto = true;
|
||||
[ObservableProperty] private string _statusMessage = "";
|
||||
[ObservableProperty] private bool _autoUpdate = true;
|
||||
|
||||
public string UpdateSourceText => _services.Updates.Remote.DisplayName;
|
||||
public string LastCheckText
|
||||
{
|
||||
get
|
||||
{
|
||||
var value = _services.Settings.Current.LastUpdateCheck;
|
||||
if (string.IsNullOrWhiteSpace(value)) return L.I["update.never"];
|
||||
return DateTimeOffset.TryParse(value, out var time)
|
||||
? time.ToLocalTime().ToString("yyyy-MM-dd HH:mm") : value!;
|
||||
}
|
||||
}
|
||||
public string PendingText => string.IsNullOrWhiteSpace(_services.Settings.Current.PendingLauncherVersion)
|
||||
? L.I["update.none"] : _services.Settings.Current.PendingLauncherVersion!;
|
||||
|
||||
public string MemoryValueText => MemoryAuto
|
||||
? $"{L.I["set.memory.auto"]} ({_services.Memory.BudgetMb} MB)"
|
||||
: $"{(int)Math.Round(MemoryValue)} MB";
|
||||
public string UsageText => _services.Memory.UsageText;
|
||||
public string ModelRoot => _services.Paths.ModelRoot;
|
||||
public string DataRoot => _services.Paths.DataRoot;
|
||||
public string PlatformText => $"{RuntimeInformation.OSDescription} · {RuntimeInformation.RuntimeIdentifier}";
|
||||
public string VersionText => "v1.0.0";
|
||||
public string MemoryHint => L.I["set.memory.hint"];
|
||||
|
||||
public SettingsViewModel(AppServices services)
|
||||
{
|
||||
_services = services;
|
||||
L.I.LanguageChanged += OnLanguageChanged;
|
||||
Refresh();
|
||||
_loading = false;
|
||||
}
|
||||
|
||||
public void Refresh()
|
||||
{
|
||||
_loading = true;
|
||||
BuildLanguages();
|
||||
var settings = _services.Settings.Current;
|
||||
SelectedFps = settings.RenderFps;
|
||||
MemoryValue = settings.MemoryMb;
|
||||
MemoryAuto = settings.MemoryAuto;
|
||||
AutoUpdate = settings.AutoUpdateOnStartup;
|
||||
|
||||
Sources.Clear();
|
||||
foreach (var source in settings.Sources)
|
||||
Sources.Add(new SettingsSourceViewModel(source, _services, this));
|
||||
|
||||
_loading = false;
|
||||
OnPropertyChanged(nameof(UsageText));
|
||||
OnPropertyChanged(nameof(MemoryValueText));
|
||||
OnPropertyChanged(nameof(MemoryHint));
|
||||
OnPropertyChanged(nameof(ModelRoot));
|
||||
OnPropertyChanged(nameof(DataRoot));
|
||||
OnPropertyChanged(nameof(UpdateSourceText));
|
||||
OnPropertyChanged(nameof(LastCheckText));
|
||||
OnPropertyChanged(nameof(PendingText));
|
||||
}
|
||||
|
||||
partial void OnAutoUpdateChanged(bool value)
|
||||
{
|
||||
if (_loading) return;
|
||||
_services.Settings.Apply(s => s.AutoUpdateOnStartup = value);
|
||||
}
|
||||
|
||||
private void BuildLanguages()
|
||||
{
|
||||
var current = _services.Settings.Current.Language;
|
||||
Languages.Clear();
|
||||
Languages.Add(new LanguageOption { Code = "auto", Label = L.I["set.language.auto"] });
|
||||
foreach (var (code, label) in L.Supported)
|
||||
Languages.Add(new LanguageOption { Code = code, Label = label });
|
||||
SelectedLanguage = Languages.FirstOrDefault(l => l.Code == current) ?? Languages[0];
|
||||
}
|
||||
|
||||
private void OnLanguageChanged()
|
||||
{
|
||||
_loading = true;
|
||||
BuildLanguages();
|
||||
_loading = false;
|
||||
Refresh();
|
||||
}
|
||||
|
||||
partial void OnSelectedLanguageChanged(LanguageOption? value)
|
||||
{
|
||||
if (_loading || value == null) return;
|
||||
_services.Settings.Apply(s => s.Language = value.Code);
|
||||
L.I.SetLanguage(value.Code);
|
||||
}
|
||||
|
||||
partial void OnSelectedFpsChanged(int value)
|
||||
{
|
||||
if (_loading) return;
|
||||
_services.Settings.Apply(s => s.RenderFps = Math.Clamp(value, 12, 120));
|
||||
}
|
||||
|
||||
partial void OnMemoryValueChanged(double value)
|
||||
{
|
||||
if (_loading) return;
|
||||
var mb = (int)Math.Round(value);
|
||||
_services.Settings.Apply(s => s.MemoryMb = mb);
|
||||
_services.Memory.Apply(mb);
|
||||
OnPropertyChanged(nameof(MemoryValueText));
|
||||
OnPropertyChanged(nameof(UsageText));
|
||||
}
|
||||
|
||||
partial void OnMemoryAutoChanged(bool value)
|
||||
{
|
||||
if (_loading) return;
|
||||
_services.Settings.Apply(s => s.MemoryAuto = value);
|
||||
_services.Memory.ApplyAuto(value, (int)Math.Round(MemoryValue));
|
||||
OnPropertyChanged(nameof(MemoryValueText));
|
||||
OnPropertyChanged(nameof(UsageText));
|
||||
}
|
||||
|
||||
[RelayCommand]
|
||||
private void OpenModelFolder() => Shell.OpenFolder(_services.Paths.ModelRoot);
|
||||
|
||||
[RelayCommand]
|
||||
private void OpenDataFolder() => Shell.OpenFolder(_services.Paths.DataRoot);
|
||||
|
||||
[RelayCommand]
|
||||
private void ClearCache()
|
||||
{
|
||||
// 模型数据由模型自己管理;这里只回收启动器侧托管内存
|
||||
System.GC.Collect();
|
||||
System.GC.WaitForPendingFinalizers();
|
||||
_services.Memory.Refresh();
|
||||
StatusMessage = L.I["set.cacheCleared"];
|
||||
OnPropertyChanged(nameof(UsageText));
|
||||
}
|
||||
|
||||
[RelayCommand]
|
||||
private void ApplyMemory()
|
||||
{
|
||||
_services.Memory.Apply((int)Math.Round(MemoryValue));
|
||||
StatusMessage = L.I["common.applied"];
|
||||
OnPropertyChanged(nameof(UsageText));
|
||||
}
|
||||
|
||||
internal void RemoveSource(SettingsSourceViewModel source)
|
||||
{
|
||||
if (source.Model.BuiltIn) return; // 内置默认源不允许删除
|
||||
_services.Settings.Current.Sources.Remove(source.Model);
|
||||
_services.Settings.Save();
|
||||
Sources.Remove(source);
|
||||
_services.Settings.Notify();
|
||||
}
|
||||
}
|
||||
|
||||
public partial class SettingsSourceViewModel : ObservableObject
|
||||
{
|
||||
private readonly AppServices _services;
|
||||
private readonly SettingsViewModel _owner;
|
||||
|
||||
public ModelSource Model { get; }
|
||||
|
||||
public SettingsSourceViewModel(ModelSource model, AppServices services, SettingsViewModel owner)
|
||||
{
|
||||
Model = model;
|
||||
_services = services;
|
||||
_owner = owner;
|
||||
RemoveCommand = new RelayCommand(() => _owner.RemoveSource(this));
|
||||
}
|
||||
|
||||
public string Name => string.IsNullOrWhiteSpace(Model.Name) ? Model.Id : Model.Name;
|
||||
public string UrlText => string.IsNullOrWhiteSpace(Model.Url) ? L.I["dl.noSource"] : Model.Url;
|
||||
/// <summary>内置默认源不可删除。</summary>
|
||||
public bool CanRemove => !Model.BuiltIn;
|
||||
|
||||
public bool Enabled
|
||||
{
|
||||
get => Model.Enabled;
|
||||
set
|
||||
{
|
||||
if (Model.Enabled == value) return;
|
||||
Model.Enabled = value;
|
||||
_services.Settings.Save();
|
||||
OnPropertyChanged();
|
||||
}
|
||||
}
|
||||
|
||||
public ICommand RemoveCommand { get; }
|
||||
}
|
||||
Reference in new issue
Block a user