From df23cd1be91aafb7b9105a69b8a54bd44cbf8a62 Mon Sep 17 00:00:00 2001 From: PrimeBuild-pc Date: Wed, 26 Aug 2026 22:48:36 +0200 Subject: [PATCH] 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 --- Locales/de-DE.xaml | 8 ++ Locales/en-US.xaml | 8 ++ Locales/es-ES.xaml | 8 ++ Locales/fr-FR.xaml | 8 ++ Locales/it-IT.xaml | 8 ++ Locales/ru-RU.xaml | 8 ++ Locales/zh-CN.xaml | 8 ++ MainWindow.Behaviors.partial.cs | 18 ++++ MainWindow.xaml.cs | 1 + Services/ProcessRuleCreationService.cs | 41 ++++++- ...ocessPowerPlanAssociationViewModelTests.cs | 80 ++++++++++++++ .../ProcessPowerPlanAssociationViewModel.cs | 102 +++++++++++++++++- .../ProcessViewModel.Behaviors.partial.cs | 49 +++------ ViewModels/ProcessViewModel.cs | 2 + Views/ProcessPowerPlanAssociationView.xaml | 75 +++++++++++++ 15 files changed, 384 insertions(+), 40 deletions(-) diff --git a/Locales/de-DE.xaml b/Locales/de-DE.xaml index 9d2c0ad..b89cd16 100644 --- a/Locales/de-DE.xaml +++ b/Locales/de-DE.xaml @@ -238,6 +238,14 @@ Beschreibung: Automatisierungsdienst Regeln + Gespeicherte Prozessregeln + 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. + Prozess + Wendet an + Modus + Aktualisiert + Löschen + Noch keine gespeicherten Prozessregeln. Klicken Sie auf der Registerkarte Prozesse mit der rechten Maustaste auf einen Prozess und wählen Sie Regeln. Ausführbar Energieplan CPU Maske diff --git a/Locales/en-US.xaml b/Locales/en-US.xaml index e882a4a..b1e2ac9 100644 --- a/Locales/en-US.xaml +++ b/Locales/en-US.xaml @@ -238,6 +238,14 @@ Description: Automation Service Rules + Saved process rules + 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. + Process + Applies + Mode + Updated + Delete + No saved process rules yet. Right-click a process in the Process tab and choose Rules to save one. Executable Power Plan CPU Mask diff --git a/Locales/es-ES.xaml b/Locales/es-ES.xaml index 35413f8..3c42b49 100644 --- a/Locales/es-ES.xaml +++ b/Locales/es-ES.xaml @@ -238,6 +238,14 @@ Descripción: Servicio de automatización Reglas + Reglas de proceso guardadas + 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. + Proceso + Aplica + Modo + Actualizada + Eliminar + 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. ejecutable Plan de energía Máscara de CPU diff --git a/Locales/fr-FR.xaml b/Locales/fr-FR.xaml index 263338c..5d0cbc9 100644 --- a/Locales/fr-FR.xaml +++ b/Locales/fr-FR.xaml @@ -238,6 +238,14 @@ Descriptif : Service d'automatisation Règles + Règles de processus enregistrées + 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. + Processus + Applique + Mode + Mise à jour + Supprimer + 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. Exécutable Plan d'alimentation CPU Masque diff --git a/Locales/it-IT.xaml b/Locales/it-IT.xaml index 0c38108..48f99b9 100644 --- a/Locales/it-IT.xaml +++ b/Locales/it-IT.xaml @@ -238,6 +238,14 @@ Descrizione: Servizio di automazione Regole + Regole di processo salvate + 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. + Processo + Applica + Modalità + Aggiornata + Elimina + Nessuna regola di processo salvata. Fai clic destro su un processo nella scheda Processi e scegli Regole per salvarne una. Eseguibile Piano di alimentazione CPU Maschera diff --git a/Locales/ru-RU.xaml b/Locales/ru-RU.xaml index 7313ede..69a8439 100644 --- a/Locales/ru-RU.xaml +++ b/Locales/ru-RU.xaml @@ -238,6 +238,14 @@ Описание: Служба автоматизации Правила + Сохранённые правила процессов + Правила, сохранённые на вкладке «Процессы». ThreadPilot применяет их к процессу при каждом запуске, пока включён автоматический мониторинг. Они отличаются от правил схем питания выше, которые переключают глобальную схему питания Windows. + Процесс + Применяет + Режим + Обновлено + Удалить + Сохранённых правил процессов пока нет. Щёлкните процесс правой кнопкой на вкладке «Процессы» и выберите «Правила». Исполняемый файл План электропитания CPU Маска diff --git a/Locales/zh-CN.xaml b/Locales/zh-CN.xaml index e855aaa..ac2ac3f 100644 --- a/Locales/zh-CN.xaml +++ b/Locales/zh-CN.xaml @@ -238,6 +238,14 @@ 描述: 自动化服务 规则 + 已保存的进程规则 + 在“进程”选项卡中保存的规则。只要自动化监控处于开启状态,ThreadPilot 会在该进程每次启动时重新应用它们。它们与上方的电源计划规则不同,后者切换的是 Windows 全局电源计划。 + 进程 + 应用 + 模式 + 更新时间 + 删除 + 尚无已保存的进程规则。在“进程”选项卡中右键点击某个进程并选择“规则”即可保存。 可执行文件 电源计划 CPU 掩码 diff --git a/MainWindow.Behaviors.partial.cs b/MainWindow.Behaviors.partial.cs index 3212609..b3137bf 100644 --- a/MainWindow.Behaviors.partial.cs +++ b/MainWindow.Behaviors.partial.cs @@ -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; diff --git a/MainWindow.xaml.cs b/MainWindow.xaml.cs index 4d7520d..300d8e1 100644 --- a/MainWindow.xaml.cs +++ b/MainWindow.xaml.cs @@ -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"); diff --git a/Services/ProcessRuleCreationService.cs b/Services/ProcessRuleCreationService.cs index 96b5efc..be14b64 100644 --- a/Services/ProcessRuleCreationService.cs +++ b/Services/ProcessRuleCreationService.cs @@ -26,6 +26,10 @@ namespace ThreadPilot.Services Task DeleteRuleAsync( ProcessModel process, CancellationToken cancellationToken = default); + + Task 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 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 RemoveAtAsync( + List 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, diff --git a/Tests/ThreadPilot.Core.Tests/ProcessPowerPlanAssociationViewModelTests.cs b/Tests/ThreadPilot.Core.Tests/ProcessPowerPlanAssociationViewModelTests.cs index 1aa6a9e..b47143c 100644 --- a/Tests/ThreadPilot.Core.Tests/ProcessPowerPlanAssociationViewModelTests.cs +++ b/Tests/ThreadPilot.Core.Tests/ProcessPowerPlanAssociationViewModelTests.cs @@ -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().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(); + ruleService + .Setup(service => service.DeleteRuleByIdAsync("rule-1", It.IsAny())) + .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()), Times.Once); + Assert.Empty(viewModel.SavedProcessRules); + Assert.False(viewModel.HasSavedProcessRules); + } + + private static ProcessPowerPlanAssociationViewModel CreateViewModel( + IPersistentProcessRuleStore store, + IProcessRuleCreationService ruleService) => + new( + NullLogger.Instance, + new Mock(MockBehavior.Loose).Object, + new Mock(MockBehavior.Loose).Object, + new Mock(MockBehavior.Loose).Object, + new Mock(MockBehavior.Loose).Object, + new Mock(MockBehavior.Loose).Object, + persistentRuleStore: store, + ruleCreationService: ruleService); + + private sealed class FakeRuleStore(IReadOnlyList rules) : IPersistentProcessRuleStore + { + public IReadOnlyList Rules { get; set; } = rules; + + public Task> LoadAsync() => Task.FromResult(this.Rules); + + public Task SaveAsync(IReadOnlyList rules) + { + this.Rules = rules; + return Task.CompletedTask; + } + } } } diff --git a/ViewModels/ProcessPowerPlanAssociationViewModel.cs b/ViewModels/ProcessPowerPlanAssociationViewModel.cs index 80a025b..c32a696 100644 --- a/ViewModels/ProcessPowerPlanAssociationViewModel.cs +++ b/ViewModels/ProcessPowerPlanAssociationViewModel.cs @@ -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 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(); + 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(); } diff --git a/ViewModels/ProcessViewModel.Behaviors.partial.cs b/ViewModels/ProcessViewModel.Behaviors.partial.cs index f2a80fe..d214b29 100644 --- a/ViewModels/ProcessViewModel.Behaviors.partial.cs +++ b/ViewModels/ProcessViewModel.Behaviors.partial.cs @@ -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(mainWindow); - if (tabControl != null) - { - // Switch to Core Masks tab (index 1) - tabControl.SelectedIndex = 1; - } - } - }); - } - - private static T? FindVisualChild(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(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", diff --git a/ViewModels/ProcessViewModel.cs b/ViewModels/ProcessViewModel.cs index be2dad8..fafeb38 100644 --- a/ViewModels/ProcessViewModel.cs +++ b/ViewModels/ProcessViewModel.cs @@ -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; diff --git a/Views/ProcessPowerPlanAssociationView.xaml b/Views/ProcessPowerPlanAssociationView.xaml index 78c68db..a25e145 100644 --- a/Views/ProcessPowerPlanAssociationView.xaml +++ b/Views/ProcessPowerPlanAssociationView.xaml @@ -274,6 +274,81 @@ + + + + + + + + + + + + + + + + + + + + + +