Skip to content

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

feat(windows): use documented Windows APIs instead of shell paths

fatDuckc28673f9828d
diff --git a/AGENTS.md b/AGENTS.md
index c8d8e14..ed9985e 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -44,11 +44,10 @@
- `Configuration/` — `ConfigManager`, `LanguageManager`
- `Customize/` — `CustomizeRegistry` (reflection-based discovery), `CustomizationExecutor` (debounce + sequential serialization for setting writes)
- `Optimization/` — `OptimizationRegistry`, `OptimizationService`, `OptimizationValidation` (fail-fast Id checks at startup)
- - `System/Primitives/` — `RegistryService`, `ScheduledTaskService`, `ServiceProcessService` are **static** (stateless); `ShellService` + `ProcessRunner` are DI singletons (stateful; `ShellService` reads the timeout live from settings). Those four take an explicit `OpCall`, record into `call.Changes`, log via `call.Logger`, return `OpResult`. `ShellMapping` centralises cmd/PowerShell argument building and result mapping. `PowerPlanChanges` is the single edge recorder turning lean `PowerPlanService` results into `Change` + revert step + retry (categories never hand-roll power steps).
- - `Windows/Services/ScStartupTypeParser.cs` — shared parser for `sc.exe qc` START_TYPE output, used by `ServiceProcessService`.
+ - `System/Primitives/` — `RegistryService`, `ScheduledTaskService`, `ServiceProcessService` are **static** (stateless); `ShellService` + `ProcessRunner` are DI singletons (stateful; `ShellService` reads the timeout live from settings). Those four take an explicit `OpCall`, record into `call.Changes`, log via `call.Logger`, return `OpResult`. `ShellMapping` centralises cmd/PowerShell argument building and result mapping. `PowerPlanChanges` is the single edge recorder turning lean `PowerPlanService` results into `Change` + revert step + retry (categories never hand-roll power steps). Service startup types are read and written through the Service Control Manager inside `ServiceProcessService` (no `sc.exe`, no START_TYPE parsing). `RecycleBinService`, `HibernationService` and `UsbPowerService` are **static** primitives owning one Windows operation each (shell Recycle Bin APIs, the documented power information callback, `root\wmi` device power) and fail open instead of throwing.
- `ApplicationServiceCollectionExtensions.cs` — `AddOptimizerApplication(IConfiguration)`: the whole application graph, separated from `App.xaml.cs` so a test can build it
- `Revert/` — `RevertManager` (atomic file-based revert data persistence)
- - `System/` — `RegistryWatcher` (+ `IRegistryWatcher`), `SystemInfoService` (defines `SystemInfo` + models), `StreamService`, `UpdaterService`, `CrossPageEventBus`, `CrossPageEvents`, `PowerPlanService` (lean native core: reads take ids, writes take `ILogger? = null` and record nothing; single owner of all `powrprof.dll` interop)
+ - `System/` — `RegistryWatcher` (+ `IRegistryWatcher`), `SystemInfoService` (defines `SystemInfo` + models), `StreamService`, `UpdaterService`, `CrossPageEventBus`, `CrossPageEvents`, `PowerPlanService` (lean native core: reads take ids, writes take `ILogger? = null` and record nothing; single owner of power **scheme** interop), `SystemRestoreService` (same lean shape; single owner of every System Restore WMI call, reusable by a future restore-point tool)
- `UI/` — `BloatwareService`, `DiskCleanupService`, `StartupManagerService`
- `UI/` — XAML pages, ViewModels, windows, controls, dialogs, styles
- `Common/` — extensions, helpers, converters:
@@ -80,7 +79,7 @@
- **Provider services**: stateless services are static (`RegistryService`, `ServiceProcessService`, `ScheduledTaskService`) — call directly. `ShellService` + `ProcessRunner` are DI singletons, reached from optimizations as `context.Shell`. All take an explicit `OpCall`, record into `call.Changes`, return `OpResult`. Exception: `PowerPlanService` is a lean DI singleton — reads take ids, writes take `ILogger? = null` and record nothing (named record results); `PowerPlanChanges` records at the edge instead.
- **Results**: Optimizations end `ApplyAsync` with `return context.Changes.ToApplyResult();`. Do not manually construct `ApplyResult` except for early-out failures.
- **Single execution path**: `BaseOptimization` + `OptimizationContext` (`OpCall`) + static providers + `ShellService`, orchestrated by `OptimizationService`. There is no second framework — do not add one, and do not write a second implementation of an existing Windows operation.
-- **One implementation per Windows operation**: `RegistryService`/`ServiceProcessService`/`ScheduledTaskService`/`ShellService` are the single source of truth (plus the shared `ScStartupTypeParser`, `RegistryValues`, `ShellMapping`). `PowerPlanService` is the single owner of all `powrprof.dll` interop. Fix behaviour there, not in a copy.
+- **One implementation per Windows operation**: `RegistryService`/`ServiceProcessService`/`ScheduledTaskService`/`ShellService` are the single source of truth (plus the shared `RegistryValues`, `ShellMapping`), `PowerPlanService` owns power-scheme interop, `SystemRestoreService` owns System Restore, and the static primitives (`RecycleBinService`, `HibernationService`, `UsbPowerService`) own one Windows operation each. Fix behaviour there, not in a copy.
- **DI**: register through `AddOptimizerApplication(configuration)` (the whole app graph); `App.xaml.cs` only builds the host. The host sets `ValidateOnBuild`/`ValidateScopes`, so a broken registration fails at startup instead of at Apply time — keep it that way.
- **Per-step failure policy**: providers record a failed `Change` with an error and (where a retry can help) a retry action; they do not throw. Power failures record the same way via `PowerPlanChanges` (the service itself only returns diagnostics). Only truly unrecoverable state throws. `OptimizationService` persists partial work with `CancellationToken.None` and builds the `OptimizationResult`.
- **Preloading**: `OptimizationRegistry.PreloadOptimizationsAsync()` / `EnsurePreloadedAsync()` (and `CustomizeRegistry.PreloadCategoriesAsync()` / `EnsurePreloadedAsync()`) run reflection discovery on a background thread. `App.xaml.cs` preloads at startup; the Optimize/Customize pages call `EnsurePreloadedAsync()` before binding.
@@ -161,11 +160,11 @@ Applies to every supported and future locale. Goal is natural localization, not
- `Write(params RegistryItem[] items)` and `DeleteValue(params RegistryItem[] items)` — batch variants that deduplicate.
## Service Process Service Details
-- `GetStartupTypeAsync(serviceName)` — queries current startup type via `sc.exe qc`. Returns `(ServiceStartupType?, bool NotFound)`. Uses locale-independent regex parsing of `sc qc` output.
-- `ChangeServiceStartupTypeAsync(ServiceItem)` — changes via `sc.exe config`. Records `ServiceRevertStep` only if the startup type actually changed.
+- `GetStartupTypeAsync(serviceName)` — reads the configured startup type from the Service Control Manager (`QueryServiceConfig`, plus `QueryServiceConfig2` for the delayed-auto flag). Returns `(ServiceStartupType?, bool NotFound)`; a missing service comes back as `ERROR_SERVICE_DOES_NOT_EXIST` (1060), boot/system starts as `null`.
+- `ChangeServiceStartupTypeAsync(ServiceItem)` — writes through `ChangeServiceConfig`, then `ChangeServiceConfig2` for auto-start targets so a stale delayed-auto flag cannot survive a change back to plain Automatic. Records `ServiceRevertStep` only if the startup type actually changed.
- `ChangeServiceStartupTypeAsync(params ServiceItem[])` — batch variant for multiple services.
- `ServiceStartupType` enum: `Automatic`, `AutomaticDelayedStart`, `Manual`, `Disabled`. Note: Boot (0) and System (1) startup types are not used in this app.
-- Uses `sc.exe` with timeouts: 15s for queries, 30s for config changes.
+- No child process and no `sc.exe`: handles are opened and closed per operation and Win32 codes are mapped (1060 not found, 5 access denied, anything else reported as a failure).
## Scheduled Task Service Details
- Uses `Microsoft.Win32.TaskScheduler` library (TaskScheduler NuGet package).
@@ -183,7 +182,8 @@ Applies to every supported and future locale. Goal is natural localization, not
- `ServiceRevertStep` — stores `ServiceName` and `OriginalStartupType`.
- `ScheduledTaskRevertStep` — stores `FullPath` and `OriginalEnabled` state.
- `ShellRevertStep` — stores `ShellType` (CMD/PowerShell) and `Command`.
-- `UsbPowerRevertStep` — stores list of `DeviceState` (InstanceName + Enable) for USB power settings.
+- `UsbPowerRevertStep` — stores list of `DeviceState` (InstanceName + Enable) for USB power settings; restoring goes through the in-process `root\wmi` client.
+- `HibernationRevertStep` — stores `WasPresent` (whether the hibernation file existed) and restores it through the power information callback.
## Commit & PR
- Conventional Commits: `feat:`, `fix:`, `refactor:`, `docs:`, `test:`, `i18n:`, `chore:`.
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index a632898..53939c4 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -482,7 +482,7 @@ Providers reached through `context`:
| Provider | Records | Notes |
|---|---|---|
| `RegistryService` (static) | `RegistryRevertStep` | `Write` / `DeleteValue` / `CreateSubKey` / `DeleteSubKeyTree` |
-| `ServiceProcessService` (static) | `ServiceRevertStep` | sc.exe; access-denied is a reported failure, never a silent success |
+| `ServiceProcessService` (static) | `ServiceRevertStep` | SCM (`ChangeServiceConfig` + `ChangeServiceConfig2`); access-denied is a reported failure, never a silent success |
| `ScheduledTaskService` (static) | `ScheduledTaskRevertStep` | enable/disable, run/stop, register |
| `context.Shell` (`ShellService`) | `ShellRevertStep` | pass a `revertCommand` with `CMDAsync`/`PowerShellAsync` |
diff --git a/optimizerDuck.Test/Common/Helpers/SystemRefreshServiceTests.cs b/optimizerDuck.Test/Common/Helpers/SystemRefreshServiceTests.cs
index f539975..f67b67a 100644
--- a/optimizerDuck.Test/Common/Helpers/SystemRefreshServiceTests.cs
+++ b/optimizerDuck.Test/Common/Helpers/SystemRefreshServiceTests.cs
@@ -52,6 +52,18 @@ public class SystemRefreshServiceTests
Assert.Null(exception);
}
+ [Fact]
+ public void Notify_InvalidWindowHandle_ReturnsWithoutThrowing()
+ {
+ // 0x1033 is LVM_REFRESH. A bogus handle must make the send fail fast instead of
+ // blocking, and the refresh path must swallow that as a no-op.
+ var exception = Record.Exception(() =>
+ SystemRefreshService.Notify(new IntPtr(0x12345678), 0x1033, IntPtr.Zero)
+ );
+
+ Assert.Null(exception);
+ }
+
[Fact]
public void UpdatePerUserSystemParameters_DoesNotThrow()
{
diff --git a/optimizerDuck.Test/Domain/Revert/Steps/RevertStepSerializationTests.cs b/optimizerDuck.Test/Domain/Revert/Steps/RevertStepSerializationTests.cs
index 8736f63..317bf82 100644
--- a/optimizerDuck.Test/Domain/Revert/Steps/RevertStepSerializationTests.cs
+++ b/optimizerDuck.Test/Domain/Revert/Steps/RevertStepSerializationTests.cs
@@ -25,6 +25,28 @@ public class RevertStepSerializationTests
Assert.Equal(original.Type, restored.Type);
}
+ [Fact]
+ public void HibernationRevertStep_RoundTrip_PreservesAllProperties()
+ {
+ var original = new HibernationRevertStep { WasPresent = true };
+
+ var json = original.ToData();
+ var restored = HibernationRevertStep.FromData(json);
+
+ Assert.True(restored.WasPresent);
+ Assert.Equal("Hibernation", restored.Type);
+ Assert.Equal(original.Type, restored.Type);
+ }
+
+ [Fact]
+ public void HibernationRevertStep_MissingFlag_DefaultsToPresent()
+ {
+ // Fail-safe default shared with the optimization: restore hibernation when unknown.
+ var restored = HibernationRevertStep.FromData(new JObject());
+
+ Assert.True(restored.WasPresent);
+ }
+
[Fact]
public void ShellRevertStep_PowerShell_RoundTrip()
{
@@ -221,6 +243,24 @@ public class RevertStepSerializationTests
Assert.Empty(restored.States);
}
+ [Fact]
+ public void UsbPowerRevertStep_DeserializesPayloadWrittenBeforeTheConversion()
+ {
+ // Literal on-disk shape produced by the PowerShell-era implementation; the step must keep
+ // reading it now that restoring goes through the in-process WMI client.
+ var json = JObject.Parse(
+ """{"States":[{"InstanceName":"USB\\ROOT_HUB30\\5&1&0_0","Enable":true},{"InstanceName":"USB\\ROOT_HUB30\\5&2&0_0","Enable":false}]}"""
+ );
+
+ var restored = UsbPowerRevertStep.FromData(json);
+
+ Assert.Equal("UsbPower", restored.Type);
+ Assert.Equal(2, restored.States.Count);
+ Assert.Equal(@"USB\ROOT_HUB30\5&1&0_0", restored.States[0].InstanceName);
+ Assert.True(restored.States[0].Enable);
+ Assert.False(restored.States[1].Enable);
+ }
+
[Fact]
public void RegistryRevertStep_RestorePreviousDWord_RoundTrip()
{
diff --git a/optimizerDuck.Test/Services/ApplyRevertComprehensiveTests.cs b/optimizerDuck.Test/Services/ApplyRevertComprehensiveTests.cs
index 965b78a..a0f272d 100644
--- a/optimizerDuck.Test/Services/ApplyRevertComprehensiveTests.cs
+++ b/optimizerDuck.Test/Services/ApplyRevertComprehensiveTests.cs
@@ -1096,6 +1096,7 @@ public class ApplyRevertComprehensiveTests
contentDialogService,
shellService,
new PowerPlanService(NullLogger<PowerPlanService>.Instance),
+ new SystemRestoreService(NullLogger<SystemRestoreService>.Instance),
logger
);
}
diff --git a/optimizerDuck.Test/Services/OptimizationServiceIntegrationTests.cs b/optimizerDuck.Test/Services/OptimizationServiceIntegrationTests.cs
index b732908..cc66331 100644
--- a/optimizerDuck.Test/Services/OptimizationServiceIntegrationTests.cs
+++ b/optimizerDuck.Test/Services/OptimizationServiceIntegrationTests.cs
@@ -128,6 +128,7 @@ public class OptimizationServiceIntegrationTests : IDisposable
null!,
new ShellService(new ProcessRunner(120000)),
new PowerPlanService(NullLogger<PowerPlanService>.Instance),
+ new SystemRestoreService(NullLogger<SystemRestoreService>.Instance),
NullLogger<OptimizationService>.Instance
);
diff --git a/optimizerDuck.Test/Services/OptimizationServiceTests.cs b/optimizerDuck.Test/Services/OptimizationServiceTests.cs
index bfab7f8..a2013d3 100644
--- a/optimizerDuck.Test/Services/OptimizationServiceTests.cs
+++ b/optimizerDuck.Test/Services/OptimizationServiceTests.cs
@@ -562,6 +562,7 @@ public class OptimizationServiceTests
contentDialogService,
shellService,
new PowerPlanService(NullLogger<PowerPlanService>.Instance),
+ new SystemRestoreService(NullLogger<SystemRestoreService>.Instance),
logger
);
}
diff --git a/optimizerDuck.Test/Services/OptimizationServices/HibernationServiceTests.cs b/optimizerDuck.Test/Services/OptimizationServices/HibernationServiceTests.cs
new file mode 100644
index 0000000..853b6c7
--- /dev/null
+++ b/optimizerDuck.Test/Services/OptimizationServices/HibernationServiceTests.cs
@@ -0,0 +1,62 @@
+using optimizerDuck.Services.System.Primitives;
+
+namespace optimizerDuck.Test.Services.OptimizationServices;
+
+/// <summary>
+/// Live powrprof tests. The read path is checked against the hibernation file itself; the
+/// commit/removal path is only exercised when a call is refused, because actually changing the
+/// hibernation file on the test host is a system change (task 5.3 verifies it by hand).
+/// </summary>
+public class HibernationServiceTests
+{
+ private static bool IsElevated()
+ {
+ using var identity = System.Security.Principal.WindowsIdentity.GetCurrent();
+ return new System.Security.Principal.WindowsPrincipal(identity).IsInRole(
+ System.Security.Principal.WindowsBuiltInRole.Administrator
+ );
+ }
+
+ [Fact]
+ public void IsHibernationFilePresent_ReportsStateWithoutThrowing()
+ {
+ var reported = HibernationService.IsHibernationFilePresent();
+
+ Assert.NotNull(reported);
+
+ // One-directional cross-check: when Windows reports no hibernation file, hiberfil.sys must
+ // not be there. The reverse cannot be asserted safely - File.Exists swallows access-denied
+ // on that protected system file.
+ if (reported is false)
+ Assert.False(File.Exists(@"C:\hiberfil.sys"));
+ }
+
+ [Fact]
+ public void IsHibernationFilePresent_IsStableAcrossCalls()
+ {
+ Assert.Equal(
+ HibernationService.IsHibernationFilePresent(),
+ HibernationService.IsHibernationFilePresent()
+ );
+ }
+
+ [Fact]
+ public void SetHibernationFile_WithoutPrivileges_IsRefusedWithStatus()
+ {
+ if (IsElevated())
+ {
+ Assert.Skip(
+ "Elevated: this would really commit or remove the hibernation file, which is a system change (task 5.3 covers it by hand)."
+ );
+ }
+
+ var result = HibernationService.SetHibernationFile(present: false);
+
+ Assert.False(result.Succeeded);
+ Assert.Null(result.ExceptionText);
+ // Observed on an unelevated host: 0xC0000061 (STATUS_PRIVILEGE_NOT_HELD). The documented
+ // failure table lists STATUS_ACCESS_DENIED instead, so this asserts "not success" rather
+ // than one specific code.
+ Assert.NotEqual(0u, result.NativeStatus);
+ }
+}
diff --git a/optimizerDuck.Test/Services/OptimizationServices/RecycleBinServiceTests.cs b/optimizerDuck.Test/Services/OptimizationServices/RecycleBinServiceTests.cs
new file mode 100644
index 0000000..503e073
--- /dev/null
+++ b/optimizerDuck.Test/Services/OptimizationServices/RecycleBinServiceTests.cs
@@ -0,0 +1,83 @@
+using optimizerDuck.Services.System.Primitives;
+
+namespace optimizerDuck.Test.Services.OptimizationServices;
+
+/// <summary>
+/// Live shell32 tests: real Recycle Bin state, no mocks. Nothing here destroys user data -
+/// the only emptying call runs on an empty bin, and the failure path targets an invalid root.
+/// </summary>
+public class RecycleBinServiceTests
+{
+ [Fact]
+ public void Query_AllDrives_ReportsConsistentTotals()
+ {
+ var totals = RecycleBinService.Query();
+
+ Assert.True(totals.SizeBytes >= 0, $"negative size {totals.SizeBytes}");
+ Assert.True(totals.ItemCount >= 0, $"negative count {totals.ItemCount}");
+
+ // Empty bins report zero for both; a non-empty bin cannot report bytes without items.
+ if (totals.SizeBytes == 0)
+ Assert.Equal(0, totals.ItemCount);
+ else
+ Assert.True(totals.ItemCount > 0, $"size {totals.SizeBytes} with no items");
+ }
+
+ [Fact]
+ public void Query_InvalidRoot_ReturnsZeroes()
+ {
+ // Verified live: shell32 answers ERROR_PATH_NOT_FOUND for a non-drive string, and the
+ // service turns that into zeroes so the cleanup page has no failure branch.
+ var totals = RecycleBinService.Query("not-a-drive");
+
+ Assert.Equal(0, totals.SizeBytes);
+ Assert.Equal(0, totals.ItemCount);
+ }
+
+ [Fact]
+ public void Query_SystemDrive_DoesNotExceedAllDrives()
+ {
+ var all = RecycleBinService.Query();
+ var systemDrive = Path.GetPathRoot(
+ Environment.GetFolderPath(Environment.SpecialFolder.Windows)
+ );
+ Assert.False(string.IsNullOrEmpty(systemDrive));
+
+ var one = RecycleBinService.Query(systemDrive!);
+
+ Assert.True(one.SizeBytes >= 0);
+ Assert.True(one.ItemCount >= 0);
+ }
+
+ [Fact]
+ public void Empty_InvalidRoot_FailsWithError()
+ {
+ var (succeeded, errorCode) = RecycleBinService.Empty("not-a-drive");
+
+ Assert.False(succeeded);
+ Assert.NotEqual(0, errorCode);
+ }
+
+ [Fact]
+ public void Empty_EmptyBin_Succeeds()
+ {
+ var totals = RecycleBinService.Query();
+ if (totals.ItemCount != 0)
+ {
+ Assert.Skip(
+ $"Recycle Bin holds {totals.ItemCount} item(s); emptying it here would destroy real user data, so this test only runs on an empty bin."
+ );
+ }
+
+ var (succeeded, errorCode) = RecycleBinService.Empty();
+
+ Assert.True(succeeded, $"SHEmptyRecycleBin failed with 0x{errorCode:X8}");
+ }
+
+ [Fact]
+ public void SuppressionFlags_AreTheThreeDocumentedOnes()
+ {
+ // SHERB_NOCONFIRMATION (1) | SHERB_NOPROGRESSUI (2) | SHERB_NOSOUND (4)
+ Assert.Equal(0x7u, RecycleBinService.SuppressionFlags);
+ }
+}
diff --git a/optimizerDuck.Test/Services/OptimizationServices/ServiceProcessServiceTests.cs b/optimizerDuck.Test/Services/OptimizationServices/ServiceProcessServiceTests.cs
index 0e62bd6..a7b9933 100644
--- a/optimizerDuck.Test/Services/OptimizationServices/ServiceProcessServiceTests.cs
+++ b/optimizerDuck.Test/Services/OptimizationServices/ServiceProcessServiceTests.cs
@@ -1,6 +1,8 @@
using Microsoft.Extensions.Logging.Abstractions;
+using Microsoft.Win32;
using optimizerDuck.Domain.Execution;
using optimizerDuck.Domain.Optimizations.Models.Services;
+using optimizerDuck.Domain.Revert.Steps;
using optimizerDuck.Services.System.Primitives;
namespace optimizerDuck.Test.Services.OptimizationServices;
@@ -11,227 +13,136 @@ public class ServiceProcessServiceTests
new() { Changes = new ChangeSet(), Logger = NullLogger.Instance };
// =============================================
- // Unit tests: ParseScStartType (hardcoded input)
+ // Integration tests: GetStartupTypeAsync (real sc.exe)
// =============================================
[Fact]
- public void ParseScStartType_AutoStart_ReturnsAutomatic()
+ public async Task GetStartupTypeAsync_ExistingAutoService_ReturnsAutomatic()
{
- var stdout = """
- SERVICE_NAME: Audiosrv
- TYPE : 20 WIN32_SHARE_PROCESS
- START_TYPE : 2 AUTO_START
- ERROR_CONTROL : 1 NORMAL
- """;
-
- var (result, parseFailed) = ServiceProcessService.ParseScStartType(stdout);
+ var (result, notFound) = await ServiceProcessService.GetStartupTypeAsync("Audiosrv");
- Assert.False(parseFailed);
+ Assert.False(notFound);
+ Assert.NotNull(result);
Assert.Equal(ServiceStartupType.Automatic, result);
}
[Fact]
- public void ParseScStartType_AutoStartDelayed_ReturnsAutomaticDelayedStart()
- {
- var stdout = """
- SERVICE_NAME: CDPSvc
- TYPE : 20 WIN32_SHARE_PROCESS
- START_TYPE : 2 AUTO_START (DELAYED)
- ERROR_CONTROL : 1 NORMAL
- """;
-
- var (result, parseFailed) = ServiceProcessService.ParseScStartType(stdout);
-
- Assert.False(parseFailed);
- Assert.Equal(ServiceStartupType.AutomaticDelayedStart, result);
- }
-
- [Fact]
- public void ParseScStartType_DemandStart_ReturnsManual()
- {
- var stdout = """
- SERVICE_NAME: BITS
- TYPE : 20 WIN32_SHARE_PROCESS
- START_TYPE : 3 DEMAND_START
- ERROR_CONTROL : 1 NORMAL
- """;
-
- var (result, parseFailed) = ServiceProcessService.ParseScStartType(stdout);
-
- Assert.False(parseFailed);
- Assert.Equal(ServiceStartupType.Manual, result);
- }
-
- [Fact]
- public void ParseScStartType_Disabled_ReturnsDisabled()
- {
- var stdout = """
- SERVICE_NAME: AppVClient
- TYPE : 10 WIN32_OWN_PROCESS
- START_TYPE : 4 DISABLED
- ERROR_CONTROL : 1 NORMAL
- """;
-
- var (result, parseFailed) = ServiceProcessService.ParseScStartType(stdout);
-
- Assert.False(parseFailed);
- Assert.Equal(ServiceStartupType.Disabled, result);
- }
-
- [Fact]
- public void ParseScStartType_BootStart_ReturnsNullNotFailed()
- {
- var stdout = """
- SERVICE_NAME: ACPI
- TYPE : 1 KERNEL_DRIVER
- START_TYPE : 0 BOOT_START
- ERROR_CONTROL : 1 NORMAL
- """;
-
- var (result, parseFailed) = ServiceProcessService.ParseScStartType(stdout);
-
- Assert.False(parseFailed);
- Assert.Null(result);
- }
-
- [Fact]
- public void ParseScStartType_SystemStart_ReturnsNullNotFailed()
- {
- var stdout = """
- SERVICE_NAME: AFD
- TYPE : 1 KERNEL_DRIVER
- START_TYPE : 1 SYSTEM_START
- ERROR_CONTROL : 1 NORMAL
- """;
-
- var (result, parseFailed) = ServiceProcessService.ParseScStartType(stdout);
-
- Assert.False(parseFailed);
- Assert.Null(result);
- }
-
- [Fact]
- public void ParseScStartType_NoStartTypeLine_ReturnsParseFailed()
- {
- var stdout = """
- SERVICE_NAME: TestSvc
- BINARY_PATH_NAME : C:\test.exe
- """;
-
- var (result, parseFailed) = ServiceProcessService.ParseScStartType(stdout);
-
- Assert.True(parseFailed);
- Assert.Null(result);
- }
-
- [Fact]
- public void ParseScStartType_IgnoresErrorControlLine_ReturnsCorrectType()
+ public async Task GetStartupTypeAsync_ExistingDemandService_ReturnsManual()
{
- var stdout = """
- SERVICE_NAME: Test
- TYPE : 20 WIN32_SHARE_PROCESS
- START_TYPE : 3 DEMAND_START
- ERROR_CONTROL : 1 NORMAL
- """;
-
- var (result, parseFailed) = ServiceProcessService.ParseScStartType(stdout);
+ var (result, notFound) = await ServiceProcessService.GetStartupTypeAsync("msiserver");
- Assert.False(parseFailed);
+ Assert.False(notFound);
+ Assert.NotNull(result);
Assert.Equal(ServiceStartupType.Manual, result);
}
[Fact]
- public void ParseScStartType_IgnoresTagZero_ReturnsCorrectType()
+ public async Task GetStartupTypeAsync_NonexistentService_ReturnsNotFound()
{
- var stdout = """
- SERVICE_NAME: Test
- TYPE : 20 WIN32_SHARE_PROCESS
- START_TYPE : 3 DEMAND_START
- ERROR_CONTROL : 1 NORMAL
- TAG : 0
- """;
-
- var (result, parseFailed) = ServiceProcessService.ParseScStartType(stdout);
+ var (_, notFound) = await ServiceProcessService.GetStartupTypeAsync(
+ "OptimizerDuckTest_Nonexistent_Service_12345"
+ );
- Assert.False(parseFailed);
- Assert.Equal(ServiceStartupType.Manual, result);
+ Assert.True(notFound);
}
- [Fact]
- public void ParseScStartType_LocaleIndependentFieldName_ReturnsCorrectType()
- {
- var stdout = """
- SERVICE_NAME: Test
- FOO_TYPE : 20 WIN32_SHARE_PROCESS
- STARTTYP : 2 AUTOMATISCHER_START
- FEHLERKONTROLLE : 1 NORMAL
- """;
-
- var (result, parseFailed) = ServiceProcessService.ParseScStartType(stdout);
-
- Assert.False(parseFailed);
- Assert.Equal(ServiceStartupType.Automatic, result);
- }
+ // =============================================
+ // Contract fixture: read mapping against registry ground truth.
+ // Independent of the mechanism: the expected value comes from
+ // HKLM\SYSTEM\CurrentControlSet\Services, where Windows stores Start (2 auto / 3 manual /
+ // 4 disabled) and the DelayedAutoStart flag. Driver entries are included on purpose - the
+ // Service Control Manager reports their start type without the TYPE/START_TYPE ambiguity that
+ // sc.exe output had. Boot (0) and system (1) starts are excluded: they are outside the app's
+ // ServiceStartupType domain, and the registry is not authoritative for them (55 uninstalled
+ // driver entries on this machine report DEMAND_START through the SCM, and sc.exe - which also
+ // reads the SCM - reported exactly the same before this conversion).
+ // =============================================
- [Fact]
- public void ParseScStartType_LocaleIndependentDelayed_ReturnsAutomaticDelayedStart()
+ private const int PerTypeSampleLimit = 8;
+
+ /// <summary>
+ /// Registry truth for one services entry: the startup type implied by Start plus the
+ /// DelayedAutoStart flag, and whether this is a Win32 service (Type 0x10 | 0x20 | 0x30)
+ /// rather than a driver (Type 1 kernel, 2 file system, 4 recognizer, 8 adapter).
+ /// </summary>
+ private static (
+ bool Found,
+ ServiceStartupType? Expected,
+ bool IsWin32Service
+ ) ReadRegistryTruth(RegistryKey services, string name)
{
- var stdout = """
- SERVICE_NAME: Test
- STARTTYP : 2 AUTOMATISCHER_START (VERZÖGERT)
- """;
-
- var (result, parseFailed) = ServiceProcessService.ParseScStartType(stdout);
+ using var key = services.OpenSubKey(name);
+ if (
+ key?.GetValue("ImagePath") is null
+ || key.GetValue("Start") is not int start
+ || key.GetValue("Type") is not int type
+ )
+ return (false, null, false);
+
+ var delayed = key.GetValue("DelayedAutoStart") is int flag && flag == 1;
+ ServiceStartupType? expected = start switch
+ {
+ 2 => delayed ? ServiceStartupType.AutomaticDelayedStart : ServiceStartupType.Automatic,
+ 3 => ServiceStartupType.Manual,
+ 4 => ServiceStartupType.Disabled,
+ _ => null,
+ };
- Assert.False(parseFailed);
- Assert.Equal(ServiceStartupType.AutomaticDelayedStart, result);
+ return (true, expected, (type & 0x10) != 0);
}
[Fact]
- public void ParseScStartType_EmptyOutput_ReturnsParseFailed()
+ public async Task GetStartupTypeAsync_MatchesRegistryGroundTruth_SampledAcrossTypes()
{
- var (result, parseFailed) = ServiceProcessService.ParseScStartType("");
-
- Assert.True(parseFailed);
- Assert.Null(result);
- }
+ using var services = Registry.LocalMachine.OpenSubKey(@"SYSTEM\CurrentControlSet\Services");
+ Assert.NotNull(services);
- // =============================================
- // Integration tests: GetStartupTypeAsync (real sc.exe)
- // =============================================
-
- [Fact]
- public async Task GetStartupTypeAsync_ExistingAutoService_ReturnsAutomatic()
- {
- var (result, notFound) = await ServiceProcessService.GetStartupTypeAsync("Audiosrv");
+ // Nullable value types cannot be Dictionary keys, so buckets are a list of pairs.
+ var buckets = new List<(ServiceStartupType? Expected, List<string> Names)>
+ {
+ (ServiceStartupType.Automatic, []),
+ (ServiceStartupType.AutomaticDelayedStart, []),
+ (ServiceStartupType.Manual, []),
+ (ServiceStartupType.Disabled, []),
+ };
- Assert.False(notFound);
- Assert.NotNull(result);
- Assert.Equal(ServiceStartupType.Automatic, result);
- }
+ foreach (var name in services!.GetSubKeyNames())
+ {
+ var (found, expected, _) = ReadRegistryTruth(services, name);
+ if (!found || expected is null)
+ continue;
- [Fact]
- public async Task GetStartupTypeAsync_ExistingDemandService_ReturnsManual()
- {
- var (result, notFound) = await ServiceProcessService.GetStartupTypeAsync("msiserver");
+ var bucket = buckets.First(b => b.Expected == expected).Names;
+ if (bucket.Count < PerTypeSampleLimit)
+ bucket.Add(name);
+ }
- Assert.False(notFound);
- Assert.NotNull(result);
- Assert.Equal(ServiceStartupType.Manual, result);
- }
+ var checkedNames = 0;
+ foreach (var (expected, names) in buckets)
+ {
+ foreach (var name in names)
+ {
+ var (actual, notFound) = await ServiceProcessService.GetStartupTypeAsync(name);
+
+ Assert.False(
+ notFound,
+ $"'{name}' has an ImagePath in the registry but was reported as not found"
+ );
+ Assert.Equal(expected, actual);
+ checkedNames++;
+ }
+ }
- [Fact]
- public async Task GetStartupTypeAsync_NonexistentService_ReturnsNotFound()
- {
- var (_, notFound) = await ServiceProcessService.GetStartupTypeAsync(
- "OptimizerDuckTest_Nonexistent_Service_12345"
+ Assert.True(checkedNames > 0, "no service could be sampled from the registry");
+ Assert.True(
+ buckets.Count(b => b.Expected is not null && b.Names.Count > 0) >= 2,
+ $"expected at least two startup types on this machine, sampled {checkedNames} services"
);
-
- Assert.True(notFound);
}
// =============================================
- // Integration tests: ChangeServiceStartupTypeAsync (real sc.exe)
+ // Integration tests: ChangeServiceStartupTypeAsync (real service, SCM writes).
+ // sc.exe stays in this file only to create/inspect the scratch test service.
// =============================================
private const string TestServiceName = "odTestSvc";
@@ -389,16 +300,70 @@ public class ServiceProcessServiceTests
[Fact]
public async Task ChangeServiceStartupTypeAsync_NonexistentService_ReturnsNotFound()
{
+ var call = NewCall();
var result = await ServiceProcessService.ChangeServiceStartupTypeAsync(
- NewCall(),
+ call,
new ServiceItem(
"OptimizerDuckTest_Nonexistent_Service_12345",
ServiceStartupType.Manual
)
);
- // NotFound maps to informational success (Ok).
+ // NotFound maps to informational success (Ok), and there is nothing to revert.
Assert.True(result.Ok, result.Error);
+ Assert.Null(Assert.Single(call.Changes.Changes).Revert);
+ }
+
+ [Fact]
+ public async Task ChangeServiceStartupTypeAsync_AllFourTypes_RoundTripThroughRead()
+ {
+ if (!IsElevated())
+ Assert.Skip("Service creation requires an elevated test host.");
+ await EnsureTestServiceAsync();
+ try
+ {
+ // Automatic runs first because the scratch service is created without a delayed
+ // flag; whether sc.exe (or a later SCM write) clears that flag when moving back to
+ // plain automatic is a real behaviour worth pinning separately, and this order
+ // does not depend on the answer.
+ var previousType = ServiceStartupType.Manual;
+
+ foreach (
+ var target in new[]
+ {
+ ServiceStartupType.Automatic,
+ ServiceStartupType.Manual,
+ ServiceStartupType.Disabled,
+ ServiceStartupType.AutomaticDelayedStart,
+ }
+ )
+ {
+ var call = NewCall();
+ var result = await ServiceProcessService.ChangeServiceStartupTypeAsync(
+ call,
+ new ServiceItem(TestServiceName, target)
+ );
+ Assert.True(result.Ok, $"{target}: {result.Error}");
+
+ // The recorded step must carry the type Windows reported before the write, or a
+ // revert cannot restore it. The scratch service starts as demand (Manual).
+ var revert = Assert.IsType<ServiceRevertStep>(
+ Assert.Single(call.Changes.Changes).Revert
+ );
+ Assert.Equal(previousType, revert.OriginalStartupType);
+ previousType = target;
+
+ var (readBack, notFound) = await ServiceProcessService.GetStartupTypeAsync(
+ TestServiceName
+ );
+ Assert.False(notFound, $"{target}: service reported as not found after the write");
+ Assert.Equal(target, readBack);
+ }
+ }
+ finally
+ {
+ await DeleteTestServiceBestEffortAsync();
+ }
}
[Fact]
diff --git a/optimizerDuck.Test/Services/OptimizationServices/UsbPowerServiceTests.cs b/optimizerDuck.Test/Services/OptimizationServices/UsbPowerServiceTests.cs
new file mode 100644
index 0000000..8a4fe79
--- /dev/null
+++ b/optimizerDuck.Test/Services/OptimizationServices/UsbPowerServiceTests.cs
@@ -0,0 +1,57 @@
+using optimizerDuck.Services.System.Primitives;
+
+namespace optimizerDuck.Test.Services.OptimizationServices;
+
+/// <summary>
+/// Live <c>root\wmi</c> tests. Reads only: no test here flips a real device's power setting,
+/// because that is a system change (task 6.4 compares against the PowerShell oracle instead).
+/// </summary>
+public class UsbPowerServiceTests
+{
+ [Fact]
+ public void Capture_ReturnsOnlyRootHubDevices()
+ {
+ var captured = UsbPowerService.Capture();
+
+ Assert.All(
+ captured,
+ state =>
+ Assert.Contains(@"USB\ROOT", state.InstanceName, StringComparison.OrdinalIgnoreCase)
+ );
+ }
+
+ [Fact]
+ public void Capture_IsStableAcrossCalls()
+ {
+ var first = UsbPowerService.Capture();
+ var second = UsbPowerService.Capture();
+
+ Assert.Equal(
+ first.Select(s => s.InstanceName).OrderBy(n => n, StringComparer.OrdinalIgnoreCase),
+ second.Select(s => s.InstanceName).OrderBy(n => n, StringComparer.OrdinalIgnoreCase)
+ );
+ }
+
+ [Fact]
+ public void Restore_WithNothingCaptured_ChangesNothing()
+ {
+ // The write loop skips every device when the captured set is empty, so this exercises the
+ // "only flip devices that differ" rule without touching a single device.
+ var result = UsbPowerService.Restore([]);
+
+ Assert.NotNull(result);
+ Assert.Equal(0, result.ChangedCount);
+ }
+
+ [Fact]
+ public void Capture_ThenRestore_OfCapturedState_WouldBeANoOp()
+ {
+ // Feeding back exactly what Windows reports must ask for no change at all.
+ var captured = UsbPowerService.Capture();
+
+ var result = UsbPowerService.Restore(captured);
+
+ Assert.NotNull(result);
+ Assert.Equal(0, result.ChangedCount);
+ }
+}
diff --git a/optimizerDuck.Test/Services/PowerPlanIntegrationTests.cs b/optimizerDuck.Test/Services/PowerPlanIntegrationTests.cs
index e09d021..6d73cb4 100644
--- a/optimizerDuck.Test/Services/PowerPlanIntegrationTests.cs
+++ b/optimizerDuck.Test/Services/PowerPlanIntegrationTests.cs
@@ -63,6 +63,54 @@ public class PowerPlanIntegrationTests
Assert.NotNull(settings);
}
+ /// <summary>
+ /// Pins the range-vs-indexed decision against real powrprof metadata. Maximum processor
+ /// state is a range (0-100); System cooling policy is an indexed list. Both live in
+ /// SUB_PROCESSOR, which every Windows 10/11 installation exposes.
+ /// </summary>
+ [Theory]
+ [InlineData(
+ "54533251-82be-4824-96c1-47b60b740d00",
+ "bc5038f7-23e0-4960-96da-33abaf5935ec",
+ PowerValueKind.Range
+ )]
+ [InlineData(
+ "54533251-82be-4824-96c1-47b60b740d00",
+ "94d3a615-a899-4ac5-ae2b-e4d8f634367f",
+ PowerValueKind.Indexed
+ )]
+ public void GetSetting_KnownRangeAndIndexedSettings_ReportDocumentedKind(
+ string subgroupId,
+ string settingId,
+ PowerValueKind expectedKind
+ )
+ {
+ var service = new PowerPlanService(NullLogger<PowerPlanService>.Instance);
+ var activeId = service.GetActiveSchemeId();
+ Assert.NotNull(activeId);
+
+ var setting = service.GetSetting(
+ activeId.Value,
+ Guid.Parse(subgroupId),
+ Guid.Parse(settingId)
+ );
+
+ Assert.NotNull(setting);
+ Assert.Equal(expectedKind, setting.Kind);
+
+ if (expectedKind == PowerValueKind.Range)
+ {
+ Assert.NotNull(setting.MinValue);
+ Assert.NotNull(setting.MaxValue);
+ Assert.NotNull(setting.Increment);
+ }
+ else
+ {
+ Assert.NotNull(setting.PossibleValues);
+ Assert.NotEmpty(setting.PossibleValues!);
+ }
+ }
+
[Fact]
public void SettingValue_RoundTrip_RestoresExactValues()
{
diff --git a/optimizerDuck.Test/Services/SystemInfoServiceTests.cs b/optimizerDuck.Test/Services/SystemInfoServiceTests.cs
index e47f56d..81e3a4c 100644
--- a/optimizerDuck.Test/Services/SystemInfoServiceTests.cs
+++ b/optimizerDuck.Test/Services/SystemInfoServiceTests.cs
@@ -1,3 +1,4 @@
+using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
using optimizerDuck.Services.System;
@@ -23,4 +24,47 @@ public class SystemInfoServiceTests
service.LogSummary();
}
+
+ [Fact]
+ public async Task LogSummary_ReportsDiskSizeInWholeGigabytes()
+ {
+ var logger = new CapturingLogger<SystemInfoService>();
+ var service = new SystemInfoService(logger);
+
+ await service.RefreshAsync(TestContext.Current.CancellationToken);
+ service.LogSummary();
+
+ var diskLines = logger
+ .Lines.Where(line => line.StartsWith("Disk ", StringComparison.Ordinal))
+ .ToList();
+ if (diskLines.Count == 0)
+ Assert.Skip("This host reports no ready volumes, so there is no disk line to check.");
+
+ // A raw byte double renders as "109.17089462280273 GB"; the summary must show whole
+ // gigabytes. The DoesNotMatch assertion is the one that catches that regression.
+ Assert.All(diskLines, line => Assert.DoesNotMatch(@"\d+\.\d+ GB", line));
+ Assert.All(diskLines, line => Assert.Matches(@"\d+ GB \(free \d+ GB\)", line));
+ }
+
+ /// <summary>
+ /// Hand-written logger double that keeps the rendered messages, so a test can assert on
+ /// what a log line actually says.
+ /// </summary>
+ private sealed class CapturingLogger<T> : ILogger<T>
+ {
+ public List<string> Lines { get; } = [];
+
+ public IDisposable? BeginScope<TState>(TState state)
+ where TState : notnull => null;
+
+ public bool IsEnabled(LogLevel logLevel) => true;
+
+ public void Log<TState>(
+ LogLevel logLevel,
+ EventId eventId,
+ TState state,
+ Exception? exception,
+ Func<TState, Exception?, string> formatter
+ ) => Lines.Add(formatter(state, exception));
+ }
}
diff --git a/optimizerDuck.Test/Services/SystemRestoreServiceTests.cs b/optimizerDuck.Test/Services/SystemRestoreServiceTests.cs
new file mode 100644
index 0000000..8af6c8f
--- /dev/null
+++ b/optimizerDuck.Test/Services/SystemRestoreServiceTests.cs
@@ -0,0 +1,171 @@
+using Microsoft.Extensions.Logging.Abstractions;
+using optimizerDuck.Services.System;
+
+namespace optimizerDuck.Test.Services;
+
+/// <summary>
+/// System Restore decisions with hand-doubled results. Classification takes status codes only
+/// (never message text, which is localizable) and the throttle takes the documented setting plus
+/// the newest existing point. The live create/enable round trip needs elevation, so the virtual
+/// members are driven through a hand-written double - the same seam a restore-point manager tool
+/// would use.
+/// </summary>
+public class SystemRestoreServiceTests
+{
+ private static readonly DateTime Now = new(2026, 9, 14, 12, 0, 0, DateTimeKind.Utc);
+
+ private sealed class FakeSystemRestoreService : SystemRestoreService
+ {
+ public FakeSystemRestoreService()
+ : base(NullLogger<SystemRestoreService>.Instance) { }
+
+ public IReadOnlyList<RestorePointInfo> Points { get; init; } = [];
+
+ public int FrequencyMinutes { get; init; } = DefaultCreationFrequencyMinutes;
+
+ public SystemRestoreResult CreateResult { get; init; } = new(true, 0);
+
+ public SystemRestoreResult EnableResult { get; init; } = new(true, 0);
+
+ public string? EnabledDrive { get; private set; }
+
+ public override IReadOnlyList<RestorePointInfo> ListRestorePoints() => Points;
+
+ public override int GetCreationFrequencyMinutes() => FrequencyMinutes;
+
+ public override SystemRestoreResult CreateRestorePoint(
+ string description,
+ uint restorePointType = RestorePointTypeModifySettings,
+ uint eventType = EventTypeBeginSystemChange
+ ) => CreateResult;
+
+ public override SystemRestoreResult EnableProtection(string drive)
+ {
+ EnabledDrive = drive;
+ return EnableResult;
+ }
+ }
+
+ [Fact]
+ public void IsWithinCreationThrottle_PointInsideWindow_IsThrottled()
+ {
+ Assert.True(
+ SystemRestoreService.IsWithinCreationThrottle(
+ SystemRestoreService.DefaultCreationFrequencyMinutes,
+ Now.AddHours(-1),
+ Now
+ )
+ );
+ }
+
+ [Fact]
+ public void IsWithinCreationThrottle_PointOutsideWindow_IsNotThrottled()
+ {
+ Assert.False(
+ SystemRestoreService.IsWithinCreationThrottle(
+ SystemRestoreService.DefaultCreationFrequencyMinutes,
+ Now.AddHours(-25),
+ Now
+ )
+ );
+ }
+
+ [Fact]
+ public void IsWithinCreationThrottle_ExactlyAtBoundary_IsNotThrottled()
+ {
+ // Windows skips only points created strictly inside the window.
+ Assert.False(SystemRestoreService.IsWithinCreationThrottle(60, Now.AddMinutes(-60), Now));
+ }
+
+ [Fact]
+ public void IsWithinCreationThrottle_FrequencyZero_NeverSkips()
+ {
+ Assert.False(SystemRestoreService.IsWithinCreationThrottle(0, Now.AddSeconds(-1), Now));
+ }
+
+ [Fact]
+ public void IsWithinCreationThrottle_UnknownNewestPoint_FailsOpen()
+ {
+ Assert.False(SystemRestoreService.IsWithinCreationThrottle(1440, null, Now));
+ }
+
+ [Fact]
+ public void DefaultCreationFrequencyMinutes_IsTheDocumentedTwentyFourHours()
+ {
+ Assert.Equal(1440, SystemRestoreService.DefaultCreationFrequencyMinutes);
+ }
+
+ [Theory]
+ [InlineData(0u, false)] // success
+ [InlineData(1058u, true)] // ERROR_SERVICE_DISABLED
+ [InlineData(0x80070422u, true)] // HRESULT_FROM_WIN32(ERROR_SERVICE_DISABLED)
+ [InlineData(5u, false)] // ERROR_ACCESS_DENIED: a refusal, not "protection off"
+ [InlineData(0x80070005u, false)] // E_ACCESSDENIED
+ [InlineData(uint.MaxValue, false)] // the interop threw
+ public void IsProtectionDisabledStatus_OnlyMatchesTheDisabledCodes(uint status, bool expected)
+ {
+ Assert.Equal(expected, SystemRestoreService.IsProtectionDisabledStatus(status));
+ }
+
+ [Fact]
+ public void IsWithinCreationThrottle_ThroughTheDouble_SeesTheReportedPointsAndSetting()
+ {
+ var service = new FakeSystemRestoreService
+ {
+ FrequencyMinutes = 1440,
+ Points = [new SystemRestoreService.RestorePointInfo(7, 12, "recent", Now.AddHours(-1))],
+ };
+
+ Assert.True(service.IsWithinCreationThrottle(Now));
+ Assert.Equal(Now.AddHours(-1), service.GetNewestRestorePointUtc());
+ }
+
+ [Fact]
+ public void IsWithinCreationThrottle_FrequencyZeroThroughTheDouble_IsNotThrottled()
+ {
+ var service = new FakeSystemRestoreService
+ {
+ FrequencyMinutes = 0,
+ Points = [new SystemRestoreService.RestorePointInfo(7, 12, "just now", Now.AddSeconds(-30))],
+ };
+
+ Assert.False(service.IsWithinCreationThrottle(Now));
+ }
+
+ [Fact]
+ public void IsWithinCreationThrottle_NoReadablePoints_FailsOpen()
+ {
+ var service = new FakeSystemRestoreService { FrequencyMinutes = 1440, Points = [] };
+
+ Assert.False(service.IsWithinCreationThrottle(Now));
+ }
+
+ [Fact]
+ public void CreateRestorePoint_SurfacesTheNativeStatusUnchanged()
+ {
+ var service = new FakeSystemRestoreService
+ {
+ CreateResult = new SystemRestoreService.SystemRestoreResult(
+ false,
+ SystemRestoreService.ErrorServiceDisabled
+ ),
+ };
+
+ var result = service.CreateRestorePoint("optimizerDuck");
+
+ Assert.False(result.Succeeded);
+ Assert.Equal(SystemRestoreService.ErrorServiceDisabled, result.NativeStatus);
+ Assert.True(SystemRestoreService.IsProtectionDisabledStatus(result.NativeStatus));
+ }
+
+ [Fact]
+ public void EnableProtection_PassesTheDriveThrough()
+ {
+ var service = new FakeSystemRestoreService();
+
+ var result = service.EnableProtection("C:");
+
+ Assert.True(result.Succeeded);
+ Assert.Equal("C:", service.EnabledDrive);
+ }
+}
diff --git a/optimizerDuck.Test/Services/UI/DiskCleanupServiceTests.cs b/optimizerDuck.Test/Services/UI/DiskCleanupServiceTests.cs
index 80ca571..05efe71 100644
--- a/optimizerDuck.Test/Services/UI/DiskCleanupServiceTests.cs
+++ b/optimizerDuck.Test/Services/UI/DiskCleanupServiceTests.cs
@@ -8,11 +8,7 @@ namespace optimizerDuck.Test.Services.UI;
public class DiskCleanupServiceTests
{
- private static DiskCleanupService NewService() =>
- new(
- NullLogger<DiskCleanupService>.Instance,
- new ShellService(new ProcessRunner(120000, NullLogger<ProcessRunner>.Instance))
- );
+ private static DiskCleanupService NewService() => new(NullLogger<DiskCleanupService>.Instance);
[Fact]
public async Task CleanAsync_DoesNotDeleteFilesInDotNetDirectory()
@@ -123,19 +119,37 @@ public class DiskCleanupServiceTests
}
[Fact]
- public async Task CleanAsync_FailingCommand_ReportsNoFreedBytes()
+ public void GetCleanupItems_RecycleBinItem_HasNoCommandPath()
{
- var service = NewService();
- var item = new CleanupItem
+ var item = DiskCleanupService.GetCleanupItems().Single(i => i.Id == "RecycleBin");
+
+ // Still flagged as "not a directory", but the PowerShell command is gone: size and
+ // emptying now come from the shell Recycle Bin APIs.
+ Assert.True(item.IsCommand);
+ Assert.Empty(item.Path);
+ Assert.False(item.CanOpenFolder);
+ }
+
+ [Fact]
+ public async Task CleanAsync_RecycleBinItem_ReportsNoFreedBytesForAnEmptyBin()
+ {
+ // The failing-empty half of the contract lives in RecycleBinServiceTests
+ // (Empty_InvalidRoot_FailsWithError): DiskCleanupService always empties every drive, so a
+ // failure cannot be forced here without either destroying real data or adding a
+ // test-only seam to the service.
+ var totals = RecycleBinService.Query();
+ if (totals.ItemCount != 0)
{
- Id = "Command",
- NameKey = "Temp Files",
- DescriptionKey = "Temp Description",
- Path = "exit 1",
- Icon = SymbolRegular.Document24,
- IsCommand = true,
- SizeBytes = 4096,
- };
+ Assert.Skip(
+ $"Recycle Bin holds {totals.ItemCount} item(s); emptying it here would destroy real user data, so this test only runs on an empty bin."
+ );
+ }
+
+ var service = NewService();
+ var item = DiskCleanupService.GetCleanupItems().Single(i => i.Id == "RecycleBin");
+
+ await service.ScanAsync(item);
+ Assert.Equal(0, item.SizeBytes);
var freed = await service.CleanAsync(item);
diff --git a/optimizerDuck/ApplicationServiceCollectionExtensions.cs b/optimizerDuck/ApplicationServiceCollectionExtensions.cs
index acb6bab..ac89741 100644
--- a/optimizerDuck/ApplicationServiceCollectionExtensions.cs
+++ b/optimizerDuck/ApplicationServiceCollectionExtensions.cs
@@ -93,6 +93,7 @@ public static class ApplicationServiceCollectionExtensions
// Services
services.AddSingleton<ProcessRunner>();
services.AddSingleton<PowerPlanService>();
+ services.AddSingleton<SystemRestoreService>();
services.AddSingleton<ShellService>();
services.AddSingleton<RevertManager>();
services.AddSingleton<OptimizationRegistry>();
diff --git a/optimizerDuck/Common/Helpers/SystemRefreshService.cs b/optimizerDuck/Common/Helpers/SystemRefreshService.cs
index 28b716f..1ccc7c7 100644
--- a/optimizerDuck/Common/Helpers/SystemRefreshService.cs
+++ b/optimizerDuck/Common/Helpers/SystemRefreshService.cs
@@ -17,9 +17,6 @@ internal static class SystemRefreshService
out IntPtr lpdwResult
);
- [DllImport("user32.dll", CharSet = CharSet.Unicode)]
- private static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);
-
[DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
private static extern IntPtr FindWindow(string? lpClassName, string? lpWindowName);
@@ -72,6 +69,7 @@ internal static class SystemRefreshService
private const uint WM_THEMECHANGED = 0x031A;
private const uint WM_COMMAND = 0x0111;
private const uint SMTO_ABORTIFHUNG = 0x0002;
+ private const uint NotifyTimeoutMs = 100;
private const uint SHCNE_ASSOCCHANGED = 0x08000000;
private const uint SHCNF_IDLIST = 0x0000;
@@ -130,14 +128,26 @@ internal static class SystemRefreshService
foreach (var listView in EnumerateDesktopListViews())
{
- SendMessage(listView, LVM_REFRESH, IntPtr.Zero, IntPtr.Zero);
- SendMessage(listView, LVM_UPDATE, IntPtr.Zero, IntPtr.Zero);
+ Notify(listView, LVM_REFRESH, IntPtr.Zero);
+ Notify(listView, LVM_UPDATE, IntPtr.Zero);
InvalidateRect(listView, IntPtr.Zero, true);
UpdateWindow(listView);
}
}
+ /// <summary>
+ /// Fire-and-forget message to a window that may belong to another process. Plain
+ /// <c>SendMessage</c> blocks until the receiver processes the message, which Microsoft
+ /// documents as a deadlock risk when that receiver is hung or exiting (Explorer here), so
+ /// this uses the timeout-bounded variant and treats a timeout or missing window as a
+ /// no-op. <paramref name="lParam" /> is always null: these messages carry no string.
+ /// </summary>
+ internal static void Notify(IntPtr hWnd, uint message, IntPtr wParam)
+ {
+ SendMessageTimeout(hWnd, message, wParam, null, SMTO_ABORTIFHUNG, NotifyTimeoutMs, out _);
+ }
+
public static void SetDesktopIconsVisible(bool showIcons)
{
var defView = FindDesktopDefView();
@@ -148,7 +158,7 @@ internal static class SystemRefreshService
var currentlyVisible = listView != IntPtr.Zero && IsWindowVisible(listView);
if (currentlyVisible != showIcons)
- SendMessage(defView, WM_COMMAND, TOGGLE_DESKTOP_ICONS, IntPtr.Zero);
+ Notify(defView, WM_COMMAND, TOGGLE_DESKTOP_ICONS);
SHChangeNotify(SHCNE_ASSOCCHANGED, SHCNF_IDLIST, IntPtr.Zero, IntPtr.Zero);
}
diff --git a/optimizerDuck/Domain/Optimizations/Categories/PowerManagement.cs b/optimizerDuck/Domain/Optimizations/Categories/PowerManagement.cs
index 0c471db..38c9ec9 100644
--- a/optimizerDuck/Domain/Optimizations/Categories/PowerManagement.cs
+++ b/optimizerDuck/Domain/Optimizations/Categories/PowerManagement.cs
@@ -7,6 +7,7 @@ using optimizerDuck.Common.Extensions;
using optimizerDuck.Common.Helpers;
using optimizerDuck.Domain.Abstractions;
using optimizerDuck.Domain.Attributes;
+using optimizerDuck.Domain.Execution;
using optimizerDuck.Domain.Optimizations.Models;
using optimizerDuck.Domain.Optimizations.Models.Services;
using optimizerDuck.Domain.Revert.Steps;
@@ -33,37 +34,59 @@ public class PowerManagement : LocalizedObject, IOptimizationCategory
)]
public class DisableHibernateAndFastStartup : BaseOptimization
{
- public override async Task<ApplyResult> ApplyAsync(
+ public override Task<ApplyResult> ApplyAsync(
IProgress<ProcessingProgress> progress,
OptimizationContext context
)
{
- var hibernateItem = new RegistryItem(
- @"HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Power",
- "HibernateEnabled"
- );
+ // Fail-safe: when the previous state cannot be read, revert restores hibernation.
+ var wasPresent = HibernationService.IsHibernationFilePresent() ?? true;
- // default to restoring hibernation on when the previous state is unknown.
- var wasEnabled = true;
- if (RegistryService.TryReadValue(hibernateItem, out var hibernateValue, context.Logger))
- wasEnabled = hibernateValue switch
- {
- null => true,
- int value => value != 0,
- long value => value != 0,
- string value => value != "0",
- _ => true,
- };
+ Apply(context, wasPresent);
- string revertCommand = wasEnabled ? "powercfg /h on" : "powercfg /h off";
+ return Task.FromResult(context.Changes.ToApplyResult());
+ }
+
+ private static OpResult Apply(OpCall call, bool wasPresent)
+ {
+ var result = HibernationService.SetHibernationFile(present: false);
+ var revert = new HibernationRevertStep { WasPresent = wasPresent };
- await context.Shell.CMDAsync("powercfg /h off", context, revertCommand);
+ if (result.Succeeded)
+ {
+ call.Changes.Add(
+ ServiceStrings.HibernationName,
+ ServiceStrings.HibernationDescriptionDisable,
+ true,
+ revert
+ );
+ call.Logger.LogInformation(
+ "Disabled hibernation and Fast Startup. Previous state: {State}",
+ wasPresent ? "Enabled" : "Disabled"
+ );
+ return OpResult.Success(revert);
+ }
- context.Logger.LogInformation(
- "Disabled hibernation and Fast Startup. Previous state: {State}",
- wasEnabled ? "Enabled" : "Disabled"
+ // A refused transition fails the same way on a retry (it needs privileges), but the
+ // retry keeps the recorded step consistent with the other providers.
+ var error = ServiceStrings.Format(
+ ServiceStrings.HibernationErrorChangeFailed,
+ $"0x{result.NativeStatus:X8}"
);
- return context.Changes.ToApplyResult();
+ call.Logger.LogWarning(
+ "[HIBERNATION][FAIL] NTSTATUS 0x{Status:X8}",
+ result.NativeStatus
+ );
+ call.Changes.Add(
+ ServiceStrings.HibernationName,
+ ServiceStrings.HibernationDescriptionDisable,
+ false,
+ null,
+ error,
+ result.ExceptionText,
+ retryCall => Task.FromResult(Apply(retryCall, wasPresent))
+ );
+ return OpResult.Fail(error, result.ExceptionText);
}
}
@@ -74,73 +97,72 @@ public class PowerManagement : LocalizedObject, IOptimizationCategory
)]
public class DisableUSBPowerSaving : BaseOptimization
{
- public override async Task<ApplyResult> ApplyAsync(
+ public override Task<ApplyResult> ApplyAsync(
IProgress<ProcessingProgress> progress,
OptimizationContext context
)
{
context.Logger.LogInformation("Saving current USB power state");
- var usbStates = await context.Shell.QueryPowerShellAsync(
- """
- $states = Get-CimInstance -Namespace root\wmi -ClassName MSPower_DeviceEnable -ErrorAction SilentlyContinue |
- Where-Object { $_.InstanceName -match 'USB\\ROOT' } |
- Select-Object InstanceName, Enable
-
- $states | ConvertTo-Json -Compress
- """,
- context.Logger
- );
-
- if (string.IsNullOrWhiteSpace(usbStates.Stdout))
+ var captured = UsbPowerService.Capture();
+ if (captured.Count == 0)
{
context.Logger.LogInformation("No USB devices found, skipping");
- return ApplyResult.True();
+ return Task.FromResult(ApplyResult.True());
}
- var capturedStates = ParseUsbPowerStates(usbStates.Stdout);
- if (capturedStates.Count == 0)
+ context.Logger.LogInformation("Disabling USB power saving");
+ var revertStep = new UsbPowerRevertStep
{
- context.Logger.LogInformation("No USB device states parsed, skipping");
- return ApplyResult.True();
- }
+ States = captured
+ .Select(static state => new UsbPowerRevertStep.DeviceState
+ {
+ InstanceName = state.InstanceName,
+ Enable = state.Enable,
+ })
+ .ToList(),
+ };
- context.Logger.LogInformation("Disabling USB power saving");
- var revertStep = new UsbPowerRevertStep { States = capturedStates };
- var disableOp = await context.Shell.PowerShellAsync(
- """
- $devices = Get-CimInstance -Namespace root\wmi -ClassName MSPower_DeviceEnable -ErrorAction SilentlyContinue |
- Where-Object { $_.InstanceName -match 'USB\\ROOT' }
-
- foreach ($d in $devices) {
- if ($d.Enable -ne $false) {
- Set-CimInstance -CimInstance $d -Property @{ Enable = $false } | Out-Null
- }
- }
- """,
- context,
- revertStep
- );
- var ok = disableOp.Ok;
+ Apply(context, revertStep, UsbPowerService.Disable());
- return context.Changes.ToApplyResult();
+ return Task.FromResult(context.Changes.ToApplyResult());
}
- private static List<UsbPowerRevertStep.DeviceState> ParseUsbPowerStates(string stdout)
+ private static OpResult Apply(
+ OpCall call,
+ UsbPowerRevertStep revertStep,
+ UsbPowerService.UsbPowerWriteResult? result
+ )
{
- try
- {
- var token = JToken.Parse(stdout.Trim());
- return token switch
- {
- JArray array => array.ToObject<List<UsbPowerRevertStep.DeviceState>>() ?? [],
- JObject obj => [obj.ToObject<UsbPowerRevertStep.DeviceState>()!],
- _ => [],
- };
- }
- catch (JsonException)
+ var description = ServiceStrings.Format(
+ ServiceStrings.UsbPowerDescriptionDisable,
+ revertStep.States.Count
+ );
+
+ if (result is not null)
{
- return [];
+ call.Changes.Add(ServiceStrings.UsbPowerName, description, true, revertStep);
+ call.Logger.LogInformation(
+ "[USB][OK] power saving disabled, {Count} device(s) changed",
+ result.ChangedCount
+ );
+ return OpResult.Success(revertStep);
}
+
+ // Null means the WMI query itself failed (class unavailable or the write was refused),
+ // which is the one case the old exit-code check also treated as a failure.
+ var error = ServiceStrings.UsbPowerErrorChangeFailed;
+ call.Logger.LogWarning("[USB][FAIL] WMI write refused or unavailable");
+ call.Changes.Add(
+ ServiceStrings.UsbPowerName,
+ description,
+ false,
+ null,
+ error,
+ null,
+ retryCall =>
+ Task.FromResult(Apply(retryCall, revertStep, UsbPowerService.Disable()))
+ );
+ return OpResult.Fail(error, null);
}
}
diff --git a/optimizerDuck/Domain/Revert/Steps/HibernationRevertStep.cs b/optimizerDuck/Domain/Revert/Steps/HibernationRevertStep.cs
new file mode 100644
index 0000000..4066ee6
--- /dev/null
+++ b/optimizerDuck/Domain/Revert/Steps/HibernationRevertStep.cs
@@ -0,0 +1,69 @@
+using Microsoft.Extensions.Logging;
+using Newtonsoft.Json.Linq;
+using optimizerDuck.Domain.Abstractions;
+using optimizerDuck.Domain.Exceptions;
+using optimizerDuck.Resources.Languages;
+using optimizerDuck.Services.Configuration;
+using optimizerDuck.Services.System.Primitives;
+
+namespace optimizerDuck.Domain.Revert.Steps;
+
+/// <summary>
+/// Restores the hibernation file state captured before it was removed, through the documented
+/// power information callback instead of a <c>powercfg /h</c> shell command.
+/// </summary>
+public class HibernationRevertStep : IRevertStep
+{
+ /// <summary>
+ /// Gets or sets a value that indicates whether the hibernation file existed before the
+ /// change, so reverting commits it back.
+ /// </summary>
+ public bool WasPresent { get; set; }
+
+ /// <inheritdoc />
+ public string Type => "Hibernation";
+
+ /// <inheritdoc />
+ public string Description => Loc.Instance["Revert.Hibernation.Description"];
+
+ /// <inheritdoc />
+ public Task<bool> ExecuteAsync(RevertContext context, ILogger logger)
+ {
+ var result = HibernationService.SetHibernationFile(WasPresent);
+
+ if (!result.Succeeded)
+ {
+ var error =
+ result.ExceptionText
+ ?? Loc.Instance[
+ "Revert.Hibernation.Error.RestoreFailed",
+ $"0x{result.NativeStatus:X8}"
+ ];
+ logger.LogWarning(
+ "[HIBERNATION][REVERT][FAIL] NTSTATUS 0x{Status:X8}",
+ result.NativeStatus
+ );
+ throw new StepExecutionException(error, result.ExceptionText ?? string.Empty);
+ }
+
+ return Task.FromResult(true);
+ }
+
+ /// <inheritdoc />
+ public JObject ToData()
+ {
+ return new JObject { [nameof(WasPresent)] = WasPresent };
+ }
+
+ /// <summary>
+ /// Deserializes a <see cref="HibernationRevertStep" /> from JSON data. Defaults to
+ /// "was present" when the flag is missing, matching the optimization's fail-safe default.
+ /// </summary>
+ public static HibernationRevertStep FromData(JObject data)
+ {
+ return new HibernationRevertStep
+ {
+ WasPresent = data[nameof(WasPresent)]?.Value<bool>() ?? true,
+ };
+ }
+}
diff --git a/optimizerDuck/Domain/Revert/Steps/UsbPowerRevertStep.cs b/optimizerDuck/Domain/Revert/Steps/UsbPowerRevertStep.cs
index eccc966..4565a9d 100644
--- a/optimizerDuck/Domain/Revert/Steps/UsbPowerRevertStep.cs
+++ b/optimizerDuck/Domain/Revert/Steps/UsbPowerRevertStep.cs
@@ -1,10 +1,7 @@
-using System.Text;
using Microsoft.Extensions.Logging;
-using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using optimizerDuck.Domain.Abstractions;
using optimizerDuck.Domain.Exceptions;
-using optimizerDuck.Resources.Languages;
using optimizerDuck.Services.Configuration;
using optimizerDuck.Services.System.Primitives;
@@ -43,38 +40,30 @@ public class UsbPowerRevertStep : IRevertStep
public string Description => Loc.Instance["Revert.UsbPower.Description"];
/// <inheritdoc />
- public async Task<bool> ExecuteAsync(RevertContext context, ILogger logger)
+ public Task<bool> ExecuteAsync(RevertContext context, ILogger logger)
{
if (States.Count == 0)
- return true;
+ return Task.FromResult(true);
- var payload = Convert.ToBase64String(
- Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(States))
- );
+ var captured = States
+ .Select(static state => new UsbPowerService.UsbPowerState(
+ state.InstanceName,
+ state.Enable
+ ))
+ .ToList();
- var script =
- "$json = [System.Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('"
- + payload
- + "')); "
- + "$states = $json | ConvertFrom-Json; "
- + "foreach ($s in $states) { "
- + "$obj = Get-CimInstance -Namespace root\\wmi -ClassName MSPower_DeviceEnable -ErrorAction SilentlyContinue | "
- + "Where-Object { $_.InstanceName -eq $s.InstanceName }; "
- + "if ($obj -and $obj.Enable -ne [bool]$s.Enable) { "
- + "Set-CimInstance -CimInstance $obj -Property @{ Enable = [bool]$s.Enable } | Out-Null "
- + "}}";
+ var result = UsbPowerService.Restore(captured);
- var result = await context.Shell.QueryPowerShellAsync(script, logger).ConfigureAwait(false);
-
- if (result.ExitCode != 0)
+ if (result is null)
{
- var error = !string.IsNullOrWhiteSpace(result.Stderr)
- ? result.Stderr
- : Loc.Instance["Revert.UsbPower.Error.CommandFailed", result.ExitCode];
- throw new StepExecutionException(error, result.Stderr);
+ logger.LogWarning("[USB][REVERT][FAIL] WMI restore refused or unavailable");
+ throw new StepExecutionException(
+ Loc.Instance["Revert.UsbPower.Error.RestoreFailed"],
+ string.Empty
+ );
}
- return true;
+ return Task.FromResult(true);
}
/// <inheritdoc />
diff --git a/optimizerDuck/Resources/Languages/Translations.ar-SA.resx b/optimizerDuck/Resources/Languages/Translations.ar-SA.resx
index 65e73c7..61ce9bf 100644
--- a/optimizerDuck/Resources/Languages/Translations.ar-SA.resx
+++ b/optimizerDuck/Resources/Languages/Translations.ar-SA.resx
@@ -1442,8 +1442,14 @@
<data name="Revert.UsbPower.Description" xml:space="preserve">
<value>استعادة حالات طاقة التعليق الانتقائي لمنافذ ‎USB‎</value>
</data>
- <data name="Revert.UsbPower.Error.CommandFailed" xml:space="preserve">
- <value>فشل التراجع عن طاقة ‎USB‎ برمز خروج {0}</value>
+ <data name="Revert.Hibernation.Description" xml:space="preserve">
+ <value>استعادة حالة السكون</value>
+ </data>
+ <data name="Revert.Hibernation.Error.RestoreFailed" xml:space="preserve">
+ <value>تعذّر استعادة السكون: {0}</value>
+ </data>
+ <data name="Revert.UsbPower.Error.RestoreFailed" xml:space="preserve">
+ <value>تعذّر استعادة حالات طاقة USB</value>
</data>
<data name="ScheduledTasks.Action.Delete" xml:space="preserve">
<value>حذف</value>
diff --git a/optimizerDuck/Resources/Languages/Translations.de-DE.resx b/optimizerDuck/Resources/Languages/Translations.de-DE.resx
index 583adb0..6f44a4d 100644
--- a/optimizerDuck/Resources/Languages/Translations.de-DE.resx
+++ b/optimizerDuck/Resources/Languages/Translations.de-DE.resx
@@ -335,6 +335,12 @@
<data name="Revert.UsbPower.Description" xml:space="preserve">
<value>Energiezustände für selektives USB-Energiesparen wiederherstellen</value>
</data>
+ <data name="Revert.Hibernation.Description" xml:space="preserve">
+ <value>Ruhezustand wiederherstellen</value>
+ </data>
+ <data name="Revert.Hibernation.Error.RestoreFailed" xml:space="preserve">
+ <value>Ruhezustand konnte nicht wiederhergestellt werden: {0}</value>
+ </data>
<data name="Optimization.Apply.Processing" xml:space="preserve">
<value>Änderungen werden angewendet...</value>
</data>
@@ -1464,8 +1470,8 @@ Aktualisiere jetzt, um die neuesten Funktionen, Verbesserungen und Fehlerbehebun
<data name="Revert.Shell.Error.CommandFailed" xml:space="preserve">
<value>Wiederherstellungsbefehl mit Exitcode {0} fehlgeschlagen</value>
</data>
- <data name="Revert.UsbPower.Error.CommandFailed" xml:space="preserve">
- <value>USB-Energiewiederherstellung mit Exitcode {0} fehlgeschlagen</value>
+ <data name="Revert.UsbPower.Error.RestoreFailed" xml:space="preserve">
+ <value>USB-Energiestatus konnte nicht wiederhergestellt werden</value>
</data>
<data name="Settings.Optimize.ShowCompletionNotification.Title" xml:space="preserve">
<value>Abschlussbenachrichtigung anzeigen</value>
diff --git a/optimizerDuck/Resources/Languages/Translations.es-ES.resx b/optimizerDuck/Resources/Languages/Translations.es-ES.resx
index 395110d..3b6a4af 100644
--- a/optimizerDuck/Resources/Languages/Translations.es-ES.resx
+++ b/optimizerDuck/Resources/Languages/Translations.es-ES.resx
@@ -582,6 +582,12 @@
<value>Restaurar estados de energia de suspención selectiva de USB</value>
</data>
+ <data name="Revert.Hibernation.Description" xml:space="preserve">
+ <value>Restaurar el estado de hibernación</value>
+ </data>
+ <data name="Revert.Hibernation.Error.RestoreFailed" xml:space="preserve">
+ <value>No se pudo restaurar la hibernación: {0}</value>
+ </data>
@@ -2820,9 +2826,9 @@ Actualiza ahora para disfrutar de las nuevas funciones y mejoras.</value>
</data>
- <data name="Revert.UsbPower.Error.CommandFailed" xml:space="preserve">
+ <data name="Revert.UsbPower.Error.RestoreFailed" xml:space="preserve">
- <value>La reversión de energía USB falló con código de salida {0}</value>
+ <value>No se pudieron restaurar los estados de energía USB</value>
</data>
diff --git a/optimizerDuck/Resources/Languages/Translations.fr-FR.resx b/optimizerDuck/Resources/Languages/Translations.fr-FR.resx
index bec8a72..4e74c74 100644
--- a/optimizerDuck/Resources/Languages/Translations.fr-FR.resx
+++ b/optimizerDuck/Resources/Languages/Translations.fr-FR.resx
@@ -287,6 +287,12 @@
<data name="Revert.UsbPower.Description" xml:space="preserve">
<value>Restaurer les états d'alimentation de la suspension sélective USB</value>
</data>
+ <data name="Revert.Hibernation.Description" xml:space="preserve">
+ <value>Restaurer l'état de veille prolongée</value>
+ </data>
+ <data name="Revert.Hibernation.Error.RestoreFailed" xml:space="preserve">
+ <value>Échec de la restauration de la veille prolongée : {0}</value>
+ </data>
<data name="Optimization.Apply.Processing" xml:space="preserve">
<value>Application des modifications...</value>
</data>
@@ -1397,8 +1403,8 @@ Mettez à jour maintenant pour profiter des dernières fonctionnalités, amélio
<data name="Revert.Shell.Error.CommandFailed" xml:space="preserve">
<value>La commande de restauration a échoué avec le code de sortie {0}</value>
</data>
- <data name="Revert.UsbPower.Error.CommandFailed" xml:space="preserve">
- <value>La restauration de l'alimentation USB a échoué avec le code de sortie {0}</value>
+ <data name="Revert.UsbPower.Error.RestoreFailed" xml:space="preserve">
+ <value>Échec de la restauration des états d'alimentation USB</value>
</data>
<data name="Settings.Optimize.ShowCompletionNotification.Title" xml:space="preserve">
<value>Afficher la notification de fin</value>
diff --git a/optimizerDuck/Resources/Languages/Translations.he-IL.resx b/optimizerDuck/Resources/Languages/Translations.he-IL.resx
index 5b3f0ed..0b68cf1 100644
--- a/optimizerDuck/Resources/Languages/Translations.he-IL.resx
+++ b/optimizerDuck/Resources/Languages/Translations.he-IL.resx
@@ -335,6 +335,12 @@
<data name="Revert.UsbPower.Description" xml:space="preserve">
<value>שחזור מצבי צריכת החשמל של USB selective suspend</value>
</data>
+ <data name="Revert.Hibernation.Description" xml:space="preserve">
+ <value>שחזור מצב השינה</value>
+ </data>
+ <data name="Revert.Hibernation.Error.RestoreFailed" xml:space="preserve">
+ <value>שחזור השינה נכשל: {0}</value>
+ </data>
<data name="Optimization.Apply.Processing" xml:space="preserve">
<value>מחיל שינויים...</value>
</data>
@@ -1464,8 +1470,8 @@
<data name="Revert.Shell.Error.CommandFailed" xml:space="preserve">
<value>פקודת הביטול נכשלה עם קוד יציאה {0}</value>
</data>
- <data name="Revert.UsbPower.Error.CommandFailed" xml:space="preserve">
- <value>ביטול צריכת החשמל של USB נכשל עם קוד יציאה {0}</value>
+ <data name="Revert.UsbPower.Error.RestoreFailed" xml:space="preserve">
+ <value>שחזור מצבי צריכת החשמל של USB נכשל</value>
</data>
<data name="Settings.Optimize.ShowCompletionNotification.Title" xml:space="preserve">
<value>הצג התראת השלמה</value>
diff --git a/optimizerDuck/Resources/Languages/Translations.id-ID.resx b/optimizerDuck/Resources/Languages/Translations.id-ID.resx
index 67ac75b..d7e5104 100644
--- a/optimizerDuck/Resources/Languages/Translations.id-ID.resx
+++ b/optimizerDuck/Resources/Languages/Translations.id-ID.resx
@@ -329,6 +329,12 @@
<data name="Revert.UsbPower.Description" xml:space="preserve">
<value>Memulihkan status daya suspend selektif USB</value>
</data>
+ <data name="Revert.Hibernation.Description" xml:space="preserve">
+ <value>Pulihkan status hibernasi</value>
+ </data>
+ <data name="Revert.Hibernation.Error.RestoreFailed" xml:space="preserve">
+ <value>Gagal memulihkan hibernasi: {0}</value>
+ </data>
<data name="Optimization.Apply.Processing" xml:space="preserve">
<value>Menerapkan perubahan...</value>
</data>
@@ -1488,8 +1494,8 @@ Perbarui sekarang untuk menikmati fitur terbaru, peningkatan, dan perbaikan bug.
<data name="Revert.Shell.Error.CommandFailed" xml:space="preserve">
<value>Perintah revert gagal dengan kode keluar {0}</value>
</data>
- <data name="Revert.UsbPower.Error.CommandFailed" xml:space="preserve">
- <value>Revert daya USB gagal dengan kode keluar {0}</value>
+ <data name="Revert.UsbPower.Error.RestoreFailed" xml:space="preserve">
+ <value>Gagal memulihkan status daya USB</value>
</data>
<data name="Settings.Optimize.ShowCompletionNotification.Title" xml:space="preserve">
<value>Tampilkan notifikasi penyelesaian</value>
diff --git a/optimizerDuck/Resources/Languages/Translations.it-IT.resx b/optimizerDuck/Resources/Languages/Translations.it-IT.resx
index 977bbbd..7159118 100644
--- a/optimizerDuck/Resources/Languages/Translations.it-IT.resx
+++ b/optimizerDuck/Resources/Languages/Translations.it-IT.resx
@@ -280,6 +280,12 @@
<data name="Revert.UsbPower.Description" xml:space="preserve">
<value>Ripristina stati di alimentazione sospensione selettiva USB</value>
</data>
+ <data name="Revert.Hibernation.Description" xml:space="preserve">
+ <value>Ripristina lo stato di ibernazione</value>
+ </data>
+ <data name="Revert.Hibernation.Error.RestoreFailed" xml:space="preserve">
+ <value>Ripristino dell'ibernazione non riuscito: {0}</value>
+ </data>
<data name="Optimization.Apply.Processing" xml:space="preserve">
<value>Applicazione modifiche in corso...</value>
</data>
@@ -1439,8 +1445,8 @@ Aggiorna ora per godere delle ultime funzionalità, miglioramenti e correzioni.<
<data name="Revert.Shell.Error.CommandFailed" xml:space="preserve">
<value>Comando di ripristino fallito con codice uscita {0}</value>
</data>
- <data name="Revert.UsbPower.Error.CommandFailed" xml:space="preserve">
- <value>Ripristino alimentazione USB fallito con codice uscita {0}</value>
+ <data name="Revert.UsbPower.Error.RestoreFailed" xml:space="preserve">
+ <value>Ripristino degli stati di alimentazione USB non riuscito</value>
</data>
<data name="Settings.Optimize.ShowCompletionNotification.Title" xml:space="preserve">
<value>Mostra notifica completamento</value>
diff --git a/optimizerDuck/Resources/Languages/Translations.ja-JP.resx b/optimizerDuck/Resources/Languages/Translations.ja-JP.resx
index ec7fa43..77a8c6f 100644
--- a/optimizerDuck/Resources/Languages/Translations.ja-JP.resx
+++ b/optimizerDuck/Resources/Languages/Translations.ja-JP.resx
@@ -285,6 +285,12 @@
<data name="Revert.UsbPower.Description" xml:space="preserve">
<value>USB 選択的サスペンドの電源状態を復元</value>
</data>
+ <data name="Revert.Hibernation.Description" xml:space="preserve">
+ <value>休止状態を復元</value>
+ </data>
+ <data name="Revert.Hibernation.Error.RestoreFailed" xml:space="preserve">
+ <value>休止状態を復元できませんでした:{0}</value>
+ </data>
<data name="Optimization.Apply.Processing" xml:space="preserve">
<value>変更を適用しています…</value>
</data>
@@ -1395,8 +1401,8 @@
<data name="Revert.Shell.Error.CommandFailed" xml:space="preserve">
<value>終了コード {0} で元に戻すコマンドが失敗しました</value>
</data>
- <data name="Revert.UsbPower.Error.CommandFailed" xml:space="preserve">
- <value>終了コード {0} で USB 電源の復元に失敗しました</value>
+ <data name="Revert.UsbPower.Error.RestoreFailed" xml:space="preserve">
+ <value>USB の電力状態を復元できませんでした</value>
</data>
<data name="Settings.Optimize.ShowCompletionNotification.Title" xml:space="preserve">
<value>完了通知を表示</value>
diff --git a/optimizerDuck/Resources/Languages/Translations.ko-KR.resx b/optimizerDuck/Resources/Languages/Translations.ko-KR.resx
index 9d58493..eda4083 100644
--- a/optimizerDuck/Resources/Languages/Translations.ko-KR.resx
+++ b/optimizerDuck/Resources/Languages/Translations.ko-KR.resx
@@ -285,6 +285,12 @@
<data name="Revert.UsbPower.Description" xml:space="preserve">
<value>USB 선택적 절전 전원 상태 복원</value>
</data>
+ <data name="Revert.Hibernation.Description" xml:space="preserve">
+ <value>최대 절전 모드 상태 복원</value>
+ </data>
+ <data name="Revert.Hibernation.Error.RestoreFailed" xml:space="preserve">
+ <value>최대 절전 모드를 복원하지 못했습니다: {0}</value>
+ </data>
<data name="Optimization.Apply.Processing" xml:space="preserve">
<value>변경 사항 적용 중...</value>
</data>
@@ -1394,8 +1400,8 @@
<data name="Revert.Shell.Error.CommandFailed" xml:space="preserve">
<value>종료 코드 {0}으로 인해 되돌리기 명령이 실패했습니다</value>
</data>
- <data name="Revert.UsbPower.Error.CommandFailed" xml:space="preserve">
- <value>종료 코드 {0}으로 인해 USB 전원 복구에 실패했습니다</value>
+ <data name="Revert.UsbPower.Error.RestoreFailed" xml:space="preserve">
+ <value>USB 전원 상태를 복원하지 못했습니다</value>
</data>
<data name="Settings.Optimize.ShowCompletionNotification.Title" xml:space="preserve">
<value>완료 알림 표시</value>
diff --git a/optimizerDuck/Resources/Languages/Translations.pl-PL.resx b/optimizerDuck/Resources/Languages/Translations.pl-PL.resx
index 91acd66..3611cb8 100644
--- a/optimizerDuck/Resources/Languages/Translations.pl-PL.resx
+++ b/optimizerDuck/Resources/Languages/Translations.pl-PL.resx
@@ -286,6 +286,12 @@
<data name="Revert.UsbPower.Description" xml:space="preserve">
<value>Przywróć stany zasilania selektywnego wstrzymywania USB</value>
</data>
+ <data name="Revert.Hibernation.Description" xml:space="preserve">
+ <value>Przywróć stan hibernacji</value>
+ </data>
+ <data name="Revert.Hibernation.Error.RestoreFailed" xml:space="preserve">
+ <value>Nie udało się przywrócić hibernacji: {0}</value>
+ </data>
<data name="Optimization.Apply.Processing" xml:space="preserve">
<value>Stosowanie zmian...</value>
</data>
@@ -1403,8 +1409,8 @@ Zaktualizuj teraz, aby korzystać z najnowszych funkcji, ulepszeń i poprawek b
<data name="Revert.Shell.Error.CommandFailed" xml:space="preserve">
<value>Polecenie cofania nie powiodło się z kodem wyjścia {0}</value>
</data>
- <data name="Revert.UsbPower.Error.CommandFailed" xml:space="preserve">
- <value>Cofnięcie zasilania USB nie powiodło się z kodem wyjścia {0}</value>
+ <data name="Revert.UsbPower.Error.RestoreFailed" xml:space="preserve">
+ <value>Nie udało się przywrócić stanów zasilania USB</value>
</data>
<data name="Settings.Optimize.ShowCompletionNotification.Title" xml:space="preserve">
<value>Pokaż powiadomienie o ukończeniu</value>
diff --git a/optimizerDuck/Resources/Languages/Translations.pt-BR.resx b/optimizerDuck/Resources/Languages/Translations.pt-BR.resx
index 31a075e..3f9fa01 100644
--- a/optimizerDuck/Resources/Languages/Translations.pt-BR.resx
+++ b/optimizerDuck/Resources/Languages/Translations.pt-BR.resx
@@ -286,6 +286,12 @@
<data name="Revert.UsbPower.Description" xml:space="preserve">
<value>Restaurar estados de energia de suspensão seletiva de USB</value>
</data>
+ <data name="Revert.Hibernation.Description" xml:space="preserve">
+ <value>Restaurar o estado de hibernação</value>
+ </data>
+ <data name="Revert.Hibernation.Error.RestoreFailed" xml:space="preserve">
+ <value>Falha ao restaurar a hibernação: {0}</value>
+ </data>
<data name="Optimization.Apply.Processing" xml:space="preserve">
<value>Aplicando alterações...</value>
</data>
@@ -1403,8 +1409,8 @@ Atualize agora para desfrutar das últimas funcionalidades, melhorias e correç
<data name="Revert.Shell.Error.CommandFailed" xml:space="preserve">
<value>Comando de reversão falhou com código de saída {0}</value>
</data>
- <data name="Revert.UsbPower.Error.CommandFailed" xml:space="preserve">
- <value>Reversão de energia USB falhou com código de saída {0}</value>
+ <data name="Revert.UsbPower.Error.RestoreFailed" xml:space="preserve">
+ <value>Falha ao restaurar os estados de energia USB</value>
</data>
<data name="Settings.Optimize.ShowCompletionNotification.Title" xml:space="preserve">
<value>Mostrar notificação de conclusão</value>
diff --git a/optimizerDuck/Resources/Languages/Translations.resx b/optimizerDuck/Resources/Languages/Translations.resx
index 943f250..4b7fdf0 100644
--- a/optimizerDuck/Resources/Languages/Translations.resx
+++ b/optimizerDuck/Resources/Languages/Translations.resx
@@ -335,6 +335,12 @@
<data name="Revert.UsbPower.Description" xml:space="preserve">
<value>Restore USB selective suspend power states</value>
</data>
+ <data name="Revert.Hibernation.Description" xml:space="preserve">
+ <value>Restore hibernation state</value>
+ </data>
+ <data name="Revert.Hibernation.Error.RestoreFailed" xml:space="preserve">
+ <value>Failed to restore hibernation: {0}</value>
+ </data>
<data name="Revert.PowerPlan.Description" xml:space="preserve">
<value>Restore previous active power plan {0}</value>
</data>
@@ -1663,8 +1669,8 @@ Update now to enjoy the latest features, improvements, and bug fixes.</value>
<data name="Revert.Shell.Error.CommandFailed" xml:space="preserve">
<value>Revert command failed with exit code {0}</value>
</data>
- <data name="Revert.UsbPower.Error.CommandFailed" xml:space="preserve">
- <value>USB power revert failed with exit code {0}</value>
+ <data name="Revert.UsbPower.Error.RestoreFailed" xml:space="preserve">
+ <value>Failed to restore USB power states</value>
</data>
<data name="Settings.Optimize.ShowCompletionNotification.Title" xml:space="preserve">
<value>Show completion notification</value>
diff --git a/optimizerDuck/Resources/Languages/Translations.ru-RU.resx b/optimizerDuck/Resources/Languages/Translations.ru-RU.resx
index e68e0ee..e64485e 100644
--- a/optimizerDuck/Resources/Languages/Translations.ru-RU.resx
+++ b/optimizerDuck/Resources/Languages/Translations.ru-RU.resx
@@ -286,6 +286,12 @@
<data name="Revert.UsbPower.Description" xml:space="preserve">
<value>Восстановить параметры выборочной приостановки USB</value>
</data>
+ <data name="Revert.Hibernation.Description" xml:space="preserve">
+ <value>Восстановить состояние гибернации</value>
+ </data>
+ <data name="Revert.Hibernation.Error.RestoreFailed" xml:space="preserve">
+ <value>Не удалось восстановить гибернацию: {0}</value>
+ </data>
<data name="Optimization.Apply.Processing" xml:space="preserve">
<value>Применение изменений...</value>
</data>
@@ -1397,8 +1403,8 @@
<data name="Revert.Shell.Error.CommandFailed" xml:space="preserve">
<value>Команда отката завершилась с кодом {0}</value>
</data>
- <data name="Revert.UsbPower.Error.CommandFailed" xml:space="preserve">
- <value>Откат питания USB завершился с кодом {0}</value>
+ <data name="Revert.UsbPower.Error.RestoreFailed" xml:space="preserve">
+ <value>Не удалось восстановить состояния питания USB</value>
</data>
<data name="Settings.Optimize.ShowCompletionNotification.Title" xml:space="preserve">
<value>Показывать уведомление о завершении</value>
diff --git a/optimizerDuck/Resources/Languages/Translations.tr-TR.resx b/optimizerDuck/Resources/Languages/Translations.tr-TR.resx
index 2a17a30..9fa362b 100644
--- a/optimizerDuck/Resources/Languages/Translations.tr-TR.resx
+++ b/optimizerDuck/Resources/Languages/Translations.tr-TR.resx
@@ -285,6 +285,12 @@
<data name="Revert.UsbPower.Description" xml:space="preserve">
<value>USB seçici askıya alma güç durumlarını geri yükle</value>
</data>
+ <data name="Revert.Hibernation.Description" xml:space="preserve">
+ <value>Hazırda bekletme durumunu geri yükle</value>
+ </data>
+ <data name="Revert.Hibernation.Error.RestoreFailed" xml:space="preserve">
+ <value>Hazırda bekletme geri yüklenemedi: {0}</value>
+ </data>
<data name="Optimization.Apply.Processing" xml:space="preserve">
<value>Değişiklikler uygulanıyor...</value>
</data>
@@ -1394,8 +1400,8 @@ En son özelliklerden, iyileştirmelerden ve hata düzeltmelerinden yararlanmak
<data name="Revert.Shell.Error.CommandFailed" xml:space="preserve">
<value>Geri alma komutu {0} çıkış koduyla başarısız oldu</value>
</data>
- <data name="Revert.UsbPower.Error.CommandFailed" xml:space="preserve">
- <value>USB güç geri alması {0} çıkış koduyla başarısız oldu</value>
+ <data name="Revert.UsbPower.Error.RestoreFailed" xml:space="preserve">
+ <value>USB güç durumları geri yüklenemedi</value>
</data>
<data name="Settings.Optimize.ShowCompletionNotification.Title" xml:space="preserve">
<value>Tamamlanma bildirimi göster</value>
diff --git a/optimizerDuck/Resources/Languages/Translations.vi-VN.resx b/optimizerDuck/Resources/Languages/Translations.vi-VN.resx
index 774e14f..595aa3d 100644
--- a/optimizerDuck/Resources/Languages/Translations.vi-VN.resx
+++ b/optimizerDuck/Resources/Languages/Translations.vi-VN.resx
@@ -289,6 +289,12 @@
<data name="Revert.UsbPower.Description" xml:space="preserve">
<value>Khôi phục trạng thái nguồn tạm ngưng chọn lọc USB</value>
</data>
+ <data name="Revert.Hibernation.Description" xml:space="preserve">
+ <value>Khôi phục trạng thái ngủ đông</value>
+ </data>
+ <data name="Revert.Hibernation.Error.RestoreFailed" xml:space="preserve">
+ <value>Không khôi phục được trạng thái ngủ đông: {0}</value>
+ </data>
<data name="Optimization.Apply.Processing" xml:space="preserve">
<value>Đang áp dụng...</value>
</data>
@@ -1305,8 +1311,8 @@ Cập nhật ngay để trải nghiệm các tính năng mới, cải tiến và
<data name="Revert.Shell.Error.CommandFailed" xml:space="preserve">
<value>Lệnh hoàn tác thất bại với mã thoát {0}</value>
</data>
- <data name="Revert.UsbPower.Error.CommandFailed" xml:space="preserve">
- <value>Hoàn tác nguồn USB thất bại với mã thoát {0}</value>
+ <data name="Revert.UsbPower.Error.RestoreFailed" xml:space="preserve">
+ <value>Không khôi phục được trạng thái nguồn USB</value>
</data>
<data name="Settings.Optimize.ShowCompletionNotification.Title" xml:space="preserve">
<value>Hiển thị thông báo hoàn tất</value>
diff --git a/optimizerDuck/Resources/Languages/Translations.zh-CN.resx b/optimizerDuck/Resources/Languages/Translations.zh-CN.resx
index e736f6d..64377b7 100644
--- a/optimizerDuck/Resources/Languages/Translations.zh-CN.resx
+++ b/optimizerDuck/Resources/Languages/Translations.zh-CN.resx
@@ -286,6 +286,12 @@
<data name="Revert.UsbPower.Description" xml:space="preserve">
<value>还原 USB 选择性挂起电源状态</value>
</data>
+ <data name="Revert.Hibernation.Description" xml:space="preserve">
+ <value>恢复休眠状态</value>
+ </data>
+ <data name="Revert.Hibernation.Error.RestoreFailed" xml:space="preserve">
+ <value>无法恢复休眠状态:{0}</value>
+ </data>
<data name="Optimization.Apply.Processing" xml:space="preserve">
<value>正在应用更改...</value>
</data>
@@ -1475,8 +1481,8 @@
<data name="Revert.Shell.Error.CommandFailed" xml:space="preserve">
<value>还原命令执行失败,返回代码为 {0}</value>
</data>
- <data name="Revert.UsbPower.Error.CommandFailed" xml:space="preserve">
- <value>USB 电源恢复操作失败,返回代码为 {0}</value>
+ <data name="Revert.UsbPower.Error.RestoreFailed" xml:space="preserve">
+ <value>无法恢复 USB 电源状态</value>
</data>
<data name="Settings.Optimize.ShowCompletionNotification.Title" xml:space="preserve">
<value>显示完成通知</value>
diff --git a/optimizerDuck/Resources/Languages/Translations.zh-TW.resx b/optimizerDuck/Resources/Languages/Translations.zh-TW.resx
index 62fd151..6acc9c0 100644
--- a/optimizerDuck/Resources/Languages/Translations.zh-TW.resx
+++ b/optimizerDuck/Resources/Languages/Translations.zh-TW.resx
@@ -264,6 +264,12 @@
<data name="Revert.UsbPower.Description" xml:space="preserve">
<value>還原 USB 選擇性暫停電源狀態</value>
</data>
+ <data name="Revert.Hibernation.Description" xml:space="preserve">
+ <value>還原休眠狀態</value>
+ </data>
+ <data name="Revert.Hibernation.Error.RestoreFailed" xml:space="preserve">
+ <value>無法還原休眠狀態:{0}</value>
+ </data>
<data name="Optimization.Apply.Processing" xml:space="preserve">
<value>正在套用變更...</value>
</data>
@@ -1098,8 +1104,8 @@
<data name="Revert.Shell.Error.CommandFailed" xml:space="preserve">
<value>還原命令執行失敗,結束代碼為 {0}</value>
</data>
- <data name="Revert.UsbPower.Error.CommandFailed" xml:space="preserve">
- <value>USB 電源還原操作失敗,結束代碼為 {0}</value>
+ <data name="Revert.UsbPower.Error.RestoreFailed" xml:space="preserve">
+ <value>無法還原 USB 電源狀態</value>
</data>
<data name="Settings.Optimize.ShowCompletionNotification.Title" xml:space="preserve">
<value>顯示完成通知</value>
diff --git a/optimizerDuck/Services/Optimization/OptimizationService.cs b/optimizerDuck/Services/Optimization/OptimizationService.cs
index dcadf30..65182e5 100644
--- a/optimizerDuck/Services/Optimization/OptimizationService.cs
+++ b/optimizerDuck/Services/Optimization/OptimizationService.cs
@@ -1,4 +1,5 @@
-using System.IO;
+using System.IO;
+using System.Management;
using System.Text.RegularExpressions;
using Microsoft.Extensions.Logging;
using optimizerDuck.Common.Extensions;
@@ -6,6 +7,7 @@ using optimizerDuck.Common.Helpers;
using optimizerDuck.Domain.Abstractions;
using optimizerDuck.Domain.Execution;
using optimizerDuck.Domain.Optimizations.Models;
+using optimizerDuck.Domain.Optimizations.Models.Services;
using optimizerDuck.Domain.Revert;
using optimizerDuck.Domain.UI;
using optimizerDuck.Resources.Languages;
@@ -28,12 +30,14 @@ public class OptimizationService(
IContentDialogService contentDialogService,
ShellService shellService,
PowerPlanService powerPlanService,
+ SystemRestoreService systemRestoreService,
ILogger<OptimizationService> logger
)
{
private readonly ILogger _logger = logger;
private readonly ShellService _shellService = shellService;
private readonly PowerPlanService _powerPlanService = powerPlanService;
+ private readonly SystemRestoreService _systemRestoreService = systemRestoreService;
private OptimizationContext NewContext(
ChangeSet changes,
@@ -56,12 +60,17 @@ public class OptimizationService(
/// <summary>Gets or sets a value that indicates whether a system restore point was created before applying optimizations.</summary>
public bool WasRequestedRestorePoint { get; set; } = false;
- private static readonly Regex _restorePointDisabledRegex = new(
- @"\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 | RegexOptions.Compiled
- );
-
- /// <summary>Creates a system restore point via PowerShell, showing a processing dialog. Enables System Protection if it is disabled.</summary>
+ /// <summary>
+ /// Creates a restore point through the System Restore subsystem, showing a processing
+ /// dialog. Enables System Protection for the system drive and retries once when Windows
+ /// reports protection as disabled.
+ /// <para>
+ /// This is a UI orchestration method: it must be awaited from the UI thread and it keeps
+ /// that thread for itself, because it shows, updates and hides a <see cref="ContentDialog"/>.
+ /// Only the native calls are pushed onto the thread pool, so a slow service call never
+ /// blocks the interface.
+ /// </para>
+ /// </summary>
/// <returns>A <see cref="RestorePointResult"/> indicating success, failure, or frequency-limit reached.</returns>
public async Task<RestorePointResult> CreateRestorePointAsync()
{
@@ -77,6 +86,15 @@ public class OptimizationService(
try
{
+ // Throttle is the documented frequency setting plus the newest existing point; the
+ // service fails open when that state cannot be read, exactly like the create below.
+ var nowUtc = DateTime.UtcNow;
+ if (await Task.Run(() => _systemRestoreService.IsWithinCreationThrottle(nowUtc)))
+ {
+ _logger.LogWarning("Restore point creation skipped: frequency limit reached.");
+ return RestorePointResult.FrequencyLimitReached;
+ }
+
dialogViewModel.ProgressReporter.Report(
new ProcessingProgress
{
@@ -84,28 +102,26 @@ public class OptimizationService(
IsIndeterminate = true,
}
);
- var result = await _shellService
- .QueryPowerShellAsync(
- $"Checkpoint-Computer -Description \"{Shared.RestorePointName}\" -RestorePointType MODIFY_SETTINGS",
- _logger
- )
- .ConfigureAwait(false);
- if (IsFrequencyLimited(result.Stderr))
- {
- _logger.LogWarning("Restore point creation skipped: frequency limit reached.");
- return RestorePointResult.FrequencyLimitReached;
- }
+ var first = await Task.Run(() =>
+ _systemRestoreService.CreateRestorePoint(Shared.RestorePointName)
+ );
+
+ if (first.ExceptionText is not null)
+ _logger.LogError("Restore point creation failed: {Message}", first.ExceptionText);
- if (result.ExitCode == 0)
+ if (first.Succeeded)
{
_logger.LogInformation("Restore point created successfully.");
return RestorePointResult.Success;
}
- if (!_restorePointDisabledRegex.IsMatch(result.Stderr))
+ if (!SystemRestoreService.IsProtectionDisabledStatus(first.NativeStatus))
{
- _logger.LogError("Failed to create restore point: {Message}", result.Stderr);
+ _logger.LogError(
+ "Failed to create restore point: native status 0x{Status:X8}",
+ first.NativeStatus
+ );
return RestorePointResult.Failed;
}
@@ -118,14 +134,14 @@ public class OptimizationService(
}
);
- var enableResult = await _shellService
- .QueryPowerShellAsync("Enable-ComputerRestore -Drive \"$env:SystemDrive\"", _logger)
- .ConfigureAwait(false);
- if (enableResult.ExitCode != 0)
+ var systemDrive = Environment.GetEnvironmentVariable("SystemDrive") ?? "C:";
+ var enable = await Task.Run(() => _systemRestoreService.EnableProtection(systemDrive));
+ if (!enable.Succeeded)
{
_logger.LogError(
- "Failed to enable System Protection: {Message}",
- enableResult.Stderr
+ "Failed to enable System Protection: native status 0x{Status:X8} {Message}",
+ enable.NativeStatus,
+ enable.ExceptionText
);
return RestorePointResult.Failed;
}
@@ -138,32 +154,34 @@ public class OptimizationService(
}
);
- result = await _shellService
- .QueryPowerShellAsync(
- $"Checkpoint-Computer -Description \"{Shared.RestorePointName}\" -RestorePointType MODIFY_SETTINGS",
- _logger
- )
- .ConfigureAwait(false);
+ var retry = await Task.Run(() =>
+ _systemRestoreService.CreateRestorePoint(Shared.RestorePointName)
+ );
- if (IsFrequencyLimited(result.Stderr))
- return RestorePointResult.FrequencyLimitReached;
+ if (retry.ExceptionText is not null)
+ _logger.LogError("Restore point creation failed: {Message}", retry.ExceptionText);
- return result.ExitCode == 0 ? RestorePointResult.Success : RestorePointResult.Failed;
+ if (retry.Succeeded)
+ {
+ _logger.LogInformation("Restore point created successfully.");
+ return RestorePointResult.Success;
+ }
+
+ _logger.LogError(
+ "Failed to create restore point after enabling System Protection: native status 0x{Status:X8}",
+ retry.NativeStatus
+ );
+ return RestorePointResult.Failed;
}
finally
{
+ // Hide() raises a routed event, so it throws when called from another thread. This
+ // method deliberately does not drop the synchronization context, which keeps the
+ // continuation here on the UI thread.
dialog?.Hide();
}
}
- private static bool IsFrequencyLimited(string? stderr)
- {
- return stderr?.Contains(
- "already been created within the past",
- StringComparison.OrdinalIgnoreCase
- ) == true;
- }
-
/// <summary>Applies the specified optimization, captures revert steps into an execution scope, and persists revert data on any successful steps.</summary>
/// <param name="optimization">The optimization to apply.</param>
/// <param name="progress">An <see cref="IProgress{T}"/> to report application progress.</param>
diff --git a/optimizerDuck/Services/System/PowerPlanService.cs b/optimizerDuck/Services/System/PowerPlanService.cs
index 8494477..da553cb 100644
--- a/optimizerDuck/Services/System/PowerPlanService.cs
+++ b/optimizerDuck/Services/System/PowerPlanService.cs
@@ -1413,8 +1413,10 @@ public class PowerPlanService
uint DcValueIndex
);
+ // Native return is BOOLEAN (one byte): UnmanagedType.Bool would read four, and the x64 ABI
+ // leaves the unused return bits undefined.
[DllImport("powrprof.dll")]
- [return: MarshalAs(UnmanagedType.Bool)]
+ [return: MarshalAs(UnmanagedType.U1)]
private static extern bool PowerIsSettingRangeDefined(
ref Guid SubKeyGuid,
ref Guid SettingGuid
diff --git a/optimizerDuck/Services/System/Primitives/HibernationService.cs b/optimizerDuck/Services/System/Primitives/HibernationService.cs
new file mode 100644
index 0000000..1e63450
--- /dev/null
+++ b/optimizerDuck/Services/System/Primitives/HibernationService.cs
@@ -0,0 +1,120 @@
+using System.Runtime.InteropServices;
+using System.Runtime.Versioning;
+
+namespace optimizerDuck.Services.System.Primitives;
+
+/// <summary>
+/// Hibernation file state and commit/removal over the documented power information callback
+/// (<c>CallNtPowerInformation</c>), so the optimization no longer shells out to
+/// <c>powercfg /h</c>. Level 4 returns the system capabilities that carry the previous state,
+/// level 10 commits or removes the hibernation file.
+/// </summary>
+[SupportedOSPlatform("windows")]
+public static class HibernationService
+{
+ private const int SystemPowerCapabilities = 4;
+ private const int SystemReserveHiberFile = 10;
+
+ /// <summary>
+ /// Comfortably larger than the native <c>SYSTEM_POWER_CAPABILITIES</c> structure (~88
+ /// bytes); the callback writes only its own fields, so an oversized buffer is safe and
+ /// avoids modelling the whole structure.
+ /// </summary>
+ private const int CapabilitiesBufferSize = 160;
+
+ /// <summary>
+ /// Byte offset of <c>HiberFilePresent</c>: the documented structure opens with nine
+ /// one-byte <c>BOOLEAN</c> members (PowerButtonPresent, SleepButtonPresent, LidPresent,
+ /// SystemS1-S5, HiberFilePresent), so there is no padding before it.
+ /// </summary>
+ private const int HiberFilePresentOffset = 8;
+
+ private const uint StatusSuccess = 0;
+
+ /// <summary>Result of a hibernation file commit/removal request, with the raw NTSTATUS.</summary>
+ /// <param name="Succeeded">Whether the callback reported STATUS_SUCCESS.</param>
+ /// <param name="NativeStatus">The NTSTATUS value, so callers can log the real code.</param>
+ /// <param name="ExceptionText">Throw text when the interop itself failed, else null.</param>
+ public sealed record HibernationChangeResult(
+ bool Succeeded,
+ uint NativeStatus,
+ string? ExceptionText = null
+ );
+
+ /// <summary>
+ /// Whether the system reports a hibernation file right now, which is what hibernation and
+ /// Fast Startup depend on. Null when the capabilities could not be read, so a caller can
+ /// keep its own fail-safe default instead of treating "unknown" as "absent".
+ /// </summary>
+ public static bool? IsHibernationFilePresent()
+ {
+ var buffer = Marshal.AllocHGlobal(CapabilitiesBufferSize);
+ try
+ {
+ var status = CallNtPowerInformation(
+ SystemPowerCapabilities,
+ IntPtr.Zero,
+ 0,
+ buffer,
+ CapabilitiesBufferSize
+ );
+
+ if (status != StatusSuccess)
+ return null;
+
+ return Marshal.ReadByte(buffer, HiberFilePresentOffset) != 0;
+ }
+ catch
+ {
+ return null;
+ }
+ finally
+ {
+ Marshal.FreeHGlobal(buffer);
+ }
+ }
+
+ /// <summary>
+ /// Commits (<paramref name="present" /> true) or removes (false) the hibernation file, the
+ /// documented equivalent of <c>powercfg /h on|off</c>. Needs sufficient privileges; a
+ /// refusal comes back as a failed result carrying the NTSTATUS instead of throwing.
+ /// </summary>
+ public static HibernationChangeResult SetHibernationFile(bool present)
+ {
+ try
+ {
+ var request = (byte)(present ? 1 : 0);
+ var status = CallNtPowerInformation(
+ SystemReserveHiberFile,
+ ref request,
+ 1,
+ IntPtr.Zero,
+ 0
+ );
+
+ return new HibernationChangeResult(status == StatusSuccess, unchecked((uint)status));
+ }
+ catch (Exception ex)
+ {
+ return new HibernationChangeResult(false, 0, ex.Message);
+ }
+ }
+
+ [DllImport("powrprof.dll")]
+ private static extern int CallNtPowerInformation(
+ int informationLevel,
+ IntPtr inputBuffer,
+ uint inputBufferLength,
+ IntPtr outputBuffer,
+ uint outputBufferLength
+ );
+
+ [DllImport("powrprof.dll")]
+ private static extern int CallNtPowerInformation(
+ int informationLevel,
+ ref byte inputBuffer,
+ uint inputBufferLength,
+ IntPtr outputBuffer,
+ uint outputBufferLength
+ );
+}
diff --git a/optimizerDuck/Services/System/Primitives/RecycleBinService.cs b/optimizerDuck/Services/System/Primitives/RecycleBinService.cs
new file mode 100644
index 0000000..3960718
--- /dev/null
+++ b/optimizerDuck/Services/System/Primitives/RecycleBinService.cs
@@ -0,0 +1,79 @@
+using System.Runtime.InteropServices;
+using System.Runtime.Versioning;
+
+namespace optimizerDuck.Services.System.Primitives;
+
+/// <summary>
+/// Recycle Bin size/count and emptying over shell32, without launching PowerShell.
+/// Layout note: <c>SHQUERYRBINFO</c> is a default-aligned 24-byte structure. Verified
+/// against live shell32: <c>cbSize</c> 20 is refused with E_INVALIDARG while 24 is accepted,
+/// so this must NOT be declared with <c>Pack = 1</c> the way older samples do.
+/// </summary>
+[SupportedOSPlatform("windows")]
+public static class RecycleBinService
+{
+ private const int S_OK = 0;
+
+ // Documented prompt suppression for SHEmptyRecycleBin.
+ internal const uint ShrbNoConfirmation = 0x00000001;
+ internal const uint ShrbNoProgressUi = 0x00000002;
+ internal const uint ShrbNoSound = 0x00000004;
+ internal const uint SuppressionFlags = ShrbNoConfirmation | ShrbNoProgressUi | ShrbNoSound;
+
+ /// <summary>Totals for one Recycle Bin scope: bytes and item count as the shell reports them.</summary>
+ public sealed record RecycleBinTotals(long SizeBytes, long ItemCount);
+
+ /// <summary>
+ /// Reads the caller's Recycle Bin totals. <paramref name="rootPath" /> empty means every
+ /// drive (the documented <c>L""</c> form); a drive root such as <c>C:\</c> narrows it.
+ /// Returns zeros when the shell refuses the path, so callers can render without a failure
+ /// branch.
+ /// </summary>
+ public static RecycleBinTotals Query(string rootPath = "")
+ {
+ var info = new SHQUERYRBINFO { cbSize = (uint)Marshal.SizeOf<SHQUERYRBINFO>() };
+ if (SHQueryRecycleBin(rootPath, ref info) != S_OK)
+ return new RecycleBinTotals(0, 0);
+
+ return new RecycleBinTotals(info.i64Size, info.i64NumItems);
+ }
+
+ /// <summary>
+ /// Empties the Recycle Bin for <paramref name="rootPath" /> (empty = every drive) with
+ /// confirmation, progress UI, and sound suppressed. Irreversible: callers must not record
+ /// a revert step for it.
+ /// </summary>
+ /// <returns>Whether the shell reported success, plus the HRESULT when it did not.</returns>
+ public static (bool Succeeded, int ErrorCode) Empty(string rootPath = "")
+ {
+ var hr = SHEmptyRecycleBin(IntPtr.Zero, rootPath, SuppressionFlags);
+ return (hr == S_OK, hr);
+ }
+
+ [StructLayout(LayoutKind.Sequential)]
+ private struct SHQUERYRBINFO
+ {
+ public uint cbSize;
+ public long i64Size;
+ public long i64NumItems;
+ }
+
+ [DllImport(
+ "shell32.dll",
+ EntryPoint = "SHQueryRecycleBinW",
+ ExactSpelling = true,
+ CharSet = CharSet.Unicode
+ )]
+ private static extern int SHQueryRecycleBin(
+ string pszRootPath,
+ ref SHQUERYRBINFO pSHQueryRBInfo
+ );
+
+ [DllImport(
+ "shell32.dll",
+ EntryPoint = "SHEmptyRecycleBinW",
+ ExactSpelling = true,
+ CharSet = CharSet.Unicode
+ )]
+ private static extern int SHEmptyRecycleBin(IntPtr hwnd, string pszRootPath, uint dwFlags);
+}
diff --git a/optimizerDuck/Services/System/Primitives/ServiceProcessService.cs b/optimizerDuck/Services/System/Primitives/ServiceProcessService.cs
index 3810d40..1a2ea53 100644
--- a/optimizerDuck/Services/System/Primitives/ServiceProcessService.cs
+++ b/optimizerDuck/Services/System/Primitives/ServiceProcessService.cs
@@ -1,4 +1,5 @@
using System.Diagnostics;
+using System.Runtime.InteropServices;
using Microsoft.Extensions.Logging;
using optimizerDuck.Common.Extensions;
using optimizerDuck.Domain.Abstractions;
@@ -14,75 +15,38 @@ public static class ServiceProcessService
private const int ErrorAccessDenied = 5;
- private const int DefaultScTimeoutMs = 30000;
- private const int DefaultScQueryTimeoutMs = 15000;
-
/// <summary>
- /// Parses the START_TYPE from raw <c>sc qc</c> stdout.
- /// Exposed as internal for unit testing.
+ /// Retrieves the current startup type of a Windows service from the Service Control Manager.
/// </summary>
- internal static (ServiceStartupType? StartupType, bool ParseFailed) ParseScStartType(
- string stdout
- )
- {
- var (type, matched) = Windows.Services.ScStartupTypeParser.ParseWithMatch(stdout);
- return (type, !matched);
- }
-
- /// <summary>Retrieves the current startup type of a Windows service by running <c>sc.exe qc</c>.</summary>
/// <param name="serviceName">The internal service name.</param>
/// <param name="logger">Optional logger used only for logging.</param>
/// <returns>
- /// A tuple. <c>StartupType</c> is the type if parsed successfully.
- /// <c>NotFound</c> is <see langword="true"/> when the service does not exist (exit code 1060),
- /// <see langword="false"/> for other errors.
+ /// A tuple. <c>StartupType</c> is the type Windows reports (null for boot and system starts,
+ /// which have no <see cref="ServiceStartupType"/> value). <c>NotFound</c> is
+ /// <see langword="true"/> when the service does not exist
+ /// (<c>ERROR_SERVICE_DOES_NOT_EXIST</c>, 1060), <see langword="false"/> for other errors.
/// </returns>
- public static async Task<(ServiceStartupType? StartupType, bool NotFound)> GetStartupTypeAsync(
+ public static Task<(ServiceStartupType? StartupType, bool NotFound)> GetStartupTypeAsync(
string serviceName,
ILogger? logger = null
)
{
- try
- {
- var (exitCode, stdout, stderr) = await RunScExeAsync(
- $"qc \"{serviceName}\"",
- DefaultScQueryTimeoutMs
- );
-
- if (exitCode != 0)
- {
- var notFound = exitCode == ErrorServiceDoesNotExist;
- logger?.LogWarning(
- "[SERVICE][{Name}] sc.exe qc failed with exit code {ExitCode}: {Stderr}",
- serviceName,
- exitCode,
- stderr
- );
- return (null, notFound);
- }
-
- var (result, parseError) = ParseScStartType(stdout);
+ var (startupType, error) = QueryStartupType(serviceName);
- if (parseError)
- {
- logger?.LogWarning(
- "[SERVICE][{Name}] Could not parse START_TYPE from sc.exe qc output:\n{Output}",
- serviceName,
- stdout
- );
- return (null, false);
- }
+ if (error != 0 && error != ErrorServiceDoesNotExist)
+ logger?.LogWarning(
+ "[SERVICE][{Name}] opening the service failed with Win32 error {Error}",
+ serviceName,
+ error
+ );
- return (result, false);
- }
- catch (Exception ex)
- {
- logger?.LogError(ex, "Failed to get startup type for {ServiceName}", serviceName);
- return (null, false);
- }
+ return Task.FromResult((startupType, error == ErrorServiceDoesNotExist));
}
- /// <summary>Changes the startup type of a single Windows service via <c>sc.exe config</c>. Records the change into <paramref name="call"/>.</summary>
+ /// <summary>
+ /// Changes the startup type of a single Windows service through the Service Control Manager.
+ /// Records the change into <paramref name="call"/>.
+ /// </summary>
/// <param name="call">The explicit call context: change collector, logger and cancellation token.</param>
/// <param name="item">The service item with the target startup type.</param>
/// <returns>The outcome of the change request.</returns>
@@ -151,26 +115,14 @@ public static class ServiceProcessService
return MapToOpResult(ServiceChangeResult.AlreadyConfigured, null, null, null);
}
- var scType = item.StartupType switch
- {
- ServiceStartupType.Automatic => "auto",
- ServiceStartupType.AutomaticDelayedStart => "delayed-auto",
- ServiceStartupType.Manual => "demand",
- ServiceStartupType.Disabled => "disabled",
- _ => "demand",
- };
-
- var (exitCode, stdout, stderr) = await RunScExeAsync(
- $"config \"{item.Name}\" start= {scType}",
- DefaultScTimeoutMs
- );
+ var nativeError = SetStartupType(item.Name, item.StartupType);
- var success = exitCode == 0;
+ var success = nativeError == 0;
sw.Stop();
string? errorDetail = null;
if (!success)
- errorDetail = $"sc.exe exit code: {exitCode}\nstdout: {stdout}\nstderr: {stderr}";
+ errorDetail = $"ChangeServiceConfig failed with Win32 error {nativeError}";
if (success)
{
@@ -193,7 +145,7 @@ public static class ServiceProcessService
return MapToOpResult(ServiceChangeResult.Success, revertStep, null, null);
}
- if (exitCode == ErrorAccessDenied)
+ if (nativeError == ErrorAccessDenied)
{
var accessDeniedError = ServiceStrings.Format(
ServiceStrings.ServiceInfoSkippedAccessDenied,
@@ -304,72 +256,266 @@ public static class ServiceProcessService
};
}
- private static async Task<(int ExitCode, string Stdout, string Stderr)> RunScExeAsync(
- string arguments,
- int timeoutMs
- )
- {
- using var process = new Process
- {
- StartInfo = new ProcessStartInfo
- {
- FileName = "sc.exe",
- Arguments = arguments,
- RedirectStandardOutput = true,
- RedirectStandardError = true,
- UseShellExecute = false,
- CreateNoWindow = true,
- },
- };
+ // =============================================
+ // Service Control Manager interop
+ // =============================================
- process.Start();
- // drain both pipes concurrently so a chatty child can never block on a full pipe.
- var stdoutTask = process.StandardOutput.ReadToEndAsync();
- var stderrTask = process.StandardError.ReadToEndAsync();
+ private const int ScManagerConnect = 0x0001;
+ private const int ServiceQueryConfig = 0x0001;
+ private const int ServiceChangeConfig = 0x0002;
+
+ private const uint ScServiceNoChange = 0xFFFFFFFF;
+ private const uint ScServiceAutoStart = 0x00000002;
+ private const uint ScServiceDemandStart = 0x00000003;
+ private const uint ScServiceDisabled = 0x00000004;
+
+ private const uint ServiceConfigDelayedAutoStartInfo = 3;
+
+ /// <summary>Offset of <c>dwStartType</c> in the native <c>QUERY_SERVICE_CONFIG</c> structure.</summary>
+ private const int QueryServiceConfigStartTypeOffset = 4;
+
+ /// <summary>
+ /// Comfortably larger than <c>QUERY_SERVICE_CONFIG</c> plus the variable-length strings
+ /// Windows appends to the same buffer; only the fixed prefix is read.
+ /// </summary>
+ private const int QueryServiceConfigBufferSize = 8 * 1024;
+
+ /// <summary>
+ /// Reads the configured start type, and whether the delayed flag is set, through the SCM.
+ /// The returned error is a Win32 code (0 on success).
+ /// </summary>
+ private static (ServiceStartupType? StartupType, int Error) QueryStartupType(string serviceName)
+ {
+ var manager = OpenSCManager(null, null, ScManagerConnect);
+ if (manager == IntPtr.Zero)
+ return (null, Marshal.GetLastWin32Error());
- using var cts = new CancellationTokenSource(timeoutMs);
- var timedOut = false;
try
{
- await process.WaitForExitAsync(cts.Token).ConfigureAwait(false);
- }
- catch (OperationCanceledException)
- {
- timedOut = true;
+ var service = OpenService(manager, serviceName, ServiceQueryConfig);
+ if (service == IntPtr.Zero)
+ return (null, Marshal.GetLastWin32Error());
+
try
{
- process.Kill(entireProcessTree: true);
- }
- catch
- {
- // best effort
+ var buffer = Marshal.AllocHGlobal(QueryServiceConfigBufferSize);
+ try
+ {
+ if (!QueryServiceConfig(service, buffer, QueryServiceConfigBufferSize, out _))
+ return (null, Marshal.GetLastWin32Error());
+
+ var startType = (uint)
+ Marshal.ReadInt32(buffer, QueryServiceConfigStartTypeOffset);
+
+ return (
+ startType switch
+ {
+ ScServiceAutoStart => IsDelayedAutoStart(service)
+ ? ServiceStartupType.AutomaticDelayedStart
+ : ServiceStartupType.Automatic,
+ ScServiceDemandStart => ServiceStartupType.Manual,
+ ScServiceDisabled => ServiceStartupType.Disabled,
+ // Boot (0) and system (1) starts have no ServiceStartupType value.
+ _ => null,
+ },
+ 0
+ );
+ }
+ finally
+ {
+ Marshal.FreeHGlobal(buffer);
+ }
}
-
- // bounded wait so ExitCode is never read on a live process.
- try
+ finally
{
- process.WaitForExit(2000);
+ CloseServiceHandle(service);
}
- catch { }
}
+ finally
+ {
+ CloseServiceHandle(manager);
+ }
+ }
- var stdout = await stdoutTask.ConfigureAwait(false);
- var stderr = await stderrTask.ConfigureAwait(false);
-
- // -1 means timeout (same convention as ProcessRunner), never a real exit code.
- var exitCode = timedOut || !HasExited(process) ? -1 : process.ExitCode;
- return (exitCode, stdout, stderr);
+ private static bool IsDelayedAutoStart(IntPtr service)
+ {
+ var buffer = Marshal.AllocHGlobal(sizeof(int));
+ try
+ {
+ // A missing record means the flag is not set, not a failure.
+ return QueryServiceConfig2(
+ service,
+ ServiceConfigDelayedAutoStartInfo,
+ buffer,
+ sizeof(int),
+ out _
+ )
+ && Marshal.ReadInt32(buffer) != 0;
+ }
+ finally
+ {
+ Marshal.FreeHGlobal(buffer);
+ }
}
- private static bool HasExited(Process process)
+ /// <summary>
+ /// Writes the start type, then the delayed flag for auto-start targets. Returns a Win32
+ /// error code (0 on success).
+ /// </summary>
+ private static int SetStartupType(string serviceName, ServiceStartupType startupType)
{
+ var desiredStart = startupType switch
+ {
+ ServiceStartupType.Automatic or ServiceStartupType.AutomaticDelayedStart =>
+ ScServiceAutoStart,
+ ServiceStartupType.Manual => ScServiceDemandStart,
+ ServiceStartupType.Disabled => ScServiceDisabled,
+ _ => ScServiceDemandStart,
+ };
+
+ var manager = OpenSCManager(null, null, ScManagerConnect);
+ if (manager == IntPtr.Zero)
+ return Marshal.GetLastWin32Error();
+
try
{
- return process.HasExited;
+ var service = OpenService(
+ manager,
+ serviceName,
+ ServiceQueryConfig | ServiceChangeConfig
+ );
+ if (service == IntPtr.Zero)
+ return Marshal.GetLastWin32Error();
+
+ try
+ {
+ if (
+ !ChangeServiceConfig(
+ service,
+ ScServiceNoChange,
+ desiredStart,
+ ScServiceNoChange,
+ null,
+ null,
+ IntPtr.Zero,
+ null,
+ null,
+ null,
+ null
+ )
+ )
+ return Marshal.GetLastWin32Error();
+
+ // The flag is ignored for non-auto-start services, and leaving a previous "delayed"
+ // flag behind would keep reporting the old state, so it is always written for
+ // auto-start targets.
+ if (desiredStart == ScServiceAutoStart)
+ {
+ var info = new SERVICE_DELAYED_AUTO_START_INFO
+ {
+ fDelayedAutostart = startupType == ServiceStartupType.AutomaticDelayedStart,
+ };
+
+ if (!ChangeServiceConfig2(service, ServiceConfigDelayedAutoStartInfo, ref info))
+ return Marshal.GetLastWin32Error();
+ }
+
+ return 0;
+ }
+ finally
+ {
+ CloseServiceHandle(service);
+ }
}
- catch
+ finally
{
- return false;
+ CloseServiceHandle(manager);
}
}
+
+ [StructLayout(LayoutKind.Sequential)]
+ private struct SERVICE_DELAYED_AUTO_START_INFO
+ {
+ [MarshalAs(UnmanagedType.Bool)]
+ public bool fDelayedAutostart;
+ }
+
+ [DllImport(
+ "advapi32.dll",
+ EntryPoint = "OpenSCManagerW",
+ ExactSpelling = true,
+ CharSet = CharSet.Unicode,
+ SetLastError = true
+ )]
+ private static extern IntPtr OpenSCManager(
+ string? machineName,
+ string? databaseName,
+ int desiredAccess
+ );
+
+ [DllImport(
+ "advapi32.dll",
+ EntryPoint = "OpenServiceW",
+ ExactSpelling = true,
+ CharSet = CharSet.Unicode,
+ SetLastError = true
+ )]
+ private static extern IntPtr OpenService(
+ IntPtr scManager,
+ string serviceName,
+ int desiredAccess
+ );
+
+ [DllImport("advapi32.dll", SetLastError = true)]
+ [return: MarshalAs(UnmanagedType.Bool)]
+ private static extern bool QueryServiceConfig(
+ IntPtr service,
+ IntPtr queryServiceConfig,
+ int bufferSize,
+ out int bytesNeeded
+ );
+
+ [DllImport("advapi32.dll", SetLastError = true)]
+ [return: MarshalAs(UnmanagedType.Bool)]
+ private static extern bool QueryServiceConfig2(
+ IntPtr service,
+ uint infoLevel,
+ IntPtr buffer,
+ int bufferSize,
+ out int bytesNeeded
+ );
+
+ [DllImport(
+ "advapi32.dll",
+ EntryPoint = "ChangeServiceConfigW",
+ ExactSpelling = true,
+ CharSet = CharSet.Unicode,
+ SetLastError = true
+ )]
+ [return: MarshalAs(UnmanagedType.Bool)]
+ private static extern bool ChangeServiceConfig(
+ IntPtr service,
+ uint serviceType,
+ uint startType,
+ uint errorControl,
+ string? binaryPathName,
+ string? loadOrderGroup,
+ IntPtr tagId,
+ string? dependencies,
+ string? serviceStartName,
+ string? password,
+ string? displayName
+ );
+
+ [DllImport("advapi32.dll", SetLastError = true)]
+ [return: MarshalAs(UnmanagedType.Bool)]
+ private static extern bool ChangeServiceConfig2(
+ IntPtr service,
+ uint infoLevel,
+ ref SERVICE_DELAYED_AUTO_START_INFO info
+ );
+
+ [DllImport("advapi32.dll", SetLastError = true)]
+ [return: MarshalAs(UnmanagedType.Bool)]
+ private static extern bool CloseServiceHandle(IntPtr serviceHandle);
}
diff --git a/optimizerDuck/Services/System/Primitives/ServiceStrings.cs b/optimizerDuck/Services/System/Primitives/ServiceStrings.cs
index 5676349..32a56b5 100644
--- a/optimizerDuck/Services/System/Primitives/ServiceStrings.cs
+++ b/optimizerDuck/Services/System/Primitives/ServiceStrings.cs
@@ -46,7 +46,7 @@ public static class ServiceStrings
public const string ServiceErrorChangeStartupTypeFailed =
"Failed to change startup type for service";
public const string ServiceErrorChangeStartupTypeFailedTemplate =
- "Failed to change service '{0}' to {1} startup. sc.exe exited with {2}: {3}";
+ "Failed to change service '{0}' to {1} startup. Windows error {2}: {3}";
public const string ServiceErrorQueryFailed = "Failed to query service '{0}'";
public const string RevertDataUnloadableDescription =
@@ -67,6 +67,15 @@ public static class ServiceStrings
public const string StartupAppErrorUnsupportedLocation =
"Cannot toggle startup app '{0}': its location is not supported";
+ public const string HibernationName = "Hibernation";
+ public const string HibernationDescriptionDisable = "Disable hibernation and Fast Startup";
+ public const string HibernationErrorChangeFailed =
+ "Failed to change the hibernation file state: {0}";
+
+ public const string UsbPowerName = "USB power";
+ public const string UsbPowerDescriptionDisable = "Disable USB power saving for {0} device(s)";
+ public const string UsbPowerErrorChangeFailed = "Failed to change USB power saving";
+
/// <summary>Formats a template with invariant culture (same as Loc.Invariant did).</summary>
public static string Format(string template, params object?[] args) =>
string.Format(CultureInfo.InvariantCulture, template, args);
diff --git a/optimizerDuck/Services/System/Primitives/UsbPowerService.cs b/optimizerDuck/Services/System/Primitives/UsbPowerService.cs
new file mode 100644
index 0000000..46d064e
--- /dev/null
+++ b/optimizerDuck/Services/System/Primitives/UsbPowerService.cs
@@ -0,0 +1,116 @@
+using System.Management;
+using System.Runtime.Versioning;
+
+namespace optimizerDuck.Services.System.Primitives;
+
+/// <summary>
+/// Per-device USB power management over <c>root\wmi</c>'s <c>MSPower_DeviceEnable</c>, using the
+/// in-process WMI client (via <c>WmiHelper</c>) instead of a PowerShell script.
+/// Microsoft does not document this WMI class and documents no API for the per-device "allow the
+/// computer to turn off this device" setting, so the surface underneath is unchanged - only the
+/// client is. Every operation fails open: no devices, a failed query, or a refused write never
+/// throws out of this service.
+/// </summary>
+[SupportedOSPlatform("windows")]
+public static class UsbPowerService
+{
+ private const string NamespacePath = @"root\wmi";
+ private const string RootHubMarker = @"USB\ROOT";
+ private const string DeviceQuery = "SELECT InstanceName, Enable FROM MSPower_DeviceEnable";
+
+ /// <summary>One device and the USB power-management state Windows reports for it.</summary>
+ /// <param name="InstanceName">The WMI device instance name (used to match on revert).</param>
+ /// <param name="Enable">Whether Windows may power the device down to save energy.</param>
+ public sealed record UsbPowerState(string InstanceName, bool Enable);
+
+ /// <summary>How many devices a write pass actually changed (already-correct devices are left alone).</summary>
+ public sealed record UsbPowerWriteResult(int ChangedCount);
+
+ /// <summary>
+ /// Captures the current state of every USB root-hub device, which is what a revert restores.
+ /// Empty when the class is unavailable, so callers treat it as "nothing to do".
+ /// </summary>
+ public static IReadOnlyList<UsbPowerState> Capture()
+ {
+ return WmiHelper.Query(
+ DeviceQuery,
+ static devices =>
+ (IReadOnlyList<UsbPowerState>)
+ devices
+ .Select(ToState)
+ .Where(static state => state is not null)
+ .Select(static state => state!)
+ .ToList(),
+ NamespacePath
+ ) ?? [];
+ }
+
+ /// <summary>
+ /// Turns power saving off for every root-hub device that currently has it on. Null when the
+ /// query failed, so a caller can record a failed change instead of an empty success.
+ /// </summary>
+ public static UsbPowerWriteResult? Disable()
+ {
+ return Write(static _ => false);
+ }
+
+ /// <summary>
+ /// Restores captured states, writing only the devices whose state differs from the captured
+ /// one. Null when the query failed.
+ /// </summary>
+ public static UsbPowerWriteResult? Restore(IEnumerable<UsbPowerState> captured)
+ {
+ var wanted = captured.ToDictionary(
+ static state => state.InstanceName,
+ static state => state.Enable,
+ StringComparer.OrdinalIgnoreCase
+ );
+
+ return Write(state =>
+ wanted.TryGetValue(state.InstanceName, out var enable) ? enable : null
+ );
+ }
+
+ /// <summary>
+ /// Applies <paramref name="target" /> to every matching device; a null target means "leave
+ /// this device alone". Devices already in the requested state are not written.
+ /// </summary>
+ private static UsbPowerWriteResult? Write(Func<UsbPowerState, bool?> target)
+ {
+ return WmiHelper.Query(
+ DeviceQuery,
+ devices =>
+ {
+ var changed = 0;
+ foreach (var device in devices)
+ {
+ var state = ToState(device);
+ if (state is null)
+ continue;
+
+ var want = target(state);
+ if (want is null || want == state.Enable)
+ continue;
+
+ device["Enable"] = want.Value;
+ device.Put();
+ changed++;
+ }
+
+ return new UsbPowerWriteResult(changed);
+ },
+ NamespacePath
+ );
+ }
+
+ private static UsbPowerState? ToState(ManagementObject device)
+ {
+ if (device["InstanceName"] is not string name || string.IsNullOrWhiteSpace(name))
+ return null;
+
+ if (!name.Contains(RootHubMarker, StringComparison.OrdinalIgnoreCase))
+ return null;
+
+ return new UsbPowerState(name, device["Enable"] is true);
+ }
+}
diff --git a/optimizerDuck/Services/System/SystemInfoService.cs b/optimizerDuck/Services/System/SystemInfoService.cs
index e129adf..1087626 100644
--- a/optimizerDuck/Services/System/SystemInfoService.cs
+++ b/optimizerDuck/Services/System/SystemInfoService.cs
@@ -2118,8 +2118,10 @@ public sealed class SystemInfoService : IDisposable
v.DriveLetter,
v.IsSystemDrive ? " [System]" : "",
v.MediaType,
- v.TotalBytes / (1024.0 * 1024.0 * 1024.0),
- v.FreeBytes / (1024.0 * 1024.0 * 1024.0),
+ // Integer division on purpose: a whole-gigabyte figure reads like Explorer's,
+ // while the double it came from would log 109.17089462280273.
+ v.TotalBytes / (1024L * 1024 * 1024),
+ v.FreeBytes / (1024L * 1024 * 1024),
v.Model is not null ? $" - {v.Model}" : ""
);
}
diff --git a/optimizerDuck/Services/System/SystemRestoreService.cs b/optimizerDuck/Services/System/SystemRestoreService.cs
new file mode 100644
index 0000000..c8d3650
--- /dev/null
+++ b/optimizerDuck/Services/System/SystemRestoreService.cs
@@ -0,0 +1,251 @@
+using System.Management;
+using System.Runtime.Versioning;
+using Microsoft.Extensions.Logging;
+using optimizerDuck.Domain.Optimizations.Models.Services;
+using optimizerDuck.Services.System.Primitives;
+
+namespace optimizerDuck.Services.System;
+
+/// <summary>
+/// System Restore over the documented <c>SystemRestore</c> class in <c>root\default</c> - the
+/// same subsystem that backs <c>Checkpoint-Computer</c> and <c>Enable-ComputerRestore</c>, without
+/// a child process. Single owner of every System Restore WMI call in the app.
+/// Reads take ids only; mutating calls take an optional <see cref="ILogger" /> (default null),
+/// return typed results carrying the real native status, and record nothing - so a restore-point
+/// manager tool can reuse this service exactly like a tool reuses
+/// <see cref="PowerPlanService" />. Virtual members are the hand-double seam for tests, because
+/// System Restore needs elevation and test hosts do not have it.
+/// </summary>
+[SupportedOSPlatform("windows")]
+public class SystemRestoreService
+{
+ private const string NamespacePath = @"root\default";
+ private const string ClassName = "SystemRestore";
+
+ private const string FrequencyKey =
+ @"HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\SystemRestore";
+
+ private const string FrequencyValueName = "SystemRestorePointCreationFrequency";
+
+ /// <summary>RestorePointType MODIFY_SETTINGS.</summary>
+ public const uint RestorePointTypeModifySettings = 12;
+
+ /// <summary>EventType BEGIN_SYSTEM_CHANGE.</summary>
+ public const uint EventTypeBeginSystemChange = 100;
+
+ /// <summary>ERROR_SERVICE_DISABLED: System Restore is not enabled for the drive.</summary>
+ public const uint ErrorServiceDisabled = 1058;
+
+ /// <summary>HRESULT_FROM_WIN32(ERROR_SERVICE_DISABLED), the other shape that refusal takes.</summary>
+ public const uint HrServiceDisabled = 0x80070422;
+
+ /// <summary>
+ /// Documented default for <c>SystemRestorePointCreationFrequency</c> when the value is
+ /// absent: 24 hours.
+ /// </summary>
+ public const int DefaultCreationFrequencyMinutes = 24 * 60;
+
+ private readonly ILogger<SystemRestoreService> _logger;
+
+ public SystemRestoreService(ILogger<SystemRestoreService> logger) => _logger = logger;
+
+ /// <summary>One restore point as Windows reports it.</summary>
+ /// <param name="SequenceNumber">The restore point's sequence number.</param>
+ /// <param name="RestorePointType">The documented restore point type (12 = MODIFY_SETTINGS).</param>
+ /// <param name="Description">The description the creating application supplied.</param>
+ /// <param name="CreationTimeUtc">When the point was created, in UTC.</param>
+ public sealed record RestorePointInfo(
+ uint SequenceNumber,
+ uint RestorePointType,
+ string Description,
+ DateTime CreationTimeUtc
+ );
+
+ /// <summary>Outcome of a System Restore operation, with the real native status.</summary>
+ /// <param name="Succeeded">Whether the subsystem reported success.</param>
+ /// <param name="NativeStatus">The return value Windows reported (0 = success).</param>
+ /// <param name="ExceptionText">Throw text when the call itself failed, else null.</param>
+ public sealed record SystemRestoreResult(
+ bool Succeeded,
+ uint NativeStatus,
+ string? ExceptionText = null
+ );
+
+ /// <summary>
+ /// Lists every restore point Windows reports, newest last. Empty when the list cannot be
+ /// read - enumeration needs elevation, and a machine with protection off has none.
+ /// </summary>
+ public virtual IReadOnlyList<RestorePointInfo> ListRestorePoints()
+ {
+ return WmiHelper.Query(
+ $"SELECT SequenceNumber, Description, RestorePointType, CreationTime FROM {ClassName}",
+ instances =>
+ {
+ var points = new List<RestorePointInfo>(instances.Count);
+ foreach (var instance in instances)
+ {
+ if (instance["CreationTime"] is not string raw)
+ continue;
+
+ try
+ {
+ points.Add(
+ new RestorePointInfo(
+ instance["SequenceNumber"] is uint sequence ? sequence : 0u,
+ instance["RestorePointType"] is uint type ? type : 0u,
+ instance["Description"] as string ?? string.Empty,
+ ManagementDateTimeConverter.ToDateTime(raw).ToUniversalTime()
+ )
+ );
+ }
+ catch (ArgumentException)
+ {
+ // Skip an unparsable timestamp rather than failing the whole read.
+ _logger.LogDebug(
+ "Skipped a restore point with an unreadable CreationTime: {Raw}",
+ raw
+ );
+ }
+ }
+
+ return (IReadOnlyList<RestorePointInfo>)points;
+ },
+ NamespacePath
+ ) ?? [];
+ }
+
+ /// <summary>Newest restore point, or null when there is none or the list cannot be read.</summary>
+ public virtual DateTime? GetNewestRestorePointUtc()
+ {
+ DateTime? newest = null;
+ foreach (var point in ListRestorePoints())
+ {
+ if (newest is null || point.CreationTimeUtc > newest.Value)
+ newest = point.CreationTimeUtc;
+ }
+
+ return newest;
+ }
+
+ /// <summary>
+ /// The documented creation frequency in minutes: 0 means Windows never skips, an absent
+ /// value means <see cref="DefaultCreationFrequencyMinutes" />.
+ /// </summary>
+ public virtual int GetCreationFrequencyMinutes()
+ {
+ if (
+ RegistryService.TryReadValue(
+ new RegistryItem(FrequencyKey, FrequencyValueName),
+ out var raw,
+ _logger
+ ) && int.TryParse(raw?.ToString(), out var configured)
+ )
+ return configured;
+
+ return DefaultCreationFrequencyMinutes;
+ }
+
+ /// <summary>
+ /// Whether Windows would refuse a new point because one was created inside the frequency
+ /// window. Unreadable state fails open (false), so a caller attempts the create instead of
+ /// blocking the user on a guess.
+ /// </summary>
+ public virtual bool IsWithinCreationThrottle(DateTime nowUtc)
+ {
+ return IsWithinCreationThrottle(
+ GetCreationFrequencyMinutes(),
+ GetNewestRestorePointUtc(),
+ nowUtc
+ );
+ }
+
+ /// <summary>Creates a restore point. Needs elevation.</summary>
+ public virtual SystemRestoreResult CreateRestorePoint(
+ string description,
+ uint restorePointType = RestorePointTypeModifySettings,
+ uint eventType = EventTypeBeginSystemChange
+ )
+ {
+ return Invoke(
+ "CreateRestorePoint",
+ parameters =>
+ {
+ parameters["Description"] = description;
+ parameters["RestorePointType"] = restorePointType;
+ parameters["EventType"] = eventType;
+ }
+ );
+ }
+
+ /// <summary>Enables System Protection for one drive, for example <c>C:</c>. Needs elevation.</summary>
+ public virtual SystemRestoreResult EnableProtection(string drive)
+ {
+ return Invoke("Enable", parameters => parameters["Drive"] = drive);
+ }
+
+ /// <summary>Disables System Protection for one drive. Needs elevation.</summary>
+ public virtual SystemRestoreResult DisableProtection(string drive)
+ {
+ return Invoke("Disable", parameters => parameters["Drive"] = drive);
+ }
+
+ /// <summary>
+ /// Whether a status means System Protection is not enabled for the drive. Codes only:
+ /// message text is localizable and must never decide this.
+ /// </summary>
+ public static bool IsProtectionDisabledStatus(uint status) =>
+ status is ErrorServiceDisabled or HrServiceDisabled;
+
+ /// <summary>
+ /// The throttle rule on its own: Windows skips a create when the newest point is inside the
+ /// window, so exactly-at-the-boundary is not throttled.
+ /// </summary>
+ internal static bool IsWithinCreationThrottle(
+ int frequencyMinutes,
+ DateTime? newestRestorePointUtc,
+ DateTime nowUtc
+ )
+ {
+ if (frequencyMinutes <= 0 || newestRestorePointUtc is null)
+ return false;
+
+ return (nowUtc - newestRestorePointUtc.Value).TotalMinutes < frequencyMinutes;
+ }
+
+ /// <summary>
+ /// Invokes one <c>SystemRestore</c> method and reports its <c>ReturnValue</c>. A throw (no
+ /// elevation, subsystem unavailable) comes back as exception text with
+ /// <see cref="uint.MaxValue" />, a value no documented return code uses.
+ /// </summary>
+ private SystemRestoreResult Invoke(string method, Action<ManagementBaseObject> fillParameters)
+ {
+ try
+ {
+ var scope = new ManagementScope(NamespacePath);
+ using var restoreClass = new ManagementClass(
+ scope,
+ new ManagementPath(ClassName),
+ null
+ );
+ using var inParameters = restoreClass.GetMethodParameters(method);
+ fillParameters(inParameters);
+
+ using var outParameters = restoreClass.InvokeMethod(method, inParameters, null);
+ var status = outParameters?["ReturnValue"] is uint value ? value : 0u;
+
+ if (status != 0 && !IsProtectionDisabledStatus(status))
+ _logger.LogWarning(
+ "[SYSTEMRESTORE][{Method}] failed with native status 0x{Status:X8}",
+ method,
+ status
+ );
+
+ return new SystemRestoreResult(status == 0, status);
+ }
+ catch (Exception ex)
+ {
+ _logger.LogWarning(ex, "[SYSTEMRESTORE][{Method}] threw", method);
+ return new SystemRestoreResult(false, uint.MaxValue, ex.Message);
+ }
+ }
+}
diff --git a/optimizerDuck/Services/UI/DiskCleanupService.cs b/optimizerDuck/Services/UI/DiskCleanupService.cs
index fb30e29..6cc4d51 100644
--- a/optimizerDuck/Services/UI/DiskCleanupService.cs
+++ b/optimizerDuck/Services/UI/DiskCleanupService.cs
@@ -8,8 +8,10 @@ using CleanupItem = optimizerDuck.Domain.Optimizations.Models.Cleanup.CleanupIte
namespace optimizerDuck.Services.UI;
-public class DiskCleanupService(ILogger<DiskCleanupService> logger, ShellService shellService)
+public class DiskCleanupService(ILogger<DiskCleanupService> logger)
{
+ private const string RecycleBinItemId = "RecycleBin";
+
private static readonly string DotNetTempPath =
Path.GetFullPath(Path.Combine(Path.GetTempPath(), ".net"))
.TrimEnd(Path.DirectorySeparatorChar) + Path.DirectorySeparatorChar;
@@ -70,10 +72,11 @@ public class DiskCleanupService(ILogger<DiskCleanupService> logger, ShellService
},
new CleanupItem
{
- Id = "RecycleBin",
+ Id = RecycleBinItemId,
NameKey = "DiskCleanup.Item.RecycleBin",
DescriptionKey = "DiskCleanup.Item.RecycleBin.Description",
- Path = "Clear-RecycleBin -Force -ErrorAction SilentlyContinue",
+ // Not a directory: size and emptying come from the shell Recycle Bin APIs.
+ Path = string.Empty,
Icon = SymbolRegular.Delete24,
IsCommand = true,
},
@@ -105,40 +108,15 @@ public class DiskCleanupService(ILogger<DiskCleanupService> logger, ShellService
item.IsScanning = true;
try
{
- if (item.IsCommand)
+ if (item.Id == RecycleBinItemId)
{
- // For RecycleBin, estimate size via PowerShell
- if (item.Id == "RecycleBin")
- {
- var script =
- "$items = (New-Object -ComObject Shell.Application).NameSpace(0xA).Items(); "
- + "if ($null -ne $items) { "
- + " $measure = $items | Measure-Object -Property Size -Sum; "
- + " $sum = if ($null -ne $measure.Sum) { $measure.Sum } else { 0 }; "
- + " $count = if ($null -ne $items.Count) { $items.Count } else { 0 }; "
- + " Write-Output \"$sum|$count\" "
- + "} else { Write-Output '0|0' }";
-
- var result = await shellService.QueryPowerShellAsync(script, logger);
- var parts = result.Stdout.Trim().Split('|');
- if (
- parts.Length == 2
- && long.TryParse(parts[0], out var size)
- && long.TryParse(parts[1], out var count)
- )
- {
- item.SizeBytes = size;
- item.FileCount = count;
- }
- else
- {
- item.SizeBytes = 0;
- item.FileCount = 0;
- }
- }
+ var totals = RecycleBinService.Query();
+ item.SizeBytes = totals.SizeBytes;
+ item.FileCount = totals.ItemCount;
}
- else
+ else if (!item.IsCommand)
{
+ // Command items have no path to walk; their size stays unknown until they run.
var metrics = await Task.Run(() => CalculateDirectoryMetrics(item.Path, item.Id));
item.SizeBytes = metrics.Size;
item.FileCount = metrics.Count;
@@ -180,28 +158,27 @@ public class DiskCleanupService(ILogger<DiskCleanupService> logger, ShellService
try
{
- if (item.IsCommand)
+ if (item.Id == RecycleBinItemId)
{
var sizeBefore = item.SizeBytes;
- var result = await shellService.QueryPowerShellAsync(item.Path, logger);
- if (result.ExitCode == 0)
+ var (succeeded, errorCode) = RecycleBinService.Empty();
+ if (succeeded)
{
freedBytes = sizeBefore;
logger.LogInformation(
- "Cleaned {ItemId} via command, freed ~{Size}",
+ "Emptied {ItemId} via shell, freed ~{Size}",
item.Id,
CleanupItem.FormatBytes(freedBytes)
);
}
else
{
- // Never report freed space for a command that failed; only the exit
- // code distinguishes "cleaned" from "ran but did nothing".
+ // Never report freed space for an empty that failed; the HRESULT is the only
+ // thing that distinguishes "emptied" from "did nothing".
logger.LogError(
- "Clean command for {ItemId} failed with exit code {ExitCode}: {Error}",
+ "Emptying {ItemId} failed with HRESULT 0x{Code:X8}",
item.Id,
- result.ExitCode,
- result.Stderr
+ errorCode
);
}
}
diff --git a/optimizerDuck/Windows/Services/ScStartupTypeParser.cs b/optimizerDuck/Windows/Services/ScStartupTypeParser.cs
deleted file mode 100644
index 40e6a9a..0000000
--- a/optimizerDuck/Windows/Services/ScStartupTypeParser.cs
+++ /dev/null
@@ -1,48 +0,0 @@
-using System.Text.RegularExpressions;
-using optimizerDuck.Domain.Optimizations.Models.Services;
-
-namespace optimizerDuck.Windows.Services;
-
-/// <summary>
-/// Shared parser for <c>sc.exe qc</c> START_TYPE output, used by
-/// <c>ServiceProcessService</c>.
-/// </summary>
-public static partial class ScStartupTypeParser
-{
- [GeneratedRegex(@"^\s*\S+\s*:\s*([0-4])\s(.+)$")]
- private static partial Regex StartTypeLineRegex();
-
- [GeneratedRegex(@"\([^)]+\)", RegexOptions.IgnoreCase)]
- private static partial Regex DelayedRegex();
-
- public static ServiceStartupType? Parse(string stdout) => ParseWithMatch(stdout).Type;
-
- public static (ServiceStartupType? Type, bool Matched) ParseWithMatch(string stdout)
- {
- var lines = stdout.Split(['\r', '\n'], StringSplitOptions.RemoveEmptyEntries);
- foreach (var line in lines)
- {
- var match = StartTypeLineRegex().Match(line);
- if (!match.Success)
- continue;
-
- var startValue = int.Parse(match.Groups[1].Value);
- var isDelayed = DelayedRegex().IsMatch(match.Groups[2].Value);
-
- return (
- startValue switch
- {
- 2 => isDelayed
- ? ServiceStartupType.AutomaticDelayedStart
- : ServiceStartupType.Automatic,
- 3 => ServiceStartupType.Manual,
- 4 => ServiceStartupType.Disabled,
- _ => null,
- },
- true
- );
- }
-
- return (null, false);
- }
-}