Perf/professional hardening (#4)

* Improve background refresh and process detection

* Harden affinity and power plan automation

* Fix passive process refresh failures

* Improve UX terminology and process layout

* Polish UX layout and empty states

* Expand core service test coverage
This commit is contained in:
Prime Build
2026-05-09 23:15:49 +02:00
committed by GitHub
parent 2382c47789
commit 4fceda163d
40 changed files with 3254 additions and 801 deletions
+81 -47
View File
@@ -782,23 +782,23 @@ namespace ThreadPilot
{
await this.processMonitorManagerService.StartAsync();
await this.notificationService.ShowSuccessNotificationAsync(
"Monitoring Enabled",
"Process monitoring and power plan management has been enabled");
"Automation Monitoring Enabled",
"Process rule automation and power plan management have been enabled.");
}
else
{
await this.processMonitorManagerService.StopAsync();
await this.notificationService.ShowNotificationAsync(
"Monitoring Disabled",
"Process monitoring and power plan management has been disabled",
"Automation Monitoring Disabled",
"Process rule automation and power plan management have been disabled.",
Models.NotificationType.Warning);
}
}
catch (Exception ex)
{
await this.notificationService.ShowErrorNotificationAsync(
"Monitoring Error",
"Failed to toggle process monitoring",
"Automation Monitoring Error",
"Failed to toggle automation monitoring.",
ex);
}
}
@@ -969,10 +969,7 @@ namespace ThreadPilot
{
this.ShowInTaskbar = false;
this.Hide();
this.SuspendHiddenModeRefreshes();
this.processViewModel.PauseRefresh();
this.processViewModel.SetProcessViewActive(false);
_ = this.performanceViewModel.SuspendBackgroundMonitoringAsync();
this.ApplyAppRefreshPolicy(AppActivityState.TrayHidden);
}
else
{
@@ -1273,8 +1270,8 @@ namespace ThreadPilot
if (e.Error != null && this.settingsService.Settings.EnableErrorNotifications)
{
this.notificationService.ShowErrorNotificationAsync(
"Monitoring Error",
e.StatusMessage ?? "An error occurred with process monitoring",
"Automation Monitoring Error",
e.StatusMessage ?? "An error occurred with automation monitoring.",
e.Error);
}
}
@@ -1288,8 +1285,8 @@ namespace ThreadPilot
if (!e.IsRunning && e.Error != null && this.settingsService.Settings.EnableErrorNotifications)
{
this.notificationService.ShowErrorNotificationAsync(
"Process Monitoring Error",
e.Details ?? "Process monitoring manager encountered an error",
"Automation Monitoring Error",
e.Details ?? "Automation monitoring encountered an error.",
e.Error);
}
}
@@ -1300,42 +1297,22 @@ namespace ThreadPilot
{
if (this.WindowState == WindowState.Minimized)
{
var activityState = AppActivityState.Minimized;
if (this.settingsService.Settings.MinimizeToTray)
{
this.ShowInTaskbar = false;
this.Hide();
this.systemTrayService.Show();
activityState = AppActivityState.TrayHidden;
}
this.SuspendHiddenModeRefreshes();
if (this.processViewModel != null)
{
this.processViewModel.PauseRefresh();
this.processViewModel.SetProcessViewActive(false);
}
if (this.performanceViewModel != null)
{
_ = this.performanceViewModel.SuspendBackgroundMonitoringAsync();
}
this.ApplyAppRefreshPolicy(activityState);
}
else if (this.WindowState == WindowState.Normal || this.WindowState == WindowState.Maximized)
{
this.ShowInTaskbar = true;
this.ResumeForegroundRefreshes();
if (this.processViewModel != null)
{
this.processViewModel.SetProcessViewActive(this.ProcessManagementTab.Visibility == Visibility.Visible);
this.processViewModel.ResumeRefresh();
}
if (this.performanceViewModel != null)
{
_ = this.performanceViewModel.ResumeBackgroundMonitoringAsync();
}
this.ApplyAppRefreshPolicy(this.GetForegroundActivityState());
}
}
catch (Exception ex)
@@ -1364,7 +1341,6 @@ namespace ThreadPilot
this.systemTrayUpdateTimer.Interval = SystemTrayUpdateBaseIntervalMs;
}
this.systemTrayUpdateTimer?.Start();
this.powerPlanViewModel.ResumeAutoRefresh(refreshImmediately: true);
_ = this.Dispatcher.InvokeAsync(async () =>
{
@@ -1380,6 +1356,52 @@ namespace ThreadPilot
});
}
private AppActivityState GetForegroundActivityState()
{
return this.ProcessManagementTab.Visibility == Visibility.Visible
? AppActivityState.ForegroundProcessView
: AppActivityState.ForegroundOtherTab;
}
private void ApplyAppRefreshPolicy(AppActivityState state)
{
var decision = AppRefreshPolicy.Evaluate(state);
var isHiddenState = state is AppActivityState.Minimized or AppActivityState.TrayHidden;
var isProcessViewActive = state == AppActivityState.ForegroundProcessView;
if (isHiddenState)
{
this.isSystemTrayUpdatesSuspended = true;
this.systemTrayUpdateTimer?.Stop();
Interlocked.Exchange(ref this.isSystemTrayUpdateInProgress, 0);
}
else
{
this.ResumeForegroundRefreshes();
}
this.processViewModel.SetProcessViewActive(isProcessViewActive);
this.processViewModel.ApplyRefreshDecision(decision);
if (decision.PowerPlanUiRefreshEnabled)
{
this.powerPlanViewModel.ResumeAutoRefresh(refreshImmediately: state != AppActivityState.ForegroundOtherTab);
}
else
{
this.powerPlanViewModel.PauseAutoRefresh();
}
if (decision.PerformanceUiMonitoringEnabled)
{
_ = this.performanceViewModel.ResumeBackgroundMonitoringAsync();
}
else
{
_ = this.performanceViewModel.SuspendBackgroundMonitoringAsync();
}
}
protected override void OnSourceInitialized(EventArgs e)
{
base.OnSourceInitialized(e);
@@ -1447,15 +1469,16 @@ namespace ThreadPilot
this.Activate();
this.Focus();
this.Topmost = false;
this.Activate();
this.Focus();
var processViewWillBeActive = tabTag == null
? this.ProcessManagementTab.Visibility == Visibility.Visible
: string.Equals(tabTag, "Process", StringComparison.Ordinal);
this.ResumeForegroundRefreshes();
this.processViewModel.SetProcessViewActive(processViewWillBeActive);
this.processViewModel.ResumeRefresh();
_ = this.performanceViewModel.ResumeBackgroundMonitoringAsync();
this.ApplyAppRefreshPolicy(processViewWillBeActive
? AppActivityState.ForegroundProcessView
: AppActivityState.ForegroundOtherTab);
if (tabTag != null)
{
@@ -1664,10 +1687,21 @@ namespace ThreadPilot
this.NavTweaks.IsActive = tag == "Tweaks";
this.NavSettings.IsActive = tag == "Settings";
this.processViewModel.SetProcessViewActive(
string.Equals(tag, "Process", StringComparison.Ordinal) &&
this.IsVisible &&
this.WindowState != WindowState.Minimized);
if (!this.IsVisible)
{
this.ApplyAppRefreshPolicy(AppActivityState.TrayHidden);
return;
}
if (this.WindowState == WindowState.Minimized)
{
this.ApplyAppRefreshPolicy(AppActivityState.Minimized);
return;
}
this.ApplyAppRefreshPolicy(string.Equals(tag, "Process", StringComparison.Ordinal)
? AppActivityState.ForegroundProcessView
: AppActivityState.ForegroundOtherTab);
}
private void NavMenuItem_Click(object sender, RoutedEventArgs e)
+1 -1
View File
@@ -323,7 +323,7 @@
Margin="0,0,0,6"/>
<TextBlock x:Name="PerformanceIntroTip1"
Text="1. Start monitoring to collect a live snapshot."
Text="1. Start live metrics to collect a current system snapshot."
Foreground="{DynamicResource TextFillColorSecondaryBrush}"
Margin="0,0,0,4"/>
<TextBlock x:Name="PerformanceIntroTip2"
+17
View File
@@ -20,6 +20,17 @@ namespace ThreadPilot.Models
using System.Diagnostics;
using CommunityToolkit.Mvvm.ComponentModel;
public enum ProcessClassification
{
ForegroundApp,
VisibleWindowApp,
BackgroundUser,
System,
ProtectedOrAccessDenied,
Terminated,
Unknown,
}
public partial class ProcessModel : ObservableObject
{
[ObservableProperty]
@@ -52,6 +63,12 @@ namespace ThreadPilot.Models
[ObservableProperty]
private bool hasVisibleWindow;
[ObservableProperty]
private bool isForeground;
[ObservableProperty]
private ProcessClassification classification = ProcessClassification.Unknown;
[ObservableProperty]
private bool isIdleServerDisabled;
+250
View File
@@ -0,0 +1,250 @@
/*
* 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/>.
*/
namespace ThreadPilot.Services
{
using Microsoft.Extensions.Logging;
using ThreadPilot.Models;
public enum AffinityApplyFailureReason
{
None,
InvalidMask,
ProcessTerminated,
AccessDenied,
VerificationMismatch,
ApplyFailed,
}
public sealed record AffinityApplyResult(
bool Success,
long RequestedMask,
long VerifiedMask,
AffinityApplyFailureReason FailureReason,
string Message)
{
public static AffinityApplyResult Succeeded(long requestedMask, long verifiedMask) =>
new(true, requestedMask, verifiedMask, AffinityApplyFailureReason.None, "Affinity applied successfully.");
public static AffinityApplyResult Failed(
long requestedMask,
long verifiedMask,
AffinityApplyFailureReason failureReason,
string message) =>
new(false, requestedMask, verifiedMask, failureReason, message);
}
public interface IAffinityApplyService
{
Task<AffinityApplyResult> ApplyAsync(ProcessModel process, long requestedMask);
}
public sealed class AffinityApplyService : IAffinityApplyService
{
private readonly IProcessService processService;
private readonly ICpuTopologyService cpuTopologyService;
private readonly ILogger<AffinityApplyService> logger;
public AffinityApplyService(
IProcessService processService,
ICpuTopologyService cpuTopologyService,
ILogger<AffinityApplyService> logger)
{
this.processService = processService ?? throw new ArgumentNullException(nameof(processService));
this.cpuTopologyService = cpuTopologyService ?? throw new ArgumentNullException(nameof(cpuTopologyService));
this.logger = logger ?? throw new ArgumentNullException(nameof(logger));
}
public async Task<AffinityApplyResult> ApplyAsync(ProcessModel process, long requestedMask)
{
ArgumentNullException.ThrowIfNull(process);
var startingMask = process.ProcessorAffinity;
if (requestedMask == 0)
{
return AffinityApplyResult.Failed(
requestedMask,
startingMask,
AffinityApplyFailureReason.InvalidMask,
"Affinity mask cannot be zero.");
}
if (!this.cpuTopologyService.IsAffinityMaskValid(requestedMask))
{
return AffinityApplyResult.Failed(
requestedMask,
startingMask,
AffinityApplyFailureReason.InvalidMask,
"Affinity mask is not valid for this CPU topology.");
}
if (!await this.IsProcessRunningAsync(process).ConfigureAwait(false))
{
return AffinityApplyResult.Failed(
requestedMask,
startingMask,
AffinityApplyFailureReason.ProcessTerminated,
"Process is no longer running.");
}
try
{
await this.processService.SetProcessorAffinity(process, requestedMask).ConfigureAwait(false);
}
catch (Exception ex) when (IsAccessDenied(ex))
{
this.logger.LogWarning(
ex,
"Affinity apply blocked for process {ProcessName} (PID: {ProcessId})",
process.Name,
process.ProcessId);
await this.TryRefreshProcessInfoAsync(process).ConfigureAwait(false);
return AffinityApplyResult.Failed(
requestedMask,
process.ProcessorAffinity,
AffinityApplyFailureReason.AccessDenied,
"Affinity change blocked (anti-cheat or insufficient privileges).");
}
catch (Exception ex) when (IsProcessTerminated(ex))
{
this.logger.LogDebug(
ex,
"Process terminated while applying affinity to {ProcessName} (PID: {ProcessId})",
process.Name,
process.ProcessId);
return AffinityApplyResult.Failed(
requestedMask,
process.ProcessorAffinity,
AffinityApplyFailureReason.ProcessTerminated,
"Process exited before affinity could be applied.");
}
catch (Exception ex)
{
this.logger.LogWarning(
ex,
"Affinity apply failed for process {ProcessName} (PID: {ProcessId})",
process.Name,
process.ProcessId);
await this.TryRefreshProcessInfoAsync(process).ConfigureAwait(false);
return AffinityApplyResult.Failed(
requestedMask,
process.ProcessorAffinity,
AffinityApplyFailureReason.ApplyFailed,
$"Failed to set processor affinity: {ex.Message}");
}
if (!await this.TryRefreshProcessInfoAsync(process).ConfigureAwait(false))
{
return AffinityApplyResult.Failed(
requestedMask,
process.ProcessorAffinity,
AffinityApplyFailureReason.ProcessTerminated,
"Process exited before affinity could be verified.");
}
var verifiedMask = process.ProcessorAffinity;
if (verifiedMask != requestedMask)
{
return AffinityApplyResult.Failed(
requestedMask,
verifiedMask,
AffinityApplyFailureReason.VerificationMismatch,
$"Windows reported affinity 0x{verifiedMask:X} after requesting 0x{requestedMask:X}.");
}
return AffinityApplyResult.Succeeded(requestedMask, verifiedMask);
}
private static bool IsAccessDenied(Exception ex)
{
var message = ex.Message ?? string.Empty;
return ex is UnauthorizedAccessException ||
message.Contains("access denied", StringComparison.OrdinalIgnoreCase) ||
message.Contains("anti-cheat", StringComparison.OrdinalIgnoreCase) ||
message.Contains("anti cheat", StringComparison.OrdinalIgnoreCase) ||
message.Contains("protected", StringComparison.OrdinalIgnoreCase) ||
message.Contains("insufficient privileges", StringComparison.OrdinalIgnoreCase);
}
private static bool IsProcessTerminated(Exception ex)
{
var message = ex.Message ?? string.Empty;
return ex is ArgumentException ||
(ex is InvalidOperationException &&
(message.Contains("process", StringComparison.OrdinalIgnoreCase) &&
(message.Contains("exit", StringComparison.OrdinalIgnoreCase) ||
message.Contains("terminated", StringComparison.OrdinalIgnoreCase) ||
message.Contains("not running", StringComparison.OrdinalIgnoreCase))));
}
private async Task<bool> IsProcessRunningAsync(ProcessModel process)
{
try
{
return await this.processService.IsProcessStillRunning(process).ConfigureAwait(false);
}
catch (Exception ex) when (IsAccessDenied(ex))
{
this.logger.LogDebug(
ex,
"Could not confirm process state before affinity apply for {ProcessName} (PID: {ProcessId})",
process.Name,
process.ProcessId);
return true;
}
catch (Exception ex)
{
this.logger.LogDebug(
ex,
"Process state check failed before affinity apply for {ProcessName} (PID: {ProcessId})",
process.Name,
process.ProcessId);
return false;
}
}
private async Task<bool> TryRefreshProcessInfoAsync(ProcessModel process)
{
try
{
await this.processService.RefreshProcessInfo(process).ConfigureAwait(false);
return true;
}
catch (Exception ex) when (IsAccessDenied(ex))
{
this.logger.LogDebug(
ex,
"Could not refresh process after affinity apply for {ProcessName} (PID: {ProcessId})",
process.Name,
process.ProcessId);
return true;
}
catch (Exception ex)
{
this.logger.LogDebug(
ex,
"Process refresh failed after affinity apply for {ProcessName} (PID: {ProcessId})",
process.Name,
process.ProcessId);
return false;
}
}
}
}
+81
View File
@@ -0,0 +1,81 @@
/*
* 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/>.
*/
namespace ThreadPilot.Services
{
/// <summary>
/// Represents the current UI activity state used to decide refresh work.
/// </summary>
public enum AppActivityState
{
ForegroundProcessView,
ForegroundOtherTab,
Minimized,
TrayHidden,
}
/// <summary>
/// Describes refresh and monitoring work allowed for a UI activity state.
/// </summary>
public sealed record AppRefreshDecision(
bool ProcessUiRefreshEnabled,
bool ImmediateProcessRefresh,
bool VirtualizedPreloadEnabled,
bool PerformanceUiMonitoringEnabled,
bool PowerPlanUiRefreshEnabled,
bool BackgroundAutomationEnabled);
/// <summary>
/// Central policy for foreground/background refresh decisions.
/// </summary>
public static class AppRefreshPolicy
{
public static AppRefreshDecision Evaluate(AppActivityState state)
{
return state switch
{
AppActivityState.ForegroundProcessView => new AppRefreshDecision(
ProcessUiRefreshEnabled: true,
ImmediateProcessRefresh: true,
VirtualizedPreloadEnabled: true,
PerformanceUiMonitoringEnabled: true,
PowerPlanUiRefreshEnabled: true,
BackgroundAutomationEnabled: true),
AppActivityState.ForegroundOtherTab => new AppRefreshDecision(
ProcessUiRefreshEnabled: false,
ImmediateProcessRefresh: false,
VirtualizedPreloadEnabled: false,
PerformanceUiMonitoringEnabled: true,
PowerPlanUiRefreshEnabled: true,
BackgroundAutomationEnabled: true),
AppActivityState.Minimized or AppActivityState.TrayHidden => new AppRefreshDecision(
ProcessUiRefreshEnabled: false,
ImmediateProcessRefresh: false,
VirtualizedPreloadEnabled: false,
PerformanceUiMonitoringEnabled: false,
PowerPlanUiRefreshEnabled: false,
BackgroundAutomationEnabled: true),
_ => new AppRefreshDecision(
ProcessUiRefreshEnabled: false,
ImmediateProcessRefresh: false,
VirtualizedPreloadEnabled: false,
PerformanceUiMonitoringEnabled: false,
PowerPlanUiRefreshEnabled: false,
BackgroundAutomationEnabled: true),
};
}
}
}
+74
View File
@@ -0,0 +1,74 @@
/*
* ThreadPilot - Advanced Windows Process and Power Plan Manager
* Copyright (C) 2025 Prime Build
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU 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/>.
*/
namespace ThreadPilot.Services
{
using System;
using Microsoft.Extensions.Logging;
public readonly record struct ForegroundWindowSnapshot(
IntPtr WindowHandle,
int ProcessId,
bool IsVisible,
bool IsCloaked);
public interface IForegroundWindowProvider
{
bool TryGetForegroundWindow(out ForegroundWindowSnapshot snapshot);
}
public interface IForegroundProcessService
{
int? TryGetForegroundProcessId();
}
public sealed class ForegroundProcessService : IForegroundProcessService
{
private readonly IForegroundWindowProvider foregroundWindowProvider;
private readonly ILogger<ForegroundProcessService> logger;
public ForegroundProcessService(
IForegroundWindowProvider foregroundWindowProvider,
ILogger<ForegroundProcessService> logger)
{
this.foregroundWindowProvider = foregroundWindowProvider ?? throw new ArgumentNullException(nameof(foregroundWindowProvider));
this.logger = logger ?? throw new ArgumentNullException(nameof(logger));
}
public int? TryGetForegroundProcessId()
{
try
{
if (!this.foregroundWindowProvider.TryGetForegroundWindow(out var snapshot))
{
return null;
}
if (snapshot.ProcessId <= 0 || !snapshot.IsVisible || snapshot.IsCloaked)
{
return null;
}
return snapshot.ProcessId;
}
catch (Exception ex)
{
this.logger.LogDebug(ex, "Foreground process detection failed");
return null;
}
}
}
}
+70
View File
@@ -0,0 +1,70 @@
/*
* 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/>.
*/
namespace ThreadPilot.Services
{
using System;
using System.Collections.Concurrent;
public enum PassiveProcessErrorKind
{
AccessDenied,
Terminated,
Unknown,
}
public interface IPassiveProcessErrorThrottle
{
bool ShouldLog(int processId, PassiveProcessErrorKind errorKind);
}
public sealed class PassiveProcessErrorThrottle : IPassiveProcessErrorThrottle
{
private readonly ConcurrentDictionary<(int ProcessId, PassiveProcessErrorKind ErrorKind), DateTimeOffset> lastLogByError = new();
private readonly Func<DateTimeOffset> nowProvider;
private readonly TimeSpan ttl;
public PassiveProcessErrorThrottle()
: this(TimeSpan.FromMinutes(5), () => DateTimeOffset.UtcNow)
{
}
public PassiveProcessErrorThrottle(TimeSpan ttl, Func<DateTimeOffset> nowProvider)
{
if (ttl <= TimeSpan.Zero)
{
throw new ArgumentOutOfRangeException(nameof(ttl), "TTL must be greater than zero.");
}
this.ttl = ttl;
this.nowProvider = nowProvider ?? throw new ArgumentNullException(nameof(nowProvider));
}
public bool ShouldLog(int processId, PassiveProcessErrorKind errorKind)
{
var now = this.nowProvider();
var key = (processId, errorKind);
if (this.lastLogByError.TryGetValue(key, out var lastLog) && now - lastLog < this.ttl)
{
return false;
}
this.lastLogByError[key] = now;
return true;
}
}
}
+78
View File
@@ -0,0 +1,78 @@
/*
* 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/>.
*/
namespace ThreadPilot.Services
{
public enum PowerPlanTransitionSuppressionReason
{
None,
AlreadyActive,
RecentDuplicateRequest,
}
public sealed record PowerPlanTransitionDecision(
bool ShouldApply,
PowerPlanTransitionSuppressionReason SuppressionReason);
public sealed class PowerPlanTransitionGate
{
private readonly TimeSpan duplicateWindow;
private readonly Func<DateTimeOffset> nowProvider;
private readonly object lockObject = new();
private string? lastRequestedPowerPlanGuid;
private DateTimeOffset lastRequestTime;
public PowerPlanTransitionGate()
: this(TimeSpan.FromSeconds(2), () => DateTimeOffset.UtcNow)
{
}
public PowerPlanTransitionGate(TimeSpan duplicateWindow, Func<DateTimeOffset> nowProvider)
{
this.duplicateWindow = duplicateWindow < TimeSpan.Zero ? TimeSpan.Zero : duplicateWindow;
this.nowProvider = nowProvider ?? throw new ArgumentNullException(nameof(nowProvider));
}
public PowerPlanTransitionDecision ShouldApply(string targetPowerPlanGuid, string? currentPowerPlanGuid)
{
if (string.Equals(targetPowerPlanGuid, currentPowerPlanGuid, StringComparison.OrdinalIgnoreCase))
{
return new PowerPlanTransitionDecision(false, PowerPlanTransitionSuppressionReason.AlreadyActive);
}
lock (this.lockObject)
{
var now = this.nowProvider();
if (string.Equals(this.lastRequestedPowerPlanGuid, targetPowerPlanGuid, StringComparison.OrdinalIgnoreCase) &&
now - this.lastRequestTime < this.duplicateWindow)
{
return new PowerPlanTransitionDecision(false, PowerPlanTransitionSuppressionReason.RecentDuplicateRequest);
}
}
return new PowerPlanTransitionDecision(true, PowerPlanTransitionSuppressionReason.None);
}
public void RecordAttempt(string targetPowerPlanGuid)
{
lock (this.lockObject)
{
this.lastRequestedPowerPlanGuid = targetPowerPlanGuid;
this.lastRequestTime = this.nowProvider();
}
}
}
}
+78
View File
@@ -0,0 +1,78 @@
/*
* 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/>.
*/
namespace ThreadPilot.Services
{
using System;
using ThreadPilot.Models;
public readonly record struct ProcessClassificationContext(
int? ForegroundProcessId,
bool AccessDenied = false,
bool Terminated = false);
public interface IProcessClassifier
{
ProcessClassification Classify(ProcessModel process, ProcessClassificationContext context);
}
public sealed class ProcessClassifier : IProcessClassifier
{
private readonly ProcessFilterService processFilterService;
public ProcessClassifier(ProcessFilterService processFilterService)
{
this.processFilterService = processFilterService ?? throw new ArgumentNullException(nameof(processFilterService));
}
public ProcessClassification Classify(ProcessModel process, ProcessClassificationContext context)
{
ArgumentNullException.ThrowIfNull(process);
if (context.Terminated)
{
return ProcessClassification.Terminated;
}
if (context.AccessDenied)
{
return ProcessClassification.ProtectedOrAccessDenied;
}
if (context.ForegroundProcessId == process.ProcessId)
{
return ProcessClassification.ForegroundApp;
}
if (this.processFilterService.IsSystemProcess(process))
{
return ProcessClassification.System;
}
if (process.HasVisibleWindow)
{
return ProcessClassification.VisibleWindowApp;
}
if (!string.IsNullOrWhiteSpace(process.Name))
{
return ProcessClassification.BackgroundUser;
}
return ProcessClassification.Unknown;
}
}
}
+2 -2
View File
@@ -66,7 +66,7 @@ namespace ThreadPilot.Services
if (criteria.HideSystemProcesses)
{
filtered = filtered.Where(p => !IsSystemProcess(p));
filtered = filtered.Where(p => !this.IsSystemProcess(p));
}
if (criteria.HideIdleProcesses)
@@ -86,7 +86,7 @@ namespace ThreadPilot.Services
return sorted.ToList();
}
private static bool IsSystemProcess(ProcessModel process)
public bool IsSystemProcess(ProcessModel process)
{
if (process == null)
{
+103
View File
@@ -0,0 +1,103 @@
/*
* 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/>.
*/
namespace ThreadPilot.Services
{
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using ThreadPilot.Models;
public sealed record ProcessListDeltaResult(ProcessModel? SelectedProcess, bool SelectedProcessTerminated);
/// <summary>
/// Applies process snapshots to the UI collection while preserving existing models by PID.
/// </summary>
public static class ProcessListDeltaUpdater
{
public static ProcessListDeltaResult ApplyDelta(
ObservableCollection<ProcessModel> target,
IEnumerable<ProcessModel> snapshot,
int? selectedProcessId)
{
ArgumentNullException.ThrowIfNull(target);
ArgumentNullException.ThrowIfNull(snapshot);
var currentByPid = target
.GroupBy(process => process.ProcessId)
.ToDictionary(group => group.Key, group => group.First());
var snapshotByPid = new Dictionary<int, ProcessModel>();
foreach (var process in snapshot)
{
snapshotByPid[process.ProcessId] = process;
}
var seenPids = new HashSet<int>();
ProcessModel? selectedProcess = null;
foreach (var incoming in snapshotByPid.Values)
{
seenPids.Add(incoming.ProcessId);
if (currentByPid.TryGetValue(incoming.ProcessId, out var existing))
{
CopyProcessState(incoming, existing);
if (selectedProcessId == incoming.ProcessId)
{
selectedProcess = existing;
}
continue;
}
target.Add(incoming);
if (selectedProcessId == incoming.ProcessId)
{
selectedProcess = incoming;
}
}
for (int i = target.Count - 1; i >= 0; i--)
{
if (!seenPids.Contains(target[i].ProcessId))
{
target.RemoveAt(i);
}
}
var selectedProcessTerminated = selectedProcessId.HasValue && selectedProcess == null;
return new ProcessListDeltaResult(selectedProcess, selectedProcessTerminated);
}
private static void CopyProcessState(ProcessModel source, ProcessModel target)
{
target.Name = source.Name;
target.ExecutablePath = source.ExecutablePath;
target.CpuUsage = source.CpuUsage;
target.MemoryUsage = source.MemoryUsage;
target.Priority = source.Priority;
target.ProcessorAffinity = source.ProcessorAffinity;
target.MainWindowHandle = source.MainWindowHandle;
target.MainWindowTitle = source.MainWindowTitle;
target.HasVisibleWindow = source.HasVisibleWindow;
target.IsForeground = source.IsForeground;
target.Classification = source.Classification;
target.IsIdleServerDisabled = source.IsIdleServerDisabled;
target.IsRegistryPriorityEnabled = source.IsRegistryPriorityEnabled;
}
}
}
+68 -10
View File
@@ -38,6 +38,8 @@ namespace ThreadPilot.Services
private readonly IApplicationSettingsService settingsService;
private readonly IProcessService processService;
private readonly ICoreMaskService coreMaskService;
private readonly IAffinityApplyService affinityApplyService;
private readonly PowerPlanTransitionGate powerPlanTransitionGate;
private readonly ILogger<ProcessMonitorManagerService> logger;
private readonly IEnhancedLoggingService enhancedLogger;
private readonly object lockObject = new();
@@ -71,6 +73,8 @@ namespace ThreadPilot.Services
IApplicationSettingsService settingsService,
IProcessService processService,
ICoreMaskService coreMaskService,
IAffinityApplyService affinityApplyService,
PowerPlanTransitionGate powerPlanTransitionGate,
ILogger<ProcessMonitorManagerService> logger,
IEnhancedLoggingService enhancedLogger)
{
@@ -81,6 +85,8 @@ namespace ThreadPilot.Services
this.settingsService = settingsService ?? throw new ArgumentNullException(nameof(settingsService));
this.processService = processService ?? throw new ArgumentNullException(nameof(processService));
this.coreMaskService = coreMaskService ?? throw new ArgumentNullException(nameof(coreMaskService));
this.affinityApplyService = affinityApplyService ?? throw new ArgumentNullException(nameof(affinityApplyService));
this.powerPlanTransitionGate = powerPlanTransitionGate ?? throw new ArgumentNullException(nameof(powerPlanTransitionGate));
this.logger = logger ?? throw new ArgumentNullException(nameof(logger));
this.enhancedLogger = enhancedLogger ?? throw new ArgumentNullException(nameof(enhancedLogger));
@@ -264,6 +270,19 @@ namespace ThreadPilot.Services
await this.powerPlanChangeSemaphore.WaitAsync();
var currentPowerPlan = await this.powerPlanService.GetActivePowerPlan();
var decision = this.powerPlanTransitionGate.ShouldApply(
this.configuration.DefaultPowerPlanGuid,
currentPowerPlan?.Guid);
if (!decision.ShouldApply)
{
this.logger.LogDebug(
"Default power plan restore suppressed for {PowerPlanGuid}: {Reason}",
this.configuration.DefaultPowerPlanGuid,
decision.SuppressionReason);
return;
}
this.powerPlanTransitionGate.RecordAttempt(this.configuration.DefaultPowerPlanGuid);
var success = await this.powerPlanService.SetActivePowerPlanByGuidAsync(
this.configuration.DefaultPowerPlanGuid,
this.configuration.PreventDuplicatePowerPlanChanges);
@@ -284,6 +303,12 @@ namespace ThreadPilot.Services
newPowerPlan?.Name ?? this.configuration.DefaultPowerPlanName,
string.Empty);
}
else
{
this.logger.LogWarning(
"Failed to restore default power plan {PowerPlanGuid}",
this.configuration.DefaultPowerPlanGuid);
}
}
catch (Exception ex)
{
@@ -505,6 +530,19 @@ namespace ThreadPilot.Services
await this.powerPlanChangeSemaphore.WaitAsync();
var currentPowerPlan = await this.powerPlanService.GetActivePowerPlan();
var decision = this.powerPlanTransitionGate.ShouldApply(
association.PowerPlanGuid,
currentPowerPlan?.Guid);
if (!decision.ShouldApply)
{
this.logger.LogDebug(
"Power plan change suppressed for {PowerPlanGuid}: {Reason}",
association.PowerPlanGuid,
decision.SuppressionReason);
return;
}
this.powerPlanTransitionGate.RecordAttempt(association.PowerPlanGuid);
var success = await this.powerPlanService.SetActivePowerPlanByGuidAsync(
association.PowerPlanGuid,
this.configuration?.PreventDuplicatePowerPlanChanges ?? true);
@@ -521,6 +559,14 @@ namespace ThreadPilot.Services
newPowerPlan?.Name ?? association.PowerPlanName,
process.Name);
}
else
{
this.logger.LogWarning(
"Failed to change power plan to {PowerPlanGuid} for process {ProcessName} (PID: {ProcessId})",
association.PowerPlanGuid,
process.Name,
process.ProcessId);
}
}
catch (Exception ex)
{
@@ -583,18 +629,30 @@ namespace ThreadPilot.Services
var affinity = coreMask.ToProcessorAffinity();
if (affinity > 0)
{
await this.processService.SetProcessorAffinity(process, affinity);
this.processService.TrackAppliedMask(process.ProcessId, coreMask.Id);
this.coreMaskService.RegisterMaskApplication(process.ProcessId, coreMask.Id);
var result = await this.affinityApplyService.ApplyAsync(process, affinity);
if (!result.Success)
{
this.logger.LogWarning(
"Failed to apply CPU mask '{MaskName}' to process {ProcessName} (PID: {ProcessId}): {Message}",
coreMask.Name,
process.Name,
process.ProcessId,
result.Message);
}
else
{
this.processService.TrackAppliedMask(process.ProcessId, coreMask.Id);
this.coreMaskService.RegisterMaskApplication(process.ProcessId, coreMask.Id);
this.logger.LogInformation(
"Applied CPU mask '{MaskName}' (affinity: 0x{Affinity:X}) to process {ProcessName} (PID: {ProcessId})",
coreMask.Name, affinity, process.Name, process.ProcessId);
this.logger.LogInformation(
"Applied CPU mask '{MaskName}' (affinity: 0x{Affinity:X}) to process {ProcessName} (PID: {ProcessId})",
coreMask.Name, affinity, process.Name, process.ProcessId);
await this.enhancedLogger.LogProcessMonitoringEventAsync(
LogEventTypes.ProcessMonitoring.AssociationTriggered,
process.Name, process.ProcessId,
$"CPU mask '{coreMask.Name}' applied automatically from association");
await this.enhancedLogger.LogProcessMonitoringEventAsync(
LogEventTypes.ProcessMonitoring.AssociationTriggered,
process.Name, process.ProcessId,
$"CPU mask '{coreMask.Name}' applied automatically from association");
}
}
}
catch (Exception ex)
+326 -33
View File
@@ -38,6 +38,9 @@ namespace ThreadPilot.Services
private readonly ConcurrentDictionary<int, IProcessCpuSetHandler> cpuSetHandlers = new();
private readonly ILogger<ProcessService>? logger;
private readonly ISecurityService? securityService;
private readonly IForegroundProcessService? foregroundProcessService;
private readonly IProcessClassifier processClassifier;
private readonly IPassiveProcessErrorThrottle passiveProcessErrorThrottle;
private readonly Func<string> profilesDirectoryProvider;
private string ProfilesDirectory => this.profilesDirectoryProvider();
@@ -51,10 +54,16 @@ namespace ThreadPilot.Services
public ProcessService(
ILogger<ProcessService>? logger = null,
ISecurityService? securityService = null,
Func<string>? profilesDirectoryProvider = null)
Func<string>? profilesDirectoryProvider = null,
IForegroundProcessService? foregroundProcessService = null,
IProcessClassifier? processClassifier = null,
IPassiveProcessErrorThrottle? passiveProcessErrorThrottle = null)
{
this.logger = logger;
this.securityService = securityService;
this.foregroundProcessService = foregroundProcessService;
this.processClassifier = processClassifier ?? new ProcessClassifier(new ProcessFilterService());
this.passiveProcessErrorThrottle = passiveProcessErrorThrottle ?? new PassiveProcessErrorThrottle();
this.profilesDirectoryProvider = profilesDirectoryProvider ?? (() => StoragePaths.ProfilesDirectory);
StoragePaths.EnsureAppDataDirectories();
@@ -72,9 +81,10 @@ namespace ThreadPilot.Services
{
return await Task.Run(() =>
{
var foregroundProcessId = this.foregroundProcessService?.TryGetForegroundProcessId();
var processes = Process.GetProcesses()
.Select(this.CreateProcessModel)
.Where(p => p != null)
.Select(process => this.TryCreateProcessModel(process, foregroundProcessId))
.OfType<ProcessModel>()
.OrderBy(p => p.Name);
return new ObservableCollection<ProcessModel>(processes);
@@ -139,40 +149,212 @@ namespace ThreadPilot.Services
}
public ProcessModel CreateProcessModel(Process process)
{
return this.CreateProcessModel(process, this.foregroundProcessService?.TryGetForegroundProcessId());
}
private ProcessModel? TryCreateProcessModel(Process process, int? foregroundProcessId)
{
try
{
return this.CreateProcessModel(process, foregroundProcessId);
}
catch (Exception ex) when (IsTerminatedProcessException(ex))
{
var processId = TryGetProcessId(process);
if (processId.HasValue)
{
this.CleanupProcessResources(processId.Value);
this.LogPassiveProcessReadFailure(processId.Value, PassiveProcessErrorKind.Terminated, ex);
}
return CreateMinimalProcessModel(process, processId, ProcessClassification.Terminated);
}
catch (Exception ex) when (IsPassiveProcessAccessException(ex))
{
var processId = TryGetProcessId(process);
if (processId.HasValue)
{
this.LogPassiveProcessReadFailure(processId.Value, PassiveProcessErrorKind.AccessDenied, ex);
}
return CreateMinimalProcessModel(process, processId, ProcessClassification.ProtectedOrAccessDenied);
}
catch (Exception ex)
{
var processId = TryGetProcessId(process);
if (processId.HasValue)
{
this.LogPassiveProcessReadFailure(processId.Value, PassiveProcessErrorKind.Unknown, ex);
}
return CreateMinimalProcessModel(process, processId, ProcessClassification.Unknown);
}
}
private ProcessModel CreateProcessModel(Process process, int? foregroundProcessId)
{
var model = new ProcessModel();
var accessDenied = false;
var terminated = false;
try
{
model.ProcessId = process.Id;
model.Name = process.ProcessName;
model.MemoryUsage = process.PrivateMemorySize64;
model.Priority = process.PriorityClass;
model.ProcessorAffinity = (long)process.ProcessorAffinity;
model.CpuUsage = this.CalculateCpuUsage(process);
// Capture window information
model.MainWindowHandle = process.MainWindowHandle;
model.MainWindowTitle = process.MainWindowTitle ?? string.Empty;
model.HasVisibleWindow = model.MainWindowHandle != IntPtr.Zero && !string.IsNullOrWhiteSpace(model.MainWindowTitle);
// Try to get executable path
try
{
model.ExecutablePath = process.MainModule?.FileName ?? string.Empty;
}
catch
{
model.ExecutablePath = string.Empty;
}
}
catch
{
// Process may have terminated or access denied
// Return a minimal model
model.ProcessId = process.Id;
model.Name = process.ProcessName;
model.Classification = ProcessClassification.Unknown;
return model;
}
try
{
model.Name = process.ProcessName;
}
catch (Exception ex) when (IsAccessDeniedException(ex))
{
accessDenied = true;
model.Name = $"PID_{model.ProcessId}";
this.LogPassiveProcessReadFailure(model.ProcessId, PassiveProcessErrorKind.AccessDenied, ex);
}
catch (Exception ex) when (IsTerminatedProcessException(ex))
{
terminated = true;
model.Name = $"PID_{model.ProcessId}";
}
if (!terminated)
{
try
{
if (process.HasExited)
{
terminated = true;
}
}
catch (Exception ex) when (IsTerminatedProcessException(ex))
{
terminated = true;
}
catch (Exception ex) when (IsAccessDeniedException(ex))
{
accessDenied = true;
this.LogPassiveProcessReadFailure(model.ProcessId, PassiveProcessErrorKind.AccessDenied, ex);
}
}
if (!terminated)
{
try
{
model.MemoryUsage = process.PrivateMemorySize64;
}
catch (Exception ex) when (IsAccessDeniedException(ex))
{
accessDenied = true;
this.LogPassiveProcessReadFailure(model.ProcessId, PassiveProcessErrorKind.AccessDenied, ex);
}
catch (Exception ex) when (IsTerminatedProcessException(ex))
{
terminated = true;
}
if (!terminated)
{
try
{
model.Priority = process.PriorityClass;
}
catch (Exception ex) when (IsAccessDeniedException(ex))
{
accessDenied = true;
model.MainWindowHandle = IntPtr.Zero;
model.MainWindowTitle = string.Empty;
model.HasVisibleWindow = false;
this.LogPassiveProcessReadFailure(model.ProcessId, PassiveProcessErrorKind.AccessDenied, ex);
}
catch (Exception ex) when (IsPassiveProcessAccessException(ex))
{
accessDenied = true;
model.MainWindowHandle = IntPtr.Zero;
model.MainWindowTitle = string.Empty;
model.HasVisibleWindow = false;
this.LogPassiveProcessReadFailure(model.ProcessId, PassiveProcessErrorKind.AccessDenied, ex);
}
catch (Exception ex) when (IsTerminatedProcessException(ex))
{
terminated = true;
}
}
if (!terminated)
{
try
{
model.ProcessorAffinity = (long)process.ProcessorAffinity;
}
catch (Exception ex) when (IsAccessDeniedException(ex))
{
accessDenied = true;
this.LogPassiveProcessReadFailure(model.ProcessId, PassiveProcessErrorKind.AccessDenied, ex);
}
catch (Exception ex) when (IsTerminatedProcessException(ex))
{
terminated = true;
}
}
if (!terminated)
{
model.CpuUsage = this.CalculateCpuUsage(process);
}
if (!terminated)
{
try
{
model.MainWindowHandle = process.MainWindowHandle;
model.MainWindowTitle = process.MainWindowTitle ?? string.Empty;
model.HasVisibleWindow = model.MainWindowHandle != IntPtr.Zero && !string.IsNullOrWhiteSpace(model.MainWindowTitle);
}
catch (Exception ex) when (IsTerminatedProcessException(ex))
{
terminated = true;
}
}
if (!terminated)
{
try
{
model.ExecutablePath = process.MainModule?.FileName ?? string.Empty;
}
catch (Exception ex) when (IsAccessDeniedException(ex))
{
accessDenied = true;
model.ExecutablePath = string.Empty;
this.LogPassiveProcessReadFailure(model.ProcessId, PassiveProcessErrorKind.AccessDenied, ex);
}
catch (Exception ex) when (IsPassiveProcessAccessException(ex))
{
accessDenied = true;
model.ExecutablePath = string.Empty;
this.LogPassiveProcessReadFailure(model.ProcessId, PassiveProcessErrorKind.AccessDenied, ex);
}
catch (Exception ex) when (IsTerminatedProcessException(ex))
{
terminated = true;
}
}
}
if (terminated)
{
this.CleanupProcessResources(model.ProcessId);
}
this.ApplyProcessClassification(model, foregroundProcessId, accessDenied, terminated);
return model;
}
@@ -384,22 +566,128 @@ namespace ThreadPilot.Services
process.MainWindowHandle = p.MainWindowHandle;
process.MainWindowTitle = p.MainWindowTitle ?? string.Empty;
process.HasVisibleWindow = process.MainWindowHandle != IntPtr.Zero && !string.IsNullOrWhiteSpace(process.MainWindowTitle);
this.ApplyProcessClassification(
process,
this.foregroundProcessService?.TryGetForegroundProcessId(),
accessDenied: false,
terminated: false);
}
catch (ArgumentException)
{
// Process with the specified ID does not exist
this.CleanupProcessResources(process.ProcessId);
this.ApplyProcessClassification(process, null, accessDenied: false, terminated: true);
throw new InvalidOperationException("Process no longer exists");
}
catch (Exception ex) when (IsAccessDeniedException(ex))
{
this.ApplyProcessClassification(process, null, accessDenied: true, terminated: false);
throw new InvalidOperationException("Access denied while refreshing process information.", ex);
}
catch (Exception ex) when (ex.Message.Contains("exited") || ex.Message.Contains("terminated"))
{
// Process has terminated
this.CleanupProcessResources(process.ProcessId);
this.ApplyProcessClassification(process, null, accessDenied: false, terminated: true);
throw new InvalidOperationException("Process has terminated");
}
}).ConfigureAwait(false);
}
private void ApplyProcessClassification(
ProcessModel process,
int? foregroundProcessId,
bool accessDenied,
bool terminated)
{
process.IsForeground = foregroundProcessId == process.ProcessId && !accessDenied && !terminated;
process.Classification = this.processClassifier.Classify(
process,
new ProcessClassificationContext(foregroundProcessId, accessDenied, terminated));
}
private void LogPassiveProcessReadFailure(int processId, PassiveProcessErrorKind errorKind, Exception exception)
{
if (this.passiveProcessErrorThrottle.ShouldLog(processId, errorKind))
{
this.logger?.LogDebug(
exception,
"Passive process read returned {ErrorKind} for PID {ProcessId}",
errorKind,
processId);
}
}
internal static bool IsPassiveProcessAccessException(Exception exception)
{
return IsAccessDeniedException(exception) ||
exception is Win32Exception { NativeErrorCode: 299 } ||
exception.Message.Contains("enumerate the process modules", StringComparison.OrdinalIgnoreCase) ||
exception.Message.Contains("access modules", StringComparison.OrdinalIgnoreCase) ||
exception.Message.Contains("ReadProcessMemory", StringComparison.OrdinalIgnoreCase);
}
private static bool IsAccessDeniedException(Exception exception)
{
return exception is UnauthorizedAccessException ||
exception is Win32Exception { NativeErrorCode: 5 };
}
private static bool IsTerminatedProcessException(Exception exception)
{
return exception is ArgumentException ||
(exception is InvalidOperationException invalidOperationException &&
(invalidOperationException.Message.Contains("exited", StringComparison.OrdinalIgnoreCase) ||
invalidOperationException.Message.Contains("terminated", StringComparison.OrdinalIgnoreCase) ||
invalidOperationException.Message.Contains("no longer exists", StringComparison.OrdinalIgnoreCase)));
}
private static int? TryGetProcessId(Process process)
{
try
{
return process.Id;
}
catch
{
return null;
}
}
private static ProcessModel? CreateMinimalProcessModel(
Process process,
int? processId,
ProcessClassification classification)
{
if (!processId.HasValue)
{
return null;
}
return new ProcessModel
{
ProcessId = processId.Value,
Name = TryGetProcessName(process, processId.Value),
ExecutablePath = string.Empty,
MainWindowHandle = IntPtr.Zero,
MainWindowTitle = string.Empty,
HasVisibleWindow = false,
Classification = classification,
};
}
private static string TryGetProcessName(Process process, int processId)
{
try
{
return process.ProcessName;
}
catch
{
return $"PID_{processId}";
}
}
/// <summary>
/// Cleanup resources associated with a process.
/// </summary>
@@ -518,9 +806,10 @@ namespace ThreadPilot.Services
{
try
{
var foregroundProcessId = this.foregroundProcessService?.TryGetForegroundProcessId();
var processes = Process.GetProcessesByName(executableName)
.Select(this.CreateProcessModel)
.Where(p => p != null);
.Select(process => this.TryCreateProcessModel(process, foregroundProcessId))
.OfType<ProcessModel>();
return processes;
}
@@ -541,9 +830,11 @@ namespace ThreadPilot.Services
{
return await Task.Run(() =>
{
var foregroundProcessId = this.foregroundProcessService?.TryGetForegroundProcessId();
var processes = Process.GetProcesses()
.Select(this.CreateProcessModel)
.Where(p => p != null && !string.IsNullOrEmpty(p.ExecutablePath))
.Select(process => this.TryCreateProcessModel(process, foregroundProcessId))
.OfType<ProcessModel>()
.Where(p => !string.IsNullOrEmpty(p.ExecutablePath))
.OrderBy(p => p.Name);
return processes;
@@ -554,9 +845,11 @@ namespace ThreadPilot.Services
{
return await Task.Run(() =>
{
var foregroundProcessId = this.foregroundProcessService?.TryGetForegroundProcessId();
var processes = Process.GetProcesses()
.Select(this.CreateProcessModel)
.Where(p => p != null && p.HasVisibleWindow)
.Select(process => this.TryCreateProcessModel(process, foregroundProcessId))
.OfType<ProcessModel>()
.Where(p => p.HasVisibleWindow)
.OrderBy(p => p.Name);
return new ObservableCollection<ProcessModel>(processes);
+6
View File
@@ -99,11 +99,17 @@ namespace ThreadPilot.Services
private static IServiceCollection ConfigureCoreSystemServices(this IServiceCollection services)
{
// Core system interaction services
services.AddSingleton<IForegroundWindowProvider, WindowsForegroundWindowProvider>();
services.AddSingleton<IForegroundProcessService, ForegroundProcessService>();
services.AddSingleton<IPassiveProcessErrorThrottle, PassiveProcessErrorThrottle>();
services.AddSingleton<IProcessClassifier, ProcessClassifier>();
services.AddSingleton<IProcessService, ProcessService>();
services.AddSingleton<IAffinityApplyService, AffinityApplyService>();
services.AddSingleton<ProcessFilterService>();
services.AddSingleton<IVirtualizedProcessService, VirtualizedProcessService>();
services.AddSingleton<IConditionalProfileService, ConditionalProfileService>();
services.AddSingleton<IPowerPlanService, PowerPlanService>();
services.AddSingleton<PowerPlanTransitionGate>();
services.AddSingleton<ICpuTopologyService, CpuTopologyService>();
// CoreMaskService needs IServiceProvider for checking profile references
+7 -7
View File
@@ -134,7 +134,7 @@ namespace ThreadPilot.Services
this.performanceMenuItem.Click += this.OnPerformanceDashboardClick;
this.contextMenu.Items.Add(this.performanceMenuItem);
this.monitoringToggleMenuItem = new ToolStripMenuItem("Pause Monitoring");
this.monitoringToggleMenuItem = new ToolStripMenuItem("Pause Automation Monitoring");
this.monitoringToggleMenuItem.Click += this.OnMonitoringToggleClick;
this.contextMenu.Items.Add(this.monitoringToggleMenuItem);
@@ -157,7 +157,7 @@ namespace ThreadPilot.Services
this.contextMenu.Items.Add(this.selectedProcessMenuItem);
// Quick apply command
this.quickApplyMenuItem = new ToolStripMenuItem("Quick Apply to Selected Process")
this.quickApplyMenuItem = new ToolStripMenuItem("Apply Pending Settings to Selected Process")
{
Enabled = false,
};
@@ -237,13 +237,13 @@ namespace ThreadPilot.Services
{
this.selectedProcessMenuItem.Text = $"Selected: {selectedProcessName}";
this.quickApplyMenuItem.Enabled = true;
this.quickApplyMenuItem.Text = $"Quick Apply to {selectedProcessName}";
this.quickApplyMenuItem.Text = $"Apply Pending Settings to {selectedProcessName}";
}
else
{
this.selectedProcessMenuItem.Text = "No process selected";
this.quickApplyMenuItem.Enabled = false;
this.quickApplyMenuItem.Text = "Quick Apply to Selected Process";
this.quickApplyMenuItem.Text = "Apply Pending Settings to Selected Process";
}
}
@@ -307,7 +307,7 @@ namespace ThreadPilot.Services
if (this.monitoringToggleMenuItem != null)
{
this.monitoringToggleMenuItem.Text = isMonitoring ? "Pause Monitoring" : "Resume Monitoring";
this.monitoringToggleMenuItem.Text = isMonitoring ? "Pause Automation Monitoring" : "Resume Automation Monitoring";
this.monitoringToggleMenuItem.Enabled = isWmiAvailable;
}
@@ -317,8 +317,8 @@ namespace ThreadPilot.Services
this.UpdateTrayIcon(iconState);
// Update tooltip
var status = !isWmiAvailable ? "WMI Error" :
isMonitoring ? "Monitoring Active" : "Monitoring Disabled";
var status = !isWmiAvailable ? "Automation WMI Error" :
isMonitoring ? "Automation Active" : "Automation Disabled";
this.UpdateTooltip($"ThreadPilot - {status}");
}
+1 -1
View File
@@ -274,7 +274,7 @@ namespace ThreadPilot.Services
{
TaskSafety.FireAndForget(this.BackgroundPreloadCallbackAsync(), ex =>
{
this.logger.LogWarning(ex, "Background process refresh failed");
this.logger.LogDebug(ex, "Background process refresh failed");
});
}
@@ -0,0 +1,78 @@
/*
* 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/>.
*/
namespace ThreadPilot.Services
{
using System;
using System.Runtime.InteropServices;
public sealed class WindowsForegroundWindowProvider : IForegroundWindowProvider
{
private const int DwmwaCloaked = 14;
public bool TryGetForegroundWindow(out ForegroundWindowSnapshot snapshot)
{
snapshot = default;
var windowHandle = GetForegroundWindow();
if (windowHandle == IntPtr.Zero)
{
return false;
}
_ = GetWindowThreadProcessId(windowHandle, out var processId);
if (processId == 0)
{
return false;
}
snapshot = new ForegroundWindowSnapshot(
windowHandle,
unchecked((int)processId),
IsWindowVisible(windowHandle),
IsWindowCloaked(windowHandle));
return true;
}
private static bool IsWindowCloaked(IntPtr windowHandle)
{
var result = DwmGetWindowAttribute(
windowHandle,
DwmwaCloaked,
out int cloaked,
Marshal.SizeOf<int>());
return result == 0 && cloaked != 0;
}
[DllImport("dwmapi.dll", PreserveSig = true)]
private static extern int DwmGetWindowAttribute(
IntPtr hwnd,
int dwAttribute,
out int pvAttribute,
int cbAttribute);
[DllImport("user32.dll")]
private static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll")]
private static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint processId);
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool IsWindowVisible(IntPtr hWnd);
}
}
@@ -0,0 +1,211 @@
namespace ThreadPilot.Core.Tests
{
using Microsoft.Extensions.Logging.Abstractions;
using Moq;
using ThreadPilot.Models;
using ThreadPilot.Services;
public sealed class AffinityApplyServiceTests
{
[Fact]
public async Task ApplyAsync_WhenVerifiedMaskMatches_ReturnsSuccess()
{
var process = new ProcessModel { ProcessId = 42, Name = "Game", ProcessorAffinity = 3 };
var processService = CreateProcessService(processStillRunning: true);
processService
.Setup(service => service.SetProcessorAffinity(process, 1))
.Returns(Task.CompletedTask);
processService
.Setup(service => service.RefreshProcessInfo(process))
.Callback(() => process.ProcessorAffinity = 1)
.Returns(Task.CompletedTask);
var service = CreateService(processService);
var result = await service.ApplyAsync(process, 1);
Assert.True(result.Success);
Assert.Equal(1, result.RequestedMask);
Assert.Equal(1, result.VerifiedMask);
Assert.Equal(AffinityApplyFailureReason.None, result.FailureReason);
}
[Fact]
public async Task ApplyAsync_WhenProcessIsTerminated_ReturnsFailureWithoutApplying()
{
var process = new ProcessModel { ProcessId = 42, Name = "Game", ProcessorAffinity = 3 };
var processService = CreateProcessService(processStillRunning: false);
var service = CreateService(processService);
var result = await service.ApplyAsync(process, 1);
Assert.False(result.Success);
Assert.Equal(AffinityApplyFailureReason.ProcessTerminated, result.FailureReason);
processService.Verify(
service => service.SetProcessorAffinity(It.IsAny<ProcessModel>(), It.IsAny<long>()),
Times.Never);
}
[Fact]
public async Task ApplyAsync_WhenAccessDenied_ReturnsAccessDeniedFailure()
{
var process = new ProcessModel { ProcessId = 42, Name = "Game", ProcessorAffinity = 3 };
var processService = CreateProcessService(processStillRunning: true);
processService
.Setup(service => service.SetProcessorAffinity(process, 1))
.ThrowsAsync(new InvalidOperationException("Access denied while setting processor affinity."));
var service = CreateService(processService);
var result = await service.ApplyAsync(process, 1);
Assert.False(result.Success);
Assert.Equal(AffinityApplyFailureReason.AccessDenied, result.FailureReason);
Assert.Equal(3, result.VerifiedMask);
}
[Fact]
public async Task ApplyAsync_WhenVerifiedMaskDiffers_ReturnsMismatchFailure()
{
var process = new ProcessModel { ProcessId = 42, Name = "Game", ProcessorAffinity = 3 };
var processService = CreateProcessService(processStillRunning: true);
processService
.Setup(service => service.SetProcessorAffinity(process, 1))
.Returns(Task.CompletedTask);
processService
.Setup(service => service.RefreshProcessInfo(process))
.Callback(() => process.ProcessorAffinity = 2)
.Returns(Task.CompletedTask);
var service = CreateService(processService);
var result = await service.ApplyAsync(process, 1);
Assert.False(result.Success);
Assert.Equal(AffinityApplyFailureReason.VerificationMismatch, result.FailureReason);
Assert.Equal(1, result.RequestedMask);
Assert.Equal(2, result.VerifiedMask);
}
[Fact]
public async Task ApplyAsync_WhenMaskIsZero_ReturnsInvalidMaskFailure()
{
var process = new ProcessModel { ProcessId = 42, Name = "Game", ProcessorAffinity = 3 };
var processService = CreateProcessService(processStillRunning: true);
var service = CreateService(processService);
var result = await service.ApplyAsync(process, 0);
Assert.False(result.Success);
Assert.Equal(AffinityApplyFailureReason.InvalidMask, result.FailureReason);
}
[Fact]
public async Task ApplyAsync_WhenTopologyRejectsMask_ReturnsInvalidMaskFailure()
{
var process = new ProcessModel { ProcessId = 42, Name = "Game", ProcessorAffinity = 3 };
var processService = CreateProcessService(processStillRunning: true);
var topologyService = new Mock<ICpuTopologyService>(MockBehavior.Strict);
topologyService.Setup(service => service.IsAffinityMaskValid(8)).Returns(false);
var service = CreateService(processService, topologyService);
var result = await service.ApplyAsync(process, 8);
Assert.False(result.Success);
Assert.Equal(AffinityApplyFailureReason.InvalidMask, result.FailureReason);
processService.Verify(
service => service.SetProcessorAffinity(It.IsAny<ProcessModel>(), It.IsAny<long>()),
Times.Never);
}
[Fact]
public async Task ApplyAsync_WhenProcessStateCheckIsAccessDenied_StillAttemptsApply()
{
var process = new ProcessModel { ProcessId = 42, Name = "Game", ProcessorAffinity = 3 };
var processService = new Mock<IProcessService>(MockBehavior.Strict);
processService
.Setup(service => service.IsProcessStillRunning(process))
.ThrowsAsync(new UnauthorizedAccessException("Access denied."));
processService
.Setup(service => service.SetProcessorAffinity(process, 1))
.Returns(Task.CompletedTask);
processService
.Setup(service => service.RefreshProcessInfo(process))
.Callback(() => process.ProcessorAffinity = 1)
.Returns(Task.CompletedTask);
var service = CreateService(processService);
var result = await service.ApplyAsync(process, 1);
Assert.True(result.Success);
processService.Verify(service => service.SetProcessorAffinity(process, 1), Times.Once);
}
[Fact]
public async Task ApplyAsync_WhenRefreshAfterApplyIsAccessDenied_ReportsVerificationMismatch()
{
var process = new ProcessModel { ProcessId = 42, Name = "Game", ProcessorAffinity = 3 };
var processService = CreateProcessService(processStillRunning: true);
processService
.Setup(service => service.SetProcessorAffinity(process, 1))
.Returns(Task.CompletedTask);
processService
.Setup(service => service.RefreshProcessInfo(process))
.ThrowsAsync(new UnauthorizedAccessException("Access denied."));
var service = CreateService(processService);
var result = await service.ApplyAsync(process, 1);
Assert.False(result.Success);
Assert.Equal(AffinityApplyFailureReason.VerificationMismatch, result.FailureReason);
Assert.Equal(3, result.VerifiedMask);
}
[Fact]
public async Task ApplyAsync_WhenApplyThrowsUnexpectedError_ReturnsApplyFailed()
{
var process = new ProcessModel { ProcessId = 42, Name = "Game", ProcessorAffinity = 3 };
var processService = CreateProcessService(processStillRunning: true);
processService
.Setup(service => service.SetProcessorAffinity(process, 1))
.ThrowsAsync(new InvalidOperationException("Driver rejected request."));
processService
.Setup(service => service.RefreshProcessInfo(process))
.Returns(Task.CompletedTask);
var service = CreateService(processService);
var result = await service.ApplyAsync(process, 1);
Assert.False(result.Success);
Assert.Equal(AffinityApplyFailureReason.ApplyFailed, result.FailureReason);
Assert.Equal(3, result.VerifiedMask);
}
private static AffinityApplyService CreateService(Mock<IProcessService> processService)
{
var topologyService = new Mock<ICpuTopologyService>(MockBehavior.Loose);
topologyService.Setup(service => service.IsAffinityMaskValid(It.IsAny<long>())).Returns(true);
return CreateService(processService, topologyService);
}
private static AffinityApplyService CreateService(
Mock<IProcessService> processService,
Mock<ICpuTopologyService> topologyService)
{
return new AffinityApplyService(
processService.Object,
topologyService.Object,
NullLogger<AffinityApplyService>.Instance);
}
private static Mock<IProcessService> CreateProcessService(bool processStillRunning)
{
var processService = new Mock<IProcessService>(MockBehavior.Strict);
processService
.Setup(service => service.IsProcessStillRunning(It.IsAny<ProcessModel>()))
.ReturnsAsync(processStillRunning);
return processService;
}
}
}
@@ -0,0 +1,44 @@
namespace ThreadPilot.Core.Tests
{
using ThreadPilot.Services;
public sealed class AppRefreshPolicyTests
{
[Theory]
[InlineData(AppActivityState.ForegroundProcessView, true, true, true, true, true, true)]
[InlineData(AppActivityState.ForegroundOtherTab, false, false, false, true, true, true)]
[InlineData(AppActivityState.Minimized, false, false, false, false, false, true)]
[InlineData(AppActivityState.TrayHidden, false, false, false, false, false, true)]
public void Evaluate_ReturnsExpectedRefreshDecision(
AppActivityState state,
bool processUiRefreshEnabled,
bool immediateProcessRefresh,
bool virtualizedPreloadEnabled,
bool performanceUiMonitoringEnabled,
bool powerPlanUiRefreshEnabled,
bool backgroundAutomationEnabled)
{
var decision = AppRefreshPolicy.Evaluate(state);
Assert.Equal(processUiRefreshEnabled, decision.ProcessUiRefreshEnabled);
Assert.Equal(immediateProcessRefresh, decision.ImmediateProcessRefresh);
Assert.Equal(virtualizedPreloadEnabled, decision.VirtualizedPreloadEnabled);
Assert.Equal(performanceUiMonitoringEnabled, decision.PerformanceUiMonitoringEnabled);
Assert.Equal(powerPlanUiRefreshEnabled, decision.PowerPlanUiRefreshEnabled);
Assert.Equal(backgroundAutomationEnabled, decision.BackgroundAutomationEnabled);
}
[Fact]
public void Evaluate_WhenStateIsUnknown_KeepsBackgroundAutomationOnly()
{
var decision = AppRefreshPolicy.Evaluate((AppActivityState)999);
Assert.False(decision.ProcessUiRefreshEnabled);
Assert.False(decision.ImmediateProcessRefresh);
Assert.False(decision.VirtualizedPreloadEnabled);
Assert.False(decision.PerformanceUiMonitoringEnabled);
Assert.False(decision.PowerPlanUiRefreshEnabled);
Assert.True(decision.BackgroundAutomationEnabled);
}
}
}
@@ -0,0 +1,68 @@
namespace ThreadPilot.Core.Tests
{
using Microsoft.Extensions.Logging.Abstractions;
using ThreadPilot.Services;
public sealed class ForegroundProcessServiceTests
{
[Fact]
public void TryGetForegroundProcessId_ReturnsPidFromVisibleForegroundWindow()
{
var provider = new FakeForegroundWindowProvider(
new ForegroundWindowSnapshot(new IntPtr(42), 1234, true, false));
var service = new ForegroundProcessService(provider, NullLogger<ForegroundProcessService>.Instance);
var result = service.TryGetForegroundProcessId();
Assert.Equal(1234, result);
}
[Theory]
[InlineData(0, true, false)]
[InlineData(1234, false, false)]
[InlineData(1234, true, true)]
public void TryGetForegroundProcessId_ReturnsNullForInvalidForegroundWindow(int processId, bool isVisible, bool isCloaked)
{
var provider = new FakeForegroundWindowProvider(
new ForegroundWindowSnapshot(new IntPtr(42), processId, isVisible, isCloaked));
var service = new ForegroundProcessService(provider, NullLogger<ForegroundProcessService>.Instance);
var result = service.TryGetForegroundProcessId();
Assert.Null(result);
}
[Fact]
public void TryGetForegroundProcessId_ReturnsNullWhenProviderFails()
{
var provider = new FakeForegroundWindowProvider(null);
var service = new ForegroundProcessService(provider, NullLogger<ForegroundProcessService>.Instance);
var result = service.TryGetForegroundProcessId();
Assert.Null(result);
}
private sealed class FakeForegroundWindowProvider : IForegroundWindowProvider
{
private readonly ForegroundWindowSnapshot? snapshot;
public FakeForegroundWindowProvider(ForegroundWindowSnapshot? snapshot)
{
this.snapshot = snapshot;
}
public bool TryGetForegroundWindow(out ForegroundWindowSnapshot snapshot)
{
if (this.snapshot == null)
{
snapshot = default;
return false;
}
snapshot = this.snapshot.Value;
return true;
}
}
}
}
@@ -0,0 +1,59 @@
namespace ThreadPilot.Core.Tests
{
using ThreadPilot.Services;
public sealed class PassiveProcessErrorThrottleTests
{
[Fact]
public void ShouldLog_ReturnsFalseForRepeatedErrorInsideTtl()
{
var now = new DateTimeOffset(2026, 5, 9, 12, 0, 0, TimeSpan.Zero);
var throttle = new PassiveProcessErrorThrottle(TimeSpan.FromMinutes(1), () => now);
Assert.True(throttle.ShouldLog(42, PassiveProcessErrorKind.AccessDenied));
Assert.False(throttle.ShouldLog(42, PassiveProcessErrorKind.AccessDenied));
}
[Fact]
public void ShouldLog_ReturnsTrueAfterTtlExpires()
{
var now = new DateTimeOffset(2026, 5, 9, 12, 0, 0, TimeSpan.Zero);
var throttle = new PassiveProcessErrorThrottle(TimeSpan.FromMinutes(1), () => now);
Assert.True(throttle.ShouldLog(42, PassiveProcessErrorKind.AccessDenied));
now = now.AddMinutes(2);
Assert.True(throttle.ShouldLog(42, PassiveProcessErrorKind.AccessDenied));
}
[Fact]
public void ShouldLog_TracksPidAndErrorKindSeparately()
{
var now = new DateTimeOffset(2026, 5, 9, 12, 0, 0, TimeSpan.Zero);
var throttle = new PassiveProcessErrorThrottle(TimeSpan.FromMinutes(1), () => now);
Assert.True(throttle.ShouldLog(42, PassiveProcessErrorKind.AccessDenied));
Assert.True(throttle.ShouldLog(42, PassiveProcessErrorKind.Terminated));
Assert.True(throttle.ShouldLog(43, PassiveProcessErrorKind.AccessDenied));
}
[Fact]
public void ShouldLog_WhenElapsedTimeEqualsTtl_ReturnsTrue()
{
var now = new DateTimeOffset(2026, 5, 9, 12, 0, 0, TimeSpan.Zero);
var throttle = new PassiveProcessErrorThrottle(TimeSpan.FromMinutes(1), () => now);
Assert.True(throttle.ShouldLog(42, PassiveProcessErrorKind.Unknown));
now = now.AddMinutes(1);
Assert.True(throttle.ShouldLog(42, PassiveProcessErrorKind.Unknown));
}
[Fact]
public void Constructor_WhenTtlIsZero_Throws()
{
Assert.Throws<ArgumentOutOfRangeException>(() =>
new PassiveProcessErrorThrottle(TimeSpan.Zero, () => DateTimeOffset.UtcNow));
}
}
}
@@ -0,0 +1,89 @@
namespace ThreadPilot.Core.Tests
{
using ThreadPilot.Services;
public sealed class PowerPlanTransitionGateTests
{
[Fact]
public void ShouldApply_WhenTargetWasNotRequested_ReturnsTrue()
{
var now = DateTimeOffset.Parse("2026-05-09T10:00:00Z");
var gate = new PowerPlanTransitionGate(TimeSpan.FromSeconds(2), () => now);
var decision = gate.ShouldApply("plan-game", "balanced");
Assert.True(decision.ShouldApply);
Assert.Equal(PowerPlanTransitionSuppressionReason.None, decision.SuppressionReason);
}
[Fact]
public void ShouldApply_WhenTargetIsAlreadyActive_ReturnsFalse()
{
var now = DateTimeOffset.Parse("2026-05-09T10:00:00Z");
var gate = new PowerPlanTransitionGate(TimeSpan.FromSeconds(2), () => now);
var decision = gate.ShouldApply("plan-game", "plan-game");
Assert.False(decision.ShouldApply);
Assert.Equal(PowerPlanTransitionSuppressionReason.AlreadyActive, decision.SuppressionReason);
}
[Fact]
public void ShouldApply_WhenSameTargetWasRecentlyRequested_ReturnsFalse()
{
var now = DateTimeOffset.Parse("2026-05-09T10:00:00Z");
var gate = new PowerPlanTransitionGate(TimeSpan.FromSeconds(2), () => now);
Assert.True(gate.ShouldApply("plan-game", "balanced").ShouldApply);
gate.RecordAttempt("plan-game");
now = now.AddMilliseconds(500);
var decision = gate.ShouldApply("plan-game", "balanced");
Assert.False(decision.ShouldApply);
Assert.Equal(PowerPlanTransitionSuppressionReason.RecentDuplicateRequest, decision.SuppressionReason);
}
[Fact]
public void ShouldApply_WhenDifferentTargetArrives_UsesLatestTarget()
{
var now = DateTimeOffset.Parse("2026-05-09T10:00:00Z");
var gate = new PowerPlanTransitionGate(TimeSpan.FromSeconds(2), () => now);
gate.RecordAttempt("plan-game");
now = now.AddMilliseconds(500);
var decision = gate.ShouldApply("plan-default", "plan-game");
Assert.True(decision.ShouldApply);
}
[Fact]
public void ShouldApply_WhenDuplicateWindowExpires_ReturnsTrue()
{
var now = DateTimeOffset.Parse("2026-05-09T10:00:00Z");
var gate = new PowerPlanTransitionGate(TimeSpan.FromSeconds(2), () => now);
gate.RecordAttempt("plan-game");
now = now.AddSeconds(3);
var decision = gate.ShouldApply("plan-game", "balanced");
Assert.True(decision.ShouldApply);
Assert.Equal(PowerPlanTransitionSuppressionReason.None, decision.SuppressionReason);
}
[Fact]
public void Constructor_WhenDuplicateWindowIsNegative_UsesZeroWindow()
{
var now = DateTimeOffset.Parse("2026-05-09T10:00:00Z");
var gate = new PowerPlanTransitionGate(TimeSpan.FromSeconds(-1), () => now);
gate.RecordAttempt("plan-game");
var decision = gate.ShouldApply("plan-game", "balanced");
Assert.True(decision.ShouldApply);
}
}
}
@@ -0,0 +1,149 @@
namespace ThreadPilot.Core.Tests
{
using ThreadPilot.Models;
using ThreadPilot.Services;
public sealed class ProcessClassifierTests
{
[Fact]
public void Classify_ReturnsForegroundAppForForegroundPid()
{
var classifier = new ProcessClassifier(new ProcessFilterService());
var process = new ProcessModel
{
ProcessId = 10,
Name = "Game",
HasVisibleWindow = true,
};
var result = classifier.Classify(process, new ProcessClassificationContext(10));
Assert.Equal(ProcessClassification.ForegroundApp, result);
}
[Fact]
public void Classify_ReturnsVisibleWindowAppForVisibleNonForegroundProcess()
{
var classifier = new ProcessClassifier(new ProcessFilterService());
var process = new ProcessModel
{
ProcessId = 10,
Name = "Editor",
HasVisibleWindow = true,
};
var result = classifier.Classify(process, new ProcessClassificationContext(20));
Assert.Equal(ProcessClassification.VisibleWindowApp, result);
}
[Theory]
[InlineData("svchost")]
[InlineData("svchost.exe")]
public void Classify_ReturnsSystemForNormalizedSystemProcessNames(string processName)
{
var classifier = new ProcessClassifier(new ProcessFilterService());
var process = new ProcessModel
{
ProcessId = 10,
Name = processName,
};
var result = classifier.Classify(process, new ProcessClassificationContext(null));
Assert.Equal(ProcessClassification.System, result);
}
[Fact]
public void Classify_ReturnsProtectedOrAccessDeniedWhenAccessWasDenied()
{
var classifier = new ProcessClassifier(new ProcessFilterService());
var process = new ProcessModel
{
ProcessId = 10,
Name = "ProtectedProcess",
};
var result = classifier.Classify(process, new ProcessClassificationContext(null, AccessDenied: true));
Assert.Equal(ProcessClassification.ProtectedOrAccessDenied, result);
}
[Fact]
public void Classify_ReturnsTerminatedWhenProcessTerminated()
{
var classifier = new ProcessClassifier(new ProcessFilterService());
var process = new ProcessModel
{
ProcessId = 10,
Name = "ClosedProcess",
};
var result = classifier.Classify(process, new ProcessClassificationContext(null, Terminated: true));
Assert.Equal(ProcessClassification.Terminated, result);
}
[Fact]
public void Classify_ReturnsBackgroundUserForNonSystemProcessWithoutWindow()
{
var classifier = new ProcessClassifier(new ProcessFilterService());
var process = new ProcessModel
{
ProcessId = 10,
Name = "Worker",
};
var result = classifier.Classify(process, new ProcessClassificationContext(null));
Assert.Equal(ProcessClassification.BackgroundUser, result);
}
[Fact]
public void Classify_TerminatedTakesPrecedenceOverForegroundAndSystem()
{
var classifier = new ProcessClassifier(new ProcessFilterService());
var process = new ProcessModel
{
ProcessId = 10,
Name = "svchost",
HasVisibleWindow = true,
};
var result = classifier.Classify(process, new ProcessClassificationContext(10, Terminated: true));
Assert.Equal(ProcessClassification.Terminated, result);
}
[Fact]
public void Classify_AccessDeniedTakesPrecedenceOverForegroundAndWindow()
{
var classifier = new ProcessClassifier(new ProcessFilterService());
var process = new ProcessModel
{
ProcessId = 10,
Name = "ProtectedWindow",
HasVisibleWindow = true,
};
var result = classifier.Classify(process, new ProcessClassificationContext(10, AccessDenied: true));
Assert.Equal(ProcessClassification.ProtectedOrAccessDenied, result);
}
[Fact]
public void Classify_ReturnsUnknownWhenNameIsMissing()
{
var classifier = new ProcessClassifier(new ProcessFilterService());
var process = new ProcessModel
{
ProcessId = 10,
Name = string.Empty,
};
var result = classifier.Classify(process, new ProcessClassificationContext(null));
Assert.Equal(ProcessClassification.Unknown, result);
}
}
}
@@ -0,0 +1,134 @@
namespace ThreadPilot.Core.Tests
{
using System.Collections.ObjectModel;
using System.Diagnostics;
using ThreadPilot.Models;
using ThreadPilot.Services;
public sealed class ProcessListDeltaUpdaterTests
{
[Fact]
public void ApplyDelta_PreservesExistingInstancesAndUpdatesProperties()
{
var existing = new ProcessModel
{
ProcessId = 42,
Name = "ThreadPilot",
CpuUsage = 1,
MemoryUsage = 100,
Priority = ProcessPriorityClass.Normal,
ProcessorAffinity = 1,
};
var processes = new ObservableCollection<ProcessModel> { existing };
var snapshot = new[]
{
new ProcessModel
{
ProcessId = 42,
Name = "ThreadPilot",
CpuUsage = 7,
MemoryUsage = 500,
Priority = ProcessPriorityClass.High,
ProcessorAffinity = 3,
HasVisibleWindow = true,
IsForeground = true,
Classification = ProcessClassification.ForegroundApp,
MainWindowTitle = "ThreadPilot - Processes",
},
};
var result = ProcessListDeltaUpdater.ApplyDelta(processes, snapshot, 42);
Assert.Same(existing, processes[0]);
Assert.Same(existing, result.SelectedProcess);
Assert.False(result.SelectedProcessTerminated);
Assert.Equal(7, existing.CpuUsage);
Assert.Equal(500, existing.MemoryUsage);
Assert.Equal(ProcessPriorityClass.High, existing.Priority);
Assert.Equal(3, existing.ProcessorAffinity);
Assert.True(existing.HasVisibleWindow);
Assert.True(existing.IsForeground);
Assert.Equal(ProcessClassification.ForegroundApp, existing.Classification);
Assert.Equal("ThreadPilot - Processes", existing.MainWindowTitle);
}
[Fact]
public void ApplyDelta_AddsNewProcessesAndRemovesDeadProcesses()
{
var removed = new ProcessModel { ProcessId = 10, Name = "Dead" };
var kept = new ProcessModel { ProcessId = 20, Name = "Kept" };
var processes = new ObservableCollection<ProcessModel> { removed, kept };
var snapshot = new[]
{
new ProcessModel { ProcessId = 20, Name = "Kept" },
new ProcessModel { ProcessId = 30, Name = "New" },
};
var result = ProcessListDeltaUpdater.ApplyDelta(processes, snapshot, 20);
Assert.Equal(2, processes.Count);
Assert.DoesNotContain(processes, p => p.ProcessId == 10);
Assert.Contains(processes, p => p.ProcessId == 30);
Assert.Same(kept, result.SelectedProcess);
Assert.False(result.SelectedProcessTerminated);
}
[Fact]
public void ApplyDelta_ReportsTerminatedSelection()
{
var selected = new ProcessModel { ProcessId = 10, Name = "Dead" };
var processes = new ObservableCollection<ProcessModel> { selected };
var result = ProcessListDeltaUpdater.ApplyDelta(processes, Array.Empty<ProcessModel>(), 10);
Assert.Empty(processes);
Assert.Null(result.SelectedProcess);
Assert.True(result.SelectedProcessTerminated);
}
[Fact]
public void ApplyDelta_WhenSnapshotContainsDuplicatePid_UsesLatestSnapshot()
{
var existing = new ProcessModel { ProcessId = 42, Name = "Old" };
var processes = new ObservableCollection<ProcessModel> { existing };
var snapshot = new[]
{
new ProcessModel { ProcessId = 42, Name = "First", CpuUsage = 1 },
new ProcessModel { ProcessId = 42, Name = "Latest", CpuUsage = 9 },
};
var result = ProcessListDeltaUpdater.ApplyDelta(processes, snapshot, 42);
Assert.Single(processes);
Assert.Same(existing, processes[0]);
Assert.Same(existing, result.SelectedProcess);
Assert.Equal("Latest", existing.Name);
Assert.Equal(9, existing.CpuUsage);
}
[Fact]
public void ApplyDelta_PreservesSelectionDuringAddRemoveChurn()
{
var selected = new ProcessModel { ProcessId = 20, Name = "Selected" };
var processes = new ObservableCollection<ProcessModel>
{
new() { ProcessId = 10, Name = "Removed" },
selected,
};
var snapshot = new[]
{
new ProcessModel { ProcessId = 20, Name = "Selected Updated" },
new ProcessModel { ProcessId = 30, Name = "Added" },
};
var result = ProcessListDeltaUpdater.ApplyDelta(processes, snapshot, 20);
Assert.Equal(2, processes.Count);
Assert.Same(selected, result.SelectedProcess);
Assert.False(result.SelectedProcessTerminated);
Assert.DoesNotContain(processes, process => process.ProcessId == 10);
Assert.Contains(processes, process => process.ProcessId == 30);
}
}
}
@@ -25,13 +25,15 @@ namespace ThreadPilot.Core.Tests
var notificationService = CreateNotificationService();
var processService = CreateProcessService();
var coreMaskService = CreateCoreMaskService();
var affinityApplyService = CreateAffinityApplyService();
var manager = CreateService(
processMonitor,
associationService,
powerPlanService,
notificationService,
processService,
coreMaskService);
coreMaskService,
affinityApplyService);
await manager.StartAsync();
@@ -68,13 +70,15 @@ namespace ThreadPilot.Core.Tests
var notificationService = CreateNotificationService();
var processService = CreateProcessService();
var coreMaskService = CreateCoreMaskService();
var affinityApplyService = CreateAffinityApplyService();
var manager = CreateService(
processMonitor,
associationService,
powerPlanService,
notificationService,
processService,
coreMaskService);
coreMaskService,
affinityApplyService);
await manager.StartAsync();
@@ -104,13 +108,15 @@ namespace ThreadPilot.Core.Tests
var notificationService = CreateNotificationService();
var processService = CreateProcessService();
var coreMaskService = CreateCoreMaskService();
var affinityApplyService = CreateAffinityApplyService();
var manager = CreateService(
processMonitor,
associationService,
powerPlanService,
notificationService,
processService,
coreMaskService);
coreMaskService,
affinityApplyService);
await manager.StartAsync();
processMonitor.RaiseProcessStarted(new ProcessModel { ProcessId = 10, Name = "game" });
@@ -123,6 +129,90 @@ namespace ThreadPilot.Core.Tests
Times.Once);
}
[Fact]
public async Task ProcessStarted_SamePlanRequest_IsSuppressedWithinDuplicateWindow()
{
var processMonitor = new FakeProcessMonitorService();
var configuration = new ProcessMonitorConfiguration
{
PowerPlanChangeDelayMs = 0,
Associations =
{
new ProcessPowerPlanAssociation("game", "plan-game", "Game") { Priority = 5 },
},
};
var associationService = CreateAssociationService(configuration);
var powerPlanService = CreatePowerPlanService();
var notificationService = CreateNotificationService();
var processService = CreateProcessService();
var coreMaskService = CreateCoreMaskService();
var affinityApplyService = CreateAffinityApplyService();
var manager = CreateService(
processMonitor,
associationService,
powerPlanService,
notificationService,
processService,
coreMaskService,
affinityApplyService);
await manager.StartAsync();
processMonitor.RaiseProcessStarted(new ProcessModel { ProcessId = 10, Name = "game" });
processMonitor.RaiseProcessStarted(new ProcessModel { ProcessId = 11, Name = "game" });
await Task.Delay(100);
powerPlanService.Verify(
x => x.SetActivePowerPlanByGuidAsync("plan-game", true),
Times.Once);
}
[Fact]
public async Task ProcessStarted_WhenPowerPlanChangeFails_DoesNotRetrySamePlanImmediately()
{
var processMonitor = new FakeProcessMonitorService();
var configuration = new ProcessMonitorConfiguration
{
PowerPlanChangeDelayMs = 0,
Associations =
{
new ProcessPowerPlanAssociation("game", "plan-game", "Game") { Priority = 5 },
},
};
var associationService = CreateAssociationService(configuration);
var powerPlanService = CreatePowerPlanService();
powerPlanService
.Setup(x => x.SetActivePowerPlanByGuidAsync("plan-game", true))
.ReturnsAsync(false);
var notificationService = CreateNotificationService();
var processService = CreateProcessService();
var coreMaskService = CreateCoreMaskService();
var affinityApplyService = CreateAffinityApplyService();
var manager = CreateService(
processMonitor,
associationService,
powerPlanService,
notificationService,
processService,
coreMaskService,
affinityApplyService);
await manager.StartAsync();
processMonitor.RaiseProcessStarted(new ProcessModel { ProcessId = 10, Name = "game" });
processMonitor.RaiseProcessStarted(new ProcessModel { ProcessId = 11, Name = "game" });
await Task.Delay(100);
powerPlanService.Verify(
x => x.SetActivePowerPlanByGuidAsync("plan-game", true),
Times.Once);
notificationService.Verify(
x => x.ShowPowerPlanChangeNotificationAsync(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()),
Times.Never);
}
[Fact]
public async Task StopAsync_RestoresDefaultPowerPlan_WhenConfigured()
{
@@ -150,13 +240,15 @@ namespace ThreadPilot.Core.Tests
var notificationService = CreateNotificationService();
var processService = CreateProcessService();
var coreMaskService = CreateCoreMaskService();
var affinityApplyService = CreateAffinityApplyService();
var manager = CreateService(
processMonitor,
associationService,
powerPlanService,
notificationService,
processService,
coreMaskService);
coreMaskService,
affinityApplyService);
await manager.StartAsync();
await manager.StopAsync();
@@ -168,6 +260,60 @@ namespace ThreadPilot.Core.Tests
coreMaskService.Verify(x => x.UnregisterMaskApplication(21), Times.Once);
}
[Fact]
public async Task ProcessStarted_AppliesConfiguredCoreMaskForMatchingProcess()
{
var process = new ProcessModel { ProcessId = 31, Name = "game" };
var processMonitor = new FakeProcessMonitorService();
var configuration = new ProcessMonitorConfiguration
{
PowerPlanChangeDelayMs = 0,
Associations =
{
new ProcessPowerPlanAssociation("game", "plan-game", "Game")
{
CoreMaskId = "mask-game",
Priority = 5,
},
},
};
var associationService = CreateAssociationService(configuration);
var powerPlanService = CreatePowerPlanService();
var notificationService = CreateNotificationService();
var processService = CreateProcessService();
processService.Setup(x => x.TrackAppliedMask(31, "mask-game"));
var coreMaskService = CreateCoreMaskService();
coreMaskService.SetupGet(x => x.AvailableMasks).Returns(new ObservableCollection<CoreMask>
{
new()
{
Id = "mask-game",
Name = "Game Mask",
BoolMask = new ObservableCollection<bool> { true, false },
},
});
coreMaskService.Setup(x => x.RegisterMaskApplication(31, "mask-game"));
var affinityApplyService = CreateAffinityApplyService();
var manager = CreateService(
processMonitor,
associationService,
powerPlanService,
notificationService,
processService,
coreMaskService,
affinityApplyService);
await manager.StartAsync();
processMonitor.RaiseProcessStarted(process);
await Task.Delay(100);
affinityApplyService.Verify(x => x.ApplyAsync(process, 1), Times.Once);
processService.Verify(x => x.TrackAppliedMask(31, "mask-game"), Times.Once);
coreMaskService.Verify(x => x.RegisterMaskApplication(31, "mask-game"), Times.Once);
}
[Fact]
public async Task Dispose_CompletesOnBlockingSynchronizationContext()
{
@@ -185,13 +331,15 @@ namespace ThreadPilot.Core.Tests
var notificationService = CreateNotificationService();
var processService = CreateProcessService();
var coreMaskService = CreateCoreMaskService();
var affinityApplyService = CreateAffinityApplyService();
var manager = CreateService(
processMonitor,
associationService,
powerPlanService,
notificationService,
processService,
coreMaskService);
coreMaskService,
affinityApplyService);
await manager.StartAsync();
@@ -229,7 +377,8 @@ namespace ThreadPilot.Core.Tests
Mock<IPowerPlanService> powerPlanService,
Mock<INotificationService> notificationService,
Mock<IProcessService> processService,
Mock<ICoreMaskService> coreMaskService)
Mock<ICoreMaskService> coreMaskService,
Mock<IAffinityApplyService> affinityApplyService)
{
var enhancedLogger = new Mock<IEnhancedLoggingService>(MockBehavior.Loose);
enhancedLogger
@@ -253,6 +402,8 @@ namespace ThreadPilot.Core.Tests
settingsService.Object,
processService.Object,
coreMaskService.Object,
affinityApplyService.Object,
new PowerPlanTransitionGate(TimeSpan.FromSeconds(2), () => DateTimeOffset.UtcNow),
NullLogger<ProcessMonitorManagerService>.Instance,
enhancedLogger.Object);
}
@@ -303,6 +454,16 @@ namespace ThreadPilot.Core.Tests
return coreMaskService;
}
private static Mock<IAffinityApplyService> CreateAffinityApplyService()
{
var affinityApplyService = new Mock<IAffinityApplyService>(MockBehavior.Strict);
affinityApplyService
.Setup(x => x.ApplyAsync(It.IsAny<ProcessModel>(), It.IsAny<long>()))
.ReturnsAsync((ProcessModel process, long affinity) =>
AffinityApplyResult.Succeeded(affinity, affinity));
return affinityApplyService;
}
private sealed class FakeProcessMonitorService : IProcessMonitorService
{
public event EventHandler<ProcessEventArgs>? ProcessStarted;
@@ -4,6 +4,7 @@
namespace ThreadPilot.Core.Tests
{
using System.Collections.Concurrent;
using System.ComponentModel;
using System.Diagnostics;
using System.Text.Json;
using ThreadPilot.Models;
@@ -67,6 +68,48 @@ namespace ThreadPilot.Core.Tests
}
}
[Fact]
public void IsPassiveProcessAccessException_ReturnsTrue_ForModuleEnumerationFailure()
{
var exception = new Win32Exception(299, "Unable to enumerate the process modules.");
var result = ProcessService.IsPassiveProcessAccessException(exception);
Assert.True(result);
}
[Fact]
public void IsPassiveProcessAccessException_ReturnsTrue_ForUnauthorizedAccess()
{
var exception = new UnauthorizedAccessException("Access denied.");
var result = ProcessService.IsPassiveProcessAccessException(exception);
Assert.True(result);
}
[Theory]
[InlineData("Unable to access modules for this process.")]
[InlineData("ReadProcessMemory failed for protected process.")]
public void IsPassiveProcessAccessException_ReturnsTrue_ForKnownPassiveMessages(string message)
{
var exception = new InvalidOperationException(message);
var result = ProcessService.IsPassiveProcessAccessException(exception);
Assert.True(result);
}
[Fact]
public void IsPassiveProcessAccessException_ReturnsFalse_ForUnrelatedException()
{
var exception = new InvalidOperationException("Unexpected parse failure.");
var result = ProcessService.IsPassiveProcessAccessException(exception);
Assert.False(result);
}
[Fact]
public void TrackPriorityChange_PreservesOriginalPriority()
{
@@ -0,0 +1,104 @@
namespace ThreadPilot.Core.Tests
{
using Microsoft.Extensions.Logging.Abstractions;
using Moq;
using ThreadPilot.Models;
using ThreadPilot.Services;
using ThreadPilot.ViewModels;
public sealed class ProcessViewModelAffinityTests
{
[Fact]
public async Task SelectingCoreMask_DoesNotApplyProcessorAffinity()
{
var processService = new Mock<IProcessService>(MockBehavior.Loose);
var gameModeService = new Mock<IGameModeService>(MockBehavior.Loose);
gameModeService
.Setup(service => service.DisableGameModeForAffinityAsync())
.ReturnsAsync(false);
var viewModel = CreateViewModel(processService.Object, gameModeService.Object);
viewModel.SelectedProcess = new ProcessModel
{
ProcessId = 1234,
Name = "Game",
ProcessorAffinity = 3,
};
viewModel.SelectedCoreMask = CoreMask.FromProcessorAffinity(1, 2, "First Core");
await Task.Delay(100);
processService.Verify(
service => service.SetProcessorAffinity(It.IsAny<ProcessModel>(), It.IsAny<long>()),
Times.Never);
}
[Fact]
public async Task SelectingCoreMask_ReportsPendingAffinityWithoutChangingCurrentAffinity()
{
var processService = new Mock<IProcessService>(MockBehavior.Loose);
var gameModeService = new Mock<IGameModeService>(MockBehavior.Loose);
var viewModel = CreateViewModel(processService.Object, gameModeService.Object);
viewModel.CpuTopology = CreateTwoCoreTopology();
viewModel.CpuCores = new System.Collections.ObjectModel.ObservableCollection<CpuCoreModel>(
viewModel.CpuTopology.LogicalCores);
viewModel.SelectedProcess = new ProcessModel
{
ProcessId = 1234,
Name = "Game",
ProcessorAffinity = 3,
};
viewModel.SelectedCoreMask = CoreMask.FromProcessorAffinity(1, 2, "First Core");
await Task.Delay(100);
Assert.True(viewModel.HasPendingAffinityEdits);
Assert.Equal("Current OS affinity: 0x3", viewModel.CurrentAffinityText);
Assert.Equal("Pending core mask: 0x1", viewModel.PendingAffinityText);
Assert.Equal("Core mask staged. Use Apply Affinity to change Windows affinity.", viewModel.AffinityEditStateText);
}
private static ProcessViewModel CreateViewModel(IProcessService processService, IGameModeService gameModeService)
{
var virtualizedProcessService = new Mock<IVirtualizedProcessService>(MockBehavior.Loose);
virtualizedProcessService.SetupProperty(
service => service.Configuration,
new VirtualizedProcessConfig());
var cpuTopologyService = new Mock<ICpuTopologyService>(MockBehavior.Loose);
var powerPlanService = new Mock<IPowerPlanService>(MockBehavior.Loose);
var notificationService = new Mock<INotificationService>(MockBehavior.Loose);
var systemTrayService = new Mock<ISystemTrayService>(MockBehavior.Loose);
var coreMaskService = new Mock<ICoreMaskService>(MockBehavior.Loose);
var associationService = new Mock<IProcessPowerPlanAssociationService>(MockBehavior.Loose);
return new ProcessViewModel(
NullLogger<ProcessViewModel>.Instance,
processService,
new ProcessFilterService(),
virtualizedProcessService.Object,
cpuTopologyService.Object,
powerPlanService.Object,
notificationService.Object,
systemTrayService.Object,
coreMaskService.Object,
associationService.Object,
gameModeService);
}
private static CpuTopologyModel CreateTwoCoreTopology()
{
return new CpuTopologyModel
{
LogicalCores =
[
new CpuCoreModel { LogicalCoreId = 0, PhysicalCoreId = 0, Label = "CPU 0" },
new CpuCoreModel { LogicalCoreId = 1, PhysicalCoreId = 1, Label = "CPU 1" },
],
};
}
}
}
+9 -9
View File
@@ -37,7 +37,7 @@ namespace ThreadPilot
private bool isProcessMonitoringActive = false;
[ObservableProperty]
private string processMonitoringStatusText = "Process Monitoring: Inactive";
private string processMonitoringStatusText = "Automation Monitoring: Inactive";
[ObservableProperty]
private bool isRunningAsAdministrator = false;
@@ -109,14 +109,14 @@ namespace ThreadPilot
if (this.IsProcessMonitoringActive)
{
await this.processMonitorManagerService.StopAsync();
await this.LogUserActionAsync("ProcessMonitoring", "Stopped process monitoring", "User action");
await this.LogUserActionAsync("ProcessMonitoring", "Stopped automation monitoring", "User action");
}
else
{
await this.processMonitorManagerService.StartAsync();
await this.LogUserActionAsync("ProcessMonitoring", "Started process monitoring", "User action");
await this.LogUserActionAsync("ProcessMonitoring", "Started automation monitoring", "User action");
}
}, this.IsProcessMonitoringActive ? "Stopping monitoring..." : "Starting monitoring...");
}, this.IsProcessMonitoringActive ? "Stopping automation monitoring..." : "Starting automation monitoring...");
}
[RelayCommand]
@@ -151,8 +151,8 @@ namespace ThreadPilot
{
this.IsProcessMonitoringActive = this.processMonitorManagerService.IsRunning;
this.ProcessMonitoringStatusText = this.IsProcessMonitoringActive
? "Process Monitoring: Active"
: "Process Monitoring: Inactive";
? "Automation Monitoring: Active"
: "Automation Monitoring: Inactive";
}
// Update elevation status
@@ -185,7 +185,7 @@ namespace ThreadPilot
System.Windows.Application.Current.Dispatcher.InvokeAsync(() =>
{
this.IsProcessMonitoringActive = e.IsRunning;
this.ProcessMonitoringStatusText = $"Process Monitoring: {e.Status}";
this.ProcessMonitoringStatusText = $"Automation Monitoring: {e.Status}";
});
}
@@ -194,14 +194,14 @@ namespace ThreadPilot
if (System.Windows.Application.Current.Dispatcher.CheckAccess())
{
this.IsProcessMonitoringActive = isActive;
this.ProcessMonitoringStatusText = $"Process Monitoring: {status}";
this.ProcessMonitoringStatusText = $"Automation Monitoring: {status}";
}
else
{
System.Windows.Application.Current.Dispatcher.InvokeAsync(() =>
{
this.IsProcessMonitoringActive = isActive;
this.ProcessMonitoringStatusText = $"Process Monitoring: {status}";
this.ProcessMonitoringStatusText = $"Automation Monitoring: {status}";
});
}
}
+9 -9
View File
@@ -58,7 +58,7 @@ namespace ThreadPilot.ViewModels
private bool isMonitoring;
[ObservableProperty]
private string monitoringStatusText = "Monitoring Stopped";
private string monitoringStatusText = "Live metrics stopped";
[ObservableProperty]
private DateTime lastUpdateTime;
@@ -224,9 +224,9 @@ namespace ThreadPilot.ViewModels
await this.performanceService.StartMonitoringAsync();
this.IsMonitoring = true;
this.MonitoringStatusText = "Monitoring Active";
this.MonitoringStatusText = "Live metrics active";
this.MonitoringStateText = "Active";
this.AddTimelineEvent("Monitoring", "Real-time monitoring started.", "Info");
this.AddTimelineEvent("Live Metrics", "Live metrics started.", "Info");
this.SetStatus("Performance monitoring started", false);
}
@@ -245,9 +245,9 @@ namespace ThreadPilot.ViewModels
await this.performanceService.StopMonitoringAsync();
this.IsMonitoring = false;
this.MonitoringStatusText = "Monitoring Stopped";
this.MonitoringStatusText = "Live metrics stopped";
this.MonitoringStateText = "Stopped";
this.AddTimelineEvent("Monitoring", "Real-time monitoring stopped.", "Warning");
this.AddTimelineEvent("Live Metrics", "Live metrics stopped.", "Warning");
this.SetStatus("Performance monitoring stopped", false);
}
@@ -271,9 +271,9 @@ namespace ThreadPilot.ViewModels
await this.performanceService.StopMonitoringAsync();
this.IsMonitoring = false;
this.MonitoringStatusText = "Monitoring Paused";
this.MonitoringStatusText = "Live metrics paused";
this.MonitoringStateText = "Paused";
this.AddTimelineEvent("Monitoring", "Monitoring paused while app is minimized.", "Info");
this.AddTimelineEvent("Live Metrics", "Live metrics paused while app is minimized.", "Info");
}
catch (Exception ex)
{
@@ -293,9 +293,9 @@ namespace ThreadPilot.ViewModels
await this.performanceService.StartMonitoringAsync();
this.IsMonitoring = true;
this.MonitoringStatusText = "Monitoring Active";
this.MonitoringStatusText = "Live metrics active";
this.MonitoringStateText = "Active";
this.AddTimelineEvent("Monitoring", "Monitoring resumed after restore.", "Info");
this.AddTimelineEvent("Live Metrics", "Live metrics resumed after restore.", "Info");
this.monitoringWasActiveBeforeSuspend = false;
}
catch (Exception ex)
@@ -371,12 +371,12 @@ namespace ThreadPilot.ViewModels
{
try
{
this.SetStatus("Starting monitoring service...");
this.SetStatus("Starting automation monitoring...");
await this.monitorManagerService.StartAsync();
}
catch (Exception ex)
{
this.SetStatus($"Error starting monitoring: {ex.Message}", false);
this.SetStatus($"Error starting automation monitoring: {ex.Message}", false);
}
}
@@ -385,12 +385,12 @@ namespace ThreadPilot.ViewModels
{
try
{
this.SetStatus("Stopping monitoring service...");
this.SetStatus("Stopping automation monitoring...");
await this.monitorManagerService.StopAsync();
}
catch (Exception ex)
{
this.SetStatus($"Error stopping monitoring: {ex.Message}", false);
this.SetStatus($"Error stopping automation monitoring: {ex.Message}", false);
}
}
+152 -181
View File
@@ -156,21 +156,22 @@ namespace ThreadPilot.ViewModels
{
if (value != null && CpuTopology != null)
{
hasPendingAffinityEdits = false;
this.HasPendingAffinityEdits = false;
this.UpdateAffinityDisplayState();
// Immediately fetch and display real-time process information
TaskSafety.FireAndForget(HandleSelectedProcessChangedAsync(value), ex =>
{
Logger.LogWarning(ex, "Failed while handling selected process change for {ProcessName}", value.Name);
this.Logger.LogWarning(ex, "Failed while handling selected process change for {ProcessName}", value.Name);
});
}
else if (value == null)
{
// Clear selection
ClearProcessSelection();
this.ClearProcessSelection();
}
// Update system tray context menu
systemTrayService.UpdateContextMenu(value?.Name, value != null);
this.systemTrayService.UpdateContextMenu(value?.Name, value != null);
}
private async Task HandleSelectedProcessChangedAsync(ProcessModel value)
@@ -197,6 +198,7 @@ namespace ThreadPilot.ViewModels
System.Windows.Application.Current.Dispatcher.Invoke(() =>
{
this.UpdateCoreSelections(value.ProcessorAffinity);
this.UpdateAffinityDisplayState();
value.ForceNotifyProcessorAffinityChanged();
// Update priority display - trigger property change to refresh ComboBox
@@ -254,7 +256,7 @@ namespace ThreadPilot.ViewModels
await this.QuickApplyAffinityAndPowerPlanCommand.ExecuteAsync(null);
this.systemTrayService.ShowBalloonTip(
"ThreadPilot",
$"Settings applied to {this.SelectedProcess?.Name ?? "selected process"}", 2000);
$"Pending settings applied to {this.SelectedProcess?.Name ?? "selected process"}", 2000);
});
}
catch (Exception ex)
@@ -264,7 +266,7 @@ namespace ThreadPilot.ViewModels
{
this.systemTrayService.ShowBalloonTip(
"ThreadPilot Error",
$"Failed to apply settings: {ex.Message}", 3000);
$"Failed to apply pending settings: {ex.Message}", 3000);
});
}
}
@@ -324,61 +326,6 @@ namespace ThreadPilot.ViewModels
this.Logger.LogDebug("Core property changed but cores are read-only - no action taken");
}
private async Task AutoApplyAffinityAsync()
{
if (this.SelectedProcess == null || !this.hasPendingAffinityEdits)
{
return;
}
try
{
var affinityMask = this.CalculateAffinityMask();
if (affinityMask == 0)
{
this.Logger.LogDebug("Affinity mask is zero, skipping auto-apply");
return;
}
this.Logger.LogInformation(
"Auto-applying affinity 0x{AffinityMask:X} to process {ProcessName} (PID: {ProcessId})",
affinityMask, this.SelectedProcess.Name, this.SelectedProcess.ProcessId);
// Apply the affinity change
await this.processService.SetProcessorAffinity(this.SelectedProcess, affinityMask);
// Immediately refresh the process to get the actual system state
await this.processService.RefreshProcessInfo(this.SelectedProcess);
// Update UI to reflect the actual system affinity
this.UpdateCoreSelections(this.SelectedProcess.ProcessorAffinity, true);
// Notify UI of all changes
this.OnPropertyChanged(nameof(this.SelectedProcess));
// Clear pending edits flag
this.hasPendingAffinityEdits = false;
this.Logger.LogInformation("Auto-applied affinity successfully to {ProcessName}", this.SelectedProcess.Name);
}
catch (Exception ex)
{
this.Logger.LogWarning(ex, "Failed to auto-apply affinity to {ProcessName}", this.SelectedProcess.Name);
// Try to refresh process info even if setting failed, to show current state
try
{
await this.processService.RefreshProcessInfo(this.SelectedProcess);
this.UpdateCoreSelections(this.SelectedProcess.ProcessorAffinity, true);
this.OnPropertyChanged(nameof(this.SelectedProcess));
}
catch
{
// Process may have terminated
}
}
}
private void UpdateHyperThreadingStatus()
{
if (this.CpuTopology == null)
@@ -432,7 +379,7 @@ namespace ThreadPilot.ViewModels
return;
}
if (this.hasPendingAffinityEdits && !forceSync)
if (this.HasPendingAffinityEdits && !forceSync)
{
this.Logger.LogDebug("Skipping affinity sync because user edits are pending");
return;
@@ -492,8 +439,10 @@ namespace ThreadPilot.ViewModels
if (forceSync)
{
this.hasPendingAffinityEdits = false;
this.HasPendingAffinityEdits = false;
}
this.UpdateAffinityDisplayState();
}
private long CalculateAffinityMask()
@@ -511,6 +460,34 @@ namespace ThreadPilot.ViewModels
return selectedCores.Aggregate(0L, (mask, core) => mask | core.AffinityMask);
}
private void UpdateAffinityDisplayState()
{
var currentMask = this.SelectedProcess?.ProcessorAffinity;
this.CurrentAffinityText = currentMask.HasValue
? $"Current OS affinity: 0x{currentMask.Value:X}"
: "Current OS affinity: no process selected";
if (this.SelectedProcess == null)
{
this.PendingAffinityText = "Pending core mask: none";
this.AffinityEditStateText = "Select a process to view its current Windows affinity.";
return;
}
if (!this.HasPendingAffinityEdits)
{
this.PendingAffinityText = "Pending core mask: none";
this.AffinityEditStateText = "Current OS affinity is displayed. Select a core mask to stage a change.";
return;
}
var pendingMask = this.CalculateAffinityMask();
this.PendingAffinityText = pendingMask > 0
? $"Pending core mask: 0x{pendingMask:X}"
: "Pending core mask: no cores selected";
this.AffinityEditStateText = "Core mask staged. Use Apply Affinity to change Windows affinity.";
}
[RelayCommand]
public async Task LoadMoreProcesses()
{
@@ -669,67 +646,32 @@ namespace ThreadPilot.ViewModels
try
{
// Store the currently selected process ID to preserve selection
var selectedProcessId = this.SelectedProcess?.ProcessId;
var currentProcesses = this.ShowActiveApplicationsOnly
? await this.processService.GetActiveApplicationsAsync()
: await this.processService.GetProcessesAsync();
// Update UI on the UI thread
await System.Windows.Application.Current.Dispatcher.InvokeAsync(() =>
{
// Update existing processes or add new ones
foreach (var process in currentProcesses)
{
var existingProcess = this.Processes.FirstOrDefault(p => p.ProcessId == process.ProcessId);
if (existingProcess != null)
{
// Update existing process data by copying properties
existingProcess.MemoryUsage = process.MemoryUsage;
existingProcess.Priority = process.Priority;
existingProcess.ProcessorAffinity = process.ProcessorAffinity;
existingProcess.MainWindowHandle = process.MainWindowHandle;
existingProcess.MainWindowTitle = process.MainWindowTitle;
existingProcess.HasVisibleWindow = process.HasVisibleWindow;
existingProcess.CpuUsage = process.CpuUsage;
}
else
{
this.Processes.Add(process);
}
}
// Remove terminated processes
var terminatedProcesses = this.Processes
.Where(p => !currentProcesses.Any(cp => cp.ProcessId == p.ProcessId))
.ToList();
// Check if selected process was terminated
bool selectedProcessTerminated = false;
foreach (var terminated in terminatedProcesses)
{
if (terminated.ProcessId == selectedProcessId)
{
selectedProcessTerminated = true;
}
this.Processes.Remove(terminated);
}
var deltaResult = ProcessListDeltaUpdater.ApplyDelta(
this.Processes,
currentProcesses,
selectedProcessId);
this.FilterProcesses();
// Restore selection if the process still exists
if (selectedProcessId.HasValue && !selectedProcessTerminated)
if (deltaResult.SelectedProcess != null)
{
var processToSelect = this.FilteredProcesses.FirstOrDefault(p => p.ProcessId == selectedProcessId.Value);
var processToSelect = this.FilteredProcesses.FirstOrDefault(
p => p.ProcessId == deltaResult.SelectedProcess.ProcessId);
if (processToSelect != null)
{
this.SelectedProcess = processToSelect;
}
}
else if (selectedProcessTerminated)
else if (deltaResult.SelectedProcessTerminated)
{
// Clear selection and reset UI if selected process was terminated
this.SelectedProcess = null;
this.ClearProcessSelection();
}
@@ -747,7 +689,8 @@ namespace ThreadPilot.ViewModels
[RelayCommand]
private async Task SetAffinity()
{
if (this.SelectedProcess == null)
var selectedProcess = this.SelectedProcess;
if (selectedProcess == null)
{
return;
}
@@ -755,65 +698,57 @@ namespace ThreadPilot.ViewModels
try
{
var affinityMask = this.CalculateAffinityMask();
if (affinityMask == 0)
{
await System.Windows.Application.Current.Dispatcher.InvokeAsync(() =>
{
this.SetStatus("Please select at least one CPU core", false);
});
return;
}
await System.Windows.Application.Current.Dispatcher.InvokeAsync(() =>
{
this.SetStatus($"Setting affinity for {this.SelectedProcess.Name}...");
this.SetStatus($"Setting affinity for {selectedProcess.Name}...");
});
// Apply the affinity change
await this.processService.SetProcessorAffinity(this.SelectedProcess, affinityMask);
var result = await this.affinityApplyService.ApplyAsync(selectedProcess, affinityMask);
// Immediately refresh the process to get the actual system state
await this.processService.RefreshProcessInfo(this.SelectedProcess);
// Update UI to reflect the actual system affinity (not our calculated one)
// This ensures we show what the OS actually set, which may differ from our request
await System.Windows.Application.Current.Dispatcher.InvokeAsync(() =>
{
this.UpdateCoreSelections(this.SelectedProcess.ProcessorAffinity, true);
// Notify UI of all changes
this.UpdateCoreSelections(selectedProcess.ProcessorAffinity, true);
selectedProcess.ForceNotifyProcessorAffinityChanged();
this.OnPropertyChanged(nameof(this.SelectedProcess));
// Verify the affinity was set correctly
if (this.SelectedProcess.ProcessorAffinity == affinityMask)
if (result.Success)
{
this.SetStatus($"Affinity applied successfully to {this.SelectedProcess.Name} (0x{affinityMask:X}).", false);
_ = this.notificationService.ShowNotificationAsync("Affinity applied", $"{this.SelectedProcess.Name}: 0x{affinityMask:X}", NotificationType.Success);
this.HasPendingAffinityEdits = false;
this.UpdateAffinityDisplayState();
this.SetStatus($"Affinity applied successfully to {selectedProcess.Name} (0x{result.VerifiedMask:X}).", false);
_ = this.notificationService.ShowNotificationAsync("Affinity applied", $"{selectedProcess.Name}: 0x{result.VerifiedMask:X}", NotificationType.Success);
}
else if (result.FailureReason == AffinityApplyFailureReason.VerificationMismatch)
{
this.HasPendingAffinityEdits = false;
this.UpdateAffinityDisplayState();
this.SetStatus(result.Message, false);
_ = this.notificationService.ShowNotificationAsync("Affinity adjusted", result.Message, NotificationType.Warning);
}
else if (result.FailureReason == AffinityApplyFailureReason.ProcessTerminated)
{
this.SelectedProcess = null;
this.ClearProcessSelection();
this.SetStatus(result.Message, false);
_ = this.notificationService.ShowNotificationAsync("Affinity failed", result.Message, NotificationType.Warning);
}
else if (result.FailureReason == AffinityApplyFailureReason.AccessDenied)
{
this.SetStatus(result.Message, false);
_ = this.notificationService.ShowNotificationAsync("Affinity blocked", result.Message, NotificationType.Warning);
}
else
{
this.SetStatus($"Affinity adjusted by system for {this.SelectedProcess.Name} to 0x{this.SelectedProcess.ProcessorAffinity:X}.", false);
_ = this.notificationService.ShowNotificationAsync("Affinity adjusted", $"{this.SelectedProcess.Name}: 0x{this.SelectedProcess.ProcessorAffinity:X}", NotificationType.Warning);
this.SetStatus(result.Message, false);
_ = this.notificationService.ShowNotificationAsync("Affinity error", result.Message, NotificationType.Error);
}
});
}
catch (Exception ex)
{
var friendly = ex.Message;
if (friendly.Contains("access denied", StringComparison.OrdinalIgnoreCase) ||
friendly.Contains("anti-cheat", StringComparison.OrdinalIgnoreCase))
{
friendly = "Affinity change blocked (anti-cheat or insufficient privileges).";
_ = this.notificationService.ShowNotificationAsync("Affinity blocked", friendly, NotificationType.Warning);
}
else if (friendly.Contains("invalid affinity", StringComparison.OrdinalIgnoreCase))
{
_ = this.notificationService.ShowNotificationAsync("Affinity invalid", friendly, NotificationType.Error);
}
else
{
_ = this.notificationService.ShowNotificationAsync("Affinity error", friendly, NotificationType.Error);
}
_ = this.notificationService.ShowNotificationAsync("Affinity error", friendly, NotificationType.Error);
await System.Windows.Application.Current.Dispatcher.InvokeAsync(() =>
{
@@ -823,11 +758,18 @@ namespace ThreadPilot.ViewModels
// Try to refresh process info even if setting failed, to show current state
try
{
await this.processService.RefreshProcessInfo(this.SelectedProcess);
if (this.SelectedProcess != null)
{
await this.processService.RefreshProcessInfo(this.SelectedProcess);
}
await System.Windows.Application.Current.Dispatcher.InvokeAsync(() =>
{
this.UpdateCoreSelections(this.SelectedProcess.ProcessorAffinity, true);
this.OnPropertyChanged(nameof(this.SelectedProcess));
if (this.SelectedProcess != null)
{
this.UpdateCoreSelections(this.SelectedProcess.ProcessorAffinity, true);
this.OnPropertyChanged(nameof(this.SelectedProcess));
}
});
}
catch
@@ -879,11 +821,9 @@ namespace ThreadPilot.ViewModels
this.suppressCoreSelectionEvents = false;
}
// Trigger auto-apply with the preset mask
this.hasPendingAffinityEdits = true;
// Apply immediately for presets (no debounce needed)
_ = this.AutoApplyAffinityAsync();
// Keep the preset as a pending selection; affinity changes require an explicit apply command.
this.HasPendingAffinityEdits = true;
this.UpdateAffinityDisplayState();
});
}
@@ -941,7 +881,8 @@ namespace ThreadPilot.ViewModels
private async Task ApplyCoreMaskToProcessAsync(CoreMask mask)
{
if (this.SelectedProcess == null || mask == null)
var selectedProcess = this.SelectedProcess;
if (selectedProcess == null || mask == null)
{
return;
}
@@ -951,7 +892,7 @@ namespace ThreadPilot.ViewModels
{
this.Logger.LogInformation(
"Applying mask '{MaskName}' to process {ProcessName} (PID: {ProcessId})",
mask.Name, this.SelectedProcess.Name, this.SelectedProcess.ProcessId);
mask.Name, selectedProcess.Name, selectedProcess.ProcessId);
// Convert mask to affinity
long affinity = mask.ToProcessorAffinity();
@@ -967,34 +908,35 @@ namespace ThreadPilot.ViewModels
// Game Mode can interfere with CPU Sets, particularly on AMD systems
await this.gameModeService.DisableGameModeForAffinityAsync();
// Apply affinity using ProcessService (which uses CPU Sets with fallback)
await this.processService.SetProcessorAffinity(this.SelectedProcess, affinity);
var result = await this.affinityApplyService.ApplyAsync(selectedProcess, affinity);
// Refresh process info to get actual system state
await this.processService.RefreshProcessInfo(this.SelectedProcess);
// CRITICAL: Force UI updates on UI thread
// RefreshProcessInfo runs on background thread, DataGrid won't receive PropertyChanged from non-UI threads
System.Windows.Application.Current.Dispatcher.Invoke(() =>
{
// Force PropertyChanged notification for ProcessorAffinity property
// This ensures the DataGrid Affinity column binding updates immediately
this.SelectedProcess.ForceNotifyProcessorAffinityChanged();
// Update Advanced CPU Affinity checkboxes to reflect the mask
this.UpdateCoreSelectionsFromMask(mask);
// Force complete refresh of SelectedProcess bindings in DataGrid
selectedProcess.ForceNotifyProcessorAffinityChanged();
this.UpdateCoreSelections(selectedProcess.ProcessorAffinity, true);
this.OnPropertyChanged(nameof(this.SelectedProcess));
});
this.SetStatus($"Applied mask '{mask.Name}' to {this.SelectedProcess.Name}");
this.Logger.LogInformation("Successfully applied mask '{MaskName}' to {ProcessName}", mask.Name, this.SelectedProcess.Name);
if (!result.Success)
{
this.SetStatus(result.Message);
this.Logger.LogWarning(
"Failed to apply mask '{MaskName}' to process {ProcessName}: {Message}",
mask.Name,
selectedProcess.Name,
result.Message);
return;
}
this.HasPendingAffinityEdits = false;
this.UpdateAffinityDisplayState();
this.SetStatus($"Applied mask '{mask.Name}' to {selectedProcess.Name}");
this.Logger.LogInformation("Successfully applied mask '{MaskName}' to {ProcessName}", mask.Name, selectedProcess.Name);
}
catch (Exception ex)
{
this.Logger.LogError(ex, "Failed to apply mask '{MaskName}' to process {ProcessName}",
mask.Name, this.SelectedProcess.Name);
mask.Name, selectedProcess.Name);
this.SetStatus($"Error applying mask: {ex.Message}");
}
finally
@@ -1020,6 +962,8 @@ namespace ThreadPilot.ViewModels
}
this.OnPropertyChanged(nameof(this.CpuCores));
this.HasPendingAffinityEdits = this.SelectedProcess != null;
this.UpdateAffinityDisplayState();
}
finally
{
@@ -1031,7 +975,8 @@ namespace ThreadPilot.ViewModels
[RelayCommand]
private async Task QuickApplyAffinityAndPowerPlan()
{
if (this.SelectedProcess == null)
var selectedProcess = this.SelectedProcess;
if (selectedProcess == null)
{
return;
}
@@ -1040,14 +985,28 @@ namespace ThreadPilot.ViewModels
{
await System.Windows.Application.Current.Dispatcher.InvokeAsync(() =>
{
this.SetStatus($"Applying settings to {this.SelectedProcess.Name}...");
this.SetStatus($"Applying pending settings to {selectedProcess.Name}...");
});
// Apply CPU affinity
var affinityMask = this.CalculateAffinityMask();
if (affinityMask > 0)
{
await this.processService.SetProcessorAffinity(this.SelectedProcess, affinityMask);
var result = await this.affinityApplyService.ApplyAsync(selectedProcess, affinityMask);
if (!result.Success)
{
await System.Windows.Application.Current.Dispatcher.InvokeAsync(() =>
{
this.UpdateCoreSelections(selectedProcess.ProcessorAffinity, true);
selectedProcess.ForceNotifyProcessorAffinityChanged();
this.OnPropertyChanged(nameof(this.SelectedProcess));
this.SetStatus(result.Message, false);
});
return;
}
this.HasPendingAffinityEdits = false;
this.UpdateAffinityDisplayState();
}
// Apply power plan if selected
@@ -1056,24 +1015,25 @@ namespace ThreadPilot.ViewModels
await this.powerPlanService.SetActivePowerPlan(this.SelectedPowerPlan);
}
await this.processService.RefreshProcessInfo(this.SelectedProcess);
await this.processService.RefreshProcessInfo(selectedProcess);
await System.Windows.Application.Current.Dispatcher.InvokeAsync(() =>
{
this.UpdateCoreSelections(this.SelectedProcess.ProcessorAffinity, true);
this.UpdateCoreSelections(selectedProcess.ProcessorAffinity, true);
selectedProcess.ForceNotifyProcessorAffinityChanged();
this.OnPropertyChanged(nameof(this.SelectedProcess));
});
await System.Windows.Application.Current.Dispatcher.InvokeAsync(() =>
{
this.SetStatus($"Quick apply completed for {this.SelectedProcess.Name}.", false);
this.SetStatus($"Pending settings applied to {selectedProcess.Name}.", false);
});
}
catch (Exception ex)
{
await System.Windows.Application.Current.Dispatcher.InvokeAsync(() =>
{
this.SetStatus($"Error applying settings: {ex.Message}", false);
this.SetStatus($"Error applying pending settings: {ex.Message}", false);
});
}
}
@@ -1329,6 +1289,14 @@ namespace ThreadPilot.ViewModels
this.SetUiRefreshEnabled(true, refreshImmediately: true);
}
public void ApplyRefreshDecision(AppRefreshDecision decision)
{
ArgumentNullException.ThrowIfNull(decision);
this.virtualizedProcessService.Configuration.EnableBackgroundLoading = decision.VirtualizedPreloadEnabled;
this.SetUiRefreshEnabled(decision.ProcessUiRefreshEnabled, decision.ImmediateProcessRefresh);
}
public void SetProcessViewActive(bool isActive)
{
if (this.isProcessViewActive == isActive)
@@ -1515,6 +1483,9 @@ namespace ThreadPilot.ViewModels
core.IsSelected = false;
}
this.HasPendingAffinityEdits = false;
this.UpdateAffinityDisplayState();
// Reset power plan to current system default
_ = Task.Run(async () =>
{
+19 -1
View File
@@ -26,6 +26,7 @@ namespace ThreadPilot.ViewModels
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
using ThreadPilot.Models;
using ThreadPilot.Services;
@@ -43,6 +44,7 @@ namespace ThreadPilot.ViewModels
private readonly ICoreMaskService coreMaskService;
private readonly IProcessPowerPlanAssociationService associationService;
private readonly IGameModeService gameModeService;
private readonly IAffinityApplyService affinityApplyService;
private System.Timers.Timer? refreshTimer;
private bool isUiRefreshPaused;
private bool isProcessViewActive = true;
@@ -51,7 +53,6 @@ namespace ThreadPilot.ViewModels
private bool isApplyingFilter;
private bool filterRefreshPending;
private bool suppressCoreSelectionEvents;
private bool hasPendingAffinityEdits;
[ObservableProperty]
private ObservableCollection<ProcessModel> processes = new();
@@ -85,6 +86,18 @@ namespace ThreadPilot.ViewModels
[ObservableProperty]
private CoreMask? selectedCoreMask;
[ObservableProperty]
private bool hasPendingAffinityEdits;
[ObservableProperty]
private string currentAffinityText = "Current OS affinity: no process selected";
[ObservableProperty]
private string pendingAffinityText = "Pending core mask: none";
[ObservableProperty]
private string affinityEditStateText = "Select a process to view its current Windows affinity.";
[ObservableProperty]
private bool isTopologyDetectionSuccessful = false;
@@ -163,6 +176,7 @@ namespace ThreadPilot.ViewModels
ICoreMaskService coreMaskService,
IProcessPowerPlanAssociationService associationService,
IGameModeService gameModeService,
IAffinityApplyService? affinityApplyService = null,
IEnhancedLoggingService? enhancedLoggingService = null)
: base(logger, enhancedLoggingService)
{
@@ -176,6 +190,10 @@ namespace ThreadPilot.ViewModels
this.coreMaskService = coreMaskService ?? throw new ArgumentNullException(nameof(coreMaskService));
this.associationService = associationService ?? throw new ArgumentNullException(nameof(associationService));
this.gameModeService = gameModeService ?? throw new ArgumentNullException(nameof(gameModeService));
this.affinityApplyService = affinityApplyService ?? new AffinityApplyService(
this.processService,
this.cpuTopologyService,
NullLogger<AffinityApplyService>.Instance);
// Subscribe to topology detection events
this.cpuTopologyService.TopologyDetected += this.OnTopologyDetected;
+54 -25
View File
@@ -140,19 +140,20 @@
</Grid>
</Border>
<!-- Log Entries List -->
<ListView Grid.Row="2" ItemsSource="{Binding LogEntries}"
SelectedItem="{Binding SelectedLogEntry}"
Style="{StaticResource LogListViewStyle}"
ItemContainerStyle="{StaticResource LogEntryStyle}"
ScrollViewer.HorizontalScrollBarVisibility="Auto"
ScrollViewer.VerticalScrollBarVisibility="Auto"
VirtualizingPanel.IsVirtualizing="True"
VirtualizingPanel.VirtualizationMode="Recycling"
VirtualizingPanel.ScrollUnit="Item"
ScrollViewer.CanContentScroll="True">
<ListView.View>
<GridView ColumnHeaderContainerStyle="{StaticResource LogGridViewHeaderStyle}">
<Grid Grid.Row="2">
<!-- Log Entries List -->
<ListView ItemsSource="{Binding LogEntries}"
SelectedItem="{Binding SelectedLogEntry}"
Style="{StaticResource LogListViewStyle}"
ItemContainerStyle="{StaticResource LogEntryStyle}"
ScrollViewer.HorizontalScrollBarVisibility="Auto"
ScrollViewer.VerticalScrollBarVisibility="Auto"
VirtualizingPanel.IsVirtualizing="True"
VirtualizingPanel.VirtualizationMode="Recycling"
VirtualizingPanel.ScrollUnit="Item"
ScrollViewer.CanContentScroll="True">
<ListView.View>
<GridView ColumnHeaderContainerStyle="{StaticResource LogGridViewHeaderStyle}">
<GridViewColumn Header="Time" Width="150">
<GridViewColumn.CellTemplate>
<DataTemplate>
@@ -215,18 +216,46 @@
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
</GridView>
</ListView.View>
<ListView.ContextMenu>
<ContextMenu>
<MenuItem Header="Copy Entry" Command="{Binding CopyLogEntryCommand}"
CommandParameter="{Binding SelectedLogEntry}"/>
<Separator/>
<MenuItem Header="Refresh" Command="{Binding RefreshLogsCommand}"/>
</ContextMenu>
</ListView.ContextMenu>
</ListView>
</GridView>
</ListView.View>
<ListView.ContextMenu>
<ContextMenu>
<MenuItem Header="Copy Entry" Command="{Binding CopyLogEntryCommand}"
CommandParameter="{Binding SelectedLogEntry}"/>
<Separator/>
<MenuItem Header="Refresh" Command="{Binding RefreshLogsCommand}"/>
</ContextMenu>
</ListView.ContextMenu>
</ListView>
<Border Padding="18"
IsHitTestVisible="False"
HorizontalAlignment="Center"
VerticalAlignment="Center">
<Border.Style>
<Style TargetType="Border">
<Setter Property="Visibility" Value="Collapsed"/>
<Style.Triggers>
<DataTrigger Binding="{Binding LogEntries.Count}" Value="0">
<Setter Property="Visibility" Value="Visible"/>
</DataTrigger>
</Style.Triggers>
</Style>
</Border.Style>
<StackPanel>
<TextBlock Text="No log entries to display"
FontWeight="SemiBold"
HorizontalAlignment="Center"
Margin="0,0,0,4"/>
<TextBlock Text="Adjust filters or refresh logs to load recent ThreadPilot activity."
Foreground="{DynamicResource TextSecondaryBrush}"
TextAlignment="Center"
TextWrapping="Wrap"
MaxWidth="360"/>
</StackPanel>
</Border>
</Grid>
<!-- Splitter -->
<GridSplitter Grid.Row="3" Height="5" HorizontalAlignment="Stretch"
+15 -13
View File
@@ -19,9 +19,8 @@
<ColumnDefinition Width="3*" MinWidth="300"/>
</Grid.ColumnDefinitions>
<!-- LISTA MASCHERE SINISTRA -->
<DockPanel Grid.Column="0">
<!-- Header con bottoni -->
<!-- Mask list actions -->
<StackPanel DockPanel.Dock="Top" Orientation="Horizontal" Margin="0,0,0,10">
<Button Content="➕ New" Command="{Binding CreateMaskCommand}"
Padding="10,5" FontSize="13" Margin="0,0,5,0"
@@ -31,7 +30,6 @@
ToolTip="Delete selected mask"/>
</StackPanel>
<!-- ListBox delle maschere -->
<Border BorderBrush="{DynamicResource ControlStrokeColorDefaultBrush}" BorderThickness="1" CornerRadius="8">
<ListBox ItemsSource="{Binding CoreMasks}"
SelectedItem="{Binding SelectedCoreMask, Mode=TwoWay}"
@@ -84,7 +82,6 @@
<!-- DIVIDER -->
<GridSplitter Grid.Column="1" Width="8" HorizontalAlignment="Stretch" Background="Transparent"/>
<!-- EDITOR MASK DESTRA -->
<ScrollViewer Grid.Column="2" VerticalScrollBarVisibility="Auto">
<StackPanel Margin="10,0,0,0">
<StackPanel.Style>
@@ -98,16 +95,20 @@
</Style>
</StackPanel.Style>
<!-- Nome e Descrizione -->
<GroupBox Header="Mask Information" Padding="10" Margin="0,10,0,10">
<GroupBox Header="Mask Information" Padding="10" Margin="0,0,0,10">
<StackPanel>
<TextBlock Text="Mask names, descriptions, CPU selections, and options are saved automatically."
FontSize="11"
Foreground="{DynamicResource TextFillColorSecondaryBrush}"
TextWrapping="Wrap"
Margin="0,0,0,10"/>
<TextBlock Text="Name:" FontWeight="SemiBold" Margin="0,0,0,5"/>
<TextBox Text="{Binding SelectedCoreMask.Name, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
Padding="8,6" FontSize="13" Margin="0,0,0,10"/>
<TextBlock Text="Description:" FontWeight="SemiBold" Margin="0,0,0,5"/>
<TextBox Text="{Binding SelectedCoreMask.Description, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
Padding="8,6" MinHeight="72" TextWrapping="Wrap" AcceptsReturn="True"
Padding="8,6" MinHeight="52" MaxHeight="90" TextWrapping="Wrap" AcceptsReturn="True"
VerticalScrollBarVisibility="Auto"/>
</StackPanel>
</GroupBox>
@@ -115,9 +116,11 @@
<!-- CPU Selection Grid -->
<GroupBox Header="Select CPUs" Padding="10" Margin="0,10,0,10">
<StackPanel>
<!-- CPU checkboxes - direct binding to BoolMask like CPUSetSetter -->
<TextBlock Text="Click checkboxes to toggle CPUs. Changes are saved automatically."
FontSize="11" Foreground="{DynamicResource TextFillColorSecondaryBrush}" Margin="0,0,0,10"/>
<TextBlock Text="Toggle CPUs to update this mask. Changes are saved automatically; All Cores remains the protected default mask."
FontSize="11"
Foreground="{DynamicResource TextFillColorSecondaryBrush}"
TextWrapping="Wrap"
Margin="0,0,0,10"/>
<ScrollViewer VerticalScrollBarVisibility="Auto">
<ItemsControl x:Name="CoreItemsControl" ItemsSource="{Binding CoreBits}">
<ItemsControl.ItemsPanel>
@@ -158,10 +161,9 @@
</StackPanel>
</GroupBox>
<!-- Actions -->
<GroupBox Header="Actions" Padding="10">
<GroupBox Header="Mask Options" Padding="10">
<StackPanel>
<Button Content="📋 Duplicate Mask" Command="{Binding DuplicateMaskCommand}"
<Button Content="Duplicate Mask" Command="{Binding DuplicateMaskCommand}"
HorizontalAlignment="Left" Padding="10,6" Margin="0,0,0,5"/>
<CheckBox Content="Set as Default Mask"
+15 -10
View File
@@ -75,23 +75,27 @@
</StackPanel>
<WrapPanel Grid.Column="1" HorizontalAlignment="Right" VerticalAlignment="Center" ItemHeight="32">
<Button Content="Start Monitoring"
<Button Content="Start Live Metrics"
Command="{Binding StartMonitoringCommand}"
IsEnabled="{Binding IsMonitoring, Converter={StaticResource InverseBooleanConverter}}"
MinWidth="118"
Margin="0,0,8,0"/>
<Button Content="Stop Monitoring"
MinWidth="128"
Margin="0,0,8,0"
ToolTip="Start live metrics collection for this dashboard"/>
<Button Content="Stop Live Metrics"
Command="{Binding StopMonitoringCommand}"
IsEnabled="{Binding IsMonitoring}"
MinWidth="108"
Margin="0,0,8,0"/>
MinWidth="120"
Margin="0,0,8,0"
ToolTip="Pause live metrics collection; background automation is separate"/>
<Button Content="Refresh"
Command="{Binding RefreshMetricsCommand}"
MinWidth="84"
Margin="0,0,8,0"/>
Margin="0,0,8,0"
ToolTip="Refresh the current dashboard snapshot"/>
<Button Content="Clear History"
MinWidth="104"
Command="{Binding ClearHistoricalDataCommand}"/>
Command="{Binding ClearHistoricalDataCommand}"
ToolTip="Clear the displayed metrics and timeline history"/>
</WrapPanel>
</Grid>
</Border>
@@ -124,7 +128,7 @@
<StackPanel>
<TextBlock Text="Active Processes" Style="{StaticResource LabelTextStyle}"/>
<TextBlock Text="{Binding ProcessCountText}" Style="{StaticResource ValueTextStyle}"/>
<TextBlock Text="{Binding MonitoringStateText, StringFormat=Monitoring: {0}}" Style="{StaticResource LabelTextStyle}"/>
<TextBlock Text="{Binding MonitoringStateText, StringFormat=Live metrics: {0}}" Style="{StaticResource LabelTextStyle}"/>
</StackPanel>
</Border>
@@ -167,7 +171,8 @@
<Button Content="Create/Update Rule from Selection"
Command="{Binding CreateRuleFromSelectedProcessCommand}"
IsEnabled="{Binding CanCreateRuleFromSelectedProcess}"
Margin="0,0,8,0"/>
Margin="0,0,8,0"
ToolTip="Create or update an automation rule from the selected hotspot process"/>
<Button Content="Toggle Core Panel"
Command="{Binding ToggleCoreDetailsCommand}"
Margin="0,0,8,0"/>
+52 -37
View File
@@ -13,12 +13,11 @@
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<StackPanel Grid.Row="0" Margin="0,0,0,16">
<TextBlock Text="Power Plans" FontSize="24" FontWeight="SemiBold" Margin="0,0,0,4"/>
<TextBlock Text="Manage system power plans and import custom profiles" FontSize="14" Opacity="0.7"/>
<TextBlock Text="Manage the active Windows power plan and import custom .pow profiles" FontSize="14" Opacity="0.7"/>
</StackPanel>
<Grid Grid.Row="1">
@@ -29,7 +28,7 @@
<!-- System Power Plans -->
<GroupBox Grid.Column="0"
Header="Available Power Plans"
Header="Windows Power Plans"
Margin="0,0,5,0">
<Grid Margin="8">
<Grid.RowDefinitions>
@@ -37,13 +36,28 @@
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Button Grid.Row="0"
Command="{Binding LoadPowerPlansCommand}"
Content="Refresh Plans"
HorizontalAlignment="Right"
Padding="10,5"
Margin="0,0,0,12"
ToolTip="Refresh the list of available power plans"/>
<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"
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"/>
</Grid>
<ui:ListView Grid.Row="1"
ItemsSource="{Binding PowerPlans}"
@@ -76,10 +90,28 @@
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<TextBlock Grid.Row="0"
Text="Available custom power plans:"
Margin="0,0,0,10"
Foreground="{DynamicResource TextFillColorSecondaryBrush}"/>
<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"
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"/>
</Grid>
<ui:ListView Grid.Row="1"
ItemsSource="{Binding CustomPowerPlans}"
@@ -89,11 +121,14 @@
Foreground="{DynamicResource TextFillColorPrimaryBrush}">
<ui:ListView.ItemTemplate>
<DataTemplate>
<StackPanel Margin="5">
<TextBlock Text="{Binding Name}"/>
<StackPanel Margin="5" ToolTip="{Binding FilePath}">
<TextBlock Text="{Binding Name}"
FontWeight="SemiBold"
TextTrimming="CharacterEllipsis"/>
<TextBlock Text="{Binding FilePath}"
Foreground="{DynamicResource TextFillColorSecondaryBrush}"
FontSize="11"/>
FontSize="11"
TextTrimming="CharacterEllipsis"/>
</StackPanel>
</DataTemplate>
</ui:ListView.ItemTemplate>
@@ -101,25 +136,5 @@
</Grid>
</GroupBox>
</Grid>
<!-- Action Buttons -->
<StackPanel Grid.Row="2"
Orientation="Horizontal"
Margin="0,12,0,0">
<Button Command="{Binding SetActivePlanCommand}"
Content="Set Active"
Padding="20,5"
Margin="0,0,10,0"
ToolTip="Activate the selected power plan"/>
<Button Command="{Binding ImportCustomPlanCommand}"
Content="Apply Selected Custom"
Padding="20,5"
Margin="0,0,10,0"
ToolTip="Import the selected custom power plan into the system"/>
<Button Command="{Binding AddCustomPlanFileCommand}"
Content="Add .pow File"
Padding="20,5"
ToolTip="Add a new custom power plan file to the custom library"/>
</StackPanel>
</Grid>
</UserControl>
+67 -20
View File
@@ -20,7 +20,7 @@
</Grid.RowDefinitions>
<!-- Standardized Header -->
<GroupBox Grid.Row="0" Header="📐 Rules &amp; Automation" Margin="0,0,0,10">
<GroupBox Grid.Row="0" Header="Rules &amp; Automation" Margin="0,0,0,10">
<Grid Margin="5">
<TextBlock Text="Define per-process rules. Power plans are global; masks and priorities apply to matching processes."
FontSize="12" Foreground="{DynamicResource TextSecondaryBrush}" VerticalAlignment="Center"/>
@@ -68,7 +68,7 @@
</TabControl.Resources>
<!-- Rules Tab -->
<TabItem Header="📐 Rules">
<TabItem Header="Rules">
<Grid Margin="10">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="2*"/>
@@ -77,7 +77,7 @@
</Grid.ColumnDefinitions>
<!-- Rules List -->
<GroupBox Grid.Column="0" Header="📋 Current Rules">
<GroupBox Grid.Column="0" Header="Current Rules">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
@@ -120,6 +120,34 @@
</DataGrid.Columns>
</DataGrid>
<Border Grid.Row="0"
Padding="18"
IsHitTestVisible="False"
HorizontalAlignment="Center"
VerticalAlignment="Center">
<Border.Style>
<Style TargetType="Border">
<Setter Property="Visibility" Value="Collapsed"/>
<Style.Triggers>
<DataTrigger Binding="{Binding Associations.Count}" Value="0">
<Setter Property="Visibility" Value="Visible"/>
</DataTrigger>
</Style.Triggers>
</Style>
</Border.Style>
<StackPanel>
<TextBlock Text="No automation rules yet"
FontWeight="SemiBold"
HorizontalAlignment="Center"
Margin="0,0,0,4"/>
<TextBlock Text="Create a rule from an executable or running process to automate power plan, CPU mask, and priority behavior."
Foreground="{DynamicResource TextSecondaryBrush}"
TextWrapping="Wrap"
TextAlignment="Center"
MaxWidth="360"/>
</StackPanel>
</Border>
<StackPanel Grid.Row="1" Orientation="Horizontal"
HorizontalAlignment="Right" Margin="0,10,0,0">
<Button Content="Update"
@@ -139,10 +167,15 @@
<ScrollViewer VerticalScrollBarVisibility="Auto">
<StackPanel>
<!-- Executable Selection Section -->
<TextBlock Text="Select Executable:" FontWeight="Bold" Margin="0,0,0,5"/>
<TextBlock Text="Executable Match:" FontWeight="Bold" Margin="0,0,0,5"/>
<TextBlock Text="Choose an executable. Match by path is more precise; matching by name applies to any process with that executable name."
Foreground="{DynamicResource TextSecondaryBrush}"
FontSize="10"
TextWrapping="Wrap"
Margin="0,0,0,8"/>
<!-- Browse Button -->
<Button Content="📁 Browse for Executable"
<Button Content="Browse for Executable"
Command="{Binding BrowseExecutableCommand}"
Padding="10,8" Margin="0,0,0,10"
HorizontalAlignment="Left"
@@ -162,7 +195,7 @@
</Border>
<!-- Clear Selection Button -->
<Button Content="✖ Clear Selection"
<Button Content="Clear Selection"
Command="{Binding ClearSelectedExecutableCommand}"
Padding="5,3" Margin="0,0,0,15"
HorizontalAlignment="Left" FontSize="10"
@@ -174,8 +207,8 @@
Margin="0,0,0,10"
ToolTip="Match processes by full path instead of just executable name"/>
<TextBlock Text="Power Plan (Global):" Margin="0,0,0,5" FontWeight="SemiBold"/>
<TextBlock Text="Changing this rule changes the system power plan when matched."
<TextBlock Text="Rule Power Plan (global switch):" Margin="0,0,0,5" FontWeight="SemiBold"/>
<TextBlock Text="When this rule matches, Windows switches the global active power plan."
Foreground="{DynamicResource WarningTextBrush}"
FontSize="10"
TextWrapping="Wrap"
@@ -185,7 +218,12 @@
DisplayMemberPath="Name"
Padding="5" Margin="0,0,0,10"/>
<TextBlock Text="CPU Mask:" Margin="0,0,0,5"/>
<TextBlock Text="Rule CPU Mask:" Margin="0,0,0,5"/>
<TextBlock Text="Applied only to matching processes; it does not change the global Windows power plan."
Foreground="{DynamicResource TextSecondaryBrush}"
FontSize="10"
TextWrapping="Wrap"
Margin="0,0,0,5"/>
<ComboBox ItemsSource="{Binding AvailableCoreMasks}"
SelectedItem="{Binding SelectedCoreMask}"
DisplayMemberPath="Name"
@@ -193,6 +231,11 @@
ToolTip="Optional: Select a CPU mask to apply when this process starts"/>
<TextBlock Text="Process Priority:" Margin="0,0,0,5"/>
<TextBlock Text="Applied to each matching process when the automation rule runs."
Foreground="{DynamicResource TextSecondaryBrush}"
FontSize="10"
TextWrapping="Wrap"
Margin="0,0,0,5"/>
<ComboBox ItemsSource="{Binding AvailablePriorities}"
SelectedItem="{Binding SelectedProcessPriority}"
Padding="5" Margin="0,0,0,10"
@@ -227,7 +270,7 @@
Padding="5" Margin="0,0,0,10"
ToolTip="Select a currently running process to use its executable"/>
<Button Content="📋 Use Selected Process"
<Button Content="Use Selected Process"
Command="{Binding UseSelectedProcessForAssociationCommand}"
Padding="10,5"
ToolTip="Use the executable from the selected running process"/>
@@ -237,13 +280,17 @@
</Grid>
</TabItem>
<!-- Monitoring Configuration Tab -->
<TabItem Header="🛰️ Monitoring Configuration">
<!-- Automation Monitoring Tab -->
<TabItem Header="Automation Monitoring">
<ScrollViewer Margin="10">
<StackPanel>
<!-- Service Control -->
<GroupBox Header="Service Control" Margin="0,0,0,15">
<GroupBox Header="Automation Service" Margin="0,0,0,15">
<StackPanel>
<TextBlock Text="Automation monitoring watches process start/stop events and applies configured power plan, CPU mask, and priority rules."
Foreground="{DynamicResource TextSecondaryBrush}"
TextWrapping="Wrap"
Margin="0,0,0,10"/>
<StackPanel Orientation="Horizontal" Margin="0,0,0,10">
<TextBlock Text="Status: " VerticalAlignment="Center"/>
<TextBlock Text="{Binding ServiceStatus}"
@@ -252,11 +299,11 @@
</StackPanel>
<StackPanel Orientation="Horizontal">
<Button Content="Start Monitoring"
<Button Content="Start Automation Monitoring"
Command="{Binding StartMonitoringCommand}"
IsEnabled="{Binding IsServiceRunning, Converter={StaticResource InverseBoolConverter}}"
Padding="15,8" Margin="0,0,10,0"/>
<Button Content="Stop Monitoring"
<Button Content="Stop Automation Monitoring"
Command="{Binding StopMonitoringCommand}"
IsEnabled="{Binding IsServiceRunning}"
Padding="15,8"/>
@@ -265,7 +312,7 @@
</GroupBox>
<!-- Default Power Plan -->
<GroupBox Header="Default Power Plan (Global fallback)" Margin="0,0,0,15">
<GroupBox Header="Default Power Plan (fallback when no rule matches)" Margin="0,0,0,15">
<StackPanel>
<TextBlock Text="Power plan to use when no associated processes are running:"
Foreground="{DynamicResource TextSecondaryBrush}" Margin="0,0,0,10"/>
@@ -281,14 +328,14 @@
</StackPanel>
</GroupBox>
<!-- Monitoring Settings -->
<GroupBox Header="Monitoring Settings" Margin="0,0,0,15">
<!-- Automation Monitoring Settings -->
<GroupBox Header="Automation Monitoring Settings" Margin="0,0,0,15">
<StackPanel>
<CheckBox Content="Enable Event-Based Monitoring (WMI)"
<CheckBox Content="Enable Event-Based Automation (WMI)"
IsChecked="{Binding IsEventBasedMonitoringEnabled}"
Margin="0,0,0,10"/>
<CheckBox Content="Enable Fallback Polling"
<CheckBox Content="Enable Automation Fallback Polling"
IsChecked="{Binding IsFallbackPollingEnabled}"
Margin="0,0,0,10"/>
+433 -343
View File
@@ -3,8 +3,6 @@
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:ThreadPilot.Views"
xmlns:helpers="clr-namespace:ThreadPilot.Helpers"
xmlns:converters="clr-namespace:ThreadPilot.Converters"
xmlns:Diagnostics="clr-namespace:System.Diagnostics;assembly=System.Diagnostics.Process"
xmlns:sys="clr-namespace:System;assembly=mscorlib"
@@ -26,378 +24,470 @@
<sys:Double x:Key="ProcessFontMediumSmall">12</sys:Double>
<sys:Double x:Key="ProcessFontSmall">11</sys:Double>
</UserControl.Resources>
<Grid Margin="10">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<!-- Standardized Header -->
<StackPanel Grid.Row="0" Margin="0,0,0,16">
<TextBlock Text="Process Management" FontSize="{StaticResource ProcessFontLarge}" FontWeight="SemiBold" Margin="0,0,0,4"/>
<TextBlock Text="Search, filter, and control active process configurations" FontSize="{StaticResource ProcessFontMedium}" Opacity="0.7"/>
</StackPanel>
<!-- Search and Refresh Controls Filter Grid -->
<Border Grid.Row="1" Background="{DynamicResource ControlFillColorDefaultBrush}" Padding="16" BorderBrush="{DynamicResource SurfaceStrokeColorDefaultBrush}" BorderThickness="1" CornerRadius="8" Margin="0,0,0,12">
<Grid>
<Grid Grid.Row="1">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="16"/>
<ColumnDefinition Width="360"/>
</Grid.ColumnDefinitions>
<Grid Grid.Column="0">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="12"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<!-- Search and Basic Controls -->
<Grid Grid.Row="0">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="16"/>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="16"/>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="8"/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<TextBox Grid.Column="0" Text="{Binding SearchText, UpdateSourceTrigger=PropertyChanged}" ToolTip="Search processes by name" HorizontalAlignment="Stretch" AutomationProperties.Name="Process search" />
<CheckBox Grid.Column="2" Content="Active Apps Only" IsChecked="{Binding ShowActiveApplicationsOnly}" VerticalAlignment="Center" ToolTip="Show only applications with visible windows"/>
<Button Grid.Column="4" Command="{Binding LoadProcessesCommand}" Content="Refresh" ToolTip="Refresh the process list" AutomationProperties.Name="Refresh processes"/>
<Button Grid.Column="6" Command="{Binding LoadMoreProcessesCommand}" Content="Load More" Visibility="{Binding HasMoreBatches, Converter={StaticResource BoolToVisibilityConverter}}" ToolTip="Load more processes" AutomationProperties.Name="Load more processes"/>
</Grid>
<!-- Smart Filtering Controls -->
<WrapPanel Grid.Row="2" Orientation="Horizontal">
<CheckBox Content="Hide System Processes"
IsChecked="{Binding HideSystemProcesses}"
Margin="0,0,15,0"
VerticalAlignment="Center"
ToolTip="Hide Windows system processes"/>
<CheckBox Content="Hide Idle Processes"
IsChecked="{Binding HideIdleProcesses}"
Margin="0,0,15,0"
VerticalAlignment="Center"
ToolTip="Hide processes with very low CPU usage"/>
<TextBlock Text="Sort by:" VerticalAlignment="Center" Margin="0,0,5,0"/>
<ComboBox SelectedValue="{Binding SortMode}"
SelectedValuePath="Tag"
Width="120"
VerticalAlignment="Center"
ToolTip="Choose how to sort the process list">
<ComboBoxItem Content="CPU Usage" Tag="CpuUsage"/>
<ComboBoxItem Content="Memory Usage" Tag="MemoryUsage"/>
<ComboBoxItem Content="Process Name" Tag="Name"/>
<ComboBoxItem Content="Process ID" Tag="ProcessId"/>
</ComboBox>
</WrapPanel>
</Grid>
</Border>
<!-- Process List with Loading Overlay -->
<Grid Grid.Row="2">
<DataGrid ItemsSource="{Binding FilteredProcesses}"
SelectedItem="{Binding SelectedProcess}"
AutoGenerateColumns="False"
IsReadOnly="True"
SelectionMode="Single"
GridLinesVisibility="Horizontal"
HeadersVisibility="Column"
CanUserResizeColumns="True"
CanUserSortColumns="True"
Margin="0,0,0,10"
VirtualizingPanel.IsVirtualizing="True"
VirtualizingPanel.VirtualizationMode="Recycling"
VirtualizingPanel.ScrollUnit="Item"
EnableRowVirtualization="True"
EnableColumnVirtualization="True"
ScrollViewer.CanContentScroll="True"
AutomationProperties.Name="Running process list"
AutomationProperties.HelpText="Virtualized process table with sorting and selection">
<DataGrid.Columns>
<DataGridTextColumn Header="Name" Binding="{Binding Name}" Width="150"/>
<DataGridTextColumn Header="ID" Binding="{Binding ProcessId}" Width="60"/>
<DataGridTextColumn Header="Window Title" Binding="{Binding MainWindowTitle}" Width="200"/>
<DataGridCheckBoxColumn Header="Has Window" Binding="{Binding HasVisibleWindow}" Width="80"/>
<DataGridTextColumn Header="CPU Usage" Binding="{Binding CpuUsage, StringFormat={}{0:N1}%}" Width="80"/>
<DataGridTextColumn Header="Memory (MB)"
Binding="{Binding MemoryUsage, Converter={StaticResource BytesToMbConverter}}"
Width="80"/>
<DataGridTextColumn Header="Priority" Binding="{Binding Priority}" Width="*"/>
</DataGrid.Columns>
</DataGrid>
<!-- Progressive Loading Indicator -->
<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"/>
</StackPanel>
</Border>
<!-- Virtualization Status -->
<Border Background="{DynamicResource InfoBackgroundBrush}" BorderBrush="{DynamicResource InfoBorderBrush}" BorderThickness="1"
Visibility="{Binding IsVirtualizationEnabled, Converter={StaticResource BoolToVisibilityConverter}}"
HorizontalAlignment="Right" VerticalAlignment="Bottom" Margin="10" Padding="5">
<StackPanel Orientation="Horizontal">
<TextBlock Text="📊" FontSize="{StaticResource ProcessFontMediumSmall}" Margin="0,0,3,0"/>
<TextBlock FontSize="{StaticResource ProcessFontSmall}" Foreground="{DynamicResource InfoTextBrush}">
<Run Text="Batch:"/>
<Run Text="{Binding CurrentBatchIndex, StringFormat={}{0:N0}}"/>
<Run Text="/"/>
<Run Text="{Binding TotalBatches, StringFormat={}{0:N0}}"/>
<Run Text="("/>
<Run Text="{Binding TotalProcessCount, StringFormat={}{0:N0}}"/>
<Run Text="total)"/>
</TextBlock>
</StackPanel>
</Border>
</Grid>
<!-- Process Controls -->
<Grid Grid.Row="3">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Grid Grid.Row="0">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="2*"/>
</Grid.ColumnDefinitions>
<!-- Priority Controls -->
<GroupBox Grid.Column="0" Header="Process Priority" Margin="0,0,5,0">
<StackPanel Margin="5">
<ComboBox x:Name="PriorityComboBox"
SelectedValue="{Binding SelectedProcess.Priority, Mode=TwoWay}"
SelectedValuePath="Tag"
Margin="0,0,0,5"
IsEnabled="{Binding SelectedProcess, Converter={StaticResource NullToBoolConverter}}">
<ComboBoxItem Content="Realtime" Tag="{x:Static Diagnostics:ProcessPriorityClass.RealTime}"/>
<ComboBoxItem Content="High" Tag="{x:Static Diagnostics:ProcessPriorityClass.High}"/>
<ComboBoxItem Content="Above Normal" Tag="{x:Static Diagnostics:ProcessPriorityClass.AboveNormal}"/>
<ComboBoxItem Content="Normal" Tag="{x:Static Diagnostics:ProcessPriorityClass.Normal}"/>
<ComboBoxItem Content="Below Normal" Tag="{x:Static Diagnostics:ProcessPriorityClass.BelowNormal}"/>
<ComboBoxItem Content="Idle" Tag="{x:Static Diagnostics:ProcessPriorityClass.Idle}"/>
</ComboBox>
<Button Command="{Binding SetPriorityCommand}"
CommandParameter="{Binding ElementName=PriorityComboBox, Path=SelectedValue}"
Content="Set Priority"
Padding="10,5"
Margin="0,0,0,5"
IsEnabled="{Binding SelectedProcess, Converter={StaticResource NullToBoolConverter}}"
ToolTip="Apply the selected priority to the process"/>
<!-- Registry Priority Enforcement -->
<CheckBox Content="Enforce Priority by Registry"
IsChecked="{Binding IsRegistryPriorityEnabled}"
IsEnabled="{Binding SelectedProcess, Converter={StaticResource NullToBoolConverter}}"
Margin="0,0,0,5"
ToolTip="Apply priority through Windows registry. Process must be restarted for changes to take effect. This setting persists across system reboots."/>
<!-- Disable Idle Server -->
<CheckBox Content="Disable Idle Server"
IsChecked="{Binding IsIdleServerDisabled}"
IsEnabled="{Binding SelectedProcess, Converter={StaticResource NullToBoolConverter}}"
ToolTip="Prevents the system from entering idle state while this process is running. Useful for games and performance-critical applications."/>
</StackPanel>
</GroupBox>
<!-- CPU Mask Selection -->
<GroupBox Grid.Column="1" Header="CPU Mask" Margin="5,0,5,0">
<Grid Margin="5" MinHeight="148">
<Border Grid.Row="0"
Background="{DynamicResource ControlFillColorDefaultBrush}"
Padding="16"
BorderBrush="{DynamicResource SurfaceStrokeColorDefaultBrush}"
BorderThickness="1"
CornerRadius="8"
Margin="0,0,0,12">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="12"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<TextBlock Grid.Row="0"
Text="Quick apply a predefined CPU mask:"
FontSize="{StaticResource ProcessFontSmall}"
Margin="0,0,0,5"
Foreground="{DynamicResource TextSecondaryBrush}"/>
<Grid Grid.Row="0">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="16"/>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="16"/>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="8"/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<ComboBox Grid.Row="1"
ItemsSource="{Binding AvailableCoreMasks}"
SelectedItem="{Binding SelectedCoreMask, Mode=TwoWay}"
Margin="0,0,0,8">
<ComboBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Name}" FontWeight="SemiBold" Margin="0,0,8,0"/>
<TextBlock Text="{Binding SelectedCoreCount, StringFormat='({0} CPUs)'}"
FontSize="{StaticResource ProcessFontSmall}"
Foreground="{DynamicResource TextSecondaryBrush}"
VerticalAlignment="Center"/>
</StackPanel>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
<TextBox Grid.Column="0"
Text="{Binding SearchText, UpdateSourceTrigger=PropertyChanged}"
ToolTip="Search processes by name"
HorizontalAlignment="Stretch"
AutomationProperties.Name="Process search"/>
<CheckBox Grid.Column="2"
Content="Active Apps Only"
IsChecked="{Binding ShowActiveApplicationsOnly}"
VerticalAlignment="Center"
ToolTip="Show only applications with visible windows"/>
<Button Grid.Column="4"
Command="{Binding LoadProcessesCommand}"
Content="Refresh"
ToolTip="Refresh the process list"
AutomationProperties.Name="Refresh processes"/>
<Button Grid.Column="6"
Command="{Binding LoadMoreProcessesCommand}"
Content="Load More"
Visibility="{Binding HasMoreBatches, Converter={StaticResource BoolToVisibilityConverter}}"
ToolTip="Load more processes"
AutomationProperties.Name="Load more processes"/>
</Grid>
<Button Grid.Row="2"
Command="{Binding CreateCustomMaskCommand}"
Padding="8,6"
Margin="0,0,0,0"
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="Create Custom Mask"
FontSize="{StaticResource ProcessFontMediumSmall}"
VerticalAlignment="Center"/>
</StackPanel>
</Button>
<WrapPanel Grid.Row="2" Orientation="Horizontal">
<CheckBox Content="Hide System Processes"
IsChecked="{Binding HideSystemProcesses}"
Margin="0,0,15,0"
VerticalAlignment="Center"
ToolTip="Hide Windows system processes"/>
<CheckBox Content="Hide Idle Processes"
IsChecked="{Binding HideIdleProcesses}"
Margin="0,0,15,0"
VerticalAlignment="Center"
ToolTip="Hide processes with very low CPU usage"/>
<TextBlock Text="Sort by:" VerticalAlignment="Center" Margin="0,0,5,0"/>
<ComboBox SelectedValue="{Binding SortMode}"
SelectedValuePath="Tag"
Width="120"
VerticalAlignment="Center"
ToolTip="Choose how to sort the process list">
<ComboBoxItem Content="CPU Usage" Tag="CpuUsage"/>
<ComboBoxItem Content="Memory Usage" Tag="MemoryUsage"/>
<ComboBoxItem Content="Process Name" Tag="Name"/>
<ComboBoxItem Content="Process ID" Tag="ProcessId"/>
</ComboBox>
</WrapPanel>
</Grid>
</GroupBox>
</Border>
<!-- Advanced CPU Affinity Controls -->
<GroupBox Grid.Column="2" Header="Advanced CPU Affinity" Margin="5,0,0,0">
<Grid Margin="5">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Grid Grid.Row="1">
<DataGrid ItemsSource="{Binding FilteredProcesses}"
SelectedItem="{Binding SelectedProcess}"
AutoGenerateColumns="False"
IsReadOnly="True"
SelectionMode="Single"
GridLinesVisibility="Horizontal"
HeadersVisibility="Column"
CanUserResizeColumns="True"
CanUserSortColumns="True"
VirtualizingPanel.IsVirtualizing="True"
VirtualizingPanel.VirtualizationMode="Recycling"
VirtualizingPanel.ScrollUnit="Item"
EnableRowVirtualization="True"
EnableColumnVirtualization="True"
ScrollViewer.CanContentScroll="True"
AutomationProperties.Name="Running process list"
AutomationProperties.HelpText="Virtualized process table with sorting and selection">
<DataGrid.Columns>
<DataGridTextColumn Header="Name" Binding="{Binding Name}" Width="160"/>
<DataGridTextColumn Header="ID" Binding="{Binding ProcessId}" Width="70"/>
<DataGridTextColumn Header="Window Title" Binding="{Binding MainWindowTitle}" Width="220"/>
<DataGridCheckBoxColumn Header="Has Window" Binding="{Binding HasVisibleWindow}" Width="90"/>
<DataGridTextColumn Header="CPU Usage" Binding="{Binding CpuUsage, StringFormat={}{0:N1}%}" Width="90"/>
<DataGridTextColumn Header="Memory (MB)"
Binding="{Binding MemoryUsage, Converter={StaticResource BytesToMbConverter}}"
Width="90"/>
<DataGridTextColumn Header="Priority" Binding="{Binding Priority}" Width="*"/>
</DataGrid.Columns>
</DataGrid>
<!-- Topology Status and HyperThreading Status -->
<StackPanel Grid.Row="0" Orientation="Vertical" Margin="0,0,0,5">
<TextBlock Text="{Binding TopologyStatus}"
FontSize="{StaticResource ProcessFontSmall}"
Foreground="{Binding IsTopologyDetectionSuccessful, Converter={StaticResource BoolToColorConverter}}"/>
<TextBlock Text="{Binding HyperThreadingStatusText}"
FontSize="{StaticResource ProcessFontSmall}"
Margin="0,2,0,0"
Foreground="{Binding IsHyperThreadingActive, Converter={StaticResource BoolToColorConverter}}"
ToolTip="Shows whether Hyper-Threading (Intel) or SMT (AMD) is present and active on this system"/>
<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"/>
</StackPanel>
</Border>
<!-- CPU Core Grid -->
<ScrollViewer Grid.Row="1"
MaxHeight="120"
VerticalScrollBarVisibility="Auto"
HorizontalScrollBarVisibility="Disabled"
Margin="0,0,0,5">
<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}"
ToolTip="Read-only - modify CPUs in CPU Mask tab">
</CheckBox>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</ScrollViewer>
</Grid>
</GroupBox>
</Grid>
<!-- Profile Management & Rule Save -->
<GroupBox Grid.Row="1" Header="Profile Management &amp; Rule Save" Margin="0,10,0,0">
<Grid Margin="5">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<!-- Profile Management Row -->
<Grid Grid.Row="0" Margin="0,0,0,10">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<TextBox Grid.Column="0"
Text="{Binding ProfileName, UpdateSourceTrigger=PropertyChanged}"
Margin="0,0,10,0"
ToolTip="Enter a profile name to save current settings"/>
<Button Grid.Column="1"
Command="{Binding SaveProfileCommand}"
Content="Save Profile"
Padding="10,5"
Margin="0,0,5,0"
ToolTip="Save current CPU affinity and priority as a reusable profile"/>
<Button Grid.Column="2"
Command="{Binding LoadProfileCommand}"
Content="Load Profile"
Padding="10,5"
ToolTip="Load a previously saved profile"/>
</Grid>
<!-- Rule Save Row -->
<Grid Grid.Row="1">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<TextBlock Grid.Column="0"
VerticalAlignment="Center"
TextWrapping="Wrap"
Foreground="{DynamicResource TextSecondaryBrush}"
FontSize="{StaticResource ProcessFontMediumSmall}">
<Run Text="💾 Save current settings (CPU mask, priority) as an automatic rule for this process"/>
</TextBlock>
<Button Grid.Column="1"
Command="{Binding SaveCurrentAsAssociationCommand}"
Content="💾 Save as Rule"
Padding="12,6"
FontWeight="SemiBold"
IsEnabled="{Binding SelectedProcess, Converter={StaticResource NullToBoolConverter}}"
ToolTip="Save current process settings as a rule. These settings will be automatically applied when this process starts in the future."/>
</Grid>
<Border Grid.Row="2"
Margin="0,10,0,0"
Padding="10,7"
CornerRadius="6"
<Border Background="{DynamicResource InfoBackgroundBrush}"
BorderBrush="{DynamicResource InfoBorderBrush}"
BorderThickness="1"
Opacity="{Binding StatusOpacity}"
Visibility="{Binding StatusMessage, Converter={x:Static converters:StringToVisibilityConverter.Instance}}">
<Border.Style>
<Style TargetType="Border">
<Setter Property="Background" Value="{DynamicResource SuccessBackgroundBrush}"/>
<Setter Property="BorderBrush" Value="{DynamicResource SuccessBorderBrush}"/>
<Style.Triggers>
<DataTrigger Binding="{Binding HasError}" Value="True">
<Setter Property="Background" Value="{DynamicResource ErrorBackgroundBrush}"/>
<Setter Property="BorderBrush" Value="{DynamicResource ErrorBorderBrush}"/>
</DataTrigger>
</Style.Triggers>
</Style>
</Border.Style>
<TextBlock Text="{Binding StatusMessage}">
<TextBlock.Style>
<Style TargetType="TextBlock">
<Setter Property="Foreground" Value="{DynamicResource SuccessTextBrush}"/>
<Style.Triggers>
<DataTrigger Binding="{Binding HasError}" Value="True">
<Setter Property="Foreground" Value="{DynamicResource ErrorTextBrush}"/>
</DataTrigger>
</Style.Triggers>
</Style>
</TextBlock.Style>
Visibility="{Binding IsVirtualizationEnabled, Converter={StaticResource BoolToVisibilityConverter}}"
HorizontalAlignment="Right"
VerticalAlignment="Bottom"
Margin="10"
Padding="6"
CornerRadius="4">
<TextBlock FontSize="{StaticResource ProcessFontSmall}" Foreground="{DynamicResource InfoTextBrush}">
<Run Text="Batch "/>
<Run Text="{Binding CurrentBatchIndex, StringFormat={}{0:N0}}"/>
<Run Text="/"/>
<Run Text="{Binding TotalBatches, StringFormat={}{0:N0}}"/>
<Run Text=" ("/>
<Run Text="{Binding TotalProcessCount, StringFormat={}{0:N0}}"/>
<Run Text=" total)"/>
</TextBlock>
</Border>
</Grid>
</GroupBox>
</Grid>
<Border Grid.Column="2"
Background="{DynamicResource ControlFillColorDefaultBrush}"
BorderBrush="{DynamicResource SurfaceStrokeColorDefaultBrush}"
BorderThickness="1"
CornerRadius="8">
<ScrollViewer VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Disabled">
<StackPanel Margin="14">
<TextBlock Text="Selected Process"
FontSize="{StaticResource ProcessFontMedium}"
FontWeight="SemiBold"
Margin="0,0,0,8"/>
<Border Padding="10"
CornerRadius="6"
BorderBrush="{DynamicResource SurfaceStrokeColorDefaultBrush}"
BorderThickness="1"
Margin="0,0,0,12">
<StackPanel>
<TextBlock Text="No process selected"
FontWeight="SemiBold"
Foreground="{DynamicResource TextSecondaryBrush}"
TextWrapping="Wrap">
<TextBlock.Style>
<Style TargetType="TextBlock">
<Setter Property="Visibility" Value="Collapsed"/>
<Style.Triggers>
<DataTrigger Binding="{Binding SelectedProcess}" Value="{x:Null}">
<Setter Property="Visibility" Value="Visible"/>
</DataTrigger>
</Style.Triggers>
</Style>
</TextBlock.Style>
</TextBlock>
<TextBlock Text="Select a process from the table to enable affinity, priority, power plan, and rule actions."
FontSize="{StaticResource ProcessFontSmall}"
Foreground="{DynamicResource TextSecondaryBrush}"
TextWrapping="Wrap"
Margin="0,4,0,0">
<TextBlock.Style>
<Style TargetType="TextBlock">
<Setter Property="Visibility" Value="Collapsed"/>
<Style.Triggers>
<DataTrigger Binding="{Binding SelectedProcess}" Value="{x:Null}">
<Setter Property="Visibility" Value="Visible"/>
</DataTrigger>
</Style.Triggers>
</Style>
</TextBlock.Style>
</TextBlock>
<StackPanel>
<StackPanel.Style>
<Style TargetType="StackPanel">
<Setter Property="Visibility" Value="Visible"/>
<Style.Triggers>
<DataTrigger Binding="{Binding SelectedProcess}" Value="{x:Null}">
<Setter Property="Visibility" Value="Collapsed"/>
</DataTrigger>
</Style.Triggers>
</Style>
</StackPanel.Style>
<TextBlock Text="{Binding SelectedProcess.Name}"
FontWeight="SemiBold"
TextTrimming="CharacterEllipsis"/>
<TextBlock FontSize="{StaticResource ProcessFontSmall}" Foreground="{DynamicResource TextSecondaryBrush}">
<Run Text="PID "/>
<Run Text="{Binding SelectedProcess.ProcessId}"/>
<Run Text=" Priority "/>
<Run Text="{Binding SelectedProcess.Priority}"/>
</TextBlock>
<TextBlock Text="{Binding SelectedProcess.MainWindowTitle, TargetNullValue=No visible window title}"
FontSize="{StaticResource ProcessFontSmall}"
Foreground="{DynamicResource TextSecondaryBrush}"
TextWrapping="Wrap"
Margin="0,4,0,0"/>
</StackPanel>
</StackPanel>
</Border>
<GroupBox Header="Affinity" Margin="0,0,0,12">
<StackPanel Margin="8">
<TextBlock Text="{Binding CurrentAffinityText}"
FontSize="{StaticResource ProcessFontSmall}"
Foreground="{DynamicResource TextSecondaryBrush}"
TextWrapping="Wrap"
ToolTip="Affinity currently reported by Windows for the selected process"/>
<TextBlock Text="{Binding PendingAffinityText}"
FontSize="{StaticResource ProcessFontSmall}"
Foreground="{DynamicResource TextSecondaryBrush}"
TextWrapping="Wrap"
Margin="0,3,0,0"
ToolTip="Affinity staged in the UI. It is not applied until Apply Affinity is clicked."/>
<TextBlock Text="{Binding AffinityEditStateText}"
FontSize="{StaticResource ProcessFontSmall}"
Foreground="{DynamicResource WarningTextBrush}"
TextWrapping="Wrap"
Margin="0,3,0,10"/>
<TextBlock Text="Pending core mask" FontSize="{StaticResource ProcessFontSmall}" FontWeight="SemiBold" Margin="0,0,0,4"/>
<ComboBox ItemsSource="{Binding AvailableCoreMasks}"
SelectedItem="{Binding SelectedCoreMask, Mode=TwoWay}"
IsEnabled="{Binding SelectedProcess, Converter={StaticResource NullToBoolConverter}}"
Margin="0,0,0,8"
ToolTip="Select a mask to stage it. This does not change OS affinity until Apply Affinity is clicked.">
<ComboBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Name}" FontWeight="SemiBold" Margin="0,0,8,0"/>
<TextBlock Text="{Binding SelectedCoreCount, StringFormat='({0} CPUs)'}"
FontSize="{StaticResource ProcessFontSmall}"
Foreground="{DynamicResource TextSecondaryBrush}"
VerticalAlignment="Center"/>
</StackPanel>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
<TextBlock Text="{Binding TopologyStatus}"
FontSize="{StaticResource ProcessFontSmall}"
Foreground="{Binding IsTopologyDetectionSuccessful, Converter={StaticResource BoolToColorConverter}}"/>
<TextBlock Text="{Binding HyperThreadingStatusText}"
FontSize="{StaticResource ProcessFontSmall}"
Margin="0,2,0,6"
Foreground="{Binding IsHyperThreadingActive, Converter={StaticResource BoolToColorConverter}}"
ToolTip="Shows whether Hyper-Threading (Intel) or SMT (AMD) is present and active on this system"/>
<ScrollViewer MaxHeight="92"
VerticalScrollBarVisibility="Auto"
HorizontalScrollBarVisibility="Disabled"
Margin="0,0,0,8">
<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}"
ToolTip="Read-only preview of current or pending CPU selection"/>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</ScrollViewer>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="8"/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<Button Grid.Column="0"
Command="{Binding SetAffinityCommand}"
Content="Apply Affinity"
Padding="10,6"
IsEnabled="{Binding SelectedProcess, Converter={StaticResource NullToBoolConverter}}"
ToolTip="Apply the pending core mask to the selected process and verify the Windows affinity state"/>
<Button Grid.Column="2"
Command="{Binding CreateCustomMaskCommand}"
Padding="8,6"
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>
</StackPanel>
</GroupBox>
<GroupBox Header="Priority" Margin="0,0,0,12">
<StackPanel Margin="8">
<ComboBox x:Name="PriorityComboBox"
SelectedValue="{Binding SelectedProcess.Priority, Mode=TwoWay}"
SelectedValuePath="Tag"
Margin="0,0,0,6"
IsEnabled="{Binding SelectedProcess, Converter={StaticResource NullToBoolConverter}}">
<ComboBoxItem Content="Realtime" Tag="{x:Static Diagnostics:ProcessPriorityClass.RealTime}"/>
<ComboBoxItem Content="High" Tag="{x:Static Diagnostics:ProcessPriorityClass.High}"/>
<ComboBoxItem Content="Above Normal" Tag="{x:Static Diagnostics:ProcessPriorityClass.AboveNormal}"/>
<ComboBoxItem Content="Normal" Tag="{x:Static Diagnostics:ProcessPriorityClass.Normal}"/>
<ComboBoxItem Content="Below Normal" Tag="{x:Static Diagnostics:ProcessPriorityClass.BelowNormal}"/>
<ComboBoxItem Content="Idle" Tag="{x:Static Diagnostics:ProcessPriorityClass.Idle}"/>
</ComboBox>
<Button Command="{Binding SetPriorityCommand}"
CommandParameter="{Binding ElementName=PriorityComboBox, Path=SelectedValue}"
Content="Set Priority"
Padding="10,6"
Margin="0,0,0,8"
IsEnabled="{Binding SelectedProcess, Converter={StaticResource NullToBoolConverter}}"
ToolTip="Apply the selected priority to the process"/>
<CheckBox Content="Enforce Priority by Registry"
IsChecked="{Binding IsRegistryPriorityEnabled}"
IsEnabled="{Binding SelectedProcess, Converter={StaticResource NullToBoolConverter}}"
Margin="0,0,0,6"
ToolTip="Apply priority through Windows registry. Process must be restarted for changes to take effect. This setting persists across system reboots."/>
<CheckBox Content="Disable Idle Server"
IsChecked="{Binding IsIdleServerDisabled}"
IsEnabled="{Binding SelectedProcess, Converter={StaticResource NullToBoolConverter}}"
ToolTip="Prevents the system from entering idle state while this process is running. Useful for games and performance-critical applications."/>
</StackPanel>
</GroupBox>
<GroupBox Header="Power Plan / Pending Settings" Margin="0,0,0,12">
<StackPanel Margin="8">
<TextBlock Text="Selected power plan"
FontSize="{StaticResource ProcessFontSmall}"
FontWeight="SemiBold"
Margin="0,0,0,4"/>
<ComboBox ItemsSource="{Binding PowerPlans}"
SelectedItem="{Binding SelectedPowerPlan, Mode=TwoWay}"
DisplayMemberPath="Name"
Margin="0,0,0,8"
ToolTip="Choose the power plan to activate manually or include with quick apply"/>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="8"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Button Grid.Column="0"
Command="{Binding SetPowerPlanCommand}"
Content="Set Power Plan"
Padding="10,6"
ToolTip="Activate the selected Windows power plan"/>
<Button Grid.Column="2"
Command="{Binding QuickApplyAffinityAndPowerPlanCommand}"
Content="Apply Pending Settings"
Padding="10,6"
IsEnabled="{Binding SelectedProcess, Converter={StaticResource NullToBoolConverter}}"
ToolTip="Apply the pending affinity and selected power plan to the selected process"/>
</Grid>
</StackPanel>
</GroupBox>
<GroupBox Header="Profile / Rule" Margin="0,0,0,12">
<StackPanel Margin="8">
<TextBox Text="{Binding ProfileName, UpdateSourceTrigger=PropertyChanged}"
Margin="0,0,0,8"
ToolTip="Enter a profile name to save or load settings"/>
<Grid Margin="0,0,0,8">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="8"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Button Grid.Column="0"
Command="{Binding SaveProfileCommand}"
Content="Save Profile"
Padding="10,6"
ToolTip="Save current CPU affinity and priority as a reusable profile"/>
<Button Grid.Column="2"
Command="{Binding LoadProfileCommand}"
Content="Load Profile"
Padding="10,6"
ToolTip="Load a previously saved profile"/>
</Grid>
<Button Command="{Binding SaveCurrentAsAssociationCommand}"
Content="Save as Rule"
Padding="10,6"
FontWeight="SemiBold"
IsEnabled="{Binding SelectedProcess, Converter={StaticResource NullToBoolConverter}}"
ToolTip="Save current process settings as a rule. These settings will be automatically applied when this process starts in the future."/>
</StackPanel>
</GroupBox>
<Border Padding="10,7"
CornerRadius="6"
BorderThickness="1"
Opacity="{Binding StatusOpacity}"
Visibility="{Binding StatusMessage, Converter={x:Static converters:StringToVisibilityConverter.Instance}}">
<Border.Style>
<Style TargetType="Border">
<Setter Property="Background" Value="{DynamicResource SuccessBackgroundBrush}"/>
<Setter Property="BorderBrush" Value="{DynamicResource SuccessBorderBrush}"/>
<Style.Triggers>
<DataTrigger Binding="{Binding HasError}" Value="True">
<Setter Property="Background" Value="{DynamicResource ErrorBackgroundBrush}"/>
<Setter Property="BorderBrush" Value="{DynamicResource ErrorBorderBrush}"/>
</DataTrigger>
</Style.Triggers>
</Style>
</Border.Style>
<TextBlock Text="{Binding StatusMessage}" TextWrapping="Wrap">
<TextBlock.Style>
<Style TargetType="TextBlock">
<Setter Property="Foreground" Value="{DynamicResource SuccessTextBrush}"/>
<Style.Triggers>
<DataTrigger Binding="{Binding HasError}" Value="True">
<Setter Property="Foreground" Value="{DynamicResource ErrorTextBrush}"/>
</DataTrigger>
</Style.Triggers>
</Style>
</TextBlock.Style>
</TextBlock>
</Border>
</StackPanel>
</ScrollViewer>
</Border>
</Grid>
</Grid>
</UserControl>
+7 -7
View File
@@ -154,12 +154,12 @@
<Separator Margin="0,10"/>
<CheckBox Content="Enable quick apply from tray"
<CheckBox Content="Enable pending settings apply from tray"
IsChecked="{Binding Settings.EnableQuickApplyFromTray}"
IsEnabled="{Binding Settings.ShowTrayIcon}"
Margin="0,5"/>
<CheckBox Content="Enable monitoring controls from tray"
<CheckBox Content="Enable automation monitoring controls from tray"
IsChecked="{Binding Settings.EnableMonitoringControlFromTray}"
IsEnabled="{Binding Settings.ShowTrayIcon}"
Margin="0,0,0,5"/>
@@ -198,22 +198,22 @@
</Border>
</StackPanel>
<!-- Monitoring Section -->
<!-- Process Event Settings Section -->
<StackPanel Width="360" Margin="10">
<TextBlock Text="Monitoring Settings" Style="{StaticResource SectionHeaderStyle}" Margin="0,0,0,8"/>
<TextBlock Text="Process Event Settings" Style="{StaticResource SectionHeaderStyle}" Margin="0,0,0,8"/>
<Border Background="{DynamicResource SurfaceAltBrush}" CornerRadius="5" Padding="15" BorderThickness="1" BorderBrush="{DynamicResource BorderBrush}">
<StackPanel>
<CheckBox Content="Enable WMI monitoring"
<CheckBox Content="Enable WMI process events"
IsChecked="{Binding Settings.EnableWmiMonitoring}"
Margin="0,0,0,5"/>
<TextBlock Text="Use Windows Management Instrumentation for real-time process monitoring"
<TextBlock Text="Use Windows Management Instrumentation for process start/stop events"
Style="{StaticResource DescriptionStyle}"
Margin="20,0,0,15"/>
<CheckBox Content="Enable fallback polling"
IsChecked="{Binding Settings.EnableFallbackPolling}"
Margin="0,0,0,5"/>
<TextBlock Text="Use polling as backup when WMI monitoring fails"
<TextBlock Text="Use polling as backup when WMI process events fail"
Style="{StaticResource DescriptionStyle}"
Margin="20,0,0,15"/>
+29 -35
View File
@@ -156,33 +156,28 @@
<ItemsControl.ItemTemplate>
<DataTemplate>
<GroupBox Margin="5" Padding="10">
<GroupBox Margin="5" Padding="8">
<GroupBox.Header>
<!-- Enhanced Tweak Name Styling -->
<TextBlock Text="{Binding Name}"
FontSize="15"
FontWeight="Bold"
FontSize="14"
FontWeight="SemiBold"
Foreground="{DynamicResource TextPrimaryBrush}"/>
</GroupBox.Header>
<!-- Main Card Content with Two-Column Layout -->
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<StackPanel>
<TextBlock Text="{Binding Description}"
FontSize="11"
Foreground="{DynamicResource TextSecondaryBrush}"
TextWrapping="Wrap"
Margin="0,0,0,8"/>
<!-- Left Column: Content -->
<StackPanel Grid.Column="0" Margin="0,0,15,0">
<!-- Description -->
<TextBlock Text="{Binding Description}"
FontSize="11"
Foreground="{DynamicResource TextSecondaryBrush}"
TextWrapping="Wrap"
Margin="0,0,0,8"/>
<Grid Margin="0,0,0,5">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<!-- Status Indicator -->
<StackPanel Orientation="Horizontal" Margin="0,0,0,5">
<StackPanel Grid.Column="0" Orientation="Horizontal" VerticalAlignment="Center">
<Ellipse Width="8" Height="8"
VerticalAlignment="Center"
Margin="0,0,8,0">
@@ -215,21 +210,12 @@
<Setter Property="Text" Value="Disabled"/>
</DataTrigger>
</Style.Triggers>
</Style>
</TextBlock.Style>
</TextBlock>
</Style>
</TextBlock.Style>
</TextBlock>
</StackPanel>
<!-- Error Message -->
<TextBlock Text="{Binding ErrorMessage}"
FontSize="11"
Foreground="{DynamicResource ErrorTextBrush}"
TextWrapping="Wrap"
Visibility="{Binding ErrorMessage, Converter={StaticResource StringToVisibilityConverter}}"/>
</StackPanel>
<!-- Right Column: Toggle Button -->
<ToggleButton Grid.Column="1"
<ToggleButton Grid.Column="1"
Style="{StaticResource PillToggleButtonStyle}"
IsChecked="{Binding IsEnabled, Mode=OneWay}"
IsEnabled="{Binding IsAvailable}"
@@ -237,8 +223,16 @@
CommandParameter="{Binding}"
VerticalAlignment="Center"
HorizontalAlignment="Right"
Margin="10,0,10,0"/>
</Grid>
Margin="10,0,0,0"
ToolTip="Toggle this Windows tweak"/>
</Grid>
<TextBlock Text="{Binding ErrorMessage}"
FontSize="11"
Foreground="{DynamicResource ErrorTextBrush}"
TextWrapping="Wrap"
Visibility="{Binding ErrorMessage, Converter={StaticResource StringToVisibilityConverter}}"/>
</StackPanel>
</GroupBox>
</DataTemplate>
</ItemsControl.ItemTemplate>