diff --git a/Locales/de-DE.xaml b/Locales/de-DE.xaml index b89cd16..d2155a1 100644 --- a/Locales/de-DE.xaml +++ b/Locales/de-DE.xaml @@ -245,6 +245,14 @@ Modus Aktualisiert Löschen + Regel bearbeiten + CPU-Priorität + Speicherpriorität + E/A-Priorität + CPU-Zuweisungsmodus + System wach halten, solange dieser Prozess läuft + Die Kerne, an die diese Regel bindet, werden auf der Registerkarte Prozesse bearbeitet, wo die Kernauswahl liegt. + Änderungen speichern 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 @@ -605,6 +613,7 @@ Bereit + ThreadPilot konnte diese Einstellung auf diesem System nicht lesen. Erfrischende Systemoptimierungen... Letzte Aktualisierung: {0} Systemoptimierungen konnten nicht aktualisiert werden diff --git a/Locales/en-US.xaml b/Locales/en-US.xaml index b1e2ac9..0dc1d89 100644 --- a/Locales/en-US.xaml +++ b/Locales/en-US.xaml @@ -245,6 +245,14 @@ Mode Updated Delete + Edit rule + CPU priority + Memory priority + I/O priority + CPU assignment mode + Keep the system awake while this process runs + The cores this rule pins to are edited from the Process tab, where the core picker lives. + Save changes No saved process rules yet. Right-click a process in the Process tab and choose Rules to save one. Executable Power Plan @@ -605,6 +613,7 @@ Ready + ThreadPilot could not read this setting on this system. Refreshing system tweaks... Last refreshed: {0} Failed to refresh system tweaks diff --git a/Locales/es-ES.xaml b/Locales/es-ES.xaml index 3c42b49..f129932 100644 --- a/Locales/es-ES.xaml +++ b/Locales/es-ES.xaml @@ -245,6 +245,14 @@ Modo Actualizada Eliminar + Editar regla + Prioridad de CPU + Prioridad de memoria + Prioridad de E/S + Modo de asignación de CPU + Impedir la suspensión mientras este proceso se ejecuta + Los núcleos a los que se fija esta regla se editan en la pestaña Procesos, donde está el selector de núcleos. + Guardar cambios 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 @@ -605,6 +613,7 @@ Listo + ThreadPilot no ha podido leer esta configuración en este sistema. Actualizaciones en el sistema... Última actualización: {0} No se pudieron actualizar los ajustes del sistema diff --git a/Locales/fr-FR.xaml b/Locales/fr-FR.xaml index 5d0cbc9..a9c4521 100644 --- a/Locales/fr-FR.xaml +++ b/Locales/fr-FR.xaml @@ -245,6 +245,14 @@ Mode Mise à jour Supprimer + Modifier la règle + Priorité CPU + Priorité mémoire + Priorité E/S + Mode d'affectation CPU + Empêcher la mise en veille pendant l'exécution de ce processus + Les cœurs auxquels cette règle est liée se modifient dans l'onglet Processus, où se trouve le sélecteur de cœurs. + Enregistrer les modifications 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 @@ -605,6 +613,7 @@ Prêt + ThreadPilot n'a pas pu lire ce paramètre sur ce système. Modifications rafraîchissantes du système... Dernière actualisation : {0} Échec de l'actualisation des réglages du système diff --git a/Locales/it-IT.xaml b/Locales/it-IT.xaml index 48f99b9..508ef6e 100644 --- a/Locales/it-IT.xaml +++ b/Locales/it-IT.xaml @@ -245,6 +245,14 @@ Modalità Aggiornata Elimina + Modifica regola + Priorità CPU + Priorità memoria + Priorità I/O + Modalità di assegnazione CPU + Impedisci la sospensione mentre il processo è in esecuzione + I core a cui questa regola vincola il processo si modificano dalla scheda Processi, dove c'è il selettore dei core. + Salva modifiche Nessuna regola di processo salvata. Fai clic destro su un processo nella scheda Processi e scegli Regole per salvarne una. Eseguibile Piano di alimentazione @@ -605,6 +613,7 @@ Pronto + ThreadPilot non è riuscito a leggere questa impostazione su questo sistema. Aggiornamento delle modifiche al sistema... Ultimo aggiornamento: {0} Impossibile aggiornare le modifiche al sistema diff --git a/Locales/ru-RU.xaml b/Locales/ru-RU.xaml index 69a8439..aed1d2f 100644 --- a/Locales/ru-RU.xaml +++ b/Locales/ru-RU.xaml @@ -245,6 +245,14 @@ Режим Обновлено Удалить + Изменить правило + Приоритет ЦП + Приоритет памяти + Приоритет ввода-вывода + Режим назначения ЦП + Не давать системе засыпать, пока процесс работает + Ядра, к которым привязано это правило, изменяются на вкладке «Процессы», где находится выбор ядер. + Сохранить изменения Сохранённых правил процессов пока нет. Щёлкните процесс правой кнопкой на вкладке «Процессы» и выберите «Правила». Исполняемый файл План электропитания @@ -605,6 +613,7 @@ Готово + ThreadPilot не смог прочитать этот параметр в этой системе. Обновление настроек системы... Последнее обновление: {0} Не удалось обновить настройки системы. diff --git a/Locales/zh-CN.xaml b/Locales/zh-CN.xaml index ac2ac3f..5e18c83 100644 --- a/Locales/zh-CN.xaml +++ b/Locales/zh-CN.xaml @@ -245,6 +245,14 @@ 模式 更新时间 删除 + 编辑规则 + CPU 优先级 + 内存优先级 + I/O 优先级 + CPU 分配模式 + 该进程运行时阻止系统休眠 + 此规则绑定的核心需在“进程”选项卡中修改,核心选择器在那里。 + 保存更改 尚无已保存的进程规则。在“进程”选项卡中右键点击某个进程并选择“规则”即可保存。 可执行文件 电源计划 @@ -605,6 +613,7 @@ 就绪 + ThreadPilot 无法在此系统上读取该设置。 正在刷新系统微调选项... 上次刷新时间: {0} 刷新系统微调失败 diff --git a/Services/ProcessRuleCreationService.cs b/Services/ProcessRuleCreationService.cs index be14b64..10382ce 100644 --- a/Services/ProcessRuleCreationService.cs +++ b/Services/ProcessRuleCreationService.cs @@ -30,6 +30,10 @@ namespace ThreadPilot.Services Task DeleteRuleByIdAsync( string ruleId, CancellationToken cancellationToken = default); + + Task UpdateRuleAsync( + PersistentProcessRule rule, + CancellationToken cancellationToken = default); } public sealed record ProcessRuleCreationPayload @@ -192,6 +196,63 @@ namespace ThreadPilot.Services return await this.RemoveAtAsync(rules, existingIndex, cancellationToken).ConfigureAwait(false); } + // Editing a rule in place, from the saved-rules list. The affinity payload is not editable + // there - that needs the core picker in the Process tab - so it is carried over untouched + // rather than rebuilt, and only the fields the editor owns are replaced. + public async Task UpdateRuleAsync( + PersistentProcessRule rule, + CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(rule); + + if (rule.Priority.HasValue && ProcessPriorityGuardrails.IsBlocked(rule.Priority.Value)) + { + return ProcessRuleCreationResult.Failed( + "RealtimePriorityBlocked", + ProcessOperationUserMessages.RealtimePriorityBlocked); + } + + var rules = (await this.ruleStore.LoadAsync().ConfigureAwait(false)).ToList(); + var existingIndex = rules.FindIndex(candidate => string.Equals(candidate.Id, rule.Id, StringComparison.Ordinal)); + if (existingIndex < 0) + { + return ProcessRuleCreationResult.Failed("NoSavedRuleToUpdate", NoSavedRuleMessage); + } + + var existing = rules[existingIndex]; + var updated = existing with + { + IsEnabled = rule.IsEnabled, + Priority = rule.Priority, + MemoryPriority = rule.MemoryPriority, + IoPriority = rule.IoPriority, + CpuAssignmentMode = rule.CpuAssignmentMode, + PreventSystemSleepWhileRunning = rule.PreventSystemSleepWhileRunning, + ApplyPriorityOnStart = rule.Priority.HasValue, + ApplyMemoryPriorityOnStart = rule.MemoryPriority.HasValue, + ApplyIoPriorityOnStart = rule.IoPriority.HasValue, + UpdatedAt = DateTime.UtcNow, + }; + + rules[existingIndex] = updated; + + cancellationToken.ThrowIfCancellationRequested(); + await this.ruleStore.SaveAsync(rules).ConfigureAwait(false); + + var processName = string.IsNullOrWhiteSpace(updated.ProcessName) + ? "process" + : updated.ProcessName.Trim(); + this.logger.LogInformation("Updated saved rule {RuleId} for process {ProcessName}", updated.Id, processName); + + return new ProcessRuleCreationResult + { + Success = true, + Updated = true, + Rule = updated, + UserMessage = $"Updated saved rule for {processName}.", + }; + } + private async Task RemoveAtAsync( List rules, int index, diff --git a/Tests/ThreadPilot.Core.Tests/ProcessRuleCreationServiceTests.cs b/Tests/ThreadPilot.Core.Tests/ProcessRuleCreationServiceTests.cs index b38c1cd..b4285c1 100644 --- a/Tests/ThreadPilot.Core.Tests/ProcessRuleCreationServiceTests.cs +++ b/Tests/ThreadPilot.Core.Tests/ProcessRuleCreationServiceTests.cs @@ -556,6 +556,94 @@ namespace ThreadPilot.Core.Tests Assert.Empty(store.SavedRules); } + [Fact] + public async Task UpdateRuleAsync_ChangesTheEditableFieldsAndKeepsTheAffinity() + { + var selection = CreateCpuSelection(); + var existing = new PersistentProcessRule + { + Id = "rule-1", + ProcessName = "cs2", + IsEnabled = true, + CpuSelection = selection, + ApplyAffinityOnStart = true, + CpuAssignmentMode = CpuAssignmentMode.AffinityMask, + }; + var store = new CapturingRuleStore([existing]); + var service = CreateService(store); + + var result = await service.UpdateRuleAsync(existing with + { + IsEnabled = false, + MemoryPriority = ProcessMemoryPriority.Low, + Priority = ProcessPriorityClass.High, + }); + + Assert.True(result.Success); + var rule = Assert.Single(store.SavedRules); + Assert.False(rule.IsEnabled); + Assert.Equal(ProcessMemoryPriority.Low, rule.MemoryPriority); + Assert.True(rule.ApplyMemoryPriorityOnStart); + Assert.Equal(ProcessPriorityClass.High, rule.Priority); + Assert.True(rule.ApplyPriorityOnStart); + Assert.Same(selection, rule.CpuSelection); + Assert.True(rule.ApplyAffinityOnStart); + } + + [Fact] + public async Task UpdateRuleAsync_ClearsAFieldTheEditorSetBackToNone() + { + var existing = new PersistentProcessRule + { + Id = "rule-1", + ProcessName = "cs2", + IsEnabled = true, + MemoryPriority = ProcessMemoryPriority.Low, + ApplyMemoryPriorityOnStart = true, + }; + var store = new CapturingRuleStore([existing]); + var service = CreateService(store); + + await service.UpdateRuleAsync(existing with { MemoryPriority = null }); + + var rule = Assert.Single(store.SavedRules); + Assert.Null(rule.MemoryPriority); + Assert.False(rule.ApplyMemoryPriorityOnStart); + } + + [Fact] + public async Task UpdateRuleAsync_RefusesRealtimeAndLeavesTheRuleAlone() + { + var existing = new PersistentProcessRule + { + Id = "rule-1", + ProcessName = "cs2", + IsEnabled = true, + Priority = ProcessPriorityClass.High, + ApplyPriorityOnStart = true, + }; + var store = new CapturingRuleStore([existing]); + var service = CreateService(store); + + var result = await service.UpdateRuleAsync(existing with { Priority = ProcessPriorityClass.RealTime }); + + Assert.False(result.Success); + Assert.Equal("RealtimePriorityBlocked", result.ErrorCode); + Assert.Empty(store.SavedRules); + } + + [Fact] + public async Task UpdateRuleAsync_ReportsAControlledFailureForAnUnknownRule() + { + var store = new CapturingRuleStore([]); + var service = CreateService(store); + + var result = await service.UpdateRuleAsync(new PersistentProcessRule { Id = "missing", ProcessName = "cs2" }); + + Assert.False(result.Success); + Assert.Equal("NoSavedRuleToUpdate", result.ErrorCode); + } + private static ProcessModel CreateProcess( string name = "Game.exe", string path = @"C:\Games\Game.exe", diff --git a/ViewModels/ProcessPowerPlanAssociationViewModel.cs b/ViewModels/ProcessPowerPlanAssociationViewModel.cs index c32a696..fd2bc5e 100644 --- a/ViewModels/ProcessPowerPlanAssociationViewModel.cs +++ b/ViewModels/ProcessPowerPlanAssociationViewModel.cs @@ -179,13 +179,111 @@ namespace ThreadPilot.ViewModels await this.RefreshSavedProcessRulesAsync().ConfigureAwait(true); } + // Editing a saved rule in place. Everything except the core selection is editable here; + // that one needs the picker in the Process tab, so it is shown but not editable, and + // carried through untouched by the update. + [ObservableProperty] + private SavedProcessRule? selectedSavedProcessRule; + + [ObservableProperty] + private bool savedRuleIsEnabled = true; + + [ObservableProperty] + private bool savedRulePreventSleep; + + [ObservableProperty] + private string savedRulePriority = NoneOption; + + [ObservableProperty] + private string savedRuleMemoryPriority = NoneOption; + + [ObservableProperty] + private string savedRuleIoPriority = NoneOption; + + [ObservableProperty] + private string savedRuleCpuAssignmentMode = nameof(CpuAssignmentMode.AffinityMask); + + public const string NoneOption = "None"; + + // Realtime is deliberately absent: the service refuses it, so offering it would only + // produce an error the user cannot resolve. + public IReadOnlyList SavedRulePriorityOptions { get; } = + [ + NoneOption, + nameof(System.Diagnostics.ProcessPriorityClass.Idle), + nameof(System.Diagnostics.ProcessPriorityClass.BelowNormal), + nameof(System.Diagnostics.ProcessPriorityClass.Normal), + nameof(System.Diagnostics.ProcessPriorityClass.AboveNormal), + nameof(System.Diagnostics.ProcessPriorityClass.High), + ]; + + public IReadOnlyList SavedRuleMemoryPriorityOptions { get; } = + [NoneOption, .. Enum.GetNames()]; + + public IReadOnlyList SavedRuleIoPriorityOptions { get; } = + [NoneOption, .. Enum.GetNames()]; + + public IReadOnlyList SavedRuleCpuAssignmentModeOptions { get; } = + [.. Enum.GetNames()]; + + partial void OnSelectedSavedProcessRuleChanged(SavedProcessRule? value) + { + if (value == null) + { + return; + } + + var rule = value.Source; + this.SavedRuleIsEnabled = rule.IsEnabled; + this.SavedRulePreventSleep = rule.PreventSystemSleepWhileRunning; + this.SavedRulePriority = rule.Priority?.ToString() ?? NoneOption; + this.SavedRuleMemoryPriority = rule.MemoryPriority?.ToString() ?? NoneOption; + this.SavedRuleIoPriority = rule.IoPriority?.ToString() ?? NoneOption; + this.SavedRuleCpuAssignmentMode = rule.CpuAssignmentMode.ToString(); + } + + [RelayCommand] + private async Task SaveSavedProcessRuleAsync() + { + var selected = this.SelectedSavedProcessRule; + if (selected == null || this.ruleCreationService == null) + { + return; + } + + var updated = selected.Source with + { + IsEnabled = this.SavedRuleIsEnabled, + PreventSystemSleepWhileRunning = this.SavedRulePreventSleep, + Priority = ParseOption(this.SavedRulePriority), + MemoryPriority = ParseOption(this.SavedRuleMemoryPriority), + IoPriority = ParseOption(this.SavedRuleIoPriority), + CpuAssignmentMode = Enum.TryParse(this.SavedRuleCpuAssignmentMode, out var mode) + ? mode + : selected.Source.CpuAssignmentMode, + }; + + var result = await this.ruleCreationService.UpdateRuleAsync(updated).ConfigureAwait(true); + this.SetStatus(result.UserMessage, false); + await this.RefreshSavedProcessRulesAsync().ConfigureAwait(true); + this.SelectedSavedProcessRule = this.SavedProcessRules + .FirstOrDefault(row => string.Equals(row.Id, selected.Id, StringComparison.Ordinal)); + } + + private static T? ParseOption(string? option) + where T : struct, Enum => + string.IsNullOrWhiteSpace(option) || string.Equals(option, NoneOption, StringComparison.Ordinal) + ? null + : Enum.TryParse(option, out var parsed) ? parsed : null; + public sealed record SavedProcessRule( string Id, string ProcessName, string Applies, string Mode, bool IsEnabled, - DateTime UpdatedAt) + DateTime UpdatedAt, + PersistentProcessRule Source) { public static SavedProcessRule From(PersistentProcessRule rule) { @@ -221,7 +319,8 @@ namespace ThreadPilot.ViewModels applies.Count == 0 ? "nothing" : string.Join(", ", applies), rule.ApplyAffinityOnStart ? rule.CpuAssignmentMode.ToString() : "-", rule.IsEnabled, - rule.UpdatedAt.ToLocalTime()); + rule.UpdatedAt.ToLocalTime(), + rule); } } diff --git a/Views/ProcessPowerPlanAssociationView.xaml b/Views/ProcessPowerPlanAssociationView.xaml index a25e145..0367ef6 100644 --- a/Views/ProcessPowerPlanAssociationView.xaml +++ b/Views/ProcessPowerPlanAssociationView.xaml @@ -289,7 +289,15 @@ Margin="0,0,0,10"/> - + + + + + + - + + + + + + + + + + + + + + + + + + + + + +