diff --git a/.gitignore b/.gitignore index 7bb0ee8..e3733b6 100644 --- a/.gitignore +++ b/.gitignore @@ -1,50 +1,8 @@ -# Escludi tutti gli .exe -*.exe - -.claude/ -Installer/Output/ - -# Escludi la sorgente CPUSetSetter upstream -/CPUSetSetter-main/ - -# Escludi Markdown tranne il README principale -*.md -!README.md -!LICENSE.md - -# Escludi directory di build comuni -/bin/ -/obj/ -/publish/ -/publish_*/ - -# .NET Core / .NET 5+ specifici -*.deps.json -*.runtimeconfig.json -*.dll.config -project.lock.json -project.fragment.lock.json -artifacts/ - -# Visual Studio specifici -.vs/ -*.user -*.suo -*.userosscache -*.sln.docstates -*.vcxproj.filters -*.vcxproj.user - -# Rider / JetBrains -.idea/ -*.sln.iml - -# Resharper -_ReSharper*/ -*.[Rr]e[Ss]harper -*.DotSettings.user - -# Build results +# Build outputs +bin/ +obj/ +publish/ +publish_*/ [Dd]ebug/ [Dd]ebugPublic/ [Rr]elease/ @@ -55,28 +13,26 @@ x86/ [Aa][Rr][Mm]/ [Aa][Rr][Mm]64/ bld/ -[Bb]in/ -[Oo]bj/ -[Ll]og/ -[Ll]ogs/ +artifacts/ -# MSTest test Results +# Test and coverage [Tt]est[Rr]esult*/ [Bb]uild[Ll]og.* - -# NUnit *.VisualState.xml TestResult.xml nunit-*.xml - -# Coverage reports coverage*.json coverage*.xml coverage*.info *.coverage *.coveragexml -# NuGet +# .NET / NuGet +*.deps.json +*.runtimeconfig.json +*.dll.config +project.lock.json +project.fragment.lock.json *.nupkg *.snupkg .nuget/ @@ -84,187 +40,94 @@ packages/ !packages/build/ !packages/repositories.config -# Package manager files -paket-files/ -.paket/paket.exe -.fake/ - -# Windows specifici -Thumbs.db -ehthumbs.db -Desktop.ini -$RECYCLE.BIN/ -*.cab -*.msi -*.msix -*.msm -*.msp -*.lnk - -# Temporary files -*.tmp -*.temp -*~ -*.swp -*.swo - -# Log files -*.log -logs/ -Logs/ - -# Configuration files con dati sensibili -appsettings.local.json -appsettings.*.local.json -secrets.json -*.secrets.json - -# ThreadPilot specifici -# Dati utente e configurazioni locali -/Configuration/UserSettings.json -/Configuration/ProcessProfiles.json -/Data/ -/AppData/ -%AppData%/ThreadPilot/ - -# File di backup automatici -*.bak -*.backup -*_backup.* -*_old.* - -# Crash dumps e diagnostici -*.dmp -*.mdmp -crashdumps/ - -# Performance profiling -*.psess -*.vsp -*.vspx -*.sap - -# Installer files -*.msi -*.cab -*.msm -*.msp -*.exe.config - -# ClickOnce directory -publish/ - -# Publish Web Output -*.[Pp]ublish.xml -*.azurePubxml -*.pubxml -*.publishproj - -# Microsoft Azure Web App publish settings -PublishScripts/ - -# Node.js (se usato per build tools) -node_modules/ -npm-debug.log* -yarn-debug.log* -yarn-error.log* - -# Python (se usato per script di build) -__pycache__/ -*.py[cod] -*$py.class - -# macOS (per sviluppatori cross-platform) -.DS_Store -.AppleDouble -.LSOverride - -# Linux -*~ -.fuse_hidden* -.directory -.Trash-* - -# Backup files da editor -*.orig -*.rej - -# JetBrains Rider +# IDEs +.vs/ +*.user +*.suo +*.userosscache +*.sln.docstates +*.vcxproj.filters +*.vcxproj.user .idea/ *.sln.iml - -# CodeRush personal settings -.cr/personal - -# Python Tools for Visual Studio (PTVS) -__pycache__/ -*.pyc - -# Cake - Uncomment if you are using it -# tools/** -# !tools/packages.config - -# Tabs Studio -*.tss - -# Telerik's JustMock configuration file -*.jmconfig - -# BizTalk build output -*.btp.cs -*.btm.cs -*.odx.cs -*.xsd.cs - -# OpenCover UI analysis results -OpenCover/ - -# Azure Stream Analytics local run output -ASALocalRun/ - -# MSBuild Binary and Structured Log -*.binlog - -# NVidia Nsight GPU debugger configuration file -*.nvuser - -# MFractors (Xamarin productivity tool) working folder -.mfractor/ - -# Local History for Visual Studio -.localhistory/ - -# BeatPulse healthcheck temp database -healthchecksdb - -# Backup folder for Package Reference Convert tool in Visual Studio 2017 -MigrationBackup/ - -# Ionide (cross platform F# VS Code tools) working folder -.ionide/ - -# Fody - auto-generated XML schema -FodyWeavers.xsd - -# VS Code +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user .vscode/ !.vscode/settings.json !.vscode/tasks.json !.vscode/launch.json !.vscode/extensions.json *.code-workspace - -# Local History for Visual Studio Code .history/ +.localhistory/ -# Windows Installer files from build outputs +# OS / temp / logs +Thumbs.db +ehthumbs.db +Desktop.ini +$RECYCLE.BIN/ +*.tmp +*.temp +*~ +*.swp +*.swo +*.log +logs/ +Logs/ +.DS_Store +.fuse_hidden* +.directory +.Trash-* + +# Installer / packaging artifacts +Installer/Output/ +*.cab *.msi +*.msix *.msm *.msp +*.lnk +*.exe.config +*.[Pp]ublish.xml +*.azurePubxml +*.pubxml +*.publishproj +PublishScripts/ -# JetBrains Rider -*.sln.iml +# Local app data / secrets +appsettings.local.json +appsettings.*.local.json +secrets.json +*.secrets.json +/Configuration/UserSettings.json +/Configuration/ProcessProfiles.json +/Data/ +/AppData/ +%AppData%/ThreadPilot/ -# Continue.dev (AI coding assistant) -.continue/nul -nul \ No newline at end of file +# Project-specific extras +.claude/ +.continue/ +/CPUSetSetter-main/ +*.bak +*.backup +*_backup.* +*_old.* +*.orig +*.rej +*.dmp +*.mdmp +crashdumps/ +*.binlog +nul + +ADVANCED_CPU_FEATURES.md +API_REFERENCE.md +ARCHITECTURE_GUIDE.md +CLAUDE.md +DEVELOPER_GUIDE.md +GAME_BOOST_VALIDATION.md +PROJECT_STRUCTURE.md +TRADEMARK.md +UI_STYLE_GUIDE.md diff --git a/App.xaml b/App.xaml index 99952d1..1eb8cbc 100644 --- a/App.xaml +++ b/App.xaml @@ -6,6 +6,9 @@ xmlns:converters="clr-namespace:ThreadPilot.Converters"> + + + @@ -14,6 +17,7 @@ + diff --git a/App.xaml.cs b/App.xaml.cs index 7f957c9..563ab20 100644 --- a/App.xaml.cs +++ b/App.xaml.cs @@ -23,6 +23,9 @@ using System.Windows; using System.Windows.Threading; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; +#if DEBUG +using ThreadPilot.Tests; +#endif using ThreadPilot.Services; using ThreadPilot.ViewModels; @@ -91,15 +94,19 @@ namespace ThreadPilot // Parse command line arguments bool startMinimized = false; bool isAutostart = false; +#if DEBUG bool isTestMode = false; +#endif foreach (var arg in e.Args) { switch (arg.ToLowerInvariant()) { +#if DEBUG case "--test": isTestMode = true; break; +#endif case "--start-minimized": startMinimized = true; break; @@ -114,6 +121,7 @@ namespace ThreadPilot } // Check for test mode +#if DEBUG if (isTestMode) { // Run in console test mode @@ -125,6 +133,7 @@ namespace ThreadPilot }); return; } +#endif var mainWindow = ServiceProvider.GetRequiredService(); @@ -186,8 +195,10 @@ namespace ThreadPilot base.OnExit(e); } +#if DEBUG [System.Runtime.InteropServices.DllImport("kernel32.dll")] private static extern bool AllocConsole(); +#endif /// /// Shows a message to the user about elevation requirements diff --git a/Converters/NullToBoolConverter.cs b/Converters/NullToBoolConverter.cs new file mode 100644 index 0000000..09d5f33 --- /dev/null +++ b/Converters/NullToBoolConverter.cs @@ -0,0 +1,35 @@ +/* + * ThreadPilot - Advanced Windows Process and Power Plan Manager + * Copyright (C) 2025 Prime Build + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, version 3 only. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +using System; +using System.Globalization; +using System.Windows.Data; + +namespace ThreadPilot.Converters +{ + public class NullToBoolConverter : IValueConverter + { + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) + { + return value != null; + } + + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + { + throw new NotImplementedException(); + } + } +} diff --git a/MainWindow.xaml b/MainWindow.xaml index 4d99d41..0378015 100644 --- a/MainWindow.xaml +++ b/MainWindow.xaml @@ -13,6 +13,23 @@ WindowStartupLocation="CenterScreen"> + + + + + + - + @@ -44,7 +61,7 @@ - @@ -66,23 +83,32 @@ - - + + - + - - + + - + - + + + + - + + + + + + + @@ -109,11 +135,11 @@ - @@ -161,7 +187,7 @@ diff --git a/MainWindow.xaml.cs b/MainWindow.xaml.cs index 45afb00..e62b8a8 100644 --- a/MainWindow.xaml.cs +++ b/MainWindow.xaml.cs @@ -28,7 +28,6 @@ using System.Windows.Media.Imaging; using ThreadPilot.ViewModels; using ThreadPilot.Services; using ThreadPilot.Views; -using ThreadPilot.Tests; using Microsoft.Extensions.DependencyInjection; namespace ThreadPilot @@ -37,17 +36,20 @@ namespace ThreadPilot { private readonly ProcessViewModel _processViewModel; private readonly PowerPlanViewModel _powerPlanViewModel; + private readonly PerformanceViewModel _performanceViewModel; private readonly ProcessPowerPlanAssociationViewModel _associationViewModel; private readonly ISystemTrayService _systemTrayService; private readonly IApplicationSettingsService _settingsService; private readonly INotificationService _notificationService; private readonly IProcessMonitorService _processMonitorService; private readonly IProcessMonitorManagerService _processMonitorManagerService; + private readonly IProcessPowerPlanAssociationService _processPowerPlanAssociationService; private readonly SettingsViewModel _settingsViewModel; private readonly MainWindowViewModel _mainWindowViewModel; private readonly SystemTweaksViewModel _systemTweaksViewModel; private readonly IKeyboardShortcutService _keyboardShortcutService; private readonly IServiceProvider _serviceProvider; + private readonly IThemeService _themeService; private System.Timers.Timer? _systemTrayUpdateTimer; private readonly IElevationService _elevationService; private readonly ISecurityService _securityService; @@ -61,20 +63,26 @@ namespace ThreadPilot // Flag to skip process monitoring during startup if it causes issues private readonly bool _skipProcessMonitoringDuringStartup = false; + private bool _isPerformingShutdown = false; + private int _currentTabIndex = -1; + private bool _isHandlingTabSelection; public MainWindow( ProcessViewModel processViewModel, PowerPlanViewModel powerPlanViewModel, + PerformanceViewModel performanceViewModel, ProcessPowerPlanAssociationViewModel associationViewModel, ISystemTrayService systemTrayService, IApplicationSettingsService settingsService, INotificationService notificationService, IProcessMonitorService processMonitorService, IProcessMonitorManagerService processMonitorManagerService, + IProcessPowerPlanAssociationService processPowerPlanAssociationService, SettingsViewModel settingsViewModel, MainWindowViewModel mainWindowViewModel, SystemTweaksViewModel systemTweaksViewModel, IKeyboardShortcutService keyboardShortcutService, + IThemeService themeService, IServiceProvider serviceProvider, IElevationService elevationService, ISecurityService securityService) @@ -93,20 +101,25 @@ namespace ThreadPilot _processViewModel = processViewModel; _powerPlanViewModel = powerPlanViewModel; + _performanceViewModel = performanceViewModel; _associationViewModel = associationViewModel; _systemTrayService = systemTrayService; _settingsService = settingsService; _notificationService = notificationService; _processMonitorService = processMonitorService; _processMonitorManagerService = processMonitorManagerService; + _processPowerPlanAssociationService = processPowerPlanAssociationService; _settingsViewModel = settingsViewModel; _mainWindowViewModel = mainWindowViewModel; _systemTweaksViewModel = systemTweaksViewModel; _keyboardShortcutService = keyboardShortcutService; + _themeService = themeService; _serviceProvider = serviceProvider; _elevationService = elevationService; _securityService = securityService; + _processViewModel.OpenRulesRequested += OnOpenRulesRequested; + System.Diagnostics.Debug.WriteLine("Dependencies assigned"); SetDataContexts(); @@ -116,6 +129,8 @@ namespace ThreadPilot _ = Dispatcher.InvokeAsync(async () => await InitializeApplicationAsync()); System.Diagnostics.Debug.WriteLine("Async initialization started"); System.Diagnostics.Debug.WriteLine("MainWindow constructor completed successfully"); + + _currentTabIndex = MainTabControl.SelectedIndex; } catch (Exception ex) { @@ -131,9 +146,15 @@ namespace ThreadPilot // Set DataContext for the main window DataContext = _mainWindowViewModel; + // Set DataContext for the power plans view + PowerPlanViewControl.DataContext = _powerPlanViewModel; + // Set DataContext for the association view AssociationView.DataContext = _associationViewModel; + // Set DataContext for the performance view + PerformanceViewControl.DataContext = _performanceViewModel; + // Set DataContext for the system tweaks view SystemTweaksView.DataContext = _systemTweaksViewModel; @@ -189,6 +210,11 @@ namespace ThreadPilot LogDebug("LoadViewModelsAsync completed successfully"); CompleteInitializationTask("ViewModels"); + LogDebug("About to initialize MainWindowViewModel..."); + await _mainWindowViewModel.InitializeAsync(); + LogDebug("MainWindowViewModel initialized successfully"); + CompleteInitializationTask("MainWindowViewModel"); + await Dispatcher.InvokeAsync(() => UpdateLoadingStatus("Initializing services...")); LogDebug("About to call InitializeServicesAsync..."); await InitializeServicesAsync(); @@ -403,6 +429,16 @@ namespace ThreadPilot await powerPlanTask; // Ensure we get any exceptions LogDebug("PowerPlanViewModel loaded successfully"); + LogDebug("About to initialize PerformanceViewModel..."); + var performanceTask = _performanceViewModel.InitializeAsync(); + var performanceResult = await Task.WhenAny(performanceTask, Task.Delay(5000)); + if (performanceResult != performanceTask) + { + throw new TimeoutException("PerformanceViewModel.InitializeAsync() timed out after 5 seconds"); + } + await performanceTask; // Ensure we get any exceptions + LogDebug("PerformanceViewModel initialized successfully"); + LogDebug("About to load SystemTweaksViewModel..."); var systemTweaksTask = _systemTweaksViewModel.LoadCommand.ExecuteAsync(null); var systemTweaksResult = await Task.WhenAny(systemTweaksTask, Task.Delay(5000)); // 5 second timeout @@ -414,7 +450,7 @@ namespace ThreadPilot LogDebug("SystemTweaksViewModel loaded successfully"); // Initialize keyboard shortcuts after window is loaded - this.Loaded += async (s, e) => await InitializeKeyboardShortcutsAsync(); + Loaded += OnWindowLoaded; LogDebug("Keyboard shortcuts event handler attached"); // The association view model loads its data automatically in its constructor @@ -523,6 +559,7 @@ namespace ThreadPilot // Apply initial settings var settings = _settingsService.Settings; + _themeService.ApplyTheme(settings.UseDarkTheme); if (settings.StartMinimized) { WindowState = WindowState.Minimized; @@ -542,7 +579,9 @@ namespace ThreadPilot _systemTrayService.Show(); // Subscribe to tray events + UnsubscribeSystemTrayEvents(); _systemTrayService.ShowMainWindowRequested += OnShowMainWindowRequested; + _systemTrayService.DashboardRequested += OnDashboardRequested; _systemTrayService.ExitRequested += OnExitRequested; _systemTrayService.MonitoringToggleRequested += OnMonitoringToggleRequested; _systemTrayService.SettingsRequested += OnSettingsRequested; @@ -578,7 +617,9 @@ namespace ThreadPilot _systemTrayService.Show(); // Subscribe to essential tray events only + UnsubscribeSystemTrayEvents(); _systemTrayService.ShowMainWindowRequested += OnShowMainWindowRequested; + _systemTrayService.DashboardRequested += OnDashboardRequested; _systemTrayService.ExitRequested += OnExitRequested; // Update basic settings and tooltip @@ -606,12 +647,32 @@ namespace ThreadPilot await PerformGracefulShutdownAsync(); } + private void OnDashboardRequested(object? sender, EventArgs e) + { + Show(); + WindowState = WindowState.Normal; + Activate(); + SelectMainTab(ProcessManagementTab); + } + /// /// Performs graceful shutdown with cleanup of all applied optimizations /// Similar to CPU Set Setter's ExitAppGracefully /// - private async Task PerformGracefulShutdownAsync() + private async Task PerformGracefulShutdownAsync(bool validateUnsavedChanges = true) { + if (_isPerformingShutdown) + { + return; + } + + if (validateUnsavedChanges && !await HandleUnsavedSettingsBeforeExitAsync()) + { + return; + } + + _isPerformingShutdown = true; + try { LogDebug("Starting graceful shutdown..."); @@ -658,15 +719,37 @@ namespace ThreadPilot } // 3. Restore default power plan if configured - if (_settingsService.Settings.RestoreDefaultPowerPlanOnExit && - !string.IsNullOrEmpty(_settingsService.Settings.DefaultPowerPlanId)) + if (_settingsService.Settings.RestoreDefaultPowerPlanOnExit) { try { + var targetDefaultPowerPlanGuid = _settingsService.Settings.DefaultPowerPlanId; + + try + { + await _processPowerPlanAssociationService.LoadConfigurationAsync(); + var (associationDefaultPowerPlanGuid, _) = await _processPowerPlanAssociationService.GetDefaultPowerPlanAsync(); + if (!string.IsNullOrWhiteSpace(associationDefaultPowerPlanGuid)) + { + targetDefaultPowerPlanGuid = associationDefaultPowerPlanGuid; + } + } + catch (Exception associationEx) + { + LogDebug($"Could not read default power plan from association config: {associationEx.Message}"); + } + + if (string.IsNullOrWhiteSpace(targetDefaultPowerPlanGuid)) + { + LogDebug("No default power plan configured for restore on exit"); + } + else + { LogDebug("Restoring default power plan..."); var powerPlanService = _serviceProvider.GetRequiredService(); - await powerPlanService.SetActivePowerPlanByGuidAsync(_settingsService.Settings.DefaultPowerPlanId); + await powerPlanService.SetActivePowerPlanByGuidAsync(targetDefaultPowerPlanGuid); LogDebug("Default power plan restored"); + } } catch (Exception ex) { @@ -711,6 +794,50 @@ namespace ThreadPilot } } + private async Task HandleUnsavedSettingsBeforeExitAsync() + { + if (!_settingsViewModel.HasPendingChanges) + { + return true; + } + + var result = System.Windows.MessageBox.Show( + "You have unsaved changes in Settings.\n\nChoose an action:\n- Yes: Save and exit\n- No: Discard and exit\n- Cancel: Return to app", + "Unsaved Settings", + MessageBoxButton.YesNoCancel, + MessageBoxImage.Warning); + + if (result == MessageBoxResult.Cancel) + { + return false; + } + + if (result == MessageBoxResult.Yes) + { + var saved = await _settingsViewModel.SaveIfDirtyAsync(); + return saved; + } + + await _settingsViewModel.DiscardPendingChangesAsync(); + return true; + } + + private async Task HandleWindowCloseAsync() + { + if (!await HandleUnsavedSettingsBeforeExitAsync()) + { + return; + } + + if (_settingsService.Settings.CloseToTray) + { + WindowState = WindowState.Minimized; + return; + } + + await PerformGracefulShutdownAsync(validateUnsavedChanges: false); + } + private async void OnMonitoringToggleRequested(object? sender, MonitoringToggleEventArgs e) { try @@ -822,16 +949,7 @@ namespace ThreadPilot WindowState = WindowState.Normal; Activate(); - // Switch to Tweaks tab - var tabControl = FindName("MainTabControl") as System.Windows.Controls.TabControl; - if (tabControl != null) - { - // Find the Tweaks tab (index 3 based on MainWindow.xaml) - if (tabControl.Items.Count > 3) - { - tabControl.SelectedIndex = 3; - } - } + SelectMainTab(PerformanceTab); } catch (Exception ex) { @@ -853,6 +971,7 @@ namespace ThreadPilot } // Subscribe to shortcut activation events + _keyboardShortcutService.ShortcutActivated -= OnShortcutActivated; _keyboardShortcutService.ShortcutActivated += OnShortcutActivated; // Load shortcuts from settings - with error handling @@ -919,22 +1038,14 @@ namespace ThreadPilot Show(); WindowState = WindowState.Normal; Activate(); - var tabControl = FindName("MainTabControl") as System.Windows.Controls.TabControl; - if (tabControl != null && tabControl.Items.Count > 3) - { - tabControl.SelectedIndex = 3; // Tweaks tab - } + SelectMainTab(SystemTweaksTab); break; case ShortcutActions.OpenSettings: Show(); WindowState = WindowState.Normal; Activate(); - var settingsTabControl = FindName("MainTabControl") as System.Windows.Controls.TabControl; - if (settingsTabControl != null && settingsTabControl.Items.Count > 4) - { - settingsTabControl.SelectedIndex = 4; // Settings tab - } + SelectMainTab(SettingsTab); break; case ShortcutActions.RefreshProcessList: @@ -959,7 +1070,7 @@ namespace ThreadPilot _systemTrayService.UpdatePowerPlans(powerPlans, activePowerPlan); // Update profiles in system tray - var profilesDirectory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "ThreadPilot", "Profiles"); + var profilesDirectory = StoragePaths.ProfilesDirectory; var profileNames = new List(); if (Directory.Exists(profilesDirectory)) @@ -1185,6 +1296,11 @@ namespace ThreadPilot { _processViewModel.PauseRefresh(); } + + if (_performanceViewModel != null) + { + _ = _performanceViewModel.SuspendBackgroundMonitoringAsync(); + } } else if (WindowState == WindowState.Normal) { @@ -1193,6 +1309,11 @@ namespace ThreadPilot { _processViewModel.ResumeRefresh(); } + + if (_performanceViewModel != null) + { + _ = _performanceViewModel.ResumeBackgroundMonitoringAsync(); + } } } catch (Exception ex) @@ -1203,6 +1324,7 @@ namespace ThreadPilot base.OnStateChanged(e); } + [System.Diagnostics.Conditional("DEBUG")] private void LogDebug(string message) { try @@ -1217,26 +1339,131 @@ namespace ThreadPilot } } + private async void OnWindowLoaded(object? sender, RoutedEventArgs e) + { + Loaded -= OnWindowLoaded; + await InitializeKeyboardShortcutsAsync(); + } + + private void OnOpenRulesRequested(object? sender, EventArgs e) + { + SelectMainTab(ProcessAssociationsTab); + } + + private static bool IsTabItem(object? item, object target) + { + return ReferenceEquals(item, target); + } + + private void SelectMainTab(TabItem tab) + { + if (tab != null) + { + MainTabControl.SelectedItem = tab; + } + } + + private async void OnMainTabSelectionChanged(object sender, SelectionChangedEventArgs e) + { + if (_isHandlingTabSelection) + { + return; + } + + if (!IsLoaded || e.Source != MainTabControl) + { + return; + } + + var newIndex = MainTabControl.SelectedIndex; + if (_currentTabIndex < 0) + { + _currentTabIndex = newIndex; + return; + } + + if (newIndex == _currentTabIndex) + { + return; + } + + var previousTab = _currentTabIndex >= 0 && _currentTabIndex < MainTabControl.Items.Count + ? MainTabControl.Items[_currentTabIndex] + : null; + var currentTab = MainTabControl.SelectedItem; + + var settingsTabChanged = IsTabItem(previousTab, SettingsTab) || IsTabItem(currentTab, SettingsTab); + if (!settingsTabChanged) + { + _currentTabIndex = newIndex; + return; + } + + if (!_settingsViewModel.HasPendingChanges) + { + _currentTabIndex = newIndex; + return; + } + + var result = System.Windows.MessageBox.Show( + "You have unsaved changes in Settings.\n\nChoose an action:\n- Yes: Save changes\n- No: Discard changes\n- Cancel: Stay on current tab", + "Unsaved Settings", + MessageBoxButton.YesNoCancel, + MessageBoxImage.Warning); + + if (result == MessageBoxResult.Cancel) + { + _isHandlingTabSelection = true; + MainTabControl.SelectedIndex = _currentTabIndex; + _isHandlingTabSelection = false; + return; + } + + if (result == MessageBoxResult.Yes) + { + var saved = await _settingsViewModel.SaveIfDirtyAsync(); + if (!saved) + { + _isHandlingTabSelection = true; + MainTabControl.SelectedIndex = _currentTabIndex; + _isHandlingTabSelection = false; + return; + } + } + else if (result == MessageBoxResult.No) + { + await _settingsViewModel.DiscardPendingChangesAsync(); + } + + _currentTabIndex = MainTabControl.SelectedIndex; + } + protected override void OnClosing(System.ComponentModel.CancelEventArgs e) { - // Check settings for close behavior - if (_settingsService.Settings.CloseToTray) + if (_isPerformingShutdown) { - // Minimize to tray instead of closing - e.Cancel = true; - WindowState = WindowState.Minimized; - } - else - { - // Actually close the application - System.Windows.Application.Current.Shutdown(); + base.OnClosing(e); + return; } + + e.Cancel = true; + _ = HandleWindowCloseAsync(); } protected override void OnClosed(EventArgs e) { try { + Loaded -= OnWindowLoaded; + _processViewModel.OpenRulesRequested -= OnOpenRulesRequested; + + _settingsService.SettingsChanged -= OnSettingsChanged; + _processMonitorService.MonitoringStatusChanged -= OnMonitoringStatusChanged; + _processMonitorManagerService.ServiceStatusChanged -= OnProcessMonitorManagerStatusChanged; + _keyboardShortcutService.ShortcutActivated -= OnShortcutActivated; + + UnsubscribeSystemTrayEvents(); + _systemTrayUpdateTimer?.Stop(); _systemTrayUpdateTimer?.Dispose(); @@ -1250,5 +1477,17 @@ namespace ThreadPilot base.OnClosed(e); } + + private void UnsubscribeSystemTrayEvents() + { + _systemTrayService.ShowMainWindowRequested -= OnShowMainWindowRequested; + _systemTrayService.DashboardRequested -= OnDashboardRequested; + _systemTrayService.ExitRequested -= OnExitRequested; + _systemTrayService.MonitoringToggleRequested -= OnMonitoringToggleRequested; + _systemTrayService.SettingsRequested -= OnSettingsRequested; + _systemTrayService.PowerPlanChangeRequested -= OnPowerPlanChangeRequested; + _systemTrayService.ProfileApplicationRequested -= OnProfileApplicationRequested; + _systemTrayService.PerformanceDashboardRequested -= OnPerformanceDashboardRequested; + } } } diff --git a/Models/ApplicationSettingsModel.cs b/Models/ApplicationSettingsModel.cs index 193cf56..7ccfe87 100644 --- a/Models/ApplicationSettingsModel.cs +++ b/Models/ApplicationSettingsModel.cs @@ -40,6 +40,9 @@ namespace ThreadPilot.Models [ObservableProperty] private bool enableNotifications = true; + [ObservableProperty] + private NotificationLevelProfile notificationLevel = NotificationLevelProfile.All; + [ObservableProperty] private bool enableBalloonNotifications = true; @@ -136,6 +139,9 @@ namespace ThreadPilot.Models [ObservableProperty] private bool clearMasksOnClose = true; + [ObservableProperty] + private bool useDarkTheme = false; + // Monitoring Settings [ObservableProperty] private int pollingIntervalMs = 5000; @@ -176,6 +182,7 @@ namespace ThreadPilot.Models if (other == null) return; EnableNotifications = other.EnableNotifications; + NotificationLevel = other.NotificationLevel; EnableBalloonNotifications = other.EnableBalloonNotifications; EnableToastNotifications = other.EnableToastNotifications; EnablePowerPlanChangeNotifications = other.EnablePowerPlanChangeNotifications; @@ -210,6 +217,7 @@ namespace ThreadPilot.Models DefaultPowerPlanName = other.DefaultPowerPlanName; RestoreDefaultPowerPlanOnExit = other.RestoreDefaultPowerPlanOnExit; ClearMasksOnClose = other.ClearMasksOnClose; + UseDarkTheme = other.UseDarkTheme; // Monitoring Settings PollingIntervalMs = other.PollingIntervalMs; @@ -224,7 +232,9 @@ namespace ThreadPilot.Models LogRetentionDays = other.LogRetentionDays; // Keyboard Shortcuts - KeyboardShortcuts = new List(other.KeyboardShortcuts); + KeyboardShortcuts = other.KeyboardShortcuts != null + ? new List(other.KeyboardShortcuts) + : new List(); } // IModel implementation - properties are auto-generated by ObservableProperty @@ -246,48 +256,25 @@ namespace ThreadPilot.Models public IModel Clone() { - return new ApplicationSettingsModel - { - id = "ApplicationSettings", - EnableNotifications = this.EnableNotifications, - EnableBalloonNotifications = this.EnableBalloonNotifications, - EnableToastNotifications = this.EnableToastNotifications, - EnablePowerPlanChangeNotifications = this.EnablePowerPlanChangeNotifications, - EnableProcessMonitoringNotifications = this.EnableProcessMonitoringNotifications, - EnableErrorNotifications = this.EnableErrorNotifications, - EnableSuccessNotifications = this.EnableSuccessNotifications, - MinimizeToTray = this.MinimizeToTray, - CloseToTray = this.CloseToTray, - StartMinimized = this.StartMinimized, - ShowTrayIcon = this.ShowTrayIcon, - EnableQuickApplyFromTray = this.EnableQuickApplyFromTray, - EnableMonitoringControlFromTray = this.EnableMonitoringControlFromTray, - NotificationDisplayDurationMs = this.NotificationDisplayDurationMs, - BalloonNotificationTimeoutMs = this.BalloonNotificationTimeoutMs, - NotificationPosition = this.NotificationPosition, - NotificationSound = this.NotificationSound, - EnableNotificationSound = this.EnableNotificationSound, - TrayIconStyle = this.TrayIconStyle, - AutostartWithWindows = this.AutostartWithWindows, - DefaultPowerPlanId = this.DefaultPowerPlanId, - DefaultPowerPlanName = this.DefaultPowerPlanName, - RestoreDefaultPowerPlanOnExit = this.RestoreDefaultPowerPlanOnExit, - ClearMasksOnClose = this.ClearMasksOnClose, - PollingIntervalMs = this.PollingIntervalMs, - FallbackPollingIntervalMs = this.FallbackPollingIntervalMs, - EnableWmiMonitoring = this.EnableWmiMonitoring, - EnableFallbackPolling = this.EnableFallbackPolling, - EnableDebugLogging = this.EnableDebugLogging, - EnablePerformanceCounters = this.EnablePerformanceCounters, - MaxLogFileSizeMb = this.MaxLogFileSizeMb, - LogRetentionDays = this.LogRetentionDays, - KeyboardShortcuts = new List(this.KeyboardShortcuts), - CreatedAt = this.CreatedAt, - UpdatedAt = DateTime.UtcNow - }; + var clone = new ApplicationSettingsModel(); + clone.CopyFrom(this); + clone.Id = this.Id; + clone.CreatedAt = this.CreatedAt; + clone.UpdatedAt = this.UpdatedAt; + return clone; } } + /// + /// Notification level profile options + /// + public enum NotificationLevelProfile + { + All, + WarningsAndErrorsOnly, + Silent + } + /// /// Notification position options /// diff --git a/Models/ProcessPowerPlanAssociation.cs b/Models/ProcessPowerPlanAssociation.cs index e01c592..e5018da 100644 --- a/Models/ProcessPowerPlanAssociation.cs +++ b/Models/ProcessPowerPlanAssociation.cs @@ -16,6 +16,7 @@ */ using System; using System.Collections.Generic; +using System.IO; using CommunityToolkit.Mvvm.ComponentModel; using ThreadPilot.Models.Core; @@ -110,7 +111,9 @@ namespace ThreadPilot.Models } else { - return string.Equals(process.Name, ExecutableName, StringComparison.OrdinalIgnoreCase); + var processName = NormalizeExecutableName(process.Name); + var associationName = NormalizeExecutableName(ExecutableName); + return string.Equals(processName, associationName, StringComparison.OrdinalIgnoreCase); } } @@ -120,7 +123,19 @@ namespace ThreadPilot.Models public bool MatchesExecutable(string executableName) { if (!IsEnabled) return false; - return string.Equals(ExecutableName, executableName, StringComparison.OrdinalIgnoreCase); + var associationName = NormalizeExecutableName(ExecutableName); + var inputName = NormalizeExecutableName(executableName); + return string.Equals(associationName, inputName, StringComparison.OrdinalIgnoreCase); + } + + private static string NormalizeExecutableName(string? executableName) + { + if (string.IsNullOrWhiteSpace(executableName)) + { + return string.Empty; + } + + return Path.GetFileNameWithoutExtension(executableName.Trim()); } diff --git a/README.md b/README.md index c271db8..a29d043 100644 --- a/README.md +++ b/README.md @@ -1,71 +1,61 @@ -# ThreadPilot ✈️ PUBLIC BETA +# ThreadPilot -[![Status](https://img.shields.io/badge/Status-Public%20Beta-orange.svg)]() -[![Windows](https://img.shields.io/badge/Windows-10%2F11-blue?logo=windows&logoColor=white)](https://www.microsoft.com/windows) -[![.NET](https://img.shields.io/badge/.NET-8.0-purple?logo=dotnet&logoColor=white)](https://dotnet.microsoft.com/) -[![WPF](https://img.shields.io/badge/WPF-Windows%20Presentation%20Foundation-blue?logo=microsoft&logoColor=white)](https://docs.microsoft.com/en-us/dotnet/desktop/wpf/) -[![License](https://img.shields.io/badge/License-GPLv3-blue.svg)](LICENSE) -[![Release](https://img.shields.io/badge/Release-Latest-brightgreen)](../../releases) -[![Architecture](https://img.shields.io/badge/Architecture-x64-red?logo=windows&logoColor=white)](https://docs.microsoft.com/en-us/windows/win32/) +ThreadPilot is a Windows process and power plan manager built with WPF and .NET 8. +It is focused on deterministic performance workflows for power users, gamers, and admins. -**ThreadPilot** is a Windows application for advanced **process management**, **CPU affinity control**, and **power plan automation**. -It is designed for power users, gamers, and professionals who want precise control over system performance. +## Highlights -[![Thread-Pilotbanner.png](https://i.postimg.cc/sDZLXMqr/Thread-Pilotbanner.png)](https://postimg.cc/cr0hkLd9) +- Process management with CPU affinity and priority controls. +- Rule-based automation for process-triggered power plan behavior. +- Global power plan management with explicit separation from per-process actions. +- System tweaks panel for advanced Windows performance settings. +- Performance Intelligence dashboard with hotspots, rule impact, and timeline events. +- Light/Dark theming with runtime switching. -## ✨ Features +## Requirements -- Advanced process management with real-time monitoring -- CPU affinity control with physical / logical core awareness -- Automatic power plan switching per process -- Game-focused performance optimization -- System tweaks and performance-related Windows settings -- Profile-based configuration and persistence +- Windows 10/11 (x64) +- .NET 8 SDK for building from source +- Administrator privileges for full functionality -Screenshot 2025-12-21 044753 +## Build -## πŸ“¦ Installation - -### Portable (recommended) -1. Download the latest release from [GitHub Releases](../../releases) -2. Extract the archive -3. Run `ThreadPilot.exe` **as Administrator** - -### Build from source ```bash -git clone https://github.com/PrimeBuild-pc/ThreadPilot.git -cd ThreadPilot -dotnet build --configuration Release -dotnet run --configuration Release -```` +dotnet build "ThreadPilot_1.sln" --configuration Release +``` -Requires **.NET 8.0 SDK** or newer. +## Run ---- +```bash +dotnet run --project "ThreadPilot.csproj" --configuration Release +``` -## πŸ› οΈ Tech Stack +Useful arguments: -* .NET 8.0 -* WPF -* MVVM (CommunityToolkit.Mvvm) -* Dependency Injection -* Async / Await +- `--start-minimized` +- `--autostart` +- `--test` (console test mode) ---- +## Test Mode -## πŸ“„ License +Console test mode runs via the app entrypoint and uses `TestRunner.cs`. -This project is licensed under the **GNU General Public License v3.0**. -See [LICENSE](LICENSE) for details. +```bash +dotnet run --project "ThreadPilot.csproj" --configuration Release -- --test +``` ---- +Notes: -## πŸ“ž Support +- In environments where elevation is required to start the app process, test mode may need an elevated terminal. +- `dotnet test` will only execute tests in dedicated test projects; this repository currently uses an integrated runtime test runner. -**Made for Windows power usersβ˜•** [![PayPal](https://img.shields.io/badge/Supporta%20su-PayPal-blue?logo=paypal)](https://paypal.me/PrimeBuildOfficial?country.x=IT&locale.x=it_IT) - -* **Issues**: [https://github.com/PrimeBuild-pc/ThreadPilot/issues](https://github.com/PrimeBuild-pc/ThreadPilot/issues) -* **Discussions**: [https://github.com/PrimeBuild-pc/ThreadPilot/discussions](https://github.com/PrimeBuild-pc/ThreadPilot/discussions) +## Architecture Notes +- MVVM with CommunityToolkit.Mvvm. +- DI configuration in `Services/ServiceConfiguration.cs`. +- Rules and automation in `Services/ProcessPowerPlanAssociationService.cs` and `ViewModels/ProcessPowerPlanAssociationViewModel.cs`. +- Performance dashboard in `Views/PerformanceView.xaml` and `ViewModels/PerformanceViewModel.cs`. +## License +GPLv3. See `LICENSE`. diff --git a/Services/ApplicationSettingsService.cs b/Services/ApplicationSettingsService.cs index cba9cf4..5fd8910 100644 --- a/Services/ApplicationSettingsService.cs +++ b/Services/ApplicationSettingsService.cs @@ -16,6 +16,7 @@ */ using System; using System.IO; +using System.Text; using System.Text.Json; using System.Threading.Tasks; using Microsoft.Extensions.Logging; @@ -31,20 +32,27 @@ namespace ThreadPilot.Services private readonly ILogger _logger; private readonly string _settingsFilePath; private ApplicationSettingsModel _settings; + private static readonly JsonSerializerOptions JsonOptions = new() + { + WriteIndented = true, + PropertyNamingPolicy = JsonNamingPolicy.CamelCase, + PropertyNameCaseInsensitive = true, + ReadCommentHandling = JsonCommentHandling.Skip, + AllowTrailingCommas = true + }; public event EventHandler? SettingsChanged; - public ApplicationSettingsModel Settings => _settings; + public ApplicationSettingsModel Settings => (ApplicationSettingsModel)_settings.Clone(); public ApplicationSettingsService(ILogger logger) { _logger = logger ?? throw new ArgumentNullException(nameof(logger)); - - // Set settings file path in user's AppData folder - var appDataPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData); - var appFolder = Path.Combine(appDataPath, "ThreadPilot"); - Directory.CreateDirectory(appFolder); - _settingsFilePath = Path.Combine(appFolder, "settings.json"); + + StoragePaths.EnsureAppDataDirectories(); + _settingsFilePath = StoragePaths.SettingsFilePath; + + MigrateLegacySettingsIfNeeded(); _settings = new ApplicationSettingsModel(); } @@ -64,7 +72,7 @@ namespace ThreadPilot.Services } var json = await File.ReadAllTextAsync(_settingsFilePath); - var loadedSettings = JsonSerializer.Deserialize(json); + var loadedSettings = JsonSerializer.Deserialize(json, JsonOptions); if (loadedSettings != null) { @@ -96,14 +104,8 @@ namespace ThreadPilot.Services ValidateAndFixSettings(); - var options = new JsonSerializerOptions - { - WriteIndented = true, - PropertyNamingPolicy = JsonNamingPolicy.CamelCase - }; - - var json = JsonSerializer.Serialize(_settings, options); - await File.WriteAllTextAsync(_settingsFilePath, json); + var json = JsonSerializer.Serialize(_settings, JsonOptions); + await AtomicFileWriter.WriteAllTextAsync(_settingsFilePath, json, Encoding.UTF8); _logger.LogDebug("Settings saved successfully"); } @@ -198,14 +200,8 @@ namespace ThreadPilot.Services { _logger.LogInformation("Exporting settings to {FilePath}", filePath); - var options = new JsonSerializerOptions - { - WriteIndented = true, - PropertyNamingPolicy = JsonNamingPolicy.CamelCase - }; - - var json = JsonSerializer.Serialize(_settings, options); - await File.WriteAllTextAsync(filePath, json); + var json = JsonSerializer.Serialize(_settings, JsonOptions); + await AtomicFileWriter.WriteAllTextAsync(filePath, json, Encoding.UTF8); _logger.LogInformation("Settings exported successfully"); } @@ -226,7 +222,7 @@ namespace ThreadPilot.Services throw new FileNotFoundException($"Settings file not found: {filePath}"); var json = await File.ReadAllTextAsync(filePath); - var importedSettings = JsonSerializer.Deserialize(json); + var importedSettings = JsonSerializer.Deserialize(json, JsonOptions); if (importedSettings == null) throw new InvalidOperationException("Failed to deserialize imported settings"); @@ -248,15 +244,36 @@ namespace ThreadPilot.Services // For simplicity, we'll just indicate that settings changed // In a more sophisticated implementation, we could track specific property changes var changedProperties = new[] { "Settings" }; + + var oldSnapshot = (ApplicationSettingsModel)oldSettings.Clone(); + var newSnapshot = (ApplicationSettingsModel)newSettings.Clone(); SettingsChanged?.Invoke(this, new ApplicationSettingsChangedEventArgs( - oldSettings, newSettings, changedProperties)); + oldSnapshot, newSnapshot, changedProperties)); } catch (Exception ex) { _logger.LogError(ex, "Error firing settings changed event"); } } + + private void MigrateLegacySettingsIfNeeded() + { + try + { + var legacySettingsPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "settings.json"); + if (File.Exists(legacySettingsPath) && !File.Exists(_settingsFilePath)) + { + Directory.CreateDirectory(Path.GetDirectoryName(_settingsFilePath)!); + File.Copy(legacySettingsPath, _settingsFilePath); + _logger.LogInformation("Migrated legacy settings file to AppData storage"); + } + } + catch (Exception ex) + { + _logger.LogWarning(ex, "Failed to migrate legacy settings file"); + } + } } } diff --git a/Services/AtomicFileWriter.cs b/Services/AtomicFileWriter.cs new file mode 100644 index 0000000..f738d65 --- /dev/null +++ b/Services/AtomicFileWriter.cs @@ -0,0 +1,72 @@ +/* + * ThreadPilot - Advanced Windows Process and Power Plan Manager + * Copyright (C) 2025 Prime Build + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, version 3 only. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +using System; +using System.IO; +using System.Text; +using System.Threading.Tasks; + +namespace ThreadPilot.Services +{ + internal static class AtomicFileWriter + { + public static async Task WriteAllTextAsync(string filePath, string content, Encoding? encoding = null) + { + if (string.IsNullOrWhiteSpace(filePath)) + { + throw new ArgumentException("File path cannot be null or empty.", nameof(filePath)); + } + + var targetDirectory = Path.GetDirectoryName(filePath); + if (string.IsNullOrEmpty(targetDirectory)) + { + throw new InvalidOperationException($"Cannot determine target directory for path '{filePath}'."); + } + + Directory.CreateDirectory(targetDirectory); + + var tempFilePath = Path.Combine(targetDirectory, $".{Path.GetFileName(filePath)}.{Guid.NewGuid():N}.tmp"); + var backupFilePath = filePath + ".bak"; + + try + { + encoding ??= new UTF8Encoding(encoderShouldEmitUTF8Identifier: false); + await File.WriteAllTextAsync(tempFilePath, content, encoding); + + if (File.Exists(filePath)) + { + File.Replace(tempFilePath, filePath, backupFilePath, ignoreMetadataErrors: true); + + if (File.Exists(backupFilePath)) + { + File.Delete(backupFilePath); + } + } + else + { + File.Move(tempFilePath, filePath); + } + } + finally + { + if (File.Exists(tempFilePath)) + { + File.Delete(tempFilePath); + } + } + } + } +} diff --git a/Services/AutostartService.cs b/Services/AutostartService.cs index ef2ee5f..5bfd178 100644 --- a/Services/AutostartService.cs +++ b/Services/AutostartService.cs @@ -31,6 +31,7 @@ namespace ThreadPilot.Services private const string REGISTRY_KEY_PATH = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Run"; private const string APPLICATION_NAME = "ThreadPilot"; private const string SCHEDULED_TASK_NAME = "ThreadPilot_Startup"; + private static readonly string SchTasksExecutablePath = Path.Combine(Environment.SystemDirectory, "schtasks.exe"); private readonly ILogger _logger; private readonly IElevationService _elevationService; @@ -236,11 +237,11 @@ namespace ThreadPilot.Services try { var taskArguments = $"/Create /TN \"{SCHEDULED_TASK_NAME}\" /TR \"\\\"{executablePath}\\\" {arguments}\" " + - "/SC ONLOGON /RL HIGHEST /F /RU \"{Environment.UserName}\""; + $"/SC ONLOGON /RL HIGHEST /F /RU \"{Environment.UserName}\""; var processInfo = new ProcessStartInfo { - FileName = "schtasks.exe", + FileName = SchTasksExecutablePath, Arguments = taskArguments, UseShellExecute = false, CreateNoWindow = true, @@ -281,7 +282,7 @@ namespace ThreadPilot.Services var processInfo = new ProcessStartInfo { - FileName = "schtasks.exe", + FileName = SchTasksExecutablePath, Arguments = taskArguments, UseShellExecute = false, CreateNoWindow = true, diff --git a/Services/CoreMaskService.cs b/Services/CoreMaskService.cs index a36b725..88146a3 100644 --- a/Services/CoreMaskService.cs +++ b/Services/CoreMaskService.cs @@ -19,6 +19,7 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.IO; +using System.Text; using System.Linq; using System.Text.Json; using System.Threading.Tasks; @@ -33,6 +34,13 @@ namespace ThreadPilot.Services /// public class CoreMaskService : ICoreMaskService { + private static readonly JsonSerializerOptions JsonOptions = new() + { + WriteIndented = true, + PropertyNameCaseInsensitive = true, + ReadCommentHandling = JsonCommentHandling.Skip, + AllowTrailingCommas = true + }; private readonly ILogger _logger; private readonly ICpuTopologyService _cpuTopologyService; private readonly IServiceProvider _serviceProvider; @@ -59,12 +67,8 @@ namespace ThreadPilot.Services _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"); + StoragePaths.EnsureAppDataDirectories(); + _masksFilePath = StoragePaths.CoreMasksFilePath; } public async Task InitializeAsync() @@ -183,12 +187,9 @@ namespace ThreadPilot.Services updatedAt = m.UpdatedAt }).ToList(); - var json = JsonSerializer.Serialize(data, new JsonSerializerOptions - { - WriteIndented = true - }); + var json = JsonSerializer.Serialize(data, JsonOptions); - await File.WriteAllTextAsync(_masksFilePath, json); + await AtomicFileWriter.WriteAllTextAsync(_masksFilePath, json, Encoding.UTF8); _logger.LogDebug("Saved {Count} masks to {Path}", AvailableMasks.Count, _masksFilePath); } catch (Exception ex) @@ -209,7 +210,7 @@ namespace ThreadPilot.Services } var json = await File.ReadAllTextAsync(_masksFilePath); - var data = JsonSerializer.Deserialize>(json); + var data = JsonSerializer.Deserialize>(json, JsonOptions); if (data == null) { diff --git a/Services/CpuTopologyService.cs b/Services/CpuTopologyService.cs index 80b0c26..223d8fc 100644 --- a/Services/CpuTopologyService.cs +++ b/Services/CpuTopologyService.cs @@ -20,6 +20,7 @@ using System.Diagnostics; using System.Linq; using System.Management; using System.Runtime.InteropServices; +using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Caching.Memory; using Microsoft.Extensions.Logging; @@ -34,6 +35,7 @@ namespace ThreadPilot.Services { private readonly ILogger _logger; private readonly IMemoryCache _cache; + private readonly SemaphoreSlim _detectSemaphore = new(1, 1); private CpuTopologyModel? _currentTopology; private const string TOPOLOGY_CACHE_KEY = "cpu_topology"; @@ -62,8 +64,18 @@ namespace ThreadPilot.Services return cachedTopology; } + await _detectSemaphore.WaitAsync(); + try { + // Re-check cache after entering the critical section + if (_cache.TryGetValue(TOPOLOGY_CACHE_KEY, out cachedTopology) && cachedTopology != null) + { + _logger.LogInformation("CPU topology retrieved from cache after synchronization"); + _currentTopology = cachedTopology; + return cachedTopology; + } + _logger.LogInformation("Starting CPU topology detection (cache miss)"); var topology = new CpuTopologyModel(); @@ -84,7 +96,12 @@ namespace ThreadPilot.Services topology.TopologyDetectionSuccessful = true; // PERFORMANCE IMPROVEMENT: Cache the topology to avoid expensive WMI calls - _cache.Set(TOPOLOGY_CACHE_KEY, topology, CACHE_DURATION); + _cache.Set( + TOPOLOGY_CACHE_KEY, + topology, + new MemoryCacheEntryOptions() + .SetAbsoluteExpiration(CACHE_DURATION) + .SetSize(1)); _logger.LogInformation("CPU topology detection completed successfully and cached. " + "Logical cores: {LogicalCores}, Physical cores: {PhysicalCores}, " + @@ -106,6 +123,10 @@ namespace ThreadPilot.Services TopologyDetected?.Invoke(this, new CpuTopologyDetectedEventArgs(fallbackTopology, false, ex.Message)); return fallbackTopology; } + finally + { + _detectSemaphore.Release(); + } } private async Task DetectBasicCpuInfoAsync(CpuTopologyModel topology) @@ -365,13 +386,43 @@ namespace ThreadPilot.Services { CreateBasicTopology(topology, Environment.ProcessorCount); } + + if (string.IsNullOrWhiteSpace(topology.CpuBrand)) + { + topology.CpuBrand = "Unknown"; + } + + if (string.IsNullOrWhiteSpace(topology.CpuArchitecture)) + { + topology.CpuArchitecture = RuntimeInformation.ProcessArchitecture.ToString(); + } // Ensure logical core IDs are sequential for (int i = 0; i < topology.LogicalCores.Count; i++) { topology.LogicalCores[i].LogicalCoreId = i; } - + + // Normalize physical core IDs to avoid invalid/negative mappings + var normalizedPhysicalCoreIds = topology.LogicalCores + .Select((core, index) => new + { + core, + physical = core.PhysicalCoreId >= 0 ? core.PhysicalCoreId : index + }) + .GroupBy(x => x.physical) + .OrderBy(g => g.Key) + .Select((group, normalizedId) => new { group, normalizedId }) + .ToList(); + + foreach (var item in normalizedPhysicalCoreIds) + { + foreach (var entry in item.group) + { + entry.core.PhysicalCoreId = item.normalizedId; + } + } + // Update labels - simplified without CCD clutter foreach (var core in topology.LogicalCores) { @@ -385,6 +436,12 @@ namespace ThreadPilot.Services var htLabel = core.IsHyperThreaded ? " (HT)" : ""; core.Label = $"{typeLabel}Core {core.LogicalCoreId}{htLabel}"; + + if (string.IsNullOrWhiteSpace(core.LogicalProcessorName)) + { + var threadIndex = Math.Max(0, core.LogicalCoreId - core.PhysicalCoreId); + core.LogicalProcessorName = $"Core{core.PhysicalCoreId}_T{threadIndex}"; + } } } @@ -398,7 +455,8 @@ namespace ThreadPilot.Services private long CalculateFullAffinityMask(int logicalCoreCount) { - // For 64 logical cores the mask needs all bits set; shifting by 64 would wrap to zero + // Affinity masks are represented as signed 64-bit values in this application. + // For 63+ logical cores, use all available bits to avoid undefined shifts. return logicalCoreCount >= 63 ? -1L : (1L << logicalCoreCount) - 1; @@ -428,7 +486,7 @@ namespace ThreadPilot.Services Name = "No HT", Description = $"All {_currentTopology.TotalPhysicalCores} physical cores (no HyperThreading)", AffinityMask = _currentTopology.GetPhysicalCoresAffinityMask(), - IsAvailable = true + IsAvailable = _currentTopology.GetPhysicalCoresAffinityMask() != 0 }); } @@ -440,7 +498,7 @@ namespace ThreadPilot.Services Name = "Performance Cores", Description = $"Intel P-cores ({_currentTopology.PerformanceCores.Count()} cores)", AffinityMask = _currentTopology.GetPerformanceCoresAffinityMask(), - IsAvailable = true + IsAvailable = _currentTopology.GetPerformanceCoresAffinityMask() != 0 }); } @@ -452,7 +510,7 @@ namespace ThreadPilot.Services Name = "Efficiency Cores", Description = $"Intel E-cores ({_currentTopology.EfficiencyCores.Count()} cores)", AffinityMask = _currentTopology.GetEfficiencyCoresAffinityMask(), - IsAvailable = true + IsAvailable = _currentTopology.GetEfficiencyCoresAffinityMask() != 0 }); } @@ -467,7 +525,7 @@ namespace ThreadPilot.Services Name = $"CCD {ccdId}", Description = $"AMD CCD {ccdId} ({ccdCores.Count()} cores)", AffinityMask = _currentTopology.GetCcdAffinityMask(ccdId), - IsAvailable = true + IsAvailable = _currentTopology.GetCcdAffinityMask(ccdId) != 0 }); } } @@ -479,6 +537,13 @@ namespace ThreadPilot.Services { if (_currentTopology == null) return false; + // Long-based affinity masks cannot represent cores beyond bit 62 explicitly. + // Accept any non-zero mask for large-core systems and let runtime APIs enforce final validity. + if (_currentTopology.TotalLogicalCores >= 63) + { + return affinityMask != 0; + } + var maxMask = CalculateFullAffinityMask(_currentTopology.TotalLogicalCores); return affinityMask > 0 && affinityMask <= maxMask; } @@ -490,6 +555,7 @@ namespace ThreadPilot.Services public async Task RefreshTopologyAsync() { + _cache.Remove(TOPOLOGY_CACHE_KEY); await DetectTopologyAsync(); } } diff --git a/Services/EnhancedLoggingService.cs b/Services/EnhancedLoggingService.cs index 1a74cfe..2c9054c 100644 --- a/Services/EnhancedLoggingService.cs +++ b/Services/EnhancedLoggingService.cs @@ -488,11 +488,12 @@ namespace ThreadPilot.Services public async Task UpdateConfigurationAsync(bool enableDebugLogging, int maxFileSizeMb, int retentionDays) { - _settingsService.Settings.EnableDebugLogging = enableDebugLogging; - _settingsService.Settings.MaxLogFileSizeMb = maxFileSizeMb; - _settingsService.Settings.LogRetentionDays = retentionDays; + var updatedSettings = _settingsService.Settings; + updatedSettings.EnableDebugLogging = enableDebugLogging; + updatedSettings.MaxLogFileSizeMb = maxFileSizeMb; + updatedSettings.LogRetentionDays = retentionDays; - await _settingsService.SaveSettingsAsync(); + await _settingsService.UpdateSettingsAsync(updatedSettings); await LogSystemEventAsync("Configuration", $"Logging configuration updated: Debug={enableDebugLogging}, MaxSize={maxFileSizeMb}MB, Retention={retentionDays}days"); } diff --git a/Services/ICoreMaskService.cs b/Services/ICoreMaskService.cs index 895a394..7ce7a63 100644 --- a/Services/ICoreMaskService.cs +++ b/Services/ICoreMaskService.cs @@ -105,6 +105,16 @@ namespace ThreadPilot.Services /// Gets the "All Cores" baseline mask (cannot be deleted) /// CoreMask? GetAllCoresMask(); + + /// + /// Registers that a mask has been applied to a running process + /// + void RegisterMaskApplication(int processId, string maskId); + + /// + /// Unregisters mask tracking when a process exits or a mask is removed + /// + void UnregisterMaskApplication(int processId); } } diff --git a/Services/ISystemTrayService.cs b/Services/ISystemTrayService.cs index 94629db..f3b2399 100644 --- a/Services/ISystemTrayService.cs +++ b/Services/ISystemTrayService.cs @@ -65,6 +65,11 @@ namespace ThreadPilot.Services /// event EventHandler? PerformanceDashboardRequested; + /// + /// Event fired when process management dashboard is requested from tray + /// + event EventHandler? DashboardRequested; + /// /// Initializes the system tray icon /// diff --git a/Services/IThemeService.cs b/Services/IThemeService.cs new file mode 100644 index 0000000..f6c123a --- /dev/null +++ b/Services/IThemeService.cs @@ -0,0 +1,27 @@ +/* + * ThreadPilot - Advanced Windows Process and Power Plan Manager + * Copyright (C) 2025 Prime Build + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, version 3 only. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +using System; + +namespace ThreadPilot.Services +{ + public interface IThemeService + { + bool IsDarkTheme { get; } + + void ApplyTheme(bool useDarkTheme); + } +} diff --git a/Services/KeyboardShortcutService.cs b/Services/KeyboardShortcutService.cs index f8a625c..e0306d6 100644 --- a/Services/KeyboardShortcutService.cs +++ b/Services/KeyboardShortcutService.cs @@ -209,7 +209,7 @@ namespace ThreadPilot.Services { var settings = _settingsService.Settings; settings.KeyboardShortcuts = _registeredShortcuts.Values.ToList(); - await _settingsService.SaveSettingsAsync(); + await _settingsService.UpdateSettingsAsync(settings); _logger.LogInformation("Saved {Count} keyboard shortcuts to settings", _registeredShortcuts.Count); } diff --git a/Services/NotificationService.cs b/Services/NotificationService.cs index bc85e37..cc65546 100644 --- a/Services/NotificationService.cs +++ b/Services/NotificationService.cs @@ -289,6 +289,18 @@ namespace ThreadPilot.Services { if (!_settings.EnableNotifications) return false; + if (_settings.NotificationLevel == NotificationLevelProfile.Silent) + { + return false; + } + + if (_settings.NotificationLevel == NotificationLevelProfile.WarningsAndErrorsOnly && + type != NotificationType.Warning && + type != NotificationType.Error) + { + return false; + } + return type switch { NotificationType.PowerPlanChange => _settings.EnablePowerPlanChangeNotifications, diff --git a/Services/PowerPlanService.cs b/Services/PowerPlanService.cs index fbdfff3..82ebb68 100644 --- a/Services/PowerPlanService.cs +++ b/Services/PowerPlanService.cs @@ -29,6 +29,7 @@ namespace ThreadPilot.Services public class PowerPlanService : IPowerPlanService { private static readonly Lazy _powerPlansPath = new(GetPowerPlansPath); + private static readonly string _powerCfgExecutablePath = Path.Combine(Environment.SystemDirectory, "powercfg.exe"); private static string PowerPlansPath => _powerPlansPath.Value; private readonly object _lockObject = new(); @@ -51,6 +52,8 @@ namespace ThreadPilot.Services /// private static string GetPowerPlansPath() { + StoragePaths.EnsureAppDataDirectories(); + // Check portable mode first (Powerplans folder next to EXE) var exeDir = AppContext.BaseDirectory; var portablePath = Path.Combine(exeDir, "Powerplans"); @@ -60,9 +63,7 @@ namespace ThreadPilot.Services } // Installed mode: use AppData - var appDataPath = Path.Combine( - Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), - "ThreadPilot", "Powerplans"); + var appDataPath = StoragePaths.PowerPlansDirectory; // Ensure directory exists if (!Directory.Exists(appDataPath)) @@ -105,7 +106,7 @@ namespace ThreadPilot.Services { StartInfo = new ProcessStartInfo { - FileName = "powercfg", + FileName = _powerCfgExecutablePath, Arguments = "/list", UseShellExecute = false, RedirectStandardOutput = true, @@ -199,12 +200,11 @@ namespace ThreadPilot.Services { StartInfo = new ProcessStartInfo { - FileName = "powercfg", + FileName = _powerCfgExecutablePath, Arguments = $"/setactive {powerPlanGuid}", UseShellExecute = false, RedirectStandardOutput = true, - CreateNoWindow = true, - Verb = "runas" // Run with elevated privileges + CreateNoWindow = true } }; @@ -270,7 +270,7 @@ namespace ThreadPilot.Services { StartInfo = new ProcessStartInfo { - FileName = "powercfg", + FileName = _powerCfgExecutablePath, Arguments = "/getactivescheme", UseShellExecute = false, RedirectStandardOutput = true, @@ -314,12 +314,11 @@ namespace ThreadPilot.Services { StartInfo = new ProcessStartInfo { - FileName = "powercfg", + FileName = _powerCfgExecutablePath, Arguments = $"/import \"{filePath}\"", UseShellExecute = false, RedirectStandardOutput = true, - CreateNoWindow = true, - Verb = "runas" // Run with elevated privileges + CreateNoWindow = true } }; diff --git a/Services/ProcessMonitorManagerService.cs b/Services/ProcessMonitorManagerService.cs index d67fd58..ebb09c8 100644 --- a/Services/ProcessMonitorManagerService.cs +++ b/Services/ProcessMonitorManagerService.cs @@ -45,11 +45,13 @@ namespace ThreadPilot.Services private readonly ConcurrentDictionary _runningAssociatedProcesses = new(); private readonly System.Threading.Timer _delayTimer; private readonly SemaphoreSlim _powerPlanChangeSemaphore = new(1, 1); + private readonly SemaphoreSlim _stateMutationSemaphore = new(1, 1); private bool _isRunning; private string _status = "Stopped"; private bool _disposed; private ProcessMonitorConfiguration? _configuration; + private int _pendingPowerPlanReevaluation; public event EventHandler? ProcessPowerPlanChanged; public event EventHandler? ServiceStatusChanged; @@ -92,11 +94,15 @@ namespace ThreadPilot.Services public async Task StartAsync() { if (_disposed) throw new ObjectDisposedException(nameof(ProcessMonitorManagerService)); - - if (_isRunning) return; + await _stateMutationSemaphore.WaitAsync(); try { + if (_isRunning) + { + return; + } + _logger.LogInformation("Starting Process Monitor Manager Service"); await _enhancedLogger.LogSystemEventAsync(LogEventTypes.System.ServiceStarted, "Process Monitor Manager Service starting"); @@ -115,14 +121,14 @@ namespace ThreadPilot.Services await _processMonitorService.StartMonitoringAsync(); _logger.LogInformation("Process monitoring started"); + Interlocked.Exchange(ref _pendingPowerPlanReevaluation, 0); + await _enhancedLogger.LogProcessMonitoringEventAsync(LogEventTypes.ProcessMonitoring.MonitoringStarted, "ProcessMonitorService", 0, "WMI-based process monitoring started"); - // Evaluate current processes - await EvaluateCurrentProcessesAsync(); - _isRunning = true; SetStatus(true, "Running"); + _logger.LogInformation("Process Monitor Manager Service started successfully"); await _enhancedLogger.LogSystemEventAsync(LogEventTypes.System.ServiceStarted, @@ -137,20 +143,40 @@ namespace ThreadPilot.Services SetStatus(false, "Failed to start", $"Error: {ex.Message}", ex); throw; } + finally + { + _stateMutationSemaphore.Release(); + } + + // Evaluate current processes after startup lock is released + await EvaluateCurrentProcessesAsync(); } public async Task StopAsync() { - if (!_isRunning) return; - + await _stateMutationSemaphore.WaitAsync(); try { + if (!_isRunning) + { + return; + } + SetStatus(false, "Stopping..."); + // Mark as stopped early to prevent new event handling while shutting down + _isRunning = false; + Interlocked.Exchange(ref _pendingPowerPlanReevaluation, 0); + // Stop process monitoring await _processMonitorService.StopMonitoringAsync(); // Clear running processes + foreach (var processId in _runningAssociatedProcesses.Keys) + { + _coreMaskService.UnregisterMaskApplication(processId); + _processService.UntrackProcess(processId); + } _runningAssociatedProcesses.Clear(); // Restore default power plan if configured @@ -159,7 +185,6 @@ namespace ThreadPilot.Services await ForceDefaultPowerPlanAsync(); } - _isRunning = false; SetStatus(false, "Stopped"); } catch (Exception ex) @@ -167,6 +192,10 @@ namespace ThreadPilot.Services SetStatus(false, "Error stopping", $"Error: {ex.Message}", ex); throw; } + finally + { + _stateMutationSemaphore.Release(); + } } public async Task EvaluateCurrentProcessesAsync() @@ -177,6 +206,17 @@ namespace ThreadPilot.Services { var currentProcesses = await _processMonitorService.GetRunningProcessesAsync(); var associatedProcesses = new List(); + var currentProcessIds = new HashSet(currentProcesses.Select(p => p.ProcessId)); + + // Remove stale tracked processes that are no longer running + foreach (var trackedPid in _runningAssociatedProcesses.Keys) + { + if (!currentProcessIds.Contains(trackedPid) && _runningAssociatedProcesses.TryRemove(trackedPid, out _)) + { + _coreMaskService.UnregisterMaskApplication(trackedPid); + _processService.UntrackProcess(trackedPid); + } + } // Find all currently running processes that have associations foreach (var process in currentProcesses) @@ -185,7 +225,7 @@ namespace ThreadPilot.Services if (association != null) { associatedProcesses.Add(process); - _runningAssociatedProcesses.TryAdd(process.ProcessId, process); + _runningAssociatedProcesses[process.ProcessId] = process; } } @@ -247,6 +287,7 @@ namespace ThreadPilot.Services { await _associationService.LoadConfigurationAsync(); _configuration = _associationService.Configuration; + _processMonitorService.UpdateSettings(); if (_isRunning) { @@ -258,6 +299,11 @@ namespace ThreadPilot.Services { if (!_isRunning || _configuration == null) return; + if (string.IsNullOrWhiteSpace(e.Process.Name) || e.Process.ProcessId <= 0) + { + return; + } + try { await _enhancedLogger.LogProcessMonitoringEventAsync(LogEventTypes.ProcessMonitoring.Started, @@ -266,7 +312,7 @@ namespace ThreadPilot.Services var association = _configuration.FindMatchingAssociation(e.Process); if (association != null) { - _runningAssociatedProcesses.TryAdd(e.Process.ProcessId, e.Process); + _runningAssociatedProcesses[e.Process.ProcessId] = e.Process; await _enhancedLogger.LogProcessMonitoringEventAsync(LogEventTypes.ProcessMonitoring.AssociationTriggered, e.Process.Name, e.Process.ProcessId, @@ -278,6 +324,7 @@ namespace ThreadPilot.Services // Schedule power plan change with delay if configured if (_configuration.PowerPlanChangeDelayMs > 0) { + Interlocked.Exchange(ref _pendingPowerPlanReevaluation, 1); _delayTimer.Change(_configuration.PowerPlanChangeDelayMs, Timeout.Infinite); await _enhancedLogger.LogSystemEventAsync(LogEventTypes.System.ConfigurationLoaded, @@ -307,8 +354,11 @@ namespace ThreadPilot.Services try { - if (_runningAssociatedProcesses.TryRemove(e.Process.ProcessId, out var removedProcess)) + if (_runningAssociatedProcesses.TryRemove(e.Process.ProcessId, out _)) { + _coreMaskService.UnregisterMaskApplication(e.Process.ProcessId); + _processService.UntrackProcess(e.Process.ProcessId); + // Check if there are any other associated processes still running var remainingProcesses = _runningAssociatedProcesses.Values.ToList(); await DeterminePowerPlanAsync(remainingProcesses); @@ -334,11 +384,19 @@ namespace ThreadPilot.Services { Task.Run(async () => await EvaluateCurrentProcessesAsync()); } + + // Keep process monitor settings synchronized with configuration edits + _processMonitorService.UpdateSettings(); } private async void DelayedPowerPlanChangeCallback(object? state) { if (!_isRunning) return; + + if (Interlocked.Exchange(ref _pendingPowerPlanReevaluation, 0) == 0) + { + return; + } var runningProcesses = _runningAssociatedProcesses.Values.ToList(); await DeterminePowerPlanAsync(runningProcesses); @@ -472,6 +530,8 @@ namespace ThreadPilot.Services if (affinity > 0) { await _processService.SetProcessorAffinity(process, affinity); + _processService.TrackAppliedMask(process.ProcessId, coreMask.Id); + _coreMaskService.RegisterMaskApplication(process.ProcessId, coreMask.Id); _logger.LogInformation( "Applied CPU mask '{MaskName}' (affinity: 0x{Affinity:X}) to process {ProcessName} (PID: {ProcessId})", @@ -485,6 +545,15 @@ namespace ThreadPilot.Services } catch (Exception ex) { + var blockedReason = BuildAffinityOrPriorityBlockedMessage(ex, process.Name, "affinity"); + if (!string.IsNullOrEmpty(blockedReason)) + { + await _notificationService.ShowNotificationAsync( + "Affinity blocked", + blockedReason, + NotificationType.Warning); + } + _logger.LogWarning(ex, "Failed to apply CPU mask '{MaskName}' to process {ProcessName} (PID: {ProcessId})", coreMask.Name, process.Name, process.ProcessId); @@ -513,6 +582,28 @@ namespace ThreadPilot.Services { try { + var currentPriority = process.Priority; + + if (!Enum.IsDefined(typeof(ProcessPriorityClass), currentPriority)) + { + try + { + await _processService.RefreshProcessInfo(process); + currentPriority = process.Priority; + } + catch (Exception refreshEx) + { + _logger.LogDebug(refreshEx, + "Could not refresh process priority before tracking for {ProcessName} (PID: {ProcessId})", + process.Name, process.ProcessId); + } + } + + if (Enum.IsDefined(typeof(ProcessPriorityClass), currentPriority)) + { + _processService.TrackPriorityChange(process.ProcessId, currentPriority); + } + await _processService.SetProcessPriority(process, priority); _logger.LogInformation( @@ -526,6 +617,15 @@ namespace ThreadPilot.Services } catch (Exception ex) { + var blockedReason = BuildAffinityOrPriorityBlockedMessage(ex, process.Name, "priority"); + if (!string.IsNullOrEmpty(blockedReason)) + { + await _notificationService.ShowNotificationAsync( + "Priority blocked", + blockedReason, + NotificationType.Warning); + } + _logger.LogWarning(ex, "Failed to apply priority '{Priority}' to process {ProcessName} (PID: {ProcessId})", priority, process.Name, process.ProcessId); @@ -563,6 +663,24 @@ namespace ThreadPilot.Services } } + private static string BuildAffinityOrPriorityBlockedMessage(Exception ex, string processName, string operation) + { + var message = ex.Message ?? string.Empty; + var lowered = message.ToLowerInvariant(); + + if (lowered.Contains("access denied") || + lowered.Contains("anti-cheat") || + lowered.Contains("anti cheat") || + lowered.Contains("protected") || + lowered.Contains("insufficient privileges") || + ex is UnauthorizedAccessException) + { + return $"{operation} change blocked by Anti-Cheat/System for '{processName}'."; + } + + return string.Empty; + } + public void Dispose() { if (_disposed) return; @@ -571,6 +689,7 @@ namespace ThreadPilot.Services _delayTimer?.Dispose(); _powerPlanChangeSemaphore?.Dispose(); + _stateMutationSemaphore?.Dispose(); _processMonitorService?.Dispose(); _disposed = true; diff --git a/Services/ProcessMonitorService.cs b/Services/ProcessMonitorService.cs index df84d45..cb406cb 100644 --- a/Services/ProcessMonitorService.cs +++ b/Services/ProcessMonitorService.cs @@ -18,6 +18,7 @@ using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; +using System.IO; using System.Linq; using System.Management; using System.Threading; @@ -35,6 +36,7 @@ namespace ThreadPilot.Services private readonly IApplicationSettingsService _settingsService; private readonly object _lockObject = new(); private readonly ConcurrentDictionary _runningProcesses = new(); + private readonly SemaphoreSlim _wmiStartSemaphore = new(1, 1); private ManagementEventWatcher? _processStartWatcher; private ManagementEventWatcher? _processStopWatcher; @@ -49,6 +51,11 @@ namespace ThreadPilot.Services // Configuration - will be updated from settings private int _fallbackPollingIntervalMs = 5000; // Default 5 seconds private readonly int _wmiRetryDelayMs = 10000; // 10 seconds + private bool _enableWmiMonitoring = true; + private bool _enableFallbackPolling = true; + private int _isFallbackPollingInProgress; + private int _isWmiRecoveryInProgress; + private DateTime _lastWmiRetryAttemptUtc = DateTime.MinValue; public event EventHandler? ProcessStarted; public event EventHandler? ProcessStopped; @@ -64,7 +71,7 @@ namespace ThreadPilot.Services _settingsService = settingsService ?? throw new ArgumentNullException(nameof(settingsService)); // Initialize polling interval from settings - UpdatePollingInterval(); + UpdateMonitoringSettings(); } public async Task StartMonitoringAsync() @@ -78,18 +85,35 @@ namespace ThreadPilot.Services } _cancellationTokenSource = new CancellationTokenSource(); + _lastWmiRetryAttemptUtc = DateTime.MinValue; + Interlocked.Exchange(ref _isFallbackPollingInProgress, 0); + Interlocked.Exchange(ref _isWmiRecoveryInProgress, 0); + + UpdateMonitoringSettings(); // Initialize current process list await InitializeProcessListAsync(); - // Try to start WMI monitoring first - var wmiStarted = await TryStartWmiMonitoringAsync(); - - if (!wmiStarted) + bool wmiStarted = false; + if (_enableWmiMonitoring) + { + // Try to start WMI monitoring first + wmiStarted = await TryStartWmiMonitoringAsync(); + } + + if (!wmiStarted && _enableFallbackPolling) { // Fall back to polling if WMI is not available StartFallbackPolling(); } + else if (!wmiStarted && !_enableFallbackPolling) + { + var reason = _enableWmiMonitoring + ? "WMI monitoring unavailable and fallback polling is disabled" + : "Both WMI monitoring and fallback polling are disabled"; + + OnMonitoringStatusChanged(reason); + } OnMonitoringStatusChanged(); } @@ -116,6 +140,8 @@ namespace ThreadPilot.Services _cancellationTokenSource = null; _runningProcesses.Clear(); + Interlocked.Exchange(ref _isFallbackPollingInProgress, 0); + Interlocked.Exchange(ref _isWmiRecoveryInProgress, 0); OnMonitoringStatusChanged(); await Task.CompletedTask; @@ -167,10 +193,29 @@ namespace ThreadPilot.Services private async Task TryStartWmiMonitoringAsync() { + if (_disposed || !_isMonitoring || !_enableWmiMonitoring) + { + return false; + } + + await _wmiStartSemaphore.WaitAsync(); try { + if (_disposed || !_isMonitoring || !_enableWmiMonitoring) + { + return false; + } + + if (_isWmiAvailable && _processStartWatcher != null && _processStopWatcher != null) + { + return true; + } + await Task.Run(() => { + // Ensure any previous watchers are fully cleaned up before re-creating them + StopWmiWatchers(); + // Create WMI event watchers for process start and stop var startQuery = new WqlEventQuery("SELECT * FROM Win32_ProcessStartTrace"); var stopQuery = new WqlEventQuery("SELECT * FROM Win32_ProcessStopTrace"); @@ -180,12 +225,21 @@ namespace ThreadPilot.Services _processStartWatcher.EventArrived += OnProcessStarted; _processStopWatcher.EventArrived += OnProcessStopped; + _processStartWatcher.Stopped += OnWmiWatcherStopped; + _processStopWatcher.Stopped += OnWmiWatcherStopped; _processStartWatcher.Start(); _processStopWatcher.Start(); }); _isWmiAvailable = true; + + // Prefer WMI when available to reduce polling overhead + if (_isFallbackPollingActive) + { + StopFallbackPolling(); + } + OnMonitoringStatusChanged("WMI monitoring started successfully"); return true; } @@ -199,26 +253,69 @@ namespace ThreadPilot.Services return false; } + finally + { + _wmiStartSemaphore.Release(); + } } private void StartFallbackPolling() { + if (_disposed || !_isMonitoring || !_enableFallbackPolling) + { + return; + } + // Update polling interval from current settings - UpdatePollingInterval(); + UpdateMonitoringSettings(); + + if (_isFallbackPollingActive) + { + _fallbackTimer?.Change(0, _fallbackPollingIntervalMs); + return; + } _isFallbackPollingActive = true; _fallbackTimer = new System.Threading.Timer(FallbackPollingCallback, null, 0, _fallbackPollingIntervalMs); OnMonitoringStatusChanged($"Fallback polling started (interval: {_fallbackPollingIntervalMs}ms)"); } + private void OnWmiWatcherStopped(object sender, StoppedEventArgs e) + { + if (!_isMonitoring || _disposed) + { + return; + } + + _isWmiAvailable = false; + OnMonitoringStatusChanged($"WMI watcher stopped ({e.Status})"); + + if (_enableFallbackPolling && !_isFallbackPollingActive) + { + StartFallbackPolling(); + } + } + private void StopWmiWatchers() { try { + if (_processStartWatcher != null) + { + _processStartWatcher.EventArrived -= OnProcessStarted; + _processStartWatcher.Stopped -= OnWmiWatcherStopped; + } + _processStartWatcher?.Stop(); _processStartWatcher?.Dispose(); _processStartWatcher = null; + if (_processStopWatcher != null) + { + _processStopWatcher.EventArrived -= OnProcessStopped; + _processStopWatcher.Stopped -= OnWmiWatcherStopped; + } + _processStopWatcher?.Stop(); _processStopWatcher?.Dispose(); _processStopWatcher = null; @@ -236,17 +333,27 @@ namespace ThreadPilot.Services _fallbackTimer?.Dispose(); _fallbackTimer = null; _isFallbackPollingActive = false; + Interlocked.Exchange(ref _isFallbackPollingInProgress, 0); } private async void OnProcessStarted(object sender, EventArrivedEventArgs e) { + if (!_isMonitoring || _disposed) + { + return; + } + try { var processId = Convert.ToInt32(e.NewEvent["ProcessID"]); var processName = e.NewEvent["ProcessName"]?.ToString() ?? string.Empty; // Get detailed process information - var process = await CreateProcessModelFromId(processId, processName); + var process = await CreateProcessModelFromId(processId, processName) + ?? (!string.IsNullOrWhiteSpace(processName) + ? new ProcessModel { ProcessId = processId, Name = NormalizeProcessName(processName) } + : null); + if (process != null) { _runningProcesses.TryAdd(processId, process); @@ -261,6 +368,11 @@ namespace ThreadPilot.Services private void OnProcessStopped(object sender, EventArrivedEventArgs e) { + if (!_isMonitoring || _disposed) + { + return; + } + try { var processId = Convert.ToInt32(e.NewEvent["ProcessID"]); @@ -276,11 +388,24 @@ namespace ThreadPilot.Services } } - private async void FallbackPollingCallback(object? state) + private void FallbackPollingCallback(object? state) { - if (!_isMonitoring || _cancellationTokenSource?.Token.IsCancellationRequested == true) + if (!_isMonitoring || _disposed || _cancellationTokenSource?.Token.IsCancellationRequested == true) + { return; + } + // Prevent overlapping polling iterations when processing takes longer than interval + if (Interlocked.Exchange(ref _isFallbackPollingInProgress, 1) == 1) + { + return; + } + + _ = RunFallbackPollingAsync(); + } + + private async Task RunFallbackPollingAsync() + { try { var currentProcesses = await GetRunningProcessesAsync(); @@ -308,11 +433,52 @@ namespace ThreadPilot.Services ProcessStopped?.Invoke(this, new ProcessEventArgs(stoppedProcess)); } } + + // Periodically retry WMI monitoring recovery while polling is active + await TryRecoverWmiMonitoringAsync(); } catch (Exception ex) { OnMonitoringStatusChanged($"Error in fallback polling: {ex.Message}", ex); } + finally + { + Interlocked.Exchange(ref _isFallbackPollingInProgress, 0); + } + } + + private async Task TryRecoverWmiMonitoringAsync() + { + if (!_isMonitoring || _disposed || _isWmiAvailable || !_enableWmiMonitoring) + { + return; + } + + var now = DateTime.UtcNow; + if ((now - _lastWmiRetryAttemptUtc).TotalMilliseconds < _wmiRetryDelayMs) + { + return; + } + + if (Interlocked.Exchange(ref _isWmiRecoveryInProgress, 1) == 1) + { + return; + } + + _lastWmiRetryAttemptUtc = now; + + try + { + var recovered = await TryStartWmiMonitoringAsync(); + if (recovered) + { + OnMonitoringStatusChanged("WMI monitoring recovered successfully"); + } + } + finally + { + Interlocked.Exchange(ref _isWmiRecoveryInProgress, 0); + } } private async Task CreateProcessModelFromId(int processId, string processName) @@ -336,29 +502,72 @@ namespace ThreadPilot.Services _isMonitoring, _isWmiAvailable, _isFallbackPollingActive, message, error)); } - private void UpdatePollingInterval() + private void UpdateMonitoringSettings() { var settings = _settingsService.Settings; - _fallbackPollingIntervalMs = settings.FallbackPollingIntervalMs; + _fallbackPollingIntervalMs = Math.Clamp(settings.FallbackPollingIntervalMs, 1000, 60000); + _enableWmiMonitoring = settings.EnableWmiMonitoring; + _enableFallbackPolling = settings.EnableFallbackPolling; } public void UpdateSettings() { - UpdatePollingInterval(); + var previousInterval = _fallbackPollingIntervalMs; + var previousWmiEnabled = _enableWmiMonitoring; + var previousFallbackEnabled = _enableFallbackPolling; + + UpdateMonitoringSettings(); + + if (!_isMonitoring) + { + return; + } + + if (!_enableWmiMonitoring && _isWmiAvailable) + { + StopWmiWatchers(); + OnMonitoringStatusChanged("WMI monitoring disabled by settings"); + } + else if (_enableWmiMonitoring && !previousWmiEnabled && !_isWmiAvailable) + { + _ = Task.Run(async () => await TryStartWmiMonitoringAsync()); + } + + if (!_enableFallbackPolling && _isFallbackPollingActive) + { + StopFallbackPolling(); + OnMonitoringStatusChanged("Fallback polling disabled by settings"); + } + else if (_enableFallbackPolling && !previousFallbackEnabled && (!_isWmiAvailable || !_enableWmiMonitoring)) + { + StartFallbackPolling(); + } // If fallback polling is active, restart it with new interval - if (_isFallbackPollingActive && _fallbackTimer != null) + if (_isFallbackPollingActive && _fallbackTimer != null && previousInterval != _fallbackPollingIntervalMs) { _fallbackTimer.Change(0, _fallbackPollingIntervalMs); OnMonitoringStatusChanged($"Polling interval updated to {_fallbackPollingIntervalMs}ms"); } } + private static string NormalizeProcessName(string processName) + { + if (string.IsNullOrWhiteSpace(processName)) + { + return string.Empty; + } + + // Keep process naming consistent with Process.ProcessName (no extension) + return Path.GetFileNameWithoutExtension(processName.Trim()); + } + public void Dispose() { if (_disposed) return; StopMonitoringAsync().Wait(5000); // Wait up to 5 seconds for clean shutdown + _wmiStartSemaphore.Dispose(); _disposed = true; } diff --git a/Services/ProcessPowerPlanAssociationService.cs b/Services/ProcessPowerPlanAssociationService.cs index 0dd427f..98a24a1 100644 --- a/Services/ProcessPowerPlanAssociationService.cs +++ b/Services/ProcessPowerPlanAssociationService.cs @@ -18,6 +18,7 @@ using System; using System.Collections.Generic; using System.IO; using System.Linq; +using System.Text; using System.Text.Json; using System.Threading.Tasks; using ThreadPilot.Models; @@ -29,6 +30,16 @@ namespace ThreadPilot.Services /// public class ProcessPowerPlanAssociationService : IProcessPowerPlanAssociationService { + private static string LegacyConfigurationDirectory => Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Configuration"); + private static string LegacyConfigurationFilePath => Path.Combine(LegacyConfigurationDirectory, "ProcessPowerPlanAssociations.json"); + private static readonly JsonSerializerOptions JsonOptions = new() + { + WriteIndented = true, + PropertyNamingPolicy = JsonNamingPolicy.CamelCase, + PropertyNameCaseInsensitive = true, + ReadCommentHandling = JsonCommentHandling.Skip, + AllowTrailingCommas = true + }; private readonly string _configurationDirectory; private readonly string _configurationFilePath; private readonly object _lockObject = new(); @@ -41,11 +52,14 @@ namespace ThreadPilot.Services public ProcessPowerPlanAssociationService() { - _configurationDirectory = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Configuration"); + StoragePaths.EnsureAppDataDirectories(); + + _configurationDirectory = StoragePaths.ConfigurationDirectory; _configurationFilePath = Path.Combine(_configurationDirectory, "ProcessPowerPlanAssociations.json"); _configuration = new ProcessMonitorConfiguration(); EnsureConfigurationDirectoryExists(); + MigrateLegacyConfigurationIfNeeded(); } public async Task LoadConfigurationAsync() @@ -61,12 +75,13 @@ namespace ThreadPilot.Services } var json = await File.ReadAllTextAsync(_configurationFilePath); - var loadedConfig = JsonSerializer.Deserialize(json); + var loadedConfig = JsonSerializer.Deserialize(json, JsonOptions); if (loadedConfig != null) { lock (_lockObject) { + loadedConfig.Associations ??= new List(); _configuration = loadedConfig; } @@ -94,14 +109,8 @@ namespace ThreadPilot.Services configToSave.LastSavedDate = DateTime.Now; } - var options = new JsonSerializerOptions - { - WriteIndented = true, - PropertyNamingPolicy = JsonNamingPolicy.CamelCase - }; - - var json = JsonSerializer.Serialize(configToSave, options); - await File.WriteAllTextAsync(_configurationFilePath, json); + var json = JsonSerializer.Serialize(configToSave, JsonOptions); + await AtomicFileWriter.WriteAllTextAsync(_configurationFilePath, json, Encoding.UTF8); OnConfigurationChanged("Saved", null, "Configuration saved to file"); return true; @@ -141,7 +150,7 @@ namespace ThreadPilot.Services { // Check for duplicates var existing = _configuration.Associations - .FirstOrDefault(a => a.ExecutableName.Equals(association.ExecutableName, StringComparison.OrdinalIgnoreCase)); + .FirstOrDefault(a => AreAssociationsConflicting(a, association)); if (existing != null) { @@ -291,14 +300,8 @@ namespace ThreadPilot.Services configToExport = _configuration; } - var options = new JsonSerializerOptions - { - WriteIndented = true, - PropertyNamingPolicy = JsonNamingPolicy.CamelCase - }; - - var json = JsonSerializer.Serialize(configToExport, options); - await File.WriteAllTextAsync(filePath, json); + var json = JsonSerializer.Serialize(configToExport, JsonOptions); + await AtomicFileWriter.WriteAllTextAsync(filePath, json, Encoding.UTF8); OnConfigurationChanged("Exported", null, $"Configuration exported to {filePath}"); return true; @@ -317,12 +320,13 @@ namespace ThreadPilot.Services if (!File.Exists(filePath)) return false; var json = await File.ReadAllTextAsync(filePath); - var importedConfig = JsonSerializer.Deserialize(json); + var importedConfig = JsonSerializer.Deserialize(json, JsonOptions); if (importedConfig != null) { lock (_lockObject) { + importedConfig.Associations ??= new List(); _configuration = importedConfig; } @@ -348,10 +352,61 @@ namespace ThreadPilot.Services } } + private void MigrateLegacyConfigurationIfNeeded() + { + try + { + if (!File.Exists(LegacyConfigurationFilePath) || File.Exists(_configurationFilePath)) + { + return; + } + + Directory.CreateDirectory(_configurationDirectory); + File.Copy(LegacyConfigurationFilePath, _configurationFilePath); + } + catch + { + // Ignore migration failures and continue with current storage path. + } + } + private void OnConfigurationChanged(string changeType, ProcessPowerPlanAssociation? association = null, string? details = null) { ConfigurationChanged?.Invoke(this, new ConfigurationChangedEventArgs(changeType, association, details)); } + + private static bool AreAssociationsConflicting(ProcessPowerPlanAssociation existing, ProcessPowerPlanAssociation candidate) + { + var existingName = NormalizeExecutableName(existing.ExecutableName); + var candidateName = NormalizeExecutableName(candidate.ExecutableName); + + if (!string.Equals(existingName, candidateName, StringComparison.OrdinalIgnoreCase)) + { + return false; + } + + if (existing.MatchByPath || candidate.MatchByPath) + { + var existingPath = existing.ExecutablePath?.Trim() ?? string.Empty; + var candidatePath = candidate.ExecutablePath?.Trim() ?? string.Empty; + + return string.Equals(existingPath, candidatePath, StringComparison.OrdinalIgnoreCase) && + existing.MatchByPath == candidate.MatchByPath; + } + + // Name-only associations conflict by executable name + return true; + } + + private static string NormalizeExecutableName(string? executableName) + { + if (string.IsNullOrWhiteSpace(executableName)) + { + return string.Empty; + } + + return Path.GetFileNameWithoutExtension(executableName.Trim()); + } } } diff --git a/Services/ProcessService.cs b/Services/ProcessService.cs index c502cdd..7fb8c7e 100644 --- a/Services/ProcessService.cs +++ b/Services/ProcessService.cs @@ -20,6 +20,7 @@ using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.IO; +using System.Text; using System.Linq; using System.Text.Json; using System.Threading.Tasks; @@ -31,10 +32,11 @@ namespace ThreadPilot.Services { public class ProcessService : IProcessService { + private static string LegacyProfilesDirectory => Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Profiles"); private readonly ConcurrentDictionary _cpuSamples = new(); private readonly ConcurrentDictionary _cpuSetHandlers = new(); private readonly ILogger? _logger; - private string ProfilesDirectory => Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Profiles"); + private string ProfilesDirectory => StoragePaths.ProfilesDirectory; private bool _useCpuSets = true; // Enable CPU Sets by default // Tracking for cleanup on exit @@ -45,6 +47,9 @@ namespace ThreadPilot.Services { _logger = logger; + StoragePaths.EnsureAppDataDirectories(); + MigrateLegacyProfilesIfNeeded(); + if (!Directory.Exists(ProfilesDirectory)) { Directory.CreateDirectory(ProfilesDirectory); @@ -78,6 +83,13 @@ namespace ThreadPilot.Services public DateTime Timestamp { get; set; } } + private sealed class ProcessProfileSnapshot + { + public string ProcessName { get; set; } = string.Empty; + public ProcessPriorityClass Priority { get; set; } + public long ProcessorAffinity { get; set; } + } + private double CalculateCpuUsage(Process process) { try @@ -299,7 +311,8 @@ namespace ThreadPilot.Services }; var filePath = Path.Combine(ProfilesDirectory, $"{profileName}.json"); - await File.WriteAllTextAsync(filePath, JsonSerializer.Serialize(profile)); + var json = JsonSerializer.Serialize(profile, new JsonSerializerOptions { WriteIndented = true }); + await AtomicFileWriter.WriteAllTextAsync(filePath, json, Encoding.UTF8); return true; } @@ -310,16 +323,21 @@ namespace ThreadPilot.Services return false; var content = await File.ReadAllTextAsync(filePath); - var profile = JsonSerializer.Deserialize(content); - - if (profile != null) + var profile = JsonSerializer.Deserialize(content, new JsonSerializerOptions { - await SetProcessPriority(process, profile.Priority); - await SetProcessorAffinity(process, profile.ProcessorAffinity); - return true; + PropertyNameCaseInsensitive = true, + ReadCommentHandling = JsonCommentHandling.Skip, + AllowTrailingCommas = true + }); + + if (profile == null) + { + return false; } - return false; + await SetProcessPriority(process, profile.Priority); + await SetProcessorAffinity(process, profile.ProcessorAffinity); + return true; } public async Task RefreshProcessInfo(ProcessModel process) @@ -788,6 +806,37 @@ namespace ThreadPilot.Services int coreCount = Environment.ProcessorCount; return coreCount >= 64 ? -1L : (1L << coreCount) - 1; } + + private void MigrateLegacyProfilesIfNeeded() + { + try + { + if (!Directory.Exists(LegacyProfilesDirectory)) + { + return; + } + + Directory.CreateDirectory(ProfilesDirectory); + var legacyFiles = Directory.GetFiles(LegacyProfilesDirectory, "*.json"); + foreach (var legacyFile in legacyFiles) + { + var destinationFile = Path.Combine(ProfilesDirectory, Path.GetFileName(legacyFile)); + if (!File.Exists(destinationFile)) + { + File.Copy(legacyFile, destinationFile); + } + } + + if (legacyFiles.Length > 0) + { + _logger?.LogInformation("Migrated {Count} legacy profile files to AppData storage", legacyFiles.Length); + } + } + catch (Exception ex) + { + _logger?.LogWarning(ex, "Failed to migrate legacy profile files"); + } + } } /// diff --git a/Services/ServiceConfiguration.cs b/Services/ServiceConfiguration.cs index f4d3e30..93bdf92 100644 --- a/Services/ServiceConfiguration.cs +++ b/Services/ServiceConfiguration.cs @@ -125,6 +125,7 @@ namespace ThreadPilot.Services { // Application configuration and settings services.AddSingleton(); + services.AddSingleton(); // User interface services services.AddSingleton(); diff --git a/Services/SmartNotificationService.cs b/Services/SmartNotificationService.cs index e746ad6..42f9f12 100644 --- a/Services/SmartNotificationService.cs +++ b/Services/SmartNotificationService.cs @@ -196,11 +196,7 @@ namespace ThreadPilot.Services var pending = new List(); // Add queued notifications - while (_notificationQueue.TryDequeue(out var notification)) - { - pending.Add(notification); - _notificationQueue.Enqueue(notification); // Put it back - } + pending.AddRange(_notificationQueue.ToArray()); // Add scheduled notifications pending.AddRange(_scheduledNotifications.Values); diff --git a/Services/StoragePaths.cs b/Services/StoragePaths.cs new file mode 100644 index 0000000..7e13f3a --- /dev/null +++ b/Services/StoragePaths.cs @@ -0,0 +1,42 @@ +/* + * ThreadPilot - Advanced Windows Process and Power Plan Manager + * Copyright (C) 2025 Prime Build + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, version 3 only. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +using System; +using System.IO; + +namespace ThreadPilot.Services +{ + internal static class StoragePaths + { + public static string AppDataRoot { get; } = Path.Combine( + Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), + "ThreadPilot"); + + public static string SettingsFilePath => Path.Combine(AppDataRoot, "settings.json"); + public static string ProfilesDirectory => Path.Combine(AppDataRoot, "Profiles"); + public static string ConfigurationDirectory => Path.Combine(AppDataRoot, "Configuration"); + public static string CoreMasksFilePath => Path.Combine(AppDataRoot, "core_masks.json"); + public static string PowerPlansDirectory => Path.Combine(AppDataRoot, "Powerplans"); + + public static void EnsureAppDataDirectories() + { + Directory.CreateDirectory(AppDataRoot); + Directory.CreateDirectory(ProfilesDirectory); + Directory.CreateDirectory(ConfigurationDirectory); + Directory.CreateDirectory(PowerPlansDirectory); + } + } +} diff --git a/Services/SystemTrayService.cs b/Services/SystemTrayService.cs index e4b62cd..5261ed9 100644 --- a/Services/SystemTrayService.cs +++ b/Services/SystemTrayService.cs @@ -53,6 +53,7 @@ namespace ThreadPilot.Services public event EventHandler? PowerPlanChangeRequested; public event EventHandler? ProfileApplicationRequested; public event EventHandler? PerformanceDashboardRequested; + public event EventHandler? DashboardRequested; public SystemTrayService(ILogger logger) { @@ -106,6 +107,26 @@ namespace ThreadPilot.Services { _contextMenu = new ContextMenuStrip(); + var openDashboardMenuItem = new ToolStripMenuItem("Open Dashboard") + { + Font = new Font(_contextMenu.Font, FontStyle.Bold) + }; + openDashboardMenuItem.Click += OnDashboardClick; + _contextMenu.Items.Add(openDashboardMenuItem); + + _performanceMenuItem = new ToolStripMenuItem("Open Performance") + { + Font = new Font(_contextMenu.Font, FontStyle.Bold) + }; + _performanceMenuItem.Click += OnPerformanceDashboardClick; + _contextMenu.Items.Add(_performanceMenuItem); + + _monitoringToggleMenuItem = new ToolStripMenuItem("Pause Monitoring"); + _monitoringToggleMenuItem.Click += OnMonitoringToggleClick; + _contextMenu.Items.Add(_monitoringToggleMenuItem); + + _contextMenu.Items.Add(new ToolStripSeparator()); + // System status (disabled, for display only) _systemStatusMenuItem = new ToolStripMenuItem("System Status") { @@ -122,18 +143,14 @@ namespace ThreadPilot.Services }; _contextMenu.Items.Add(_selectedProcessMenuItem); - // Separator - _contextMenu.Items.Add(new ToolStripSeparator()); - // Quick apply command - _quickApplyMenuItem = new ToolStripMenuItem("⚑ Quick Apply Affinity & Power Plan") + _quickApplyMenuItem = new ToolStripMenuItem("Quick Apply to Selected Process") { Enabled = false }; _quickApplyMenuItem.Click += OnQuickApplyClick; _contextMenu.Items.Add(_quickApplyMenuItem); - // Separator _contextMenu.Items.Add(new ToolStripSeparator()); // Power Plans submenu @@ -144,37 +161,18 @@ namespace ThreadPilot.Services _profilesMenuItem = new ToolStripMenuItem("πŸ“‹ Profiles"); _contextMenu.Items.Add(_profilesMenuItem); - // Performance Dashboard - _performanceMenuItem = new ToolStripMenuItem("πŸ“Š Performance Dashboard"); - _performanceMenuItem.Click += OnPerformanceDashboardClick; - _contextMenu.Items.Add(_performanceMenuItem); - - // Separator - _contextMenu.Items.Add(new ToolStripSeparator()); - - // Monitoring toggle - _monitoringToggleMenuItem = new ToolStripMenuItem("πŸ” Disable Process Monitoring"); - _monitoringToggleMenuItem.Click += OnMonitoringToggleClick; - _contextMenu.Items.Add(_monitoringToggleMenuItem); - - // Separator _contextMenu.Items.Add(new ToolStripSeparator()); // Settings - _settingsMenuItem = new ToolStripMenuItem("βš™οΈ Settings..."); + _settingsMenuItem = new ToolStripMenuItem("Settings"); _settingsMenuItem.Click += OnSettingsClick; _contextMenu.Items.Add(_settingsMenuItem); - // Show main window - var showMenuItem = new ToolStripMenuItem("πŸͺŸ Show ThreadPilot"); - showMenuItem.Click += OnShowMainWindowClick; - _contextMenu.Items.Add(showMenuItem); - // Separator _contextMenu.Items.Add(new ToolStripSeparator()); // Exit - var exitMenuItem = new ToolStripMenuItem("❌ Exit"); + var exitMenuItem = new ToolStripMenuItem("Exit"); exitMenuItem.Click += OnExitClick; _contextMenu.Items.Add(exitMenuItem); } @@ -227,7 +225,7 @@ namespace ThreadPilot.Services { _selectedProcessMenuItem.Text = "No process selected"; _quickApplyMenuItem.Enabled = false; - _quickApplyMenuItem.Text = "Quick Apply Affinity & Power Plan"; + _quickApplyMenuItem.Text = "Quick Apply to Selected Process"; } } @@ -241,9 +239,9 @@ namespace ThreadPilot.Services QuickApplyRequested?.Invoke(this, EventArgs.Empty); } - private void OnShowMainWindowClick(object? sender, EventArgs e) + private void OnDashboardClick(object? sender, EventArgs e) { - ShowMainWindowRequested?.Invoke(this, EventArgs.Empty); + DashboardRequested?.Invoke(this, EventArgs.Empty); } private void OnExitClick(object? sender, EventArgs e) @@ -291,7 +289,7 @@ namespace ThreadPilot.Services if (_monitoringToggleMenuItem != null) { - _monitoringToggleMenuItem.Text = isMonitoring ? "Disable Process Monitoring" : "Enable Process Monitoring"; + _monitoringToggleMenuItem.Text = isMonitoring ? "Pause Monitoring" : "Resume Monitoring"; _monitoringToggleMenuItem.Enabled = isWmiAvailable; } diff --git a/Services/SystemTweaksService.cs b/Services/SystemTweaksService.cs index d8218ef..3ae70f6 100644 --- a/Services/SystemTweaksService.cs +++ b/Services/SystemTweaksService.cs @@ -19,6 +19,7 @@ using System.Diagnostics; using System.IO; using System.Management; using System.ServiceProcess; +using System.Text.RegularExpressions; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using Microsoft.Win32; @@ -30,6 +31,15 @@ namespace ThreadPilot.Services /// public class SystemTweaksService : ISystemTweaksService { + private static readonly string BcdEditExecutablePath = Path.Combine(Environment.SystemDirectory, "bcdedit.exe"); + private static readonly string PowerCfgExecutablePath = Path.Combine(Environment.SystemDirectory, "powercfg.exe"); + private static readonly Regex HexValueRegex = new("0x([0-9a-fA-F]+)", RegexOptions.Compiled); + private const string ProcessorSubgroupAlias = "SUB_PROCESSOR"; + private const string CoreParkingSettingAlias = "CPMINCORES"; + private const string CStatesSettingAlias = "IDLEDISABLE"; + private const string CoreParkingVisibilityKeyPath = @"SYSTEM\CurrentControlSet\Control\Power\PowerSettings\54533251-82be-4824-96c1-47b60b740d00\0cc5b647-c1df-4637-891a-dec35c318583"; + private const string PriorityControlKeyPath = @"SYSTEM\CurrentControlSet\Control\PriorityControl"; + private const string PrioritySeparationValueName = "Win32PrioritySeparation"; private readonly ILogger _logger; private readonly IElevationService _elevationService; @@ -47,20 +57,22 @@ namespace ThreadPilot.Services { try { - using var key = Registry.LocalMachine.OpenSubKey(@"SYSTEM\CurrentControlSet\Control\Power\PowerSettings\54533251-82be-4824-96c1-47b60b740d00\0cc5b647-c1df-4637-891a-dec35c318583"); - if (key == null) + await EnsurePowerSettingVisibleAsync(ProcessorSubgroupAlias, CoreParkingSettingAlias); + + var acValue = await GetPowerCfgAcSettingValueAsync(ProcessorSubgroupAlias, CoreParkingSettingAlias); + if (!acValue.HasValue) { - return new TweakStatus { IsAvailable = false, ErrorMessage = "Core Parking registry key not found" }; + return new TweakStatus { IsAvailable = false, ErrorMessage = "Could not query Core Parking value via powercfg" }; } - var attributes = key.GetValue("Attributes"); - var isEnabled = attributes?.ToString() != "1"; // 1 = hidden (disabled), 2 = visible (enabled) + // ON = disable parking (keep all cores unparked, typically 100) + var isEnabled = acValue.Value >= 100; return new TweakStatus { IsEnabled = isEnabled, IsAvailable = true, - Description = "Controls CPU core parking for power management" + Description = "ON disables core parking (all cores unparked); OFF allows parking" }; } catch (Exception ex) @@ -80,15 +92,32 @@ namespace ThreadPilot.Services return false; } - using var key = Registry.LocalMachine.OpenSubKey(@"SYSTEM\CurrentControlSet\Control\Power\PowerSettings\54533251-82be-4824-96c1-47b60b740d00\0cc5b647-c1df-4637-891a-dec35c318583", true); - if (key == null) + await EnsurePowerSettingVisibleAsync(ProcessorSubgroupAlias, CoreParkingSettingAlias); + + var acValue = enabled ? 100 : 10; + var setValueResult = await RunProcessAsync(PowerCfgExecutablePath, + $"-setacvalueindex SCHEME_CURRENT {ProcessorSubgroupAlias} {CoreParkingSettingAlias} {acValue}"); + if (setValueResult.ExitCode != 0) { - _logger.LogError("Core Parking registry key not found"); + _logger.LogError("Failed setting Core Parking AC value. ExitCode={ExitCode}, Error={Error}", + setValueResult.ExitCode, setValueResult.StandardError); return false; } - // Set attributes: 1 = hidden (disabled), 2 = visible (enabled) - key.SetValue("Attributes", enabled ? 2 : 1, RegistryValueKind.DWord); + var activateResult = await RunProcessAsync(PowerCfgExecutablePath, "/setactive SCHEME_CURRENT"); + if (activateResult.ExitCode != 0) + { + _logger.LogError("Failed activating current power scheme after Core Parking change. ExitCode={ExitCode}, Error={Error}", + activateResult.ExitCode, activateResult.StandardError); + return false; + } + + // Keep setting visible in Windows advanced power UI if the key exists. + using var visibilityKey = Registry.LocalMachine.OpenSubKey(CoreParkingVisibilityKeyPath, true); + if (visibilityKey != null) + { + visibilityKey.SetValue("Attributes", 2, RegistryValueKind.DWord); + } var status = await GetCoreParkingStatusAsync(); TweakStatusChanged?.Invoke(this, new TweakStatusChangedEventArgs("CoreParking", status)); @@ -107,21 +136,22 @@ namespace ThreadPilot.Services { try { - // Check C-States via registry - using var key = Registry.LocalMachine.OpenSubKey(@"SYSTEM\CurrentControlSet\Control\Processor"); - if (key == null) + await EnsurePowerSettingVisibleAsync(ProcessorSubgroupAlias, CStatesSettingAlias); + + var acValue = await GetPowerCfgAcSettingValueAsync(ProcessorSubgroupAlias, CStatesSettingAlias); + if (!acValue.HasValue) { - return new TweakStatus { IsAvailable = false, ErrorMessage = "Processor registry key not found" }; + return new TweakStatus { IsAvailable = false, ErrorMessage = "Could not query C-States value via powercfg" }; } - var cStateDisable = key.GetValue("CStateDisable"); - var isEnabled = cStateDisable?.ToString() != "1"; // 1 = disabled, 0 or null = enabled + // ON = enable C-States (IDLEDISABLE=0), OFF = disable C-States (IDLEDISABLE=1) + var isEnabled = acValue.Value == 0; return new TweakStatus { IsEnabled = isEnabled, IsAvailable = true, - Description = "Controls CPU C-States for power management" + Description = "ON enables C-States; OFF disables C-States for lower latency" }; } catch (Exception ex) @@ -141,15 +171,25 @@ namespace ThreadPilot.Services return false; } - using var key = Registry.LocalMachine.OpenSubKey(@"SYSTEM\CurrentControlSet\Control\Processor", true); - if (key == null) + await EnsurePowerSettingVisibleAsync(ProcessorSubgroupAlias, CStatesSettingAlias); + + var value = enabled ? 0 : 1; + var setValueResult = await RunProcessAsync(PowerCfgExecutablePath, + $"-setacvalueindex SCHEME_CURRENT {ProcessorSubgroupAlias} {CStatesSettingAlias} {value}"); + if (setValueResult.ExitCode != 0) { - _logger.LogError("Processor registry key not found"); + _logger.LogError("Failed setting C-States AC value. ExitCode={ExitCode}, Error={Error}", + setValueResult.ExitCode, setValueResult.StandardError); return false; } - // Set CStateDisable: 1 = disabled, 0 = enabled - key.SetValue("CStateDisable", enabled ? 0 : 1, RegistryValueKind.DWord); + var activateResult = await RunProcessAsync(PowerCfgExecutablePath, "/setactive SCHEME_CURRENT"); + if (activateResult.ExitCode != 0) + { + _logger.LogError("Failed activating current power scheme after C-States change. ExitCode={ExitCode}, Error={Error}", + activateResult.ExitCode, activateResult.StandardError); + return false; + } var status = await GetCStatesStatusAsync(); TweakStatusChanged?.Invoke(this, new TweakStatusChangedEventArgs("CStates", status)); @@ -169,7 +209,8 @@ namespace ThreadPilot.Services try { using var serviceController = new ServiceController("SysMain"); - var isEnabled = serviceController.Status == System.ServiceProcess.ServiceControllerStatus.Running; + serviceController.Refresh(); + var isEnabled = serviceController.StartType != ServiceStartMode.Disabled; var isAvailable = true; return new TweakStatus @@ -197,16 +238,23 @@ namespace ThreadPilot.Services } using var serviceController = new ServiceController("SysMain"); + if (!SetServiceStartMode("SysMain", enabled ? ServiceStartMode.Automatic : ServiceStartMode.Disabled)) + { + _logger.LogError("Failed to set SysMain startup mode"); + return false; + } + + serviceController.Refresh(); - if (enabled && serviceController.Status != System.ServiceProcess.ServiceControllerStatus.Running) + if (enabled && serviceController.Status == ServiceControllerStatus.Stopped) { serviceController.Start(); - serviceController.WaitForStatus(System.ServiceProcess.ServiceControllerStatus.Running, TimeSpan.FromSeconds(30)); + serviceController.WaitForStatus(ServiceControllerStatus.Running, TimeSpan.FromSeconds(30)); } - else if (!enabled && serviceController.Status == System.ServiceProcess.ServiceControllerStatus.Running) + else if (!enabled && (serviceController.Status == ServiceControllerStatus.Running || serviceController.Status == ServiceControllerStatus.Paused)) { serviceController.Stop(); - serviceController.WaitForStatus(System.ServiceProcess.ServiceControllerStatus.Stopped, TimeSpan.FromSeconds(30)); + serviceController.WaitForStatus(ServiceControllerStatus.Stopped, TimeSpan.FromSeconds(30)); } var status = await GetSysMainStatusAsync(); @@ -292,14 +340,15 @@ namespace ThreadPilot.Services return new TweakStatus { IsAvailable = false, ErrorMessage = "Power Throttling not available on this system" }; } - var powerThrottlingOff = key.GetValue("PowerThrottlingOff"); - var isEnabled = powerThrottlingOff?.ToString() != "1"; // 1 = disabled, 0 or null = enabled + var powerThrottlingOff = ReadRegistryIntValue(key, "PowerThrottlingOff"); + // ON = disable throttling (PowerThrottlingOff=1) + var isEnabled = powerThrottlingOff.GetValueOrDefault(0) == 1; return new TweakStatus { IsEnabled = isEnabled, IsAvailable = true, - Description = "Windows Power Throttling for energy efficiency" + Description = "ON disables Windows Power Throttling for sustained performance" }; } catch (Exception ex) @@ -326,8 +375,8 @@ namespace ThreadPilot.Services return false; } - // Set PowerThrottlingOff: 1 = disabled, 0 = enabled - key.SetValue("PowerThrottlingOff", enabled ? 0 : 1, RegistryValueKind.DWord); + // Set PowerThrottlingOff: 1 = throttling disabled, 0 = throttling enabled + key.SetValue("PowerThrottlingOff", enabled ? 1 : 0, RegistryValueKind.DWord); var status = await GetPowerThrottlingStatusAsync(); TweakStatusChanged?.Invoke(this, new TweakStatusChangedEventArgs("PowerThrottling", status)); @@ -349,7 +398,7 @@ namespace ThreadPilot.Services // Check HPET status via bcdedit var processInfo = new ProcessStartInfo { - FileName = "bcdedit", + FileName = BcdEditExecutablePath, Arguments = "/enum", UseShellExecute = false, RedirectStandardOutput = true, @@ -365,7 +414,15 @@ namespace ThreadPilot.Services var output = await process.StandardOutput.ReadToEndAsync(); await process.WaitForExitAsync(); - var isEnabled = !output.Contains("useplatformclock") || output.Contains("useplatformclock Yes"); + var platformClockLine = output.Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries) + .FirstOrDefault(l => l.TrimStart().StartsWith("useplatformclock", StringComparison.OrdinalIgnoreCase)); + + // ON = disable HPET (useplatformclock removed/absent) + var isEnabled = true; + if (!string.IsNullOrWhiteSpace(platformClockLine)) + { + isEnabled = !platformClockLine.TrimEnd().EndsWith("Yes", StringComparison.OrdinalIgnoreCase); + } return new TweakStatus { @@ -391,10 +448,11 @@ namespace ThreadPilot.Services return false; } - var arguments = enabled ? "/set useplatformclock true" : "/set useplatformclock false"; + // ON = disable HPET (/deletevalue), OFF = force HPET (/set true) + var arguments = enabled ? "/deletevalue useplatformclock" : "/set useplatformclock true"; var processInfo = new ProcessStartInfo { - FileName = "bcdedit", + FileName = BcdEditExecutablePath, Arguments = arguments, UseShellExecute = false, RedirectStandardOutput = true, @@ -431,20 +489,20 @@ namespace ThreadPilot.Services { try { - using var key = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion\Multimedia\SystemProfile\Tasks\Games"); + using var key = Registry.LocalMachine.OpenSubKey(PriorityControlKeyPath); if (key == null) { - return new TweakStatus { IsAvailable = false, ErrorMessage = "Games scheduling registry key not found" }; + return new TweakStatus { IsAvailable = false, ErrorMessage = "PriorityControl registry key not found" }; } - var priority = key.GetValue("Priority"); - var isEnabled = priority?.ToString() == "6"; // 6 = High priority + var rawValue = ReadRegistryIntValue(key, PrioritySeparationValueName); + var isEnabled = rawValue.GetValueOrDefault(2) == 38; return new TweakStatus { IsEnabled = isEnabled, IsAvailable = true, - Description = "High scheduling priority for gaming applications" + Description = "ON applies high foreground boost (Win32PrioritySeparation=38)" }; } catch (Exception ex) @@ -464,15 +522,15 @@ namespace ThreadPilot.Services return false; } - using var key = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion\Multimedia\SystemProfile\Tasks\Games", true); + using var key = Registry.LocalMachine.OpenSubKey(PriorityControlKeyPath, true); if (key == null) { - _logger.LogError("Games scheduling registry key not found"); + _logger.LogError("PriorityControl registry key not found"); return false; } - // Set Priority: 6 = High, 2 = Normal - key.SetValue("Priority", enabled ? 6 : 2, RegistryValueKind.DWord); + // ON = 38 (Short, Variable, High), OFF = 2 (default/minimal boost) + key.SetValue(PrioritySeparationValueName, enabled ? 38 : 2, RegistryValueKind.DWord); var status = await GetHighSchedulingCategoryStatusAsync(); TweakStatusChanged?.Invoke(this, new TweakStatusChangedEventArgs("HighSchedulingCategory", status)); @@ -487,6 +545,129 @@ namespace ThreadPilot.Services } } + private bool SetServiceStartMode(string serviceName, ServiceStartMode mode) + { + var startModeValue = mode switch + { + ServiceStartMode.Automatic => "auto", + ServiceStartMode.Manual => "demand", + ServiceStartMode.Disabled => "disabled", + _ => "demand" + }; + + var processInfo = new ProcessStartInfo + { + FileName = Path.Combine(Environment.SystemDirectory, "sc.exe"), + Arguments = $"config \"{serviceName}\" start= {startModeValue}", + UseShellExecute = false, + RedirectStandardOutput = true, + RedirectStandardError = true, + CreateNoWindow = true + }; + + using var process = Process.Start(processInfo); + if (process == null) + { + _logger.LogError("Could not start sc.exe to update service start mode for {ServiceName}", serviceName); + return false; + } + + process.WaitForExit(); + if (process.ExitCode != 0) + { + var error = process.StandardError.ReadToEnd(); + _logger.LogWarning("Failed to update service start mode for {ServiceName}. ExitCode={ExitCode}, Error={Error}", + serviceName, process.ExitCode, error); + return false; + } + + return true; + } + + private async Task EnsurePowerSettingVisibleAsync(string subgroupAlias, string settingAlias) + { + var attributesResult = await RunProcessAsync(PowerCfgExecutablePath, + $"-attributes {subgroupAlias} {settingAlias} -ATTRIB_HIDE"); + + if (attributesResult.ExitCode != 0) + { + _logger.LogDebug("Could not unhide power setting {Subgroup}/{Setting}. ExitCode={ExitCode}, Error={Error}", + subgroupAlias, settingAlias, attributesResult.ExitCode, attributesResult.StandardError); + } + } + + private async Task GetPowerCfgAcSettingValueAsync(string subgroupAlias, string settingAlias) + { + var queryResult = await RunProcessAsync(PowerCfgExecutablePath, + $"-query SCHEME_CURRENT {subgroupAlias} {settingAlias}"); + + if (queryResult.ExitCode != 0) + { + _logger.LogWarning("powercfg query failed for {Subgroup}/{Setting}. ExitCode={ExitCode}, Error={Error}", + subgroupAlias, settingAlias, queryResult.ExitCode, queryResult.StandardError); + return null; + } + + var line = queryResult.StandardOutput + .Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries) + .FirstOrDefault(l => l.Contains("Current AC Power Setting Index", StringComparison.OrdinalIgnoreCase)); + if (string.IsNullOrWhiteSpace(line)) + { + return null; + } + + var match = HexValueRegex.Match(line); + if (!match.Success) + { + return null; + } + + return int.TryParse(match.Groups[1].Value, System.Globalization.NumberStyles.HexNumber, + System.Globalization.CultureInfo.InvariantCulture, out var parsed) + ? parsed + : null; + } + + private static async Task RunProcessAsync(string fileName, string arguments) + { + var processInfo = new ProcessStartInfo + { + FileName = fileName, + Arguments = arguments, + UseShellExecute = false, + RedirectStandardOutput = true, + RedirectStandardError = true, + CreateNoWindow = true + }; + + using var process = Process.Start(processInfo); + if (process == null) + { + return new ProcessResult(-1, string.Empty, "Could not start process"); + } + + var outputTask = process.StandardOutput.ReadToEndAsync(); + var errorTask = process.StandardError.ReadToEndAsync(); + await process.WaitForExitAsync(); + + return new ProcessResult(process.ExitCode, await outputTask, await errorTask); + } + + private static int? ReadRegistryIntValue(RegistryKey key, string valueName) + { + var raw = key.GetValue(valueName); + return raw switch + { + int intValue => intValue, + uint uintValue => unchecked((int)uintValue), + long longValue when longValue >= int.MinValue && longValue <= int.MaxValue => (int)longValue, + string stringValue when int.TryParse(stringValue, out var parsed) => parsed, + _ => null + }; + } + + private readonly record struct ProcessResult(int ExitCode, string StandardOutput, string StandardError); + public async Task GetMenuShowDelayStatusAsync() { try diff --git a/Services/ThemeService.cs b/Services/ThemeService.cs new file mode 100644 index 0000000..edc07ef --- /dev/null +++ b/Services/ThemeService.cs @@ -0,0 +1,74 @@ +/* + * ThreadPilot - Advanced Windows Process and Power Plan Manager + * Copyright (C) 2025 Prime Build + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, version 3 only. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +using System; +using System.Windows; +using Microsoft.Extensions.Logging; + +namespace ThreadPilot.Services +{ + public class ThemeService : IThemeService + { + private const string LightThemeDictionaryPath = "Themes/FluentLight.xaml"; + private const string DarkThemeDictionaryPath = "Themes/FluentDark.xaml"; + + private readonly ILogger _logger; + private ResourceDictionary? _activeThemeDictionary; + + public bool IsDarkTheme { get; private set; } + + public ThemeService(ILogger logger) + { + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); + } + + public void ApplyTheme(bool useDarkTheme) + { + var targetUri = new Uri(useDarkTheme ? DarkThemeDictionaryPath : LightThemeDictionaryPath, UriKind.Relative); + + var appResources = System.Windows.Application.Current?.Resources; + if (appResources == null) + { + return; + } + + try + { + for (int i = appResources.MergedDictionaries.Count - 1; i >= 0; i--) + { + var dictionary = appResources.MergedDictionaries[i]; + var source = dictionary.Source?.OriginalString; + if (string.Equals(source, LightThemeDictionaryPath, StringComparison.OrdinalIgnoreCase) || + string.Equals(source, DarkThemeDictionaryPath, StringComparison.OrdinalIgnoreCase)) + { + appResources.MergedDictionaries.RemoveAt(i); + } + } + + _activeThemeDictionary = null; + + var nextDictionary = new ResourceDictionary { Source = targetUri }; + appResources.MergedDictionaries.Insert(0, nextDictionary); + _activeThemeDictionary = nextDictionary; + IsDarkTheme = useDarkTheme; + } + catch (Exception ex) + { + _logger.LogError(ex, "Failed to apply theme {ThemeUri}", targetUri); + } + } + } +} diff --git a/TestRunner.cs b/TestRunner.cs deleted file mode 100644 index 021e6a0..0000000 --- a/TestRunner.cs +++ /dev/null @@ -1,57 +0,0 @@ -/* - * ThreadPilot - Advanced Windows Process and Power Plan Manager - * Copyright (C) 2025 Prime Build - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, version 3 only. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ -using System; -using System.Threading.Tasks; -using ThreadPilot.Tests; - -namespace ThreadPilot -{ - /// - /// Simple test runner for CPU topology functionality - /// - public static class TestRunner - { - /// - /// Main test entry point - /// - public static async Task RunTests() - { - Console.WriteLine("ThreadPilot CPU Topology Test Runner"); - Console.WriteLine("===================================="); - - try - { - await CpuTopologyServiceTests.TestCpuTopologyDetection(); - - Console.WriteLine(); - - // Run Process Selection Test - var processSelectionTest = new ProcessSelectionTest(); - await processSelectionTest.RunAllTests(); - } - catch (Exception ex) - { - Console.WriteLine($"Test failed with exception: {ex.Message}"); - Console.WriteLine($"Stack trace: {ex.StackTrace}"); - } - - Console.WriteLine("\nPress any key to exit..."); - Console.ReadKey(); - } - } -} - diff --git a/Tests/TestRunner.cs b/Tests/TestRunner.cs index 5c59496..e414485 100644 --- a/Tests/TestRunner.cs +++ b/Tests/TestRunner.cs @@ -16,91 +16,44 @@ */ using System; using System.Threading.Tasks; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Logging; namespace ThreadPilot.Tests { /// - /// Test runner for validating Game Boost functionality + /// Integrated runtime test runner used by --test mode. /// public static class TestRunner { - /// - /// Runs all Game Boost integration tests - /// - public static async Task RunGameBoostTestsAsync(IServiceProvider serviceProvider) + public static async Task RunTests() { - var logger = serviceProvider.GetRequiredService>(); - - try - { - logger.LogInformation("=== Starting Game Boost Integration Tests ==="); - - var integrationTest = new GameBoostIntegrationTest(serviceProvider); - var result = await integrationTest.RunIntegrationTestAsync(); - - if (result) - { - logger.LogInformation("=== All Game Boost Tests PASSED ==="); - } - else - { - logger.LogError("=== Game Boost Tests FAILED ==="); - } - - return result; - } - catch (Exception ex) - { - logger.LogError(ex, "Test runner failed with exception"); - return false; - } - } - - /// - /// Validates that all required services are properly configured - /// - public static bool ValidateServiceConfiguration(IServiceProvider serviceProvider) - { - var logger = serviceProvider.GetRequiredService>(); + Console.WriteLine("ThreadPilot Integrated Test Runner"); + Console.WriteLine("================================"); try { - logger.LogInformation("Validating service configuration..."); + await CpuTopologyServiceTests.TestCpuTopologyDetection(); + Console.WriteLine(); - // Check all required services - var requiredServices = new[] - { - typeof(ThreadPilot.Services.IGameBoostService), - typeof(ThreadPilot.Services.ISystemTrayService), - typeof(ThreadPilot.Services.IProcessMonitorService), - typeof(ThreadPilot.Services.IApplicationSettingsService), - typeof(ThreadPilot.Services.INotificationService), - typeof(ThreadPilot.Services.IPowerPlanService), - typeof(ThreadPilot.Services.IProcessService) - }; + var processSelectionTest = new ProcessSelectionTest(); + await processSelectionTest.RunAllTests(); + Console.WriteLine(); - foreach (var serviceType in requiredServices) - { - var service = serviceProvider.GetService(serviceType); - if (service == null) - { - logger.LogError("Required service {ServiceType} is not registered", serviceType.Name); - return false; - } - logger.LogDebug("Service {ServiceType} is properly registered", serviceType.Name); - } + var executableBrowseTest = new ExecutableBrowseTest(); + var browsePassed = executableBrowseTest.RunAllTests(); + Console.WriteLine(); - logger.LogInformation("Service configuration validation passed"); - return true; + Console.WriteLine(browsePassed + ? "Integrated tests completed." + : "Integrated tests completed with failures."); } catch (Exception ex) { - logger.LogError(ex, "Service configuration validation failed"); - return false; + Console.WriteLine($"Test runner failed with exception: {ex.Message}"); + Console.WriteLine($"Stack trace: {ex.StackTrace}"); } + + Console.WriteLine("\nPress any key to exit..."); + Console.ReadKey(); } } } - diff --git a/Themes/FluentDark.xaml b/Themes/FluentDark.xaml new file mode 100644 index 0000000..eedab17 --- /dev/null +++ b/Themes/FluentDark.xaml @@ -0,0 +1,80 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Themes/FluentLight.xaml b/Themes/FluentLight.xaml new file mode 100644 index 0000000..1061f98 --- /dev/null +++ b/Themes/FluentLight.xaml @@ -0,0 +1,80 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/ThreadPilot.csproj b/ThreadPilot.csproj index 31200f1..f124a9a 100644 --- a/ThreadPilot.csproj +++ b/ThreadPilot.csproj @@ -16,10 +16,10 @@ link true CS1998;CS0067;CS0414;WFAC010;IL3000;MVVMTK0034 - 0.1.0-beta - 0.1.0.0 - 0.1.0.0 - 0.1.0-beta + 1.0.0 + 1.0.0.0 + 1.0.0.0 + 1.0.0 @@ -61,12 +61,12 @@ - + - + diff --git a/ViewModels/LogViewerViewModel.cs b/ViewModels/LogViewerViewModel.cs index 03127f6..e878a1f 100644 --- a/ViewModels/LogViewerViewModel.cs +++ b/ViewModels/LogViewerViewModel.cs @@ -282,12 +282,6 @@ namespace ThreadPilot.ViewModels try { await _loggingService.UpdateConfigurationAsync(EnableDebugLogging, MaxLogFileSizeMb, LogRetentionDays); - - _settingsService.Settings.EnableDebugLogging = EnableDebugLogging; - _settingsService.Settings.MaxLogFileSizeMb = MaxLogFileSizeMb; - _settingsService.Settings.LogRetentionDays = LogRetentionDays; - - await _settingsService.SaveSettingsAsync(); StatusMessage = "Logging settings saved successfully"; await _loggingService.LogUserActionAsync("LoggingSettingsChanged", diff --git a/ViewModels/MainWindowViewModel.cs b/ViewModels/MainWindowViewModel.cs index eaba491..0acb02d 100644 --- a/ViewModels/MainWindowViewModel.cs +++ b/ViewModels/MainWindowViewModel.cs @@ -168,8 +168,19 @@ namespace ThreadPilot public void UpdateProcessMonitoringStatus(bool isActive, string status) { - IsProcessMonitoringActive = isActive; - ProcessMonitoringStatusText = $"Process Monitoring: {status}"; + if (System.Windows.Application.Current.Dispatcher.CheckAccess()) + { + IsProcessMonitoringActive = isActive; + ProcessMonitoringStatusText = $"Process Monitoring: {status}"; + } + else + { + System.Windows.Application.Current.Dispatcher.InvokeAsync(() => + { + IsProcessMonitoringActive = isActive; + ProcessMonitoringStatusText = $"Process Monitoring: {status}"; + }); + } } protected override void OnDispose() diff --git a/ViewModels/PerformanceViewModel.cs b/ViewModels/PerformanceViewModel.cs index 93f2461..7c676e4 100644 --- a/ViewModels/PerformanceViewModel.cs +++ b/ViewModels/PerformanceViewModel.cs @@ -15,56 +15,43 @@ * along with this program. If not, see . */ using System; +using System.Collections.Generic; using System.Collections.ObjectModel; +using System.Diagnostics; 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; namespace ThreadPilot.ViewModels { - /// - /// ViewModel for the performance monitoring dashboard - /// public partial class PerformanceViewModel : BaseViewModel { private readonly IPerformanceMonitoringService _performanceService; + private readonly IProcessService _processService; + private readonly IProcessPowerPlanAssociationService _associationService; + private readonly IPowerPlanService _powerPlanService; + private readonly IProcessMonitorManagerService _processMonitorManagerService; + private readonly ISystemTweaksService _systemTweaksService; private readonly ILogger _logger; [ObservableProperty] private ObservableCollection coreUsages = new(); - [ObservableProperty] - private double totalCpuUsage; - - [ObservableProperty] - private long totalMemoryUsage; - - [ObservableProperty] - private long availableMemory; - - [ObservableProperty] - private long totalMemory; - - [ObservableProperty] - private double memoryUsagePercentage; - - [ObservableProperty] - private ProcessPerformanceInfo? topCpuProcess; - - [ObservableProperty] - private ProcessPerformanceInfo? topMemoryProcess; - [ObservableProperty] private ObservableCollection topCpuProcesses = new(); [ObservableProperty] - private ObservableCollection topMemoryProcesses = new(); + private ObservableCollection historicalData = new(); [ObservableProperty] - private int activeProcessCount; + private ObservableCollection timelineEvents = new(); + + [ObservableProperty] + private ProcessPerformanceInfo? selectedHotspotProcess; [ObservableProperty] private bool isMonitoring; @@ -76,16 +63,22 @@ namespace ThreadPilot.ViewModels private DateTime lastUpdateTime; [ObservableProperty] - private ObservableCollection historicalData = new(); + private double totalCpuUsage; [ObservableProperty] - private int updateInterval = 1000; // milliseconds + private long totalMemoryUsage; [ObservableProperty] - private bool showCoreDetails = true; + private long totalMemory; [ObservableProperty] - private bool showProcessDetails = true; + private long availableMemory; + + [ObservableProperty] + private double memoryUsagePercentage; + + [ObservableProperty] + private int activeProcessCount; [ObservableProperty] private string cpuUsageText = "0.0%"; @@ -94,133 +87,529 @@ namespace ThreadPilot.ViewModels private string memoryUsageText = "0 MB / 0 MB"; [ObservableProperty] - private string uptimeText = "00:00:00"; + private string processCountText = "0"; + + [ObservableProperty] + private string currentGlobalPowerPlanText = "Unknown"; + + [ObservableProperty] + private string monitoringStateText = "Stopped"; + + [ObservableProperty] + private string selectedProcessName = "No hotspot selected"; + + [ObservableProperty] + private string selectedProcessExecutable = "-"; + + [ObservableProperty] + private string selectedProcessCpuText = "-"; + + [ObservableProperty] + private string selectedProcessMemoryText = "-"; + + [ObservableProperty] + private string selectedProcessRuleStatus = "No linked rule"; + + [ObservableProperty] + private string selectedProcessRuleSummary = "Create a rule from this process to automate affinity and priority behavior."; + + [ObservableProperty] + private string selectedProcessLastApplyText = "No recent automation event"; + + [ObservableProperty] + private bool canCreateRuleFromSelectedProcess; + + [ObservableProperty] + private string timelineSampleCountText = "0 samples"; + + [ObservableProperty] + private string lastTimelineEventText = "No events yet"; + + [ObservableProperty] + private int updateInterval = 2000; + + [ObservableProperty] + private bool showCoreDetails = true; + + [ObservableProperty] + private bool showProcessDetails = true; + + [ObservableProperty] + private bool showOnlyRuleBackedHotspots; + + [ObservableProperty] + private bool showOnlyActionableHotspots = true; + + [ObservableProperty] + private string sortMode = "Cpu"; + + [ObservableProperty] + private string lastManualRefreshText = "Not refreshed yet"; + + [ObservableProperty] + private string processSearchText = string.Empty; + + [ObservableProperty] + private bool isRuleCreateBusy; + + private readonly Dictionary _lastRuleApplyByExecutable = new(StringComparer.OrdinalIgnoreCase); + private bool _monitoringWasActiveBeforeSuspend; public PerformanceViewModel( IPerformanceMonitoringService performanceService, + IProcessService processService, + IProcessPowerPlanAssociationService associationService, + IPowerPlanService powerPlanService, + IProcessMonitorManagerService processMonitorManagerService, + ISystemTweaksService systemTweaksService, ILogger logger) : base(logger, null) { _performanceService = performanceService; + _processService = processService; + _associationService = associationService; + _powerPlanService = powerPlanService; + _processMonitorManagerService = processMonitorManagerService; + _systemTweaksService = systemTweaksService; _logger = logger; - // Subscribe to performance updates _performanceService.MetricsUpdated += OnMetricsUpdated; + _processMonitorManagerService.ProcessPowerPlanChanged += OnProcessPowerPlanChanged; + _powerPlanService.PowerPlanChanged += OnPowerPlanChanged; + _systemTweaksService.TweakStatusChanged += OnTweakStatusChanged; + } + + public override async Task InitializeAsync() + { + try + { + SetStatus("Initializing performance dashboard..."); + + await RefreshMetricsAsync(); + await LoadHistoricalDataAsync(); + await LoadTopProcessesAsync(); + await RefreshGlobalPowerPlanAsync(); + + MonitoringStateText = IsMonitoring ? "Active" : "Stopped"; + SetStatus("Performance dashboard initialized", false); + } + catch (Exception ex) + { + SetError("Failed to initialize performance dashboard", ex); + _logger.LogError(ex, "Error initializing performance dashboard"); + } } [RelayCommand] - public async Task StartMonitoringAsync() + private async Task StartMonitoringAsync() { try { SetStatus("Starting performance monitoring..."); await _performanceService.StartMonitoringAsync(); + IsMonitoring = true; MonitoringStatusText = "Monitoring Active"; - SetStatus("Performance monitoring started"); - _logger.LogInformation("Performance monitoring started"); + MonitoringStateText = "Active"; + AddTimelineEvent("Monitoring", "Real-time monitoring started.", "Info"); + + SetStatus("Performance monitoring started", false); } catch (Exception ex) { SetError("Failed to start performance monitoring", ex); - _logger.LogError(ex, "Error starting performance monitoring"); } } [RelayCommand] - public async Task StopMonitoringAsync() + private async Task StopMonitoringAsync() { try { SetStatus("Stopping performance monitoring..."); await _performanceService.StopMonitoringAsync(); + IsMonitoring = false; MonitoringStatusText = "Monitoring Stopped"; - SetStatus("Performance monitoring stopped"); - _logger.LogInformation("Performance monitoring stopped"); + MonitoringStateText = "Stopped"; + AddTimelineEvent("Monitoring", "Real-time monitoring stopped.", "Warning"); + + SetStatus("Performance monitoring stopped", false); } catch (Exception ex) { SetError("Failed to stop performance monitoring", ex); - _logger.LogError(ex, "Error stopping performance monitoring"); } } - [RelayCommand] - public async Task RefreshMetricsAsync() + public async Task SuspendBackgroundMonitoringAsync() { try { - SetStatus("Refreshing performance metrics..."); - var metrics = await _performanceService.GetSystemMetricsAsync(); - UpdateMetrics(metrics); - SetStatus("Performance metrics refreshed"); + if (!IsMonitoring) + { + _monitoringWasActiveBeforeSuspend = false; + return; + } + + _monitoringWasActiveBeforeSuspend = true; + await _performanceService.StopMonitoringAsync(); + + IsMonitoring = false; + MonitoringStatusText = "Monitoring Paused"; + MonitoringStateText = "Paused"; + AddTimelineEvent("Monitoring", "Monitoring paused while app is minimized.", "Info"); } catch (Exception ex) { - SetError("Failed to refresh performance metrics", ex); - _logger.LogError(ex, "Error refreshing performance metrics"); + _logger.LogWarning(ex, "Failed to suspend performance monitoring while minimized"); + } + } + + public async Task ResumeBackgroundMonitoringAsync() + { + try + { + if (!_monitoringWasActiveBeforeSuspend || IsMonitoring) + { + return; + } + + await _performanceService.StartMonitoringAsync(); + + IsMonitoring = true; + MonitoringStatusText = "Monitoring Active"; + MonitoringStateText = "Active"; + AddTimelineEvent("Monitoring", "Monitoring resumed after restore.", "Info"); + _monitoringWasActiveBeforeSuspend = false; + } + catch (Exception ex) + { + _logger.LogWarning(ex, "Failed to resume performance monitoring after restore"); } } [RelayCommand] - public async Task ClearHistoricalDataAsync() + private async Task RefreshMetricsAsync() + { + try + { + SetStatus("Refreshing performance snapshot..."); + + var metrics = await _performanceService.GetSystemMetricsAsync(); + await RefreshGlobalPowerPlanAsync(); + await LoadTopProcessesAsync(); + UpdateMetrics(metrics); + + LastManualRefreshText = $"Refreshed at {DateTime.Now:HH:mm:ss}"; + SetStatus("Performance snapshot refreshed", false); + } + catch (Exception ex) + { + SetError("Failed to refresh performance snapshot", ex); + } + } + + [RelayCommand] + private async Task ClearHistoricalDataAsync() { try { await _performanceService.ClearHistoricalDataAsync(); HistoricalData.Clear(); - SetStatus("Historical data cleared"); - _logger.LogInformation("Historical performance data cleared"); + UpdateTimelineSummary(); + AddTimelineEvent("History", "Historical metrics cleared.", "Info"); + SetStatus("Historical data cleared", false); } catch (Exception ex) { SetError("Failed to clear historical data", ex); - _logger.LogError(ex, "Error clearing historical data"); } } [RelayCommand] - public async Task LoadHistoricalDataAsync() + private async Task LoadHistoricalDataAsync() { try { - SetStatus("Loading historical data..."); - var data = await _performanceService.GetHistoricalDataAsync(TimeSpan.FromHours(1)); - - // Marshal ObservableCollection assignment to UI thread to prevent cross-thread access exceptions - await System.Windows.Application.Current.Dispatcher.InvokeAsync(() => - { - HistoricalData = new ObservableCollection(data); - SetStatus($"Loaded {data.Count} historical data points"); - }); + var history = await _performanceService.GetHistoricalDataAsync(TimeSpan.FromHours(1)); + HistoricalData = new ObservableCollection(history); + UpdateTimelineSummary(); } catch (Exception ex) { SetError("Failed to load historical data", ex); - _logger.LogError(ex, "Error loading historical data"); } } [RelayCommand] - public void ToggleCoreDetails() + private async Task CreateRuleFromSelectedProcessAsync() + { + if (SelectedHotspotProcess == null || IsRuleCreateBusy) + { + return; + } + + IsRuleCreateBusy = true; + + try + { + var liveProcesses = await _processService.GetProcessesAsync(); + var targetProcess = liveProcesses.FirstOrDefault(p => p.ProcessId == SelectedHotspotProcess.ProcessId) + ?? liveProcesses.FirstOrDefault(p => + string.Equals(p.Name, SelectedHotspotProcess.ProcessName, StringComparison.OrdinalIgnoreCase)); + + if (targetProcess == null) + { + SetStatus("Selected hotspot process is no longer running", false); + return; + } + + var activePlan = await _powerPlanService.GetActivePowerPlan(); + if (activePlan == null) + { + SetStatus("Could not resolve active global power plan", false); + return; + } + + var executableName = NormalizeExecutableName(targetProcess.Name); + var existing = await _associationService.FindAssociationByExecutableAsync(executableName); + + if (existing == null) + { + var association = new ProcessPowerPlanAssociation + { + ExecutableName = executableName, + ExecutablePath = targetProcess.ExecutablePath ?? string.Empty, + PowerPlanGuid = activePlan.Guid, + PowerPlanName = activePlan.Name, + ProcessPriority = targetProcess.Priority.ToString(), + MatchByPath = !string.IsNullOrWhiteSpace(targetProcess.ExecutablePath), + Priority = 0, + Description = $"Created from Performance hotspot on {DateTime.Now:g}", + IsEnabled = true, + UpdatedAt = DateTime.UtcNow + }; + + var added = await _associationService.AddAssociationAsync(association); + if (!added) + { + SetStatus("A rule already exists and could not be created", false); + return; + } + + AddTimelineEvent("Rule", $"Rule created for {executableName} from hotspot panel.", "Success"); + SetStatus($"Rule created for {executableName} and ready for automation.", false); + } + else + { + existing.ExecutablePath = targetProcess.ExecutablePath ?? existing.ExecutablePath; + existing.PowerPlanGuid = activePlan.Guid; + existing.PowerPlanName = activePlan.Name; + existing.ProcessPriority = targetProcess.Priority.ToString(); + existing.IsEnabled = true; + existing.MatchByPath = !string.IsNullOrWhiteSpace(existing.ExecutablePath); + existing.Description = $"Updated from Performance hotspot on {DateTime.Now:g}"; + existing.UpdatedAt = DateTime.UtcNow; + + var updated = await _associationService.UpdateAssociationAsync(existing); + if (!updated) + { + SetStatus("Failed to update existing rule from hotspot", false); + return; + } + + AddTimelineEvent("Rule", $"Rule updated for {executableName} from hotspot panel.", "Success"); + SetStatus($"Rule updated for {executableName} from hotspot panel.", false); + } + + await RefreshSelectedProcessRuleImpactAsync(); + await LoadTopProcessesAsync(); + } + catch (Exception ex) + { + _logger.LogError(ex, "Failed to create or update rule from performance hotspot"); + SetError("Failed to create rule from selected hotspot", ex); + } + finally + { + IsRuleCreateBusy = false; + } + } + + [RelayCommand] + private void ToggleCoreDetails() { ShowCoreDetails = !ShowCoreDetails; } [RelayCommand] - public void ToggleProcessDetails() + private void ToggleProcessDetails() { ShowProcessDetails = !ShowProcessDetails; } + partial void OnSelectedHotspotProcessChanged(ProcessPerformanceInfo? value) + { + _ = RefreshSelectedProcessRuleImpactAsync(); + CanCreateRuleFromSelectedProcess = value != null; + } + + partial void OnShowOnlyRuleBackedHotspotsChanged(bool value) + { + _ = LoadTopProcessesAsync(); + } + + partial void OnShowOnlyActionableHotspotsChanged(bool value) + { + _ = LoadTopProcessesAsync(); + } + + partial void OnSortModeChanged(string value) + { + _ = LoadTopProcessesAsync(); + } + + partial void OnProcessSearchTextChanged(string value) + { + _ = LoadTopProcessesAsync(); + } + + private async Task RefreshSelectedProcessRuleImpactAsync() + { + try + { + if (SelectedHotspotProcess == null) + { + SelectedProcessName = "No hotspot selected"; + SelectedProcessExecutable = "-"; + SelectedProcessCpuText = "-"; + SelectedProcessMemoryText = "-"; + SelectedProcessRuleStatus = "No linked rule"; + SelectedProcessRuleSummary = "Create a rule from this process to automate affinity and priority behavior."; + SelectedProcessLastApplyText = "No recent automation event"; + return; + } + + var executableName = NormalizeExecutableName(SelectedHotspotProcess.ProcessName); + var association = await _associationService.FindAssociationByExecutableAsync(executableName); + + SelectedProcessName = SelectedHotspotProcess.ProcessName; + SelectedProcessExecutable = string.IsNullOrWhiteSpace(SelectedHotspotProcess.ExecutablePath) + ? executableName + : SelectedHotspotProcess.ExecutablePath; + SelectedProcessCpuText = $"{SelectedHotspotProcess.CpuUsage:F1}% CPU"; + SelectedProcessMemoryText = FormatBytes(SelectedHotspotProcess.MemoryUsage); + + if (association == null) + { + SelectedProcessRuleStatus = "No linked rule"; + SelectedProcessRuleSummary = "No automation rule matches this executable yet."; + } + else + { + SelectedProcessRuleStatus = association.IsEnabled ? "Linked rule is active" : "Linked rule is disabled"; + SelectedProcessRuleSummary = BuildRuleSummary(association); + } + + if (_lastRuleApplyByExecutable.TryGetValue(executableName, out var appliedAt)) + { + SelectedProcessLastApplyText = $"Last rule application: {appliedAt:HH:mm:ss}"; + } + else + { + SelectedProcessLastApplyText = "No recent automation event"; + } + } + catch (Exception ex) + { + _logger.LogError(ex, "Failed to refresh rule impact panel"); + } + } + + private async Task LoadTopProcessesAsync() + { + try + { + var topCpu = await _performanceService.GetTopCpuProcessesAsync(25); + var topMemory = await _performanceService.GetTopMemoryProcessesAsync(25); + + var merged = topCpu + .Concat(topMemory) + .GroupBy(p => p.ProcessId) + .Select(g => g.OrderByDescending(x => x.CpuUsage).First()) + .ToList(); + + var associations = await _associationService.GetAssociationsAsync(); + var associationSet = associations + .Select(a => NormalizeExecutableName(a.ExecutableName)) + .Where(name => !string.IsNullOrWhiteSpace(name)) + .ToHashSet(StringComparer.OrdinalIgnoreCase); + + IEnumerable filtered = merged; + + if (!string.IsNullOrWhiteSpace(ProcessSearchText)) + { + filtered = filtered.Where(p => p.ProcessName.Contains(ProcessSearchText, StringComparison.OrdinalIgnoreCase)); + } + + if (ShowOnlyRuleBackedHotspots) + { + filtered = filtered.Where(p => associationSet.Contains(NormalizeExecutableName(p.ProcessName))); + } + + if (ShowOnlyActionableHotspots) + { + filtered = filtered.Where(p => p.CpuUsage >= 1.0 || p.MemoryUsage >= (200L * 1024 * 1024)); + } + + filtered = SortMode switch + { + "Memory" => filtered.OrderByDescending(p => p.MemoryUsage), + "Name" => filtered.OrderBy(p => p.ProcessName), + _ => filtered.OrderByDescending(p => p.CpuUsage) + }; + + TopCpuProcesses = new ObservableCollection(filtered.Take(50)); + + if (SelectedHotspotProcess != null) + { + var refreshedSelection = TopCpuProcesses.FirstOrDefault(p => p.ProcessId == SelectedHotspotProcess.ProcessId); + if (refreshedSelection != null) + { + SelectedHotspotProcess = refreshedSelection; + } + } + + await RefreshSelectedProcessRuleImpactAsync(); + } + catch (Exception ex) + { + _logger.LogError(ex, "Error loading hotspot process lists"); + } + } + + private async Task RefreshGlobalPowerPlanAsync() + { + try + { + var activePlan = await _powerPlanService.GetActivePowerPlan(); + CurrentGlobalPowerPlanText = activePlan?.Name ?? "Unknown"; + } + catch (Exception ex) + { + _logger.LogWarning(ex, "Failed to refresh global power plan text"); + CurrentGlobalPowerPlanText = "Unknown"; + } + } + private void OnMetricsUpdated(object? sender, PerformanceMetricsUpdatedEventArgs e) { try { - // Update on UI thread - App.Current.Dispatcher.Invoke(() => + System.Windows.Application.Current.Dispatcher.Invoke(() => { UpdateMetrics(e.Metrics); + _ = LoadTopProcessesAsync(); }); } catch (Exception ex) @@ -231,136 +620,168 @@ namespace ThreadPilot.ViewModels private void UpdateMetrics(SystemPerformanceMetrics metrics) { - try + TotalCpuUsage = metrics.TotalCpuUsage; + TotalMemoryUsage = metrics.TotalMemoryUsage; + AvailableMemory = metrics.AvailableMemory; + TotalMemory = metrics.TotalMemory; + MemoryUsagePercentage = metrics.MemoryUsagePercentage; + ActiveProcessCount = metrics.ActiveProcessCount; + LastUpdateTime = metrics.Timestamp; + + CpuUsageText = $"{TotalCpuUsage:F1}%"; + MemoryUsageText = $"{FormatBytes(TotalMemoryUsage)} / {FormatBytes(TotalMemory)}"; + ProcessCountText = ActiveProcessCount.ToString(); + + CoreUsages = new ObservableCollection(metrics.CpuCoreUsages); + + if (IsMonitoring) { - TotalCpuUsage = metrics.TotalCpuUsage; - TotalMemoryUsage = metrics.TotalMemoryUsage; - AvailableMemory = metrics.AvailableMemory; - TotalMemory = metrics.TotalMemory; - MemoryUsagePercentage = metrics.MemoryUsagePercentage; - TopCpuProcess = metrics.TopCpuProcess; - TopMemoryProcess = metrics.TopMemoryProcess; - ActiveProcessCount = metrics.ActiveProcessCount; - LastUpdateTime = metrics.Timestamp; - - // Update core usages - CoreUsages.Clear(); - foreach (var coreUsage in metrics.CpuCoreUsages) + HistoricalData.Add(metrics); + while (HistoricalData.Count > 360) { - CoreUsages.Add(coreUsage); - } - - // Update formatted text - CpuUsageText = $"{TotalCpuUsage:F1}%"; - MemoryUsageText = $"{TotalMemoryUsage / (1024 * 1024):N0} MB / {TotalMemory / (1024 * 1024):N0} MB"; - UptimeText = (DateTime.UtcNow - System.Diagnostics.Process.GetCurrentProcess().StartTime).ToString(@"hh\:mm\:ss"); - - // Add to historical data if monitoring - if (IsMonitoring) - { - HistoricalData.Add(metrics); - - // Keep only last 300 entries (5 minutes at 1-second intervals) - while (HistoricalData.Count > 300) - { - HistoricalData.RemoveAt(0); - } + HistoricalData.RemoveAt(0); } } - catch (Exception ex) - { - _logger.LogError(ex, "Error updating metrics display"); - } + + UpdateTimelineSummary(); } - public override async Task InitializeAsync() + private void OnProcessPowerPlanChanged(object? sender, ProcessPowerPlanChangeEventArgs e) { try { - SetStatus("Initializing performance monitoring..."); - - // Load initial metrics - await RefreshMetricsAsync(); - - // Load top processes - await LoadTopProcessesAsync(); - - SetStatus("Performance monitoring initialized"); + var executable = NormalizeExecutableName(e.Process.Name); + _lastRuleApplyByExecutable[executable] = e.Timestamp; + + var detail = $"{e.Action}: {e.Process.Name} -> {e.NewPowerPlan?.Name ?? "Unknown"}"; + AddTimelineEvent("Rule Applied", detail, "Success"); + + _ = RefreshSelectedProcessRuleImpactAsync(); } catch (Exception ex) { - SetError("Failed to initialize performance monitoring", ex); - _logger.LogError(ex, "Error initializing performance monitoring"); + _logger.LogWarning(ex, "Failed handling process power plan change event"); } } - private async Task LoadTopProcessesAsync() + private void OnPowerPlanChanged(object? sender, PowerPlanChangedEventArgs e) { - try - { - var topCpu = await _performanceService.GetTopCpuProcessesAsync(10); - var topMemory = await _performanceService.GetTopMemoryProcessesAsync(10); - - // PERFORMANCE OPTIMIZATION: Update existing collections instead of creating new ones - await System.Windows.Application.Current.Dispatcher.InvokeAsync(() => - { - UpdateObservableCollection(TopCpuProcesses, topCpu); - UpdateObservableCollection(TopMemoryProcesses, topMemory); - }); - } - catch (Exception ex) - { - _logger.LogError(ex, "Error loading top processes"); - } + var detail = $"Global plan changed to {e.NewPowerPlan?.Name ?? "Unknown"}"; + AddTimelineEvent("Power Plan", detail, "Info"); + CurrentGlobalPowerPlanText = e.NewPowerPlan?.Name ?? "Unknown"; } - /// - /// PERFORMANCE OPTIMIZATION: Updates an ObservableCollection efficiently by only modifying changed items - /// - private void UpdateObservableCollection(ObservableCollection collection, IEnumerable newItems) where T : class + private void OnTweakStatusChanged(object? sender, TweakStatusChangedEventArgs e) { - var newList = newItems.ToList(); + var state = e.Status.IsEnabled ? "enabled" : "disabled"; + AddTimelineEvent("Tweak", $"{e.TweakName} {state}", "Warning"); + } - // Remove items that are no longer in the new list - for (int i = collection.Count - 1; i >= 0; i--) + private void AddTimelineEvent(string category, string detail, string severity) + { + var evt = new PerformanceTimelineEvent { - if (!newList.Contains(collection[i])) - { - collection.RemoveAt(i); - } + Category = category, + Detail = detail, + Severity = severity, + Timestamp = DateTime.Now + }; + + TimelineEvents.Insert(0, evt); + while (TimelineEvents.Count > 200) + { + TimelineEvents.RemoveAt(TimelineEvents.Count - 1); } - // Add or update items - for (int i = 0; i < newList.Count; i++) + UpdateTimelineSummary(); + } + + private void UpdateTimelineSummary() + { + TimelineSampleCountText = $"{HistoricalData.Count} samples"; + if (TimelineEvents.Count == 0) { - if (i < collection.Count) - { - // Update existing item if different - if (!collection[i].Equals(newList[i])) - { - collection[i] = newList[i]; - } - } - else - { - // Add new item - collection.Add(newList[i]); - } + LastTimelineEventText = "No events yet"; + return; } + + var latest = TimelineEvents[0]; + LastTimelineEventText = $"{latest.Timestamp:HH:mm:ss} - {latest.Category}"; + } + + private static string BuildRuleSummary(ProcessPowerPlanAssociation association) + { + var parts = new List(); + if (!string.IsNullOrWhiteSpace(association.PowerPlanName)) + { + parts.Add($"Plan: {association.PowerPlanName}"); + } + + if (!string.IsNullOrWhiteSpace(association.CoreMaskName)) + { + parts.Add($"Mask: {association.CoreMaskName}"); + } + + if (!string.IsNullOrWhiteSpace(association.ProcessPriority)) + { + parts.Add($"Priority: {association.ProcessPriority}"); + } + + return parts.Count == 0 + ? "Rule exists but has no advanced affinity/priority settings." + : string.Join(" | ", parts); + } + + private static string NormalizeExecutableName(string? name) + { + if (string.IsNullOrWhiteSpace(name)) + { + return string.Empty; + } + + return System.IO.Path.GetFileNameWithoutExtension(name.Trim()); + } + + private static string FormatBytes(long bytes) + { + if (bytes <= 0) + { + return "0 MB"; + } + + const double kb = 1024d; + const double mb = kb * 1024d; + const double gb = mb * 1024d; + + if (bytes >= gb) + { + return $"{bytes / gb:F2} GB"; + } + + return $"{bytes / mb:F0} MB"; } protected override void OnDispose() { _performanceService.MetricsUpdated -= OnMetricsUpdated; + _processMonitorManagerService.ProcessPowerPlanChanged -= OnProcessPowerPlanChanged; + _powerPlanService.PowerPlanChanged -= OnPowerPlanChanged; + _systemTweaksService.TweakStatusChanged -= OnTweakStatusChanged; - // Stop monitoring if active if (IsMonitoring) { - _ = Task.Run(async () => await StopMonitoringAsync()); + _ = Task.Run(async () => await _performanceService.StopMonitoringAsync()); } base.OnDispose(); } } -} + public class PerformanceTimelineEvent + { + public DateTime Timestamp { get; set; } + public string Category { get; set; } = string.Empty; + public string Detail { get; set; } = string.Empty; + public string Severity { get; set; } = "Info"; + } +} diff --git a/ViewModels/ProcessPowerPlanAssociationViewModel.cs b/ViewModels/ProcessPowerPlanAssociationViewModel.cs index 18c02b8..23ce4bd 100644 --- a/ViewModels/ProcessPowerPlanAssociationViewModel.cs +++ b/ViewModels/ProcessPowerPlanAssociationViewModel.cs @@ -159,6 +159,16 @@ namespace ThreadPilot.ViewModels UpdateServiceStatus(); } + partial void OnSelectedAssociationChanged(ProcessPowerPlanAssociation? value) + { + if (value == null) + { + return; + } + + PopulateEditorFromAssociation(value); + } + [RelayCommand] public async Task LoadDataAsync() { @@ -242,18 +252,19 @@ namespace ThreadPilot.ViewModels MatchByPath = false; Priority = 0; Description = string.Empty; + SelectedAssociation = null; await LoadDataAsync(); - SetStatus("Association added successfully"); + SetStatus("Rule created and applied successfully.", false); } else { - SetStatus("Failed to add association - it may already exist", false); + SetStatus("Failed to add rule - it may already exist", false); } } catch (Exception ex) { - SetStatus($"Error adding association: {ex.Message}", false); + SetStatus($"Error adding rule: {ex.Message}", false); } } @@ -264,26 +275,34 @@ namespace ThreadPilot.ViewModels { if (SelectedAssociation == null) { - SetStatus("Please select an association to update", false); + SetStatus("Please select a rule to update", false); return; } - SetStatus("Updating association..."); + if (string.IsNullOrWhiteSpace(NewExecutableName) || SelectedPowerPlan == null) + { + SetStatus("Executable and power plan are required", false); + return; + } + + SetStatus("Updating rule..."); + + ApplyEditorToAssociation(SelectedAssociation); var success = await _associationService.UpdateAssociationAsync(SelectedAssociation); if (success) { await LoadDataAsync(); - SetStatus("Association updated successfully"); + SetStatus("Rule updated and applied successfully.", false); } else { - SetStatus("Failed to update association", false); + SetStatus("Failed to update rule", false); } } catch (Exception ex) { - SetStatus($"Error updating association: {ex.Message}", false); + SetStatus($"Error updating rule: {ex.Message}", false); } } @@ -294,26 +313,27 @@ namespace ThreadPilot.ViewModels { if (SelectedAssociation == null) { - SetStatus("Please select an association to remove", false); + SetStatus("Please select a rule to remove", false); return; } - SetStatus("Removing association..."); + SetStatus("Removing rule..."); var success = await _associationService.RemoveAssociationAsync(SelectedAssociation.Id); if (success) { + SelectedAssociation = null; await LoadDataAsync(); - SetStatus("Association removed successfully"); + SetStatus("Rule removed successfully"); } else { - SetStatus("Failed to remove association", false); + SetStatus("Failed to remove rule", false); } } catch (Exception ex) { - SetStatus($"Error removing association: {ex.Message}", false); + SetStatus($"Error removing rule: {ex.Message}", false); } } @@ -392,7 +412,7 @@ namespace ThreadPilot.ViewModels var success = await _associationService.SaveConfigurationAsync(); if (success) { - SetStatus("Configuration saved successfully"); + SetStatus("Configuration saved and active.", false); } else { @@ -522,6 +542,43 @@ namespace ThreadPilot.ViewModels } } + private void PopulateEditorFromAssociation(ProcessPowerPlanAssociation association) + { + NewExecutableName = association.ExecutableName ?? string.Empty; + NewExecutablePath = association.ExecutablePath ?? string.Empty; + MatchByPath = association.MatchByPath; + Priority = association.Priority; + Description = association.Description ?? string.Empty; + SelectedProcessPriority = association.ProcessPriority; + + SelectedPowerPlan = AvailablePowerPlans.FirstOrDefault(p => + string.Equals(p.Guid, association.PowerPlanGuid, StringComparison.OrdinalIgnoreCase)); + + SelectedCoreMask = AvailableCoreMasks.FirstOrDefault(m => + string.Equals(m.Id, association.CoreMaskId, StringComparison.Ordinal)); + + UpdateSelectedExecutableDisplay( + NewExecutablePath, + string.IsNullOrWhiteSpace(NewExecutableName) + ? Path.GetFileName(NewExecutablePath) + : NewExecutableName); + } + + private void ApplyEditorToAssociation(ProcessPowerPlanAssociation association) + { + association.ExecutableName = NewExecutableName.Trim(); + association.ExecutablePath = NewExecutablePath.Trim(); + association.MatchByPath = MatchByPath; + association.Priority = Priority; + association.Description = Description.Trim(); + association.ProcessPriority = SelectedProcessPriority; + association.PowerPlanGuid = SelectedPowerPlan?.Guid ?? string.Empty; + association.PowerPlanName = SelectedPowerPlan?.Name ?? string.Empty; + association.CoreMaskId = SelectedCoreMask?.Id; + association.CoreMaskName = SelectedCoreMask?.Name; + association.UpdatedAt = DateTime.UtcNow; + } + private void OnProcessPowerPlanChanged(object? sender, ProcessPowerPlanChangeEventArgs e) { // Marshal UI updates to the UI thread to prevent cross-thread access exceptions diff --git a/ViewModels/ProcessViewModel.cs b/ViewModels/ProcessViewModel.cs index 51c78ac..6fcc63c 100644 --- a/ViewModels/ProcessViewModel.cs +++ b/ViewModels/ProcessViewModel.cs @@ -31,6 +31,8 @@ namespace ThreadPilot.ViewModels { public partial class ProcessViewModel : BaseViewModel { + public event EventHandler? OpenRulesRequested; + private readonly IProcessService _processService; private readonly IVirtualizedProcessService _virtualizedProcessService; private readonly ICpuTopologyService _cpuTopologyService; @@ -143,9 +145,6 @@ namespace ThreadPilot.ViewModels [ObservableProperty] private bool isVirtualizationEnabled = true; - [ObservableProperty] - private bool isBusy = false; - public ProcessViewModel( ILogger logger, IProcessService processService, @@ -904,12 +903,12 @@ namespace ThreadPilot.ViewModels // Verify the affinity was set correctly if (SelectedProcess.ProcessorAffinity == affinityMask) { - SetStatus($"Affinity set successfully for {SelectedProcess.Name} (0x{affinityMask:X})", false); + SetStatus($"Affinity applied successfully to {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); + SetStatus($"Affinity adjusted by system for {SelectedProcess.Name} to 0x{SelectedProcess.ProcessorAffinity:X}.", false); _ = _notificationService.ShowNotificationAsync("Affinity adjusted", $"{SelectedProcess.Name}: 0x{SelectedProcess.ProcessorAffinity:X}", NotificationType.Warning); } }); @@ -1176,7 +1175,7 @@ namespace ThreadPilot.ViewModels await System.Windows.Application.Current.Dispatcher.InvokeAsync(() => { - SetStatus($"Settings applied successfully to {SelectedProcess.Name}", false); + SetStatus($"Quick apply completed for {SelectedProcess.Name}.", false); }); } catch (Exception ex) @@ -1285,12 +1284,12 @@ namespace ThreadPilot.ViewModels // Verify the priority was set correctly if (SelectedProcess.Priority == priority) { - SetStatus($"Priority set successfully for {SelectedProcess.Name} to {priority}", false); + SetStatus($"Priority applied successfully to {SelectedProcess.Name}: {priority}.", false); _ = _notificationService.ShowNotificationAsync("Priority applied", $"{SelectedProcess.Name}: {priority}", NotificationType.Success); } else { - SetStatus($"Priority set for {SelectedProcess.Name} - OS adjusted to {SelectedProcess.Priority}", false); + SetStatus($"Priority adjusted by system for {SelectedProcess.Name} to {SelectedProcess.Priority}.", false); _ = _notificationService.ShowNotificationAsync("Priority adjusted", $"{SelectedProcess.Name}: {SelectedProcess.Priority}", NotificationType.Warning); } }); @@ -1783,6 +1782,12 @@ namespace ThreadPilot.ViewModels /// Saves the current process settings (affinity mask, priority, power plan) as an association /// Based on CPUSetSetter's SetMask pattern /// + [RelayCommand] + private void OpenRulesTab() + { + OpenRulesRequested?.Invoke(this, EventArgs.Empty); + } + [RelayCommand] private async Task SaveCurrentAsAssociation() { @@ -1795,7 +1800,7 @@ namespace ThreadPilot.ViewModels try { - SetStatus($"Saving association for {SelectedProcess.Name}..."); + SetStatus($"Saving rule for {SelectedProcess.Name}..."); // Get current power plan var currentPowerPlan = await _powerPlanService.GetActivePowerPlan(); @@ -1821,8 +1826,8 @@ namespace ThreadPilot.ViewModels if (success) { - SetStatus($"Association saved for {SelectedProcess.Name}", false); - await _notificationService.ShowNotificationAsync("Association Saved", + SetStatus($"Rule created for {SelectedProcess.Name} and ready for auto-apply.", false); + await _notificationService.ShowNotificationAsync("Rule Saved", $"Settings for {SelectedProcess.Name} saved successfully", NotificationType.Success); await LogUserActionAsync("SaveAssociation", @@ -1832,17 +1837,48 @@ namespace ThreadPilot.ViewModels } else { - SetStatus($"Association already exists for {SelectedProcess.Name}", false); - await _notificationService.ShowNotificationAsync("Association Exists", - $"An association for {SelectedProcess.Name} already exists", NotificationType.Warning); + var existingAssociation = await _associationService.FindAssociationByExecutableAsync(SelectedProcess.Name); + if (existingAssociation != null) + { + existingAssociation.ExecutablePath = association.ExecutablePath; + existingAssociation.PowerPlanGuid = association.PowerPlanGuid; + existingAssociation.PowerPlanName = association.PowerPlanName; + existingAssociation.CoreMaskId = association.CoreMaskId; + existingAssociation.CoreMaskName = association.CoreMaskName; + existingAssociation.ProcessPriority = association.ProcessPriority; + existingAssociation.MatchByPath = association.MatchByPath; + existingAssociation.Description = association.Description; + existingAssociation.IsEnabled = true; + existingAssociation.UpdatedAt = DateTime.UtcNow; + + var updated = await _associationService.UpdateAssociationAsync(existingAssociation); + if (updated) + { + SetStatus($"Existing rule updated for {SelectedProcess.Name}.", false); + await _notificationService.ShowNotificationAsync("Rule Updated", + $"Existing rule for {SelectedProcess.Name} was updated", NotificationType.Information); + } + else + { + SetStatus($"Failed to update existing rule for {SelectedProcess.Name}", false); + await _notificationService.ShowNotificationAsync("Rule Update Failed", + $"Could not update existing rule for {SelectedProcess.Name}", NotificationType.Warning); + } + } + else + { + SetStatus($"Rule already exists for {SelectedProcess.Name}", false); + await _notificationService.ShowNotificationAsync("Rule Exists", + $"A rule 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); + SetStatus($"Error saving rule: {ex.Message}", false); await _notificationService.ShowNotificationAsync("Error", - $"Failed to save association: {ex.Message}", NotificationType.Error); + $"Failed to save rule: {ex.Message}", NotificationType.Error); } } } diff --git a/ViewModels/SettingsViewModel.cs b/ViewModels/SettingsViewModel.cs index b376fd1..fbea800 100644 --- a/ViewModels/SettingsViewModel.cs +++ b/ViewModels/SettingsViewModel.cs @@ -15,8 +15,10 @@ * along with this program. If not, see . */ using System; +using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; +using System.Linq; using System.Threading.Tasks; using System.Windows.Input; using System.Windows; @@ -38,8 +40,12 @@ namespace ThreadPilot.ViewModels private readonly INotificationService _notificationService; private readonly IAutostartService _autostartService; private readonly IPowerPlanService _powerPlanService; + private readonly IProcessPowerPlanAssociationService _associationService; private readonly IProcessMonitorManagerService _processMonitorManagerService; + private readonly IThemeService _themeService; private bool _isSyncingFromService = false; + private string _cachedDefaultPowerPlanGuid = string.Empty; + private string _cachedDefaultPowerPlanName = string.Empty; [ObservableProperty] private ApplicationSettingsModel settings; @@ -50,8 +56,9 @@ namespace ThreadPilot.ViewModels [ObservableProperty] private bool isLoading = false; - [ObservableProperty] - private string statusMessage = string.Empty; + public bool CanSaveSettings => HasUnsavedChanges && !IsLoading; + + public bool HasPendingChanges => HasUnsavedChanges; [ObservableProperty] private ObservableCollection availablePowerPlans = new(); @@ -72,7 +79,9 @@ namespace ThreadPilot.ViewModels INotificationService notificationService, IAutostartService autostartService, IPowerPlanService powerPlanService, + IProcessPowerPlanAssociationService associationService, IProcessMonitorManagerService processMonitorManagerService, + IThemeService themeService, IEnhancedLoggingService? enhancedLoggingService = null) : base(logger, enhancedLoggingService) { @@ -80,7 +89,9 @@ namespace ThreadPilot.ViewModels _notificationService = notificationService ?? throw new ArgumentNullException(nameof(notificationService)); _autostartService = autostartService ?? throw new ArgumentNullException(nameof(autostartService)); _powerPlanService = powerPlanService ?? throw new ArgumentNullException(nameof(powerPlanService)); + _associationService = associationService ?? throw new ArgumentNullException(nameof(associationService)); _processMonitorManagerService = processMonitorManagerService ?? throw new ArgumentNullException(nameof(processMonitorManagerService)); + _themeService = themeService ?? throw new ArgumentNullException(nameof(themeService)); // Get version and strip the git commit hash (everything after '+') var rawVersion = typeof(App).Assembly @@ -131,42 +142,86 @@ namespace ThreadPilot.ViewModels StatusMessage = "Settings have been modified"; } + partial void OnHasUnsavedChangesChanged(bool value) + { + OnPropertyChanged(nameof(CanSaveSettings)); + } + + partial void OnIsLoadingChanged(bool value) + { + OnPropertyChanged(nameof(CanSaveSettings)); + } + private async Task SaveSettingsAsync() { + string previousDefaultPowerPlanGuid = string.Empty; + string previousDefaultPowerPlanName = string.Empty; + try { IsLoading = true; StatusMessage = "Saving settings..."; + var warnings = new List(); + + previousDefaultPowerPlanGuid = Settings.DefaultPowerPlanId; + previousDefaultPowerPlanName = Settings.DefaultPowerPlanName; // Handle autostart setting - if (Settings.AutostartWithWindows != _settingsService.Settings.AutostartWithWindows) + var currentAutostartState = await _autostartService.CheckAutostartStatusAsync(); + if (Settings.AutostartWithWindows != currentAutostartState) { + bool autostartUpdated; if (Settings.AutostartWithWindows) { - await _autostartService.EnableAutostartAsync(Settings.StartMinimized); + autostartUpdated = await _autostartService.EnableAutostartAsync(Settings.StartMinimized); } else { - await _autostartService.DisableAutostartAsync(); + autostartUpdated = await _autostartService.DisableAutostartAsync(); + } + + if (!autostartUpdated) + { + warnings.Add("Failed to update Windows autostart. Keeping previous autostart state."); + Settings.AutostartWithWindows = currentAutostartState; + } + else + { + Settings.AutostartWithWindows = await _autostartService.CheckAutostartStatusAsync(); } } await _settingsService.UpdateSettingsAsync(Settings); + _themeService.ApplyTheme(Settings.UseDarkTheme); + // Update monitoring services with new settings _processMonitorManagerService.UpdateSettings(); HasUnsavedChanges = false; - StatusMessage = "Settings saved successfully"; - - await _notificationService.ShowSuccessNotificationAsync( - "Settings Saved", - "Application settings have been saved successfully"); + if (warnings.Count > 0) + { + StatusMessage = $"Settings saved with warnings: {string.Join(" ", warnings)}"; + await _notificationService.ShowNotificationAsync( + "Settings Saved with Warnings", + string.Join(" ", warnings), + NotificationType.Warning); + } + else + { + StatusMessage = "Settings saved and applied successfully."; + await _notificationService.ShowSuccessNotificationAsync( + "Settings Saved", + "Application settings have been saved successfully"); + } Logger.LogInformation("Settings saved successfully"); } catch (Exception ex) { + Settings.DefaultPowerPlanId = previousDefaultPowerPlanGuid; + Settings.DefaultPowerPlanName = previousDefaultPowerPlanName; + StatusMessage = $"Error saving settings: {ex.Message}"; Logger.LogError(ex, "Error saving settings"); @@ -299,10 +354,24 @@ namespace ThreadPilot.ViewModels StatusMessage = "Loading settings..."; await _settingsService.LoadSettingsAsync(); + await _associationService.LoadConfigurationAsync(); + + var settingsSnapshot = _settingsService.Settings; + var (defaultPowerPlanGuid, defaultPowerPlanName) = await _associationService.GetDefaultPowerPlanAsync(); + _cachedDefaultPowerPlanGuid = defaultPowerPlanGuid; + _cachedDefaultPowerPlanName = defaultPowerPlanName; + if (!string.IsNullOrWhiteSpace(defaultPowerPlanGuid)) + { + settingsSnapshot.DefaultPowerPlanId = defaultPowerPlanGuid; + settingsSnapshot.DefaultPowerPlanName = defaultPowerPlanName; + } + _isSyncingFromService = true; - Settings.CopyFrom(_settingsService.Settings); + Settings.CopyFrom(settingsSnapshot); _isSyncingFromService = false; + _themeService.ApplyTheme(Settings.UseDarkTheme); + HasUnsavedChanges = false; StatusMessage = "Settings loaded"; @@ -337,6 +406,11 @@ namespace ThreadPilot.ViewModels try { Settings.CopyFrom(e.NewSettings); + if (!string.IsNullOrWhiteSpace(_cachedDefaultPowerPlanGuid)) + { + Settings.DefaultPowerPlanId = _cachedDefaultPowerPlanGuid; + Settings.DefaultPowerPlanName = _cachedDefaultPowerPlanName; + } HasUnsavedChanges = false; StatusMessage = "Settings synchronized"; } @@ -449,6 +523,27 @@ namespace ThreadPilot.ViewModels ? parsed : new Version(0, 0, 0); } + + public async Task SaveIfDirtyAsync() + { + if (!HasUnsavedChanges) + { + return true; + } + + await SaveSettingsAsync(); + return !HasUnsavedChanges; + } + + public async Task DiscardPendingChangesAsync() + { + if (!HasUnsavedChanges) + { + return; + } + + await RefreshSettingsAsync(); + } } } diff --git a/Views/MasksView.xaml b/Views/MasksView.xaml index 1e58b9d..fb37292 100644 --- a/Views/MasksView.xaml +++ b/Views/MasksView.xaml @@ -32,10 +32,10 @@ - + @@ -47,11 +47,11 @@ - - + @@ -117,7 +117,7 @@ + FontSize="11" Foreground="{DynamicResource TextSecondaryBrush}" Margin="0,0,0,10"/> @@ -127,14 +127,14 @@ - @@ -178,9 +178,9 @@ - + diff --git a/Views/PerformanceView.xaml b/Views/PerformanceView.xaml index 3d04fb2..fefd90e 100644 --- a/Views/PerformanceView.xaml +++ b/Views/PerformanceView.xaml @@ -1,213 +1,375 @@ + xmlns:converters="clr-namespace:ThreadPilot.Converters" + xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" + xmlns:d="http://schemas.microsoft.com/expression/blend/2008" + mc:Ignorable="d" + d:DesignHeight="640" + d:DesignWidth="1080"> + - - - - - - - + + - - + + - - - - - - - - - + + - - - + + + + - -