From 7916dd9ed26281a8b1450f9d99b575dde7b2020d Mon Sep 17 00:00:00 2001 From: ymg2006 Date: Tue, 24 Nov 2026 00:01:38 +0100 Subject: [PATCH] feat: Upgrade to .NET 11, add CrossCooling, and improve dark theme support MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Upgrade the application target framework to .NET 11. - Introduce CrossCooling to enable CPU and GPU temperature-based fan coordination. - Add configurable CrossCooling modes: - **Off:** Preserve original independent fan control. - **CPU → GPU:** Allow CPU cooling demand to influence the GPU fan. - **GPU → CPU:** Allow GPU cooling demand to influence the CPU fan. - **Both Fans:** Use the maximum CPU/GPU cooling demand for both fans. - Integrate CrossCooling settings with existing fan control functionality. - Update context menus to automatically follow the application's active theme, displaying dark menus in dark mode. - Preserve existing light theme behavior and compatibility with current settings. --- .github/workflows/ci.yml | 8 +- .github/workflows/release.yml | 4 +- Core/AppSettings.cs | 5 + Core/CrossCooling.cs | 143 +++++ Core/CrossCoolingController.cs | 147 +++++ Core/EcCrossCoolingHardware.cs | 46 ++ Core/Lang.cs | 60 +- Forms/GhostCardForm.cs | 1 + Forms/OsdForm.cs | 1 + Forms/ReportForm.cs | 2 + GhostDeck.csproj | 7 +- .../PublishProfiles/FolderProfile.pubxml | 17 + TrayContext.cs | 119 +++- UI/Controls/CheckItem.cs | 2 + UI/Controls/HelpPopup.cs | 2 + UI/Controls/SegControl.cs | 1 + UI/Controls/Slider.cs | 5 + UI/Controls/ThemedComboBox.cs | 8 + UI/Controls/ThemedContextMenu.cs | 110 ++++ UI/Controls/ToggleSwitch.cs | 1 + UI/CrossCoolingPanel.cs | 218 +++++++ UI/Dash/DashCanvas.cs | 2 + UI/FanCurvePage.cs | 34 +- UI/MainDeps.cs | 5 + UI/MainForm.cs | 2 + UI/ReportPage.cs | 3 + UI/ScenariosPage.cs | 4 +- UI/SettingsTrueColor.cs | 1 + UI/SubTabs.cs | 1 + UI/UpdatesPage.cs | 1 + docs/BUILD.md | 44 +- docs/CROSS-COOLING.md | 146 +++++ docs/FAN-CURVE.md | 2 + docs/TECHNICAL.md | 3 + tests/GhostDeck.Tests.csproj | 12 + tests/Program.cs | 555 ++++++++++++++++++ tools/restricted-build.py | 58 ++ 37 files changed, 1753 insertions(+), 27 deletions(-) create mode 100644 Core/CrossCooling.cs create mode 100644 Core/CrossCoolingController.cs create mode 100644 Core/EcCrossCoolingHardware.cs create mode 100644 Properties/PublishProfiles/FolderProfile.pubxml create mode 100644 UI/Controls/ThemedContextMenu.cs create mode 100644 UI/CrossCoolingPanel.cs create mode 100644 docs/CROSS-COOLING.md create mode 100644 tests/GhostDeck.Tests.csproj create mode 100644 tests/Program.cs create mode 100644 tools/restricted-build.py diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 8fd0b42..bd3f33f 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -16,9 +16,11 @@ jobs: - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5 - uses: actions/setup-dotnet@26b0ec14cb23fa6904739307f278c14f94c95bf1 # v5 with: - dotnet-version: '8.0.x' + dotnet-version: '11.0.100' - name: Build run: dotnet build GhostDeck.csproj -c Release + - name: Cross-Cooling tests + run: dotnet run --project tests/GhostDeck.Tests.csproj -c Release # Every Lang.T key must ship in all 15 languages, with no duplicate keys (a duplicate is # accepted silently by the dictionary indexer and quietly kills the earlier translations). @@ -42,7 +44,7 @@ jobs: - name: Model database consistency shell: pwsh run: | - $p = Start-Process -FilePath "bin/Release/net8.0-windows/GhostDeck.exe" ` + $p = Start-Process -FilePath "bin/Release/net11.0-windows7.0/GhostDeck.exe" ` -ArgumentList "--verify-models","data/models.json" -Wait -PassThru -NoNewWindow if ($p.ExitCode -ne 0) { throw "data/models.json does not match the compiled tables - run --dump-models, re-sign (tools/sign-models.ps1) and commit" } "models.json consistent" @@ -67,7 +69,7 @@ jobs: - name: Supported-models doc consistency shell: pwsh run: | - $p = Start-Process -FilePath "bin/Release/net8.0-windows/GhostDeck.exe" ` + $p = Start-Process -FilePath "bin/Release/net11.0-windows7.0/GhostDeck.exe" ` -ArgumentList "--dump-supported-md","fresh-supported.md" -Wait -PassThru -NoNewWindow if ($p.ExitCode -ne 0) { throw "--dump-supported-md failed" } $fresh = ([IO.File]::ReadAllText("fresh-supported.md")) -replace "`r`n", "`n" diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index f3574d0..4db7cac 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -28,8 +28,8 @@ jobs: - uses: actions/setup-dotnet@26b0ec14cb23fa6904739307f278c14f94c95bf1 # v5 with: # Pinned so the same commit always builds with the same SDK. Raise deliberately when - # Microsoft ships a new .NET 8 servicing release. - dotnet-version: '8.0.424' + # Microsoft ships a new .NET 11 servicing release. + dotnet-version: '11.0.100' - name: Ustal wersje id: ver diff --git a/Core/AppSettings.cs b/Core/AppSettings.cs index 0481609..51cca74 100644 --- a/Core/AppSettings.cs +++ b/Core/AppSettings.cs @@ -39,6 +39,7 @@ public sealed class HotkeyDef public sealed class AppSettings { + public CrossCoolingSettings CrossCooling { get; set; } = new(); // Every property of settings.json this version does not know lands here and goes back into // the file on the next save, byte for byte. Without it an older version started after a // newer one rewrote the file with only the fields it knew, and the newer version's settings @@ -637,6 +638,8 @@ public bool TryImportFrom(AppSettings src, out string why) public void EnsureDefaults() { + CrossCooling ??= new(); + CrossCooling.Normalize(); _initialised = true; // from here on this instance may be saved (see Save) DashItem.Sanitize(Dashboard); if (DashboardVersion < 1) { Dashboard = DashItem.DefaultLayout(); DashboardVersion = DashItem.FormatVersion; } @@ -796,6 +799,7 @@ bool ValidAction(string a) => /// public void ImportFrom(AppSettings src) { + CrossCooling = src.CrossCooling?.Clone() ?? new(); Language = src.Language; HotkeysEnabled = src.HotkeysEnabled; Hotkeys.Clear(); @@ -943,6 +947,7 @@ public AppSettings Clone() ProfileOnAC = ProfileOnAC, ProfileOnBattery = ProfileOnBattery, ChargeLimit = ChargeLimit, + CrossCooling = CrossCooling.Clone(), StatusOnTop = StatusOnTop, ExperimentalEnabled = ExperimentalEnabled, ExperimentalWriteFw = new List(ExperimentalWriteFw), diff --git a/Core/CrossCooling.cs b/Core/CrossCooling.cs new file mode 100644 index 0000000..9dfeadc --- /dev/null +++ b/Core/CrossCooling.cs @@ -0,0 +1,143 @@ +using System.Text.Json.Serialization; + +namespace GhostDeck; + +public enum CrossCoolingMode { Off, CpuToGpu, GpuToCpu, Both } +public enum CoolingMix { Maximum, Average, WeightedAverage, PriorityBoost } + +/// Portable cooling preferences, including the user's saved activation choice. +public sealed class CrossCoolingSettings +{ + public bool Enabled { get; set; } + public CrossCoolingMode Mode { get; set; } + public CoolingMix Algorithm { get; set; } + public int CpuWeight { get; set; } = 50; + public int GpuWeight { get; set; } = 50; + public int BoostPercent { get; set; } = 100; + public int SamplingSeconds { get; set; } = 2; + public int UpdateSeconds { get; set; } = 5; + public int Threshold { get; set; } = 5; + public int IncreaseHysteresis { get; set; } = 0; + public int DecreaseHysteresis { get; set; } = 5; + public int DecreaseStep { get; set; } = 5; + public bool Smoothing { get; set; } + [JsonExtensionData] public Dictionary? Extra { get; set; } + + public CrossCoolingSettings Clone() => new() + { + Enabled = Enabled, Mode = Mode, Algorithm = Algorithm, CpuWeight = CpuWeight, GpuWeight = GpuWeight, + BoostPercent = BoostPercent, SamplingSeconds = SamplingSeconds, UpdateSeconds = UpdateSeconds, + Threshold = Threshold, IncreaseHysteresis = IncreaseHysteresis, DecreaseHysteresis = DecreaseHysteresis, + DecreaseStep = DecreaseStep, Smoothing = Smoothing, Extra = Extra == null ? null : new(Extra), + }; + + public void Normalize() + { + if (!Enum.IsDefined(Mode)) Mode = CrossCoolingMode.Off; + if (Mode == CrossCoolingMode.Off) Enabled = false; + if (!Enum.IsDefined(Algorithm)) Algorithm = CoolingMix.Maximum; + CpuWeight = Math.Clamp(CpuWeight, 0, 100); GpuWeight = Math.Clamp(GpuWeight, 0, 100); + if (CpuWeight + GpuWeight == 0) { CpuWeight = 50; GpuWeight = 50; } + BoostPercent = Math.Clamp(BoostPercent, 0, 100); + SamplingSeconds = Math.Clamp(SamplingSeconds, 1, 10); + UpdateSeconds = Math.Clamp(UpdateSeconds, 5, 60); + Threshold = Math.Clamp(Threshold, 1, 20); + IncreaseHysteresis = Math.Clamp(IncreaseHysteresis, 0, 10); + DecreaseHysteresis = Math.Clamp(DecreaseHysteresis, 0, 20); + DecreaseStep = Math.Clamp(DecreaseStep, 1, 20); + } +} + +public readonly record struct CoolingDemand(double CpuOriginal, double GpuOriginal, double Mixed, + double CpuTarget, double GpuTarget); + +/// Pure demand arithmetic. Values use the device's scale, which can reach 150%. +public static class CrossCooling +{ + public static CoolingDemand Calculate(double cpu, double gpu, int max, CrossCoolingSettings s) + { + if (!double.IsFinite(cpu) || !double.IsFinite(gpu) || max <= 0) + throw new ArgumentOutOfRangeException(nameof(cpu)); + if (!Enum.IsDefined(s.Mode) || !Enum.IsDefined(s.Algorithm)) throw new ArgumentException("Invalid mode or algorithm"); + cpu = Math.Clamp(cpu, 0, max); gpu = Math.Clamp(gpu, 0, max); + if (s.CpuWeight is < 0 or > 100 || s.GpuWeight is < 0 or > 100 || s.CpuWeight + s.GpuWeight == 0) + throw new ArgumentException("Weights must be between 0 and 100 with a positive sum"); + if (s.BoostPercent is < 0 or > 100) throw new ArgumentOutOfRangeException(nameof(s.BoostPercent)); + double mix = s.Algorithm switch + { + CoolingMix.Maximum => Math.Max(cpu, gpu), + CoolingMix.Average => (cpu + gpu) / 2, + CoolingMix.WeightedAverage => (s.CpuWeight * cpu + s.GpuWeight * gpu) / (s.CpuWeight + s.GpuWeight), + _ => Math.Max(cpu, gpu), // directional boost is evaluated separately for each target + }; + double Target(double own, double other) => Math.Clamp(s.Algorithm == CoolingMix.PriorityBoost + ? own + s.BoostPercent / 100.0 * Math.Max(0, other - own) : Math.Max(own, mix), own, max); + return new(cpu, gpu, mix, + s.Mode is CrossCoolingMode.GpuToCpu or CrossCoolingMode.Both ? Target(cpu, gpu) : cpu, + s.Mode is CrossCoolingMode.CpuToGpu or CrossCoolingMode.Both ? Target(gpu, cpu) : gpu); + } + + public static bool ValidTemperature(double? t) => t is > 0 and <= 115 && double.IsFinite(t.Value); + + public static bool ValidCurve(int[] temps, int[] speeds, int max) => max > 0 && temps.Length == 6 && speeds.Length == 6 && + temps.All(t => t is >= 0 and <= 115) && speeds.All(s => s >= 0 && s <= max) && + temps.Zip(temps.Skip(1)).All(p => p.First <= p.Second) && + speeds.Zip(speeds.Skip(1)).All(p => p.First <= p.Second); + + /// Keeps every original node and the monotonic constraint. + public static int[] Floor(int[] speeds, double demand, int max) + { + if (!double.IsFinite(demand) || speeds.Length != 6 || speeds.Any(s => s < 0 || s > max) || + speeds.Zip(speeds.Skip(1)).Any(p => p.First > p.Second)) throw new ArgumentException("Invalid speed table"); + int floor = (int)Math.Ceiling(Math.Clamp(demand, 0, max)); + return speeds.Select(s => Math.Max(s, floor)).ToArray(); + } +} + +public sealed record CoolingPlan(CoolingDemand Demand, int[] CpuTable, int[] GpuTable, bool PlanChanged); + +/// +/// Stateful, clock-injected floor scheduling. Hardware ownership belongs to CrossCoolingController. +/// +public sealed class CrossCoolingScheduler +{ + private double? _cpu, _gpu; + private int[]? _cpuTable, _gpuTable; + private DateTimeOffset? _last; + public DateTimeOffset? LastPlan => _last; + + public void Reset() { _cpu = _gpu = null; _cpuTable = _gpuTable = null; _last = null; } + + public CoolingPlan? Sample(double? cpu, double? gpu, DateTimeOffset sampled, DateTimeOffset now, + int[] ct, int[] cs, int[] gt, int[] gs, int max, CrossCoolingSettings s, + bool supported = true, bool singleFan = false, bool conflict = false, bool cancelled = false) + { + if (!supported || singleFan || conflict || cancelled || !CrossCooling.ValidTemperature(cpu) || !CrossCooling.ValidTemperature(gpu) || + now < sampled || (now - sampled).TotalSeconds > Math.Max(6, s.SamplingSeconds * 3) || + !CrossCooling.ValidCurve(ct, cs, max) || !CrossCooling.ValidCurve(gt, gs, max)) + { Reset(); return null; } + double Smooth(double raw, double? old) => !s.Smoothing || old == null || raw >= old ? raw : old.Value + .35 * (raw - old.Value); + _cpu = Smooth(cpu!.Value, _cpu); _gpu = Smooth(gpu!.Value, _gpu); + double dc = CurveModel.SpeedAt(ct, cs, (float)cpu.Value), dg = CurveModel.SpeedAt(gt, gs, (float)gpu.Value); + var d = CrossCooling.Calculate(CurveModel.SpeedAt(ct, cs, (float)_cpu), CurveModel.SpeedAt(gt, gs, (float)_gpu), max, s); + d = d with { CpuOriginal = dc, GpuOriginal = dg, CpuTarget = Math.Max(dc, d.CpuTarget), GpuTarget = Math.Max(dg, d.GpuTarget) }; + if (s.Mode == CrossCoolingMode.Off) + { Reset(); return new(new(dc, dg, d.Mixed, dc, dg), (int[])cs.Clone(), (int[])gs.Clone(), false); } + // Raise only the selected table. Own demand is already encoded by its original curve. + int[] c = s.Mode is CrossCoolingMode.GpuToCpu or CrossCoolingMode.Both ? CrossCooling.Floor(cs, d.CpuTarget, max) : (int[])cs.Clone(); + int[] g = s.Mode is CrossCoolingMode.CpuToGpu or CrossCoolingMode.Both ? CrossCooling.Floor(gs, d.GpuTarget, max) : (int[])gs.Clone(); + int[] Ease(int[] next, int[]? old) + { + if (old == null) return next; + return next.Select((v, i) => v >= old[i] ? (v - old[i] >= s.IncreaseHysteresis ? v : old[i]) + : old[i] - v > s.DecreaseHysteresis ? Math.Max(v, old[i] - s.DecreaseStep) : old[i]).ToArray(); + } + if (s.Mode is CrossCoolingMode.GpuToCpu or CrossCoolingMode.Both) c = Ease(c, _cpuTable); + if (s.Mode is CrossCoolingMode.CpuToGpu or CrossCoolingMode.Both) g = Ease(g, _gpuTable); + bool Different(int[] next, int[]? old) => old == null || next.Where((v, i) => Math.Abs(v - old[i]) >= s.Threshold).Any(); + bool changed = (_last == null || (now - _last.Value).TotalSeconds >= s.UpdateSeconds) && + (Different(c, _cpuTable) || Different(g, _gpuTable)); + if (changed) { _cpuTable = c; _gpuTable = g; _last = now; } + return new(d, (int[])(_cpuTable ?? c).Clone(), (int[])(_gpuTable ?? g).Clone(), changed); + } +} diff --git a/Core/CrossCoolingController.cs b/Core/CrossCoolingController.cs new file mode 100644 index 0000000..9de2fb9 --- /dev/null +++ b/Core/CrossCoolingController.cs @@ -0,0 +1,147 @@ +namespace GhostDeck; + +public sealed record CoolingBaseline(FanCurvePreset Curve, byte Mode); +public readonly record struct CoolingReading(DateTimeOffset Time, HwSnapshot Hardware, byte Mode, bool Boost); +public sealed record CoolingStatus(bool Enabled, string Key, string Error = "", CoolingReading? Reading = null, + CoolingDemand? Demand = null, DateTimeOffset? LastWrite = null); + +/// Only the existing fan-table and fan-mode operations. No direct duty/PWM registers. +public interface ICrossCoolingHardware +{ + byte AdvancedMode { get; } + CoolingBaseline Capture(); + CoolingReading Read(); + void Apply(FanCurvePreset original, int[] cpuSpeeds, int[] gpuSpeeds); + void Restore(CoolingBaseline baseline); + void Automatic(); +} + +/// +/// One owner for the full read/calculate/write transaction. External EC sessions synchronously +/// suspend it before starting, so diagnostics/profile writes cannot overlap a pending cooling write. +/// A failed restoration retains its baseline for retry; a native-auto fallback is attempted too. +/// +public sealed class CrossCoolingController : IDisposable +{ + private readonly object _gate = new(); + private readonly ICrossCoolingHardware _hardware; + private readonly int _max; + private readonly Action _log; + private readonly CrossCoolingScheduler _scheduler = new(); + private CrossCoolingSettings _settings = new(); + private CoolingBaseline? _baseline; + private bool _dirty, _disposed, _suspended; + private CoolingStatus _status = new(false, "cc_disabled"); + public CrossCoolingController(ICrossCoolingHardware hardware, int max, Action? log = null) + { _hardware = hardware; _max = max; _log = log ?? ((_, _) => { }); } + + public CoolingStatus Status => Volatile.Read(ref _status); + public FanCurvePreset? Baseline { get { lock (_gate) return _baseline?.Curve.Clone(); } } + + public void Configure(CrossCoolingSettings settings, bool enabled) + { + lock (_gate) + { + if (_disposed) return; + var next = settings.Clone(); next.Normalize(); + if (_status.Enabled && enabled && next.Mode != CrossCoolingMode.Off && _status.Key != "cc_restore_failed") + { + // Slider changes keep the current schedule; dragging cannot bypass the write interval. + _settings = next; + return; + } + bool restored = Restore(); + _settings = next; + bool on = enabled && _settings.Mode != CrossCoolingMode.Off; + _suspended = false; + _status = new(on, restored ? on ? "cc_starting" : "cc_disabled" : "cc_restore_failed", _status.Error); + _log(on ? "Cross-Cooling enabled" : "Cross-Cooling disabled", _settings.Mode + ", " + _settings.Algorithm); + } + } + + public void Tick(DateTimeOffset? now = null, string? blocked = null) + { + lock (_gate) + { + if (_disposed) return; + if (_suspended) return; + if (!_status.Enabled || blocked != null) + { + bool ok = Restore(); + if (ok && (_status.Enabled || _status.Key == "cc_restore_failed")) + _status = _status with { Key = _status.Enabled ? blocked ?? "cc_disabled" : "cc_disabled", Error = "", Demand = null }; + return; + } + try + { + // Retry an earlier failed restoration before attempting any new control. + if (_status.Key == "cc_restore_failed" && !Restore()) return; + var reading = _hardware.Read(); + var hw = reading.Hardware; + _status = _status with { Reading = reading }; + if (reading.Boost) { Suspend("cc_boost_paused"); return; } + if (_dirty && reading.Mode != _hardware.AdvancedMode) + { + // Keep the newly selected native mode when relinquishing ownership. + if (_baseline != null) _baseline = _baseline with { Mode = reading.Mode }; + Suspend("cc_mode_changed"); _status = _status with { Enabled = false }; return; + } + _baseline ??= _hardware.Capture(); + var c = _baseline.Curve; + var checkedAt = now ?? DateTimeOffset.UtcNow; + var plan = _scheduler.Sample(hw.CpuTemp, hw.GpuTemp, reading.Time, checkedAt, + c.CpuTemp, c.CpuSpeed, c.GpuTemp, c.GpuSpeed, _max, _settings); + if (plan == null) { Suspend("cc_sensor_paused"); return; } + if (plan.PlanChanged) + { + _dirty = true; // even a partially failed table write must be restored + _hardware.Apply(c, plan.CpuTable, plan.GpuTable); + _status = _status with { LastWrite = checkedAt }; + _log("Cross-Cooling applied", $"CPU {plan.Demand.CpuTarget:0.#}%, GPU {plan.Demand.GpuTarget:0.#}%"); + } + _status = _status with { Key = "cc_running", Error = "", Demand = plan.Demand }; + } + catch (Exception ex) + { + _log("Cross-Cooling failed", ex.Message); + Restore(); + // A write/read exception disarms until the user explicitly retries. + _status = _status with { Enabled = false, Key = _dirty ? "cc_restore_failed" : "cc_failed", Error = ex.Message, Demand = null }; + } + } + } + + public void Suspend(string reason = "cc_session_paused") + { + lock (_gate) + { + _suspended = true; + if (Restore()) _status = _status with { Key = reason, Demand = null, Error = "" }; + } + } + + public void Resume() { lock (_gate) { if (!_disposed) _suspended = false; } } + + private bool Restore() + { + if (_baseline == null) { _scheduler.Reset(); return true; } + try + { + if (_dirty) { _hardware.Restore(_baseline); _log("Cross-Cooling restored", "Original tables and fan mode"); } + _baseline = null; _dirty = false; _scheduler.Reset(); + return true; + } + catch (Exception ex) + { + _log("Cross-Cooling restore failed", ex.Message); + try { _hardware.Automatic(); } catch (Exception fallback) { _log("Cross-Cooling auto fallback failed", fallback.Message); } + _status = _status with { Key = "cc_restore_failed", Error = ex.Message, Demand = null }; + return false; + } + } + + public void Dispose() + { + lock (_gate) { if (_disposed) return; _status = _status with { Enabled = false }; Restore(); _disposed = true; } + } +} diff --git a/Core/EcCrossCoolingHardware.cs b/Core/EcCrossCoolingHardware.cs new file mode 100644 index 0000000..f0809d8 --- /dev/null +++ b/Core/EcCrossCoolingHardware.cs @@ -0,0 +1,46 @@ +namespace GhostDeck; + +/// Uses only the same device-profile tables and mode path as the existing curve editor. +public sealed class EcCrossCoolingHardware : ICrossCoolingHardware +{ + private readonly DeviceProfile _device; + private readonly FanCurveSpec _spec; + private readonly byte _automatic; + public byte AdvancedMode => _spec.AdvancedModeValue; + public EcCrossCoolingHardware(DeviceProfile device) + { + _device = device; + _spec = device.FanCurve ?? throw new ArgumentException("No fan tables"); + if (_spec.SingleFan || _spec.Points != 6 || Ec.OnBackupPath) throw new ArgumentException("No dual fan method interface"); + _automatic = device.Recipes[ProfileId.Balanced].First(p => p.Item1 == device.FanMode).Item2; + } + + public CoolingBaseline Capture() + { + var curve = Ec.ReadFanCurve(_device) ?? throw new InvalidOperationException("Fan tables could not be read"); + return new(new FanCurvePreset { CpuTemp = curve.cpuTemp, CpuSpeed = curve.cpuSpeed, + GpuTemp = curve.gpuTemp, GpuSpeed = curve.gpuSpeed }, Ec.ReadByte(_device.FanMode)); + } + + public CoolingReading Read() + { + var started = DateTimeOffset.UtcNow; + if (!Ec.TryReadHw(_device, out var hw)) throw new InvalidOperationException("Fan telemetry could not be read"); + return new(started, hw, Ec.ReadByte(_device.FanMode), Ec.GetCoolerBoost(_device)); + } + + public void Apply(FanCurvePreset original, int[] cpuSpeeds, int[] gpuSpeeds) + { + Ec.WriteFanCurve(_device, original.CpuTemp, cpuSpeeds, original.GpuTemp, gpuSpeeds); + if (Ec.ReadByte(_device.FanMode) != AdvancedMode) Ec.SetFanMode(_device, AdvancedMode); + } + + public void Restore(CoolingBaseline baseline) + { + var c = baseline.Curve; + Ec.WriteFanCurve(_device, c.CpuTemp, c.CpuSpeed, c.GpuTemp, c.GpuSpeed); + Ec.SetFanMode(_device, baseline.Mode); + } + + public void Automatic() => Ec.SetFanMode(_device, _automatic); +} diff --git a/Core/Lang.cs b/Core/Lang.cs index 086a94a..9f264ac 100644 --- a/Core/Lang.cs +++ b/Core/Lang.cs @@ -1,4 +1,4 @@ -namespace GhostDeck; +namespace GhostDeck; /// Prosta lokalizacja. Kolejnosc jezykow = indeksy w tablicach. public static class Lang @@ -71,9 +71,67 @@ private static Dictionary Build() L12(m); L13(m); L14(m); + CrossCoolingText(m); return m; } + private static void CrossCoolingText(Dictionary m) + { + m["cc_graph"] = new[] { "Estimated curve → calculated target", "Szacowana krzywa → obliczony cel", "Geschätzte Kurve → berechnetes Ziel", "Courbe estimée → cible calculée", "Curva estimada → objetivo calculado", "估算曲线 → 计算目标", "Curva estimada → alvo calculado", "Расчётная кривая → расчётная цель", "推定カーブ → 計算目標", "예상 곡선 → 계산 목표", "估算曲線 → 計算目標", "Tahmini eğri → hesaplanan hedef", "Đường cong ước tính → mục tiêu tính toán", "Perkiraan kurva → target terhitung", "Curva stimata → obiettivo calcolato" }; + m["cc_control_help"] = new[] { "Combines CPU/GPU curve demand and controls fan tables in Advanced mode.", "Łączy zapotrzebowanie CPU/GPU i steruje tabelami w trybie zaawansowanym.", "Kombiniert CPU/GPU-Kurvenbedarf und steuert Lüftertabellen im erweiterten Modus.", "Combine les besoins CPU/GPU et commande les tables en mode avancé.", "Combina la demanda CPU/GPU y controla las tablas en modo avanzado.", "合并 CPU/GPU 曲线需求,在高级模式下控制风扇表。", "Combina a demanda CPU/GPU e controla as tabelas no modo avançado.", "Объединяет запросы CPU/GPU и управляет таблицами в расширенном режиме.", "CPU/GPU のカーブ需要を統合し、詳細モードでファンテーブルを制御します。", "CPU/GPU 곡선 요구량을 결합하고 고급 모드에서 팬 테이블을 제어합니다.", "合併 CPU/GPU 曲線需求,在進階模式下控制風扇表。", "CPU/GPU eğri talebini birleştirir ve gelişmiş modda fan tablolarını kontrol eder.", "Kết hợp nhu cầu CPU/GPU và điều khiển bảng quạt ở chế độ nâng cao.", "Menggabungkan kebutuhan kurva CPU/GPU dan mengontrol tabel kipas dalam mode lanjutan.", "Combina la richiesta CPU/GPU e controlla le tabelle in modalità avanzata." }; + m["cc_starting"] = new[] { "Starting control...", "Uruchamianie...", "Steuerung startet...", "Démarrage...", "Iniciando...", "正在启动控制...", "Iniciando...", "Запуск управления...", "制御を開始中...", "제어 시작 중...", "正在啟動控制...", "Kontrol başlatılıyor...", "Đang bắt đầu...", "Memulai kontrol...", "Avvio del controllo..." }; + m["cc_running"] = new[] { "Active - controlling fan tables", "Aktywne - sterowanie tabelami", "Aktiv - Lüftertabellen werden gesteuert", "Actif - commande des tables", "Activo - control de tablas", "已启用 - 正在控制风扇表", "Ativo - controlando tabelas", "Активно - управление таблицами", "動作中 - ファンテーブルを制御", "활성 - 팬 테이블 제어 중", "已啟用 - 正在控制風扇表", "Etkin - fan tabloları kontrol ediliyor", "Đang điều khiển bảng quạt", "Aktif - mengontrol tabel kipas", "Attivo - controllo delle tabelle" }; + m["cc_session_paused"] = new[] { "Paused for another hardware operation", "Wstrzymane dla innej operacji", "Für anderen Hardwarezugriff pausiert", "Suspendu pour une autre opération", "Pausado por otra operación", "已暂停,其他硬件操作正在进行", "Pausado para outra operação", "Пауза для другой операции", "他のハードウェア操作のため一時停止", "다른 하드웨어 작업으로 일시 중지", "已暫停,其他硬體操作正在進行", "Başka donanım işlemi için duraklatıldı", "Tạm dừng cho thao tác phần cứng khác", "Dijeda untuk operasi perangkat keras lain", "Sospeso per un’altra operazione hardware" }; + m["cc_editor_paused"] = new[] { "Paused while editing fan curves", "Wstrzymane podczas edycji krzywych", "Während der Kurvenbearbeitung pausiert", "Suspendu pendant la modification des courbes", "Pausado al editar curvas", "编辑风扇曲线时暂停", "Pausado durante edição das curvas", "Пауза при редактировании кривых", "カーブ編集中は一時停止", "팬 곡선 편집 중 일시 중지", "編輯風扇曲線時暫停", "Fan eğrileri düzenlenirken duraklatıldı", "Tạm dừng khi chỉnh sửa đường cong", "Dijeda saat mengedit kurva kipas", "Sospeso durante la modifica delle curve" }; + m["cc_unsupported"] = new[] { "Unavailable - requires a supported dual-fan EC interface", "Niedostępne - wymagany obsługiwany interfejs dwóch wentylatorów", "Nicht verfügbar - unterstützte EC-Schnittstelle für zwei Lüfter erforderlich", "Indisponible - interface EC à deux ventilateurs requise", "No disponible - requiere interfaz EC compatible de dos ventiladores", "不可用 - 需要受支持的双风扇 EC 接口", "Indisponível - requer interface EC compatível com duas ventoinhas", "Недоступно - нужен поддерживаемый EC с двумя вентиляторами", "利用不可 - 対応するデュアルファン EC が必要", "사용 불가 - 지원되는 듀얼 팬 EC 인터페이스 필요", "無法使用 - 需要支援的雙風扇 EC 介面", "Kullanılamıyor - desteklenen çift fan EC arabirimi gerekir", "Không khả dụng - cần giao diện EC hai quạt được hỗ trợ", "Tidak tersedia - memerlukan antarmuka EC dua kipas yang didukung", "Non disponibile - richiede un’interfaccia EC compatibile a due ventole" }; + m["cc_write_blocked"] = new[] { "Unavailable - hardware writes are not enabled for this firmware", "Niedostępne - zapis sprzętowy wyłączony dla firmware", "Nicht verfügbar - Hardwarezugriff für diese Firmware deaktiviert", "Indisponible - écritures désactivées pour ce firmware", "No disponible - escrituras desactivadas para este firmware", "不可用 - 此固件未启用硬件写入", "Indisponível - gravações desativadas para este firmware", "Недоступно - запись для этой прошивки отключена", "利用不可 - このファームウェアへの書き込みは無効", "사용 불가 - 이 펌웨어의 하드웨어 쓰기가 비활성화됨", "無法使用 - 此韌體未啟用硬體寫入", "Kullanılamıyor - bu firmware için yazma etkin değil", "Không khả dụng - chưa bật ghi phần cứng cho firmware này", "Tidak tersedia - penulisan perangkat keras belum aktif untuk firmware ini", "Non disponibile - scritture disabilitate per questo firmware" }; + m["cc_silent_paused"] = new[] { "Paused in Silent mode", "Wstrzymane w trybie cichym", "Im Lautlos-Modus pausiert", "Suspendu en mode silencieux", "Pausado en modo silencioso", "静音模式下暂停", "Pausado no modo silencioso", "Пауза в тихом режиме", "静音モードで一時停止", "저소음 모드에서 일시 중지", "靜音模式下暫停", "Sessiz modda duraklatıldı", "Tạm dừng ở chế độ im lặng", "Dijeda dalam mode senyap", "Sospeso in modalità silenziosa" }; + m["cc_boost_paused"] = new[] { "Paused - Fan Boost is active", "Wstrzymane - Fan Boost aktywny", "Pausiert - Fan Boost aktiv", "Suspendu - Fan Boost actif", "Pausado - Fan Boost activo", "已暂停 - 风扇增强已启用", "Pausado - Fan Boost ativo", "Пауза - активен Fan Boost", "一時停止 - Fan Boost 有効", "일시 중지 - Fan Boost 활성", "已暫停 - 風扇增強已啟用", "Duraklatıldı - Fan Boost etkin", "Tạm dừng - Fan Boost đang bật", "Dijeda - Fan Boost aktif", "Sospeso - Fan Boost attivo" }; + m["cc_mode_changed"] = new[] { "Stopped - native fan mode changed", "Zatrzymane - zmieniono tryb wentylatora", "Gestoppt - nativer Lüftermodus geändert", "Arrêté - mode du ventilateur modifié", "Detenido - cambió el modo nativo", "已停止 - 原生风扇模式已更改", "Parado - modo nativo alterado", "Остановлено - изменён штатный режим", "停止 - 標準ファンモードが変更されました", "중지 - 기본 팬 모드 변경됨", "已停止 - 原生風扇模式已變更", "Durduruldu - yerel fan modu değişti", "Đã dừng - chế độ quạt gốc thay đổi", "Dihentikan - mode kipas asli berubah", "Arrestato - modalità nativa modificata" }; + m["cc_sensor_paused"] = new[] { "Paused - missing, stale or invalid temperature/curve data", "Wstrzymane - brak lub nieprawidłowe dane temperatur/krzywych", "Pausiert - fehlende, veraltete oder ungültige Temperatur-/Kurvendaten", "Suspendu - données de température/courbe absentes ou invalides", "Pausado - datos de temperatura/curva ausentes o inválidos", "已暂停 - 温度或曲线数据缺失、过期或无效", "Pausado - dados de temperatura/curva ausentes ou inválidos", "Пауза - нет свежих допустимых температур или кривых", "一時停止 - 温度・カーブデータが未取得、古い、または無効", "일시 중지 - 온도/곡선 데이터 누락, 오래됨 또는 유효하지 않음", "已暫停 - 溫度或曲線資料缺失、過期或無效", "Duraklatıldı - sıcaklık/eğri verileri eksik, eski veya geçersiz", "Tạm dừng - dữ liệu nhiệt độ/đường cong thiếu, cũ hoặc không hợp lệ", "Dijeda - data suhu/kurva hilang, usang, atau tidak valid", "Sospeso - dati di temperatura/curva mancanti, vecchi o non validi" }; + m["cc_restore_failed"] = new[] { "Restoration failed - retrying; native Auto fallback requested", "Przywracanie nieudane - ponawianie; żądanie trybu Auto", "Wiederherstellung fehlgeschlagen - erneuter Versuch; Auto angefordert", "Restauration échouée - nouvelle tentative ; mode Auto demandé", "Error al restaurar - reintentando; modo Auto solicitado", "恢复失败 - 正在重试;已请求原生自动模式", "Falha ao restaurar - tentando novamente; Auto solicitado", "Ошибка восстановления - повтор; запрошен режим Авто", "復元失敗 - 再試行中、標準自動モードを要求", "복원 실패 - 재시도 중, 기본 자동 모드 요청됨", "還原失敗 - 正在重試;已請求原生自動模式", "Geri yükleme başarısız - yeniden deneniyor; Otomatik mod istendi", "Khôi phục thất bại - đang thử lại; đã yêu cầu chế độ Tự động", "Pemulihan gagal - mencoba lagi; mode Otomatis diminta", "Ripristino fallito - nuovo tentativo; richiesta modalità Auto" }; + m["cc_failed"] = new[] { "Control stopped after a hardware error - enable again to retry", "Sterowanie zatrzymane po błędzie - włącz ponownie", "Nach Hardwarefehler gestoppt - zum Wiederholen erneut aktivieren", "Commande arrêtée après erreur - réactivez pour réessayer", "Control detenido por error - activa de nuevo para reintentar", "硬件错误后控制已停止 - 重新启用以重试", "Controle parado após erro - ative novamente", "Управление остановлено из-за ошибки - включите снова", "ハードウェアエラーで停止 - 再度有効化して再試行", "하드웨어 오류로 중지 - 다시 활성화하여 재시도", "硬體錯誤後控制已停止 - 重新啟用以重試", "Donanım hatası nedeniyle durdu - yeniden etkinleştirin", "Điều khiển dừng do lỗi - bật lại để thử lại", "Kontrol dihentikan karena kesalahan - aktifkan lagi untuk mencoba", "Controllo arrestato per errore - riattiva per riprovare" }; + m["cc_temperatures"] = new[] { "CPU {0}°C · GPU {1}°C", "CPU {0}°C · GPU {1}°C", "CPU {0}°C · GPU {1}°C", "CPU {0}°C · GPU {1}°C", "CPU {0}°C · GPU {1}°C", "CPU {0}°C · GPU {1}°C", "CPU {0}°C · GPU {1}°C", "CPU {0}°C · GPU {1}°C", "CPU {0}°C · GPU {1}°C", "CPU {0}°C · GPU {1}°C", "CPU {0}°C · GPU {1}°C", "CPU {0}°C · GPU {1}°C", "CPU {0}°C · GPU {1}°C", "CPU {0}°C · GPU {1}°C", "CPU {0}°C · GPU {1}°C" }; + m["cc_title"] = new[] { "Cross-Cooling", "Chłodzenie krzyżowe", "Kreuzkühlung", "Refroidissement croisé", "Refrigeración cruzada", "交叉散热", "Resfriamento cruzado", "Перекрёстное охлаждение", "クロス冷却", "교차 냉각", "交叉散熱", "Çapraz soğutma", "Làm mát chéo", "Pendinginan silang", "Raffreddamento incrociato" }; + m["cc_enable"] = new[] { "Enable Cross-Cooling", "Włącz chłodzenie krzyżowe", "Kreuzkühlung aktivieren", "Activer le refroidissement croisé", "Activar refrigeración cruzada", "启用交叉散热", "Ativar resfriamento cruzado", "Включить перекрёстное охлаждение", "クロス冷却を有効化", "교차 냉각 활성화", "啟用交叉散熱", "Çapraz soğutmayı aç", "Bật làm mát chéo", "Aktifkan pendinginan silang", "Attiva raffreddamento incrociato" }; + m["cc_mode"] = new[] { "Operating mode", "Tryb pracy", "Betriebsart", "Mode de fonctionnement", "Modo de funcionamiento", "工作模式", "Modo de operação", "Режим работы", "動作モード", "작동 모드", "運作模式", "Çalışma modu", "Chế độ hoạt động", "Mode operasi", "Modalità operativa" }; + m["cc_off"] = new[] { "Off - original behavior", "Wył. - oryginalne działanie", "Aus - ursprüngliches Verhalten", "Désactivé - comportement d'origine", "Desactivado - comportamiento original", "关闭 - 原有行为", "Desligado - comportamento original", "Выкл. - исходное поведение", "オフ - 元の動作", "꺼짐 - 기존 동작", "關閉 - 原有行為", "Kapalı - özgün davranış", "Tắt - hoạt động ban đầu", "Mati - perilaku asli", "Disattivato - comportamento originale" }; + m["cc_cpu_gpu"] = new[] { "CPU → GPU fan", "CPU → wentylator GPU", "CPU → GPU-Lüfter", "CPU → ventilateur GPU", "CPU → ventilador GPU", "CPU → GPU 风扇", "CPU → ventoinha GPU", "CPU → вентилятор GPU", "CPU → GPU ファン", "CPU → GPU 팬", "CPU → GPU 風扇", "CPU → GPU fanı", "CPU → quạt GPU", "CPU → kipas GPU", "CPU → ventola GPU" }; + m["cc_gpu_cpu"] = new[] { "GPU → CPU fan", "GPU → wentylator CPU", "GPU → CPU-Lüfter", "GPU → ventilateur CPU", "GPU → ventilador CPU", "GPU → CPU 风扇", "GPU → ventoinha CPU", "GPU → вентилятор CPU", "GPU → CPU ファン", "GPU → CPU 팬", "GPU → CPU 風扇", "GPU → CPU fanı", "GPU → quạt CPU", "GPU → kipas CPU", "GPU → ventola CPU" }; + m["cc_both"] = new[] { "Both fans", "Oba wentylatory", "Beide Lüfter", "Les deux ventilateurs", "Ambos ventiladores", "两个风扇", "Ambas as ventoinhas", "Оба вентилятора", "両方のファン", "양쪽 팬", "兩個風扇", "Her iki fan", "Cả hai quạt", "Kedua kipas", "Entrambe le ventole" }; + m["cc_algorithm"] = new[] { "Mixing algorithm", "Algorytm mieszania", "Mischalgorithmus", "Algorithme de mélange", "Algoritmo de mezcla", "混合算法", "Algoritmo de mistura", "Алгоритм смешивания", "混合アルゴリズム", "혼합 알고리즘", "混合演算法", "Karıştırma algoritması", "Thuật toán trộn", "Algoritme pencampuran", "Algoritmo di miscelazione" }; + m["cc_max"] = new[] { "Maximum", "Maksimum", "Maximum", "Maximum", "Máximo", "最大值", "Máximo", "Максимум", "最大", "최댓값", "最大值", "En yüksek", "Tối đa", "Maksimum", "Massimo" }; + m["cc_average"] = new[] { "Average", "Średnia", "Mittelwert", "Moyenne", "Promedio", "平均值", "Média", "Среднее", "平均", "평균", "平均值", "Ortalama", "Trung bình", "Rata-rata", "Media" }; + m["cc_weighted"] = new[] { "Weighted average", "Średnia ważona", "Gewichteter Mittelwert", "Moyenne pondérée", "Promedio ponderado", "加权平均", "Média ponderada", "Взвешенное среднее", "加重平均", "가중 평균", "加權平均", "Ağırlıklı ortalama", "Trung bình có trọng số", "Rata-rata berbobot", "Media ponderata" }; + m["cc_priority"] = new[] { "Priority Boost", "Wzmocnienie priorytetowe", "Prioritätsverstärkung", "Renfort prioritaire", "Refuerzo prioritario", "优先增强", "Reforço prioritário", "Приоритетное усиление", "優先ブースト", "우선 부스트", "優先增強", "Öncelik desteği", "Tăng cường ưu tiên", "Peningkatan prioritas", "Potenziamento prioritario" }; + m["cc_advanced"] = new[] { "Advanced Cross-Cooling Settings ▾", "Zaawansowane ustawienia chłodzenia ▾", "Erweiterte Kreuzkühlung-Einstellungen ▾", "Réglages avancés du refroidissement croisé ▾", "Ajustes avanzados de refrigeración cruzada ▾", "高级交叉散热设置 ▾", "Configurações avançadas de resfriamento ▾", "Дополнительные настройки охлаждения ▾", "クロス冷却の詳細設定 ▾", "고급 교차 냉각 설정 ▾", "進階交叉散熱設定 ▾", "Gelişmiş çapraz soğutma ayarları ▾", "Cài đặt làm mát chéo nâng cao ▾", "Pengaturan pendinginan silang lanjutan ▾", "Impostazioni avanzate raffreddamento incrociato ▾" }; + m["cc_sampling"] = new[] { "Temperature sampling interval", "Odstęp próbkowania temperatur", "Temperatur-Abtastintervall", "Intervalle d'échantillonnage", "Intervalo de muestreo", "温度采样间隔", "Intervalo de amostragem", "Интервал измерения температуры", "温度サンプリング間隔", "온도 샘플링 간격", "溫度取樣間隔", "Sıcaklık örnekleme aralığı", "Chu kỳ lấy mẫu nhiệt độ", "Interval sampel suhu", "Intervallo di campionamento" }; + m["cc_interval"] = new[] { "Minimum table update interval", "Minimalny odstęp zmian tabel", "Minimales Tabellenintervall", "Intervalle minimal des tables", "Intervalo mínimo de tablas", "最小表更新间隔", "Intervalo mínimo das tabelas", "Мин. интервал таблиц", "テーブル更新の最小間隔", "최소 테이블 갱신 간격", "最小表格更新間隔", "En az tablo güncelleme aralığı", "Chu kỳ cập nhật bảng tối thiểu", "Interval pembaruan tabel minimum", "Intervallo minimo tabelle" }; + m["cc_threshold"] = new[] { "Demand change threshold", "Próg zmiany zapotrzebowania", "Bedarfsänderungsschwelle", "Seuil de variation de demande", "Umbral de cambio de demanda", "需求变化阈值", "Limiar de mudança de demanda", "Порог изменения потребности", "需要変化のしきい値", "요구량 변경 임계값", "需求變化閾值", "Talep değişim eşiği", "Ngưỡng thay đổi nhu cầu", "Ambang perubahan kebutuhan", "Soglia di variazione richiesta" }; + m["cc_increase"] = new[] { "Increase hysteresis", "Histereza wzrostu", "Hysterese beim Anstieg", "Hystérésis de hausse", "Histéresis de subida", "上升滞后", "Histerese de aumento", "Гистерезис повышения", "上昇ヒステリシス", "상승 히스테리시스", "上升遲滯", "Artış histerezisi", "Độ trễ tăng", "Histeresis kenaikan", "Isteresi di aumento" }; + m["cc_decrease"] = new[] { "Decrease hysteresis", "Histereza spadku", "Hysterese beim Abfall", "Hystérésis de baisse", "Histéresis de bajada", "下降滞后", "Histerese de redução", "Гистерезис понижения", "下降ヒステリシス", "하강 히스테리시스", "下降遲滯", "Azalış histerezisi", "Độ trễ giảm", "Histeresis penurunan", "Isteresi di diminuzione" }; + m["cc_step"] = new[] { "Maximum decrease per update", "Maksymalny spadek na zmianę", "Maximale Absenkung pro Änderung", "Baisse maximale par mise à jour", "Bajada máxima por actualización", "每次更新最大降幅", "Redução máxima por atualização", "Макс. снижение за обновление", "更新ごとの最大下降幅", "갱신당 최대 감소량", "每次更新最大降幅", "Güncelleme başına en çok azalış", "Mức giảm tối đa mỗi lần cập nhật", "Penurunan maksimum per pembaruan", "Diminuzione massima per aggiornamento" }; + m["cc_smoothing"] = new[] { "Smooth falling temperatures (rises are immediate)", "Wygładzaj spadki temperatur (wzrost natychmiast)", "Fallende Temperaturen glätten (Anstieg sofort)", "Lisser les baisses de température (hausse immédiate)", "Suavizar bajadas de temperatura (subidas inmediatas)", "平滑降温(升温立即响应)", "Suavizar quedas de temperatura (subidas imediatas)", "Сглаживать снижение температуры (рост сразу)", "温度下降を平滑化(上昇は即時)", "온도 하강 평활화 (상승은 즉시)", "平滑降溫(升溫立即回應)", "Sıcaklık düşüşlerini yumuşat (artışlar anlık)", "Làm mượt nhiệt độ giảm (tăng tức thì)", "Haluskan penurunan suhu (kenaikan langsung)", "Smussa le temperature in calo (aumenti immediati)" }; + m["cc_weights"] = new[] { "Weight preset", "Zestaw wag", "Gewichtungsvorgabe", "Préréglage des poids", "Preajuste de pesos", "权重预设", "Predefinição de pesos", "Набор весов", "重みプリセット", "가중치 사전 설정", "權重預設", "Ağırlık ön ayarı", "Mẫu trọng số", "Preset bobot", "Preimpostazione pesi" }; + m["cc_cpu_priority"] = new[] { "CPU Priority", "Priorytet CPU", "CPU-Priorität", "Priorité CPU", "Prioridad CPU", "CPU 优先", "Prioridade CPU", "Приоритет CPU", "CPU 優先", "CPU 우선", "CPU 優先", "CPU önceliği", "Ưu tiên CPU", "Prioritas CPU", "Priorità CPU" }; + m["cc_gpu_priority"] = new[] { "GPU Priority", "Priorytet GPU", "GPU-Priorität", "Priorité GPU", "Prioridad GPU", "GPU 优先", "Prioridade GPU", "Приоритет GPU", "GPU 優先", "GPU 우선", "GPU 優先", "GPU önceliği", "Ưu tiên GPU", "Prioritas GPU", "Priorità GPU" }; + m["cc_balanced"] = new[] { "Balanced", "Zrównoważone", "Ausgeglichen", "Équilibré", "Equilibrado", "均衡", "Equilibrado", "Сбалансировано", "バランス", "균형", "均衡", "Dengeli", "Cân bằng", "Seimbang", "Bilanciato" }; + m["cc_custom"] = new[] { "Custom", "Własne", "Benutzerdefiniert", "Personnalisé", "Personalizado", "自定义", "Personalizado", "Свой", "カスタム", "사용자 지정", "自訂", "Özel", "Tùy chỉnh", "Kustom", "Personalizzato" }; + m["cc_cpu_weight"] = new[] { "CPU weight", "Waga CPU", "CPU-Gewicht", "Poids CPU", "Peso CPU", "CPU 权重", "Peso CPU", "Вес CPU", "CPU 重み", "CPU 가중치", "CPU 權重", "CPU ağırlığı", "Trọng số CPU", "Bobot CPU", "Peso CPU" }; + m["cc_gpu_weight"] = new[] { "GPU weight", "Waga GPU", "GPU-Gewicht", "Poids GPU", "Peso GPU", "GPU 权重", "Peso GPU", "Вес GPU", "GPU 重み", "GPU 가중치", "GPU 權重", "GPU ağırlığı", "Trọng số GPU", "Bobot GPU", "Peso GPU" }; + m["cc_boost"] = new[] { "Boost factor", "Współczynnik wzmocnienia", "Verstärkungsfaktor", "Facteur de renfort", "Factor de refuerzo", "增强系数", "Fator de reforço", "Коэффициент усиления", "ブースト係数", "부스트 계수", "增強係數", "Destek katsayısı", "Hệ số tăng cường", "Faktor peningkatan", "Fattore di potenziamento" }; + m["cc_reset"] = new[] { "Reset to Defaults", "Przywróć domyślne", "Standardwerte wiederherstellen", "Rétablir les valeurs par défaut", "Restablecer valores predeterminados", "恢复默认设置", "Restaurar padrões", "Сбросить настройки", "既定値に戻す", "기본값 복원", "恢復預設值", "Varsayılanlara sıfırla", "Đặt lại mặc định", "Atur ulang ke bawaan", "Ripristina valori predefiniti" }; + m["cc_startup"] = new[] { "The enabled state and options are saved and restored when the app starts.", "Stan włączenia i opcje są zapisywane i przywracane po uruchomieniu aplikacji.", "Aktivierung und Optionen werden gespeichert und beim App-Start wiederhergestellt.", "L’activation et les options sont enregistrées et restaurées au démarrage de l’application.", "El estado de activación y las opciones se guardan y restauran al iniciar la aplicación.", "启用状态和选项已保存,并在应用启动时恢复。", "O estado de ativação e as opções são salvos e restaurados ao iniciar o aplicativo.", "Состояние включения и параметры сохраняются и восстанавливаются при запуске приложения.", "有効状態と設定を保存し、アプリ起動時に復元します。", "활성화 상태와 옵션이 저장되고 앱 시작 시 복원됩니다.", "啟用狀態和選項已儲存,並在應用程式啟動時還原。", "Etkinlik durumu ve seçenekler kaydedilir ve uygulama başlatıldığında geri yüklenir.", "Trạng thái bật và các tùy chọn được lưu và khôi phục khi ứng dụng khởi động.", "Status aktif dan opsi disimpan dan dipulihkan saat aplikasi dimulai.", "Lo stato di attivazione e le opzioni vengono salvati e ripristinati all’avvio dell’app." }; + m["cc_emergency"] = new[] { "Fan Boost overrides Cross-Cooling. Disabling restores the original tables and fan mode.", "Fan Boost ma pierwszeństwo. Wyłączenie przywraca tabele i tryb.", "Fan Boost hat Vorrang. Ausschalten stellt Tabellen und Lüftermodus wieder her.", "Fan Boost est prioritaire. Désactiver restaure les tables et le mode.", "Fan Boost tiene prioridad. Desactivar restaura las tablas y el modo.", "风扇增强优先。禁用后恢复原始风扇表和模式。", "Fan Boost tem prioridade. Desativar restaura as tabelas e o modo.", "Fan Boost имеет приоритет. Отключение восстанавливает таблицы и режим.", "Fan Boost が優先されます。無効化すると元のテーブルとモードを復元します。", "Fan Boost가 우선합니다. 비활성화하면 원래 테이블과 모드를 복원합니다.", "風扇增強優先。停用後還原原始風扇表和模式。", "Fan Boost önceliklidir. Kapatmak özgün tabloları ve modu geri yükler.", "Fan Boost được ưu tiên. Tắt sẽ khôi phục bảng và chế độ gốc.", "Fan Boost diutamakan. Menonaktifkan memulihkan tabel dan mode asli.", "Fan Boost ha priorità. Disattivare ripristina le tabelle e la modalità." }; + m["cc_disabled"] = new[] { "Off - original curves retained; no Cross-Cooling EC writes.", "Wył. - oryginalne krzywe, bez zapisów EC.", "Aus - ursprüngliche Kurven; keine Kreuzkühlung-EC-Schreibzugriffe.", "Désactivé - courbes d'origine ; aucune écriture EC.", "Desactivado - curvas originales; sin escrituras EC.", "关闭 - 保留原始曲线;无 EC 写入。", "Desligado - curvas originais; sem gravações EC.", "Выкл. - исходные кривые; без записи EC.", "オフ - 元のカーブを維持、EC 書き込みなし。", "꺼짐 - 기존 곡선 유지, EC 쓰기 없음.", "關閉 - 保留原始曲線;無 EC 寫入。", "Kapalı - özgün eğriler korunur; EC yazımı yok.", "Tắt - giữ đường cong gốc; không ghi EC.", "Mati - kurva asli dipertahankan; tanpa penulisan EC.", "Disattivato - curve originali; nessuna scrittura EC." }; + m["cc_no_sample"] = new[] { "Hardware readings unavailable", "Odczyty sprzętowe niedostępne", "Hardware-Messwerte nicht verfügbar", "Mesures matérielles indisponibles", "Lecturas de hardware no disponibles", "硬件读数不可用", "Leituras de hardware indisponíveis", "Аппаратные показания недоступны", "実機の測定値なし", "하드웨어 측정값 없음", "硬體讀數不可用", "Donanım okumaları kullanılamıyor", "Không có số đo phần cứng", "Pembacaan perangkat keras tidak tersedia", "Letture hardware non disponibili" }; + m["cc_actual"] = new[] { "Actual firmware duty / RPM: CPU {0}% / {1} RPM · GPU {2}% / {3} RPM", "Rzeczywisty odczyt / RPM: CPU {0}% / {1} RPM · GPU {2}% / {3} RPM", "Firmware-Istwert / RPM: CPU {0}% / {1} RPM · GPU {2}% / {3} RPM", "Rapport firmware réel / RPM : CPU {0}% / {1} RPM · GPU {2}% / {3} RPM", "Valor real del firmware / RPM: CPU {0}% / {1} RPM · GPU {2}% / {3} RPM", "实际固件占空比 / RPM:CPU {0}% / {1} RPM · GPU {2}% / {3} RPM", "Valor real do firmware / RPM: CPU {0}% / {1} RPM · GPU {2}% / {3} RPM", "Фактическое значение / RPM: CPU {0}% / {1} RPM · GPU {2}% / {3} RPM", "実測ファームウェア値 / RPM: CPU {0}% / {1} RPM · GPU {2}% / {3} RPM", "실제 펌웨어 값 / RPM: CPU {0}% / {1} RPM · GPU {2}% / {3} RPM", "實際韌體占空比 / RPM:CPU {0}% / {1} RPM · GPU {2}% / {3} RPM", "Gerçek firmware değeri / RPM: CPU {0}% / {1} RPM · GPU {2}% / {3} RPM", "Giá trị firmware thực / RPM: CPU {0}% / {1} RPM · GPU {2}% / {3} RPM", "Nilai firmware aktual / RPM: CPU {0}% / {1} RPM · GPU {2}% / {3} RPM", "Valore firmware reale / RPM: CPU {0}% / {1} RPM · GPU {2}% / {3} RPM" }; + m["cc_duty"] = new[] { "Firmware duty: CPU {0}% · GPU {1}% · RPM unavailable", "Odczyt firmware: CPU {0}% · GPU {1}% · RPM niedostępne", "Firmware-Wert: CPU {0}% · GPU {1}% · RPM nicht verfügbar", "Rapport firmware : CPU {0}% · GPU {1}% · RPM indisponibles", "Valor del firmware: CPU {0}% · GPU {1}% · RPM no disponibles", "固件占空比:CPU {0}% · GPU {1}% · RPM 不可用", "Valor do firmware: CPU {0}% · GPU {1}% · RPM indisponível", "Значение прошивки: CPU {0}% · GPU {1}% · RPM недоступны", "ファームウェア値: CPU {0}% · GPU {1}% · RPM なし", "펌웨어 값: CPU {0}% · GPU {1}% · RPM 없음", "韌體占空比:CPU {0}% · GPU {1}% · RPM 不可用", "Firmware değeri: CPU {0}% · GPU {1}% · RPM yok", "Giá trị firmware: CPU {0}% · GPU {1}% · không có RPM", "Nilai firmware: CPU {0}% · GPU {1}% · RPM tidak tersedia", "Valore firmware: CPU {0}% · GPU {1}% · RPM non disponibili" }; + m["cc_values"] = new[] { "CPU {0}°C · GPU {1}°C\nEstimated curve demand: CPU {2} · GPU {3}\nMixed reference: {4}\nCalculated targets: CPU {5} · GPU {6}", "CPU {0}°C · GPU {1}°C\nSzacowane krzywe: CPU {2} · GPU {3}\nWartość mieszana: {4}\nObliczone cele: CPU {5} · GPU {6}", "CPU {0}°C · GPU {1}°C\nGeschätzter Kurvenbedarf: CPU {2} · GPU {3}\nMischreferenz: {4}\nBerechnete Ziele: CPU {5} · GPU {6}", "CPU {0}°C · GPU {1}°C\nDemande estimée : CPU {2} · GPU {3}\nRéférence mixte : {4}\nCibles calculées : CPU {5} · GPU {6}", "CPU {0}°C · GPU {1}°C\nDemanda estimada: CPU {2} · GPU {3}\nReferencia mixta: {4}\nObjetivos calculados: CPU {5} · GPU {6}", "CPU {0}°C · GPU {1}°C\n估算曲线需求:CPU {2} · GPU {3}\n混合参考:{4}\n计算目标:CPU {5} · GPU {6}", "CPU {0}°C · GPU {1}°C\nDemanda estimada: CPU {2} · GPU {3}\nReferência mista: {4}\nAlvos calculados: CPU {5} · GPU {6}", "CPU {0}°C · GPU {1}°C\nРасчёт по кривой: CPU {2} · GPU {3}\nСмешанный ориентир: {4}\nРасчётные цели: CPU {5} · GPU {6}", "CPU {0}°C · GPU {1}°C\n推定カーブ需要: CPU {2} · GPU {3}\n混合基準: {4}\n計算目標: CPU {5} · GPU {6}", "CPU {0}°C · GPU {1}°C\n예상 곡선 요구량: CPU {2} · GPU {3}\n혼합 기준: {4}\n계산 목표: CPU {5} · GPU {6}", "CPU {0}°C · GPU {1}°C\n估算曲線需求:CPU {2} · GPU {3}\n混合參考:{4}\n計算目標:CPU {5} · GPU {6}", "CPU {0}°C · GPU {1}°C\nTahmini eğri talebi: CPU {2} · GPU {3}\nKarışık referans: {4}\nHesaplanan hedefler: CPU {5} · GPU {6}", "CPU {0}°C · GPU {1}°C\nNhu cầu ước tính: CPU {2} · GPU {3}\nTham chiếu trộn: {4}\nMục tiêu tính toán: CPU {5} · GPU {6}", "CPU {0}°C · GPU {1}°C\nPerkiraan kebutuhan kurva: CPU {2} · GPU {3}\nReferensi campuran: {4}\nTarget terhitung: CPU {5} · GPU {6}", "CPU {0}°C · GPU {1}°C\nRichiesta stimata: CPU {2} · GPU {3}\nRiferimento misto: {4}\nObiettivi calcolati: CPU {5} · GPU {6}" }; + m["cc_plan"] = new[] { "Last successful EC update: {0} · Profile: {1} · Curve: {2}", "Ostatni zapis EC: {0} · Profil: {1} · Krzywa: {2}", "Letzte EC-Aktualisierung: {0} · Profil: {1} · Kurve: {2}", "Dernière mise à jour EC : {0} · Profil : {1} · Courbe : {2}", "Última actualización EC: {0} · Perfil: {1} · Curva: {2}", "上次 EC 更新:{0} · 配置:{1} · 曲线:{2}", "Última atualização EC: {0} · Perfil: {1} · Curva: {2}", "Последнее обновление EC: {0} · Профиль: {1} · Кривая: {2}", "最終 EC 更新: {0} · プロファイル: {1} · カーブ: {2}", "최근 EC 갱신: {0} · 프로필: {1} · 곡선: {2}", "上次 EC 更新:{0} · 設定:{1} · 曲線:{2}", "Son EC güncellemesi: {0} · Profil: {1} · Eğri: {2}", "Cập nhật EC cuối: {0} · Hồ sơ: {1} · Đường cong: {2}", "Pembaruan EC terakhir: {0} · Profil: {1} · Kurva: {2}", "Ultimo aggiornamento EC: {0} · Profilo: {1} · Curva: {2}" }; + m["cc_effective_weights"] = new[] { "Normalized weights: CPU {0}% · GPU {1}%", "Znormalizowane wagi: CPU {0}% · GPU {1}%", "Normierte Gewichte: CPU {0}% · GPU {1}%", "Poids normalisés : CPU {0}% · GPU {1}%", "Pesos normalizados: CPU {0}% · GPU {1}%", "归一化权重:CPU {0}% · GPU {1}%", "Pesos normalizados: CPU {0}% · GPU {1}%", "Нормированные веса: CPU {0}% · GPU {1}%", "正規化した重み: CPU {0}% · GPU {1}%", "정규화 가중치: CPU {0}% · GPU {1}%", "正規化權重:CPU {0}% · GPU {1}%", "Normalize ağırlıklar: CPU {0}% · GPU {1}%", "Trọng số chuẩn hóa: CPU {0}% · GPU {1}%", "Bobot ternormalisasi: CPU {0}% · GPU {1}%", "Pesi normalizzati: CPU {0}% · GPU {1}%" }; + } + private static void L00(Dictionary m) { // ---- sub-tabs ---- diff --git a/Forms/GhostCardForm.cs b/Forms/GhostCardForm.cs index 34607fc..821351b 100644 --- a/Forms/GhostCardForm.cs +++ b/Forms/GhostCardForm.cs @@ -39,6 +39,7 @@ public class GhostCardForm : Form /// an update, a notice), which may land in the middle of a game. The card still sits on /// top; a click on it focuses it as usual. /// + [System.ComponentModel.DesignerSerializationVisibility(System.ComponentModel.DesignerSerializationVisibility.Hidden)] public bool Quiet { get; init; } protected override bool ShowWithoutActivation => Quiet; diff --git a/Forms/OsdForm.cs b/Forms/OsdForm.cs index 0b915f5..e2da7b5 100644 --- a/Forms/OsdForm.cs +++ b/Forms/OsdForm.cs @@ -32,6 +32,7 @@ private enum Phase { Idle, In, Hold, Out } private int _holdMs = 3000; /// How long a toast stays fully visible (seconds); follows the OSD setting. + [System.ComponentModel.DesignerSerializationVisibility(System.ComponentModel.DesignerSerializationVisibility.Hidden)] public int HoldSeconds { get; set; } = 3; protected override bool ShowWithoutActivation => true; diff --git a/Forms/ReportForm.cs b/Forms/ReportForm.cs index a909842..782ce91 100644 --- a/Forms/ReportForm.cs +++ b/Forms/ReportForm.cs @@ -725,10 +725,12 @@ private static void DrawCheck(Graphics g, int cx, int cy, float d, float pop) private sealed class RoundedBar : Control { private float _value; + [System.ComponentModel.DesignerSerializationVisibility(System.ComponentModel.DesignerSerializationVisibility.Hidden)] public Color Accent { get; set; } = Color.MediumPurple; public RoundedBar() { DoubleBuffered = true; } + [System.ComponentModel.DesignerSerializationVisibility(System.ComponentModel.DesignerSerializationVisibility.Hidden)] public float Value { get => _value; diff --git a/GhostDeck.csproj b/GhostDeck.csproj index dab2c11..55138a7 100644 --- a/GhostDeck.csproj +++ b/GhostDeck.csproj @@ -2,7 +2,7 @@ WinExe - net8.0-windows + net11.0-windows7.0 true enable enable @@ -14,14 +14,15 @@ GhostDeck GhostDeck GhostDeck - 1.0.0 + 1.46.0 WYGODA DAWID FENIX INSPIRE Copyright (C) 2026 Dawid Wygoda GPL-3.0-or-later - + + diff --git a/Properties/PublishProfiles/FolderProfile.pubxml b/Properties/PublishProfiles/FolderProfile.pubxml new file mode 100644 index 0000000..645b03f --- /dev/null +++ b/Properties/PublishProfiles/FolderProfile.pubxml @@ -0,0 +1,17 @@ + + + + + Release + Any CPU + bin\Release\net11.0\publish\win-x64\ + FileSystem + <_TargetId>Folder + net11.0-windows7.0 + win-x64 + true + false + false + false + + \ No newline at end of file diff --git a/TrayContext.cs b/TrayContext.cs index 55f82ed..24f0387 100644 --- a/TrayContext.cs +++ b/TrayContext.cs @@ -28,6 +28,12 @@ public sealed class TrayContext : ApplicationContext // >0 while a composed EC operation is running. A model-database swap in the middle of one // would mix registers from two generations, so it waits. private int _ecBusy; + private CrossCoolingController? _cooling; + private DeviceProfile? _coolingDevice; + private CoolingStatus _coolingNotice = new(false, "cc_disabled"); + private readonly System.Windows.Forms.Timer _coolingTimer = new() { Interval = 2000 }; + private int _coolingBusy; + private bool _sleeping; private ModelDb.Parsed? _pendingDb; // swap deferred until the gate opens private string _firmware; // startup probe result; a successful retry may fill it in private FirmwareProbeStatus _probeStatus; // WHY there is no EC control (drives the unsupported subtitle) @@ -212,6 +218,7 @@ public TrayContext() _poll.Tick += (_, _) => Poll(); _poll.Start(); + _coolingTimer.Tick += (_, _) => TickCooling(); ShowState(); if (_firmwareChanged) ShowFirmwareDialog(); @@ -221,6 +228,8 @@ public TrayContext() if (_settings.OverlayEnabled) SetOverlay(true, osd: false); _ui = SynchronizationContext.Current; + // Restore only after startup profile/curve writes and the worker's UI context are ready. + if (_settings.CrossCooling.Enabled) ConfigureCooling(true); // A settings file that cannot be written is said in a card. The start-up above saves too, // before a card can be shown: such a failure is kept by AppSettings and said now. _onSaveFailed = why => (_ui ?? SynchronizationContext.Current)?.Post(_ => TellSettingsNotSaved(why), null); @@ -639,6 +648,7 @@ private void AcknowledgeFirmware() if (AutoWritable) TryApplyChargeLimit(); if (AutoWritable && _settings.AutoSwitchEnabled) ApplyForPower(SystemInformation.PowerStatus.PowerLineStatus, osd: false); + if (_ui != null && _settings.CrossCooling.Enabled) ConfigureCooling(true); } /// @@ -900,6 +910,7 @@ private void RedetectFromFirmware() BuildMenu(); UpdateUi(_current); _main?.OnDeviceDbChanged(); + if (_settings.CrossCooling.Enabled) ConfigureCooling(true); } // ---------------- menu ---------------- @@ -928,7 +939,7 @@ private void BuildMenu() var oldSwatches = _menuSwatches.ToArray(); _menuSwatches.Clear(); - var menu = new ContextMenuStrip(); + var menu = new ThemedContextMenu(); menu.Items.Add(new ToolStripLabel("GhostDeck") { Font = Dpi.Font("Segoe UI", 9, FontStyle.Bold) }); menu.Items.Add(new ToolStripLabel(DeviceDescriptor()) { ForeColor = Color.Gray, Font = Dpi.Font("Segoe UI", 8) }); menu.Items.Add(new ToolStripSeparator()); @@ -2215,10 +2226,13 @@ private void OnPowerModeChanged(object? sender, PowerModeChangedEventArgs e) { if (e.Mode == PowerModes.Suspend) { + _sleeping = true; + _cooling?.Suspend("cc_session_paused"); _profileBeforeSleep = Writable ? _current : null; return; } if (e.Mode != PowerModes.Resume) return; + _sleeping = false; Ec.DropSession(); // the WMI session from before sleep is gone; reconnect on the next read bool wantProfile = _settings.RestoreProfileOnResume && !_settings.AutoSwitchEnabled && _profileBeforeSleep is { }; bool wantCurve = _settings.RestoreCurveOnResume && _settings.CurveActive; // (#49) @@ -2539,6 +2553,9 @@ private void SaveFpsSnapshot() // custom fan curve (0x8D) and the Silent cap (0x1D), so no separate fan write is needed. private void PanicReset() { + _settings.CrossCooling.Enabled = false; + _settings.Save(); + ConfigureCooling(false); // Every step on its own: a step that fails is recorded by name and the rest still run, // because a panic reset must do as much as it can; the result (OSD, log, CLI exit code) // then says what did not happen instead of "done". @@ -2621,6 +2638,7 @@ private void ChangeLanguage(string code) SettingsChanged = () => { ApplyHotkeys(); BuildMenu(); UpdateUi(_current); + ConfigureCooling(_settings.CrossCooling.Enabled); ApplyTrayWheel(); // (#23) follow a just-edited wheel mode (install or remove the hook) SyncTempTrays(); // drop a temperature icon the user just switched off // apply a just-edited refresh preference right away (no-op when disabled) @@ -2688,11 +2706,17 @@ private void ChangeLanguage(string code) { if (Writable && !_simulate && _device != null) { + using var session = EcBusy(); try { act(_device); } catch { } } }, Simulating = () => _simulate, EcSession = () => EcBusy(), + EcBusy = () => _ecBusy > 0, + CoolingStatus = () => _cooling?.Status ?? _coolingNotice, + ConfigureCooling = ConfigureCooling, + SuspendCooling = () => _cooling?.Suspend("cc_editor_paused"), + CoolingBaseline = () => _cooling?.Baseline, RestoreActiveCurve = RestoreActiveCurve, }; @@ -2940,6 +2964,8 @@ private bool TryApplyModelDb(ModelDb.Parsed p) _pendingDb = p; return false; } + ConfigureCooling(false); + if (_cooling?.Status.Key == "cc_restore_failed") { _pendingDb = p; return false; } if (!Devices.ApplyOverride(p)) return false; _device = Devices.Detect(_firmware); @@ -2953,6 +2979,7 @@ private bool TryApplyModelDb(ModelDb.Parsed p) BuildMenu(); UpdateUi(_current); _main?.OnDeviceDbChanged(); + if (_settings.CrossCooling.Enabled) ConfigureCooling(true); return true; } @@ -2968,12 +2995,97 @@ private void DrainPendingDb() private readonly struct EcScope : IDisposable { private readonly TrayContext _t; - public EcScope(TrayContext t) { _t = t; t._ecBusy++; } + public EcScope(TrayContext t, bool pauseCooling = true) + { + _t = t; t._ecBusy++; + try + { + if (pauseCooling) + { + t._cooling?.Suspend(); + if (t._cooling?.Status.Key == "cc_restore_failed") + throw new InvalidOperationException(t._cooling.Status.Error); + } + } + catch { t._ecBusy--; throw; } + } public void Dispose() { _t._ecBusy--; if (_t._ecBusy == 0) _t.DrainPendingDb(); } } private EcScope EcBusy() => new(this); + private string? CoolingBlocked() + { + if (_closing || _sleeping || AppLifecycle.ShuttingDown || _ecBusy > 0) return "cc_session_paused"; + if (_simulate || _device?.FanCurve is not { SingleFan: false, Points: 6 } || Ec.OnBackupPath) return "cc_unsupported"; + if (!AutoWritable) return "cc_write_blocked"; + if (_current == ProfileId.Silent) return "cc_silent_paused"; + if (_coolerBoost) return "cc_boost_paused"; + if (_main is { IsDisposed: false, FanCurveEditing: true }) return "cc_editor_paused"; + return null; + } + + private void ConfigureCooling(bool enabled) + { + try + { + if (!enabled) + { + _cooling?.Configure(_settings.CrossCooling, false); + _coolingNotice = new(false, "cc_disabled"); + if (_cooling?.Status.Key != "cc_restore_failed") _coolingTimer.Stop(); + return; + } + if (_simulate || _device?.FanCurve is not { SingleFan: false, Points: 6 } || Ec.OnBackupPath) + { _cooling?.Configure(_settings.CrossCooling, false); _cooling?.Suspend("cc_unsupported"); _coolingNotice = new(false, "cc_unsupported"); return; } + if (!AutoWritable) { _cooling?.Configure(_settings.CrossCooling, false); _cooling?.Suspend("cc_write_blocked"); _coolingNotice = new(false, "cc_write_blocked"); return; } + if (_cooling == null || !ReferenceEquals(_coolingDevice, _device)) + { + _cooling?.Dispose(); + _coolingDevice = _device; + _cooling = new(new EcCrossCoolingHardware(_device), _device.FanCurve.MaxFanPct, + (message, detail) => ChangeLog.Add(ChangeSource.FanCurve, message, detail)); + } + _cooling.Configure(_settings.CrossCooling, true); + _coolingTimer.Interval = _settings.CrossCooling.SamplingSeconds * 1000; + _coolingTimer.Start(); + TickCooling(); + } + catch (Exception ex) + { + _coolingNotice = new(false, "cc_failed", ex.Message); + AppLifecycle.Report(ex, "cross-cooling configuration"); + } + } + + private void TickCooling() + { + if (_cooling == null || Volatile.Read(ref _coolingBusy) != 0) return; + if (!ReferenceEquals(_coolingDevice, _device)) { ConfigureCooling(false); return; } + if (CoolingBlocked() is { } blocked) { _cooling.Suspend(blocked); return; } + _cooling.Resume(); + Interlocked.Exchange(ref _coolingBusy, 1); + // Held across the worker, just like diagnostics: model swaps and automatic writers wait. + // This scope is our own operation, so it must not suspend itself. + var session = new EcScope(this, pauseCooling: false); + var controller = _cooling; + Task.Run(() => + { + try { controller.Tick(); } + catch (Exception ex) { AppLifecycle.Report(ex, "cross-cooling worker"); } + finally + { + _ui?.Post(_ => + { + session.Dispose(); + Interlocked.Exchange(ref _coolingBusy, 0); + if (!controller.Status.Enabled && controller.Status.Key != "cc_restore_failed") _coolingTimer.Stop(); + if (_main is { IsDisposed: false }) _main.RefreshActive(); + }, null); + } + }); + } + private void OnUpdateResult(Updater.Result? res) { _settings.LastUpdateCheckUtc = DateTime.UtcNow; @@ -3576,6 +3688,9 @@ private void ExitApp() if (_onSaveFailed != null) { AppSettings.SaveFailed -= _onSaveFailed; _onSaveFailed = null; } if (_saveCard is { IsDisposed: false } saveCard) { _saveCard = null; saveCard.Close(); } _poll.Stop(); + _coolingTimer.Stop(); + _cooling?.Dispose(); + _coolingTimer.Dispose(); DisarmProbeRetry(); _wheelTimer?.Stop(); _wheel?.Dispose(); diff --git a/UI/Controls/CheckItem.cs b/UI/Controls/CheckItem.cs index eb878ae..32dd673 100644 --- a/UI/Controls/CheckItem.cs +++ b/UI/Controls/CheckItem.cs @@ -18,8 +18,10 @@ public CheckItem(string text, bool on) Height = Math.Max(26, F.Height + 6); // the label's line plus air; layouts may set their own SetStyle(ControlStyles.Selectable, false); } + [System.ComponentModel.DesignerSerializationVisibility(System.ComponentModel.DesignerSerializationVisibility.Hidden)] public bool Checked { get => _on; set { _on = value; Invalidate(); } } /// Let a long label wrap instead of being cut with an ellipsis (caller sizes the height). + [System.ComponentModel.DesignerSerializationVisibility(System.ComponentModel.DesignerSerializationVisibility.Hidden)] public bool Wrap { get; set; } private static readonly Font F = Dpi.Font("Segoe UI", 10.5f); private int Box => (int)Math.Ceiling(18 * Dpi.Of(this) / 96f); // DPI-aware box size diff --git a/UI/Controls/HelpPopup.cs b/UI/Controls/HelpPopup.cs index cf55084..a3464fa 100644 --- a/UI/Controls/HelpPopup.cs +++ b/UI/Controls/HelpPopup.cs @@ -133,8 +133,10 @@ public static void Toggle(Control host, Rectangle anchor, string text, object ow internal sealed class HelpDot : Control { /// Supplies the text at click time, so a bubble about a live reading is never stale. + [System.ComponentModel.DesignerSerializationVisibility(System.ComponentModel.DesignerSerializationVisibility.Hidden)] public Func? TextProvider { get; set; } /// Set for a topic too big for a bubble: the dot opens this (a GhostDeck help card) instead. + [System.ComponentModel.DesignerSerializationVisibility(System.ComponentModel.DesignerSerializationVisibility.Hidden)] public Action? OpenCard { get; set; } public HelpDot() diff --git a/UI/Controls/SegControl.cs b/UI/Controls/SegControl.cs index b601265..67654f4 100644 --- a/UI/Controls/SegControl.cs +++ b/UI/Controls/SegControl.cs @@ -12,6 +12,7 @@ public sealed class SegControl : Control private int _sel; private readonly Font _font = Dpi.Font("Segoe UI", 9.5f, FontStyle.Bold); public event Action? SelectedChanged; + [System.ComponentModel.DesignerSerializationVisibility(System.ComponentModel.DesignerSerializationVisibility.Hidden)] public int Selected { get => _sel; set { _sel = value; Invalidate(); } } public SegControl(string[] items, int sel) diff --git a/UI/Controls/Slider.cs b/UI/Controls/Slider.cs index 44705cf..a562e1e 100644 --- a/UI/Controls/Slider.cs +++ b/UI/Controls/Slider.cs @@ -15,10 +15,13 @@ public sealed class Slider : Control private int _val; private bool _drag; public event Action? ValueChanged; + [System.ComponentModel.DesignerSerializationVisibility(System.ComponentModel.DesignerSerializationVisibility.Hidden)] public bool ShowValue { get; set; } = true; // false = full-width track, caption drawn elsewhere /// A value the thumb snaps to when dragged close (0 for an offset); wheel and keys still reach every value. + [System.ComponentModel.DesignerSerializationVisibility(System.ComponentModel.DesignerSerializationVisibility.Hidden)] public int? SnapTo { get; set; } /// A double-click puts the slider back to this value. + [System.ComponentModel.DesignerSerializationVisibility(System.ComponentModel.DesignerSerializationVisibility.Hidden)] public int? DefaultValue { get; set; } public Slider(int min, int max, int val, int step = 1, string suffix = "") @@ -44,8 +47,10 @@ public Slider(int min, int max, int val, int step = 1, string suffix = "") /// Width of the value column. Sliders stacked in one card share the widest one, so their /// tracks start and end at the same place whatever each can show. /// + [System.ComponentModel.DesignerSerializationVisibility(System.ComponentModel.DesignerSerializationVisibility.Hidden)] public int ValueWidth { get => _valueW; set { _valueW = Math.Max(NaturalValueWidth, value); Invalidate(); } } + [System.ComponentModel.DesignerSerializationVisibility(System.ComponentModel.DesignerSerializationVisibility.Hidden)] public int Value { get => _val; set { _val = Clamp(value); Invalidate(); } } private int Clamp(int v) => Math.Clamp(v, _min, _max); private int ValueW => ShowValue ? _valueW : 0; diff --git a/UI/Controls/ThemedComboBox.cs b/UI/Controls/ThemedComboBox.cs index 0c09a11..4eafb9f 100644 --- a/UI/Controls/ThemedComboBox.cs +++ b/UI/Controls/ThemedComboBox.cs @@ -82,8 +82,10 @@ public ThemedComboBox() /// True while the list is open. public bool DroppedDown => _popup != null; /// Rows shown before the list scrolls. + [System.ComponentModel.DesignerSerializationVisibility(System.ComponentModel.DesignerSerializationVisibility.Hidden)] public int MaxDropDownItems { get; set; } = 8; /// Width of the open list; anything below the field's width means "as wide as the field". + [System.ComponentModel.DesignerSerializationVisibility(System.ComponentModel.DesignerSerializationVisibility.Hidden)] public int DropDownWidth { get; set; } /// @@ -91,8 +93,10 @@ public ThemedComboBox() /// text only, as in every list that does not set it. Drawn in the field for the selected item /// and on every row of the open list (#117: the turbo-mode group icons). /// + [System.ComponentModel.DesignerSerializationVisibility(System.ComponentModel.DesignerSerializationVisibility.Hidden)] public Action? ItemIcon { get; set; } /// Optional short note at the right end of a row of the open list (grey), e.g. the group of a mode. + [System.ComponentModel.DesignerSerializationVisibility(System.ComponentModel.DesignerSerializationVisibility.Hidden)] public Func? ItemNote { get; set; } /// @@ -100,6 +104,7 @@ public ThemedComboBox() /// field grows to fit it, instead of ending in "..." (#117: Windows names of turbo modes such /// as "Wydajność: agresywnie - gwarantowane"). The owner reads Height after a change. /// + [System.ComponentModel.DesignerSerializationVisibility(System.ComponentModel.DesignerSerializationVisibility.Hidden)] public bool WrapSelected { get => _wrap; @@ -129,6 +134,7 @@ public int FieldHeightFor(int width) internal static int IconSide(int rowHeight) => Math.Max(10, (int)(rowHeight * 0.7f)); /// Height of one row of the open list; the field is this plus 6. + [System.ComponentModel.DesignerSerializationVisibility(System.ComponentModel.DesignerSerializationVisibility.Hidden)] public int ItemHeight { get => _itemHeight; @@ -170,6 +176,7 @@ public int PreferredFieldWidth } private int _prefW = -1; + [System.ComponentModel.DesignerSerializationVisibility(System.ComponentModel.DesignerSerializationVisibility.Hidden)] public int SelectedIndex { get => _sel; @@ -185,6 +192,7 @@ public int SelectedIndex } } + [System.ComponentModel.DesignerSerializationVisibility(System.ComponentModel.DesignerSerializationVisibility.Hidden)] public object? SelectedItem { get => _sel >= 0 && _sel < _items.Count ? _items[_sel] : null; diff --git a/UI/Controls/ThemedContextMenu.cs b/UI/Controls/ThemedContextMenu.cs new file mode 100644 index 0000000..40f7053 --- /dev/null +++ b/UI/Controls/ThemedContextMenu.cs @@ -0,0 +1,110 @@ +using System.ComponentModel; + +namespace GhostDeck; + +/// App-palette context menus, including nested drop-downs and live theme changes. +public sealed class ThemedContextMenu : ContextMenuStrip +{ + public ThemedContextMenu() + { + Renderer = new MenuRenderer(); + Theme.Changed += OnThemeChanged; + ApplyTheme(this); + } + + protected override void OnOpening(CancelEventArgs e) + { + ApplyTheme(this); + base.OnOpening(e); + // Opening handlers may populate dynamic items. + if (!IsDisposed) ApplyTheme(this); + } + + private void OnThemeChanged() + { + if (IsDisposed) return; + if (IsHandleCreated && InvokeRequired) + { + try { BeginInvoke(OnThemeChanged); } catch (InvalidOperationException) { } + return; + } + ApplyTheme(this); + } + + private void ApplyTheme(ToolStrip strip) + { + strip.Renderer = Renderer; + strip.BackColor = Theme.Surface; + strip.ForeColor = Theme.Text; + foreach (ToolStripItem item in strip.Items) + if (item is ToolStripDropDownItem { HasDropDownItems: true } parent) + ApplyTheme(parent.DropDown); + strip.Invalidate(); + } + + protected override void Dispose(bool disposing) + { + if (disposing) Theme.Changed -= OnThemeChanged; + base.Dispose(disposing); + } + + private sealed class MenuRenderer : ToolStripProfessionalRenderer + { + public MenuRenderer() : base(new MenuColors()) { RoundedEdges = false; } + + protected override void OnRenderMenuItemBackground(ToolStripItemRenderEventArgs e) + { + // Visual styles can substitute the Windows highlight despite the color table. + if (e.Item.Enabled && (e.Item.Selected || e.Item.Pressed)) + { + var bounds = new Rectangle(Point.Empty, e.Item.Size); + bounds.Width--; bounds.Height--; + using var fill = new SolidBrush(Theme.AccentSoft); + using var border = new Pen(Theme.BorderStrong); + e.Graphics.FillRectangle(fill, bounds); + e.Graphics.DrawRectangle(border, bounds); + } + } + + protected override void OnRenderArrow(ToolStripArrowRenderEventArgs e) + { + e.ArrowColor = e.Item?.Enabled == false ? Theme.Muted : Theme.Text; + base.OnRenderArrow(e); + } + + protected override void OnRenderItemText(ToolStripItemTextRenderEventArgs e) + { + // Draw text directly: the base renderer substitutes system highlight/disabled colors. + TextRenderer.DrawText(e.Graphics, e.Text, e.TextFont, e.TextRectangle, + e.Item.Enabled ? e.Item.ForeColor : Theme.Muted, e.TextFormat); + } + + protected override void OnRenderItemCheck(ToolStripItemImageRenderEventArgs e) + { + ControlPaint.DrawMenuGlyph(e.Graphics, e.ImageRectangle, MenuGlyph.Checkmark, + e.Item.Enabled ? Theme.Text : Theme.Muted, Theme.AccentSoft); + } + } + + private sealed class MenuColors : ProfessionalColorTable + { + public MenuColors() { UseSystemColors = false; } + public override Color ToolStripDropDownBackground => Theme.Surface; + public override Color ImageMarginGradientBegin => Theme.Surface; + public override Color ImageMarginGradientMiddle => Theme.Surface; + public override Color ImageMarginGradientEnd => Theme.Surface; + public override Color MenuBorder => Theme.BorderStrong; + public override Color MenuItemBorder => Theme.BorderStrong; + public override Color MenuItemSelected => Theme.AccentSoft; + public override Color MenuItemSelectedGradientBegin => Theme.AccentSoft; + public override Color MenuItemSelectedGradientEnd => Theme.AccentSoft; + public override Color MenuItemPressedGradientBegin => Theme.AccentSoft; + public override Color MenuItemPressedGradientMiddle => Theme.AccentSoft; + public override Color MenuItemPressedGradientEnd => Theme.AccentSoft; + public override Color CheckBackground => Theme.AccentSoft; + public override Color CheckSelectedBackground => Theme.AccentSoft; + public override Color CheckPressedBackground => Theme.AccentSoft; + public override Color SeparatorDark => Theme.Border; + public override Color SeparatorLight => Theme.Surface; + } +} diff --git a/UI/Controls/ToggleSwitch.cs b/UI/Controls/ToggleSwitch.cs index d877183..22d50bd 100644 --- a/UI/Controls/ToggleSwitch.cs +++ b/UI/Controls/ToggleSwitch.cs @@ -11,6 +11,7 @@ public sealed class ToggleSwitch : Control { private bool _checked; public event Action? Toggled; + [System.ComponentModel.DesignerSerializationVisibility(System.ComponentModel.DesignerSerializationVisibility.Hidden)] public bool Checked { get => _checked; set { _checked = value; Invalidate(); } } // 52 x 28 at 100 %. Above that it grows by a quarter of the display scale's growth (57 x 31 at diff --git a/UI/CrossCoolingPanel.cs b/UI/CrossCoolingPanel.cs new file mode 100644 index 0000000..01edb6b --- /dev/null +++ b/UI/CrossCoolingPanel.cs @@ -0,0 +1,218 @@ +namespace GhostDeck; + +/// Native controls for the tray-owned cooling controller. +public sealed class CrossCoolingPanel : UserControl +{ + private readonly MainDeps _d; + private readonly Func _device; + private readonly Func _sample; + private readonly System.Windows.Forms.Timer _timer = new(); + private readonly TableLayoutPanel _rows = new() { AutoSize = true, ColumnCount = 2, Dock = DockStyle.Top }; + private readonly Label _status = new() { AutoSize = true }; + private readonly Label _values = new() { AutoSize = true }; + private readonly CrossCoolingGraph _graph = new(); + private readonly ToggleSwitch _enable = new(); + private readonly ThemedComboBox _mode = new(), _algorithm = new(), _weights = new(); + private readonly CheckItem _smooth = new("", false); + private readonly Panel _advanced = new() { AutoSize = true, Dock = DockStyle.Top, Visible = false }; + private bool _sync; + private CrossCoolingMode _selected = CrossCoolingMode.Both; + private CrossCoolingSettings Settings => _d.Settings.CrossCooling; + + public CrossCoolingPanel(MainDeps d, Func device, Func sample) + { + _d = d; _device = device; _sample = sample; + AutoScroll = true; DoubleBuffered = true; + _rows.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 48)); + _rows.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 52)); + Controls.Add(_rows); + _timer.Tick += (_, _) => UpdateStatus(); + VisibleChanged += (_, _) => { if (Visible) { Rebuild(); _timer.Start(); UpdateStatus(); } else _timer.Stop(); }; + _mode.SelectedIndexChanged += (_, _) => + { + if (_sync || _mode.SelectedIndex < 0) return; + Settings.Mode = (CrossCoolingMode)_mode.SelectedIndex; + if (Settings.Mode != CrossCoolingMode.Off) _selected = Settings.Mode; + Save(Settings.Mode != CrossCoolingMode.Off); + }; + _enable.Toggled += on => + { + if (_sync) return; + if (on && Settings.Mode == CrossCoolingMode.Off) _mode.SelectedIndex = (int)_selected; + else Save(on); + }; + _algorithm.SelectedIndexChanged += (_, _) => + { if (!_sync && _algorithm.SelectedIndex >= 0) { Settings.Algorithm = (CoolingMix)_algorithm.SelectedIndex; Save(); Rebuild(); } }; + _weights.SelectedIndexChanged += (_, _) => + { + if (_sync || _weights.SelectedIndex < 0) return; + (Settings.CpuWeight, Settings.GpuWeight) = _weights.SelectedIndex switch { 0 => (75, 25), 1 => (25, 75), 2 => (50, 50), _ => (Settings.CpuWeight, Settings.GpuWeight) }; + Save(); Rebuild(); + }; + _smooth.Toggled += v => { Settings.Smoothing = v; Save(); }; + Rebuild(); + } + + private void Save(bool? enabled = null) + { + if (_sync) return; + if (enabled.HasValue) Settings.Enabled = enabled.Value; + Settings.Normalize(); _d.SaveSettings(); + _d.ConfigureCooling(Settings.Enabled); + UpdateStatus(); + } + + public void Rebuild() + { + if (_sync || IsDisposed) return; + _sync = true; SuspendLayout(); _rows.SuspendLayout(); + try + { + Settings.Normalize(); + if (Settings.Mode != CrossCoolingMode.Off) _selected = Settings.Mode; + // Retain stateful controls; dispose the generated labels/sliders/buttons each rebuild. + Control[] keep = { _enable, _mode, _algorithm, _weights, _smooth, _status, _values, _advanced, _graph }; + foreach (Control c in keep) c.Parent?.Controls.Remove(c); + foreach (Control c in _rows.Controls.Cast().ToArray()) + { _rows.Controls.Remove(c); if (!keep.Contains(c)) c.Dispose(); } + foreach (Control c in _advanced.Controls.Cast().ToArray()) + { _advanced.Controls.Remove(c); c.Dispose(); } + _rows.RowStyles.Clear(); _rows.RowCount = 0; + BackColor = _rows.BackColor = _advanced.BackColor = Theme.Surface; + Font = Dpi.Font("Segoe UI", 10f); ForeColor = Theme.Text; + int pad = Scale(12); _rows.Padding = new Padding(pad); + AddWide(TextLabel("cc_control_help")); + Add("cc_enable", _enable); _enable.Checked = _d.CoolingStatus().Enabled; + Fill(_mode, new[] { "cc_off", "cc_cpu_gpu", "cc_gpu_cpu", "cc_both" }, (int)Settings.Mode); + Fill(_algorithm, new[] { "cc_max", "cc_average", "cc_weighted", "cc_priority" }, (int)Settings.Algorithm); + Add("cc_mode", _mode); Add("cc_algorithm", _algorithm); + var expand = new Button { Text = Lang.T("cc_advanced"), AutoSize = true }; + Ui.StyleGhost(expand); expand.Click += (_, _) => _advanced.Visible = !_advanced.Visible; + AddWide(expand); + var advancedRows = new TableLayoutPanel { AutoSize = true, Dock = DockStyle.Top, ColumnCount = 2 }; + advancedRows.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 48)); + advancedRows.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 52)); + _advanced.Controls.Add(advancedRows); + void Setting(string key, int min, int max, int val, Action change, string suffix = "") + { + var slider = new Slider(min, max, val, suffix: suffix) { Dock = DockStyle.Fill, AccessibleName = Lang.T(key) }; + if (key is "cc_cpu_weight" or "cc_gpu_weight") slider.Enabled = Settings.Algorithm == CoolingMix.WeightedAverage; + if (key == "cc_boost") slider.Enabled = Settings.Algorithm == CoolingMix.PriorityBoost; + slider.ValueChanged += v => { change(v); Save(); }; + Row(advancedRows, TextLabel(key), slider); + } + Setting("cc_sampling", 1, 10, Settings.SamplingSeconds, v => { Settings.SamplingSeconds = v; _timer.Interval = v * 1000; }, " s"); + Setting("cc_interval", 5, 60, Settings.UpdateSeconds, v => Settings.UpdateSeconds = v, " s"); + Setting("cc_threshold", 1, 20, Settings.Threshold, v => Settings.Threshold = v, " pp"); + Setting("cc_increase", 0, 10, Settings.IncreaseHysteresis, v => Settings.IncreaseHysteresis = v, " pp"); + Setting("cc_decrease", 0, 20, Settings.DecreaseHysteresis, v => Settings.DecreaseHysteresis = v, " pp"); + Setting("cc_step", 1, 20, Settings.DecreaseStep, v => Settings.DecreaseStep = v, " pp"); + _smooth.Text = Lang.T("cc_smoothing"); _smooth.Checked = Settings.Smoothing; + Row(advancedRows, _smooth, new Label { AutoSize = true }); + int preset = (Settings.CpuWeight, Settings.GpuWeight) switch { (75, 25) => 0, (25, 75) => 1, (50, 50) => 2, _ => 3 }; + Fill(_weights, new[] { "cc_cpu_priority", "cc_gpu_priority", "cc_balanced", "cc_custom" }, preset); + Row(advancedRows, TextLabel("cc_weights"), _weights); _weights.Enabled = Settings.Algorithm == CoolingMix.WeightedAverage; + void Weight(bool cpu, int v) + { + if ((cpu ? Settings.GpuWeight : Settings.CpuWeight) + v == 0) { Rebuild(); return; } + if (cpu) Settings.CpuWeight = v; else Settings.GpuWeight = v; + Save(); + _sync = true; _weights.SelectedIndex = 3; _sync = false; + } + Setting("cc_cpu_weight", 0, 100, Settings.CpuWeight, v => Weight(true, v), "%"); + Setting("cc_gpu_weight", 0, 100, Settings.GpuWeight, v => Weight(false, v), "%"); + Setting("cc_boost", 0, 100, Settings.BoostPercent, v => Settings.BoostPercent = v, "%"); + var reset = new Button { Text = Lang.T("cc_reset"), AutoSize = true }; + Ui.StyleGhost(reset); reset.Click += (_, _) => { _d.Settings.CrossCooling = new(); Save(false); Rebuild(); }; + Row(advancedRows, reset, new Label { AutoSize = true }); + AddWide(_advanced); + AddWide(TextLabel("cc_startup")); AddWide(TextLabel("cc_emergency")); + AddWide(_status); AddWide(_values); + AddWide(TextLabel("cc_graph")); _graph.Height = Scale(100); AddWide(_graph); + _status.ForeColor = Theme.Amber; _values.ForeColor = Theme.Text; + _timer.Interval = Settings.SamplingSeconds * 1000; + } + finally { _rows.ResumeLayout(true); ResumeLayout(true); _sync = false; } + UpdateStatus(); + } + + private int Scale(int px) => (int)Math.Ceiling(px * Dpi.Of(this) / 96f); + private Label TextLabel(string key) => new() { Text = Lang.T(key), AutoSize = true, ForeColor = Theme.Text, Dock = DockStyle.Fill, TextAlign = ContentAlignment.MiddleLeft }; + private void Add(string key, Control control) { control.AccessibleName = Lang.T(key); Row(_rows, TextLabel(key), control); } + private void AddWide(Control c) { int r = _rows.RowCount++; _rows.Controls.Add(c, 0, r); _rows.SetColumnSpan(c, 2); c.Margin = new Padding(Scale(4), Scale(8), Scale(4), Scale(8)); c.Dock = DockStyle.Top; } + private void Row(TableLayoutPanel table, Control label, Control value) + { + int r = table.RowCount++; table.Controls.Add(label, 0, r); table.Controls.Add(value, 1, r); + label.Margin = value.Margin = new Padding(Scale(4), Scale(6), Scale(4), Scale(6)); + value.Dock = value is ToggleSwitch ? DockStyle.None : DockStyle.Fill; + if (value is ToggleSwitch) value.Anchor = AnchorStyles.Left; + } + private static void Fill(ThemedComboBox c, string[] keys, int selected) + { c.Items.Clear(); c.Items.AddRange(keys.Select(Lang.T).Cast().ToArray()); c.SelectedIndex = selected; } + + public void UpdateStatus() + { + if (_sync || IsDisposed) return; + var status = _d.CoolingStatus(); + _enable.Checked = status.Enabled; + _status.Text = Lang.T(status.Key) + (status.Error.Length == 0 ? "" : "\n" + status.Error); + var dev = _device(); + _graph.SetState(status.Demand, dev?.FanCurve?.MaxFanPct ?? 100); + var sample = _sample(); + var reading = status.Reading; + int cpu = reading?.Hardware.CpuTemp ?? sample.CpuTemp, gpu = reading?.Hardware.GpuTemp ?? sample.GpuTemp; + var time = reading?.Time ?? (sample.Time == default ? DateTimeOffset.MinValue : new DateTimeOffset(sample.Time)); + bool fresh = DateTimeOffset.UtcNow - time <= TimeSpan.FromSeconds(Math.Max(6, Settings.SamplingSeconds * 3)); + string values = Lang.T("cc_no_sample"); + if (fresh && CrossCooling.ValidTemperature(cpu) && CrossCooling.ValidTemperature(gpu)) + { + string pct(double x) => x.ToString("0.#", Lang.Culture) + "%"; + values = status.Demand is { } demand + ? string.Format(Lang.T("cc_values"), cpu, gpu, pct(demand.CpuOriginal), pct(demand.GpuOriginal), + pct(demand.Mixed), pct(demand.CpuTarget), pct(demand.GpuTarget)) + : string.Format(Lang.T("cc_temperatures"), cpu, gpu); + int cf = reading?.Hardware.CpuFan ?? sample.CpuFan, gf = reading?.Hardware.GpuFan ?? sample.GpuFan; + int cr = reading?.Hardware.CpuRpm ?? sample.CpuRpm, gr = reading?.Hardware.GpuRpm ?? sample.GpuRpm; + values += "\n" + (dev != null && Ec.HasTach(dev) + ? string.Format(Lang.T("cc_actual"), cf, cr, gf, gr) + : string.Format(Lang.T("cc_duty"), cf, gf)); + } + _values.Text = values + "\n" + string.Format(Lang.T("cc_plan"), + status.LastWrite?.ToLocalTime().ToString("T", Lang.Culture) ?? "-", _d.Current(), + _d.Settings.CurveName.Length == 0 ? Lang.T("cc_custom") : _d.Settings.CurveName) + "\n" + + string.Format(Lang.T("cc_effective_weights"), (100.0 * Settings.CpuWeight / (Settings.CpuWeight + Settings.GpuWeight)).ToString("0.#", Lang.Culture), + (100.0 * Settings.GpuWeight / (Settings.CpuWeight + Settings.GpuWeight)).ToString("0.#", Lang.Culture)); + } + + protected override Point ScrollToControl(Control activeControl) => AutoScrollPosition; + protected override void Dispose(bool disposing) { if (disposing) _timer.Dispose(); base.Dispose(disposing); } +} + +internal sealed class CrossCoolingGraph : Control +{ + private CoolingDemand? _demand; + private int _max = 100; + public CrossCoolingGraph() { DoubleBuffered = true; ResizeRedraw = true; } + public void SetState(CoolingDemand? demand, int max) { _demand = demand; _max = max; Invalidate(); } + protected override void OnPaint(PaintEventArgs e) + { + e.Graphics.Clear(Theme.Surface); + if (_demand is not { } d) return; + int s(int n) => (int)Math.Ceiling(n * Dpi.Of(this) / 96f); + var font = Dpi.Font("Segoe UI", 10f); + int h = Math.Max(s(42), font.Height + s(20)); + void Fan(string name, double own, double target, int y, Color color) + { + TextRenderer.DrawText(e.Graphics, $"{name} {own:0.#}% → {target:0.#}%", font, new Point(0, y), Theme.Text); + int top = y + font.Height + s(3), w = Math.Max(1, Width - s(4)); + using var track = new SolidBrush(Theme.Border); + using var original = new SolidBrush(Theme.Muted); + using var mixed = new SolidBrush(color); + e.Graphics.FillRectangle(track, 0, top, w, s(10)); + e.Graphics.FillRectangle(mixed, 0, top, (int)(w * target / _max), s(10)); + e.Graphics.FillRectangle(original, 0, top, (int)(w * own / _max), s(4)); + } + Fan("CPU", d.CpuOriginal, d.CpuTarget, 0, Theme.AccentFill); + Fan("GPU", d.GpuOriginal, d.GpuTarget, h, Theme.Violet); + } +} diff --git a/UI/Dash/DashCanvas.cs b/UI/Dash/DashCanvas.cs index 77c12f6..94a3ed7 100644 --- a/UI/Dash/DashCanvas.cs +++ b/UI/Dash/DashCanvas.cs @@ -1081,6 +1081,7 @@ internal void Duplicate(DashItem it) } // ---- actions ---------------------------------------------------------------------------- + [System.ComponentModel.DesignerSerializationVisibility(System.ComponentModel.DesignerSerializationVisibility.Hidden)] internal bool EditMode { get => _edit; @@ -1095,6 +1096,7 @@ internal bool EditMode } } + [System.ComponentModel.DesignerSerializationVisibility(System.ComponentModel.DesignerSerializationVisibility.Hidden)] internal bool CatalogOpen { get => _catalog; diff --git a/UI/FanCurvePage.cs b/UI/FanCurvePage.cs index 3f133aa..b8b41f2 100644 --- a/UI/FanCurvePage.cs +++ b/UI/FanCurvePage.cs @@ -17,7 +17,8 @@ namespace GhostDeck; public sealed class FanCurvePage : ThemedPage { private const int Pad = 28; - private const int ViewChart = 0, ViewEq = 1, ViewDeck = 2, ViewPlay = 3, ViewCount = 4; + private const int ViewChart = 0, ViewEq = 1, ViewDeck = 2, ViewPlay = 3, ViewCross = 4, ViewCount = 5; + private readonly CrossCoolingPanel _cross; // DPI scale for every dimension the redesign added. The page predates per-monitor DPI // handling (the original two charts size themselves off Width/Height and use TextRenderer, @@ -121,7 +122,7 @@ public FanCurvePage(MainDeps d) : base(d) // View strip (same control as Status/Report/Settings). Glyphs: chart, equalizer // (slider bars), deck (a mixer-ish dial glyph) and playground (a flask). _view = Math.Clamp(d.Settings.FanCurveView, 0, ViewCount - 1); - _views = new SubTabs(ViewLabels(), new[] { "", "", "", "" }); + _views = new SubTabs(ViewLabels(), new[] { "", "", "", "", "" }); _views.SetActive(_view); _views.Changed += i => SelectView(i, save: true); Controls.Add(_views); @@ -129,6 +130,8 @@ public FanCurvePage(MainDeps d) : base(d) _live = new FanLiveFeed(this, () => _dev, () => _fc != null && D.Status().Known && !D.Simulating()); _live.Updated += OnLiveSample; + _cross = new CrossCoolingPanel(d, () => _dev, () => _live.Sample) { Visible = false }; + Controls.Add(_cross); // Chart-view options. Zones and intents are plain checkboxes; the table is a toggle // button (it changes the layout, so it reads as an action, not a preference); the @@ -227,6 +230,7 @@ public FanCurvePage(MainDeps d) : base(d) public override void OnEnter() { + if (_view is ViewChart or ViewEq or ViewDeck) D.SuspendCooling(); // First open used to read the whole curve (dozens of WMI calls) synchronously and froze // the tab switch; load it on a worker and repaint when it lands. if (!_loaded && !_loading && _fc != null) @@ -234,10 +238,11 @@ public override void OnEnter() _loading = true; var dev = _dev!; int points = _fc.Points; + var baseline = D.CoolingBaseline(); Task.Run(() => { (int[] cpuTemp, int[] cpuSpeed, int[] gpuTemp, int[] gpuSpeed)? c = null; - try { c = Ec.ReadFanCurve(dev); } catch { } + try { c = baseline is { } b ? (b.CpuTemp, b.CpuSpeed, b.GpuTemp, b.GpuSpeed) : Ec.ReadFanCurve(dev); } catch { } try { BeginInvoke(() => @@ -268,15 +273,16 @@ public override void OnEnter() // ---------------- views ---------------- private static string[] ViewLabels() => - new[] { Lang.T("fc_view_chart"), Lang.T("fc_view_eq"), Lang.T("fc_view_deck"), Lang.T("fc_view_play") }; + new[] { Lang.T("fc_view_chart"), Lang.T("fc_view_eq"), Lang.T("fc_view_deck"), Lang.T("fc_view_play"), Lang.T("cc_title") }; private void SelectView(int i, bool save) { + if (i is ViewChart or ViewEq or ViewDeck) D.SuspendCooling(); CloseCellEditor(commit: true); // an open inline editor belongs to the chart view - bool wasPlay = _view == ViewPlay; + bool wasPlay = _view is ViewPlay or ViewCross; _view = Math.Clamp(i, 0, ViewCount - 1); _views.SetActive(_view); - if (wasPlay && _view != ViewPlay && _fc != null) RestoreChrome(); + if (wasPlay && _view is not (ViewPlay or ViewCross) && _fc != null) RestoreChrome(); if (save && D.Settings.FanCurveView != _view) { D.Settings.FanCurveView = _view; D.SaveSettings(); } _dragFan = _dragIdx = -1; _hoverChip = _hoverIntent = _hoverRow = _eqHoverFan = _eqHoverIdx = _dialHoverFan = _dialHoverIdx = -1; @@ -288,6 +294,7 @@ private void SelectView(int i, bool save) public override void OnLanguageChanged() { _views.SetLabels(ViewLabels()); + _cross.Rebuild(); Restyle(); RefreshPresetUi(); LayoutButtons(); @@ -649,7 +656,7 @@ protected override void Dispose(bool disposing) base.Dispose(disposing); } - public override void ApplyTheme() { base.ApplyTheme(); Restyle(); } + public override void ApplyTheme() { base.ApplyTheme(); Restyle(); _cross.Rebuild(); } private void Restyle() { @@ -761,6 +768,7 @@ private string HintText() ViewEq => Lang.T("fc_hint_eq"), ViewDeck => Lang.T("fc_hint_deck"), ViewPlay => Lang.T("fc_hint_play"), + ViewCross => Lang.T("cc_control_help"), _ => !D.Writable() ? Lang.T("fc_locked") : _fc is { Verified: false } ? Lang.T("fc_preview") // editable, but addresses unconfirmed : Lang.T("fc_hint"), @@ -786,7 +794,7 @@ private string HintText() private void LayoutButtons() { if (!(_view == ViewChart && _fc != null)) _optRow2 = false; // only the chart view has the options row - _views.Visible = _fc != null; + _views.Visible = true; _views.SetBounds(Pad, ViewsY, _views.FitTo(Width - Pad * 2), _views.Height); LayoutDeck(); LayoutPlayground(); @@ -893,7 +901,7 @@ private void LayoutButtons() // The Playground neither edits nor applies the curve, so none of the editing chrome // belongs there: preset bar, assignment row, on/off switch, MSI default, Report. The // other views restore it through RefreshPresetUi/RefreshMode on their next layout. - if (_view == ViewPlay && _fc != null) + if (_view == ViewCross || (_view == ViewPlay && _fc != null)) { foreach (var c in new Control[] { _presetLabel, _presetCombo, _psSave, _psSaveAs, _psRename, _psDelete, _psImport, _psExport, _psShare, _assignLabel, _enable, _enableLabel, _default, _report }) @@ -901,6 +909,9 @@ private void LayoutButtons() foreach (var c in _assignNames) c.Visible = false; foreach (var c in _assignCombos) c.Visible = false; } + _cross.Visible = _view == ViewCross; + _cross.SetBounds(Pad, ViewsY + S(46), Math.Max(1, Width - Pad * 2), Math.Max(1, Height - ViewsY - S(46))); + if (_cross.Visible) { _both.Visible = _bothLabel.Visible = _bothHelp.Visible = false; _cross.BringToFront(); } } // Leaving the Playground: bring the editing chrome back (RefreshPresetUi decides which @@ -1790,11 +1801,11 @@ private void StartTwoTable() // what to put back: table 1 as the page has it (the editor's curve, or the profile's), and // table 2 exactly as the controller holds it NOW - on a single-fan entry the page never // reads or writes that table, so its own arrays would not describe it + var session = D.EcSession(); bool wasOn = _enable.Checked; int[] ct = (int[])_cpuT.Clone(), cs = (int[])_cpuS.Clone(), gt = (int[])_gpuT.Clone(), gs = (int[])_gpuS.Clone(); try { if (Ec.ReadFanCurve(dev) is { } cur) { gt = cur.gpuTemp; gs = cur.gpuSpeed; } } catch { } byte restoreMode = wasOn ? fc.AdvancedModeValue : ProfileFanByte(); - var session = D.EcSession(); _sweepCts = new CancellationTokenSource(); var ctk = _sweepCts.Token; _running = 2; _shown = 2; @@ -2697,6 +2708,8 @@ protected override void OnPaint(PaintEventArgs e) var g = e.Graphics; g.SmoothingMode = SmoothingMode.AntiAlias; + if (_view == ViewCross) { DrawPageHeader(g); return; } + if (_fc == null) { DrawPageHeader(g); @@ -3170,6 +3183,7 @@ private void DrawTable(Graphics g) /// because the page holds its own copy of the register layout and the point values. /// public bool CurveHot => Visible && _enable.Checked; + public bool EditingCurve => Visible && _view is ViewChart or ViewEq or ViewDeck; public override void OnDeviceDbChanged() { diff --git a/UI/MainDeps.cs b/UI/MainDeps.cs index 3584355..881bd07 100644 --- a/UI/MainDeps.cs +++ b/UI/MainDeps.cs @@ -7,6 +7,11 @@ public enum MainTab { Scenarios, Status, Dashboard, FanCurve, Settings, Models, /// Everything the tabbed UI needs from the tray context (data + actions). public sealed class MainDeps { + public Func EcBusy { get; init; } = () => false; + public Func CoolingStatus { get; init; } = () => new(false, "cc_disabled"); + public Action ConfigureCooling { get; init; } = _ => { }; + public Action SuspendCooling { get; init; } = () => { }; + public Func CoolingBaseline { get; init; } = () => null; public required AppSettings Settings { get; init; } public required Func Status { get; init; } public required Func Hw { get; init; } diff --git a/UI/MainForm.cs b/UI/MainForm.cs index 6a26417..3fb79fd 100644 --- a/UI/MainForm.cs +++ b/UI/MainForm.cs @@ -477,6 +477,8 @@ public void RefreshActive() /// True while the fan-curve editor is actively driving the EC (see FanCurvePage). public bool CurveEditorHot => _pages.TryGetValue(MainTab.FanCurve, out var p) && p is FanCurvePage fc && fc.CurveHot; + public bool FanCurveEditing => + _pages.TryGetValue(MainTab.FanCurve, out var p) && p is FanCurvePage fc && fc.EditingCurve; /// (#100) A preset was applied from the tray; mirror it in the fan-curve editor. public void SyncFanCurvePreset(string name) diff --git a/UI/ReportPage.cs b/UI/ReportPage.cs index 700d8c1..b9acbcf 100644 --- a/UI/ReportPage.cs +++ b/UI/ReportPage.cs @@ -2038,12 +2038,15 @@ public StepRowT(int num, string name, Color color) { _num = num; _name = name; Tint = color; DoubleBuffered = true; ResizeRedraw = true; } /// The power test names its rows from the model database, which can change at runtime. + [System.ComponentModel.DesignerSerializationVisibility(System.ComponentModel.DesignerSerializationVisibility.Hidden)] public string Label { set { if (_name == value) return; _name = value; Invalidate(); } } /// The same tile under another vendor app's name, drawn as a muted second line. + [System.ComponentModel.DesignerSerializationVisibility(System.ComponentModel.DesignerSerializationVisibility.Hidden)] public string? Alt { set { if (_alt == value) return; _alt = value; Invalidate(); } } /// Numbering follows the rows actually shown, so a hidden row leaves no gap. + [System.ComponentModel.DesignerSerializationVisibility(System.ComponentModel.DesignerSerializationVisibility.Hidden)] public int Number { set { if (_num == value) return; _num = value; Invalidate(); } } public void SetState(bool done, bool current) { _done = done; _current = current; Invalidate(); } diff --git a/UI/ScenariosPage.cs b/UI/ScenariosPage.cs index 83c66a0..0adc774 100644 --- a/UI/ScenariosPage.cs +++ b/UI/ScenariosPage.cs @@ -734,7 +734,7 @@ public SceneCard(SceneDef scene, Action run, Action edit, Action del, Action Disarm(); - var menu = new ContextMenuStrip(); + var menu = new ThemedContextMenu(); var mRun = new ToolStripMenuItem(Lang.T("scene_run")); mRun.Click += (_, _) => run(); var mEdit = new ToolStripMenuItem(Lang.T("scene_edit")); mEdit.Click += (_, _) => edit(); var mUp = new ToolStripMenuItem(Lang.T("scene_up")); mUp.Click += (_, _) => move(-1); @@ -837,7 +837,7 @@ public int DesiredHeight(int width) protected override void Dispose(bool disposing) { - if (disposing) _armTimer.Dispose(); + if (disposing) { _armTimer.Dispose(); ContextMenuStrip?.Dispose(); } base.Dispose(disposing); } diff --git a/UI/SettingsTrueColor.cs b/UI/SettingsTrueColor.cs index d8c425d..4e094ee 100644 --- a/UI/SettingsTrueColor.cs +++ b/UI/SettingsTrueColor.cs @@ -178,6 +178,7 @@ private sealed class TrueColorTiles : Control private readonly Rectangle[] _rects = new Rectangle[TrueColor.Profiles.Length]; private int _hover = -1; + [System.ComponentModel.DesignerSerializationVisibility(System.ComponentModel.DesignerSerializationVisibility.Hidden)] public int? Recorded { get; set; } public event Action? Pick; diff --git a/UI/SubTabs.cs b/UI/SubTabs.cs index 10a3c3e..e84f2b5 100644 --- a/UI/SubTabs.cs +++ b/UI/SubTabs.cs @@ -24,6 +24,7 @@ public sealed class SubTabs : Control public event Action? Changed; public int Active => _active; /// A strip nested under another one (Settings -> Gaming) fills a step lighter, so the two read as levels. + [System.ComponentModel.DesignerSerializationVisibility(System.ComponentModel.DesignerSerializationVisibility.Hidden)] public bool Nested { get; set; } public SubTabs(params string[] labels) : this(labels, null) { } diff --git a/UI/UpdatesPage.cs b/UI/UpdatesPage.cs index 461d3cf..2adca51 100644 --- a/UI/UpdatesPage.cs +++ b/UI/UpdatesPage.cs @@ -28,6 +28,7 @@ public sealed class UpdatesPage : ThemedPage private sealed class ThinBar : Control { private float _value; + [System.ComponentModel.DesignerSerializationVisibility(System.ComponentModel.DesignerSerializationVisibility.Hidden)] public float Value { get => _value; set { _value = Math.Clamp(value, 0, 1); Invalidate(); } } public ThinBar() { DoubleBuffered = true; Size = new Size(320, 12); Visible = false; } // dpi-ok: a progress strip without text protected override void OnPaint(PaintEventArgs e) diff --git a/docs/BUILD.md b/docs/BUILD.md index 9545d0c..9510fc7 100644 --- a/docs/BUILD.md +++ b/docs/BUILD.md @@ -1,24 +1,60 @@ # Building & releasing > **Building the `.exe` does NOT need admin rights and does NOT need an MSI laptop.** -> It works on any machine with the .NET 8 SDK. Only *running / testing* the app +> This checkout targets .NET 11 and builds with the .NET 11 SDK. Only *running / testing* the app > needs an MSI laptop (the EC/WMI interface) and elevation (UAC). ## Prerequisites -- .NET 8 SDK (`dotnet --version` → 8.x). Already installed on the dev machine. +- .NET 11 SDK (`dotnet --version` → 11.x; locally validated with 11.0.100). ## Compile check (fast) ```powershell dotnet build -c Release ``` +Restore and run the hardware-free Cross-Cooling test executable: + +```powershell +dotnet restore +dotnet run --project tests/GhostDeck.Tests.csproj -c Release +python tools/lang-check.py +python tools/dpi-check.py +``` + +The app is built entirely in code. Runtime-only WinForms control properties explicitly use +`DesignerSerializationVisibility.Hidden`, satisfying the .NET 11 WFO1000 analyzer without +disabling it. The existing .NET 11 target and System.Management package migration are retained. + +In a restricted runner that denies the compiler's named pipe (`MSB3883`, access denied under +`\\.\pipe\LOCAL\dotnet_*`), use: + +```powershell +python tools/restricted-build.py --configuration Release --tests +``` + +This restores dependencies, gets MSBuild's exact compiler arguments, runs the installed SDK's +compiler and analyzers directly, and completes MSBuild output assembly. It returns failure on +any compiler or test error. It produces the Windows app host, DLLs and runtime files under +`bin/Release/net11.0-windows7.0`; use the publish command below for a single-file executable. This is an environment +workaround, not a suppression of source errors. See [CROSS-COOLING.md](CROSS-COOLING.md) for what +is and is not hardware-validated. + +To validate and publish with the existing Visual Studio FolderProfile in that restricted runner: + +```powershell +python tools/restricted-build.py --configuration Release --tests --publish +``` + +The profile produces a self-contained folder at `bin/Release/net11.0/publish/win-x64/`. +Run `GhostDeck.exe` from that folder and keep its companion files together. + ## Produce the single-file exe From the repo root: ```powershell dotnet publish -c Release -r win-x64 --self-contained false ` -p:PublishSingleFile=true -p:DebugType=none -p:Version=X.Y.Z -o release ``` -Output: `release/GhostDeck.exe` (~2.5 MB, framework-dependent, requires the .NET 8 Desktop Runtime and admin to *run*). +Output: `release/GhostDeck.exe` (framework-dependent, requires the .NET 11 Desktop Runtime and admin to *run*). The release workflow renames this file to `GhostDeck-win-x64.exe` after signing; that is the name published as the release asset. A local re-publish to `release/` needs the running app closed first (file lock) - exit it from the tray. Local builds are **unsigned**; only the release workflow signs (see below). @@ -37,7 +73,7 @@ git push origin main git tag vX.Y.Z git push origin vX.Y.Z ``` -GitHub Actions then builds the exe with a pinned SDK (8.0.424), **signs it** (Azure Artifact Signing via +GitHub Actions then builds the exe with a pinned SDK (11.0.100), **signs it** (Azure Artifact Signing via OIDC; publisher "WYGODA DAWID FENIX INSPIRE") and publishes a **Release** with the exe attached and the notes taken from the matching CHANGELOG section. The workflow verifies the signature and **refuses to publish** when it is missing or has an unexpected subject, so a diff --git a/docs/CROSS-COOLING.md b/docs/CROSS-COOLING.md new file mode 100644 index 0000000..70f9d88 --- /dev/null +++ b/docs/CROSS-COOLING.md @@ -0,0 +1,146 @@ +# Cross-Cooling + +Cross-Cooling is an optional live controller in **Fan curve → Cross-Cooling**. Enabling it +captures the current six-node CPU/GPU tables and fan mode, raises selected speed tables using +combined curve demand, and enters the device's Advanced fan mode. It uses the existing +`Ec.WriteFanCurve` / `Ec.SetFanMode` path, with no new direct PWM registers. + +Off is the default. The enabled state, selected mode and options are saved. Enabled control +is restored after startup profile/curve setup, subject to the existing hardware and firmware +gates. Turning the switch off saves that choice without losing the selected mode. Normal exit +restores the hardware baseline while keeping the enabled preference for the next start. +The switch reports actual controller activation. There are no simulated-temperature controls. + +## Modes and mathematics + +Temperatures are converted independently with `CurveModel.SpeedAt`: +`Dc = CpuCurve(Tc)`, `Dg = GpuCurve(Tg)`. Temperatures themselves are not averaged. + +| Mode | CPU target | GPU target | +| --- | --- | --- | +| Off | Dc | Dg | +| CPU → GPU fan | Dc | max(Dg, M) | +| GPU → CPU fan | max(Dc, M) | Dg | +| Both fans | max(Dc, M) | max(Dg, M) | + +| Algorithm | Mixed demand M | +| --- | --- | +| Maximum (default) | max(Dc, Dg) | +| Average | (Dc + Dg) / 2 | +| Weighted Average | (Wc × Dc + Wg × Dg) / (Wc + Wg) | +| Priority Boost | Per selected fan: Own + B × max(0, Other - Own) | + +Priority Boost's displayed mixed reference is max(Dc, Dg); its targets apply B separately. +Weights accept 0–100 and are normalized by their positive sum. CPU Priority = 75/25, +GPU Priority = 25/75, Balanced = 50/50. The UI rejects 0/0; malformed saved weights recover +to Balanced. Targets retain their own original-demand floor and the device's maximum, +including 150% where specified. + +Selected speed nodes become `max(originalNode, ceil(target))`. Temperature nodes remain +unchanged; tables stay monotonic and never fall below the captured original table. +The unselected fan retains its original table. Both + Maximum requests equal demands; +different hardware and firmware can still produce different actual RPM. +Curve interpolation estimates demand; it is not measured duty or airflow. + +## Scheduling and status + +| Option | Default | Range | +| --- | --- | --- | +| Mode | Off | Off / CPU → GPU / GPU → CPU / Both | +| Algorithm | Maximum | Four algorithms above | +| Sampling interval | 2 seconds | 1–10 seconds | +| Minimum table update interval | 5 seconds | 5–60 seconds | +| Meaningful change | 5 percentage points | 1–20 pp | +| Increase hysteresis | 0 pp | 0–10 pp | +| Decrease hysteresis | 5 pp | 0–20 pp | +| Maximum decrease per update | 5 pp | 1–20 pp | +| Temperature smoothing | Off | On / Off | +| Weights | 50/50 | 0–100 each, positive total | +| Boost factor | 100% | 0–100% | + +The tray owns the controller and timer. Sampling and EC writes run on a worker and continue +when the page closes. The page timer only refreshes status. Smoothing keeps 65% of the previous +temperature on a fall and passes increases immediately; raw own demand remains a floor. +Targets can precede applied tables because updates are bounded. Settings changes retain the +write schedule so dragging sliders cannot flood EC writes. + +The page displays active/paused/error status, real temperatures, estimated demands, targets, +firmware duty and available RPM. **Last successful EC update** is set only after table and mode +calls complete successfully. It confirms write-call completion, not physical airflow or +sustained firmware retention. Stale readings are hidden. + +## Ownership and restoration + +Control requires a supported dual-fan, six-point method interface and existing write-permission +and firmware-change gates. Experimental entries require the existing Experimental opt-in. +Single-fan, unsupported, application simulation and backup WMI paths are excluded. +`FanCurveSpec.Verified` remains the existing confidence marker, not a new write gate. + +The controller serializes its read/calculate/write transaction. Existing EC sessions suspend +it and restore the baseline before profiles, presets, scenes, diagnostics or other writers +proceed. Editing views suspend control before reading/editing tables. After the operation, +a new baseline is captured so old floors never become the new user curve. Active-curve +settings and presets retain original tables. A model database swap disables and restores +the old device controller first. + +Fan Boost, Silent, sleep, curve editing and another EC session pause control. It resumes +after those conditions clear while enabled. Missing/zero/sleeping-GPU temperatures, values +above 115°C, invalid tables and stale/future samples restore and pause. Staleness is +max(6 seconds, three sampling intervals). + +A hardware read/write exception restores and disarms until explicitly enabled again. +If another program changes Advanced mode, control stops and preserves that newly selected +mode while restoring original tables. Failed restoration retains the baseline for retry +and requests the Balanced recipe's native Auto mode as fallback. Failures are logged and +displayed; fallback is an attempt, not a guarantee of successful hardware access. + +Disabling, Off, reset, Panic Reset and normal exit restore original tables and mode. +Off, reset and Panic Reset also save the disabled choice; normal exit preserves it. +Closing the page leaves the tray controller running. Forced termination cannot run cleanup: +applied floor tables may remain until firmware resets them. Firmware retention and response +can differ across models. Native thermal protections are not modified. + +`AppSettings.CrossCooling` supports serialization, backups, cloning and import, preserving +unknown option fields. Preset and scene JSON contracts are unchanged. Actual applications, +restoration and failures use ChangeLog; duplicate samples create no entries. The UI uses +shared theme/DPI controls and all 15 languages. + +## Validation + +Run [BUILD.md](BUILD.md). Hardware-free tests cover math, floors, weights, limits, scheduling, +sensors, settings, localization and native UI navigation/rebuild/disposal in both themes. +An injected hardware adapter tests Auto-to-Advanced activation, both tables, exact baseline +and mode restoration, directionality, settings-change intervals, competing sessions, +concurrent suspension, Fan Boost, partial writes, read failure, failed restoration with Auto +fallback/retry, native mode changes, disable and disposal. A disk save/load test also covers enabled restart, every saved option, +clone/import, disabled restart and legacy defaults. Tests perform no physical EC writes. + +This change has not been physically validated on MS-17S1 / `17S1IMS1.114` or any other laptop. +Hardware acceptance still requires CPU-only, GPU-only and combined loads with duty/RPM and +temperature recording, confirmation of table retention, profile/scene/Fan Boost/diagnostic +interactions, sleep/resume, sensor loss and disable/exit restoration. Equal requested +percentages do not establish equal RPM. Keep firmware protections enabled during measurements. + +## Implementation + +`Core/CrossCooling.cs` contains settings, math and scheduling. +`Core/CrossCoolingController.cs` owns lifecycle through `ICrossCoolingHardware`; +`Core/EcCrossCoolingHardware.cs` adapts existing EC calls. `TrayContext.cs` owns activation, +gates, sessions and workers. `UI/CrossCoolingPanel.cs` displays controls/status within +`UI/FanCurvePage.cs`. Tests are in `tests/Program.cs`. + +| Modified files | Purpose | +| --- | --- | +| `Core/CrossCooling.cs`, `Core/CrossCoolingController.cs`, `Core/EcCrossCoolingHardware.cs` | Settings, math, scheduling, live ownership and existing EC adapter | +| `Core/AppSettings.cs`, `Core/Lang.cs` | Persistence, normalization, clone/import and 15-language UI | +| `TrayContext.cs`, `UI/MainDeps.cs`, `UI/MainForm.cs` | Tray lifecycle, EC sessions, status/actions and editor conflict detection | +| `UI/FanCurvePage.cs`, `UI/CrossCoolingPanel.cs` | New sub-tab, native settings, hardware status and visualization | +| `GhostDeck.csproj`, `.github/workflows/ci.yml`, `.github/workflows/release.yml` | Preserve .NET 11 migration, exclude test source, update SDK/output paths and run tests | +| `UI/Controls/Slider.cs`, `SegControl.cs`, `ToggleSwitch.cs`, `ThemedComboBox.cs`, `CheckItem.cs`, `HelpPopup.cs` | Runtime property annotations for the .NET 11 WinForms serialization analyzer | +| `UI/SubTabs.cs`, `UI/ReportPage.cs`, `UI/SettingsTrueColor.cs`, `UI/UpdatesPage.cs`, `UI/Dash/DashCanvas.cs` | Same build annotations | +| `Forms/GhostCardForm.cs`, `Forms/OsdForm.cs`, `Forms/ReportForm.cs` | Same build annotations | +| `tests/GhostDeck.Tests.csproj`, `tests/Program.cs` | Hardware-free math, controller and native UI tests | +| `tools/restricted-build.py` | Exact compiler-argument fallback and FolderProfile publish support | +| `docs/BUILD.md`, `docs/FAN-CURVE.md`, `docs/TECHNICAL.md`, `docs/CROSS-COOLING.md` | Build instructions, behavior, limits and physical acceptance procedure | + +The existing Visual Studio `Properties/PublishProfiles/FolderProfile.pubxml` is used as supplied. diff --git a/docs/FAN-CURVE.md b/docs/FAN-CURVE.md index d247bab..3bb66d2 100644 --- a/docs/FAN-CURVE.md +++ b/docs/FAN-CURVE.md @@ -1,5 +1,7 @@ # Fan curve page +The optional **Cross-Cooling** sub-tab combines CPU/GPU curve demands and controls fan tables in Advanced mode, with four modes and four mixing algorithms. See [CROSS-COOLING.md](CROSS-COOLING.md) for ownership, restoration, tests and physical-validation limits. + Everything the Fan curve tab does, why it does it that way, and where the numbers come from. [TECHNICAL.md](TECHNICAL.md) §65 is the short version and links here; §17 holds the register maps this page writes through, and [RENDERING.md](RENDERING.md) holds the drawing rules it obeys. diff --git a/docs/TECHNICAL.md b/docs/TECHNICAL.md index 7032eb8..a4830e9 100644 --- a/docs/TECHNICAL.md +++ b/docs/TECHNICAL.md @@ -507,6 +507,9 @@ The fan byte is independent of the profile: you can pair any profile's power byt ### 17.3 The fan-curve tables +Cross-Cooling uses these same six-point definitions through the existing EC table writer. +Static curve compatibility does not validate continuous mixing. See [CROSS-COOLING.md](CROSS-COOLING.md). + Advanced mode (`0xD4=0x8D`) makes the firmware follow a **single shared curve** stored in EC (NOT per-profile). Two fans, 6 points each, first point is `0°C→0%`: | Fan | Temp table | Speed table | diff --git a/tests/GhostDeck.Tests.csproj b/tests/GhostDeck.Tests.csproj new file mode 100644 index 0000000..22490a4 --- /dev/null +++ b/tests/GhostDeck.Tests.csproj @@ -0,0 +1,12 @@ + + + Exe + net11.0-windows7.0 + true + enable + enable + + + + + diff --git a/tests/Program.cs b/tests/Program.cs new file mode 100644 index 0000000..1bb2db4 --- /dev/null +++ b/tests/Program.cs @@ -0,0 +1,555 @@ +using GhostDeck; +using System.Reflection; +using System.Text.Json; + +internal static class Program +{ + private static int _passed; + private static void Check(bool value, string message) { if (!value) throw new Exception(message); } + private static void Near(double actual, double expected) => Check(Math.Abs(actual - expected) < .001, $"{actual} != {expected}"); + private static void Test(string name, Action body) { body(); Console.WriteLine("PASS " + name); _passed++; } + private static void Throws(Action body) { try { body(); } catch (ArgumentException) { return; } throw new Exception("Expected rejection"); } + private static readonly int[] Temps = { 0, 20, 40, 60, 80, 100 }, Speeds = { 0, 20, 40, 60, 80, 100 }; + private static readonly DateTimeOffset Epoch = new(2026, 11, 23, 12, 0, 0, TimeSpan.Zero); + + [STAThread] + private static int Main() + { + try + { + AppSettings.DirOverride = Path.Combine(Path.GetTempPath(), "ghostdeck-cross-cooling-tests-" + Guid.NewGuid().ToString("N")); + Test("all modes x algorithms preserve floors and direction", () => + { + foreach (var mode in Enum.GetValues()) + foreach (var algorithm in Enum.GetValues()) + foreach (var pair in new[] { (90.0, 30.0), (30.0, 90.0), (90.0, 90.0), (0.0, 150.0) }) + { + var r = CrossCooling.Calculate(pair.Item1, pair.Item2, 150, new() { Mode = mode, Algorithm = algorithm }); + Check(r.CpuTarget >= pair.Item1 && r.GpuTarget >= pair.Item2, "floor"); + if (mode is CrossCoolingMode.Off or CrossCoolingMode.CpuToGpu) Near(r.CpuTarget, pair.Item1); + if (mode is CrossCoolingMode.Off or CrossCoolingMode.GpuToCpu) Near(r.GpuTarget, pair.Item2); + } + }); + Test("maximum and average", () => + { + var s = new CrossCoolingSettings { Mode = CrossCoolingMode.Both }; + var r = CrossCooling.Calculate(90, 30, 150, s); Near(r.CpuTarget, 90); Near(r.GpuTarget, 90); + s.Algorithm = CoolingMix.Average; r = CrossCooling.Calculate(90, 30, 150, s); + Near(r.Mixed, 60); Near(r.CpuTarget, 90); Near(r.GpuTarget, 60); + }); + Test("normalized weights and presets", () => + { + var s = new CrossCoolingSettings { Mode = CrossCoolingMode.Both, Algorithm = CoolingMix.WeightedAverage, CpuWeight = 75, GpuWeight = 25 }; + Near(CrossCooling.Calculate(90, 30, 150, s).Mixed, 75); + s.CpuWeight = 30; s.GpuWeight = 10; Near(CrossCooling.Calculate(90, 30, 150, s).Mixed, 75); + s.CpuWeight = 25; s.GpuWeight = 75; Near(CrossCooling.Calculate(90, 30, 150, s).Mixed, 45); + }); + Test("zero, negative and oversized weights rejected", () => + { + foreach (var weights in new[] { (0, 0), (-1, 50), (101, 0) }) + Throws(() => CrossCooling.Calculate(90, 30, 150, new() { CpuWeight = weights.Item1, GpuWeight = weights.Item2 })); + }); + Test("priority boost both directions and endpoints", () => + { + foreach (int boost in new[] { 0, 25, 100 }) + { + var s = new CrossCoolingSettings { Mode = CrossCoolingMode.Both, Algorithm = CoolingMix.PriorityBoost, BoostPercent = boost }; + var r = CrossCooling.Calculate(90, 30, 150, s); Near(r.CpuTarget, 90); Near(r.GpuTarget, 30 + .6 * boost); + r = CrossCooling.Calculate(30, 90, 150, s); Near(r.GpuTarget, 90); Near(r.CpuTarget, 30 + .6 * boost); + } + }); + Test("device-specific ceiling including 150", () => + { + Near(CrossCooling.Calculate(200, 30, 150, new() { Mode = CrossCoolingMode.Both }).GpuTarget, 150); + Near(CrossCooling.Calculate(200, -1, 80, new() { Mode = CrossCoolingMode.Both }).CpuTarget, 80); + Throws(() => CrossCooling.Calculate(double.NaN, 30, 150, new())); + Throws(() => CrossCooling.Calculate(30, double.PositiveInfinity, 150, new())); + }); + Test("six point floor retains nodes, monotonicity and original table", () => + { + var original = new[] { 0, 40, 60, 80, 110, 150 }; + var table = CrossCooling.Floor(original, 75.1, 150); + Check(table.SequenceEqual(new[] { 76, 76, 76, 80, 110, 150 }), "floor table"); + Check(original[0] == 0, "input mutated"); + Check(CrossCooling.ValidCurve(Temps, table, 150), "monotone"); + Throws(() => CrossCooling.Floor(new[] { 0, 50, 40, 60, 70, 80 }, 70, 150)); + Throws(() => CrossCooling.Floor(new[] { 10, 20 }, 70, 150)); + }); + Test("temperature boundaries, sleeping GPU, NaN and infinity", () => + { + foreach (double? bad in new double?[] { null, 0, -1, 116, double.NaN, double.PositiveInfinity }) + Check(!CrossCooling.ValidTemperature(bad), "invalid temperature"); + Check(CrossCooling.ValidTemperature(115), "boundary"); + }); + Test("sensor faults reset scheduler state", () => + { + foreach (double? bad in new double?[] { null, 0, double.NaN }) + { + var p = new CrossCoolingScheduler(); var s = new CrossCoolingSettings { Mode = CrossCoolingMode.Both }; + Check(Sample(p, s, 90, 30) != null, "baseline"); + Check(Sample(p, s, 90, bad) == null && p.LastPlan == null, "fault reset"); + } + }); + Test("stale/future sample and timeout reset", () => + { + var p = new CrossCoolingScheduler(); var s = new CrossCoolingSettings { Mode = CrossCoolingMode.Both }; + Check(Sample(p, s, 90, 30, 7, Epoch) == null, "stale"); + Check(Sample(p, s, 90, 30, 0, Epoch.AddSeconds(1)) == null, "future"); + }); + Test("bounded updates and no duplicate plans", () => + { + var p = new CrossCoolingScheduler(); var s = new CrossCoolingSettings { Mode = CrossCoolingMode.Both }; + Check(Sample(p, s, 80, 30)!.PlanChanged, "first"); + Check(!Sample(p, s, 100, 30, 2)!.PlanChanged, "minimum interval"); + Check(Sample(p, s, 100, 30, 5)!.PlanChanged, "interval elapsed"); + Check(!Sample(p, s, 100, 30, 10)!.PlanChanged, "duplicate"); + }); + Test("hysteresis and gradual decrease", () => + { + var p = new CrossCoolingScheduler(); var s = new CrossCoolingSettings { Mode = CrossCoolingMode.Both }; + Sample(p, s, 90, 30); + Check(!Sample(p, s, 87, 30, 5)!.PlanChanged, "small fall"); + var r = Sample(p, s, 40, 30, 10)!; Check(r.CpuTable[0] == 85, "gradual decline"); + }); + Test("smoothing never delays heat spike or reduces raw-demand floor", () => + { + var p = new CrossCoolingScheduler(); var s = new CrossCoolingSettings { Mode = CrossCoolingMode.Both, Smoothing = true }; + Sample(p, s, 30, 30); + var r = Sample(p, s, 100, 30, 2)!; Near(r.Demand.CpuTarget, 100); Near(r.Demand.GpuTarget, 100); + r = Sample(p, s, 40, 30, 5)!; Check(r.Demand.CpuTarget > 40, "smooth fall"); + }); + Test("off and cancellation discard plan without writes", () => + { + var p = new CrossCoolingScheduler(); var s = new CrossCoolingSettings { Mode = CrossCoolingMode.Both }; + Sample(p, s, 90, 30); s.Mode = CrossCoolingMode.Off; + var r = Sample(p, s, 90, 30, 5)!; + Check(!r.PlanChanged && p.LastPlan == null && r.CpuTable.SequenceEqual(Speeds), "off"); + Check(p.Sample(90, 30, Epoch, Epoch, Temps, Speeds, Temps, Speeds, 150, s, cancelled: true) == null, "cancel"); + }); + Test("conflicts, silent/native mode, boost, diagnostics and unsupported devices", () => + { + var p = new CrossCoolingScheduler(); var s = new CrossCoolingSettings { Mode = CrossCoolingMode.Both }; + foreach (int reason in new[] { 0, 1, 2 }) + Check(p.Sample(90, 30, Epoch, Epoch, Temps, Speeds, Temps, Speeds, 150, s, + supported: reason != 0, singleFan: reason == 1, conflict: reason == 2) == null, "gate"); + }); + Test("profile/curve change can reset schedule", () => + { + var p = new CrossCoolingScheduler(); var s = new CrossCoolingSettings { Mode = CrossCoolingMode.Both }; + Sample(p, s, 90, 30); p.Reset(); + Check(p.LastPlan == null && Sample(p, s, 40, 30, 1)!.PlanChanged, "reset profile"); + }); + Test("scheduler uses CurveModel interpolation rather than raw-temperature average", () => + { + var p = new CrossCoolingScheduler(); var s = new CrossCoolingSettings { Mode = CrossCoolingMode.Both }; + var r = p.Sample(90, 30, Epoch, Epoch, Temps, new[] { 0, 40, 80, 100, 140, 150 }, Temps, Speeds, 150, s)!; + Near(r.Demand.CpuOriginal, 145); Near(r.Demand.GpuTarget, 145); + }); + Test("settings legacy migration, normalization and JSON roundtrip", () => + { + var app = JsonSerializer.Deserialize("{}")!; + Check(app.CrossCooling.Mode == CrossCoolingMode.Off, "legacy default"); + app = JsonSerializer.Deserialize("{\"CrossCooling\":null}")!; app.EnsureDefaults(); + Check(app.CrossCooling.Mode == CrossCoolingMode.Off, "null default"); + app.CrossCooling = new() { Mode = CrossCoolingMode.Both, Algorithm = CoolingMix.PriorityBoost, BoostPercent = 35 }; + var restored = JsonSerializer.Deserialize(JsonSerializer.Serialize(app))!; + Check(restored.CrossCooling.BoostPercent == 35 && restored.CrossCooling.Mode == CrossCoolingMode.Both, "roundtrip"); + restored.CrossCooling.UpdateSeconds = 1; restored.CrossCooling.CpuWeight = restored.CrossCooling.GpuWeight = 0; restored.EnsureDefaults(); + Check(restored.CrossCooling.UpdateSeconds == 5 && restored.CrossCooling.CpuWeight == 50, "normalization"); + }); + Test("application embedded resources survive restricted builds", () => + { + var resources = typeof(AppSettings).Assembly.GetManifestResourceNames(); + foreach (string name in new[] { "GhostDeck.app.ico", "GhostDeck.model-history.json", "GhostDeck.worldmap.txt" }) + Check(resources.Contains(name), "missing embedded resource " + name); + }); + Test("settings clone/import are independent and preserve unknown options", () => + { + var app = JsonSerializer.Deserialize("{\"CrossCooling\":{\"Mode\":3,\"FutureOption\":42}}")!; + app.EnsureDefaults(); var clone = app.Clone(); clone.CrossCooling.CpuWeight = 75; + Check(app.CrossCooling.CpuWeight == 50, "clone alias"); + var target = new AppSettings(); target.ImportFrom(app); target.CrossCooling.Mode = CrossCoolingMode.Off; + Check(app.CrossCooling.Mode == CrossCoolingMode.Both, "import alias"); + Check(JsonSerializer.Serialize(clone).Contains("FutureOption"), "unknown field lost"); + }); + Test("all UI localization keys resolve in every language", () => + { + var map = (Dictionary)typeof(Lang).GetField("Map", BindingFlags.NonPublic | BindingFlags.Static)!.GetValue(null)!; + foreach (var code in Lang.Codes) + { + Lang.Set(code); + foreach (string key in map.Keys.Where(k => k.StartsWith("cc_"))) Check(Lang.T(key) != key, key + "/" + code); + _ = string.Format(Lang.T("cc_values"), 90, 30, "90%", "30%", "90%", "90%", "90%"); + } + Lang.Set("en"); + }); + LiveTests(); + Test("native switch binds to actual live activation and restores on disable", LiveUiTest); + Test("native UI rebuild, themes, languages and disposal without EC writes", UiTest); + Test("Fan Curve page navigation, unsupported-device scheduler and rendering", PageTest); + Test("context menus render dark/light surfaces, states and nested menus", ContextMenuTest); + Test("Cross-Cooling saves enable/options to disk and restores after restart", CoolingPersistenceTest); + Console.WriteLine($"{_passed} tests passed. No physical hardware writes were performed."); + return 0; + } + catch (Exception ex) { Console.Error.WriteLine(ex); return 1; } + finally + { + if (AppSettings.DirOverride is { } dir && Directory.Exists(dir)) Directory.Delete(dir, true); + AppSettings.DirOverride = null; + } + } + + private static CoolingPlan? Sample(CrossCoolingScheduler p, CrossCoolingSettings s, double? cpu, double? gpu, + int seconds = 0, DateTimeOffset? sampled = null) => p.Sample(cpu, gpu, sampled ?? Epoch.AddSeconds(seconds), Epoch.AddSeconds(seconds), Temps, Speeds, Temps, Speeds, 150, s); + + private sealed class FakeHardware : ICrossCoolingHardware + { + public byte AdvancedMode => 0x8D; + public FanCurvePreset Curve = new() { CpuTemp = (int[])Temps.Clone(), CpuSpeed = (int[])Speeds.Clone(), GpuTemp = (int[])Temps.Clone(), GpuSpeed = (int[])Speeds.Clone() }; + public byte Mode = 0x0D; + public int Cpu = 90, Gpu = 30, Applies, Restores, Autos; + public bool Boost, FailApply, FailRestore, FailRead; + public DateTimeOffset Time = Epoch; + public Action? OnApply; + public CoolingBaseline Capture() => new(Curve.Clone(), Mode); + public CoolingReading Read() + { + if (FailRead) throw new IOException("read failure"); + return new(Time, new(Cpu, Gpu, 90, 30, 100, "test", 4000, 2000), Mode, Boost); + } + public void Apply(FanCurvePreset original, int[] cpuSpeeds, int[] gpuSpeeds) + { + Applies++; Curve = original.Clone(); Curve.CpuSpeed = (int[])cpuSpeeds.Clone(); + OnApply?.Invoke(); + if (FailApply) throw new IOException("partial write"); + Curve.GpuSpeed = (int[])gpuSpeeds.Clone(); Mode = AdvancedMode; + } + public void Restore(CoolingBaseline b) + { + Restores++; + if (FailRestore) throw new IOException("restore failure"); + Curve = b.Curve.Clone(); Mode = b.Mode; + } + public void Automatic() { Autos++; Mode = 0x0D; } + } + + private static CrossCoolingSettings LiveSettings(CrossCoolingMode mode = CrossCoolingMode.Both) => new() { Mode = mode }; + private static void LiveTests() + { + Test("live Auto activation writes both tables and enters Advanced", () => + { + var h = new FakeHardware(); using var c = new CrossCoolingController(h, 150); + c.Configure(LiveSettings(), true); c.Tick(Epoch); + Check(h.Applies == 1 && h.Mode == h.AdvancedMode && c.Status.Key == "cc_running", "not active"); + Check(h.Curve.CpuSpeed[0] == 90 && h.Curve.GpuSpeed[0] == 90, "both fans demand"); + Check(c.Status.LastWrite == Epoch && c.Status.Reading!.Value.Hardware.CpuRpm == 4000, "actual status"); + Check(c.Baseline!.CpuSpeed.SequenceEqual(Speeds), "baseline overwritten"); + c.Configure(LiveSettings(), false); + Check(h.Restores == 1 && h.Mode == 0x0D && h.Curve.GpuSpeed.SequenceEqual(Speeds), "disable restore"); + }); + Test("live directional control and exact mode restoration", () => + { + foreach (var mode in new[] { CrossCoolingMode.CpuToGpu, CrossCoolingMode.GpuToCpu }) + { + var h = new FakeHardware { Mode = 0xCD, Cpu = mode == CrossCoolingMode.GpuToCpu ? 30 : 90, Gpu = mode == CrossCoolingMode.GpuToCpu ? 90 : 30 }; + using var c = new CrossCoolingController(h, 150); c.Configure(LiveSettings(mode), true); c.Tick(Epoch); + Check((mode == CrossCoolingMode.CpuToGpu ? h.Curve.CpuSpeed : h.Curve.GpuSpeed).SequenceEqual(Speeds), "source table changed"); + c.Configure(LiveSettings(mode), false); Check(h.Mode == 0xCD, "previous mode lost"); + } + }); + Test("live duplicate and interval writes are bounded", () => + { + var h = new FakeHardware(); using var c = new CrossCoolingController(h, 150); c.Configure(LiveSettings(), true); + c.Tick(Epoch); h.Time = Epoch.AddSeconds(2); h.Cpu = 100; c.Tick(h.Time); Check(h.Applies == 1, "interval ignored"); + h.Time = Epoch.AddSeconds(5); c.Tick(h.Time); Check(h.Applies == 2, "update missing"); + h.Time = Epoch.AddSeconds(10); c.Tick(h.Time); Check(h.Applies == 2, "duplicate write"); + }); + Test("live missing and stale sensors restore and recover", () => + { + foreach (bool stale in new[] { false, true }) + { + var h = new FakeHardware(); using var c = new CrossCoolingController(h, 150); c.Configure(LiveSettings(), true); c.Tick(Epoch); + if (!stale) h.Gpu = 0; + c.Tick(Epoch.AddSeconds(10)); Check(h.Restores == 1 && c.Status.Key == "cc_sensor_paused", "fault not restored"); + h.Gpu = 30; h.Time = Epoch.AddSeconds(12); c.Resume(); c.Tick(h.Time); + Check(h.Applies == 2 && c.Status.Key == "cc_running", "sensor recovery"); + } + }); + Test("live settings changes cannot bypass write interval or keep a deselected fan floor", () => + { + var h = new FakeHardware(); using var c = new CrossCoolingController(h, 150); + c.Configure(LiveSettings(), true); c.Tick(Epoch); + var settings = LiveSettings(CrossCoolingMode.CpuToGpu); + for (int i = 1; i < 5; i++) + { + settings.CpuWeight = i; c.Configure(settings, true); h.Time = Epoch.AddSeconds(i); c.Tick(h.Time); + } + Check(h.Applies == 1 && h.Restores == 0, "settings slider spammed EC"); + h.Time = Epoch.AddSeconds(5); c.Tick(h.Time); + Check(h.Applies == 2 && h.Curve.CpuSpeed.SequenceEqual(Speeds), "source floor retained"); + }); + Test("live Fan Boost suspends and resumes without losing baseline", () => + { + var h = new FakeHardware(); using var c = new CrossCoolingController(h, 150); c.Configure(LiveSettings(), true); c.Tick(Epoch); + h.Boost = true; h.Time = Epoch.AddSeconds(5); c.Tick(h.Time); + Check(h.Restores == 1 && c.Status.Key == "cc_boost_paused" && c.Status.Enabled, "boost pause"); + h.Boost = false; c.Resume(); c.Tick(h.Time); Check(h.Applies == 2, "boost recovery"); + }); + Test("live session suspension blocks queued writes and accepts new curve baseline", () => + { + var h = new FakeHardware(); using var c = new CrossCoolingController(h, 150); c.Configure(LiveSettings(), true); c.Tick(Epoch); + c.Suspend(); c.Tick(Epoch.AddSeconds(5)); Check(h.Applies == 1 && h.Restores == 1, "queued write after suspension"); + h.Curve.CpuSpeed = new[] { 10, 30, 50, 70, 90, 110 }; h.Time = Epoch.AddSeconds(10); + c.Resume(); c.Tick(h.Time); c.Configure(LiveSettings(), false); + Check(h.Curve.CpuSpeed[0] == 10, "new baseline discarded"); + }); + Test("live suspension serializes with an in-flight write", () => + { + using var entered = new ManualResetEventSlim(); using var release = new ManualResetEventSlim(); + var h = new FakeHardware { OnApply = () => { entered.Set(); Check(release.Wait(5000), "write timeout"); } }; + using var c = new CrossCoolingController(h, 150); c.Configure(LiveSettings(), true); + var writer = Task.Run(() => c.Tick(Epoch)); Check(entered.Wait(5000), "write never started"); + var pause = Task.Run(() => c.Suspend()); + release.Set(); Check(Task.WaitAll(new[] { writer, pause }, 5000), "suspension deadlock"); + c.Tick(Epoch); Check(h.Applies == 1 && h.Restores == 1 && h.Mode == 0x0D, "suspension did not restore"); + }); + Test("live partial writes restore and disarm", () => + { + var h = new FakeHardware { FailApply = true }; using var c = new CrossCoolingController(h, 150); + c.Configure(LiveSettings(), true); c.Tick(Epoch); + Check(!c.Status.Enabled && c.Status.Key == "cc_failed" && h.Restores == 1 && h.Curve.CpuSpeed.SequenceEqual(Speeds), "partial write recovery"); + h.FailApply = false; c.Tick(Epoch); Check(h.Applies == 1, "failure silently rearmed"); + }); + Test("live failed restoration retains baseline, requests Auto and retries", () => + { + var h = new FakeHardware(); using var c = new CrossCoolingController(h, 150); c.Configure(LiveSettings(), true); c.Tick(Epoch); + h.FailRestore = true; c.Configure(LiveSettings(), false); + Check(c.Status.Key == "cc_restore_failed" && h.Autos == 1 && c.Baseline != null, "restore failure lost"); + h.FailRestore = false; c.Tick(Epoch.AddSeconds(5)); + Check(c.Status.Key == "cc_disabled" && c.Baseline == null && h.Curve.CpuSpeed.SequenceEqual(Speeds), "retry missing"); + }); + Test("live native mode change disarms and preserves the selected mode", () => + { + var h = new FakeHardware(); using var c = new CrossCoolingController(h, 150); c.Configure(LiveSettings(), true); c.Tick(Epoch); + h.Mode = 0x1D; h.Time = Epoch.AddSeconds(5); c.Tick(h.Time); + Check(!c.Status.Enabled && h.Mode == 0x1D && h.Curve.CpuSpeed.SequenceEqual(Speeds), "native mode overridden"); + }); + Test("live read failure and disposal stop further control", () => + { + var h = new FakeHardware(); var c = new CrossCoolingController(h, 150); c.Configure(LiveSettings(), true); c.Tick(Epoch); + h.FailRead = true; c.Tick(Epoch); Check(!c.Status.Enabled && h.Restores == 1, "read failure left control active"); + h.FailRead = false; c.Configure(LiveSettings(), true); c.Tick(Epoch); c.Dispose(); c.Resume(); c.Tick(Epoch); + Check(h.Applies == 2 && h.Restores == 2, "write after disposal"); + }); + Test("live Off never acquires hardware", () => + { + var h = new FakeHardware { FailRead = true }; using var c = new CrossCoolingController(h, 150); + c.Configure(new(), true); c.Tick(Epoch); Check(!c.Status.Enabled && h.Applies == 0 && h.Restores == 0, "off writes"); + }); + } + + private static void CoolingPersistenceTest() + { + var app = new AppSettings + { + CrossCooling = new() + { + Mode = CrossCoolingMode.Both, Algorithm = CoolingMix.WeightedAverage, + CpuWeight = 75, GpuWeight = 25, SamplingSeconds = 3, UpdateSeconds = 10, + Threshold = 7, IncreaseHysteresis = 2, DecreaseHysteresis = 8, DecreaseStep = 4, + BoostPercent = 60, Smoothing = true, + }, + }; + app.EnsureDefaults(); + var h = new FakeHardware { Time = DateTimeOffset.UtcNow }; + using (var controller = new CrossCoolingController(h, 150)) + { + var deps = Activator.CreateInstance(); + void Set(string name, object value) => typeof(MainDeps).GetProperty(name)!.SetValue(deps, value); + Set("Settings", app); Set("SaveSettings", (Action)app.Save); + Set("Current", (Func)(() => ProfileId.Balanced)); + Set("CoolingStatus", (Func)(() => controller.Status)); + Set("ConfigureCooling", (Action)(on => { controller.Configure(app.CrossCooling, on); controller.Tick(h.Time); })); + using var panel = new CrossCoolingPanel(deps, () => null, () => default); + var toggle = (ToggleSwitch)typeof(CrossCoolingPanel).GetField("_enable", BindingFlags.NonPublic | BindingFlags.Instance)!.GetValue(panel)!; + typeof(ToggleSwitch).GetMethod("OnClick", BindingFlags.NonPublic | BindingFlags.Instance)!.Invoke(toggle, new object[] { EventArgs.Empty }); + Check(app.CrossCooling.Enabled && controller.Status.Enabled, "enable was not saved"); + Check(app.Clone().CrossCooling.Enabled, "clone lost enabled state"); + var imported = new AppSettings(); imported.ImportFrom(app); + Check(imported.CrossCooling.Enabled, "import lost enabled state"); + } + Check(app.CrossCooling.Enabled && h.Mode == 0x0D, "normal exit forgot preference or failed restore"); + var loaded = AppSettings.Load(); + Check(JsonSerializer.Serialize(loaded.CrossCooling) == JsonSerializer.Serialize(app.CrossCooling), + "disk roundtrip lost an option: " + JsonSerializer.Serialize(loaded.CrossCooling) + " expected " + JsonSerializer.Serialize(app.CrossCooling)); + var nextHardware = new FakeHardware { Time = DateTimeOffset.UtcNow }; + using var nextController = new CrossCoolingController(nextHardware, 150); + nextController.Configure(loaded.CrossCooling, loaded.CrossCooling.Enabled); nextController.Tick(nextHardware.Time); + Check(nextController.Status.Enabled && nextHardware.Applies == 1, "restart did not restore enabled choice"); + loaded.CrossCooling.Enabled = false; loaded.Save(); nextController.Configure(loaded.CrossCooling, false); + var disabled = AppSettings.Load(); + Check(!disabled.CrossCooling.Enabled && disabled.CrossCooling.Mode == CrossCoolingMode.Both, "disabled choice or selected mode lost"); + nextController.Configure(disabled.CrossCooling, disabled.CrossCooling.Enabled); nextController.Tick(nextHardware.Time); + Check(!nextController.Status.Enabled && nextHardware.Applies == 1, "disabled restarted control"); + var off = new CrossCoolingSettings { Enabled = true, Mode = CrossCoolingMode.Off }; off.Normalize(); + Check(!off.Enabled, "Off mode retained enabled choice"); + Check(!JsonSerializer.Deserialize("{}")!.CrossCooling.Enabled, "legacy settings activate unexpectedly"); + } + + private static void ContextMenuTest() + { + Lang.Set("en"); + Theme.Set(false); + using var menu = new ThemedContextMenu(); + var normal = new ToolStripMenuItem("Open panel"); + var selected = new ToolStripMenuItem("Selected profile") { Checked = true }; + var disabled = new ToolStripMenuItem("Unavailable") { Enabled = false }; + var custom = new ToolStripMenuItem("Warning") { ForeColor = Color.OrangeRed }; + var parent = new ToolStripMenuItem("Profiles"); + var nested = new ToolStripMenuItem("Nested"); + nested.DropDownItems.Add("Balanced"); parent.DropDownItems.Add(nested); + menu.Items.AddRange(new ToolStripItem[] { new ToolStripLabel("GhostDeck"), normal, selected, + disabled, custom, new ToolStripSeparator(), parent }); + int clicks = 0; normal.Click += (_, _) => clicks++; + var opening = typeof(ThemedContextMenu).GetMethod("OnOpening", BindingFlags.NonPublic | BindingFlags.Instance)!; + void Open() => opening.Invoke(menu, new object[] { new System.ComponentModel.CancelEventArgs() }); + static bool HasColor(Bitmap bitmap, Color color) + { + for (int y = 0; y < bitmap.Height; y++) + for (int x = 0; x < bitmap.Width; x++) + if (bitmap.GetPixel(x, y).ToArgb() == color.ToArgb()) return true; + return false; + } + Bitmap Render(ToolStrip strip) + { + strip.Size = strip.GetPreferredSize(Size.Empty); strip.PerformLayout(); + var bitmap = new Bitmap(strip.Width, strip.Height); + strip.DrawToBitmap(bitmap, strip.ClientRectangle); + return bitmap; + } + foreach (bool dark in new[] { true, false, true }) + { + Theme.Set(dark); Open(); + Check(menu.BackColor == Theme.Surface && normal.ForeColor == Theme.Text, "root theme"); + foreach (var drop in new[] { parent.DropDown, nested.DropDown }) + { + Check(drop.BackColor == Theme.Surface && drop.ForeColor == Theme.Text, "nested theme"); + Check(ReferenceEquals(drop.Renderer, menu.Renderer), "nested renderer"); + using var subBitmap = Render(drop); + Check(HasColor(subBitmap, Theme.Surface), "nested background pixels"); + } + Check(custom.ForeColor == Color.OrangeRed, "custom text color lost"); + selected.Select(); + using var bitmap = Render(menu); + Check(HasColor(bitmap, Theme.Surface), "background pixels"); + Check(HasColor(bitmap, Theme.Text), "text/checkmark pixels"); + Check(HasColor(bitmap, Theme.Muted), "disabled text pixels"); + Check(HasColor(bitmap, Theme.Border), "separator pixels"); + Check(HasColor(bitmap, Theme.AccentSoft), "hover/check background pixels"); + Check(bitmap.GetPixel(selected.Bounds.Right - 5, selected.Bounds.Top + 3).ToArgb() == Theme.AccentSoft.ToArgb(), + "Windows highlight replaced app hover color"); + bitmap.Save(Path.Combine(AppContext.BaseDirectory, dark ? "context-menu-dark.png" : "context-menu-light.png")); + // Update already constructed menus immediately, without opening/rebuilding them. + Theme.Toggle(); + Check(menu.BackColor == Theme.Surface && nested.DropDown.BackColor == Theme.Surface, "live theme change"); + } + normal.PerformClick(); disabled.PerformClick(); Check(clicks == 1, "menu action changed"); + // A dynamically added submenu gets the palette on the next opening. + var late = new ToolStripMenuItem("New scene"); late.DropDownItems.Add("Run"); menu.Items.Add(late); Open(); + Check(late.DropDown.BackColor == Theme.Surface, "dynamic submenu"); + menu.Dispose(); Theme.Toggle(); Theme.Toggle(); // no disposed handler retained + Theme.Set(false); + } + + private static void LiveUiTest() + { + var h = new FakeHardware { Time = DateTimeOffset.UtcNow }; + using var c = new CrossCoolingController(h, 150); + var d = Activator.CreateInstance(); + void Set(string name, object value) => typeof(MainDeps).GetProperty(name)!.SetValue(d, value); + Set("Settings", new AppSettings { CrossCooling = LiveSettings() }); + Set("Current", (Func)(() => ProfileId.Balanced)); Set("SaveSettings", (Action)(() => { })); + Set("CoolingStatus", (Func)(() => c.Status)); + Set("ConfigureCooling", (Action)(on => { c.Configure(d.Settings.CrossCooling, on); c.Tick(h.Time); })); + using var panel = new CrossCoolingPanel(d, () => null, () => default); + var toggle = (ToggleSwitch)typeof(CrossCoolingPanel).GetField("_enable", BindingFlags.NonPublic | BindingFlags.Instance)!.GetValue(panel)!; + Check(!toggle.Checked, "saved mode falsely shows active control"); + var click = typeof(ToggleSwitch).GetMethod("OnClick", BindingFlags.NonPublic | BindingFlags.Instance)!; + click.Invoke(toggle, new object[] { EventArgs.Empty }); + Check(toggle.Checked && c.Status.Enabled && h.Applies == 1, "switch did not activate hardware adapter"); + var label = (Label)typeof(CrossCoolingPanel).GetField("_values", BindingFlags.NonPublic | BindingFlags.Instance)!.GetValue(panel)!; + Check(label.Text.Contains("Calculated targets") && !label.Text.Contains("live control disabled"), "live display wrong"); + panel.Rebuild(); panel.Visible = false; + Check(c.Status.Enabled && h.Restores == 0, "hiding page disabled tray controller"); + click.Invoke(toggle, new object[] { EventArgs.Empty }); + Check(!c.Status.Enabled && !toggle.Checked && h.Restores == 1, "switch did not restore"); + Check(d.Settings.CrossCooling.Mode == CrossCoolingMode.Both, "disable lost saved mode"); + } + + private static void UiTest() + { + var d = Activator.CreateInstance(); + void Set(string name, object value) => typeof(MainDeps).GetProperty(name)!.SetValue(d, value); + Set("Settings", new AppSettings()); Set("Current", (Func)(() => ProfileId.Balanced)); + Set("SaveSettings", (Action)(() => { })); Set("CoolerBoost", (Func)(() => false)); + using var panel = new CrossCoolingPanel(d, () => null, () => default); + panel.CreateControl(); + foreach (string lang in Lang.Codes) + { + Lang.Set(lang); Theme.Set(true); panel.Width = 400; panel.Height = 500; panel.Rebuild(); + Theme.Set(false); panel.Rebuild(); + Check(panel.Controls.Count == 1, "rebuild leaked root"); + } + Lang.Set("en"); + var field = typeof(CrossCoolingPanel).GetField("_mode", BindingFlags.NonPublic | BindingFlags.Instance)!; + var combo = (ThemedComboBox)field.GetValue(panel)!; + foreach (var mode in Enum.GetValues()) { combo.SelectedIndex = (int)mode; Check(d.Settings.CrossCooling.Mode == mode, "mode UI"); } + panel.UpdateStatus(); panel.Rebuild(); + Check(!combo.IsDisposed, "retained control disposed"); + Check(typeof(CrossCoolingPanel).GetField("_simulate", BindingFlags.NonPublic | BindingFlags.Instance) == null, + "simulated temperature controls remain"); + } + + private static void PageTest() + { + var d = Activator.CreateInstance(); + void Set(string name, object value) => typeof(MainDeps).GetProperty(name)!.SetValue(d, value); + Set("Settings", new AppSettings()); Set("Current", (Func)(() => ProfileId.Balanced)); + Set("SaveSettings", (Action)(() => { })); Set("SettingsChanged", (Action)(() => { })); + Set("CoolerBoost", (Func)(() => false)); Set("Writable", (Func)(() => false)); + Set("Firmware", (Func)(() => "")); Set("Simulating", (Func)(() => true)); + Set("ColorOf", (Func)(_ => Theme.Accent)); + Set("Status", (Func)(() => new(ProfileId.Balanced, false, false, "", "", Theme.Text, 0, TimeSpan.Zero, false, "test"))); + using var host = new Form { Size = new Size(1000, 900), ShowInTaskbar = false, + StartPosition = FormStartPosition.Manual, Location = new Point(-20000, -20000) }; + using var page = new FanCurvePage(d); + host.Controls.Add(page); host.CreateControl(); page.CreateControl(); + host.Show(); + var select = typeof(FanCurvePage).GetMethod("SelectView", BindingFlags.NonPublic | BindingFlags.Instance)!; + var panel = (CrossCoolingPanel)typeof(FanCurvePage).GetField("_cross", BindingFlags.NonPublic | BindingFlags.Instance)!.GetValue(page)!; + select.Invoke(page, new object[] { 4, true }); + Check(panel.Visible, "Cross-Cooling panel is hidden"); + Check(d.Settings.FanCurveView == 4, "view persistence"); + panel.UpdateStatus(); + var values = (Label)typeof(CrossCoolingPanel).GetField("_values", BindingFlags.NonPublic | BindingFlags.Instance)!.GetValue(panel)!; + Check(values.Text.Contains("Hardware readings unavailable"), "fabricated hardware readings"); + foreach (bool dark in new[] { true, false }) + { + Theme.Set(dark); page.ApplyTheme(); page.OnLanguageChanged(); + page.PerformLayout(); panel.PerformLayout(); + using var bitmap = new Bitmap(page.Width, page.Height); + page.DrawToBitmap(bitmap, page.ClientRectangle); + bitmap.Save(Path.Combine(AppContext.BaseDirectory, dark ? "cross-cooling-dark.png" : "cross-cooling-light.png")); + } + foreach (int view in new[] { 0, 1, 2, 3, 4 }) select.Invoke(page, new object[] { view, true }); + Set("Firmware", (Func)(() => "17S1IMS1.114")); + using var supportedPage = new FanCurvePage(d); + host.Controls.Remove(page); host.Controls.Add(supportedPage); + select.Invoke(supportedPage, new object[] { 4, false }); + select.Invoke(supportedPage, new object[] { 0, false }); + var curveSwitch = (ToggleSwitch)typeof(FanCurvePage).GetField("_enable", BindingFlags.NonPublic | BindingFlags.Instance)!.GetValue(supportedPage)!; + Check(curveSwitch.Visible, "editing controls were not restored after Cross-Cooling"); + Theme.Set(false); + } +} diff --git a/tools/restricted-build.py b/tools/restricted-build.py new file mode 100644 index 0000000..7afa6d3 --- /dev/null +++ b/tools/restricted-build.py @@ -0,0 +1,58 @@ +"""Compile with MSBuild's exact compiler arguments when a restricted runner blocks its pipes. + +Normal developer builds should use dotnet build. This fallback still runs the compiler, +including analyzers, and only skips MSBuild's redundant compiler launch after it succeeds. +Usage: python tools/restricted-build.py [--configuration Release] [--tests] [--publish] +""" +import argparse +import json +from pathlib import Path +import subprocess + + +def run(args, cwd, capture=False): + return subprocess.run(args, cwd=cwd, check=True, text=True, encoding="utf-8", + stdout=subprocess.PIPE if capture else None).stdout + + +def build(project, configuration, publish=False): + cwd = project.parent + properties = ["-p:PublishProfile=FolderProfile"] if publish else [] + run(["dotnet", "restore", str(project), "--disable-build-servers", "-v:q", *properties], cwd) + command = ["dotnet", "msbuild", str(project), "-t:Clean;PrepareResources;Compile", + "-p:BuildProjectReferences=false", "-p:SkipCompilerExecution=true", + "-p:ProvideCommandLineArgs=true", f"-p:Configuration={configuration}", + "-getItem:CscCommandLineArgs", "-getProperty:MSBuildSDKsPath", *properties] + raw = run(command, cwd, capture=True) + data = json.loads(raw[raw.index("{"):]) + compiler = Path(data["Properties"]["MSBuildSDKsPath"]).parent / "Roslyn/bincore/csc.dll" + args = [item["Identity"] for item in data["Items"]["CscCommandLineArgs"] + if item["Identity"] != "/noconfig"] + if not args: + raise RuntimeError("MSBuild returned no compiler arguments") + rsp = cwd / "obj/restricted-compiler.rsp" + rsp.write_text("\n".join(args), encoding="utf-8") + run(["dotnet", str(compiler), "/noconfig", "@" + str(rsp)], cwd) + run(["dotnet", "publish" if publish else "build", str(project), "--no-restore", "--disable-build-servers", + "-p:BuildProjectReferences=false", "-p:SkipCompilerExecution=true", + "-c", configuration, "-v:q", *properties], cwd) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--configuration", choices=["Debug", "Release"], default="Debug") + parser.add_argument("--tests", action="store_true") + parser.add_argument("--publish", action="store_true", help="Publish with the existing FolderProfile after validation") + options = parser.parse_args() + root = Path(__file__).resolve().parent.parent + build(root / "GhostDeck.csproj", options.configuration) + if options.tests: + build(root / "tests/GhostDeck.Tests.csproj", options.configuration) + run(["dotnet", str(root / "tests/bin" / options.configuration / + "net11.0-windows7.0/GhostDeck.Tests.dll")], root) + if options.publish: + build(root / "GhostDeck.csproj", options.configuration, publish=True) + + +if __name__ == "__main__": + main()