Free, open-source Windows optimization tool for performance, privacy, and simplicity.
C# csharpdebloatdotnetgamingopen-sourceoptimizationoptimizeroptimizerduckperformanceprivacytweakertweakswindowswinui
refactor: native power plans, SystemInfo split and dashboard live data
fatDuckf69bd689779d
diff --git a/.github/contributing/CONTRIBUTING.ja-JP.md b/.github/contributing/CONTRIBUTING.ja-JP.mdindex 339863c..b8d3053 100644--- a/.github/contributing/CONTRIBUTING.ja-JP.md+++ b/.github/contributing/CONTRIBUTING.ja-JP.md@@ -324,7 +324,7 @@ public class Performance : IOptimizationCategory| **すべての例外をキャッチしない** | 例外は上位に伝播。プロバイダーが `OpResult` に成功/失敗を記録し、`OptimizationService` が `ChangeSet` から処理。 || **リバートステップを手動で作成しない** | インスタンス型プロバイダーが `call.Changes` への記録経由で自動的に行う。 || **`context.Logger` を使用する** | 重要な診断情報の記録に使用。 |-| **`context.Snapshot` を使用する** | `OptimizationContext.Snapshot`(`SystemSnapshot`)が RAM、GPU、CPU、OS 情報を提供。条件分岐に使用。 |+| **`context.Snapshot` を使用する** | `OptimizationContext.Snapshot`(`SystemInfo`)が RAM、GPU、CPU、OS 情報を提供。条件分岐に使用。 || **`context.StreamService` を使用する** | リモートリソース(電源プランなど)をダウンロードする最適化向け。 || **必要なら `Condition` を宣言する** | Windows バージョンやハードウェアでゲート — [条件システム](#the-condition-system) を参照。 |@@ -734,7 +734,7 @@ Customize.{CategoryName}.Section.{SectionName} (セクション| 要素 | 目的 ||---|---|-| `ICondition` | コントラクト: `ConditionResult Evaluate(SystemSnapshot snapshot)`。実装には public のパラメータなしコンストラクタが必要(リフレクションでインスタンス化されるため)。 |+| `ICondition` | コントラクト: `ConditionResult Evaluate(SystemInfo snapshot)`。実装には public のパラメータなしコンストラクタが必要(リフレクションでインスタンス化されるため)。 || `ConditionBase` | 共通ヘルパーを持つ任意の基底クラス(例:OS ビルド番号解析の `TryGetOsBuild`)。 || `ConditionResult` | 結果: `Available`、`Unsupported(title, description)`、または `Error()`。ローカライズテキストはプロバイダー経由で遅延解決。 || `ConditionState` | `Available`、`Unsupported`、`Error`。 |@@ -779,7 +779,7 @@ public class TaskbarWidgets : BaseCustomizeSetting { ... }```csharppublic sealed class MyCondition : ConditionBase{- public override ConditionResult Evaluate(SystemSnapshot snapshot)+ public override ConditionResult Evaluate(SystemInfo snapshot){// ConditionBase.TryGetOsBuild は "22631.xxxx" を 22631 に解析if (TryGetOsBuild(snapshot, out var build) && build >= 22000)@@ -938,7 +938,7 @@ services.AddSingleton<IRegistryWatcher, RegistryWatcher>();| サービス | 目的 ||---|---|-| `SystemInfoService` | `OptimizationContext` と条件システムが使う `SystemSnapshot`(CPU、RAM、GPU、OS、ディスク)を提供。 |+| `SystemInfoService` | `OptimizationContext` と条件システムが使う `SystemInfo`(CPU、RAM、GPU、OS、ディスク)を提供。 || `StreamService` | リモートリソース(更新された電源プランなど)をダウンロード。`OptimizationContext.StreamService` 経由。 || `UpdaterService` | GitHub リリースの更新確認。Dashboard に更新プロンプトを表示。 || `RegistryWatcher` | 外部変更を監視して UI にリフレッシュ通知。`IRegistryWatcher` を実装。 |diff --git a/.github/contributing/CONTRIBUTING.tr-TR.md b/.github/contributing/CONTRIBUTING.tr-TR.mdindex 7129d14..f53f9fa 100644--- a/.github/contributing/CONTRIBUTING.tr-TR.md+++ b/.github/contributing/CONTRIBUTING.tr-TR.md@@ -325,7 +325,7 @@ public class Performance : IOptimizationCategory| **Tüm istisnaları yakalamayın** | Yukarı yayılsın. Başarı/başarısızlık `ChangeSet` içinde izlenir; `OptimizationService` istisnaları işler. || **Geri alma adımlarını elle oluşturmayın** | Örnek sağlayıcılar bunu otomatik yapar (`call.Changes` içine kaydeder). `ChangeSet.Add()` ile elle kayıt yapmayın (USB durumları gibi özel sağlayıcı dışı durumlar dışında). || **`context.Logger` kullanın** | Önemli tanılama bilgileri için günlük kaydı sağlar. |-| **`context.Snapshot` kullanın** | `OptimizationContext.Snapshot` (`SystemSnapshot`) RAM, GPU, CPU, OS bilgisi verir. Koşullu mantık için kullanın. |+| **`context.Snapshot` kullanın** | `OptimizationContext.Snapshot` (`SystemInfo`) RAM, GPU, CPU, OS bilgisi verir. Koşullu mantık için kullanın. || **`context.StreamService` kullanın** | Uzak kaynakları (örn. güç planları) indiren optimizasyonlar için. || **Gerekirse `Condition` bildirin** | Windows sürümü veya donanımla kapılayın — [Koşul Sistemi](#the-condition-system) bölümüne bakın. |@@ -738,7 +738,7 @@ Koşullar `Domain/Conditions/` içinde bulunur ve `Services/Conditions/` içinde| Parça | Amaç ||---|---|-| `ICondition` | Sözleşme: `ConditionResult Evaluate(SystemSnapshot snapshot)`. Uygulamaların public parametresiz yapıcıya ihtiyacı vardır (yansıma ile örneklenirler). |+| `ICondition` | Sözleşme: `ConditionResult Evaluate(SystemInfo snapshot)`. Uygulamaların public parametresiz yapıcıya ihtiyacı vardır (yansıma ile örneklenirler). || `ConditionBase` | Paylaşılan yardımcılara sahip isteğe bağlı taban sınıf (örn. OS derleme numarası ayrıştırmak için `TryGetOsBuild`). || `ConditionResult` | Sonuç: `Available`, `Unsupported(title, description)` veya `Error()`. Yerelleştirilmiş metin sağlayıcılar üzerinden tembel çözülür. || `ConditionState` | `Available`, `Unsupported`, `Error`. |@@ -783,7 +783,7 @@ Hazır koşullar `Domain/Conditions/BuiltIn/` içinde bulunur — tam ve güncel```csharppublic sealed class MyCondition : ConditionBase{- public override ConditionResult Evaluate(SystemSnapshot snapshot)+ public override ConditionResult Evaluate(SystemInfo snapshot){// ConditionBase.TryGetOsBuild "22631.xxxx" -> 22631 olarak ayrıştırırif (TryGetOsBuild(snapshot, out var build) && build >= 22000)@@ -943,7 +943,7 @@ services.AddSingleton<IRegistryWatcher, RegistryWatcher>();| Hizmet | Amaç ||---|---|-| `SystemInfoService` | `OptimizationContext` ve koşul sisteminin kullandığı `SystemSnapshot`'ı (CPU, RAM, GPU, OS, disk) sağlar. |+| `SystemInfoService` | `OptimizationContext` ve koşul sisteminin kullandığı `SystemInfo`'ı (CPU, RAM, GPU, OS, disk) sağlar. || `StreamService` | Uzak kaynakları (örn. güncellenmiş güç planı dosyaları) indirir. `OptimizationContext.StreamService` ile kullanılır. || `UpdaterService` | Güncellemeler için GitHub sürümlerini kontrol eder. Dashboard'da güncelleme istemi gösterir. || `RegistryWatcher` | Kayıt defteri anahtarlarını dış değişiklikler için izler ve UI'ya yenileme bildirir. `IRegistryWatcher` uygular. |diff --git a/.gitignore b/.gitignoreindex d08439e..30f4be3 100644--- a/.gitignore+++ b/.gitignore@@ -702,3 +702,4 @@ $RECYCLE.BIN/omp-session-*.htmlcrash_*.logTestResults/+openspec/diff --git a/AGENTS.md b/AGENTS.mdindex 9e9da52..eeed47b 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -47,7 +47,7 @@- `Windows/Services/ScStartupTypeParser.cs` — shared parser for `sc.exe qc` START_TYPE output, used by `ServiceProcessService`.- `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 `SystemSnapshot` + models), `StreamService`, `UpdaterService`, `CrossPageEventBus`, `CrossPageEvents`+ - `System/` — `RegistryWatcher` (+ `IRegistryWatcher`), `SystemInfoService` (defines `SystemInfo` + models), `StreamService`, `UpdaterService`, `CrossPageEventBus`, `CrossPageEvents`- `UI/` — `BloatwareService`, `DiskCleanupService`, `StartupManagerService`- `UI/` — XAML pages, ViewModels, windows, controls, dialogs, styles- `Common/` — extensions, helpers, converters:@@ -87,7 +87,7 @@## Condition System (Compatibility Gating)- Conditions live in `Domain/Conditions/` (`ICondition`, `ConditionBase`, `ConditionResult`, `ConditionState`, `ConditionValidation`, `WindowsBuilds`, `BuiltIn/`). They're evaluated by the static `Services/Conditions/ConditionEvaluator.cs`.- `[Optimization]` and `[CustomizeSetting]` both accept an optional `Condition = typeof(SomeCondition)` where the type implements `ICondition` with a public parameterless constructor.-- `ConditionState` = `Available` | `Unsupported` | `Error`. Only `Unsupported` blocks an item, and only when the item isn't already applied (or hidden by the user). `Error` and an unpopulated `SystemSnapshot` **fail open** (never hide).+- `ConditionState` = `Available` | `Unsupported` | `Error`. Only `Unsupported` blocks an item, and only when the item isn't already applied (or hidden by the user). `Error` and an unpopulated `SystemInfo` (`IsUnknown`) **fail open** (never hide).- `ConditionValidation.Validate(...)` runs at discovery time to fail fast on misconfigured condition metadata.- Custom conditions return `ConditionResult.Available` / `ConditionResult.Unsupported(titleProvider, descriptionProvider)` / `ConditionResult.Error()`. User-facing text must go behind localization providers (`() => Loc.Instance[...]`).diff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex 777b6f9..9321915 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -324,7 +324,7 @@ public class Performance : IOptimizationCategory| **Don't catch all exceptions** | Let them bubble up. `ChangeSet` tracks per-step success/failure; `OptimizationService` handles exceptions. || **Don't manually create revert steps** | Static providers record `Change` entries (with revert steps) into `context.Changes` automatically. || **Use `context.Logger`** | The optimization context provides a logger for important diagnostic info. |-| **Use `context.Snapshot`** | `OptimizationContext.Snapshot` (a `SystemSnapshot`) gives system info: RAM, GPU, CPU, OS. Use it for conditional logic. |+| **Use `context.Snapshot`** | `OptimizationContext.Snapshot` (a `SystemInfo`) gives system info: memory, GPU, CPU, Windows, firmware, security, power, storage. Use it for conditional logic. || **Use `context.StreamService`** | For optimizations that need to download remote resources (e.g. power plans). || **Declare a `Condition` if needed** | Gate the optimization on Windows version or hardware — see [The Condition System](#the-condition-system). |### Available Service Providers@@ -824,8 +824,8 @@ Conditions live in `Domain/Conditions/` and are evaluated by the static `Conditi| Piece | Purpose ||---|---|-| `ICondition` | The contract: `ConditionResult Evaluate(SystemSnapshot snapshot)`. Implementations need a public parameterless constructor (they're instantiated via reflection). |-| `ConditionBase` | Optional base class with shared helpers (e.g., `TryGetOsBuild` for parsing the OS build number). |+| `ICondition` | The contract: `ConditionResult Evaluate(SystemInfo snapshot)`. Implementations need a public parameterless constructor (they're instantiated via reflection). |+| `ConditionBase` | Optional base class with shared helpers (e.g., `TryGetOsBuild` for reading the typed OS build number). || `ConditionResult` | Outcome: `Available`, `Unsupported(title, description)`, or `Error()`. Localized text is resolved lazily via providers. || `ConditionState` | `Available`, `Unsupported`, `Error`. || `ConditionValidation` | Validates `Condition = typeof(...)` metadata at discovery time so misconfigurations fail fast at startup. |@@ -869,9 +869,9 @@ Ready-made conditions live in `Domain/Conditions/BuiltIn/` — check that folder```csharppublic sealed class MyCondition : ConditionBase{- public override ConditionResult Evaluate(SystemSnapshot snapshot)+ public override ConditionResult Evaluate(SystemInfo snapshot){- // ConditionBase.TryGetOsBuild parses "22631.xxxx" -> 22631+ // ConditionBase.TryGetOsBuild reads the typed build numberif (TryGetOsBuild(snapshot, out var build) && build >= 22000)return ConditionResult.Available;@@ -1027,7 +1027,7 @@ services.AddSingleton<IRegistryWatcher, RegistryWatcher>();| Service | Purpose ||---|---|-| `SystemInfoService` | Provides the `SystemSnapshot` (CPU, RAM, GPU, OS, disk) used by `OptimizationContext` and the condition system. |+| `SystemInfoService` | Provides the `SystemInfo` (Windows, CPU, memory, GPUs, firmware, security, power, storage) used by `OptimizationContext` and the condition system. || `StreamService` | Downloads remote resources (e.g., updated power plan files). Used via `OptimizationContext.StreamService`. || `UpdaterService` | Checks GitHub releases for updates. Shows update prompt on Dashboard. || `RegistryWatcher` | Monitors registry keys for external changes and notifies the UI to refresh. Implements `IRegistryWatcher`. |diff --git a/optimizerDuck.Test/Domain/Conditions/ConditionTests.cs b/optimizerDuck.Test/Domain/Conditions/ConditionTests.csindex 0cf5f91..fb34ff4 100644--- a/optimizerDuck.Test/Domain/Conditions/ConditionTests.cs+++ b/optimizerDuck.Test/Domain/Conditions/ConditionTests.cs@@ -14,8 +14,8 @@ public class ConditionTests{#region Snapshot builder- private static SystemSnapshot Snapshot(- string build = "22631",+ private static SystemInfo Snapshot(+ int? build = 22631,GpuVendor gpuVendor = GpuVendor.Unknown,CpuVendor cpuVendor = CpuVendor.Unknown,double ramGb = 0@@ -25,38 +25,31 @@ public class ConditionTestsCpu = new CpuInfo{Name = "Test CPU",- Manufacturer = "TestManufacturer",Vendor = cpuVendor,- Architecture = "64-bit",- Cores = 8,- Threads = 16,- MaxClockMHz = 4000,- CurrentClockMHz = 4000,- L2CacheKB = 0,- L3CacheKB = 0,+ Architecture = Architecture.X64,+ CoreCount = 8,+ ThreadCount = 16,+ MaxFrequencyMhz = 4000,+ CurrentFrequencyMhz = 4000,},- Ram = new RamInfo+ Memory = new MemoryInfo{- TotalGB = ramGb,- TotalMB = (long)(ramGb * 1024),- TotalKB = (long)(ramGb * 1024 * 1024),- AvailableGB = ramGb,- UsedPercent = 0,- UsedGB = 0,+ TotalBytes = (long)(ramGb * 1024 * 1024 * 1024),+ AvailableBytes = (long)(ramGb * 1024 * 1024 * 1024),Modules = [],},- Os = new OsInfo+ Windows = new WindowsInfo{- Name = "Microsoft Windows 11 Pro",- Version = "11",BuildNumber = build,- Edition = "Pro",- Architecture = "64-bit",- DeviceType = DeviceKind.Desktop,- InstallDate = "2024-01-01",- LastBootUpTime = "2024-01-01 00:00",+ Edition = WindowsEdition.Pro,+ Architecture = Architecture.X64,+ DeviceKind = DeviceKind.Desktop,+ InstallDate = new DateTime(2024, 1, 1),+ LastBootTime = new DateTime(2024, 1, 1),},- Bios = BiosInfo.Unknown,+ Firmware = FirmwareInfo.Unknown,+ Security = SecurityInfo.Unknown,+ Power = PowerInfo.Unknown,Gpus =gpuVendor == GpuVendor.Unknown? []@@ -67,11 +60,11 @@ public class ConditionTestsName = "Test GPU",DriverVersion = "1.0",Vendor = gpuVendor,- MemoryMB = 8192,+ VramMB = 8192,},],- PrimaryGpu = null,- Disk = DiskInfo.Unknown,+ Storage = StorageInfo.Unknown,+ Runtime = RuntimeInfo.Unknown,};#endregion@@ -117,65 +110,69 @@ public class ConditionTests#region OS conditions[Theory]- [InlineData("22000")]- [InlineData("22631")]- [InlineData("26100")]- public void Windows11Condition_Win11Builds_Available(string build)+ [InlineData(22000)]+ [InlineData(22631)]+ [InlineData(26100)]+ public void Windows11Condition_Win11Builds_Available(int build){var result = new Windows11Condition().Evaluate(Snapshot(build: build));Assert.Equal(ConditionState.Available, result.State);}[Fact]- public void Windows11Condition_DottedBuild_ParsesMajorVersionOnly()+ public void Windows11Condition_UnknownBuild_Unsupported(){- // Real UBR-suffixed builds (e.g. 24H2 with KB5055627 reports 26100.3915)- // must be compared by major build number only.- var result = new Windows11Condition().Evaluate(Snapshot(build: "26100.3915"));- Assert.Equal(ConditionState.Available, result.State);+ // An unreadable build number never passes a version gate (fail closed),+ // while an entirely unknown snapshot still fails open (see evaluator test).+ var snapshot = Snapshot() with+ {+ Windows = new WindowsInfo(),+ };+ var result = new Windows11Condition().Evaluate(snapshot);+ Assert.Equal(ConditionState.Unsupported, result.State);}[Theory]- [InlineData("10240")]- [InlineData("19045")]- public void Windows11Condition_Win10Builds_Unsupported(string build)+ [InlineData(10240)]+ [InlineData(19045)]+ public void Windows11Condition_Win10Builds_Unsupported(int build){var result = new Windows11Condition().Evaluate(Snapshot(build: build));Assert.Equal(ConditionState.Unsupported, result.State);}[Theory]- [InlineData("10240")]- [InlineData("19045")]- public void Windows10Condition_Win10Builds_Available(string build)+ [InlineData(10240)]+ [InlineData(19045)]+ public void Windows10Condition_Win10Builds_Available(int build){var result = new Windows10Condition().Evaluate(Snapshot(build: build));Assert.Equal(ConditionState.Available, result.State);}[Theory]- [InlineData("22000")]- [InlineData("22631")]- public void Windows10Condition_Win11Builds_Unsupported(string build)+ [InlineData(22000)]+ [InlineData(22631)]+ public void Windows10Condition_Win11Builds_Unsupported(int build){var result = new Windows10Condition().Evaluate(Snapshot(build: build));Assert.Equal(ConditionState.Unsupported, result.State);}[Theory]- [InlineData("26100")]- [InlineData("26120")]- public void Windows11_24H2OrGreaterCondition_24H2Builds_Available(string build)+ [InlineData(26100)]+ [InlineData(26120)]+ public void Windows11_24H2OrGreaterCondition_24H2Builds_Available(int build){var result = new Windows11_24H2OrGreaterCondition().Evaluate(Snapshot(build: build));Assert.Equal(ConditionState.Available, result.State);}[Theory]- [InlineData("22631")]- [InlineData("22000")]- [InlineData("19045")]- public void Windows11_24H2OrGreaterCondition_OlderBuilds_Unsupported(string build)+ [InlineData(22631)]+ [InlineData(22000)]+ [InlineData(19045)]+ public void Windows11_24H2OrGreaterCondition_OlderBuilds_Unsupported(int build){var result = new Windows11_24H2OrGreaterCondition().Evaluate(Snapshot(build: build));Assert.Equal(ConditionState.Unsupported, result.State);@@ -188,28 +185,28 @@ public class ConditionTests[Fact]public void AmdGpuCondition_AmdGpu_Available(){- var result = new AmdGpuCondition().Evaluate(Snapshot(gpuVendor: GpuVendor.AMD));+ var result = new AmdGpuCondition().Evaluate(Snapshot(gpuVendor: GpuVendor.Amd));Assert.Equal(ConditionState.Available, result.State);}[Fact]public void AmdGpuCondition_NvidiaGpu_Unsupported(){- var result = new AmdGpuCondition().Evaluate(Snapshot(gpuVendor: GpuVendor.NVIDIA));+ var result = new AmdGpuCondition().Evaluate(Snapshot(gpuVendor: GpuVendor.Nvidia));Assert.Equal(ConditionState.Unsupported, result.State);}[Fact]public void NvidiaGpuCondition_NvidiaGpu_Available(){- var result = new NvidiaGpuCondition().Evaluate(Snapshot(gpuVendor: GpuVendor.NVIDIA));+ var result = new NvidiaGpuCondition().Evaluate(Snapshot(gpuVendor: GpuVendor.Nvidia));Assert.Equal(ConditionState.Available, result.State);}[Fact]public void NvidiaGpuCondition_AmdGpu_Unsupported(){- var result = new NvidiaGpuCondition().Evaluate(Snapshot(gpuVendor: GpuVendor.AMD));+ var result = new NvidiaGpuCondition().Evaluate(Snapshot(gpuVendor: GpuVendor.Amd));Assert.Equal(ConditionState.Unsupported, result.State);}@@ -230,14 +227,14 @@ public class ConditionTests[Fact]public void IntelCpuCondition_AmdCpu_Unsupported(){- var result = new IntelCpuCondition().Evaluate(Snapshot(cpuVendor: CpuVendor.AMD));+ var result = new IntelCpuCondition().Evaluate(Snapshot(cpuVendor: CpuVendor.Amd));Assert.Equal(ConditionState.Unsupported, result.State);}[Fact]public void AmdCpuCondition_AmdCpu_Available(){- var result = new AmdCpuCondition().Evaluate(Snapshot(cpuVendor: CpuVendor.AMD));+ var result = new AmdCpuCondition().Evaluate(Snapshot(cpuVendor: CpuVendor.Amd));Assert.Equal(ConditionState.Available, result.State);}@@ -346,7 +343,7 @@ public class ConditionTests#region ConditionEvaluator- private static ConditionResult Evaluate(Type? type, SystemSnapshot snapshot) =>+ private static ConditionResult Evaluate(Type? type, SystemInfo snapshot) =>ConditionEvaluator.Evaluate(type, snapshot, NullLogger.Instance);[Fact]@@ -358,7 +355,7 @@ public class ConditionTests[Fact]public void ConditionEvaluator_ValidType_ReturnsEvaluatedResult(){- var result = Evaluate(typeof(Windows11Condition), Snapshot(build: "19045"));+ var result = Evaluate(typeof(Windows11Condition), Snapshot(build: 19045));Assert.Equal(ConditionState.Unsupported, result.State);}@@ -368,23 +365,23 @@ public class ConditionTests// An unpopulated snapshot (detection not finished/failed) never hides an item.Assert.Equal(ConditionState.Available,- Evaluate(typeof(Windows11Condition), SystemSnapshot.Unknown).State+ Evaluate(typeof(Windows11Condition), SystemInfo.Unknown).State);Assert.Equal(ConditionState.Available,- Evaluate(typeof(Windows11_24H2OrGreaterCondition), SystemSnapshot.Unknown).State+ Evaluate(typeof(Windows11_24H2OrGreaterCondition), SystemInfo.Unknown).State);Assert.Equal(ConditionState.Available,- Evaluate(typeof(NvidiaGpuCondition), SystemSnapshot.Unknown).State+ Evaluate(typeof(NvidiaGpuCondition), SystemInfo.Unknown).State);Assert.Equal(ConditionState.Available,- Evaluate(typeof(SixteenGbRamCondition), SystemSnapshot.Unknown).State+ Evaluate(typeof(SixteenGbRamCondition), SystemInfo.Unknown).State);Assert.Equal(ConditionState.Available,- Evaluate(typeof(IntelCpuCondition), SystemSnapshot.Unknown).State+ Evaluate(typeof(IntelCpuCondition), SystemInfo.Unknown).State);}@@ -412,7 +409,7 @@ public class ConditionTestsitems,t => t,(t, r) => applied.Add(r),- Snapshot(build: "19045"),+ Snapshot(build: 19045),NullLogger.Instance);@@ -423,7 +420,7 @@ public class ConditionTestsprivate sealed class ThrowingCondition : ConditionBase{- public override ConditionResult Evaluate(SystemSnapshot snapshot)+ public override ConditionResult Evaluate(SystemInfo snapshot){throw new InvalidOperationException("boom");}diff --git a/optimizerDuck.Test/Domain/Revert/Steps/PowerPlanRevertStepTests.cs b/optimizerDuck.Test/Domain/Revert/Steps/PowerPlanRevertStepTests.csnew file mode 100644index 0000000..01cc178--- /dev/null+++ b/optimizerDuck.Test/Domain/Revert/Steps/PowerPlanRevertStepTests.cs@@ -0,0 +1,34 @@+using Microsoft.Extensions.Logging.Abstractions;+using Newtonsoft.Json.Linq;+using optimizerDuck.Domain.Exceptions;+using optimizerDuck.Domain.Revert.Steps;++namespace optimizerDuck.Test.Domain.Revert.Steps;++public class PowerPlanRevertStepTests+{+ [Fact]+ public void RoundTrip_PreservesSchemeIds()+ {+ var original = new PowerPlanRevertStep+ {+ PreviousSchemeId = Guid.Parse("381b4222-f694-41f0-9685-ff5bb260df2e"),+ InstalledSchemeId = Guid.Parse("8ae61178-2c55-43f2-afb2-f83725823657"),+ };++ var restored = PowerPlanRevertStep.FromData(original.ToData());++ Assert.Equal(original.PreviousSchemeId, restored.PreviousSchemeId);+ Assert.Equal(original.InstalledSchemeId, restored.InstalledSchemeId);+ Assert.Equal("PowerPlan", restored.Type);+ }++ [Fact]+ public void FromData_MissingIds_ThrowsFailClosed()+ {+ Assert.Throws<StepExecutionException>(() => PowerPlanRevertStep.FromData(new JObject()));+ Assert.Throws<StepExecutionException>(() =>+ PowerPlanRevertStep.FromData(JToken.Parse("{}"))+ );+ }+}diff --git a/optimizerDuck.Test/Domain/Revert/Steps/RevertStepSerializationTests.cs b/optimizerDuck.Test/Domain/Revert/Steps/RevertStepSerializationTests.csindex 264dbb0..8736f63 100644--- a/optimizerDuck.Test/Domain/Revert/Steps/RevertStepSerializationTests.cs+++ b/optimizerDuck.Test/Domain/Revert/Steps/RevertStepSerializationTests.cs@@ -1,5 +1,6 @@using Microsoft.Win32;using Newtonsoft.Json.Linq;+using optimizerDuck.Domain.Exceptions;using optimizerDuck.Domain.Optimizations.Models.Services;using optimizerDuck.Domain.Revert.Steps;@@ -485,4 +486,33 @@ public class RevertStepSerializationTestsAssert.Equal(RevertAction.RestorePrevious, restored.SubSteps[1].Action);Assert.Equal("Value1", restored.SubSteps[1].Name);}++ [Fact]+ public void PowerSettingRevertStep_RoundTrip_PreservesAllProperties()+ {+ var original = new PowerSettingRevertStep+ {+ SchemeId = Guid.Parse("381b4222-f694-41f0-9685-ff5bb260df2e"),+ SubgroupId = Guid.Parse("54533251-82be-4824-96c1-47b60b740d00"),+ SettingId = Guid.Parse("893dee8e-2bef-41e0-89c6-b55d0929964c"),+ PreviousAcValue = 100u,+ PreviousDcValue = 50u,+ };++ var json = original.ToData();+ var restored = PowerSettingRevertStep.FromData(json);++ Assert.Equal(original.SchemeId, restored.SchemeId);+ Assert.Equal(original.SubgroupId, restored.SubgroupId);+ Assert.Equal(original.SettingId, restored.SettingId);+ Assert.Equal(100u, restored.PreviousAcValue);+ Assert.Equal(50u, restored.PreviousDcValue);+ Assert.Equal("PowerSetting", restored.Type);+ }++ [Fact]+ public void PowerSettingRevertStep_MissingValues_ThrowsFailClosed()+ {+ Assert.Throws<StepExecutionException>(() => PowerSettingRevertStep.FromData(new JObject()));+ }}diff --git a/optimizerDuck.Test/Domain/Revert/Steps/ScheduledTaskRevertStepTests.cs b/optimizerDuck.Test/Domain/Revert/Steps/ScheduledTaskRevertStepTests.csindex 397c98f..bd55ff5 100644--- a/optimizerDuck.Test/Domain/Revert/Steps/ScheduledTaskRevertStepTests.cs+++ b/optimizerDuck.Test/Domain/Revert/Steps/ScheduledTaskRevertStepTests.cs@@ -18,7 +18,7 @@ public class ScheduledTaskRevertStepTests};var ex = await Assert.ThrowsAsync<StepExecutionException>(() =>- step.ExecuteAsync(TestShell.New(), NullLogger.Instance)+ step.ExecuteAsync(TestShell.Context(), NullLogger.Instance));Assert.Contains("NonExistent", ex.Message);diff --git a/optimizerDuck.Test/Domain/Revert/Steps/ServiceRevertStepTests.cs b/optimizerDuck.Test/Domain/Revert/Steps/ServiceRevertStepTests.csindex 6def822..6e335f9 100644--- a/optimizerDuck.Test/Domain/Revert/Steps/ServiceRevertStepTests.cs+++ b/optimizerDuck.Test/Domain/Revert/Steps/ServiceRevertStepTests.cs@@ -18,7 +18,7 @@ public class ServiceRevertStepTestsOriginalStartupType = ServiceStartupType.Manual,};- var result = await step.ExecuteAsync(TestShell.New(), NullLogger.Instance);+ var result = await step.ExecuteAsync(TestShell.Context(), NullLogger.Instance);Assert.True(result);}diff --git a/optimizerDuck.Test/Services/ApplyRevertComprehensiveTests.cs b/optimizerDuck.Test/Services/ApplyRevertComprehensiveTests.csindex 80000c0..c3ca741 100644--- a/optimizerDuck.Test/Services/ApplyRevertComprehensiveTests.cs+++ b/optimizerDuck.Test/Services/ApplyRevertComprehensiveTests.cs@@ -452,6 +452,7 @@ public class ApplyRevertComprehensiveTestsvar manager = new RevertManager(NullLogger<RevertManager>.Instance,TestShell.New(),+ new PowerPlanService(NullLogger<PowerPlanService>.Instance),TimeProvider.System);var result = await manager.RevertAsync(optimization);@@ -729,6 +730,7 @@ public class ApplyRevertComprehensiveTestsvar manager = new RevertManager(NullLogger<RevertManager>.Instance,TestShell.New(),+ new PowerPlanService(NullLogger<PowerPlanService>.Instance),TimeProvider.System);var result = await manager.RevertAsync(optimization);@@ -944,6 +946,7 @@ public class ApplyRevertComprehensiveTestsvar revertManager = new RevertManager(NullLogger<RevertManager>.Instance,TestShell.New(),+ new PowerPlanService(NullLogger<PowerPlanService>.Instance),TimeProvider.System);await revertManager.AppendRevertStepAsync(@@ -1076,6 +1079,7 @@ public class ApplyRevertComprehensiveTestsvar revertManager = new RevertManager(NullLogger<RevertManager>.Instance,TestShell.New(),+ new PowerPlanService(NullLogger<PowerPlanService>.Instance),TimeProvider.System);var loggerFactory = NullLoggerFactory.Instance;@@ -1091,6 +1095,7 @@ public class ApplyRevertComprehensiveTestsstreamService,contentDialogService,shellService,+ new PowerPlanService(NullLogger<PowerPlanService>.Instance),logger);}diff --git a/optimizerDuck.Test/Services/Managers/RevertManagerTests.cs b/optimizerDuck.Test/Services/Managers/RevertManagerTests.csindex c56c233..4d4ef62 100644--- a/optimizerDuck.Test/Services/Managers/RevertManagerTests.cs+++ b/optimizerDuck.Test/Services/Managers/RevertManagerTests.cs@@ -11,6 +11,7 @@ using optimizerDuck.Domain.Revert.Steps;using optimizerDuck.Domain.UI;using optimizerDuck.Services.Optimization.Providers;using optimizerDuck.Services.Revert;+using optimizerDuck.Services.System;using optimizerDuck.Test.TestDoubles;namespace optimizerDuck.Test.Services.Managers;@@ -100,6 +101,7 @@ public class RevertManagerTestsvar manager = new RevertManager(NullLogger<RevertManager>.Instance,TestShell.New(),+ new PowerPlanService(NullLogger<PowerPlanService>.Instance),TimeProvider.System);var op = new MockOptimization(id);@@ -163,6 +165,7 @@ public class RevertManagerTestsvar manager = new RevertManager(NullLogger<RevertManager>.Instance,TestShell.New(),+ new PowerPlanService(NullLogger<PowerPlanService>.Instance),TimeProvider.System);var result = await manager.RevertAsync(@@ -224,6 +227,7 @@ public class RevertManagerTestsvar manager = new RevertManager(NullLogger<RevertManager>.Instance,TestShell.New(),+ new PowerPlanService(NullLogger<PowerPlanService>.Instance),TimeProvider.System);var result = await manager.RevertAsync(@@ -290,6 +294,7 @@ public class RevertManagerTestsvar manager = new RevertManager(NullLogger<RevertManager>.Instance,TestShell.New(),+ new PowerPlanService(NullLogger<PowerPlanService>.Instance),TimeProvider.System);var result = await manager.RevertAsync(@@ -322,6 +327,7 @@ public class RevertManagerTestsvar manager = new RevertManager(NullLogger<RevertManager>.Instance,TestShell.New(),+ new PowerPlanService(NullLogger<PowerPlanService>.Instance),TimeProvider.System);@@ -372,6 +378,7 @@ public class RevertManagerTestsvar manager = new RevertManager(NullLogger<RevertManager>.Instance,TestShell.New(),+ new PowerPlanService(NullLogger<PowerPlanService>.Instance),TimeProvider.System);@@ -434,6 +441,7 @@ public class RevertManagerTestsvar manager = new RevertManager(NullLogger<RevertManager>.Instance,TestShell.New(),+ new PowerPlanService(NullLogger<PowerPlanService>.Instance),TimeProvider.System);var result = await manager.RevertAsync(@@ -570,7 +578,7 @@ public class RetryableTestRevertStep : IRevertSteppublic string Description => $"Retryable test step {StepId}";- public Task<bool> ExecuteAsync(ShellService _, ILogger logger)+ public Task<bool> ExecuteAsync(RevertContext _, ILogger logger){if (RemainingFailures > 0){diff --git a/optimizerDuck.Test/Services/OptimizationExecutionContextTests.cs b/optimizerDuck.Test/Services/OptimizationExecutionContextTests.csindex 9bdd296..7cd431a 100644--- a/optimizerDuck.Test/Services/OptimizationExecutionContextTests.cs+++ b/optimizerDuck.Test/Services/OptimizationExecutionContextTests.cs@@ -135,7 +135,7 @@ public class MockRevertStep : IRevertSteppublic string Type => "Mock";public string Description => "Mock Description";- public Task<bool> ExecuteAsync(ShellService _, ILogger logger)+ public Task<bool> ExecuteAsync(RevertContext _, ILogger logger){return Task.FromResult(true);}diff --git a/optimizerDuck.Test/Services/OptimizationServiceIntegrationTests.cs b/optimizerDuck.Test/Services/OptimizationServiceIntegrationTests.csindex 5f7a6fb..4d60498 100644--- a/optimizerDuck.Test/Services/OptimizationServiceIntegrationTests.cs+++ b/optimizerDuck.Test/Services/OptimizationServiceIntegrationTests.cs@@ -73,7 +73,7 @@ public class OptimizationServiceIntegrationTests : IDisposablepublic string Type => "Test";public string Description => $"Revert step {StepId}";- public Task<bool> ExecuteAsync(ShellService _, ILogger logger)+ public Task<bool> ExecuteAsync(RevertContext _, ILogger logger){// Simulate revert operationreturn Task.FromResult(true);@@ -114,6 +114,7 @@ public class OptimizationServiceIntegrationTests : IDisposablevar revertManager = new RevertManager(NullLogger<RevertManager>.Instance,TestShell.New(),+ new PowerPlanService(NullLogger<PowerPlanService>.Instance),TimeProvider.System);var systemInfoService = new SystemInfoService(NullLogger<SystemInfoService>.Instance);@@ -126,6 +127,7 @@ public class OptimizationServiceIntegrationTests : IDisposablestreamService,null!,new ShellService(new ProcessRunner(120000)),+ new PowerPlanService(NullLogger<PowerPlanService>.Instance),NullLogger<OptimizationService>.Instance);diff --git a/optimizerDuck.Test/Services/OptimizationServiceTests.cs b/optimizerDuck.Test/Services/OptimizationServiceTests.csindex 6d69caf..641a728 100644--- a/optimizerDuck.Test/Services/OptimizationServiceTests.cs+++ b/optimizerDuck.Test/Services/OptimizationServiceTests.cs@@ -352,6 +352,7 @@ public class OptimizationServiceTestsvar revertManager = new RevertManager(NullLogger<RevertManager>.Instance,TestShell.New(),+ new PowerPlanService(NullLogger<PowerPlanService>.Instance),TimeProvider.System);await revertManager.AppendRevertStepAsync(@@ -482,6 +483,7 @@ public class OptimizationServiceTestsvar revertManager = new RevertManager(NullLogger<RevertManager>.Instance,TestShell.New(),+ new PowerPlanService(NullLogger<PowerPlanService>.Instance),TimeProvider.System);foreach (var recoveredStep in retryResult.RecoveredSteps)@@ -543,6 +545,7 @@ public class OptimizationServiceTestsvar revertManager = new RevertManager(NullLogger<RevertManager>.Instance,TestShell.New(),+ new PowerPlanService(NullLogger<PowerPlanService>.Instance),TimeProvider.System);var loggerFactory = NullLoggerFactory.Instance;@@ -558,6 +561,7 @@ public class OptimizationServiceTestsstreamService,contentDialogService,shellService,+ new PowerPlanService(NullLogger<PowerPlanService>.Instance),logger);}diff --git a/optimizerDuck.Test/Services/OptimizationServices/RegistryServiceTests.cs b/optimizerDuck.Test/Services/OptimizationServices/RegistryServiceTests.csindex 11c0a7c..11fb05f 100644--- a/optimizerDuck.Test/Services/OptimizationServices/RegistryServiceTests.cs+++ b/optimizerDuck.Test/Services/OptimizationServices/RegistryServiceTests.cs@@ -134,7 +134,7 @@ public class RegistryServiceTests : IDisposableAssert.True(delete.Ok, delete.Error);Assert.NotNull(delete.Revert);- Assert.True(await delete.Revert.ExecuteAsync(TestShell.New(), NullLogger.Instance));+ Assert.True(await delete.Revert.ExecuteAsync(TestShell.Context(), NullLogger.Instance));var val = RegistryService.Read<string>(new RegistryItem(key, "A"));Assert.Equal("Hello", val);@@ -151,7 +151,7 @@ public class RegistryServiceTests : IDisposableAssert.True(delete.Ok, delete.Error);Assert.NotNull(delete.Revert);- Assert.True(await delete.Revert.ExecuteAsync(TestShell.New(), NullLogger.Instance));+ Assert.True(await delete.Revert.ExecuteAsync(TestShell.Context(), NullLogger.Instance));var value = RegistryService.Read<string>(new RegistryItem(key, null));Assert.Equal("DefaultHello", value);@@ -177,7 +177,7 @@ public class RegistryServiceTests : IDisposableAssert.Equal("UpdatedDefault", value);Assert.NotNull(second.Revert);- Assert.True(await second.Revert.ExecuteAsync(TestShell.New(), NullLogger.Instance));+ Assert.True(await second.Revert.ExecuteAsync(TestShell.Context(), NullLogger.Instance));var restoredValue = RegistryService.Read<string>(new RegistryItem(key, null));Assert.Equal("OriginalDefault", restoredValue);@@ -222,7 +222,7 @@ public class RegistryServiceTests : IDisposableAssert.Equal("Registry", revertStep.Type);// 4. Act: Execute the Revert Step- Assert.True(await revertStep.ExecuteAsync(TestShell.New(), NullLogger.Instance));+ Assert.True(await revertStep.ExecuteAsync(TestShell.Context(), NullLogger.Instance));// 5. Assert: Verify the tree structure is perfectly restoredAssert.True(RegistryService.KeyExists(new RegistryItem(keyPathC))); // C exists, implies A and B exist@@ -253,7 +253,7 @@ public class RegistryServiceTests : IDisposableAssert.NotNull(create.Revert);// Execute revert- Assert.True(await create.Revert.ExecuteAsync(TestShell.New(), NullLogger.Instance));+ Assert.True(await create.Revert.ExecuteAsync(TestShell.Context(), NullLogger.Instance));// Verify that B and A were cleaned up since they were emptyAssert.False(RegistryService.KeyExists(new RegistryItem(keyPathB)));@@ -304,7 +304,7 @@ public class RegistryServiceTests : IDisposable// Revert all steps in reverse orderforeach (var step in revertSteps.AsEnumerable().Reverse()){- Assert.True(await step.ExecuteAsync(TestShell.New(), NullLogger.Instance));+ Assert.True(await step.ExecuteAsync(TestShell.Context(), NullLogger.Instance));}// Verify original state is restored@@ -433,7 +433,7 @@ public class RegistryServiceTests : IDisposable{var desc = step.Description;executionOrder.Add(desc);- Assert.True(await step.ExecuteAsync(TestShell.New(), NullLogger.Instance));+ Assert.True(await step.ExecuteAsync(TestShell.Context(), NullLogger.Instance));}// Verify state is restoreddiff --git a/optimizerDuck.Test/Services/PowerPlanIntegrationTests.cs b/optimizerDuck.Test/Services/PowerPlanIntegrationTests.csnew file mode 100644index 0000000..2af0314--- /dev/null+++ b/optimizerDuck.Test/Services/PowerPlanIntegrationTests.cs@@ -0,0 +1,187 @@+using Microsoft.Extensions.Logging.Abstractions;+using optimizerDuck.Services.System;++namespace optimizerDuck.Test.Services;++/// <summary>+/// Windows integration tests against real powrprof.dll. No mocks:+/// every test touches the live API and restores what it changed.+/// </summary>+public class PowerPlanIntegrationTests+{+ [Fact]+ public void ListSchemes_ContainsActiveScheme()+ {+ var service = new PowerPlanService(NullLogger<PowerPlanService>.Instance);++ var schemes = service.ListSchemes();+ var activeId = service.GetActiveSchemeId();++ Assert.NotNull(activeId);+ Assert.NotEmpty(schemes);+ Assert.Contains(schemes, s => s.Id == activeId.Value && s.IsActive);+ Assert.All(schemes, s => Assert.False(string.IsNullOrWhiteSpace(s.Name)));+ }++ [Fact]+ public void GetScheme_ActiveScheme_ReturnsMetadata()+ {+ var service = new PowerPlanService(NullLogger<PowerPlanService>.Instance);+ var activeId = service.GetActiveSchemeId();+ Assert.NotNull(activeId);++ var scheme = service.GetScheme(activeId.Value);++ Assert.NotNull(scheme);+ Assert.Equal(activeId.Value, scheme.Id);+ Assert.True(scheme.IsActive);+ Assert.False(string.IsNullOrWhiteSpace(scheme.Name));+ }++ [Fact]+ public void GetScheme_UnknownGuid_ReturnsNull()+ {+ var service = new PowerPlanService(NullLogger<PowerPlanService>.Instance);++ Assert.Null(service.GetScheme(Guid.NewGuid()));+ Assert.False(service.SchemeExists(Guid.NewGuid()));+ }++ [Fact]+ public void ListGroupsAndSettings_ActiveScheme_HasEntries()+ {+ var service = new PowerPlanService(NullLogger<PowerPlanService>.Instance);+ var activeId = service.GetActiveSchemeId();+ Assert.NotNull(activeId);++ var groups = service.ListGroups(activeId.Value);++ Assert.NotEmpty(groups);+ var first = groups[0];+ var settings = service.ListSettings(activeId.Value, first.Id);+ Assert.NotNull(settings);+ }++ [Fact]+ public void SettingValue_RoundTrip_RestoresExactValues()+ {+ var service = new PowerPlanService(NullLogger<PowerPlanService>.Instance);+ var activeId = service.GetActiveSchemeId();+ Assert.NotNull(activeId);++ // Find the first setting with readable AC/DC values.+ PowerSetting? target = null;+ foreach (var group in service.ListGroups(activeId.Value))+ {+ foreach (var setting in service.ListSettings(activeId.Value, group.Id))+ {+ target = setting;+ break;+ }+ if (target is not null)+ break;+ }+ Assert.NotNull(target);++ var origAc = service.GetSettingValue(+ activeId.Value,+ target.GroupId,+ target.Id,+ PowerSource.Ac+ );+ var origDc = service.GetSettingValue(+ activeId.Value,+ target.GroupId,+ target.Id,+ PowerSource.Dc+ );+ Assert.NotNull(origAc);+ Assert.NotNull(origDc);++ try+ {+ var call = new optimizerDuck.Domain.Execution.OpCall { Logger = NullLogger.Instance };+ // Write back the same values: exercises the write path with no semantic change.+ var write = service.SetSetting(+ call,+ activeId.Value,+ target.GroupId,+ target.Id,+ origAc.Value,+ origDc.Value+ );+ Assert.True(write.Ok);++ var rereadAc = service.GetSettingValue(+ activeId.Value,+ target.GroupId,+ target.Id,+ PowerSource.Ac+ );+ var rereadDc = service.GetSettingValue(+ activeId.Value,+ target.GroupId,+ target.Id,+ PowerSource.Dc+ );+ Assert.Equal(origAc.Value, rereadAc);+ Assert.Equal(origDc.Value, rereadDc);+ }+ finally+ {+ var call = new optimizerDuck.Domain.Execution.OpCall { Logger = NullLogger.Instance };+ service.SetSetting(+ call,+ activeId.Value,+ target.GroupId,+ target.Id,+ origAc.Value,+ origDc.Value+ );+ }+ }++ [Fact]+ public void DeleteScheme_ActiveScheme_Refused()+ {+ var service = new PowerPlanService(NullLogger<PowerPlanService>.Instance);+ var activeId = service.GetActiveSchemeId();+ Assert.NotNull(activeId);+ var call = new optimizerDuck.Domain.Execution.OpCall { Logger = NullLogger.Instance };++ var result = service.DeleteScheme(call, activeId.Value);++ Assert.False(result.Ok);+ }++ [Fact]+ public void DuplicateAndDelete_Lifecycle_RoundTrips()+ {+ var service = new PowerPlanService(NullLogger<PowerPlanService>.Instance);+ var activeId = service.GetActiveSchemeId();+ Assert.NotNull(activeId);+ var call = new optimizerDuck.Domain.Execution.OpCall { Logger = NullLogger.Instance };++ var (dupResult, dupId) = service.DuplicateScheme(call, activeId.Value);+ Assert.True(dupResult.Ok);+ Assert.NotNull(dupId);+ Assert.True(service.SchemeExists(dupId.Value));++ try+ {+ var rename = service.SetSchemeName(call, dupId.Value, "optimizerDuck test plan");+ Assert.True(rename.Ok);+ var renamed = service.GetScheme(dupId.Value);+ Assert.Equal("optimizerDuck test plan", renamed?.Name);++ var describe = service.SetSchemeDescription(call, dupId.Value, "test description");+ Assert.True(describe.Ok);+ }+ finally+ {+ var del = service.DeleteScheme(call, dupId.Value);+ Assert.True(del.Ok);+ Assert.False(service.SchemeExists(dupId.Value));+ }+ }+}diff --git a/optimizerDuck.Test/Services/PowerPlanModelsTests.cs b/optimizerDuck.Test/Services/PowerPlanModelsTests.csnew file mode 100644index 0000000..19159f8--- /dev/null+++ b/optimizerDuck.Test/Services/PowerPlanModelsTests.cs@@ -0,0 +1,143 @@+using Microsoft.Extensions.Logging.Abstractions;+using optimizerDuck.Domain.Execution;+using optimizerDuck.Services.System;++namespace optimizerDuck.Test.Services;++public class PowerPlanModelsTests+{+ [Fact]+ public void PowerScheme_RoundTrip_PreservesAllFields()+ {+ var id = Guid.NewGuid();+ var scheme = new PowerScheme+ {+ Id = id,+ Name = "Balanced",+ Description = "Desc",+ IsActive = true,+ };++ Assert.Equal(id, scheme.Id);+ Assert.Equal("Balanced", scheme.Name);+ Assert.Equal("Desc", scheme.Description);+ Assert.True(scheme.IsActive);+ }++ [Fact]+ public void PowerSetting_RawValues_StayNumeric()+ {+ var setting = new PowerSetting+ {+ SchemeId = Guid.NewGuid(),+ GroupId = Guid.NewGuid(),+ Id = Guid.NewGuid(),+ Name = "Setting",+ Kind = PowerValueKind.Unknown,+ AcValue = 42u,+ DcValue = 7u,+ };++ Assert.Equal(42u, setting.AcValue);+ Assert.Equal(7u, setting.DcValue);+ Assert.Equal(PowerValueKind.Unknown, setting.Kind);+ Assert.Null(setting.PossibleValues);+ }++ [Fact]+ public void PowerSetting_RangeMetadata_Optional()+ {+ var setting = new PowerSetting+ {+ SchemeId = Guid.NewGuid(),+ GroupId = Guid.NewGuid(),+ Id = Guid.NewGuid(),+ Name = "Timeout",+ Kind = PowerValueKind.Range,+ AcValue = 0u,+ DcValue = 0u,+ MinValue = 0u,+ MaxValue = 3600u,+ Unit = "seconds",+ };++ Assert.Equal(PowerValueKind.Range, setting.Kind);+ Assert.Equal(3600u, setting.MaxValue);+ Assert.Equal("seconds", setting.Unit);+ }++ [Fact]+ public void PowerSource_HasNoMagicIntegers()+ {+ Assert.Equal(0, (int)PowerSource.Ac);+ Assert.Equal(1, (int)PowerSource.Dc);+ Assert.NotEqual(PowerSource.Ac, PowerSource.Dc);+ }++ [Fact]+ public void PowerPlanError_NativeFailure_CarriesTruth()+ {+ var err = new PowerPlanError+ {+ Operation = "PowerSetActiveScheme",+ SchemeId = Guid.NewGuid(),+ ErrorCode = 1168u,+ };++ Assert.Contains("PowerSetActiveScheme", err.Describe());+ Assert.Contains("1168", err.Describe());+ }++ [Fact]+ public void PowerPlanError_Throw_HasNoFakeCode()+ {+ var err = new PowerPlanError+ {+ Operation = "PowerReadACValueIndex",+ SchemeId = Guid.NewGuid(),+ ExceptionText = "boom",+ };++ Assert.Null(err.ErrorCode);+ Assert.Contains("boom", err.Describe());+ }++ [Fact]+ public void SetSetting_BothNull_FailsWithoutNativeCall()+ {+ var service = new PowerPlanService(NullLogger<PowerPlanService>.Instance);+ var call = new OpCall { Logger = NullLogger.Instance };++ var result = service.SetSetting(+ call,+ Guid.NewGuid(),+ Guid.NewGuid(),+ Guid.NewGuid(),+ null,+ null+ );++ Assert.False(result.Ok);+ Assert.NotNull(result.Error);+ Assert.Single(call.Changes.FailedSteps);+ }++ [Fact]+ public void SetActiveScheme_UnknownActive_FailsClosed()+ {+ // Random GUIDs force the unreadable path only when Windows cannot+ // resolve them; the assertion is fail-closed shape, not live state.+ var service = new PowerPlanService(NullLogger<PowerPlanService>.Instance);+ var call = new OpCall { Logger = NullLogger.Instance };++ var result = service.SetActiveScheme(call, Guid.NewGuid());++ // Either refused (no active readable / unknown scheme) or, on a+ // machine where GetActiveSchemeId works, a recorded native failure.+ // What must never happen: success with a revert for a bogus GUID.+ if (result.Ok)+ Assert.NotNull(call.Changes.SuccessfulSteps);+ else+ Assert.NotNull(result.Error);+ }+}diff --git a/optimizerDuck.Test/Services/SystemInfoTests.cs b/optimizerDuck.Test/Services/SystemInfoTests.csnew file mode 100644index 0000000..658a3a1--- /dev/null+++ b/optimizerDuck.Test/Services/SystemInfoTests.cs@@ -0,0 +1,261 @@+using Microsoft.Extensions.Logging.Abstractions;+using optimizerDuck.Services.System;++namespace optimizerDuck.Test.Services;++public class SystemInfoTests+{+ [Theory]+ [InlineData(22000, true)]+ [InlineData(22631, true)]+ [InlineData(26100, true)]+ [InlineData(19045, false)]+ public void WindowsInfo_IsWindows11_MatchesBuild(int build, bool expected)+ {+ Assert.Equal(expected, new WindowsInfo { BuildNumber = build }.IsWindows11);+ }++ [Theory]+ [InlineData(10240, true)]+ [InlineData(19045, true)]+ [InlineData(22000, false)]+ public void WindowsInfo_IsWindows10_MatchesBuild(int build, bool expected)+ {+ Assert.Equal(expected, new WindowsInfo { BuildNumber = build }.IsWindows10);+ }++ [Fact]+ public void WindowsInfo_NullBuild_IsNeither11Nor10()+ {+ var info = new WindowsInfo();+ Assert.False(info.IsWindows11);+ Assert.False(info.IsWindows10);+ }++ [Theory]+ [InlineData("Professional", WindowsEdition.Pro)]+ [InlineData("Core", WindowsEdition.Home)]+ [InlineData("CoreSingleLanguage", WindowsEdition.Home)]+ [InlineData("Education", WindowsEdition.Education)]+ [InlineData("Enterprise", WindowsEdition.Enterprise)]+ [InlineData("ServerDatacenter", WindowsEdition.Server)]+ [InlineData(null, WindowsEdition.Unknown)]+ [InlineData("", WindowsEdition.Unknown)]+ [InlineData("Quantum", WindowsEdition.Unknown)]+ public void MapEdition_MapsKnownIds(string? editionId, WindowsEdition expected)+ {+ Assert.Equal(expected, WindowsProvider.MapEdition(editionId));+ }++ [Fact]+ public void PowerPlanService_UnknownScheme_ReadsNullName()+ {+ var service = new PowerPlanService(NullLogger<PowerPlanService>.Instance);+ // Random GUID: no friendly name exists, must be null (never guessed).+ Assert.Null(service.GetSchemeName(Guid.NewGuid()));+ Assert.False(service.SchemeExists(Guid.NewGuid()));+ Assert.Null(service.GetScheme(Guid.NewGuid()));+ }++ [Fact]+ public void PowerPlanService_BadDelete_FailsClosed()+ {+ var service = new PowerPlanService(NullLogger<PowerPlanService>.Instance);+ var call = new optimizerDuck.Domain.Execution.OpCall { Logger = NullLogger.Instance };+ // Deleting a nonexistent scheme must report failure, never throw.+ var result = service.DeleteScheme(call, Guid.NewGuid());+ Assert.False(result.Ok);+ }++ [Theory]+ [InlineData(0x13, MemoryType.Ddr2)]+ [InlineData(0x18, MemoryType.Ddr3)]+ [InlineData(0x1A, MemoryType.Ddr4)]+ [InlineData(0x22, MemoryType.Ddr5)]+ [InlineData(0x0F, MemoryType.Sdram)]+ [InlineData(0, MemoryType.Unknown)]+ [InlineData(null, MemoryType.Unknown)]+ [InlineData(0x99, MemoryType.Other)]+ public void MapMemoryType_MapsSmbiosCodes(int? code, MemoryType expected)+ {+ Assert.Equal(expected, MemoryProvider.MapMemoryType(code));+ }++ [Theory]+ [InlineData("GenuineIntel", CpuVendor.Intel)]+ [InlineData("AuthenticAMD", CpuVendor.Amd)]+ [InlineData(null, CpuVendor.Unknown)]+ [InlineData("", CpuVendor.Unknown)]+ [InlineData("QuantumCorp", CpuVendor.Unknown)]+ public void DetectCpuVendor_MatchesManufacturer(string? manufacturer, CpuVendor expected)+ {+ Assert.Equal(expected, CpuProvider.DetectVendor(manufacturer));+ }++ [Theory]+ [InlineData(0x10DE, GpuVendor.Nvidia)]+ [InlineData(0x1002, GpuVendor.Amd)]+ [InlineData(0x8086, GpuVendor.Intel)]+ [InlineData(0x1234, GpuVendor.Unknown)]+ public void DetectGpuVendorById_MatchesPciIds(uint vendorId, GpuVendor expected)+ {+ Assert.Equal(expected, GpuProvider.DetectVendorById(vendorId));+ }++ [Theory]+ [InlineData("NVIDIA GeForce RTX 4090", GpuVendor.Nvidia)]+ [InlineData("AMD Radeon RX 7900", GpuVendor.Amd)]+ [InlineData("Intel UHD Graphics 770", GpuVendor.Intel)]+ [InlineData("Quantum Render Device", GpuVendor.Unknown)]+ public void DetectGpuVendor_MatchesNames(string name, GpuVendor expected)+ {+ Assert.Equal(expected, GpuProvider.DetectVendor(name, null));+ }++ [Fact]+ public void GetPrimary_Empty_ReturnsNull()+ {+ Assert.Null(GpuProvider.GetPrimary([]));+ }++ [Fact]+ public void GetPrimary_PrefersMostVramThenVendor()+ {+ var intel = new GpuInfo+ {+ Name = "Intel UHD",+ Vendor = GpuVendor.Intel,+ VramMB = 128,+ };+ var amd = new GpuInfo+ {+ Name = "AMD Radeon",+ Vendor = GpuVendor.Amd,+ VramMB = 8192,+ };+ var nvidia = new GpuInfo+ {+ Name = "NVIDIA RTX",+ Vendor = GpuVendor.Nvidia,+ VramMB = 8192,+ };++ // Most VRAM wins regardless of order.+ Assert.Same(amd, GpuProvider.GetPrimary([intel, amd]));+ // VRAM tie breaks toward Nvidia.+ Assert.Same(nvidia, GpuProvider.GetPrimary([amd, nvidia]));+ }++ [Theory]+ [InlineData("Samsung SSD 980 PRO NVMe", StorageMediaType.Nvme)]+ [InlineData("WD Blue 3D NAND SSD", StorageMediaType.Ssd)]+ [InlineData("Seagate BarraCuda", StorageMediaType.Unknown)]+ public void InferFromModel_DoesNotGuess(string model, StorageMediaType expected)+ {+ Assert.Equal(expected, DiskProvider.InferFromModel(model));+ }++ [Fact]+ public void MaxSpeed_PicksHighestReported()+ {+ var modules = new List<MemoryModuleInfo>+ {+ new() { CapacityGB = 8, SpeedMTps = 3200 },+ new() { CapacityGB = 8 },+ new() { CapacityGB = 8, SpeedMTps = 3600 },+ };+ Assert.Equal(3600, MemoryProvider.MaxSpeed(modules));+ Assert.Null(MemoryProvider.MaxSpeed(new List<MemoryModuleInfo>()));+ }++ [Fact]+ public void DominantType_PicksMajorityIgnoresUnknown()+ {+ var modules = new List<MemoryModuleInfo>+ {+ new() { CapacityGB = 8, Type = MemoryType.Ddr4 },+ new() { CapacityGB = 8 },+ new() { CapacityGB = 8, Type = MemoryType.Ddr4 },+ new() { CapacityGB = 8, Type = MemoryType.Ddr5 },+ };+ Assert.Equal(MemoryType.Ddr4, MemoryProvider.DominantType(modules));+ Assert.Equal(MemoryType.Unknown, MemoryProvider.DominantType(new List<MemoryModuleInfo>()));+ }++ [Theory]+ [InlineData(new ushort[] { 9 }, DeviceKind.Laptop)]+ [InlineData(new ushort[] { 3 }, DeviceKind.Desktop)]+ [InlineData(new ushort[] { 99 }, DeviceKind.Unknown)]+ public void MapChassisType_MapsKnownTypes(ushort[] types, DeviceKind expected)+ {+ Assert.Equal(expected, WindowsProvider.MapChassisType(types));+ }++ [Theory]+ [InlineData(0, FirmwareMode.Uefi, VbsState.Disabled)]+ [InlineData(1, FirmwareMode.Uefi, VbsState.Enabled)]+ [InlineData(2, FirmwareMode.Uefi, VbsState.Enabled)]+ [InlineData(9, FirmwareMode.Uefi, VbsState.Unknown)]+ [InlineData(0, FirmwareMode.Legacy, VbsState.Unavailable)]+ [InlineData(2, FirmwareMode.Legacy, VbsState.Unavailable)]+ [InlineData(0, FirmwareMode.Unknown, VbsState.Disabled)]+ public void MapVbsStatus_MapsDeviceGuardStatus(int status, FirmwareMode mode, VbsState expected)+ {+ Assert.Equal(expected, SecurityProvider.MapVbsStatus(status, mode));+ }++ [Fact]+ public void MapMemoryIntegrity_RunningContainsHvciId()+ {+ Assert.Equal(VbsState.Enabled, SecurityProvider.MapMemoryIntegrity(new List<int> { 0, 2 }));+ Assert.Equal(VbsState.Disabled, SecurityProvider.MapMemoryIntegrity(new List<int> { 0 }));+ Assert.Equal(VbsState.Disabled, SecurityProvider.MapMemoryIntegrity(new List<int>()));+ Assert.Equal(+ VbsState.Disabled,+ SecurityProvider.MapMemoryIntegrity(new List<int> { 1, 3 })+ );+ }++ [Fact]+ public void ToServiceIds_HandlesWmiArrayShapes()+ {+ Assert.Equal(new List<int> { 0 }, SecurityProvider.ToServiceIds(new ushort[] { 0 }));+ Assert.Equal(new List<int> { 1, 2 }, SecurityProvider.ToServiceIds(new uint[] { 1, 2 }));+ Assert.Equal(new List<int>(), SecurityProvider.ToServiceIds(null));+ Assert.Equal(new List<int> { 2 }, SecurityProvider.ToServiceIds(2));+ }++ [Fact]+ public void SystemInfo_Unknown_IsMarked()+ {+ Assert.True(SystemInfo.Unknown.IsUnknown);+ var customized = SystemInfo.Unknown with { IsUnknown = false };+ Assert.False(customized.IsUnknown);+ }++ [Fact]+ public async Task RefreshAsync_CancelledToken_Throws()+ {+ var service = new SystemInfoService(NullLogger<SystemInfoService>.Instance);+ using var cts = new CancellationTokenSource();+ cts.Cancel();++ await Assert.ThrowsAnyAsync<OperationCanceledException>(() =>+ service.RefreshAsync(cts.Token)+ );+ }++ [Fact]+ public async Task RefreshAsync_NotifiesAllHandlers_DespiteThrowingOne()+ {+ var service = new SystemInfoService(NullLogger<SystemInfoService>.Instance);+ var calls = 0;+ service.SnapshotRefreshed += (_, _) => calls++;+ service.SnapshotRefreshed += (_, _) => throw new InvalidOperationException("boom");+ service.SnapshotRefreshed += (_, _) => calls++;++ await service.RefreshAsync(TestContext.Current.CancellationToken);++ Assert.Equal(2, calls);+ }+}diff --git a/optimizerDuck.Test/TestDoubles/TestShell.cs b/optimizerDuck.Test/TestDoubles/TestShell.csindex 6e0f910..110ca51 100644--- a/optimizerDuck.Test/TestDoubles/TestShell.cs+++ b/optimizerDuck.Test/TestDoubles/TestShell.cs@@ -1,5 +1,8 @@+using Microsoft.Extensions.Logging;using Microsoft.Extensions.Logging.Abstractions;+using optimizerDuck.Domain.Abstractions;using optimizerDuck.Services.Optimization.Providers;+using optimizerDuck.Services.System;namespace optimizerDuck.Test.TestDoubles;@@ -10,4 +13,12 @@ internal static class TestShellpublic static ShellService New() =>new(new ProcessRunner(TimeoutMs, NullLogger<ProcessRunner>.Instance));++ public static RevertContext Context(ILogger? logger = null) =>+ new()+ {+ Shell = New(),+ PowerPlans = new PowerPlanService(NullLogger<PowerPlanService>.Instance),+ Logger = logger ?? NullLogger.Instance,+ };}diff --git a/optimizerDuck/ApplicationServiceCollectionExtensions.cs b/optimizerDuck/ApplicationServiceCollectionExtensions.csindex af187a6..2873e04 100644--- a/optimizerDuck/ApplicationServiceCollectionExtensions.cs+++ b/optimizerDuck/ApplicationServiceCollectionExtensions.cs@@ -88,12 +88,13 @@ public static class ApplicationServiceCollectionExtensions// Managersservices.AddSingleton<ConfigManager>();- services.AddSingleton<RevertManager>();services.AddSingleton(TimeProvider.System);// Servicesservices.AddSingleton<ProcessRunner>();+ services.AddSingleton<PowerPlanService>();services.AddSingleton<ShellService>();+ services.AddSingleton<RevertManager>();services.AddSingleton<OptimizationRegistry>();services.AddSingleton<CustomizeRegistry>();services.AddSingleton<OptimizationService>();diff --git a/optimizerDuck/Common/Converters/BytesToGBConverter.cs b/optimizerDuck/Common/Converters/BytesToGBConverter.csnew file mode 100644index 0000000..a14e94c--- /dev/null+++ b/optimizerDuck/Common/Converters/BytesToGBConverter.cs@@ -0,0 +1,33 @@+using System.Globalization;+using System.Windows.Data;+using optimizerDuck.Services.Configuration;++namespace optimizerDuck.Common.Converters;++/// <summary>Formats a byte count as gigabytes ("F1"). Null maps to localized Unknown.</summary>+public class BytesToGBConverter : IValueConverter+{+ public object Convert(object? value, Type targetType, object? parameter, CultureInfo culture)+ {+ double bytes = value switch+ {+ long l => l,+ int i => i,+ double d => d,+ _ => double.NaN,+ };+ if (double.IsNaN(bytes) || bytes < 0)+ return Loc.Instance["Common.Unknown"];+ return (bytes / (1024.0 * 1024.0 * 1024.0)).ToString("F1", culture);+ }++ public object ConvertBack(+ object? value,+ Type targetType,+ object? parameter,+ CultureInfo culture+ )+ {+ throw new NotSupportedException();+ }+}diff --git a/optimizerDuck/Common/Converters/EnumDisplayConverter.cs b/optimizerDuck/Common/Converters/EnumDisplayConverter.csnew file mode 100644index 0000000..a907bbd--- /dev/null+++ b/optimizerDuck/Common/Converters/EnumDisplayConverter.cs@@ -0,0 +1,41 @@+using System.Globalization;+using System.Windows.Data;+using optimizerDuck.Services.Configuration;++namespace optimizerDuck.Common.Converters;++/// <summary>+/// Displays any system-info enum via resource key <c>Enum.{Type}.{Value}</c>.+/// <see cref="Enum.Unknown"/>-style values and null map to <c>Common.Unknown</c>;+/// a missing resource falls back to the raw value name (never a raw key).+/// Re-evaluates on language change through the normal binding refresh.+/// </summary>+public class EnumDisplayConverter : IValueConverter+{+ public object Convert(object? value, Type targetType, object? parameter, CultureInfo culture)+ {+ if (value is null)+ return Loc.Instance["Common.Unknown"];++ if (value is Enum e)+ {+ if (e.ToString() == "Unknown")+ return Loc.Instance["Common.Unknown"];+ var key = $"Enum.{e.GetType().Name}.{e}";+ var text = Loc.Instance[key];+ return text == key ? e.ToString() : text;+ }++ return Loc.Instance["Common.Unknown"];+ }++ public object ConvertBack(+ object? value,+ Type targetType,+ object? parameter,+ CultureInfo culture+ )+ {+ throw new NotSupportedException();+ }+}diff --git a/optimizerDuck/Common/Converters/MBToGBConverter.cs b/optimizerDuck/Common/Converters/MBToGBConverter.csindex fa0e1a2..378bda0 100644--- a/optimizerDuck/Common/Converters/MBToGBConverter.cs+++ b/optimizerDuck/Common/Converters/MBToGBConverter.cs@@ -1,16 +1,17 @@-using System.Globalization;+using System.Globalization;using System.Windows.Data;+using optimizerDuck.Services.Configuration;namespace optimizerDuck.Common.Converters;-/// <summary>Converts a megabyte value to a formatted gigabyte string, or "N/A" when invalid.</summary>+/// <summary>Converts a megabyte value to a formatted gigabyte string, else localized Unknown.</summary>public class MBToGBConverter : IValueConverter{public object Convert(object? value, Type targetType, object? parameter, CultureInfo culture){if (value is int mb and > 0)- return (mb / 1024.0).ToString("F1");- return "N/A";+ return (mb / 1024.0).ToString("F1", culture);+ return Loc.Instance["Common.Unknown"];}public object ConvertBack(diff --git a/optimizerDuck/Common/Converters/NullToUnknownTextConverter.cs b/optimizerDuck/Common/Converters/NullToUnknownTextConverter.csnew file mode 100644index 0000000..0c44a2e--- /dev/null+++ b/optimizerDuck/Common/Converters/NullToUnknownTextConverter.cs@@ -0,0 +1,24 @@+using System.Globalization;+using System.Windows.Data;+using optimizerDuck.Services.Configuration;++namespace optimizerDuck.Common.Converters;++/// <summary>Passes strings through; null or empty becomes localized Unknown.</summary>+public class NullToUnknownTextConverter : IValueConverter+{+ public object Convert(object? value, Type targetType, object? parameter, CultureInfo culture)+ {+ return string.IsNullOrEmpty(value as string) ? Loc.Instance["Common.Unknown"] : value!;+ }++ public object ConvertBack(+ object? value,+ Type targetType,+ object? parameter,+ CultureInfo culture+ )+ {+ throw new NotSupportedException();+ }+}diff --git a/optimizerDuck/Domain/Abstractions/IRevertStep.cs b/optimizerDuck/Domain/Abstractions/IRevertStep.csindex 366b352..9ab267a 100644--- a/optimizerDuck/Domain/Abstractions/IRevertStep.cs+++ b/optimizerDuck/Domain/Abstractions/IRevertStep.cs@@ -21,12 +21,12 @@ public interface IRevertSteppublic string Description { get; }/// <summary>- /// Executes this revert step asynchronously.+ /// Executes this revert step with its full execution context./// </summary>- /// <param name="shell">The application shell service, so command-executing steps use the configured timeout.</param>+ /// <param name="context">Shell, power service, and logger for this revert.</param>/// <param name="logger">The logger to record provider and shell operations.</param>/// <returns><c>true</c> if the revert succeeded; otherwise, <c>false</c>.</returns>- Task<bool> ExecuteAsync(ShellService shell, ILogger logger);+ Task<bool> ExecuteAsync(RevertContext context, ILogger logger);/// <summary>/// Serializes this revert step to a JSON object for persistence.diff --git a/optimizerDuck/Domain/Abstractions/RevertContext.cs b/optimizerDuck/Domain/Abstractions/RevertContext.csnew file mode 100644index 0000000..dd0c7a9--- /dev/null+++ b/optimizerDuck/Domain/Abstractions/RevertContext.cs@@ -0,0 +1,18 @@+using Microsoft.Extensions.Logging;+using optimizerDuck.Services.Optimization.Providers;+using optimizerDuck.Services.System;++namespace optimizerDuck.Domain.Abstractions;++/// <summary>+/// Explicit per-revert execution context: every capability a revert step+/// needs travels as a parameter instead of hiding behind service locators.+/// </summary>+public sealed class RevertContext+{+ public required ShellService Shell { get; init; }++ public required PowerPlanService PowerPlans { get; init; }++ public required ILogger Logger { get; init; }+}diff --git a/optimizerDuck/Domain/Conditions/BuiltIn/CpuBrandCondition.cs b/optimizerDuck/Domain/Conditions/BuiltIn/CpuBrandCondition.csindex 0de54b5..19bea9d 100644--- a/optimizerDuck/Domain/Conditions/BuiltIn/CpuBrandCondition.cs+++ b/optimizerDuck/Domain/Conditions/BuiltIn/CpuBrandCondition.cs@@ -16,7 +16,7 @@ public abstract class CpuBrandCondition : ConditionBase/// <summary>Strongly-typed localized failure description.</summary>protected abstract Func<string> Description { get; }- public override ConditionResult Evaluate(SystemSnapshot snapshot)+ public override ConditionResult Evaluate(SystemInfo snapshot){// An unknown CPU vendor means hardware detection produced no usable answer// (e.g. WMI/registry failed), fail open so a detection failure never hides@@ -42,7 +42,7 @@ public sealed class IntelCpuCondition : CpuBrandCondition/// <summary>Requires an AMD CPU.</summary>public sealed class AmdCpuCondition : CpuBrandCondition{- protected override CpuVendor RequiredVendor => CpuVendor.AMD;+ protected override CpuVendor RequiredVendor => CpuVendor.Amd;protected override Func<string> Title => () => Loc.Instance["Condition.Cpu.Amd.Title"];protected override Func<string> Description =>() => Loc.Instance["Condition.Cpu.Amd.Description"];diff --git a/optimizerDuck/Domain/Conditions/BuiltIn/GpuBrandCondition.cs b/optimizerDuck/Domain/Conditions/BuiltIn/GpuBrandCondition.csindex 70aedb1..e53d9ef 100644--- a/optimizerDuck/Domain/Conditions/BuiltIn/GpuBrandCondition.cs+++ b/optimizerDuck/Domain/Conditions/BuiltIn/GpuBrandCondition.cs@@ -16,7 +16,7 @@ public abstract class GpuBrandCondition : ConditionBase/// <summary>Strongly-typed localized failure description.</summary>protected abstract Func<string> Description { get; }- public override ConditionResult Evaluate(SystemSnapshot snapshot)+ public override ConditionResult Evaluate(SystemInfo snapshot){// An empty or all-unknown GPU list means hardware detection produced no usable// answer (e.g. DXGI/WMI failed), fail open so a detection failure never hides@@ -37,7 +37,7 @@ public abstract class GpuBrandCondition : ConditionBase/// <summary>Requires an NVIDIA GPU.</summary>public sealed class NvidiaGpuCondition : GpuBrandCondition{- protected override GpuVendor RequiredVendor => GpuVendor.NVIDIA;+ protected override GpuVendor RequiredVendor => GpuVendor.Nvidia;protected override Func<string> Title => () => Loc.Instance["Condition.Gpu.Nvidia.Title"];protected override Func<string> Description =>() => Loc.Instance["Condition.Gpu.Nvidia.Description"];@@ -46,7 +46,7 @@ public sealed class NvidiaGpuCondition : GpuBrandCondition/// <summary>Requires an AMD GPU.</summary>public sealed class AmdGpuCondition : GpuBrandCondition{- protected override GpuVendor RequiredVendor => GpuVendor.AMD;+ protected override GpuVendor RequiredVendor => GpuVendor.Amd;protected override Func<string> Title => () => Loc.Instance["Condition.Gpu.Amd.Title"];protected override Func<string> Description =>() => Loc.Instance["Condition.Gpu.Amd.Description"];diff --git a/optimizerDuck/Domain/Conditions/BuiltIn/MinimumRamCondition.cs b/optimizerDuck/Domain/Conditions/BuiltIn/MinimumRamCondition.csindex 483698a..fbd8986 100644--- a/optimizerDuck/Domain/Conditions/BuiltIn/MinimumRamCondition.cs+++ b/optimizerDuck/Domain/Conditions/BuiltIn/MinimumRamCondition.cs@@ -16,8 +16,8 @@ public abstract class MinimumRamCondition : ConditionBase/// <summary>Strongly-typed localized failure description.</summary>protected abstract Func<string> Description { get; }- public override ConditionResult Evaluate(SystemSnapshot snapshot) =>- snapshot.Ram.TotalGB >= MinimumGb+ public override ConditionResult Evaluate(SystemInfo snapshot) =>+ snapshot.Memory.TotalGB >= MinimumGb? ConditionResult.Available: ConditionResult.Unsupported(Title, Description);}diff --git a/optimizerDuck/Domain/Conditions/BuiltIn/RecallInstalledCondition.cs b/optimizerDuck/Domain/Conditions/BuiltIn/RecallInstalledCondition.csindex c0022c5..6225d7f 100644--- a/optimizerDuck/Domain/Conditions/BuiltIn/RecallInstalledCondition.cs+++ b/optimizerDuck/Domain/Conditions/BuiltIn/RecallInstalledCondition.cs@@ -17,7 +17,7 @@ public sealed class RecallInstalledCondition : ConditionBase// feature is installed; the directory is absent on systems without it.private const string AiShellDirectory = @"C:\Windows\System32\CoreAISpeech";- public override ConditionResult Evaluate(SystemSnapshot snapshot)+ public override ConditionResult Evaluate(SystemInfo snapshot){var isSupported =TryGetOsBuild(snapshot, out var build)diff --git a/optimizerDuck/Domain/Conditions/BuiltIn/RegistryKeyExistsCondition.cs b/optimizerDuck/Domain/Conditions/BuiltIn/RegistryKeyExistsCondition.csindex 797a3fb..0a9caa7 100644--- a/optimizerDuck/Domain/Conditions/BuiltIn/RegistryKeyExistsCondition.cs+++ b/optimizerDuck/Domain/Conditions/BuiltIn/RegistryKeyExistsCondition.cs@@ -21,7 +21,7 @@ public abstract class RegistryKeyExistsCondition : ConditionBase/// <summary>Strongly-typed localized failure description.</summary>protected abstract Func<string> Description { get; }- public override ConditionResult Evaluate(SystemSnapshot snapshot)+ public override ConditionResult Evaluate(SystemInfo snapshot){if (!RegistryService.TryKeyExists(RegistryItem, out var exists))return ConditionResult.Error();diff --git a/optimizerDuck/Domain/Conditions/BuiltIn/ServiceExistsCondition.cs b/optimizerDuck/Domain/Conditions/BuiltIn/ServiceExistsCondition.csindex 1fca06f..15ec899 100644--- a/optimizerDuck/Domain/Conditions/BuiltIn/ServiceExistsCondition.cs+++ b/optimizerDuck/Domain/Conditions/BuiltIn/ServiceExistsCondition.cs@@ -20,7 +20,7 @@ public abstract class ServiceExistsCondition : ConditionBase/// <summary>Strongly-typed localized failure description.</summary>protected abstract Func<string> Description { get; }- public override ConditionResult Evaluate(SystemSnapshot snapshot)+ public override ConditionResult Evaluate(SystemInfo snapshot){var serviceKey = new RegistryItem($@"HKLM\SYSTEM\CurrentControlSet\Services\{ServiceName}");if (!RegistryService.TryKeyExists(serviceKey, out var exists))diff --git a/optimizerDuck/Domain/Conditions/BuiltIn/Windows10Condition.cs b/optimizerDuck/Domain/Conditions/BuiltIn/Windows10Condition.csindex 988a646..0d67071 100644--- a/optimizerDuck/Domain/Conditions/BuiltIn/Windows10Condition.cs+++ b/optimizerDuck/Domain/Conditions/BuiltIn/Windows10Condition.cs@@ -7,7 +7,7 @@ namespace optimizerDuck.Domain.Conditions;/// <summary>Requires Windows 10 (build 10240 to 21999).</summary>public sealed class Windows10Condition : ConditionBase{- public override ConditionResult Evaluate(SystemSnapshot snapshot) =>+ public override ConditionResult Evaluate(SystemInfo snapshot) =>TryGetOsBuild(snapshot, out var build)&& build is >= WindowsBuilds.Windows10 and < WindowsBuilds.Windows11? ConditionResult.Availablediff --git a/optimizerDuck/Domain/Conditions/BuiltIn/Windows11Condition.cs b/optimizerDuck/Domain/Conditions/BuiltIn/Windows11Condition.csindex f28f01e..660697e 100644--- a/optimizerDuck/Domain/Conditions/BuiltIn/Windows11Condition.cs+++ b/optimizerDuck/Domain/Conditions/BuiltIn/Windows11Condition.cs@@ -7,7 +7,7 @@ namespace optimizerDuck.Domain.Conditions;/// <summary>Requires Windows 11 (build 22000 or later).</summary>public sealed class Windows11Condition : ConditionBase{- public override ConditionResult Evaluate(SystemSnapshot snapshot) =>+ public override ConditionResult Evaluate(SystemInfo snapshot) =>TryGetOsBuild(snapshot, out var build) && build >= WindowsBuilds.Windows11? ConditionResult.Available: ConditionResult.Unsupported(diff --git a/optimizerDuck/Domain/Conditions/BuiltIn/Windows11_24H2OrGreaterCondition.cs b/optimizerDuck/Domain/Conditions/BuiltIn/Windows11_24H2OrGreaterCondition.csindex ccf5ab0..d17b04e 100644--- a/optimizerDuck/Domain/Conditions/BuiltIn/Windows11_24H2OrGreaterCondition.cs+++ b/optimizerDuck/Domain/Conditions/BuiltIn/Windows11_24H2OrGreaterCondition.cs@@ -10,7 +10,7 @@ namespace optimizerDuck.Domain.Conditions;/// </summary>public sealed class Windows11_24H2OrGreaterCondition : ConditionBase{- public override ConditionResult Evaluate(SystemSnapshot snapshot) =>+ public override ConditionResult Evaluate(SystemInfo snapshot) =>TryGetOsBuild(snapshot, out var build) && build >= WindowsBuilds.Windows11_24H2? ConditionResult.Available: ConditionResult.Unsupported(diff --git a/optimizerDuck/Domain/Conditions/ConditionBase.cs b/optimizerDuck/Domain/Conditions/ConditionBase.csindex b540864..03fbdc0 100644--- a/optimizerDuck/Domain/Conditions/ConditionBase.cs+++ b/optimizerDuck/Domain/Conditions/ConditionBase.cs@@ -8,19 +8,12 @@ namespace optimizerDuck.Domain.Conditions;public abstract class ConditionBase : ICondition{/// <inheritdoc />- public abstract ConditionResult Evaluate(SystemSnapshot snapshot);+ public abstract ConditionResult Evaluate(SystemInfo snapshot);- /// <summary>Attempts to parse the OS build number (e.g. "22631") from the snapshot.</summary>- protected static bool TryGetOsBuild(SystemSnapshot snapshot, out int build)+ /// <summary>Reads the major OS build number (e.g. 22631) from the snapshot.</summary>+ protected static bool TryGetOsBuild(SystemInfo snapshot, out int build){- build = 0;- if (snapshot.Os.BuildNumber is not { } text)- return false;-- var span = text.AsSpan();- var dot = span.IndexOf('.');- if (dot >= 0)- span = span[..dot];- return int.TryParse(span, out build);+ build = snapshot.Windows.BuildNumber ?? 0;+ return snapshot.Windows.BuildNumber.HasValue;}}diff --git a/optimizerDuck/Domain/Conditions/ICondition.cs b/optimizerDuck/Domain/Conditions/ICondition.csindex fa59678..876dece 100644--- a/optimizerDuck/Domain/Conditions/ICondition.cs+++ b/optimizerDuck/Domain/Conditions/ICondition.cs@@ -10,5 +10,5 @@ namespace optimizerDuck.Domain.Conditions;public interface ICondition{/// <summary>Evaluates the condition against the system snapshot.</summary>- ConditionResult Evaluate(SystemSnapshot snapshot);+ ConditionResult Evaluate(SystemInfo snapshot);}diff --git a/optimizerDuck/Domain/Optimizations/Categories/Gpu.cs b/optimizerDuck/Domain/Optimizations/Categories/Gpu.csindex 4ae254d..21ca1a6 100644--- a/optimizerDuck/Domain/Optimizations/Categories/Gpu.cs+++ b/optimizerDuck/Domain/Optimizations/Categories/Gpu.cs@@ -87,7 +87,7 @@ public class Gpu : LocalizedObject, IOptimizationCategory/// </list>/// </para>/// <para>- /// This mapping is <strong>required</strong> because the order of GPUs in <see cref="SystemSnapshot.Gpus" />+ /// This mapping is <strong>required</strong> because the order of GPUs in <see cref="SystemInfo.Gpus" />/// does <strong>not</strong> guarantee alignment with registry index order. Using array index (0, 1, 2...)/// leads to applying tweaks to the wrong GPU (e.g., iGPU instead of dGPU)./// </para>@@ -146,7 +146,7 @@ public class Gpu : LocalizedObject, IOptimizationCategory)]public class AmdDisableUlps : GpuRegistryOptimization{- protected override GpuVendor Vendor => GpuVendor.AMD;+ protected override GpuVendor Vendor => GpuVendor.Amd;protected override IReadOnlyList<RegistryItem> CreateItems(string path){@@ -162,7 +162,7 @@ public class Gpu : LocalizedObject, IOptimizationCategory)]public class AmdDisablePowerGating : GpuRegistryOptimization{- protected override GpuVendor Vendor => GpuVendor.AMD;+ protected override GpuVendor Vendor => GpuVendor.Amd;protected override IReadOnlyList<RegistryItem> CreateItems(string path){@@ -183,7 +183,7 @@ public class Gpu : LocalizedObject, IOptimizationCategory)]public class AmdDisableVideoClockGating : GpuRegistryOptimization{- protected override GpuVendor Vendor => GpuVendor.AMD;+ protected override GpuVendor Vendor => GpuVendor.Amd;protected override IReadOnlyList<RegistryItem> CreateItems(string path){@@ -205,7 +205,7 @@ public class Gpu : LocalizedObject, IOptimizationCategory)]public class AmdDisableAspm : GpuRegistryOptimization{- protected override GpuVendor Vendor => GpuVendor.AMD;+ protected override GpuVendor Vendor => GpuVendor.Amd;protected override IReadOnlyList<RegistryItem> CreateItems(string path){@@ -225,7 +225,7 @@ public class Gpu : LocalizedObject, IOptimizationCategory)]public class NvidiaDisableDynamicPstate : GpuRegistryOptimization{- protected override GpuVendor Vendor => GpuVendor.NVIDIA;+ protected override GpuVendor Vendor => GpuVendor.Nvidia;protected override IReadOnlyList<RegistryItem> CreateItems(string path){@@ -241,7 +241,7 @@ public class Gpu : LocalizedObject, IOptimizationCategory)]public class NvidiaDisableAsyncPstates : GpuRegistryOptimization{- protected override GpuVendor Vendor => GpuVendor.NVIDIA;+ protected override GpuVendor Vendor => GpuVendor.Nvidia;protected override IReadOnlyList<RegistryItem> CreateItems(string path){diff --git a/optimizerDuck/Domain/Optimizations/Categories/Performance.cs b/optimizerDuck/Domain/Optimizations/Categories/Performance.csindex ca0a756..445d692 100644--- a/optimizerDuck/Domain/Optimizations/Categories/Performance.cs+++ b/optimizerDuck/Domain/Optimizations/Categories/Performance.cs@@ -63,15 +63,15 @@ public class Performance : LocalizedObject, IOptimizationCategoryOptimizationContext context){- if (context.Snapshot.Ram.TotalKB <= 0)+ if (context.Snapshot.Memory.TotalKB <= 0){context.Logger.LogInformation("Invalid RAM value: {RamTotalKB}. Skipping...",- context.Snapshot.Ram.TotalKB+ context.Snapshot.Memory.TotalKB);return Task.FromResult(ApplyResult.False(- Loc.Instance[$"{ErrorPrefix}.InvalidRAM", context.Snapshot.Ram.TotalKB]+ Loc.Instance[$"{ErrorPrefix}.InvalidRAM", context.Snapshot.Memory.TotalKB]));}@@ -81,13 +81,13 @@ public class Performance : LocalizedObject, IOptimizationCategorynew RegistryItem(@"HKLM\SYSTEM\CurrentControlSet\Control","SvcHostSplitThresholdInKB",- context.Snapshot.Ram.TotalKB,+ context.Snapshot.Memory.TotalKB,RegistryValueKind.DWord));context.Logger.LogInformation("Consolidated service hosts with threshold: {ThresholdKB} KB",- context.Snapshot.Ram.TotalKB+ context.Snapshot.Memory.TotalKB);return Task.FromResult(CompleteFromScope(context));}diff --git a/optimizerDuck/Domain/Optimizations/Categories/PowerManagement.cs b/optimizerDuck/Domain/Optimizations/Categories/PowerManagement.csindex 695ba48..b2d9e90 100644--- a/optimizerDuck/Domain/Optimizations/Categories/PowerManagement.cs+++ b/optimizerDuck/Domain/Optimizations/Categories/PowerManagement.cs@@ -1,6 +1,5 @@using System.Collections.ObjectModel;using System.IO;-using System.Text.RegularExpressions;using Microsoft.Extensions.Logging;using Newtonsoft.Json;using Newtonsoft.Json.Linq;@@ -15,6 +14,7 @@ using optimizerDuck.Domain.UI;using optimizerDuck.Resources.Languages;using optimizerDuck.Services.Configuration;using optimizerDuck.Services.Optimization.Providers;+using optimizerDuck.Services.System;using optimizerDuck.UI.Pages.Optimize.Categories;namespace optimizerDuck.Domain.Optimizations.Categories;@@ -144,11 +144,6 @@ public class PowerManagement : LocalizedObject, IOptimizationCategory}}- private static readonly Regex _activePlanGuidRegex = new(- @".*:\s*([a-fA-F0-9\-]{36})",- RegexOptions.IgnoreCase | RegexOptions.Compiled- );-[Optimization(Id = "EE71E993-EE41-4449-8856-84B09B2B0C46",Risk = OptimizationRisk.Safe,@@ -156,25 +151,27 @@ public class PowerManagement : LocalizedObject, IOptimizationCategory)]public class InstallOptimizerDuckPowerPlan : BaseOptimization{+ private static readonly Guid OptimizerDuckPlanId = Guid.Parse(Shared.PowerPlanGUID);+public override async Task<ApplyResult> ApplyAsync(IProgress<ProcessingProgress> progress,OptimizationContext context){- var activeQuery = await context.Shell.QueryCMDAsync(- "powercfg /getactivescheme",- context.Logger- );- var match = _activePlanGuidRegex.Match(activeQuery.Stdout);-- if (!match.Success)+ var previousPlanId = context.PowerPlans.GetActiveSchemeId();+ if (previousPlanId is null){context.Logger.LogError("Failed to detect current active power plan");return ApplyResult.False(Loc.Instance[$"{ErrorPrefix}.DetectActivePlanFailed"]);}- var previousPlanGuid = match.Groups[1].Value;- context.Logger.LogInformation("Current active power plan: {Guid}", previousPlanGuid);+ var previousName =+ context.PowerPlans.GetSchemeName(previousPlanId.Value) ?? previousPlanId.ToString();+ context.Logger.LogInformation(+ "Current active power plan: {Name} ({Guid})",+ previousName,+ previousPlanId+ );var powerPlanPath = Path.Combine(Shared.AssetsDirectory,@@ -205,34 +202,53 @@ public class PowerManagement : LocalizedObject, IOptimizationCategory});- var importOp = await context.Shell.CMDAsync(- $"powercfg /import \"{powerPlanPath}\" {Shared.PowerPlanGUID}",- context,- $"powercfg /delete {Shared.PowerPlanGUID}"+ var (importResult, installedId) = await context.PowerPlans.ImportSchemeAsync(+ powerPlanPath,+ OptimizerDuckPlanId,+ context.CancellationToken);- if (!importOp.Ok)+ if (!importResult.Ok || installedId is null){context.Logger.LogError("Failed to import optimizerDuck power plan: {Error}",- importOp.Error+ importResult.Error ?? "unknown");return ApplyResult.False(Loc.Instance[$"{ErrorPrefix}.ImportFailed"]);}- var setActiveOp = await context.Shell.CMDAsync(- $"powercfg /setactive {Shared.PowerPlanGUID}",- context,- $"powercfg /setactive {previousPlanGuid}"- );- if (!setActiveOp.Ok)+ var setActive = context.PowerPlans.SetActiveScheme(context, installedId.Value);+ if (!setActive.Ok){context.Logger.LogError("Failed to activate optimizerDuck power plan: {Error}",- setActiveOp.Error+ setActive.Error ?? "unknown");return ApplyResult.False(Loc.Instance[$"{ErrorPrefix}.ActivateFailed"]);}+ // SetActiveScheme records its own revert step with PreviousSchemeId;+ // point it at the installed scheme so revert restores then deletes.+ var activation = context.Changes.Changes.LastOrDefault(c =>+ c.Ok && c.Revert is PowerPlanRevertStep+ );+ if (activation?.Revert is PowerPlanRevertStep activationStep)+ activationStep.InstalledSchemeId = installedId.Value;+ else+ context.Changes.Add(+ ServiceStrings.PowerPlanName,+ Loc.Instance[+ "Revert.PowerPlan.Description.Set",+ context.PowerPlans.GetSchemeName(installedId.Value)+ ?? installedId.ToString()+ ],+ true,+ new PowerPlanRevertStep+ {+ PreviousSchemeId = previousPlanId.Value,+ InstalledSchemeId = installedId.Value,+ }+ );+context.Logger.LogInformation("Installed optimizerDuck power plan successfully!");return context.Changes.ToApplyResult();}diff --git a/optimizerDuck/Domain/Optimizations/Models/OptimizationContext.cs b/optimizerDuck/Domain/Optimizations/Models/OptimizationContext.csindex 9d67c50..ff094f9 100644--- a/optimizerDuck/Domain/Optimizations/Models/OptimizationContext.cs+++ b/optimizerDuck/Domain/Optimizations/Models/OptimizationContext.cs@@ -16,7 +16,7 @@ public class OptimizationContext : OpCall/// <summary>/// Gets a snapshot of the current system hardware and software information./// </summary>- public required SystemSnapshot Snapshot { get; init; }+ public required SystemInfo Snapshot { get; init; }/// <summary>/// Gets the service used to download remote resources required by optimizations.@@ -27,4 +27,9 @@ public class OptimizationContext : OpCall/// Gets the shell service used to execute CMD/PowerShell commands./// </summary>public required ShellService Shell { get; init; }++ /// <summary>+ /// Gets the native power-scheme service (get/set/import/delete, live names).+ /// </summary>+ public required PowerPlanService PowerPlans { get; init; }}diff --git a/optimizerDuck/Domain/Revert/Steps/PowerPlanRevertStep.cs b/optimizerDuck/Domain/Revert/Steps/PowerPlanRevertStep.csnew file mode 100644index 0000000..1ba5037--- /dev/null+++ b/optimizerDuck/Domain/Revert/Steps/PowerPlanRevertStep.cs@@ -0,0 +1,118 @@+using Microsoft.Extensions.Logging;+using Newtonsoft.Json.Linq;+using optimizerDuck.Domain.Abstractions;+using optimizerDuck.Domain.Exceptions;+using optimizerDuck.Domain.Execution;+using optimizerDuck.Resources.Languages;+using optimizerDuck.Services.Configuration;++namespace optimizerDuck.Domain.Revert.Steps;++/// <summary>+/// Restores the previous active power scheme and removes the installed+/// optimizerDuck scheme. Verifies the restore by re-reading the active+/// scheme; deleting the installed scheme is best-effort after a verified+/// restore (a missing scheme at delete time counts as already reverted).+/// </summary>+public class PowerPlanRevertStep : IRevertStep+{+ public Guid PreviousSchemeId { get; set; }++ public Guid InstalledSchemeId { get; set; }++ /// <inheritdoc />+ public string Type => "PowerPlan";++ /// <inheritdoc />+ public string Description => Loc.Instance["Revert.PowerPlan.Description", PreviousSchemeId];++ /// <inheritdoc />+ public Task<bool> ExecuteAsync(RevertContext context, ILogger logger)+ {+ ArgumentNullException.ThrowIfNull(context);+ var powerPlans = context.PowerPlans;+ var call = new OpCall { Logger = logger };++ var restored = false;+ if (PreviousSchemeId != Guid.Empty)+ {+ var setActive = powerPlans.SetActiveScheme(call, PreviousSchemeId);+ if (!setActive.Ok)+ throw new StepExecutionException(+ Loc.Instance["Revert.PowerPlan.Error.RestoreFailed", setActive.Error ?? ""],+ setActive.ErrorDetail+ );+ var active = powerPlans.GetActiveSchemeId();+ if (active is null)+ throw new StepExecutionException(+ Loc.Instance["Revert.PowerPlan.Error.VerifyFailed", PreviousSchemeId],+ null+ );+ if (active.Value != PreviousSchemeId)+ throw new StepExecutionException(+ Loc.Instance[+ "Revert.PowerPlan.Error.VerifyMismatch",+ PreviousSchemeId,+ active.Value+ ],+ null+ );+ restored = true;+ }++ if (InstalledSchemeId != Guid.Empty)+ {+ // Never delete the scheme we just restored: installing over the+ // same GUID means previous == installed.+ if (InstalledSchemeId != PreviousSchemeId)+ {+ if (powerPlans.SchemeExists(InstalledSchemeId))+ {+ var deleted = powerPlans.DeleteScheme(call, InstalledSchemeId);+ if (!deleted.Ok)+ throw new StepExecutionException(+ Loc.Instance[+ "Revert.PowerPlan.Error.DeleteFailed",+ deleted.Error ?? ""+ ],+ deleted.ErrorDetail+ );+ }+ }+ }++ if (!restored && InstalledSchemeId == Guid.Empty)+ throw new StepExecutionException(+ Loc.Instance["Revert.PowerPlan.Error.NothingToDo"],+ ""+ );++ return Task.FromResult(true);+ }++ /// <inheritdoc />+ public JObject ToData()+ {+ return new JObject+ {+ [nameof(PreviousSchemeId)] = PreviousSchemeId.ToString(),+ [nameof(InstalledSchemeId)] = InstalledSchemeId.ToString(),+ };+ }++ public static PowerPlanRevertStep FromData(JToken data)+ {+ if (data is not JObject obj)+ throw new StepExecutionException("Invalid PowerPlan revert data.", "");+ if (+ !Guid.TryParse(obj[nameof(PreviousSchemeId)]?.ToString(), out var previous)+ || !Guid.TryParse(obj[nameof(InstalledSchemeId)]?.ToString(), out var installed)+ )+ throw new StepExecutionException("Invalid PowerPlan revert data.", "");+ return new PowerPlanRevertStep+ {+ PreviousSchemeId = previous,+ InstalledSchemeId = installed,+ };+ }+}diff --git a/optimizerDuck/Domain/Revert/Steps/PowerSettingRevertStep.cs b/optimizerDuck/Domain/Revert/Steps/PowerSettingRevertStep.csnew file mode 100644index 0000000..4eddcad--- /dev/null+++ b/optimizerDuck/Domain/Revert/Steps/PowerSettingRevertStep.cs@@ -0,0 +1,111 @@+using Microsoft.Extensions.Logging;+using Newtonsoft.Json.Linq;+using optimizerDuck.Domain.Abstractions;+using optimizerDuck.Domain.Exceptions;+using optimizerDuck.Domain.Execution;+using optimizerDuck.Resources.Languages;+using optimizerDuck.Services.Configuration;+using optimizerDuck.Services.System;++namespace optimizerDuck.Domain.Revert.Steps;++/// <summary>+/// Restores exact previous AC/DC values captured before a power-setting+/// write. Fails closed: an unreadable value after restore is a failure,+/// never a silent success.+/// </summary>+public class PowerSettingRevertStep : IRevertStep+{+ public Guid SchemeId { get; set; }++ public Guid SubgroupId { get; set; }++ public Guid SettingId { get; set; }++ public uint PreviousAcValue { get; set; }++ public uint PreviousDcValue { get; set; }++ /// <inheritdoc />+ public string Type => "PowerSetting";++ /// <inheritdoc />+ public string Description =>+ Loc.Instance["Revert.PowerSetting.Description", SchemeId, SubgroupId, SettingId];++ /// <inheritdoc />+ public Task<bool> ExecuteAsync(RevertContext context, ILogger logger)+ {+ ArgumentNullException.ThrowIfNull(context);+ var call = new OpCall { Logger = logger };+ var result = context.PowerPlans.SetSetting(+ call,+ SchemeId,+ SubgroupId,+ SettingId,+ PreviousAcValue,+ PreviousDcValue+ );+ if (!result.Ok)+ throw new StepExecutionException(result.Error ?? Description, result.ErrorDetail);++ var ac = context.PowerPlans.GetSettingValue(+ SchemeId,+ SubgroupId,+ SettingId,+ PowerSource.Ac+ );+ var dc = context.PowerPlans.GetSettingValue(+ SchemeId,+ SubgroupId,+ SettingId,+ PowerSource.Dc+ );+ if (ac is null || dc is null)+ throw new StepExecutionException(+ $"Power setting verify failed for {SchemeId}/{SubgroupId}/{SettingId}: could not read the values.",+ null+ );+ if (ac.Value != PreviousAcValue || dc.Value != PreviousDcValue)+ throw new StepExecutionException(+ $"Power setting verify failed for {SchemeId}/{SubgroupId}/{SettingId}: expected AC={PreviousAcValue} DC={PreviousDcValue}, actual AC={ac} DC={dc}",+ null+ );+ return Task.FromResult(true);+ }++ /// <inheritdoc />+ public JObject ToData()+ {+ return new JObject+ {+ [nameof(SchemeId)] = SchemeId.ToString(),+ [nameof(SubgroupId)] = SubgroupId.ToString(),+ [nameof(SettingId)] = SettingId.ToString(),+ [nameof(PreviousAcValue)] = PreviousAcValue,+ [nameof(PreviousDcValue)] = PreviousDcValue,+ };+ }++ public static PowerSettingRevertStep FromData(JToken data)+ {+ if (data is not JObject obj)+ throw new StepExecutionException("Invalid PowerSetting revert data.", "");+ if (+ !Guid.TryParse(obj[nameof(SchemeId)]?.ToString(), out var scheme)+ || !Guid.TryParse(obj[nameof(SubgroupId)]?.ToString(), out var subgroup)+ || !Guid.TryParse(obj[nameof(SettingId)]?.ToString(), out var setting)+ || !uint.TryParse(obj[nameof(PreviousAcValue)]?.ToString(), out var ac)+ || !uint.TryParse(obj[nameof(PreviousDcValue)]?.ToString(), out var dc)+ )+ throw new StepExecutionException("Invalid PowerSetting revert data.", "");+ return new PowerSettingRevertStep+ {+ SchemeId = scheme,+ SubgroupId = subgroup,+ SettingId = setting,+ PreviousAcValue = ac,+ PreviousDcValue = dc,+ };+ }+}diff --git a/optimizerDuck/Domain/Revert/Steps/RegistryRevertStep.cs b/optimizerDuck/Domain/Revert/Steps/RegistryRevertStep.csindex b6d305d..2636b8b 100644--- a/optimizerDuck/Domain/Revert/Steps/RegistryRevertStep.cs+++ b/optimizerDuck/Domain/Revert/Steps/RegistryRevertStep.cs@@ -79,7 +79,7 @@ public class RegistryRevertStep : IRevertStep};/// <inheritdoc />- public async Task<bool> ExecuteAsync(ShellService shell, ILogger logger)+ public async Task<bool> ExecuteAsync(RevertContext context, ILogger logger){var opCall = new OpCall { Logger = logger };OpResult result = Action switch@@ -100,7 +100,7 @@ public class RegistryRevertStep : IRevertStepnew RegistryItem(Path)),- RevertAction.RestoreKeyTree => await ExecuteSubStepsAsync(shell, logger)+ RevertAction.RestoreKeyTree => await ExecuteSubStepsAsync(context, logger).ConfigureAwait(false)? OpResult.Success(): OpResult.Fail(Description),@@ -333,13 +333,13 @@ public class RegistryRevertStep : IRevertStepprivate static bool ValuesEqual(object? actual, object? expected, RegistryValueKind kind) =>RegistryValues.Equal(actual, expected, kind);- private async Task<bool> ExecuteSubStepsAsync(ShellService shell, ILogger logger)+ private async Task<bool> ExecuteSubStepsAsync(RevertContext context, ILogger logger){if (SubSteps == null)return true;foreach (var step in SubSteps){- if (!await step.ExecuteAsync(shell, logger))+ if (!await step.ExecuteAsync(context, logger))return false;}return true;diff --git a/optimizerDuck/Domain/Revert/Steps/ScheduledTaskRevertStep.cs b/optimizerDuck/Domain/Revert/Steps/ScheduledTaskRevertStep.csindex 94a3683..4202956 100644--- a/optimizerDuck/Domain/Revert/Steps/ScheduledTaskRevertStep.cs+++ b/optimizerDuck/Domain/Revert/Steps/ScheduledTaskRevertStep.cs@@ -34,7 +34,7 @@ public class ScheduledTaskRevertStep : IRevertStep: Loc.Instance["Revert.ScheduledTask.Description.Disable", FullPath];/// <inheritdoc />- public Task<bool> ExecuteAsync(ShellService _, ILogger logger)+ public Task<bool> ExecuteAsync(RevertContext _, ILogger logger){var opCall = new OpCall { Logger = logger };var result = OriginalEnableddiff --git a/optimizerDuck/Domain/Revert/Steps/ServiceRevertStep.cs b/optimizerDuck/Domain/Revert/Steps/ServiceRevertStep.csindex 1488738..31305c1 100644--- a/optimizerDuck/Domain/Revert/Steps/ServiceRevertStep.cs+++ b/optimizerDuck/Domain/Revert/Steps/ServiceRevertStep.cs@@ -33,7 +33,7 @@ public class ServiceRevertStep : IRevertStepLoc.Instance["Revert.Service.Description.Restore", ServiceName, OriginalStartupType];/// <inheritdoc />- public async Task<bool> ExecuteAsync(ShellService _, ILogger logger)+ public async Task<bool> ExecuteAsync(RevertContext _, ILogger logger){var opCall = new OpCall { Logger = logger };var result = await ServiceProcessServicediff --git a/optimizerDuck/Domain/Revert/Steps/ShellRevertStep.cs b/optimizerDuck/Domain/Revert/Steps/ShellRevertStep.csindex d80f410..e32abaf 100644--- a/optimizerDuck/Domain/Revert/Steps/ShellRevertStep.cs+++ b/optimizerDuck/Domain/Revert/Steps/ShellRevertStep.cs@@ -31,14 +31,16 @@ public class ShellRevertStep : IRevertSteppublic string Description => Loc.Instance["Revert.Shell.Description.Run", ShellType, Command];/// <inheritdoc />- public async Task<bool> ExecuteAsync(ShellService shell, ILogger logger)+ public async Task<bool> ExecuteAsync(RevertContext context, ILogger logger){var result = ShellType switch{- ShellType.PowerShell => await shell- .QueryPowerShellAsync(Command, logger)+ ShellType.PowerShell => await context+ .Shell.QueryPowerShellAsync(Command, logger)+ .ConfigureAwait(false),+ ShellType.CMD => await context+ .Shell.QueryCMDAsync(Command, logger).ConfigureAwait(false),- ShellType.CMD => await shell.QueryCMDAsync(Command, logger).ConfigureAwait(false),_ => new ShellResult{Command = Command,diff --git a/optimizerDuck/Domain/Revert/Steps/UsbPowerRevertStep.cs b/optimizerDuck/Domain/Revert/Steps/UsbPowerRevertStep.csindex 792f386..dd4e7f8 100644--- a/optimizerDuck/Domain/Revert/Steps/UsbPowerRevertStep.cs+++ b/optimizerDuck/Domain/Revert/Steps/UsbPowerRevertStep.cs@@ -43,7 +43,7 @@ public class UsbPowerRevertStep : IRevertSteppublic string Description => Loc.Instance["Revert.UsbPower.Description"];/// <inheritdoc />- public async Task<bool> ExecuteAsync(ShellService shell, ILogger logger)+ public async Task<bool> ExecuteAsync(RevertContext context, ILogger logger){if (States.Count == 0)return true;@@ -64,7 +64,7 @@ public class UsbPowerRevertStep : IRevertStep+ "Set-CimInstance -CimInstance $obj -Property @{ Enable = [bool]$s.Enable } | Out-Null "+ "}}";- var result = await shell.QueryPowerShellAsync(script, logger).ConfigureAwait(false);+ var result = await context.Shell.QueryPowerShellAsync(script, logger).ConfigureAwait(false);if (result.ExitCode != 0){diff --git a/optimizerDuck/Resources/Languages/Translations.Designer.cs b/optimizerDuck/Resources/Languages/Translations.Designer.csindex 8c01f6d..08b491e 100644--- a/optimizerDuck/Resources/Languages/Translations.Designer.cs+++ b/optimizerDuck/Resources/Languages/Translations.Designer.cs@@ -411,6 +411,15 @@ namespace optimizerDuck.Resources.Languages {}}+ /// <summary>+ /// Looks up a localized string similar to Operation canceled..+ /// </summary>+ internal static string Common_OperationCancelled {+ get {+ return ResourceManager.GetString("Common.OperationCancelled", resourceCulture);+ }+ }+/// <summary>/// Looks up a localized string similar to Other./// </summary>@@ -510,6 +519,15 @@ namespace optimizerDuck.Resources.Languages {}}+ /// <summary>+ /// Looks up a localized string similar to Risk & Status.+ /// </summary>+ internal static string Common_SortBy_RiskAndStatus {+ get {+ return ResourceManager.GetString("Common.SortBy.RiskAndStatus", resourceCulture);+ }+ }+/// <summary>/// Looks up a localized string similar to Size./// </summary>@@ -2211,6 +2229,15 @@ namespace optimizerDuck.Resources.Languages {}}+ /// <summary>+ /// Looks up a localized string similar to {0} MHz.+ /// </summary>+ internal static string Dashboard_SystemInfo_Cpu_Frequency {+ get {+ return ResourceManager.GetString("Dashboard.SystemInfo.Cpu.Frequency", resourceCulture);+ }+ }+/// <summary>/// Looks up a localized string similar to {0} Threads./// </summary>@@ -2220,6 +2247,33 @@ namespace optimizerDuck.Resources.Languages {}}+ /// <summary>+ /// Looks up a localized string similar to Firmware: {0}.+ /// </summary>+ internal static string Dashboard_SystemInfo_Firmware {+ get {+ return ResourceManager.GetString("Dashboard.SystemInfo.Firmware", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Driver {0}.+ /// </summary>+ internal static string Dashboard_SystemInfo_Gpu_Driver {+ get {+ return ResourceManager.GetString("Dashboard.SystemInfo.Gpu.Driver", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to {0} GB.+ /// </summary>+ internal static string Dashboard_SystemInfo_Gpu_Memory {+ get {+ return ResourceManager.GetString("Dashboard.SystemInfo.Gpu.Memory", resourceCulture);+ }+ }+/// <summary>/// Looks up a localized string similar to + {0} more GPU./// </summary>@@ -2238,6 +2292,24 @@ namespace optimizerDuck.Resources.Languages {}}+ /// <summary>+ /// Looks up a localized string similar to {0} MT/s.+ /// </summary>+ internal static string Dashboard_SystemInfo_Memory_Speed {+ get {+ return ResourceManager.GetString("Dashboard.SystemInfo.Memory.Speed", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Memory integrity: {0}.+ /// </summary>+ internal static string Dashboard_SystemInfo_MemoryIntegrity {+ get {+ return ResourceManager.GetString("Dashboard.SystemInfo.MemoryIntegrity", resourceCulture);+ }+ }+/// <summary>/// Looks up a localized string similar to Build {0}./// </summary>@@ -2265,6 +2337,24 @@ namespace optimizerDuck.Resources.Languages {}}+ /// <summary>+ /// Looks up a localized string similar to Platform & security.+ /// </summary>+ internal static string Dashboard_SystemInfo_Platform_Header {+ get {+ return ResourceManager.GetString("Dashboard.SystemInfo.Platform.Header", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Power: {0}.+ /// </summary>+ internal static string Dashboard_SystemInfo_PowerPlan {+ get {+ return ResourceManager.GetString("Dashboard.SystemInfo.PowerPlan", resourceCulture);+ }+ }+/// <summary>/// Looks up a localized string similar to {0} GB Available./// </summary>@@ -2283,6 +2373,15 @@ namespace optimizerDuck.Resources.Languages {}}+ /// <summary>+ /// Looks up a localized string similar to {0} GB RAM.+ /// </summary>+ internal static string Dashboard_SystemInfo_Ram_Total {+ get {+ return ResourceManager.GetString("Dashboard.SystemInfo.Ram.Total", resourceCulture);+ }+ }+/// <summary>/// Looks up a localized string similar to {0} GB Used./// </summary>@@ -2292,6 +2391,15 @@ namespace optimizerDuck.Resources.Languages {}}+ /// <summary>+ /// Looks up a localized string similar to Secure Boot: {0}.+ /// </summary>+ internal static string Dashboard_SystemInfo_SecureBoot {+ get {+ return ResourceManager.GetString("Dashboard.SystemInfo.SecureBoot", resourceCulture);+ }+ }+/// <summary>/// Looks up a localized string similar to {0} GB used of {1} GB ({2} GB free)./// </summary>@@ -2319,6 +2427,24 @@ namespace optimizerDuck.Resources.Languages {}}+ /// <summary>+ /// Looks up a localized string similar to Uptime.+ /// </summary>+ internal static string Dashboard_SystemInfo_Uptime_Label {+ get {+ return ResourceManager.GetString("Dashboard.SystemInfo.Uptime.Label", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to VBS: {0}.+ /// </summary>+ internal static string Dashboard_SystemInfo_Vbs {+ get {+ return ResourceManager.GetString("Dashboard.SystemInfo.Vbs", resourceCulture);+ }+ }+/// <summary>/// Looks up a localized string similar to optimizerDuck (v{0}) is available!///Update now to enjoy the latest features, improvements, and bug fixes..@@ -2699,385 +2825,664 @@ namespace optimizerDuck.Resources.Languages {}/// <summary>- /// Looks up a localized string similar to Third-party notices.+ /// Looks up a localized string similar to ARM64./// </summary>- internal static string LegalDialog_Extras_Acknowledgements_Description {+ internal static string Enum_Architecture_Arm64 {get {- return ResourceManager.GetString("LegalDialog.Extras.Acknowledgements.Description", resourceCulture);+ return ResourceManager.GetString("Enum.Architecture.Arm64", resourceCulture);}}/// <summary>- /// Looks up a localized string similar to Acknowledgements.+ /// Looks up a localized string similar to 64-bit./// </summary>- internal static string LegalDialog_Extras_Acknowledgements_Title {+ internal static string Enum_Architecture_X64 {get {- return ResourceManager.GetString("LegalDialog.Extras.Acknowledgements.Title", resourceCulture);+ return ResourceManager.GetString("Enum.Architecture.X64", resourceCulture);}}/// <summary>- /// Looks up a localized string similar to Community & support.+ /// Looks up a localized string similar to 32-bit./// </summary>- internal static string LegalDialog_Extras_Discord_Description {+ internal static string Enum_Architecture_X86 {get {- return ResourceManager.GetString("LegalDialog.Extras.Discord.Description", resourceCulture);+ return ResourceManager.GetString("Enum.Architecture.X86", resourceCulture);}}/// <summary>- /// Looks up a localized string similar to Discord.+ /// Looks up a localized string similar to AMD./// </summary>- internal static string LegalDialog_Extras_Discord_Title {+ internal static string Enum_CpuVendor_Amd {get {- return ResourceManager.GetString("LegalDialog.Extras.Discord.Title", resourceCulture);+ return ResourceManager.GetString("Enum.CpuVendor.Amd", resourceCulture);}}/// <summary>- /// Looks up a localized string similar to Guides & getting started.+ /// Looks up a localized string similar to Intel./// </summary>- internal static string LegalDialog_Extras_Docs_Description {+ internal static string Enum_CpuVendor_Intel {get {- return ResourceManager.GetString("LegalDialog.Extras.Docs.Description", resourceCulture);+ return ResourceManager.GetString("Enum.CpuVendor.Intel", resourceCulture);}}/// <summary>- /// Looks up a localized string similar to Documentation.+ /// Looks up a localized string similar to Legacy BIOS./// </summary>- internal static string LegalDialog_Extras_Docs_Title {+ internal static string Enum_FirmwareMode_Legacy {get {- return ResourceManager.GetString("LegalDialog.Extras.Docs.Title", resourceCulture);+ return ResourceManager.GetString("Enum.FirmwareMode.Legacy", resourceCulture);}}/// <summary>- /// Looks up a localized string similar to Source code & issues.+ /// Looks up a localized string similar to UEFI./// </summary>- internal static string LegalDialog_Extras_GitHub_Description {+ internal static string Enum_FirmwareMode_Uefi {get {- return ResourceManager.GetString("LegalDialog.Extras.GitHub.Description", resourceCulture);+ return ResourceManager.GetString("Enum.FirmwareMode.Uefi", resourceCulture);}}/// <summary>- /// Looks up a localized string similar to GitHub.+ /// Looks up a localized string similar to AMD./// </summary>- internal static string LegalDialog_Extras_GitHub_Title {+ internal static string Enum_GpuVendor_Amd {get {- return ResourceManager.GetString("LegalDialog.Extras.GitHub.Title", resourceCulture);+ return ResourceManager.GetString("Enum.GpuVendor.Amd", resourceCulture);}}/// <summary>- /// Looks up a localized string similar to Explore.+ /// Looks up a localized string similar to Intel./// </summary>- internal static string LegalDialog_Extras_Header {+ internal static string Enum_GpuVendor_Intel {get {- return ResourceManager.GetString("LegalDialog.Extras.Header", resourceCulture);+ return ResourceManager.GetString("Enum.GpuVendor.Intel", resourceCulture);}}/// <summary>- /// Looks up a localized string similar to Choose your language and theme, take a moment to review our Terms, Privacy Policy, and Disclaimer, then you're ready to go..+ /// Looks up a localized string similar to NVIDIA./// </summary>- internal static string LegalDialog_Intro_Description {+ internal static string Enum_GpuVendor_Nvidia {get {- return ResourceManager.GetString("LegalDialog.Intro.Description", resourceCulture);+ return ResourceManager.GetString("Enum.GpuVendor.Nvidia", resourceCulture);}}/// <summary>- /// Looks up a localized string similar to Welcome to optimizerDuck!.+ /// Looks up a localized string similar to DDR2./// </summary>- internal static string LegalDialog_Intro_Title {+ internal static string Enum_MemoryType_Ddr2 {get {- return ResourceManager.GetString("LegalDialog.Intro.Title", resourceCulture);+ return ResourceManager.GetString("Enum.MemoryType.Ddr2", resourceCulture);}}/// <summary>- /// Looks up a localized string similar to Choose your preferred language.+ /// Looks up a localized string similar to DDR3./// </summary>- internal static string LegalDialog_Language_Description {+ internal static string Enum_MemoryType_Ddr3 {get {- return ResourceManager.GetString("LegalDialog.Language.Description", resourceCulture);+ return ResourceManager.GetString("Enum.MemoryType.Ddr3", resourceCulture);}}/// <summary>- /// Looks up a localized string similar to Language.+ /// Looks up a localized string similar to DDR4./// </summary>- internal static string LegalDialog_Language_Title {+ internal static string Enum_MemoryType_Ddr4 {get {- return ResourceManager.GetString("LegalDialog.Language.Title", resourceCulture);+ return ResourceManager.GetString("Enum.MemoryType.Ddr4", resourceCulture);}}/// <summary>- /// Looks up a localized string similar to Disclaimer.+ /// Looks up a localized string similar to DDR5./// </summary>- internal static string LegalDialog_Link_Disclaimer {+ internal static string Enum_MemoryType_Ddr5 {get {- return ResourceManager.GetString("LegalDialog.Link.Disclaimer", resourceCulture);+ return ResourceManager.GetString("Enum.MemoryType.Ddr5", resourceCulture);}}/// <summary>- /// Looks up a localized string similar to Privacy Policy.+ /// Looks up a localized string similar to Other./// </summary>- internal static string LegalDialog_Link_PrivacyPolicy {+ internal static string Enum_MemoryType_Other {get {- return ResourceManager.GetString("LegalDialog.Link.PrivacyPolicy", resourceCulture);+ return ResourceManager.GetString("Enum.MemoryType.Other", resourceCulture);}}/// <summary>- /// Looks up a localized string similar to Terms of Service.+ /// Looks up a localized string similar to SDRAM./// </summary>- internal static string LegalDialog_Link_TermsOfService {+ internal static string Enum_MemoryType_Sdram {get {- return ResourceManager.GetString("LegalDialog.Link.TermsOfService", resourceCulture);+ return ResourceManager.GetString("Enum.MemoryType.Sdram", resourceCulture);}}/// <summary>- /// Looks up a localized string similar to Preferences.+ /// Looks up a localized string similar to Disabled./// </summary>- internal static string LegalDialog_Preferences_Header {+ internal static string Enum_SecureBootState_Disabled {get {- return ResourceManager.GetString("LegalDialog.Preferences.Header", resourceCulture);+ return ResourceManager.GetString("Enum.SecureBootState.Disabled", resourceCulture);}}/// <summary>- /// Looks up a localized string similar to Choose your preferred theme.+ /// Looks up a localized string similar to Enabled./// </summary>- internal static string LegalDialog_Theme_Description {+ internal static string Enum_SecureBootState_Enabled {get {- return ResourceManager.GetString("LegalDialog.Theme.Description", resourceCulture);+ return ResourceManager.GetString("Enum.SecureBootState.Enabled", resourceCulture);}}/// <summary>- /// Looks up a localized string similar to Theme.+ /// Looks up a localized string similar to Unavailable./// </summary>- internal static string LegalDialog_Theme_Title {+ internal static string Enum_SecureBootState_Unavailable {get {- return ResourceManager.GetString("LegalDialog.Theme.Title", resourceCulture);+ return ResourceManager.GetString("Enum.SecureBootState.Unavailable", resourceCulture);}}/// <summary>- /// Looks up a localized string similar to Legal Agreement.+ /// Looks up a localized string similar to HDD./// </summary>- internal static string LegalDialog_Title {+ internal static string Enum_StorageMediaType_Hdd {get {- return ResourceManager.GetString("LegalDialog.Title", resourceCulture);+ return ResourceManager.GetString("Enum.StorageMediaType.Hdd", resourceCulture);}}/// <summary>- /// Looks up a localized string similar to We recommend creating a backup before applying any changes..+ /// Looks up a localized string similar to NVMe./// </summary>- internal static string LegalDialog_Warning_Message {+ internal static string Enum_StorageMediaType_Nvme {get {- return ResourceManager.GetString("LegalDialog.Warning.Message", resourceCulture);+ return ResourceManager.GetString("Enum.StorageMediaType.Nvme", resourceCulture);}}/// <summary>- /// Looks up a localized string similar to Use at your own risk.+ /// Looks up a localized string similar to SSD./// </summary>- internal static string LegalDialog_Warning_Title {+ internal static string Enum_StorageMediaType_Ssd {get {- return ResourceManager.GetString("LegalDialog.Warning.Title", resourceCulture);+ return ResourceManager.GetString("Enum.StorageMediaType.Ssd", resourceCulture);}}/// <summary>- /// Looks up a localized string similar to Completed.+ /// Looks up a localized string similar to Disabled./// </summary>- internal static string Optimization_Apply_Completed {+ internal static string Enum_VbsState_Disabled {get {- return ResourceManager.GetString("Optimization.Apply.Completed", resourceCulture);+ return ResourceManager.GetString("Enum.VbsState.Disabled", resourceCulture);}}/// <summary>- /// Looks up a localized string similar to Failed to apply {0}..+ /// Looks up a localized string similar to Enabled./// </summary>- internal static string Optimization_Apply_Error_Failed {+ internal static string Enum_VbsState_Enabled {get {- return ResourceManager.GetString("Optimization.Apply.Error.Failed", resourceCulture);+ return ResourceManager.GetString("Enum.VbsState.Enabled", resourceCulture);}}/// <summary>- /// Looks up a localized string similar to Applied {0} with {1} failed step(s)..+ /// Looks up a localized string similar to Unavailable./// </summary>- internal static string Optimization_Apply_Error_FailedWithSteps {+ internal static string Enum_VbsState_Unavailable {get {- return ResourceManager.GetString("Optimization.Apply.Error.FailedWithSteps", resourceCulture);+ return ResourceManager.GetString("Enum.VbsState.Unavailable", resourceCulture);}}/// <summary>- /// Looks up a localized string similar to Unknown result for {0}..+ /// Looks up a localized string similar to Education./// </summary>- internal static string Optimization_Apply_Error_Unknown {+ internal static string Enum_WindowsEdition_Education {get {- return ResourceManager.GetString("Optimization.Apply.Error.Unknown", resourceCulture);+ return ResourceManager.GetString("Enum.WindowsEdition.Education", resourceCulture);}}/// <summary>- /// Looks up a localized string similar to Applying changes....+ /// Looks up a localized string similar to Enterprise./// </summary>- internal static string Optimization_Apply_Processing {+ internal static string Enum_WindowsEdition_Enterprise {get {- return ResourceManager.GetString("Optimization.Apply.Processing", resourceCulture);+ return ResourceManager.GetString("Enum.WindowsEdition.Enterprise", resourceCulture);}}/// <summary>- /// Looks up a localized string similar to Couldn't fully apply optimization.+ /// Looks up a localized string similar to Home./// </summary>- internal static string Optimization_Apply_Snackbar_Error_Title {+ internal static string Enum_WindowsEdition_Home {get {- return ResourceManager.GetString("Optimization.Apply.Snackbar.Error.Title", resourceCulture);+ return ResourceManager.GetString("Enum.WindowsEdition.Home", resourceCulture);}}/// <summary>- /// Looks up a localized string similar to Optimization applied successfully.+ /// Looks up a localized string similar to Pro./// </summary>- internal static string Optimization_Apply_Snackbar_Success_Title {+ internal static string Enum_WindowsEdition_Pro {get {- return ResourceManager.GetString("Optimization.Apply.Snackbar.Success.Title", resourceCulture);+ return ResourceManager.GetString("Enum.WindowsEdition.Pro", resourceCulture);}}/// <summary>- /// Looks up a localized string similar to Successfully applied {0}..+ /// Looks up a localized string similar to Server./// </summary>- internal static string Optimization_Apply_Success {+ internal static string Enum_WindowsEdition_Server {get {- return ResourceManager.GetString("Optimization.Apply.Success", resourceCulture);+ return ResourceManager.GetString("Enum.WindowsEdition.Server", resourceCulture);}}/// <summary>- /// Looks up a localized string similar to Retrying failed steps....+ /// Looks up a localized string similar to Third-party notices./// </summary>- internal static string Optimization_Retry_Processing {+ internal static string LegalDialog_Extras_Acknowledgements_Description {get {- return ResourceManager.GetString("Optimization.Retry.Processing", resourceCulture);+ return ResourceManager.GetString("LegalDialog.Extras.Acknowledgements.Description", resourceCulture);}}/// <summary>- /// Looks up a localized string similar to Retrying {0} step ({1}/{2} steps).+ /// Looks up a localized string similar to Acknowledgements./// </summary>- internal static string Optimization_RetryStep_Processing {+ internal static string LegalDialog_Extras_Acknowledgements_Title {get {- return ResourceManager.GetString("Optimization.RetryStep.Processing", resourceCulture);+ return ResourceManager.GetString("LegalDialog.Extras.Acknowledgements.Title", resourceCulture);}}/// <summary>- /// Looks up a localized string similar to Failed to revert {0}..+ /// Looks up a localized string similar to Community & support./// </summary>- internal static string Optimization_Revert_Error_Failed {+ internal static string LegalDialog_Extras_Discord_Description {get {- return ResourceManager.GetString("Optimization.Revert.Error.Failed", resourceCulture);+ return ResourceManager.GetString("LegalDialog.Extras.Discord.Description", resourceCulture);}}/// <summary>- /// Looks up a localized string similar to Reverted {0} with {1} failed step(s)..+ /// Looks up a localized string similar to Discord./// </summary>- internal static string Optimization_Revert_Error_FailedWithSteps {+ internal static string LegalDialog_Extras_Discord_Title {get {- return ResourceManager.GetString("Optimization.Revert.Error.FailedWithSteps", resourceCulture);+ return ResourceManager.GetString("LegalDialog.Extras.Discord.Title", resourceCulture);}}/// <summary>- /// Looks up a localized string similar to Executing revert step: {0}/{1} ({2}).+ /// Looks up a localized string similar to Guides & getting started./// </summary>- internal static string Optimization_Revert_ExecutingStep {+ internal static string LegalDialog_Extras_Docs_Description {get {- return ResourceManager.GetString("Optimization.Revert.ExecutingStep", resourceCulture);+ return ResourceManager.GetString("LegalDialog.Extras.Docs.Description", resourceCulture);}}/// <summary>- /// Looks up a localized string similar to Reverting....+ /// Looks up a localized string similar to Documentation./// </summary>- internal static string Optimization_Revert_Reverting {+ internal static string LegalDialog_Extras_Docs_Title {get {- return ResourceManager.GetString("Optimization.Revert.Reverting", resourceCulture);+ return ResourceManager.GetString("LegalDialog.Extras.Docs.Title", resourceCulture);}}/// <summary>- /// Looks up a localized string similar to Couldn't revert optimization.+ /// Looks up a localized string similar to Source code & issues./// </summary>- internal static string Optimization_Revert_Snackbar_Error_Title {+ internal static string LegalDialog_Extras_GitHub_Description {get {- return ResourceManager.GetString("Optimization.Revert.Snackbar.Error.Title", resourceCulture);+ return ResourceManager.GetString("LegalDialog.Extras.GitHub.Description", resourceCulture);}}/// <summary>- /// Looks up a localized string similar to Optimization reverted successfully.+ /// Looks up a localized string similar to GitHub./// </summary>- internal static string Optimization_Revert_Snackbar_Success_Title {+ internal static string LegalDialog_Extras_GitHub_Title {get {- return ResourceManager.GetString("Optimization.Revert.Snackbar.Success.Title", resourceCulture);+ return ResourceManager.GetString("LegalDialog.Extras.GitHub.Title", resourceCulture);}}/// <summary>- /// Looks up a localized string similar to Successfully reverted {0}!.+ /// Looks up a localized string similar to Explore./// </summary>- internal static string Optimization_Revert_Success {+ internal static string LegalDialog_Extras_Header {get {- return ResourceManager.GetString("Optimization.Revert.Success", resourceCulture);+ return ResourceManager.GetString("LegalDialog.Extras.Header", resourceCulture);}}/// <summary>- /// Looks up a localized string similar to An error occurred: {0}.+ /// Looks up a localized string similar to Choose your language and theme, take a moment to review our Terms, Privacy Policy, and Disclaimer, then you're ready to go../// </summary>- internal static string Optimization_Toggle_Snackbar_Error_Message {+ internal static string LegalDialog_Intro_Description {get {- return ResourceManager.GetString("Optimization.Toggle.Snackbar.Error.Message", resourceCulture);+ return ResourceManager.GetString("LegalDialog.Intro.Description", resourceCulture);}}/// <summary>- /// Looks up a localized string similar to Couldn't toggle optimization.+ /// Looks up a localized string similar to Welcome to optimizerDuck!./// </summary>- internal static string Optimization_Toggle_Snackbar_Error_Title {+ internal static string LegalDialog_Intro_Title {get {- return ResourceManager.GetString("Optimization.Toggle.Snackbar.Error.Title", resourceCulture);+ return ResourceManager.GetString("LegalDialog.Intro.Title", resourceCulture);}}/// <summary>- /// Looks up a localized string similar to Class Name.+ /// Looks up a localized string similar to Choose your preferred language./// </summary>- internal static string OptimizationDetailsDialog_Class {+ internal static string LegalDialog_Language_Description {get {- return ResourceManager.GetString("OptimizationDetailsDialog.Class", resourceCulture);+ return ResourceManager.GetString("LegalDialog.Language.Description", resourceCulture);}}/// <summary>- /// Looks up a localized string similar to Detailed description.+ /// Looks up a localized string similar to Language.+ /// </summary>+ internal static string LegalDialog_Language_Title {+ get {+ return ResourceManager.GetString("LegalDialog.Language.Title", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Disclaimer.+ /// </summary>+ internal static string LegalDialog_Link_Disclaimer {+ get {+ return ResourceManager.GetString("LegalDialog.Link.Disclaimer", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Privacy Policy.+ /// </summary>+ internal static string LegalDialog_Link_PrivacyPolicy {+ get {+ return ResourceManager.GetString("LegalDialog.Link.PrivacyPolicy", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Terms of Service.+ /// </summary>+ internal static string LegalDialog_Link_TermsOfService {+ get {+ return ResourceManager.GetString("LegalDialog.Link.TermsOfService", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Preferences.+ /// </summary>+ internal static string LegalDialog_Preferences_Header {+ get {+ return ResourceManager.GetString("LegalDialog.Preferences.Header", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Choose your preferred theme.+ /// </summary>+ internal static string LegalDialog_Theme_Description {+ get {+ return ResourceManager.GetString("LegalDialog.Theme.Description", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Theme.+ /// </summary>+ internal static string LegalDialog_Theme_Title {+ get {+ return ResourceManager.GetString("LegalDialog.Theme.Title", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Legal Agreement.+ /// </summary>+ internal static string LegalDialog_Title {+ get {+ return ResourceManager.GetString("LegalDialog.Title", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to We recommend creating a backup before applying any changes..+ /// </summary>+ internal static string LegalDialog_Warning_Message {+ get {+ return ResourceManager.GetString("LegalDialog.Warning.Message", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Use at your own risk.+ /// </summary>+ internal static string LegalDialog_Warning_Title {+ get {+ return ResourceManager.GetString("LegalDialog.Warning.Title", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Completed.+ /// </summary>+ internal static string Optimization_Apply_Completed {+ get {+ return ResourceManager.GetString("Optimization.Apply.Completed", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to All steps failed..+ /// </summary>+ internal static string Optimization_Apply_Error_AllStepsFailed {+ get {+ return ResourceManager.GetString("Optimization.Apply.Error.AllStepsFailed", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Failed to apply {0}..+ /// </summary>+ internal static string Optimization_Apply_Error_Failed {+ get {+ return ResourceManager.GetString("Optimization.Apply.Error.Failed", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Applied {0} with {1} failed step(s)..+ /// </summary>+ internal static string Optimization_Apply_Error_FailedWithSteps {+ get {+ return ResourceManager.GetString("Optimization.Apply.Error.FailedWithSteps", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Unknown result for {0}..+ /// </summary>+ internal static string Optimization_Apply_Error_Unknown {+ get {+ return ResourceManager.GetString("Optimization.Apply.Error.Unknown", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Applying changes....+ /// </summary>+ internal static string Optimization_Apply_Processing {+ get {+ return ResourceManager.GetString("Optimization.Apply.Processing", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Couldn't fully apply optimization.+ /// </summary>+ internal static string Optimization_Apply_Snackbar_Error_Title {+ get {+ return ResourceManager.GetString("Optimization.Apply.Snackbar.Error.Title", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Optimization applied successfully.+ /// </summary>+ internal static string Optimization_Apply_Snackbar_Success_Title {+ get {+ return ResourceManager.GetString("Optimization.Apply.Snackbar.Success.Title", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Successfully applied {0}..+ /// </summary>+ internal static string Optimization_Apply_Success {+ get {+ return ResourceManager.GetString("Optimization.Apply.Success", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Retrying failed steps....+ /// </summary>+ internal static string Optimization_Retry_Processing {+ get {+ return ResourceManager.GetString("Optimization.Retry.Processing", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Retrying {0} step ({1}/{2} steps).+ /// </summary>+ internal static string Optimization_RetryStep_Processing {+ get {+ return ResourceManager.GetString("Optimization.RetryStep.Processing", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Failed to revert {0}..+ /// </summary>+ internal static string Optimization_Revert_Error_Failed {+ get {+ return ResourceManager.GetString("Optimization.Revert.Error.Failed", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Reverted {0} with {1} failed step(s)..+ /// </summary>+ internal static string Optimization_Revert_Error_FailedWithSteps {+ get {+ return ResourceManager.GetString("Optimization.Revert.Error.FailedWithSteps", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Executing revert step: {0}/{1} ({2}).+ /// </summary>+ internal static string Optimization_Revert_ExecutingStep {+ get {+ return ResourceManager.GetString("Optimization.Revert.ExecutingStep", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Reverting....+ /// </summary>+ internal static string Optimization_Revert_Reverting {+ get {+ return ResourceManager.GetString("Optimization.Revert.Reverting", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Couldn't revert optimization.+ /// </summary>+ internal static string Optimization_Revert_Snackbar_Error_Title {+ get {+ return ResourceManager.GetString("Optimization.Revert.Snackbar.Error.Title", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Optimization reverted successfully.+ /// </summary>+ internal static string Optimization_Revert_Snackbar_Success_Title {+ get {+ return ResourceManager.GetString("Optimization.Revert.Snackbar.Success.Title", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Successfully reverted {0}!.+ /// </summary>+ internal static string Optimization_Revert_Success {+ get {+ return ResourceManager.GetString("Optimization.Revert.Success", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to An error occurred: {0}.+ /// </summary>+ internal static string Optimization_Toggle_Snackbar_Error_Message {+ get {+ return ResourceManager.GetString("Optimization.Toggle.Snackbar.Error.Message", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Couldn't toggle optimization.+ /// </summary>+ internal static string Optimization_Toggle_Snackbar_Error_Title {+ get {+ return ResourceManager.GetString("Optimization.Toggle.Snackbar.Error.Title", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Class Name.+ /// </summary>+ internal static string OptimizationDetailsDialog_Class {+ get {+ return ResourceManager.GetString("OptimizationDetailsDialog.Class", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Detailed description./// </summary>internal static string OptimizationDetailsDialog_DetailedDescription {get {@@ -4493,6 +4898,78 @@ namespace optimizerDuck.Resources.Languages {}}+ /// <summary>+ /// Looks up a localized string similar to Restore previous active power plan {0}.+ /// </summary>+ internal static string Revert_PowerPlan_Description {+ get {+ return ResourceManager.GetString("Revert.PowerPlan.Description", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Installed power plan {0}.+ /// </summary>+ internal static string Revert_PowerPlan_Description_Set {+ get {+ return ResourceManager.GetString("Revert.PowerPlan.Description.Set", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Failed to delete optimizerDuck power plan: {0}.+ /// </summary>+ internal static string Revert_PowerPlan_Error_DeleteFailed {+ get {+ return ResourceManager.GetString("Revert.PowerPlan.Error.DeleteFailed", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Nothing to revert: no previous or installed power plan recorded..+ /// </summary>+ internal static string Revert_PowerPlan_Error_NothingToDo {+ get {+ return ResourceManager.GetString("Revert.PowerPlan.Error.NothingToDo", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Failed to restore previous power plan: {0}..+ /// </summary>+ internal static string Revert_PowerPlan_Error_RestoreFailed {+ get {+ return ResourceManager.GetString("Revert.PowerPlan.Error.RestoreFailed", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Restored power plan {0} but could not verify the active plan..+ /// </summary>+ internal static string Revert_PowerPlan_Error_VerifyFailed {+ get {+ return ResourceManager.GetString("Revert.PowerPlan.Error.VerifyFailed", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Power plan verify failed: expected {0}, active is {1}..+ /// </summary>+ internal static string Revert_PowerPlan_Error_VerifyMismatch {+ get {+ return ResourceManager.GetString("Revert.PowerPlan.Error.VerifyMismatch", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Restore power setting {0}/{1}/{2}.+ /// </summary>+ internal static string Revert_PowerSetting_Description {+ get {+ return ResourceManager.GetString("Revert.PowerSetting.Description", resourceCulture);+ }+ }+/// <summary>/// Looks up a localized string similar to Delete registry value: {0}\{1}./// </summary>@@ -4943,6 +5420,312 @@ namespace optimizerDuck.Resources.Languages {}}+ /// <summary>+ /// Looks up a localized string similar to At startup.+ /// </summary>+ internal static string ScheduledTasks_Trigger_Boot {+ get {+ return ResourceManager.GetString("ScheduledTasks.Trigger.Boot", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Daily.+ /// </summary>+ internal static string ScheduledTasks_Trigger_Daily {+ get {+ return ResourceManager.GetString("ScheduledTasks.Trigger.Daily", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to On event.+ /// </summary>+ internal static string ScheduledTasks_Trigger_Event {+ get {+ return ResourceManager.GetString("ScheduledTasks.Trigger.Event", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to When idle.+ /// </summary>+ internal static string ScheduledTasks_Trigger_Idle {+ get {+ return ResourceManager.GetString("ScheduledTasks.Trigger.Idle", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to At log on.+ /// </summary>+ internal static string ScheduledTasks_Trigger_Logon {+ get {+ return ResourceManager.GetString("ScheduledTasks.Trigger.Logon", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Monthly.+ /// </summary>+ internal static string ScheduledTasks_Trigger_Monthly {+ get {+ return ResourceManager.GetString("ScheduledTasks.Trigger.Monthly", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Monthly.+ /// </summary>+ internal static string ScheduledTasks_Trigger_MonthlyDOW {+ get {+ return ResourceManager.GetString("ScheduledTasks.Trigger.MonthlyDOW", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Trigger.+ /// </summary>+ internal static string ScheduledTasks_Trigger_Other {+ get {+ return ResourceManager.GetString("ScheduledTasks.Trigger.Other", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to At registration.+ /// </summary>+ internal static string ScheduledTasks_Trigger_Registration {+ get {+ return ResourceManager.GetString("ScheduledTasks.Trigger.Registration", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Console connect.+ /// </summary>+ internal static string ScheduledTasks_Trigger_Session_ConsoleConnect {+ get {+ return ResourceManager.GetString("ScheduledTasks.Trigger.Session.ConsoleConnect", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Console disconnect.+ /// </summary>+ internal static string ScheduledTasks_Trigger_Session_ConsoleDisconnect {+ get {+ return ResourceManager.GetString("ScheduledTasks.Trigger.Session.ConsoleDisconnect", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Session lock.+ /// </summary>+ internal static string ScheduledTasks_Trigger_Session_Lock {+ get {+ return ResourceManager.GetString("ScheduledTasks.Trigger.Session.Lock", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Remote connect.+ /// </summary>+ internal static string ScheduledTasks_Trigger_Session_RemoteConnect {+ get {+ return ResourceManager.GetString("ScheduledTasks.Trigger.Session.RemoteConnect", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Remote disconnect.+ /// </summary>+ internal static string ScheduledTasks_Trigger_Session_RemoteDisconnect {+ get {+ return ResourceManager.GetString("ScheduledTasks.Trigger.Session.RemoteDisconnect", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Session unlock.+ /// </summary>+ internal static string ScheduledTasks_Trigger_Session_Unlock {+ get {+ return ResourceManager.GetString("ScheduledTasks.Trigger.Session.Unlock", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to On session change.+ /// </summary>+ internal static string ScheduledTasks_Trigger_SessionStateChange {+ get {+ return ResourceManager.GetString("ScheduledTasks.Trigger.SessionStateChange", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to At a specific time.+ /// </summary>+ internal static string ScheduledTasks_Trigger_Time {+ get {+ return ResourceManager.GetString("ScheduledTasks.Trigger.Time", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to every.+ /// </summary>+ internal static string ScheduledTasks_Trigger_Week_Every {+ get {+ return ResourceManager.GetString("ScheduledTasks.Trigger.Week.Every", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to first.+ /// </summary>+ internal static string ScheduledTasks_Trigger_Week_First {+ get {+ return ResourceManager.GetString("ScheduledTasks.Trigger.Week.First", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to fourth.+ /// </summary>+ internal static string ScheduledTasks_Trigger_Week_Fourth {+ get {+ return ResourceManager.GetString("ScheduledTasks.Trigger.Week.Fourth", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to last.+ /// </summary>+ internal static string ScheduledTasks_Trigger_Week_Last {+ get {+ return ResourceManager.GetString("ScheduledTasks.Trigger.Week.Last", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to second.+ /// </summary>+ internal static string ScheduledTasks_Trigger_Week_Second {+ get {+ return ResourceManager.GetString("ScheduledTasks.Trigger.Week.Second", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to third.+ /// </summary>+ internal static string ScheduledTasks_Trigger_Week_Third {+ get {+ return ResourceManager.GetString("ScheduledTasks.Trigger.Week.Third", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Weekly.+ /// </summary>+ internal static string ScheduledTasks_Trigger_Weekly {+ get {+ return ResourceManager.GetString("ScheduledTasks.Trigger.Weekly", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Every {0} day(s), at {1}.+ /// </summary>+ internal static string ScheduledTasks_TriggerDetail_Daily {+ get {+ return ResourceManager.GetString("ScheduledTasks.TriggerDetail.Daily", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to after {0}.+ /// </summary>+ internal static string ScheduledTasks_TriggerDetail_Delay {+ get {+ return ResourceManager.GetString("ScheduledTasks.TriggerDetail.Delay", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to On day(s) {0} of {1}.+ /// </summary>+ internal static string ScheduledTasks_TriggerDetail_Monthly {+ get {+ return ResourceManager.GetString("ScheduledTasks.TriggerDetail.Monthly", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to {0} {1} of {2}.+ /// </summary>+ internal static string ScheduledTasks_TriggerDetail_MonthlyDOW {+ get {+ return ResourceManager.GetString("ScheduledTasks.TriggerDetail.MonthlyDOW", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to (repeat every {0}).+ /// </summary>+ internal static string ScheduledTasks_TriggerDetail_Repeat {+ get {+ return ResourceManager.GetString("ScheduledTasks.TriggerDetail.Repeat", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to (repeat every {0} for {1}).+ /// </summary>+ internal static string ScheduledTasks_TriggerDetail_RepeatFor {+ get {+ return ResourceManager.GetString("ScheduledTasks.TriggerDetail.RepeatFor", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to At {0}.+ /// </summary>+ internal static string ScheduledTasks_TriggerDetail_Time {+ get {+ return ResourceManager.GetString("ScheduledTasks.TriggerDetail.Time", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to for user {0}.+ /// </summary>+ internal static string ScheduledTasks_TriggerDetail_User {+ get {+ return ResourceManager.GetString("ScheduledTasks.TriggerDetail.User", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to for user {0} after {1}.+ /// </summary>+ internal static string ScheduledTasks_TriggerDetail_UserDelay {+ get {+ return ResourceManager.GetString("ScheduledTasks.TriggerDetail.UserDelay", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Every {0} week(s) on {1}, at {2}.+ /// </summary>+ internal static string ScheduledTasks_TriggerDetail_Weekly {+ get {+ return ResourceManager.GetString("ScheduledTasks.TriggerDetail.Weekly", resourceCulture);+ }+ }+/// <summary>/// Looks up a localized string similar to Exit code {0}./// </summary>diff --git a/optimizerDuck/Resources/Languages/Translations.resx b/optimizerDuck/Resources/Languages/Translations.resxindex 542ff27..d23a2db 100644--- a/optimizerDuck/Resources/Languages/Translations.resx+++ b/optimizerDuck/Resources/Languages/Translations.resx@@ -344,6 +344,31 @@<data name="Revert.UsbPower.Description" xml:space="preserve"><value>Restore USB selective suspend power states</value></data>+ <data name="Revert.PowerPlan.Description" xml:space="preserve">+ <value>Restore previous active power plan {0}</value>+ </data>+ <data name="Revert.PowerPlan.Description.Set" xml:space="preserve">+ <value>Installed power plan {0}</value>+ </data>++ <data name="Revert.PowerPlan.Error.RestoreFailed" xml:space="preserve">+ <value>Failed to restore previous power plan: {0}.</value>+ </data>+ <data name="Revert.PowerPlan.Error.DeleteFailed" xml:space="preserve">+ <value>Failed to delete optimizerDuck power plan: {0}</value>+ </data>+ <data name="Revert.PowerPlan.Error.NothingToDo" xml:space="preserve">+ <value>Nothing to revert: no previous or installed power plan recorded.</value>+ </data>+ <data name="Revert.PowerPlan.Error.VerifyFailed" xml:space="preserve">+ <value>Restored power plan {0} but could not verify the active plan.</value>+ </data>+ <data name="Revert.PowerPlan.Error.VerifyMismatch" xml:space="preserve">+ <value>Power plan verify failed: expected {0}, active is {1}.</value>+ </data>+ <data name="Revert.PowerSetting.Description" xml:space="preserve">+ <value>Restore power setting {0}/{1}/{2}</value>+ </data><data name="Optimization.Apply.Processing" xml:space="preserve"><value>Applying changes...</value></data>@@ -1264,6 +1289,126 @@ Update now to enjoy the latest features, improvements, and bug fixes.</value><data name="Dashboard.SystemInfo.Os.Build" xml:space="preserve"><value>Build {0}</value></data>+ <data name="Dashboard.SystemInfo.Platform.Header" xml:space="preserve">+ <value>Platform & security</value>+ </data>+ <data name="Dashboard.SystemInfo.Firmware" xml:space="preserve">+ <value>Firmware: {0}</value>+ </data>+ <data name="Dashboard.SystemInfo.SecureBoot" xml:space="preserve">+ <value>Secure Boot: {0}</value>+ </data>+ <data name="Dashboard.SystemInfo.Vbs" xml:space="preserve">+ <value>VBS: {0}</value>+ </data>+ <data name="Dashboard.SystemInfo.MemoryIntegrity" xml:space="preserve">+ <value>Memory integrity: {0}</value>+ </data>+ <data name="Dashboard.SystemInfo.PowerPlan" xml:space="preserve">+ <value>Power: {0}</value>+ </data>+ <data name="Dashboard.SystemInfo.Uptime.Label" xml:space="preserve">+ <value>Uptime</value>+ </data>+ <data name="Dashboard.SystemInfo.Memory.Speed" xml:space="preserve">+ <value>{0} MT/s</value>+ </data>+ <data name="Dashboard.SystemInfo.Cpu.Frequency" xml:space="preserve">+ <value>{0} MHz</value>+ </data>+ <data name="Dashboard.SystemInfo.Gpu.Driver" xml:space="preserve">+ <value>Driver {0}</value>+ </data>+ <data name="Enum.CpuVendor.Intel" xml:space="preserve">+ <value>Intel</value>+ </data>+ <data name="Enum.CpuVendor.Amd" xml:space="preserve">+ <value>AMD</value>+ </data>+ <data name="Enum.GpuVendor.Nvidia" xml:space="preserve">+ <value>NVIDIA</value>+ </data>+ <data name="Enum.GpuVendor.Amd" xml:space="preserve">+ <value>AMD</value>+ </data>+ <data name="Enum.GpuVendor.Intel" xml:space="preserve">+ <value>Intel</value>+ </data>+ <data name="Enum.Architecture.X64" xml:space="preserve">+ <value>64-bit</value>+ </data>+ <data name="Enum.Architecture.X86" xml:space="preserve">+ <value>32-bit</value>+ </data>+ <data name="Enum.Architecture.Arm64" xml:space="preserve">+ <value>ARM64</value>+ </data>+ <data name="Enum.FirmwareMode.Uefi" xml:space="preserve">+ <value>UEFI</value>+ </data>+ <data name="Enum.FirmwareMode.Legacy" xml:space="preserve">+ <value>Legacy BIOS</value>+ </data>+ <data name="Enum.SecureBootState.Enabled" xml:space="preserve">+ <value>Enabled</value>+ </data>+ <data name="Enum.SecureBootState.Disabled" xml:space="preserve">+ <value>Disabled</value>+ </data>+ <data name="Enum.SecureBootState.Unavailable" xml:space="preserve">+ <value>Unavailable</value>+ </data>+ <data name="Enum.VbsState.Enabled" xml:space="preserve">+ <value>Enabled</value>+ </data>+ <data name="Enum.VbsState.Disabled" xml:space="preserve">+ <value>Disabled</value>+ </data>+ <data name="Enum.VbsState.Unavailable" xml:space="preserve">+ <value>Unavailable</value>+ </data>+ <data name="Enum.MemoryType.Ddr2" xml:space="preserve">+ <value>DDR2</value>+ </data>+ <data name="Enum.MemoryType.Ddr3" xml:space="preserve">+ <value>DDR3</value>+ </data>+ <data name="Enum.MemoryType.Ddr4" xml:space="preserve">+ <value>DDR4</value>+ </data>+ <data name="Enum.MemoryType.Ddr5" xml:space="preserve">+ <value>DDR5</value>+ </data>+ <data name="Enum.MemoryType.Sdram" xml:space="preserve">+ <value>SDRAM</value>+ </data>+ <data name="Enum.MemoryType.Other" xml:space="preserve">+ <value>Other</value>+ </data>+ <data name="Enum.StorageMediaType.Hdd" xml:space="preserve">+ <value>HDD</value>+ </data>+ <data name="Enum.StorageMediaType.Ssd" xml:space="preserve">+ <value>SSD</value>+ </data>+ <data name="Enum.StorageMediaType.Nvme" xml:space="preserve">+ <value>NVMe</value>+ </data>+ <data name="Enum.WindowsEdition.Home" xml:space="preserve">+ <value>Home</value>+ </data>+ <data name="Enum.WindowsEdition.Pro" xml:space="preserve">+ <value>Pro</value>+ </data>+ <data name="Enum.WindowsEdition.Education" xml:space="preserve">+ <value>Education</value>+ </data>+ <data name="Enum.WindowsEdition.Enterprise" xml:space="preserve">+ <value>Enterprise</value>+ </data>+ <data name="Enum.WindowsEdition.Server" xml:space="preserve">+ <value>Server</value>+ </data><data name="Bloatware.Header.Description" xml:space="preserve"><value>Manage and remove pre-installed applications that you don't need</value></data>diff --git a/optimizerDuck/Services/Conditions/ConditionEvaluator.cs b/optimizerDuck/Services/Conditions/ConditionEvaluator.csindex c051218..2472f46 100644--- a/optimizerDuck/Services/Conditions/ConditionEvaluator.cs+++ b/optimizerDuck/Services/Conditions/ConditionEvaluator.cs@@ -27,11 +27,7 @@ public static class ConditionEvaluator/// <param name="conditionType">The condition type declared in an attribute, or <c>null</c>.</param>/// <param name="snapshot">The current system snapshot to evaluate against.</param>/// <param name="logger">Logger for evaluation diagnostics.</param>- public static ConditionResult Evaluate(- Type? conditionType,- SystemSnapshot snapshot,- ILogger logger- )+ public static ConditionResult Evaluate(Type? conditionType, SystemInfo snapshot, ILogger logger){if (conditionType is null)return ConditionResult.Available;@@ -39,7 +35,7 @@ public static class ConditionEvaluator// Fail open: an unpopulated snapshot means hardware detection has not finished (or// failed), so never hide an item based on incomplete data. Callers re-evaluate once// a real snapshot is available.- if (ReferenceEquals(snapshot, SystemSnapshot.Unknown))+ if (snapshot.IsUnknown)return ConditionResult.Available;try@@ -66,7 +62,7 @@ public static class ConditionEvaluatorIEnumerable<T> items,Func<T, Type?> conditionTypeOf,Action<T, ConditionResult> apply,- SystemSnapshot snapshot,+ SystemInfo snapshot,ILogger logger){diff --git a/optimizerDuck/Services/Optimization/OptimizationService.cs b/optimizerDuck/Services/Optimization/OptimizationService.csindex 97537c8..599962f 100644--- a/optimizerDuck/Services/Optimization/OptimizationService.cs+++ b/optimizerDuck/Services/Optimization/OptimizationService.cs@@ -27,11 +27,31 @@ public class OptimizationService(StreamService streamService,IContentDialogService contentDialogService,ShellService shellService,+ PowerPlanService powerPlanService,ILogger<OptimizationService> logger){private readonly ILogger _logger = logger;private readonly ShellService _shellService = shellService;+ private readonly PowerPlanService _powerPlanService = powerPlanService;++ private OptimizationContext NewContext(+ ChangeSet changes,+ ILogger optLogger,+ CancellationToken cancellationToken+ )+ {+ return new OptimizationContext+ {+ Changes = changes,+ Logger = optLogger,+ CancellationToken = cancellationToken,+ Snapshot = systemInfoService.Snapshot,+ StreamService = streamService,+ Shell = _shellService,+ PowerPlans = _powerPlanService,+ };+ }/// <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;@@ -178,18 +198,7 @@ public class OptimizationService(try{var applyResult = await optimization- .ApplyAsync(- progress,- new OptimizationContext- {- Changes = changes,- Logger = optLogger,- CancellationToken = cancellationToken,- Snapshot = systemInfoService.Snapshot,- StreamService = streamService,- Shell = _shellService,- }- )+ .ApplyAsync(progress, NewContext(changes, optLogger, cancellationToken)).ConfigureAwait(false);providerError = string.IsNullOrWhiteSpace(applyResult.ErrorMessage)diff --git a/optimizerDuck/Services/Optimization/Providers/ServiceStrings.cs b/optimizerDuck/Services/Optimization/Providers/ServiceStrings.csindex ec33d38..0b3944a 100644--- a/optimizerDuck/Services/Optimization/Providers/ServiceStrings.cs+++ b/optimizerDuck/Services/Optimization/Providers/ServiceStrings.cs@@ -62,6 +62,8 @@ public static class ServiceStringspublic const string ShellName = "Shell";+ public const string PowerPlanName = "PowerPlan";+public const string StartupAppErrorUnsupportedLocation ="Cannot toggle startup app '{0}': its location is not supported";diff --git a/optimizerDuck/Services/Optimization/Providers/ShellService.cs b/optimizerDuck/Services/Optimization/Providers/ShellService.csindex 7b7ac0f..fed8c3a 100644--- a/optimizerDuck/Services/Optimization/Providers/ShellService.cs+++ b/optimizerDuck/Services/Optimization/Providers/ShellService.cs@@ -17,8 +17,15 @@ namespace optimizerDuck.Services.Optimization.Providers;/// Holds no static state; the timeout lives in <see cref="ProcessRunner"/>/// and is read live from settings on every call./// </summary>-public sealed class ShellService(ProcessRunner _runner)+public sealed class ShellService{+ private readonly ProcessRunner _runner;++ public ShellService(ProcessRunner runner)+ {+ _runner = runner;+ }+private static (string commandForUser, string fullCommandForUser) SanitizeCommandForUser(string fileName,string arguments,diff --git a/optimizerDuck/Services/Revert/RevertManager.cs b/optimizerDuck/Services/Revert/RevertManager.csindex 5b5ffaf..818d76b 100644--- a/optimizerDuck/Services/Revert/RevertManager.cs+++ b/optimizerDuck/Services/Revert/RevertManager.cs@@ -15,10 +15,16 @@ using optimizerDuck.Domain.UI;using optimizerDuck.Resources.Languages;using optimizerDuck.Services.Configuration;using optimizerDuck.Services.Optimization.Providers;+using optimizerDuck.Services.System;namespace optimizerDuck.Services.Revert;-public class RevertManager(ILogger<RevertManager> _logger, ShellService _shell, TimeProvider _time)+public class RevertManager(+ ILogger<RevertManager> _logger,+ ShellService _shell,+ PowerPlanService _powerPlans,+ TimeProvider _time+){private const int SchemaVersion = 1;private const int FileLockTimeoutSeconds = 30;@@ -146,7 +152,13 @@ public class RevertManager(ILogger<RevertManager> _logger, ShellService _shell,try{- if (!await step.ExecuteAsync(_shell, _logger).ConfigureAwait(false))+ var context = new RevertContext+ {+ Shell = _shell,+ PowerPlans = _powerPlans,+ Logger = _logger,+ };+ if (!await step.ExecuteAsync(context, _logger).ConfigureAwait(false))throw new Exception(Loc.Instance["Revert.Error.StepFailed"]);}catch (Exception ex)@@ -169,7 +181,16 @@ public class RevertManager(ILogger<RevertManager> _logger, ShellService _shell,Error = stepEx?.Message ?? ex.Message,ErrorDetail = stepEx?.ErrorDetail,Retry = async _ => new OpResult(- await step.ExecuteAsync(_shell, _logger).ConfigureAwait(false)+ await step.ExecuteAsync(+ new RevertContext+ {+ Shell = _shell,+ PowerPlans = _powerPlans,+ Logger = _logger,+ },+ _logger+ )+ .ConfigureAwait(false)),});@@ -734,7 +755,7 @@ public class RevertManager(ILogger<RevertManager> _logger, ShellService _shell,rawType);- public Task<bool> ExecuteAsync(ShellService _, ILogger logger)+ public Task<bool> ExecuteAsync(RevertContext _, ILogger logger){throw new StepExecutionException(Services.Optimization.Providers.ServiceStrings.Format(diff --git a/optimizerDuck/Services/System/PowerPlanModels.cs b/optimizerDuck/Services/System/PowerPlanModels.csnew file mode 100644index 0000000..d6a9e28--- /dev/null+++ b/optimizerDuck/Services/System/PowerPlanModels.cs@@ -0,0 +1,141 @@+namespace optimizerDuck.Services.System;++/// <summary>+/// A Windows power scheme (power plan): GUID identity plus the live metadata+/// Windows reports for it. <see cref="Description"/> is null when Windows has+/// none; <see cref="Name"/> falls back to the GUID string in that case.+/// </summary>+public sealed record PowerScheme+{+ public required Guid Id { get; init; }++ public required string Name { get; init; }++ public string? Description { get; init; }++ public bool IsActive { get; init; }+}++/// <summary>A subgroup of power settings inside one scheme.</summary>+public sealed record PowerSettingGroup+{+ public required Guid SchemeId { get; init; }++ public required Guid Id { get; init; }++ public required string Name { get; init; }++ public string? Description { get; init; }+}++/// <summary>Which mains/battery value a call targets. No magic 0/1 at call sites.</summary>+public enum PowerSource+{+ Ac,+ Dc,+}++/// <summary>+/// How much Windows tells us about a setting's shape. <c>Unknown</c> means+/// Windows exposed no usable metadata: values stay raw numbers, nothing is+/// invented. There is deliberately no per-setting enum type: most settings+/// are plain DWORD indexes whose friendly names live elsewhere or nowhere.+/// </summary>+public enum PowerValueKind+{+ Unknown,+ Range,+ Indexed,+}++/// <summary>+/// One named choice of an indexed setting, read live from Windows via+/// <c>PowerReadPossibleFriendlyName</c> / <c>PowerReadPossibleDescription</c>.+/// Index is positional (the PossibleSettingIndex Windows was asked for).+/// </summary>+public sealed record PowerPossibleValue+{+ public required uint Index { get; init; }++ public required uint Value { get; init; }++ public string? Name { get; init; }++ public string? Description { get; init; }+}++/// <summary>+/// A single power setting: identity plus raw AC/DC values exactly as Windows+/// stores them (DWORD indexes), with optional range/enumeration metadata.+/// Raw vs semantic vs display: <see cref="AcValue"/>/<see cref="DcValue"/>+/// are the raw numbers; <see cref="Kind"/>, <see cref="MinValue"/>,+/// <see cref="MaxValue"/>, <see cref="Unit"/>, and+/// <see cref="PossibleValues"/> describe semantics when Windows provides+/// them; friendly display text is built by callers, never stored here.+/// </summary>+public sealed record PowerSetting+{+ public required Guid SchemeId { get; init; }++ public required Guid GroupId { get; init; }++ public required Guid Id { get; init; }++ public required string Name { get; init; }++ public string? Description { get; init; }++ public PowerValueKind Kind { get; init; } = PowerValueKind.Unknown;++ public required uint AcValue { get; init; }++ public required uint DcValue { get; init; }++ public uint? MinValue { get; init; }++ public uint? MaxValue { get; init; }++ public uint? Increment { get; init; }++ public string? Unit { get; init; }++ public IReadOnlyList<PowerPossibleValue>? PossibleValues { get; init; }+}++/// <summary>+/// A native power-operation failure with the truth callers need: what ran,+/// on which identifiers, the real Win32 code, and the throw text when the+/// interop itself threw (never a fabricated sentinel code).+/// </summary>+public sealed record PowerPlanError+{+ public required string Operation { get; init; }++ public Guid? SchemeId { get; init; }++ public Guid? SubgroupId { get; init; }++ public Guid? SettingId { get; init; }++ public PowerSource? Source { get; init; }++ public string? Path { get; init; }++ /// <summary>Win32 error code, or null when the failure was a throw.</summary>+ public uint? ErrorCode { get; init; }++ /// <summary>Throw text when the interop threw; null for plain error codes.</summary>+ public string? ExceptionText { get; init; }++ public string Describe()+ {+ var target = SettingId ?? SubgroupId ?? SchemeId;+ var where =+ target.HasValue ? $" {target}"+ : Path is not null ? $" {Path}"+ : "";+ var code = ErrorCode.HasValue ? $" Win32 {ErrorCode}" : "";+ var thrown = ExceptionText is not null ? $": {ExceptionText}" : "";+ return $"{Operation} failed{where}.{code}{thrown}".TrimEnd('.', ' ');+ }+}diff --git a/optimizerDuck/Services/System/PowerPlanService.cs b/optimizerDuck/Services/System/PowerPlanService.csnew file mode 100644index 0000000..22f5519--- /dev/null+++ b/optimizerDuck/Services/System/PowerPlanService.cs@@ -0,0 +1,1616 @@+using System.IO;+using System.Runtime.InteropServices;+using System.Runtime.Versioning;+using System.Text;+using Microsoft.Extensions.Logging;+using optimizerDuck.Domain.Execution;+using optimizerDuck.Domain.Revert.Steps;+using optimizerDuck.Services.Optimization.Providers;++namespace optimizerDuck.Services.System;++/// <summary>+/// Power scheme operations over powrprof (no child processes).+/// Single owner of every power P/Invoke in the app.+/// Fast Win32 calls run synchronously on the caller thread; only the+/// file-I/O-bound import is async. Mutating paths take an+/// <see cref="OpCall"/>, record a <see cref="Change"/>, and return+/// <see cref="OpResult"/> like <see cref="RegistryService"/> does.+/// Import semantics: a non-empty <c>destinationId</c> pre-seeds the GUID**+/// slot so Windows imports under it (replacing any scheme with the same+/// GUID, same as <c>powercfg /import file guid</c>); an empty GUID passes+/// NULL and Windows allocates one, returned to the caller.+/// Hibernate (<c>powercfg /h</c>) is intentionally NOT here: it disables the+/// hibernation feature and deletes hiberfil.sys, and no supported native+/// power-scheme API covers that. It stays a documented shell exception in+/// <c>DisableHibernateAndFastStartup</c>.+/// </summary>+[SupportedOSPlatform("windows")]+public sealed class PowerPlanService+{+ private const uint ERROR_SUCCESS = 0;+ private const uint ERROR_MORE_DATA = 234;+ private const uint ACCESS_SCHEME = 16;+ private const uint ACCESS_SUBGROUP = 17;+ private const uint ACCESS_INDIVIDUAL_SETTING = 18;++ private readonly ILogger<PowerPlanService> _logger;++ public PowerPlanService(ILogger<PowerPlanService> logger)+ {+ _logger = logger;+ }++ public Guid? GetActiveSchemeId()+ {+ IntPtr ptr = IntPtr.Zero;+ try+ {+ if (PowerGetActiveScheme(IntPtr.Zero, out ptr) != ERROR_SUCCESS || ptr == IntPtr.Zero)+ return null;+ return Marshal.PtrToStructure<Guid>(ptr);+ }+ catch (Exception ex)+ {+ _logger.LogDebug(ex, "Failed to read active power scheme");+ return null;+ }+ finally+ {+ if (ptr != IntPtr.Zero)+ LocalFree(ptr);+ }+ }++ public IReadOnlyList<PowerScheme> ListSchemes()+ {+ var schemes = new List<PowerScheme>();+ try+ {+ var active = GetActiveSchemeId();+ foreach (var id in EnumerateGuids(ACCESS_SCHEME, null, null))+ schemes.Add(ReadScheme(id, active == id));+ }+ catch (Exception ex)+ {+ _logger.LogDebug(ex, "Failed to enumerate power schemes");+ }+ return schemes;+ }++ public PowerScheme? GetScheme(Guid schemeId)+ {+ var id = schemeId;+ var active = GetActiveSchemeId();+ var name = GetSchemeName(id);+ if (name is null && !SchemeExists(id))+ return null;+ return new PowerScheme+ {+ Id = id,+ Name = name ?? id.ToString(),+ Description = GetSchemeDescription(id),+ IsActive = active == id,+ };+ }++ public bool SchemeExists(Guid schemeId)+ {+ // No direct 'exists' API: a friendly-name read succeeds only for+ // real schemes, so reuse it instead of guessing from a list.+ try+ {+ return ReadSchemeNameRaw(schemeId) is not null;+ }+ catch+ {+ return false;+ }+ }++ public string? GetSchemeName(Guid schemeId)+ {+ try+ {+ return ReadSchemeNameRaw(schemeId);+ }+ catch (Exception ex)+ {+ _logger.LogDebug(ex, "Failed to read power scheme name {SchemeId}", schemeId);+ return null;+ }+ }++ public string? GetSchemeDescription(Guid schemeId)+ {+ try+ {+ return ReadSchemeDescriptionRaw(schemeId);+ }+ catch (Exception ex)+ {+ _logger.LogDebug(ex, "Failed to read power scheme description {SchemeId}", schemeId);+ return null;+ }+ }++ public IReadOnlyList<PowerSettingGroup> ListGroups(Guid schemeId)+ {+ var groups = new List<PowerSettingGroup>();+ try+ {+ foreach (var id in EnumerateGuids(ACCESS_SUBGROUP, schemeId, null))+ {+ var gid = id;+ groups.Add(+ new PowerSettingGroup+ {+ SchemeId = schemeId,+ Id = gid,+ Name = ReadGroupNameRaw(schemeId, gid) ?? gid.ToString(),+ Description = ReadGroupDescriptionRaw(schemeId, gid),+ }+ );+ }+ }+ catch (Exception ex)+ {+ _logger.LogDebug(ex, "Failed to enumerate subgroups for {SchemeId}", schemeId);+ }+ return groups;+ }++ public IReadOnlyList<PowerSetting> ListSettings(Guid schemeId, Guid subgroupId)+ {+ var settings = new List<PowerSetting>();+ try+ {+ foreach (var id in EnumerateGuids(ACCESS_INDIVIDUAL_SETTING, schemeId, subgroupId))+ {+ var setting = ReadSetting(schemeId, subgroupId, id);+ if (setting is not null)+ settings.Add(setting);+ }+ }+ catch (Exception ex)+ {+ _logger.LogDebug(+ ex,+ "Failed to enumerate settings for {SchemeId}/{SubgroupId}",+ schemeId,+ subgroupId+ );+ }+ return settings;+ }++ public PowerSetting? GetSetting(Guid schemeId, Guid subgroupId, Guid settingId)+ {+ try+ {+ return ReadSetting(schemeId, subgroupId, settingId);+ }+ catch (Exception ex)+ {+ _logger.LogDebug(+ ex,+ "Failed to read setting {SchemeId}/{SubgroupId}/{SettingId}",+ schemeId,+ subgroupId,+ settingId+ );+ return null;+ }+ }++ public uint? GetSettingValue(Guid schemeId, Guid subgroupId, Guid settingId, PowerSource source)+ {+ try+ {+ return TryReadRaw(schemeId, subgroupId, settingId, source);+ }+ catch (Exception ex)+ {+ _logger.LogDebug(+ ex,+ "Failed to read {Source} value for {SchemeId}/{SubgroupId}/{SettingId}",+ source,+ schemeId,+ subgroupId,+ settingId+ );+ return null;+ }+ }++ public OpResult SetSetting(+ OpCall call,+ Guid schemeId,+ Guid subgroupId,+ Guid settingId,+ uint? acValue,+ uint? dcValue+ )+ {+ ArgumentNullException.ThrowIfNull(call);+ var description = ServiceStrings.Format(+ "Write power setting {0}/{1}/{2}",+ schemeId,+ subgroupId,+ settingId+ );++ if (acValue is null && dcValue is null)+ {+ const string error = "No value to write: both AC and DC are null.";+ call.Changes.Add(+ ServiceStrings.PowerPlanName,+ description,+ false,+ null,+ error,+ error,+ retryCall =>+ Task.FromResult(+ SetSetting(retryCall, schemeId, subgroupId, settingId, acValue, dcValue)+ )+ );+ return OpResult.Fail(error, error);+ }++ var prevAc = TryReadRaw(schemeId, subgroupId, settingId, PowerSource.Ac);+ var prevDc = TryReadRaw(schemeId, subgroupId, settingId, PowerSource.Dc);+ if (prevAc is null || prevDc is null)+ {+ // Fail closed: never assume an unreadable previous value is zero.+ var missing = prevAc is null ? PowerSource.Ac : PowerSource.Dc;+ var error = ServiceStrings.Format(+ "Could not read previous {0} value for {1}/{2}/{3}; refusing to write.",+ missing,+ schemeId,+ subgroupId,+ settingId+ );+ call.Logger.LogError(+ "Refusing power-setting write: previous {Source} value unreadable for {SchemeId}/{SubgroupId}/{SettingId}",+ missing,+ schemeId,+ subgroupId,+ settingId+ );+ call.Changes.Add(+ ServiceStrings.PowerPlanName,+ description,+ false,+ null,+ error,+ error,+ retryCall =>+ Task.FromResult(+ SetSetting(retryCall, schemeId, subgroupId, settingId, acValue, dcValue)+ )+ );+ return OpResult.Fail(error, error);+ }++ var failure = WriteValues(schemeId, subgroupId, settingId, acValue, dcValue);+ if (failure is not null)+ {+ call.Changes.Add(+ ServiceStrings.PowerPlanName,+ description,+ false,+ null,+ failure.Describe(),+ failure.Describe(),+ retryCall =>+ Task.FromResult(+ SetSetting(retryCall, schemeId, subgroupId, settingId, acValue, dcValue)+ )+ );+ return OpResult.Fail(failure.Describe(), failure.Describe());+ }++ var revertStep = new PowerSettingRevertStep+ {+ SchemeId = schemeId,+ SubgroupId = subgroupId,+ SettingId = settingId,+ PreviousAcValue = prevAc.Value,+ PreviousDcValue = prevDc.Value,+ };+ call.Changes.Add(ServiceStrings.PowerPlanName, description, true, revertStep);+ call.Logger.LogInformation(+ "Wrote power setting {SchemeId}/{SubgroupId}/{SettingId} AC={Ac} DC={Dc}",+ schemeId,+ subgroupId,+ settingId,+ acValue?.ToString() ?? "(unchanged)",+ dcValue?.ToString() ?? "(unchanged)"+ );+ return OpResult.Success(revertStep);+ }++ public OpResult SetActiveScheme(OpCall call, Guid schemeId)+ {+ ArgumentNullException.ThrowIfNull(call);+ var name = GetSchemeName(schemeId) ?? schemeId.ToString();+ var description = ServiceStrings.Format("Activate power plan {0}", name);++ var previous = GetActiveSchemeId();+ if (previous is null)+ {+ const string error = "Could not read the active power plan; refusing to switch.";+ call.Logger.LogError("Refusing power-plan switch: active scheme unreadable");+ call.Changes.Add(+ ServiceStrings.PowerPlanName,+ description,+ false,+ null,+ error,+ error,+ retryCall => Task.FromResult(SetActiveScheme(retryCall, schemeId))+ );+ return OpResult.Fail(error, error);+ }++ if (previous.Value == schemeId)+ {+ call.Logger.LogInformation("Power plan {Name} already active, skipping", name);+ call.Changes.Add(+ ServiceStrings.PowerPlanName,+ ServiceStrings.Format("Power plan {0} already active (skipped)", name),+ true+ );+ return OpResult.Success();+ }++ uint code;+ try+ {+ var id = schemeId;+ code = PowerSetActiveScheme(IntPtr.Zero, ref id);+ }+ catch (Exception ex)+ {+ var err = new PowerPlanError+ {+ Operation = nameof(PowerSetActiveScheme),+ SchemeId = schemeId,+ ExceptionText = ex.Message,+ };+ call.Logger.LogWarning(ex, "PowerSetActiveScheme threw for {SchemeId}", schemeId);+ call.Changes.Add(+ ServiceStrings.PowerPlanName,+ description,+ false,+ null,+ err.Describe(),+ ex.ToString(),+ retryCall => Task.FromResult(SetActiveScheme(retryCall, schemeId))+ );+ return OpResult.Fail(err.Describe(), ex.ToString());+ }++ if (code != ERROR_SUCCESS)+ {+ var err = new PowerPlanError+ {+ Operation = nameof(PowerSetActiveScheme),+ SchemeId = schemeId,+ ErrorCode = code,+ };+ _logger.LogWarning(+ "PowerSetActiveScheme failed for {SchemeId}: Win32 {ErrorCode}",+ schemeId,+ code+ );+ call.Changes.Add(+ ServiceStrings.PowerPlanName,+ description,+ false,+ null,+ err.Describe(),+ err.Describe(),+ retryCall => Task.FromResult(SetActiveScheme(retryCall, schemeId))+ );+ return OpResult.Fail(err.Describe(), err.Describe());+ }++ var revertStep = new PowerPlanRevertStep+ {+ PreviousSchemeId = previous.Value,+ InstalledSchemeId = Guid.Empty,+ };+ call.Changes.Add(ServiceStrings.PowerPlanName, description, true, revertStep);+ return OpResult.Success(revertStep);+ }++ public OpResult DeleteScheme(OpCall call, Guid schemeId)+ {+ ArgumentNullException.ThrowIfNull(call);+ var name = GetSchemeName(schemeId) ?? schemeId.ToString();+ var description = ServiceStrings.Format("Delete power plan {0}", name);++ if (GetActiveSchemeId() == schemeId)+ {+ var error = ServiceStrings.Format(+ "Refusing to delete the active power plan {0}; activate another plan first.",+ name+ );+ call.Logger.LogError("Refusing to delete active power plan {SchemeId}", schemeId);+ call.Changes.Add(ServiceStrings.PowerPlanName, description, false, null, error, error);+ return OpResult.Fail(error, error);+ }++ uint code;+ try+ {+ var id = schemeId;+ code = PowerDeleteScheme(IntPtr.Zero, ref id);+ }+ catch (Exception ex)+ {+ var err = new PowerPlanError+ {+ Operation = nameof(PowerDeleteScheme),+ SchemeId = schemeId,+ ExceptionText = ex.Message,+ };+ call.Logger.LogWarning(ex, "PowerDeleteScheme threw for {SchemeId}", schemeId);+ call.Changes.Add(+ ServiceStrings.PowerPlanName,+ description,+ false,+ null,+ err.Describe(),+ ex.ToString(),+ retryCall => Task.FromResult(DeleteScheme(retryCall, schemeId))+ );+ return OpResult.Fail(err.Describe(), ex.ToString());+ }++ if (code != ERROR_SUCCESS)+ {+ var err = new PowerPlanError+ {+ Operation = nameof(PowerDeleteScheme),+ SchemeId = schemeId,+ ErrorCode = code,+ };+ _logger.LogWarning(+ "PowerDeleteScheme failed for {SchemeId}: Win32 {ErrorCode}",+ schemeId,+ code+ );+ call.Changes.Add(+ ServiceStrings.PowerPlanName,+ description,+ false,+ null,+ err.Describe(),+ err.Describe(),+ retryCall => Task.FromResult(DeleteScheme(retryCall, schemeId))+ );+ return OpResult.Fail(err.Describe(), err.Describe());+ }++ // Deleted schemes are gone: no revert step can restore them.+ call.Changes.Add(ServiceStrings.PowerPlanName, description, true);+ return OpResult.Success();+ }++ public async Task<(OpResult Result, Guid? SchemeId)> ImportSchemeAsync(+ string filePath,+ Guid destinationId,+ CancellationToken ct = default+ )+ {+ ct.ThrowIfCancellationRequested();+ if (!File.Exists(filePath))+ {+ var missing = new PowerPlanError+ {+ Operation = nameof(PowerImportPowerScheme),+ Path = filePath,+ ExceptionText = "File not found.",+ };+ return (OpResult.Fail(missing.Describe(), missing.Describe()), null);+ }++ // Genuine async boundary: file I/O, not a faked-async native call.+ await Task.Yield();++ IntPtr ppGuid = IntPtr.Zero;+ IntPtr slot = IntPtr.Zero;+ try+ {+ ppGuid = Marshal.AllocHGlobal(IntPtr.Size);+ if (destinationId != Guid.Empty)+ {+ slot = Marshal.AllocHGlobal(16);+ Marshal.StructureToPtr(destinationId, slot, false);+ Marshal.WriteIntPtr(ppGuid, slot);+ }+ else+ {+ Marshal.WriteIntPtr(ppGuid, IntPtr.Zero);+ }++ var code = PowerImportPowerScheme(IntPtr.Zero, filePath, ppGuid);+ var outSlot = Marshal.ReadIntPtr(ppGuid);+ Guid? imported =+ outSlot == IntPtr.Zero ? null : (Guid?)Marshal.PtrToStructure<Guid>(outSlot);+ if (outSlot != IntPtr.Zero && outSlot != slot)+ LocalFree(outSlot);++ if (code != ERROR_SUCCESS || imported is null)+ {+ var err = new PowerPlanError+ {+ Operation = nameof(PowerImportPowerScheme),+ Path = filePath,+ ErrorCode = code,+ };+ _logger.LogWarning(+ "PowerImportPowerScheme failed for {Path}: Win32 {ErrorCode}",+ filePath,+ code+ );+ return (OpResult.Fail(err.Describe(), err.Describe()), null);+ }+ return (OpResult.Success(), imported);+ }+ catch (Exception ex)+ {+ var err = new PowerPlanError+ {+ Operation = nameof(PowerImportPowerScheme),+ Path = filePath,+ ExceptionText = ex.Message,+ };+ _logger.LogWarning(ex, "PowerImportPowerScheme threw for {Path}", filePath);+ return (OpResult.Fail(err.Describe(), ex.ToString()), null);+ }+ finally+ {+ if (slot != IntPtr.Zero)+ Marshal.FreeHGlobal(slot);+ if (ppGuid != IntPtr.Zero)+ Marshal.FreeHGlobal(ppGuid);+ }+ }++ public (OpResult Result, Guid? SchemeId) DuplicateScheme(OpCall call, Guid sourceId)+ {+ ArgumentNullException.ThrowIfNull(call);+ var description = ServiceStrings.Format("Duplicate power plan {0}", sourceId);++ IntPtr ppGuid = IntPtr.Zero;+ try+ {+ // NULL seed: Windows allocates the new GUID; caller frees via LocalFree.+ ppGuid = Marshal.AllocHGlobal(IntPtr.Size);+ Marshal.WriteIntPtr(ppGuid, IntPtr.Zero);++ var src = sourceId;+ var code = PowerDuplicateScheme(IntPtr.Zero, ref src, ppGuid);+ var outSlot = Marshal.ReadIntPtr(ppGuid);+ Guid? duplicated =+ outSlot == IntPtr.Zero ? null : (Guid?)Marshal.PtrToStructure<Guid>(outSlot);+ if (outSlot != IntPtr.Zero)+ LocalFree(outSlot);++ if (code != ERROR_SUCCESS || duplicated is null)+ {+ var err = new PowerPlanError+ {+ Operation = nameof(PowerDuplicateScheme),+ SchemeId = sourceId,+ ErrorCode = code,+ };+ _logger.LogWarning(+ "PowerDuplicateScheme failed for {SchemeId}: Win32 {ErrorCode}",+ sourceId,+ code+ );+ call.Changes.Add(+ ServiceStrings.PowerPlanName,+ description,+ false,+ null,+ err.Describe(),+ err.Describe(),+ retryCall => Task.FromResult(DuplicateScheme(retryCall, sourceId).Result)+ );+ return (OpResult.Fail(err.Describe(), err.Describe()), null);+ }++ call.Changes.Add(ServiceStrings.PowerPlanName, description, true);+ return (OpResult.Success(), duplicated);+ }+ catch (Exception ex)+ {+ var err = new PowerPlanError+ {+ Operation = nameof(PowerDuplicateScheme),+ SchemeId = sourceId,+ ExceptionText = ex.Message,+ };+ call.Logger.LogWarning(ex, "PowerDuplicateScheme threw for {SchemeId}", sourceId);+ call.Changes.Add(+ ServiceStrings.PowerPlanName,+ description,+ false,+ null,+ err.Describe(),+ ex.ToString(),+ retryCall => Task.FromResult(DuplicateScheme(retryCall, sourceId).Result)+ );+ return (OpResult.Fail(err.Describe(), ex.ToString()), null);+ }+ finally+ {+ if (ppGuid != IntPtr.Zero)+ Marshal.FreeHGlobal(ppGuid);+ }+ }++ public OpResult SetSchemeName(OpCall call, Guid schemeId, string name)+ {+ ArgumentNullException.ThrowIfNull(call);+ var description = ServiceStrings.Format("Rename power plan {0}", schemeId);++ var bytes = Encoding.Unicode.GetBytes(name + '\0');+ IntPtr buffer = IntPtr.Zero;+ try+ {+ buffer = Marshal.AllocHGlobal(bytes.Length);+ Marshal.Copy(bytes, 0, buffer, bytes.Length);+ var id = schemeId;+ var code = PowerWriteFriendlyName(+ IntPtr.Zero,+ ref id,+ IntPtr.Zero,+ IntPtr.Zero,+ buffer,+ (uint)bytes.Length+ );+ if (code != ERROR_SUCCESS)+ return FailTextWrite(+ call,+ description,+ nameof(PowerWriteFriendlyName),+ schemeId,+ code+ );+ call.Changes.Add(ServiceStrings.PowerPlanName, description, true);+ return OpResult.Success();+ }+ catch (Exception ex)+ {+ return FailTextWrite(+ call,+ description,+ nameof(PowerWriteFriendlyName),+ schemeId,+ null,+ ex+ );+ }+ finally+ {+ if (buffer != IntPtr.Zero)+ Marshal.FreeHGlobal(buffer);+ }+ }++ public OpResult SetSchemeDescription(OpCall call, Guid schemeId, string descriptionText)+ {+ ArgumentNullException.ThrowIfNull(call);+ var description = ServiceStrings.Format("Re-describe power plan {0}", schemeId);++ var bytes = Encoding.Unicode.GetBytes(descriptionText + '\0');+ IntPtr buffer = IntPtr.Zero;+ try+ {+ buffer = Marshal.AllocHGlobal(bytes.Length);+ Marshal.Copy(bytes, 0, buffer, bytes.Length);+ var id = schemeId;+ var code = PowerWriteDescription(+ IntPtr.Zero,+ ref id,+ IntPtr.Zero,+ IntPtr.Zero,+ buffer,+ (uint)bytes.Length+ );+ if (code != ERROR_SUCCESS)+ return FailTextWrite(+ call,+ description,+ nameof(PowerWriteDescription),+ schemeId,+ code+ );+ call.Changes.Add(ServiceStrings.PowerPlanName, description, true);+ return OpResult.Success();+ }+ catch (Exception ex)+ {+ return FailTextWrite(+ call,+ description,+ nameof(PowerWriteDescription),+ schemeId,+ null,+ ex+ );+ }+ finally+ {+ if (buffer != IntPtr.Zero)+ Marshal.FreeHGlobal(buffer);+ }+ }++ private static OpResult FailTextWrite(+ OpCall call,+ string description,+ string operation,+ Guid schemeId,+ uint? code,+ Exception? ex = null+ )+ {+ var err = new PowerPlanError+ {+ Operation = operation,+ SchemeId = schemeId,+ ErrorCode = code,+ ExceptionText = ex?.Message,+ };+ var detail = ex?.ToString() ?? err.Describe();+ call.Changes.Add(+ ServiceStrings.PowerPlanName,+ description,+ false,+ null,+ err.Describe(),+ detail+ );+ return OpResult.Fail(err.Describe(), detail);+ }++ private PowerScheme ReadScheme(Guid id, bool isActive)+ {+ return new PowerScheme+ {+ Id = id,+ Name = ReadSchemeNameRaw(id) ?? id.ToString(),+ Description = ReadSchemeDescriptionRaw(id),+ IsActive = isActive,+ };+ }++ private PowerSetting? ReadSetting(Guid schemeId, Guid subgroupId, Guid settingId)+ {+ var name = ReadSettingNameRaw(schemeId, subgroupId, settingId);+ if (name is null)+ return null;++ var ac = TryReadRaw(schemeId, subgroupId, settingId, PowerSource.Ac);+ var dc = TryReadRaw(schemeId, subgroupId, settingId, PowerSource.Dc);+ if (ac is null || dc is null)+ return null;++ var description = ReadSettingDescriptionRaw(schemeId, subgroupId, settingId);++ var kind = PowerValueKind.Unknown;+ uint? min = null;+ uint? max = null;+ uint? incr = null;+ string? unit = null;+ IReadOnlyList<PowerPossibleValue>? possible = null;+ try+ {+ var sg = subgroupId;+ var st = settingId;+ if (PowerIsSettingRangeDefined(ref sg, ref st))+ {+ kind = PowerValueKind.Range;+ if (PowerReadValueMin(IntPtr.Zero, ref sg, ref st, out var lo) == ERROR_SUCCESS)+ min = lo;+ if (PowerReadValueMax(IntPtr.Zero, ref sg, ref st, out var hi) == ERROR_SUCCESS)+ max = hi;+ if (+ PowerReadValueIncrement(IntPtr.Zero, ref sg, ref st, out var step)+ == ERROR_SUCCESS+ )+ incr = step;+ unit = ReadUnitsRaw(subgroupId, settingId);+ }+ else+ {+ possible = ReadPossibleValues(subgroupId, settingId);+ if (possible is { Count: > 0 })+ kind = PowerValueKind.Indexed;+ }+ }+ catch+ {+ // Metadata is best-effort: raw values above already succeeded.+ }++ return new PowerSetting+ {+ SchemeId = schemeId,+ GroupId = subgroupId,+ Id = settingId,+ Name = name,+ Description = description,+ Kind = kind,+ AcValue = ac.Value,+ DcValue = dc.Value,+ MinValue = min,+ MaxValue = max,+ Increment = incr,+ Unit = unit,+ PossibleValues = possible,+ };+ }++ private static IReadOnlyList<PowerPossibleValue>? ReadPossibleValues(+ Guid subgroupId,+ Guid settingId+ )+ {+ var list = new List<PowerPossibleValue>();+ try+ {+ for (uint index = 0; index < 512; index++)+ {+ var name = ReadPossibleNameRaw(subgroupId, settingId, index);+ if (name is null)+ break;+ var value = ReadPossibleValueRaw(subgroupId, settingId, index);+ if (value is null)+ break;+ list.Add(+ new PowerPossibleValue+ {+ Index = index,+ Value = value.Value,+ Name = name,+ Description = ReadPossibleDescriptionRaw(subgroupId, settingId, index),+ }+ );+ }+ }+ catch+ {+ return list.Count > 0 ? list : null;+ }+ return list.Count > 0 ? list : null;+ }++ private uint? TryReadRaw(Guid schemeId, Guid subgroupId, Guid settingId, PowerSource source)+ {+ try+ {+ var s = schemeId;+ var g = subgroupId;+ var st = settingId;+ uint value;+ var code =+ source == PowerSource.Ac+ ? PowerReadACValueIndex(IntPtr.Zero, ref s, ref g, ref st, out value)+ : PowerReadDCValueIndex(IntPtr.Zero, ref s, ref g, ref st, out value);+ return code == ERROR_SUCCESS ? value : null;+ }+ catch+ {+ return null;+ }+ }++ private static uint? ReadPossibleValueRaw(Guid subgroupId, Guid settingId, uint index)+ {+ var g = subgroupId;+ var st = settingId;+ uint size = 4;+ var buffer = Marshal.AllocHGlobal(4);+ try+ {+ var code = PowerReadPossibleValue(+ IntPtr.Zero,+ ref g,+ ref st,+ out _,+ index,+ buffer,+ ref size+ );+ if (code != ERROR_SUCCESS)+ return null;+ return (uint)Marshal.ReadInt32(buffer);+ }+ finally+ {+ Marshal.FreeHGlobal(buffer);+ }+ }++ private PowerPlanError? WriteValues(+ Guid schemeId,+ Guid subgroupId,+ Guid settingId,+ uint? acValue,+ uint? dcValue+ )+ {+ try+ {+ if (acValue.HasValue)+ {+ var s = schemeId;+ var g = subgroupId;+ var st = settingId;+ var code = PowerWriteACValueIndex(IntPtr.Zero, ref s, ref g, ref st, acValue.Value);+ if (code != ERROR_SUCCESS)+ return new PowerPlanError+ {+ Operation = nameof(PowerWriteACValueIndex),+ SchemeId = schemeId,+ SubgroupId = subgroupId,+ SettingId = settingId,+ Source = PowerSource.Ac,+ ErrorCode = code,+ };+ }+ if (dcValue.HasValue)+ {+ var s = schemeId;+ var g = subgroupId;+ var st = settingId;+ var code = PowerWriteDCValueIndex(IntPtr.Zero, ref s, ref g, ref st, dcValue.Value);+ if (code != ERROR_SUCCESS)+ return new PowerPlanError+ {+ Operation = nameof(PowerWriteDCValueIndex),+ SchemeId = schemeId,+ SubgroupId = subgroupId,+ SettingId = settingId,+ Source = PowerSource.Dc,+ ErrorCode = code,+ };+ }+ // Writes to the active scheme need reactivation to take effect.+ if (GetActiveSchemeId() == schemeId)+ {+ var s = schemeId;+ PowerSetActiveScheme(IntPtr.Zero, ref s);+ }+ return null;+ }+ catch (Exception ex)+ {+ return new PowerPlanError+ {+ Operation = "PowerWriteValueIndex",+ SchemeId = schemeId,+ SubgroupId = subgroupId,+ SettingId = settingId,+ ExceptionText = ex.Message,+ };+ }+ }++ private static string? ReadSchemeNameRaw(Guid schemeId)+ {+ var id = schemeId;+ uint size = 0;+ var probe = PowerReadFriendlyName(+ IntPtr.Zero,+ ref id,+ IntPtr.Zero,+ IntPtr.Zero,+ IntPtr.Zero,+ ref size+ );+ return ReadProbedString(+ probe,+ size,+ (buf, ref len) => SchemeNameInto(ref id, buf, ref len)+ );+ }++ private static uint SchemeNameInto(ref Guid schemeId, IntPtr buffer, ref uint size)+ {+ return PowerReadFriendlyName(+ IntPtr.Zero,+ ref schemeId,+ IntPtr.Zero,+ IntPtr.Zero,+ buffer,+ ref size+ );+ }++ private static string? ReadSchemeDescriptionRaw(Guid schemeId)+ {+ var id = schemeId;+ uint size = 0;+ var probe = PowerReadDescription(+ IntPtr.Zero,+ ref id,+ IntPtr.Zero,+ IntPtr.Zero,+ IntPtr.Zero,+ ref size+ );+ return ReadProbedString(+ probe,+ size,+ (buf, ref len) => SchemeDescriptionInto(ref id, buf, ref len)+ );+ }++ private static uint SchemeDescriptionInto(ref Guid schemeId, IntPtr buffer, ref uint size)+ {+ return PowerReadDescription(+ IntPtr.Zero,+ ref schemeId,+ IntPtr.Zero,+ IntPtr.Zero,+ buffer,+ ref size+ );+ }++ private static string? ReadGroupNameRaw(Guid schemeId, Guid subgroupId)+ {+ var s = schemeId;+ var g = subgroupId;+ uint size = 0;+ var probe = PowerReadFriendlyName(+ IntPtr.Zero,+ ref s,+ ref g,+ IntPtr.Zero,+ IntPtr.Zero,+ ref size+ );+ return ReadProbedString(+ probe,+ size,+ (buf, ref len) => GroupNameInto(ref s, ref g, buf, ref len)+ );+ }++ private static uint GroupNameInto(+ ref Guid schemeId,+ ref Guid subgroupId,+ IntPtr buffer,+ ref uint size+ )+ {+ return PowerReadFriendlyName(+ IntPtr.Zero,+ ref schemeId,+ ref subgroupId,+ IntPtr.Zero,+ buffer,+ ref size+ );+ }++ private static string? ReadGroupDescriptionRaw(Guid schemeId, Guid subgroupId)+ {+ var s = schemeId;+ var g = subgroupId;+ uint size = 0;+ var probe = PowerReadDescription(+ IntPtr.Zero,+ ref s,+ ref g,+ IntPtr.Zero,+ IntPtr.Zero,+ ref size+ );+ return ReadProbedString(+ probe,+ size,+ (buf, ref len) => GroupDescriptionInto(ref s, ref g, buf, ref len)+ );+ }++ private static uint GroupDescriptionInto(+ ref Guid schemeId,+ ref Guid subgroupId,+ IntPtr buffer,+ ref uint size+ )+ {+ return PowerReadDescription(+ IntPtr.Zero,+ ref schemeId,+ ref subgroupId,+ IntPtr.Zero,+ buffer,+ ref size+ );+ }++ private static string? ReadSettingNameRaw(Guid schemeId, Guid subgroupId, Guid settingId)+ {+ var s = schemeId;+ var g = subgroupId;+ var st = settingId;+ uint size = 0;+ var probe = PowerReadFriendlyName(IntPtr.Zero, ref s, ref g, ref st, IntPtr.Zero, ref size);+ return ReadProbedString(+ probe,+ size,+ (buf, ref len) => SettingNameInto(ref s, ref g, ref st, buf, ref len)+ );+ }++ private static uint SettingNameInto(+ ref Guid schemeId,+ ref Guid subgroupId,+ ref Guid settingId,+ IntPtr buffer,+ ref uint size+ )+ {+ return PowerReadFriendlyName(+ IntPtr.Zero,+ ref schemeId,+ ref subgroupId,+ ref settingId,+ buffer,+ ref size+ );+ }++ private static string? ReadSettingDescriptionRaw(Guid schemeId, Guid subgroupId, Guid settingId)+ {+ var s = schemeId;+ var g = subgroupId;+ var st = settingId;+ uint size = 0;+ var probe = PowerReadDescription(IntPtr.Zero, ref s, ref g, ref st, IntPtr.Zero, ref size);+ return ReadProbedString(+ probe,+ size,+ (buf, ref len) => SettingDescriptionInto(ref s, ref g, ref st, buf, ref len)+ );+ }++ private static uint SettingDescriptionInto(+ ref Guid schemeId,+ ref Guid subgroupId,+ ref Guid settingId,+ IntPtr buffer,+ ref uint size+ )+ {+ return PowerReadDescription(+ IntPtr.Zero,+ ref schemeId,+ ref subgroupId,+ ref settingId,+ buffer,+ ref size+ );+ }++ private static string? ReadUnitsRaw(Guid subgroupId, Guid settingId)+ {+ var g = subgroupId;+ var st = settingId;+ uint size = 0;+ var probe = PowerReadValueUnitsSpecifier(IntPtr.Zero, ref g, ref st, IntPtr.Zero, ref size);+ return ReadProbedString(+ probe,+ size,+ (buf, ref len) => UnitsInto(ref g, ref st, buf, ref len)+ );+ }++ private static uint UnitsInto(+ ref Guid subgroupId,+ ref Guid settingId,+ IntPtr buffer,+ ref uint size+ )+ {+ return PowerReadValueUnitsSpecifier(+ IntPtr.Zero,+ ref subgroupId,+ ref settingId,+ buffer,+ ref size+ );+ }++ private static string? ReadPossibleNameRaw(Guid subgroupId, Guid settingId, uint index)+ {+ var g = subgroupId;+ var st = settingId;+ uint size = 0;+ var probe = PowerReadPossibleFriendlyName(+ IntPtr.Zero,+ ref g,+ ref st,+ index,+ IntPtr.Zero,+ ref size+ );+ return ReadProbedString(+ probe,+ size,+ (buf, ref len) => PossibleNameInto(ref g, ref st, index, buf, ref len)+ );+ }++ private static uint PossibleNameInto(+ ref Guid subgroupId,+ ref Guid settingId,+ uint index,+ IntPtr buffer,+ ref uint size+ )+ {+ return PowerReadPossibleFriendlyName(+ IntPtr.Zero,+ ref subgroupId,+ ref settingId,+ index,+ buffer,+ ref size+ );+ }++ private static string? ReadPossibleDescriptionRaw(Guid subgroupId, Guid settingId, uint index)+ {+ var g = subgroupId;+ var st = settingId;+ uint size = 0;+ var probe = PowerReadPossibleDescription(+ IntPtr.Zero,+ ref g,+ ref st,+ index,+ IntPtr.Zero,+ ref size+ );+ return ReadProbedString(+ probe,+ size,+ (buf, ref len) => PossibleDescriptionInto(ref g, ref st, index, buf, ref len)+ );+ }++ private static uint PossibleDescriptionInto(+ ref Guid subgroupId,+ ref Guid settingId,+ uint index,+ IntPtr buffer,+ ref uint size+ )+ {+ return PowerReadPossibleDescription(+ IntPtr.Zero,+ ref subgroupId,+ ref settingId,+ index,+ buffer,+ ref size+ );+ }++ private delegate uint FillBuffer(IntPtr buffer, ref uint size);++ private static string? ReadProbedString(uint probe, uint size, FillBuffer fill)+ {+ // Probe-then-read: NULL buffer returns the required size; some APIs+ // report ERROR_SUCCESS with size on probe, others ERROR_MORE_DATA.+ if (probe != ERROR_SUCCESS && probe != ERROR_MORE_DATA)+ return null;+ if (size == 0)+ return null;+ IntPtr buffer = IntPtr.Zero;+ try+ {+ buffer = Marshal.AllocHGlobal((int)size);+ if (fill(buffer, ref size) != ERROR_SUCCESS)+ return null;+ var text = Marshal.PtrToStringUni(buffer);+ return string.IsNullOrWhiteSpace(text) ? null : text.Trim();+ }+ finally+ {+ if (buffer != IntPtr.Zero)+ Marshal.FreeHGlobal(buffer);+ }+ }++ private static IEnumerable<Guid> EnumerateGuids(uint access, Guid? schemeId, Guid? subgroupId)+ {+ for (uint index = 0; ; index++)+ {+ uint size = 16;+ var buffer = Marshal.AllocHGlobal(16);+ try+ {+ Guid sCopy = schemeId ?? Guid.Empty;+ Guid gCopy = subgroupId ?? Guid.Empty;+ IntPtr pScheme = schemeId.HasValue ? AddrOf(ref sCopy) : IntPtr.Zero;+ IntPtr pGroup = subgroupId.HasValue ? AddrOf(ref gCopy) : IntPtr.Zero;+ uint code;+ try+ {+ code = PowerEnumerate(+ IntPtr.Zero,+ pScheme,+ pGroup,+ access,+ index,+ buffer,+ ref size+ );+ }+ finally+ {+ if (pScheme != IntPtr.Zero)+ Marshal.FreeHGlobal(pScheme);+ if (pGroup != IntPtr.Zero)+ Marshal.FreeHGlobal(pGroup);+ }+ if (code != ERROR_SUCCESS)+ yield break;+ yield return Marshal.PtrToStructure<Guid>(buffer);+ }+ finally+ {+ Marshal.FreeHGlobal(buffer);+ }+ }+ }++ private static IntPtr AddrOf(ref Guid value)+ {+ var ptr = Marshal.AllocHGlobal(16);+ Marshal.StructureToPtr(value, ptr, false);+ return ptr;+ }++ [DllImport("powrprof.dll")]+ private static extern uint PowerGetActiveScheme(+ IntPtr UserRootPowerKey,+ out IntPtr ActivePolicyGuid+ );++ [DllImport("powrprof.dll")]+ private static extern uint PowerEnumerate(+ IntPtr RootPowerKey,+ IntPtr SchemeGuid,+ IntPtr SubGroupOfPowerSettingsGuid,+ uint AccessFlags,+ uint Index,+ IntPtr Buffer,+ ref uint BufferSize+ );++ [DllImport("powrprof.dll", CharSet = CharSet.Unicode)]+ private static extern uint PowerReadFriendlyName(+ IntPtr RootPowerKey,+ ref Guid SchemeGuid,+ IntPtr SubGroupOfPowerSettingsGuid,+ IntPtr PowerSettingGuid,+ IntPtr Buffer,+ ref uint BufferSize+ );++ [DllImport("powrprof.dll", CharSet = CharSet.Unicode)]+ private static extern uint PowerReadFriendlyName(+ IntPtr RootPowerKey,+ ref Guid SchemeGuid,+ ref Guid SubGroupOfPowerSettingsGuid,+ IntPtr PowerSettingGuid,+ IntPtr Buffer,+ ref uint BufferSize+ );++ [DllImport("powrprof.dll", CharSet = CharSet.Unicode)]+ private static extern uint PowerReadFriendlyName(+ IntPtr RootPowerKey,+ ref Guid SchemeGuid,+ ref Guid SubGroupOfPowerSettingsGuid,+ ref Guid PowerSettingGuid,+ IntPtr Buffer,+ ref uint BufferSize+ );++ [DllImport("powrprof.dll", CharSet = CharSet.Unicode)]+ private static extern uint PowerReadDescription(+ IntPtr RootPowerKey,+ ref Guid SchemeGuid,+ IntPtr SubGroupOfPowerSettingsGuid,+ IntPtr PowerSettingGuid,+ IntPtr Buffer,+ ref uint BufferSize+ );++ [DllImport("powrprof.dll", CharSet = CharSet.Unicode)]+ private static extern uint PowerReadDescription(+ IntPtr RootPowerKey,+ ref Guid SchemeGuid,+ ref Guid SubGroupOfPowerSettingsGuid,+ IntPtr PowerSettingGuid,+ IntPtr Buffer,+ ref uint BufferSize+ );++ [DllImport("powrprof.dll", CharSet = CharSet.Unicode)]+ private static extern uint PowerReadDescription(+ IntPtr RootPowerKey,+ ref Guid SchemeGuid,+ ref Guid SubGroupOfPowerSettingsGuid,+ ref Guid PowerSettingGuid,+ IntPtr Buffer,+ ref uint BufferSize+ );++ [DllImport("powrprof.dll")]+ private static extern uint PowerSetActiveScheme(IntPtr UserRootPowerKey, ref Guid SchemeGuid);++ [DllImport("powrprof.dll", CharSet = CharSet.Unicode)]+ private static extern uint PowerImportPowerScheme(+ IntPtr RootPowerKey,+ string ImportFileNamePath,+ IntPtr DestinationSchemeGuid+ );++ [DllImport("powrprof.dll")]+ private static extern uint PowerDuplicateScheme(+ IntPtr RootPowerKey,+ ref Guid SourceSchemeGuid,+ IntPtr DestinationSchemeGuid+ );++ [DllImport("powrprof.dll")]+ private static extern uint PowerDeleteScheme(IntPtr RootPowerKey, ref Guid SchemeGuid);++ [DllImport("powrprof.dll", CharSet = CharSet.Unicode)]+ private static extern uint PowerWriteFriendlyName(+ IntPtr RootPowerKey,+ ref Guid SchemeGuid,+ IntPtr SubGroupOfPowerSettingsGuid,+ IntPtr PowerSettingGuid,+ IntPtr Buffer,+ uint BufferSize+ );++ [DllImport("powrprof.dll", CharSet = CharSet.Unicode)]+ private static extern uint PowerWriteDescription(+ IntPtr RootPowerKey,+ ref Guid SchemeGuid,+ IntPtr SubGroupOfPowerSettingsGuid,+ IntPtr PowerSettingGuid,+ IntPtr Buffer,+ uint BufferSize+ );++ [DllImport("powrprof.dll")]+ private static extern uint PowerReadACValueIndex(+ IntPtr RootPowerKey,+ ref Guid SchemeGuid,+ ref Guid SubGroupOfPowerSettingsGuid,+ ref Guid PowerSettingGuid,+ out uint AcValueIndex+ );++ [DllImport("powrprof.dll")]+ private static extern uint PowerReadDCValueIndex(+ IntPtr RootPowerKey,+ ref Guid SchemeGuid,+ ref Guid SubGroupOfPowerSettingsGuid,+ ref Guid PowerSettingGuid,+ out uint DcValueIndex+ );++ [DllImport("powrprof.dll")]+ private static extern uint PowerWriteACValueIndex(+ IntPtr RootPowerKey,+ ref Guid SchemeGuid,+ ref Guid SubGroupOfPowerSettingsGuid,+ ref Guid PowerSettingGuid,+ uint AcValueIndex+ );++ [DllImport("powrprof.dll")]+ private static extern uint PowerWriteDCValueIndex(+ IntPtr RootPowerKey,+ ref Guid SchemeGuid,+ ref Guid SubGroupOfPowerSettingsGuid,+ ref Guid PowerSettingGuid,+ uint DcValueIndex+ );++ [DllImport("powrprof.dll")]+ [return: MarshalAs(UnmanagedType.Bool)]+ private static extern bool PowerIsSettingRangeDefined(+ ref Guid SubKeyGuid,+ ref Guid SettingGuid+ );++ [DllImport("powrprof.dll")]+ private static extern uint PowerReadValueMin(+ IntPtr RootPowerKey,+ ref Guid SubGroupOfPowerSettingsGuid,+ ref Guid PowerSettingGuid,+ out uint ValueMinimum+ );++ [DllImport("powrprof.dll")]+ private static extern uint PowerReadValueMax(+ IntPtr RootPowerKey,+ ref Guid SubGroupOfPowerSettingsGuid,+ ref Guid PowerSettingGuid,+ out uint ValueMaximum+ );++ [DllImport("powrprof.dll")]+ private static extern uint PowerReadValueIncrement(+ IntPtr RootPowerKey,+ ref Guid SubGroupOfPowerSettingsGuid,+ ref Guid PowerSettingGuid,+ out uint ValueIncrement+ );++ [DllImport("powrprof.dll", CharSet = CharSet.Unicode)]+ private static extern uint PowerReadValueUnitsSpecifier(+ IntPtr RootPowerKey,+ ref Guid SubGroupOfPowerSettingsGuid,+ ref Guid PowerSettingGuid,+ IntPtr Buffer,+ ref uint BufferSize+ );++ [DllImport("powrprof.dll")]+ private static extern uint PowerReadPossibleValue(+ IntPtr RootPowerKey,+ ref Guid SubGroupOfPowerSettingsGuid,+ ref Guid PowerSettingGuid,+ out uint Type,+ uint PossibleSettingIndex,+ IntPtr Buffer,+ ref uint BufferSize+ );++ [DllImport("powrprof.dll", CharSet = CharSet.Unicode)]+ private static extern uint PowerReadPossibleFriendlyName(+ IntPtr RootPowerKey,+ ref Guid SubGroupOfPowerSettingsGuid,+ ref Guid PowerSettingGuid,+ uint PossibleSettingIndex,+ IntPtr Buffer,+ ref uint BufferSize+ );++ [DllImport("powrprof.dll", CharSet = CharSet.Unicode)]+ private static extern uint PowerReadPossibleDescription(+ IntPtr RootPowerKey,+ ref Guid SubGroupOfPowerSettingsGuid,+ ref Guid PowerSettingGuid,+ uint PossibleSettingIndex,+ IntPtr Buffer,+ ref uint BufferSize+ );++ [DllImport("kernel32.dll")]+ private static extern IntPtr LocalFree(IntPtr hMem);+}diff --git a/optimizerDuck/Services/System/SystemInfo.cs b/optimizerDuck/Services/System/SystemInfo.csnew file mode 100644index 0000000..0beac64--- /dev/null+++ b/optimizerDuck/Services/System/SystemInfo.cs@@ -0,0 +1,305 @@+namespace optimizerDuck.Services.System;++/// <summary>CPU vendor. Unknown = detection failed, never guessed.</summary>+public enum CpuVendor+{+ Unknown,+ Intel,+ Amd,+}++/// <summary>GPU vendor, keyed by PCI vendor ID on the DXGI path.</summary>+public enum GpuVendor+{+ Unknown,+ Nvidia,+ Amd,+ Intel,+}++/// <summary>OS/CPU architecture.</summary>+public enum Architecture+{+ Unknown,+ X86,+ X64,+ Arm64,+}++/// <summary>Device form factor inferred from SMBIOS chassis type.</summary>+public enum DeviceKind+{+ Unknown,+ Desktop,+ Laptop,+}++/// <summary>Firmware boot mode. From GetFirmwareType; never inferred.</summary>+public enum FirmwareMode+{+ Unknown,+ Uefi,+ Legacy,+}++/// <summary>Secure Boot state. Unavailable = Legacy boot (no Secure Boot possible).</summary>+public enum SecureBootState+{+ Unknown,+ Enabled,+ Disabled,+ Unavailable,+}++/// <summary>Generic on/off/unknown state for VBS and Memory Integrity.</summary>+public enum VbsState+{+ Unknown,+ Enabled,+ Disabled,+ Unavailable,+}++/// <summary>RAM technology from SMBIOS memory type. Unknown when WMI hides it.</summary>+public enum MemoryType+{+ Unknown,+ Ddr2,+ Ddr3,+ Ddr4,+ Ddr5,+ Sdram,+ Other,+}++/// <summary>+/// Vendor overclock-profile state. Always <see cref="Unknown"/>: Windows exposes+/// no reliable XMP/EXPO flag (speed alone never implies a profile). Exists so+/// callers can distinguish "not detected" from a future reliable detection.+/// </summary>+public enum MemoryProfileState+{+ Unknown,+ Enabled,+ Disabled,+}++/// <summary>Physical storage kind. Nvme is split out because it matters for perf expectations.</summary>+public enum StorageMediaType+{+ Unknown,+ Hdd,+ Ssd,+ Nvme,+}++/// <summary>Windows edition from EditionID. Server SKUs collapse to Server.</summary>+public enum WindowsEdition+{+ Unknown,+ Home,+ Pro,+ Education,+ Enterprise,+ Server,+}++/// <summary>Operating system facts. All display text is resolved in UI layer.</summary>+public sealed record WindowsInfo+{+ public static readonly WindowsInfo Unknown = new();++ /// <summary>Major build number (e.g. 26100). Null when unreadable.</summary>+ public int? BuildNumber { get; init; }++ /// <summary>Display version (e.g. "24H2"). Null when unreadable.</summary>+ public string? DisplayVersion { get; init; }++ public WindowsEdition Edition { get; init; } = WindowsEdition.Unknown;+ public Architecture Architecture { get; init; } = Architecture.Unknown;+ public DeviceKind DeviceKind { get; init; } = DeviceKind.Unknown;+ public DateTime? InstallDate { get; init; }+ public DateTime? LastBootTime { get; init; }++ public bool IsWindows11 => BuildNumber is >= 22000;+ public bool IsWindows10 => BuildNumber is >= 10240 and < 22000;+}++/// <summary>CPU facts. Frequencies are best-effort informational, never gating.</summary>+public sealed record CpuInfo+{+ public static readonly CpuInfo Unknown = new();++ public string? Name { get; init; }+ public CpuVendor Vendor { get; init; } = CpuVendor.Unknown;+ public Architecture Architecture { get; init; } = Architecture.Unknown;+ public int CoreCount { get; init; }+ public int ThreadCount { get; init; }+ public int? MaxFrequencyMhz { get; init; }+ public int? CurrentFrequencyMhz { get; init; }+ public int? L2CacheKB { get; init; }+ public int? L3CacheKB { get; init; }++ /// <summary>Null when firmware flag unreadable (Win32_Processor.VirtualizationFirmwareEnabled).</summary>+ public bool? VirtualizationFirmwareEnabled { get; init; }++ public bool IsIntel => Vendor == CpuVendor.Intel;+ public bool IsAmd => Vendor == CpuVendor.Amd;+}++/// <summary>Single GPU. Null VramMB/DriverVersion = not reported, not zero.</summary>+public sealed record GpuInfo+{+ public static readonly GpuInfo Unknown = new();++ public string? Name { get; init; }+ public GpuVendor Vendor { get; init; } = GpuVendor.Unknown;+ public int? VramMB { get; init; }+ public string? DriverVersion { get; init; }+ public DateTime? DriverDate { get; init; }+ public string? DeviceId { get; init; }+ public string? PnpDeviceId { get; init; }++ public bool IsNvidia => Vendor == GpuVendor.Nvidia;+ public bool IsAmd => Vendor == GpuVendor.Amd;+ public bool IsIntel => Vendor == GpuVendor.Intel;+}++/// <summary>One physical RAM stick. Null numeric = slot reports nothing usable.</summary>+public sealed record MemoryModuleInfo+{+ public double CapacityGB { get; init; }+ public int? SpeedMTps { get; init; }+ public MemoryType Type { get; init; } = MemoryType.Unknown;+ public string? Manufacturer { get; init; }+ public string? PartNumber { get; init; }+ public string? Slot { get; init; }+}++/// <summary>Memory facts. Totals from GlobalMemoryStatusEx (Task Manager accuracy).</summary>+public sealed record MemoryInfo+{+ public static readonly MemoryInfo Unknown = new() { Modules = [] };++ public long TotalBytes { get; init; }+ public long AvailableBytes { get; init; }++ /// <summary>Max configured clock across modules, MT/s. Null when unreported.</summary>+ public int? SpeedMTps { get; init; }++ public MemoryType Type { get; init; } = MemoryType.Unknown;++ /// <summary>Always Unknown today; kept so callers never invent it from speed.</summary>+ public MemoryProfileState OverclockProfile { get; init; } = MemoryProfileState.Unknown;++ public required IReadOnlyList<MemoryModuleInfo> Modules { get; init; }++ public long UsedBytes => Math.Max(0, TotalBytes - AvailableBytes);+ public double TotalGB => TotalBytes / (1024.0 * 1024.0 * 1024.0);+ public long TotalKB => TotalBytes / 1024;+ public double UsedPercent => TotalBytes > 0 ? UsedBytes * 100.0 / TotalBytes : 0;+}++/// <summary>Firmware + board facts. Mode from GetFirmwareType, never guessed.</summary>+public sealed record FirmwareInfo+{+ public static readonly FirmwareInfo Unknown = new();++ public FirmwareMode Mode { get; init; } = FirmwareMode.Unknown;+ public string? BiosVersion { get; init; }+ public string? BiosManufacturer { get; init; }+ public DateTime? BiosReleaseDate { get; init; }+ public string? SmbiosVersion { get; init; }+ public string? Motherboard { get; init; }+}++/// <summary>Security states. Unknown = could not read; Unavailable = not applicable.</summary>+public sealed record SecurityInfo+{+ public static readonly SecurityInfo Unknown = new();++ public SecureBootState SecureBoot { get; init; } = SecureBootState.Unknown;+ public VbsState VirtualizationBasedSecurity { get; init; } = VbsState.Unknown;+ public VbsState MemoryIntegrity { get; init; } = VbsState.Unknown;+}++/// <summary>+/// Active power scheme. Names come live from Windows+/// (<c>PowerReadFriendlyName</c>), never from a hardcoded table:+/// OEM and custom schemes have arbitrary names.+/// Null <see cref="SchemeId"/> means the active scheme could not be read.+/// </summary>+public sealed record PowerInfo+{+ public static readonly PowerInfo Unknown = new();++ public Guid? SchemeId { get; init; }+ public string? SchemeName { get; init; }++ public bool IsOptimizerDuckScheme(Guid optimizerDuckSchemeId) =>+ SchemeId == optimizerDuckSchemeId && optimizerDuckSchemeId != Guid.Empty;+}++/// <summary>One logical volume; Model/MediaType join physical disk when resolvable.</summary>+public sealed record StorageVolume+{+ public required string DriveLetter { get; init; }+ public bool IsSystemDrive { get; init; }+ public string? Label { get; init; }+ public string? FileSystem { get; init; }+ public long TotalBytes { get; init; }+ public long FreeBytes { get; init; }+ public StorageMediaType MediaType { get; init; } = StorageMediaType.Unknown;+ public string? Model { get; init; }+ public bool IsRemovable { get; init; }++ public long UsedBytes => Math.Max(0, TotalBytes - FreeBytes);+ public double UsedPercent => TotalBytes > 0 ? UsedBytes * 100.0 / TotalBytes : 0;+}++public sealed record StorageInfo+{+ public static readonly StorageInfo Unknown = new() { Volumes = [] };+ public required IReadOnlyList<StorageVolume> Volumes { get; init; }+}++/// <summary>Cheap always-available runtime facts.</summary>+public sealed record RuntimeInfo+{+ public static readonly RuntimeInfo Unknown = new();+ public TimeSpan Uptime { get; init; }+}++/// <summary>+/// Root snapshot. Sections fail independently: one Unknown section never+/// poisons the rest. <see cref="IsUnknown"/> marks a fully failed scan+/// (conditions fail open on it).+/// </summary>+public sealed record SystemInfo+{+ public static readonly SystemInfo Unknown = new()+ {+ IsUnknown = true,+ Windows = WindowsInfo.Unknown,+ Cpu = CpuInfo.Unknown,+ Memory = MemoryInfo.Unknown,+ Gpus = [],+ Firmware = FirmwareInfo.Unknown,+ Security = SecurityInfo.Unknown,+ Power = PowerInfo.Unknown,+ Storage = StorageInfo.Unknown,+ Runtime = RuntimeInfo.Unknown,+ };++ public bool IsUnknown { get; init; }+ public required WindowsInfo Windows { get; init; }+ public required CpuInfo Cpu { get; init; }+ public required MemoryInfo Memory { get; init; }+ public required IReadOnlyList<GpuInfo> Gpus { get; init; }+ public GpuInfo? PrimaryGpu { get; init; }+ public required FirmwareInfo Firmware { get; init; }+ public required SecurityInfo Security { get; init; }+ public required PowerInfo Power { get; init; }+ public required StorageInfo Storage { get; init; }+ public required RuntimeInfo Runtime { get; init; }+}diff --git a/optimizerDuck/Services/System/SystemInfoService.cs b/optimizerDuck/Services/System/SystemInfoService.csindex fd9315c..033ab5b 100644--- a/optimizerDuck/Services/System/SystemInfoService.cs+++ b/optimizerDuck/Services/System/SystemInfoService.cs@@ -3,513 +3,17 @@ using System.Globalization;using System.IO;using System.Management;using System.Runtime.InteropServices;+using System.Runtime.Versioning;using Microsoft.Extensions.Logging;using Microsoft.Win32;using Microsoft.Win32.SafeHandles;-using optimizerDuck.Resources.Languages;-using optimizerDuck.Services.Configuration;+using DotNetArch = System.Runtime.InteropServices.Architecture;using WmiEnumerationOptions = System.Management.EnumerationOptions;namespace optimizerDuck.Services.System;// ============================================================================-// MODELS (Immutable Records)-// ============================================================================--/// <summary>-/// Specifies the GPU vendor manufacturer.-/// </summary>-public enum GpuVendor-{- /// <summary>Unknown or unrecognized GPU vendor.</summary>- Unknown,-- /// <summary>NVIDIA Corporation.</summary>- NVIDIA,-- /// <summary>Advanced Micro Devices (AMD).</summary>- AMD,-- /// <summary>Intel Corporation.</summary>- Intel,-}--/// <summary>-/// Specifies the CPU vendor manufacturer.-/// </summary>-public enum CpuVendor-{- /// <summary>Unknown or unrecognized CPU vendor.</summary>- Unknown,-- /// <summary>Intel Corporation.</summary>- Intel,-- /// <summary>Advanced Micro Devices (AMD).</summary>- AMD,-}--/// <summary>-/// Specifies the device form factor inferred from chassis information.-/// Stored raw (never localized) so the display text can re-resolve on language change.-/// </summary>-public enum DeviceKind-{- /// <summary>Unknown or unrecognized device type.</summary>- Unknown,-- /// <summary>Desktop, tower, or other stationary machine.</summary>- Desktop,-- /// <summary>Laptop, notebook, or other portable machine.</summary>- Laptop,-}--/// <summary>-/// Represents information about a GPU.-/// </summary>-public sealed record GpuInfo-{- /// <summary>A sentinel value representing an unknown GPU.</summary>- public static readonly GpuInfo Unknown = new()- {- Name = Loc.Instance["Common.Unknown"],- DriverVersion = Loc.Instance["Common.Unknown"],- Vendor = GpuVendor.Unknown,- };-- /// <summary>- /// The display name of the GPU (e.g., "NVIDIA GeForce RTX 4090").- /// </summary>- public required string Name { get; init; }-- /// <summary>- /// The driver version string.- /// </summary>- public required string DriverVersion { get; init; }-- /// <summary>- /// The GPU vendor manufacturer.- /// </summary>- public required GpuVendor Vendor { get; init; }-- /// <summary>- /// The dedicated video memory in megabytes, or <c>null</c> if unknown.- /// </summary>- public int? MemoryMB { get; init; }-- /// <summary>- /// The PnP device ID from WMI, or <c>null</c> if unavailable.- /// </summary>- public string? DeviceId { get; init; }-- /// <summary>- /// The Plug and Play device ID, or <c>null</c> if unavailable.- /// </summary>- public string? PnpDeviceId { get; init; }-- /// <inheritdoc />- public override string ToString()- {- return $"GPU: {Name}, Driver: {DriverVersion}, Vendor: {Vendor}, Memory: {MemoryMB} MB, DeviceId: {DeviceId}, PnpDeviceId: {PnpDeviceId}";- }-}--/// <summary>-/// Represents information about the CPU.-/// </summary>-public sealed record CpuInfo-{- /// <summary>A sentinel value representing an unknown CPU.</summary>- public static readonly CpuInfo Unknown = new()- {- Name = Loc.Instance["Common.Unknown"],- Manufacturer = Loc.Instance["Common.Unknown"],- Vendor = CpuVendor.Unknown,- Architecture = Loc.Instance["Common.Unknown"],- Cores = 0,- Threads = 0,- MaxClockMHz = 0,- CurrentClockMHz = 0,- L2CacheKB = 0,- L3CacheKB = 0,- };-- /// <summary>- /// The processor display name (e.g., "Intel Core i9-13900K").- /// </summary>- public required string Name { get; init; }-- /// <summary>- /// The manufacturer identifier (e.g., "GenuineIntel").- /// </summary>- public required string Manufacturer { get; init; }-- /// <summary>- /// The detected CPU vendor (e.g., <see cref="CpuVendor.Intel"/>).- /// </summary>- public required CpuVendor Vendor { get; init; }-- /// <summary>- /// The processor architecture (e.g., "64-bit").- /// </summary>- public required string Architecture { get; init; }-- /// <summary>- /// The number of physical cores.- /// </summary>- public required int Cores { get; init; }-- /// <summary>- /// The number of logical threads.- /// </summary>- public required int Threads { get; init; }-- /// <summary>- /// The maximum clock speed in MHz.- /// </summary>- public required int MaxClockMHz { get; init; }-- /// <summary>- /// The current clock speed in MHz.- /// </summary>- public required int CurrentClockMHz { get; init; }-- /// <summary>- /// The L2 cache size in kilobytes.- /// </summary>- public required int L2CacheKB { get; init; }-- /// <summary>- /// The L3 cache size in kilobytes.- /// </summary>- public required int L3CacheKB { get; init; }-}--/// <summary>-/// Represents information about a disk volume.-/// </summary>-public sealed record DiskVolume-{- /// <summary>- /// The drive letter (e.g., "C:").- /// </summary>- public required string DriveLetter { get; init; }-- /// <summary>- /// Indicates whether this is the Windows system drive.- /// </summary>- public required bool IsSystemDrive { get; init; }-- /// <summary>- /// The file system format (e.g., "NTFS").- /// </summary>- public required string DriveFormat { get; init; }-- /// <summary>- /// The drive type (e.g., "Fixed", "Removable").- /// </summary>- public required string DriveType { get; init; }-- /// <summary>- /// The volume label.- /// </summary>- public required string VolumeLabel { get; init; }-- /// <summary>- /// The total disk size in gigabytes.- /// </summary>- public required double TotalSizeGB { get; init; }-- /// <summary>- /// The available free space in gigabytes.- /// </summary>- public required double AvailableSizeGB { get; init; }-- /// <summary>- /// The used space in gigabytes.- /// </summary>- public required double UsedSizeGB { get; init; }-- /// <summary>- /// The percentage of disk space used.- /// </summary>- public required double UsedPercent { get; init; }-- /// <summary>- /// The storage media type: "SSD", "HDD", or "Unknown".- /// </summary>- public required string MediaType { get; init; }-- /// <summary>- /// Indicates whether the drive is removable (e.g., USB).- /// </summary>- public required bool IsRemovable { get; init; }-- /// <summary>- /// The disk serial number, or <c>null</c> if unavailable.- /// </summary>- public string? SerialNumber { get; init; }-- /// <summary>- /// The disk model name, or <c>null</c> if unavailable.- /// </summary>- public string? Model { get; init; }-}--/// <summary>-/// Represents information about all disk volumes.-/// </summary>-public sealed record DiskInfo-{- /// <summary>A sentinel value representing unknown disk information.</summary>- public static readonly DiskInfo Unknown = new() { Volumes = [] };-- /// <summary>- /// The list of detected disk volumes.- /// </summary>- public required IReadOnlyList<DiskVolume> Volumes { get; init; }-}--/// <summary>-/// Represents a physical RAM module.-/// </summary>-public sealed record RamModule-{- /// <summary>- /// The module capacity in gigabytes.- /// </summary>- public required double CapacityGB { get; init; }-- /// <summary>- /// The memory speed in MHz.- /// </summary>- public required string SpeedMHz { get; init; }-- /// <summary>- /// The module manufacturer.- /// </summary>- public required string Manufacturer { get; init; }-- /// <summary>- /// The module part number.- /// </summary>- public required string PartNumber { get; init; }-- /// <summary>- /// The physical slot or device locator string.- /// </summary>- public required string DeviceLocator { get; init; }-}--/// <summary>-/// Represents information about RAM.-/// </summary>-public sealed record RamInfo-{- /// <summary>A sentinel value representing unknown RAM information.</summary>- public static readonly RamInfo Unknown = new()- {- TotalGB = 0,- TotalMB = 0,- TotalKB = 0,- AvailableGB = 0,- UsedPercent = 0,- UsedGB = 0,- Modules = [],- };-- /// <summary>- /// The total installed RAM in gigabytes.- /// </summary>- public required double TotalGB { get; init; }-- /// <summary>- /// The total installed RAM in megabytes.- /// </summary>- public required long TotalMB { get; init; }-- /// <summary>- /// The total installed RAM in kilobytes.- /// </summary>- public required long TotalKB { get; init; }-- /// <summary>- /// The available (free) RAM in gigabytes.- /// </summary>- public required double AvailableGB { get; init; }-- /// <summary>- /// The percentage of RAM currently in use.- /// </summary>- public required double UsedPercent { get; init; }-- /// <summary>- /// The amount of RAM currently in use in gigabytes.- /// </summary>- public required double UsedGB { get; init; }-- /// <summary>- /// The list of physical RAM modules.- /// </summary>- public required IReadOnlyList<RamModule> Modules { get; init; }-}--/// <summary>-/// Represents information about the operating system.-/// </summary>-public sealed record OsInfo-{- /// <summary>A sentinel value representing unknown OS information.</summary>- public static readonly OsInfo Unknown = new()- {- Name = Loc.Instance["Common.Unknown"],- Version = Loc.Instance["Common.Unknown"],- BuildNumber = Loc.Instance["Common.Unknown"],- Edition = Loc.Instance["Common.Unknown"],- Architecture = Loc.Instance["Common.Unknown"],- DeviceType = DeviceKind.Unknown,- InstallDate = Loc.Instance["Common.Unknown"],- LastBootUpTime = Loc.Instance["Common.Unknown"],- };-- /// <summary>- /// The OS name (e.g., "Microsoft Windows 11 Pro").- /// </summary>- public required string Name { get; init; }-- /// <summary>- /// The OS version string.- /// </summary>- public required string Version { get; init; }-- /// <summary>- /// The OS build number.- /// </summary>- public required string BuildNumber { get; init; }-- /// <summary>- /// The OS edition (e.g., "Pro", "Home").- /// </summary>- public required string Edition { get; init; }-- /// <summary>- /// The OS architecture (e.g., "64-bit").- /// </summary>- public required string Architecture { get; init; }-- /// <summary>- /// The device form factor inferred from chassis information.- /// </summary>- public required DeviceKind DeviceType { get; init; }-- /// <summary>- /// The OS install date.- /// </summary>- public required string InstallDate { get; init; }-- /// <summary>- /// The last boot-up time.- /// </summary>- public required string LastBootUpTime { get; init; }-}--/// <summary>-/// Represents information about the system BIOS.-/// </summary>-public sealed record BiosInfo-{- /// <summary>A sentinel value representing unknown BIOS information.</summary>- public static readonly BiosInfo Unknown = new()- {- Manufacturer = Loc.Instance["Common.Unknown"],- Version = Loc.Instance["Common.Unknown"],- ReleaseDate = Loc.Instance["Common.Unknown"],- SmbiosVersion = Loc.Instance["Common.Unknown"],- SerialNumber = Loc.Instance["Common.Unknown"],- };-- /// <summary>- /// The BIOS manufacturer.- /// </summary>- public required string Manufacturer { get; init; }-- /// <summary>- /// The BIOS version string.- /// </summary>- public required string Version { get; init; }-- /// <summary>- /// The BIOS release date.- /// </summary>- public required string ReleaseDate { get; init; }-- /// <summary>- /// The SMBIOS version.- /// </summary>- public required string SmbiosVersion { get; init; }-- /// <summary>- /// The system serial number.- /// </summary>- public required string SerialNumber { get; init; }-}--/// <summary>-/// Represents a complete snapshot of the system's hardware and software information.-/// </summary>-public sealed record SystemSnapshot-{- /// <summary>A sentinel value representing a completely unknown system.</summary>- public static readonly SystemSnapshot Unknown = new()- {- Cpu = CpuInfo.Unknown,- Ram = RamInfo.Unknown,- Os = OsInfo.Unknown,- Bios = BiosInfo.Unknown,- Gpus = [],- PrimaryGpu = null,- Disk = DiskInfo.Unknown,- };-- /// <summary>- /// CPU information.- /// </summary>- public required CpuInfo Cpu { get; init; }-- /// <summary>- /// RAM information.- /// </summary>- public required RamInfo Ram { get; init; }-- /// <summary>- /// Operating system information.- /// </summary>- public required OsInfo Os { get; init; }-- /// <summary>- /// BIOS information.- /// </summary>- public required BiosInfo Bios { get; init; }-- /// <summary>- /// List of all detected GPUs.- /// </summary>- public required IReadOnlyList<GpuInfo> Gpus { get; init; }-- /// <summary>- /// The primary GPU (typically the one with the most VRAM), or <c>null</c> if none detected.- /// </summary>- public GpuInfo? PrimaryGpu { get; init; }-- /// <summary>- /// Disk volume information.- /// </summary>- public required DiskInfo Disk { get; init; }-}--// ============================================================================-// WMI HELPER (with connection caching)+// WMI HELPER (connection caching, always-disposing queries)// ============================================================================internal static class WmiHelper@@ -559,11 +63,18 @@ internal static class WmiHelperScopeCache.Clear();}- public static IEnumerable<ManagementObject> Query(+ /// <summary>+ /// Executes a WMI query and maps the live objects to <typeparamref name="T"/>.+ /// Every <see cref="ManagementObject"/> is disposed before return.+ /// Returns default on any failure; the selector itself never sees disposed objects.+ /// </summary>+ public static T? Query<T>(string query,+ Func<IReadOnlyList<ManagementObject>, T> selector,string namespacePath = @"root\cimv2"){+ ManagementObject[] items = [];try{var scope = GetScope(namespacePath);@@ -573,23 +84,27 @@ internal static class WmiHelperDefaultOptions);using var results = searcher.Get();- return results.Cast<ManagementObject>().ToArray();+ items = results.Cast<ManagementObject>().ToArray();+ return selector(items);}catch{- return [];+ return default;+ }+ finally+ {+ foreach (var item in items)+ item.Dispose();}}/// <summary>- /// Executes a WMI query and passes results to a selector.- /// All ManagementObject items are disposed after the selector completes.- /// Returns <c>default(T)</c> if the query fails or throws; callers must null-check- /// the result for reference types.+ /// Maps the first row of a WMI query. The object is disposed before return.+ /// Returns default when the query yields nothing or fails./// </summary>- public static T? Query<T>(+ public static T QueryFirst<T>(string query,- Func<IEnumerable<ManagementObject>, T> selector,+ Func<ManagementObject, T> selector,string namespacePath = @"root\cimv2"){@@ -604,11 +119,13 @@ internal static class WmiHelper);using var results = searcher.Get();items = results.Cast<ManagementObject>().ToArray();- return selector(items);+ if (items.Length == 0)+ return default!;+ return selector(items[0]);}catch{- return default;+ return default!;}finally{@@ -617,71 +134,76 @@ internal static class WmiHelper}}- public static string GetString(ManagementObject mo, string property, string? fallback = null)+ /// <summary>Escapes a value for safe use in WQL string literals.</summary>+ public static string EscapeWql(string value)+ {+ return value.Replace("'", "''");+ }++ public static string? GetString(ManagementObject mo, string property){- fallback ??= Loc.Instance["Common.Unknown"];try{- var value = mo[property];- return value switch+ return mo[property] switch{- null => fallback,- string[] arr => arr.Length > 0 ? arr[0].Trim() : fallback,- _ => value.ToString()?.Trim() ?? fallback,+ null => null,+ string[] arr => arr.Length > 0 ? arr[0].Trim() : null,+ var v => v.ToString()?.Trim() is { Length: > 0 } s ? s : null,};}catch{- return fallback;+ return null;}}- public static int GetInt(ManagementObject mo, string property, int fallback = 0)+ public static int? GetInt(ManagementObject mo, string property){try{var value = mo[property];- return value == null ? fallback : Convert.ToInt32(value);+ return value is null ? null : Convert.ToInt32(value);}catch{- return fallback;+ return null;}}- public static long GetLong(ManagementObject mo, string property, long fallback = 0)+ public static long? GetLong(ManagementObject mo, string property){try{var value = mo[property];- return value == null ? fallback : Convert.ToInt64(value);+ return value is null ? null : Convert.ToInt64(value);}catch{- return fallback;+ return null;}}- /// <summary>- /// Escapes a value for safe use in WQL string literals (doubles single quotes).- /// </summary>- public static string EscapeWql(string value)+ public static bool? GetBool(ManagementObject mo, string property){- return value.Replace("'", "''");+ try+ {+ var value = mo[property];+ return value is null ? null : Convert.ToBoolean(value);+ }+ catch+ {+ return null;+ }}- public static ManagementObject? GetFirst(string query, string namespacePath = @"root\cimv2")+ public static DateTime? GetWmiDate(ManagementObject mo, string property){+ var raw = GetString(mo, property);+ if (string.IsNullOrEmpty(raw))+ return null;try{- var scope = GetScope(namespacePath);- using var searcher = new ManagementObjectSearcher(- scope,- new ObjectQuery(query),- DefaultOptions- );- using var results = searcher.Get();- return results.Cast<ManagementObject>().FirstOrDefault();+ return ManagementDateTimeConverter.ToDateTime(raw);}catch{@@ -691,7 +213,7 @@ internal static class WmiHelper}// ============================================================================-// NATIVE MEMORY API (Task Manager accuracy)+// NATIVE APIS (no process spawning)// ============================================================================internal static class NativeMemory@@ -700,9 +222,7 @@ internal static class NativeMemory[return: MarshalAs(UnmanagedType.Bool)]private static extern bool GlobalMemoryStatusEx(ref MEMORYSTATUSEX lpBuffer);- /// <summary>- /// Returns current memory status using the same API Task Manager uses.- /// </summary>+ /// <summary>Same API Task Manager uses for memory usage.</summary>public static MEMORYSTATUSEX? GetMemoryStatus(){var status = new MEMORYSTATUSEX { dwLength = (uint)Marshal.SizeOf<MEMORYSTATUSEX>() };@@ -724,18 +244,67 @@ internal static class NativeMemory}}-// ============================================================================-// COMPONENT PROVIDERS-// ============================================================================+[SupportedOSPlatform("windows")]+internal static class NativeFirmware+{+ // FIRMWARE_TYPE: 0 Unknown, 1 Bios, 2 Uefi.+ [DllImport("kernel32.dll", SetLastError = true)]+ [return: MarshalAs(UnmanagedType.Bool)]+ private static extern bool GetFirmwareType(out uint firmwareType);++ public static FirmwareMode GetMode()+ {+ try+ {+ if (!GetFirmwareType(out var type))+ return FirmwareMode.Unknown;+ return type switch+ {+ 1 => FirmwareMode.Legacy,+ 2 => FirmwareMode.Uefi,+ _ => FirmwareMode.Unknown,+ };+ }+ catch+ {+ return FirmwareMode.Unknown;+ }+ }+}++internal static class PowerReader+{+ private static PowerPlanService? _service;++ internal static void Configure(PowerPlanService service)+ {+ _service = service;+ }++ internal static (Guid? Id, string? Name) ReadActive()+ {+ var service = _service;+ if (service is null)+ return (null, null);+ try+ {+ var id = service.GetActiveSchemeId();+ if (id is null)+ return (null, null);+ return (id.Value, service.GetSchemeName(id.Value));+ }+ catch+ {+ return (null, null);+ }+ }+}internal static class CpuProvider{private static readonly Lazy<CpuInfo> _cached = new(Load, LazyThreadSafetyMode.PublicationOnly);- /// <summary>- /// Gets CPU info using Registry (fast) + targeted WMI (only for cache sizes).- /// Registry path: HKLM\HARDWARE\DESCRIPTION\System\CentralProcessor\0- /// </summary>+ /// <summary>Registry (fast) + one targeted WMI row for caches/virtualization.</summary>public static CpuInfo Get(){return _cached.Value;@@ -745,10 +314,9 @@ internal static class CpuProvider{try{- // ── Fast path: Registry ──────────────────────────────────────- var name = Loc.Instance["Common.Unknown"];- var manufacturer = Loc.Instance["Common.Unknown"];- var currentMHz = 0;+ string? name = null;+ string? manufacturer = null;+ int? currentMHz = null;using (var cpuKey = Registry.LocalMachine.OpenSubKey(@@ -758,58 +326,52 @@ internal static class CpuProvider{if (cpuKey != null){- name = cpuKey.GetValue("ProcessorNameString")?.ToString()?.Trim() ?? name;- manufacturer =- cpuKey.GetValue("VendorIdentifier")?.ToString()?.Trim() ?? manufacturer;- currentMHz = cpuKey.GetValue("~MHz") is int mhz ? mhz : 0;+ name = cpuKey.GetValue("ProcessorNameString")?.ToString()?.Trim();+ manufacturer = cpuKey.GetValue("VendorIdentifier")?.ToString()?.Trim();+ if (cpuKey.GetValue("~MHz") is int mhz)+ currentMHz = mhz;}}- // Thread count via Environment (instant, no WMI)var threads = Environment.ProcessorCount;-- // ── Targeted WMI: only fields not available in Registry ──────- var cores = 0;- var maxMHz = currentMHz;- var l2kb = 0;- var l3kb = 0;-- var cpu = WmiHelper.GetFirst(- "SELECT NumberOfCores, MaxClockSpeed, L2CacheSize, L3CacheSize FROM Win32_Processor"+ int? cores = null;+ int? maxMHz = null;+ int? l2kb = null;+ int? l3kb = null;+ bool? virtualization = null;++ var row = WmiHelper.QueryFirst(+ "SELECT NumberOfCores, MaxClockSpeed, L2CacheSize, L3CacheSize, VirtualizationFirmwareEnabled FROM Win32_Processor",+ static mo =>+ (+ Cores: WmiHelper.GetInt(mo, "NumberOfCores"),+ MaxMHz: WmiHelper.GetInt(mo, "MaxClockSpeed"),+ L2: WmiHelper.GetInt(mo, "L2CacheSize"),+ L3: WmiHelper.GetInt(mo, "L3CacheSize"),+ Virt: WmiHelper.GetBool(mo, "VirtualizationFirmwareEnabled")+ ));- if (cpu != null)+ if (row is { } r){- try- {- cores = WmiHelper.GetInt(cpu, "NumberOfCores");- maxMHz = WmiHelper.GetInt(cpu, "MaxClockSpeed", maxMHz);- l2kb = WmiHelper.GetInt(cpu, "L2CacheSize");- l3kb = WmiHelper.GetInt(cpu, "L3CacheSize");- }- finally- {- cpu.Dispose();- }+ cores = r.Cores;+ maxMHz = r.MaxMHz;+ l2kb = r.L2;+ l3kb = r.L3;+ virtualization = r.Virt;}- if (cores == 0)- cores = threads;-- var vendor = DetectCpuVendor(manufacturer);- var architecture = Environment.Is64BitOperatingSystem ? "64-bit" : "32-bit";-return new CpuInfo{- Name = name,- Manufacturer = manufacturer,- Vendor = vendor,- Architecture = architecture,- Cores = cores,- Threads = threads,- MaxClockMHz = maxMHz,- CurrentClockMHz = currentMHz,+ Name = string.IsNullOrWhiteSpace(name) ? null : name,+ Vendor = DetectVendor(manufacturer),+ Architecture = MapArchitecture(),+ CoreCount = cores is > 0 ? cores.Value : threads,+ ThreadCount = threads,+ MaxFrequencyMhz = maxMHz ?? currentMHz,+ CurrentFrequencyMhz = currentMHz,L2CacheKB = l2kb,L3CacheKB = l3kb,+ VirtualizationFirmwareEnabled = virtualization,};}catch@@ -818,134 +380,174 @@ internal static class CpuProvider}}- private static CpuVendor DetectCpuVendor(string manufacturer)+ internal static Architecture MapArchitecture(){+ return RuntimeInformation.OSArchitecture switch+ {+ DotNetArch.X64 => Architecture.X64,+ DotNetArch.X86 => Architecture.X86,+ DotNetArch.Arm64 => Architecture.Arm64,+ _ => Architecture.Unknown,+ };+ }++ internal static CpuVendor DetectVendor(string? manufacturer)+ {+ if (string.IsNullOrWhiteSpace(manufacturer))+ return CpuVendor.Unknown;var lower = manufacturer.ToLowerInvariant();if (lower.Contains("intel") || lower.Contains("genuineintel"))return CpuVendor.Intel;if (lower.Contains("amd") || lower.Contains("authenticamd"))- return CpuVendor.AMD;+ return CpuVendor.Amd;return CpuVendor.Unknown;}}-internal static class RamProvider+internal static class MemoryProvider{- private static readonly Lazy<List<RamModule>> _cachedModules = new(+ private static readonly Lazy<IReadOnlyList<MemoryModuleInfo>> _cachedModules = new(LoadPhysicalModules,LazyThreadSafetyMode.PublicationOnly);- /// <summary>- /// Gets RAM info using GlobalMemoryStatusEx (same API as Task Manager)- /// for usage stats, and WMI only for physical module details.- /// </summary>- public static RamInfo Get()+ /// <summary>Live usage via GlobalMemoryStatusEx + cached module details.</summary>+ public static MemoryInfo Get(){try{var modules = _cachedModules.Value;- var (totalGB, totalMB, totalKB, availableGB, usedPercent, usedGB) = GetMemoryStats(- modules- );+ var status = NativeMemory.GetMemoryStatus();+ if (status is not { } s || s.ullTotalPhys == 0)+ return FallbackFromModules(modules);- return new RamInfo+ return new MemoryInfo{- TotalGB = totalGB,- TotalMB = totalMB,- TotalKB = totalKB,- AvailableGB = availableGB,- UsedPercent = usedPercent,- UsedGB = usedGB,+ TotalBytes = (long)s.ullTotalPhys,+ AvailableBytes = (long)s.ullAvailPhys,+ SpeedMTps = MaxSpeed(modules),+ Type = DominantType(modules),+ OverclockProfile = MemoryProfileState.Unknown,Modules = modules,};}catch{- return RamInfo.Unknown;+ return MemoryInfo.Unknown;}}- private static List<RamModule> LoadPhysicalModules()+ private static MemoryInfo FallbackFromModules(IReadOnlyList<MemoryModuleInfo> modules){- var modules = new List<RamModule>();- var physicalMemory = WmiHelper.Query(- "SELECT Capacity, Speed, Manufacturer, PartNumber, DeviceLocator FROM Win32_PhysicalMemory"- );+ // GlobalMemoryStatusEx failed: report installed capacity, zero live data.+ long total = 0;+ foreach (var m in modules)+ total += (long)(m.CapacityGB * 1024 * 1024 * 1024);+ return new MemoryInfo+ {+ TotalBytes = total,+ AvailableBytes = 0,+ SpeedMTps = null,+ Type = DominantType(modules),+ OverclockProfile = MemoryProfileState.Unknown,+ Modules = modules,+ };+ }- foreach (var mem in physicalMemory)+ internal static int? MaxSpeed(IReadOnlyList<MemoryModuleInfo> modules)+ {+ int? speed = null;+ foreach (var m in modules)+ if (m.SpeedMTps is > 0 && (speed is null || m.SpeedMTps > speed))+ speed = m.SpeedMTps;+ return speed;+ }++ internal static MemoryType DominantType(IReadOnlyList<MemoryModuleInfo> modules)+ {+ var counts = new Dictionary<MemoryType, int>();+ foreach (var m in modules){- try+ if (m.Type == MemoryType.Unknown)+ continue;+ counts.TryGetValue(m.Type, out var n);+ counts[m.Type] = n + 1;+ }+ var best = MemoryType.Unknown;+ var bestCount = 0;+ foreach (var (type, n) in counts)+ if (n > bestCount){- var capacityBytes = WmiHelper.GetLong(mem, "Capacity");- var capacityGB = capacityBytes > 0 ? capacityBytes / (1024.0 * 1024.0 * 1024.0) : 0;- var speed = WmiHelper.GetString(mem, "Speed");- var manufacturer = WmiHelper.GetString(mem, "Manufacturer");- var partNumber = WmiHelper.GetString(mem, "PartNumber");- var deviceLocator = WmiHelper.GetString(mem, "DeviceLocator");-- modules.Add(- new RamModule+ best = type;+ bestCount = n;+ }+ return best;+ }++ private static IReadOnlyList<MemoryModuleInfo> LoadPhysicalModules()+ {+ try+ {+ var modules =+ WmiHelper.Query(+ "SELECT Capacity, Speed, ConfiguredClockSpeed, SMBIOSMemoryType, Manufacturer, PartNumber, DeviceLocator FROM Win32_PhysicalMemory",+ static items =>{- CapacityGB = Math.Round(capacityGB, 2),- SpeedMHz = speed,- Manufacturer = manufacturer,- PartNumber = partNumber,- DeviceLocator = deviceLocator,+ var list = new List<MemoryModuleInfo>(items.Count);+ foreach (var mem in items)+ {+ var capacityBytes = WmiHelper.GetLong(mem, "Capacity") ?? 0;+ if (capacityBytes <= 0)+ continue;+ var configured = WmiHelper.GetInt(mem, "ConfiguredClockSpeed");+ var memType = MapMemoryType(WmiHelper.GetInt(mem, "SMBIOSMemoryType"));+ var speed = WmiHelper.GetInt(mem, "Speed");+ list.Add(+ new MemoryModuleInfo+ {+ CapacityGB = Math.Round(+ capacityBytes / (1024.0 * 1024.0 * 1024.0),+ 2+ ),+ SpeedMTps =+ configured is > 0 ? configured+ : speed is > 0 ? speed+ : null,+ Type = memType,+ Manufacturer = WmiHelper.GetString(mem, "Manufacturer"),+ PartNumber = WmiHelper.GetString(mem, "PartNumber"),+ Slot = WmiHelper.GetString(mem, "DeviceLocator"),+ }+ );+ }+ return list;}- );- }- finally- {- mem.Dispose();- }+ ) ?? new List<MemoryModuleInfo>();+ return modules;+ }+ catch+ {+ return [];}-- return modules;}- private static (- double totalGB,- long totalMB,- long totalKB,- double availableGB,- double usedPercent,- double usedGB- ) GetMemoryStats(List<RamModule> modules)+ /// <summary>SMBIOS memory-type codes (DMTF). Unlisted/zero = Unknown, never guessed.</summary>+ internal static MemoryType MapMemoryType(int? code){- // ── Primary: GlobalMemoryStatusEx (Task Manager accuracy) ────────- var memStatus = NativeMemory.GetMemoryStatus();- if (memStatus.HasValue)+ return code switch{- var status = memStatus.Value;-- var totalBytes = (double)status.ullTotalPhys;- var availBytes = (double)status.ullAvailPhys;- var usedBytes = totalBytes - availBytes;-- var totalGB = Math.Round(totalBytes / (1024.0 * 1024.0 * 1024.0), 2);- var totalMB = (long)(totalBytes / (1024.0 * 1024.0));- var totalKB = (long)(totalBytes / 1024.0);- var availableGB = Math.Round(availBytes / (1024.0 * 1024.0 * 1024.0), 2);- var usedGB = Math.Round(usedBytes / (1024.0 * 1024.0 * 1024.0), 2);- var usedPercent = (double)status.dwMemoryLoad; // Already calculated by Windows-- return (totalGB, totalMB, totalKB, availableGB, usedPercent, usedGB);- }-- // ── Fallback: module-based calculation ───────────────────────────- var fallbackTotalGB = modules.Sum(m => m.CapacityGB);- if (fallbackTotalGB <= 0)- fallbackTotalGB = 0;-- var fallbackTotalMB = (long)(fallbackTotalGB * 1024);- var fallbackTotalKB = fallbackTotalMB * 1024;-- return (Math.Round(fallbackTotalGB, 2), fallbackTotalMB, fallbackTotalKB, 0, 0, 0);+ 0x13 => MemoryType.Ddr2,+ 0x18 => MemoryType.Ddr3,+ 0x1A => MemoryType.Ddr4,+ 0x22 => MemoryType.Ddr5,+ 0x0F or 0x10 or 0x11 or 0x12 => MemoryType.Sdram,+ null or 0x00 or 0x02 => MemoryType.Unknown,+ _ => MemoryType.Other,+ };}}-public static class DiskHelper+internal static class DiskMediaDetector{private const uint FILE_SHARE_READ = 0x00000001;private const uint FILE_SHARE_WRITE = 0x00000002;@@ -954,7 +556,7 @@ public static class DiskHelperprivate const uint GENERIC_READ = 0x0;private const uint IOCTL_STORAGE_QUERY_PROPERTY = 0x2D1400;- private static readonly ConcurrentDictionary<string, string> MediaTypeCache = new(+ private static readonly ConcurrentDictionary<string, StorageMediaType> MediaTypeCache = new(StringComparer.OrdinalIgnoreCase);@@ -970,6 +572,7 @@ public static class DiskHelper);[DllImport("kernel32.dll", SetLastError = true)]+ [return: MarshalAs(UnmanagedType.Bool)]private static extern bool DeviceIoControl(SafeFileHandle hDevice,uint dwIoControlCode,@@ -981,39 +584,23 @@ public static class DiskHelperIntPtr lpOverlapped);- /// <summary>Detects the storage media type for the given drive letter using a combination of seek-penalty detection and WMI queries.</summary>- /// <param name="driveLetter">The drive letter (e.g., "C:" or "C:\").</param>- /// <returns>A string describing the media type (e.g., "SSD", "HDD"), or "Unknown" if detection fails.</returns>- public static string DetectMediaType(string driveLetter)+ /// <summary>Seek-penalty ioctl (fast, cached). Unknown when the handle/ioctl fails.</summary>+ public static StorageMediaType Detect(string driveLetter){var key = driveLetter.TrimEnd('\\', '/').ToUpperInvariant();- return MediaTypeCache.GetOrAdd(- key,- static lk =>- {- var seekPenalty = DetectViaSSDSeekPenalty(lk);- if (seekPenalty != "Unknown")- return seekPenalty;-- var wmiType = DetectViaWMI(lk);- if (wmiType != "Unknown")- return wmiType;-- return "Unknown";- }- );+ return MediaTypeCache.GetOrAdd(key, static lk => DetectViaSeekPenalty(lk));}- private static string DetectViaSSDSeekPenalty(string driveLetter)+ private static StorageMediaType DetectViaSeekPenalty(string driveLetter){try{- var trimmedDrive = driveLetter.TrimEnd('\\', '/');- if (string.IsNullOrWhiteSpace(trimmedDrive))- return "Unknown";+ var trimmed = driveLetter.TrimEnd('\\', '/');+ if (string.IsNullOrWhiteSpace(trimmed))+ return StorageMediaType.Unknown;using var handle = CreateFile(- @"\\.\" + trimmedDrive,+ @"\\.\" + trimmed,GENERIC_READ,FILE_SHARE_READ | FILE_SHARE_WRITE,IntPtr.Zero,@@ -1021,9 +608,8 @@ public static class DiskHelperFILE_ATTRIBUTE_NORMAL,IntPtr.Zero);-if (handle.IsInvalid)- return "Unknown";+ return StorageMediaType.Unknown;var query = new STORAGE_PROPERTY_QUERY{@@ -1031,21 +617,16 @@ public static class DiskHelperQueryType = STORAGE_QUERY_TYPE.PropertyStandardQuery,AdditionalParameters = new byte[1],};-var querySize = Marshal.SizeOf(query);var resultSize = Marshal.SizeOf<DEVICE_SEEK_PENALTY_DESCRIPTOR>();-var queryPtr = IntPtr.Zero;var resultPtr = IntPtr.Zero;-try{queryPtr = Marshal.AllocHGlobal(querySize);Marshal.StructureToPtr(query, queryPtr, false);-resultPtr = Marshal.AllocHGlobal(resultSize);-- var success = DeviceIoControl(+ var ok = DeviceIoControl(handle,IOCTL_STORAGE_QUERY_PROPERTY,queryPtr,@@ -1055,95 +636,25 @@ public static class DiskHelperout _,IntPtr.Zero);-- if (!success)- return "Unknown";-- var descriptor = Marshal.PtrToStructure<DEVICE_SEEK_PENALTY_DESCRIPTOR>(resultPtr);- return descriptor.IncursSeekPenalty ? "HDD" : "SSD";+ if (!ok)+ return StorageMediaType.Unknown;+ var desc = Marshal.PtrToStructure<DEVICE_SEEK_PENALTY_DESCRIPTOR>(resultPtr);+ return desc.IncursSeekPenalty ? StorageMediaType.Hdd : StorageMediaType.Ssd;}finally{if (queryPtr != IntPtr.Zero)Marshal.FreeHGlobal(queryPtr);-if (resultPtr != IntPtr.Zero)Marshal.FreeHGlobal(resultPtr);}}catch{- return "Unknown";- }- }-- private static string DetectViaWMI(string driveLetter)- {- try- {- var partitions = WmiHelper.Query(- $"ASSOCIATORS OF {{Win32_LogicalDisk.DeviceID='{WmiHelper.EscapeWql(driveLetter.TrimEnd('\\'))}' }} WHERE AssocClass=Win32_LogicalDiskToPartition"- );-- foreach (var partition in partitions)- {- try- {- var diskDrives = WmiHelper.Query(- $"ASSOCIATORS OF {{Win32_DiskPartition.DeviceID='{WmiHelper.EscapeWql(partition["DeviceID"]?.ToString() ?? "")}'}} WHERE AssocClass=Win32_DiskDriveToDiskPartition"- );-- foreach (var disk in diskDrives)- {- try- {- var mediaType = WmiHelper- .GetString(disk, "MediaType", "")- .ToLowerInvariant();- var model = WmiHelper.GetString(disk, "Model", "").ToLowerInvariant();-- if (- mediaType.Contains("ssd")- || model.Contains("ssd")- || model.Contains("nvme")- || mediaType.Contains("fixed hard disk media")- )- {- var capabilities = disk["Capabilities"];- if (capabilities != null && capabilities is ushort[] caps)- if (caps.Contains((ushort)4))- return "SSD";-- if (model.Contains("ssd") || model.Contains("nvme"))- return "SSD";- }-- if (mediaType.Contains("removable"))- return "Unknown";- }- finally- {- disk.Dispose();- }- }- }- finally- {- partition.Dispose();- }- }- }- catch- {- // Ignore errors+ return StorageMediaType.Unknown;}-- return "Unknown";}- /// <summary>Determines whether the specified drive letter is the system drive (where Windows is installed).</summary>- /// <param name="driveLetter">The drive letter to check.</param>- /// <returns><see langword="true"/> if the drive is the system drive, otherwise <see langword="false"/>.</returns>public static bool IsSystemDrive(string driveLetter){var systemDrive = Path.GetPathRoot(Environment.SystemDirectory)?.TrimEnd('\\') ?? "C:";@@ -1187,313 +698,320 @@ public static class DiskHelperinternal static class DiskProvider{- public static DiskInfo Get()- {- try- {- static double ToGb(long bytes)- {- return Math.Round(bytes / (1024.0 * 1024.0 * 1024.0), 2);- }-- var physicalDisks = GetPhysicalDiskInfo();- var diskNumberToInfo = BuildDiskNumberMap(physicalDisks);-- // Batch: single WMI query maps all drive letters → PhysicalDiskInfo- var driveToDisk = BuildDriveToDiskMap(diskNumberToInfo);-- var volumes = DriveInfo- .GetDrives()- .Where(d => d.IsReady)- .Select(drive =>- {- var totalBytes = drive.TotalSize;- var freeBytes = drive.AvailableFreeSpace;- var usedBytes = totalBytes - freeBytes;-- var isSystemDrive = DiskHelper.IsSystemDrive(drive.Name);- var isRemovable = drive.DriveType == DriveType.Removable;-- var letter = drive.Name.TrimEnd('\\');- var driveLetterKey = letter.TrimEnd(':');-- PhysicalDiskInfo? diskInfo = null;- if (- !driveToDisk.TryGetValue(driveLetterKey, out diskInfo)- && diskNumberToInfo.Count > 0- )- {- diskInfo = GetDiskInfoForDriveFallback(drive.Name, diskNumberToInfo);- }+ private sealed record PhysicalDiskInfo(+ string DeviceID,+ int DiskNumber,+ string? Model,+ string? SerialNumber,+ StorageMediaType MediaType+ );- var mediaType = diskInfo?.MediaType ?? DiskHelper.DetectMediaType(drive.Name);+ // Physical topology changes ~never at runtime: resolve once, reuse everywhere.+ private static readonly Lazy<IReadOnlyList<PhysicalDiskInfo>> _cachedDisks = new(+ LoadPhysicalDisks,+ LazyThreadSafetyMode.PublicationOnly+ );+ private static readonly Lazy<IReadOnlyDictionary<string, PhysicalDiskInfo>> _cachedDriveMap =+ new(BuildDriveToDiskMap, LazyThreadSafetyMode.PublicationOnly);- return new DiskVolume- {- DriveLetter = letter,- IsSystemDrive = isSystemDrive,- DriveFormat = drive.DriveFormat,- DriveType = drive.DriveType.ToString(),- VolumeLabel = string.IsNullOrWhiteSpace(drive.VolumeLabel)- ? "Local Disk"- : drive.VolumeLabel,- TotalSizeGB = ToGb(totalBytes),- AvailableSizeGB = ToGb(freeBytes),- UsedSizeGB = ToGb(usedBytes),- UsedPercent =- totalBytes > 0 ? Math.Round(usedBytes * 100.0 / totalBytes, 1) : 0,- MediaType = mediaType,- IsRemovable = isRemovable,- SerialNumber = diskInfo?.SerialNumber,- Model = diskInfo?.Model,- };- })- .ToList();-- return new DiskInfo { Volumes = volumes };- }- catch- {- return DiskInfo.Unknown;- }+ /// <summary>Full scan (first load / manual refresh): WMI topology + live sizes.</summary>+ public static StorageInfo GetFull()+ {+ return BuildVolumes(resolveUnmapped: true);}/// <summary>- /// Batch-queries MSFT_Partition to map drive letters → disk numbers,- /// then resolves to PhysicalDiskInfo. Single WMI call for all drives.+ /// Live 2s-tick path: DriveInfo sizes + cached topology only. Never issues a new+ /// WMI query, so the Dashboard timer cannot cause a WMI storm./// </summary>- private static Dictionary<string, PhysicalDiskInfo> BuildDriveToDiskMap(- Dictionary<int, PhysicalDiskInfo> diskNumberMap- )+ public static StorageInfo GetFast(){- var map = new Dictionary<string, PhysicalDiskInfo>(StringComparer.OrdinalIgnoreCase);- if (diskNumberMap.Count == 0)- return map;+ return BuildVolumes(resolveUnmapped: false);+ }+ private static StorageInfo BuildVolumes(bool resolveUnmapped)+ {try{- var partitions = WmiHelper.Query(- "SELECT DriveLetter, DiskNumber FROM MSFT_Partition WHERE DriveLetter IS NOT NULL",- @"root\Microsoft\Windows\Storage"- );-- foreach (var partition in partitions)+ var driveMap = _cachedDriveMap.Value;+ var volumes = new List<StorageVolume>();+ foreach (var drive in DriveInfo.GetDrives()){+ StorageVolume? volume;try{- var driveLetter = WmiHelper.GetString(partition, "DriveLetter", "");- var diskNumber = WmiHelper.GetInt(partition, "DiskNumber", -1);-- if (- !string.IsNullOrEmpty(driveLetter)- && diskNumber >= 0- && diskNumberMap.TryGetValue(diskNumber, out var info)- )- map.TryAdd(driveLetter, info);+ if (!drive.IsReady)+ continue;+ volume = BuildVolume(drive, driveMap, resolveUnmapped);}- finally+ catch{- partition.Dispose();+ // One transient drive never fails the whole scan.+ continue;}+ if (volume is not null)+ volumes.Add(volume);}+ return new StorageInfo { Volumes = volumes };}catch{- // Storage namespace not available (older OS)+ return StorageInfo.Unknown;+ }+ }++ private static StorageVolume BuildVolume(+ DriveInfo drive,+ IReadOnlyDictionary<string, PhysicalDiskInfo> driveMap,+ bool resolveUnmapped+ )+ {+ var letter = drive.Name.TrimEnd('\\');+ var key = letter.TrimEnd(':');+ driveMap.TryGetValue(key, out var disk);++ if (disk is null && resolveUnmapped)+ disk = ResolveViaAssociators(letter);++ var media = disk?.MediaType ?? StorageMediaType.Unknown;+ if (media == StorageMediaType.Unknown && disk?.Model is { } model)+ media = InferFromModel(model);+ if (media is StorageMediaType.Unknown or StorageMediaType.Ssd)+ {+ // Seek-penalty ioctl is cheap and distinguishes SSD/HDD reliably;+ // NVMe comes from the topology/model path above, never from here.+ var probed = DiskMediaDetector.Detect(drive.Name);+ if (probed != StorageMediaType.Unknown)+ media =+ probed == StorageMediaType.Ssd && media == StorageMediaType.Unknown+ ? StorageMediaType.Ssd+ : media == StorageMediaType.Unknown ? probed+ : media;}- return map;+ return new StorageVolume+ {+ DriveLetter = letter,+ IsSystemDrive = DiskMediaDetector.IsSystemDrive(drive.Name),+ Label = string.IsNullOrWhiteSpace(drive.VolumeLabel) ? "Local Disk" : drive.VolumeLabel,+ FileSystem = string.IsNullOrWhiteSpace(drive.DriveFormat) ? null : drive.DriveFormat,+ TotalBytes = drive.TotalSize,+ FreeBytes = drive.AvailableFreeSpace,+ MediaType = media,+ Model = disk?.Model,+ IsRemovable = drive.DriveType == DriveType.Removable,+ };}- private static List<PhysicalDiskInfo> GetPhysicalDiskInfo()+ internal static StorageMediaType InferFromModel(string model){- var disks = GetViaMsftPhysicalDisk();- if (disks.Count > 0)- return disks;+ var lower = model.ToLowerInvariant();+ if (lower.Contains("nvme"))+ return StorageMediaType.Nvme;+ if (lower.Contains("ssd"))+ return StorageMediaType.Ssd;+ if (lower.Contains("hdd") || lower.Contains("hard disk"))+ return StorageMediaType.Hdd;+ return StorageMediaType.Unknown;+ }- return GetViaWin32DiskDrive();+ private static IReadOnlyList<PhysicalDiskInfo> LoadPhysicalDisks()+ {+ var disks = LoadViaMsftPhysicalDisk();+ return disks.Count > 0 ? disks : LoadViaWin32DiskDrive();}- private static List<PhysicalDiskInfo> GetViaMsftPhysicalDisk()+ private static List<PhysicalDiskInfo> LoadViaMsftPhysicalDisk(){- var disks = new List<PhysicalDiskInfo>();try{- var physicalDisks = WmiHelper.Query(- "SELECT DeviceId, FriendlyName, SerialNumber, MediaType, BusType FROM MSFT_PhysicalDisk",- @"root\Microsoft\Windows\Storage"- );-- foreach (var disk in physicalDisks)- {- try- {- var mediaTypeValue = WmiHelper.GetInt(disk, "MediaType");- var mediaType = mediaTypeValue switch+ return WmiHelper.Query(+ "SELECT DeviceId, FriendlyName, SerialNumber, MediaType, BusType FROM MSFT_PhysicalDisk",+ static items =>{- 3 => "HDD",- 4 => "SSD",- 5 => "SCM",- _ => "Unknown",- };-- disks.Add(- new PhysicalDiskInfo+ var list = new List<PhysicalDiskInfo>(items.Count);+ foreach (var disk in items){- DiskNumber = WmiHelper.GetString(disk, "DeviceId", "-1"),- Model = WmiHelper.GetString(disk, "FriendlyName"),- SerialNumber = WmiHelper.GetString(disk, "SerialNumber").Trim(),- MediaType = mediaType,- DeviceID = "",+ var mediaValue = WmiHelper.GetInt(disk, "MediaType") ?? 0;+ var busValue = WmiHelper.GetInt(disk, "BusType") ?? 0;+ var media = mediaValue switch+ {+ // MSFT_PhysicalDisk MediaType: 3 HDD, 4 SSD, 5 SCM.+ 3 => StorageMediaType.Hdd,+ 4 => busValue == 17 ? StorageMediaType.Nvme : StorageMediaType.Ssd,+ _ => StorageMediaType.Unknown,+ };+ list.Add(+ new PhysicalDiskInfo(+ "",+ TryParseDiskNumber(WmiHelper.GetString(disk, "DeviceId")),+ NullIfEmpty(WmiHelper.GetString(disk, "FriendlyName")),+ NullIfEmpty(WmiHelper.GetString(disk, "SerialNumber"))?.Trim(),+ media+ )+ );}- );- }- finally- {- disk.Dispose();- }- }+ return list;+ },+ @"root\Microsoft\Windows\Storage"+ ) ?? new List<PhysicalDiskInfo>();}catch{- // Storage namespace not available (older OS)+ return new List<PhysicalDiskInfo>();}-- return disks;}- private static List<PhysicalDiskInfo> GetViaWin32DiskDrive()+ private static List<PhysicalDiskInfo> LoadViaWin32DiskDrive(){- var disks = new List<PhysicalDiskInfo>();try{- var diskDrives = WmiHelper.Query(- "SELECT DeviceID, Model, SerialNumber, MediaType, Index FROM Win32_DiskDrive"- );- foreach (var disk in diskDrives)- {- try- {- disks.Add(- new PhysicalDiskInfo+ return WmiHelper.Query(+ "SELECT DeviceID, Model, Index FROM Win32_DiskDrive",+ static items =>+ {+ var list = new List<PhysicalDiskInfo>(items.Count);+ foreach (var disk in items){- DeviceID = WmiHelper.GetString(disk, "DeviceID"),- DiskNumber = WmiHelper.GetInt(disk, "Index").ToString(),- Model = WmiHelper.GetString(disk, "Model"),- SerialNumber = WmiHelper.GetString(disk, "SerialNumber").Trim(),- MediaType = "",+ var model = NullIfEmpty(WmiHelper.GetString(disk, "Model"));+ list.Add(+ new PhysicalDiskInfo(+ WmiHelper.GetString(disk, "DeviceID") ?? "",+ WmiHelper.GetInt(disk, "Index") ?? -1,+ model,+ null,+ model is not null+ ? InferFromModel(model)+ : StorageMediaType.Unknown+ )+ );}- );- }- finally- {- disk.Dispose();- }- }+ return list;+ }+ ) ?? new List<PhysicalDiskInfo>();}catch{- // Ignore errors+ return new List<PhysicalDiskInfo>();}-- return disks;}- private static Dictionary<int, PhysicalDiskInfo> BuildDiskNumberMap(- List<PhysicalDiskInfo> disks- )+ private static IReadOnlyDictionary<string, PhysicalDiskInfo> BuildDriveToDiskMap(){- var map = new Dictionary<int, PhysicalDiskInfo>();- foreach (var disk in disks)- if (int.TryParse(disk.DiskNumber, out var num))- map.TryAdd(num, disk);-+ var map = new Dictionary<string, PhysicalDiskInfo>(StringComparer.OrdinalIgnoreCase);+ try+ {+ var byNumber = _cachedDisks+ .Value.Where(static d => d.DiskNumber >= 0)+ .ToDictionary(static d => d.DiskNumber);+ if (byNumber.Count == 0)+ return map;++ var rows =+ WmiHelper.Query(+ "SELECT DriveLetter, DiskNumber FROM MSFT_Partition WHERE DriveLetter IS NOT NULL",+ static items =>+ {+ var list = new List<(string Letter, int Disk)>(items.Count);+ foreach (var p in items)+ {+ var letter = WmiHelper.GetString(p, "DriveLetter");+ var number = WmiHelper.GetInt(p, "DiskNumber");+ if (!string.IsNullOrEmpty(letter) && number.HasValue)+ list.Add((letter!, number.Value));+ }+ return list;+ },+ @"root\Microsoft\Windows\Storage"+ ) ?? new List<(string, int)>();++ foreach (var (letter, number) in rows)+ if (byNumber.TryGetValue(number, out var info))+ map.TryAdd(letter.TrimEnd(':'), info);+ }+ catch+ {+ // Storage namespace missing on older OS: callers fall back per-drive.+ }return map;}- /// <summary>- /// Fallback for drives not resolved by the batched MSFT_Partition query.- /// Uses classic ASSOCIATORS path (slower, per-drive).- /// </summary>- private static PhysicalDiskInfo? GetDiskInfoForDriveFallback(- string driveLetter,- Dictionary<int, PhysicalDiskInfo> diskNumberMap- )+ /// <summary>Slow per-drive ASSOCIATORS fallback, used only by full scans.</summary>+ private static PhysicalDiskInfo? ResolveViaAssociators(string letter){try{- var letter = driveLetter.TrimEnd('\\');-- var classicPartitions = WmiHelper.Query(- $"ASSOCIATORS OF {{Win32_LogicalDisk.DeviceID='{WmiHelper.EscapeWql(letter)}'}} WHERE AssocClass=Win32_LogicalDiskToPartition"+ var byNumber = _cachedDisks+ .Value.Where(static d => d.DiskNumber >= 0)+ .ToDictionary(static d => d.DiskNumber);+ var partitions = WmiHelper.Query(+ $"ASSOCIATORS OF {{Win32_LogicalDisk.DeviceID='{WmiHelper.EscapeWql(letter)}'}} WHERE AssocClass=Win32_LogicalDiskToPartition",+ static items =>+ {+ var list = new List<string>(items.Count);+ foreach (var p in items)+ if (WmiHelper.GetString(p, "DeviceID") is { } id)+ list.Add(id);+ return list;+ });-- foreach (var partition in classicPartitions)+ foreach (var partitionId in partitions ?? new List<string>()){- try- {- var diskDrives = WmiHelper.Query(- $"ASSOCIATORS OF {{Win32_DiskPartition.DeviceID='{WmiHelper.EscapeWql(partition["DeviceID"]?.ToString() ?? "")}'}} WHERE AssocClass=Win32_DiskDriveToDiskPartition"- );-- foreach (var disk in diskDrives)+ var indexes = WmiHelper.Query(+ $"ASSOCIATORS OF {{Win32_DiskPartition.DeviceID='{WmiHelper.EscapeWql(partitionId)}'}} WHERE AssocClass=Win32_DiskDriveToDiskPartition",+ static items =>{- try- {- var index = WmiHelper.GetInt(disk, "Index", -1);- if (index >= 0 && diskNumberMap.TryGetValue(index, out var info))- return info;-- var deviceId = WmiHelper.GetString(disk, "DeviceID");- foreach (var entry in diskNumberMap.Values)- if (entry.DeviceID == deviceId)- return entry;- }- finally- {- disk.Dispose();- }+ var list = new List<(int Index, string Device)>(items.Count);+ foreach (var d in items)+ list.Add(+ (+ WmiHelper.GetInt(d, "Index") ?? -1,+ WmiHelper.GetString(d, "DeviceID") ?? ""+ )+ );+ return list;}- }- finally+ );+ foreach (var (index, device) in indexes ?? new List<(int, string)>()){- partition.Dispose();+ if (index >= 0 && byNumber.TryGetValue(index, out var info))+ return info;+ foreach (var entry in _cachedDisks.Value)+ if (entry.DeviceID == device)+ return entry;}}}catch{- // Ignore errors+ // Ignore: media falls back to probe/Unknown.}- if (diskNumberMap.Count == 1)- return diskNumberMap.Values.First();-+ if (_cachedDisks.Value.Count == 1)+ return _cachedDisks.Value[0];return null;}- private class PhysicalDiskInfo+ private static int TryParseDiskNumber(string? text)+ {+ return int.TryParse(text, out var n) ? n : -1;+ }++ private static string? NullIfEmpty(string? text){- public string DeviceID { get; set; } = string.Empty;- public string DiskNumber { get; set; } = string.Empty;- public string Model { get; set; } = string.Empty;- public string SerialNumber { get; set; } = string.Empty;- public string MediaType { get; set; } = string.Empty;+ return string.IsNullOrWhiteSpace(text) ? null : text.Trim();}}// ============================================================================-// DXGI INTEROP (COM P/Invoke)+// DXGI INTEROP (COM P/Invoke, unchanged behavior)// ============================================================================internal static class DxgiHelper{- // DXGI_ADAPTER_FLAG valuespublic const uint DXGI_ADAPTER_FLAG_SOFTWARE = 2;- // Microsoft Basic Render Driver identifiersprivate const uint MICROSOFT_VENDOR_ID = 0x1414;-private const uint BASIC_RENDER_DEVICE_ID = 0x8C;private static readonly Guid IID_IDXGIFactory1 = new("770aae78-f26f-4dba-a829-253c83d1b387");@@ -1514,8 +1032,6 @@ internal static class DxgiHelper{if ((desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE) != 0)return true;-- // Microsoft Basic Render Driverreturn desc.VendorId == MICROSOFT_VENDOR_ID && desc.DeviceId == BASIC_RENDER_DEVICE_ID;}@@ -1524,40 +1040,28 @@ internal static class DxgiHelper[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]public interface IDXGIFactory1{- // IDXGIObject (4 methods)void SetPrivateData([In] ref Guid Name, uint DataSize, IntPtr pData);-void SetPrivateDataInterface([In] ref Guid Name,[MarshalAs(UnmanagedType.IUnknown)] object pUnknown);-void GetPrivateData([In] ref Guid Name, ref uint pDataSize, IntPtr pData);-void GetParent([In] ref Guid riid, [MarshalAs(UnmanagedType.IUnknown)] out object ppParent);-- // IDXGIFactory (4 methods)void EnumAdapters(uint Adapter, [MarshalAs(UnmanagedType.IUnknown)] out object ppAdapter);-void MakeWindowAssociation(IntPtr WindowHandle, uint Flags);-void GetWindowAssociation(out IntPtr pWindowHandle);-void CreateSwapChain([MarshalAs(UnmanagedType.IUnknown)] object pDevice,IntPtr pDesc,[MarshalAs(UnmanagedType.IUnknown)] out object ppSwapChain);-void CreateSoftwareAdapter(IntPtr Module,[MarshalAs(UnmanagedType.IUnknown)] out object ppAdapter);- // IDXGIFactory1 (2 methods)[PreserveSig]int EnumAdapters1(uint Adapter, out IDXGIAdapter1? ppAdapter);-bool IsCurrent();}@@ -1566,26 +1070,16 @@ internal static class DxgiHelper[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]public interface IDXGIAdapter1{- // IDXGIObject (4 methods)void SetPrivateData([In] ref Guid Name, uint DataSize, IntPtr pData);-void SetPrivateDataInterface([In] ref Guid Name,[MarshalAs(UnmanagedType.IUnknown)] object pUnknown);-void GetPrivateData([In] ref Guid Name, ref uint pDataSize, IntPtr pData);-void GetParent([In] ref Guid riid, [MarshalAs(UnmanagedType.IUnknown)] out object ppParent);-- // IDXGIAdapter (3 methods)void EnumOutputs(uint Output, [MarshalAs(UnmanagedType.IUnknown)] out object ppOutput);-void GetDesc(out DXGI_ADAPTER_DESC pDesc);-int CheckInterfaceSupport([In] ref Guid InterfaceName, out long pUMDVersion);-- // IDXGIAdapter1 (1 method)void GetDesc1(out DXGI_ADAPTER_DESC1 pDesc);}@@ -1594,7 +1088,6 @@ internal static class DxgiHelper{[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)]public string Description;-public uint VendorId;public uint DeviceId;public uint SubSysId;@@ -1610,7 +1103,6 @@ internal static class DxgiHelper{[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)]public string Description;-public uint VendorId;public uint DeviceId;public uint SubSysId;@@ -1619,20 +1111,17 @@ internal static class DxgiHelperpublic nuint DedicatedSystemMemory;public nuint SharedSystemMemory;public long AdapterLuid;- public uint Flags; // DXGI_ADAPTER_FLAG+ public uint Flags;}}// ============================================================================-// GPU PROVIDER (DXGI + minimal WMI)+// GPU PROVIDER (DXGI + one WMI pass for driver details)// ============================================================================internal static class GpuProvider{- /// <summary>- /// Enumerates all physical GPUs using DXGI, with WMI fallback for driver info.- /// The returned list is ordered by DXGI adapter index (index 0 = primary display adapter).- /// </summary>+ /// <summary>Physical GPUs ordered by DXGI index; empty when nothing usable found.</summary>public static IReadOnlyList<GpuInfo> GetAll(){try@@ -1641,16 +1130,13 @@ internal static class GpuProvider}catch{- // DXGI unavailable (e.g., old OS or headless server), so fall back to WMIreturn GetAllViaWmi();}}/// <summary>- /// Selects the primary performance GPU from the list.- /// On hybrid laptops DXGI index 0 is often the iGPU (Intel), so we- /// pick by highest VRAM first, then vendor priority (NVIDIA > AMD > Intel).- /// Intel is only considered primary when it is the sole GPU.+ /// Primary = most VRAM, then vendor priority (Nvidia > Amd > Intel).+ /// On hybrid laptops DXGI index 0 is often the iGPU, so index order misleads./// </summary>public static GpuInfo? GetPrimary(IReadOnlyList<GpuInfo> gpus){@@ -1667,32 +1153,29 @@ internal static class GpuProviderbest = g;continue;}-- var memG = g.MemoryMB ?? 0;- var memBest = best.MemoryMB ?? 0;+ var memG = g.VramMB ?? 0;+ var memBest = best.VramMB ?? 0;if (memG != memBest){if (memG > memBest)best = g;continue;}-- var gScore =- g.Vendor == GpuVendor.NVIDIA ? 2- : g.Vendor == GpuVendor.AMD ? 1- : 0;- var bestScore =- best.Vendor == GpuVendor.NVIDIA ? 2- : best.Vendor == GpuVendor.AMD ? 1- : 0;- if (gScore > bestScore)+ if (VendorScore(g.Vendor) > VendorScore(best.Vendor))best = g;}-return best;}- // ── DXGI path ──────────────────────────────────────────────────────────+ internal static int VendorScore(GpuVendor vendor)+ {+ return vendor switch+ {+ GpuVendor.Nvidia => 2,+ GpuVendor.Amd => 1,+ _ => 0,+ };+ }private static IReadOnlyList<GpuInfo> GetAllViaDxgi(){@@ -1702,39 +1185,31 @@ internal static class GpuProviderfactory = DxgiHelper.CreateFactory();var wmiLookup = BuildWmiLookup();var gpus = new List<GpuInfo>();-for (uint i = 0; ; i++){var hr = factory.EnumAdapters1(i, out var adapter);if (hr != 0 || adapter == null)break;-try{adapter.GetDesc1(out var desc);-if (DxgiHelper.IsSoftwareAdapter(desc))continue;-- var name = desc.Description?.Trim() ?? "";+ var name = desc.Description?.Trim();if (string.IsNullOrWhiteSpace(name) || IsVirtualAdapter(name))continue;-- var vendor = DetectGpuVendorById(desc.VendorId);var memoryMB = (int)((long)desc.DedicatedVideoMemory / (1024 * 1024));-- var wmiMatch = FindWmiMatch(name, desc.VendorId, desc.DeviceId, wmiLookup);-+ var match = FindWmiMatch(name, desc.VendorId, desc.DeviceId, wmiLookup);gpus.Add(new GpuInfo{Name = name,- DriverVersion =- wmiMatch?.DriverVersion ?? Loc.Instance["Common.Unknown"],- Vendor = vendor,- MemoryMB = memoryMB > 0 ? memoryMB : null,- DeviceId = wmiMatch?.DeviceId,- PnpDeviceId = wmiMatch?.PnpDeviceId,+ Vendor = DetectVendorById(desc.VendorId),+ VramMB = memoryMB > 0 ? memoryMB : null,+ DriverVersion = match?.DriverVersion,+ DriverDate = match?.DriverDate,+ DeviceId = match?.DeviceId,+ PnpDeviceId = match?.PnpDeviceId,});}@@ -1743,8 +1218,7 @@ internal static class GpuProviderMarshal.ReleaseComObject(adapter);}}-- return gpus.Count > 0 ? gpus : [GpuInfo.Unknown];+ return gpus;}finally{@@ -1753,161 +1227,124 @@ internal static class GpuProvider}}- // ── WMI fallback path ──────────────────────────────────────────────────-private static IReadOnlyList<GpuInfo> GetAllViaWmi(){- var gpus = new List<GpuInfo>();- var controllers = WmiHelper.Query(- "SELECT Name, DriverVersion, DeviceID, PNPDeviceID, AdapterRAM FROM Win32_VideoController"- );-- foreach (var controller in controllers)+ try{- try- {- var name = WmiHelper.GetString(controller, "Name", "");- if (string.IsNullOrWhiteSpace(name) || IsVirtualAdapter(name))- continue;-- var driver = WmiHelper.GetString(controller, "DriverVersion");- var deviceId = WmiHelper.GetString(controller, "DeviceID");- var pnpId = WmiHelper.GetString(controller, "PNPDeviceID");- var adapterRam = WmiHelper.GetLong(controller, "AdapterRAM");-- int? memoryMB = adapterRam > 0 ? (int)(adapterRam / (1024 * 1024)) : null;- var vendor = DetectGpuVendor(name, pnpId);-- gpus.Add(- new GpuInfo+ return WmiHelper.Query(+ "SELECT Name, DriverVersion, DriverDate, DeviceID, PNPDeviceID, AdapterRAM FROM Win32_VideoController",+ static items =>{- Name = name,- DriverVersion = driver,- Vendor = vendor,- MemoryMB = memoryMB,- DeviceId = deviceId,- PnpDeviceId = pnpId,+ var list = new List<GpuInfo>(items.Count);+ foreach (var c in items)+ {+ var name = WmiHelper.GetString(c, "Name");+ if (string.IsNullOrWhiteSpace(name) || IsVirtualAdapter(name!))+ continue;+ var adapterRam = WmiHelper.GetLong(c, "AdapterRAM");+ var pnpId = WmiHelper.GetString(c, "PNPDeviceID");+ list.Add(+ new GpuInfo+ {+ Name = name,+ Vendor = DetectVendor(name!, pnpId),+ VramMB = adapterRam is > 0+ ? (int)(adapterRam.Value / (1024 * 1024))+ : null,+ DriverVersion = WmiHelper.GetString(c, "DriverVersion"),+ DriverDate = WmiHelper.GetWmiDate(c, "DriverDate"),+ DeviceId = WmiHelper.GetString(c, "DeviceID"),+ PnpDeviceId = pnpId,+ }+ );+ }+ return (IReadOnlyList<GpuInfo>)list;}- );- }- finally- {- controller.Dispose();- }+ ) ?? [];+ }+ catch+ {+ return [];}-- return gpus.Count > 0 ? gpus : [GpuInfo.Unknown];}- /// <summary>- /// Builds a lightweight WMI lookup table (Name, DriverVersion, DeviceID, PNPDeviceID)- /// for cross-referencing with DXGI adapters.- /// </summary>private static List<WmiGpuEntry> BuildWmiLookup(){- var entries = new List<WmiGpuEntry>();try{- var controllers = WmiHelper.Query(- "SELECT Name, DriverVersion, DeviceID, PNPDeviceID FROM Win32_VideoController"- );-- foreach (var controller in controllers)- {- try- {- var name = WmiHelper.GetString(controller, "Name", "");- var driver = WmiHelper.GetString(controller, "DriverVersion");- var deviceId = WmiHelper.GetString(controller, "DeviceID");- var pnpId = WmiHelper.GetString(controller, "PNPDeviceID");-- ParsePnpIds(pnpId, out var vendorId, out var hardwareDeviceId);-- entries.Add(- new WmiGpuEntry(name, driver, deviceId, pnpId, vendorId, hardwareDeviceId)- );- }- finally- {- controller.Dispose();- }- }+ return WmiHelper.Query(+ "SELECT Name, DriverVersion, DriverDate, DeviceID, PNPDeviceID FROM Win32_VideoController",+ static items =>+ {+ var list = new List<WmiGpuEntry>(items.Count);+ foreach (var c in items)+ {+ var pnpId = WmiHelper.GetString(c, "PNPDeviceID");+ ParsePnpIds(pnpId, out var vendorId, out var deviceId);+ list.Add(+ new WmiGpuEntry(+ WmiHelper.GetString(c, "Name"),+ WmiHelper.GetString(c, "DriverVersion"),+ WmiHelper.GetWmiDate(c, "DriverDate"),+ WmiHelper.GetString(c, "DeviceID"),+ pnpId,+ vendorId,+ deviceId+ )+ );+ }+ return list;+ }+ ) ?? new List<WmiGpuEntry>();}catch{- // WMI unavailable+ return new List<WmiGpuEntry>();}-- return entries;}- /// <summary>- /// Parses PNP DeviceID string like "PCI\VEN_10DE&DEV_2684&SUBSYS_..." to extract VendorId and DeviceId.- /// </summary>- private static void ParsePnpIds(string? pnpId, out uint vendorId, out uint hardwareDeviceId)+ private static void ParsePnpIds(string? pnpId, out uint vendorId, out uint deviceId){vendorId = 0;- hardwareDeviceId = 0;+ deviceId = 0;if (string.IsNullOrWhiteSpace(pnpId))return;-var upper = pnpId.ToUpperInvariant();-var venIdx = upper.IndexOf("VEN_", StringComparison.Ordinal);- if (venIdx >= 0 && venIdx + 8 <= upper.Length)- if (- uint.TryParse(- upper.Substring(venIdx + 4, 4),- NumberStyles.HexNumber,- null,- out var v- )- )- vendorId = v;-+ if (venIdx >= 0 && venIdx + 8 <= upper.Length)+ uint.TryParse(+ upper.Substring(venIdx + 4, 4),+ NumberStyles.HexNumber,+ null,+ out vendorId+ );var devIdx = upper.IndexOf("DEV_", StringComparison.Ordinal);if (devIdx >= 0 && devIdx + 8 <= upper.Length)- if (- uint.TryParse(- upper.Substring(devIdx + 4, 4),- NumberStyles.HexNumber,- null,- out var d- )- )- hardwareDeviceId = d;+ uint.TryParse(+ upper.Substring(devIdx + 4, 4),+ NumberStyles.HexNumber,+ null,+ out deviceId+ );}- /// <summary>- /// Matches a DXGI adapter to its WMI entry.- /// Priority: VendorId+DeviceId match > name substring match.- /// </summary>private static WmiGpuEntry? FindWmiMatch(string dxgiName,uint dxgiVendorId,uint dxgiDeviceId,- List<WmiGpuEntry> wmiEntries+ List<WmiGpuEntry> entries){- // First pass: match by hardware IDs (most reliable)- foreach (var entry in wmiEntries)- if (entry.VendorId == dxgiVendorId && entry.HardwareDeviceId == dxgiDeviceId)- return entry;-- // Second pass: match by name substring- var dxgiNameLower = dxgiName.ToLowerInvariant();- foreach (var entry in wmiEntries)- if (- !string.IsNullOrEmpty(entry.Name)- && dxgiNameLower.Contains(entry.Name.ToLowerInvariant())- )- return entry;-+ foreach (var e in entries)+ if (e.VendorId == dxgiVendorId && e.HardwareDeviceId == dxgiDeviceId)+ return e;+ var lower = dxgiName.ToLowerInvariant();+ foreach (var e in entries)+ if (!string.IsNullOrEmpty(e.Name) && lower.Contains(e.Name.ToLowerInvariant()))+ return e;return null;}- // ── Shared helpers ─────────────────────────────────────────────────────-private static bool IsVirtualAdapter(string name){var lower = name.ToLowerInvariant();@@ -1916,28 +1353,21 @@ internal static class GpuProvider|| lower.Contains("virtual");}- /// <summary>- /// Detects GPU vendor from DXGI VendorId (PCI Vendor ID).- /// </summary>- private static GpuVendor DetectGpuVendorById(uint vendorId)+ internal static GpuVendor DetectVendorById(uint vendorId){return vendorId switch{- 0x10DE => GpuVendor.NVIDIA,- 0x1002 => GpuVendor.AMD,+ 0x10DE => GpuVendor.Nvidia,+ 0x1002 => GpuVendor.Amd,0x8086 => GpuVendor.Intel,_ => GpuVendor.Unknown,};}- /// <summary>- /// Detects GPU vendor from name and PNP DeviceID strings (WMI fallback path).- /// </summary>- private static GpuVendor DetectGpuVendor(string name, string? pnpId)+ internal static GpuVendor DetectVendor(string name, string? pnpId){var nameLower = name.ToLowerInvariant();var pnpLower = pnpId?.ToLowerInvariant() ?? "";-if (nameLower.Contains("nvidia")|| nameLower.Contains("geforce")@@ -1945,16 +1375,13 @@ internal static class GpuProvider|| nameLower.Contains("tesla")|| pnpLower.Contains("ven_10de"))- return GpuVendor.NVIDIA;-+ return GpuVendor.Nvidia;if (nameLower.Contains("amd")|| nameLower.Contains("radeon")- || nameLower.Contains("ryzen")|| pnpLower.Contains("ven_1002"))- return GpuVendor.AMD;-+ return GpuVendor.Amd;if (nameLower.Contains("intel")|| nameLower.Contains("iris")@@ -1962,15 +1389,13 @@ internal static class GpuProvider|| pnpLower.Contains("ven_8086"))return GpuVendor.Intel;-return GpuVendor.Unknown;}- // ── WMI lookup for DXGI matching ───────────────────────────────────────-private sealed record WmiGpuEntry(- string Name,- string DriverVersion,+ string? Name,+ string? DriverVersion,+ DateTime? DriverDate,string? DeviceId,string? PnpDeviceId,uint VendorId,@@ -1978,20 +1403,30 @@ internal static class GpuProvider);}-internal static class OsProvider+// ============================================================================+// WINDOWS / FIRMWARE / SECURITY / POWER / RUNTIME PROVIDERS+// ============================================================================++internal static class WindowsProvider{- /// <summary>- /// Gets OS info using Registry (fast) + targeted WMI (only for LastBootUpTime).- /// </summary>- public static OsInfo Get()+ private static readonly Lazy<WindowsInfo> _cached = new(+ Load,+ LazyThreadSafetyMode.PublicationOnly+ );++ public static WindowsInfo Get()+ {+ return _cached.Value;+ }++ private static WindowsInfo Load(){try{- // ── Fast path: Registry ──────────────────────────────────────- var buildNumber = Loc.Instance["Common.Unknown"];- var edition = Loc.Instance["Common.Unknown"];- var installDate = Loc.Instance["Common.Unknown"];- var displayVersion = "";+ int? build = null;+ string? displayVersion = null;+ var edition = WindowsEdition.Unknown;+ DateTime? installDate = null;using (var ntKey = Registry.LocalMachine.OpenSubKey(@@ -2001,423 +1436,606 @@ internal static class OsProvider{if (ntKey != null){- buildNumber =+ var buildText =ntKey.GetValue("CurrentBuildNumber")?.ToString()- ?? ntKey.GetValue("CurrentBuild")?.ToString()- ?? buildNumber;- edition = ntKey.GetValue("EditionID")?.ToString() ?? edition;- displayVersion = ntKey.GetValue("DisplayVersion")?.ToString() ?? "";-- // Install date from Registry (Unix timestamp)- if (- ntKey.GetValue("InstallDate") is int installTimestamp- && installTimestamp > 0- )- {- var installDateTime = DateTimeOffset.FromUnixTimeSeconds(installTimestamp);- installDate = installDateTime.LocalDateTime.ToString("yyyy-MM-dd");- }+ ?? ntKey.GetValue("CurrentBuild")?.ToString();+ if (int.TryParse(buildText?.Split('.')[0], out var parsed))+ build = parsed;+ displayVersion = NullIfEmpty(ntKey.GetValue("DisplayVersion")?.ToString());+ edition = MapEdition(ntKey.GetValue("EditionID")?.ToString());+ installDate = ParseInstallDate(ntKey.GetValue("InstallDate"));}}- // Determine Windows version from build number- var version = MapWindowsVersion(buildNumber);- var architecture = Environment.Is64BitOperatingSystem ? "64-bit" : "32-bit";- var deviceType = GetDeviceType();- var name = $"Windows {version}";-- // ── Targeted WMI: only for LastBootUpTime ────────────────────- var lastBoot = Loc.Instance["Common.Unknown"];- var os = WmiHelper.GetFirst("SELECT LastBootUpTime FROM Win32_OperatingSystem");- if (os != null)- {- try- {- lastBoot = FormatWmiDateTime(WmiHelper.GetString(os, "LastBootUpTime", ""));- }- finally- {- os.Dispose();- }- }+ var lastBoot = WmiHelper.QueryFirst(+ "SELECT LastBootUpTime FROM Win32_OperatingSystem",+ static mo => WmiHelper.GetWmiDate(mo, "LastBootUpTime")+ );- return new OsInfo+ return new WindowsInfo{- Name = name,- Version = version,- BuildNumber = buildNumber,+ BuildNumber = build,+ DisplayVersion = displayVersion,Edition = edition,- Architecture = architecture,- DeviceType = deviceType,+ Architecture = CpuProvider.MapArchitecture(),+ DeviceKind = DetectDeviceKind(),InstallDate = installDate,- LastBootUpTime = lastBoot,+ LastBootTime = lastBoot,};}catch{- return OsInfo.Unknown;+ return WindowsInfo.Unknown;}}- private static string MapWindowsVersion(string build)+ internal static WindowsEdition MapEdition(string? editionId){- if (!int.TryParse(build, out var buildNum))- return "Unknown";-- // Rough mapping based on build number ranges- return buildNum switch+ if (string.IsNullOrWhiteSpace(editionId))+ return WindowsEdition.Unknown;+ var id = editionId.Trim();+ if (id.StartsWith("Server", StringComparison.OrdinalIgnoreCase))+ return WindowsEdition.Server;+ if (id.StartsWith("Core", StringComparison.OrdinalIgnoreCase))+ return WindowsEdition.Home;+ return id switch{- >= 22000 => "11",- >= 10240 => "10",- >= 9600 => "8.1",- >= 9200 => "8",- >= 7600 => "7",- _ => "Unknown",+ "Home" => WindowsEdition.Home,+ "Professional" => WindowsEdition.Pro,+ "ProfessionalEducation" => WindowsEdition.Education,+ "Education" => WindowsEdition.Education,+ "Enterprise" => WindowsEdition.Enterprise,+ _ when id.Contains("Education", StringComparison.OrdinalIgnoreCase) =>+ WindowsEdition.Education,+ _ when id.Contains("Enterprise", StringComparison.OrdinalIgnoreCase) =>+ WindowsEdition.Enterprise,+ _ when id.Contains("Pro", StringComparison.OrdinalIgnoreCase) => WindowsEdition.Pro,+ _ => WindowsEdition.Unknown,};}- private static DeviceKind GetDeviceType()+ private static DateTime? ParseInstallDate(object? value){- var chassis = WmiHelper.GetFirst("SELECT ChassisTypes FROM Win32_SystemEnclosure");- if (chassis == null)- return DeviceKind.Unknown;-try{- return chassis["ChassisTypes"] is ushort[] { Length: > 0 } types- ? MapChassisType(types)- : DeviceKind.Unknown;+ long seconds = value switch+ {+ int i => i,+ uint u => u,+ long l => l,+ _ => 0,+ };+ if (seconds <= 0)+ return null;+ return DateTimeOffset.FromUnixTimeSeconds(seconds).LocalDateTime;}catch{- return DeviceKind.Unknown;+ return null;}- finally+ }++ private static DeviceKind DetectDeviceKind()+ {+ try{- chassis.Dispose();+ return WmiHelper.QueryFirst(+ "SELECT ChassisTypes FROM Win32_SystemEnclosure",+ static mo =>+ mo["ChassisTypes"] is ushort[] { Length: > 0 } types+ ? MapChassisType(types)+ : DeviceKind.Unknown+ );+ }+ catch+ {+ return DeviceKind.Unknown;}}- private static DeviceKind MapChassisType(IEnumerable<ushort> types)+ internal static DeviceKind MapChassisType(IEnumerable<ushort> types){foreach (var type in types)switch (type){case 8 or 9 or 10 or 11 or 14 or 30 or 31 or 32:return DeviceKind.Laptop;-- case >= 1- and <= 7- or 12- or 13- or >= 15- and <= 29- or >= 33- and <= 36:+ case >= 1 and <= 7 or 12 or 13 or >= 15 and <= 29 or >= 33 and <= 36:return DeviceKind.Desktop;}-return DeviceKind.Unknown;}- private static string FormatWmiDateTime(string wmiDate)+ private static string? NullIfEmpty(string? text){- if (wmiDate.Length < 12)- return "Unknown";- return $"{wmiDate[..4]}-{wmiDate.Substring(4, 2)}-{wmiDate.Substring(6, 2)} {wmiDate.Substring(8, 2)}:{wmiDate.Substring(10, 2)}";+ return string.IsNullOrWhiteSpace(text) ? null : text.Trim();}}-internal static class BiosProvider+internal static class FirmwareProvider{- public static BiosInfo Get()+ private static readonly Lazy<FirmwareInfo> _cached = new(+ Load,+ LazyThreadSafetyMode.PublicationOnly+ );++ public static FirmwareInfo Get()+ {+ return _cached.Value;+ }++ private static FirmwareInfo Load(){try{- var bios = WmiHelper.GetFirst(- "SELECT Manufacturer, BIOSVersion, SMBIOSBIOSVersion, SerialNumber, ReleaseDate FROM Win32_BIOS"+ var bios = WmiHelper.QueryFirst(+ "SELECT Manufacturer, BIOSVersion, SMBIOSBIOSVersion, ReleaseDate FROM Win32_BIOS",+ static mo => new+ {+ Manufacturer = WmiHelper.GetString(mo, "Manufacturer"),+ Version = WmiHelper.GetString(mo, "BIOSVersion"),+ Smbios = WmiHelper.GetString(mo, "SMBIOSBIOSVersion"),+ Date = WmiHelper.GetWmiDate(mo, "ReleaseDate"),+ }+ );+ var board = WmiHelper.QueryFirst(+ "SELECT Manufacturer, Product FROM Win32_BaseBoard",+ static mo => new+ {+ Manufacturer = WmiHelper.GetString(mo, "Manufacturer"),+ Product = WmiHelper.GetString(mo, "Product"),+ });- if (bios == null)- return BiosInfo.Unknown;- try+ string? motherboard = null;+ if (board is not null){- var manufacturer = WmiHelper.GetString(bios, "Manufacturer");- var version = WmiHelper.GetString(bios, "BIOSVersion");- var smbiosVersion = WmiHelper.GetString(bios, "SMBIOSBIOSVersion");- var serialNumber = WmiHelper.GetString(bios, "SerialNumber");- var releaseDate = FormatWmiDate(WmiHelper.GetString(bios, "ReleaseDate", ""));-- return new BiosInfo+ var maker = board.Manufacturer?.Trim();+ var product = board.Product?.Trim();+ motherboard = (maker, product) switch{- Manufacturer = manufacturer,- Version = version,- ReleaseDate = releaseDate,- SmbiosVersion = smbiosVersion,- SerialNumber = serialNumber,+ (null, null) => null,+ (null, { } p) => p,+ ({ } m, null) => m,+ ({ } m, { } p) => string.Equals(m, p, StringComparison.OrdinalIgnoreCase)+ ? m+ : $"{m} {p}",};}- finally++ return new FirmwareInfo{- bios.Dispose();- }+ Mode = NativeFirmware.GetMode(),+ BiosVersion = bios?.Version,+ BiosManufacturer = bios?.Manufacturer,+ BiosReleaseDate = bios?.Date,+ SmbiosVersion = bios?.Smbios,+ Motherboard = motherboard,+ };+ }+ catch+ {+ return FirmwareInfo.Unknown;+ }+ }+}++internal static class SecurityProvider+{+ // VBS/HVCI source priority: Win32_DeviceGuard WMI (authoritative runtime+ // state, same data msinfo32 shows) first, registry policy second. A missing+ // registry value means "never configured", not "off", so registry alone+ // cannot distinguish Disabled from Unknown.+ private const string DeviceGuardNamespace = @"root\Microsoft\Windows\DeviceGuard";++ // SecurityServices id 2 == Memory integrity (HVCI). Full table: 0 none,+ // 1 Credential Guard, 2 HVCI, 3 Secure Launch, 4 SMM measurement.+ private const int HypervisorEnforcedCodeIntegrityId = 2;++ public static SecurityInfo Get()+ {+ try+ {+ var firmwareMode = NativeFirmware.GetMode();+ var guard = ReadDeviceGuard();+ return new SecurityInfo+ {+ SecureBoot = ReadSecureBoot(firmwareMode),+ VirtualizationBasedSecurity = guard?.Status is { } status+ ? MapVbsStatus(status, firmwareMode)+ : ReadDwordState(+ @"SYSTEM\CurrentControlSet\Control\DeviceGuard",+ "EnableVirtualizationBasedSecurity"+ ),+ MemoryIntegrity = guard is not null+ ? MapMemoryIntegrity(guard.Running)+ : ReadDwordState(+ @"SYSTEM\CurrentControlSet\Control\DeviceGuard\Scenarios\HypervisorEnforcedCodeIntegrity",+ "Enabled"+ ),+ };+ }+ catch+ {+ return SecurityInfo.Unknown;+ }+ }++ private sealed record DeviceGuardState(int? Status, List<int> Running);++ private static DeviceGuardState? ReadDeviceGuard()+ {+ // May throw without elevation or on old OS: caller maps that to Unknown.+ return WmiHelper.QueryFirst(+ "SELECT VirtualizationBasedSecurityStatus, SecurityServicesRunning FROM Win32_DeviceGuard",+ static mo => new DeviceGuardState(+ WmiHelper.GetInt(mo, "VirtualizationBasedSecurityStatus"),+ ToServiceIds(mo["SecurityServicesRunning"])+ ),+ DeviceGuardNamespace+ );+ }++ /// <summary>+ /// VirtualizationBasedSecurityStatus: 0 not enabled, 1 enabled but not+ /// running, 2 enabled and running. Both 1 and 2 mean "enabled".+ /// </summary>+ internal static VbsState MapVbsStatus(int status, FirmwareMode firmwareMode)+ {+ if (firmwareMode == FirmwareMode.Legacy)+ return VbsState.Unavailable;+ return status switch+ {+ 0 => VbsState.Disabled,+ 1 or 2 => VbsState.Enabled,+ _ => VbsState.Unknown,+ };+ }++ /// <summary>Effective state: HVCI protects only when actually running.</summary>+ internal static VbsState MapMemoryIntegrity(List<int> runningServices)+ {+ return runningServices.Contains(HypervisorEnforcedCodeIntegrityId)+ ? VbsState.Enabled+ : VbsState.Disabled;+ }++ internal static List<int> ToServiceIds(object? value)+ {+ var ids = new List<int>();+ switch (value)+ {+ case Array arr:+ foreach (var item in arr)+ {+ try+ {+ ids.Add(Convert.ToInt32(item));+ }+ catch+ {+ // Skip one malformed entry, keep the rest.+ }+ }+ break;+ case null:+ break;+ default:+ try+ {+ ids.Add(Convert.ToInt32(value));+ }+ catch+ {+ // Unparseable single value: treat as no services.+ }+ break;+ }+ return ids;+ }++ private static SecureBootState ReadSecureBoot(FirmwareMode mode)+ {+ // Secure Boot cannot exist on Legacy boot: report Unavailable, not Disabled.+ if (mode == FirmwareMode.Legacy)+ return SecureBootState.Unavailable;+ return ReadDword(+ @"SYSTEM\CurrentControlSet\Control\SecureBoot\State",+ "UEFISecureBootEnabled"+ ) switch+ {+ 1 => SecureBootState.Enabled,+ 0 => SecureBootState.Disabled,+ _ => SecureBootState.Unknown,+ };+ }++ private static VbsState ReadDwordState(string subKey, string valueName)+ {+ return ReadDword(subKey, valueName) switch+ {+ 1 => VbsState.Enabled,+ 0 => VbsState.Disabled,+ _ => VbsState.Unknown,+ };+ }++ private static int? ReadDword(string subKey, string valueName)+ {+ try+ {+ using var key = Registry.LocalMachine.OpenSubKey(subKey);+ return key?.GetValue(valueName) switch+ {+ int i => i,+ uint u => (int)u,+ long l => (int)l,+ _ => null,+ };+ }+ catch+ {+ // Missing key or access denied: Unknown, never Disabled.+ return null;+ }+ }+}++internal static class PowerProvider+{+ public static PowerInfo Get()+ {+ try+ {+ var (id, name) = PowerReader.ReadActive();+ if (id is null)+ return PowerInfo.Unknown;+ return new PowerInfo { SchemeId = id.Value, SchemeName = name };}catch{- return BiosInfo.Unknown;+ return PowerInfo.Unknown;}}+}- private static string FormatWmiDate(string wmiDate)+internal static class RuntimeProvider+{+ public static RuntimeInfo Get(){- if (wmiDate.Length < 8)- return "Unknown";- return $"{wmiDate[..4]}-{wmiDate.Substring(4, 2)}-{wmiDate.Substring(6, 2)}";+ try+ {+ return new RuntimeInfo+ {+ Uptime = TimeSpan.FromMilliseconds((double)Environment.TickCount64),+ };+ }+ catch+ {+ return RuntimeInfo.Unknown;+ }}}// ============================================================================-// MAIN SERVICE (Public API)+// MAIN SERVICE (public API)// ============================================================================public sealed class SystemInfoService : IDisposable{+ private static readonly TimeSpan ScanTimeout = TimeSpan.FromSeconds(20);+private readonly ILogger<SystemInfoService> _logger;private readonly SemaphoreSlim _semaphore = new(1, 1);- private BiosInfo? _cachedBios;- // Cache CPU, OS, BIOS info (doesn't change at runtime)+ // Static sections: resolved once, reused by every later refresh.private CpuInfo? _cachedCpu;-+ private WindowsInfo? _cachedWindows;+ private FirmwareInfo? _cachedFirmware;private IReadOnlyList<GpuInfo>? _cachedGpus;- private OsInfo? _cachedOs;- public SystemInfoService(ILogger<SystemInfoService> logger)+ public SystemInfoService(ILogger<SystemInfoService> logger, PowerPlanService? powerPlans = null){_logger = logger;+ if (powerPlans is not null)+ PowerReader.Configure(powerPlans);}- public SystemSnapshot Snapshot { get; private set; } = SystemSnapshot.Unknown;+ public SystemInfo Snapshot { get; private set; } = SystemInfo.Unknown;/// <summary>- /// Raised whenever a refresh completes with a new snapshot. Fires on the thread- /// that finished the refresh (usually a thread-pool thread), so subscribers must- /// marshal back to the UI thread before touching the UI.+ /// Raised after a refresh completes. Fires on the thread that finished the+ /// refresh (usually a pool thread): subscribers must marshal to UI./// </summary>- public event EventHandler<SystemSnapshot>? SnapshotRefreshed;+ public event EventHandler<SystemInfo>? SnapshotRefreshed;/// <summary>- /// Returns the current snapshot, refreshing it first when it has not been loaded yet.- /// Callers that need hardware/OS facts (e.g. compatibility conditions) use this to- /// guarantee a populated snapshot before reading it.+ /// Returns the current snapshot, refreshing first when nothing loaded yet./// </summary>- public async Task<SystemSnapshot> EnsureSnapshotAsync(CancellationToken ct = default)+ public async Task<SystemInfo> EnsureSnapshotAsync(CancellationToken ct = default){- if (!ReferenceEquals(Snapshot, SystemSnapshot.Unknown))+ if (!Snapshot.IsUnknown)return Snapshot;-return await RefreshAsync(ct).ConfigureAwait(false);}- public async Task<SystemSnapshot> RefreshAsync(CancellationToken ct = default)+ public async Task<SystemInfo> RefreshAsync(CancellationToken ct = default){await _semaphore.WaitAsync(ct).ConfigureAwait(false);try{- var isFirstRun = _cachedCpu == null;+ Snapshot = await ScanAsync(ct).ConfigureAwait(false);+ }+ finally+ {+ _semaphore.Release();+ }- if (isFirstRun)+ // After release so handlers may safely call back into RefreshAsync.+ // Multicast-safe: one failing handler never skips the rest.+ var snapshot = Snapshot;+ foreach (EventHandler<SystemInfo> handler in SnapshotRefreshed?.GetInvocationList() ?? [])+ {+ try{- // First run: fetch everything in parallel- var cpuTask = Task.Run(CpuProvider.Get, ct);- var ramTask = Task.Run(RamProvider.Get, ct);- var gpusTask = Task.Run(GpuProvider.GetAll, ct);- var diskTask = Task.Run(DiskProvider.Get, ct);- var osTask = Task.Run(OsProvider.Get, ct);- var biosTask = Task.Run(BiosProvider.Get, ct);+ handler(this, snapshot);+ }+ catch (Exception ex)+ {+ _logger.LogError(ex, "Snapshot refresh notification handler failed");+ }+ }- await Task.WhenAll(cpuTask, ramTask, gpusTask, diskTask, osTask, biosTask)- .ConfigureAwait(false);+ return snapshot;+ }- _cachedCpu = await cpuTask.ConfigureAwait(false);- _cachedOs = await osTask.ConfigureAwait(false);- _cachedBios = await biosTask.ConfigureAwait(false);- _cachedGpus = await gpusTask.ConfigureAwait(false);+ /// <summary>+ /// Live memory for high-frequency UI ticks. Cheap after the first full scan+ /// (module topology is cached); never touches WMI on the hot path itself.+ /// </summary>+ public MemoryInfo GetLiveMemory()+ {+ return MemoryProvider.Get();+ }- var primaryGpu = GpuProvider.GetPrimary(_cachedGpus);+ /// <summary>+ /// Live storage sizes for high-frequency UI ticks. Uses DriveInfo plus the+ /// cached topology only: issues zero new WMI queries.+ /// </summary>+ public StorageInfo GetLiveStorage()+ {+ return DiskProvider.GetFast();+ }- Snapshot = new SystemSnapshot- {- Cpu = _cachedCpu,- Ram = await ramTask.ConfigureAwait(false),- Os = _cachedOs,- Bios = _cachedBios,- Gpus = _cachedGpus,- PrimaryGpu = primaryGpu,- Disk = await diskTask.ConfigureAwait(false),- };- }- else- {- // Subsequent runs: only refresh dynamic data (RAM, Disk)- // GPU list changes very rarely, so cache it too- var ramTask = Task.Run(RamProvider.Get, ct);- var diskTask = Task.Run(DiskProvider.Get, ct);+ private async Task<SystemInfo> ScanAsync(CancellationToken ct)+ {+ var firstRun = _cachedCpu is null;- await Task.WhenAll(ramTask, diskTask).ConfigureAwait(false);+ // Cheap synchronous sections: no Task.Run needed, none of them block.+ var power = PowerProvider.Get();+ var runtime = RuntimeProvider.Get();+ var security = SecurityProvider.Get();- var gpus = _cachedGpus!;- var primaryGpu = GpuProvider.GetPrimary(gpus);+ Task<CpuInfo>? cpuTask = null;+ Task<WindowsInfo>? windowsTask = null;+ Task<FirmwareInfo>? firmwareTask = null;+ Task<IReadOnlyList<GpuInfo>>? gpusTask = null;- Snapshot = new SystemSnapshot- {- Cpu = _cachedCpu!,- Ram = await ramTask.ConfigureAwait(false),- Os = _cachedOs!,- Bios = _cachedBios!,- Gpus = gpus,- PrimaryGpu = primaryGpu,- Disk = await diskTask.ConfigureAwait(false),- };- }- }- catch (OperationCanceledException)+ if (firstRun){- throw;+ cpuTask = Task.Run(CpuProvider.Get, ct);+ windowsTask = Task.Run(WindowsProvider.Get, ct);+ firmwareTask = Task.Run(FirmwareProvider.Get, ct);+ gpusTask = Task.Run(GpuProvider.GetAll, ct);}- catch (Exception ex)++ var memoryTask = Task.Run(MemoryProvider.Get, ct);+ var storageTask = Task.Run(DiskProvider.GetFull, ct);++ var pending = new List<Task>(capacity: 6);+ if (cpuTask is not null)+ pending.AddRange([cpuTask, windowsTask!, firmwareTask!, gpusTask!]);+ pending.AddRange([memoryTask, storageTask]);++ try{- _logger.LogError(ex, "Failed to refresh system info");- return SystemSnapshot.Unknown;+ // Bounds a hung WMI call: on timeout the scan completes with the+ // sections that did finish instead of hanging the Dashboard.+ await Task.WhenAll(pending).WaitAsync(ScanTimeout, ct).ConfigureAwait(false);}- finally+ catch (OperationCanceledException) when (!ct.IsCancellationRequested){- _semaphore.Release();+ _logger.LogWarning("System info scan timed out; using partial results");}- // Raised after the semaphore is released so subscribers can safely call back- // into RefreshAsync; handler exceptions are isolated and logged so a failing- // subscriber never corrupts the refresh result.- try+ // User cancellation still aborts: never silently return partial data for it.+ ct.ThrowIfCancellationRequested();++ if (firstRun){- SnapshotRefreshed?.Invoke(this, Snapshot);+ _cachedCpu = Take(cpuTask!, CpuInfo.Unknown);+ _cachedWindows = Take(windowsTask!, WindowsInfo.Unknown);+ _cachedFirmware = Take(firmwareTask!, FirmwareInfo.Unknown);+ _cachedGpus = Take(gpusTask!, (IReadOnlyList<GpuInfo>)[]);}- catch (Exception ex)++ var gpus = _cachedGpus ?? [];+ return new SystemInfo{- _logger.LogError(ex, "Snapshot refresh notification handler failed");- }+ Windows = _cachedWindows ?? WindowsInfo.Unknown,+ Cpu = _cachedCpu ?? CpuInfo.Unknown,+ Memory = Take(memoryTask, MemoryInfo.Unknown),+ Gpus = gpus,+ PrimaryGpu = GpuProvider.GetPrimary(gpus),+ Firmware = _cachedFirmware ?? FirmwareInfo.Unknown,+ Security = security,+ Power = power,+ Storage = Take(storageTask, StorageInfo.Unknown),+ Runtime = runtime,+ };- return Snapshot;+ static T Take<T>(Task<T> task, T fallback)+ {+ // Only already-finished results: never block on a timed-out WMI call.+ // Providers never throw, so non-success means cancelled/abandoned.+ return task.IsCompletedSuccessfully ? task.Result : fallback;+ }}public void LogSummary(){try{+ var s = Snapshot;_logger.LogInformation(- "OS : {OsName} {OsEdition} [{OsArchitecture}] ({OsDeviceType})",- Snapshot.Os.Name,- Snapshot.Os.Edition,- Snapshot.Os.Architecture,- Snapshot.Os.DeviceType+ "OS: Windows {Build} {Edition} [{Arch}] ({Device})",+ s.Windows.BuildNumber?.ToString() ?? "?",+ s.Windows.Edition,+ s.Windows.Architecture,+ s.Windows.DeviceKind);-- LogGpuSummary();-_logger.LogInformation(- "CPU: {CpuName} [{CpuVendor}] ({CpuCores} Cores/{CpuThreads} Threads)",- Snapshot.Cpu.Name,- Snapshot.Cpu.Vendor,- Snapshot.Cpu.Cores,- Snapshot.Cpu.Threads+ "CPU: {Cpu} [{Vendor}] ({Cores}C/{Threads}T)",+ s.Cpu.Name ?? "?",+ s.Cpu.Vendor,+ s.Cpu.CoreCount,+ s.Cpu.ThreadCount);-_logger.LogInformation(- "RAM: {RamTotalGb:F1} GB [{RamModules} Module(s)] (Used: {RamUsedGB:F1} GB)",- Snapshot.Ram.TotalGB,- Snapshot.Ram.Modules.Count,- Snapshot.Ram.UsedGB+ "RAM: {Total:F1} GB ({Modules} modules, {Speed} MT/s {Type})",+ s.Memory.TotalGB,+ s.Memory.Modules.Count,+ s.Memory.SpeedMTps?.ToString() ?? "?",+ s.Memory.Type);-- foreach (var volume in Snapshot.Disk.Volumes)- {- var systemDrive = volume.IsSystemDrive ? " [System Drive]" : "";- var modelInfo = !string.IsNullOrEmpty(volume.Model) ? $" - {volume.Model}" : "";+ foreach (var gpu in s.Gpus)_logger.LogInformation(- "Disk {VolumeLetter}{SystemDrive} [{MediaType}] {VolumeTotalSizeGb:F1} GB (Free: {VolumeFreeSpaceGb:F1} GB){ModelInfo}",- volume.DriveLetter,- systemDrive,- volume.MediaType,- volume.TotalSizeGB,- volume.AvailableSizeGB,- modelInfo+ "GPU: {Gpu} [{Vendor}] ({Vram} MB)",+ gpu.Name ?? "?",+ gpu.Vendor,+ gpu.VramMB?.ToString() ?? "?");- }- }- catch (Exception ex)- {- _logger.LogError(ex, "Failed to log system summary");- }- }-- private void LogGpuSummary()- {- var gpuCount = Snapshot.Gpus.Count;-- if (gpuCount == 0 || (gpuCount == 1 && Snapshot.Gpus[0] == GpuInfo.Unknown))- {- _logger.LogWarning("GPU: None detected");- return;- }-- if (gpuCount == 1)- {- var gpu = Snapshot.Gpus[0];- var memoryInfo = gpu.MemoryMB.HasValue ? $" ({gpu.MemoryMB.Value / 1024.0:F0} GB)" : "";- _logger.LogInformation(- "GPU: {GpuName} [{GpuVendor}]{MemoryInfo}",- gpu.Name,- gpu.Vendor,- memoryInfo- );- return;- }-- // Multiple GPUs- if (Snapshot.PrimaryGpu != null)- {- var memoryInfoPrimary = Snapshot.PrimaryGpu.MemoryMB.HasValue- ? $" ({Snapshot.PrimaryGpu.MemoryMB.Value / 1024.0:F0} GB)"- : "";_logger.LogInformation(- "GPU (Primary): {PrimaryGpuName} [{PrimaryGpuVendor}]{MemoryInfo}",- Snapshot.PrimaryGpu.Name,- Snapshot.PrimaryGpu.Vendor,- memoryInfoPrimary+ "Firmware: {Mode}, SecureBoot: {SecureBoot}, VBS: {Vbs}, Power: {Power}",+ s.Firmware.Mode,+ s.Security.SecureBoot,+ s.Security.VirtualizationBasedSecurity,+ s.Power.SchemeName ?? s.Power.SchemeId?.ToString() ?? "?");-- for (var index = 0; index < Snapshot.Gpus.Count; index++)- {- if (- Snapshot.Gpus[index].Name == Snapshot.PrimaryGpu.Name- && Snapshot.Gpus[index].Vendor == Snapshot.PrimaryGpu.Vendor- )- continue;-- var gpu = Snapshot.Gpus[index];- var memoryInfo = gpu.MemoryMB.HasValue- ? $" [{gpu.MemoryMB.Value / 1024.0:F0} GB]"- : "";+ foreach (var v in s.Storage.Volumes)_logger.LogInformation(- "GPU ({GpuIndex}): {GpuName} ({GpuVendor}){MemoryInfo}",- index + 1,- gpu.Name,- gpu.Vendor,- memoryInfo+ "Disk {Letter}{System} [{Media}] {Total} GB (free {Free} GB){Model}",+ v.DriveLetter,+ v.IsSystemDrive ? " [System]" : "",+ v.MediaType,+ v.TotalBytes / (1024.0 * 1024.0 * 1024.0),+ v.FreeBytes / (1024.0 * 1024.0 * 1024.0),+ v.Model is not null ? $" - {v.Model}" : "");- }-- _logger.LogInformation("Total GPUs : {GpuCount}", gpuCount);+ }+ catch (Exception ex)+ {+ _logger.LogError(ex, "Failed to log system summary");}}diff --git a/optimizerDuck/UI/Pages/DashboardPage.xaml b/optimizerDuck/UI/Pages/DashboardPage.xamlindex dad1a01..5389bff 100644--- a/optimizerDuck/UI/Pages/DashboardPage.xaml+++ b/optimizerDuck/UI/Pages/DashboardPage.xaml@@ -152,11 +152,13 @@</Grid.RowDefinitions><StackPanel Grid.Row="0">- <ui:TextBlock FontTypography="BodyStrong" Text="{Binding ViewModel.SystemInfo.Os.Name}" />+ <ui:TextBlock FontTypography="BodyStrong" Text="{Binding ViewModel.WindowsTitle}" /><ui:TextBlock FontTypography="Caption" Foreground="{DynamicResource TextFillColorSecondaryBrush}">- <Run Text="{Binding ViewModel.SystemInfo.Os.Edition}" />+ <Run Text="{Binding ViewModel.SystemInfo.Windows.Edition, Converter={StaticResource EnumDisplayConverter}, Mode=OneWay}" /><Run Text="·" />- <Run Text="{Binding ViewModel.SystemInfo.Os.Architecture}" />+ <Run Text="{Binding ViewModel.SystemInfo.Windows.Architecture, Converter={StaticResource EnumDisplayConverter}, Mode=OneWay}" />+ <Run Text="·" />+ <Run Text="{Binding ViewModel.SystemInfo.Windows.DisplayVersion, TargetNullValue=—, Mode=OneWay}" /></ui:TextBlock></StackPanel>@@ -169,21 +171,21 @@Padding="6,2"Background="{DynamicResource CardBackgroundFillColorSecondaryBrush}"CornerRadius="{StaticResource CornerRadiusSmall}">- <ui:TextBlock FontTypography="Caption" Text="{ext:Loc Dashboard.SystemInfo.Os.Build, {Binding ViewModel.SystemInfo.Os.BuildNumber}}" />+ <ui:TextBlock FontTypography="Caption" Text="{ext:Loc Dashboard.SystemInfo.Os.Build, {Binding ViewModel.SystemInfo.Windows.BuildNumber, FallbackValue=—, Mode=OneWay}}" /></Border><BorderMargin="0,0,4,4"Padding="6,2"Background="{DynamicResource CardBackgroundFillColorSecondaryBrush}"CornerRadius="{StaticResource CornerRadiusSmall}">- <ui:TextBlock FontTypography="Caption" Text="{Binding ViewModel.SystemInfo.Os.DeviceType, Converter={StaticResource DeviceKindConverter}}" />+ <ui:TextBlock FontTypography="Caption" Text="{Binding ViewModel.SystemInfo.Windows.DeviceKind, Converter={StaticResource DeviceKindConverter}, Mode=OneWay}" /></Border><BorderMargin="0,0,4,4"Padding="6,2"Background="{DynamicResource CardBackgroundFillColorSecondaryBrush}"CornerRadius="{StaticResource CornerRadiusSmall}">- <ui:TextBlock FontTypography="Caption" Text="{Binding ViewModel.SystemInfo.Os.InstallDate}" />+ <ui:TextBlock FontTypography="Caption" Text="{Binding ViewModel.InstallDateText, Mode=OneWay}" /></Border></WrapPanel></Grid>@@ -205,14 +207,14 @@<StackPanel Grid.Row="0"><ui:TextBlockFontTypography="BodyStrong"- Text="{Binding ViewModel.SystemInfo.Cpu.Name}"+ Text="{Binding ViewModel.SystemInfo.Cpu.Name, Converter={StaticResource NullToUnknownTextConverter}, Mode=OneWay}"TextTrimming="CharacterEllipsis" /><ui:TextBlock FontTypography="Caption" Foreground="{DynamicResource TextFillColorSecondaryBrush}">- <Run Text="{Binding ViewModel.SystemInfo.Cpu.Vendor}" />+ <Run Text="{Binding ViewModel.SystemInfo.Cpu.Vendor, Converter={StaticResource EnumDisplayConverter}, Mode=OneWay}" /><Run Text="·" />- <Run Text="{ext:Loc Dashboard.SystemInfo.Cpu.Cores, {Binding ViewModel.SystemInfo.Cpu.Cores}}" />+ <Run Text="{ext:Loc Dashboard.SystemInfo.Cpu.Cores, {Binding ViewModel.SystemInfo.Cpu.CoreCount, Mode=OneWay}}" /><Run Text="/" />- <Run Text="{ext:Loc Dashboard.SystemInfo.Cpu.Threads, {Binding ViewModel.SystemInfo.Cpu.Threads}}" />+ <Run Text="{ext:Loc Dashboard.SystemInfo.Cpu.Threads, {Binding ViewModel.SystemInfo.Cpu.ThreadCount, Mode=OneWay}}" /></ui:TextBlock></StackPanel>@@ -224,20 +226,19 @@Margin="0,0,4,4"Padding="6,2"Background="{DynamicResource CardBackgroundFillColorSecondaryBrush}"- CornerRadius="{StaticResource CornerRadiusSmall}">- <ui:TextBlock FontTypography="Caption">- <Run Text="{Binding ViewModel.SystemInfo.Cpu.CurrentClockMHz}" />- <Run Text="MHz" />- </ui:TextBlock>+ CornerRadius="{StaticResource CornerRadiusSmall}"+ Visibility="{Binding ViewModel.SystemInfo.Cpu.CurrentFrequencyMhz, Converter={StaticResource NullToVisibilityConverter}, Mode=OneWay}">+ <ui:TextBlock FontTypography="Caption" Text="{ext:Loc Dashboard.SystemInfo.Cpu.Frequency, {Binding ViewModel.SystemInfo.Cpu.CurrentFrequencyMhz, Mode=OneWay}}" /></Border><BorderMargin="0,0,4,4"Padding="6,2"Background="{DynamicResource CardBackgroundFillColorSecondaryBrush}"- CornerRadius="{StaticResource CornerRadiusSmall}">+ CornerRadius="{StaticResource CornerRadiusSmall}"+ Visibility="{Binding ViewModel.SystemInfo.Cpu.L2CacheKB, Converter={StaticResource NullToVisibilityConverter}, Mode=OneWay}"><ui:TextBlock FontTypography="Caption"><Run Text="L2:" />- <Run Text="{Binding ViewModel.SystemInfo.Cpu.L2CacheKB}" />+ <Run Text="{Binding ViewModel.SystemInfo.Cpu.L2CacheKB, Mode=OneWay}" /><Run Text="KB" /></ui:TextBlock></Border>@@ -245,10 +246,11 @@Margin="0,0,4,4"Padding="6,2"Background="{DynamicResource CardBackgroundFillColorSecondaryBrush}"- CornerRadius="{StaticResource CornerRadiusSmall}">+ CornerRadius="{StaticResource CornerRadiusSmall}"+ Visibility="{Binding ViewModel.SystemInfo.Cpu.L3CacheKB, Converter={StaticResource NullToVisibilityConverter}, Mode=OneWay}"><ui:TextBlock FontTypography="Caption"><Run Text="L3:" />- <Run Text="{Binding ViewModel.SystemInfo.Cpu.L3CacheKB}" />+ <Run Text="{Binding ViewModel.SystemInfo.Cpu.L3CacheKB, Mode=OneWay}" /><Run Text="KB" /></ui:TextBlock></Border>@@ -272,12 +274,12 @@<StackPanel Grid.Row="0"><ui:TextBlock FontTypography="BodyStrong">- <Run Text="{ext:Loc Dashboard.SystemInfo.Ram.Total, {Binding ViewModel.RuntimeRam.TotalGB, StringFormat='{}{0:F1}'}}" />+ <Run Text="{ext:Loc Dashboard.SystemInfo.Ram.Total, {Binding ViewModel.RuntimeMemory.TotalBytes, Converter={StaticResource BytesToGBConverter}}}" /></ui:TextBlock><ui:TextBlock FontTypography="Caption" Foreground="{DynamicResource TextFillColorSecondaryBrush}">- <Run Text="{ext:Loc Dashboard.SystemInfo.Ram.Used, {Binding ViewModel.RuntimeRam.UsedGB, StringFormat='{}{0:F1}'}}" />+ <Run Text="{ext:Loc Dashboard.SystemInfo.Ram.Used, {Binding ViewModel.RuntimeMemory.UsedBytes, Converter={StaticResource BytesToGBConverter}}}" /><Run Text="·" />- <Run Text="{ext:Loc Dashboard.SystemInfo.Ram.Available, {Binding ViewModel.RuntimeRam.AvailableGB, StringFormat='{}{0:F1}'}}" />+ <Run Text="{ext:Loc Dashboard.SystemInfo.Ram.Available, {Binding ViewModel.RuntimeMemory.AvailableBytes, Converter={StaticResource BytesToGBConverter}}}" /></ui:TextBlock></StackPanel>@@ -286,21 +288,37 @@Height="6"Margin="0,8,0,0"Maximum="100"- Value="{Binding ViewModel.RuntimeRam.UsedPercent}"- Foreground="{Binding ViewModel.RuntimeRam.UsedPercent, Converter={StaticResource ProgressBarValueToBrushConverter}}" />+ Value="{Binding ViewModel.RuntimeMemory.UsedPercent, Mode=OneWay}"+ Foreground="{Binding ViewModel.RuntimeMemory.UsedPercent, Converter={StaticResource ProgressBarValueToBrushConverter}}" /><WrapPanelGrid.Row="2"Margin="0,8,0,0"Orientation="Horizontal"><Border+ Margin="0,0,4,4"Padding="6,2"Background="{DynamicResource CardBackgroundFillColorSecondaryBrush}"CornerRadius="{StaticResource CornerRadiusSmall}"><ui:TextBlock FontTypography="Caption">- <Run Text="{ext:Loc Dashboard.SystemInfo.Ram.Modules, {Binding ViewModel.RuntimeRam.Modules.Count, Mode=OneWay}}" />+ <Run Text="{ext:Loc Dashboard.SystemInfo.Ram.Modules, {Binding ViewModel.RuntimeMemory.Modules.Count, Mode=OneWay}}" /></ui:TextBlock></Border>+ <Border+ Margin="0,0,4,4"+ Padding="6,2"+ Background="{DynamicResource CardBackgroundFillColorSecondaryBrush}"+ CornerRadius="{StaticResource CornerRadiusSmall}"+ Visibility="{Binding ViewModel.RuntimeMemory.SpeedMTps, Converter={StaticResource NullToVisibilityConverter}, Mode=OneWay}">+ <ui:TextBlock FontTypography="Caption" Text="{ext:Loc Dashboard.SystemInfo.Memory.Speed, {Binding ViewModel.RuntimeMemory.SpeedMTps, Mode=OneWay}}" />+ </Border>+ <Border+ Margin="0,0,4,4"+ Padding="6,2"+ Background="{DynamicResource CardBackgroundFillColorSecondaryBrush}"+ CornerRadius="{StaticResource CornerRadiusSmall}">+ <ui:TextBlock FontTypography="Caption" Text="{Binding ViewModel.RuntimeMemory.Type, Converter={StaticResource EnumDisplayConverter}, Mode=OneWay}" />+ </Border></WrapPanel></Grid></ui:CardControl.Header>@@ -321,12 +339,12 @@<StackPanel Grid.Row="0"><ui:TextBlockFontTypography="BodyStrong"- Text="{Binding ViewModel.SystemInfo.PrimaryGpu.Name}"+ Text="{Binding ViewModel.SystemInfo.PrimaryGpu.Name, Converter={StaticResource NullToUnknownTextConverter}, Mode=OneWay}"TextTrimming="CharacterEllipsis" /><ui:TextBlockFontTypography="Caption"Foreground="{DynamicResource TextFillColorSecondaryBrush}"- Text="{Binding ViewModel.SystemInfo.PrimaryGpu.Vendor}" />+ Text="{Binding ViewModel.SystemInfo.PrimaryGpu.Vendor, Converter={StaticResource EnumDisplayConverter}, Mode=OneWay}" /></StackPanel><WrapPanel@@ -339,17 +357,18 @@Background="{DynamicResource CardBackgroundFillColorSecondaryBrush}"CornerRadius="{StaticResource CornerRadiusSmall}"><ui:TextBlock FontTypography="Caption">- <Run Text="{ext:Loc Dashboard.SystemInfo.Gpu.Memory, {Binding ViewModel.SystemInfo.PrimaryGpu.MemoryMB, Converter={StaticResource MBToGBConverter}}}" />+ <Run Text="{ext:Loc Dashboard.SystemInfo.Gpu.Memory, {Binding ViewModel.SystemInfo.PrimaryGpu.VramMB, Converter={StaticResource MBToGBConverter}, Mode=OneWay}}" /></ui:TextBlock></Border><BorderMargin="0,0,4,4"Padding="6,2"Background="{DynamicResource CardBackgroundFillColorSecondaryBrush}"- CornerRadius="{StaticResource CornerRadiusSmall}">+ CornerRadius="{StaticResource CornerRadiusSmall}"+ Visibility="{Binding ViewModel.SystemInfo.PrimaryGpu.DriverVersion, Converter={StaticResource NullToVisibilityConverter}, Mode=OneWay}"><ui:TextBlockFontTypography="Caption"- Text="{Binding ViewModel.SystemInfo.PrimaryGpu.DriverVersion}"+ Text="{ext:Loc Dashboard.SystemInfo.Gpu.Driver, {Binding ViewModel.SystemInfo.PrimaryGpu.DriverVersion, Mode=OneWay}}"TextTrimming="CharacterEllipsis" /></Border><Border@@ -368,6 +387,79 @@</ui:CardControl></UniformGrid>+ <!-- Platform & Security -->+ <ui:CardControl+ Margin="0,12,0,0"+ VerticalAlignment="Stretch"+ Icon="{ui:SymbolIcon ShieldCheckmark24}">+ <ui:CardControl.Header>+ <Grid>+ <Grid.RowDefinitions>+ <RowDefinition Height="Auto" />+ <RowDefinition Height="*" />+ </Grid.RowDefinitions>++ <StackPanel Grid.Row="0">+ <ui:TextBlock FontTypography="BodyStrong" Text="{ext:Loc Dashboard.SystemInfo.Platform.Header}" />+ <ui:TextBlock+ FontTypography="Caption"+ Foreground="{DynamicResource TextFillColorSecondaryBrush}"+ Text="{Binding ViewModel.SystemInfo.Firmware.Motherboard, Mode=OneWay}"+ TextTrimming="CharacterEllipsis"+ Visibility="{Binding ViewModel.SystemInfo.Firmware.Motherboard, Converter={StaticResource NullToVisibilityConverter}, Mode=OneWay}" />+ </StackPanel>++ <WrapPanel+ Grid.Row="1"+ Margin="0,8,0,0"+ Orientation="Horizontal">+ <Border+ Margin="0,0,4,4"+ Padding="6,2"+ Background="{DynamicResource CardBackgroundFillColorSecondaryBrush}"+ CornerRadius="{StaticResource CornerRadiusSmall}">+ <ui:TextBlock FontTypography="Caption" Text="{ext:Loc Dashboard.SystemInfo.Firmware, {Binding ViewModel.SystemInfo.Firmware.Mode, Converter={StaticResource EnumDisplayConverter}, Mode=OneWay}}" />+ </Border>+ <Border+ Margin="0,0,4,4"+ Padding="6,2"+ Background="{DynamicResource CardBackgroundFillColorSecondaryBrush}"+ CornerRadius="{StaticResource CornerRadiusSmall}">+ <ui:TextBlock FontTypography="Caption" Text="{ext:Loc Dashboard.SystemInfo.SecureBoot, {Binding ViewModel.SystemInfo.Security.SecureBoot, Converter={StaticResource EnumDisplayConverter}, Mode=OneWay}}" />+ </Border>+ <Border+ Margin="0,0,4,4"+ Padding="6,2"+ Background="{DynamicResource CardBackgroundFillColorSecondaryBrush}"+ CornerRadius="{StaticResource CornerRadiusSmall}">+ <ui:TextBlock FontTypography="Caption" Text="{ext:Loc Dashboard.SystemInfo.Vbs, {Binding ViewModel.SystemInfo.Security.VirtualizationBasedSecurity, Converter={StaticResource EnumDisplayConverter}, Mode=OneWay}}" />+ </Border>+ <Border+ Margin="0,0,4,4"+ Padding="6,2"+ Background="{DynamicResource CardBackgroundFillColorSecondaryBrush}"+ CornerRadius="{StaticResource CornerRadiusSmall}">+ <ui:TextBlock FontTypography="Caption" Text="{ext:Loc Dashboard.SystemInfo.MemoryIntegrity, {Binding ViewModel.SystemInfo.Security.MemoryIntegrity, Converter={StaticResource EnumDisplayConverter}, Mode=OneWay}}" />+ </Border>+ <Border+ Margin="0,0,4,4"+ Padding="6,2"+ Background="{DynamicResource CardBackgroundFillColorSecondaryBrush}"+ CornerRadius="{StaticResource CornerRadiusSmall}">+ <ui:TextBlock FontTypography="Caption" Text="{Binding ViewModel.PowerPlanText, Mode=OneWay}" />+ </Border>+ <Border+ Margin="0,0,4,4"+ Padding="6,2"+ Background="{DynamicResource CardBackgroundFillColorSecondaryBrush}"+ CornerRadius="{StaticResource CornerRadiusSmall}">+ <ui:TextBlock FontTypography="Caption" Text="{Binding ViewModel.UptimeText, Mode=OneWay}" />+ </Border>+ </WrapPanel>+ </Grid>+ </ui:CardControl.Header>+ </ui:CardControl>+<!-- Storage Section --><ui:TextBlockMargin="0,20,0,8"@@ -375,7 +467,7 @@Text="{ext:Loc Dashboard.SystemInfo.Storage.Header}" /><ItemsControl- ItemsSource="{Binding ViewModel.RuntimeDisk.Volumes}"+ ItemsSource="{Binding ViewModel.RuntimeStorage.Volumes}"VirtualizingStackPanel.IsVirtualizing="True"VirtualizingStackPanel.VirtualizationMode="Recycling"><ItemsControl.ItemsPanel>@@ -422,7 +514,7 @@Margin="0,0,8,0"VerticalAlignment="Center"FontTypography="Caption"- Text="{Binding VolumeLabel}" />+ Text="{Binding Label, TargetNullValue=''}" /><BorderMargin="0,0,4,0"@@ -443,28 +535,16 @@VerticalAlignment="Center"Background="{DynamicResource CardBackgroundFillColorSecondaryBrush}"CornerRadius="{StaticResource CornerRadiusSmall}">- <ui:TextBlock FontTypography="Caption" Text="{Binding MediaType}">- <ui:TextBlock.Style>- <Style TargetType="ui:TextBlock">- <Style.Triggers>- <DataTrigger Binding="{Binding MediaType}" Value="SSD">- <Setter Property="Foreground" Value="{DynamicResource SystemFillColorSuccessBrush}" />- </DataTrigger>- <DataTrigger Binding="{Binding MediaType}" Value="HDD">- <Setter Property="Foreground" Value="{DynamicResource SystemFillColorCautionBrush}" />- </DataTrigger>- </Style.Triggers>- </Style>- </ui:TextBlock.Style>- </ui:TextBlock>+ <ui:TextBlock FontTypography="Caption" Text="{Binding MediaType, Converter={StaticResource EnumDisplayConverter}}" /></Border><BorderPadding="5,2"VerticalAlignment="Center"Background="{DynamicResource CardBackgroundFillColorSecondaryBrush}"- CornerRadius="{StaticResource CornerRadiusSmall}">- <ui:TextBlock FontTypography="Caption" Text="{Binding DriveFormat}" />+ CornerRadius="{StaticResource CornerRadiusSmall}"+ Visibility="{Binding FileSystem, Converter={StaticResource NullToVisibilityConverter}}">+ <ui:TextBlock FontTypography="Caption" Text="{Binding FileSystem}" /></Border></StackPanel>@@ -487,9 +567,9 @@FontTypography="Caption"Foreground="{DynamicResource TextFillColorSecondaryBrush}"Text="{ext:Loc Dashboard.SystemInfo.Storage.DiskInfo,- {Binding UsedSizeGB, StringFormat='{}{0:F1}'},- {Binding TotalSizeGB, StringFormat='{}{0:F1}'},- {Binding AvailableSizeGB, StringFormat='{}{0:F1}'}}" />+ {Binding UsedBytes, Converter={StaticResource BytesToGBConverter}},+ {Binding TotalBytes, Converter={StaticResource BytesToGBConverter}},+ {Binding FreeBytes, Converter={StaticResource BytesToGBConverter}}}" /></StackPanel><!-- Progress Bar -->@@ -498,7 +578,7 @@Height="6"Margin="0,8,0,0"Maximum="100"- Value="{Binding UsedPercent}"+ Value="{Binding UsedPercent, Mode=OneWay}"Foreground="{Binding UsedPercent, Converter={StaticResource ProgressBarValueToBrushConverter}}" /></Grid></ui:CardAction>diff --git a/optimizerDuck/UI/Styles/Converters.xaml b/optimizerDuck/UI/Styles/Converters.xamlindex b5b4ba2..2220e23 100644--- a/optimizerDuck/UI/Styles/Converters.xaml+++ b/optimizerDuck/UI/Styles/Converters.xaml@@ -39,6 +39,9 @@<converters:ObjectToNullableDoubleConverter x:Key="ObjectToNullableDoubleConverter" /><converters:WidthToColumnConverter x:Key="WidthToColumnConverter" /><converters:MBToGBConverter x:Key="MBToGBConverter" />+ <converters:BytesToGBConverter x:Key="BytesToGBConverter" />+ <converters:EnumDisplayConverter x:Key="EnumDisplayConverter" />+ <converters:NullToUnknownTextConverter x:Key="NullToUnknownTextConverter" /><converters:MinusNumberConverter x:Key="MinusNumberConverter" /><converters:MinusNumberConverter x:Key="MinusOneConverter" NumberToMinus="1" /><converters:DeviceKindConverter x:Key="DeviceKindConverter" />diff --git a/optimizerDuck/UI/ViewModels/Optimizer/OptimizationCategoryViewModel.cs b/optimizerDuck/UI/ViewModels/Optimizer/OptimizationCategoryViewModel.csindex 6ac2b69..f1ef47a 100644--- a/optimizerDuck/UI/ViewModels/Optimizer/OptimizationCategoryViewModel.cs+++ b/optimizerDuck/UI/ViewModels/Optimizer/OptimizationCategoryViewModel.cs@@ -422,7 +422,7 @@ public partial class OptimizationCategoryViewModel : ViewModel}var snapshot = await _systemInfoService.EnsureSnapshotAsync();- if (ReferenceEquals(snapshot, SystemSnapshot.Unknown))+ if (snapshot.IsUnknown)_logger.LogWarning("System snapshot is unavailable; conditions fail open for this session");@@ -444,13 +444,13 @@ public partial class OptimizationCategoryViewModel : ViewModel/// system snapshot is refreshed (e.g. hardware changed) or the UI language changes./// Marshalled to the UI thread by <see cref="UiThread"/>./// </summary>- private void OnSnapshotRefreshed(object? sender, SystemSnapshot snapshot) =>+ private void OnSnapshotRefreshed(object? sender, SystemInfo snapshot) =>ReEvaluateConditions(snapshot);private void OnCultureChanged(object? sender, PropertyChangedEventArgs e) =>ReEvaluateConditions(_systemInfoService.Snapshot);- private void ReEvaluateConditions(SystemSnapshot snapshot)+ private void ReEvaluateConditions(SystemInfo snapshot){_ = UiThread.InvokeAsync(() =>{@@ -486,7 +486,7 @@ public partial class OptimizationCategoryViewModel : ViewModel/// <summary>/// Re-evaluates every optimization's condition against the system snapshot./// </summary>- private void EvaluateConditions(SystemSnapshot snapshot)+ private void EvaluateConditions(SystemInfo snapshot){ConditionEvaluator.EvaluateAll(_allOptimizations,diff --git a/optimizerDuck/UI/ViewModels/Pages/CustomizeCategoryViewModel.cs b/optimizerDuck/UI/ViewModels/Pages/CustomizeCategoryViewModel.csindex d48b945..f967fbd 100644--- a/optimizerDuck/UI/ViewModels/Pages/CustomizeCategoryViewModel.cs+++ b/optimizerDuck/UI/ViewModels/Pages/CustomizeCategoryViewModel.cs@@ -90,7 +90,7 @@ public partial class CustomizeCategoryViewModel : ViewModelprotected override async Task InitializeOnceAsync(){var snapshot = await _systemInfoService.EnsureSnapshotAsync();- if (ReferenceEquals(snapshot, SystemSnapshot.Unknown))+ if (snapshot.IsUnknown)_logger.LogWarning("System snapshot is unavailable; conditions fail open for this session");@@ -112,7 +112,7 @@ public partial class CustomizeCategoryViewModel : ViewModel/// <summary>/// Evaluates the compatibility condition of every setting against the system snapshot./// </summary>- private void EvaluateConditions(SystemSnapshot snapshot)+ private void EvaluateConditions(SystemInfo snapshot){ConditionEvaluator.EvaluateAll(_allSettings,@@ -199,7 +199,7 @@ public partial class CustomizeCategoryViewModel : ViewModel/// when the system snapshot is refreshed (e.g. hardware changed) or the UI/// language changes. Marshalled to the UI thread by <see cref="UiThread"/>./// </summary>- private void OnSnapshotRefreshed(object? sender, SystemSnapshot snapshot) =>+ private void OnSnapshotRefreshed(object? sender, SystemInfo snapshot) =>ReEvaluateConditions(snapshot);/// <summary>@@ -209,7 +209,7 @@ public partial class CustomizeCategoryViewModel : ViewModelprotected override void OnLanguageChanged(CultureInfo newCulture) =>ReEvaluateConditions(_systemInfoService.Snapshot);- private void ReEvaluateConditions(SystemSnapshot snapshot)+ private void ReEvaluateConditions(SystemInfo snapshot){_ = UiThread.InvokeAsync(() =>{diff --git a/optimizerDuck/UI/ViewModels/Pages/DashboardViewModel.cs b/optimizerDuck/UI/ViewModels/Pages/DashboardViewModel.csindex 1a52e77..f5aa950 100644--- a/optimizerDuck/UI/ViewModels/Pages/DashboardViewModel.cs+++ b/optimizerDuck/UI/ViewModels/Pages/DashboardViewModel.cs@@ -1,4 +1,5 @@using System.Diagnostics;+using System.Globalization;using System.Windows.Media;using System.Windows.Threading;using CommunityToolkit.Mvvm.ComponentModel;@@ -23,6 +24,7 @@ public partial class DashboardViewModel : ViewModelprivate readonly UpdaterService _updaterService;private readonly DispatcherTimer _updateTimer;+ private bool _ticking;[ObservableProperty]private ApplicationTheme _currentApplicationTheme = ApplicationTheme.Unknown;@@ -38,13 +40,28 @@ public partial class DashboardViewModel : ViewModelprivate string? _latestVersion;[ObservableProperty]- private DiskInfo _runtimeDisk = DiskInfo.Unknown;+ private StorageInfo _runtimeStorage = StorageInfo.Unknown;[ObservableProperty]- private RamInfo _runtimeRam = RamInfo.Unknown;+ private MemoryInfo _runtimeMemory = MemoryInfo.Unknown;[ObservableProperty]- private SystemSnapshot _systemInfo = SystemSnapshot.Unknown;+ private SystemInfo _systemInfo = SystemInfo.Unknown;++ [ObservableProperty]+ private string _windowsTitle = Loc.Instance["Common.Unknown"];++ [ObservableProperty]+ private string _installDateText = Loc.Instance["Common.Unknown"];++ [ObservableProperty]+ private string _lastBootText = Loc.Instance["Common.Unknown"];++ [ObservableProperty]+ private string _uptimeText = Loc.Instance["Common.Unknown"];++ [ObservableProperty]+ private string _powerPlanText = Loc.Instance["Common.Unknown"];private bool _updateNotified;public DashboardViewModel(@@ -62,7 +79,7 @@ public partial class DashboardViewModel : ViewModel_contentDialogService = contentDialogService;_updateTimer = new DispatcherTimer { Interval = TimeSpan.FromSeconds(2) };- _updateTimer.Tick += async (s, e) => await UpdateRuntimeInfoAsync();+ _updateTimer.Tick += OnUpdateTick;CurrentApplicationTheme = ApplicationThemeManager.GetAppTheme();}@@ -114,6 +131,11 @@ public partial class DashboardViewModel : ViewModelreturn base.OnNavigatedFromAsync();}+ protected override void OnLanguageChanged(CultureInfo newCulture)+ {+ ApplyDisplayTexts(SystemInfo);+ }+#region Property Changedprivate void OnThemeChanged(ApplicationTheme currentApplicationTheme, Color systemAccent)@@ -133,7 +155,7 @@ public partial class DashboardViewModel : ViewModel}[RelayCommand]- private void SelectDisk(DiskVolume diskVolume)+ private void SelectDisk(StorageVolume diskVolume){if (diskVolume is null || string.IsNullOrWhiteSpace(diskVolume.DriveLetter))return;@@ -265,8 +287,9 @@ public partial class DashboardViewModel : ViewModel{var snapshot = await _systemInfoService.RefreshAsync();SystemInfo = snapshot;- RuntimeRam = snapshot.Ram;- RuntimeDisk = snapshot.Disk;+ RuntimeMemory = snapshot.Memory;+ RuntimeStorage = snapshot.Storage;+ ApplyDisplayTexts(snapshot);}catch (Exception ex){@@ -286,19 +309,69 @@ public partial class DashboardViewModel : ViewModel}}- private async Task UpdateRuntimeInfoAsync()+ /// <summary>+ /// 2s live tick. Runs on the UI thread and calls only the cheap cached+ /// service paths (no WMI, no Task.Run): a slow scan can never overlap ticks.+ /// </summary>+ private void OnUpdateTick(object? sender, EventArgs e){+ if (_ticking)+ return;+ _ticking = true;try{- var ramInfo = await Task.Run(RamProvider.Get);- var diskInfo = await Task.Run(DiskProvider.Get);- RuntimeRam = ramInfo;- RuntimeDisk = diskInfo;+ RuntimeMemory = _systemInfoService.GetLiveMemory();+ RuntimeStorage = _systemInfoService.GetLiveStorage();+ UptimeText =+ Loc.Instance["Dashboard.SystemInfo.Uptime.Label"]+ + ": "+ + FormatUptime(TimeSpan.FromMilliseconds((double)Environment.TickCount64));}catch (Exception ex){_logger.LogWarning(ex, "Failed to update runtime info");}+ finally+ {+ _ticking = false;+ }+ }++ private void ApplyDisplayTexts(SystemInfo snapshot)+ {+ var unknown = Loc.Instance["Common.Unknown"];+ WindowsTitle = snapshot.Windows switch+ {+ { IsWindows11: true } => "Windows 11",+ { IsWindows10: true } => "Windows 10",+ { BuildNumber: { } build } => $"Windows (build {build})",+ _ => unknown,+ };+ InstallDateText = snapshot.Windows.InstallDate?.ToString("yyyy-MM-dd") ?? unknown;+ LastBootText = snapshot.Windows.LastBootTime?.ToString("yyyy-MM-dd HH:mm") ?? unknown;+ PowerPlanText = FormatPowerPlan(snapshot.Power);+ UptimeText =+ Loc.Instance["Dashboard.SystemInfo.Uptime.Label"]+ + ": "+ + FormatUptime(TimeSpan.FromMilliseconds((double)Environment.TickCount64));+ }++ private static string FormatPowerPlan(PowerInfo power)+ {+ // Live name from Windows; GUID fallback when the name is unreadable.+ var label = power.SchemeName ?? power.SchemeId?.ToString();+ if (string.IsNullOrWhiteSpace(label))+ return Loc.Instance["Common.Unknown"];+ return Loc.Instance["Dashboard.SystemInfo.PowerPlan", label];+ }++ private static string FormatUptime(TimeSpan uptime)+ {+ if (uptime < TimeSpan.Zero)+ return Loc.Instance["Common.Unknown"];+ return uptime.TotalDays >= 1 ? $"{(int)uptime.TotalDays}d {uptime.Hours}h {uptime.Minutes}m"+ : uptime.TotalHours >= 1 ? $"{(int)uptime.TotalHours}h {uptime.Minutes}m"+ : $"{uptime.Minutes}m {uptime.Seconds}s";}private void OpenLatestRelease()