Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

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 ourterms of service andprivacy statement. We’ll occasionally send you account related emails.

Already on GitHub?Sign in to your account

Merged
ibetitsmike merged 18 commits intomainfrommike/57-starting-coder-desktop-on-boot
Jun 10, 2025
Merged
Show file tree
Hide file tree
Changes fromall commits
Commits
Show all changes
18 commits
Select commitHold shift + click to select a range
7465bb5
added new settings dialog + settings manager
ibetitsmikeMay 29, 2025
cd99645
WIP
ibetitsmikeJun 2, 2025
779c11b
added StartupManager to handle auto-start
ibetitsmikeJun 2, 2025
fcefec4
settings manager moved from generic to explicit settings
ibetitsmikeJun 2, 2025
39ff83c
added comments
ibetitsmikeJun 2, 2025
07ec725
PR review + fmt
ibetitsmikeJun 2, 2025
c21072f
created Settings class to handle versioning
ibetitsmikeJun 3, 2025
bad5320
async handling of dependency load in app
ibetitsmikeJun 3, 2025
065eda1
fmt fix
ibetitsmikeJun 3, 2025
fc426a8
JsonContext improvements and usage within Settings
ibetitsmikeJun 4, 2025
fa4fbd8
implemented a generic settings manager
ibetitsmikeJun 6, 2025
e7b2491
formatting
ibetitsmikeJun 6, 2025
ced517e
PR adjustments
ibetitsmikeJun 6, 2025
c4c52e2
PR review fixes
ibetitsmikeJun 9, 2025
0c7567b
renamed Settings models
ibetitsmikeJun 9, 2025
2824bd8
comment added to ConnectOnLaunch setting
ibetitsmikeJun 9, 2025
c11f6db
removed unecessary using
ibetitsmikeJun 9, 2025
043c9bb
adjusted comments, linked cancellation token for file sync
ibetitsmikeJun 10, 2025
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletionsApp/App.csproj
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -57,6 +57,7 @@
<ItemGroup>
<PackageReference Include="CommunityToolkit.Mvvm" Version="8.4.0" />
<PackageReference Include="CommunityToolkit.WinUI.Controls.Primitives" Version="8.2.250402" />
<PackageReference Include="CommunityToolkit.WinUI.Controls.SettingsControls" Version="8.2.250402" />
<PackageReference Include="CommunityToolkit.WinUI.Extensions" Version="8.2.250402" />
<PackageReference Include="DependencyPropertyGenerator" Version="1.5.0">
<PrivateAssets>all</PrivateAssets>
Expand Down
138 changes: 84 additions & 54 deletionsApp/App.xaml.cs
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
Expand DownExpand Up@@ -44,6 +43,10 @@ public partial class App : Application
private readonly ILogger<App> _logger;
private readonly IUriHandler _uriHandler;

private readonly ISettingsManager<CoderConnectSettings> _settingsManager;

private readonly IHostApplicationLifetime _appLifetime;

public App()
{
var builder = Host.CreateApplicationBuilder();
Expand DownExpand Up@@ -90,6 +93,13 @@ public App()
// FileSyncListMainPage is created by FileSyncListWindow.
services.AddTransient<FileSyncListWindow>();

services.AddSingleton<ISettingsManager<CoderConnectSettings>, SettingsManager<CoderConnectSettings>>();
services.AddSingleton<IStartupManager, StartupManager>();
// SettingsWindow views and view models
services.AddTransient<SettingsViewModel>();
// SettingsMainPage is created by SettingsWindow.
services.AddTransient<SettingsWindow>();

// DirectoryPickerWindow views and view models are created by FileSyncListViewModel.

// TrayWindow views and view models
Expand All@@ -107,8 +117,10 @@ public App()
services.AddTransient<TrayWindow>();

_services = services.BuildServiceProvider();
_logger = (ILogger<App>)_services.GetService(typeof(ILogger<App>))!;
_uriHandler = (IUriHandler)_services.GetService(typeof(IUriHandler))!;
_logger = _services.GetRequiredService<ILogger<App>>();
_uriHandler = _services.GetRequiredService<IUriHandler>();
_settingsManager = _services.GetRequiredService<ISettingsManager<CoderConnectSettings>>();
_appLifetime = _services.GetRequiredService<IHostApplicationLifetime>();

InitializeComponent();
}
Expand All@@ -129,58 +141,8 @@ public async Task ExitApplication()
protected override void OnLaunched(LaunchActivatedEventArgs args)
{
_logger.LogInformation("new instance launched");
// Start connecting to the manager in the background.
var rpcController = _services.GetRequiredService<IRpcController>();
if (rpcController.GetState().RpcLifecycle == RpcLifecycle.Disconnected)
// Passing in a CT with no cancellation is desired here, because
// the named pipe open will block until the pipe comes up.
_logger.LogDebug("reconnecting with VPN service");
_ = rpcController.Reconnect(CancellationToken.None).ContinueWith(t =>
{
if (t.Exception != null)
{
_logger.LogError(t.Exception, "failed to connect to VPN service");
#if DEBUG
Debug.WriteLine(t.Exception);
Debugger.Break();
#endif
}
});

// Load the credentials in the background.
var credentialManagerCts = new CancellationTokenSource(TimeSpan.FromSeconds(15));
var credentialManager = _services.GetRequiredService<ICredentialManager>();
_ = credentialManager.LoadCredentials(credentialManagerCts.Token).ContinueWith(t =>
{
if (t.Exception != null)
{
_logger.LogError(t.Exception, "failed to load credentials");
#if DEBUG
Debug.WriteLine(t.Exception);
Debugger.Break();
#endif
}

credentialManagerCts.Dispose();
}, CancellationToken.None);

// Initialize file sync.
// We're adding a 5s delay here to avoid race conditions when loading the mutagen binary.

_ = Task.Delay(5000).ContinueWith((_) =>
{
var syncSessionCts = new CancellationTokenSource(TimeSpan.FromSeconds(10));
var syncSessionController = _services.GetRequiredService<ISyncSessionController>();
syncSessionController.RefreshState(syncSessionCts.Token).ContinueWith(
t =>
{
if (t.IsCanceled || t.Exception != null)
{
_logger.LogError(t.Exception, "failed to refresh sync state (canceled = {canceled})", t.IsCanceled);
}
syncSessionCts.Dispose();
}, CancellationToken.None);
});
_ = InitializeServicesAsync(_appLifetime.ApplicationStopping);

// Prevent the TrayWindow from closing, just hide it.
var trayWindow = _services.GetRequiredService<TrayWindow>();
Expand All@@ -192,6 +154,74 @@ protected override void OnLaunched(LaunchActivatedEventArgs args)
};
}

/// <summary>
/// Loads stored VPN credentials, reconnects the RPC controller,
/// and (optionally) starts the VPN tunnel on application launch.
/// </summary>
private async Task InitializeServicesAsync(CancellationToken cancellationToken = default)
{
var credentialManager = _services.GetRequiredService<ICredentialManager>();
var rpcController = _services.GetRequiredService<IRpcController>();

using var credsCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
credsCts.CancelAfter(TimeSpan.FromSeconds(15));

var loadCredsTask = credentialManager.LoadCredentials(credsCts.Token);
var reconnectTask = rpcController.Reconnect(cancellationToken);
var settingsTask = _settingsManager.Read(cancellationToken);

var dependenciesLoaded = true;

try
{
await Task.WhenAll(loadCredsTask, reconnectTask, settingsTask);
}
catch (Exception)
{
if (loadCredsTask.IsFaulted)
_logger.LogError(loadCredsTask.Exception!.GetBaseException(),
"Failed to load credentials");

if (reconnectTask.IsFaulted)
_logger.LogError(reconnectTask.Exception!.GetBaseException(),
"Failed to connect to VPN service");

if (settingsTask.IsFaulted)
_logger.LogError(settingsTask.Exception!.GetBaseException(),
"Failed to fetch Coder Connect settings");

// Don't attempt to connect if we failed to load credentials or reconnect.
// This will prevent the app from trying to connect to the VPN service.
dependenciesLoaded = false;
}

var attemptCoderConnection = settingsTask.Result?.ConnectOnLaunch ?? false;
if (dependenciesLoaded && attemptCoderConnection)
{
try
{
await rpcController.StartVpn(cancellationToken);
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to connect on launch");
}
}

// Initialize file sync.
using var syncSessionCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
syncSessionCts.CancelAfter(TimeSpan.FromSeconds(10));
var syncSessionController = _services.GetRequiredService<ISyncSessionController>();
try
{
await syncSessionController.RefreshState(syncSessionCts.Token);
}
catch (Exception ex)
{
_logger.LogError($"Failed to refresh sync session state {ex.Message}", ex);
}
}

public void OnActivated(object? sender, AppActivationArguments args)
{
switch (args.Kind)
Expand Down
62 changes: 62 additions & 0 deletionsApp/Models/Settings.cs
View file
Open in desktop
Original file line numberDiff line numberDiff 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);
}
}
144 changes: 144 additions & 0 deletionsApp/Services/SettingsManager.cs
View file
Open in desktop
Original file line numberDiff line numberDiff 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;

/// <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);
}

/// <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();
}
}
}
Loading
Loading

[8]ページ先頭

©2009-2025 Movatter.jp