基于WebView2实现的Win11桌面框架,利用插件自定义
chunhualin1
2026-08-12 da97410f48a1e94d7e1fe019c69a7c847fe67ddf
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
using System.IO;
using System.Text.Json;
using System.Text.Json.Serialization;
using Moli.Desktop.Diagnostics;
using Moli.Desktop.Host;
 
namespace Moli.Desktop.Configuration;
 
public sealed class JsonConfigurationService : IConfigurationService
{
    private readonly DesktopPaths _paths;
    private readonly IDiagnosticsService _diagnostics;
    private readonly JsonSerializerOptions _jsonOptions = new()
    {
        PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
        PropertyNameCaseInsensitive = true,
        WriteIndented = true,
        Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
    };
 
    public JsonConfigurationService(DesktopPaths paths, IDiagnosticsService diagnostics)
    {
        _paths = paths;
        _diagnostics = diagnostics;
    }
 
    public Task<AppSettingsDocument> LoadAppSettingsAsync(CancellationToken cancellationToken = default)
        => LoadDocumentAsync("appsettings.json", () => new AppSettingsDocument(), cancellationToken);
 
    public Task SaveAppSettingsAsync(AppSettingsDocument document, CancellationToken cancellationToken = default)
        => SaveDocumentAsync("appsettings.json", document, cancellationToken);
 
    public Task<PluginRegistryDocument> LoadPluginRegistryAsync(CancellationToken cancellationToken = default)
        => LoadDocumentAsync("plugins.json", () => new PluginRegistryDocument(), cancellationToken);
 
    public Task SavePluginRegistryAsync(PluginRegistryDocument document, CancellationToken cancellationToken = default)
        => SaveDocumentAsync("plugins.json", document, cancellationToken);
 
    public Task<LayoutDocument> LoadLayoutAsync(CancellationToken cancellationToken = default)
        => LoadDocumentAsync("layout.json", () => new LayoutDocument(), cancellationToken);
 
    public Task SaveLayoutAsync(LayoutDocument document, CancellationToken cancellationToken = default)
        => SaveDocumentAsync("layout.json", document, cancellationToken);
 
    public async Task<ConfigurationSnapshot> LoadAllAsync(CancellationToken cancellationToken = default)
    {
        return new ConfigurationSnapshot
        {
            AppSettings = await LoadAppSettingsAsync(cancellationToken).ConfigureAwait(false),
            Plugins = await LoadPluginRegistryAsync(cancellationToken).ConfigureAwait(false),
            Layout = await LoadLayoutAsync(cancellationToken).ConfigureAwait(false)
        };
    }
 
    public async Task SaveAllAsync(ConfigurationSnapshot snapshot, CancellationToken cancellationToken = default)
    {
        await SaveAppSettingsAsync(snapshot.AppSettings, cancellationToken).ConfigureAwait(false);
        await SavePluginRegistryAsync(snapshot.Plugins, cancellationToken).ConfigureAwait(false);
        await SaveLayoutAsync(snapshot.Layout, cancellationToken).ConfigureAwait(false);
    }
 
    private async Task<T> LoadDocumentAsync<T>(string fileName, Func<T> createDefault, CancellationToken cancellationToken)
    {
        Directory.CreateDirectory(_paths.ConfigDirectory);
        var path = Path.Combine(_paths.ConfigDirectory, fileName);
 
        if (!File.Exists(path))
        {
            var created = createDefault();
            await SaveDocumentAsync(fileName, created, cancellationToken).ConfigureAwait(false);
            return created;
        }
 
        try
        {
            await using var stream = File.OpenRead(path);
            var document = await JsonSerializer.DeserializeAsync<T>(stream, _jsonOptions, cancellationToken).ConfigureAwait(false);
            if (document is null || GetSchemaVersion(document) <= 0)
            {
                throw new JsonException("Configuration document is empty or missing schemaVersion.");
            }
 
            _diagnostics.Record(DiagnosticSeverity.Info, DiagnosticCodes.ConfigurationLoaded, $"Loaded {fileName}.");
            return document;
        }
        catch (Exception ex) when (ex is JsonException or IOException or UnauthorizedAccessException)
        {
            BackupInvalidFile(path);
            var recovered = createDefault();
            await SaveDocumentAsync(fileName, recovered, cancellationToken).ConfigureAwait(false);
            _diagnostics.Record(
                DiagnosticSeverity.Warning,
                DiagnosticCodes.ConfigurationRecovered,
                $"Recovered {fileName} from invalid configuration.",
                new Dictionary<string, string> { ["exception"] = ex.GetType().Name });
            return recovered;
        }
    }
 
    private async Task SaveDocumentAsync<T>(string fileName, T document, CancellationToken cancellationToken)
    {
        Directory.CreateDirectory(_paths.ConfigDirectory);
        var path = Path.Combine(_paths.ConfigDirectory, fileName);
        var tempPath = path + ".tmp";
        var backupPath = path + ".bak";
 
        try
        {
            await using (var stream = File.Create(tempPath))
            {
                await JsonSerializer.SerializeAsync(stream, document, _jsonOptions, cancellationToken).ConfigureAwait(false);
            }
 
            if (File.Exists(path))
            {
                File.Copy(path, backupPath, overwrite: true);
            }
 
            File.Move(tempPath, path, overwrite: true);
        }
        catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
        {
            _diagnostics.Record(
                DiagnosticSeverity.Error,
                DiagnosticCodes.ConfigurationSaveFailed,
                $"Failed to save {fileName}.",
                new Dictionary<string, string> { ["exception"] = ex.GetType().Name });
            throw;
        }
    }
 
    private static int GetSchemaVersion<T>(T document)
    {
        var property = typeof(T).GetProperty("SchemaVersion");
        return property?.GetValue(document) is int version ? version : 0;
    }
 
    private static void BackupInvalidFile(string path)
    {
        if (!File.Exists(path))
        {
            return;
        }
 
        var timestamp = DateTimeOffset.Now.ToString("yyyyMMddHHmmss");
        var invalidPath = Path.Combine(
            Path.GetDirectoryName(path)!,
            $"{Path.GetFileNameWithoutExtension(path)}.invalid.{timestamp}{Path.GetExtension(path)}");
        File.Move(path, invalidPath, overwrite: true);
    }
}