fix(desktop): 修正解密、配置和任务生命周期问题

修复 KGG/KGM 识别、密钥解码及输出文件保护;改进配置无损保存、登录会话安全和取消处理。统一新增 C# 代码风格,补齐发布许可声明及文档,并增加针对性回归测试。
This commit is contained in:
real-zony committed 2026-11-09 18:13:55 -08:00
1 parent 7379571e2d
commit 8912a79168
64 files changed
+2787 -1182

No files matched your search

@@ -25,7 +25,7 @@ public partial class AlbumDownloadViewModel : ViewModelBase
private CancellationTokenSource? _downloadCts;
private readonly Dictionary<string, AlbumFileViewModel> _musicFileMap = new();
private List<MusicInfo> _scannedMusicInfos = new();
private readonly List<MusicInfo> _scannedMusicInfos = new();
[ObservableProperty]
private string? _selectedFolderPath;
@@ -75,6 +75,7 @@ public partial class AlbumDownloadViewModel : ViewModelBase
public string AlbumParallel => _localization?["Album_Parallel"] ?? "Parallel:";
public string AlbumStartDownload => _localization?["Album_StartDownload"] ?? "Start Download";
public string AlbumStopDownload => _localization?["Album_StopDownload"] ?? "Stop Download";
/// <summary>扫描进度提示。</summary>
public string AlbumScanning => _localization?["Lyrics_Status_Scanning"] ?? "Scanning files...";
public string CommonTotal => _localization?["Common_Total"] ?? "Total:";
public string CommonFiles => _localization?["Common_Files"] ?? "files";
@@ -142,23 +143,23 @@ public partial class AlbumDownloadViewModel : ViewModelBase
}
[RelayCommand(CanExecute = nameof(CanSelectFolder))]
private async Task SelectFolderAsync()
private async Task SelectFolderAsync(CancellationToken cancellationToken = default)
{
var folder = await _dialogService.ShowFolderPickerAsync(
_localization?["Album_SelectFolder"] ?? "Select Music Folder");
cancellationToken.ThrowIfCancellationRequested();
if (string.IsNullOrEmpty(folder)) return;
SelectedFolderPath = folder;
await ScanFilesAsync();
await ScanFilesAsync(cancellationToken);
}
private bool CanSelectFolder => !IsScanning && !IsDownloading;
/// <summary>
/// Tag-read the folder the same way the lyrics page does: identical row set, so the user sees
/// the same songs whichever feature they open first.
/// 扫描文件并读取音乐标签。
/// </summary>
private async Task ScanFilesAsync()
private async Task ScanFilesAsync(CancellationToken cancellationToken = default)
{
if (string.IsNullOrEmpty(SelectedFolderPath)) return;
@@ -176,8 +177,9 @@ public partial class AlbumDownloadViewModel : ViewModelBase
try
{
var files = (await _fileScanner.ScanMusicFilesAsync(SelectedFolderPath, _options.SupportFileExtensions))
.ToList();
var files = (await Task.Run(
() => _fileScanner.ScanMusicFilesAsync(SelectedFolderPath, _options.SupportFileExtensions),
cancellationToken)).ToList();
if (files.Count == 0)
{
@@ -193,7 +195,7 @@ public partial class AlbumDownloadViewModel : ViewModelBase
var scanTasks = files.Select(file =>
warpTask.RunAsync(async () =>
{
var musicInfo = await _tagLoader.LoadTagAsync(file);
var musicInfo = await Task.Run(() => _tagLoader.LoadTagAsync(file).AsTask(), cancellationToken);
await Dispatcher.UIThread.InvokeAsync(() =>
{
@@ -215,12 +217,16 @@ public partial class AlbumDownloadViewModel : ViewModelBase
ScanProgressCount++;
ScanProgressPercentage = ScanProgressCount * 100.0 / ScanTotalCount;
});
}));
}, cancellationToken));
await Task.WhenAll(scanTasks);
TotalCount = MusicFiles.Count;
}
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
{
// 用户取消扫描。
}
catch (Exception ex)
{
await _dialogService.ShowMessageAsync(
@@ -235,7 +241,7 @@ public partial class AlbumDownloadViewModel : ViewModelBase
}
[RelayCommand(CanExecute = nameof(CanStartDownload))]
private async Task StartDownloadAsync()
private async Task StartDownloadAsync(CancellationToken cancellationToken = default)
{
if (_scannedMusicInfos.Count == 0) return;
@@ -252,7 +258,7 @@ public partial class AlbumDownloadViewModel : ViewModelBase
vm.StatusMessage = _localization?["Status_Pending"] ?? "Pending";
}
_downloadCts = new CancellationTokenSource();
_downloadCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
try
{
@@ -283,9 +289,15 @@ public partial class AlbumDownloadViewModel : ViewModelBase
},
_downloadCts.Token);
}
catch (OperationCanceledException)
catch (OperationCanceledException) when (_downloadCts.IsCancellationRequested)
{
// User cancelled.
// 用户取消下载。
}
catch (Exception ex)
{
await _dialogService.ShowMessageAsync(
_localization?["Common_Error"] ?? "Error",
ex.Message);
}
finally
{
@@ -302,6 +314,9 @@ public partial class AlbumDownloadViewModel : ViewModelBase
}
}
/// <summary>
/// 单个音乐文件的封面下载状态。
/// </summary>
public partial class AlbumFileViewModel : ObservableObject
{
[ObservableProperty]
@@ -10,6 +10,9 @@ using ZonyLrcTools.Desktop.Services;
namespace ZonyLrcTools.Desktop.ViewModels;
/// <summary>
/// 音乐文件解密页面。
/// </summary>
public partial class DecryptViewModel : ViewModelBase
{
private const string KggExtension = ".kgg";
@@ -23,6 +26,13 @@ public partial class DecryptViewModel : ViewModelBase
private CancellationTokenSource? _decryptCts;
private bool _isInitialized;
[ObservableProperty]
[NotifyCanExecuteChangedFor(nameof(StartDecryptCommand))]
[NotifyCanExecuteChangedFor(nameof(SelectFilesCommand))]
[NotifyCanExecuteChangedFor(nameof(SpecifyDatabaseCommand))]
[NotifyPropertyChangedFor(nameof(CanStartDecrypt))]
private bool _isInitializing;
[ObservableProperty]
private int _parallelCount = 2;
@@ -42,13 +52,13 @@ public partial class DecryptViewModel : ViewModelBase
[NotifyCanExecuteChangedFor(nameof(StartDecryptCommand))]
[NotifyCanExecuteChangedFor(nameof(SelectFilesCommand))]
[NotifyCanExecuteChangedFor(nameof(ClearFilesCommand))]
[NotifyCanExecuteChangedFor(nameof(SpecifyDatabaseCommand))]
[NotifyPropertyChangedFor(nameof(CanStartDecrypt))]
[NotifyPropertyChangedFor(nameof(CanClear))]
private bool _isDecrypting;
/// <summary>
/// True when the KuGou key database could not be read. kgg files cannot be decrypted without
/// it, so the page says so up front instead of letting every row fail with a wall of text.
/// 是否可以读取酷狗解密密钥数据库。
/// </summary>
[ObservableProperty]
[NotifyPropertyChangedFor(nameof(ShowDatabaseWarning))]
@@ -57,54 +67,78 @@ public partial class DecryptViewModel : ViewModelBase
[ObservableProperty]
private string _kugouDatabaseStatus = string.Empty;
// Localized strings
// 界面文案。
/// <summary>页面标题。</summary>
public string DecryptTitle => _localization?["Decrypt_Title"] ?? "Music Decryption";
/// <summary>页面说明。</summary>
public string DecryptDescription => _localization?["Decrypt_Description"] ?? "Convert encrypted music files (ncm / qmc / kgm / kgg / kwm) into playable formats";
/// <summary>文件选择提示。</summary>
public string DecryptSelectFiles => _localization?["Decrypt_SelectFiles"] ?? "Select encrypted music files...";
/// <summary>添加文件按钮文案。</summary>
public string DecryptBrowse => _localization?["Decrypt_Browse"] ?? "Add Files...";
/// <summary>并行任务数标签。</summary>
public string DecryptParallel => _localization?["Decrypt_Parallel"] ?? "Parallel:";
/// <summary>开始解密按钮文案。</summary>
public string DecryptStart => _localization?["Decrypt_Start"] ?? "Start Decrypt";
/// <summary>停止按钮文案。</summary>
public string DecryptStop => _localization?["Decrypt_Stop"] ?? "Stop";
/// <summary>文件列表为空时的提示。</summary>
public string DecryptEmptyState => _localization?["Decrypt_EmptyState"] ?? "No files yet, add files to start decrypting";
/// <summary>清空按钮文案。</summary>
public string DecryptClear => _localization?["Decrypt_Clear"] ?? "Clear";
/// <summary>文件列表标签。</summary>
public string DecryptFilesLabel => _localization?["Decrypt_FilesLabel"] ?? "Files";
/// <summary>选择数据库按钮文案。</summary>
public string DecryptSpecifyDatabase => _localization?["Decrypt_SpecifyDatabase"] ?? "Locate KGMusicV3.db...";
/// <summary>数据库缺失状态文案。</summary>
public string DecryptStatusMissingDb => _localization?["Decrypt_StatusMissingDb"] ?? "KuGou database missing";
/// <summary>查看详情按钮文案。</summary>
public string DecryptViewDetail => _localization?["Decrypt_ViewDetail"] ?? "Details";
/// <summary>失败详情窗口标题。</summary>
public string DecryptFailureTitle => _localization?["Decrypt_FailureTitle"] ?? "Decryption failure";
/// <summary>
/// Explanation shown in the warning strip. Kept as one sentence because the real condition is
/// simple: kgg needs the KuGou database, and that database only holds keys for songs KuGou
/// itself downloaded on this machine.
/// 酷狗数据库缺失时的提示。
/// </summary>
public string DecryptKugouRequirement => _localization?["Decrypt_KugouMissing"]
?? "kgg decryption needs the KuGou database KGMusicV3.db (the key is only written when KuGou downloaded that song)";
/// <summary>是否显示数据库缺失提示。</summary>
public bool ShowDatabaseWarning => !IsKugouDatabaseAvailable;
/// <summary>
/// Read-only summary shown in the picker text box: "3 files selected" rather than a path,
/// because this page takes a list, not a single location.
/// 已选文件数量。
/// </summary>
public string SelectionSummary => Files.Count == 0
? string.Empty
: $"{Files.Count} {CommonFiles}";
/// <summary>总数标签。</summary>
public string CommonTotal => _localization?["Common_Total"] ?? "Total:";
/// <summary>文件数量单位。</summary>
public string CommonFiles => _localization?["Common_Files"] ?? "files";
/// <summary>成功数量标签。</summary>
public string CommonSuccess => _localization?["Common_Success"] ?? "Success:";
/// <summary>失败数量标签。</summary>
public string CommonFailed => _localization?["Common_Failed"] ?? "Failed:";
/// <summary>文件名列标题。</summary>
public string ColumnFileName => _localization?["Column_FileName"] ?? "File Name";
/// <summary>输出路径列标题。</summary>
public string ColumnOutputPath => _localization?["Column_OutputPath"] ?? "Output";
/// <summary>状态列标题。</summary>
public string ColumnStatus => _localization?["Column_Status"] ?? "Status";
// 全部行都被 blocked 时按钮不该亮着,否则点下去只会空转一次。
public bool CanStartDecrypt => !IsDecrypting && Files.Any(f => !f.IsBlocked);
/// <summary>是否存在可以开始解密的文件。</summary>
public bool CanStartDecrypt => !IsDecrypting && !IsInitializing && Files.Any(f => !f.IsBlocked);
/// <summary>文件列表是否为空。</summary>
public bool HasNoFiles => Files.Count == 0;
/// <summary>待解密文件列表。</summary>
public ObservableCollection<DecryptFileViewModel> Files { get; } = new();
/// <summary>
/// 创建音乐解密页面。
/// </summary>
public DecryptViewModel(
IMusicDecryptor musicDecryptor,
IDialogService dialogService,
@@ -135,11 +169,12 @@ public partial class DecryptViewModel : ViewModelBase
}
/// <summary>
/// Restores the manually chosen database path (if any) and probes it once so the page can show
/// the warning strip and mark kgg rows before the user presses start.
/// 恢复已保存的数据库路径并刷新文件状态。
/// </summary>
public override async Task OnActivatedAsync()
{
if (IsDecrypting || IsInitializing) return;
if (!_isInitialized)
{
await InitializeAsync();
@@ -149,26 +184,47 @@ public partial class DecryptViewModel : ViewModelBase
RefreshDatabaseStatus();
}
public async Task InitializeAsync()
/// <summary>
/// 初始化酷狗数据库路径。
/// </summary>
public async Task InitializeAsync(CancellationToken cancellationToken = default)
{
_isInitialized = true;
if (_kugouDatabaseStore != null && _kugouKeyProvider != null)
{
var stored = await _kugouDatabaseStore.LoadAsync().ConfigureAwait(true);
if (!string.IsNullOrWhiteSpace(stored))
{
_kugouKeyProvider.SetDatabasePath(stored);
}
}
if (IsInitializing) return;
RefreshDatabaseStatus();
IsInitializing = true;
try
{
if (_kugouDatabaseStore != null && _kugouKeyProvider != null)
{
var stored = await _kugouDatabaseStore.LoadAsync(cancellationToken);
if (!string.IsNullOrWhiteSpace(stored))
{
_kugouKeyProvider.SetDatabasePath(stored);
}
}
RefreshDatabaseStatus();
_isInitialized = true;
}
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
{
// 用户取消初始化,下次进入页面时重试。
}
catch (Exception ex)
{
await _dialogService.ShowMessageAsync(_localization?["Common_Error"] ?? "Error", ex.Message);
}
finally
{
IsInitializing = false;
}
}
private void RefreshDatabaseStatus()
{
if (_kugouKeyProvider == null)
{
// No provider at all: keep the page usable, kgg will report the failure itself.
// 未注册密钥提供者时,由解密器报告具体错误。
IsKugouDatabaseAvailable = true;
KugouDatabaseStatus = string.Empty;
return;
@@ -178,7 +234,7 @@ public partial class DecryptViewModel : ViewModelBase
IsKugouDatabaseAvailable = info.IsAvailable;
KugouDatabaseStatus = info.Message;
// Rows added while the database was missing are stale the moment it becomes readable.
// 数据库可用后解除未处理文件的阻止状态。
foreach (var file in Files)
{
if (!IsKggFile(file.FilePath)) continue;
@@ -241,24 +297,35 @@ public partial class DecryptViewModel : ViewModelBase
OnPropertyChanged(nameof(ColumnFileName));
OnPropertyChanged(nameof(ColumnOutputPath));
OnPropertyChanged(nameof(ColumnStatus));
foreach (var file in Files)
{
file.ViewDetailLabel = DecryptViewDetail;
file.StatusMessage = file.IsBlocked
? DecryptStatusMissingDb
: file.IsProcessed
? file.IsSuccessful
? _localization?["Status_Success"] ?? "Success"
: _localization?["Status_Failed"] ?? "Failed"
: _localization?["Status_Pending"] ?? "Pending";
}
}
[RelayCommand(CanExecute = nameof(CanSelectFiles))]
private async Task SelectFilesAsync()
private async Task SelectFilesAsync(CancellationToken cancellationToken = default)
{
var picked = await _dialogService.ShowFilesPickerAsync(
DecryptSelectFiles,
new[] { ".ncm", ".qmc0", ".qmc2", ".qmc3", ".qmcflac", ".qmcogg", ".mflac", ".mgg", ".kgm", ".kgma", ".kgg", ".kwm" });
[".ncm", ".qmc0", ".qmc2", ".qmc3", ".qmcflac", ".qmcogg", ".mflac", ".mgg", ".kgm", ".kgma", ".kgg", ".kwm"],
cancellationToken);
if (picked.Count == 0) return;
// Probe once for the whole batch instead of per file: the database is either readable or
// it is not, and re-reading it for every dropped file would be pointless I/O.
// 同一批文件只检查一次数据库。
RefreshDatabaseStatus();
foreach (var path in picked)
{
// The picker can hand back the same file twice; keys must stay unique.
// 避免重复添加同一文件。
if (Files.Any(f => string.Equals(f.FilePath, path, StringComparison.OrdinalIgnoreCase)))
{
continue;
@@ -277,9 +344,7 @@ public partial class DecryptViewModel : ViewModelBase
ViewDetailLabel = DecryptViewDetail
};
// 详情命令挂在行自己身上,比在模板里通过 $parent 硬转成父 VM 再取命令更稳,
// 也不会因为 DataTemplate 的上下文变化而悄悄失效。
row.ShowDetailCommand = new AsyncRelayCommand(() => ShowDetailAsync(row));
row.ShowDetailCommand = new AsyncRelayCommand(token => ShowDetailAsync(row, token));
Files.Add(row);
}
@@ -287,14 +352,15 @@ public partial class DecryptViewModel : ViewModelBase
OnPropertyChanged(nameof(CanStartDecrypt));
}
private bool CanSelectFiles => !IsDecrypting;
private bool CanSelectFiles => !IsDecrypting && !IsInitializing;
[RelayCommand(CanExecute = nameof(CanSelectFiles))]
private async Task SpecifyDatabaseAsync()
private async Task SpecifyDatabaseAsync(CancellationToken cancellationToken = default)
{
var picked = await _dialogService.ShowFilePickerAsync(
DecryptSpecifyDatabase,
new[] { ".db" });
cancellationToken.ThrowIfCancellationRequested();
if (string.IsNullOrWhiteSpace(picked))
{
@@ -306,16 +372,15 @@ public partial class DecryptViewModel : ViewModelBase
if (_kugouDatabaseStore != null)
{
await _kugouDatabaseStore.SaveAsync(picked).ConfigureAwait(true);
await _kugouDatabaseStore.SaveAsync(picked, cancellationToken);
}
}
[RelayCommand(CanExecute = nameof(CanStartDecrypt))]
private async Task StartDecryptAsync()
private async Task StartDecryptAsync(CancellationToken cancellationToken = default)
{
if (Files.Count == 0) return;
// A kgg row without a readable database cannot decrypt, so it is left out of the run
// entirely instead of failing one file at a time with the same message.
// 缺少密钥数据库的文件不加入本次任务。
var runnable = Files.Where(f => !f.IsBlocked).ToList();
IsDecrypting = true;
@@ -329,6 +394,7 @@ public partial class DecryptViewModel : ViewModelBase
file.IsProcessed = false;
file.IsSuccessful = false;
file.OutputPath = null;
file.ErrorDetail = null;
if (!file.IsBlocked)
{
@@ -342,7 +408,7 @@ public partial class DecryptViewModel : ViewModelBase
return;
}
_decryptCts = new CancellationTokenSource();
_decryptCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
var token = _decryptCts.Token;
try
@@ -358,7 +424,11 @@ public partial class DecryptViewModel : ViewModelBase
DecryptionResult result;
try
{
result = await _musicDecryptor.ConvertMusicAsync(file.FilePath, token);
result = await Task.Run(() => _musicDecryptor.ConvertMusicAsync(file.FilePath, token), token);
}
catch (OperationCanceledException) when (token.IsCancellationRequested)
{
throw;
}
catch (Exception ex)
{
@@ -379,8 +449,7 @@ public partial class DecryptViewModel : ViewModelBase
}
else
{
// The status column shows a short label; the full reason (a missing
// database dumps several hundred characters) lives in the row detail.
// 状态列只显示摘要,完整错误在详情对话框展示。
file.ErrorDetail = result.ErrorMessage;
file.StatusMessage = _localization?["Status_Failed"] ?? "Failed";
FailedCount++;
@@ -389,13 +458,13 @@ public partial class DecryptViewModel : ViewModelBase
var done = CompletedCount + FailedCount;
ProgressPercentage = done * 100.0 / TotalCount;
});
}));
}, token));
await Task.WhenAll(tasks);
}
catch (OperationCanceledException)
catch (OperationCanceledException) when (token.IsCancellationRequested)
{
// User cancelled; rows that never ran stay "Pending".
// 用户取消时,未完成的文件保持待处理状态。
}
finally
{
@@ -406,11 +475,11 @@ public partial class DecryptViewModel : ViewModelBase
}
/// <summary>
/// Shows the untruncated reason a row failed. Without this the only place the explanatory text
/// exists is a tooltip, which is unreadable for the long "database not found" message.
/// 显示文件解密失败的完整原因。
/// </summary>
private async Task ShowDetailAsync(DecryptFileViewModel? file)
private async Task ShowDetailAsync(DecryptFileViewModel? file, CancellationToken cancellationToken = default)
{
cancellationToken.ThrowIfCancellationRequested();
if (file == null || string.IsNullOrWhiteSpace(file.ErrorDetail))
{
return;
@@ -436,47 +505,57 @@ public partial class DecryptViewModel : ViewModelBase
OnPropertyChanged(nameof(CanStartDecrypt));
}
/// <summary>
/// 是否可以清空文件列表。
/// </summary>
private bool CanClear => !IsDecrypting && Files.Count > 0;
}
/// <summary>
/// 单个文件的解密状态。
/// </summary>
public partial class DecryptFileViewModel : ObservableObject
{
/// <summary>输入文件路径。</summary>
[ObservableProperty]
private string _filePath = string.Empty;
/// <summary>输入文件名。</summary>
[ObservableProperty]
private string _fileName = string.Empty;
/// <summary>解密后的输出路径。</summary>
[ObservableProperty]
private string? _outputPath;
/// <summary>是否已完成处理。</summary>
[ObservableProperty]
private bool _isProcessed;
/// <summary>是否解密成功。</summary>
[ObservableProperty]
private bool _isSuccessful;
/// <summary>
/// Short label for the status column. Long explanations belong in <see cref="ErrorDetail"/>,
/// which the detail dialog shows in full.
/// 状态列摘要,完整原因保存在 <see cref="ErrorDetail"/>。
/// </summary>
[ObservableProperty]
[NotifyPropertyChangedFor(nameof(HasErrorDetail))]
private string? _statusMessage;
/// <summary>解密失败的完整原因。</summary>
[ObservableProperty]
[NotifyPropertyChangedFor(nameof(HasErrorDetail))]
private string? _errorDetail;
/// <summary>
/// Set when the row cannot run at all (kgg without a readable KuGou database). Blocked rows are
/// tinted so the reason is visible before pressing start.
/// 是否因缺少酷狗数据库而无法开始解密。
/// </summary>
[ObservableProperty]
private bool _isBlocked;
/// <summary>
/// 详情按钮上的文案。挂在行上,模板就不必再通过 $parent 反向取父 ViewModel。
/// 详情按钮文案。
/// </summary>
[ObservableProperty]
private string? _viewDetailLabel;
@@ -486,5 +565,8 @@ public partial class DecryptFileViewModel : ObservableObject
/// </summary>
public IAsyncRelayCommand? ShowDetailCommand { get; set; }
/// <summary>
/// 是否存在可查看的错误详情。
/// </summary>
public bool HasErrorDetail => !string.IsNullOrWhiteSpace(ErrorDetail);
}
@@ -7,14 +7,16 @@ using ZonyLrcTools.Desktop.Services;
namespace ZonyLrcTools.Desktop.ViewModels;
/// <summary>
/// The landing page. Its only job is to point people at the three things this app actually does,
/// so every quick-action button navigates for real instead of sitting there looking clickable.
/// 首页与功能入口。
/// </summary>
public partial class HomeViewModel : ViewModelBase
{
private readonly INavigationService _navigation;
private readonly IUILocalizationService _localization;
/// <summary>
/// 创建首页。
/// </summary>
public HomeViewModel(INavigationService navigation, IUILocalizationService localization)
{
_navigation = navigation;
@@ -26,22 +28,37 @@ public partial class HomeViewModel : ViewModelBase
[ObservableProperty]
private string _version;
/// <summary>欢迎语。</summary>
public string WelcomeMessage => _localization["Home_Welcome"];
/// <summary>应用说明。</summary>
public string Description => _localization["Home_Description"];
/// <summary>快捷操作标题。</summary>
public string QuickActionsTitle => _localization["Home_QuickActions"];
/// <summary>功能特性标题。</summary>
public string FeaturesTitle => _localization["Home_Features"];
/// <summary>支持格式说明。</summary>
public string FeatureFormats => _localization["Home_FeatureFormats"];
/// <summary>并行下载说明。</summary>
public string FeatureParallel => _localization["Home_FeatureParallel"];
/// <summary>编码支持说明。</summary>
public string FeatureEncodings => _localization["Home_FeatureEncodings"];
/// <summary>跨平台支持说明。</summary>
public string FeatureCrossPlatform => _localization["Home_FeatureCrossPlatform"];
/// <summary>版本标签。</summary>
public string VersionLabel => _localization["Home_Version"];
// Card copy: title + one-line explanation, both localized.
// 功能入口文案。
/// <summary>歌词下载入口标题。</summary>
public string LyricsCardTitle => _localization["Home_DownloadLyrics"];
/// <summary>歌词下载入口说明。</summary>
public string LyricsCardDescription => _localization["Home_DownloadLyricsHint"];
/// <summary>封面下载入口标题。</summary>
public string AlbumCardTitle => _localization["Home_DownloadAlbumCover"];
/// <summary>封面下载入口说明。</summary>
public string AlbumCardDescription => _localization["Home_DownloadAlbumCoverHint"];
/// <summary>音乐解密入口标题。</summary>
public string DecryptCardTitle => _localization["Home_Decrypt"];
/// <summary>音乐解密入口说明。</summary>
public string DecryptCardDescription => _localization["Home_DecryptHint"];
[RelayCommand]
@@ -79,7 +96,7 @@ public partial class HomeViewModel : ViewModelBase
if (!string.IsNullOrWhiteSpace(informational))
{
// Strip the "+<commit sha>" suffix that SourceLink appends.
// 隐藏 SourceLink 添加的提交标识。
var plusIndex = informational.IndexOf('+');
return plusIndex > 0 ? informational[..plusIndex] : informational;
}
@@ -17,17 +17,17 @@ using ZonyLrcTools.Desktop.Services;
namespace ZonyLrcTools.Desktop.ViewModels;
/// <summary>
/// Which source the lyrics page reads its song list from.
/// 歌词列表的数据来源。
/// </summary>
public enum LyricsScannerKind
{
/// <summary>Scan a local folder for audio files.</summary>
/// <summary>扫描本地音乐文件夹。</summary>
Local = 0,
/// <summary>Read a CSV file containing "song,artist" rows.</summary>
/// <summary>读取歌曲与歌手信息的 CSV 文件。</summary>
Csv = 1,
/// <summary>Pull a NetEase Cloud Music playlist by id.</summary>
/// <summary>读取网易云歌单。</summary>
NetEase = 2
}
@@ -47,9 +47,8 @@ public partial class LyricsDownloadViewModel : ViewModelBase
private readonly IUILocalizationService? _localization;
private CancellationTokenSource? _downloadCts;
private CancellationTokenSource? _scanCts;
private readonly Dictionary<string, MusicFileViewModel> _musicFileMap = new();
private List<MusicInfo> _scannedMusicInfos = new();
private readonly List<MusicInfo> _scannedMusicInfos = new();
[ObservableProperty]
[NotifyCanExecuteChangedFor(nameof(StartScanCommand))]
@@ -73,6 +72,7 @@ public partial class LyricsDownloadViewModel : ViewModelBase
[NotifyPropertyChangedFor(nameof(IsLocalScanner))]
[NotifyPropertyChangedFor(nameof(IsCsvScanner))]
[NotifyPropertyChangedFor(nameof(IsNetEaseScanner))]
[NotifyCanExecuteChangedFor(nameof(StartScanCommand))]
[NotifyPropertyChangedFor(nameof(CanScan))]
private int _selectedScannerIndex;
@@ -93,6 +93,14 @@ public partial class LyricsDownloadViewModel : ViewModelBase
[ObservableProperty]
[NotifyCanExecuteChangedFor(nameof(StartDownloadCommand))]
[NotifyCanExecuteChangedFor(nameof(SelectFolderCommand))]
[NotifyCanExecuteChangedFor(nameof(SelectCsvFileCommand))]
[NotifyCanExecuteChangedFor(nameof(SelectOutputFolderCommand))]
[NotifyCanExecuteChangedFor(nameof(StartScanCommand))]
[NotifyCanExecuteChangedFor(nameof(SignInNetEaseCommand))]
[NotifyCanExecuteChangedFor(nameof(SignOutNetEaseCommand))]
[NotifyPropertyChangedFor(nameof(CanScan))]
[NotifyPropertyChangedFor(nameof(CanEditInputs))]
[NotifyPropertyChangedFor(nameof(CanStartDownload))]
private bool _isDownloading;
@@ -102,6 +110,9 @@ public partial class LyricsDownloadViewModel : ViewModelBase
[NotifyCanExecuteChangedFor(nameof(SelectCsvFileCommand))]
[NotifyCanExecuteChangedFor(nameof(SelectOutputFolderCommand))]
[NotifyCanExecuteChangedFor(nameof(StartScanCommand))]
[NotifyCanExecuteChangedFor(nameof(SignInNetEaseCommand))]
[NotifyCanExecuteChangedFor(nameof(SignOutNetEaseCommand))]
[NotifyPropertyChangedFor(nameof(CanEditInputs))]
[NotifyPropertyChangedFor(nameof(CanStartDownload))]
[NotifyPropertyChangedFor(nameof(CanScan))]
private bool _isScanning;
@@ -121,10 +132,23 @@ public partial class LyricsDownloadViewModel : ViewModelBase
[NotifyCanExecuteChangedFor(nameof(SignInNetEaseCommand))]
private bool _isNetEaseLoggedIn;
[ObservableProperty]
[NotifyCanExecuteChangedFor(nameof(StartDownloadCommand))]
[NotifyCanExecuteChangedFor(nameof(SelectFolderCommand))]
[NotifyCanExecuteChangedFor(nameof(SelectCsvFileCommand))]
[NotifyCanExecuteChangedFor(nameof(SelectOutputFolderCommand))]
[NotifyCanExecuteChangedFor(nameof(StartScanCommand))]
[NotifyCanExecuteChangedFor(nameof(SignInNetEaseCommand))]
[NotifyCanExecuteChangedFor(nameof(SignOutNetEaseCommand))]
[NotifyPropertyChangedFor(nameof(CanStartDownload))]
[NotifyPropertyChangedFor(nameof(CanScan))]
[NotifyPropertyChangedFor(nameof(CanEditInputs))]
private bool _isAccountBusy;
[ObservableProperty]
private string? _currentProcessingFile;
// Localized strings
// 界面文案。
public string LyricsTitle => _localization?["Lyrics_Title"] ?? "Lyrics Download";
public string LyricsDescription => _localization?["Lyrics_Description"] ?? "Batch download lyrics for your music files";
public string LyricsFolderLabel => _localization?["Lyrics_FolderLabel"] ?? "Music Folder";
@@ -134,32 +158,45 @@ public partial class LyricsDownloadViewModel : ViewModelBase
public string LyricsStartDownload => _localization?["Lyrics_StartDownload"] ?? "Start Download";
public string LyricsStopDownload => _localization?["Lyrics_StopDownload"] ?? "Stop Download";
public string LyricsScanning => _localization?["Lyrics_Status_Scanning"] ?? "Scanning files...";
/// <summary>数据来源标签。</summary>
public string LyricsScannerLabel => _localization?["Lyrics_Scanner"] ?? "Source";
/// <summary>扫描按钮文案。</summary>
public string LyricsScan => _localization?["Lyrics_Scan"] ?? "Scan";
/// <summary>CSV 文件标签。</summary>
public string LyricsCsvLabel => _localization?["Lyrics_CsvLabel"] ?? "CSV File";
/// <summary>CSV 文件选择提示。</summary>
public string LyricsCsvSelect => _localization?["Lyrics_CsvSelect"] ?? "Select a CSV file...";
/// <summary>CSV 文件选择按钮文案。</summary>
public string LyricsCsvBrowse => _localization?["Lyrics_CsvBrowse"] ?? "Choose...";
/// <summary>网易云歌单编号标签。</summary>
public string LyricsSongListLabel => _localization?["Lyrics_SongListLabel"] ?? "Playlist ID";
/// <summary>网易云歌单编号输入提示。</summary>
public string LyricsSongListWatermark => _localization?["Lyrics_SongListWatermark"] ?? "e.g. 7224428149 (separate multiple ids with ;)";
/// <summary>输出目录标签。</summary>
public string LyricsOutputLabel => _localization?["Lyrics_OutputLabel"] ?? "Save To";
/// <summary>输出目录选择提示。</summary>
public string LyricsOutputSelect => _localization?["Lyrics_OutputSelect"] ?? "Where the .lrc files should be written";
/// <summary>输出目录选择按钮文案。</summary>
public string LyricsOutputBrowse => _localization?["Lyrics_OutputBrowse"] ?? "Choose...";
/// <summary>退出登录按钮文案。</summary>
public string NetEaseSignOut => _localization?["NetEase_SignOut"] ?? "Sign out";
/// <summary>退出登录提示。</summary>
public string NetEaseSignOutHint => _localization?["NetEase_SignOutHint"] ??
"Forget the saved session and scan the QR code again next time.";
/// <summary>登录按钮文案。</summary>
public string NetEaseSignIn => _localization?["NetEase_SignIn"] ?? "Sign in…";
/// <summary>登录按钮提示。</summary>
public string NetEaseSignInHint => _localization?["NetEase_SignInHint"] ??
"Scan a QR code now instead of waiting until the next scan.";
/// <summary>
/// Human readable login state. The sign in / sign out buttons alone were not enough: a user
/// who had never signed in could not tell whether a session was stored, and a user who had
/// signed in had no way to notice the cookie was restored from disk.
/// 当前网易云登录状态。
/// </summary>
public string NetEaseAccountStatus => IsNetEaseLoggedIn
? _localization?["NetEase_LoggedIn"] ?? "Signed in. Scanning a playlist reuses this session."
: _localization?["NetEase_NotLoggedIn"] ?? "Not signed in. Scanning a playlist will show a QR code.";
/// <summary>账号状态标签。</summary>
public string NetEaseAccountLabel => _localization?["NetEase_AccountLabel"] ?? "Account";
public string CommonTotal => _localization?["Common_Total"] ?? "Total:";
public string CommonFiles => _localization?["Common_Files"] ?? "files";
@@ -171,7 +208,7 @@ public partial class LyricsDownloadViewModel : ViewModelBase
public string ColumnStatus => _localization?["Column_Status"] ?? "Status";
/// <summary>
/// Scanner display names, indexed the same way as <see cref="SelectedScannerIndex"/>.
/// 按 <see cref="SelectedScannerIndex"/> 排列的数据来源名称。
/// </summary>
public string[] ScannerNames =>
[
@@ -184,7 +221,7 @@ public partial class LyricsDownloadViewModel : ViewModelBase
public bool IsCsvScanner => SelectedScannerIndex == (int)LyricsScannerKind.Csv;
public bool IsNetEaseScanner => SelectedScannerIndex == (int)LyricsScannerKind.NetEase;
public bool CanStartDownload => !IsDownloading && !IsScanning && MusicFiles.Count > 0;
public bool CanStartDownload => CanEditInputs && MusicFiles.Count > 0;
public bool HasNoFiles => MusicFiles.Count == 0;
@@ -222,8 +259,7 @@ public partial class LyricsDownloadViewModel : ViewModelBase
_localization.LanguageChanged += OnLanguageChanged;
}
// The scanner is a singleton, so a session restored by an earlier page visit is already
// in memory; reflect it right away instead of waiting for the first activation.
// 扫描器为单例,页面直接复用已恢复的登录状态。
IsNetEaseLoggedIn = _neteaseMusicScanner.IsLoggedIn;
MusicFiles.CollectionChanged += (_, _) =>
@@ -273,75 +309,93 @@ public partial class LyricsDownloadViewModel : ViewModelBase
OnPropertyChanged(nameof(ScannerNames));
}
// ---------------------------------------------------------------- selection commands
partial void OnSelectedScannerIndexChanged(int value) => InvalidateScan();
partial void OnSelectedCsvFilePathChanged(string? value) => InvalidateScan();
partial void OnSongListIdsChanged(string? value) => InvalidateScan();
partial void OnOutputDirectoryChanged(string? value) => InvalidateScan();
private void InvalidateScan()
{
if (CanEditInputs)
{
ResetCollections();
}
}
[RelayCommand(CanExecute = nameof(CanSelectFolder))]
private async Task SelectFolderAsync()
private async Task SelectFolderAsync(CancellationToken cancellationToken = default)
{
var folder = await _dialogService.ShowFolderPickerAsync(
_localization?["Lyrics_SelectFolder"] ?? "Select Music Folder");
cancellationToken.ThrowIfCancellationRequested();
if (string.IsNullOrEmpty(folder)) return;
SelectedFolderPath = folder;
await ScanFilesAsync();
await ScanFilesAsync(cancellationToken);
}
private bool CanSelectFolder => !IsScanning && !IsDownloading;
/// <summary>
/// 是否可以修改任务来源与输出目录。
/// </summary>
public bool CanEditInputs => !IsScanning && !IsDownloading && !IsAccountBusy;
private bool CanSelectFolder => CanEditInputs;
[RelayCommand(CanExecute = nameof(CanSelectFolder))]
private async Task SelectCsvFileAsync()
private async Task SelectCsvFileAsync(CancellationToken cancellationToken = default)
{
var file = await _dialogService.ShowFilePickerAsync(
_localization?["Lyrics_CsvSelect"] ?? "Select a CSV file", [".csv"]);
cancellationToken.ThrowIfCancellationRequested();
if (string.IsNullOrEmpty(file)) return;
SelectedCsvFilePath = file;
}
[RelayCommand(CanExecute = nameof(CanSelectFolder))]
private async Task SelectOutputFolderAsync()
private async Task SelectOutputFolderAsync(CancellationToken cancellationToken = default)
{
var folder = await _dialogService.ShowFolderPickerAsync(
_localization?["Lyrics_OutputSelect"] ?? "Select Output Folder");
cancellationToken.ThrowIfCancellationRequested();
if (string.IsNullOrEmpty(folder)) return;
OutputDirectory = folder;
}
// ---------------------------------------------------------------- scanning
/// <summary>
/// Whether the current source has enough input to start reading a song list.
/// 当前来源是否具备扫描所需的输入。
/// </summary>
public bool CanScan => !IsScanning && !IsDownloading && SelectedScannerIndex switch
public bool CanScan => CanEditInputs && (SelectedScannerIndex switch
{
(int)LyricsScannerKind.Local => !string.IsNullOrEmpty(SelectedFolderPath),
(int)LyricsScannerKind.Csv => !string.IsNullOrEmpty(SelectedCsvFilePath),
(int)LyricsScannerKind.NetEase => !string.IsNullOrWhiteSpace(SongListIds),
_ => false
};
});
/// <summary>
/// Re-read the song list using the currently selected source.
/// 使用当前来源重新读取歌曲列表。
/// </summary>
[RelayCommand(CanExecute = nameof(CanScan))]
private async Task StartScanAsync()
private async Task StartScanAsync(CancellationToken cancellationToken = default)
{
switch ((LyricsScannerKind)SelectedScannerIndex)
{
case LyricsScannerKind.Csv:
await ScanCsvFileAsync();
await ScanCsvFileAsync(cancellationToken);
break;
case LyricsScannerKind.NetEase:
await ScanNetEasePlaylistAsync();
await ScanNetEasePlaylistAsync(cancellationToken);
break;
default:
await ScanFilesAsync();
await ScanFilesAsync(cancellationToken);
break;
}
}
private async Task ScanFilesAsync()
private async Task ScanFilesAsync(CancellationToken cancellationToken = default)
{
if (string.IsNullOrEmpty(SelectedFolderPath)) return;
@@ -350,12 +404,13 @@ public partial class LyricsDownloadViewModel : ViewModelBase
try
{
var files = (await _fileScanner.ScanMusicFilesAsync(SelectedFolderPath, _options.SupportFileExtensions))
.ToList();
var files = (await Task.Run(
() => _fileScanner.ScanMusicFilesAsync(SelectedFolderPath, _options.SupportFileExtensions),
cancellationToken)).ToList();
if (files.Count == 0)
{
await ShowNoMusicFilesAsync();
await ShowNoMusicFilesAsync(cancellationToken);
return;
}
@@ -365,7 +420,7 @@ public partial class LyricsDownloadViewModel : ViewModelBase
var scanTasks = files.Select(file =>
warpTask.RunAsync(async () =>
{
var musicInfo = await _tagLoader.LoadTagAsync(file);
var musicInfo = await Task.Run(() => _tagLoader.LoadTagAsync(file).AsTask(), cancellationToken);
await Dispatcher.UIThread.InvokeAsync(() =>
{
@@ -378,15 +433,19 @@ public partial class LyricsDownloadViewModel : ViewModelBase
ScanProgressCount++;
ScanProgressPercentage = ScanProgressCount * 100.0 / ScanTotalCount;
});
}));
}, cancellationToken));
await Task.WhenAll(scanTasks);
TotalCount = MusicFiles.Count;
}
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
{
// 用户取消扫描。
}
catch (Exception ex)
{
await ShowErrorAsync(ex.Message);
await ShowErrorAsync(ex.Message, cancellationToken);
}
finally
{
@@ -394,7 +453,7 @@ public partial class LyricsDownloadViewModel : ViewModelBase
}
}
private async Task ScanCsvFileAsync()
private async Task ScanCsvFileAsync(CancellationToken cancellationToken = default)
{
if (string.IsNullOrEmpty(SelectedCsvFilePath)) return;
@@ -403,16 +462,19 @@ public partial class LyricsDownloadViewModel : ViewModelBase
try
{
var musicInfos = await _csvFileMusicScanner.GetMusicInfoFromCsvFileAsync(
SelectedCsvFilePath,
RequireOutputDirectory(),
DefaultFileNamePattern);
var outputDirectory = RequireOutputDirectory();
var musicInfos = await Task.Run(() => _csvFileMusicScanner.GetMusicInfoFromCsvFileAsync(
SelectedCsvFilePath, outputDirectory, DefaultFileNamePattern, cancellationToken), cancellationToken);
AppendScannedMusicInfos(musicInfos);
}
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
{
// 用户取消扫描。
}
catch (Exception ex)
{
await ShowErrorAsync(ex.Message);
await ShowErrorAsync(ex.Message, cancellationToken);
}
finally
{
@@ -420,21 +482,18 @@ public partial class LyricsDownloadViewModel : ViewModelBase
}
}
private async Task ScanNetEasePlaylistAsync()
private async Task ScanNetEasePlaylistAsync(CancellationToken cancellationToken = default)
{
if (string.IsNullOrWhiteSpace(SongListIds)) return;
ResetCollections();
IsScanning = true;
using var scanCts = new CancellationTokenSource();
_scanCts = scanCts;
try
{
await RestoreNetEaseSessionAsync();
await RestoreNetEaseSessionAsync(cancellationToken);
if (!_neteaseMusicScanner.IsLoggedIn && !await LoginToNetEaseAsync())
if (!_neteaseMusicScanner.IsLoggedIn && !await LoginToNetEaseAsync(cancellationToken))
{
return;
}
@@ -448,46 +507,43 @@ public partial class LyricsDownloadViewModel : ViewModelBase
DefaultFileNamePattern,
onQrCodeReady: null,
onStateChanged: null,
cancellationToken: scanCts.Token);
cancellationToken: cancellationToken);
await PersistNetEaseSessionAsync();
await PersistNetEaseSessionAsync(cancellationToken);
AppendScannedMusicInfos(musicInfos);
}
catch (OperationCanceledException)
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
{
// User closed the login dialog.
// 用户取消扫描。
}
catch (Exception ex)
{
await ShowErrorAsync(ex.Message);
await ShowErrorAsync(ex.Message, cancellationToken);
}
finally
{
_scanCts = null;
IsScanning = false;
// Whatever happened above - scan ok, user cancelled the QR dialog, request failed -
// the account row must reflect the scanner's real state. Without this the sign-in
// button kept saying "Sign out" after a successful login from the scan flow.
// 无论登录成功还是取消,都以扫描器中的状态为准。
IsNetEaseLoggedIn = _neteaseMusicScanner.IsLoggedIn;
}
}
/// <summary>
/// Load a previously saved NetEase session so the QR dialog only appears on first use.
/// 恢复已保存的网易云登录状态。
/// </summary>
private async Task RestoreNetEaseSessionAsync()
private async Task RestoreNetEaseSessionAsync(CancellationToken cancellationToken = default)
{
if (_neteaseMusicScanner.IsLoggedIn) return;
var session = await _sessionStore.LoadAsync();
var session = await _sessionStore.LoadAsync(cancellationToken);
if (session == null) return;
_neteaseMusicScanner.RestoreLoginState(session.Cookie, session.CsrfToken);
}
private async Task PersistNetEaseSessionAsync()
private async Task PersistNetEaseSessionAsync(CancellationToken cancellationToken = default)
{
if (!_neteaseMusicScanner.IsLoggedIn) return;
@@ -495,61 +551,81 @@ public partial class LyricsDownloadViewModel : ViewModelBase
{
Cookie = _neteaseMusicScanner.Cookie,
CsrfToken = _neteaseMusicScanner.CsrfToken,
SavedAt = DateTimeOffset.Now
});
SavedAtUtc = DateTimeOffset.UtcNow
}, cancellationToken);
}
/// <summary>
/// Show the QR dialog and wait for the scan-and-confirm flow to finish.
/// 显示二维码并等待登录或窗口关闭。
/// </summary>
private async Task<bool> LoginToNetEaseAsync()
private async Task<bool> LoginToNetEaseAsync(CancellationToken cancellationToken = default)
{
var loginViewModel = new QrCodeLoginViewModel(_localization);
using var loginCts = new CancellationTokenSource();
loginViewModel.Cancelled += (_, _) => loginCts.Cancel();
using var loginCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
void OnCancelled(object? sender, EventArgs args) => loginCts.Cancel();
loginViewModel.Cancelled += OnCancelled;
var loginTask = Task.Run(async () =>
{
try
{
var expired = false;
var isSuccess = await _neteaseMusicScanner.LoginAsync(
payload => Dispatcher.UIThread.Post(() => loginViewModel.SetPayload(payload)),
state => Dispatcher.UIThread.Post(() => loginViewModel.SetState(state)),
state =>
{
expired = state == NetEaseLoginState.Expired;
Dispatcher.UIThread.Post(() => loginViewModel.SetState(state));
},
loginCts.Token);
if (isSuccess)
await Dispatcher.UIThread.InvokeAsync(() =>
{
Dispatcher.UIThread.Post(() => loginViewModel.Complete());
}
if (isSuccess)
{
loginViewModel.Complete();
}
else if (!expired)
{
loginViewModel.SetError(_localization?["NetEase_LoginFailed"] ??
"Login did not complete. Close this dialog and try again.");
}
});
return isSuccess;
}
catch (OperationCanceledException)
catch (OperationCanceledException) when (loginCts.IsCancellationRequested)
{
return false;
}
catch (Exception ex)
{
Dispatcher.UIThread.Post(() => loginViewModel.SetError(ex.Message));
await Dispatcher.UIThread.InvokeAsync(() => loginViewModel.SetError(ex.Message));
return false;
}
});
// The dialog closes itself once the flow calls Complete(), so this await returns as soon
// as the user either confirms on the phone or gives up.
await _dialogService.ShowQrCodeLoginDialogAsync(loginViewModel);
try
{
await _dialogService.ShowQrCodeLoginDialogAsync(loginViewModel, cancellationToken);
}
finally
{
loginViewModel.NotifyClosed();
loginCts.Cancel();
await loginTask;
loginViewModel.Cancelled -= OnCancelled;
}
var isSuccess = await loginTask;
if (isSuccess)
{
await PersistNetEaseSessionAsync();
await PersistNetEaseSessionAsync(cancellationToken);
}
return isSuccess;
}
// ---------------------------------------------------------------- shared helpers
private void ResetCollections()
{
@@ -567,6 +643,8 @@ public partial class LyricsDownloadViewModel : ViewModelBase
private void AddRow(MusicInfo musicInfo)
{
if (_musicFileMap.ContainsKey(musicInfo.FilePath)) return;
var vm = new MusicFileViewModel
{
FilePath = musicInfo.FilePath,
@@ -581,7 +659,7 @@ public partial class LyricsDownloadViewModel : ViewModelBase
}
/// <summary>
/// Fill the grid from a scanner that returns its list in one shot (CSV, NetEase).
/// 将 CSV 或网易云扫描结果加入列表。
/// </summary>
private void AppendScannedMusicInfos(List<MusicInfo> musicInfos)
{
@@ -611,22 +689,23 @@ public partial class LyricsDownloadViewModel : ViewModelBase
return fallback;
}
private Task ShowNoMusicFilesAsync()
private Task ShowNoMusicFilesAsync(CancellationToken cancellationToken = default)
{
cancellationToken.ThrowIfCancellationRequested();
return _dialogService.ShowMessageAsync(
_localization?["Common_Info"] ?? "Info",
_localization?["Error_NoMusicFiles"] ?? "No music files found in the selected folder.");
}
private Task ShowErrorAsync(string message)
private Task ShowErrorAsync(string message, CancellationToken cancellationToken = default)
{
cancellationToken.ThrowIfCancellationRequested();
return _dialogService.ShowMessageAsync(_localization?["Common_Error"] ?? "Error", message);
}
// ---------------------------------------------------------------- download
[RelayCommand(CanExecute = nameof(CanStartDownload))]
private async Task StartDownloadAsync()
private async Task StartDownloadAsync(CancellationToken cancellationToken = default)
{
if (_scannedMusicInfos.Count == 0) return;
@@ -643,7 +722,7 @@ public partial class LyricsDownloadViewModel : ViewModelBase
vm.StatusMessage = _localization?["Status_Pending"] ?? "Pending";
}
_downloadCts = new CancellationTokenSource();
_downloadCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
try
{
@@ -683,9 +762,13 @@ public partial class LyricsDownloadViewModel : ViewModelBase
},
_downloadCts.Token);
}
catch (OperationCanceledException)
catch (OperationCanceledException) when (_downloadCts.IsCancellationRequested)
{
// User cancelled
// 用户取消下载。
}
catch (Exception ex)
{
await ShowErrorAsync(ex.Message, cancellationToken);
}
finally
{
@@ -702,54 +785,85 @@ public partial class LyricsDownloadViewModel : ViewModelBase
}
/// <summary>
/// Clears the saved NetEase session so the next playlist scan asks for a fresh QR login.
/// <remarks>
/// Without this the only way to recover from an expired Cookie was to delete
/// <c>netease.session.json</c> by hand.
/// </remarks>
/// 清除已保存的网易云登录状态。
/// </summary>
[RelayCommand(CanExecute = nameof(IsNetEaseLoggedIn))]
private async Task SignOutNetEaseAsync()
[RelayCommand(CanExecute = nameof(CanSignOutNetEase))]
private async Task SignOutNetEaseAsync(CancellationToken cancellationToken = default)
{
_neteaseMusicScanner.ClearLoginState();
await _sessionStore.ClearAsync();
IsNetEaseLoggedIn = false;
await _dialogService.ShowMessageAsync(
_localization?["Common_Info"] ?? "Info",
_localization?["NetEase_SignedOut"] ?? "Signed out. The next playlist scan will ask for a QR login.");
IsAccountBusy = true;
try
{
await _sessionStore.ClearAsync(cancellationToken);
_neteaseMusicScanner.ClearLoginState();
await _dialogService.ShowMessageAsync(
_localization?["Common_Info"] ?? "Info",
_localization?["NetEase_SignedOut"] ?? "Signed out. The next playlist scan will ask for a QR login.");
}
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
{
// 用户取消操作。
}
catch (Exception ex)
{
await ShowErrorAsync(ex.Message, cancellationToken);
}
finally
{
IsNetEaseLoggedIn = _neteaseMusicScanner.IsLoggedIn;
IsAccountBusy = false;
}
}
private bool CanSignInNetEase => !IsNetEaseLoggedIn && !IsScanning && !IsDownloading;
private bool CanSignInNetEase => !IsNetEaseLoggedIn && CanEditInputs;
private bool CanSignOutNetEase => IsNetEaseLoggedIn && CanEditInputs;
/// <summary>
/// Let the user sign in from the page itself instead of discovering the QR dialog only after
/// pressing "Scan" - the button used to be hidden behind one specific scanner choice.
/// 主动发起网易云扫码登录。
/// </summary>
[RelayCommand(CanExecute = nameof(CanSignInNetEase))]
private async Task SignInNetEaseAsync()
private async Task SignInNetEaseAsync(CancellationToken cancellationToken = default)
{
if (await LoginToNetEaseAsync())
IsAccountBusy = true;
try
{
IsNetEaseLoggedIn = true;
await LoginToNetEaseAsync(cancellationToken);
}
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
{
// 用户取消登录。
}
catch (Exception ex)
{
await ShowErrorAsync(ex.Message, cancellationToken);
}
finally
{
IsNetEaseLoggedIn = _neteaseMusicScanner.IsLoggedIn;
IsAccountBusy = false;
}
}
/// <summary>
/// Refresh the visible login state. Called on construction and every time the page is shown,
/// because the session may have been written by an earlier run of the app.
/// 页面打开时恢复登录状态。
/// </summary>
private async Task RefreshNetEaseLoginStateAsync()
{
await RestoreNetEaseSessionAsync();
IsNetEaseLoggedIn = _neteaseMusicScanner.IsLoggedIn;
SignOutNetEaseCommand.NotifyCanExecuteChanged();
SignInNetEaseCommand.NotifyCanExecuteChanged();
}
public override async Task OnActivatedAsync()
{
await base.OnActivatedAsync();
await RefreshNetEaseLoginStateAsync();
if (!CanEditInputs) return;
IsAccountBusy = true;
try
{
await RestoreNetEaseSessionAsync();
}
catch (Exception ex)
{
await ShowErrorAsync(ex.Message);
}
finally
{
IsNetEaseLoggedIn = _neteaseMusicScanner.IsLoggedIn;
IsAccountBusy = false;
}
}
}
@@ -28,6 +28,7 @@ public partial class MainWindowViewModel : ViewModelBase
public string NavHome => _localization["Nav_Home"];
public string NavLyricsDownload => _localization["Nav_LyricsDownload"];
public string NavAlbumDownload => _localization["Nav_AlbumDownload"];
/// <summary>音乐解密导航文案。</summary>
public string NavDecrypt => _localization["Nav_Decrypt"];
public string NavSettings => _localization["Nav_Settings"];
public string HomeDescription => _localization["Home_Description"];
@@ -44,17 +45,20 @@ public partial class MainWindowViewModel : ViewModelBase
_themeService = themeService;
_localization = localization;
_navigation = navigation;
IsDarkTheme = _themeService.CurrentTheme == Avalonia.Styling.ThemeVariant.Dark;
_themeService.ThemeChanged += (_, _) =>
IsDarkTheme = _themeService.CurrentTheme == Avalonia.Styling.ThemeVariant.Dark;
// Subscribe to language changes
_localization.LanguageChanged += OnLanguageChanged;
// The navigation service is the single owner of "which page is showing".
// 页面切换统一由导航服务管理。
_navigation.NavigationChanged += OnNavigationChanged;
NavigateToIndex(0);
}
// Guards against the re-entrant loop "index changed -> navigate -> navigation changed -> index changed".
// 避免导航通知与侧栏选中状态互相触发。
private bool _isSyncingNavigation;
partial void OnSelectedNavigationIndexChanged(int value)
@@ -69,8 +73,7 @@ public partial class MainWindowViewModel : ViewModelBase
private void NavigateToIndex(int index)
{
// NavigateRoot keeps the stack depth at one: sidebar switching is not a back-navigable
// action, so clicking around must not grow history.
// 侧栏切换不累积返回记录。
CurrentPage = index switch
{
1 => _navigation.NavigateRoot<LyricsDownloadViewModel>(),
@@ -85,7 +88,7 @@ public partial class MainWindowViewModel : ViewModelBase
{
CurrentPage = viewModel;
// The home page quick actions navigate directly, so the sidebar has to follow them.
// 首页快捷入口跳转时同步侧栏选中项。
var index = IndexOf(viewModel);
if (index < 0 || index == SelectedNavigationIndex)
{
@@ -128,9 +131,6 @@ public partial class MainWindowViewModel : ViewModelBase
[RelayCommand]
private void ToggleTheme()
{
IsDarkTheme = !IsDarkTheme;
_themeService.SetTheme(IsDarkTheme
? Avalonia.Styling.ThemeVariant.Dark
: Avalonia.Styling.ThemeVariant.Light);
_themeService.ToggleTheme();
}
}
@@ -7,16 +7,12 @@ using ZonyLrcTools.Desktop.Infrastructure.Localization;
namespace ZonyLrcTools.Desktop.ViewModels;
/// <summary>
/// Drives the NetEase QR-code login dialog.
/// 网易云扫码登录对话框。
/// </summary>
/// <remarks>
/// Two events cross the dialog boundary in opposite directions: <see cref="CloseRequested"/>
/// lets the login flow close the window once it is done, and <see cref="Cancelled"/> fires when
/// the user closed the window first, so the caller can stop polling instead of waiting forever.
/// </remarks>
public partial class QrCodeLoginViewModel : ObservableObject
{
private readonly IUILocalizationService? _localization;
private bool _isClosed;
[ObservableProperty]
private Bitmap? _qrCodeImage;
@@ -28,24 +24,30 @@ public partial class QrCodeLoginViewModel : ObservableObject
private bool _hasImage;
/// <summary>
/// Raised when the login flow wants the dialog closed.
/// 请求关闭登录对话框。
/// </summary>
public event EventHandler? CloseRequested;
/// <summary>
/// Raised when the user closed the dialog before logging in.
/// 登录完成前关闭对话框时触发。
/// </summary>
public event EventHandler? Cancelled;
/// <summary>
/// True once the login succeeded; the dialog stays closable but no longer counts as a cancel.
/// 是否已登录成功。
/// </summary>
public bool IsCompleted { get; private set; }
/// <summary>登录窗口标题。</summary>
public string LoginTitle => _localization?["NetEase_LoginTitle"] ?? "Sign in to NetEase Cloud Music";
/// <summary>扫码登录提示。</summary>
public string LoginTip => _localization?["NetEase_LoginTip"] ?? "Scan the QR code with the NetEase Cloud Music app on your phone.";
/// <summary>取消按钮文案。</summary>
public string CancelText => _localization?["Common_Cancel"] ?? "Cancel";
/// <summary>
/// 创建扫码登录对话框状态。
/// </summary>
public QrCodeLoginViewModel(IUILocalizationService? localization = null)
{
_localization = localization;
@@ -57,47 +59,60 @@ public partial class QrCodeLoginViewModel : ObservableObject
private string SuccessText => _localization?["NetEase_LoginSucceeded"] ?? "Signed in.";
/// <summary>
/// Render the QR payload the scanner produced.
/// 显示扫描器提供的二维码。
/// </summary>
public void SetPayload(NetEaseQrCodePayload payload)
{
if (_isClosed) return;
var previousImage = QrCodeImage;
QrCodeImage = RenderQrCode(payload.Content);
HasImage = QrCodeImage != null;
StatusText = WaitText;
previousImage?.Dispose();
StatusText = HasImage
? WaitText
: _localization?["NetEase_LoginFailed"] ?? "Login did not complete. Close this dialog and try again.";
}
/// <summary>
/// Reflect a login-state change reported by the scanner.
/// 更新扫码登录状态。
/// </summary>
public void SetState(NetEaseLoginState state)
{
if (_isClosed) return;
StatusText = state switch
{
NetEaseLoginState.ScanConfirmed => ScannedText,
NetEaseLoginState.Succeeded => SuccessText,
NetEaseLoginState.Expired => _localization?["NetEase_LoginExpired"] ?? "The QR code expired. Close this dialog and try again.",
_ => WaitText
};
}
/// <summary>
/// Push an error message into the dialog.
/// 显示登录错误。
/// </summary>
public void SetError(string message)
{
if (_isClosed) return;
StatusText = message;
}
/// <summary>
/// Mark the flow as finished and close the dialog.
/// 标记登录完成并关闭对话框。
/// </summary>
public void Complete()
{
if (_isClosed) return;
IsCompleted = true;
RequestClose();
}
/// <summary>
/// Ask the dialog to close.
/// 请求关闭对话框。
/// </summary>
public void RequestClose()
{
@@ -105,10 +120,18 @@ public partial class QrCodeLoginViewModel : ObservableObject
}
/// <summary>
/// Called by the dialog when its window closed, for whatever reason.
/// 窗口关闭后停止登录并释放二维码。
/// </summary>
public void NotifyClosed()
{
if (_isClosed) return;
_isClosed = true;
var image = QrCodeImage;
QrCodeImage = null;
HasImage = false;
image?.Dispose();
if (!IsCompleted)
{
Cancelled?.Invoke(this, EventArgs.Empty);
@@ -121,13 +144,13 @@ public partial class QrCodeLoginViewModel : ObservableObject
{
using var generator = new QRCodeGenerator();
using var data = generator.CreateQrCode(content, QRCodeGenerator.ECCLevel.M);
var pngBytes = new PngByteQRCode(data).GetGraphic(12);
return new Bitmap(new MemoryStream(pngBytes));
using var qrCode = new PngByteQRCode(data);
using var stream = new MemoryStream(qrCode.GetGraphic(12));
return new Bitmap(stream);
}
catch (Exception)
{
// A render failure shows up as the placeholder, not as a crash.
// 二维码无法生成时,由界面显示登录失败提示。
return null;
}
}
@@ -9,12 +9,13 @@ using ZonyLrcTools.Desktop.Infrastructure.Localization;
namespace ZonyLrcTools.Desktop.ViewModels;
/// <summary>设置页面及自动保存状态。</summary>
public partial class SettingsViewModel : ViewModelBase
{
private readonly ISettingsStore _settingsStore;
private readonly IUILocalizationService? _localizationService;
private readonly GlobalOptions _globalOptions;
private bool _isLoading = true; // Prevent saving during initial load
private bool _isLoading = true;
[ObservableProperty]
private bool _followSystemLanguage = true;
@@ -32,7 +33,7 @@ public partial class SettingsViewModel : ViewModelBase
private string _proxyIp = "127.0.0.1";
[ObservableProperty]
private int _proxyPort = 7890;
private int _proxyPort = 4780;
[ObservableProperty]
private bool _isTranslationEnabled;
@@ -61,15 +62,11 @@ public partial class SettingsViewModel : ViewModelBase
[ObservableProperty]
private bool _isRomanOutputEnabled;
/// <summary>
/// Advanced options are collapsed by default: the common path is language + proxy + the four
/// lyric flags, everything else is a power-user setting.
/// </summary>
/// <summary>是否显示高级设置。</summary>
[ObservableProperty]
private bool _isAdvancedVisible;
// Status line for the settings page: shows where settings are stored and whether the
// last save succeeded.
// 显示配置位置及上次保存结果。
[ObservableProperty]
private string _storageHint = string.Empty;
@@ -83,10 +80,7 @@ public partial class SettingsViewModel : ViewModelBase
[NotifyPropertyChangedFor(nameof(ShowSaveFailure))]
private bool _hasSaveError;
/// <summary>
/// Encoding choices offered in the settings page. These map to the values accepted by
/// <see cref="GlobalLyricsConfigOptions.FileEncoding"/>.
/// </summary>
/// <summary>可选择的歌词编码。</summary>
public ObservableCollection<string> AvailableEncodings { get; } = new()
{
"utf-8",
@@ -95,10 +89,7 @@ public partial class SettingsViewModel : ViewModelBase
"gbk"
};
/// <summary>
/// Line-break choices, parallel to <see cref="LineBreakDisplayNames"/>. The stored value is the
/// actual escape sequence so the YAML file stays compatible with the CLI.
/// </summary>
/// <summary>预设换行符,与显示列表顺序一致。</summary>
private static readonly string[] LineBreaks =
{
LineBreakType.Unix,
@@ -106,9 +97,7 @@ public partial class SettingsViewModel : ViewModelBase
LineBreakType.MacOs
};
/// <summary>
/// Display names for the line-break selector, parallel to the internal sequence table.
/// </summary>
/// <summary>换行符的显示名称。</summary>
public ObservableCollection<string> LineBreakDisplayNames { get; } = new()
{
"LF (Unix)",
@@ -116,68 +105,103 @@ public partial class SettingsViewModel : ViewModelBase
"CR (macOS)"
};
/// <summary>
/// Value the current settings file uses, for the selected line-break entry.
/// </summary>
private string CurrentLineBreak => LineBreaks[Math.Clamp(SelectedLineBreakIndex, 0, LineBreaks.Length - 1)];
private string CurrentLineBreak => SelectedLineBreakIndex >= 0 && SelectedLineBreakIndex < LineBreaks.Length
? LineBreaks[SelectedLineBreakIndex]
: _globalOptions.Provider?.Lyric?.Config?.LineBreak ?? LineBreakType.Unix;
/// <summary>歌词提供者及搜索顺序。</summary>
public ObservableCollection<LyricsProviderSettingViewModel> LyricsProviders { get; } = new();
/// <summary>标签提供者及加载顺序。</summary>
public ObservableCollection<TagInfoProviderSettingViewModel> TagProviders { get; } = new();
// Localized strings
// 本地化文本。
/// <summary>设置标题的本地化文本。</summary>
public string SettingsTitle => _localizationService?["Settings_Title"] ?? "Settings";
/// <summary>语言设置标题的本地化文本。</summary>
public string SettingsLanguage => _localizationService?["Settings_Language"] ?? "Language";
/// <summary>跟随系统语言的本地化文本。</summary>
public string SettingsFollowSystem => _localizationService?["Settings_FollowSystem"] ?? "Follow System";
/// <summary>中文选项的本地化文本。</summary>
public string SettingsChinese => _localizationService?["Settings_Chinese"] ?? "Chinese";
/// <summary>英文选项的本地化文本。</summary>
public string SettingsEnglish => _localizationService?["Settings_English"] ?? "English";
/// <summary>代理设置标题的本地化文本。</summary>
public string SettingsProxy => _localizationService?["Settings_Proxy"] ?? "Proxy";
/// <summary>启用代理的本地化文本。</summary>
public string SettingsProxyEnable => _localizationService?["Settings_ProxyEnable"] ?? "Enable Proxy";
/// <summary>代理地址的本地化文本。</summary>
public string SettingsProxyAddress => _localizationService?["Settings_ProxyAddress"] ?? "Proxy Address";
/// <summary>代理端口的本地化文本。</summary>
public string SettingsProxyPort => _localizationService?["Settings_ProxyPort"] ?? "Port";
/// <summary>歌词提供者标题的本地化文本。</summary>
public string SettingsLyricsProvider => _localizationService?["Settings_LyricsProvider"] ?? "Lyrics Provider";
/// <summary>恢复默认值的本地化文本。</summary>
public string SettingsReset => _localizationService?["Settings_Reset"] ?? "Reset";
/// <summary>基本设置标题的本地化文本。</summary>
public string SettingsBasicSection => _localizationService?["Settings_BasicSection"] ?? "Basics";
/// <summary>高级设置标题的本地化文本。</summary>
public string SettingsAdvancedSection => _localizationService?["Settings_AdvancedSection"] ?? "Advanced";
/// <summary>高级选项开关的本地化文本。</summary>
public string SettingsShowAdvanced => _localizationService?["Settings_ShowAdvanced"] ?? "Show advanced options";
/// <summary>歌词设置标题的本地化文本。</summary>
public string SettingsLyricsSection => _localizationService?["Settings_LyricsSection"] ?? "Lyrics";
/// <summary>翻译开关的本地化文本。</summary>
public string SettingsEnableTranslation => _localizationService?["Settings_EnableTranslation"] ?? "Enable translation lyrics";
/// <summary>合并双语歌词开关的本地化文本。</summary>
public string SettingsOneLineMode => _localizationService?["Settings_OneLineMode"] ?? "One-line mode (original + translation on same line)";
/// <summary>仅输出翻译开关的本地化文本。</summary>
public string SettingsOnlyTranslation => _localizationService?["Settings_OnlyTranslation"] ?? "Output translation only";
/// <summary>跳过已有文件开关的本地化文本。</summary>
public string SettingsSkipExisting => _localizationService?["Settings_SkipExisting"] ?? "Skip existing lyrics files";
/// <summary>编码选项的本地化文本。</summary>
public string SettingsFileEncoding => _localizationService?["Settings_FileEncoding"] ?? "File Encoding:";
/// <summary>换行符选项的本地化文本。</summary>
public string SettingsLineBreak => _localizationService?["Settings_LineBreak"] ?? "Line break:";
/// <summary>罗马音开关的本地化文本。</summary>
public string SettingsRomanOutput => _localizationService?["Settings_RomanOutput"] ?? "Enable romanized output (NetEase)";
/// <summary>屏蔽词设置标题的本地化文本。</summary>
public string SettingsBlockWordSection => _localizationService?["Settings_BlockWordSection"] ?? "Tag block word dictionary";
/// <summary>屏蔽词开关的本地化文本。</summary>
public string SettingsBlockWordEnable => _localizationService?["Settings_BlockWordEnable"] ?? "Enable block word dictionary";
public string SettingsBlockWordPath => _localizationService?["Settings_BlockWordPath"] ?? "Dictionary file (relative to the app folder)";
/// <summary>屏蔽词路径的本地化文本。</summary>
public string SettingsBlockWordPath => _localizationService?["Settings_BlockWordPath"] ?? "Dictionary file (relative to the working directory)";
/// <summary>标签提供者标题的本地化文本。</summary>
public string SettingsTagProvider => _localizationService?["Settings_TagProvider"] ?? "Tag Provider";
/// <summary>优先级标题的本地化文本。</summary>
public string SettingsPriority => _localizationService?["Settings_Priority"] ?? "Priority: ";
/// <summary>上移按钮的本地化文本。</summary>
public string SettingsMoveUp => _localizationService?["Settings_MoveUp"] ?? "Move up";
/// <summary>下移按钮的本地化文本。</summary>
public string SettingsMoveDown => _localizationService?["Settings_MoveDown"] ?? "Move down";
/// <summary>提供者顺序说明的本地化文本。</summary>
public string SettingsProviderOrderHint => _localizationService?["Settings_ProviderOrderHint"]
?? "The list order is the search order. Use the arrows to change which source is tried first.";
/// <summary>设置保存位置的本地化文本。</summary>
public string SettingsStorage => _localizationService?["Settings_Storage"] ?? "Settings file";
/// <summary>保存成功的本地化文本。</summary>
public string SettingsSaved => _localizationService?["Settings_Saved"] ?? "Saved";
/// <summary>保存失败的本地化文本。</summary>
public string SettingsSaveFailed => _localizationService?["Settings_SaveFailed"] ?? "Could not save settings";
/// <summary>代理重启提示的本地化文本。</summary>
public string SettingsProxyRestartHint => _localizationService?["Settings_ProxyRestartHint"]
?? "Proxy changes take effect the next time the app starts.";
/// <summary>
/// Save feedback: only one of these is ever true, and both stay false before the first save.
/// </summary>
/// <summary>是否显示保存成功提示。</summary>
public bool ShowSaveSuccess => !HasSaveError && !string.IsNullOrEmpty(SaveStatusText);
/// <summary>是否显示保存失败提示。</summary>
public bool ShowSaveFailure => HasSaveError && !string.IsNullOrEmpty(SaveStatusText);
/// <summary>创建设置页面。</summary>
public SettingsViewModel(ISettingsStore settingsStore, IUILocalizationService? localizationService = null)
{
_settingsStore = settingsStore;
_localizationService = localizationService;
_globalOptions = settingsStore.Options;
// Subscribe to language changes
// 跟随应用语言切换更新界面。
if (_localizationService != null)
{
_localizationService.LanguageChanged += OnLanguageChanged;
@@ -186,7 +210,7 @@ public partial class SettingsViewModel : ViewModelBase
LoadSettings();
LoadLanguageSettings();
StorageHint = $"{SettingsStorage}: {_settingsStore.ConfigFilePath}";
_isLoading = false; // Allow saving after initial load
_isLoading = false;
}
private void OnLanguageChanged(object? sender, EventArgs e)
@@ -225,6 +249,7 @@ public partial class SettingsViewModel : ViewModelBase
OnPropertyChanged(nameof(SettingsSaved));
OnPropertyChanged(nameof(SettingsSaveFailed));
OnPropertyChanged(nameof(SettingsProxyRestartHint));
StorageHint = $"{SettingsStorage}: {_settingsStore.ConfigFilePath}";
}
private void LoadLanguageSettings()
@@ -238,7 +263,7 @@ public partial class SettingsViewModel : ViewModelBase
{
if (value)
{
// Auto-detect system language
// 使用操作系统语言。
var systemCulture = CultureInfo.InstalledUICulture.Name;
ApplyLanguage(systemCulture.StartsWith("zh") ? "zh-CN" : "en-US");
}
@@ -294,12 +319,12 @@ public partial class SettingsViewModel : ViewModelBase
private void LoadSettings()
{
// Load network settings
// 加载代理设置。
IsProxyEnabled = _globalOptions.NetworkOptions?.IsEnable ?? false;
ProxyIp = _globalOptions.NetworkOptions?.Ip ?? "127.0.0.1";
ProxyPort = _globalOptions.NetworkOptions?.Port ?? 7890;
ProxyPort = _globalOptions.NetworkOptions?.Port ?? 4780;
// Load lyrics settings
// 加载歌词设置,保留未列入预设的有效编码。
var lyricsConfig = _globalOptions.Provider?.Lyric?.Config;
if (lyricsConfig != null)
{
@@ -307,11 +332,15 @@ public partial class SettingsViewModel : ViewModelBase
IsOneLineMode = lyricsConfig.IsOneLine;
SkipExistingLyrics = lyricsConfig.IsSkipExistLyricFiles;
SelectedEncoding = lyricsConfig.FileEncoding ?? "utf-8";
if (!AvailableEncodings.Contains(SelectedEncoding))
{
AvailableEncodings.Add(SelectedEncoding);
}
IsOnlyOutputTranslation = lyricsConfig.IsOnlyOutputTranslation;
SelectedLineBreakIndex = ResolveLineBreakIndex(lyricsConfig.LineBreak);
}
// Load block word settings
// 加载屏蔽词设置。
var blockWord = _globalOptions.Provider?.Tag?.BlockWord;
if (blockWord != null)
{
@@ -321,7 +350,7 @@ public partial class SettingsViewModel : ViewModelBase
: blockWord.FilePath;
}
// Load romanized output flag from the NetEase provider's extended options
// 罗马音开关保存在网易云提供者的扩展设置中。
var netEase = _globalOptions.Provider?.Lyric?.Plugin?
.FirstOrDefault(p => string.Equals(p.Name, "NetEase", StringComparison.OrdinalIgnoreCase));
if (netEase?.Additional != null &&
@@ -330,9 +359,7 @@ public partial class SettingsViewModel : ViewModelBase
IsRomanOutputEnabled = string.Equals(romanValue, "true", StringComparison.OrdinalIgnoreCase);
}
// Tag providers are listed in ascending priority, which is also the order the loader tries
// them in. The list itself is the order now: the number is derived from the position, so a
// row that is moved up shows a smaller number without any extra bookkeeping.
// 启用的提供者按优先级排列,禁用项放到末尾。
var tagProviders = _globalOptions.Provider?.Tag?.Plugin;
if (tagProviders != null)
{
@@ -341,8 +368,7 @@ public partial class SettingsViewModel : ViewModelBase
AddTagProviderRow(provider.Name, true);
}
// Disabled sources (priority -1) have no slot of their own; they sit at the bottom of
// the list, greyed out, so re-enabling one just drops it back into the queue.
// 禁用项不参与搜索。
foreach (var provider in tagProviders.Where(p => p.Priority == -1))
{
AddTagProviderRow(provider.Name, false);
@@ -351,7 +377,7 @@ public partial class SettingsViewModel : ViewModelBase
NormalizeProviderOrder(TagProviders);
}
// Lyrics providers follow the same rule as the tag providers above.
// 歌词提供者与标签提供者采用相同排序规则。
var providers = _globalOptions.Provider?.Lyric?.Plugin;
if (providers != null)
{
@@ -377,13 +403,11 @@ public partial class SettingsViewModel : ViewModelBase
IsEnabled = isEnabled
};
// The arrows move the row inside its own list; the callback has to be installed after the
// row exists, otherwise the lambda would capture an unassigned local.
// 创建行后绑定移动命令。
row.MoveUpCommand = new RelayCommand(() => MoveProviderBy(TagProviders, row, -1));
row.MoveDownCommand = new RelayCommand(() => MoveProviderBy(TagProviders, row, 1));
// Rows are separate objects, so their own change notifications have to be wired back into
// the save pipeline or the checkbox moves and the file never changes.
// 将行内编辑接入自动保存。
row.PropertyChanged += OnProviderRowChanged;
TagProviders.Add(row);
}
@@ -403,11 +427,7 @@ public partial class SettingsViewModel : ViewModelBase
LyricsProviders.Add(row);
}
/// <summary>
/// Any edit inside a provider row funnels into the same debounced save that the top-level
/// settings use. Toggling a checkbox also re-sorts the list, because enabled sources always
/// sit above disabled ones and the visible numbering has to follow.
/// </summary>
/// <summary>提供者启用状态改变后重新排序并保存。</summary>
private void OnProviderRowChanged(object? sender, System.ComponentModel.PropertyChangedEventArgs e)
{
if (_isLoading || _isNormalizing)
@@ -442,11 +462,7 @@ public partial class SettingsViewModel : ViewModelBase
private bool _isNormalizing;
/// <summary>
/// The list order <em>is</em> the search order. This enforces the two invariants that make that
/// readable: enabled rows above disabled ones, and a visible 1..n numbering that matches the
/// position. Priorities are derived here, never typed by hand.
/// </summary>
/// <summary>启用项在前,优先级按可见顺序从一开始。</summary>
private void NormalizeProviderOrder<T>(ObservableCollection<T> rows) where T : class, IProviderRowViewModel
{
var ordered = rows.Where(r => r.IsEnabled).Concat(rows.Where(r => !r.IsEnabled)).ToList();
@@ -465,8 +481,7 @@ public partial class SettingsViewModel : ViewModelBase
{
var row = ordered[i];
// 禁用行在内存里就写 -1,和配置文件里的语义保持一致;否则一旦某条路径漏掉
// ApplyProviderSelection,就会把一个不存在的「第 5 名」写回 config.yaml。
// 禁用项统一使用 -1。
row.Priority = i < enabledCount ? i + 1 : -1;
row.PriorityLabel = i < enabledCount ? (i + 1).ToString(CultureInfo.InvariantCulture) : "—";
row.CanMoveUp = i > 0 && i < enabledCount;
@@ -474,11 +489,7 @@ public partial class SettingsViewModel : ViewModelBase
}
}
/// <summary>
/// Moves a row one slot up or down. Disabled rows are pinned to the bottom, so a move that
/// would cross the enabled/disabled boundary is ignored rather than silently doing nothing
/// visible.
/// </summary>
/// <summary>在启用项范围内移动提供者。</summary>
private void MoveProviderBy<T>(ObservableCollection<T> rows, T row, int offset)
where T : class, IProviderRowViewModel
{
@@ -513,7 +524,7 @@ public partial class SettingsViewModel : ViewModelBase
}
}
return 0;
return -1;
}
private void WriteSettingsToOptions()
@@ -551,18 +562,12 @@ public partial class SettingsViewModel : ViewModelBase
netEase.Additional["isEnableRomanOutput"] = IsRomanOutputEnabled ? "true" : "false";
}
// Provider toggles are not decoration: unchecking writes priority -1, which is how the
// downloader skips a source. Without this the checkboxes move and the file never changes.
// 同步启用状态及搜索顺序。
ApplyProviderSelection(_globalOptions.Provider?.Lyric?.Plugin, LyricsProviders);
ApplyProviderSelection(_globalOptions.Provider?.Tag?.Plugin, TagProviders);
}
/// <summary>
/// Push the row state onto the options: the checkbox decides whether a source runs at all
/// (disabled sources store -1, which is how the downloader skips them) and the list position
/// decides the search order. The number in the UI is derived from that position, so there is
/// nothing to reconcile here — no duplicate slots, no silent renumbering.
/// </summary>
/// <summary>将歌词提供者的界面顺序写入共享配置。</summary>
private static void ApplyProviderSelection(
IEnumerable<LyricsProviderOptions>? options,
IEnumerable<LyricsProviderSettingViewModel> viewModels)
@@ -611,18 +616,22 @@ public partial class SettingsViewModel : ViewModelBase
}
}
private async Task SaveSettingsAsync()
private async Task SaveSettingsAsync(CancellationToken cancellationToken = default)
{
// Debounce rapid changes (dragging a port spinner, typing an IP) into one write.
// 合并连续输入,但配置在内存中立即生效。
var pending = Interlocked.Increment(ref _saveRequestId);
await Task.Delay(SaveDebounceMilliseconds).ConfigureAwait(true);
await Task.Delay(SaveDebounceMilliseconds, cancellationToken).ConfigureAwait(true);
if (pending != Volatile.Read(ref _saveRequestId))
{
return;
}
var result = await _settingsStore.SaveAsync().ConfigureAwait(true);
var result = await _settingsStore.SaveAsync(cancellationToken).ConfigureAwait(true);
if (pending != Volatile.Read(ref _saveRequestId))
{
return;
}
HasSaveError = !result.IsSuccess;
SaveStatusText = result.IsSuccess
@@ -635,12 +644,13 @@ public partial class SettingsViewModel : ViewModelBase
private const int SaveDebounceMilliseconds = 400;
[RelayCommand]
private async Task ResetToDefaults()
private async Task ResetToDefaultsAsync(CancellationToken cancellationToken = default)
{
_isLoading = true; // Prevent multiple saves during reset
Interlocked.Increment(ref _saveRequestId);
_isLoading = true;
IsProxyEnabled = false;
ProxyIp = "127.0.0.1";
ProxyPort = 7890;
ProxyPort = 4780;
IsTranslationEnabled = true;
IsOneLineMode = true;
SkipExistingLyrics = false;
@@ -651,9 +661,9 @@ public partial class SettingsViewModel : ViewModelBase
BlockWordFilePath = "BlockWords.json";
IsRomanOutputEnabled = false;
// Provider rows are settings too; leaving a disabled source behind after "reset" would
// look like the button half worked. Everything comes back enabled, in the order the rows
// are listed, which the numbering then reflects as 1..n again.
// 恢复随程序附带的默认顺序,额外提供者保留在末尾。
RestoreProviderOrder(LyricsProviders, ["NetEase", "QQ", "KuGou", "KuWo"], row => row.Name);
RestoreProviderOrder(TagProviders, ["Taglib", "FileName"], row => row.Name);
foreach (var row in LyricsProviders)
{
row.IsEnabled = true;
@@ -669,44 +679,59 @@ public partial class SettingsViewModel : ViewModelBase
_isLoading = false;
// Save once after all resets
// 所有默认值恢复后只保存一次。
WriteSettingsToOptions();
var result = await _settingsStore.SaveAsync().ConfigureAwait(true);
var result = await _settingsStore.SaveAsync(cancellationToken).ConfigureAwait(true);
HasSaveError = !result.IsSuccess;
SaveStatusText = result.IsSuccess
? $"{SettingsSaved}: {result.FilePath}"
: $"{SettingsSaveFailed}: {result.ErrorMessage}";
}
private static void RestoreProviderOrder<T>(ObservableCollection<T> rows, string[] names, Func<T, string> getName)
where T : class
{
var target = 0;
foreach (var name in names)
{
var row = rows.FirstOrDefault(row => string.Equals(getName(row), name, StringComparison.OrdinalIgnoreCase));
if (row is not null)
{
rows.Move(rows.IndexOf(row), target++);
}
}
}
}
/// <summary>
/// Shared shape of a source row so the reordering logic can work on both lists without
/// duplicating it. The visible order is the search order; <see cref="Priority"/> and
/// <see cref="PriorityLabel"/> are written by the view model, never typed by the user.
/// </summary>
/// <summary>可排序的提供者设置行。</summary>
public interface IProviderRowViewModel
{
/// <summary>是否启用。</summary>
bool IsEnabled { get; set; }
/// <summary>搜索优先级,禁用时为 -1。</summary>
int Priority { get; set; }
/// <summary>界面显示的顺序。</summary>
string PriorityLabel { get; set; }
/// <summary>是否可以向上移动。</summary>
bool CanMoveUp { get; set; }
/// <summary>是否可以向下移动。</summary>
bool CanMoveDown { get; set; }
/// <summary>
/// Dimming for disabled rows: they are out of the running and pinned to the bottom, so they
/// should read as inactive rather than as just another entry.
/// </summary>
/// <summary>禁用时降低行透明度。</summary>
double RowOpacity { get; }
/// <summary>向上移动命令。</summary>
IRelayCommand MoveUpCommand { get; }
/// <summary>向下移动命令。</summary>
IRelayCommand MoveDownCommand { get; }
}
/// <summary>歌词提供者设置行。</summary>
public partial class LyricsProviderSettingViewModel : ObservableObject, IProviderRowViewModel
{
[ObservableProperty]
@@ -716,17 +741,11 @@ public partial class LyricsProviderSettingViewModel : ObservableObject, IProvide
[NotifyPropertyChangedFor(nameof(RowOpacity))]
private bool _isEnabled;
/// <summary>
/// Search order derived from the row position, smaller runs first. Disabled rows keep the
/// number they would occupy but are written as -1, which is how the downloader skips them.
/// </summary>
/// <summary>搜索优先级,禁用时为 -1。</summary>
[ObservableProperty]
private int _priority;
/// <summary>
/// What the list shows in the number column: the position, or a dash once the row is disabled
/// and pushed to the bottom.
/// </summary>
/// <summary>显示的顺序,禁用时显示横线。</summary>
[ObservableProperty]
private string _priorityLabel = string.Empty;
@@ -736,13 +755,17 @@ public partial class LyricsProviderSettingViewModel : ObservableObject, IProvide
[ObservableProperty]
private bool _canMoveDown;
/// <inheritdoc />
public double RowOpacity => IsEnabled ? 1.0 : 0.45;
/// <inheritdoc />
public IRelayCommand MoveUpCommand { get; set; } = new RelayCommand(() => { });
/// <inheritdoc />
public IRelayCommand MoveDownCommand { get; set; } = new RelayCommand(() => { });
}
/// <summary>标签提供者设置行。</summary>
public partial class TagInfoProviderSettingViewModel : ObservableObject, IProviderRowViewModel
{
[ObservableProperty]
@@ -766,9 +789,12 @@ public partial class TagInfoProviderSettingViewModel : ObservableObject, IProvid
[ObservableProperty]
private bool _canMoveDown;
/// <inheritdoc />
public double RowOpacity => IsEnabled ? 1.0 : 0.45;
/// <inheritdoc />
public IRelayCommand MoveUpCommand { get; set; } = new RelayCommand(() => { });
/// <inheritdoc />
public IRelayCommand MoveDownCommand { get; set; } = new RelayCommand(() => { });
}