Skip to content

Free, open-source Windows optimization tool for performance, privacy, and simplicity.

refactor(core-optimization): simply code and optimizessssssssssssss

itsfatduck92dd8eade38b
diff --git a/optimizerDuck.Test/Services/Managers/RevertManagerTests.cs b/optimizerDuck.Test/Services/Managers/RevertManagerTests.cs
index b48cfdc..972c4a7 100644
--- a/optimizerDuck.Test/Services/Managers/RevertManagerTests.cs
+++ b/optimizerDuck.Test/Services/Managers/RevertManagerTests.cs
@@ -68,7 +68,7 @@ public class RevertManagerTests
{
await File.WriteAllTextAsync(path, "{ invalid json }");
- var manager = new RevertManager(NullLogger<RevertManager>.Instance);
+ var manager = new RevertManager(NullLogger<RevertManager>.Instance, NullLoggerFactory.Instance);
var op = new MockOptimization(id);
var result = await manager.RevertAsync(op);
@@ -121,7 +121,7 @@ public class RevertManagerTests
var json = JsonConvert.SerializeObject(payload, Formatting.Indented);
await File.WriteAllTextAsync(path, json);
- var manager = new RevertManager(NullLogger<RevertManager>.Instance);
+ var manager = new RevertManager(NullLogger<RevertManager>.Instance, NullLoggerFactory.Instance);
var result = await manager.RevertAsync(new MockOptimization(id));
Assert.False(result.Success);
diff --git a/optimizerDuck.Test/Services/OptimizationServiceTests.cs b/optimizerDuck.Test/Services/OptimizationServiceTests.cs
index 9363f57..160e3d8 100644
--- a/optimizerDuck.Test/Services/OptimizationServiceTests.cs
+++ b/optimizerDuck.Test/Services/OptimizationServiceTests.cs
@@ -153,7 +153,7 @@ public class OptimizationServiceTests
private static OptimizationService CreateService()
{
- var revertManager = new RevertManager(NullLogger<RevertManager>.Instance);
+ var revertManager = new RevertManager(NullLogger<RevertManager>.Instance, NullLoggerFactory.Instance);
var loggerFactory = NullLoggerFactory.Instance;
var systemInfoService = new SystemInfoService(NullLogger<SystemInfoService>.Instance);
var streamService = new StreamService(NullLogger<StreamService>.Instance);
diff --git a/optimizerDuck.slnx b/optimizerDuck.slnx
index 379ec99..a990a7c 100644
--- a/optimizerDuck.slnx
+++ b/optimizerDuck.slnx
@@ -1,4 +1,4 @@
<Solution>
- <Project Path="optimizerDuck.Test/optimizerDuck.Test.csproj"/>
- <Project Path="optimizerDuck/optimizerDuck.csproj"/>
+ <Project Path="optimizerDuck.Test/optimizerDuck.Test.csproj" />
+ <Project Path="optimizerDuck/optimizerDuck.csproj" />
</Solution>
diff --git a/optimizerDuck/Core/Interfaces/IRevertStep.cs b/optimizerDuck/Core/Interfaces/IRevertStep.cs
index 8c227c3..76d4631 100644
--- a/optimizerDuck/Core/Interfaces/IRevertStep.cs
+++ b/optimizerDuck/Core/Interfaces/IRevertStep.cs
@@ -11,7 +11,7 @@ public interface IRevertStep
/// The type identifier for this revert step (e.g., "Registry", "Service", "Shell").
/// </summary>
public string Type { get; }
-
+
/// <summary>
/// A localized description of what this revert step does.
/// </summary>
diff --git a/optimizerDuck/Core/Models/Config/AppSettings.cs b/optimizerDuck/Core/Models/Config/AppSettings.cs
index a720467..f5c429d 100644
--- a/optimizerDuck/Core/Models/Config/AppSettings.cs
+++ b/optimizerDuck/Core/Models/Config/AppSettings.cs
@@ -45,6 +45,11 @@ public sealed class AppSettings
/// Timeout in milliseconds for shell command execution.
/// </summary>
public int ShellTimeoutMs { get; set; } = 120000;
+
+ /// <summary>
+ /// Whether to show the success snackbar after applying an optimization.
+ /// </summary>
+ public bool ShowSnackbarNotificationAfterAppliedSuccessfully { get; set; } = true;
}
/// <summary>
diff --git a/optimizerDuck/Core/Models/Execution/ExecutionScope.cs b/optimizerDuck/Core/Models/Execution/ExecutionScope.cs
index 0a52288..804b465 100644
--- a/optimizerDuck/Core/Models/Execution/ExecutionScope.cs
+++ b/optimizerDuck/Core/Models/Execution/ExecutionScope.cs
@@ -180,7 +180,6 @@ public sealed class ExecutionScope : IDisposable
}).ToList();
var allFailed = failedSteps.Count == ExecutedSteps.Count;
- var hasFailures = failedSteps.Count > 0;
return new OptimizationResult
{
@@ -286,7 +285,7 @@ public sealed class ExecutionScope : IDisposable
}
/// <summary>
-/// Represents a step that was executed during an optimization.
+/// Represents a single step recorded during optimization execution.
/// </summary>
public sealed record ExecutedStep
{
diff --git a/optimizerDuck/Core/Models/Revert/Steps/ServiceRevertStep.cs b/optimizerDuck/Core/Models/Revert/Steps/ServiceRevertStep.cs
index 3e987d2..aa5f24e 100644
--- a/optimizerDuck/Core/Models/Revert/Steps/ServiceRevertStep.cs
+++ b/optimizerDuck/Core/Models/Revert/Steps/ServiceRevertStep.cs
@@ -29,7 +29,6 @@ public class ServiceRevertStep : IRevertStep
Translations.Revert_Service_Description_Restore,
ServiceName, OriginalStartupType);
-
/// <inheritdoc />
public async Task<bool> ExecuteAsync()
{
diff --git a/optimizerDuck/Core/Optimizers/BaseOptimization.cs b/optimizerDuck/Core/Optimizers/BaseOptimization.cs
index 1161a51..53ecee6 100644
--- a/optimizerDuck/Core/Optimizers/BaseOptimization.cs
+++ b/optimizerDuck/Core/Optimizers/BaseOptimization.cs
@@ -1,6 +1,7 @@
using System.Reflection;
using optimizerDuck.Core.Interfaces;
using optimizerDuck.Core.Models.Attributes;
+using optimizerDuck.Core.Models.Execution;
using optimizerDuck.Core.Models.Optimization;
using optimizerDuck.Core.Models.UI;
using optimizerDuck.Resources.Languages;
diff --git a/optimizerDuck/Resources/Languages/Translations.Designer.cs b/optimizerDuck/Resources/Languages/Translations.Designer.cs
index 6e45963..8e3d52a 100644
--- a/optimizerDuck/Resources/Languages/Translations.Designer.cs
+++ b/optimizerDuck/Resources/Languages/Translations.Designer.cs
@@ -3124,6 +3124,24 @@ namespace optimizerDuck.Resources.Languages {
}
}
+ /// <summary>
+ /// Looks up a localized string similar to Delete registry value: {0}\{1}.
+ /// </summary>
+ internal static string Service_Registry_Description_Delete {
+ get {
+ return ResourceManager.GetString("Service.Registry.Description.Delete", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to Write registry value: {0}\{1}.
+ /// </summary>
+ internal static string Service_Registry_Description_Write {
+ get {
+ return ResourceManager.GetString("Service.Registry.Description.Write", resourceCulture);
+ }
+ }
+
/// <summary>
/// Looks up a localized string similar to Access denied (protected hive).
/// </summary>
@@ -3160,6 +3178,24 @@ namespace optimizerDuck.Resources.Languages {
}
}
+ /// <summary>
+ /// Looks up a localized string similar to Disable scheduled task: {0}.
+ /// </summary>
+ internal static string Service_ScheduledTask_Description_Disable {
+ get {
+ return ResourceManager.GetString("Service.ScheduledTask.Description.Disable", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to Enable scheduled task: {0}.
+ /// </summary>
+ internal static string Service_ScheduledTask_Description_Enable {
+ get {
+ return ResourceManager.GetString("Service.ScheduledTask.Description.Enable", resourceCulture);
+ }
+ }
+
/// <summary>
/// Looks up a localized string similar to Scheduled Task.
/// </summary>
@@ -3169,6 +3205,15 @@ namespace optimizerDuck.Resources.Languages {
}
}
+ /// <summary>
+ /// Looks up a localized string similar to Change service &apos;{0}&apos; to {1} startup.
+ /// </summary>
+ internal static string Service_Service_Description_Change {
+ get {
+ return ResourceManager.GetString("Service.Service.Description.Change", resourceCulture);
+ }
+ }
+
/// <summary>
/// Looks up a localized string similar to ChangeStartMode failed (code: {0}).
/// </summary>
diff --git a/optimizerDuck/Resources/Languages/Translations.resx b/optimizerDuck/Resources/Languages/Translations.resx
index db4c6cd..162d784 100644
--- a/optimizerDuck/Resources/Languages/Translations.resx
+++ b/optimizerDuck/Resources/Languages/Translations.resx
@@ -1,4 +1,4 @@
-<?xml version="1.0" encoding="utf-8"?>
+<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
@@ -1369,6 +1369,21 @@ Update now to enjoy the latest features, improvements, and bug fixes.</value>
<data name="Service.Shell.Name" xml:space="preserve">
<value>Shell</value>
</data>
+ <data name="Service.Registry.Description.Write" xml:space="preserve">
+ <value>Write registry value: {0}\{1}</value>
+ </data>
+ <data name="Service.Registry.Description.Delete" xml:space="preserve">
+ <value>Delete registry value: {0}\{1}</value>
+ </data>
+ <data name="Service.Service.Description.Change" xml:space="preserve">
+ <value>Change service '{0}' to {1} startup</value>
+ </data>
+ <data name="Service.ScheduledTask.Description.Enable" xml:space="preserve">
+ <value>Enable scheduled task: {0}</value>
+ </data>
+ <data name="Service.ScheduledTask.Description.Disable" xml:space="preserve">
+ <value>Disable scheduled task: {0}</value>
+ </data>
<data name="Revert.Registry.Description.Restore" xml:space="preserve">
<value>Restore registry value: {0}\{1}</value>
</data>
diff --git a/optimizerDuck/Resources/Languages/Translations.vi-VN.resx b/optimizerDuck/Resources/Languages/Translations.vi-VN.resx
index 85c7e2e..f15fabb 100644
--- a/optimizerDuck/Resources/Languages/Translations.vi-VN.resx
+++ b/optimizerDuck/Resources/Languages/Translations.vi-VN.resx
@@ -1352,6 +1352,21 @@ Cập nhật ngay để trải nghiệm các tính năng mới, cải tiến và
<data name="Service.Shell.Name" xml:space="preserve">
<value>Lệnh hệ thống</value>
</data>
+ <data name="Service.Registry.Description.Write" xml:space="preserve">
+ <value>Ghi giá trị registry: {0}\{1}</value>
+ </data>
+ <data name="Service.Registry.Description.Delete" xml:space="preserve">
+ <value>Xóa giá trị registry: {0}\{1}</value>
+ </data>
+ <data name="Service.Service.Description.Change" xml:space="preserve">
+ <value>Thay đổi dịch vụ '{0}' sang kiểu khởi động {1}</value>
+ </data>
+ <data name="Service.ScheduledTask.Description.Enable" xml:space="preserve">
+ <value>Bật tác vụ hệ thống: {0}</value>
+ </data>
+ <data name="Service.ScheduledTask.Description.Disable" xml:space="preserve">
+ <value>Tắt tác vụ hệ thống: {0}</value>
+ </data>
<data name="Revert.Registry.Description.Restore" xml:space="preserve">
<value>Khôi phục giá trị registry: {0}\{1}</value>
</data>
diff --git a/optimizerDuck/Services/Managers/RevertManager.cs b/optimizerDuck/Services/Managers/RevertManager.cs
index 7201fb4..6f51b50 100644
--- a/optimizerDuck/Services/Managers/RevertManager.cs
+++ b/optimizerDuck/Services/Managers/RevertManager.cs
@@ -14,26 +14,15 @@ using optimizerDuck.Resources.Languages;
namespace optimizerDuck.Services.Managers;
-public class RevertManager(ILogger<RevertManager> logger)
+public class RevertManager(ILogger<RevertManager> logger, ILoggerFactory loggerFactory)
{
private static readonly Dictionary<string, Func<JObject, IRevertStep>> _stepRegistry = BuildStepRegistry();
- private static readonly ConcurrentDictionary<Guid, object> _fileLocks = new();
+ private static readonly ConcurrentDictionary<Guid, SemaphoreSlim> _fileLocks = new();
- public static IReadOnlyCollection<string> RegisteredStepTypes => _stepRegistry.Keys.ToList().AsReadOnly();
-
- public async Task SaveRevertDataAsync(ExecutionScope executionScope)
+ public async Task SaveRevertDataAsync(ExecutionScope scope)
{
- var successfulSteps = executionScope.SuccessfulSteps
+ var steps = scope.SuccessfulSteps
.Where(s => s.RevertStep != null)
- .ToList();
-
- if (successfulSteps.Count == 0)
- {
- logger.LogWarning("No revert steps to save for {Key}", executionScope.OptimizationKey);
- return;
- }
-
- var steps = successfulSteps
.Select(s => new RevertStepData
{
Type = s.RevertStep!.Type,
@@ -41,468 +30,193 @@ public class RevertManager(ILogger<RevertManager> logger)
})
.ToList();
- var filePath = Path.Combine(Shared.RevertDirectory, executionScope.OptimizationId + ".json");
- var tempPath = filePath + ".tmp";
-
- try
+ if (steps.Count == 0)
{
- var payload = new RevertData
- {
- OptimizationId = executionScope.OptimizationId,
- OptimizationName = executionScope.OptimizationKey,
- AppliedAt = DateTime.Now,
- Steps = steps
- };
-
- Directory.CreateDirectory(Shared.RevertDirectory);
- var json = JsonConvert.SerializeObject(payload, Formatting.Indented);
- await File.WriteAllTextAsync(tempPath, json);
- File.Move(tempPath, filePath, true);
- logger.LogInformation("Saved {Count} revert steps for {Name} to {File}",
- steps.Count, executionScope.OptimizationKey, filePath);
+ logger.LogWarning("No revert steps to save for {Key}", scope.OptimizationKey);
+ return;
}
- catch (Exception ex)
+
+ var filePath = GetFilePath(scope.OptimizationId);
+ var payload = new RevertData
{
- try
- {
- if (File.Exists(tempPath))
- File.Delete(tempPath);
- }
- catch (Exception deleteEx)
- {
- logger.LogWarning(deleteEx, "Failed to delete temp file {File} after save failure", tempPath);
- }
+ OptimizationId = scope.OptimizationId,
+ OptimizationName = scope.OptimizationKey,
+ AppliedAt = DateTime.Now,
+ Steps = steps
+ };
- logger.LogError(ex, "Failed to save revert data for {Name}", executionScope.OptimizationKey);
- throw;
- }
+ await WriteJsonAsync(filePath, payload);
+ logger.LogInformation("Saved {Count} revert steps for {Name}", steps.Count, scope.OptimizationKey);
}
- public async Task<RevertResult> RevertAsync(IOptimization optimization,
- IProgress<ProcessingProgress>? progress = null)
+ public async Task<RevertResult> RevertAsync(IOptimization opt, IProgress<ProcessingProgress>? progress = null)
{
- using var scope = ExecutionScope.BeginForLogging(optimization.Id, optimization.OptimizationKey, logger);
+ var l = loggerFactory.CreateLogger<RevertManager>();
+ using var scope = ExecutionScope.BeginForLogging(opt.Id, opt.OptimizationKey, l);
- try
- {
- var validation = await ValidateAsync(optimization.Id);
- if (!validation.IsValid)
- {
- logger.LogWarning("Invalid revert data for {Key}: {Message}", optimization.OptimizationKey,
- validation.Message);
- return new RevertResult
- {
- Success = false,
- Message = string.Format(Translations.Revert_Error_InvalidData, optimization.Name,
- validation.LocalizedMessage)
- };
- }
+ var steps = await LoadStepsAsync(opt.Id);
+ if (steps.Count == 0)
+ return new RevertResult { Success = false, Message = string.Format(Translations.Revert_Error_NoDataFound, opt.Name) };
- var steps = await LoadStepsAsync(optimization.Id);
- if (steps.Count == 0)
- {
- logger.LogWarning("No revert steps found for {Key}", optimization.OptimizationKey);
- return new RevertResult
- {
- Success = false,
- Message = string.Format(Translations.Revert_Error_NoDataFound, optimization.Name)
- };
- }
+ logger.LogInformation("Reverting {Key} ({Count} steps)", opt.OptimizationKey, steps.Count);
- logger.LogInformation("Reverting {Key} ({StepCount} steps)",
- optimization.OptimizationKey, steps.Count);
+ var failed = new List<OperationStepResult>();
+ var total = steps.Count;
- var failedStepDetails = new List<OperationStepResult>();
- var totalSteps = steps.Count;
-
- // Revert steps in reverse order (LIFO) for correct undo semantics
- for (var i = steps.Count - 1; i >= 0; i--)
+ for (var i = steps.Count - 1; i >= 0; i--)
+ {
+ var (idx, step) = steps[i];
+ progress?.Report(new ProcessingProgress
{
- var (currentIndex, step) = steps[i];
-
- progress?.Report(new ProcessingProgress
- {
- Message = string.Format(Translations.Optimization_Revert_ExecutingStep, currentIndex, totalSteps,
- step.Type),
- IsIndeterminate = false,
- Value = currentIndex,
- Total = totalSteps
- });
+ Message = string.Format(Translations.Optimization_Revert_ExecutingStep, idx, total, step.Type),
+ IsIndeterminate = false,
+ Value = idx,
+ Total = total
+ });
- var success = false;
- Exception? lastError = null;
+ var success = false;
+ Exception? error = null;
- try
- {
- success = await step.ExecuteAsync();
- }
- catch (Exception ex)
- {
- lastError = ex;
- }
+ try { success = await step.ExecuteAsync(); }
+ catch (Exception ex) { error = ex; }
- if (!success)
+ if (!success)
+ {
+ var msg = error?.Message ?? Translations.Revert_Error_StepFailed;
+ logger.LogError(error, "Revert step {Idx} ({Type}) failed", idx, step.Type);
+ failed.Add(new OperationStepResult
{
- var errorMessage = lastError?.Message ?? Translations.Revert_Error_StepFailed;
- logger.LogError(lastError, "Revert step {Index} ({Type}) failed: {Message}",
- currentIndex, step.Type, errorMessage);
-
- failedStepDetails.Add(new OperationStepResult
- {
- Index = currentIndex,
- Name = step.Type,
- Description = step.Description,
- Success = false,
- Error = errorMessage,
- RetryAction = async () => await step.ExecuteAsync()
- });
- }
+ Index = idx,
+ Name = step.Type,
+ Description = step.Description,
+ Success = false,
+ Error = msg,
+ RetryAction = () => step.ExecuteAsync()
+ });
}
+ }
- var failedCount = failedStepDetails.Count;
- var allFailed = failedCount == totalSteps;
- var hasFailures = failedCount > 0;
-
- // if some steps failed but not all, log a warning
- if (hasFailures && !allFailed)
- logger.LogWarning(
- "Partial revert for {Key}: {FailedCount}/{TotalCount} steps failed. " +
- "Revert data file will be removed; remaining retries operate in-memory.",
- optimization.OptimizationKey, failedCount, totalSteps);
+ var failedCount = failed.Count;
+ var allFailed = failedCount == total;
- // keep revert data if its all failed
- if (!allFailed) Remove(optimization.Id, optimization.Name);
+ if (!allFailed) Remove(opt.Id);
- return new RevertResult
- {
- Success = !hasFailures,
- IsCompleteFailure = allFailed,
- Message = allFailed
- ? string.Format(Translations.Optimization_Revert_Error_Failed, optimization.Name)
- : hasFailures
- ? string.Format(Translations.Optimization_Revert_Error_FailedWithSteps, optimization.Name,
- failedCount)
- : string.Format(Translations.Optimization_Revert_Success, optimization.Name),
- FailedStepDetails = failedStepDetails
- };
- }
- catch (Exception ex)
+ return new RevertResult
{
- logger.LogError(ex, "Failed to revert {Key}", optimization.OptimizationKey);
- return new RevertResult
- {
- Success = false,
- IsCompleteFailure = true,
- Message = string.Format(Translations.Revert_Error_RevertFailed, optimization.Name, ex.Message),
- Exception = ex
- };
- }
+ Success = failedCount == 0,
+ IsCompleteFailure = allFailed,
+ Message = allFailed
+ ? string.Format(Translations.Optimization_Revert_Error_Failed, opt.Name)
+ : failedCount > 0
+ ? string.Format(Translations.Optimization_Revert_Error_FailedWithSteps, opt.Name, failedCount)
+ : string.Format(Translations.Optimization_Revert_Success, opt.Name),
+ FailedStepDetails = failed
+ };
}
- public Task AppendOrUpdateRevertStepAsync(Guid optimizationId, string optimizationName, int stepIndex,
- IRevertStep newStep)
+ public async Task AppendOrUpdateRevertStepAsync(Guid id, string name, int idx, IRevertStep step)
{
- var filePath = Path.Combine(Shared.RevertDirectory, optimizationId + ".json");
- var tempPath = filePath + ".tmp";
+ var filePath = GetFilePath(id);
+ var lockObj = _fileLocks.GetOrAdd(id, _ => new SemaphoreSlim(1, 1));
- // Use a per-file lock keyed by optimizationId to ensure thread-safe file access
- var fileLockObj = _fileLocks.GetOrAdd(optimizationId, _ => new object());
- lock (fileLockObj)
+ await lockObj.WaitAsync();
+ try
{
- try
- {
- var content = File.Exists(filePath) ? File.ReadAllText(filePath) : string.Empty;
- var revertData = string.IsNullOrWhiteSpace(content)
- ? new RevertData
- {
- OptimizationId = optimizationId,
- OptimizationName = optimizationName,
- AppliedAt = DateTime.Now,
- Steps = []
- }
- : JsonConvert.DeserializeObject<RevertData>(content);
-
- if (revertData == null)
- return Task.CompletedTask;
-
- // Adjust the steps list to match exactly the 1-based index length
- while (revertData.Steps.Count < stepIndex)
- revertData.Steps.Add(new RevertStepData { Type = "Unknown", Data = new JObject() });
-
- // Replace at exact 0-based index
- revertData.Steps[stepIndex - 1] = new RevertStepData
- {
- Type = newStep.Type,
- Data = newStep.ToData()
- };
-
- Directory.CreateDirectory(Shared.RevertDirectory);
- var json = JsonConvert.SerializeObject(revertData, Formatting.Indented);
- File.WriteAllText(tempPath, json);
- File.Move(tempPath, filePath, true);
+ var data = await LoadAsync(filePath) ?? new RevertData { OptimizationId = id, OptimizationName = name, Steps = [] };
- logger.LogInformation("Successfully inserted retried revert step at index {Index} for {Name}",
- stepIndex, optimizationName);
- }
- catch (Exception ex)
- {
- try
- {
- if (File.Exists(tempPath))
- File.Delete(tempPath);
- }
- catch (Exception deleteEx)
- {
- logger.LogWarning(deleteEx, "Failed to delete temp file {File} after save failure", tempPath);
- }
+ while (data.Steps.Count < idx)
+ data.Steps.Add(new RevertStepData { Type = "Unknown", Data = new JObject() });
- logger.LogError(ex, "Failed to append/update revert step {Index} for {Name}", stepIndex,
- optimizationName);
- }
+ data.Steps[idx - 1] = new RevertStepData { Type = step.Type, Data = step.ToData() };
+ await WriteJsonAsync(filePath, data);
}
-
- return Task.CompletedTask;
+ finally { lockObj.Release(); }
}
- private async Task<List<RevertStepEntry>> LoadStepsAsync(Guid optimizationId)
- {
- var filePath = Path.Combine(Shared.RevertDirectory, optimizationId + ".json");
- if (!File.Exists(filePath))
- return [];
-
- try
- {
- var content = await File.ReadAllTextAsync(filePath);
- if (string.IsNullOrWhiteSpace(content))
- return [];
+ public static Task<bool> IsAppliedAsync(Guid id) => Task.FromResult(File.Exists(GetFilePath(id)));
- var revertData = JsonConvert.DeserializeObject<RevertData>(content);
- if (revertData == null || revertData.Steps.Count == 0)
- return [];
-
- var stepsList = new List<RevertStepEntry>();
- var index = 0;
- foreach (var stepData in revertData.Steps)
- {
- var step = DeserializeStep(stepData.Type, stepData.Data);
- if (step == null)
- {
- logger.LogWarning("Skipping unknown revert step type '{Type}' at index {Index}",
- stepData.Type, index);
- continue;
- }
+ public static async Task<RevertData?> GetRevertDataAsync(Guid id) => await LoadAsync(GetFilePath(id));
- index++;
- stepsList.Add(new RevertStepEntry(index, step));
- }
-
- return stepsList;
- }
- catch (Exception ex)
- {
- logger.LogError(ex, "Failed to load revert steps for {Id}", optimizationId);
- return [];
- }
- }
-
- public static Task<bool> IsAppliedAsync(Guid optimizationId)
+ public static void ClearAllRevertData(ILogger l)
{
- var filePath = Path.Combine(Shared.RevertDirectory, optimizationId + ".json");
- return Task.FromResult(File.Exists(filePath));
+ if (!Directory.Exists(Shared.RevertDirectory)) return;
+ foreach (var f in Directory.GetFiles(Shared.RevertDirectory))
+ try { File.Delete(f); }
+ catch (Exception ex) { l.LogError(ex, "Failed to delete {File}", f); }
}
- public static async Task<RevertData?> GetRevertDataAsync(Guid optimizationId)
- {
- var filePath = Path.Combine(Shared.RevertDirectory, optimizationId + ".json");
- if (!File.Exists(filePath))
- return null;
+ #region Helpers
- try
- {
- var content = await File.ReadAllTextAsync(filePath);
- if (string.IsNullOrWhiteSpace(content))
- return null;
+ private static string GetFilePath(Guid id) => Path.Combine(Shared.RevertDirectory, $"{id}.json");
- return JsonConvert.DeserializeObject<RevertData>(content);
- }
- catch
- {
- return null;
- }
+ private static async Task<RevertData?> LoadAsync(string path)
+ {
+ if (!File.Exists(path)) return null;
+ var content = await File.ReadAllTextAsync(path);
+ return string.IsNullOrWhiteSpace(content) ? null : JsonConvert.DeserializeObject<RevertData>(content);
}
- private void Remove(Guid optimizationId, string optimizationName)
+ private static async Task WriteJsonAsync(string path, RevertData data)
{
- try
- {
- var filePath = Path.Combine(Shared.RevertDirectory, optimizationId + ".json");
- if (File.Exists(filePath))
- {
- File.Delete(filePath);
- logger.LogInformation("Removed revert data for {Name} ({File})", optimizationName, filePath);
- }
- }
- catch (Exception ex)
- {
- logger.LogError(ex, "Failed to remove revert data for {Id}", optimizationId);
- }
+ Directory.CreateDirectory(Path.GetDirectoryName(path)!);
+ var json = JsonConvert.SerializeObject(data, Formatting.Indented);
+ await File.WriteAllTextAsync(path + ".tmp", json);
+ File.Move(path + ".tmp", path, true);
}
- private static Dictionary<string, Func<JObject, IRevertStep>> BuildStepRegistry()
+ private async Task<List<(int Index, IRevertStep Step)>> LoadStepsAsync(Guid id)
{
- var registry = new Dictionary<string, Func<JObject, IRevertStep>>(StringComparer.OrdinalIgnoreCase);
+ var data = await LoadAsync(GetFilePath(id));
+ if (data == null || data.Steps.Count == 0) return [];
- try
- {
- var stepTypes = Assembly.GetExecutingAssembly()
- .GetTypes()
- .Where(t => t is { IsAbstract: false, IsInterface: false }
- && typeof(IRevertStep).IsAssignableFrom(t));
-
- foreach (var type in stepTypes)
- try
- {
- var instance = (IRevertStep)Activator.CreateInstance(type)!;
- var typeKey = instance.Type;
-
- var fromDataMethod = type.GetMethod("FromData",
- BindingFlags.Static | BindingFlags.Public,
- null,
- [typeof(JObject)],
- null);
-
- fromDataMethod ??= type.GetMethod("FromData",
- BindingFlags.Static | BindingFlags.Public,
- null,
- [typeof(JToken)],
- null);
-
- if (fromDataMethod != null)
- registry[typeKey] = data =>
- (IRevertStep)fromDataMethod.Invoke(null, [data])!;
- }
- catch
- {
- }
- }
- catch
+ var result = new List<(int, IRevertStep)>();
+ for (var i = 0; i < data.Steps.Count; i++)
{
+ var step = DeserializeStep(data.Steps[i].Type, data.Steps[i].Data);
+ if (step != null) result.Add((i + 1, step));
}
-
- return registry;
+ return result;
}
- private IRevertStep? DeserializeStep(string serviceType, JToken data)
+ private void Remove(Guid id, string? name = null)
{
try
{
- if (data is not JObject obj)
+ var path = GetFilePath(id);
+ if (File.Exists(path))
{
- logger.LogError(
- "Invalid revert step payload for type {Type}. Expected JObject, got {TokenType}",
- serviceType,
- data.Type
- );
- return null;
+ File.Delete(path);
+ logger.LogInformation("Removed revert data for {Name}", name ?? id.ToString());
}
-
- if (_stepRegistry.TryGetValue(serviceType, out var factory))
- return factory(obj);
-
- logger.LogWarning("Unknown revert step type '{Type}'. Registered types: {Types}",
- serviceType, string.Join(", ", _stepRegistry.Keys));
- return null;
- }
- catch (Exception ex)
- {
- logger.LogError(ex, "Failed to deserialize step of type {Type}", serviceType);
- return null;
}
+ catch (Exception ex) { logger.LogError(ex, "Failed to remove revert data for {Id}", id); }
}
- private async Task<RevertValidationResult> ValidateAsync(Guid optimizationId)
+ private static Dictionary<string, Func<JObject, IRevertStep>> BuildStepRegistry()
{
- var filePath = Path.Combine(Shared.RevertDirectory, optimizationId + ".json");
- if (!File.Exists(filePath))
- return RevertValidationResult.Fail(Translations.Revert_Error_FileNotFound,
- "Revert data file not found.");
-
- string content;
- try
- {
- content = await File.ReadAllTextAsync(filePath);
- if (string.IsNullOrWhiteSpace(content))
- return RevertValidationResult.Fail(Translations.Revert_Error_FileEmpty,
- "Revert data file is empty.");
- }
- catch (Exception ex)
- {
- return RevertValidationResult.Fail(string.Format(Translations.Revert_Error_ReadFailed, ex.Message),
- ex.Message);
- }
-
- RevertData? data;
- try
- {
- data = JsonConvert.DeserializeObject<RevertData>(content);
- if (data == null)
- return RevertValidationResult.Fail(Translations.Revert_Error_InvalidJson, "Revert data JSON is null after deserialization.");
- }
- catch (Exception ex)
- {
- return RevertValidationResult.Fail(
- string.Format(Translations.Revert_Error_InvalidJsonFormat, ex.Message), ex.Message);
- }
+ var dict = new Dictionary<string, Func<JObject, IRevertStep>>();
- if (data.OptimizationId != optimizationId)
- return RevertValidationResult.Fail(Translations.Revert_Error_OptimizationIdMismatch,
- $"Optimization ID mismatch: expected {optimizationId}, found {data.OptimizationId}.");
-
- if (data.Steps.Count == 0)
- return RevertValidationResult.Fail(Translations.Revert_Error_NoSteps, "Revert data contains zero steps.");
-
- var invalidSteps = new List<string>();
- foreach (var stepData in data.Steps)
+ foreach (var type in ReflectionHelper.FindImplementationsInLoadedAssemblies<IRevertStep>())
{
- if (string.IsNullOrWhiteSpace(stepData.Type))
- {
- invalidSteps.Add("(empty)");
- continue;
- }
-
- if (!_stepRegistry.ContainsKey(stepData.Type))
+ try
{
- invalidSteps.Add(stepData.Type);
- continue;
+ var instance = (IRevertStep)Activator.CreateInstance(type)!;
+ var key = instance.Type;
+ var method = type.GetMethod("FromData", BindingFlags.Static | BindingFlags.Public);
+ if (method != null)
+ dict[key] = data => (IRevertStep)method.Invoke(null, [data])!;
}
-
- var step = DeserializeStep(stepData.Type, stepData.Data);
- if (step == null)
- invalidSteps.Add(stepData.Type);
+ catch { }
}
- if (invalidSteps.Count > 0)
- return RevertValidationResult.Fail(string.Format(Translations.Revert_Error_InvalidSteps,
- string.Join(", ", invalidSteps)), $"Invalid or unrecognized step types: {string.Join(", ", invalidSteps)}.");
-
- return RevertValidationResult.Success();
+ return dict;
}
- public static void ClearAllRevertData(ILogger logger)
+ private IRevertStep? DeserializeStep(string type, JToken data)
{
- if (!Directory.Exists(Shared.RevertDirectory))
- return;
-
- foreach (var filePath in Directory.GetFiles(Shared.RevertDirectory))
- try
- {
- File.Delete(filePath);
- }
- catch (Exception ex)
- {
- logger.LogError(ex, "Failed to delete revert data file {File}", filePath);
- }
+ if (data is not JObject obj) return null;
+ return _stepRegistry.TryGetValue(type, out var factory) ? factory(obj) : null;
}
- public sealed record RevertStepEntry(int Index, IRevertStep Step);
+ #endregion
}
\ No newline at end of file
diff --git a/optimizerDuck/Services/OptimizationPageRegistryExtensions.cs b/optimizerDuck/Services/OptimizationPageRegistryExtensions.cs
index 314f001..a01270c 100644
--- a/optimizerDuck/Services/OptimizationPageRegistryExtensions.cs
+++ b/optimizerDuck/Services/OptimizationPageRegistryExtensions.cs
@@ -1,9 +1,11 @@
using System.Reflection;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
+using Microsoft.Extensions.Options;
using optimizerDuck.Common.Helpers;
using optimizerDuck.Core.Interfaces;
using optimizerDuck.Core.Models.Attributes;
+using optimizerDuck.Core.Models.Config;
using optimizerDuck.Services.Managers;
using Wpf.Ui;
using OptimizationCategoryViewModel = optimizerDuck.UI.ViewModels.Optimizer.OptimizationCategoryViewModel;
@@ -38,6 +40,7 @@ public static class OptimizationPageRegistryExtensions
var snackbarService = serviceProvider.GetRequiredService<ISnackbarService>();
var contentDialogService = serviceProvider.GetRequiredService<IContentDialogService>();
var logger = serviceProvider.GetRequiredService<ILogger<OptimizationCategoryViewModel>>();
+ var appOptionsMonitor = serviceProvider.GetRequiredService<IOptionsMonitor<AppSettings>>();
var optimizationCategoryType = optimizationRegistry.GetCategory(categoryType);
@@ -47,7 +50,8 @@ public static class OptimizationPageRegistryExtensions
revertManager,
snackbarService,
contentDialogService,
- logger
+ logger,
+ appOptionsMonitor
);
return Activator.CreateInstance(pageType, viewModel)!;
diff --git a/optimizerDuck/Services/OptimizationService.cs b/optimizerDuck/Services/OptimizationService.cs
index 3e36071..fd5d546 100644
--- a/optimizerDuck/Services/OptimizationService.cs
+++ b/optimizerDuck/Services/OptimizationService.cs
@@ -46,11 +46,6 @@ public class OptimizationService(
try
{
- async Task<ShellResult> RunPowerShellAsync(string command)
- {
- return await Task.Run(() => ShellService.PowerShell(command));
- }
-
dialogViewModel.ProgressReporter.Report(new ProcessingProgress
{
Message = Translations.RestorePoint_Progress_Creating,
@@ -59,7 +54,7 @@ public class OptimizationService(
using var scope = ExecutionScope.Begin(_logger);
- var result = await RunPowerShellAsync(
+ var result = await ShellService.PowerShellAsync(
$"Checkpoint-Computer -Description \"{Shared.RestorePointName}\" -RestorePointType MODIFY_SETTINGS");
if (result.Stderr.Contains("already been created within the past 1440 minutes",
@@ -72,356 +67,162 @@ public class OptimizationService(
if (result.ExitCode == 0)
return RestorePointResult.Success;
- if (!Regex.IsMatch(result.Stderr,
- @"\b(is\s+disabled|system\s+restore\s+is\s+disabled|disabled\s+by\s+group\s+policy|disableconfig|disablesr|protection\s+is\s+off)\b",
- RegexOptions.IgnoreCase | RegexOptions.CultureInvariant))
+ if (!Regex.IsMatch(result.Stderr, @"\b(is\s+disabled|system\s+restore\s+is\s+disabled|disabled\s+by\s+group\s+policy|disableconfig|disablesr|protection\s+is\s+off)\b",
+ RegexOptions.IgnoreCase | RegexOptions.CultureInvariant))
{
- _logger.LogError("Failed to create restore point (not a 'disabled' case): {Message}", result.Stderr);
+ _logger.LogError("Failed to create restore point: {Message}", result.Stderr);
return RestorePointResult.Failed;
}
- _logger.LogError("Failed to create restore point due to disabled feature: {Message}", result.Stderr);
-
- dialogViewModel.ProgressReporter.Report(new ProcessingProgress
- {
- Message = Translations.RestorePoint_Progress_Enabling,
- IsIndeterminate = true
- });
+ _logger.LogInformation("Enabling System Protection...");
+ dialogViewModel.ProgressReporter.Report(new ProcessingProgress { Message = Translations.RestorePoint_Progress_Enabling, IsIndeterminate = true });
- _logger.LogInformation("Enabling System Protection on system drive...");
- var enableResult = await RunPowerShellAsync("Enable-ComputerRestore -Drive \"$env:SystemDrive\"");
+ var enableResult = await ShellService.PowerShellAsync("Enable-ComputerRestore -Drive \"$env:SystemDrive\"");
if (enableResult.ExitCode != 0)
{
- _logger.LogError("Failed to enable System Protection on system drive: {Message}", enableResult.Stderr);
+ _logger.LogError("Failed to enable System Protection: {Message}", enableResult.Stderr);
return RestorePointResult.Failed;
}
- dialogViewModel.ProgressReporter.Report(new ProcessingProgress
- {
- Message = Translations.RestorePoint_Progress_Retrying,
- IsIndeterminate = true
- });
+ dialogViewModel.ProgressReporter.Report(new ProcessingProgress { Message = Translations.RestorePoint_Progress_Retrying, IsIndeterminate = true });
- _logger.LogInformation("Retrying to create restore point...");
- result = await RunPowerShellAsync(
+ result = await ShellService.PowerShellAsync(
$"Checkpoint-Computer -Description \"{Shared.RestorePointName}\" -RestorePointType MODIFY_SETTINGS");
- if (result.Stderr.Contains("already been created within the past 1440 minutes",
- StringComparison.OrdinalIgnoreCase))
- {
- _logger.LogWarning("Restore point creation skipped: frequency limit reached.");
+ if (result.Stderr.Contains("already been created within the past 1440 minutes", StringComparison.OrdinalIgnoreCase))
return RestorePointResult.FrequencyLimitReached;
- }
- if (result.ExitCode == 0)
- return RestorePointResult.Success;
-
- if (result.Stderr.Contains("is disabled", StringComparison.OrdinalIgnoreCase))
- {
- _logger.LogError("Failed to create restore point after enabling feature: {Message}", result.Stderr);
- return RestorePointResult.Failed;
- }
-
- _logger.LogError("Failed to create restore point: {Message}", result.Stderr);
- return RestorePointResult.Failed;
- }
- finally
- {
- dialog.Hide();
+ return result.ExitCode == 0 ? RestorePointResult.Success : RestorePointResult.Failed;
}
+ finally { dialog.Hide(); }
}
- #region Main Methods
-
- /// <summary>
- /// Apply an optimization.
- /// </summary>
- /// <param name="optimization">The optimization to apply.</param>
- /// <param name="progress">The progress reporter.</param>
- /// <returns>The result of the optimization.</returns>
- public async Task<OptimizationResult> ApplyAsync(IOptimization optimization,
- IProgress<ProcessingProgress> progress)
+ public async Task<OptimizationResult> ApplyAsync(IOptimization optimization, IProgress<ProcessingProgress> progress)
{
- var optimizationLogger = loggerFactory.CreateLogger(optimization.GetType());
- using var executionScope = ExecutionScope.Begin(optimization, optimizationLogger);
+ var optLogger = loggerFactory.CreateLogger(optimization.GetType());
+ using var scope = ExecutionScope.Begin(optimization, optLogger);
- OptimizationResult result;
+ progress.Report(new ProcessingProgress { Message = Translations.Optimization_Apply_Processing, IsIndeterminate = true });
try
{
- progress.Report(new ProcessingProgress
- {
- Message = Translations.Optimization_Apply_Processing,
- IsIndeterminate = true
- });
-
var applyResult = await Task.Run(async () =>
- await optimization.ApplyAsync(progress,
- new OptimizationContext
- {
- Logger = optimizationLogger,
- Snapshot = systemInfoService.Snapshot,
- StreamService = streamService
- }));
+ await optimization.ApplyAsync(progress, new OptimizationContext
+ {
+ Logger = optLogger,
+ Snapshot = systemInfoService.Snapshot,
+ StreamService = streamService
+ }));
if (!string.IsNullOrWhiteSpace(applyResult.Message))
{
- var failedSteps = executionScope.FailedSteps;
-
return new OptimizationResult
{
Status = OptimizationSuccessResult.Failed,
Message = applyResult.Message,
- FailedSteps = failedSteps.Select(step => new OperationStepResult
+ FailedSteps = scope.FailedSteps.Select(s => new OperationStepResult
{
- Index = step.Index,
- Name = step.Name,
- Description = step.Description,
- Success = step.Success,
- Error = step.Error,
- RetryAction = step.RetryAction
+ Index = s.Index, Name = s.Name, Description = s.Description,
+ Success = s.Success, Error = s.Error, RetryAction = s.RetryAction
}).ToList()
};
}
- progress.Report(new ProcessingProgress
- {
- Message = Translations.Optimization_Apply_Completed,
- IsIndeterminate = false,
- Value = 1,
- Total = 1
- });
+ progress.Report(new ProcessingProgress { Message = Translations.Optimization_Apply_Completed, IsIndeterminate = false, Value = 1, Total = 1 });
- result = executionScope.ToResult();
+ var result = scope.ToResult();
+ if (scope.HasSuccessfulSteps)
+ try { await revertManager.SaveRevertDataAsync(scope); }
+ catch (Exception ex) { _logger.LogError(ex, "Failed to save revert data for {Name}", optimization.OptimizationKey); }
- if (executionScope.HasSuccessfulSteps)
- try
- {
- await revertManager.SaveRevertDataAsync(executionScope);
- }
- catch (Exception saveEx)
- {
- _logger.LogError(saveEx, "Failed to save revert data for {Name}, but optimization was applied",
- optimization.OptimizationKey);
- }
+ return result;
}
catch (Exception ex)
{
- var failedStepResults = executionScope.FailedSteps.Select(step => new OperationStepResult
+ var failedSteps = scope.FailedSteps.Select(s => new OperationStepResult
{
- Index = step.Index,
- Name = step.Name,
- Description = step.Description,
- Success = step.Success,
- Error = step.Error,
- RetryAction = step.RetryAction
+ Index = s.Index, Name = s.Name, Description = s.Description,
+ Success = s.Success, Error = s.Error, RetryAction = s.RetryAction
}).ToList();
- var hasAnySuccess = executionScope.HasSuccessfulSteps;
- var status = hasAnySuccess
- ? OptimizationSuccessResult.PartialSuccess
- : OptimizationSuccessResult.Failed;
- result = new OptimizationResult
+ var status = scope.HasSuccessfulSteps ? OptimizationSuccessResult.PartialSuccess : OptimizationSuccessResult.Failed;
+ var result = new OptimizationResult
{
Status = status,
- Message = string.Format(Translations.Optimization_Apply_Error_Failed,
- optimization.Name),
+ Message = string.Format(Translations.Optimization_Apply_Error_Failed, optimization.Name),
Exception = ex,
- FailedSteps = failedStepResults
+ FailedSteps = failedSteps
};
- if (executionScope.HasSuccessfulSteps)
- try
- {
- await revertManager.SaveRevertDataAsync(executionScope);
- _logger.LogWarning("Saved revert data for {Name} despite exception", optimization.OptimizationKey);
- }
- catch (Exception saveEx)
- {
- _logger.LogError(saveEx, "Critical: Failed to save revert data after exception for {Name}",
- optimization.OptimizationKey);
- }
- }
+ if (scope.HasSuccessfulSteps)
+ try { await revertManager.SaveRevertDataAsync(scope); }
+ catch (Exception ex2) { _logger.LogError(ex2, "Failed to save revert data after exception"); }
- return result;
+ return result;
+ }
}
- /// <summary>
- /// Revert an optimization.
- /// </summary>
- /// <param name="optimization">The optimization to revert.</param>
- /// <param name="progress">The progress reporter.</param>
- /// <returns>The result of the revert.</returns>
- public async Task<RevertResult> RevertAsync(IOptimization optimization,
- IProgress<ProcessingProgress>? progress = null)
+ public async Task<RevertResult> RevertAsync(IOptimization optimization, IProgress<ProcessingProgress>? progress = null)
{
- var optimizationLogger = loggerFactory.CreateLogger(optimization.GetType());
-
- progress?.Report(new ProcessingProgress
- {
- Message = Translations.Optimization_Revert_Reverting,
- IsIndeterminate = true
- });
-
- var result = await revertManager.RevertAsync(
- optimization,
- progress);
-
- progress?.Report(new ProcessingProgress
- {
- Message = result.Message,
- IsIndeterminate = false,
- Value = 1,
- Total = 1
- });
-
+ progress?.Report(new ProcessingProgress { Message = Translations.Optimization_Revert_Reverting, IsIndeterminate = true });
+ var result = await revertManager.RevertAsync(optimization, progress);
+ progress?.Report(new ProcessingProgress { Message = result.Message, IsIndeterminate = false, Value = 1, Total = 1 });
return result;
}
- #endregion Main Methods
+ public static Task<bool> IsAppliedAsync(Guid id) => RevertManager.IsAppliedAsync(id);
- #region Helpers
-
- /// <summary>
- /// Check if an optimization is applied.
- /// </summary>
- /// <param name="optimizationId">The ID of the optimization.</param>
- /// <returns>Whether the optimization is applied.</returns>
- public static Task<bool> IsAppliedAsync(Guid optimizationId)
- {
- return RevertManager.IsAppliedAsync(optimizationId);
- }
-
- /// <summary>
- /// Update the state of optimizations.
- /// </summary>
- /// <param name="optimizations">The optimizations to update.</param>
public static async Task UpdateOptimizationStateAsync(params IOptimization[] optimizations)
{
- var tasks = optimizations.Select(async optimization =>
+ await Task.WhenAll(optimizations.Select(async opt =>
{
- var revertData = await RevertManager.GetRevertDataAsync(optimization.Id);
- optimization.State.IsApplied = revertData != null;
- optimization.State.AppliedAt = revertData?.AppliedAt;
- });
-
- await Task.WhenAll(tasks);
+ var data = await RevertManager.GetRevertDataAsync(opt.Id);
+ opt.State.IsApplied = data != null;
+ opt.State.AppliedAt = data?.AppliedAt;
+ }));
}
- public static async Task UpdateOptimizationStateAsync(IEnumerable<IOptimization> optimizations)
- {
- await UpdateOptimizationStateAsync(optimizations.ToArray());
- }
+ public static Task UpdateOptimizationStateAsync(IEnumerable<IOptimization> optimizations) => UpdateOptimizationStateAsync(optimizations.ToArray());
- /// <summary>
- /// Retry failed steps for an optimization.
- /// </summary>
- /// <param name="failedSteps">The failed steps.</param>
- /// <param name="reverseOrder">Whether to reverse the order of the steps.</param>
- /// <param name="logger">The logger.</param>
- /// <param name="progress">The progress reporter.</param>
- /// <returns>The result of the retry.</returns>
public static async Task<List<OperationStepResult>> RetryFailedStepsAsync(
- IReadOnlyList<OperationStepResult> failedSteps,
- bool reverseOrder,
- ILogger logger,
- IProgress<ProcessingProgress>? progress = null)
+ IReadOnlyList<OperationStepResult> failedSteps, bool reverseOrder, ILogger logger, IProgress<ProcessingProgress>? progress = null)
{
- if (failedSteps.Count == 0)
- return [];
+ if (failedSteps.Count == 0) return [];
var stillFailed = new List<OperationStepResult>();
+ var orderedSteps = reverseOrder ? failedSteps.OrderByDescending(s => s.Index) : failedSteps.OrderBy(s => s.Index);
+ var total = failedSteps.Count;
- // Order steps by index, reverse if reverseOrder is true (revert flow)
- var orderedSteps = reverseOrder
- ? failedSteps.OrderByDescending(s => s.Index)
- : failedSteps.OrderBy(s => s.Index);
-
- var totalSteps = failedSteps.Count;
-
- progress?.Report(new ProcessingProgress
- {
- Message = Translations.Optimization_Retry_Processing,
- IsIndeterminate = true,
- Value = 0,
- Total = 0
- });
+ progress?.Report(new ProcessingProgress { Message = Translations.Optimization_Retry_Processing, IsIndeterminate = true });
foreach (var step in orderedSteps)
{
progress?.Report(new ProcessingProgress
{
- Message = string.Format(Translations.Optimization_RetryStep_Processing, step.Name, step.Index,
- totalSteps),
- IsIndeterminate = false,
- Value = step.Index,
- Total = totalSteps
+ Message = string.Format(Translations.Optimization_RetryStep_Processing, step.Name, step.Index, total),
+ IsIndeterminate = false, Value = step.Index, Total = total
});
- if (step.RetryAction == null)
- {
- stillFailed.Add(step);
- continue;
- }
+ if (step.RetryAction == null) { stillFailed.Add(step); continue; }
var success = false;
- Exception? lastEx = null;
-
- try
- {
- success = await step.RetryAction();
- }
- catch (Exception ex)
- {
- logger.LogError(ex, "Retry step {Name} failed", step.Name);
- lastEx = ex;
- }
+ Exception? error = null;
+ try { success = await step.RetryAction(); }
+ catch (Exception ex) { error = ex; logger.LogError(ex, "Retry step {Name} failed", step.Name); }
- if (!success)
- stillFailed.Add(lastEx != null ? step with { Error = lastEx.Message } : step);
+ if (!success) stillFailed.Add(error != null ? step with { Error = error.Message } : step);
}
return stillFailed;
}
- /// <summary>
- /// Clear resources.
- /// </summary>
- /// <param name="logger">The logger.</param>
public static void ClearResources(ILogger logger)
{
- if (!Directory.Exists(Shared.ResourcesDirectory))
- return;
-
- foreach (var filePath in Directory.GetFiles(Shared.ResourcesDirectory))
- try
- {
- File.Delete(filePath);
- }
- catch (Exception ex)
- {
- logger.LogError(ex, "Failed to delete resource file {File}", filePath);
- }
+ if (!Directory.Exists(Shared.ResourcesDirectory)) return;
+ foreach (var f in Directory.GetFiles(Shared.ResourcesDirectory))
+ try { File.Delete(f); }
+ catch (Exception ex) { logger.LogError(ex, "Failed to delete {File}", f); }
}
-
- #endregion Helpers
}
-/// <summary>
-/// The result of a restore point operation.
-/// </summary>
-public enum RestorePointResult
-{
- /// <summary>
- /// The restore point was created successfully.
- /// </summary>
- Success,
- /// <summary>
- /// The restore point creation failed.
- /// </summary>
- Failed,
- /// <summary>
- /// The restore point creation was skipped due to a frequency limit.
- /// </summary>
- FrequencyLimitReached
-}
\ No newline at end of file
+public enum RestorePointResult { Success, Failed, FrequencyLimitReached }
\ No newline at end of file
diff --git a/optimizerDuck/Services/OptimizationServices/RegistryService.cs b/optimizerDuck/Services/OptimizationServices/RegistryService.cs
index 5e41f01..4dde78d 100644
--- a/optimizerDuck/Services/OptimizationServices/RegistryService.cs
+++ b/optimizerDuck/Services/OptimizationServices/RegistryService.cs
@@ -197,7 +197,7 @@ public static class RegistryService
return WithKey(item, key =>
{
- var description = $"{item.Path}:{item.Name}";
+ var description = string.Format(Translations.Service_Registry_Description_Write, item.Path, item.Name);
try
{
object? backupValue = null;
@@ -290,7 +290,7 @@ public static class RegistryService
try
{
- var description = $"{item.Path}:{item.Name}";
+ var description = string.Format(Translations.Service_Registry_Description_Delete, item.Path, item.Name);
if (string.IsNullOrEmpty(subPath))
{
key = rootKey;
diff --git a/optimizerDuck/Services/OptimizationServices/ScheduledTaskService.cs b/optimizerDuck/Services/OptimizationServices/ScheduledTaskService.cs
index 57378d8..d3b6049 100644
--- a/optimizerDuck/Services/OptimizationServices/ScheduledTaskService.cs
+++ b/optimizerDuck/Services/OptimizationServices/ScheduledTaskService.cs
@@ -33,7 +33,7 @@ public static class ScheduledTaskService
/// </summary>
public static bool DisableTask(string fullPath)
{
- var description = $"Disable: {fullPath}";
+ var description = string.Format(Translations.Service_ScheduledTask_Description_Disable, fullPath);
try
{
using var ts = new TaskService();
@@ -95,7 +95,7 @@ public static class ScheduledTaskService
/// </summary>
public static bool EnableTask(string fullPath)
{
- var description = $"Enable: {fullPath}";
+ var description = string.Format(Translations.Service_ScheduledTask_Description_Enable, fullPath);
try
{
using var ts = new TaskService();
diff --git a/optimizerDuck/Services/OptimizationServices/ServiceProcessService.cs b/optimizerDuck/Services/OptimizationServices/ServiceProcessService.cs
index 212e822..6f360d5 100644
--- a/optimizerDuck/Services/OptimizationServices/ServiceProcessService.cs
+++ b/optimizerDuck/Services/OptimizationServices/ServiceProcessService.cs
@@ -46,7 +46,7 @@ public static class ServiceProcessService
public static bool ChangeServiceStartupType(ServiceItem item)
{
- var description = $"{item.Name} -> {item.StartupType}";
+ var description = string.Format(Translations.Service_Service_Description_Change, item.Name, item.StartupType);
try
{
if (!Scope.IsConnected)
diff --git a/optimizerDuck/UI/ViewModels/Optimizer/OptimizationCategoryViewModel.cs b/optimizerDuck/UI/ViewModels/Optimizer/OptimizationCategoryViewModel.cs
index 901d00a..d60fb77 100644
--- a/optimizerDuck/UI/ViewModels/Optimizer/OptimizationCategoryViewModel.cs
+++ b/optimizerDuck/UI/ViewModels/Optimizer/OptimizationCategoryViewModel.cs
@@ -14,6 +14,8 @@ using optimizerDuck.Core.Optimizers;
using optimizerDuck.Resources.Languages;
using optimizerDuck.Services;
using optimizerDuck.Services.Managers;
+using optimizerDuck.Core.Models.Config;
+using Microsoft.Extensions.Options;
using optimizerDuck.UI.ViewModels.Dialogs;
using optimizerDuck.UI.Views.Dialogs;
using Wpf.Ui;
@@ -36,22 +38,28 @@ public partial class OptimizationCategoryViewModel : ViewModel
private readonly RevertManager _revertManager;
private readonly ISnackbarService _snackbarService;
[ObservableProperty] private bool _hideApplied;
- [ObservableProperty] private bool _isProcessing;
+
[ObservableProperty] private ObservableCollection<IOptimization> _optimizations = [];
// Search, Filter, Sort
[ObservableProperty] private string _searchText = string.Empty;
+ private readonly IOptionsMonitor<AppSettings> _appOptionsMonitor;
+
[ObservableProperty] private int _selectedRiskFilterIndex; // 0=All, 1=Safe, 2=Moderate, 3=Risky
[ObservableProperty] private int _selectedSortByIndex; // 0=Risk & Status, 1=Name, 2=Risk
+ [ObservableProperty] [NotifyCanExecuteChangedFor(nameof(ToggleOptimizationCommand))]
+ private bool _isProcessing;
+
public OptimizationCategoryViewModel(
IOptimizationCategory category,
OptimizationService optimizationService,
RevertManager revertManager,
ISnackbarService snackbarService,
IContentDialogService contentDialogService,
- ILogger<OptimizationCategoryViewModel> logger)
+ ILogger<OptimizationCategoryViewModel> logger,
+ IOptionsMonitor<AppSettings> appOptionsMonitor)
{
_category = category;
_optimizationService = optimizationService;
@@ -59,6 +67,7 @@ public partial class OptimizationCategoryViewModel : ViewModel
_snackbarService = snackbarService;
_logger = logger;
_contentDialogService = contentDialogService;
+ _appOptionsMonitor = appOptionsMonitor;
}
public bool HasAppliedOptimizations => _allOptimizations.Any(o => o.State.IsApplied);
@@ -88,6 +97,245 @@ public partial class OptimizationCategoryViewModel : ViewModel
await LoadOptimizationStatesAsync();
}
+ #region Commands
+
+ /// <summary>
+ /// Toggles the optimization.
+ /// </summary>
+ /// <param name="optimization">The optimization to toggle.</param>
+ [RelayCommand(CanExecute = nameof(CanToggleOptimization))]
+ private async Task ToggleOptimizationAsync(IOptimization optimization)
+ {
+ try
+ {
+ // Keep a stable reference to the previous state in case we need to roll back UI changes.
+ var wasApplied = await OptimizationService.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;
+ }
+
+ try
+ {
+ // Apply optimization if not already applied
+ if (!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 Failed, we can't retry it
+ if (applyResult.Status == OptimizationSuccessResult.Failed)
+ {
+ ShowOutcomeSnackbar(false, false, true, "apply",
+ applyResult.Message, restorePointCreated);
+
+ _logger.LogWarning("Apply failed for {Name}: {Message}",
+ optimization.OptimizationKey, applyResult.Message);
+
+ _logger.LogInformation(
+ "===== END applying optimization {OptimizationName} ({OptimizationId}) =====",
+ optimization.OptimizationKey, optimization.Id);
+
+ await OptimizationService.UpdateOptimizationStateAsync(optimization);
+ return;
+ }
+
+ // Retry only if there are some successful steps and some failed steps
+ var retryOutcome = await HandleFailedStepsAsync(
+ optimization,
+ applyResult.FailedSteps,
+ false);
+
+ await OptimizationService.UpdateOptimizationStateAsync(optimization);
+
+ var succeeded = applyResult.Status == OptimizationSuccessResult.Success ||
+ retryOutcome == RetryOutcome.Succeeded;
+ var partial = retryOutcome == RetryOutcome.Skipped;
+ var failed = retryOutcome == RetryOutcome.None &&
+ applyResult.Status != OptimizationSuccessResult.Success;
+
+ ShowOutcomeSnackbar(succeeded, partial, failed, "apply",
+ applyResult.Message, restorePointCreated);
+
+ if (succeeded)
+ _logger.LogInformation("Successfully applied {Name}", optimization.OptimizationKey);
+ else if (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);
+ }
+ 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));
+
+
+ var retryOutcome = await HandleFailedStepsAsync(
+ optimization,
+ revertResult.FailedStepDetails,
+ true);
+
+ await OptimizationService.UpdateOptimizationStateAsync(optimization);
+
+ var succeeded = revertResult.Success || retryOutcome == RetryOutcome.Succeeded;
+ var partial = retryOutcome == RetryOutcome.Skipped && !revertResult.IsCompleteFailure;
+ var failed = (retryOutcome == RetryOutcome.None && !revertResult.Success) ||
+ (revertResult.IsCompleteFailure && retryOutcome == RetryOutcome.Skipped);
+
+ ShowOutcomeSnackbar(succeeded, partial, failed, "revert",
+ revertResult.Message, restorePointCreated);
+
+ if (succeeded)
+ _logger.LogInformation("Successfully reverted {Name}", optimization.OptimizationKey);
+ else if (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);
+ }
+ }
+ catch (Exception ex)
+ {
+ optimization.State.IsApplied = wasApplied; // revert UI state on failure
+ _logger.LogError(ex, "Failed to toggle optimization {Name}", optimization.OptimizationKey);
+ _snackbarService.Show(
+ Translations.Optimization_Toggle_Snackbar_Error_Title,
+ string.Format(Translations.Optimization_Toggle_Snackbar_Error_Message, ex.Message),
+ ControlAppearance.Danger,
+ new SymbolIcon { Symbol = SymbolRegular.ErrorCircle24, Filled = true },
+ TimeSpan.FromSeconds(5)
+ );
+ }
+ }
+ finally
+ {
+ IsProcessing = false;
+ }
+ }
+
+ /// <summary>
+ /// Shows the details of an optimization.
+ /// </summary>
+ /// <param name="optimization">The optimization to show details for.</param>
+ [RelayCommand]
+ private async Task ShowDetailsAsync(IOptimization optimization)
+ {
+ var dialogViewModel = new OptimizationDetailsViewModel(optimization, _snackbarService, _logger);
+ var dialogContent = new OptimizationDetailsDialog { DataContext = dialogViewModel };
+ var dialog = new ContentDialog
+ {
+ Title = BuildDialogTitle(optimization),
+ Content = dialogContent,
+ CloseButtonText = Translations.Button_Ok
+ };
+ var result = await _contentDialogService.ShowAsync(dialog, CancellationToken.None);
+ }
+
+ /// <summary>
+ /// Opens the source code of an optimization on GitHub.
+ /// </summary>
+ /// <param name="optimization">The optimization to view the source code for.</param>
+ [RelayCommand]
+ private async Task ViewSourceOnGitHubAsync(IOptimization optimization)
+ {
+ if (optimization is not BaseOptimization baseOpt || baseOpt.OwnerType == null)
+ return;
+
+ var fileName = baseOpt.OwnerType.Name;
+ var className = optimization.OptimizationKey;
+ var relativePath = $"optimizerDuck/Core/Optimizers/{fileName}.cs";
+ var url = $"{Shared.GitHubRepoURL}/blob/master/{relativePath}";
+
+ // Fetch source from GitHub raw content to find the class line number
+ try
+ {
+ var rawUrl = $"https://raw.githubusercontent.com/itsfatduck/optimizerDuck/master/{relativePath}";
+
+ string source;
+ if (_sourceCache.TryGetValue(rawUrl, out var cached)
+ && DateTime.UtcNow - cached.FetchedAt < SourceCacheTtl)
+ {
+ source = cached.Content;
+ }
+ else
+ {
+ source = await httpClient.GetStringAsync(rawUrl);
+ _sourceCache[rawUrl] = (source, DateTime.UtcNow);
+ }
+
+ var lines = source.Split('\n');
+ for (var i = 0; i < lines.Length; i++)
+ if (lines[i].Contains($"class {className}", StringComparison.OrdinalIgnoreCase))
+ {
+ url += $"#L{i + 1}";
+ break;
+ }
+ }
+ catch (Exception ex)
+ {
+ _logger.LogWarning(ex, "Could not fetch source to find line number for {Class}", className);
+ }
+
+ try
+ {
+ Process.Start(new ProcessStartInfo
+ {
+ FileName = url,
+ UseShellExecute = true
+ });
+ }
+ catch (Exception ex)
+ {
+ _logger.LogError(ex, "Failed to open GitHub URL: {Url}", url);
+ _snackbarService.Show(
+ Translations.Snackbar_OpenLinkFailed_Title,
+ Translations.Snackbar_OpenLinkFailed_Message,
+ ControlAppearance.Danger,
+ new SymbolIcon { Symbol = SymbolRegular.ErrorCircle24, Filled = true },
+ TimeSpan.FromSeconds(5));
+ }
+ }
+
+ #endregion Commands
+
+ #region CanExecutes
+
+ private bool CanToggleOptimization(IOptimization optimization)
+ {
+ return !IsProcessing;
+ }
+
+ #endregion
+
+ #region Helpers
+
/// <summary>
/// Load all optimizations from the category and apply filters.
/// </summary>
@@ -270,23 +518,31 @@ public partial class OptimizationCategoryViewModel : ViewModel
/// <param name="failed">Whether the operation failed.</param>
/// <param name="operationType">The type of operation.</param>
/// <param name="message">The message to show.</param>
- /// <param name="optimizationName">The name of the optimization.</param>
+ /// <param name="restorePointCreated">Whether a restore point was created.</param>
private void ShowOutcomeSnackbar(bool succeeded, bool partial, bool failed, string operationType,
- string message, string optimizationName, bool restorePointCreated = false)
+ string message, bool restorePointCreated = false)
{
+ var showSuccess = _appOptionsMonitor.CurrentValue.Optimize.ShowSnackbarNotificationAfterAppliedSuccessfully;
var finalMessage = message;
- if (restorePointCreated)
- finalMessage += "\n" + string.Format(Translations.RestorePoint_Snackbar_Success_Message, Shared.RestorePointName);
+
+ if (restorePointCreated && showSuccess)
+ finalMessage += "\n" + string.Format(Translations.RestorePoint_Snackbar_Success_Message,
+ Shared.RestorePointName);
if (succeeded)
- _snackbarService.Show(
- operationType == "apply"
- ? Translations.Optimization_Apply_Snackbar_Success_Title
- : Translations.Optimization_Revert_Snackbar_Success_Title,
- finalMessage,
- ControlAppearance.Success,
- new SymbolIcon { Symbol = SymbolRegular.CheckmarkCircle24, Filled = true },
- TimeSpan.FromSeconds(5));
+ {
+ if (showSuccess)
+ {
+ _snackbarService.Show(
+ operationType == "apply"
+ ? Translations.Optimization_Apply_Snackbar_Success_Title
+ : Translations.Optimization_Revert_Snackbar_Success_Title,
+ finalMessage,
+ ControlAppearance.Success,
+ new SymbolIcon { Symbol = SymbolRegular.CheckmarkCircle24, Filled = true },
+ TimeSpan.FromSeconds(5));
+ }
+ }
else if (partial)
_snackbarService.Show(
operationType == "apply"
@@ -337,6 +593,18 @@ public partial class OptimizationCategoryViewModel : ViewModel
switch (resultState)
{
case RestorePointResult.Success:
+ // if setting show snackbar after applied successfully was off, so show it and applied snackbar wont conflict this
+ if (!_appOptionsMonitor.CurrentValue.Optimize.ShowSnackbarNotificationAfterAppliedSuccessfully)
+ {
+ _snackbarService.Show(
+ Translations.RestorePoint_Snackbar_Success_Title,
+ string.Format(Translations.RestorePoint_Snackbar_Success_Message, Shared.RestorePointName),
+ ControlAppearance.Success,
+ new SymbolIcon { Symbol = SymbolRegular.CheckmarkCircle24, Filled = true },
+ TimeSpan.FromSeconds(5));
+ break;
+ }
+
restorePointCreated = true;
break;
@@ -398,240 +666,5 @@ public partial class OptimizationCategoryViewModel : ViewModel
Skipped
}
- #region Commands
-
-
- /// <summary>
- /// Toggles the optimization.
- /// </summary>
- /// <param name="optimization">The optimization to toggle.</param>
- [RelayCommand]
- private async Task ToggleOptimizationAsync(IOptimization optimization)
- {
- if (IsProcessing)
- {
- _logger.LogWarning("An optimization is already being processed, ignoring spam");
- return;
- }
-
- IsProcessing = true;
-
- try
- {
- // Keep a stable reference to the previous state in case we need to roll back UI changes.
- var wasApplied = await OptimizationService.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;
- }
-
- try
- {
- // Apply optimization if not already applied
- if (!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 Failed, we can't retry it
- if (applyResult.Status == OptimizationSuccessResult.Failed)
- {
- ShowOutcomeSnackbar(false, false, true, "apply",
- applyResult.Message, optimization.OptimizationKey, restorePointCreated);
-
- _logger.LogWarning("Apply failed for {Name}: {Message}",
- optimization.OptimizationKey, applyResult.Message);
-
- _logger.LogInformation(
- "===== END applying optimization {OptimizationName} ({OptimizationId}) =====",
- optimization.OptimizationKey, optimization.Id);
-
- await OptimizationService.UpdateOptimizationStateAsync(optimization);
- return;
- }
-
- // Retry only if there are some successful steps and some failed steps
- var retryOutcome = await HandleFailedStepsAsync(
- optimization,
- applyResult.FailedSteps,
- false);
-
- await OptimizationService.UpdateOptimizationStateAsync(optimization);
-
- var succeeded = applyResult.Status == OptimizationSuccessResult.Success ||
- retryOutcome == RetryOutcome.Succeeded;
- var partial = retryOutcome == RetryOutcome.Skipped;
- var failed = retryOutcome == RetryOutcome.None &&
- applyResult.Status != OptimizationSuccessResult.Success;
-
- ShowOutcomeSnackbar(succeeded, partial, failed, "apply",
- applyResult.Message, optimization.OptimizationKey, restorePointCreated);
-
- if (succeeded)
- _logger.LogInformation("Successfully applied {Name}", optimization.OptimizationKey);
- else if (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);
- }
- 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));
-
-
- var retryOutcome = await HandleFailedStepsAsync(
- optimization,
- revertResult.FailedStepDetails,
- true);
-
- await OptimizationService.UpdateOptimizationStateAsync(optimization);
-
- var succeeded = revertResult.Success || retryOutcome == RetryOutcome.Succeeded;
- var partial = retryOutcome == RetryOutcome.Skipped && !revertResult.IsCompleteFailure;
- var failed = (retryOutcome == RetryOutcome.None && !revertResult.Success) ||
- (revertResult.IsCompleteFailure && retryOutcome == RetryOutcome.Skipped);
-
- ShowOutcomeSnackbar(succeeded, partial, failed, "revert",
- revertResult.Message, optimization.OptimizationKey, restorePointCreated);
-
- if (succeeded)
- _logger.LogInformation("Successfully reverted {Name}", optimization.OptimizationKey);
- else if (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);
- }
- }
- catch (Exception ex)
- {
- optimization.State.IsApplied = wasApplied; // revert UI state on failure
- _logger.LogError(ex, "Failed to toggle optimization {Name}", optimization.OptimizationKey);
- _snackbarService.Show(
- Translations.Optimization_Toggle_Snackbar_Error_Title,
- string.Format(Translations.Optimization_Toggle_Snackbar_Error_Message, ex.Message),
- ControlAppearance.Danger,
- new SymbolIcon { Symbol = SymbolRegular.ErrorCircle24, Filled = true },
- TimeSpan.FromSeconds(5)
- );
- }
- }
- finally
- {
- IsProcessing = false;
- }
- }
-
- /// <summary>
- /// Shows the details of an optimization.
- /// </summary>
- /// <param name="optimization">The optimization to show details for.</param>
- [RelayCommand]
- private async Task ShowDetailsAsync(IOptimization optimization)
- {
- var dialogViewModel = new OptimizationDetailsViewModel(optimization, _snackbarService, _logger);
- var dialogContent = new OptimizationDetailsDialog { DataContext = dialogViewModel };
- var dialog = new ContentDialog
- {
- Title = BuildDialogTitle(optimization),
- Content = dialogContent,
- CloseButtonText = Translations.Button_Ok
- };
- var result = await _contentDialogService.ShowAsync(dialog, CancellationToken.None);
- }
-
- /// <summary>
- /// Opens the source code of an optimization on GitHub.
- /// </summary>
- /// <param name="optimization">The optimization to view the source code for.</param>
- [RelayCommand]
- private async Task ViewSourceOnGitHubAsync(IOptimization optimization)
- {
- if (optimization is not BaseOptimization baseOpt || baseOpt.OwnerType == null)
- return;
-
- var fileName = baseOpt.OwnerType.Name;
- var className = optimization.OptimizationKey;
- var relativePath = $"optimizerDuck/Core/Optimizers/{fileName}.cs";
- var url = $"{Shared.GitHubRepoURL}/blob/master/{relativePath}";
-
- // Fetch source from GitHub raw content to find the class line number
- try
- {
- var rawUrl = $"https://raw.githubusercontent.com/itsfatduck/optimizerDuck/master/{relativePath}";
-
- string source;
- if (_sourceCache.TryGetValue(rawUrl, out var cached)
- && DateTime.UtcNow - cached.FetchedAt < SourceCacheTtl)
- {
- source = cached.Content;
- }
- else
- {
- source = await httpClient.GetStringAsync(rawUrl);
- _sourceCache[rawUrl] = (source, DateTime.UtcNow);
- }
-
- var lines = source.Split('\n');
- for (var i = 0; i < lines.Length; i++)
- if (lines[i].Contains($"class {className}", StringComparison.OrdinalIgnoreCase))
- {
- url += $"#L{i + 1}";
- break;
- }
- }
- catch (Exception ex)
- {
- _logger.LogWarning(ex, "Could not fetch source to find line number for {Class}", className);
- }
-
- try
- {
- Process.Start(new ProcessStartInfo
- {
- FileName = url,
- UseShellExecute = true
- });
- }
- catch (Exception ex)
- {
- _logger.LogError(ex, "Failed to open GitHub URL: {Url}", url);
- _snackbarService.Show(
- Translations.Snackbar_OpenLinkFailed_Title,
- Translations.Snackbar_OpenLinkFailed_Message,
- ControlAppearance.Danger,
- new SymbolIcon { Symbol = SymbolRegular.ErrorCircle24, Filled = true },
- TimeSpan.FromSeconds(5));
- }
- }
-
- #endregion Commands
+ #endregion
}
\ No newline at end of file
diff --git a/optimizerDuck/UI/ViewModels/Pages/SettingsViewModel.cs b/optimizerDuck/UI/ViewModels/Pages/SettingsViewModel.cs
index 1f959bc..fac44da 100644
--- a/optimizerDuck/UI/ViewModels/Pages/SettingsViewModel.cs
+++ b/optimizerDuck/UI/ViewModels/Pages/SettingsViewModel.cs
@@ -33,6 +33,7 @@ public partial class SettingsViewModel(
[ObservableProperty] private string _selectedCultureName = string.Empty;
[ObservableProperty] private int _shellTimeoutMs;
+ [ObservableProperty] private bool _showSnackbarNotificationAfterAppliedSuccessfully;
public string Version { get; } = Shared.FileVersion;
//Learn more links
@@ -58,6 +59,7 @@ public partial class SettingsViewModel(
{
SelectedCultureName = appOptionsMonitor.CurrentValue.App.Language;
ShellTimeoutMs = appOptionsMonitor.CurrentValue.Optimize.ShellTimeoutMs;
+ ShowSnackbarNotificationAfterAppliedSuccessfully = appOptionsMonitor.CurrentValue.Optimize.ShowSnackbarNotificationAfterAppliedSuccessfully;
RemoveProvisioned = appOptionsMonitor.CurrentValue.Bloatware.RemoveProvisioned;
CurrentApplicationTheme = ApplicationThemeManager.GetAppTheme();
@@ -214,6 +216,14 @@ public partial class SettingsViewModel(
(!appOptionsMonitor.CurrentValue.Bloatware.RemoveProvisioned).ToString());
}
+ [RelayCommand]
+ private void ToggleShowSnackbarNotificationAfterAppliedSuccessfully()
+ {
+ if (!_isInitialized) return;
+ _ = configManager.SetAsync("optimize:showSnackbarNotificationAfterAppliedSuccessfully",
+ (!appOptionsMonitor.CurrentValue.Optimize.ShowSnackbarNotificationAfterAppliedSuccessfully).ToString());
+ }
+
[RelayCommand]
private void OpenLatestRelease()
{
diff --git a/optimizerDuck/UI/Views/Pages/SettingsPage.xaml b/optimizerDuck/UI/Views/Pages/SettingsPage.xaml
index d20ebe0..28b6517 100644
--- a/optimizerDuck/UI/Views/Pages/SettingsPage.xaml
+++ b/optimizerDuck/UI/Views/Pages/SettingsPage.xaml
@@ -111,6 +111,25 @@
SmallChange="1000"
Value="{Binding ViewModel.ShellTimeoutMs, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />
</ui:CardControl>
+
+ <ui:CardControl Icon="{ui:SymbolIcon Alert24}">
+ <ui:CardControl.Header>
+ <StackPanel>
+ <ui:TextBlock
+ Appearance="Primary"
+ FontTypography="BodyStrong"
+ Margin="0"
+ Text="{ext:Loc Settings.Optimize.ShowSnackbarNotificationAfterAppliedSuccessfully.Title}"
+ TextWrapping="Wrap" />
+ <ui:TextBlock
+ Appearance="Secondary"
+ Text="{ext:Loc Settings.Optimize.ShowSnackbarNotificationAfterAppliedSuccessfully.Description}"
+ TextWrapping="Wrap" />
+ </StackPanel>
+ </ui:CardControl.Header>
+
+ <ui:ToggleSwitch Command="{Binding ViewModel.ToggleShowSnackbarNotificationAfterAppliedSuccessfullyCommand}" IsChecked="{Binding ViewModel.ShowSnackbarNotificationAfterAppliedSuccessfully, Mode=TwoWay}" />
+ </ui:CardControl>
</StackPanel>
<StackPanel Margin="0,20,0,0">