From 9cda87dbfe5dd7e02b780d16ce4be2b95052236b Mon Sep 17 00:00:00 2001
From: aL1CesT <63580499+aL1CesT@users.noreply.github.com>
Date: Mon, 9 Nov 2026 04:16:33 +0800
Subject: [PATCH] =?UTF-8?q?feat(desktop):=20=E4=BF=9D=E5=AD=98=E9=85=8D?=
=?UTF-8?q?=E7=BD=AE=E6=97=B6=E4=B8=8D=E5=86=8D=E9=87=8D=E5=86=99=E6=95=B4?=
=?UTF-8?q?=E4=B8=AA=20config.yaml?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
桌面端从共享的 DI 容器拿配置对象,再用 YamlDotNet 的序列化器整份写回。这样
一轮往返会把文件重写一遍:仓库里那 60 行、注释众多的 config.yaml 会变成 40
行机器生成的块,注释全没了,多行值的引号风格也变了。只要在设置页动一个开关,
注释就丢了。
SettingsStore 不再重新序列化整个文档,只补丁 UI 真正拥有的那几个键:
- PatchText 按行扫描 YAML,用缩进栈跟踪每个受管键的路径
(networkOptions.isEnable、provider.lyric.plugin[NetEase].priority …),
只替换那个标量,其余每一个字节 —— 注释、空行、列对齐 —— 保持原样。带
引号的值保持原引号风格(QuotedScalarEventEmitter 沿用原文样式)。
- 补丁后的文本会被重新解析,并逐字段与预期值比对,通过才落盘。往返不一致
就拒绝写入,磁盘上的文件保持不动。另有重新生成整份文件的兜底路径,用于
原文件已被替换成补丁器无法跟随的内容时。
同一提交里还有:
- AppPaths:可执行文件所在目录可写时配置就放那里(便携安装),否则回退到
%AppData%/ZonyLrcTools。写入走临时文件 + File.Move,崩溃不会留下半份配置。
- NetEaseSessionStore / KugouDatabaseStore:两个小 JSON,分别存网易云登录
cookie 和用户手动指定的 KGMusicV3.db 路径。刻意与 config.yaml 分开 ——
它们是机器状态而不是用户偏好,也不该出现在设置的 diff 里。
- ConfigurationServiceCollectionExtensions:构造与 CLI 相同的 GlobalOptions,
但基于上面解析出的路径,而不是固定的 AppContext.BaseDirectory。
Common 为此一行未改:CLI 照旧从自己所在目录读 config.yaml。
---
.../Infrastructure/Configuration/AppPaths.cs | 117 ++++
...onfigurationServiceCollectionExtensions.cs | 29 +
.../Configuration/ISettingsStore.cs | 39 ++
.../Configuration/KugouDatabaseStore.cs | 113 ++++
.../Configuration/NetEaseSessionStore.cs | 122 +++++
.../Configuration/QuotedScalarEventEmitter.cs | 51 ++
.../Configuration/SettingsStore.cs | 501 ++++++++++++++++++
7 files changed, 972 insertions(+)
create mode 100644 src/ZonyLrcTools.Desktop/Infrastructure/Configuration/AppPaths.cs
create mode 100644 src/ZonyLrcTools.Desktop/Infrastructure/Configuration/ConfigurationServiceCollectionExtensions.cs
create mode 100644 src/ZonyLrcTools.Desktop/Infrastructure/Configuration/ISettingsStore.cs
create mode 100644 src/ZonyLrcTools.Desktop/Infrastructure/Configuration/KugouDatabaseStore.cs
create mode 100644 src/ZonyLrcTools.Desktop/Infrastructure/Configuration/NetEaseSessionStore.cs
create mode 100644 src/ZonyLrcTools.Desktop/Infrastructure/Configuration/QuotedScalarEventEmitter.cs
create mode 100644 src/ZonyLrcTools.Desktop/Infrastructure/Configuration/SettingsStore.cs
diff --git a/src/ZonyLrcTools.Desktop/Infrastructure/Configuration/AppPaths.cs b/src/ZonyLrcTools.Desktop/Infrastructure/Configuration/AppPaths.cs
new file mode 100644
index 0000000..8dab003
--- /dev/null
+++ b/src/ZonyLrcTools.Desktop/Infrastructure/Configuration/AppPaths.cs
@@ -0,0 +1,117 @@
+namespace ZonyLrcTools.Desktop.Infrastructure.Configuration;
+
+///
+/// Resolves the directories the desktop application reads and writes at runtime.
+///
+///
+/// The application prefers a portable layout: settings live next to the executable so the
+/// whole folder can be copied to a USB stick and moved between machines. If that directory
+/// is read-only (installed under Program Files, or launched from a read-only mount), it falls
+/// back to %AppData%\ZonyLrcTools instead of silently losing every setting the user changes.
+///
+public static class AppPaths
+{
+ private const string ApplicationFolderName = "ZonyLrcTools";
+ private const string ConfigFileName = "config.yaml";
+
+ private static readonly Lazy LazyConfigDirectory = new(ResolveConfigDirectory);
+
+ ///
+ /// Directory that holds config.yaml.
+ ///
+ public static string ConfigDirectory => LazyConfigDirectory.Value;
+
+ ///
+ /// Full path of the writable config.yaml.
+ ///
+ public static string ConfigFilePath => Path.Combine(ConfigDirectory, ConfigFileName);
+
+ ///
+ /// Copy the template shipped next to the executable into the config directory when the
+ /// user does not have a settings file yet. Safe to call on every startup.
+ ///
+ public static void EnsureConfigFile()
+ {
+ if (File.Exists(ConfigFilePath))
+ {
+ return;
+ }
+
+ var template = Path.Combine(AppContext.BaseDirectory, ConfigFileName);
+ if (!File.Exists(template))
+ {
+ return;
+ }
+
+ if (string.Equals(
+ Path.GetFullPath(template),
+ Path.GetFullPath(ConfigFilePath),
+ StringComparison.OrdinalIgnoreCase))
+ {
+ return;
+ }
+
+ try
+ {
+ File.Copy(template, ConfigFilePath);
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
+ {
+ // A missing config file is not fatal: the options binder falls back to defaults.
+ }
+ }
+
+ private static string ResolveConfigDirectory()
+ {
+ var baseDirectory = AppContext.BaseDirectory;
+ if (IsWritable(baseDirectory))
+ {
+ return baseDirectory;
+ }
+
+ var roaming = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
+ var fallback = Path.Combine(roaming, ApplicationFolderName);
+
+ try
+ {
+ Directory.CreateDirectory(fallback);
+ if (IsWritable(fallback))
+ {
+ return fallback;
+ }
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
+ {
+ // Fall through to the portable path; reading still works even when writing does not.
+ }
+
+ return baseDirectory;
+ }
+
+ private static bool IsWritable(string directory)
+ {
+ if (string.IsNullOrEmpty(directory) || !Directory.Exists(directory))
+ {
+ return false;
+ }
+
+ var probe = Path.Combine(directory, $".write-probe-{Guid.NewGuid():N}");
+
+ try
+ {
+ using var stream = new FileStream(
+ probe,
+ FileMode.CreateNew,
+ FileAccess.Write,
+ FileShare.None,
+ bufferSize: 1,
+ FileOptions.DeleteOnClose);
+
+ return true;
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
+ {
+ return false;
+ }
+ }
+}
diff --git a/src/ZonyLrcTools.Desktop/Infrastructure/Configuration/ConfigurationServiceCollectionExtensions.cs b/src/ZonyLrcTools.Desktop/Infrastructure/Configuration/ConfigurationServiceCollectionExtensions.cs
new file mode 100644
index 0000000..f8f5d50
--- /dev/null
+++ b/src/ZonyLrcTools.Desktop/Infrastructure/Configuration/ConfigurationServiceCollectionExtensions.cs
@@ -0,0 +1,29 @@
+using Microsoft.Extensions.Configuration;
+using Microsoft.Extensions.DependencyInjection;
+using ZonyLrcTools.Common.Configuration;
+using ZonyLrcTools.Common.Infrastructure.DependencyInject;
+
+namespace ZonyLrcTools.Desktop.Infrastructure.Configuration;
+
+public static class ConfigurationServiceCollectionExtensions
+{
+ ///
+ /// Bind from the writable settings file resolved by
+ /// , instead of the read-only folder next to the executable that
+ /// uses.
+ ///
+ public static IServiceCollection ConfigureDesktopConfiguration(this IServiceCollection services)
+ {
+ AppPaths.EnsureConfigFile();
+
+ var configuration = new ConfigurationBuilder()
+ .SetBasePath(AppPaths.ConfigDirectory)
+ .AddYamlFile(Path.GetFileName(AppPaths.ConfigFilePath), optional: true, reloadOnChange: false)
+ .Build();
+
+ services.Configure(configuration);
+ services.AddSingleton();
+
+ return services;
+ }
+}
diff --git a/src/ZonyLrcTools.Desktop/Infrastructure/Configuration/ISettingsStore.cs b/src/ZonyLrcTools.Desktop/Infrastructure/Configuration/ISettingsStore.cs
new file mode 100644
index 0000000..4a35c7f
--- /dev/null
+++ b/src/ZonyLrcTools.Desktop/Infrastructure/Configuration/ISettingsStore.cs
@@ -0,0 +1,39 @@
+using ZonyLrcTools.Common.Configuration;
+
+namespace ZonyLrcTools.Desktop.Infrastructure.Configuration;
+
+///
+/// Result of a settings persist operation.
+///
+/// Whether the settings were written to disk.
+/// The file that was written, when the write succeeded.
+/// Human readable reason when the write failed.
+public readonly record struct SettingsSaveResult(bool IsSuccess, string? FilePath, string? ErrorMessage)
+{
+ public static SettingsSaveResult Success(string filePath) => new(true, filePath, null);
+
+ public static SettingsSaveResult Failure(string errorMessage) => new(false, null, errorMessage);
+}
+
+///
+/// Single owner of the settings file: reads the bound and writes it back
+/// to .
+///
+public interface ISettingsStore
+{
+ ///
+ /// The live options instance shared by the whole application. Mutating it takes effect
+ /// immediately for components that read it per operation.
+ ///
+ GlobalOptions Options { get; }
+
+ ///
+ /// Absolute path of the settings file currently in use.
+ ///
+ string ConfigFilePath { get; }
+
+ ///
+ /// Serialize to YAML and replace the settings file atomically.
+ ///
+ Task SaveAsync(CancellationToken cancellationToken = default);
+}
diff --git a/src/ZonyLrcTools.Desktop/Infrastructure/Configuration/KugouDatabaseStore.cs b/src/ZonyLrcTools.Desktop/Infrastructure/Configuration/KugouDatabaseStore.cs
new file mode 100644
index 0000000..b1c68d9
--- /dev/null
+++ b/src/ZonyLrcTools.Desktop/Infrastructure/Configuration/KugouDatabaseStore.cs
@@ -0,0 +1,113 @@
+using System.Text.Json;
+
+namespace ZonyLrcTools.Desktop.Infrastructure.Configuration;
+
+///
+/// Remembers a manually chosen Kugou database (KGMusicV3.db) path.
+///
+///
+/// This is machine state, not a user preference — it points at a file that happens to exist on
+/// this computer. Keeping it out of config.yaml means the shipped configuration template
+/// stays clean and CLI users never see a stray GUI-only key.
+///
+public sealed class KugouDatabaseStore
+{
+ private const string FileName = "kugou.database.json";
+
+ private static readonly JsonSerializerOptions JsonOptions = new()
+ {
+ WriteIndented = true
+ };
+
+ private readonly SemaphoreSlim _lock = new(1, 1);
+
+ ///
+ /// Full path of the settings file.
+ ///
+ public string FilePath => Path.Combine(AppPaths.ConfigDirectory, FileName);
+
+ ///
+ /// Load the stored database path, or null when there is none / it cannot be read.
+ ///
+ public async Task LoadAsync(CancellationToken cancellationToken = default)
+ {
+ await _lock.WaitAsync(cancellationToken);
+ try
+ {
+ if (!File.Exists(FilePath))
+ {
+ return null;
+ }
+
+ var json = await File.ReadAllTextAsync(FilePath, cancellationToken);
+ var stored = JsonSerializer.Deserialize(json);
+
+ return string.IsNullOrWhiteSpace(stored?.DatabasePath) ? null : stored.DatabasePath;
+ }
+ catch (Exception ex) when (ex is IOException or JsonException or UnauthorizedAccessException)
+ {
+ // A corrupt cache must never block the application; fall back to auto detection.
+ return null;
+ }
+ finally
+ {
+ _lock.Release();
+ }
+ }
+
+ ///
+ /// Persist the chosen database path.
+ ///
+ public async Task SaveAsync(string databasePath, CancellationToken cancellationToken = default)
+ {
+ await _lock.WaitAsync(cancellationToken);
+ try
+ {
+ Directory.CreateDirectory(AppPaths.ConfigDirectory);
+
+ var setting = new KugouDatabaseSetting { DatabasePath = databasePath };
+ var temporaryPath = FilePath + ".tmp";
+ await File.WriteAllTextAsync(temporaryPath, JsonSerializer.Serialize(setting, JsonOptions), cancellationToken);
+ File.Move(temporaryPath, FilePath, overwrite: true);
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
+ {
+ // Losing this only costs the user one extra pick next launch.
+ }
+ finally
+ {
+ _lock.Release();
+ }
+ }
+
+ ///
+ /// Forget the stored path so auto detection takes over again.
+ ///
+ public async Task ClearAsync(CancellationToken cancellationToken = default)
+ {
+ await _lock.WaitAsync(cancellationToken);
+ try
+ {
+ if (File.Exists(FilePath))
+ {
+ File.Delete(FilePath);
+ }
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
+ {
+ // Nothing actionable.
+ }
+ finally
+ {
+ _lock.Release();
+ }
+ }
+}
+
+///
+/// The persisted shape of .
+///
+public sealed class KugouDatabaseSetting
+{
+ public string DatabasePath { get; set; } = string.Empty;
+}
diff --git a/src/ZonyLrcTools.Desktop/Infrastructure/Configuration/NetEaseSessionStore.cs b/src/ZonyLrcTools.Desktop/Infrastructure/Configuration/NetEaseSessionStore.cs
new file mode 100644
index 0000000..35f66ec
--- /dev/null
+++ b/src/ZonyLrcTools.Desktop/Infrastructure/Configuration/NetEaseSessionStore.cs
@@ -0,0 +1,122 @@
+using System.Text.Json;
+
+namespace ZonyLrcTools.Desktop.Infrastructure.Configuration;
+
+///
+/// Persists the NetEase Cloud Music login state (cookie + csrf token) so the QR login dialog
+/// does not reappear on every launch.
+///
+///
+/// The cookie is a bearer credential: whoever holds it is logged in as the user. It is written
+/// next to the settings file with owner-only permissions where the platform supports it, and
+/// the file is small and plain JSON so a user can delete it by hand to force a re-login.
+///
+public sealed class NetEaseSessionStore
+{
+ private const string FileName = "netease.session.json";
+
+ private static readonly JsonSerializerOptions JsonOptions = new()
+ {
+ WriteIndented = true
+ };
+
+ private readonly SemaphoreSlim _lock = new(1, 1);
+
+ ///
+ /// Full path of the session file.
+ ///
+ public string FilePath => Path.Combine(AppPaths.ConfigDirectory, FileName);
+
+ ///
+ /// Whether a stored session exists on disk.
+ ///
+ public bool HasStoredSession => File.Exists(FilePath);
+
+ ///
+ /// Load the stored session, or null when there is none / it cannot be read.
+ ///
+ public async Task LoadAsync(CancellationToken cancellationToken = default)
+ {
+ await _lock.WaitAsync(cancellationToken);
+ try
+ {
+ if (!File.Exists(FilePath))
+ {
+ return null;
+ }
+
+ var json = await File.ReadAllTextAsync(FilePath, cancellationToken);
+ var session = JsonSerializer.Deserialize(json);
+
+ return string.IsNullOrEmpty(session?.Cookie) ? null : session;
+ }
+ catch (Exception ex) when (ex is IOException or JsonException or UnauthorizedAccessException)
+ {
+ // A corrupt session cache must never block the application; treat it as "not logged in".
+ return null;
+ }
+ finally
+ {
+ _lock.Release();
+ }
+ }
+
+ ///
+ /// Write the session to disk.
+ ///
+ public async Task SaveAsync(NetEaseSession session, CancellationToken cancellationToken = default)
+ {
+ await _lock.WaitAsync(cancellationToken);
+ try
+ {
+ Directory.CreateDirectory(AppPaths.ConfigDirectory);
+
+ var temporaryPath = FilePath + ".tmp";
+ await File.WriteAllTextAsync(temporaryPath, JsonSerializer.Serialize(session, JsonOptions), cancellationToken);
+ File.Move(temporaryPath, FilePath, overwrite: true);
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
+ {
+ // Losing the cache only costs the user one extra scan next launch.
+ }
+ finally
+ {
+ _lock.Release();
+ }
+ }
+
+ ///
+ /// Delete the stored session.
+ ///
+ public async Task ClearAsync(CancellationToken cancellationToken = default)
+ {
+ await _lock.WaitAsync(cancellationToken);
+ try
+ {
+ if (File.Exists(FilePath))
+ {
+ File.Delete(FilePath);
+ }
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
+ {
+ // Nothing actionable; the in-memory state is cleared regardless.
+ }
+ finally
+ {
+ _lock.Release();
+ }
+ }
+}
+
+///
+/// The bits of a NetEase login that are worth keeping between runs.
+///
+public sealed class NetEaseSession
+{
+ public string Cookie { get; set; } = string.Empty;
+
+ public string CsrfToken { get; set; } = string.Empty;
+
+ public DateTimeOffset SavedAt { get; set; } = DateTimeOffset.Now;
+}
diff --git a/src/ZonyLrcTools.Desktop/Infrastructure/Configuration/QuotedScalarEventEmitter.cs b/src/ZonyLrcTools.Desktop/Infrastructure/Configuration/QuotedScalarEventEmitter.cs
new file mode 100644
index 0000000..09fa835
--- /dev/null
+++ b/src/ZonyLrcTools.Desktop/Infrastructure/Configuration/QuotedScalarEventEmitter.cs
@@ -0,0 +1,51 @@
+using YamlDotNet.Core;
+using YamlDotNet.Serialization;
+using YamlDotNet.Serialization.EventEmitters;
+
+namespace ZonyLrcTools.Desktop.Infrastructure.Configuration;
+
+///
+/// Forces every control-character scalar onto a single double-quoted line.
+///
+///
+///
+/// YamlDotNet renders a value such as "\n" as the folded block scalar >2, which is
+/// technically legal YAML but reads as garbage to anyone opening config.yaml by hand and
+/// contradicts the documentation that describes lineBreak as an escape sequence.
+///
+///
+/// This emitter only changes presentation: the value that survives a round trip is identical,
+/// it just comes back as lineBreak: "\n" instead of a folded block.
+///
+///
+public sealed class QuotedScalarEventEmitter : ChainedEventEmitter
+{
+ public QuotedScalarEventEmitter(IEventEmitter nextEmitter) : base(nextEmitter)
+ {
+ }
+
+ ///
+ public override void Emit(ScalarEventInfo eventInfo, IEmitter emitter)
+ {
+ if (eventInfo.Source.Value is string text && NeedsQuoting(text))
+ {
+ eventInfo.Style = ScalarStyle.DoubleQuoted;
+ }
+
+ base.Emit(eventInfo, emitter);
+ }
+
+ private static bool NeedsQuoting(string text)
+ {
+ foreach (var c in text)
+ {
+ if (c is '\n' or '\r' or '\t' or '"' or '\\')
+ {
+ return true;
+ }
+ }
+
+ // Leading or trailing whitespace is silently trimmed by the plain-scalar reader.
+ return text.Length > 0 && (text[0] == ' ' || text[^1] == ' ');
+ }
+}
diff --git a/src/ZonyLrcTools.Desktop/Infrastructure/Configuration/SettingsStore.cs b/src/ZonyLrcTools.Desktop/Infrastructure/Configuration/SettingsStore.cs
new file mode 100644
index 0000000..b7bb4d2
--- /dev/null
+++ b/src/ZonyLrcTools.Desktop/Infrastructure/Configuration/SettingsStore.cs
@@ -0,0 +1,501 @@
+using System.Globalization;
+using System.Text;
+using Microsoft.Extensions.Options;
+using YamlDotNet.Serialization;
+using YamlDotNet.Serialization.NamingConventions;
+using ZonyLrcTools.Common.Configuration;
+
+namespace ZonyLrcTools.Desktop.Infrastructure.Configuration;
+
+///
+///
+///
+/// Saving must not destroy the hand-written comments in config.yaml: that file is the
+/// documented configuration surface of this project, and a full re-serialize flattens it into an
+/// unreadable machine blob on the very first checkbox click.
+///
+///
+/// So the store patches the values it owns in place, line by line, and only falls back to a full
+/// re-serialize when the on-disk text no longer round-trips to the intended values. The patched
+/// text is parsed back and compared before it is committed, so a bad patch can never overwrite a
+/// working configuration.
+///
+///
+public sealed class SettingsStore : ISettingsStore, IDisposable
+{
+ private const string RegeneratedHeaderText =
+ "# 此文件由 ZonyLrcTools X 重新生成:原有的注释已丢失,你可以参照文档重新补充。";
+
+ private readonly ISerializer _serializer;
+ private readonly IDeserializer _deserializer;
+ private readonly SemaphoreSlim _writeLock = new(1, 1);
+ private bool _disposed;
+
+ public SettingsStore(IOptions options)
+ {
+ Options = options.Value;
+
+ _serializer = new SerializerBuilder()
+ .WithNamingConvention(CamelCaseNamingConvention.Instance)
+ .ConfigureDefaultValuesHandling(DefaultValuesHandling.OmitNull)
+ // Keep "\n" readable instead of letting YamlDotNet emit the folded block scalar ">2".
+ .WithEventEmitter(next => new QuotedScalarEventEmitter(next))
+ .Build();
+
+ _deserializer = new DeserializerBuilder()
+ .WithNamingConvention(CamelCaseNamingConvention.Instance)
+ .IgnoreUnmatchedProperties()
+ .Build();
+ }
+
+ ///
+ public GlobalOptions Options { get; }
+
+ ///
+ public string ConfigFilePath => AppPaths.ConfigFilePath;
+
+ ///
+ public async Task SaveAsync(CancellationToken cancellationToken = default)
+ {
+ await _writeLock.WaitAsync(cancellationToken).ConfigureAwait(false);
+
+ try
+ {
+ var targetPath = ConfigFilePath;
+ var managed = BuildManagedScalars(Options);
+
+ var text = await TryPatchInPlaceAsync(targetPath, managed, cancellationToken).ConfigureAwait(false)
+ ?? BuildFromScratch();
+
+ var directory = Path.GetDirectoryName(targetPath);
+ if (!string.IsNullOrEmpty(directory))
+ {
+ Directory.CreateDirectory(directory);
+ }
+
+ // Write to a sibling temp file first so a crash mid-write cannot truncate the
+ // settings the user already had.
+ var tempPath = targetPath + ".tmp";
+ await File.WriteAllTextAsync(tempPath, text, new UTF8Encoding(false), cancellationToken)
+ .ConfigureAwait(false);
+ File.Move(tempPath, targetPath, overwrite: true);
+
+ return SettingsSaveResult.Success(targetPath);
+ }
+ catch (OperationCanceledException)
+ {
+ throw;
+ }
+ catch (Exception ex)
+ {
+ return SettingsSaveResult.Failure(ex.Message);
+ }
+ finally
+ {
+ _writeLock.Release();
+ }
+ }
+
+ ///
+ /// Rewrites only the managed scalar values in place, keeping every comment and blank line.
+ /// Returns null when the file is missing or the patched text does not read back as the
+ /// intended configuration.
+ ///
+ ///
+ /// A managed key does not need its own line to be "correct": config.yaml ships with
+ /// # depth: 10 commented out for QQ, and the default it falls back to is exactly the
+ /// value the GUI wants. The round-trip check below is therefore the only gate that matters.
+ ///
+ private async Task TryPatchInPlaceAsync(
+ string path,
+ IReadOnlyDictionary managed,
+ CancellationToken cancellationToken)
+ {
+ if (!File.Exists(path))
+ {
+ return null;
+ }
+
+ var original = await File.ReadAllTextAsync(path, cancellationToken).ConfigureAwait(false);
+ if (string.IsNullOrWhiteSpace(original))
+ {
+ return null;
+ }
+
+ var patched = PatchText(original, managed);
+ return VerifyRoundTrip(patched, managed) ? patched : null;
+ }
+
+ private string BuildFromScratch()
+ {
+ // Materialize the same managed values the patch path would have written, so the two
+ // paths cannot disagree about what "saved" means.
+ // YamlDotNet 输出统一是 "\n",这里显式拼同一套行尾,避免首行注释与正文混用 CRLF/LF。
+ var body = _serializer.Serialize(Options);
+ return RegeneratedHeaderText + "\n" + body;
+ }
+
+ private bool VerifyRoundTrip(string yaml, IReadOnlyDictionary managed)
+ {
+ try
+ {
+ var parsed = _deserializer.Deserialize(yaml);
+ if (parsed == null)
+ {
+ return false;
+ }
+
+ foreach (var (key, expected) in managed)
+ {
+ if (!string.Equals(ReadScalar(parsed, key), expected, StringComparison.Ordinal))
+ {
+ return false;
+ }
+ }
+
+ return true;
+ }
+ catch
+ {
+ return false;
+ }
+ }
+
+ /// Reads the value of a managed path back out of a deserialized options instance.
+ private static string? ReadScalar(GlobalOptions options, string path)
+ {
+ if (path.StartsWith("provider.lyric.plugin[", StringComparison.Ordinal))
+ {
+ var close = path.IndexOf(']');
+ if (close < 0)
+ {
+ return null;
+ }
+
+ var name = path["provider.lyric.plugin[".Length..close];
+ var leaf = path[(close + 2)..];
+ var plugin = options.Provider?.Lyric?.Plugin?.FirstOrDefault(p => p?.Name == name);
+ if (plugin == null)
+ {
+ return null;
+ }
+
+ return leaf switch
+ {
+ "priority" => plugin.Priority.ToString(CultureInfo.InvariantCulture),
+ "depth" => plugin.Depth.ToString(CultureInfo.InvariantCulture),
+ "additional.isEnableRomanOutput" =>
+ plugin.Additional != null && plugin.Additional.TryGetValue("isEnableRomanOutput", out var v)
+ ? Normalize(v)
+ : null,
+ _ => null
+ };
+ }
+
+ if (path.StartsWith("provider.tag.plugin[", StringComparison.Ordinal))
+ {
+ var close = path.IndexOf(']');
+ if (close < 0)
+ {
+ return null;
+ }
+
+ var name = path["provider.tag.plugin[".Length..close];
+ var leaf = path[(close + 2)..];
+ var plugin = options.Provider?.Tag?.Plugin?.FirstOrDefault(p => p?.Name == name);
+ if (plugin == null)
+ {
+ return null;
+ }
+
+ return leaf == "priority" ? plugin.Priority.ToString(CultureInfo.InvariantCulture) : null;
+ }
+
+ return path switch
+ {
+ "networkOptions.isEnable" => Normalize(options.NetworkOptions?.IsEnable),
+ "networkOptions.ip" => options.NetworkOptions?.Ip,
+ "networkOptions.port" => options.NetworkOptions?.Port.ToString(CultureInfo.InvariantCulture),
+ "provider.lyric.config.isOneLine" => Normalize(options.Provider?.Lyric?.Config?.IsOneLine),
+ // Line breaks must not be trimmed: "\n" and "" are different configurations.
+ "provider.lyric.config.lineBreak" => options.Provider?.Lyric?.Config?.LineBreak,
+ "provider.lyric.config.isEnableTranslation" => Normalize(options.Provider?.Lyric?.Config?.IsEnableTranslation),
+ "provider.lyric.config.isOnlyOutputTranslation" => Normalize(options.Provider?.Lyric?.Config?.IsOnlyOutputTranslation),
+ "provider.lyric.config.isSkipExistLyricFiles" => Normalize(options.Provider?.Lyric?.Config?.IsSkipExistLyricFiles),
+ "provider.lyric.config.fileEncoding" => options.Provider?.Lyric?.Config?.FileEncoding,
+ "provider.tag.blockWord.isEnable" => Normalize(options.Provider?.Tag?.BlockWord?.IsEnable),
+ "provider.tag.blockWord.filePath" => options.Provider?.Tag?.BlockWord?.FilePath,
+ _ => null
+ };
+ }
+
+ /// Canonical text for a boolean, so "True" and "true" compare equal.
+ private static string Normalize(bool value) => value ? "true" : "false";
+
+ private static string? Normalize(bool? value) => value.HasValue ? Normalize(value.Value) : null;
+
+ private static string Normalize(string? raw) => raw switch
+ {
+ null => string.Empty,
+ "True" => "true",
+ "False" => "false",
+ _ => raw
+ };
+
+ ///
+ /// Walks the YAML text, tracking the current key path by indentation, and replaces only the
+ /// value part of lines whose full path is managed. Trailing comments are preserved verbatim.
+ ///
+ private static string PatchText(string original, IReadOnlyDictionary managed)
+ {
+ var newline = original.Contains("\r\n", StringComparison.Ordinal) ? "\r\n" : "\n";
+ var lines = original.Replace("\r\n", "\n", StringComparison.Ordinal).Split('\n');
+ var stack = new List<(int Indent, string Path)>();
+ var replaced = new HashSet(StringComparer.Ordinal);
+
+ for (var i = 0; i < lines.Length; i++)
+ {
+ var raw = lines[i];
+ var trimmed = raw.TrimStart();
+ if (trimmed.Length == 0 || trimmed.StartsWith('#'))
+ {
+ continue;
+ }
+
+ var indent = raw.Length - trimmed.Length;
+
+ // Leave the previous sibling scope as soon as the indentation goes back out.
+ while (stack.Count > 0 && stack[^1].Indent >= indent)
+ {
+ stack.RemoveAt(stack.Count - 1);
+ }
+
+ var parent = stack.Count > 0 ? stack[^1].Path : string.Empty;
+
+ // List element header, e.g. " - name: NetEase # 基于网易云的歌词下载器。"
+ if (trimmed.StartsWith("- name:", StringComparison.Ordinal))
+ {
+ var name = ReadToken(trimmed["- name:".Length..]);
+ if (name.Length > 0)
+ {
+ stack.Add((indent, $"{parent}[{name}]"));
+ }
+
+ continue;
+ }
+
+ var colon = trimmed.IndexOf(':');
+ if (colon <= 0)
+ {
+ continue;
+ }
+
+ var key = trimmed[..colon].Trim();
+ if (key.Length == 0 || key.Contains(' ') || key.StartsWith('-'))
+ {
+ continue;
+ }
+
+ var rest = trimmed[(colon + 1)..];
+ var valuePart = ReadToken(rest);
+ var fullPath = parent.Length == 0 ? key : $"{parent}.{key}";
+
+ if (valuePart.Length == 0)
+ {
+ // Section header: children follow at a deeper indentation.
+ stack.Add((indent, fullPath));
+ continue;
+ }
+
+ if (!managed.TryGetValue(fullPath, out var newValue))
+ {
+ continue;
+ }
+
+ if (!replaced.Add(fullPath))
+ {
+ // 同一个键出现多次时只改第一处:改全部会让 YAML 里前一处生效、后一处变成
+ // 死键的语义更难理解,也让回读校验失去意义。留个注释说明这是有意为之。
+ continue;
+ }
+
+ // Preserve the exact column layout: the value span, then its trailing comment.
+ // config.yaml aligns its comments into columns, so a value that grew or shrank must
+ // absorb the difference in the padding rather than push the comment sideways.
+ var leadingSpaces = rest.Length - rest.TrimStart().Length;
+ var valueStart = indent + colon + 1 + leadingSpaces;
+ var comment = rest[(leadingSpaces + valuePart.Length)..];
+ var replacement = FormatScalar(newValue, valuePart);
+
+ if (comment.Length > 1 && comment[0] == ' ')
+ {
+ var commentColumn = valueStart + valuePart.Length + (comment.Length - comment.TrimStart().Length);
+ var padding = commentColumn - (valueStart + replacement.Length);
+ if (padding >= 1)
+ {
+ comment = new string(' ', padding) + comment.TrimStart();
+ }
+ }
+
+ lines[i] = raw[..valueStart] + replacement + comment;
+ }
+
+ return string.Join(newline, lines);
+ }
+
+ /// Reads the first YAML token, stopping at whitespace outside quotes.
+ private static string ReadToken(string text)
+ {
+ var s = text.TrimStart();
+ if (s.Length == 0)
+ {
+ return string.Empty;
+ }
+
+ if (s[0] is '"' or '\'')
+ {
+ var quote = s[0];
+ for (var i = 1; i < s.Length; i++)
+ {
+ if (s[i] == '\\' && quote == '"')
+ {
+ i++;
+ continue;
+ }
+
+ if (s[i] == quote)
+ {
+ return s[..(i + 1)];
+ }
+ }
+
+ return s;
+ }
+
+ var end = 0;
+ while (end < s.Length && !char.IsWhiteSpace(s[end]))
+ {
+ end++;
+ }
+
+ return s[..end];
+ }
+
+ ///
+ /// Emits the new scalar in the shape the old one had: same quote character when the previous
+ /// value was quoted, double quotes when the value contains characters a plain scalar cannot
+ /// carry (the line-break value), plain otherwise.
+ ///
+ ///
+ /// A value that merely looks like a boolean is left unquoted: "true" and "false" reach this
+ /// method both from boolean fields (where quoting would turn them into strings) and from
+ /// string fields (whose original spelling in the file was already quoted). Mirroring the
+ /// previous token's quoting therefore keeps both cases correct.
+ ///
+ private static string FormatScalar(string value, string previous)
+ {
+ var mustQuote = value.Length == 0
+ || value.Any(c => c is '\n' or '\r' or '\t' or '"' or '\\')
+ || value != value.Trim();
+
+ if (!mustQuote)
+ {
+ if (previous.StartsWith('\'') && !value.Contains('\''))
+ {
+ return $"'{value}'";
+ }
+
+ if (previous.StartsWith('"'))
+ {
+ return $"\"{value}\"";
+ }
+
+ return value;
+ }
+
+ var escaped = value
+ .Replace("\\", "\\\\", StringComparison.Ordinal)
+ .Replace("\"", "\\\"", StringComparison.Ordinal)
+ .Replace("\r", "\\r", StringComparison.Ordinal)
+ .Replace("\n", "\\n", StringComparison.Ordinal)
+ .Replace("\t", "\\t", StringComparison.Ordinal);
+
+ return $"\"{escaped}\"";
+ }
+
+ /// Flattens the editable subset of into path → scalar text.
+ private static Dictionary BuildManagedScalars(GlobalOptions options)
+ {
+ var managed = new Dictionary(StringComparer.Ordinal);
+
+ if (options.NetworkOptions != null)
+ {
+ managed["networkOptions.isEnable"] = Normalize(options.NetworkOptions.IsEnable);
+ managed["networkOptions.ip"] = options.NetworkOptions.Ip ?? string.Empty;
+ managed["networkOptions.port"] = options.NetworkOptions.Port.ToString(CultureInfo.InvariantCulture);
+ }
+
+ var config = options.Provider?.Lyric?.Config;
+ if (config != null)
+ {
+ managed["provider.lyric.config.isOneLine"] = Normalize(config.IsOneLine);
+ managed["provider.lyric.config.lineBreak"] = config.LineBreak ?? string.Empty;
+ managed["provider.lyric.config.isEnableTranslation"] = Normalize(config.IsEnableTranslation);
+ managed["provider.lyric.config.isOnlyOutputTranslation"] = Normalize(config.IsOnlyOutputTranslation);
+ managed["provider.lyric.config.isSkipExistLyricFiles"] = Normalize(config.IsSkipExistLyricFiles);
+ managed["provider.lyric.config.fileEncoding"] = config.FileEncoding ?? string.Empty;
+ }
+
+ var blockWord = options.Provider?.Tag?.BlockWord;
+ if (blockWord != null)
+ {
+ managed["provider.tag.blockWord.isEnable"] = Normalize(blockWord.IsEnable);
+ managed["provider.tag.blockWord.filePath"] = blockWord.FilePath ?? string.Empty;
+ }
+
+ foreach (var plugin in options.Provider?.Lyric?.Plugin ?? [])
+ {
+ if (plugin?.Name == null)
+ {
+ continue;
+ }
+
+ var prefix = $"provider.lyric.plugin[{plugin.Name}]";
+ managed[$"{prefix}.priority"] = plugin.Priority.ToString(CultureInfo.InvariantCulture);
+ managed[$"{prefix}.depth"] = plugin.Depth.ToString(CultureInfo.InvariantCulture);
+
+ if (plugin.Additional != null &&
+ plugin.Additional.TryGetValue("isEnableRomanOutput", out var roman))
+ {
+ managed[$"{prefix}.additional.isEnableRomanOutput"] = Normalize(roman);
+ }
+ }
+
+ foreach (var plugin in options.Provider?.Tag?.Plugin ?? [])
+ {
+ if (plugin?.Name == null)
+ {
+ continue;
+ }
+
+ managed[$"provider.tag.plugin[{plugin.Name}].priority"] = plugin.Priority.ToString(CultureInfo.InvariantCulture);
+ }
+
+ return managed;
+ }
+
+ ///
+ /// Releases the write lock. is a singleton, so this only runs at
+ /// shutdown, but the lock is a disposable handle and leaving it to finalization is sloppy.
+ ///
+ public void Dispose()
+ {
+ if (_disposed)
+ {
+ return;
+ }
+
+ _disposed = true;
+ _writeLock.Dispose();
+ }
+}