aisop/src/SopHelper.Avalonia/Models/RuntimeSettingsStore.cs

56 lines
2.3 KiB
C#

using System.IO;
using System.Text.Json;
using SopHelper.Engine.Sop;
using SopHelper.Presentation;
namespace SopHelper.Models;
public sealed class RuntimeOptions
{
public int FrameStride { get; set; } = 1;
public bool AutoResetOnComplete { get; set; } = true;
public int ResetDelaySec { get; set; } = 1;
private int _djevTimeoutSeconds = 1;
public int DjevTimeoutSeconds { get => _djevTimeoutSeconds; set => _djevTimeoutSeconds = Math.Clamp(value, 1, RealtimeDecisionPolicy.MaxTimeoutSeconds); }
public void Apply(SopConfig config)
{
config.Sop.Settings.FrameStride = Math.Max(1, FrameStride);
config.Sop.Settings.AutoResetOnComplete = AutoResetOnComplete;
config.Sop.Settings.ResetDelaySec = Math.Max(1, ResetDelaySec);
config.Sop.Settings.DjevTimeoutSeconds = DjevTimeoutSeconds;
}
}
/// <summary>执行方式独立保存,切换或导出配方不会覆盖运行设置。</summary>
public sealed class RuntimeSettingsStore(string root)
{
public static RuntimeSettingsStore Current => new(DesktopPlatform.WorkspaceRoot);
public string FilePath => Path.Combine(root, "workspace", "runtime-settings.json");
public RuntimeOptions? Read() => File.Exists(FilePath)
? JsonSerializer.Deserialize<RuntimeOptions>(File.ReadAllText(FilePath))
?? throw new InvalidDataException("运行设置内容为空") : null;
public RuntimeOptions LoadOrMigrate(SopConfig? legacy = null)
{
if (Read() is { } saved) return saved;
var options = legacy?.Sop.HasLegacySettings == true ? new RuntimeOptions
{
FrameStride = Math.Max(1, legacy.Sop.Settings.FrameStride),
AutoResetOnComplete = legacy.Sop.Settings.AutoResetOnComplete,
ResetDelaySec = Math.Max(1, legacy.Sop.Settings.ResetDelaySec),
} : new RuntimeOptions();
Save(options);
return options;
}
public void Save(RuntimeOptions options)
{
Directory.CreateDirectory(Path.GetDirectoryName(FilePath)!);
var temporary = FilePath + ".tmp";
try
{
File.WriteAllText(temporary, JsonSerializer.Serialize(options, new JsonSerializerOptions { WriteIndented = true }));
File.Move(temporary, FilePath, true);
}
finally { if (File.Exists(temporary)) File.Delete(temporary); }
}
}