diff --git a/MainWindow.Behaviors.partial.cs b/MainWindow.Behaviors.partial.cs index fec2c6a..bc7bedf 100644 --- a/MainWindow.Behaviors.partial.cs +++ b/MainWindow.Behaviors.partial.cs @@ -31,6 +31,7 @@ namespace ThreadPilot using System.Windows.Media.Imaging; using Microsoft.Extensions.DependencyInjection; using ThreadPilot.Helpers; + using ThreadPilot.Models; using ThreadPilot.Services; using ThreadPilot.ViewModels; using ThreadPilot.Views; @@ -1105,7 +1106,13 @@ namespace ThreadPilot } }; this.systemTrayUpdateTimer.AutoReset = true; - this.systemTrayUpdateTimer.Start(); + + if (!this.isSystemTrayUpdatesSuspended && + this.IsVisible && + this.WindowState != WindowState.Minimized) + { + this.systemTrayUpdateTimer.Start(); + } } catch (Exception ex) { @@ -1259,6 +1266,7 @@ namespace ThreadPilot this.mainWindowViewModel.IsDarkTheme = useDarkTheme; this.systemTrayService.ApplyTheme(useDarkTheme); DwmHelper.ApplyWindowCaptionTheme(this, useDarkTheme); + this.ApplySelfResourcePolicy(this.lastAppliedRefreshState ?? this.GetForegroundActivityState(), e.NewSettings); } private void OnMonitoringStatusChanged(object? sender, MonitoringStatusEventArgs e) @@ -1366,6 +1374,13 @@ namespace ThreadPilot private void ApplyAppRefreshPolicy(AppActivityState state) { + if (!AppRefreshPolicy.ShouldApplyTransition(this.lastAppliedRefreshState, state)) + { + return; + } + + this.lastAppliedRefreshState = state; + var decision = AppRefreshPolicy.Evaluate(state); var isHiddenState = state is AppActivityState.Minimized or AppActivityState.TrayHidden; var isProcessViewActive = state == AppActivityState.ForegroundProcessView; @@ -1401,6 +1416,22 @@ namespace ThreadPilot { _ = this.performanceViewModel.SuspendBackgroundMonitoringAsync(); } + + this.ApplySelfResourcePolicy(state); + } + + private void ApplySelfResourcePolicy(AppActivityState state, ApplicationSettingsModel? settings = null) + { + var currentSettings = settings ?? this.settingsService.Settings; + var isHiddenState = state is AppActivityState.Minimized or AppActivityState.TrayHidden; + + if (isHiddenState && currentSettings.EnableSelfLowImpactMode) + { + this.selfResourceManagementService.ApplyLowImpactMode(currentSettings.EnableSelfAffinityLimit); + return; + } + + this.selfResourceManagementService.RestoreForegroundMode(); } protected override void OnSourceInitialized(EventArgs e) diff --git a/MainWindow.xaml.cs b/MainWindow.xaml.cs index 8c189f5..4e98593 100644 --- a/MainWindow.xaml.cs +++ b/MainWindow.xaml.cs @@ -54,6 +54,7 @@ namespace ThreadPilot private readonly SettingsViewModel settingsViewModel; private readonly MainWindowViewModel mainWindowViewModel; private readonly SystemTweaksViewModel systemTweaksViewModel; + private readonly ISelfResourceManagementService selfResourceManagementService; private readonly IKeyboardShortcutService keyboardShortcutService; private readonly IServiceProvider serviceProvider; private readonly IThemeService themeService; @@ -61,6 +62,7 @@ namespace ThreadPilot private bool isSystemTrayUpdatesSuspended; private int isSystemTrayUpdateInProgress; private int systemTrayUpdateFailureStreak; + private AppActivityState? lastAppliedRefreshState; private readonly IElevationService elevationService; private readonly ISecurityService securityService; @@ -93,6 +95,7 @@ namespace ThreadPilot SettingsViewModel settingsViewModel, MainWindowViewModel mainWindowViewModel, SystemTweaksViewModel systemTweaksViewModel, + ISelfResourceManagementService selfResourceManagementService, IKeyboardShortcutService keyboardShortcutService, IThemeService themeService, IServiceProvider serviceProvider, @@ -125,6 +128,7 @@ namespace ThreadPilot this.settingsViewModel = settingsViewModel; this.mainWindowViewModel = mainWindowViewModel; this.systemTweaksViewModel = systemTweaksViewModel; + this.selfResourceManagementService = selfResourceManagementService; this.keyboardShortcutService = keyboardShortcutService; this.themeService = themeService; this.serviceProvider = serviceProvider; @@ -156,4 +160,3 @@ namespace ThreadPilot } } } - diff --git a/Models/ApplicationSettingsModel.cs b/Models/ApplicationSettingsModel.cs index 474c71d..16972e6 100644 --- a/Models/ApplicationSettingsModel.cs +++ b/Models/ApplicationSettingsModel.cs @@ -171,6 +171,12 @@ namespace ThreadPilot.Models [ObservableProperty] private bool hasSeenElevationWarning = false; + [ObservableProperty] + private bool enableSelfLowImpactMode = false; + + [ObservableProperty] + private bool enableSelfAffinityLimit = false; + [ObservableProperty] private int maxLogFileSizeMb = 10; @@ -243,6 +249,8 @@ namespace ThreadPilot.Models this.EnablePerformanceCounters = other.EnablePerformanceCounters; this.HasSeenPerformanceIntro = other.HasSeenPerformanceIntro; this.HasSeenElevationWarning = other.HasSeenElevationWarning; + this.EnableSelfLowImpactMode = other.EnableSelfLowImpactMode; + this.EnableSelfAffinityLimit = other.EnableSelfAffinityLimit; this.MaxLogFileSizeMb = other.MaxLogFileSizeMb; this.LogRetentionDays = other.LogRetentionDays; diff --git a/Services/AppRefreshPolicy.cs b/Services/AppRefreshPolicy.cs index 80a6cbf..e766bcc 100644 --- a/Services/AppRefreshPolicy.cs +++ b/Services/AppRefreshPolicy.cs @@ -43,6 +43,11 @@ namespace ThreadPilot.Services /// public static class AppRefreshPolicy { + public static bool ShouldApplyTransition(AppActivityState? previousState, AppActivityState nextState) + { + return previousState != nextState; + } + public static AppRefreshDecision Evaluate(AppActivityState state) { return state switch diff --git a/Services/ISelfResourceManagementService.cs b/Services/ISelfResourceManagementService.cs new file mode 100644 index 0000000..dc7e7f6 --- /dev/null +++ b/Services/ISelfResourceManagementService.cs @@ -0,0 +1,25 @@ +/* + * ThreadPilot - Advanced Windows Process and Power Plan Manager + * Copyright (C) 2025 Prime Build + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, version 3 only. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ +namespace ThreadPilot.Services +{ + public interface ISelfResourceManagementService + { + void ApplyLowImpactMode(bool limitAffinity); + + void RestoreForegroundMode(); + } +} diff --git a/Services/SelfResourceManagementService.cs b/Services/SelfResourceManagementService.cs new file mode 100644 index 0000000..8b9cace --- /dev/null +++ b/Services/SelfResourceManagementService.cs @@ -0,0 +1,208 @@ +/* + * ThreadPilot - Advanced Windows Process and Power Plan Manager + * Copyright (C) 2025 Prime Build + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, version 3 only. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ +namespace ThreadPilot.Services +{ + using System; + using System.ComponentModel; + using System.Diagnostics; + using Microsoft.Extensions.Logging; + + public static class SelfResourcePolicy + { + public static bool TryCreateLowImpactAffinityMask(int logicalProcessorCount, out long affinityMask) + { + affinityMask = 0; + + if (logicalProcessorCount <= 2 || logicalProcessorCount >= 64) + { + return false; + } + + var selectedProcessorCount = logicalProcessorCount >= 4 ? 2 : 1; + for (var index = logicalProcessorCount - selectedProcessorCount; index < logicalProcessorCount; index++) + { + affinityMask |= 1L << index; + } + + return affinityMask != 0; + } + } + + public sealed class SelfResourceManagementService : ISelfResourceManagementService + { + private readonly ILogger logger; + private readonly object syncRoot = new(); + private ProcessPriorityClass? originalPriority; + private IntPtr? originalAffinity; + private bool priorityLowered; + private bool affinityConstrained; + + public SelfResourceManagementService(ILogger logger) + { + this.logger = logger ?? throw new ArgumentNullException(nameof(logger)); + } + + public void ApplyLowImpactMode(bool limitAffinity) + { + lock (this.syncRoot) + { + this.TryLowerPriority(); + + if (limitAffinity) + { + this.TryConstrainAffinity(); + return; + } + + this.TryRestoreAffinity(); + } + } + + public void RestoreForegroundMode() + { + lock (this.syncRoot) + { + this.TryRestoreAffinity(); + this.TryRestorePriority(); + } + } + + private void TryLowerPriority() + { + if (this.priorityLowered) + { + return; + } + + try + { + using var process = Process.GetCurrentProcess(); + var currentPriority = process.PriorityClass; + if (!ShouldLowerPriority(currentPriority)) + { + return; + } + + this.originalPriority = currentPriority; + process.PriorityClass = ProcessPriorityClass.BelowNormal; + this.priorityLowered = true; + this.logger.LogDebug("Lowered ThreadPilot priority from {OriginalPriority} to BelowNormal", currentPriority); + } + catch (Win32Exception ex) + { + this.logger.LogDebug(ex, "Windows blocked ThreadPilot self-priority lowering"); + } + catch (Exception ex) + { + this.logger.LogDebug(ex, "Failed to lower ThreadPilot priority"); + } + } + + private void TryConstrainAffinity() + { + if (this.affinityConstrained) + { + return; + } + + try + { + if (!SelfResourcePolicy.TryCreateLowImpactAffinityMask(Environment.ProcessorCount, out var candidateMask)) + { + return; + } + + using var process = Process.GetCurrentProcess(); + var currentAffinity = process.ProcessorAffinity; + var effectiveMask = candidateMask & currentAffinity.ToInt64(); + if (effectiveMask == 0 || effectiveMask == currentAffinity.ToInt64()) + { + return; + } + + this.originalAffinity = currentAffinity; + process.ProcessorAffinity = new IntPtr(effectiveMask); + this.affinityConstrained = true; + this.logger.LogDebug("Constrained ThreadPilot affinity from 0x{OriginalAffinity:X} to 0x{LowImpactAffinity:X}", currentAffinity.ToInt64(), effectiveMask); + } + catch (Win32Exception ex) + { + this.logger.LogDebug(ex, "Windows blocked ThreadPilot self-affinity limiting"); + } + catch (Exception ex) + { + this.logger.LogDebug(ex, "Failed to constrain ThreadPilot affinity"); + } + } + + private void TryRestoreAffinity() + { + if (!this.affinityConstrained || this.originalAffinity == null) + { + return; + } + + try + { + using var process = Process.GetCurrentProcess(); + process.ProcessorAffinity = this.originalAffinity.Value; + this.logger.LogDebug("Restored ThreadPilot affinity to 0x{OriginalAffinity:X}", this.originalAffinity.Value.ToInt64()); + } + catch (Exception ex) + { + this.logger.LogDebug(ex, "Failed to restore ThreadPilot affinity"); + } + finally + { + this.affinityConstrained = false; + this.originalAffinity = null; + } + } + + private void TryRestorePriority() + { + if (!this.priorityLowered || this.originalPriority == null) + { + return; + } + + try + { + using var process = Process.GetCurrentProcess(); + process.PriorityClass = this.originalPriority.Value; + this.logger.LogDebug("Restored ThreadPilot priority to {OriginalPriority}", this.originalPriority.Value); + } + catch (Exception ex) + { + this.logger.LogDebug(ex, "Failed to restore ThreadPilot priority"); + } + finally + { + this.priorityLowered = false; + this.originalPriority = null; + } + } + + private static bool ShouldLowerPriority(ProcessPriorityClass priority) + { + return priority is ProcessPriorityClass.Normal + or ProcessPriorityClass.AboveNormal + or ProcessPriorityClass.High + or ProcessPriorityClass.RealTime; + } + } +} diff --git a/Services/ServiceConfiguration.cs b/Services/ServiceConfiguration.cs index e311e55..eb70c5e 100644 --- a/Services/ServiceConfiguration.cs +++ b/Services/ServiceConfiguration.cs @@ -147,6 +147,7 @@ namespace ThreadPilot.Services // Application configuration and settings services.AddSingleton(); services.AddSingleton(); + services.AddSingleton(); // User interface services services.AddSingleton(); diff --git a/Services/SystemTrayService.cs b/Services/SystemTrayService.cs index bcb6143..bdfd866 100644 --- a/Services/SystemTrayService.cs +++ b/Services/SystemTrayService.cs @@ -378,6 +378,11 @@ namespace ThreadPilot.Services public void ApplyTheme(bool useDarkTheme) { + if (this.isDarkTheme == useDarkTheme) + { + return; + } + this.isDarkTheme = useDarkTheme; this.ApplyContextMenuTheme(); } diff --git a/Services/ThemeService.cs b/Services/ThemeService.cs index 5adf595..17e61b5 100644 --- a/Services/ThemeService.cs +++ b/Services/ThemeService.cs @@ -51,6 +51,14 @@ namespace ThreadPilot.Services try { + if (this.IsDarkTheme == useDarkTheme && + this.activeThemeDictionary?.Source?.OriginalString != null && + string.Equals(this.activeThemeDictionary.Source.OriginalString, targetUri.OriginalString, StringComparison.OrdinalIgnoreCase) && + appResources.MergedDictionaries.Contains(this.activeThemeDictionary)) + { + return; + } + for (int i = appResources.MergedDictionaries.Count - 1; i >= 0; i--) { var dictionary = appResources.MergedDictionaries[i]; diff --git a/Tests/ThreadPilot.Core.Tests/AppRefreshPolicyTests.cs b/Tests/ThreadPilot.Core.Tests/AppRefreshPolicyTests.cs index f78bca4..59d5742 100644 --- a/Tests/ThreadPilot.Core.Tests/AppRefreshPolicyTests.cs +++ b/Tests/ThreadPilot.Core.Tests/AppRefreshPolicyTests.cs @@ -40,5 +40,21 @@ namespace ThreadPilot.Core.Tests Assert.False(decision.PowerPlanUiRefreshEnabled); Assert.True(decision.BackgroundAutomationEnabled); } + + [Theory] + [InlineData(null, AppActivityState.ForegroundProcessView, true)] + [InlineData(AppActivityState.ForegroundProcessView, AppActivityState.ForegroundProcessView, false)] + [InlineData(AppActivityState.ForegroundOtherTab, AppActivityState.ForegroundOtherTab, false)] + [InlineData(AppActivityState.Minimized, AppActivityState.Minimized, false)] + [InlineData(AppActivityState.TrayHidden, AppActivityState.TrayHidden, false)] + [InlineData(AppActivityState.TrayHidden, AppActivityState.ForegroundProcessView, true)] + [InlineData(AppActivityState.ForegroundProcessView, AppActivityState.ForegroundOtherTab, true)] + public void ShouldApplyTransition_SkipsRedundantStateTransitions( + AppActivityState? previousState, + AppActivityState nextState, + bool expected) + { + Assert.Equal(expected, AppRefreshPolicy.ShouldApplyTransition(previousState, nextState)); + } } } diff --git a/Tests/ThreadPilot.Core.Tests/SelfResourcePolicyTests.cs b/Tests/ThreadPilot.Core.Tests/SelfResourcePolicyTests.cs new file mode 100644 index 0000000..1a4767e --- /dev/null +++ b/Tests/ThreadPilot.Core.Tests/SelfResourcePolicyTests.cs @@ -0,0 +1,37 @@ +namespace ThreadPilot.Core.Tests +{ + using ThreadPilot.Services; + + public sealed class SelfResourcePolicyTests + { + [Theory] + [InlineData(1)] + [InlineData(2)] + public void TryCreateLowImpactAffinityMask_DisablesAffinityOnSmallSystems(int logicalProcessorCount) + { + Assert.False(SelfResourcePolicy.TryCreateLowImpactAffinityMask(logicalProcessorCount, out _)); + } + + [Theory] + [InlineData(3, 0b100)] + [InlineData(4, 0b1100)] + [InlineData(8, 0b1100_0000)] + public void TryCreateLowImpactAffinityMask_UsesLastLogicalProcessors( + int logicalProcessorCount, + long expectedMask) + { + Assert.True(SelfResourcePolicy.TryCreateLowImpactAffinityMask(logicalProcessorCount, out var mask)); + Assert.Equal(expectedMask, mask); + } + + [Theory] + [InlineData(0)] + [InlineData(-1)] + [InlineData(64)] + [InlineData(128)] + public void TryCreateLowImpactAffinityMask_RejectsInvalidProcessorCounts(int logicalProcessorCount) + { + Assert.False(SelfResourcePolicy.TryCreateLowImpactAffinityMask(logicalProcessorCount, out _)); + } + } +} diff --git a/ThreadPilot.csproj b/ThreadPilot.csproj index 23459c2..be0006e 100644 --- a/ThreadPilot.csproj +++ b/ThreadPilot.csproj @@ -16,10 +16,10 @@ link true CS1998;CS0067;CS0414;WFAC010;IL3000;MVVMTK0034 - 1.1.4 - 1.1.4.0 - 1.1.4.0 - 1.1.4 + 1.1.5 + 1.1.5.0 + 1.1.5.0 + 1.1.5 diff --git a/ViewModels/PowerPlanViewModel.cs b/ViewModels/PowerPlanViewModel.cs index 097ed6c..39e5871 100644 --- a/ViewModels/PowerPlanViewModel.cs +++ b/ViewModels/PowerPlanViewModel.cs @@ -34,7 +34,7 @@ namespace ThreadPilot.ViewModels { private readonly IPowerPlanService powerPlanService; private System.Timers.Timer? refreshTimer; - private bool isAutoRefreshPaused; + private bool isAutoRefreshPaused = true; private int isRefreshInProgress; [ObservableProperty] @@ -97,7 +97,6 @@ namespace ThreadPilot.ViewModels Interlocked.Exchange(ref this.isRefreshInProgress, 0); } }; - this.refreshTimer.Start(); } public void PauseAutoRefresh() @@ -108,10 +107,11 @@ namespace ThreadPilot.ViewModels public void ResumeAutoRefresh(bool refreshImmediately = true) { + var wasPaused = this.isAutoRefreshPaused; this.isAutoRefreshPaused = false; this.refreshTimer?.Start(); - if (!refreshImmediately) + if (!refreshImmediately || !wasPaused) { return; }