9a4baba19a
* feat: back up persistent rules and resolve rule precedence deterministically
- Configuration export now includes persistent process rules (schema 3.0),
stays compatible with 2.0 bundles, validates before writing, previews
what an import replaces and rolls back on failure.
- Matching rules apply broad-to-specific (name, wildcard path, exact path,
then most recently edited), shared by the engine and the process summary,
which now lists the apply order and flags conflicting values.
- Localized the new strings in all seven languages.
* feat: clearer process and rule editors
- Process details: CPU, memory and I/O priority pickers with an explicit
Apply, undo of the last manual priority change (guarded against reused
PIDs), adaptive side/bottom details panel.
- Manual process control stays available while automation is paused, with
a persistent notice instead of an overlay.
- Saved-rule editor stages all edits (including the core mask) and saves
them together, showing pending changes.
- Localized the new strings in all seven languages.
* fix: one save path for a saved rule's cores
The rules editor's core mask went through a new update path that reported
success without saving when no affinity payload was built, and kept a
legacy mask next to a CPU selection. Merge it with the old single-purpose
method (now unused), keep its checks, and localize the undo message.
* feat: per-process efficiency mode (EcoQoS) for live processes and rules
Closes #66.
- Native: SetProcessInformation/GetProcessInformation with
ProcessPowerThrottling (EXECUTION_SPEED), three states: Windows decides,
On (EcoQoS), Off (never throttle / HighQoS).
- Process tab: context menu entries, a picker with Apply in the details
panel, current state in the summary, undo of the last change, included
when saving current settings as a rule (only if explicitly set).
- Rules: EfficiencyMode + ApplyEfficiencyModeOnStart, applied by the rules
engine, editable in the saved-rule editor, validated on import and part
of conflict detection.
- The summary flags when the global Power Throttling tweak voids it. CPU
priority is left alone, unlike Task Manager's efficiency mode.
- Localized in all seven languages.
* chore: keep CRLF line endings in SelectedProcessSummaryViewModel
* feat: clearer navigation, process page and rules editor
- Navigation pane open with short labels instead of seven bare icons.
- Processes: one toolbar row (search with placeholder, Filters and
Columns menus, sort, refresh); details split into Process, Priority,
CPU cores and Rule cards; pickers start from the process's current
values and stay empty when a value cannot be read; help paragraphs
moved into tooltips; core picker always visible.
- Rules: process rules first, clearer tab names, localized choices in the
saved-rule editor instead of internal enum names.
- Shorter page titles and subtitles in all seven languages; removed the
strings this made unused.
No data format changes.
* feat: settings and tweaks as Windows 11 rows, localized rule list
- Settings: one column of rows (what it is on the left, its switch on the
right), most used sections first, Save as the primary action.
- Tweaks: one tweak per row with its status dot and switch.
- Rule list: 'Applies' and 'Mode' columns use the same localized labels as
the editor and refresh on language change.
- Removed 76 strings no code referenced, from all seven languages.
* fix: issues found testing the beta in a clean Windows 11 VM
- Process counter could show more visible processes than the total
('157 / 151'): the batch total was a snapshot from the first load.
- Narrow windows (or 150% scaling): toolbar buttons move under the search
box instead of squeezing it to a few letters.
- Rules list keeps the 'Applies' column readable when narrow.
- Settings status message gets its own line instead of being cut.
Tested in a Hyper-V Windows 11 VM: clean install, upgrade, uninstall,
light and dark theme, 100% and 150% scaling.
* feat: remember layout choices; Windows 11 toggles in Tweaks
- The navigation pane, window size/position/maximized state, and the
process list filters, sort and columns now survive a restart. They live
in ui-state.json, apart from settings.json, so they never mark the
Settings page as unsaved or travel in exported configurations. A corrupt
file falls back to defaults; tests write to a temp file.
- Fixes the pane re-opening on every start (it was hard-coded open).
- Tweaks use a native-looking Windows 11 switch (40x20 track, sliding
thumb) with On/Off written beside it.
- New test: every on/off setting survives save and reload.
* docs: handoff for the 1.7.7 PR stack and beta test
* fix: P/E cores from the highest EfficiencyClass, AMD CCDs from real L3 groups
The legacy topology treated the lowest EfficiencyClass as the performance
core, swapping P- and E-cores on hybrid Intel CPUs. AMD CCDs were guessed
as 8 cores each, which split 6+6 parts (7900X3D, 9900X3D) into 8+4; they now
come from the L3 groups Windows reports, with the guess kept only as a
fallback. The topology snapshot also keeps each L3 group's size.
* feat: Game Boost, CPU Sets for the game and selected background apps
While a detected game runs, Game Boost sets process default CPU Sets from
the CPU topology: on AMD X3D with one larger L3 the game goes to the V-Cache
CCD, on Intel hybrid CPUs to the P-cores, and selected background apps
(browsers, sync clients, updaters, launchers) to the other cores. On dual-CCD
parts with equal L3 only the background moves, unless Isolation mode also
keeps the game on CCD0. Single-L3 and unreadable topologies are left to
Windows. Above Normal priority for the game is optional; never High.
Each change is written to a journal before it is made and undone when the
game exits, Game Boost is turned off or ThreadPilot closes, and on the next
start after a crash. Only values still exactly as Game Boost set them are
restored, never one a user rule or a manual change has taken over since.
Persistent rules and Game Boost share one apply gate, and a rule always
wins over Game Boost for the setting it covers.
The switch, mode and lists are on the Tweaks page, off by default, and take
effect without a restart.
* fix: Game Boost background entries with a full path never matched
The background list compared full-path entries against an empty path, so
only bare process names worked. Found by a new integration test that runs
the real services on two copies of PING.EXE: CPU Sets and priority are set
and read back through Windows, removed when Game Boost is turned off, and
undone from the journal after a simulated crash. The topology is simulated
from this machine's CPU Set IDs, so the test also runs on CPUs where Game
Boost would not act; it skips itself below 8 cores.
* feat: report Game Boost sessions and restore results in Activity
* test: diagnose EcoQoS read failures on Windows Server
* chore: prepare 1.7.7-beta.2 and keep prereleases out of stable channels
* test: use native full-query access mask in EcoQoS diagnostic
* docs: update beta handoff and prerelease publication policy
* ci: run native EcoQoS tests on a Windows 11-era kernel
Windows Server 2022 build 20348 rejects GetProcessInformation(ProcessPowerThrottling) with ERROR_INVALID_PARAMETER (87), with both limited and full query handles. Windows 11 local tests pass. Use Server 2025 for CI/release tests and smoke testing; keep the real round-trip assertions, remove temporary probes.
* test: lock beta publication and native runner contracts
* chore: separate stable 1.7.7 from experimental Game Boost
Stable retains the validated EcoQoS/rules/UI stack. Preserve the complete local Game Boost implementation at ef2ec24 for the separate 1.7.8-beta.1 prerelease; no experimental Game Boost/topology changes ship in stable. Keep channel-aware publication and Windows 11-era native CI tests.
922 lines
38 KiB
C#
922 lines
38 KiB
C#
namespace ThreadPilot.ViewModels
|
|
{
|
|
using System;
|
|
using System.Collections.Generic;
|
|
using System.Collections.ObjectModel;
|
|
using System.IO;
|
|
using System.Linq;
|
|
using System.Threading.Tasks;
|
|
using System.Windows.Input;
|
|
using CommunityToolkit.Mvvm.ComponentModel;
|
|
using CommunityToolkit.Mvvm.Input;
|
|
using Microsoft.Extensions.Logging;
|
|
using Microsoft.Win32;
|
|
using ThreadPilot.Models;
|
|
using ThreadPilot.Services;
|
|
using ThreadPilot.ViewModels;
|
|
|
|
public partial class ProcessPowerPlanAssociationViewModel : BaseViewModel
|
|
{
|
|
private readonly IProcessPowerPlanAssociationService associationService;
|
|
private readonly IPowerPlanService powerPlanService;
|
|
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;
|
|
|
|
[ObservableProperty]
|
|
private ObservableCollection<ProcessPowerPlanAssociation> associations = new();
|
|
|
|
[ObservableProperty]
|
|
private ObservableCollection<PowerPlanModel> availablePowerPlans = new();
|
|
|
|
[ObservableProperty]
|
|
private ObservableCollection<CoreMask> availableCoreMasks = new();
|
|
|
|
[ObservableProperty]
|
|
private ObservableCollection<string> availablePriorities = new()
|
|
{
|
|
"Idle",
|
|
"BelowNormal",
|
|
"Normal",
|
|
"AboveNormal",
|
|
"High",
|
|
"RealTime",
|
|
};
|
|
|
|
[ObservableProperty]
|
|
private ObservableCollection<ProcessModel> runningProcesses = new();
|
|
|
|
[ObservableProperty]
|
|
private ProcessPowerPlanAssociation? selectedAssociation;
|
|
|
|
[ObservableProperty]
|
|
private PowerPlanModel? selectedPowerPlan;
|
|
|
|
[ObservableProperty]
|
|
private CoreMask? selectedCoreMask;
|
|
|
|
[ObservableProperty]
|
|
private string? selectedProcessPriority;
|
|
|
|
[ObservableProperty]
|
|
private ProcessModel? selectedProcess;
|
|
|
|
[ObservableProperty]
|
|
private string newExecutableName = string.Empty;
|
|
|
|
[ObservableProperty]
|
|
private string newExecutablePath = string.Empty;
|
|
|
|
// Properties for the selected executable (read-only display)
|
|
[ObservableProperty]
|
|
private string selectedExecutableDisplayName = "No executable selected";
|
|
|
|
[ObservableProperty]
|
|
private string selectedExecutableFullPath = string.Empty;
|
|
|
|
[ObservableProperty]
|
|
private bool hasSelectedExecutable = false;
|
|
|
|
[ObservableProperty]
|
|
private bool matchByPath = false;
|
|
|
|
[ObservableProperty]
|
|
private int priority = 0;
|
|
|
|
[ObservableProperty]
|
|
private string description = string.Empty;
|
|
|
|
[ObservableProperty]
|
|
private PowerPlanModel? defaultPowerPlan;
|
|
|
|
[ObservableProperty]
|
|
private bool preventDuplicatePowerPlanChanges = true;
|
|
|
|
[ObservableProperty]
|
|
private int powerPlanChangeDelayMs = 250;
|
|
|
|
[ObservableProperty]
|
|
private string serviceStatus = "Stopped";
|
|
|
|
[ObservableProperty]
|
|
private bool isServiceRunning = false;
|
|
|
|
public ProcessPowerPlanAssociationViewModel(
|
|
ILogger<ProcessPowerPlanAssociationViewModel> logger,
|
|
IProcessPowerPlanAssociationService associationService,
|
|
IPowerPlanService powerPlanService,
|
|
IProcessService processService,
|
|
IProcessMonitorManagerService monitorManagerService,
|
|
ICoreMaskService coreMaskService,
|
|
IEnhancedLoggingService? enhancedLoggingService = null,
|
|
ILocalizationService? localizationService = null,
|
|
IPersistentProcessRuleStore? persistentRuleStore = null,
|
|
IProcessRuleCreationService? ruleCreationService = null)
|
|
: base(logger, enhancedLoggingService)
|
|
{
|
|
this.associationService = associationService ?? throw new ArgumentNullException(nameof(associationService));
|
|
this.powerPlanService = powerPlanService ?? throw new ArgumentNullException(nameof(powerPlanService));
|
|
this.processService = processService ?? throw new ArgumentNullException(nameof(processService));
|
|
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;
|
|
|
|
if (localizationService != null)
|
|
{
|
|
localizationService.LanguageChanged += (_, _) =>
|
|
{
|
|
this.OnPropertyChanged(nameof(this.SavedRulePriorityOptions));
|
|
this.OnPropertyChanged(nameof(this.SavedRuleMemoryPriorityOptions));
|
|
this.OnPropertyChanged(nameof(this.SavedRuleIoPriorityOptions));
|
|
this.OnPropertyChanged(nameof(this.SavedRuleEfficiencyModeOptions));
|
|
this.OnPropertyChanged(nameof(this.SavedRuleCpuAssignmentModeOptions));
|
|
TaskSafety.FireAndForget(this.RefreshSavedProcessRulesAsync(), _ => { });
|
|
};
|
|
}
|
|
|
|
// Subscribe to events
|
|
this.associationService.ConfigurationChanged += this.OnConfigurationChanged;
|
|
this.monitorManagerService.ServiceStatusChanged += this.OnServiceStatusChanged;
|
|
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;
|
|
|
|
[ObservableProperty]
|
|
private string savedRulesReviewMessage = string.Empty;
|
|
|
|
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.Localize));
|
|
}
|
|
|
|
this.HasSavedProcessRules = this.SavedProcessRules.Count > 0;
|
|
|
|
var needingReview = this.ruleCreationService == null
|
|
? []
|
|
: await this.ruleCreationService.GetRulesNeedingTopologyReviewAsync().ConfigureAwait(true);
|
|
this.SavedRulesReviewMessage = needingReview.Count == 0
|
|
? string.Empty
|
|
: $"These rules pin cores from a different CPU than the one running now, so what they select may not mean what it did when they were saved: {string.Join(", ", needingReview)}. Set their cores again from a saved mask below.";
|
|
}
|
|
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);
|
|
}
|
|
|
|
// 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]
|
|
[NotifyPropertyChangedFor(nameof(HasPendingRuleChanges))]
|
|
private bool savedRuleIsEnabled = true;
|
|
|
|
[ObservableProperty]
|
|
[NotifyPropertyChangedFor(nameof(HasPendingRuleChanges))]
|
|
private bool savedRulePreventSleep;
|
|
|
|
[ObservableProperty]
|
|
[NotifyPropertyChangedFor(nameof(HasPendingRuleChanges))]
|
|
private string savedRulePriority = NoneOption;
|
|
|
|
[ObservableProperty]
|
|
[NotifyPropertyChangedFor(nameof(HasPendingRuleChanges))]
|
|
private string savedRuleMemoryPriority = NoneOption;
|
|
|
|
[ObservableProperty]
|
|
[NotifyPropertyChangedFor(nameof(HasPendingRuleChanges))]
|
|
private string savedRuleIoPriority = NoneOption;
|
|
|
|
[ObservableProperty]
|
|
[NotifyPropertyChangedFor(nameof(HasPendingRuleChanges))]
|
|
private string savedRuleEfficiencyMode = NoneOption;
|
|
|
|
[ObservableProperty]
|
|
[NotifyPropertyChangedFor(nameof(HasPendingRuleChanges))]
|
|
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.
|
|
// Values stay the enum names the editor already stores; only the labels are localized.
|
|
public IReadOnlyList<RuleOption> SavedRulePriorityOptions => this.Options(
|
|
"ProcessView_Priority",
|
|
[
|
|
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<RuleOption> SavedRuleMemoryPriorityOptions =>
|
|
this.Options("ProcessView_Priority", [NoneOption, .. Enum.GetNames<ProcessMemoryPriority>()]);
|
|
|
|
public IReadOnlyList<RuleOption> SavedRuleIoPriorityOptions =>
|
|
this.Options("ProcessView_Priority", [NoneOption, .. Enum.GetNames<ProcessIoPriority>()]);
|
|
|
|
public IReadOnlyList<RuleOption> SavedRuleEfficiencyModeOptions =>
|
|
this.Options("EfficiencyMode_", [NoneOption, .. Enum.GetNames<ProcessEfficiencyMode>()]);
|
|
|
|
public IReadOnlyList<RuleOption> SavedRuleCpuAssignmentModeOptions =>
|
|
this.Options("CpuAssignmentMode_", [.. Enum.GetNames<CpuAssignmentMode>()]);
|
|
|
|
private RuleOption[] Options(string labelPrefix, IReadOnlyList<string> values) =>
|
|
values.Select(value => new RuleOption(
|
|
value,
|
|
value == NoneOption ? this.Localize("Rules_NotSet", "Not set")
|
|
// Windows calls the Idle class "Low", as Task Manager does.
|
|
: value == nameof(System.Diagnostics.ProcessPriorityClass.Idle) ? this.Localize("ProcessView_PriorityLow", "Low")
|
|
: this.Localize(labelPrefix + value, value)))
|
|
.ToArray();
|
|
|
|
public sealed record RuleOption(string Value, string Label);
|
|
|
|
partial void OnSelectedSavedProcessRuleChanged(SavedProcessRule? value)
|
|
{
|
|
if (value == null)
|
|
{
|
|
return;
|
|
}
|
|
|
|
this.SavedRuleCoreMask = null;
|
|
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.SavedRuleEfficiencyMode = rule.EfficiencyMode?.ToString() ?? NoneOption;
|
|
this.SavedRuleCpuAssignmentMode = rule.CpuAssignmentMode.ToString();
|
|
}
|
|
|
|
// The cores of a rule can now be set without the process running: the Process tab needs a
|
|
// live process to hang its picker on, and a rule for a game you are not currently playing
|
|
// was the one thing you could not change. The vocabulary here is the saved CPU masks, which
|
|
// is what the Masks tab exists to define, rather than a second per-core picker.
|
|
[ObservableProperty]
|
|
[NotifyPropertyChangedFor(nameof(HasPendingRuleChanges))]
|
|
private CoreMask? savedRuleCoreMask;
|
|
|
|
public bool HasPendingRuleChanges => this.SelectedSavedProcessRule is { } selected &&
|
|
(this.SavedRuleCoreMask != null || this.SavedRuleIsEnabled != selected.Source.IsEnabled ||
|
|
this.SavedRulePreventSleep != selected.Source.PreventSystemSleepWhileRunning ||
|
|
this.SavedRulePriority != (selected.Source.Priority?.ToString() ?? NoneOption) ||
|
|
this.SavedRuleMemoryPriority != (selected.Source.MemoryPriority?.ToString() ?? NoneOption) ||
|
|
this.SavedRuleIoPriority != (selected.Source.IoPriority?.ToString() ?? NoneOption) ||
|
|
this.SavedRuleEfficiencyMode != (selected.Source.EfficiencyMode?.ToString() ?? NoneOption) ||
|
|
this.SavedRuleCpuAssignmentMode != selected.Source.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<System.Diagnostics.ProcessPriorityClass>(this.SavedRulePriority),
|
|
MemoryPriority = ParseOption<ProcessMemoryPriority>(this.SavedRuleMemoryPriority),
|
|
IoPriority = ParseOption<ProcessIoPriority>(this.SavedRuleIoPriority),
|
|
EfficiencyMode = ParseOption<ProcessEfficiencyMode>(this.SavedRuleEfficiencyMode),
|
|
CpuAssignmentMode = Enum.TryParse<CpuAssignmentMode>(this.SavedRuleCpuAssignmentMode, out var mode)
|
|
? mode
|
|
: selected.Source.CpuAssignmentMode,
|
|
};
|
|
|
|
var result = this.SavedRuleCoreMask == null
|
|
? await this.ruleCreationService.UpdateRuleAsync(updated).ConfigureAwait(true)
|
|
: await this.ruleCreationService.UpdateRuleWithCoreSelectionAsync(updated, this.SavedRuleCoreMask.BoolMask).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<T>(string? option)
|
|
where T : struct, Enum =>
|
|
string.IsNullOrWhiteSpace(option) || string.Equals(option, NoneOption, StringComparison.Ordinal)
|
|
? null
|
|
: Enum.TryParse<T>(option, out var parsed) ? parsed : null;
|
|
|
|
public sealed record SavedProcessRule(
|
|
string Id,
|
|
string ProcessName,
|
|
string Applies,
|
|
string Mode,
|
|
bool IsEnabled,
|
|
DateTime UpdatedAt,
|
|
string Cores,
|
|
PersistentProcessRule Source)
|
|
{
|
|
// text(key, fallback) resolves a localized string; the fallbacks keep the list readable without one.
|
|
public static SavedProcessRule From(PersistentProcessRule rule, Func<string, string, string> text)
|
|
{
|
|
string Level(object value) => value.ToString() == nameof(System.Diagnostics.ProcessPriorityClass.Idle)
|
|
? text("ProcessView_PriorityLow", "Low")
|
|
: text("ProcessView_Priority" + value, value.ToString()!);
|
|
|
|
var applies = new List<string>();
|
|
if (rule.ApplyAffinityOnStart)
|
|
{
|
|
applies.Add(text("ProcessView_CoresSection", "CPU cores"));
|
|
}
|
|
|
|
if (rule.ApplyPriorityOnStart && rule.Priority.HasValue)
|
|
{
|
|
applies.Add($"{text("ProcessView_RowCpu", "CPU")} {Level(rule.Priority.Value)}");
|
|
}
|
|
|
|
if (rule.ApplyMemoryPriorityOnStart && rule.MemoryPriority.HasValue)
|
|
{
|
|
applies.Add($"{text("ProcessView_RowMemory", "Memory")} {Level(rule.MemoryPriority.Value)}");
|
|
}
|
|
|
|
if (rule.ApplyIoPriorityOnStart && rule.IoPriority.HasValue)
|
|
{
|
|
applies.Add($"{text("ProcessView_RowIo", "I/O")} {Level(rule.IoPriority.Value)}");
|
|
}
|
|
|
|
if (rule.ApplyEfficiencyModeOnStart && rule.EfficiencyMode.HasValue)
|
|
{
|
|
applies.Add($"{text("ProcessView_RowEfficiency", "Efficiency")} {text("EfficiencyMode_" + rule.EfficiencyMode.Value, rule.EfficiencyMode.Value.ToString())}");
|
|
}
|
|
|
|
if (rule.PreventSystemSleepWhileRunning)
|
|
{
|
|
applies.Add(text("Rules_AppliesKeepAwake", "keeps the PC awake"));
|
|
}
|
|
|
|
return new SavedProcessRule(
|
|
rule.Id,
|
|
string.IsNullOrWhiteSpace(rule.ProcessName) ? text("Rules_Unnamed", "(unnamed)") : rule.ProcessName,
|
|
applies.Count == 0 ? text("Rules_AppliesNothing", "nothing") : string.Join(", ", applies),
|
|
rule.ApplyAffinityOnStart ? text("CpuAssignmentMode_" + rule.CpuAssignmentMode, rule.CpuAssignmentMode.ToString()) : "-",
|
|
rule.IsEnabled,
|
|
rule.UpdatedAt.ToLocalTime(),
|
|
DescribeCores(rule),
|
|
rule);
|
|
}
|
|
|
|
// "0-7, 16" reads better than a 64-bit mask or a list of every index.
|
|
private static string DescribeCores(PersistentProcessRule rule)
|
|
{
|
|
if (!rule.ApplyAffinityOnStart)
|
|
{
|
|
return "-";
|
|
}
|
|
|
|
IReadOnlyList<int>? indexes = rule.CpuSelection?.GlobalLogicalProcessorIndexes;
|
|
if (indexes == null || indexes.Count == 0)
|
|
{
|
|
if (!rule.LegacyAffinityMask.HasValue)
|
|
{
|
|
return "-";
|
|
}
|
|
|
|
var mask = unchecked((ulong)rule.LegacyAffinityMask.Value);
|
|
indexes = Enumerable.Range(0, 64).Where(bit => (mask & (1UL << bit)) != 0).ToList();
|
|
}
|
|
|
|
var ordered = indexes.Distinct().OrderBy(index => index).ToList();
|
|
if (ordered.Count == 0)
|
|
{
|
|
return "-";
|
|
}
|
|
|
|
var parts = new List<string>();
|
|
var start = ordered[0];
|
|
var previous = start;
|
|
foreach (var index in ordered.Skip(1))
|
|
{
|
|
if (index != previous + 1)
|
|
{
|
|
parts.Add(start == previous ? $"{start}" : $"{start}-{previous}");
|
|
start = index;
|
|
}
|
|
|
|
previous = index;
|
|
}
|
|
|
|
parts.Add(start == previous ? $"{start}" : $"{start}-{previous}");
|
|
return string.Join(", ", parts);
|
|
}
|
|
}
|
|
|
|
protected override void OnDispose()
|
|
{
|
|
this.associationService.ConfigurationChanged -= this.OnConfigurationChanged;
|
|
this.monitorManagerService.ServiceStatusChanged -= this.OnServiceStatusChanged;
|
|
this.monitorManagerService.ProcessPowerPlanChanged -= this.OnProcessPowerPlanChanged;
|
|
base.OnDispose();
|
|
}
|
|
|
|
public override async Task InitializeAsync()
|
|
{
|
|
if (this.isInitialized)
|
|
{
|
|
return;
|
|
}
|
|
|
|
this.isInitialized = true;
|
|
await this.LoadDataAsync();
|
|
await this.RefreshSavedProcessRulesAsync();
|
|
this.UpdateServiceStatus();
|
|
}
|
|
|
|
partial void OnSelectedAssociationChanged(ProcessPowerPlanAssociation? value)
|
|
{
|
|
if (value == null)
|
|
{
|
|
return;
|
|
}
|
|
|
|
PopulateEditorFromAssociation(value);
|
|
}
|
|
|
|
[RelayCommand]
|
|
public async Task LoadDataAsync()
|
|
{
|
|
try
|
|
{
|
|
this.SetStatus("Loading data...");
|
|
|
|
// Load associations
|
|
var associationsData = await this.associationService.GetAssociationsAsync();
|
|
this.Associations = new ObservableCollection<ProcessPowerPlanAssociation>(associationsData);
|
|
|
|
// Load power plans
|
|
var powerPlans = await this.powerPlanService.GetPowerPlansAsync();
|
|
this.AvailablePowerPlans = powerPlans;
|
|
|
|
// Load core masks
|
|
await this.coreMaskService.InitializeAsync();
|
|
this.AvailableCoreMasks = this.coreMaskService.AvailableMasks;
|
|
|
|
// Load running processes
|
|
var processes = await this.processService.GetProcessesAsync();
|
|
this.RunningProcesses = processes;
|
|
|
|
// Load configuration settings
|
|
var config = this.associationService.Configuration;
|
|
this.PreventDuplicatePowerPlanChanges = config.PreventDuplicatePowerPlanChanges;
|
|
this.PowerPlanChangeDelayMs = config.PowerPlanChangeDelayMs;
|
|
|
|
// Load default power plan
|
|
var (defaultGuid, defaultName) = await this.associationService.GetDefaultPowerPlanAsync();
|
|
this.DefaultPowerPlan = this.AvailablePowerPlans.FirstOrDefault(p => p.Guid == defaultGuid);
|
|
|
|
this.ClearStatus();
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
this.SetStatus($"Error loading data: {ex.Message}", false);
|
|
}
|
|
}
|
|
|
|
[RelayCommand]
|
|
public async Task AddAssociationAsync()
|
|
{
|
|
try
|
|
{
|
|
if (string.IsNullOrWhiteSpace(this.NewExecutableName) || this.SelectedPowerPlan == null)
|
|
{
|
|
this.SetStatus("Please select an executable and a power plan", false);
|
|
return;
|
|
}
|
|
|
|
this.SetStatus("Adding association...");
|
|
|
|
var association = new ProcessPowerPlanAssociation
|
|
{
|
|
ExecutableName = this.NewExecutableName.Trim(),
|
|
ExecutablePath = this.NewExecutablePath.Trim(),
|
|
PowerPlanGuid = this.SelectedPowerPlan.Guid,
|
|
PowerPlanName = this.SelectedPowerPlan.Name,
|
|
CoreMaskId = this.SelectedCoreMask?.Id,
|
|
CoreMaskName = this.SelectedCoreMask?.Name,
|
|
ProcessPriority = this.SelectedProcessPriority,
|
|
MatchByPath = this.MatchByPath,
|
|
Priority = this.Priority,
|
|
Description = this.Description.Trim(),
|
|
IsEnabled = true,
|
|
};
|
|
|
|
var success = await this.associationService.AddAssociationAsync(association);
|
|
if (success)
|
|
{
|
|
// Clear form
|
|
this.NewExecutableName = string.Empty;
|
|
this.NewExecutablePath = string.Empty;
|
|
this.SelectedPowerPlan = null;
|
|
this.SelectedCoreMask = null;
|
|
this.SelectedProcessPriority = null;
|
|
this.MatchByPath = false;
|
|
this.Priority = 0;
|
|
this.Description = string.Empty;
|
|
this.SelectedAssociation = null;
|
|
|
|
await this.LoadDataAsync();
|
|
this.SetStatus("Rule created and applied successfully.", false);
|
|
}
|
|
else
|
|
{
|
|
this.SetStatus("Failed to add rule - it may already exist", false);
|
|
}
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
this.SetStatus($"Error adding rule: {ex.Message}", false);
|
|
}
|
|
}
|
|
|
|
[RelayCommand]
|
|
public async Task UpdateAssociationAsync()
|
|
{
|
|
try
|
|
{
|
|
if (this.SelectedAssociation == null)
|
|
{
|
|
this.SetStatus("Please select a rule to update", false);
|
|
return;
|
|
}
|
|
|
|
if (string.IsNullOrWhiteSpace(this.NewExecutableName) || this.SelectedPowerPlan == null)
|
|
{
|
|
this.SetStatus("Executable and power plan are required", false);
|
|
return;
|
|
}
|
|
|
|
this.SetStatus("Updating rule...");
|
|
|
|
this.ApplyEditorToAssociation(this.SelectedAssociation);
|
|
|
|
var success = await this.associationService.UpdateAssociationAsync(this.SelectedAssociation);
|
|
if (success)
|
|
{
|
|
await this.LoadDataAsync();
|
|
this.SetStatus("Rule updated and applied successfully.", false);
|
|
}
|
|
else
|
|
{
|
|
this.SetStatus("Failed to update rule", false);
|
|
}
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
this.SetStatus($"Error updating rule: {ex.Message}", false);
|
|
}
|
|
}
|
|
|
|
[RelayCommand]
|
|
public async Task RemoveAssociationAsync()
|
|
{
|
|
try
|
|
{
|
|
if (this.SelectedAssociation == null)
|
|
{
|
|
this.SetStatus("Please select a rule to remove", false);
|
|
return;
|
|
}
|
|
|
|
this.SetStatus("Removing rule...");
|
|
|
|
var success = await this.associationService.RemoveAssociationAsync(this.SelectedAssociation.Id);
|
|
if (success)
|
|
{
|
|
this.SelectedAssociation = null;
|
|
await this.LoadDataAsync();
|
|
this.SetStatus("Rule removed successfully");
|
|
}
|
|
else
|
|
{
|
|
this.SetStatus("Failed to remove rule", false);
|
|
}
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
this.SetStatus($"Error removing rule: {ex.Message}", false);
|
|
}
|
|
}
|
|
|
|
[RelayCommand]
|
|
public async Task SetDefaultPowerPlanAsync()
|
|
{
|
|
try
|
|
{
|
|
if (this.DefaultPowerPlan == null)
|
|
{
|
|
this.SetStatus("Please select a default power plan", false);
|
|
return;
|
|
}
|
|
|
|
this.SetStatus("Setting default power plan...");
|
|
|
|
var success = await this.associationService.SetDefaultPowerPlanAsync(this.DefaultPowerPlan.Guid, this.DefaultPowerPlan.Name);
|
|
if (success)
|
|
{
|
|
this.SetStatus("Default power plan set successfully");
|
|
}
|
|
else
|
|
{
|
|
this.SetStatus("Failed to set default power plan", false);
|
|
}
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
this.SetStatus($"Error setting default power plan: {ex.Message}", false);
|
|
}
|
|
}
|
|
|
|
[RelayCommand]
|
|
public async Task StartMonitoringAsync()
|
|
{
|
|
try
|
|
{
|
|
this.SetStatus(this.Localize("AutomationMonitoring_StatusStarting", "Starting automation monitoring..."));
|
|
await this.monitorManagerService.SetAutomationMonitoringEnabledAsync(true);
|
|
this.SetStatus(this.Localize("AutomationMonitoring_StatusEnabled", "Automation monitoring enabled."), false);
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
this.SetStatus($"Error starting automation monitoring: {ex.Message}", false);
|
|
}
|
|
}
|
|
|
|
[RelayCommand]
|
|
public async Task StopMonitoringAsync()
|
|
{
|
|
try
|
|
{
|
|
if (new Views.MonitoringDisableDialog().ShowDialog() != true)
|
|
{
|
|
return;
|
|
}
|
|
|
|
this.SetStatus(this.Localize("AutomationMonitoring_StatusStopping", "Stopping automation monitoring..."));
|
|
await this.monitorManagerService.SetAutomationMonitoringEnabledAsync(false);
|
|
this.SetStatus(this.Localize("AutomationMonitoring_StatusDisabled", "Automation monitoring disabled."), false);
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
this.SetStatus($"Error stopping automation monitoring: {ex.Message}", false);
|
|
}
|
|
}
|
|
|
|
[RelayCommand]
|
|
public async Task SaveConfigurationAsync()
|
|
{
|
|
try
|
|
{
|
|
this.SetStatus("Saving configuration...");
|
|
|
|
// Update configuration with current settings
|
|
var config = this.associationService.Configuration;
|
|
config.PreventDuplicatePowerPlanChanges = this.PreventDuplicatePowerPlanChanges;
|
|
config.PowerPlanChangeDelayMs = this.PowerPlanChangeDelayMs;
|
|
|
|
var success = await this.associationService.SaveConfigurationAsync();
|
|
if (success)
|
|
{
|
|
this.SetStatus("Configuration saved and active.", false);
|
|
}
|
|
else
|
|
{
|
|
this.SetStatus("Failed to save configuration", false);
|
|
}
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
this.SetStatus($"Error saving configuration: {ex.Message}", false);
|
|
}
|
|
}
|
|
|
|
[RelayCommand]
|
|
public void UseSelectedProcessForAssociation()
|
|
{
|
|
if (this.SelectedProcess != null)
|
|
{
|
|
this.NewExecutableName = this.SelectedProcess.Name;
|
|
this.NewExecutablePath = this.SelectedProcess.ExecutablePath;
|
|
|
|
// Update the selected executable display
|
|
this.UpdateSelectedExecutableDisplay(this.SelectedProcess.ExecutablePath, this.SelectedProcess.Name);
|
|
}
|
|
}
|
|
|
|
[RelayCommand]
|
|
public void BrowseExecutable()
|
|
{
|
|
try
|
|
{
|
|
var openFileDialog = new Microsoft.Win32.OpenFileDialog
|
|
{
|
|
Title = "Select Executable File",
|
|
Filter = "Executable Files (*.exe)|*.exe|All Files (*.*)|*.*",
|
|
FilterIndex = 1,
|
|
CheckFileExists = true,
|
|
CheckPathExists = true,
|
|
Multiselect = false,
|
|
};
|
|
|
|
if (openFileDialog.ShowDialog() == true)
|
|
{
|
|
var selectedFilePath = openFileDialog.FileName;
|
|
|
|
// Validate that it's an executable file
|
|
if (!this.IsValidExecutable(selectedFilePath))
|
|
{
|
|
this.SetStatus("Selected file is not a valid executable", false);
|
|
return;
|
|
}
|
|
|
|
// Extract executable name from the full path
|
|
var executableName = Path.GetFileName(selectedFilePath);
|
|
|
|
// Auto-populate the fields
|
|
this.NewExecutableName = executableName;
|
|
this.NewExecutablePath = selectedFilePath;
|
|
|
|
// Update the display
|
|
this.UpdateSelectedExecutableDisplay(selectedFilePath, executableName);
|
|
|
|
this.SetStatus($"Selected executable: {executableName}");
|
|
}
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
this.SetStatus($"Error selecting executable: {ex.Message}", false);
|
|
}
|
|
}
|
|
|
|
[RelayCommand]
|
|
public void ClearSelectedExecutable()
|
|
{
|
|
this.NewExecutableName = string.Empty;
|
|
this.NewExecutablePath = string.Empty;
|
|
this.SelectedExecutableDisplayName = "No executable selected";
|
|
this.SelectedExecutableFullPath = string.Empty;
|
|
this.HasSelectedExecutable = false;
|
|
this.SetStatus("Executable selection cleared");
|
|
}
|
|
|
|
private void OnConfigurationChanged(object? sender, ConfigurationChangedEventArgs e)
|
|
{
|
|
if (this.isInitialized)
|
|
{
|
|
_ = System.Windows.Application.Current.Dispatcher.InvokeAsync(async () => await this.LoadDataAsync());
|
|
}
|
|
}
|
|
|
|
private void OnServiceStatusChanged(object? sender, ServiceStatusEventArgs e)
|
|
{
|
|
// Marshal UI updates to the UI thread to prevent cross-thread access exceptions
|
|
System.Windows.Application.Current.Dispatcher.InvokeAsync(() =>
|
|
{
|
|
this.ServiceStatus = e.Status;
|
|
this.IsServiceRunning = e.IsRunning;
|
|
});
|
|
}
|
|
|
|
private bool IsValidExecutable(string filePath)
|
|
{
|
|
try
|
|
{
|
|
if (string.IsNullOrWhiteSpace(filePath) || !File.Exists(filePath))
|
|
{
|
|
return false;
|
|
}
|
|
|
|
var extension = Path.GetExtension(filePath);
|
|
return string.Equals(extension, ".exe", StringComparison.OrdinalIgnoreCase);
|
|
}
|
|
catch
|
|
{
|
|
return false;
|
|
}
|
|
}
|
|
|
|
private void UpdateSelectedExecutableDisplay(string fullPath, string executableName)
|
|
{
|
|
if (string.IsNullOrWhiteSpace(fullPath))
|
|
{
|
|
this.SelectedExecutableDisplayName = "No executable selected";
|
|
this.SelectedExecutableFullPath = string.Empty;
|
|
this.HasSelectedExecutable = false;
|
|
}
|
|
else
|
|
{
|
|
this.SelectedExecutableDisplayName = executableName;
|
|
this.SelectedExecutableFullPath = fullPath;
|
|
this.HasSelectedExecutable = true;
|
|
}
|
|
}
|
|
|
|
private void PopulateEditorFromAssociation(ProcessPowerPlanAssociation association)
|
|
{
|
|
this.NewExecutableName = association.ExecutableName ?? string.Empty;
|
|
this.NewExecutablePath = association.ExecutablePath ?? string.Empty;
|
|
this.MatchByPath = association.MatchByPath;
|
|
this.Priority = association.Priority;
|
|
this.Description = association.Description ?? string.Empty;
|
|
this.SelectedProcessPriority = association.ProcessPriority;
|
|
|
|
this.SelectedPowerPlan = this.AvailablePowerPlans.FirstOrDefault(p =>
|
|
string.Equals(p.Guid, association.PowerPlanGuid, StringComparison.OrdinalIgnoreCase));
|
|
|
|
this.SelectedCoreMask = this.AvailableCoreMasks.FirstOrDefault(m =>
|
|
string.Equals(m.Id, association.CoreMaskId, StringComparison.Ordinal));
|
|
|
|
this.UpdateSelectedExecutableDisplay(
|
|
this.NewExecutablePath,
|
|
string.IsNullOrWhiteSpace(this.NewExecutableName)
|
|
? Path.GetFileName(this.NewExecutablePath)
|
|
: this.NewExecutableName);
|
|
}
|
|
|
|
private void ApplyEditorToAssociation(ProcessPowerPlanAssociation association)
|
|
{
|
|
association.ExecutableName = this.NewExecutableName.Trim();
|
|
association.ExecutablePath = this.NewExecutablePath.Trim();
|
|
association.MatchByPath = this.MatchByPath;
|
|
association.Priority = this.Priority;
|
|
association.Description = this.Description.Trim();
|
|
association.ProcessPriority = this.SelectedProcessPriority;
|
|
association.PowerPlanGuid = this.SelectedPowerPlan?.Guid ?? string.Empty;
|
|
association.PowerPlanName = this.SelectedPowerPlan?.Name ?? string.Empty;
|
|
association.CoreMaskId = this.SelectedCoreMask?.Id;
|
|
association.CoreMaskName = this.SelectedCoreMask?.Name;
|
|
association.UpdatedAt = DateTime.UtcNow;
|
|
}
|
|
|
|
private void OnProcessPowerPlanChanged(object? sender, ProcessPowerPlanChangeEventArgs e)
|
|
{
|
|
// Marshal UI updates to the UI thread to prevent cross-thread access exceptions
|
|
System.Windows.Application.Current.Dispatcher.InvokeAsync(() =>
|
|
{
|
|
// Update status when power plan changes occur
|
|
this.SetStatus($"Power plan changed: {e.NewPowerPlan?.Name} for {e.Process.Name}", false);
|
|
});
|
|
}
|
|
|
|
// GetString echoes the key when it is missing, so treat that as "no translation".
|
|
private string Localize(string key, string fallback) =>
|
|
this.localizationService?.GetString(key) is { Length: > 0 } text && text != key ? text : fallback;
|
|
|
|
private void UpdateServiceStatus()
|
|
{
|
|
this.ServiceStatus = this.monitorManagerService.Status;
|
|
this.IsServiceRunning = this.monitorManagerService.IsRunning;
|
|
}
|
|
}
|
|
}
|
|
|