fix: buttons that do what they say, and rules you can actually see

Three findings from a pass over the main dashboard.

"+ Custom" in the affinity picker did nothing at all. CreateCustomMask was
searching the visual tree for a TabControl and setting SelectedIndex; the
window has been a NavigationView for several versions, so the search returned
null - no navigation, no error, no feedback. It now raises OpenMasksRequested,
mirroring the OpenRulesRequested event the window already handles. The dead
FindVisualChild helper goes with it.

Clearing CPU Sets left the core chips advertising the assignment that had just
been removed until the process happened to be reselected - and a rule saved in
between would have captured those cores.

Rules saved from the Process tab context menu were invisible: nothing listed
them, and the Rules tab shows power plan associations, which are a different
thing entirely. They now have their own tab there, saying in plain words what
each rule applies and how it differs from the associations, with a delete that
shares one implementation with the context menu path so the two can never
disagree about which rule belongs to a process. The list is re-read on every
visit to the tab, which is enough while the two views cannot be on screen at
the same time.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
PrimeBuild-pc
2026-08-26 22:48:36 +02:00
committed by Prime Build
parent b3cd418864
commit df23cd1be9
15 changed files with 384 additions and 40 deletions
+8
View File
@@ -238,6 +238,14 @@
<sys:String x:Key="ProcessPowerPlanAssociationView_DescriptionLabel">Beschreibung:</sys:String>
<sys:String x:Key="ProcessPowerPlanAssociationView_AutomationService">Automatisierungsdienst</sys:String>
<sys:String x:Key="ProcessPowerPlanAssociationView_RulesHeader">Regeln</sys:String>
<sys:String x:Key="ProcessPowerPlanAssociationView_SavedRulesHeader">Gespeicherte Prozessregeln</sys:String>
<sys:String x:Key="ProcessPowerPlanAssociationView_SavedRulesDescription">Regeln, die auf der Registerkarte Prozesse gespeichert wurden. ThreadPilot wendet sie bei jedem Start des Prozesses erneut an, solange die Automatisierungsüberwachung aktiv ist. Sie sind getrennt von den Energieplanregeln oben, die den globalen Windows-Energieplan umschalten.</sys:String>
<sys:String x:Key="ProcessPowerPlanAssociationView_SavedRuleProcess">Prozess</sys:String>
<sys:String x:Key="ProcessPowerPlanAssociationView_SavedRuleApplies">Wendet an</sys:String>
<sys:String x:Key="ProcessPowerPlanAssociationView_SavedRuleMode">Modus</sys:String>
<sys:String x:Key="ProcessPowerPlanAssociationView_SavedRuleUpdated">Aktualisiert</sys:String>
<sys:String x:Key="ProcessPowerPlanAssociationView_SavedRuleDelete">Löschen</sys:String>
<sys:String x:Key="ProcessPowerPlanAssociationView_NoSavedRules">Noch keine gespeicherten Prozessregeln. Klicken Sie auf der Registerkarte Prozesse mit der rechten Maustaste auf einen Prozess und wählen Sie Regeln.</sys:String>
<sys:String x:Key="ProcessPowerPlanAssociationView_Executable">Ausführbar</sys:String>
<sys:String x:Key="ProcessPowerPlanAssociationView_PowerPlan">Energieplan</sys:String>
<sys:String x:Key="ProcessPowerPlanAssociationView_CpuMask">CPU Maske</sys:String>
+8
View File
@@ -238,6 +238,14 @@
<sys:String x:Key="ProcessPowerPlanAssociationView_DescriptionLabel">Description:</sys:String>
<sys:String x:Key="ProcessPowerPlanAssociationView_AutomationService">Automation Service</sys:String>
<sys:String x:Key="ProcessPowerPlanAssociationView_RulesHeader">Rules</sys:String>
<sys:String x:Key="ProcessPowerPlanAssociationView_SavedRulesHeader">Saved process rules</sys:String>
<sys:String x:Key="ProcessPowerPlanAssociationView_SavedRulesDescription">Rules saved from the Process tab. ThreadPilot re-applies them to that process every time it starts, while automation monitoring is on. These are separate from the power plan rules above, which switch the global Windows power plan.</sys:String>
<sys:String x:Key="ProcessPowerPlanAssociationView_SavedRuleProcess">Process</sys:String>
<sys:String x:Key="ProcessPowerPlanAssociationView_SavedRuleApplies">Applies</sys:String>
<sys:String x:Key="ProcessPowerPlanAssociationView_SavedRuleMode">Mode</sys:String>
<sys:String x:Key="ProcessPowerPlanAssociationView_SavedRuleUpdated">Updated</sys:String>
<sys:String x:Key="ProcessPowerPlanAssociationView_SavedRuleDelete">Delete</sys:String>
<sys:String x:Key="ProcessPowerPlanAssociationView_NoSavedRules">No saved process rules yet. Right-click a process in the Process tab and choose Rules to save one.</sys:String>
<sys:String x:Key="ProcessPowerPlanAssociationView_Executable">Executable</sys:String>
<sys:String x:Key="ProcessPowerPlanAssociationView_PowerPlan">Power Plan</sys:String>
<sys:String x:Key="ProcessPowerPlanAssociationView_CpuMask">CPU Mask</sys:String>
+8
View File
@@ -238,6 +238,14 @@
<sys:String x:Key="ProcessPowerPlanAssociationView_DescriptionLabel">Descripción:</sys:String>
<sys:String x:Key="ProcessPowerPlanAssociationView_AutomationService">Servicio de automatización</sys:String>
<sys:String x:Key="ProcessPowerPlanAssociationView_RulesHeader">Reglas</sys:String>
<sys:String x:Key="ProcessPowerPlanAssociationView_SavedRulesHeader">Reglas de proceso guardadas</sys:String>
<sys:String x:Key="ProcessPowerPlanAssociationView_SavedRulesDescription">Reglas guardadas desde la pestaña Procesos. ThreadPilot las vuelve a aplicar a ese proceso cada vez que se inicia, si la supervisión automática está activada. Son distintas de las reglas de plan de energía de arriba, que cambian el plan de energía global de Windows.</sys:String>
<sys:String x:Key="ProcessPowerPlanAssociationView_SavedRuleProcess">Proceso</sys:String>
<sys:String x:Key="ProcessPowerPlanAssociationView_SavedRuleApplies">Aplica</sys:String>
<sys:String x:Key="ProcessPowerPlanAssociationView_SavedRuleMode">Modo</sys:String>
<sys:String x:Key="ProcessPowerPlanAssociationView_SavedRuleUpdated">Actualizada</sys:String>
<sys:String x:Key="ProcessPowerPlanAssociationView_SavedRuleDelete">Eliminar</sys:String>
<sys:String x:Key="ProcessPowerPlanAssociationView_NoSavedRules">Aún no hay reglas de proceso guardadas. Haz clic derecho en un proceso en la pestaña Procesos y elige Reglas para guardar una.</sys:String>
<sys:String x:Key="ProcessPowerPlanAssociationView_Executable">ejecutable</sys:String>
<sys:String x:Key="ProcessPowerPlanAssociationView_PowerPlan">Plan de energía</sys:String>
<sys:String x:Key="ProcessPowerPlanAssociationView_CpuMask">Máscara de CPU</sys:String>
+8
View File
@@ -238,6 +238,14 @@
<sys:String x:Key="ProcessPowerPlanAssociationView_DescriptionLabel">Descriptif :</sys:String>
<sys:String x:Key="ProcessPowerPlanAssociationView_AutomationService">Service d'automatisation</sys:String>
<sys:String x:Key="ProcessPowerPlanAssociationView_RulesHeader">Règles</sys:String>
<sys:String x:Key="ProcessPowerPlanAssociationView_SavedRulesHeader">Règles de processus enregistrées</sys:String>
<sys:String x:Key="ProcessPowerPlanAssociationView_SavedRulesDescription">Règles enregistrées depuis l'onglet Processus. ThreadPilot les réapplique à ce processus à chaque démarrage, tant que la surveillance automatique est active. Elles sont distinctes des règles de mode d'alimentation ci-dessus, qui changent le mode d'alimentation global de Windows.</sys:String>
<sys:String x:Key="ProcessPowerPlanAssociationView_SavedRuleProcess">Processus</sys:String>
<sys:String x:Key="ProcessPowerPlanAssociationView_SavedRuleApplies">Applique</sys:String>
<sys:String x:Key="ProcessPowerPlanAssociationView_SavedRuleMode">Mode</sys:String>
<sys:String x:Key="ProcessPowerPlanAssociationView_SavedRuleUpdated">Mise à jour</sys:String>
<sys:String x:Key="ProcessPowerPlanAssociationView_SavedRuleDelete">Supprimer</sys:String>
<sys:String x:Key="ProcessPowerPlanAssociationView_NoSavedRules">Aucune règle de processus enregistrée. Faites un clic droit sur un processus dans l'onglet Processus et choisissez Règles pour en enregistrer une.</sys:String>
<sys:String x:Key="ProcessPowerPlanAssociationView_Executable">Exécutable</sys:String>
<sys:String x:Key="ProcessPowerPlanAssociationView_PowerPlan">Plan d'alimentation</sys:String>
<sys:String x:Key="ProcessPowerPlanAssociationView_CpuMask">CPU Masque</sys:String>
+8
View File
@@ -238,6 +238,14 @@
<sys:String x:Key="ProcessPowerPlanAssociationView_DescriptionLabel">Descrizione:</sys:String>
<sys:String x:Key="ProcessPowerPlanAssociationView_AutomationService">Servizio di automazione</sys:String>
<sys:String x:Key="ProcessPowerPlanAssociationView_RulesHeader">Regole</sys:String>
<sys:String x:Key="ProcessPowerPlanAssociationView_SavedRulesHeader">Regole di processo salvate</sys:String>
<sys:String x:Key="ProcessPowerPlanAssociationView_SavedRulesDescription">Regole salvate dalla scheda Processi. ThreadPilot le riapplica a quel processo a ogni avvio, se il monitoraggio automatico è attivo. Sono separate dalle regole dei profili energetici qui sopra, che cambiano il piano di alimentazione globale di Windows.</sys:String>
<sys:String x:Key="ProcessPowerPlanAssociationView_SavedRuleProcess">Processo</sys:String>
<sys:String x:Key="ProcessPowerPlanAssociationView_SavedRuleApplies">Applica</sys:String>
<sys:String x:Key="ProcessPowerPlanAssociationView_SavedRuleMode">Modalità</sys:String>
<sys:String x:Key="ProcessPowerPlanAssociationView_SavedRuleUpdated">Aggiornata</sys:String>
<sys:String x:Key="ProcessPowerPlanAssociationView_SavedRuleDelete">Elimina</sys:String>
<sys:String x:Key="ProcessPowerPlanAssociationView_NoSavedRules">Nessuna regola di processo salvata. Fai clic destro su un processo nella scheda Processi e scegli Regole per salvarne una.</sys:String>
<sys:String x:Key="ProcessPowerPlanAssociationView_Executable">Eseguibile</sys:String>
<sys:String x:Key="ProcessPowerPlanAssociationView_PowerPlan">Piano di alimentazione</sys:String>
<sys:String x:Key="ProcessPowerPlanAssociationView_CpuMask">CPU Maschera</sys:String>
+8
View File
@@ -238,6 +238,14 @@
<sys:String x:Key="ProcessPowerPlanAssociationView_DescriptionLabel">Описание:</sys:String>
<sys:String x:Key="ProcessPowerPlanAssociationView_AutomationService">Служба автоматизации</sys:String>
<sys:String x:Key="ProcessPowerPlanAssociationView_RulesHeader">Правила</sys:String>
<sys:String x:Key="ProcessPowerPlanAssociationView_SavedRulesHeader">Сохранённые правила процессов</sys:String>
<sys:String x:Key="ProcessPowerPlanAssociationView_SavedRulesDescription">Правила, сохранённые на вкладке «Процессы». ThreadPilot применяет их к процессу при каждом запуске, пока включён автоматический мониторинг. Они отличаются от правил схем питания выше, которые переключают глобальную схему питания Windows.</sys:String>
<sys:String x:Key="ProcessPowerPlanAssociationView_SavedRuleProcess">Процесс</sys:String>
<sys:String x:Key="ProcessPowerPlanAssociationView_SavedRuleApplies">Применяет</sys:String>
<sys:String x:Key="ProcessPowerPlanAssociationView_SavedRuleMode">Режим</sys:String>
<sys:String x:Key="ProcessPowerPlanAssociationView_SavedRuleUpdated">Обновлено</sys:String>
<sys:String x:Key="ProcessPowerPlanAssociationView_SavedRuleDelete">Удалить</sys:String>
<sys:String x:Key="ProcessPowerPlanAssociationView_NoSavedRules">Сохранённых правил процессов пока нет. Щёлкните процесс правой кнопкой на вкладке «Процессы» и выберите «Правила».</sys:String>
<sys:String x:Key="ProcessPowerPlanAssociationView_Executable">Исполняемый файл</sys:String>
<sys:String x:Key="ProcessPowerPlanAssociationView_PowerPlan">План электропитания</sys:String>
<sys:String x:Key="ProcessPowerPlanAssociationView_CpuMask">CPU Маска</sys:String>
+8
View File
@@ -238,6 +238,14 @@
<sys:String x:Key="ProcessPowerPlanAssociationView_DescriptionLabel">描述:</sys:String>
<sys:String x:Key="ProcessPowerPlanAssociationView_AutomationService">自动化服务</sys:String>
<sys:String x:Key="ProcessPowerPlanAssociationView_RulesHeader">规则</sys:String>
<sys:String x:Key="ProcessPowerPlanAssociationView_SavedRulesHeader">已保存的进程规则</sys:String>
<sys:String x:Key="ProcessPowerPlanAssociationView_SavedRulesDescription">在“进程”选项卡中保存的规则。只要自动化监控处于开启状态,ThreadPilot 会在该进程每次启动时重新应用它们。它们与上方的电源计划规则不同,后者切换的是 Windows 全局电源计划。</sys:String>
<sys:String x:Key="ProcessPowerPlanAssociationView_SavedRuleProcess">进程</sys:String>
<sys:String x:Key="ProcessPowerPlanAssociationView_SavedRuleApplies">应用</sys:String>
<sys:String x:Key="ProcessPowerPlanAssociationView_SavedRuleMode">模式</sys:String>
<sys:String x:Key="ProcessPowerPlanAssociationView_SavedRuleUpdated">更新时间</sys:String>
<sys:String x:Key="ProcessPowerPlanAssociationView_SavedRuleDelete">删除</sys:String>
<sys:String x:Key="ProcessPowerPlanAssociationView_NoSavedRules">尚无已保存的进程规则。在“进程”选项卡中右键点击某个进程并选择“规则”即可保存。</sys:String>
<sys:String x:Key="ProcessPowerPlanAssociationView_Executable">可执行文件</sys:String>
<sys:String x:Key="ProcessPowerPlanAssociationView_PowerPlan">电源计划</sys:String>
<sys:String x:Key="ProcessPowerPlanAssociationView_CpuMask">CPU 掩码</sys:String>
+18
View File
@@ -1604,6 +1604,11 @@ namespace ThreadPilot
this.SelectMainTab("Rules");
}
private void OnOpenMasksRequested(object? sender, EventArgs e)
{
this.SelectMainTab("Masks");
}
private void ShowWindowFromTray(string? tabTag = null)
{
this.ShowInTaskbar = true;
@@ -2030,6 +2035,18 @@ namespace ThreadPilot
this.SystemTweaksView.Visibility = tag == "Tweaks" ? Visibility.Visible : Visibility.Collapsed;
this.SettingsView.Visibility = tag == "Settings" ? Visibility.Visible : Visibility.Collapsed;
if (string.Equals(tag, "Rules", StringComparison.Ordinal))
{
// Re-read on every visit: a rule saved from the Process tab a moment ago has to be
// there when the user comes to look for it.
// ponytail: refresh on show, not a store change event - the two views are never
// visible at the same time. Revisit if a rule can ever be written while this is up.
TaskSafety.FireAndForget(this.associationViewModel.RefreshSavedProcessRulesAsync(), ex =>
{
this.LogDebug($"Refreshing saved process rules failed: {ex.Message}");
});
}
this.NavProcess.IsActive = tag == "Process";
this.NavMasks.IsActive = tag == "Masks";
this.NavPower.IsActive = tag == "Power";
@@ -2201,6 +2218,7 @@ namespace ThreadPilot
{
this.Loaded -= this.OnWindowLoaded;
this.processViewModel.OpenRulesRequested -= this.OnOpenRulesRequested;
this.processViewModel.OpenMasksRequested -= this.OnOpenMasksRequested;
this.settingsService.SettingsChanged -= this.OnSettingsChanged;
this.processMonitorService.MonitoringStatusChanged -= this.OnMonitoringStatusChanged;
+1
View File
@@ -131,6 +131,7 @@ namespace ThreadPilot
this.securityService = securityService;
this.processViewModel.OpenRulesRequested += this.OnOpenRulesRequested;
this.processViewModel.OpenMasksRequested += this.OnOpenMasksRequested;
System.Diagnostics.Debug.WriteLine("Dependencies assigned");
+37 -4
View File
@@ -26,6 +26,10 @@ namespace ThreadPilot.Services
Task<ProcessRuleCreationResult> DeleteRuleAsync(
ProcessModel process,
CancellationToken cancellationToken = default);
Task<ProcessRuleCreationResult> DeleteRuleByIdAsync(
string ruleId,
CancellationToken cancellationToken = default);
}
public sealed record ProcessRuleCreationPayload
@@ -164,15 +168,44 @@ namespace ThreadPilot.Services
return ProcessRuleCreationResult.Failed("NoSavedRuleToDelete", NoSavedRuleMessage);
}
var removed = rules[existingIndex];
rules.RemoveAt(existingIndex);
return await this.RemoveAtAsync(rules, existingIndex, cancellationToken).ConfigureAwait(false);
}
// The saved-rules list in the Rules tab holds rules, not processes: it can address a rule
// whose process is not running, which is exactly when a stale rule needs removing.
public async Task<ProcessRuleCreationResult> DeleteRuleByIdAsync(
string ruleId,
CancellationToken cancellationToken = default)
{
if (string.IsNullOrWhiteSpace(ruleId))
{
return ProcessRuleCreationResult.Failed("NoSavedRuleToDelete", NoSavedRuleMessage);
}
var rules = (await this.ruleStore.LoadAsync().ConfigureAwait(false)).ToList();
var existingIndex = rules.FindIndex(rule => string.Equals(rule.Id, ruleId, StringComparison.Ordinal));
if (existingIndex < 0)
{
return ProcessRuleCreationResult.Failed("NoSavedRuleToDelete", NoSavedRuleMessage);
}
return await this.RemoveAtAsync(rules, existingIndex, cancellationToken).ConfigureAwait(false);
}
private async Task<ProcessRuleCreationResult> RemoveAtAsync(
List<PersistentProcessRule> rules,
int index,
CancellationToken cancellationToken)
{
var removed = rules[index];
rules.RemoveAt(index);
cancellationToken.ThrowIfCancellationRequested();
await this.ruleStore.SaveAsync(rules).ConfigureAwait(false);
var processName = string.IsNullOrWhiteSpace(process.Name)
var processName = string.IsNullOrWhiteSpace(removed.ProcessName)
? "process"
: process.Name.Trim();
: removed.ProcessName.Trim();
this.logger.LogInformation(
"Deleted saved rule {RuleId} for process {ProcessName}",
removed.Id,
@@ -2,6 +2,7 @@ namespace ThreadPilot.Core.Tests
{
using Microsoft.Extensions.Logging.Abstractions;
using Moq;
using ThreadPilot.Models;
using ThreadPilot.Services;
using ThreadPilot.ViewModels;
@@ -31,5 +32,84 @@ namespace ThreadPilot.Core.Tests
processes.Verify(service => service.GetProcessesAsync(), Times.Never);
masks.Verify(service => service.InitializeAsync(), Times.Never);
}
[Fact]
public async Task RefreshSavedProcessRulesAsync_ListsWhatEachRuleActuallyApplies()
{
var store = new FakeRuleStore(
[
new PersistentProcessRule
{
Id = "rule-1",
ProcessName = "cs2",
IsEnabled = true,
ApplyAffinityOnStart = true,
CpuAssignmentMode = CpuAssignmentMode.AffinityMask,
ApplyMemoryPriorityOnStart = true,
MemoryPriority = ProcessMemoryPriority.Low,
},
]);
var viewModel = CreateViewModel(store, new Mock<IProcessRuleCreationService>().Object);
await viewModel.RefreshSavedProcessRulesAsync();
var row = Assert.Single(viewModel.SavedProcessRules);
Assert.Equal("cs2", row.ProcessName);
Assert.Contains("CPU assignment", row.Applies);
Assert.Contains("memory Low", row.Applies);
Assert.Equal("AffinityMask", row.Mode);
Assert.True(viewModel.HasSavedProcessRules);
}
[Fact]
public async Task DeleteSavedProcessRuleCommand_RemovesTheRuleAndReloadsTheList()
{
var store = new FakeRuleStore(
[
new PersistentProcessRule { Id = "rule-1", ProcessName = "cs2", IsEnabled = true },
]);
var ruleService = new Mock<IProcessRuleCreationService>();
ruleService
.Setup(service => service.DeleteRuleByIdAsync("rule-1", It.IsAny<CancellationToken>()))
.ReturnsAsync(() =>
{
store.Rules = [];
return new ProcessRuleCreationResult { Success = true, UserMessage = "Deleted saved rule for cs2." };
});
var viewModel = CreateViewModel(store, ruleService.Object);
await viewModel.RefreshSavedProcessRulesAsync();
await viewModel.DeleteSavedProcessRuleCommand.ExecuteAsync(viewModel.SavedProcessRules[0]);
ruleService.Verify(service => service.DeleteRuleByIdAsync("rule-1", It.IsAny<CancellationToken>()), Times.Once);
Assert.Empty(viewModel.SavedProcessRules);
Assert.False(viewModel.HasSavedProcessRules);
}
private static ProcessPowerPlanAssociationViewModel CreateViewModel(
IPersistentProcessRuleStore store,
IProcessRuleCreationService ruleService) =>
new(
NullLogger<ProcessPowerPlanAssociationViewModel>.Instance,
new Mock<IProcessPowerPlanAssociationService>(MockBehavior.Loose).Object,
new Mock<IPowerPlanService>(MockBehavior.Loose).Object,
new Mock<IProcessService>(MockBehavior.Loose).Object,
new Mock<IProcessMonitorManagerService>(MockBehavior.Loose).Object,
new Mock<ICoreMaskService>(MockBehavior.Loose).Object,
persistentRuleStore: store,
ruleCreationService: ruleService);
private sealed class FakeRuleStore(IReadOnlyList<PersistentProcessRule> rules) : IPersistentProcessRuleStore
{
public IReadOnlyList<PersistentProcessRule> Rules { get; set; } = rules;
public Task<IReadOnlyList<PersistentProcessRule>> LoadAsync() => Task.FromResult(this.Rules);
public Task SaveAsync(IReadOnlyList<PersistentProcessRule> rules)
{
this.Rules = rules;
return Task.CompletedTask;
}
}
}
}
@@ -1,6 +1,7 @@
namespace ThreadPilot.ViewModels
{
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
@@ -21,6 +22,8 @@ namespace ThreadPilot.ViewModels
private readonly IProcessService processService;
private readonly IProcessMonitorManagerService monitorManagerService;
private readonly ICoreMaskService coreMaskService;
private readonly IPersistentProcessRuleStore? persistentRuleStore;
private readonly IProcessRuleCreationService? ruleCreationService;
private bool isInitialized;
private readonly ILocalizationService? localizationService;
@@ -110,7 +113,9 @@ namespace ThreadPilot.ViewModels
IProcessMonitorManagerService monitorManagerService,
ICoreMaskService coreMaskService,
IEnhancedLoggingService? enhancedLoggingService = null,
ILocalizationService? localizationService = null)
ILocalizationService? localizationService = null,
IPersistentProcessRuleStore? persistentRuleStore = null,
IProcessRuleCreationService? ruleCreationService = null)
: base(logger, enhancedLoggingService)
{
this.associationService = associationService ?? throw new ArgumentNullException(nameof(associationService));
@@ -119,6 +124,8 @@ namespace ThreadPilot.ViewModels
this.monitorManagerService = monitorManagerService ?? throw new ArgumentNullException(nameof(monitorManagerService));
this.coreMaskService = coreMaskService ?? throw new ArgumentNullException(nameof(coreMaskService));
this.localizationService = localizationService;
this.persistentRuleStore = persistentRuleStore;
this.ruleCreationService = ruleCreationService;
// Subscribe to events
this.associationService.ConfigurationChanged += this.OnConfigurationChanged;
@@ -126,6 +133,98 @@ namespace ThreadPilot.ViewModels
this.monitorManagerService.ProcessPowerPlanChanged += this.OnProcessPowerPlanChanged;
}
// The per-process rules saved from the Process tab context menu. They are a different thing
// from the associations above - those switch the global power plan, these re-apply a
// process's own settings - and until they were listed here there was no way to see, or
// remove, a rule you had saved.
public ObservableCollection<SavedProcessRule> SavedProcessRules { get; } = new();
[ObservableProperty]
private bool hasSavedProcessRules;
public async Task RefreshSavedProcessRulesAsync()
{
if (this.persistentRuleStore == null)
{
return;
}
try
{
var rules = await this.persistentRuleStore.LoadAsync().ConfigureAwait(true);
this.SavedProcessRules.Clear();
foreach (var rule in rules.OrderBy(rule => rule.ProcessName, StringComparer.OrdinalIgnoreCase))
{
this.SavedProcessRules.Add(SavedProcessRule.From(rule));
}
this.HasSavedProcessRules = this.SavedProcessRules.Count > 0;
}
catch (Exception ex)
{
this.Logger.LogWarning(ex, "Could not load saved process rules for the Rules tab");
}
}
[RelayCommand]
private async Task DeleteSavedProcessRuleAsync(SavedProcessRule? rule)
{
if (rule == null || this.ruleCreationService == null)
{
return;
}
var result = await this.ruleCreationService.DeleteRuleByIdAsync(rule.Id).ConfigureAwait(true);
this.SetStatus(result.UserMessage, false);
await this.RefreshSavedProcessRulesAsync().ConfigureAwait(true);
}
public sealed record SavedProcessRule(
string Id,
string ProcessName,
string Applies,
string Mode,
bool IsEnabled,
DateTime UpdatedAt)
{
public static SavedProcessRule From(PersistentProcessRule rule)
{
var applies = new List<string>();
if (rule.ApplyAffinityOnStart)
{
applies.Add("CPU assignment");
}
if (rule.ApplyPriorityOnStart && rule.Priority.HasValue)
{
applies.Add($"priority {rule.Priority}");
}
if (rule.ApplyMemoryPriorityOnStart && rule.MemoryPriority.HasValue)
{
applies.Add($"memory {rule.MemoryPriority}");
}
if (rule.ApplyIoPriorityOnStart && rule.IoPriority.HasValue)
{
applies.Add($"I/O {rule.IoPriority}");
}
if (rule.PreventSystemSleepWhileRunning)
{
applies.Add("keeps the system awake");
}
return new SavedProcessRule(
rule.Id,
string.IsNullOrWhiteSpace(rule.ProcessName) ? "(unnamed)" : rule.ProcessName,
applies.Count == 0 ? "nothing" : string.Join(", ", applies),
rule.ApplyAffinityOnStart ? rule.CpuAssignmentMode.ToString() : "-",
rule.IsEnabled,
rule.UpdatedAt.ToLocalTime());
}
}
protected override void OnDispose()
{
this.associationService.ConfigurationChanged -= this.OnConfigurationChanged;
@@ -143,6 +242,7 @@ namespace ThreadPilot.ViewModels
this.isInitialized = true;
await this.LoadDataAsync();
await this.RefreshSavedProcessRulesAsync();
this.UpdateServiceStatus();
}
@@ -1171,44 +1171,14 @@ namespace ThreadPilot.ViewModels
}
// Was hunting for a TabControl in the visual tree and setting SelectedIndex; the window has
// been a NavigationView for several versions, so the lookup returned null and the button did
// nothing at all. Navigation belongs to the window, which already owns this exact pattern
// for the Rules tab.
[RelayCommand]
private void CreateCustomMask()
{
// Request to switch to Core Masks tab
System.Windows.Application.Current.Dispatcher.Invoke(() =>
{
var mainWindow = System.Windows.Application.Current.MainWindow;
if (mainWindow != null)
{
// Find the TabControl in MainWindow
var tabControl = FindVisualChild<System.Windows.Controls.TabControl>(mainWindow);
if (tabControl != null)
{
// Switch to Core Masks tab (index 1)
tabControl.SelectedIndex = 1;
}
}
});
}
private static T? FindVisualChild<T>(System.Windows.DependencyObject obj)
where T : System.Windows.DependencyObject
{
for (int i = 0; i < System.Windows.Media.VisualTreeHelper.GetChildrenCount(obj); i++)
{
var child = System.Windows.Media.VisualTreeHelper.GetChild(obj, i);
if (child is T typedChild)
{
return typedChild;
}
var childOfChild = FindVisualChild<T>(child);
if (childOfChild != null)
{
return childOfChild;
}
}
return null;
this.OpenMasksRequested?.Invoke(this, EventArgs.Empty);
}
partial void OnSelectedCoreMaskChanged(CoreMask? oldValue, CoreMask? newValue)
@@ -1604,6 +1574,15 @@ namespace ThreadPilot.ViewModels
}
await this.processService.RefreshProcessInfo(process);
if (ReferenceEquals(this.SelectedProcess, process))
{
// The chips were showing the soft assignment that has just been removed. Without
// this they keep advertising cores the process is no longer pinned to until it
// happens to be reselected - and a rule saved in between would capture them.
this.UpdateCoreSelections(process.ProcessorAffinity, true);
this.UpdateAffinityDisplayState();
}
this.SetStatus($"CPU Sets cleared for {process.Name}.", false);
await this.LogUserActionAsync(
"CpuSetsCleared",
+2
View File
@@ -19,6 +19,8 @@ namespace ThreadPilot.ViewModels
{
public event EventHandler? OpenRulesRequested;
public event EventHandler? OpenMasksRequested;
private readonly IProcessService processService;
private readonly ProcessFilterService processFilterService;
private readonly IVirtualizedProcessService virtualizedProcessService;
@@ -274,6 +274,81 @@
</Grid>
</TabItem>
<!-- Saved Process Rules Tab -->
<TabItem Header="{DynamicResource ProcessPowerPlanAssociationView_SavedRulesHeader}">
<Grid Margin="10">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<TextBlock Grid.Row="0"
Text="{DynamicResource ProcessPowerPlanAssociationView_SavedRulesDescription}"
Foreground="{DynamicResource TextSecondaryBrush}"
TextWrapping="Wrap"
Margin="0,0,0,10"/>
<Grid Grid.Row="1">
<DataGrid ItemsSource="{Binding SavedProcessRules}"
AutoGenerateColumns="False"
CanUserAddRows="False"
IsReadOnly="True"
GridLinesVisibility="Horizontal"
HeadersVisibility="Column"
BorderThickness="1">
<DataGrid.Columns>
<DataGridCheckBoxColumn Header="{DynamicResource MasksView_Enabled}"
Binding="{Binding IsEnabled}"
Width="60"/>
<DataGridTextColumn Header="{DynamicResource ProcessPowerPlanAssociationView_SavedRuleProcess}"
Binding="{Binding ProcessName}"
Width="150"/>
<DataGridTextColumn Header="{DynamicResource ProcessPowerPlanAssociationView_SavedRuleApplies}"
Binding="{Binding Applies}"
Width="*"/>
<DataGridTextColumn Header="{DynamicResource ProcessPowerPlanAssociationView_SavedRuleMode}"
Binding="{Binding Mode}"
Width="110"/>
<DataGridTextColumn Header="{DynamicResource ProcessPowerPlanAssociationView_SavedRuleUpdated}"
Binding="{Binding UpdatedAt}"
Width="140"/>
<DataGridTemplateColumn Width="90">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Button Content="{DynamicResource ProcessPowerPlanAssociationView_SavedRuleDelete}"
Padding="8,2"
Margin="2"
Command="{Binding DataContext.DeleteSavedProcessRuleCommand, RelativeSource={RelativeSource AncestorType=DataGrid}}"
CommandParameter="{Binding}"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
<Border Padding="18"
IsHitTestVisible="False"
HorizontalAlignment="Center"
VerticalAlignment="Center">
<Border.Style>
<Style TargetType="Border">
<Setter Property="Visibility" Value="Collapsed"/>
<Style.Triggers>
<DataTrigger Binding="{Binding SavedProcessRules.Count}" Value="0">
<Setter Property="Visibility" Value="Visible"/>
</DataTrigger>
</Style.Triggers>
</Style>
</Border.Style>
<TextBlock Text="{DynamicResource ProcessPowerPlanAssociationView_NoSavedRules}"
Foreground="{DynamicResource TextSecondaryBrush}"
TextWrapping="Wrap"
TextAlignment="Center"/>
</Border>
</Grid>
</Grid>
</TabItem>
<!-- Automation Monitoring Tab -->
<TabItem Header="{DynamicResource ProcessPowerPlanAssociationView_AutomationMonitoring}">
<ScrollViewer Margin="10">