diff --git a/.claude/settings.local.json b/.claude/settings.local.json new file mode 100644 index 0000000..0982ce5 --- /dev/null +++ b/.claude/settings.local.json @@ -0,0 +1,13 @@ +{ + "permissions": { + "allow": [ + "Bash(dotnet build:*)", + "Bash(Select-String -Pattern \"error|Build succeeded|Build FAILED\" -Context 0,2)", + "Bash(ls -la \"c:\\\\Users\\\\Lorenzo\\\\Documents\\\\Projects\\\\CPUSetSetter-main\\\\CPUSetSetter\"\" | grep -i \".xaml \")", + "Bash(cat:*)", + "Bash(grep:*)", + "Bash(dotnet run:*)", + "Bash(powershell -Command \"Start-Process ''C:\\\\Users\\\\Lorenzo\\\\Documents\\\\Projects\\\\ThreadPilot\\\\bin\\\\Release\\\\net8.0-windows\\\\win-x64\\\\ThreadPilot.exe'' -Verb RunAs\")" + ] + } +} diff --git a/.gitignore b/.gitignore index 9367abc..519cb3f 100644 --- a/.gitignore +++ b/.gitignore @@ -1,6 +1,13 @@ # Escludi tutti gli .exe *.exe +# Escludi la sorgente CPUSetSetter upstream +/CPUSetSetter-main/ + +# Escludi Markdown tranne il README principale +*.md +!README.md + # Escludi directory di build comuni /bin/ /obj/ diff --git a/App.xaml.cs b/App.xaml.cs index edf44de..383966d 100644 --- a/App.xaml.cs +++ b/App.xaml.cs @@ -1,18 +1,20 @@ -using System.Windows; -using System.Windows.Threading; +using System; +using System.Linq; +using System.Security.Principal; +using System.Threading; using System.Threading.Tasks; +using System.Windows; +using System.Windows.Threading; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using ThreadPilot.Services; using ThreadPilot.ViewModels; -using System; -using System.Linq; -using System.Security.Principal; namespace ThreadPilot { public partial class App : System.Windows.Application { + private Mutex? _singleInstanceMutex; public IServiceProvider ServiceProvider { get; private set; } public App() @@ -32,6 +34,21 @@ namespace ThreadPilot protected override void OnStartup(StartupEventArgs e) { + // Enforce single-instance: bail out if another instance is already running + bool createdNew; + _singleInstanceMutex = new Mutex(initiallyOwned: true, name: "Global\\ThreadPilot_SingleInstance", createdNew: out createdNew); + if (!createdNew) + { + System.Windows.MessageBox.Show( + "ThreadPilot è già in esecuzione.", + "Istanza già aperta", + MessageBoxButton.OK, + MessageBoxImage.Information); + + Shutdown(); + return; + } + // Set up global exception handlers first AppDomain.CurrentDomain.UnhandledException += OnUnhandledException; DispatcherUnhandledException += OnDispatcherUnhandledException; @@ -108,9 +125,14 @@ namespace ThreadPilot // Show the window with explicit visibility settings mainWindow.Visibility = Visibility.Visible; + mainWindow.WindowState = (startMinimized || isAutostart) + ? WindowState.Minimized + : WindowState.Normal; mainWindow.Show(); - mainWindow.WindowState = WindowState.Normal; - mainWindow.Activate(); + if (mainWindow.WindowState != WindowState.Minimized) + { + mainWindow.Activate(); + } logger.LogInformation("Main window displayed successfully"); } @@ -129,6 +151,25 @@ namespace ThreadPilot } } + protected override void OnExit(ExitEventArgs e) + { + if (_singleInstanceMutex != null) + { + try + { + _singleInstanceMutex.ReleaseMutex(); + } + catch + { + // Ignore; we just want to clean up quietly + } + _singleInstanceMutex.Dispose(); + _singleInstanceMutex = null; + } + + base.OnExit(e); + } + [System.Runtime.InteropServices.DllImport("kernel32.dll")] private static extern bool AllocConsole(); diff --git a/Converters/ItemIndexConverter.cs b/Converters/ItemIndexConverter.cs new file mode 100644 index 0000000..57e9b73 --- /dev/null +++ b/Converters/ItemIndexConverter.cs @@ -0,0 +1,34 @@ +using System; +using System.Globalization; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Data; + +namespace ThreadPilot.Converters +{ + /// + /// Converter to get the index of an item in an ItemsControl + /// + public class ItemIndexConverter : IValueConverter + { + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) + { + if (value is DependencyObject item) + { + var itemsControl = ItemsControl.ItemsControlFromItemContainer(item); + if (itemsControl != null) + { + int index = itemsControl.ItemContainerGenerator.IndexFromContainer(item); + return index; + } + } + + return -1; + } + + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + { + throw new NotImplementedException(); + } + } +} diff --git a/Helpers/Converters.cs b/Helpers/Converters.cs index 46eeb6f..6e9f8ad 100644 --- a/Helpers/Converters.cs +++ b/Helpers/Converters.cs @@ -28,16 +28,57 @@ namespace ThreadPilot.Helpers { if (value is long mask) { - var cores = new System.Text.StringBuilder(); - for (int i = 0; i < 16; i++) + var selectedIndices = new System.Collections.Generic.List(); + // Dynamic core count based on system, limited to 64 (long is 64-bit) + int maxCores = Math.Min(64, Environment.ProcessorCount); + + for (int i = 0; i < maxCores; i++) { if ((mask & (1L << i)) != 0) { - if (cores.Length > 0) cores.Append(", "); - cores.Append(i); + selectedIndices.Add(i); } } - return $"CPU {cores}"; + + if (selectedIndices.Count == 0) + return "None"; + + // Build the display string + var indicesStr = string.Join(", ", selectedIndices); + int selectedCount = selectedIndices.Count; + + // Detect if this is likely physical cores only (every other logical processor) + // This heuristic checks if selected indices are evenly spaced by 2 (e.g., 0,2,4,6,8...) + bool isProbablyPhysicalCoresOnly = false; + if (selectedCount > 1 && selectedCount <= maxCores / 2) + { + isProbablyPhysicalCoresOnly = true; + for (int i = 1; i < selectedIndices.Count; i++) + { + if (selectedIndices[i] - selectedIndices[i - 1] != 2) + { + isProbablyPhysicalCoresOnly = false; + break; + } + } + } + + // Choose terminology based on what's selected + string label; + if (selectedCount == maxCores) + { + label = $"All threads (0-{maxCores - 1})"; + } + else if (isProbablyPhysicalCoresOnly && selectedIndices[0] == 0) + { + label = $"Physical cores ({indicesStr}) - {selectedCount} cores"; + } + else + { + label = $"Threads ({indicesStr}) - {selectedCount} threads"; + } + + return label; } return "Unknown"; } diff --git a/Installer/Installer.iss b/Installer/Installer.iss new file mode 100644 index 0000000..f52af82 --- /dev/null +++ b/Installer/Installer.iss @@ -0,0 +1,59 @@ +; ThreadPilot installer script (Inno Setup) +; Requires Inno Setup to build the installer. Adjust MyAppVersion/MyAppBuildDir as needed. + +#define MyAppName "ThreadPilot" +#define MyAppPublisher "ThreadPilot" +#define MyAppURL "https://github.com/" +#define MyAppExeName "ThreadPilot.exe" +#define MyAppVersion "1.0.0" +; Point this to the folder containing the published binaries (e.g. dotnet publish -c Release -r win-x64) +#define MyAppBuildDir "..\\artifacts\\build" + +[Setup] +AppId={{A2A4C8B5-4A9A-4B1B-93F4-5F8B1C7E8C2A} +AppName={#MyAppName} +AppVersion={#MyAppVersion} +AppVerName={#MyAppName} {#MyAppVersion} +AppPublisher={#MyAppPublisher} +AppPublisherURL={#MyAppURL} +AppSupportURL={#MyAppURL} +AppUpdatesURL={#MyAppURL} +DefaultDirName={autopf}\{#MyAppName} +UninstallDisplayIcon={app}\{#MyAppExeName} +ArchitecturesAllowed=x64compatible +ArchitecturesInstallIn64BitMode=x64compatible +DefaultGroupName={#MyAppName} +AllowNoIcons=yes +PrivilegesRequiredOverridesAllowed=dialog +OutputBaseFilename=ThreadPilot_Setup +SetupIconFile=..\ico.ico +SolidCompression=yes +WizardStyle=modern + +[Languages] +Name: "english"; MessagesFile: "compiler:Default.isl" + +[Tasks] +Name: "desktopicon"; Description: "{cm:CreateDesktopIcon}"; GroupDescription: "{cm:AdditionalIcons}"; Flags: unchecked + +[Files] +Source: "{#MyAppBuildDir}\*"; DestDir: "{app}"; Flags: ignoreversion recursesubdirs createallsubdirs; BeforeInstall: KillRunningInstance() + +[Icons] +Name: "{group}\{#MyAppName}"; Filename: "{app}\{#MyAppExeName}" +Name: "{autodesktop}\{#MyAppName}"; Filename: "{app}\{#MyAppExeName}"; Tasks: desktopicon + +[Run] +Filename: "{app}\{#MyAppExeName}"; Description: "{cm:LaunchProgram,{#StringChange(MyAppName, '&', '&&')}}"; Flags: nowait postinstall skipifsilent + +[UninstallRun] +Filename: taskkill.exe; Parameters: "/IM '{#MyAppExeName}' /F"; Flags: runhidden waituntilterminated; RunOnceId: UninstallKill + +[Code] + +procedure KillRunningInstance(); +var + ResultCode: Integer; +begin + Exec('taskkill.exe', '/IM "{#MyAppExeName}" /F', '', SW_HIDE, ewWaitUntilTerminated, ResultCode); +end; diff --git a/MainWindow.xaml b/MainWindow.xaml index 30d54c2..c5cfac5 100644 --- a/MainWindow.xaml +++ b/MainWindow.xaml @@ -70,6 +70,9 @@ + + + @@ -79,11 +82,8 @@ - - - - + @@ -94,17 +94,6 @@ - - - - - - - await InitializeApplicationAsync()); System.Diagnostics.Debug.WriteLine("Async initialization started"); - - SetupTestKeyBinding(); System.Diagnostics.Debug.WriteLine("MainWindow constructor completed successfully"); } catch (Exception ex) @@ -125,60 +120,36 @@ namespace ThreadPilot // Set DataContext for the system tweaks view SystemTweaksView.DataContext = _systemTweaksViewModel; - } - private void LogDebug(string message) - { - var timestamp = DateTime.Now.ToString("HH:mm:ss.fff"); - var logMessage = $"[{timestamp}] {message}"; - - try - { - System.Diagnostics.Debug.WriteLine(logMessage); - File.AppendAllText(_debugLogPath, logMessage + Environment.NewLine); - } - catch - { - // Ignore file write errors - } + // Set DataContext for the settings view + SettingsView.DataContext = _settingsViewModel; } private void InitializeLoadingOverlay() { try { - // Load application icon for loading overlay - var iconPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "ico.ico"); - if (File.Exists(iconPath)) + var loadingOverlay = FindName("LoadingOverlay") as Grid; + var mainContent = FindName("MainContent") as Grid; + + // Ensure overlay is visible while initialization runs + if (loadingOverlay != null) { - var loadingIcon = FindName("LoadingIcon") as System.Windows.Controls.Image; - if (loadingIcon != null) - { - var bitmap = new BitmapImage(); - bitmap.BeginInit(); - bitmap.UriSource = new Uri(iconPath, UriKind.Absolute); - bitmap.DecodePixelWidth = 64; - bitmap.EndInit(); - loadingIcon.Source = bitmap; - } + loadingOverlay.Visibility = Visibility.Visible; } - // Start spinner animation + // Start spinner animation if available var spinnerAnimation = FindResource("SpinnerAnimation") as Storyboard; spinnerAnimation?.Begin(); - // Start fade-in animation - var fadeInAnimation = FindResource("FadeInAnimation") as Storyboard; - fadeInAnimation?.Begin(); - - // Set up initialization timeout (15 seconds) - _initializationTimeoutTimer = new System.Timers.Timer(15000); + // Set a timeout guard for initialization + _initializationTimeoutTimer = new System.Timers.Timer(15000) + { + AutoReset = false + }; _initializationTimeoutTimer.Elapsed += OnInitializationTimeout; - _initializationTimeoutTimer.AutoReset = false; _initializationTimeoutTimer.Start(); - // Block main content interaction - var mainContent = FindName("MainContent") as Grid; if (mainContent != null) { mainContent.IsHitTestVisible = false; @@ -485,10 +456,6 @@ namespace ThreadPilot InitializeNotifications(); LogDebug("Notifications initialized successfully"); - LogDebug("About to initialize game boost..."); - InitializeGameBoost(); - LogDebug("Game boost initialized successfully"); - LogDebug("About to initialize monitoring..."); await InitializeMonitoringAsync(); LogDebug("Monitoring initialized successfully"); @@ -618,9 +585,114 @@ namespace ThreadPilot Activate(); } - private void OnExitRequested(object? sender, EventArgs e) + private async void OnExitRequested(object? sender, EventArgs e) { - System.Windows.Application.Current.Shutdown(); + await PerformGracefulShutdownAsync(); + } + + /// + /// Performs graceful shutdown with cleanup of all applied optimizations + /// Similar to CPU Set Setter's ExitAppGracefully + /// + private async Task PerformGracefulShutdownAsync() + { + try + { + LogDebug("Starting graceful shutdown..."); + + // 1. Stop monitoring services + try + { + LogDebug("Stopping process monitoring manager..."); + await _processMonitorManagerService.StopAsync(); + LogDebug("Process monitoring manager stopped"); + } + catch (Exception ex) + { + LogDebug($"Error stopping process monitoring: {ex.Message}"); + } + + // 2. Cleanup applied CPU masks (like CPU Set Setter's ClearAllProcessMasksNoSave) + if (_settingsService.Settings.ClearMasksOnClose) + { + try + { + LogDebug("Clearing all applied CPU masks..."); + var processService = _serviceProvider.GetRequiredService(); + await processService.ClearAllAppliedMasksAsync(); + LogDebug("CPU masks cleared"); + } + catch (Exception ex) + { + LogDebug($"Error clearing CPU masks: {ex.Message}"); + } + + // Also reset priorities + try + { + LogDebug("Resetting all process priorities..."); + var processService = _serviceProvider.GetRequiredService(); + await processService.ResetAllProcessPrioritiesAsync(); + LogDebug("Process priorities reset"); + } + catch (Exception ex) + { + LogDebug($"Error resetting priorities: {ex.Message}"); + } + } + + // 3. Restore default power plan if configured + if (_settingsService.Settings.RestoreDefaultPowerPlanOnExit && + !string.IsNullOrEmpty(_settingsService.Settings.DefaultPowerPlanId)) + { + try + { + LogDebug("Restoring default power plan..."); + var powerPlanService = _serviceProvider.GetRequiredService(); + await powerPlanService.SetActivePowerPlanByGuidAsync(_settingsService.Settings.DefaultPowerPlanId); + LogDebug("Default power plan restored"); + } + catch (Exception ex) + { + LogDebug($"Error restoring power plan: {ex.Message}"); + } + } + + // 4. Save settings + try + { + LogDebug("Saving settings..."); + await _settingsService.SaveSettingsAsync(); + LogDebug("Settings saved"); + } + catch (Exception ex) + { + LogDebug($"Error saving settings: {ex.Message}"); + } + + // 5. Dispose tray service + try + { + LogDebug("Disposing system tray..."); + _systemTrayService.Dispose(); + LogDebug("System tray disposed"); + } + catch (Exception ex) + { + LogDebug($"Error disposing tray: {ex.Message}"); + } + + LogDebug("Graceful shutdown completed"); + } + catch (Exception ex) + { + LogDebug($"Error during graceful shutdown: {ex.Message}"); + } + finally + { + // Ensure application exits + System.Windows.Application.Current.Shutdown(); + } } private async void OnMonitoringToggleRequested(object? sender, MonitoringToggleEventArgs e) @@ -822,11 +894,6 @@ namespace ThreadPilot await _notificationService.ShowNotificationAsync("Keyboard Shortcut", "Toggle monitoring shortcut activated"); break; - case ShortcutActions.GameBoostToggle: - // Toggle game boost mode - implementation can be added later - await _notificationService.ShowNotificationAsync("Keyboard Shortcut", "Game Boost toggle shortcut activated"); - break; - case ShortcutActions.PowerPlanHighPerformance: // Switch to high performance power plan - implementation can be added later await _notificationService.ShowNotificationAsync("Keyboard Shortcut", "High Performance power plan shortcut activated"); @@ -883,7 +950,8 @@ namespace ThreadPilot { profileNames = Directory.GetFiles(profilesDirectory, "*.json") .Select(Path.GetFileNameWithoutExtension) - .ToList(); + .Where(name => !string.IsNullOrWhiteSpace(name)) + .ToList()!; } _systemTrayService.UpdateProfiles(profileNames); @@ -986,28 +1054,6 @@ namespace ThreadPilot } } - private void InitializeGameBoost() - { - try - { - // Subscribe to Game Boost events - _gameBoostService.GameBoostActivated += OnGameBoostActivated; - _gameBoostService.GameBoostDeactivated += OnGameBoostDeactivated; - - // Update initial Game Boost status in tray and main window - _systemTrayService.UpdateGameBoostStatus( - _gameBoostService.IsGameBoostActive, - _gameBoostService.CurrentGameProcess?.Name); - _mainWindowViewModel.UpdateGameBoostStatus( - _gameBoostService.IsGameBoostActive, - _gameBoostService.CurrentGameProcess?.Name); - } - catch (Exception ex) - { - System.Diagnostics.Debug.WriteLine($"Failed to initialize Game Boost: {ex.Message}"); - } - } - private async Task InitializeMonitoringAsync() { try @@ -1109,46 +1155,6 @@ namespace ThreadPilot } } - private void OnGameBoostActivated(object? sender, GameBoostActivatedEventArgs e) - { - try - { - // Marshal UI updates to the UI thread to prevent cross-thread access exceptions - Dispatcher.InvokeAsync(() => - { - // Update tray with Game Boost active status - _systemTrayService.UpdateGameBoostStatus(true, e.GameProcess.Name); - - // Update main window status - _mainWindowViewModel.UpdateGameBoostStatus(true, e.GameProcess.Name); - }); - } - catch (Exception ex) - { - System.Diagnostics.Debug.WriteLine($"Error handling Game Boost activation: {ex.Message}"); - } - } - - private void OnGameBoostDeactivated(object? sender, GameBoostDeactivatedEventArgs e) - { - try - { - // Marshal UI updates to the UI thread to prevent cross-thread access exceptions - Dispatcher.InvokeAsync(() => - { - // Update tray with Game Boost inactive status - _systemTrayService.UpdateGameBoostStatus(false); - - // Update main window status - _mainWindowViewModel.UpdateGameBoostStatus(false); - }); - } - catch (Exception ex) - { - System.Diagnostics.Debug.WriteLine($"Error handling Game Boost deactivation: {ex.Message}"); - } - } - protected override void OnStateChanged(EventArgs e) { try @@ -1181,6 +1187,20 @@ namespace ThreadPilot base.OnStateChanged(e); } + private void LogDebug(string message) + { + try + { + var timestampedMessage = $"{DateTime.Now:yyyy-MM-dd HH:mm:ss.fff} [MainWindow] {message}"; + System.Diagnostics.Debug.WriteLine(timestampedMessage); + File.AppendAllText(_debugLogPath, timestampedMessage + Environment.NewLine); + } + catch + { + // Swallow logging failures to avoid impacting runtime behavior + } + } + protected override void OnClosing(System.ComponentModel.CancelEventArgs e) { // Check settings for close behavior @@ -1197,59 +1217,6 @@ namespace ThreadPilot } } - private void SetupTestKeyBinding() - { - // Add Ctrl+Shift+T to run Game Boost tests - var testCommand = new RoutedCommand(); - var testBinding = new KeyBinding(testCommand, Key.T, ModifierKeys.Control | ModifierKeys.Shift); - InputBindings.Add(testBinding); - CommandBindings.Add(new CommandBinding(testCommand, RunGameBoostTests)); - } - - private async void RunGameBoostTests(object sender, ExecutedRoutedEventArgs e) - { - try - { - _mainWindowViewModel.StatusMessage = "Running Game Boost integration tests..."; - - // Validate service configuration first - if (!ThreadPilot.Tests.TestRunner.ValidateServiceConfiguration(_serviceProvider)) - { - _mainWindowViewModel.StatusMessage = "Service configuration validation failed"; - await _notificationService.ShowErrorNotificationAsync( - "Test Failed", - "Service configuration validation failed"); - return; - } - - // Run integration tests - var testResult = await ThreadPilot.Tests.TestRunner.RunGameBoostTestsAsync(_serviceProvider); - - if (testResult) - { - _mainWindowViewModel.StatusMessage = "All Game Boost tests passed successfully!"; - await _notificationService.ShowSuccessNotificationAsync( - "Tests Passed", - "All Game Boost integration tests completed successfully"); - } - else - { - _mainWindowViewModel.StatusMessage = "Game Boost tests failed - check logs for details"; - await _notificationService.ShowErrorNotificationAsync( - "Tests Failed", - "One or more Game Boost tests failed - check logs for details"); - } - } - catch (Exception ex) - { - _mainWindowViewModel.StatusMessage = $"Test execution failed: {ex.Message}"; - await _notificationService.ShowErrorNotificationAsync( - "Test Error", - "Failed to execute Game Boost tests", - ex); - } - } - protected override void OnClosed(EventArgs e) { try diff --git a/Models/ApplicationSettingsModel.cs b/Models/ApplicationSettingsModel.cs index cdd7ae0..87eed60 100644 --- a/Models/ApplicationSettingsModel.cs +++ b/Models/ApplicationSettingsModel.cs @@ -46,7 +46,7 @@ namespace ThreadPilot.Models private bool minimizeToTray = true; [ObservableProperty] - private bool closeToTray = false; + private bool closeToTray = true; // Default true: close to tray like CPU Set Setter [ObservableProperty] private bool startMinimized = false; @@ -101,7 +101,7 @@ namespace ThreadPilot.Models // Autostart Settings [ObservableProperty] - private bool autostartWithWindows = false; + private bool autostartWithWindows = true; // Power Plan Settings [ObservableProperty] @@ -113,6 +113,13 @@ namespace ThreadPilot.Models [ObservableProperty] private bool restoreDefaultPowerPlanOnExit = true; + /// + /// When true, all applied CPU masks are cleared when exiting the application + /// (processes return to using all cores) + /// + [ObservableProperty] + private bool clearMasksOnClose = true; + // Monitoring Settings [ObservableProperty] private int pollingIntervalMs = 5000; @@ -126,28 +133,6 @@ namespace ThreadPilot.Models [ObservableProperty] private bool enableFallbackPolling = true; - // Game Boost Mode Settings - [ObservableProperty] - private bool enableGameBoostMode = false; - - [ObservableProperty] - private string gameBoostPowerPlanId = string.Empty; - - [ObservableProperty] - private string gameBoostPowerPlanName = "High performance"; - - [ObservableProperty] - private bool gameBoostAutoDetectGames = true; - - [ObservableProperty] - private bool gameBoostSetHighPriority = true; - - [ObservableProperty] - private bool gameBoostOptimizeCpuAffinity = true; - - [ObservableProperty] - private int gameBoostDetectionDelayMs = 2000; - // Advanced Settings [ObservableProperty] private bool enableDebugLogging = false; @@ -208,6 +193,7 @@ namespace ThreadPilot.Models DefaultPowerPlanId = other.DefaultPowerPlanId; DefaultPowerPlanName = other.DefaultPowerPlanName; RestoreDefaultPowerPlanOnExit = other.RestoreDefaultPowerPlanOnExit; + ClearMasksOnClose = other.ClearMasksOnClose; // Monitoring Settings PollingIntervalMs = other.PollingIntervalMs; @@ -215,15 +201,6 @@ namespace ThreadPilot.Models EnableWmiMonitoring = other.EnableWmiMonitoring; EnableFallbackPolling = other.EnableFallbackPolling; - // Game Boost Mode Settings - EnableGameBoostMode = other.EnableGameBoostMode; - GameBoostPowerPlanId = other.GameBoostPowerPlanId; - GameBoostPowerPlanName = other.GameBoostPowerPlanName; - GameBoostAutoDetectGames = other.GameBoostAutoDetectGames; - GameBoostSetHighPriority = other.GameBoostSetHighPriority; - GameBoostOptimizeCpuAffinity = other.GameBoostOptimizeCpuAffinity; - GameBoostDetectionDelayMs = other.GameBoostDetectionDelayMs; - // Advanced Settings EnableDebugLogging = other.EnableDebugLogging; EnablePerformanceCounters = other.EnablePerformanceCounters; @@ -279,17 +256,11 @@ namespace ThreadPilot.Models DefaultPowerPlanId = this.DefaultPowerPlanId, DefaultPowerPlanName = this.DefaultPowerPlanName, RestoreDefaultPowerPlanOnExit = this.RestoreDefaultPowerPlanOnExit, + ClearMasksOnClose = this.ClearMasksOnClose, PollingIntervalMs = this.PollingIntervalMs, FallbackPollingIntervalMs = this.FallbackPollingIntervalMs, EnableWmiMonitoring = this.EnableWmiMonitoring, EnableFallbackPolling = this.EnableFallbackPolling, - EnableGameBoostMode = this.EnableGameBoostMode, - GameBoostPowerPlanId = this.GameBoostPowerPlanId, - GameBoostPowerPlanName = this.GameBoostPowerPlanName, - GameBoostAutoDetectGames = this.GameBoostAutoDetectGames, - GameBoostSetHighPriority = this.GameBoostSetHighPriority, - GameBoostOptimizeCpuAffinity = this.GameBoostOptimizeCpuAffinity, - GameBoostDetectionDelayMs = this.GameBoostDetectionDelayMs, EnableDebugLogging = this.EnableDebugLogging, EnablePerformanceCounters = this.EnablePerformanceCounters, MaxLogFileSizeMb = this.MaxLogFileSizeMb, diff --git a/Models/CoreMask.cs b/Models/CoreMask.cs new file mode 100644 index 0000000..a765f6b --- /dev/null +++ b/Models/CoreMask.cs @@ -0,0 +1,133 @@ +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using CommunityToolkit.Mvvm.ComponentModel; + +namespace ThreadPilot.Models +{ + /// + /// Represents a reusable CPU core affinity mask + /// Based on CPUSetSetter's LogicalProcessorMask + /// + public partial class CoreMask : ObservableObject + { + [ObservableProperty] + private string id = Guid.NewGuid().ToString(); + + [ObservableProperty] + private string name = string.Empty; + + [ObservableProperty] + private string description = string.Empty; + + /// + /// Array of boolean values, one per logical core + /// + public ObservableCollection BoolMask { get; set; } = new(); + + [ObservableProperty] + private bool isDefault = false; + + [ObservableProperty] + private bool isEnabled = true; + + [ObservableProperty] + private DateTime createdAt = DateTime.UtcNow; + + [ObservableProperty] + private DateTime updatedAt = DateTime.UtcNow; + + /// + /// Special mask that allows all cores (no restrictions) + /// + public bool IsNoMask => BoolMask.All(b => b); + + /// + /// Gets the count of selected cores + /// + public int SelectedCoreCount => BoolMask.Count(b => b); + + /// + /// Converts the boolean mask to a processor affinity value + /// + public long ToProcessorAffinity() + { + long affinity = 0; + for (int i = 0; i < BoolMask.Count; i++) + { + if (BoolMask[i]) + affinity |= (1L << i); + } + return affinity; + } + + /// + /// Creates a CoreMask from a processor affinity value + /// + public static CoreMask FromProcessorAffinity(long affinity, int coreCount, string name = "Custom") + { + var mask = new CoreMask { Name = name }; + for (int i = 0; i < coreCount; i++) + { + mask.BoolMask.Add(((affinity >> i) & 1) == 1); + } + return mask; + } + + /// + /// Creates a mask with all cores enabled + /// + public static CoreMask CreateAllCoresMask(int coreCount) + { + var mask = new CoreMask + { + Name = "All Cores", + Description = "Use all available CPU cores", + IsDefault = true + }; + + for (int i = 0; i < coreCount; i++) + mask.BoolMask.Add(true); + + return mask; + } + + /// + /// Creates a mask with no cores (empty mask, for deletion purposes) + /// + public static CoreMask CreateNoMask() + { + return new CoreMask + { + Name = "No Restriction", + Description = "Process can use all cores", + IsDefault = false + }; + } + + public CoreMask Clone() + { + var cloned = new CoreMask + { + Id = Guid.NewGuid().ToString(), + Name = this.Name + " (Copy)", + Description = this.Description, + IsEnabled = this.IsEnabled, + IsDefault = false, + CreatedAt = DateTime.UtcNow, + UpdatedAt = DateTime.UtcNow + }; + + foreach (var bit in BoolMask) + cloned.BoolMask.Add(bit); + + return cloned; + } + + public override string ToString() + { + return $"{Name} ({SelectedCoreCount}/{BoolMask.Count} cores)"; + } + } +} diff --git a/Models/CpuTopologyModel.cs b/Models/CpuTopologyModel.cs index 74848ca..f46237f 100644 --- a/Models/CpuTopologyModel.cs +++ b/Models/CpuTopologyModel.cs @@ -19,6 +19,7 @@ namespace ThreadPilot.Models public bool IsHyperThreaded { get; set; } public int? HyperThreadSibling { get; set; } public string Label { get; set; } = string.Empty; + public string LogicalProcessorName { get; set; } = string.Empty; // e.g., "Core0_T0", "Core0_T1" (T0 = physical, T1+ = SMT) [ObservableProperty] private bool isEnabled = true; diff --git a/Models/LogEventTypes.cs b/Models/LogEventTypes.cs index 1939c01..3247c2f 100644 --- a/Models/LogEventTypes.cs +++ b/Models/LogEventTypes.cs @@ -35,23 +35,6 @@ namespace ThreadPilot.Models public const string AssociationTriggered = "AssociationTriggered"; } - /// - /// Game boost related events - /// - public static class GameBoost - { - public const string Activated = "GameBoostActivated"; - public const string Deactivated = "GameBoostDeactivated"; - public const string GameDetected = "GameDetected"; - public const string GameAdded = "GameAdded"; - public const string GameRemoved = "GameRemoved"; - public const string PrioritySet = "ProcessPrioritySet"; - public const string PriorityFailed = "ProcessPriorityFailed"; - public const string AffinitySet = "CpuAffinitySet"; - public const string AffinityFailed = "CpuAffinityFailed"; - public const string ConfigurationChanged = "GameBoostConfigurationChanged"; - } - /// /// User action events /// @@ -123,7 +106,6 @@ namespace ThreadPilot.Models { public const string PowerPlan = "PowerPlan"; public const string ProcessMonitoring = "ProcessMonitoring"; - public const string GameBoost = "GameBoost"; public const string UserAction = "UserAction"; public const string System = "System"; public const string Error = "Error"; diff --git a/Models/ProcessModel.cs b/Models/ProcessModel.cs index 1b81e98..fc20099 100644 --- a/Models/ProcessModel.cs +++ b/Models/ProcessModel.cs @@ -21,7 +21,7 @@ namespace ThreadPilot.Models { ProcessorAffinity = (long)value.ProcessorAffinity; Priority = value.PriorityClass; - MemoryUsage = value.WorkingSet64; + MemoryUsage = value.PrivateMemorySize64; ExecutablePath = value.MainModule?.FileName ?? string.Empty; MainWindowHandle = value.MainWindowHandle; MainWindowTitle = value.MainWindowTitle ?? string.Empty; @@ -70,5 +70,14 @@ namespace ThreadPilot.Models [ObservableProperty] private bool isRegistryPriorityEnabled; + + /// + /// Forces PropertyChanged notification for ProcessorAffinity. + /// Used to update DataGrid binding when affinity changes from background thread. + /// + public void ForceNotifyProcessorAffinityChanged() + { + OnPropertyChanged(nameof(ProcessorAffinity)); + } } } \ No newline at end of file diff --git a/Models/ProcessPowerPlanAssociation.cs b/Models/ProcessPowerPlanAssociation.cs index 757b9f9..138a14f 100644 --- a/Models/ProcessPowerPlanAssociation.cs +++ b/Models/ProcessPowerPlanAssociation.cs @@ -25,6 +25,24 @@ namespace ThreadPilot.Models [ObservableProperty] private string powerPlanName = string.Empty; + /// + /// Core mask ID to apply to this process (optional) + /// + [ObservableProperty] + private string? coreMaskId = null; + + /// + /// Core mask name for display (optional) + /// + [ObservableProperty] + private string? coreMaskName = null; + + /// + /// Process priority to apply (optional) + /// + [ObservableProperty] + private string? processPriority = null; + [ObservableProperty] private bool isEnabled = true; @@ -116,6 +134,9 @@ namespace ThreadPilot.Models ExecutablePath = this.ExecutablePath, PowerPlanGuid = this.PowerPlanGuid, PowerPlanName = this.PowerPlanName, + CoreMaskId = this.CoreMaskId, + CoreMaskName = this.CoreMaskName, + ProcessPriority = this.ProcessPriority, IsEnabled = this.IsEnabled, Description = this.Description, MatchByPath = this.MatchByPath, diff --git a/Platforms/Windows/CpuSetNativeMethods.cs b/Platforms/Windows/CpuSetNativeMethods.cs new file mode 100644 index 0000000..049a518 --- /dev/null +++ b/Platforms/Windows/CpuSetNativeMethods.cs @@ -0,0 +1,65 @@ +using Microsoft.Win32.SafeHandles; +using System; +using System.Runtime.InteropServices; + +namespace ThreadPilot.Platforms.Windows +{ + /// + /// P/Invoke declarations for Windows CPU Set APIs + /// + internal static partial class CpuSetNativeMethods + { + [LibraryImport("kernel32.dll", SetLastError = true)] + public static partial SafeProcessHandle OpenProcess(ProcessAccessFlags access, [MarshalAs(UnmanagedType.Bool)] bool inheritHandle, uint processId); + + [LibraryImport("kernel32.dll", SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + public static partial bool GetSystemCpuSetInformation(IntPtr Information, uint BufferLength, ref uint ReturnedLength, SafeProcessHandle Process, uint Flags); + + [LibraryImport("kernel32.dll", SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + public static partial bool SetProcessDefaultCpuSets(SafeProcessHandle Process, uint[]? CpuSetIds, uint CpuSetIdCount); + + [LibraryImport("kernel32.dll", SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + public static partial bool GetProcessTimes(SafeProcessHandle hProcess, out FILETIME lpCreationTime, out FILETIME lpExitTime, out FILETIME lpKernelTime, out FILETIME lpUserTime); + } + + [Flags] + public enum ProcessAccessFlags : uint + { + PROCESS_QUERY_LIMITED_INFORMATION = 0x00001000, + PROCESS_SET_LIMITED_INFORMATION = 0x00002000 + } + + [StructLayout(LayoutKind.Sequential)] + public struct FILETIME + { + public uint dwLowDateTime; + public uint dwHighDateTime; + + public readonly ulong ULong => (((ulong)dwHighDateTime) << 32) + dwLowDateTime; + } + + [StructLayout(LayoutKind.Sequential)] + public struct SYSTEM_CPU_SET_INFORMATION + { + public uint Size; + public CPU_SET_INFORMATION_TYPE Type; + public uint Id; + public ushort Group; + public byte LogicalProcessorIndex; + public byte CoreIndex; + public byte LastLevelCacheIndex; + public byte NumaNodeIndex; + public byte EfficiencyClass; + public byte AllFlags; + public uint Reserved; + public ulong AllocationTag; + } + + public enum CPU_SET_INFORMATION_TYPE : int + { + CpuSetInformation = 0 + } +} diff --git a/Platforms/Windows/IProcessCpuSetHandler.cs b/Platforms/Windows/IProcessCpuSetHandler.cs new file mode 100644 index 0000000..093ca02 --- /dev/null +++ b/Platforms/Windows/IProcessCpuSetHandler.cs @@ -0,0 +1,39 @@ +using System; + +namespace ThreadPilot.Platforms.Windows +{ + /// + /// Interface for handling CPU Set operations on a specific process + /// + public interface IProcessCpuSetHandler : IDisposable + { + /// + /// Gets the process ID this handler manages + /// + uint ProcessId { get; } + + /// + /// Gets the executable name + /// + string ExecutableName { get; } + + /// + /// Applies a CPU affinity mask to the process using CPU Sets + /// + /// The affinity mask where each bit represents a logical processor + /// If true, clears the CPU Set (allows all cores); if false, applies the mask + /// True if the operation succeeded, false otherwise + bool ApplyCpuSetMask(long affinityMask, bool clearMask = false); + + /// + /// Gets the average CPU usage for this process + /// + /// CPU usage percentage (0-1 range), or -1 if unavailable + double GetAverageCpuUsage(); + + /// + /// Checks if the handler has valid handles to the process + /// + bool IsValid { get; } + } +} diff --git a/Platforms/Windows/ProcessCpuSetHandler.cs b/Platforms/Windows/ProcessCpuSetHandler.cs new file mode 100644 index 0000000..e09b058 --- /dev/null +++ b/Platforms/Windows/ProcessCpuSetHandler.cs @@ -0,0 +1,329 @@ +using Microsoft.Extensions.Logging; +using Microsoft.Win32.SafeHandles; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Runtime.InteropServices; + +namespace ThreadPilot.Platforms.Windows +{ + /// + /// Handles CPU Set operations for a specific process using Windows APIs + /// Based on CPUSetSetter's ProcessHandlerWindows implementation + /// + public class ProcessCpuSetHandler : IProcessCpuSetHandler + { + private static readonly Dictionary _cpuSetIdPerLogicalProcessor; + private static readonly object _staticInitLock = new object(); + private static bool _staticInitialized = false; + + private readonly Queue _cpuTimeMovingAverageBuffer = new(); + private readonly string _executableName; + private readonly uint _pid; + private readonly ILogger? _logger; + + private SafeProcessHandle? _queryLimitedInfoHandle; + private SafeProcessHandle? _setLimitedInfoHandle; + private bool _disposed = false; + + static ProcessCpuSetHandler() + { + _cpuSetIdPerLogicalProcessor = new Dictionary(); + } + + public ProcessCpuSetHandler(uint processId, string executableName, ILogger? logger = null) + { + _pid = processId; + _executableName = executableName ?? $"PID_{processId}"; + _logger = logger; + + // Initialize CPU Set mapping on first use + EnsureStaticInitialization(); + + // Open handle for querying process information + _queryLimitedInfoHandle = CpuSetNativeMethods.OpenProcess( + ProcessAccessFlags.PROCESS_QUERY_LIMITED_INFORMATION, + false, + processId); + + if (_queryLimitedInfoHandle == null || _queryLimitedInfoHandle.IsInvalid) + { + var error = Marshal.GetLastWin32Error(); + _logger?.LogWarning("Failed to open process {ProcessId} for querying: {Error}", processId, new Win32Exception(error).Message); + } + } + + public uint ProcessId => _pid; + public string ExecutableName => _executableName; + public bool IsValid => _queryLimitedInfoHandle != null && !_queryLimitedInfoHandle.IsInvalid; + + private static void EnsureStaticInitialization() + { + if (_staticInitialized) return; + + lock (_staticInitLock) + { + if (_staticInitialized) return; + + try + { + var mapping = GetCpuSetIdPerLogicalProcessor(); + foreach (var kvp in mapping) + { + _cpuSetIdPerLogicalProcessor[kvp.Key] = kvp.Value; + } + _staticInitialized = true; + } + catch (Exception) + { + // If we can't get CPU Set mapping, CPU Sets won't be available + // The handler will still work but ApplyCpuSetMask will return false + } + } + } + + public double GetAverageCpuUsage() + { + if (_queryLimitedInfoHandle == null || _queryLimitedInfoHandle.IsInvalid) + { + return -1; + } + + try + { + DateTime now = DateTime.Now; + + // Remove datapoints older than 30 seconds from the moving average buffer + while (_cpuTimeMovingAverageBuffer.Count > 0) + { + TimeSpan datapointAge = now - _cpuTimeMovingAverageBuffer.Peek().Timestamp; + if (datapointAge.TotalSeconds > 30) + { + _cpuTimeMovingAverageBuffer.Dequeue(); + } + else + { + break; + } + } + + // Get the current total CPU time of the process + bool success = CpuSetNativeMethods.GetProcessTimes( + _queryLimitedInfoHandle, + out _, + out _, + out FILETIME kernelTime, + out FILETIME userTime); + + if (!success) + { + return -1; + } + + TimeSpan totalCpuTime = TimeSpan.FromTicks((long)(kernelTime.ULong + userTime.ULong)); + _cpuTimeMovingAverageBuffer.Enqueue(new CpuTimeTimestamp + { + Timestamp = now, + TotalCpuTime = totalCpuTime + }); + + // Need at least 2 samples to calculate usage + if (_cpuTimeMovingAverageBuffer.Count < 2) + { + return 0; + } + + // Take the CPU time from now and (up to) a minute ago, and get the average usage % + CpuTimeTimestamp startDatapoint = _cpuTimeMovingAverageBuffer.Peek(); + TimeSpan deltaTime = now - startDatapoint.Timestamp; + TimeSpan deltaCpuTime = totalCpuTime - startDatapoint.TotalCpuTime; + + if (deltaCpuTime.Ticks == 0 || deltaTime.Ticks == 0) + { + return 0; + } + + return (double)deltaCpuTime.Ticks / deltaTime.Ticks / Environment.ProcessorCount; + } + catch + { + return -1; + } + } + + public bool ApplyCpuSetMask(long affinityMask, bool clearMask = false) + { + if (_disposed) + { + throw new ObjectDisposedException(nameof(ProcessCpuSetHandler)); + } + + // Ensure we have CPU Set mapping + if (_cpuSetIdPerLogicalProcessor.Count == 0) + { + _logger?.LogWarning("CPU Set mapping not available. Cannot apply CPU Sets to process {ProcessId}", _pid); + return false; + } + + // Open handle for setting process information if not already open + if (_setLimitedInfoHandle == null) + { + _setLimitedInfoHandle = CpuSetNativeMethods.OpenProcess( + ProcessAccessFlags.PROCESS_SET_LIMITED_INFORMATION, + false, + _pid); + + if (_setLimitedInfoHandle == null || _setLimitedInfoHandle.IsInvalid) + { + int openError = Marshal.GetLastWin32Error(); + string extraHelpString = (openError == 5) ? " Try restarting as Administrator" : ""; + _logger?.LogWarning("Could not open process '{ExecutableName}' (PID: {ProcessId}) for setting affinity: {Error}{Help}", + _executableName, _pid, new Win32Exception(openError).Message, extraHelpString); + return false; + } + } + else if (_setLimitedInfoHandle.IsInvalid) + { + // The handle was already made previously and failed, don't bother trying again + return false; + } + + bool success; + int error; + + if (clearMask) + { + // Clear the CPU Set (allow process to run on all cores) + success = CpuSetNativeMethods.SetProcessDefaultCpuSets(_setLimitedInfoHandle, null, 0); + if (success) + { + _logger?.LogInformation("Cleared CPU Set of '{ExecutableName}' (PID: {ProcessId})", _executableName, _pid); + return true; + } + + error = Marshal.GetLastWin32Error(); + _logger?.LogWarning("Could not clear CPU Set of '{ExecutableName}' (PID: {ProcessId}): {Error}", + _executableName, _pid, new Win32Exception(error).Message); + return false; + } + + // Convert affinity mask to CPU Set IDs + List cpuSetIds = new List(); + int logicalCoreCount = Environment.ProcessorCount; + + for (int i = 0; i < logicalCoreCount; i++) + { + long coreBit = 1L << i; + if ((affinityMask & coreBit) != 0) + { + if (_cpuSetIdPerLogicalProcessor.TryGetValue(i, out uint cpuSetId)) + { + cpuSetIds.Add(cpuSetId); + } + else + { + _logger?.LogWarning("Unable to include core {CoreIndex} in CPU Set for '{ExecutableName}'. It does not have a CPU Set ID", + i, _executableName); + } + } + } + + if (cpuSetIds.Count == 0) + { + _logger?.LogWarning("No valid CPU Set IDs found for affinity mask 0x{AffinityMask:X} on process '{ExecutableName}'", + affinityMask, _executableName); + return false; + } + + uint[] cpuSetIdsArray = cpuSetIds.ToArray(); + success = CpuSetNativeMethods.SetProcessDefaultCpuSets(_setLimitedInfoHandle, cpuSetIdsArray, (uint)cpuSetIdsArray.Length); + + if (success) + { + _logger?.LogInformation("Applied CPU Set (affinity mask 0x{AffinityMask:X}) to '{ExecutableName}' (PID: {ProcessId})", + affinityMask, _executableName, _pid); + return true; + } + + error = Marshal.GetLastWin32Error(); + string errorMessage = $"Could not apply CPU Set to '{_executableName}' (PID: {_pid}): {new Win32Exception(error).Message}"; + if (error == 5) + { + errorMessage += " (Likely due to anti-cheat or insufficient privileges)"; + } + _logger?.LogWarning(errorMessage); + return false; + } + + /// + /// Get the CPU Set Id of each logical processor + /// + private static Dictionary GetCpuSetIdPerLogicalProcessor() + { + uint bufferLength = 0; + + // First call to get buffer size + if (!CpuSetNativeMethods.GetSystemCpuSetInformation(IntPtr.Zero, 0, ref bufferLength, new SafeProcessHandle(), 0)) + { + int error = Marshal.GetLastWin32Error(); + if (error != 0x7A) // ERROR_INSUFFICIENT_BUFFER + { + throw new Win32Exception(error, "Failed to query CPU Set information buffer size"); + } + } + + Dictionary cpuSets = new Dictionary(); + IntPtr buffer = Marshal.AllocHGlobal((int)bufferLength); + + try + { + // Second call to get actual data + if (!CpuSetNativeMethods.GetSystemCpuSetInformation(buffer, bufferLength, ref bufferLength, new SafeProcessHandle(), 0)) + { + throw new Win32Exception(Marshal.GetLastWin32Error(), "Failed to get CPU Set information"); + } + + IntPtr current = buffer; + IntPtr bufferEnd = buffer + (int)bufferLength; + + while (current.ToInt64() < bufferEnd.ToInt64()) + { + SYSTEM_CPU_SET_INFORMATION item = Marshal.PtrToStructure(current); + + if (item.Type != CPU_SET_INFORMATION_TYPE.CpuSetInformation) + { + throw new InvalidCastException("Invalid CPU Set information type encountered"); + } + + cpuSets[item.LogicalProcessorIndex] = item.Id; + + current = IntPtr.Add(current, (int)item.Size); + } + + return cpuSets; + } + finally + { + Marshal.FreeHGlobal(buffer); + } + } + + public void Dispose() + { + if (_disposed) return; + + _queryLimitedInfoHandle?.Dispose(); + _setLimitedInfoHandle?.Dispose(); + _cpuTimeMovingAverageBuffer.Clear(); + + _disposed = true; + GC.SuppressFinalize(this); + } + + private class CpuTimeTimestamp + { + public DateTime Timestamp { get; init; } + public TimeSpan TotalCpuTime { get; init; } + } + } +} diff --git a/Services/CoreMaskService.cs b/Services/CoreMaskService.cs new file mode 100644 index 0000000..6469f0b --- /dev/null +++ b/Services/CoreMaskService.cs @@ -0,0 +1,682 @@ +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.IO; +using System.Linq; +using System.Text.Json; +using System.Threading.Tasks; +using Microsoft.Extensions.Logging; +using ThreadPilot.Models; + +namespace ThreadPilot.Services +{ + /// + /// Service for managing CPU core affinity masks + /// Based on CPUSetSetter's AppConfig and LogicalProcessorMask system + /// + public class CoreMaskService : ICoreMaskService + { + private readonly ILogger _logger; + private readonly ICpuTopologyService _cpuTopologyService; + private readonly IServiceProvider _serviceProvider; + private readonly string _masksFilePath; + private bool _initialized = false; + + // Tracks which masks are actively applied to processes + private readonly Dictionary _activeProcessMasks = new(); // ProcessId -> MaskId + + public ObservableCollection AvailableMasks { get; private set; } = new(); + public CoreMask? DefaultMask => AvailableMasks.FirstOrDefault(m => m.IsDefault); + + /// + /// The "All Cores" baseline mask - cannot be deleted + /// + private const string ALL_CORES_MASK_NAME = "All Cores"; + + public CoreMaskService( + ILogger logger, + ICpuTopologyService cpuTopologyService, + IServiceProvider serviceProvider) + { + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); + _cpuTopologyService = cpuTopologyService ?? throw new ArgumentNullException(nameof(cpuTopologyService)); + _serviceProvider = serviceProvider ?? throw new ArgumentNullException(nameof(serviceProvider)); + + var appDataPath = Path.Combine( + Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), + "ThreadPilot"); + + Directory.CreateDirectory(appDataPath); + _masksFilePath = Path.Combine(appDataPath, "core_masks.json"); + } + + public async Task InitializeAsync() + { + if (_initialized) + return; + + _logger.LogInformation("Initializing CoreMaskService..."); + + await LoadMasksAsync(); + + // If no masks exist, create defaults + if (AvailableMasks.Count == 0) + { + _logger.LogInformation("No masks found, creating defaults..."); + await CreateDefaultMasksAsync(); + } + + _initialized = true; + _logger.LogInformation("CoreMaskService initialized with {Count} masks", AvailableMasks.Count); + } + + public async Task CreateMaskAsync(string name, string description, IEnumerable boolMask) + { + var mask = new CoreMask + { + Name = name, + Description = description, + CreatedAt = DateTime.UtcNow, + UpdatedAt = DateTime.UtcNow + }; + + foreach (var bit in boolMask) + mask.BoolMask.Add(bit); + + AvailableMasks.Add(mask); + await SaveMasksAsync(); + + _logger.LogInformation("Created new mask '{Name}' with {Count} cores selected", + name, mask.SelectedCoreCount); + + return mask; + } + + public async Task UpdateMaskAsync(CoreMask mask) + { + if (mask == null) + throw new ArgumentNullException(nameof(mask)); + + var existing = GetMaskById(mask.Id); + if (existing == null) + { + _logger.LogWarning("Cannot update mask {Id}: not found", mask.Id); + return; + } + + mask.UpdatedAt = DateTime.UtcNow; + await SaveMasksAsync(); + + _logger.LogInformation("Updated mask '{Name}'", mask.Name); + } + + public async Task DeleteMaskAsync(string maskId) + { + var mask = GetMaskById(maskId); + if (mask == null) + { + _logger.LogWarning("Cannot delete mask {Id}: not found", maskId); + return; + } + + // Cannot delete the "All Cores" baseline mask + if (mask.Name == ALL_CORES_MASK_NAME) + { + _logger.LogWarning("Cannot delete 'All Cores' baseline mask"); + throw new InvalidOperationException("Cannot delete the 'All Cores' baseline mask - it is required as the default fallback"); + } + + // Check if mask is actively applied to running processes + if (await IsMaskActivelyAppliedAsync(maskId)) + { + _logger.LogWarning("Cannot delete mask '{Name}': it is actively applied to running processes", mask.Name); + throw new InvalidOperationException($"Cannot delete mask '{mask.Name}' - it is currently applied to running processes. Please change the mask on those processes first."); + } + + AvailableMasks.Remove(mask); + await SaveMasksAsync(); + + _logger.LogInformation("Deleted mask '{Name}'", mask.Name); + } + + public CoreMask? GetMaskById(string maskId) + { + return AvailableMasks.FirstOrDefault(m => m.Id == maskId); + } + + public CoreMask? GetMaskByName(string name) + { + return AvailableMasks.FirstOrDefault(m => + m.Name.Equals(name, StringComparison.OrdinalIgnoreCase)); + } + + public async Task SaveMasksAsync() + { + try + { + var data = AvailableMasks.Select(m => new + { + id = m.Id, + name = m.Name, + description = m.Description, + boolMask = m.BoolMask.ToList(), + isDefault = m.IsDefault, + isEnabled = m.IsEnabled, + createdAt = m.CreatedAt, + updatedAt = m.UpdatedAt + }).ToList(); + + var json = JsonSerializer.Serialize(data, new JsonSerializerOptions + { + WriteIndented = true + }); + + await File.WriteAllTextAsync(_masksFilePath, json); + _logger.LogDebug("Saved {Count} masks to {Path}", AvailableMasks.Count, _masksFilePath); + } + catch (Exception ex) + { + _logger.LogError(ex, "Failed to save masks to {Path}", _masksFilePath); + throw; + } + } + + public async Task LoadMasksAsync() + { + try + { + if (!File.Exists(_masksFilePath)) + { + _logger.LogInformation("Masks file not found at {Path}, will create defaults", _masksFilePath); + return; + } + + var json = await File.ReadAllTextAsync(_masksFilePath); + var data = JsonSerializer.Deserialize>(json); + + if (data == null) + { + _logger.LogWarning("Failed to deserialize masks from {Path}", _masksFilePath); + return; + } + + AvailableMasks.Clear(); + + foreach (var item in data) + { + try + { + var mask = new CoreMask + { + Id = item.GetProperty("id").GetString() ?? Guid.NewGuid().ToString(), + Name = item.GetProperty("name").GetString() ?? "Unnamed", + Description = item.GetProperty("description").GetString() ?? "", + IsDefault = item.GetProperty("isDefault").GetBoolean(), + IsEnabled = item.GetProperty("isEnabled").GetBoolean(), + CreatedAt = item.GetProperty("createdAt").GetDateTime(), + UpdatedAt = item.GetProperty("updatedAt").GetDateTime() + }; + + var boolMask = item.GetProperty("boolMask"); + foreach (var bit in boolMask.EnumerateArray()) + { + mask.BoolMask.Add(bit.GetBoolean()); + } + + AvailableMasks.Add(mask); + } + catch (Exception ex) + { + _logger.LogWarning(ex, "Failed to load individual mask, skipping"); + } + } + + _logger.LogInformation("Loaded {Count} masks from {Path}", AvailableMasks.Count, _masksFilePath); + } + catch (Exception ex) + { + _logger.LogError(ex, "Failed to load masks from {Path}", _masksFilePath); + } + } + + public async Task IsMaskReferencedByProfilesAsync(string maskId) + { + try + { + var profileNames = await GetProfilesReferencingMaskAsync(maskId); + return profileNames.Any(); + } + catch (Exception ex) + { + _logger.LogError(ex, "Failed to check if mask {MaskId} is referenced by profiles", maskId); + return false; + } + } + + public async Task IsMaskActivelyAppliedAsync(string maskId) + { + try + { + // Check our tracking dictionary for active process masks + var isActive = _activeProcessMasks.ContainsValue(maskId); + + if (isActive) + { + // Verify processes are still running + var deadProcesses = new List(); + foreach (var kvp in _activeProcessMasks.Where(x => x.Value == maskId)) + { + try + { + Process.GetProcessById(kvp.Key); + } + catch (ArgumentException) + { + // Process no longer exists + deadProcesses.Add(kvp.Key); + } + } + + // Clean up dead processes + foreach (var pid in deadProcesses) + { + _activeProcessMasks.Remove(pid); + } + + // Re-check after cleanup + isActive = _activeProcessMasks.ContainsValue(maskId); + } + + await Task.CompletedTask; + return isActive; + } + catch (Exception ex) + { + _logger.LogError(ex, "Failed to check if mask {MaskId} is actively applied", maskId); + return false; + } + } + + public async Task> GetProfilesReferencingMaskAsync(string maskId) + { + var referencingProfiles = new List(); + + try + { + // Get the association service to check profiles + var associationService = _serviceProvider.GetService(typeof(IProcessPowerPlanAssociationService)) as IProcessPowerPlanAssociationService; + if (associationService != null) + { + var associations = await associationService.GetAssociationsAsync(); + foreach (var association in associations) + { + if (association.CoreMaskId == maskId) + { + var profileName = !string.IsNullOrEmpty(association.Description) + ? association.Description + : association.ExecutableName; + referencingProfiles.Add(profileName); + } + } + } + } + catch (Exception ex) + { + _logger.LogError(ex, "Failed to get profiles referencing mask {MaskId}", maskId); + } + + return referencingProfiles; + } + + public async Task UpdateProfilesToDefaultMaskAsync(string maskId) + { + try + { + var allCoresMask = GetAllCoresMask(); + if (allCoresMask == null) + { + _logger.LogError("Cannot update profiles: 'All Cores' mask not found"); + return; + } + + var associationService = _serviceProvider.GetService(typeof(IProcessPowerPlanAssociationService)) as IProcessPowerPlanAssociationService; + if (associationService != null) + { + var associations = await associationService.GetAssociationsAsync(); + foreach (var association in associations) + { + if (association.CoreMaskId == maskId) + { + association.CoreMaskId = allCoresMask.Id; + association.CoreMaskName = allCoresMask.Name; + await associationService.UpdateAssociationAsync(association); + _logger.LogInformation("Updated association '{Name}' to use 'All Cores' mask", association.ExecutableName); + } + } + } + } + catch (Exception ex) + { + _logger.LogError(ex, "Failed to update profiles to default mask"); + } + } + + public CoreMask? GetAllCoresMask() + { + return AvailableMasks.FirstOrDefault(m => m.Name == ALL_CORES_MASK_NAME); + } + + /// + /// Registers that a mask is being applied to a process + /// + public void RegisterMaskApplication(int processId, string maskId) + { + _activeProcessMasks[processId] = maskId; + _logger.LogDebug("Registered mask {MaskId} for process {ProcessId}", maskId, processId); + } + + /// + /// Unregisters a mask application when a process exits or mask is removed + /// + public void UnregisterMaskApplication(int processId) + { + if (_activeProcessMasks.Remove(processId)) + { + _logger.LogDebug("Unregistered mask for process {ProcessId}", processId); + } + } + + /// + /// Gets all processes that have a specific mask applied + /// + public IEnumerable GetProcessesWithMask(string maskId) + { + return _activeProcessMasks.Where(x => x.Value == maskId).Select(x => x.Key); + } + + public async Task CreateDefaultMasksAsync() + { + int coreCount = Environment.ProcessorCount; + var topology = _cpuTopologyService.CurrentTopology; + bool topologyConfident = topology?.TopologyDetectionSuccessful == true; + bool hasHyperThreading = topology?.HasHyperThreading == true; + bool canCreateNoSmtVariants = topologyConfident && hasHyperThreading; + + // Collect all default masks with their "no SMT" variants + var defaultMasks = new List<(string name, List boolMask, string description)>(); + + // Determine CPU manufacturer for naming convention + bool isIntel = topology?.CpuBrand?.Contains("Intel", StringComparison.OrdinalIgnoreCase) == true; + bool isAmd = topology?.CpuBrand?.Contains("AMD", StringComparison.OrdinalIgnoreCase) == true; + string noSmtSuffix = isIntel ? " no HT" : " no SMT"; + + // 1. Always add "All Cores" baseline mask (IsDefault = true, cannot be deleted) + var allCoresMask = new CoreMask + { + Name = ALL_CORES_MASK_NAME, + Description = "Use all available CPU cores - baseline mask", + IsDefault = true + }; + for (int i = 0; i < coreCount; i++) + allCoresMask.BoolMask.Add(true); + AvailableMasks.Add(allCoresMask); + + // 2. Intel Hybrid Architecture: P-Cores, E-Cores, LPE-Cores (Arrow Lake+) + if (topology != null && topology.HasIntelHybrid) + { + // Detect efficiency class distribution for LPE support + var efficiencyClasses = topology.LogicalCores + .Select(c => GetEfficiencyClass(c)) + .Distinct() + .OrderByDescending(x => x) + .ToList(); + + bool hasLpeCores = efficiencyClasses.Count >= 3; // P, E, LPE + int pClass = hasLpeCores ? 2 : 1; + int eClass = hasLpeCores ? 1 : 0; + int lpeClass = 0; + + // P-Cores mask + var pCoresBoolMask = new List(); + for (int i = 0; i < coreCount; i++) + { + var core = topology.LogicalCores.FirstOrDefault(c => c.LogicalCoreId == i); + pCoresBoolMask.Add(GetEfficiencyClass(core) == pClass); + } + if (pCoresBoolMask.Any(b => b)) + defaultMasks.Add(("P-Cores", pCoresBoolMask, "Intel Performance cores (highest performance)")); + + // E-Cores mask + var eCoresBoolMask = new List(); + for (int i = 0; i < coreCount; i++) + { + var core = topology.LogicalCores.FirstOrDefault(c => c.LogicalCoreId == i); + eCoresBoolMask.Add(GetEfficiencyClass(core) == eClass); + } + if (eCoresBoolMask.Any(b => b)) + defaultMasks.Add(("E-Cores", eCoresBoolMask, "Intel Efficiency cores (power efficient)")); + + // LPE-Cores mask (Arrow Lake and beyond) + if (hasLpeCores) + { + var lpeCoresBoolMask = new List(); + for (int i = 0; i < coreCount; i++) + { + var core = topology.LogicalCores.FirstOrDefault(c => c.LogicalCoreId == i); + lpeCoresBoolMask.Add(GetEfficiencyClass(core) == lpeClass); + } + if (lpeCoresBoolMask.Any(b => b)) + defaultMasks.Add(("LPE-Cores", lpeCoresBoolMask, "Intel Low-Power Efficiency cores (ultra power efficient)")); + } + + _logger.LogInformation("Created Intel Hybrid masks (P/E{0})", hasLpeCores ? "/LPE" : ""); + } + + // 3. AMD CCD Masks with Cache/Freq differentiation (like CPU Set Setter) + if (topology != null && topology.HasAmdCcd) + { + await CreateAmdCcdMasksAsync(topology, defaultMasks, coreCount); + } + + // 4. Generate "no SMT/HT" variants for each mask + var resultMasks = new List(); + foreach (var (name, boolMask, description) in defaultMasks) + { + // Original mask + resultMasks.Add(CreateCoreMaskFromBoolList(name, boolMask, description)); + + // No SMT variant + if (canCreateNoSmtVariants) + { + var noSmtMask = StripSMT(boolMask, topology, out bool wasStripped); + if (wasStripped) + { + resultMasks.Add(CreateCoreMaskFromBoolList( + name + noSmtSuffix, + noSmtMask, + description + " (no HyperThreading/SMT)")); + } + } + } + + // 5. "All no HT/SMT" as the last mask + if (canCreateNoSmtVariants) + { + var allCoresBoolMask = Enumerable.Repeat(true, coreCount).ToList(); + var allNoSmtMask = StripSMT(allCoresBoolMask, topology, out bool hasStripped); + if (hasStripped) + { + resultMasks.Add(CreateCoreMaskFromBoolList( + "All" + noSmtSuffix, + allNoSmtMask, + "All physical cores without HyperThreading/SMT")); + } + } + + // Add all generated masks to AvailableMasks + foreach (var mask in resultMasks) + { + AvailableMasks.Add(mask); + } + + await SaveMasksAsync(); + _logger.LogInformation("Created {Count} default masks with topology-aware presets (including no SMT variants)", + AvailableMasks.Count); + } + + /// + /// Creates AMD CCD masks with Cache/Freq differentiation (X3D support) + /// Based on CPU Set Setter's GetDefaultLogicalProcessorMasks + /// + private async Task CreateAmdCcdMasksAsync(CpuTopologyModel topology, + List<(string name, List boolMask, string description)> defaultMasks, + int coreCount) + { + try + { + var ccdIds = topology.AvailableCcds.ToList(); + + if (ccdIds.Count < 2) + { + // Single CCD - just create one CCD mask + if (ccdIds.Count == 1) + { + var ccdBoolMask = new List(); + for (int i = 0; i < coreCount; i++) + { + var core = topology.LogicalCores.FirstOrDefault(c => c.LogicalCoreId == i); + ccdBoolMask.Add(core?.CcdId == ccdIds[0]); + } + defaultMasks.Add(($"CCD{ccdIds[0]}", ccdBoolMask, $"AMD Core Complex Die {ccdIds[0]}")); + } + return; + } + + // Multiple CCDs - try to detect X3D (Cache vs Freq CCDs) + // X3D chips have one CCD with significantly more L3 cache + // For simplicity, we'll create numbered CCD masks + // TODO: Implement L3 cache size detection for X3D differentiation + + foreach (var ccdId in ccdIds) + { + var ccdBoolMask = new List(); + for (int i = 0; i < coreCount; i++) + { + var core = topology.LogicalCores.FirstOrDefault(c => c.LogicalCoreId == i); + ccdBoolMask.Add(core?.CcdId == ccdId); + } + + if (ccdBoolMask.Any(b => b)) + { + defaultMasks.Add(($"CCD{ccdId}", ccdBoolMask, $"AMD Core Complex Die {ccdId}")); + } + } + + _logger.LogInformation("Created {Count} AMD CCD masks for CCDs: {CCDs}", + ccdIds.Count, string.Join(", ", ccdIds)); + } + catch (Exception ex) + { + _logger.LogError(ex, "Failed to create AMD CCD masks"); + } + } + + /// + /// Strips SMT/HT threads from a bool mask, keeping only physical cores (T0) + /// Based on CPU Set Setter's StripSMT method + /// + private List StripSMT(List boolMask, CpuTopologyModel? topology, out bool hasStripped) + { + var result = new List(boolMask.Count); + hasStripped = false; + + var coreById = topology?.LogicalCores.ToDictionary(c => c.LogicalCoreId); + var primaryThreadIds = new HashSet(); + + if (coreById != null) + { + foreach (var group in coreById.Values.GroupBy(c => c.PhysicalCoreId)) + { + var primary = group.OrderBy(c => c.LogicalCoreId).First(); + primaryThreadIds.Add(primary.LogicalCoreId); + } + } + + bool topologyBased = topology?.TopologyDetectionSuccessful == true && primaryThreadIds.Count > 0; + + for (int i = 0; i < boolMask.Count; i++) + { + bool isSMTThread = false; + bool keepBit = boolMask[i]; + + if (keepBit) + { + if (topologyBased && coreById != null && coreById.TryGetValue(i, out var core)) + { + isSMTThread = core.IsHyperThreaded && !primaryThreadIds.Contains(i); + } + else + { + // Fallback heuristic based on naming + var fallbackCore = coreById != null && coreById.TryGetValue(i, out var c) ? c : null; + var name = fallbackCore?.LogicalProcessorName; + if (!string.IsNullOrEmpty(name) && name.Length >= 2) + { + var lastTwo = name.Substring(name.Length - 2); + if (lastTwo.StartsWith("T") || lastTwo.StartsWith("_T")) + { + isSMTThread = !name.EndsWith("T0") && !name.EndsWith("_T0"); + } + } + else if (fallbackCore?.IsHyperThreaded == true && fallbackCore.HyperThreadSibling.HasValue) + { + isSMTThread = fallbackCore.LogicalCoreId > fallbackCore.HyperThreadSibling.Value; + } + } + } + + if (keepBit && isSMTThread) + hasStripped = true; + + result.Add(keepBit && !isSMTThread); + } + + return result; + } + + /// + /// Gets the efficiency class of a core (for Intel Hybrid detection) + /// + private int GetEfficiencyClass(CpuCoreModel? core) + { + if (core == null) return 0; + + return core.CoreType switch + { + CpuCoreType.PerformanceCore => 2, // Highest efficiency class + CpuCoreType.EfficiencyCore => 1, // Middle efficiency class + _ => 0 // Lowest (or unknown/LPE) + }; + } + + /// + /// Creates a CoreMask from a bool list + /// + private CoreMask CreateCoreMaskFromBoolList(string name, List boolMask, string description) + { + var mask = new CoreMask + { + Name = name, + Description = description, + IsDefault = false, + IsEnabled = true + }; + + foreach (var bit in boolMask) + mask.BoolMask.Add(bit); + + return mask; + } + } +} diff --git a/Services/CpuTopologyService.cs b/Services/CpuTopologyService.cs index 95ac91c..311b933 100644 --- a/Services/CpuTopologyService.cs +++ b/Services/CpuTopologyService.cs @@ -39,7 +39,7 @@ namespace ThreadPilot.Services public async Task DetectTopologyAsync() { // PERFORMANCE IMPROVEMENT: Check cache first to avoid expensive WMI calls - if (_cache.TryGetValue(TOPOLOGY_CACHE_KEY, out CpuTopologyModel? cachedTopology)) + if (_cache.TryGetValue(TOPOLOGY_CACHE_KEY, out CpuTopologyModel? cachedTopology) && cachedTopology != null) { _logger.LogInformation("CPU topology retrieved from cache"); _currentTopology = cachedTopology; @@ -173,8 +173,9 @@ namespace ThreadPilot.Services for (int logicalId = 0; logicalId < logicalCoreCount; logicalId++) { var physicalId = logicalId / threadsPerCore; - var isHyperThreaded = hasHyperThreading && (logicalId % threadsPerCore != 0); - var htSibling = hasHyperThreading ? (logicalId % threadsPerCore == 0 ? logicalId + 1 : logicalId - 1) : (int?)null; + var threadIndexOnCore = logicalId % threadsPerCore; + var isHyperThreaded = hasHyperThreading && (threadIndexOnCore != 0); + var htSibling = hasHyperThreading ? (threadIndexOnCore == 0 ? logicalId + 1 : logicalId - 1) : (int?)null; var core = new CpuCoreModel { @@ -182,6 +183,7 @@ namespace ThreadPilot.Services PhysicalCoreId = physicalId, SocketId = 0, // Will be refined later Label = $"Core {logicalId}", + LogicalProcessorName = $"Core{physicalId}_T{threadIndexOnCore}", // T0 = physical, T1+ = SMT IsEnabled = true, IsHyperThreaded = isHyperThreaded, HyperThreadSibling = htSibling @@ -212,9 +214,10 @@ namespace ThreadPilot.Services SocketId = 0, CoreType = CpuCoreType.Standard, Label = $"Core {i}", + LogicalProcessorName = $"Core{i}_T0", // All physical cores in basic fallback (no HT detected) IsEnabled = true }; - + topology.LogicalCores.Add(core); } } @@ -377,6 +380,14 @@ namespace ThreadPilot.Services return topology; } + private long CalculateFullAffinityMask(int logicalCoreCount) + { + // For 64 logical cores the mask needs all bits set; shifting by 64 would wrap to zero + return logicalCoreCount >= 63 + ? -1L + : (1L << logicalCoreCount) - 1; + } + public IEnumerable GetAffinityPresets() { if (_currentTopology == null) @@ -389,7 +400,7 @@ namespace ThreadPilot.Services { Name = "All Cores", Description = $"All {_currentTopology.TotalLogicalCores} logical cores", - AffinityMask = (1L << _currentTopology.TotalLogicalCores) - 1, + AffinityMask = CalculateFullAffinityMask(_currentTopology.TotalLogicalCores), IsAvailable = true }); @@ -398,7 +409,7 @@ namespace ThreadPilot.Services { presets.Add(new CpuAffinityPreset { - Name = "Physical Cores Only", + Name = "No HT", Description = $"All {_currentTopology.TotalPhysicalCores} physical cores (no HyperThreading)", AffinityMask = _currentTopology.GetPhysicalCoresAffinityMask(), IsAvailable = true @@ -451,8 +462,8 @@ namespace ThreadPilot.Services public bool IsAffinityMaskValid(long affinityMask) { if (_currentTopology == null) return false; - - var maxMask = (1L << _currentTopology.TotalLogicalCores) - 1; + + var maxMask = CalculateFullAffinityMask(_currentTopology.TotalLogicalCores); return affinityMask > 0 && affinityMask <= maxMask; } diff --git a/Services/ElevationService.cs b/Services/ElevationService.cs index a8f718c..efa0d32 100644 --- a/Services/ElevationService.cs +++ b/Services/ElevationService.cs @@ -67,7 +67,7 @@ namespace ThreadPilot.Services return await RestartWithElevation(); } - public async Task RestartWithElevation(string[] arguments = null) + public async Task RestartWithElevation(string[]? arguments = null) { try { diff --git a/Services/EnhancedLoggingService.cs b/Services/EnhancedLoggingService.cs index 60b1372..32385fb 100644 --- a/Services/EnhancedLoggingService.cs +++ b/Services/EnhancedLoggingService.cs @@ -110,19 +110,6 @@ namespace ThreadPilot.Services await LogStructuredEventAsync("ProcessMonitoring", message, LogLevel.Information, properties); } - public async Task LogGameBoostEventAsync(string eventType, string gameName, string details) - { - var properties = new Dictionary - { - ["EventType"] = eventType, - ["GameName"] = gameName, - ["Details"] = details - }; - - var message = $"Game Boost {eventType}: {gameName} - {details}"; - await LogStructuredEventAsync("GameBoost", message, LogLevel.Information, properties); - } - public async Task LogUserActionAsync(string action, string details, string? context = null) { var properties = new Dictionary @@ -532,7 +519,7 @@ namespace ThreadPilot.Services _loggingService._correlationId.Value = null; // Use the public logging method instead of accessing private _logger - _loggingService.LogSystemEventAsync("OperationCompleted", + _ = _loggingService.LogSystemEventAsync("OperationCompleted", $"Operation {_operationName} completed with correlation {_correlationId} in {duration.TotalMilliseconds}ms"); _disposed = true; diff --git a/Services/GameModeService.cs b/Services/GameModeService.cs new file mode 100644 index 0000000..dc3ec29 --- /dev/null +++ b/Services/GameModeService.cs @@ -0,0 +1,119 @@ +using System; +using System.Threading.Tasks; +using Microsoft.Extensions.Logging; +using Microsoft.Win32; + +namespace ThreadPilot.Services +{ + /// + /// Service for managing Windows Game Mode settings + /// Windows Game Mode can interfere with CPU Sets and affinity, particularly on AMD systems + /// Reference: CPU Set Setter warning system + /// + public class GameModeService : IGameModeService + { + private readonly ILogger _logger; + private const string GameBarKeyPath = @"Software\Microsoft\GameBar"; + private const string GameModeValueName = "AutoGameModeEnabled"; + + public GameModeService(ILogger logger) + { + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); + } + + /// + public async Task IsGameModeEnabledAsync() + { + await Task.CompletedTask; // Make async for consistency + + try + { + using var key = Registry.CurrentUser.OpenSubKey(GameBarKeyPath, writable: false); + if (key == null) + { + _logger.LogDebug("GameBar registry key not found, assuming Game Mode is disabled"); + return false; + } + + var value = key.GetValue(GameModeValueName); + if (value is int intValue) + { + bool isEnabled = intValue != 0; + _logger.LogDebug("Game Mode status: {Status}", isEnabled ? "Enabled" : "Disabled"); + return isEnabled; + } + + _logger.LogDebug("GameMode value not found, assuming disabled"); + return false; + } + catch (Exception ex) + { + _logger.LogWarning(ex, "Failed to read Game Mode registry key, assuming disabled"); + return false; + } + } + + /// + public async Task SetGameModeAsync(bool enabled) + { + await Task.CompletedTask; // Make async for consistency + + try + { + using var key = Registry.CurrentUser.OpenSubKey(GameBarKeyPath, writable: true); + if (key == null) + { + _logger.LogWarning("GameBar registry key not found, cannot modify Game Mode"); + return false; + } + + key.SetValue(GameModeValueName, enabled ? 1 : 0, RegistryValueKind.DWord); + _logger.LogInformation("Set Windows Game Mode to {State}", enabled ? "enabled" : "disabled"); + return true; + } + catch (UnauthorizedAccessException ex) + { + _logger.LogWarning(ex, "Insufficient permissions to modify Game Mode registry key"); + return false; + } + catch (Exception ex) + { + _logger.LogError(ex, "Failed to set Game Mode to {State}", enabled ? "enabled" : "disabled"); + return false; + } + } + + /// + public async Task DisableGameModeForAffinityAsync() + { + try + { + bool isEnabled = await IsGameModeEnabledAsync(); + if (!isEnabled) + { + _logger.LogDebug("Game Mode already disabled, no action needed"); + return false; + } + + _logger.LogInformation("Game Mode is enabled, disabling for better CPU affinity control"); + bool success = await SetGameModeAsync(false); + + if (success) + { + _logger.LogInformation("Successfully disabled Windows Game Mode for CPU affinity optimization"); + } + else + { + _logger.LogWarning("Failed to disable Game Mode, CPU affinity may be affected"); + } + + return success; + } + catch (Exception ex) + { + _logger.LogError(ex, "Error disabling Game Mode for affinity"); + return false; + } + } + } +} diff --git a/Services/ICoreMaskService.cs b/Services/ICoreMaskService.cs new file mode 100644 index 0000000..353e8de --- /dev/null +++ b/Services/ICoreMaskService.cs @@ -0,0 +1,93 @@ +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Threading.Tasks; +using ThreadPilot.Models; + +namespace ThreadPilot.Services +{ + /// + /// Service for managing CPU core affinity masks + /// + public interface ICoreMaskService + { + /// + /// Gets all available core masks + /// + ObservableCollection AvailableMasks { get; } + + /// + /// Gets the default mask (all cores) + /// + CoreMask? DefaultMask { get; } + + /// + /// Initializes the service and loads masks from storage + /// + Task InitializeAsync(); + + /// + /// Creates a new core mask + /// + Task CreateMaskAsync(string name, string description, IEnumerable boolMask); + + /// + /// Updates an existing mask + /// + Task UpdateMaskAsync(CoreMask mask); + + /// + /// Deletes a mask by ID + /// + Task DeleteMaskAsync(string maskId); + + /// + /// Gets a mask by ID + /// + CoreMask? GetMaskById(string maskId); + + /// + /// Gets a mask by name + /// + CoreMask? GetMaskByName(string name); + + /// + /// Saves all masks to persistent storage + /// + Task SaveMasksAsync(); + + /// + /// Loads masks from persistent storage + /// + Task LoadMasksAsync(); + + /// + /// Checks if a mask is referenced by any profile or rule (not necessarily active) + /// + Task IsMaskReferencedByProfilesAsync(string maskId); + + /// + /// Checks if a mask is actively applied to any running process + /// + Task IsMaskActivelyAppliedAsync(string maskId); + + /// + /// Gets the names of profiles/rules that reference a specific mask + /// + Task> GetProfilesReferencingMaskAsync(string maskId); + + /// + /// Updates all profiles referencing a mask to use the default "All Cores" mask + /// + Task UpdateProfilesToDefaultMaskAsync(string maskId); + + /// + /// Creates default masks for the system based on CPU topology + /// + Task CreateDefaultMasksAsync(); + + /// + /// Gets the "All Cores" baseline mask (cannot be deleted) + /// + CoreMask? GetAllCoresMask(); + } +} diff --git a/Services/IElevationService.cs b/Services/IElevationService.cs index e706500..cb3bb77 100644 --- a/Services/IElevationService.cs +++ b/Services/IElevationService.cs @@ -24,7 +24,7 @@ namespace ThreadPilot.Services /// /// Command line arguments to pass to the elevated process /// True if restart was initiated successfully, false otherwise - Task RestartWithElevation(string[] arguments = null); + Task RestartWithElevation(string[]? arguments = null); /// /// Validates that the current process has the necessary privileges for the specified operation diff --git a/Services/IEnhancedLoggingService.cs b/Services/IEnhancedLoggingService.cs index 11f0c02..cab13b3 100644 --- a/Services/IEnhancedLoggingService.cs +++ b/Services/IEnhancedLoggingService.cs @@ -45,11 +45,6 @@ namespace ThreadPilot.Services /// Task LogProcessMonitoringEventAsync(string eventType, string processName, int processId, string details); - /// - /// Log a game boost event - /// - Task LogGameBoostEventAsync(string eventType, string gameName, string details); - /// /// Log a user action /// diff --git a/Services/IGameModeService.cs b/Services/IGameModeService.cs new file mode 100644 index 0000000..0a16071 --- /dev/null +++ b/Services/IGameModeService.cs @@ -0,0 +1,31 @@ +using System.Threading.Tasks; + +namespace ThreadPilot.Services +{ + /// + /// Service for managing Windows Game Mode settings + /// Game Mode can interfere with CPU affinity settings, particularly on AMD systems + /// + public interface IGameModeService + { + /// + /// Checks if Windows Game Mode is currently enabled + /// + /// True if Game Mode is enabled, false otherwise + Task IsGameModeEnabledAsync(); + + /// + /// Sets Windows Game Mode to enabled or disabled + /// + /// True to enable Game Mode, false to disable + /// True if the operation succeeded, false otherwise + Task SetGameModeAsync(bool enabled); + + /// + /// Disables Game Mode for better CPU affinity control + /// This is a non-intrusive operation that only disables if currently enabled + /// + /// True if Game Mode was disabled, false if it was already disabled or operation failed + Task DisableGameModeForAffinityAsync(); + } +} diff --git a/Services/IKeyboardShortcutService.cs b/Services/IKeyboardShortcutService.cs index fac5cf8..a1425b1 100644 --- a/Services/IKeyboardShortcutService.cs +++ b/Services/IKeyboardShortcutService.cs @@ -121,7 +121,6 @@ namespace ThreadPilot.Services public const string PowerPlanBalanced = "PowerPlanBalanced"; public const string PowerPlanHighPerformance = "PowerPlanHighPerformance"; public const string PowerPlanPowerSaver = "PowerPlanPowerSaver"; - public const string GameBoostToggle = "GameBoostToggle"; public const string RefreshProcessList = "RefreshProcessList"; public const string OpenSettings = "OpenSettings"; public const string OpenTweaks = "OpenTweaks"; diff --git a/Services/IProcessService.cs b/Services/IProcessService.cs index 1ce17b7..57fa989 100644 --- a/Services/IProcessService.cs +++ b/Services/IProcessService.cs @@ -59,5 +59,47 @@ namespace ThreadPilot.Services /// Sets registry-based priority enforcement for a process /// Task SetRegistryPriorityAsync(ProcessModel process, bool enable, ProcessPriorityClass priority); + + /// + /// Enables or disables the use of Windows CPU Sets for affinity management + /// + void SetUseCpuSets(bool useCpuSets); + + /// + /// Gets whether CPU Sets are currently enabled for affinity management + /// + bool GetUseCpuSets(); + + /// + /// Clears the CPU Set for a process (allows it to run on all cores) + /// + Task ClearProcessCpuSetAsync(ProcessModel process); + + /// + /// Clears all applied CPU masks/affinities from all tracked processes + /// Processes return to using all cores (used on application exit) + /// + Task ClearAllAppliedMasksAsync(); + + /// + /// Resets all modified process priorities to Normal + /// (used on application exit) + /// + Task ResetAllProcessPrioritiesAsync(); + + /// + /// Registers that a mask has been applied to a process (for tracking) + /// + void TrackAppliedMask(int processId, string maskId); + + /// + /// Registers that a priority has been changed for a process (for tracking) + /// + void TrackPriorityChange(int processId, ProcessPriorityClass originalPriority); + + /// + /// Unregisters tracking when a process exits + /// + void UntrackProcess(int processId); } } \ No newline at end of file diff --git a/Services/ISmartNotificationService.cs b/Services/ISmartNotificationService.cs index 6d48b64..2a2792e 100644 --- a/Services/ISmartNotificationService.cs +++ b/Services/ISmartNotificationService.cs @@ -15,7 +15,6 @@ namespace ThreadPilot.Services System, Process, Performance, - GameBoost, PowerPlan, Error, Warning, diff --git a/Services/ISystemTrayService.cs b/Services/ISystemTrayService.cs index 96be9d2..95be094 100644 --- a/Services/ISystemTrayService.cs +++ b/Services/ISystemTrayService.cs @@ -99,11 +99,6 @@ namespace ThreadPilot.Services /// void UpdateSettings(ApplicationSettingsModel settings); - /// - /// Updates the Game Boost status in the tray - /// - void UpdateGameBoostStatus(bool isGameBoostActive, string? currentGameName = null); - /// /// Updates the available power plans in the context menu /// @@ -169,7 +164,6 @@ namespace ThreadPilot.Services Normal, Monitoring, Error, - Disabled, - GameBoost + Disabled } } diff --git a/Services/KeyboardShortcutService.cs b/Services/KeyboardShortcutService.cs index 6646461..d6e5457 100644 --- a/Services/KeyboardShortcutService.cs +++ b/Services/KeyboardShortcutService.cs @@ -234,15 +234,6 @@ namespace ThreadPilot.Services IsEnabled = true, IsGlobal = true }, - [ShortcutActions.GameBoostToggle] = new KeyboardShortcut - { - ActionName = ShortcutActions.GameBoostToggle, - Key = Key.G, - Modifiers = ModifierKeys.Control | ModifierKeys.Shift, - Description = "Toggle Game Boost mode", - IsEnabled = true, - IsGlobal = true - }, [ShortcutActions.PowerPlanHighPerformance] = new KeyboardShortcut { ActionName = ShortcutActions.PowerPlanHighPerformance, @@ -331,7 +322,6 @@ namespace ThreadPilot.Services ShortcutActions.PowerPlanBalanced => "Switch to Balanced power plan", ShortcutActions.PowerPlanHighPerformance => "Switch to High Performance power plan", ShortcutActions.PowerPlanPowerSaver => "Switch to Power Saver power plan", - ShortcutActions.GameBoostToggle => "Toggle Game Boost mode", ShortcutActions.RefreshProcessList => "Refresh process list", ShortcutActions.OpenSettings => "Open Settings tab", ShortcutActions.OpenTweaks => "Open System Tweaks tab", diff --git a/Services/ProcessMonitorManagerService.cs b/Services/ProcessMonitorManagerService.cs index e434714..8b38db0 100644 --- a/Services/ProcessMonitorManagerService.cs +++ b/Services/ProcessMonitorManagerService.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Concurrent; using System.Collections.Generic; +using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; @@ -17,9 +18,10 @@ namespace ThreadPilot.Services private readonly IProcessMonitorService _processMonitorService; private readonly IProcessPowerPlanAssociationService _associationService; private readonly IPowerPlanService _powerPlanService; - private readonly IGameBoostService _gameBoostService; private readonly INotificationService _notificationService; private readonly IApplicationSettingsService _settingsService; + private readonly IProcessService _processService; + private readonly ICoreMaskService _coreMaskService; private readonly ILogger _logger; private readonly IEnhancedLoggingService _enhancedLogger; private readonly object _lockObject = new(); @@ -44,18 +46,20 @@ namespace ThreadPilot.Services IProcessMonitorService processMonitorService, IProcessPowerPlanAssociationService associationService, IPowerPlanService powerPlanService, - IGameBoostService gameBoostService, INotificationService notificationService, IApplicationSettingsService settingsService, + IProcessService processService, + ICoreMaskService coreMaskService, ILogger logger, IEnhancedLoggingService enhancedLogger) { _processMonitorService = processMonitorService ?? throw new ArgumentNullException(nameof(processMonitorService)); _associationService = associationService ?? throw new ArgumentNullException(nameof(associationService)); _powerPlanService = powerPlanService ?? throw new ArgumentNullException(nameof(powerPlanService)); - _gameBoostService = gameBoostService ?? throw new ArgumentNullException(nameof(gameBoostService)); _notificationService = notificationService ?? throw new ArgumentNullException(nameof(notificationService)); _settingsService = settingsService ?? throw new ArgumentNullException(nameof(settingsService)); + _processService = processService ?? throw new ArgumentNullException(nameof(processService)); + _coreMaskService = coreMaskService ?? throw new ArgumentNullException(nameof(coreMaskService)); _logger = logger ?? throw new ArgumentNullException(nameof(logger)); _enhancedLogger = enhancedLogger ?? throw new ArgumentNullException(nameof(enhancedLogger)); @@ -243,9 +247,6 @@ namespace ThreadPilot.Services await _enhancedLogger.LogProcessMonitoringEventAsync(LogEventTypes.ProcessMonitoring.Started, e.Process.Name, e.Process.ProcessId, "Process started and detected by monitoring"); - // Check for Game Boost first - await CheckForGameBoostAsync(e.Process); - var association = _configuration.FindMatchingAssociation(e.Process); if (association != null) { @@ -255,6 +256,9 @@ namespace ThreadPilot.Services e.Process.Name, e.Process.ProcessId, $"Process matched association for power plan: {association.PowerPlanName}"); + // Apply CPU affinity mask if configured + await ApplyCoreMaskAndPriorityAsync(e.Process, association); + // Schedule power plan change with delay if configured if (_configuration.PowerPlanChangeDelayMs > 0) { @@ -287,9 +291,6 @@ namespace ThreadPilot.Services try { - // Check if this was a game process and deactivate Game Boost if needed - await CheckForGameBoostDeactivationAsync(e.Process); - if (_runningAssociatedProcesses.TryRemove(e.Process.ProcessId, out var removedProcess)) { // Check if there are any other associated processes still running @@ -427,50 +428,6 @@ namespace ThreadPilot.Services } } - /// - /// Checks if a process is a game and activates Game Boost if enabled - /// - private async Task CheckForGameBoostAsync(ProcessModel process) - { - try - { - if (_gameBoostService.IsGameProcess(process)) - { - _logger.LogInformation("Game detected: {ProcessName} (PID: {ProcessId})", process.Name, process.ProcessId); - - // Activate Game Boost if enabled and not already active for this process - if (!_gameBoostService.IsGameBoostActive || _gameBoostService.CurrentGameProcess?.ProcessId != process.ProcessId) - { - await _gameBoostService.ActivateGameBoostAsync(process); - } - } - } - catch (Exception ex) - { - _logger.LogError(ex, "Error checking for Game Boost activation for process {ProcessName}", process.Name); - } - } - - /// - /// Checks if a stopped process was the current game and deactivates Game Boost if needed - /// - private async Task CheckForGameBoostDeactivationAsync(ProcessModel process) - { - try - { - if (_gameBoostService.IsGameBoostActive && - _gameBoostService.CurrentGameProcess?.ProcessId == process.ProcessId) - { - _logger.LogInformation("Game process stopped: {ProcessName} (PID: {ProcessId})", process.Name, process.ProcessId); - await _gameBoostService.DeactivateGameBoostAsync(); - } - } - catch (Exception ex) - { - _logger.LogError(ex, "Error checking for Game Boost deactivation for process {ProcessName}", process.Name); - } - } - public void UpdateSettings() { // Update the process monitor service with new settings @@ -479,6 +436,117 @@ namespace ThreadPilot.Services _logger.LogDebug("ProcessMonitorManagerService settings updated"); } + /// + /// Applies CPU affinity mask and process priority from association when a process starts + /// Based on CPUSetSetter's ProgramRule.SetMask pattern + /// + private async Task ApplyCoreMaskAndPriorityAsync(ProcessModel process, ProcessPowerPlanAssociation association) + { + try + { + // Apply CPU affinity mask if configured + if (!string.IsNullOrEmpty(association.CoreMaskId)) + { + var coreMask = _coreMaskService.AvailableMasks.FirstOrDefault(m => m.Id == association.CoreMaskId); + if (coreMask != null) + { + try + { + var affinity = coreMask.ToProcessorAffinity(); + if (affinity > 0) + { + await _processService.SetProcessorAffinity(process, affinity); + + _logger.LogInformation( + "Applied CPU mask '{MaskName}' (affinity: 0x{Affinity:X}) to process {ProcessName} (PID: {ProcessId})", + coreMask.Name, affinity, process.Name, process.ProcessId); + + await _enhancedLogger.LogProcessMonitoringEventAsync( + LogEventTypes.ProcessMonitoring.AssociationTriggered, + process.Name, process.ProcessId, + $"CPU mask '{coreMask.Name}' applied automatically from association"); + } + } + catch (Exception ex) + { + _logger.LogWarning(ex, + "Failed to apply CPU mask '{MaskName}' to process {ProcessName} (PID: {ProcessId})", + coreMask.Name, process.Name, process.ProcessId); + + await _enhancedLogger.LogErrorAsync(ex, "ProcessMonitorManagerService.ApplyCoreMaskAndPriorityAsync", + new Dictionary + { + ["ProcessName"] = process.Name, + ["ProcessId"] = process.ProcessId, + ["MaskName"] = coreMask.Name + }); + } + } + else + { + _logger.LogWarning( + "Core mask ID '{CoreMaskId}' not found for process {ProcessName}, skipping affinity application", + association.CoreMaskId, process.Name); + } + } + + // Apply process priority if configured + if (!string.IsNullOrEmpty(association.ProcessPriority)) + { + if (Enum.TryParse(association.ProcessPriority, out var priority)) + { + try + { + await _processService.SetProcessPriority(process, priority); + + _logger.LogInformation( + "Applied priority '{Priority}' to process {ProcessName} (PID: {ProcessId})", + priority, process.Name, process.ProcessId); + + await _enhancedLogger.LogProcessMonitoringEventAsync( + LogEventTypes.ProcessMonitoring.AssociationTriggered, + process.Name, process.ProcessId, + $"Priority '{priority}' applied automatically from association"); + } + catch (Exception ex) + { + _logger.LogWarning(ex, + "Failed to apply priority '{Priority}' to process {ProcessName} (PID: {ProcessId})", + priority, process.Name, process.ProcessId); + + await _enhancedLogger.LogErrorAsync(ex, "ProcessMonitorManagerService.ApplyCoreMaskAndPriorityAsync", + new Dictionary + { + ["ProcessName"] = process.Name, + ["ProcessId"] = process.ProcessId, + ["Priority"] = priority.ToString() + }); + } + } + else + { + _logger.LogWarning( + "Invalid priority value '{Priority}' for process {ProcessName}, skipping priority application", + association.ProcessPriority, process.Name); + } + } + } + catch (Exception ex) + { + _logger.LogError(ex, + "Error applying CPU mask and priority to process {ProcessName} (PID: {ProcessId})", + process.Name, process.ProcessId); + + await _enhancedLogger.LogErrorAsync(ex, "ProcessMonitorManagerService.ApplyCoreMaskAndPriorityAsync", + new Dictionary + { + ["ProcessName"] = process.Name, + ["ProcessId"] = process.ProcessId, + ["AssociationId"] = association.Id + }); + } + } + public void Dispose() { if (_disposed) return; diff --git a/Services/ProcessService.cs b/Services/ProcessService.cs index 24275a9..0070ba7 100644 --- a/Services/ProcessService.cs +++ b/Services/ProcessService.cs @@ -1,24 +1,40 @@ using System; +using System.Collections.Concurrent; using System.Collections.ObjectModel; +using System.ComponentModel; using System.Diagnostics; using System.IO; using System.Linq; using System.Text.Json; using System.Threading.Tasks; +using Microsoft.Extensions.Logging; using ThreadPilot.Models; +using ThreadPilot.Platforms.Windows; namespace ThreadPilot.Services { public class ProcessService : IProcessService { + private readonly ConcurrentDictionary _cpuSamples = new(); + private readonly ConcurrentDictionary _cpuSetHandlers = new(); + private readonly ILogger? _logger; private string ProfilesDirectory => Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Profiles"); + private bool _useCpuSets = true; // Enable CPU Sets by default - public ProcessService() + // Tracking for cleanup on exit + private readonly ConcurrentDictionary _appliedMasks = new(); // ProcessId -> MaskId + private readonly ConcurrentDictionary _originalPriorities = new(); // ProcessId -> OriginalPriority + + public ProcessService(ILogger? logger = null) { + _logger = logger; + if (!Directory.Exists(ProfilesDirectory)) { Directory.CreateDirectory(ProfilesDirectory); } + + _logger?.LogInformation("ProcessService initialized with CPU Sets support enabled"); } public async Task> GetProcessesAsync() @@ -34,6 +50,53 @@ namespace ThreadPilot.Services }); } + private sealed class CpuSample + { + public CpuSample(TimeSpan totalProcessorTime, DateTime timestamp) + { + TotalProcessorTime = totalProcessorTime; + Timestamp = timestamp; + } + + public TimeSpan TotalProcessorTime { get; set; } + public DateTime Timestamp { get; set; } + } + + private double CalculateCpuUsage(Process process) + { + try + { + var now = DateTime.UtcNow; + var totalProcessorTime = process.TotalProcessorTime; + + if (_cpuSamples.TryGetValue(process.Id, out var previous)) + { + var cpuDeltaMs = (totalProcessorTime - previous.TotalProcessorTime).TotalMilliseconds; + var timeDeltaMs = (now - previous.Timestamp).TotalMilliseconds; + + // Ignore extremely small deltas to avoid noisy values + if (timeDeltaMs <= 0 || cpuDeltaMs < 0) + { + _cpuSamples[process.Id] = new CpuSample(totalProcessorTime, now); + return 0; + } + + var usage = (cpuDeltaMs / (timeDeltaMs * Environment.ProcessorCount)) * 100.0; + usage = Math.Clamp(usage, 0, 100); + + _cpuSamples[process.Id] = new CpuSample(totalProcessorTime, now); + return usage; + } + + _cpuSamples[process.Id] = new CpuSample(totalProcessorTime, now); + return 0; // First sample cannot produce a rate + } + catch + { + return 0; + } + } + public ProcessModel CreateProcessModel(Process process) { var model = new ProcessModel(); @@ -42,9 +105,10 @@ namespace ThreadPilot.Services model.Process = process; model.ProcessId = process.Id; model.Name = process.ProcessName; - model.MemoryUsage = process.WorkingSet64; + model.MemoryUsage = process.PrivateMemorySize64; model.Priority = process.PriorityClass; model.ProcessorAffinity = (long)process.ProcessorAffinity; + model.CpuUsage = CalculateCpuUsage(process); // Capture window information model.MainWindowHandle = process.MainWindowHandle; @@ -78,11 +142,52 @@ namespace ThreadPilot.Services { try { - if (process.Process != null) + if (affinityMask == 0) { - process.Process.ProcessorAffinity = new IntPtr(affinityMask); - process.ProcessorAffinity = affinityMask; + throw new InvalidOperationException("Affinity mask cannot be zero."); } + + // Try using CPU Sets first (Windows 10+) + if (_useCpuSets) + { + bool cpuSetSuccess = TrySetAffinityViaCpuSets(process, affinityMask); + if (cpuSetSuccess) + { + _logger?.LogInformation("Successfully applied CPU Sets affinity 0x{AffinityMask:X} to process {ProcessName} (PID: {ProcessId})", + affinityMask, process.Name, process.ProcessId); + + // Update the model with the new affinity + process.ProcessorAffinity = affinityMask; + return; + } + else + { + _logger?.LogDebug("CPU Sets failed for process {ProcessName} (PID: {ProcessId}), falling back to classic ProcessorAffinity", + process.Name, process.ProcessId); + } + } + + // Fallback to classic ProcessorAffinity method + var targetProcess = process.Process; + if (targetProcess == null || targetProcess.HasExited) + { + targetProcess = Process.GetProcessById(process.ProcessId); + } + + targetProcess.ProcessorAffinity = new IntPtr(affinityMask); + process.Process = targetProcess; + process.ProcessorAffinity = (long)targetProcess.ProcessorAffinity; + + _logger?.LogInformation("Successfully applied classic ProcessorAffinity 0x{AffinityMask:X} to process {ProcessName} (PID: {ProcessId})", + affinityMask, process.Name, process.ProcessId); + } + catch (Win32Exception ex) when (ex.NativeErrorCode == 87) + { + throw new InvalidOperationException("Invalid affinity mask for this system.", ex); + } + catch (Win32Exception ex) when (ex.NativeErrorCode == 5) + { + throw new InvalidOperationException("Access denied while setting processor affinity. The process may be protected (e.g., anti-cheat).", ex); } catch (Exception ex) { @@ -91,17 +196,75 @@ namespace ThreadPilot.Services }); } + /// + /// Attempts to set process affinity using CPU Sets (Windows 10+ feature) + /// + private bool TrySetAffinityViaCpuSets(ProcessModel process, long affinityMask) + { + try + { + // Get or create CPU Set handler for this process + var handler = _cpuSetHandlers.GetOrAdd(process.ProcessId, pid => + { + return new ProcessCpuSetHandler((uint)pid, process.Name, _logger); + }); + + // Check if handler is valid + if (!handler.IsValid) + { + _logger?.LogDebug("CPU Set handler for process {ProcessName} (PID: {ProcessId}) is invalid", + process.Name, process.ProcessId); + + // Remove invalid handler + _cpuSetHandlers.TryRemove(process.ProcessId, out _); + return false; + } + + // Apply the CPU Set mask + bool success = handler.ApplyCpuSetMask(affinityMask, clearMask: false); + + if (!success) + { + // Remove failed handler so we can try again later if needed + _cpuSetHandlers.TryRemove(process.ProcessId, out _); + } + + return success; + } + catch (Exception ex) + { + _logger?.LogWarning(ex, "Exception while applying CPU Sets to process {ProcessName} (PID: {ProcessId})", + process.Name, process.ProcessId); + + // Remove handler on exception + _cpuSetHandlers.TryRemove(process.ProcessId, out _); + return false; + } + } + public async Task SetProcessPriority(ProcessModel process, ProcessPriorityClass priority) { await Task.Run(() => { try { - if (process.Process != null) + var targetProcess = process.Process; + if (targetProcess == null || targetProcess.HasExited) { - process.Process.PriorityClass = priority; - process.Priority = priority; + targetProcess = Process.GetProcessById(process.ProcessId); } + + targetProcess.PriorityClass = priority; + process.Process = targetProcess; + process.Priority = targetProcess.PriorityClass; + } + catch (Win32Exception ex) when (ex.NativeErrorCode == 5) + { + throw new InvalidOperationException("Access denied while setting process priority. The process may be protected (e.g., anti-cheat).", ex); + } + catch (UnauthorizedAccessException ex) + { + throw new InvalidOperationException("Access denied while setting process priority. The process may be protected (e.g., anti-cheat).", ex); } catch (Exception ex) { @@ -157,9 +320,11 @@ namespace ThreadPilot.Services throw new InvalidOperationException("Process has exited"); } - process.MemoryUsage = p.WorkingSet64; + process.MemoryUsage = p.PrivateMemorySize64; process.Priority = p.PriorityClass; process.ProcessorAffinity = (long)p.ProcessorAffinity; + process.CpuUsage = CalculateCpuUsage(p); + process.Process = p; // Update window information process.MainWindowHandle = p.MainWindowHandle; @@ -169,16 +334,112 @@ namespace ThreadPilot.Services catch (ArgumentException) { // Process with the specified ID does not exist + CleanupProcessResources(process.ProcessId); throw new InvalidOperationException("Process no longer exists"); } catch (Exception ex) when (ex.Message.Contains("exited") || ex.Message.Contains("terminated")) { // Process has terminated + CleanupProcessResources(process.ProcessId); throw new InvalidOperationException("Process has terminated"); } }); } + /// + /// Cleanup resources associated with a process + /// + private void CleanupProcessResources(int processId) + { + // Remove CPU samples + _cpuSamples.TryRemove(processId, out _); + + // Dispose and remove CPU Set handler + if (_cpuSetHandlers.TryRemove(processId, out var handler)) + { + try + { + handler.Dispose(); + _logger?.LogDebug("Cleaned up CPU Set handler for process ID {ProcessId}", processId); + } + catch (Exception ex) + { + _logger?.LogWarning(ex, "Error disposing CPU Set handler for process ID {ProcessId}", processId); + } + } + } + + /// + /// Enables or disables the use of Windows CPU Sets for affinity management + /// + public void SetUseCpuSets(bool useCpuSets) + { + _useCpuSets = useCpuSets; + _logger?.LogInformation("CPU Sets usage {Status}", useCpuSets ? "enabled" : "disabled"); + } + + /// + /// Gets whether CPU Sets are currently enabled for affinity management + /// + public bool GetUseCpuSets() + { + return _useCpuSets; + } + + /// + /// Clears the CPU Set for a process (allows it to run on all cores) + /// + public async Task ClearProcessCpuSetAsync(ProcessModel process) + { + return await Task.Run(() => + { + try + { + if (!_useCpuSets) + { + _logger?.LogDebug("CPU Sets are disabled, cannot clear CPU Set for process {ProcessName}", process.Name); + return false; + } + + // Get or create CPU Set handler for this process + var handler = _cpuSetHandlers.GetOrAdd(process.ProcessId, pid => + { + return new ProcessCpuSetHandler((uint)pid, process.Name, _logger); + }); + + if (!handler.IsValid) + { + _logger?.LogDebug("CPU Set handler for process {ProcessName} (PID: {ProcessId}) is invalid", + process.Name, process.ProcessId); + _cpuSetHandlers.TryRemove(process.ProcessId, out _); + return false; + } + + // Clear the mask (set clearMask = true) + bool success = handler.ApplyCpuSetMask(0, clearMask: true); + + if (success) + { + _logger?.LogInformation("Successfully cleared CPU Set for process {ProcessName} (PID: {ProcessId})", + process.Name, process.ProcessId); + } + else + { + _cpuSetHandlers.TryRemove(process.ProcessId, out _); + } + + return success; + } + catch (Exception ex) + { + _logger?.LogWarning(ex, "Exception while clearing CPU Set for process {ProcessName} (PID: {ProcessId})", + process.Name, process.ProcessId); + _cpuSetHandlers.TryRemove(process.ProcessId, out _); + return false; + } + }); + } + public async Task GetProcessByIdAsync(int processId) { return await Task.Run(() => @@ -345,6 +606,172 @@ namespace ThreadPilot.Services } }); } + + /// + /// Registers that a mask has been applied to a process (for tracking cleanup on exit) + /// + public void TrackAppliedMask(int processId, string maskId) + { + _appliedMasks[processId] = maskId; + _logger?.LogDebug("Tracking mask {MaskId} applied to process {ProcessId}", maskId, processId); + } + + /// + /// Registers that a priority has been changed for a process (for tracking cleanup on exit) + /// + public void TrackPriorityChange(int processId, ProcessPriorityClass originalPriority) + { + // Only track if not already tracked (keep the original priority) + if (!_originalPriorities.ContainsKey(processId)) + { + _originalPriorities[processId] = originalPriority; + _logger?.LogDebug("Tracking original priority {Priority} for process {ProcessId}", originalPriority, processId); + } + } + + /// + /// Unregisters tracking when a process exits + /// + public void UntrackProcess(int processId) + { + _appliedMasks.TryRemove(processId, out _); + _originalPriorities.TryRemove(processId, out _); + CleanupProcessResources(processId); + _logger?.LogDebug("Untracked process {ProcessId}", processId); + } + + /// + /// Clears all applied CPU masks/affinities from all tracked processes + /// Processes return to using all cores (used on application exit) + /// + public async Task ClearAllAppliedMasksAsync() + { + _logger?.LogInformation("Clearing all applied CPU masks from {Count} tracked processes", _appliedMasks.Count); + + var processIds = _appliedMasks.Keys.ToList(); + var clearedCount = 0; + var failedCount = 0; + + foreach (var processId in processIds) + { + try + { + // Check if process is still running + Process process; + try + { + process = Process.GetProcessById(processId); + if (process.HasExited) + { + _appliedMasks.TryRemove(processId, out _); + continue; + } + } + catch (ArgumentException) + { + // Process no longer exists + _appliedMasks.TryRemove(processId, out _); + continue; + } + + // Clear CPU Set if we have a handler + if (_cpuSetHandlers.TryGetValue(processId, out var handler) && handler.IsValid) + { + handler.ApplyCpuSetMask(0, clearMask: true); + _logger?.LogDebug("Cleared CPU Set for process {ProcessName} (PID: {ProcessId})", + process.ProcessName, processId); + } + + // Reset processor affinity to all cores + try + { + long allCoresMask = GetAllCoresAffinityMask(); + process.ProcessorAffinity = new IntPtr(allCoresMask); + _logger?.LogDebug("Reset ProcessorAffinity for process {ProcessName} (PID: {ProcessId})", + process.ProcessName, processId); + } + catch (Exception ex) + { + _logger?.LogWarning(ex, "Failed to reset ProcessorAffinity for process PID {ProcessId}", processId); + } + + _appliedMasks.TryRemove(processId, out _); + clearedCount++; + } + catch (Exception ex) + { + _logger?.LogWarning(ex, "Failed to clear mask for process PID {ProcessId}", processId); + failedCount++; + } + } + + _logger?.LogInformation("Cleared CPU masks: {Cleared} succeeded, {Failed} failed", clearedCount, failedCount); + await Task.CompletedTask; + } + + /// + /// Resets all modified process priorities to Normal (or their original priority) + /// + public async Task ResetAllProcessPrioritiesAsync() + { + _logger?.LogInformation("Resetting priorities for {Count} tracked processes", _originalPriorities.Count); + + var processIds = _originalPriorities.Keys.ToList(); + var resetCount = 0; + var failedCount = 0; + + foreach (var processId in processIds) + { + try + { + // Check if process is still running + Process process; + try + { + process = Process.GetProcessById(processId); + if (process.HasExited) + { + _originalPriorities.TryRemove(processId, out _); + continue; + } + } + catch (ArgumentException) + { + // Process no longer exists + _originalPriorities.TryRemove(processId, out _); + continue; + } + + // Get original priority + if (_originalPriorities.TryGetValue(processId, out var originalPriority)) + { + process.PriorityClass = originalPriority; + _logger?.LogDebug("Reset priority for process {ProcessName} (PID: {ProcessId}) to {Priority}", + process.ProcessName, processId, originalPriority); + } + + _originalPriorities.TryRemove(processId, out _); + resetCount++; + } + catch (Exception ex) + { + _logger?.LogWarning(ex, "Failed to reset priority for process PID {ProcessId}", processId); + failedCount++; + } + } + + _logger?.LogInformation("Reset priorities: {Reset} succeeded, {Failed} failed", resetCount, failedCount); + await Task.CompletedTask; + } + + /// + /// Gets an affinity mask with all cores enabled + /// + private long GetAllCoresAffinityMask() + { + int coreCount = Environment.ProcessorCount; + return coreCount >= 64 ? -1L : (1L << coreCount) - 1; + } } /// diff --git a/Services/ServiceConfiguration.cs b/Services/ServiceConfiguration.cs index 4a8d439..ceababa 100644 --- a/Services/ServiceConfiguration.cs +++ b/Services/ServiceConfiguration.cs @@ -60,9 +60,6 @@ namespace ThreadPilot.Services // Service factory for advanced service management services.AddSingleton(); - // Data access services - services.AddSingleton(); - return services; } @@ -77,6 +74,14 @@ namespace ThreadPilot.Services services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); + + // CoreMaskService needs IServiceProvider for checking profile references + services.AddSingleton(sp => + { + var logger = sp.GetRequiredService>(); + var cpuTopologyService = sp.GetRequiredService(); + return new CoreMaskService(logger, cpuTopologyService, sp); + }); return services; } @@ -90,12 +95,8 @@ namespace ThreadPilot.Services services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); - - // Game boost and optimization services - services.AddSingleton(); - // Game detection and performance monitoring services - services.AddSingleton(); + // Performance monitoring services services.AddSingleton(); return services; @@ -117,6 +118,9 @@ namespace ThreadPilot.Services // System integration services services.AddSingleton(); + // System optimization services + services.AddSingleton(); + // Security and elevation services services.AddSingleton(); services.AddSingleton(); @@ -140,10 +144,10 @@ namespace ThreadPilot.Services // ViewModels - ProcessViewModel as Singleton to share state across views, others as Transient services.AddSingleton(); + services.AddSingleton(); services.AddTransient(); services.AddTransient(); services.AddTransient(); - services.AddTransient(); services.AddTransient(); services.AddTransient(); services.AddTransient(); diff --git a/Services/SystemTrayService.cs b/Services/SystemTrayService.cs index f093201..d6b72f6 100644 --- a/Services/SystemTrayService.cs +++ b/Services/SystemTrayService.cs @@ -18,7 +18,6 @@ namespace ThreadPilot.Services private ToolStripMenuItem? _quickApplyMenuItem; private ToolStripMenuItem? _selectedProcessMenuItem; private ToolStripMenuItem? _monitoringToggleMenuItem; - private ToolStripMenuItem? _gameBoostStatusMenuItem; private ToolStripMenuItem? _settingsMenuItem; private ToolStripMenuItem? _powerPlansMenuItem; private ToolStripMenuItem? _profilesMenuItem; @@ -27,8 +26,6 @@ namespace ThreadPilot.Services private ApplicationSettingsModel _settings; private bool _isMonitoring = true; private bool _isWmiAvailable = true; - private bool _isGameBoostActive = false; - private string? _currentGameName = null; private TrayIconState _currentIconState = TrayIconState.Normal; private bool _disposed = false; @@ -67,47 +64,8 @@ namespace ThreadPilot.Services Visible = false }; - // Try to load the same icon as the main application - try - { - // First try to use the application's icon (same as main window) - var app = System.Windows.Application.Current; - if (app?.MainWindow?.Icon != null) - { - // Convert WPF ImageSource to System.Drawing.Icon - var iconPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "ico.ico"); - if (File.Exists(iconPath)) - { - _notifyIcon.Icon = new Icon(iconPath); - _logger.LogInformation("Loaded custom tray icon from ico.ico file (same as main application)"); - } - else - { - _logger.LogWarning("ico.ico file not found, using default system icon"); - _notifyIcon.Icon = SystemIcons.Application; - } - } - else - { - // Fallback to file-based loading - var iconPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "ico.ico"); - if (File.Exists(iconPath)) - { - _notifyIcon.Icon = new Icon(iconPath); - _logger.LogInformation("Loaded custom tray icon from ico.ico file"); - } - else - { - _logger.LogWarning("ico.ico file not found at {IconPath}, using default system icon", iconPath); - _notifyIcon.Icon = SystemIcons.Application; - } - } - } - catch (Exception ex) - { - _logger.LogWarning(ex, "Failed to load custom tray icon, using default"); - _notifyIcon.Icon = SystemIcons.Application; - } + // Load the tray icon (custom path if enabled, otherwise bundled ico.ico) + TryLoadTrayIcon(); // Create context menu CreateContextMenu(); @@ -183,14 +141,6 @@ namespace ThreadPilot.Services _monitoringToggleMenuItem.Click += OnMonitoringToggleClick; _contextMenu.Items.Add(_monitoringToggleMenuItem); - // Game Boost status (disabled, for display only) - _gameBoostStatusMenuItem = new ToolStripMenuItem("🎮 Game Boost: Inactive") - { - Enabled = false, - Font = new Font(_contextMenu.Font, FontStyle.Italic) - }; - _contextMenu.Items.Add(_gameBoostStatusMenuItem); - // Separator _contextMenu.Items.Add(new ToolStripSeparator()); @@ -346,36 +296,7 @@ namespace ThreadPilot.Services _currentIconState = state; - try - { - // Always use the custom ThreadPilot icon regardless of state - // The tooltip will indicate the current state instead - var iconPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "ico.ico"); - if (File.Exists(iconPath)) - { - // Use custom icon for all states - _notifyIcon.Icon = new Icon(iconPath); - _logger.LogDebug("Tray icon updated to state: {State} using custom icon", state); - } - else - { - // Fallback to system icons if custom icon is not available - _notifyIcon.Icon = state switch - { - TrayIconState.Normal => SystemIcons.Application, - TrayIconState.Monitoring => SystemIcons.Information, - TrayIconState.Error => SystemIcons.Error, - TrayIconState.Disabled => SystemIcons.Warning, - TrayIconState.GameBoost => SystemIcons.Shield, - _ => SystemIcons.Application - }; - _logger.LogDebug("Tray icon updated to state: {State} using system icon (custom icon not found)", state); - } - } - catch (Exception ex) - { - _logger.LogWarning(ex, "Failed to update tray icon"); - } + TryLoadTrayIcon(state); } public void ShowTrayNotification(string title, string message, NotificationType type = NotificationType.Information, int timeoutMs = 3000) @@ -409,51 +330,12 @@ namespace ThreadPilot.Services if (_notifyIcon != null) { _notifyIcon.Visible = settings.ShowTrayIcon; + TryLoadTrayIcon(_currentIconState); } _logger.LogDebug("Tray service settings updated"); } - public void UpdateGameBoostStatus(bool isGameBoostActive, string? currentGameName = null) - { - _isGameBoostActive = isGameBoostActive; - _currentGameName = currentGameName; - - // Update Game Boost status menu item - if (_gameBoostStatusMenuItem != null) - { - if (isGameBoostActive && !string.IsNullOrEmpty(currentGameName)) - { - _gameBoostStatusMenuItem.Text = $"Game Boost: Active ({currentGameName})"; - _gameBoostStatusMenuItem.Font = new Font(_gameBoostStatusMenuItem.Font, FontStyle.Bold); - } - else if (isGameBoostActive) - { - _gameBoostStatusMenuItem.Text = "Game Boost: Active"; - _gameBoostStatusMenuItem.Font = new Font(_gameBoostStatusMenuItem.Font, FontStyle.Bold); - } - else - { - _gameBoostStatusMenuItem.Text = "Game Boost: Inactive"; - _gameBoostStatusMenuItem.Font = new Font(_gameBoostStatusMenuItem.Font, FontStyle.Italic); - } - } - - // Update tray icon state - Game Boost takes priority over monitoring state - var iconState = !_isWmiAvailable ? TrayIconState.Error : - isGameBoostActive ? TrayIconState.GameBoost : - _isMonitoring ? TrayIconState.Monitoring : TrayIconState.Disabled; - UpdateTrayIcon(iconState); - - // Update tooltip - var status = !_isWmiAvailable ? "WMI Error" : - isGameBoostActive ? $"Game Boost Active{(!string.IsNullOrEmpty(currentGameName) ? $" - {currentGameName}" : "")}" : - _isMonitoring ? "Monitoring Active" : "Monitoring Disabled"; - UpdateTooltip($"ThreadPilot - {status}"); - - _logger.LogDebug("Game Boost status updated: Active={IsActive}, Game={GameName}", isGameBoostActive, currentGameName); - } - public void UpdatePowerPlans(IEnumerable powerPlans, PowerPlanModel? activePlan) { if (_powerPlansMenuItem == null) return; @@ -562,5 +444,48 @@ namespace ThreadPilot.Services _logger.LogError(ex, "Error disposing system tray service"); } } + + private string? ResolveTrayIconPath() + { + if (_settings.UseCustomTrayIcon && !string.IsNullOrWhiteSpace(_settings.CustomTrayIconPath) && File.Exists(_settings.CustomTrayIconPath)) + { + return _settings.CustomTrayIconPath; + } + + var bundledIcon = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "ico.ico"); + return File.Exists(bundledIcon) ? bundledIcon : null; + } + + private void TryLoadTrayIcon(TrayIconState? stateOverride = null) + { + if (_notifyIcon == null) return; + + try + { + var iconPath = ResolveTrayIconPath(); + if (iconPath != null) + { + _notifyIcon.Icon = new Icon(iconPath); + _logger.LogDebug("Tray icon set from {IconPath}", iconPath); + return; + } + + // Fallback to system icons if no custom/bundled icon is available + var state = stateOverride ?? _currentIconState; + _notifyIcon.Icon = state switch + { + TrayIconState.Normal => SystemIcons.Application, + TrayIconState.Monitoring => SystemIcons.Information, + TrayIconState.Error => SystemIcons.Error, + TrayIconState.Disabled => SystemIcons.Warning, + _ => SystemIcons.Application + }; + _logger.LogDebug("Tray icon set to system icon for state {State}", state); + } + catch (Exception ex) + { + _logger.LogWarning(ex, "Failed to load tray icon"); + } + } } } diff --git a/ThreadPilot.csproj b/ThreadPilot.csproj index 3efc21b..06ee2e8 100644 --- a/ThreadPilot.csproj +++ b/ThreadPilot.csproj @@ -14,17 +14,51 @@ win-x64 false link + true + CS1998;CS0067;CS0414;WFAC010;IL3000;MVVMTK0034 - - - - + + + + + + + PreserveNewest + + + + + + + MSBuild:Compile + + + + + + + + + + + + + + + + + + + + + + diff --git a/UI_STYLE_GUIDE.md b/UI_STYLE_GUIDE.md index 5277efc..ba38d5f 100644 --- a/UI_STYLE_GUIDE.md +++ b/UI_STYLE_GUIDE.md @@ -12,7 +12,6 @@ This document defines the UI standards, terminology, and style guidelines for th - 🔧 Process Management - ⚡ Power Plans - 🔗 Process Associations - - 📋 Activity Logs - ⚙️ Settings ### Status Bar diff --git a/ViewModels/MainWindowViewModel.cs b/ViewModels/MainWindowViewModel.cs index 1aba6ab..422843b 100644 --- a/ViewModels/MainWindowViewModel.cs +++ b/ViewModels/MainWindowViewModel.cs @@ -11,21 +11,11 @@ namespace ThreadPilot { public partial class MainWindowViewModel : BaseViewModel { - private readonly IGameBoostService? _gameBoostService; private readonly IProcessMonitorManagerService? _processMonitorManagerService; private readonly INotificationService? _notificationService; private readonly IElevationService? _elevationService; private readonly ISecurityService? _securityService; - [ObservableProperty] - private bool isGameBoostActive = false; - - [ObservableProperty] - private string gameBoostStatusText = "Game Boost: Inactive"; - - [ObservableProperty] - private string? currentGameName = null; - [ObservableProperty] private bool isProcessMonitoringActive = false; @@ -44,14 +34,12 @@ namespace ThreadPilot public MainWindowViewModel( ILogger logger, IEnhancedLoggingService? enhancedLoggingService = null, - IGameBoostService? gameBoostService = null, IProcessMonitorManagerService? processMonitorManagerService = null, INotificationService? notificationService = null, IElevationService? elevationService = null, ISecurityService? securityService = null) : base(logger, enhancedLoggingService) { - _gameBoostService = gameBoostService; _processMonitorManagerService = processMonitorManagerService; _notificationService = notificationService; _elevationService = elevationService; @@ -63,12 +51,6 @@ namespace ThreadPilot await ExecuteAsync(async () => { // Subscribe to service events - if (_gameBoostService != null) - { - _gameBoostService.GameBoostActivated += OnGameBoostActivated; - _gameBoostService.GameBoostDeactivated += OnGameBoostDeactivated; - } - if (_processMonitorManagerService != null) { _processMonitorManagerService.ServiceStatusChanged += OnServiceStatusChanged; @@ -102,26 +84,6 @@ namespace ThreadPilot }, IsProcessMonitoringActive ? "Stopping monitoring..." : "Starting monitoring..."); } - [RelayCommand] - private async Task ToggleGameBoostAsync() - { - if (_gameBoostService == null) return; - - await ExecuteAsync(async () => - { - if (IsGameBoostActive) - { - await _gameBoostService.DeactivateGameBoostAsync(); - await LogUserActionAsync("GameBoost", "Deactivated game boost", "User action"); - } - else - { - // Game boost is typically activated automatically, but we can force it - await LogUserActionAsync("GameBoost", "Attempted to activate game boost", "User action"); - } - }, "Toggling game boost..."); - } - [RelayCommand] private async Task RequestElevationAsync() { @@ -145,14 +107,6 @@ namespace ThreadPilot { try { - // Update game boost status - if (_gameBoostService != null) - { - IsGameBoostActive = _gameBoostService.IsGameBoostActive; - CurrentGameName = _gameBoostService.CurrentGameProcess?.Name; - UpdateGameBoostStatusText(); - } - // Update process monitoring status if (_processMonitorManagerService != null) { @@ -186,67 +140,6 @@ namespace ThreadPilot ShowElevationPrompt = !IsRunningAsAdministrator; } - private void UpdateGameBoostStatusText() - { - if (IsGameBoostActive && !string.IsNullOrEmpty(CurrentGameName)) - { - GameBoostStatusText = $"Game Boost: Active ({CurrentGameName})"; - } - else if (IsGameBoostActive) - { - GameBoostStatusText = "Game Boost: Active"; - } - else - { - GameBoostStatusText = "Game Boost: Inactive"; - } - } - - public void UpdateGameBoostStatus(bool isActive, string? gameName = null) - { - IsGameBoostActive = isActive; - CurrentGameName = gameName; - UpdateGameBoostStatusText(); - } - - private async void OnGameBoostActivated(object? sender, GameBoostActivatedEventArgs e) - { - // Marshal UI updates to the UI thread to prevent cross-thread access exceptions - await System.Windows.Application.Current.Dispatcher.InvokeAsync(() => - { - IsGameBoostActive = true; - CurrentGameName = e.GameProcess?.Name; - UpdateGameBoostStatusText(); - }); - - if (_notificationService != null) - { - await _notificationService.ShowNotificationAsync( - "Game Boost Activated", - $"Performance boost enabled for {CurrentGameName}", - NotificationType.Information); - } - } - - private async void OnGameBoostDeactivated(object? sender, GameBoostDeactivatedEventArgs e) - { - // Marshal UI updates to the UI thread to prevent cross-thread access exceptions - await System.Windows.Application.Current.Dispatcher.InvokeAsync(() => - { - IsGameBoostActive = false; - CurrentGameName = null; - UpdateGameBoostStatusText(); - }); - - if (_notificationService != null) - { - await _notificationService.ShowNotificationAsync( - "Game Boost Deactivated", - "Performance boost disabled", - NotificationType.Information); - } - } - private void OnServiceStatusChanged(object? sender, ServiceStatusEventArgs e) { // Marshal UI updates to the UI thread to prevent cross-thread access exceptions @@ -265,13 +158,6 @@ namespace ThreadPilot protected override void OnDispose() { - // Unsubscribe from events - if (_gameBoostService != null) - { - _gameBoostService.GameBoostActivated -= OnGameBoostActivated; - _gameBoostService.GameBoostDeactivated -= OnGameBoostDeactivated; - } - if (_processMonitorManagerService != null) { _processMonitorManagerService.ServiceStatusChanged -= OnServiceStatusChanged; diff --git a/ViewModels/MasksViewModel.cs b/ViewModels/MasksViewModel.cs new file mode 100644 index 0000000..e41d785 --- /dev/null +++ b/ViewModels/MasksViewModel.cs @@ -0,0 +1,351 @@ +using System; +using System.Collections.ObjectModel; +using System.Linq; +using System.Threading.Tasks; +using CommunityToolkit.Mvvm.ComponentModel; +using CommunityToolkit.Mvvm.Input; +using Microsoft.Extensions.Logging; +using ThreadPilot.Models; +using ThreadPilot.Services; +using MessageBox = System.Windows.MessageBox; +using MessageBoxButton = System.Windows.MessageBoxButton; +using MessageBoxImage = System.Windows.MessageBoxImage; +using MessageBoxResult = System.Windows.MessageBoxResult; + +namespace ThreadPilot.ViewModels +{ + /// + /// Wrapper for individual core bit in the mask, similar to CPUSetSetter's MaskBitViewModel + /// + public partial class CoreBitViewModel : ObservableObject + { + private readonly ObservableCollection _boolMask; + private readonly int _index; + + public int Index => _index; + + public bool IsSelected + { + get => _index < _boolMask.Count && _boolMask[_index]; + set + { + if (_index < _boolMask.Count && _boolMask[_index] != value) + { + _boolMask[_index] = value; + OnPropertyChanged(); + } + } + } + + public CoreBitViewModel(ObservableCollection boolMask, int index) + { + _boolMask = boolMask; + _index = index; + } + } + + /// + /// ViewModel for managing CPU core affinity masks + /// Based on CPUSetSetter's MasksTabViewModel + /// + public partial class MasksViewModel : ObservableObject + { + private readonly ICoreMaskService _coreMaskService; + private readonly ICpuTopologyService _cpuTopologyService; + private readonly ILogger _logger; + + [ObservableProperty] + private ObservableCollection coreMasks = new(); + + [ObservableProperty] + [NotifyPropertyChangedFor(nameof(CanDeleteMask))] + [NotifyPropertyChangedFor(nameof(CanDuplicateMask))] + private CoreMask? selectedCoreMask; + + [ObservableProperty] + private string statusMessage = string.Empty; + + [ObservableProperty] + private ObservableCollection coreBits = new(); + + /// + /// Can delete if: mask selected, not "All Cores" baseline, not actively applied to processes + /// Note: The actual validation happens in DeleteMask command with proper async checks + /// + public bool CanDeleteMask => SelectedCoreMask != null && SelectedCoreMask.Name != "All Cores"; + public bool CanDuplicateMask => SelectedCoreMask != null; + + public MasksViewModel( + ICoreMaskService coreMaskService, + ICpuTopologyService cpuTopologyService, + ILogger logger) + { + _coreMaskService = coreMaskService ?? throw new ArgumentNullException(nameof(coreMaskService)); + _cpuTopologyService = cpuTopologyService ?? throw new ArgumentNullException(nameof(cpuTopologyService)); + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); + + // Initialize + _ = InitializeAsync(); + } + + private async Task InitializeAsync() + { + try + { + await _coreMaskService.InitializeAsync(); + + // Link to the service's collection + CoreMasks = _coreMaskService.AvailableMasks; + + // Select the default mask + SelectedCoreMask = _coreMaskService.DefaultMask; + + _logger.LogInformation("MasksViewModel initialized with {Count} masks", CoreMasks.Count); + } + catch (Exception ex) + { + _logger.LogError(ex, "Failed to initialize MasksViewModel"); + StatusMessage = $"Error initializing masks: {ex.Message}"; + } + } + + [RelayCommand] + private async Task CreateMask() + { + try + { + var coreCount = Environment.ProcessorCount; + var newMask = new CoreMask + { + Name = "New Mask", + Description = $"Created at {DateTime.Now:HH:mm:ss}" + }; + + // Initialize with all cores enabled + for (int i = 0; i < coreCount; i++) + newMask.BoolMask.Add(true); + + CoreMasks.Add(newMask); + SelectedCoreMask = newMask; + + await _coreMaskService.SaveMasksAsync(); + + StatusMessage = $"Created mask '{newMask.Name}'"; + _logger.LogInformation("Created new mask '{Name}'", newMask.Name); + } + catch (Exception ex) + { + _logger.LogError(ex, "Failed to create mask"); + StatusMessage = $"Error creating mask: {ex.Message}"; + MessageBox.Show($"Failed to create mask: {ex.Message}", "Error", + MessageBoxButton.OK, MessageBoxImage.Error); + } + } + + [RelayCommand(CanExecute = nameof(CanDeleteMask))] + private async Task DeleteMask() + { + if (SelectedCoreMask == null) + return; + + try + { + var maskId = SelectedCoreMask.Id; + var maskName = SelectedCoreMask.Name; + + // 1. Check if mask is the "All Cores" baseline (cannot be deleted) + if (maskName == "All Cores") + { + MessageBox.Show( + "The 'All Cores' mask is the baseline mask and cannot be deleted.\n\n" + + "This mask is required as the default fallback for all processes.", + "Cannot Delete Baseline Mask", + MessageBoxButton.OK, + MessageBoxImage.Warning); + return; + } + + // 2. Check if mask is actively applied to running processes + bool isActivelyApplied = await _coreMaskService.IsMaskActivelyAppliedAsync(maskId); + if (isActivelyApplied) + { + MessageBox.Show( + $"The mask '{maskName}' is currently applied to one or more running processes.\n\n" + + "You must change the mask on those processes before deleting this mask.\n\n" + + "Go to the Processes tab to change the affinity of the affected processes.", + "Mask In Use", + MessageBoxButton.OK, + MessageBoxImage.Warning); + return; + } + + // 3. Check if mask is referenced by profiles/rules (not actively applied) + var referencingProfiles = (await _coreMaskService.GetProfilesReferencingMaskAsync(maskId)).ToList(); + if (referencingProfiles.Any()) + { + var profileList = string.Join("\n - ", referencingProfiles.Take(10)); + if (referencingProfiles.Count > 10) + profileList += $"\n ... and {referencingProfiles.Count - 10} more"; + + var result = MessageBox.Show( + $"The mask '{maskName}' is referenced by the following profiles/rules:\n\n" + + $" - {profileList}\n\n" + + "If you delete this mask, these profiles will be updated to use the 'All Cores' mask instead.\n\n" + + "Do you want to continue?", + "Mask Referenced by Profiles", + MessageBoxButton.YesNo, + MessageBoxImage.Warning); + + if (result != MessageBoxResult.Yes) + return; + + // Update all referencing profiles to use "All Cores" + await _coreMaskService.UpdateProfilesToDefaultMaskAsync(maskId); + StatusMessage = $"Updated {referencingProfiles.Count} profile(s) to use 'All Cores' mask"; + } + else + { + // Simple confirmation + var result = MessageBox.Show( + $"Are you sure you want to delete the mask '{maskName}'?", + "Confirm Delete", + MessageBoxButton.YesNo, + MessageBoxImage.Question); + + if (result != MessageBoxResult.Yes) + return; + } + + // 4. Delete the mask + await _coreMaskService.DeleteMaskAsync(maskId); + SelectedCoreMask = CoreMasks.FirstOrDefault(); + + StatusMessage = $"Deleted mask '{maskName}'"; + _logger.LogInformation("Deleted mask '{Name}'", maskName); + } + catch (Exception ex) + { + _logger.LogError(ex, "Failed to delete mask"); + StatusMessage = $"Error deleting mask: {ex.Message}"; + MessageBox.Show($"Failed to delete mask: {ex.Message}", "Error", + MessageBoxButton.OK, MessageBoxImage.Error); + } + } + + [RelayCommand(CanExecute = nameof(CanDuplicateMask))] + private async Task DuplicateMask() + { + if (SelectedCoreMask == null) + return; + + try + { + var cloned = SelectedCoreMask.Clone(); + CoreMasks.Add(cloned); + SelectedCoreMask = cloned; + + await _coreMaskService.SaveMasksAsync(); + + StatusMessage = $"Duplicated mask '{cloned.Name}'"; + _logger.LogInformation("Duplicated mask to '{Name}'", cloned.Name); + } + catch (Exception ex) + { + _logger.LogError(ex, "Failed to duplicate mask"); + StatusMessage = $"Error duplicating mask: {ex.Message}"; + MessageBox.Show($"Failed to duplicate mask: {ex.Message}", "Error", + MessageBoxButton.OK, MessageBoxImage.Error); + } + } + + private async Task SaveCurrentMaskAsync() + { + if (SelectedCoreMask == null) + return; + + try + { + await _coreMaskService.UpdateMaskAsync(SelectedCoreMask); + _logger.LogDebug("Saved mask '{Name}'", SelectedCoreMask.Name); + } + catch (Exception ex) + { + _logger.LogError(ex, "Failed to save mask"); + } + } + + partial void OnSelectedCoreMaskChanged(CoreMask? oldValue, CoreMask? newValue) + { + // Unsubscribe from old mask + if (oldValue != null) + { + oldValue.PropertyChanged -= OnMaskPropertyChanged; + oldValue.BoolMask.CollectionChanged -= OnBoolMaskCollectionChanged; + } + + // Subscribe to new mask + if (newValue != null) + { + newValue.PropertyChanged += OnMaskPropertyChanged; + newValue.BoolMask.CollectionChanged += OnBoolMaskCollectionChanged; + + // Rebuild CoreBits collection to match CPUSetSetter pattern + RebuildCoreBits(); + } + else + { + CoreBits.Clear(); + } + + RefreshCommandStates(); + } + + private void RebuildCoreBits() + { + CoreBits.Clear(); + + if (SelectedCoreMask == null) + return; + + for (int i = 0; i < SelectedCoreMask.BoolMask.Count; i++) + { + CoreBits.Add(new CoreBitViewModel(SelectedCoreMask.BoolMask, i)); + } + } + + private async void OnBoolMaskCollectionChanged(object? sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e) + { + // Auto-save when BoolMask changes (like CPUSetSetter's auto-save pattern) + await SaveCurrentMaskAsync(); + + // Update status to show real-time changes + if (SelectedCoreMask != null) + { + StatusMessage = $"{SelectedCoreMask.SelectedCoreCount} of {SelectedCoreMask.BoolMask.Count} cores selected"; + } + } + + private async void OnMaskPropertyChanged(object? sender, System.ComponentModel.PropertyChangedEventArgs e) + { + if (e.PropertyName == nameof(CoreMask.Name) || + e.PropertyName == nameof(CoreMask.Description) || + e.PropertyName == nameof(CoreMask.IsDefault) || + e.PropertyName == nameof(CoreMask.IsEnabled)) + { + await SaveCurrentMaskAsync(); + } + + if (e.PropertyName == nameof(CoreMask.Name)) + { + // CanDeleteMask depends on the name (e.g., "All Cores") + RefreshCommandStates(); + } + } + + private void RefreshCommandStates() + { + DeleteMaskCommand.NotifyCanExecuteChanged(); + DuplicateMaskCommand.NotifyCanExecuteChanged(); + } + } +} diff --git a/ViewModels/ProcessPowerPlanAssociationViewModel.cs b/ViewModels/ProcessPowerPlanAssociationViewModel.cs index b7e7f9a..3df89b0 100644 --- a/ViewModels/ProcessPowerPlanAssociationViewModel.cs +++ b/ViewModels/ProcessPowerPlanAssociationViewModel.cs @@ -20,6 +20,7 @@ namespace ThreadPilot.ViewModels private readonly IPowerPlanService _powerPlanService; private readonly IProcessService _processService; private readonly IProcessMonitorManagerService _monitorManagerService; + private readonly ICoreMaskService _coreMaskService; [ObservableProperty] private ObservableCollection associations = new(); @@ -27,6 +28,20 @@ namespace ThreadPilot.ViewModels [ObservableProperty] private ObservableCollection availablePowerPlans = new(); + [ObservableProperty] + private ObservableCollection availableCoreMasks = new(); + + [ObservableProperty] + private ObservableCollection availablePriorities = new() + { + "Idle", + "BelowNormal", + "Normal", + "AboveNormal", + "High", + "RealTime" + }; + [ObservableProperty] private ObservableCollection runningProcesses = new(); @@ -36,6 +51,12 @@ namespace ThreadPilot.ViewModels [ObservableProperty] private PowerPlanModel? selectedPowerPlan; + [ObservableProperty] + private CoreMask? selectedCoreMask; + + [ObservableProperty] + private string? selectedProcessPriority; + [ObservableProperty] private ProcessModel? selectedProcess; @@ -97,6 +118,7 @@ namespace ThreadPilot.ViewModels IPowerPlanService powerPlanService, IProcessService processService, IProcessMonitorManagerService monitorManagerService, + ICoreMaskService coreMaskService, IEnhancedLoggingService? enhancedLoggingService = null) : base(logger, enhancedLoggingService) { @@ -104,6 +126,7 @@ namespace ThreadPilot.ViewModels _powerPlanService = powerPlanService ?? throw new ArgumentNullException(nameof(powerPlanService)); _processService = processService ?? throw new ArgumentNullException(nameof(processService)); _monitorManagerService = monitorManagerService ?? throw new ArgumentNullException(nameof(monitorManagerService)); + _coreMaskService = coreMaskService ?? throw new ArgumentNullException(nameof(coreMaskService)); // Subscribe to events _associationService.ConfigurationChanged += OnConfigurationChanged; @@ -135,6 +158,10 @@ namespace ThreadPilot.ViewModels var powerPlans = await _powerPlanService.GetPowerPlansAsync(); AvailablePowerPlans = powerPlans; + // Load core masks + await _coreMaskService.InitializeAsync(); + AvailableCoreMasks = _coreMaskService.AvailableMasks; + // Load running processes var processes = await _processService.GetProcessesAsync(); RunningProcesses = processes; @@ -178,6 +205,9 @@ namespace ThreadPilot.ViewModels ExecutablePath = NewExecutablePath.Trim(), PowerPlanGuid = SelectedPowerPlan.Guid, PowerPlanName = SelectedPowerPlan.Name, + CoreMaskId = SelectedCoreMask?.Id, + CoreMaskName = SelectedCoreMask?.Name, + ProcessPriority = SelectedProcessPriority, MatchByPath = MatchByPath, Priority = Priority, Description = Description.Trim(), @@ -191,6 +221,8 @@ namespace ThreadPilot.ViewModels NewExecutableName = string.Empty; NewExecutablePath = string.Empty; SelectedPowerPlan = null; + SelectedCoreMask = null; + SelectedProcessPriority = null; MatchByPath = false; Priority = 0; Description = string.Empty; diff --git a/ViewModels/ProcessViewModel.cs b/ViewModels/ProcessViewModel.cs index 9bb906b..f7eda31 100644 --- a/ViewModels/ProcessViewModel.cs +++ b/ViewModels/ProcessViewModel.cs @@ -1,5 +1,6 @@ using System; using System.Collections.ObjectModel; +using System.ComponentModel; using System.Diagnostics; using System.Linq; using System.Threading.Tasks; @@ -18,9 +19,15 @@ namespace ThreadPilot.ViewModels private readonly IVirtualizedProcessService _virtualizedProcessService; private readonly ICpuTopologyService _cpuTopologyService; private readonly IPowerPlanService _powerPlanService; + private readonly INotificationService _notificationService; private readonly ISystemTrayService _systemTrayService; + private readonly ICoreMaskService _coreMaskService; + private readonly IProcessPowerPlanAssociationService _associationService; + private readonly IGameModeService _gameModeService; private System.Timers.Timer? _refreshTimer; private System.Timers.Timer? _searchDebounceTimer; + private bool _suppressCoreSelectionEvents; + private bool _hasPendingAffinityEdits; [ObservableProperty] private ObservableCollection processes = new(); @@ -47,6 +54,13 @@ namespace ThreadPilot.ViewModels [ObservableProperty] private ObservableCollection affinityPresets = new(); + // Core Masks - Available masks from the service + [ObservableProperty] + private ObservableCollection availableCoreMasks = new(); + + [ObservableProperty] + private CoreMask? selectedCoreMask; + [ObservableProperty] private bool isTopologyDetectionSuccessful = false; @@ -113,13 +127,20 @@ namespace ThreadPilot.ViewModels [ObservableProperty] private bool isVirtualizationEnabled = true; + [ObservableProperty] + private bool isBusy = false; + public ProcessViewModel( ILogger logger, IProcessService processService, IVirtualizedProcessService virtualizedProcessService, ICpuTopologyService cpuTopologyService, IPowerPlanService powerPlanService, + INotificationService notificationService, ISystemTrayService systemTrayService, + ICoreMaskService coreMaskService, + IProcessPowerPlanAssociationService associationService, + IGameModeService gameModeService, IEnhancedLoggingService? enhancedLoggingService = null) : base(logger, enhancedLoggingService) { @@ -127,7 +148,11 @@ namespace ThreadPilot.ViewModels _virtualizedProcessService = virtualizedProcessService ?? throw new ArgumentNullException(nameof(virtualizedProcessService)); _cpuTopologyService = cpuTopologyService ?? throw new ArgumentNullException(nameof(cpuTopologyService)); _powerPlanService = powerPlanService ?? throw new ArgumentNullException(nameof(powerPlanService)); + _notificationService = notificationService ?? throw new ArgumentNullException(nameof(notificationService)); _systemTrayService = systemTrayService ?? throw new ArgumentNullException(nameof(systemTrayService)); + _coreMaskService = coreMaskService ?? throw new ArgumentNullException(nameof(coreMaskService)); + _associationService = associationService ?? throw new ArgumentNullException(nameof(associationService)); + _gameModeService = gameModeService ?? throw new ArgumentNullException(nameof(gameModeService)); // Subscribe to topology detection events _cpuTopologyService.TopologyDetected += OnTopologyDetected; @@ -186,9 +211,16 @@ namespace ThreadPilot.ViewModels await _cpuTopologyService.DetectTopologyAsync(); System.Diagnostics.Debug.WriteLine("ProcessViewModel.InitializeAsync: CPU topology detection completed"); + // Initialize core masks service + System.Diagnostics.Debug.WriteLine("ProcessViewModel.InitializeAsync: About to initialize core masks"); + await _coreMaskService.InitializeAsync(); + AvailableCoreMasks = _coreMaskService.AvailableMasks; + SelectedCoreMask = _coreMaskService.DefaultMask; + System.Diagnostics.Debug.WriteLine("ProcessViewModel.InitializeAsync: Core masks initialized"); + // Load power plans System.Diagnostics.Debug.WriteLine("ProcessViewModel.InitializeAsync: About to load power plans"); - await LoadPowerPlansAsync(); + await RefreshPowerPlansAsync(); System.Diagnostics.Debug.WriteLine("ProcessViewModel.InitializeAsync: Power plans loaded"); // Load processes automatically on startup (Bug #8 fix) @@ -219,29 +251,27 @@ namespace ThreadPilot.ViewModels } } - private async Task LoadPowerPlansAsync() + private async Task RefreshPowerPlansAsync() { try { var plans = await _powerPlanService.GetPowerPlansAsync(); var activePlan = await _powerPlanService.GetActivePowerPlan(); - // Update UI collections on the UI thread await System.Windows.Application.Current.Dispatcher.InvokeAsync(() => { PowerPlans.Clear(); foreach (var plan in plans) { + plan.IsActive = plan.Guid == activePlan?.Guid; PowerPlans.Add(plan); } - // Set current active power plan as selected SelectedPowerPlan = PowerPlans.FirstOrDefault(p => p.Guid == activePlan?.Guid); }); } catch (Exception ex) { - // Update status on UI thread await System.Windows.Application.Current.Dispatcher.InvokeAsync(() => { SetStatus($"Failed to load power plans: {ex.Message}", false); @@ -253,6 +283,7 @@ namespace ThreadPilot.ViewModels { if (value != null && CpuTopology != null) { + _hasPendingAffinityEdits = false; // Immediately fetch and display real-time process information _ = Task.Run(async () => { @@ -278,7 +309,23 @@ namespace ThreadPilot.ViewModels System.Windows.Application.Current.Dispatcher.Invoke(() => { // Update CPU affinity display - UpdateCoreSelections(value.ProcessorAffinity); + // If a Core Mask is selected, show that instead of the process's current affinity + // This ensures visual coherence between selected mask and Advanced CPU Affinity + if (SelectedCoreMask != null) + { + UpdateCoreSelectionsFromMask(SelectedCoreMask); + // Auto-apply the selected mask to the newly selected process + _ = ApplyCoreMaskToProcessAsync(SelectedCoreMask); + } + else + { + // No mask selected - show process's current affinity + UpdateCoreSelections(value.ProcessorAffinity); + + // Force ProcessorAffinity notification for DataGrid column + // Ensures Affinity column displays the correct current value immediately + value.ForceNotifyProcessorAffinityChanged(); + } // Update priority display - trigger property change to refresh ComboBox OnPropertyChanged(nameof(SelectedProcess)); @@ -382,10 +429,73 @@ namespace ThreadPilot.ViewModels CpuCores.Clear(); foreach (var core in CpuTopology.LogicalCores) { + core.PropertyChanged -= OnCorePropertyChanged; + core.PropertyChanged += OnCorePropertyChanged; CpuCores.Add(core); } } + private void OnCorePropertyChanged(object? sender, PropertyChangedEventArgs e) + { + // Note: Advanced CPU Affinity cores are now read-only (ProcessView.xaml has IsHitTestVisible="False") + // This event handler is kept for compatibility but should not be triggered + // Core modifications are done exclusively through the Core Mask tab + if (_suppressCoreSelectionEvents) return; + + Logger.LogDebug("Core property changed but cores are read-only - no action taken"); + } + + private async Task AutoApplyAffinityAsync() + { + if (SelectedProcess == null || !_hasPendingAffinityEdits) return; + + try + { + var affinityMask = CalculateAffinityMask(); + if (affinityMask == 0) + { + Logger.LogDebug("Affinity mask is zero, skipping auto-apply"); + return; + } + + Logger.LogInformation("Auto-applying affinity 0x{AffinityMask:X} to process {ProcessName} (PID: {ProcessId})", + affinityMask, SelectedProcess.Name, SelectedProcess.ProcessId); + + // Apply the affinity change + await _processService.SetProcessorAffinity(SelectedProcess, affinityMask); + + // Immediately refresh the process to get the actual system state + await _processService.RefreshProcessInfo(SelectedProcess); + + // Update UI to reflect the actual system affinity + UpdateCoreSelections(SelectedProcess.ProcessorAffinity, true); + + // Notify UI of all changes + OnPropertyChanged(nameof(SelectedProcess)); + + // Clear pending edits flag + _hasPendingAffinityEdits = false; + + Logger.LogInformation("Auto-applied affinity successfully to {ProcessName}", SelectedProcess.Name); + } + catch (Exception ex) + { + Logger.LogWarning(ex, "Failed to auto-apply affinity to {ProcessName}", SelectedProcess.Name); + + // Try to refresh process info even if setting failed, to show current state + try + { + await _processService.RefreshProcessInfo(SelectedProcess); + UpdateCoreSelections(SelectedProcess.ProcessorAffinity, true); + OnPropertyChanged(nameof(SelectedProcess)); + } + catch + { + // Process may have terminated + } + } + } + private void UpdateHyperThreadingStatus() { if (CpuTopology == null) @@ -428,7 +538,7 @@ namespace ThreadPilot.ViewModels } } - private void UpdateCoreSelections(long affinityMask) + private void UpdateCoreSelections(long affinityMask, bool forceSync = false) { if (CpuTopology == null || CpuCores.Count == 0) { @@ -437,23 +547,38 @@ namespace ThreadPilot.ViewModels return; } + if (_hasPendingAffinityEdits && !forceSync) + { + Logger.LogDebug("Skipping affinity sync because user edits are pending"); + return; + } + Logger.LogDebug("Updating core selections for affinity mask 0x{AffinityMask:X} ({AffinityMaskBinary})", affinityMask, Convert.ToString(affinityMask, 2).PadLeft(Environment.ProcessorCount, '0')); // Update each core's selection state based on the actual OS affinity mask var updatedCores = new List<(int CoreId, bool WasSelected, bool IsSelected)>(); - foreach (var core in CpuCores) + try { - bool wasSelected = core.IsSelected; - bool shouldBeSelected = (affinityMask & core.AffinityMask) != 0; + _suppressCoreSelectionEvents = true; - if (wasSelected != shouldBeSelected) + foreach (var core in CpuCores) { - core.IsSelected = shouldBeSelected; - updatedCores.Add((core.LogicalCoreId, wasSelected, shouldBeSelected)); + bool wasSelected = core.IsSelected; + bool shouldBeSelected = (affinityMask & core.AffinityMask) != 0; + + if (wasSelected != shouldBeSelected) + { + core.IsSelected = shouldBeSelected; + updatedCores.Add((core.LogicalCoreId, wasSelected, shouldBeSelected)); + } } } + finally + { + _suppressCoreSelectionEvents = false; + } // The UI will automatically update since CpuCoreModel now implements INotifyPropertyChanged // No need to force collection refresh as individual property changes will be notified @@ -476,6 +601,11 @@ namespace ThreadPilot.ViewModels { Logger.LogDebug("No core selection changes needed - UI already matches affinity mask"); } + + if (forceSync) + { + _hasPendingAffinityEdits = false; + } } private long CalculateAffinityMask() @@ -750,7 +880,7 @@ namespace ThreadPilot.ViewModels // This ensures we show what the OS actually set, which may differ from our request await System.Windows.Application.Current.Dispatcher.InvokeAsync(() => { - UpdateCoreSelections(SelectedProcess.ProcessorAffinity); + UpdateCoreSelections(SelectedProcess.ProcessorAffinity, true); // Notify UI of all changes OnPropertyChanged(nameof(SelectedProcess)); @@ -758,19 +888,37 @@ namespace ThreadPilot.ViewModels // Verify the affinity was set correctly if (SelectedProcess.ProcessorAffinity == affinityMask) { - SetStatus($"Affinity set successfully for {SelectedProcess.Name} (0x{affinityMask:X})"); + SetStatus($"Affinity set successfully for {SelectedProcess.Name} (0x{affinityMask:X})", false); + _ = _notificationService.ShowNotificationAsync("Affinity applied", $"{SelectedProcess.Name}: 0x{affinityMask:X}", NotificationType.Success); } else { SetStatus($"Affinity partially set for {SelectedProcess.Name} - OS adjusted to 0x{SelectedProcess.ProcessorAffinity:X}", false); + _ = _notificationService.ShowNotificationAsync("Affinity adjusted", $"{SelectedProcess.Name}: 0x{SelectedProcess.ProcessorAffinity:X}", NotificationType.Warning); } }); } catch (Exception ex) { + var friendly = ex.Message; + if (friendly.Contains("access denied", StringComparison.OrdinalIgnoreCase) || + friendly.Contains("anti-cheat", StringComparison.OrdinalIgnoreCase)) + { + friendly = "Affinity change blocked (anti-cheat or insufficient privileges)."; + _ = _notificationService.ShowNotificationAsync("Affinity blocked", friendly, NotificationType.Warning); + } + else if (friendly.Contains("invalid affinity", StringComparison.OrdinalIgnoreCase)) + { + _ = _notificationService.ShowNotificationAsync("Affinity invalid", friendly, NotificationType.Error); + } + else + { + _ = _notificationService.ShowNotificationAsync("Affinity error", friendly, NotificationType.Error); + } + await System.Windows.Application.Current.Dispatcher.InvokeAsync(() => { - SetStatus($"Error setting affinity: {ex.Message}", false); + SetStatus($"Error setting affinity: {friendly}", false); }); // Try to refresh process info even if setting failed, to show current state @@ -779,7 +927,7 @@ namespace ThreadPilot.ViewModels await _processService.RefreshProcessInfo(SelectedProcess); await System.Windows.Application.Current.Dispatcher.InvokeAsync(() => { - UpdateCoreSelections(SelectedProcess.ProcessorAffinity); + UpdateCoreSelections(SelectedProcess.ProcessorAffinity, true); OnPropertyChanged(nameof(SelectedProcess)); }); } @@ -788,6 +936,13 @@ namespace ThreadPilot.ViewModels // Process may have terminated } } + finally + { + await System.Windows.Application.Current.Dispatcher.InvokeAsync(() => + { + ClearStatus(); + }); + } } [RelayCommand] @@ -797,128 +952,178 @@ namespace ThreadPilot.ViewModels await System.Windows.Application.Current.Dispatcher.InvokeAsync(() => { - // Clear all selections first - foreach (var core in CpuCores) + try { - core.IsSelected = false; - } + _suppressCoreSelectionEvents = true; - // Apply preset mask - foreach (var core in CpuCores) - { - core.IsSelected = (preset.AffinityMask & core.AffinityMask) != 0; - } - - // Notify UI of changes - OnPropertyChanged(nameof(CpuCores)); - SetStatus($"Applied preset: {preset.Name}"); - }); - } - - [RelayCommand] - private async Task SelectAllCores() - { - await System.Windows.Application.Current.Dispatcher.InvokeAsync(() => - { - foreach (var core in CpuCores) - { - core.IsSelected = true; - } - OnPropertyChanged(nameof(CpuCores)); - SetStatus("Selected all CPU cores"); - }); - } - - [RelayCommand] - private async Task SelectPhysicalCoresOnly() - { - if (CpuTopology == null) return; - - await System.Windows.Application.Current.Dispatcher.InvokeAsync(() => - { - foreach (var core in CpuCores) - { - core.IsSelected = false; - } - - foreach (var physicalCore in CpuTopology.PhysicalCores) - { - var coreModel = CpuCores.FirstOrDefault(c => c.LogicalCoreId == physicalCore.LogicalCoreId); - if (coreModel != null) + // Clear all selections first + foreach (var core in CpuCores) { - coreModel.IsSelected = true; + core.IsSelected = false; + } + + // Apply preset mask + foreach (var core in CpuCores) + { + core.IsSelected = (preset.AffinityMask & core.AffinityMask) != 0; + } + + // Notify UI of changes + OnPropertyChanged(nameof(CpuCores)); + SetStatus($"Applied preset: {preset.Name}"); + } + finally + { + _suppressCoreSelectionEvents = false; + } + + // Trigger auto-apply with the preset mask + _hasPendingAffinityEdits = true; + + // Apply immediately for presets (no debounce needed) + _ = AutoApplyAffinityAsync(); + }); + } + + + [RelayCommand] + private void CreateCustomMask() + { + // Request to switch to Core Masks tab + System.Windows.Application.Current.Dispatcher.Invoke(() => + { + var mainWindow = System.Windows.Application.Current.MainWindow; + if (mainWindow != null) + { + // Find the TabControl in MainWindow + var tabControl = FindVisualChild(mainWindow); + if (tabControl != null) + { + // Switch to Core Masks tab (index 1) + tabControl.SelectedIndex = 1; } } - - OnPropertyChanged(nameof(CpuCores)); - SetStatus("Selected physical cores only (no HyperThreading)"); }); } - [RelayCommand] - private async Task SelectPerformanceCores() + private static T? FindVisualChild(System.Windows.DependencyObject obj) where T : System.Windows.DependencyObject { - if (CpuTopology == null || !CpuTopology.HasIntelHybrid) return; - - await System.Windows.Application.Current.Dispatcher.InvokeAsync(() => + for (int i = 0; i < System.Windows.Media.VisualTreeHelper.GetChildrenCount(obj); i++) { - foreach (var core in CpuCores) + var child = System.Windows.Media.VisualTreeHelper.GetChild(obj, i); + if (child is T typedChild) + return typedChild; + + var childOfChild = FindVisualChild(child); + if (childOfChild != null) + return childOfChild; + } + return null; + } + + /// + /// Called when a CoreMask is selected from the ComboBox - applies it immediately to the selected process + /// Based on CPUSetSetter's OnMaskChanged pattern + /// + partial void OnSelectedCoreMaskChanged(CoreMask? oldValue, CoreMask? newValue) + { + if (newValue == null) + return; + + // ALWAYS update Advanced CPU Affinity visual representation to match the selected mask + // This ensures UI coherence even when no process is selected + UpdateCoreSelectionsFromMask(newValue); + + // If a process is selected, apply the mask to it + if (SelectedProcess != null) + { + _ = ApplyCoreMaskToProcessAsync(newValue); + } + } + + private async Task ApplyCoreMaskToProcessAsync(CoreMask mask) + { + if (SelectedProcess == null || mask == null) + return; + + IsBusy = true; + try + { + Logger.LogInformation("Applying mask '{MaskName}' to process {ProcessName} (PID: {ProcessId})", + mask.Name, SelectedProcess.Name, SelectedProcess.ProcessId); + + // Convert mask to affinity + long affinity = mask.ToProcessorAffinity(); + + if (affinity == 0) { - core.IsSelected = core.CoreType == CpuCoreType.PerformanceCore; + Logger.LogWarning("Mask '{MaskName}' produces zero affinity, skipping", mask.Name); + SetStatus("Invalid mask: no cores selected"); + return; + } + + // Disable Windows Game Mode for better CPU affinity control + // Game Mode can interfere with CPU Sets, particularly on AMD systems + await _gameModeService.DisableGameModeForAffinityAsync(); + + // Apply affinity using ProcessService (which uses CPU Sets with fallback) + await _processService.SetProcessorAffinity(SelectedProcess, affinity); + + // Refresh process info to get actual system state + await _processService.RefreshProcessInfo(SelectedProcess); + + // CRITICAL: Force UI updates on UI thread + // RefreshProcessInfo runs on background thread, DataGrid won't receive PropertyChanged from non-UI threads + System.Windows.Application.Current.Dispatcher.Invoke(() => + { + // Force PropertyChanged notification for ProcessorAffinity property + // This ensures the DataGrid Affinity column binding updates immediately + SelectedProcess.ForceNotifyProcessorAffinityChanged(); + + // Update Advanced CPU Affinity checkboxes to reflect the mask + UpdateCoreSelectionsFromMask(mask); + + // Force complete refresh of SelectedProcess bindings in DataGrid + OnPropertyChanged(nameof(SelectedProcess)); + }); + + SetStatus($"Applied mask '{mask.Name}' to {SelectedProcess.Name}"); + Logger.LogInformation("Successfully applied mask '{MaskName}' to {ProcessName}", mask.Name, SelectedProcess.Name); + } + catch (Exception ex) + { + Logger.LogError(ex, "Failed to apply mask '{MaskName}' to process {ProcessName}", + mask.Name, SelectedProcess.Name); + SetStatus($"Error applying mask: {ex.Message}"); + } + finally + { + IsBusy = false; + } + } + + private void UpdateCoreSelectionsFromMask(CoreMask mask) + { + if (mask == null || CpuCores.Count == 0) + return; + + try + { + _suppressCoreSelectionEvents = true; + + for (int i = 0; i < CpuCores.Count && i < mask.BoolMask.Count; i++) + { + CpuCores[i].IsSelected = mask.BoolMask[i]; } OnPropertyChanged(nameof(CpuCores)); - SetStatus("Selected Intel Performance cores (P-cores)"); - }); - } - - [RelayCommand] - private async Task SelectEfficiencyCores() - { - if (CpuTopology == null || !CpuTopology.HasIntelHybrid) return; - - await System.Windows.Application.Current.Dispatcher.InvokeAsync(() => + } + finally { - foreach (var core in CpuCores) - { - core.IsSelected = core.CoreType == CpuCoreType.EfficiencyCore; - } - - OnPropertyChanged(nameof(CpuCores)); - SetStatus("Selected Intel Efficiency cores (E-cores)"); - }); + _suppressCoreSelectionEvents = false; + } } - [RelayCommand] - private async Task SelectCcdCores(int ccdId) - { - if (CpuTopology == null || !CpuTopology.HasAmdCcd) return; - - await System.Windows.Application.Current.Dispatcher.InvokeAsync(() => - { - foreach (var core in CpuCores) - { - core.IsSelected = core.CcdId == ccdId; - } - - OnPropertyChanged(nameof(CpuCores)); - SetStatus($"Selected AMD CCD {ccdId} cores"); - }); - } - - [RelayCommand] - private async Task ClearCoreSelection() - { - await System.Windows.Application.Current.Dispatcher.InvokeAsync(() => - { - foreach (var core in CpuCores) - { - core.IsSelected = false; - } - OnPropertyChanged(nameof(CpuCores)); - SetStatus("Cleared CPU core selection"); - }); - } [RelayCommand] private async Task QuickApplyAffinityAndPowerPlan() @@ -945,9 +1150,17 @@ namespace ThreadPilot.ViewModels await _powerPlanService.SetActivePowerPlan(SelectedPowerPlan); } + await _processService.RefreshProcessInfo(SelectedProcess); + await System.Windows.Application.Current.Dispatcher.InvokeAsync(() => { - SetStatus($"Settings applied successfully to {SelectedProcess.Name}"); + UpdateCoreSelections(SelectedProcess.ProcessorAffinity, true); + OnPropertyChanged(nameof(SelectedProcess)); + }); + + await System.Windows.Application.Current.Dispatcher.InvokeAsync(() => + { + SetStatus($"Settings applied successfully to {SelectedProcess.Name}", false); }); } catch (Exception ex) @@ -991,20 +1204,16 @@ namespace ThreadPilot.ViewModels SetStatus($"Setting power plan to {SelectedPowerPlan.Name}..."); }); - // Apply the power plan change - await _powerPlanService.SetActivePowerPlan(SelectedPowerPlan); + var success = await _powerPlanService.SetActivePowerPlan(SelectedPowerPlan); - // Verify the power plan was set by getting the current active plan - var activePlan = await _powerPlanService.GetActivePowerPlan(); + await RefreshPowerPlansAsync(); await System.Windows.Application.Current.Dispatcher.InvokeAsync(() => { - // Update UI to reflect the actual system state - SelectedPowerPlan = PowerPlans.FirstOrDefault(p => p.Guid == activePlan?.Guid) ?? SelectedPowerPlan; - - if (activePlan?.Guid == SelectedPowerPlan.Guid) + var activePlan = PowerPlans.FirstOrDefault(p => p.IsActive); + if (success && activePlan?.Guid == SelectedPowerPlan.Guid) { - SetStatus($"Power plan set successfully to {SelectedPowerPlan.Name}"); + SetStatus($"Power plan set successfully to {SelectedPowerPlan.Name}", false); } else { @@ -1019,20 +1228,19 @@ namespace ThreadPilot.ViewModels SetStatus($"Error setting power plan: {ex.Message}", false); }); - // Try to refresh the current power plan even if setting failed try { - var activePlan = await _powerPlanService.GetActivePowerPlan(); - await System.Windows.Application.Current.Dispatcher.InvokeAsync(() => - { - SelectedPowerPlan = PowerPlans.FirstOrDefault(p => p.Guid == activePlan?.Guid); - }); + await RefreshPowerPlansAsync(); } catch { - // Ignore refresh errors + // ignored } } + finally + { + await System.Windows.Application.Current.Dispatcher.InvokeAsync(ClearStatus); + } } [RelayCommand] @@ -1061,19 +1269,33 @@ namespace ThreadPilot.ViewModels // Verify the priority was set correctly if (SelectedProcess.Priority == priority) { - SetStatus($"Priority set successfully for {SelectedProcess.Name} to {priority}"); + SetStatus($"Priority set successfully for {SelectedProcess.Name} to {priority}", false); + _ = _notificationService.ShowNotificationAsync("Priority applied", $"{SelectedProcess.Name}: {priority}", NotificationType.Success); } else { SetStatus($"Priority set for {SelectedProcess.Name} - OS adjusted to {SelectedProcess.Priority}", false); + _ = _notificationService.ShowNotificationAsync("Priority adjusted", $"{SelectedProcess.Name}: {SelectedProcess.Priority}", NotificationType.Warning); } }); } catch (Exception ex) { + var message = ex.Message; + if (message.Contains("Access denied", StringComparison.OrdinalIgnoreCase) || + message.Contains("anti-cheat", StringComparison.OrdinalIgnoreCase)) + { + message = "Priority change blocked (anti-cheat or insufficient privileges)."; + _ = _notificationService.ShowNotificationAsync("Priority blocked", message, NotificationType.Warning); + } + else + { + _ = _notificationService.ShowNotificationAsync("Priority error", message, NotificationType.Error); + } + await System.Windows.Application.Current.Dispatcher.InvokeAsync(() => { - SetStatus($"Error setting priority: {ex.Message}", false); + SetStatus($"Error setting priority: {message}", false); }); // Try to refresh process info even if setting failed, to show current state @@ -1090,6 +1312,10 @@ namespace ThreadPilot.ViewModels // Process may have terminated } } + finally + { + await System.Windows.Application.Current.Dispatcher.InvokeAsync(ClearStatus); + } } [RelayCommand] @@ -1383,13 +1609,7 @@ namespace ThreadPilot.ViewModels { try { - // For now, just show the current active power plan - // In a full implementation, this could check for process-specific power plan associations - var activePlan = await _powerPlanService.GetActivePowerPlan(); - System.Windows.Application.Current.Dispatcher.Invoke(() => - { - SelectedPowerPlan = PowerPlans.FirstOrDefault(p => p.Guid == activePlan?.Guid); - }); + await RefreshPowerPlansAsync(); } catch (Exception ex) { @@ -1410,11 +1630,7 @@ namespace ThreadPilot.ViewModels { try { - var activePlan = await _powerPlanService.GetActivePowerPlan(); - System.Windows.Application.Current.Dispatcher.Invoke(() => - { - SelectedPowerPlan = PowerPlans.FirstOrDefault(p => p.Guid == activePlan?.Guid); - }); + await RefreshPowerPlansAsync(); } catch (Exception ex) { @@ -1546,5 +1762,72 @@ namespace ThreadPilot.ViewModels IsRegistryPriorityEnabled = !enable; } } + + /// + /// Saves the current process settings (affinity mask, priority, power plan) as an association + /// Based on CPUSetSetter's SetMask pattern + /// + [RelayCommand] + private async Task SaveCurrentAsAssociation() + { + if (SelectedProcess == null) + { + await _notificationService.ShowNotificationAsync("No Process Selected", + "Please select a process to save as an association", NotificationType.Warning); + return; + } + + try + { + SetStatus($"Saving association for {SelectedProcess.Name}..."); + + // Get current power plan + var currentPowerPlan = await _powerPlanService.GetActivePowerPlan(); + + // Create new association + var association = new ProcessPowerPlanAssociation + { + ExecutableName = SelectedProcess.Name, + ExecutablePath = SelectedProcess.ExecutablePath ?? string.Empty, + PowerPlanGuid = currentPowerPlan?.Guid ?? string.Empty, + PowerPlanName = currentPowerPlan?.Name ?? "Unknown", + CoreMaskId = SelectedCoreMask?.Id, + CoreMaskName = SelectedCoreMask?.Name, + ProcessPriority = SelectedProcess.Priority.ToString(), + MatchByPath = !string.IsNullOrEmpty(SelectedProcess.ExecutablePath), + Priority = 0, + Description = $"Saved from Process Management on {DateTime.Now:g}", + IsEnabled = true + }; + + // Try to add the association + var success = await _associationService.AddAssociationAsync(association); + + if (success) + { + SetStatus($"Association saved for {SelectedProcess.Name}", false); + await _notificationService.ShowNotificationAsync("Association Saved", + $"Settings for {SelectedProcess.Name} saved successfully", NotificationType.Success); + + await LogUserActionAsync("SaveAssociation", + $"Saved association for process {SelectedProcess.Name}", + $"PID: {SelectedProcess.ProcessId}, PowerPlan: {currentPowerPlan?.Name}, " + + $"CoreMask: {SelectedCoreMask?.Name ?? "None"}, Priority: {SelectedProcess.Priority}"); + } + else + { + SetStatus($"Association already exists for {SelectedProcess.Name}", false); + await _notificationService.ShowNotificationAsync("Association Exists", + $"An association for {SelectedProcess.Name} already exists", NotificationType.Warning); + } + } + catch (Exception ex) + { + Logger.LogError(ex, "Error saving association for process {ProcessName}", SelectedProcess.Name); + SetStatus($"Error saving association: {ex.Message}", false); + await _notificationService.ShowNotificationAsync("Error", + $"Failed to save association: {ex.Message}", NotificationType.Error); + } + } } } \ No newline at end of file diff --git a/ViewModels/SettingsViewModel.cs b/ViewModels/SettingsViewModel.cs index b76330b..19bcba1 100644 --- a/ViewModels/SettingsViewModel.cs +++ b/ViewModels/SettingsViewModel.cs @@ -19,8 +19,8 @@ namespace ThreadPilot.ViewModels private readonly INotificationService _notificationService; private readonly IAutostartService _autostartService; private readonly IPowerPlanService _powerPlanService; - private readonly IGameBoostService _gameBoostService; private readonly IProcessMonitorManagerService _processMonitorManagerService; + private bool _isSyncingFromService = false; [ObservableProperty] private ApplicationSettingsModel settings; @@ -37,23 +37,12 @@ namespace ThreadPilot.ViewModels [ObservableProperty] private ObservableCollection availablePowerPlans = new(); - [ObservableProperty] - private ObservableCollection knownGameExecutables = new(); - - [ObservableProperty] - private string newGameExecutableName = string.Empty; - - [ObservableProperty] - private string? selectedKnownGame; - public ICommand SaveSettingsCommand { get; } public ICommand ResetToDefaultsCommand { get; } public ICommand ExportSettingsCommand { get; } public ICommand ImportSettingsCommand { get; } public ICommand TestNotificationCommand { get; } public ICommand RefreshPowerPlansCommand { get; } - public ICommand AddKnownGameCommand { get; } - public ICommand RemoveKnownGameCommand { get; } public SettingsViewModel( ILogger logger, @@ -61,7 +50,6 @@ namespace ThreadPilot.ViewModels INotificationService notificationService, IAutostartService autostartService, IPowerPlanService powerPlanService, - IGameBoostService gameBoostService, IProcessMonitorManagerService processMonitorManagerService, IEnhancedLoggingService? enhancedLoggingService = null) : base(logger, enhancedLoggingService) @@ -70,7 +58,6 @@ namespace ThreadPilot.ViewModels _notificationService = notificationService ?? throw new ArgumentNullException(nameof(notificationService)); _autostartService = autostartService ?? throw new ArgumentNullException(nameof(autostartService)); _powerPlanService = powerPlanService ?? throw new ArgumentNullException(nameof(powerPlanService)); - _gameBoostService = gameBoostService ?? throw new ArgumentNullException(nameof(gameBoostService)); _processMonitorManagerService = processMonitorManagerService ?? throw new ArgumentNullException(nameof(processMonitorManagerService)); // Initialize with current settings @@ -83,38 +70,33 @@ namespace ThreadPilot.ViewModels ImportSettingsCommand = new AsyncRelayCommand(ImportSettingsAsync); TestNotificationCommand = new AsyncRelayCommand(TestNotificationAsync); RefreshPowerPlansCommand = new AsyncRelayCommand(RefreshPowerPlansAsync); - AddKnownGameCommand = new AsyncRelayCommand(AddKnownGameAsync, CanAddKnownGame); - RemoveKnownGameCommand = new AsyncRelayCommand(RemoveKnownGameAsync, CanRemoveKnownGame); // Subscribe to property changes to track unsaved changes Settings.PropertyChanged += OnSettingsPropertyChanged; - PropertyChanged += OnViewModelPropertyChanged; + + // Keep viewmodel in sync with persisted settings + _settingsService.SettingsChanged += OnSettingsServiceSettingsChanged; + + // Ensure we load the latest persisted settings on startup + _ = System.Windows.Application.Current.Dispatcher.InvokeAsync(async () => await RefreshSettingsAsync()); // Initialize data - marshal to UI thread to prevent cross-thread access exceptions _ = System.Windows.Application.Current.Dispatcher.InvokeAsync(async () => await RefreshPowerPlansAsync()); - _ = System.Windows.Application.Current.Dispatcher.InvokeAsync(async () => await LoadKnownGamesAsync()); Logger.LogInformation("Settings ViewModel initialized"); } private void OnSettingsPropertyChanged(object? sender, System.ComponentModel.PropertyChangedEventArgs e) { + if (_isSyncingFromService) + { + return; + } + HasUnsavedChanges = true; StatusMessage = "Settings have been modified"; } - private void OnViewModelPropertyChanged(object? sender, System.ComponentModel.PropertyChangedEventArgs e) - { - if (e.PropertyName == nameof(NewGameExecutableName)) - { - ((AsyncRelayCommand)AddKnownGameCommand).NotifyCanExecuteChanged(); - } - else if (e.PropertyName == nameof(SelectedKnownGame)) - { - ((AsyncRelayCommand)RemoveKnownGameCommand).NotifyCanExecuteChanged(); - } - } - private async Task SaveSettingsAsync() { try @@ -283,7 +265,9 @@ namespace ThreadPilot.ViewModels StatusMessage = "Loading settings..."; await _settingsService.LoadSettingsAsync(); + _isSyncingFromService = true; Settings.CopyFrom(_settingsService.Settings); + _isSyncingFromService = false; HasUnsavedChanges = false; StatusMessage = "Settings loaded"; @@ -297,6 +281,7 @@ namespace ThreadPilot.ViewModels } finally { + _isSyncingFromService = false; IsLoading = false; } } @@ -309,6 +294,25 @@ namespace ThreadPilot.ViewModels return !HasUnsavedChanges; } + private void OnSettingsServiceSettingsChanged(object? sender, ApplicationSettingsChangedEventArgs e) + { + // Marshal to UI thread to avoid cross-thread property change issues + System.Windows.Application.Current.Dispatcher.InvokeAsync(() => + { + _isSyncingFromService = true; + try + { + Settings.CopyFrom(e.NewSettings); + HasUnsavedChanges = false; + StatusMessage = "Settings synchronized"; + } + finally + { + _isSyncingFromService = false; + } + }); + } + private async Task RefreshPowerPlansAsync() { try @@ -328,104 +332,5 @@ namespace ThreadPilot.ViewModels Logger.LogError(ex, "Failed to refresh power plans"); } } - - /// - /// Loads known games from the GameBoostService - /// - private async Task LoadKnownGamesAsync() - { - try - { - var knownGames = _gameBoostService.GetKnownGameExecutables(); - KnownGameExecutables.Clear(); - foreach (var game in knownGames) - { - KnownGameExecutables.Add(game); - } - Logger.LogDebug("Loaded {Count} known games", KnownGameExecutables.Count); - } - catch (Exception ex) - { - Logger.LogError(ex, "Error loading known games"); - } - } - - /// - /// Adds a new known game executable - /// - private async Task AddKnownGameAsync() - { - try - { - if (string.IsNullOrWhiteSpace(NewGameExecutableName)) - return; - - var success = await _gameBoostService.AddKnownGameAsync(NewGameExecutableName); - if (success) - { - await LoadKnownGamesAsync(); - var gameName = NewGameExecutableName; - NewGameExecutableName = string.Empty; - StatusMessage = $"Added game: {gameName}"; - Logger.LogInformation("Added known game: {GameName}", gameName); - } - else - { - StatusMessage = "Game already exists or invalid name"; - } - } - catch (Exception ex) - { - StatusMessage = $"Error adding game: {ex.Message}"; - Logger.LogError(ex, "Error adding known game: {GameName}", NewGameExecutableName); - } - } - - /// - /// Removes the selected known game executable - /// - private async Task RemoveKnownGameAsync() - { - try - { - if (string.IsNullOrWhiteSpace(SelectedKnownGame)) - return; - - var gameName = SelectedKnownGame; - var success = await _gameBoostService.RemoveKnownGameAsync(gameName); - if (success) - { - await LoadKnownGamesAsync(); - SelectedKnownGame = null; - StatusMessage = $"Removed game: {gameName}"; - Logger.LogInformation("Removed known game: {GameName}", gameName); - } - else - { - StatusMessage = "Game not found"; - } - } - catch (Exception ex) - { - StatusMessage = $"Error removing game: {ex.Message}"; - Logger.LogError(ex, "Error removing known game: {GameName}", SelectedKnownGame); - } - } - - /// - /// Determines if a new game can be added - /// - private bool CanAddKnownGame() - { - return !string.IsNullOrWhiteSpace(NewGameExecutableName); - } - - /// - /// Determines if the selected game can be removed - /// - private bool CanRemoveKnownGame() - { - return !string.IsNullOrWhiteSpace(SelectedKnownGame); - } } } diff --git a/Views/MasksView.xaml b/Views/MasksView.xaml new file mode 100644 index 0000000..1e58b9d --- /dev/null +++ b/Views/MasksView.xaml @@ -0,0 +1,187 @@ + + + + + + + + + + + + + + + + + + + +