-
Notifications
You must be signed in to change notification settings - Fork 4
added new settings dialog + settings manager #113
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
18 commits
Select commit
Hold shift + click to select a range
7465bb5
added new settings dialog + settings manager
ibetitsmike cd99645
WIP
ibetitsmike 779c11b
added StartupManager to handle auto-start
ibetitsmike fcefec4
settings manager moved from generic to explicit settings
ibetitsmike 39ff83c
added comments
ibetitsmike 07ec725
PR review + fmt
ibetitsmike c21072f
created Settings class to handle versioning
ibetitsmike bad5320
async handling of dependency load in app
ibetitsmike 065eda1
fmt fix
ibetitsmike fc426a8
JsonContext improvements and usage within Settings
ibetitsmike fa4fbd8
implemented a generic settings manager
ibetitsmike e7b2491
formatting
ibetitsmike ced517e
PR adjustments
ibetitsmike c4c52e2
PR review fixes
ibetitsmike 0c7567b
renamed Settings models
ibetitsmike 2824bd8
comment added to ConnectOnLaunch setting
ibetitsmike c11f6db
removed unecessary using
ibetitsmike 043c9bb
adjusted comments, linked cancellation token for file sync
ibetitsmike File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,62 @@ | ||
namespace Coder.Desktop.App.Models; | ||
|
||
public interface ISettings<T> : ICloneable<T> | ||
{ | ||
/// <summary> | ||
/// FileName where the settings are stored. | ||
/// </summary> | ||
static abstract string SettingsFileName { get; } | ||
|
||
/// <summary> | ||
/// Gets the version of the settings schema. | ||
/// </summary> | ||
int Version { get; } | ||
} | ||
|
||
public interface ICloneable<T> | ||
{ | ||
/// <summary> | ||
/// Creates a deep copy of the settings object. | ||
/// </summary> | ||
/// <returns>A new instance of the settings object with the same values.</returns> | ||
T Clone(); | ||
} | ||
|
||
/// <summary> | ||
/// CoderConnect settings class that holds the settings for the CoderConnect feature. | ||
/// </summary> | ||
public class CoderConnectSettings : ISettings<CoderConnectSettings> | ||
{ | ||
public static string SettingsFileName { get; } = "coder-connect-settings.json"; | ||
public int Version { get; set; } | ||
/// <summary> | ||
/// When this is true, CoderConnect will automatically connect to the Coder VPN when the application starts. | ||
/// </summary> | ||
public bool ConnectOnLaunch { get; set; } | ||
|
||
/// <summary> | ||
/// CoderConnect current 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> | ||
private const int VERSION = 1; | ||
|
||
public CoderConnectSettings() | ||
{ | ||
Version = VERSION; | ||
|
||
ConnectOnLaunch = false; | ||
} | ||
|
||
public CoderConnectSettings(int? version, bool connectOnLaunch) | ||
{ | ||
Version = version ?? VERSION; | ||
|
||
ConnectOnLaunch = connectOnLaunch; | ||
} | ||
|
||
public CoderConnectSettings Clone() | ||
{ | ||
return new CoderConnectSettings(Version, ConnectOnLaunch); | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,144 @@ | ||
using System; | ||
using System.IO; | ||
using System.Text.Json; | ||
using System.Threading; | ||
using System.Threading.Tasks; | ||
using Coder.Desktop.App.Models; | ||
|
||
namespace Coder.Desktop.App.Services; | ||
ibetitsmike marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
/// <summary> | ||
/// Settings contract exposing properties for app settings. | ||
/// </summary> | ||
public interface ISettingsManager<T> where T : ISettings<T>, new() | ||
{ | ||
/// <summary> | ||
/// Reads the settings from the file system or returns from cache if available. | ||
/// Returned object is always a cloned instance, so it can be modified without affecting the stored settings. | ||
/// </summary> | ||
/// <param name="ct"></param> | ||
/// <returns></returns> | ||
Task<T> Read(CancellationToken ct = default); | ||
/// <summary> | ||
/// Writes the settings to the file system. | ||
/// </summary> | ||
/// <param name="settings">Object containing the settings.</param> | ||
/// <param name="ct"></param> | ||
/// <returns></returns> | ||
Task Write(T settings, CancellationToken ct = default); | ||
} | ||
ibetitsmike marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
/// <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<T> : ISettingsManager<T> where T : ISettings<T>, new() | ||
{ | ||
private readonly string _settingsFilePath; | ||
private readonly string _appName = "CoderDesktop"; | ||
private string _fileName; | ||
|
||
private T? _cachedSettings; | ||
|
||
private readonly SemaphoreSlim _gate = new(1, 1); | ||
private static readonly TimeSpan LockTimeout = TimeSpan.FromSeconds(3); | ||
|
||
/// <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); | ||
|
||
_fileName = T.SettingsFileName; | ||
_settingsFilePath = Path.Combine(folder, _fileName); | ||
} | ||
|
||
public async Task<T> Read(CancellationToken ct = default) | ||
{ | ||
if (_cachedSettings is not null) | ||
{ | ||
// return cached settings if available | ||
return _cachedSettings.Clone(); | ||
} | ||
|
||
// try to get the lock with short timeout | ||
if (!await _gate.WaitAsync(LockTimeout, ct).ConfigureAwait(false)) | ||
throw new InvalidOperationException( | ||
$"Could not acquire the settings lock within {LockTimeout.TotalSeconds} s."); | ||
|
||
try | ||
{ | ||
if (!File.Exists(_settingsFilePath)) | ||
return new(); | ||
|
||
var json = await File.ReadAllTextAsync(_settingsFilePath, ct) | ||
.ConfigureAwait(false); | ||
|
||
// deserialize; fall back to default(T) if empty or malformed | ||
var result = JsonSerializer.Deserialize<T>(json)!; | ||
_cachedSettings = result; | ||
return _cachedSettings.Clone(); // return a fresh instance of the settings | ||
} | ||
catch (OperationCanceledException) | ||
{ | ||
throw; // propagate caller-requested cancellation | ||
} | ||
catch (Exception ex) | ||
{ | ||
throw new InvalidOperationException( | ||
$"Failed to read settings from {_settingsFilePath}. " + | ||
"The file may be corrupted, malformed or locked.", ex); | ||
} | ||
finally | ||
{ | ||
_gate.Release(); | ||
} | ||
} | ||
|
||
public async Task Write(T settings, CancellationToken ct = default) | ||
{ | ||
// try to get the lock with short timeout | ||
if (!await _gate.WaitAsync(LockTimeout, ct).ConfigureAwait(false)) | ||
throw new InvalidOperationException( | ||
$"Could not acquire the settings lock within {LockTimeout.TotalSeconds} s."); | ||
|
||
try | ||
{ | ||
// overwrite the settings file with the new settings | ||
var json = JsonSerializer.Serialize( | ||
settings, new JsonSerializerOptions() { WriteIndented = true }); | ||
_cachedSettings = settings; // cache the settings | ||
await File.WriteAllTextAsync(_settingsFilePath, json, ct) | ||
.ConfigureAwait(false); | ||
} | ||
catch (OperationCanceledException) | ||
{ | ||
throw; // let callers observe cancellation | ||
} | ||
catch (Exception ex) | ||
{ | ||
throw new InvalidOperationException( | ||
$"Failed to persist settings to {_settingsFilePath}. " + | ||
"The file may be corrupted, malformed or locked.", ex); | ||
} | ||
finally | ||
{ | ||
_gate.Release(); | ||
} | ||
} | ||
} |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.