Free, open-source Windows optimization tool for performance, privacy, and simplicity.
C# csharpdebloatdotnetgamingopen-sourceoptimizationoptimizeroptimizerduckperformanceprivacytweakertweakswindowswinui
feat: add RegistryWatcher, set LabelPosition off ToggleSwitch to Left globally and improve RevertManager
fatDuck742620fee65e
diff --git a/optimizerDuck.Test/Common/Helpers/SystemRefreshServiceTests.cs b/optimizerDuck.Test/Common/Helpers/SystemRefreshServiceTests.csnew file mode 100644index 0000000..d201668--- /dev/null+++ b/optimizerDuck.Test/Common/Helpers/SystemRefreshServiceTests.cs@@ -0,0 +1,46 @@+using optimizerDuck.Common.Helpers;++namespace optimizerDuck.Test.Common.Helpers;++/// <summary>+/// Integration-style smoke tests for <see cref="SystemRefreshService"/>.+/// These call the actual Win32 API — they verify the P/Invoke signatures+/// are correct and the service doesn't throw.+/// </summary>+public class SystemRefreshServiceTests+{+ [Fact]+ public void NotifySettingChange_DoesNotThrow()+ {+ var exception = Record.Exception(() => SystemRefreshService.NotifySettingChange());+ Assert.Null(exception);+ }++ [Fact]+ public void RefreshShell_DoesNotThrow()+ {+ var exception = Record.Exception(() => SystemRefreshService.RefreshShell());+ Assert.Null(exception);+ }++ [Fact]+ public void NotifySettingChange_ThenRefreshShell_DoesNotThrow()+ {+ // Simulate the call sequence ExecutePostActionAsync would make+ var exception1 = Record.Exception(() => SystemRefreshService.NotifySettingChange());+ Assert.Null(exception1);++ var exception2 = Record.Exception(() => SystemRefreshService.RefreshShell());+ Assert.Null(exception2);+ }++ [Fact]+ public void NotifySettingChange_CanBeCalledMultipleTimes()+ {+ for (var i = 0; i < 5; i++)+ {+ var exception = Record.Exception(() => SystemRefreshService.NotifySettingChange());+ Assert.Null(exception);+ }+ }+}diff --git a/optimizerDuck.Test/Domain/Customize/BaseCustomizeSettingTests.cs b/optimizerDuck.Test/Domain/Customize/BaseCustomizeSettingTests.csindex a73256b..4125d4f 100644--- a/optimizerDuck.Test/Domain/Customize/BaseCustomizeSettingTests.cs+++ b/optimizerDuck.Test/Domain/Customize/BaseCustomizeSettingTests.cs@@ -3,6 +3,7 @@ using System.Threading.Channels;using System.Threading.Tasks;using Microsoft.Extensions.Logging;using Microsoft.Win32;+using optimizerDuck.Domain.Abstractions;using optimizerDuck.Domain.Customize.Models;using optimizerDuck.Domain.Optimizations.Models.Services;using optimizerDuck.Services.Optimization.Providers;@@ -29,6 +30,61 @@ public class BaseCustomizeSettingTests : IDisposable];}+ #region GetStateWithRetryAsync helpers++ /// <summary>Always returns the same stable state.</summary>+ private sealed class StableStateSetting : BaseCustomizeSetting+ {+ public bool State { get; set; }++ public override Task<bool> GetStateAsync() => Task.Run(() => State);+ }++ /// <summary>Uses base GetStateAsync (no toggles → returns false).</summary>+ private sealed class EmptyTogglesSetting : BaseCustomizeSetting+ {+ // No RegistryToggles override → empty+ // No GetStateAsync override → uses base (empty toggles → false)+ }++ /// <summary>Alternates on every call — never stabilises.</summary>+ private sealed class OscillatingStateSetting : BaseCustomizeSetting+ {+ private int _callCount;++ public override Task<bool> GetStateAsync() =>+ Task.Run(() => Interlocked.Increment(ref _callCount) % 2 == 1);+ }++ /// <summary>Returns stable after a configurable delay.</summary>+ private sealed class DelayedStateSetting : BaseCustomizeSetting+ {+ public bool State { get; set; } = true;+ public int CallCount { get; set; }+ public int DelayMs { get; set; }++ public override async Task<bool> GetStateAsync()+ {+ if (DelayMs > 0)+ await Task.Delay(DelayMs);+ CallCount++;+ return State;+ }+ }++ /// <summary>Setting with multiple toggles to test path dedup.</summary>+ private sealed class MultiToggleSetting : BaseCustomizeSetting+ {+ protected override IEnumerable<RegistryToggle> RegistryToggles =>+ [+ new() { Path = @"HKCU\Software\TestA", Name = "Val1" },+ new() { Path = @"HKCU\Software\TestB", Name = "Val2" },+ new() { Path = @"HKCU\Software\TestA", Name = "Val3" },+ ];+ }++ #endregion+public BaseCustomizeSettingTests(){CleanupTestKeys();@@ -139,4 +195,132 @@ public class BaseCustomizeSettingTests : IDisposablevar finalState = await setting.GetStateAsync();Assert.False(finalState);}++ #region GetStateWithRetryAsync tests++ [Fact]+ public async Task GetStateWithRetryAsync_StableState_ReturnsTrue()+ {+ var setting = new StableStateSetting { State = true };++ var result = await setting.GetStateWithRetryAsync(maxRetries: 3, delayMs: 10);++ Assert.True(result);+ }++ [Fact]+ public async Task GetStateWithRetryAsync_StableState_ReturnsFalse()+ {+ var setting = new StableStateSetting { State = false };++ var result = await setting.GetStateWithRetryAsync(maxRetries: 3, delayMs: 10);++ Assert.False(result);+ }++ [Fact]+ public async Task GetStateWithRetryAsync_StableState_ConvergesQuickly()+ {+ var setting = new StableStateSetting { State = true };++ var sw = System.Diagnostics.Stopwatch.StartNew();+ var result = await setting.GetStateWithRetryAsync(maxRetries: 10, delayMs: 200);+ sw.Stop();++ // Should converge on 2nd read (< 200ms) not wait for all 10 retries+ Assert.True(result);+ Assert.True(+ sw.ElapsedMilliseconds < 300,+ $"Took {sw.ElapsedMilliseconds}ms, expected < 300ms (convergence should be fast)"+ );+ }++ [Fact]+ public async Task GetStateWithRetryAsync_OscillatingState_UsesAllRetriesAndReturnsLast()+ {+ var setting = new OscillatingStateSetting();++ var result = await setting.GetStateWithRetryAsync(maxRetries: 5, delayMs: 10);++ // 5 reads with alternating values: T, F, T, F, T → never converges → returns last (true)+ Assert.True(result);+ }++ [Fact]+ public async Task GetStateWithRetryAsync_WithNoToggles_ReturnsFalse()+ {+ // Empty toggles → base GetStateAsync returns false+ var setting = new EmptyTogglesSetting();++ var result = await setting.GetStateWithRetryAsync(maxRetries: 2, delayMs: 10);++ Assert.False(result);+ }++ [Fact]+ public async Task GetStateWithRetryAsync_ThroughInterface_WorksCorrectly()+ {+ ICustomizeSetting setting = new StableStateSetting { State = true };++ var result = await setting.GetStateWithRetryAsync(maxRetries: 2, delayMs: 10);++ Assert.True(result);+ }++ [Fact]+ public async Task GetStateWithRetryAsync_AfterApply_ReturnsCorrectState()+ {+ var setting = new TestCustomizeSetting { OwnerType = typeof(TestCustomizeSetting) };++ await setting.ApplyAsync(true);+ var result = await setting.GetStateWithRetryAsync(maxRetries: 3, delayMs: 10);++ Assert.True(result);++ await setting.ApplyAsync(false);+ result = await setting.GetStateWithRetryAsync(maxRetries: 3, delayMs: 10);++ Assert.False(result);+ }++ #endregion++ #region WatchedRegistryPaths tests++ [Fact]+ public void WatchedRegistryPaths_WhenMultipleToggles_ReturnsDistinctPaths()+ {+ ICustomizeSetting setting = new MultiToggleSetting();++ var paths = setting.WatchedRegistryPaths;++ // 3 toggles but only 2 distinct paths+ Assert.Equal(2, paths.Count);+ Assert.Contains(@"HKCU\Software\TestA", paths);+ Assert.Contains(@"HKCU\Software\TestB", paths);+ }++ [Fact]+ public void WatchedRegistryPaths_WhenSingleToggle_ReturnsOnePath()+ {+ ICustomizeSetting setting = new TestCustomizeSetting();++ var paths = setting.WatchedRegistryPaths;++ Assert.Single(paths);+ Assert.Equal(TestKeyPath, paths[0]);+ }++ [Fact]+ public void WatchedRegistryPaths_WhenNoToggles_ReturnsEmpty()+ {+ // StableStateSetting has no toggles overrides → empty+ ICustomizeSetting setting = new StableStateSetting();++ var paths = setting.WatchedRegistryPaths;++ Assert.Empty(paths);+ }++ #endregion}diff --git a/optimizerDuck.Test/Services/RegistryWatcherTests.cs b/optimizerDuck.Test/Services/RegistryWatcherTests.csnew file mode 100644index 0000000..e887594--- /dev/null+++ b/optimizerDuck.Test/Services/RegistryWatcherTests.cs@@ -0,0 +1,216 @@+using Microsoft.Extensions.Logging.Abstractions;+using Microsoft.Win32;+using optimizerDuck.Services;++namespace optimizerDuck.Test.Services;++/// <summary>+/// Integration tests for <see cref="RegistryWatcher"/>.+/// Uses real registry writes under <c>HKCU\Software\TestOptimizerDuckWatcher</c>+/// and verifies that <see cref="IRegistryWatcher.RegistryKeyChanged"/> fires+/// when external changes are made.+/// </summary>+public class RegistryWatcherTests : IDisposable+{+ private const string TestRoot = @"HKCU\Software\TestOptimizerDuckWatcher";+ private const string TestRootNative = @"Software\TestOptimizerDuckWatcher";++ public RegistryWatcherTests()+ {+ Cleanup();+ }++ public void Dispose()+ {+ Cleanup();+ }++ private static void Cleanup()+ {+ try+ {+ using var hkcu = Registry.CurrentUser;+ hkcu.DeleteSubKeyTree(TestRootNative, false);+ }+ catch+ {+ // Ignore if it doesn't exist+ }+ }++ [Fact]+ public void Watch_And_Unwatch_DoesNotThrow()+ {+ using var watcher = new RegistryWatcher(NullLogger<RegistryWatcher>.Instance);++ var exception = Record.Exception(() => watcher.Watch(TestRoot));+ Assert.Null(exception);++ exception = Record.Exception(() => watcher.Unwatch(TestRoot));+ Assert.Null(exception);+ }++ [Fact]+ public void Watch_SamePathTwice_DoesNotDuplicate()+ {+ using var watcher = new RegistryWatcher(NullLogger<RegistryWatcher>.Instance);++ watcher.Watch(TestRoot);+ watcher.Watch(TestRoot); // Should be no-op++ // No exception = dedup works+ }++ [Fact]+ public void Watch_EmptyPath_DoesNotThrow()+ {+ using var watcher = new RegistryWatcher(NullLogger<RegistryWatcher>.Instance);++ var exception = Record.Exception(() => watcher.Watch(""));+ Assert.Null(exception);+ }++ [Fact]+ public async Task RegistryChange_FiresEvent()+ {+ // Pre-create the key so the watcher opens it immediately+ using (Registry.CurrentUser.CreateSubKey(TestRootNative)) { }++ using var watcher = new RegistryWatcher(NullLogger<RegistryWatcher>.Instance);+ var tcs = new TaskCompletionSource<string>(+ TaskCreationOptions.RunContinuationsAsynchronously+ );++ watcher.RegistryKeyChanged += (_, path) => tcs.TrySetResult(path!);+ watcher.Watch(TestRoot);++ // Give the watcher thread time to start and block on RegNotifyChangeKeyValue+ await Task.Delay(500);++ // Write a value to trigger the notification+ using var key = Registry.CurrentUser.OpenSubKey(TestRootNative, writable: true);+ Assert.NotNull(key);+ key.SetValue("TestValue", 42);++ // Wait for the event with a timeout+ var completed = await Task.WhenAny(tcs.Task, Task.Delay(5000));+ Assert.Equal(tcs.Task, completed);++ var firedPath = await tcs.Task;+ Assert.Equal(TestRoot, firedPath);+ }++ [Fact]+ public async Task RegistryChange_AfterUnwatch_DoesNotFire()+ {+ using var watcher = new RegistryWatcher(NullLogger<RegistryWatcher>.Instance);+ var fireCount = 0;++ watcher.RegistryKeyChanged += (_, _) => Interlocked.Increment(ref fireCount);+ watcher.Watch(TestRoot);++ // Give the watcher time to attempt opening the key and start its retry loop+ await Task.Delay(300);++ watcher.Unwatch(TestRoot);++ // Give cancellation time to interrupt any in-flight delay/operation+ await Task.Delay(500);++ // Create key and write — at this point the watcher should be stopped+ using var key = Registry.CurrentUser.CreateSubKey(TestRootNative);+ Assert.NotNull(key);+ key.SetValue("TestValue", 99);++ // Extra settle time to ensure no late notification arrives+ await Task.Delay(1500);++ Assert.Equal(0, fireCount);+ }++ [Fact]+ public async Task MultipleWatchers_IndependentPaths_BothFire()+ {+ const string pathA = TestRoot + @"\A";+ const string pathANative = TestRootNative + @"\A";+ const string pathB = TestRoot + @"\B";+ const string pathBNative = TestRootNative + @"\B";++ // Pre-create both sub-keys so the watcher opens them immediately+ using (Registry.CurrentUser.CreateSubKey(pathANative)) { }+ using (Registry.CurrentUser.CreateSubKey(pathBNative)) { }++ using var watcher = new RegistryWatcher(NullLogger<RegistryWatcher>.Instance);+ var tcsA = new TaskCompletionSource<string>(+ TaskCreationOptions.RunContinuationsAsynchronously+ );+ var tcsB = new TaskCompletionSource<string>(+ TaskCreationOptions.RunContinuationsAsynchronously+ );++ watcher.RegistryKeyChanged += (_, path) =>+ {+ if (path == pathA) tcsA.TrySetResult(path!);+ if (path == pathB) tcsB.TrySetResult(path!);+ };++ watcher.Watch(pathA);+ watcher.Watch(pathB);++ // Give watcher threads time to block on RegNotifyChangeKeyValue+ await Task.Delay(500);++ // Write to path A+ using (var keyA = Registry.CurrentUser.OpenSubKey(pathANative, writable: true))+ {+ Assert.NotNull(keyA);+ keyA.SetValue("Val", 1);+ }++ // Write to path B+ using (var keyB = Registry.CurrentUser.OpenSubKey(pathBNative, writable: true))+ {+ Assert.NotNull(keyB);+ keyB.SetValue("Val", 2);+ }++ var completedA = await Task.WhenAny(tcsA.Task, Task.Delay(5000));+ var completedB = await Task.WhenAny(tcsB.Task, Task.Delay(5000));++ Assert.Equal(tcsA.Task, completedA);+ Assert.Equal(tcsB.Task, completedB);+ }++ [Fact]+ public void Dispose_CleansUpAllWatchers()+ {+ var watcher = new RegistryWatcher(NullLogger<RegistryWatcher>.Instance);++ watcher.Watch(TestRoot);+ watcher.Watch(TestRoot + @"\SubKey");++ // Should not throw+ var exception = Record.Exception(() => watcher.Dispose());+ Assert.Null(exception);+ }++ [Fact]+ public void Dispose_MultipleCalls_DoesNotThrow()+ {+ var watcher = new RegistryWatcher(NullLogger<RegistryWatcher>.Instance);+ watcher.Watch(TestRoot);++ watcher.Dispose();+ var exception = Record.Exception(() => watcher.Dispose());+ Assert.Null(exception);+ }++ [Fact]+ public void Watch_AfterDispose_ThrowsObjectDisposed()+ {+ var watcher = new RegistryWatcher(NullLogger<RegistryWatcher>.Instance);+ watcher.Dispose();++ Assert.Throws<ObjectDisposedException>(() => watcher.Watch(TestRoot));+ }+}diff --git a/optimizerDuck/App.xaml.cs b/optimizerDuck/App.xaml.csindex e766a1b..f1e11a6 100644--- a/optimizerDuck/App.xaml.cs+++ b/optimizerDuck/App.xaml.cs@@ -252,6 +252,7 @@ public partial class App : Applicationservices.AddSingleton<SystemInfoService>();services.AddSingleton<StreamService>();services.AddSingleton<UpdaterService>();+ services.AddSingleton<IRegistryWatcher, RegistryWatcher>();}).Build();diff --git a/optimizerDuck/Common/Extensions/CustomizePageRegistryExtensions.cs b/optimizerDuck/Common/Extensions/CustomizePageRegistryExtensions.csindex cbf4765..824c8ad 100644--- a/optimizerDuck/Common/Extensions/CustomizePageRegistryExtensions.cs+++ b/optimizerDuck/Common/Extensions/CustomizePageRegistryExtensions.cs@@ -32,9 +32,10 @@ public static class CustomizePageRegistryExtensions{var registry = serviceProvider.GetRequiredService<CustomizeRegistry>();var loggerFactory = serviceProvider.GetRequiredService<ILoggerFactory>();+ var registryWatcher = serviceProvider.GetRequiredService<IRegistryWatcher>();var category = registry.Categories.First(c => c.GetType() == categoryType);- var viewModel = new CustomizeCategoryViewModel(category, loggerFactory);+ var viewModel = new CustomizeCategoryViewModel(category, loggerFactory, registryWatcher);return Activator.CreateInstance(pageType, viewModel)!;}diff --git a/optimizerDuck/Common/Helpers/SystemRefreshService.cs b/optimizerDuck/Common/Helpers/SystemRefreshService.csnew file mode 100644index 0000000..4ff0b69--- /dev/null+++ b/optimizerDuck/Common/Helpers/SystemRefreshService.cs@@ -0,0 +1,57 @@+using System.Runtime.InteropServices;++namespace optimizerDuck.Common.Helpers;++/// <summary>+/// Provides targeted Windows API-based refresh mechanisms instead of restarting Explorer.+/// Uses WM_SETTINGCHANGE broadcasts and SHChangeNotify for shell/explorer settings.+/// </summary>+internal static class SystemRefreshService+{+ [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]+ private static extern IntPtr SendMessageTimeout(+ IntPtr hWnd,+ uint Msg,+ IntPtr wParam,+ string? lParam,+ uint fuFlags,+ uint uTimeout,+ out IntPtr lpdwResult+ );++ [DllImport("shell32.dll", CharSet = CharSet.Auto)]+ private static extern void SHChangeNotify(uint wEventId, uint uFlags, IntPtr dwItem1, IntPtr dwItem2);++ private static readonly IntPtr HWND_BROADCAST = new(0xffff);+ private const uint WM_SETTINGCHANGE = 0x001A;+ private const uint SMTO_ABORTIFHUNG = 0x0002;++ private const uint SHCNE_ASSOCCHANGED = 0x08000000;+ private const uint SHCNF_IDLIST = 0x0000;++ /// <summary>+ /// Broadcasts a WM_SETTINGCHANGE to all top-level windows, telling them+ /// to re-read their registry settings. Suitable for most system settings.+ /// </summary>+ public static void NotifySettingChange()+ {+ SendMessageTimeout(+ HWND_BROADCAST,+ WM_SETTINGCHANGE,+ IntPtr.Zero,+ null,+ SMTO_ABORTIFHUNG,+ 100,+ out _+ );+ }++ /// <summary>+ /// Notifies shell/explorer that a setting affecting file view or shell behavior has changed.+ /// Equivalent to refreshing File Explorer without restarting it.+ /// </summary>+ public static void RefreshShell()+ {+ SHChangeNotify(SHCNE_ASSOCCHANGED, SHCNF_IDLIST, IntPtr.Zero, IntPtr.Zero);+ }+}diff --git a/optimizerDuck/Domain/Abstractions/ICustomizeSetting.cs b/optimizerDuck/Domain/Abstractions/ICustomizeSetting.csindex d32f628..fcaa4b9 100644--- a/optimizerDuck/Domain/Abstractions/ICustomizeSetting.cs+++ b/optimizerDuck/Domain/Abstractions/ICustomizeSetting.cs@@ -18,8 +18,20 @@ public interface ICustomizeSetting/// <summary>Read the current system state. For toggles: true = on, false = off.</summary>Task<bool> GetStateAsync();+ /// <summary>+ /// Reads state with a cooldown and convergence check. Use after+ /// <see cref="ApplyAsync"/> to let the registry settle.+ /// </summary>+ Task<bool> GetStateWithRetryAsync(int maxRetries = 3, int delayMs = 80);+/// <summary>Apply a value to the system.</summary>Task ApplyAsync(object? value);+ /// <summary>+ /// Registry key paths that should be watched for external changes,+ /// so the UI can auto-refresh when someone else modifies a setting.+ /// </summary>+ IReadOnlyList<string> WatchedRegistryPaths { get; }+CustomizeRecommendationResult? GetRecommendation();}diff --git a/optimizerDuck/Domain/Customize/Categories/Desktop.cs b/optimizerDuck/Domain/Customize/Categories/Desktop.csindex bc7c9ab..4daf0f4 100644--- a/optimizerDuck/Domain/Customize/Categories/Desktop.cs+++ b/optimizerDuck/Domain/Customize/Categories/Desktop.cs@@ -173,6 +173,8 @@ public class Desktop : ICustomizeCategory|| fileName.Equals("blankicon.ico", StringComparison.OrdinalIgnoreCase);}+ protected override IReadOnlyList<string> GetWatchedRegistryPaths() => [Path];+public override Task<bool> GetStateAsync(){var value = RegistryService.Read<string>(new RegistryItem(Path, "29"));diff --git a/optimizerDuck/Domain/Customize/Categories/Gaming.cs b/optimizerDuck/Domain/Customize/Categories/Gaming.csindex ae450bd..40204bf 100644--- a/optimizerDuck/Domain/Customize/Categories/Gaming.cs+++ b/optimizerDuck/Domain/Customize/Categories/Gaming.cs@@ -165,24 +165,31 @@ public class Gaming : ICustomizeCategory{private const string Path = @"HKCU\Control Panel\Mouse";+ protected override IReadOnlyList<string> GetWatchedRegistryPaths() => [Path];+public override Task<bool> GetStateAsync(){- // Mouse acceleration is ON if any of the values are non-zero- var mouseSpeed = RegistryService.Read<string>(new RegistryItem(Path, "MouseSpeed"));- var threshold1 = RegistryService.Read<string>(- new RegistryItem(Path, "MouseThreshold1")- );- var threshold2 = RegistryService.Read<string>(- new RegistryItem(Path, "MouseThreshold2")- );+ return Task.Run(() =>+ {+ // Mouse acceleration is ON if any of the values are non-zero+ var mouseSpeed = RegistryService.Read<string>(+ new RegistryItem(Path, "MouseSpeed")+ );+ var threshold1 = RegistryService.Read<string>(+ new RegistryItem(Path, "MouseThreshold1")+ );+ var threshold2 = RegistryService.Read<string>(+ new RegistryItem(Path, "MouseThreshold2")+ );- // Check if any value is non-zero (acceleration enabled)- var isNonZero =- (int.TryParse(mouseSpeed, out var speed) && speed != 0)- || (int.TryParse(threshold1, out var t1) && t1 != 0)- || (int.TryParse(threshold2, out var t2) && t2 != 0);+ // Check if any value is non-zero (acceleration enabled)+ var isNonZero =+ (int.TryParse(mouseSpeed, out var speed) && speed != 0)+ || (int.TryParse(threshold1, out var t1) && t1 != 0)+ || (int.TryParse(threshold2, out var t2) && t2 != 0);- return Task.FromResult(isNonZero);+ return isNonZero;+ });}public override async Task ApplyAsync(object? value)diff --git a/optimizerDuck/Domain/Customize/Categories/Preferences.cs b/optimizerDuck/Domain/Customize/Categories/Preferences.csindex 27e964e..f47e31b 100644--- a/optimizerDuck/Domain/Customize/Categories/Preferences.cs+++ b/optimizerDuck/Domain/Customize/Categories/Preferences.cs@@ -53,6 +53,8 @@ public class Preferences : ICustomizeCategory}protected override bool NeedsPostAction => true;++ protected override IReadOnlyList<string> GetWatchedRegistryPaths() => [RegPath];}[CustomizeSetting(@@ -429,6 +431,8 @@ public class Preferences : ICustomizeCategoryprotected override bool NeedsPostAction => true;+ protected override IReadOnlyList<string> GetWatchedRegistryPaths() => [BasePath];+public override Task<bool> GetStateAsync(){var exists = RegistryService.KeyExists(new RegistryItem(InprocPath));diff --git a/optimizerDuck/Domain/Customize/Models/BaseCustomizeSetting.cs b/optimizerDuck/Domain/Customize/Models/BaseCustomizeSetting.csindex 8f6dc28..e0e085e 100644--- a/optimizerDuck/Domain/Customize/Models/BaseCustomizeSetting.cs+++ b/optimizerDuck/Domain/Customize/Models/BaseCustomizeSetting.cs@@ -1,4 +1,5 @@using System.Reflection;+using optimizerDuck.Common.Helpers;using optimizerDuck.Domain.Abstractions;using optimizerDuck.Domain.Attributes;using optimizerDuck.Services.Managers;@@ -12,27 +13,17 @@ public abstract class BaseCustomizeSetting : ICustomizeSettingprivate CustomizeSettingAttribute? _meta;private CustomizeSettingAttribute Meta =>- _meta ??=- GetType().GetCustomAttribute<CustomizeSettingAttribute>()- ?? throw new InvalidOperationException(- $"{GetType().Name} is missing [CustomizeSetting] attribute"- );-- #region Metadata & Identity+ _meta ??= GetType().GetCustomAttribute<CustomizeSettingAttribute>()+ ?? throw new InvalidOperationException($"{GetType().Name} is missing [CustomizeSetting] attribute");public Type? OwnerType { get; set; }public string OwnerKey =>- OwnerType?.Name- ?? throw new InvalidOperationException($"{GetType().Name} has no owner assigned");+ OwnerType?.Name ?? throw new InvalidOperationException($"{GetType().Name} has no owner assigned");public string FeatureKey => GetType().Name;public SymbolRegular Icon => Meta.Icon;- #endregion-- #region Localization-public string Name => Loc.Instance[$"Customize.{OwnerKey}.{FeatureKey}.Name"];public string Description => Loc.Instance[$"Customize.{OwnerKey}.{FeatureKey}.Description"];@@ -47,47 +38,46 @@ public abstract class BaseCustomizeSetting : ICustomizeSetting}}- #endregion-- #region Control Configuration-- /// <summary>Which UI control to render. Override for non-toggle types.</summary>public virtual CustomizeControlType ControlType => CustomizeControlType.Toggle;-- /// <summary>Current value for Dropdown / Option / Numeric / String controls.</summary>public virtual object? CurrentValue => null;-- /// <summary>Available choices for Dropdown / Option controls.</summary>public virtual IReadOnlyList<SettingOption>? Options => null;- #endregion+ public virtual Task<bool> GetStateAsync()+ {+ return Task.Run(() =>+ {+ var toggles = RegistryToggles.ToList();+ if (toggles.Count == 0)+ return false;- #region State Management+ var required = toggles.Where(t => !t.IsOptional).ToList();+ if (required.Count == 0)+ required = toggles;- /// <summary>- /// Read the current system state. For toggles: true = on, false = off.- /// Default implementation checks all <see cref="RegistryToggles"/>.- /// </summary>- public virtual Task<bool> GetStateAsync()+ return required.All(t => t.GetState());+ });+ }++ public async Task<bool> GetStateWithRetryAsync(int maxRetries = 3, int delayMs = 80){- var toggles = RegistryToggles.ToList();- if (toggles.Count == 0)- return Task.FromResult(false);+ bool? previous = null;++ for (var i = 0; i < maxRetries; i++)+ {+ if (i > 0)+ await Task.Delay(delayMs);- var required = toggles.Where(t => !t.IsOptional).ToList();- if (required.Count == 0)- required = toggles;+ var state = await GetStateAsync();++ if (previous.HasValue && previous.Value == state)+ return state;++ previous = state;+ }- return Task.FromResult(required.All(t => t.GetState()));+ return previous ?? await GetStateAsync();}- /// <summary>- /// Apply a value. The UI calls this on every user interaction- /// <para/>- /// Default: if <paramref name="value"/> is <c>bool</c>, writes all- /// <see cref="RegistryToggles"/> and runs the post-action.- /// Override for custom behaviour.- /// </summary>public virtual async Task ApplyAsync(object? value){if (value is bool isOn)@@ -103,32 +93,28 @@ public abstract class BaseCustomizeSetting : ICustomizeSettingawait ExecutePostActionAsync();}- /// <summary>- /// Optional: override to provide registry key/value pairs that back a toggle.- /// Used by the default <see cref="GetStateAsync"/> and <see cref="ApplyAsync"/>.- /// Leave empty for non-toggle items.- /// </summary>protected virtual IEnumerable<RegistryToggle> RegistryToggles => [];+ IReadOnlyList<string> ICustomizeSetting.WatchedRegistryPaths => GetWatchedRegistryPaths();++ protected virtual IReadOnlyList<string> GetWatchedRegistryPaths() =>+ [.. RegistryToggles.Select(t => t.Path).Distinct(StringComparer.OrdinalIgnoreCase)];+protected virtual bool NeedsPostAction => false;protected virtual async Task ExecutePostActionAsync(){- await ShellService.CMDAsync("taskkill /f /im explorer.exe & start explorer.exe");+ await Task.Run(() =>+ {+ SystemRefreshService.NotifySettingChange();+ SystemRefreshService.RefreshShell();+ });}- #endregion-- #region Recommendation-- /// <summary>- /// Creates a <see cref="SettingOption"/> whose <see cref="SettingOption.DisplayName"/>- /// is resolved from <c>"Customize.{OwnerKey}.{FeatureKey}.Options.{optionKey}"</c>.- /// </summary>protected SettingOption Option(string optionKey, object value) =>new(Loc.Instance[$"Customize.{OwnerKey}.{FeatureKey}.Options.{optionKey}"], value);- public string RecommendationPrefix => $"Customize.{OwnerKey}.{FeatureKey}.Recommendation";+ protected string RecommendationPrefix => $"Customize.{OwnerKey}.{FeatureKey}.Recommendation";public virtual CustomizeRecommendationResult? GetRecommendation(){@@ -138,6 +124,4 @@ public abstract class BaseCustomizeSetting : ICustomizeSettingreturn new CustomizeRecommendationResult(state, $"{RecommendationPrefix}.Reason");}-- #endregion}diff --git a/optimizerDuck/Services/Optimization/Providers/ServiceProcessService.cs b/optimizerDuck/Services/Optimization/Providers/ServiceProcessService.csindex 6789ec2..6907d3f 100644--- a/optimizerDuck/Services/Optimization/Providers/ServiceProcessService.cs+++ b/optimizerDuck/Services/Optimization/Providers/ServiceProcessService.cs@@ -1,5 +1,4 @@using System.Diagnostics;-using System.Management;using optimizerDuck.Common.Extensions;using optimizerDuck.Domain.Execution;using optimizerDuck.Domain.Optimizations.Models.Services;@@ -16,8 +15,6 @@ public static class ServiceProcessServiceinternal static string? LastError => _lastError.Value;internal static string? LastErrorDetail => _lastErrorDetail.Value;- private static readonly ManagementScope Scope = new(@"\\.\root\cimv2");-/// <summary>Gets the current startup type of a Windows service from the registry.</summary>/// <param name="serviceName">The name of the service.</param>/// <returns>The startup type, or <see langword="null" /> if the value is unrecognized or an error occurs.</returns>diff --git a/optimizerDuck/Services/Revert/RevertManager.cs b/optimizerDuck/Services/Revert/RevertManager.csindex 5202b38..964d6f0 100644--- a/optimizerDuck/Services/Revert/RevertManager.cs+++ b/optimizerDuck/Services/Revert/RevertManager.cs@@ -34,8 +34,6 @@ public class RevertManager(ILogger<RevertManager> _logger, ILoggerFactory _loggeif (successfulSteps.Count == 0)return;- // rebuild the gap-and-index array from the 1-based step indexes- // ExecutionScope uses 1-based indexes, but the array is 0-basedvar maxIndex = successfulSteps.Max(s => s.Index);var steps = new RevertStepData?[maxIndex];@@ -85,7 +83,6 @@ public class RevertManager(ILogger<RevertManager> _logger, ILoggerFactory _loggeMessage = string.Format(Translations.Revert_Error_NoDataFound, optimization.Name),};- // revert in reverse order (LIFO) so later steps don't depend on earlier onesvar failedSteps = new List<OperationStepResult>();var sortedSteps = steps.OrderByDescending(s => s.Index).ToList();var total = sortedSteps.Count;@@ -137,13 +134,16 @@ public class RevertManager(ILogger<RevertManager> _logger, ILoggerFactory _logge}}- // if at least one step reverted, remove the revert file so the optimization shows as not-applied- // if all steps failed, leave the file in place for another attemptif (failedSteps.Count < total)RemoveRevertData(optimization.Id, optimization.OptimizationKey);if (failedSteps.Count == 0)- _fileLocks.TryRemove(optimization.Id, out _);+ {+ if (_fileLocks.TryRemove(optimization.Id, out var sem))+ {+ sem.Dispose();+ }+ }return new RevertResult{@@ -190,8 +190,6 @@ public class RevertManager(ILogger<RevertManager> _logger, ILoggerFactory _loggeSteps = Array.Empty<RevertStepData?>(),};- // grow the array if needed so the index slot exists- // gaps before this index remain nullif (data.Steps.Length < stepIndex){var newSteps = new RevertStepData?[stepIndex];@@ -215,8 +213,6 @@ public class RevertManager(ILogger<RevertManager> _logger, ILoggerFactory _logge}}- #region Helpers-public static async Task<bool> IsAppliedAsync(Guid id){var data = await LoadAsync(GetFilePath(id));@@ -230,17 +226,27 @@ public class RevertManager(ILogger<RevertManager> _logger, ILoggerFactory _loggepublic static void ClearAllRevertData(ILogger logger){- if (!Directory.Exists(Shared.RevertDirectory))- return;- foreach (var f in Directory.GetFiles(Shared.RevertDirectory))- try- {- File.Delete(f);- }- catch (Exception ex)+ if (Directory.Exists(Shared.RevertDirectory))+ {+ foreach (var f in Directory.GetFiles(Shared.RevertDirectory)){- logger.LogError(ex, "Failed to delete {File}", f);+ try+ {+ File.Delete(f);+ }+ catch (Exception ex)+ {+ logger.LogError(ex, "Failed to delete {File}", f);+ }}+ }++ var semaphores = _fileLocks.Values.ToList();+ _fileLocks.Clear();+ foreach (var sem in semaphores)+ {+ sem.Dispose();+ }}private static string GetFilePath(Guid id)@@ -252,13 +258,34 @@ public class RevertManager(ILogger<RevertManager> _logger, ILoggerFactory _logge{if (!File.Exists(path))return null;++ var id = ExtractIdFromPath(path);+ SemaphoreSlim? lockObj = null;++ if (id.HasValue)+ {+ lockObj = _fileLocks.GetOrAdd(id.Value, _ => new SemaphoreSlim(1, 1));+ await lockObj.WaitAsync().ConfigureAwait(false);+ }+try{- var json = await File.ReadAllTextAsync(path);- if (string.IsNullOrWhiteSpace(json))- return null;+ for (var i = 0; i < 3; i++)+ {+ try+ {+ var json = await File.ReadAllTextAsync(path);+ if (string.IsNullOrWhiteSpace(json))+ return null;- return JsonConvert.DeserializeObject<RevertData>(json);+ return JsonConvert.DeserializeObject<RevertData>(json);+ }+ catch (IOException) when (i < 2)+ {+ await Task.Delay(50);+ }+ }+ return null;}catch (JsonException ex){@@ -270,6 +297,24 @@ public class RevertManager(ILogger<RevertManager> _logger, ILoggerFactory _loggeTraceCorruptRevertFile(path, ex);return null;}+ finally+ {+ lockObj?.Release();+ }+ }++ private static Guid? ExtractIdFromPath(string path)+ {+ try+ {+ var fileName = Path.GetFileNameWithoutExtension(path);+ if (Guid.TryParse(fileName, out var id))+ return id;+ }+ catch+ {+ }+ return null;}private static void TraceCorruptRevertFile(string path, Exception ex)@@ -280,7 +325,10 @@ public class RevertManager(ILogger<RevertManager> _logger, ILoggerFactory _loggepublic void RemoveRevertData(Guid id, string? name = null){Remove(id, name);- _fileLocks.TryRemove(id, out _);+ if (_fileLocks.TryRemove(id, out var sem))+ {+ sem.Dispose();+ }}private async Task WriteJsonAsync(Guid optimizationId, string path, RevertData data)@@ -299,8 +347,6 @@ public class RevertManager(ILogger<RevertManager> _logger, ILoggerFactory _logge}}- // write to .tmp then replace atomically so a crash mid-write doesn't corrupt the revert file- // File.Replace is the .NET atomic swap for existing filesprivate static async Task WriteJsonAtomicAsync(string path, RevertData data){Directory.CreateDirectory(Path.GetDirectoryName(path)!);@@ -315,7 +361,7 @@ public class RevertManager(ILogger<RevertManager> _logger, ILoggerFactory _loggeFile.Move(tempPath, path);}- private async Task<SemaphoreSlim> AcquireFileLockAsync(Guid id)+ private static async Task<SemaphoreSlim> AcquireFileLockAsync(Guid id){var lockObj = _fileLocks.GetOrAdd(id, _ => new SemaphoreSlim(1, 1));if (@@ -337,36 +383,39 @@ public class RevertManager(ILogger<RevertManager> _logger, ILoggerFactory _loggereturn [];var seenIndexes = new HashSet<int>();- foreach (var step in data.Steps.Where(s => s != null))+ var result = new List<(int, IRevertStep)>();++ foreach (var stepData in data.Steps.Where(s => s != null)){- if (step!.Index <= 0)+ if (stepData!.Index <= 0){- _logger.LogWarning("Invalid index {Index} in revert data for {Id}", step.Index, id);- return [];+ _logger.LogWarning("Skipping step with invalid index {Index} in revert data for {Id}", stepData.Index, id);+ continue;}- if (!seenIndexes.Add(step.Index))++ if (!seenIndexes.Add(stepData.Index)){_logger.LogWarning(- "Duplicate index {Index} in revert data for {Id}",- step.Index,+ "Skipping step with duplicate index {Index} in revert data for {Id}",+ stepData.Index,id);- return [];+ continue;}- }- var result = new List<(int, IRevertStep)>();- foreach (var stepData in data.Steps.Where(s => s != null))- {- var step = DeserializeStep(stepData!.Type, stepData.Data);+ var step = DeserializeStep(stepData.Type, stepData.Data);if (step != null)+ {result.Add((stepData.Index, step));+ }else+ {_logger.LogWarning("Skipped unknown revert step type '{Type}' for optimization {Id}",stepData.Type,id);+ }}return result.OrderBy(x => x.Item1).ToList();@@ -397,8 +446,6 @@ public class RevertManager(ILogger<RevertManager> _logger, ILoggerFactory _logge}}- // discover all IRevertStep implementations via reflection and map their Type string to a factory- // each step type must expose a static FromData(JObject) method for deserializationprivate static Dictionary<string, Func<JObject, IRevertStep>> BuildStepRegistry(){var dict = new Dictionary<string, Func<JObject, IRevertStep>>();@@ -434,6 +481,4 @@ public class RevertManager(ILogger<RevertManager> _logger, ILoggerFactory _logge_logger.LogWarning("Unknown revert step type: {Type}", type);return null;}-- #endregion}diff --git a/optimizerDuck/Services/System/RegistryWatcher.cs b/optimizerDuck/Services/System/RegistryWatcher.csnew file mode 100644index 0000000..866904c--- /dev/null+++ b/optimizerDuck/Services/System/RegistryWatcher.cs@@ -0,0 +1,281 @@+using System.Collections.Concurrent;+using System.Runtime.InteropServices;+using Microsoft.Extensions.Logging;++namespace optimizerDuck.Services;++public interface IRegistryWatcher : IDisposable+{+ event EventHandler<string>? RegistryKeyChanged;+ void Watch(string registryPath);+ void Unwatch(string registryPath);+}++internal sealed class RegistryWatcher(ILogger<RegistryWatcher> logger) : IRegistryWatcher+{+ public event EventHandler<string>? RegistryKeyChanged;++ private readonly ConcurrentDictionary<string, PathWatcher> _watchers = new(StringComparer.OrdinalIgnoreCase);+ private bool _disposed;++ public void Watch(string registryPath)+ {+ ObjectDisposedException.ThrowIf(_disposed, this);++ if (string.IsNullOrWhiteSpace(registryPath))+ return;++ if (_watchers.ContainsKey(registryPath))+ return;++ var watcher = new PathWatcher(registryPath, OnPathChanged, logger);+ if (_watchers.TryAdd(registryPath, watcher))+ {+ watcher.Start();+ }+ else+ {+ watcher.Dispose();+ }+ }++ public void Unwatch(string registryPath)+ {+ if (string.IsNullOrWhiteSpace(registryPath))+ return;++ if (_watchers.TryRemove(registryPath, out var watcher))+ {+ watcher.Dispose();+ }+ }++ private void OnPathChanged(string path)+ {+ RegistryKeyChanged?.Invoke(this, path);+ }++ public void Dispose()+ {+ if (_disposed)+ return;++ _disposed = true;++ foreach (var watcher in _watchers.Values)+ {+ watcher.Dispose();+ }+ _watchers.Clear();+ }++ private sealed class PathWatcher : IDisposable+ {+ private readonly string _path;+ private readonly Action<string> _onChanged;+ private readonly ILogger _logger;+ private readonly object _lock = new();++ private IntPtr _hKey;+ private AutoResetEvent? _event;+ private RegisteredWaitHandle? _registeredWait;+ private CancellationTokenSource? _retryCts;+ private DateTime _lastFiredTime = DateTime.MinValue;+ private bool _isWatching;+ private bool _disposed;++ public PathWatcher(string path, Action<string> onChanged, ILogger logger)+ {+ _path = path;+ _onChanged = onChanged;+ _logger = logger;+ }++ public void Start()+ {+ lock (_lock)+ {+ if (_disposed || _isWatching)+ return;++ _isWatching = true;+ _retryCts = new CancellationTokenSource();+ _ = ArmWatcherAsync(_retryCts.Token);+ }+ }++ private async Task ArmWatcherAsync(CancellationToken token)+ {+ while (!token.IsCancellationRequested)+ {+ try+ {+ lock (_lock)+ {+ if (_disposed || token.IsCancellationRequested)+ return;++ var (hive, subKey) = ParseRegistryPath(_path);+ var error = NativeMethods.RegOpenKeyEx(hive, subKey, 0, NativeMethods.KEY_NOTIFY, out _hKey);++ if (error == 0 && _hKey != IntPtr.Zero)+ {+ _event = new AutoResetEvent(false);++ NativeMethods.RegNotifyChangeKeyValue(+ _hKey,+ false,+ NativeMethods.REG_NOTIFY_CHANGE_LAST_SET | NativeMethods.REG_NOTIFY_CHANGE_NAME,+ _event.SafeWaitHandle.DangerousGetHandle(),+ true+ );++ _registeredWait = ThreadPool.RegisterWaitForSingleObject(+ _event,+ OnKeyChangedCallback,+ null,+ Timeout.Infinite,+ true+ );++ return;+ }+ }++ await Task.Delay(1000, token);+ }+ catch (Exception ex)+ {+ _logger.LogWarning(ex, "RegistryWatcher: Failed to watch {Path}, retrying", _path);+ try+ {+ await Task.Delay(1000, token);+ }+ catch+ {+ break;+ }+ }+ }+ }++ private void OnKeyChangedCallback(object? state, bool timedOut)+ {+ lock (_lock)+ {+ if (_disposed || !_isWatching)+ return;++ CleanupArm();++ var now = DateTime.UtcNow;+ if (now - _lastFiredTime > TimeSpan.FromMilliseconds(300))+ {+ _lastFiredTime = now;+ _onChanged(_path);+ }++ if (_retryCts != null && !_retryCts.Token.IsCancellationRequested)+ {+ _ = ArmWatcherAsync(_retryCts.Token);+ }+ }+ }++ private void CleanupArm()+ {+ if (_registeredWait != null)+ {+ _registeredWait.Unregister(null);+ _registeredWait = null;+ }+ if (_event != null)+ {+ _event.Dispose();+ _event = null;+ }+ if (_hKey != IntPtr.Zero)+ {+ NativeMethods.RegCloseKey(_hKey);+ _hKey = IntPtr.Zero;+ }+ }++ public void Dispose()+ {+ lock (_lock)+ {+ if (_disposed)+ return;++ _disposed = true;+ _isWatching = false;++ if (_retryCts != null)+ {+ _retryCts.Cancel();+ _retryCts.Dispose();+ _retryCts = null;+ }++ CleanupArm();+ }+ }++ private static (IntPtr hive, string subKey) ParseRegistryPath(string path)+ {+ var firstBackslash = path.IndexOf('\\');+ var root = firstBackslash > 0+ ? path[..firstBackslash].ToUpperInvariant()+ : path.ToUpperInvariant();++ var subKey = firstBackslash > 0 ? path[(firstBackslash + 1)..] : string.Empty;++ var hive = root switch+ {+ "HKEY_CURRENT_USER" or "HKCU" => NativeMethods.HKEY_CURRENT_USER,+ "HKEY_LOCAL_MACHINE" or "HKLM" => NativeMethods.HKEY_LOCAL_MACHINE,+ "HKEY_CLASSES_ROOT" or "HKCR" => NativeMethods.HKEY_CLASSES_ROOT,+ "HKEY_USERS" or "HKU" => NativeMethods.HKEY_USERS,+ "HKEY_CURRENT_CONFIG" or "HKCC" => NativeMethods.HKEY_CURRENT_CONFIG,+ _ => throw new ArgumentException($"Unknown registry hive: {root}", nameof(path))+ };++ return (hive, subKey);+ }+ }++ private static class NativeMethods+ {+ internal static readonly IntPtr HKEY_CURRENT_USER = new(unchecked((int)0x80000001));+ internal static readonly IntPtr HKEY_LOCAL_MACHINE = new(unchecked((int)0x80000002));+ internal static readonly IntPtr HKEY_CLASSES_ROOT = new(unchecked((int)0x80000000));+ internal static readonly IntPtr HKEY_USERS = new(unchecked((int)0x80000003));+ internal static readonly IntPtr HKEY_CURRENT_CONFIG = new(unchecked((int)0x80000005));++ internal const int KEY_NOTIFY = 0x0010;+ internal const uint REG_NOTIFY_CHANGE_NAME = 0x00000001;+ internal const uint REG_NOTIFY_CHANGE_LAST_SET = 0x00000004;++ [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Auto)]+ internal static extern int RegOpenKeyEx(+ IntPtr hKey,+ string lpSubKey,+ uint ulOptions,+ int samDesired,+ out IntPtr phkResult+ );++ [DllImport("advapi32.dll", SetLastError = true)]+ internal static extern int RegNotifyChangeKeyValue(+ IntPtr hKey,+ bool bWatchSubtree,+ uint dwNotifyFilter,+ IntPtr hEvent,+ bool fAsynchronous+ );++ [DllImport("advapi32.dll", SetLastError = true)]+ internal static extern int RegCloseKey(IntPtr hKey);+ }+}diff --git a/optimizerDuck/UI/Styles/FluentDesign.xaml b/optimizerDuck/UI/Styles/FluentDesign.xamlindex 3f6cdab..37dde18 100644--- a/optimizerDuck/UI/Styles/FluentDesign.xaml+++ b/optimizerDuck/UI/Styles/FluentDesign.xaml@@ -146,6 +146,7 @@<Setter Property="Margin" Value="{StaticResource ControlGap}" /><Setter Property="VerticalAlignment" Value="Center" /><Setter Property="Cursor" Value="Hand" />+ <Setter Property="LabelPosition" Value="Left" /></Style><Stylediff --git a/optimizerDuck/UI/ViewModels/Customize/CustomizeItemViewModel.cs b/optimizerDuck/UI/ViewModels/Customize/CustomizeItemViewModel.csindex 91e4f8b..1ea6639 100644--- a/optimizerDuck/UI/ViewModels/Customize/CustomizeItemViewModel.cs+++ b/optimizerDuck/UI/ViewModels/Customize/CustomizeItemViewModel.cs@@ -5,35 +5,37 @@ using Microsoft.Extensions.Logging;using optimizerDuck.Domain.Abstractions;using optimizerDuck.Domain.Customize.Models;using optimizerDuck.Domain.Execution;+using optimizerDuck.Services;using optimizerDuck.Services.Managers;using Wpf.Ui.Controls;namespace optimizerDuck.UI.ViewModels.Customize;-/// <summary>-/// Wraps an <see cref="ICustomizeSetting"/> for the UI.-/// Both toggle flips and value changes auto-apply immediately.-/// </summary>-public partial class CustomizeItemViewModel(ICustomizeSetting setting, ILoggerFactory loggerFactory)- : ObservableObject+public partial class CustomizeItemViewModel(+ ICustomizeSetting setting,+ ILoggerFactory loggerFactory,+ IRegistryWatcher registryWatcher+) : ObservableObject, IDisposable{private readonly ILogger<CustomizeItemViewModel> _logger =loggerFactory.CreateLogger<CustomizeItemViewModel>();private bool _hasLoaded;private CancellationTokenSource? _debounceCts;+ private bool _disposed;- #region Public Pass-through Properties+ private readonly HashSet<string> _watchedPaths = new(StringComparer.OrdinalIgnoreCase);++ private readonly object _applyLock = new();+ private bool _isApplying;+ private object? _pendingValue;+ private bool _hasPendingValue;public ICustomizeSetting Setting => setting;public CustomizeControlType ControlType => setting.ControlType;public IReadOnlyList<SettingOption>? Options => setting.Options;public SymbolRegular Icon => setting.Icon;- #endregion-- #region Observable Properties-[ObservableProperty]private string _description = setting.Description;@@ -52,17 +54,9 @@ public partial class CustomizeItemViewModel(ICustomizeSetting setting, ILoggerFa[ObservableProperty]private string _categoryName = string.Empty;- /// <summary>- /// Bound by every control (ToggleSwitch, ComboBox, ListBox, NumberBox, TextBox).- /// When the user interacts with the UI this value changes and auto-triggers apply.- /// </summary>[ObservableProperty]private object? _currentValue;- #endregion-- #region Recommendation UI-public CustomizeRecommendationResult? Recommendation => setting.GetRecommendation();public bool HasRecommendation => Recommendation != null;@@ -89,10 +83,6 @@ public partial class CustomizeItemViewModel(ICustomizeSetting setting, ILoggerFapublic string? RecommendationReason =>Recommendation != null ? Loc.Instance[Recommendation.ReasonTranslationKey] : null;- #endregion-- #region State Management-public async Task LoadStateAsync(){try@@ -100,6 +90,8 @@ public partial class CustomizeItemViewModel(ICustomizeSetting setting, ILoggerFaIsEnabled = await setting.GetStateAsync();CurrentValue = setting.CurrentValue;_hasLoaded = true;++ SubscribeToRegistryChanges();}catch{@@ -107,44 +99,68 @@ public partial class CustomizeItemViewModel(ICustomizeSetting setting, ILoggerFa}}- /// <summary>- /// Called by the ToggleSwitch. Always applies the opposite of the current state.- /// </summary>- [RelayCommand]- private async Task ToggleAsync()+ private void SubscribeToRegistryChanges(){- if (IsLoading)+ if (_disposed)return;- var newState = !IsEnabled;+ foreach (var path in setting.WatchedRegistryPaths)+ {+ if (_watchedPaths.Add(path))+ registryWatcher.Watch(path);+ }- _logger.LogInformation(- "Apply {Action} {Setting} ({Key})",- newState ? "On" : "Off",- setting.Name,- setting.FeatureKey- );+ if (_watchedPaths.Count > 0)+ registryWatcher.RegistryKeyChanged += OnRegistryKeyChanged;+ }- IsLoading = true;- try+ private async void OnRegistryKeyChanged(object? sender, string path)+ {+ if (_disposed || !_hasLoaded)+ return;++ if (!_watchedPaths.Contains(path))+ return;++ await Application.Current.Dispatcher.InvokeAsync(async () =>{- using (ExecutionScope.BeginForLogging(_logger))+ try{- await setting.ApplyAsync(newState);+ lock (_applyLock)+ {+ if (_isApplying)+ return;+ }++ var state = await setting.GetStateWithRetryAsync(maxRetries: 2, delayMs: 50);+ IsEnabled = state;+ CurrentValue = setting.CurrentValue;}- IsEnabled = await setting.GetStateAsync();- CurrentValue = setting.CurrentValue;- ((App)Application.Current).HasPendingChanges = true;- }- catch (Exception ex)- {- _logger.LogError(ex, "Failed to toggle {SettingName}", setting.Name);- throw;- }- finally+ catch (Exception ex)+ {+ _logger.LogWarning(ex, "RegistryWatcher: failed to refresh state for {Setting}", setting.Name);+ }+ });+ }++ [RelayCommand]+ private void Toggle()+ {+ lock (_applyLock){- IsLoading = false;+ var currentTarget = _hasPendingValue ? (bool)_pendingValue! : IsEnabled;+ var nextState = !currentTarget;++ _pendingValue = nextState;+ _hasPendingValue = true;++ if (_isApplying)+ return;++ _isApplying = true;}++ _ = ProcessPendingValuesAsync();}partial void OnCurrentValueChanged(object? value)@@ -152,55 +168,29 @@ public partial class CustomizeItemViewModel(ICustomizeSetting setting, ILoggerFaif (!_hasLoaded || ControlType == CustomizeControlType.Toggle)return;- // Debounce for text input; immediate for discrete selections+ if (Equals(value, setting.CurrentValue))+ return;+if (ControlType == CustomizeControlType.String)_ = ApplyWithDebounceAsync(value);else- _ = ApplyValueAsync(value);+ QueueApplyValue(value);}- private async Task ApplyValueAsync(object? value)+ private void QueueApplyValue(object? value){- if (IsLoading)- return;-- IsLoading = true;- try- {- _logger.LogInformation(- "===== START applying setting {Setting} ({Key}) =====",- setting.Name,- setting.FeatureKey- );- using (ExecutionScope.BeginForLogging(_logger))- {- await setting.ApplyAsync(value);- }- IsEnabled = await setting.GetStateAsync();- ((App)Application.Current).HasPendingChanges = true;-- _logger.LogInformation(- "Applied {Setting} ({Key}) = {Value}",- setting.Name,- setting.FeatureKey,- value- );-- _logger.LogInformation(- "===== END applying setting {Setting} ({Key}) =====",- setting.Name,- setting.FeatureKey- );- }- catch (Exception ex)+ lock (_applyLock){- _logger.LogError(ex, "Failed to apply {SettingName}", setting.Name);- throw;- }- finally- {- IsLoading = false;+ _pendingValue = value;+ _hasPendingValue = true;++ if (_isApplying)+ return;++ _isApplying = true;}++ _ = ProcessPendingValuesAsync();}private async Task ApplyWithDebounceAsync(object? value)@@ -215,13 +205,82 @@ public partial class CustomizeItemViewModel(ICustomizeSetting setting, ILoggerFaif (token.IsCancellationRequested)return;- await ApplyValueAsync(value);+ QueueApplyValue(value);}catch (TaskCanceledException){- // Expected on debounce reset}}- #endregion+ private async Task ProcessPendingValuesAsync()+ {+ try+ {+ while (true)+ {+ object? valueToApply;+ lock (_applyLock)+ {+ if (!_hasPendingValue)+ {+ _isApplying = false;+ break;+ }++ valueToApply = _pendingValue;+ _hasPendingValue = false;+ }++ IsLoading = true;+ try+ {+ _logger.LogInformation(+ "Apply {Value} for {Setting} ({Key})",+ valueToApply,+ setting.Name,+ setting.FeatureKey+ );++ using (ExecutionScope.BeginForLogging(_logger))+ {+ await setting.ApplyAsync(valueToApply);+ }++ IsEnabled = await setting.GetStateWithRetryAsync();++ if (ControlType != CustomizeControlType.Toggle)+ {+ CurrentValue = setting.CurrentValue;+ }++ ((App)Application.Current).HasPendingChanges = true;+ }+ catch (Exception ex)+ {+ _logger.LogError(ex, "Failed to apply {SettingName}", setting.Name);+ }+ }+ }+ finally+ {+ IsLoading = false;+ }+ }++ public void Dispose()+ {+ if (_disposed)+ return;++ _disposed = true;++ registryWatcher.RegistryKeyChanged -= OnRegistryKeyChanged;++ foreach (var path in _watchedPaths)+ registryWatcher.Unwatch(path);++ _watchedPaths.Clear();+ _debounceCts?.Cancel();+ _debounceCts?.Dispose();+ }}diff --git a/optimizerDuck/UI/ViewModels/Pages/CustomizeCategoryViewModel.cs b/optimizerDuck/UI/ViewModels/Pages/CustomizeCategoryViewModel.csindex 4cf2b0a..207de16 100644--- a/optimizerDuck/UI/ViewModels/Pages/CustomizeCategoryViewModel.cs+++ b/optimizerDuck/UI/ViewModels/Pages/CustomizeCategoryViewModel.cs@@ -9,6 +9,7 @@ using CommunityToolkit.Mvvm.Input;using Microsoft.Extensions.Logging;using optimizerDuck.Common.Helpers;using optimizerDuck.Domain.Abstractions;+using optimizerDuck.Services;using optimizerDuck.Domain.Customize.Models;using optimizerDuck.Resources.Languages;using optimizerDuck.UI.ViewModels.Customize;@@ -60,7 +61,11 @@ public partial class CustomizeCategoryViewModel : ViewModelprivate readonly List<CustomizeItemViewModel> _allSettings = [];private readonly ICustomizeCategory? _currentCategory;- public CustomizeCategoryViewModel(ICustomizeCategory category, ILoggerFactory loggerFactory)+ public CustomizeCategoryViewModel(+ ICustomizeCategory category,+ ILoggerFactory loggerFactory,+ IRegistryWatcher registryWatcher+ ){_currentCategory = category;@@ -72,7 +77,7 @@ public partial class CustomizeCategoryViewModel : ViewModel_allSettings.Clear();foreach (var setting in _currentCategory.Features)- _allSettings.Add(new CustomizeItemViewModel(setting, loggerFactory));+ _allSettings.Add(new CustomizeItemViewModel(setting, loggerFactory, registryWatcher));_ = InitializeAsync();}diff --git a/optimizerDuck/optimizerDuck.csproj b/optimizerDuck/optimizerDuck.csprojindex 5313d7a..4fc939c 100644--- a/optimizerDuck/optimizerDuck.csproj+++ b/optimizerDuck/optimizerDuck.csproj@@ -55,6 +55,10 @@<PackageReference Include="WPF-UI.DependencyInjection" Version="4.3.0" /></ItemGroup>+ <ItemGroup>+ <InternalsVisibleTo Include="optimizerDuck.Test" />+ </ItemGroup>+<ItemGroup><EmbeddedResource Update="Resources\Languages\Translations.resx"><Generator>ResXFileCodeGenerator</Generator>