Add docs, themes, services and UI updates

Large changeset adding documentation, themes, converters and wiring between UI and services. Key changes:

- Rewrote .gitignore to standardize build, IDE, OS and project-specific ignores.
- Added comprehensive documentation: ADVANCED_CPU_FEATURES.md, API_REFERENCE.md, ARCHITECTURE_GUIDE.md, DEVELOPER_GUIDE.md, GAME_BOOST_VALIDATION.md, CLAUDE.md, PROJECT_STRUCTURE.md, UI_STYLE_GUIDE.md, TRADEMARK.md.
- Added theme resources (Themes/FluentLight.xaml, Themes/FluentDark.xaml) and merged FluentLight into App.xaml resource dictionary.
- Added NullToBoolConverter and registered it in App.xaml.
- Enabled a DEBUG-only console test mode in App.xaml.cs (--test flag) and guarded AllocConsole with #if DEBUG.
- Added new service/support files (AtomicFileWriter, StoragePaths, ThemeService) and numerous updates across Services (CpuTopologyService, CoreMaskService, PowerPlanService, ProcessMonitorManagerService, ProcessService, NotificationService, SystemTrayService, SystemTweaksService, EnhancedLoggingService, etc.).
- Updated many ViewModels and Views to support new functionality (CPU topology, power plan and game-boost features) and tests (Tests/TestRunner.cs).
- Added build-release.ps1 and various project metadata updates.

Overall this commit introduces documentation, theming, new converters and test/debug support, plus extensive service and UI wiring for CPU topology, process monitoring, power plans and game boost features.
This commit is contained in:
PrimeBuild-pc
2026-04-10 03:58:51 +02:00
parent bb3602342a
commit 010dee679f
52 changed files with 3370 additions and 1215 deletions
+89 -226
View File
@@ -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
# 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
+4
View File
@@ -6,6 +6,9 @@
xmlns:converters="clr-namespace:ThreadPilot.Converters">
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="Themes/FluentLight.xaml"/>
</ResourceDictionary.MergedDictionaries>
<helpers:BytesToMbConverter x:Key="BytesToMbConverter"/>
<helpers:AffinityMaskConverter x:Key="AffinityMaskConverter"/>
<helpers:BoolToFontWeightConverter x:Key="BoolToFontWeightConverter"/>
@@ -14,6 +17,7 @@
<converters:BoolToStringConverter x:Key="BoolToStringConverter"/>
<converters:BytesToStringConverter x:Key="BytesToStringConverter"/>
<converters:InverseBooleanConverter x:Key="InverseBooleanConverter"/>
<converters:NullToBoolConverter x:Key="NullToBoolConverter"/>
<local:BoolToVisibilityConverter x:Key="BooleanToVisibilityConverter"/>
<converters:StringToVisibilityConverter x:Key="StringToVisibilityConverter"/>
</ResourceDictionary>
+11
View File
@@ -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<MainWindow>();
@@ -186,8 +195,10 @@ namespace ThreadPilot
base.OnExit(e);
}
#if DEBUG
[System.Runtime.InteropServices.DllImport("kernel32.dll")]
private static extern bool AllocConsole();
#endif
/// <summary>
/// Shows a message to the user about elevation requirements
+35
View File
@@ -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 <https://www.gnu.org/licenses/>.
*/
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();
}
}
}
+42 -16
View File
@@ -13,6 +13,23 @@
WindowStartupLocation="CenterScreen">
<Window.Resources>
<Style TargetType="GroupBox">
<Setter Property="Background" Value="{DynamicResource SurfaceBrush}"/>
<Setter Property="BorderBrush" Value="{DynamicResource BorderBrush}"/>
<Setter Property="Foreground" Value="{DynamicResource TextPrimaryBrush}"/>
</Style>
<Style TargetType="TabControl">
<Setter Property="Background" Value="{DynamicResource AppBackgroundBrush}"/>
<Setter Property="Foreground" Value="{DynamicResource TextPrimaryBrush}"/>
<Setter Property="BorderBrush" Value="{DynamicResource BorderBrush}"/>
</Style>
<Style TargetType="StatusBar">
<Setter Property="Background" Value="{DynamicResource SurfaceAltBrush}"/>
<Setter Property="Foreground" Value="{DynamicResource TextPrimaryBrush}"/>
</Style>
<!-- Loading Spinner Animation -->
<Storyboard x:Key="SpinnerAnimation" RepeatBehavior="Forever">
<DoubleAnimation Storyboard.TargetName="SpinnerRotation"
@@ -35,7 +52,7 @@
</Storyboard>
</Window.Resources>
<Grid>
<Grid Background="{DynamicResource AppBackgroundBrush}">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
@@ -44,7 +61,7 @@
</Grid.RowDefinitions>
<!-- Elevation Status Bar -->
<Border Grid.Row="0" Background="#FFF3CD" BorderBrush="#FFEAA2" BorderThickness="1"
<Border Grid.Row="0" Background="{DynamicResource WarningBackgroundBrush}" BorderBrush="{DynamicResource WarningBorderBrush}" BorderThickness="1"
Visibility="{Binding ShowElevationPrompt, Converter={StaticResource BoolToVisibilityConverter}}"
Margin="5,5,5,0">
<Grid Margin="10,5">
@@ -66,23 +83,32 @@
<!-- Main Application Content -->
<Grid x:Name="MainContent" Grid.Row="2">
<TabControl Margin="10">
<TabItem Header="🔧 Process Management">
<TabControl x:Name="MainTabControl" Margin="10" SelectionChanged="OnMainTabSelectionChanged">
<TabItem x:Name="ProcessManagementTab" Header="🔧 Process Management">
<views:ProcessView/>
</TabItem>
<TabItem Header="🎯 Core Masks">
<TabItem x:Name="CoreMasksTab" Header="🎯 Core Masks">
<views:MasksView/>
</TabItem>
<TabItem Header="⚡ Power Plans">
<views:PowerPlanView/>
<TabItem x:Name="PowerPlansTab" Header="⚡ Power Plans">
<views:PowerPlanView x:Name="PowerPlanViewControl"/>
</TabItem>
<TabItem Header="🔗 Process Associations">
<TabItem x:Name="ProcessAssociationsTab" Header="📐 Rules">
<views:ProcessPowerPlanAssociationView x:Name="AssociationView"/>
</TabItem>
<TabItem Header="🔧 Tweaks">
<TabItem x:Name="PerformanceTab" Header="📊 Performance">
<views:PerformanceView x:Name="PerformanceViewControl"/>
</TabItem>
<TabItem x:Name="SystemTweaksTab" Header="🔧 Tweaks">
<views:SystemTweaksView x:Name="SystemTweaksView"/>
</TabItem>
<TabItem Header="⚙️ Settings">
<TabItem x:Name="SettingsTab">
<TabItem.Header>
<StackPanel Orientation="Horizontal">
<TextBlock Text="" FontFamily="Segoe Fluent Icons, Segoe MDL2 Assets, Segoe UI Symbol, Segoe UI" Margin="0,0,6,0"/>
<TextBlock Text="Settings"/>
</StackPanel>
</TabItem.Header>
<views:SettingsView x:Name="SettingsView"/>
</TabItem>
</TabControl>
@@ -109,11 +135,11 @@
<!-- Startup Loading Overlay -->
<Grid x:Name="LoadingOverlay"
Grid.RowSpan="4"
Background="#80000000"
Background="{DynamicResource OverlayBrush}"
Visibility="Visible"
Panel.ZIndex="1000">
<Border Background="White"
BorderBrush="LightGray"
<Border Background="{DynamicResource SurfaceBrush}"
BorderBrush="{DynamicResource BorderBrush}"
BorderThickness="1"
CornerRadius="8"
Padding="30"
@@ -133,13 +159,13 @@
<!-- Loading Spinner -->
<Grid Width="32" Height="32" Margin="0,0,0,20" HorizontalAlignment="Center">
<Ellipse Width="32" Height="32"
Stroke="LightGray"
Stroke="{DynamicResource SpinnerTrackBrush}"
StrokeThickness="3"
Opacity="0.3"/>
<Ellipse x:Name="SpinnerEllipse"
Width="32"
Height="32"
Stroke="#0078D4"
Stroke="{DynamicResource AccentBrush}"
StrokeThickness="3"
StrokeDashArray="20,10"
RenderTransformOrigin="0.5,0.5">
@@ -161,7 +187,7 @@
<TextBlock x:Name="LoadingStatus"
Text="Initializing services..."
FontSize="12"
Foreground="Gray"
Foreground="{DynamicResource TextSecondaryBrush}"
HorizontalAlignment="Center"/>
</StackPanel>
</Border>
+276 -37
View File
@@ -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);
}
/// <summary>
/// Performs graceful shutdown with cleanup of all applied optimizations
/// Similar to CPU Set Setter's ExitAppGracefully
/// </summary>
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<IPowerPlanService>();
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<bool> 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<string>();
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;
}
}
}
+27 -40
View File
@@ -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<KeyboardShortcut>(other.KeyboardShortcuts);
KeyboardShortcuts = other.KeyboardShortcuts != null
? new List<KeyboardShortcut>(other.KeyboardShortcuts)
: new List<KeyboardShortcut>();
}
// 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<KeyboardShortcut>(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;
}
}
/// <summary>
/// Notification level profile options
/// </summary>
public enum NotificationLevelProfile
{
All,
WarningsAndErrorsOnly,
Silent
}
/// <summary>
/// Notification position options
/// </summary>
+17 -2
View File
@@ -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());
}
+40 -50
View File
@@ -1,71 +1,61 @@
# ThreadPilot ✈️ <sup><kbd>PUBLIC BETA</kbd></sup>
# 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
<img width="1474" height="920" alt="Screenshot 2025-12-21 044753" src="https://github.com/user-attachments/assets/77fc944e-d2a1-4cc7-9915-e01b0776106c" />
## 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`.
+43 -26
View File
@@ -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<ApplicationSettingsService> _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<ApplicationSettingsChangedEventArgs>? SettingsChanged;
public ApplicationSettingsModel Settings => _settings;
public ApplicationSettingsModel Settings => (ApplicationSettingsModel)_settings.Clone();
public ApplicationSettingsService(ILogger<ApplicationSettingsService> 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<ApplicationSettingsModel>(json);
var loadedSettings = JsonSerializer.Deserialize<ApplicationSettingsModel>(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<ApplicationSettingsModel>(json);
var importedSettings = JsonSerializer.Deserialize<ApplicationSettingsModel>(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");
}
}
}
}
+72
View File
@@ -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 <https://www.gnu.org/licenses/>.
*/
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);
}
}
}
}
}
+4 -3
View File
@@ -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<AutostartService> _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,
+13 -12
View File
@@ -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
/// </summary>
public class CoreMaskService : ICoreMaskService
{
private static readonly JsonSerializerOptions JsonOptions = new()
{
WriteIndented = true,
PropertyNameCaseInsensitive = true,
ReadCommentHandling = JsonCommentHandling.Skip,
AllowTrailingCommas = true
};
private readonly ILogger<CoreMaskService> _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<List<JsonElement>>(json);
var data = JsonSerializer.Deserialize<List<JsonElement>>(json, JsonOptions);
if (data == null)
{
+73 -7
View File
@@ -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<CpuTopologyService> _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();
}
}
+5 -4
View File
@@ -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");
}
+10
View File
@@ -105,6 +105,16 @@ namespace ThreadPilot.Services
/// Gets the "All Cores" baseline mask (cannot be deleted)
/// </summary>
CoreMask? GetAllCoresMask();
/// <summary>
/// Registers that a mask has been applied to a running process
/// </summary>
void RegisterMaskApplication(int processId, string maskId);
/// <summary>
/// Unregisters mask tracking when a process exits or a mask is removed
/// </summary>
void UnregisterMaskApplication(int processId);
}
}
+5
View File
@@ -65,6 +65,11 @@ namespace ThreadPilot.Services
/// </summary>
event EventHandler? PerformanceDashboardRequested;
/// <summary>
/// Event fired when process management dashboard is requested from tray
/// </summary>
event EventHandler? DashboardRequested;
/// <summary>
/// Initializes the system tray icon
/// </summary>
+27
View File
@@ -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 <https://www.gnu.org/licenses/>.
*/
using System;
namespace ThreadPilot.Services
{
public interface IThemeService
{
bool IsDarkTheme { get; }
void ApplyTheme(bool useDarkTheme);
}
}
+1 -1
View File
@@ -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);
}
+12
View File
@@ -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,
+10 -11
View File
@@ -29,6 +29,7 @@ namespace ThreadPilot.Services
public class PowerPlanService : IPowerPlanService
{
private static readonly Lazy<string> _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
/// </summary>
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
}
};
+130 -11
View File
@@ -45,11 +45,13 @@ namespace ThreadPilot.Services
private readonly ConcurrentDictionary<int, ProcessModel> _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<ProcessPowerPlanChangeEventArgs>? ProcessPowerPlanChanged;
public event EventHandler<ServiceStatusEventArgs>? 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<ProcessModel>();
var currentProcessIds = new HashSet<int>(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;
+222 -13
View File
@@ -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<int, ProcessModel> _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<ProcessEventArgs>? ProcessStarted;
public event EventHandler<ProcessEventArgs>? 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<bool> 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<ProcessModel?> 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;
}
+75 -20
View File
@@ -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
/// </summary>
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<bool> LoadConfigurationAsync()
@@ -61,12 +75,13 @@ namespace ThreadPilot.Services
}
var json = await File.ReadAllTextAsync(_configurationFilePath);
var loadedConfig = JsonSerializer.Deserialize<ProcessMonitorConfiguration>(json);
var loadedConfig = JsonSerializer.Deserialize<ProcessMonitorConfiguration>(json, JsonOptions);
if (loadedConfig != null)
{
lock (_lockObject)
{
loadedConfig.Associations ??= new List<ProcessPowerPlanAssociation>();
_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<ProcessMonitorConfiguration>(json);
var importedConfig = JsonSerializer.Deserialize<ProcessMonitorConfiguration>(json, JsonOptions);
if (importedConfig != null)
{
lock (_lockObject)
{
importedConfig.Associations ??= new List<ProcessPowerPlanAssociation>();
_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());
}
}
}
+58 -9
View File
@@ -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<int, CpuSample> _cpuSamples = new();
private readonly ConcurrentDictionary<int, IProcessCpuSetHandler> _cpuSetHandlers = new();
private readonly ILogger<ProcessService>? _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<dynamic>(content);
if (profile != null)
var profile = JsonSerializer.Deserialize<ProcessProfileSnapshot>(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");
}
}
}
/// <summary>
+1
View File
@@ -125,6 +125,7 @@ namespace ThreadPilot.Services
{
// Application configuration and settings
services.AddSingleton<IApplicationSettingsService, ApplicationSettingsService>();
services.AddSingleton<IThemeService, ThemeService>();
// User interface services
services.AddSingleton<INotificationService, NotificationService>();
+1 -5
View File
@@ -196,11 +196,7 @@ namespace ThreadPilot.Services
var pending = new List<SmartNotification>();
// 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);
+42
View File
@@ -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 <https://www.gnu.org/licenses/>.
*/
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);
}
}
}
+28 -30
View File
@@ -53,6 +53,7 @@ namespace ThreadPilot.Services
public event EventHandler<PowerPlanChangeRequestedEventArgs>? PowerPlanChangeRequested;
public event EventHandler<ProfileApplicationRequestedEventArgs>? ProfileApplicationRequested;
public event EventHandler? PerformanceDashboardRequested;
public event EventHandler? DashboardRequested;
public SystemTrayService(ILogger<SystemTrayService> 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;
}
+227 -46
View File
@@ -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
/// </summary>
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<SystemTweaksService> _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<int?> 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<ProcessResult> 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<TweakStatus> GetMenuShowDelayStatusAsync()
{
try
+74
View File
@@ -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 <https://www.gnu.org/licenses/>.
*/
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<ThemeService> _logger;
private ResourceDictionary? _activeThemeDictionary;
public bool IsDarkTheme { get; private set; }
public ThemeService(ILogger<ThemeService> 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);
}
}
}
}
-57
View File
@@ -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 <https://www.gnu.org/licenses/>.
*/
using System;
using System.Threading.Tasks;
using ThreadPilot.Tests;
namespace ThreadPilot
{
/// <summary>
/// Simple test runner for CPU topology functionality
/// </summary>
public static class TestRunner
{
/// <summary>
/// Main test entry point
/// </summary>
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();
}
}
}
+20 -67
View File
@@ -16,91 +16,44 @@
*/
using System;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
namespace ThreadPilot.Tests
{
/// <summary>
/// Test runner for validating Game Boost functionality
/// Integrated runtime test runner used by --test mode.
/// </summary>
public static class TestRunner
{
/// <summary>
/// Runs all Game Boost integration tests
/// </summary>
public static async Task<bool> RunGameBoostTestsAsync(IServiceProvider serviceProvider)
public static async Task RunTests()
{
var logger = serviceProvider.GetRequiredService<ILogger<GameBoostIntegrationTest>>();
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;
}
}
/// <summary>
/// Validates that all required services are properly configured
/// </summary>
public static bool ValidateServiceConfiguration(IServiceProvider serviceProvider)
{
var logger = serviceProvider.GetRequiredService<ILogger<GameBoostIntegrationTest>>();
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();
}
}
}
+80
View File
@@ -0,0 +1,80 @@
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<SolidColorBrush x:Key="AppBackgroundBrush" Color="#FF0F141A"/>
<SolidColorBrush x:Key="SurfaceBrush" Color="#FF1A222C"/>
<SolidColorBrush x:Key="SurfaceAltBrush" Color="#FF23303C"/>
<SolidColorBrush x:Key="TextPrimaryBrush" Color="#FFE7EDF3"/>
<SolidColorBrush x:Key="TextSecondaryBrush" Color="#FFAFBDC9"/>
<SolidColorBrush x:Key="AccentBrush" Color="#FF45A0FF"/>
<SolidColorBrush x:Key="BorderBrush" Color="#FF344555"/>
<SolidColorBrush x:Key="OverlayBrush" Color="#99060A10"/>
<SolidColorBrush x:Key="SpinnerTrackBrush" Color="#FF4B5E71"/>
<SolidColorBrush x:Key="InfoBackgroundBrush" Color="#FF1A2B3A"/>
<SolidColorBrush x:Key="InfoBorderBrush" Color="#FF2D4A64"/>
<SolidColorBrush x:Key="InfoTextBrush" Color="#FF9DD3FF"/>
<SolidColorBrush x:Key="SuccessBackgroundBrush" Color="#FF172A20"/>
<SolidColorBrush x:Key="SuccessBorderBrush" Color="#FF29523C"/>
<SolidColorBrush x:Key="SuccessTextBrush" Color="#FF89DFAF"/>
<SolidColorBrush x:Key="WarningBackgroundBrush" Color="#FF342A14"/>
<SolidColorBrush x:Key="WarningBorderBrush" Color="#FF685126"/>
<SolidColorBrush x:Key="WarningTextBrush" Color="#FFF2C56D"/>
<SolidColorBrush x:Key="ErrorBackgroundBrush" Color="#FF351D1D"/>
<SolidColorBrush x:Key="ErrorBorderBrush" Color="#FF653333"/>
<SolidColorBrush x:Key="ErrorTextBrush" Color="#FFFFA4A4"/>
<Style TargetType="Window">
<Setter Property="Background" Value="{StaticResource AppBackgroundBrush}"/>
<Setter Property="Foreground" Value="{StaticResource TextPrimaryBrush}"/>
<Setter Property="FontFamily" Value="Segoe UI, Segoe UI Variable Text, Arial"/>
</Style>
<Style TargetType="UserControl">
<Setter Property="Background" Value="{StaticResource AppBackgroundBrush}"/>
<Setter Property="Foreground" Value="{StaticResource TextPrimaryBrush}"/>
<Setter Property="FontFamily" Value="Segoe UI, Segoe UI Variable Text, Arial"/>
</Style>
<Style TargetType="GroupBox">
<Setter Property="Foreground" Value="{StaticResource TextPrimaryBrush}"/>
<Setter Property="BorderBrush" Value="{StaticResource BorderBrush}"/>
<Setter Property="Background" Value="{StaticResource SurfaceBrush}"/>
</Style>
<Style TargetType="TabControl">
<Setter Property="Background" Value="{StaticResource AppBackgroundBrush}"/>
<Setter Property="BorderBrush" Value="{StaticResource BorderBrush}"/>
<Setter Property="Foreground" Value="{StaticResource TextPrimaryBrush}"/>
</Style>
<Style TargetType="TabItem">
<Setter Property="Background" Value="{StaticResource SurfaceAltBrush}"/>
<Setter Property="Foreground" Value="{StaticResource TextPrimaryBrush}"/>
<Setter Property="BorderBrush" Value="{StaticResource BorderBrush}"/>
</Style>
<Style TargetType="DataGrid">
<Setter Property="Background" Value="{StaticResource SurfaceBrush}"/>
<Setter Property="Foreground" Value="{StaticResource TextPrimaryBrush}"/>
<Setter Property="BorderBrush" Value="{StaticResource BorderBrush}"/>
<Setter Property="RowBackground" Value="{StaticResource SurfaceBrush}"/>
<Setter Property="AlternatingRowBackground" Value="{StaticResource SurfaceAltBrush}"/>
<Setter Property="HorizontalGridLinesBrush" Value="{StaticResource BorderBrush}"/>
<Setter Property="VerticalGridLinesBrush" Value="{StaticResource BorderBrush}"/>
</Style>
<Style TargetType="Button">
<Setter Property="Foreground" Value="{StaticResource TextPrimaryBrush}"/>
<Setter Property="Background" Value="{StaticResource SurfaceBrush}"/>
<Setter Property="BorderBrush" Value="{StaticResource BorderBrush}"/>
<Setter Property="Padding" Value="10,6"/>
</Style>
<Style TargetType="TextBlock">
<Setter Property="FontFamily" Value="Segoe UI, Segoe UI Variable Text, Arial"/>
<Setter Property="Foreground" Value="{StaticResource TextPrimaryBrush}"/>
</Style>
<Style TargetType="TextElement">
<Setter Property="FontFamily" Value="Segoe UI, Segoe UI Variable Text, Arial"/>
</Style>
</ResourceDictionary>
+80
View File
@@ -0,0 +1,80 @@
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<SolidColorBrush x:Key="AppBackgroundBrush" Color="#FFF7F9FC"/>
<SolidColorBrush x:Key="SurfaceBrush" Color="#FFFFFFFF"/>
<SolidColorBrush x:Key="SurfaceAltBrush" Color="#FFF1F5FA"/>
<SolidColorBrush x:Key="TextPrimaryBrush" Color="#FF1E2A35"/>
<SolidColorBrush x:Key="TextSecondaryBrush" Color="#FF5D6A76"/>
<SolidColorBrush x:Key="AccentBrush" Color="#FF0A66C2"/>
<SolidColorBrush x:Key="BorderBrush" Color="#FFD3DEE8"/>
<SolidColorBrush x:Key="OverlayBrush" Color="#66050A12"/>
<SolidColorBrush x:Key="SpinnerTrackBrush" Color="#FFB8C5D1"/>
<SolidColorBrush x:Key="InfoBackgroundBrush" Color="#FFEAF4FF"/>
<SolidColorBrush x:Key="InfoBorderBrush" Color="#FFB9D8F7"/>
<SolidColorBrush x:Key="InfoTextBrush" Color="#FF154B7D"/>
<SolidColorBrush x:Key="SuccessBackgroundBrush" Color="#FFE9F8EE"/>
<SolidColorBrush x:Key="SuccessBorderBrush" Color="#FFB7E3C5"/>
<SolidColorBrush x:Key="SuccessTextBrush" Color="#FF1F6F3B"/>
<SolidColorBrush x:Key="WarningBackgroundBrush" Color="#FFFFF4DB"/>
<SolidColorBrush x:Key="WarningBorderBrush" Color="#FFEFC26B"/>
<SolidColorBrush x:Key="WarningTextBrush" Color="#FF8A5A00"/>
<SolidColorBrush x:Key="ErrorBackgroundBrush" Color="#FFFDECEC"/>
<SolidColorBrush x:Key="ErrorBorderBrush" Color="#FFF3B8B8"/>
<SolidColorBrush x:Key="ErrorTextBrush" Color="#FFA12626"/>
<Style TargetType="Window">
<Setter Property="Background" Value="{StaticResource AppBackgroundBrush}"/>
<Setter Property="Foreground" Value="{StaticResource TextPrimaryBrush}"/>
<Setter Property="FontFamily" Value="Segoe UI, Segoe UI Variable Text, Arial"/>
</Style>
<Style TargetType="UserControl">
<Setter Property="Background" Value="{StaticResource AppBackgroundBrush}"/>
<Setter Property="Foreground" Value="{StaticResource TextPrimaryBrush}"/>
<Setter Property="FontFamily" Value="Segoe UI, Segoe UI Variable Text, Arial"/>
</Style>
<Style TargetType="GroupBox">
<Setter Property="Foreground" Value="{StaticResource TextPrimaryBrush}"/>
<Setter Property="BorderBrush" Value="{StaticResource BorderBrush}"/>
<Setter Property="Background" Value="{StaticResource SurfaceBrush}"/>
</Style>
<Style TargetType="TabControl">
<Setter Property="Background" Value="{StaticResource AppBackgroundBrush}"/>
<Setter Property="BorderBrush" Value="{StaticResource BorderBrush}"/>
<Setter Property="Foreground" Value="{StaticResource TextPrimaryBrush}"/>
</Style>
<Style TargetType="TabItem">
<Setter Property="Background" Value="{StaticResource SurfaceAltBrush}"/>
<Setter Property="Foreground" Value="{StaticResource TextPrimaryBrush}"/>
<Setter Property="BorderBrush" Value="{StaticResource BorderBrush}"/>
</Style>
<Style TargetType="DataGrid">
<Setter Property="Background" Value="{StaticResource SurfaceBrush}"/>
<Setter Property="Foreground" Value="{StaticResource TextPrimaryBrush}"/>
<Setter Property="BorderBrush" Value="{StaticResource BorderBrush}"/>
<Setter Property="RowBackground" Value="{StaticResource SurfaceBrush}"/>
<Setter Property="AlternatingRowBackground" Value="{StaticResource SurfaceAltBrush}"/>
<Setter Property="HorizontalGridLinesBrush" Value="{StaticResource BorderBrush}"/>
<Setter Property="VerticalGridLinesBrush" Value="{StaticResource BorderBrush}"/>
</Style>
<Style TargetType="Button">
<Setter Property="Foreground" Value="{StaticResource TextPrimaryBrush}"/>
<Setter Property="Background" Value="{StaticResource SurfaceBrush}"/>
<Setter Property="BorderBrush" Value="{StaticResource BorderBrush}"/>
<Setter Property="Padding" Value="10,6"/>
</Style>
<Style TargetType="TextBlock">
<Setter Property="FontFamily" Value="Segoe UI, Segoe UI Variable Text, Arial"/>
<Setter Property="Foreground" Value="{StaticResource TextPrimaryBrush}"/>
</Style>
<Style TargetType="TextElement">
<Setter Property="FontFamily" Value="Segoe UI, Segoe UI Variable Text, Arial"/>
</Style>
</ResourceDictionary>
+6 -6
View File
@@ -16,10 +16,10 @@
<TrimMode>link</TrimMode>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<NoWarn>CS1998;CS0067;CS0414;WFAC010;IL3000;MVVMTK0034</NoWarn>
<Version>0.1.0-beta</Version>
<AssemblyVersion>0.1.0.0</AssemblyVersion>
<FileVersion>0.1.0.0</FileVersion>
<InformationalVersion>0.1.0-beta</InformationalVersion>
<Version>1.0.0</Version>
<AssemblyVersion>1.0.0.0</AssemblyVersion>
<FileVersion>1.0.0.0</FileVersion>
<InformationalVersion>1.0.0</InformationalVersion>
</PropertyGroup>
<ItemGroup>
@@ -61,12 +61,12 @@
<Compile Remove="ViewModels\LogViewerViewModel.cs" />
<Compile Remove="Views\LogViewerView.xaml.cs" />
<Page Remove="Views\LogViewerView.xaml" />
<!-- Remove Game Boost feature and tests from build -->
<!-- Remove optional Game Boost feature from build -->
<Compile Remove="Services\GameBoostService.cs" />
<Compile Remove="Services\IGameBoostService.cs" />
<Compile Remove="Services\GameDetectionService.cs" />
<Compile Remove="Services\IGameDetectionService.cs" />
<Compile Remove="Tests\TestRunner.cs" />
<!-- Remove Game Boost-specific integration test from build -->
<Compile Remove="Tests\GameBoostIntegrationTest.cs" />
</ItemGroup>
-6
View File
@@ -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",
+13 -2
View File
@@ -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()
+582 -161
View File
@@ -15,56 +15,43 @@
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
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
{
/// <summary>
/// ViewModel for the performance monitoring dashboard
/// </summary>
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<PerformanceViewModel> _logger;
[ObservableProperty]
private ObservableCollection<CpuCoreUsage> 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<ProcessPerformanceInfo> topCpuProcesses = new();
[ObservableProperty]
private ObservableCollection<ProcessPerformanceInfo> topMemoryProcesses = new();
private ObservableCollection<SystemPerformanceMetrics> historicalData = new();
[ObservableProperty]
private int activeProcessCount;
private ObservableCollection<PerformanceTimelineEvent> timelineEvents = new();
[ObservableProperty]
private ProcessPerformanceInfo? selectedHotspotProcess;
[ObservableProperty]
private bool isMonitoring;
@@ -76,16 +63,22 @@ namespace ThreadPilot.ViewModels
private DateTime lastUpdateTime;
[ObservableProperty]
private ObservableCollection<SystemPerformanceMetrics> 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<string, DateTime> _lastRuleApplyByExecutable = new(StringComparer.OrdinalIgnoreCase);
private bool _monitoringWasActiveBeforeSuspend;
public PerformanceViewModel(
IPerformanceMonitoringService performanceService,
IProcessService processService,
IProcessPowerPlanAssociationService associationService,
IPowerPlanService powerPlanService,
IProcessMonitorManagerService processMonitorManagerService,
ISystemTweaksService systemTweaksService,
ILogger<PerformanceViewModel> 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<SystemPerformanceMetrics>(data);
SetStatus($"Loaded {data.Count} historical data points");
});
var history = await _performanceService.GetHistoricalDataAsync(TimeSpan.FromHours(1));
HistoricalData = new ObservableCollection<SystemPerformanceMetrics>(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<ProcessPerformanceInfo> 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<ProcessPerformanceInfo>(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<CpuCoreUsage>(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";
}
/// <summary>
/// PERFORMANCE OPTIMIZATION: Updates an ObservableCollection efficiently by only modifying changed items
/// </summary>
private void UpdateObservableCollection<T>(ObservableCollection<T> collection, IEnumerable<T> 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<string>();
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";
}
}
@@ -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
+52 -16
View File
@@ -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<ProcessViewModel> 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
/// </summary>
[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);
}
}
}
+106 -11
View File
@@ -15,8 +15,10 @@
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
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<PowerPlanModel> 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<string>();
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<bool> SaveIfDirtyAsync()
{
if (!HasUnsavedChanges)
{
return true;
}
await SaveSettingsAsync();
return !HasUnsavedChanges;
}
public async Task DiscardPendingChangesAsync()
{
if (!HasUnsavedChanges)
{
return;
}
await RefreshSettingsAsync();
}
}
}
+11 -11
View File
@@ -32,10 +32,10 @@
</StackPanel>
<!-- ListBox delle maschere -->
<Border BorderBrush="#CCCCCC" BorderThickness="1" CornerRadius="4">
<Border BorderBrush="{DynamicResource BorderBrush}" BorderThickness="1" CornerRadius="4">
<ListBox ItemsSource="{Binding CoreMasks}"
SelectedItem="{Binding SelectedCoreMask, Mode=TwoWay}"
Background="White"
Background="{DynamicResource SurfaceBrush}"
BorderThickness="0">
<ListBox.ItemTemplate>
<DataTemplate>
@@ -47,11 +47,11 @@
<StackPanel Grid.Column="0">
<TextBlock Text="{Binding Name}" FontWeight="SemiBold" FontSize="13"/>
<TextBlock Text="{Binding Description}"
FontSize="11" Foreground="#666666"
<TextBlock Text="{Binding Description}"
FontSize="11" Foreground="{DynamicResource TextSecondaryBrush}"
TextTrimming="CharacterEllipsis"
Margin="0,2,0,0"/>
<TextBlock FontSize="10" Foreground="#999999" Margin="0,2,0,0">
<TextBlock FontSize="10" Foreground="{DynamicResource TextSecondaryBrush}" Margin="0,2,0,0">
<Run Text="{Binding SelectedCoreCount, Mode=OneWay}"/>
<Run Text="/"/>
<Run Text="{Binding BoolMask.Count, Mode=OneWay}"/>
@@ -117,7 +117,7 @@
<StackPanel>
<!-- Core Checkboxes - Direct binding to BoolMask like CPUSetSetter -->
<TextBlock Text="Click checkboxes to toggle cores. Changes are saved automatically."
FontSize="11" Foreground="Gray" Margin="0,0,0,10"/>
FontSize="11" Foreground="{DynamicResource TextSecondaryBrush}" Margin="0,0,0,10"/>
<ScrollViewer VerticalScrollBarVisibility="Auto" MaxHeight="300">
<ItemsControl x:Name="CoreItemsControl" ItemsSource="{Binding CoreBits}">
<ItemsControl.ItemsPanel>
@@ -127,14 +127,14 @@
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Border BorderBrush="#CCCCCC" BorderThickness="1"
<Border BorderBrush="{DynamicResource BorderBrush}" BorderThickness="1"
Margin="2" Padding="4" CornerRadius="3">
<Border.Style>
<Style TargetType="Border">
<Setter Property="Background" Value="White"/>
<Setter Property="Background" Value="{DynamicResource SurfaceBrush}"/>
<Style.Triggers>
<DataTrigger Binding="{Binding IsSelected}" Value="True">
<Setter Property="Background" Value="#E3F2FD"/>
<Setter Property="Background" Value="{DynamicResource InfoBackgroundBrush}"/>
</DataTrigger>
</Style.Triggers>
</Style>
@@ -178,9 +178,9 @@
</Grid>
<!-- Status Bar -->
<Border Grid.Row="1" Background="#F5F5F5" Padding="10,5" Margin="0,10,0,0" CornerRadius="3">
<Border Grid.Row="1" Background="{DynamicResource SurfaceAltBrush}" Padding="10,5" Margin="0,10,0,0" CornerRadius="3">
<TextBlock Text="{Binding StatusMessage}"
FontSize="12" Foreground="#666666"
FontSize="12" Foreground="{DynamicResource TextSecondaryBrush}"
TextTrimming="CharacterEllipsis"/>
</Border>
</Grid>
+318 -156
View File
@@ -1,213 +1,375 @@
<UserControl x:Class="ThreadPilot.Views.PerformanceView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:ThreadPilot.Views"
mc:Ignorable="d"
d:DesignHeight="600" d:DesignWidth="800">
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">
<UserControl.Resources>
<Style x:Key="MetricCardStyle" TargetType="Border">
<Setter Property="Background" Value="#2D2D30"/>
<Setter Property="BorderBrush" Value="#3F3F46"/>
<Style x:Key="CardStyle" TargetType="Border">
<Setter Property="Background" Value="{DynamicResource SurfaceBrush}"/>
<Setter Property="BorderBrush" Value="{DynamicResource BorderBrush}"/>
<Setter Property="BorderThickness" Value="1"/>
<Setter Property="CornerRadius" Value="8"/>
<Setter Property="CornerRadius" Value="12"/>
<Setter Property="Padding" Value="16"/>
<Setter Property="Margin" Value="8"/>
<Setter Property="Margin" Value="0,0,0,12"/>
</Style>
<Style x:Key="MetricTitleStyle" TargetType="TextBlock">
<Setter Property="FontSize" Value="14"/>
<Style x:Key="TitleTextStyle" TargetType="TextBlock">
<Setter Property="FontSize" Value="16"/>
<Setter Property="FontWeight" Value="SemiBold"/>
<Setter Property="Foreground" Value="#E1E1E6"/>
<Setter Property="Margin" Value="0,0,0,8"/>
<Setter Property="Foreground" Value="{DynamicResource TextPrimaryBrush}"/>
</Style>
<Style x:Key="MetricValueStyle" TargetType="TextBlock">
<Setter Property="FontSize" Value="24"/>
<Setter Property="FontWeight" Value="Bold"/>
<Setter Property="Foreground" Value="#00D4FF"/>
</Style>
<Style x:Key="MetricSubtitleStyle" TargetType="TextBlock">
<Style x:Key="LabelTextStyle" TargetType="TextBlock">
<Setter Property="FontSize" Value="12"/>
<Setter Property="Foreground" Value="#A1A1AA"/>
<Setter Property="Margin" Value="0,4,0,0"/>
<Setter Property="Foreground" Value="{DynamicResource TextSecondaryBrush}"/>
</Style>
<Style x:Key="ValueTextStyle" TargetType="TextBlock">
<Setter Property="FontSize" Value="22"/>
<Setter Property="FontWeight" Value="Bold"/>
<Setter Property="Foreground" Value="{DynamicResource AccentBrush}"/>
</Style>
</UserControl.Resources>
<Grid Background="#1E1E1E" Margin="10">
<Grid Margin="12" Background="{DynamicResource AppBackgroundBrush}">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<!-- Standardized Header with Dark Theme -->
<GroupBox Grid.Row="0" Margin="0,0,0,10">
<GroupBox.Header>
<TextBlock Text="📊 Performance Dashboard" Foreground="#E1E1E6" FontWeight="Bold"/>
</GroupBox.Header>
<GroupBox.Style>
<Style TargetType="GroupBox">
<Setter Property="BorderBrush" Value="#3F3F46"/>
<Setter Property="BorderThickness" Value="1"/>
<Setter Property="Background" Value="#252526"/>
<Setter Property="Foreground" Value="#E1E1E6"/>
</Style>
</GroupBox.Style>
<Grid Margin="5">
<Border Grid.Row="0" Style="{StaticResource CardStyle}">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<StackPanel Grid.Column="0" Orientation="Horizontal">
<TextBlock Text="Real-time system performance monitoring and metrics"
FontSize="12" Foreground="#A1A1AA" VerticalAlignment="Center"/>
<TextBlock Text="{Binding UptimeText}" FontSize="12" Foreground="#A1A1AA" VerticalAlignment="Center" Margin="16,0,0,0"/>
<StackPanel Grid.Column="0">
<TextBlock Text="Performance Intelligence" Style="{StaticResource TitleTextStyle}"/>
<TextBlock Text="System snapshot, actionable hotspots, rule impact, and stability timeline." Style="{StaticResource LabelTextStyle}" Margin="0,4,0,0"/>
<TextBlock Text="All actions are safety-first and route through existing Rules and Tweaks workflows." Style="{StaticResource LabelTextStyle}" Margin="0,2,0,0"/>
</StackPanel>
<StackPanel Grid.Column="1" Orientation="Horizontal">
<Button Content="{Binding IsMonitoring, Converter={StaticResource BoolToStringConverter}, ConverterParameter='Stop Monitoring|Start Monitoring'}"
Command="{Binding ToggleMonitoringCommand}"
Background="#0E639C"
Foreground="White"
BorderThickness="0"
Padding="12,6"
Margin="8,0"/>
<WrapPanel Grid.Column="1" HorizontalAlignment="Right" VerticalAlignment="Center" ItemHeight="32">
<Button Content="Start Monitoring"
Command="{Binding StartMonitoringCommand}"
IsEnabled="{Binding IsMonitoring, Converter={StaticResource InverseBooleanConverter}}"
MinWidth="118"
Margin="0,0,8,0"/>
<Button Content="Stop Monitoring"
Command="{Binding StopMonitoringCommand}"
IsEnabled="{Binding IsMonitoring}"
MinWidth="108"
Margin="0,0,8,0"/>
<Button Content="Refresh"
Command="{Binding RefreshMetricsCommand}"
MinWidth="84"
Margin="0,0,8,0"/>
<Button Content="Clear History"
Command="{Binding ClearHistoryCommand}"
Background="#DC3545"
Foreground="White"
BorderThickness="0"
Padding="12,6"
Margin="8,0"/>
</StackPanel>
MinWidth="104"
Command="{Binding ClearHistoricalDataCommand}"/>
</WrapPanel>
</Grid>
</GroupBox>
<!-- Metrics Overview -->
<Grid Grid.Row="1" Margin="8">
</Border>
<Grid Grid.Row="1" Margin="0,0,0,12">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<!-- CPU Usage -->
<Border Grid.Column="0" Style="{StaticResource MetricCardStyle}">
<Border Grid.Column="0" Style="{StaticResource CardStyle}" Margin="0,0,10,0">
<StackPanel>
<TextBlock Text="CPU Usage" Style="{StaticResource MetricTitleStyle}"/>
<TextBlock Text="{Binding CurrentMetrics.TotalCpuUsage, StringFormat={}{0:F1}%}" Style="{StaticResource MetricValueStyle}"/>
<TextBlock Text="{Binding CurrentMetrics.LogicalCoreCount, StringFormat={}{0} cores}" Style="{StaticResource MetricSubtitleStyle}"/>
<TextBlock Text="CPU" Style="{StaticResource LabelTextStyle}"/>
<TextBlock Text="{Binding CpuUsageText}" Style="{StaticResource ValueTextStyle}"/>
<TextBlock Text="{Binding LastManualRefreshText}" Style="{StaticResource LabelTextStyle}"/>
</StackPanel>
</Border>
<!-- Memory Usage -->
<Border Grid.Column="1" Style="{StaticResource MetricCardStyle}">
<Border Grid.Column="1" Style="{StaticResource CardStyle}" Margin="0,0,10,0">
<StackPanel>
<TextBlock Text="Memory Usage" Style="{StaticResource MetricTitleStyle}"/>
<TextBlock Text="{Binding CurrentMetrics.MemoryUsage.UsagePercentage, StringFormat={}{0:F1}%}" Style="{StaticResource MetricValueStyle}"/>
<TextBlock Text="{Binding MemoryUsageText}" Style="{StaticResource MetricSubtitleStyle}"/>
<TextBlock Text="Memory" Style="{StaticResource LabelTextStyle}"/>
<TextBlock Text="{Binding MemoryUsageText}" Style="{StaticResource ValueTextStyle}" FontSize="18"/>
<TextBlock Text="{Binding MemoryUsagePercentage, StringFormat={}{0:F1}% utilized}" Style="{StaticResource LabelTextStyle}"/>
</StackPanel>
</Border>
<!-- Top Process -->
<Border Grid.Column="2" Style="{StaticResource MetricCardStyle}">
<Border Grid.Column="2" Style="{StaticResource CardStyle}" Margin="0,0,10,0">
<StackPanel>
<TextBlock Text="Top CPU Process" Style="{StaticResource MetricTitleStyle}"/>
<TextBlock Text="{Binding TopProcess.ProcessName}" Style="{StaticResource MetricValueStyle}" FontSize="16"/>
<TextBlock Text="{Binding TopProcess.CpuUsage, StringFormat={}{0:F1}% CPU}" Style="{StaticResource MetricSubtitleStyle}"/>
<TextBlock Text="Active Processes" Style="{StaticResource LabelTextStyle}"/>
<TextBlock Text="{Binding ProcessCountText}" Style="{StaticResource ValueTextStyle}"/>
<TextBlock Text="{Binding MonitoringStateText, StringFormat=Monitoring: {0}}" Style="{StaticResource LabelTextStyle}"/>
</StackPanel>
</Border>
<!-- Performance Cores -->
<Border Grid.Column="3" Style="{StaticResource MetricCardStyle}">
<Border Grid.Column="3" Style="{StaticResource CardStyle}" Margin="0">
<StackPanel>
<TextBlock Text="P-Cores Usage" Style="{StaticResource MetricTitleStyle}"/>
<TextBlock Text="{Binding PerformanceCoresUsage, StringFormat={}{0:F1}%}" Style="{StaticResource MetricValueStyle}"/>
<TextBlock Text="{Binding PerformanceCoresCount, StringFormat={}{0} P-cores}" Style="{StaticResource MetricSubtitleStyle}"/>
<TextBlock Text="Global Power Plan" Style="{StaticResource LabelTextStyle}"/>
<TextBlock Text="{Binding CurrentGlobalPowerPlanText}" Style="{StaticResource ValueTextStyle}" FontSize="16"/>
<TextBlock Text="{Binding LastUpdateTime, StringFormat=Last metric update: {0:HH:mm:ss}}" Style="{StaticResource LabelTextStyle}"/>
</StackPanel>
</Border>
</Grid>
<!-- Detailed Views -->
<TabControl Grid.Row="2" Background="#1E1E1E" BorderThickness="0" Margin="8">
<TabControl.Resources>
<Style TargetType="TabItem">
<Setter Property="Background" Value="#2D2D30"/>
<Setter Property="Foreground" Value="#E1E1E6"/>
<Setter Property="BorderThickness" Value="0"/>
<Setter Property="Padding" Value="12,8"/>
<Setter Property="Margin" Value="0,0,2,0"/>
</Style>
</TabControl.Resources>
<!-- Per-Core CPU Usage -->
<TabItem Header="Per-Core Usage">
<Grid Background="#1E1E1E">
<ScrollViewer VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Disabled">
<ItemsControl ItemsSource="{Binding CurrentMetrics.CpuCores}" Margin="16">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<UniformGrid Columns="4"/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Border Style="{StaticResource MetricCardStyle}" Margin="4">
<StackPanel>
<TextBlock Text="{Binding CoreId, StringFormat=Core {0}}" Style="{StaticResource MetricTitleStyle}" FontSize="12"/>
<TextBlock Text="{Binding Usage, StringFormat={}{0:F1}%}" Style="{StaticResource MetricValueStyle}" FontSize="18"/>
<TextBlock Text="{Binding CoreType}" Style="{StaticResource MetricSubtitleStyle}"/>
<ProgressBar Value="{Binding Usage}" Maximum="100" Height="4" Margin="0,4,0,0"
Background="#3F3F46" Foreground="#00D4FF"/>
</StackPanel>
</Border>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</ScrollViewer>
</Grid>
</TabItem>
<!-- Top Processes -->
<TabItem Header="Top Processes">
<Grid Background="#1E1E1E">
<DataGrid ItemsSource="{Binding CurrentMetrics.TopProcesses}"
<Grid Grid.Row="2">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="2.2*"/>
<ColumnDefinition Width="1.3*"/>
</Grid.ColumnDefinitions>
<Border Grid.Column="0" Style="{StaticResource CardStyle}" Margin="0,0,10,0">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Grid Grid.Row="0" Margin="0,0,0,10">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<StackPanel Grid.Column="0">
<TextBlock Text="Process Hotspots" Style="{StaticResource TitleTextStyle}"/>
<TextBlock Text="Top CPU and memory consumers with one-click rule creation." Style="{StaticResource LabelTextStyle}" Margin="0,2,0,0"/>
</StackPanel>
<StackPanel Grid.Column="1" Orientation="Horizontal" VerticalAlignment="Center">
<Button Content="Create/Update Rule from Selection"
Command="{Binding CreateRuleFromSelectedProcessCommand}"
IsEnabled="{Binding CanCreateRuleFromSelectedProcess}"
Margin="0,0,8,0"/>
<Button Content="Toggle Core Panel"
Command="{Binding ToggleCoreDetailsCommand}"
Margin="0,0,8,0"/>
<Button Content="Toggle Process Panel"
Command="{Binding ToggleProcessDetailsCommand}"/>
</StackPanel>
</Grid>
<Grid Grid.Row="1" Margin="0,0,0,10">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="2*"/>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<TextBlock Grid.Column="0"
Text="Filter"
Style="{StaticResource LabelTextStyle}"
Margin="0,0,8,0"
VerticalAlignment="Center"/>
<TextBox Grid.Column="1"
Text="{Binding ProcessSearchText, UpdateSourceTrigger=PropertyChanged}"
MinWidth="220"
Margin="0,0,8,0"
VerticalContentAlignment="Center"/>
<ComboBox Grid.Column="2"
SelectedValue="{Binding SortMode}"
SelectedValuePath="Tag"
Width="110"
Margin="0,0,8,0">
<ComboBoxItem Content="CPU" Tag="Cpu"/>
<ComboBoxItem Content="Memory" Tag="Memory"/>
<ComboBoxItem Content="Name" Tag="Name"/>
</ComboBox>
<CheckBox Grid.Column="3"
Content="Actionable only"
IsChecked="{Binding ShowOnlyActionableHotspots}"
Margin="0,0,8,0"
VerticalAlignment="Center"/>
<CheckBox Grid.Column="4"
Content="Rule-backed only"
IsChecked="{Binding ShowOnlyRuleBackedHotspots}"
Margin="0,0,8,0"
VerticalAlignment="Center"/>
<TextBlock Grid.Column="5"
Text="{Binding MonitoringStatusText}"
Style="{StaticResource LabelTextStyle}"
VerticalAlignment="Center"/>
</Grid>
<DataGrid Grid.Row="2"
ItemsSource="{Binding TopCpuProcesses}"
SelectedItem="{Binding SelectedHotspotProcess}"
Visibility="{Binding ShowProcessDetails, Converter={StaticResource BoolToVisibilityConverter}}"
AutoGenerateColumns="False"
Background="#1E1E1E"
Foreground="#E1E1E6"
GridLinesVisibility="Horizontal"
HeadersVisibility="Column"
CanUserAddRows="False"
CanUserDeleteRows="False"
IsReadOnly="True"
Margin="16">
HeadersVisibility="Column"
GridLinesVisibility="Horizontal">
<DataGrid.Columns>
<DataGridTextColumn Header="Process" Binding="{Binding ProcessName}" Width="*"/>
<DataGridTextColumn Header="Window Title" Binding="{Binding WindowTitle}" Width="2*"/>
<DataGridTextColumn Header="CPU %" Binding="{Binding CpuUsage, StringFormat={}{0:F1}}" Width="80"/>
<DataGridTextColumn Header="Memory" Binding="{Binding MemoryUsage, Converter={StaticResource BytesToStringConverter}}" Width="100"/>
<DataGridTextColumn Header="Process" Binding="{Binding ProcessName}" Width="2*"/>
<DataGridTextColumn Header="CPU %" Binding="{Binding CpuUsage, StringFormat={}{0:F1}}" Width="90"/>
<DataGridTextColumn Header="Memory" Binding="{Binding MemoryUsage, Converter={StaticResource BytesToStringConverter}}" Width="110"/>
<DataGridTextColumn Header="Threads" Binding="{Binding ThreadCount}" Width="80"/>
<DataGridTextColumn Header="Priority" Binding="{Binding Priority}" Width="100"/>
<DataGridTextColumn Header="Priority" Binding="{Binding Priority}" Width="110"/>
<DataGridTextColumn Header="Window" Binding="{Binding WindowTitle}" Width="3*"/>
</DataGrid.Columns>
</DataGrid>
<Border Grid.Row="3"
Margin="0,10,0,0"
Padding="10,7"
CornerRadius="6"
BorderThickness="1"
Visibility="{Binding StatusMessage, Converter={x:Static converters:StringToVisibilityConverter.Instance}}">
<Border.Style>
<Style TargetType="Border">
<Setter Property="Background" Value="{DynamicResource SuccessBackgroundBrush}"/>
<Setter Property="BorderBrush" Value="{DynamicResource SuccessBorderBrush}"/>
<Style.Triggers>
<DataTrigger Binding="{Binding HasError}" Value="True">
<Setter Property="Background" Value="{DynamicResource ErrorBackgroundBrush}"/>
<Setter Property="BorderBrush" Value="{DynamicResource ErrorBorderBrush}"/>
</DataTrigger>
</Style.Triggers>
</Style>
</Border.Style>
<TextBlock Text="{Binding StatusMessage}">
<TextBlock.Style>
<Style TargetType="TextBlock">
<Setter Property="Foreground" Value="{DynamicResource SuccessTextBrush}"/>
<Style.Triggers>
<DataTrigger Binding="{Binding HasError}" Value="True">
<Setter Property="Foreground" Value="{DynamicResource ErrorTextBrush}"/>
</DataTrigger>
</Style.Triggers>
</Style>
</TextBlock.Style>
</TextBlock>
</Border>
</Grid>
</TabItem>
<!-- Historical Data -->
<TabItem Header="History">
<Grid Background="#1E1E1E">
<TextBlock Text="Historical performance charts will be implemented here"
HorizontalAlignment="Center"
VerticalAlignment="Center"
Foreground="#A1A1AA"
FontSize="16"/>
</Grid>
</TabItem>
</TabControl>
</Border>
<Grid Grid.Column="1">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Border Grid.Row="0" Style="{StaticResource CardStyle}">
<StackPanel>
<TextBlock Text="Rule Impact" Style="{StaticResource TitleTextStyle}"/>
<TextBlock Text="Selected hotspot process" Style="{StaticResource LabelTextStyle}" Margin="0,4,0,8"/>
<TextBlock Text="{Binding SelectedProcessName}" FontWeight="SemiBold" FontSize="14"/>
<TextBlock Text="{Binding SelectedProcessExecutable}" Style="{StaticResource LabelTextStyle}" TextWrapping="Wrap" TextTrimming="CharacterEllipsis" Margin="0,2,0,8"/>
<TextBlock Text="{Binding SelectedProcessCpuText}"/>
<TextBlock Text="{Binding SelectedProcessMemoryText}" Margin="0,2,0,8"/>
<TextBlock Text="{Binding SelectedProcessRuleStatus}" FontWeight="SemiBold"/>
<TextBlock Text="{Binding SelectedProcessRuleSummary}" Style="{StaticResource LabelTextStyle}" TextWrapping="Wrap" Margin="0,2,0,0"/>
<TextBlock Text="{Binding SelectedProcessLastApplyText}" Style="{StaticResource LabelTextStyle}" Margin="0,8,0,0"/>
</StackPanel>
</Border>
<Border Grid.Row="1" Style="{StaticResource CardStyle}">
<StackPanel>
<TextBlock Text="Core Snapshot" Style="{StaticResource TitleTextStyle}"/>
<TextBlock Text="Per-core utilization for quick imbalance checks." Style="{StaticResource LabelTextStyle}" Margin="0,4,0,8"/>
<ScrollViewer VerticalScrollBarVisibility="Auto"
HorizontalScrollBarVisibility="Disabled"
MaxHeight="220"
Visibility="{Binding ShowCoreDetails, Converter={StaticResource BoolToVisibilityConverter}}">
<ItemsControl ItemsSource="{Binding CoreUsages}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<UniformGrid Columns="2"/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Border BorderBrush="{DynamicResource BorderBrush}" BorderThickness="1" CornerRadius="6" Padding="8" Margin="0,0,6,6" Background="{DynamicResource SurfaceAltBrush}">
<StackPanel>
<TextBlock Text="{Binding CoreId, StringFormat=Core {0}}" FontWeight="SemiBold"/>
<TextBlock Text="{Binding CoreType}" Style="{StaticResource LabelTextStyle}"/>
<ProgressBar Value="{Binding Usage}" Maximum="100" Height="5" Margin="0,6,0,2"/>
<TextBlock Text="{Binding Usage, StringFormat={}{0:F1}%}" Style="{StaticResource LabelTextStyle}"/>
</StackPanel>
</Border>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</ScrollViewer>
</StackPanel>
</Border>
<Border Grid.Row="2" Style="{StaticResource CardStyle}" Margin="0,0,0,0">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<TextBlock Grid.Row="0" Text="Stability Timeline" Style="{StaticResource TitleTextStyle}"/>
<StackPanel Grid.Row="1" Orientation="Horizontal" Margin="0,6,0,8">
<TextBlock Text="{Binding TimelineSampleCountText}" Style="{StaticResource LabelTextStyle}" Margin="0,0,14,0"/>
<TextBlock Text="{Binding LastTimelineEventText}" Style="{StaticResource LabelTextStyle}"/>
</StackPanel>
<TabControl Grid.Row="2">
<TabItem Header="Events">
<DataGrid ItemsSource="{Binding TimelineEvents}"
AutoGenerateColumns="False"
IsReadOnly="True"
CanUserAddRows="False"
CanUserDeleteRows="False"
GridLinesVisibility="Horizontal"
HeadersVisibility="Column">
<DataGrid.Columns>
<DataGridTextColumn Header="Time" Binding="{Binding Timestamp, StringFormat={}{0:HH:mm:ss}}" Width="80"/>
<DataGridTextColumn Header="Category" Binding="{Binding Category}" Width="110"/>
<DataGridTextColumn Header="Severity" Binding="{Binding Severity}" Width="90"/>
<DataGridTextColumn Header="Detail" Binding="{Binding Detail}" Width="*"/>
</DataGrid.Columns>
</DataGrid>
</TabItem>
<TabItem Header="Metrics">
<DataGrid ItemsSource="{Binding HistoricalData}"
AutoGenerateColumns="False"
IsReadOnly="True"
CanUserAddRows="False"
CanUserDeleteRows="False"
GridLinesVisibility="Horizontal"
HeadersVisibility="Column">
<DataGrid.Columns>
<DataGridTextColumn Header="Time" Binding="{Binding Timestamp, StringFormat={}{0:HH:mm:ss}}" Width="80"/>
<DataGridTextColumn Header="CPU %" Binding="{Binding TotalCpuUsage, StringFormat={}{0:F1}}" Width="70"/>
<DataGridTextColumn Header="Mem %" Binding="{Binding MemoryUsagePercentage, StringFormat={}{0:F1}}" Width="70"/>
<DataGridTextColumn Header="Processes" Binding="{Binding ActiveProcessCount}" Width="90"/>
<DataGridTextColumn Header="Memory Used" Binding="{Binding TotalMemoryUsage, Converter={StaticResource BytesToStringConverter}}" Width="110"/>
</DataGrid.Columns>
</DataGrid>
</TabItem>
</TabControl>
</Grid>
</Border>
</Grid>
</Grid>
</Grid>
</UserControl>
+3 -3
View File
@@ -47,7 +47,7 @@
<TextBlock Text="{Binding Name}"
FontWeight="{Binding IsActive, Converter={StaticResource BoolToFontWeightConverter}}"/>
<TextBlock Text="{Binding Guid}"
Foreground="Gray"
Foreground="{DynamicResource TextSecondaryBrush}"
FontSize="11"/>
</StackPanel>
</DataTemplate>
@@ -78,7 +78,7 @@
<StackPanel Margin="5">
<TextBlock Text="{Binding Name}"/>
<TextBlock Text="{Binding FilePath}"
Foreground="Gray"
Foreground="{DynamicResource TextSecondaryBrush}"
FontSize="11"/>
</StackPanel>
</DataTemplate>
@@ -107,4 +107,4 @@
ToolTip="Import a custom power plan from file"/>
</StackPanel>
</Grid>
</UserControl>
</UserControl>
+5 -2
View File
@@ -15,7 +15,6 @@
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
using System.Windows.Controls;
using ThreadPilot.Helpers;
using ThreadPilot.ViewModels;
namespace ThreadPilot.Views
@@ -25,7 +24,11 @@ namespace ThreadPilot.Views
public PowerPlanView()
{
InitializeComponent();
DataContext = ServiceProviderExtensions.GetService<PowerPlanViewModel>();
}
public PowerPlanView(PowerPlanViewModel viewModel) : this()
{
DataContext = viewModel;
}
}
}
+82 -39
View File
@@ -20,18 +20,18 @@
</Grid.RowDefinitions>
<!-- Standardized Header -->
<GroupBox Grid.Row="0" Header="🔗 Process-Power Plan Associations" Margin="0,0,0,10">
<GroupBox Grid.Row="0" Header="📐 Rules &amp; Automation" Margin="0,0,0,10">
<Grid Margin="5">
<TextBlock Text="Configure automatic power plan switching based on running processes"
FontSize="12" Foreground="Gray" VerticalAlignment="Center"/>
<TextBlock Text="Define per-process rules. Power plans are global; masks and priorities apply to matching processes."
FontSize="12" Foreground="{DynamicResource TextSecondaryBrush}" VerticalAlignment="Center"/>
</Grid>
</GroupBox>
<!-- Main Content -->
<TabControl Grid.Row="1" Background="White" BorderThickness="0">
<TabControl Grid.Row="1" Background="{DynamicResource SurfaceBrush}" BorderThickness="0">
<!-- Associations Tab -->
<TabItem Header="🔗 Process Associations">
<!-- Rules Tab -->
<TabItem Header="📐 Rules">
<Grid Margin="10">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="2*"/>
@@ -39,8 +39,8 @@
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<!-- Associations List -->
<GroupBox Grid.Column="0" Header="📋 Current Associations">
<!-- Rules List -->
<GroupBox Grid.Column="0" Header="📋 Current Rules">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
@@ -71,9 +71,9 @@
<DataGridTextColumn Header="Priority"
Binding="{Binding ProcessPriority}"
Width="80"/>
<DataGridTextColumn Header="Assoc. Priority"
Binding="{Binding Priority}"
Width="60"/>
<DataGridTextColumn Header="Rule Priority"
Binding="{Binding Priority}"
Width="60"/>
<DataGridCheckBoxColumn Header="Match by Path"
Binding="{Binding MatchByPath}"
Width="100"/>
@@ -97,8 +97,8 @@
</Grid>
</GroupBox>
<!-- Add New Association -->
<GroupBox Grid.Column="2" Header="Add New Association">
<!-- Rule Editor -->
<GroupBox Grid.Column="2" Header="Rule Editor">
<ScrollViewer VerticalScrollBarVisibility="Auto">
<StackPanel>
<!-- Executable Selection Section -->
@@ -112,17 +112,17 @@
ToolTip="Click to select an executable file (.exe) from your computer"/>
<!-- Selected Executable Display -->
<Border BorderBrush="#CCCCCC" BorderThickness="1"
Background="#F8F8F8" Padding="8" Margin="0,0,0,10"
Visibility="{Binding HasSelectedExecutable, Converter={StaticResource BoolToVisibilityConverter}}">
<StackPanel>
<TextBlock Text="Selected Executable:" FontSize="10" Foreground="#666666" Margin="0,0,0,2"/>
<TextBlock Text="{Binding SelectedExecutableDisplayName}"
FontWeight="Bold" Margin="0,0,0,2"/>
<TextBlock Text="{Binding SelectedExecutableFullPath}"
FontSize="10" Foreground="#666666" TextWrapping="Wrap"/>
</StackPanel>
</Border>
<Border BorderBrush="{DynamicResource BorderBrush}" BorderThickness="1"
Background="{DynamicResource SurfaceAltBrush}" Padding="8" Margin="0,0,0,10"
Visibility="{Binding HasSelectedExecutable, Converter={StaticResource BoolToVisibilityConverter}}">
<StackPanel>
<TextBlock Text="Selected Executable:" FontSize="10" Foreground="{DynamicResource TextSecondaryBrush}" Margin="0,0,0,2"/>
<TextBlock Text="{Binding SelectedExecutableDisplayName}"
FontWeight="Bold" Margin="0,0,0,2"/>
<TextBlock Text="{Binding SelectedExecutableFullPath}"
FontSize="10" Foreground="{DynamicResource TextSecondaryBrush}" TextWrapping="Wrap"/>
</StackPanel>
</Border>
<!-- Clear Selection Button -->
<Button Content="✖ Clear Selection"
@@ -137,7 +137,12 @@
Margin="0,0,0,10"
ToolTip="Match processes by full path instead of just executable name"/>
<TextBlock Text="Power Plan:" Margin="0,0,0,5"/>
<TextBlock Text="Power Plan (Global):" Margin="0,0,0,5" FontWeight="SemiBold"/>
<TextBlock Text="Changing this rule changes the system power plan when matched."
Foreground="{DynamicResource WarningTextBrush}"
FontSize="10"
TextWrapping="Wrap"
Margin="0,0,0,5"/>
<ComboBox ItemsSource="{Binding AvailablePowerPlans}"
SelectedItem="{Binding SelectedPowerPlan}"
DisplayMemberPath="Name"
@@ -165,14 +170,19 @@
<TextBox Text="{Binding Description}"
Padding="5" Margin="0,0,0,15"/>
<Button Content="Add Association"
Command="{Binding AddAssociationCommand}"
Padding="10,8"/>
<Button Content="Add Rule"
Command="{Binding AddAssociationCommand}"
Padding="10,8"/>
<Button Content="Update Selected Rule"
Command="{Binding UpdateAssociationCommand}"
Padding="10,8"
Margin="0,8,0,0"/>
<Separator Margin="0,15,0,15"/>
<TextBlock Text="Or Select from Running Processes:"
FontWeight="Bold" Margin="0,0,0,10"/>
<TextBlock Text="Use Running Process:"
FontWeight="Bold" Margin="0,0,0,10"/>
<ComboBox ItemsSource="{Binding RunningProcesses}"
SelectedItem="{Binding SelectedProcess}"
@@ -181,17 +191,17 @@
ToolTip="Select a currently running process to use its executable"/>
<Button Content="📋 Use Selected Process"
Command="{Binding UseSelectedProcessForAssociationCommand}"
Padding="10,5"
ToolTip="Use the executable from the selected running process"/>
Command="{Binding UseSelectedProcessForAssociationCommand}"
Padding="10,5"
ToolTip="Use the executable from the selected running process"/>
</StackPanel>
</ScrollViewer>
</GroupBox>
</Grid>
</TabItem>
<!-- Settings Tab -->
<TabItem Header="⚙️ Configuration">
<!-- Monitoring Configuration Tab -->
<TabItem Header="⚙️ Monitoring Configuration">
<ScrollViewer Margin="10">
<StackPanel>
<!-- Service Control -->
@@ -218,10 +228,10 @@
</GroupBox>
<!-- Default Power Plan -->
<GroupBox Header="Default Power Plan" Margin="0,0,0,15">
<StackPanel>
<TextBlock Text="Power plan to use when no associated processes are running:"
Foreground="#666666" Margin="0,0,0,10"/>
<GroupBox Header="Default Power Plan (Global fallback)" Margin="0,0,0,15">
<StackPanel>
<TextBlock Text="Power plan to use when no associated processes are running:"
Foreground="{DynamicResource TextSecondaryBrush}" Margin="0,0,0,10"/>
<ComboBox ItemsSource="{Binding AvailablePowerPlans}"
SelectedItem="{Binding DefaultPowerPlan}"
@@ -272,5 +282,38 @@
</ScrollViewer>
</TabItem>
</TabControl>
<Border Grid.Row="1"
VerticalAlignment="Bottom"
Margin="10"
Padding="10,7"
CornerRadius="6"
BorderThickness="1"
Visibility="{Binding StatusMessage, Converter={x:Static converters:StringToVisibilityConverter.Instance}}">
<Border.Style>
<Style TargetType="Border">
<Setter Property="Background" Value="{DynamicResource SuccessBackgroundBrush}"/>
<Setter Property="BorderBrush" Value="{DynamicResource SuccessBorderBrush}"/>
<Style.Triggers>
<DataTrigger Binding="{Binding HasError}" Value="True">
<Setter Property="Background" Value="{DynamicResource ErrorBackgroundBrush}"/>
<Setter Property="BorderBrush" Value="{DynamicResource ErrorBorderBrush}"/>
</DataTrigger>
</Style.Triggers>
</Style>
</Border.Style>
<TextBlock Text="{Binding StatusMessage}">
<TextBlock.Style>
<Style TargetType="TextBlock">
<Setter Property="Foreground" Value="{DynamicResource SuccessTextBrush}"/>
<Style.Triggers>
<DataTrigger Binding="{Binding HasError}" Value="True">
<Setter Property="Foreground" Value="{DynamicResource ErrorTextBrush}"/>
</DataTrigger>
</Style.Triggers>
</Style>
</TextBlock.Style>
</TextBlock>
</Border>
</Grid>
</UserControl>
+64 -28
View File
@@ -14,6 +14,7 @@
<converters:CoreTypeToColorConverter x:Key="CoreTypeToColorConverter"/>
<converters:BoolToColorConverter x:Key="BoolToColorConverter"/>
<converters:BoolToVisibilityConverter x:Key="BoolToVisibilityConverter"/>
<converters:NullToBoolConverter x:Key="NullToBoolConverter"/>
<converters:AffinityMaskConverter x:Key="AffinityMaskConverter"/>
<converters:BytesToMbConverter x:Key="BytesToMbConverter"/>
</UserControl.Resources>
@@ -116,7 +117,7 @@
</DataGrid>
<!-- Progressive Loading Indicator -->
<Border Background="#80FFFFFF" Visibility="{Binding IsBusy, Converter={StaticResource BoolToVisibilityConverter}}">
<Border Background="{DynamicResource OverlayBrush}" Visibility="{Binding IsBusy, Converter={StaticResource BoolToVisibilityConverter}}">
<StackPanel HorizontalAlignment="Center" VerticalAlignment="Center">
<ProgressBar Value="{Binding LoadingProgress}" Maximum="100" Width="200" Height="20" Margin="0,0,0,10"/>
<TextBlock Text="{Binding LoadingStatusText}" HorizontalAlignment="Center" FontWeight="Bold"/>
@@ -124,12 +125,12 @@
</Border>
<!-- Virtualization Status -->
<Border Background="#F0F8FF" BorderBrush="#4169E1" BorderThickness="1"
<Border Background="{DynamicResource InfoBackgroundBrush}" BorderBrush="{DynamicResource InfoBorderBrush}" BorderThickness="1"
Visibility="{Binding IsVirtualizationEnabled, Converter={StaticResource BoolToVisibilityConverter}}"
HorizontalAlignment="Right" VerticalAlignment="Bottom" Margin="10" Padding="5">
<StackPanel Orientation="Horizontal">
<TextBlock Text="📊" FontSize="12" Margin="0,0,3,0"/>
<TextBlock FontSize="10" Foreground="#4169E1">
<TextBlock FontSize="10" Foreground="{DynamicResource InfoTextBrush}">
<Run Text="Batch:"/>
<Run Text="{Binding CurrentBatchIndex, StringFormat={}{0:N0}}"/>
<Run Text="/"/>
@@ -164,7 +165,7 @@
SelectedValue="{Binding SelectedProcess.Priority, Mode=TwoWay}"
SelectedValuePath="Tag"
Margin="0,0,0,5"
IsEnabled="{Binding SelectedProcess, Converter={StaticResource BoolToVisibilityConverter}}">
IsEnabled="{Binding SelectedProcess, Converter={StaticResource NullToBoolConverter}}">
<ComboBoxItem Content="Realtime" Tag="{x:Static Diagnostics:ProcessPriorityClass.RealTime}"/>
<ComboBoxItem Content="High" Tag="{x:Static Diagnostics:ProcessPriorityClass.High}"/>
<ComboBoxItem Content="Above Normal" Tag="{x:Static Diagnostics:ProcessPriorityClass.AboveNormal}"/>
@@ -177,20 +178,20 @@
Content="Set Priority"
Padding="10,5"
Margin="0,0,0,5"
IsEnabled="{Binding SelectedProcess, Converter={StaticResource BoolToVisibilityConverter}}"
IsEnabled="{Binding SelectedProcess, Converter={StaticResource NullToBoolConverter}}"
ToolTip="Apply the selected priority to the process"/>
<!-- Registry Priority Enforcement -->
<CheckBox Content="Enforce Priority by Registry"
IsChecked="{Binding IsRegistryPriorityEnabled}"
IsEnabled="{Binding SelectedProcess, Converter={StaticResource BoolToVisibilityConverter}}"
IsEnabled="{Binding SelectedProcess, Converter={StaticResource NullToBoolConverter}}"
Margin="0,0,0,5"
ToolTip="Apply priority through Windows registry. Process must be restarted for changes to take effect. This setting persists across system reboots."/>
<!-- Disable Idle Server -->
<CheckBox Content="Disable Idle Server"
IsChecked="{Binding IsIdleServerDisabled}"
IsEnabled="{Binding SelectedProcess, Converter={StaticResource BoolToVisibilityConverter}}"
IsEnabled="{Binding SelectedProcess, Converter={StaticResource NullToBoolConverter}}"
ToolTip="Prevents the system from entering idle state while this process is running. Useful for games and performance-critical applications."/>
</StackPanel>
</GroupBox>
@@ -198,7 +199,7 @@
<!-- Core Mask Selection -->
<GroupBox Grid.Column="1" Header="Core Mask" Margin="5,0,5,0">
<StackPanel Margin="5">
<TextBlock Text="Quick apply a predefined core mask:" FontSize="10" Margin="0,0,0,5" Foreground="Gray"/>
<TextBlock Text="Quick apply a predefined core mask:" FontSize="10" Margin="0,0,0,5" Foreground="{DynamicResource TextSecondaryBrush}"/>
<ComboBox ItemsSource="{Binding AvailableCoreMasks}"
SelectedItem="{Binding SelectedCoreMask, Mode=TwoWay}"
Margin="0,0,0,5">
@@ -207,7 +208,7 @@
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Name}" FontWeight="SemiBold" Margin="0,0,8,0"/>
<TextBlock Text="{Binding SelectedCoreCount, StringFormat='({0} cores)'}"
FontSize="10" Foreground="Gray" VerticalAlignment="Center"/>
FontSize="10" Foreground="{DynamicResource TextSecondaryBrush}" VerticalAlignment="Center"/>
</StackPanel>
</DataTemplate>
</ComboBox.ItemTemplate>
@@ -217,23 +218,25 @@
Padding="8,5"
Margin="0,0,0,5"
ToolTip="Open Core Masks tab to create a new custom mask"/>
<TextBlock FontSize="9" Foreground="DarkGreen" TextWrapping="Wrap">
<TextBlock FontSize="9" Foreground="{DynamicResource SuccessTextBrush}" TextWrapping="Wrap">
<Run Text="ℹ️ Selecting a mask applies it immediately to the selected process."/>
</TextBlock>
</StackPanel>
</GroupBox>
<!-- Power Plan Selection -->
<GroupBox Grid.Column="2" Header="Power Plan" Margin="5,0,5,0">
<!-- Global Power Plan Notice -->
<GroupBox Grid.Column="2" Header="Global Power Plan" Margin="5,0,5,0">
<StackPanel Margin="5">
<ComboBox ItemsSource="{Binding PowerPlans}"
SelectedItem="{Binding SelectedPowerPlan}"
DisplayMemberPath="Name"
Margin="0,0,0,5"/>
<Button Command="{Binding SetPowerPlanCommand}"
Content="Set Power Plan"
<TextBlock Text="Power plans are system-wide." FontWeight="SemiBold" Margin="0,0,0,4"/>
<TextBlock Text="Use the Power Plans or Rules tab to change them intentionally."
TextWrapping="Wrap"
Foreground="{DynamicResource TextSecondaryBrush}"
FontSize="11"
Margin="0,0,0,8"/>
<Button Content="Open Rules"
Command="{Binding OpenRulesTabCommand}"
Padding="10,5"
ToolTip="Apply the selected power plan to the system"/>
ToolTip="Open Rules to configure process-based automation"/>
</StackPanel>
</GroupBox>
@@ -294,12 +297,13 @@
</GroupBox>
</Grid>
<!-- Profile Management & Process Association -->
<GroupBox Grid.Row="1" Header="Profile Management &amp; Process Association" Margin="0,10,0,0">
<!-- Profile Management & Rule Save -->
<GroupBox Grid.Row="1" Header="Profile Management &amp; Rule Save" Margin="0,10,0,0">
<Grid Margin="5">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<!-- Profile Management Row -->
@@ -327,7 +331,7 @@
ToolTip="Load a previously saved profile"/>
</Grid>
<!-- Process Association Row -->
<!-- Rule Save Row -->
<Grid Grid.Row="1">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
@@ -337,20 +341,52 @@
<TextBlock Grid.Column="0"
VerticalAlignment="Center"
TextWrapping="Wrap"
Foreground="Gray"
Foreground="{DynamicResource TextSecondaryBrush}"
FontSize="11">
<Run Text="💾 Save current settings (CPU mask, priority, power plan) as an automatic association for this process"/>
<Run Text="💾 Save current settings (CPU mask, priority) as an automatic rule for this process"/>
</TextBlock>
<Button Grid.Column="1"
Command="{Binding SaveCurrentAsAssociationCommand}"
Content="💾 Save as Association"
Content="💾 Save as Rule"
Padding="12,6"
FontWeight="SemiBold"
IsEnabled="{Binding SelectedProcess, Converter={StaticResource BoolToVisibilityConverter}}"
ToolTip="Save current process settings as an association. These settings will be automatically applied when this process starts in the future."/>
IsEnabled="{Binding SelectedProcess, Converter={StaticResource NullToBoolConverter}}"
ToolTip="Save current process settings as a rule. These settings will be automatically applied when this process starts in the future."/>
</Grid>
<Border Grid.Row="2"
Margin="0,10,0,0"
Padding="10,7"
CornerRadius="6"
BorderThickness="1"
Visibility="{Binding StatusMessage, Converter={x:Static converters:StringToVisibilityConverter.Instance}}">
<Border.Style>
<Style TargetType="Border">
<Setter Property="Background" Value="{DynamicResource SuccessBackgroundBrush}"/>
<Setter Property="BorderBrush" Value="{DynamicResource SuccessBorderBrush}"/>
<Style.Triggers>
<DataTrigger Binding="{Binding HasError}" Value="True">
<Setter Property="Background" Value="{DynamicResource ErrorBackgroundBrush}"/>
<Setter Property="BorderBrush" Value="{DynamicResource ErrorBorderBrush}"/>
</DataTrigger>
</Style.Triggers>
</Style>
</Border.Style>
<TextBlock Text="{Binding StatusMessage}">
<TextBlock.Style>
<Style TargetType="TextBlock">
<Setter Property="Foreground" Value="{DynamicResource SuccessTextBrush}"/>
<Style.Triggers>
<DataTrigger Binding="{Binding HasError}" Value="True">
<Setter Property="Foreground" Value="{DynamicResource ErrorTextBrush}"/>
</DataTrigger>
</Style.Triggers>
</Style>
</TextBlock.Style>
</TextBlock>
</Border>
</Grid>
</GroupBox>
</Grid>
</Grid>
</UserControl>
</UserControl>
+62 -38
View File
@@ -4,6 +4,7 @@
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:ThreadPilot.Views"
xmlns:models="clr-namespace:ThreadPilot.Models"
xmlns:converters="clr-namespace:ThreadPilot.Converters"
mc:Ignorable="d"
d:DesignHeight="600" d:DesignWidth="800">
@@ -13,13 +14,13 @@
<Setter Property="FontSize" Value="16"/>
<Setter Property="FontWeight" Value="SemiBold"/>
<Setter Property="Margin" Value="0,15,0,8"/>
<Setter Property="Foreground" Value="#2E3440"/>
<Setter Property="Foreground" Value="{DynamicResource TextPrimaryBrush}"/>
<Setter Property="VerticalAlignment" Value="Center"/>
</Style>
<Style x:Key="DescriptionStyle" TargetType="TextBlock">
<Setter Property="FontSize" Value="11"/>
<Setter Property="Foreground" Value="#5E81AC"/>
<Setter Property="Foreground" Value="{DynamicResource TextSecondaryBrush}"/>
<Setter Property="Margin" Value="0,2,0,0"/>
<Setter Property="TextWrapping" Value="Wrap"/>
</Style>
@@ -36,7 +37,7 @@
<GroupBox Grid.Row="0" Header="⚙️ Application Settings" Margin="0,0,0,10">
<Grid Margin="5">
<TextBlock Text="Configure notifications, system tray, and application behavior"
FontSize="12" Foreground="Gray" VerticalAlignment="Center"/>
FontSize="12" Foreground="{DynamicResource TextSecondaryBrush}" VerticalAlignment="Center"/>
</Grid>
</GroupBox>
@@ -46,11 +47,23 @@
<!-- Notifications Section -->
<TextBlock Text="Notifications" Style="{StaticResource SectionHeaderStyle}"/>
<Border Background="#F8F9FA" CornerRadius="5" Padding="15" Margin="0,5,0,15">
<Border Background="{DynamicResource SurfaceAltBrush}" CornerRadius="5" Padding="15" Margin="0,5,0,15">
<StackPanel>
<CheckBox Content="Enable notifications"
IsChecked="{Binding Settings.EnableNotifications}"
Margin="0,0,0,10"/>
<StackPanel Margin="20,0,0,10"
IsEnabled="{Binding Settings.EnableNotifications}">
<TextBlock Text="Notification Level" FontWeight="SemiBold" Margin="0,0,0,4"/>
<ComboBox SelectedValue="{Binding Settings.NotificationLevel}"
SelectedValuePath="Tag"
Width="240">
<ComboBoxItem Content="All" Tag="{x:Static models:NotificationLevelProfile.All}"/>
<ComboBoxItem Content="Warnings/Errors only" Tag="{x:Static models:NotificationLevelProfile.WarningsAndErrorsOnly}"/>
<ComboBoxItem Content="Silent" Tag="{x:Static models:NotificationLevelProfile.Silent}"/>
</ComboBox>
</StackPanel>
<CheckBox Content="Enable balloon notifications (system tray)"
IsChecked="{Binding Settings.EnableBalloonNotifications}"
@@ -117,7 +130,7 @@
<!-- System Tray Section -->
<TextBlock Text="System Tray" Style="{StaticResource SectionHeaderStyle}"/>
<Border Background="#F8F9FA" CornerRadius="5" Padding="15" Margin="0,5,0,15">
<Border Background="{DynamicResource SurfaceAltBrush}" CornerRadius="5" Padding="15" Margin="0,5,0,15">
<StackPanel>
<CheckBox Content="Show tray icon"
IsChecked="{Binding Settings.ShowTrayIcon}"
@@ -158,7 +171,7 @@
<!-- Autostart Section -->
<TextBlock Text="Autostart" Style="{StaticResource SectionHeaderStyle}"/>
<Border Background="#F8F9FA" CornerRadius="5" Padding="15" Margin="0,5,0,15">
<Border Background="{DynamicResource SurfaceAltBrush}" CornerRadius="5" Padding="15" Margin="0,5,0,15">
<StackPanel>
<CheckBox Content="Start with Windows"
IsChecked="{Binding Settings.AutostartWithWindows}"
@@ -169,38 +182,22 @@
</StackPanel>
</Border>
<!-- Power Plan Settings Section -->
<TextBlock Text="Power Plan Settings" Style="{StaticResource SectionHeaderStyle}"/>
<Border Background="#F8F9FA" CornerRadius="5" Padding="15" Margin="0,5,0,15">
<!-- Appearance Section -->
<TextBlock Text="Appearance" Style="{StaticResource SectionHeaderStyle}"/>
<Border Background="{DynamicResource SurfaceAltBrush}" CornerRadius="5" Padding="15" Margin="0,5,0,15">
<StackPanel>
<Grid Margin="0,0,0,10">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<TextBlock Text="Default power plan:" VerticalAlignment="Center"/>
<ComboBox Grid.Column="1"
ItemsSource="{Binding AvailablePowerPlans}"
SelectedValue="{Binding Settings.DefaultPowerPlanId}"
SelectedValuePath="Id"
DisplayMemberPath="Name"
Margin="10,0"/>
<Button Grid.Column="2" Content="Refresh"
Command="{Binding RefreshPowerPlansCommand}"
Padding="10,5" Margin="5,0,0,0"/>
</Grid>
<CheckBox Content="Restore default power plan on exit"
IsChecked="{Binding Settings.RestoreDefaultPowerPlanOnExit}"
<CheckBox Content="Use dark theme"
IsChecked="{Binding Settings.UseDarkTheme}"
Margin="0,0,0,10"/>
<TextBlock Text="Applies a global Dark/Light theme across all tabs"
Style="{StaticResource DescriptionStyle}"
Margin="20,0,0,10"/>
</StackPanel>
</Border>
<!-- Monitoring Settings Section -->
<TextBlock Text="Monitoring Settings" Style="{StaticResource SectionHeaderStyle}"/>
<Border Background="#F8F9FA" CornerRadius="5" Padding="15" Margin="0,5,0,15">
<Border Background="{DynamicResource SurfaceAltBrush}" CornerRadius="5" Padding="15" Margin="0,5,0,15">
<StackPanel>
<CheckBox Content="Enable WMI monitoring"
IsChecked="{Binding Settings.EnableWmiMonitoring}"
@@ -258,7 +255,7 @@
<!-- Advanced Section -->
<TextBlock Text="Advanced" Style="{StaticResource SectionHeaderStyle}"/>
<Border Background="#F8F9FA" CornerRadius="5" Padding="15" Margin="0,5,0,15">
<Border Background="{DynamicResource SurfaceAltBrush}" CornerRadius="5" Padding="15" Margin="0,5,0,15">
<StackPanel>
<CheckBox Content="Enable notification history"
IsChecked="{Binding Settings.EnableNotificationHistory}"
@@ -303,7 +300,7 @@
<!-- About Section -->
<TextBlock Text="About" Style="{StaticResource SectionHeaderStyle}"/>
<Border Background="#F8F9FA" CornerRadius="5" Padding="15" Margin="0,5,0,15">
<Border Background="{DynamicResource SurfaceAltBrush}" CornerRadius="5" Padding="15" Margin="0,5,0,15">
<StackPanel>
<TextBlock Text="ThreadPilot" FontWeight="SemiBold" FontSize="14"/>
<TextBlock Text="Version:" FontWeight="SemiBold" Margin="0,8,0,0"/>
@@ -335,11 +332,37 @@
</Grid.RowDefinitions>
<!-- Status -->
<TextBlock Grid.Row="0"
Text="{Binding StatusMessage}"
Foreground="#5E81AC"
Margin="0,0,0,10"
Visibility="{Binding StatusMessage, Converter={x:Static converters:StringToVisibilityConverter.Instance}}"/>
<Border Grid.Row="0"
Margin="0,0,0,10"
Padding="10,7"
CornerRadius="6"
BorderThickness="1"
Visibility="{Binding StatusMessage, Converter={x:Static converters:StringToVisibilityConverter.Instance}}">
<Border.Style>
<Style TargetType="Border">
<Setter Property="Background" Value="{DynamicResource SuccessBackgroundBrush}"/>
<Setter Property="BorderBrush" Value="{DynamicResource SuccessBorderBrush}"/>
<Style.Triggers>
<DataTrigger Binding="{Binding HasError}" Value="True">
<Setter Property="Background" Value="{DynamicResource ErrorBackgroundBrush}"/>
<Setter Property="BorderBrush" Value="{DynamicResource ErrorBorderBrush}"/>
</DataTrigger>
</Style.Triggers>
</Style>
</Border.Style>
<TextBlock Text="{Binding StatusMessage}">
<TextBlock.Style>
<Style TargetType="TextBlock">
<Setter Property="Foreground" Value="{DynamicResource SuccessTextBrush}"/>
<Style.Triggers>
<DataTrigger Binding="{Binding HasError}" Value="True">
<Setter Property="Foreground" Value="{DynamicResource ErrorTextBrush}"/>
</DataTrigger>
</Style.Triggers>
</Style>
</TextBlock.Style>
</TextBlock>
</Border>
<!-- Buttons -->
<StackPanel Grid.Row="1" Orientation="Horizontal" HorizontalAlignment="Right">
@@ -360,6 +383,7 @@
<Button Content="Save Settings"
Command="{Binding SaveSettingsCommand}"
IsEnabled="{Binding CanSaveSettings}"
Padding="20,8"/>
</StackPanel>
</Grid>
+1 -1
View File
@@ -14,7 +14,7 @@
<Window.Resources>
<Style TargetType="Window">
<Setter Property="Background" Value="#FFFFFF"/>
<Setter Property="Background" Value="{DynamicResource AppBackgroundBrush}"/>
</Style>
</Window.Resources>
+28 -28
View File
@@ -13,8 +13,8 @@
<Setter.Value>
<ControlTemplate TargetType="ToggleButton">
<Border x:Name="Border"
Background="LightGray"
BorderBrush="Gray"
Background="{DynamicResource SurfaceAltBrush}"
BorderBrush="{DynamicResource BorderBrush}"
BorderThickness="1"
CornerRadius="10"
Height="20"
@@ -23,7 +23,7 @@
<Ellipse x:Name="Thumb"
Width="16"
Height="16"
Fill="White"
Fill="{DynamicResource SurfaceBrush}"
HorizontalAlignment="Left"
Margin="2,0,0,0"
RenderTransformOrigin="0.5,0.5">
@@ -35,8 +35,8 @@
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsChecked" Value="True">
<Setter TargetName="Border" Property="Background" Value="#0078D4"/>
<Setter TargetName="Thumb" Property="Fill" Value="White"/>
<Setter TargetName="Border" Property="Background" Value="{DynamicResource AccentBrush}"/>
<Setter TargetName="Thumb" Property="Fill" Value="{DynamicResource SurfaceBrush}"/>
<Trigger.EnterActions>
<BeginStoryboard>
<Storyboard>
@@ -59,13 +59,13 @@
</Trigger.ExitActions>
</Trigger>
<Trigger Property="IsEnabled" Value="False">
<Setter TargetName="Border" Property="Background" Value="#E0E0E0"/>
<Setter TargetName="Border" Property="BorderBrush" Value="#C0C0C0"/>
<Setter TargetName="Thumb" Property="Fill" Value="#A0A0A0"/>
<Setter TargetName="Border" Property="Background" Value="{DynamicResource SurfaceAltBrush}"/>
<Setter TargetName="Border" Property="BorderBrush" Value="{DynamicResource BorderBrush}"/>
<Setter TargetName="Thumb" Property="Fill" Value="{DynamicResource TextSecondaryBrush}"/>
<Setter TargetName="Border" Property="Opacity" Value="0.6"/>
</Trigger>
<Trigger Property="IsMouseOver" Value="True">
<Setter TargetName="Border" Property="BorderBrush" Value="#0078D4"/>
<Setter TargetName="Border" Property="BorderBrush" Value="{DynamicResource AccentBrush}"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
@@ -98,7 +98,7 @@
<TextBlock Grid.Column="0"
Text="Configure Windows system optimizations and performance tweaks"
FontSize="12"
Foreground="Gray"
Foreground="{DynamicResource TextSecondaryBrush}"
VerticalAlignment="Center"/>
<Button Grid.Column="1"
@@ -153,10 +153,10 @@
<GroupBox Margin="5" Padding="10">
<GroupBox.Header>
<!-- Enhanced Tweak Name Styling -->
<TextBlock Text="{Binding Name}"
FontSize="15"
FontWeight="Bold"
Foreground="#2E3440"/>
<TextBlock Text="{Binding Name}"
FontSize="15"
FontWeight="Bold"
Foreground="{DynamicResource TextPrimaryBrush}"/>
</GroupBox.Header>
<!-- Main Card Content with Two-Column Layout -->
@@ -169,11 +169,11 @@
<!-- Left Column: Content -->
<StackPanel Grid.Column="0" Margin="0,0,15,0">
<!-- Description -->
<TextBlock Text="{Binding Description}"
FontSize="11"
Foreground="Gray"
TextWrapping="Wrap"
Margin="0,0,0,8"/>
<TextBlock Text="{Binding Description}"
FontSize="11"
Foreground="{DynamicResource TextSecondaryBrush}"
TextWrapping="Wrap"
Margin="0,0,0,8"/>
<!-- Status Indicator -->
<StackPanel Orientation="Horizontal" Margin="0,0,0,5">
@@ -182,13 +182,13 @@
Margin="0,0,8,0">
<Ellipse.Style>
<Style TargetType="Ellipse">
<Setter Property="Fill" Value="Green"/>
<Setter Property="Fill" Value="{DynamicResource SuccessTextBrush}"/>
<Style.Triggers>
<DataTrigger Binding="{Binding IsAvailable}" Value="False">
<Setter Property="Fill" Value="Red"/>
<Setter Property="Fill" Value="{DynamicResource ErrorTextBrush}"/>
</DataTrigger>
<DataTrigger Binding="{Binding IsEnabled}" Value="False">
<Setter Property="Fill" Value="Gray"/>
<Setter Property="Fill" Value="{DynamicResource TextSecondaryBrush}"/>
</DataTrigger>
</Style.Triggers>
</Style>
@@ -196,7 +196,7 @@
</Ellipse>
<TextBlock FontSize="11"
Foreground="Gray"
Foreground="{DynamicResource TextSecondaryBrush}"
VerticalAlignment="Center">
<TextBlock.Style>
<Style TargetType="TextBlock">
@@ -215,11 +215,11 @@
</StackPanel>
<!-- Error Message -->
<TextBlock Text="{Binding ErrorMessage}"
FontSize="11"
Foreground="Red"
TextWrapping="Wrap"
Visibility="{Binding ErrorMessage, Converter={StaticResource StringToVisibilityConverter}}"/>
<TextBlock Text="{Binding ErrorMessage}"
FontSize="11"
Foreground="{DynamicResource ErrorTextBrush}"
TextWrapping="Wrap"
Visibility="{Binding ErrorMessage, Converter={StaticResource StringToVisibilityConverter}}"/>
</StackPanel>
<!-- Right Column: Toggle Button -->
+112
View File
@@ -0,0 +1,112 @@
param(
[string]$Version = "1.0.0",
[string]$Configuration = "Release",
[string]$Runtime = "win-x64"
)
$ErrorActionPreference = "Stop"
function Remove-IfExists {
param([string]$Path)
if (Test-Path -LiteralPath $Path) {
Remove-Item -LiteralPath $Path -Recurse -Force
}
}
$projectRoot = Split-Path -Parent $PSCommandPath
Set-Location -LiteralPath $projectRoot
$outputRoot = Join-Path $projectRoot ("Installer\Output\v" + $Version)
$publishDir = Join-Path $outputRoot "publish"
$portableStage = Join-Path $outputRoot "portable_stage"
$setupStage = Join-Path $outputRoot "setup_stage"
$portableZip = Join-Path $outputRoot ("ThreadPilot_v" + $Version + "_Portable.zip")
$setupZip = Join-Path $outputRoot ("ThreadPilot_v" + $Version + "_Setup.zip")
$uninstallerPath = Join-Path $outputRoot "uninstaller.bat"
Write-Host "Preparing output directories..."
Remove-IfExists -Path $outputRoot
New-Item -ItemType Directory -Path $publishDir -Force | Out-Null
Write-Host "Publishing ThreadPilot $Version ($Configuration, $Runtime)..."
dotnet publish "ThreadPilot.csproj" `
--configuration $Configuration `
--runtime $Runtime `
--self-contained true `
/p:PublishSingleFile=true `
/p:EnableCompressionInSingleFile=true `
/p:DebugType=None `
/p:DebugSymbols=false `
/p:PublishTrimmed=false `
-o $publishDir
Write-Host "Creating uninstaller script..."
$uninstallerContent = @'
@echo off
setlocal EnableExtensions
title ThreadPilot Uninstaller
set "APP_DIR=%~dp0"
if "%APP_DIR:~-1%"=="\" set "APP_DIR=%APP_DIR:~0,-1%"
echo ======================================================
echo ThreadPilot v1.0.0 Uninstaller
echo ======================================================
echo.
echo App directory: "%APP_DIR%"
echo.
echo [1/4] Closing running ThreadPilot processes...
taskkill /IM "ThreadPilot.exe" /F >nul 2>&1
echo [2/4] Removing startup task and startup registry entry...
schtasks /Delete /TN "ThreadPilot_Startup" /F >nul 2>&1
reg delete "HKCU\Software\Microsoft\Windows\CurrentVersion\Run" /v "ThreadPilot" /f >nul 2>&1
echo [3/4] Optional user data cleanup...
set "REMOVE_DATA=N"
set /p REMOVE_DATA=Do you want to remove user settings at "%APPDATA%\ThreadPilot"? [y/N]:
if /I "%REMOVE_DATA%"=="Y" (
if exist "%APPDATA%\ThreadPilot" (
rd /s /q "%APPDATA%\ThreadPilot"
echo User settings removed.
) else (
echo No user settings folder found.
)
) else (
echo User settings were kept.
)
echo [4/4] Scheduling app folder removal...
start "" /min cmd /c "timeout /t 5 /nobreak >nul & rd /s /q \"%APP_DIR%\""
echo.
echo Uninstall completed. Remaining files will be removed in a few seconds.
endlocal
exit /b 0
'@
Set-Content -LiteralPath $uninstallerPath -Value $uninstallerContent -Encoding Ascii
Write-Host "Packaging portable archive..."
New-Item -ItemType Directory -Path $portableStage -Force | Out-Null
Copy-Item -Path (Join-Path $publishDir "*") -Destination $portableStage -Recurse -Force
Remove-IfExists -Path $portableZip
Compress-Archive -Path (Join-Path $portableStage "*") -DestinationPath $portableZip -CompressionLevel Optimal
Write-Host "Packaging setup archive..."
New-Item -ItemType Directory -Path $setupStage -Force | Out-Null
Copy-Item -Path (Join-Path $publishDir "*") -Destination $setupStage -Recurse -Force
Copy-Item -LiteralPath $uninstallerPath -Destination (Join-Path $setupStage "uninstaller.bat") -Force
Remove-IfExists -Path $setupZip
Compress-Archive -Path (Join-Path $setupStage "*") -DestinationPath $setupZip -CompressionLevel Optimal
Write-Host "Cleaning staging folders..."
Remove-IfExists -Path $portableStage
Remove-IfExists -Path $setupStage
Write-Host "Release packaging complete." -ForegroundColor Green
Write-Host "Portable: $portableZip"
Write-Host "Setup: $setupZip"
Write-Host "Uninstaller script source: $uninstallerPath"