Free, open-source Windows optimization tool for performance, privacy, and simplicity.
C# csharpdebloatdotnetgamingopen-sourceoptimizationoptimizeroptimizerduckperformanceprivacytweakertweakswindowswinui
refactor: add xml docs to methods/properties. fix locking in InitializeOnceAsync, add events to update across pages
fatDuck50507dc6b021
diff --git a/optimizerDuck/App.xaml.cs b/optimizerDuck/App.xaml.csindex a1c2ad8..612e7c9 100644--- a/optimizerDuck/App.xaml.cs+++ b/optimizerDuck/App.xaml.cs@@ -148,16 +148,52 @@ public partial class App : ApplicationTaskScheduler.UnobservedTaskException += OnUnobservedTaskException;DispatcherUnhandledException += OnDispatcherUnhandledException;- _ = Task.Run(async () =>+ _ = SafeFireAndForgetAsync(() => OnStartupAsync(e));+ }++ private static async Task SafeFireAndForgetAsync(Func<Task> taskFactory)+ {+ try+ {+ await taskFactory();+ }+ catch (Exception ex){try{- await OnStartupAsync(e);+ await HandleStartupErrorStaticAsync(ex);}- catch (Exception ex)+ catch{- await HandleStartupErrorAsync(ex);+ // what you expect}+ }+ }+++ private static async Task HandleStartupErrorStaticAsync(Exception ex)+ {+ LogExceptionToFile("App.Startup", ex);++ try+ {+ Log.Logger?.Fatal(ex, "Fatal error during startup");+ await Log.CloseAndFlushAsync();+ }+ catch+ {+ // ignore logging failures during fatal startup handling+ }++ await Application.Current.Dispatcher.InvokeAsync(() =>+ {+ System.Windows.MessageBox.Show(+ $"Failed to start optimizerDuck.{Environment.NewLine}{Environment.NewLine}{ex.Message}",+ "optimizerDuck",+ System.Windows.MessageBoxButton.OK,+ MessageBoxImage.Error+ );+ Application.Current.Shutdown(-1);});}diff --git a/optimizerDuck/Domain/Abstractions/ICustomizeSetting.cs b/optimizerDuck/Domain/Abstractions/ICustomizeSetting.csindex fcaa4b9..6ddd4ed 100644--- a/optimizerDuck/Domain/Abstractions/ICustomizeSetting.cs+++ b/optimizerDuck/Domain/Abstractions/ICustomizeSetting.cs@@ -3,16 +3,31 @@ using Wpf.Ui.Controls;namespace optimizerDuck.Domain.Abstractions;+/// <summary>+/// Defines a single customizable setting that the user can configure.+/// </summary>public interface ICustomizeSetting{+ /// <summary>Gets the localized display name of the setting.</summary>string Name { get; }++ /// <summary>Gets the localized description of what this setting does.</summary>string Description { get; }++ /// <summary>Gets the localized section/group this setting belongs to.</summary>string Section { get; }++ /// <summary>Gets the icon symbol displayed next to the setting in the UI.</summary>public SymbolRegular Icon { get; }++ /// <summary>Gets the unique key used for localization lookup.</summary>string FeatureKey { get; }+ /// <summary>Gets the type of UI control to render for this setting.</summary>CustomizeControlType ControlType { get; }+object? CurrentValue { get; }+IReadOnlyList<SettingOption>? Options { get; }/// <summary>Read the current system state. For toggles: true = on, false = off.</summary>@@ -24,7 +39,6 @@ public interface ICustomizeSetting/// </summary>Task<bool> GetStateWithRetryAsync(int maxRetries = 3, int delayMs = 80);- /// <summary>Apply a value to the system.</summary>Task ApplyAsync(object? value);/// <summary>diff --git a/optimizerDuck/Domain/Attributes/CustomizeCategoryAttribute.cs b/optimizerDuck/Domain/Attributes/CustomizeCategoryAttribute.csindex e964ebf..ffbd2b4 100644--- a/optimizerDuck/Domain/Attributes/CustomizeCategoryAttribute.cs+++ b/optimizerDuck/Domain/Attributes/CustomizeCategoryAttribute.cs@@ -1,4 +1,4 @@-namespace optimizerDuck.Domain.Attributes;+namespace optimizerDuck.Domain.Attributes;[AttributeUsage(AttributeTargets.Class, Inherited = false)]public class CustomizeCategoryAttribute : Attributediff --git a/optimizerDuck/Domain/Customize/Models/BaseCustomizeSetting.cs b/optimizerDuck/Domain/Customize/Models/BaseCustomizeSetting.csindex a2533bd..d9a6e6f 100644--- a/optimizerDuck/Domain/Customize/Models/BaseCustomizeSetting.cs+++ b/optimizerDuck/Domain/Customize/Models/BaseCustomizeSetting.cs@@ -7,6 +7,12 @@ using Wpf.Ui.Controls;namespace optimizerDuck.Domain.Customize.Models;+/// <summary>+/// Base class for customize settings that read from and write to the Windows registry.+/// Subclasses declare <see cref="RegistryToggles"/> to define which registry values+/// are controlled, and may override <see cref="RefreshScope"/> to specify which+/// Windows surfaces should be refreshed after applying.+/// </summary>public abstract class BaseCustomizeSetting : ICustomizeSetting{private CustomizeSettingAttribute? _meta;diff --git a/optimizerDuck/Domain/Customize/Models/RecommendationState.cs b/optimizerDuck/Domain/Customize/Models/RecommendationState.csindex d953b94..31d9f16 100644--- a/optimizerDuck/Domain/Customize/Models/RecommendationState.cs+++ b/optimizerDuck/Domain/Customize/Models/RecommendationState.cs@@ -1,10 +1,22 @@namespace optimizerDuck.Domain.Customize.Models;+/// <summary>+/// Specifies the recommended state for a customize setting.+/// </summary>public enum RecommendationState{+ /// <summary>No recommendation is provided.</summary>None,++ /// <summary>The setting is recommended to be turned on.</summary>On,++ /// <summary>The setting is recommended to be turned off.</summary>Off,++ /// <summary>The setting is experimental and may cause unexpected behavior.</summary>Experimental,++ /// <summary>The recommendation depends on other factors (e.g., hardware or user preference).</summary>Depends,}diff --git a/optimizerDuck/Domain/Customize/Models/RegistryToggle.cs b/optimizerDuck/Domain/Customize/Models/RegistryToggle.csindex 446443c..e23a264 100644--- a/optimizerDuck/Domain/Customize/Models/RegistryToggle.cs+++ b/optimizerDuck/Domain/Customize/Models/RegistryToggle.cs@@ -4,17 +4,43 @@ using optimizerDuck.Services.Optimization.Providers;namespace optimizerDuck.Domain.Customize.Models;+/// <summary>+/// Represents a single registry key-value pair that can be toggled on or off.+/// </summary>public class RegistryToggle{+ /// <summary>Gets the full registry key path (e.g., <c>HKCU\Software\MyApp</c>).</summary>public required string Path { get; init; }++ /// <summary>Gets the name of the registry value.</summary>public required string Name { get; init; }++ /// <summary>Gets the value to write when toggling on. Default is <c>1</c>.</summary>public object? OnValue { get; init; } = 1;++ /// <summary>Gets the value to write when toggling off. Default is <c>0</c>.</summary>public object? OffValue { get; init; } = 0;++ /// <summary>Gets the default state value when the key is missing. Default is <c>0</c>.</summary>public object? DefaultValue { get; init; } = 0;++ /// <summary>+ /// Gets a value that indicates whether a missing registry value should be treated as <see cref="DefaultValue"/>.+ /// Default is <see langword="false"/>.+ /// </summary>public bool TreatMissingAsDefault { get; init; } = false;++ /// <summary>+ /// Gets a value that indicates whether this toggle is optional (non-required for state detection).+ /// Default is <see langword="false"/>.+ /// </summary>public bool IsOptional { get; init; } = false;++ /// <summary>Gets the registry value type. Default is <see cref="RegistryValueKind.DWord"/>.</summary>public RegistryValueKind ValueKind { get; init; } = RegistryValueKind.DWord;+ /// <summary>Reads the registry and returns whether the toggle is currently on.</summary>+ /// <returns><see langword="true"/> if the registry value matches <see cref="OnValue"/>; otherwise <see langword="false"/>.</returns>public bool GetState(){var value = GetRawValue();diff --git a/optimizerDuck/Domain/Exceptions/StepExecutionException.cs b/optimizerDuck/Domain/Exceptions/StepExecutionException.csindex c171b85..7ee07f7 100644--- a/optimizerDuck/Domain/Exceptions/StepExecutionException.cs+++ b/optimizerDuck/Domain/Exceptions/StepExecutionException.cs@@ -1,9 +1,22 @@namespace optimizerDuck.Domain.Exceptions;+/// <summary>+/// Represents an exception that occurred during the execution of an optimization step.+/// Carries both a user-facing error message and optional detailed diagnostic information.+/// </summary>public class StepExecutionException : Exception{+ /// <summary>+ /// Gets optional detailed error information (for example, exception details or stack trace)+ /// that can aid in diagnosing the failure.+ /// </summary>public string? ErrorDetail { get; }+ /// <summary>+ /// Initializes a new instance of the <see cref="StepExecutionException"/> class.+ /// </summary>+ /// <param name="error">A user-facing error message describing the failure.</param>+ /// <param name="errorDetail">Optional detailed diagnostic information.</param>public StepExecutionException(string? error, string? errorDetail): base(error ?? "Step execution failed"){diff --git a/optimizerDuck/Domain/Execution/ExecutionScope.cs b/optimizerDuck/Domain/Execution/ExecutionScope.csindex dcf8dab..344f66c 100644--- a/optimizerDuck/Domain/Execution/ExecutionScope.cs+++ b/optimizerDuck/Domain/Execution/ExecutionScope.cs@@ -8,6 +8,11 @@ using optimizerDuck.Resources.Languages;namespace optimizerDuck.Domain.Execution;+/// <summary>+/// Tracks the execution of optimization steps within an ambient async context.+/// Provider services use <see cref="Current"/> to record revert steps without+/// requiring explicit dependency injection.+/// </summary>public sealed class ExecutionScope : IDisposable{private static readonly AsyncLocal<ExecutionScope?> _current = new();diff --git a/optimizerDuck/Domain/Optimizations/Models/BaseOptimization.cs b/optimizerDuck/Domain/Optimizations/Models/BaseOptimization.csindex 7bccec0..8ae928d 100644--- a/optimizerDuck/Domain/Optimizations/Models/BaseOptimization.cs+++ b/optimizerDuck/Domain/Optimizations/Models/BaseOptimization.cs@@ -10,6 +10,12 @@ using OptimizationState = optimizerDuck.Domain.UI.OptimizationState;namespace optimizerDuck.Domain.Optimizations.Models;++/// <summary>+/// Base class for all optimizations. Subclasses implement <see cref="ApplyAsync"/> and are+/// decorated with <see cref="OptimizationAttribute"/> to provide metadata. The category+/// (<see cref="OwnerType"/>) is assigned automatically during reflection-based discovery.+/// </summary>public abstract class BaseOptimization : IOptimization{#region Metadata@@ -23,8 +29,14 @@ public abstract class BaseOptimization : IOptimization$"{GetType().Name} is missing [Optimization] attribute");+ /// <summary>+ /// Gets or sets the type of the category class that owns this optimization.+ /// Assigned automatically during reflection-based discovery in <c>OptimizationRegistry</c>.+ /// </summary>public Type? OwnerType { get; set; }+ /// <summary>Gets the name of the owner category class.</summary>+ /// <exception cref="InvalidOperationException">Thrown when <see cref="OwnerType"/> has not been assigned.</exception>public string OwnerKey =>OwnerType?.Name?? throw new InvalidOperationException($"{GetType().Name} has no owner assigned");@@ -33,14 +45,20 @@ public abstract class BaseOptimization : IOptimization#region Identification+ /// <summary>Gets the unique identifier for this optimization, parsed from the <see cref="OptimizationAttribute.Id"/>.</summary>public Guid Id => Guid.Parse(Meta.Id);++ /// <summary>Gets the risk level associated with this optimization.</summary>public OptimizationRisk Risk => Meta.Risk;++ /// <summary>Gets the unique key used for localization and identification.</summary>public string OptimizationKey => GetType().Name;#endregion#region Presentation+ /// <summary>Gets the visual representation (icon and localized text) of the risk level.</summary>public RiskVisual RiskVisual =>Risk switch{@@ -66,19 +84,29 @@ public abstract class BaseOptimization : IOptimization},};+ /// <summary>Gets the collection of tag displays for the UI, derived from <see cref="OptimizationTags"/>.</summary>public IEnumerable<OptimizationTagDisplay> TagDisplays => Meta.Tags.ToDisplays();+ /// <summary>Gets or sets the current applied state and timing information for this optimization.</summary>public OptimizationState State { get; set; } = new();#endregion#region Localization+ /// <summary>Gets the full localization prefix for this optimization.</summary>public string Prefix => Loc.Instance[$"Optimizer.{OwnerKey}.{OptimizationKey}"];++ /// <summary>Gets the localization prefix for progress messages.</summary>public string ProgressPrefix => Loc.Instance[$"{Prefix}.Progress"];++ /// <summary>Gets the localization prefix for error messages.</summary>public string ErrorPrefix => Loc.Instance[$"{Prefix}.Error"];+ /// <summary>Gets the localized display name of the optimization.</summary>public string Name => Loc.Instance[$"{Prefix}.Name"];++ /// <summary>Gets the localized short description of what this optimization does.</summary>public string ShortDescription => Loc.Instance[$"{Prefix}.ShortDescription"];#endregiondiff --git a/optimizerDuck/Domain/Optimizations/Models/OperationStepResult.cs b/optimizerDuck/Domain/Optimizations/Models/OperationStepResult.csindex c09c2a0..75fe1f0 100644--- a/optimizerDuck/Domain/Optimizations/Models/OperationStepResult.cs+++ b/optimizerDuck/Domain/Optimizations/Models/OperationStepResult.cs@@ -8,42 +8,42 @@ namespace optimizerDuck.Domain.Optimizations.Models;public record OperationStepResult{/// <summary>- /// The one-based index of this step in the execution order.+ /// Gets the one-based index of this step in the execution order./// </summary>public int Index { get; init; }/// <summary>- /// The name of the step.+ /// Gets the name of the step./// </summary>public string Name { get; init; } = string.Empty;/// <summary>- /// A description of what this step does.+ /// Gets a description of what this step does./// </summary>public string Description { get; init; } = string.Empty;/// <summary>- /// Indicates whether the step completed successfully.+ /// Gets a value that indicates whether the step completed successfully./// </summary>public bool Success { get; init; }/// <summary>- /// The error message if the step failed.+ /// Gets the error message if the step failed, or <see langword="null"/> if it succeeded./// </summary>public string? Error { get; init; }/// <summary>- /// Detailed error information (exception details) for the step failure.+ /// Gets detailed error information (exception details) for the step failure./// </summary>public string? ErrorDetail { get; init; }/// <summary>- /// An optional action to retry this step.+ /// Gets an optional action to retry this step./// </summary>public Func<Task<bool>>? RetryAction { get; init; }/// <summary>- /// The revert data generated when applying this step, used to support retry synchronization.+ /// Gets the revert data generated when applying this step, used to support retry synchronization./// </summary>public IRevertStep? RevertStep { get; init; }}diff --git a/optimizerDuck/Domain/Optimizations/Models/OptimizationContext.cs b/optimizerDuck/Domain/Optimizations/Models/OptimizationContext.csindex 48cf33b..bee6857 100644--- a/optimizerDuck/Domain/Optimizations/Models/OptimizationContext.cs+++ b/optimizerDuck/Domain/Optimizations/Models/OptimizationContext.cs@@ -4,22 +4,23 @@ using optimizerDuck.Services.System;namespace optimizerDuck.Domain.Optimizations.Models;/// <summary>-/// Provides context information for optimization execution.+/// Provides context information for optimization execution, including+/// logging, system state, and download capabilities./// </summary>public record OptimizationContext{/// <summary>- /// The logger instance used to record diagnostic messages during optimization.+ /// Gets the logger instance used to record diagnostic messages during optimization./// </summary>public required ILogger Logger { get; init; }/// <summary>- /// A snapshot of the current system hardware and software information.+ /// Gets a snapshot of the current system hardware and software information./// </summary>public required SystemSnapshot Snapshot { get; init; }/// <summary>- /// The service used to download remote resources required by optimizations.+ /// Gets the service used to download remote resources required by optimizations./// </summary>public required StreamService StreamService { get; init; }}diff --git a/optimizerDuck/Domain/Optimizations/Models/OptimizationResult.cs b/optimizerDuck/Domain/Optimizations/Models/OptimizationResult.csindex 5ab106f..e6917b9 100644--- a/optimizerDuck/Domain/Optimizations/Models/OptimizationResult.cs+++ b/optimizerDuck/Domain/Optimizations/Models/OptimizationResult.cs@@ -4,26 +4,28 @@ namespace optimizerDuck.Domain.Optimizations.Models;/// <summary>/// Represents the result of an optimization apply operation.+/// Includes the overall status, a human-readable message, and details+/// about any steps that failed./// </summary>public record OptimizationResult{/// <summary>- /// The status of the operation (Success, PartialSuccess, or Failed).+ /// Gets the status of the operation (Success, PartialSuccess, or Failed)./// </summary>public OptimizationSuccessResult Status { get; init; }/// <summary>- /// A message describing the result.+ /// Gets a human-readable message describing the result./// </summary>public string Message { get; init; } = string.Empty;/// <summary>- /// The exception that occurred, if any.+ /// Gets the exception that occurred, if any, during the apply operation./// </summary>public Exception? Exception { get; init; }/// <summary>- /// List of steps that failed during the operation.+ /// Gets the list of steps that failed during the operation./// </summary>public List<OperationStepResult> FailedSteps { get; init; } = [];}diff --git a/optimizerDuck/Domain/Revert/RevertData.cs b/optimizerDuck/Domain/Revert/RevertData.csindex 3a63e58..71af60f 100644--- a/optimizerDuck/Domain/Revert/RevertData.cs+++ b/optimizerDuck/Domain/Revert/RevertData.cs@@ -8,17 +8,19 @@ namespace optimizerDuck.Domain.Revert;public class RevertStepData{/// <summary>- /// The explicit index of this step in the execution sequence.+ /// Gets or sets the explicit 1-based index of this step in the execution sequence./// </summary>public int Index { get; set; }/// <summary>- /// The type of the revert step (e.g., "Registry", "Service", "Shell").+ /// Gets or sets the type of the revert step (e.g., "Registry", "Service", "Shell").+ /// Used for deserialization of the correct step type./// </summary>public string Type { get; set; } = string.Empty;/// <summary>- /// The serialized data for the step.+ /// Gets or sets the serialized JSON data for the revert step.+ /// The structure of this object depends on <see cref="Type"/>./// </summary>public JObject Data { get; set; } = new();}diff --git a/optimizerDuck/Domain/Revert/RevertResult.cs b/optimizerDuck/Domain/Revert/RevertResult.csindex c873ae0..a7b7720 100644--- a/optimizerDuck/Domain/Revert/RevertResult.cs+++ b/optimizerDuck/Domain/Revert/RevertResult.cs@@ -3,32 +3,34 @@namespace optimizerDuck.Domain.Revert;/// <summary>-/// Represents the result of a revert operation.+/// Represents the result of a revert operation, including success status,+/// a human-readable message, and details about any steps that failed./// </summary>public class RevertResult{/// <summary>- /// Indicates whether the revert was successful.+ /// Gets or sets a value that indicates whether the revert was fully successful./// </summary>public bool Success { get; set; }/// <summary>- /// A message describing the result.+ /// Gets or sets a human-readable message describing the result./// </summary>public string Message { get; set; } = string.Empty;/// <summary>- /// The exception that occurred, if any.+ /// Gets or sets the exception that occurred, if any, during the revert./// </summary>public Exception? Exception { get; set; }/// <summary>- /// Details of any steps that failed during revert.+ /// Gets or sets the list of steps that failed during the revert operation./// </summary>public List<OperationStepResult> FailedSteps { get; set; } = [];/// <summary>- /// Indicates whether the revert failed completely (all steps failed).+ /// Gets or sets a value that indicates whether the revert failed completely+ /// (that is, all individual steps failed)./// </summary>public bool AllStepsFailed { get; set; }}diff --git a/optimizerDuck/Domain/Revert/Steps/RegistryRevertStep.cs b/optimizerDuck/Domain/Revert/Steps/RegistryRevertStep.csindex 8ae1435..b424095 100644--- a/optimizerDuck/Domain/Revert/Steps/RegistryRevertStep.cs+++ b/optimizerDuck/Domain/Revert/Steps/RegistryRevertStep.cs@@ -14,37 +14,38 @@ namespace optimizerDuck.Domain.Revert.Steps;public class RegistryRevertStep : IRevertStep{/// <summary>- /// The action to perform (restore previous value or delete).+ /// Gets the action to perform (e.g., restore previous value, delete value, restore key tree)./// </summary>public RevertAction Action { get; init; }/// <summary>- /// The registry key path.+ /// Gets the registry key path (e.g., <c>HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer</c>)./// </summary>public string Path { get; init; } = string.Empty;/// <summary>- /// The registry value name, or <c>null</c> for the default value.+ /// Gets the registry value name, or <see langword="null"/> for the default value./// </summary>public string? Name { get; init; }/// <summary>- /// List of subkeys that were created during the apply operation (in order of creation, deepest first for cleanup)+ /// Gets the list of subkeys that were created during the apply operation.+ /// Ordered deepest first for correct cleanup order./// </summary>public IReadOnlyList<string>? CreatedSubKeys { get; init; }/// <summary>- /// Nested sub-steps to perform a complex action like restoring a full registry tree.+ /// Gets nested sub-steps to perform a complex action like restoring a full registry tree./// </summary>public IReadOnlyList<RegistryRevertStep>? SubSteps { get; init; }/// <summary>- /// The original registry value to restore.+ /// Gets the original registry value to restore, or <see langword="null"/> if the value did not exist./// </summary>public object? Value { get; init; }/// <summary>- /// The registry value kind (DWord, String, etc.).+ /// Gets the registry value kind (DWord, QWord, String, Binary, MultiString, ExpandString)./// </summary>public RegistryValueKind Kind { get; init; }diff --git a/optimizerDuck/Domain/Revert/Steps/ScheduledTaskRevertStep.cs b/optimizerDuck/Domain/Revert/Steps/ScheduledTaskRevertStep.csindex 10ad4c9..9159bd9 100644--- a/optimizerDuck/Domain/Revert/Steps/ScheduledTaskRevertStep.cs+++ b/optimizerDuck/Domain/Revert/Steps/ScheduledTaskRevertStep.cs@@ -12,12 +12,12 @@ namespace optimizerDuck.Domain.Revert.Steps;public class ScheduledTaskRevertStep : IRevertStep{/// <summary>- /// The full path of the scheduled task (e.g., \Microsoft\Windows\...).+ /// Gets or sets the full path of the scheduled task (e.g., <c>\Microsoft\Windows\...</c>)./// </summary>public string FullPath { get; set; } = string.Empty;/// <summary>- /// Whether the task was originally enabled before the optimization.+ /// Gets or sets a value that indicates whether the task was originally enabled before the optimization./// </summary>public bool OriginalEnabled { get; set; }diff --git a/optimizerDuck/Domain/Revert/Steps/ServiceRevertStep.cs b/optimizerDuck/Domain/Revert/Steps/ServiceRevertStep.csindex 96786dd..2dd91ed 100644--- a/optimizerDuck/Domain/Revert/Steps/ServiceRevertStep.cs+++ b/optimizerDuck/Domain/Revert/Steps/ServiceRevertStep.cs@@ -13,12 +13,12 @@ namespace optimizerDuck.Domain.Revert.Steps;public class ServiceRevertStep : IRevertStep{/// <summary>- /// The name of the Windows service to restore.+ /// Gets or sets the name of the Windows service to restore./// </summary>public string ServiceName { get; set; } = string.Empty;/// <summary>- /// The original startup type to restore the service to.+ /// Gets or sets the original startup type to restore the service to./// </summary>public ServiceStartupType OriginalStartupType { get; set; }diff --git a/optimizerDuck/Domain/Revert/Steps/ShellRevertStep.cs b/optimizerDuck/Domain/Revert/Steps/ShellRevertStep.csindex 7c239b1..436b5e6 100644--- a/optimizerDuck/Domain/Revert/Steps/ShellRevertStep.cs+++ b/optimizerDuck/Domain/Revert/Steps/ShellRevertStep.cs@@ -13,12 +13,12 @@ namespace optimizerDuck.Domain.Revert.Steps;public class ShellRevertStep : IRevertStep{/// <summary>- /// The type of shell to use for execution.+ /// Gets or sets the type of shell to use for execution (<see cref="ShellType.CMD"/> or <see cref="ShellType.PowerShell"/>)./// </summary>public ShellType ShellType { get; set; }/// <summary>- /// The command string to execute for reverting.+ /// Gets or sets the command string to execute for reverting./// </summary>public string Command { get; set; } = string.Empty;diff --git a/optimizerDuck/Domain/Revert/Steps/UsbPowerRevertStep.cs b/optimizerDuck/Domain/Revert/Steps/UsbPowerRevertStep.csindex 4e2c3d2..5a92574 100644--- a/optimizerDuck/Domain/Revert/Steps/UsbPowerRevertStep.cs+++ b/optimizerDuck/Domain/Revert/Steps/UsbPowerRevertStep.cs@@ -14,14 +14,24 @@ namespace optimizerDuck.Domain.Revert.Steps;public class UsbPowerRevertStep : IRevertStep{/// <summary>- /// A single device instance and its original enabled flag.+ /// Represents a single USB device instance and its original <c>MSPower_DeviceEnable</c> state./// </summary>public sealed class DeviceState{+ /// <summary>+ /// Gets or sets the WMI <c>InstanceName</c> of the USB device.+ /// </summary>public string InstanceName { get; set; } = string.Empty;++ /// <summary>+ /// Gets or sets a value that indicates whether the device was originally enabled.+ /// </summary>public bool Enable { get; set; }}+ /// <summary>+ /// Gets or sets the list of USB device states to restore.+ /// </summary>public IList<DeviceState> States { get; set; } = [];/// <inheritdoc />diff --git a/optimizerDuck/Services/Revert/RevertManager.cs b/optimizerDuck/Services/Revert/RevertManager.csindex 617248e..a61ccbf 100644--- a/optimizerDuck/Services/Revert/RevertManager.cs+++ b/optimizerDuck/Services/Revert/RevertManager.cs@@ -260,23 +260,10 @@ public class RevertManager(ILogger<RevertManager> _logger, ILoggerFactory _loggeif (!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- {- return await LoadAsyncUnlocked(path);- }- finally- {- lockObj?.Release();- }+ // Static reads are inherently safe with atomic writes (WriteJsonAtomicAsync uses temp+replace),+ // so we avoid allocating a SemaphoreSlim in the global dictionary for read-only operations.+ // This prevents unbounded dictionary growth from one-off reads that never call RemoveRevertData.+ return await LoadAsyncUnlocked(path);}private static async Task<RevertData?> LoadAsyncUnlocked(string path)diff --git a/optimizerDuck/Services/System/CrossPageEventBus.cs b/optimizerDuck/Services/System/CrossPageEventBus.csnew file mode 100644index 0000000..cd46071--- /dev/null+++ b/optimizerDuck/Services/System/CrossPageEventBus.cs@@ -0,0 +1,55 @@+namespace optimizerDuck.Services.System;++/// <summary>+/// Provides a thread-safe event bus for signaling cross-page data changes.+/// </summary>+/// <remarks>+/// When one ViewModel modifies data that another page displays, call <see cref="NotifyDataChanged{T}"/>+/// with the appropriate event type. The target ViewModel checks for pending changes in+/// <c>OnNavigatedToAsync</c> via <see cref="HasPendingRefresh{T}"/> to reload stale data.+/// <para>+/// Internally uses a <see cref="HashSet{T}"/> of <see cref="Type"/> keys behind a lock.+/// All type safety is enforced at compile time via the <see cref="ICrossPageEvent"/> constraint.+/// </para>+/// </remarks>+public static class CrossPageEventBus+{+ private static readonly HashSet<Type> _pendingEvents = [];++ /// <summary>+ /// Adds a pending refresh notification for the specified event type.+ /// </summary>+ /// <typeparam name="T">An event type that implements <see cref="ICrossPageEvent"/>.</typeparam>+ /// <remarks>+ /// The target page picks up this notification the next time it navigates to.+ /// Multiple notifications for the same type are coalesced into one.+ /// </remarks>+ public static void NotifyDataChanged<T>()+ where T : ICrossPageEvent+ {+ lock (_pendingEvents)+ {+ _pendingEvents.Add(typeof(T));+ }+ }++ /// <summary>+ /// Checks and consumes a pending refresh notification for the specified event type.+ /// </summary>+ /// <typeparam name="T">An event type that implements <see cref="ICrossPageEvent"/>.</typeparam>+ /// <returns>+ /// <see langword="true"/> if a refresh was pending; otherwise <see langword="false"/>.+ /// </returns>+ /// <remarks>+ /// This method removes the notification so subsequent calls return <see langword="false"/>+ /// until a new <see cref="NotifyDataChanged{T}"/> call arrives.+ /// </remarks>+ public static bool HasPendingRefresh<T>()+ where T : ICrossPageEvent+ {+ lock (_pendingEvents)+ {+ return _pendingEvents.Remove(typeof(T));+ }+ }+}diff --git a/optimizerDuck/Services/System/CrossPageEvents.cs b/optimizerDuck/Services/System/CrossPageEvents.csnew file mode 100644index 0000000..2522a73--- /dev/null+++ b/optimizerDuck/Services/System/CrossPageEvents.cs@@ -0,0 +1,40 @@+namespace optimizerDuck.Services.System;++/// <summary>+/// Defines a compile-time-safe token for cross-page data change events.+/// </summary>+/// <remarks>+/// Create a new event by declaring a stateless record that implements this interface:+/// <code language="csharp">public readonly record struct MyEvent : ICrossPageEvent;</code>+/// Use it with <see cref="CrossPageEventBus.NotifyDataChanged{T}"/> and+/// <see cref="CrossPageEventBus.HasPendingRefresh{T}"/>.+/// </remarks>+public interface ICrossPageEvent;++/// <summary>+/// Signals that scheduled tasks were added, removed, or toggled.+/// </summary>+/// <remarks>+/// Fired by <see cref="optimizerDuck.UI.ViewModels.Pages.ScheduledTasksViewModel"/> after toggling a task.+/// Consumed by <see cref="optimizerDuck.UI.ViewModels.Pages.StartupManagerViewModel"/> to reload its Tasks section.+/// </remarks>+public readonly record struct ScheduledTasksChanged : ICrossPageEvent;++/// <summary>+/// Signals that startup apps or tasks were added, removed, or toggled.+/// </summary>+/// <remarks>+/// Fired by <see cref="optimizerDuck.UI.ViewModels.Pages.StartupManagerViewModel"/> after toggling a startup task.+/// Consumed by <see cref="optimizerDuck.UI.ViewModels.Pages.ScheduledTasksViewModel"/> to reload all tasks.+/// </remarks>+public readonly record struct StartupAppsChanged : ICrossPageEvent;++/// <summary>+/// Signals that bloatware packages were removed or may have changed externally.+/// </summary>+/// <remarks>+/// Fired by <see cref="optimizerDuck.UI.ViewModels.Pages.BloatwareViewModel"/> after removing packages.+/// Consumed by <see cref="optimizerDuck.UI.ViewModels.Pages.StartupManagerViewModel"/> (reloads tasks)+/// and <see cref="optimizerDuck.UI.ViewModels.Pages.BloatwareViewModel"/> (full refresh on re-navigation).+/// </remarks>+public readonly record struct BloatwareChanged : ICrossPageEvent;diff --git a/optimizerDuck/Services/System/RegistryWatcher.cs b/optimizerDuck/Services/System/RegistryWatcher.csindex a32d2ec..cf330dd 100644--- a/optimizerDuck/Services/System/RegistryWatcher.cs+++ b/optimizerDuck/Services/System/RegistryWatcher.cs@@ -118,56 +118,89 @@ internal sealed class RegistryWatcher(ILogger<RegistryWatcher> logger) : IRegist{while (!token.IsCancellationRequested){+ IntPtr hKey = IntPtr.Zero;+ AutoResetEvent? evt = null;+ RegisteredWaitHandle? registeredWait = null;+try{- lock (_lock)+ var (hive, subKey) = ParseRegistryPath(_path);+ var error = NativeMethods.RegOpenKeyEx(+ hive,+ subKey,+ 0,+ NativeMethods.KEY_NOTIFY,+ out hKey+ );++ if (error != 0 || hKey == IntPtr.Zero){- if (_disposed || token.IsCancellationRequested)- return;+ await Task.Delay(1000, token);+ continue;+ }- var (hive, subKey) = ParseRegistryPath(_path);- var error = NativeMethods.RegOpenKeyEx(- hive,- subKey,- 0,- NativeMethods.KEY_NOTIFY,- out _hKey- );+ evt = new AutoResetEvent(false);- 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- );+ var notifyError = NativeMethods.RegNotifyChangeKeyValue(+ hKey,+ false,+ NativeMethods.REG_NOTIFY_CHANGE_LAST_SET+ | NativeMethods.REG_NOTIFY_CHANGE_NAME,+ evt.SafeWaitHandle.DangerousGetHandle(),+ true+ );+ if (notifyError != 0)+ {+ NativeMethods.RegCloseKey(hKey);+ hKey = IntPtr.Zero;+ evt.Dispose();+ evt = null;+ await Task.Delay(1000, token);+ continue;+ }++ registeredWait = ThreadPool.RegisterWaitForSingleObject(+ evt,+ OnKeyChangedCallback,+ null,+ Timeout.Infinite,+ true+ );++ // Store handles only after ALL setup steps succeed+ lock (_lock)+ {+ if (_disposed || token.IsCancellationRequested)+ {+ registeredWait.Unregister(null);+ NativeMethods.RegCloseKey(hKey);+ evt.Dispose();return;}++ _hKey = hKey;+ _event = evt;+ _registeredWait = registeredWait;}- await Task.Delay(1000, token);+ return; // Successfully armed}- catch (Exception ex)+ catch (Exception ex) when (!token.IsCancellationRequested){+ // Cleanup local resources on failure before retry+ if (registeredWait != null)+ registeredWait.Unregister(null);+ if (hKey != IntPtr.Zero)+ NativeMethods.RegCloseKey(hKey);+ evt?.Dispose();+_logger.LogWarning(ex,"RegistryWatcher: Failed to watch {Path}, retrying",_path);+try{await Task.Delay(1000, token);diff --git a/optimizerDuck/Services/System/SystemInfoService.cs b/optimizerDuck/Services/System/SystemInfoService.csindex 69de060..26db72b 100644--- a/optimizerDuck/Services/System/SystemInfoService.cs+++ b/optimizerDuck/Services/System/SystemInfoService.cs@@ -691,7 +691,10 @@ internal static class NativeMemoryinternal static class CpuProvider{- private static CpuInfo? _cachedStatic;+ private static readonly Lazy<CpuInfo> _cached = new(+ Load,+ LazyThreadSafetyMode.ExecutionAndPublication+ );/// <summary>/// Gets CPU info using Registry (fast) + targeted WMI (only for cache sizes).@@ -699,13 +702,11 @@ internal static class CpuProvider/// </summary>public static CpuInfo Get(){- if (_cachedStatic != null)- {- // Only current clock speed changes, but we'll stick to max/registry value for stability- // unless we really need real-time tracking (which WMI isn't great for anyway)- return _cachedStatic;- }+ return _cached.Value;+ }+ private static CpuInfo Load()+ {try{// ── Fast path: Registry ──────────────────────────────────────@@ -733,7 +734,7 @@ internal static class CpuProvider// ── Targeted WMI: only fields not available in Registry ──────var cores = 0;- var maxMHz = currentMHz; // fallback to registry MHz+ var maxMHz = currentMHz;var l2kb = 0;var l3kb = 0;@@ -749,12 +750,12 @@ internal static class CpuProvider}if (cores == 0)- cores = threads; // fallback+ cores = threads;var vendor = DetectCpuVendor(manufacturer);var architecture = Environment.Is64BitOperatingSystem ? "64-bit" : "32-bit";- _cachedStatic = new CpuInfo+ return new CpuInfo{Name = name,Manufacturer = manufacturer,@@ -767,8 +768,6 @@ internal static class CpuProviderL2CacheKB = l2kb,L3CacheKB = l3kb,};-- return _cachedStatic;}catch{@@ -789,7 +788,10 @@ internal static class CpuProviderinternal static class RamProvider{- private static List<RamModule>? _cachedModules;+ private static readonly Lazy<List<RamModule>> _cachedModules = new(+ LoadPhysicalModules,+ LazyThreadSafetyMode.ExecutionAndPublication+ );/// <summary>/// Gets RAM info using GlobalMemoryStatusEx (same API as Task Manager)@@ -799,7 +801,7 @@ internal static class RamProvider{try{- var modules = GetPhysicalModules();+ var modules = _cachedModules.Value;var (totalGB, totalMB, totalKB, availableGB, usedPercent, usedGB) = GetMemoryStats(modules);@@ -821,11 +823,8 @@ internal static class RamProvider}}- private static List<RamModule> GetPhysicalModules()+ private static List<RamModule> LoadPhysicalModules(){- if (_cachedModules != null)- return _cachedModules;-var modules = new List<RamModule>();var physicalMemory = WmiHelper.Query("SELECT Capacity, Speed, Manufacturer, PartNumber, DeviceLocator FROM Win32_PhysicalMemory"@@ -852,7 +851,6 @@ internal static class RamProvider);}- _cachedModules = modules;return modules;}diff --git a/optimizerDuck/Services/UI/BloatwareService.cs b/optimizerDuck/Services/UI/BloatwareService.csindex 83ba48e..40077f3 100644--- a/optimizerDuck/Services/UI/BloatwareService.cs+++ b/optimizerDuck/Services/UI/BloatwareService.cs@@ -15,9 +15,6 @@ using JsonSerializer = System.Text.Json.JsonSerializer;namespace optimizerDuck.Services.UI;-/// <summary>-/// Provides services for discovering and removing AppX bloatware packages.-/// </summary>public class BloatwareService(ILogger<BloatwareService> logger,IOptionsMonitor<AppSettings> appOptionsMonitor@@ -288,8 +285,13 @@ public class BloatwareService().ThenByDescending(g => g.Count());+ // Limit to first 10 groups to avoid excessive I/O for packages with many files+ var groupCount = 0;foreach (var group in groups){+ if (++groupCount > 10)+ break;+var preferredSize = GuessLogicalBaseSize(group.Key);var best = group.Select(path => new LogoVariant(path, preferredSize, true))diff --git a/optimizerDuck/Services/UI/DiskCleanupService.cs b/optimizerDuck/Services/UI/DiskCleanupService.csindex a9c4330..46bfdf8 100644--- a/optimizerDuck/Services/UI/DiskCleanupService.cs+++ b/optimizerDuck/Services/UI/DiskCleanupService.cs@@ -7,9 +7,6 @@ using CleanupItem = optimizerDuck.Domain.Optimizations.Models.Cleanup.CleanupItenamespace optimizerDuck.Services.UI;-/// <summary>-/// Provides services for cleaning up disk space (temp files, caches, etc.).-/// </summary>public class DiskCleanupService(ILogger<DiskCleanupService> logger){private static readonly string DotNetTempPath =@@ -240,20 +237,29 @@ public class DiskCleanupService(ILogger<DiskCleanupService> logger)try{var searchPattern = itemId == "Thumbnails" ? "thumbcache_*" : "*";+ var isRecursive = itemId != "Thumbnails";var options = new EnumerationOptions{IgnoreInaccessible = true,- RecurseSubdirectories = itemId != "Thumbnails",+ RecurseSubdirectories = isRecursive,ReturnSpecialDirectories = false,};var dirInfo = new DirectoryInfo(path);+ // Pre-check: only filter .net path if the .net temp directory is a descendant of the scan root+ var needsDotNetFilter =+ isRecursive+ && DotNetTempPath.StartsWith(+ path.TrimEnd(Path.DirectorySeparatorChar) + Path.DirectorySeparatorChar,+ StringComparison.OrdinalIgnoreCase+ );+foreach (var fileInfo in dirInfo.EnumerateFiles(searchPattern, options))try{- // Skip .net temp files if we are doing recursive search- if (options.RecurseSubdirectories)+ // Skip .net temp files (only when necessary)+ if (needsDotNetFilter){var fullDirPath = fileInfo.DirectoryName ?? string.Empty;fullDirPath =@@ -293,20 +299,29 @@ public class DiskCleanupService(ILogger<DiskCleanupService> logger)long freed = 0;var searchPattern = itemId == "Thumbnails" ? "thumbcache_*" : "*";+ var isRecursive = itemId != "Thumbnails";var options = new EnumerationOptions{IgnoreInaccessible = true,- RecurseSubdirectories = itemId != "Thumbnails",+ RecurseSubdirectories = isRecursive,ReturnSpecialDirectories = false,};var dirInfo = new DirectoryInfo(path);+ // Pre-check: only filter .net path if the root path itself is related+ var needsDotNetFilter =+ isRecursive+ && path.StartsWith(+ DotNetTempPath.TrimEnd(Path.DirectorySeparatorChar),+ StringComparison.OrdinalIgnoreCase+ );+// Delete filesforeach (var fileInfo in dirInfo.EnumerateFiles(searchPattern, options))try{- if (options.RecurseSubdirectories)+ if (needsDotNetFilter){var fullDirPath = fileInfo.DirectoryName ?? string.Empty;fullDirPath =diff --git a/optimizerDuck/Services/UI/StartupManagerService.cs b/optimizerDuck/Services/UI/StartupManagerService.csindex cc6f900..7e6510b 100644--- a/optimizerDuck/Services/UI/StartupManagerService.cs+++ b/optimizerDuck/Services/UI/StartupManagerService.cs@@ -1,6 +1,7 @@using System.Diagnostics;using System.Drawing;using System.IO;+using System.Runtime.InteropServices;using System.Windows;using System.Windows.Interop;using System.Windows.Media.Imaging;@@ -361,39 +362,24 @@ public class StartupManagerService(ILogger<StartupManagerService> logger)/// <summary>Extracts the associated icon from an executable path or command string. Expands environment variables and searches PATH if needed.</summary>/// <param name="command">The command or file path to extract the icon from.</param>/// <returns>A frozen <see cref="BitmapSource"/> suitable for cross-thread UI binding, or <see langword="null"/> if the icon cannot be extracted.</returns>- /// <example>- /// <code language="csharp">- /// var icon = StartupManagerService.ExtractIcon(@"C:\Windows\System32\notepad.exe");- /// </code>- /// </example>+ /// <remarks>+ /// Uses <c>SHGetFileInfo</c> with <c>SHGFI_LARGEICON</c> (48x48) for higher quality icons+ /// where possible, falling back to <see cref="Icon.ExtractAssociatedIcon"/> (32x32) if the+ /// P/Invoke approach fails.+ /// </remarks>public static BitmapSource? ExtractIcon(string command){try{- var path = command.Trim('\"');+ var path = ResolveExecutablePath(command);+ if (path == null)+ return null;- // Expand environment variables (e.g., %USERPROFILE%, %ProgramFiles%) so that- // shortcut/command paths using them can be resolved to the actual executable for icon extraction.- path = Environment.ExpandEnvironmentVariables(path);- var exeIdx = path.IndexOf(".exe", StringComparison.OrdinalIgnoreCase);- if (exeIdx > 0)- path = path[..(exeIdx + 4)].Trim('\"', ' ', '\'');-- if (!File.Exists(path))- {- // try to see if it is in PATH- if (!path.Contains('\\') && !path.Contains('/'))- {- path = GetFullPathFromEnvironment(path);- if (string.IsNullOrEmpty(path) || !File.Exists(path))- return null;- }- else- {- return null;- }- }+ var iconSource = ExtractIconWithShGetFileInfo(path);+ if (iconSource != null)+ return iconSource;+ // fallback to ExtractAssociatedIcon (32x32)using var icon = Icon.ExtractAssociatedIcon(path);if (icon != null){@@ -402,18 +388,110 @@ public class StartupManagerService(ILogger<StartupManagerService> logger)Int32Rect.Empty,BitmapSizeOptions.FromEmptyOptions());- imageSource.Freeze(); // Crucial for cross-thread access+ imageSource.Freeze();return imageSource;}}catch{- // Ignored, fallback to generic or null+ // ignored, fallback to generic or null+ }++ return null;+ }++ private static string? ResolveExecutablePath(string command)+ {+ var path = command.Trim('\"');++ // expand environment variables (e.g., %USERPROFILE%, %ProgramFiles%)+ path = Environment.ExpandEnvironmentVariables(path);+ var exeIdx = path.IndexOf(".exe", StringComparison.OrdinalIgnoreCase);+ if (exeIdx > 0)+ path = path[..(exeIdx + 4)].Trim('\"', ' ', '\'');++ if (!File.Exists(path))+ {+ // try to see if it is in PATH+ if (!path.Contains('\\') && !path.Contains('/'))+ {+ path = GetFullPathFromEnvironment(path);+ if (string.IsNullOrEmpty(path) || !File.Exists(path))+ return null;+ }+ else+ {+ return null;+ }+ }++ return path;+ }++ [DllImport("shell32.dll", CharSet = CharSet.Auto)]+ private static extern IntPtr SHGetFileInfo(+ string pszPath,+ uint dwFileAttributes,+ ref SHFILEINFO psfi,+ uint cbFileInfo,+ uint uFlags+ );++ private const uint SHGFI_ICON = 0x000000100;+ private const uint SHGFI_LARGEICON = 0x000000000; // 48x48++ [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]+ private struct SHFILEINFO+ {+ public IntPtr hIcon;+ public int iIcon;+ public uint dwAttributes;++ [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]+ public string szDisplayName;++ [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 80)]+ public string szTypeName;+ }++ private static BitmapSource? ExtractIconWithShGetFileInfo(string path)+ {+ var shfi = new SHFILEINFO();+ var result = SHGetFileInfo(+ path,+ 0,+ ref shfi,+ (uint)Marshal.SizeOf<SHFILEINFO>(),+ SHGFI_ICON | SHGFI_LARGEICON+ );++ if (result != IntPtr.Zero && shfi.hIcon != IntPtr.Zero)+ {+ try+ {+ var imageSource = Imaging.CreateBitmapSourceFromHIcon(+ shfi.hIcon,+ Int32Rect.Empty,+ BitmapSizeOptions.FromEmptyOptions()+ );+ imageSource.Freeze();+ return imageSource;+ }+ finally+ {+ NativeMethods.DestroyIcon(shfi.hIcon);+ }}return null;}+ private static class NativeMethods+ {+ [DllImport("user32.dll", SetLastError = true)]+ internal static extern bool DestroyIcon(IntPtr hIcon);+ }+/// <summary>Resolves a file name to its full path by searching the directories listed in the PATH environment variable.</summary>/// <param name="fileName">The file name (e.g., "notepad.exe") to resolve.</param>/// <returns>The full path if found, otherwise <see langword="null"/>.</returns>diff --git a/optimizerDuck/UI/ViewModels/Optimizer/OptimizationCategoryViewModel.cs b/optimizerDuck/UI/ViewModels/Optimizer/OptimizationCategoryViewModel.csindex 7cddcdb..c2cbdfe 100644--- a/optimizerDuck/UI/ViewModels/Optimizer/OptimizationCategoryViewModel.cs+++ b/optimizerDuck/UI/ViewModels/Optimizer/OptimizationCategoryViewModel.cs@@ -153,7 +153,7 @@ public partial class OptimizationCategoryViewModel : ViewModel#region Commands/// <summary>- /// Toggles the optimization.+ /// Toggles the optimization (apply if not applied, revert if applied)./// </summary>/// <param name="optimization">The optimization to toggle.</param>[RelayCommand(CanExecute = nameof(CanToggleOptimization))]@@ -161,173 +161,25 @@ public partial class OptimizationCategoryViewModel : ViewModel{try{- // Keep a stable reference to the previous state in case we need to roll back UI changes.var wasApplied = await RevertManager.IsAppliedAsync(optimization.Id);- var restorePointCreated = false;- if (!_optimizationService.WasRequestedRestorePoint)- {- var (proceed, created) = await HandleRestorePointAsync();- if (!proceed)- {- optimization.State.IsApplied = wasApplied;- return;- }-- restorePointCreated = created;- _optimizationService.WasRequestedRestorePoint = true;- }+ var (canProceed, restorePointCreated) = await EnsureRestorePointAsync(+ optimization,+ wasApplied+ );+ if (!canProceed)+ return;try{- // Apply optimization if not already appliedif (!wasApplied)- {- _logger.LogInformation(- "===== START applying optimization {OptimizationName} ({OptimizationId}) =====",- optimization.OptimizationKey,- optimization.Id- );- var applyResult = await RunWithProcessingDialogAsync(- optimization,- progress => _optimizationService.ApplyAsync(optimization, progress)- );-- // If result status is completely Failed, we can't retry it- if (applyResult.Status == OptimizationSuccessResult.Failed)- {- ShowOperationOutcomeSnackbar(- OperationNotificationState.Failed,- OptimizationOperation.Apply,- applyResult.Message,- restorePointCreated- );-- _logger.LogWarning(- "Apply failed {Name} optimization: {Message}",- optimization.OptimizationKey,- applyResult.Message- );-- _logger.LogInformation(- "===== END applying optimization {OptimizationName} ({OptimizationId}) =====",- optimization.OptimizationKey,- optimization.Id- );-- await OptimizationService.UpdateOptimizationStateAsync(optimization);- OnPropertyChanged(nameof(HasAppliedOptimizations));- return;- }-- ((App)Application.Current).HasPendingChanges = true;-- // Retry only if there are some successful steps and some failed steps- var retryOutcome = await HandleRetryableFailuresAsync(- optimization,- applyResult.FailedSteps,- OptimizationOperation.Apply- );-- // Explicitly update state after all operations complete- await OptimizationService.UpdateOptimizationStateAsync(optimization);-- // Ensure UI reflects the correct state- OnPropertyChanged(nameof(HasAppliedOptimizations));-- var notificationState = ResolveApplyNotificationState(- applyResult,- retryOutcome- );-- ShowOperationOutcomeSnackbar(- notificationState,- OptimizationOperation.Apply,- applyResult.Message,- restorePointCreated- );-- if (notificationState == OperationNotificationState.Success)- _logger.LogInformation(- "Successfully applied {Name}",- optimization.OptimizationKey- );- else if (notificationState == OperationNotificationState.Partial)- _logger.LogWarning(- "Partially applied {Name}",- optimization.OptimizationKey- );- else- _logger.LogWarning("Failed to apply {Name}", optimization.OptimizationKey);-- _logger.LogInformation(- "===== END applying optimization {OptimizationName} ({OptimizationId}) =====",- optimization.OptimizationKey,- optimization.Id- );- }+ await ApplyOptimizationAsync(optimization, restorePointCreated);else- {- // Revert optimization if already applied- _logger.LogInformation(- "===== START reverting optimization {OptimizationName} ({OptimizationId}) =====",- optimization.OptimizationKey,- optimization.Id- );-- var revertResult = await RunWithProcessingDialogAsync(- optimization,- progress => _optimizationService.RevertAsync(optimization, progress)- );-- ((App)Application.Current).HasPendingChanges = true;-- var retryOutcome = await HandleRetryableFailuresAsync(- optimization,- revertResult.FailedSteps,- OptimizationOperation.Revert- );-- // Explicitly update state after revert completes- await OptimizationService.UpdateOptimizationStateAsync(optimization);-- // Ensure UI reflects the correct state- OnPropertyChanged(nameof(HasAppliedOptimizations));-- var notificationState = ResolveRevertNotificationState(- revertResult,- retryOutcome- );-- ShowOperationOutcomeSnackbar(- notificationState,- OptimizationOperation.Revert,- revertResult.Message,- restorePointCreated- );-- if (notificationState == OperationNotificationState.Success)- _logger.LogInformation(- "Successfully reverted {Name}",- optimization.OptimizationKey- );- else if (notificationState == OperationNotificationState.Partial)- _logger.LogWarning(- "Partially reverted {Name}",- optimization.OptimizationKey- );- else- _logger.LogWarning("Failed to revert {Name}", optimization.OptimizationKey);- _logger.LogInformation(- "===== END reverting optimization {OptimizationName} ({OptimizationId}) =====",- optimization.OptimizationKey,- optimization.Id- );- }+ await RevertOptimizationAsync(optimization, restorePointCreated);}catch (Exception ex){- optimization.State.IsApplied = wasApplied; // revert UI state on failure+ optimization.State.IsApplied = wasApplied;_logger.LogError(ex,"Failed to toggle optimization {Name}",@@ -352,9 +204,157 @@ public partial class OptimizationCategoryViewModel : ViewModel}/// <summary>- /// Shows the details of an optimization.+ /// Ensures a restore point is created before modifying system settings.+ /// </summary>+ /// <returns>(canProceed, restorePointCreated).</returns>+ private async Task<(bool Proceed, bool RestorePointCreated)> EnsureRestorePointAsync(+ IOptimization optimization,+ bool wasApplied+ )+ {+ if (_optimizationService.WasRequestedRestorePoint)+ return (true, false);++ var (proceed, created) = await HandleRestorePointAsync();+ if (!proceed)+ {+ optimization.State.IsApplied = wasApplied;+ return (false, false);+ }++ _optimizationService.WasRequestedRestorePoint = true;+ return (true, created);+ }++ /// <summary>+ /// Applies an optimization with progress reporting and retry handling.+ /// </summary>+ /// <param name="optimization">The optimization to apply.</param>+ /// <param name="restorePointCreated">Whether a system restore point was created beforehand.</param>+ private async Task ApplyOptimizationAsync(IOptimization optimization, bool restorePointCreated)+ {+ _logger.LogInformation(+ "===== START applying {Name} ({Id}) =====",+ optimization.OptimizationKey,+ optimization.Id+ );++ var applyResult = await RunWithProcessingDialogAsync(+ optimization,+ p => _optimizationService.ApplyAsync(optimization, p)+ );++ // Complete failure: can't retry+ if (applyResult.Status == OptimizationSuccessResult.Failed)+ {+ ShowOperationOutcomeSnackbar(+ OperationNotificationState.Failed,+ OptimizationOperation.Apply,+ applyResult.Message,+ restorePointCreated+ );+ _logger.LogWarning("Apply failed: {Message}", applyResult.Message);+ await FinalizeOperationAsync(optimization);+ return;+ }++ ((App)Application.Current).HasPendingChanges = true;++ var retryOutcome = await HandleRetryableFailuresAsync(+ optimization,+ applyResult.FailedSteps,+ OptimizationOperation.Apply+ );++ var notificationState = ResolveApplyNotificationState(applyResult, retryOutcome);+ await FinalizeOperationAsync(optimization);+ ShowOperationOutcomeSnackbar(+ notificationState,+ OptimizationOperation.Apply,+ applyResult.Message,+ restorePointCreated+ );++ LogOperationOutcome(notificationState, "apply", optimization);+ _logger.LogInformation(+ "===== END applying {Name} ({Id}) =====",+ optimization.OptimizationKey,+ optimization.Id+ );+ }++ /// <summary>+ /// Reverts an optimization with progress reporting and retry handling./// </summary>- /// <param name="optimization">The optimization to show details for.</param>+ /// <param name="optimization">The optimization to revert.</param>+ /// <param name="restorePointCreated">Whether a system restore point was created beforehand.</param>+ private async Task RevertOptimizationAsync(IOptimization optimization, bool restorePointCreated)+ {+ _logger.LogInformation(+ "===== START reverting {Name} ({Id}) =====",+ optimization.OptimizationKey,+ optimization.Id+ );++ var revertResult = await RunWithProcessingDialogAsync(+ optimization,+ p => _optimizationService.RevertAsync(optimization, p)+ );++ ((App)Application.Current).HasPendingChanges = true;++ var retryOutcome = await HandleRetryableFailuresAsync(+ optimization,+ revertResult.FailedSteps,+ OptimizationOperation.Revert+ );++ var notificationState = ResolveRevertNotificationState(revertResult, retryOutcome);+ await FinalizeOperationAsync(optimization);+ ShowOperationOutcomeSnackbar(+ notificationState,+ OptimizationOperation.Revert,+ revertResult.Message,+ restorePointCreated+ );++ LogOperationOutcome(notificationState, "revert", optimization);+ _logger.LogInformation(+ "===== END reverting {Name} ({Id}) =====",+ optimization.OptimizationKey,+ optimization.Id+ );+ }++ /// <summary>+ /// Updates optimization state and notifies the UI.+ /// </summary>+ private static async Task FinalizeOperationAsync(IOptimization optimization)+ {+ await OptimizationService.UpdateOptimizationStateAsync(optimization);+ }++ private void LogOperationOutcome(+ OperationNotificationState notificationState,+ string operationName,+ IOptimization optimization+ )+ {+ var level =+ notificationState == OperationNotificationState.Success ? LogLevel.Information+ : notificationState == OperationNotificationState.Partial ? LogLevel.Warning+ : LogLevel.Warning;++ var message =+ notificationState == OperationNotificationState.Success+ ? $"Successfully {operationName}d"+ : notificationState == OperationNotificationState.Partial+ ? $"Partially {operationName}d"+ : $"Failed to {operationName}";++ _logger.Log(level, "{Message}: {Name}", message, optimization.OptimizationKey);+ }+[RelayCommand]private async Task ShowDetailsAsync(IOptimization optimization){diff --git a/optimizerDuck/UI/ViewModels/Pages/BloatwareViewModel.cs b/optimizerDuck/UI/ViewModels/Pages/BloatwareViewModel.csindex 1802d04..e7d250b 100644--- a/optimizerDuck/UI/ViewModels/Pages/BloatwareViewModel.cs+++ b/optimizerDuck/UI/ViewModels/Pages/BloatwareViewModel.cs@@ -6,6 +6,7 @@ using Microsoft.Extensions.Logging;using optimizerDuck.Domain.Optimizations.Models.Bloatware;using optimizerDuck.Domain.UI;using optimizerDuck.Resources.Languages;+using optimizerDuck.Services.System;using optimizerDuck.Services.UI;using optimizerDuck.UI.Dialogs;using optimizerDuck.UI.ViewModels.Dialogs;@@ -88,13 +89,27 @@ public partial class BloatwareViewModel : ViewModelApplyFilter();}+ public override async Task OnNavigatedToAsync()+ {+ await base.OnNavigatedToAsync();++ if (CrossPageEventBus.HasPendingRefresh<BloatwareChanged>())+ await Refresh();+ }+protected override async Task InitializeOnceAsync(){IsLoading = true;- var appxPackages = await _bloatwareService.GetAppXPackagesAsync();- _allPackages.AddRange(appxPackages);- ApplyFilter();- IsLoading = false;+ try+ {+ var appxPackages = await _bloatwareService.GetAppXPackagesAsync();+ _allPackages.AddRange(appxPackages);+ ApplyFilter();+ }+ finally+ {+ IsLoading = false;+ }}private void ApplyFilter()@@ -243,6 +258,7 @@ public partial class BloatwareViewModel : ViewModel);dialog.Hide();await Refresh();+ CrossPageEventBus.NotifyDataChanged<BloatwareChanged>();}}@@ -259,10 +275,16 @@ public partial class BloatwareViewModel : ViewModelAppxPackages.Clear();UpdateProperties();- var appxPackages = await _bloatwareService.GetAppXPackagesAsync();- _allPackages.AddRange(appxPackages);- ApplyFilter();- IsLoading = false;+ try+ {+ var appxPackages = await _bloatwareService.GetAppXPackagesAsync();+ _allPackages.AddRange(appxPackages);+ ApplyFilter();+ }+ finally+ {+ IsLoading = false;+ }}[RelayCommand]diff --git a/optimizerDuck/UI/ViewModels/Pages/ScheduledTasksViewModel.cs b/optimizerDuck/UI/ViewModels/Pages/ScheduledTasksViewModel.csindex aa4a25e..cd5cc2d 100644--- a/optimizerDuck/UI/ViewModels/Pages/ScheduledTasksViewModel.cs+++ b/optimizerDuck/UI/ViewModels/Pages/ScheduledTasksViewModel.cs@@ -6,6 +6,7 @@ using CommunityToolkit.Mvvm.Input;using Microsoft.Extensions.Logging;using optimizerDuck.Resources.Languages;using optimizerDuck.Services.Optimization.Providers;+using optimizerDuck.Services.System;using optimizerDuck.UI.Dialogs;using Wpf.Ui;using Wpf.Ui.Controls;@@ -53,6 +54,14 @@ public partial class ScheduledTasksViewModel : ViewModelpublic bool HasResults => Tasks.Count > 0;public bool ShowRefreshButton => IsNotLoading && HasResults;+ public override async Task OnNavigatedToAsync()+ {+ await base.OnNavigatedToAsync();++ if (CrossPageEventBus.HasPendingRefresh<StartupAppsChanged>())+ await LoadDataAsync();+ }+protected override async Task InitializeOnceAsync(){await LoadDataAsync();@@ -470,6 +479,7 @@ public partial class ScheduledTasksViewModel : ViewModeltry{await ToggleTask(task);+ CrossPageEventBus.NotifyDataChanged<ScheduledTasksChanged>();}catch (Exception ex){diff --git a/optimizerDuck/UI/ViewModels/Pages/SettingsViewModel.cs b/optimizerDuck/UI/ViewModels/Pages/SettingsViewModel.csindex 63493be..6062c2b 100644--- a/optimizerDuck/UI/ViewModels/Pages/SettingsViewModel.cs+++ b/optimizerDuck/UI/ViewModels/Pages/SettingsViewModel.cs@@ -1,6 +1,7 @@using System.Collections.ObjectModel;using System.Diagnostics;using System.Globalization;+using System.Windows;using System.Windows.Media;using CommunityToolkit.Mvvm.ComponentModel;using CommunityToolkit.Mvvm.Input;@@ -365,30 +366,38 @@ public partial class SettingsViewModel(return;var oldValue = appOptionsMonitor.CurrentValue.App.Language;- _ = SaveConfigAsync(+ _ = SafeFireAndForgetAsync(async () =>{await configManager.SetAsync(x => x.App.Language, value);},async () =>{- SelectedCultureName = oldValue;+ await Application.Current.Dispatcher.InvokeAsync(() =>+ SelectedCultureName = oldValue+ );});if (value == Loc.CurrentCulture.Name)return;- _ = contentDialogService- .ShowAlertAsync(- Translations.Settings_LanguageChanged_Title,- Translations.Settings_LanguageChanged_Description,- Translations.Button_Ok,- CancellationToken.None- )- .ContinueWith(- t => logger.LogError(t.Exception, "Failed to show language changed dialog"),- TaskContinuationOptions.OnlyOnFaulted- );++ _ = SafeFireAndForgetAsync(async () =>+ {+ try+ {+ await contentDialogService.ShowAlertAsync(+ Translations.Settings_LanguageChanged_Title,+ Translations.Settings_LanguageChanged_Description,+ Translations.Button_Ok,+ CancellationToken.None+ );+ }+ catch (Exception ex)+ {+ logger.LogError(ex, "Failed to show language changed dialog");+ }+ });}partial void OnCurrentApplicationThemeChanged(@@ -433,4 +442,33 @@ public partial class SettingsViewModel(}#endregion Property Changed++ /// <summary>+ /// Fires an async task without awaiting it, but catches all exceptions+ /// </summary>+ private async Task SafeFireAndForgetAsync(+ Func<Task> taskFactory,+ Func<Task>? revertAction = null+ )+ {+ try+ {+ await taskFactory();+ }+ catch (Exception ex)+ {+ logger.LogError(ex, "An error occurred in a fire-and-forget operation");+ if (revertAction != null)+ {+ try+ {+ await revertAction();+ }+ catch (Exception revertEx)+ {+ logger.LogError(revertEx, "Failed to revert after error");+ }+ }+ }+ }}diff --git a/optimizerDuck/UI/ViewModels/Pages/StartupManagerViewModel.cs b/optimizerDuck/UI/ViewModels/Pages/StartupManagerViewModel.csindex 23cd952..71a68f1 100644--- a/optimizerDuck/UI/ViewModels/Pages/StartupManagerViewModel.cs+++ b/optimizerDuck/UI/ViewModels/Pages/StartupManagerViewModel.cs@@ -5,6 +5,7 @@ using CommunityToolkit.Mvvm.ComponentModel;using CommunityToolkit.Mvvm.Input;using Microsoft.Extensions.Logging;using optimizerDuck.Resources.Languages;+using optimizerDuck.Services.System;using optimizerDuck.Services.UI;using optimizerDuck.UI.Dialogs;using Wpf.Ui;@@ -67,6 +68,19 @@ public partial class StartupManagerViewModel : ViewModelpublic bool HasResults => Apps.Count > 0 || Tasks.Count > 0;public bool ShowRefreshButton => IsNotLoading && HasResults;+ public override async Task OnNavigatedToAsync()+ {+ await base.OnNavigatedToAsync();++ if (+ CrossPageEventBus.HasPendingRefresh<ScheduledTasksChanged>()+ || CrossPageEventBus.HasPendingRefresh<BloatwareChanged>()+ )+ {+ await ReloadTasksAsync();+ }+ }+protected override async Task InitializeOnceAsync(){await LoadDataAsync();@@ -303,6 +317,7 @@ public partial class StartupManagerViewModel : ViewModeltry{await _startupManagerService.ToggleStartupTask(task, task.IsEnabled);+ CrossPageEventBus.NotifyDataChanged<StartupAppsChanged>();}catch (Exception ex){@@ -310,4 +325,22 @@ public partial class StartupManagerViewModel : ViewModel}}}++ private async Task ReloadTasksAsync()+ {+ try+ {+ foreach (var task in Tasks)+ task.PropertyChanged -= Task_PropertyChanged;++ var tasks = await _startupManagerService.GetStartupTasksAsync();+ _allTasks.Clear();+ _allTasks.AddRange(tasks);+ ApplyTaskFilter();+ }+ catch (Exception ex)+ {+ _logger.LogError(ex, "Failed to reload startup tasks");+ }+ }}diff --git a/optimizerDuck/UI/ViewModels/ViewModel.cs b/optimizerDuck/UI/ViewModels/ViewModel.csindex f4a4893..80591df 100644--- a/optimizerDuck/UI/ViewModels/ViewModel.cs+++ b/optimizerDuck/UI/ViewModels/ViewModel.cs@@ -4,33 +4,77 @@ using Wpf.Ui.Abstractions.Controls;namespace optimizerDuck.UI.ViewModels;/// <summary>-/// Provides a base class for view models that supports navigation event handling and validation.+/// Provides a base class for view models that support navigation and validation./// </summary>/// <remarks>-/// Inherit from this class to implement view models that participate in navigation events within an-/// application. The ViewModel class implements the INavigationAware interface and provides virtual methods for-/// responding to navigation events, allowing derived classes to override and customize navigation behavior as needed.-/// It also inherits from ObservableValidator to support property validation and change notification.+/// <see cref="ViewModel"/> implements <see cref="INavigationAware"/> to participate in+/// navigation events. It also inherits from <see cref="ObservableValidator"/> for property+/// change notification and validation support.+/// <para>+/// Override <see cref="InitializeOnceAsync"/> to run one-time setup logic.+/// Override <see cref="OnNavigatedToAsync"/> and <see cref="OnNavigatedFromAsync"/>+/// to react to page transitions.+/// </para>/// </remarks>public abstract class ViewModel : ObservableValidator, INavigationAware{private bool _isInitialized;+ /// <summary>+ /// Gets a value that indicates whether the one-time initialization has completed.+ /// </summary>+ /// <value>+ /// <see langword="true"/> if <see cref="InitializeOnceAsync"/> has finished;+ /// otherwise <see langword="false"/>.+ /// </value>protected bool IsInitialized => _isInitialized;+ /// <summary>+ /// Runs one-time initialization logic the first time the page is navigated to.+ /// </summary>+ /// <returns>A task that represents the asynchronous operation.</returns>+ /// <remarks>+ /// Override this method to load data or subscribe to events. It runs only once+ /// per view model lifetime, even if the user navigates away and back.+ /// </remarks>protected virtual Task InitializeOnceAsync() => Task.CompletedTask;+ /// <summary>+ /// Called when the page becomes the active view.+ /// </summary>+ /// <returns>A task that represents the asynchronous operation.</returns>+ /// <remarks>+ /// Ensures <see cref="InitializeOnceAsync"/> runs exactly once, then calls+ /// <see cref="OnNavigatedTo()"/>. If initialization fails, the flag resets+ /// so the next navigation can retry.+ /// </remarks>public virtual async Task OnNavigatedToAsync(){if (!_isInitialized){- await InitializeOnceAsync();_isInitialized = true;+ try+ {+ await InitializeOnceAsync();+ }+ catch+ {+ // Reset flag so a future navigation can retry initialization+ _isInitialized = false;+ throw;+ }}OnNavigatedTo();}+ /// <summary>+ /// Called when the page is no longer the active view.+ /// </summary>+ /// <returns>A task that represents the asynchronous operation.</returns>+ /// <remarks>+ /// Override this method to clean up resources or stop timers when leaving the page.+ /// </remarks>public virtual Task OnNavigatedFromAsync(){OnNavigatedFrom();@@ -38,7 +82,20 @@ public abstract class ViewModel : ObservableValidator, INavigationAwarereturn Task.CompletedTask;}+ /// <summary>+ /// Called after the page becomes the active view.+ /// </summary>+ /// <remarks>+ /// Override this method for synchronous logic that runs after every navigation,+ /// not just the first one.+ /// </remarks>public virtual void OnNavigatedTo() { }+ /// <summary>+ /// Called when the page is no longer the active view.+ /// </summary>+ /// <remarks>+ /// Override this method for synchronous cleanup logic that runs on every navigation away.+ /// </remarks>public virtual void OnNavigatedFrom() { }}diff --git a/optimizerDuck/UI/Windows/MainWindow.xaml.cs b/optimizerDuck/UI/Windows/MainWindow.xaml.csindex 4b6491c..99c566f 100644--- a/optimizerDuck/UI/Windows/MainWindow.xaml.cs+++ b/optimizerDuck/UI/Windows/MainWindow.xaml.cs@@ -56,32 +56,41 @@ public partial class MainWindow : IWindowprivate async void OnRootNavigationLoaded(object sender, RoutedEventArgs e){- RootNavigation.Loaded -= OnRootNavigationLoaded;-- if (!_appOptionsMonitor.CurrentValue.App.LegalAccepted)+ try{- var legalDialog = new LegalDialog();- var dialog = new ContentDialog- {- Title = Translations.LegalDialog_Title,- Content = legalDialog,- PrimaryButtonText = Translations.Button_Accept,- CloseButtonText = Translations.Button_Close,- DefaultButton = ContentDialogButton.Primary,- };+ RootNavigation.Loaded -= OnRootNavigationLoaded;- var result = await _contentDialogService.ShowAsync(dialog, CancellationToken.None);- if (result == ContentDialogResult.Primary)+ if (!_appOptionsMonitor.CurrentValue.App.LegalAccepted){- await _configManager.SetAsync(x => x.App.LegalAccepted, true);- }- else- {- Close();- return;+ var legalDialog = new LegalDialog();+ var dialog = new ContentDialog+ {+ Title = Translations.LegalDialog_Title,+ Content = legalDialog,+ PrimaryButtonText = Translations.Button_Accept,+ CloseButtonText = Translations.Button_Close,+ DefaultButton = ContentDialogButton.Primary,+ };++ var result = await _contentDialogService.ShowAsync(dialog, CancellationToken.None);+ if (result == ContentDialogResult.Primary)+ {+ await _configManager.SetAsync(x => x.App.LegalAccepted, true);+ }+ else+ {+ Close();+ return;+ }}- }- RootNavigation.Navigate(typeof(DashboardPage));+ RootNavigation.Navigate(typeof(DashboardPage));+ }+ catch (Exception ex)+ {+ System.Diagnostics.Debug.WriteLine(+ $"Error during navigation initialization: {ex.Message}"+ );+ }}}