feat(desktop): 设置页覆盖全部配置项,歌词源改为上下移动排序

设置页原先只写 config.yaml 里的五个键(代理开关/地址/端口,以及四个歌词开关)。
其余 —— 支持的文件后缀、标签源列表、屏蔽词、换行符、罗马音输出 —— 在界面上都
看不见,所以没法把 GUI 当成"不用手改 YAML"的替代品。

现在页面分两层:

基础:语言、主题、代理、歌词开关(翻译、单行、只输出翻译、跳过已存在)、文件
编码与换行符。

高级(默认折叠):罗马音输出、屏蔽词及其文件路径、标签源列表。

歌词源的优先级换了交互方式。第一版是在每行旁边放一个数字微调框,结果很别扭:
把 1 改成 3 行不会动,输入重复数字还会静默把另一行改号。现在列表本身就是顺序
—— 左侧只读名次、右侧上下箭头,被禁用的源沉到底部并变灰,名次位置显示短横线。
保存时直接把位置写进 priority,因此重复优先级不可能出现。

服务商勾选框这回真的生效了。它们原先纯属装饰:保存路径根本没碰插件列表,取消
勾选酷狗,文件里它仍然是 priority: 4 的启用状态。

MessageDialog 从纯 TextBlock 改成只读可选中文本框加"复制"按钮 —— 这个应用产生
的失败信息(酷狗密钥查找、网易云请求错误)长到没法复制就成了真问题。
This commit is contained in:
aL1CesT committed 2026-11-09 04:27:44 +08:00
1 parent bc0017b050
commit 201b1abf40
5 files changed
+804 -101

No files matched your search

@@ -2,18 +2,18 @@ using System.Collections.ObjectModel;
using System.Globalization; using System.Globalization;
using CommunityToolkit.Mvvm.ComponentModel; using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input; using CommunityToolkit.Mvvm.Input;
using Microsoft.Extensions.Options;
using YamlDotNet.Serialization;
using YamlDotNet.Serialization.NamingConventions;
using ZonyLrcTools.Common.Configuration; using ZonyLrcTools.Common.Configuration;
using ZonyLrcTools.Common.Lyrics;
using ZonyLrcTools.Desktop.Infrastructure.Configuration;
using ZonyLrcTools.Desktop.Infrastructure.Localization; using ZonyLrcTools.Desktop.Infrastructure.Localization;
namespace ZonyLrcTools.Desktop.ViewModels; namespace ZonyLrcTools.Desktop.ViewModels;
public partial class SettingsViewModel : ViewModelBase public partial class SettingsViewModel : ViewModelBase
{ {
private readonly GlobalOptions _globalOptions; private readonly ISettingsStore _settingsStore;
private readonly IUILocalizationService? _localizationService; private readonly IUILocalizationService? _localizationService;
private readonly GlobalOptions _globalOptions;
private bool _isLoading = true; // Prevent saving during initial load private bool _isLoading = true; // Prevent saving during initial load
[ObservableProperty] [ObservableProperty]
@@ -46,6 +46,85 @@ public partial class SettingsViewModel : ViewModelBase
[ObservableProperty] [ObservableProperty]
private string _selectedEncoding = "utf-8"; private string _selectedEncoding = "utf-8";
[ObservableProperty]
private bool _isOnlyOutputTranslation;
[ObservableProperty]
private int _selectedLineBreakIndex;
[ObservableProperty]
private bool _isBlockWordEnabled;
[ObservableProperty]
private string _blockWordFilePath = "BlockWords.json";
[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>
[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;
[ObservableProperty]
[NotifyPropertyChangedFor(nameof(ShowSaveSuccess))]
[NotifyPropertyChangedFor(nameof(ShowSaveFailure))]
private string _saveStatusText = string.Empty;
[ObservableProperty]
[NotifyPropertyChangedFor(nameof(ShowSaveSuccess))]
[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>
public ObservableCollection<string> AvailableEncodings { get; } = new()
{
"utf-8",
"utf-8-bom",
"gb2312",
"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>
private static readonly string[] LineBreaks =
{
LineBreakType.Unix,
LineBreakType.Windows,
LineBreakType.MacOs
};
/// <summary>
/// Display names for the line-break selector, parallel to the internal sequence table.
/// </summary>
public ObservableCollection<string> LineBreakDisplayNames { get; } = new()
{
"LF (Unix)",
"CRLF (Windows)",
"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)];
public ObservableCollection<LyricsProviderSettingViewModel> LyricsProviders { get; } = new();
public ObservableCollection<TagInfoProviderSettingViewModel> TagProviders { get; } = new();
// Localized strings // Localized strings
public string SettingsTitle => _localizationService?["Settings_Title"] ?? "Settings"; public string SettingsTitle => _localizationService?["Settings_Title"] ?? "Settings";
public string SettingsLanguage => _localizationService?["Settings_Language"] ?? "Language"; public string SettingsLanguage => _localizationService?["Settings_Language"] ?? "Language";
@@ -55,23 +134,48 @@ public partial class SettingsViewModel : ViewModelBase
public string SettingsProxy => _localizationService?["Settings_Proxy"] ?? "Proxy"; public string SettingsProxy => _localizationService?["Settings_Proxy"] ?? "Proxy";
public string SettingsProxyEnable => _localizationService?["Settings_ProxyEnable"] ?? "Enable Proxy"; public string SettingsProxyEnable => _localizationService?["Settings_ProxyEnable"] ?? "Enable Proxy";
public string SettingsProxyAddress => _localizationService?["Settings_ProxyAddress"] ?? "Proxy Address"; public string SettingsProxyAddress => _localizationService?["Settings_ProxyAddress"] ?? "Proxy Address";
public string SettingsProxyPort => _localizationService?["Settings_ProxyPort"] ?? "Port";
public string SettingsLyricsProvider => _localizationService?["Settings_LyricsProvider"] ?? "Lyrics Provider"; public string SettingsLyricsProvider => _localizationService?["Settings_LyricsProvider"] ?? "Lyrics Provider";
public string SettingsReset => _localizationService?["Settings_Reset"] ?? "Reset"; public string SettingsReset => _localizationService?["Settings_Reset"] ?? "Reset";
public ObservableCollection<string> AvailableEncodings { get; } = new() public string SettingsBasicSection => _localizationService?["Settings_BasicSection"] ?? "Basics";
{ public string SettingsAdvancedSection => _localizationService?["Settings_AdvancedSection"] ?? "Advanced";
"utf-8", public string SettingsShowAdvanced => _localizationService?["Settings_ShowAdvanced"] ?? "Show advanced options";
"utf-8-bom", public string SettingsLyricsSection => _localizationService?["Settings_LyricsSection"] ?? "Lyrics";
"gb2312", public string SettingsEnableTranslation => _localizationService?["Settings_EnableTranslation"] ?? "Enable translation lyrics";
"gbk" public string SettingsOneLineMode => _localizationService?["Settings_OneLineMode"] ?? "One-line mode (original + translation on same line)";
}; public string SettingsOnlyTranslation => _localizationService?["Settings_OnlyTranslation"] ?? "Output translation only";
public string SettingsSkipExisting => _localizationService?["Settings_SkipExisting"] ?? "Skip existing lyrics files";
public string SettingsFileEncoding => _localizationService?["Settings_FileEncoding"] ?? "File Encoding:";
public string SettingsLineBreak => _localizationService?["Settings_LineBreak"] ?? "Line break:";
public string SettingsRomanOutput => _localizationService?["Settings_RomanOutput"] ?? "Enable romanized output (NetEase)";
public string SettingsBlockWordSection => _localizationService?["Settings_BlockWordSection"] ?? "Tag block word dictionary";
public string SettingsBlockWordEnable => _localizationService?["Settings_BlockWordEnable"] ?? "Enable block word dictionary";
public string SettingsBlockWordPath => _localizationService?["Settings_BlockWordPath"] ?? "Dictionary file (relative to the app folder)";
public string SettingsTagProvider => _localizationService?["Settings_TagProvider"] ?? "Tag Provider";
public string SettingsPriority => _localizationService?["Settings_Priority"] ?? "Priority: ";
public string SettingsMoveUp => _localizationService?["Settings_MoveUp"] ?? "Move up";
public string SettingsMoveDown => _localizationService?["Settings_MoveDown"] ?? "Move down";
public string SettingsProviderOrderHint => _localizationService?["Settings_ProviderOrderHint"]
?? "The list order is the search order. Use the arrows to change which source is tried first.";
public string SettingsStorage => _localizationService?["Settings_Storage"] ?? "Settings file";
public string SettingsSaved => _localizationService?["Settings_Saved"] ?? "Saved";
public string SettingsSaveFailed => _localizationService?["Settings_SaveFailed"] ?? "Could not save settings";
public string SettingsProxyRestartHint => _localizationService?["Settings_ProxyRestartHint"]
?? "Proxy changes take effect the next time the app starts.";
public ObservableCollection<LyricsProviderSettingViewModel> LyricsProviders { get; } = new(); /// <summary>
/// Save feedback: only one of these is ever true, and both stay false before the first save.
/// </summary>
public bool ShowSaveSuccess => !HasSaveError && !string.IsNullOrEmpty(SaveStatusText);
public SettingsViewModel(IOptions<GlobalOptions> options, IUILocalizationService? localizationService = null) public bool ShowSaveFailure => HasSaveError && !string.IsNullOrEmpty(SaveStatusText);
public SettingsViewModel(ISettingsStore settingsStore, IUILocalizationService? localizationService = null)
{ {
_globalOptions = options.Value; _settingsStore = settingsStore;
_localizationService = localizationService; _localizationService = localizationService;
_globalOptions = settingsStore.Options;
// Subscribe to language changes // Subscribe to language changes
if (_localizationService != null) if (_localizationService != null)
@@ -81,6 +185,7 @@ public partial class SettingsViewModel : ViewModelBase
LoadSettings(); LoadSettings();
LoadLanguageSettings(); LoadLanguageSettings();
StorageHint = $"{SettingsStorage}: {_settingsStore.ConfigFilePath}";
_isLoading = false; // Allow saving after initial load _isLoading = false; // Allow saving after initial load
} }
@@ -94,8 +199,32 @@ public partial class SettingsViewModel : ViewModelBase
OnPropertyChanged(nameof(SettingsProxy)); OnPropertyChanged(nameof(SettingsProxy));
OnPropertyChanged(nameof(SettingsProxyEnable)); OnPropertyChanged(nameof(SettingsProxyEnable));
OnPropertyChanged(nameof(SettingsProxyAddress)); OnPropertyChanged(nameof(SettingsProxyAddress));
OnPropertyChanged(nameof(SettingsProxyPort));
OnPropertyChanged(nameof(SettingsLyricsProvider)); OnPropertyChanged(nameof(SettingsLyricsProvider));
OnPropertyChanged(nameof(SettingsReset)); OnPropertyChanged(nameof(SettingsReset));
OnPropertyChanged(nameof(SettingsBasicSection));
OnPropertyChanged(nameof(SettingsAdvancedSection));
OnPropertyChanged(nameof(SettingsShowAdvanced));
OnPropertyChanged(nameof(SettingsLyricsSection));
OnPropertyChanged(nameof(SettingsEnableTranslation));
OnPropertyChanged(nameof(SettingsOneLineMode));
OnPropertyChanged(nameof(SettingsOnlyTranslation));
OnPropertyChanged(nameof(SettingsSkipExisting));
OnPropertyChanged(nameof(SettingsFileEncoding));
OnPropertyChanged(nameof(SettingsLineBreak));
OnPropertyChanged(nameof(SettingsRomanOutput));
OnPropertyChanged(nameof(SettingsBlockWordSection));
OnPropertyChanged(nameof(SettingsBlockWordEnable));
OnPropertyChanged(nameof(SettingsBlockWordPath));
OnPropertyChanged(nameof(SettingsTagProvider));
OnPropertyChanged(nameof(SettingsPriority));
OnPropertyChanged(nameof(SettingsMoveUp));
OnPropertyChanged(nameof(SettingsMoveDown));
OnPropertyChanged(nameof(SettingsProviderOrderHint));
OnPropertyChanged(nameof(SettingsStorage));
OnPropertyChanged(nameof(SettingsSaved));
OnPropertyChanged(nameof(SettingsSaveFailed));
OnPropertyChanged(nameof(SettingsProxyRestartHint));
} }
private void LoadLanguageSettings() private void LoadLanguageSettings()
@@ -141,6 +270,11 @@ public partial class SettingsViewModel : ViewModelBase
partial void OnIsOneLineModeChanged(bool value) => SaveSettingsIfNotLoading(); partial void OnIsOneLineModeChanged(bool value) => SaveSettingsIfNotLoading();
partial void OnSkipExistingLyricsChanged(bool value) => SaveSettingsIfNotLoading(); partial void OnSkipExistingLyricsChanged(bool value) => SaveSettingsIfNotLoading();
partial void OnSelectedEncodingChanged(string value) => SaveSettingsIfNotLoading(); partial void OnSelectedEncodingChanged(string value) => SaveSettingsIfNotLoading();
partial void OnIsOnlyOutputTranslationChanged(bool value) => SaveSettingsIfNotLoading();
partial void OnSelectedLineBreakIndexChanged(int value) => SaveSettingsIfNotLoading();
partial void OnIsBlockWordEnabledChanged(bool value) => SaveSettingsIfNotLoading();
partial void OnBlockWordFilePathChanged(string value) => SaveSettingsIfNotLoading();
partial void OnIsRomanOutputEnabledChanged(bool value) => SaveSettingsIfNotLoading();
private void ApplyLanguage(string cultureName) private void ApplyLanguage(string cultureName)
{ {
@@ -149,10 +283,13 @@ public partial class SettingsViewModel : ViewModelBase
private void SaveSettingsIfNotLoading() private void SaveSettingsIfNotLoading()
{ {
if (!_isLoading) if (_isLoading)
{ {
SaveSettingsToFile(); return;
} }
WriteSettingsToOptions();
_ = SaveSettingsAsync();
} }
private void LoadSettings() private void LoadSettings()
@@ -170,84 +307,468 @@ public partial class SettingsViewModel : ViewModelBase
IsOneLineMode = lyricsConfig.IsOneLine; IsOneLineMode = lyricsConfig.IsOneLine;
SkipExistingLyrics = lyricsConfig.IsSkipExistLyricFiles; SkipExistingLyrics = lyricsConfig.IsSkipExistLyricFiles;
SelectedEncoding = lyricsConfig.FileEncoding ?? "utf-8"; SelectedEncoding = lyricsConfig.FileEncoding ?? "utf-8";
IsOnlyOutputTranslation = lyricsConfig.IsOnlyOutputTranslation;
SelectedLineBreakIndex = ResolveLineBreakIndex(lyricsConfig.LineBreak);
} }
// Load lyrics providers // Load block word settings
var blockWord = _globalOptions.Provider?.Tag?.BlockWord;
if (blockWord != null)
{
IsBlockWordEnabled = blockWord.IsEnable;
BlockWordFilePath = string.IsNullOrWhiteSpace(blockWord.FilePath)
? "BlockWords.json"
: 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 &&
netEase.Additional.TryGetValue("isEnableRomanOutput", out var romanValue))
{
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)
{
foreach (var provider in tagProviders.Where(p => p.Priority != -1).OrderBy(p => p.Priority))
{
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);
}
NormalizeProviderOrder(TagProviders);
}
// Lyrics providers follow the same rule as the tag providers above.
var providers = _globalOptions.Provider?.Lyric?.Plugin; var providers = _globalOptions.Provider?.Lyric?.Plugin;
if (providers != null) if (providers != null)
{ {
foreach (var provider in providers.OrderBy(p => p.Priority)) foreach (var provider in providers.Where(p => p.Priority != -1).OrderBy(p => p.Priority))
{ {
LyricsProviders.Add(new LyricsProviderSettingViewModel AddLyricsProviderRow(provider.Name, true);
{
Name = provider.Name ?? "Unknown",
Priority = provider.Priority,
IsEnabled = provider.Priority != -1
});
} }
foreach (var provider in providers.Where(p => p.Priority == -1))
{
AddLyricsProviderRow(provider.Name, false);
}
NormalizeProviderOrder(LyricsProviders);
} }
} }
private void SaveSettingsToFile() private void AddTagProviderRow(string? name, bool isEnabled)
{ {
var row = new TagInfoProviderSettingViewModel
{
Name = name ?? "Unknown",
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);
}
private void AddLyricsProviderRow(string? name, bool isEnabled)
{
var row = new LyricsProviderSettingViewModel
{
Name = name ?? "Unknown",
IsEnabled = isEnabled
};
row.MoveUpCommand = new RelayCommand(() => MoveProviderBy(LyricsProviders, row, -1));
row.MoveDownCommand = new RelayCommand(() => MoveProviderBy(LyricsProviders, row, 1));
row.PropertyChanged += OnProviderRowChanged;
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>
private void OnProviderRowChanged(object? sender, System.ComponentModel.PropertyChangedEventArgs e)
{
if (_isLoading || _isNormalizing)
{
return;
}
if (e.PropertyName is nameof(LyricsProviderSettingViewModel.IsEnabled)
or nameof(TagInfoProviderSettingViewModel.IsEnabled))
{
_isNormalizing = true;
try
{
if (sender is LyricsProviderSettingViewModel) NormalizeProviderOrder(LyricsProviders);
else if (sender is TagInfoProviderSettingViewModel) NormalizeProviderOrder(TagProviders);
}
finally
{
_isNormalizing = false;
}
SaveSettingsIfNotLoading();
return;
}
if (e.PropertyName is nameof(LyricsProviderSettingViewModel.Priority)
or nameof(TagInfoProviderSettingViewModel.Priority))
{
SaveSettingsIfNotLoading();
}
}
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>
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();
for (var target = 0; target < ordered.Count; target++)
{
var current = rows.IndexOf(ordered[target]);
if (current != target)
{
rows.Move(current, target);
}
}
var enabledCount = ordered.Count(r => r.IsEnabled);
for (var i = 0; i < ordered.Count; i++)
{
var row = ordered[i];
// 禁用行在内存里就写 -1,和配置文件里的语义保持一致;否则一旦某条路径漏掉
// ApplyProviderSelection,就会把一个不存在的「第 5 名」写回 config.yaml。
row.Priority = i < enabledCount ? i + 1 : -1;
row.PriorityLabel = i < enabledCount ? (i + 1).ToString(CultureInfo.InvariantCulture) : "—";
row.CanMoveUp = i > 0 && i < enabledCount;
row.CanMoveDown = i + 1 < enabledCount;
}
}
/// <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>
private void MoveProviderBy<T>(ObservableCollection<T> rows, T row, int offset)
where T : class, IProviderRowViewModel
{
var index = rows.IndexOf(row);
var target = index + offset;
if (index < 0 || target < 0 || target >= rows.Count || !row.IsEnabled || !rows[target].IsEnabled)
{
return;
}
_isNormalizing = true;
try try
{ {
// Update GlobalOptions with current values rows.Move(index, target);
if (_globalOptions.NetworkOptions != null) NormalizeProviderOrder(rows);
{
_globalOptions.NetworkOptions.IsEnable = IsProxyEnabled;
_globalOptions.NetworkOptions.Ip = ProxyIp;
_globalOptions.NetworkOptions.Port = ProxyPort;
}
if (_globalOptions.Provider?.Lyric?.Config != null)
{
_globalOptions.Provider.Lyric.Config.IsEnableTranslation = IsTranslationEnabled;
_globalOptions.Provider.Lyric.Config.IsOneLine = IsOneLineMode;
_globalOptions.Provider.Lyric.Config.IsSkipExistLyricFiles = SkipExistingLyrics;
_globalOptions.Provider.Lyric.Config.FileEncoding = SelectedEncoding;
}
// Serialize and save to file
var serializer = new SerializerBuilder()
.WithNamingConvention(CamelCaseNamingConvention.Instance)
.Build();
var yaml = serializer.Serialize(_globalOptions);
var configPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "config.yaml");
File.WriteAllText(configPath, yaml);
} }
catch (Exception ex) finally
{ {
// Log error but don't crash - settings save is best effort _isNormalizing = false;
System.Diagnostics.Debug.WriteLine($"Failed to save settings: {ex.Message}"); }
SaveSettingsIfNotLoading();
}
private static int ResolveLineBreakIndex(string? value)
{
for (var i = 0; i < LineBreaks.Length; i++)
{
if (string.Equals(LineBreaks[i], value, StringComparison.Ordinal))
{
return i;
}
}
return 0;
}
private void WriteSettingsToOptions()
{
if (_globalOptions.NetworkOptions != null)
{
_globalOptions.NetworkOptions.IsEnable = IsProxyEnabled;
_globalOptions.NetworkOptions.Ip = ProxyIp;
_globalOptions.NetworkOptions.Port = ProxyPort;
}
var lyricsConfig = _globalOptions.Provider?.Lyric?.Config;
if (lyricsConfig != null)
{
lyricsConfig.IsEnableTranslation = IsTranslationEnabled;
lyricsConfig.IsOneLine = IsOneLineMode;
lyricsConfig.IsSkipExistLyricFiles = SkipExistingLyrics;
lyricsConfig.FileEncoding = SelectedEncoding;
lyricsConfig.IsOnlyOutputTranslation = IsOnlyOutputTranslation;
lyricsConfig.LineBreak = CurrentLineBreak;
}
var blockWord = _globalOptions.Provider?.Tag?.BlockWord;
if (blockWord != null)
{
blockWord.IsEnable = IsBlockWordEnabled;
blockWord.FilePath = BlockWordFilePath;
}
var netEase = _globalOptions.Provider?.Lyric?.Plugin?
.FirstOrDefault(p => string.Equals(p.Name, "NetEase", StringComparison.OrdinalIgnoreCase));
if (netEase != null)
{
netEase.Additional ??= new Dictionary<string, string>();
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>
private static void ApplyProviderSelection(
IEnumerable<LyricsProviderOptions>? options,
IEnumerable<LyricsProviderSettingViewModel> viewModels)
{
if (options == null)
{
return;
}
var optionList = options.ToList();
var order = 1;
foreach (var row in viewModels)
{
var option = optionList.FirstOrDefault(o => string.Equals(o.Name, row.Name, StringComparison.OrdinalIgnoreCase));
if (option == null)
{
continue;
}
option.Priority = row.IsEnabled ? order++ : -1;
} }
} }
private static void ApplyProviderSelection(
IEnumerable<TagInfoProviderOptions>? options,
IEnumerable<TagInfoProviderSettingViewModel> viewModels)
{
if (options == null)
{
return;
}
var optionList = options.ToList();
var order = 1;
foreach (var row in viewModels)
{
var option = optionList.FirstOrDefault(o => string.Equals(o.Name, row.Name, StringComparison.OrdinalIgnoreCase));
if (option == null)
{
continue;
}
option.Priority = row.IsEnabled ? order++ : -1;
}
}
private async Task SaveSettingsAsync()
{
// 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);
if (pending != Volatile.Read(ref _saveRequestId))
{
return;
}
var result = await _settingsStore.SaveAsync().ConfigureAwait(true);
HasSaveError = !result.IsSuccess;
SaveStatusText = result.IsSuccess
? $"{SettingsSaved}: {result.FilePath}"
: $"{SettingsSaveFailed}: {result.ErrorMessage}";
StorageHint = $"{SettingsStorage}: {_settingsStore.ConfigFilePath}";
}
private int _saveRequestId;
private const int SaveDebounceMilliseconds = 400;
[RelayCommand] [RelayCommand]
private void ResetToDefaults() private async Task ResetToDefaults()
{ {
_isLoading = true; // Prevent multiple saves during reset _isLoading = true; // Prevent multiple saves during reset
IsProxyEnabled = false; IsProxyEnabled = false;
ProxyIp = "127.0.0.1"; ProxyIp = "127.0.0.1";
ProxyPort = 7890; ProxyPort = 7890;
IsTranslationEnabled = false; IsTranslationEnabled = true;
IsOneLineMode = false; IsOneLineMode = true;
SkipExistingLyrics = true; SkipExistingLyrics = false;
IsOnlyOutputTranslation = false;
SelectedEncoding = "utf-8"; SelectedEncoding = "utf-8";
SelectedLineBreakIndex = 0;
IsBlockWordEnabled = false;
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.
foreach (var row in LyricsProviders)
{
row.IsEnabled = true;
}
foreach (var row in TagProviders)
{
row.IsEnabled = true;
}
NormalizeProviderOrder(LyricsProviders);
NormalizeProviderOrder(TagProviders);
_isLoading = false; _isLoading = false;
SaveSettingsToFile(); // Save once after all resets
// Save once after all resets
WriteSettingsToOptions();
var result = await _settingsStore.SaveAsync().ConfigureAwait(true);
HasSaveError = !result.IsSuccess;
SaveStatusText = result.IsSuccess
? $"{SettingsSaved}: {result.FilePath}"
: $"{SettingsSaveFailed}: {result.ErrorMessage}";
} }
} }
public partial class LyricsProviderSettingViewModel : ObservableObject /// <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>
public interface IProviderRowViewModel
{
bool IsEnabled { get; set; }
int Priority { get; set; }
string PriorityLabel { get; set; }
bool CanMoveUp { get; set; }
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>
double RowOpacity { get; }
IRelayCommand MoveUpCommand { get; }
IRelayCommand MoveDownCommand { get; }
}
public partial class LyricsProviderSettingViewModel : ObservableObject, IProviderRowViewModel
{ {
[ObservableProperty] [ObservableProperty]
private string _name = string.Empty; private string _name = string.Empty;
[ObservableProperty]
[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>
[ObservableProperty] [ObservableProperty]
private int _priority; 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>
[ObservableProperty] [ObservableProperty]
private string _priorityLabel = string.Empty;
[ObservableProperty]
private bool _canMoveUp;
[ObservableProperty]
private bool _canMoveDown;
public double RowOpacity => IsEnabled ? 1.0 : 0.45;
public IRelayCommand MoveUpCommand { get; set; } = new RelayCommand(() => { });
public IRelayCommand MoveDownCommand { get; set; } = new RelayCommand(() => { });
}
public partial class TagInfoProviderSettingViewModel : ObservableObject, IProviderRowViewModel
{
[ObservableProperty]
private string _name = string.Empty;
[ObservableProperty]
[NotifyPropertyChangedFor(nameof(RowOpacity))]
private bool _isEnabled; private bool _isEnabled;
/// <inheritdoc cref="LyricsProviderSettingViewModel.Priority" />
[ObservableProperty]
private int _priority;
/// <inheritdoc cref="LyricsProviderSettingViewModel.PriorityLabel" />
[ObservableProperty]
private string _priorityLabel = string.Empty;
[ObservableProperty]
private bool _canMoveUp;
[ObservableProperty]
private bool _canMoveDown;
public double RowOpacity => IsEnabled ? 1.0 : 0.45;
public IRelayCommand MoveUpCommand { get; set; } = new RelayCommand(() => { });
public IRelayCommand MoveDownCommand { get; set; } = new RelayCommand(() => { });
} }
@@ -28,10 +28,10 @@
HorizontalAlignment="Right" HorizontalAlignment="Right"
Spacing="8"> Spacing="8">
<Button x:Name="CancelButton" <Button x:Name="CancelButton"
MinWidth="80" MinWidth="88"
Click="OnCancelClick" /> Click="OnCancelClick" />
<Button x:Name="ConfirmButton" <Button x:Name="ConfirmButton"
MinWidth="80" MinWidth="88"
Classes="accent" Classes="accent"
Click="OnConfirmClick" /> Click="OnConfirmClick" />
</StackPanel> </StackPanel>
@@ -2,13 +2,13 @@
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Class="ZonyLrcTools.Desktop.Views.Dialogs.MessageDialog" x:Class="ZonyLrcTools.Desktop.Views.Dialogs.MessageDialog"
Title="" Title=""
Width="400" Width="480"
Height="200" MaxHeight="520"
CanResize="False" CanResize="False"
WindowStartupLocation="CenterOwner" WindowStartupLocation="CenterOwner"
SizeToContent="Height"> SizeToContent="Height">
<Grid Margin="24" RowDefinitions="Auto,*,Auto"> <Grid Margin="24" RowDefinitions="Auto,Auto,Auto">
<!-- Title --> <!-- Title -->
<TextBlock Grid.Row="0" <TextBlock Grid.Row="0"
x:Name="TitleText" x:Name="TitleText"
@@ -16,17 +16,29 @@
FontWeight="SemiBold" FontWeight="SemiBold"
Margin="0,0,0,12" /> Margin="0,0,0,12" />
<!-- Message --> <!-- Message. 用只读 TextBox 而不是 TextBlock,这样正文可以被选中复制。 -->
<TextBlock Grid.Row="1" <TextBox Grid.Row="1"
x:Name="MessageText" x:Name="MessageText"
TextWrapping="Wrap" IsReadOnly="True"
Margin="0,0,0,20" /> AcceptsReturn="True"
TextWrapping="Wrap"
MaxHeight="380"
BorderThickness="0"
Background="Transparent"
Padding="0"
Margin="0,0,0,20" />
<!-- OK Button --> <!-- Buttons -->
<Button Grid.Row="2" <StackPanel Grid.Row="2"
x:Name="OkButton" Orientation="Horizontal"
HorizontalAlignment="Right" HorizontalAlignment="Right"
MinWidth="80" Spacing="8">
Click="OnOkClick" /> <Button x:Name="CopyButton"
MinWidth="88"
Click="OnCopyClick" />
<Button x:Name="OkButton"
MinWidth="88"
Click="OnOkClick" />
</StackPanel>
</Grid> </Grid>
</Window> </Window>
@@ -20,6 +20,18 @@ public partial class MessageDialog : Window
var localization = App.Services?.GetService<IUILocalizationService>(); var localization = App.Services?.GetService<IUILocalizationService>();
OkButton.Content = localization?["Common_OK"] ?? "OK"; OkButton.Content = localization?["Common_OK"] ?? "OK";
CopyButton.Content = localization?["Common_Copy"] ?? "Copy";
}
private async void OnCopyClick(object? sender, RoutedEventArgs e)
{
var clipboard = TopLevel.GetTopLevel(this)?.Clipboard;
if (clipboard == null)
{
return;
}
await clipboard.SetTextAsync(MessageText.Text ?? string.Empty);
} }
private void OnOkClick(object? sender, RoutedEventArgs e) private void OnOkClick(object? sender, RoutedEventArgs e)
@@ -1,6 +1,7 @@
<UserControl xmlns="https://github.com/avaloniaui" <UserControl xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:vm="using:ZonyLrcTools.Desktop.ViewModels" xmlns:vm="using:ZonyLrcTools.Desktop.ViewModels"
xmlns:loc="using:ZonyLrcTools.Desktop.Infrastructure.Localization"
x:Class="ZonyLrcTools.Desktop.Views.Pages.SettingsPage" x:Class="ZonyLrcTools.Desktop.Views.Pages.SettingsPage"
x:DataType="vm:SettingsViewModel"> x:DataType="vm:SettingsViewModel">
@@ -64,6 +65,12 @@
Minimum="1" Minimum="1"
Maximum="65535" /> Maximum="65535" />
</Grid> </Grid>
<TextBlock Text="{Binding SettingsProxyRestartHint}"
FontSize="12"
Opacity="0.55"
TextWrapping="Wrap"
IsVisible="{Binding IsProxyEnabled}" />
</StackPanel> </StackPanel>
</Border> </Border>
@@ -73,26 +80,43 @@
BoxShadow="0 2 8 0 #0D000000" BoxShadow="0 2 8 0 #0D000000"
Padding="24"> Padding="24">
<StackPanel Spacing="16"> <StackPanel Spacing="16">
<TextBlock Text="Lyrics" <TextBlock Text="{Binding SettingsLyricsSection}"
FontSize="18" FontSize="18"
FontWeight="SemiBold" /> FontWeight="SemiBold" />
<CheckBox Content="Enable translation lyrics" <CheckBox Content="{Binding SettingsEnableTranslation}"
IsChecked="{Binding IsTranslationEnabled}" /> IsChecked="{Binding IsTranslationEnabled}" />
<CheckBox Content="One-line mode (original + translation on same line)" <CheckBox Content="{Binding SettingsOneLineMode}"
IsChecked="{Binding IsOneLineMode}" /> IsChecked="{Binding IsOneLineMode}"
IsEnabled="{Binding IsTranslationEnabled}" />
<CheckBox Content="Skip existing lyrics files" <CheckBox Content="{Binding SettingsOnlyTranslation}"
IsChecked="{Binding IsOnlyOutputTranslation}"
IsEnabled="{Binding IsTranslationEnabled}" />
<CheckBox Content="{Binding SettingsSkipExisting}"
IsChecked="{Binding SkipExistingLyrics}" /> IsChecked="{Binding SkipExistingLyrics}" />
<StackPanel Orientation="Horizontal" Spacing="16"> <Grid ColumnDefinitions="Auto,180,Auto,180" RowDefinitions="Auto,Auto">
<TextBlock Text="File Encoding:" <TextBlock Grid.Row="0" Grid.Column="0"
VerticalAlignment="Center" /> Text="{Binding SettingsFileEncoding}"
<ComboBox ItemsSource="{Binding AvailableEncodings}" VerticalAlignment="Center"
Margin="0,0,12,0" />
<ComboBox Grid.Row="0" Grid.Column="1"
ItemsSource="{Binding AvailableEncodings}"
SelectedItem="{Binding SelectedEncoding}" SelectedItem="{Binding SelectedEncoding}"
Width="150" /> HorizontalAlignment="Stretch" />
</StackPanel>
<TextBlock Grid.Row="0" Grid.Column="2"
Text="{Binding SettingsLineBreak}"
VerticalAlignment="Center"
Margin="24,0,12,0" />
<ComboBox Grid.Row="0" Grid.Column="3"
ItemsSource="{Binding LineBreakDisplayNames}"
SelectedIndex="{Binding SelectedLineBreakIndex}"
HorizontalAlignment="Stretch" />
</Grid>
</StackPanel> </StackPanel>
</Border> </Border>
@@ -102,9 +126,15 @@
BoxShadow="0 2 8 0 #0D000000" BoxShadow="0 2 8 0 #0D000000"
Padding="24"> Padding="24">
<StackPanel Spacing="16"> <StackPanel Spacing="16">
<TextBlock Text="{Binding SettingsLyricsProvider}" <StackPanel Spacing="4">
FontSize="18" <TextBlock Text="{Binding SettingsLyricsProvider}"
FontWeight="SemiBold" /> FontSize="18"
FontWeight="SemiBold" />
<TextBlock Text="{Binding SettingsProviderOrderHint}"
FontSize="12"
Opacity="0.55"
TextWrapping="Wrap" />
</StackPanel>
<ItemsControl ItemsSource="{Binding LyricsProviders}"> <ItemsControl ItemsSource="{Binding LyricsProviders}">
<ItemsControl.ItemTemplate> <ItemsControl.ItemTemplate>
@@ -112,20 +142,35 @@
<Border Background="{DynamicResource AppBackgroundBrush}" <Border Background="{DynamicResource AppBackgroundBrush}"
CornerRadius="4" CornerRadius="4"
Padding="12,8" Padding="12,8"
Margin="0,4"> Margin="0,4"
<Grid ColumnDefinitions="Auto,*,Auto"> Opacity="{Binding RowOpacity}">
<Grid ColumnDefinitions="Auto,28,*,Auto,Auto">
<CheckBox Grid.Column="0" <CheckBox Grid.Column="0"
IsChecked="{Binding IsEnabled}" IsChecked="{Binding IsEnabled}"
Margin="0,0,12,0" /> Margin="0,0,12,0" />
<TextBlock Grid.Column="1" <TextBlock Grid.Column="1"
Text="{Binding PriorityLabel}"
VerticalAlignment="Center"
FontFamily="{DynamicResource NumericFontFamily}"
Opacity="0.55" />
<TextBlock Grid.Column="2"
Text="{Binding Name}" Text="{Binding Name}"
VerticalAlignment="Center" /> VerticalAlignment="Center" />
<TextBlock Grid.Column="2" <Button Grid.Column="3"
VerticalAlignment="Center" Command="{Binding MoveUpCommand}"
Opacity="0.5"> IsEnabled="{Binding CanMoveUp}"
<Run Text="Priority: " /> Classes="icon"
<Run Text="{Binding Priority}" /> Margin="0,0,4,0"
</TextBlock> ToolTip.Tip="{loc:Localize Settings_MoveUp}">
<PathIcon Data="{StaticResource ChevronUpIcon}" Width="12" Height="12" />
</Button>
<Button Grid.Column="4"
Command="{Binding MoveDownCommand}"
IsEnabled="{Binding CanMoveDown}"
Classes="icon"
ToolTip.Tip="{loc:Localize Settings_MoveDown}">
<PathIcon Data="{StaticResource ChevronDownIcon}" Width="12" Height="12" />
</Button>
</Grid> </Grid>
</Border> </Border>
</DataTemplate> </DataTemplate>
@@ -134,11 +179,124 @@
</StackPanel> </StackPanel>
</Border> </Border>
<!-- Actions --> <!-- Advanced Settings (collapsed by default) -->
<StackPanel Orientation="Horizontal" Spacing="16" HorizontalAlignment="Right"> <Border Background="{DynamicResource CardBackgroundBrush}"
<Button Content="{Binding SettingsReset}" CornerRadius="8"
Command="{Binding ResetToDefaultsCommand}" /> BoxShadow="0 2 8 0 #0D000000"
</StackPanel> Padding="24">
<StackPanel Spacing="16">
<ToggleSwitch IsChecked="{Binding IsAdvancedVisible}"
Content="{Binding SettingsShowAdvanced}"
OnContent="{Binding SettingsAdvancedSection}"
OffContent="{Binding SettingsShowAdvanced}" />
<StackPanel Spacing="16" IsVisible="{Binding IsAdvancedVisible}">
<Border Height="1" Background="{DynamicResource SeparatorBrush}" Opacity="0.5" />
<!-- Romanized output -->
<CheckBox Content="{Binding SettingsRomanOutput}"
IsChecked="{Binding IsRomanOutputEnabled}" />
<!-- Block word dictionary -->
<TextBlock Text="{Binding SettingsBlockWordSection}"
FontSize="15"
FontWeight="Medium" />
<CheckBox Content="{Binding SettingsBlockWordEnable}"
IsChecked="{Binding IsBlockWordEnabled}" />
<Grid ColumnDefinitions="Auto,*">
<TextBlock Grid.Column="0"
Text="{Binding SettingsBlockWordPath}"
VerticalAlignment="Center"
Margin="0,0,12,0" />
<TextBox Grid.Column="1"
Text="{Binding BlockWordFilePath}"
IsEnabled="{Binding IsBlockWordEnabled}" />
</Grid>
<!-- Tag providers -->
<StackPanel Spacing="4">
<TextBlock Text="{Binding SettingsTagProvider}"
FontSize="15"
FontWeight="Medium" />
<TextBlock Text="{Binding SettingsProviderOrderHint}"
FontSize="12"
Opacity="0.55"
TextWrapping="Wrap" />
</StackPanel>
<ItemsControl ItemsSource="{Binding TagProviders}">
<ItemsControl.ItemTemplate>
<DataTemplate x:DataType="vm:TagInfoProviderSettingViewModel">
<Border Background="{DynamicResource AppBackgroundBrush}"
CornerRadius="4"
Padding="12,8"
Margin="0,4"
Opacity="{Binding RowOpacity}">
<Grid ColumnDefinitions="Auto,28,*,Auto,Auto">
<CheckBox Grid.Column="0"
IsChecked="{Binding IsEnabled}"
Margin="0,0,12,0" />
<TextBlock Grid.Column="1"
Text="{Binding PriorityLabel}"
VerticalAlignment="Center"
Opacity="0.55" />
<TextBlock Grid.Column="2"
Text="{Binding Name}"
VerticalAlignment="Center" />
<Button Grid.Column="3"
Command="{Binding MoveUpCommand}"
IsEnabled="{Binding CanMoveUp}"
Classes="icon"
Margin="0,0,4,0"
ToolTip.Tip="{loc:Localize Settings_MoveUp}">
<PathIcon Data="{StaticResource ChevronUpIcon}" Width="12" Height="12" />
</Button>
<Button Grid.Column="4"
Command="{Binding MoveDownCommand}"
IsEnabled="{Binding CanMoveDown}"
Classes="icon"
ToolTip.Tip="{loc:Localize Settings_MoveDown}">
<PathIcon Data="{StaticResource ChevronDownIcon}" Width="12" Height="12" />
</Button>
</Grid>
</Border>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</StackPanel>
</StackPanel>
</Border>
<!-- Actions + status -->
<Border Background="{DynamicResource CardBackgroundBrush}"
CornerRadius="8"
BoxShadow="0 2 8 0 #0D000000"
Padding="24,14">
<Grid ColumnDefinitions="*,Auto">
<StackPanel Grid.Column="0" Spacing="4" VerticalAlignment="Center">
<TextBlock Text="{Binding StorageHint}"
FontSize="12"
Opacity="0.55"
TextTrimming="CharacterEllipsis" />
<TextBlock Text="{Binding SaveStatusText}"
FontSize="12"
Foreground="{DynamicResource SuccessColorBrush}"
IsVisible="{Binding ShowSaveSuccess}" />
<TextBlock Text="{Binding SaveStatusText}"
FontSize="12"
Foreground="{DynamicResource ErrorColorBrush}"
IsVisible="{Binding ShowSaveFailure}"
TextWrapping="Wrap" />
</StackPanel>
<Button Grid.Column="1"
Content="{Binding SettingsReset}"
Command="{Binding ResetToDefaultsCommand}"
VerticalAlignment="Center" />
</Grid>
</Border>
</StackPanel> </StackPanel>
</ScrollViewer> </ScrollViewer>