-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathSettingsManager.cs
More file actions
189 lines (168 loc) · 5.87 KB
/
Copy pathSettingsManager.cs
File metadata and controls
189 lines (168 loc) · 5.87 KB
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
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
using System;
using System.Collections.Generic;
using System.IO;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace Coder.Desktop.App.Services;
/// <summary>
/// Settings contract exposing properties for app settings.
/// </summary>
public interface ISettingsManager
{
/// <summary>
/// Returns the value of the StartOnLogin setting. Returns <c>false</c> if the key is not found.
/// </summary>
bool StartOnLogin { get; set; }
/// <summary>
/// Returns the value of the ConnectOnLaunch setting. Returns <c>false</c> if the key is not found.
/// </summary>
bool ConnectOnLaunch { get; set; }
}
/// <summary>
/// Implemention of <see cref="ISettingsManager"/> that persists settings to a JSON file
/// located in the user's local application data folder.
/// </summary>
public sealed class SettingsManager : ISettingsManager
{
private readonly string _settingsFilePath;
private Settings _settings;
private readonly string _fileName = "app-settings.json";
private readonly string _appName = "CoderDesktop";
private readonly object _lock = new();
public const string ConnectOnLaunchKey = "ConnectOnLaunch";
public const string StartOnLoginKey = "StartOnLogin";
public bool StartOnLogin
{
get
{
return Read(StartOnLoginKey, false);
}
set
{
Save(StartOnLoginKey, value);
}
}
public bool ConnectOnLaunch
{
get
{
return Read(ConnectOnLaunchKey, false);
}
set
{
Save(ConnectOnLaunchKey, value);
}
}
/// <param name="settingsFilePath">
/// For unit‑tests you can pass an absolute path that already exists.
/// Otherwise the settings file will be created in the user's local application data folder.
/// </param>
public SettingsManager(string? settingsFilePath = null)
{
if (settingsFilePath is null)
{
settingsFilePath = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
}
else if (!Path.IsPathRooted(settingsFilePath))
{
throw new ArgumentException("settingsFilePath must be an absolute path if provided", nameof(settingsFilePath));
}
var folder = Path.Combine(
settingsFilePath,
_appName);
Directory.CreateDirectory(folder);
_settingsFilePath = Path.Combine(folder, _fileName);
if (!File.Exists(_settingsFilePath))
{
// Create the settings file if it doesn't exist
_settings = new();
File.WriteAllText(_settingsFilePath, JsonSerializer.Serialize(_settings, SettingsJsonContext.Default.Settings));
}
else
{
_settings = Load();
}
}
private void Save(string name, bool value)
{
lock (_lock)
{
try
{
// We lock the file for the entire operation to prevent concurrent writes
using var fs = new FileStream(_settingsFilePath,
FileMode.OpenOrCreate,
FileAccess.ReadWrite,
FileShare.None);
// Ensure cache is loaded before saving
var freshCache = JsonSerializer.Deserialize(fs, SettingsJsonContext.Default.Settings) ?? new();
_settings = freshCache;
_settings.Options[name] = JsonSerializer.SerializeToElement(value);
fs.Position = 0; // Reset stream position to the beginning before writing
JsonSerializer.Serialize(fs, _settings, SettingsJsonContext.Default.Settings);
// This ensures the file is truncated to the new length
// if the new content is shorter than the old content
fs.SetLength(fs.Position);
}
catch
{
throw new InvalidOperationException($"Failed to persist settings to {_settingsFilePath}. The file may be corrupted, malformed or locked.");
}
}
}
private bool Read(string name, bool defaultValue)
{
lock (_lock)
{
if (_settings.Options.TryGetValue(name, out var element))
{
try
{
return element.Deserialize<bool?>() ?? defaultValue;
}
catch
{
// malformed value – return default value
return defaultValue;
}
}
return defaultValue; // key not found – return default value
}
}
private Settings Load()
{
try
{
using var fs = File.OpenRead(_settingsFilePath);
return JsonSerializer.Deserialize(fs, SettingsJsonContext.Default.Settings) ?? new();
}
catch (Exception ex)
{
throw new InvalidOperationException($"Failed to load settings from {_settingsFilePath}. The file may be corrupted or malformed. Exception: {ex.Message}");
}
}
}
public class Settings
{
/// <summary>
/// User settings version. Increment this when the settings schema changes.
/// In future iterations we will be able to handle migrations when the user has
/// an older version.
/// </summary>
public int Version { get; set; }
public Dictionary<string, JsonElement> Options { get; set; }
private const int VERSION = 1; // Default version for backward compatibility
public Settings()
{
Version = VERSION;
Options = [];
}
public Settings(int? version, Dictionary<string, JsonElement> options)
{
Version = version ?? VERSION;
Options = options;
}
}
[JsonSerializable(typeof(Settings))]
[JsonSourceGenerationOptions(WriteIndented = true)]
public partial class SettingsJsonContext : JsonSerializerContext;