Fix startup binding and prepare v1.2.0 pre-release (#22)
* Fix startup binding and prep v1.2.0 * Polish v1.2.0 validation UX * Fix final v1.2.0 validation polish * Make Activity Logs a ThreadPilot audit trail * Fix high scheduling registry value * Polish process list and automation settings UX * Fix process context menu separator styling * Theme process context menu visuals * Stabilize process context menu styling * Remove process menu icon gutter * Polish startup and idle process refresh * Finalize PR22 release polish
This commit is contained in:
+41
-3
@@ -23,26 +23,37 @@ uninstall.bat
|
||||
# Keep release documentation tracked
|
||||
!docs/release/
|
||||
!docs/release/*.md
|
||||
!docs/releases/
|
||||
!docs/releases/*.md
|
||||
|
||||
# Local worktrees and planning docs
|
||||
.worktrees/
|
||||
docs/superpowers/plans/
|
||||
/FINAL_RELEASE_PLAN*.md
|
||||
/RELEASE_PLAN*.md
|
||||
/LOCAL_VALIDATION*.md
|
||||
/VALIDATION_NOTES*.md
|
||||
/PR*_VALIDATION*.md
|
||||
/CHOCOLATEY_MODERATOR_NOTICE*.md
|
||||
|
||||
# Test and coverage
|
||||
[Tt]est[Rr]esult*/
|
||||
**/[Tt]est[Rr]esult*/
|
||||
[Bb]uild[Ll]og.*
|
||||
*.VisualState.xml
|
||||
TestResult.xml
|
||||
nunit-*.xml
|
||||
coverage/
|
||||
coverage-report/
|
||||
coverage-results/
|
||||
lcov-report/
|
||||
coverage*.json
|
||||
coverage*.xml
|
||||
coverage*.info
|
||||
lcov.info
|
||||
*.coverage
|
||||
*.coveragexml
|
||||
*.trx
|
||||
FINAL_RELEASE_PLAN.md
|
||||
RELEASE_PLAN.md
|
||||
CHOCOLATEY_MODERATOR_NOTICE.md
|
||||
|
||||
# .NET / NuGet
|
||||
*.deps.json
|
||||
@@ -92,17 +103,37 @@ $RECYCLE.BIN/
|
||||
*.log
|
||||
logs/
|
||||
Logs/
|
||||
*.pid
|
||||
*.trace
|
||||
*.stackdump
|
||||
.DS_Store
|
||||
.fuse_hidden*
|
||||
.directory
|
||||
.Trash-*
|
||||
/screenshots/
|
||||
/validation-screenshots/
|
||||
/threadpilot-menu-validation/
|
||||
*-screenshot.png
|
||||
*-screenshot.jpg
|
||||
*-validation.png
|
||||
|
||||
# Installer / packaging artifacts
|
||||
Installer/Output/
|
||||
/release/
|
||||
/release-build/
|
||||
/package-stage/
|
||||
/_stage*/
|
||||
*.cab
|
||||
*.msi
|
||||
*.msm
|
||||
*.msp
|
||||
*.msix
|
||||
*.msixbundle
|
||||
*.appinstaller
|
||||
*.blockmap
|
||||
*.sha256
|
||||
*.sha512
|
||||
ThreadPilot-*.zip
|
||||
*.lnk
|
||||
*.exe.config
|
||||
*.[Pp]ublish.xml
|
||||
@@ -131,7 +162,14 @@ Configuration/ProcessProfiles.json
|
||||
Configuration/*.local.json
|
||||
Data/
|
||||
AppData/
|
||||
appdata/
|
||||
%AppData%/ThreadPilot/
|
||||
/settings.json
|
||||
/core_masks.json
|
||||
/persistent_rules.json
|
||||
/Configuration/
|
||||
/Profiles/
|
||||
/PowerPlans/
|
||||
|
||||
# Project-specific extras
|
||||
.claude/
|
||||
|
||||
+27
-11
@@ -71,6 +71,8 @@ namespace ThreadPilot
|
||||
#if DEBUG
|
||||
bool isTestMode = false;
|
||||
#endif
|
||||
bool effectiveStartMinimized = false;
|
||||
ApplicationSettingsModel? loadedSettings = null;
|
||||
|
||||
foreach (var arg in e.Args)
|
||||
{
|
||||
@@ -103,6 +105,8 @@ namespace ThreadPilot
|
||||
}
|
||||
}
|
||||
|
||||
effectiveStartMinimized = startMinimized;
|
||||
|
||||
// Set up global exception handlers first
|
||||
AppDomain.CurrentDomain.UnhandledException += this.OnUnhandledException;
|
||||
this.DispatcherUnhandledException += this.OnDispatcherUnhandledException;
|
||||
@@ -219,6 +223,8 @@ namespace ThreadPilot
|
||||
|
||||
Task.Run(async () => await settingsService.LoadSettingsAsync()).GetAwaiter().GetResult();
|
||||
var settings = settingsService.Settings;
|
||||
loadedSettings = settings;
|
||||
effectiveStartMinimized = startMinimized || settings.StartMinimized;
|
||||
var useDarkTheme = settings.HasUserThemePreference
|
||||
? settings.UseDarkTheme
|
||||
: themeService.GetSystemUsesDarkTheme();
|
||||
@@ -237,6 +243,7 @@ namespace ThreadPilot
|
||||
}
|
||||
|
||||
var mainWindow = this.ServiceProvider.GetRequiredService<MainWindow>();
|
||||
this.MainWindow = mainWindow;
|
||||
|
||||
// Handle startup behavior with comprehensive error handling
|
||||
try
|
||||
@@ -249,23 +256,33 @@ namespace ThreadPilot
|
||||
throw new InvalidOperationException("MainWindow could not be created");
|
||||
}
|
||||
|
||||
var startupWindowBehavior = StartupWindowBehavior.Resolve(isAutostart, startMinimized);
|
||||
var startupWindowBehavior = StartupWindowBehavior.Resolve(isAutostart, effectiveStartMinimized);
|
||||
var showStartupSuggestion = loadedSettings != null
|
||||
&& StartupMinimizedSuggestionPolicy.ShouldShow(loadedSettings, startupWindowBehavior);
|
||||
mainWindow.ConfigureStartupMode(
|
||||
isSilentStartupMode: !startupWindowBehavior.ShouldShowWindow,
|
||||
showStartupMinimizedSuggestionOnReady: showStartupSuggestion);
|
||||
|
||||
mainWindow.ShowInTaskbar = startupWindowBehavior.ShowInTaskbar;
|
||||
mainWindow.Visibility = startupWindowBehavior.Visibility;
|
||||
mainWindow.WindowState = startupWindowBehavior.WindowState;
|
||||
mainWindow.Show();
|
||||
|
||||
if (startupWindowBehavior.HideAfterShow)
|
||||
if (startupWindowBehavior.ShouldShowWindow)
|
||||
{
|
||||
mainWindow.Hide();
|
||||
}
|
||||
else if (startupWindowBehavior.ActivateAfterShow)
|
||||
{
|
||||
mainWindow.EnsureDashboardVisibleOnScreen();
|
||||
mainWindow.Activate();
|
||||
mainWindow.Show();
|
||||
|
||||
if (startupWindowBehavior.HideAfterShow)
|
||||
{
|
||||
mainWindow.Hide();
|
||||
}
|
||||
else if (startupWindowBehavior.ActivateAfterShow)
|
||||
{
|
||||
mainWindow.EnsureDashboardVisibleOnScreen();
|
||||
mainWindow.Activate();
|
||||
}
|
||||
}
|
||||
|
||||
logger.LogInformation("Main window displayed successfully");
|
||||
logger.LogInformation("Startup window behavior applied successfully");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
@@ -450,4 +467,3 @@ namespace ThreadPilot
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
namespace ThreadPilot.Helpers
|
||||
{
|
||||
using System;
|
||||
using ThreadPilot.Models;
|
||||
|
||||
public static class StartupMinimizedSuggestionPolicy
|
||||
{
|
||||
public static bool ShouldShow(ApplicationSettingsModel settings, StartupWindowBehavior behavior)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(settings);
|
||||
|
||||
return behavior.ShouldShowWindow
|
||||
&& !settings.StartMinimized
|
||||
&& !settings.HasSeenStartupMinimizedSuggestion;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,7 @@ namespace ThreadPilot.Helpers
|
||||
using System.Windows;
|
||||
|
||||
public readonly record struct StartupWindowBehavior(
|
||||
bool ShouldShowWindow,
|
||||
bool ShowInTaskbar,
|
||||
Visibility Visibility,
|
||||
WindowState WindowState,
|
||||
@@ -14,24 +15,27 @@ namespace ThreadPilot.Helpers
|
||||
if (isAutostart && startMinimized)
|
||||
{
|
||||
return new StartupWindowBehavior(
|
||||
ShouldShowWindow: false,
|
||||
ShowInTaskbar: false,
|
||||
Visibility: Visibility.Hidden,
|
||||
WindowState: WindowState.Minimized,
|
||||
HideAfterShow: true,
|
||||
HideAfterShow: false,
|
||||
ActivateAfterShow: false);
|
||||
}
|
||||
|
||||
if (startMinimized)
|
||||
{
|
||||
return new StartupWindowBehavior(
|
||||
ShowInTaskbar: true,
|
||||
Visibility: Visibility.Visible,
|
||||
ShouldShowWindow: false,
|
||||
ShowInTaskbar: false,
|
||||
Visibility: Visibility.Hidden,
|
||||
WindowState: WindowState.Minimized,
|
||||
HideAfterShow: false,
|
||||
ActivateAfterShow: false);
|
||||
}
|
||||
|
||||
return new StartupWindowBehavior(
|
||||
ShouldShowWindow: true,
|
||||
ShowInTaskbar: true,
|
||||
Visibility: Visibility.Visible,
|
||||
WindowState: WindowState.Normal,
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
#define MyAppPublisher "ThreadPilot"
|
||||
#define MyAppURL "https://github.com/"
|
||||
#define MyAppExeName "ThreadPilot.exe"
|
||||
#define MyAppVersion "0.1.0-beta"
|
||||
#define MyAppVersion "1.2.0"
|
||||
|
||||
#ifndef MyWizardStyle
|
||||
#define MyWizardStyle "modern dynamic windows11"
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
<Package
|
||||
Name="ThreadPilot"
|
||||
Manufacturer="Prime Build"
|
||||
Version="1.1.1.0"
|
||||
Version="1.2.0.0"
|
||||
UpgradeCode="PUT-GENERATED-UPGRADE-CODE-HERE"
|
||||
Language="1033">
|
||||
<SummaryInformation Description="ThreadPilot MSI template" />
|
||||
|
||||
+1
-1
@@ -11,7 +11,7 @@
|
||||
#endif
|
||||
|
||||
#ifndef MyAppVersion
|
||||
#define MyAppVersion "1.1.3"
|
||||
#define MyAppVersion "1.2.0"
|
||||
#endif
|
||||
|
||||
#ifndef MyAppSourceDir
|
||||
|
||||
@@ -68,16 +68,21 @@ namespace ThreadPilot
|
||||
// Ensure overlay is visible while initialization runs
|
||||
if (loadingOverlay != null)
|
||||
{
|
||||
loadingOverlay.Visibility = Visibility.Visible;
|
||||
loadingOverlay.Opacity = 1;
|
||||
loadingOverlay.Visibility = this.isSilentStartupMode ? Visibility.Collapsed : Visibility.Visible;
|
||||
loadingOverlay.Opacity = this.isSilentStartupMode ? 0 : 1;
|
||||
}
|
||||
|
||||
// Enable blur on main app content during startup loading.
|
||||
this.ApplyUIContentBlur(15);
|
||||
if (!this.isSilentStartupMode)
|
||||
{
|
||||
this.ApplyUIContentBlur(15);
|
||||
}
|
||||
|
||||
// Start spinner animation if available
|
||||
var spinnerAnimation = this.FindResource("SpinnerAnimation") as Storyboard;
|
||||
spinnerAnimation?.Begin();
|
||||
if (!this.isSilentStartupMode)
|
||||
{
|
||||
spinnerAnimation?.Begin();
|
||||
}
|
||||
|
||||
// Set a timeout guard for initialization
|
||||
this.initializationTimeoutTimer = new System.Timers.Timer(15000)
|
||||
@@ -115,6 +120,7 @@ namespace ThreadPilot
|
||||
await this.InitializeServicesAsync();
|
||||
this.LogDebug("InitializeServicesAsync completed successfully");
|
||||
this.CompleteInitializationTask("Services");
|
||||
this.QueueStartupUpdateCheck();
|
||||
|
||||
await this.Dispatcher.InvokeAsync(() => this.UpdateLoadingStatus("Finalizing startup...", "Applying final UI state and startup checks."));
|
||||
this.LogDebug("Finalizing startup...");
|
||||
@@ -133,6 +139,75 @@ namespace ThreadPilot
|
||||
}
|
||||
}
|
||||
|
||||
private void QueueStartupUpdateCheck()
|
||||
{
|
||||
if (Interlocked.Exchange(ref this.startupUpdateCheckStarted, 1) != 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
TaskSafety.FireAndForget(this.CheckForUpdatesAtStartupAsync(), ex =>
|
||||
{
|
||||
this.LogDebug($"Startup update check failed: {ex.Message}");
|
||||
});
|
||||
}
|
||||
|
||||
private async Task CheckForUpdatesAtStartupAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
this.LogDebug("Startup update check started");
|
||||
var checker = this.serviceProvider.GetRequiredService<GitHubUpdateChecker>();
|
||||
var currentVersion = GetCurrentApplicationVersion();
|
||||
var (latest, _) = await checker.GetLatestVersionAsync("PrimeBuild-pc", "ThreadPilot");
|
||||
|
||||
if (latest == null)
|
||||
{
|
||||
this.LogDebug("Startup update check completed without release information");
|
||||
return;
|
||||
}
|
||||
|
||||
if (latest <= currentVersion)
|
||||
{
|
||||
this.LogDebug($"Startup update check complete: installed {currentVersion}, latest {latest}");
|
||||
return;
|
||||
}
|
||||
|
||||
await this.notificationService.ShowNotificationAsync(
|
||||
"Update available",
|
||||
$"ThreadPilot {latest} is available from GitHub releases.",
|
||||
NotificationType.Information);
|
||||
this.LogDebug($"Startup update check found update: installed {currentVersion}, latest {latest}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
this.LogDebug($"Startup update check ignored failure: {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
private static Version GetCurrentApplicationVersion()
|
||||
{
|
||||
var rawVersion = typeof(App).Assembly
|
||||
.GetCustomAttributes(typeof(System.Reflection.AssemblyInformationalVersionAttribute), false)
|
||||
.OfType<System.Reflection.AssemblyInformationalVersionAttribute>()
|
||||
.FirstOrDefault()?
|
||||
.InformationalVersion
|
||||
?? typeof(App).Assembly.GetName().Version?.ToString()
|
||||
?? "0.0.0";
|
||||
|
||||
var sanitized = rawVersion.Trim();
|
||||
if (sanitized.StartsWith("v", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
sanitized = sanitized[1..];
|
||||
}
|
||||
|
||||
sanitized = sanitized.Split('-', '+')[0];
|
||||
|
||||
return Version.TryParse(sanitized, out var version)
|
||||
? version
|
||||
: new Version(0, 0, 0);
|
||||
}
|
||||
|
||||
private void UpdateLoadingStatus(string stage, string details = "")
|
||||
{
|
||||
if (this.mainWindowViewModel != null)
|
||||
@@ -160,6 +235,20 @@ namespace ThreadPilot
|
||||
this.initializationTimeoutTimer?.Stop();
|
||||
this.initializationTimeoutTimer?.Dispose();
|
||||
|
||||
if (this.isSilentStartupMode)
|
||||
{
|
||||
var silentLoadingOverlay = this.FindName("LoadingOverlay") as Grid;
|
||||
if (silentLoadingOverlay != null)
|
||||
{
|
||||
silentLoadingOverlay.Visibility = Visibility.Collapsed;
|
||||
silentLoadingOverlay.Opacity = 0;
|
||||
}
|
||||
|
||||
this.ClearUIContentBlur();
|
||||
this.ApplyAppRefreshPolicy(AppActivityState.TrayHidden);
|
||||
return;
|
||||
}
|
||||
|
||||
// Stop spinner animation
|
||||
var spinnerAnimation = this.FindResource("SpinnerAnimation") as Storyboard;
|
||||
spinnerAnimation?.Stop();
|
||||
@@ -186,6 +275,7 @@ namespace ThreadPilot
|
||||
|
||||
// Show elevation warning if needed
|
||||
this.TryShowElevationWarning();
|
||||
this.TryShowStartupMinimizedSuggestion();
|
||||
};
|
||||
fadeOutAnimation.Begin();
|
||||
}
|
||||
@@ -204,6 +294,7 @@ namespace ThreadPilot
|
||||
|
||||
// Show elevation warning if needed
|
||||
this.TryShowElevationWarning();
|
||||
this.TryShowStartupMinimizedSuggestion();
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
@@ -223,6 +314,7 @@ namespace ThreadPilot
|
||||
|
||||
// Show elevation warning if needed
|
||||
this.TryShowElevationWarning();
|
||||
this.TryShowStartupMinimizedSuggestion();
|
||||
}
|
||||
catch (Exception fallbackEx)
|
||||
{
|
||||
@@ -1160,11 +1252,16 @@ namespace ThreadPilot
|
||||
await startTask; // Get any exceptions
|
||||
this.LogDebug("Process monitoring manager service started, showing notification...");
|
||||
|
||||
await this.notificationService.ShowSuccessNotificationAsync(
|
||||
"ThreadPilot Started",
|
||||
"Process monitoring and power plan management is now active");
|
||||
if (!this.isSilentStartupMode)
|
||||
{
|
||||
await this.notificationService.ShowSuccessNotificationAsync(
|
||||
"ThreadPilot Started",
|
||||
"Process monitoring and power plan management is now active");
|
||||
}
|
||||
|
||||
this.LogDebug("Success notification shown");
|
||||
this.LogDebug(this.isSilentStartupMode
|
||||
? "Startup success notification skipped for silent startup"
|
||||
: "Success notification shown");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
@@ -1522,6 +1619,71 @@ namespace ThreadPilot
|
||||
}
|
||||
}
|
||||
|
||||
private void TryShowStartupMinimizedSuggestion()
|
||||
{
|
||||
if (!this.showStartupMinimizedSuggestionOnReady
|
||||
|| this.isSilentStartupMode
|
||||
|| !this.isInitializationComplete
|
||||
|| this.isElevationWarningVisible)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
if (!StartupMinimizedSuggestionPolicy.ShouldShow(
|
||||
this.settingsService.Settings,
|
||||
StartupWindowBehavior.Resolve(isAutostart: false, startMinimized: false)))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
this.StartupMinimizedSuggestionOverlay.Visibility = Visibility.Visible;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
this.LogDebug($"Failed to show startup minimized suggestion: {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
private async Task PersistStartupMinimizedSuggestionSeenAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
var settings = this.settingsService.Settings;
|
||||
if (settings.HasSeenStartupMinimizedSuggestion)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
settings.HasSeenStartupMinimizedSuggestion = true;
|
||||
await this.settingsService.UpdateSettingsAsync(settings);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
this.LogDebug($"Failed to persist startup minimized suggestion state: {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
private void HideStartupMinimizedSuggestion()
|
||||
{
|
||||
this.showStartupMinimizedSuggestionOnReady = false;
|
||||
this.StartupMinimizedSuggestionOverlay.Visibility = Visibility.Collapsed;
|
||||
}
|
||||
|
||||
private async void StartupSuggestionOpenSettings_Click(object sender, RoutedEventArgs e)
|
||||
{
|
||||
await this.PersistStartupMinimizedSuggestionSeenAsync();
|
||||
this.HideStartupMinimizedSuggestion();
|
||||
this.SelectMainTab("Settings");
|
||||
}
|
||||
|
||||
private async void StartupSuggestionDontShowAgain_Click(object sender, RoutedEventArgs e)
|
||||
{
|
||||
await this.PersistStartupMinimizedSuggestionSeenAsync();
|
||||
this.HideStartupMinimizedSuggestion();
|
||||
}
|
||||
|
||||
private void HidePerformanceIntro()
|
||||
{
|
||||
this.isPerformanceIntroVisible = false;
|
||||
@@ -1661,6 +1823,8 @@ namespace ThreadPilot
|
||||
{
|
||||
elevationBlur.Radius = this.previousElevationBackdropBlurRadius;
|
||||
}
|
||||
|
||||
this.TryShowStartupMinimizedSuggestion();
|
||||
}
|
||||
|
||||
private void ElevationWarningDismiss_Click(object sender, RoutedEventArgs e)
|
||||
|
||||
+60
-2
@@ -143,7 +143,7 @@
|
||||
<ui:SymbolIcon Symbol="DataHistogram24"/>
|
||||
</ui:NavigationViewItem.Icon>
|
||||
</ui:NavigationViewItem>
|
||||
<ui:NavigationViewItem x:Name="NavLogs" Content="Activity Logs" Tag="Logs" TargetPageTag="Logs" Click="NavMenuItem_Click">
|
||||
<ui:NavigationViewItem x:Name="NavLogs" Content="ThreadPilot Activity" Tag="Logs" TargetPageTag="Logs" Click="NavMenuItem_Click">
|
||||
<ui:NavigationViewItem.Icon>
|
||||
<ui:SymbolIcon Symbol="DocumentText24"/>
|
||||
</ui:NavigationViewItem.Icon>
|
||||
@@ -282,7 +282,7 @@
|
||||
<Border Grid.Row="2" Background="{DynamicResource SolidBackgroundFillColorBaseBrush}" BorderThickness="0,1,0,0" BorderBrush="{DynamicResource BorderSubtleBrush}" Padding="12,4">
|
||||
<Border.Resources>
|
||||
<Style TargetType="TextBlock">
|
||||
<Setter Property="FontFamily" Value="Segoe UI Variable, Segoe UI"/>
|
||||
<Setter Property="FontFamily" Value="{DynamicResource AppFontFamily}"/>
|
||||
<Setter Property="FontSize" Value="12"/>
|
||||
</Style>
|
||||
</Border.Resources>
|
||||
@@ -368,6 +368,64 @@
|
||||
</Border>
|
||||
</Grid>
|
||||
|
||||
<Grid x:Name="StartupMinimizedSuggestionOverlay"
|
||||
Visibility="Collapsed"
|
||||
Panel.ZIndex="955"
|
||||
Background="{DynamicResource OverlayBrush}"
|
||||
AutomationProperties.Name="Startup minimized suggestion">
|
||||
<Border Background="{DynamicResource CardSurfaceBrush}"
|
||||
BorderBrush="{DynamicResource BorderSubtleBrush}"
|
||||
BorderThickness="1"
|
||||
CornerRadius="{DynamicResource StandardCardCornerRadius}"
|
||||
Padding="20"
|
||||
HorizontalAlignment="Center"
|
||||
VerticalAlignment="Top"
|
||||
Margin="0,56,0,0"
|
||||
MinWidth="420"
|
||||
MaxWidth="560"
|
||||
IsHitTestVisible="True">
|
||||
<Border.Effect>
|
||||
<DropShadowEffect BlurRadius="12" ShadowDepth="0" Opacity="0.16"/>
|
||||
</Border.Effect>
|
||||
<StackPanel>
|
||||
<Border Background="{DynamicResource InfoBackgroundBrush}"
|
||||
BorderBrush="{DynamicResource InfoBorderBrush}"
|
||||
BorderThickness="1"
|
||||
CornerRadius="{DynamicResource StandardCardCornerRadius}"
|
||||
Padding="8,3"
|
||||
HorizontalAlignment="Left"
|
||||
Margin="0,0,0,10">
|
||||
<TextBlock Text="Recommended"
|
||||
FontSize="{DynamicResource CaptionFontSize}"
|
||||
FontWeight="SemiBold"
|
||||
Foreground="{DynamicResource InfoTextBrush}"/>
|
||||
</Border>
|
||||
<TextBlock Text="Startup minimized"
|
||||
FontSize="20"
|
||||
FontWeight="SemiBold"
|
||||
Foreground="{DynamicResource TextFillColorPrimaryBrush}"
|
||||
Margin="0,0,0,8"/>
|
||||
<TextBlock Text="Enable Startup minimized when you want ThreadPilot to start silently in the tray on future Windows sign-ins."
|
||||
TextWrapping="Wrap"
|
||||
Foreground="{DynamicResource TextFillColorSecondaryBrush}"
|
||||
Margin="0,0,0,16"/>
|
||||
<StackPanel Orientation="Horizontal" HorizontalAlignment="Right">
|
||||
<Button Content="Don't show again"
|
||||
Click="StartupSuggestionDontShowAgain_Click"
|
||||
Background="{DynamicResource ControlFillColorDefaultBrush}"
|
||||
Foreground="{DynamicResource TextFillColorPrimaryBrush}"
|
||||
Padding="14,7"
|
||||
Margin="0,0,10,0"/>
|
||||
<Button Content="Open Settings"
|
||||
Click="StartupSuggestionOpenSettings_Click"
|
||||
Background="{DynamicResource AccentFillColorDefaultBrush}"
|
||||
Foreground="{DynamicResource TextOnAccentFillColorPrimaryBrush}"
|
||||
Padding="14,7"/>
|
||||
</StackPanel>
|
||||
</StackPanel>
|
||||
</Border>
|
||||
</Grid>
|
||||
|
||||
<Grid x:Name="UnsavedSettingsOverlay"
|
||||
Visibility="Collapsed"
|
||||
Panel.ZIndex="960"
|
||||
|
||||
@@ -64,6 +64,7 @@ namespace ThreadPilot
|
||||
private bool isSystemTrayUpdatesSuspended;
|
||||
private int isSystemTrayUpdateInProgress;
|
||||
private int systemTrayUpdateFailureStreak;
|
||||
private int startupUpdateCheckStarted;
|
||||
private AppActivityState? lastAppliedRefreshState;
|
||||
private readonly IElevationService elevationService;
|
||||
private readonly ISecurityService securityService;
|
||||
@@ -82,6 +83,8 @@ namespace ThreadPilot
|
||||
private bool isPerformanceIntroVisible = false;
|
||||
private double previousAppContentOpacity = 1;
|
||||
private TaskCompletionSource<MessageBoxResult>? unsavedSettingsDialogCompletionSource;
|
||||
private bool isSilentStartupMode;
|
||||
private bool showStartupMinimizedSuggestionOnReady;
|
||||
|
||||
public MainWindow(
|
||||
ProcessViewModel processViewModel,
|
||||
@@ -165,6 +168,32 @@ namespace ThreadPilot
|
||||
}
|
||||
}
|
||||
|
||||
public void ConfigureStartupMode(bool isSilentStartupMode, bool showStartupMinimizedSuggestionOnReady)
|
||||
{
|
||||
this.isSilentStartupMode = isSilentStartupMode;
|
||||
this.showStartupMinimizedSuggestionOnReady = showStartupMinimizedSuggestionOnReady;
|
||||
|
||||
if (!isSilentStartupMode)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
this.showStartupMinimizedSuggestionOnReady = false;
|
||||
this.LoadingOverlay.Visibility = Visibility.Collapsed;
|
||||
this.ClearUIContentBlur();
|
||||
|
||||
if (this.FindResource("SpinnerAnimation") is Storyboard spinnerAnimation)
|
||||
{
|
||||
spinnerAnimation.Stop();
|
||||
}
|
||||
|
||||
this.isSystemTrayUpdatesSuspended = true;
|
||||
this.lastAppliedRefreshState = AppActivityState.TrayHidden;
|
||||
this.processViewModel.SetProcessViewActive(false);
|
||||
this.processViewModel.ApplyRefreshDecision(AppRefreshPolicy.Evaluate(AppActivityState.TrayHidden));
|
||||
this.powerPlanViewModel.PauseAutoRefresh();
|
||||
}
|
||||
|
||||
private void ConfigureDiagnosticsNavigation()
|
||||
{
|
||||
this.NavPerf.Visibility = AppNavigationOptions.ShowAdvancedDiagnostics
|
||||
|
||||
@@ -180,6 +180,9 @@ namespace ThreadPilot.Models
|
||||
[ObservableProperty]
|
||||
private bool hasSeenElevationWarning = false;
|
||||
|
||||
[ObservableProperty]
|
||||
private bool hasSeenStartupMinimizedSuggestion = false;
|
||||
|
||||
[ObservableProperty]
|
||||
private bool enableSelfLowImpactMode = true;
|
||||
|
||||
@@ -259,6 +262,7 @@ namespace ThreadPilot.Models
|
||||
this.EnablePerformanceCounters = other.EnablePerformanceCounters;
|
||||
this.HasSeenPerformanceIntro = other.HasSeenPerformanceIntro;
|
||||
this.HasSeenElevationWarning = other.HasSeenElevationWarning;
|
||||
this.HasSeenStartupMinimizedSuggestion = other.HasSeenStartupMinimizedSuggestion;
|
||||
this.EnableSelfLowImpactMode = other.EnableSelfLowImpactMode;
|
||||
this.EnableSelfAffinityLimit = other.EnableSelfAffinityLimit;
|
||||
this.MaxLogFileSizeMb = other.MaxLogFileSizeMb;
|
||||
|
||||
@@ -2,10 +2,11 @@
|
||||
|
||||
# ThreadPilot ✈️
|
||||
|
||||
**A free and open-source Windows process and power plan manager for deterministic performance workflows.**
|
||||
**A free and open-source Windows process control center for deterministic CPU, priority, memory, and power-plan workflows.**
|
||||
|
||||
[](https://github.com/PrimeBuild-pc/ThreadPilot/actions/workflows/ci-devsecops.yml)
|
||||
[](https://github.com/PrimeBuild-pc/ThreadPilot/releases)
|
||||
[](https://github.com/PrimeBuild-pc/ThreadPilot/actions/workflows/ci-devsecops.yml)
|
||||
[](https://codecov.io/gh/PrimeBuild-pc/ThreadPilot)
|
||||
[](https://github.com/PrimeBuild-pc/ThreadPilot/releases)
|
||||
[](https://github.com/microsoft/winget-pkgs/tree/master/manifests/p/PrimeBuild/ThreadPilot)
|
||||
[](https://www.microsoft.com/windows)
|
||||
[](https://dotnet.microsoft.com/)
|
||||
@@ -21,20 +22,27 @@
|
||||
|
||||
## What is ThreadPilot?
|
||||
|
||||
ThreadPilot is a modern Windows desktop application for users who want predictable control over process behavior, CPU affinity, priority, power plans, and rule-driven performance workflows.
|
||||
|
||||
It is designed as an open-source alternative for power users who need Process Lasso-style capabilities, automation support, system tray controls, and a Windows 11-first experience.
|
||||
ThreadPilot is a modern Windows process control center for users who want predictable control over process behavior, CPU affinity, CPU Sets, priority, memory priority, power plans, and saved process rules.
|
||||
|
||||
It is designed as an open-source alternative for power users who need Process Lasso-style capabilities, automation support, system tray controls, and a Windows 11-first experience. ThreadPilot is not a performance overlay: its primary job is applying explicit process controls safely and making the result visible.
|
||||
|
||||
## ✨ Features
|
||||
|
||||
- Live process management with refresh, filtering, and high-volume process handling.
|
||||
- CPU affinity and priority controls with topology-aware logic.
|
||||
- I/O and scheduler-related tuning utilities.
|
||||
- Rule-based automation for power plan switching when selected processes start or stop.
|
||||
- Conditional profiles, tray controls, Live Metrics, and dashboard views.
|
||||
- Administrator-aware Windows desktop workflow.
|
||||
- CI-backed release artifacts and package-manager distribution.
|
||||
- Windows 11 native visual refresh with neutral Fluent surfaces and refined card-based layouts.
|
||||
- Live process management with refresh, filtering, context-menu actions, and a selected-process summary.
|
||||
- Topology-aware CPU affinity through `CpuSelection`, including CPU Sets support, processor groups, and safe handling for systems with more than 64 logical processors.
|
||||
- Safer CPU indexing in new affinity paths: CPU64 no longer aliases CPU0.
|
||||
- Intel hybrid CPU handling through Windows topology and `EfficiencyClass`, not hardcoded SKU lists.
|
||||
- AMD CCD/L3-aware preset generation, also topology-driven instead of hardcoded SKU lists.
|
||||
- Default gaming-oriented CPU presets for common foreground-game workflows.
|
||||
- CPU priority controls with guardrails: High priority warning and Realtime priority blocked.
|
||||
- Process memory priority support.
|
||||
- Persistent process rules with explicit Apply now and Save as rule flows.
|
||||
- Apply saved rules automatically when matching processes start while ThreadPilot is running.
|
||||
- Rule-based automation for power plan switching when selected processes start or stop.
|
||||
- Optional Diagnostics view, hidden by default, plus tray controls and dashboard views.
|
||||
- Administrator-aware Windows desktop workflow.
|
||||
- CI-backed build validation and package-manager distribution.
|
||||
- Windows 11 native visual refresh with neutral Fluent surfaces and refined card-based layouts.
|
||||
|
||||
## 📦 Install
|
||||
|
||||
@@ -86,9 +94,13 @@ Compare the result with `SHA256SUMS.txt` from the same release.
|
||||
|
||||
## 🚀 Usage Notes
|
||||
|
||||
ThreadPilot uses an administrator-required manifest and requests elevation at startup. If UAC elevation is declined, the application exits instead of continuing in a limited mode.
|
||||
|
||||
Useful startup arguments:
|
||||
ThreadPilot uses an administrator-required manifest and requests elevation at startup. If UAC elevation is declined, the application exits instead of continuing in a limited mode.
|
||||
|
||||
Persistent process rules are runtime-based. Apply at process start works only while ThreadPilot is running; it does not install a Windows Service, write registry or IFEO persistence, or use installer privilege tricks.
|
||||
|
||||
ThreadPilot does not bypass anti-cheat or protected-process restrictions. Running as administrator may help with normal access-denied cases, but it does not override protected-process or anti-cheat enforcement.
|
||||
|
||||
Useful startup arguments:
|
||||
|
||||
```text
|
||||
--start-minimized
|
||||
|
||||
@@ -0,0 +1,244 @@
|
||||
namespace ThreadPilot.Services
|
||||
{
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
public sealed class ActivityAuditService : IActivityAuditService
|
||||
{
|
||||
private const int MaxEntries = 1000;
|
||||
private readonly ILogger<ActivityAuditService> logger;
|
||||
private readonly object syncRoot = new();
|
||||
private readonly List<ActivityAuditEntry> entries = new();
|
||||
|
||||
public event EventHandler<ActivityAuditEntry>? EntryAdded;
|
||||
|
||||
public ActivityAuditService(ILogger<ActivityAuditService> logger)
|
||||
{
|
||||
this.logger = logger ?? throw new ArgumentNullException(nameof(logger));
|
||||
}
|
||||
|
||||
public Task LogInfoAsync(string category, string message, string? details = null) =>
|
||||
this.AddEntryAsync(category, ActivityAuditSeverity.Info, message, details);
|
||||
|
||||
public Task LogSuccessAsync(string category, string message, string? details = null) =>
|
||||
this.AddEntryAsync(category, ActivityAuditSeverity.Success, message, details);
|
||||
|
||||
public Task LogWarningAsync(string category, string message, string? details = null) =>
|
||||
this.AddEntryAsync(category, ActivityAuditSeverity.Warning, message, details);
|
||||
|
||||
public Task LogErrorAsync(string category, string message, string? details = null) =>
|
||||
this.AddEntryAsync(category, ActivityAuditSeverity.Error, message, details);
|
||||
|
||||
public Task LogUserActionAsync(string action, string details, string? context = null)
|
||||
{
|
||||
var entry = ActivityAuditActionMapper.Map(action, details, context);
|
||||
return this.AddEntryAsync(entry.Category, entry.Severity, entry.Message, entry.Details);
|
||||
}
|
||||
|
||||
public Task<IReadOnlyList<ActivityAuditEntry>> GetEntriesAsync(DateTime? fromDate = null, DateTime? toDate = null)
|
||||
{
|
||||
lock (this.syncRoot)
|
||||
{
|
||||
IEnumerable<ActivityAuditEntry> snapshot = this.entries;
|
||||
if (fromDate.HasValue)
|
||||
{
|
||||
snapshot = snapshot.Where(entry => entry.Timestamp >= fromDate.Value);
|
||||
}
|
||||
|
||||
if (toDate.HasValue)
|
||||
{
|
||||
snapshot = snapshot.Where(entry => entry.Timestamp <= toDate.Value);
|
||||
}
|
||||
|
||||
return Task.FromResult<IReadOnlyList<ActivityAuditEntry>>(
|
||||
snapshot
|
||||
.OrderByDescending(entry => entry.Timestamp)
|
||||
.ToList());
|
||||
}
|
||||
}
|
||||
|
||||
public Task ClearDisplayAsync()
|
||||
{
|
||||
lock (this.syncRoot)
|
||||
{
|
||||
this.entries.Clear();
|
||||
}
|
||||
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
private Task AddEntryAsync(string category, ActivityAuditSeverity severity, string message, string? details)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(message))
|
||||
{
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
var entry = new ActivityAuditEntry
|
||||
{
|
||||
Timestamp = DateTime.Now,
|
||||
Category = string.IsNullOrWhiteSpace(category) ? ActivityAuditCategories.Diagnostics : category.Trim(),
|
||||
Severity = severity,
|
||||
Message = message.Trim(),
|
||||
Details = string.IsNullOrWhiteSpace(details) ? null : details.Trim(),
|
||||
};
|
||||
|
||||
lock (this.syncRoot)
|
||||
{
|
||||
this.entries.Add(entry);
|
||||
if (this.entries.Count > MaxEntries)
|
||||
{
|
||||
this.entries.RemoveRange(0, this.entries.Count - MaxEntries);
|
||||
}
|
||||
}
|
||||
|
||||
this.logger.Log(
|
||||
ToLogLevel(severity),
|
||||
"Activity audit: {Category} {Severity}: {Message}",
|
||||
entry.Category,
|
||||
entry.Severity,
|
||||
entry.Message);
|
||||
this.EntryAdded?.Invoke(this, entry);
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
private static LogLevel ToLogLevel(ActivityAuditSeverity severity) =>
|
||||
severity switch
|
||||
{
|
||||
ActivityAuditSeverity.Error => LogLevel.Error,
|
||||
ActivityAuditSeverity.Warning => LogLevel.Warning,
|
||||
_ => LogLevel.Information,
|
||||
};
|
||||
}
|
||||
|
||||
internal static class ActivityAuditCategories
|
||||
{
|
||||
public const string Process = "Process";
|
||||
public const string Affinity = "Affinity";
|
||||
public const string Priority = "Priority";
|
||||
public const string MemoryPriority = "Memory Priority";
|
||||
public const string Rules = "Rules";
|
||||
public const string PowerPlans = "Power Plans";
|
||||
public const string Settings = "Settings";
|
||||
public const string Tweaks = "Tweaks";
|
||||
public const string Optimization = "Optimization";
|
||||
public const string Diagnostics = "Diagnostics";
|
||||
public const string Safety = "Safety";
|
||||
}
|
||||
|
||||
internal static class ActivityAuditActionMapper
|
||||
{
|
||||
public static ActivityAuditEntry Map(string action, string details, string? context)
|
||||
{
|
||||
var category = ResolveCategory(action);
|
||||
var severity = ResolveSeverity(action, details);
|
||||
return new ActivityAuditEntry
|
||||
{
|
||||
Category = category,
|
||||
Severity = severity,
|
||||
Message = string.IsNullOrWhiteSpace(details) ? action : details,
|
||||
Details = context,
|
||||
};
|
||||
}
|
||||
|
||||
private static string ResolveCategory(string action)
|
||||
{
|
||||
if (action.StartsWith("ProcessAffinity", StringComparison.OrdinalIgnoreCase) ||
|
||||
action.StartsWith("CpuSets", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return ActivityAuditCategories.Affinity;
|
||||
}
|
||||
|
||||
if (action.StartsWith("ProcessPriority", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return ActivityAuditCategories.Priority;
|
||||
}
|
||||
|
||||
if (action.StartsWith("ProcessMemoryPriority", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return ActivityAuditCategories.MemoryPriority;
|
||||
}
|
||||
|
||||
if (action.StartsWith("PersistentRule", StringComparison.OrdinalIgnoreCase) ||
|
||||
action.Contains("Association", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return ActivityAuditCategories.Rules;
|
||||
}
|
||||
|
||||
if (action.StartsWith("PowerPlan", StringComparison.OrdinalIgnoreCase) ||
|
||||
action.StartsWith("PowerPlans", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return ActivityAuditCategories.PowerPlans;
|
||||
}
|
||||
|
||||
if (action.StartsWith("Theme", StringComparison.OrdinalIgnoreCase) ||
|
||||
action.StartsWith("Settings", StringComparison.OrdinalIgnoreCase) ||
|
||||
action.Contains("Configuration", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return ActivityAuditCategories.Settings;
|
||||
}
|
||||
|
||||
if (action.StartsWith("SystemTweak", StringComparison.OrdinalIgnoreCase) ||
|
||||
action.Contains("IdleServer", StringComparison.OrdinalIgnoreCase) ||
|
||||
action.Contains("RegistryPriority", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return ActivityAuditCategories.Tweaks;
|
||||
}
|
||||
|
||||
if (action.StartsWith("Optimization", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return ActivityAuditCategories.Optimization;
|
||||
}
|
||||
|
||||
if (action.Contains("Protected", StringComparison.OrdinalIgnoreCase) ||
|
||||
action.Contains("Elevation", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return ActivityAuditCategories.Safety;
|
||||
}
|
||||
|
||||
if (action.StartsWith("Process", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return ActivityAuditCategories.Process;
|
||||
}
|
||||
|
||||
return ActivityAuditCategories.Diagnostics;
|
||||
}
|
||||
|
||||
private static ActivityAuditSeverity ResolveSeverity(string action, string details)
|
||||
{
|
||||
if (ContainsAny(action, "Blocked", "Denied") || ContainsAny(details, "blocked", "denied", "anti-cheat", "protected"))
|
||||
{
|
||||
return ActivityAuditSeverity.Warning;
|
||||
}
|
||||
|
||||
if (ContainsAny(action, "Failed", "Failure", "Error") || ContainsAny(details, "failed", "error", "exited"))
|
||||
{
|
||||
return ActivityAuditSeverity.Error;
|
||||
}
|
||||
|
||||
if (ContainsAny(
|
||||
action,
|
||||
"Applied",
|
||||
"Changed",
|
||||
"Saved",
|
||||
"Updated",
|
||||
"Deleted",
|
||||
"Imported",
|
||||
"Added",
|
||||
"Cleared",
|
||||
"Refreshed",
|
||||
"Started",
|
||||
"Stopped",
|
||||
"Exported",
|
||||
"Opened",
|
||||
"Copied"))
|
||||
{
|
||||
return ActivityAuditSeverity.Success;
|
||||
}
|
||||
|
||||
return ActivityAuditSeverity.Info;
|
||||
}
|
||||
|
||||
private static bool ContainsAny(string value, params string[] terms) =>
|
||||
terms.Any(term => value.Contains(term, StringComparison.OrdinalIgnoreCase));
|
||||
}
|
||||
}
|
||||
+121
-12
@@ -24,7 +24,9 @@ namespace ThreadPilot.Services
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using System.Windows;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using ThreadPilot.Models;
|
||||
|
||||
@@ -49,6 +51,7 @@ namespace ThreadPilot.Services
|
||||
private readonly CpuSelectionMigrationService cpuSelectionMigrationService;
|
||||
private readonly string masksFilePath;
|
||||
private bool initialized = false;
|
||||
private int topologyBackfillInProgress;
|
||||
|
||||
// Tracks which masks are actively applied to processes
|
||||
private readonly Dictionary<int, string> activeProcessMasks = new(); // ProcessId -> MaskId
|
||||
@@ -61,13 +64,15 @@ namespace ThreadPilot.Services
|
||||
/// The "All Cores" baseline mask - cannot be deleted.
|
||||
/// </summary>
|
||||
private const string ALLCORESMASKNAME = "All Cores";
|
||||
private const string NOCORE0MASKNAME = "No Core 0";
|
||||
|
||||
public CoreMaskService(
|
||||
ILogger<CoreMaskService> logger,
|
||||
ICpuTopologyService cpuTopologyService,
|
||||
IServiceProvider serviceProvider,
|
||||
ICpuTopologyProvider? cpuTopologyProvider = null,
|
||||
CpuSelectionMigrationService? cpuSelectionMigrationService = null)
|
||||
CpuSelectionMigrationService? cpuSelectionMigrationService = null,
|
||||
string? masksFilePath = null)
|
||||
{
|
||||
this.logger = logger ?? throw new ArgumentNullException(nameof(logger));
|
||||
this.cpuTopologyService = cpuTopologyService ?? throw new ArgumentNullException(nameof(cpuTopologyService));
|
||||
@@ -75,8 +80,18 @@ namespace ThreadPilot.Services
|
||||
this.cpuTopologyProvider = cpuTopologyProvider;
|
||||
this.cpuSelectionMigrationService = cpuSelectionMigrationService ?? new CpuSelectionMigrationService();
|
||||
|
||||
StoragePaths.EnsureAppDataDirectories();
|
||||
this.masksFilePath = StoragePaths.CoreMasksFilePath;
|
||||
if (string.IsNullOrWhiteSpace(masksFilePath))
|
||||
{
|
||||
StoragePaths.EnsureAppDataDirectories();
|
||||
this.masksFilePath = StoragePaths.CoreMasksFilePath;
|
||||
}
|
||||
else
|
||||
{
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(masksFilePath)!);
|
||||
this.masksFilePath = masksFilePath;
|
||||
}
|
||||
|
||||
this.cpuTopologyService.TopologyDetected += this.OnTopologyDetected;
|
||||
}
|
||||
|
||||
public async Task InitializeAsync()
|
||||
@@ -90,17 +105,57 @@ namespace ThreadPilot.Services
|
||||
|
||||
await this.LoadMasksAsync();
|
||||
|
||||
// If no masks exist, create defaults
|
||||
if (this.AvailableMasks.Count == 0)
|
||||
{
|
||||
this.logger.LogInformation("No masks found, creating defaults...");
|
||||
await this.CreateDefaultMasksAsync();
|
||||
}
|
||||
|
||||
if (await this.BackfillBuiltInDefaultMasksAsync())
|
||||
{
|
||||
await this.SaveMasksAsync();
|
||||
}
|
||||
|
||||
this.initialized = true;
|
||||
this.logger.LogInformation("CoreMaskService initialized with {Count} masks", this.AvailableMasks.Count);
|
||||
}
|
||||
|
||||
private void OnTopologyDetected(object? sender, CpuTopologyDetectedEventArgs e)
|
||||
{
|
||||
if (!this.initialized || !e.DetectionSuccessful)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var dispatcher = Application.Current?.Dispatcher;
|
||||
if (dispatcher != null)
|
||||
{
|
||||
_ = dispatcher.InvokeAsync(async () => await this.BackfillBuiltInDefaultMasksAndSaveAsync());
|
||||
return;
|
||||
}
|
||||
|
||||
_ = Task.Run(this.BackfillBuiltInDefaultMasksAndSaveAsync);
|
||||
}
|
||||
|
||||
private async Task BackfillBuiltInDefaultMasksAndSaveAsync()
|
||||
{
|
||||
if (Interlocked.Exchange(ref this.topologyBackfillInProgress, 1) != 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
if (await this.BackfillBuiltInDefaultMasksAsync())
|
||||
{
|
||||
await this.SaveMasksAsync();
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
Interlocked.Exchange(ref this.topologyBackfillInProgress, 0);
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<CoreMask> CreateMaskAsync(string name, string description, IEnumerable<bool> boolMask)
|
||||
{
|
||||
var mask = new CoreMask
|
||||
@@ -498,11 +553,25 @@ namespace ThreadPilot.Services
|
||||
|
||||
public async Task CreateDefaultMasksAsync()
|
||||
{
|
||||
int coreCount = Environment.ProcessorCount;
|
||||
bool changed = await this.BackfillBuiltInDefaultMasksAsync();
|
||||
if (changed)
|
||||
{
|
||||
await this.SaveMasksAsync();
|
||||
}
|
||||
|
||||
this.logger.LogInformation(
|
||||
"Created or backfilled default masks with topology-aware presets; total masks: {Count}",
|
||||
this.AvailableMasks.Count);
|
||||
}
|
||||
|
||||
private async Task<bool> BackfillBuiltInDefaultMasksAsync()
|
||||
{
|
||||
var topology = this.cpuTopologyService.CurrentTopology;
|
||||
int coreCount = this.ResolveLogicalCoreCount(topology);
|
||||
bool topologyConfident = topology?.TopologyDetectionSuccessful == true;
|
||||
bool hasHyperThreading = topology?.HasHyperThreading == true;
|
||||
bool canCreateNoSmtVariants = topologyConfident && hasHyperThreading;
|
||||
bool changed = false;
|
||||
|
||||
// Collect all default masks with their "no SMT" variants
|
||||
var defaultMasks = new List<(string name, List<bool> boolMask, string description)>();
|
||||
@@ -518,13 +587,32 @@ namespace ThreadPilot.Services
|
||||
Name = ALLCORESMASKNAME,
|
||||
Description = "Use all available CPU cores - baseline mask",
|
||||
IsDefault = true,
|
||||
IsEnabled = true,
|
||||
};
|
||||
for (int i = 0; i < coreCount; i++)
|
||||
{
|
||||
allCoresMask.BoolMask.Add(true);
|
||||
}
|
||||
|
||||
this.AvailableMasks.Add(allCoresMask);
|
||||
changed |= this.AddBuiltInMaskIfMissing(allCoresMask);
|
||||
|
||||
if (coreCount > 1)
|
||||
{
|
||||
var noCoreZeroMask = new CoreMask
|
||||
{
|
||||
Name = NOCORE0MASKNAME,
|
||||
Description = "Use all logical CPUs except CPU 0",
|
||||
IsDefault = false,
|
||||
IsEnabled = true,
|
||||
};
|
||||
|
||||
for (int i = 0; i < coreCount; i++)
|
||||
{
|
||||
noCoreZeroMask.BoolMask.Add(i != 0);
|
||||
}
|
||||
|
||||
changed |= this.AddBuiltInMaskIfMissing(noCoreZeroMask);
|
||||
}
|
||||
|
||||
// 2. Intel Hybrid Architecture: P-Cores, E-Cores, LPE-Cores (Arrow Lake+)
|
||||
if (topology != null && topology.HasIntelHybrid)
|
||||
@@ -634,13 +722,34 @@ namespace ThreadPilot.Services
|
||||
// Add all generated masks to AvailableMasks
|
||||
foreach (var mask in resultMasks)
|
||||
{
|
||||
this.AvailableMasks.Add(mask);
|
||||
changed |= this.AddBuiltInMaskIfMissing(mask);
|
||||
}
|
||||
|
||||
await this.SaveMasksAsync();
|
||||
this.logger.LogInformation(
|
||||
"Created {Count} default masks with topology-aware presets (including no SMT variants)",
|
||||
this.AvailableMasks.Count);
|
||||
await Task.CompletedTask;
|
||||
return changed;
|
||||
}
|
||||
|
||||
private int ResolveLogicalCoreCount(CpuTopologyModel? topology)
|
||||
{
|
||||
if (topology?.TopologyDetectionSuccessful == true && topology.TotalLogicalCores > 0)
|
||||
{
|
||||
return topology.TotalLogicalCores;
|
||||
}
|
||||
|
||||
return Environment.ProcessorCount;
|
||||
}
|
||||
|
||||
private bool AddBuiltInMaskIfMissing(CoreMask mask)
|
||||
{
|
||||
if (this.AvailableMasks.Any(existing =>
|
||||
existing.Name.Equals(mask.Name, StringComparison.OrdinalIgnoreCase)))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
this.AvailableMasks.Add(mask);
|
||||
this.logger.LogInformation("Backfilled built-in core mask '{Name}'", mask.Name);
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
namespace ThreadPilot.Services
|
||||
{
|
||||
public enum ActivityAuditSeverity
|
||||
{
|
||||
Info,
|
||||
Success,
|
||||
Warning,
|
||||
Error,
|
||||
}
|
||||
|
||||
public sealed record ActivityAuditEntry
|
||||
{
|
||||
public DateTime Timestamp { get; init; }
|
||||
|
||||
public string Category { get; init; } = string.Empty;
|
||||
|
||||
public ActivityAuditSeverity Severity { get; init; }
|
||||
|
||||
public string Message { get; init; } = string.Empty;
|
||||
|
||||
public string? Details { get; init; }
|
||||
}
|
||||
|
||||
public interface IActivityAuditService
|
||||
{
|
||||
event EventHandler<ActivityAuditEntry>? EntryAdded;
|
||||
|
||||
Task LogInfoAsync(string category, string message, string? details = null);
|
||||
|
||||
Task LogSuccessAsync(string category, string message, string? details = null);
|
||||
|
||||
Task LogWarningAsync(string category, string message, string? details = null);
|
||||
|
||||
Task LogErrorAsync(string category, string message, string? details = null);
|
||||
|
||||
Task LogUserActionAsync(string action, string details, string? context = null);
|
||||
|
||||
Task<IReadOnlyList<ActivityAuditEntry>> GetEntriesAsync(DateTime? fromDate = null, DateTime? toDate = null);
|
||||
|
||||
Task ClearDisplayAsync();
|
||||
}
|
||||
}
|
||||
@@ -67,6 +67,13 @@ namespace ThreadPilot.Services
|
||||
/// <returns><see langword="true"/> when the file is added successfully; otherwise <see langword="false"/>.</returns>
|
||||
Task<bool> AddCustomPowerPlanFileAsync(string filePath);
|
||||
|
||||
/// <summary>
|
||||
/// Deletes a non-active Windows power plan by GUID when Windows permits removal.
|
||||
/// </summary>
|
||||
/// <param name="powerPlanGuid">Power plan GUID to delete.</param>
|
||||
/// <returns><see langword="true"/> when deletion succeeds; otherwise <see langword="false"/>.</returns>
|
||||
Task<bool> DeletePowerPlanAsync(string powerPlanGuid);
|
||||
|
||||
/// <summary>
|
||||
/// Sets the active power plan by GUID with duplicate change prevention.
|
||||
/// </summary>
|
||||
|
||||
@@ -69,6 +69,7 @@ namespace ThreadPilot.Services
|
||||
private readonly IPersistentRulesEngine rulesEngine;
|
||||
private readonly IApplicationSettingsService settingsService;
|
||||
private readonly ILogger<PersistentRuleAutoApplyService> logger;
|
||||
private readonly IActivityAuditService? activityAuditService;
|
||||
private readonly Func<DateTimeOffset> nowProvider;
|
||||
private readonly TimeSpan cooldown;
|
||||
private readonly ConcurrentDictionary<RuleAttemptKey, DateTimeOffset> recentAttempts = new();
|
||||
@@ -78,8 +79,9 @@ namespace ThreadPilot.Services
|
||||
IPersistentProcessRuleMatcher matcher,
|
||||
IPersistentRulesEngine rulesEngine,
|
||||
IApplicationSettingsService settingsService,
|
||||
ILogger<PersistentRuleAutoApplyService> logger)
|
||||
: this(ruleStore, matcher, rulesEngine, settingsService, logger, () => DateTimeOffset.UtcNow, DefaultCooldown)
|
||||
ILogger<PersistentRuleAutoApplyService> logger,
|
||||
IActivityAuditService? activityAuditService = null)
|
||||
: this(ruleStore, matcher, rulesEngine, settingsService, logger, () => DateTimeOffset.UtcNow, DefaultCooldown, activityAuditService)
|
||||
{
|
||||
}
|
||||
|
||||
@@ -90,7 +92,8 @@ namespace ThreadPilot.Services
|
||||
IApplicationSettingsService settingsService,
|
||||
ILogger<PersistentRuleAutoApplyService> logger,
|
||||
Func<DateTimeOffset> nowProvider,
|
||||
TimeSpan cooldown)
|
||||
TimeSpan cooldown,
|
||||
IActivityAuditService? activityAuditService = null)
|
||||
{
|
||||
this.ruleStore = ruleStore ?? throw new ArgumentNullException(nameof(ruleStore));
|
||||
this.matcher = matcher ?? throw new ArgumentNullException(nameof(matcher));
|
||||
@@ -99,6 +102,7 @@ namespace ThreadPilot.Services
|
||||
this.logger = logger ?? throw new ArgumentNullException(nameof(logger));
|
||||
this.nowProvider = nowProvider ?? throw new ArgumentNullException(nameof(nowProvider));
|
||||
this.cooldown = cooldown <= TimeSpan.Zero ? DefaultCooldown : cooldown;
|
||||
this.activityAuditService = activityAuditService;
|
||||
}
|
||||
|
||||
public async Task<IReadOnlyList<PersistentRuleAutoApplyResult>> ApplyForDiscoveredProcessesAsync(
|
||||
@@ -204,7 +208,7 @@ namespace ThreadPilot.Services
|
||||
var results = applyResults.Select(PersistentRuleAutoApplyResult.FromApplyResult).ToList();
|
||||
foreach (var result in results)
|
||||
{
|
||||
this.LogResult(result);
|
||||
await this.LogResultAsync(result).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
return results;
|
||||
@@ -252,7 +256,7 @@ namespace ThreadPilot.Services
|
||||
}
|
||||
}
|
||||
|
||||
private void LogResult(PersistentRuleAutoApplyResult result)
|
||||
private async Task LogResultAsync(PersistentRuleAutoApplyResult result)
|
||||
{
|
||||
if (result.Success)
|
||||
{
|
||||
@@ -261,6 +265,7 @@ namespace ThreadPilot.Services
|
||||
result.RuleId,
|
||||
result.ProcessName,
|
||||
result.ProcessId);
|
||||
await this.LogActivityResultAsync(result).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -274,6 +279,36 @@ namespace ThreadPilot.Services
|
||||
result.ProcessName,
|
||||
result.ProcessId,
|
||||
result.UserMessage);
|
||||
await this.LogActivityResultAsync(result).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private async Task LogActivityResultAsync(PersistentRuleAutoApplyResult result)
|
||||
{
|
||||
if (this.activityAuditService == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var action = result.Success
|
||||
? "PersistentRuleAutoApplied"
|
||||
: "PersistentRuleAutoApplyFailed";
|
||||
var message = result.Success
|
||||
? $"Auto-applied saved rule for {result.ProcessName}."
|
||||
: $"Failed to auto-apply saved rule for {result.ProcessName}: {result.UserMessage}";
|
||||
|
||||
try
|
||||
{
|
||||
await this.activityAuditService
|
||||
.LogUserActionAsync(
|
||||
action,
|
||||
message,
|
||||
$"Rule: {result.RuleId}, PID: {result.ProcessId}")
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
this.logger.LogWarning(ex, "Failed to write persistent rule activity audit entry");
|
||||
}
|
||||
}
|
||||
|
||||
private bool IsEnabled() =>
|
||||
|
||||
@@ -377,6 +377,64 @@ namespace ThreadPilot.Services
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<bool> DeletePowerPlanAsync(string powerPlanGuid)
|
||||
{
|
||||
if (!Guid.TryParse(powerPlanGuid, out _))
|
||||
{
|
||||
this.logger.LogWarning("Rejected invalid power plan GUID for delete: {PowerPlanGuid}", powerPlanGuid);
|
||||
return false;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
var activePlan = await this.GetActivePowerPlan().ConfigureAwait(false);
|
||||
if (string.Equals(activePlan?.Guid, powerPlanGuid, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
this.logger.LogWarning("Blocked deletion of active power plan: {PowerPlanGuid}", powerPlanGuid);
|
||||
await this.enhancedLogger.LogSystemEventAsync(
|
||||
LogEventTypes.PowerPlan.ChangeFailed,
|
||||
$"Blocked deletion of active power plan '{activePlan?.Name ?? powerPlanGuid}'",
|
||||
Microsoft.Extensions.Logging.LogLevel.Warning).ConfigureAwait(false);
|
||||
return false;
|
||||
}
|
||||
|
||||
var targetPlan = await this.GetPowerPlanByGuidAsync(powerPlanGuid).ConfigureAwait(false);
|
||||
var result = await this.RunPowerCfgAsync("/delete", powerPlanGuid).ConfigureAwait(false);
|
||||
var success = result.ExitCode == 0;
|
||||
|
||||
if (success)
|
||||
{
|
||||
this.logger.LogInformation("Deleted power plan '{PowerPlan}' ({PowerPlanGuid})", targetPlan?.Name ?? "Unknown", powerPlanGuid);
|
||||
await this.enhancedLogger.LogUserActionAsync(
|
||||
"PowerPlanDeleted",
|
||||
$"Deleted power plan {targetPlan?.Name ?? powerPlanGuid}",
|
||||
$"Guid: {powerPlanGuid}").ConfigureAwait(false);
|
||||
}
|
||||
else
|
||||
{
|
||||
this.logger.LogWarning(
|
||||
"Failed to delete power plan '{PowerPlanGuid}' - powercfg exit code: {ExitCode}, stderr: {StdErr}",
|
||||
powerPlanGuid,
|
||||
result.ExitCode,
|
||||
result.StandardError);
|
||||
|
||||
await this.enhancedLogger.LogSystemEventAsync(
|
||||
LogEventTypes.PowerPlan.ChangeFailed,
|
||||
$"Failed to delete power plan '{targetPlan?.Name ?? powerPlanGuid}' - Exit code: {result.ExitCode}",
|
||||
Microsoft.Extensions.Logging.LogLevel.Warning).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
return success;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
this.logger.LogError(ex, "Exception occurred while deleting power plan '{PowerPlanGuid}'", powerPlanGuid);
|
||||
await this.enhancedLogger.LogErrorAsync(ex, "PowerPlanService.DeletePowerPlanAsync",
|
||||
new Dictionary<string, object> { ["PowerPlanGuid"] = powerPlanGuid }).ConfigureAwait(false);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<string?> GetActivePowerPlanGuidAsync()
|
||||
{
|
||||
var activePlan = await this.GetActivePowerPlan().ConfigureAwait(false);
|
||||
|
||||
@@ -66,6 +66,7 @@ namespace ThreadPilot.Services
|
||||
|
||||
// Enhanced logging service
|
||||
services.AddSingleton<IEnhancedLoggingService, EnhancedLoggingService>();
|
||||
services.AddSingleton<IActivityAuditService, ActivityAuditService>();
|
||||
services.AddSingleton<IProcessRunner, SystemProcessRunner>();
|
||||
services.AddSingleton<ISettingsStorage, FileSettingsStorage>();
|
||||
services.AddSingleton(sp =>
|
||||
@@ -236,6 +237,7 @@ namespace ThreadPilot.Services
|
||||
typeof(IPowerPlanService),
|
||||
typeof(ICpuTopologyService),
|
||||
typeof(IEnhancedLoggingService),
|
||||
typeof(IActivityAuditService),
|
||||
typeof(IApplicationSettingsService),
|
||||
};
|
||||
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
namespace ThreadPilot.Services
|
||||
{
|
||||
using System.Drawing;
|
||||
|
||||
public static class SystemTrayMenuPlacement
|
||||
{
|
||||
public static Point ResolveMenuOpenPoint(Point cursorPosition, Point lastKnownPosition)
|
||||
{
|
||||
return ResolveMenuOpenPoint(
|
||||
cursorPosition,
|
||||
lastKnownPosition,
|
||||
Rectangle.Empty,
|
||||
Rectangle.Empty);
|
||||
}
|
||||
|
||||
public static Point ResolveMenuOpenPoint(
|
||||
Point cursorPosition,
|
||||
Point lastKnownPosition,
|
||||
Rectangle trayBounds,
|
||||
Rectangle fallbackWorkingArea)
|
||||
{
|
||||
if (!cursorPosition.IsEmpty)
|
||||
{
|
||||
return cursorPosition;
|
||||
}
|
||||
|
||||
if (!lastKnownPosition.IsEmpty)
|
||||
{
|
||||
return lastKnownPosition;
|
||||
}
|
||||
|
||||
if (!trayBounds.IsEmpty)
|
||||
{
|
||||
return new Point(trayBounds.Left + (trayBounds.Width / 2), trayBounds.Top + (trayBounds.Height / 2));
|
||||
}
|
||||
|
||||
if (!fallbackWorkingArea.IsEmpty)
|
||||
{
|
||||
return new Point(
|
||||
Math.Max(fallbackWorkingArea.Left + 1, fallbackWorkingArea.Right - 8),
|
||||
Math.Max(fallbackWorkingArea.Top + 1, fallbackWorkingArea.Bottom - 8));
|
||||
}
|
||||
|
||||
return new Point(16, 16);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -46,6 +46,7 @@ namespace ThreadPilot.Services
|
||||
private TrayIconState currentIconState = TrayIconState.Normal;
|
||||
private bool isDarkTheme = true;
|
||||
private Font? menuFont;
|
||||
private Point lastContextMenuOpenPoint = Point.Empty;
|
||||
private bool disposed = false;
|
||||
|
||||
public event EventHandler? QuickApplyRequested;
|
||||
@@ -100,7 +101,7 @@ namespace ThreadPilot.Services
|
||||
|
||||
// Set up event handlers
|
||||
this.notifyIcon.DoubleClick += this.OnTrayIconDoubleClick;
|
||||
this.notifyIcon.ContextMenuStrip = this.contextMenu;
|
||||
this.notifyIcon.MouseUp += this.OnTrayIconMouseUp;
|
||||
|
||||
// Set initial icon state
|
||||
this.UpdateTrayIcon(TrayIconState.Normal);
|
||||
@@ -255,6 +256,30 @@ namespace ThreadPilot.Services
|
||||
this.ShowMainWindowRequested?.Invoke(this, EventArgs.Empty);
|
||||
}
|
||||
|
||||
private void OnTrayIconMouseUp(object? sender, MouseEventArgs e)
|
||||
{
|
||||
if (e.Button != MouseButtons.Right || this.contextMenu == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var cursorPosition = Cursor.Position;
|
||||
var workingArea = Screen.FromPoint(cursorPosition.IsEmpty ? this.lastContextMenuOpenPoint : cursorPosition).WorkingArea;
|
||||
var openPoint = SystemTrayMenuPlacement.ResolveMenuOpenPoint(
|
||||
cursorPosition,
|
||||
this.lastContextMenuOpenPoint,
|
||||
Rectangle.Empty,
|
||||
workingArea);
|
||||
this.lastContextMenuOpenPoint = openPoint;
|
||||
|
||||
if (this.contextMenu.Visible)
|
||||
{
|
||||
this.contextMenu.Close(ToolStripDropDownCloseReason.CloseCalled);
|
||||
}
|
||||
|
||||
this.contextMenu.Show(openPoint, ToolStripDropDownDirection.Default);
|
||||
}
|
||||
|
||||
private void OnQuickApplyClick(object? sender, EventArgs e)
|
||||
{
|
||||
this.QuickApplyRequested?.Invoke(this, EventArgs.Empty);
|
||||
@@ -513,6 +538,7 @@ namespace ThreadPilot.Services
|
||||
|
||||
if (this.notifyIcon != null)
|
||||
{
|
||||
this.notifyIcon.MouseUp -= this.OnTrayIconMouseUp;
|
||||
this.notifyIcon.Visible = false;
|
||||
this.notifyIcon.Dispose();
|
||||
this.notifyIcon = null;
|
||||
|
||||
@@ -51,6 +51,8 @@ namespace ThreadPilot.Services
|
||||
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 const int HighSchedulingCategoryDisabledValue = 2;
|
||||
internal const int HighSchedulingCategoryEnabledValue = 0x1A;
|
||||
private readonly ILogger<SystemTweaksService> logger;
|
||||
private readonly IElevationService elevationService;
|
||||
|
||||
@@ -498,13 +500,13 @@ namespace ThreadPilot.Services
|
||||
}
|
||||
|
||||
var rawValue = ReadRegistryIntValue(key, PrioritySeparationValueName);
|
||||
var isEnabled = rawValue.GetValueOrDefault(2) == 38;
|
||||
var isEnabled = rawValue.GetValueOrDefault(HighSchedulingCategoryDisabledValue) == HighSchedulingCategoryEnabledValue;
|
||||
|
||||
return Task.FromResult(new TweakStatus
|
||||
{
|
||||
IsEnabled = isEnabled,
|
||||
IsAvailable = true,
|
||||
Description = "ON applies high foreground boost (Win32PrioritySeparation=38)",
|
||||
Description = "ON applies high foreground boost (Win32PrioritySeparation=26 / 0x1A)",
|
||||
});
|
||||
}
|
||||
catch (Exception ex)
|
||||
@@ -531,8 +533,8 @@ namespace ThreadPilot.Services
|
||||
return false;
|
||||
}
|
||||
|
||||
// ON = 38 (Short, Variable, High), OFF = 2 (default/minimal boost)
|
||||
key.SetValue(PrioritySeparationValueName, enabled ? 38 : 2, RegistryValueKind.DWord);
|
||||
// ON = 26 / 0x1A, OFF = 2 (default/minimal boost)
|
||||
key.SetValue(PrioritySeparationValueName, GetHighSchedulingCategoryRegistryValue(enabled), RegistryValueKind.DWord);
|
||||
|
||||
var status = await this.GetHighSchedulingCategoryStatusAsync();
|
||||
this.TweakStatusChanged?.Invoke(this, new TweakStatusChangedEventArgs("HighSchedulingCategory", status));
|
||||
@@ -575,6 +577,9 @@ namespace ThreadPilot.Services
|
||||
return true;
|
||||
}
|
||||
|
||||
internal static int GetHighSchedulingCategoryRegistryValue(bool enabled) =>
|
||||
enabled ? HighSchedulingCategoryEnabledValue : HighSchedulingCategoryDisabledValue;
|
||||
|
||||
private async Task EnsurePowerSettingVisibleAsync(string subgroupAlias, string settingAlias)
|
||||
{
|
||||
var attributesResult = await RunProcessAsync(
|
||||
|
||||
@@ -30,6 +30,8 @@ namespace ThreadPilot.Services
|
||||
|
||||
private readonly ILogger<ThemeService> logger;
|
||||
private ResourceDictionary? activeThemeDictionary;
|
||||
private Uri? activeThemeUri;
|
||||
private bool hasAppliedTheme;
|
||||
|
||||
public bool IsDarkTheme { get; private set; }
|
||||
|
||||
@@ -42,6 +44,12 @@ namespace ThreadPilot.Services
|
||||
public void ApplyTheme(bool useDarkTheme)
|
||||
{
|
||||
var targetUri = new Uri(useDarkTheme ? DarkThemeDictionaryPath : LightThemeDictionaryPath, UriKind.Relative);
|
||||
if (this.hasAppliedTheme &&
|
||||
this.IsDarkTheme == useDarkTheme &&
|
||||
string.Equals(this.activeThemeUri?.OriginalString, targetUri.OriginalString, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var appResources = System.Windows.Application.Current?.Resources;
|
||||
if (appResources == null)
|
||||
@@ -60,6 +68,8 @@ namespace ThreadPilot.Services
|
||||
this.activeThemeDictionary = ThemeDictionaryPolicy.ReplaceThreadPilotThemeDictionary(appResources, targetUri);
|
||||
|
||||
this.IsDarkTheme = useDarkTheme;
|
||||
this.activeThemeUri = targetUri;
|
||||
this.hasAppliedTheme = true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
@@ -190,15 +200,32 @@ namespace ThreadPilot.Services
|
||||
ArgumentNullException.ThrowIfNull(targetUri);
|
||||
ArgumentNullException.ThrowIfNull(dictionaryFactory);
|
||||
|
||||
ResourceDictionary? matchingDictionary = null;
|
||||
for (int i = appResources.MergedDictionaries.Count - 1; i >= 0; i--)
|
||||
{
|
||||
var dictionary = appResources.MergedDictionaries[i];
|
||||
if (IsThreadPilotThemeDictionary(dictionary.Source?.OriginalString))
|
||||
{
|
||||
if (matchingDictionary == null &&
|
||||
string.Equals(dictionary.Source?.OriginalString, targetUri.OriginalString, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
matchingDictionary = dictionary;
|
||||
continue;
|
||||
}
|
||||
|
||||
appResources.MergedDictionaries.RemoveAt(i);
|
||||
}
|
||||
}
|
||||
|
||||
if (matchingDictionary != null)
|
||||
{
|
||||
appResources.MergedDictionaries.Remove(matchingDictionary);
|
||||
appResources.MergedDictionaries.Insert(
|
||||
GetInsertionIndex(appResources.MergedDictionaries.Count),
|
||||
matchingDictionary);
|
||||
return matchingDictionary;
|
||||
}
|
||||
|
||||
var nextDictionary = dictionaryFactory(targetUri);
|
||||
appResources.MergedDictionaries.Insert(
|
||||
GetInsertionIndex(appResources.MergedDictionaries.Count),
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
namespace ThreadPilot.Core.Tests
|
||||
{
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
using ThreadPilot.Services;
|
||||
|
||||
public sealed class ActivityAuditServiceTests
|
||||
{
|
||||
[Theory]
|
||||
[InlineData("ThemeChanged", "Theme changed to Dark", "Settings", ActivityAuditSeverity.Success)]
|
||||
[InlineData("SystemTweakApplied", "Core Parking enabled", "Tweaks", ActivityAuditSeverity.Success)]
|
||||
[InlineData("SystemTweakFailed", "Failed to enable Core Parking", "Tweaks", ActivityAuditSeverity.Error)]
|
||||
[InlineData("OptimizationMonitoringStarted", "Performance monitoring started", "Optimization", ActivityAuditSeverity.Success)]
|
||||
[InlineData("OptimizationActionFailed", "Failed to start performance monitoring: unavailable", "Optimization", ActivityAuditSeverity.Error)]
|
||||
[InlineData("PowerPlanApplied", "Applied power plan Gaming", "Power Plans", ActivityAuditSeverity.Success)]
|
||||
[InlineData("PowerPlanDeleted", "Deleted power plan Gaming", "Power Plans", ActivityAuditSeverity.Success)]
|
||||
[InlineData("PowerPlansRefreshed", "Refreshed power plan list", "Power Plans", ActivityAuditSeverity.Success)]
|
||||
[InlineData("ProcessPriorityChanged", "CPU priority changed for Game.exe: High", "Priority", ActivityAuditSeverity.Success)]
|
||||
[InlineData("ProcessPriorityChangeFailed", "Windows denied this change.", "Priority", ActivityAuditSeverity.Warning)]
|
||||
[InlineData("ProcessPriorityBlocked", "Realtime priority is blocked by ThreadPilot.", "Priority", ActivityAuditSeverity.Warning)]
|
||||
[InlineData("ProcessMemoryPriorityChanged", "Memory priority changed for Game.exe: Low", "Memory Priority", ActivityAuditSeverity.Success)]
|
||||
[InlineData("ProcessMemoryPriorityFailed", "The process appears protected by anti-cheat or process protection.", "Memory Priority", ActivityAuditSeverity.Warning)]
|
||||
[InlineData("CpuSetsCleared", "CPU Sets cleared for Game.exe", "Affinity", ActivityAuditSeverity.Success)]
|
||||
[InlineData("CpuSetsClearFailed", "The process exited before ThreadPilot could apply the change.", "Affinity", ActivityAuditSeverity.Error)]
|
||||
[InlineData("ProcessAffinityApplied", "Affinity applied successfully to Game.exe", "Affinity", ActivityAuditSeverity.Success)]
|
||||
[InlineData("ProcessAffinityFailed", "The process appears protected by anti-cheat or process protection.", "Affinity", ActivityAuditSeverity.Warning)]
|
||||
[InlineData("PersistentRuleSaved", "Saved rule for Game.exe.", "Rules", ActivityAuditSeverity.Success)]
|
||||
[InlineData("PersistentRuleSaveFailed", "Failed to save rule for Game.exe.", "Rules", ActivityAuditSeverity.Error)]
|
||||
[InlineData("PersistentRuleAutoApplied", "Auto-applied saved rule for Game.exe.", "Rules", ActivityAuditSeverity.Success)]
|
||||
[InlineData("PersistentRuleAutoApplyFailed", "Failed to auto-apply saved rule for Game.exe: protected process.", "Rules", ActivityAuditSeverity.Warning)]
|
||||
public async Task LogUserActionAsync_CreatesVisibleActivityEntry(
|
||||
string action,
|
||||
string details,
|
||||
string expectedCategory,
|
||||
ActivityAuditSeverity expectedSeverity)
|
||||
{
|
||||
var service = new ActivityAuditService(NullLogger<ActivityAuditService>.Instance);
|
||||
|
||||
await service.LogUserActionAsync(action, details, "PID: 42");
|
||||
|
||||
var entry = Assert.Single(await service.GetEntriesAsync());
|
||||
Assert.Equal(expectedCategory, entry.Category);
|
||||
Assert.Equal(expectedSeverity, entry.Severity);
|
||||
Assert.Equal(details, entry.Message);
|
||||
Assert.Equal("PID: 42", entry.Details);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetEntriesAsync_ReturnsMostRecentFirstAndPreservesTimestamp()
|
||||
{
|
||||
var service = new ActivityAuditService(NullLogger<ActivityAuditService>.Instance);
|
||||
|
||||
await service.LogInfoAsync("Diagnostics", "First");
|
||||
await Task.Delay(5);
|
||||
await service.LogSuccessAsync("Power Plans", "Second");
|
||||
|
||||
var entries = await service.GetEntriesAsync();
|
||||
|
||||
Assert.Collection(
|
||||
entries,
|
||||
entry => Assert.Equal("Second", entry.Message),
|
||||
entry => Assert.Equal("First", entry.Message));
|
||||
Assert.All(entries, entry => Assert.NotEqual(default, entry.Timestamp));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -12,6 +12,7 @@ namespace ThreadPilot.Core.Tests
|
||||
Assert.True(settings.AutostartWithWindows);
|
||||
Assert.False(settings.StartMinimized);
|
||||
Assert.True(settings.ApplyPersistentRulesOnProcessStart);
|
||||
Assert.False(settings.HasSeenStartupMinimizedSuggestion);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
|
||||
@@ -132,6 +132,22 @@ namespace ThreadPilot.Core.Tests
|
||||
Assert.True(service.Settings.StartMinimized);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task LoadSettingsAsync_PreservesStartupMinimizedSuggestionDismissal()
|
||||
{
|
||||
var storage = new FakeSettingsStorage();
|
||||
storage.Files[TestPaths.SettingsFilePath] = """
|
||||
{
|
||||
"hasSeenStartupMinimizedSuggestion": true
|
||||
}
|
||||
""";
|
||||
var service = CreateService(storage);
|
||||
|
||||
await service.LoadSettingsAsync();
|
||||
|
||||
Assert.True(service.Settings.HasSeenStartupMinimizedSuggestion);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ImportSettingsAsync_Throws_WhenFileIsMissing()
|
||||
{
|
||||
|
||||
@@ -0,0 +1,225 @@
|
||||
namespace ThreadPilot.Core.Tests
|
||||
{
|
||||
using System.Text.Json;
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
using Moq;
|
||||
using ThreadPilot.Models;
|
||||
using ThreadPilot.Services;
|
||||
|
||||
public sealed class CoreMaskServiceTests
|
||||
{
|
||||
private static readonly JsonSerializerOptions JsonOptions = new()
|
||||
{
|
||||
WriteIndented = true,
|
||||
};
|
||||
|
||||
[Fact]
|
||||
public async Task InitializeAsync_WhenNoMaskFile_CreatesAllCoresAndNoCoreZero()
|
||||
{
|
||||
var masksFilePath = CreateTempMasksPath();
|
||||
var service = CreateService(CreateTopology(logicalCoreCount: 4), masksFilePath);
|
||||
|
||||
await service.InitializeAsync();
|
||||
|
||||
Assert.Contains(service.AvailableMasks, mask => mask.Name == "All Cores");
|
||||
var noCoreZero = Assert.Single(service.AvailableMasks, mask => mask.Name == "No Core 0");
|
||||
Assert.Equal(new[] { false, true, true, true }, noCoreZero.BoolMask);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task InitializeAsync_WithSmtTopology_CreatesAllNoSmt()
|
||||
{
|
||||
var masksFilePath = CreateTempMasksPath();
|
||||
var service = CreateService(CreateAmdSmtTopology(physicalCoreCount: 8, threadsPerCore: 2), masksFilePath);
|
||||
|
||||
await service.InitializeAsync();
|
||||
|
||||
var allNoSmt = Assert.Single(service.AvailableMasks, mask => mask.Name == "All no SMT");
|
||||
Assert.Equal(16, allNoSmt.BoolMask.Count);
|
||||
Assert.Equal(8, allNoSmt.SelectedCoreCount);
|
||||
Assert.Equal(
|
||||
Enumerable.Range(0, 16).Select(index => index % 2 == 0),
|
||||
allNoSmt.BoolMask);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task InitializeAsync_WhenExistingFileHasOnlyAllCores_BackfillsMissingBuiltIns()
|
||||
{
|
||||
var masksFilePath = CreateTempMasksPath();
|
||||
var existingId = "existing-all-cores";
|
||||
await WriteMasksAsync(
|
||||
masksFilePath,
|
||||
CreateStoredMask(existingId, "All Cores", [true, true, true, true], isDefault: true));
|
||||
var service = CreateService(CreateTopology(logicalCoreCount: 4), masksFilePath);
|
||||
|
||||
await service.InitializeAsync();
|
||||
|
||||
Assert.Equal(existingId, Assert.Single(service.AvailableMasks, mask => mask.Name == "All Cores").Id);
|
||||
Assert.Contains(service.AvailableMasks, mask => mask.Name == "No Core 0");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task InitializeAsync_BackfillDoesNotDuplicateBuiltIns()
|
||||
{
|
||||
var masksFilePath = CreateTempMasksPath();
|
||||
await WriteMasksAsync(
|
||||
masksFilePath,
|
||||
CreateStoredMask("all-cores", "All Cores", [true, true, true, true], isDefault: true),
|
||||
CreateStoredMask("no-core-zero", "No Core 0", [false, true, true, true]));
|
||||
var service = CreateService(CreateTopology(logicalCoreCount: 4), masksFilePath);
|
||||
|
||||
await service.InitializeAsync();
|
||||
await service.InitializeAsync();
|
||||
|
||||
Assert.Equal(1, service.AvailableMasks.Count(mask => mask.Name == "All Cores"));
|
||||
Assert.Equal(1, service.AvailableMasks.Count(mask => mask.Name == "No Core 0"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task InitializeAsync_BackfillPreservesUserMasks()
|
||||
{
|
||||
var masksFilePath = CreateTempMasksPath();
|
||||
await WriteMasksAsync(
|
||||
masksFilePath,
|
||||
CreateStoredMask("all-cores", "All Cores", [true, true, true, true], isDefault: true),
|
||||
CreateStoredMask("custom-mask", "My Game Mask", [false, true, true, false]));
|
||||
var service = CreateService(CreateTopology(logicalCoreCount: 4), masksFilePath);
|
||||
|
||||
await service.InitializeAsync();
|
||||
|
||||
var customMask = Assert.Single(service.AvailableMasks, mask => mask.Id == "custom-mask");
|
||||
Assert.Equal("My Game Mask", customMask.Name);
|
||||
Assert.Equal(new[] { false, true, true, false }, customMask.BoolMask);
|
||||
Assert.Contains(service.AvailableMasks, mask => mask.Name == "No Core 0");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task TopologyDetected_AfterInitialLoad_BackfillsSmtDefaults()
|
||||
{
|
||||
var masksFilePath = CreateTempMasksPath();
|
||||
await WriteMasksAsync(
|
||||
masksFilePath,
|
||||
CreateStoredMask("all-cores", "All Cores", [true, true, true, true], isDefault: true));
|
||||
CpuTopologyModel? currentTopology = null;
|
||||
var topologyService = new Mock<ICpuTopologyService>(MockBehavior.Strict);
|
||||
topologyService.SetupGet(service => service.CurrentTopology).Returns(() => currentTopology);
|
||||
var service = new CoreMaskService(
|
||||
NullLogger<CoreMaskService>.Instance,
|
||||
topologyService.Object,
|
||||
Mock.Of<IServiceProvider>(),
|
||||
masksFilePath: masksFilePath);
|
||||
|
||||
await service.InitializeAsync();
|
||||
Assert.DoesNotContain(service.AvailableMasks, mask => mask.Name == "All no SMT");
|
||||
|
||||
currentTopology = CreateAmdSmtTopology(physicalCoreCount: 8, threadsPerCore: 2);
|
||||
topologyService.Raise(
|
||||
mock => mock.TopologyDetected += null,
|
||||
new CpuTopologyDetectedEventArgs(currentTopology, successful: true));
|
||||
|
||||
Assert.True(SpinWait.SpinUntil(
|
||||
() => service.AvailableMasks.Any(mask => mask.Name == "All no SMT"),
|
||||
TimeSpan.FromSeconds(3)));
|
||||
Assert.Equal(1, service.AvailableMasks.Count(mask => mask.Name == "All no SMT"));
|
||||
}
|
||||
|
||||
private static CoreMaskService CreateService(CpuTopologyModel topology, string masksFilePath)
|
||||
{
|
||||
var topologyService = new Mock<ICpuTopologyService>(MockBehavior.Strict);
|
||||
topologyService.SetupGet(service => service.CurrentTopology).Returns(topology);
|
||||
|
||||
return new CoreMaskService(
|
||||
NullLogger<CoreMaskService>.Instance,
|
||||
topologyService.Object,
|
||||
Mock.Of<IServiceProvider>(),
|
||||
masksFilePath: masksFilePath);
|
||||
}
|
||||
|
||||
private static CpuTopologyModel CreateTopology(int logicalCoreCount)
|
||||
{
|
||||
var topology = new CpuTopologyModel
|
||||
{
|
||||
CpuBrand = "Generic CPU",
|
||||
TopologyDetectionSuccessful = true,
|
||||
};
|
||||
|
||||
for (var index = 0; index < logicalCoreCount; index++)
|
||||
{
|
||||
topology.LogicalCores.Add(new CpuCoreModel
|
||||
{
|
||||
LogicalCoreId = index,
|
||||
PhysicalCoreId = index,
|
||||
SocketId = 0,
|
||||
LogicalProcessorName = $"CPU{index}",
|
||||
});
|
||||
}
|
||||
|
||||
return topology;
|
||||
}
|
||||
|
||||
private static CpuTopologyModel CreateAmdSmtTopology(int physicalCoreCount, int threadsPerCore)
|
||||
{
|
||||
var topology = new CpuTopologyModel
|
||||
{
|
||||
CpuBrand = "AMD Ryzen",
|
||||
TopologyDetectionSuccessful = true,
|
||||
};
|
||||
|
||||
for (var physicalCore = 0; physicalCore < physicalCoreCount; physicalCore++)
|
||||
{
|
||||
var firstLogicalCore = physicalCore * threadsPerCore;
|
||||
for (var thread = 0; thread < threadsPerCore; thread++)
|
||||
{
|
||||
var logicalCore = firstLogicalCore + thread;
|
||||
topology.LogicalCores.Add(new CpuCoreModel
|
||||
{
|
||||
LogicalCoreId = logicalCore,
|
||||
PhysicalCoreId = physicalCore,
|
||||
SocketId = 0,
|
||||
CoreType = CpuCoreType.Zen4,
|
||||
IsHyperThreaded = threadsPerCore > 1,
|
||||
HyperThreadSibling = threadsPerCore > 1
|
||||
? firstLogicalCore + ((thread + 1) % threadsPerCore)
|
||||
: null,
|
||||
LogicalProcessorName = $"CPU{physicalCore}_T{thread}",
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return topology;
|
||||
}
|
||||
|
||||
private static string CreateTempMasksPath()
|
||||
{
|
||||
var directory = Path.Combine(Path.GetTempPath(), "ThreadPilot-CoreMaskServiceTests", Guid.NewGuid().ToString("N"));
|
||||
Directory.CreateDirectory(directory);
|
||||
return Path.Combine(directory, "core_masks.json");
|
||||
}
|
||||
|
||||
private static object CreateStoredMask(
|
||||
string id,
|
||||
string name,
|
||||
IEnumerable<bool> boolMask,
|
||||
bool isDefault = false) =>
|
||||
new
|
||||
{
|
||||
id,
|
||||
name,
|
||||
description = $"{name} description",
|
||||
boolMask = boolMask.ToList(),
|
||||
profileSchemaVersion = CpuAffinityProfileSchemaVersions.Legacy,
|
||||
cpuSelection = (CpuSelection?)null,
|
||||
cpuSelectionMigration = (CpuSelectionMigrationMetadata?)null,
|
||||
isDefault,
|
||||
isEnabled = true,
|
||||
createdAt = DateTime.UtcNow.AddDays(-1),
|
||||
updatedAt = DateTime.UtcNow.AddDays(-1),
|
||||
};
|
||||
|
||||
private static Task WriteMasksAsync(string masksFilePath, params object[] masks)
|
||||
{
|
||||
var json = JsonSerializer.Serialize(masks, JsonOptions);
|
||||
return File.WriteAllTextAsync(masksFilePath, json);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
namespace ThreadPilot.Core.Tests
|
||||
{
|
||||
using CommunityToolkit.Mvvm.Input;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
using Moq;
|
||||
using ThreadPilot.Models;
|
||||
using ThreadPilot.Services;
|
||||
using ThreadPilot.ViewModels;
|
||||
|
||||
public sealed class LogViewerActivityAuditTests
|
||||
{
|
||||
[Fact]
|
||||
public async Task InitializeAsync_LoadsVisibleThreadPilotActivityEntries()
|
||||
{
|
||||
var audit = new ActivityAuditService(NullLogger<ActivityAuditService>.Instance);
|
||||
await audit.LogSuccessAsync("Power Plans", "Applied power plan Gaming", "Guid: game");
|
||||
var viewModel = CreateViewModel(audit);
|
||||
|
||||
await viewModel.InitializeAsync();
|
||||
|
||||
var entry = Assert.Single(viewModel.LogEntries);
|
||||
Assert.Equal("Power Plans", entry.Category);
|
||||
Assert.Equal("Applied power plan Gaming", entry.Message);
|
||||
Assert.Equal(LogLevel.Information, entry.Level);
|
||||
Assert.Equal("Guid: game", entry.Details);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ClearLogsCommand_ClearsOnlyVisibleActivityDisplayWithoutAddingNoise()
|
||||
{
|
||||
var audit = new ActivityAuditService(NullLogger<ActivityAuditService>.Instance);
|
||||
await audit.LogSuccessAsync("Power Plans", "Applied power plan Gaming");
|
||||
var viewModel = CreateViewModel(audit);
|
||||
await viewModel.InitializeAsync();
|
||||
|
||||
await ((IAsyncRelayCommand)viewModel.ClearLogsCommand).ExecuteAsync(null);
|
||||
|
||||
Assert.Empty(viewModel.LogEntries);
|
||||
Assert.Single(await audit.GetEntriesAsync());
|
||||
}
|
||||
|
||||
private static LogViewerViewModel CreateViewModel(IActivityAuditService audit)
|
||||
{
|
||||
var logging = new Mock<IEnhancedLoggingService>(MockBehavior.Loose);
|
||||
logging
|
||||
.Setup(service => service.GetLogStatisticsAsync())
|
||||
.ReturnsAsync(new LogFileStatistics());
|
||||
var settings = new Mock<IApplicationSettingsService>(MockBehavior.Loose);
|
||||
settings
|
||||
.SetupGet(service => service.Settings)
|
||||
.Returns(new ApplicationSettingsModel());
|
||||
|
||||
return new LogViewerViewModel(
|
||||
audit,
|
||||
logging.Object,
|
||||
settings.Object,
|
||||
NullLogger<LogViewerViewModel>.Instance);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -38,6 +38,7 @@ namespace ThreadPilot.Core.Tests
|
||||
harness.PowerPlan.Verify(x => x.GetActivePowerPlan(), Times.Once);
|
||||
harness.Performance.Verify(x => x.StartMonitoringAsync(), Times.Never);
|
||||
Assert.False(viewModel.IsMonitoring);
|
||||
Assert.Empty(await harness.Audit.GetEntriesAsync());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -56,6 +57,111 @@ namespace ThreadPilot.Core.Tests
|
||||
Assert.Equal("Stopped", viewModel.MonitoringStateText);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task StartMonitoringCommand_LogsSuccess_WhenServiceStarts()
|
||||
{
|
||||
var harness = new Harness();
|
||||
var viewModel = harness.CreateViewModel();
|
||||
|
||||
await viewModel.StartMonitoringCommand.ExecuteAsync(null);
|
||||
|
||||
harness.Logging.Verify(
|
||||
logger => logger.LogUserActionAsync(
|
||||
"OptimizationMonitoringStarted",
|
||||
"Performance monitoring started",
|
||||
null),
|
||||
Times.Once);
|
||||
var entry = Assert.Single(
|
||||
await harness.Audit.GetEntriesAsync(),
|
||||
entry => entry.Message == "Performance monitoring started");
|
||||
Assert.Equal("Optimization", entry.Category);
|
||||
Assert.Equal(ActivityAuditSeverity.Success, entry.Severity);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task StartMonitoringCommand_LogsFailure_WhenServiceFails()
|
||||
{
|
||||
var harness = new Harness(startMonitoringThrows: true);
|
||||
var viewModel = harness.CreateViewModel();
|
||||
|
||||
await viewModel.StartMonitoringCommand.ExecuteAsync(null);
|
||||
|
||||
Assert.True(viewModel.HasError);
|
||||
harness.Logging.Verify(
|
||||
logger => logger.LogUserActionAsync(
|
||||
"OptimizationActionFailed",
|
||||
It.Is<string>(details => details.Contains("Failed to start performance monitoring")),
|
||||
null),
|
||||
Times.Once);
|
||||
var entry = Assert.Single(
|
||||
await harness.Audit.GetEntriesAsync(),
|
||||
entry => entry.Message.Contains("Failed to start performance monitoring"));
|
||||
Assert.Equal("Optimization", entry.Category);
|
||||
Assert.Equal(ActivityAuditSeverity.Error, entry.Severity);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task StopMonitoringCommand_StopsServiceAndLogsSuccess()
|
||||
{
|
||||
var harness = new Harness();
|
||||
var viewModel = harness.CreateViewModel();
|
||||
|
||||
await viewModel.StopMonitoringCommand.ExecuteAsync(null);
|
||||
|
||||
harness.Performance.Verify(service => service.StopMonitoringAsync(), Times.Once);
|
||||
harness.Logging.Verify(
|
||||
logger => logger.LogUserActionAsync(
|
||||
"OptimizationMonitoringStopped",
|
||||
"Performance monitoring stopped",
|
||||
null),
|
||||
Times.Once);
|
||||
var entry = Assert.Single(await harness.Audit.GetEntriesAsync());
|
||||
Assert.Equal("Optimization", entry.Category);
|
||||
Assert.Equal(ActivityAuditSeverity.Success, entry.Severity);
|
||||
Assert.Equal("Performance monitoring stopped", viewModel.StatusMessage);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RefreshMetricsCommand_WhenMetricsFails_LogsFailureSafely()
|
||||
{
|
||||
var harness = new Harness(metricsThrows: true);
|
||||
var viewModel = harness.CreateViewModel();
|
||||
|
||||
await viewModel.RefreshMetricsCommand.ExecuteAsync(null);
|
||||
|
||||
Assert.True(viewModel.HasError);
|
||||
harness.Logging.Verify(
|
||||
logger => logger.LogUserActionAsync(
|
||||
"OptimizationActionFailed",
|
||||
It.Is<string>(details => details.Contains("Failed to refresh performance snapshot")),
|
||||
null),
|
||||
Times.Once);
|
||||
var entry = Assert.Single(await harness.Audit.GetEntriesAsync());
|
||||
Assert.Equal("Optimization", entry.Category);
|
||||
Assert.Equal(ActivityAuditSeverity.Error, entry.Severity);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ClearHistoricalDataCommand_ClearsServiceAndLogsSuccess()
|
||||
{
|
||||
var harness = new Harness();
|
||||
var viewModel = harness.CreateViewModel();
|
||||
|
||||
await viewModel.ClearHistoricalDataCommand.ExecuteAsync(null);
|
||||
|
||||
harness.Performance.Verify(service => service.ClearHistoricalDataAsync(), Times.Once);
|
||||
harness.Logging.Verify(
|
||||
logger => logger.LogUserActionAsync(
|
||||
"OptimizationHistoryCleared",
|
||||
"Historical metrics cleared",
|
||||
null),
|
||||
Times.Once);
|
||||
var entry = Assert.Single(await harness.Audit.GetEntriesAsync());
|
||||
Assert.Equal("Optimization", entry.Category);
|
||||
Assert.Equal(ActivityAuditSeverity.Success, entry.Severity);
|
||||
Assert.Equal("Historical data cleared", viewModel.StatusMessage);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ShowAdvancedDiagnostics_DefaultsToHidden()
|
||||
{
|
||||
@@ -76,11 +182,25 @@ namespace ThreadPilot.Core.Tests
|
||||
|
||||
public Mock<ISystemTweaksService> SystemTweaks { get; } = new(MockBehavior.Strict);
|
||||
|
||||
public Harness()
|
||||
public Mock<IEnhancedLoggingService> Logging { get; } = new(MockBehavior.Loose);
|
||||
|
||||
public ActivityAuditService Audit { get; } = new(NullLogger<ActivityAuditService>.Instance);
|
||||
|
||||
public Harness(bool startMonitoringThrows = false, bool metricsThrows = false)
|
||||
{
|
||||
this.Performance
|
||||
.Setup(x => x.GetSystemMetricsAsync(It.IsAny<bool>()))
|
||||
.ReturnsAsync(new SystemPerformanceMetrics());
|
||||
if (metricsThrows)
|
||||
{
|
||||
this.Performance
|
||||
.Setup(x => x.GetSystemMetricsAsync(It.IsAny<bool>()))
|
||||
.ThrowsAsync(new InvalidOperationException("metrics unavailable"));
|
||||
}
|
||||
else
|
||||
{
|
||||
this.Performance
|
||||
.Setup(x => x.GetSystemMetricsAsync(It.IsAny<bool>()))
|
||||
.ReturnsAsync(new SystemPerformanceMetrics());
|
||||
}
|
||||
|
||||
this.Performance
|
||||
.Setup(x => x.GetHistoricalDataAsync(It.IsAny<TimeSpan>()))
|
||||
.ReturnsAsync(new List<SystemPerformanceMetrics>());
|
||||
@@ -90,12 +210,25 @@ namespace ThreadPilot.Core.Tests
|
||||
this.Performance
|
||||
.Setup(x => x.GetTopMemoryProcessesAsync(It.IsAny<int>()))
|
||||
.ReturnsAsync(new List<ProcessPerformanceInfo>());
|
||||
this.Performance
|
||||
.Setup(x => x.StartMonitoringAsync())
|
||||
.Returns(Task.CompletedTask);
|
||||
if (startMonitoringThrows)
|
||||
{
|
||||
this.Performance
|
||||
.Setup(x => x.StartMonitoringAsync())
|
||||
.ThrowsAsync(new InvalidOperationException("monitoring unavailable"));
|
||||
}
|
||||
else
|
||||
{
|
||||
this.Performance
|
||||
.Setup(x => x.StartMonitoringAsync())
|
||||
.Returns(Task.CompletedTask);
|
||||
}
|
||||
|
||||
this.Performance
|
||||
.Setup(x => x.StopMonitoringAsync())
|
||||
.Returns(Task.CompletedTask);
|
||||
this.Performance
|
||||
.Setup(x => x.ClearHistoricalDataAsync())
|
||||
.Returns(Task.CompletedTask);
|
||||
|
||||
this.Associations
|
||||
.Setup(x => x.GetAssociationsAsync())
|
||||
@@ -114,7 +247,9 @@ namespace ThreadPilot.Core.Tests
|
||||
this.PowerPlan.Object,
|
||||
this.ProcessMonitorManager.Object,
|
||||
this.SystemTweaks.Object,
|
||||
NullLogger<PerformanceViewModel>.Instance);
|
||||
NullLogger<PerformanceViewModel>.Instance,
|
||||
this.Logging.Object,
|
||||
this.Audit);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -17,11 +17,16 @@ namespace ThreadPilot.Core.Tests
|
||||
var process = CreateProcess();
|
||||
var rule = CreateRule();
|
||||
var engine = CreateEngine(rule, CreateSuccess(rule, process));
|
||||
var service = CreateService([rule], engine.Object);
|
||||
var audit = new ActivityAuditService(NullLogger<ActivityAuditService>.Instance);
|
||||
var service = CreateService([rule], engine.Object, audit: audit);
|
||||
|
||||
var results = await service.ApplyForProcessStartAsync(process);
|
||||
|
||||
Assert.Single(results);
|
||||
var entry = Assert.Single(await audit.GetEntriesAsync());
|
||||
Assert.Equal("Rules", entry.Category);
|
||||
Assert.Equal(ActivityAuditSeverity.Success, entry.Severity);
|
||||
Assert.Contains("Auto-applied saved rule", entry.Message);
|
||||
engine.Verify(
|
||||
x => x.ApplyMatchingRulesAsync(
|
||||
process,
|
||||
@@ -75,11 +80,13 @@ namespace ThreadPilot.Core.Tests
|
||||
var process = CreateProcess();
|
||||
var rule = CreateRule();
|
||||
var engine = CreateEngine(rule, CreateSuccess(rule, process));
|
||||
var service = CreateService([rule], engine.Object, nowProvider: () => now);
|
||||
var audit = new ActivityAuditService(NullLogger<ActivityAuditService>.Instance);
|
||||
var service = CreateService([rule], engine.Object, nowProvider: () => now, audit: audit);
|
||||
|
||||
await service.ApplyForProcessStartAsync(process);
|
||||
await service.ApplyForProcessStartAsync(process);
|
||||
|
||||
Assert.Single(await audit.GetEntriesAsync());
|
||||
engine.Verify(
|
||||
x => x.ApplyMatchingRulesAsync(
|
||||
process,
|
||||
@@ -136,13 +143,18 @@ namespace ThreadPilot.Core.Tests
|
||||
var rule = CreateRule();
|
||||
var failure = CreateFailure(rule, process, ProcessOperationUserMessages.AccessDenied, isAccessDenied: true);
|
||||
var engine = CreateEngine(rule, failure);
|
||||
var service = CreateService([rule], engine.Object);
|
||||
var audit = new ActivityAuditService(NullLogger<ActivityAuditService>.Instance);
|
||||
var service = CreateService([rule], engine.Object, audit: audit);
|
||||
|
||||
var result = Assert.Single(await service.ApplyForProcessStartAsync(process));
|
||||
|
||||
Assert.False(result.Success);
|
||||
Assert.True(result.IsAccessDenied);
|
||||
Assert.Equal(ProcessOperationUserMessages.AccessDenied, result.UserMessage);
|
||||
var entry = Assert.Single(await audit.GetEntriesAsync());
|
||||
Assert.Equal("Rules", entry.Category);
|
||||
Assert.Equal(ActivityAuditSeverity.Warning, entry.Severity);
|
||||
Assert.Contains("Failed to auto-apply saved rule", entry.Message);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -194,6 +206,51 @@ namespace ThreadPilot.Core.Tests
|
||||
service.ApplyForProcessStartAsync(process));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ApplyForProcessStartAsync_FeatureFlagDisabled_DoesNotCallRulesEngine()
|
||||
{
|
||||
var process = CreateProcess();
|
||||
var rule = CreateRule();
|
||||
var engine = CreateEngine(rule, CreateSuccess(rule, process));
|
||||
var service = CreateService(
|
||||
[rule],
|
||||
engine.Object,
|
||||
settings: new ApplicationSettingsModel { ApplyPersistentRulesOnProcessStart = false });
|
||||
|
||||
var results = await service.ApplyForProcessStartAsync(process);
|
||||
|
||||
Assert.Empty(results);
|
||||
engine.Verify(
|
||||
x => x.ApplyMatchingRulesAsync(
|
||||
It.IsAny<ProcessModel>(),
|
||||
It.IsAny<Predicate<PersistentProcessRule>?>(),
|
||||
It.IsAny<CancellationToken>()),
|
||||
Times.Never);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(0, "game.exe")]
|
||||
[InlineData(42, "")]
|
||||
[InlineData(42, " ")]
|
||||
public async Task ApplyForProcessStartAsync_WithInvalidProcess_DoesNotCallRulesEngine(int processId, string processName)
|
||||
{
|
||||
var process = CreateProcess(processName);
|
||||
process.ProcessId = processId;
|
||||
var rule = CreateRule();
|
||||
var engine = CreateEngine(rule, CreateSuccess(rule, process));
|
||||
var service = CreateService([rule], engine.Object);
|
||||
|
||||
var results = await service.ApplyForProcessStartAsync(process);
|
||||
|
||||
Assert.Empty(results);
|
||||
engine.Verify(
|
||||
x => x.ApplyMatchingRulesAsync(
|
||||
It.IsAny<ProcessModel>(),
|
||||
It.IsAny<Predicate<PersistentProcessRule>?>(),
|
||||
It.IsAny<CancellationToken>()),
|
||||
Times.Never);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ApplyForDiscoveredProcessesAsync_FeatureFlagDisabled_DoesNotCallRulesEngine()
|
||||
{
|
||||
@@ -216,6 +273,26 @@ namespace ThreadPilot.Core.Tests
|
||||
Times.Never);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ApplyForDiscoveredProcessesAsync_GroupsDuplicateProcessesByProcessId()
|
||||
{
|
||||
var process = CreateProcess();
|
||||
var duplicate = CreateProcess("game.exe");
|
||||
duplicate.ExecutablePath = @"C:\Games\GameCopy.exe";
|
||||
var rule = CreateRule();
|
||||
var engine = CreateEngine(rule, CreateSuccess(rule, process));
|
||||
var service = CreateService([rule], engine.Object);
|
||||
|
||||
await service.ApplyForDiscoveredProcessesAsync([process, duplicate]);
|
||||
|
||||
engine.Verify(
|
||||
x => x.ApplyMatchingRulesAsync(
|
||||
It.IsAny<ProcessModel>(),
|
||||
It.IsAny<Predicate<PersistentProcessRule>?>(),
|
||||
It.IsAny<CancellationToken>()),
|
||||
Times.Once);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ApplyForDiscoveredProcessesAsync_ClearsCooldownForProcessesNoLongerPresent()
|
||||
{
|
||||
@@ -236,11 +313,80 @@ namespace ThreadPilot.Core.Tests
|
||||
Times.Exactly(2));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ApplyForProcessStartAsync_WhenRuleUpdatedDuringCooldown_AllowsReapply()
|
||||
{
|
||||
var process = CreateProcess();
|
||||
var rule = CreateRule();
|
||||
var rules = new List<PersistentProcessRule> { rule };
|
||||
var engine = CreateEngine(rule, CreateSuccess(rule, process));
|
||||
var service = CreateService(rules, engine.Object);
|
||||
|
||||
await service.ApplyForProcessStartAsync(process);
|
||||
rules[0] = rule with { UpdatedAt = rule.UpdatedAt.AddSeconds(1) };
|
||||
await service.ApplyForProcessStartAsync(process);
|
||||
|
||||
engine.Verify(
|
||||
x => x.ApplyMatchingRulesAsync(
|
||||
process,
|
||||
It.IsAny<Predicate<PersistentProcessRule>?>(),
|
||||
It.IsAny<CancellationToken>()),
|
||||
Times.Exactly(2));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ApplyForProcessStartAsync_WhenRulesEngineThrows_ReturnsControlledFailure()
|
||||
{
|
||||
var process = CreateProcess();
|
||||
var rule = CreateRule();
|
||||
var engine = CreateEngineThatThrows(new InvalidOperationException("native apply failed"));
|
||||
var service = CreateService([rule], engine.Object);
|
||||
|
||||
var result = Assert.Single(await service.ApplyForProcessStartAsync(process));
|
||||
|
||||
Assert.False(result.Success);
|
||||
Assert.Equal(rule.Id, result.RuleId);
|
||||
Assert.Equal(process.ProcessId, result.ProcessId);
|
||||
Assert.Equal("ThreadPilot could not apply the saved rule.", result.UserMessage);
|
||||
Assert.Equal("native apply failed", result.TechnicalMessage);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task MarkProcessExited_RemovesOnlyMatchingProcessAttempts()
|
||||
{
|
||||
var process = CreateProcess();
|
||||
var otherProcess = CreateProcess("game.exe");
|
||||
otherProcess.ProcessId = 84;
|
||||
var rule = CreateRule();
|
||||
var engine = CreateEngine(rule, CreateSuccess(rule, process));
|
||||
var service = CreateService([rule], engine.Object);
|
||||
|
||||
await service.ApplyForProcessStartAsync(process);
|
||||
await service.ApplyForProcessStartAsync(otherProcess);
|
||||
service.MarkProcessExited(process.ProcessId);
|
||||
await service.ApplyForProcessStartAsync(process);
|
||||
await service.ApplyForProcessStartAsync(otherProcess);
|
||||
|
||||
engine.Verify(
|
||||
x => x.ApplyMatchingRulesAsync(
|
||||
process,
|
||||
It.IsAny<Predicate<PersistentProcessRule>?>(),
|
||||
It.IsAny<CancellationToken>()),
|
||||
Times.Exactly(2));
|
||||
engine.Verify(
|
||||
x => x.ApplyMatchingRulesAsync(
|
||||
otherProcess,
|
||||
It.IsAny<Predicate<PersistentProcessRule>?>(),
|
||||
It.IsAny<CancellationToken>()),
|
||||
Times.Once);
|
||||
}
|
||||
|
||||
private static PersistentRuleAutoApplyService CreateService(
|
||||
IReadOnlyList<PersistentProcessRule> rules,
|
||||
IPersistentRulesEngine engine,
|
||||
ApplicationSettingsModel? settings = null,
|
||||
Func<DateTimeOffset>? nowProvider = null) =>
|
||||
Func<DateTimeOffset>? nowProvider = null,
|
||||
IActivityAuditService? audit = null) =>
|
||||
new(
|
||||
new FakePersistentProcessRuleStore(rules),
|
||||
new PersistentProcessRuleMatcher(),
|
||||
@@ -248,7 +394,8 @@ namespace ThreadPilot.Core.Tests
|
||||
CreateSettingsService(settings ?? new ApplicationSettingsModel()),
|
||||
NullLogger<PersistentRuleAutoApplyService>.Instance,
|
||||
nowProvider ?? (() => DateTimeOffset.UtcNow),
|
||||
TimeSpan.FromSeconds(30));
|
||||
TimeSpan.FromSeconds(30),
|
||||
audit);
|
||||
|
||||
private static Mock<IPersistentRulesEngine> CreateEngine(
|
||||
PersistentProcessRule rule,
|
||||
@@ -279,6 +426,18 @@ namespace ThreadPilot.Core.Tests
|
||||
return engine;
|
||||
}
|
||||
|
||||
private static Mock<IPersistentRulesEngine> CreateEngineThatThrows(Exception exception)
|
||||
{
|
||||
var engine = new Mock<IPersistentRulesEngine>(MockBehavior.Strict);
|
||||
engine
|
||||
.Setup(x => x.ApplyMatchingRulesAsync(
|
||||
It.IsAny<ProcessModel>(),
|
||||
It.IsAny<Predicate<PersistentProcessRule>?>(),
|
||||
It.IsAny<CancellationToken>()))
|
||||
.ThrowsAsync(exception);
|
||||
return engine;
|
||||
}
|
||||
|
||||
private static IApplicationSettingsService CreateSettingsService(ApplicationSettingsModel settings)
|
||||
{
|
||||
var settingsService = new Mock<IApplicationSettingsService>(MockBehavior.Loose);
|
||||
|
||||
@@ -337,6 +337,50 @@ namespace ThreadPilot.Core.Tests
|
||||
processService.Verify(s => s.SetProcessPriority(It.IsAny<ProcessModel>(), It.IsAny<ProcessPriorityClass>()), Times.Once);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ApplyMatchingRulesAsync_WhenRuleFilterExcludesMatchingRule_DoesNotApplyIt()
|
||||
{
|
||||
var rules = new[]
|
||||
{
|
||||
CreateRule(id: "rule-a", legacyAffinityMask: 1, applyAffinity: true),
|
||||
CreateRule(id: "rule-b", legacyAffinityMask: 2, applyAffinity: true),
|
||||
};
|
||||
var affinity = CreateAffinityService();
|
||||
var processService = CreateProcessService();
|
||||
var engine = CreateEngine(rules, affinity.Object, processService.Object, CreateMemoryPriorityService().Object);
|
||||
|
||||
var results = await engine.ApplyMatchingRulesAsync(
|
||||
CreateProcess(),
|
||||
rule => rule.Id != "rule-a");
|
||||
|
||||
var result = Assert.Single(results);
|
||||
Assert.Equal("rule-b", result.RuleId);
|
||||
affinity.Verify(s => s.ApplyAsync(It.IsAny<ProcessModel>(), 1L), Times.Never);
|
||||
affinity.Verify(s => s.ApplyAsync(It.IsAny<ProcessModel>(), 2L), Times.Once);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ApplyMatchingRulesAsync_WhenRuleFilterIncludesSelectedRule_AppliesOnlyThatRule()
|
||||
{
|
||||
var rules = new[]
|
||||
{
|
||||
CreateRule(id: "rule-a", priority: ProcessPriorityClass.AboveNormal, applyPriority: true),
|
||||
CreateRule(id: "rule-b", priority: ProcessPriorityClass.High, applyPriority: true),
|
||||
};
|
||||
var affinity = CreateAffinityService();
|
||||
var processService = CreateProcessService();
|
||||
var engine = CreateEngine(rules, affinity.Object, processService.Object, CreateMemoryPriorityService().Object);
|
||||
|
||||
var results = await engine.ApplyMatchingRulesAsync(
|
||||
CreateProcess(),
|
||||
rule => rule.Id == "rule-b");
|
||||
|
||||
var result = Assert.Single(results);
|
||||
Assert.Equal("rule-b", result.RuleId);
|
||||
processService.Verify(s => s.SetProcessPriority(It.IsAny<ProcessModel>(), ProcessPriorityClass.AboveNormal), Times.Never);
|
||||
processService.Verify(s => s.SetProcessPriority(It.IsAny<ProcessModel>(), ProcessPriorityClass.High), Times.Once);
|
||||
}
|
||||
|
||||
private static PersistentRulesEngine CreateEngine(
|
||||
IReadOnlyList<PersistentProcessRule> rules,
|
||||
IAffinityApplyService affinityApplyService,
|
||||
|
||||
@@ -56,6 +56,50 @@ namespace ThreadPilot.Core.Tests
|
||||
Assert.Equal(new[] { "/getactivescheme" }, invocation.Arguments);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeletePowerPlanAsync_InvokesPowerCfgDelete_WhenPlanIsNotActive()
|
||||
{
|
||||
const string activeGuid = "381b4222-f694-41f0-9685-ff5bb260df2e";
|
||||
const string deleteGuid = "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee";
|
||||
var runner = new RecordingProcessRunner
|
||||
{
|
||||
ResultFactory = invocation =>
|
||||
invocation.Arguments.SequenceEqual(new[] { "/getactivescheme" })
|
||||
? new ProcessRunResult(
|
||||
0,
|
||||
$"Power Scheme GUID: {activeGuid} (Balanced)",
|
||||
string.Empty)
|
||||
: new ProcessRunResult(0, string.Empty, string.Empty),
|
||||
};
|
||||
var service = CreateService(runner);
|
||||
|
||||
var result = await service.DeletePowerPlanAsync(deleteGuid);
|
||||
|
||||
Assert.True(result);
|
||||
Assert.Contains(runner.Invocations, invocation =>
|
||||
invocation.Arguments.SequenceEqual(new[] { "/delete", deleteGuid }));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeletePowerPlanAsync_DoesNotDeleteActivePlan()
|
||||
{
|
||||
const string activeGuid = "381b4222-f694-41f0-9685-ff5bb260df2e";
|
||||
var runner = new RecordingProcessRunner
|
||||
{
|
||||
ResultFactory = _ => new ProcessRunResult(
|
||||
0,
|
||||
$"Power Scheme GUID: {activeGuid} (Balanced)",
|
||||
string.Empty),
|
||||
};
|
||||
var service = CreateService(runner);
|
||||
|
||||
var result = await service.DeletePowerPlanAsync(activeGuid);
|
||||
|
||||
Assert.False(result);
|
||||
Assert.DoesNotContain(runner.Invocations, invocation =>
|
||||
invocation.Arguments.Contains("/delete", StringComparer.OrdinalIgnoreCase));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AddCustomPowerPlanFileAsync_RenamesOnCollision()
|
||||
{
|
||||
|
||||
@@ -0,0 +1,152 @@
|
||||
namespace ThreadPilot.Core.Tests
|
||||
{
|
||||
using System.Collections.ObjectModel;
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
using Moq;
|
||||
using ThreadPilot.Models;
|
||||
using ThreadPilot.Services;
|
||||
using ThreadPilot.ViewModels;
|
||||
|
||||
public sealed class PowerPlanViewModelTests
|
||||
{
|
||||
[Fact]
|
||||
public async Task DeletePowerPlanCommand_CallsServiceRefreshesAndLogs_WhenPlanIsNotActive()
|
||||
{
|
||||
var harness = new Harness();
|
||||
var deletePlan = new PowerPlanModel { Guid = Harness.DeleteGuid, Name = "Gaming" };
|
||||
var viewModel = harness.CreateViewModel();
|
||||
|
||||
await viewModel.DeletePowerPlanCommand.ExecuteAsync(deletePlan);
|
||||
|
||||
harness.PowerPlan.Verify(service => service.DeletePowerPlanAsync(Harness.DeleteGuid), Times.Once);
|
||||
harness.PowerPlan.Verify(service => service.GetPowerPlansAsync(), Times.Once);
|
||||
harness.Logging.Verify(
|
||||
logger => logger.LogUserActionAsync(
|
||||
"PowerPlanDeleted",
|
||||
"Deleted power plan Gaming",
|
||||
$"Guid: {Harness.DeleteGuid}"),
|
||||
Times.Once);
|
||||
var entry = Assert.Single(await harness.Audit.GetEntriesAsync());
|
||||
Assert.Equal("Power Plans", entry.Category);
|
||||
Assert.Equal(ActivityAuditSeverity.Success, entry.Severity);
|
||||
Assert.Equal("Deleted power plan Gaming", entry.Message);
|
||||
Assert.Equal("Power plan deleted: Gaming.", viewModel.StatusMessage);
|
||||
Assert.False(viewModel.HasError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeletePowerPlanCommand_BlocksActivePlanBeforeCallingService()
|
||||
{
|
||||
var harness = new Harness();
|
||||
var activePlan = new PowerPlanModel { Guid = Harness.ActiveGuid, Name = "Balanced", IsActive = true };
|
||||
var viewModel = harness.CreateViewModel();
|
||||
|
||||
await viewModel.DeletePowerPlanCommand.ExecuteAsync(activePlan);
|
||||
|
||||
harness.PowerPlan.Verify(service => service.DeletePowerPlanAsync(It.IsAny<string>()), Times.Never);
|
||||
Assert.Equal("Switch to another power plan before deleting the active plan.", viewModel.StatusMessage);
|
||||
Assert.True(viewModel.HasError);
|
||||
var entry = Assert.Single(await harness.Audit.GetEntriesAsync());
|
||||
Assert.Equal("Power Plans", entry.Category);
|
||||
Assert.Equal(ActivityAuditSeverity.Warning, entry.Severity);
|
||||
Assert.Contains("Switch to another power plan", entry.Message);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeletePowerPlanCommand_ShowsFailureAndDoesNotCrash_WhenServiceFails()
|
||||
{
|
||||
var harness = new Harness(deleteSucceeds: false);
|
||||
var deletePlan = new PowerPlanModel { Guid = Harness.DeleteGuid, Name = "Gaming" };
|
||||
var viewModel = harness.CreateViewModel();
|
||||
|
||||
await viewModel.DeletePowerPlanCommand.ExecuteAsync(deletePlan);
|
||||
|
||||
Assert.Equal("Could not delete power plan Gaming. Windows may not allow this plan to be removed.", viewModel.StatusMessage);
|
||||
Assert.True(viewModel.HasError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SetActivePlanCommand_ShowsSuccessStatusAndLogs()
|
||||
{
|
||||
var harness = new Harness();
|
||||
var viewModel = harness.CreateViewModel();
|
||||
viewModel.SelectedPowerPlan = new PowerPlanModel { Guid = Harness.DeleteGuid, Name = "Gaming" };
|
||||
|
||||
await viewModel.SetActivePlanCommand.ExecuteAsync(null);
|
||||
|
||||
Assert.Equal("Power plan applied: Gaming.", viewModel.StatusMessage);
|
||||
harness.Logging.Verify(
|
||||
logger => logger.LogUserActionAsync(
|
||||
"PowerPlanApplied",
|
||||
"Applied power plan Gaming",
|
||||
$"Guid: {Harness.DeleteGuid}"),
|
||||
Times.Once);
|
||||
var entry = Assert.Single(await harness.Audit.GetEntriesAsync());
|
||||
Assert.Equal("Power Plans", entry.Category);
|
||||
Assert.Equal(ActivityAuditSeverity.Success, entry.Severity);
|
||||
Assert.Equal("Applied power plan Gaming", entry.Message);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RefreshPowerPlansCommand_ShowsCompletionStatusAndLogs()
|
||||
{
|
||||
var harness = new Harness();
|
||||
var viewModel = harness.CreateViewModel();
|
||||
|
||||
await viewModel.RefreshPowerPlansCommand.ExecuteAsync(null);
|
||||
|
||||
Assert.Equal("Power plans refreshed.", viewModel.StatusMessage);
|
||||
harness.Logging.Verify(
|
||||
logger => logger.LogUserActionAsync(
|
||||
"PowerPlansRefreshed",
|
||||
"Refreshed power plan list",
|
||||
null),
|
||||
Times.Once);
|
||||
var entry = Assert.Single(await harness.Audit.GetEntriesAsync());
|
||||
Assert.Equal("Power Plans", entry.Category);
|
||||
Assert.Equal(ActivityAuditSeverity.Success, entry.Severity);
|
||||
Assert.Equal("Refreshed power plan list", entry.Message);
|
||||
}
|
||||
|
||||
private sealed class Harness
|
||||
{
|
||||
public const string ActiveGuid = "381b4222-f694-41f0-9685-ff5bb260df2e";
|
||||
public const string DeleteGuid = "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee";
|
||||
|
||||
public Mock<IPowerPlanService> PowerPlan { get; } = new(MockBehavior.Strict);
|
||||
|
||||
public Mock<IEnhancedLoggingService> Logging { get; } = new(MockBehavior.Loose);
|
||||
|
||||
public ActivityAuditService Audit { get; } = new(NullLogger<ActivityAuditService>.Instance);
|
||||
|
||||
public Harness(bool deleteSucceeds = true)
|
||||
{
|
||||
var active = new PowerPlanModel { Guid = ActiveGuid, Name = "Balanced", IsActive = true };
|
||||
var delete = new PowerPlanModel { Guid = DeleteGuid, Name = "Gaming" };
|
||||
|
||||
this.PowerPlan
|
||||
.Setup(service => service.GetPowerPlansAsync())
|
||||
.ReturnsAsync(new ObservableCollection<PowerPlanModel> { active, delete });
|
||||
this.PowerPlan
|
||||
.Setup(service => service.GetCustomPowerPlansAsync())
|
||||
.ReturnsAsync(new ObservableCollection<PowerPlanModel>());
|
||||
this.PowerPlan
|
||||
.Setup(service => service.GetActivePowerPlan())
|
||||
.ReturnsAsync(active);
|
||||
this.PowerPlan
|
||||
.Setup(service => service.SetActivePowerPlan(It.IsAny<PowerPlanModel>()))
|
||||
.ReturnsAsync(true);
|
||||
this.PowerPlan
|
||||
.Setup(service => service.DeletePowerPlanAsync(DeleteGuid))
|
||||
.ReturnsAsync(deleteSucceeds);
|
||||
}
|
||||
|
||||
public PowerPlanViewModel CreateViewModel() =>
|
||||
new(
|
||||
NullLogger<PowerPlanViewModel>.Instance,
|
||||
this.PowerPlan.Object,
|
||||
this.Logging.Object,
|
||||
this.Audit);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
namespace ThreadPilot.Core.Tests
|
||||
{
|
||||
using System.Xml.Linq;
|
||||
|
||||
public sealed class PowerPlanViewXamlTests
|
||||
{
|
||||
private static readonly string PowerPlanViewPath = Path.Combine(
|
||||
AppContext.BaseDirectory,
|
||||
"..",
|
||||
"..",
|
||||
"..",
|
||||
"..",
|
||||
"..",
|
||||
"Views",
|
||||
"PowerPlanView.xaml");
|
||||
|
||||
[Fact]
|
||||
public void PowerPlanItems_ExposeDeleteContextMenu()
|
||||
{
|
||||
var document = XDocument.Load(PowerPlanViewPath, LoadOptions.PreserveWhitespace);
|
||||
var deleteCommandBinding = document
|
||||
.Descendants()
|
||||
.SelectMany(element => element.Attributes())
|
||||
.SingleOrDefault(attribute => attribute.Value.Contains("DeletePowerPlanCommand", StringComparison.Ordinal));
|
||||
|
||||
Assert.NotNull(deleteCommandBinding);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void HeaderInstructionText_WrapsToAvoidButtonOverlap()
|
||||
{
|
||||
var document = XDocument.Load(PowerPlanViewPath, LoadOptions.PreserveWhitespace);
|
||||
var instructionTextBlocks = document
|
||||
.Descendants()
|
||||
.Where(element => element.Name.LocalName == "TextBlock")
|
||||
.Where(element => element.Attributes().Any(attribute =>
|
||||
attribute.Value.Contains("Select the Windows plan", StringComparison.Ordinal) ||
|
||||
attribute.Value.Contains("Local .pow files", StringComparison.Ordinal)))
|
||||
.ToList();
|
||||
|
||||
Assert.Equal(2, instructionTextBlocks.Count);
|
||||
Assert.All(instructionTextBlocks, textBlock =>
|
||||
Assert.Contains(textBlock.Attributes(), attribute =>
|
||||
attribute.Name.LocalName == "TextWrapping" && attribute.Value == "Wrap"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ActivePowerPlanTemplate_ContainsActiveBadgeAndAccentBorder()
|
||||
{
|
||||
var document = XDocument.Load(PowerPlanViewPath, LoadOptions.PreserveWhitespace);
|
||||
var serialized = document.ToString(SaveOptions.DisableFormatting);
|
||||
|
||||
Assert.Contains("Active", serialized, StringComparison.Ordinal);
|
||||
Assert.Contains("IsActive", serialized, StringComparison.Ordinal);
|
||||
Assert.Contains("Accent", serialized, StringComparison.Ordinal);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -430,6 +430,195 @@ namespace ThreadPilot.Core.Tests
|
||||
Assert.Empty(logger.WarningMessages);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task EvaluateCurrentProcessesAsync_WhenPersistentRuleAutoApplyThrows_LogsWarningWithoutBreakingRefresh()
|
||||
{
|
||||
var processMonitor = new FakeProcessMonitorService
|
||||
{
|
||||
RunningProcesses =
|
||||
{
|
||||
new ProcessModel { ProcessId = 44, Name = "game.exe" },
|
||||
},
|
||||
};
|
||||
var configuration = new ProcessMonitorConfiguration();
|
||||
var associationService = CreateAssociationService(configuration);
|
||||
var powerPlanService = CreatePowerPlanService();
|
||||
var notificationService = CreateNotificationService();
|
||||
var processService = CreateProcessService();
|
||||
var coreMaskService = CreateCoreMaskService();
|
||||
var affinityApplyService = CreateAffinityApplyService();
|
||||
var autoApplyService = CreateAutoApplyService();
|
||||
autoApplyService
|
||||
.Setup(x => x.ApplyForDiscoveredProcessesAsync(
|
||||
It.IsAny<IEnumerable<ProcessModel>>(),
|
||||
It.IsAny<CancellationToken>()))
|
||||
.ThrowsAsync(new InvalidOperationException("auto apply failed"));
|
||||
var logger = new CapturingLogger<ProcessMonitorManagerService>();
|
||||
var manager = CreateService(
|
||||
processMonitor,
|
||||
associationService,
|
||||
powerPlanService,
|
||||
notificationService,
|
||||
processService,
|
||||
coreMaskService,
|
||||
affinityApplyService,
|
||||
autoApplyService,
|
||||
logger);
|
||||
|
||||
await manager.StartAsync();
|
||||
await manager.EvaluateCurrentProcessesAsync();
|
||||
|
||||
Assert.Contains(
|
||||
logger.WarningMessages,
|
||||
message => message.Contains("snapshot refresh", StringComparison.OrdinalIgnoreCase));
|
||||
Assert.True(manager.IsRunning);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ProcessStarted_WhenPersistentRuleAutoApplyThrows_LogsWarningWithoutBreakingStartHandling()
|
||||
{
|
||||
var process = new ProcessModel { ProcessId = 45, Name = "game.exe" };
|
||||
var processMonitor = new FakeProcessMonitorService();
|
||||
var configuration = new ProcessMonitorConfiguration();
|
||||
var associationService = CreateAssociationService(configuration);
|
||||
var powerPlanService = CreatePowerPlanService();
|
||||
var notificationService = CreateNotificationService();
|
||||
var processService = CreateProcessService();
|
||||
var coreMaskService = CreateCoreMaskService();
|
||||
var affinityApplyService = CreateAffinityApplyService();
|
||||
var autoApplyService = CreateAutoApplyService();
|
||||
autoApplyService
|
||||
.Setup(x => x.ApplyForProcessStartAsync(
|
||||
process,
|
||||
It.IsAny<CancellationToken>()))
|
||||
.ThrowsAsync(new InvalidOperationException("auto apply failed"));
|
||||
var logger = new CapturingLogger<ProcessMonitorManagerService>();
|
||||
var manager = CreateService(
|
||||
processMonitor,
|
||||
associationService,
|
||||
powerPlanService,
|
||||
notificationService,
|
||||
processService,
|
||||
coreMaskService,
|
||||
affinityApplyService,
|
||||
autoApplyService,
|
||||
logger);
|
||||
|
||||
await manager.StartAsync();
|
||||
processMonitor.RaiseProcessStarted(process);
|
||||
await Task.Delay(100);
|
||||
|
||||
Assert.Contains(
|
||||
logger.WarningMessages,
|
||||
message => message.Contains("Persistent rule auto-apply failed", StringComparison.OrdinalIgnoreCase));
|
||||
Assert.True(manager.IsRunning);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ProcessStarted_WhenPersistentRuleAutoApplySucceeds_LogsEnhancedMonitoringEvent()
|
||||
{
|
||||
var process = new ProcessModel { ProcessId = 46, Name = "game.exe" };
|
||||
var processMonitor = new FakeProcessMonitorService();
|
||||
var configuration = new ProcessMonitorConfiguration();
|
||||
var associationService = CreateAssociationService(configuration);
|
||||
var powerPlanService = CreatePowerPlanService();
|
||||
var notificationService = CreateNotificationService();
|
||||
var processService = CreateProcessService();
|
||||
var coreMaskService = CreateCoreMaskService();
|
||||
var affinityApplyService = CreateAffinityApplyService();
|
||||
var autoApplyService = CreateAutoApplyService();
|
||||
autoApplyService
|
||||
.Setup(x => x.ApplyForProcessStartAsync(
|
||||
process,
|
||||
It.IsAny<CancellationToken>()))
|
||||
.ReturnsAsync(new[]
|
||||
{
|
||||
new PersistentRuleAutoApplyResult
|
||||
{
|
||||
Success = true,
|
||||
RuleId = "rule-game",
|
||||
ProcessId = process.ProcessId,
|
||||
ProcessName = process.Name,
|
||||
UserMessage = "Persistent rule applied.",
|
||||
},
|
||||
});
|
||||
var enhancedLogger = CreateEnhancedLogger();
|
||||
var manager = CreateService(
|
||||
processMonitor,
|
||||
associationService,
|
||||
powerPlanService,
|
||||
notificationService,
|
||||
processService,
|
||||
coreMaskService,
|
||||
affinityApplyService,
|
||||
autoApplyService,
|
||||
enhancedLogger: enhancedLogger);
|
||||
|
||||
await manager.StartAsync();
|
||||
processMonitor.RaiseProcessStarted(process);
|
||||
await Task.Delay(100);
|
||||
|
||||
enhancedLogger.Verify(
|
||||
x => x.LogProcessMonitoringEventAsync(
|
||||
LogEventTypes.ProcessMonitoring.AssociationTriggered,
|
||||
process.Name,
|
||||
process.ProcessId,
|
||||
It.Is<string>(message => message.Contains("Persistent rule 'rule-game' applied automatically", StringComparison.Ordinal))),
|
||||
Times.Once);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ProcessStarted_WhenPersistentRuleAutoApplyReturnsFailure_DoesNotNotifyOrThrow()
|
||||
{
|
||||
var process = new ProcessModel { ProcessId = 47, Name = "game.exe" };
|
||||
var processMonitor = new FakeProcessMonitorService();
|
||||
var configuration = new ProcessMonitorConfiguration();
|
||||
var associationService = CreateAssociationService(configuration);
|
||||
var powerPlanService = CreatePowerPlanService();
|
||||
var notificationService = CreateNotificationService();
|
||||
var processService = CreateProcessService();
|
||||
var coreMaskService = CreateCoreMaskService();
|
||||
var affinityApplyService = CreateAffinityApplyService();
|
||||
var autoApplyService = CreateAutoApplyService();
|
||||
autoApplyService
|
||||
.Setup(x => x.ApplyForProcessStartAsync(
|
||||
process,
|
||||
It.IsAny<CancellationToken>()))
|
||||
.ReturnsAsync(new[]
|
||||
{
|
||||
new PersistentRuleAutoApplyResult
|
||||
{
|
||||
Success = false,
|
||||
RuleId = "rule-game",
|
||||
ProcessId = process.ProcessId,
|
||||
ProcessName = process.Name,
|
||||
UserMessage = ProcessOperationUserMessages.AccessDenied,
|
||||
IsAccessDenied = true,
|
||||
},
|
||||
});
|
||||
var manager = CreateService(
|
||||
processMonitor,
|
||||
associationService,
|
||||
powerPlanService,
|
||||
notificationService,
|
||||
processService,
|
||||
coreMaskService,
|
||||
affinityApplyService,
|
||||
autoApplyService);
|
||||
|
||||
await manager.StartAsync();
|
||||
processMonitor.RaiseProcessStarted(process);
|
||||
await Task.Delay(100);
|
||||
|
||||
Assert.True(manager.IsRunning);
|
||||
notificationService.Verify(
|
||||
x => x.ShowNotificationAsync(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<NotificationType>()),
|
||||
Times.Never);
|
||||
notificationService.Verify(
|
||||
x => x.ShowErrorNotificationAsync(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<Exception?>()),
|
||||
Times.Never);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Dispose_CompletesOnBlockingSynchronizationContext()
|
||||
{
|
||||
@@ -496,18 +685,10 @@ namespace ThreadPilot.Core.Tests
|
||||
Mock<ICoreMaskService> coreMaskService,
|
||||
Mock<IAffinityApplyService> affinityApplyService,
|
||||
Mock<IPersistentRuleAutoApplyService>? autoApplyService = null,
|
||||
ILogger<ProcessMonitorManagerService>? logger = null)
|
||||
ILogger<ProcessMonitorManagerService>? logger = null,
|
||||
Mock<IEnhancedLoggingService>? enhancedLogger = null)
|
||||
{
|
||||
var enhancedLogger = new Mock<IEnhancedLoggingService>(MockBehavior.Loose);
|
||||
enhancedLogger
|
||||
.Setup(x => x.LogSystemEventAsync(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<Microsoft.Extensions.Logging.LogLevel>()))
|
||||
.Returns(Task.CompletedTask);
|
||||
enhancedLogger
|
||||
.Setup(x => x.LogProcessMonitoringEventAsync(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<int>(), It.IsAny<string>()))
|
||||
.Returns(Task.CompletedTask);
|
||||
enhancedLogger
|
||||
.Setup(x => x.LogErrorAsync(It.IsAny<Exception>(), It.IsAny<string>(), It.IsAny<Dictionary<string, object>?>()))
|
||||
.Returns(Task.CompletedTask);
|
||||
var resolvedEnhancedLogger = enhancedLogger ?? CreateEnhancedLogger();
|
||||
|
||||
var settingsService = new Mock<IApplicationSettingsService>(MockBehavior.Loose);
|
||||
settingsService.SetupGet(x => x.Settings).Returns(new ApplicationSettingsModel());
|
||||
@@ -524,7 +705,22 @@ namespace ThreadPilot.Core.Tests
|
||||
(autoApplyService ?? CreateAutoApplyService()).Object,
|
||||
new PowerPlanTransitionGate(TimeSpan.FromSeconds(2), () => DateTimeOffset.UtcNow),
|
||||
logger ?? NullLogger<ProcessMonitorManagerService>.Instance,
|
||||
enhancedLogger.Object);
|
||||
resolvedEnhancedLogger.Object);
|
||||
}
|
||||
|
||||
private static Mock<IEnhancedLoggingService> CreateEnhancedLogger()
|
||||
{
|
||||
var enhancedLogger = new Mock<IEnhancedLoggingService>(MockBehavior.Loose);
|
||||
enhancedLogger
|
||||
.Setup(x => x.LogSystemEventAsync(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<Microsoft.Extensions.Logging.LogLevel>()))
|
||||
.Returns(Task.CompletedTask);
|
||||
enhancedLogger
|
||||
.Setup(x => x.LogProcessMonitoringEventAsync(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<int>(), It.IsAny<string>()))
|
||||
.Returns(Task.CompletedTask);
|
||||
enhancedLogger
|
||||
.Setup(x => x.LogErrorAsync(It.IsAny<Exception>(), It.IsAny<string>(), It.IsAny<Dictionary<string, object>?>()))
|
||||
.Returns(Task.CompletedTask);
|
||||
return enhancedLogger;
|
||||
}
|
||||
|
||||
private static Mock<IProcessPowerPlanAssociationService> CreateAssociationService(ProcessMonitorConfiguration configuration)
|
||||
@@ -604,9 +800,17 @@ namespace ThreadPilot.Core.Tests
|
||||
{
|
||||
public event EventHandler<ProcessEventArgs>? ProcessStarted;
|
||||
|
||||
public event EventHandler<ProcessEventArgs>? ProcessStopped;
|
||||
public event EventHandler<ProcessEventArgs>? ProcessStopped
|
||||
{
|
||||
add { }
|
||||
remove { }
|
||||
}
|
||||
|
||||
public event EventHandler<MonitoringStatusEventArgs>? MonitoringStatusChanged;
|
||||
public event EventHandler<MonitoringStatusEventArgs>? MonitoringStatusChanged
|
||||
{
|
||||
add { }
|
||||
remove { }
|
||||
}
|
||||
|
||||
public List<ProcessModel> RunningProcesses { get; } = new();
|
||||
|
||||
|
||||
@@ -14,7 +14,12 @@ namespace ThreadPilot.Core.Tests
|
||||
public async Task ContextCpuPriorityCommand_CallsSafePriorityServicePath()
|
||||
{
|
||||
var processService = CreateProcessService();
|
||||
var viewModel = CreateViewModel(processService.Object);
|
||||
var enhancedLoggingService = new Mock<IEnhancedLoggingService>(MockBehavior.Loose);
|
||||
var audit = new ActivityAuditService(NullLogger<ActivityAuditService>.Instance);
|
||||
var viewModel = CreateViewModel(
|
||||
processService.Object,
|
||||
enhancedLoggingService: enhancedLoggingService.Object,
|
||||
activityAuditService: audit);
|
||||
var process = CreateProcess(priority: ProcessPriorityClass.Normal);
|
||||
|
||||
await viewModel.SetContextHighPriorityCommand.ExecuteAsync(process);
|
||||
@@ -22,8 +27,18 @@ namespace ThreadPilot.Core.Tests
|
||||
processService.Verify(
|
||||
service => service.SetProcessPriority(process, ProcessPriorityClass.High),
|
||||
Times.Once);
|
||||
enhancedLoggingService.Verify(
|
||||
service => service.LogUserActionAsync(
|
||||
"ProcessPriorityChanged",
|
||||
It.Is<string>(details => details.Contains("Game.exe") && details.Contains("High")),
|
||||
It.Is<string>(context => context.Contains("PID: 42"))),
|
||||
Times.Once);
|
||||
Assert.Equal(ProcessOperationUserMessages.HighPriorityWarning, viewModel.StatusMessage);
|
||||
Assert.False(viewModel.HasError);
|
||||
var entry = Assert.Single(await audit.GetEntriesAsync());
|
||||
Assert.Equal("Priority", entry.Category);
|
||||
Assert.Equal(ActivityAuditSeverity.Success, entry.Severity);
|
||||
Assert.Contains("High", entry.Message);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -31,9 +46,13 @@ namespace ThreadPilot.Core.Tests
|
||||
{
|
||||
var processService = CreateProcessService();
|
||||
var coordinator = CreateAffinityCoordinator();
|
||||
var enhancedLoggingService = new Mock<IEnhancedLoggingService>(MockBehavior.Loose);
|
||||
var audit = new ActivityAuditService(NullLogger<ActivityAuditService>.Instance);
|
||||
var viewModel = CreateViewModel(
|
||||
processService.Object,
|
||||
processAffinityApplyCoordinator: coordinator.Object);
|
||||
processAffinityApplyCoordinator: coordinator.Object,
|
||||
enhancedLoggingService: enhancedLoggingService.Object,
|
||||
activityAuditService: audit);
|
||||
viewModel.CpuCores =
|
||||
[
|
||||
new CpuCoreModel { LogicalCoreId = 0, IsSelected = true },
|
||||
@@ -50,7 +69,16 @@ namespace ThreadPilot.Core.Tests
|
||||
"Manual Process tab context menu CPU selection",
|
||||
default),
|
||||
Times.Once);
|
||||
enhancedLoggingService.Verify(
|
||||
service => service.LogUserActionAsync(
|
||||
"ProcessAffinityApplied",
|
||||
It.IsAny<string>(),
|
||||
It.Is<string>(context => context.Contains("Process: Game.exe") && context.Contains("PID: 100"))),
|
||||
Times.Once);
|
||||
Assert.Same(rowProcess, viewModel.SelectedProcess);
|
||||
var entry = Assert.Single(await audit.GetEntriesAsync());
|
||||
Assert.Equal("Affinity", entry.Category);
|
||||
Assert.Equal(ActivityAuditSeverity.Success, entry.Severity);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -126,6 +154,25 @@ namespace ThreadPilot.Core.Tests
|
||||
Assert.Contains(ProcessPriorityClass.High, viewModel.ContextMenuCpuPriorityActions);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SetPriorityCommand_WhenRealtimeRequested_LogsVisibleBlockedEntry()
|
||||
{
|
||||
var processService = CreateProcessService();
|
||||
var audit = new ActivityAuditService(NullLogger<ActivityAuditService>.Instance);
|
||||
var viewModel = CreateViewModel(processService.Object, activityAuditService: audit);
|
||||
viewModel.SelectedProcess = CreateProcess();
|
||||
|
||||
await viewModel.SetPriorityCommand.ExecuteAsync(ProcessPriorityClass.RealTime);
|
||||
|
||||
processService.Verify(
|
||||
service => service.SetProcessPriority(It.IsAny<ProcessModel>(), ProcessPriorityClass.RealTime),
|
||||
Times.Never);
|
||||
var entry = Assert.Single(await audit.GetEntriesAsync());
|
||||
Assert.Equal("Priority", entry.Category);
|
||||
Assert.Equal(ActivityAuditSeverity.Warning, entry.Severity);
|
||||
Assert.Equal(ProcessOperationUserMessages.RealtimePriorityBlocked, entry.Message);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ContextMemoryPriorityCommand_CallsMemoryPriorityService()
|
||||
{
|
||||
@@ -136,16 +183,29 @@ namespace ThreadPilot.Core.Tests
|
||||
memoryPriorityService
|
||||
.Setup(service => service.GetMemoryPriorityAsync(It.IsAny<ProcessModel>()))
|
||||
.ReturnsAsync(ProcessMemoryPriority.Low);
|
||||
var enhancedLoggingService = new Mock<IEnhancedLoggingService>(MockBehavior.Loose);
|
||||
var audit = new ActivityAuditService(NullLogger<ActivityAuditService>.Instance);
|
||||
var process = CreateProcess();
|
||||
var viewModel = CreateViewModel(
|
||||
CreateProcessService().Object,
|
||||
memoryPriorityService: memoryPriorityService.Object);
|
||||
memoryPriorityService: memoryPriorityService.Object,
|
||||
enhancedLoggingService: enhancedLoggingService.Object,
|
||||
activityAuditService: audit);
|
||||
|
||||
await viewModel.SetContextMemoryPriorityLowCommand.ExecuteAsync(process);
|
||||
|
||||
memoryPriorityService.Verify(
|
||||
service => service.SetMemoryPriorityAsync(process, ProcessMemoryPriority.Low),
|
||||
Times.Once);
|
||||
var entry = Assert.Single(await audit.GetEntriesAsync());
|
||||
Assert.Equal("Memory Priority", entry.Category);
|
||||
Assert.Equal(ActivityAuditSeverity.Success, entry.Severity);
|
||||
enhancedLoggingService.Verify(
|
||||
service => service.LogUserActionAsync(
|
||||
"ProcessMemoryPriorityChanged",
|
||||
It.Is<string>(details => details.Contains("Game.exe") && details.Contains("Low")),
|
||||
It.Is<string>(context => context.Contains("PID: 42"))),
|
||||
Times.Once);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -160,14 +220,19 @@ namespace ThreadPilot.Core.Tests
|
||||
"Access is denied.",
|
||||
isAccessDenied: true));
|
||||
var process = CreateProcess();
|
||||
var audit = new ActivityAuditService(NullLogger<ActivityAuditService>.Instance);
|
||||
var viewModel = CreateViewModel(
|
||||
CreateProcessService().Object,
|
||||
memoryPriorityService: memoryPriorityService.Object);
|
||||
memoryPriorityService: memoryPriorityService.Object,
|
||||
activityAuditService: audit);
|
||||
|
||||
await viewModel.SetContextMemoryPriorityNormalCommand.ExecuteAsync(process);
|
||||
|
||||
Assert.Equal(ProcessOperationUserMessages.AccessDenied, viewModel.StatusMessage);
|
||||
Assert.True(viewModel.HasError);
|
||||
var entry = Assert.Single(await audit.GetEntriesAsync());
|
||||
Assert.Equal("Memory Priority", entry.Category);
|
||||
Assert.Equal(ActivityAuditSeverity.Warning, entry.Severity);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -245,11 +310,15 @@ namespace ThreadPilot.Core.Tests
|
||||
.Setup(service => service.ClearProcessCpuSetAsync(It.IsAny<ProcessModel>()))
|
||||
.ReturnsAsync(true);
|
||||
var process = CreateProcess();
|
||||
var viewModel = CreateViewModel(processService.Object);
|
||||
var audit = new ActivityAuditService(NullLogger<ActivityAuditService>.Instance);
|
||||
var viewModel = CreateViewModel(processService.Object, activityAuditService: audit);
|
||||
|
||||
await viewModel.ClearContextCpuSetsCommand.ExecuteAsync(process);
|
||||
|
||||
processService.Verify(service => service.ClearProcessCpuSetAsync(process), Times.Once);
|
||||
var entry = Assert.Single(await audit.GetEntriesAsync());
|
||||
Assert.Equal("Affinity", entry.Category);
|
||||
Assert.Equal(ActivityAuditSeverity.Success, entry.Severity);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -257,12 +326,127 @@ namespace ThreadPilot.Core.Tests
|
||||
{
|
||||
var processService = CreateProcessService();
|
||||
var process = CreateProcess();
|
||||
var viewModel = CreateViewModel(processService.Object);
|
||||
var audit = new ActivityAuditService(NullLogger<ActivityAuditService>.Instance);
|
||||
var viewModel = CreateViewModel(processService.Object, activityAuditService: audit);
|
||||
|
||||
await viewModel.RefreshContextProcessInfoCommand.ExecuteAsync(process);
|
||||
|
||||
processService.Verify(service => service.RefreshProcessInfo(process), Times.Once);
|
||||
Assert.Equal("Process info refreshed for Game.exe.", viewModel.StatusMessage);
|
||||
var entry = Assert.Single(await audit.GetEntriesAsync());
|
||||
Assert.Equal("Process", entry.Category);
|
||||
Assert.Equal(ActivityAuditSeverity.Success, entry.Severity);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RefreshProcessesCommand_DoesNotCreateActivityAuditEntry()
|
||||
{
|
||||
var processService = CreateProcessService();
|
||||
var audit = new ActivityAuditService(NullLogger<ActivityAuditService>.Instance);
|
||||
var viewModel = CreateViewModel(processService.Object, activityAuditService: audit);
|
||||
|
||||
await viewModel.RefreshProcessesCommand.ExecuteAsync(null);
|
||||
|
||||
Assert.Empty(await audit.GetEntriesAsync());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task LockProcessList_WhenEnabled_SkipsRefreshAndKeepsSelection()
|
||||
{
|
||||
var processService = CreateProcessService();
|
||||
var audit = new ActivityAuditService(NullLogger<ActivityAuditService>.Instance);
|
||||
var viewModel = CreateViewModel(processService.Object, activityAuditService: audit);
|
||||
var selected = CreateProcess(processId: 42);
|
||||
viewModel.Processes = new ObservableCollection<ProcessModel> { selected };
|
||||
viewModel.FilteredProcesses = new ObservableCollection<ProcessModel> { selected };
|
||||
viewModel.SelectedProcess = selected;
|
||||
|
||||
viewModel.IsProcessListLocked = true;
|
||||
await viewModel.RefreshProcessesCommand.ExecuteAsync(null);
|
||||
|
||||
processService.Verify(service => service.GetProcessesAsync(), Times.Never);
|
||||
Assert.Same(selected, viewModel.SelectedProcess);
|
||||
var entry = Assert.Single(await audit.GetEntriesAsync());
|
||||
Assert.Equal("Process", entry.Category);
|
||||
Assert.Equal("Lock process list enabled.", entry.Message);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RefreshProcessesCommand_WhenProcessViewInactive_SkipsProcessRead()
|
||||
{
|
||||
var processService = CreateProcessService();
|
||||
var viewModel = CreateViewModel(processService.Object);
|
||||
|
||||
viewModel.SetProcessViewActive(false);
|
||||
await viewModel.RefreshProcessesCommand.ExecuteAsync(null);
|
||||
|
||||
processService.Verify(service => service.GetProcessesAsync(), Times.Never);
|
||||
processService.Verify(service => service.GetActiveApplicationsAsync(), Times.Never);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RefreshProcessesCommand_WhenRefreshPaused_SkipsProcessRead()
|
||||
{
|
||||
var processService = CreateProcessService();
|
||||
var viewModel = CreateViewModel(processService.Object);
|
||||
|
||||
viewModel.PauseRefresh();
|
||||
await viewModel.RefreshProcessesCommand.ExecuteAsync(null);
|
||||
|
||||
processService.Verify(service => service.GetProcessesAsync(), Times.Never);
|
||||
processService.Verify(service => service.GetActiveApplicationsAsync(), Times.Never);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task LoadProcessesCommand_WhenProcessViewInactive_DoesNotPreloadVirtualizedBatch()
|
||||
{
|
||||
var processService = CreateProcessService();
|
||||
var virtualizedProcessService = CreateVirtualizedProcessService(totalProcessCount: 100);
|
||||
var viewModel = CreateViewModel(
|
||||
processService.Object,
|
||||
virtualizedProcessService: virtualizedProcessService.Object);
|
||||
|
||||
viewModel.SetProcessViewActive(false);
|
||||
await viewModel.LoadProcessesCommand.ExecuteAsync(null);
|
||||
|
||||
virtualizedProcessService.Verify(
|
||||
service => service.PreloadNextBatchAsync(It.IsAny<int>(), It.IsAny<bool>()),
|
||||
Times.Never);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task LoadProcessesCommand_WhenProcessListLocked_DoesNotPreloadVirtualizedBatch()
|
||||
{
|
||||
var processService = CreateProcessService();
|
||||
var virtualizedProcessService = CreateVirtualizedProcessService(totalProcessCount: 100);
|
||||
var viewModel = CreateViewModel(
|
||||
processService.Object,
|
||||
virtualizedProcessService: virtualizedProcessService.Object);
|
||||
|
||||
viewModel.IsProcessListLocked = true;
|
||||
await viewModel.LoadProcessesCommand.ExecuteAsync(null);
|
||||
|
||||
virtualizedProcessService.Verify(
|
||||
service => service.PreloadNextBatchAsync(It.IsAny<int>(), It.IsAny<bool>()),
|
||||
Times.Never);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task LockProcessList_WhenDisabled_RefreshesOnceWithoutPersistentRuleSettingChange()
|
||||
{
|
||||
var processService = CreateProcessService();
|
||||
var audit = new ActivityAuditService(NullLogger<ActivityAuditService>.Instance);
|
||||
var viewModel = CreateViewModel(processService.Object, activityAuditService: audit);
|
||||
|
||||
viewModel.IsProcessListLocked = true;
|
||||
viewModel.IsProcessListLocked = false;
|
||||
|
||||
processService.Verify(service => service.GetProcessesAsync(), Times.Once);
|
||||
var entries = await audit.GetEntriesAsync();
|
||||
Assert.Contains(entries, entry => entry.Message == "Lock process list enabled.");
|
||||
Assert.Contains(entries, entry => entry.Message == "Lock process list disabled.");
|
||||
Assert.DoesNotContain(entries, entry => entry.Message.Contains("refreshed", StringComparison.OrdinalIgnoreCase));
|
||||
Assert.DoesNotContain(entries, entry => entry.Message.Contains("Apply saved rules", StringComparison.OrdinalIgnoreCase));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -298,10 +482,12 @@ namespace ThreadPilot.Core.Tests
|
||||
public async Task SaveCurrentSettingsAsRuleCommand_CreatesRuleForSelectedProcess()
|
||||
{
|
||||
var ruleStore = new CapturingRuleStore();
|
||||
var enhancedLoggingService = new Mock<IEnhancedLoggingService>(MockBehavior.Loose);
|
||||
var viewModel = CreateViewModel(
|
||||
CreateProcessService().Object,
|
||||
persistentRuleStore: ruleStore,
|
||||
processRuleCreationService: CreateRuleCreationService(ruleStore));
|
||||
processRuleCreationService: CreateRuleCreationService(ruleStore),
|
||||
enhancedLoggingService: enhancedLoggingService.Object);
|
||||
var process = CreateProcess();
|
||||
viewModel.SelectedProcess = process;
|
||||
viewModel.CpuCores =
|
||||
@@ -316,6 +502,12 @@ namespace ThreadPilot.Core.Tests
|
||||
Assert.Equal(process.Name, rule.ProcessName);
|
||||
Assert.Equal(process.ExecutablePath, rule.ExecutablePath);
|
||||
Assert.Equal("Saved rule for Game.exe.", viewModel.StatusMessage);
|
||||
enhancedLoggingService.Verify(
|
||||
service => service.LogUserActionAsync(
|
||||
"PersistentRuleSaved",
|
||||
"Saved rule for Game.exe.",
|
||||
It.Is<string>(context => context.Contains("Process: Game.exe") && context.Contains("PID: 42"))),
|
||||
Times.Once);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -332,10 +524,12 @@ namespace ThreadPilot.Core.Tests
|
||||
UpdatedAt = DateTime.UtcNow.AddDays(-1),
|
||||
};
|
||||
var ruleStore = new CapturingRuleStore([existing]);
|
||||
var enhancedLoggingService = new Mock<IEnhancedLoggingService>(MockBehavior.Loose);
|
||||
var viewModel = CreateViewModel(
|
||||
CreateProcessService().Object,
|
||||
persistentRuleStore: ruleStore,
|
||||
processRuleCreationService: CreateRuleCreationService(ruleStore));
|
||||
processRuleCreationService: CreateRuleCreationService(ruleStore),
|
||||
enhancedLoggingService: enhancedLoggingService.Object);
|
||||
|
||||
await viewModel.SaveCurrentSettingsAsRuleCommand.ExecuteAsync(CreateProcess(priority: ProcessPriorityClass.High));
|
||||
|
||||
@@ -343,6 +537,12 @@ namespace ThreadPilot.Core.Tests
|
||||
Assert.Equal("rule-1", rule.Id);
|
||||
Assert.Equal(ProcessPriorityClass.High, rule.Priority);
|
||||
Assert.Equal("Updated saved rule for Game.exe.", viewModel.StatusMessage);
|
||||
enhancedLoggingService.Verify(
|
||||
service => service.LogUserActionAsync(
|
||||
"PersistentRuleSaved",
|
||||
"Updated saved rule for Game.exe.",
|
||||
It.Is<string>(context => context.Contains("Process: Game.exe") && context.Contains("PID: 42"))),
|
||||
Times.Once);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -427,11 +627,13 @@ namespace ThreadPilot.Core.Tests
|
||||
ProcessOperationUserMessages.AccessDenied,
|
||||
"Access denied.",
|
||||
isAccessDenied: true));
|
||||
var audit = new ActivityAuditService(NullLogger<ActivityAuditService>.Instance);
|
||||
var viewModel = CreateViewModel(
|
||||
CreateProcessService().Object,
|
||||
processAffinityApplyCoordinator: coordinator.Object,
|
||||
persistentRuleStore: ruleStore,
|
||||
processRuleCreationService: CreateRuleCreationService(ruleStore));
|
||||
processRuleCreationService: CreateRuleCreationService(ruleStore),
|
||||
activityAuditService: audit);
|
||||
viewModel.CpuCores =
|
||||
[
|
||||
new CpuCoreModel { LogicalCoreId = 0, IsSelected = true },
|
||||
@@ -442,6 +644,9 @@ namespace ThreadPilot.Core.Tests
|
||||
Assert.Empty(ruleStore.SavedRules);
|
||||
Assert.Equal(ProcessOperationUserMessages.AccessDenied, viewModel.StatusMessage);
|
||||
Assert.True(viewModel.HasError);
|
||||
var entry = Assert.Single(await audit.GetEntriesAsync());
|
||||
Assert.Equal("Affinity", entry.Category);
|
||||
Assert.Equal(ActivityAuditSeverity.Warning, entry.Severity);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -510,6 +715,31 @@ namespace ThreadPilot.Core.Tests
|
||||
return processService;
|
||||
}
|
||||
|
||||
private static Mock<IVirtualizedProcessService> CreateVirtualizedProcessService(int totalProcessCount)
|
||||
{
|
||||
var virtualizedProcessService = new Mock<IVirtualizedProcessService>(MockBehavior.Loose);
|
||||
virtualizedProcessService.SetupProperty(
|
||||
service => service.Configuration,
|
||||
new VirtualizedProcessConfig());
|
||||
virtualizedProcessService
|
||||
.Setup(service => service.InitializeAsync())
|
||||
.Returns(Task.CompletedTask);
|
||||
virtualizedProcessService
|
||||
.Setup(service => service.GetTotalProcessCountAsync(It.IsAny<bool>()))
|
||||
.ReturnsAsync(totalProcessCount);
|
||||
virtualizedProcessService
|
||||
.Setup(service => service.LoadProcessBatchAsync(It.IsAny<int>(), It.IsAny<bool>()))
|
||||
.ReturnsAsync(new ProcessBatchResult
|
||||
{
|
||||
Processes = [CreateProcess()],
|
||||
BatchIndex = 0,
|
||||
TotalBatches = 2,
|
||||
TotalProcessCount = totalProcessCount,
|
||||
HasMoreBatches = true,
|
||||
});
|
||||
return virtualizedProcessService;
|
||||
}
|
||||
|
||||
private static Mock<IProcessAffinityApplyCoordinator> CreateAffinityCoordinator()
|
||||
{
|
||||
var coordinator = new Mock<IProcessAffinityApplyCoordinator>(MockBehavior.Strict);
|
||||
@@ -530,12 +760,19 @@ namespace ThreadPilot.Core.Tests
|
||||
IPersistentProcessRuleStore? persistentRuleStore = null,
|
||||
IProcessRuleCreationService? processRuleCreationService = null,
|
||||
Action<string>? clipboardSetter = null,
|
||||
Action<string>? executableLocationOpener = null)
|
||||
Action<string>? executableLocationOpener = null,
|
||||
IEnhancedLoggingService? enhancedLoggingService = null,
|
||||
IActivityAuditService? activityAuditService = null,
|
||||
IVirtualizedProcessService? virtualizedProcessService = null)
|
||||
{
|
||||
var virtualizedProcessService = new Mock<IVirtualizedProcessService>(MockBehavior.Loose);
|
||||
virtualizedProcessService.SetupProperty(
|
||||
service => service.Configuration,
|
||||
new VirtualizedProcessConfig());
|
||||
if (virtualizedProcessService == null)
|
||||
{
|
||||
var virtualizedProcessServiceMock = new Mock<IVirtualizedProcessService>(MockBehavior.Loose);
|
||||
virtualizedProcessServiceMock.SetupProperty(
|
||||
service => service.Configuration,
|
||||
new VirtualizedProcessConfig());
|
||||
virtualizedProcessService = virtualizedProcessServiceMock.Object;
|
||||
}
|
||||
|
||||
var cpuTopologyService = new Mock<ICpuTopologyService>(MockBehavior.Loose);
|
||||
var powerPlanService = new Mock<IPowerPlanService>(MockBehavior.Loose);
|
||||
@@ -549,7 +786,7 @@ namespace ThreadPilot.Core.Tests
|
||||
NullLogger<ProcessViewModel>.Instance,
|
||||
processService,
|
||||
new ProcessFilterService(),
|
||||
virtualizedProcessService.Object,
|
||||
virtualizedProcessService,
|
||||
cpuTopologyService.Object,
|
||||
powerPlanService.Object,
|
||||
notificationService.Object,
|
||||
@@ -558,6 +795,8 @@ namespace ThreadPilot.Core.Tests
|
||||
associationService.Object,
|
||||
gameModeService.Object,
|
||||
processAffinityApplyCoordinator: processAffinityApplyCoordinator,
|
||||
enhancedLoggingService: enhancedLoggingService,
|
||||
activityAuditService: activityAuditService,
|
||||
memoryPriorityService: memoryPriorityService,
|
||||
persistentRuleStore: persistentRuleStore,
|
||||
persistentRuleMatcher: new PersistentProcessRuleMatcher(),
|
||||
|
||||
@@ -0,0 +1,288 @@
|
||||
namespace ThreadPilot.Core.Tests
|
||||
{
|
||||
using System.Xml.Linq;
|
||||
|
||||
public sealed class ProcessViewXamlBindingTests
|
||||
{
|
||||
private static readonly string ProcessViewPath = Path.Combine(
|
||||
AppContext.BaseDirectory,
|
||||
"..",
|
||||
"..",
|
||||
"..",
|
||||
"..",
|
||||
"..",
|
||||
"Views",
|
||||
"ProcessView.xaml");
|
||||
|
||||
[Fact]
|
||||
public void LastOperationMessageBinding_IsDisplayOnly()
|
||||
{
|
||||
var document = XDocument.Load(ProcessViewPath, LoadOptions.PreserveWhitespace);
|
||||
var lastOperationBindings = document
|
||||
.Descendants()
|
||||
.SelectMany(element => element.Attributes().Select(attribute => new
|
||||
{
|
||||
Element = element.Name.LocalName,
|
||||
Attribute = attribute.Name.LocalName,
|
||||
Value = attribute.Value,
|
||||
}))
|
||||
.Where(attribute => attribute.Value.Contains("SelectedProcessSummary.LastOperationMessage", StringComparison.Ordinal))
|
||||
.ToList();
|
||||
|
||||
var binding = Assert.Single(lastOperationBindings);
|
||||
Assert.Equal("Text", binding.Attribute);
|
||||
Assert.Contains("Mode=OneWay", binding.Value, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SelectedProcessSummaryBindings_AreNotUsedByEditableControls()
|
||||
{
|
||||
var editableControls = new HashSet<string>(StringComparer.Ordinal)
|
||||
{
|
||||
"CheckBox",
|
||||
"ComboBox",
|
||||
"DatePicker",
|
||||
"PasswordBox",
|
||||
"Slider",
|
||||
"TextBox",
|
||||
"ToggleButton",
|
||||
};
|
||||
var document = XDocument.Load(ProcessViewPath, LoadOptions.PreserveWhitespace);
|
||||
|
||||
var editableSummaryBindings = document
|
||||
.Descendants()
|
||||
.Where(element => editableControls.Contains(element.Name.LocalName))
|
||||
.SelectMany(element => element.Attributes().Select(attribute => new
|
||||
{
|
||||
Element = element.Name.LocalName,
|
||||
Attribute = attribute.Name.LocalName,
|
||||
Value = attribute.Value,
|
||||
}))
|
||||
.Where(attribute => attribute.Value.Contains("SelectedProcessSummary.", StringComparison.Ordinal))
|
||||
.ToList();
|
||||
|
||||
Assert.Empty(editableSummaryBindings);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ProcessGridRowStyle_HighlightsSelectedRowsWithAccentTheme()
|
||||
{
|
||||
var document = XDocument.Load(ProcessViewPath, LoadOptions.PreserveWhitespace);
|
||||
var serialized = document.ToString(SaveOptions.DisableFormatting);
|
||||
|
||||
Assert.Contains("IsSelected", serialized, StringComparison.Ordinal);
|
||||
Assert.Contains("Accent", serialized, StringComparison.Ordinal);
|
||||
Assert.Contains("BorderThickness", serialized, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ProcessGridContextMenu_MenuItemsUseStableDetachedMenuStyle()
|
||||
{
|
||||
var document = XDocument.Load(ProcessViewPath, LoadOptions.PreserveWhitespace);
|
||||
var serialized = document.ToString(SaveOptions.DisableFormatting);
|
||||
|
||||
Assert.Contains("<ContextMenu", serialized, StringComparison.Ordinal);
|
||||
Assert.Contains("Style=\"{StaticResource ProcessContextMenuStyle}\"", serialized, StringComparison.Ordinal);
|
||||
Assert.Contains("TargetType=\"{x:Type MenuItem}\"", serialized, StringComparison.Ordinal);
|
||||
Assert.Contains("FontWeight\" Value=\"Normal\"", serialized, StringComparison.Ordinal);
|
||||
Assert.Contains("FontSize\" Value=\"{DynamicResource BodyFontSize}\"", serialized, StringComparison.Ordinal);
|
||||
Assert.Contains("Style=\"{StaticResource ProcessContextMenuItemStyle}\"", serialized, StringComparison.Ordinal);
|
||||
Assert.Contains("ControlTemplate TargetType=\"{x:Type MenuItem}\"", serialized, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("FontWeight\" Value=\"{Binding", serialized, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("FontWeight\" Value=\"{TemplateBinding", serialized, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ProcessGridContextMenu_DoesNotApplyMenuItemStyleToSeparators()
|
||||
{
|
||||
var document = XDocument.Load(ProcessViewPath, LoadOptions.PreserveWhitespace);
|
||||
var serialized = document.ToString(SaveOptions.DisableFormatting);
|
||||
|
||||
Assert.Contains("<Separator", serialized, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("ItemContainerStyle", serialized, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("<Separator Style=\"{StaticResource ProcessContextMenuItemStyle}\"", serialized, StringComparison.Ordinal);
|
||||
Assert.Contains("<Separator Style=\"{StaticResource ProcessContextMenuSeparatorStyle}\"", serialized, StringComparison.Ordinal);
|
||||
Assert.Contains("TargetType=\"{x:Type Separator}\"", serialized, StringComparison.Ordinal);
|
||||
Assert.Contains("ControlTemplate TargetType=\"{x:Type Separator}\"", serialized, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ProcessGridContextMenu_UsesThemeAwareTemplateWithoutIconCheckGutter()
|
||||
{
|
||||
var document = XDocument.Load(ProcessViewPath, LoadOptions.PreserveWhitespace);
|
||||
var serialized = document.ToString(SaveOptions.DisableFormatting);
|
||||
|
||||
Assert.Contains("TargetType=\"{x:Type ContextMenu}\"", serialized, StringComparison.Ordinal);
|
||||
Assert.Contains("TargetType=\"{x:Type MenuItem}\"", serialized, StringComparison.Ordinal);
|
||||
Assert.Contains("ControlTemplate TargetType=\"{x:Type MenuItem}\"", serialized, StringComparison.Ordinal);
|
||||
Assert.Contains("x:Name=\"SubmenuArrow\"", serialized, StringComparison.Ordinal);
|
||||
Assert.Contains("PART_Popup", serialized, StringComparison.Ordinal);
|
||||
Assert.Contains("QuietRowHoverBackgroundBrush", serialized, StringComparison.Ordinal);
|
||||
Assert.Contains("CardSurfaceBrush", serialized, StringComparison.Ordinal);
|
||||
Assert.Contains("BorderSubtleBrush", serialized, StringComparison.Ordinal);
|
||||
Assert.Contains("TextPrimaryBrush", serialized, StringComparison.Ordinal);
|
||||
Assert.Contains("TextDisabledBrush", serialized, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("Grid.IsSharedSizeScope", serialized, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("IconPresenter", serialized, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("GlyphPanel", serialized, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("Checkmark", serialized, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("CheckMark", serialized, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("IconHost", serialized, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("CheckGlyph", serialized, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("SystemColors.Menu", serialized, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ProcessGridContextMenu_ThemeResourceKeysExistInLightAndDarkThemes()
|
||||
{
|
||||
var themePaths = new[]
|
||||
{
|
||||
Path.Combine(AppContext.BaseDirectory, "..", "..", "..", "..", "..", "Themes", "FluentLight.xaml"),
|
||||
Path.Combine(AppContext.BaseDirectory, "..", "..", "..", "..", "..", "Themes", "FluentDark.xaml"),
|
||||
};
|
||||
|
||||
foreach (var themePath in themePaths)
|
||||
{
|
||||
var theme = File.ReadAllText(themePath);
|
||||
|
||||
Assert.Contains("x:Key=\"BodyFontSize\"", theme, StringComparison.Ordinal);
|
||||
Assert.Contains("x:Key=\"CardSurfaceBrush\"", theme, StringComparison.Ordinal);
|
||||
Assert.Contains("x:Key=\"BorderSubtleBrush\"", theme, StringComparison.Ordinal);
|
||||
Assert.Contains("x:Key=\"TextPrimaryBrush\"", theme, StringComparison.Ordinal);
|
||||
Assert.Contains("x:Key=\"TextSecondaryBrush\"", theme, StringComparison.Ordinal);
|
||||
Assert.Contains("x:Key=\"TextDisabledBrush\"", theme, StringComparison.Ordinal);
|
||||
Assert.Contains("x:Key=\"QuietRowHoverBackgroundBrush\"", theme, StringComparison.Ordinal);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ProcessGridContextMenu_ContainsExpectedActionsAndSubmenus()
|
||||
{
|
||||
var document = XDocument.Load(ProcessViewPath, LoadOptions.PreserveWhitespace);
|
||||
var serialized = document.ToString(SaveOptions.DisableFormatting);
|
||||
|
||||
Assert.Contains("Header=\"Apply Affinity\"", serialized, StringComparison.Ordinal);
|
||||
Assert.Contains("Header=\"Clear CPU Sets\"", serialized, StringComparison.Ordinal);
|
||||
Assert.Contains("Header=\"Rules\"", serialized, StringComparison.Ordinal);
|
||||
Assert.Contains("Header=\"Save Current Settings as Rule\"", serialized, StringComparison.Ordinal);
|
||||
Assert.Contains("Header=\"Apply Affinity and Save as Rule\"", serialized, StringComparison.Ordinal);
|
||||
Assert.Contains("Header=\"Set CPU Priority\"", serialized, StringComparison.Ordinal);
|
||||
Assert.Contains("Header=\"Below Normal\"", serialized, StringComparison.Ordinal);
|
||||
Assert.Contains("Header=\"Normal\"", serialized, StringComparison.Ordinal);
|
||||
Assert.Contains("Header=\"Above Normal\"", serialized, StringComparison.Ordinal);
|
||||
Assert.Contains("Header=\"High\"", serialized, StringComparison.Ordinal);
|
||||
Assert.Contains("Header=\"Realtime (blocked)\"", serialized, StringComparison.Ordinal);
|
||||
Assert.Contains("Header=\"Set Memory Priority\"", serialized, StringComparison.Ordinal);
|
||||
Assert.Contains("Header=\"Very Low\"", serialized, StringComparison.Ordinal);
|
||||
Assert.Contains("Header=\"Low\"", serialized, StringComparison.Ordinal);
|
||||
Assert.Contains("Header=\"Medium\"", serialized, StringComparison.Ordinal);
|
||||
Assert.Contains("Header=\"Open Executable Location\"", serialized, StringComparison.Ordinal);
|
||||
Assert.Contains("Header=\"Copy Process Info\"", serialized, StringComparison.Ordinal);
|
||||
Assert.Contains("Header=\"Refresh Process Info\"", serialized, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ProcessToolbar_ExposesLockProcessListToggle()
|
||||
{
|
||||
var document = XDocument.Load(ProcessViewPath, LoadOptions.PreserveWhitespace);
|
||||
var serialized = document.ToString(SaveOptions.DisableFormatting);
|
||||
|
||||
Assert.Contains("Lock process list", serialized, StringComparison.Ordinal);
|
||||
Assert.Contains("IsChecked=\"{Binding IsProcessListLocked}\"", serialized, StringComparison.Ordinal);
|
||||
Assert.Contains("Pause process list refresh and sorting updates while you work with the current list.", serialized, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void MasksView_SelectedCpuTilesUseSubtleMaskSelectionResources()
|
||||
{
|
||||
var masksViewPath = Path.Combine(
|
||||
GetRepositoryRoot(),
|
||||
"Views",
|
||||
"MasksView.xaml");
|
||||
var document = XDocument.Load(masksViewPath, LoadOptions.PreserveWhitespace);
|
||||
var serialized = document.ToString(SaveOptions.DisableFormatting);
|
||||
|
||||
Assert.Contains("MaskSelectedBackgroundBrush", serialized, StringComparison.Ordinal);
|
||||
Assert.Contains("MaskSelectedBorderBrush", serialized, StringComparison.Ordinal);
|
||||
Assert.Contains("BorderThickness\" Value=\"2\"", serialized, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("SoftSelectionBackgroundBrush", serialized, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void MasksView_SelectedMaskListItemUsesReadableFluentSelection()
|
||||
{
|
||||
var masksViewPath = Path.Combine(
|
||||
GetRepositoryRoot(),
|
||||
"Views",
|
||||
"MasksView.xaml");
|
||||
var document = XDocument.Load(masksViewPath, LoadOptions.PreserveWhitespace);
|
||||
var serialized = document.ToString(SaveOptions.DisableFormatting);
|
||||
|
||||
Assert.Contains("x:Key=\"MaskListItemStyle\"", serialized, StringComparison.Ordinal);
|
||||
Assert.Contains("TargetType=\"{x:Type ListBoxItem}\"", serialized, StringComparison.Ordinal);
|
||||
Assert.Contains("ItemContainerStyle=\"{StaticResource MaskListItemStyle}\"", serialized, StringComparison.Ordinal);
|
||||
Assert.Contains("MaskSelectedListBackgroundBrush", serialized, StringComparison.Ordinal);
|
||||
Assert.Contains("MaskSelectedBorderBrush", serialized, StringComparison.Ordinal);
|
||||
Assert.Contains("BorderThickness\" Value=\"2\"", serialized, StringComparison.Ordinal);
|
||||
Assert.Contains("Foreground\" Value=\"{DynamicResource TextFillColorPrimaryBrush}\"", serialized, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("TextOnAccentFillColorPrimaryBrush", serialized, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("AccentFillColorDefaultBrush", serialized, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void MainWindow_ContainsStartupMinimizedSuggestionOverlay()
|
||||
{
|
||||
var mainWindowPath = Path.Combine(GetRepositoryRoot(), "MainWindow.xaml");
|
||||
var document = XDocument.Load(mainWindowPath, LoadOptions.PreserveWhitespace);
|
||||
var serialized = document.ToString(SaveOptions.DisableFormatting);
|
||||
|
||||
Assert.Contains("StartupMinimizedSuggestionOverlay", serialized, StringComparison.Ordinal);
|
||||
Assert.Contains("Startup minimized", serialized, StringComparison.Ordinal);
|
||||
Assert.Contains("Open Settings", serialized, StringComparison.Ordinal);
|
||||
Assert.Contains("Don't show again", serialized, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void MainWindow_QueuesStartupUpdateCheckOnceWithoutBlockingStartup()
|
||||
{
|
||||
var mainWindowBehaviorPath = Path.Combine(GetRepositoryRoot(), "MainWindow.Behaviors.partial.cs");
|
||||
var source = File.ReadAllText(mainWindowBehaviorPath);
|
||||
var updateCheckSection = source[
|
||||
source.IndexOf("private void QueueStartupUpdateCheck()", StringComparison.Ordinal)..
|
||||
source.IndexOf("private void UpdateLoadingStatus", StringComparison.Ordinal)];
|
||||
|
||||
Assert.Contains("QueueStartupUpdateCheck();", source, StringComparison.Ordinal);
|
||||
Assert.Contains("Interlocked.Exchange(ref this.startupUpdateCheckStarted, 1)", updateCheckSection, StringComparison.Ordinal);
|
||||
Assert.Contains("TaskSafety.FireAndForget(this.CheckForUpdatesAtStartupAsync()", updateCheckSection, StringComparison.Ordinal);
|
||||
Assert.Contains("GetLatestVersionAsync(\"PrimeBuild-pc\", \"ThreadPilot\")", updateCheckSection, StringComparison.Ordinal);
|
||||
Assert.Contains("Startup update check ignored failure", updateCheckSection, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("System.Windows.MessageBox.Show", updateCheckSection, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void LegacyActionSidePanel_IsNotPersistentPrimaryUi()
|
||||
{
|
||||
var document = XDocument.Load(ProcessViewPath, LoadOptions.PreserveWhitespace);
|
||||
var serialized = document.ToString(SaveOptions.DisableFormatting);
|
||||
|
||||
Assert.Contains("Grid.Column=\"2\" Visibility=\"Collapsed\"", serialized, StringComparison.Ordinal);
|
||||
Assert.Contains("Advanced affinity picker", serialized, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
private static string GetRepositoryRoot()
|
||||
{
|
||||
var directory = new DirectoryInfo(AppContext.BaseDirectory);
|
||||
while (directory != null && !File.Exists(Path.Combine(directory.FullName, "ThreadPilot.csproj")))
|
||||
{
|
||||
directory = directory.Parent;
|
||||
}
|
||||
|
||||
if (directory == null)
|
||||
{
|
||||
throw new InvalidOperationException("Repository root was not found.");
|
||||
}
|
||||
|
||||
return directory.FullName;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -30,15 +30,15 @@ namespace ThreadPilot.Core.Tests
|
||||
};
|
||||
|
||||
var result = await service.ExecuteAsync(
|
||||
async () =>
|
||||
() =>
|
||||
{
|
||||
attempts++;
|
||||
if (attempts < 3)
|
||||
{
|
||||
throw new InvalidOperationException("transient");
|
||||
return Task.FromException<string>(new InvalidOperationException("transient"));
|
||||
}
|
||||
|
||||
return "ok";
|
||||
return Task.FromResult("ok");
|
||||
},
|
||||
policy);
|
||||
|
||||
@@ -67,10 +67,10 @@ namespace ThreadPilot.Core.Tests
|
||||
await Assert.ThrowsAsync<UnauthorizedAccessException>(async () =>
|
||||
{
|
||||
await service.ExecuteAsync<string>(
|
||||
async () =>
|
||||
() =>
|
||||
{
|
||||
attempts++;
|
||||
throw new UnauthorizedAccessException("denied");
|
||||
return Task.FromException<string>(new UnauthorizedAccessException("denied"));
|
||||
},
|
||||
policy);
|
||||
});
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
/*
|
||||
* ThreadPilot - dependency injection registration tests.
|
||||
*/
|
||||
namespace ThreadPilot.Core.Tests
|
||||
{
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using ThreadPilot.Models;
|
||||
using ThreadPilot.Services;
|
||||
|
||||
public sealed class ServiceConfigurationTests
|
||||
{
|
||||
[Fact]
|
||||
public void ConfigureApplicationServices_RegistersPersistentRuleAutoApplyService()
|
||||
{
|
||||
using var provider = CreateProvider();
|
||||
|
||||
var service = provider.GetRequiredService<IPersistentRuleAutoApplyService>();
|
||||
|
||||
Assert.IsType<PersistentRuleAutoApplyService>(service);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ConfigureApplicationServices_RegistersProcessRuleCreationService()
|
||||
{
|
||||
using var provider = CreateProvider();
|
||||
|
||||
var service = provider.GetRequiredService<IProcessRuleCreationService>();
|
||||
|
||||
Assert.IsType<ProcessRuleCreationService>(service);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ConfigureApplicationServices_RegistersActivityAuditService()
|
||||
{
|
||||
using var provider = CreateProvider();
|
||||
|
||||
var service = provider.GetRequiredService<IActivityAuditService>();
|
||||
|
||||
Assert.IsType<ActivityAuditService>(service);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ApplicationSettings_DefaultsToPersistentRulesAutoApplyEnabled()
|
||||
{
|
||||
var settings = new ApplicationSettingsModel();
|
||||
|
||||
Assert.True(settings.ApplyPersistentRulesOnProcessStart);
|
||||
}
|
||||
|
||||
private static ServiceProvider CreateProvider() =>
|
||||
new ServiceCollection()
|
||||
.ConfigureApplicationServices()
|
||||
.BuildServiceProvider(new ServiceProviderOptions { ValidateScopes = true });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,166 @@
|
||||
namespace ThreadPilot.Core.Tests
|
||||
{
|
||||
using System.Collections.ObjectModel;
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
using Moq;
|
||||
using ThreadPilot.Models;
|
||||
using ThreadPilot.Services;
|
||||
using ThreadPilot.Services.Abstractions;
|
||||
using ThreadPilot.ViewModels;
|
||||
|
||||
public sealed class SettingsViewModelThemeTests
|
||||
{
|
||||
[Fact]
|
||||
public async Task ChangingTheme_AppliesThemeAndLogsVisibleActivityEntry()
|
||||
{
|
||||
var harness = new Harness();
|
||||
var viewModel = harness.CreateViewModel();
|
||||
|
||||
viewModel.Settings.UseDarkTheme = true;
|
||||
|
||||
harness.Theme.Verify(service => service.ApplyTheme(true), Times.Once);
|
||||
harness.Tray.Verify(service => service.ApplyTheme(true), Times.Once);
|
||||
harness.Logging.Verify(
|
||||
service => service.LogUserActionAsync(
|
||||
"ThemeChanged",
|
||||
"Theme changed to Dark",
|
||||
null),
|
||||
Times.Once);
|
||||
var entry = Assert.Single(await harness.Audit.GetEntriesAsync());
|
||||
Assert.Equal("Settings", entry.Category);
|
||||
Assert.Equal(ActivityAuditSeverity.Success, entry.Severity);
|
||||
Assert.Equal("Theme changed to Dark", entry.Message);
|
||||
Assert.Equal("Theme changed to Dark.", viewModel.StatusMessage);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ChangingTheme_ToSameValue_DoesNotApplyOrLogAgain()
|
||||
{
|
||||
var harness = new Harness(initialDarkTheme: true);
|
||||
var viewModel = harness.CreateViewModel();
|
||||
|
||||
viewModel.Settings.UseDarkTheme = true;
|
||||
|
||||
harness.Theme.Verify(service => service.ApplyTheme(It.IsAny<bool>()), Times.Never);
|
||||
harness.Tray.Verify(service => service.ApplyTheme(It.IsAny<bool>()), Times.Never);
|
||||
harness.Logging.Verify(
|
||||
service => service.LogUserActionAsync(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string?>()),
|
||||
Times.Never);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ChangingApplyPersistentRulesOnProcessStart_UpdatesSettingAndLogsVisibleActivityEntry()
|
||||
{
|
||||
var harness = new Harness();
|
||||
var viewModel = harness.CreateViewModel();
|
||||
|
||||
viewModel.Settings.ApplyPersistentRulesOnProcessStart = false;
|
||||
|
||||
Assert.False(viewModel.Settings.ApplyPersistentRulesOnProcessStart);
|
||||
harness.Logging.Verify(
|
||||
service => service.LogUserActionAsync(
|
||||
"SettingsChanged",
|
||||
"[Settings] Apply saved rules at process start disabled.",
|
||||
null),
|
||||
Times.Once);
|
||||
var disabledEntry = Assert.Single(await harness.Audit.GetEntriesAsync());
|
||||
Assert.Equal("Settings", disabledEntry.Category);
|
||||
Assert.Equal("[Settings] Apply saved rules at process start disabled.", disabledEntry.Message);
|
||||
|
||||
viewModel.Settings.ApplyPersistentRulesOnProcessStart = true;
|
||||
|
||||
Assert.True(viewModel.Settings.ApplyPersistentRulesOnProcessStart);
|
||||
harness.Logging.Verify(
|
||||
service => service.LogUserActionAsync(
|
||||
"SettingsChanged",
|
||||
"[Settings] Apply saved rules at process start enabled.",
|
||||
null),
|
||||
Times.Once);
|
||||
var entries = await harness.Audit.GetEntriesAsync();
|
||||
Assert.Contains(entries, entry => entry.Message == "[Settings] Apply saved rules at process start enabled.");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SettingsView_ExposesPersistentRuleAutoApplyToggle()
|
||||
{
|
||||
var settingsViewPath = Path.Combine(
|
||||
AppContext.BaseDirectory,
|
||||
"..",
|
||||
"..",
|
||||
"..",
|
||||
"..",
|
||||
"..",
|
||||
"Views",
|
||||
"SettingsView.xaml");
|
||||
var serialized = File.ReadAllText(settingsViewPath);
|
||||
|
||||
Assert.Contains("Text=\"Rules & automation\" Style=\"{StaticResource SectionHeaderStyle}\"", serialized, StringComparison.Ordinal);
|
||||
Assert.Contains("Text=\"Apply saved rules when matching processes start\"", serialized, StringComparison.Ordinal);
|
||||
Assert.Contains("TextWrapping=\"Wrap\"", serialized, StringComparison.Ordinal);
|
||||
Assert.Contains("IsChecked=\"{Binding Settings.ApplyPersistentRulesOnProcessStart}\"", serialized, StringComparison.Ordinal);
|
||||
Assert.Contains("This does not install a Windows Service and does not use registry/IFEO persistence.", serialized, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
private sealed class Harness
|
||||
{
|
||||
private readonly ApplicationSettingsModel settings;
|
||||
|
||||
public Mock<IApplicationSettingsService> SettingsService { get; } = new(MockBehavior.Loose);
|
||||
|
||||
public Mock<INotificationService> Notifications { get; } = new(MockBehavior.Loose);
|
||||
|
||||
public Mock<IAutostartService> Autostart { get; } = new(MockBehavior.Loose);
|
||||
|
||||
public Mock<IPowerPlanService> PowerPlans { get; } = new(MockBehavior.Loose);
|
||||
|
||||
public Mock<IProcessPowerPlanAssociationService> Associations { get; } = new(MockBehavior.Loose);
|
||||
|
||||
public Mock<IProcessMonitorManagerService> ProcessMonitorManager { get; } = new(MockBehavior.Loose);
|
||||
|
||||
public Mock<IThemeService> Theme { get; } = new(MockBehavior.Loose);
|
||||
|
||||
public Mock<ISystemTrayService> Tray { get; } = new(MockBehavior.Loose);
|
||||
|
||||
public Mock<IEnhancedLoggingService> Logging { get; } = new(MockBehavior.Loose);
|
||||
|
||||
public ActivityAuditService Audit { get; } = new(NullLogger<ActivityAuditService>.Instance);
|
||||
|
||||
public Harness(bool initialDarkTheme = false)
|
||||
{
|
||||
this.settings = new ApplicationSettingsModel
|
||||
{
|
||||
UseDarkTheme = initialDarkTheme,
|
||||
HasUserThemePreference = initialDarkTheme,
|
||||
};
|
||||
this.SettingsService.SetupGet(service => service.Settings).Returns(this.settings);
|
||||
this.PowerPlans
|
||||
.Setup(service => service.GetPowerPlansAsync())
|
||||
.ReturnsAsync(new ObservableCollection<PowerPlanModel>());
|
||||
this.PowerPlans
|
||||
.Setup(service => service.GetCustomPowerPlansAsync())
|
||||
.ReturnsAsync(new ObservableCollection<PowerPlanModel>());
|
||||
this.PowerPlans
|
||||
.Setup(service => service.GetActivePowerPlan())
|
||||
.ReturnsAsync((PowerPlanModel?)null);
|
||||
this.Associations
|
||||
.Setup(service => service.GetDefaultPowerPlanAsync())
|
||||
.ReturnsAsync((string.Empty, string.Empty));
|
||||
}
|
||||
|
||||
public SettingsViewModel CreateViewModel() =>
|
||||
new(
|
||||
NullLogger<SettingsViewModel>.Instance,
|
||||
this.SettingsService.Object,
|
||||
this.Notifications.Object,
|
||||
this.Autostart.Object,
|
||||
this.PowerPlans.Object,
|
||||
this.Associations.Object,
|
||||
this.ProcessMonitorManager.Object,
|
||||
this.Theme.Object,
|
||||
this.Tray.Object,
|
||||
new GitHubUpdateChecker(new Mock<IGitHubReleaseClient>().Object),
|
||||
this.Logging.Object,
|
||||
this.Audit);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
namespace ThreadPilot.Core.Tests
|
||||
{
|
||||
using ThreadPilot.Helpers;
|
||||
using ThreadPilot.Models;
|
||||
|
||||
public sealed class StartupMinimizedSuggestionPolicyTests
|
||||
{
|
||||
[Fact]
|
||||
public void ShouldShow_ReturnsTrue_ForFirstVisibleNormalLaunchWithoutStartMinimized()
|
||||
{
|
||||
var settings = new ApplicationSettingsModel();
|
||||
var behavior = StartupWindowBehavior.Resolve(isAutostart: false, startMinimized: false);
|
||||
|
||||
Assert.True(StartupMinimizedSuggestionPolicy.ShouldShow(settings, behavior));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ShouldShow_ReturnsFalse_WhenStartupIsSilent()
|
||||
{
|
||||
var settings = new ApplicationSettingsModel();
|
||||
var behavior = StartupWindowBehavior.Resolve(isAutostart: false, startMinimized: true);
|
||||
|
||||
Assert.False(StartupMinimizedSuggestionPolicy.ShouldShow(settings, behavior));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ShouldShow_ReturnsFalse_WhenSuggestionWasAlreadySeen()
|
||||
{
|
||||
var settings = new ApplicationSettingsModel();
|
||||
settings.HasSeenStartupMinimizedSuggestion = true;
|
||||
var behavior = StartupWindowBehavior.Resolve(isAutostart: false, startMinimized: false);
|
||||
|
||||
Assert.False(StartupMinimizedSuggestionPolicy.ShouldShow(settings, behavior));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -10,6 +10,7 @@ namespace ThreadPilot.Core.Tests
|
||||
{
|
||||
var behavior = StartupWindowBehavior.Resolve(isAutostart: false, startMinimized: false);
|
||||
|
||||
Assert.True(behavior.ShouldShowWindow);
|
||||
Assert.True(behavior.ShowInTaskbar);
|
||||
Assert.Equal(Visibility.Visible, behavior.Visibility);
|
||||
Assert.Equal(WindowState.Normal, behavior.WindowState);
|
||||
@@ -18,12 +19,13 @@ namespace ThreadPilot.Core.Tests
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Resolve_ShowsMinimizedTaskbarWindow_ForManualLaunchWithStartMinimized()
|
||||
public void Resolve_HidesToTray_ForManualLaunchWithStartMinimized()
|
||||
{
|
||||
var behavior = StartupWindowBehavior.Resolve(isAutostart: false, startMinimized: true);
|
||||
|
||||
Assert.True(behavior.ShowInTaskbar);
|
||||
Assert.Equal(Visibility.Visible, behavior.Visibility);
|
||||
Assert.False(behavior.ShouldShowWindow);
|
||||
Assert.False(behavior.ShowInTaskbar);
|
||||
Assert.Equal(Visibility.Hidden, behavior.Visibility);
|
||||
Assert.Equal(WindowState.Minimized, behavior.WindowState);
|
||||
Assert.False(behavior.HideAfterShow);
|
||||
Assert.False(behavior.ActivateAfterShow);
|
||||
@@ -34,10 +36,11 @@ namespace ThreadPilot.Core.Tests
|
||||
{
|
||||
var behavior = StartupWindowBehavior.Resolve(isAutostart: true, startMinimized: true);
|
||||
|
||||
Assert.False(behavior.ShouldShowWindow);
|
||||
Assert.False(behavior.ShowInTaskbar);
|
||||
Assert.Equal(Visibility.Hidden, behavior.Visibility);
|
||||
Assert.Equal(WindowState.Minimized, behavior.WindowState);
|
||||
Assert.True(behavior.HideAfterShow);
|
||||
Assert.False(behavior.HideAfterShow);
|
||||
Assert.False(behavior.ActivateAfterShow);
|
||||
}
|
||||
|
||||
@@ -46,6 +49,7 @@ namespace ThreadPilot.Core.Tests
|
||||
{
|
||||
var behavior = StartupWindowBehavior.Resolve(isAutostart: true, startMinimized: false);
|
||||
|
||||
Assert.True(behavior.ShouldShowWindow);
|
||||
Assert.True(behavior.ShowInTaskbar);
|
||||
Assert.Equal(Visibility.Visible, behavior.Visibility);
|
||||
Assert.Equal(WindowState.Normal, behavior.WindowState);
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
namespace ThreadPilot.Core.Tests
|
||||
{
|
||||
using System.Drawing;
|
||||
using ThreadPilot.Services;
|
||||
|
||||
public sealed class SystemTrayPlacementHelperTests
|
||||
{
|
||||
[Fact]
|
||||
public void ResolveMenuOpenPoint_UsesCursorPositionOnFirstOpen()
|
||||
{
|
||||
var cursor = new Point(1200, 700);
|
||||
|
||||
var result = SystemTrayMenuPlacement.ResolveMenuOpenPoint(
|
||||
cursor,
|
||||
Point.Empty,
|
||||
Rectangle.Empty,
|
||||
new Rectangle(0, 0, 1920, 1080));
|
||||
|
||||
Assert.Equal(cursor, result);
|
||||
Assert.NotEqual(Point.Empty, result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ResolveMenuOpenPoint_FallsBackToLastKnownPoint_WhenCursorIsUnavailable()
|
||||
{
|
||||
var lastKnown = new Point(1600, 900);
|
||||
|
||||
var result = SystemTrayMenuPlacement.ResolveMenuOpenPoint(
|
||||
Point.Empty,
|
||||
lastKnown,
|
||||
Rectangle.Empty,
|
||||
new Rectangle(0, 0, 1920, 1080));
|
||||
|
||||
Assert.Equal(lastKnown, result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ResolveMenuOpenPoint_WhenFirstCursorIsUnavailable_UsesTaskbarAreaInsteadOfTopLeft()
|
||||
{
|
||||
var result = SystemTrayMenuPlacement.ResolveMenuOpenPoint(
|
||||
Point.Empty,
|
||||
Point.Empty,
|
||||
Rectangle.Empty,
|
||||
new Rectangle(0, 0, 1920, 1080));
|
||||
|
||||
Assert.NotEqual(Point.Empty, result);
|
||||
Assert.True(result.X > 0);
|
||||
Assert.True(result.Y > 0);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ResolveMenuOpenPoint_WhenTrayBoundsAreInvalid_FallsBackToCursor()
|
||||
{
|
||||
var cursor = new Point(900, 500);
|
||||
|
||||
var result = SystemTrayMenuPlacement.ResolveMenuOpenPoint(
|
||||
cursor,
|
||||
Point.Empty,
|
||||
Rectangle.Empty,
|
||||
new Rectangle(0, 0, 1920, 1080));
|
||||
|
||||
Assert.Equal(cursor, result);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
namespace ThreadPilot.Core.Tests
|
||||
{
|
||||
using ThreadPilot.Services;
|
||||
|
||||
public sealed class SystemTweaksServiceTests
|
||||
{
|
||||
[Fact]
|
||||
public void GetHighSchedulingCategoryRegistryValue_WhenEnabled_ReturnsWin32PrioritySeparation26()
|
||||
{
|
||||
var value = SystemTweaksService.GetHighSchedulingCategoryRegistryValue(enabled: true);
|
||||
|
||||
Assert.Equal(26, value);
|
||||
Assert.Equal(0x1A, value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetHighSchedulingCategoryRegistryValue_WhenDisabled_KeepsDefaultRevertValue()
|
||||
{
|
||||
var value = SystemTweaksService.GetHighSchedulingCategoryRegistryValue(enabled: false);
|
||||
|
||||
Assert.Equal(2, value);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,166 @@
|
||||
namespace ThreadPilot.Core.Tests
|
||||
{
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
using Moq;
|
||||
using ThreadPilot.Services;
|
||||
using ThreadPilot.ViewModels;
|
||||
|
||||
public sealed class SystemTweaksViewModelTests
|
||||
{
|
||||
[Theory]
|
||||
[InlineData(SystemTweak.CoreParking, "Core Parking")]
|
||||
[InlineData(SystemTweak.CStates, "C-States")]
|
||||
[InlineData(SystemTweak.SysMain, "SysMain Service")]
|
||||
[InlineData(SystemTweak.Prefetch, "Prefetch")]
|
||||
[InlineData(SystemTweak.PowerThrottling, "Power Throttling")]
|
||||
[InlineData(SystemTweak.Hpet, "HPET")]
|
||||
[InlineData(SystemTweak.HighSchedulingCategory, "High Scheduling Category")]
|
||||
[InlineData(SystemTweak.MenuShowDelay, "Menu Show Delay")]
|
||||
public async Task ToggleTweakCommand_CallsExpectedServiceAndLogsSuccess(SystemTweak tweakType, string name)
|
||||
{
|
||||
var harness = new Harness();
|
||||
harness.SetupTweak(tweakType, setResult: true);
|
||||
var viewModel = harness.CreateViewModel();
|
||||
var item = viewModel.TweakItems.Single(tweak => tweak.TweakType == tweakType);
|
||||
|
||||
Assert.NotNull(item.ToggleCommand);
|
||||
await item.ToggleCommand.ExecuteAsync(item);
|
||||
|
||||
harness.VerifySetCalled(tweakType);
|
||||
harness.Logging.Verify(
|
||||
service => service.LogUserActionAsync(
|
||||
"SystemTweakApplied",
|
||||
$"{name} enabled",
|
||||
tweakType.ToString()),
|
||||
Times.Once);
|
||||
var entry = Assert.Single(await harness.Audit.GetEntriesAsync());
|
||||
Assert.Equal("Tweaks", entry.Category);
|
||||
Assert.Equal(ActivityAuditSeverity.Success, entry.Severity);
|
||||
Assert.Equal($"{name} enabled", entry.Message);
|
||||
Assert.Equal($"{name} enabled successfully", viewModel.StatusMessage);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ToggleTweakCommand_WhenServiceFails_LogsFailureAndShowsSafeStatus()
|
||||
{
|
||||
var harness = new Harness();
|
||||
harness.Tweaks
|
||||
.Setup(service => service.SetCoreParkingAsync(true))
|
||||
.ReturnsAsync(false);
|
||||
var viewModel = harness.CreateViewModel();
|
||||
var item = viewModel.TweakItems.Single(tweak => tweak.TweakType == SystemTweak.CoreParking);
|
||||
|
||||
Assert.NotNull(item.ToggleCommand);
|
||||
await item.ToggleCommand.ExecuteAsync(item);
|
||||
|
||||
harness.Logging.Verify(
|
||||
service => service.LogUserActionAsync(
|
||||
"SystemTweakFailed",
|
||||
"Failed to enable Core Parking",
|
||||
"CoreParking"),
|
||||
Times.Once);
|
||||
var entry = Assert.Single(await harness.Audit.GetEntriesAsync());
|
||||
Assert.Equal("Tweaks", entry.Category);
|
||||
Assert.Equal(ActivityAuditSeverity.Error, entry.Severity);
|
||||
Assert.Equal("Failed to enable Core Parking", entry.Message);
|
||||
Assert.True(viewModel.HasError);
|
||||
Assert.Equal("Failed to toggle Core Parking", viewModel.ErrorMessage);
|
||||
}
|
||||
|
||||
private sealed class Harness
|
||||
{
|
||||
public Mock<ISystemTweaksService> Tweaks { get; } = new(MockBehavior.Loose);
|
||||
|
||||
public Mock<INotificationService> Notifications { get; } = new(MockBehavior.Loose);
|
||||
|
||||
public Mock<IEnhancedLoggingService> Logging { get; } = new(MockBehavior.Loose);
|
||||
|
||||
public ActivityAuditService Audit { get; } = new(NullLogger<ActivityAuditService>.Instance);
|
||||
|
||||
public void SetupTweak(SystemTweak tweakType, bool setResult)
|
||||
{
|
||||
switch (tweakType)
|
||||
{
|
||||
case SystemTweak.CoreParking:
|
||||
this.Tweaks.Setup(service => service.SetCoreParkingAsync(true)).ReturnsAsync(setResult);
|
||||
this.Tweaks.Setup(service => service.GetCoreParkingStatusAsync()).ReturnsAsync(CreateEnabledStatus());
|
||||
break;
|
||||
case SystemTweak.CStates:
|
||||
this.Tweaks.Setup(service => service.SetCStatesAsync(true)).ReturnsAsync(setResult);
|
||||
this.Tweaks.Setup(service => service.GetCStatesStatusAsync()).ReturnsAsync(CreateEnabledStatus());
|
||||
break;
|
||||
case SystemTweak.SysMain:
|
||||
this.Tweaks.Setup(service => service.SetSysMainAsync(true)).ReturnsAsync(setResult);
|
||||
this.Tweaks.Setup(service => service.GetSysMainStatusAsync()).ReturnsAsync(CreateEnabledStatus());
|
||||
break;
|
||||
case SystemTweak.Prefetch:
|
||||
this.Tweaks.Setup(service => service.SetPrefetchAsync(true)).ReturnsAsync(setResult);
|
||||
this.Tweaks.Setup(service => service.GetPrefetchStatusAsync()).ReturnsAsync(CreateEnabledStatus());
|
||||
break;
|
||||
case SystemTweak.PowerThrottling:
|
||||
this.Tweaks.Setup(service => service.SetPowerThrottlingAsync(true)).ReturnsAsync(setResult);
|
||||
this.Tweaks.Setup(service => service.GetPowerThrottlingStatusAsync()).ReturnsAsync(CreateEnabledStatus());
|
||||
break;
|
||||
case SystemTweak.Hpet:
|
||||
this.Tweaks.Setup(service => service.SetHpetAsync(true)).ReturnsAsync(setResult);
|
||||
this.Tweaks.Setup(service => service.GetHpetStatusAsync()).ReturnsAsync(CreateEnabledStatus());
|
||||
break;
|
||||
case SystemTweak.HighSchedulingCategory:
|
||||
this.Tweaks.Setup(service => service.SetHighSchedulingCategoryAsync(true)).ReturnsAsync(setResult);
|
||||
this.Tweaks.Setup(service => service.GetHighSchedulingCategoryStatusAsync()).ReturnsAsync(CreateEnabledStatus());
|
||||
break;
|
||||
case SystemTweak.MenuShowDelay:
|
||||
this.Tweaks.Setup(service => service.SetMenuShowDelayAsync(true)).ReturnsAsync(setResult);
|
||||
this.Tweaks.Setup(service => service.GetMenuShowDelayStatusAsync()).ReturnsAsync(CreateEnabledStatus());
|
||||
break;
|
||||
default:
|
||||
throw new ArgumentOutOfRangeException(nameof(tweakType), tweakType, null);
|
||||
}
|
||||
}
|
||||
|
||||
public void VerifySetCalled(SystemTweak tweakType)
|
||||
{
|
||||
switch (tweakType)
|
||||
{
|
||||
case SystemTweak.CoreParking:
|
||||
this.Tweaks.Verify(service => service.SetCoreParkingAsync(true), Times.Once);
|
||||
break;
|
||||
case SystemTweak.CStates:
|
||||
this.Tweaks.Verify(service => service.SetCStatesAsync(true), Times.Once);
|
||||
break;
|
||||
case SystemTweak.SysMain:
|
||||
this.Tweaks.Verify(service => service.SetSysMainAsync(true), Times.Once);
|
||||
break;
|
||||
case SystemTweak.Prefetch:
|
||||
this.Tweaks.Verify(service => service.SetPrefetchAsync(true), Times.Once);
|
||||
break;
|
||||
case SystemTweak.PowerThrottling:
|
||||
this.Tweaks.Verify(service => service.SetPowerThrottlingAsync(true), Times.Once);
|
||||
break;
|
||||
case SystemTweak.Hpet:
|
||||
this.Tweaks.Verify(service => service.SetHpetAsync(true), Times.Once);
|
||||
break;
|
||||
case SystemTweak.HighSchedulingCategory:
|
||||
this.Tweaks.Verify(service => service.SetHighSchedulingCategoryAsync(true), Times.Once);
|
||||
break;
|
||||
case SystemTweak.MenuShowDelay:
|
||||
this.Tweaks.Verify(service => service.SetMenuShowDelayAsync(true), Times.Once);
|
||||
break;
|
||||
default:
|
||||
throw new ArgumentOutOfRangeException(nameof(tweakType), tweakType, null);
|
||||
}
|
||||
}
|
||||
|
||||
public SystemTweaksViewModel CreateViewModel() =>
|
||||
new(
|
||||
this.Tweaks.Object,
|
||||
this.Notifications.Object,
|
||||
NullLogger<SystemTweaksViewModel>.Instance,
|
||||
this.Logging.Object,
|
||||
this.Audit);
|
||||
|
||||
private static TweakStatus CreateEnabledStatus() =>
|
||||
new() { IsEnabled = true, IsAvailable = true };
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -44,6 +44,30 @@ namespace ThreadPilot.Core.Tests
|
||||
dictionary => ThemeDictionaryPolicy.IsThreadPilotThemeDictionary(dictionary.Source?.OriginalString));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ReplaceThreadPilotThemeDictionary_WhenRequestedThemeIsAlreadyActive_ReusesExistingDictionary()
|
||||
{
|
||||
var darkThemeUri = new Uri("Themes/FluentDark.xaml", UriKind.Relative);
|
||||
var resources = new ResourceDictionary();
|
||||
var activeDictionary = CreateDictionaryWithSource(darkThemeUri);
|
||||
resources.MergedDictionaries.Add(new ResourceDictionary());
|
||||
resources.MergedDictionaries.Add(activeDictionary);
|
||||
var factoryCalls = 0;
|
||||
|
||||
var result = ThemeDictionaryPolicy.ReplaceThreadPilotThemeDictionary(
|
||||
resources,
|
||||
darkThemeUri,
|
||||
uri =>
|
||||
{
|
||||
factoryCalls++;
|
||||
return CreateDictionaryWithSource(uri);
|
||||
});
|
||||
|
||||
Assert.Same(activeDictionary, result);
|
||||
Assert.Equal(0, factoryCalls);
|
||||
Assert.Same(activeDictionary, resources.MergedDictionaries[^1]);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("Themes/FluentDark.xaml")]
|
||||
[InlineData("Themes/FluentLight.xaml")]
|
||||
@@ -59,6 +83,28 @@ namespace ThreadPilot.Core.Tests
|
||||
Assert.Contains("SectionTitleTextStyle", themeText, StringComparison.Ordinal);
|
||||
Assert.Contains("QuietRowBackgroundBrush", themeText, StringComparison.Ordinal);
|
||||
Assert.Contains("StatusPillBackgroundBrush", themeText, StringComparison.Ordinal);
|
||||
Assert.Contains("AppFontFamily", themeText, StringComparison.Ordinal);
|
||||
Assert.Contains("MaskSelectedBackgroundBrush", themeText, StringComparison.Ordinal);
|
||||
Assert.Contains("MaskSelectedListBackgroundBrush", themeText, StringComparison.Ordinal);
|
||||
Assert.Contains("MaskSelectedBorderBrush", themeText, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void DarkTheme_MaskListSelectionUsesSubtleTintWithoutAccentForeground()
|
||||
{
|
||||
var themeText = File.ReadAllText(GetRepositoryFilePath("Themes/FluentDark.xaml"));
|
||||
|
||||
Assert.Contains("x:Key=\"MaskSelectedListBackgroundBrush\"", themeText, StringComparison.Ordinal);
|
||||
Assert.Contains("Opacity=\"0.05\"", themeText, StringComparison.Ordinal);
|
||||
Assert.Contains("x:Key=\"MaskSelectedBorderBrush\"", themeText, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain(
|
||||
"x:Key=\"MaskSelectedListBackgroundBrush\" Color=\"{StaticResource AccentFillColorDefault}\"",
|
||||
themeText,
|
||||
StringComparison.Ordinal);
|
||||
Assert.DoesNotContain(
|
||||
"x:Key=\"MaskSelectedListForegroundBrush\" Color=\"{StaticResource TextOnAccentFillColorPrimary}\"",
|
||||
themeText,
|
||||
StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
private static ResourceDictionary CreateDictionaryWithSource(Uri source)
|
||||
|
||||
+13
-8
@@ -63,9 +63,11 @@
|
||||
<CornerRadius x:Key="StandardCardCornerRadius">8</CornerRadius>
|
||||
<Thickness x:Key="StandardCardPadding">16</Thickness>
|
||||
<Thickness x:Key="CompactCardPadding">12</Thickness>
|
||||
<FontFamily x:Key="AppFontFamily">Segoe UI Variable, Segoe UI</FontFamily>
|
||||
<sys:Double x:Key="PageTitleFontSize">24</sys:Double>
|
||||
<sys:Double x:Key="PageSubtitleFontSize">14</sys:Double>
|
||||
<sys:Double x:Key="SectionTitleFontSize">16</sys:Double>
|
||||
<sys:Double x:Key="BodyFontSize">14</sys:Double>
|
||||
<sys:Double x:Key="CaptionFontSize">12</sys:Double>
|
||||
|
||||
<SolidColorBrush x:Key="CardSurfaceBrush" Color="{StaticResource CardBackgroundFillColorDefault}"/>
|
||||
@@ -93,6 +95,9 @@
|
||||
|
||||
<SolidColorBrush x:Key="SoftSelectionBackgroundBrush" Color="{StaticResource SystemAccentColorPrimary}" Opacity="0.16"/>
|
||||
<SolidColorBrush x:Key="SoftSelectionBorderBrush" Color="{StaticResource SystemAccentColorPrimary}" Opacity="0.30"/>
|
||||
<SolidColorBrush x:Key="MaskSelectedBackgroundBrush" Color="{StaticResource SystemAccentColorPrimary}" Opacity="0.08"/>
|
||||
<SolidColorBrush x:Key="MaskSelectedListBackgroundBrush" Color="{StaticResource SystemAccentColorPrimary}" Opacity="0.05"/>
|
||||
<SolidColorBrush x:Key="MaskSelectedBorderBrush" Color="{StaticResource SystemAccentColorPrimary}" Opacity="0.58"/>
|
||||
|
||||
<!-- System Colors overrides -->
|
||||
<SolidColorBrush x:Key="{x:Static SystemColors.WindowBrushKey}" Color="{StaticResource ApplicationBackgroundColor}"/>
|
||||
@@ -110,17 +115,17 @@
|
||||
<Style TargetType="Window">
|
||||
<Setter Property="Background" Value="{DynamicResource AppBackgroundBrush}"/>
|
||||
<Setter Property="Foreground" Value="{DynamicResource TextPrimaryBrush}"/>
|
||||
<Setter Property="FontFamily" Value="Segoe UI Variable, Segoe UI"/>
|
||||
<Setter Property="FontFamily" Value="{DynamicResource AppFontFamily}"/>
|
||||
</Style>
|
||||
|
||||
<Style TargetType="UserControl">
|
||||
<Setter Property="Background" Value="{DynamicResource AppBackgroundBrush}"/>
|
||||
<Setter Property="Foreground" Value="{DynamicResource TextPrimaryBrush}"/>
|
||||
<Setter Property="FontFamily" Value="Segoe UI Variable, Segoe UI"/>
|
||||
<Setter Property="FontFamily" Value="{DynamicResource AppFontFamily}"/>
|
||||
</Style>
|
||||
|
||||
<Style TargetType="Control">
|
||||
<Setter Property="FontFamily" Value="Segoe UI Variable, Segoe UI"/>
|
||||
<Setter Property="FontFamily" Value="{DynamicResource AppFontFamily}"/>
|
||||
</Style>
|
||||
|
||||
<Style TargetType="Grid">
|
||||
@@ -173,14 +178,14 @@
|
||||
|
||||
<!-- Preserved explicit font settings -->
|
||||
<Style x:Key="PageTitleTextStyle" TargetType="TextBlock">
|
||||
<Setter Property="FontFamily" Value="Segoe UI Variable, Segoe UI"/>
|
||||
<Setter Property="FontFamily" Value="{DynamicResource AppFontFamily}"/>
|
||||
<Setter Property="FontSize" Value="{DynamicResource PageTitleFontSize}"/>
|
||||
<Setter Property="FontWeight" Value="SemiBold"/>
|
||||
<Setter Property="Foreground" Value="{DynamicResource TextPrimaryBrush}"/>
|
||||
</Style>
|
||||
|
||||
<Style x:Key="PageSubtitleTextStyle" TargetType="TextBlock">
|
||||
<Setter Property="FontFamily" Value="Segoe UI Variable, Segoe UI"/>
|
||||
<Setter Property="FontFamily" Value="{DynamicResource AppFontFamily}"/>
|
||||
<Setter Property="FontSize" Value="{DynamicResource PageSubtitleFontSize}"/>
|
||||
<Setter Property="FontWeight" Value="Normal"/>
|
||||
<Setter Property="Foreground" Value="{DynamicResource TextSecondaryBrush}"/>
|
||||
@@ -188,18 +193,18 @@
|
||||
</Style>
|
||||
|
||||
<Style x:Key="SectionTitleTextStyle" TargetType="TextBlock">
|
||||
<Setter Property="FontFamily" Value="Segoe UI Variable, Segoe UI"/>
|
||||
<Setter Property="FontFamily" Value="{DynamicResource AppFontFamily}"/>
|
||||
<Setter Property="FontSize" Value="{DynamicResource SectionTitleFontSize}"/>
|
||||
<Setter Property="FontWeight" Value="SemiBold"/>
|
||||
<Setter Property="Foreground" Value="{DynamicResource TextPrimaryBrush}"/>
|
||||
</Style>
|
||||
|
||||
<Style TargetType="TextBlock">
|
||||
<Setter Property="FontFamily" Value="Segoe UI Variable, Segoe UI"/>
|
||||
<Setter Property="FontFamily" Value="{DynamicResource AppFontFamily}"/>
|
||||
<Setter Property="Foreground" Value="{DynamicResource TextPrimaryBrush}"/>
|
||||
</Style>
|
||||
|
||||
<Style TargetType="TextElement">
|
||||
<Setter Property="FontFamily" Value="Segoe UI Variable, Segoe UI"/>
|
||||
<Setter Property="FontFamily" Value="{DynamicResource AppFontFamily}"/>
|
||||
</Style>
|
||||
</ResourceDictionary>
|
||||
|
||||
+13
-8
@@ -63,9 +63,11 @@
|
||||
<CornerRadius x:Key="StandardCardCornerRadius">8</CornerRadius>
|
||||
<Thickness x:Key="StandardCardPadding">16</Thickness>
|
||||
<Thickness x:Key="CompactCardPadding">12</Thickness>
|
||||
<FontFamily x:Key="AppFontFamily">Segoe UI Variable, Segoe UI</FontFamily>
|
||||
<sys:Double x:Key="PageTitleFontSize">24</sys:Double>
|
||||
<sys:Double x:Key="PageSubtitleFontSize">14</sys:Double>
|
||||
<sys:Double x:Key="SectionTitleFontSize">16</sys:Double>
|
||||
<sys:Double x:Key="BodyFontSize">14</sys:Double>
|
||||
<sys:Double x:Key="CaptionFontSize">12</sys:Double>
|
||||
|
||||
<SolidColorBrush x:Key="CardSurfaceBrush" Color="{StaticResource CardBackgroundFillColorDefault}"/>
|
||||
@@ -93,6 +95,9 @@
|
||||
|
||||
<SolidColorBrush x:Key="SoftSelectionBackgroundBrush" Color="{StaticResource SystemAccentColorPrimary}" Opacity="0.12"/>
|
||||
<SolidColorBrush x:Key="SoftSelectionBorderBrush" Color="{StaticResource SystemAccentColorPrimary}" Opacity="0.24"/>
|
||||
<SolidColorBrush x:Key="MaskSelectedBackgroundBrush" Color="{StaticResource SystemAccentColorPrimary}" Opacity="0.06"/>
|
||||
<SolidColorBrush x:Key="MaskSelectedListBackgroundBrush" Color="{StaticResource SystemAccentColorPrimary}" Opacity="0.04"/>
|
||||
<SolidColorBrush x:Key="MaskSelectedBorderBrush" Color="{StaticResource SystemAccentColorPrimary}" Opacity="0.45"/>
|
||||
|
||||
<!-- System Colors overrides -->
|
||||
<SolidColorBrush x:Key="{x:Static SystemColors.WindowBrushKey}" Color="{StaticResource ApplicationBackgroundColor}"/>
|
||||
@@ -110,17 +115,17 @@
|
||||
<Style TargetType="Window">
|
||||
<Setter Property="Background" Value="{DynamicResource AppBackgroundBrush}"/>
|
||||
<Setter Property="Foreground" Value="{DynamicResource TextPrimaryBrush}"/>
|
||||
<Setter Property="FontFamily" Value="Segoe UI Variable, Segoe UI"/>
|
||||
<Setter Property="FontFamily" Value="{DynamicResource AppFontFamily}"/>
|
||||
</Style>
|
||||
|
||||
<Style TargetType="UserControl">
|
||||
<Setter Property="Background" Value="{DynamicResource AppBackgroundBrush}"/>
|
||||
<Setter Property="Foreground" Value="{DynamicResource TextPrimaryBrush}"/>
|
||||
<Setter Property="FontFamily" Value="Segoe UI Variable, Segoe UI"/>
|
||||
<Setter Property="FontFamily" Value="{DynamicResource AppFontFamily}"/>
|
||||
</Style>
|
||||
|
||||
<Style TargetType="Control">
|
||||
<Setter Property="FontFamily" Value="Segoe UI Variable, Segoe UI"/>
|
||||
<Setter Property="FontFamily" Value="{DynamicResource AppFontFamily}"/>
|
||||
</Style>
|
||||
|
||||
<Style TargetType="Grid">
|
||||
@@ -172,14 +177,14 @@
|
||||
<!-- Removed native implicit styles to allow Wpf.Ui to style them fully -->
|
||||
|
||||
<Style x:Key="PageTitleTextStyle" TargetType="TextBlock">
|
||||
<Setter Property="FontFamily" Value="Segoe UI Variable, Segoe UI"/>
|
||||
<Setter Property="FontFamily" Value="{DynamicResource AppFontFamily}"/>
|
||||
<Setter Property="FontSize" Value="{DynamicResource PageTitleFontSize}"/>
|
||||
<Setter Property="FontWeight" Value="SemiBold"/>
|
||||
<Setter Property="Foreground" Value="{DynamicResource TextPrimaryBrush}"/>
|
||||
</Style>
|
||||
|
||||
<Style x:Key="PageSubtitleTextStyle" TargetType="TextBlock">
|
||||
<Setter Property="FontFamily" Value="Segoe UI Variable, Segoe UI"/>
|
||||
<Setter Property="FontFamily" Value="{DynamicResource AppFontFamily}"/>
|
||||
<Setter Property="FontSize" Value="{DynamicResource PageSubtitleFontSize}"/>
|
||||
<Setter Property="FontWeight" Value="Normal"/>
|
||||
<Setter Property="Foreground" Value="{DynamicResource TextSecondaryBrush}"/>
|
||||
@@ -187,18 +192,18 @@
|
||||
</Style>
|
||||
|
||||
<Style x:Key="SectionTitleTextStyle" TargetType="TextBlock">
|
||||
<Setter Property="FontFamily" Value="Segoe UI Variable, Segoe UI"/>
|
||||
<Setter Property="FontFamily" Value="{DynamicResource AppFontFamily}"/>
|
||||
<Setter Property="FontSize" Value="{DynamicResource SectionTitleFontSize}"/>
|
||||
<Setter Property="FontWeight" Value="SemiBold"/>
|
||||
<Setter Property="Foreground" Value="{DynamicResource TextPrimaryBrush}"/>
|
||||
</Style>
|
||||
|
||||
<Style TargetType="TextBlock">
|
||||
<Setter Property="FontFamily" Value="Segoe UI Variable, Segoe UI"/>
|
||||
<Setter Property="FontFamily" Value="{DynamicResource AppFontFamily}"/>
|
||||
<Setter Property="Foreground" Value="{DynamicResource TextPrimaryBrush}"/>
|
||||
</Style>
|
||||
|
||||
<Style TargetType="TextElement">
|
||||
<Setter Property="FontFamily" Value="Segoe UI Variable, Segoe UI"/>
|
||||
<Setter Property="FontFamily" Value="{DynamicResource AppFontFamily}"/>
|
||||
</Style>
|
||||
</ResourceDictionary>
|
||||
|
||||
+4
-4
@@ -16,10 +16,10 @@
|
||||
<TrimMode>link</TrimMode>
|
||||
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
|
||||
<NoWarn>CS1998;CS0067;CS0414;WFAC010;IL3000;MVVMTK0034</NoWarn>
|
||||
<Version>1.1.6</Version>
|
||||
<AssemblyVersion>1.1.6.0</AssemblyVersion>
|
||||
<FileVersion>1.1.6.0</FileVersion>
|
||||
<InformationalVersion>1.1.6</InformationalVersion>
|
||||
<Version>1.2.0</Version>
|
||||
<AssemblyVersion>1.2.0.0</AssemblyVersion>
|
||||
<FileVersion>1.2.0.0</FileVersion>
|
||||
<InformationalVersion>1.2.0</InformationalVersion>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
|
||||
@@ -30,6 +30,7 @@ namespace ThreadPilot.ViewModels
|
||||
{
|
||||
protected readonly ILogger Logger;
|
||||
protected readonly IEnhancedLoggingService? EnhancedLoggingService;
|
||||
protected readonly IActivityAuditService? ActivityAuditService;
|
||||
private bool disposed;
|
||||
private CancellationTokenSource? statusLifetimeCts;
|
||||
private bool preserveStatusUntilReplaced;
|
||||
@@ -51,10 +52,14 @@ namespace ThreadPilot.ViewModels
|
||||
[ObservableProperty]
|
||||
private string errorMessage = string.Empty;
|
||||
|
||||
protected BaseViewModel(ILogger logger, IEnhancedLoggingService? enhancedLoggingService = null)
|
||||
protected BaseViewModel(
|
||||
ILogger logger,
|
||||
IEnhancedLoggingService? enhancedLoggingService = null,
|
||||
IActivityAuditService? activityAuditService = null)
|
||||
{
|
||||
this.Logger = logger ?? throw new ArgumentNullException(nameof(logger));
|
||||
this.EnhancedLoggingService = enhancedLoggingService;
|
||||
this.ActivityAuditService = activityAuditService;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -233,6 +238,11 @@ namespace ThreadPilot.ViewModels
|
||||
{
|
||||
await this.EnhancedLoggingService.LogUserActionAsync(action, details, context);
|
||||
}
|
||||
|
||||
if (this.ActivityAuditService != null)
|
||||
{
|
||||
await this.ActivityAuditService.LogUserActionAsync(action, details, context);
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
|
||||
+516
-424
@@ -1,424 +1,516 @@
|
||||
/*
|
||||
* ThreadPilot - Advanced Windows Process and Power Plan Manager
|
||||
* Copyright (C) 2025 Prime Build
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published by
|
||||
* the Free Software Foundation, version 3 only.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
using System;
|
||||
using System.Collections.ObjectModel;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
using System.Windows.Input;
|
||||
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 log viewer and management interface.
|
||||
/// </summary>
|
||||
public partial class LogViewerViewModel : ObservableObject
|
||||
{
|
||||
private readonly IEnhancedLoggingService _loggingService;
|
||||
private readonly IApplicationSettingsService _settingsService;
|
||||
private readonly ILogger<LogViewerViewModel> _logger;
|
||||
|
||||
[ObservableProperty]
|
||||
private ObservableCollection<LogEntryDisplayModel> _logEntries = new();
|
||||
|
||||
[ObservableProperty]
|
||||
private LogEntryDisplayModel? _selectedLogEntry;
|
||||
|
||||
[ObservableProperty]
|
||||
private string _searchText = string.Empty;
|
||||
|
||||
[ObservableProperty]
|
||||
private LogLevel _selectedLogLevel = LogLevel.Information;
|
||||
|
||||
[ObservableProperty]
|
||||
private string _selectedCategory = "All";
|
||||
|
||||
[ObservableProperty]
|
||||
private DateTime _fromDate = DateTime.Today.AddDays(-7);
|
||||
|
||||
[ObservableProperty]
|
||||
private DateTime _toDate = DateTime.Today.AddDays(1);
|
||||
|
||||
[ObservableProperty]
|
||||
private bool _isLoading;
|
||||
|
||||
[ObservableProperty]
|
||||
private string _statusMessage = "Ready";
|
||||
|
||||
[ObservableProperty]
|
||||
private LogFileStatistics? _logStatistics;
|
||||
|
||||
[ObservableProperty]
|
||||
private bool _enableDebugLogging;
|
||||
|
||||
[ObservableProperty]
|
||||
private int _maxLogFileSizeMb = 10;
|
||||
|
||||
[ObservableProperty]
|
||||
private int _logRetentionDays = 7;
|
||||
|
||||
[ObservableProperty]
|
||||
private bool _autoRefresh = true;
|
||||
|
||||
[ObservableProperty]
|
||||
private int _refreshIntervalSeconds = 30;
|
||||
|
||||
public ObservableCollection<string> AvailableCategories { get; } = new()
|
||||
{
|
||||
"All", "PowerPlan", "ProcessMonitoring", "GameBoost", "UserAction", "System", "Error", "Performance"
|
||||
};
|
||||
|
||||
public ObservableCollection<LogLevel> AvailableLogLevels { get; } = new()
|
||||
{
|
||||
LogLevel.Trace, LogLevel.Debug, LogLevel.Information, LogLevel.Warning, LogLevel.Error, LogLevel.Critical
|
||||
};
|
||||
|
||||
public ICommand RefreshLogsCommand { get; }
|
||||
|
||||
public ICommand ClearLogsCommand { get; }
|
||||
|
||||
public ICommand ExportLogsCommand { get; }
|
||||
|
||||
public ICommand CleanupOldLogsCommand { get; }
|
||||
|
||||
public ICommand SaveSettingsCommand { get; }
|
||||
|
||||
public ICommand OpenLogDirectoryCommand { get; }
|
||||
|
||||
public ICommand CopyLogEntryCommand { get; }
|
||||
|
||||
public LogViewerViewModel(
|
||||
IEnhancedLoggingService loggingService,
|
||||
IApplicationSettingsService settingsService,
|
||||
ILogger<LogViewerViewModel> logger)
|
||||
{
|
||||
this._loggingService = loggingService ?? throw new ArgumentNullException(nameof(loggingService));
|
||||
this._settingsService = settingsService ?? throw new ArgumentNullException(nameof(settingsService));
|
||||
this._logger = logger ?? throw new ArgumentNullException(nameof(logger));
|
||||
|
||||
// Initialize commands
|
||||
this.RefreshLogsCommand = new AsyncRelayCommand(this.RefreshLogsAsync);
|
||||
this.ClearLogsCommand = new AsyncRelayCommand(this.ClearLogsAsync);
|
||||
this.ExportLogsCommand = new AsyncRelayCommand(this.ExportLogsAsync);
|
||||
this.CleanupOldLogsCommand = new AsyncRelayCommand(this.CleanupOldLogsAsync);
|
||||
this.SaveSettingsCommand = new AsyncRelayCommand(this.SaveSettingsAsync);
|
||||
this.OpenLogDirectoryCommand = new RelayCommand(this.OpenLogDirectory);
|
||||
this.CopyLogEntryCommand = new RelayCommand<LogEntryDisplayModel>(this.CopyLogEntry);
|
||||
|
||||
// Load initial settings
|
||||
this.LoadSettings();
|
||||
|
||||
// Start auto-refresh if enabled
|
||||
if (this._autoRefresh)
|
||||
{
|
||||
this.StartAutoRefresh();
|
||||
}
|
||||
}
|
||||
|
||||
public async Task InitializeAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
this.IsLoading = true;
|
||||
this.StatusMessage = "Loading logs...";
|
||||
|
||||
await this.RefreshLogsAsync();
|
||||
await this.RefreshStatisticsAsync();
|
||||
|
||||
this.StatusMessage = "Ready";
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
this._logger.LogError(ex, "Failed to initialize log viewer");
|
||||
this.StatusMessage = $"Error: {ex.Message}";
|
||||
}
|
||||
finally
|
||||
{
|
||||
this.IsLoading = false;
|
||||
}
|
||||
}
|
||||
|
||||
private async Task RefreshLogsAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
this.IsLoading = true;
|
||||
this.StatusMessage = "Refreshing logs...";
|
||||
|
||||
var logEntries = await this._loggingService.GetLogEntriesAsync(this.FromDate, this.ToDate);
|
||||
|
||||
// Filter by category and log level
|
||||
var filteredEntries = logEntries.Where(entry =>
|
||||
{
|
||||
var categoryMatch = this.SelectedCategory == "All" || entry.Category == this.SelectedCategory;
|
||||
var levelMatch = entry.Level >= this.SelectedLogLevel;
|
||||
var searchMatch = string.IsNullOrEmpty(this.SearchText) ||
|
||||
entry.Message.Contains(this.SearchText, StringComparison.OrdinalIgnoreCase) ||
|
||||
entry.Category.Contains(this.SearchText, StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
return categoryMatch && levelMatch && searchMatch;
|
||||
}).ToList();
|
||||
|
||||
// Convert to display models
|
||||
var displayModels = filteredEntries.Select(entry => new LogEntryDisplayModel
|
||||
{
|
||||
Timestamp = entry.Timestamp,
|
||||
Level = entry.Level,
|
||||
Category = entry.Category,
|
||||
Message = entry.Message,
|
||||
Exception = entry.Exception,
|
||||
Properties = entry.Properties,
|
||||
CorrelationId = entry.CorrelationId
|
||||
}).ToList();
|
||||
|
||||
// PERFORMANCE OPTIMIZATION: Replace collection instead of Clear() + Add() loop
|
||||
await System.Windows.Application.Current.Dispatcher.InvokeAsync(() =>
|
||||
{
|
||||
this.LogEntries = new ObservableCollection<LogEntryDisplayModel>(displayModels);
|
||||
this.StatusMessage = $"Loaded {this.LogEntries.Count} log entries";
|
||||
});
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
this._logger.LogError(ex, "Failed to refresh logs");
|
||||
this.StatusMessage = $"Error refreshing logs: {ex.Message}";
|
||||
}
|
||||
finally
|
||||
{
|
||||
this.IsLoading = false;
|
||||
}
|
||||
}
|
||||
|
||||
private async Task RefreshStatisticsAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
this.LogStatistics = await this._loggingService.GetLogStatisticsAsync();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
this._logger.LogError(ex, "Failed to refresh log statistics");
|
||||
}
|
||||
}
|
||||
|
||||
private async Task ClearLogsAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
this.LogEntries.Clear();
|
||||
this.StatusMessage = "Log display cleared";
|
||||
await this._loggingService.LogUserActionAsync("LogsCleared", "User cleared log display");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
this._logger.LogError(ex, "Failed to clear logs");
|
||||
this.StatusMessage = $"Error clearing logs: {ex.Message}";
|
||||
}
|
||||
}
|
||||
|
||||
private async Task ExportLogsAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
this.IsLoading = true;
|
||||
this.StatusMessage = "Exporting logs...";
|
||||
|
||||
var exportPath = await this._loggingService.ExportLogsAsync(this.FromDate, this.ToDate);
|
||||
this.StatusMessage = $"Logs exported to: {exportPath}";
|
||||
|
||||
await this._loggingService.LogUserActionAsync(
|
||||
"LogsExported",
|
||||
$"Logs exported to {exportPath}",
|
||||
$"DateRange: {this.FromDate:yyyy-MM-dd} to {this.ToDate:yyyy-MM-dd}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
this._logger.LogError(ex, "Failed to export logs");
|
||||
this.StatusMessage = $"Error exporting logs: {ex.Message}";
|
||||
}
|
||||
finally
|
||||
{
|
||||
this.IsLoading = false;
|
||||
}
|
||||
}
|
||||
|
||||
private async Task CleanupOldLogsAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
this.IsLoading = true;
|
||||
this.StatusMessage = "Cleaning up old logs...";
|
||||
|
||||
await this._loggingService.CleanupOldLogsAsync();
|
||||
await this.RefreshStatisticsAsync();
|
||||
|
||||
this.StatusMessage = "Old logs cleaned up successfully";
|
||||
await this._loggingService.LogUserActionAsync("LogsCleanup", "User initiated log cleanup");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
this._logger.LogError(ex, "Failed to cleanup old logs");
|
||||
this.StatusMessage = $"Error cleaning up logs: {ex.Message}";
|
||||
}
|
||||
finally
|
||||
{
|
||||
this.IsLoading = false;
|
||||
}
|
||||
}
|
||||
|
||||
private async Task SaveSettingsAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
await this._loggingService.UpdateConfigurationAsync(this.EnableDebugLogging, this.MaxLogFileSizeMb, this.LogRetentionDays);
|
||||
|
||||
this.StatusMessage = "Logging settings saved successfully";
|
||||
await this._loggingService.LogUserActionAsync(
|
||||
"LoggingSettingsChanged",
|
||||
$"Debug: {this.EnableDebugLogging}, MaxSize: {this.MaxLogFileSizeMb}MB, Retention: {this.LogRetentionDays} days");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
this._logger.LogError(ex, "Failed to save logging settings");
|
||||
this.StatusMessage = $"Error saving settings: {ex.Message}";
|
||||
}
|
||||
}
|
||||
|
||||
private void OpenLogDirectory()
|
||||
{
|
||||
try
|
||||
{
|
||||
var logDirectory = this._loggingService.LogDirectoryPath;
|
||||
if (Directory.Exists(logDirectory))
|
||||
{
|
||||
System.Diagnostics.Process.Start("explorer.exe", logDirectory);
|
||||
}
|
||||
else
|
||||
{
|
||||
this.StatusMessage = "Log directory not found";
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
this._logger.LogError(ex, "Failed to open log directory");
|
||||
this.StatusMessage = $"Error opening log directory: {ex.Message}";
|
||||
}
|
||||
}
|
||||
|
||||
private void CopyLogEntry(LogEntryDisplayModel? logEntry)
|
||||
{
|
||||
if (logEntry == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
var logText = $"[{logEntry.Timestamp:yyyy-MM-dd HH:mm:ss.fff}] [{logEntry.Level}] {logEntry.Category}: {logEntry.Message}";
|
||||
if (!string.IsNullOrEmpty(logEntry.Exception))
|
||||
{
|
||||
logText += $"\nException: {logEntry.Exception}";
|
||||
}
|
||||
|
||||
System.Windows.Clipboard.SetText(logText);
|
||||
this.StatusMessage = "Log entry copied to clipboard";
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
this._logger.LogError(ex, "Failed to copy log entry to clipboard");
|
||||
this.StatusMessage = "Failed to copy log entry";
|
||||
}
|
||||
}
|
||||
|
||||
private void LoadSettings()
|
||||
{
|
||||
var settings = this._settingsService.Settings;
|
||||
this.EnableDebugLogging = settings.EnableDebugLogging;
|
||||
this.MaxLogFileSizeMb = settings.MaxLogFileSizeMb;
|
||||
this.LogRetentionDays = settings.LogRetentionDays;
|
||||
}
|
||||
|
||||
private void StartAutoRefresh()
|
||||
{
|
||||
// Implementation for auto-refresh timer would go here
|
||||
// For now, we'll keep it simple without the timer
|
||||
}
|
||||
|
||||
partial void OnSearchTextChanged(string value)
|
||||
{
|
||||
// Trigger refresh when search text changes - marshal to UI thread to prevent cross-thread access exceptions
|
||||
_ = System.Windows.Application.Current.Dispatcher.InvokeAsync(async () => await this.RefreshLogsAsync());
|
||||
}
|
||||
|
||||
partial void OnSelectedCategoryChanged(string value)
|
||||
{
|
||||
// Trigger refresh when category changes - marshal to UI thread to prevent cross-thread access exceptions
|
||||
_ = System.Windows.Application.Current.Dispatcher.InvokeAsync(async () => await this.RefreshLogsAsync());
|
||||
}
|
||||
|
||||
partial void OnSelectedLogLevelChanged(LogLevel value)
|
||||
{
|
||||
// Trigger refresh when log level changes - marshal to UI thread to prevent cross-thread access exceptions
|
||||
_ = System.Windows.Application.Current.Dispatcher.InvokeAsync(async () => await this.RefreshLogsAsync());
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Display model for log entries in the UI.
|
||||
/// </summary>
|
||||
public class LogEntryDisplayModel
|
||||
{
|
||||
public DateTime Timestamp { get; set; }
|
||||
|
||||
public LogLevel Level { get; set; }
|
||||
|
||||
public string Category { get; set; } = string.Empty;
|
||||
|
||||
public string Message { get; set; } = string.Empty;
|
||||
|
||||
public string? Exception { get; set; }
|
||||
|
||||
public Dictionary<string, object> Properties { get; set; } = new();
|
||||
|
||||
public string? CorrelationId { get; set; }
|
||||
|
||||
public string LevelColor => this.Level switch
|
||||
{
|
||||
LogLevel.Critical => "#FF0000",
|
||||
LogLevel.Error => "#FF4444",
|
||||
LogLevel.Warning => "#FFA500",
|
||||
LogLevel.Information => "#0066CC",
|
||||
LogLevel.Debug => "#808080",
|
||||
LogLevel.Trace => "#C0C0C0",
|
||||
_ => "#000000"
|
||||
};
|
||||
|
||||
public string FormattedTimestamp => this.Timestamp.ToString("yyyy-MM-dd HH:mm:ss.fff");
|
||||
|
||||
public string ShortMessage => this.Message.Length > 100 ? this.Message.Substring(0, 100) + "..." : this.Message;
|
||||
|
||||
public bool HasException => !string.IsNullOrEmpty(this.Exception);
|
||||
|
||||
public bool HasProperties => this.Properties.Any();
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
* ThreadPilot - Advanced Windows Process and Power Plan Manager
|
||||
* Copyright (C) 2025 Prime Build
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published by
|
||||
* the Free Software Foundation, version 3 only.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
using System;
|
||||
using System.Collections.ObjectModel;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
using System.Windows.Input;
|
||||
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 log viewer and management interface.
|
||||
/// </summary>
|
||||
public partial class LogViewerViewModel : ObservableObject
|
||||
{
|
||||
private readonly IActivityAuditService activityAuditService;
|
||||
private readonly IEnhancedLoggingService loggingService;
|
||||
private readonly IApplicationSettingsService settingsService;
|
||||
private readonly ILogger<LogViewerViewModel> logger;
|
||||
|
||||
[ObservableProperty]
|
||||
private ObservableCollection<LogEntryDisplayModel> logEntries = new();
|
||||
|
||||
[ObservableProperty]
|
||||
private LogEntryDisplayModel? selectedLogEntry;
|
||||
|
||||
[ObservableProperty]
|
||||
private string searchText = string.Empty;
|
||||
|
||||
[ObservableProperty]
|
||||
private LogLevel selectedLogLevel = LogLevel.Information;
|
||||
|
||||
[ObservableProperty]
|
||||
private string selectedCategory = "All";
|
||||
|
||||
[ObservableProperty]
|
||||
private DateTime fromDate = DateTime.Today.AddDays(-7);
|
||||
|
||||
[ObservableProperty]
|
||||
private DateTime toDate = DateTime.Today.AddDays(1);
|
||||
|
||||
[ObservableProperty]
|
||||
private bool isLoading;
|
||||
|
||||
[ObservableProperty]
|
||||
private string statusMessage = "Ready";
|
||||
|
||||
[ObservableProperty]
|
||||
private LogFileStatistics? logStatistics;
|
||||
|
||||
[ObservableProperty]
|
||||
private bool enableDebugLogging;
|
||||
|
||||
[ObservableProperty]
|
||||
private int maxLogFileSizeMb = 10;
|
||||
|
||||
[ObservableProperty]
|
||||
private int logRetentionDays = 7;
|
||||
|
||||
[ObservableProperty]
|
||||
private bool autoRefresh = true;
|
||||
|
||||
[ObservableProperty]
|
||||
private int refreshIntervalSeconds = 30;
|
||||
|
||||
public ObservableCollection<string> AvailableCategories { get; } = new()
|
||||
{
|
||||
"All",
|
||||
"Process",
|
||||
"Affinity",
|
||||
"Priority",
|
||||
"Memory Priority",
|
||||
"Rules",
|
||||
"Power Plans",
|
||||
"Settings",
|
||||
"Tweaks",
|
||||
"Optimization",
|
||||
"Diagnostics",
|
||||
"Safety",
|
||||
};
|
||||
|
||||
public ObservableCollection<LogLevel> AvailableLogLevels { get; } = new()
|
||||
{
|
||||
LogLevel.Trace, LogLevel.Debug, LogLevel.Information, LogLevel.Warning, LogLevel.Error, LogLevel.Critical
|
||||
};
|
||||
|
||||
public ICommand RefreshLogsCommand { get; }
|
||||
|
||||
public ICommand ClearLogsCommand { get; }
|
||||
|
||||
public ICommand ExportLogsCommand { get; }
|
||||
|
||||
public ICommand CleanupOldLogsCommand { get; }
|
||||
|
||||
public ICommand SaveSettingsCommand { get; }
|
||||
|
||||
public ICommand OpenLogDirectoryCommand { get; }
|
||||
|
||||
public ICommand CopyLogEntryCommand { get; }
|
||||
|
||||
public LogViewerViewModel(
|
||||
IActivityAuditService activityAuditService,
|
||||
IEnhancedLoggingService loggingService,
|
||||
IApplicationSettingsService settingsService,
|
||||
ILogger<LogViewerViewModel> logger)
|
||||
{
|
||||
this.activityAuditService = activityAuditService ?? throw new ArgumentNullException(nameof(activityAuditService));
|
||||
this.loggingService = loggingService ?? throw new ArgumentNullException(nameof(loggingService));
|
||||
this.settingsService = settingsService ?? throw new ArgumentNullException(nameof(settingsService));
|
||||
this.logger = logger ?? throw new ArgumentNullException(nameof(logger));
|
||||
|
||||
// Initialize commands
|
||||
this.RefreshLogsCommand = new AsyncRelayCommand(this.RefreshLogsAsync);
|
||||
this.ClearLogsCommand = new AsyncRelayCommand(this.ClearLogsAsync);
|
||||
this.ExportLogsCommand = new AsyncRelayCommand(this.ExportLogsAsync);
|
||||
this.CleanupOldLogsCommand = new AsyncRelayCommand(this.CleanupOldLogsAsync);
|
||||
this.SaveSettingsCommand = new AsyncRelayCommand(this.SaveSettingsAsync);
|
||||
this.OpenLogDirectoryCommand = new RelayCommand(this.OpenLogDirectory);
|
||||
this.CopyLogEntryCommand = new RelayCommand<LogEntryDisplayModel>(this.CopyLogEntry);
|
||||
|
||||
// Load initial settings
|
||||
this.LoadSettings();
|
||||
this.activityAuditService.EntryAdded += this.OnActivityEntryAdded;
|
||||
|
||||
// Start auto-refresh if enabled
|
||||
if (this.autoRefresh)
|
||||
{
|
||||
this.StartAutoRefresh();
|
||||
}
|
||||
}
|
||||
|
||||
public async Task InitializeAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
this.IsLoading = true;
|
||||
this.StatusMessage = "Loading activity...";
|
||||
|
||||
await this.RefreshLogsAsync();
|
||||
await this.RefreshStatisticsAsync();
|
||||
|
||||
this.StatusMessage = "Ready";
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
this.logger.LogError(ex, "Failed to initialize log viewer");
|
||||
this.StatusMessage = $"Error: {ex.Message}";
|
||||
}
|
||||
finally
|
||||
{
|
||||
this.IsLoading = false;
|
||||
}
|
||||
}
|
||||
|
||||
private async Task RefreshLogsAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
this.IsLoading = true;
|
||||
this.StatusMessage = "Refreshing activity...";
|
||||
|
||||
var logEntries = await this.activityAuditService.GetEntriesAsync(this.FromDate, this.ToDate);
|
||||
|
||||
// Filter by category and log level
|
||||
var filteredEntries = logEntries.Where(entry =>
|
||||
this.ShouldDisplay(entry)).ToList();
|
||||
|
||||
// Convert to display models
|
||||
var displayModels = filteredEntries.Select(ToDisplayModel).ToList();
|
||||
|
||||
// PERFORMANCE OPTIMIZATION: Replace collection instead of Clear() + Add() loop
|
||||
await InvokeOnUiAsync(() =>
|
||||
{
|
||||
this.LogEntries = new ObservableCollection<LogEntryDisplayModel>(displayModels);
|
||||
this.StatusMessage = $"Loaded {this.LogEntries.Count} log entries";
|
||||
});
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
this.logger.LogError(ex, "Failed to refresh logs");
|
||||
this.StatusMessage = $"Error refreshing activity: {ex.Message}";
|
||||
}
|
||||
finally
|
||||
{
|
||||
this.IsLoading = false;
|
||||
}
|
||||
}
|
||||
|
||||
private async Task RefreshStatisticsAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
this.LogStatistics = await this.loggingService.GetLogStatisticsAsync();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
this.logger.LogError(ex, "Failed to refresh log statistics");
|
||||
}
|
||||
}
|
||||
|
||||
private async Task ClearLogsAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
this.LogEntries.Clear();
|
||||
this.StatusMessage = "Activity display cleared";
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
this.logger.LogError(ex, "Failed to clear logs");
|
||||
this.StatusMessage = $"Error clearing logs: {ex.Message}";
|
||||
}
|
||||
}
|
||||
|
||||
private async Task ExportLogsAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
this.IsLoading = true;
|
||||
this.StatusMessage = "Exporting activity...";
|
||||
|
||||
var entries = await this.activityAuditService.GetEntriesAsync(this.FromDate, this.ToDate);
|
||||
var exportPath = Path.Combine(
|
||||
Environment.GetFolderPath(Environment.SpecialFolder.Desktop),
|
||||
$"ThreadPilot_Activity_{DateTime.Now:yyyyMMdd_HHmmss}.txt");
|
||||
var exportLines = entries.Select(e =>
|
||||
$"{e.Timestamp:yyyy-MM-dd HH:mm:ss.fff} [{e.Severity}] {e.Category}: {e.Message}" +
|
||||
(string.IsNullOrWhiteSpace(e.Details) ? string.Empty : $" ({e.Details})"));
|
||||
await File.WriteAllLinesAsync(exportPath, exportLines);
|
||||
this.StatusMessage = $"Activity exported to: {exportPath}";
|
||||
|
||||
await this.activityAuditService.LogInfoAsync(
|
||||
"Diagnostics",
|
||||
$"Activity exported to {Path.GetFileName(exportPath)}",
|
||||
$"DateRange: {this.FromDate:yyyy-MM-dd} to {this.ToDate:yyyy-MM-dd}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
this.logger.LogError(ex, "Failed to export logs");
|
||||
this.StatusMessage = $"Error exporting logs: {ex.Message}";
|
||||
}
|
||||
finally
|
||||
{
|
||||
this.IsLoading = false;
|
||||
}
|
||||
}
|
||||
|
||||
private async Task CleanupOldLogsAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
this.IsLoading = true;
|
||||
this.StatusMessage = "Cleaning up old logs...";
|
||||
|
||||
await this.loggingService.CleanupOldLogsAsync();
|
||||
await this.RefreshStatisticsAsync();
|
||||
|
||||
this.StatusMessage = "Old diagnostic log files cleaned up successfully";
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
this.logger.LogError(ex, "Failed to cleanup old logs");
|
||||
this.StatusMessage = $"Error cleaning up logs: {ex.Message}";
|
||||
}
|
||||
finally
|
||||
{
|
||||
this.IsLoading = false;
|
||||
}
|
||||
}
|
||||
|
||||
private async Task SaveSettingsAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
await this.loggingService.UpdateConfigurationAsync(this.EnableDebugLogging, this.MaxLogFileSizeMb, this.LogRetentionDays);
|
||||
|
||||
this.StatusMessage = "Diagnostic logging settings saved successfully";
|
||||
await this.activityAuditService.LogInfoAsync(
|
||||
"Diagnostics",
|
||||
"Diagnostic logging settings saved",
|
||||
$"Debug: {this.EnableDebugLogging}, MaxSize: {this.MaxLogFileSizeMb}MB, Retention: {this.LogRetentionDays} days");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
this.logger.LogError(ex, "Failed to save logging settings");
|
||||
this.StatusMessage = $"Error saving settings: {ex.Message}";
|
||||
}
|
||||
}
|
||||
|
||||
private void OpenLogDirectory()
|
||||
{
|
||||
try
|
||||
{
|
||||
var logDirectory = this.loggingService.LogDirectoryPath;
|
||||
if (Directory.Exists(logDirectory))
|
||||
{
|
||||
System.Diagnostics.Process.Start("explorer.exe", logDirectory);
|
||||
}
|
||||
else
|
||||
{
|
||||
this.StatusMessage = "Log directory not found";
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
this.logger.LogError(ex, "Failed to open log directory");
|
||||
this.StatusMessage = $"Error opening log directory: {ex.Message}";
|
||||
}
|
||||
}
|
||||
|
||||
private void CopyLogEntry(LogEntryDisplayModel? logEntry)
|
||||
{
|
||||
if (logEntry == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
var logText = $"[{logEntry.Timestamp:yyyy-MM-dd HH:mm:ss.fff}] [{logEntry.Status}] {logEntry.Category}: {logEntry.Message}";
|
||||
if (!string.IsNullOrEmpty(logEntry.Details))
|
||||
{
|
||||
logText += $"\nDetails: {logEntry.Details}";
|
||||
}
|
||||
|
||||
System.Windows.Clipboard.SetText(logText);
|
||||
this.StatusMessage = "Log entry copied to clipboard";
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
this.logger.LogError(ex, "Failed to copy log entry to clipboard");
|
||||
this.StatusMessage = "Failed to copy log entry";
|
||||
}
|
||||
}
|
||||
|
||||
private void LoadSettings()
|
||||
{
|
||||
var settings = this.settingsService.Settings;
|
||||
this.EnableDebugLogging = settings.EnableDebugLogging;
|
||||
this.MaxLogFileSizeMb = settings.MaxLogFileSizeMb;
|
||||
this.LogRetentionDays = settings.LogRetentionDays;
|
||||
}
|
||||
|
||||
private void StartAutoRefresh()
|
||||
{
|
||||
// Implementation for auto-refresh timer would go here
|
||||
// For now, we'll keep it simple without the timer
|
||||
}
|
||||
|
||||
private void OnActivityEntryAdded(object? sender, ActivityAuditEntry entry)
|
||||
{
|
||||
if (!this.ShouldDisplay(entry))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_ = InvokeOnUiAsync(() =>
|
||||
{
|
||||
this.LogEntries.Insert(0, ToDisplayModel(entry));
|
||||
while (this.LogEntries.Count > 1000)
|
||||
{
|
||||
this.LogEntries.RemoveAt(this.LogEntries.Count - 1);
|
||||
}
|
||||
|
||||
this.StatusMessage = $"Loaded {this.LogEntries.Count} activity entries";
|
||||
});
|
||||
}
|
||||
|
||||
private bool ShouldDisplay(ActivityAuditEntry entry)
|
||||
{
|
||||
var categoryMatch = this.SelectedCategory == "All" || entry.Category == this.SelectedCategory;
|
||||
var levelMatch = ToLogLevel(entry.Severity) >= this.SelectedLogLevel;
|
||||
var searchMatch = string.IsNullOrEmpty(this.SearchText) ||
|
||||
entry.Message.Contains(this.SearchText, StringComparison.OrdinalIgnoreCase) ||
|
||||
entry.Category.Contains(this.SearchText, StringComparison.OrdinalIgnoreCase) ||
|
||||
(entry.Details?.Contains(this.SearchText, StringComparison.OrdinalIgnoreCase) ?? false);
|
||||
|
||||
return categoryMatch && levelMatch && searchMatch;
|
||||
}
|
||||
|
||||
private static LogEntryDisplayModel ToDisplayModel(ActivityAuditEntry entry) =>
|
||||
new()
|
||||
{
|
||||
Timestamp = entry.Timestamp,
|
||||
Level = ToLogLevel(entry.Severity),
|
||||
AuditSeverity = entry.Severity,
|
||||
Category = entry.Category,
|
||||
Message = entry.Message,
|
||||
Details = entry.Details,
|
||||
};
|
||||
|
||||
partial void OnSearchTextChanged(string value)
|
||||
{
|
||||
// Trigger refresh when search text changes - marshal to UI thread to prevent cross-thread access exceptions
|
||||
_ = InvokeOnUiAsync(async () => await this.RefreshLogsAsync());
|
||||
}
|
||||
|
||||
partial void OnSelectedCategoryChanged(string value)
|
||||
{
|
||||
// Trigger refresh when category changes - marshal to UI thread to prevent cross-thread access exceptions
|
||||
_ = InvokeOnUiAsync(async () => await this.RefreshLogsAsync());
|
||||
}
|
||||
|
||||
partial void OnSelectedLogLevelChanged(LogLevel value)
|
||||
{
|
||||
// Trigger refresh when log level changes - marshal to UI thread to prevent cross-thread access exceptions
|
||||
_ = InvokeOnUiAsync(async () => await this.RefreshLogsAsync());
|
||||
}
|
||||
|
||||
private static Task InvokeOnUiAsync(Action action)
|
||||
{
|
||||
var dispatcher = System.Windows.Application.Current?.Dispatcher;
|
||||
if (dispatcher == null || dispatcher.CheckAccess())
|
||||
{
|
||||
action();
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
return dispatcher.InvokeAsync(action).Task;
|
||||
}
|
||||
|
||||
private static Task InvokeOnUiAsync(Func<Task> action)
|
||||
{
|
||||
var dispatcher = System.Windows.Application.Current?.Dispatcher;
|
||||
if (dispatcher == null || dispatcher.CheckAccess())
|
||||
{
|
||||
return action();
|
||||
}
|
||||
|
||||
return dispatcher.InvokeAsync(action).Task.Unwrap();
|
||||
}
|
||||
|
||||
private static LogLevel ToLogLevel(ActivityAuditSeverity severity) =>
|
||||
severity switch
|
||||
{
|
||||
ActivityAuditSeverity.Error => LogLevel.Error,
|
||||
ActivityAuditSeverity.Warning => LogLevel.Warning,
|
||||
_ => LogLevel.Information,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Display model for log entries in the UI.
|
||||
/// </summary>
|
||||
public class LogEntryDisplayModel
|
||||
{
|
||||
public DateTime Timestamp { get; set; }
|
||||
|
||||
public LogLevel Level { get; set; }
|
||||
|
||||
public ActivityAuditSeverity? AuditSeverity { get; set; }
|
||||
|
||||
public string Category { get; set; } = string.Empty;
|
||||
|
||||
public string Message { get; set; } = string.Empty;
|
||||
|
||||
public string? Exception { get; set; }
|
||||
|
||||
public string? Details { get; set; }
|
||||
|
||||
public Dictionary<string, object> Properties { get; set; } = new();
|
||||
|
||||
public string? CorrelationId { get; set; }
|
||||
|
||||
public string LevelColor => this.AuditSeverity switch
|
||||
{
|
||||
ActivityAuditSeverity.Error => "#FF4444",
|
||||
ActivityAuditSeverity.Warning => "#FFA500",
|
||||
ActivityAuditSeverity.Success => "#107C10",
|
||||
ActivityAuditSeverity.Info => "#0066CC",
|
||||
_ => this.Level switch
|
||||
{
|
||||
LogLevel.Critical => "#FF0000",
|
||||
LogLevel.Error => "#FF4444",
|
||||
LogLevel.Warning => "#FFA500",
|
||||
LogLevel.Information => "#0066CC",
|
||||
LogLevel.Debug => "#808080",
|
||||
LogLevel.Trace => "#C0C0C0",
|
||||
_ => "#000000"
|
||||
},
|
||||
};
|
||||
|
||||
public string Status => this.AuditSeverity?.ToString() ?? this.Level.ToString();
|
||||
|
||||
public string FormattedTimestamp => this.Timestamp.ToString("yyyy-MM-dd HH:mm:ss.fff");
|
||||
|
||||
public string ShortMessage => this.Message.Length > 100 ? this.Message.Substring(0, 100) + "..." : this.Message;
|
||||
|
||||
public bool HasException => !string.IsNullOrEmpty(this.Exception);
|
||||
|
||||
public bool HasDetails => !string.IsNullOrEmpty(this.Details);
|
||||
|
||||
public bool HasProperties => this.Properties.Any();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -66,8 +66,9 @@ namespace ThreadPilot
|
||||
IProcessMonitorManagerService? processMonitorManagerService = null,
|
||||
INotificationService? notificationService = null,
|
||||
IElevationService? elevationService = null,
|
||||
ISecurityService? securityService = null)
|
||||
: base(logger, enhancedLoggingService)
|
||||
ISecurityService? securityService = null,
|
||||
IActivityAuditService? activityAuditService = null)
|
||||
: base(logger, enhancedLoggingService, activityAuditService)
|
||||
{
|
||||
this.processMonitorManagerService = processMonitorManagerService;
|
||||
this.notificationService = notificationService;
|
||||
|
||||
@@ -177,8 +177,10 @@ namespace ThreadPilot.ViewModels
|
||||
IPowerPlanService powerPlanService,
|
||||
IProcessMonitorManagerService processMonitorManagerService,
|
||||
ISystemTweaksService systemTweaksService,
|
||||
ILogger<PerformanceViewModel> logger)
|
||||
: base(logger, null)
|
||||
ILogger<PerformanceViewModel> logger,
|
||||
IEnhancedLoggingService? enhancedLoggingService = null,
|
||||
IActivityAuditService? activityAuditService = null)
|
||||
: base(logger, enhancedLoggingService, activityAuditService)
|
||||
{
|
||||
this.performanceService = performanceService;
|
||||
this.processService = processService;
|
||||
@@ -203,18 +205,30 @@ namespace ThreadPilot.ViewModels
|
||||
}
|
||||
|
||||
public async Task ActivateDiagnosticsAsync()
|
||||
{
|
||||
await this.ActivateDiagnosticsCoreAsync(auditActivity: false);
|
||||
}
|
||||
|
||||
private async Task ActivateDiagnosticsCoreAsync(bool auditActivity)
|
||||
{
|
||||
try
|
||||
{
|
||||
this.SetStatus("Loading optional diagnostics...");
|
||||
|
||||
await this.RefreshMetricsSnapshotAsync();
|
||||
var snapshotLoaded = await this.RefreshMetricsSnapshotAsync(auditActivity);
|
||||
await this.LoadHistoricalDataAsync();
|
||||
|
||||
this.diagnosticsActivated = true;
|
||||
this.MonitoringStateText = this.IsMonitoring ? "Active" : "Stopped";
|
||||
this.MonitoringStatusText = this.IsMonitoring ? "Live metrics active" : "Diagnostics snapshot loaded";
|
||||
this.SetStatus("Optional diagnostics loaded", false);
|
||||
if (snapshotLoaded)
|
||||
{
|
||||
this.MonitoringStatusText = this.IsMonitoring ? "Live metrics active" : "Diagnostics snapshot loaded";
|
||||
this.SetStatus("Optional diagnostics loaded", false);
|
||||
}
|
||||
else
|
||||
{
|
||||
this.MonitoringStatusText = "Diagnostics snapshot failed";
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
@@ -263,10 +277,12 @@ namespace ThreadPilot.ViewModels
|
||||
this.AddTimelineEvent("Live Metrics", "Live metrics started.", "Info");
|
||||
|
||||
this.SetStatus("Performance monitoring started", false);
|
||||
await this.LogUserActionAsync("OptimizationMonitoringStarted", "Performance monitoring started");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
this.SetError("Failed to start performance monitoring", ex);
|
||||
await this.LogUserActionAsync("OptimizationActionFailed", $"Failed to start performance monitoring: {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -284,10 +300,12 @@ namespace ThreadPilot.ViewModels
|
||||
this.AddTimelineEvent("Live Metrics", "Live metrics stopped.", "Warning");
|
||||
|
||||
this.SetStatus("Performance monitoring stopped", false);
|
||||
await this.LogUserActionAsync("OptimizationMonitoringStopped", "Performance monitoring stopped");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
this.SetError("Failed to stop performance monitoring", ex);
|
||||
await this.LogUserActionAsync("OptimizationActionFailed", $"Failed to stop performance monitoring: {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -313,14 +331,14 @@ namespace ThreadPilot.ViewModels
|
||||
{
|
||||
if (!this.diagnosticsActivated)
|
||||
{
|
||||
await this.ActivateDiagnosticsAsync();
|
||||
await this.ActivateDiagnosticsCoreAsync(auditActivity: true);
|
||||
return;
|
||||
}
|
||||
|
||||
await this.RefreshMetricsSnapshotAsync();
|
||||
await this.RefreshMetricsSnapshotAsync(auditActivity: true);
|
||||
}
|
||||
|
||||
private async Task RefreshMetricsSnapshotAsync()
|
||||
private async Task<bool> RefreshMetricsSnapshotAsync(bool auditActivity)
|
||||
{
|
||||
try
|
||||
{
|
||||
@@ -333,10 +351,20 @@ namespace ThreadPilot.ViewModels
|
||||
|
||||
this.LastManualRefreshText = $"Refreshed at {DateTime.Now:HH:mm:ss}";
|
||||
this.SetStatus("Performance snapshot refreshed", false);
|
||||
if (auditActivity)
|
||||
{
|
||||
await this.LogUserActionAsync("OptimizationSnapshotRefreshed", "Performance snapshot refreshed");
|
||||
}
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
this.SetError("Failed to refresh performance snapshot", ex);
|
||||
if (auditActivity)
|
||||
{
|
||||
await this.LogUserActionAsync("OptimizationActionFailed", $"Failed to refresh performance snapshot: {ex.Message}");
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -350,10 +378,12 @@ namespace ThreadPilot.ViewModels
|
||||
this.UpdateTimelineSummary();
|
||||
this.AddTimelineEvent("History", "Historical metrics cleared.", "Info");
|
||||
this.SetStatus("Historical data cleared", false);
|
||||
await this.LogUserActionAsync("OptimizationHistoryCleared", "Historical metrics cleared");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
this.SetError("Failed to clear historical data", ex);
|
||||
await this.LogUserActionAsync("OptimizationActionFailed", $"Failed to clear historical data: {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -430,6 +460,7 @@ namespace ThreadPilot.ViewModels
|
||||
|
||||
this.AddTimelineEvent("Rule", $"Rule created for {executableName} from hotspot panel.", "Success");
|
||||
this.SetStatus($"Rule created for {executableName} and ready for automation.", false);
|
||||
await this.LogUserActionAsync("PersistentRuleSaved", $"Rule created for {executableName} from hotspot panel");
|
||||
}
|
||||
else
|
||||
{
|
||||
@@ -451,6 +482,7 @@ namespace ThreadPilot.ViewModels
|
||||
|
||||
this.AddTimelineEvent("Rule", $"Rule updated for {executableName} from hotspot panel.", "Success");
|
||||
this.SetStatus($"Rule updated for {executableName} from hotspot panel.", false);
|
||||
await this.LogUserActionAsync("PersistentRuleUpdated", $"Rule updated for {executableName} from hotspot panel");
|
||||
}
|
||||
|
||||
await this.RefreshSelectedProcessRuleImpactAsync();
|
||||
@@ -460,6 +492,7 @@ namespace ThreadPilot.ViewModels
|
||||
{
|
||||
this.logger.LogError(ex, "Failed to create or update rule from performance hotspot");
|
||||
this.SetError("Failed to create rule from selected hotspot", ex);
|
||||
await this.LogUserActionAsync("PersistentRuleSaveFailed", $"Failed to create rule from selected hotspot: {ex.Message}");
|
||||
}
|
||||
finally
|
||||
{
|
||||
|
||||
@@ -55,8 +55,9 @@ namespace ThreadPilot.ViewModels
|
||||
public PowerPlanViewModel(
|
||||
ILogger<PowerPlanViewModel> logger,
|
||||
IPowerPlanService powerPlanService,
|
||||
IEnhancedLoggingService? enhancedLoggingService = null)
|
||||
: base(logger, enhancedLoggingService)
|
||||
IEnhancedLoggingService? enhancedLoggingService = null,
|
||||
IActivityAuditService? activityAuditService = null)
|
||||
: base(logger, enhancedLoggingService, activityAuditService)
|
||||
{
|
||||
this.powerPlanService = powerPlanService;
|
||||
this.SetupRefreshTimer();
|
||||
@@ -84,7 +85,7 @@ namespace ThreadPilot.ViewModels
|
||||
{
|
||||
if (!this.isAutoRefreshPaused)
|
||||
{
|
||||
await this.RefreshPowerPlansCommand.ExecuteAsync(null);
|
||||
await this.RefreshPowerPlansCoreAsync(reportStatus: false);
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -120,7 +121,7 @@ namespace ThreadPilot.ViewModels
|
||||
{
|
||||
try
|
||||
{
|
||||
await this.RefreshPowerPlansCommand.ExecuteAsync(null);
|
||||
await this.RefreshPowerPlansCoreAsync(reportStatus: false);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
@@ -135,14 +136,12 @@ namespace ThreadPilot.ViewModels
|
||||
try
|
||||
{
|
||||
this.SetStatus("Loading power plans...");
|
||||
this.PowerPlans = await this.powerPlanService.GetPowerPlansAsync();
|
||||
this.CustomPowerPlans = await this.powerPlanService.GetCustomPowerPlansAsync();
|
||||
this.ActivePowerPlan = await this.powerPlanService.GetActivePowerPlan();
|
||||
this.ClearStatus();
|
||||
await this.RefreshPowerPlansCoreAsync(reportStatus: false);
|
||||
this.SetStatus("Power plans loaded.", false);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
this.SetStatus($"Error loading power plans: {ex.Message}", false);
|
||||
await this.SetOperationFailedAsync($"Error loading power plans: {ex.Message}", "PowerPlanLoadFailed");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -156,24 +155,11 @@ namespace ThreadPilot.ViewModels
|
||||
|
||||
try
|
||||
{
|
||||
var currentPlans = await this.powerPlanService.GetPowerPlansAsync();
|
||||
var currentActive = await this.powerPlanService.GetActivePowerPlan();
|
||||
var customPlans = await this.powerPlanService.GetCustomPowerPlansAsync();
|
||||
|
||||
// Update power plans
|
||||
this.PowerPlans = new ObservableCollection<PowerPlanModel>(currentPlans);
|
||||
this.CustomPowerPlans = new ObservableCollection<PowerPlanModel>(customPlans);
|
||||
this.ActivePowerPlan = currentActive;
|
||||
|
||||
// Update selected plan if it exists
|
||||
if (this.SelectedPowerPlan != null)
|
||||
{
|
||||
this.SelectedPowerPlan = this.PowerPlans.FirstOrDefault(p => p.Guid == this.SelectedPowerPlan.Guid);
|
||||
}
|
||||
await this.RefreshPowerPlansCoreAsync(reportStatus: true);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
this.SetStatus($"Error refreshing power plans: {ex.Message}", false);
|
||||
await this.SetOperationFailedAsync($"Error refreshing power plans: {ex.Message}", "PowerPlanRefreshFailed");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -187,23 +173,25 @@ namespace ThreadPilot.ViewModels
|
||||
|
||||
try
|
||||
{
|
||||
this.SetStatus($"Setting active power plan to {this.SelectedPowerPlan.Name}...");
|
||||
var success = await this.powerPlanService.SetActivePowerPlan(this.SelectedPowerPlan);
|
||||
var targetPlan = this.SelectedPowerPlan;
|
||||
this.SetStatus($"Setting active power plan to {targetPlan.Name}...");
|
||||
var success = await this.powerPlanService.SetActivePowerPlan(targetPlan);
|
||||
|
||||
if (success)
|
||||
{
|
||||
this.ActivePowerPlan = this.SelectedPowerPlan;
|
||||
await this.RefreshPowerPlans();
|
||||
this.ClearStatus();
|
||||
this.ActivePowerPlan = targetPlan;
|
||||
await this.RefreshPowerPlansCoreAsync(reportStatus: false);
|
||||
this.SetStatus($"Power plan applied: {targetPlan.Name}.", false);
|
||||
await this.LogUserActionAsync("PowerPlanApplied", $"Applied power plan {targetPlan.Name}", $"Guid: {targetPlan.Guid}");
|
||||
}
|
||||
else
|
||||
{
|
||||
this.SetStatus($"Failed to set power plan {this.SelectedPowerPlan.Name}", false);
|
||||
await this.SetOperationFailedAsync($"Failed to set power plan {targetPlan.Name}", "PowerPlanApplyFailed");
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
this.SetStatus($"Error setting power plan: {ex.Message}", false);
|
||||
await this.SetOperationFailedAsync($"Error setting power plan: {ex.Message}", "PowerPlanApplyFailed");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -217,22 +205,24 @@ namespace ThreadPilot.ViewModels
|
||||
|
||||
try
|
||||
{
|
||||
this.SetStatus($"Importing custom power plan {this.SelectedCustomPlan.Name}...");
|
||||
var success = await this.powerPlanService.ImportCustomPowerPlan(this.SelectedCustomPlan.FilePath);
|
||||
var customPlan = this.SelectedCustomPlan;
|
||||
this.SetStatus($"Importing custom power plan {customPlan.Name}...");
|
||||
var success = await this.powerPlanService.ImportCustomPowerPlan(customPlan.FilePath);
|
||||
|
||||
if (success)
|
||||
{
|
||||
await this.RefreshPowerPlans();
|
||||
this.ClearStatus();
|
||||
await this.RefreshPowerPlansCoreAsync(reportStatus: false);
|
||||
this.SetStatus($"Power plan imported: {customPlan.Name}.", false);
|
||||
await this.LogUserActionAsync("PowerPlanImported", $"Imported power plan {customPlan.Name}", customPlan.FilePath);
|
||||
}
|
||||
else
|
||||
{
|
||||
this.SetStatus($"Failed to import power plan {this.SelectedCustomPlan.Name}", false);
|
||||
await this.SetOperationFailedAsync($"Failed to import power plan {customPlan.Name}", "PowerPlanImportFailed");
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
this.SetStatus($"Error importing power plan: {ex.Message}", false);
|
||||
await this.SetOperationFailedAsync($"Error importing power plan: {ex.Message}", "PowerPlanImportFailed");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -261,18 +251,91 @@ namespace ThreadPilot.ViewModels
|
||||
|
||||
if (success)
|
||||
{
|
||||
await this.RefreshPowerPlans();
|
||||
await this.RefreshPowerPlansCoreAsync(reportStatus: false);
|
||||
this.SetStatus("Custom power plan added to library.", false);
|
||||
await this.LogUserActionAsync("PowerPlanAdded", "Added custom power plan file", dialog.FileName);
|
||||
}
|
||||
else
|
||||
{
|
||||
this.SetStatus("Failed to add custom power plan file.", false);
|
||||
await this.SetOperationFailedAsync("Failed to add custom power plan file.", "PowerPlanAddFailed");
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
this.SetStatus($"Error adding custom power plan file: {ex.Message}", false);
|
||||
await this.SetOperationFailedAsync($"Error adding custom power plan file: {ex.Message}", "PowerPlanAddFailed");
|
||||
}
|
||||
}
|
||||
|
||||
[RelayCommand]
|
||||
private async Task DeletePowerPlan(PowerPlanModel? powerPlan)
|
||||
{
|
||||
var targetPlan = powerPlan ?? this.SelectedPowerPlan;
|
||||
if (targetPlan == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var activePlan = this.ActivePowerPlan ?? await this.powerPlanService.GetActivePowerPlan();
|
||||
if (targetPlan.IsActive || string.Equals(targetPlan.Guid, activePlan?.Guid, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
await this.SetOperationFailedAsync("Switch to another power plan before deleting the active plan.", "PowerPlanDeleteBlocked");
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
this.SetStatus($"Deleting power plan {targetPlan.Name}...");
|
||||
var success = await this.powerPlanService.DeletePowerPlanAsync(targetPlan.Guid);
|
||||
if (!success)
|
||||
{
|
||||
await this.SetOperationFailedAsync(
|
||||
$"Could not delete power plan {targetPlan.Name}. Windows may not allow this plan to be removed.",
|
||||
"PowerPlanDeleteFailed");
|
||||
return;
|
||||
}
|
||||
|
||||
await this.RefreshPowerPlansCoreAsync(reportStatus: false);
|
||||
this.SetStatus($"Power plan deleted: {targetPlan.Name}.", false);
|
||||
await this.LogUserActionAsync("PowerPlanDeleted", $"Deleted power plan {targetPlan.Name}", $"Guid: {targetPlan.Guid}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
await this.SetOperationFailedAsync($"Error deleting power plan: {ex.Message}", "PowerPlanDeleteFailed");
|
||||
}
|
||||
}
|
||||
|
||||
private async Task RefreshPowerPlansCoreAsync(bool reportStatus)
|
||||
{
|
||||
var currentPlans = await this.powerPlanService.GetPowerPlansAsync();
|
||||
var currentActive = await this.powerPlanService.GetActivePowerPlan();
|
||||
var customPlans = await this.powerPlanService.GetCustomPowerPlansAsync();
|
||||
|
||||
this.PowerPlans = new ObservableCollection<PowerPlanModel>(currentPlans);
|
||||
this.CustomPowerPlans = new ObservableCollection<PowerPlanModel>(customPlans);
|
||||
this.ActivePowerPlan = currentActive;
|
||||
|
||||
foreach (var plan in this.PowerPlans)
|
||||
{
|
||||
plan.IsActive = string.Equals(plan.Guid, currentActive?.Guid, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
if (this.SelectedPowerPlan != null)
|
||||
{
|
||||
this.SelectedPowerPlan = this.PowerPlans.FirstOrDefault(p => p.Guid == this.SelectedPowerPlan.Guid);
|
||||
}
|
||||
|
||||
if (reportStatus)
|
||||
{
|
||||
this.SetStatus("Power plans refreshed.", false);
|
||||
await this.LogUserActionAsync("PowerPlansRefreshed", "Refreshed power plan list");
|
||||
}
|
||||
}
|
||||
|
||||
private async Task SetOperationFailedAsync(string message, string action)
|
||||
{
|
||||
this.SetStatus(message, false);
|
||||
this.SetError(message);
|
||||
await this.LogUserActionAsync(action, message);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -23,6 +23,7 @@ namespace ThreadPilot.ViewModels
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using System.Windows.Input;
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
@@ -524,7 +525,7 @@ namespace ThreadPilot.ViewModels
|
||||
[RelayCommand]
|
||||
public async Task LoadMoreProcesses()
|
||||
{
|
||||
if (!this.IsVirtualizationEnabled || !this.HasMoreBatches || this.IsBusy)
|
||||
if (!this.ShouldRunProcessUiRefresh() || !this.IsVirtualizationEnabled || !this.HasMoreBatches || this.IsBusy)
|
||||
{
|
||||
return;
|
||||
}
|
||||
@@ -560,8 +561,7 @@ namespace ThreadPilot.ViewModels
|
||||
this.LoadingStatusText = string.Empty;
|
||||
});
|
||||
|
||||
// Preload next batch in background
|
||||
await this.virtualizedProcessService.PreloadNextBatchAsync(this.CurrentBatchIndex, this.ShowActiveApplicationsOnly);
|
||||
await this.PreloadNextBatchIfAllowedAsync(this.CurrentBatchIndex);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
@@ -578,6 +578,11 @@ namespace ThreadPilot.ViewModels
|
||||
[RelayCommand]
|
||||
public async Task LoadProcesses()
|
||||
{
|
||||
if (!this.ShouldRunProcessUiRefresh())
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
System.Diagnostics.Debug.WriteLine($"LoadProcesses: Starting, ShowActiveApplicationsOnly={this.ShowActiveApplicationsOnly}");
|
||||
@@ -614,8 +619,7 @@ namespace ThreadPilot.ViewModels
|
||||
this.TotalProcessCount = batch.TotalProcessCount;
|
||||
});
|
||||
|
||||
// Preload next batch in background
|
||||
await this.virtualizedProcessService.PreloadNextBatchAsync(0, this.ShowActiveApplicationsOnly);
|
||||
await this.PreloadNextBatchIfAllowedAsync(0);
|
||||
}
|
||||
else
|
||||
{
|
||||
@@ -672,7 +676,12 @@ namespace ThreadPilot.ViewModels
|
||||
[RelayCommand]
|
||||
private async Task RefreshProcesses()
|
||||
{
|
||||
if (this.IsBusy)
|
||||
if (!this.ShouldRunProcessUiRefresh())
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (this.IsBusy || Interlocked.Exchange(ref this.isRefreshProcessesInProgress, 1) == 1)
|
||||
{
|
||||
return;
|
||||
}
|
||||
@@ -685,7 +694,7 @@ namespace ThreadPilot.ViewModels
|
||||
? await this.processService.GetActiveApplicationsAsync()
|
||||
: await this.processService.GetProcessesAsync();
|
||||
|
||||
await System.Windows.Application.Current.Dispatcher.InvokeAsync(() =>
|
||||
await InvokeOnUiAsync(() =>
|
||||
{
|
||||
var deltaResult = ProcessListDeltaUpdater.ApplyDelta(
|
||||
this.Processes,
|
||||
@@ -712,11 +721,15 @@ namespace ThreadPilot.ViewModels
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
await System.Windows.Application.Current.Dispatcher.InvokeAsync(() =>
|
||||
await InvokeOnUiAsync(() =>
|
||||
{
|
||||
this.SetStatus($"Error refreshing processes: {ex.Message}", false);
|
||||
});
|
||||
}
|
||||
finally
|
||||
{
|
||||
Interlocked.Exchange(ref this.isRefreshProcessesInProgress, 0);
|
||||
}
|
||||
}
|
||||
|
||||
[RelayCommand]
|
||||
@@ -779,6 +792,10 @@ namespace ThreadPilot.ViewModels
|
||||
this.SelectedProcessSummary.MemoryPriority);
|
||||
|
||||
this.ApplyRuleCreationResultStatus(result);
|
||||
await this.LogUserActionAsync(
|
||||
result.Success ? "PersistentRuleSaved" : "PersistentRuleSaveFailed",
|
||||
result.UserMessage,
|
||||
$"Process: {targetProcess.Name}, PID: {targetProcess.ProcessId}");
|
||||
await this.UpdateSelectedProcessSummaryAsync(targetProcess);
|
||||
}
|
||||
|
||||
@@ -811,6 +828,10 @@ namespace ThreadPilot.ViewModels
|
||||
if (!applyResult.Success)
|
||||
{
|
||||
this.SetContextError(applyResult.Message);
|
||||
await this.LogUserActionAsync(
|
||||
"ProcessAffinityFailed",
|
||||
applyResult.Message,
|
||||
$"Process: {process.Name}, PID: {process.ProcessId}, RequestedMask: 0x{applyResult.RequestedMask:X}");
|
||||
await this.UpdateSelectedProcessSummaryAsync(process);
|
||||
return;
|
||||
}
|
||||
@@ -840,6 +861,10 @@ namespace ThreadPilot.ViewModels
|
||||
});
|
||||
|
||||
this.ApplyRuleCreationResultStatus(saveResult);
|
||||
await this.LogUserActionAsync(
|
||||
saveResult.Success ? "PersistentRuleSaved" : "PersistentRuleSaveFailed",
|
||||
saveResult.UserMessage,
|
||||
$"Process: {process.Name}, PID: {process.ProcessId}");
|
||||
await this.UpdateSelectedProcessSummaryAsync(process);
|
||||
}
|
||||
|
||||
@@ -920,12 +945,20 @@ namespace ThreadPilot.ViewModels
|
||||
}
|
||||
});
|
||||
|
||||
await this.LogUserActionAsync(
|
||||
result.Success ? "ProcessAffinityApplied" : "ProcessAffinityFailed",
|
||||
result.Message,
|
||||
$"Process: {selectedProcess.Name}, PID: {selectedProcess.ProcessId}, RequestedMask: 0x{result.RequestedMask:X}, VerifiedMask: 0x{result.VerifiedMask:X}");
|
||||
await this.UpdateSelectedProcessSummaryAsync(selectedProcess);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
var friendly = ex.Message;
|
||||
_ = this.notificationService.ShowNotificationAsync("Affinity error", friendly, NotificationType.Error);
|
||||
await this.LogUserActionAsync(
|
||||
"ProcessAffinityFailed",
|
||||
friendly,
|
||||
$"Process: {selectedProcess.Name}, PID: {selectedProcess.ProcessId}");
|
||||
|
||||
await InvokeOnUiAsync(() =>
|
||||
{
|
||||
@@ -977,6 +1010,17 @@ namespace ThreadPilot.ViewModels
|
||||
return dispatcher.InvokeAsync(action).Task;
|
||||
}
|
||||
|
||||
private static Task InvokeOnUiAsync(Func<Task> action)
|
||||
{
|
||||
var dispatcher = System.Windows.Application.Current?.Dispatcher;
|
||||
if (dispatcher == null || dispatcher.CheckAccess())
|
||||
{
|
||||
return action();
|
||||
}
|
||||
|
||||
return dispatcher.InvokeAsync(action).Task.Unwrap();
|
||||
}
|
||||
|
||||
[RelayCommand]
|
||||
private async Task ApplyAffinityPreset(CpuAffinityPreset preset)
|
||||
{
|
||||
@@ -1318,23 +1362,39 @@ namespace ThreadPilot.ViewModels
|
||||
[RelayCommand]
|
||||
private async Task SetPriority(ProcessPriorityClass priority)
|
||||
{
|
||||
if (this.SelectedProcess == null)
|
||||
var selectedProcess = this.SelectedProcess;
|
||||
if (selectedProcess == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (ProcessPriorityGuardrails.IsBlocked(priority))
|
||||
{
|
||||
var message = ProcessOperationUserMessages.RealtimePriorityBlocked;
|
||||
await InvokeOnUiAsync(() =>
|
||||
{
|
||||
this.SetCriticalStatus(message);
|
||||
});
|
||||
_ = this.notificationService.ShowNotificationAsync("Priority blocked", message, NotificationType.Warning);
|
||||
await this.LogUserActionAsync(
|
||||
"ProcessPriorityBlocked",
|
||||
message,
|
||||
$"Process: {selectedProcess.Name}, PID: {selectedProcess.ProcessId}, Priority: {priority}");
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
await System.Windows.Application.Current.Dispatcher.InvokeAsync(() =>
|
||||
{
|
||||
this.SetStatus($"Setting priority for {this.SelectedProcess.Name} to {priority}...");
|
||||
this.SetStatus($"Setting priority for {selectedProcess.Name} to {priority}...");
|
||||
});
|
||||
|
||||
// Apply the priority change
|
||||
await this.processService.SetProcessPriority(this.SelectedProcess, priority);
|
||||
await this.processService.SetProcessPriority(selectedProcess, priority);
|
||||
|
||||
// Immediately refresh the process to get the actual system state
|
||||
await this.processService.RefreshProcessInfo(this.SelectedProcess);
|
||||
await this.processService.RefreshProcessInfo(selectedProcess);
|
||||
|
||||
await System.Windows.Application.Current.Dispatcher.InvokeAsync(() =>
|
||||
{
|
||||
@@ -1342,7 +1402,7 @@ namespace ThreadPilot.ViewModels
|
||||
this.OnPropertyChanged(nameof(this.SelectedProcess));
|
||||
|
||||
// Verify the priority was set correctly
|
||||
if (this.SelectedProcess.Priority == priority)
|
||||
if (selectedProcess.Priority == priority)
|
||||
{
|
||||
var warning = ProcessPriorityGuardrails.GetWarning(priority);
|
||||
if (!string.IsNullOrWhiteSpace(warning))
|
||||
@@ -1352,16 +1412,20 @@ namespace ThreadPilot.ViewModels
|
||||
}
|
||||
else
|
||||
{
|
||||
this.SetStatus($"Priority applied successfully to {this.SelectedProcess.Name}: {priority}.", false);
|
||||
_ = this.notificationService.ShowNotificationAsync("Priority applied", $"{this.SelectedProcess.Name}: {priority}", NotificationType.Success);
|
||||
this.SetStatus($"Priority applied successfully to {selectedProcess.Name}: {priority}.", false);
|
||||
_ = this.notificationService.ShowNotificationAsync("Priority applied", $"{selectedProcess.Name}: {priority}", NotificationType.Success);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
this.SetStatus($"Priority adjusted by system for {this.SelectedProcess.Name} to {this.SelectedProcess.Priority}.", false);
|
||||
_ = this.notificationService.ShowNotificationAsync("Priority adjusted", $"{this.SelectedProcess.Name}: {this.SelectedProcess.Priority}", NotificationType.Warning);
|
||||
this.SetStatus($"Priority adjusted by system for {selectedProcess.Name} to {selectedProcess.Priority}.", false);
|
||||
_ = this.notificationService.ShowNotificationAsync("Priority adjusted", $"{selectedProcess.Name}: {selectedProcess.Priority}", NotificationType.Warning);
|
||||
}
|
||||
});
|
||||
await this.LogUserActionAsync(
|
||||
"ProcessPriorityChanged",
|
||||
$"CPU priority changed for {selectedProcess.Name}: {priority}",
|
||||
$"PID: {selectedProcess.ProcessId}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
@@ -1386,11 +1450,15 @@ namespace ThreadPilot.ViewModels
|
||||
{
|
||||
this.SetCriticalStatus($"Error setting priority: {message}");
|
||||
});
|
||||
await this.LogUserActionAsync(
|
||||
message == ProcessOperationUserMessages.RealtimePriorityBlocked ? "ProcessPriorityBlocked" : "ProcessPriorityChangeFailed",
|
||||
message,
|
||||
$"Process: {selectedProcess.Name}, PID: {selectedProcess.ProcessId}, Priority: {priority}");
|
||||
|
||||
// Try to refresh process info even if setting failed, to show current state
|
||||
try
|
||||
{
|
||||
await this.processService.RefreshProcessInfo(this.SelectedProcess);
|
||||
await this.processService.RefreshProcessInfo(selectedProcess);
|
||||
await System.Windows.Application.Current.Dispatcher.InvokeAsync(() =>
|
||||
{
|
||||
this.OnPropertyChanged(nameof(this.SelectedProcess));
|
||||
@@ -1457,17 +1525,30 @@ namespace ThreadPilot.ViewModels
|
||||
if (!success)
|
||||
{
|
||||
this.SetContextError(ProcessOperationUserMessages.AccessDenied);
|
||||
await this.LogUserActionAsync(
|
||||
"CpuSetsClearFailed",
|
||||
ProcessOperationUserMessages.AccessDenied,
|
||||
$"Process: {process.Name}, PID: {process.ProcessId}");
|
||||
await this.UpdateSelectedProcessSummaryAsync(process);
|
||||
return;
|
||||
}
|
||||
|
||||
await this.processService.RefreshProcessInfo(process);
|
||||
this.SetStatus($"CPU Sets cleared for {process.Name}.", false);
|
||||
await this.LogUserActionAsync(
|
||||
"CpuSetsCleared",
|
||||
$"CPU Sets cleared for {process.Name}",
|
||||
$"PID: {process.ProcessId}");
|
||||
await this.UpdateSelectedProcessSummaryAsync(process);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
this.SetContextError(MapProcessOperationException(ex));
|
||||
var message = MapProcessOperationException(ex);
|
||||
this.SetContextError(message);
|
||||
await this.LogUserActionAsync(
|
||||
"CpuSetsClearFailed",
|
||||
message,
|
||||
$"Process: {process.Name}, PID: {process.ProcessId}");
|
||||
await this.TryRefreshContextProcessSummaryAsync(process);
|
||||
}
|
||||
}
|
||||
@@ -1484,11 +1565,20 @@ namespace ThreadPilot.ViewModels
|
||||
{
|
||||
await this.processService.RefreshProcessInfo(process);
|
||||
this.SetStatus($"Process info refreshed for {process.Name}.", false);
|
||||
await this.LogUserActionAsync(
|
||||
"ProcessInfoRefreshed",
|
||||
$"Process info refreshed for {process.Name}.",
|
||||
$"PID: {process.ProcessId}");
|
||||
await this.UpdateSelectedProcessSummaryAsync(process);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
this.SetContextError(MapProcessOperationException(ex));
|
||||
var message = MapProcessOperationException(ex);
|
||||
this.SetContextError(message);
|
||||
await this.LogUserActionAsync(
|
||||
"ProcessInfoRefreshFailed",
|
||||
message,
|
||||
$"Process: {process.Name}, PID: {process.ProcessId}");
|
||||
await this.TryRefreshContextProcessSummaryAsync(process);
|
||||
}
|
||||
}
|
||||
@@ -1504,7 +1594,12 @@ namespace ThreadPilot.ViewModels
|
||||
var path = process.ExecutablePath;
|
||||
if (string.IsNullOrWhiteSpace(path) || !File.Exists(path))
|
||||
{
|
||||
this.SetContextError($"Executable path is unavailable for {process.Name}.");
|
||||
var message = $"Executable path is unavailable for {process.Name}.";
|
||||
this.SetContextError(message);
|
||||
await this.LogUserActionAsync(
|
||||
"ProcessExecutableOpenFailed",
|
||||
message,
|
||||
$"Process: {process.Name}, PID: {process.ProcessId}");
|
||||
await this.UpdateSelectedProcessSummaryAsync(process);
|
||||
return;
|
||||
}
|
||||
@@ -1513,11 +1608,20 @@ namespace ThreadPilot.ViewModels
|
||||
{
|
||||
this.executableLocationOpener(path);
|
||||
this.SetStatus($"Opened executable location for {process.Name}.", false);
|
||||
await this.LogUserActionAsync(
|
||||
"ProcessExecutableLocationOpened",
|
||||
$"Opened executable location for {process.Name}.",
|
||||
path);
|
||||
await this.UpdateSelectedProcessSummaryAsync(process);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
this.SetContextError($"Could not open executable location: {ex.Message}");
|
||||
var message = $"Could not open executable location: {ex.Message}";
|
||||
this.SetContextError(message);
|
||||
await this.LogUserActionAsync(
|
||||
"ProcessExecutableOpenFailed",
|
||||
message,
|
||||
$"Process: {process.Name}, PID: {process.ProcessId}");
|
||||
await this.UpdateSelectedProcessSummaryAsync(process);
|
||||
}
|
||||
}
|
||||
@@ -1548,11 +1652,20 @@ namespace ThreadPilot.ViewModels
|
||||
{
|
||||
this.clipboardSetter(builder.ToString().TrimEnd());
|
||||
this.SetStatus($"Copied process info for {process.Name}.", false);
|
||||
await this.LogUserActionAsync(
|
||||
"ProcessInfoCopied",
|
||||
$"Copied process info for {process.Name}.",
|
||||
$"PID: {process.ProcessId}");
|
||||
await this.UpdateSelectedProcessSummaryAsync(process);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
this.SetContextError($"Could not copy process info: {ex.Message}");
|
||||
var message = $"Could not copy process info: {ex.Message}";
|
||||
this.SetContextError(message);
|
||||
await this.LogUserActionAsync(
|
||||
"ProcessInfoCopyFailed",
|
||||
message,
|
||||
$"Process: {process.Name}, PID: {process.ProcessId}");
|
||||
await this.UpdateSelectedProcessSummaryAsync(process);
|
||||
}
|
||||
}
|
||||
@@ -1567,6 +1680,10 @@ namespace ThreadPilot.ViewModels
|
||||
if (ProcessPriorityGuardrails.IsBlocked(priority))
|
||||
{
|
||||
this.SetContextError(ProcessOperationUserMessages.RealtimePriorityBlocked);
|
||||
await this.LogUserActionAsync(
|
||||
"ProcessPriorityBlocked",
|
||||
ProcessOperationUserMessages.RealtimePriorityBlocked,
|
||||
$"Process: {process.Name}, PID: {process.ProcessId}, Priority: {priority}");
|
||||
await this.UpdateSelectedProcessSummaryAsync(process);
|
||||
return;
|
||||
}
|
||||
@@ -1588,6 +1705,10 @@ namespace ThreadPilot.ViewModels
|
||||
_ = this.notificationService.ShowNotificationAsync("Priority applied", $"{process.Name}: {priority}", NotificationType.Success);
|
||||
}
|
||||
|
||||
await this.LogUserActionAsync(
|
||||
"ProcessPriorityChanged",
|
||||
$"CPU priority changed for {process.Name}: {priority}",
|
||||
$"PID: {process.ProcessId}");
|
||||
await this.UpdateSelectedProcessSummaryAsync(process);
|
||||
}
|
||||
catch (Exception ex)
|
||||
@@ -1595,6 +1716,10 @@ namespace ThreadPilot.ViewModels
|
||||
var message = MapProcessOperationException(ex);
|
||||
this.SetContextError(message);
|
||||
_ = this.notificationService.ShowNotificationAsync("Priority blocked", message, NotificationType.Warning);
|
||||
await this.LogUserActionAsync(
|
||||
"ProcessPriorityChangeFailed",
|
||||
message,
|
||||
$"Process: {process.Name}, PID: {process.ProcessId}, Priority: {priority}");
|
||||
await this.TryRefreshContextProcessSummaryAsync(process);
|
||||
}
|
||||
}
|
||||
@@ -1618,19 +1743,33 @@ namespace ThreadPilot.ViewModels
|
||||
var result = await this.memoryPriorityService.SetMemoryPriorityAsync(process, priority);
|
||||
if (!result.Success)
|
||||
{
|
||||
this.SetContextError(string.IsNullOrWhiteSpace(result.UserMessage)
|
||||
var message = string.IsNullOrWhiteSpace(result.UserMessage)
|
||||
? ProcessOperationUserMessages.AccessDenied
|
||||
: result.UserMessage);
|
||||
: result.UserMessage;
|
||||
this.SetContextError(message);
|
||||
await this.LogUserActionAsync(
|
||||
"ProcessMemoryPriorityFailed",
|
||||
message,
|
||||
$"Process: {process.Name}, PID: {process.ProcessId}, Priority: {priority}");
|
||||
await this.UpdateSelectedProcessSummaryAsync(process);
|
||||
return;
|
||||
}
|
||||
|
||||
this.SetStatus($"Memory priority applied successfully to {process.Name}: {priority}.", false);
|
||||
await this.LogUserActionAsync(
|
||||
"ProcessMemoryPriorityChanged",
|
||||
$"Memory priority changed for {process.Name}: {priority}",
|
||||
$"PID: {process.ProcessId}");
|
||||
await this.UpdateSelectedProcessSummaryAsync(process);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
this.SetContextError(MapProcessOperationException(ex));
|
||||
var message = MapProcessOperationException(ex);
|
||||
this.SetContextError(message);
|
||||
await this.LogUserActionAsync(
|
||||
"ProcessMemoryPriorityFailed",
|
||||
message,
|
||||
$"Process: {process.Name}, PID: {process.ProcessId}, Priority: {priority}");
|
||||
await this.UpdateSelectedProcessSummaryAsync(process);
|
||||
}
|
||||
}
|
||||
@@ -1796,20 +1935,23 @@ namespace ThreadPilot.ViewModels
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(decision);
|
||||
|
||||
this.virtualizedProcessService.Configuration.EnableBackgroundLoading = decision.VirtualizedPreloadEnabled;
|
||||
this.SetUiRefreshEnabled(decision.ProcessUiRefreshEnabled, decision.ImmediateProcessRefresh);
|
||||
this.isVirtualizedPreloadAllowedByPolicy = decision.VirtualizedPreloadEnabled;
|
||||
this.virtualizedProcessService.Configuration.EnableBackgroundLoading = this.ShouldPreloadVirtualizedBatches();
|
||||
this.SetUiRefreshEnabled(
|
||||
decision.ProcessUiRefreshEnabled && !this.IsProcessListLocked,
|
||||
decision.ImmediateProcessRefresh && !this.IsProcessListLocked);
|
||||
}
|
||||
|
||||
public void SetProcessViewActive(bool isActive)
|
||||
{
|
||||
if (this.isProcessViewActive == isActive)
|
||||
{
|
||||
this.virtualizedProcessService.Configuration.EnableBackgroundLoading = isActive && !this.isUiRefreshPaused;
|
||||
this.virtualizedProcessService.Configuration.EnableBackgroundLoading = this.ShouldPreloadVirtualizedBatches();
|
||||
return;
|
||||
}
|
||||
|
||||
this.isProcessViewActive = isActive;
|
||||
this.virtualizedProcessService.Configuration.EnableBackgroundLoading = isActive && !this.isUiRefreshPaused;
|
||||
this.virtualizedProcessService.Configuration.EnableBackgroundLoading = this.ShouldPreloadVirtualizedBatches();
|
||||
|
||||
if (!isActive)
|
||||
{
|
||||
@@ -1837,7 +1979,7 @@ namespace ThreadPilot.ViewModels
|
||||
public void SetUiRefreshEnabled(bool enabled, bool refreshImmediately = true)
|
||||
{
|
||||
this.isUiRefreshPaused = !enabled;
|
||||
this.virtualizedProcessService.Configuration.EnableBackgroundLoading = enabled && this.isProcessViewActive;
|
||||
this.virtualizedProcessService.Configuration.EnableBackgroundLoading = this.ShouldPreloadVirtualizedBatches();
|
||||
|
||||
if (!enabled)
|
||||
{
|
||||
@@ -1855,23 +1997,54 @@ namespace ThreadPilot.ViewModels
|
||||
return;
|
||||
}
|
||||
|
||||
_ = System.Windows.Application.Current.Dispatcher.InvokeAsync(async () =>
|
||||
{
|
||||
if (this.isUiRefreshPaused)
|
||||
TaskSafety.FireAndForget(
|
||||
InvokeOnUiAsync(async () =>
|
||||
{
|
||||
return;
|
||||
}
|
||||
if (this.isUiRefreshPaused)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
this.ClearStatus();
|
||||
await this.RefreshProcessesCommand.ExecuteAsync(null);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
this.Logger.LogDebug(ex, "Immediate process refresh after resume failed");
|
||||
}
|
||||
});
|
||||
try
|
||||
{
|
||||
this.ClearStatus();
|
||||
await this.RefreshProcessesCommand.ExecuteAsync(null);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
this.Logger.LogDebug(ex, "Immediate process refresh after resume failed");
|
||||
}
|
||||
}),
|
||||
ex => this.Logger.LogDebug(ex, "Immediate process refresh dispatch after resume failed"));
|
||||
}
|
||||
|
||||
partial void OnIsProcessListLockedChanged(bool value)
|
||||
{
|
||||
this.SetUiRefreshEnabled(!value, refreshImmediately: !value);
|
||||
|
||||
_ = this.LogUserActionAsync(
|
||||
"ProcessListLockChanged",
|
||||
value ? "Lock process list enabled." : "Lock process list disabled.");
|
||||
}
|
||||
|
||||
private bool ShouldRunProcessUiRefresh()
|
||||
{
|
||||
return this.isProcessViewActive && !this.isUiRefreshPaused && !this.IsProcessListLocked;
|
||||
}
|
||||
|
||||
private bool ShouldPreloadVirtualizedBatches()
|
||||
{
|
||||
return this.IsVirtualizationEnabled
|
||||
&& this.isVirtualizedPreloadAllowedByPolicy
|
||||
&& this.ShouldRunProcessUiRefresh()
|
||||
&& !this.IsProcessListLocked;
|
||||
}
|
||||
|
||||
private Task PreloadNextBatchIfAllowedAsync(int currentBatchIndex)
|
||||
{
|
||||
return this.ShouldPreloadVirtualizedBatches()
|
||||
? this.virtualizedProcessService.PreloadNextBatchAsync(currentBatchIndex, this.ShowActiveApplicationsOnly)
|
||||
: Task.CompletedTask;
|
||||
}
|
||||
|
||||
partial void OnSearchTextChanged(string value)
|
||||
|
||||
@@ -54,6 +54,8 @@ namespace ThreadPilot.ViewModels
|
||||
private System.Timers.Timer? refreshTimer;
|
||||
private bool isUiRefreshPaused;
|
||||
private bool isProcessViewActive = true;
|
||||
private bool isVirtualizedPreloadAllowedByPolicy = true;
|
||||
private int isRefreshProcessesInProgress;
|
||||
private readonly ThrottledRefreshCoordinator searchRefreshCoordinator;
|
||||
private readonly ThrottledRefreshCoordinator filterRefreshCoordinator;
|
||||
private bool isApplyingFilter;
|
||||
@@ -147,6 +149,9 @@ namespace ThreadPilot.ViewModels
|
||||
[ObservableProperty]
|
||||
private bool isRegistryPriorityEnabled = false;
|
||||
|
||||
[ObservableProperty]
|
||||
private bool isProcessListLocked = false;
|
||||
|
||||
// PERFORMANCE IMPROVEMENT: Progressive loading support
|
||||
[ObservableProperty]
|
||||
private double loadingProgress = 0.0;
|
||||
@@ -186,13 +191,14 @@ namespace ThreadPilot.ViewModels
|
||||
IProcessAffinityApplyCoordinator? processAffinityApplyCoordinator = null,
|
||||
ICpuTopologyProvider? cpuTopologyProvider = null,
|
||||
IEnhancedLoggingService? enhancedLoggingService = null,
|
||||
IActivityAuditService? activityAuditService = null,
|
||||
IProcessMemoryPriorityService? memoryPriorityService = null,
|
||||
IPersistentProcessRuleStore? persistentRuleStore = null,
|
||||
IPersistentProcessRuleMatcher? persistentRuleMatcher = null,
|
||||
IProcessRuleCreationService? processRuleCreationService = null,
|
||||
Action<string>? clipboardSetter = null,
|
||||
Action<string>? executableLocationOpener = null)
|
||||
: base(logger, enhancedLoggingService)
|
||||
: base(logger, enhancedLoggingService, activityAuditService)
|
||||
{
|
||||
this.processService = processService ?? throw new ArgumentNullException(nameof(processService));
|
||||
this.processFilterService = processFilterService ?? throw new ArgumentNullException(nameof(processFilterService));
|
||||
|
||||
@@ -51,6 +51,7 @@ namespace ThreadPilot.ViewModels
|
||||
private readonly GitHubUpdateChecker gitHubUpdateChecker;
|
||||
private ApplicationSettingsModel savedSettingsSnapshot;
|
||||
private bool isSyncingFromService = false;
|
||||
private bool? appliedThemePreference;
|
||||
private string cachedDefaultPowerPlanGuid = string.Empty;
|
||||
private string cachedDefaultPowerPlanName = string.Empty;
|
||||
private static readonly JsonSerializerOptions ImportExportJsonOptions = new()
|
||||
@@ -105,8 +106,9 @@ namespace ThreadPilot.ViewModels
|
||||
IThemeService themeService,
|
||||
ISystemTrayService systemTrayService,
|
||||
GitHubUpdateChecker gitHubUpdateChecker,
|
||||
IEnhancedLoggingService? enhancedLoggingService = null)
|
||||
: base(logger, enhancedLoggingService)
|
||||
IEnhancedLoggingService? enhancedLoggingService = null,
|
||||
IActivityAuditService? activityAuditService = null)
|
||||
: base(logger, enhancedLoggingService, activityAuditService)
|
||||
{
|
||||
this.settingsService = settingsService ?? throw new ArgumentNullException(nameof(settingsService));
|
||||
this.notificationService = notificationService ?? throw new ArgumentNullException(nameof(notificationService));
|
||||
@@ -132,6 +134,7 @@ namespace ThreadPilot.ViewModels
|
||||
// Initialize with current settings
|
||||
this.settings = (ApplicationSettingsModel)this.settingsService.Settings.Clone();
|
||||
this.savedSettingsSnapshot = (ApplicationSettingsModel)this.settings.Clone();
|
||||
this.appliedThemePreference = this.settings.UseDarkTheme;
|
||||
|
||||
// Initialize commands
|
||||
this.SaveSettingsCommand = new AsyncRelayCommand(this.SaveSettingsAsync);
|
||||
@@ -148,11 +151,15 @@ namespace ThreadPilot.ViewModels
|
||||
// Keep viewmodel in sync with persisted settings
|
||||
this.settingsService.SettingsChanged += this.OnSettingsServiceSettingsChanged;
|
||||
|
||||
// Ensure we load the latest persisted settings on startup
|
||||
_ = System.Windows.Application.Current.Dispatcher.InvokeAsync(async () => await this.RefreshSettingsAsync());
|
||||
var dispatcher = System.Windows.Application.Current?.Dispatcher;
|
||||
if (dispatcher != null)
|
||||
{
|
||||
// Ensure we load the latest persisted settings on startup.
|
||||
_ = dispatcher.InvokeAsync(async () => await this.RefreshSettingsAsync());
|
||||
|
||||
// Initialize data - marshal to UI thread to prevent cross-thread access exceptions
|
||||
_ = System.Windows.Application.Current.Dispatcher.InvokeAsync(async () => await this.RefreshPowerPlansAsync());
|
||||
// Initialize data - marshal to UI thread to prevent cross-thread access exceptions.
|
||||
_ = dispatcher.InvokeAsync(async () => await this.RefreshPowerPlansAsync());
|
||||
}
|
||||
|
||||
this.Logger.LogInformation("Settings ViewModel initialized");
|
||||
}
|
||||
@@ -167,15 +174,52 @@ namespace ThreadPilot.ViewModels
|
||||
if (string.Equals(e.PropertyName, nameof(ApplicationSettingsModel.UseDarkTheme), StringComparison.Ordinal))
|
||||
{
|
||||
this.Settings.HasUserThemePreference = true;
|
||||
this.UpdatePendingChangesState();
|
||||
this.ApplyThemePreference(this.Settings.UseDarkTheme, logUserAction: true);
|
||||
return;
|
||||
}
|
||||
|
||||
var useDarkTheme = this.Settings.UseDarkTheme;
|
||||
this.themeService.ApplyTheme(useDarkTheme);
|
||||
this.systemTrayService.ApplyTheme(useDarkTheme);
|
||||
if (string.Equals(e.PropertyName, nameof(ApplicationSettingsModel.ApplyPersistentRulesOnProcessStart), StringComparison.Ordinal))
|
||||
{
|
||||
this.UpdatePendingChangesState();
|
||||
var state = this.Settings.ApplyPersistentRulesOnProcessStart ? "enabled" : "disabled";
|
||||
_ = this.LogUserActionAsync(
|
||||
"SettingsChanged",
|
||||
$"[Settings] Apply saved rules at process start {state}.");
|
||||
return;
|
||||
}
|
||||
|
||||
this.UpdatePendingChangesState();
|
||||
}
|
||||
|
||||
private void ApplyThemePreference(bool useDarkTheme, bool logUserAction)
|
||||
{
|
||||
if (this.appliedThemePreference == useDarkTheme)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var themeName = useDarkTheme ? "Dark" : "Light";
|
||||
try
|
||||
{
|
||||
this.themeService.ApplyTheme(useDarkTheme);
|
||||
this.systemTrayService.ApplyTheme(useDarkTheme);
|
||||
this.appliedThemePreference = useDarkTheme;
|
||||
this.StatusMessage = $"Theme changed to {themeName}.";
|
||||
|
||||
if (logUserAction)
|
||||
{
|
||||
_ = this.LogUserActionAsync("ThemeChanged", $"Theme changed to {themeName}");
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
this.StatusMessage = $"Failed to change theme to {themeName}.";
|
||||
this.Logger.LogError(ex, "Failed to apply theme preference {ThemeName}", themeName);
|
||||
_ = this.LogUserActionAsync("ThemeChangeFailed", $"Failed to change theme to {themeName}: {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
partial void OnHasUnsavedChangesChanged(bool value)
|
||||
{
|
||||
OnPropertyChanged(nameof(CanSaveSettings));
|
||||
@@ -234,8 +278,7 @@ namespace ThreadPilot.ViewModels
|
||||
this.isSyncingFromService = true;
|
||||
this.Settings.UseDarkTheme = useDarkTheme;
|
||||
this.isSyncingFromService = false;
|
||||
this.themeService.ApplyTheme(useDarkTheme);
|
||||
this.systemTrayService.ApplyTheme(useDarkTheme);
|
||||
this.ApplyThemePreference(useDarkTheme, logUserAction: false);
|
||||
|
||||
// Update monitoring services with new settings
|
||||
this.processMonitorManagerService.UpdateSettings();
|
||||
@@ -257,6 +300,7 @@ namespace ThreadPilot.ViewModels
|
||||
"Application settings have been saved successfully");
|
||||
}
|
||||
|
||||
await this.LogUserActionAsync("SettingsChanged", "Settings saved and applied");
|
||||
this.Logger.LogInformation("Settings saved successfully");
|
||||
}
|
||||
catch (Exception ex)
|
||||
@@ -271,6 +315,7 @@ namespace ThreadPilot.ViewModels
|
||||
"Settings Error",
|
||||
"Failed to save settings",
|
||||
ex);
|
||||
await this.LogUserActionAsync("SettingsChangeFailed", $"Failed to save settings: {ex.Message}");
|
||||
}
|
||||
finally
|
||||
{
|
||||
@@ -291,12 +336,14 @@ namespace ThreadPilot.ViewModels
|
||||
this.UpdatePendingChangesState();
|
||||
this.StatusMessage = "Settings reset to defaults (not saved yet)";
|
||||
|
||||
await this.LogUserActionAsync("SettingsChanged", "Settings reset to defaults pending save");
|
||||
this.Logger.LogInformation("Settings reset to defaults");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
this.StatusMessage = $"Error resetting settings: {ex.Message}";
|
||||
this.Logger.LogError(ex, "Error resetting settings");
|
||||
await this.LogUserActionAsync("SettingsChangeFailed", $"Failed to reset settings: {ex.Message}");
|
||||
}
|
||||
finally
|
||||
{
|
||||
@@ -348,6 +395,7 @@ namespace ThreadPilot.ViewModels
|
||||
$"Settings and rules exported to {Path.GetFileName(saveDialog.FileName)}");
|
||||
|
||||
this.Logger.LogInformation("Configuration bundle exported to {Path}", saveDialog.FileName);
|
||||
await this.LogUserActionAsync("SettingsChanged", "Configuration exported", Path.GetFileName(saveDialog.FileName));
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
@@ -358,6 +406,7 @@ namespace ThreadPilot.ViewModels
|
||||
"Export Error",
|
||||
"Failed to export settings",
|
||||
ex);
|
||||
await this.LogUserActionAsync("SettingsChangeFailed", $"Failed to export settings: {ex.Message}");
|
||||
}
|
||||
finally
|
||||
{
|
||||
@@ -411,6 +460,7 @@ namespace ThreadPilot.ViewModels
|
||||
$"Settings and rules imported from {Path.GetFileName(importPath)}");
|
||||
|
||||
this.Logger.LogInformation("Configuration bundle imported from {Path}", importPath);
|
||||
await this.LogUserActionAsync("SettingsChanged", "Configuration bundle imported", Path.GetFileName(importPath));
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -426,6 +476,7 @@ namespace ThreadPilot.ViewModels
|
||||
NotificationType.Information);
|
||||
|
||||
this.Logger.LogInformation("Legacy settings imported from {Path}", importPath);
|
||||
await this.LogUserActionAsync("SettingsChanged", "Legacy settings imported", Path.GetFileName(importPath));
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
@@ -436,6 +487,7 @@ namespace ThreadPilot.ViewModels
|
||||
"Import Error",
|
||||
"Failed to import configuration",
|
||||
ex);
|
||||
await this.LogUserActionAsync("SettingsChangeFailed", $"Failed to import settings: {ex.Message}");
|
||||
}
|
||||
finally
|
||||
{
|
||||
@@ -496,8 +548,7 @@ namespace ThreadPilot.ViewModels
|
||||
this.isSyncingFromService = true;
|
||||
this.Settings.UseDarkTheme = useDarkTheme;
|
||||
this.isSyncingFromService = false;
|
||||
this.themeService.ApplyTheme(useDarkTheme);
|
||||
this.systemTrayService.ApplyTheme(useDarkTheme);
|
||||
this.ApplyThemePreference(useDarkTheme, logUserAction: false);
|
||||
|
||||
this.SetSavedSettingsSnapshot(this.Settings);
|
||||
this.StatusMessage = "Settings loaded";
|
||||
@@ -754,4 +805,3 @@ namespace ThreadPilot.ViewModels
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -45,8 +45,10 @@ namespace ThreadPilot.ViewModels
|
||||
public SystemTweaksViewModel(
|
||||
ISystemTweaksService systemTweaksService,
|
||||
INotificationService notificationService,
|
||||
ILogger<SystemTweaksViewModel> logger)
|
||||
: base(logger, null)
|
||||
ILogger<SystemTweaksViewModel> logger,
|
||||
IEnhancedLoggingService? enhancedLoggingService = null,
|
||||
IActivityAuditService? activityAuditService = null)
|
||||
: base(logger, enhancedLoggingService, activityAuditService)
|
||||
{
|
||||
this.systemTweaksService = systemTweaksService;
|
||||
this.notificationService = notificationService;
|
||||
@@ -232,7 +234,7 @@ namespace ThreadPilot.ViewModels
|
||||
|
||||
try
|
||||
{
|
||||
await System.Windows.Application.Current.Dispatcher.InvokeAsync(() =>
|
||||
await InvokeOnUiAsync(() =>
|
||||
{
|
||||
this.SetStatus($"Toggling {item.Name}...");
|
||||
});
|
||||
@@ -254,7 +256,7 @@ namespace ThreadPilot.ViewModels
|
||||
if (success)
|
||||
{
|
||||
await this.UpdateTweakItemStatusAsync(item);
|
||||
await System.Windows.Application.Current.Dispatcher.InvokeAsync(() =>
|
||||
await InvokeOnUiAsync(() =>
|
||||
{
|
||||
this.SetStatus($"{item.Name} {(newState ? "enabled" : "disabled")} successfully");
|
||||
});
|
||||
@@ -262,10 +264,14 @@ namespace ThreadPilot.ViewModels
|
||||
await this.notificationService.ShowSuccessNotificationAsync(
|
||||
"System Tweak Updated",
|
||||
$"{item.Name} has been {(newState ? "enabled" : "disabled")}");
|
||||
await this.LogUserActionAsync(
|
||||
"SystemTweakApplied",
|
||||
$"{item.Name} {(newState ? "enabled" : "disabled")}",
|
||||
item.TweakType.ToString());
|
||||
}
|
||||
else
|
||||
{
|
||||
await System.Windows.Application.Current.Dispatcher.InvokeAsync(() =>
|
||||
await InvokeOnUiAsync(() =>
|
||||
{
|
||||
this.SetError($"Failed to toggle {item.Name}", null);
|
||||
});
|
||||
@@ -273,18 +279,38 @@ namespace ThreadPilot.ViewModels
|
||||
await this.notificationService.ShowErrorNotificationAsync(
|
||||
"System Tweak Failed",
|
||||
$"Failed to {(newState ? "enable" : "disable")} {item.Name}");
|
||||
await this.LogUserActionAsync(
|
||||
"SystemTweakFailed",
|
||||
$"Failed to {(newState ? "enable" : "disable")} {item.Name}",
|
||||
item.TweakType.ToString());
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
await System.Windows.Application.Current.Dispatcher.InvokeAsync(() =>
|
||||
await InvokeOnUiAsync(() =>
|
||||
{
|
||||
this.SetError($"Error toggling {item.Name}", ex);
|
||||
});
|
||||
this.Logger.LogError(ex, "Error toggling tweak {TweakName}", item.Name);
|
||||
await this.LogUserActionAsync(
|
||||
"SystemTweakFailed",
|
||||
$"Error toggling {item.Name}: {ex.Message}",
|
||||
item.TweakType.ToString());
|
||||
}
|
||||
}
|
||||
|
||||
private static Task InvokeOnUiAsync(Action action)
|
||||
{
|
||||
var dispatcher = System.Windows.Application.Current?.Dispatcher;
|
||||
if (dispatcher == null)
|
||||
{
|
||||
action();
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
return dispatcher.InvokeAsync(action).Task;
|
||||
}
|
||||
|
||||
private void OnTweakStatusChanged(object? sender, TweakStatusChangedEventArgs e)
|
||||
{
|
||||
try
|
||||
@@ -336,4 +362,3 @@ namespace ThreadPilot.ViewModels
|
||||
public IAsyncRelayCommand<SystemTweakItem>? ToggleCommand { get; set; }
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+23
-23
@@ -63,8 +63,8 @@
|
||||
|
||||
<!-- Standardized Header -->
|
||||
<StackPanel Grid.Row="0" Margin="0,0,0,16">
|
||||
<TextBlock Text="Activity Logs" Style="{StaticResource PageTitleTextStyle}" Margin="0,0,0,4"/>
|
||||
<TextBlock Text="View and filter application logs and system events" Style="{StaticResource PageSubtitleTextStyle}"/>
|
||||
<TextBlock Text="ThreadPilot Activity" Style="{StaticResource PageTitleTextStyle}" Margin="0,0,0,4"/>
|
||||
<TextBlock Text="Shows actions performed by ThreadPilot, including applied rules, affinity changes, priority changes, power plan changes, settings changes, tweaks, optimizations, and safe failure messages." Style="{StaticResource PageSubtitleTextStyle}" TextWrapping="Wrap"/>
|
||||
</StackPanel>
|
||||
|
||||
<!-- Filter and Control Panel -->
|
||||
@@ -133,9 +133,9 @@
|
||||
</Button.IsEnabled>
|
||||
</Button>
|
||||
<Button Content="Clear Display" Command="{Binding ClearLogsCommand}" Margin="5,0"/>
|
||||
<Button Content="Export" Command="{Binding ExportLogsCommand}" Margin="5,0"/>
|
||||
<Button Content="Cleanup Old" Command="{Binding CleanupOldLogsCommand}" Margin="5,0"/>
|
||||
<Button Content="Open Directory" Command="{Binding OpenLogDirectoryCommand}" Margin="5,0"/>
|
||||
<Button Content="Export Activity" Command="{Binding ExportLogsCommand}" Margin="5,0"/>
|
||||
<Button Content="Cleanup Diagnostic Files" Command="{Binding CleanupOldLogsCommand}" Margin="5,0"/>
|
||||
<Button Content="Open Diagnostic Folder" Command="{Binding OpenLogDirectoryCommand}" Margin="5,0"/>
|
||||
</StackPanel>
|
||||
</Grid>
|
||||
</Border>
|
||||
@@ -162,10 +162,10 @@
|
||||
</GridViewColumn.CellTemplate>
|
||||
</GridViewColumn>
|
||||
|
||||
<GridViewColumn Header="Level" Width="80">
|
||||
<GridViewColumn Header="Status" Width="90">
|
||||
<GridViewColumn.CellTemplate>
|
||||
<DataTemplate>
|
||||
<TextBlock Text="{Binding Level}"
|
||||
<TextBlock Text="{Binding Status}"
|
||||
Foreground="{Binding LevelColor}"
|
||||
Style="{StaticResource LogLevelTextStyle}"/>
|
||||
</DataTemplate>
|
||||
@@ -188,17 +188,17 @@
|
||||
</GridViewColumn.CellTemplate>
|
||||
</GridViewColumn>
|
||||
|
||||
<GridViewColumn Header="Exception" Width="60">
|
||||
<GridViewColumn Header="Details" Width="70">
|
||||
<GridViewColumn.CellTemplate>
|
||||
<DataTemplate>
|
||||
<TextBlock Foreground="{DynamicResource ErrorTextBrush}" FontWeight="Bold">
|
||||
<TextBlock Foreground="{DynamicResource ErrorTextBrush}" FontWeight="SemiBold">
|
||||
<TextBlock.Style>
|
||||
<Style TargetType="TextBlock">
|
||||
<Style.Triggers>
|
||||
<DataTrigger Binding="{Binding HasException}" Value="True">
|
||||
<DataTrigger Binding="{Binding HasDetails}" Value="True">
|
||||
<Setter Property="Text" Value="!"/>
|
||||
</DataTrigger>
|
||||
<DataTrigger Binding="{Binding HasException}" Value="False">
|
||||
<DataTrigger Binding="{Binding HasDetails}" Value="False">
|
||||
<Setter Property="Text" Value=""/>
|
||||
</DataTrigger>
|
||||
</Style.Triggers>
|
||||
@@ -261,11 +261,11 @@
|
||||
<GridSplitter Grid.Row="3" Height="5" HorizontalAlignment="Stretch"
|
||||
Background="{DynamicResource SurfaceStrokeColorDefaultBrush}" ResizeBehavior="PreviousAndNext"/>
|
||||
|
||||
<!-- Log Entry Details -->
|
||||
<!-- Activity Details -->
|
||||
<Border Grid.Row="4" Background="{DynamicResource SolidBackgroundFillColorBaseBrush}" BorderBrush="{DynamicResource SurfaceStrokeColorDefaultBrush}" BorderThickness="0,1,0,0">
|
||||
<ScrollViewer VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Auto">
|
||||
<StackPanel Margin="16" DataContext="{Binding SelectedLogEntry}">
|
||||
<TextBlock Text="Log Entry Details" FontWeight="SemiBold" FontSize="16" Margin="0,0,0,16"/>
|
||||
<TextBlock Text="Activity Details" FontWeight="SemiBold" FontSize="16" Margin="0,0,0,16"/>
|
||||
|
||||
<Grid>
|
||||
<Grid.Style>
|
||||
@@ -293,8 +293,8 @@
|
||||
<TextBlock Grid.Row="0" Grid.Column="0" Text="Timestamp:" FontWeight="SemiBold" Margin="0,0,10,5"/>
|
||||
<TextBlock Grid.Row="0" Grid.Column="1" Text="{Binding FormattedTimestamp}" Margin="0,0,0,5"/>
|
||||
|
||||
<TextBlock Grid.Row="1" Grid.Column="0" Text="Level:" FontWeight="SemiBold" Margin="0,0,10,5"/>
|
||||
<TextBlock Grid.Row="1" Grid.Column="1" Text="{Binding Level}"
|
||||
<TextBlock Grid.Row="1" Grid.Column="0" Text="Status:" FontWeight="SemiBold" Margin="0,0,10,5"/>
|
||||
<TextBlock Grid.Row="1" Grid.Column="1" Text="{Binding Status}"
|
||||
Foreground="{Binding LevelColor}" FontWeight="SemiBold" Margin="0,0,0,5"/>
|
||||
|
||||
<TextBlock Grid.Row="2" Grid.Column="0" Text="Category:" FontWeight="SemiBold" Margin="0,0,10,5"/>
|
||||
@@ -305,25 +305,25 @@
|
||||
IsReadOnly="True" TextWrapping="Wrap" Background="Transparent"
|
||||
BorderThickness="0" Margin="0,0,0,10"/>
|
||||
|
||||
<TextBlock Grid.Row="4" Grid.Column="0" Text="Exception:" FontWeight="SemiBold" Margin="0,0,10,5"
|
||||
<TextBlock Grid.Row="4" Grid.Column="0" Text="Details:" FontWeight="SemiBold" Margin="0,0,10,5"
|
||||
VerticalAlignment="Top">
|
||||
<TextBlock.Style>
|
||||
<Style TargetType="TextBlock">
|
||||
<Style.Triggers>
|
||||
<DataTrigger Binding="{Binding HasException}" Value="False">
|
||||
<DataTrigger Binding="{Binding HasDetails}" Value="False">
|
||||
<Setter Property="Visibility" Value="Collapsed"/>
|
||||
</DataTrigger>
|
||||
</Style.Triggers>
|
||||
</Style>
|
||||
</TextBlock.Style>
|
||||
</TextBlock>
|
||||
<TextBox Grid.Row="4" Grid.Column="1" Text="{Binding Exception, Mode=OneWay}"
|
||||
IsReadOnly="True" TextWrapping="Wrap" Background="{DynamicResource ErrorBackgroundBrush}"
|
||||
BorderThickness="1" BorderBrush="{DynamicResource ErrorBorderBrush}" Margin="0,0,0,10">
|
||||
<TextBox Grid.Row="4" Grid.Column="1" Text="{Binding Details, Mode=OneWay}"
|
||||
IsReadOnly="True" TextWrapping="Wrap" Background="Transparent"
|
||||
BorderThickness="0" Margin="0,0,0,10">
|
||||
<TextBox.Style>
|
||||
<Style TargetType="TextBox">
|
||||
<Style.Triggers>
|
||||
<DataTrigger Binding="{Binding HasException}" Value="False">
|
||||
<DataTrigger Binding="{Binding HasDetails}" Value="False">
|
||||
<Setter Property="Visibility" Value="Collapsed"/>
|
||||
</DataTrigger>
|
||||
</Style.Triggers>
|
||||
@@ -392,7 +392,7 @@
|
||||
|
||||
<!-- Settings Panel -->
|
||||
<StackPanel Grid.Column="1" Orientation="Horizontal">
|
||||
<CheckBox Content="Debug Logging" IsChecked="{Binding EnableDebugLogging}"
|
||||
<CheckBox Content="Debug Diagnostics" IsChecked="{Binding EnableDebugLogging}"
|
||||
VerticalAlignment="Center" Margin="0,0,15,0"/>
|
||||
|
||||
<TextBlock Text="Max Size (MB):" VerticalAlignment="Center" Margin="0,0,5,0"/>
|
||||
@@ -407,4 +407,4 @@
|
||||
</Grid>
|
||||
</Border>
|
||||
</Grid>
|
||||
</UserControl>
|
||||
</UserControl>
|
||||
|
||||
+50
-4
@@ -6,6 +6,47 @@
|
||||
mc:Ignorable="d"
|
||||
d:DesignHeight="600" d:DesignWidth="900">
|
||||
|
||||
<UserControl.Resources>
|
||||
<Style x:Key="MaskListItemStyle" TargetType="{x:Type ListBoxItem}">
|
||||
<Setter Property="Background" Value="Transparent"/>
|
||||
<Setter Property="BorderBrush" Value="Transparent"/>
|
||||
<Setter Property="BorderThickness" Value="1"/>
|
||||
<Setter Property="Foreground" Value="{DynamicResource TextFillColorPrimaryBrush}"/>
|
||||
<Setter Property="HorizontalContentAlignment" Value="Stretch"/>
|
||||
<Setter Property="Padding" Value="4"/>
|
||||
<Setter Property="Margin" Value="4"/>
|
||||
<Setter Property="Template">
|
||||
<Setter.Value>
|
||||
<ControlTemplate TargetType="{x:Type ListBoxItem}">
|
||||
<Border Background="{TemplateBinding Background}"
|
||||
BorderBrush="{TemplateBinding BorderBrush}"
|
||||
BorderThickness="{TemplateBinding BorderThickness}"
|
||||
CornerRadius="{DynamicResource StandardCardCornerRadius}"
|
||||
Padding="{TemplateBinding Padding}"
|
||||
SnapsToDevicePixels="True">
|
||||
<ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
|
||||
VerticalAlignment="{TemplateBinding VerticalContentAlignment}"
|
||||
TextElement.Foreground="{TemplateBinding Foreground}"
|
||||
SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"/>
|
||||
</Border>
|
||||
</ControlTemplate>
|
||||
</Setter.Value>
|
||||
</Setter>
|
||||
<Style.Triggers>
|
||||
<Trigger Property="IsMouseOver" Value="True">
|
||||
<Setter Property="Background" Value="{DynamicResource QuietRowHoverBackgroundBrush}"/>
|
||||
<Setter Property="BorderBrush" Value="{DynamicResource BorderSubtleBrush}"/>
|
||||
</Trigger>
|
||||
<Trigger Property="IsSelected" Value="True">
|
||||
<Setter Property="Background" Value="{DynamicResource MaskSelectedListBackgroundBrush}"/>
|
||||
<Setter Property="BorderBrush" Value="{DynamicResource MaskSelectedBorderBrush}"/>
|
||||
<Setter Property="BorderThickness" Value="2"/>
|
||||
<Setter Property="Foreground" Value="{DynamicResource TextFillColorPrimaryBrush}"/>
|
||||
</Trigger>
|
||||
</Style.Triggers>
|
||||
</Style>
|
||||
</UserControl.Resources>
|
||||
|
||||
<Grid Margin="12">
|
||||
<Grid.RowDefinitions>
|
||||
<RowDefinition Height="Auto"/>
|
||||
@@ -42,6 +83,7 @@
|
||||
CornerRadius="{DynamicResource StandardCardCornerRadius}">
|
||||
<ListBox ItemsSource="{Binding CoreMasks}"
|
||||
SelectedItem="{Binding SelectedCoreMask, Mode=TwoWay}"
|
||||
ItemContainerStyle="{StaticResource MaskListItemStyle}"
|
||||
Background="{DynamicResource CardSurfaceBrush}"
|
||||
BorderThickness="0">
|
||||
<ListBox.ItemTemplate>
|
||||
@@ -139,22 +181,26 @@
|
||||
</ItemsControl.ItemsPanel>
|
||||
<ItemsControl.ItemTemplate>
|
||||
<DataTemplate>
|
||||
<Border BorderBrush="{DynamicResource BorderSubtleBrush}" BorderThickness="1"
|
||||
<Border BorderBrush="{DynamicResource BorderSubtleBrush}"
|
||||
Margin="2" Padding="4" CornerRadius="4">
|
||||
<Border.Style>
|
||||
<Style TargetType="Border">
|
||||
<Setter Property="Background" Value="{DynamicResource QuietRowBackgroundBrush}"/>
|
||||
<Setter Property="BorderBrush" Value="{DynamicResource BorderSubtleBrush}"/>
|
||||
<Setter Property="BorderThickness" Value="1"/>
|
||||
<Style.Triggers>
|
||||
<DataTrigger Binding="{Binding IsSelected}" Value="True">
|
||||
<Setter Property="Background" Value="{DynamicResource SoftSelectionBackgroundBrush}"/>
|
||||
<Setter Property="BorderBrush" Value="{DynamicResource SoftSelectionBorderBrush}"/>
|
||||
<Setter Property="Background" Value="{DynamicResource MaskSelectedBackgroundBrush}"/>
|
||||
<Setter Property="BorderBrush" Value="{DynamicResource MaskSelectedBorderBrush}"/>
|
||||
<Setter Property="BorderThickness" Value="2"/>
|
||||
</DataTrigger>
|
||||
</Style.Triggers>
|
||||
</Style>
|
||||
</Border.Style>
|
||||
<CheckBox IsChecked="{Binding IsSelected, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
|
||||
FontSize="10" MinWidth="60">
|
||||
FontSize="11"
|
||||
Foreground="{DynamicResource TextFillColorPrimaryBrush}"
|
||||
MinWidth="60">
|
||||
<CheckBox.Content>
|
||||
<TextBlock>
|
||||
<Run Text="CPU "/>
|
||||
|
||||
@@ -31,13 +31,13 @@
|
||||
|
||||
<Style x:Key="MetricValueTextStyle" TargetType="TextBlock">
|
||||
<Setter Property="FontSize" Value="22"/>
|
||||
<Setter Property="FontWeight" Value="Bold"/>
|
||||
<Setter Property="FontWeight" Value="SemiBold"/>
|
||||
<Setter Property="Foreground" Value="{DynamicResource TextPrimaryBrush}"/>
|
||||
</Style>
|
||||
|
||||
<Style x:Key="AccentValueTextStyle" TargetType="TextBlock">
|
||||
<Setter Property="FontSize" Value="22"/>
|
||||
<Setter Property="FontWeight" Value="Bold"/>
|
||||
<Setter Property="FontWeight" Value="SemiBold"/>
|
||||
<Setter Property="Foreground" Value="{DynamicResource AccentBrush}"/>
|
||||
</Style>
|
||||
</UserControl.Resources>
|
||||
|
||||
+96
-43
@@ -38,26 +38,27 @@
|
||||
</Grid.RowDefinitions>
|
||||
|
||||
<Grid Grid.Row="0" Margin="0,0,0,12">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="*"/>
|
||||
<ColumnDefinition Width="Auto"/>
|
||||
<ColumnDefinition Width="8"/>
|
||||
<ColumnDefinition Width="Auto"/>
|
||||
</Grid.ColumnDefinitions>
|
||||
<TextBlock Grid.Column="0"
|
||||
<Grid.RowDefinitions>
|
||||
<RowDefinition Height="Auto"/>
|
||||
<RowDefinition Height="Auto"/>
|
||||
</Grid.RowDefinitions>
|
||||
<TextBlock Grid.Row="0"
|
||||
Text="Select the Windows plan to make active."
|
||||
Foreground="{DynamicResource TextFillColorSecondaryBrush}"
|
||||
VerticalAlignment="Center"/>
|
||||
<Button Grid.Column="1"
|
||||
Command="{Binding SetActivePlanCommand}"
|
||||
Content="Set as Active Windows Plan"
|
||||
Padding="10,5"
|
||||
ToolTip="Change the active Windows power plan to the selected plan"/>
|
||||
<Button Grid.Column="3"
|
||||
Command="{Binding LoadPowerPlansCommand}"
|
||||
Content="Refresh Plans"
|
||||
Padding="10,5"
|
||||
ToolTip="Refresh the list of available power plans"/>
|
||||
TextWrapping="Wrap"
|
||||
TextTrimming="CharacterEllipsis"
|
||||
ToolTip="Select the Windows plan to make active."/>
|
||||
<WrapPanel Grid.Row="1" Margin="0,8,0,0">
|
||||
<Button Command="{Binding SetActivePlanCommand}"
|
||||
Content="Set as Active Windows Plan"
|
||||
Padding="10,5"
|
||||
Margin="0,0,8,0"
|
||||
ToolTip="Change the active Windows power plan to the selected plan"/>
|
||||
<Button Command="{Binding LoadPowerPlansCommand}"
|
||||
Content="Refresh Plans"
|
||||
Padding="10,5"
|
||||
ToolTip="Refresh the list of available power plans"/>
|
||||
</WrapPanel>
|
||||
</Grid>
|
||||
|
||||
<ui:ListView Grid.Row="1"
|
||||
@@ -66,15 +67,66 @@
|
||||
Background="{DynamicResource QuietRowBackgroundBrush}"
|
||||
BorderBrush="{DynamicResource BorderSubtleBrush}"
|
||||
Foreground="{DynamicResource TextFillColorPrimaryBrush}">
|
||||
<ui:ListView.ItemContainerStyle>
|
||||
<Style TargetType="ListViewItem">
|
||||
<Setter Property="Tag" Value="{Binding DataContext, RelativeSource={RelativeSource AncestorType=ListView}}"/>
|
||||
<Setter Property="ContextMenu">
|
||||
<Setter.Value>
|
||||
<ContextMenu DataContext="{Binding PlacementTarget.Tag, RelativeSource={RelativeSource Self}}">
|
||||
<MenuItem Header="Delete"
|
||||
Command="{Binding DeletePowerPlanCommand}"
|
||||
CommandParameter="{Binding PlacementTarget.DataContext, RelativeSource={RelativeSource AncestorType=ContextMenu}}"/>
|
||||
</ContextMenu>
|
||||
</Setter.Value>
|
||||
</Setter>
|
||||
</Style>
|
||||
</ui:ListView.ItemContainerStyle>
|
||||
<ui:ListView.ItemTemplate>
|
||||
<DataTemplate>
|
||||
<StackPanel Margin="5">
|
||||
<TextBlock Text="{Binding Name}"
|
||||
FontWeight="{Binding IsActive, Converter={StaticResource BoolToFontWeightConverter}}"/>
|
||||
<TextBlock Text="{Binding Guid}"
|
||||
Foreground="{DynamicResource TextFillColorSecondaryBrush}"
|
||||
FontSize="11"/>
|
||||
</StackPanel>
|
||||
<Border Margin="2"
|
||||
Padding="8"
|
||||
BorderThickness="4,1,1,1"
|
||||
CornerRadius="6">
|
||||
<Border.Style>
|
||||
<Style TargetType="Border">
|
||||
<Setter Property="Background" Value="Transparent"/>
|
||||
<Setter Property="BorderBrush" Value="{DynamicResource BorderSubtleBrush}"/>
|
||||
<Style.Triggers>
|
||||
<DataTrigger Binding="{Binding IsActive}" Value="True">
|
||||
<Setter Property="Background" Value="{DynamicResource SoftSelectionBackgroundBrush}"/>
|
||||
<Setter Property="BorderBrush" Value="{DynamicResource AccentBrush}"/>
|
||||
</DataTrigger>
|
||||
</Style.Triggers>
|
||||
</Style>
|
||||
</Border.Style>
|
||||
<Grid>
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="*"/>
|
||||
<ColumnDefinition Width="8"/>
|
||||
<ColumnDefinition Width="Auto"/>
|
||||
</Grid.ColumnDefinitions>
|
||||
<StackPanel Grid.Column="0">
|
||||
<TextBlock Text="{Binding Name}"
|
||||
FontWeight="{Binding IsActive, Converter={StaticResource BoolToFontWeightConverter}}"
|
||||
TextTrimming="CharacterEllipsis"/>
|
||||
<TextBlock Text="{Binding Guid}"
|
||||
Foreground="{DynamicResource TextFillColorSecondaryBrush}"
|
||||
FontSize="11"
|
||||
TextTrimming="CharacterEllipsis"/>
|
||||
</StackPanel>
|
||||
<Border Grid.Column="2"
|
||||
Background="{DynamicResource AccentFillColorDefaultBrush}"
|
||||
CornerRadius="4"
|
||||
Padding="8,2"
|
||||
VerticalAlignment="Top"
|
||||
Visibility="{Binding IsActive, Converter={StaticResource BoolToVisibilityConverter}}">
|
||||
<TextBlock Text="Active"
|
||||
FontSize="11"
|
||||
FontWeight="SemiBold"
|
||||
Foreground="{DynamicResource TextOnAccentFillColorPrimaryBrush}"/>
|
||||
</Border>
|
||||
</Grid>
|
||||
</Border>
|
||||
</DataTemplate>
|
||||
</ui:ListView.ItemTemplate>
|
||||
</ui:ListView>
|
||||
@@ -92,26 +144,27 @@
|
||||
</Grid.RowDefinitions>
|
||||
|
||||
<Grid Grid.Row="0" Margin="0,0,0,12">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="*"/>
|
||||
<ColumnDefinition Width="Auto"/>
|
||||
<ColumnDefinition Width="8"/>
|
||||
<ColumnDefinition Width="Auto"/>
|
||||
</Grid.ColumnDefinitions>
|
||||
<TextBlock Grid.Column="0"
|
||||
<Grid.RowDefinitions>
|
||||
<RowDefinition Height="Auto"/>
|
||||
<RowDefinition Height="Auto"/>
|
||||
</Grid.RowDefinitions>
|
||||
<TextBlock Grid.Row="0"
|
||||
Text="Local .pow files ready to import into Windows."
|
||||
Foreground="{DynamicResource TextFillColorSecondaryBrush}"
|
||||
VerticalAlignment="Center"/>
|
||||
<Button Grid.Column="1"
|
||||
Command="{Binding ImportCustomPlanCommand}"
|
||||
Content="Import Selected .pow"
|
||||
Padding="10,5"
|
||||
ToolTip="Import the selected custom .pow file into Windows"/>
|
||||
<Button Grid.Column="3"
|
||||
Command="{Binding AddCustomPlanFileCommand}"
|
||||
Content="Add .pow File"
|
||||
Padding="10,5"
|
||||
ToolTip="Add a new custom power plan file to the custom library"/>
|
||||
TextWrapping="Wrap"
|
||||
TextTrimming="CharacterEllipsis"
|
||||
ToolTip="Local .pow files ready to import into Windows."/>
|
||||
<WrapPanel Grid.Row="1" Margin="0,8,0,0">
|
||||
<Button Command="{Binding ImportCustomPlanCommand}"
|
||||
Content="Import Selected .pow"
|
||||
Padding="10,5"
|
||||
Margin="0,0,8,0"
|
||||
ToolTip="Import the selected custom .pow file into Windows"/>
|
||||
<Button Command="{Binding AddCustomPlanFileCommand}"
|
||||
Content="Add .pow File"
|
||||
Padding="10,5"
|
||||
ToolTip="Add a new custom power plan file to the custom library"/>
|
||||
</WrapPanel>
|
||||
</Grid>
|
||||
|
||||
<ui:ListView Grid.Row="1"
|
||||
|
||||
+285
-28
@@ -23,6 +23,130 @@
|
||||
<sys:Double x:Key="ProcessFontMedium">14</sys:Double>
|
||||
<sys:Double x:Key="ProcessFontMediumSmall">12</sys:Double>
|
||||
<sys:Double x:Key="ProcessFontSmall">11</sys:Double>
|
||||
<Style x:Key="ProcessContextMenuItemStyle" TargetType="{x:Type MenuItem}" BasedOn="{x:Null}">
|
||||
<Setter Property="OverridesDefaultStyle" Value="True"/>
|
||||
<Setter Property="FontWeight" Value="Normal"/>
|
||||
<Setter Property="FontSize" Value="{DynamicResource BodyFontSize}"/>
|
||||
<Setter Property="Foreground" Value="{DynamicResource TextPrimaryBrush}"/>
|
||||
<Setter Property="Background" Value="Transparent"/>
|
||||
<Setter Property="BorderBrush" Value="Transparent"/>
|
||||
<Setter Property="Padding" Value="12,7"/>
|
||||
<Setter Property="MinWidth" Value="220"/>
|
||||
<Setter Property="SnapsToDevicePixels" Value="True"/>
|
||||
<Setter Property="Template">
|
||||
<Setter.Value>
|
||||
<ControlTemplate TargetType="{x:Type MenuItem}">
|
||||
<Border x:Name="MenuItemRoot"
|
||||
Background="{TemplateBinding Background}"
|
||||
BorderBrush="{TemplateBinding BorderBrush}"
|
||||
BorderThickness="0"
|
||||
SnapsToDevicePixels="True">
|
||||
<Grid MinWidth="{TemplateBinding MinWidth}">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="*"/>
|
||||
<ColumnDefinition Width="Auto"/>
|
||||
</Grid.ColumnDefinitions>
|
||||
|
||||
<ContentPresenter Grid.Column="0"
|
||||
Margin="{TemplateBinding Padding}"
|
||||
ContentSource="Header"
|
||||
RecognizesAccessKey="True"
|
||||
VerticalAlignment="Center"
|
||||
TextElement.Foreground="{TemplateBinding Foreground}"
|
||||
TextElement.FontSize="{TemplateBinding FontSize}"
|
||||
TextElement.FontWeight="{TemplateBinding FontWeight}"/>
|
||||
|
||||
<Path x:Name="SubmenuArrow"
|
||||
Grid.Column="1"
|
||||
Width="6"
|
||||
Height="10"
|
||||
Margin="8,0,12,0"
|
||||
Data="M 0 0 L 6 5 L 0 10 Z"
|
||||
Fill="{DynamicResource TextSecondaryBrush}"
|
||||
Stretch="Fill"
|
||||
VerticalAlignment="Center"
|
||||
Visibility="Collapsed"/>
|
||||
|
||||
<Popup x:Name="PART_Popup"
|
||||
AllowsTransparency="True"
|
||||
Focusable="False"
|
||||
IsOpen="{Binding IsSubmenuOpen, RelativeSource={RelativeSource TemplatedParent}}"
|
||||
Placement="Right"
|
||||
PopupAnimation="Fade">
|
||||
<Border Background="{DynamicResource CardSurfaceBrush}"
|
||||
BorderBrush="{DynamicResource BorderSubtleBrush}"
|
||||
BorderThickness="1"
|
||||
Padding="4"
|
||||
SnapsToDevicePixels="True">
|
||||
<ScrollViewer CanContentScroll="True"
|
||||
HorizontalScrollBarVisibility="Disabled"
|
||||
VerticalScrollBarVisibility="Auto">
|
||||
<ItemsPresenter KeyboardNavigation.DirectionalNavigation="Cycle"
|
||||
KeyboardNavigation.TabNavigation="Cycle"/>
|
||||
</ScrollViewer>
|
||||
</Border>
|
||||
</Popup>
|
||||
</Grid>
|
||||
</Border>
|
||||
<ControlTemplate.Triggers>
|
||||
<Trigger Property="HasItems" Value="True">
|
||||
<Setter TargetName="SubmenuArrow" Property="Visibility" Value="Visible"/>
|
||||
</Trigger>
|
||||
<Trigger Property="IsHighlighted" Value="True">
|
||||
<Setter TargetName="MenuItemRoot" Property="Background" Value="{DynamicResource QuietRowHoverBackgroundBrush}"/>
|
||||
<Setter TargetName="SubmenuArrow" Property="Fill" Value="{DynamicResource TextPrimaryBrush}"/>
|
||||
</Trigger>
|
||||
<Trigger Property="IsSubmenuOpen" Value="True">
|
||||
<Setter TargetName="MenuItemRoot" Property="Background" Value="{DynamicResource QuietRowHoverBackgroundBrush}"/>
|
||||
<Setter TargetName="SubmenuArrow" Property="Fill" Value="{DynamicResource TextPrimaryBrush}"/>
|
||||
</Trigger>
|
||||
<Trigger Property="IsEnabled" Value="False">
|
||||
<Setter Property="Foreground" Value="{DynamicResource TextDisabledBrush}"/>
|
||||
<Setter TargetName="SubmenuArrow" Property="Fill" Value="{DynamicResource TextDisabledBrush}"/>
|
||||
</Trigger>
|
||||
</ControlTemplate.Triggers>
|
||||
</ControlTemplate>
|
||||
</Setter.Value>
|
||||
</Setter>
|
||||
</Style>
|
||||
<Style x:Key="ProcessContextMenuSeparatorStyle" TargetType="{x:Type Separator}" BasedOn="{x:Null}">
|
||||
<Setter Property="Background" Value="{DynamicResource BorderSubtleBrush}"/>
|
||||
<Setter Property="Margin" Value="8,4"/>
|
||||
<Setter Property="Template">
|
||||
<Setter.Value>
|
||||
<ControlTemplate TargetType="{x:Type Separator}">
|
||||
<Border Height="1"
|
||||
Background="{TemplateBinding Background}"
|
||||
SnapsToDevicePixels="True"/>
|
||||
</ControlTemplate>
|
||||
</Setter.Value>
|
||||
</Setter>
|
||||
</Style>
|
||||
<Style x:Key="ProcessContextMenuStyle" TargetType="{x:Type ContextMenu}" BasedOn="{x:Null}">
|
||||
<Setter Property="OverridesDefaultStyle" Value="True"/>
|
||||
<Setter Property="FontWeight" Value="Normal"/>
|
||||
<Setter Property="FontSize" Value="{DynamicResource BodyFontSize}"/>
|
||||
<Setter Property="Foreground" Value="{DynamicResource TextPrimaryBrush}"/>
|
||||
<Setter Property="Background" Value="{DynamicResource CardSurfaceBrush}"/>
|
||||
<Setter Property="BorderBrush" Value="{DynamicResource BorderSubtleBrush}"/>
|
||||
<Setter Property="BorderThickness" Value="1"/>
|
||||
<Setter Property="Padding" Value="4"/>
|
||||
<Setter Property="SnapsToDevicePixels" Value="True"/>
|
||||
<Setter Property="Template">
|
||||
<Setter.Value>
|
||||
<ControlTemplate TargetType="{x:Type ContextMenu}">
|
||||
<Border Background="{TemplateBinding Background}"
|
||||
BorderBrush="{TemplateBinding BorderBrush}"
|
||||
BorderThickness="{TemplateBinding BorderThickness}"
|
||||
Padding="{TemplateBinding Padding}"
|
||||
SnapsToDevicePixels="True">
|
||||
<ItemsPresenter KeyboardNavigation.DirectionalNavigation="Cycle"
|
||||
KeyboardNavigation.TabNavigation="Cycle"/>
|
||||
</Border>
|
||||
</ControlTemplate>
|
||||
</Setter.Value>
|
||||
</Setter>
|
||||
</Style>
|
||||
</UserControl.Resources>
|
||||
|
||||
<Grid Margin="10">
|
||||
@@ -39,8 +163,8 @@
|
||||
<Grid Grid.Row="1">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="*"/>
|
||||
<ColumnDefinition Width="16"/>
|
||||
<ColumnDefinition Width="360"/>
|
||||
<ColumnDefinition Width="0"/>
|
||||
<ColumnDefinition Width="0"/>
|
||||
</Grid.ColumnDefinitions>
|
||||
|
||||
<Grid Grid.Column="0">
|
||||
@@ -109,6 +233,11 @@
|
||||
Margin="0,0,15,0"
|
||||
VerticalAlignment="Center"
|
||||
ToolTip="Hide processes with very low CPU usage"/>
|
||||
<CheckBox Content="Lock process list"
|
||||
IsChecked="{Binding IsProcessListLocked}"
|
||||
Margin="0,0,15,0"
|
||||
VerticalAlignment="Center"
|
||||
ToolTip="Pause process list refresh and sorting updates while you work with the current list. Background monitoring and saved-rule auto-apply continue while ThreadPilot is running."/>
|
||||
<TextBlock Text="Sort by:" VerticalAlignment="Center" Margin="0,0,5,0"/>
|
||||
<ComboBox SelectedValue="{Binding SortMode}"
|
||||
SelectedValuePath="Tag"
|
||||
@@ -145,74 +274,115 @@
|
||||
<DataGrid.RowStyle>
|
||||
<Style TargetType="DataGridRow">
|
||||
<Setter Property="Tag" Value="{Binding DataContext, RelativeSource={RelativeSource AncestorType=DataGrid}}"/>
|
||||
<Setter Property="Background" Value="Transparent"/>
|
||||
<Setter Property="BorderBrush" Value="Transparent"/>
|
||||
<Setter Property="BorderThickness" Value="3,0,0,0"/>
|
||||
<EventSetter Event="PreviewMouseRightButtonDown" Handler="ProcessRow_PreviewMouseRightButtonDown"/>
|
||||
<Setter Property="ContextMenu">
|
||||
<Setter.Value>
|
||||
<ContextMenu DataContext="{Binding PlacementTarget.Tag, RelativeSource={RelativeSource Self}}">
|
||||
<MenuItem Header="Apply Affinity"
|
||||
<ContextMenu Style="{StaticResource ProcessContextMenuStyle}"
|
||||
DataContext="{Binding PlacementTarget.Tag, RelativeSource={RelativeSource Self}}">
|
||||
<MenuItem Style="{StaticResource ProcessContextMenuItemStyle}"
|
||||
Header="Apply Affinity"
|
||||
Command="{Binding ApplyContextAffinityCommand}"
|
||||
CommandParameter="{Binding PlacementTarget.DataContext, RelativeSource={RelativeSource AncestorType=ContextMenu}}"/>
|
||||
<MenuItem Header="Clear CPU Sets"
|
||||
<MenuItem Style="{StaticResource ProcessContextMenuItemStyle}"
|
||||
Header="Clear CPU Sets"
|
||||
Command="{Binding ClearContextCpuSetsCommand}"
|
||||
CommandParameter="{Binding PlacementTarget.DataContext, RelativeSource={RelativeSource AncestorType=ContextMenu}}"/>
|
||||
<Separator/>
|
||||
<MenuItem Header="Rules">
|
||||
<MenuItem Header="Save Current Settings as Rule"
|
||||
<Separator Style="{StaticResource ProcessContextMenuSeparatorStyle}"/>
|
||||
<MenuItem Style="{StaticResource ProcessContextMenuItemStyle}"
|
||||
Header="Rules">
|
||||
<MenuItem Style="{StaticResource ProcessContextMenuItemStyle}"
|
||||
Header="Save Current Settings as Rule"
|
||||
Command="{Binding SaveCurrentSettingsAsRuleCommand}"
|
||||
CommandParameter="{Binding PlacementTarget.DataContext, RelativeSource={RelativeSource AncestorType=ContextMenu}}"/>
|
||||
<MenuItem Header="Apply Affinity and Save as Rule"
|
||||
<MenuItem Style="{StaticResource ProcessContextMenuItemStyle}"
|
||||
Header="Apply Affinity and Save as Rule"
|
||||
Command="{Binding ApplyAffinityAndSaveAsRuleCommand}"
|
||||
CommandParameter="{Binding PlacementTarget.DataContext, RelativeSource={RelativeSource AncestorType=ContextMenu}}"/>
|
||||
</MenuItem>
|
||||
<Separator/>
|
||||
<MenuItem Header="Set CPU Priority">
|
||||
<MenuItem Header="Below Normal"
|
||||
<Separator Style="{StaticResource ProcessContextMenuSeparatorStyle}"/>
|
||||
<MenuItem Style="{StaticResource ProcessContextMenuItemStyle}"
|
||||
Header="Set CPU Priority">
|
||||
<MenuItem Style="{StaticResource ProcessContextMenuItemStyle}"
|
||||
Header="Below Normal"
|
||||
Command="{Binding SetContextBelowNormalPriorityCommand}"
|
||||
CommandParameter="{Binding PlacementTarget.DataContext, RelativeSource={RelativeSource AncestorType=ContextMenu}}"/>
|
||||
<MenuItem Header="Normal"
|
||||
<MenuItem Style="{StaticResource ProcessContextMenuItemStyle}"
|
||||
Header="Normal"
|
||||
Command="{Binding SetContextNormalPriorityCommand}"
|
||||
CommandParameter="{Binding PlacementTarget.DataContext, RelativeSource={RelativeSource AncestorType=ContextMenu}}"/>
|
||||
<MenuItem Header="Above Normal"
|
||||
<MenuItem Style="{StaticResource ProcessContextMenuItemStyle}"
|
||||
Header="Above Normal"
|
||||
Command="{Binding SetContextAboveNormalPriorityCommand}"
|
||||
CommandParameter="{Binding PlacementTarget.DataContext, RelativeSource={RelativeSource AncestorType=ContextMenu}}"/>
|
||||
<MenuItem Header="High"
|
||||
<MenuItem Style="{StaticResource ProcessContextMenuItemStyle}"
|
||||
Header="High"
|
||||
Command="{Binding SetContextHighPriorityCommand}"
|
||||
CommandParameter="{Binding PlacementTarget.DataContext, RelativeSource={RelativeSource AncestorType=ContextMenu}}"/>
|
||||
<MenuItem Header="Realtime (blocked)"
|
||||
<MenuItem Style="{StaticResource ProcessContextMenuItemStyle}"
|
||||
Header="Realtime (blocked)"
|
||||
IsEnabled="False"
|
||||
ToolTipService.ShowOnDisabled="True"
|
||||
ToolTip="Realtime priority is blocked by ThreadPilot because it can make Windows unstable or unresponsive."/>
|
||||
</MenuItem>
|
||||
<MenuItem Header="Set Memory Priority">
|
||||
<MenuItem Header="Very Low"
|
||||
<MenuItem Style="{StaticResource ProcessContextMenuItemStyle}"
|
||||
Header="Set Memory Priority">
|
||||
<MenuItem Style="{StaticResource ProcessContextMenuItemStyle}"
|
||||
Header="Very Low"
|
||||
Command="{Binding SetContextMemoryPriorityVeryLowCommand}"
|
||||
CommandParameter="{Binding PlacementTarget.DataContext, RelativeSource={RelativeSource AncestorType=ContextMenu}}"/>
|
||||
<MenuItem Header="Low"
|
||||
<MenuItem Style="{StaticResource ProcessContextMenuItemStyle}"
|
||||
Header="Low"
|
||||
Command="{Binding SetContextMemoryPriorityLowCommand}"
|
||||
CommandParameter="{Binding PlacementTarget.DataContext, RelativeSource={RelativeSource AncestorType=ContextMenu}}"/>
|
||||
<MenuItem Header="Medium"
|
||||
<MenuItem Style="{StaticResource ProcessContextMenuItemStyle}"
|
||||
Header="Medium"
|
||||
Command="{Binding SetContextMemoryPriorityMediumCommand}"
|
||||
CommandParameter="{Binding PlacementTarget.DataContext, RelativeSource={RelativeSource AncestorType=ContextMenu}}"/>
|
||||
<MenuItem Header="Below Normal"
|
||||
<MenuItem Style="{StaticResource ProcessContextMenuItemStyle}"
|
||||
Header="Below Normal"
|
||||
Command="{Binding SetContextMemoryPriorityBelowNormalCommand}"
|
||||
CommandParameter="{Binding PlacementTarget.DataContext, RelativeSource={RelativeSource AncestorType=ContextMenu}}"/>
|
||||
<MenuItem Header="Normal"
|
||||
<MenuItem Style="{StaticResource ProcessContextMenuItemStyle}"
|
||||
Header="Normal"
|
||||
Command="{Binding SetContextMemoryPriorityNormalCommand}"
|
||||
CommandParameter="{Binding PlacementTarget.DataContext, RelativeSource={RelativeSource AncestorType=ContextMenu}}"/>
|
||||
</MenuItem>
|
||||
<Separator/>
|
||||
<MenuItem Header="Open Executable Location"
|
||||
<Separator Style="{StaticResource ProcessContextMenuSeparatorStyle}"/>
|
||||
<MenuItem Style="{StaticResource ProcessContextMenuItemStyle}"
|
||||
Header="Open Executable Location"
|
||||
Command="{Binding OpenContextExecutableLocationCommand}"
|
||||
CommandParameter="{Binding PlacementTarget.DataContext, RelativeSource={RelativeSource AncestorType=ContextMenu}}"/>
|
||||
<MenuItem Header="Copy Process Info"
|
||||
<MenuItem Style="{StaticResource ProcessContextMenuItemStyle}"
|
||||
Header="Copy Process Info"
|
||||
Command="{Binding CopyContextProcessInfoCommand}"
|
||||
CommandParameter="{Binding PlacementTarget.DataContext, RelativeSource={RelativeSource AncestorType=ContextMenu}}"/>
|
||||
<MenuItem Header="Refresh Process Info"
|
||||
<MenuItem Style="{StaticResource ProcessContextMenuItemStyle}"
|
||||
Header="Refresh Process Info"
|
||||
Command="{Binding RefreshContextProcessInfoCommand}"
|
||||
CommandParameter="{Binding PlacementTarget.DataContext, RelativeSource={RelativeSource AncestorType=ContextMenu}}"/>
|
||||
</ContextMenu>
|
||||
</Setter.Value>
|
||||
</Setter>
|
||||
<Style.Triggers>
|
||||
<Trigger Property="IsMouseOver" Value="True">
|
||||
<Setter Property="Background" Value="{DynamicResource QuietRowHoverBackgroundBrush}"/>
|
||||
</Trigger>
|
||||
<Trigger Property="IsSelected" Value="True">
|
||||
<Setter Property="Background" Value="{DynamicResource SoftSelectionBackgroundBrush}"/>
|
||||
<Setter Property="BorderBrush" Value="{DynamicResource AccentBrush}"/>
|
||||
<Setter Property="FontWeight" Value="SemiBold"/>
|
||||
</Trigger>
|
||||
<MultiTrigger>
|
||||
<MultiTrigger.Conditions>
|
||||
<Condition Property="IsSelected" Value="True"/>
|
||||
<Condition Property="IsKeyboardFocusWithin" Value="True"/>
|
||||
</MultiTrigger.Conditions>
|
||||
<Setter Property="BorderBrush" Value="{DynamicResource AccentAltBrush}"/>
|
||||
</MultiTrigger>
|
||||
</Style.Triggers>
|
||||
</Style>
|
||||
</DataGrid.RowStyle>
|
||||
<DataGrid.Columns>
|
||||
@@ -231,7 +401,7 @@
|
||||
<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"/>
|
||||
<TextBlock Text="{Binding LoadingStatusText}" HorizontalAlignment="Center" FontWeight="SemiBold"/>
|
||||
</StackPanel>
|
||||
</Border>
|
||||
|
||||
@@ -312,14 +482,101 @@
|
||||
Foreground="{DynamicResource TextSecondaryBrush}"
|
||||
TextWrapping="Wrap">
|
||||
<Run Text="Last ThreadPilot action: "/>
|
||||
<Run Text="{Binding SelectedProcessSummary.LastOperationMessage}"/>
|
||||
<Run Text="{Binding SelectedProcessSummary.LastOperationMessage, Mode=OneWay}"/>
|
||||
</TextBlock>
|
||||
</WrapPanel>
|
||||
|
||||
<Expander Header="Advanced affinity picker"
|
||||
IsExpanded="False"
|
||||
Margin="0,10,0,0">
|
||||
<StackPanel Margin="0,8,0,0">
|
||||
<Grid Margin="0,0,0,8">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="Auto"/>
|
||||
<ColumnDefinition Width="10"/>
|
||||
<ColumnDefinition Width="260"/>
|
||||
<ColumnDefinition Width="10"/>
|
||||
<ColumnDefinition Width="Auto"/>
|
||||
</Grid.ColumnDefinitions>
|
||||
<TextBlock Grid.Column="0"
|
||||
Text="Pending core mask"
|
||||
FontSize="{StaticResource ProcessFontSmall}"
|
||||
FontWeight="SemiBold"
|
||||
VerticalAlignment="Center"/>
|
||||
<ComboBox Grid.Column="2"
|
||||
ItemsSource="{Binding AvailableCoreMasks}"
|
||||
SelectedItem="{Binding SelectedCoreMask, Mode=TwoWay}"
|
||||
DisplayMemberPath="Name"
|
||||
IsEnabled="{Binding SelectedProcess, Converter={StaticResource NullToBoolConverter}}"
|
||||
ToolTip="Select the pending mask for row context-menu affinity actions"/>
|
||||
<Button Grid.Column="4"
|
||||
Command="{Binding CreateCustomMaskCommand}"
|
||||
Padding="8,5"
|
||||
ToolTip="Open CPU Masks tab to create a new custom mask">
|
||||
<StackPanel Orientation="Horizontal">
|
||||
<ui:SymbolIcon Symbol="Add12" Margin="0,0,6,0" VerticalAlignment="Center"/>
|
||||
<TextBlock Text="Custom" FontSize="{StaticResource ProcessFontMediumSmall}" VerticalAlignment="Center"/>
|
||||
</StackPanel>
|
||||
</Button>
|
||||
</Grid>
|
||||
|
||||
<WrapPanel Margin="0,0,0,8">
|
||||
<TextBlock Text="{Binding CurrentAffinityText}"
|
||||
FontSize="{StaticResource ProcessFontSmall}"
|
||||
Foreground="{DynamicResource TextSecondaryBrush}"
|
||||
Margin="0,0,18,4"/>
|
||||
<TextBlock Text="{Binding PendingAffinityText}"
|
||||
FontSize="{StaticResource ProcessFontSmall}"
|
||||
Foreground="{DynamicResource TextSecondaryBrush}"
|
||||
Margin="0,0,18,4"/>
|
||||
<TextBlock Text="{Binding AffinityEditStateText}"
|
||||
FontSize="{StaticResource ProcessFontSmall}"
|
||||
Foreground="{DynamicResource WarningTextBrush}"
|
||||
Margin="0,0,18,4"/>
|
||||
</WrapPanel>
|
||||
|
||||
<WrapPanel Margin="0,0,0,6">
|
||||
<TextBlock Text="{Binding TopologyStatus}"
|
||||
FontSize="{StaticResource ProcessFontSmall}"
|
||||
Foreground="{Binding IsTopologyDetectionSuccessful, Converter={StaticResource BoolToColorConverter}}"
|
||||
Margin="0,0,18,4"/>
|
||||
<TextBlock Text="{Binding HyperThreadingStatusText}"
|
||||
FontSize="{StaticResource ProcessFontSmall}"
|
||||
Foreground="{Binding IsHyperThreadingActive, Converter={StaticResource BoolToColorConverter}}"
|
||||
Margin="0,0,18,4"/>
|
||||
</WrapPanel>
|
||||
|
||||
<ScrollViewer MaxHeight="88"
|
||||
VerticalScrollBarVisibility="Auto"
|
||||
HorizontalScrollBarVisibility="Disabled">
|
||||
<ItemsControl ItemsSource="{Binding CpuCores}">
|
||||
<ItemsControl.ItemsPanel>
|
||||
<ItemsPanelTemplate>
|
||||
<WrapPanel Orientation="Horizontal"/>
|
||||
</ItemsPanelTemplate>
|
||||
</ItemsControl.ItemsPanel>
|
||||
<ItemsControl.ItemTemplate>
|
||||
<DataTemplate>
|
||||
<CheckBox Content="{Binding Label}"
|
||||
IsChecked="{Binding IsSelected, Mode=OneWay}"
|
||||
IsHitTestVisible="False"
|
||||
Focusable="False"
|
||||
IsEnabled="{Binding IsEnabled}"
|
||||
Margin="2"
|
||||
FontSize="{StaticResource ProcessFontSmall}"
|
||||
Foreground="{DynamicResource TextPrimaryBrush}"/>
|
||||
</DataTemplate>
|
||||
</ItemsControl.ItemTemplate>
|
||||
</ItemsControl>
|
||||
</ScrollViewer>
|
||||
</StackPanel>
|
||||
</Expander>
|
||||
</StackPanel>
|
||||
</Border>
|
||||
</Grid>
|
||||
|
||||
<Border Grid.Column="2"
|
||||
Visibility="Collapsed"
|
||||
Background="{DynamicResource CardSurfaceBrush}"
|
||||
BorderBrush="{DynamicResource BorderSubtleBrush}"
|
||||
BorderThickness="1"
|
||||
|
||||
+14
-2
@@ -209,11 +209,23 @@
|
||||
</Border>
|
||||
</StackPanel>
|
||||
|
||||
<!-- Process Event Settings Section -->
|
||||
<!-- Rules & automation Section -->
|
||||
<StackPanel Width="372" Margin="0,0,16,16">
|
||||
<TextBlock Text="Process Event Settings" Style="{StaticResource SectionHeaderStyle}" Margin="0,0,0,8"/>
|
||||
<TextBlock Text="Rules & automation" Style="{StaticResource SectionHeaderStyle}" Margin="0,0,0,8"/>
|
||||
<Border Style="{StaticResource SettingsCardStyle}">
|
||||
<StackPanel>
|
||||
<TextBlock Text="Saved rule auto-apply" FontWeight="SemiBold" Margin="0,0,0,5"/>
|
||||
<CheckBox IsChecked="{Binding Settings.ApplyPersistentRulesOnProcessStart}"
|
||||
Margin="0,0,0,5">
|
||||
<TextBlock Text="Apply saved rules when matching processes start"
|
||||
TextWrapping="Wrap"/>
|
||||
</CheckBox>
|
||||
<TextBlock Text="Applies enabled saved rules while ThreadPilot is running. This does not install a Windows Service and does not use registry/IFEO persistence."
|
||||
Style="{StaticResource DescriptionStyle}"
|
||||
Margin="20,0,0,15"/>
|
||||
|
||||
<Separator Margin="0,0,0,15"/>
|
||||
|
||||
<CheckBox Content="Enable WMI process events"
|
||||
IsChecked="{Binding Settings.EnableWmiMonitoring}"
|
||||
Margin="0,0,0,5"/>
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<assembly manifestVersion="1.0" xmlns="urn:schemas-microsoft-com:asm.v1">
|
||||
<assemblyIdentity version="1.1.3.0" name="ThreadPilot.app"/>
|
||||
<assemblyIdentity version="1.2.0.0" name="ThreadPilot.app"/>
|
||||
<trustInfo xmlns="urn:schemas-microsoft-com:asm.v2">
|
||||
<security>
|
||||
<requestedPrivileges xmlns="urn:schemas-microsoft-com:asm.v3">
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
param(
|
||||
[string]$Version = "1.1.3",
|
||||
[string]$Version = "1.2.0",
|
||||
[string]$Configuration = "Release",
|
||||
[switch]$SkipPublish
|
||||
)
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
param(
|
||||
[string]$Version = "1.1.3",
|
||||
[string]$Version = "1.2.0",
|
||||
[string]$Configuration = "Release",
|
||||
[string]$Runtime = "win-x64"
|
||||
)
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
param(
|
||||
[string]$Version = "1.1.3"
|
||||
[string]$Version = "1.2.0"
|
||||
)
|
||||
|
||||
$ErrorActionPreference = "Stop"
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
<package xmlns="http://schemas.microsoft.com/packaging/2015/06/nuspec.xsd">
|
||||
<metadata>
|
||||
<id>threadpilot</id>
|
||||
<version>1.1.3</version>
|
||||
<version>1.2.0</version>
|
||||
<title>ThreadPilot</title>
|
||||
<authors>Prime Build</authors>
|
||||
<projectUrl>https://github.com/PrimeBuild-pc/ThreadPilot</projectUrl>
|
||||
@@ -15,7 +15,7 @@
|
||||
<requireLicenseAcceptance>false</requireLicenseAcceptance>
|
||||
<description>Advanced Windows process and power plan manager with rules automation and performance controls.</description>
|
||||
<summary>ThreadPilot process and power plan manager.</summary>
|
||||
<releaseNotes>https://github.com/PrimeBuild-pc/ThreadPilot/releases/tag/v1.1.3</releaseNotes>
|
||||
<releaseNotes>https://github.com/PrimeBuild-pc/ThreadPilot/releases/tag/v1.2.0</releaseNotes>
|
||||
<tags>threadpilot process powerplan performance windows</tags>
|
||||
</metadata>
|
||||
<files>
|
||||
|
||||
@@ -2,6 +2,44 @@
|
||||
|
||||
All notable changes to this project are documented in this file.
|
||||
|
||||
## v1.2.0 - CPU topology, persistent rules, and process control update
|
||||
|
||||
### Added
|
||||
|
||||
- CPU topology v2 support with `CpuSelection` for topology-aware affinity.
|
||||
- Group-aware CPU Sets support and safer handling for processor groups and systems with more than 64 logical processors.
|
||||
- Memory priority controls and persistent process rules.
|
||||
- Apply at process start for saved rules while ThreadPilot is running.
|
||||
- Process tab context menu actions, explicit Apply now, and Save as rule flows.
|
||||
- Selected process summary panel for current affinity, priority, memory priority, and last operation status.
|
||||
- Optional Diagnostics experience hidden by default.
|
||||
|
||||
### Changed
|
||||
|
||||
- README and release documentation now describe ThreadPilot as a process control center rather than a performance overlay.
|
||||
- Default presets are gaming-oriented and topology-aware.
|
||||
- Intel hybrid handling uses topology and `EfficiencyClass` instead of hardcoded SKU lists.
|
||||
- AMD preset generation is CCD/L3-aware and avoids hardcoded SKU lists.
|
||||
- Project version updated to 1.2.0.
|
||||
|
||||
### Fixed
|
||||
|
||||
- Startup binding crash caused by a display-only selected-process summary message binding to a read-only property with a TwoWay-capable target.
|
||||
- CPU64 no longer aliases CPU0 in the new safe affinity paths.
|
||||
- Persistent rule auto-apply cancellation is handled as shutdown/cancellation instead of logged as a warning.
|
||||
|
||||
### Safety
|
||||
|
||||
- CPU priority guardrails warn for High priority and block Realtime priority.
|
||||
- Anti-cheat/protected-process failures use safe user messaging and ThreadPilot does not bypass protected processes.
|
||||
- Persistent rules reuse the existing affinity, priority, memory-priority, and Realtime guardrail backend instead of duplicating apply logic.
|
||||
|
||||
### Notes / limitations
|
||||
|
||||
- Apply at process start is runtime-based and works only while ThreadPilot is running.
|
||||
- No Windows Service, registry autorun, IFEO persistence, installer privilege workaround, tag, GitHub release, or generated release artifact is included in this update.
|
||||
- Administrator rights can help normal access-denied cases but do not bypass protected-process or anti-cheat restrictions.
|
||||
|
||||
## [1.1.6] - 2026-05-16
|
||||
|
||||
### Added
|
||||
|
||||
@@ -1,50 +1,57 @@
|
||||
# ThreadPilot v1.1.6 Release Notes
|
||||
# ThreadPilot v1.2.0 Release Notes Draft
|
||||
|
||||
## Highlights
|
||||
|
||||
- Windows 11 native visual refresh across all major views with neutral Fluent surfaces.
|
||||
- Refined sidebar navigation: separator lines softened for a cleaner, Settings-like appearance.
|
||||
- Reduced visual weight and consistent card-based layouts in Rules, Logs, Performance, Settings, Tweaks, Process, Power Plans, and CPU Masks.
|
||||
- Start minimized default clarified: `StartMinimized` now explicitly defaults to `false` for predictable manual-launch visibility.
|
||||
- CPU topology v2 with topology-aware `CpuSelection`, CPU Sets, processor groups, and safer handling above 64 logical processors.
|
||||
- New safe affinity paths where CPU64 no longer aliases CPU0.
|
||||
- Intel hybrid handling through topology and `EfficiencyClass`, plus AMD CCD/L3-aware preset generation.
|
||||
- Memory priority support and persistent process rules.
|
||||
- Apply saved rules automatically when matching processes start while ThreadPilot is running.
|
||||
- Process tab context menu actions, Save as rule, Apply now, and selected-process summary.
|
||||
|
||||
## Added
|
||||
|
||||
- Windows 11 visual refresh pass completed for neutral Fluent surfaces and card polish.
|
||||
- Sidebar navigation separator polish: horizontal separator lines removed/softened for a native Windows 11 Settings-like feel.
|
||||
- CPU topology v2 and `CpuSelection` for topology-aware affinity.
|
||||
- Group-aware CPU Sets support and processor group safety.
|
||||
- Memory priority controls.
|
||||
- Persistent process rules with runtime apply-at-process-start support.
|
||||
- Process tab context menu actions and selected-process summary.
|
||||
- Optional Diagnostics view hidden by default.
|
||||
|
||||
## Changed
|
||||
|
||||
- `StartMinimized` defaults to `false` in `ApplicationSettingsModel`: manual exe launch opens the main window visibly by default.
|
||||
- Older settings JSON without `startMinimized` field now reliably defaults to `false`.
|
||||
- Explicit saved `startMinimized: true` or `startMinimized: false` values remain fully respected.
|
||||
- Project version updated to 1.1.6.
|
||||
- Default presets are gaming-oriented and generated from topology rather than hardcoded CPU SKU lists.
|
||||
- Intel hybrid behavior uses Windows topology and `EfficiencyClass`.
|
||||
- AMD behavior uses CCD/L3-aware preset generation.
|
||||
- Project version updated to 1.2.0.
|
||||
|
||||
## Fixed
|
||||
|
||||
- Legacy settings without `startMinimized` no longer risk unexpected minimized startup.
|
||||
- Startup no longer fails from a read-only selected-process summary binding.
|
||||
- CPU64 no longer aliases CPU0 in new safe affinity paths.
|
||||
- Persistent rule auto-apply cancellation does not log shutdown/future cancellation as a warning.
|
||||
|
||||
## Breaking Changes
|
||||
## Safety
|
||||
|
||||
- None.
|
||||
- High CPU priority shows a warning and Realtime priority remains blocked.
|
||||
- ThreadPilot does not bypass anti-cheat or protected-process restrictions.
|
||||
- Administrator rights may help ordinary access-denied cases but do not bypass protected processes.
|
||||
|
||||
## Installation
|
||||
## Compatibility and Upgrade Notes
|
||||
|
||||
### Installer
|
||||
- Requires Windows 11 build 22000 or newer.
|
||||
- Existing legacy affinity profiles continue to load.
|
||||
- New saved rules prefer topology-aware `CpuSelection` when safe topology mapping is available.
|
||||
- Apply at process start works only while ThreadPilot is running.
|
||||
|
||||
1. Download ThreadPilot_v1.1.6_Setup.exe.
|
||||
2. Run installer.
|
||||
3. Launch ThreadPilot.
|
||||
## Known Non-Goals
|
||||
|
||||
### Portable
|
||||
- No anti-cheat bypass.
|
||||
- No Windows Service.
|
||||
- No registry or IFEO persistence.
|
||||
- No generated release artifacts yet.
|
||||
- No GitHub release or tag yet.
|
||||
|
||||
1. Download ThreadPilot_v1.1.6_singlefile_win-x64.zip.
|
||||
2. Extract archive.
|
||||
3. Run ThreadPilot.exe.
|
||||
## Release Artifact Status
|
||||
|
||||
## Checksums
|
||||
|
||||
See SHA256SUMS.txt in release assets.
|
||||
|
||||
## Known Issues
|
||||
|
||||
- Windows 10 support remains best effort.
|
||||
- Installer, portable ZIP, checksums, package metadata verification, and release upload remain pending manual validation.
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
# ThreadPilot v1.2.0 Manual Validation Checklist
|
||||
|
||||
- [ ] App starts without binding or startup errors.
|
||||
- [ ] Process tab loads.
|
||||
- [ ] Selected-process summary renders.
|
||||
- [ ] Process tab context menu works.
|
||||
- [ ] Affinity apply works on a normal single-group machine.
|
||||
- [ ] CPU Sets clear works or fails safely with user-safe messaging.
|
||||
- [ ] Memory priority set/read works or fails safely.
|
||||
- [ ] Save as rule creates or updates a persistent process rule.
|
||||
- [ ] Process-start auto-apply works while ThreadPilot is running.
|
||||
- [ ] Protected or anti-cheat process operations fail safely without bypass language.
|
||||
- [ ] Diagnostics is hidden by default.
|
||||
- [ ] Startup does not enable performance monitoring or create performance-monitoring cost by default.
|
||||
- [ ] Release artifacts are still pending manual validation.
|
||||
@@ -0,0 +1,44 @@
|
||||
# ThreadPilot v1.2.0 Release Notes Draft
|
||||
|
||||
## Highlights
|
||||
|
||||
- CPU topology v2: topology-aware `CpuSelection`, CPU Sets, processor groups, and safer handling above 64 logical processors.
|
||||
- New safe affinity paths where CPU64 no longer aliases CPU0.
|
||||
- Intel hybrid handling uses topology and `EfficiencyClass`; AMD preset generation is CCD/L3-aware.
|
||||
- Memory priority support and persistent process rules.
|
||||
- Saved rules can apply automatically when matching processes start while ThreadPilot is running.
|
||||
- Process tab context menu actions, Save as rule, Apply now, and selected-process summary.
|
||||
- Diagnostics remains optional and hidden by default.
|
||||
|
||||
## Compatibility Notes
|
||||
|
||||
- Requires Windows 11 build 22000 or newer.
|
||||
- Administrator launch is still required for system-level process operations.
|
||||
- Existing legacy affinity profiles remain supported. New safe paths prefer `CpuSelection` when topology data is available.
|
||||
- CPU Sets and memory priority operations can fail on processes Windows denies access to; failures are reported safely.
|
||||
|
||||
## Upgrade Notes for Legacy Profiles
|
||||
|
||||
- Legacy affinity masks continue to load.
|
||||
- When saving new rules from current Process tab settings, ThreadPilot attempts to store topology-aware `CpuSelection` when it can map the legacy selection safely.
|
||||
- On systems where topology data is unavailable, ThreadPilot keeps the legacy affinity mask path instead of inventing an unsafe mapping.
|
||||
- Users with old profiles should verify presets once on the target machine before relying on them for competitive or latency-sensitive workloads.
|
||||
|
||||
## Limitations
|
||||
|
||||
- Apply at process start is runtime-based and only works while ThreadPilot is running.
|
||||
- ThreadPilot does not install a Windows Service for persistent rule application.
|
||||
- ThreadPilot does not write registry or IFEO persistence for process rules.
|
||||
- ThreadPilot does not bypass anti-cheat or protected-process restrictions. Administrator rights may help ordinary access-denied cases but do not override protected-process enforcement.
|
||||
|
||||
## Known Non-Goals for This Draft
|
||||
|
||||
- No anti-cheat bypass.
|
||||
- No Windows Service.
|
||||
- No registry or IFEO persistence.
|
||||
- No generated release artifacts yet.
|
||||
- No GitHub release or tag yet.
|
||||
|
||||
## Release Artifact Status
|
||||
|
||||
- Installer, portable ZIP, checksums, package metadata verification, and release upload remain pending manual validation.
|
||||
@@ -1,6 +1,6 @@
|
||||
sonar.projectKey=threadpilot
|
||||
sonar.projectName=ThreadPilot
|
||||
sonar.projectVersion=1.1.3
|
||||
sonar.projectVersion=1.2.0
|
||||
|
||||
sonar.sourceEncoding=UTF-8
|
||||
sonar.sources=.
|
||||
|
||||
Reference in New Issue
Block a user