Refactor repo with ponytail cleanup (#31)
This commit is contained in:
+469
-497
@@ -1,497 +1,469 @@
|
||||
/*
|
||||
* ThreadPilot - Advanced Windows Process and Power Plan Manager
|
||||
* Copyright (C) 2025 Prime Build
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published by
|
||||
* the Free Software Foundation, version 3 only.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
#if DEBUG
|
||||
using ThreadPilot.Tests;
|
||||
#endif
|
||||
using ThreadPilot.Services;
|
||||
using ThreadPilot.ViewModels;
|
||||
|
||||
namespace ThreadPilot
|
||||
{
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using System.Windows;
|
||||
using System.Windows.Threading;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using ThreadPilot.Helpers;
|
||||
using ThreadPilot.Models;
|
||||
|
||||
public partial class App : System.Windows.Application
|
||||
{
|
||||
private const string RegisterLaunchTaskArgument = "--register-launch-task";
|
||||
private const string LaunchedViaTaskArgument = "--launched-via-task";
|
||||
|
||||
private Mutex? singleInstanceMutex;
|
||||
private int uiExceptionDialogOpen;
|
||||
private DateTime lastUiExceptionDialogUtc = DateTime.MinValue;
|
||||
|
||||
public IServiceProvider ServiceProvider { get; private set; }
|
||||
|
||||
public App()
|
||||
{
|
||||
ServiceCollection services = new ServiceCollection();
|
||||
|
||||
// Use the new centralized service configuration
|
||||
services.ConfigureApplicationServices();
|
||||
|
||||
this.ServiceProvider = services.BuildServiceProvider();
|
||||
|
||||
// Validate service configuration
|
||||
ServiceConfiguration.ValidateServiceConfiguration(this.ServiceProvider);
|
||||
}
|
||||
|
||||
|
||||
|
||||
protected override void OnStartup(StartupEventArgs e)
|
||||
{
|
||||
// Parse command line arguments early so special startup modes can short-circuit normal flow.
|
||||
var startupMode = StartupMode.Parse(e.Args);
|
||||
bool effectiveStartMinimized = false;
|
||||
ApplicationSettingsModel? loadedSettings = null;
|
||||
|
||||
effectiveStartMinimized = startupMode.StartMinimized;
|
||||
|
||||
if (startupMode.IsSmokeTest)
|
||||
{
|
||||
var smokeLogger = this.ServiceProvider.GetRequiredService<ILogger<App>>();
|
||||
var smokeTestResult = this.RunSmokeTestWithTimeout(smokeLogger, TimeSpan.FromSeconds(10));
|
||||
Environment.ExitCode = smokeTestResult;
|
||||
this.Shutdown(smokeTestResult);
|
||||
Environment.Exit(smokeTestResult);
|
||||
return;
|
||||
}
|
||||
|
||||
// Set up global exception handlers first
|
||||
AppDomain.CurrentDomain.UnhandledException += this.OnUnhandledException;
|
||||
this.DispatcherUnhandledException += this.OnDispatcherUnhandledException;
|
||||
TaskScheduler.UnobservedTaskException += this.OnUnobservedTaskException;
|
||||
|
||||
// Check elevation status first
|
||||
var elevationService = this.ServiceProvider.GetRequiredService<IElevationService>();
|
||||
var elevatedTaskService = this.ServiceProvider.GetRequiredService<IElevatedTaskService>();
|
||||
var logger = this.ServiceProvider.GetRequiredService<ILogger<App>>();
|
||||
var isRunningAsAdministrator = elevationService.IsRunningAsAdministrator();
|
||||
|
||||
if (isRunningAsAdministrator)
|
||||
{
|
||||
logger.LogInformation("Application is running with administrator privileges");
|
||||
|
||||
var launchTaskEnsured = Task.Run(async () => await elevatedTaskService.EnsureLaunchTaskAsync()).GetAwaiter().GetResult();
|
||||
if (!launchTaskEnsured)
|
||||
{
|
||||
logger.LogWarning("Failed to ensure managed elevated launch task during startup. Future launches may require one-time elevation again.");
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
if (startupMode.LaunchedViaTask)
|
||||
{
|
||||
logger.LogError("Application was launched via managed task marker but is still not elevated.");
|
||||
}
|
||||
#if DEBUG
|
||||
else if (!startupMode.IsTestMode)
|
||||
#else
|
||||
else
|
||||
#endif
|
||||
{
|
||||
var launchedElevatedInstance = Task.Run(async () => await elevatedTaskService.TryRunLaunchTaskAsync()).GetAwaiter().GetResult();
|
||||
if (launchedElevatedInstance)
|
||||
{
|
||||
logger.LogInformation("Managed elevated launch task started successfully. Exiting current non-elevated instance.");
|
||||
this.Shutdown();
|
||||
return;
|
||||
}
|
||||
|
||||
if (!startupMode.RegisterLaunchTask)
|
||||
{
|
||||
logger.LogInformation("Managed elevated launch task is unavailable. Requesting one-time elevation to bootstrap persistent launch.");
|
||||
var restartInitiated = Task.Run(async () => await elevationService.RestartWithElevation(new[] { RegisterLaunchTaskArgument })).GetAwaiter().GetResult();
|
||||
if (restartInitiated)
|
||||
{
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#if DEBUG
|
||||
if (!startupMode.IsTestMode)
|
||||
#else
|
||||
if (true)
|
||||
#endif
|
||||
{
|
||||
logger.LogError("ThreadPilot requires administrator privileges and cannot continue without elevation.");
|
||||
this.ShowElevationRequiredMessage();
|
||||
this.Shutdown(1);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// Enforce single-instance after elevation bootstrap logic to avoid mutex races during handoff.
|
||||
bool createdNew;
|
||||
this.singleInstanceMutex = new Mutex(initiallyOwned: true, name: "Global\\ThreadPilot_SingleInstance", createdNew: out createdNew);
|
||||
if (!createdNew)
|
||||
{
|
||||
System.Windows.MessageBox.Show(
|
||||
"ThreadPilot is already running.",
|
||||
"Instance already open",
|
||||
MessageBoxButton.OK,
|
||||
MessageBoxImage.Information);
|
||||
|
||||
this.Shutdown();
|
||||
return;
|
||||
}
|
||||
|
||||
base.OnStartup(e);
|
||||
|
||||
// Check for test mode
|
||||
#if DEBUG
|
||||
if (startupMode.IsTestMode)
|
||||
{
|
||||
// Run in console test mode
|
||||
AllocConsole();
|
||||
_ = Task.Run(async () =>
|
||||
{
|
||||
await TestRunner.RunTests();
|
||||
this.Dispatcher.Invoke(() => this.Shutdown());
|
||||
});
|
||||
return;
|
||||
}
|
||||
#endif
|
||||
|
||||
try
|
||||
{
|
||||
var settingsService = this.ServiceProvider.GetRequiredService<IApplicationSettingsService>();
|
||||
var themeService = this.ServiceProvider.GetRequiredService<IThemeService>();
|
||||
var localizationService = this.ServiceProvider.GetRequiredService<ILocalizationService>();
|
||||
|
||||
Task.Run(async () => await settingsService.LoadSettingsAsync()).GetAwaiter().GetResult();
|
||||
var settings = settingsService.Settings;
|
||||
loadedSettings = settings;
|
||||
localizationService.ApplyLanguage(settings.Language);
|
||||
effectiveStartMinimized = startupMode.StartMinimized || settings.StartMinimized;
|
||||
var useDarkTheme = settings.HasUserThemePreference
|
||||
? settings.UseDarkTheme
|
||||
: themeService.GetSystemUsesDarkTheme();
|
||||
|
||||
if (!settings.HasUserThemePreference && settings.UseDarkTheme != useDarkTheme)
|
||||
{
|
||||
settings.UseDarkTheme = useDarkTheme;
|
||||
Task.Run(async () => await settingsService.UpdateSettingsAsync(settings)).GetAwaiter().GetResult();
|
||||
}
|
||||
|
||||
themeService.ApplyTheme(useDarkTheme);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.LogWarning(ex, "Failed to preload theme settings during startup");
|
||||
}
|
||||
|
||||
var mainWindow = this.ServiceProvider.GetRequiredService<MainWindow>();
|
||||
this.MainWindow = mainWindow;
|
||||
|
||||
// Handle startup behavior with comprehensive error handling
|
||||
try
|
||||
{
|
||||
logger.LogInformation("Attempting to show main window...");
|
||||
|
||||
// Ensure the window is properly initialized
|
||||
if (mainWindow == null)
|
||||
{
|
||||
throw new InvalidOperationException("MainWindow could not be created");
|
||||
}
|
||||
|
||||
var startupWindowBehavior = StartupWindowBehavior.Resolve(startupMode.IsAutostart, effectiveStartMinimized);
|
||||
var showStartupSuggestion = loadedSettings != null
|
||||
&& StartupMinimizedSuggestionPolicy.ShouldShow(loadedSettings, startupWindowBehavior);
|
||||
mainWindow.ConfigureStartupMode(
|
||||
isSilentStartupMode: !startupWindowBehavior.ShouldShowWindow,
|
||||
showStartupMinimizedSuggestionOnReady: showStartupSuggestion);
|
||||
|
||||
mainWindow.ShowInTaskbar = startupWindowBehavior.ShowInTaskbar;
|
||||
mainWindow.Visibility = startupWindowBehavior.Visibility;
|
||||
mainWindow.WindowState = startupWindowBehavior.WindowState;
|
||||
|
||||
if (startupWindowBehavior.ShouldShowWindow)
|
||||
{
|
||||
mainWindow.Show();
|
||||
|
||||
if (startupWindowBehavior.HideAfterShow)
|
||||
{
|
||||
mainWindow.Hide();
|
||||
}
|
||||
else if (startupWindowBehavior.ActivateAfterShow)
|
||||
{
|
||||
mainWindow.EnsureDashboardVisibleOnScreen();
|
||||
mainWindow.Activate();
|
||||
}
|
||||
}
|
||||
|
||||
logger.LogInformation("Startup window behavior applied successfully");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.LogError(ex, "Critical error during application startup");
|
||||
|
||||
// Show error message and exit gracefully
|
||||
var errorMessage = $"ThreadPilot failed to start:\n\n{ex.Message}\n\nStack Trace:\n{ex.StackTrace}";
|
||||
System.Windows.MessageBox.Show(errorMessage, "ThreadPilot Startup Error",
|
||||
MessageBoxButton.OK, MessageBoxImage.Error);
|
||||
|
||||
// Exit the application
|
||||
this.Shutdown(1);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
private int RunSmokeTestWithTimeout(ILogger logger, TimeSpan timeout)
|
||||
{
|
||||
var smokeTestTask = Task.Run(() => this.RunSmokeTest(logger));
|
||||
if (smokeTestTask.Wait(timeout))
|
||||
{
|
||||
return smokeTestTask.GetAwaiter().GetResult();
|
||||
}
|
||||
|
||||
logger.LogError("ThreadPilot smoke test timed out after {TimeoutSeconds} seconds", timeout.TotalSeconds);
|
||||
return 2;
|
||||
}
|
||||
|
||||
private int RunSmokeTest(ILogger logger)
|
||||
{
|
||||
try
|
||||
{
|
||||
logger.LogInformation("Starting ThreadPilot smoke test");
|
||||
|
||||
_ = this.ServiceProvider.GetRequiredService<ILoggerFactory>();
|
||||
_ = this.ServiceProvider.GetRequiredService<IApplicationSettingsService>();
|
||||
_ = this.ServiceProvider.GetRequiredService<IThemeService>();
|
||||
_ = this.ServiceProvider.GetRequiredService<ILocalizationService>();
|
||||
|
||||
if (!System.IO.Directory.Exists(AppContext.BaseDirectory))
|
||||
{
|
||||
throw new InvalidOperationException("Application base directory was not found.");
|
||||
}
|
||||
|
||||
logger.LogInformation("ThreadPilot smoke test completed successfully");
|
||||
return 0;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.LogError(ex, "ThreadPilot smoke test failed");
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
|
||||
private readonly struct StartupMode
|
||||
{
|
||||
public bool StartMinimized { get; init; }
|
||||
|
||||
public bool IsAutostart { get; init; }
|
||||
|
||||
public bool IsSmokeTest { get; init; }
|
||||
|
||||
public bool RegisterLaunchTask { get; init; }
|
||||
|
||||
public bool LaunchedViaTask { get; init; }
|
||||
|
||||
public bool IsTestMode { get; init; }
|
||||
|
||||
public static StartupMode Parse(IEnumerable<string> args)
|
||||
{
|
||||
var mode = default(StartupMode);
|
||||
foreach (var arg in args)
|
||||
{
|
||||
switch (arg.ToLowerInvariant())
|
||||
{
|
||||
case "--test":
|
||||
mode = mode with { IsTestMode = true };
|
||||
break;
|
||||
case "--smoke-test":
|
||||
mode = mode with { IsSmokeTest = true };
|
||||
break;
|
||||
case "--start-minimized":
|
||||
mode = mode with { StartMinimized = true };
|
||||
break;
|
||||
case "--autostart":
|
||||
mode = mode with { IsAutostart = true };
|
||||
break;
|
||||
case "--startup":
|
||||
mode = mode with { IsAutostart = true, StartMinimized = true };
|
||||
break;
|
||||
case RegisterLaunchTaskArgument:
|
||||
mode = mode with { RegisterLaunchTask = true };
|
||||
break;
|
||||
case LaunchedViaTaskArgument:
|
||||
mode = mode with { LaunchedViaTask = true };
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return mode;
|
||||
}
|
||||
}
|
||||
|
||||
protected override void OnExit(ExitEventArgs e)
|
||||
{
|
||||
AppDomain.CurrentDomain.UnhandledException -= this.OnUnhandledException;
|
||||
this.DispatcherUnhandledException -= this.OnDispatcherUnhandledException;
|
||||
TaskScheduler.UnobservedTaskException -= this.OnUnobservedTaskException;
|
||||
|
||||
if (this.singleInstanceMutex != null)
|
||||
{
|
||||
try
|
||||
{
|
||||
this.singleInstanceMutex.ReleaseMutex();
|
||||
}
|
||||
catch
|
||||
{
|
||||
// Ignore; we just want to clean up quietly
|
||||
}
|
||||
this.singleInstanceMutex.Dispose();
|
||||
this.singleInstanceMutex = null;
|
||||
}
|
||||
|
||||
base.OnExit(e);
|
||||
}
|
||||
|
||||
#if DEBUG
|
||||
[System.Runtime.InteropServices.DllImport("kernel32.dll")]
|
||||
private static extern bool AllocConsole();
|
||||
#endif
|
||||
|
||||
/// <summary>
|
||||
/// Shows a message to the user about elevation requirements.
|
||||
/// </summary>
|
||||
private void ShowElevationRequiredMessage()
|
||||
{
|
||||
// Don't show the message during autostart to avoid interrupting the user
|
||||
var args = Environment.GetCommandLineArgs();
|
||||
if (args.Any(arg => arg.Equals("--autostart", StringComparison.OrdinalIgnoreCase) ||
|
||||
arg.Equals("--startup", StringComparison.OrdinalIgnoreCase)))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
System.Windows.MessageBox.Show(
|
||||
"ThreadPilot requires administrator privileges to start.\n\n" +
|
||||
"Please relaunch the application and approve the UAC prompt.\n\n" +
|
||||
"This instance will now close.",
|
||||
"Administrator Privileges Required",
|
||||
MessageBoxButton.OK,
|
||||
MessageBoxImage.Warning);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Handles unhandled exceptions in the application domain.
|
||||
/// </summary>
|
||||
private void OnUnhandledException(object sender, UnhandledExceptionEventArgs e)
|
||||
{
|
||||
var exception = e.ExceptionObject as Exception ?? new InvalidOperationException("Unhandled non-Exception object was raised.");
|
||||
this.ReportUnhandledException(exception, "AppDomain.CurrentDomain.UnhandledException", LogLevel.Critical);
|
||||
|
||||
var errorMessage = $"A critical error occurred:\n\n{exception?.Message}\n\nThe application will now exit.";
|
||||
System.Windows.MessageBox.Show(errorMessage, "Critical Error",
|
||||
MessageBoxButton.OK, MessageBoxImage.Error);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Handles unhandled exceptions on the UI thread.
|
||||
/// </summary>
|
||||
private void OnDispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
|
||||
{
|
||||
this.ReportUnhandledException(e.Exception, "Application.DispatcherUnhandledException", LogLevel.Error);
|
||||
|
||||
if (Interlocked.CompareExchange(ref this.uiExceptionDialogOpen, 1, 0) != 0)
|
||||
{
|
||||
e.Handled = true;
|
||||
return;
|
||||
}
|
||||
|
||||
if (DateTime.UtcNow - this.lastUiExceptionDialogUtc < TimeSpan.FromSeconds(2))
|
||||
{
|
||||
e.Handled = true;
|
||||
Interlocked.Exchange(ref this.uiExceptionDialogOpen, 0);
|
||||
return;
|
||||
}
|
||||
|
||||
this.lastUiExceptionDialogUtc = DateTime.UtcNow;
|
||||
|
||||
var errorMessage = $"An error occurred in the user interface:\n\n{e.Exception.Message}\n\nDo you want to continue?";
|
||||
var result = System.Windows.MessageBox.Show(errorMessage, "UI Error",
|
||||
MessageBoxButton.YesNo, MessageBoxImage.Error);
|
||||
|
||||
if (result == MessageBoxResult.Yes)
|
||||
{
|
||||
e.Handled = true; // Continue running
|
||||
}
|
||||
else
|
||||
{
|
||||
e.Handled = false; // Let the application crash
|
||||
}
|
||||
|
||||
Interlocked.Exchange(ref this.uiExceptionDialogOpen, 0);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Handles unobserved task exceptions from fire-and-forget tasks that escaped local handlers.
|
||||
/// </summary>
|
||||
private void OnUnobservedTaskException(object? sender, UnobservedTaskExceptionEventArgs e)
|
||||
{
|
||||
var exception = e.Exception.Flatten();
|
||||
this.ReportUnhandledException(exception, "TaskScheduler.UnobservedTaskException", LogLevel.Error);
|
||||
e.SetObserved();
|
||||
}
|
||||
|
||||
private void ReportUnhandledException(Exception exception, string source, LogLevel level)
|
||||
{
|
||||
var logger = this.ServiceProvider?.GetService<ILogger<App>>();
|
||||
if (level == LogLevel.Critical)
|
||||
{
|
||||
logger?.LogCritical(exception, "Unhandled exception in {Source}", source);
|
||||
}
|
||||
else
|
||||
{
|
||||
logger?.LogError(exception, "Unhandled exception in {Source}", source);
|
||||
}
|
||||
|
||||
var enhancedLogger = this.ServiceProvider?.GetService<IEnhancedLoggingService>();
|
||||
if (enhancedLogger == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var errorCode = exception is ThreadPilotException typedException
|
||||
? typedException.ErrorCode.ToString()
|
||||
: ErrorCode.Unhandled.ToString();
|
||||
|
||||
var context = new Dictionary<string, object>
|
||||
{
|
||||
["Source"] = source,
|
||||
[LogProperties.ErrorCode] = errorCode,
|
||||
[LogProperties.CorrelationId] = enhancedLogger.GetCurrentCorrelationId() ?? "N/A",
|
||||
["IsTerminatingLevel"] = level == LogLevel.Critical,
|
||||
};
|
||||
|
||||
TaskSafety.FireAndForget(
|
||||
enhancedLogger.LogErrorAsync(exception, source, context),
|
||||
logFailure => logger?.LogWarning(logFailure, "Failed to persist unhandled exception report"));
|
||||
}
|
||||
}
|
||||
}
|
||||
#if DEBUG
|
||||
using ThreadPilot.Tests;
|
||||
#endif
|
||||
using ThreadPilot.Services;
|
||||
using ThreadPilot.ViewModels;
|
||||
|
||||
namespace ThreadPilot
|
||||
{
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using System.Windows;
|
||||
using System.Windows.Threading;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using ThreadPilot.Helpers;
|
||||
using ThreadPilot.Models;
|
||||
|
||||
public partial class App : System.Windows.Application
|
||||
{
|
||||
private const string RegisterLaunchTaskArgument = "--register-launch-task";
|
||||
private const string LaunchedViaTaskArgument = "--launched-via-task";
|
||||
|
||||
private Mutex? singleInstanceMutex;
|
||||
private int uiExceptionDialogOpen;
|
||||
private DateTime lastUiExceptionDialogUtc = DateTime.MinValue;
|
||||
|
||||
public IServiceProvider ServiceProvider { get; private set; }
|
||||
|
||||
public App()
|
||||
{
|
||||
ServiceCollection services = new ServiceCollection();
|
||||
|
||||
// Use the new centralized service configuration
|
||||
services.ConfigureApplicationServices();
|
||||
|
||||
this.ServiceProvider = services.BuildServiceProvider();
|
||||
|
||||
// Validate service configuration
|
||||
ServiceConfiguration.ValidateServiceConfiguration(this.ServiceProvider);
|
||||
}
|
||||
|
||||
|
||||
|
||||
protected override void OnStartup(StartupEventArgs e)
|
||||
{
|
||||
// Parse command line arguments early so special startup modes can short-circuit normal flow.
|
||||
var startupMode = StartupMode.Parse(e.Args);
|
||||
bool effectiveStartMinimized = false;
|
||||
ApplicationSettingsModel? loadedSettings = null;
|
||||
|
||||
effectiveStartMinimized = startupMode.StartMinimized;
|
||||
|
||||
if (startupMode.IsSmokeTest)
|
||||
{
|
||||
var smokeLogger = this.ServiceProvider.GetRequiredService<ILogger<App>>();
|
||||
var smokeTestResult = this.RunSmokeTestWithTimeout(smokeLogger, TimeSpan.FromSeconds(10));
|
||||
Environment.ExitCode = smokeTestResult;
|
||||
this.Shutdown(smokeTestResult);
|
||||
Environment.Exit(smokeTestResult);
|
||||
return;
|
||||
}
|
||||
|
||||
// Set up global exception handlers first
|
||||
AppDomain.CurrentDomain.UnhandledException += this.OnUnhandledException;
|
||||
this.DispatcherUnhandledException += this.OnDispatcherUnhandledException;
|
||||
TaskScheduler.UnobservedTaskException += this.OnUnobservedTaskException;
|
||||
|
||||
// Check elevation status first
|
||||
var elevationService = this.ServiceProvider.GetRequiredService<IElevationService>();
|
||||
var elevatedTaskService = this.ServiceProvider.GetRequiredService<IElevatedTaskService>();
|
||||
var logger = this.ServiceProvider.GetRequiredService<ILogger<App>>();
|
||||
var isRunningAsAdministrator = elevationService.IsRunningAsAdministrator();
|
||||
|
||||
if (isRunningAsAdministrator)
|
||||
{
|
||||
logger.LogInformation("Application is running with administrator privileges");
|
||||
|
||||
var launchTaskEnsured = Task.Run(async () => await elevatedTaskService.EnsureLaunchTaskAsync()).GetAwaiter().GetResult();
|
||||
if (!launchTaskEnsured)
|
||||
{
|
||||
logger.LogWarning("Failed to ensure managed elevated launch task during startup. Future launches may require one-time elevation again.");
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
if (startupMode.LaunchedViaTask)
|
||||
{
|
||||
logger.LogError("Application was launched via managed task marker but is still not elevated.");
|
||||
}
|
||||
#if DEBUG
|
||||
else if (!startupMode.IsTestMode)
|
||||
#else
|
||||
else
|
||||
#endif
|
||||
{
|
||||
var launchedElevatedInstance = Task.Run(async () => await elevatedTaskService.TryRunLaunchTaskAsync()).GetAwaiter().GetResult();
|
||||
if (launchedElevatedInstance)
|
||||
{
|
||||
logger.LogInformation("Managed elevated launch task started successfully. Exiting current non-elevated instance.");
|
||||
this.Shutdown();
|
||||
return;
|
||||
}
|
||||
|
||||
if (!startupMode.RegisterLaunchTask)
|
||||
{
|
||||
logger.LogInformation("Managed elevated launch task is unavailable. Requesting one-time elevation to bootstrap persistent launch.");
|
||||
var restartInitiated = Task.Run(async () => await elevationService.RestartWithElevation(new[] { RegisterLaunchTaskArgument })).GetAwaiter().GetResult();
|
||||
if (restartInitiated)
|
||||
{
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#if DEBUG
|
||||
if (!startupMode.IsTestMode)
|
||||
#else
|
||||
if (true)
|
||||
#endif
|
||||
{
|
||||
logger.LogError("ThreadPilot requires administrator privileges and cannot continue without elevation.");
|
||||
this.ShowElevationRequiredMessage();
|
||||
this.Shutdown(1);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// Enforce single-instance after elevation bootstrap logic to avoid mutex races during handoff.
|
||||
bool createdNew;
|
||||
this.singleInstanceMutex = new Mutex(initiallyOwned: true, name: "Global\\ThreadPilot_SingleInstance", createdNew: out createdNew);
|
||||
if (!createdNew)
|
||||
{
|
||||
System.Windows.MessageBox.Show(
|
||||
"ThreadPilot is already running.",
|
||||
"Instance already open",
|
||||
MessageBoxButton.OK,
|
||||
MessageBoxImage.Information);
|
||||
|
||||
this.Shutdown();
|
||||
return;
|
||||
}
|
||||
|
||||
base.OnStartup(e);
|
||||
|
||||
// Check for test mode
|
||||
#if DEBUG
|
||||
if (startupMode.IsTestMode)
|
||||
{
|
||||
// Run in console test mode
|
||||
AllocConsole();
|
||||
_ = Task.Run(async () =>
|
||||
{
|
||||
await TestRunner.RunTests();
|
||||
this.Dispatcher.Invoke(() => this.Shutdown());
|
||||
});
|
||||
return;
|
||||
}
|
||||
#endif
|
||||
|
||||
try
|
||||
{
|
||||
var settingsService = this.ServiceProvider.GetRequiredService<IApplicationSettingsService>();
|
||||
var themeService = this.ServiceProvider.GetRequiredService<IThemeService>();
|
||||
var localizationService = this.ServiceProvider.GetRequiredService<ILocalizationService>();
|
||||
|
||||
Task.Run(async () => await settingsService.LoadSettingsAsync()).GetAwaiter().GetResult();
|
||||
var settings = settingsService.Settings;
|
||||
loadedSettings = settings;
|
||||
localizationService.ApplyLanguage(settings.Language);
|
||||
effectiveStartMinimized = startupMode.StartMinimized || settings.StartMinimized;
|
||||
var useDarkTheme = settings.HasUserThemePreference
|
||||
? settings.UseDarkTheme
|
||||
: themeService.GetSystemUsesDarkTheme();
|
||||
|
||||
if (!settings.HasUserThemePreference && settings.UseDarkTheme != useDarkTheme)
|
||||
{
|
||||
settings.UseDarkTheme = useDarkTheme;
|
||||
Task.Run(async () => await settingsService.UpdateSettingsAsync(settings)).GetAwaiter().GetResult();
|
||||
}
|
||||
|
||||
themeService.ApplyTheme(useDarkTheme);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.LogWarning(ex, "Failed to preload theme settings during startup");
|
||||
}
|
||||
|
||||
var mainWindow = this.ServiceProvider.GetRequiredService<MainWindow>();
|
||||
this.MainWindow = mainWindow;
|
||||
|
||||
// Handle startup behavior with comprehensive error handling
|
||||
try
|
||||
{
|
||||
logger.LogInformation("Attempting to show main window...");
|
||||
|
||||
// Ensure the window is properly initialized
|
||||
if (mainWindow == null)
|
||||
{
|
||||
throw new InvalidOperationException("MainWindow could not be created");
|
||||
}
|
||||
|
||||
var startupWindowBehavior = StartupWindowBehavior.Resolve(startupMode.IsAutostart, effectiveStartMinimized);
|
||||
var showStartupSuggestion = loadedSettings != null
|
||||
&& StartupMinimizedSuggestionPolicy.ShouldShow(loadedSettings, startupWindowBehavior);
|
||||
mainWindow.ConfigureStartupMode(
|
||||
isSilentStartupMode: !startupWindowBehavior.ShouldShowWindow,
|
||||
showStartupMinimizedSuggestionOnReady: showStartupSuggestion);
|
||||
|
||||
mainWindow.ShowInTaskbar = startupWindowBehavior.ShowInTaskbar;
|
||||
mainWindow.Visibility = startupWindowBehavior.Visibility;
|
||||
mainWindow.WindowState = startupWindowBehavior.WindowState;
|
||||
|
||||
if (startupWindowBehavior.ShouldShowWindow)
|
||||
{
|
||||
mainWindow.Show();
|
||||
|
||||
if (startupWindowBehavior.HideAfterShow)
|
||||
{
|
||||
mainWindow.Hide();
|
||||
}
|
||||
else if (startupWindowBehavior.ActivateAfterShow)
|
||||
{
|
||||
mainWindow.EnsureDashboardVisibleOnScreen();
|
||||
mainWindow.Activate();
|
||||
}
|
||||
}
|
||||
|
||||
logger.LogInformation("Startup window behavior applied successfully");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.LogError(ex, "Critical error during application startup");
|
||||
|
||||
// Show error message and exit gracefully
|
||||
var errorMessage = $"ThreadPilot failed to start:\n\n{ex.Message}\n\nStack Trace:\n{ex.StackTrace}";
|
||||
System.Windows.MessageBox.Show(errorMessage, "ThreadPilot Startup Error",
|
||||
MessageBoxButton.OK, MessageBoxImage.Error);
|
||||
|
||||
// Exit the application
|
||||
this.Shutdown(1);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
private int RunSmokeTestWithTimeout(ILogger logger, TimeSpan timeout)
|
||||
{
|
||||
var smokeTestTask = Task.Run(() => this.RunSmokeTest(logger));
|
||||
if (smokeTestTask.Wait(timeout))
|
||||
{
|
||||
return smokeTestTask.GetAwaiter().GetResult();
|
||||
}
|
||||
|
||||
logger.LogError("ThreadPilot smoke test timed out after {TimeoutSeconds} seconds", timeout.TotalSeconds);
|
||||
return 2;
|
||||
}
|
||||
|
||||
private int RunSmokeTest(ILogger logger)
|
||||
{
|
||||
try
|
||||
{
|
||||
logger.LogInformation("Starting ThreadPilot smoke test");
|
||||
|
||||
_ = this.ServiceProvider.GetRequiredService<ILoggerFactory>();
|
||||
_ = this.ServiceProvider.GetRequiredService<IApplicationSettingsService>();
|
||||
_ = this.ServiceProvider.GetRequiredService<IThemeService>();
|
||||
_ = this.ServiceProvider.GetRequiredService<ILocalizationService>();
|
||||
|
||||
if (!System.IO.Directory.Exists(AppContext.BaseDirectory))
|
||||
{
|
||||
throw new InvalidOperationException("Application base directory was not found.");
|
||||
}
|
||||
|
||||
logger.LogInformation("ThreadPilot smoke test completed successfully");
|
||||
return 0;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.LogError(ex, "ThreadPilot smoke test failed");
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
|
||||
private readonly struct StartupMode
|
||||
{
|
||||
public bool StartMinimized { get; init; }
|
||||
|
||||
public bool IsAutostart { get; init; }
|
||||
|
||||
public bool IsSmokeTest { get; init; }
|
||||
|
||||
public bool RegisterLaunchTask { get; init; }
|
||||
|
||||
public bool LaunchedViaTask { get; init; }
|
||||
|
||||
public bool IsTestMode { get; init; }
|
||||
|
||||
public static StartupMode Parse(IEnumerable<string> args)
|
||||
{
|
||||
var mode = default(StartupMode);
|
||||
foreach (var arg in args)
|
||||
{
|
||||
switch (arg.ToLowerInvariant())
|
||||
{
|
||||
case "--test":
|
||||
mode = mode with { IsTestMode = true };
|
||||
break;
|
||||
case "--smoke-test":
|
||||
mode = mode with { IsSmokeTest = true };
|
||||
break;
|
||||
case "--start-minimized":
|
||||
mode = mode with { StartMinimized = true };
|
||||
break;
|
||||
case "--autostart":
|
||||
mode = mode with { IsAutostart = true };
|
||||
break;
|
||||
case "--startup":
|
||||
mode = mode with { IsAutostart = true, StartMinimized = true };
|
||||
break;
|
||||
case RegisterLaunchTaskArgument:
|
||||
mode = mode with { RegisterLaunchTask = true };
|
||||
break;
|
||||
case LaunchedViaTaskArgument:
|
||||
mode = mode with { LaunchedViaTask = true };
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return mode;
|
||||
}
|
||||
}
|
||||
|
||||
protected override void OnExit(ExitEventArgs e)
|
||||
{
|
||||
AppDomain.CurrentDomain.UnhandledException -= this.OnUnhandledException;
|
||||
this.DispatcherUnhandledException -= this.OnDispatcherUnhandledException;
|
||||
TaskScheduler.UnobservedTaskException -= this.OnUnobservedTaskException;
|
||||
|
||||
if (this.singleInstanceMutex != null)
|
||||
{
|
||||
try
|
||||
{
|
||||
this.singleInstanceMutex.ReleaseMutex();
|
||||
}
|
||||
catch
|
||||
{
|
||||
// Ignore; we just want to clean up quietly
|
||||
}
|
||||
this.singleInstanceMutex.Dispose();
|
||||
this.singleInstanceMutex = null;
|
||||
}
|
||||
|
||||
base.OnExit(e);
|
||||
}
|
||||
|
||||
#if DEBUG
|
||||
[System.Runtime.InteropServices.DllImport("kernel32.dll")]
|
||||
private static extern bool AllocConsole();
|
||||
#endif
|
||||
|
||||
private void ShowElevationRequiredMessage()
|
||||
{
|
||||
// Don't show the message during autostart to avoid interrupting the user
|
||||
var args = Environment.GetCommandLineArgs();
|
||||
if (args.Any(arg => arg.Equals("--autostart", StringComparison.OrdinalIgnoreCase) ||
|
||||
arg.Equals("--startup", StringComparison.OrdinalIgnoreCase)))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
System.Windows.MessageBox.Show(
|
||||
"ThreadPilot requires administrator privileges to start.\n\n" +
|
||||
"Please relaunch the application and approve the UAC prompt.\n\n" +
|
||||
"This instance will now close.",
|
||||
"Administrator Privileges Required",
|
||||
MessageBoxButton.OK,
|
||||
MessageBoxImage.Warning);
|
||||
}
|
||||
|
||||
private void OnUnhandledException(object sender, UnhandledExceptionEventArgs e)
|
||||
{
|
||||
var exception = e.ExceptionObject as Exception ?? new InvalidOperationException("Unhandled non-Exception object was raised.");
|
||||
this.ReportUnhandledException(exception, "AppDomain.CurrentDomain.UnhandledException", LogLevel.Critical);
|
||||
|
||||
var errorMessage = $"A critical error occurred:\n\n{exception?.Message}\n\nThe application will now exit.";
|
||||
System.Windows.MessageBox.Show(errorMessage, "Critical Error",
|
||||
MessageBoxButton.OK, MessageBoxImage.Error);
|
||||
}
|
||||
|
||||
private void OnDispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
|
||||
{
|
||||
this.ReportUnhandledException(e.Exception, "Application.DispatcherUnhandledException", LogLevel.Error);
|
||||
|
||||
if (Interlocked.CompareExchange(ref this.uiExceptionDialogOpen, 1, 0) != 0)
|
||||
{
|
||||
e.Handled = true;
|
||||
return;
|
||||
}
|
||||
|
||||
if (DateTime.UtcNow - this.lastUiExceptionDialogUtc < TimeSpan.FromSeconds(2))
|
||||
{
|
||||
e.Handled = true;
|
||||
Interlocked.Exchange(ref this.uiExceptionDialogOpen, 0);
|
||||
return;
|
||||
}
|
||||
|
||||
this.lastUiExceptionDialogUtc = DateTime.UtcNow;
|
||||
|
||||
var errorMessage = $"An error occurred in the user interface:\n\n{e.Exception.Message}\n\nDo you want to continue?";
|
||||
var result = System.Windows.MessageBox.Show(errorMessage, "UI Error",
|
||||
MessageBoxButton.YesNo, MessageBoxImage.Error);
|
||||
|
||||
if (result == MessageBoxResult.Yes)
|
||||
{
|
||||
e.Handled = true; // Continue running
|
||||
}
|
||||
else
|
||||
{
|
||||
e.Handled = false; // Let the application crash
|
||||
}
|
||||
|
||||
Interlocked.Exchange(ref this.uiExceptionDialogOpen, 0);
|
||||
}
|
||||
|
||||
private void OnUnobservedTaskException(object? sender, UnobservedTaskExceptionEventArgs e)
|
||||
{
|
||||
var exception = e.Exception.Flatten();
|
||||
this.ReportUnhandledException(exception, "TaskScheduler.UnobservedTaskException", LogLevel.Error);
|
||||
e.SetObserved();
|
||||
}
|
||||
|
||||
private void ReportUnhandledException(Exception exception, string source, LogLevel level)
|
||||
{
|
||||
var logger = this.ServiceProvider?.GetService<ILogger<App>>();
|
||||
if (level == LogLevel.Critical)
|
||||
{
|
||||
logger?.LogCritical(exception, "Unhandled exception in {Source}", source);
|
||||
}
|
||||
else
|
||||
{
|
||||
logger?.LogError(exception, "Unhandled exception in {Source}", source);
|
||||
}
|
||||
|
||||
var enhancedLogger = this.ServiceProvider?.GetService<IEnhancedLoggingService>();
|
||||
if (enhancedLogger == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var errorCode = exception is ThreadPilotException typedException
|
||||
? typedException.ErrorCode.ToString()
|
||||
: ErrorCode.Unhandled.ToString();
|
||||
|
||||
var context = new Dictionary<string, object>
|
||||
{
|
||||
["Source"] = source,
|
||||
[LogProperties.ErrorCode] = errorCode,
|
||||
[LogProperties.CorrelationId] = enhancedLogger.GetCurrentCorrelationId() ?? "N/A",
|
||||
["IsTerminatingLevel"] = level == LogLevel.Critical,
|
||||
};
|
||||
|
||||
TaskSafety.FireAndForget(
|
||||
enhancedLogger.LogErrorAsync(exception, source, context),
|
||||
logFailure => logger?.LogWarning(logFailure, "Failed to persist unhandled exception report"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+14
-30
@@ -1,30 +1,14 @@
|
||||
/*
|
||||
* ThreadPilot - Advanced Windows Process and Power Plan Manager
|
||||
* Copyright (C) 2025 Prime Build
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published by
|
||||
* the Free Software Foundation, version 3 only.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Windows;
|
||||
|
||||
[assembly: InternalsVisibleTo("ThreadPilot.Core.Tests")]
|
||||
|
||||
[assembly: ThemeInfo(
|
||||
ResourceDictionaryLocation.None, // where theme specific resource dictionaries are located
|
||||
// (used if a resource is not found in the page,
|
||||
// or application resource dictionaries)
|
||||
ResourceDictionaryLocation.SourceAssembly) // where the generic resource dictionary is located
|
||||
// (used if a resource is not found in the page,
|
||||
// app, or any theme specific resource dictionaries)
|
||||
]
|
||||
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Windows;
|
||||
|
||||
[assembly: InternalsVisibleTo("ThreadPilot.Core.Tests")]
|
||||
|
||||
[assembly: ThemeInfo(
|
||||
ResourceDictionaryLocation.None, // where theme specific resource dictionaries are located
|
||||
// (used if a resource is not found in the page,
|
||||
// or application resource dictionaries)
|
||||
ResourceDictionaryLocation.SourceAssembly) // where the generic resource dictionary is located
|
||||
// (used if a resource is not found in the page,
|
||||
// app, or any theme specific resource dictionaries)
|
||||
]
|
||||
|
||||
|
||||
@@ -1,57 +1,41 @@
|
||||
/*
|
||||
* ThreadPilot - Advanced Windows Process and Power Plan Manager
|
||||
* Copyright (C) 2025 Prime Build
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published by
|
||||
* the Free Software Foundation, version 3 only.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
namespace ThreadPilot
|
||||
{
|
||||
using System;
|
||||
using System.Globalization;
|
||||
using System.Windows;
|
||||
using System.Windows.Data;
|
||||
using System.Windows.Media;
|
||||
|
||||
public class BoolToColorConverter : IValueConverter
|
||||
{
|
||||
public static readonly BoolToColorConverter Instance = new();
|
||||
|
||||
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
|
||||
{
|
||||
if (value is bool boolValue)
|
||||
{
|
||||
return boolValue
|
||||
? ResolveBrush("TextFillColorPrimaryBrush", System.Windows.Media.Brushes.Black)
|
||||
: ResolveBrush("TextFillColorSecondaryBrush", System.Windows.Media.Brushes.Gray);
|
||||
}
|
||||
|
||||
return ResolveBrush("TextFillColorSecondaryBrush", System.Windows.Media.Brushes.Gray);
|
||||
}
|
||||
|
||||
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
private static System.Windows.Media.Brush ResolveBrush(string key, System.Windows.Media.Brush fallback)
|
||||
{
|
||||
if (System.Windows.Application.Current?.TryFindResource(key) is System.Windows.Media.Brush brush)
|
||||
{
|
||||
return brush;
|
||||
}
|
||||
|
||||
return fallback;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
namespace ThreadPilot
|
||||
{
|
||||
using System;
|
||||
using System.Globalization;
|
||||
using System.Windows;
|
||||
using System.Windows.Data;
|
||||
using System.Windows.Media;
|
||||
|
||||
public class BoolToColorConverter : IValueConverter
|
||||
{
|
||||
public static readonly BoolToColorConverter Instance = new();
|
||||
|
||||
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
|
||||
{
|
||||
if (value is bool boolValue)
|
||||
{
|
||||
return boolValue
|
||||
? ResolveBrush("TextFillColorPrimaryBrush", System.Windows.Media.Brushes.Black)
|
||||
: ResolveBrush("TextFillColorSecondaryBrush", System.Windows.Media.Brushes.Gray);
|
||||
}
|
||||
|
||||
return ResolveBrush("TextFillColorSecondaryBrush", System.Windows.Media.Brushes.Gray);
|
||||
}
|
||||
|
||||
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
private static System.Windows.Media.Brush ResolveBrush(string key, System.Windows.Media.Brush fallback)
|
||||
{
|
||||
if (System.Windows.Application.Current?.TryFindResource(key) is System.Windows.Media.Brush brush)
|
||||
{
|
||||
return brush;
|
||||
}
|
||||
|
||||
return fallback;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,43 +1,27 @@
|
||||
/*
|
||||
* ThreadPilot - Advanced Windows Process and Power Plan Manager
|
||||
* Copyright (C) 2025 Prime Build
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published by
|
||||
* the Free Software Foundation, version 3 only.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
namespace ThreadPilot
|
||||
{
|
||||
using System;
|
||||
using System.Globalization;
|
||||
using System.Windows;
|
||||
using System.Windows.Data;
|
||||
|
||||
public class BoolToFontWeightConverter : IValueConverter
|
||||
{
|
||||
public static readonly BoolToFontWeightConverter Instance = new();
|
||||
|
||||
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
|
||||
{
|
||||
if (value is bool boolValue && boolValue)
|
||||
{
|
||||
return FontWeights.Bold;
|
||||
}
|
||||
return FontWeights.Normal;
|
||||
}
|
||||
|
||||
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
namespace ThreadPilot
|
||||
{
|
||||
using System;
|
||||
using System.Globalization;
|
||||
using System.Windows;
|
||||
using System.Windows.Data;
|
||||
|
||||
public class BoolToFontWeightConverter : IValueConverter
|
||||
{
|
||||
public static readonly BoolToFontWeightConverter Instance = new();
|
||||
|
||||
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
|
||||
{
|
||||
if (value is bool boolValue && boolValue)
|
||||
{
|
||||
return FontWeights.Bold;
|
||||
}
|
||||
return FontWeights.Normal;
|
||||
}
|
||||
|
||||
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,48 +1,29 @@
|
||||
/*
|
||||
* ThreadPilot - Advanced Windows Process and Power Plan Manager
|
||||
* Copyright (C) 2025 Prime Build
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published by
|
||||
* the Free Software Foundation, version 3 only.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
namespace ThreadPilot.Converters
|
||||
{
|
||||
using System;
|
||||
using System.Globalization;
|
||||
using System.Windows.Data;
|
||||
|
||||
/// <summary>
|
||||
/// Converts boolean values to strings based on parameter format.
|
||||
/// </summary>
|
||||
public class BoolToStringConverter : IValueConverter
|
||||
{
|
||||
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
|
||||
{
|
||||
if (value is bool boolValue && parameter is string paramString)
|
||||
{
|
||||
var parts = paramString.Split('|');
|
||||
if (parts.Length == 2)
|
||||
{
|
||||
return boolValue ? parts[0] : parts[1];
|
||||
}
|
||||
}
|
||||
|
||||
return value?.ToString() ?? string.Empty;
|
||||
}
|
||||
|
||||
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
namespace ThreadPilot.Converters
|
||||
{
|
||||
using System;
|
||||
using System.Globalization;
|
||||
using System.Windows.Data;
|
||||
|
||||
public class BoolToStringConverter : IValueConverter
|
||||
{
|
||||
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
|
||||
{
|
||||
if (value is bool boolValue && parameter is string paramString)
|
||||
{
|
||||
var parts = paramString.Split('|');
|
||||
if (parts.Length == 2)
|
||||
{
|
||||
return boolValue ? parts[0] : parts[1];
|
||||
}
|
||||
}
|
||||
|
||||
return value?.ToString() ?? string.Empty;
|
||||
}
|
||||
|
||||
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,47 +1,31 @@
|
||||
/*
|
||||
* ThreadPilot - Advanced Windows Process and Power Plan Manager
|
||||
* Copyright (C) 2025 Prime Build
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published by
|
||||
* the Free Software Foundation, version 3 only.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
namespace ThreadPilot
|
||||
{
|
||||
using System;
|
||||
using System.Globalization;
|
||||
using System.Windows;
|
||||
using System.Windows.Data;
|
||||
|
||||
public class BoolToVisibilityConverter : IValueConverter
|
||||
{
|
||||
public static readonly BoolToVisibilityConverter Instance = new();
|
||||
|
||||
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
|
||||
{
|
||||
if (value is bool boolValue && boolValue)
|
||||
{
|
||||
return Visibility.Visible;
|
||||
}
|
||||
return Visibility.Collapsed;
|
||||
}
|
||||
|
||||
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
|
||||
{
|
||||
if (value is Visibility visibility)
|
||||
{
|
||||
return visibility == Visibility.Visible;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
namespace ThreadPilot
|
||||
{
|
||||
using System;
|
||||
using System.Globalization;
|
||||
using System.Windows;
|
||||
using System.Windows.Data;
|
||||
|
||||
public class BoolToVisibilityConverter : IValueConverter
|
||||
{
|
||||
public static readonly BoolToVisibilityConverter Instance = new();
|
||||
|
||||
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
|
||||
{
|
||||
if (value is bool boolValue && boolValue)
|
||||
{
|
||||
return Visibility.Visible;
|
||||
}
|
||||
return Visibility.Collapsed;
|
||||
}
|
||||
|
||||
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
|
||||
{
|
||||
if (value is Visibility visibility)
|
||||
{
|
||||
return visibility == Visibility.Visible;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,64 +1,45 @@
|
||||
/*
|
||||
* ThreadPilot - Advanced Windows Process and Power Plan Manager
|
||||
* Copyright (C) 2025 Prime Build
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published by
|
||||
* the Free Software Foundation, version 3 only.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
namespace ThreadPilot.Converters
|
||||
{
|
||||
using System;
|
||||
using System.Globalization;
|
||||
using System.Windows.Data;
|
||||
|
||||
/// <summary>
|
||||
/// Converts byte values to human-readable string format.
|
||||
/// </summary>
|
||||
public class BytesToStringConverter : IValueConverter
|
||||
{
|
||||
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
|
||||
{
|
||||
if (value is long bytes)
|
||||
{
|
||||
return FormatBytes(bytes);
|
||||
}
|
||||
|
||||
if (value is int intBytes)
|
||||
{
|
||||
return FormatBytes(intBytes);
|
||||
}
|
||||
|
||||
return "0 B";
|
||||
}
|
||||
|
||||
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
private static string FormatBytes(long bytes)
|
||||
{
|
||||
string[] suffixes = { "B", "KB", "MB", "GB", "TB" };
|
||||
int counter = 0;
|
||||
decimal number = bytes;
|
||||
|
||||
while (Math.Round(number / 1024) >= 1)
|
||||
{
|
||||
number /= 1024;
|
||||
counter++;
|
||||
}
|
||||
|
||||
return $"{number:n1} {suffixes[counter]}";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
namespace ThreadPilot.Converters
|
||||
{
|
||||
using System;
|
||||
using System.Globalization;
|
||||
using System.Windows.Data;
|
||||
|
||||
public class BytesToStringConverter : IValueConverter
|
||||
{
|
||||
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
|
||||
{
|
||||
if (value is long bytes)
|
||||
{
|
||||
return FormatBytes(bytes);
|
||||
}
|
||||
|
||||
if (value is int intBytes)
|
||||
{
|
||||
return FormatBytes(intBytes);
|
||||
}
|
||||
|
||||
return "0 B";
|
||||
}
|
||||
|
||||
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
private static string FormatBytes(long bytes)
|
||||
{
|
||||
string[] suffixes = { "B", "KB", "MB", "GB", "TB" };
|
||||
int counter = 0;
|
||||
decimal number = bytes;
|
||||
|
||||
while (Math.Round(number / 1024) >= 1)
|
||||
{
|
||||
number /= 1024;
|
||||
counter++;
|
||||
}
|
||||
|
||||
return $"{number:n1} {suffixes[counter]}";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+178
-212
@@ -1,212 +1,178 @@
|
||||
/*
|
||||
* ThreadPilot - Advanced Windows Process and Power Plan Manager
|
||||
* Copyright (C) 2025 Prime Build
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published by
|
||||
* the Free Software Foundation, version 3 only.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
namespace ThreadPilot.Converters
|
||||
{
|
||||
using System;
|
||||
using System.Globalization;
|
||||
using System.Windows;
|
||||
using System.Windows.Data;
|
||||
using System.Windows.Media;
|
||||
using ThreadPilot.Models;
|
||||
|
||||
/// <summary>
|
||||
/// Converter for CPU core type to color.
|
||||
/// </summary>
|
||||
public class CoreTypeToColorConverter : IMultiValueConverter
|
||||
{
|
||||
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
|
||||
{
|
||||
if (values.Length < 2)
|
||||
{
|
||||
return ResolveBrush("TextFillColorPrimaryBrush", System.Windows.Media.Brushes.Black);
|
||||
}
|
||||
|
||||
var coreType = values[0] as CpuCoreType? ?? CpuCoreType.Unknown;
|
||||
var isHyperThreaded = values[1] as bool? ?? false;
|
||||
|
||||
return coreType switch
|
||||
{
|
||||
CpuCoreType.PerformanceCore => isHyperThreaded
|
||||
? ResolveBrush("SystemAccentColorSecondaryBrush", System.Windows.Media.Brushes.DodgerBlue)
|
||||
: ResolveBrush("SystemAccentColorPrimaryBrush", System.Windows.Media.Brushes.Blue),
|
||||
CpuCoreType.EfficiencyCore => isHyperThreaded
|
||||
? ResolveBrush("TextFillColorSecondaryBrush", System.Windows.Media.Brushes.DarkGray)
|
||||
: ResolveBrush("TextFillColorPrimaryBrush", System.Windows.Media.Brushes.Black),
|
||||
CpuCoreType.Zen or CpuCoreType.ZenPlus or CpuCoreType.Zen2 or CpuCoreType.Zen3 or CpuCoreType.Zen4 =>
|
||||
isHyperThreaded
|
||||
? ResolveBrush("SystemAccentColorSecondaryBrush", System.Windows.Media.Brushes.DarkOrange)
|
||||
: ResolveBrush("SystemAccentColorPrimaryBrush", System.Windows.Media.Brushes.Orange),
|
||||
_ => ResolveBrush("TextFillColorSecondaryBrush", System.Windows.Media.Brushes.Gray),
|
||||
};
|
||||
}
|
||||
|
||||
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
private static System.Windows.Media.Brush ResolveBrush(string key, System.Windows.Media.Brush fallback)
|
||||
{
|
||||
if (System.Windows.Application.Current?.TryFindResource(key) is System.Windows.Media.Brush brush)
|
||||
{
|
||||
return brush;
|
||||
}
|
||||
|
||||
return fallback;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Converter for boolean to color (success/failure indication).
|
||||
/// </summary>
|
||||
public class BoolToColorConverter : IValueConverter
|
||||
{
|
||||
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
|
||||
{
|
||||
if (value is bool success)
|
||||
{
|
||||
return success
|
||||
? ResolveBrush("TextFillColorPrimaryBrush", System.Windows.Media.Brushes.Black)
|
||||
: ResolveBrush("TextFillColorSecondaryBrush", System.Windows.Media.Brushes.Gray);
|
||||
}
|
||||
return ResolveBrush("TextFillColorSecondaryBrush", System.Windows.Media.Brushes.Gray);
|
||||
}
|
||||
|
||||
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
private static System.Windows.Media.Brush ResolveBrush(string key, System.Windows.Media.Brush fallback)
|
||||
{
|
||||
if (System.Windows.Application.Current?.TryFindResource(key) is System.Windows.Media.Brush brush)
|
||||
{
|
||||
return brush;
|
||||
}
|
||||
|
||||
return fallback;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Converter for boolean to visibility.
|
||||
/// </summary>
|
||||
public class BoolToVisibilityConverter : IValueConverter
|
||||
{
|
||||
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
|
||||
{
|
||||
if (value is bool visible)
|
||||
{
|
||||
return visible ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed;
|
||||
}
|
||||
return System.Windows.Visibility.Collapsed;
|
||||
}
|
||||
|
||||
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Converter for affinity mask to readable string.
|
||||
/// </summary>
|
||||
public class AffinityMaskConverter : IValueConverter
|
||||
{
|
||||
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
|
||||
{
|
||||
if (value is long mask)
|
||||
{
|
||||
if (mask == 0)
|
||||
{
|
||||
return "None";
|
||||
}
|
||||
|
||||
var cores = new System.Collections.Generic.List<int>();
|
||||
for (int i = 0; i < 64; i++)
|
||||
{
|
||||
if ((mask & (1L << i)) != 0)
|
||||
{
|
||||
cores.Add(i);
|
||||
}
|
||||
}
|
||||
|
||||
if (cores.Count == 0)
|
||||
{
|
||||
return "None";
|
||||
}
|
||||
|
||||
if (cores.Count == 1)
|
||||
{
|
||||
return $"Core {cores[0]}";
|
||||
}
|
||||
|
||||
if (cores.Count <= 4)
|
||||
{
|
||||
return $"Cores {string.Join(", ", cores)}";
|
||||
}
|
||||
|
||||
return $"Cores {cores[0]}-{cores[cores.Count - 1]} ({cores.Count} cores)";
|
||||
}
|
||||
return "Unknown";
|
||||
}
|
||||
|
||||
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Converter for bytes to megabytes.
|
||||
/// </summary>
|
||||
public class BytesToMbConverter : IValueConverter
|
||||
{
|
||||
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
|
||||
{
|
||||
if (value is long bytes)
|
||||
{
|
||||
return (bytes / (1024.0 * 1024.0)).ToString("F1");
|
||||
}
|
||||
return "0.0";
|
||||
}
|
||||
|
||||
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Converter for string to visibility (empty/null = collapsed).
|
||||
/// </summary>
|
||||
public class StringToVisibilityConverter : IValueConverter
|
||||
{
|
||||
public static readonly StringToVisibilityConverter Instance = new();
|
||||
|
||||
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
|
||||
{
|
||||
return string.IsNullOrEmpty(value as string) ? System.Windows.Visibility.Collapsed : System.Windows.Visibility.Visible;
|
||||
}
|
||||
|
||||
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
namespace ThreadPilot.Converters
|
||||
{
|
||||
using System;
|
||||
using System.Globalization;
|
||||
using System.Windows;
|
||||
using System.Windows.Data;
|
||||
using System.Windows.Media;
|
||||
using ThreadPilot.Models;
|
||||
|
||||
public class CoreTypeToColorConverter : IMultiValueConverter
|
||||
{
|
||||
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
|
||||
{
|
||||
if (values.Length < 2)
|
||||
{
|
||||
return ResolveBrush("TextFillColorPrimaryBrush", System.Windows.Media.Brushes.Black);
|
||||
}
|
||||
|
||||
var coreType = values[0] as CpuCoreType? ?? CpuCoreType.Unknown;
|
||||
var isHyperThreaded = values[1] as bool? ?? false;
|
||||
|
||||
return coreType switch
|
||||
{
|
||||
CpuCoreType.PerformanceCore => isHyperThreaded
|
||||
? ResolveBrush("SystemAccentColorSecondaryBrush", System.Windows.Media.Brushes.DodgerBlue)
|
||||
: ResolveBrush("SystemAccentColorPrimaryBrush", System.Windows.Media.Brushes.Blue),
|
||||
CpuCoreType.EfficiencyCore => isHyperThreaded
|
||||
? ResolveBrush("TextFillColorSecondaryBrush", System.Windows.Media.Brushes.DarkGray)
|
||||
: ResolveBrush("TextFillColorPrimaryBrush", System.Windows.Media.Brushes.Black),
|
||||
CpuCoreType.Zen or CpuCoreType.ZenPlus or CpuCoreType.Zen2 or CpuCoreType.Zen3 or CpuCoreType.Zen4 =>
|
||||
isHyperThreaded
|
||||
? ResolveBrush("SystemAccentColorSecondaryBrush", System.Windows.Media.Brushes.DarkOrange)
|
||||
: ResolveBrush("SystemAccentColorPrimaryBrush", System.Windows.Media.Brushes.Orange),
|
||||
_ => ResolveBrush("TextFillColorSecondaryBrush", System.Windows.Media.Brushes.Gray),
|
||||
};
|
||||
}
|
||||
|
||||
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
private static System.Windows.Media.Brush ResolveBrush(string key, System.Windows.Media.Brush fallback)
|
||||
{
|
||||
if (System.Windows.Application.Current?.TryFindResource(key) is System.Windows.Media.Brush brush)
|
||||
{
|
||||
return brush;
|
||||
}
|
||||
|
||||
return fallback;
|
||||
}
|
||||
}
|
||||
|
||||
public class BoolToColorConverter : IValueConverter
|
||||
{
|
||||
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
|
||||
{
|
||||
if (value is bool success)
|
||||
{
|
||||
return success
|
||||
? ResolveBrush("TextFillColorPrimaryBrush", System.Windows.Media.Brushes.Black)
|
||||
: ResolveBrush("TextFillColorSecondaryBrush", System.Windows.Media.Brushes.Gray);
|
||||
}
|
||||
return ResolveBrush("TextFillColorSecondaryBrush", System.Windows.Media.Brushes.Gray);
|
||||
}
|
||||
|
||||
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
private static System.Windows.Media.Brush ResolveBrush(string key, System.Windows.Media.Brush fallback)
|
||||
{
|
||||
if (System.Windows.Application.Current?.TryFindResource(key) is System.Windows.Media.Brush brush)
|
||||
{
|
||||
return brush;
|
||||
}
|
||||
|
||||
return fallback;
|
||||
}
|
||||
}
|
||||
|
||||
public class BoolToVisibilityConverter : IValueConverter
|
||||
{
|
||||
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
|
||||
{
|
||||
if (value is bool visible)
|
||||
{
|
||||
return visible ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed;
|
||||
}
|
||||
return System.Windows.Visibility.Collapsed;
|
||||
}
|
||||
|
||||
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
}
|
||||
|
||||
public class AffinityMaskConverter : IValueConverter
|
||||
{
|
||||
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
|
||||
{
|
||||
if (value is long mask)
|
||||
{
|
||||
if (mask == 0)
|
||||
{
|
||||
return "None";
|
||||
}
|
||||
|
||||
var cores = new System.Collections.Generic.List<int>();
|
||||
for (int i = 0; i < 64; i++)
|
||||
{
|
||||
if ((mask & (1L << i)) != 0)
|
||||
{
|
||||
cores.Add(i);
|
||||
}
|
||||
}
|
||||
|
||||
if (cores.Count == 0)
|
||||
{
|
||||
return "None";
|
||||
}
|
||||
|
||||
if (cores.Count == 1)
|
||||
{
|
||||
return $"Core {cores[0]}";
|
||||
}
|
||||
|
||||
if (cores.Count <= 4)
|
||||
{
|
||||
return $"Cores {string.Join(", ", cores)}";
|
||||
}
|
||||
|
||||
return $"Cores {cores[0]}-{cores[cores.Count - 1]} ({cores.Count} cores)";
|
||||
}
|
||||
return "Unknown";
|
||||
}
|
||||
|
||||
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
}
|
||||
|
||||
public class BytesToMbConverter : IValueConverter
|
||||
{
|
||||
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
|
||||
{
|
||||
if (value is long bytes)
|
||||
{
|
||||
return (bytes / (1024.0 * 1024.0)).ToString("F1");
|
||||
}
|
||||
return "0.0";
|
||||
}
|
||||
|
||||
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
}
|
||||
|
||||
public class StringToVisibilityConverter : IValueConverter
|
||||
{
|
||||
public static readonly StringToVisibilityConverter Instance = new();
|
||||
|
||||
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
|
||||
{
|
||||
return string.IsNullOrEmpty(value as string) ? System.Windows.Visibility.Collapsed : System.Windows.Visibility.Visible;
|
||||
}
|
||||
|
||||
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,49 +1,30 @@
|
||||
/*
|
||||
* ThreadPilot - Advanced Windows Process and Power Plan Manager
|
||||
* Copyright (C) 2025 Prime Build
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published by
|
||||
* the Free Software Foundation, version 3 only.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
namespace ThreadPilot.Converters
|
||||
{
|
||||
using System;
|
||||
using System.Globalization;
|
||||
using System.Windows.Data;
|
||||
|
||||
/// <summary>
|
||||
/// Converter to invert boolean values.
|
||||
/// </summary>
|
||||
public class InverseBooleanConverter : IValueConverter
|
||||
{
|
||||
public static readonly InverseBooleanConverter Instance = new();
|
||||
|
||||
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
|
||||
{
|
||||
if (value is bool boolValue)
|
||||
{
|
||||
return !boolValue;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
|
||||
{
|
||||
if (value is bool boolValue)
|
||||
{
|
||||
return !boolValue;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
namespace ThreadPilot.Converters
|
||||
{
|
||||
using System;
|
||||
using System.Globalization;
|
||||
using System.Windows.Data;
|
||||
|
||||
public class InverseBooleanConverter : IValueConverter
|
||||
{
|
||||
public static readonly InverseBooleanConverter Instance = new();
|
||||
|
||||
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
|
||||
{
|
||||
if (value is bool boolValue)
|
||||
{
|
||||
return !boolValue;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
|
||||
{
|
||||
if (value is bool boolValue)
|
||||
{
|
||||
return !boolValue;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,51 +1,32 @@
|
||||
/*
|
||||
* ThreadPilot - Advanced Windows Process and Power Plan Manager
|
||||
* Copyright (C) 2025 Prime Build
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published by
|
||||
* the Free Software Foundation, version 3 only.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
namespace ThreadPilot.Converters
|
||||
{
|
||||
using System;
|
||||
using System.Globalization;
|
||||
using System.Windows;
|
||||
using System.Windows.Controls;
|
||||
using System.Windows.Data;
|
||||
|
||||
/// <summary>
|
||||
/// Converter to get the index of an item in an ItemsControl.
|
||||
/// </summary>
|
||||
public class ItemIndexConverter : IValueConverter
|
||||
{
|
||||
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
|
||||
{
|
||||
if (value is DependencyObject item)
|
||||
{
|
||||
var itemsControl = ItemsControl.ItemsControlFromItemContainer(item);
|
||||
if (itemsControl != null)
|
||||
{
|
||||
int index = itemsControl.ItemContainerGenerator.IndexFromContainer(item);
|
||||
return index;
|
||||
}
|
||||
}
|
||||
|
||||
return -1;
|
||||
}
|
||||
|
||||
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
namespace ThreadPilot.Converters
|
||||
{
|
||||
using System;
|
||||
using System.Globalization;
|
||||
using System.Windows;
|
||||
using System.Windows.Controls;
|
||||
using System.Windows.Data;
|
||||
|
||||
public class ItemIndexConverter : IValueConverter
|
||||
{
|
||||
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
|
||||
{
|
||||
if (value is DependencyObject item)
|
||||
{
|
||||
var itemsControl = ItemsControl.ItemsControlFromItemContainer(item);
|
||||
if (itemsControl != null)
|
||||
{
|
||||
int index = itemsControl.ItemContainerGenerator.IndexFromContainer(item);
|
||||
return index;
|
||||
}
|
||||
}
|
||||
|
||||
return -1;
|
||||
}
|
||||
|
||||
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,35 +1,19 @@
|
||||
/*
|
||||
* ThreadPilot - Advanced Windows Process and Power Plan Manager
|
||||
* Copyright (C) 2025 Prime Build
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published by
|
||||
* the Free Software Foundation, version 3 only.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
namespace ThreadPilot.Converters
|
||||
{
|
||||
using System;
|
||||
using System.Globalization;
|
||||
using System.Windows.Data;
|
||||
|
||||
public class NullToBoolConverter : IValueConverter
|
||||
{
|
||||
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
|
||||
{
|
||||
return value != null;
|
||||
}
|
||||
|
||||
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
}
|
||||
}
|
||||
namespace ThreadPilot.Converters
|
||||
{
|
||||
using System;
|
||||
using System.Globalization;
|
||||
using System.Windows.Data;
|
||||
|
||||
public class NullToBoolConverter : IValueConverter
|
||||
{
|
||||
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
|
||||
{
|
||||
return value != null;
|
||||
}
|
||||
|
||||
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+25
-41
@@ -1,41 +1,25 @@
|
||||
/*
|
||||
* ThreadPilot - Advanced Windows Process and Power Plan Manager
|
||||
* Copyright (C) 2025 Prime Build
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published by
|
||||
* the Free Software Foundation, version 3 only.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
namespace ThreadPilot.Helpers
|
||||
{
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Windows.Controls;
|
||||
|
||||
public static class AffinityHelper
|
||||
{
|
||||
public static long CalculateAffinityMask(IEnumerable<System.Windows.Controls.CheckBox> cpuCheckboxes)
|
||||
{
|
||||
return cpuCheckboxes
|
||||
.Where(cb => cb.IsChecked == true)
|
||||
.Sum(cb => (long)cb.Tag);
|
||||
}
|
||||
|
||||
public static void UpdateCheckboxesFromMask(IEnumerable<System.Windows.Controls.CheckBox> cpuCheckboxes, long affinityMask)
|
||||
{
|
||||
foreach (var checkbox in cpuCheckboxes)
|
||||
{
|
||||
var cpuBit = (long)checkbox.Tag;
|
||||
checkbox.IsChecked = (affinityMask & cpuBit) != 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
namespace ThreadPilot.Helpers
|
||||
{
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Windows.Controls;
|
||||
|
||||
public static class AffinityHelper
|
||||
{
|
||||
public static long CalculateAffinityMask(IEnumerable<System.Windows.Controls.CheckBox> cpuCheckboxes)
|
||||
{
|
||||
return cpuCheckboxes
|
||||
.Where(cb => cb.IsChecked == true)
|
||||
.Sum(cb => (long)cb.Tag);
|
||||
}
|
||||
|
||||
public static void UpdateCheckboxesFromMask(IEnumerable<System.Windows.Controls.CheckBox> cpuCheckboxes, long affinityMask)
|
||||
{
|
||||
foreach (var checkbox in cpuCheckboxes)
|
||||
{
|
||||
var cpuBit = (long)checkbox.Tag;
|
||||
checkbox.IsChecked = (affinityMask & cpuBit) != 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+106
-122
@@ -1,122 +1,106 @@
|
||||
/*
|
||||
* ThreadPilot - Advanced Windows Process and Power Plan Manager
|
||||
* Copyright (C) 2025 Prime Build
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published by
|
||||
* the Free Software Foundation, version 3 only.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
namespace ThreadPilot.Helpers
|
||||
{
|
||||
using System;
|
||||
using System.Globalization;
|
||||
using System.Windows;
|
||||
using System.Windows.Data;
|
||||
|
||||
public class BytesToMbConverter : IValueConverter
|
||||
{
|
||||
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
|
||||
{
|
||||
if (value is long bytes)
|
||||
{
|
||||
return Math.Round((double)bytes / (1024 * 1024), 1);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
}
|
||||
|
||||
public class AffinityMaskConverter : IValueConverter
|
||||
{
|
||||
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
|
||||
{
|
||||
if (value is long mask)
|
||||
{
|
||||
var selectedIndices = new System.Collections.Generic.List<int>();
|
||||
// Dynamic core count based on system, limited to 64 (long is 64-bit)
|
||||
int maxCores = Math.Min(64, Environment.ProcessorCount);
|
||||
|
||||
for (int i = 0; i < maxCores; i++)
|
||||
{
|
||||
if ((mask & (1L << i)) != 0)
|
||||
{
|
||||
selectedIndices.Add(i);
|
||||
}
|
||||
}
|
||||
|
||||
if (selectedIndices.Count == 0)
|
||||
{
|
||||
return "None";
|
||||
}
|
||||
|
||||
// Build the display string
|
||||
var indicesStr = string.Join(", ", selectedIndices);
|
||||
int selectedCount = selectedIndices.Count;
|
||||
|
||||
// Detect if this is likely physical cores only (every other logical processor)
|
||||
// This heuristic checks if selected indices are evenly spaced by 2 (e.g., 0,2,4,6,8...)
|
||||
bool isProbablyPhysicalCoresOnly = false;
|
||||
if (selectedCount > 1 && selectedCount <= maxCores / 2)
|
||||
{
|
||||
isProbablyPhysicalCoresOnly = true;
|
||||
for (int i = 1; i < selectedIndices.Count; i++)
|
||||
{
|
||||
if (selectedIndices[i] - selectedIndices[i - 1] != 2)
|
||||
{
|
||||
isProbablyPhysicalCoresOnly = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Choose terminology based on what's selected
|
||||
string label;
|
||||
if (selectedCount == maxCores)
|
||||
{
|
||||
label = $"All threads (0-{maxCores - 1})";
|
||||
}
|
||||
else if (isProbablyPhysicalCoresOnly && selectedIndices[0] == 0)
|
||||
{
|
||||
label = $"Physical cores ({indicesStr}) - {selectedCount} cores";
|
||||
}
|
||||
else
|
||||
{
|
||||
label = $"Threads ({indicesStr}) - {selectedCount} threads";
|
||||
}
|
||||
|
||||
return label;
|
||||
}
|
||||
return "Unknown";
|
||||
}
|
||||
|
||||
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
}
|
||||
|
||||
public class BoolToFontWeightConverter : IValueConverter
|
||||
{
|
||||
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
|
||||
{
|
||||
return (bool)value ? FontWeights.Bold : FontWeights.Normal;
|
||||
}
|
||||
|
||||
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
}
|
||||
}
|
||||
namespace ThreadPilot.Helpers
|
||||
{
|
||||
using System;
|
||||
using System.Globalization;
|
||||
using System.Windows;
|
||||
using System.Windows.Data;
|
||||
|
||||
public class BytesToMbConverter : IValueConverter
|
||||
{
|
||||
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
|
||||
{
|
||||
if (value is long bytes)
|
||||
{
|
||||
return Math.Round((double)bytes / (1024 * 1024), 1);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
}
|
||||
|
||||
public class AffinityMaskConverter : IValueConverter
|
||||
{
|
||||
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
|
||||
{
|
||||
if (value is long mask)
|
||||
{
|
||||
var selectedIndices = new System.Collections.Generic.List<int>();
|
||||
// Dynamic core count based on system, limited to 64 (long is 64-bit)
|
||||
int maxCores = Math.Min(64, Environment.ProcessorCount);
|
||||
|
||||
for (int i = 0; i < maxCores; i++)
|
||||
{
|
||||
if ((mask & (1L << i)) != 0)
|
||||
{
|
||||
selectedIndices.Add(i);
|
||||
}
|
||||
}
|
||||
|
||||
if (selectedIndices.Count == 0)
|
||||
{
|
||||
return "None";
|
||||
}
|
||||
|
||||
// Build the display string
|
||||
var indicesStr = string.Join(", ", selectedIndices);
|
||||
int selectedCount = selectedIndices.Count;
|
||||
|
||||
// Detect if this is likely physical cores only (every other logical processor)
|
||||
// This heuristic checks if selected indices are evenly spaced by 2 (e.g., 0,2,4,6,8...)
|
||||
bool isProbablyPhysicalCoresOnly = false;
|
||||
if (selectedCount > 1 && selectedCount <= maxCores / 2)
|
||||
{
|
||||
isProbablyPhysicalCoresOnly = true;
|
||||
for (int i = 1; i < selectedIndices.Count; i++)
|
||||
{
|
||||
if (selectedIndices[i] - selectedIndices[i - 1] != 2)
|
||||
{
|
||||
isProbablyPhysicalCoresOnly = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Choose terminology based on what's selected
|
||||
string label;
|
||||
if (selectedCount == maxCores)
|
||||
{
|
||||
label = $"All threads (0-{maxCores - 1})";
|
||||
}
|
||||
else if (isProbablyPhysicalCoresOnly && selectedIndices[0] == 0)
|
||||
{
|
||||
label = $"Physical cores ({indicesStr}) - {selectedCount} cores";
|
||||
}
|
||||
else
|
||||
{
|
||||
label = $"Threads ({indicesStr}) - {selectedCount} threads";
|
||||
}
|
||||
|
||||
return label;
|
||||
}
|
||||
return "Unknown";
|
||||
}
|
||||
|
||||
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
}
|
||||
|
||||
public class BoolToFontWeightConverter : IValueConverter
|
||||
{
|
||||
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
|
||||
{
|
||||
return (bool)value ? FontWeights.Bold : FontWeights.Normal;
|
||||
}
|
||||
|
||||
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+34
-56
@@ -1,56 +1,34 @@
|
||||
/*
|
||||
* ThreadPilot - Advanced Windows Process and Power Plan Manager
|
||||
* Copyright (C) 2025 Prime Build
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published by
|
||||
* the Free Software Foundation, version 3 only.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
namespace ThreadPilot.Helpers
|
||||
{
|
||||
using System;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Windows;
|
||||
using System.Windows.Interop;
|
||||
|
||||
/// <summary>
|
||||
/// Desktop Window Manager helper methods.
|
||||
/// </summary>
|
||||
public static class DwmHelper
|
||||
{
|
||||
private const int DwmUseImmersiveDarkMode = 20;
|
||||
private const int DwmUseImmersiveDarkModeLegacy = 19;
|
||||
|
||||
[DllImport("dwmapi.dll")]
|
||||
private static extern int DwmSetWindowAttribute(IntPtr hwnd, int dwAttribute, ref int pvAttribute, int cbAttribute);
|
||||
|
||||
/// <summary>
|
||||
/// Applies dark/light title-bar styling through DWM attributes.
|
||||
/// </summary>
|
||||
public static void ApplyWindowCaptionTheme(Window window, bool useDarkTheme)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(window);
|
||||
|
||||
var windowHandle = new WindowInteropHelper(window).Handle;
|
||||
if (windowHandle == IntPtr.Zero)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var darkMode = useDarkTheme ? 1 : 0;
|
||||
var result = DwmSetWindowAttribute(windowHandle, DwmUseImmersiveDarkMode, ref darkMode, Marshal.SizeOf<int>());
|
||||
if (result != 0)
|
||||
{
|
||||
_ = DwmSetWindowAttribute(windowHandle, DwmUseImmersiveDarkModeLegacy, ref darkMode, Marshal.SizeOf<int>());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
namespace ThreadPilot.Helpers
|
||||
{
|
||||
using System;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Windows;
|
||||
using System.Windows.Interop;
|
||||
|
||||
public static class DwmHelper
|
||||
{
|
||||
private const int DwmUseImmersiveDarkMode = 20;
|
||||
private const int DwmUseImmersiveDarkModeLegacy = 19;
|
||||
|
||||
[DllImport("dwmapi.dll")]
|
||||
private static extern int DwmSetWindowAttribute(IntPtr hwnd, int dwAttribute, ref int pvAttribute, int cbAttribute);
|
||||
|
||||
public static void ApplyWindowCaptionTheme(Window window, bool useDarkTheme)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(window);
|
||||
|
||||
var windowHandle = new WindowInteropHelper(window).Handle;
|
||||
if (windowHandle == IntPtr.Zero)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var darkMode = useDarkTheme ? 1 : 0;
|
||||
var result = DwmSetWindowAttribute(windowHandle, DwmUseImmersiveDarkMode, ref darkMode, Marshal.SizeOf<int>());
|
||||
if (result != 0)
|
||||
{
|
||||
_ = DwmSetWindowAttribute(windowHandle, DwmUseImmersiveDarkModeLegacy, ref darkMode, Marshal.SizeOf<int>());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+73
-101
@@ -1,101 +1,73 @@
|
||||
/*
|
||||
* ThreadPilot - Advanced Windows Process and Power Plan Manager
|
||||
* Copyright (C) 2025 Prime Build
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published by
|
||||
* the Free Software Foundation, version 3 only.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
namespace ThreadPilot.Helpers
|
||||
{
|
||||
using System;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using System.Windows;
|
||||
using ThreadPilot.ViewModels;
|
||||
|
||||
/// <summary>
|
||||
/// Coordinates serialized navigation transitions and unsaved-changes policy.
|
||||
/// </summary>
|
||||
public sealed class NavigationBehavior : IDisposable
|
||||
{
|
||||
private readonly SemaphoreSlim navigationGuard = new(1, 1);
|
||||
private bool isHandlingNavigation;
|
||||
|
||||
/// <summary>
|
||||
/// Tries entering the navigation critical section.
|
||||
/// </summary>
|
||||
public async Task<bool> TryEnterAsync()
|
||||
{
|
||||
if (this.isHandlingNavigation)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
await this.navigationGuard.WaitAsync().ConfigureAwait(false);
|
||||
this.isHandlingNavigation = true;
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Leaves the navigation critical section.
|
||||
/// </summary>
|
||||
public void Exit()
|
||||
{
|
||||
this.isHandlingNavigation = false;
|
||||
this.navigationGuard.Release();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Applies unsaved-settings policy before navigating away from the settings section.
|
||||
/// </summary>
|
||||
public static async Task<bool> EnsureCanNavigateAsync(
|
||||
string targetTag,
|
||||
SettingsViewModel settingsViewModel,
|
||||
Func<Task<MessageBoxResult>>? showUnsavedSettingsPromptAsync = null)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(targetTag);
|
||||
ArgumentNullException.ThrowIfNull(settingsViewModel);
|
||||
|
||||
if (!settingsViewModel.HasPendingChanges || string.Equals(targetTag, "Settings", StringComparison.Ordinal))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
var result = showUnsavedSettingsPromptAsync != null
|
||||
? await showUnsavedSettingsPromptAsync().ConfigureAwait(false)
|
||||
: MessageBox.Show(
|
||||
"You have unsaved changes in Settings.\n\nChoose an action:\n- Yes: Save changes\n- No: Discard changes\n- Cancel: Stay on current tab",
|
||||
"Unsaved Settings",
|
||||
MessageBoxButton.YesNoCancel,
|
||||
MessageBoxImage.Warning);
|
||||
|
||||
return result switch
|
||||
{
|
||||
MessageBoxResult.Cancel => false,
|
||||
MessageBoxResult.Yes => await settingsViewModel.SaveIfDirtyAsync().ConfigureAwait(false),
|
||||
MessageBoxResult.No => await DiscardPendingChangesAsync(settingsViewModel).ConfigureAwait(false),
|
||||
_ => true,
|
||||
};
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
this.navigationGuard.Dispose();
|
||||
}
|
||||
|
||||
private static async Task<bool> DiscardPendingChangesAsync(SettingsViewModel settingsViewModel)
|
||||
{
|
||||
await settingsViewModel.DiscardPendingChangesAsync().ConfigureAwait(false);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
namespace ThreadPilot.Helpers
|
||||
{
|
||||
using System;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using System.Windows;
|
||||
using ThreadPilot.ViewModels;
|
||||
|
||||
public sealed class NavigationBehavior : IDisposable
|
||||
{
|
||||
private readonly SemaphoreSlim navigationGuard = new(1, 1);
|
||||
private bool isHandlingNavigation;
|
||||
|
||||
public async Task<bool> TryEnterAsync()
|
||||
{
|
||||
if (this.isHandlingNavigation)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
await this.navigationGuard.WaitAsync().ConfigureAwait(false);
|
||||
this.isHandlingNavigation = true;
|
||||
return true;
|
||||
}
|
||||
|
||||
public void Exit()
|
||||
{
|
||||
this.isHandlingNavigation = false;
|
||||
this.navigationGuard.Release();
|
||||
}
|
||||
|
||||
public static async Task<bool> EnsureCanNavigateAsync(
|
||||
string targetTag,
|
||||
SettingsViewModel settingsViewModel,
|
||||
Func<Task<MessageBoxResult>>? showUnsavedSettingsPromptAsync = null)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(targetTag);
|
||||
ArgumentNullException.ThrowIfNull(settingsViewModel);
|
||||
|
||||
if (!settingsViewModel.HasPendingChanges || string.Equals(targetTag, "Settings", StringComparison.Ordinal))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
var result = showUnsavedSettingsPromptAsync != null
|
||||
? await showUnsavedSettingsPromptAsync().ConfigureAwait(false)
|
||||
: MessageBox.Show(
|
||||
"You have unsaved changes in Settings.\n\nChoose an action:\n- Yes: Save changes\n- No: Discard changes\n- Cancel: Stay on current tab",
|
||||
"Unsaved Settings",
|
||||
MessageBoxButton.YesNoCancel,
|
||||
MessageBoxImage.Warning);
|
||||
|
||||
return result switch
|
||||
{
|
||||
MessageBoxResult.Cancel => false,
|
||||
MessageBoxResult.Yes => await settingsViewModel.SaveIfDirtyAsync().ConfigureAwait(false),
|
||||
MessageBoxResult.No => await DiscardPendingChangesAsync(settingsViewModel).ConfigureAwait(false),
|
||||
_ => true,
|
||||
};
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
this.navigationGuard.Dispose();
|
||||
}
|
||||
|
||||
private static async Task<bool> DiscardPendingChangesAsync(SettingsViewModel settingsViewModel)
|
||||
{
|
||||
await settingsViewModel.DiscardPendingChangesAsync().ConfigureAwait(false);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,32 +1,16 @@
|
||||
/*
|
||||
* ThreadPilot - Advanced Windows Process and Power Plan Manager
|
||||
* Copyright (C) 2025 Prime Build
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published by
|
||||
* the Free Software Foundation, version 3 only.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
namespace ThreadPilot.Helpers
|
||||
{
|
||||
using System;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
|
||||
public static class ServiceProviderExtensions
|
||||
{
|
||||
public static IServiceProvider Services => ((App)App.Current).ServiceProvider;
|
||||
|
||||
public static T? GetService<T>()
|
||||
where T : class
|
||||
{
|
||||
return Services.GetService(typeof(T)) as T;
|
||||
}
|
||||
}
|
||||
}
|
||||
namespace ThreadPilot.Helpers
|
||||
{
|
||||
using System;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
|
||||
public static class ServiceProviderExtensions
|
||||
{
|
||||
public static IServiceProvider Services => ((App)App.Current).ServiceProvider;
|
||||
|
||||
public static T? GetService<T>()
|
||||
where T : class
|
||||
{
|
||||
return Services.GetService(typeof(T)) as T;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,17 +1,17 @@
|
||||
namespace ThreadPilot.Helpers
|
||||
{
|
||||
using System;
|
||||
using ThreadPilot.Models;
|
||||
|
||||
public static class StartupMinimizedSuggestionPolicy
|
||||
{
|
||||
public static bool ShouldShow(ApplicationSettingsModel settings, StartupWindowBehavior behavior)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(settings);
|
||||
|
||||
return behavior.ShouldShowWindow
|
||||
&& !settings.StartMinimized
|
||||
&& !settings.HasSeenStartupMinimizedSuggestion;
|
||||
}
|
||||
}
|
||||
}
|
||||
namespace ThreadPilot.Helpers
|
||||
{
|
||||
using System;
|
||||
using ThreadPilot.Models;
|
||||
|
||||
public static class StartupMinimizedSuggestionPolicy
|
||||
{
|
||||
public static bool ShouldShow(ApplicationSettingsModel settings, StartupWindowBehavior behavior)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(settings);
|
||||
|
||||
return behavior.ShouldShowWindow
|
||||
&& !settings.StartMinimized
|
||||
&& !settings.HasSeenStartupMinimizedSuggestion;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,46 +1,46 @@
|
||||
namespace ThreadPilot.Helpers
|
||||
{
|
||||
using System.Windows;
|
||||
|
||||
public readonly record struct StartupWindowBehavior(
|
||||
bool ShouldShowWindow,
|
||||
bool ShowInTaskbar,
|
||||
Visibility Visibility,
|
||||
WindowState WindowState,
|
||||
bool HideAfterShow,
|
||||
bool ActivateAfterShow)
|
||||
{
|
||||
public static StartupWindowBehavior Resolve(bool isAutostart, bool startMinimized)
|
||||
{
|
||||
if (isAutostart && startMinimized)
|
||||
{
|
||||
return new StartupWindowBehavior(
|
||||
ShouldShowWindow: false,
|
||||
ShowInTaskbar: false,
|
||||
Visibility: Visibility.Hidden,
|
||||
WindowState: WindowState.Minimized,
|
||||
HideAfterShow: false,
|
||||
ActivateAfterShow: false);
|
||||
}
|
||||
|
||||
if (startMinimized)
|
||||
{
|
||||
return new StartupWindowBehavior(
|
||||
ShouldShowWindow: false,
|
||||
ShowInTaskbar: false,
|
||||
Visibility: Visibility.Hidden,
|
||||
WindowState: WindowState.Minimized,
|
||||
HideAfterShow: false,
|
||||
ActivateAfterShow: false);
|
||||
}
|
||||
|
||||
return new StartupWindowBehavior(
|
||||
ShouldShowWindow: true,
|
||||
ShowInTaskbar: true,
|
||||
Visibility: Visibility.Visible,
|
||||
WindowState: WindowState.Normal,
|
||||
HideAfterShow: false,
|
||||
ActivateAfterShow: true);
|
||||
}
|
||||
}
|
||||
}
|
||||
namespace ThreadPilot.Helpers
|
||||
{
|
||||
using System.Windows;
|
||||
|
||||
public readonly record struct StartupWindowBehavior(
|
||||
bool ShouldShowWindow,
|
||||
bool ShowInTaskbar,
|
||||
Visibility Visibility,
|
||||
WindowState WindowState,
|
||||
bool HideAfterShow,
|
||||
bool ActivateAfterShow)
|
||||
{
|
||||
public static StartupWindowBehavior Resolve(bool isAutostart, bool startMinimized)
|
||||
{
|
||||
if (isAutostart && startMinimized)
|
||||
{
|
||||
return new StartupWindowBehavior(
|
||||
ShouldShowWindow: false,
|
||||
ShowInTaskbar: false,
|
||||
Visibility: Visibility.Hidden,
|
||||
WindowState: WindowState.Minimized,
|
||||
HideAfterShow: false,
|
||||
ActivateAfterShow: false);
|
||||
}
|
||||
|
||||
if (startMinimized)
|
||||
{
|
||||
return new StartupWindowBehavior(
|
||||
ShouldShowWindow: false,
|
||||
ShowInTaskbar: false,
|
||||
Visibility: Visibility.Hidden,
|
||||
WindowState: WindowState.Minimized,
|
||||
HideAfterShow: false,
|
||||
ActivateAfterShow: false);
|
||||
}
|
||||
|
||||
return new StartupWindowBehavior(
|
||||
ShouldShowWindow: true,
|
||||
ShowInTaskbar: true,
|
||||
Visibility: Visibility.Visible,
|
||||
WindowState: WindowState.Normal,
|
||||
HideAfterShow: false,
|
||||
ActivateAfterShow: true);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+295
-295
@@ -1,295 +1,295 @@
|
||||
namespace ThreadPilot.Helpers
|
||||
{
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Windows;
|
||||
using System.Windows.Forms;
|
||||
using System.Windows.Media;
|
||||
using DrawingRectangle = System.Drawing.Rectangle;
|
||||
using WpfPoint = System.Windows.Point;
|
||||
|
||||
public readonly record struct WindowBounds(double Left, double Top, double Width, double Height)
|
||||
{
|
||||
public double Right => this.Left + this.Width;
|
||||
|
||||
public double Bottom => this.Top + this.Height;
|
||||
|
||||
public double Area => Math.Max(0, this.Width) * Math.Max(0, this.Height);
|
||||
}
|
||||
|
||||
public readonly record struct MonitorWorkingArea(double Left, double Top, double Width, double Height, bool IsPrimary)
|
||||
{
|
||||
public double Right => this.Left + this.Width;
|
||||
|
||||
public double Bottom => this.Top + this.Height;
|
||||
|
||||
public double Area => Math.Max(0, this.Width) * Math.Max(0, this.Height);
|
||||
}
|
||||
|
||||
public readonly record struct WindowPlacementCorrection(WindowBounds Bounds, bool WasCorrected);
|
||||
|
||||
public static class WindowPlacementHelper
|
||||
{
|
||||
private const double DefaultWindowWidth = 1280;
|
||||
private const double DefaultWindowHeight = 864;
|
||||
private const double MinimumVisibleAreaRatio = 0.25;
|
||||
private const double Epsilon = 0.001;
|
||||
|
||||
public static WindowPlacementCorrection CorrectWindowBounds(
|
||||
WindowBounds currentBounds,
|
||||
IReadOnlyCollection<MonitorWorkingArea> workingAreas)
|
||||
{
|
||||
var validWorkingAreas = workingAreas
|
||||
.Where(IsValidWorkingArea)
|
||||
.ToArray();
|
||||
|
||||
if (validWorkingAreas.Length == 0)
|
||||
{
|
||||
var fallbackBounds = new WindowBounds(
|
||||
IsFinite(currentBounds.Left) ? currentBounds.Left : 0,
|
||||
IsFinite(currentBounds.Top) ? currentBounds.Top : 0,
|
||||
ResolveDimension(currentBounds.Width, DefaultWindowWidth),
|
||||
ResolveDimension(currentBounds.Height, DefaultWindowHeight));
|
||||
|
||||
return new WindowPlacementCorrection(fallbackBounds, !BoundsAreEquivalent(currentBounds, fallbackBounds));
|
||||
}
|
||||
|
||||
var targetArea = SelectTargetWorkingArea(currentBounds, validWorkingAreas);
|
||||
var correctedWidth = Math.Min(ResolveDimension(currentBounds.Width, DefaultWindowWidth), targetArea.Width);
|
||||
var correctedHeight = Math.Min(ResolveDimension(currentBounds.Height, DefaultWindowHeight), targetArea.Height);
|
||||
var sanitizedBounds = new WindowBounds(
|
||||
currentBounds.Left,
|
||||
currentBounds.Top,
|
||||
correctedWidth,
|
||||
correctedHeight);
|
||||
|
||||
var hasSufficientIntersection = HasSufficientIntersection(sanitizedBounds, targetArea);
|
||||
double correctedLeft;
|
||||
double correctedTop;
|
||||
|
||||
if (!hasSufficientIntersection || !IsFinite(sanitizedBounds.Left) || !IsFinite(sanitizedBounds.Top))
|
||||
{
|
||||
correctedLeft = targetArea.Left + ((targetArea.Width - correctedWidth) / 2);
|
||||
correctedTop = targetArea.Top + ((targetArea.Height - correctedHeight) / 2);
|
||||
}
|
||||
else
|
||||
{
|
||||
correctedLeft = Clamp(sanitizedBounds.Left, targetArea.Left, targetArea.Right - correctedWidth);
|
||||
correctedTop = Clamp(sanitizedBounds.Top, targetArea.Top, targetArea.Bottom - correctedHeight);
|
||||
}
|
||||
|
||||
var correctedBounds = new WindowBounds(
|
||||
Math.Round(correctedLeft),
|
||||
Math.Round(correctedTop),
|
||||
Math.Round(correctedWidth),
|
||||
Math.Round(correctedHeight));
|
||||
|
||||
return new WindowPlacementCorrection(correctedBounds, !BoundsAreEquivalent(currentBounds, correctedBounds));
|
||||
}
|
||||
|
||||
public static bool TryCorrectWindowPlacement(Window window)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(window);
|
||||
|
||||
try
|
||||
{
|
||||
if (window.WindowState == WindowState.Maximized)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var workingAreas = GetWorkingAreasInWindowDips(window);
|
||||
var currentBounds = new WindowBounds(
|
||||
window.Left,
|
||||
window.Top,
|
||||
ResolveWindowDimension(window.ActualWidth, window.Width, DefaultWindowWidth),
|
||||
ResolveWindowDimension(window.ActualHeight, window.Height, DefaultWindowHeight));
|
||||
|
||||
var correction = CorrectWindowBounds(currentBounds, workingAreas);
|
||||
if (!correction.WasCorrected)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
window.Width = correction.Bounds.Width;
|
||||
window.Height = correction.Bounds.Height;
|
||||
window.Left = correction.Bounds.Left;
|
||||
window.Top = correction.Bounds.Top;
|
||||
return true;
|
||||
}
|
||||
catch
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private static MonitorWorkingArea[] GetWorkingAreasInWindowDips(Window window)
|
||||
{
|
||||
var transformFromDevice = GetTransformFromDevice(window);
|
||||
var screens = Screen.AllScreens;
|
||||
if (screens.Length == 0)
|
||||
{
|
||||
return new[]
|
||||
{
|
||||
new MonitorWorkingArea(
|
||||
SystemParameters.WorkArea.Left,
|
||||
SystemParameters.WorkArea.Top,
|
||||
SystemParameters.WorkArea.Width,
|
||||
SystemParameters.WorkArea.Height,
|
||||
true),
|
||||
};
|
||||
}
|
||||
|
||||
return screens
|
||||
.Select(screen => ConvertWorkingAreaToDips(screen.WorkingArea, screen.Primary, transformFromDevice))
|
||||
.Where(IsValidWorkingArea)
|
||||
.ToArray();
|
||||
}
|
||||
|
||||
private static Matrix GetTransformFromDevice(Window window)
|
||||
{
|
||||
try
|
||||
{
|
||||
var source = PresentationSource.FromVisual(window);
|
||||
return source?.CompositionTarget?.TransformFromDevice ?? Matrix.Identity;
|
||||
}
|
||||
catch
|
||||
{
|
||||
return Matrix.Identity;
|
||||
}
|
||||
}
|
||||
|
||||
private static MonitorWorkingArea ConvertWorkingAreaToDips(
|
||||
DrawingRectangle workingArea,
|
||||
bool isPrimary,
|
||||
Matrix transformFromDevice)
|
||||
{
|
||||
var topLeft = transformFromDevice.Transform(new WpfPoint(workingArea.Left, workingArea.Top));
|
||||
var bottomRight = transformFromDevice.Transform(new WpfPoint(workingArea.Right, workingArea.Bottom));
|
||||
|
||||
return new MonitorWorkingArea(
|
||||
topLeft.X,
|
||||
topLeft.Y,
|
||||
bottomRight.X - topLeft.X,
|
||||
bottomRight.Y - topLeft.Y,
|
||||
isPrimary);
|
||||
}
|
||||
|
||||
private static MonitorWorkingArea SelectTargetWorkingArea(
|
||||
WindowBounds currentBounds,
|
||||
IReadOnlyList<MonitorWorkingArea> workingAreas)
|
||||
{
|
||||
var bestIntersection = workingAreas
|
||||
.Select(area => new
|
||||
{
|
||||
Area = area,
|
||||
IntersectionArea = GetIntersectionArea(currentBounds, area),
|
||||
})
|
||||
.OrderByDescending(candidate => candidate.IntersectionArea)
|
||||
.ThenByDescending(candidate => candidate.Area.IsPrimary)
|
||||
.First();
|
||||
|
||||
if (bestIntersection.IntersectionArea > 0 && HasSufficientIntersection(currentBounds, bestIntersection.Area))
|
||||
{
|
||||
return bestIntersection.Area;
|
||||
}
|
||||
|
||||
if (!IsFinite(currentBounds.Left) || !IsFinite(currentBounds.Top))
|
||||
{
|
||||
return workingAreas.FirstOrDefault(area => area.IsPrimary, workingAreas[0]);
|
||||
}
|
||||
|
||||
var centerX = currentBounds.Left + (ResolveDimension(currentBounds.Width, DefaultWindowWidth) / 2);
|
||||
var centerY = currentBounds.Top + (ResolveDimension(currentBounds.Height, DefaultWindowHeight) / 2);
|
||||
|
||||
return workingAreas
|
||||
.OrderBy(area => GetSquaredDistanceToArea(centerX, centerY, area))
|
||||
.ThenByDescending(area => area.IsPrimary)
|
||||
.First();
|
||||
}
|
||||
|
||||
private static double GetSquaredDistanceToArea(double x, double y, MonitorWorkingArea area)
|
||||
{
|
||||
var nearestX = Clamp(x, area.Left, area.Right);
|
||||
var nearestY = Clamp(y, area.Top, area.Bottom);
|
||||
var deltaX = x - nearestX;
|
||||
var deltaY = y - nearestY;
|
||||
|
||||
return (deltaX * deltaX) + (deltaY * deltaY);
|
||||
}
|
||||
|
||||
private static bool HasSufficientIntersection(WindowBounds bounds, MonitorWorkingArea area)
|
||||
{
|
||||
var intersectionArea = GetIntersectionArea(bounds, area);
|
||||
var boundedWindowArea = Math.Max(1, Math.Min(bounds.Width, area.Width) * Math.Min(bounds.Height, area.Height));
|
||||
|
||||
return intersectionArea / boundedWindowArea >= MinimumVisibleAreaRatio;
|
||||
}
|
||||
|
||||
private static double GetIntersectionArea(WindowBounds bounds, MonitorWorkingArea area)
|
||||
{
|
||||
if (!IsFinite(bounds.Left) || !IsFinite(bounds.Top) || !IsFinite(bounds.Width) || !IsFinite(bounds.Height))
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
var left = Math.Max(bounds.Left, area.Left);
|
||||
var top = Math.Max(bounds.Top, area.Top);
|
||||
var right = Math.Min(bounds.Right, area.Right);
|
||||
var bottom = Math.Min(bounds.Bottom, area.Bottom);
|
||||
var width = Math.Max(0, right - left);
|
||||
var height = Math.Max(0, bottom - top);
|
||||
|
||||
return width * height;
|
||||
}
|
||||
|
||||
private static bool IsValidWorkingArea(MonitorWorkingArea workingArea)
|
||||
{
|
||||
return IsFinite(workingArea.Left)
|
||||
&& IsFinite(workingArea.Top)
|
||||
&& IsFinite(workingArea.Width)
|
||||
&& IsFinite(workingArea.Height)
|
||||
&& workingArea.Width > 0
|
||||
&& workingArea.Height > 0;
|
||||
}
|
||||
|
||||
private static double ResolveWindowDimension(double actualValue, double configuredValue, double fallback)
|
||||
{
|
||||
if (IsFinite(actualValue) && actualValue > 0)
|
||||
{
|
||||
return actualValue;
|
||||
}
|
||||
|
||||
return ResolveDimension(configuredValue, fallback);
|
||||
}
|
||||
|
||||
private static double ResolveDimension(double value, double fallback)
|
||||
{
|
||||
return IsFinite(value) && value > 0 ? value : fallback;
|
||||
}
|
||||
|
||||
private static double Clamp(double value, double minimum, double maximum)
|
||||
{
|
||||
if (maximum < minimum)
|
||||
{
|
||||
return minimum;
|
||||
}
|
||||
|
||||
return Math.Min(Math.Max(value, minimum), maximum);
|
||||
}
|
||||
|
||||
private static bool IsFinite(double value)
|
||||
{
|
||||
return !double.IsNaN(value) && !double.IsInfinity(value);
|
||||
}
|
||||
|
||||
private static bool BoundsAreEquivalent(WindowBounds left, WindowBounds right)
|
||||
{
|
||||
return Math.Abs(left.Left - right.Left) < Epsilon
|
||||
&& Math.Abs(left.Top - right.Top) < Epsilon
|
||||
&& Math.Abs(left.Width - right.Width) < Epsilon
|
||||
&& Math.Abs(left.Height - right.Height) < Epsilon;
|
||||
}
|
||||
}
|
||||
}
|
||||
namespace ThreadPilot.Helpers
|
||||
{
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Windows;
|
||||
using System.Windows.Forms;
|
||||
using System.Windows.Media;
|
||||
using DrawingRectangle = System.Drawing.Rectangle;
|
||||
using WpfPoint = System.Windows.Point;
|
||||
|
||||
public readonly record struct WindowBounds(double Left, double Top, double Width, double Height)
|
||||
{
|
||||
public double Right => this.Left + this.Width;
|
||||
|
||||
public double Bottom => this.Top + this.Height;
|
||||
|
||||
public double Area => Math.Max(0, this.Width) * Math.Max(0, this.Height);
|
||||
}
|
||||
|
||||
public readonly record struct MonitorWorkingArea(double Left, double Top, double Width, double Height, bool IsPrimary)
|
||||
{
|
||||
public double Right => this.Left + this.Width;
|
||||
|
||||
public double Bottom => this.Top + this.Height;
|
||||
|
||||
public double Area => Math.Max(0, this.Width) * Math.Max(0, this.Height);
|
||||
}
|
||||
|
||||
public readonly record struct WindowPlacementCorrection(WindowBounds Bounds, bool WasCorrected);
|
||||
|
||||
public static class WindowPlacementHelper
|
||||
{
|
||||
private const double DefaultWindowWidth = 1280;
|
||||
private const double DefaultWindowHeight = 864;
|
||||
private const double MinimumVisibleAreaRatio = 0.25;
|
||||
private const double Epsilon = 0.001;
|
||||
|
||||
public static WindowPlacementCorrection CorrectWindowBounds(
|
||||
WindowBounds currentBounds,
|
||||
IReadOnlyCollection<MonitorWorkingArea> workingAreas)
|
||||
{
|
||||
var validWorkingAreas = workingAreas
|
||||
.Where(IsValidWorkingArea)
|
||||
.ToArray();
|
||||
|
||||
if (validWorkingAreas.Length == 0)
|
||||
{
|
||||
var fallbackBounds = new WindowBounds(
|
||||
IsFinite(currentBounds.Left) ? currentBounds.Left : 0,
|
||||
IsFinite(currentBounds.Top) ? currentBounds.Top : 0,
|
||||
ResolveDimension(currentBounds.Width, DefaultWindowWidth),
|
||||
ResolveDimension(currentBounds.Height, DefaultWindowHeight));
|
||||
|
||||
return new WindowPlacementCorrection(fallbackBounds, !BoundsAreEquivalent(currentBounds, fallbackBounds));
|
||||
}
|
||||
|
||||
var targetArea = SelectTargetWorkingArea(currentBounds, validWorkingAreas);
|
||||
var correctedWidth = Math.Min(ResolveDimension(currentBounds.Width, DefaultWindowWidth), targetArea.Width);
|
||||
var correctedHeight = Math.Min(ResolveDimension(currentBounds.Height, DefaultWindowHeight), targetArea.Height);
|
||||
var sanitizedBounds = new WindowBounds(
|
||||
currentBounds.Left,
|
||||
currentBounds.Top,
|
||||
correctedWidth,
|
||||
correctedHeight);
|
||||
|
||||
var hasSufficientIntersection = HasSufficientIntersection(sanitizedBounds, targetArea);
|
||||
double correctedLeft;
|
||||
double correctedTop;
|
||||
|
||||
if (!hasSufficientIntersection || !IsFinite(sanitizedBounds.Left) || !IsFinite(sanitizedBounds.Top))
|
||||
{
|
||||
correctedLeft = targetArea.Left + ((targetArea.Width - correctedWidth) / 2);
|
||||
correctedTop = targetArea.Top + ((targetArea.Height - correctedHeight) / 2);
|
||||
}
|
||||
else
|
||||
{
|
||||
correctedLeft = Clamp(sanitizedBounds.Left, targetArea.Left, targetArea.Right - correctedWidth);
|
||||
correctedTop = Clamp(sanitizedBounds.Top, targetArea.Top, targetArea.Bottom - correctedHeight);
|
||||
}
|
||||
|
||||
var correctedBounds = new WindowBounds(
|
||||
Math.Round(correctedLeft),
|
||||
Math.Round(correctedTop),
|
||||
Math.Round(correctedWidth),
|
||||
Math.Round(correctedHeight));
|
||||
|
||||
return new WindowPlacementCorrection(correctedBounds, !BoundsAreEquivalent(currentBounds, correctedBounds));
|
||||
}
|
||||
|
||||
public static bool TryCorrectWindowPlacement(Window window)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(window);
|
||||
|
||||
try
|
||||
{
|
||||
if (window.WindowState == WindowState.Maximized)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var workingAreas = GetWorkingAreasInWindowDips(window);
|
||||
var currentBounds = new WindowBounds(
|
||||
window.Left,
|
||||
window.Top,
|
||||
ResolveWindowDimension(window.ActualWidth, window.Width, DefaultWindowWidth),
|
||||
ResolveWindowDimension(window.ActualHeight, window.Height, DefaultWindowHeight));
|
||||
|
||||
var correction = CorrectWindowBounds(currentBounds, workingAreas);
|
||||
if (!correction.WasCorrected)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
window.Width = correction.Bounds.Width;
|
||||
window.Height = correction.Bounds.Height;
|
||||
window.Left = correction.Bounds.Left;
|
||||
window.Top = correction.Bounds.Top;
|
||||
return true;
|
||||
}
|
||||
catch
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private static MonitorWorkingArea[] GetWorkingAreasInWindowDips(Window window)
|
||||
{
|
||||
var transformFromDevice = GetTransformFromDevice(window);
|
||||
var screens = Screen.AllScreens;
|
||||
if (screens.Length == 0)
|
||||
{
|
||||
return new[]
|
||||
{
|
||||
new MonitorWorkingArea(
|
||||
SystemParameters.WorkArea.Left,
|
||||
SystemParameters.WorkArea.Top,
|
||||
SystemParameters.WorkArea.Width,
|
||||
SystemParameters.WorkArea.Height,
|
||||
true),
|
||||
};
|
||||
}
|
||||
|
||||
return screens
|
||||
.Select(screen => ConvertWorkingAreaToDips(screen.WorkingArea, screen.Primary, transformFromDevice))
|
||||
.Where(IsValidWorkingArea)
|
||||
.ToArray();
|
||||
}
|
||||
|
||||
private static Matrix GetTransformFromDevice(Window window)
|
||||
{
|
||||
try
|
||||
{
|
||||
var source = PresentationSource.FromVisual(window);
|
||||
return source?.CompositionTarget?.TransformFromDevice ?? Matrix.Identity;
|
||||
}
|
||||
catch
|
||||
{
|
||||
return Matrix.Identity;
|
||||
}
|
||||
}
|
||||
|
||||
private static MonitorWorkingArea ConvertWorkingAreaToDips(
|
||||
DrawingRectangle workingArea,
|
||||
bool isPrimary,
|
||||
Matrix transformFromDevice)
|
||||
{
|
||||
var topLeft = transformFromDevice.Transform(new WpfPoint(workingArea.Left, workingArea.Top));
|
||||
var bottomRight = transformFromDevice.Transform(new WpfPoint(workingArea.Right, workingArea.Bottom));
|
||||
|
||||
return new MonitorWorkingArea(
|
||||
topLeft.X,
|
||||
topLeft.Y,
|
||||
bottomRight.X - topLeft.X,
|
||||
bottomRight.Y - topLeft.Y,
|
||||
isPrimary);
|
||||
}
|
||||
|
||||
private static MonitorWorkingArea SelectTargetWorkingArea(
|
||||
WindowBounds currentBounds,
|
||||
IReadOnlyList<MonitorWorkingArea> workingAreas)
|
||||
{
|
||||
var bestIntersection = workingAreas
|
||||
.Select(area => new
|
||||
{
|
||||
Area = area,
|
||||
IntersectionArea = GetIntersectionArea(currentBounds, area),
|
||||
})
|
||||
.OrderByDescending(candidate => candidate.IntersectionArea)
|
||||
.ThenByDescending(candidate => candidate.Area.IsPrimary)
|
||||
.First();
|
||||
|
||||
if (bestIntersection.IntersectionArea > 0 && HasSufficientIntersection(currentBounds, bestIntersection.Area))
|
||||
{
|
||||
return bestIntersection.Area;
|
||||
}
|
||||
|
||||
if (!IsFinite(currentBounds.Left) || !IsFinite(currentBounds.Top))
|
||||
{
|
||||
return workingAreas.FirstOrDefault(area => area.IsPrimary, workingAreas[0]);
|
||||
}
|
||||
|
||||
var centerX = currentBounds.Left + (ResolveDimension(currentBounds.Width, DefaultWindowWidth) / 2);
|
||||
var centerY = currentBounds.Top + (ResolveDimension(currentBounds.Height, DefaultWindowHeight) / 2);
|
||||
|
||||
return workingAreas
|
||||
.OrderBy(area => GetSquaredDistanceToArea(centerX, centerY, area))
|
||||
.ThenByDescending(area => area.IsPrimary)
|
||||
.First();
|
||||
}
|
||||
|
||||
private static double GetSquaredDistanceToArea(double x, double y, MonitorWorkingArea area)
|
||||
{
|
||||
var nearestX = Clamp(x, area.Left, area.Right);
|
||||
var nearestY = Clamp(y, area.Top, area.Bottom);
|
||||
var deltaX = x - nearestX;
|
||||
var deltaY = y - nearestY;
|
||||
|
||||
return (deltaX * deltaX) + (deltaY * deltaY);
|
||||
}
|
||||
|
||||
private static bool HasSufficientIntersection(WindowBounds bounds, MonitorWorkingArea area)
|
||||
{
|
||||
var intersectionArea = GetIntersectionArea(bounds, area);
|
||||
var boundedWindowArea = Math.Max(1, Math.Min(bounds.Width, area.Width) * Math.Min(bounds.Height, area.Height));
|
||||
|
||||
return intersectionArea / boundedWindowArea >= MinimumVisibleAreaRatio;
|
||||
}
|
||||
|
||||
private static double GetIntersectionArea(WindowBounds bounds, MonitorWorkingArea area)
|
||||
{
|
||||
if (!IsFinite(bounds.Left) || !IsFinite(bounds.Top) || !IsFinite(bounds.Width) || !IsFinite(bounds.Height))
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
var left = Math.Max(bounds.Left, area.Left);
|
||||
var top = Math.Max(bounds.Top, area.Top);
|
||||
var right = Math.Min(bounds.Right, area.Right);
|
||||
var bottom = Math.Min(bounds.Bottom, area.Bottom);
|
||||
var width = Math.Max(0, right - left);
|
||||
var height = Math.Max(0, bottom - top);
|
||||
|
||||
return width * height;
|
||||
}
|
||||
|
||||
private static bool IsValidWorkingArea(MonitorWorkingArea workingArea)
|
||||
{
|
||||
return IsFinite(workingArea.Left)
|
||||
&& IsFinite(workingArea.Top)
|
||||
&& IsFinite(workingArea.Width)
|
||||
&& IsFinite(workingArea.Height)
|
||||
&& workingArea.Width > 0
|
||||
&& workingArea.Height > 0;
|
||||
}
|
||||
|
||||
private static double ResolveWindowDimension(double actualValue, double configuredValue, double fallback)
|
||||
{
|
||||
if (IsFinite(actualValue) && actualValue > 0)
|
||||
{
|
||||
return actualValue;
|
||||
}
|
||||
|
||||
return ResolveDimension(configuredValue, fallback);
|
||||
}
|
||||
|
||||
private static double ResolveDimension(double value, double fallback)
|
||||
{
|
||||
return IsFinite(value) && value > 0 ? value : fallback;
|
||||
}
|
||||
|
||||
private static double Clamp(double value, double minimum, double maximum)
|
||||
{
|
||||
if (maximum < minimum)
|
||||
{
|
||||
return minimum;
|
||||
}
|
||||
|
||||
return Math.Min(Math.Max(value, minimum), maximum);
|
||||
}
|
||||
|
||||
private static bool IsFinite(double value)
|
||||
{
|
||||
return !double.IsNaN(value) && !double.IsInfinity(value);
|
||||
}
|
||||
|
||||
private static bool BoundsAreEquivalent(WindowBounds left, WindowBounds right)
|
||||
{
|
||||
return Math.Abs(left.Left - right.Left) < Epsilon
|
||||
&& Math.Abs(left.Top - right.Top) < Epsilon
|
||||
&& Math.Abs(left.Width - right.Width) < Epsilon
|
||||
&& Math.Abs(left.Height - right.Height) < Epsilon;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+2025
-2045
File diff suppressed because it is too large
Load Diff
+200
-216
@@ -1,216 +1,200 @@
|
||||
/*
|
||||
* ThreadPilot - Advanced Windows Process and Power Plan Manager
|
||||
* Copyright (C) 2025 Prime Build
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published by
|
||||
* the Free Software Foundation, version 3 only.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
namespace ThreadPilot
|
||||
{
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using System.Timers;
|
||||
using System.Windows;
|
||||
using System.Windows.Controls;
|
||||
using System.Windows.Input;
|
||||
using System.Windows.Media.Animation;
|
||||
using System.Windows.Media.Effects;
|
||||
using System.Windows.Media.Imaging;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using ThreadPilot.Helpers;
|
||||
using ThreadPilot.Services;
|
||||
using ThreadPilot.ViewModels;
|
||||
using ThreadPilot.Views;
|
||||
|
||||
public partial class MainWindow : Wpf.Ui.Controls.FluentWindow
|
||||
{
|
||||
private const int SystemTrayUpdateBaseIntervalMs = 10000;
|
||||
private const int SystemTrayUpdateMaxIntervalMs = 60000;
|
||||
|
||||
private readonly ProcessViewModel processViewModel;
|
||||
private readonly PowerPlanViewModel powerPlanViewModel;
|
||||
private readonly IDiagnosticsViewModelProvider diagnosticsViewModelProvider;
|
||||
private readonly ProcessPowerPlanAssociationViewModel associationViewModel;
|
||||
private readonly LogViewerViewModel logViewerViewModel;
|
||||
private readonly ISystemTrayService systemTrayService;
|
||||
private readonly ISystemTrayStatusUpdater systemTrayStatusUpdater;
|
||||
private readonly IApplicationSettingsService settingsService;
|
||||
private readonly INotificationService notificationService;
|
||||
private readonly IProcessMonitorService processMonitorService;
|
||||
private readonly IProcessMonitorManagerService processMonitorManagerService;
|
||||
private readonly IProcessPowerPlanAssociationService processPowerPlanAssociationService;
|
||||
private readonly SettingsViewModel settingsViewModel;
|
||||
private readonly MainWindowViewModel mainWindowViewModel;
|
||||
private readonly SystemTweaksViewModel systemTweaksViewModel;
|
||||
private readonly ISelfResourceManagementService selfResourceManagementService;
|
||||
private readonly IKeyboardShortcutService keyboardShortcutService;
|
||||
private readonly IServiceProvider serviceProvider;
|
||||
private readonly IThemeService themeService;
|
||||
private System.Timers.Timer? systemTrayUpdateTimer;
|
||||
private PerformanceViewModel? performanceViewModel;
|
||||
private bool isSystemTrayUpdatesSuspended;
|
||||
private int isSystemTrayUpdateInProgress;
|
||||
private int systemTrayUpdateFailureStreak;
|
||||
private int startupUpdateCheckStarted;
|
||||
private AppActivityState? lastAppliedRefreshState;
|
||||
private readonly IElevationService elevationService;
|
||||
private readonly ISecurityService securityService;
|
||||
|
||||
// Loading overlay management
|
||||
private bool isInitializationComplete = false;
|
||||
private readonly List<string> initializationTasks = new();
|
||||
private readonly object initializationLock = new();
|
||||
private System.Timers.Timer? initializationTimeoutTimer;
|
||||
private readonly string debugLogPath = Path.Combine(Path.GetTempPath(), "ThreadPilot_Debug.log");
|
||||
|
||||
// Flag to skip process monitoring during startup if it causes issues
|
||||
private readonly bool skipProcessMonitoringDuringStartup = false;
|
||||
private bool isPerformingShutdown = false;
|
||||
private readonly NavigationBehavior navigationBehavior = new();
|
||||
private bool isPerformanceIntroVisible = false;
|
||||
private double previousAppContentOpacity = 1;
|
||||
private TaskCompletionSource<MessageBoxResult>? unsavedSettingsDialogCompletionSource;
|
||||
private bool isSilentStartupMode;
|
||||
private bool showStartupMinimizedSuggestionOnReady;
|
||||
|
||||
public MainWindow(
|
||||
ProcessViewModel processViewModel,
|
||||
PowerPlanViewModel powerPlanViewModel,
|
||||
IDiagnosticsViewModelProvider diagnosticsViewModelProvider,
|
||||
ProcessPowerPlanAssociationViewModel associationViewModel,
|
||||
LogViewerViewModel logViewerViewModel,
|
||||
ISystemTrayService systemTrayService,
|
||||
ISystemTrayStatusUpdater systemTrayStatusUpdater,
|
||||
IApplicationSettingsService settingsService,
|
||||
INotificationService notificationService,
|
||||
IProcessMonitorService processMonitorService,
|
||||
IProcessMonitorManagerService processMonitorManagerService,
|
||||
IProcessPowerPlanAssociationService processPowerPlanAssociationService,
|
||||
SettingsViewModel settingsViewModel,
|
||||
MainWindowViewModel mainWindowViewModel,
|
||||
SystemTweaksViewModel systemTweaksViewModel,
|
||||
ISelfResourceManagementService selfResourceManagementService,
|
||||
IKeyboardShortcutService keyboardShortcutService,
|
||||
IThemeService themeService,
|
||||
IServiceProvider serviceProvider,
|
||||
IElevationService elevationService,
|
||||
ISecurityService securityService)
|
||||
{
|
||||
try
|
||||
{
|
||||
System.Diagnostics.Debug.WriteLine("MainWindow constructor starting...");
|
||||
|
||||
this.InitializeComponent();
|
||||
System.Diagnostics.Debug.WriteLine("InitializeComponent completed");
|
||||
this.ConfigureDiagnosticsNavigation();
|
||||
|
||||
// Initialize loading overlay
|
||||
this.InitializeLoadingOverlay();
|
||||
this.LogDebug("Loading overlay initialized");
|
||||
this.LogDebug($"Debug log file: {this.debugLogPath}");
|
||||
|
||||
this.processViewModel = processViewModel;
|
||||
this.powerPlanViewModel = powerPlanViewModel;
|
||||
this.diagnosticsViewModelProvider = diagnosticsViewModelProvider;
|
||||
this.associationViewModel = associationViewModel;
|
||||
this.logViewerViewModel = logViewerViewModel;
|
||||
this.systemTrayService = systemTrayService;
|
||||
this.systemTrayStatusUpdater = systemTrayStatusUpdater;
|
||||
this.settingsService = settingsService;
|
||||
this.notificationService = notificationService;
|
||||
this.processMonitorService = processMonitorService;
|
||||
this.processMonitorManagerService = processMonitorManagerService;
|
||||
this.processPowerPlanAssociationService = processPowerPlanAssociationService;
|
||||
this.settingsViewModel = settingsViewModel;
|
||||
this.mainWindowViewModel = mainWindowViewModel;
|
||||
this.systemTweaksViewModel = systemTweaksViewModel;
|
||||
this.selfResourceManagementService = selfResourceManagementService;
|
||||
this.keyboardShortcutService = keyboardShortcutService;
|
||||
this.themeService = themeService;
|
||||
this.serviceProvider = serviceProvider;
|
||||
this.elevationService = elevationService;
|
||||
this.securityService = securityService;
|
||||
|
||||
this.processViewModel.OpenRulesRequested += this.OnOpenRulesRequested;
|
||||
|
||||
System.Diagnostics.Debug.WriteLine("Dependencies assigned");
|
||||
|
||||
this.SetDataContexts();
|
||||
System.Diagnostics.Debug.WriteLine("DataContexts set");
|
||||
|
||||
this.UpdateLoadingStatus("Starting ThreadPilot...", "Preparing startup sequence.");
|
||||
|
||||
// Start async initialization - marshal to UI thread to prevent cross-thread access exceptions
|
||||
_ = this.Dispatcher.InvokeAsync(async () => await this.InitializeApplicationAsync());
|
||||
System.Diagnostics.Debug.WriteLine("Async initialization started");
|
||||
System.Diagnostics.Debug.WriteLine("MainWindow constructor completed successfully");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
System.Diagnostics.Debug.WriteLine($"Error in MainWindow constructor: {ex}");
|
||||
System.Windows.MessageBox.Show(
|
||||
$"Error initializing MainWindow:\n\n{ex.Message}\n\nStack Trace:\n{ex.StackTrace}",
|
||||
"MainWindow Initialization Error", MessageBoxButton.OK, MessageBoxImage.Error);
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
public void ConfigureStartupMode(bool isSilentStartupMode, bool showStartupMinimizedSuggestionOnReady)
|
||||
{
|
||||
this.isSilentStartupMode = isSilentStartupMode;
|
||||
this.showStartupMinimizedSuggestionOnReady = showStartupMinimizedSuggestionOnReady;
|
||||
|
||||
if (!isSilentStartupMode)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
this.showStartupMinimizedSuggestionOnReady = false;
|
||||
this.LoadingOverlay.Visibility = Visibility.Collapsed;
|
||||
this.ClearUIContentBlur();
|
||||
|
||||
if (this.FindResource("SpinnerAnimation") is Storyboard spinnerAnimation)
|
||||
{
|
||||
spinnerAnimation.Stop();
|
||||
}
|
||||
|
||||
this.isSystemTrayUpdatesSuspended = true;
|
||||
this.lastAppliedRefreshState = AppActivityState.TrayHidden;
|
||||
this.processViewModel.SetProcessViewActive(false);
|
||||
this.processViewModel.ApplyRefreshDecision(AppRefreshPolicy.Evaluate(AppActivityState.TrayHidden));
|
||||
this.powerPlanViewModel.PauseAutoRefresh();
|
||||
}
|
||||
|
||||
private void ConfigureDiagnosticsNavigation()
|
||||
{
|
||||
this.NavPerf.Visibility = AppNavigationOptions.ShowAdvancedDiagnostics
|
||||
? Visibility.Visible
|
||||
: Visibility.Collapsed;
|
||||
}
|
||||
|
||||
private PerformanceViewModel GetPerformanceViewModel()
|
||||
{
|
||||
if (this.performanceViewModel != null)
|
||||
{
|
||||
return this.performanceViewModel;
|
||||
}
|
||||
|
||||
this.performanceViewModel = this.diagnosticsViewModelProvider.GetOrCreate();
|
||||
this.PerformanceViewControl.DataContext = this.performanceViewModel;
|
||||
return this.performanceViewModel;
|
||||
}
|
||||
}
|
||||
}
|
||||
namespace ThreadPilot
|
||||
{
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using System.Timers;
|
||||
using System.Windows;
|
||||
using System.Windows.Controls;
|
||||
using System.Windows.Input;
|
||||
using System.Windows.Media.Animation;
|
||||
using System.Windows.Media.Effects;
|
||||
using System.Windows.Media.Imaging;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using ThreadPilot.Helpers;
|
||||
using ThreadPilot.Services;
|
||||
using ThreadPilot.ViewModels;
|
||||
using ThreadPilot.Views;
|
||||
|
||||
public partial class MainWindow : Wpf.Ui.Controls.FluentWindow
|
||||
{
|
||||
private const int SystemTrayUpdateBaseIntervalMs = 10000;
|
||||
private const int SystemTrayUpdateMaxIntervalMs = 60000;
|
||||
|
||||
private readonly ProcessViewModel processViewModel;
|
||||
private readonly PowerPlanViewModel powerPlanViewModel;
|
||||
private readonly Lazy<PerformanceViewModel> performanceViewModelFactory;
|
||||
private readonly ProcessPowerPlanAssociationViewModel associationViewModel;
|
||||
private readonly LogViewerViewModel logViewerViewModel;
|
||||
private readonly ISystemTrayService systemTrayService;
|
||||
private readonly ISystemTrayStatusUpdater systemTrayStatusUpdater;
|
||||
private readonly IApplicationSettingsService settingsService;
|
||||
private readonly INotificationService notificationService;
|
||||
private readonly IProcessMonitorService processMonitorService;
|
||||
private readonly IProcessMonitorManagerService processMonitorManagerService;
|
||||
private readonly IProcessPowerPlanAssociationService processPowerPlanAssociationService;
|
||||
private readonly SettingsViewModel settingsViewModel;
|
||||
private readonly MainWindowViewModel mainWindowViewModel;
|
||||
private readonly SystemTweaksViewModel systemTweaksViewModel;
|
||||
private readonly ISelfResourceManagementService selfResourceManagementService;
|
||||
private readonly IKeyboardShortcutService keyboardShortcutService;
|
||||
private readonly IServiceProvider serviceProvider;
|
||||
private readonly IThemeService themeService;
|
||||
private System.Timers.Timer? systemTrayUpdateTimer;
|
||||
private PerformanceViewModel? performanceViewModel;
|
||||
private bool isSystemTrayUpdatesSuspended;
|
||||
private int isSystemTrayUpdateInProgress;
|
||||
private int systemTrayUpdateFailureStreak;
|
||||
private int startupUpdateCheckStarted;
|
||||
private AppActivityState? lastAppliedRefreshState;
|
||||
private readonly IElevationService elevationService;
|
||||
private readonly ISecurityService securityService;
|
||||
|
||||
// Loading overlay management
|
||||
private bool isInitializationComplete = false;
|
||||
private readonly List<string> initializationTasks = new();
|
||||
private readonly object initializationLock = new();
|
||||
private System.Timers.Timer? initializationTimeoutTimer;
|
||||
private readonly string debugLogPath = Path.Combine(Path.GetTempPath(), "ThreadPilot_Debug.log");
|
||||
|
||||
// Flag to skip process monitoring during startup if it causes issues
|
||||
private readonly bool skipProcessMonitoringDuringStartup = false;
|
||||
private bool isPerformingShutdown = false;
|
||||
private readonly NavigationBehavior navigationBehavior = new();
|
||||
private bool isPerformanceIntroVisible = false;
|
||||
private double previousAppContentOpacity = 1;
|
||||
private TaskCompletionSource<MessageBoxResult>? unsavedSettingsDialogCompletionSource;
|
||||
private bool isSilentStartupMode;
|
||||
private bool showStartupMinimizedSuggestionOnReady;
|
||||
|
||||
public MainWindow(
|
||||
ProcessViewModel processViewModel,
|
||||
PowerPlanViewModel powerPlanViewModel,
|
||||
Lazy<PerformanceViewModel> performanceViewModelFactory,
|
||||
ProcessPowerPlanAssociationViewModel associationViewModel,
|
||||
LogViewerViewModel logViewerViewModel,
|
||||
ISystemTrayService systemTrayService,
|
||||
ISystemTrayStatusUpdater systemTrayStatusUpdater,
|
||||
IApplicationSettingsService settingsService,
|
||||
INotificationService notificationService,
|
||||
IProcessMonitorService processMonitorService,
|
||||
IProcessMonitorManagerService processMonitorManagerService,
|
||||
IProcessPowerPlanAssociationService processPowerPlanAssociationService,
|
||||
SettingsViewModel settingsViewModel,
|
||||
MainWindowViewModel mainWindowViewModel,
|
||||
SystemTweaksViewModel systemTweaksViewModel,
|
||||
ISelfResourceManagementService selfResourceManagementService,
|
||||
IKeyboardShortcutService keyboardShortcutService,
|
||||
IThemeService themeService,
|
||||
IServiceProvider serviceProvider,
|
||||
IElevationService elevationService,
|
||||
ISecurityService securityService)
|
||||
{
|
||||
try
|
||||
{
|
||||
System.Diagnostics.Debug.WriteLine("MainWindow constructor starting...");
|
||||
|
||||
this.InitializeComponent();
|
||||
System.Diagnostics.Debug.WriteLine("InitializeComponent completed");
|
||||
this.ConfigureDiagnosticsNavigation();
|
||||
|
||||
// Initialize loading overlay
|
||||
this.InitializeLoadingOverlay();
|
||||
this.LogDebug("Loading overlay initialized");
|
||||
this.LogDebug($"Debug log file: {this.debugLogPath}");
|
||||
|
||||
this.processViewModel = processViewModel;
|
||||
this.powerPlanViewModel = powerPlanViewModel;
|
||||
this.performanceViewModelFactory = performanceViewModelFactory;
|
||||
this.associationViewModel = associationViewModel;
|
||||
this.logViewerViewModel = logViewerViewModel;
|
||||
this.systemTrayService = systemTrayService;
|
||||
this.systemTrayStatusUpdater = systemTrayStatusUpdater;
|
||||
this.settingsService = settingsService;
|
||||
this.notificationService = notificationService;
|
||||
this.processMonitorService = processMonitorService;
|
||||
this.processMonitorManagerService = processMonitorManagerService;
|
||||
this.processPowerPlanAssociationService = processPowerPlanAssociationService;
|
||||
this.settingsViewModel = settingsViewModel;
|
||||
this.mainWindowViewModel = mainWindowViewModel;
|
||||
this.systemTweaksViewModel = systemTweaksViewModel;
|
||||
this.selfResourceManagementService = selfResourceManagementService;
|
||||
this.keyboardShortcutService = keyboardShortcutService;
|
||||
this.themeService = themeService;
|
||||
this.serviceProvider = serviceProvider;
|
||||
this.elevationService = elevationService;
|
||||
this.securityService = securityService;
|
||||
|
||||
this.processViewModel.OpenRulesRequested += this.OnOpenRulesRequested;
|
||||
|
||||
System.Diagnostics.Debug.WriteLine("Dependencies assigned");
|
||||
|
||||
this.SetDataContexts();
|
||||
System.Diagnostics.Debug.WriteLine("DataContexts set");
|
||||
|
||||
this.UpdateLoadingStatus("Starting ThreadPilot...", "Preparing startup sequence.");
|
||||
|
||||
// Start async initialization - marshal to UI thread to prevent cross-thread access exceptions
|
||||
_ = this.Dispatcher.InvokeAsync(async () => await this.InitializeApplicationAsync());
|
||||
System.Diagnostics.Debug.WriteLine("Async initialization started");
|
||||
System.Diagnostics.Debug.WriteLine("MainWindow constructor completed successfully");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
System.Diagnostics.Debug.WriteLine($"Error in MainWindow constructor: {ex}");
|
||||
System.Windows.MessageBox.Show(
|
||||
$"Error initializing MainWindow:\n\n{ex.Message}\n\nStack Trace:\n{ex.StackTrace}",
|
||||
"MainWindow Initialization Error", MessageBoxButton.OK, MessageBoxImage.Error);
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
public void ConfigureStartupMode(bool isSilentStartupMode, bool showStartupMinimizedSuggestionOnReady)
|
||||
{
|
||||
this.isSilentStartupMode = isSilentStartupMode;
|
||||
this.showStartupMinimizedSuggestionOnReady = showStartupMinimizedSuggestionOnReady;
|
||||
|
||||
if (!isSilentStartupMode)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
this.showStartupMinimizedSuggestionOnReady = false;
|
||||
this.LoadingOverlay.Visibility = Visibility.Collapsed;
|
||||
this.ClearUIContentBlur();
|
||||
|
||||
if (this.FindResource("SpinnerAnimation") is Storyboard spinnerAnimation)
|
||||
{
|
||||
spinnerAnimation.Stop();
|
||||
}
|
||||
|
||||
this.isSystemTrayUpdatesSuspended = true;
|
||||
this.lastAppliedRefreshState = AppActivityState.TrayHidden;
|
||||
this.processViewModel.SetProcessViewActive(false);
|
||||
this.processViewModel.ApplyRefreshDecision(AppRefreshPolicy.Evaluate(AppActivityState.TrayHidden));
|
||||
this.powerPlanViewModel.PauseAutoRefresh();
|
||||
}
|
||||
|
||||
private void ConfigureDiagnosticsNavigation()
|
||||
{
|
||||
this.NavPerf.Visibility = AppNavigationOptions.ShowAdvancedDiagnostics
|
||||
? Visibility.Visible
|
||||
: Visibility.Collapsed;
|
||||
}
|
||||
|
||||
private PerformanceViewModel GetPerformanceViewModel()
|
||||
{
|
||||
if (this.performanceViewModel != null)
|
||||
{
|
||||
return this.performanceViewModel;
|
||||
}
|
||||
|
||||
this.performanceViewModel = this.performanceViewModelFactory.Value;
|
||||
this.PerformanceViewControl.DataContext = this.performanceViewModel;
|
||||
return this.performanceViewModel;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+359
-400
@@ -1,400 +1,359 @@
|
||||
/*
|
||||
* ThreadPilot - Advanced Windows Process and Power Plan Manager
|
||||
* Copyright (C) 2025 Prime Build
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published by
|
||||
* the Free Software Foundation, version 3 only.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
namespace ThreadPilot.Models
|
||||
{
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.ComponentModel;
|
||||
using System.Text.Json;
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
using ThreadPilot.Models.Core;
|
||||
using ThreadPilot.Services;
|
||||
|
||||
/// <summary>
|
||||
/// Model for application settings including notifications and tray preferences.
|
||||
/// </summary>
|
||||
public partial class ApplicationSettingsModel : ObservableObject, IModel
|
||||
{
|
||||
private static readonly JsonSerializerOptions UserSettingsComparisonJsonOptions = new()
|
||||
{
|
||||
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
|
||||
};
|
||||
|
||||
[ObservableProperty]
|
||||
private string id = "ApplicationSettings"; // Singleton settings
|
||||
|
||||
[ObservableProperty]
|
||||
private DateTime createdAt = DateTime.UtcNow;
|
||||
|
||||
[ObservableProperty]
|
||||
private DateTime updatedAt = DateTime.UtcNow;
|
||||
|
||||
[ObservableProperty]
|
||||
private bool enableNotifications = true;
|
||||
|
||||
[ObservableProperty]
|
||||
private NotificationLevelProfile notificationLevel = NotificationLevelProfile.All;
|
||||
|
||||
[ObservableProperty]
|
||||
private bool enableBalloonNotifications = true;
|
||||
|
||||
[ObservableProperty]
|
||||
private bool enableToastNotifications = true;
|
||||
|
||||
[ObservableProperty]
|
||||
private bool enablePowerPlanChangeNotifications = true;
|
||||
|
||||
[ObservableProperty]
|
||||
private bool enableProcessMonitoringNotifications = true;
|
||||
|
||||
[ObservableProperty]
|
||||
private bool enableErrorNotifications = true;
|
||||
|
||||
[ObservableProperty]
|
||||
private bool enableSuccessNotifications = true;
|
||||
|
||||
[ObservableProperty]
|
||||
private bool minimizeToTray = true;
|
||||
|
||||
[ObservableProperty]
|
||||
private bool closeToTray = true; // Default true: close to tray like CPU Set Setter
|
||||
|
||||
[ObservableProperty]
|
||||
private bool startMinimized = false;
|
||||
|
||||
[ObservableProperty]
|
||||
private bool showTrayIcon = true;
|
||||
|
||||
[ObservableProperty]
|
||||
private bool enableQuickApplyFromTray = true;
|
||||
|
||||
[ObservableProperty]
|
||||
private bool enableMonitoringControlFromTray = true;
|
||||
|
||||
[ObservableProperty]
|
||||
private int notificationDisplayDurationMs = 3000;
|
||||
|
||||
[ObservableProperty]
|
||||
private int balloonNotificationTimeoutMs = 5000;
|
||||
|
||||
[ObservableProperty]
|
||||
private NotificationPosition notificationPosition = NotificationPosition.BottomRight;
|
||||
|
||||
[ObservableProperty]
|
||||
private NotificationSound notificationSound = NotificationSound.Default;
|
||||
|
||||
[ObservableProperty]
|
||||
private bool enableNotificationSound = false;
|
||||
|
||||
[ObservableProperty]
|
||||
private string customTrayIconPath = string.Empty;
|
||||
|
||||
[ObservableProperty]
|
||||
private bool useCustomTrayIcon = false;
|
||||
|
||||
[ObservableProperty]
|
||||
private TrayIconStyle trayIconStyle = TrayIconStyle.Default;
|
||||
|
||||
[ObservableProperty]
|
||||
private bool showDetailedTooltips = true;
|
||||
|
||||
[ObservableProperty]
|
||||
private bool enableContextMenuAnimations = true;
|
||||
|
||||
[ObservableProperty]
|
||||
private bool autoHideNotifications = true;
|
||||
|
||||
[ObservableProperty]
|
||||
private bool enableNotificationHistory = true;
|
||||
|
||||
[ObservableProperty]
|
||||
private int maxNotificationHistoryItems = 50;
|
||||
|
||||
// Autostart Settings
|
||||
[ObservableProperty]
|
||||
private bool autostartWithWindows = true;
|
||||
|
||||
// Power Plan Settings
|
||||
[ObservableProperty]
|
||||
private string defaultPowerPlanId = string.Empty;
|
||||
|
||||
[ObservableProperty]
|
||||
private string defaultPowerPlanName = "Balanced";
|
||||
|
||||
[ObservableProperty]
|
||||
private bool restoreDefaultPowerPlanOnExit = true;
|
||||
|
||||
/// <summary>
|
||||
/// When true, all applied CPU masks are cleared when exiting the application
|
||||
/// (processes return to using all cores).
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private bool clearMasksOnClose = true;
|
||||
|
||||
[ObservableProperty]
|
||||
private bool useDarkTheme = false;
|
||||
|
||||
[ObservableProperty]
|
||||
private bool hasUserThemePreference = false;
|
||||
|
||||
[ObservableProperty]
|
||||
private string language = LocalizationService.DefaultLanguage;
|
||||
|
||||
[ObservableProperty]
|
||||
private bool enableAutomaticUpdateChecks = true;
|
||||
|
||||
[ObservableProperty]
|
||||
private DateTimeOffset? lastUpdateCheckUtc = null;
|
||||
|
||||
[ObservableProperty]
|
||||
private int updateCheckIntervalDays = 7;
|
||||
|
||||
[ObservableProperty]
|
||||
private bool includePrereleaseUpdates = false;
|
||||
|
||||
// Monitoring Settings
|
||||
[ObservableProperty]
|
||||
private int pollingIntervalMs = 5000;
|
||||
|
||||
[ObservableProperty]
|
||||
private int fallbackPollingIntervalMs = 10000;
|
||||
|
||||
[ObservableProperty]
|
||||
private bool enableWmiMonitoring = true;
|
||||
|
||||
[ObservableProperty]
|
||||
private bool enableFallbackPolling = true;
|
||||
|
||||
[ObservableProperty]
|
||||
private bool applyPersistentRulesOnProcessStart = true;
|
||||
|
||||
// Advanced Settings
|
||||
[ObservableProperty]
|
||||
private bool enableDebugLogging = false;
|
||||
|
||||
[ObservableProperty]
|
||||
private bool enablePerformanceCounters = false;
|
||||
|
||||
[ObservableProperty]
|
||||
private bool hasSeenPerformanceIntro = false;
|
||||
|
||||
[ObservableProperty]
|
||||
private bool hasSeenElevationWarning = false;
|
||||
|
||||
[ObservableProperty]
|
||||
private bool hasSeenStartupMinimizedSuggestion = false;
|
||||
|
||||
[ObservableProperty]
|
||||
private bool enableSelfLowImpactMode = true;
|
||||
|
||||
[ObservableProperty]
|
||||
private bool enableSelfAffinityLimit = false;
|
||||
|
||||
[ObservableProperty]
|
||||
private int maxLogFileSizeMb = 10;
|
||||
|
||||
[ObservableProperty]
|
||||
private int logRetentionDays = 7;
|
||||
|
||||
/// <summary>
|
||||
/// Keyboard shortcuts configuration.
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private List<KeyboardShortcut> keyboardShortcuts = new();
|
||||
|
||||
/// <summary>
|
||||
/// Copies settings from another instance.
|
||||
/// </summary>
|
||||
public void CopyFrom(ApplicationSettingsModel other)
|
||||
{
|
||||
if (other == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
this.EnableNotifications = other.EnableNotifications;
|
||||
this.NotificationLevel = other.NotificationLevel;
|
||||
this.EnableBalloonNotifications = other.EnableBalloonNotifications;
|
||||
this.EnableToastNotifications = other.EnableToastNotifications;
|
||||
this.EnablePowerPlanChangeNotifications = other.EnablePowerPlanChangeNotifications;
|
||||
this.EnableProcessMonitoringNotifications = other.EnableProcessMonitoringNotifications;
|
||||
this.EnableErrorNotifications = other.EnableErrorNotifications;
|
||||
this.EnableSuccessNotifications = other.EnableSuccessNotifications;
|
||||
this.MinimizeToTray = other.MinimizeToTray;
|
||||
this.CloseToTray = other.CloseToTray;
|
||||
this.StartMinimized = other.StartMinimized;
|
||||
this.ShowTrayIcon = other.ShowTrayIcon;
|
||||
this.EnableQuickApplyFromTray = other.EnableQuickApplyFromTray;
|
||||
this.EnableMonitoringControlFromTray = other.EnableMonitoringControlFromTray;
|
||||
this.NotificationDisplayDurationMs = other.NotificationDisplayDurationMs;
|
||||
this.BalloonNotificationTimeoutMs = other.BalloonNotificationTimeoutMs;
|
||||
this.NotificationPosition = other.NotificationPosition;
|
||||
this.NotificationSound = other.NotificationSound;
|
||||
this.EnableNotificationSound = other.EnableNotificationSound;
|
||||
this.CustomTrayIconPath = other.CustomTrayIconPath;
|
||||
this.UseCustomTrayIcon = other.UseCustomTrayIcon;
|
||||
this.TrayIconStyle = other.TrayIconStyle;
|
||||
this.ShowDetailedTooltips = other.ShowDetailedTooltips;
|
||||
this.EnableContextMenuAnimations = other.EnableContextMenuAnimations;
|
||||
this.AutoHideNotifications = other.AutoHideNotifications;
|
||||
this.EnableNotificationHistory = other.EnableNotificationHistory;
|
||||
this.MaxNotificationHistoryItems = other.MaxNotificationHistoryItems;
|
||||
|
||||
// Autostart Settings
|
||||
this.AutostartWithWindows = other.AutostartWithWindows;
|
||||
|
||||
// Power Plan Settings
|
||||
this.DefaultPowerPlanId = other.DefaultPowerPlanId;
|
||||
this.DefaultPowerPlanName = other.DefaultPowerPlanName;
|
||||
this.RestoreDefaultPowerPlanOnExit = other.RestoreDefaultPowerPlanOnExit;
|
||||
this.ClearMasksOnClose = other.ClearMasksOnClose;
|
||||
this.UseDarkTheme = other.UseDarkTheme;
|
||||
this.HasUserThemePreference = other.HasUserThemePreference;
|
||||
this.Language = LocalizationService.NormalizeLanguage(other.Language);
|
||||
this.EnableAutomaticUpdateChecks = other.EnableAutomaticUpdateChecks;
|
||||
this.LastUpdateCheckUtc = other.LastUpdateCheckUtc;
|
||||
this.UpdateCheckIntervalDays = other.UpdateCheckIntervalDays;
|
||||
this.IncludePrereleaseUpdates = other.IncludePrereleaseUpdates;
|
||||
|
||||
// Monitoring Settings
|
||||
this.PollingIntervalMs = other.PollingIntervalMs;
|
||||
this.FallbackPollingIntervalMs = other.FallbackPollingIntervalMs;
|
||||
this.EnableWmiMonitoring = other.EnableWmiMonitoring;
|
||||
this.EnableFallbackPolling = other.EnableFallbackPolling;
|
||||
this.ApplyPersistentRulesOnProcessStart = other.ApplyPersistentRulesOnProcessStart;
|
||||
|
||||
// Advanced Settings
|
||||
this.EnableDebugLogging = other.EnableDebugLogging;
|
||||
this.EnablePerformanceCounters = other.EnablePerformanceCounters;
|
||||
this.HasSeenPerformanceIntro = other.HasSeenPerformanceIntro;
|
||||
this.HasSeenElevationWarning = other.HasSeenElevationWarning;
|
||||
this.HasSeenStartupMinimizedSuggestion = other.HasSeenStartupMinimizedSuggestion;
|
||||
this.EnableSelfLowImpactMode = other.EnableSelfLowImpactMode;
|
||||
this.EnableSelfAffinityLimit = other.EnableSelfAffinityLimit;
|
||||
this.MaxLogFileSizeMb = other.MaxLogFileSizeMb;
|
||||
this.LogRetentionDays = other.LogRetentionDays;
|
||||
|
||||
// Keyboard Shortcuts
|
||||
this.KeyboardShortcuts = other.KeyboardShortcuts != null
|
||||
? new List<KeyboardShortcut>(other.KeyboardShortcuts)
|
||||
: new List<KeyboardShortcut>();
|
||||
}
|
||||
|
||||
// IModel implementation - properties are auto-generated by ObservableProperty
|
||||
public ValidationResult Validate()
|
||||
{
|
||||
var errors = new List<string>();
|
||||
|
||||
if (this.NotificationDisplayDurationMs < 1000 || this.NotificationDisplayDurationMs > 30000)
|
||||
{
|
||||
errors.Add("Notification display duration must be between 1 and 30 seconds");
|
||||
}
|
||||
|
||||
if (this.PollingIntervalMs < 1000 || this.PollingIntervalMs > 60000)
|
||||
{
|
||||
errors.Add("Process polling interval must be between 1 and 60 seconds");
|
||||
}
|
||||
|
||||
if (this.FallbackPollingIntervalMs < 1000 || this.FallbackPollingIntervalMs > 60000)
|
||||
{
|
||||
errors.Add("Fallback polling interval must be between 1 and 60 seconds");
|
||||
}
|
||||
|
||||
if (this.UpdateCheckIntervalDays < 1 || this.UpdateCheckIntervalDays > 365)
|
||||
{
|
||||
errors.Add("Update check interval must be between 1 and 365 days");
|
||||
}
|
||||
|
||||
return errors.Count == 0 ? ValidationResult.Success() : ValidationResult.Failure(errors.ToArray());
|
||||
}
|
||||
|
||||
public IModel Clone()
|
||||
{
|
||||
var clone = new ApplicationSettingsModel();
|
||||
clone.CopyFrom(this);
|
||||
clone.Id = this.Id;
|
||||
clone.CreatedAt = this.CreatedAt;
|
||||
clone.UpdatedAt = this.UpdatedAt;
|
||||
return clone;
|
||||
}
|
||||
|
||||
public bool HasSameUserSettingsAs(ApplicationSettingsModel? other)
|
||||
{
|
||||
if (other == null)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var currentSnapshot = (ApplicationSettingsModel)this.Clone();
|
||||
var otherSnapshot = (ApplicationSettingsModel)other.Clone();
|
||||
|
||||
currentSnapshot.Id = otherSnapshot.Id;
|
||||
currentSnapshot.CreatedAt = otherSnapshot.CreatedAt;
|
||||
currentSnapshot.UpdatedAt = otherSnapshot.UpdatedAt;
|
||||
|
||||
var currentJson = JsonSerializer.Serialize(currentSnapshot, UserSettingsComparisonJsonOptions);
|
||||
var otherJson = JsonSerializer.Serialize(otherSnapshot, UserSettingsComparisonJsonOptions);
|
||||
return string.Equals(currentJson, otherJson, StringComparison.Ordinal);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Notification level profile options.
|
||||
/// </summary>
|
||||
public enum NotificationLevelProfile
|
||||
{
|
||||
All,
|
||||
WarningsAndErrorsOnly,
|
||||
Silent,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Notification position options.
|
||||
/// </summary>
|
||||
public enum NotificationPosition
|
||||
{
|
||||
TopLeft,
|
||||
TopRight,
|
||||
BottomLeft,
|
||||
BottomRight,
|
||||
Center,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Notification sound options.
|
||||
/// </summary>
|
||||
public enum NotificationSound
|
||||
{
|
||||
None,
|
||||
Default,
|
||||
Information,
|
||||
Warning,
|
||||
Error,
|
||||
Custom,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Tray icon style options.
|
||||
/// </summary>
|
||||
public enum TrayIconStyle
|
||||
{
|
||||
Default,
|
||||
Monochrome,
|
||||
Colored,
|
||||
Custom,
|
||||
}
|
||||
}
|
||||
namespace ThreadPilot.Models
|
||||
{
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.ComponentModel;
|
||||
using System.Text.Json;
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
using ThreadPilot.Models.Core;
|
||||
using ThreadPilot.Services;
|
||||
|
||||
public partial class ApplicationSettingsModel : ObservableObject, IModel
|
||||
{
|
||||
private static readonly JsonSerializerOptions UserSettingsComparisonJsonOptions = new()
|
||||
{
|
||||
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
|
||||
};
|
||||
|
||||
[ObservableProperty]
|
||||
private string id = "ApplicationSettings"; // Singleton settings
|
||||
|
||||
[ObservableProperty]
|
||||
private DateTime createdAt = DateTime.UtcNow;
|
||||
|
||||
[ObservableProperty]
|
||||
private DateTime updatedAt = DateTime.UtcNow;
|
||||
|
||||
[ObservableProperty]
|
||||
private bool enableNotifications = true;
|
||||
|
||||
[ObservableProperty]
|
||||
private NotificationLevelProfile notificationLevel = NotificationLevelProfile.All;
|
||||
|
||||
[ObservableProperty]
|
||||
private bool enableBalloonNotifications = true;
|
||||
|
||||
[ObservableProperty]
|
||||
private bool enableToastNotifications = true;
|
||||
|
||||
[ObservableProperty]
|
||||
private bool enablePowerPlanChangeNotifications = true;
|
||||
|
||||
[ObservableProperty]
|
||||
private bool enableProcessMonitoringNotifications = true;
|
||||
|
||||
[ObservableProperty]
|
||||
private bool enableErrorNotifications = true;
|
||||
|
||||
[ObservableProperty]
|
||||
private bool enableSuccessNotifications = true;
|
||||
|
||||
[ObservableProperty]
|
||||
private bool minimizeToTray = true;
|
||||
|
||||
[ObservableProperty]
|
||||
private bool closeToTray = true; // Default true: close to tray like CPU Set Setter
|
||||
|
||||
[ObservableProperty]
|
||||
private bool startMinimized = false;
|
||||
|
||||
[ObservableProperty]
|
||||
private bool showTrayIcon = true;
|
||||
|
||||
[ObservableProperty]
|
||||
private bool enableQuickApplyFromTray = true;
|
||||
|
||||
[ObservableProperty]
|
||||
private bool enableMonitoringControlFromTray = true;
|
||||
|
||||
[ObservableProperty]
|
||||
private int notificationDisplayDurationMs = 3000;
|
||||
|
||||
[ObservableProperty]
|
||||
private int balloonNotificationTimeoutMs = 5000;
|
||||
|
||||
[ObservableProperty]
|
||||
private NotificationPosition notificationPosition = NotificationPosition.BottomRight;
|
||||
|
||||
[ObservableProperty]
|
||||
private NotificationSound notificationSound = NotificationSound.Default;
|
||||
|
||||
[ObservableProperty]
|
||||
private bool enableNotificationSound = false;
|
||||
|
||||
[ObservableProperty]
|
||||
private string customTrayIconPath = string.Empty;
|
||||
|
||||
[ObservableProperty]
|
||||
private bool useCustomTrayIcon = false;
|
||||
|
||||
[ObservableProperty]
|
||||
private TrayIconStyle trayIconStyle = TrayIconStyle.Default;
|
||||
|
||||
[ObservableProperty]
|
||||
private bool showDetailedTooltips = true;
|
||||
|
||||
[ObservableProperty]
|
||||
private bool enableContextMenuAnimations = true;
|
||||
|
||||
[ObservableProperty]
|
||||
private bool autoHideNotifications = true;
|
||||
|
||||
[ObservableProperty]
|
||||
private bool enableNotificationHistory = true;
|
||||
|
||||
[ObservableProperty]
|
||||
private int maxNotificationHistoryItems = 50;
|
||||
|
||||
// Autostart Settings
|
||||
[ObservableProperty]
|
||||
private bool autostartWithWindows = true;
|
||||
|
||||
// Power Plan Settings
|
||||
[ObservableProperty]
|
||||
private string defaultPowerPlanId = string.Empty;
|
||||
|
||||
[ObservableProperty]
|
||||
private string defaultPowerPlanName = "Balanced";
|
||||
|
||||
[ObservableProperty]
|
||||
private bool restoreDefaultPowerPlanOnExit = true;
|
||||
|
||||
[ObservableProperty]
|
||||
private bool clearMasksOnClose = true;
|
||||
|
||||
[ObservableProperty]
|
||||
private bool useDarkTheme = false;
|
||||
|
||||
[ObservableProperty]
|
||||
private bool hasUserThemePreference = false;
|
||||
|
||||
[ObservableProperty]
|
||||
private string language = LocalizationService.DefaultLanguage;
|
||||
|
||||
[ObservableProperty]
|
||||
private bool enableAutomaticUpdateChecks = true;
|
||||
|
||||
[ObservableProperty]
|
||||
private DateTimeOffset? lastUpdateCheckUtc = null;
|
||||
|
||||
[ObservableProperty]
|
||||
private int updateCheckIntervalDays = 7;
|
||||
|
||||
[ObservableProperty]
|
||||
private bool includePrereleaseUpdates = false;
|
||||
|
||||
// Monitoring Settings
|
||||
[ObservableProperty]
|
||||
private int pollingIntervalMs = 5000;
|
||||
|
||||
[ObservableProperty]
|
||||
private int fallbackPollingIntervalMs = 10000;
|
||||
|
||||
[ObservableProperty]
|
||||
private bool enableWmiMonitoring = true;
|
||||
|
||||
[ObservableProperty]
|
||||
private bool enableFallbackPolling = true;
|
||||
|
||||
[ObservableProperty]
|
||||
private bool applyPersistentRulesOnProcessStart = true;
|
||||
|
||||
// Advanced Settings
|
||||
[ObservableProperty]
|
||||
private bool enableDebugLogging = false;
|
||||
|
||||
[ObservableProperty]
|
||||
private bool enablePerformanceCounters = false;
|
||||
|
||||
[ObservableProperty]
|
||||
private bool hasSeenPerformanceIntro = false;
|
||||
|
||||
[ObservableProperty]
|
||||
private bool hasSeenElevationWarning = false;
|
||||
|
||||
[ObservableProperty]
|
||||
private bool hasSeenStartupMinimizedSuggestion = false;
|
||||
|
||||
[ObservableProperty]
|
||||
private bool enableSelfLowImpactMode = true;
|
||||
|
||||
[ObservableProperty]
|
||||
private bool enableSelfAffinityLimit = false;
|
||||
|
||||
[ObservableProperty]
|
||||
private int maxLogFileSizeMb = 10;
|
||||
|
||||
[ObservableProperty]
|
||||
private int logRetentionDays = 7;
|
||||
|
||||
[ObservableProperty]
|
||||
private List<KeyboardShortcut> keyboardShortcuts = new();
|
||||
|
||||
public void CopyFrom(ApplicationSettingsModel other)
|
||||
{
|
||||
if (other == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
this.EnableNotifications = other.EnableNotifications;
|
||||
this.NotificationLevel = other.NotificationLevel;
|
||||
this.EnableBalloonNotifications = other.EnableBalloonNotifications;
|
||||
this.EnableToastNotifications = other.EnableToastNotifications;
|
||||
this.EnablePowerPlanChangeNotifications = other.EnablePowerPlanChangeNotifications;
|
||||
this.EnableProcessMonitoringNotifications = other.EnableProcessMonitoringNotifications;
|
||||
this.EnableErrorNotifications = other.EnableErrorNotifications;
|
||||
this.EnableSuccessNotifications = other.EnableSuccessNotifications;
|
||||
this.MinimizeToTray = other.MinimizeToTray;
|
||||
this.CloseToTray = other.CloseToTray;
|
||||
this.StartMinimized = other.StartMinimized;
|
||||
this.ShowTrayIcon = other.ShowTrayIcon;
|
||||
this.EnableQuickApplyFromTray = other.EnableQuickApplyFromTray;
|
||||
this.EnableMonitoringControlFromTray = other.EnableMonitoringControlFromTray;
|
||||
this.NotificationDisplayDurationMs = other.NotificationDisplayDurationMs;
|
||||
this.BalloonNotificationTimeoutMs = other.BalloonNotificationTimeoutMs;
|
||||
this.NotificationPosition = other.NotificationPosition;
|
||||
this.NotificationSound = other.NotificationSound;
|
||||
this.EnableNotificationSound = other.EnableNotificationSound;
|
||||
this.CustomTrayIconPath = other.CustomTrayIconPath;
|
||||
this.UseCustomTrayIcon = other.UseCustomTrayIcon;
|
||||
this.TrayIconStyle = other.TrayIconStyle;
|
||||
this.ShowDetailedTooltips = other.ShowDetailedTooltips;
|
||||
this.EnableContextMenuAnimations = other.EnableContextMenuAnimations;
|
||||
this.AutoHideNotifications = other.AutoHideNotifications;
|
||||
this.EnableNotificationHistory = other.EnableNotificationHistory;
|
||||
this.MaxNotificationHistoryItems = other.MaxNotificationHistoryItems;
|
||||
|
||||
// Autostart Settings
|
||||
this.AutostartWithWindows = other.AutostartWithWindows;
|
||||
|
||||
// Power Plan Settings
|
||||
this.DefaultPowerPlanId = other.DefaultPowerPlanId;
|
||||
this.DefaultPowerPlanName = other.DefaultPowerPlanName;
|
||||
this.RestoreDefaultPowerPlanOnExit = other.RestoreDefaultPowerPlanOnExit;
|
||||
this.ClearMasksOnClose = other.ClearMasksOnClose;
|
||||
this.UseDarkTheme = other.UseDarkTheme;
|
||||
this.HasUserThemePreference = other.HasUserThemePreference;
|
||||
this.Language = LocalizationService.NormalizeLanguage(other.Language);
|
||||
this.EnableAutomaticUpdateChecks = other.EnableAutomaticUpdateChecks;
|
||||
this.LastUpdateCheckUtc = other.LastUpdateCheckUtc;
|
||||
this.UpdateCheckIntervalDays = other.UpdateCheckIntervalDays;
|
||||
this.IncludePrereleaseUpdates = other.IncludePrereleaseUpdates;
|
||||
|
||||
// Monitoring Settings
|
||||
this.PollingIntervalMs = other.PollingIntervalMs;
|
||||
this.FallbackPollingIntervalMs = other.FallbackPollingIntervalMs;
|
||||
this.EnableWmiMonitoring = other.EnableWmiMonitoring;
|
||||
this.EnableFallbackPolling = other.EnableFallbackPolling;
|
||||
this.ApplyPersistentRulesOnProcessStart = other.ApplyPersistentRulesOnProcessStart;
|
||||
|
||||
// Advanced Settings
|
||||
this.EnableDebugLogging = other.EnableDebugLogging;
|
||||
this.EnablePerformanceCounters = other.EnablePerformanceCounters;
|
||||
this.HasSeenPerformanceIntro = other.HasSeenPerformanceIntro;
|
||||
this.HasSeenElevationWarning = other.HasSeenElevationWarning;
|
||||
this.HasSeenStartupMinimizedSuggestion = other.HasSeenStartupMinimizedSuggestion;
|
||||
this.EnableSelfLowImpactMode = other.EnableSelfLowImpactMode;
|
||||
this.EnableSelfAffinityLimit = other.EnableSelfAffinityLimit;
|
||||
this.MaxLogFileSizeMb = other.MaxLogFileSizeMb;
|
||||
this.LogRetentionDays = other.LogRetentionDays;
|
||||
|
||||
// Keyboard Shortcuts
|
||||
this.KeyboardShortcuts = other.KeyboardShortcuts != null
|
||||
? new List<KeyboardShortcut>(other.KeyboardShortcuts)
|
||||
: new List<KeyboardShortcut>();
|
||||
}
|
||||
|
||||
// IModel implementation - properties are auto-generated by ObservableProperty
|
||||
public ValidationResult Validate()
|
||||
{
|
||||
var errors = new List<string>();
|
||||
|
||||
if (this.NotificationDisplayDurationMs < 1000 || this.NotificationDisplayDurationMs > 30000)
|
||||
{
|
||||
errors.Add("Notification display duration must be between 1 and 30 seconds");
|
||||
}
|
||||
|
||||
if (this.PollingIntervalMs < 1000 || this.PollingIntervalMs > 60000)
|
||||
{
|
||||
errors.Add("Process polling interval must be between 1 and 60 seconds");
|
||||
}
|
||||
|
||||
if (this.FallbackPollingIntervalMs < 1000 || this.FallbackPollingIntervalMs > 60000)
|
||||
{
|
||||
errors.Add("Fallback polling interval must be between 1 and 60 seconds");
|
||||
}
|
||||
|
||||
if (this.UpdateCheckIntervalDays < 1 || this.UpdateCheckIntervalDays > 365)
|
||||
{
|
||||
errors.Add("Update check interval must be between 1 and 365 days");
|
||||
}
|
||||
|
||||
return errors.Count == 0 ? ValidationResult.Success() : ValidationResult.Failure(errors.ToArray());
|
||||
}
|
||||
|
||||
public IModel Clone()
|
||||
{
|
||||
var clone = new ApplicationSettingsModel();
|
||||
clone.CopyFrom(this);
|
||||
clone.Id = this.Id;
|
||||
clone.CreatedAt = this.CreatedAt;
|
||||
clone.UpdatedAt = this.UpdatedAt;
|
||||
return clone;
|
||||
}
|
||||
|
||||
public bool HasSameUserSettingsAs(ApplicationSettingsModel? other)
|
||||
{
|
||||
if (other == null)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var currentSnapshot = (ApplicationSettingsModel)this.Clone();
|
||||
var otherSnapshot = (ApplicationSettingsModel)other.Clone();
|
||||
|
||||
currentSnapshot.Id = otherSnapshot.Id;
|
||||
currentSnapshot.CreatedAt = otherSnapshot.CreatedAt;
|
||||
currentSnapshot.UpdatedAt = otherSnapshot.UpdatedAt;
|
||||
|
||||
var currentJson = JsonSerializer.Serialize(currentSnapshot, UserSettingsComparisonJsonOptions);
|
||||
var otherJson = JsonSerializer.Serialize(otherSnapshot, UserSettingsComparisonJsonOptions);
|
||||
return string.Equals(currentJson, otherJson, StringComparison.Ordinal);
|
||||
}
|
||||
}
|
||||
|
||||
public enum NotificationLevelProfile
|
||||
{
|
||||
All,
|
||||
WarningsAndErrorsOnly,
|
||||
Silent,
|
||||
}
|
||||
|
||||
public enum NotificationPosition
|
||||
{
|
||||
TopLeft,
|
||||
TopRight,
|
||||
BottomLeft,
|
||||
BottomRight,
|
||||
Center,
|
||||
}
|
||||
|
||||
public enum NotificationSound
|
||||
{
|
||||
None,
|
||||
Default,
|
||||
Information,
|
||||
Warning,
|
||||
Error,
|
||||
Custom,
|
||||
}
|
||||
|
||||
public enum TrayIconStyle
|
||||
{
|
||||
Default,
|
||||
Monochrome,
|
||||
Colored,
|
||||
Custom,
|
||||
}
|
||||
}
|
||||
|
||||
+273
-325
@@ -1,325 +1,273 @@
|
||||
/*
|
||||
* ThreadPilot - Advanced Windows Process and Power Plan Manager
|
||||
* Copyright (C) 2025 Prime Build
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published by
|
||||
* the Free Software Foundation, version 3 only.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
namespace ThreadPilot.Models
|
||||
{
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
|
||||
/// <summary>
|
||||
/// Condition types for profile triggers.
|
||||
/// </summary>
|
||||
public enum ProfileConditionType
|
||||
{
|
||||
SystemLoad,
|
||||
TimeOfDay,
|
||||
PowerState,
|
||||
ProcessCount,
|
||||
MemoryUsage,
|
||||
CpuTemperature,
|
||||
BatteryLevel,
|
||||
NetworkActivity,
|
||||
UserIdle,
|
||||
Custom,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Comparison operators for conditions.
|
||||
/// </summary>
|
||||
public enum ComparisonOperator
|
||||
{
|
||||
Equals,
|
||||
NotEquals,
|
||||
GreaterThan,
|
||||
LessThan,
|
||||
GreaterThanOrEqual,
|
||||
LessThanOrEqual,
|
||||
Contains,
|
||||
NotContains,
|
||||
Between,
|
||||
NotBetween,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Logical operators for combining conditions.
|
||||
/// </summary>
|
||||
public enum LogicalOperator
|
||||
{
|
||||
And,
|
||||
Or,
|
||||
Not,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// System state information for condition evaluation.
|
||||
/// </summary>
|
||||
public class SystemState
|
||||
{
|
||||
public double CpuUsage { get; set; }
|
||||
|
||||
public double MemoryUsage { get; set; }
|
||||
|
||||
public int ProcessCount { get; set; }
|
||||
|
||||
public DateTime CurrentTime { get; set; } = DateTime.Now;
|
||||
|
||||
public bool IsOnBattery { get; set; }
|
||||
|
||||
public int BatteryLevel { get; set; }
|
||||
|
||||
public double CpuTemperature { get; set; }
|
||||
|
||||
public bool IsUserIdle { get; set; }
|
||||
|
||||
public TimeSpan UserIdleTime { get; set; }
|
||||
|
||||
public double NetworkActivity { get; set; }
|
||||
|
||||
public Dictionary<string, object> CustomProperties { get; set; } = new();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Individual condition for profile evaluation.
|
||||
/// </summary>
|
||||
public partial class ProfileCondition : ObservableObject
|
||||
{
|
||||
[ObservableProperty]
|
||||
private string name = string.Empty;
|
||||
|
||||
[ObservableProperty]
|
||||
private ProfileConditionType conditionType;
|
||||
|
||||
[ObservableProperty]
|
||||
private ComparisonOperator comparisonOperator;
|
||||
|
||||
[ObservableProperty]
|
||||
private object? value;
|
||||
|
||||
[ObservableProperty]
|
||||
private object? secondaryValue; // For Between/NotBetween operations
|
||||
|
||||
[ObservableProperty]
|
||||
private bool isEnabled = true;
|
||||
|
||||
[ObservableProperty]
|
||||
private string description = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// Evaluate this condition against the current system state.
|
||||
/// </summary>
|
||||
public bool Evaluate(ProcessModel process, SystemState systemState)
|
||||
{
|
||||
if (!this.IsEnabled)
|
||||
{
|
||||
return true; // Disabled conditions are considered true
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
var actualValue = this.GetActualValue(process, systemState);
|
||||
return CompareValues(actualValue, this.Value, this.SecondaryValue, this.ComparisonOperator);
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
return false; // Failed conditions are considered false
|
||||
}
|
||||
}
|
||||
|
||||
private object? GetActualValue(ProcessModel process, SystemState systemState)
|
||||
{
|
||||
return this.ConditionType switch
|
||||
{
|
||||
ProfileConditionType.SystemLoad => systemState.CpuUsage,
|
||||
ProfileConditionType.TimeOfDay => systemState.CurrentTime.TimeOfDay.TotalHours,
|
||||
ProfileConditionType.PowerState => systemState.IsOnBattery,
|
||||
ProfileConditionType.ProcessCount => systemState.ProcessCount,
|
||||
ProfileConditionType.MemoryUsage => systemState.MemoryUsage,
|
||||
ProfileConditionType.CpuTemperature => systemState.CpuTemperature,
|
||||
ProfileConditionType.BatteryLevel => systemState.BatteryLevel,
|
||||
ProfileConditionType.NetworkActivity => systemState.NetworkActivity,
|
||||
ProfileConditionType.UserIdle => systemState.IsUserIdle,
|
||||
ProfileConditionType.Custom => systemState.CustomProperties.GetValueOrDefault(this.Name),
|
||||
_ => null,
|
||||
};
|
||||
}
|
||||
|
||||
private static bool CompareValues(object? actual, object? expected, object? secondary, ComparisonOperator op)
|
||||
{
|
||||
if (actual == null || expected == null)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
return op switch
|
||||
{
|
||||
ComparisonOperator.Equals => actual.Equals(expected),
|
||||
ComparisonOperator.NotEquals => !actual.Equals(expected),
|
||||
ComparisonOperator.GreaterThan => Comparer<object>.Default.Compare(actual, expected) > 0,
|
||||
ComparisonOperator.LessThan => Comparer<object>.Default.Compare(actual, expected) < 0,
|
||||
ComparisonOperator.GreaterThanOrEqual => Comparer<object>.Default.Compare(actual, expected) >= 0,
|
||||
ComparisonOperator.LessThanOrEqual => Comparer<object>.Default.Compare(actual, expected) <= 0,
|
||||
ComparisonOperator.Contains => actual.ToString()?.Contains(expected.ToString() ?? string.Empty) ?? false,
|
||||
ComparisonOperator.NotContains => !(actual.ToString()?.Contains(expected.ToString() ?? string.Empty) ?? false),
|
||||
ComparisonOperator.Between => secondary != null &&
|
||||
Comparer<object>.Default.Compare(actual, expected) >= 0 &&
|
||||
Comparer<object>.Default.Compare(actual, secondary) <= 0,
|
||||
ComparisonOperator.NotBetween => secondary != null &&
|
||||
!(Comparer<object>.Default.Compare(actual, expected) >= 0 &&
|
||||
Comparer<object>.Default.Compare(actual, secondary) <= 0),
|
||||
_ => false,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Group of conditions with logical operators.
|
||||
/// </summary>
|
||||
public partial class ConditionGroup : ObservableObject
|
||||
{
|
||||
[ObservableProperty]
|
||||
private string name = string.Empty;
|
||||
|
||||
[ObservableProperty]
|
||||
private LogicalOperator logicalOperator = LogicalOperator.And;
|
||||
|
||||
[ObservableProperty]
|
||||
private List<ProfileCondition> conditions = new();
|
||||
|
||||
[ObservableProperty]
|
||||
private List<ConditionGroup> subGroups = new();
|
||||
|
||||
[ObservableProperty]
|
||||
private bool isEnabled = true;
|
||||
|
||||
/// <summary>
|
||||
/// Evaluate this condition group.
|
||||
/// </summary>
|
||||
public bool Evaluate(ProcessModel process, SystemState systemState)
|
||||
{
|
||||
if (!this.IsEnabled)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
var conditionResults = this.Conditions.Select(c => c.Evaluate(process, systemState)).ToList();
|
||||
var subGroupResults = this.SubGroups.Select(g => g.Evaluate(process, systemState)).ToList();
|
||||
var allResults = conditionResults.Concat(subGroupResults).ToList();
|
||||
|
||||
if (!allResults.Any())
|
||||
{
|
||||
return true; // No conditions means always true
|
||||
}
|
||||
|
||||
return this.LogicalOperator switch
|
||||
{
|
||||
LogicalOperator.And => allResults.All(r => r),
|
||||
LogicalOperator.Or => allResults.Any(r => r),
|
||||
LogicalOperator.Not => !allResults.All(r => r),
|
||||
_ => false,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Extended ProfileModel with conditional triggers.
|
||||
/// </summary>
|
||||
public partial class ConditionalProcessProfile : ProfileModel
|
||||
{
|
||||
[ObservableProperty]
|
||||
private List<ConditionGroup> conditionGroups = new();
|
||||
|
||||
[ObservableProperty]
|
||||
private TimeSpan autoApplyDelay = TimeSpan.FromSeconds(5);
|
||||
|
||||
[ObservableProperty]
|
||||
private int priority = 0; // Higher priority profiles are applied first
|
||||
|
||||
[ObservableProperty]
|
||||
private bool isAutoApplyEnabled = true;
|
||||
|
||||
[ObservableProperty]
|
||||
private DateTime lastEvaluated = DateTime.MinValue;
|
||||
|
||||
[ObservableProperty]
|
||||
private DateTime lastApplied = DateTime.MinValue;
|
||||
|
||||
[ObservableProperty]
|
||||
private bool wasLastEvaluationTrue = false;
|
||||
|
||||
[ObservableProperty]
|
||||
private string lastEvaluationReason = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// Check if this profile should be applied based on conditions.
|
||||
/// </summary>
|
||||
public bool ShouldApply(ProcessModel process, SystemState systemState)
|
||||
{
|
||||
if (!this.IsAutoApplyEnabled)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
this.LastEvaluated = DateTime.UtcNow;
|
||||
|
||||
try
|
||||
{
|
||||
// If no condition groups, always apply (like regular profile)
|
||||
if (!this.ConditionGroups.Any())
|
||||
{
|
||||
this.WasLastEvaluationTrue = true;
|
||||
this.LastEvaluationReason = "No conditions defined";
|
||||
return true;
|
||||
}
|
||||
|
||||
// Evaluate all condition groups (AND logic between groups)
|
||||
var results = this.ConditionGroups.Select(g => g.Evaluate(process, systemState)).ToList();
|
||||
var shouldApply = results.All(r => r);
|
||||
|
||||
this.WasLastEvaluationTrue = shouldApply;
|
||||
this.LastEvaluationReason = shouldApply
|
||||
? "All condition groups satisfied"
|
||||
: $"Failed conditions: {string.Join(", ", this.ConditionGroups.Where((g, i) => !results[i]).Select(g => g.Name))}";
|
||||
|
||||
return shouldApply;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
this.WasLastEvaluationTrue = false;
|
||||
this.LastEvaluationReason = $"Evaluation error: {ex.Message}";
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Check if enough time has passed since last application.
|
||||
/// </summary>
|
||||
public bool CanApplyNow()
|
||||
{
|
||||
return DateTime.UtcNow - this.LastApplied >= this.AutoApplyDelay;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Mark this profile as applied.
|
||||
/// </summary>
|
||||
public void MarkAsApplied()
|
||||
{
|
||||
this.LastApplied = DateTime.UtcNow;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
namespace ThreadPilot.Models
|
||||
{
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
|
||||
public enum ProfileConditionType
|
||||
{
|
||||
SystemLoad,
|
||||
TimeOfDay,
|
||||
PowerState,
|
||||
ProcessCount,
|
||||
MemoryUsage,
|
||||
CpuTemperature,
|
||||
BatteryLevel,
|
||||
NetworkActivity,
|
||||
UserIdle,
|
||||
Custom,
|
||||
}
|
||||
|
||||
public enum ComparisonOperator
|
||||
{
|
||||
Equals,
|
||||
NotEquals,
|
||||
GreaterThan,
|
||||
LessThan,
|
||||
GreaterThanOrEqual,
|
||||
LessThanOrEqual,
|
||||
Contains,
|
||||
NotContains,
|
||||
Between,
|
||||
NotBetween,
|
||||
}
|
||||
|
||||
public enum LogicalOperator
|
||||
{
|
||||
And,
|
||||
Or,
|
||||
Not,
|
||||
}
|
||||
|
||||
public class SystemState
|
||||
{
|
||||
public double CpuUsage { get; set; }
|
||||
|
||||
public double MemoryUsage { get; set; }
|
||||
|
||||
public int ProcessCount { get; set; }
|
||||
|
||||
public DateTime CurrentTime { get; set; } = DateTime.Now;
|
||||
|
||||
public bool IsOnBattery { get; set; }
|
||||
|
||||
public int BatteryLevel { get; set; }
|
||||
|
||||
public double CpuTemperature { get; set; }
|
||||
|
||||
public bool IsUserIdle { get; set; }
|
||||
|
||||
public TimeSpan UserIdleTime { get; set; }
|
||||
|
||||
public double NetworkActivity { get; set; }
|
||||
|
||||
public Dictionary<string, object> CustomProperties { get; set; } = new();
|
||||
}
|
||||
|
||||
public partial class ProfileCondition : ObservableObject
|
||||
{
|
||||
[ObservableProperty]
|
||||
private string name = string.Empty;
|
||||
|
||||
[ObservableProperty]
|
||||
private ProfileConditionType conditionType;
|
||||
|
||||
[ObservableProperty]
|
||||
private ComparisonOperator comparisonOperator;
|
||||
|
||||
[ObservableProperty]
|
||||
private object? value;
|
||||
|
||||
[ObservableProperty]
|
||||
private object? secondaryValue; // For Between/NotBetween operations
|
||||
|
||||
[ObservableProperty]
|
||||
private bool isEnabled = true;
|
||||
|
||||
[ObservableProperty]
|
||||
private string description = string.Empty;
|
||||
|
||||
public bool Evaluate(ProcessModel process, SystemState systemState)
|
||||
{
|
||||
if (!this.IsEnabled)
|
||||
{
|
||||
return true; // Disabled conditions are considered true
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
var actualValue = this.GetActualValue(process, systemState);
|
||||
return CompareValues(actualValue, this.Value, this.SecondaryValue, this.ComparisonOperator);
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
return false; // Failed conditions are considered false
|
||||
}
|
||||
}
|
||||
|
||||
private object? GetActualValue(ProcessModel process, SystemState systemState)
|
||||
{
|
||||
return this.ConditionType switch
|
||||
{
|
||||
ProfileConditionType.SystemLoad => systemState.CpuUsage,
|
||||
ProfileConditionType.TimeOfDay => systemState.CurrentTime.TimeOfDay.TotalHours,
|
||||
ProfileConditionType.PowerState => systemState.IsOnBattery,
|
||||
ProfileConditionType.ProcessCount => systemState.ProcessCount,
|
||||
ProfileConditionType.MemoryUsage => systemState.MemoryUsage,
|
||||
ProfileConditionType.CpuTemperature => systemState.CpuTemperature,
|
||||
ProfileConditionType.BatteryLevel => systemState.BatteryLevel,
|
||||
ProfileConditionType.NetworkActivity => systemState.NetworkActivity,
|
||||
ProfileConditionType.UserIdle => systemState.IsUserIdle,
|
||||
ProfileConditionType.Custom => systemState.CustomProperties.GetValueOrDefault(this.Name),
|
||||
_ => null,
|
||||
};
|
||||
}
|
||||
|
||||
private static bool CompareValues(object? actual, object? expected, object? secondary, ComparisonOperator op)
|
||||
{
|
||||
if (actual == null || expected == null)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
return op switch
|
||||
{
|
||||
ComparisonOperator.Equals => actual.Equals(expected),
|
||||
ComparisonOperator.NotEquals => !actual.Equals(expected),
|
||||
ComparisonOperator.GreaterThan => Comparer<object>.Default.Compare(actual, expected) > 0,
|
||||
ComparisonOperator.LessThan => Comparer<object>.Default.Compare(actual, expected) < 0,
|
||||
ComparisonOperator.GreaterThanOrEqual => Comparer<object>.Default.Compare(actual, expected) >= 0,
|
||||
ComparisonOperator.LessThanOrEqual => Comparer<object>.Default.Compare(actual, expected) <= 0,
|
||||
ComparisonOperator.Contains => actual.ToString()?.Contains(expected.ToString() ?? string.Empty) ?? false,
|
||||
ComparisonOperator.NotContains => !(actual.ToString()?.Contains(expected.ToString() ?? string.Empty) ?? false),
|
||||
ComparisonOperator.Between => secondary != null &&
|
||||
Comparer<object>.Default.Compare(actual, expected) >= 0 &&
|
||||
Comparer<object>.Default.Compare(actual, secondary) <= 0,
|
||||
ComparisonOperator.NotBetween => secondary != null &&
|
||||
!(Comparer<object>.Default.Compare(actual, expected) >= 0 &&
|
||||
Comparer<object>.Default.Compare(actual, secondary) <= 0),
|
||||
_ => false,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
public partial class ConditionGroup : ObservableObject
|
||||
{
|
||||
[ObservableProperty]
|
||||
private string name = string.Empty;
|
||||
|
||||
[ObservableProperty]
|
||||
private LogicalOperator logicalOperator = LogicalOperator.And;
|
||||
|
||||
[ObservableProperty]
|
||||
private List<ProfileCondition> conditions = new();
|
||||
|
||||
[ObservableProperty]
|
||||
private List<ConditionGroup> subGroups = new();
|
||||
|
||||
[ObservableProperty]
|
||||
private bool isEnabled = true;
|
||||
|
||||
public bool Evaluate(ProcessModel process, SystemState systemState)
|
||||
{
|
||||
if (!this.IsEnabled)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
var conditionResults = this.Conditions.Select(c => c.Evaluate(process, systemState)).ToList();
|
||||
var subGroupResults = this.SubGroups.Select(g => g.Evaluate(process, systemState)).ToList();
|
||||
var allResults = conditionResults.Concat(subGroupResults).ToList();
|
||||
|
||||
if (!allResults.Any())
|
||||
{
|
||||
return true; // No conditions means always true
|
||||
}
|
||||
|
||||
return this.LogicalOperator switch
|
||||
{
|
||||
LogicalOperator.And => allResults.All(r => r),
|
||||
LogicalOperator.Or => allResults.Any(r => r),
|
||||
LogicalOperator.Not => !allResults.All(r => r),
|
||||
_ => false,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
public partial class ConditionalProcessProfile : ProfileModel
|
||||
{
|
||||
[ObservableProperty]
|
||||
private List<ConditionGroup> conditionGroups = new();
|
||||
|
||||
[ObservableProperty]
|
||||
private TimeSpan autoApplyDelay = TimeSpan.FromSeconds(5);
|
||||
|
||||
[ObservableProperty]
|
||||
private int priority = 0; // Higher priority profiles are applied first
|
||||
|
||||
[ObservableProperty]
|
||||
private bool isAutoApplyEnabled = true;
|
||||
|
||||
[ObservableProperty]
|
||||
private DateTime lastEvaluated = DateTime.MinValue;
|
||||
|
||||
[ObservableProperty]
|
||||
private DateTime lastApplied = DateTime.MinValue;
|
||||
|
||||
[ObservableProperty]
|
||||
private bool wasLastEvaluationTrue = false;
|
||||
|
||||
[ObservableProperty]
|
||||
private string lastEvaluationReason = string.Empty;
|
||||
|
||||
public bool ShouldApply(ProcessModel process, SystemState systemState)
|
||||
{
|
||||
if (!this.IsAutoApplyEnabled)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
this.LastEvaluated = DateTime.UtcNow;
|
||||
|
||||
try
|
||||
{
|
||||
// If no condition groups, always apply (like regular profile)
|
||||
if (!this.ConditionGroups.Any())
|
||||
{
|
||||
this.WasLastEvaluationTrue = true;
|
||||
this.LastEvaluationReason = "No conditions defined";
|
||||
return true;
|
||||
}
|
||||
|
||||
// Evaluate all condition groups (AND logic between groups)
|
||||
var results = this.ConditionGroups.Select(g => g.Evaluate(process, systemState)).ToList();
|
||||
var shouldApply = results.All(r => r);
|
||||
|
||||
this.WasLastEvaluationTrue = shouldApply;
|
||||
this.LastEvaluationReason = shouldApply
|
||||
? "All condition groups satisfied"
|
||||
: $"Failed conditions: {string.Join(", ", this.ConditionGroups.Where((g, i) => !results[i]).Select(g => g.Name))}";
|
||||
|
||||
return shouldApply;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
this.WasLastEvaluationTrue = false;
|
||||
this.LastEvaluationReason = $"Evaluation error: {ex.Message}";
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public bool CanApplyNow()
|
||||
{
|
||||
return DateTime.UtcNow - this.LastApplied >= this.AutoApplyDelay;
|
||||
}
|
||||
|
||||
public void MarkAsApplied()
|
||||
{
|
||||
this.LastApplied = DateTime.UtcNow;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+83
-123
@@ -1,123 +1,83 @@
|
||||
/*
|
||||
* ThreadPilot - Advanced Windows Process and Power Plan Manager
|
||||
* Copyright (C) 2025 Prime Build
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published by
|
||||
* the Free Software Foundation, version 3 only.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
namespace ThreadPilot.Models.Core
|
||||
{
|
||||
using System;
|
||||
using System.ComponentModel;
|
||||
|
||||
/// <summary>
|
||||
/// Base interface for all domain models.
|
||||
/// </summary>
|
||||
public interface IModel : INotifyPropertyChanged
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets unique identifier for the model instance.
|
||||
/// </summary>
|
||||
string Id { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets timestamp when the model was created.
|
||||
/// </summary>
|
||||
DateTime CreatedAt { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets timestamp when the model was last updated.
|
||||
/// </summary>
|
||||
DateTime UpdatedAt { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Validate the model state.
|
||||
/// </summary>
|
||||
ValidationResult Validate();
|
||||
|
||||
/// <summary>
|
||||
/// Create a copy of the model.
|
||||
/// </summary>
|
||||
IModel Clone();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Validation result for model validation.
|
||||
/// </summary>
|
||||
public class ValidationResult
|
||||
{
|
||||
public bool IsValid { get; }
|
||||
|
||||
public string[] Errors { get; }
|
||||
|
||||
public ValidationResult(bool isValid, params string[] errors)
|
||||
{
|
||||
this.IsValid = isValid;
|
||||
this.Errors = errors ?? Array.Empty<string>();
|
||||
}
|
||||
|
||||
public static ValidationResult Success() => new(true);
|
||||
|
||||
public static ValidationResult Failure(params string[] errors) => new(false, errors);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Base implementation for domain models.
|
||||
/// </summary>
|
||||
public abstract class BaseModel : IModel
|
||||
{
|
||||
public string Id { get; protected set; }
|
||||
|
||||
public DateTime CreatedAt { get; protected set; }
|
||||
|
||||
public DateTime UpdatedAt { get; protected set; }
|
||||
|
||||
public event PropertyChangedEventHandler? PropertyChanged;
|
||||
|
||||
protected BaseModel()
|
||||
{
|
||||
this.Id = Guid.NewGuid().ToString();
|
||||
this.CreatedAt = DateTime.UtcNow;
|
||||
this.UpdatedAt = DateTime.UtcNow;
|
||||
}
|
||||
|
||||
protected BaseModel(string id)
|
||||
{
|
||||
this.Id = id ?? throw new ArgumentNullException(nameof(id));
|
||||
this.CreatedAt = DateTime.UtcNow;
|
||||
this.UpdatedAt = DateTime.UtcNow;
|
||||
}
|
||||
|
||||
protected virtual void OnPropertyChanged(string propertyName)
|
||||
{
|
||||
this.UpdatedAt = DateTime.UtcNow;
|
||||
this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
|
||||
}
|
||||
|
||||
protected bool SetProperty<T>(ref T field, T value, string propertyName)
|
||||
{
|
||||
if (Equals(field, value))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
field = value;
|
||||
this.OnPropertyChanged(propertyName);
|
||||
return true;
|
||||
}
|
||||
|
||||
public abstract ValidationResult Validate();
|
||||
|
||||
public abstract IModel Clone();
|
||||
}
|
||||
}
|
||||
|
||||
namespace ThreadPilot.Models.Core
|
||||
{
|
||||
using System;
|
||||
using System.ComponentModel;
|
||||
|
||||
public interface IModel : INotifyPropertyChanged
|
||||
{
|
||||
string Id { get; }
|
||||
|
||||
DateTime CreatedAt { get; }
|
||||
|
||||
DateTime UpdatedAt { get; }
|
||||
|
||||
ValidationResult Validate();
|
||||
|
||||
IModel Clone();
|
||||
}
|
||||
|
||||
public class ValidationResult
|
||||
{
|
||||
public bool IsValid { get; }
|
||||
|
||||
public string[] Errors { get; }
|
||||
|
||||
public ValidationResult(bool isValid, params string[] errors)
|
||||
{
|
||||
this.IsValid = isValid;
|
||||
this.Errors = errors ?? Array.Empty<string>();
|
||||
}
|
||||
|
||||
public static ValidationResult Success() => new(true);
|
||||
|
||||
public static ValidationResult Failure(params string[] errors) => new(false, errors);
|
||||
}
|
||||
|
||||
public abstract class BaseModel : IModel
|
||||
{
|
||||
public string Id { get; protected set; }
|
||||
|
||||
public DateTime CreatedAt { get; protected set; }
|
||||
|
||||
public DateTime UpdatedAt { get; protected set; }
|
||||
|
||||
public event PropertyChangedEventHandler? PropertyChanged;
|
||||
|
||||
protected BaseModel()
|
||||
{
|
||||
this.Id = Guid.NewGuid().ToString();
|
||||
this.CreatedAt = DateTime.UtcNow;
|
||||
this.UpdatedAt = DateTime.UtcNow;
|
||||
}
|
||||
|
||||
protected BaseModel(string id)
|
||||
{
|
||||
this.Id = id ?? throw new ArgumentNullException(nameof(id));
|
||||
this.CreatedAt = DateTime.UtcNow;
|
||||
this.UpdatedAt = DateTime.UtcNow;
|
||||
}
|
||||
|
||||
protected virtual void OnPropertyChanged(string propertyName)
|
||||
{
|
||||
this.UpdatedAt = DateTime.UtcNow;
|
||||
this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
|
||||
}
|
||||
|
||||
protected bool SetProperty<T>(ref T field, T value, string propertyName)
|
||||
{
|
||||
if (Equals(field, value))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
field = value;
|
||||
this.OnPropertyChanged(propertyName);
|
||||
return true;
|
||||
}
|
||||
|
||||
public abstract ValidationResult Validate();
|
||||
|
||||
public abstract IModel Clone();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+123
-166
@@ -1,166 +1,123 @@
|
||||
/*
|
||||
* ThreadPilot - Advanced Windows Process and Power Plan Manager
|
||||
* Copyright (C) 2025 Prime Build
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published by
|
||||
* the Free Software Foundation, version 3 only.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
namespace ThreadPilot.Models
|
||||
{
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.ObjectModel;
|
||||
using System.Linq;
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
|
||||
/// <summary>
|
||||
/// Represents a reusable CPU core affinity mask
|
||||
/// Based on CPUSetSetter's LogicalProcessorMask.
|
||||
/// </summary>
|
||||
public partial class CoreMask : ObservableObject
|
||||
{
|
||||
[ObservableProperty]
|
||||
private string id = Guid.NewGuid().ToString();
|
||||
|
||||
[ObservableProperty]
|
||||
private string name = string.Empty;
|
||||
|
||||
[ObservableProperty]
|
||||
private string description = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets array of boolean values, one per logical core.
|
||||
/// </summary>
|
||||
public ObservableCollection<bool> BoolMask { get; set; } = new();
|
||||
|
||||
public int ProfileSchemaVersion { get; set; } = CpuAffinityProfileSchemaVersions.Legacy;
|
||||
|
||||
public CpuSelection? CpuSelection { get; set; }
|
||||
|
||||
public CpuSelectionMigrationMetadata? CpuSelectionMigration { get; set; }
|
||||
|
||||
[ObservableProperty]
|
||||
private bool isDefault = false;
|
||||
|
||||
[ObservableProperty]
|
||||
private bool isEnabled = true;
|
||||
|
||||
[ObservableProperty]
|
||||
private DateTime createdAt = DateTime.UtcNow;
|
||||
|
||||
[ObservableProperty]
|
||||
private DateTime updatedAt = DateTime.UtcNow;
|
||||
|
||||
/// <summary>
|
||||
/// Gets a value indicating whether special mask that allows all cores (no restrictions).
|
||||
/// </summary>
|
||||
public bool IsNoMask => this.BoolMask.All(b => b);
|
||||
|
||||
/// <summary>
|
||||
/// Gets the count of selected cores.
|
||||
/// </summary>
|
||||
public int SelectedCoreCount => this.BoolMask.Count(b => b);
|
||||
|
||||
/// <summary>
|
||||
/// Converts the boolean mask to a legacy 64-bit processor affinity value.
|
||||
/// This is only safe for single processor-group selections below CPU 64;
|
||||
/// topology-aware apply paths must prefer <see cref="CpuSelection"/>.
|
||||
/// </summary>
|
||||
public long ToProcessorAffinity()
|
||||
{
|
||||
long affinity = 0;
|
||||
for (int i = 0; i < this.BoolMask.Count; i++)
|
||||
{
|
||||
if (this.BoolMask[i])
|
||||
{
|
||||
affinity |= 1L << i;
|
||||
}
|
||||
}
|
||||
return affinity;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a CoreMask from a processor affinity value.
|
||||
/// </summary>
|
||||
public static CoreMask FromProcessorAffinity(long affinity, int coreCount, string name = "Custom")
|
||||
{
|
||||
var mask = new CoreMask { Name = name };
|
||||
for (int i = 0; i < coreCount; i++)
|
||||
{
|
||||
mask.BoolMask.Add(((affinity >> i) & 1) == 1);
|
||||
}
|
||||
return mask;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a mask with all cores enabled.
|
||||
/// </summary>
|
||||
public static CoreMask CreateAllCoresMask(int coreCount)
|
||||
{
|
||||
var mask = new CoreMask
|
||||
{
|
||||
Name = "All Cores",
|
||||
Description = "Use all available CPU cores",
|
||||
IsDefault = true,
|
||||
};
|
||||
|
||||
for (int i = 0; i < coreCount; i++)
|
||||
{
|
||||
mask.BoolMask.Add(true);
|
||||
}
|
||||
|
||||
return mask;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a mask with no cores (empty mask, for deletion purposes).
|
||||
/// </summary>
|
||||
public static CoreMask CreateNoMask()
|
||||
{
|
||||
return new CoreMask
|
||||
{
|
||||
Name = "No Restriction",
|
||||
Description = "Process can use all cores",
|
||||
IsDefault = false,
|
||||
};
|
||||
}
|
||||
|
||||
public CoreMask Clone()
|
||||
{
|
||||
var cloned = new CoreMask
|
||||
{
|
||||
Id = Guid.NewGuid().ToString(),
|
||||
Name = this.Name + " (Copy)",
|
||||
Description = this.Description,
|
||||
IsEnabled = this.IsEnabled,
|
||||
IsDefault = false,
|
||||
ProfileSchemaVersion = this.ProfileSchemaVersion,
|
||||
CpuSelection = this.CpuSelection,
|
||||
CpuSelectionMigration = this.CpuSelectionMigration,
|
||||
CreatedAt = DateTime.UtcNow,
|
||||
UpdatedAt = DateTime.UtcNow,
|
||||
};
|
||||
|
||||
foreach (var bit in this.BoolMask)
|
||||
{
|
||||
cloned.BoolMask.Add(bit);
|
||||
}
|
||||
|
||||
return cloned;
|
||||
}
|
||||
|
||||
public override string ToString()
|
||||
{
|
||||
return $"{this.Name} ({this.SelectedCoreCount}/{this.BoolMask.Count} cores)";
|
||||
}
|
||||
}
|
||||
}
|
||||
namespace ThreadPilot.Models
|
||||
{
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.ObjectModel;
|
||||
using System.Linq;
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
|
||||
public partial class CoreMask : ObservableObject
|
||||
{
|
||||
[ObservableProperty]
|
||||
private string id = Guid.NewGuid().ToString();
|
||||
|
||||
[ObservableProperty]
|
||||
private string name = string.Empty;
|
||||
|
||||
[ObservableProperty]
|
||||
private string description = string.Empty;
|
||||
|
||||
public ObservableCollection<bool> BoolMask { get; set; } = new();
|
||||
|
||||
public int ProfileSchemaVersion { get; set; } = CpuAffinityProfileSchemaVersions.Legacy;
|
||||
|
||||
public CpuSelection? CpuSelection { get; set; }
|
||||
|
||||
public CpuSelectionMigrationMetadata? CpuSelectionMigration { get; set; }
|
||||
|
||||
[ObservableProperty]
|
||||
private bool isDefault = false;
|
||||
|
||||
[ObservableProperty]
|
||||
private bool isEnabled = true;
|
||||
|
||||
[ObservableProperty]
|
||||
private DateTime createdAt = DateTime.UtcNow;
|
||||
|
||||
[ObservableProperty]
|
||||
private DateTime updatedAt = DateTime.UtcNow;
|
||||
|
||||
public bool IsNoMask => this.BoolMask.All(b => b);
|
||||
|
||||
public int SelectedCoreCount => this.BoolMask.Count(b => b);
|
||||
|
||||
public long ToProcessorAffinity()
|
||||
{
|
||||
long affinity = 0;
|
||||
for (int i = 0; i < this.BoolMask.Count; i++)
|
||||
{
|
||||
if (this.BoolMask[i])
|
||||
{
|
||||
affinity |= 1L << i;
|
||||
}
|
||||
}
|
||||
return affinity;
|
||||
}
|
||||
|
||||
public static CoreMask FromProcessorAffinity(long affinity, int coreCount, string name = "Custom")
|
||||
{
|
||||
var mask = new CoreMask { Name = name };
|
||||
for (int i = 0; i < coreCount; i++)
|
||||
{
|
||||
mask.BoolMask.Add(((affinity >> i) & 1) == 1);
|
||||
}
|
||||
return mask;
|
||||
}
|
||||
|
||||
public static CoreMask CreateAllCoresMask(int coreCount)
|
||||
{
|
||||
var mask = new CoreMask
|
||||
{
|
||||
Name = "All Cores",
|
||||
Description = "Use all available CPU cores",
|
||||
IsDefault = true,
|
||||
};
|
||||
|
||||
for (int i = 0; i < coreCount; i++)
|
||||
{
|
||||
mask.BoolMask.Add(true);
|
||||
}
|
||||
|
||||
return mask;
|
||||
}
|
||||
|
||||
public static CoreMask CreateNoMask()
|
||||
{
|
||||
return new CoreMask
|
||||
{
|
||||
Name = "No Restriction",
|
||||
Description = "Process can use all cores",
|
||||
IsDefault = false,
|
||||
};
|
||||
}
|
||||
|
||||
public CoreMask Clone()
|
||||
{
|
||||
var cloned = new CoreMask
|
||||
{
|
||||
Id = Guid.NewGuid().ToString(),
|
||||
Name = this.Name + " (Copy)",
|
||||
Description = this.Description,
|
||||
IsEnabled = this.IsEnabled,
|
||||
IsDefault = false,
|
||||
ProfileSchemaVersion = this.ProfileSchemaVersion,
|
||||
CpuSelection = this.CpuSelection,
|
||||
CpuSelectionMigration = this.CpuSelectionMigration,
|
||||
CreatedAt = DateTime.UtcNow,
|
||||
UpdatedAt = DateTime.UtcNow,
|
||||
};
|
||||
|
||||
foreach (var bit in this.BoolMask)
|
||||
{
|
||||
cloned.BoolMask.Add(bit);
|
||||
}
|
||||
|
||||
return cloned;
|
||||
}
|
||||
|
||||
public override string ToString()
|
||||
{
|
||||
return $"{this.Name} ({this.SelectedCoreCount}/{this.BoolMask.Count} cores)";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,25 +1,9 @@
|
||||
/*
|
||||
* ThreadPilot - Advanced Windows Process and Power Plan Manager
|
||||
* Copyright (C) 2025 Prime Build
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published by
|
||||
* the Free Software Foundation, version 3 only.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
namespace ThreadPilot.Models
|
||||
{
|
||||
public static class CpuAffinityProfileSchemaVersions
|
||||
{
|
||||
public const int Legacy = 1;
|
||||
|
||||
public const int CpuSelection = 2;
|
||||
}
|
||||
}
|
||||
namespace ThreadPilot.Models
|
||||
{
|
||||
public static class CpuAffinityProfileSchemaVersions
|
||||
{
|
||||
public const int Legacy = 1;
|
||||
|
||||
public const int CpuSelection = 2;
|
||||
}
|
||||
}
|
||||
|
||||
+27
-46
@@ -1,46 +1,27 @@
|
||||
/*
|
||||
* ThreadPilot - Advanced Windows Process and Power Plan Manager
|
||||
* Copyright (C) 2025 Prime Build
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published by
|
||||
* the Free Software Foundation, version 3 only.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
namespace ThreadPilot.Models
|
||||
{
|
||||
/// <summary>
|
||||
/// Topology-aware CPU affinity preset generated from a CPU topology snapshot.
|
||||
/// </summary>
|
||||
public sealed record CpuPreset
|
||||
{
|
||||
public string PresetId { get; init; } = string.Empty;
|
||||
|
||||
public string Name { get; init; } = string.Empty;
|
||||
|
||||
public string Description { get; init; } = string.Empty;
|
||||
|
||||
public CpuSelection Selection { get; init; } = new();
|
||||
|
||||
public string Reason { get; init; } = string.Empty;
|
||||
|
||||
public string? SourcePresetId { get; init; }
|
||||
|
||||
public string? Warning { get; init; }
|
||||
|
||||
public CpuTopologySignature? GeneratedByTopologySignature { get; init; }
|
||||
|
||||
public bool IsUserEditable { get; init; } = true;
|
||||
|
||||
public bool IsGenerated { get; init; } = true;
|
||||
|
||||
public bool ReviewRequired { get; init; }
|
||||
}
|
||||
}
|
||||
namespace ThreadPilot.Models
|
||||
{
|
||||
public sealed record CpuPreset
|
||||
{
|
||||
public string PresetId { get; init; } = string.Empty;
|
||||
|
||||
public string Name { get; init; } = string.Empty;
|
||||
|
||||
public string Description { get; init; } = string.Empty;
|
||||
|
||||
public CpuSelection Selection { get; init; } = new();
|
||||
|
||||
public string Reason { get; init; } = string.Empty;
|
||||
|
||||
public string? SourcePresetId { get; init; }
|
||||
|
||||
public string? Warning { get; init; }
|
||||
|
||||
public CpuTopologySignature? GeneratedByTopologySignature { get; init; }
|
||||
|
||||
public bool IsUserEditable { get; init; } = true;
|
||||
|
||||
public bool IsGenerated { get; init; } = true;
|
||||
|
||||
public bool ReviewRequired { get; init; }
|
||||
}
|
||||
}
|
||||
|
||||
+346
-378
@@ -1,378 +1,346 @@
|
||||
/*
|
||||
* ThreadPilot - Advanced Windows Process and Power Plan Manager
|
||||
* Copyright (C) 2025 Prime Build
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published by
|
||||
* the Free Software Foundation, version 3 only.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
namespace ThreadPilot.Models
|
||||
{
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
|
||||
/// <summary>
|
||||
/// Identifies a logical processor without relying on a legacy 64-bit affinity mask.
|
||||
/// </summary>
|
||||
public readonly record struct ProcessorRef(ushort Group, byte LogicalProcessorNumber, int GlobalIndex);
|
||||
|
||||
/// <summary>
|
||||
/// Stable signature used to determine whether a persisted CPU selection was created for the current topology.
|
||||
/// </summary>
|
||||
public sealed record CpuTopologySignature
|
||||
{
|
||||
public string CpuBrand { get; init; } = "Unknown";
|
||||
|
||||
public int LogicalProcessorCount { get; init; }
|
||||
|
||||
public int PhysicalCoreCount { get; init; }
|
||||
|
||||
public int ProcessorGroupCount { get; init; } = 1;
|
||||
|
||||
public int NumaNodeCount { get; init; }
|
||||
|
||||
public int LastLevelCacheGroupCount { get; init; }
|
||||
|
||||
public int PackageCount { get; init; }
|
||||
|
||||
public string Source { get; init; } = "Unknown";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Metadata that explains how a CPU selection was built and whether it can be represented by legacy APIs.
|
||||
/// </summary>
|
||||
public sealed record CpuSelectionMetadata
|
||||
{
|
||||
public CpuTopologySignature? TopologySignature { get; init; }
|
||||
|
||||
public bool CreatedFromLegacyAffinityMask { get; init; }
|
||||
|
||||
public bool ContainsLogicalProcessorsBeyondLegacyMask { get; init; }
|
||||
|
||||
public bool HasMultipleProcessorGroups { get; init; }
|
||||
|
||||
public int ProcessorGroupCount { get; init; }
|
||||
|
||||
public int MaxGlobalLogicalProcessorIndex { get; init; } = -1;
|
||||
|
||||
public string SelectionReason { get; init; } = string.Empty;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Lightweight topology snapshot used by the CpuSelection migration layer.
|
||||
/// Runtime topology detection will populate this in a later phase.
|
||||
/// </summary>
|
||||
public sealed class CpuTopologySnapshot
|
||||
{
|
||||
private readonly IReadOnlyDictionary<ProcessorRef, uint> cpuSetIdsByProcessor;
|
||||
private readonly IReadOnlyDictionary<ProcessorRef, byte> efficiencyClassesByProcessor;
|
||||
private readonly IReadOnlyDictionary<ProcessorRef, int> coreIndexesByProcessor;
|
||||
private readonly IReadOnlyDictionary<ProcessorRef, int> numaNodeIndexesByProcessor;
|
||||
private readonly IReadOnlyDictionary<ProcessorRef, int> lastLevelCacheIndexesByProcessor;
|
||||
private readonly IReadOnlyDictionary<ProcessorRef, int> packageIndexesByProcessor;
|
||||
private readonly IReadOnlyDictionary<ProcessorRef, IReadOnlyList<int>> smtSiblingGlobalIndexesByProcessor;
|
||||
|
||||
private CpuTopologySnapshot(
|
||||
IReadOnlyList<ProcessorRef> logicalProcessors,
|
||||
IReadOnlyDictionary<ProcessorRef, uint> cpuSetIdsByProcessor,
|
||||
IReadOnlyDictionary<ProcessorRef, byte> efficiencyClassesByProcessor,
|
||||
IReadOnlyDictionary<ProcessorRef, int> coreIndexesByProcessor,
|
||||
IReadOnlyDictionary<ProcessorRef, int> numaNodeIndexesByProcessor,
|
||||
IReadOnlyDictionary<ProcessorRef, int> lastLevelCacheIndexesByProcessor,
|
||||
IReadOnlyDictionary<ProcessorRef, int> packageIndexesByProcessor,
|
||||
IReadOnlyDictionary<ProcessorRef, IReadOnlyList<int>> smtSiblingGlobalIndexesByProcessor,
|
||||
CpuTopologySignature signature)
|
||||
{
|
||||
this.LogicalProcessors = logicalProcessors;
|
||||
this.cpuSetIdsByProcessor = cpuSetIdsByProcessor;
|
||||
this.efficiencyClassesByProcessor = efficiencyClassesByProcessor;
|
||||
this.coreIndexesByProcessor = coreIndexesByProcessor;
|
||||
this.numaNodeIndexesByProcessor = numaNodeIndexesByProcessor;
|
||||
this.lastLevelCacheIndexesByProcessor = lastLevelCacheIndexesByProcessor;
|
||||
this.packageIndexesByProcessor = packageIndexesByProcessor;
|
||||
this.smtSiblingGlobalIndexesByProcessor = smtSiblingGlobalIndexesByProcessor;
|
||||
this.Signature = signature;
|
||||
}
|
||||
|
||||
public IReadOnlyList<ProcessorRef> LogicalProcessors { get; }
|
||||
|
||||
public CpuTopologySignature Signature { get; }
|
||||
|
||||
public static CpuTopologySnapshot Create(
|
||||
IEnumerable<ProcessorRef> logicalProcessors,
|
||||
IReadOnlyDictionary<ProcessorRef, uint>? cpuSetIds = null,
|
||||
IReadOnlyDictionary<ProcessorRef, byte>? efficiencyClasses = null,
|
||||
CpuTopologySignature? signature = null,
|
||||
IReadOnlyDictionary<ProcessorRef, int>? coreIndexes = null,
|
||||
IReadOnlyDictionary<ProcessorRef, int>? numaNodeIndexes = null,
|
||||
IReadOnlyDictionary<ProcessorRef, int>? lastLevelCacheIndexes = null,
|
||||
IReadOnlyDictionary<ProcessorRef, int>? packageIndexes = null,
|
||||
IReadOnlyDictionary<ProcessorRef, IReadOnlyList<int>>? smtSiblingGlobalIndexes = null)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(logicalProcessors);
|
||||
|
||||
var processors = logicalProcessors
|
||||
.Distinct()
|
||||
.OrderBy(processor => processor.GlobalIndex)
|
||||
.ThenBy(processor => processor.Group)
|
||||
.ThenBy(processor => processor.LogicalProcessorNumber)
|
||||
.ToList();
|
||||
|
||||
var duplicatedGlobalIndexes = processors
|
||||
.GroupBy(processor => processor.GlobalIndex)
|
||||
.Where(group => group.Count() > 1)
|
||||
.Select(group => group.Key)
|
||||
.ToList();
|
||||
if (duplicatedGlobalIndexes.Count > 0)
|
||||
{
|
||||
throw new ArgumentException(
|
||||
$"GlobalIndex must be unique in a CPU topology snapshot. Duplicates: {string.Join(", ", duplicatedGlobalIndexes)}.",
|
||||
nameof(logicalProcessors));
|
||||
}
|
||||
|
||||
var processorSet = processors.ToHashSet();
|
||||
var cpuSetMap = cpuSetIds?
|
||||
.Where(kvp => processorSet.Contains(kvp.Key))
|
||||
.ToDictionary(kvp => kvp.Key, kvp => kvp.Value)
|
||||
?? new Dictionary<ProcessorRef, uint>();
|
||||
|
||||
var efficiencyClassMap = efficiencyClasses?
|
||||
.Where(kvp => processorSet.Contains(kvp.Key))
|
||||
.ToDictionary(kvp => kvp.Key, kvp => kvp.Value)
|
||||
?? new Dictionary<ProcessorRef, byte>();
|
||||
|
||||
var coreIndexMap = FilterKnownProcessorMap(coreIndexes, processorSet);
|
||||
var numaNodeIndexMap = FilterKnownProcessorMap(numaNodeIndexes, processorSet);
|
||||
var lastLevelCacheIndexMap = FilterKnownProcessorMap(lastLevelCacheIndexes, processorSet);
|
||||
var packageIndexMap = FilterKnownProcessorMap(packageIndexes, processorSet);
|
||||
var knownGlobalIndexes = processors.Select(processor => processor.GlobalIndex).ToHashSet();
|
||||
var smtSiblingMap = smtSiblingGlobalIndexes?
|
||||
.Where(kvp => processorSet.Contains(kvp.Key))
|
||||
.ToDictionary(
|
||||
kvp => kvp.Key,
|
||||
kvp => (IReadOnlyList<int>)kvp.Value
|
||||
.Where(knownGlobalIndexes.Contains)
|
||||
.Distinct()
|
||||
.OrderBy(index => index)
|
||||
.ToList())
|
||||
?? new Dictionary<ProcessorRef, IReadOnlyList<int>>();
|
||||
|
||||
var resolvedSignature = signature ?? new CpuTopologySignature
|
||||
{
|
||||
LogicalProcessorCount = processors.Count,
|
||||
PhysicalCoreCount = coreIndexMap.Count == 0
|
||||
? processors.Count
|
||||
: coreIndexMap.Values.Distinct().Count(),
|
||||
ProcessorGroupCount = processors.Select(processor => processor.Group).Distinct().Count(),
|
||||
NumaNodeCount = numaNodeIndexMap.Values.Distinct().Count(),
|
||||
LastLevelCacheGroupCount = lastLevelCacheIndexMap.Values.Distinct().Count(),
|
||||
PackageCount = packageIndexMap.Values.Distinct().Count(),
|
||||
Source = "Snapshot",
|
||||
};
|
||||
|
||||
return new CpuTopologySnapshot(
|
||||
processors,
|
||||
cpuSetMap,
|
||||
efficiencyClassMap,
|
||||
coreIndexMap,
|
||||
numaNodeIndexMap,
|
||||
lastLevelCacheIndexMap,
|
||||
packageIndexMap,
|
||||
smtSiblingMap,
|
||||
resolvedSignature);
|
||||
}
|
||||
|
||||
public bool TryGetCpuSetId(ProcessorRef processor, out uint cpuSetId) =>
|
||||
this.cpuSetIdsByProcessor.TryGetValue(processor, out cpuSetId);
|
||||
|
||||
public bool TryGetEfficiencyClass(ProcessorRef processor, out byte efficiencyClass) =>
|
||||
this.efficiencyClassesByProcessor.TryGetValue(processor, out efficiencyClass);
|
||||
|
||||
public bool TryGetCoreIndex(ProcessorRef processor, out int coreIndex) =>
|
||||
this.coreIndexesByProcessor.TryGetValue(processor, out coreIndex);
|
||||
|
||||
public bool TryGetNumaNodeIndex(ProcessorRef processor, out int numaNodeIndex) =>
|
||||
this.numaNodeIndexesByProcessor.TryGetValue(processor, out numaNodeIndex);
|
||||
|
||||
public bool TryGetLastLevelCacheIndex(ProcessorRef processor, out int lastLevelCacheIndex) =>
|
||||
this.lastLevelCacheIndexesByProcessor.TryGetValue(processor, out lastLevelCacheIndex);
|
||||
|
||||
public bool TryGetPackageIndex(ProcessorRef processor, out int packageIndex) =>
|
||||
this.packageIndexesByProcessor.TryGetValue(processor, out packageIndex);
|
||||
|
||||
public IReadOnlyList<int> GetSmtSiblingGlobalIndexes(ProcessorRef processor) =>
|
||||
this.smtSiblingGlobalIndexesByProcessor.TryGetValue(processor, out var siblings)
|
||||
? siblings
|
||||
: [];
|
||||
|
||||
public byte? GetPerformanceEfficiencyClass()
|
||||
{
|
||||
if (this.efficiencyClassesByProcessor.Count == 0)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
return this.efficiencyClassesByProcessor.Values.Max();
|
||||
}
|
||||
|
||||
private static Dictionary<ProcessorRef, int> FilterKnownProcessorMap(
|
||||
IReadOnlyDictionary<ProcessorRef, int>? source,
|
||||
HashSet<ProcessorRef> processorSet)
|
||||
{
|
||||
return source?
|
||||
.Where(kvp => processorSet.Contains(kvp.Key))
|
||||
.ToDictionary(kvp => kvp.Key, kvp => kvp.Value)
|
||||
?? new Dictionary<ProcessorRef, int>();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Group-aware CPU selection model used by new persistence and migration code.
|
||||
/// </summary>
|
||||
public sealed record CpuSelection
|
||||
{
|
||||
public List<uint> CpuSetIds { get; init; } = new();
|
||||
|
||||
public List<ProcessorRef> LogicalProcessors { get; init; } = new();
|
||||
|
||||
public List<int> GlobalLogicalProcessorIndexes { get; init; } = new();
|
||||
|
||||
public CpuSelectionMetadata Metadata { get; init; } = new();
|
||||
|
||||
public static CpuSelection FromProcessors(
|
||||
IEnumerable<ProcessorRef> processors,
|
||||
CpuTopologySnapshot topology,
|
||||
string selectionReason = "")
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(processors);
|
||||
ArgumentNullException.ThrowIfNull(topology);
|
||||
|
||||
var selectedProcessors = processors
|
||||
.Distinct()
|
||||
.OrderBy(processor => processor.GlobalIndex)
|
||||
.ThenBy(processor => processor.Group)
|
||||
.ThenBy(processor => processor.LogicalProcessorNumber)
|
||||
.ToList();
|
||||
|
||||
var topologyProcessors = topology.LogicalProcessors.ToHashSet();
|
||||
var missingProcessors = selectedProcessors
|
||||
.Where(processor => !topologyProcessors.Contains(processor))
|
||||
.ToList();
|
||||
if (missingProcessors.Count > 0)
|
||||
{
|
||||
throw new ArgumentException(
|
||||
$"CPU selection contains processor(s) not present in the topology: {string.Join(", ", missingProcessors)}.",
|
||||
nameof(processors));
|
||||
}
|
||||
|
||||
var cpuSetIds = selectedProcessors
|
||||
.Select(processor => topology.TryGetCpuSetId(processor, out var cpuSetId) ? (uint?)cpuSetId : null)
|
||||
.Where(cpuSetId => cpuSetId.HasValue)
|
||||
.Select(cpuSetId => cpuSetId!.Value)
|
||||
.Distinct()
|
||||
.OrderBy(cpuSetId => cpuSetId)
|
||||
.ToList();
|
||||
|
||||
return new CpuSelection
|
||||
{
|
||||
CpuSetIds = cpuSetIds,
|
||||
LogicalProcessors = selectedProcessors,
|
||||
GlobalLogicalProcessorIndexes = selectedProcessors
|
||||
.Select(processor => processor.GlobalIndex)
|
||||
.Distinct()
|
||||
.OrderBy(index => index)
|
||||
.ToList(),
|
||||
Metadata = CreateMetadata(selectedProcessors, topology.Signature, createdFromLegacyAffinityMask: false, selectionReason),
|
||||
};
|
||||
}
|
||||
|
||||
public static CpuSelection FromLegacyAffinityMask(long mask, CpuTopologySnapshot topology)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(topology);
|
||||
|
||||
var unsignedMask = unchecked((ulong)mask);
|
||||
var selectedIndexes = new HashSet<int>();
|
||||
for (var bit = 0; bit < 64; bit++)
|
||||
{
|
||||
if ((unsignedMask & (1UL << bit)) != 0)
|
||||
{
|
||||
selectedIndexes.Add(bit);
|
||||
}
|
||||
}
|
||||
|
||||
var selectedProcessors = topology.LogicalProcessors
|
||||
.Where(processor => selectedIndexes.Contains(processor.GlobalIndex))
|
||||
.ToList();
|
||||
|
||||
var selection = FromProcessors(selectedProcessors, topology, "Migrated from legacy affinity mask");
|
||||
return selection with
|
||||
{
|
||||
Metadata = CreateMetadata(
|
||||
selection.LogicalProcessors,
|
||||
topology.Signature,
|
||||
createdFromLegacyAffinityMask: true,
|
||||
"Migrated from legacy affinity mask"),
|
||||
};
|
||||
}
|
||||
|
||||
public static long? ToLegacyAffinityMaskOrNull(CpuSelection selection)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(selection);
|
||||
|
||||
if (selection.LogicalProcessors.Any(processor => processor.GlobalIndex >= 64))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
if (selection.LogicalProcessors.Select(processor => processor.Group).Distinct().Count() > 1)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
long mask = 0;
|
||||
foreach (var processor in selection.LogicalProcessors)
|
||||
{
|
||||
if (processor.GlobalIndex < 0)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
mask |= 1L << processor.GlobalIndex;
|
||||
}
|
||||
|
||||
return mask;
|
||||
}
|
||||
|
||||
private static CpuSelectionMetadata CreateMetadata(
|
||||
IReadOnlyCollection<ProcessorRef> processors,
|
||||
CpuTopologySignature signature,
|
||||
bool createdFromLegacyAffinityMask,
|
||||
string selectionReason)
|
||||
{
|
||||
var groups = processors.Select(processor => processor.Group).Distinct().ToList();
|
||||
var maxGlobalIndex = processors.Count == 0
|
||||
? -1
|
||||
: processors.Max(processor => processor.GlobalIndex);
|
||||
|
||||
return new CpuSelectionMetadata
|
||||
{
|
||||
TopologySignature = signature,
|
||||
CreatedFromLegacyAffinityMask = createdFromLegacyAffinityMask,
|
||||
ContainsLogicalProcessorsBeyondLegacyMask = maxGlobalIndex >= 64,
|
||||
HasMultipleProcessorGroups = groups.Count > 1,
|
||||
ProcessorGroupCount = groups.Count,
|
||||
MaxGlobalLogicalProcessorIndex = maxGlobalIndex,
|
||||
SelectionReason = selectionReason,
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
namespace ThreadPilot.Models
|
||||
{
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
|
||||
public readonly record struct ProcessorRef(ushort Group, byte LogicalProcessorNumber, int GlobalIndex);
|
||||
|
||||
public sealed record CpuTopologySignature
|
||||
{
|
||||
public string CpuBrand { get; init; } = "Unknown";
|
||||
|
||||
public int LogicalProcessorCount { get; init; }
|
||||
|
||||
public int PhysicalCoreCount { get; init; }
|
||||
|
||||
public int ProcessorGroupCount { get; init; } = 1;
|
||||
|
||||
public int NumaNodeCount { get; init; }
|
||||
|
||||
public int LastLevelCacheGroupCount { get; init; }
|
||||
|
||||
public int PackageCount { get; init; }
|
||||
|
||||
public string Source { get; init; } = "Unknown";
|
||||
}
|
||||
|
||||
public sealed record CpuSelectionMetadata
|
||||
{
|
||||
public CpuTopologySignature? TopologySignature { get; init; }
|
||||
|
||||
public bool CreatedFromLegacyAffinityMask { get; init; }
|
||||
|
||||
public bool ContainsLogicalProcessorsBeyondLegacyMask { get; init; }
|
||||
|
||||
public bool HasMultipleProcessorGroups { get; init; }
|
||||
|
||||
public int ProcessorGroupCount { get; init; }
|
||||
|
||||
public int MaxGlobalLogicalProcessorIndex { get; init; } = -1;
|
||||
|
||||
public string SelectionReason { get; init; } = string.Empty;
|
||||
}
|
||||
|
||||
public sealed class CpuTopologySnapshot
|
||||
{
|
||||
private readonly IReadOnlyDictionary<ProcessorRef, uint> cpuSetIdsByProcessor;
|
||||
private readonly IReadOnlyDictionary<ProcessorRef, byte> efficiencyClassesByProcessor;
|
||||
private readonly IReadOnlyDictionary<ProcessorRef, int> coreIndexesByProcessor;
|
||||
private readonly IReadOnlyDictionary<ProcessorRef, int> numaNodeIndexesByProcessor;
|
||||
private readonly IReadOnlyDictionary<ProcessorRef, int> lastLevelCacheIndexesByProcessor;
|
||||
private readonly IReadOnlyDictionary<ProcessorRef, int> packageIndexesByProcessor;
|
||||
private readonly IReadOnlyDictionary<ProcessorRef, IReadOnlyList<int>> smtSiblingGlobalIndexesByProcessor;
|
||||
|
||||
private CpuTopologySnapshot(
|
||||
IReadOnlyList<ProcessorRef> logicalProcessors,
|
||||
IReadOnlyDictionary<ProcessorRef, uint> cpuSetIdsByProcessor,
|
||||
IReadOnlyDictionary<ProcessorRef, byte> efficiencyClassesByProcessor,
|
||||
IReadOnlyDictionary<ProcessorRef, int> coreIndexesByProcessor,
|
||||
IReadOnlyDictionary<ProcessorRef, int> numaNodeIndexesByProcessor,
|
||||
IReadOnlyDictionary<ProcessorRef, int> lastLevelCacheIndexesByProcessor,
|
||||
IReadOnlyDictionary<ProcessorRef, int> packageIndexesByProcessor,
|
||||
IReadOnlyDictionary<ProcessorRef, IReadOnlyList<int>> smtSiblingGlobalIndexesByProcessor,
|
||||
CpuTopologySignature signature)
|
||||
{
|
||||
this.LogicalProcessors = logicalProcessors;
|
||||
this.cpuSetIdsByProcessor = cpuSetIdsByProcessor;
|
||||
this.efficiencyClassesByProcessor = efficiencyClassesByProcessor;
|
||||
this.coreIndexesByProcessor = coreIndexesByProcessor;
|
||||
this.numaNodeIndexesByProcessor = numaNodeIndexesByProcessor;
|
||||
this.lastLevelCacheIndexesByProcessor = lastLevelCacheIndexesByProcessor;
|
||||
this.packageIndexesByProcessor = packageIndexesByProcessor;
|
||||
this.smtSiblingGlobalIndexesByProcessor = smtSiblingGlobalIndexesByProcessor;
|
||||
this.Signature = signature;
|
||||
}
|
||||
|
||||
public IReadOnlyList<ProcessorRef> LogicalProcessors { get; }
|
||||
|
||||
public CpuTopologySignature Signature { get; }
|
||||
|
||||
public static CpuTopologySnapshot Create(
|
||||
IEnumerable<ProcessorRef> logicalProcessors,
|
||||
IReadOnlyDictionary<ProcessorRef, uint>? cpuSetIds = null,
|
||||
IReadOnlyDictionary<ProcessorRef, byte>? efficiencyClasses = null,
|
||||
CpuTopologySignature? signature = null,
|
||||
IReadOnlyDictionary<ProcessorRef, int>? coreIndexes = null,
|
||||
IReadOnlyDictionary<ProcessorRef, int>? numaNodeIndexes = null,
|
||||
IReadOnlyDictionary<ProcessorRef, int>? lastLevelCacheIndexes = null,
|
||||
IReadOnlyDictionary<ProcessorRef, int>? packageIndexes = null,
|
||||
IReadOnlyDictionary<ProcessorRef, IReadOnlyList<int>>? smtSiblingGlobalIndexes = null)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(logicalProcessors);
|
||||
|
||||
var processors = logicalProcessors
|
||||
.Distinct()
|
||||
.OrderBy(processor => processor.GlobalIndex)
|
||||
.ThenBy(processor => processor.Group)
|
||||
.ThenBy(processor => processor.LogicalProcessorNumber)
|
||||
.ToList();
|
||||
|
||||
var duplicatedGlobalIndexes = processors
|
||||
.GroupBy(processor => processor.GlobalIndex)
|
||||
.Where(group => group.Count() > 1)
|
||||
.Select(group => group.Key)
|
||||
.ToList();
|
||||
if (duplicatedGlobalIndexes.Count > 0)
|
||||
{
|
||||
throw new ArgumentException(
|
||||
$"GlobalIndex must be unique in a CPU topology snapshot. Duplicates: {string.Join(", ", duplicatedGlobalIndexes)}.",
|
||||
nameof(logicalProcessors));
|
||||
}
|
||||
|
||||
var processorSet = processors.ToHashSet();
|
||||
var cpuSetMap = cpuSetIds?
|
||||
.Where(kvp => processorSet.Contains(kvp.Key))
|
||||
.ToDictionary(kvp => kvp.Key, kvp => kvp.Value)
|
||||
?? new Dictionary<ProcessorRef, uint>();
|
||||
|
||||
var efficiencyClassMap = efficiencyClasses?
|
||||
.Where(kvp => processorSet.Contains(kvp.Key))
|
||||
.ToDictionary(kvp => kvp.Key, kvp => kvp.Value)
|
||||
?? new Dictionary<ProcessorRef, byte>();
|
||||
|
||||
var coreIndexMap = FilterKnownProcessorMap(coreIndexes, processorSet);
|
||||
var numaNodeIndexMap = FilterKnownProcessorMap(numaNodeIndexes, processorSet);
|
||||
var lastLevelCacheIndexMap = FilterKnownProcessorMap(lastLevelCacheIndexes, processorSet);
|
||||
var packageIndexMap = FilterKnownProcessorMap(packageIndexes, processorSet);
|
||||
var knownGlobalIndexes = processors.Select(processor => processor.GlobalIndex).ToHashSet();
|
||||
var smtSiblingMap = smtSiblingGlobalIndexes?
|
||||
.Where(kvp => processorSet.Contains(kvp.Key))
|
||||
.ToDictionary(
|
||||
kvp => kvp.Key,
|
||||
kvp => (IReadOnlyList<int>)kvp.Value
|
||||
.Where(knownGlobalIndexes.Contains)
|
||||
.Distinct()
|
||||
.OrderBy(index => index)
|
||||
.ToList())
|
||||
?? new Dictionary<ProcessorRef, IReadOnlyList<int>>();
|
||||
|
||||
var resolvedSignature = signature ?? new CpuTopologySignature
|
||||
{
|
||||
LogicalProcessorCount = processors.Count,
|
||||
PhysicalCoreCount = coreIndexMap.Count == 0
|
||||
? processors.Count
|
||||
: coreIndexMap.Values.Distinct().Count(),
|
||||
ProcessorGroupCount = processors.Select(processor => processor.Group).Distinct().Count(),
|
||||
NumaNodeCount = numaNodeIndexMap.Values.Distinct().Count(),
|
||||
LastLevelCacheGroupCount = lastLevelCacheIndexMap.Values.Distinct().Count(),
|
||||
PackageCount = packageIndexMap.Values.Distinct().Count(),
|
||||
Source = "Snapshot",
|
||||
};
|
||||
|
||||
return new CpuTopologySnapshot(
|
||||
processors,
|
||||
cpuSetMap,
|
||||
efficiencyClassMap,
|
||||
coreIndexMap,
|
||||
numaNodeIndexMap,
|
||||
lastLevelCacheIndexMap,
|
||||
packageIndexMap,
|
||||
smtSiblingMap,
|
||||
resolvedSignature);
|
||||
}
|
||||
|
||||
public bool TryGetCpuSetId(ProcessorRef processor, out uint cpuSetId) =>
|
||||
this.cpuSetIdsByProcessor.TryGetValue(processor, out cpuSetId);
|
||||
|
||||
public bool TryGetEfficiencyClass(ProcessorRef processor, out byte efficiencyClass) =>
|
||||
this.efficiencyClassesByProcessor.TryGetValue(processor, out efficiencyClass);
|
||||
|
||||
public bool TryGetCoreIndex(ProcessorRef processor, out int coreIndex) =>
|
||||
this.coreIndexesByProcessor.TryGetValue(processor, out coreIndex);
|
||||
|
||||
public bool TryGetNumaNodeIndex(ProcessorRef processor, out int numaNodeIndex) =>
|
||||
this.numaNodeIndexesByProcessor.TryGetValue(processor, out numaNodeIndex);
|
||||
|
||||
public bool TryGetLastLevelCacheIndex(ProcessorRef processor, out int lastLevelCacheIndex) =>
|
||||
this.lastLevelCacheIndexesByProcessor.TryGetValue(processor, out lastLevelCacheIndex);
|
||||
|
||||
public bool TryGetPackageIndex(ProcessorRef processor, out int packageIndex) =>
|
||||
this.packageIndexesByProcessor.TryGetValue(processor, out packageIndex);
|
||||
|
||||
public IReadOnlyList<int> GetSmtSiblingGlobalIndexes(ProcessorRef processor) =>
|
||||
this.smtSiblingGlobalIndexesByProcessor.TryGetValue(processor, out var siblings)
|
||||
? siblings
|
||||
: [];
|
||||
|
||||
public byte? GetPerformanceEfficiencyClass()
|
||||
{
|
||||
if (this.efficiencyClassesByProcessor.Count == 0)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
return this.efficiencyClassesByProcessor.Values.Max();
|
||||
}
|
||||
|
||||
private static Dictionary<ProcessorRef, int> FilterKnownProcessorMap(
|
||||
IReadOnlyDictionary<ProcessorRef, int>? source,
|
||||
HashSet<ProcessorRef> processorSet)
|
||||
{
|
||||
return source?
|
||||
.Where(kvp => processorSet.Contains(kvp.Key))
|
||||
.ToDictionary(kvp => kvp.Key, kvp => kvp.Value)
|
||||
?? new Dictionary<ProcessorRef, int>();
|
||||
}
|
||||
}
|
||||
|
||||
public sealed record CpuSelection
|
||||
{
|
||||
public List<uint> CpuSetIds { get; init; } = new();
|
||||
|
||||
public List<ProcessorRef> LogicalProcessors { get; init; } = new();
|
||||
|
||||
public List<int> GlobalLogicalProcessorIndexes { get; init; } = new();
|
||||
|
||||
public CpuSelectionMetadata Metadata { get; init; } = new();
|
||||
|
||||
public static CpuSelection FromProcessors(
|
||||
IEnumerable<ProcessorRef> processors,
|
||||
CpuTopologySnapshot topology,
|
||||
string selectionReason = "")
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(processors);
|
||||
ArgumentNullException.ThrowIfNull(topology);
|
||||
|
||||
var selectedProcessors = processors
|
||||
.Distinct()
|
||||
.OrderBy(processor => processor.GlobalIndex)
|
||||
.ThenBy(processor => processor.Group)
|
||||
.ThenBy(processor => processor.LogicalProcessorNumber)
|
||||
.ToList();
|
||||
|
||||
var topologyProcessors = topology.LogicalProcessors.ToHashSet();
|
||||
var missingProcessors = selectedProcessors
|
||||
.Where(processor => !topologyProcessors.Contains(processor))
|
||||
.ToList();
|
||||
if (missingProcessors.Count > 0)
|
||||
{
|
||||
throw new ArgumentException(
|
||||
$"CPU selection contains processor(s) not present in the topology: {string.Join(", ", missingProcessors)}.",
|
||||
nameof(processors));
|
||||
}
|
||||
|
||||
var cpuSetIds = selectedProcessors
|
||||
.Select(processor => topology.TryGetCpuSetId(processor, out var cpuSetId) ? (uint?)cpuSetId : null)
|
||||
.Where(cpuSetId => cpuSetId.HasValue)
|
||||
.Select(cpuSetId => cpuSetId!.Value)
|
||||
.Distinct()
|
||||
.OrderBy(cpuSetId => cpuSetId)
|
||||
.ToList();
|
||||
|
||||
return new CpuSelection
|
||||
{
|
||||
CpuSetIds = cpuSetIds,
|
||||
LogicalProcessors = selectedProcessors,
|
||||
GlobalLogicalProcessorIndexes = selectedProcessors
|
||||
.Select(processor => processor.GlobalIndex)
|
||||
.Distinct()
|
||||
.OrderBy(index => index)
|
||||
.ToList(),
|
||||
Metadata = CreateMetadata(selectedProcessors, topology.Signature, createdFromLegacyAffinityMask: false, selectionReason),
|
||||
};
|
||||
}
|
||||
|
||||
public static CpuSelection FromLegacyAffinityMask(long mask, CpuTopologySnapshot topology)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(topology);
|
||||
|
||||
var unsignedMask = unchecked((ulong)mask);
|
||||
var selectedIndexes = new HashSet<int>();
|
||||
for (var bit = 0; bit < 64; bit++)
|
||||
{
|
||||
if ((unsignedMask & (1UL << bit)) != 0)
|
||||
{
|
||||
selectedIndexes.Add(bit);
|
||||
}
|
||||
}
|
||||
|
||||
var selectedProcessors = topology.LogicalProcessors
|
||||
.Where(processor => selectedIndexes.Contains(processor.GlobalIndex))
|
||||
.ToList();
|
||||
|
||||
var selection = FromProcessors(selectedProcessors, topology, "Migrated from legacy affinity mask");
|
||||
return selection with
|
||||
{
|
||||
Metadata = CreateMetadata(
|
||||
selection.LogicalProcessors,
|
||||
topology.Signature,
|
||||
createdFromLegacyAffinityMask: true,
|
||||
"Migrated from legacy affinity mask"),
|
||||
};
|
||||
}
|
||||
|
||||
public static long? ToLegacyAffinityMaskOrNull(CpuSelection selection)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(selection);
|
||||
|
||||
if (selection.LogicalProcessors.Any(processor => processor.GlobalIndex >= 64))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
if (selection.LogicalProcessors.Select(processor => processor.Group).Distinct().Count() > 1)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
long mask = 0;
|
||||
foreach (var processor in selection.LogicalProcessors)
|
||||
{
|
||||
if (processor.GlobalIndex < 0)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
mask |= 1L << processor.GlobalIndex;
|
||||
}
|
||||
|
||||
return mask;
|
||||
}
|
||||
|
||||
private static CpuSelectionMetadata CreateMetadata(
|
||||
IReadOnlyCollection<ProcessorRef> processors,
|
||||
CpuTopologySignature signature,
|
||||
bool createdFromLegacyAffinityMask,
|
||||
string selectionReason)
|
||||
{
|
||||
var groups = processors.Select(processor => processor.Group).Distinct().ToList();
|
||||
var maxGlobalIndex = processors.Count == 0
|
||||
? -1
|
||||
: processors.Max(processor => processor.GlobalIndex);
|
||||
|
||||
return new CpuSelectionMetadata
|
||||
{
|
||||
TopologySignature = signature,
|
||||
CreatedFromLegacyAffinityMask = createdFromLegacyAffinityMask,
|
||||
ContainsLogicalProcessorsBeyondLegacyMask = maxGlobalIndex >= 64,
|
||||
HasMultipleProcessorGroups = groups.Count > 1,
|
||||
ProcessorGroupCount = groups.Count,
|
||||
MaxGlobalLogicalProcessorIndex = maxGlobalIndex,
|
||||
SelectionReason = selectionReason,
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,35 +1,19 @@
|
||||
/*
|
||||
* ThreadPilot - Advanced Windows Process and Power Plan Manager
|
||||
* Copyright (C) 2025 Prime Build
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published by
|
||||
* the Free Software Foundation, version 3 only.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
namespace ThreadPilot.Models
|
||||
{
|
||||
public sealed record CpuSelectionMigrationMetadata
|
||||
{
|
||||
public bool CreatedFromLegacyAffinityMask { get; init; }
|
||||
|
||||
public bool CreatedFromLegacyCoreMask { get; init; }
|
||||
|
||||
public bool ReviewRequired { get; init; }
|
||||
|
||||
public string MigrationConfidence { get; init; } = string.Empty;
|
||||
|
||||
public string Reason { get; init; } = string.Empty;
|
||||
|
||||
public CpuTopologySignature? TopologySignature { get; init; }
|
||||
|
||||
public long? SourceLegacyAffinityMask { get; init; }
|
||||
}
|
||||
}
|
||||
namespace ThreadPilot.Models
|
||||
{
|
||||
public sealed record CpuSelectionMigrationMetadata
|
||||
{
|
||||
public bool CreatedFromLegacyAffinityMask { get; init; }
|
||||
|
||||
public bool CreatedFromLegacyCoreMask { get; init; }
|
||||
|
||||
public bool ReviewRequired { get; init; }
|
||||
|
||||
public string MigrationConfidence { get; init; } = string.Empty;
|
||||
|
||||
public string Reason { get; init; } = string.Empty;
|
||||
|
||||
public CpuTopologySignature? TopologySignature { get; init; }
|
||||
|
||||
public long? SourceLegacyAffinityMask { get; init; }
|
||||
}
|
||||
}
|
||||
|
||||
+133
-197
@@ -1,197 +1,133 @@
|
||||
/*
|
||||
* ThreadPilot - Advanced Windows Process and Power Plan Manager
|
||||
* Copyright (C) 2025 Prime Build
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published by
|
||||
* the Free Software Foundation, version 3 only.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
namespace ThreadPilot.Models
|
||||
{
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
|
||||
/// <summary>
|
||||
/// Represents a logical CPU core with topology information.
|
||||
/// </summary>
|
||||
public partial class CpuCoreModel : ObservableObject
|
||||
{
|
||||
public int LogicalCoreId { get; set; }
|
||||
|
||||
public int PhysicalCoreId { get; set; }
|
||||
|
||||
public int SocketId { get; set; }
|
||||
|
||||
public int? CcdId { get; set; } // Core Complex Die (AMD)
|
||||
|
||||
public int? ClusterId { get; set; } // Intel Cluster
|
||||
|
||||
public CpuCoreType CoreType { get; set; } = CpuCoreType.Unknown;
|
||||
|
||||
public bool IsHyperThreaded { get; set; }
|
||||
|
||||
public int? HyperThreadSibling { get; set; }
|
||||
|
||||
public string Label { get; set; } = string.Empty;
|
||||
|
||||
public string LogicalProcessorName { get; set; } = string.Empty; // e.g., "Core0_T0", "Core0_T1" (T0 = physical, T1+ = SMT)
|
||||
|
||||
[ObservableProperty]
|
||||
private bool isEnabled = true;
|
||||
|
||||
[ObservableProperty]
|
||||
private bool isSelected = false;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the affinity mask bit for this logical core.
|
||||
/// </summary>
|
||||
public long AffinityMask => 1L << this.LogicalCoreId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Types of CPU cores.
|
||||
/// </summary>
|
||||
public enum CpuCoreType
|
||||
{
|
||||
Unknown,
|
||||
Standard,
|
||||
PerformanceCore, // Intel P-cores
|
||||
EfficiencyCore, // Intel E-cores
|
||||
Zen, // AMD Zen cores
|
||||
ZenPlus, // AMD Zen+ cores
|
||||
Zen2, // AMD Zen2 cores
|
||||
Zen3, // AMD Zen3 cores
|
||||
Zen4, // AMD Zen4 cores
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Represents CPU topology information.
|
||||
/// </summary>
|
||||
public class CpuTopologyModel
|
||||
{
|
||||
public List<CpuCoreModel> LogicalCores { get; set; } = new();
|
||||
|
||||
public int TotalLogicalCores => this.LogicalCores.Count;
|
||||
|
||||
public int TotalPhysicalCores => this.LogicalCores.GroupBy(c => c.PhysicalCoreId).Count();
|
||||
|
||||
public int TotalSockets => this.LogicalCores.GroupBy(c => c.SocketId).Count();
|
||||
|
||||
public int SocketCount => this.TotalSockets; // Alias for TotalSockets
|
||||
|
||||
public bool HasHyperThreading => this.LogicalCores.Any(c => c.IsHyperThreaded);
|
||||
|
||||
public bool HasSmt => this.HasHyperThreading; // SMT is AMD's term for HyperThreading
|
||||
|
||||
public bool HasIntelHybrid => this.LogicalCores.Any(c => c.CoreType == CpuCoreType.PerformanceCore || c.CoreType == CpuCoreType.EfficiencyCore);
|
||||
|
||||
public bool HasHybridArchitecture => this.HasIntelHybrid; // Alias for HasIntelHybrid
|
||||
|
||||
public bool HasAmdCcd => this.LogicalCores.Any(c => c.CcdId.HasValue);
|
||||
|
||||
public int CcdCount => this.LogicalCores.Where(c => c.CcdId.HasValue).Select(c => c.CcdId!.Value).Distinct().Count();
|
||||
|
||||
public string Architecture => this.CpuArchitecture; // Alias for CpuArchitecture
|
||||
|
||||
public string CpuArchitecture { get; set; } = "Unknown";
|
||||
|
||||
public string CpuBrand { get; set; } = "Unknown";
|
||||
|
||||
public bool TopologyDetectionSuccessful { get; set; } = false;
|
||||
|
||||
/// <summary>
|
||||
/// Gets all CCDs (Core Complex Dies) available.
|
||||
/// </summary>
|
||||
public IEnumerable<int> AvailableCcds => this.LogicalCores
|
||||
.Where(c => c.CcdId.HasValue)
|
||||
.Select(c => c.CcdId!.Value)
|
||||
.Distinct()
|
||||
.OrderBy(id => id);
|
||||
|
||||
/// <summary>
|
||||
/// Gets all performance cores (Intel P-cores).
|
||||
/// </summary>
|
||||
public IEnumerable<CpuCoreModel> PerformanceCores => this.LogicalCores
|
||||
.Where(c => c.CoreType == CpuCoreType.PerformanceCore);
|
||||
|
||||
/// <summary>
|
||||
/// Gets all efficiency cores (Intel E-cores).
|
||||
/// </summary>
|
||||
public IEnumerable<CpuCoreModel> EfficiencyCores => this.LogicalCores
|
||||
.Where(c => c.CoreType == CpuCoreType.EfficiencyCore);
|
||||
|
||||
/// <summary>
|
||||
/// Gets all physical cores (one logical core per physical core, excluding HT siblings).
|
||||
/// </summary>
|
||||
public IEnumerable<CpuCoreModel> PhysicalCores => this.LogicalCores
|
||||
.GroupBy(c => c.PhysicalCoreId)
|
||||
.Select(g => g.OrderBy(c => c.LogicalCoreId).First());
|
||||
|
||||
/// <summary>
|
||||
/// Gets cores by CCD ID.
|
||||
/// </summary>
|
||||
public IEnumerable<CpuCoreModel> GetCoresByCcd(int ccdId) => this.LogicalCores
|
||||
.Where(c => c.CcdId == ccdId);
|
||||
|
||||
/// <summary>
|
||||
/// Gets cores by socket ID.
|
||||
/// </summary>
|
||||
public IEnumerable<CpuCoreModel> GetCoresBySocket(int socketId) => this.LogicalCores
|
||||
.Where(c => c.SocketId == socketId);
|
||||
|
||||
/// <summary>
|
||||
/// Calculates affinity mask for selected cores.
|
||||
/// </summary>
|
||||
public long CalculateAffinityMask(IEnumerable<CpuCoreModel> cores)
|
||||
{
|
||||
return cores.Aggregate(0L, (mask, core) => mask | core.AffinityMask);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets affinity mask for all physical cores (excluding HT siblings).
|
||||
/// </summary>
|
||||
public long GetPhysicalCoresAffinityMask() => this.CalculateAffinityMask(this.PhysicalCores);
|
||||
|
||||
/// <summary>
|
||||
/// Gets affinity mask for performance cores.
|
||||
/// </summary>
|
||||
public long GetPerformanceCoresAffinityMask() => this.CalculateAffinityMask(this.PerformanceCores);
|
||||
|
||||
/// <summary>
|
||||
/// Gets affinity mask for efficiency cores.
|
||||
/// </summary>
|
||||
public long GetEfficiencyCoresAffinityMask() => this.CalculateAffinityMask(this.EfficiencyCores);
|
||||
|
||||
/// <summary>
|
||||
/// Gets affinity mask for a specific CCD.
|
||||
/// </summary>
|
||||
public long GetCcdAffinityMask(int ccdId) => this.CalculateAffinityMask(this.GetCoresByCcd(ccdId));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Quick selection preset for CPU affinity.
|
||||
/// </summary>
|
||||
public class CpuAffinityPreset
|
||||
{
|
||||
public string Name { get; set; } = string.Empty;
|
||||
|
||||
public string Description { get; set; } = string.Empty;
|
||||
|
||||
public long AffinityMask { get; set; }
|
||||
|
||||
public bool IsAvailable { get; set; } = true;
|
||||
|
||||
public string UnavailableReason { get; set; } = string.Empty;
|
||||
}
|
||||
}
|
||||
|
||||
namespace ThreadPilot.Models
|
||||
{
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
|
||||
public partial class CpuCoreModel : ObservableObject
|
||||
{
|
||||
public int LogicalCoreId { get; set; }
|
||||
|
||||
public int PhysicalCoreId { get; set; }
|
||||
|
||||
public int SocketId { get; set; }
|
||||
|
||||
public int? CcdId { get; set; } // Core Complex Die (AMD)
|
||||
|
||||
public int? ClusterId { get; set; } // Intel Cluster
|
||||
|
||||
public CpuCoreType CoreType { get; set; } = CpuCoreType.Unknown;
|
||||
|
||||
public bool IsHyperThreaded { get; set; }
|
||||
|
||||
public int? HyperThreadSibling { get; set; }
|
||||
|
||||
public string Label { get; set; } = string.Empty;
|
||||
|
||||
public string LogicalProcessorName { get; set; } = string.Empty; // e.g., "Core0_T0", "Core0_T1" (T0 = physical, T1+ = SMT)
|
||||
|
||||
[ObservableProperty]
|
||||
private bool isEnabled = true;
|
||||
|
||||
[ObservableProperty]
|
||||
private bool isSelected = false;
|
||||
|
||||
public long AffinityMask => 1L << this.LogicalCoreId;
|
||||
}
|
||||
|
||||
public enum CpuCoreType
|
||||
{
|
||||
Unknown,
|
||||
Standard,
|
||||
PerformanceCore, // Intel P-cores
|
||||
EfficiencyCore, // Intel E-cores
|
||||
Zen, // AMD Zen cores
|
||||
ZenPlus, // AMD Zen+ cores
|
||||
Zen2, // AMD Zen2 cores
|
||||
Zen3, // AMD Zen3 cores
|
||||
Zen4, // AMD Zen4 cores
|
||||
}
|
||||
|
||||
public class CpuTopologyModel
|
||||
{
|
||||
public List<CpuCoreModel> LogicalCores { get; set; } = new();
|
||||
|
||||
public int TotalLogicalCores => this.LogicalCores.Count;
|
||||
|
||||
public int TotalPhysicalCores => this.LogicalCores.GroupBy(c => c.PhysicalCoreId).Count();
|
||||
|
||||
public int TotalSockets => this.LogicalCores.GroupBy(c => c.SocketId).Count();
|
||||
|
||||
public int SocketCount => this.TotalSockets; // Alias for TotalSockets
|
||||
|
||||
public bool HasHyperThreading => this.LogicalCores.Any(c => c.IsHyperThreaded);
|
||||
|
||||
public bool HasSmt => this.HasHyperThreading; // SMT is AMD's term for HyperThreading
|
||||
|
||||
public bool HasIntelHybrid => this.LogicalCores.Any(c => c.CoreType == CpuCoreType.PerformanceCore || c.CoreType == CpuCoreType.EfficiencyCore);
|
||||
|
||||
public bool HasHybridArchitecture => this.HasIntelHybrid; // Alias for HasIntelHybrid
|
||||
|
||||
public bool HasAmdCcd => this.LogicalCores.Any(c => c.CcdId.HasValue);
|
||||
|
||||
public int CcdCount => this.LogicalCores.Where(c => c.CcdId.HasValue).Select(c => c.CcdId!.Value).Distinct().Count();
|
||||
|
||||
public string Architecture => this.CpuArchitecture; // Alias for CpuArchitecture
|
||||
|
||||
public string CpuArchitecture { get; set; } = "Unknown";
|
||||
|
||||
public string CpuBrand { get; set; } = "Unknown";
|
||||
|
||||
public bool TopologyDetectionSuccessful { get; set; } = false;
|
||||
|
||||
public IEnumerable<int> AvailableCcds => this.LogicalCores
|
||||
.Where(c => c.CcdId.HasValue)
|
||||
.Select(c => c.CcdId!.Value)
|
||||
.Distinct()
|
||||
.OrderBy(id => id);
|
||||
|
||||
public IEnumerable<CpuCoreModel> PerformanceCores => this.LogicalCores
|
||||
.Where(c => c.CoreType == CpuCoreType.PerformanceCore);
|
||||
|
||||
public IEnumerable<CpuCoreModel> EfficiencyCores => this.LogicalCores
|
||||
.Where(c => c.CoreType == CpuCoreType.EfficiencyCore);
|
||||
|
||||
public IEnumerable<CpuCoreModel> PhysicalCores => this.LogicalCores
|
||||
.GroupBy(c => c.PhysicalCoreId)
|
||||
.Select(g => g.OrderBy(c => c.LogicalCoreId).First());
|
||||
|
||||
public IEnumerable<CpuCoreModel> GetCoresByCcd(int ccdId) => this.LogicalCores
|
||||
.Where(c => c.CcdId == ccdId);
|
||||
|
||||
public IEnumerable<CpuCoreModel> GetCoresBySocket(int socketId) => this.LogicalCores
|
||||
.Where(c => c.SocketId == socketId);
|
||||
|
||||
public long CalculateAffinityMask(IEnumerable<CpuCoreModel> cores)
|
||||
{
|
||||
return cores.Aggregate(0L, (mask, core) => mask | core.AffinityMask);
|
||||
}
|
||||
|
||||
public long GetPhysicalCoresAffinityMask() => this.CalculateAffinityMask(this.PhysicalCores);
|
||||
|
||||
public long GetPerformanceCoresAffinityMask() => this.CalculateAffinityMask(this.PerformanceCores);
|
||||
|
||||
public long GetEfficiencyCoresAffinityMask() => this.CalculateAffinityMask(this.EfficiencyCores);
|
||||
|
||||
public long GetCcdAffinityMask(int ccdId) => this.CalculateAffinityMask(this.GetCoresByCcd(ccdId));
|
||||
}
|
||||
|
||||
public class CpuAffinityPreset
|
||||
{
|
||||
public string Name { get; set; } = string.Empty;
|
||||
|
||||
public string Description { get; set; } = string.Empty;
|
||||
|
||||
public long AffinityMask { get; set; }
|
||||
|
||||
public bool IsAvailable { get; set; } = true;
|
||||
|
||||
public string UnavailableReason { get; set; } = string.Empty;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+187
-233
@@ -1,233 +1,187 @@
|
||||
/*
|
||||
* ThreadPilot - Advanced Windows Process and Power Plan Manager
|
||||
* Copyright (C) 2025 Prime Build
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published by
|
||||
* the Free Software Foundation, version 3 only.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
namespace ThreadPilot.Models
|
||||
{
|
||||
/// <summary>
|
||||
/// Defines structured log event types and categories for consistent logging.
|
||||
/// </summary>
|
||||
public static class LogEventTypes
|
||||
{
|
||||
/// <summary>
|
||||
/// Power plan related events.
|
||||
/// </summary>
|
||||
public static class PowerPlan
|
||||
{
|
||||
public const string Changed = "PowerPlanChanged";
|
||||
public const string ChangeRequested = "PowerPlanChangeRequested";
|
||||
public const string ChangeFailed = "PowerPlanChangeFailed";
|
||||
public const string Restored = "PowerPlanRestored";
|
||||
public const string DefaultSet = "DefaultPowerPlanSet";
|
||||
public const string EnumerationFailed = "PowerPlanEnumerationFailed";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Process monitoring events.
|
||||
/// </summary>
|
||||
public static class ProcessMonitoring
|
||||
{
|
||||
public const string Started = "ProcessStarted";
|
||||
public const string Stopped = "ProcessStopped";
|
||||
public const string MonitoringStarted = "MonitoringStarted";
|
||||
public const string MonitoringStopped = "MonitoringStopped";
|
||||
public const string WmiEventReceived = "WmiEventReceived";
|
||||
public const string WmiConnectionFailed = "WmiConnectionFailed";
|
||||
public const string PollingFallback = "PollingFallbackActivated";
|
||||
public const string ProcessDetected = "ProcessDetected";
|
||||
public const string ProcessLost = "ProcessLost";
|
||||
public const string AssociationTriggered = "AssociationTriggered";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// User action events.
|
||||
/// </summary>
|
||||
public static class UserActions
|
||||
{
|
||||
public const string SettingsChanged = "SettingsChanged";
|
||||
public const string ProcessAffinityChanged = "ProcessAffinityChanged";
|
||||
public const string ProcessPriorityChanged = "ProcessPriorityChanged";
|
||||
public const string AssociationAdded = "AssociationAdded";
|
||||
public const string AssociationRemoved = "AssociationRemoved";
|
||||
public const string MonitoringToggled = "MonitoringToggled";
|
||||
public const string GameBoostToggled = "GameBoostToggled";
|
||||
public const string AutostartToggled = "AutostartToggled";
|
||||
public const string NotificationSettingsChanged = "NotificationSettingsChanged";
|
||||
public const string LogsExported = "LogsExported";
|
||||
public const string LogsCleared = "LogsCleared";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// System events.
|
||||
/// </summary>
|
||||
public static class System
|
||||
{
|
||||
public const string ApplicationStarted = "ApplicationStarted";
|
||||
public const string ApplicationShutdown = "ApplicationShutdown";
|
||||
public const string ServiceInitialized = "ServiceInitialized";
|
||||
public const string ServiceStarted = "ServiceStarted";
|
||||
public const string ServiceStopped = "ServiceStopped";
|
||||
public const string ConfigurationLoaded = "ConfigurationLoaded";
|
||||
public const string ConfigurationSaved = "ConfigurationSaved";
|
||||
public const string CpuTopologyDetected = "CpuTopologyDetected";
|
||||
public const string SystemTrayInitialized = "SystemTrayInitialized";
|
||||
public const string NotificationSent = "NotificationSent";
|
||||
public const string ErrorRecovered = "ErrorRecovered";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Error categories.
|
||||
/// </summary>
|
||||
public static class Errors
|
||||
{
|
||||
public const string ServiceFailure = "ServiceFailure";
|
||||
public const string ConfigurationError = "ConfigurationError";
|
||||
public const string FileSystemError = "FileSystemError";
|
||||
public const string PermissionError = "PermissionError";
|
||||
public const string NetworkError = "NetworkError";
|
||||
public const string WmiError = "WmiError";
|
||||
public const string UnhandledException = "UnhandledException";
|
||||
public const string ValidationError = "ValidationError";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Performance events.
|
||||
/// </summary>
|
||||
public static class Performance
|
||||
{
|
||||
public const string HighMemoryUsage = "HighMemoryUsage";
|
||||
public const string HighCpuUsage = "HighCpuUsage";
|
||||
public const string SlowOperation = "SlowOperation";
|
||||
public const string LargeLogFile = "LargeLogFile";
|
||||
public const string ProcessCountHigh = "ProcessCountHigh";
|
||||
public const string Gen2PauseAlert = "Gen2PauseAlert";
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Log categories for organizing log entries.
|
||||
/// </summary>
|
||||
public static class LogCategories
|
||||
{
|
||||
public const string PowerPlan = "PowerPlan";
|
||||
public const string ProcessMonitoring = "ProcessMonitoring";
|
||||
public const string UserAction = "UserAction";
|
||||
public const string System = "System";
|
||||
public const string Error = "Error";
|
||||
public const string Performance = "Performance";
|
||||
public const string Security = "Security";
|
||||
public const string Configuration = "Configuration";
|
||||
public const string Lifecycle = "Lifecycle";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Common log properties for structured logging.
|
||||
/// </summary>
|
||||
public static class LogProperties
|
||||
{
|
||||
public const string ProcessName = "ProcessName";
|
||||
public const string ProcessId = "ProcessId";
|
||||
public const string PowerPlanId = "PowerPlanId";
|
||||
public const string PowerPlanName = "PowerPlanName";
|
||||
public const string GameName = "GameName";
|
||||
public const string UserId = "UserId";
|
||||
public const string SessionId = "SessionId";
|
||||
public const string CorrelationId = "CorrelationId";
|
||||
public const string Duration = "Duration";
|
||||
public const string ErrorCode = "ErrorCode";
|
||||
public const string StackTrace = "StackTrace";
|
||||
public const string MemoryUsage = "MemoryUsage";
|
||||
public const string CpuUsage = "CpuUsage";
|
||||
public const string ThreadId = "ThreadId";
|
||||
public const string Version = "Version";
|
||||
public const string Environment = "Environment";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Helper class for creating structured log data.
|
||||
/// </summary>
|
||||
public static class LogDataBuilder
|
||||
{
|
||||
public static Dictionary<string, object> CreateProcessData(string processName, int processId)
|
||||
{
|
||||
return new Dictionary<string, object>
|
||||
{
|
||||
[LogProperties.ProcessName] = processName,
|
||||
[LogProperties.ProcessId] = processId,
|
||||
};
|
||||
}
|
||||
|
||||
public static Dictionary<string, object> CreatePowerPlanData(string planId, string planName)
|
||||
{
|
||||
return new Dictionary<string, object>
|
||||
{
|
||||
[LogProperties.PowerPlanId] = planId,
|
||||
[LogProperties.PowerPlanName] = planName,
|
||||
};
|
||||
}
|
||||
|
||||
public static Dictionary<string, object> CreateGameData(string gameName)
|
||||
{
|
||||
return new Dictionary<string, object>
|
||||
{
|
||||
[LogProperties.GameName] = gameName,
|
||||
};
|
||||
}
|
||||
|
||||
public static Dictionary<string, object> CreatePerformanceData(long memoryUsage, double cpuUsage)
|
||||
{
|
||||
return new Dictionary<string, object>
|
||||
{
|
||||
[LogProperties.MemoryUsage] = memoryUsage,
|
||||
[LogProperties.CpuUsage] = cpuUsage,
|
||||
};
|
||||
}
|
||||
|
||||
public static Dictionary<string, object> CreateErrorData(Exception exception)
|
||||
{
|
||||
var stackTrace = exception.StackTrace ?? "N/A";
|
||||
stackTrace = stackTrace[..Math.Min(2000, stackTrace.Length)];
|
||||
|
||||
return new Dictionary<string, object>
|
||||
{
|
||||
[LogProperties.ErrorCode] = exception.HResult,
|
||||
[LogProperties.StackTrace] = stackTrace,
|
||||
["ExceptionType"] = exception.GetType().Name,
|
||||
["InnerException"] = exception.InnerException?.Message ?? "N/A",
|
||||
};
|
||||
}
|
||||
|
||||
public static Dictionary<string, object> CreateTimingData(TimeSpan duration)
|
||||
{
|
||||
return new Dictionary<string, object>
|
||||
{
|
||||
[LogProperties.Duration] = duration.TotalMilliseconds,
|
||||
};
|
||||
}
|
||||
|
||||
public static Dictionary<string, object> CreateSystemData()
|
||||
{
|
||||
return new Dictionary<string, object>
|
||||
{
|
||||
[LogProperties.Version] = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version?.ToString() ?? "Unknown",
|
||||
[LogProperties.Environment] = Environment.OSVersion.ToString(),
|
||||
[LogProperties.ThreadId] = Thread.CurrentThread.ManagedThreadId,
|
||||
["MachineName"] = Environment.MachineName,
|
||||
["UserName"] = Environment.UserName,
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
namespace ThreadPilot.Models
|
||||
{
|
||||
public static class LogEventTypes
|
||||
{
|
||||
public static class PowerPlan
|
||||
{
|
||||
public const string Changed = "PowerPlanChanged";
|
||||
public const string ChangeRequested = "PowerPlanChangeRequested";
|
||||
public const string ChangeFailed = "PowerPlanChangeFailed";
|
||||
public const string Restored = "PowerPlanRestored";
|
||||
public const string DefaultSet = "DefaultPowerPlanSet";
|
||||
public const string EnumerationFailed = "PowerPlanEnumerationFailed";
|
||||
}
|
||||
|
||||
public static class ProcessMonitoring
|
||||
{
|
||||
public const string Started = "ProcessStarted";
|
||||
public const string Stopped = "ProcessStopped";
|
||||
public const string MonitoringStarted = "MonitoringStarted";
|
||||
public const string MonitoringStopped = "MonitoringStopped";
|
||||
public const string WmiEventReceived = "WmiEventReceived";
|
||||
public const string WmiConnectionFailed = "WmiConnectionFailed";
|
||||
public const string PollingFallback = "PollingFallbackActivated";
|
||||
public const string ProcessDetected = "ProcessDetected";
|
||||
public const string ProcessLost = "ProcessLost";
|
||||
public const string AssociationTriggered = "AssociationTriggered";
|
||||
}
|
||||
|
||||
public static class UserActions
|
||||
{
|
||||
public const string SettingsChanged = "SettingsChanged";
|
||||
public const string ProcessAffinityChanged = "ProcessAffinityChanged";
|
||||
public const string ProcessPriorityChanged = "ProcessPriorityChanged";
|
||||
public const string AssociationAdded = "AssociationAdded";
|
||||
public const string AssociationRemoved = "AssociationRemoved";
|
||||
public const string MonitoringToggled = "MonitoringToggled";
|
||||
public const string GameBoostToggled = "GameBoostToggled";
|
||||
public const string AutostartToggled = "AutostartToggled";
|
||||
public const string NotificationSettingsChanged = "NotificationSettingsChanged";
|
||||
public const string LogsExported = "LogsExported";
|
||||
public const string LogsCleared = "LogsCleared";
|
||||
}
|
||||
|
||||
public static class System
|
||||
{
|
||||
public const string ApplicationStarted = "ApplicationStarted";
|
||||
public const string ApplicationShutdown = "ApplicationShutdown";
|
||||
public const string ServiceInitialized = "ServiceInitialized";
|
||||
public const string ServiceStarted = "ServiceStarted";
|
||||
public const string ServiceStopped = "ServiceStopped";
|
||||
public const string ConfigurationLoaded = "ConfigurationLoaded";
|
||||
public const string ConfigurationSaved = "ConfigurationSaved";
|
||||
public const string CpuTopologyDetected = "CpuTopologyDetected";
|
||||
public const string SystemTrayInitialized = "SystemTrayInitialized";
|
||||
public const string NotificationSent = "NotificationSent";
|
||||
public const string ErrorRecovered = "ErrorRecovered";
|
||||
}
|
||||
|
||||
public static class Errors
|
||||
{
|
||||
public const string ServiceFailure = "ServiceFailure";
|
||||
public const string ConfigurationError = "ConfigurationError";
|
||||
public const string FileSystemError = "FileSystemError";
|
||||
public const string PermissionError = "PermissionError";
|
||||
public const string NetworkError = "NetworkError";
|
||||
public const string WmiError = "WmiError";
|
||||
public const string UnhandledException = "UnhandledException";
|
||||
public const string ValidationError = "ValidationError";
|
||||
}
|
||||
|
||||
public static class Performance
|
||||
{
|
||||
public const string HighMemoryUsage = "HighMemoryUsage";
|
||||
public const string HighCpuUsage = "HighCpuUsage";
|
||||
public const string SlowOperation = "SlowOperation";
|
||||
public const string LargeLogFile = "LargeLogFile";
|
||||
public const string ProcessCountHigh = "ProcessCountHigh";
|
||||
public const string Gen2PauseAlert = "Gen2PauseAlert";
|
||||
}
|
||||
}
|
||||
|
||||
public static class LogCategories
|
||||
{
|
||||
public const string PowerPlan = "PowerPlan";
|
||||
public const string ProcessMonitoring = "ProcessMonitoring";
|
||||
public const string UserAction = "UserAction";
|
||||
public const string System = "System";
|
||||
public const string Error = "Error";
|
||||
public const string Performance = "Performance";
|
||||
public const string Security = "Security";
|
||||
public const string Configuration = "Configuration";
|
||||
public const string Lifecycle = "Lifecycle";
|
||||
}
|
||||
|
||||
public static class LogProperties
|
||||
{
|
||||
public const string ProcessName = "ProcessName";
|
||||
public const string ProcessId = "ProcessId";
|
||||
public const string PowerPlanId = "PowerPlanId";
|
||||
public const string PowerPlanName = "PowerPlanName";
|
||||
public const string GameName = "GameName";
|
||||
public const string UserId = "UserId";
|
||||
public const string SessionId = "SessionId";
|
||||
public const string CorrelationId = "CorrelationId";
|
||||
public const string Duration = "Duration";
|
||||
public const string ErrorCode = "ErrorCode";
|
||||
public const string StackTrace = "StackTrace";
|
||||
public const string MemoryUsage = "MemoryUsage";
|
||||
public const string CpuUsage = "CpuUsage";
|
||||
public const string ThreadId = "ThreadId";
|
||||
public const string Version = "Version";
|
||||
public const string Environment = "Environment";
|
||||
}
|
||||
|
||||
public static class LogDataBuilder
|
||||
{
|
||||
public static Dictionary<string, object> CreateProcessData(string processName, int processId)
|
||||
{
|
||||
return new Dictionary<string, object>
|
||||
{
|
||||
[LogProperties.ProcessName] = processName,
|
||||
[LogProperties.ProcessId] = processId,
|
||||
};
|
||||
}
|
||||
|
||||
public static Dictionary<string, object> CreatePowerPlanData(string planId, string planName)
|
||||
{
|
||||
return new Dictionary<string, object>
|
||||
{
|
||||
[LogProperties.PowerPlanId] = planId,
|
||||
[LogProperties.PowerPlanName] = planName,
|
||||
};
|
||||
}
|
||||
|
||||
public static Dictionary<string, object> CreateGameData(string gameName)
|
||||
{
|
||||
return new Dictionary<string, object>
|
||||
{
|
||||
[LogProperties.GameName] = gameName,
|
||||
};
|
||||
}
|
||||
|
||||
public static Dictionary<string, object> CreatePerformanceData(long memoryUsage, double cpuUsage)
|
||||
{
|
||||
return new Dictionary<string, object>
|
||||
{
|
||||
[LogProperties.MemoryUsage] = memoryUsage,
|
||||
[LogProperties.CpuUsage] = cpuUsage,
|
||||
};
|
||||
}
|
||||
|
||||
public static Dictionary<string, object> CreateErrorData(Exception exception)
|
||||
{
|
||||
var stackTrace = exception.StackTrace ?? "N/A";
|
||||
stackTrace = stackTrace[..Math.Min(2000, stackTrace.Length)];
|
||||
|
||||
return new Dictionary<string, object>
|
||||
{
|
||||
[LogProperties.ErrorCode] = exception.HResult,
|
||||
[LogProperties.StackTrace] = stackTrace,
|
||||
["ExceptionType"] = exception.GetType().Name,
|
||||
["InnerException"] = exception.InnerException?.Message ?? "N/A",
|
||||
};
|
||||
}
|
||||
|
||||
public static Dictionary<string, object> CreateTimingData(TimeSpan duration)
|
||||
{
|
||||
return new Dictionary<string, object>
|
||||
{
|
||||
[LogProperties.Duration] = duration.TotalMilliseconds,
|
||||
};
|
||||
}
|
||||
|
||||
public static Dictionary<string, object> CreateSystemData()
|
||||
{
|
||||
return new Dictionary<string, object>
|
||||
{
|
||||
[LogProperties.Version] = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version?.ToString() ?? "Unknown",
|
||||
[LogProperties.Environment] = Environment.OSVersion.ToString(),
|
||||
[LogProperties.ThreadId] = Thread.CurrentThread.ManagedThreadId,
|
||||
["MachineName"] = Environment.MachineName,
|
||||
["UserName"] = Environment.UserName,
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+111
-160
@@ -1,160 +1,111 @@
|
||||
/*
|
||||
* ThreadPilot - Advanced Windows Process and Power Plan Manager
|
||||
* Copyright (C) 2025 Prime Build
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published by
|
||||
* the Free Software Foundation, version 3 only.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
namespace ThreadPilot.Models
|
||||
{
|
||||
using System;
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
|
||||
/// <summary>
|
||||
/// Model representing a notification.
|
||||
/// </summary>
|
||||
public partial class NotificationModel : ObservableObject
|
||||
{
|
||||
[ObservableProperty]
|
||||
private string id = Guid.NewGuid().ToString();
|
||||
|
||||
[ObservableProperty]
|
||||
private string title = string.Empty;
|
||||
|
||||
[ObservableProperty]
|
||||
private string message = string.Empty;
|
||||
|
||||
[ObservableProperty]
|
||||
private NotificationType type = NotificationType.Information;
|
||||
|
||||
[ObservableProperty]
|
||||
private DateTime timestamp = DateTime.Now;
|
||||
|
||||
[ObservableProperty]
|
||||
private int durationMs = 3000;
|
||||
|
||||
[ObservableProperty]
|
||||
private bool isRead = false;
|
||||
|
||||
[ObservableProperty]
|
||||
private bool isPersistent = false;
|
||||
|
||||
[ObservableProperty]
|
||||
private string? actionText;
|
||||
|
||||
[ObservableProperty]
|
||||
private string? actionCommand;
|
||||
|
||||
[ObservableProperty]
|
||||
private string? iconPath;
|
||||
|
||||
[ObservableProperty]
|
||||
private NotificationPriority priority = NotificationPriority.Normal;
|
||||
|
||||
[ObservableProperty]
|
||||
private string? category;
|
||||
|
||||
[ObservableProperty]
|
||||
private string? sourceService;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="NotificationModel"/> class.
|
||||
/// Creates a new notification.
|
||||
/// </summary>
|
||||
public NotificationModel()
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="NotificationModel"/> class.
|
||||
/// Creates a new notification with basic information.
|
||||
/// </summary>
|
||||
public NotificationModel(string title, string message, NotificationType type = NotificationType.Information)
|
||||
{
|
||||
this.Title = title;
|
||||
this.Message = message;
|
||||
this.Type = type;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="NotificationModel"/> class.
|
||||
/// Creates a new notification with full information.
|
||||
/// </summary>
|
||||
public NotificationModel(string title, string message, NotificationType type, int durationMs, bool isPersistent = false)
|
||||
{
|
||||
this.Title = title;
|
||||
this.Message = message;
|
||||
this.Type = type;
|
||||
this.DurationMs = durationMs;
|
||||
this.IsPersistent = isPersistent;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Marks the notification as read.
|
||||
/// </summary>
|
||||
public void MarkAsRead()
|
||||
{
|
||||
this.IsRead = true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the display text for the notification type.
|
||||
/// </summary>
|
||||
public string TypeDisplayText => this.Type switch
|
||||
{
|
||||
NotificationType.Information => "Info",
|
||||
NotificationType.Success => "Success",
|
||||
NotificationType.Warning => "Warning",
|
||||
NotificationType.Error => "Error",
|
||||
NotificationType.PowerPlanChange => "Power Plan",
|
||||
NotificationType.ProcessMonitoring => "Process Monitor",
|
||||
NotificationType.CpuAffinity => "CPU Affinity",
|
||||
_ => "Unknown",
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Gets the formatted timestamp.
|
||||
/// </summary>
|
||||
public string FormattedTimestamp => this.Timestamp.ToString("HH:mm:ss");
|
||||
|
||||
/// <summary>
|
||||
/// Gets the formatted date and time.
|
||||
/// </summary>
|
||||
public string FormattedDateTime => this.Timestamp.ToString("yyyy-MM-dd HH:mm:ss");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Types of notifications.
|
||||
/// </summary>
|
||||
public enum NotificationType
|
||||
{
|
||||
Information,
|
||||
Success,
|
||||
Warning,
|
||||
Error,
|
||||
PowerPlanChange,
|
||||
ProcessMonitoring,
|
||||
CpuAffinity,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Notification priority levels.
|
||||
/// </summary>
|
||||
public enum NotificationPriority
|
||||
{
|
||||
Low,
|
||||
Normal,
|
||||
High,
|
||||
Critical,
|
||||
}
|
||||
}
|
||||
|
||||
namespace ThreadPilot.Models
|
||||
{
|
||||
using System;
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
|
||||
public partial class NotificationModel : ObservableObject
|
||||
{
|
||||
[ObservableProperty]
|
||||
private string id = Guid.NewGuid().ToString();
|
||||
|
||||
[ObservableProperty]
|
||||
private string title = string.Empty;
|
||||
|
||||
[ObservableProperty]
|
||||
private string message = string.Empty;
|
||||
|
||||
[ObservableProperty]
|
||||
private NotificationType type = NotificationType.Information;
|
||||
|
||||
[ObservableProperty]
|
||||
private DateTime timestamp = DateTime.Now;
|
||||
|
||||
[ObservableProperty]
|
||||
private int durationMs = 3000;
|
||||
|
||||
[ObservableProperty]
|
||||
private bool isRead = false;
|
||||
|
||||
[ObservableProperty]
|
||||
private bool isPersistent = false;
|
||||
|
||||
[ObservableProperty]
|
||||
private string? actionText;
|
||||
|
||||
[ObservableProperty]
|
||||
private string? actionCommand;
|
||||
|
||||
[ObservableProperty]
|
||||
private string? iconPath;
|
||||
|
||||
[ObservableProperty]
|
||||
private NotificationPriority priority = NotificationPriority.Normal;
|
||||
|
||||
[ObservableProperty]
|
||||
private string? category;
|
||||
|
||||
[ObservableProperty]
|
||||
private string? sourceService;
|
||||
|
||||
public NotificationModel()
|
||||
{
|
||||
}
|
||||
|
||||
public NotificationModel(string title, string message, NotificationType type = NotificationType.Information)
|
||||
{
|
||||
this.Title = title;
|
||||
this.Message = message;
|
||||
this.Type = type;
|
||||
}
|
||||
|
||||
public NotificationModel(string title, string message, NotificationType type, int durationMs, bool isPersistent = false)
|
||||
{
|
||||
this.Title = title;
|
||||
this.Message = message;
|
||||
this.Type = type;
|
||||
this.DurationMs = durationMs;
|
||||
this.IsPersistent = isPersistent;
|
||||
}
|
||||
|
||||
public void MarkAsRead()
|
||||
{
|
||||
this.IsRead = true;
|
||||
}
|
||||
|
||||
public string TypeDisplayText => this.Type switch
|
||||
{
|
||||
NotificationType.Information => "Info",
|
||||
NotificationType.Success => "Success",
|
||||
NotificationType.Warning => "Warning",
|
||||
NotificationType.Error => "Error",
|
||||
NotificationType.PowerPlanChange => "Power Plan",
|
||||
NotificationType.ProcessMonitoring => "Process Monitor",
|
||||
NotificationType.CpuAffinity => "CPU Affinity",
|
||||
_ => "Unknown",
|
||||
};
|
||||
|
||||
public string FormattedTimestamp => this.Timestamp.ToString("HH:mm:ss");
|
||||
|
||||
public string FormattedDateTime => this.Timestamp.ToString("yyyy-MM-dd HH:mm:ss");
|
||||
}
|
||||
|
||||
public enum NotificationType
|
||||
{
|
||||
Information,
|
||||
Success,
|
||||
Warning,
|
||||
Error,
|
||||
PowerPlanChange,
|
||||
ProcessMonitoring,
|
||||
CpuAffinity,
|
||||
}
|
||||
|
||||
public enum NotificationPriority
|
||||
{
|
||||
Low,
|
||||
Normal,
|
||||
High,
|
||||
Critical,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,70 +1,70 @@
|
||||
/*
|
||||
* ThreadPilot - persistent process rule models.
|
||||
*/
|
||||
namespace ThreadPilot.Models
|
||||
{
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
|
||||
public sealed record PersistentProcessRule
|
||||
{
|
||||
public string Id { get; init; } = Guid.NewGuid().ToString("N");
|
||||
|
||||
public string Name { get; init; } = string.Empty;
|
||||
|
||||
public bool IsEnabled { get; init; }
|
||||
|
||||
public string? ProcessName { get; init; }
|
||||
|
||||
public string? ExecutablePath { get; init; }
|
||||
|
||||
public CpuSelection? CpuSelection { get; init; }
|
||||
|
||||
public long? LegacyAffinityMask { get; init; }
|
||||
|
||||
public ProcessPriorityClass? Priority { get; init; }
|
||||
|
||||
public ProcessMemoryPriority? MemoryPriority { get; init; }
|
||||
|
||||
public bool ApplyAffinityOnStart { get; init; }
|
||||
|
||||
public bool ApplyPriorityOnStart { get; init; }
|
||||
|
||||
public bool ApplyMemoryPriorityOnStart { get; init; }
|
||||
|
||||
public DateTime CreatedAt { get; init; } = DateTime.UtcNow;
|
||||
|
||||
public DateTime UpdatedAt { get; init; } = DateTime.UtcNow;
|
||||
|
||||
public string? Description { get; init; }
|
||||
}
|
||||
|
||||
public sealed record PersistentRuleApplyResult
|
||||
{
|
||||
public bool Success { get; init; }
|
||||
|
||||
public string RuleId { get; init; } = string.Empty;
|
||||
|
||||
public int ProcessId { get; init; }
|
||||
|
||||
public string ProcessName { get; init; } = string.Empty;
|
||||
|
||||
public bool AffinityApplied { get; init; }
|
||||
|
||||
public bool PriorityApplied { get; init; }
|
||||
|
||||
public bool MemoryPriorityApplied { get; init; }
|
||||
|
||||
public string? ErrorCode { get; init; }
|
||||
|
||||
public string UserMessage { get; init; } = string.Empty;
|
||||
|
||||
public string TechnicalMessage { get; init; } = string.Empty;
|
||||
|
||||
public bool IsAccessDenied { get; init; }
|
||||
|
||||
public bool IsAntiCheatLikely { get; init; }
|
||||
|
||||
public bool IsProcessExited { get; init; }
|
||||
}
|
||||
}
|
||||
/*
|
||||
* ThreadPilot - persistent process rule models.
|
||||
*/
|
||||
namespace ThreadPilot.Models
|
||||
{
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
|
||||
public sealed record PersistentProcessRule
|
||||
{
|
||||
public string Id { get; init; } = Guid.NewGuid().ToString("N");
|
||||
|
||||
public string Name { get; init; } = string.Empty;
|
||||
|
||||
public bool IsEnabled { get; init; }
|
||||
|
||||
public string? ProcessName { get; init; }
|
||||
|
||||
public string? ExecutablePath { get; init; }
|
||||
|
||||
public CpuSelection? CpuSelection { get; init; }
|
||||
|
||||
public long? LegacyAffinityMask { get; init; }
|
||||
|
||||
public ProcessPriorityClass? Priority { get; init; }
|
||||
|
||||
public ProcessMemoryPriority? MemoryPriority { get; init; }
|
||||
|
||||
public bool ApplyAffinityOnStart { get; init; }
|
||||
|
||||
public bool ApplyPriorityOnStart { get; init; }
|
||||
|
||||
public bool ApplyMemoryPriorityOnStart { get; init; }
|
||||
|
||||
public DateTime CreatedAt { get; init; } = DateTime.UtcNow;
|
||||
|
||||
public DateTime UpdatedAt { get; init; } = DateTime.UtcNow;
|
||||
|
||||
public string? Description { get; init; }
|
||||
}
|
||||
|
||||
public sealed record PersistentRuleApplyResult
|
||||
{
|
||||
public bool Success { get; init; }
|
||||
|
||||
public string RuleId { get; init; } = string.Empty;
|
||||
|
||||
public int ProcessId { get; init; }
|
||||
|
||||
public string ProcessName { get; init; } = string.Empty;
|
||||
|
||||
public bool AffinityApplied { get; init; }
|
||||
|
||||
public bool PriorityApplied { get; init; }
|
||||
|
||||
public bool MemoryPriorityApplied { get; init; }
|
||||
|
||||
public string? ErrorCode { get; init; }
|
||||
|
||||
public string UserMessage { get; init; } = string.Empty;
|
||||
|
||||
public string TechnicalMessage { get; init; } = string.Empty;
|
||||
|
||||
public bool IsAccessDenied { get; init; }
|
||||
|
||||
public bool IsAntiCheatLikely { get; init; }
|
||||
|
||||
public bool IsProcessExited { get; init; }
|
||||
}
|
||||
}
|
||||
|
||||
+25
-41
@@ -1,41 +1,25 @@
|
||||
/*
|
||||
* ThreadPilot - Advanced Windows Process and Power Plan Manager
|
||||
* Copyright (C) 2025 Prime Build
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published by
|
||||
* the Free Software Foundation, version 3 only.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
namespace ThreadPilot.Models
|
||||
{
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
|
||||
public partial class PowerPlanModel : ObservableObject
|
||||
{
|
||||
[ObservableProperty]
|
||||
private string guid = string.Empty;
|
||||
|
||||
[ObservableProperty]
|
||||
private string name = string.Empty;
|
||||
|
||||
[ObservableProperty]
|
||||
private string description = string.Empty;
|
||||
|
||||
[ObservableProperty]
|
||||
private bool isActive;
|
||||
|
||||
[ObservableProperty]
|
||||
private bool isCustomPlan;
|
||||
|
||||
[ObservableProperty]
|
||||
private string filePath = string.Empty;
|
||||
}
|
||||
}
|
||||
namespace ThreadPilot.Models
|
||||
{
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
|
||||
public partial class PowerPlanModel : ObservableObject
|
||||
{
|
||||
[ObservableProperty]
|
||||
private string guid = string.Empty;
|
||||
|
||||
[ObservableProperty]
|
||||
private string name = string.Empty;
|
||||
|
||||
[ObservableProperty]
|
||||
private string description = string.Empty;
|
||||
|
||||
[ObservableProperty]
|
||||
private bool isActive;
|
||||
|
||||
[ObservableProperty]
|
||||
private bool isCustomPlan;
|
||||
|
||||
[ObservableProperty]
|
||||
private string filePath = string.Empty;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,19 +1,14 @@
|
||||
/*
|
||||
* ThreadPilot - process memory priority model.
|
||||
*/
|
||||
namespace ThreadPilot.Models
|
||||
{
|
||||
/// <summary>
|
||||
/// Documented Windows process memory priority levels.
|
||||
/// CPU priority influences CPU scheduling; memory priority influences how aggressively
|
||||
/// Windows may reclaim or page a process's memory under pressure.
|
||||
/// </summary>
|
||||
public enum ProcessMemoryPriority
|
||||
{
|
||||
VeryLow = 1,
|
||||
Low = 2,
|
||||
Medium = 3,
|
||||
BelowNormal = 4,
|
||||
Normal = 5,
|
||||
}
|
||||
}
|
||||
/*
|
||||
* ThreadPilot - process memory priority model.
|
||||
*/
|
||||
namespace ThreadPilot.Models
|
||||
{
|
||||
public enum ProcessMemoryPriority
|
||||
{
|
||||
VeryLow = 1,
|
||||
Low = 2,
|
||||
Medium = 3,
|
||||
BelowNormal = 4,
|
||||
Normal = 5,
|
||||
}
|
||||
}
|
||||
|
||||
+67
-87
@@ -1,87 +1,67 @@
|
||||
/*
|
||||
* ThreadPilot - Advanced Windows Process and Power Plan Manager
|
||||
* Copyright (C) 2025 Prime Build
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published by
|
||||
* the Free Software Foundation, version 3 only.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
namespace ThreadPilot.Models
|
||||
{
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
|
||||
public enum ProcessClassification
|
||||
{
|
||||
ForegroundApp,
|
||||
VisibleWindowApp,
|
||||
BackgroundUser,
|
||||
System,
|
||||
ProtectedOrAccessDenied,
|
||||
Terminated,
|
||||
Unknown,
|
||||
}
|
||||
|
||||
public partial class ProcessModel : ObservableObject
|
||||
{
|
||||
[ObservableProperty]
|
||||
private int processId;
|
||||
|
||||
[ObservableProperty]
|
||||
private string name = string.Empty;
|
||||
|
||||
[ObservableProperty]
|
||||
private string executablePath = string.Empty;
|
||||
|
||||
[ObservableProperty]
|
||||
private double cpuUsage;
|
||||
|
||||
[ObservableProperty]
|
||||
private long memoryUsage;
|
||||
|
||||
[ObservableProperty]
|
||||
private ProcessPriorityClass priority;
|
||||
|
||||
[ObservableProperty]
|
||||
private long processorAffinity;
|
||||
|
||||
[ObservableProperty]
|
||||
private IntPtr mainWindowHandle;
|
||||
|
||||
[ObservableProperty]
|
||||
private string mainWindowTitle = string.Empty;
|
||||
|
||||
[ObservableProperty]
|
||||
private bool hasVisibleWindow;
|
||||
|
||||
[ObservableProperty]
|
||||
private bool isForeground;
|
||||
|
||||
[ObservableProperty]
|
||||
private ProcessClassification classification = ProcessClassification.Unknown;
|
||||
|
||||
[ObservableProperty]
|
||||
private bool isIdleServerDisabled;
|
||||
|
||||
[ObservableProperty]
|
||||
private bool isRegistryPriorityEnabled;
|
||||
|
||||
/// <summary>
|
||||
/// Forces PropertyChanged notification for ProcessorAffinity.
|
||||
/// Used to update DataGrid binding when affinity changes from background thread.
|
||||
/// </summary>
|
||||
public void ForceNotifyProcessorAffinityChanged()
|
||||
{
|
||||
this.OnPropertyChanged(nameof(this.ProcessorAffinity));
|
||||
}
|
||||
}
|
||||
}
|
||||
namespace ThreadPilot.Models
|
||||
{
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
|
||||
public enum ProcessClassification
|
||||
{
|
||||
ForegroundApp,
|
||||
VisibleWindowApp,
|
||||
BackgroundUser,
|
||||
System,
|
||||
ProtectedOrAccessDenied,
|
||||
Terminated,
|
||||
Unknown,
|
||||
}
|
||||
|
||||
public partial class ProcessModel : ObservableObject
|
||||
{
|
||||
[ObservableProperty]
|
||||
private int processId;
|
||||
|
||||
[ObservableProperty]
|
||||
private string name = string.Empty;
|
||||
|
||||
[ObservableProperty]
|
||||
private string executablePath = string.Empty;
|
||||
|
||||
[ObservableProperty]
|
||||
private double cpuUsage;
|
||||
|
||||
[ObservableProperty]
|
||||
private long memoryUsage;
|
||||
|
||||
[ObservableProperty]
|
||||
private ProcessPriorityClass priority;
|
||||
|
||||
[ObservableProperty]
|
||||
private long processorAffinity;
|
||||
|
||||
[ObservableProperty]
|
||||
private IntPtr mainWindowHandle;
|
||||
|
||||
[ObservableProperty]
|
||||
private string mainWindowTitle = string.Empty;
|
||||
|
||||
[ObservableProperty]
|
||||
private bool hasVisibleWindow;
|
||||
|
||||
[ObservableProperty]
|
||||
private bool isForeground;
|
||||
|
||||
[ObservableProperty]
|
||||
private ProcessClassification classification = ProcessClassification.Unknown;
|
||||
|
||||
[ObservableProperty]
|
||||
private bool isIdleServerDisabled;
|
||||
|
||||
[ObservableProperty]
|
||||
private bool isRegistryPriorityEnabled;
|
||||
|
||||
public void ForceNotifyProcessorAffinityChanged()
|
||||
{
|
||||
this.OnPropertyChanged(nameof(this.ProcessorAffinity));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,160 +1,123 @@
|
||||
/*
|
||||
* ThreadPilot - Advanced Windows Process and Power Plan Manager
|
||||
* Copyright (C) 2025 Prime Build
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published by
|
||||
* the Free Software Foundation, version 3 only.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
namespace ThreadPilot.Models
|
||||
{
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
|
||||
/// <summary>
|
||||
/// Configuration model for process monitoring and power plan associations.
|
||||
/// </summary>
|
||||
public partial class ProcessMonitorConfiguration : ObservableObject
|
||||
{
|
||||
[ObservableProperty]
|
||||
private string defaultPowerPlanGuid = string.Empty;
|
||||
|
||||
[ObservableProperty]
|
||||
private string defaultPowerPlanName = string.Empty;
|
||||
|
||||
[ObservableProperty]
|
||||
private bool isEventBasedMonitoringEnabled = true;
|
||||
|
||||
[ObservableProperty]
|
||||
private bool isFallbackPollingEnabled = true;
|
||||
|
||||
[ObservableProperty]
|
||||
private int pollingIntervalSeconds = 5;
|
||||
|
||||
[ObservableProperty]
|
||||
private bool preventDuplicatePowerPlanChanges = true;
|
||||
|
||||
[ObservableProperty]
|
||||
private int powerPlanChangeDelayMs = 250;
|
||||
|
||||
[ObservableProperty]
|
||||
private bool enableLogging = true;
|
||||
|
||||
[ObservableProperty]
|
||||
private List<ProcessPowerPlanAssociation> associations = new();
|
||||
|
||||
[ObservableProperty]
|
||||
private DateTime lastSavedDate = DateTime.Now;
|
||||
|
||||
[ObservableProperty]
|
||||
private string configurationVersion = "1.0";
|
||||
|
||||
public ProcessMonitorConfiguration()
|
||||
{
|
||||
this.Associations = new List<ProcessPowerPlanAssociation>();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets all enabled associations sorted by priority (descending).
|
||||
/// </summary>
|
||||
public IEnumerable<ProcessPowerPlanAssociation> GetEnabledAssociations()
|
||||
{
|
||||
return this.Associations
|
||||
.Where(a => a.IsEnabled)
|
||||
.OrderByDescending(a => a.Priority)
|
||||
.ThenBy(a => a.ExecutableName);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Finds the best matching association for a process.
|
||||
/// </summary>
|
||||
public ProcessPowerPlanAssociation? FindMatchingAssociation(ProcessModel process)
|
||||
{
|
||||
return this.GetEnabledAssociations()
|
||||
.FirstOrDefault(a => a.MatchesProcess(process));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Finds association by executable name.
|
||||
/// </summary>
|
||||
public ProcessPowerPlanAssociation? FindAssociationByExecutable(string executableName)
|
||||
{
|
||||
return this.Associations
|
||||
.FirstOrDefault(a => a.MatchesExecutable(executableName));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Adds or updates an association.
|
||||
/// </summary>
|
||||
public void AddOrUpdateAssociation(ProcessPowerPlanAssociation association)
|
||||
{
|
||||
var existing = this.Associations.FirstOrDefault(a => a.Id == association.Id);
|
||||
if (existing != null)
|
||||
{
|
||||
var index = this.Associations.IndexOf(existing);
|
||||
this.Associations[index] = association;
|
||||
}
|
||||
else
|
||||
{
|
||||
this.Associations.Add(association);
|
||||
}
|
||||
this.LastSavedDate = DateTime.Now;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Removes an association.
|
||||
/// </summary>
|
||||
public bool RemoveAssociation(string associationId)
|
||||
{
|
||||
var association = this.Associations.FirstOrDefault(a => a.Id == associationId);
|
||||
if (association != null)
|
||||
{
|
||||
this.Associations.Remove(association);
|
||||
this.LastSavedDate = DateTime.Now;
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Validates the configuration.
|
||||
/// </summary>
|
||||
public List<string> Validate()
|
||||
{
|
||||
var errors = new List<string>();
|
||||
|
||||
if (this.PollingIntervalSeconds < 1)
|
||||
{
|
||||
errors.Add("Polling interval must be at least 1 second");
|
||||
}
|
||||
|
||||
if (this.PowerPlanChangeDelayMs < 0)
|
||||
{
|
||||
errors.Add("Power plan change delay cannot be negative");
|
||||
}
|
||||
|
||||
// Check for duplicate associations
|
||||
var duplicates = this.Associations
|
||||
.GroupBy(a => new { a.ExecutableName, a.MatchByPath })
|
||||
.Where(g => g.Count() > 1)
|
||||
.Select(g => g.Key.ExecutableName);
|
||||
|
||||
foreach (var duplicate in duplicates)
|
||||
{
|
||||
errors.Add($"Duplicate association found for executable: {duplicate}");
|
||||
}
|
||||
|
||||
return errors;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
namespace ThreadPilot.Models
|
||||
{
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
|
||||
public partial class ProcessMonitorConfiguration : ObservableObject
|
||||
{
|
||||
[ObservableProperty]
|
||||
private string defaultPowerPlanGuid = string.Empty;
|
||||
|
||||
[ObservableProperty]
|
||||
private string defaultPowerPlanName = string.Empty;
|
||||
|
||||
[ObservableProperty]
|
||||
private bool isEventBasedMonitoringEnabled = true;
|
||||
|
||||
[ObservableProperty]
|
||||
private bool isFallbackPollingEnabled = true;
|
||||
|
||||
[ObservableProperty]
|
||||
private int pollingIntervalSeconds = 5;
|
||||
|
||||
[ObservableProperty]
|
||||
private bool preventDuplicatePowerPlanChanges = true;
|
||||
|
||||
[ObservableProperty]
|
||||
private int powerPlanChangeDelayMs = 250;
|
||||
|
||||
[ObservableProperty]
|
||||
private bool enableLogging = true;
|
||||
|
||||
[ObservableProperty]
|
||||
private List<ProcessPowerPlanAssociation> associations = new();
|
||||
|
||||
[ObservableProperty]
|
||||
private DateTime lastSavedDate = DateTime.Now;
|
||||
|
||||
[ObservableProperty]
|
||||
private string configurationVersion = "1.0";
|
||||
|
||||
public ProcessMonitorConfiguration()
|
||||
{
|
||||
this.Associations = new List<ProcessPowerPlanAssociation>();
|
||||
}
|
||||
|
||||
public IEnumerable<ProcessPowerPlanAssociation> GetEnabledAssociations()
|
||||
{
|
||||
return this.Associations
|
||||
.Where(a => a.IsEnabled)
|
||||
.OrderByDescending(a => a.Priority)
|
||||
.ThenBy(a => a.ExecutableName);
|
||||
}
|
||||
|
||||
public ProcessPowerPlanAssociation? FindMatchingAssociation(ProcessModel process)
|
||||
{
|
||||
return this.GetEnabledAssociations()
|
||||
.FirstOrDefault(a => a.MatchesProcess(process));
|
||||
}
|
||||
|
||||
public ProcessPowerPlanAssociation? FindAssociationByExecutable(string executableName)
|
||||
{
|
||||
return this.Associations
|
||||
.FirstOrDefault(a => a.MatchesExecutable(executableName));
|
||||
}
|
||||
|
||||
public void AddOrUpdateAssociation(ProcessPowerPlanAssociation association)
|
||||
{
|
||||
var existing = this.Associations.FirstOrDefault(a => a.Id == association.Id);
|
||||
if (existing != null)
|
||||
{
|
||||
var index = this.Associations.IndexOf(existing);
|
||||
this.Associations[index] = association;
|
||||
}
|
||||
else
|
||||
{
|
||||
this.Associations.Add(association);
|
||||
}
|
||||
this.LastSavedDate = DateTime.Now;
|
||||
}
|
||||
|
||||
public bool RemoveAssociation(string associationId)
|
||||
{
|
||||
var association = this.Associations.FirstOrDefault(a => a.Id == associationId);
|
||||
if (association != null)
|
||||
{
|
||||
this.Associations.Remove(association);
|
||||
this.LastSavedDate = DateTime.Now;
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public List<string> Validate()
|
||||
{
|
||||
var errors = new List<string>();
|
||||
|
||||
if (this.PollingIntervalSeconds < 1)
|
||||
{
|
||||
errors.Add("Polling interval must be at least 1 second");
|
||||
}
|
||||
|
||||
if (this.PowerPlanChangeDelayMs < 0)
|
||||
{
|
||||
errors.Add("Power plan change delay cannot be negative");
|
||||
}
|
||||
|
||||
// Check for duplicate associations
|
||||
var duplicates = this.Associations
|
||||
.GroupBy(a => new { a.ExecutableName, a.MatchByPath })
|
||||
.Where(g => g.Count() > 1)
|
||||
.Select(g => g.Key.ExecutableName);
|
||||
|
||||
foreach (var duplicate in duplicates)
|
||||
{
|
||||
errors.Add($"Duplicate association found for executable: {duplicate}");
|
||||
}
|
||||
|
||||
return errors;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,193 +1,152 @@
|
||||
/*
|
||||
* ThreadPilot - Advanced Windows Process and Power Plan Manager
|
||||
* Copyright (C) 2025 Prime Build
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published by
|
||||
* the Free Software Foundation, version 3 only.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
namespace ThreadPilot.Models
|
||||
{
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
using ThreadPilot.Models.Core;
|
||||
|
||||
/// <summary>
|
||||
/// Represents an association between an executable and a power plan.
|
||||
/// </summary>
|
||||
public partial class ProcessPowerPlanAssociation : ObservableObject, IModel
|
||||
{
|
||||
[ObservableProperty]
|
||||
private string id = Guid.NewGuid().ToString();
|
||||
|
||||
[ObservableProperty]
|
||||
private string executableName = string.Empty;
|
||||
|
||||
[ObservableProperty]
|
||||
private string executablePath = string.Empty;
|
||||
|
||||
[ObservableProperty]
|
||||
private string powerPlanGuid = string.Empty;
|
||||
|
||||
[ObservableProperty]
|
||||
private string powerPlanName = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// Core mask ID to apply to this process (optional).
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private string? coreMaskId = null;
|
||||
|
||||
/// <summary>
|
||||
/// Core mask name for display (optional).
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private string? coreMaskName = null;
|
||||
|
||||
/// <summary>
|
||||
/// Process priority to apply (optional).
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private string? processPriority = null;
|
||||
|
||||
[ObservableProperty]
|
||||
private bool isEnabled = true;
|
||||
|
||||
[ObservableProperty]
|
||||
private DateTime createdAt = DateTime.UtcNow;
|
||||
|
||||
[ObservableProperty]
|
||||
private DateTime updatedAt = DateTime.UtcNow;
|
||||
|
||||
// IModel implementation - properties are auto-generated by ObservableProperty
|
||||
|
||||
[ObservableProperty]
|
||||
private string description = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// Whether to match by exact executable name or path.
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private bool matchByPath = false;
|
||||
|
||||
/// <summary>
|
||||
/// Priority for this association (higher number = higher priority)
|
||||
/// Used when multiple associations could match the same process.
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private int priority = 0;
|
||||
|
||||
public ProcessPowerPlanAssociation()
|
||||
{
|
||||
}
|
||||
|
||||
public ProcessPowerPlanAssociation(string executableName, string powerPlanGuid, string powerPlanName)
|
||||
{
|
||||
this.ExecutableName = executableName;
|
||||
this.PowerPlanGuid = powerPlanGuid;
|
||||
this.PowerPlanName = powerPlanName;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Checks if this association matches the given process.
|
||||
/// </summary>
|
||||
public bool MatchesProcess(ProcessModel process)
|
||||
{
|
||||
if (!this.IsEnabled)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (this.MatchByPath && !string.IsNullOrEmpty(this.ExecutablePath))
|
||||
{
|
||||
return string.Equals(process.ExecutablePath, this.ExecutablePath, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
else
|
||||
{
|
||||
var processName = NormalizeExecutableName(process.Name);
|
||||
var associationName = NormalizeExecutableName(this.ExecutableName);
|
||||
return string.Equals(processName, associationName, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Checks if this association matches the given executable name.
|
||||
/// </summary>
|
||||
public bool MatchesExecutable(string executableName)
|
||||
{
|
||||
if (!this.IsEnabled)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var associationName = NormalizeExecutableName(this.ExecutableName);
|
||||
var inputName = NormalizeExecutableName(executableName);
|
||||
return string.Equals(associationName, inputName, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
private static string NormalizeExecutableName(string? executableName)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(executableName))
|
||||
{
|
||||
return string.Empty;
|
||||
}
|
||||
|
||||
return Path.GetFileNameWithoutExtension(executableName.Trim());
|
||||
}
|
||||
|
||||
|
||||
|
||||
public ValidationResult Validate()
|
||||
{
|
||||
var errors = new List<string>();
|
||||
|
||||
if (string.IsNullOrWhiteSpace(this.ExecutableName))
|
||||
{
|
||||
errors.Add("Executable name is required");
|
||||
}
|
||||
|
||||
if (string.IsNullOrWhiteSpace(this.PowerPlanGuid))
|
||||
{
|
||||
errors.Add("Power plan GUID is required");
|
||||
}
|
||||
|
||||
if (string.IsNullOrWhiteSpace(this.PowerPlanName))
|
||||
{
|
||||
errors.Add("Power plan name is required");
|
||||
}
|
||||
|
||||
return errors.Count == 0 ? ValidationResult.Success() : ValidationResult.Failure(errors.ToArray());
|
||||
}
|
||||
|
||||
public IModel Clone()
|
||||
{
|
||||
return new ProcessPowerPlanAssociation
|
||||
{
|
||||
id = Guid.NewGuid().ToString(), // New ID for clone
|
||||
ExecutableName = this.ExecutableName,
|
||||
ExecutablePath = this.ExecutablePath,
|
||||
PowerPlanGuid = this.PowerPlanGuid,
|
||||
PowerPlanName = this.PowerPlanName,
|
||||
CoreMaskId = this.CoreMaskId,
|
||||
CoreMaskName = this.CoreMaskName,
|
||||
ProcessPriority = this.ProcessPriority,
|
||||
IsEnabled = this.IsEnabled,
|
||||
Description = this.Description,
|
||||
MatchByPath = this.MatchByPath,
|
||||
createdAt = DateTime.UtcNow,
|
||||
updatedAt = DateTime.UtcNow,
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
namespace ThreadPilot.Models
|
||||
{
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
using ThreadPilot.Models.Core;
|
||||
|
||||
public partial class ProcessPowerPlanAssociation : ObservableObject, IModel
|
||||
{
|
||||
[ObservableProperty]
|
||||
private string id = Guid.NewGuid().ToString();
|
||||
|
||||
[ObservableProperty]
|
||||
private string executableName = string.Empty;
|
||||
|
||||
[ObservableProperty]
|
||||
private string executablePath = string.Empty;
|
||||
|
||||
[ObservableProperty]
|
||||
private string powerPlanGuid = string.Empty;
|
||||
|
||||
[ObservableProperty]
|
||||
private string powerPlanName = string.Empty;
|
||||
|
||||
[ObservableProperty]
|
||||
private string? coreMaskId = null;
|
||||
|
||||
[ObservableProperty]
|
||||
private string? coreMaskName = null;
|
||||
|
||||
[ObservableProperty]
|
||||
private string? processPriority = null;
|
||||
|
||||
[ObservableProperty]
|
||||
private bool isEnabled = true;
|
||||
|
||||
[ObservableProperty]
|
||||
private DateTime createdAt = DateTime.UtcNow;
|
||||
|
||||
[ObservableProperty]
|
||||
private DateTime updatedAt = DateTime.UtcNow;
|
||||
|
||||
// IModel implementation - properties are auto-generated by ObservableProperty
|
||||
|
||||
[ObservableProperty]
|
||||
private string description = string.Empty;
|
||||
|
||||
[ObservableProperty]
|
||||
private bool matchByPath = false;
|
||||
|
||||
[ObservableProperty]
|
||||
private int priority = 0;
|
||||
|
||||
public ProcessPowerPlanAssociation()
|
||||
{
|
||||
}
|
||||
|
||||
public ProcessPowerPlanAssociation(string executableName, string powerPlanGuid, string powerPlanName)
|
||||
{
|
||||
this.ExecutableName = executableName;
|
||||
this.PowerPlanGuid = powerPlanGuid;
|
||||
this.PowerPlanName = powerPlanName;
|
||||
}
|
||||
|
||||
public bool MatchesProcess(ProcessModel process)
|
||||
{
|
||||
if (!this.IsEnabled)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (this.MatchByPath && !string.IsNullOrEmpty(this.ExecutablePath))
|
||||
{
|
||||
return string.Equals(process.ExecutablePath, this.ExecutablePath, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
else
|
||||
{
|
||||
var processName = NormalizeExecutableName(process.Name);
|
||||
var associationName = NormalizeExecutableName(this.ExecutableName);
|
||||
return string.Equals(processName, associationName, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
}
|
||||
|
||||
public bool MatchesExecutable(string executableName)
|
||||
{
|
||||
if (!this.IsEnabled)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var associationName = NormalizeExecutableName(this.ExecutableName);
|
||||
var inputName = NormalizeExecutableName(executableName);
|
||||
return string.Equals(associationName, inputName, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
private static string NormalizeExecutableName(string? executableName)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(executableName))
|
||||
{
|
||||
return string.Empty;
|
||||
}
|
||||
|
||||
return Path.GetFileNameWithoutExtension(executableName.Trim());
|
||||
}
|
||||
|
||||
|
||||
|
||||
public ValidationResult Validate()
|
||||
{
|
||||
var errors = new List<string>();
|
||||
|
||||
if (string.IsNullOrWhiteSpace(this.ExecutableName))
|
||||
{
|
||||
errors.Add("Executable name is required");
|
||||
}
|
||||
|
||||
if (string.IsNullOrWhiteSpace(this.PowerPlanGuid))
|
||||
{
|
||||
errors.Add("Power plan GUID is required");
|
||||
}
|
||||
|
||||
if (string.IsNullOrWhiteSpace(this.PowerPlanName))
|
||||
{
|
||||
errors.Add("Power plan name is required");
|
||||
}
|
||||
|
||||
return errors.Count == 0 ? ValidationResult.Success() : ValidationResult.Failure(errors.ToArray());
|
||||
}
|
||||
|
||||
public IModel Clone()
|
||||
{
|
||||
return new ProcessPowerPlanAssociation
|
||||
{
|
||||
id = Guid.NewGuid().ToString(), // New ID for clone
|
||||
ExecutableName = this.ExecutableName,
|
||||
ExecutablePath = this.ExecutablePath,
|
||||
PowerPlanGuid = this.PowerPlanGuid,
|
||||
PowerPlanName = this.PowerPlanName,
|
||||
CoreMaskId = this.CoreMaskId,
|
||||
CoreMaskName = this.CoreMaskName,
|
||||
ProcessPriority = this.ProcessPriority,
|
||||
IsEnabled = this.IsEnabled,
|
||||
Description = this.Description,
|
||||
MatchByPath = this.MatchByPath,
|
||||
createdAt = DateTime.UtcNow,
|
||||
updatedAt = DateTime.UtcNow,
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,35 +1,19 @@
|
||||
/*
|
||||
* ThreadPilot - Advanced Windows Process and Power Plan Manager
|
||||
* Copyright (C) 2025 Prime Build
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published by
|
||||
* the Free Software Foundation, version 3 only.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
namespace ThreadPilot.Models
|
||||
{
|
||||
using System.Diagnostics;
|
||||
|
||||
public sealed class ProcessProfileSnapshot
|
||||
{
|
||||
public int ProfileSchemaVersion { get; set; } = CpuAffinityProfileSchemaVersions.Legacy;
|
||||
|
||||
public string ProcessName { get; set; } = string.Empty;
|
||||
|
||||
public ProcessPriorityClass Priority { get; set; }
|
||||
|
||||
public long ProcessorAffinity { get; set; }
|
||||
|
||||
public CpuSelection? CpuSelection { get; set; }
|
||||
|
||||
public CpuSelectionMigrationMetadata? CpuSelectionMigration { get; set; }
|
||||
}
|
||||
}
|
||||
namespace ThreadPilot.Models
|
||||
{
|
||||
using System.Diagnostics;
|
||||
|
||||
public sealed class ProcessProfileSnapshot
|
||||
{
|
||||
public int ProfileSchemaVersion { get; set; } = CpuAffinityProfileSchemaVersions.Legacy;
|
||||
|
||||
public string ProcessName { get; set; } = string.Empty;
|
||||
|
||||
public ProcessPriorityClass Priority { get; set; }
|
||||
|
||||
public long ProcessorAffinity { get; set; }
|
||||
|
||||
public CpuSelection? CpuSelection { get; set; }
|
||||
|
||||
public CpuSelectionMigrationMetadata? CpuSelectionMigration { get; set; }
|
||||
}
|
||||
}
|
||||
|
||||
+91
-107
@@ -1,107 +1,91 @@
|
||||
/*
|
||||
* ThreadPilot - Advanced Windows Process and Power Plan Manager
|
||||
* Copyright (C) 2025 Prime Build
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published by
|
||||
* the Free Software Foundation, version 3 only.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
namespace ThreadPilot.Models
|
||||
{
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.ComponentModel;
|
||||
using System.Diagnostics;
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
using ThreadPilot.Models.Core;
|
||||
|
||||
public partial class ProfileModel : ObservableObject, IModel
|
||||
{
|
||||
[ObservableProperty]
|
||||
private string id = Guid.NewGuid().ToString();
|
||||
|
||||
[ObservableProperty]
|
||||
private DateTime createdAt = DateTime.UtcNow;
|
||||
|
||||
[ObservableProperty]
|
||||
private DateTime updatedAt = DateTime.UtcNow;
|
||||
|
||||
[ObservableProperty]
|
||||
private string name = string.Empty;
|
||||
|
||||
[ObservableProperty]
|
||||
private string processName = string.Empty;
|
||||
|
||||
[ObservableProperty]
|
||||
private ProcessPriorityClass priority = ProcessPriorityClass.Normal;
|
||||
|
||||
[ObservableProperty]
|
||||
private long processorAffinity = -1; // All cores
|
||||
|
||||
[ObservableProperty]
|
||||
private int profileSchemaVersion = CpuAffinityProfileSchemaVersions.Legacy;
|
||||
|
||||
[ObservableProperty]
|
||||
private CpuSelection? cpuSelection = null;
|
||||
|
||||
[ObservableProperty]
|
||||
private CpuSelectionMigrationMetadata? cpuSelectionMigration = null;
|
||||
|
||||
[ObservableProperty]
|
||||
private string description = string.Empty;
|
||||
|
||||
[ObservableProperty]
|
||||
private bool isEnabled = true;
|
||||
|
||||
// IModel implementation - properties are auto-generated by ObservableProperty
|
||||
|
||||
public ValidationResult Validate()
|
||||
{
|
||||
var errors = new List<string>();
|
||||
|
||||
if (string.IsNullOrWhiteSpace(this.Name))
|
||||
{
|
||||
errors.Add("Profile name is required");
|
||||
}
|
||||
|
||||
if (string.IsNullOrWhiteSpace(this.ProcessName))
|
||||
{
|
||||
errors.Add("Process name is required");
|
||||
}
|
||||
|
||||
return errors.Count == 0 ? ValidationResult.Success() : ValidationResult.Failure(errors.ToArray());
|
||||
}
|
||||
|
||||
public IModel Clone()
|
||||
{
|
||||
return new ProfileModel
|
||||
{
|
||||
id = Guid.NewGuid().ToString(), // New ID for clone
|
||||
Name = this.Name,
|
||||
ProcessName = this.ProcessName,
|
||||
Priority = this.Priority,
|
||||
ProcessorAffinity = this.ProcessorAffinity,
|
||||
ProfileSchemaVersion = this.ProfileSchemaVersion,
|
||||
CpuSelection = this.CpuSelection,
|
||||
CpuSelectionMigration = this.CpuSelectionMigration,
|
||||
Description = this.Description,
|
||||
IsEnabled = this.IsEnabled,
|
||||
createdAt = DateTime.UtcNow,
|
||||
updatedAt = DateTime.UtcNow,
|
||||
};
|
||||
}
|
||||
|
||||
partial void OnUpdatedAtChanged(DateTime value)
|
||||
{
|
||||
updatedAt = DateTime.UtcNow;
|
||||
}
|
||||
}
|
||||
}
|
||||
namespace ThreadPilot.Models
|
||||
{
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.ComponentModel;
|
||||
using System.Diagnostics;
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
using ThreadPilot.Models.Core;
|
||||
|
||||
public partial class ProfileModel : ObservableObject, IModel
|
||||
{
|
||||
[ObservableProperty]
|
||||
private string id = Guid.NewGuid().ToString();
|
||||
|
||||
[ObservableProperty]
|
||||
private DateTime createdAt = DateTime.UtcNow;
|
||||
|
||||
[ObservableProperty]
|
||||
private DateTime updatedAt = DateTime.UtcNow;
|
||||
|
||||
[ObservableProperty]
|
||||
private string name = string.Empty;
|
||||
|
||||
[ObservableProperty]
|
||||
private string processName = string.Empty;
|
||||
|
||||
[ObservableProperty]
|
||||
private ProcessPriorityClass priority = ProcessPriorityClass.Normal;
|
||||
|
||||
[ObservableProperty]
|
||||
private long processorAffinity = -1; // All cores
|
||||
|
||||
[ObservableProperty]
|
||||
private int profileSchemaVersion = CpuAffinityProfileSchemaVersions.Legacy;
|
||||
|
||||
[ObservableProperty]
|
||||
private CpuSelection? cpuSelection = null;
|
||||
|
||||
[ObservableProperty]
|
||||
private CpuSelectionMigrationMetadata? cpuSelectionMigration = null;
|
||||
|
||||
[ObservableProperty]
|
||||
private string description = string.Empty;
|
||||
|
||||
[ObservableProperty]
|
||||
private bool isEnabled = true;
|
||||
|
||||
// IModel implementation - properties are auto-generated by ObservableProperty
|
||||
|
||||
public ValidationResult Validate()
|
||||
{
|
||||
var errors = new List<string>();
|
||||
|
||||
if (string.IsNullOrWhiteSpace(this.Name))
|
||||
{
|
||||
errors.Add("Profile name is required");
|
||||
}
|
||||
|
||||
if (string.IsNullOrWhiteSpace(this.ProcessName))
|
||||
{
|
||||
errors.Add("Process name is required");
|
||||
}
|
||||
|
||||
return errors.Count == 0 ? ValidationResult.Success() : ValidationResult.Failure(errors.ToArray());
|
||||
}
|
||||
|
||||
public IModel Clone()
|
||||
{
|
||||
return new ProfileModel
|
||||
{
|
||||
id = Guid.NewGuid().ToString(), // New ID for clone
|
||||
Name = this.Name,
|
||||
ProcessName = this.ProcessName,
|
||||
Priority = this.Priority,
|
||||
ProcessorAffinity = this.ProcessorAffinity,
|
||||
ProfileSchemaVersion = this.ProfileSchemaVersion,
|
||||
CpuSelection = this.CpuSelection,
|
||||
CpuSelectionMigration = this.CpuSelectionMigration,
|
||||
Description = this.Description,
|
||||
IsEnabled = this.IsEnabled,
|
||||
createdAt = DateTime.UtcNow,
|
||||
updatedAt = DateTime.UtcNow,
|
||||
};
|
||||
}
|
||||
|
||||
partial void OnUpdatedAtChanged(DateTime value)
|
||||
{
|
||||
updatedAt = DateTime.UtcNow;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+115
-162
@@ -1,162 +1,115 @@
|
||||
/*
|
||||
* ThreadPilot - exception hierarchy and error code registry.
|
||||
*/
|
||||
namespace ThreadPilot.Models
|
||||
{
|
||||
using System;
|
||||
|
||||
/// <summary>
|
||||
/// Defines stable error codes used in diagnostics and incident reporting.
|
||||
/// </summary>
|
||||
public enum ErrorCode
|
||||
{
|
||||
Unknown = 0,
|
||||
ProcessManagement = 1000,
|
||||
Privilege = 2000,
|
||||
RuleEngine = 3000,
|
||||
ResourceOptimization = 4000,
|
||||
Persistence = 5000,
|
||||
Unhandled = 9000,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Base exception type for domain-level ThreadPilot failures.
|
||||
/// </summary>
|
||||
public class ThreadPilotException : Exception
|
||||
{
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ThreadPilotException"/> class.
|
||||
/// </summary>
|
||||
public ThreadPilotException()
|
||||
: this("A ThreadPilot error has occurred.", ErrorCode.Unknown)
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ThreadPilotException"/> class.
|
||||
/// </summary>
|
||||
/// <param name="message">Error message.</param>
|
||||
public ThreadPilotException(string message)
|
||||
: this(message, ErrorCode.Unknown)
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ThreadPilotException"/> class.
|
||||
/// </summary>
|
||||
/// <param name="message">Error message.</param>
|
||||
/// <param name="innerException">Inner exception.</param>
|
||||
public ThreadPilotException(string message, Exception innerException)
|
||||
: this(message, ErrorCode.Unknown, innerException)
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ThreadPilotException"/> class.
|
||||
/// </summary>
|
||||
/// <param name="message">Error message.</param>
|
||||
/// <param name="errorCode">Domain error code.</param>
|
||||
public ThreadPilotException(string message, ErrorCode errorCode)
|
||||
: base(message)
|
||||
{
|
||||
this.ErrorCode = errorCode;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ThreadPilotException"/> class.
|
||||
/// </summary>
|
||||
/// <param name="message">Error message.</param>
|
||||
/// <param name="errorCode">Domain error code.</param>
|
||||
/// <param name="innerException">Inner exception.</param>
|
||||
public ThreadPilotException(string message, ErrorCode errorCode, Exception innerException)
|
||||
: base(message, innerException)
|
||||
{
|
||||
this.ErrorCode = errorCode;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the domain error code associated with this exception.
|
||||
/// </summary>
|
||||
public ErrorCode ErrorCode { get; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Exception for process monitoring and process-control failures.
|
||||
/// </summary>
|
||||
public sealed class ProcessManagementException : ThreadPilotException
|
||||
{
|
||||
public ProcessManagementException(string message)
|
||||
: base(message, ErrorCode.ProcessManagement)
|
||||
{
|
||||
}
|
||||
|
||||
public ProcessManagementException(string message, Exception innerException)
|
||||
: base(message, ErrorCode.ProcessManagement, innerException)
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Exception for privilege and elevation failures.
|
||||
/// </summary>
|
||||
public sealed class PrivilegeException : ThreadPilotException
|
||||
{
|
||||
public PrivilegeException(string message)
|
||||
: base(message, ErrorCode.Privilege)
|
||||
{
|
||||
}
|
||||
|
||||
public PrivilegeException(string message, Exception innerException)
|
||||
: base(message, ErrorCode.Privilege, innerException)
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Exception for rule parsing and rule-matching failures.
|
||||
/// </summary>
|
||||
public sealed class RuleEngineException : ThreadPilotException
|
||||
{
|
||||
public RuleEngineException(string message)
|
||||
: base(message, ErrorCode.RuleEngine)
|
||||
{
|
||||
}
|
||||
|
||||
public RuleEngineException(string message, Exception innerException)
|
||||
: base(message, ErrorCode.RuleEngine, innerException)
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Exception for performance/resource optimization failures.
|
||||
/// </summary>
|
||||
public sealed class ResourceOptimizationException : ThreadPilotException
|
||||
{
|
||||
public ResourceOptimizationException(string message)
|
||||
: base(message, ErrorCode.ResourceOptimization)
|
||||
{
|
||||
}
|
||||
|
||||
public ResourceOptimizationException(string message, Exception innerException)
|
||||
: base(message, ErrorCode.ResourceOptimization, innerException)
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Exception for persistence/configuration I/O failures.
|
||||
/// </summary>
|
||||
public sealed class PersistenceException : ThreadPilotException
|
||||
{
|
||||
public PersistenceException(string message)
|
||||
: base(message, ErrorCode.Persistence)
|
||||
{
|
||||
}
|
||||
|
||||
public PersistenceException(string message, Exception innerException)
|
||||
: base(message, ErrorCode.Persistence, innerException)
|
||||
{
|
||||
}
|
||||
}
|
||||
}
|
||||
/*
|
||||
* ThreadPilot - exception hierarchy and error code registry.
|
||||
*/
|
||||
namespace ThreadPilot.Models
|
||||
{
|
||||
using System;
|
||||
|
||||
public enum ErrorCode
|
||||
{
|
||||
Unknown = 0,
|
||||
ProcessManagement = 1000,
|
||||
Privilege = 2000,
|
||||
RuleEngine = 3000,
|
||||
ResourceOptimization = 4000,
|
||||
Persistence = 5000,
|
||||
Unhandled = 9000,
|
||||
}
|
||||
|
||||
public class ThreadPilotException : Exception
|
||||
{
|
||||
public ThreadPilotException()
|
||||
: this("A ThreadPilot error has occurred.", ErrorCode.Unknown)
|
||||
{
|
||||
}
|
||||
|
||||
public ThreadPilotException(string message)
|
||||
: this(message, ErrorCode.Unknown)
|
||||
{
|
||||
}
|
||||
|
||||
public ThreadPilotException(string message, Exception innerException)
|
||||
: this(message, ErrorCode.Unknown, innerException)
|
||||
{
|
||||
}
|
||||
|
||||
public ThreadPilotException(string message, ErrorCode errorCode)
|
||||
: base(message)
|
||||
{
|
||||
this.ErrorCode = errorCode;
|
||||
}
|
||||
|
||||
public ThreadPilotException(string message, ErrorCode errorCode, Exception innerException)
|
||||
: base(message, innerException)
|
||||
{
|
||||
this.ErrorCode = errorCode;
|
||||
}
|
||||
|
||||
public ErrorCode ErrorCode { get; }
|
||||
}
|
||||
|
||||
public sealed class ProcessManagementException : ThreadPilotException
|
||||
{
|
||||
public ProcessManagementException(string message)
|
||||
: base(message, ErrorCode.ProcessManagement)
|
||||
{
|
||||
}
|
||||
|
||||
public ProcessManagementException(string message, Exception innerException)
|
||||
: base(message, ErrorCode.ProcessManagement, innerException)
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class PrivilegeException : ThreadPilotException
|
||||
{
|
||||
public PrivilegeException(string message)
|
||||
: base(message, ErrorCode.Privilege)
|
||||
{
|
||||
}
|
||||
|
||||
public PrivilegeException(string message, Exception innerException)
|
||||
: base(message, ErrorCode.Privilege, innerException)
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class RuleEngineException : ThreadPilotException
|
||||
{
|
||||
public RuleEngineException(string message)
|
||||
: base(message, ErrorCode.RuleEngine)
|
||||
{
|
||||
}
|
||||
|
||||
public RuleEngineException(string message, Exception innerException)
|
||||
: base(message, ErrorCode.RuleEngine, innerException)
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class ResourceOptimizationException : ThreadPilotException
|
||||
{
|
||||
public ResourceOptimizationException(string message)
|
||||
: base(message, ErrorCode.ResourceOptimization)
|
||||
{
|
||||
}
|
||||
|
||||
public ResourceOptimizationException(string message, Exception innerException)
|
||||
: base(message, ErrorCode.ResourceOptimization, innerException)
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class PersistenceException : ThreadPilotException
|
||||
{
|
||||
public PersistenceException(string message)
|
||||
: base(message, ErrorCode.Persistence)
|
||||
{
|
||||
}
|
||||
|
||||
public PersistenceException(string message, Exception innerException)
|
||||
: base(message, ErrorCode.Persistence, innerException)
|
||||
{
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,46 +1,46 @@
|
||||
namespace ThreadPilot.Platforms.Windows
|
||||
{
|
||||
using ThreadPilot.Services;
|
||||
|
||||
public sealed record CpuSetApplyResult
|
||||
{
|
||||
public bool Success { get; init; }
|
||||
|
||||
public string ErrorCode { get; init; } = AffinityApplyErrorCodes.None;
|
||||
|
||||
public int Win32ErrorCode { get; init; }
|
||||
|
||||
public string UserMessage { get; init; } = string.Empty;
|
||||
|
||||
public string TechnicalMessage { get; init; } = string.Empty;
|
||||
|
||||
public bool IsAccessDenied { get; init; }
|
||||
|
||||
public bool IsAntiCheatLikely { get; init; }
|
||||
|
||||
public static CpuSetApplyResult Succeeded(string technicalMessage) =>
|
||||
new()
|
||||
{
|
||||
Success = true,
|
||||
TechnicalMessage = technicalMessage,
|
||||
};
|
||||
|
||||
public static CpuSetApplyResult Failed(
|
||||
string errorCode,
|
||||
string userMessage,
|
||||
string technicalMessage,
|
||||
int win32ErrorCode = 0,
|
||||
bool isAccessDenied = false,
|
||||
bool isAntiCheatLikely = false) =>
|
||||
new()
|
||||
{
|
||||
Success = false,
|
||||
ErrorCode = errorCode,
|
||||
UserMessage = userMessage,
|
||||
TechnicalMessage = technicalMessage,
|
||||
Win32ErrorCode = win32ErrorCode,
|
||||
IsAccessDenied = isAccessDenied,
|
||||
IsAntiCheatLikely = isAntiCheatLikely,
|
||||
};
|
||||
}
|
||||
}
|
||||
namespace ThreadPilot.Platforms.Windows
|
||||
{
|
||||
using ThreadPilot.Services;
|
||||
|
||||
public sealed record CpuSetApplyResult
|
||||
{
|
||||
public bool Success { get; init; }
|
||||
|
||||
public string ErrorCode { get; init; } = AffinityApplyErrorCodes.None;
|
||||
|
||||
public int Win32ErrorCode { get; init; }
|
||||
|
||||
public string UserMessage { get; init; } = string.Empty;
|
||||
|
||||
public string TechnicalMessage { get; init; } = string.Empty;
|
||||
|
||||
public bool IsAccessDenied { get; init; }
|
||||
|
||||
public bool IsAntiCheatLikely { get; init; }
|
||||
|
||||
public static CpuSetApplyResult Succeeded(string technicalMessage) =>
|
||||
new()
|
||||
{
|
||||
Success = true,
|
||||
TechnicalMessage = technicalMessage,
|
||||
};
|
||||
|
||||
public static CpuSetApplyResult Failed(
|
||||
string errorCode,
|
||||
string userMessage,
|
||||
string technicalMessage,
|
||||
int win32ErrorCode = 0,
|
||||
bool isAccessDenied = false,
|
||||
bool isAntiCheatLikely = false) =>
|
||||
new()
|
||||
{
|
||||
Success = false,
|
||||
ErrorCode = errorCode,
|
||||
UserMessage = userMessage,
|
||||
TechnicalMessage = technicalMessage,
|
||||
Win32ErrorCode = win32ErrorCode,
|
||||
IsAccessDenied = isAccessDenied,
|
||||
IsAntiCheatLikely = isAntiCheatLikely,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
+113
-129
@@ -1,129 +1,113 @@
|
||||
/*
|
||||
* ThreadPilot - Advanced Windows Process and Power Plan Manager
|
||||
* Copyright (C) 2025 Prime Build
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published by
|
||||
* the Free Software Foundation, version 3 only.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
namespace ThreadPilot.Platforms.Windows
|
||||
{
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using ThreadPilot.Models;
|
||||
|
||||
internal sealed class CpuSetMapping
|
||||
{
|
||||
private readonly IReadOnlyDictionary<ProcessorRef, uint> cpuSetIdsByProcessor;
|
||||
private readonly IReadOnlyDictionary<uint, ProcessorRef> processorsByCpuSetId;
|
||||
|
||||
private CpuSetMapping(
|
||||
IReadOnlyDictionary<ProcessorRef, uint> cpuSetIdsByProcessor,
|
||||
IReadOnlyDictionary<uint, ProcessorRef> processorsByCpuSetId)
|
||||
{
|
||||
this.cpuSetIdsByProcessor = cpuSetIdsByProcessor;
|
||||
this.processorsByCpuSetId = processorsByCpuSetId;
|
||||
}
|
||||
|
||||
public static CpuSetMapping Empty { get; } = new(
|
||||
new Dictionary<ProcessorRef, uint>(),
|
||||
new Dictionary<uint, ProcessorRef>());
|
||||
|
||||
public bool IsEmpty => this.cpuSetIdsByProcessor.Count == 0;
|
||||
|
||||
public static CpuSetMapping Create(IReadOnlyDictionary<ProcessorRef, uint> cpuSetIdsByProcessor)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(cpuSetIdsByProcessor);
|
||||
|
||||
var forwardMap = cpuSetIdsByProcessor
|
||||
.OrderBy(kvp => kvp.Key.GlobalIndex)
|
||||
.ThenBy(kvp => kvp.Key.Group)
|
||||
.ThenBy(kvp => kvp.Key.LogicalProcessorNumber)
|
||||
.ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
|
||||
|
||||
var inverseMap = forwardMap
|
||||
.GroupBy(kvp => kvp.Value)
|
||||
.ToDictionary(
|
||||
group => group.Key,
|
||||
group => group
|
||||
.Select(kvp => kvp.Key)
|
||||
.OrderBy(processor => processor.GlobalIndex)
|
||||
.ThenBy(processor => processor.Group)
|
||||
.ThenBy(processor => processor.LogicalProcessorNumber)
|
||||
.First());
|
||||
|
||||
return new CpuSetMapping(forwardMap, inverseMap);
|
||||
}
|
||||
|
||||
public static ProcessorRef CreateProcessorRef(ushort group, byte logicalProcessorNumber)
|
||||
{
|
||||
return new ProcessorRef(group, logicalProcessorNumber, (group * 64) + logicalProcessorNumber);
|
||||
}
|
||||
|
||||
public bool TryGetCpuSetId(ProcessorRef processor, out uint cpuSetId)
|
||||
{
|
||||
return this.cpuSetIdsByProcessor.TryGetValue(processor, out cpuSetId);
|
||||
}
|
||||
|
||||
public bool TryGetProcessorRef(uint cpuSetId, out ProcessorRef processor)
|
||||
{
|
||||
return this.processorsByCpuSetId.TryGetValue(cpuSetId, out processor);
|
||||
}
|
||||
|
||||
public IReadOnlyList<uint> ResolveCpuSetIds(CpuSelection selection)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(selection);
|
||||
|
||||
if (selection.CpuSetIds.Count > 0)
|
||||
{
|
||||
return selection.CpuSetIds
|
||||
.Distinct()
|
||||
.OrderBy(cpuSetId => cpuSetId)
|
||||
.ToList();
|
||||
}
|
||||
|
||||
return selection.LogicalProcessors
|
||||
.Select(processor => this.TryGetCpuSetId(processor, out var cpuSetId) ? (uint?)cpuSetId : null)
|
||||
.Where(cpuSetId => cpuSetId.HasValue)
|
||||
.Select(cpuSetId => cpuSetId!.Value)
|
||||
.Distinct()
|
||||
.OrderBy(cpuSetId => cpuSetId)
|
||||
.ToList();
|
||||
}
|
||||
|
||||
public IReadOnlyList<uint> ResolveLegacyAffinityMask(long affinityMask, int logicalProcessorCount)
|
||||
{
|
||||
var unsignedMask = unchecked((ulong)affinityMask);
|
||||
var maxLegacyBits = Math.Min(Math.Max(logicalProcessorCount, 0), 64);
|
||||
var cpuSetIds = new List<uint>();
|
||||
|
||||
for (var bit = 0; bit < maxLegacyBits; bit++)
|
||||
{
|
||||
if ((unsignedMask & (1UL << bit)) == 0)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var processor = CreateProcessorRef(0, (byte)bit);
|
||||
if (this.TryGetCpuSetId(processor, out var cpuSetId))
|
||||
{
|
||||
cpuSetIds.Add(cpuSetId);
|
||||
}
|
||||
}
|
||||
|
||||
return cpuSetIds
|
||||
.Distinct()
|
||||
.OrderBy(cpuSetId => cpuSetId)
|
||||
.ToList();
|
||||
}
|
||||
}
|
||||
}
|
||||
namespace ThreadPilot.Platforms.Windows
|
||||
{
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using ThreadPilot.Models;
|
||||
|
||||
internal sealed class CpuSetMapping
|
||||
{
|
||||
private readonly IReadOnlyDictionary<ProcessorRef, uint> cpuSetIdsByProcessor;
|
||||
private readonly IReadOnlyDictionary<uint, ProcessorRef> processorsByCpuSetId;
|
||||
|
||||
private CpuSetMapping(
|
||||
IReadOnlyDictionary<ProcessorRef, uint> cpuSetIdsByProcessor,
|
||||
IReadOnlyDictionary<uint, ProcessorRef> processorsByCpuSetId)
|
||||
{
|
||||
this.cpuSetIdsByProcessor = cpuSetIdsByProcessor;
|
||||
this.processorsByCpuSetId = processorsByCpuSetId;
|
||||
}
|
||||
|
||||
public static CpuSetMapping Empty { get; } = new(
|
||||
new Dictionary<ProcessorRef, uint>(),
|
||||
new Dictionary<uint, ProcessorRef>());
|
||||
|
||||
public bool IsEmpty => this.cpuSetIdsByProcessor.Count == 0;
|
||||
|
||||
public static CpuSetMapping Create(IReadOnlyDictionary<ProcessorRef, uint> cpuSetIdsByProcessor)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(cpuSetIdsByProcessor);
|
||||
|
||||
var forwardMap = cpuSetIdsByProcessor
|
||||
.OrderBy(kvp => kvp.Key.GlobalIndex)
|
||||
.ThenBy(kvp => kvp.Key.Group)
|
||||
.ThenBy(kvp => kvp.Key.LogicalProcessorNumber)
|
||||
.ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
|
||||
|
||||
var inverseMap = forwardMap
|
||||
.GroupBy(kvp => kvp.Value)
|
||||
.ToDictionary(
|
||||
group => group.Key,
|
||||
group => group
|
||||
.Select(kvp => kvp.Key)
|
||||
.OrderBy(processor => processor.GlobalIndex)
|
||||
.ThenBy(processor => processor.Group)
|
||||
.ThenBy(processor => processor.LogicalProcessorNumber)
|
||||
.First());
|
||||
|
||||
return new CpuSetMapping(forwardMap, inverseMap);
|
||||
}
|
||||
|
||||
public static ProcessorRef CreateProcessorRef(ushort group, byte logicalProcessorNumber)
|
||||
{
|
||||
return new ProcessorRef(group, logicalProcessorNumber, (group * 64) + logicalProcessorNumber);
|
||||
}
|
||||
|
||||
public bool TryGetCpuSetId(ProcessorRef processor, out uint cpuSetId)
|
||||
{
|
||||
return this.cpuSetIdsByProcessor.TryGetValue(processor, out cpuSetId);
|
||||
}
|
||||
|
||||
public bool TryGetProcessorRef(uint cpuSetId, out ProcessorRef processor)
|
||||
{
|
||||
return this.processorsByCpuSetId.TryGetValue(cpuSetId, out processor);
|
||||
}
|
||||
|
||||
public IReadOnlyList<uint> ResolveCpuSetIds(CpuSelection selection)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(selection);
|
||||
|
||||
if (selection.CpuSetIds.Count > 0)
|
||||
{
|
||||
return selection.CpuSetIds
|
||||
.Distinct()
|
||||
.OrderBy(cpuSetId => cpuSetId)
|
||||
.ToList();
|
||||
}
|
||||
|
||||
return selection.LogicalProcessors
|
||||
.Select(processor => this.TryGetCpuSetId(processor, out var cpuSetId) ? (uint?)cpuSetId : null)
|
||||
.Where(cpuSetId => cpuSetId.HasValue)
|
||||
.Select(cpuSetId => cpuSetId!.Value)
|
||||
.Distinct()
|
||||
.OrderBy(cpuSetId => cpuSetId)
|
||||
.ToList();
|
||||
}
|
||||
|
||||
public IReadOnlyList<uint> ResolveLegacyAffinityMask(long affinityMask, int logicalProcessorCount)
|
||||
{
|
||||
var unsignedMask = unchecked((ulong)affinityMask);
|
||||
var maxLegacyBits = Math.Min(Math.Max(logicalProcessorCount, 0), 64);
|
||||
var cpuSetIds = new List<uint>();
|
||||
|
||||
for (var bit = 0; bit < maxLegacyBits; bit++)
|
||||
{
|
||||
if ((unsignedMask & (1UL << bit)) == 0)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var processor = CreateProcessorRef(0, (byte)bit);
|
||||
if (this.TryGetCpuSetId(processor, out var cpuSetId))
|
||||
{
|
||||
cpuSetIds.Add(cpuSetId);
|
||||
}
|
||||
}
|
||||
|
||||
return cpuSetIds
|
||||
.Distinct()
|
||||
.OrderBy(cpuSetId => cpuSetId)
|
||||
.ToList();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,83 +1,64 @@
|
||||
/*
|
||||
* ThreadPilot - Advanced Windows Process and Power Plan Manager
|
||||
* Copyright (C) 2025 Prime Build
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published by
|
||||
* the Free Software Foundation, version 3 only.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
namespace ThreadPilot.Platforms.Windows
|
||||
{
|
||||
using System;
|
||||
using System.Runtime.InteropServices;
|
||||
using Microsoft.Win32.SafeHandles;
|
||||
|
||||
/// <summary>
|
||||
/// P/Invoke declarations for Windows CPU Set APIs.
|
||||
/// </summary>
|
||||
internal static partial class CpuSetNativeMethods
|
||||
{
|
||||
[LibraryImport("kernel32.dll", SetLastError = true)]
|
||||
public static partial SafeProcessHandle OpenProcess(ProcessAccessFlags access, [MarshalAs(UnmanagedType.Bool)] bool inheritHandle, uint processId);
|
||||
|
||||
[LibraryImport("kernel32.dll", SetLastError = true)]
|
||||
[return: MarshalAs(UnmanagedType.Bool)]
|
||||
public static partial bool GetSystemCpuSetInformation(IntPtr Information, uint BufferLength, ref uint ReturnedLength, SafeProcessHandle Process, uint Flags);
|
||||
|
||||
[LibraryImport("kernel32.dll", SetLastError = true)]
|
||||
[return: MarshalAs(UnmanagedType.Bool)]
|
||||
public static partial bool SetProcessDefaultCpuSets(SafeProcessHandle Process, uint[]? CpuSetIds, uint CpuSetIdCount);
|
||||
|
||||
[LibraryImport("kernel32.dll", SetLastError = true)]
|
||||
[return: MarshalAs(UnmanagedType.Bool)]
|
||||
public static partial bool GetProcessTimes(SafeProcessHandle hProcess, out FILETIME lpCreationTime, out FILETIME lpExitTime, out FILETIME lpKernelTime, out FILETIME lpUserTime);
|
||||
}
|
||||
|
||||
[Flags]
|
||||
public enum ProcessAccessFlags : uint
|
||||
{
|
||||
PROCESS_SET_INFORMATION = 0x00000200,
|
||||
PROCESS_QUERY_LIMITED_INFORMATION = 0x00001000,
|
||||
PROCESS_SET_LIMITED_INFORMATION = 0x00002000,
|
||||
}
|
||||
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
public struct FILETIME
|
||||
{
|
||||
public uint DwLowDateTime;
|
||||
public uint DwHighDateTime;
|
||||
|
||||
public readonly ulong ULong => (((ulong)this.DwHighDateTime) << 32) + this.DwLowDateTime;
|
||||
}
|
||||
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
public struct SYSTEM_CPU_SET_INFORMATION
|
||||
{
|
||||
public uint Size;
|
||||
public CPU_SET_INFORMATION_TYPE Type;
|
||||
public uint Id;
|
||||
public ushort Group;
|
||||
public byte LogicalProcessorIndex;
|
||||
public byte CoreIndex;
|
||||
public byte LastLevelCacheIndex;
|
||||
public byte NumaNodeIndex;
|
||||
public byte EfficiencyClass;
|
||||
public byte AllFlags;
|
||||
public uint Reserved;
|
||||
public ulong AllocationTag;
|
||||
}
|
||||
|
||||
public enum CPU_SET_INFORMATION_TYPE : int
|
||||
{
|
||||
CpuSetInformation = 0,
|
||||
}
|
||||
}
|
||||
|
||||
namespace ThreadPilot.Platforms.Windows
|
||||
{
|
||||
using System;
|
||||
using System.Runtime.InteropServices;
|
||||
using Microsoft.Win32.SafeHandles;
|
||||
|
||||
internal static partial class CpuSetNativeMethods
|
||||
{
|
||||
[LibraryImport("kernel32.dll", SetLastError = true)]
|
||||
public static partial SafeProcessHandle OpenProcess(ProcessAccessFlags access, [MarshalAs(UnmanagedType.Bool)] bool inheritHandle, uint processId);
|
||||
|
||||
[LibraryImport("kernel32.dll", SetLastError = true)]
|
||||
[return: MarshalAs(UnmanagedType.Bool)]
|
||||
public static partial bool GetSystemCpuSetInformation(IntPtr Information, uint BufferLength, ref uint ReturnedLength, SafeProcessHandle Process, uint Flags);
|
||||
|
||||
[LibraryImport("kernel32.dll", SetLastError = true)]
|
||||
[return: MarshalAs(UnmanagedType.Bool)]
|
||||
public static partial bool SetProcessDefaultCpuSets(SafeProcessHandle Process, uint[]? CpuSetIds, uint CpuSetIdCount);
|
||||
|
||||
[LibraryImport("kernel32.dll", SetLastError = true)]
|
||||
[return: MarshalAs(UnmanagedType.Bool)]
|
||||
public static partial bool GetProcessTimes(SafeProcessHandle hProcess, out FILETIME lpCreationTime, out FILETIME lpExitTime, out FILETIME lpKernelTime, out FILETIME lpUserTime);
|
||||
}
|
||||
|
||||
[Flags]
|
||||
public enum ProcessAccessFlags : uint
|
||||
{
|
||||
PROCESS_SET_INFORMATION = 0x00000200,
|
||||
PROCESS_QUERY_LIMITED_INFORMATION = 0x00001000,
|
||||
PROCESS_SET_LIMITED_INFORMATION = 0x00002000,
|
||||
}
|
||||
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
public struct FILETIME
|
||||
{
|
||||
public uint DwLowDateTime;
|
||||
public uint DwHighDateTime;
|
||||
|
||||
public readonly ulong ULong => (((ulong)this.DwHighDateTime) << 32) + this.DwLowDateTime;
|
||||
}
|
||||
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
public struct SYSTEM_CPU_SET_INFORMATION
|
||||
{
|
||||
public uint Size;
|
||||
public CPU_SET_INFORMATION_TYPE Type;
|
||||
public uint Id;
|
||||
public ushort Group;
|
||||
public byte LogicalProcessorIndex;
|
||||
public byte CoreIndex;
|
||||
public byte LastLevelCacheIndex;
|
||||
public byte NumaNodeIndex;
|
||||
public byte EfficiencyClass;
|
||||
public byte AllFlags;
|
||||
public uint Reserved;
|
||||
public ulong AllocationTag;
|
||||
}
|
||||
|
||||
public enum CPU_SET_INFORMATION_TYPE : int
|
||||
{
|
||||
CpuSetInformation = 0,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,83 +1,24 @@
|
||||
/*
|
||||
* ThreadPilot - Advanced Windows Process and Power Plan Manager
|
||||
* Copyright (C) 2025 Prime Build
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published by
|
||||
* the Free Software Foundation, version 3 only.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
namespace ThreadPilot.Platforms.Windows
|
||||
{
|
||||
using System;
|
||||
using ThreadPilot.Models;
|
||||
|
||||
/// <summary>
|
||||
/// Interface for handling CPU Set operations on a specific process.
|
||||
/// </summary>
|
||||
public interface IProcessCpuSetHandler : IDisposable
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets the process ID this handler manages.
|
||||
/// </summary>
|
||||
uint ProcessId { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the executable name.
|
||||
/// </summary>
|
||||
string ExecutableName { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Applies a CPU affinity mask to the process using CPU Sets.
|
||||
/// This legacy path is valid only for single-processor-group systems with up to
|
||||
/// 64 logical processors. It will be superseded by <see cref="ApplyCpuSelection"/>
|
||||
/// for topology-aware CPU Set selection.
|
||||
/// </summary>
|
||||
/// <param name="affinityMask">The affinity mask where each bit represents a logical processor.</param>
|
||||
/// <param name="clearMask">If true, clears the CPU Set (allows all cores); if false, applies the mask.</param>
|
||||
/// <returns>True if the operation succeeded, false otherwise.</returns>
|
||||
bool ApplyCpuSetMask(long affinityMask, bool clearMask = false);
|
||||
|
||||
/// <summary>
|
||||
/// Applies a CPU affinity mask to the process using CPU Sets and returns detailed failure information.
|
||||
/// </summary>
|
||||
/// <param name="affinityMask">The affinity mask where each bit represents a logical processor.</param>
|
||||
/// <param name="clearMask">If true, clears the CPU Set (allows all cores); if false, applies the mask.</param>
|
||||
/// <returns>Detailed CPU Set apply result.</returns>
|
||||
CpuSetApplyResult ApplyCpuSetMaskDetailed(long affinityMask, bool clearMask = false);
|
||||
|
||||
/// <summary>
|
||||
/// Applies a topology-aware CPU selection to the process using CPU Sets.
|
||||
/// </summary>
|
||||
/// <param name="selection">The CPU selection to apply. Ignored and allowed to be null when <paramref name="clearSelection"/> is true.</param>
|
||||
/// <param name="clearSelection">If true, clears the CPU Set selection and ignores <paramref name="selection"/>.</param>
|
||||
/// <returns>True if the operation succeeded, false otherwise.</returns>
|
||||
bool ApplyCpuSelection(CpuSelection? selection, bool clearSelection = false);
|
||||
|
||||
/// <summary>
|
||||
/// Applies a topology-aware CPU selection to the process using CPU Sets and returns detailed failure information.
|
||||
/// </summary>
|
||||
/// <param name="selection">The CPU selection to apply. Ignored and allowed to be null when <paramref name="clearSelection"/> is true.</param>
|
||||
/// <param name="clearSelection">If true, clears the CPU Set selection and ignores <paramref name="selection"/>.</param>
|
||||
/// <returns>Detailed CPU Set apply result.</returns>
|
||||
CpuSetApplyResult ApplyCpuSelectionDetailed(CpuSelection? selection, bool clearSelection = false);
|
||||
|
||||
/// <summary>
|
||||
/// Gets the average CPU usage for this process.
|
||||
/// </summary>
|
||||
/// <returns>CPU usage percentage (0-1 range), or -1 if unavailable.</returns>
|
||||
double GetAverageCpuUsage();
|
||||
|
||||
/// <summary>
|
||||
/// Gets a value indicating whether checks if the handler has valid handles to the process.
|
||||
/// </summary>
|
||||
bool IsValid { get; }
|
||||
}
|
||||
}
|
||||
namespace ThreadPilot.Platforms.Windows
|
||||
{
|
||||
using System;
|
||||
using ThreadPilot.Models;
|
||||
|
||||
public interface IProcessCpuSetHandler : IDisposable
|
||||
{
|
||||
uint ProcessId { get; }
|
||||
|
||||
string ExecutableName { get; }
|
||||
|
||||
bool ApplyCpuSetMask(long affinityMask, bool clearMask = false);
|
||||
|
||||
CpuSetApplyResult ApplyCpuSetMaskDetailed(long affinityMask, bool clearMask = false);
|
||||
|
||||
bool ApplyCpuSelection(CpuSelection? selection, bool clearSelection = false);
|
||||
|
||||
CpuSetApplyResult ApplyCpuSelectionDetailed(CpuSelection? selection, bool clearSelection = false);
|
||||
|
||||
double GetAverageCpuUsage();
|
||||
|
||||
bool IsValid { get; }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,89 +1,73 @@
|
||||
/*
|
||||
* ThreadPilot - Advanced Windows Process and Power Plan Manager
|
||||
* Copyright (C) 2025 Prime Build
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published by
|
||||
* the Free Software Foundation, version 3 only.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
namespace ThreadPilot.Platforms.Windows
|
||||
{
|
||||
using System;
|
||||
using System.Runtime.InteropServices;
|
||||
using Microsoft.Win32.SafeHandles;
|
||||
|
||||
internal interface IProcessCpuSetNativeApi
|
||||
{
|
||||
SafeProcessHandle OpenProcess(ProcessAccessFlags access, bool inheritHandle, uint processId);
|
||||
|
||||
bool SetProcessDefaultCpuSets(SafeProcessHandle process, uint[]? cpuSetIds, uint cpuSetIdCount);
|
||||
|
||||
bool GetProcessTimes(
|
||||
SafeProcessHandle process,
|
||||
out FILETIME creationTime,
|
||||
out FILETIME exitTime,
|
||||
out FILETIME kernelTime,
|
||||
out FILETIME userTime);
|
||||
|
||||
bool GetSystemCpuSetInformation(
|
||||
IntPtr information,
|
||||
uint bufferLength,
|
||||
ref uint returnedLength,
|
||||
SafeProcessHandle process,
|
||||
uint flags);
|
||||
|
||||
int GetLastWin32Error();
|
||||
}
|
||||
|
||||
internal sealed class ProcessCpuSetNativeApi : IProcessCpuSetNativeApi
|
||||
{
|
||||
public static ProcessCpuSetNativeApi Instance { get; } = new();
|
||||
|
||||
private ProcessCpuSetNativeApi()
|
||||
{
|
||||
}
|
||||
|
||||
public SafeProcessHandle OpenProcess(ProcessAccessFlags access, bool inheritHandle, uint processId)
|
||||
{
|
||||
return CpuSetNativeMethods.OpenProcess(access, inheritHandle, processId);
|
||||
}
|
||||
|
||||
public bool SetProcessDefaultCpuSets(SafeProcessHandle process, uint[]? cpuSetIds, uint cpuSetIdCount)
|
||||
{
|
||||
return CpuSetNativeMethods.SetProcessDefaultCpuSets(process, cpuSetIds, cpuSetIdCount);
|
||||
}
|
||||
|
||||
public bool GetProcessTimes(
|
||||
SafeProcessHandle process,
|
||||
out FILETIME creationTime,
|
||||
out FILETIME exitTime,
|
||||
out FILETIME kernelTime,
|
||||
out FILETIME userTime)
|
||||
{
|
||||
return CpuSetNativeMethods.GetProcessTimes(process, out creationTime, out exitTime, out kernelTime, out userTime);
|
||||
}
|
||||
|
||||
public bool GetSystemCpuSetInformation(
|
||||
IntPtr information,
|
||||
uint bufferLength,
|
||||
ref uint returnedLength,
|
||||
SafeProcessHandle process,
|
||||
uint flags)
|
||||
{
|
||||
return CpuSetNativeMethods.GetSystemCpuSetInformation(information, bufferLength, ref returnedLength, process, flags);
|
||||
}
|
||||
|
||||
public int GetLastWin32Error()
|
||||
{
|
||||
return Marshal.GetLastWin32Error();
|
||||
}
|
||||
}
|
||||
}
|
||||
namespace ThreadPilot.Platforms.Windows
|
||||
{
|
||||
using System;
|
||||
using System.Runtime.InteropServices;
|
||||
using Microsoft.Win32.SafeHandles;
|
||||
|
||||
internal interface IProcessCpuSetNativeApi
|
||||
{
|
||||
SafeProcessHandle OpenProcess(ProcessAccessFlags access, bool inheritHandle, uint processId);
|
||||
|
||||
bool SetProcessDefaultCpuSets(SafeProcessHandle process, uint[]? cpuSetIds, uint cpuSetIdCount);
|
||||
|
||||
bool GetProcessTimes(
|
||||
SafeProcessHandle process,
|
||||
out FILETIME creationTime,
|
||||
out FILETIME exitTime,
|
||||
out FILETIME kernelTime,
|
||||
out FILETIME userTime);
|
||||
|
||||
bool GetSystemCpuSetInformation(
|
||||
IntPtr information,
|
||||
uint bufferLength,
|
||||
ref uint returnedLength,
|
||||
SafeProcessHandle process,
|
||||
uint flags);
|
||||
|
||||
int GetLastWin32Error();
|
||||
}
|
||||
|
||||
internal sealed class ProcessCpuSetNativeApi : IProcessCpuSetNativeApi
|
||||
{
|
||||
public static ProcessCpuSetNativeApi Instance { get; } = new();
|
||||
|
||||
private ProcessCpuSetNativeApi()
|
||||
{
|
||||
}
|
||||
|
||||
public SafeProcessHandle OpenProcess(ProcessAccessFlags access, bool inheritHandle, uint processId)
|
||||
{
|
||||
return CpuSetNativeMethods.OpenProcess(access, inheritHandle, processId);
|
||||
}
|
||||
|
||||
public bool SetProcessDefaultCpuSets(SafeProcessHandle process, uint[]? cpuSetIds, uint cpuSetIdCount)
|
||||
{
|
||||
return CpuSetNativeMethods.SetProcessDefaultCpuSets(process, cpuSetIds, cpuSetIdCount);
|
||||
}
|
||||
|
||||
public bool GetProcessTimes(
|
||||
SafeProcessHandle process,
|
||||
out FILETIME creationTime,
|
||||
out FILETIME exitTime,
|
||||
out FILETIME kernelTime,
|
||||
out FILETIME userTime)
|
||||
{
|
||||
return CpuSetNativeMethods.GetProcessTimes(process, out creationTime, out exitTime, out kernelTime, out userTime);
|
||||
}
|
||||
|
||||
public bool GetSystemCpuSetInformation(
|
||||
IntPtr information,
|
||||
uint bufferLength,
|
||||
ref uint returnedLength,
|
||||
SafeProcessHandle process,
|
||||
uint flags)
|
||||
{
|
||||
return CpuSetNativeMethods.GetSystemCpuSetInformation(information, bufferLength, ref returnedLength, process, flags);
|
||||
}
|
||||
|
||||
public int GetLastWin32Error()
|
||||
{
|
||||
return Marshal.GetLastWin32Error();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,88 +1,88 @@
|
||||
/*
|
||||
* ThreadPilot - Windows process memory priority native API abstraction.
|
||||
*/
|
||||
namespace ThreadPilot.Platforms.Windows
|
||||
{
|
||||
using System;
|
||||
using System.Runtime.InteropServices;
|
||||
using Microsoft.Win32.SafeHandles;
|
||||
|
||||
public interface IProcessMemoryPriorityNativeApi
|
||||
{
|
||||
bool IsSupported { get; }
|
||||
|
||||
SafeProcessHandle OpenProcess(ProcessAccessFlags access, bool inheritHandle, uint processId);
|
||||
|
||||
bool GetProcessInformation(
|
||||
SafeProcessHandle process,
|
||||
ProcessInformationClass processInformationClass,
|
||||
ref MemoryPriorityInformation processInformation,
|
||||
uint processInformationSize);
|
||||
|
||||
bool SetProcessInformation(
|
||||
SafeProcessHandle process,
|
||||
ProcessInformationClass processInformationClass,
|
||||
ref MemoryPriorityInformation processInformation,
|
||||
uint processInformationSize);
|
||||
|
||||
int GetLastWin32Error();
|
||||
}
|
||||
|
||||
public sealed class ProcessMemoryPriorityNativeApi : IProcessMemoryPriorityNativeApi
|
||||
{
|
||||
public static ProcessMemoryPriorityNativeApi Instance { get; } = new();
|
||||
|
||||
private ProcessMemoryPriorityNativeApi()
|
||||
{
|
||||
}
|
||||
|
||||
public bool IsSupported => OperatingSystem.IsWindowsVersionAtLeast(6, 2);
|
||||
|
||||
public SafeProcessHandle OpenProcess(ProcessAccessFlags access, bool inheritHandle, uint processId)
|
||||
{
|
||||
return ProcessMemoryPriorityNativeMethods.OpenProcess(access, inheritHandle, processId);
|
||||
}
|
||||
|
||||
public bool GetProcessInformation(
|
||||
SafeProcessHandle process,
|
||||
ProcessInformationClass processInformationClass,
|
||||
ref MemoryPriorityInformation processInformation,
|
||||
uint processInformationSize)
|
||||
{
|
||||
return ProcessMemoryPriorityNativeMethods.GetProcessInformation(
|
||||
process,
|
||||
processInformationClass,
|
||||
ref processInformation,
|
||||
processInformationSize);
|
||||
}
|
||||
|
||||
public bool SetProcessInformation(
|
||||
SafeProcessHandle process,
|
||||
ProcessInformationClass processInformationClass,
|
||||
ref MemoryPriorityInformation processInformation,
|
||||
uint processInformationSize)
|
||||
{
|
||||
return ProcessMemoryPriorityNativeMethods.SetProcessInformation(
|
||||
process,
|
||||
processInformationClass,
|
||||
ref processInformation,
|
||||
processInformationSize);
|
||||
}
|
||||
|
||||
public int GetLastWin32Error()
|
||||
{
|
||||
return Marshal.GetLastWin32Error();
|
||||
}
|
||||
}
|
||||
|
||||
public enum ProcessInformationClass
|
||||
{
|
||||
ProcessMemoryPriority = 0,
|
||||
}
|
||||
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
public struct MemoryPriorityInformation
|
||||
{
|
||||
public uint MemoryPriority;
|
||||
}
|
||||
}
|
||||
/*
|
||||
* ThreadPilot - Windows process memory priority native API abstraction.
|
||||
*/
|
||||
namespace ThreadPilot.Platforms.Windows
|
||||
{
|
||||
using System;
|
||||
using System.Runtime.InteropServices;
|
||||
using Microsoft.Win32.SafeHandles;
|
||||
|
||||
public interface IProcessMemoryPriorityNativeApi
|
||||
{
|
||||
bool IsSupported { get; }
|
||||
|
||||
SafeProcessHandle OpenProcess(ProcessAccessFlags access, bool inheritHandle, uint processId);
|
||||
|
||||
bool GetProcessInformation(
|
||||
SafeProcessHandle process,
|
||||
ProcessInformationClass processInformationClass,
|
||||
ref MemoryPriorityInformation processInformation,
|
||||
uint processInformationSize);
|
||||
|
||||
bool SetProcessInformation(
|
||||
SafeProcessHandle process,
|
||||
ProcessInformationClass processInformationClass,
|
||||
ref MemoryPriorityInformation processInformation,
|
||||
uint processInformationSize);
|
||||
|
||||
int GetLastWin32Error();
|
||||
}
|
||||
|
||||
public sealed class ProcessMemoryPriorityNativeApi : IProcessMemoryPriorityNativeApi
|
||||
{
|
||||
public static ProcessMemoryPriorityNativeApi Instance { get; } = new();
|
||||
|
||||
private ProcessMemoryPriorityNativeApi()
|
||||
{
|
||||
}
|
||||
|
||||
public bool IsSupported => OperatingSystem.IsWindowsVersionAtLeast(6, 2);
|
||||
|
||||
public SafeProcessHandle OpenProcess(ProcessAccessFlags access, bool inheritHandle, uint processId)
|
||||
{
|
||||
return ProcessMemoryPriorityNativeMethods.OpenProcess(access, inheritHandle, processId);
|
||||
}
|
||||
|
||||
public bool GetProcessInformation(
|
||||
SafeProcessHandle process,
|
||||
ProcessInformationClass processInformationClass,
|
||||
ref MemoryPriorityInformation processInformation,
|
||||
uint processInformationSize)
|
||||
{
|
||||
return ProcessMemoryPriorityNativeMethods.GetProcessInformation(
|
||||
process,
|
||||
processInformationClass,
|
||||
ref processInformation,
|
||||
processInformationSize);
|
||||
}
|
||||
|
||||
public bool SetProcessInformation(
|
||||
SafeProcessHandle process,
|
||||
ProcessInformationClass processInformationClass,
|
||||
ref MemoryPriorityInformation processInformation,
|
||||
uint processInformationSize)
|
||||
{
|
||||
return ProcessMemoryPriorityNativeMethods.SetProcessInformation(
|
||||
process,
|
||||
processInformationClass,
|
||||
ref processInformation,
|
||||
processInformationSize);
|
||||
}
|
||||
|
||||
public int GetLastWin32Error()
|
||||
{
|
||||
return Marshal.GetLastWin32Error();
|
||||
}
|
||||
}
|
||||
|
||||
public enum ProcessInformationClass
|
||||
{
|
||||
ProcessMemoryPriority = 0,
|
||||
}
|
||||
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
public struct MemoryPriorityInformation
|
||||
{
|
||||
public uint MemoryPriority;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,447 +1,424 @@
|
||||
/*
|
||||
* ThreadPilot - Advanced Windows Process and Power Plan Manager
|
||||
* Copyright (C) 2025 Prime Build
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published by
|
||||
* the Free Software Foundation, version 3 only.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
namespace ThreadPilot.Platforms.Windows
|
||||
{
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.ComponentModel;
|
||||
using System.Runtime.InteropServices;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Win32.SafeHandles;
|
||||
using ThreadPilot.Models;
|
||||
using ThreadPilot.Services;
|
||||
|
||||
/// <summary>
|
||||
/// Handles CPU Set operations for a specific process using Windows APIs
|
||||
/// Based on CPUSetSetter's ProcessHandlerWindows implementation.
|
||||
/// </summary>
|
||||
public class ProcessCpuSetHandler : IProcessCpuSetHandler
|
||||
{
|
||||
private static CpuSetMapping staticCpuSetMapping = CpuSetMapping.Empty;
|
||||
private static readonly object staticInitLock = new object();
|
||||
private static bool staticInitialized = false;
|
||||
|
||||
private readonly Queue<CpuTimeTimestamp> cpuTimeMovingAverageBuffer = new();
|
||||
private readonly string executableName;
|
||||
private readonly uint pid;
|
||||
private readonly IProcessCpuSetNativeApi nativeApi;
|
||||
private readonly CpuSetMapping cpuSetMapping;
|
||||
private readonly ILogger? logger;
|
||||
|
||||
private SafeProcessHandle? queryLimitedInfoHandle;
|
||||
private SafeProcessHandle? setLimitedInfoHandle;
|
||||
private bool disposed = false;
|
||||
|
||||
public ProcessCpuSetHandler(uint processId, string executableName, ILogger? logger = null)
|
||||
: this(processId, executableName, ProcessCpuSetNativeApi.Instance, EnsureStaticInitialization(ProcessCpuSetNativeApi.Instance), logger)
|
||||
{
|
||||
}
|
||||
|
||||
internal ProcessCpuSetHandler(
|
||||
uint processId,
|
||||
string executableName,
|
||||
IProcessCpuSetNativeApi nativeApi,
|
||||
CpuSetMapping cpuSetMapping,
|
||||
ILogger? logger = null)
|
||||
{
|
||||
this.pid = processId;
|
||||
this.executableName = executableName ?? $"PID_{processId}";
|
||||
this.nativeApi = nativeApi ?? throw new ArgumentNullException(nameof(nativeApi));
|
||||
this.cpuSetMapping = cpuSetMapping ?? throw new ArgumentNullException(nameof(cpuSetMapping));
|
||||
this.logger = logger;
|
||||
|
||||
// Open handle for querying process information
|
||||
this.queryLimitedInfoHandle = this.nativeApi.OpenProcess(
|
||||
ProcessAccessFlags.PROCESS_QUERY_LIMITED_INFORMATION,
|
||||
false,
|
||||
processId);
|
||||
|
||||
if (this.queryLimitedInfoHandle == null || this.queryLimitedInfoHandle.IsInvalid)
|
||||
{
|
||||
var error = this.nativeApi.GetLastWin32Error();
|
||||
this.logger?.LogWarning("Failed to open process {ProcessId} for querying: {Error}", processId, new Win32Exception(error).Message);
|
||||
}
|
||||
}
|
||||
|
||||
public uint ProcessId => this.pid;
|
||||
|
||||
public string ExecutableName => this.executableName;
|
||||
|
||||
public bool IsValid => this.queryLimitedInfoHandle != null && !this.queryLimitedInfoHandle.IsInvalid;
|
||||
|
||||
private static CpuSetMapping EnsureStaticInitialization(IProcessCpuSetNativeApi nativeApi)
|
||||
{
|
||||
if (staticInitialized)
|
||||
{
|
||||
return staticCpuSetMapping;
|
||||
}
|
||||
|
||||
lock (staticInitLock)
|
||||
{
|
||||
if (staticInitialized)
|
||||
{
|
||||
return staticCpuSetMapping;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
staticCpuSetMapping = GetCpuSetMapping(nativeApi);
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
// If we can't get CPU Set mapping, CPU Sets won't be available
|
||||
// The handler will still work but ApplyCpuSetMask will return false
|
||||
staticCpuSetMapping = CpuSetMapping.Empty;
|
||||
}
|
||||
|
||||
staticInitialized = true;
|
||||
return staticCpuSetMapping;
|
||||
}
|
||||
}
|
||||
|
||||
public double GetAverageCpuUsage()
|
||||
{
|
||||
if (this.queryLimitedInfoHandle == null || this.queryLimitedInfoHandle.IsInvalid)
|
||||
{
|
||||
return -1;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
DateTime now = DateTime.Now;
|
||||
|
||||
// Remove datapoints older than 30 seconds from the moving average buffer
|
||||
while (this.cpuTimeMovingAverageBuffer.Count > 0)
|
||||
{
|
||||
TimeSpan datapointAge = now - this.cpuTimeMovingAverageBuffer.Peek().Timestamp;
|
||||
if (datapointAge.TotalSeconds > 30)
|
||||
{
|
||||
this.cpuTimeMovingAverageBuffer.Dequeue();
|
||||
}
|
||||
else
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// Get the current total CPU time of the process
|
||||
bool success = this.nativeApi.GetProcessTimes(
|
||||
this.queryLimitedInfoHandle,
|
||||
out _,
|
||||
out _,
|
||||
out FILETIME kernelTime,
|
||||
out FILETIME userTime);
|
||||
|
||||
if (!success)
|
||||
{
|
||||
return -1;
|
||||
}
|
||||
|
||||
TimeSpan totalCpuTime = TimeSpan.FromTicks((long)(kernelTime.ULong + userTime.ULong));
|
||||
this.cpuTimeMovingAverageBuffer.Enqueue(new CpuTimeTimestamp
|
||||
{
|
||||
Timestamp = now,
|
||||
TotalCpuTime = totalCpuTime,
|
||||
});
|
||||
|
||||
// Need at least 2 samples to calculate usage
|
||||
if (this.cpuTimeMovingAverageBuffer.Count < 2)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
// Take the CPU time from now and (up to) a minute ago, and get the average usage %
|
||||
CpuTimeTimestamp startDatapoint = this.cpuTimeMovingAverageBuffer.Peek();
|
||||
TimeSpan deltaTime = now - startDatapoint.Timestamp;
|
||||
TimeSpan deltaCpuTime = totalCpuTime - startDatapoint.TotalCpuTime;
|
||||
|
||||
if (deltaCpuTime.Ticks == 0 || deltaTime.Ticks == 0)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
return (double)deltaCpuTime.Ticks / deltaTime.Ticks / Environment.ProcessorCount;
|
||||
}
|
||||
catch
|
||||
{
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
|
||||
public bool ApplyCpuSetMask(long affinityMask, bool clearMask = false) =>
|
||||
this.ApplyCpuSetMaskDetailed(affinityMask, clearMask).Success;
|
||||
|
||||
public CpuSetApplyResult ApplyCpuSetMaskDetailed(long affinityMask, bool clearMask = false)
|
||||
{
|
||||
if (this.disposed)
|
||||
{
|
||||
throw new ObjectDisposedException(nameof(ProcessCpuSetHandler));
|
||||
}
|
||||
|
||||
// Legacy mask support is intentionally limited to single-group systems where
|
||||
// logical processors 0-63 map to processor group 0. CpuSelection will replace
|
||||
// this path for group-aware selections in a later phase.
|
||||
if (this.cpuSetMapping.IsEmpty)
|
||||
{
|
||||
this.logger?.LogWarning("CPU Set mapping not available. Cannot apply CPU Sets to process {ProcessId}", this.pid);
|
||||
return CpuSetApplyResult.Failed(
|
||||
AffinityApplyErrorCodes.CpuSetsUnavailable,
|
||||
ProcessOperationUserMessages.CpuSetsUnavailable,
|
||||
$"CPU Set mapping is not available for process '{this.executableName}' (PID: {this.pid}).");
|
||||
}
|
||||
|
||||
var handleResult = this.EnsureSetHandleDetailed();
|
||||
if (!handleResult.Success)
|
||||
{
|
||||
return handleResult;
|
||||
}
|
||||
|
||||
if (clearMask)
|
||||
{
|
||||
return this.ApplyCpuSetIdsDetailed(null, 0, "clear CPU Set");
|
||||
}
|
||||
|
||||
var cpuSetIds = this.cpuSetMapping.ResolveLegacyAffinityMask(affinityMask, Environment.ProcessorCount);
|
||||
|
||||
if (cpuSetIds.Count == 0)
|
||||
{
|
||||
this.logger?.LogWarning(
|
||||
"No valid CPU Set IDs found for affinity mask 0x{AffinityMask:X} on process '{ExecutableName}'",
|
||||
affinityMask, this.executableName);
|
||||
return CpuSetApplyResult.Failed(
|
||||
AffinityApplyErrorCodes.InvalidTopology,
|
||||
ProcessOperationUserMessages.InvalidTopology,
|
||||
$"No valid CPU Set IDs found for affinity mask 0x{affinityMask:X} on process '{this.executableName}'.");
|
||||
}
|
||||
|
||||
var cpuSetIdsArray = cpuSetIds.ToArray();
|
||||
var result = this.ApplyCpuSetIdsDetailed(cpuSetIdsArray, (uint)cpuSetIdsArray.Length, "apply CPU Set");
|
||||
|
||||
if (result.Success)
|
||||
{
|
||||
this.logger?.LogInformation(
|
||||
"Applied CPU Set (affinity mask 0x{AffinityMask:X}) to '{ExecutableName}' (PID: {ProcessId})",
|
||||
affinityMask, this.executableName, this.pid);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
public bool ApplyCpuSelection(CpuSelection? selection, bool clearSelection = false) =>
|
||||
this.ApplyCpuSelectionDetailed(selection, clearSelection).Success;
|
||||
|
||||
public CpuSetApplyResult ApplyCpuSelectionDetailed(CpuSelection? selection, bool clearSelection = false)
|
||||
{
|
||||
if (this.disposed)
|
||||
{
|
||||
throw new ObjectDisposedException(nameof(ProcessCpuSetHandler));
|
||||
}
|
||||
|
||||
var handleResult = this.EnsureSetHandleDetailed();
|
||||
if (!handleResult.Success)
|
||||
{
|
||||
return handleResult;
|
||||
}
|
||||
|
||||
if (clearSelection)
|
||||
{
|
||||
return this.ApplyCpuSetIdsDetailed(null, 0, "clear CPU Set selection");
|
||||
}
|
||||
|
||||
ArgumentNullException.ThrowIfNull(selection);
|
||||
|
||||
var cpuSetIds = this.cpuSetMapping.ResolveCpuSetIds(selection);
|
||||
if (cpuSetIds.Count == 0)
|
||||
{
|
||||
this.logger?.LogWarning(
|
||||
"No valid CPU Set IDs resolved for CPU selection on process '{ExecutableName}' (PID: {ProcessId})",
|
||||
this.executableName,
|
||||
this.pid);
|
||||
return CpuSetApplyResult.Failed(
|
||||
AffinityApplyErrorCodes.InvalidTopology,
|
||||
ProcessOperationUserMessages.InvalidTopology,
|
||||
$"No valid CPU Set IDs resolved for CPU selection on process '{this.executableName}' (PID: {this.pid}).");
|
||||
}
|
||||
|
||||
var cpuSetIdsArray = cpuSetIds.ToArray();
|
||||
return this.ApplyCpuSetIdsDetailed(cpuSetIdsArray, (uint)cpuSetIdsArray.Length, "apply CPU Set selection");
|
||||
}
|
||||
|
||||
private bool EnsureSetHandle()
|
||||
{
|
||||
return this.EnsureSetHandleDetailed().Success;
|
||||
}
|
||||
|
||||
private CpuSetApplyResult EnsureSetHandleDetailed()
|
||||
{
|
||||
if (this.setLimitedInfoHandle == null)
|
||||
{
|
||||
this.setLimitedInfoHandle = this.nativeApi.OpenProcess(
|
||||
ProcessAccessFlags.PROCESS_SET_LIMITED_INFORMATION,
|
||||
false,
|
||||
this.pid);
|
||||
|
||||
if (this.setLimitedInfoHandle == null || this.setLimitedInfoHandle.IsInvalid)
|
||||
{
|
||||
int openError = this.nativeApi.GetLastWin32Error();
|
||||
string extraHelpString = (openError == 5)
|
||||
? $" {ProcessOperationUserMessages.AdminClarification}"
|
||||
: string.Empty;
|
||||
this.logger?.LogWarning(
|
||||
"Could not open process '{ExecutableName}' (PID: {ProcessId}) for setting affinity: {Error}{Help}",
|
||||
this.executableName, this.pid, new Win32Exception(openError).Message, extraHelpString);
|
||||
return this.CreateNativeFailureResult(
|
||||
"open process for CPU Set changes",
|
||||
openError);
|
||||
}
|
||||
}
|
||||
else if (this.setLimitedInfoHandle.IsInvalid)
|
||||
{
|
||||
// The handle was already made previously and failed, don't bother trying again
|
||||
return CpuSetApplyResult.Failed(
|
||||
AffinityApplyErrorCodes.CpuSetsUnavailable,
|
||||
ProcessOperationUserMessages.CpuSetsUnavailable,
|
||||
$"The cached CPU Set handle for '{this.executableName}' (PID: {this.pid}) is invalid.");
|
||||
}
|
||||
|
||||
return CpuSetApplyResult.Succeeded($"CPU Set handle is available for '{this.executableName}' (PID: {this.pid}).");
|
||||
}
|
||||
|
||||
private bool ApplyCpuSetIds(uint[]? cpuSetIds, uint cpuSetIdCount, string operationName)
|
||||
{
|
||||
return this.ApplyCpuSetIdsDetailed(cpuSetIds, cpuSetIdCount, operationName).Success;
|
||||
}
|
||||
|
||||
private CpuSetApplyResult ApplyCpuSetIdsDetailed(uint[]? cpuSetIds, uint cpuSetIdCount, string operationName)
|
||||
{
|
||||
bool success = this.nativeApi.SetProcessDefaultCpuSets(this.setLimitedInfoHandle!, cpuSetIds, cpuSetIdCount);
|
||||
if (success)
|
||||
{
|
||||
this.logger?.LogInformation(
|
||||
"Completed {OperationName} for '{ExecutableName}' (PID: {ProcessId})",
|
||||
operationName,
|
||||
this.executableName,
|
||||
this.pid);
|
||||
return CpuSetApplyResult.Succeeded(
|
||||
$"Completed {operationName} for '{this.executableName}' (PID: {this.pid}).");
|
||||
}
|
||||
|
||||
int error = this.nativeApi.GetLastWin32Error();
|
||||
string errorMessage = $"Could not {operationName} for '{this.executableName}' (PID: {this.pid}): {new Win32Exception(error).Message}";
|
||||
if (error == 5)
|
||||
{
|
||||
errorMessage += $" {ProcessOperationUserMessages.AdminClarification}";
|
||||
}
|
||||
|
||||
this.logger?.LogWarning(errorMessage);
|
||||
return this.CreateNativeFailureResult(operationName, error, errorMessage);
|
||||
}
|
||||
|
||||
private CpuSetApplyResult CreateNativeFailureResult(
|
||||
string operationName,
|
||||
int win32ErrorCode,
|
||||
string? technicalMessage = null)
|
||||
{
|
||||
var message = technicalMessage ??
|
||||
$"Could not {operationName} for '{this.executableName}' (PID: {this.pid}): {new Win32Exception(win32ErrorCode).Message}";
|
||||
var accessDenied = win32ErrorCode == 5;
|
||||
|
||||
return CpuSetApplyResult.Failed(
|
||||
accessDenied ? AffinityApplyErrorCodes.AccessDenied : AffinityApplyErrorCodes.NativeApplyFailed,
|
||||
accessDenied ? ProcessOperationUserMessages.AccessDenied : ProcessOperationUserMessages.CpuSetsUnavailable,
|
||||
message,
|
||||
win32ErrorCode,
|
||||
isAccessDenied: accessDenied);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the CPU Set ID of each logical processor keyed by processor group and group-relative logical processor number.
|
||||
/// </summary>
|
||||
private static CpuSetMapping GetCpuSetMapping(IProcessCpuSetNativeApi nativeApi)
|
||||
{
|
||||
uint bufferLength = 0;
|
||||
|
||||
// First call to get buffer size
|
||||
if (!nativeApi.GetSystemCpuSetInformation(IntPtr.Zero, 0, ref bufferLength, new SafeProcessHandle(), 0))
|
||||
{
|
||||
int error = nativeApi.GetLastWin32Error();
|
||||
if (error != 0x7A) // ERROR_INSUFFICIENT_BUFFER
|
||||
{
|
||||
throw new Win32Exception(error, "Failed to query CPU Set information buffer size");
|
||||
}
|
||||
}
|
||||
|
||||
Dictionary<ProcessorRef, uint> cpuSets = new Dictionary<ProcessorRef, uint>();
|
||||
IntPtr buffer = Marshal.AllocHGlobal((int)bufferLength);
|
||||
|
||||
try
|
||||
{
|
||||
// Second call to get actual data
|
||||
if (!nativeApi.GetSystemCpuSetInformation(buffer, bufferLength, ref bufferLength, new SafeProcessHandle(), 0))
|
||||
{
|
||||
throw new Win32Exception(nativeApi.GetLastWin32Error(), "Failed to get CPU Set information");
|
||||
}
|
||||
|
||||
IntPtr current = buffer;
|
||||
IntPtr bufferEnd = buffer + (int)bufferLength;
|
||||
|
||||
while (current.ToInt64() < bufferEnd.ToInt64())
|
||||
{
|
||||
SYSTEM_CPU_SET_INFORMATION item = Marshal.PtrToStructure<SYSTEM_CPU_SET_INFORMATION>(current);
|
||||
|
||||
if (item.Type != CPU_SET_INFORMATION_TYPE.CpuSetInformation)
|
||||
{
|
||||
throw new InvalidCastException("Invalid CPU Set information type encountered");
|
||||
}
|
||||
|
||||
var processor = CpuSetMapping.CreateProcessorRef(item.Group, item.LogicalProcessorIndex);
|
||||
cpuSets[processor] = item.Id;
|
||||
|
||||
current = IntPtr.Add(current, (int)item.Size);
|
||||
}
|
||||
|
||||
return CpuSetMapping.Create(cpuSets);
|
||||
}
|
||||
finally
|
||||
{
|
||||
Marshal.FreeHGlobal(buffer);
|
||||
}
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
if (this.disposed)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
this.queryLimitedInfoHandle?.Dispose();
|
||||
this.setLimitedInfoHandle?.Dispose();
|
||||
this.cpuTimeMovingAverageBuffer.Clear();
|
||||
|
||||
this.disposed = true;
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
|
||||
private class CpuTimeTimestamp
|
||||
{
|
||||
public DateTime Timestamp { get; init; }
|
||||
|
||||
public TimeSpan TotalCpuTime { get; init; }
|
||||
}
|
||||
}
|
||||
}
|
||||
namespace ThreadPilot.Platforms.Windows
|
||||
{
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.ComponentModel;
|
||||
using System.Runtime.InteropServices;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Win32.SafeHandles;
|
||||
using ThreadPilot.Models;
|
||||
using ThreadPilot.Services;
|
||||
|
||||
public class ProcessCpuSetHandler : IProcessCpuSetHandler
|
||||
{
|
||||
private static CpuSetMapping staticCpuSetMapping = CpuSetMapping.Empty;
|
||||
private static readonly object staticInitLock = new object();
|
||||
private static bool staticInitialized = false;
|
||||
|
||||
private readonly Queue<CpuTimeTimestamp> cpuTimeMovingAverageBuffer = new();
|
||||
private readonly string executableName;
|
||||
private readonly uint pid;
|
||||
private readonly IProcessCpuSetNativeApi nativeApi;
|
||||
private readonly CpuSetMapping cpuSetMapping;
|
||||
private readonly ILogger? logger;
|
||||
|
||||
private SafeProcessHandle? queryLimitedInfoHandle;
|
||||
private SafeProcessHandle? setLimitedInfoHandle;
|
||||
private bool disposed = false;
|
||||
|
||||
public ProcessCpuSetHandler(uint processId, string executableName, ILogger? logger = null)
|
||||
: this(processId, executableName, ProcessCpuSetNativeApi.Instance, EnsureStaticInitialization(ProcessCpuSetNativeApi.Instance), logger)
|
||||
{
|
||||
}
|
||||
|
||||
internal ProcessCpuSetHandler(
|
||||
uint processId,
|
||||
string executableName,
|
||||
IProcessCpuSetNativeApi nativeApi,
|
||||
CpuSetMapping cpuSetMapping,
|
||||
ILogger? logger = null)
|
||||
{
|
||||
this.pid = processId;
|
||||
this.executableName = executableName ?? $"PID_{processId}";
|
||||
this.nativeApi = nativeApi ?? throw new ArgumentNullException(nameof(nativeApi));
|
||||
this.cpuSetMapping = cpuSetMapping ?? throw new ArgumentNullException(nameof(cpuSetMapping));
|
||||
this.logger = logger;
|
||||
|
||||
// Open handle for querying process information
|
||||
this.queryLimitedInfoHandle = this.nativeApi.OpenProcess(
|
||||
ProcessAccessFlags.PROCESS_QUERY_LIMITED_INFORMATION,
|
||||
false,
|
||||
processId);
|
||||
|
||||
if (this.queryLimitedInfoHandle == null || this.queryLimitedInfoHandle.IsInvalid)
|
||||
{
|
||||
var error = this.nativeApi.GetLastWin32Error();
|
||||
this.logger?.LogWarning("Failed to open process {ProcessId} for querying: {Error}", processId, new Win32Exception(error).Message);
|
||||
}
|
||||
}
|
||||
|
||||
public uint ProcessId => this.pid;
|
||||
|
||||
public string ExecutableName => this.executableName;
|
||||
|
||||
public bool IsValid => this.queryLimitedInfoHandle != null && !this.queryLimitedInfoHandle.IsInvalid;
|
||||
|
||||
private static CpuSetMapping EnsureStaticInitialization(IProcessCpuSetNativeApi nativeApi)
|
||||
{
|
||||
if (staticInitialized)
|
||||
{
|
||||
return staticCpuSetMapping;
|
||||
}
|
||||
|
||||
lock (staticInitLock)
|
||||
{
|
||||
if (staticInitialized)
|
||||
{
|
||||
return staticCpuSetMapping;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
staticCpuSetMapping = GetCpuSetMapping(nativeApi);
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
// If we can't get CPU Set mapping, CPU Sets won't be available
|
||||
// The handler will still work but ApplyCpuSetMask will return false
|
||||
staticCpuSetMapping = CpuSetMapping.Empty;
|
||||
}
|
||||
|
||||
staticInitialized = true;
|
||||
return staticCpuSetMapping;
|
||||
}
|
||||
}
|
||||
|
||||
public double GetAverageCpuUsage()
|
||||
{
|
||||
if (this.queryLimitedInfoHandle == null || this.queryLimitedInfoHandle.IsInvalid)
|
||||
{
|
||||
return -1;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
DateTime now = DateTime.Now;
|
||||
|
||||
// Remove datapoints older than 30 seconds from the moving average buffer
|
||||
while (this.cpuTimeMovingAverageBuffer.Count > 0)
|
||||
{
|
||||
TimeSpan datapointAge = now - this.cpuTimeMovingAverageBuffer.Peek().Timestamp;
|
||||
if (datapointAge.TotalSeconds > 30)
|
||||
{
|
||||
this.cpuTimeMovingAverageBuffer.Dequeue();
|
||||
}
|
||||
else
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// Get the current total CPU time of the process
|
||||
bool success = this.nativeApi.GetProcessTimes(
|
||||
this.queryLimitedInfoHandle,
|
||||
out _,
|
||||
out _,
|
||||
out FILETIME kernelTime,
|
||||
out FILETIME userTime);
|
||||
|
||||
if (!success)
|
||||
{
|
||||
return -1;
|
||||
}
|
||||
|
||||
TimeSpan totalCpuTime = TimeSpan.FromTicks((long)(kernelTime.ULong + userTime.ULong));
|
||||
this.cpuTimeMovingAverageBuffer.Enqueue(new CpuTimeTimestamp
|
||||
{
|
||||
Timestamp = now,
|
||||
TotalCpuTime = totalCpuTime,
|
||||
});
|
||||
|
||||
// Need at least 2 samples to calculate usage
|
||||
if (this.cpuTimeMovingAverageBuffer.Count < 2)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
// Take the CPU time from now and (up to) a minute ago, and get the average usage %
|
||||
CpuTimeTimestamp startDatapoint = this.cpuTimeMovingAverageBuffer.Peek();
|
||||
TimeSpan deltaTime = now - startDatapoint.Timestamp;
|
||||
TimeSpan deltaCpuTime = totalCpuTime - startDatapoint.TotalCpuTime;
|
||||
|
||||
if (deltaCpuTime.Ticks == 0 || deltaTime.Ticks == 0)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
return (double)deltaCpuTime.Ticks / deltaTime.Ticks / Environment.ProcessorCount;
|
||||
}
|
||||
catch
|
||||
{
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
|
||||
public bool ApplyCpuSetMask(long affinityMask, bool clearMask = false) =>
|
||||
this.ApplyCpuSetMaskDetailed(affinityMask, clearMask).Success;
|
||||
|
||||
public CpuSetApplyResult ApplyCpuSetMaskDetailed(long affinityMask, bool clearMask = false)
|
||||
{
|
||||
if (this.disposed)
|
||||
{
|
||||
throw new ObjectDisposedException(nameof(ProcessCpuSetHandler));
|
||||
}
|
||||
|
||||
// Legacy mask support is intentionally limited to single-group systems where
|
||||
// logical processors 0-63 map to processor group 0. CpuSelection will replace
|
||||
// this path for group-aware selections in a later phase.
|
||||
if (this.cpuSetMapping.IsEmpty)
|
||||
{
|
||||
this.logger?.LogWarning("CPU Set mapping not available. Cannot apply CPU Sets to process {ProcessId}", this.pid);
|
||||
return CpuSetApplyResult.Failed(
|
||||
AffinityApplyErrorCodes.CpuSetsUnavailable,
|
||||
ProcessOperationUserMessages.CpuSetsUnavailable,
|
||||
$"CPU Set mapping is not available for process '{this.executableName}' (PID: {this.pid}).");
|
||||
}
|
||||
|
||||
var handleResult = this.EnsureSetHandleDetailed();
|
||||
if (!handleResult.Success)
|
||||
{
|
||||
return handleResult;
|
||||
}
|
||||
|
||||
if (clearMask)
|
||||
{
|
||||
return this.ApplyCpuSetIdsDetailed(null, 0, "clear CPU Set");
|
||||
}
|
||||
|
||||
var cpuSetIds = this.cpuSetMapping.ResolveLegacyAffinityMask(affinityMask, Environment.ProcessorCount);
|
||||
|
||||
if (cpuSetIds.Count == 0)
|
||||
{
|
||||
this.logger?.LogWarning(
|
||||
"No valid CPU Set IDs found for affinity mask 0x{AffinityMask:X} on process '{ExecutableName}'",
|
||||
affinityMask, this.executableName);
|
||||
return CpuSetApplyResult.Failed(
|
||||
AffinityApplyErrorCodes.InvalidTopology,
|
||||
ProcessOperationUserMessages.InvalidTopology,
|
||||
$"No valid CPU Set IDs found for affinity mask 0x{affinityMask:X} on process '{this.executableName}'.");
|
||||
}
|
||||
|
||||
var cpuSetIdsArray = cpuSetIds.ToArray();
|
||||
var result = this.ApplyCpuSetIdsDetailed(cpuSetIdsArray, (uint)cpuSetIdsArray.Length, "apply CPU Set");
|
||||
|
||||
if (result.Success)
|
||||
{
|
||||
this.logger?.LogInformation(
|
||||
"Applied CPU Set (affinity mask 0x{AffinityMask:X}) to '{ExecutableName}' (PID: {ProcessId})",
|
||||
affinityMask, this.executableName, this.pid);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
public bool ApplyCpuSelection(CpuSelection? selection, bool clearSelection = false) =>
|
||||
this.ApplyCpuSelectionDetailed(selection, clearSelection).Success;
|
||||
|
||||
public CpuSetApplyResult ApplyCpuSelectionDetailed(CpuSelection? selection, bool clearSelection = false)
|
||||
{
|
||||
if (this.disposed)
|
||||
{
|
||||
throw new ObjectDisposedException(nameof(ProcessCpuSetHandler));
|
||||
}
|
||||
|
||||
var handleResult = this.EnsureSetHandleDetailed();
|
||||
if (!handleResult.Success)
|
||||
{
|
||||
return handleResult;
|
||||
}
|
||||
|
||||
if (clearSelection)
|
||||
{
|
||||
return this.ApplyCpuSetIdsDetailed(null, 0, "clear CPU Set selection");
|
||||
}
|
||||
|
||||
ArgumentNullException.ThrowIfNull(selection);
|
||||
|
||||
var cpuSetIds = this.cpuSetMapping.ResolveCpuSetIds(selection);
|
||||
if (cpuSetIds.Count == 0)
|
||||
{
|
||||
this.logger?.LogWarning(
|
||||
"No valid CPU Set IDs resolved for CPU selection on process '{ExecutableName}' (PID: {ProcessId})",
|
||||
this.executableName,
|
||||
this.pid);
|
||||
return CpuSetApplyResult.Failed(
|
||||
AffinityApplyErrorCodes.InvalidTopology,
|
||||
ProcessOperationUserMessages.InvalidTopology,
|
||||
$"No valid CPU Set IDs resolved for CPU selection on process '{this.executableName}' (PID: {this.pid}).");
|
||||
}
|
||||
|
||||
var cpuSetIdsArray = cpuSetIds.ToArray();
|
||||
return this.ApplyCpuSetIdsDetailed(cpuSetIdsArray, (uint)cpuSetIdsArray.Length, "apply CPU Set selection");
|
||||
}
|
||||
|
||||
private bool EnsureSetHandle()
|
||||
{
|
||||
return this.EnsureSetHandleDetailed().Success;
|
||||
}
|
||||
|
||||
private CpuSetApplyResult EnsureSetHandleDetailed()
|
||||
{
|
||||
if (this.setLimitedInfoHandle == null)
|
||||
{
|
||||
this.setLimitedInfoHandle = this.nativeApi.OpenProcess(
|
||||
ProcessAccessFlags.PROCESS_SET_LIMITED_INFORMATION,
|
||||
false,
|
||||
this.pid);
|
||||
|
||||
if (this.setLimitedInfoHandle == null || this.setLimitedInfoHandle.IsInvalid)
|
||||
{
|
||||
int openError = this.nativeApi.GetLastWin32Error();
|
||||
string extraHelpString = (openError == 5)
|
||||
? $" {ProcessOperationUserMessages.AdminClarification}"
|
||||
: string.Empty;
|
||||
this.logger?.LogWarning(
|
||||
"Could not open process '{ExecutableName}' (PID: {ProcessId}) for setting affinity: {Error}{Help}",
|
||||
this.executableName, this.pid, new Win32Exception(openError).Message, extraHelpString);
|
||||
return this.CreateNativeFailureResult(
|
||||
"open process for CPU Set changes",
|
||||
openError);
|
||||
}
|
||||
}
|
||||
else if (this.setLimitedInfoHandle.IsInvalid)
|
||||
{
|
||||
// The handle was already made previously and failed, don't bother trying again
|
||||
return CpuSetApplyResult.Failed(
|
||||
AffinityApplyErrorCodes.CpuSetsUnavailable,
|
||||
ProcessOperationUserMessages.CpuSetsUnavailable,
|
||||
$"The cached CPU Set handle for '{this.executableName}' (PID: {this.pid}) is invalid.");
|
||||
}
|
||||
|
||||
return CpuSetApplyResult.Succeeded($"CPU Set handle is available for '{this.executableName}' (PID: {this.pid}).");
|
||||
}
|
||||
|
||||
private bool ApplyCpuSetIds(uint[]? cpuSetIds, uint cpuSetIdCount, string operationName)
|
||||
{
|
||||
return this.ApplyCpuSetIdsDetailed(cpuSetIds, cpuSetIdCount, operationName).Success;
|
||||
}
|
||||
|
||||
private CpuSetApplyResult ApplyCpuSetIdsDetailed(uint[]? cpuSetIds, uint cpuSetIdCount, string operationName)
|
||||
{
|
||||
bool success = this.nativeApi.SetProcessDefaultCpuSets(this.setLimitedInfoHandle!, cpuSetIds, cpuSetIdCount);
|
||||
if (success)
|
||||
{
|
||||
this.logger?.LogInformation(
|
||||
"Completed {OperationName} for '{ExecutableName}' (PID: {ProcessId})",
|
||||
operationName,
|
||||
this.executableName,
|
||||
this.pid);
|
||||
return CpuSetApplyResult.Succeeded(
|
||||
$"Completed {operationName} for '{this.executableName}' (PID: {this.pid}).");
|
||||
}
|
||||
|
||||
int error = this.nativeApi.GetLastWin32Error();
|
||||
string errorMessage = $"Could not {operationName} for '{this.executableName}' (PID: {this.pid}): {new Win32Exception(error).Message}";
|
||||
if (error == 5)
|
||||
{
|
||||
errorMessage += $" {ProcessOperationUserMessages.AdminClarification}";
|
||||
}
|
||||
|
||||
this.logger?.LogWarning(errorMessage);
|
||||
return this.CreateNativeFailureResult(operationName, error, errorMessage);
|
||||
}
|
||||
|
||||
private CpuSetApplyResult CreateNativeFailureResult(
|
||||
string operationName,
|
||||
int win32ErrorCode,
|
||||
string? technicalMessage = null)
|
||||
{
|
||||
var message = technicalMessage ??
|
||||
$"Could not {operationName} for '{this.executableName}' (PID: {this.pid}): {new Win32Exception(win32ErrorCode).Message}";
|
||||
var accessDenied = win32ErrorCode == 5;
|
||||
|
||||
return CpuSetApplyResult.Failed(
|
||||
accessDenied ? AffinityApplyErrorCodes.AccessDenied : AffinityApplyErrorCodes.NativeApplyFailed,
|
||||
accessDenied ? ProcessOperationUserMessages.AccessDenied : ProcessOperationUserMessages.CpuSetsUnavailable,
|
||||
message,
|
||||
win32ErrorCode,
|
||||
isAccessDenied: accessDenied);
|
||||
}
|
||||
|
||||
private static CpuSetMapping GetCpuSetMapping(IProcessCpuSetNativeApi nativeApi)
|
||||
{
|
||||
uint bufferLength = 0;
|
||||
|
||||
// First call to get buffer size
|
||||
if (!nativeApi.GetSystemCpuSetInformation(IntPtr.Zero, 0, ref bufferLength, new SafeProcessHandle(), 0))
|
||||
{
|
||||
int error = nativeApi.GetLastWin32Error();
|
||||
if (error != 0x7A) // ERROR_INSUFFICIENT_BUFFER
|
||||
{
|
||||
throw new Win32Exception(error, "Failed to query CPU Set information buffer size");
|
||||
}
|
||||
}
|
||||
|
||||
Dictionary<ProcessorRef, uint> cpuSets = new Dictionary<ProcessorRef, uint>();
|
||||
IntPtr buffer = Marshal.AllocHGlobal((int)bufferLength);
|
||||
|
||||
try
|
||||
{
|
||||
// Second call to get actual data
|
||||
if (!nativeApi.GetSystemCpuSetInformation(buffer, bufferLength, ref bufferLength, new SafeProcessHandle(), 0))
|
||||
{
|
||||
throw new Win32Exception(nativeApi.GetLastWin32Error(), "Failed to get CPU Set information");
|
||||
}
|
||||
|
||||
IntPtr current = buffer;
|
||||
IntPtr bufferEnd = buffer + (int)bufferLength;
|
||||
|
||||
while (current.ToInt64() < bufferEnd.ToInt64())
|
||||
{
|
||||
SYSTEM_CPU_SET_INFORMATION item = Marshal.PtrToStructure<SYSTEM_CPU_SET_INFORMATION>(current);
|
||||
|
||||
if (item.Type != CPU_SET_INFORMATION_TYPE.CpuSetInformation)
|
||||
{
|
||||
throw new InvalidCastException("Invalid CPU Set information type encountered");
|
||||
}
|
||||
|
||||
var processor = CpuSetMapping.CreateProcessorRef(item.Group, item.LogicalProcessorIndex);
|
||||
cpuSets[processor] = item.Id;
|
||||
|
||||
current = IntPtr.Add(current, (int)item.Size);
|
||||
}
|
||||
|
||||
return CpuSetMapping.Create(cpuSets);
|
||||
}
|
||||
finally
|
||||
{
|
||||
Marshal.FreeHGlobal(buffer);
|
||||
}
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
if (this.disposed)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
this.queryLimitedInfoHandle?.Dispose();
|
||||
this.setLimitedInfoHandle?.Dispose();
|
||||
this.cpuTimeMovingAverageBuffer.Clear();
|
||||
|
||||
this.disposed = true;
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
|
||||
private class CpuTimeTimestamp
|
||||
{
|
||||
public DateTime Timestamp { get; init; }
|
||||
|
||||
public TimeSpan TotalCpuTime { get; init; }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,33 +1,33 @@
|
||||
/*
|
||||
* ThreadPilot - Windows process memory priority P/Invoke declarations.
|
||||
*/
|
||||
namespace ThreadPilot.Platforms.Windows
|
||||
{
|
||||
using System.Runtime.InteropServices;
|
||||
using Microsoft.Win32.SafeHandles;
|
||||
|
||||
internal static partial class ProcessMemoryPriorityNativeMethods
|
||||
{
|
||||
[LibraryImport("kernel32.dll", SetLastError = true)]
|
||||
public static partial SafeProcessHandle OpenProcess(
|
||||
ProcessAccessFlags access,
|
||||
[MarshalAs(UnmanagedType.Bool)] bool inheritHandle,
|
||||
uint processId);
|
||||
|
||||
[LibraryImport("kernel32.dll", SetLastError = true)]
|
||||
[return: MarshalAs(UnmanagedType.Bool)]
|
||||
public static partial bool GetProcessInformation(
|
||||
SafeProcessHandle process,
|
||||
ProcessInformationClass processInformationClass,
|
||||
ref MemoryPriorityInformation processInformation,
|
||||
uint processInformationSize);
|
||||
|
||||
[LibraryImport("kernel32.dll", SetLastError = true)]
|
||||
[return: MarshalAs(UnmanagedType.Bool)]
|
||||
public static partial bool SetProcessInformation(
|
||||
SafeProcessHandle process,
|
||||
ProcessInformationClass processInformationClass,
|
||||
ref MemoryPriorityInformation processInformation,
|
||||
uint processInformationSize);
|
||||
}
|
||||
}
|
||||
/*
|
||||
* ThreadPilot - Windows process memory priority P/Invoke declarations.
|
||||
*/
|
||||
namespace ThreadPilot.Platforms.Windows
|
||||
{
|
||||
using System.Runtime.InteropServices;
|
||||
using Microsoft.Win32.SafeHandles;
|
||||
|
||||
internal static partial class ProcessMemoryPriorityNativeMethods
|
||||
{
|
||||
[LibraryImport("kernel32.dll", SetLastError = true)]
|
||||
public static partial SafeProcessHandle OpenProcess(
|
||||
ProcessAccessFlags access,
|
||||
[MarshalAs(UnmanagedType.Bool)] bool inheritHandle,
|
||||
uint processId);
|
||||
|
||||
[LibraryImport("kernel32.dll", SetLastError = true)]
|
||||
[return: MarshalAs(UnmanagedType.Bool)]
|
||||
public static partial bool GetProcessInformation(
|
||||
SafeProcessHandle process,
|
||||
ProcessInformationClass processInformationClass,
|
||||
ref MemoryPriorityInformation processInformation,
|
||||
uint processInformationSize);
|
||||
|
||||
[LibraryImport("kernel32.dll", SetLastError = true)]
|
||||
[return: MarshalAs(UnmanagedType.Bool)]
|
||||
public static partial bool SetProcessInformation(
|
||||
SafeProcessHandle process,
|
||||
ProcessInformationClass processInformationClass,
|
||||
ref MemoryPriorityInformation processInformation,
|
||||
uint processInformationSize);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,15 +1,12 @@
|
||||
namespace ThreadPilot.Services.Abstractions
|
||||
{
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
/// <summary>
|
||||
/// Retrieves GitHub release payloads for update checks.
|
||||
/// </summary>
|
||||
public interface IGitHubReleaseClient
|
||||
{
|
||||
Task<string> GetLatestReleaseJsonAsync(string owner, string repo, CancellationToken cancellationToken = default);
|
||||
|
||||
Task<string> GetReleasesJsonAsync(string owner, string repo, CancellationToken cancellationToken = default);
|
||||
}
|
||||
}
|
||||
namespace ThreadPilot.Services.Abstractions
|
||||
{
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
public interface IGitHubReleaseClient
|
||||
{
|
||||
Task<string> GetLatestReleaseJsonAsync(string owner, string repo, CancellationToken cancellationToken = default);
|
||||
|
||||
Task<string> GetReleasesJsonAsync(string owner, string repo, CancellationToken cancellationToken = default);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,32 +1,16 @@
|
||||
/*
|
||||
* ThreadPilot - process execution seam.
|
||||
*/
|
||||
namespace ThreadPilot.Services.Abstractions
|
||||
{
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
/// <summary>
|
||||
/// Runs external processes with a bounded timeout and captured output.
|
||||
/// </summary>
|
||||
public interface IProcessRunner
|
||||
{
|
||||
/// <summary>
|
||||
/// Executes a process and returns its exit code with captured output streams.
|
||||
/// </summary>
|
||||
/// <param name="fileName">Executable path.</param>
|
||||
/// <param name="arguments">Argument list passed verbatim to the process.</param>
|
||||
/// <param name="timeout">Maximum execution time before the process is treated as timed out.</param>
|
||||
/// <returns>The captured process result.</returns>
|
||||
Task<ProcessRunResult> RunAsync(string fileName, IReadOnlyList<string> arguments, TimeSpan timeout);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Immutable result returned by <see cref="IProcessRunner"/>.
|
||||
/// </summary>
|
||||
/// <param name="ExitCode">Process exit code, or a synthetic failure code when launch/timeout fails.</param>
|
||||
/// <param name="StandardOutput">Captured standard output.</param>
|
||||
/// <param name="StandardError">Captured standard error.</param>
|
||||
public readonly record struct ProcessRunResult(int ExitCode, string StandardOutput, string StandardError);
|
||||
}
|
||||
/*
|
||||
* ThreadPilot - process execution seam.
|
||||
*/
|
||||
namespace ThreadPilot.Services.Abstractions
|
||||
{
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
public interface IProcessRunner
|
||||
{
|
||||
Task<ProcessRunResult> RunAsync(string fileName, IReadOnlyList<string> arguments, TimeSpan timeout);
|
||||
}
|
||||
|
||||
public readonly record struct ProcessRunResult(int ExitCode, string StandardOutput, string StandardError);
|
||||
}
|
||||
|
||||
@@ -1,20 +1,17 @@
|
||||
namespace ThreadPilot.Services.Abstractions
|
||||
{
|
||||
using System.Threading.Tasks;
|
||||
|
||||
/// <summary>
|
||||
/// Provides a seam for reading and writing persisted settings.
|
||||
/// </summary>
|
||||
public interface ISettingsStorage
|
||||
{
|
||||
bool Exists(string path);
|
||||
|
||||
Task<string?> ReadAsync(string path);
|
||||
|
||||
Task WriteAsync(string path, string content);
|
||||
|
||||
void EnsureDirectoryForFile(string path);
|
||||
|
||||
void Copy(string sourcePath, string destinationPath, bool overwrite);
|
||||
}
|
||||
}
|
||||
namespace ThreadPilot.Services.Abstractions
|
||||
{
|
||||
using System.Threading.Tasks;
|
||||
|
||||
public interface ISettingsStorage
|
||||
{
|
||||
bool Exists(string path);
|
||||
|
||||
Task<string?> ReadAsync(string path);
|
||||
|
||||
Task WriteAsync(string path, string content);
|
||||
|
||||
void EnsureDirectoryForFile(string path);
|
||||
|
||||
void Copy(string sourcePath, string destinationPath, bool overwrite);
|
||||
}
|
||||
}
|
||||
|
||||
+244
-244
@@ -1,244 +1,244 @@
|
||||
namespace ThreadPilot.Services
|
||||
{
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
public sealed class ActivityAuditService : IActivityAuditService
|
||||
{
|
||||
private const int MaxEntries = 1000;
|
||||
private readonly ILogger<ActivityAuditService> logger;
|
||||
private readonly object syncRoot = new();
|
||||
private readonly List<ActivityAuditEntry> entries = new();
|
||||
|
||||
public event EventHandler<ActivityAuditEntry>? EntryAdded;
|
||||
|
||||
public ActivityAuditService(ILogger<ActivityAuditService> logger)
|
||||
{
|
||||
this.logger = logger ?? throw new ArgumentNullException(nameof(logger));
|
||||
}
|
||||
|
||||
public Task LogInfoAsync(string category, string message, string? details = null) =>
|
||||
this.AddEntryAsync(category, ActivityAuditSeverity.Info, message, details);
|
||||
|
||||
public Task LogSuccessAsync(string category, string message, string? details = null) =>
|
||||
this.AddEntryAsync(category, ActivityAuditSeverity.Success, message, details);
|
||||
|
||||
public Task LogWarningAsync(string category, string message, string? details = null) =>
|
||||
this.AddEntryAsync(category, ActivityAuditSeverity.Warning, message, details);
|
||||
|
||||
public Task LogErrorAsync(string category, string message, string? details = null) =>
|
||||
this.AddEntryAsync(category, ActivityAuditSeverity.Error, message, details);
|
||||
|
||||
public Task LogUserActionAsync(string action, string details, string? context = null)
|
||||
{
|
||||
var entry = ActivityAuditActionMapper.Map(action, details, context);
|
||||
return this.AddEntryAsync(entry.Category, entry.Severity, entry.Message, entry.Details);
|
||||
}
|
||||
|
||||
public Task<IReadOnlyList<ActivityAuditEntry>> GetEntriesAsync(DateTime? fromDate = null, DateTime? toDate = null)
|
||||
{
|
||||
lock (this.syncRoot)
|
||||
{
|
||||
IEnumerable<ActivityAuditEntry> snapshot = this.entries;
|
||||
if (fromDate.HasValue)
|
||||
{
|
||||
snapshot = snapshot.Where(entry => entry.Timestamp >= fromDate.Value);
|
||||
}
|
||||
|
||||
if (toDate.HasValue)
|
||||
{
|
||||
snapshot = snapshot.Where(entry => entry.Timestamp <= toDate.Value);
|
||||
}
|
||||
|
||||
return Task.FromResult<IReadOnlyList<ActivityAuditEntry>>(
|
||||
snapshot
|
||||
.OrderByDescending(entry => entry.Timestamp)
|
||||
.ToList());
|
||||
}
|
||||
}
|
||||
|
||||
public Task ClearDisplayAsync()
|
||||
{
|
||||
lock (this.syncRoot)
|
||||
{
|
||||
this.entries.Clear();
|
||||
}
|
||||
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
private Task AddEntryAsync(string category, ActivityAuditSeverity severity, string message, string? details)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(message))
|
||||
{
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
var entry = new ActivityAuditEntry
|
||||
{
|
||||
Timestamp = DateTime.Now,
|
||||
Category = string.IsNullOrWhiteSpace(category) ? ActivityAuditCategories.Diagnostics : category.Trim(),
|
||||
Severity = severity,
|
||||
Message = message.Trim(),
|
||||
Details = string.IsNullOrWhiteSpace(details) ? null : details.Trim(),
|
||||
};
|
||||
|
||||
lock (this.syncRoot)
|
||||
{
|
||||
this.entries.Add(entry);
|
||||
if (this.entries.Count > MaxEntries)
|
||||
{
|
||||
this.entries.RemoveRange(0, this.entries.Count - MaxEntries);
|
||||
}
|
||||
}
|
||||
|
||||
this.logger.Log(
|
||||
ToLogLevel(severity),
|
||||
"Activity audit: {Category} {Severity}: {Message}",
|
||||
entry.Category,
|
||||
entry.Severity,
|
||||
entry.Message);
|
||||
this.EntryAdded?.Invoke(this, entry);
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
private static LogLevel ToLogLevel(ActivityAuditSeverity severity) =>
|
||||
severity switch
|
||||
{
|
||||
ActivityAuditSeverity.Error => LogLevel.Error,
|
||||
ActivityAuditSeverity.Warning => LogLevel.Warning,
|
||||
_ => LogLevel.Information,
|
||||
};
|
||||
}
|
||||
|
||||
internal static class ActivityAuditCategories
|
||||
{
|
||||
public const string Process = "Process";
|
||||
public const string Affinity = "Affinity";
|
||||
public const string Priority = "Priority";
|
||||
public const string MemoryPriority = "Memory Priority";
|
||||
public const string Rules = "Rules";
|
||||
public const string PowerPlans = "Power Plans";
|
||||
public const string Settings = "Settings";
|
||||
public const string Tweaks = "Tweaks";
|
||||
public const string Optimization = "Optimization";
|
||||
public const string Diagnostics = "Diagnostics";
|
||||
public const string Safety = "Safety";
|
||||
}
|
||||
|
||||
internal static class ActivityAuditActionMapper
|
||||
{
|
||||
public static ActivityAuditEntry Map(string action, string details, string? context)
|
||||
{
|
||||
var category = ResolveCategory(action);
|
||||
var severity = ResolveSeverity(action, details);
|
||||
return new ActivityAuditEntry
|
||||
{
|
||||
Category = category,
|
||||
Severity = severity,
|
||||
Message = string.IsNullOrWhiteSpace(details) ? action : details,
|
||||
Details = context,
|
||||
};
|
||||
}
|
||||
|
||||
private static string ResolveCategory(string action)
|
||||
{
|
||||
if (action.StartsWith("ProcessAffinity", StringComparison.OrdinalIgnoreCase) ||
|
||||
action.StartsWith("CpuSets", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return ActivityAuditCategories.Affinity;
|
||||
}
|
||||
|
||||
if (action.StartsWith("ProcessPriority", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return ActivityAuditCategories.Priority;
|
||||
}
|
||||
|
||||
if (action.StartsWith("ProcessMemoryPriority", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return ActivityAuditCategories.MemoryPriority;
|
||||
}
|
||||
|
||||
if (action.StartsWith("PersistentRule", StringComparison.OrdinalIgnoreCase) ||
|
||||
action.Contains("Association", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return ActivityAuditCategories.Rules;
|
||||
}
|
||||
|
||||
if (action.StartsWith("PowerPlan", StringComparison.OrdinalIgnoreCase) ||
|
||||
action.StartsWith("PowerPlans", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return ActivityAuditCategories.PowerPlans;
|
||||
}
|
||||
|
||||
if (action.StartsWith("Theme", StringComparison.OrdinalIgnoreCase) ||
|
||||
action.StartsWith("Settings", StringComparison.OrdinalIgnoreCase) ||
|
||||
action.Contains("Configuration", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return ActivityAuditCategories.Settings;
|
||||
}
|
||||
|
||||
if (action.StartsWith("SystemTweak", StringComparison.OrdinalIgnoreCase) ||
|
||||
action.Contains("IdleServer", StringComparison.OrdinalIgnoreCase) ||
|
||||
action.Contains("RegistryPriority", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return ActivityAuditCategories.Tweaks;
|
||||
}
|
||||
|
||||
if (action.StartsWith("Optimization", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return ActivityAuditCategories.Optimization;
|
||||
}
|
||||
|
||||
if (action.Contains("Protected", StringComparison.OrdinalIgnoreCase) ||
|
||||
action.Contains("Elevation", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return ActivityAuditCategories.Safety;
|
||||
}
|
||||
|
||||
if (action.StartsWith("Process", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return ActivityAuditCategories.Process;
|
||||
}
|
||||
|
||||
return ActivityAuditCategories.Diagnostics;
|
||||
}
|
||||
|
||||
private static ActivityAuditSeverity ResolveSeverity(string action, string details)
|
||||
{
|
||||
if (ContainsAny(action, "Blocked", "Denied") || ContainsAny(details, "blocked", "denied", "anti-cheat", "protected"))
|
||||
{
|
||||
return ActivityAuditSeverity.Warning;
|
||||
}
|
||||
|
||||
if (ContainsAny(action, "Failed", "Failure", "Error") || ContainsAny(details, "failed", "error", "exited"))
|
||||
{
|
||||
return ActivityAuditSeverity.Error;
|
||||
}
|
||||
|
||||
if (ContainsAny(
|
||||
action,
|
||||
"Applied",
|
||||
"Changed",
|
||||
"Saved",
|
||||
"Updated",
|
||||
"Deleted",
|
||||
"Imported",
|
||||
"Added",
|
||||
"Cleared",
|
||||
"Refreshed",
|
||||
"Started",
|
||||
"Stopped",
|
||||
"Exported",
|
||||
"Opened",
|
||||
"Copied"))
|
||||
{
|
||||
return ActivityAuditSeverity.Success;
|
||||
}
|
||||
|
||||
return ActivityAuditSeverity.Info;
|
||||
}
|
||||
|
||||
private static bool ContainsAny(string value, params string[] terms) =>
|
||||
terms.Any(term => value.Contains(term, StringComparison.OrdinalIgnoreCase));
|
||||
}
|
||||
}
|
||||
namespace ThreadPilot.Services
|
||||
{
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
public sealed class ActivityAuditService : IActivityAuditService
|
||||
{
|
||||
private const int MaxEntries = 1000;
|
||||
private readonly ILogger<ActivityAuditService> logger;
|
||||
private readonly object syncRoot = new();
|
||||
private readonly List<ActivityAuditEntry> entries = new();
|
||||
|
||||
public event EventHandler<ActivityAuditEntry>? EntryAdded;
|
||||
|
||||
public ActivityAuditService(ILogger<ActivityAuditService> logger)
|
||||
{
|
||||
this.logger = logger ?? throw new ArgumentNullException(nameof(logger));
|
||||
}
|
||||
|
||||
public Task LogInfoAsync(string category, string message, string? details = null) =>
|
||||
this.AddEntryAsync(category, ActivityAuditSeverity.Info, message, details);
|
||||
|
||||
public Task LogSuccessAsync(string category, string message, string? details = null) =>
|
||||
this.AddEntryAsync(category, ActivityAuditSeverity.Success, message, details);
|
||||
|
||||
public Task LogWarningAsync(string category, string message, string? details = null) =>
|
||||
this.AddEntryAsync(category, ActivityAuditSeverity.Warning, message, details);
|
||||
|
||||
public Task LogErrorAsync(string category, string message, string? details = null) =>
|
||||
this.AddEntryAsync(category, ActivityAuditSeverity.Error, message, details);
|
||||
|
||||
public Task LogUserActionAsync(string action, string details, string? context = null)
|
||||
{
|
||||
var entry = ActivityAuditActionMapper.Map(action, details, context);
|
||||
return this.AddEntryAsync(entry.Category, entry.Severity, entry.Message, entry.Details);
|
||||
}
|
||||
|
||||
public Task<IReadOnlyList<ActivityAuditEntry>> GetEntriesAsync(DateTime? fromDate = null, DateTime? toDate = null)
|
||||
{
|
||||
lock (this.syncRoot)
|
||||
{
|
||||
IEnumerable<ActivityAuditEntry> snapshot = this.entries;
|
||||
if (fromDate.HasValue)
|
||||
{
|
||||
snapshot = snapshot.Where(entry => entry.Timestamp >= fromDate.Value);
|
||||
}
|
||||
|
||||
if (toDate.HasValue)
|
||||
{
|
||||
snapshot = snapshot.Where(entry => entry.Timestamp <= toDate.Value);
|
||||
}
|
||||
|
||||
return Task.FromResult<IReadOnlyList<ActivityAuditEntry>>(
|
||||
snapshot
|
||||
.OrderByDescending(entry => entry.Timestamp)
|
||||
.ToList());
|
||||
}
|
||||
}
|
||||
|
||||
public Task ClearDisplayAsync()
|
||||
{
|
||||
lock (this.syncRoot)
|
||||
{
|
||||
this.entries.Clear();
|
||||
}
|
||||
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
private Task AddEntryAsync(string category, ActivityAuditSeverity severity, string message, string? details)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(message))
|
||||
{
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
var entry = new ActivityAuditEntry
|
||||
{
|
||||
Timestamp = DateTime.Now,
|
||||
Category = string.IsNullOrWhiteSpace(category) ? ActivityAuditCategories.Diagnostics : category.Trim(),
|
||||
Severity = severity,
|
||||
Message = message.Trim(),
|
||||
Details = string.IsNullOrWhiteSpace(details) ? null : details.Trim(),
|
||||
};
|
||||
|
||||
lock (this.syncRoot)
|
||||
{
|
||||
this.entries.Add(entry);
|
||||
if (this.entries.Count > MaxEntries)
|
||||
{
|
||||
this.entries.RemoveRange(0, this.entries.Count - MaxEntries);
|
||||
}
|
||||
}
|
||||
|
||||
this.logger.Log(
|
||||
ToLogLevel(severity),
|
||||
"Activity audit: {Category} {Severity}: {Message}",
|
||||
entry.Category,
|
||||
entry.Severity,
|
||||
entry.Message);
|
||||
this.EntryAdded?.Invoke(this, entry);
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
private static LogLevel ToLogLevel(ActivityAuditSeverity severity) =>
|
||||
severity switch
|
||||
{
|
||||
ActivityAuditSeverity.Error => LogLevel.Error,
|
||||
ActivityAuditSeverity.Warning => LogLevel.Warning,
|
||||
_ => LogLevel.Information,
|
||||
};
|
||||
}
|
||||
|
||||
internal static class ActivityAuditCategories
|
||||
{
|
||||
public const string Process = "Process";
|
||||
public const string Affinity = "Affinity";
|
||||
public const string Priority = "Priority";
|
||||
public const string MemoryPriority = "Memory Priority";
|
||||
public const string Rules = "Rules";
|
||||
public const string PowerPlans = "Power Plans";
|
||||
public const string Settings = "Settings";
|
||||
public const string Tweaks = "Tweaks";
|
||||
public const string Optimization = "Optimization";
|
||||
public const string Diagnostics = "Diagnostics";
|
||||
public const string Safety = "Safety";
|
||||
}
|
||||
|
||||
internal static class ActivityAuditActionMapper
|
||||
{
|
||||
public static ActivityAuditEntry Map(string action, string details, string? context)
|
||||
{
|
||||
var category = ResolveCategory(action);
|
||||
var severity = ResolveSeverity(action, details);
|
||||
return new ActivityAuditEntry
|
||||
{
|
||||
Category = category,
|
||||
Severity = severity,
|
||||
Message = string.IsNullOrWhiteSpace(details) ? action : details,
|
||||
Details = context,
|
||||
};
|
||||
}
|
||||
|
||||
private static string ResolveCategory(string action)
|
||||
{
|
||||
if (action.StartsWith("ProcessAffinity", StringComparison.OrdinalIgnoreCase) ||
|
||||
action.StartsWith("CpuSets", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return ActivityAuditCategories.Affinity;
|
||||
}
|
||||
|
||||
if (action.StartsWith("ProcessPriority", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return ActivityAuditCategories.Priority;
|
||||
}
|
||||
|
||||
if (action.StartsWith("ProcessMemoryPriority", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return ActivityAuditCategories.MemoryPriority;
|
||||
}
|
||||
|
||||
if (action.StartsWith("PersistentRule", StringComparison.OrdinalIgnoreCase) ||
|
||||
action.Contains("Association", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return ActivityAuditCategories.Rules;
|
||||
}
|
||||
|
||||
if (action.StartsWith("PowerPlan", StringComparison.OrdinalIgnoreCase) ||
|
||||
action.StartsWith("PowerPlans", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return ActivityAuditCategories.PowerPlans;
|
||||
}
|
||||
|
||||
if (action.StartsWith("Theme", StringComparison.OrdinalIgnoreCase) ||
|
||||
action.StartsWith("Settings", StringComparison.OrdinalIgnoreCase) ||
|
||||
action.Contains("Configuration", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return ActivityAuditCategories.Settings;
|
||||
}
|
||||
|
||||
if (action.StartsWith("SystemTweak", StringComparison.OrdinalIgnoreCase) ||
|
||||
action.Contains("IdleServer", StringComparison.OrdinalIgnoreCase) ||
|
||||
action.Contains("RegistryPriority", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return ActivityAuditCategories.Tweaks;
|
||||
}
|
||||
|
||||
if (action.StartsWith("Optimization", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return ActivityAuditCategories.Optimization;
|
||||
}
|
||||
|
||||
if (action.Contains("Protected", StringComparison.OrdinalIgnoreCase) ||
|
||||
action.Contains("Elevation", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return ActivityAuditCategories.Safety;
|
||||
}
|
||||
|
||||
if (action.StartsWith("Process", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return ActivityAuditCategories.Process;
|
||||
}
|
||||
|
||||
return ActivityAuditCategories.Diagnostics;
|
||||
}
|
||||
|
||||
private static ActivityAuditSeverity ResolveSeverity(string action, string details)
|
||||
{
|
||||
if (ContainsAny(action, "Blocked", "Denied") || ContainsAny(details, "blocked", "denied", "anti-cheat", "protected"))
|
||||
{
|
||||
return ActivityAuditSeverity.Warning;
|
||||
}
|
||||
|
||||
if (ContainsAny(action, "Failed", "Failure", "Error") || ContainsAny(details, "failed", "error", "exited"))
|
||||
{
|
||||
return ActivityAuditSeverity.Error;
|
||||
}
|
||||
|
||||
if (ContainsAny(
|
||||
action,
|
||||
"Applied",
|
||||
"Changed",
|
||||
"Saved",
|
||||
"Updated",
|
||||
"Deleted",
|
||||
"Imported",
|
||||
"Added",
|
||||
"Cleared",
|
||||
"Refreshed",
|
||||
"Started",
|
||||
"Stopped",
|
||||
"Exported",
|
||||
"Opened",
|
||||
"Copied"))
|
||||
{
|
||||
return ActivityAuditSeverity.Success;
|
||||
}
|
||||
|
||||
return ActivityAuditSeverity.Info;
|
||||
}
|
||||
|
||||
private static bool ContainsAny(string value, params string[] terms) =>
|
||||
terms.Any(term => value.Contains(term, StringComparison.OrdinalIgnoreCase));
|
||||
}
|
||||
}
|
||||
|
||||
+636
-652
File diff suppressed because it is too large
Load Diff
@@ -1,26 +1,7 @@
|
||||
/*
|
||||
* ThreadPilot - Advanced Windows Process and Power Plan Manager
|
||||
* Copyright (C) 2025 Prime Build
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published by
|
||||
* the Free Software Foundation, version 3 only.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
namespace ThreadPilot.Services
|
||||
{
|
||||
/// <summary>
|
||||
/// Compile-time navigation switches for optional surfaces.
|
||||
/// </summary>
|
||||
public static class AppNavigationOptions
|
||||
{
|
||||
public static bool ShowAdvancedDiagnostics => false;
|
||||
}
|
||||
}
|
||||
namespace ThreadPilot.Services
|
||||
{
|
||||
public static class AppNavigationOptions
|
||||
{
|
||||
public static bool ShowAdvancedDiagnostics => false;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,94 +1,69 @@
|
||||
/*
|
||||
* ThreadPilot - Advanced Windows Process and Power Plan Manager
|
||||
* Copyright (C) 2025 Prime Build
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published by
|
||||
* the Free Software Foundation, version 3 only.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
namespace ThreadPilot.Services
|
||||
{
|
||||
/// <summary>
|
||||
/// Represents the current UI activity state used to decide refresh work.
|
||||
/// </summary>
|
||||
public enum AppActivityState
|
||||
{
|
||||
ForegroundProcessView,
|
||||
ForegroundDiagnosticsView,
|
||||
ForegroundOtherTab,
|
||||
Minimized,
|
||||
TrayHidden,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Describes refresh and monitoring work allowed for a UI activity state.
|
||||
/// </summary>
|
||||
public sealed record AppRefreshDecision(
|
||||
bool ProcessUiRefreshEnabled,
|
||||
bool ImmediateProcessRefresh,
|
||||
bool VirtualizedPreloadEnabled,
|
||||
bool PerformanceUiMonitoringEnabled,
|
||||
bool PowerPlanUiRefreshEnabled,
|
||||
bool BackgroundAutomationEnabled);
|
||||
|
||||
/// <summary>
|
||||
/// Central policy for foreground/background refresh decisions.
|
||||
/// </summary>
|
||||
public static class AppRefreshPolicy
|
||||
{
|
||||
public static bool ShouldApplyTransition(AppActivityState? previousState, AppActivityState nextState)
|
||||
{
|
||||
return previousState != nextState;
|
||||
}
|
||||
|
||||
public static AppRefreshDecision Evaluate(AppActivityState state)
|
||||
{
|
||||
return state switch
|
||||
{
|
||||
AppActivityState.ForegroundProcessView => new AppRefreshDecision(
|
||||
ProcessUiRefreshEnabled: true,
|
||||
ImmediateProcessRefresh: true,
|
||||
VirtualizedPreloadEnabled: true,
|
||||
PerformanceUiMonitoringEnabled: false,
|
||||
PowerPlanUiRefreshEnabled: true,
|
||||
BackgroundAutomationEnabled: true),
|
||||
AppActivityState.ForegroundDiagnosticsView => new AppRefreshDecision(
|
||||
ProcessUiRefreshEnabled: false,
|
||||
ImmediateProcessRefresh: false,
|
||||
VirtualizedPreloadEnabled: false,
|
||||
PerformanceUiMonitoringEnabled: true,
|
||||
PowerPlanUiRefreshEnabled: true,
|
||||
BackgroundAutomationEnabled: true),
|
||||
AppActivityState.ForegroundOtherTab => new AppRefreshDecision(
|
||||
ProcessUiRefreshEnabled: false,
|
||||
ImmediateProcessRefresh: false,
|
||||
VirtualizedPreloadEnabled: false,
|
||||
PerformanceUiMonitoringEnabled: false,
|
||||
PowerPlanUiRefreshEnabled: true,
|
||||
BackgroundAutomationEnabled: true),
|
||||
AppActivityState.Minimized or AppActivityState.TrayHidden => new AppRefreshDecision(
|
||||
ProcessUiRefreshEnabled: false,
|
||||
ImmediateProcessRefresh: false,
|
||||
VirtualizedPreloadEnabled: false,
|
||||
PerformanceUiMonitoringEnabled: false,
|
||||
PowerPlanUiRefreshEnabled: false,
|
||||
BackgroundAutomationEnabled: true),
|
||||
_ => new AppRefreshDecision(
|
||||
ProcessUiRefreshEnabled: false,
|
||||
ImmediateProcessRefresh: false,
|
||||
VirtualizedPreloadEnabled: false,
|
||||
PerformanceUiMonitoringEnabled: false,
|
||||
PowerPlanUiRefreshEnabled: false,
|
||||
BackgroundAutomationEnabled: true),
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
namespace ThreadPilot.Services
|
||||
{
|
||||
public enum AppActivityState
|
||||
{
|
||||
ForegroundProcessView,
|
||||
ForegroundDiagnosticsView,
|
||||
ForegroundOtherTab,
|
||||
Minimized,
|
||||
TrayHidden,
|
||||
}
|
||||
|
||||
public sealed record AppRefreshDecision(
|
||||
bool ProcessUiRefreshEnabled,
|
||||
bool ImmediateProcessRefresh,
|
||||
bool VirtualizedPreloadEnabled,
|
||||
bool PerformanceUiMonitoringEnabled,
|
||||
bool PowerPlanUiRefreshEnabled,
|
||||
bool BackgroundAutomationEnabled);
|
||||
|
||||
public static class AppRefreshPolicy
|
||||
{
|
||||
public static bool ShouldApplyTransition(AppActivityState? previousState, AppActivityState nextState)
|
||||
{
|
||||
return previousState != nextState;
|
||||
}
|
||||
|
||||
public static AppRefreshDecision Evaluate(AppActivityState state)
|
||||
{
|
||||
return state switch
|
||||
{
|
||||
AppActivityState.ForegroundProcessView => new AppRefreshDecision(
|
||||
ProcessUiRefreshEnabled: true,
|
||||
ImmediateProcessRefresh: true,
|
||||
VirtualizedPreloadEnabled: true,
|
||||
PerformanceUiMonitoringEnabled: false,
|
||||
PowerPlanUiRefreshEnabled: true,
|
||||
BackgroundAutomationEnabled: true),
|
||||
AppActivityState.ForegroundDiagnosticsView => new AppRefreshDecision(
|
||||
ProcessUiRefreshEnabled: false,
|
||||
ImmediateProcessRefresh: false,
|
||||
VirtualizedPreloadEnabled: false,
|
||||
PerformanceUiMonitoringEnabled: true,
|
||||
PowerPlanUiRefreshEnabled: true,
|
||||
BackgroundAutomationEnabled: true),
|
||||
AppActivityState.ForegroundOtherTab => new AppRefreshDecision(
|
||||
ProcessUiRefreshEnabled: false,
|
||||
ImmediateProcessRefresh: false,
|
||||
VirtualizedPreloadEnabled: false,
|
||||
PerformanceUiMonitoringEnabled: false,
|
||||
PowerPlanUiRefreshEnabled: true,
|
||||
BackgroundAutomationEnabled: true),
|
||||
AppActivityState.Minimized or AppActivityState.TrayHidden => new AppRefreshDecision(
|
||||
ProcessUiRefreshEnabled: false,
|
||||
ImmediateProcessRefresh: false,
|
||||
VirtualizedPreloadEnabled: false,
|
||||
PerformanceUiMonitoringEnabled: false,
|
||||
PowerPlanUiRefreshEnabled: false,
|
||||
BackgroundAutomationEnabled: true),
|
||||
_ => new AppRefreshDecision(
|
||||
ProcessUiRefreshEnabled: false,
|
||||
ImmediateProcessRefresh: false,
|
||||
VirtualizedPreloadEnabled: false,
|
||||
PerformanceUiMonitoringEnabled: false,
|
||||
PowerPlanUiRefreshEnabled: false,
|
||||
BackgroundAutomationEnabled: true),
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,19 +1,3 @@
|
||||
/*
|
||||
* ThreadPilot - Advanced Windows Process and Power Plan Manager
|
||||
* Copyright (C) 2025 Prime Build
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published by
|
||||
* the Free Software Foundation, version 3 only.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
namespace ThreadPilot.Services
|
||||
{
|
||||
using System;
|
||||
@@ -25,9 +9,6 @@ namespace ThreadPilot.Services
|
||||
using ThreadPilot.Models;
|
||||
using ThreadPilot.Services.Abstractions;
|
||||
|
||||
/// <summary>
|
||||
/// Service for managing application settings with JSON persistence.
|
||||
/// </summary>
|
||||
public class ApplicationSettingsService : IApplicationSettingsService
|
||||
{
|
||||
private readonly ILogger<ApplicationSettingsService> logger;
|
||||
|
||||
@@ -1,36 +1,36 @@
|
||||
/*
|
||||
* ThreadPilot - application version provider for update checks.
|
||||
*/
|
||||
namespace ThreadPilot.Services
|
||||
{
|
||||
using System;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
|
||||
public sealed class ApplicationVersionProvider : IApplicationVersionProvider
|
||||
{
|
||||
public SemanticVersion CurrentVersion
|
||||
{
|
||||
get
|
||||
{
|
||||
var rawVersion = GetRawVersion();
|
||||
return SemanticVersion.TryParse(rawVersion, out var version)
|
||||
? version
|
||||
: new SemanticVersion(0, 0, 0);
|
||||
}
|
||||
}
|
||||
|
||||
public string DisplayVersion => $"v{this.CurrentVersion}";
|
||||
|
||||
private static string GetRawVersion()
|
||||
{
|
||||
return typeof(App).Assembly
|
||||
.GetCustomAttributes(typeof(AssemblyInformationalVersionAttribute), false)
|
||||
.OfType<AssemblyInformationalVersionAttribute>()
|
||||
.FirstOrDefault()?
|
||||
.InformationalVersion
|
||||
?? typeof(App).Assembly.GetName().Version?.ToString()
|
||||
?? "0.0.0";
|
||||
}
|
||||
}
|
||||
}
|
||||
/*
|
||||
* ThreadPilot - application version provider for update checks.
|
||||
*/
|
||||
namespace ThreadPilot.Services
|
||||
{
|
||||
using System;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
|
||||
public sealed class ApplicationVersionProvider : IApplicationVersionProvider
|
||||
{
|
||||
public SemanticVersion CurrentVersion
|
||||
{
|
||||
get
|
||||
{
|
||||
var rawVersion = GetRawVersion();
|
||||
return SemanticVersion.TryParse(rawVersion, out var version)
|
||||
? version
|
||||
: new SemanticVersion(0, 0, 0);
|
||||
}
|
||||
}
|
||||
|
||||
public string DisplayVersion => $"v{this.CurrentVersion}";
|
||||
|
||||
private static string GetRawVersion()
|
||||
{
|
||||
return typeof(App).Assembly
|
||||
.GetCustomAttributes(typeof(AssemblyInformationalVersionAttribute), false)
|
||||
.OfType<AssemblyInformationalVersionAttribute>()
|
||||
.FirstOrDefault()?
|
||||
.InformationalVersion
|
||||
?? typeof(App).Assembly.GetName().Version?.ToString()
|
||||
?? "0.0.0";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,72 +1,56 @@
|
||||
/*
|
||||
* ThreadPilot - Advanced Windows Process and Power Plan Manager
|
||||
* Copyright (C) 2025 Prime Build
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published by
|
||||
* the Free Software Foundation, version 3 only.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
namespace ThreadPilot.Services
|
||||
{
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
internal static class AtomicFileWriter
|
||||
{
|
||||
public static async Task WriteAllTextAsync(string filePath, string content, Encoding? encoding = null)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(filePath))
|
||||
{
|
||||
throw new ArgumentException("File path cannot be null or empty.", nameof(filePath));
|
||||
}
|
||||
|
||||
var targetDirectory = Path.GetDirectoryName(filePath);
|
||||
if (string.IsNullOrEmpty(targetDirectory))
|
||||
{
|
||||
throw new InvalidOperationException($"Cannot determine target directory for path '{filePath}'.");
|
||||
}
|
||||
|
||||
Directory.CreateDirectory(targetDirectory);
|
||||
|
||||
var tempFilePath = Path.Combine(targetDirectory, $".{Path.GetFileName(filePath)}.{Guid.NewGuid():N}.tmp");
|
||||
var backupFilePath = filePath + ".bak";
|
||||
|
||||
try
|
||||
{
|
||||
encoding ??= new UTF8Encoding(encoderShouldEmitUTF8Identifier: false);
|
||||
await File.WriteAllTextAsync(tempFilePath, content, encoding);
|
||||
|
||||
if (File.Exists(filePath))
|
||||
{
|
||||
File.Replace(tempFilePath, filePath, backupFilePath, ignoreMetadataErrors: true);
|
||||
|
||||
if (File.Exists(backupFilePath))
|
||||
{
|
||||
File.Delete(backupFilePath);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
File.Move(tempFilePath, filePath);
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (File.Exists(tempFilePath))
|
||||
{
|
||||
File.Delete(tempFilePath);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
namespace ThreadPilot.Services
|
||||
{
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
internal static class AtomicFileWriter
|
||||
{
|
||||
public static async Task WriteAllTextAsync(string filePath, string content, Encoding? encoding = null)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(filePath))
|
||||
{
|
||||
throw new ArgumentException("File path cannot be null or empty.", nameof(filePath));
|
||||
}
|
||||
|
||||
var targetDirectory = Path.GetDirectoryName(filePath);
|
||||
if (string.IsNullOrEmpty(targetDirectory))
|
||||
{
|
||||
throw new InvalidOperationException($"Cannot determine target directory for path '{filePath}'.");
|
||||
}
|
||||
|
||||
Directory.CreateDirectory(targetDirectory);
|
||||
|
||||
var tempFilePath = Path.Combine(targetDirectory, $".{Path.GetFileName(filePath)}.{Guid.NewGuid():N}.tmp");
|
||||
var backupFilePath = filePath + ".bak";
|
||||
|
||||
try
|
||||
{
|
||||
encoding ??= new UTF8Encoding(encoderShouldEmitUTF8Identifier: false);
|
||||
await File.WriteAllTextAsync(tempFilePath, content, encoding);
|
||||
|
||||
if (File.Exists(filePath))
|
||||
{
|
||||
File.Replace(tempFilePath, filePath, backupFilePath, ignoreMetadataErrors: true);
|
||||
|
||||
if (File.Exists(backupFilePath))
|
||||
{
|
||||
File.Delete(backupFilePath);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
File.Move(tempFilePath, filePath);
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (File.Exists(tempFilePath))
|
||||
{
|
||||
File.Delete(tempFilePath);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,46 +1,46 @@
|
||||
/*
|
||||
* ThreadPilot - best-effort Authenticode signature detection.
|
||||
*/
|
||||
namespace ThreadPilot.Services
|
||||
{
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Security.Cryptography;
|
||||
using System.Security.Cryptography.X509Certificates;
|
||||
|
||||
public sealed class AuthenticodeSignatureVerifier : IUpdateSignatureVerifier
|
||||
{
|
||||
public UpdateSignatureStatus Verify(string installerPath)
|
||||
{
|
||||
if (!File.Exists(installerPath))
|
||||
{
|
||||
return UpdateSignatureStatus.Invalid;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
using var certificate = new X509Certificate2(X509Certificate.CreateFromSignedFile(installerPath));
|
||||
using var chain = new X509Chain
|
||||
{
|
||||
ChainPolicy =
|
||||
{
|
||||
RevocationMode = X509RevocationMode.Online,
|
||||
RevocationFlag = X509RevocationFlag.ExcludeRoot,
|
||||
},
|
||||
};
|
||||
|
||||
return chain.Build(certificate)
|
||||
? UpdateSignatureStatus.Valid
|
||||
: UpdateSignatureStatus.Unknown;
|
||||
}
|
||||
catch (CryptographicException)
|
||||
{
|
||||
return UpdateSignatureStatus.Unknown;
|
||||
}
|
||||
catch (PlatformNotSupportedException)
|
||||
{
|
||||
return UpdateSignatureStatus.Unknown;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
/*
|
||||
* ThreadPilot - best-effort Authenticode signature detection.
|
||||
*/
|
||||
namespace ThreadPilot.Services
|
||||
{
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Security.Cryptography;
|
||||
using System.Security.Cryptography.X509Certificates;
|
||||
|
||||
public sealed class AuthenticodeSignatureVerifier : IUpdateSignatureVerifier
|
||||
{
|
||||
public UpdateSignatureStatus Verify(string installerPath)
|
||||
{
|
||||
if (!File.Exists(installerPath))
|
||||
{
|
||||
return UpdateSignatureStatus.Invalid;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
using var certificate = new X509Certificate2(X509Certificate.CreateFromSignedFile(installerPath));
|
||||
using var chain = new X509Chain
|
||||
{
|
||||
ChainPolicy =
|
||||
{
|
||||
RevocationMode = X509RevocationMode.Online,
|
||||
RevocationFlag = X509RevocationFlag.ExcludeRoot,
|
||||
},
|
||||
};
|
||||
|
||||
return chain.Build(certificate)
|
||||
? UpdateSignatureStatus.Valid
|
||||
: UpdateSignatureStatus.Unknown;
|
||||
}
|
||||
catch (CryptographicException)
|
||||
{
|
||||
return UpdateSignatureStatus.Unknown;
|
||||
}
|
||||
catch (PlatformNotSupportedException)
|
||||
{
|
||||
return UpdateSignatureStatus.Unknown;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+315
-334
@@ -1,334 +1,315 @@
|
||||
/*
|
||||
* ThreadPilot - Advanced Windows Process and Power Plan Manager
|
||||
* Copyright (C) 2025 Prime Build
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published by
|
||||
* the Free Software Foundation, version 3 only.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
namespace ThreadPilot.Services
|
||||
{
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Win32;
|
||||
|
||||
/// <summary>
|
||||
/// Service for managing Windows autostart functionality using registry.
|
||||
/// </summary>
|
||||
public partial class AutostartService : IAutostartService
|
||||
{
|
||||
private const string REGISTRYKEYPATH = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Run";
|
||||
private const string APPLICATIONNAME = "ThreadPilot";
|
||||
|
||||
private readonly ILogger<AutostartService> logger;
|
||||
private readonly IElevationService elevationService;
|
||||
private readonly IElevatedTaskService elevatedTaskService;
|
||||
private bool isAutostartEnabled;
|
||||
private string? autostartPath;
|
||||
|
||||
public event EventHandler<AutostartStatusChangedEventArgs>? AutostartStatusChanged;
|
||||
|
||||
public bool IsAutostartEnabled => this.isAutostartEnabled;
|
||||
|
||||
public string? AutostartPath => this.autostartPath;
|
||||
|
||||
public AutostartService(ILogger<AutostartService> logger, IElevationService elevationService, IElevatedTaskService elevatedTaskService)
|
||||
{
|
||||
this.logger = logger ?? throw new ArgumentNullException(nameof(logger));
|
||||
this.elevationService = elevationService ?? throw new ArgumentNullException(nameof(elevationService));
|
||||
this.elevatedTaskService = elevatedTaskService ?? throw new ArgumentNullException(nameof(elevatedTaskService));
|
||||
|
||||
// Initialize current status without surfacing startup exceptions.
|
||||
TaskSafety.FireAndForget(this.CheckAutostartStatusAsync(), ex =>
|
||||
{
|
||||
LogAutostartInitializationFailed(this.logger, ex);
|
||||
});
|
||||
}
|
||||
|
||||
public async Task<bool> EnableAutostartAsync(bool startMinimized = true)
|
||||
{
|
||||
try
|
||||
{
|
||||
var executablePath = this.GetExecutablePath();
|
||||
if (string.IsNullOrEmpty(executablePath))
|
||||
{
|
||||
LogAutostartExecutablePathMissing(this.logger);
|
||||
return false;
|
||||
}
|
||||
|
||||
var arguments = this.GetAutostartArguments(startMinimized);
|
||||
var fullCommand = $"\"{executablePath}\" {arguments}";
|
||||
|
||||
// Clean up legacy registry-based startup to keep a single elevated startup mechanism.
|
||||
this.TryRemoveLegacyRegistryAutostart();
|
||||
|
||||
if (!this.elevationService.IsRunningAsAdministrator())
|
||||
{
|
||||
LogAutostartRequiresElevation(this.logger);
|
||||
|
||||
var elevationRequested = await this.elevationService.RequestElevationIfNeeded();
|
||||
if (!elevationRequested)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
LogAutostartDeferredToElevatedInstance(this.logger);
|
||||
return false;
|
||||
}
|
||||
|
||||
var scheduledTaskCreated = await this.elevatedTaskService.EnsureAutostartTaskAsync(executablePath, arguments);
|
||||
if (!scheduledTaskCreated)
|
||||
{
|
||||
LogAutostartTaskRegistrationFailed(this.logger);
|
||||
return false;
|
||||
}
|
||||
|
||||
this.isAutostartEnabled = true;
|
||||
this.autostartPath = fullCommand;
|
||||
|
||||
LogAutostartEnabled(this.logger, fullCommand);
|
||||
|
||||
this.AutostartStatusChanged?.Invoke(this, new AutostartStatusChangedEventArgs(
|
||||
true, startMinimized, fullCommand));
|
||||
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
LogEnableAutostartFailed(this.logger, ex);
|
||||
|
||||
this.AutostartStatusChanged?.Invoke(this, new AutostartStatusChangedEventArgs(
|
||||
false, startMinimized, null, ex));
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<bool> DisableAutostartAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
if (!this.elevationService.IsRunningAsAdministrator())
|
||||
{
|
||||
LogAutostartDisableRequiresElevation(this.logger);
|
||||
|
||||
var elevationRequested = await this.elevationService.RequestElevationIfNeeded();
|
||||
if (!elevationRequested)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
LogAutostartDisableDeferredToElevatedInstance(this.logger);
|
||||
return false;
|
||||
}
|
||||
|
||||
this.TryRemoveLegacyRegistryAutostart();
|
||||
|
||||
var scheduledTaskRemoved = await this.elevatedTaskService.RemoveAutostartTaskAsync();
|
||||
if (!scheduledTaskRemoved)
|
||||
{
|
||||
LogAutostartTaskRemovalFailed(this.logger);
|
||||
return false;
|
||||
}
|
||||
|
||||
LogAutostartDisabled(this.logger);
|
||||
|
||||
this.isAutostartEnabled = false;
|
||||
this.autostartPath = null;
|
||||
|
||||
this.AutostartStatusChanged?.Invoke(this, new AutostartStatusChangedEventArgs(false));
|
||||
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
LogDisableAutostartFailed(this.logger, ex);
|
||||
|
||||
this.AutostartStatusChanged?.Invoke(this, new AutostartStatusChangedEventArgs(
|
||||
false, false, null, ex));
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<bool> CheckAutostartStatusAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
var taskRegistered = await this.elevatedTaskService.IsAutostartTaskRegisteredAsync();
|
||||
var legacyRegistryValue = this.TryReadLegacyRegistryAutostart();
|
||||
|
||||
this.isAutostartEnabled = taskRegistered || !string.IsNullOrWhiteSpace(legacyRegistryValue);
|
||||
this.autostartPath = taskRegistered
|
||||
? $"task://{this.elevatedTaskService.AutostartTaskName}"
|
||||
: legacyRegistryValue;
|
||||
|
||||
LogAutostartStatusChecked(this.logger, this.isAutostartEnabled, this.autostartPath);
|
||||
|
||||
return this.isAutostartEnabled;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
LogCheckAutostartStatusFailed(this.logger, ex);
|
||||
this.isAutostartEnabled = false;
|
||||
this.autostartPath = null;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<bool> UpdateAutostartAsync(bool startMinimized = true)
|
||||
{
|
||||
if (!this.isAutostartEnabled)
|
||||
{
|
||||
return await this.EnableAutostartAsync(startMinimized);
|
||||
}
|
||||
|
||||
// Re-enable with new parameters
|
||||
await this.DisableAutostartAsync();
|
||||
return await this.EnableAutostartAsync(startMinimized);
|
||||
}
|
||||
|
||||
public string GetAutostartArguments(bool startMinimized = true)
|
||||
{
|
||||
var args = new System.Collections.Generic.List<string>();
|
||||
|
||||
if (startMinimized)
|
||||
{
|
||||
args.Add("--start-minimized");
|
||||
}
|
||||
|
||||
// Add any other startup arguments as needed
|
||||
args.Add("--autostart");
|
||||
|
||||
return string.Join(" ", args);
|
||||
}
|
||||
|
||||
private string? GetExecutablePath()
|
||||
{
|
||||
try
|
||||
{
|
||||
var assembly = System.Reflection.Assembly.GetExecutingAssembly();
|
||||
var location = assembly.Location;
|
||||
|
||||
// Handle .NET Core/5+ scenarios where Location might be empty
|
||||
if (string.IsNullOrEmpty(location))
|
||||
{
|
||||
location = System.Diagnostics.Process.GetCurrentProcess().MainModule?.FileName;
|
||||
}
|
||||
|
||||
// If we're running from a .dll, try to find the .exe
|
||||
if (!string.IsNullOrEmpty(location) && location.EndsWith(".dll", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
var exePath = Path.ChangeExtension(location, ".exe");
|
||||
if (File.Exists(exePath))
|
||||
{
|
||||
location = exePath;
|
||||
}
|
||||
}
|
||||
|
||||
return location;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
LogGetExecutablePathFailed(this.logger, ex);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private string? TryReadLegacyRegistryAutostart()
|
||||
{
|
||||
try
|
||||
{
|
||||
using var key = Registry.CurrentUser.OpenSubKey(REGISTRYKEYPATH, false);
|
||||
return key?.GetValue(APPLICATIONNAME) as string;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
LogLegacyRegistryReadFailed(this.logger, ex);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private void TryRemoveLegacyRegistryAutostart()
|
||||
{
|
||||
try
|
||||
{
|
||||
using var key = Registry.CurrentUser.OpenSubKey(REGISTRYKEYPATH, true);
|
||||
if (key?.GetValue(APPLICATIONNAME) != null)
|
||||
{
|
||||
key.DeleteValue(APPLICATIONNAME, false);
|
||||
LogLegacyRegistryEntryRemoved(this.logger);
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
LogLegacyRegistryCleanupFailed(this.logger, ex);
|
||||
}
|
||||
}
|
||||
|
||||
[LoggerMessage(EventId = 4200, Level = LogLevel.Debug, Message = "Autostart status initialization failed")]
|
||||
private static partial void LogAutostartInitializationFailed(ILogger logger, Exception ex);
|
||||
|
||||
[LoggerMessage(EventId = 4201, Level = LogLevel.Error, Message = "Could not determine executable path for autostart")]
|
||||
private static partial void LogAutostartExecutablePathMissing(ILogger logger);
|
||||
|
||||
[LoggerMessage(EventId = 4203, Level = LogLevel.Information, Message = "Autostart enabled: {Command}")]
|
||||
private static partial void LogAutostartEnabled(ILogger logger, string command);
|
||||
|
||||
[LoggerMessage(EventId = 4204, Level = LogLevel.Error, Message = "Failed to enable autostart")]
|
||||
private static partial void LogEnableAutostartFailed(ILogger logger, Exception ex);
|
||||
|
||||
[LoggerMessage(EventId = 4206, Level = LogLevel.Information, Message = "Autostart disabled")]
|
||||
private static partial void LogAutostartDisabled(ILogger logger);
|
||||
|
||||
[LoggerMessage(EventId = 4207, Level = LogLevel.Error, Message = "Failed to disable autostart")]
|
||||
private static partial void LogDisableAutostartFailed(ILogger logger, Exception ex);
|
||||
|
||||
[LoggerMessage(EventId = 4208, Level = LogLevel.Debug, Message = "Autostart status checked: {IsEnabled}, Path: {Path}")]
|
||||
private static partial void LogAutostartStatusChecked(ILogger logger, bool isEnabled, string? path);
|
||||
|
||||
[LoggerMessage(EventId = 4209, Level = LogLevel.Error, Message = "Failed to check autostart status")]
|
||||
private static partial void LogCheckAutostartStatusFailed(ILogger logger, Exception ex);
|
||||
|
||||
[LoggerMessage(EventId = 4210, Level = LogLevel.Error, Message = "Failed to get executable path")]
|
||||
private static partial void LogGetExecutablePathFailed(ILogger logger, Exception ex);
|
||||
|
||||
[LoggerMessage(EventId = 4218, Level = LogLevel.Information, Message = "Autostart configuration requires elevation; requesting elevated restart")]
|
||||
private static partial void LogAutostartRequiresElevation(ILogger logger);
|
||||
|
||||
[LoggerMessage(EventId = 4219, Level = LogLevel.Information, Message = "Autostart enable request delegated to elevated instance")]
|
||||
private static partial void LogAutostartDeferredToElevatedInstance(ILogger logger);
|
||||
|
||||
[LoggerMessage(EventId = 4220, Level = LogLevel.Warning, Message = "Failed to register elevated autostart task")]
|
||||
private static partial void LogAutostartTaskRegistrationFailed(ILogger logger);
|
||||
|
||||
[LoggerMessage(EventId = 4221, Level = LogLevel.Information, Message = "Autostart disable requires elevation; requesting elevated restart")]
|
||||
private static partial void LogAutostartDisableRequiresElevation(ILogger logger);
|
||||
|
||||
[LoggerMessage(EventId = 4222, Level = LogLevel.Information, Message = "Autostart disable request delegated to elevated instance")]
|
||||
private static partial void LogAutostartDisableDeferredToElevatedInstance(ILogger logger);
|
||||
|
||||
[LoggerMessage(EventId = 4223, Level = LogLevel.Warning, Message = "Failed to remove elevated autostart task")]
|
||||
private static partial void LogAutostartTaskRemovalFailed(ILogger logger);
|
||||
|
||||
[LoggerMessage(EventId = 4224, Level = LogLevel.Debug, Message = "Legacy HKCU Run autostart value removed")]
|
||||
private static partial void LogLegacyRegistryEntryRemoved(ILogger logger);
|
||||
|
||||
[LoggerMessage(EventId = 4225, Level = LogLevel.Debug, Message = "Failed to read legacy HKCU Run autostart value")]
|
||||
private static partial void LogLegacyRegistryReadFailed(ILogger logger, Exception ex);
|
||||
|
||||
[LoggerMessage(EventId = 4226, Level = LogLevel.Debug, Message = "Failed to remove legacy HKCU Run autostart value")]
|
||||
private static partial void LogLegacyRegistryCleanupFailed(ILogger logger, Exception ex);
|
||||
}
|
||||
}
|
||||
|
||||
namespace ThreadPilot.Services
|
||||
{
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Win32;
|
||||
|
||||
public partial class AutostartService : IAutostartService
|
||||
{
|
||||
private const string REGISTRYKEYPATH = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Run";
|
||||
private const string APPLICATIONNAME = "ThreadPilot";
|
||||
|
||||
private readonly ILogger<AutostartService> logger;
|
||||
private readonly IElevationService elevationService;
|
||||
private readonly IElevatedTaskService elevatedTaskService;
|
||||
private bool isAutostartEnabled;
|
||||
private string? autostartPath;
|
||||
|
||||
public event EventHandler<AutostartStatusChangedEventArgs>? AutostartStatusChanged;
|
||||
|
||||
public bool IsAutostartEnabled => this.isAutostartEnabled;
|
||||
|
||||
public string? AutostartPath => this.autostartPath;
|
||||
|
||||
public AutostartService(ILogger<AutostartService> logger, IElevationService elevationService, IElevatedTaskService elevatedTaskService)
|
||||
{
|
||||
this.logger = logger ?? throw new ArgumentNullException(nameof(logger));
|
||||
this.elevationService = elevationService ?? throw new ArgumentNullException(nameof(elevationService));
|
||||
this.elevatedTaskService = elevatedTaskService ?? throw new ArgumentNullException(nameof(elevatedTaskService));
|
||||
|
||||
// Initialize current status without surfacing startup exceptions.
|
||||
TaskSafety.FireAndForget(this.CheckAutostartStatusAsync(), ex =>
|
||||
{
|
||||
LogAutostartInitializationFailed(this.logger, ex);
|
||||
});
|
||||
}
|
||||
|
||||
public async Task<bool> EnableAutostartAsync(bool startMinimized = true)
|
||||
{
|
||||
try
|
||||
{
|
||||
var executablePath = this.GetExecutablePath();
|
||||
if (string.IsNullOrEmpty(executablePath))
|
||||
{
|
||||
LogAutostartExecutablePathMissing(this.logger);
|
||||
return false;
|
||||
}
|
||||
|
||||
var arguments = this.GetAutostartArguments(startMinimized);
|
||||
var fullCommand = $"\"{executablePath}\" {arguments}";
|
||||
|
||||
// Clean up legacy registry-based startup to keep a single elevated startup mechanism.
|
||||
this.TryRemoveLegacyRegistryAutostart();
|
||||
|
||||
if (!this.elevationService.IsRunningAsAdministrator())
|
||||
{
|
||||
LogAutostartRequiresElevation(this.logger);
|
||||
|
||||
var elevationRequested = await this.elevationService.RequestElevationIfNeeded();
|
||||
if (!elevationRequested)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
LogAutostartDeferredToElevatedInstance(this.logger);
|
||||
return false;
|
||||
}
|
||||
|
||||
var scheduledTaskCreated = await this.elevatedTaskService.EnsureAutostartTaskAsync(executablePath, arguments);
|
||||
if (!scheduledTaskCreated)
|
||||
{
|
||||
LogAutostartTaskRegistrationFailed(this.logger);
|
||||
return false;
|
||||
}
|
||||
|
||||
this.isAutostartEnabled = true;
|
||||
this.autostartPath = fullCommand;
|
||||
|
||||
LogAutostartEnabled(this.logger, fullCommand);
|
||||
|
||||
this.AutostartStatusChanged?.Invoke(this, new AutostartStatusChangedEventArgs(
|
||||
true, startMinimized, fullCommand));
|
||||
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
LogEnableAutostartFailed(this.logger, ex);
|
||||
|
||||
this.AutostartStatusChanged?.Invoke(this, new AutostartStatusChangedEventArgs(
|
||||
false, startMinimized, null, ex));
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<bool> DisableAutostartAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
if (!this.elevationService.IsRunningAsAdministrator())
|
||||
{
|
||||
LogAutostartDisableRequiresElevation(this.logger);
|
||||
|
||||
var elevationRequested = await this.elevationService.RequestElevationIfNeeded();
|
||||
if (!elevationRequested)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
LogAutostartDisableDeferredToElevatedInstance(this.logger);
|
||||
return false;
|
||||
}
|
||||
|
||||
this.TryRemoveLegacyRegistryAutostart();
|
||||
|
||||
var scheduledTaskRemoved = await this.elevatedTaskService.RemoveAutostartTaskAsync();
|
||||
if (!scheduledTaskRemoved)
|
||||
{
|
||||
LogAutostartTaskRemovalFailed(this.logger);
|
||||
return false;
|
||||
}
|
||||
|
||||
LogAutostartDisabled(this.logger);
|
||||
|
||||
this.isAutostartEnabled = false;
|
||||
this.autostartPath = null;
|
||||
|
||||
this.AutostartStatusChanged?.Invoke(this, new AutostartStatusChangedEventArgs(false));
|
||||
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
LogDisableAutostartFailed(this.logger, ex);
|
||||
|
||||
this.AutostartStatusChanged?.Invoke(this, new AutostartStatusChangedEventArgs(
|
||||
false, false, null, ex));
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<bool> CheckAutostartStatusAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
var taskRegistered = await this.elevatedTaskService.IsAutostartTaskRegisteredAsync();
|
||||
var legacyRegistryValue = this.TryReadLegacyRegistryAutostart();
|
||||
|
||||
this.isAutostartEnabled = taskRegistered || !string.IsNullOrWhiteSpace(legacyRegistryValue);
|
||||
this.autostartPath = taskRegistered
|
||||
? $"task://{this.elevatedTaskService.AutostartTaskName}"
|
||||
: legacyRegistryValue;
|
||||
|
||||
LogAutostartStatusChecked(this.logger, this.isAutostartEnabled, this.autostartPath);
|
||||
|
||||
return this.isAutostartEnabled;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
LogCheckAutostartStatusFailed(this.logger, ex);
|
||||
this.isAutostartEnabled = false;
|
||||
this.autostartPath = null;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<bool> UpdateAutostartAsync(bool startMinimized = true)
|
||||
{
|
||||
if (!this.isAutostartEnabled)
|
||||
{
|
||||
return await this.EnableAutostartAsync(startMinimized);
|
||||
}
|
||||
|
||||
// Re-enable with new parameters
|
||||
await this.DisableAutostartAsync();
|
||||
return await this.EnableAutostartAsync(startMinimized);
|
||||
}
|
||||
|
||||
public string GetAutostartArguments(bool startMinimized = true)
|
||||
{
|
||||
var args = new System.Collections.Generic.List<string>();
|
||||
|
||||
if (startMinimized)
|
||||
{
|
||||
args.Add("--start-minimized");
|
||||
}
|
||||
|
||||
// Add any other startup arguments as needed
|
||||
args.Add("--autostart");
|
||||
|
||||
return string.Join(" ", args);
|
||||
}
|
||||
|
||||
private string? GetExecutablePath()
|
||||
{
|
||||
try
|
||||
{
|
||||
var assembly = System.Reflection.Assembly.GetExecutingAssembly();
|
||||
var location = assembly.Location;
|
||||
|
||||
// Handle .NET Core/5+ scenarios where Location might be empty
|
||||
if (string.IsNullOrEmpty(location))
|
||||
{
|
||||
location = System.Diagnostics.Process.GetCurrentProcess().MainModule?.FileName;
|
||||
}
|
||||
|
||||
// If we're running from a .dll, try to find the .exe
|
||||
if (!string.IsNullOrEmpty(location) && location.EndsWith(".dll", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
var exePath = Path.ChangeExtension(location, ".exe");
|
||||
if (File.Exists(exePath))
|
||||
{
|
||||
location = exePath;
|
||||
}
|
||||
}
|
||||
|
||||
return location;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
LogGetExecutablePathFailed(this.logger, ex);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private string? TryReadLegacyRegistryAutostart()
|
||||
{
|
||||
try
|
||||
{
|
||||
using var key = Registry.CurrentUser.OpenSubKey(REGISTRYKEYPATH, false);
|
||||
return key?.GetValue(APPLICATIONNAME) as string;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
LogLegacyRegistryReadFailed(this.logger, ex);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private void TryRemoveLegacyRegistryAutostart()
|
||||
{
|
||||
try
|
||||
{
|
||||
using var key = Registry.CurrentUser.OpenSubKey(REGISTRYKEYPATH, true);
|
||||
if (key?.GetValue(APPLICATIONNAME) != null)
|
||||
{
|
||||
key.DeleteValue(APPLICATIONNAME, false);
|
||||
LogLegacyRegistryEntryRemoved(this.logger);
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
LogLegacyRegistryCleanupFailed(this.logger, ex);
|
||||
}
|
||||
}
|
||||
|
||||
[LoggerMessage(EventId = 4200, Level = LogLevel.Debug, Message = "Autostart status initialization failed")]
|
||||
private static partial void LogAutostartInitializationFailed(ILogger logger, Exception ex);
|
||||
|
||||
[LoggerMessage(EventId = 4201, Level = LogLevel.Error, Message = "Could not determine executable path for autostart")]
|
||||
private static partial void LogAutostartExecutablePathMissing(ILogger logger);
|
||||
|
||||
[LoggerMessage(EventId = 4203, Level = LogLevel.Information, Message = "Autostart enabled: {Command}")]
|
||||
private static partial void LogAutostartEnabled(ILogger logger, string command);
|
||||
|
||||
[LoggerMessage(EventId = 4204, Level = LogLevel.Error, Message = "Failed to enable autostart")]
|
||||
private static partial void LogEnableAutostartFailed(ILogger logger, Exception ex);
|
||||
|
||||
[LoggerMessage(EventId = 4206, Level = LogLevel.Information, Message = "Autostart disabled")]
|
||||
private static partial void LogAutostartDisabled(ILogger logger);
|
||||
|
||||
[LoggerMessage(EventId = 4207, Level = LogLevel.Error, Message = "Failed to disable autostart")]
|
||||
private static partial void LogDisableAutostartFailed(ILogger logger, Exception ex);
|
||||
|
||||
[LoggerMessage(EventId = 4208, Level = LogLevel.Debug, Message = "Autostart status checked: {IsEnabled}, Path: {Path}")]
|
||||
private static partial void LogAutostartStatusChecked(ILogger logger, bool isEnabled, string? path);
|
||||
|
||||
[LoggerMessage(EventId = 4209, Level = LogLevel.Error, Message = "Failed to check autostart status")]
|
||||
private static partial void LogCheckAutostartStatusFailed(ILogger logger, Exception ex);
|
||||
|
||||
[LoggerMessage(EventId = 4210, Level = LogLevel.Error, Message = "Failed to get executable path")]
|
||||
private static partial void LogGetExecutablePathFailed(ILogger logger, Exception ex);
|
||||
|
||||
[LoggerMessage(EventId = 4218, Level = LogLevel.Information, Message = "Autostart configuration requires elevation; requesting elevated restart")]
|
||||
private static partial void LogAutostartRequiresElevation(ILogger logger);
|
||||
|
||||
[LoggerMessage(EventId = 4219, Level = LogLevel.Information, Message = "Autostart enable request delegated to elevated instance")]
|
||||
private static partial void LogAutostartDeferredToElevatedInstance(ILogger logger);
|
||||
|
||||
[LoggerMessage(EventId = 4220, Level = LogLevel.Warning, Message = "Failed to register elevated autostart task")]
|
||||
private static partial void LogAutostartTaskRegistrationFailed(ILogger logger);
|
||||
|
||||
[LoggerMessage(EventId = 4221, Level = LogLevel.Information, Message = "Autostart disable requires elevation; requesting elevated restart")]
|
||||
private static partial void LogAutostartDisableRequiresElevation(ILogger logger);
|
||||
|
||||
[LoggerMessage(EventId = 4222, Level = LogLevel.Information, Message = "Autostart disable request delegated to elevated instance")]
|
||||
private static partial void LogAutostartDisableDeferredToElevatedInstance(ILogger logger);
|
||||
|
||||
[LoggerMessage(EventId = 4223, Level = LogLevel.Warning, Message = "Failed to remove elevated autostart task")]
|
||||
private static partial void LogAutostartTaskRemovalFailed(ILogger logger);
|
||||
|
||||
[LoggerMessage(EventId = 4224, Level = LogLevel.Debug, Message = "Legacy HKCU Run autostart value removed")]
|
||||
private static partial void LogLegacyRegistryEntryRemoved(ILogger logger);
|
||||
|
||||
[LoggerMessage(EventId = 4225, Level = LogLevel.Debug, Message = "Failed to read legacy HKCU Run autostart value")]
|
||||
private static partial void LogLegacyRegistryReadFailed(ILogger logger, Exception ex);
|
||||
|
||||
[LoggerMessage(EventId = 4226, Level = LogLevel.Debug, Message = "Failed to remove legacy HKCU Run autostart value")]
|
||||
private static partial void LogLegacyRegistryCleanupFailed(ILogger logger, Exception ex);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
+105
-124
@@ -1,124 +1,105 @@
|
||||
/*
|
||||
* ThreadPilot - Advanced Windows Process and Power Plan Manager
|
||||
* Copyright (C) 2025 Prime Build
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published by
|
||||
* the Free Software Foundation, version 3 only.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
namespace ThreadPilot.Services.Core
|
||||
{
|
||||
using System;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
/// <summary>
|
||||
/// Base implementation for system services with common functionality.
|
||||
/// </summary>
|
||||
public abstract class BaseSystemService : ISystemService, IDisposable
|
||||
{
|
||||
protected readonly ILogger Logger;
|
||||
private bool isAvailable;
|
||||
private bool disposed;
|
||||
|
||||
public bool IsAvailable
|
||||
{
|
||||
get => this.isAvailable;
|
||||
protected set
|
||||
{
|
||||
if (this.isAvailable != value)
|
||||
{
|
||||
this.isAvailable = value;
|
||||
this.OnAvailabilityChanged(value);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public event EventHandler<ServiceAvailabilityChangedEventArgs>? AvailabilityChanged;
|
||||
|
||||
protected BaseSystemService(ILogger logger)
|
||||
{
|
||||
this.Logger = logger ?? throw new ArgumentNullException(nameof(logger));
|
||||
}
|
||||
|
||||
public virtual async Task InitializeAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
this.Logger.LogInformation("Initializing {ServiceType}", this.GetType().Name);
|
||||
await this.InitializeServiceAsync();
|
||||
this.IsAvailable = true;
|
||||
this.Logger.LogInformation("{ServiceType} initialized successfully", this.GetType().Name);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
this.Logger.LogError(ex, "Failed to initialize {ServiceType}", this.GetType().Name);
|
||||
this.IsAvailable = false;
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
public virtual async Task DisposeAsync()
|
||||
{
|
||||
if (this.disposed)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
this.Logger.LogInformation("Disposing {ServiceType}", this.GetType().Name);
|
||||
await this.DisposeServiceAsync();
|
||||
this.IsAvailable = false;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
this.Logger.LogError(ex, "Error disposing {ServiceType}", this.GetType().Name);
|
||||
}
|
||||
finally
|
||||
{
|
||||
this.disposed = true;
|
||||
}
|
||||
}
|
||||
|
||||
protected abstract Task InitializeServiceAsync();
|
||||
|
||||
protected abstract Task DisposeServiceAsync();
|
||||
|
||||
protected virtual void OnAvailabilityChanged(bool isAvailable, string? reason = null)
|
||||
{
|
||||
this.AvailabilityChanged?.Invoke(this, new ServiceAvailabilityChangedEventArgs(isAvailable, reason));
|
||||
}
|
||||
|
||||
protected void ThrowIfDisposed()
|
||||
{
|
||||
if (this.disposed)
|
||||
{
|
||||
throw new ObjectDisposedException(this.GetType().Name);
|
||||
}
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
this.Dispose(true);
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
|
||||
protected virtual void Dispose(bool disposing)
|
||||
{
|
||||
if (!this.disposed && disposing)
|
||||
{
|
||||
_ = Task.Run(async () => await this.DisposeAsync());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
namespace ThreadPilot.Services.Core
|
||||
{
|
||||
using System;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
public abstract class BaseSystemService : ISystemService, IDisposable
|
||||
{
|
||||
protected readonly ILogger Logger;
|
||||
private bool isAvailable;
|
||||
private bool disposed;
|
||||
|
||||
public bool IsAvailable
|
||||
{
|
||||
get => this.isAvailable;
|
||||
protected set
|
||||
{
|
||||
if (this.isAvailable != value)
|
||||
{
|
||||
this.isAvailable = value;
|
||||
this.OnAvailabilityChanged(value);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public event EventHandler<ServiceAvailabilityChangedEventArgs>? AvailabilityChanged;
|
||||
|
||||
protected BaseSystemService(ILogger logger)
|
||||
{
|
||||
this.Logger = logger ?? throw new ArgumentNullException(nameof(logger));
|
||||
}
|
||||
|
||||
public virtual async Task InitializeAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
this.Logger.LogInformation("Initializing {ServiceType}", this.GetType().Name);
|
||||
await this.InitializeServiceAsync();
|
||||
this.IsAvailable = true;
|
||||
this.Logger.LogInformation("{ServiceType} initialized successfully", this.GetType().Name);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
this.Logger.LogError(ex, "Failed to initialize {ServiceType}", this.GetType().Name);
|
||||
this.IsAvailable = false;
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
public virtual async Task DisposeAsync()
|
||||
{
|
||||
if (this.disposed)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
this.Logger.LogInformation("Disposing {ServiceType}", this.GetType().Name);
|
||||
await this.DisposeServiceAsync();
|
||||
this.IsAvailable = false;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
this.Logger.LogError(ex, "Error disposing {ServiceType}", this.GetType().Name);
|
||||
}
|
||||
finally
|
||||
{
|
||||
this.disposed = true;
|
||||
}
|
||||
}
|
||||
|
||||
protected abstract Task InitializeServiceAsync();
|
||||
|
||||
protected abstract Task DisposeServiceAsync();
|
||||
|
||||
protected virtual void OnAvailabilityChanged(bool isAvailable, string? reason = null)
|
||||
{
|
||||
this.AvailabilityChanged?.Invoke(this, new ServiceAvailabilityChangedEventArgs(isAvailable, reason));
|
||||
}
|
||||
|
||||
protected void ThrowIfDisposed()
|
||||
{
|
||||
if (this.disposed)
|
||||
{
|
||||
throw new ObjectDisposedException(this.GetType().Name);
|
||||
}
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
this.Dispose(true);
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
|
||||
protected virtual void Dispose(bool disposing)
|
||||
{
|
||||
if (!this.disposed && disposing)
|
||||
{
|
||||
_ = Task.Run(async () => await this.DisposeAsync());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,63 +1,29 @@
|
||||
/*
|
||||
* ThreadPilot - Advanced Windows Process and Power Plan Manager
|
||||
* Copyright (C) 2025 Prime Build
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published by
|
||||
* the Free Software Foundation, version 3 only.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
namespace ThreadPilot.Services.Core
|
||||
{
|
||||
using System;
|
||||
|
||||
/// <summary>
|
||||
/// Base interface for core system services that interact directly with the operating system.
|
||||
/// </summary>
|
||||
public interface ISystemService
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets a value indicating whether gets whether the service is currently available and functional.
|
||||
/// </summary>
|
||||
bool IsAvailable { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Event fired when the service availability changes
|
||||
/// </summary>
|
||||
event EventHandler<ServiceAvailabilityChangedEventArgs>? AvailabilityChanged;
|
||||
|
||||
/// <summary>
|
||||
/// Initialize the service.
|
||||
/// </summary>
|
||||
Task InitializeAsync();
|
||||
|
||||
/// <summary>
|
||||
/// Cleanup and dispose of service resources.
|
||||
/// </summary>
|
||||
Task DisposeAsync();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Event args for service availability changes.
|
||||
/// </summary>
|
||||
public class ServiceAvailabilityChangedEventArgs : EventArgs
|
||||
{
|
||||
public bool IsAvailable { get; }
|
||||
|
||||
public string? Reason { get; }
|
||||
|
||||
public ServiceAvailabilityChangedEventArgs(bool isAvailable, string? reason = null)
|
||||
{
|
||||
this.IsAvailable = isAvailable;
|
||||
this.Reason = reason;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
namespace ThreadPilot.Services.Core
|
||||
{
|
||||
using System;
|
||||
|
||||
public interface ISystemService
|
||||
{
|
||||
bool IsAvailable { get; }
|
||||
|
||||
event EventHandler<ServiceAvailabilityChangedEventArgs>? AvailabilityChanged;
|
||||
|
||||
Task InitializeAsync();
|
||||
|
||||
Task DisposeAsync();
|
||||
}
|
||||
|
||||
public class ServiceAvailabilityChangedEventArgs : EventArgs
|
||||
{
|
||||
public bool IsAvailable { get; }
|
||||
|
||||
public string? Reason { get; }
|
||||
|
||||
public ServiceAvailabilityChangedEventArgs(bool isAvailable, string? reason = null)
|
||||
{
|
||||
this.IsAvailable = isAvailable;
|
||||
this.Reason = reason;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+872
-918
File diff suppressed because it is too large
Load Diff
@@ -1,28 +1,12 @@
|
||||
/*
|
||||
* ThreadPilot - Advanced Windows Process and Power Plan Manager
|
||||
* Copyright (C) 2025 Prime Build
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published by
|
||||
* the Free Software Foundation, version 3 only.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
namespace ThreadPilot.Services
|
||||
{
|
||||
public sealed record CpuPresetGenerationOptions
|
||||
{
|
||||
public bool ExcludeCpu0ForGaming { get; init; } = true;
|
||||
|
||||
public IReadOnlySet<string> DeletedGeneratedPresetIds { get; init; } =
|
||||
new HashSet<string>(StringComparer.Ordinal);
|
||||
|
||||
public bool IncludeExperimentalPresets { get; init; }
|
||||
}
|
||||
}
|
||||
namespace ThreadPilot.Services
|
||||
{
|
||||
public sealed record CpuPresetGenerationOptions
|
||||
{
|
||||
public bool ExcludeCpu0ForGaming { get; init; } = true;
|
||||
|
||||
public IReadOnlySet<string> DeletedGeneratedPresetIds { get; init; } =
|
||||
new HashSet<string>(StringComparer.Ordinal);
|
||||
|
||||
public bool IncludeExperimentalPresets { get; init; }
|
||||
}
|
||||
}
|
||||
|
||||
+324
-340
@@ -1,340 +1,324 @@
|
||||
/*
|
||||
* ThreadPilot - Advanced Windows Process and Power Plan Manager
|
||||
* Copyright (C) 2025 Prime Build
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published by
|
||||
* the Free Software Foundation, version 3 only.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
namespace ThreadPilot.Services
|
||||
{
|
||||
using ThreadPilot.Models;
|
||||
|
||||
public sealed class CpuPresetGenerator : ICpuPresetGenerator
|
||||
{
|
||||
private const string GamingWarning =
|
||||
"Suggested default. Results may vary by game and system. You can edit or delete this preset.";
|
||||
|
||||
public IReadOnlyList<CpuPreset> Generate(
|
||||
CpuTopologySnapshot topology,
|
||||
CpuPresetGenerationOptions? options = null)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(topology);
|
||||
|
||||
var resolvedOptions = options ?? new CpuPresetGenerationOptions();
|
||||
var presets = new List<CpuPreset>();
|
||||
|
||||
AddPreset(
|
||||
presets,
|
||||
resolvedOptions,
|
||||
CreatePreset(
|
||||
"all-cores",
|
||||
"All cores",
|
||||
"Use every logical processor reported by the current CPU topology.",
|
||||
topology.LogicalProcessors,
|
||||
topology,
|
||||
"Uses all logical processors from the topology snapshot."));
|
||||
|
||||
var allPhysicalProcessors = HasCoreIndexForAllProcessors(topology)
|
||||
? SelectOneLogicalProcessorPerCore(topology.LogicalProcessors, topology)
|
||||
: [];
|
||||
if (allPhysicalProcessors.Count > 0)
|
||||
{
|
||||
AddPreset(
|
||||
presets,
|
||||
resolvedOptions,
|
||||
CreatePreset(
|
||||
"all-physical-cores",
|
||||
"All physical cores / no SMT",
|
||||
"Use one logical processor per physical core.",
|
||||
allPhysicalProcessors,
|
||||
topology,
|
||||
"Uses CoreIndex and SMT sibling metadata to select one logical processor per core."));
|
||||
}
|
||||
|
||||
var allExceptCpu0 = topology.LogicalProcessors
|
||||
.Where(processor => processor.GlobalIndex != 0)
|
||||
.ToList();
|
||||
if (topology.LogicalProcessors.Count >= 2 && allExceptCpu0.Count > 0)
|
||||
{
|
||||
AddPreset(
|
||||
presets,
|
||||
resolvedOptions,
|
||||
CreatePreset(
|
||||
"all-except-cpu0",
|
||||
"All except CPU0",
|
||||
"Use every logical processor except global CPU index 0.",
|
||||
allExceptCpu0,
|
||||
topology,
|
||||
"Excludes GlobalIndex 0 while keeping the remaining topology-aware processor refs."));
|
||||
}
|
||||
|
||||
var efficiencyClasses = topology.LogicalProcessors
|
||||
.Select(processor => topology.TryGetEfficiencyClass(processor, out var efficiencyClass)
|
||||
? (byte?)efficiencyClass
|
||||
: null)
|
||||
.Where(efficiencyClass => efficiencyClass.HasValue)
|
||||
.Select(efficiencyClass => efficiencyClass!.Value)
|
||||
.Distinct()
|
||||
.OrderBy(efficiencyClass => efficiencyClass)
|
||||
.ToList();
|
||||
|
||||
var hasDistinctEfficiencyClasses = efficiencyClasses.Count >= 2;
|
||||
List<ProcessorRef> pCoreProcessors = [];
|
||||
if (hasDistinctEfficiencyClasses)
|
||||
{
|
||||
var performanceClass = efficiencyClasses.Max();
|
||||
pCoreProcessors = topology.LogicalProcessors
|
||||
.Where(processor =>
|
||||
topology.TryGetEfficiencyClass(processor, out var efficiencyClass) &&
|
||||
efficiencyClass == performanceClass)
|
||||
.ToList();
|
||||
var eCoreProcessors = topology.LogicalProcessors
|
||||
.Where(processor =>
|
||||
topology.TryGetEfficiencyClass(processor, out var efficiencyClass) &&
|
||||
efficiencyClass < performanceClass)
|
||||
.ToList();
|
||||
|
||||
AddPreset(
|
||||
presets,
|
||||
resolvedOptions,
|
||||
CreatePreset(
|
||||
"p-cores-only",
|
||||
"P-cores only",
|
||||
"Use logical processors in the highest EfficiencyClass.",
|
||||
pCoreProcessors,
|
||||
topology,
|
||||
"Uses the highest EfficiencyClass in the topology snapshot as performance cores."));
|
||||
|
||||
if (HasCoreIndexForProcessors(pCoreProcessors, topology))
|
||||
{
|
||||
AddPreset(
|
||||
presets,
|
||||
resolvedOptions,
|
||||
CreatePreset(
|
||||
"p-cores-no-smt",
|
||||
"P-cores only / no SMT",
|
||||
"Use one logical processor per performance core.",
|
||||
SelectOneLogicalProcessorPerCore(pCoreProcessors, topology),
|
||||
topology,
|
||||
"Uses EfficiencyClass plus CoreIndex and SMT sibling metadata to choose one logical processor per P-core."));
|
||||
}
|
||||
|
||||
AddPreset(
|
||||
presets,
|
||||
resolvedOptions,
|
||||
CreatePreset(
|
||||
"e-cores-only",
|
||||
"E-cores only",
|
||||
"Use logical processors below the highest EfficiencyClass.",
|
||||
eCoreProcessors,
|
||||
topology,
|
||||
"Uses EfficiencyClass values below the performance class as efficiency cores.",
|
||||
"Usually not recommended for games. Useful for background tasks."));
|
||||
}
|
||||
|
||||
if (topology.Signature.LastLevelCacheGroupCount > 1 && HasCoreIndexForAllProcessors(topology))
|
||||
{
|
||||
var l3Groups = topology.LogicalProcessors
|
||||
.Select(processor => topology.TryGetLastLevelCacheIndex(processor, out var cacheIndex)
|
||||
? new { Processor = processor, CacheIndex = (int?)cacheIndex }
|
||||
: null)
|
||||
.Where(item => item?.CacheIndex != null)
|
||||
.GroupBy(item => item!.CacheIndex!.Value)
|
||||
.OrderBy(group => group.Key);
|
||||
|
||||
foreach (var group in l3Groups)
|
||||
{
|
||||
AddPreset(
|
||||
presets,
|
||||
resolvedOptions,
|
||||
CreatePreset(
|
||||
$"l3-group-{group.Key}-physical",
|
||||
$"L3 group {group.Key} / physical cores",
|
||||
$"Use one logical processor per core in L3/cache group {group.Key}.",
|
||||
SelectOneLogicalProcessorPerCore(group.Select(item => item!.Processor), topology),
|
||||
topology,
|
||||
$"Based on LastLevelCacheIndex/L3 cache group {group.Key}, not on CPU SKU naming."));
|
||||
}
|
||||
}
|
||||
|
||||
var bestGamingSourceId = SelectBestGamingSourcePresetId(presets, resolvedOptions);
|
||||
if (bestGamingSourceId != null)
|
||||
{
|
||||
var sourcePreset = presets.Single(preset => preset.PresetId == bestGamingSourceId);
|
||||
AddPreset(
|
||||
presets,
|
||||
resolvedOptions,
|
||||
CreatePreset(
|
||||
"best-gaming",
|
||||
"Best gaming suggestion",
|
||||
"Suggested topology-aware starting point for games.",
|
||||
sourcePreset.Selection.LogicalProcessors,
|
||||
topology,
|
||||
CreateBestGamingReason(bestGamingSourceId),
|
||||
GamingWarning,
|
||||
sourcePresetId: bestGamingSourceId));
|
||||
}
|
||||
|
||||
AddPreset(
|
||||
presets,
|
||||
resolvedOptions,
|
||||
CreatePreset(
|
||||
"safe-compatibility",
|
||||
"Safe compatibility",
|
||||
"Use every logical processor for maximum compatibility.",
|
||||
topology.LogicalProcessors,
|
||||
topology,
|
||||
"Maximum compatibility."));
|
||||
|
||||
// TODO: X3D CCD-only presets require reliable cache/topology detection.
|
||||
// Do not generate X3D CCD-only until it can be detected with confidence.
|
||||
return presets;
|
||||
}
|
||||
|
||||
private static string? SelectBestGamingSourcePresetId(
|
||||
IReadOnlyList<CpuPreset> presets,
|
||||
CpuPresetGenerationOptions options)
|
||||
{
|
||||
var orderedCandidates = options.ExcludeCpu0ForGaming
|
||||
? new[]
|
||||
{
|
||||
"p-cores-no-smt",
|
||||
"l3-group-0-physical",
|
||||
"all-physical-cores",
|
||||
"all-except-cpu0",
|
||||
"all-cores",
|
||||
}
|
||||
: new[]
|
||||
{
|
||||
"p-cores-no-smt",
|
||||
"l3-group-0-physical",
|
||||
"all-physical-cores",
|
||||
"all-cores",
|
||||
};
|
||||
|
||||
return orderedCandidates.FirstOrDefault(candidate =>
|
||||
presets.Any(preset => preset.PresetId == candidate));
|
||||
}
|
||||
|
||||
private static string CreateBestGamingReason(string sourcePresetId) =>
|
||||
sourcePresetId switch
|
||||
{
|
||||
"p-cores-no-smt" =>
|
||||
"Selected P-cores without SMT because the topology exposes distinct performance and efficiency core classes.",
|
||||
"l3-group-0-physical" =>
|
||||
"Selected physical cores from L3/cache group 0 because the topology exposes multiple L3 groups and no P/E core classes.",
|
||||
"all-physical-cores" =>
|
||||
"Selected one logical processor per physical core because reliable CoreIndex metadata is available.",
|
||||
"all-except-cpu0" =>
|
||||
"Selected all logical processors except CPU0 as a conservative gaming-oriented fallback.",
|
||||
"all-cores" =>
|
||||
"Selected all logical processors as the safest fallback because no more specific topology preset was available.",
|
||||
_ =>
|
||||
"Selected the best available topology-aware preset for this CPU.",
|
||||
};
|
||||
|
||||
private static bool HasCoreIndexForAllProcessors(CpuTopologySnapshot topology) =>
|
||||
HasCoreIndexForProcessors(topology.LogicalProcessors, topology);
|
||||
|
||||
private static bool HasCoreIndexForProcessors(
|
||||
IEnumerable<ProcessorRef> processors,
|
||||
CpuTopologySnapshot topology)
|
||||
{
|
||||
var processorList = processors.ToList();
|
||||
return processorList.Count > 0 &&
|
||||
processorList.All(processor => topology.TryGetCoreIndex(processor, out _));
|
||||
}
|
||||
|
||||
private static List<ProcessorRef> SelectOneLogicalProcessorPerCore(
|
||||
IEnumerable<ProcessorRef> processors,
|
||||
CpuTopologySnapshot topology)
|
||||
{
|
||||
return processors
|
||||
.Select(processor =>
|
||||
{
|
||||
topology.TryGetCoreIndex(processor, out var coreIndex);
|
||||
return new
|
||||
{
|
||||
Processor = processor,
|
||||
CoreIndex = coreIndex,
|
||||
SmtSiblingCount = topology.GetSmtSiblingGlobalIndexes(processor).Count,
|
||||
};
|
||||
})
|
||||
.GroupBy(item => item.CoreIndex)
|
||||
.OrderBy(group => group.Key)
|
||||
.Select(group => group
|
||||
.OrderBy(item => item.Processor.GlobalIndex)
|
||||
.ThenBy(item => item.SmtSiblingCount)
|
||||
.First()
|
||||
.Processor)
|
||||
.ToList();
|
||||
}
|
||||
|
||||
private static CpuPreset CreatePreset(
|
||||
string presetId,
|
||||
string name,
|
||||
string description,
|
||||
IEnumerable<ProcessorRef> processors,
|
||||
CpuTopologySnapshot topology,
|
||||
string reason,
|
||||
string? warning = null,
|
||||
string? sourcePresetId = null,
|
||||
bool reviewRequired = false)
|
||||
{
|
||||
var selectedProcessors = processors
|
||||
.Distinct()
|
||||
.OrderBy(processor => processor.GlobalIndex)
|
||||
.ThenBy(processor => processor.Group)
|
||||
.ThenBy(processor => processor.LogicalProcessorNumber)
|
||||
.ToList();
|
||||
|
||||
return new CpuPreset
|
||||
{
|
||||
PresetId = presetId,
|
||||
Name = name,
|
||||
Description = description,
|
||||
Selection = CpuSelection.FromProcessors(selectedProcessors, topology, reason),
|
||||
Reason = reason,
|
||||
SourcePresetId = sourcePresetId,
|
||||
Warning = warning,
|
||||
GeneratedByTopologySignature = topology.Signature,
|
||||
IsUserEditable = true,
|
||||
IsGenerated = true,
|
||||
ReviewRequired = reviewRequired,
|
||||
};
|
||||
}
|
||||
|
||||
private static void AddPreset(
|
||||
List<CpuPreset> presets,
|
||||
CpuPresetGenerationOptions options,
|
||||
CpuPreset preset)
|
||||
{
|
||||
if (options.DeletedGeneratedPresetIds.Contains(preset.PresetId) ||
|
||||
preset.Selection.LogicalProcessors.Count == 0 ||
|
||||
presets.Any(existing => existing.PresetId == preset.PresetId))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var duplicateSamePurpose = presets.Any(existing =>
|
||||
existing.Reason == preset.Reason &&
|
||||
existing.Selection.GlobalLogicalProcessorIndexes.SequenceEqual(
|
||||
preset.Selection.GlobalLogicalProcessorIndexes));
|
||||
if (duplicateSamePurpose)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
presets.Add(preset);
|
||||
}
|
||||
}
|
||||
}
|
||||
namespace ThreadPilot.Services
|
||||
{
|
||||
using ThreadPilot.Models;
|
||||
|
||||
public sealed class CpuPresetGenerator : ICpuPresetGenerator
|
||||
{
|
||||
private const string GamingWarning =
|
||||
"Suggested default. Results may vary by game and system. You can edit or delete this preset.";
|
||||
|
||||
public IReadOnlyList<CpuPreset> Generate(
|
||||
CpuTopologySnapshot topology,
|
||||
CpuPresetGenerationOptions? options = null)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(topology);
|
||||
|
||||
var resolvedOptions = options ?? new CpuPresetGenerationOptions();
|
||||
var presets = new List<CpuPreset>();
|
||||
|
||||
AddPreset(
|
||||
presets,
|
||||
resolvedOptions,
|
||||
CreatePreset(
|
||||
"all-cores",
|
||||
"All cores",
|
||||
"Use every logical processor reported by the current CPU topology.",
|
||||
topology.LogicalProcessors,
|
||||
topology,
|
||||
"Uses all logical processors from the topology snapshot."));
|
||||
|
||||
var allPhysicalProcessors = HasCoreIndexForAllProcessors(topology)
|
||||
? SelectOneLogicalProcessorPerCore(topology.LogicalProcessors, topology)
|
||||
: [];
|
||||
if (allPhysicalProcessors.Count > 0)
|
||||
{
|
||||
AddPreset(
|
||||
presets,
|
||||
resolvedOptions,
|
||||
CreatePreset(
|
||||
"all-physical-cores",
|
||||
"All physical cores / no SMT",
|
||||
"Use one logical processor per physical core.",
|
||||
allPhysicalProcessors,
|
||||
topology,
|
||||
"Uses CoreIndex and SMT sibling metadata to select one logical processor per core."));
|
||||
}
|
||||
|
||||
var allExceptCpu0 = topology.LogicalProcessors
|
||||
.Where(processor => processor.GlobalIndex != 0)
|
||||
.ToList();
|
||||
if (topology.LogicalProcessors.Count >= 2 && allExceptCpu0.Count > 0)
|
||||
{
|
||||
AddPreset(
|
||||
presets,
|
||||
resolvedOptions,
|
||||
CreatePreset(
|
||||
"all-except-cpu0",
|
||||
"All except CPU0",
|
||||
"Use every logical processor except global CPU index 0.",
|
||||
allExceptCpu0,
|
||||
topology,
|
||||
"Excludes GlobalIndex 0 while keeping the remaining topology-aware processor refs."));
|
||||
}
|
||||
|
||||
var efficiencyClasses = topology.LogicalProcessors
|
||||
.Select(processor => topology.TryGetEfficiencyClass(processor, out var efficiencyClass)
|
||||
? (byte?)efficiencyClass
|
||||
: null)
|
||||
.Where(efficiencyClass => efficiencyClass.HasValue)
|
||||
.Select(efficiencyClass => efficiencyClass!.Value)
|
||||
.Distinct()
|
||||
.OrderBy(efficiencyClass => efficiencyClass)
|
||||
.ToList();
|
||||
|
||||
var hasDistinctEfficiencyClasses = efficiencyClasses.Count >= 2;
|
||||
List<ProcessorRef> pCoreProcessors = [];
|
||||
if (hasDistinctEfficiencyClasses)
|
||||
{
|
||||
var performanceClass = efficiencyClasses.Max();
|
||||
pCoreProcessors = topology.LogicalProcessors
|
||||
.Where(processor =>
|
||||
topology.TryGetEfficiencyClass(processor, out var efficiencyClass) &&
|
||||
efficiencyClass == performanceClass)
|
||||
.ToList();
|
||||
var eCoreProcessors = topology.LogicalProcessors
|
||||
.Where(processor =>
|
||||
topology.TryGetEfficiencyClass(processor, out var efficiencyClass) &&
|
||||
efficiencyClass < performanceClass)
|
||||
.ToList();
|
||||
|
||||
AddPreset(
|
||||
presets,
|
||||
resolvedOptions,
|
||||
CreatePreset(
|
||||
"p-cores-only",
|
||||
"P-cores only",
|
||||
"Use logical processors in the highest EfficiencyClass.",
|
||||
pCoreProcessors,
|
||||
topology,
|
||||
"Uses the highest EfficiencyClass in the topology snapshot as performance cores."));
|
||||
|
||||
if (HasCoreIndexForProcessors(pCoreProcessors, topology))
|
||||
{
|
||||
AddPreset(
|
||||
presets,
|
||||
resolvedOptions,
|
||||
CreatePreset(
|
||||
"p-cores-no-smt",
|
||||
"P-cores only / no SMT",
|
||||
"Use one logical processor per performance core.",
|
||||
SelectOneLogicalProcessorPerCore(pCoreProcessors, topology),
|
||||
topology,
|
||||
"Uses EfficiencyClass plus CoreIndex and SMT sibling metadata to choose one logical processor per P-core."));
|
||||
}
|
||||
|
||||
AddPreset(
|
||||
presets,
|
||||
resolvedOptions,
|
||||
CreatePreset(
|
||||
"e-cores-only",
|
||||
"E-cores only",
|
||||
"Use logical processors below the highest EfficiencyClass.",
|
||||
eCoreProcessors,
|
||||
topology,
|
||||
"Uses EfficiencyClass values below the performance class as efficiency cores.",
|
||||
"Usually not recommended for games. Useful for background tasks."));
|
||||
}
|
||||
|
||||
if (topology.Signature.LastLevelCacheGroupCount > 1 && HasCoreIndexForAllProcessors(topology))
|
||||
{
|
||||
var l3Groups = topology.LogicalProcessors
|
||||
.Select(processor => topology.TryGetLastLevelCacheIndex(processor, out var cacheIndex)
|
||||
? new { Processor = processor, CacheIndex = (int?)cacheIndex }
|
||||
: null)
|
||||
.Where(item => item?.CacheIndex != null)
|
||||
.GroupBy(item => item!.CacheIndex!.Value)
|
||||
.OrderBy(group => group.Key);
|
||||
|
||||
foreach (var group in l3Groups)
|
||||
{
|
||||
AddPreset(
|
||||
presets,
|
||||
resolvedOptions,
|
||||
CreatePreset(
|
||||
$"l3-group-{group.Key}-physical",
|
||||
$"L3 group {group.Key} / physical cores",
|
||||
$"Use one logical processor per core in L3/cache group {group.Key}.",
|
||||
SelectOneLogicalProcessorPerCore(group.Select(item => item!.Processor), topology),
|
||||
topology,
|
||||
$"Based on LastLevelCacheIndex/L3 cache group {group.Key}, not on CPU SKU naming."));
|
||||
}
|
||||
}
|
||||
|
||||
var bestGamingSourceId = SelectBestGamingSourcePresetId(presets, resolvedOptions);
|
||||
if (bestGamingSourceId != null)
|
||||
{
|
||||
var sourcePreset = presets.Single(preset => preset.PresetId == bestGamingSourceId);
|
||||
AddPreset(
|
||||
presets,
|
||||
resolvedOptions,
|
||||
CreatePreset(
|
||||
"best-gaming",
|
||||
"Best gaming suggestion",
|
||||
"Suggested topology-aware starting point for games.",
|
||||
sourcePreset.Selection.LogicalProcessors,
|
||||
topology,
|
||||
CreateBestGamingReason(bestGamingSourceId),
|
||||
GamingWarning,
|
||||
sourcePresetId: bestGamingSourceId));
|
||||
}
|
||||
|
||||
AddPreset(
|
||||
presets,
|
||||
resolvedOptions,
|
||||
CreatePreset(
|
||||
"safe-compatibility",
|
||||
"Safe compatibility",
|
||||
"Use every logical processor for maximum compatibility.",
|
||||
topology.LogicalProcessors,
|
||||
topology,
|
||||
"Maximum compatibility."));
|
||||
|
||||
// TODO: X3D CCD-only presets require reliable cache/topology detection.
|
||||
// Do not generate X3D CCD-only until it can be detected with confidence.
|
||||
return presets;
|
||||
}
|
||||
|
||||
private static string? SelectBestGamingSourcePresetId(
|
||||
IReadOnlyList<CpuPreset> presets,
|
||||
CpuPresetGenerationOptions options)
|
||||
{
|
||||
var orderedCandidates = options.ExcludeCpu0ForGaming
|
||||
? new[]
|
||||
{
|
||||
"p-cores-no-smt",
|
||||
"l3-group-0-physical",
|
||||
"all-physical-cores",
|
||||
"all-except-cpu0",
|
||||
"all-cores",
|
||||
}
|
||||
: new[]
|
||||
{
|
||||
"p-cores-no-smt",
|
||||
"l3-group-0-physical",
|
||||
"all-physical-cores",
|
||||
"all-cores",
|
||||
};
|
||||
|
||||
return orderedCandidates.FirstOrDefault(candidate =>
|
||||
presets.Any(preset => preset.PresetId == candidate));
|
||||
}
|
||||
|
||||
private static string CreateBestGamingReason(string sourcePresetId) =>
|
||||
sourcePresetId switch
|
||||
{
|
||||
"p-cores-no-smt" =>
|
||||
"Selected P-cores without SMT because the topology exposes distinct performance and efficiency core classes.",
|
||||
"l3-group-0-physical" =>
|
||||
"Selected physical cores from L3/cache group 0 because the topology exposes multiple L3 groups and no P/E core classes.",
|
||||
"all-physical-cores" =>
|
||||
"Selected one logical processor per physical core because reliable CoreIndex metadata is available.",
|
||||
"all-except-cpu0" =>
|
||||
"Selected all logical processors except CPU0 as a conservative gaming-oriented fallback.",
|
||||
"all-cores" =>
|
||||
"Selected all logical processors as the safest fallback because no more specific topology preset was available.",
|
||||
_ =>
|
||||
"Selected the best available topology-aware preset for this CPU.",
|
||||
};
|
||||
|
||||
private static bool HasCoreIndexForAllProcessors(CpuTopologySnapshot topology) =>
|
||||
HasCoreIndexForProcessors(topology.LogicalProcessors, topology);
|
||||
|
||||
private static bool HasCoreIndexForProcessors(
|
||||
IEnumerable<ProcessorRef> processors,
|
||||
CpuTopologySnapshot topology)
|
||||
{
|
||||
var processorList = processors.ToList();
|
||||
return processorList.Count > 0 &&
|
||||
processorList.All(processor => topology.TryGetCoreIndex(processor, out _));
|
||||
}
|
||||
|
||||
private static List<ProcessorRef> SelectOneLogicalProcessorPerCore(
|
||||
IEnumerable<ProcessorRef> processors,
|
||||
CpuTopologySnapshot topology)
|
||||
{
|
||||
return processors
|
||||
.Select(processor =>
|
||||
{
|
||||
topology.TryGetCoreIndex(processor, out var coreIndex);
|
||||
return new
|
||||
{
|
||||
Processor = processor,
|
||||
CoreIndex = coreIndex,
|
||||
SmtSiblingCount = topology.GetSmtSiblingGlobalIndexes(processor).Count,
|
||||
};
|
||||
})
|
||||
.GroupBy(item => item.CoreIndex)
|
||||
.OrderBy(group => group.Key)
|
||||
.Select(group => group
|
||||
.OrderBy(item => item.Processor.GlobalIndex)
|
||||
.ThenBy(item => item.SmtSiblingCount)
|
||||
.First()
|
||||
.Processor)
|
||||
.ToList();
|
||||
}
|
||||
|
||||
private static CpuPreset CreatePreset(
|
||||
string presetId,
|
||||
string name,
|
||||
string description,
|
||||
IEnumerable<ProcessorRef> processors,
|
||||
CpuTopologySnapshot topology,
|
||||
string reason,
|
||||
string? warning = null,
|
||||
string? sourcePresetId = null,
|
||||
bool reviewRequired = false)
|
||||
{
|
||||
var selectedProcessors = processors
|
||||
.Distinct()
|
||||
.OrderBy(processor => processor.GlobalIndex)
|
||||
.ThenBy(processor => processor.Group)
|
||||
.ThenBy(processor => processor.LogicalProcessorNumber)
|
||||
.ToList();
|
||||
|
||||
return new CpuPreset
|
||||
{
|
||||
PresetId = presetId,
|
||||
Name = name,
|
||||
Description = description,
|
||||
Selection = CpuSelection.FromProcessors(selectedProcessors, topology, reason),
|
||||
Reason = reason,
|
||||
SourcePresetId = sourcePresetId,
|
||||
Warning = warning,
|
||||
GeneratedByTopologySignature = topology.Signature,
|
||||
IsUserEditable = true,
|
||||
IsGenerated = true,
|
||||
ReviewRequired = reviewRequired,
|
||||
};
|
||||
}
|
||||
|
||||
private static void AddPreset(
|
||||
List<CpuPreset> presets,
|
||||
CpuPresetGenerationOptions options,
|
||||
CpuPreset preset)
|
||||
{
|
||||
if (options.DeletedGeneratedPresetIds.Contains(preset.PresetId) ||
|
||||
preset.Selection.LogicalProcessors.Count == 0 ||
|
||||
presets.Any(existing => existing.PresetId == preset.PresetId))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var duplicateSamePurpose = presets.Any(existing =>
|
||||
existing.Reason == preset.Reason &&
|
||||
existing.Selection.GlobalLogicalProcessorIndexes.SequenceEqual(
|
||||
preset.Selection.GlobalLogicalProcessorIndexes));
|
||||
if (duplicateSamePurpose)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
presets.Add(preset);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,24 +1,8 @@
|
||||
/*
|
||||
* ThreadPilot - Advanced Windows Process and Power Plan Manager
|
||||
* Copyright (C) 2025 Prime Build
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published by
|
||||
* the Free Software Foundation, version 3 only.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
namespace ThreadPilot.Services
|
||||
{
|
||||
using ThreadPilot.Models;
|
||||
|
||||
public sealed record CpuSelectionMigrationResult(
|
||||
CpuSelection Selection,
|
||||
CpuSelectionMigrationMetadata Metadata);
|
||||
}
|
||||
namespace ThreadPilot.Services
|
||||
{
|
||||
using ThreadPilot.Models;
|
||||
|
||||
public sealed record CpuSelectionMigrationResult(
|
||||
CpuSelection Selection,
|
||||
CpuSelectionMigrationMetadata Metadata);
|
||||
}
|
||||
|
||||
@@ -1,168 +1,152 @@
|
||||
/*
|
||||
* ThreadPilot - Advanced Windows Process and Power Plan Manager
|
||||
* Copyright (C) 2025 Prime Build
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published by
|
||||
* the Free Software Foundation, version 3 only.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
namespace ThreadPilot.Services
|
||||
{
|
||||
using ThreadPilot.Models;
|
||||
|
||||
public sealed class CpuSelectionMigrationService
|
||||
{
|
||||
public CpuSelectionMigrationResult MigrateFromLegacyAffinityMask(
|
||||
long mask,
|
||||
CpuTopologySnapshot topology)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(topology);
|
||||
|
||||
var selection = CpuSelection.FromLegacyAffinityMask(mask, topology);
|
||||
var reviewRequired = topology.Signature.LogicalProcessorCount > 64 ||
|
||||
topology.Signature.ProcessorGroupCount > 1;
|
||||
|
||||
return new CpuSelectionMigrationResult(
|
||||
selection,
|
||||
new CpuSelectionMigrationMetadata
|
||||
{
|
||||
CreatedFromLegacyAffinityMask = true,
|
||||
ReviewRequired = reviewRequired,
|
||||
MigrationConfidence = reviewRequired ? "Medium" : "High",
|
||||
Reason = reviewRequired
|
||||
? "Migrated from a legacy affinity mask on a topology that may not be fully represented by legacy masks."
|
||||
: "Migrated from a legacy affinity mask.",
|
||||
TopologySignature = topology.Signature,
|
||||
SourceLegacyAffinityMask = mask,
|
||||
});
|
||||
}
|
||||
|
||||
public CpuSelectionMigrationResult MigrateFromLegacyCoreMask(
|
||||
IReadOnlyList<bool> coreMask,
|
||||
CpuTopologySnapshot topology)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(coreMask);
|
||||
ArgumentNullException.ThrowIfNull(topology);
|
||||
|
||||
var orderedProcessors = topology.LogicalProcessors
|
||||
.OrderBy(processor => processor.GlobalIndex)
|
||||
.ThenBy(processor => processor.Group)
|
||||
.ThenBy(processor => processor.LogicalProcessorNumber)
|
||||
.ToList();
|
||||
var selectedProcessors = orderedProcessors
|
||||
.Take(Math.Min(coreMask.Count, orderedProcessors.Count))
|
||||
.Where((_, index) => coreMask[index])
|
||||
.ToList();
|
||||
var reviewRequired = coreMask.Count != orderedProcessors.Count;
|
||||
var selection = CpuSelection.FromProcessors(
|
||||
selectedProcessors,
|
||||
topology,
|
||||
"Migrated from legacy core mask");
|
||||
|
||||
return new CpuSelectionMigrationResult(
|
||||
selection,
|
||||
new CpuSelectionMigrationMetadata
|
||||
{
|
||||
CreatedFromLegacyCoreMask = true,
|
||||
ReviewRequired = reviewRequired,
|
||||
MigrationConfidence = reviewRequired ? "Medium" : "High",
|
||||
Reason = reviewRequired
|
||||
? "Migrated from a legacy core mask whose length differs from the current topology."
|
||||
: "Migrated from a legacy core mask.",
|
||||
TopologySignature = topology.Signature,
|
||||
});
|
||||
}
|
||||
|
||||
public long? BuildLegacyAffinityMaskIfRepresentable(CpuSelection selection) =>
|
||||
CpuSelection.ToLegacyAffinityMaskOrNull(selection);
|
||||
|
||||
public bool ShouldRequireReview(
|
||||
CpuSelection selection,
|
||||
CpuTopologySignature? savedSignature,
|
||||
CpuTopologySnapshot currentTopology)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(selection);
|
||||
ArgumentNullException.ThrowIfNull(currentTopology);
|
||||
|
||||
if (savedSignature == null || savedSignature != currentTopology.Signature)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
var currentProcessors = currentTopology.LogicalProcessors.ToHashSet();
|
||||
return selection.LogicalProcessors.Any(processor => !currentProcessors.Contains(processor));
|
||||
}
|
||||
|
||||
public ProcessProfileSnapshot MigrateProcessProfile(
|
||||
ProcessProfileSnapshot profile,
|
||||
CpuTopologySnapshot topology)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(profile);
|
||||
ArgumentNullException.ThrowIfNull(topology);
|
||||
|
||||
if (profile.CpuSelection != null)
|
||||
{
|
||||
profile.ProfileSchemaVersion = CpuAffinityProfileSchemaVersions.CpuSelection;
|
||||
profile.CpuSelectionMigration ??= new CpuSelectionMigrationMetadata
|
||||
{
|
||||
ReviewRequired = this.ShouldRequireReview(
|
||||
profile.CpuSelection,
|
||||
profile.CpuSelection.Metadata.TopologySignature,
|
||||
topology),
|
||||
MigrationConfidence = "High",
|
||||
Reason = "Profile already contains a CpuSelection.",
|
||||
TopologySignature = profile.CpuSelection.Metadata.TopologySignature,
|
||||
SourceLegacyAffinityMask = profile.ProcessorAffinity,
|
||||
};
|
||||
return profile;
|
||||
}
|
||||
|
||||
var migrated = this.MigrateFromLegacyAffinityMask(profile.ProcessorAffinity, topology);
|
||||
profile.ProfileSchemaVersion = CpuAffinityProfileSchemaVersions.CpuSelection;
|
||||
profile.CpuSelection = migrated.Selection;
|
||||
profile.CpuSelectionMigration = migrated.Metadata;
|
||||
return profile;
|
||||
}
|
||||
|
||||
public ProcessProfileSnapshot PrepareProcessProfileForSave(
|
||||
ProcessProfileSnapshot profile,
|
||||
CpuTopologySnapshot topology)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(profile);
|
||||
ArgumentNullException.ThrowIfNull(topology);
|
||||
|
||||
if (profile.CpuSelection == null)
|
||||
{
|
||||
this.MigrateProcessProfile(profile, topology);
|
||||
}
|
||||
|
||||
profile.ProfileSchemaVersion = CpuAffinityProfileSchemaVersions.CpuSelection;
|
||||
if (profile.CpuSelection != null)
|
||||
{
|
||||
var legacyMask = this.BuildLegacyAffinityMaskIfRepresentable(profile.CpuSelection);
|
||||
if (legacyMask.HasValue)
|
||||
{
|
||||
profile.ProcessorAffinity = legacyMask.Value;
|
||||
}
|
||||
}
|
||||
|
||||
profile.CpuSelectionMigration ??= new CpuSelectionMigrationMetadata
|
||||
{
|
||||
MigrationConfidence = "High",
|
||||
Reason = "Saved with CpuSelection profile schema.",
|
||||
TopologySignature = topology.Signature,
|
||||
SourceLegacyAffinityMask = profile.ProcessorAffinity,
|
||||
};
|
||||
|
||||
return profile;
|
||||
}
|
||||
}
|
||||
}
|
||||
namespace ThreadPilot.Services
|
||||
{
|
||||
using ThreadPilot.Models;
|
||||
|
||||
public sealed class CpuSelectionMigrationService
|
||||
{
|
||||
public CpuSelectionMigrationResult MigrateFromLegacyAffinityMask(
|
||||
long mask,
|
||||
CpuTopologySnapshot topology)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(topology);
|
||||
|
||||
var selection = CpuSelection.FromLegacyAffinityMask(mask, topology);
|
||||
var reviewRequired = topology.Signature.LogicalProcessorCount > 64 ||
|
||||
topology.Signature.ProcessorGroupCount > 1;
|
||||
|
||||
return new CpuSelectionMigrationResult(
|
||||
selection,
|
||||
new CpuSelectionMigrationMetadata
|
||||
{
|
||||
CreatedFromLegacyAffinityMask = true,
|
||||
ReviewRequired = reviewRequired,
|
||||
MigrationConfidence = reviewRequired ? "Medium" : "High",
|
||||
Reason = reviewRequired
|
||||
? "Migrated from a legacy affinity mask on a topology that may not be fully represented by legacy masks."
|
||||
: "Migrated from a legacy affinity mask.",
|
||||
TopologySignature = topology.Signature,
|
||||
SourceLegacyAffinityMask = mask,
|
||||
});
|
||||
}
|
||||
|
||||
public CpuSelectionMigrationResult MigrateFromLegacyCoreMask(
|
||||
IReadOnlyList<bool> coreMask,
|
||||
CpuTopologySnapshot topology)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(coreMask);
|
||||
ArgumentNullException.ThrowIfNull(topology);
|
||||
|
||||
var orderedProcessors = topology.LogicalProcessors
|
||||
.OrderBy(processor => processor.GlobalIndex)
|
||||
.ThenBy(processor => processor.Group)
|
||||
.ThenBy(processor => processor.LogicalProcessorNumber)
|
||||
.ToList();
|
||||
var selectedProcessors = orderedProcessors
|
||||
.Take(Math.Min(coreMask.Count, orderedProcessors.Count))
|
||||
.Where((_, index) => coreMask[index])
|
||||
.ToList();
|
||||
var reviewRequired = coreMask.Count != orderedProcessors.Count;
|
||||
var selection = CpuSelection.FromProcessors(
|
||||
selectedProcessors,
|
||||
topology,
|
||||
"Migrated from legacy core mask");
|
||||
|
||||
return new CpuSelectionMigrationResult(
|
||||
selection,
|
||||
new CpuSelectionMigrationMetadata
|
||||
{
|
||||
CreatedFromLegacyCoreMask = true,
|
||||
ReviewRequired = reviewRequired,
|
||||
MigrationConfidence = reviewRequired ? "Medium" : "High",
|
||||
Reason = reviewRequired
|
||||
? "Migrated from a legacy core mask whose length differs from the current topology."
|
||||
: "Migrated from a legacy core mask.",
|
||||
TopologySignature = topology.Signature,
|
||||
});
|
||||
}
|
||||
|
||||
public long? BuildLegacyAffinityMaskIfRepresentable(CpuSelection selection) =>
|
||||
CpuSelection.ToLegacyAffinityMaskOrNull(selection);
|
||||
|
||||
public bool ShouldRequireReview(
|
||||
CpuSelection selection,
|
||||
CpuTopologySignature? savedSignature,
|
||||
CpuTopologySnapshot currentTopology)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(selection);
|
||||
ArgumentNullException.ThrowIfNull(currentTopology);
|
||||
|
||||
if (savedSignature == null || savedSignature != currentTopology.Signature)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
var currentProcessors = currentTopology.LogicalProcessors.ToHashSet();
|
||||
return selection.LogicalProcessors.Any(processor => !currentProcessors.Contains(processor));
|
||||
}
|
||||
|
||||
public ProcessProfileSnapshot MigrateProcessProfile(
|
||||
ProcessProfileSnapshot profile,
|
||||
CpuTopologySnapshot topology)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(profile);
|
||||
ArgumentNullException.ThrowIfNull(topology);
|
||||
|
||||
if (profile.CpuSelection != null)
|
||||
{
|
||||
profile.ProfileSchemaVersion = CpuAffinityProfileSchemaVersions.CpuSelection;
|
||||
profile.CpuSelectionMigration ??= new CpuSelectionMigrationMetadata
|
||||
{
|
||||
ReviewRequired = this.ShouldRequireReview(
|
||||
profile.CpuSelection,
|
||||
profile.CpuSelection.Metadata.TopologySignature,
|
||||
topology),
|
||||
MigrationConfidence = "High",
|
||||
Reason = "Profile already contains a CpuSelection.",
|
||||
TopologySignature = profile.CpuSelection.Metadata.TopologySignature,
|
||||
SourceLegacyAffinityMask = profile.ProcessorAffinity,
|
||||
};
|
||||
return profile;
|
||||
}
|
||||
|
||||
var migrated = this.MigrateFromLegacyAffinityMask(profile.ProcessorAffinity, topology);
|
||||
profile.ProfileSchemaVersion = CpuAffinityProfileSchemaVersions.CpuSelection;
|
||||
profile.CpuSelection = migrated.Selection;
|
||||
profile.CpuSelectionMigration = migrated.Metadata;
|
||||
return profile;
|
||||
}
|
||||
|
||||
public ProcessProfileSnapshot PrepareProcessProfileForSave(
|
||||
ProcessProfileSnapshot profile,
|
||||
CpuTopologySnapshot topology)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(profile);
|
||||
ArgumentNullException.ThrowIfNull(topology);
|
||||
|
||||
if (profile.CpuSelection == null)
|
||||
{
|
||||
this.MigrateProcessProfile(profile, topology);
|
||||
}
|
||||
|
||||
profile.ProfileSchemaVersion = CpuAffinityProfileSchemaVersions.CpuSelection;
|
||||
if (profile.CpuSelection != null)
|
||||
{
|
||||
var legacyMask = this.BuildLegacyAffinityMaskIfRepresentable(profile.CpuSelection);
|
||||
if (legacyMask.HasValue)
|
||||
{
|
||||
profile.ProcessorAffinity = legacyMask.Value;
|
||||
}
|
||||
}
|
||||
|
||||
profile.CpuSelectionMigration ??= new CpuSelectionMigrationMetadata
|
||||
{
|
||||
MigrationConfidence = "High",
|
||||
Reason = "Saved with CpuSelection profile schema.",
|
||||
TopologySignature = topology.Signature,
|
||||
SourceLegacyAffinityMask = profile.ProcessorAffinity,
|
||||
};
|
||||
|
||||
return profile;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+836
-871
File diff suppressed because it is too large
Load Diff
+414
-433
@@ -1,433 +1,414 @@
|
||||
/*
|
||||
* ThreadPilot - Advanced Windows Process and Power Plan Manager
|
||||
* Copyright (C) 2025 Prime Build
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published by
|
||||
* the Free Software Foundation, version 3 only.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
namespace ThreadPilot.Services
|
||||
{
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
using System.Reflection;
|
||||
using System.Security;
|
||||
using System.Security.Principal;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using ThreadPilot.Services.Abstractions;
|
||||
|
||||
/// <summary>
|
||||
/// Manages Scheduled Tasks used for persistent elevated launch and elevated autostart.
|
||||
/// </summary>
|
||||
public partial class ElevatedTaskService : IElevatedTaskService
|
||||
{
|
||||
private static readonly string SchTasksExecutablePath = Path.Combine(Environment.SystemDirectory, "schtasks.exe");
|
||||
private static readonly TimeSpan ScheduledTaskTimeout = TimeSpan.FromSeconds(20);
|
||||
|
||||
private readonly ILogger<ElevatedTaskService> logger;
|
||||
private readonly IProcessRunner processRunner;
|
||||
private readonly Func<string?>? executablePathProvider;
|
||||
private readonly Func<string>? currentUserProvider;
|
||||
|
||||
public ElevatedTaskService(ILogger<ElevatedTaskService> logger, IProcessRunner processRunner)
|
||||
: this(logger, processRunner, null, null)
|
||||
{
|
||||
}
|
||||
|
||||
public ElevatedTaskService(
|
||||
ILogger<ElevatedTaskService> logger,
|
||||
IProcessRunner processRunner,
|
||||
Func<string?>? executablePathProvider,
|
||||
Func<string>? currentUserProvider)
|
||||
{
|
||||
this.logger = logger ?? throw new ArgumentNullException(nameof(logger));
|
||||
this.processRunner = processRunner ?? throw new ArgumentNullException(nameof(processRunner));
|
||||
this.executablePathProvider = executablePathProvider;
|
||||
this.currentUserProvider = currentUserProvider;
|
||||
}
|
||||
|
||||
public string LaunchTaskName => "ThreadPilot_Launch";
|
||||
|
||||
public string AutostartTaskName => "ThreadPilot_Startup";
|
||||
|
||||
public async Task<bool> EnsureLaunchTaskAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
var executablePath = this.executablePathProvider?.Invoke() ?? this.GetExecutablePath();
|
||||
if (!IsValidExecutablePath(executablePath))
|
||||
{
|
||||
LogSkipEnsureLaunchTaskInvalidPath(this.logger, executablePath ?? "(null)");
|
||||
return false;
|
||||
}
|
||||
|
||||
var taskXmlPath = Path.Combine(Path.GetTempPath(), $"threadpilot-launch-task-{Guid.NewGuid():N}.xml");
|
||||
try
|
||||
{
|
||||
WriteLaunchTaskDefinition(
|
||||
taskXmlPath,
|
||||
executablePath!,
|
||||
this.currentUserProvider?.Invoke() ?? GetCurrentUserName());
|
||||
|
||||
var result = await this.RunSchTasksAsync(new List<string>
|
||||
{
|
||||
"/Create",
|
||||
"/TN", this.LaunchTaskName,
|
||||
"/XML", taskXmlPath,
|
||||
"/F",
|
||||
});
|
||||
|
||||
if (result.ExitCode == 0)
|
||||
{
|
||||
LogLaunchTaskEnsured(this.logger, this.LaunchTaskName, executablePath!);
|
||||
return true;
|
||||
}
|
||||
|
||||
LogEnsureLaunchTaskFailed(this.logger, result.ExitCode, result.StandardError);
|
||||
return false;
|
||||
}
|
||||
finally
|
||||
{
|
||||
TryDeleteFile(taskXmlPath, this.logger);
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
LogEnsureLaunchTaskException(this.logger, ex);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<bool> TryRunLaunchTaskAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
var result = await this.RunSchTasksAsync(new List<string>
|
||||
{
|
||||
"/Run",
|
||||
"/TN", this.LaunchTaskName,
|
||||
});
|
||||
|
||||
if (result.ExitCode == 0)
|
||||
{
|
||||
LogLaunchTaskStarted(this.logger, this.LaunchTaskName);
|
||||
return true;
|
||||
}
|
||||
|
||||
LogRunLaunchTaskFailed(this.logger, result.ExitCode, result.StandardError);
|
||||
return false;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
LogRunLaunchTaskException(this.logger, ex);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<bool> EnsureAutostartTaskAsync(string executablePath, string arguments)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (!IsValidExecutablePath(executablePath))
|
||||
{
|
||||
LogSkipEnsureAutostartTaskInvalidPath(this.logger, executablePath);
|
||||
return false;
|
||||
}
|
||||
|
||||
var taskRunCommand = BuildCommand(executablePath, arguments);
|
||||
var result = await this.RunSchTasksAsync(new List<string>
|
||||
{
|
||||
"/Create",
|
||||
"/TN", this.AutostartTaskName,
|
||||
"/TR", taskRunCommand,
|
||||
"/SC", "ONLOGON",
|
||||
"/RL", "HIGHEST",
|
||||
"/F",
|
||||
"/RU", Environment.UserName,
|
||||
});
|
||||
|
||||
if (result.ExitCode == 0)
|
||||
{
|
||||
LogAutostartTaskEnsured(this.logger, this.AutostartTaskName);
|
||||
return true;
|
||||
}
|
||||
|
||||
LogEnsureAutostartTaskFailed(this.logger, result.ExitCode, result.StandardError);
|
||||
return false;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
LogEnsureAutostartTaskException(this.logger, ex);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<bool> RemoveAutostartTaskAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
var result = await this.RunSchTasksAsync(new List<string>
|
||||
{
|
||||
"/Delete",
|
||||
"/TN", this.AutostartTaskName,
|
||||
"/F",
|
||||
});
|
||||
|
||||
if (result.ExitCode == 0)
|
||||
{
|
||||
LogAutostartTaskRemoved(this.logger, this.AutostartTaskName);
|
||||
return true;
|
||||
}
|
||||
|
||||
// Exit code 1 is expected when task doesn't exist; treat as already removed.
|
||||
if (result.ExitCode == 1)
|
||||
{
|
||||
LogAutostartTaskAlreadyRemoved(this.logger, this.AutostartTaskName);
|
||||
return true;
|
||||
}
|
||||
|
||||
LogRemoveAutostartTaskFailed(this.logger, result.ExitCode, result.StandardError);
|
||||
return false;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
LogRemoveAutostartTaskException(this.logger, ex);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<bool> IsAutostartTaskRegisteredAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
var result = await this.RunSchTasksAsync(new List<string>
|
||||
{
|
||||
"/Query",
|
||||
"/TN", this.AutostartTaskName,
|
||||
});
|
||||
|
||||
var exists = result.ExitCode == 0;
|
||||
LogAutostartTaskQueryResult(this.logger, this.AutostartTaskName, exists, result.ExitCode);
|
||||
return exists;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
LogAutostartTaskQueryException(this.logger, ex);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private string? GetExecutablePath()
|
||||
{
|
||||
try
|
||||
{
|
||||
var currentPath = Process.GetCurrentProcess().MainModule?.FileName;
|
||||
if (IsValidExecutablePath(currentPath))
|
||||
{
|
||||
return currentPath;
|
||||
}
|
||||
|
||||
var assemblyLocation = Assembly.GetExecutingAssembly().Location;
|
||||
if (!string.IsNullOrWhiteSpace(assemblyLocation) &&
|
||||
assemblyLocation.EndsWith(".dll", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
var candidatePath = Path.ChangeExtension(assemblyLocation, ".exe");
|
||||
if (IsValidExecutablePath(candidatePath))
|
||||
{
|
||||
return candidatePath;
|
||||
}
|
||||
}
|
||||
|
||||
return IsValidExecutablePath(assemblyLocation)
|
||||
? assemblyLocation
|
||||
: null;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
LogGetExecutablePathFailed(this.logger, ex);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static string BuildCommand(string executablePath, string arguments)
|
||||
{
|
||||
var trimmedArguments = arguments?.Trim();
|
||||
return string.IsNullOrWhiteSpace(trimmedArguments)
|
||||
? $"\"{executablePath}\""
|
||||
: $"\"{executablePath}\" {trimmedArguments}";
|
||||
}
|
||||
|
||||
private static bool IsValidExecutablePath(string? executablePath)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(executablePath) || !Path.IsPathRooted(executablePath))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
return File.Exists(executablePath) &&
|
||||
string.Equals(Path.GetExtension(executablePath), ".exe", StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
private static string GetCurrentUserName()
|
||||
{
|
||||
var userName = WindowsIdentity.GetCurrent().Name;
|
||||
if (string.IsNullOrWhiteSpace(userName))
|
||||
{
|
||||
throw new InvalidOperationException("Could not determine current user identity for launch task registration.");
|
||||
}
|
||||
|
||||
return userName;
|
||||
}
|
||||
|
||||
private static void WriteLaunchTaskDefinition(string taskXmlPath, string executablePath, string userName)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(userName))
|
||||
{
|
||||
throw new InvalidOperationException("Could not determine current user identity for launch task registration.");
|
||||
}
|
||||
|
||||
var workingDirectory = Path.GetDirectoryName(executablePath);
|
||||
if (string.IsNullOrWhiteSpace(workingDirectory))
|
||||
{
|
||||
throw new InvalidOperationException("Could not determine working directory for launch task registration.");
|
||||
}
|
||||
|
||||
var escapedUserName = SecurityElement.Escape(userName);
|
||||
var escapedExecutablePath = SecurityElement.Escape(executablePath);
|
||||
var escapedArguments = SecurityElement.Escape("--launched-via-task");
|
||||
var escapedWorkingDirectory = SecurityElement.Escape(workingDirectory);
|
||||
|
||||
var taskXml = $@"<?xml version=""1.0"" encoding=""UTF-16""?>
|
||||
<Task version=""1.4"" xmlns=""http://schemas.microsoft.com/windows/2004/02/mit/task"">
|
||||
<RegistrationInfo>
|
||||
<Author>ThreadPilot</Author>
|
||||
<Description>Launches ThreadPilot with highest available privileges on demand.</Description>
|
||||
</RegistrationInfo>
|
||||
<Principals>
|
||||
<Principal id=""Author"">
|
||||
<UserId>{escapedUserName}</UserId>
|
||||
<LogonType>InteractiveToken</LogonType>
|
||||
<RunLevel>HighestAvailable</RunLevel>
|
||||
</Principal>
|
||||
</Principals>
|
||||
<Settings>
|
||||
<MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>
|
||||
<DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries>
|
||||
<StopIfGoingOnBatteries>false</StopIfGoingOnBatteries>
|
||||
<AllowHardTerminate>false</AllowHardTerminate>
|
||||
<StartWhenAvailable>false</StartWhenAvailable>
|
||||
<RunOnlyIfNetworkAvailable>false</RunOnlyIfNetworkAvailable>
|
||||
<IdleSettings>
|
||||
<StopOnIdleEnd>false</StopOnIdleEnd>
|
||||
<RestartOnIdle>false</RestartOnIdle>
|
||||
</IdleSettings>
|
||||
<AllowStartOnDemand>true</AllowStartOnDemand>
|
||||
<Enabled>true</Enabled>
|
||||
<Hidden>false</Hidden>
|
||||
<RunOnlyIfIdle>false</RunOnlyIfIdle>
|
||||
<WakeToRun>false</WakeToRun>
|
||||
<ExecutionTimeLimit>PT0S</ExecutionTimeLimit>
|
||||
<Priority>7</Priority>
|
||||
</Settings>
|
||||
<Actions Context=""Author"">
|
||||
<Exec>
|
||||
<Command>{escapedExecutablePath}</Command>
|
||||
<Arguments>{escapedArguments}</Arguments>
|
||||
<WorkingDirectory>{escapedWorkingDirectory}</WorkingDirectory>
|
||||
</Exec>
|
||||
</Actions>
|
||||
</Task>";
|
||||
|
||||
File.WriteAllText(taskXmlPath, taskXml, Encoding.Unicode);
|
||||
}
|
||||
|
||||
private Task<ProcessRunResult> RunSchTasksAsync(IReadOnlyList<string> arguments)
|
||||
{
|
||||
return this.processRunner.RunAsync(SchTasksExecutablePath, arguments, ScheduledTaskTimeout);
|
||||
}
|
||||
|
||||
private static void TryDeleteFile(string path, ILogger logger)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (File.Exists(path))
|
||||
{
|
||||
File.Delete(path);
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
LogDeleteTemporaryFileFailed(logger, path, ex);
|
||||
}
|
||||
}
|
||||
|
||||
[LoggerMessage(EventId = 4250, Level = LogLevel.Warning, Message = "Skipping launch task registration due to invalid executable path: {Path}")]
|
||||
private static partial void LogSkipEnsureLaunchTaskInvalidPath(ILogger logger, string path);
|
||||
|
||||
[LoggerMessage(EventId = 4251, Level = LogLevel.Information, Message = "Ensured elevated launch task '{TaskName}' for executable '{ExecutablePath}'")]
|
||||
private static partial void LogLaunchTaskEnsured(ILogger logger, string taskName, string executablePath);
|
||||
|
||||
[LoggerMessage(EventId = 4252, Level = LogLevel.Warning, Message = "Failed to ensure elevated launch task. Exit code: {ExitCode}, Error: {Error}")]
|
||||
private static partial void LogEnsureLaunchTaskFailed(ILogger logger, int exitCode, string error);
|
||||
|
||||
[LoggerMessage(EventId = 4253, Level = LogLevel.Warning, Message = "Exception while ensuring elevated launch task")]
|
||||
private static partial void LogEnsureLaunchTaskException(ILogger logger, Exception ex);
|
||||
|
||||
[LoggerMessage(EventId = 4254, Level = LogLevel.Information, Message = "Started elevated launch task '{TaskName}'")]
|
||||
private static partial void LogLaunchTaskStarted(ILogger logger, string taskName);
|
||||
|
||||
[LoggerMessage(EventId = 4255, Level = LogLevel.Warning, Message = "Failed to run elevated launch task. Exit code: {ExitCode}, Error: {Error}")]
|
||||
private static partial void LogRunLaunchTaskFailed(ILogger logger, int exitCode, string error);
|
||||
|
||||
[LoggerMessage(EventId = 4256, Level = LogLevel.Warning, Message = "Exception while running elevated launch task")]
|
||||
private static partial void LogRunLaunchTaskException(ILogger logger, Exception ex);
|
||||
|
||||
[LoggerMessage(EventId = 4257, Level = LogLevel.Warning, Message = "Skipping autostart task registration due to invalid executable path: {Path}")]
|
||||
private static partial void LogSkipEnsureAutostartTaskInvalidPath(ILogger logger, string path);
|
||||
|
||||
[LoggerMessage(EventId = 4258, Level = LogLevel.Information, Message = "Ensured elevated autostart task '{TaskName}'")]
|
||||
private static partial void LogAutostartTaskEnsured(ILogger logger, string taskName);
|
||||
|
||||
[LoggerMessage(EventId = 4259, Level = LogLevel.Warning, Message = "Failed to ensure elevated autostart task. Exit code: {ExitCode}, Error: {Error}")]
|
||||
private static partial void LogEnsureAutostartTaskFailed(ILogger logger, int exitCode, string error);
|
||||
|
||||
[LoggerMessage(EventId = 4260, Level = LogLevel.Warning, Message = "Exception while ensuring elevated autostart task")]
|
||||
private static partial void LogEnsureAutostartTaskException(ILogger logger, Exception ex);
|
||||
|
||||
[LoggerMessage(EventId = 4261, Level = LogLevel.Information, Message = "Removed elevated autostart task '{TaskName}'")]
|
||||
private static partial void LogAutostartTaskRemoved(ILogger logger, string taskName);
|
||||
|
||||
[LoggerMessage(EventId = 4262, Level = LogLevel.Debug, Message = "Elevated autostart task '{TaskName}' was already absent")]
|
||||
private static partial void LogAutostartTaskAlreadyRemoved(ILogger logger, string taskName);
|
||||
|
||||
[LoggerMessage(EventId = 4263, Level = LogLevel.Warning, Message = "Failed to remove elevated autostart task. Exit code: {ExitCode}, Error: {Error}")]
|
||||
private static partial void LogRemoveAutostartTaskFailed(ILogger logger, int exitCode, string error);
|
||||
|
||||
[LoggerMessage(EventId = 4264, Level = LogLevel.Warning, Message = "Exception while removing elevated autostart task")]
|
||||
private static partial void LogRemoveAutostartTaskException(ILogger logger, Exception ex);
|
||||
|
||||
[LoggerMessage(EventId = 4265, Level = LogLevel.Debug, Message = "Autostart task query for '{TaskName}': Exists={Exists}, ExitCode={ExitCode}")]
|
||||
private static partial void LogAutostartTaskQueryResult(ILogger logger, string taskName, bool exists, int exitCode);
|
||||
|
||||
[LoggerMessage(EventId = 4266, Level = LogLevel.Warning, Message = "Exception while querying elevated autostart task")]
|
||||
private static partial void LogAutostartTaskQueryException(ILogger logger, Exception ex);
|
||||
|
||||
[LoggerMessage(EventId = 4267, Level = LogLevel.Warning, Message = "Failed to resolve executable path while ensuring elevated tasks")]
|
||||
private static partial void LogGetExecutablePathFailed(ILogger logger, Exception ex);
|
||||
|
||||
[LoggerMessage(EventId = 4268, Level = LogLevel.Debug, Message = "Failed to delete temporary file '{Path}'")]
|
||||
private static partial void LogDeleteTemporaryFileFailed(ILogger logger, string path, Exception ex);
|
||||
}
|
||||
}
|
||||
namespace ThreadPilot.Services
|
||||
{
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
using System.Reflection;
|
||||
using System.Security;
|
||||
using System.Security.Principal;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using ThreadPilot.Services.Abstractions;
|
||||
|
||||
public partial class ElevatedTaskService : IElevatedTaskService
|
||||
{
|
||||
private static readonly string SchTasksExecutablePath = Path.Combine(Environment.SystemDirectory, "schtasks.exe");
|
||||
private static readonly TimeSpan ScheduledTaskTimeout = TimeSpan.FromSeconds(20);
|
||||
|
||||
private readonly ILogger<ElevatedTaskService> logger;
|
||||
private readonly IProcessRunner processRunner;
|
||||
private readonly Func<string?>? executablePathProvider;
|
||||
private readonly Func<string>? currentUserProvider;
|
||||
|
||||
public ElevatedTaskService(ILogger<ElevatedTaskService> logger, IProcessRunner processRunner)
|
||||
: this(logger, processRunner, null, null)
|
||||
{
|
||||
}
|
||||
|
||||
public ElevatedTaskService(
|
||||
ILogger<ElevatedTaskService> logger,
|
||||
IProcessRunner processRunner,
|
||||
Func<string?>? executablePathProvider,
|
||||
Func<string>? currentUserProvider)
|
||||
{
|
||||
this.logger = logger ?? throw new ArgumentNullException(nameof(logger));
|
||||
this.processRunner = processRunner ?? throw new ArgumentNullException(nameof(processRunner));
|
||||
this.executablePathProvider = executablePathProvider;
|
||||
this.currentUserProvider = currentUserProvider;
|
||||
}
|
||||
|
||||
public string LaunchTaskName => "ThreadPilot_Launch";
|
||||
|
||||
public string AutostartTaskName => "ThreadPilot_Startup";
|
||||
|
||||
public async Task<bool> EnsureLaunchTaskAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
var executablePath = this.executablePathProvider?.Invoke() ?? this.GetExecutablePath();
|
||||
if (!IsValidExecutablePath(executablePath))
|
||||
{
|
||||
LogSkipEnsureLaunchTaskInvalidPath(this.logger, executablePath ?? "(null)");
|
||||
return false;
|
||||
}
|
||||
|
||||
var taskXmlPath = Path.Combine(Path.GetTempPath(), $"threadpilot-launch-task-{Guid.NewGuid():N}.xml");
|
||||
try
|
||||
{
|
||||
WriteLaunchTaskDefinition(
|
||||
taskXmlPath,
|
||||
executablePath!,
|
||||
this.currentUserProvider?.Invoke() ?? GetCurrentUserName());
|
||||
|
||||
var result = await this.RunSchTasksAsync(new List<string>
|
||||
{
|
||||
"/Create",
|
||||
"/TN", this.LaunchTaskName,
|
||||
"/XML", taskXmlPath,
|
||||
"/F",
|
||||
});
|
||||
|
||||
if (result.ExitCode == 0)
|
||||
{
|
||||
LogLaunchTaskEnsured(this.logger, this.LaunchTaskName, executablePath!);
|
||||
return true;
|
||||
}
|
||||
|
||||
LogEnsureLaunchTaskFailed(this.logger, result.ExitCode, result.StandardError);
|
||||
return false;
|
||||
}
|
||||
finally
|
||||
{
|
||||
TryDeleteFile(taskXmlPath, this.logger);
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
LogEnsureLaunchTaskException(this.logger, ex);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<bool> TryRunLaunchTaskAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
var result = await this.RunSchTasksAsync(new List<string>
|
||||
{
|
||||
"/Run",
|
||||
"/TN", this.LaunchTaskName,
|
||||
});
|
||||
|
||||
if (result.ExitCode == 0)
|
||||
{
|
||||
LogLaunchTaskStarted(this.logger, this.LaunchTaskName);
|
||||
return true;
|
||||
}
|
||||
|
||||
LogRunLaunchTaskFailed(this.logger, result.ExitCode, result.StandardError);
|
||||
return false;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
LogRunLaunchTaskException(this.logger, ex);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<bool> EnsureAutostartTaskAsync(string executablePath, string arguments)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (!IsValidExecutablePath(executablePath))
|
||||
{
|
||||
LogSkipEnsureAutostartTaskInvalidPath(this.logger, executablePath);
|
||||
return false;
|
||||
}
|
||||
|
||||
var taskRunCommand = BuildCommand(executablePath, arguments);
|
||||
var result = await this.RunSchTasksAsync(new List<string>
|
||||
{
|
||||
"/Create",
|
||||
"/TN", this.AutostartTaskName,
|
||||
"/TR", taskRunCommand,
|
||||
"/SC", "ONLOGON",
|
||||
"/RL", "HIGHEST",
|
||||
"/F",
|
||||
"/RU", Environment.UserName,
|
||||
});
|
||||
|
||||
if (result.ExitCode == 0)
|
||||
{
|
||||
LogAutostartTaskEnsured(this.logger, this.AutostartTaskName);
|
||||
return true;
|
||||
}
|
||||
|
||||
LogEnsureAutostartTaskFailed(this.logger, result.ExitCode, result.StandardError);
|
||||
return false;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
LogEnsureAutostartTaskException(this.logger, ex);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<bool> RemoveAutostartTaskAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
var result = await this.RunSchTasksAsync(new List<string>
|
||||
{
|
||||
"/Delete",
|
||||
"/TN", this.AutostartTaskName,
|
||||
"/F",
|
||||
});
|
||||
|
||||
if (result.ExitCode == 0)
|
||||
{
|
||||
LogAutostartTaskRemoved(this.logger, this.AutostartTaskName);
|
||||
return true;
|
||||
}
|
||||
|
||||
// Exit code 1 is expected when task doesn't exist; treat as already removed.
|
||||
if (result.ExitCode == 1)
|
||||
{
|
||||
LogAutostartTaskAlreadyRemoved(this.logger, this.AutostartTaskName);
|
||||
return true;
|
||||
}
|
||||
|
||||
LogRemoveAutostartTaskFailed(this.logger, result.ExitCode, result.StandardError);
|
||||
return false;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
LogRemoveAutostartTaskException(this.logger, ex);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<bool> IsAutostartTaskRegisteredAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
var result = await this.RunSchTasksAsync(new List<string>
|
||||
{
|
||||
"/Query",
|
||||
"/TN", this.AutostartTaskName,
|
||||
});
|
||||
|
||||
var exists = result.ExitCode == 0;
|
||||
LogAutostartTaskQueryResult(this.logger, this.AutostartTaskName, exists, result.ExitCode);
|
||||
return exists;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
LogAutostartTaskQueryException(this.logger, ex);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private string? GetExecutablePath()
|
||||
{
|
||||
try
|
||||
{
|
||||
var currentPath = Process.GetCurrentProcess().MainModule?.FileName;
|
||||
if (IsValidExecutablePath(currentPath))
|
||||
{
|
||||
return currentPath;
|
||||
}
|
||||
|
||||
var assemblyLocation = Assembly.GetExecutingAssembly().Location;
|
||||
if (!string.IsNullOrWhiteSpace(assemblyLocation) &&
|
||||
assemblyLocation.EndsWith(".dll", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
var candidatePath = Path.ChangeExtension(assemblyLocation, ".exe");
|
||||
if (IsValidExecutablePath(candidatePath))
|
||||
{
|
||||
return candidatePath;
|
||||
}
|
||||
}
|
||||
|
||||
return IsValidExecutablePath(assemblyLocation)
|
||||
? assemblyLocation
|
||||
: null;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
LogGetExecutablePathFailed(this.logger, ex);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static string BuildCommand(string executablePath, string arguments)
|
||||
{
|
||||
var trimmedArguments = arguments?.Trim();
|
||||
return string.IsNullOrWhiteSpace(trimmedArguments)
|
||||
? $"\"{executablePath}\""
|
||||
: $"\"{executablePath}\" {trimmedArguments}";
|
||||
}
|
||||
|
||||
private static bool IsValidExecutablePath(string? executablePath)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(executablePath) || !Path.IsPathRooted(executablePath))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
return File.Exists(executablePath) &&
|
||||
string.Equals(Path.GetExtension(executablePath), ".exe", StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
private static string GetCurrentUserName()
|
||||
{
|
||||
var userName = WindowsIdentity.GetCurrent().Name;
|
||||
if (string.IsNullOrWhiteSpace(userName))
|
||||
{
|
||||
throw new InvalidOperationException("Could not determine current user identity for launch task registration.");
|
||||
}
|
||||
|
||||
return userName;
|
||||
}
|
||||
|
||||
private static void WriteLaunchTaskDefinition(string taskXmlPath, string executablePath, string userName)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(userName))
|
||||
{
|
||||
throw new InvalidOperationException("Could not determine current user identity for launch task registration.");
|
||||
}
|
||||
|
||||
var workingDirectory = Path.GetDirectoryName(executablePath);
|
||||
if (string.IsNullOrWhiteSpace(workingDirectory))
|
||||
{
|
||||
throw new InvalidOperationException("Could not determine working directory for launch task registration.");
|
||||
}
|
||||
|
||||
var escapedUserName = SecurityElement.Escape(userName);
|
||||
var escapedExecutablePath = SecurityElement.Escape(executablePath);
|
||||
var escapedArguments = SecurityElement.Escape("--launched-via-task");
|
||||
var escapedWorkingDirectory = SecurityElement.Escape(workingDirectory);
|
||||
|
||||
var taskXml = $@"<?xml version=""1.0"" encoding=""UTF-16""?>
|
||||
<Task version=""1.4"" xmlns=""http://schemas.microsoft.com/windows/2004/02/mit/task"">
|
||||
<RegistrationInfo>
|
||||
<Author>ThreadPilot</Author>
|
||||
<Description>Launches ThreadPilot with highest available privileges on demand.</Description>
|
||||
</RegistrationInfo>
|
||||
<Principals>
|
||||
<Principal id=""Author"">
|
||||
<UserId>{escapedUserName}</UserId>
|
||||
<LogonType>InteractiveToken</LogonType>
|
||||
<RunLevel>HighestAvailable</RunLevel>
|
||||
</Principal>
|
||||
</Principals>
|
||||
<Settings>
|
||||
<MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>
|
||||
<DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries>
|
||||
<StopIfGoingOnBatteries>false</StopIfGoingOnBatteries>
|
||||
<AllowHardTerminate>false</AllowHardTerminate>
|
||||
<StartWhenAvailable>false</StartWhenAvailable>
|
||||
<RunOnlyIfNetworkAvailable>false</RunOnlyIfNetworkAvailable>
|
||||
<IdleSettings>
|
||||
<StopOnIdleEnd>false</StopOnIdleEnd>
|
||||
<RestartOnIdle>false</RestartOnIdle>
|
||||
</IdleSettings>
|
||||
<AllowStartOnDemand>true</AllowStartOnDemand>
|
||||
<Enabled>true</Enabled>
|
||||
<Hidden>false</Hidden>
|
||||
<RunOnlyIfIdle>false</RunOnlyIfIdle>
|
||||
<WakeToRun>false</WakeToRun>
|
||||
<ExecutionTimeLimit>PT0S</ExecutionTimeLimit>
|
||||
<Priority>7</Priority>
|
||||
</Settings>
|
||||
<Actions Context=""Author"">
|
||||
<Exec>
|
||||
<Command>{escapedExecutablePath}</Command>
|
||||
<Arguments>{escapedArguments}</Arguments>
|
||||
<WorkingDirectory>{escapedWorkingDirectory}</WorkingDirectory>
|
||||
</Exec>
|
||||
</Actions>
|
||||
</Task>";
|
||||
|
||||
File.WriteAllText(taskXmlPath, taskXml, Encoding.Unicode);
|
||||
}
|
||||
|
||||
private Task<ProcessRunResult> RunSchTasksAsync(IReadOnlyList<string> arguments)
|
||||
{
|
||||
return this.processRunner.RunAsync(SchTasksExecutablePath, arguments, ScheduledTaskTimeout);
|
||||
}
|
||||
|
||||
private static void TryDeleteFile(string path, ILogger logger)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (File.Exists(path))
|
||||
{
|
||||
File.Delete(path);
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
LogDeleteTemporaryFileFailed(logger, path, ex);
|
||||
}
|
||||
}
|
||||
|
||||
[LoggerMessage(EventId = 4250, Level = LogLevel.Warning, Message = "Skipping launch task registration due to invalid executable path: {Path}")]
|
||||
private static partial void LogSkipEnsureLaunchTaskInvalidPath(ILogger logger, string path);
|
||||
|
||||
[LoggerMessage(EventId = 4251, Level = LogLevel.Information, Message = "Ensured elevated launch task '{TaskName}' for executable '{ExecutablePath}'")]
|
||||
private static partial void LogLaunchTaskEnsured(ILogger logger, string taskName, string executablePath);
|
||||
|
||||
[LoggerMessage(EventId = 4252, Level = LogLevel.Warning, Message = "Failed to ensure elevated launch task. Exit code: {ExitCode}, Error: {Error}")]
|
||||
private static partial void LogEnsureLaunchTaskFailed(ILogger logger, int exitCode, string error);
|
||||
|
||||
[LoggerMessage(EventId = 4253, Level = LogLevel.Warning, Message = "Exception while ensuring elevated launch task")]
|
||||
private static partial void LogEnsureLaunchTaskException(ILogger logger, Exception ex);
|
||||
|
||||
[LoggerMessage(EventId = 4254, Level = LogLevel.Information, Message = "Started elevated launch task '{TaskName}'")]
|
||||
private static partial void LogLaunchTaskStarted(ILogger logger, string taskName);
|
||||
|
||||
[LoggerMessage(EventId = 4255, Level = LogLevel.Warning, Message = "Failed to run elevated launch task. Exit code: {ExitCode}, Error: {Error}")]
|
||||
private static partial void LogRunLaunchTaskFailed(ILogger logger, int exitCode, string error);
|
||||
|
||||
[LoggerMessage(EventId = 4256, Level = LogLevel.Warning, Message = "Exception while running elevated launch task")]
|
||||
private static partial void LogRunLaunchTaskException(ILogger logger, Exception ex);
|
||||
|
||||
[LoggerMessage(EventId = 4257, Level = LogLevel.Warning, Message = "Skipping autostart task registration due to invalid executable path: {Path}")]
|
||||
private static partial void LogSkipEnsureAutostartTaskInvalidPath(ILogger logger, string path);
|
||||
|
||||
[LoggerMessage(EventId = 4258, Level = LogLevel.Information, Message = "Ensured elevated autostart task '{TaskName}'")]
|
||||
private static partial void LogAutostartTaskEnsured(ILogger logger, string taskName);
|
||||
|
||||
[LoggerMessage(EventId = 4259, Level = LogLevel.Warning, Message = "Failed to ensure elevated autostart task. Exit code: {ExitCode}, Error: {Error}")]
|
||||
private static partial void LogEnsureAutostartTaskFailed(ILogger logger, int exitCode, string error);
|
||||
|
||||
[LoggerMessage(EventId = 4260, Level = LogLevel.Warning, Message = "Exception while ensuring elevated autostart task")]
|
||||
private static partial void LogEnsureAutostartTaskException(ILogger logger, Exception ex);
|
||||
|
||||
[LoggerMessage(EventId = 4261, Level = LogLevel.Information, Message = "Removed elevated autostart task '{TaskName}'")]
|
||||
private static partial void LogAutostartTaskRemoved(ILogger logger, string taskName);
|
||||
|
||||
[LoggerMessage(EventId = 4262, Level = LogLevel.Debug, Message = "Elevated autostart task '{TaskName}' was already absent")]
|
||||
private static partial void LogAutostartTaskAlreadyRemoved(ILogger logger, string taskName);
|
||||
|
||||
[LoggerMessage(EventId = 4263, Level = LogLevel.Warning, Message = "Failed to remove elevated autostart task. Exit code: {ExitCode}, Error: {Error}")]
|
||||
private static partial void LogRemoveAutostartTaskFailed(ILogger logger, int exitCode, string error);
|
||||
|
||||
[LoggerMessage(EventId = 4264, Level = LogLevel.Warning, Message = "Exception while removing elevated autostart task")]
|
||||
private static partial void LogRemoveAutostartTaskException(ILogger logger, Exception ex);
|
||||
|
||||
[LoggerMessage(EventId = 4265, Level = LogLevel.Debug, Message = "Autostart task query for '{TaskName}': Exists={Exists}, ExitCode={ExitCode}")]
|
||||
private static partial void LogAutostartTaskQueryResult(ILogger logger, string taskName, bool exists, int exitCode);
|
||||
|
||||
[LoggerMessage(EventId = 4266, Level = LogLevel.Warning, Message = "Exception while querying elevated autostart task")]
|
||||
private static partial void LogAutostartTaskQueryException(ILogger logger, Exception ex);
|
||||
|
||||
[LoggerMessage(EventId = 4267, Level = LogLevel.Warning, Message = "Failed to resolve executable path while ensuring elevated tasks")]
|
||||
private static partial void LogGetExecutablePathFailed(ILogger logger, Exception ex);
|
||||
|
||||
[LoggerMessage(EventId = 4268, Level = LogLevel.Debug, Message = "Failed to delete temporary file '{Path}'")]
|
||||
private static partial void LogDeleteTemporaryFileFailed(ILogger logger, string path, Exception ex);
|
||||
}
|
||||
}
|
||||
|
||||
+223
-242
@@ -1,242 +1,223 @@
|
||||
/*
|
||||
* ThreadPilot - Advanced Windows Process and Power Plan Manager
|
||||
* Copyright (C) 2025 Prime Build
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published by
|
||||
* the Free Software Foundation, version 3 only.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
namespace ThreadPilot.Services
|
||||
{
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Security.Principal;
|
||||
using System.Text;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using System.Windows;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
/// <summary>
|
||||
/// Service for managing application elevation and administrator privileges.
|
||||
/// </summary>
|
||||
public partial class ElevationService : IElevationService
|
||||
{
|
||||
private readonly ILogger<ElevationService> logger;
|
||||
private readonly ISecurityService securityService;
|
||||
private readonly SemaphoreSlim elevationRequestSemaphore = new(1, 1);
|
||||
|
||||
public ElevationService(ILogger<ElevationService> logger, ISecurityService securityService)
|
||||
{
|
||||
this.logger = logger ?? throw new ArgumentNullException(nameof(logger));
|
||||
this.securityService = securityService ?? throw new ArgumentNullException(nameof(securityService));
|
||||
}
|
||||
|
||||
public bool IsRunningAsAdministrator()
|
||||
{
|
||||
try
|
||||
{
|
||||
var identity = WindowsIdentity.GetCurrent();
|
||||
var principal = new WindowsPrincipal(identity);
|
||||
var isAdmin = principal.IsInRole(WindowsBuiltInRole.Administrator);
|
||||
|
||||
LogAdministratorPrivilegeCheck(this.logger, isAdmin);
|
||||
return isAdmin;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
LogPrivilegeCheckFailed(this.logger, ex);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<bool> RequestElevationIfNeeded()
|
||||
{
|
||||
if (this.IsRunningAsAdministrator())
|
||||
{
|
||||
LogAlreadyElevated(this.logger);
|
||||
return true;
|
||||
}
|
||||
|
||||
LogRequestingElevation(this.logger);
|
||||
|
||||
// Show elevation prompt to user
|
||||
var result = System.Windows.MessageBox.Show(
|
||||
"ThreadPilot requires administrator privileges to manage process affinity and power plans.\n\n" +
|
||||
"Would you like to restart the application with administrator privileges?",
|
||||
"Administrator Privileges Required",
|
||||
MessageBoxButton.YesNo,
|
||||
MessageBoxImage.Question);
|
||||
|
||||
if (result != MessageBoxResult.Yes)
|
||||
{
|
||||
LogUserDeclinedElevation(this.logger);
|
||||
return false;
|
||||
}
|
||||
|
||||
return await this.RestartWithElevation();
|
||||
}
|
||||
|
||||
public async Task<bool> RestartWithElevation(string[]? arguments = null)
|
||||
{
|
||||
await this.elevationRequestSemaphore.WaitAsync();
|
||||
try
|
||||
{
|
||||
var currentProcess = Process.GetCurrentProcess();
|
||||
var executablePath = currentProcess.MainModule?.FileName;
|
||||
|
||||
if (string.IsNullOrWhiteSpace(executablePath) || !Path.IsPathFullyQualified(executablePath) || !File.Exists(executablePath))
|
||||
{
|
||||
LogMissingExecutablePath(this.logger);
|
||||
return false;
|
||||
}
|
||||
|
||||
// Combine current arguments with any additional arguments
|
||||
var currentArgs = Environment.GetCommandLineArgs().Skip(1).ToArray();
|
||||
var allArgs = arguments != null ? currentArgs.Concat(arguments).ToArray() : currentArgs;
|
||||
var argumentString = string.Join(" ", allArgs.Select(EscapeCommandLineArgument));
|
||||
var workingDirectory = Path.GetDirectoryName(executablePath);
|
||||
|
||||
var startInfo = new ProcessStartInfo
|
||||
{
|
||||
FileName = executablePath,
|
||||
Arguments = argumentString,
|
||||
UseShellExecute = true,
|
||||
Verb = "runas", // This triggers UAC elevation
|
||||
WorkingDirectory = string.IsNullOrWhiteSpace(workingDirectory) ? Environment.SystemDirectory : workingDirectory,
|
||||
};
|
||||
|
||||
LogStartingElevatedProcess(this.logger, executablePath, argumentString);
|
||||
|
||||
var elevatedProcess = Process.Start(startInfo);
|
||||
if (elevatedProcess != null)
|
||||
{
|
||||
LogElevatedProcessStarted(this.logger);
|
||||
|
||||
// Audit the elevation request
|
||||
await this.securityService.AuditElevatedAction("ApplicationRestart", "Self", true);
|
||||
|
||||
// Shutdown current instance
|
||||
await Task.Delay(1000); // Give the new process time to start
|
||||
System.Windows.Application.Current.Shutdown();
|
||||
return true;
|
||||
}
|
||||
else
|
||||
{
|
||||
LogElevatedProcessStartFailed(this.logger);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
LogRestartWithElevationFailed(this.logger, ex);
|
||||
await this.securityService.AuditElevatedAction("ApplicationRestart", "Self", false);
|
||||
|
||||
// Show user-friendly error message
|
||||
System.Windows.MessageBox.Show(
|
||||
"Failed to restart with administrator privileges. Please manually run ThreadPilot as administrator.",
|
||||
"Elevation Failed",
|
||||
MessageBoxButton.OK,
|
||||
MessageBoxImage.Warning);
|
||||
|
||||
return false;
|
||||
}
|
||||
finally
|
||||
{
|
||||
this.elevationRequestSemaphore.Release();
|
||||
}
|
||||
}
|
||||
|
||||
public bool ValidateElevationForOperation(string operation)
|
||||
{
|
||||
var isElevated = this.IsRunningAsAdministrator();
|
||||
var isValidOperation = this.securityService.ValidateElevatedOperation(operation);
|
||||
|
||||
var canPerform = isElevated && isValidOperation;
|
||||
|
||||
LogElevationValidation(this.logger, operation, isElevated, isValidOperation, canPerform);
|
||||
|
||||
return canPerform;
|
||||
}
|
||||
|
||||
public string GetElevationStatus()
|
||||
{
|
||||
return this.IsRunningAsAdministrator()
|
||||
? "Running with Administrator privileges"
|
||||
: "Running with limited privileges";
|
||||
}
|
||||
|
||||
private static string EscapeCommandLineArgument(string argument)
|
||||
{
|
||||
if (string.IsNullOrEmpty(argument))
|
||||
{
|
||||
return "\"\"";
|
||||
}
|
||||
|
||||
var escaped = new StringBuilder();
|
||||
escaped.Append('"');
|
||||
|
||||
foreach (var c in argument)
|
||||
{
|
||||
if (c == '"')
|
||||
{
|
||||
escaped.Append("\\\"");
|
||||
}
|
||||
else
|
||||
{
|
||||
escaped.Append(c);
|
||||
}
|
||||
}
|
||||
|
||||
escaped.Append('"');
|
||||
return escaped.ToString();
|
||||
}
|
||||
|
||||
[LoggerMessage(EventId = 4100, Level = LogLevel.Debug, Message = "Administrator privilege check: {IsAdmin}")]
|
||||
private static partial void LogAdministratorPrivilegeCheck(ILogger logger, bool isAdmin);
|
||||
|
||||
[LoggerMessage(EventId = 4101, Level = LogLevel.Error, Message = "Failed to check administrator privileges")]
|
||||
private static partial void LogPrivilegeCheckFailed(ILogger logger, Exception ex);
|
||||
|
||||
[LoggerMessage(EventId = 4102, Level = LogLevel.Debug, Message = "Application is already running with administrator privileges")]
|
||||
private static partial void LogAlreadyElevated(ILogger logger);
|
||||
|
||||
[LoggerMessage(EventId = 4103, Level = LogLevel.Information, Message = "Requesting elevation to administrator privileges")]
|
||||
private static partial void LogRequestingElevation(ILogger logger);
|
||||
|
||||
[LoggerMessage(EventId = 4104, Level = LogLevel.Information, Message = "User declined elevation request")]
|
||||
private static partial void LogUserDeclinedElevation(ILogger logger);
|
||||
|
||||
[LoggerMessage(EventId = 4105, Level = LogLevel.Error, Message = "Could not determine executable path for elevation")]
|
||||
private static partial void LogMissingExecutablePath(ILogger logger);
|
||||
|
||||
[LoggerMessage(EventId = 4106, Level = LogLevel.Information, Message = "Starting elevated process: {FileName} {Arguments}")]
|
||||
private static partial void LogStartingElevatedProcess(ILogger logger, string fileName, string arguments);
|
||||
|
||||
[LoggerMessage(EventId = 4107, Level = LogLevel.Information, Message = "Elevated process started successfully. Shutting down current instance.")]
|
||||
private static partial void LogElevatedProcessStarted(ILogger logger);
|
||||
|
||||
[LoggerMessage(EventId = 4108, Level = LogLevel.Error, Message = "Failed to start elevated process")]
|
||||
private static partial void LogElevatedProcessStartFailed(ILogger logger);
|
||||
|
||||
[LoggerMessage(EventId = 4109, Level = LogLevel.Error, Message = "Failed to restart with elevation")]
|
||||
private static partial void LogRestartWithElevationFailed(ILogger logger, Exception ex);
|
||||
|
||||
[LoggerMessage(
|
||||
EventId = 4110,
|
||||
Level = LogLevel.Debug,
|
||||
Message = "Elevation validation for operation '{Operation}': Elevated={IsElevated}, Valid={IsValid}, CanPerform={CanPerform}")]
|
||||
private static partial void LogElevationValidation(ILogger logger, string operation, bool isElevated, bool isValid, bool canPerform);
|
||||
}
|
||||
}
|
||||
|
||||
namespace ThreadPilot.Services
|
||||
{
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Security.Principal;
|
||||
using System.Text;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using System.Windows;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
public partial class ElevationService : IElevationService
|
||||
{
|
||||
private readonly ILogger<ElevationService> logger;
|
||||
private readonly ISecurityService securityService;
|
||||
private readonly SemaphoreSlim elevationRequestSemaphore = new(1, 1);
|
||||
|
||||
public ElevationService(ILogger<ElevationService> logger, ISecurityService securityService)
|
||||
{
|
||||
this.logger = logger ?? throw new ArgumentNullException(nameof(logger));
|
||||
this.securityService = securityService ?? throw new ArgumentNullException(nameof(securityService));
|
||||
}
|
||||
|
||||
public bool IsRunningAsAdministrator()
|
||||
{
|
||||
try
|
||||
{
|
||||
var identity = WindowsIdentity.GetCurrent();
|
||||
var principal = new WindowsPrincipal(identity);
|
||||
var isAdmin = principal.IsInRole(WindowsBuiltInRole.Administrator);
|
||||
|
||||
LogAdministratorPrivilegeCheck(this.logger, isAdmin);
|
||||
return isAdmin;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
LogPrivilegeCheckFailed(this.logger, ex);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<bool> RequestElevationIfNeeded()
|
||||
{
|
||||
if (this.IsRunningAsAdministrator())
|
||||
{
|
||||
LogAlreadyElevated(this.logger);
|
||||
return true;
|
||||
}
|
||||
|
||||
LogRequestingElevation(this.logger);
|
||||
|
||||
// Show elevation prompt to user
|
||||
var result = System.Windows.MessageBox.Show(
|
||||
"ThreadPilot requires administrator privileges to manage process affinity and power plans.\n\n" +
|
||||
"Would you like to restart the application with administrator privileges?",
|
||||
"Administrator Privileges Required",
|
||||
MessageBoxButton.YesNo,
|
||||
MessageBoxImage.Question);
|
||||
|
||||
if (result != MessageBoxResult.Yes)
|
||||
{
|
||||
LogUserDeclinedElevation(this.logger);
|
||||
return false;
|
||||
}
|
||||
|
||||
return await this.RestartWithElevation();
|
||||
}
|
||||
|
||||
public async Task<bool> RestartWithElevation(string[]? arguments = null)
|
||||
{
|
||||
await this.elevationRequestSemaphore.WaitAsync();
|
||||
try
|
||||
{
|
||||
var currentProcess = Process.GetCurrentProcess();
|
||||
var executablePath = currentProcess.MainModule?.FileName;
|
||||
|
||||
if (string.IsNullOrWhiteSpace(executablePath) || !Path.IsPathFullyQualified(executablePath) || !File.Exists(executablePath))
|
||||
{
|
||||
LogMissingExecutablePath(this.logger);
|
||||
return false;
|
||||
}
|
||||
|
||||
// Combine current arguments with any additional arguments
|
||||
var currentArgs = Environment.GetCommandLineArgs().Skip(1).ToArray();
|
||||
var allArgs = arguments != null ? currentArgs.Concat(arguments).ToArray() : currentArgs;
|
||||
var argumentString = string.Join(" ", allArgs.Select(EscapeCommandLineArgument));
|
||||
var workingDirectory = Path.GetDirectoryName(executablePath);
|
||||
|
||||
var startInfo = new ProcessStartInfo
|
||||
{
|
||||
FileName = executablePath,
|
||||
Arguments = argumentString,
|
||||
UseShellExecute = true,
|
||||
Verb = "runas", // This triggers UAC elevation
|
||||
WorkingDirectory = string.IsNullOrWhiteSpace(workingDirectory) ? Environment.SystemDirectory : workingDirectory,
|
||||
};
|
||||
|
||||
LogStartingElevatedProcess(this.logger, executablePath, argumentString);
|
||||
|
||||
var elevatedProcess = Process.Start(startInfo);
|
||||
if (elevatedProcess != null)
|
||||
{
|
||||
LogElevatedProcessStarted(this.logger);
|
||||
|
||||
// Audit the elevation request
|
||||
await this.securityService.AuditElevatedAction("ApplicationRestart", "Self", true);
|
||||
|
||||
// Shutdown current instance
|
||||
await Task.Delay(1000); // Give the new process time to start
|
||||
System.Windows.Application.Current.Shutdown();
|
||||
return true;
|
||||
}
|
||||
else
|
||||
{
|
||||
LogElevatedProcessStartFailed(this.logger);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
LogRestartWithElevationFailed(this.logger, ex);
|
||||
await this.securityService.AuditElevatedAction("ApplicationRestart", "Self", false);
|
||||
|
||||
// Show user-friendly error message
|
||||
System.Windows.MessageBox.Show(
|
||||
"Failed to restart with administrator privileges. Please manually run ThreadPilot as administrator.",
|
||||
"Elevation Failed",
|
||||
MessageBoxButton.OK,
|
||||
MessageBoxImage.Warning);
|
||||
|
||||
return false;
|
||||
}
|
||||
finally
|
||||
{
|
||||
this.elevationRequestSemaphore.Release();
|
||||
}
|
||||
}
|
||||
|
||||
public bool ValidateElevationForOperation(string operation)
|
||||
{
|
||||
var isElevated = this.IsRunningAsAdministrator();
|
||||
var isValidOperation = this.securityService.ValidateElevatedOperation(operation);
|
||||
|
||||
var canPerform = isElevated && isValidOperation;
|
||||
|
||||
LogElevationValidation(this.logger, operation, isElevated, isValidOperation, canPerform);
|
||||
|
||||
return canPerform;
|
||||
}
|
||||
|
||||
public string GetElevationStatus()
|
||||
{
|
||||
return this.IsRunningAsAdministrator()
|
||||
? "Running with Administrator privileges"
|
||||
: "Running with limited privileges";
|
||||
}
|
||||
|
||||
private static string EscapeCommandLineArgument(string argument)
|
||||
{
|
||||
if (string.IsNullOrEmpty(argument))
|
||||
{
|
||||
return "\"\"";
|
||||
}
|
||||
|
||||
var escaped = new StringBuilder();
|
||||
escaped.Append('"');
|
||||
|
||||
foreach (var c in argument)
|
||||
{
|
||||
if (c == '"')
|
||||
{
|
||||
escaped.Append("\\\"");
|
||||
}
|
||||
else
|
||||
{
|
||||
escaped.Append(c);
|
||||
}
|
||||
}
|
||||
|
||||
escaped.Append('"');
|
||||
return escaped.ToString();
|
||||
}
|
||||
|
||||
[LoggerMessage(EventId = 4100, Level = LogLevel.Debug, Message = "Administrator privilege check: {IsAdmin}")]
|
||||
private static partial void LogAdministratorPrivilegeCheck(ILogger logger, bool isAdmin);
|
||||
|
||||
[LoggerMessage(EventId = 4101, Level = LogLevel.Error, Message = "Failed to check administrator privileges")]
|
||||
private static partial void LogPrivilegeCheckFailed(ILogger logger, Exception ex);
|
||||
|
||||
[LoggerMessage(EventId = 4102, Level = LogLevel.Debug, Message = "Application is already running with administrator privileges")]
|
||||
private static partial void LogAlreadyElevated(ILogger logger);
|
||||
|
||||
[LoggerMessage(EventId = 4103, Level = LogLevel.Information, Message = "Requesting elevation to administrator privileges")]
|
||||
private static partial void LogRequestingElevation(ILogger logger);
|
||||
|
||||
[LoggerMessage(EventId = 4104, Level = LogLevel.Information, Message = "User declined elevation request")]
|
||||
private static partial void LogUserDeclinedElevation(ILogger logger);
|
||||
|
||||
[LoggerMessage(EventId = 4105, Level = LogLevel.Error, Message = "Could not determine executable path for elevation")]
|
||||
private static partial void LogMissingExecutablePath(ILogger logger);
|
||||
|
||||
[LoggerMessage(EventId = 4106, Level = LogLevel.Information, Message = "Starting elevated process: {FileName} {Arguments}")]
|
||||
private static partial void LogStartingElevatedProcess(ILogger logger, string fileName, string arguments);
|
||||
|
||||
[LoggerMessage(EventId = 4107, Level = LogLevel.Information, Message = "Elevated process started successfully. Shutting down current instance.")]
|
||||
private static partial void LogElevatedProcessStarted(ILogger logger);
|
||||
|
||||
[LoggerMessage(EventId = 4108, Level = LogLevel.Error, Message = "Failed to start elevated process")]
|
||||
private static partial void LogElevatedProcessStartFailed(ILogger logger);
|
||||
|
||||
[LoggerMessage(EventId = 4109, Level = LogLevel.Error, Message = "Failed to restart with elevation")]
|
||||
private static partial void LogRestartWithElevationFailed(ILogger logger, Exception ex);
|
||||
|
||||
[LoggerMessage(
|
||||
EventId = 4110,
|
||||
Level = LogLevel.Debug,
|
||||
Message = "Elevation validation for operation '{Operation}': Elevated={IsElevated}, Valid={IsValid}, CanPerform={CanPerform}")]
|
||||
private static partial void LogElevationValidation(ILogger logger, string operation, bool isElevated, bool isValid, bool canPerform);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+556
-578
File diff suppressed because it is too large
Load Diff
@@ -1,46 +1,43 @@
|
||||
namespace ThreadPilot.Services
|
||||
{
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using ThreadPilot.Services.Abstractions;
|
||||
|
||||
/// <summary>
|
||||
/// Default filesystem-backed settings storage.
|
||||
/// </summary>
|
||||
public sealed class FileSettingsStorage : ISettingsStorage
|
||||
{
|
||||
public void Copy(string sourcePath, string destinationPath, bool overwrite)
|
||||
{
|
||||
File.Copy(sourcePath, destinationPath, overwrite);
|
||||
}
|
||||
|
||||
public void EnsureDirectoryForFile(string path)
|
||||
{
|
||||
var directory = Path.GetDirectoryName(path);
|
||||
if (!string.IsNullOrWhiteSpace(directory))
|
||||
{
|
||||
Directory.CreateDirectory(directory);
|
||||
}
|
||||
}
|
||||
|
||||
public bool Exists(string path)
|
||||
{
|
||||
return File.Exists(path);
|
||||
}
|
||||
|
||||
public async Task<string?> ReadAsync(string path)
|
||||
{
|
||||
return this.Exists(path)
|
||||
? await File.ReadAllTextAsync(path)
|
||||
: null;
|
||||
}
|
||||
|
||||
public Task WriteAsync(string path, string content)
|
||||
{
|
||||
this.EnsureDirectoryForFile(path);
|
||||
return AtomicFileWriter.WriteAllTextAsync(path, content, Encoding.UTF8);
|
||||
}
|
||||
}
|
||||
}
|
||||
namespace ThreadPilot.Services
|
||||
{
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using ThreadPilot.Services.Abstractions;
|
||||
|
||||
public sealed class FileSettingsStorage : ISettingsStorage
|
||||
{
|
||||
public void Copy(string sourcePath, string destinationPath, bool overwrite)
|
||||
{
|
||||
File.Copy(sourcePath, destinationPath, overwrite);
|
||||
}
|
||||
|
||||
public void EnsureDirectoryForFile(string path)
|
||||
{
|
||||
var directory = Path.GetDirectoryName(path);
|
||||
if (!string.IsNullOrWhiteSpace(directory))
|
||||
{
|
||||
Directory.CreateDirectory(directory);
|
||||
}
|
||||
}
|
||||
|
||||
public bool Exists(string path)
|
||||
{
|
||||
return File.Exists(path);
|
||||
}
|
||||
|
||||
public async Task<string?> ReadAsync(string path)
|
||||
{
|
||||
return this.Exists(path)
|
||||
? await File.ReadAllTextAsync(path)
|
||||
: null;
|
||||
}
|
||||
|
||||
public Task WriteAsync(string path, string content)
|
||||
{
|
||||
this.EnsureDirectoryForFile(path);
|
||||
return AtomicFileWriter.WriteAllTextAsync(path, content, Encoding.UTF8);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,74 +1,58 @@
|
||||
/*
|
||||
* ThreadPilot - Advanced Windows Process and Power Plan Manager
|
||||
* Copyright (C) 2025 Prime Build
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published by
|
||||
* the Free Software Foundation, version 3 only.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
namespace ThreadPilot.Services
|
||||
{
|
||||
using System;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
public readonly record struct ForegroundWindowSnapshot(
|
||||
IntPtr WindowHandle,
|
||||
int ProcessId,
|
||||
bool IsVisible,
|
||||
bool IsCloaked);
|
||||
|
||||
public interface IForegroundWindowProvider
|
||||
{
|
||||
bool TryGetForegroundWindow(out ForegroundWindowSnapshot snapshot);
|
||||
}
|
||||
|
||||
public interface IForegroundProcessService
|
||||
{
|
||||
int? TryGetForegroundProcessId();
|
||||
}
|
||||
|
||||
public sealed class ForegroundProcessService : IForegroundProcessService
|
||||
{
|
||||
private readonly IForegroundWindowProvider foregroundWindowProvider;
|
||||
private readonly ILogger<ForegroundProcessService> logger;
|
||||
|
||||
public ForegroundProcessService(
|
||||
IForegroundWindowProvider foregroundWindowProvider,
|
||||
ILogger<ForegroundProcessService> logger)
|
||||
{
|
||||
this.foregroundWindowProvider = foregroundWindowProvider ?? throw new ArgumentNullException(nameof(foregroundWindowProvider));
|
||||
this.logger = logger ?? throw new ArgumentNullException(nameof(logger));
|
||||
}
|
||||
|
||||
public int? TryGetForegroundProcessId()
|
||||
{
|
||||
try
|
||||
{
|
||||
if (!this.foregroundWindowProvider.TryGetForegroundWindow(out var snapshot))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
if (snapshot.ProcessId <= 0 || !snapshot.IsVisible || snapshot.IsCloaked)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
return snapshot.ProcessId;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
this.logger.LogDebug(ex, "Foreground process detection failed");
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
namespace ThreadPilot.Services
|
||||
{
|
||||
using System;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
public readonly record struct ForegroundWindowSnapshot(
|
||||
IntPtr WindowHandle,
|
||||
int ProcessId,
|
||||
bool IsVisible,
|
||||
bool IsCloaked);
|
||||
|
||||
public interface IForegroundWindowProvider
|
||||
{
|
||||
bool TryGetForegroundWindow(out ForegroundWindowSnapshot snapshot);
|
||||
}
|
||||
|
||||
public interface IForegroundProcessService
|
||||
{
|
||||
int? TryGetForegroundProcessId();
|
||||
}
|
||||
|
||||
public sealed class ForegroundProcessService : IForegroundProcessService
|
||||
{
|
||||
private readonly IForegroundWindowProvider foregroundWindowProvider;
|
||||
private readonly ILogger<ForegroundProcessService> logger;
|
||||
|
||||
public ForegroundProcessService(
|
||||
IForegroundWindowProvider foregroundWindowProvider,
|
||||
ILogger<ForegroundProcessService> logger)
|
||||
{
|
||||
this.foregroundWindowProvider = foregroundWindowProvider ?? throw new ArgumentNullException(nameof(foregroundWindowProvider));
|
||||
this.logger = logger ?? throw new ArgumentNullException(nameof(logger));
|
||||
}
|
||||
|
||||
public int? TryGetForegroundProcessId()
|
||||
{
|
||||
try
|
||||
{
|
||||
if (!this.foregroundWindowProvider.TryGetForegroundWindow(out var snapshot))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
if (snapshot.ProcessId <= 0 || !snapshot.IsVisible || snapshot.IsCloaked)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
return snapshot.ProcessId;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
this.logger.LogDebug(ex, "Foreground process detection failed");
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,646 +0,0 @@
|
||||
/*
|
||||
* ThreadPilot - Advanced Windows Process and Power Plan Manager
|
||||
* Copyright (C) 2025 Prime Build
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published by
|
||||
* the Free Software Foundation, version 3 only.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using ThreadPilot.Models;
|
||||
|
||||
namespace ThreadPilot.Services
|
||||
{
|
||||
/// <summary>
|
||||
/// Service for managing Game Boost mode functionality
|
||||
/// </summary>
|
||||
public class GameBoostService : IGameBoostService
|
||||
{
|
||||
private readonly ILogger<GameBoostService> _logger;
|
||||
private readonly IPowerPlanService _powerPlanService;
|
||||
private readonly IProcessService _processService;
|
||||
private readonly INotificationService _notificationService;
|
||||
private readonly IApplicationSettingsService _settingsService;
|
||||
|
||||
private ApplicationSettingsModel _settings;
|
||||
private bool _isGameBoostActive;
|
||||
private ProcessModel? _currentGameProcess;
|
||||
private string? _previousPowerPlanId;
|
||||
private DateTime? _gameBoostStartTime;
|
||||
private readonly List<string> _knownGameExecutables;
|
||||
|
||||
public event EventHandler<GameBoostActivatedEventArgs>? GameBoostActivated;
|
||||
public event EventHandler<GameBoostDeactivatedEventArgs>? GameBoostDeactivated;
|
||||
public event EventHandler<GameDetectedEventArgs>? GameDetected;
|
||||
|
||||
public bool IsGameBoostActive => _isGameBoostActive;
|
||||
public ProcessModel? CurrentGameProcess => _currentGameProcess;
|
||||
public IReadOnlyList<string> KnownGameExecutables => _knownGameExecutables.AsReadOnly();
|
||||
|
||||
public GameBoostService(
|
||||
ILogger<GameBoostService> logger,
|
||||
IPowerPlanService powerPlanService,
|
||||
IProcessService processService,
|
||||
INotificationService notificationService,
|
||||
IApplicationSettingsService settingsService)
|
||||
{
|
||||
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
|
||||
_powerPlanService = powerPlanService ?? throw new ArgumentNullException(nameof(powerPlanService));
|
||||
_processService = processService ?? throw new ArgumentNullException(nameof(processService));
|
||||
_notificationService = notificationService ?? throw new ArgumentNullException(nameof(notificationService));
|
||||
_settingsService = settingsService ?? throw new ArgumentNullException(nameof(settingsService));
|
||||
|
||||
_settings = _settingsService.Settings;
|
||||
_knownGameExecutables = InitializeKnownGames();
|
||||
|
||||
// Subscribe to settings changes
|
||||
_settingsService.SettingsChanged += OnSettingsChanged;
|
||||
|
||||
_logger.LogInformation("Game Boost service initialized with {Count} known games", _knownGameExecutables.Count);
|
||||
}
|
||||
|
||||
public async Task<bool> EnableGameBoostAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
if (!_settings.EnableGameBoostMode)
|
||||
{
|
||||
_logger.LogWarning("Game Boost mode is disabled in settings");
|
||||
return false;
|
||||
}
|
||||
|
||||
_logger.LogInformation("Game Boost mode enabled");
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Failed to enable Game Boost mode");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<bool> DisableGameBoostAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
if (_isGameBoostActive)
|
||||
{
|
||||
await DeactivateGameBoostAsync();
|
||||
}
|
||||
|
||||
_logger.LogInformation("Game Boost mode disabled");
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Failed to disable Game Boost mode");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<bool> ActivateGameBoostAsync(ProcessModel process)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (_isGameBoostActive && _currentGameProcess?.ProcessId == process.ProcessId)
|
||||
{
|
||||
_logger.LogDebug("Game Boost already active for process {ProcessName}", process.Name);
|
||||
return true;
|
||||
}
|
||||
|
||||
// Deactivate current boost if active
|
||||
if (_isGameBoostActive)
|
||||
{
|
||||
await DeactivateGameBoostAsync();
|
||||
}
|
||||
|
||||
// Store current power plan
|
||||
var currentPowerPlan = await _powerPlanService.GetActivePowerPlan();
|
||||
_previousPowerPlanId = currentPowerPlan?.Guid;
|
||||
|
||||
// Apply Game Boost power plan
|
||||
var gameBoostPowerPlanId = !string.IsNullOrEmpty(_settings.GameBoostPowerPlanId)
|
||||
? _settings.GameBoostPowerPlanId
|
||||
: await GetHighPerformancePowerPlanIdAsync();
|
||||
|
||||
if (!string.IsNullOrEmpty(gameBoostPowerPlanId))
|
||||
{
|
||||
await _powerPlanService.SetActivePowerPlanByGuidAsync(gameBoostPowerPlanId);
|
||||
}
|
||||
|
||||
// Set high priority if enabled
|
||||
if (_settings.GameBoostSetHighPriority)
|
||||
{
|
||||
await SetProcessPriorityAsync(process, ProcessPriorityClass.High);
|
||||
}
|
||||
|
||||
// Optimize CPU affinity if enabled
|
||||
if (_settings.GameBoostOptimizeCpuAffinity)
|
||||
{
|
||||
await OptimizeCpuAffinityAsync(process);
|
||||
}
|
||||
|
||||
_isGameBoostActive = true;
|
||||
_currentGameProcess = process;
|
||||
_gameBoostStartTime = DateTime.Now;
|
||||
|
||||
_logger.LogInformation("Game Boost activated for {ProcessName} (PID: {ProcessId})",
|
||||
process.Name, process.ProcessId);
|
||||
|
||||
// Fire events
|
||||
GameDetected?.Invoke(this, new GameDetectedEventArgs(process, _knownGameExecutables.Contains(process.Name.ToLowerInvariant())));
|
||||
GameBoostActivated?.Invoke(this, new GameBoostActivatedEventArgs(process, gameBoostPowerPlanId ?? ""));
|
||||
|
||||
await _notificationService.ShowSuccessNotificationAsync(
|
||||
"Game Boost Activated",
|
||||
$"Game Boost mode activated for {process.Name}");
|
||||
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Failed to activate Game Boost for process {ProcessName}", process.Name);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<bool> DeactivateGameBoostAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
if (!_isGameBoostActive)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
var duration = _gameBoostStartTime.HasValue
|
||||
? DateTime.Now - _gameBoostStartTime.Value
|
||||
: TimeSpan.Zero;
|
||||
|
||||
// Restore previous power plan
|
||||
if (!string.IsNullOrEmpty(_previousPowerPlanId))
|
||||
{
|
||||
await _powerPlanService.SetActivePowerPlanByGuidAsync(_previousPowerPlanId);
|
||||
}
|
||||
else if (!string.IsNullOrEmpty(_settings.DefaultPowerPlanId))
|
||||
{
|
||||
await _powerPlanService.SetActivePowerPlanByGuidAsync(_settings.DefaultPowerPlanId);
|
||||
}
|
||||
|
||||
var gameProcess = _currentGameProcess;
|
||||
var restoredPowerPlanId = _previousPowerPlanId ?? _settings.DefaultPowerPlanId;
|
||||
|
||||
_isGameBoostActive = false;
|
||||
_currentGameProcess = null;
|
||||
_previousPowerPlanId = null;
|
||||
_gameBoostStartTime = null;
|
||||
|
||||
_logger.LogInformation("Game Boost deactivated after {Duration}", duration);
|
||||
|
||||
GameBoostDeactivated?.Invoke(this, new GameBoostDeactivatedEventArgs(
|
||||
gameProcess, restoredPowerPlanId, duration));
|
||||
|
||||
await _notificationService.ShowNotificationAsync(
|
||||
"Game Boost Deactivated",
|
||||
$"Game Boost mode deactivated after {duration:hh\\:mm\\:ss}",
|
||||
NotificationType.Information);
|
||||
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Failed to deactivate Game Boost");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<bool> AddKnownGameAsync(string executableName)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(executableName))
|
||||
return false;
|
||||
|
||||
var normalizedName = executableName.ToLowerInvariant();
|
||||
if (!_knownGameExecutables.Contains(normalizedName))
|
||||
{
|
||||
_knownGameExecutables.Add(normalizedName);
|
||||
_logger.LogInformation("Added known game: {ExecutableName}", executableName);
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
public async Task<bool> RemoveKnownGameAsync(string executableName)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(executableName))
|
||||
return false;
|
||||
|
||||
var normalizedName = executableName.ToLowerInvariant();
|
||||
var removed = _knownGameExecutables.Remove(normalizedName);
|
||||
|
||||
if (removed)
|
||||
{
|
||||
_logger.LogInformation("Removed known game: {ExecutableName}", executableName);
|
||||
}
|
||||
|
||||
return removed;
|
||||
}
|
||||
|
||||
public IReadOnlyList<string> GetKnownGameExecutables()
|
||||
{
|
||||
return _knownGameExecutables.ToList().AsReadOnly();
|
||||
}
|
||||
|
||||
public bool IsGameProcess(ProcessModel process)
|
||||
{
|
||||
if (process == null || string.IsNullOrEmpty(process.Name))
|
||||
return false;
|
||||
|
||||
var processName = process.Name.ToLowerInvariant();
|
||||
|
||||
// Check against known games list
|
||||
if (_knownGameExecutables.Contains(processName))
|
||||
return true;
|
||||
|
||||
// Auto-detection heuristics (if enabled)
|
||||
if (_settings.GameBoostAutoDetectGames)
|
||||
{
|
||||
return IsLikelyGameProcess(process);
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private void OnSettingsChanged(object? sender, ApplicationSettingsChangedEventArgs e)
|
||||
{
|
||||
try
|
||||
{
|
||||
_settings = e.NewSettings;
|
||||
_logger.LogDebug("Game Boost settings updated");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error updating Game Boost settings");
|
||||
}
|
||||
}
|
||||
|
||||
private List<string> InitializeKnownGames()
|
||||
{
|
||||
return new List<string>
|
||||
{
|
||||
// Game Launchers
|
||||
"steam.exe",
|
||||
"steamwebhelper.exe",
|
||||
"origin.exe",
|
||||
"epicgameslauncher.exe",
|
||||
"uplay.exe",
|
||||
"ubisoft connect.exe",
|
||||
"battlenet.exe",
|
||||
"battle.net.exe",
|
||||
"gog.exe",
|
||||
"gog galaxy.exe",
|
||||
"rockstarlauncher.exe",
|
||||
"bethesdanetlauncher.exe",
|
||||
"ea desktop.exe",
|
||||
"xbox.exe",
|
||||
"xboxapp.exe",
|
||||
"gamepass.exe",
|
||||
|
||||
// Popular Games - FPS/Shooters
|
||||
"csgo.exe",
|
||||
"cs2.exe",
|
||||
"valorant.exe",
|
||||
"valorant-win64-shipping.exe",
|
||||
"fortniteclient-win64-shipping.exe",
|
||||
"fortnite.exe",
|
||||
"apex_legends.exe",
|
||||
"r5apex.exe",
|
||||
"overwatch.exe",
|
||||
"overwatch2.exe",
|
||||
"cod.exe",
|
||||
"modernwarfare.exe",
|
||||
"warzone.exe",
|
||||
"blackops.exe",
|
||||
"rainbow6.exe",
|
||||
"rainbowsix.exe",
|
||||
"pubg.exe",
|
||||
"tslgame.exe",
|
||||
"bf1.exe",
|
||||
"bfv.exe",
|
||||
"bf2042.exe",
|
||||
"titanfall2.exe",
|
||||
"doom.exe",
|
||||
"doomslayers.exe",
|
||||
"doom eternal.exe",
|
||||
"halo.exe",
|
||||
"haloinfinite.exe",
|
||||
"destiny2.exe",
|
||||
|
||||
// Popular Games - MOBA/Strategy
|
||||
"dota2.exe",
|
||||
"league of legends.exe",
|
||||
"lol.exe",
|
||||
"riotclientservices.exe",
|
||||
"teamfighttactics.exe",
|
||||
"starcraft2.exe",
|
||||
"sc2.exe",
|
||||
"warcraft3.exe",
|
||||
"aoe2de.exe",
|
||||
"aoe4.exe",
|
||||
"civilization6.exe",
|
||||
"civ6.exe",
|
||||
"totalwar.exe",
|
||||
|
||||
// Popular Games - RPG/Adventure
|
||||
"witcher3.exe",
|
||||
"cyberpunk2077.exe",
|
||||
"skyrim.exe",
|
||||
"skyrimse.exe",
|
||||
"fallout4.exe",
|
||||
"fallout76.exe",
|
||||
"elderscrollsonline.exe",
|
||||
"wow.exe",
|
||||
"worldofwarcraft.exe",
|
||||
"ffxiv.exe",
|
||||
"ffxiv_dx11.exe",
|
||||
"guildwars2.exe",
|
||||
"newworld.exe",
|
||||
"lostark.exe",
|
||||
"diablo3.exe",
|
||||
"diablo4.exe",
|
||||
"pathofexile.exe",
|
||||
"borderlands3.exe",
|
||||
"masseffect.exe",
|
||||
"dragonage.exe",
|
||||
"assassinscreed.exe",
|
||||
"farcry.exe",
|
||||
"watchdogs.exe",
|
||||
|
||||
// Popular Games - Open World/Action
|
||||
"gta5.exe",
|
||||
"gtav.exe",
|
||||
"rdr2.exe",
|
||||
"reddeadredemption2.exe",
|
||||
"minecraft.exe",
|
||||
"minecraftlauncher.exe",
|
||||
"javaw.exe", // Minecraft Java
|
||||
"terraria.exe",
|
||||
"stardewvalley.exe",
|
||||
"subnautica.exe",
|
||||
"nomanssky.exe",
|
||||
"spiderman.exe",
|
||||
"godofwar.exe",
|
||||
"horizonzerodawn.exe",
|
||||
"deathstranding.exe",
|
||||
|
||||
// Popular Games - Racing/Sports
|
||||
"forza.exe",
|
||||
"forzahorizon.exe",
|
||||
"granturismo.exe",
|
||||
"f1.exe",
|
||||
"dirt.exe",
|
||||
"wreckfest.exe",
|
||||
"fifa.exe",
|
||||
"nba2k.exe",
|
||||
"madden.exe",
|
||||
"rocketleague.exe",
|
||||
|
||||
// Popular Games - Simulation/Building
|
||||
"citiesskylines.exe",
|
||||
"simcity.exe",
|
||||
"planetcoaster.exe",
|
||||
"twopointcampus.exe",
|
||||
"kerbalspaceprogram.exe",
|
||||
"factorio.exe",
|
||||
"satisfactory.exe",
|
||||
"valheim.exe",
|
||||
"rust.exe",
|
||||
"ark.exe",
|
||||
"7daystodie.exe",
|
||||
"greenhell.exe",
|
||||
"theforest.exe",
|
||||
|
||||
// VR Games
|
||||
"vrchat.exe",
|
||||
"beatsaber.exe",
|
||||
"halflife alyx.exe",
|
||||
"pavlov.exe",
|
||||
"boneworks.exe",
|
||||
|
||||
// Indie/Popular Smaller Games
|
||||
"amongus.exe",
|
||||
"fallguys.exe",
|
||||
"cuphead.exe",
|
||||
"hollowknight.exe",
|
||||
"celeste.exe",
|
||||
"ori.exe",
|
||||
"hades.exe",
|
||||
"deadcells.exe",
|
||||
"riskofrain2.exe",
|
||||
"deeprockgalactic.exe",
|
||||
"seaofthieves.exe",
|
||||
"phasmophobia.exe",
|
||||
"genshinimpact.exe",
|
||||
"honkaiimpact.exe"
|
||||
};
|
||||
}
|
||||
|
||||
private bool IsLikelyGameProcess(ProcessModel process)
|
||||
{
|
||||
try
|
||||
{
|
||||
var processName = process.Name.ToLowerInvariant();
|
||||
var processPath = process.ExecutablePath?.ToLowerInvariant() ?? "";
|
||||
|
||||
// Skip system processes and common applications
|
||||
if (IsSystemOrCommonProcess(processName))
|
||||
return false;
|
||||
|
||||
// Check for game-related keywords in process name
|
||||
if (HasGameKeywords(processName))
|
||||
return true;
|
||||
|
||||
// Check for game-related paths
|
||||
if (HasGamePath(processPath))
|
||||
return true;
|
||||
|
||||
// Check for game engines
|
||||
if (HasGameEngineIndicators(processName, processPath))
|
||||
return true;
|
||||
|
||||
// Check for executable patterns common in games
|
||||
if (HasGameExecutablePatterns(processName))
|
||||
return true;
|
||||
|
||||
return false;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogDebug(ex, "Error in game detection heuristics for process {ProcessName}", process.Name);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private bool IsSystemOrCommonProcess(string processName)
|
||||
{
|
||||
var systemProcesses = new[]
|
||||
{
|
||||
"explorer.exe", "dwm.exe", "winlogon.exe", "csrss.exe", "smss.exe", "wininit.exe",
|
||||
"services.exe", "lsass.exe", "svchost.exe", "taskhost.exe", "taskhostw.exe",
|
||||
"conhost.exe", "audiodg.exe", "spoolsv.exe", "winlogon.exe", "userinit.exe",
|
||||
"chrome.exe", "firefox.exe", "msedge.exe", "iexplore.exe", "opera.exe",
|
||||
"notepad.exe", "calc.exe", "mspaint.exe", "wordpad.exe", "cmd.exe", "powershell.exe",
|
||||
"winword.exe", "excel.exe", "powerpoint.exe", "outlook.exe", "onenote.exe",
|
||||
"photoshop.exe", "illustrator.exe", "premiere.exe", "aftereffects.exe",
|
||||
"code.exe", "devenv.exe", "rider.exe", "intellij.exe", "eclipse.exe",
|
||||
"discord.exe", "slack.exe", "teams.exe", "zoom.exe", "skype.exe",
|
||||
"spotify.exe", "vlc.exe", "wmplayer.exe", "itunes.exe", "winamp.exe",
|
||||
"7z.exe", "winrar.exe", "winzip.exe", "filezilla.exe", "putty.exe"
|
||||
};
|
||||
|
||||
return systemProcesses.Contains(processName);
|
||||
}
|
||||
|
||||
private bool HasGameKeywords(string processName)
|
||||
{
|
||||
var gameKeywords = new[]
|
||||
{
|
||||
"game", "launcher", "client", "engine", "unity", "unreal", "godot", "cryengine",
|
||||
"steam", "epic", "origin", "uplay", "battlenet", "gog", "rockstar",
|
||||
"minecraft", "roblox", "fortnite", "valorant", "csgo", "dota", "lol",
|
||||
"wow", "overwatch", "apex", "pubg", "cod", "battlefield", "destiny",
|
||||
"cyberpunk", "witcher", "skyrim", "fallout", "gta", "rdr", "assassin",
|
||||
"farcry", "watchdog", "borderlands", "diablo", "starcraft", "warcraft",
|
||||
"civilization", "totalwar", "aoe", "fifa", "nba", "madden", "forza",
|
||||
"racing", "simulator", "tycoon", "builder", "strategy", "rpg", "mmo",
|
||||
"shooter", "adventure", "action", "puzzle", "platformer", "indie"
|
||||
};
|
||||
|
||||
return gameKeywords.Any(keyword => processName.Contains(keyword));
|
||||
}
|
||||
|
||||
private bool HasGamePath(string processPath)
|
||||
{
|
||||
if (string.IsNullOrEmpty(processPath))
|
||||
return false;
|
||||
|
||||
var gamePaths = new[]
|
||||
{
|
||||
@"\steam\steamapps\", @"\steamapps\common\", @"\steam games\",
|
||||
@"\epic games\", @"\epicgames\", @"\epic\",
|
||||
@"\origin games\", @"\origin\", @"\ea games\",
|
||||
@"\ubisoft\", @"\uplay\", @"\ubisoft game launcher\",
|
||||
@"\gog galaxy\", @"\gog games\", @"\gog.com\",
|
||||
@"\battle.net\", @"\battlenet\", @"\blizzard\",
|
||||
@"\rockstar games\", @"\rockstar\",
|
||||
@"\xbox games\", @"\microsoft games\", @"\windowsapps\",
|
||||
@"\games\", @"\gaming\", @"\my games\",
|
||||
@"\program files\games\", @"\program files (x86)\games\",
|
||||
@"\minecraft\", @"\roblox\", @"\riot games\",
|
||||
@"\square enix\", @"\activision\", @"\electronic arts\",
|
||||
@"\2k games\", @"\bethesda\", @"\cd projekt red\",
|
||||
@"\valve\", @"\id software\", @"\bungie\"
|
||||
};
|
||||
|
||||
return gamePaths.Any(path => processPath.Contains(path));
|
||||
}
|
||||
|
||||
private bool HasGameEngineIndicators(string processName, string processPath)
|
||||
{
|
||||
var engineIndicators = new[]
|
||||
{
|
||||
"unity", "unreal", "ue4", "ue5", "godot", "cryengine", "frostbite",
|
||||
"source", "idtech", "creation", "anvil", "dunia", "snowdrop",
|
||||
"decima", "fox", "mt framework", "luminous", "crystal tools",
|
||||
"gamebryo", "havok", "physx", "directx", "opengl", "vulkan"
|
||||
};
|
||||
|
||||
return engineIndicators.Any(indicator =>
|
||||
processName.Contains(indicator) || processPath.Contains(indicator));
|
||||
}
|
||||
|
||||
private bool HasGameExecutablePatterns(string processName)
|
||||
{
|
||||
// Common patterns in game executables
|
||||
var patterns = new[]
|
||||
{
|
||||
// Shipping builds (Unreal Engine)
|
||||
"shipping.exe", "-shipping.exe", "_shipping.exe",
|
||||
// Win64 builds
|
||||
"win64.exe", "-win64.exe", "_win64.exe",
|
||||
// Game suffixes
|
||||
"game.exe", "_game.exe", "-game.exe",
|
||||
// Client executables
|
||||
"client.exe", "_client.exe", "-client.exe",
|
||||
// Launcher patterns
|
||||
"launcher.exe", "_launcher.exe", "-launcher.exe",
|
||||
// Engine patterns
|
||||
"engine.exe", "_engine.exe", "-engine.exe",
|
||||
// Common game number patterns (sequels)
|
||||
"2.exe", "3.exe", "4.exe", "5.exe", "2077.exe", "2042.exe"
|
||||
};
|
||||
|
||||
return patterns.Any(pattern => processName.EndsWith(pattern));
|
||||
}
|
||||
|
||||
private async Task<string?> GetHighPerformancePowerPlanIdAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
var powerPlans = await _powerPlanService.GetPowerPlansAsync();
|
||||
var highPerformancePlan = powerPlans.FirstOrDefault(p =>
|
||||
p.Name.Contains("High performance", StringComparison.OrdinalIgnoreCase) ||
|
||||
p.Name.Contains("Ultimate Performance", StringComparison.OrdinalIgnoreCase));
|
||||
|
||||
return highPerformancePlan?.Guid;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Failed to get high performance power plan");
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private async Task SetProcessPriorityAsync(ProcessModel processModel, ProcessPriorityClass priority)
|
||||
{
|
||||
try
|
||||
{
|
||||
var process = Process.GetProcessById(processModel.ProcessId);
|
||||
process.PriorityClass = priority;
|
||||
_logger.LogDebug("Set process {ProcessName} priority to {Priority}", processModel.Name, priority);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogWarning(ex, "Failed to set process priority for {ProcessName}", processModel.Name);
|
||||
}
|
||||
}
|
||||
|
||||
private async Task OptimizeCpuAffinityAsync(ProcessModel processModel)
|
||||
{
|
||||
try
|
||||
{
|
||||
// This would integrate with the CPU topology service
|
||||
// For now, just log the intent
|
||||
_logger.LogDebug("CPU affinity optimization requested for {ProcessName}", processModel.Name);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogWarning(ex, "Failed to optimize CPU affinity for {ProcessName}", processModel.Name);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,692 +0,0 @@
|
||||
/*
|
||||
* ThreadPilot - Advanced Windows Process and Power Plan Manager
|
||||
* Copyright (C) 2025 Prime Build
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published by
|
||||
* the Free Software Foundation, version 3 only.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Win32;
|
||||
using ThreadPilot.Models;
|
||||
|
||||
namespace ThreadPilot.Services
|
||||
{
|
||||
/// <summary>
|
||||
/// Service for detecting running games and applying optimal performance profiles
|
||||
/// </summary>
|
||||
public class GameDetectionService : IGameDetectionService
|
||||
{
|
||||
private readonly ILogger<GameDetectionService> _logger;
|
||||
private readonly IProcessService _processService;
|
||||
private readonly ICpuTopologyService _cpuTopologyService;
|
||||
private readonly IPowerPlanService _powerPlanService;
|
||||
private readonly Dictionary<string, GameProfile> _gameProfiles;
|
||||
private readonly Dictionary<string, DateTime> _gameStartTimes;
|
||||
|
||||
// ADVANCED GAME DETECTION: ML and performance monitoring
|
||||
private readonly Dictionary<string, bool> _gameOverrides = new();
|
||||
private readonly Dictionary<int, GamePerformanceMetrics> _monitoredGames = new();
|
||||
private readonly List<string> _gameKeywords = new()
|
||||
{
|
||||
"game", "gaming", "play", "steam", "epic", "origin", "uplay", "battle.net",
|
||||
"launcher", "client", "engine", "unity", "unreal", "directx", "opengl", "vulkan"
|
||||
};
|
||||
private readonly List<string> _gamesFolders = new()
|
||||
{
|
||||
"games", "steam", "steamapps", "epic games", "origin games", "uplay", "battle.net"
|
||||
};
|
||||
|
||||
public event EventHandler<GameProfileDetectedEventArgs>? GameDetected;
|
||||
public event EventHandler<GameStoppedEventArgs>? GameStopped;
|
||||
|
||||
public GameDetectionService(
|
||||
ILogger<GameDetectionService> logger,
|
||||
IProcessService processService,
|
||||
ICpuTopologyService cpuTopologyService,
|
||||
IPowerPlanService powerPlanService)
|
||||
{
|
||||
_logger = logger;
|
||||
_processService = processService;
|
||||
_cpuTopologyService = cpuTopologyService;
|
||||
_powerPlanService = powerPlanService;
|
||||
_gameProfiles = new Dictionary<string, GameProfile>();
|
||||
_gameStartTimes = new Dictionary<string, DateTime>();
|
||||
|
||||
InitializeDefaultGameProfiles();
|
||||
}
|
||||
|
||||
public async Task<ProcessFeatures> ExtractProcessFeaturesAsync(ProcessModel process)
|
||||
{
|
||||
var (threadCount, handleCount) = GetRuntimeProcessMetrics(process.ProcessId);
|
||||
|
||||
var features = new ProcessFeatures
|
||||
{
|
||||
ProcessName = process.Name,
|
||||
ExecutablePath = process.ExecutablePath ?? string.Empty,
|
||||
HasVisibleWindow = process.HasVisibleWindow,
|
||||
CpuUsage = process.CpuUsage,
|
||||
MemoryUsage = process.MemoryUsage,
|
||||
ThreadCount = threadCount,
|
||||
HandleCount = handleCount
|
||||
};
|
||||
|
||||
try
|
||||
{
|
||||
// Check for graphics API DLLs
|
||||
features.HasDirectXDlls = await HasLoadedDllAsync(process, "d3d", "dxgi", "d3d11", "d3d12");
|
||||
features.HasOpenGLDlls = await HasLoadedDllAsync(process, "opengl32", "glu32");
|
||||
features.HasVulkanDlls = await HasLoadedDllAsync(process, "vulkan");
|
||||
features.HasAudioDlls = await HasLoadedDllAsync(process, "dsound", "xaudio", "fmod");
|
||||
|
||||
// Check file properties
|
||||
if (!string.IsNullOrEmpty(features.ExecutablePath) && File.Exists(features.ExecutablePath))
|
||||
{
|
||||
var fileInfo = FileVersionInfo.GetVersionInfo(features.ExecutablePath);
|
||||
features.FileDescription = fileInfo.FileDescription ?? string.Empty;
|
||||
features.CompanyName = fileInfo.CompanyName ?? string.Empty;
|
||||
}
|
||||
|
||||
// Check if in games folder
|
||||
features.IsInGamesFolder = _gamesFolders.Any(folder =>
|
||||
features.ExecutablePath.Contains(folder, StringComparison.OrdinalIgnoreCase));
|
||||
|
||||
// Check for game keywords
|
||||
features.HasGameKeywords = _gameKeywords.Any(keyword =>
|
||||
features.ProcessName.Contains(keyword, StringComparison.OrdinalIgnoreCase) ||
|
||||
features.FileDescription.Contains(keyword, StringComparison.OrdinalIgnoreCase));
|
||||
|
||||
// Check if fullscreen (simplified check)
|
||||
features.IsFullscreen = process.HasVisibleWindow && process.MainWindowTitle != null;
|
||||
|
||||
_logger.LogDebug("Extracted features for {ProcessName}: DirectX={HasDirectX}, OpenGL={HasOpenGL}, GamesFolder={IsInGamesFolder}",
|
||||
process.Name, features.HasDirectXDlls, features.HasOpenGLDlls, features.IsInGamesFolder);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogWarning(ex, "Error extracting features for process {ProcessName}", process.Name);
|
||||
}
|
||||
|
||||
return features;
|
||||
}
|
||||
|
||||
private static (int ThreadCount, int HandleCount) GetRuntimeProcessMetrics(int processId)
|
||||
{
|
||||
try
|
||||
{
|
||||
using var liveProcess = Process.GetProcessById(processId);
|
||||
return (liveProcess.Threads.Count, liveProcess.HandleCount);
|
||||
}
|
||||
catch
|
||||
{
|
||||
return (0, 0);
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<GamePerformanceMetrics> GetGamePerformanceAsync(ProcessModel process)
|
||||
{
|
||||
var metrics = new GamePerformanceMetrics
|
||||
{
|
||||
ProcessId = process.ProcessId,
|
||||
GameName = process.Name,
|
||||
CpuUsage = process.CpuUsage,
|
||||
MemoryUsage = process.MemoryUsage,
|
||||
Timestamp = DateTime.UtcNow,
|
||||
IsFullscreen = process.HasVisibleWindow
|
||||
};
|
||||
|
||||
try
|
||||
{
|
||||
// Estimate frame rate based on CPU usage patterns (simplified)
|
||||
metrics.FrameRate = EstimateFrameRate(process);
|
||||
|
||||
// Get GPU usage (would require additional APIs in real implementation)
|
||||
metrics.GpuUsage = 0.0; // Placeholder
|
||||
metrics.GpuMemoryUsage = 0; // Placeholder
|
||||
|
||||
// Get window resolution (simplified)
|
||||
metrics.Resolution = process.HasVisibleWindow ? "1920x1080" : "N/A"; // Placeholder
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogWarning(ex, "Error getting performance metrics for {ProcessName}", process.Name);
|
||||
}
|
||||
|
||||
return metrics;
|
||||
}
|
||||
|
||||
public async Task<GameDetectionResult> DetectGameWithMLAsync(ProcessModel process)
|
||||
{
|
||||
try
|
||||
{
|
||||
// Check manual overrides first
|
||||
if (_gameOverrides.TryGetValue(process.Name.ToLower(), out var isGameOverride))
|
||||
{
|
||||
return new GameDetectionResult
|
||||
{
|
||||
IsGame = isGameOverride,
|
||||
Confidence = 1.0f,
|
||||
GameName = process.Name,
|
||||
DetectionMethod = "Manual Override",
|
||||
DetectionTime = DateTime.UtcNow
|
||||
};
|
||||
}
|
||||
|
||||
// Extract features for ML classification
|
||||
var features = await ExtractProcessFeaturesAsync(process);
|
||||
|
||||
// Simple ML-like scoring based on features (can be replaced with actual ML model)
|
||||
var score = CalculateGameScore(features);
|
||||
|
||||
var result = new GameDetectionResult
|
||||
{
|
||||
IsGame = score >= 0.5f,
|
||||
Confidence = score,
|
||||
GameName = features.ProcessName,
|
||||
DetectionMethod = "ML Classification",
|
||||
Features = ConvertFeaturesToDictionary(features),
|
||||
DetectionTime = DateTime.UtcNow
|
||||
};
|
||||
|
||||
_logger.LogDebug("ML game detection for {ProcessName}: IsGame={IsGame}, Confidence={Confidence:P1}",
|
||||
process.Name, result.IsGame, result.Confidence);
|
||||
|
||||
return result;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error in ML game detection for process {ProcessName}", process.Name);
|
||||
return new GameDetectionResult
|
||||
{
|
||||
IsGame = false,
|
||||
Confidence = 0.0f,
|
||||
GameName = process.Name,
|
||||
DetectionMethod = "Error",
|
||||
DetectionTime = DateTime.UtcNow
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<GameProfile?> DetectGameAsync(ProcessModel process)
|
||||
{
|
||||
try
|
||||
{
|
||||
// Check known games database first
|
||||
if (_gameProfiles.TryGetValue(process.Name.ToLower(), out var profile))
|
||||
{
|
||||
profile.LastDetected = DateTime.UtcNow;
|
||||
profile.DetectionCount++;
|
||||
|
||||
// Track game start time
|
||||
if (!_gameStartTimes.ContainsKey(process.Name))
|
||||
{
|
||||
_gameStartTimes[process.Name] = DateTime.UtcNow;
|
||||
GameDetected?.Invoke(this, new GameProfileDetectedEventArgs(process, profile));
|
||||
}
|
||||
|
||||
return profile;
|
||||
}
|
||||
|
||||
// Check Steam games
|
||||
if (await IsSteamGameAsync(process))
|
||||
{
|
||||
var steamProfile = await GetSteamGameProfileAsync(process);
|
||||
if (steamProfile != null)
|
||||
{
|
||||
return steamProfile;
|
||||
}
|
||||
}
|
||||
|
||||
// Check Epic Games
|
||||
if (await IsEpicGameAsync(process))
|
||||
{
|
||||
var epicProfile = await GetEpicGameProfileAsync(process);
|
||||
if (epicProfile != null)
|
||||
{
|
||||
return epicProfile;
|
||||
}
|
||||
}
|
||||
|
||||
// Check for common game patterns
|
||||
if (IsLikelyGame(process))
|
||||
{
|
||||
return CreateGenericGameProfile(process);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error detecting game for process {ProcessName}", process.Name);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<List<GameProfile>> GetRunningGamesAsync()
|
||||
{
|
||||
var runningGames = new List<GameProfile>();
|
||||
var processes = await _processService.GetActiveApplicationsAsync();
|
||||
|
||||
foreach (var process in processes)
|
||||
{
|
||||
var gameProfile = await DetectGameAsync(process);
|
||||
if (gameProfile != null)
|
||||
{
|
||||
runningGames.Add(gameProfile);
|
||||
}
|
||||
}
|
||||
|
||||
return runningGames;
|
||||
}
|
||||
|
||||
public async Task<bool> ApplyGameOptimizationsAsync(ProcessModel process, GameProfile gameProfile)
|
||||
{
|
||||
try
|
||||
{
|
||||
_logger.LogInformation("Applying optimizations for game {GameName} (Process: {ProcessName})",
|
||||
gameProfile.Name, process.Name);
|
||||
|
||||
var success = true;
|
||||
|
||||
// Apply CPU affinity
|
||||
if (!string.IsNullOrEmpty(gameProfile.OptimalCores))
|
||||
{
|
||||
var affinityMask = await CalculateOptimalAffinityMask(gameProfile.OptimalCores);
|
||||
if (affinityMask.HasValue)
|
||||
{
|
||||
await _processService.SetProcessorAffinity(process, (long)affinityMask.Value);
|
||||
}
|
||||
}
|
||||
|
||||
// Apply process priority
|
||||
await _processService.SetProcessPriority(process, gameProfile.Priority);
|
||||
|
||||
// Apply power plan if specified
|
||||
if (!string.IsNullOrEmpty(gameProfile.PowerPlan))
|
||||
{
|
||||
var powerPlans = await _powerPlanService.GetPowerPlansAsync();
|
||||
var targetPlan = powerPlans.FirstOrDefault(p =>
|
||||
p.Name.Contains(gameProfile.PowerPlan, StringComparison.OrdinalIgnoreCase));
|
||||
|
||||
if (targetPlan != null)
|
||||
{
|
||||
success &= await _powerPlanService.SetActivePowerPlan(targetPlan);
|
||||
}
|
||||
}
|
||||
|
||||
return success;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error applying game optimizations for {ProcessName}", process.Name);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<bool> IsSteamGameAsync(ProcessModel process)
|
||||
{
|
||||
try
|
||||
{
|
||||
// Check if process is launched by Steam
|
||||
var parentProcess = GetParentProcess(process.ProcessId);
|
||||
if (parentProcess?.ProcessName?.Contains("steam", StringComparison.OrdinalIgnoreCase) == true)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
// Check Steam installation directory
|
||||
var steamPath = GetSteamInstallPath();
|
||||
if (!string.IsNullOrEmpty(steamPath) && !string.IsNullOrEmpty(process.ExecutablePath))
|
||||
{
|
||||
return process.ExecutablePath.StartsWith(steamPath, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error checking if process is Steam game: {ProcessName}", process.Name);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<bool> IsEpicGameAsync(ProcessModel process)
|
||||
{
|
||||
try
|
||||
{
|
||||
// Check if process is launched by Epic Games Launcher
|
||||
var parentProcess = GetParentProcess(process.ProcessId);
|
||||
if (parentProcess?.ProcessName?.Contains("EpicGamesLauncher", StringComparison.OrdinalIgnoreCase) == true ||
|
||||
parentProcess?.ProcessName?.Contains("UnrealEngineLauncher", StringComparison.OrdinalIgnoreCase) == true)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
// Check Epic Games installation directory
|
||||
var epicPath = GetEpicGamesInstallPath();
|
||||
if (!string.IsNullOrEmpty(epicPath) && !string.IsNullOrEmpty(process.ExecutablePath))
|
||||
{
|
||||
return process.ExecutablePath.StartsWith(epicPath, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error checking if process is Epic game: {ProcessName}", process.Name);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<GameProfile?> GetSteamGameProfileAsync(ProcessModel process)
|
||||
{
|
||||
// Create a Steam-specific game profile
|
||||
return new GameProfile
|
||||
{
|
||||
Name = $"Steam: {process.Name}",
|
||||
ProcessName = process.Name,
|
||||
OptimalCores = "Physical", // Steam games generally benefit from physical cores
|
||||
Priority = ProcessPriorityClass.High,
|
||||
PowerPlan = "High Performance",
|
||||
Category = GameCategory.Unknown,
|
||||
Description = "Steam game detected automatically"
|
||||
};
|
||||
}
|
||||
|
||||
public async Task<GameProfile?> GetEpicGameProfileAsync(ProcessModel process)
|
||||
{
|
||||
// Create an Epic-specific game profile
|
||||
return new GameProfile
|
||||
{
|
||||
Name = $"Epic: {process.Name}",
|
||||
ProcessName = process.Name,
|
||||
OptimalCores = "Physical", // Epic games generally benefit from physical cores
|
||||
Priority = ProcessPriorityClass.High,
|
||||
PowerPlan = "High Performance",
|
||||
Category = GameCategory.Unknown,
|
||||
Description = "Epic Games game detected automatically"
|
||||
};
|
||||
}
|
||||
|
||||
public async Task AddCustomGameProfileAsync(string processName, GameProfile profile)
|
||||
{
|
||||
_gameProfiles[processName.ToLower()] = profile;
|
||||
_logger.LogInformation("Added custom game profile for {ProcessName}", processName);
|
||||
}
|
||||
|
||||
public async Task RemoveCustomGameProfileAsync(string processName)
|
||||
{
|
||||
if (_gameProfiles.Remove(processName.ToLower()))
|
||||
{
|
||||
_logger.LogInformation("Removed custom game profile for {ProcessName}", processName);
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<Dictionary<string, GameProfile>> GetAllGameProfilesAsync()
|
||||
{
|
||||
return new Dictionary<string, GameProfile>(_gameProfiles);
|
||||
}
|
||||
|
||||
private void InitializeDefaultGameProfiles()
|
||||
{
|
||||
// Popular FPS games
|
||||
_gameProfiles["valorant.exe"] = new GameProfile
|
||||
{
|
||||
Name = "Valorant",
|
||||
ProcessName = "valorant.exe",
|
||||
OptimalCores = "Physical",
|
||||
Priority = ProcessPriorityClass.High,
|
||||
PowerPlan = "High Performance",
|
||||
Category = GameCategory.FPS,
|
||||
Description = "Riot Games' tactical FPS"
|
||||
};
|
||||
|
||||
_gameProfiles["csgo.exe"] = new GameProfile
|
||||
{
|
||||
Name = "Counter-Strike: Global Offensive",
|
||||
ProcessName = "csgo.exe",
|
||||
OptimalCores = "Physical",
|
||||
Priority = ProcessPriorityClass.High,
|
||||
PowerPlan = "High Performance",
|
||||
Category = GameCategory.FPS
|
||||
};
|
||||
|
||||
_gameProfiles["cs2.exe"] = new GameProfile
|
||||
{
|
||||
Name = "Counter-Strike 2",
|
||||
ProcessName = "cs2.exe",
|
||||
OptimalCores = "P-Cores",
|
||||
Priority = ProcessPriorityClass.High,
|
||||
PowerPlan = "High Performance",
|
||||
Category = GameCategory.FPS
|
||||
};
|
||||
|
||||
_gameProfiles["cyberpunk2077.exe"] = new GameProfile
|
||||
{
|
||||
Name = "Cyberpunk 2077",
|
||||
ProcessName = "cyberpunk2077.exe",
|
||||
OptimalCores = "P-Cores",
|
||||
Priority = ProcessPriorityClass.High,
|
||||
PowerPlan = "High Performance",
|
||||
Category = GameCategory.RPG
|
||||
};
|
||||
|
||||
_gameProfiles["fortnite.exe"] = new GameProfile
|
||||
{
|
||||
Name = "Fortnite",
|
||||
ProcessName = "fortnite.exe",
|
||||
OptimalCores = "Physical",
|
||||
Priority = ProcessPriorityClass.High,
|
||||
PowerPlan = "High Performance",
|
||||
Category = GameCategory.FPS
|
||||
};
|
||||
|
||||
_gameProfiles["league of legends.exe"] = new GameProfile
|
||||
{
|
||||
Name = "League of Legends",
|
||||
ProcessName = "league of legends.exe",
|
||||
OptimalCores = "Physical",
|
||||
Priority = ProcessPriorityClass.AboveNormal,
|
||||
PowerPlan = "High Performance",
|
||||
Category = GameCategory.MOBA
|
||||
};
|
||||
}
|
||||
|
||||
private async Task<IntPtr?> CalculateOptimalAffinityMask(string optimalCores)
|
||||
{
|
||||
try
|
||||
{
|
||||
var topology = await _cpuTopologyService.DetectTopologyAsync();
|
||||
if (topology == null) return null;
|
||||
|
||||
return optimalCores switch
|
||||
{
|
||||
"Physical" => new IntPtr(topology.GetPhysicalCoresAffinityMask()),
|
||||
"P-Cores" => new IntPtr(topology.GetPerformanceCoresAffinityMask()),
|
||||
"E-Cores" => new IntPtr(topology.GetEfficiencyCoresAffinityMask()),
|
||||
"All" => new IntPtr(topology.CalculateAffinityMask(topology.LogicalCores)),
|
||||
_ => null
|
||||
};
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error calculating affinity mask for {OptimalCores}", optimalCores);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private float CalculateGameScore(ProcessFeatures features)
|
||||
{
|
||||
float score = 0.0f;
|
||||
|
||||
// Graphics API indicators (strong indicators)
|
||||
if (features.HasDirectXDlls) score += 0.3f;
|
||||
if (features.HasOpenGLDlls) score += 0.25f;
|
||||
if (features.HasVulkanDlls) score += 0.3f;
|
||||
|
||||
// Audio indicators
|
||||
if (features.HasAudioDlls) score += 0.1f;
|
||||
|
||||
// Location indicators
|
||||
if (features.IsInGamesFolder) score += 0.2f;
|
||||
|
||||
// Keyword indicators
|
||||
if (features.HasGameKeywords) score += 0.15f;
|
||||
|
||||
// Window and resource usage indicators
|
||||
if (features.HasVisibleWindow) score += 0.1f;
|
||||
if (features.IsFullscreen) score += 0.15f;
|
||||
if (features.CpuUsage > 10.0) score += 0.1f;
|
||||
if (features.MemoryUsage > 100 * 1024 * 1024) score += 0.05f; // > 100MB
|
||||
|
||||
// Company indicators
|
||||
var gameCompanies = new[] { "valve", "epic", "ubisoft", "ea", "activision", "blizzard", "steam" };
|
||||
if (gameCompanies.Any(company => features.CompanyName.Contains(company, StringComparison.OrdinalIgnoreCase)))
|
||||
score += 0.1f;
|
||||
|
||||
// Clamp score to [0, 1]
|
||||
return Math.Min(1.0f, Math.Max(0.0f, score));
|
||||
}
|
||||
|
||||
private Dictionary<string, object> ConvertFeaturesToDictionary(ProcessFeatures features)
|
||||
{
|
||||
return new Dictionary<string, object>
|
||||
{
|
||||
["ProcessName"] = features.ProcessName,
|
||||
["HasDirectXDlls"] = features.HasDirectXDlls,
|
||||
["HasOpenGLDlls"] = features.HasOpenGLDlls,
|
||||
["HasVulkanDlls"] = features.HasVulkanDlls,
|
||||
["HasAudioDlls"] = features.HasAudioDlls,
|
||||
["IsInGamesFolder"] = features.IsInGamesFolder,
|
||||
["HasGameKeywords"] = features.HasGameKeywords,
|
||||
["HasVisibleWindow"] = features.HasVisibleWindow,
|
||||
["IsFullscreen"] = features.IsFullscreen,
|
||||
["CpuUsage"] = features.CpuUsage,
|
||||
["MemoryUsage"] = features.MemoryUsage,
|
||||
["CompanyName"] = features.CompanyName
|
||||
};
|
||||
}
|
||||
|
||||
private async Task<bool> HasLoadedDllAsync(ProcessModel process, params string[] dllNames)
|
||||
{
|
||||
try
|
||||
{
|
||||
// Simplified check - in real implementation would check loaded modules
|
||||
// For now, check if executable path contains any of the DLL indicators
|
||||
var execPath = process.ExecutablePath?.ToLower() ?? string.Empty;
|
||||
return dllNames.Any(dll => execPath.Contains(dll.ToLower()));
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogDebug(ex, "Error checking DLLs for process {ProcessName}", process.Name);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private float EstimateFrameRate(ProcessModel process)
|
||||
{
|
||||
// Simplified frame rate estimation based on CPU usage patterns
|
||||
// In real implementation, would use performance counters or graphics APIs
|
||||
if (process.CpuUsage > 20.0)
|
||||
return 60.0f; // Assume 60 FPS for high CPU usage games
|
||||
else if (process.CpuUsage > 10.0)
|
||||
return 30.0f; // Assume 30 FPS for moderate CPU usage
|
||||
else
|
||||
return 0.0f; // Not actively rendering
|
||||
}
|
||||
|
||||
private static bool IsLikelyGame(ProcessModel process)
|
||||
{
|
||||
var gameIndicators = new[]
|
||||
{
|
||||
"game", "launcher", "client", "engine", "unity", "unreal",
|
||||
"dx11", "dx12", "vulkan", "opengl"
|
||||
};
|
||||
|
||||
var processName = process.Name.ToLower();
|
||||
var executablePath = process.ExecutablePath?.ToLower() ?? "";
|
||||
|
||||
return gameIndicators.Any(indicator =>
|
||||
processName.Contains(indicator) || executablePath.Contains(indicator)) ||
|
||||
process.HasVisibleWindow && process.CpuUsage > 5.0; // High CPU with window
|
||||
}
|
||||
|
||||
private GameProfile CreateGenericGameProfile(ProcessModel process)
|
||||
{
|
||||
return new GameProfile
|
||||
{
|
||||
Name = $"Generic Game: {process.Name}",
|
||||
ProcessName = process.Name,
|
||||
OptimalCores = "Physical",
|
||||
Priority = ProcessPriorityClass.AboveNormal,
|
||||
PowerPlan = "Balanced",
|
||||
Category = GameCategory.Unknown,
|
||||
Description = "Automatically detected game"
|
||||
};
|
||||
}
|
||||
|
||||
private static Process? GetParentProcess(int processId)
|
||||
{
|
||||
try
|
||||
{
|
||||
using var process = Process.GetProcessById(processId);
|
||||
var parentId = GetParentProcessId(processId);
|
||||
return parentId > 0 ? Process.GetProcessById(parentId) : null;
|
||||
}
|
||||
catch
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static int GetParentProcessId(int processId)
|
||||
{
|
||||
// Implementation would use WMI or P/Invoke to get parent process ID
|
||||
// Simplified for now
|
||||
return 0;
|
||||
}
|
||||
|
||||
private static string? GetSteamInstallPath()
|
||||
{
|
||||
try
|
||||
{
|
||||
using var key = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\WOW6432Node\Valve\Steam") ??
|
||||
Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Valve\Steam");
|
||||
return key?.GetValue("InstallPath")?.ToString();
|
||||
}
|
||||
catch
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static string? GetEpicGamesInstallPath()
|
||||
{
|
||||
try
|
||||
{
|
||||
var epicPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData),
|
||||
"Epic", "EpicGamesLauncher");
|
||||
return Directory.Exists(epicPath) ? epicPath : null;
|
||||
}
|
||||
catch
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+112
-136
@@ -1,136 +1,112 @@
|
||||
/*
|
||||
* ThreadPilot - Advanced Windows Process and Power Plan Manager
|
||||
* Copyright (C) 2025 Prime Build
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published by
|
||||
* the Free Software Foundation, version 3 only.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
namespace ThreadPilot.Services
|
||||
{
|
||||
using System;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Win32;
|
||||
|
||||
/// <summary>
|
||||
/// Service for managing Windows Game Mode settings
|
||||
/// Windows Game Mode can interfere with CPU Sets and affinity, particularly on AMD systems
|
||||
/// Reference: CPU Set Setter warning system.
|
||||
/// </summary>
|
||||
public class GameModeService : IGameModeService
|
||||
{
|
||||
private readonly ILogger<GameModeService> logger;
|
||||
private const string GameBarKeyPath = @"Software\Microsoft\GameBar";
|
||||
private const string GameModeValueName = "AutoGameModeEnabled";
|
||||
|
||||
public GameModeService(ILogger<GameModeService> logger)
|
||||
{
|
||||
this.logger = logger ?? throw new ArgumentNullException(nameof(logger));
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public async Task<bool> IsGameModeEnabledAsync()
|
||||
{
|
||||
await Task.CompletedTask; // Make async for consistency
|
||||
|
||||
try
|
||||
{
|
||||
using var key = Registry.CurrentUser.OpenSubKey(GameBarKeyPath, writable: false);
|
||||
if (key == null)
|
||||
{
|
||||
this.logger.LogDebug("GameBar registry key not found, assuming Game Mode is disabled");
|
||||
return false;
|
||||
}
|
||||
|
||||
var value = key.GetValue(GameModeValueName);
|
||||
if (value is int intValue)
|
||||
{
|
||||
bool isEnabled = intValue != 0;
|
||||
this.logger.LogDebug("Game Mode status: {Status}", isEnabled ? "Enabled" : "Disabled");
|
||||
return isEnabled;
|
||||
}
|
||||
|
||||
this.logger.LogDebug("GameMode value not found, assuming disabled");
|
||||
return false;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
this.logger.LogWarning(ex, "Failed to read Game Mode registry key, assuming disabled");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public async Task<bool> SetGameModeAsync(bool enabled)
|
||||
{
|
||||
await Task.CompletedTask; // Make async for consistency
|
||||
|
||||
try
|
||||
{
|
||||
using var key = Registry.CurrentUser.OpenSubKey(GameBarKeyPath, writable: true);
|
||||
if (key == null)
|
||||
{
|
||||
this.logger.LogWarning("GameBar registry key not found, cannot modify Game Mode");
|
||||
return false;
|
||||
}
|
||||
|
||||
key.SetValue(GameModeValueName, enabled ? 1 : 0, RegistryValueKind.DWord);
|
||||
this.logger.LogInformation("Set Windows Game Mode to {State}", enabled ? "enabled" : "disabled");
|
||||
return true;
|
||||
}
|
||||
catch (UnauthorizedAccessException ex)
|
||||
{
|
||||
this.logger.LogWarning(ex, "Insufficient permissions to modify Game Mode registry key");
|
||||
return false;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
this.logger.LogError(ex, "Failed to set Game Mode to {State}", enabled ? "enabled" : "disabled");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public async Task<bool> DisableGameModeForAffinityAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
bool isEnabled = await this.IsGameModeEnabledAsync();
|
||||
if (!isEnabled)
|
||||
{
|
||||
this.logger.LogDebug("Game Mode already disabled, no action needed");
|
||||
return false;
|
||||
}
|
||||
|
||||
this.logger.LogInformation("Game Mode is enabled, disabling for better CPU affinity control");
|
||||
bool success = await this.SetGameModeAsync(false);
|
||||
|
||||
if (success)
|
||||
{
|
||||
this.logger.LogInformation("Successfully disabled Windows Game Mode for CPU affinity optimization");
|
||||
}
|
||||
else
|
||||
{
|
||||
this.logger.LogWarning("Failed to disable Game Mode, CPU affinity may be affected");
|
||||
}
|
||||
|
||||
return success;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
this.logger.LogError(ex, "Error disabling Game Mode for affinity");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
namespace ThreadPilot.Services
|
||||
{
|
||||
using System;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Win32;
|
||||
|
||||
public class GameModeService : IGameModeService
|
||||
{
|
||||
private readonly ILogger<GameModeService> logger;
|
||||
private const string GameBarKeyPath = @"Software\Microsoft\GameBar";
|
||||
private const string GameModeValueName = "AutoGameModeEnabled";
|
||||
|
||||
public GameModeService(ILogger<GameModeService> logger)
|
||||
{
|
||||
this.logger = logger ?? throw new ArgumentNullException(nameof(logger));
|
||||
}
|
||||
|
||||
public async Task<bool> IsGameModeEnabledAsync()
|
||||
{
|
||||
await Task.CompletedTask; // Make async for consistency
|
||||
|
||||
try
|
||||
{
|
||||
using var key = Registry.CurrentUser.OpenSubKey(GameBarKeyPath, writable: false);
|
||||
if (key == null)
|
||||
{
|
||||
this.logger.LogDebug("GameBar registry key not found, assuming Game Mode is disabled");
|
||||
return false;
|
||||
}
|
||||
|
||||
var value = key.GetValue(GameModeValueName);
|
||||
if (value is int intValue)
|
||||
{
|
||||
bool isEnabled = intValue != 0;
|
||||
this.logger.LogDebug("Game Mode status: {Status}", isEnabled ? "Enabled" : "Disabled");
|
||||
return isEnabled;
|
||||
}
|
||||
|
||||
this.logger.LogDebug("GameMode value not found, assuming disabled");
|
||||
return false;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
this.logger.LogWarning(ex, "Failed to read Game Mode registry key, assuming disabled");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<bool> SetGameModeAsync(bool enabled)
|
||||
{
|
||||
await Task.CompletedTask; // Make async for consistency
|
||||
|
||||
try
|
||||
{
|
||||
using var key = Registry.CurrentUser.OpenSubKey(GameBarKeyPath, writable: true);
|
||||
if (key == null)
|
||||
{
|
||||
this.logger.LogWarning("GameBar registry key not found, cannot modify Game Mode");
|
||||
return false;
|
||||
}
|
||||
|
||||
key.SetValue(GameModeValueName, enabled ? 1 : 0, RegistryValueKind.DWord);
|
||||
this.logger.LogInformation("Set Windows Game Mode to {State}", enabled ? "enabled" : "disabled");
|
||||
return true;
|
||||
}
|
||||
catch (UnauthorizedAccessException ex)
|
||||
{
|
||||
this.logger.LogWarning(ex, "Insufficient permissions to modify Game Mode registry key");
|
||||
return false;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
this.logger.LogError(ex, "Failed to set Game Mode to {State}", enabled ? "enabled" : "disabled");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<bool> DisableGameModeForAffinityAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
bool isEnabled = await this.IsGameModeEnabledAsync();
|
||||
if (!isEnabled)
|
||||
{
|
||||
this.logger.LogDebug("Game Mode already disabled, no action needed");
|
||||
return false;
|
||||
}
|
||||
|
||||
this.logger.LogInformation("Game Mode is enabled, disabling for better CPU affinity control");
|
||||
bool success = await this.SetGameModeAsync(false);
|
||||
|
||||
if (success)
|
||||
{
|
||||
this.logger.LogInformation("Successfully disabled Windows Game Mode for CPU affinity optimization");
|
||||
}
|
||||
else
|
||||
{
|
||||
this.logger.LogWarning("Failed to disable Game Mode, CPU affinity may be affected");
|
||||
}
|
||||
|
||||
return success;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
this.logger.LogError(ex, "Error disabling Game Mode for affinity");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,33 +1,30 @@
|
||||
namespace ThreadPilot.Services
|
||||
{
|
||||
using System;
|
||||
using System.Net.Http;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using ThreadPilot.Services.Abstractions;
|
||||
|
||||
/// <summary>
|
||||
/// HTTP client wrapper for GitHub release metadata.
|
||||
/// </summary>
|
||||
public sealed class GitHubReleaseClient : IGitHubReleaseClient
|
||||
{
|
||||
private readonly HttpClient httpClient;
|
||||
|
||||
public GitHubReleaseClient(HttpClient httpClient)
|
||||
{
|
||||
this.httpClient = httpClient ?? throw new ArgumentNullException(nameof(httpClient));
|
||||
}
|
||||
|
||||
public Task<string> GetLatestReleaseJsonAsync(string owner, string repo, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var url = $"https://api.github.com/repos/{owner}/{repo}/releases/latest";
|
||||
return this.httpClient.GetStringAsync(url, cancellationToken);
|
||||
}
|
||||
|
||||
public Task<string> GetReleasesJsonAsync(string owner, string repo, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var url = $"https://api.github.com/repos/{owner}/{repo}/releases";
|
||||
return this.httpClient.GetStringAsync(url, cancellationToken);
|
||||
}
|
||||
}
|
||||
}
|
||||
namespace ThreadPilot.Services
|
||||
{
|
||||
using System;
|
||||
using System.Net.Http;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using ThreadPilot.Services.Abstractions;
|
||||
|
||||
public sealed class GitHubReleaseClient : IGitHubReleaseClient
|
||||
{
|
||||
private readonly HttpClient httpClient;
|
||||
|
||||
public GitHubReleaseClient(HttpClient httpClient)
|
||||
{
|
||||
this.httpClient = httpClient ?? throw new ArgumentNullException(nameof(httpClient));
|
||||
}
|
||||
|
||||
public Task<string> GetLatestReleaseJsonAsync(string owner, string repo, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var url = $"https://api.github.com/repos/{owner}/{repo}/releases/latest";
|
||||
return this.httpClient.GetStringAsync(url, cancellationToken);
|
||||
}
|
||||
|
||||
public Task<string> GetReleasesJsonAsync(string owner, string repo, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var url = $"https://api.github.com/repos/{owner}/{repo}/releases";
|
||||
return this.httpClient.GetStringAsync(url, cancellationToken);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+127
-143
@@ -1,143 +1,127 @@
|
||||
/*
|
||||
* ThreadPilot - Advanced Windows Process and Power Plan Manager
|
||||
* Copyright (C) 2025 Prime Build
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published by
|
||||
* the Free Software Foundation, version 3 only.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
namespace ThreadPilot.Services
|
||||
{
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using ThreadPilot.Services.Abstractions;
|
||||
|
||||
public sealed class GitHubUpdateChecker
|
||||
{
|
||||
private readonly IGitHubReleaseClient gitHubReleaseClient;
|
||||
|
||||
private record LatestRelease(
|
||||
string Tag_name,
|
||||
bool Prerelease,
|
||||
bool Draft,
|
||||
string Html_url,
|
||||
IReadOnlyList<LatestReleaseAsset>? Assets);
|
||||
|
||||
private record LatestReleaseAsset(string Name, string Browser_download_url, long Size);
|
||||
|
||||
public GitHubUpdateChecker(IGitHubReleaseClient gitHubReleaseClient)
|
||||
{
|
||||
this.gitHubReleaseClient = gitHubReleaseClient ?? throw new ArgumentNullException(nameof(gitHubReleaseClient));
|
||||
}
|
||||
|
||||
public async Task<(Version? latest, string? releaseUrl)> GetLatestVersionAsync(
|
||||
string owner,
|
||||
string repo,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(owner))
|
||||
{
|
||||
throw new ArgumentException("Owner is required", nameof(owner));
|
||||
}
|
||||
|
||||
if (string.IsNullOrWhiteSpace(repo))
|
||||
{
|
||||
throw new ArgumentException("Repository is required", nameof(repo));
|
||||
}
|
||||
|
||||
var json = await this.gitHubReleaseClient.GetLatestReleaseJsonAsync(owner, repo, cancellationToken);
|
||||
var release = JsonSerializer.Deserialize<LatestRelease>(json, new JsonSerializerOptions
|
||||
{
|
||||
PropertyNameCaseInsensitive = true,
|
||||
});
|
||||
|
||||
if (release is null || release.Draft || release.Prerelease || string.IsNullOrWhiteSpace(release.Tag_name))
|
||||
{
|
||||
return (null, null);
|
||||
}
|
||||
|
||||
var tag = release.Tag_name.Trim();
|
||||
if (tag.StartsWith("v", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
tag = tag[1..];
|
||||
}
|
||||
|
||||
var sanitized = tag.Split('-', '+')[0];
|
||||
|
||||
return Version.TryParse(sanitized, out var version)
|
||||
? (version, release.Html_url)
|
||||
: (null, release.Html_url);
|
||||
}
|
||||
|
||||
public async Task<UpdateReleaseInfo?> GetLatestReleaseInfoAsync(
|
||||
string owner,
|
||||
string repo,
|
||||
bool includePrereleases = false,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(owner))
|
||||
{
|
||||
throw new ArgumentException("Owner is required", nameof(owner));
|
||||
}
|
||||
|
||||
if (string.IsNullOrWhiteSpace(repo))
|
||||
{
|
||||
throw new ArgumentException("Repository is required", nameof(repo));
|
||||
}
|
||||
|
||||
var json = await this.gitHubReleaseClient.GetReleasesJsonAsync(owner, repo, cancellationToken).ConfigureAwait(false);
|
||||
var releases = JsonSerializer.Deserialize<List<LatestRelease>>(json, new JsonSerializerOptions
|
||||
{
|
||||
PropertyNameCaseInsensitive = true,
|
||||
});
|
||||
|
||||
if (releases == null || releases.Count == 0)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
return releases
|
||||
.Where(release => !release.Draft)
|
||||
.Where(release => includePrereleases || !release.Prerelease)
|
||||
.Select(TryMapRelease)
|
||||
.Where(release => release != null)
|
||||
.Cast<UpdateReleaseInfo>()
|
||||
.OrderByDescending(release => release.Version)
|
||||
.FirstOrDefault();
|
||||
}
|
||||
|
||||
private static UpdateReleaseInfo? TryMapRelease(LatestRelease release)
|
||||
{
|
||||
if (!SemanticVersion.TryParse(release.Tag_name, out var version) ||
|
||||
string.IsNullOrWhiteSpace(release.Html_url) ||
|
||||
!Uri.TryCreate(release.Html_url, UriKind.Absolute, out var releasePageUrl))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var assets = (release.Assets ?? Array.Empty<LatestReleaseAsset>())
|
||||
.Where(asset => !string.IsNullOrWhiteSpace(asset.Name))
|
||||
.Where(asset => Uri.TryCreate(asset.Browser_download_url, UriKind.Absolute, out _))
|
||||
.Select(asset => new UpdateAsset(
|
||||
asset.Name,
|
||||
new Uri(asset.Browser_download_url, UriKind.Absolute),
|
||||
asset.Size))
|
||||
.ToArray();
|
||||
|
||||
return new UpdateReleaseInfo(version, release.Tag_name, releasePageUrl, release.Prerelease, assets);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
namespace ThreadPilot.Services
|
||||
{
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using ThreadPilot.Services.Abstractions;
|
||||
|
||||
public sealed class GitHubUpdateChecker
|
||||
{
|
||||
private readonly IGitHubReleaseClient gitHubReleaseClient;
|
||||
|
||||
private record LatestRelease(
|
||||
string Tag_name,
|
||||
bool Prerelease,
|
||||
bool Draft,
|
||||
string Html_url,
|
||||
IReadOnlyList<LatestReleaseAsset>? Assets);
|
||||
|
||||
private record LatestReleaseAsset(string Name, string Browser_download_url, long Size);
|
||||
|
||||
public GitHubUpdateChecker(IGitHubReleaseClient gitHubReleaseClient)
|
||||
{
|
||||
this.gitHubReleaseClient = gitHubReleaseClient ?? throw new ArgumentNullException(nameof(gitHubReleaseClient));
|
||||
}
|
||||
|
||||
public async Task<(Version? latest, string? releaseUrl)> GetLatestVersionAsync(
|
||||
string owner,
|
||||
string repo,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(owner))
|
||||
{
|
||||
throw new ArgumentException("Owner is required", nameof(owner));
|
||||
}
|
||||
|
||||
if (string.IsNullOrWhiteSpace(repo))
|
||||
{
|
||||
throw new ArgumentException("Repository is required", nameof(repo));
|
||||
}
|
||||
|
||||
var json = await this.gitHubReleaseClient.GetLatestReleaseJsonAsync(owner, repo, cancellationToken);
|
||||
var release = JsonSerializer.Deserialize<LatestRelease>(json, new JsonSerializerOptions
|
||||
{
|
||||
PropertyNameCaseInsensitive = true,
|
||||
});
|
||||
|
||||
if (release is null || release.Draft || release.Prerelease || string.IsNullOrWhiteSpace(release.Tag_name))
|
||||
{
|
||||
return (null, null);
|
||||
}
|
||||
|
||||
var tag = release.Tag_name.Trim();
|
||||
if (tag.StartsWith("v", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
tag = tag[1..];
|
||||
}
|
||||
|
||||
var sanitized = tag.Split('-', '+')[0];
|
||||
|
||||
return Version.TryParse(sanitized, out var version)
|
||||
? (version, release.Html_url)
|
||||
: (null, release.Html_url);
|
||||
}
|
||||
|
||||
public async Task<UpdateReleaseInfo?> GetLatestReleaseInfoAsync(
|
||||
string owner,
|
||||
string repo,
|
||||
bool includePrereleases = false,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(owner))
|
||||
{
|
||||
throw new ArgumentException("Owner is required", nameof(owner));
|
||||
}
|
||||
|
||||
if (string.IsNullOrWhiteSpace(repo))
|
||||
{
|
||||
throw new ArgumentException("Repository is required", nameof(repo));
|
||||
}
|
||||
|
||||
var json = await this.gitHubReleaseClient.GetReleasesJsonAsync(owner, repo, cancellationToken).ConfigureAwait(false);
|
||||
var releases = JsonSerializer.Deserialize<List<LatestRelease>>(json, new JsonSerializerOptions
|
||||
{
|
||||
PropertyNameCaseInsensitive = true,
|
||||
});
|
||||
|
||||
if (releases == null || releases.Count == 0)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
return releases
|
||||
.Where(release => !release.Draft)
|
||||
.Where(release => includePrereleases || !release.Prerelease)
|
||||
.Select(TryMapRelease)
|
||||
.Where(release => release != null)
|
||||
.Cast<UpdateReleaseInfo>()
|
||||
.OrderByDescending(release => release.Version)
|
||||
.FirstOrDefault();
|
||||
}
|
||||
|
||||
private static UpdateReleaseInfo? TryMapRelease(LatestRelease release)
|
||||
{
|
||||
if (!SemanticVersion.TryParse(release.Tag_name, out var version) ||
|
||||
string.IsNullOrWhiteSpace(release.Html_url) ||
|
||||
!Uri.TryCreate(release.Html_url, UriKind.Absolute, out var releasePageUrl))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var assets = (release.Assets ?? Array.Empty<LatestReleaseAsset>())
|
||||
.Where(asset => !string.IsNullOrWhiteSpace(asset.Name))
|
||||
.Where(asset => Uri.TryCreate(asset.Browser_download_url, UriKind.Absolute, out _))
|
||||
.Select(asset => new UpdateAsset(
|
||||
asset.Name,
|
||||
new Uri(asset.Browser_download_url, UriKind.Absolute),
|
||||
asset.Size))
|
||||
.ToArray();
|
||||
|
||||
return new UpdateReleaseInfo(version, release.Tag_name, releasePageUrl, release.Prerelease, assets);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,44 +1,44 @@
|
||||
/*
|
||||
* ThreadPilot - HTTP downloads for update assets.
|
||||
*/
|
||||
namespace ThreadPilot.Services
|
||||
{
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Net.Http;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
public sealed class HttpUpdateDownloadClient : IUpdateDownloadClient
|
||||
{
|
||||
private readonly HttpClient httpClient;
|
||||
|
||||
public HttpUpdateDownloadClient(HttpClient httpClient)
|
||||
{
|
||||
this.httpClient = httpClient ?? throw new ArgumentNullException(nameof(httpClient));
|
||||
}
|
||||
|
||||
public async Task DownloadFileAsync(Uri uri, string destinationPath, CancellationToken cancellationToken = default)
|
||||
{
|
||||
using var response = await this.httpClient.GetAsync(uri, HttpCompletionOption.ResponseHeadersRead, cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
response.EnsureSuccessStatusCode();
|
||||
|
||||
await using var source = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
|
||||
await using var destination = File.Create(destinationPath);
|
||||
await source.CopyToAsync(destination, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
public async Task<string?> TryDownloadStringAsync(Uri uri, CancellationToken cancellationToken = default)
|
||||
{
|
||||
try
|
||||
{
|
||||
return await this.httpClient.GetStringAsync(uri, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
catch (HttpRequestException)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
/*
|
||||
* ThreadPilot - HTTP downloads for update assets.
|
||||
*/
|
||||
namespace ThreadPilot.Services
|
||||
{
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Net.Http;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
public sealed class HttpUpdateDownloadClient : IUpdateDownloadClient
|
||||
{
|
||||
private readonly HttpClient httpClient;
|
||||
|
||||
public HttpUpdateDownloadClient(HttpClient httpClient)
|
||||
{
|
||||
this.httpClient = httpClient ?? throw new ArgumentNullException(nameof(httpClient));
|
||||
}
|
||||
|
||||
public async Task DownloadFileAsync(Uri uri, string destinationPath, CancellationToken cancellationToken = default)
|
||||
{
|
||||
using var response = await this.httpClient.GetAsync(uri, HttpCompletionOption.ResponseHeadersRead, cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
response.EnsureSuccessStatusCode();
|
||||
|
||||
await using var source = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
|
||||
await using var destination = File.Create(destinationPath);
|
||||
await source.CopyToAsync(destination, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
public async Task<string?> TryDownloadStringAsync(Uri uri, CancellationToken cancellationToken = default)
|
||||
{
|
||||
try
|
||||
{
|
||||
return await this.httpClient.GetStringAsync(uri, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
catch (HttpRequestException)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,42 +1,42 @@
|
||||
namespace ThreadPilot.Services
|
||||
{
|
||||
public enum ActivityAuditSeverity
|
||||
{
|
||||
Info,
|
||||
Success,
|
||||
Warning,
|
||||
Error,
|
||||
}
|
||||
|
||||
public sealed record ActivityAuditEntry
|
||||
{
|
||||
public DateTime Timestamp { get; init; }
|
||||
|
||||
public string Category { get; init; } = string.Empty;
|
||||
|
||||
public ActivityAuditSeverity Severity { get; init; }
|
||||
|
||||
public string Message { get; init; } = string.Empty;
|
||||
|
||||
public string? Details { get; init; }
|
||||
}
|
||||
|
||||
public interface IActivityAuditService
|
||||
{
|
||||
event EventHandler<ActivityAuditEntry>? EntryAdded;
|
||||
|
||||
Task LogInfoAsync(string category, string message, string? details = null);
|
||||
|
||||
Task LogSuccessAsync(string category, string message, string? details = null);
|
||||
|
||||
Task LogWarningAsync(string category, string message, string? details = null);
|
||||
|
||||
Task LogErrorAsync(string category, string message, string? details = null);
|
||||
|
||||
Task LogUserActionAsync(string action, string details, string? context = null);
|
||||
|
||||
Task<IReadOnlyList<ActivityAuditEntry>> GetEntriesAsync(DateTime? fromDate = null, DateTime? toDate = null);
|
||||
|
||||
Task ClearDisplayAsync();
|
||||
}
|
||||
}
|
||||
namespace ThreadPilot.Services
|
||||
{
|
||||
public enum ActivityAuditSeverity
|
||||
{
|
||||
Info,
|
||||
Success,
|
||||
Warning,
|
||||
Error,
|
||||
}
|
||||
|
||||
public sealed record ActivityAuditEntry
|
||||
{
|
||||
public DateTime Timestamp { get; init; }
|
||||
|
||||
public string Category { get; init; } = string.Empty;
|
||||
|
||||
public ActivityAuditSeverity Severity { get; init; }
|
||||
|
||||
public string Message { get; init; } = string.Empty;
|
||||
|
||||
public string? Details { get; init; }
|
||||
}
|
||||
|
||||
public interface IActivityAuditService
|
||||
{
|
||||
event EventHandler<ActivityAuditEntry>? EntryAdded;
|
||||
|
||||
Task LogInfoAsync(string category, string message, string? details = null);
|
||||
|
||||
Task LogSuccessAsync(string category, string message, string? details = null);
|
||||
|
||||
Task LogWarningAsync(string category, string message, string? details = null);
|
||||
|
||||
Task LogErrorAsync(string category, string message, string? details = null);
|
||||
|
||||
Task LogUserActionAsync(string action, string details, string? context = null);
|
||||
|
||||
Task<IReadOnlyList<ActivityAuditEntry>> GetEntriesAsync(DateTime? fromDate = null, DateTime? toDate = null);
|
||||
|
||||
Task ClearDisplayAsync();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,101 +1,49 @@
|
||||
/*
|
||||
* ThreadPilot - Advanced Windows Process and Power Plan Manager
|
||||
* Copyright (C) 2025 Prime Build
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published by
|
||||
* the Free Software Foundation, version 3 only.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
namespace ThreadPilot.Services
|
||||
{
|
||||
using System;
|
||||
using System.Threading.Tasks;
|
||||
using ThreadPilot.Models;
|
||||
|
||||
/// <summary>
|
||||
/// Service for managing application settings.
|
||||
/// </summary>
|
||||
public interface IApplicationSettingsService
|
||||
{
|
||||
/// <summary>
|
||||
/// Event fired when settings are changed
|
||||
/// </summary>
|
||||
event EventHandler<ApplicationSettingsChangedEventArgs>? SettingsChanged;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the current application settings.
|
||||
/// </summary>
|
||||
ApplicationSettingsModel Settings { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Loads settings from storage.
|
||||
/// </summary>
|
||||
Task LoadSettingsAsync();
|
||||
|
||||
/// <summary>
|
||||
/// Saves current settings to storage.
|
||||
/// </summary>
|
||||
Task SaveSettingsAsync();
|
||||
|
||||
/// <summary>
|
||||
/// Updates settings and saves them.
|
||||
/// </summary>
|
||||
Task UpdateSettingsAsync(ApplicationSettingsModel newSettings);
|
||||
|
||||
/// <summary>
|
||||
/// Resets settings to default values.
|
||||
/// </summary>
|
||||
Task ResetToDefaultsAsync();
|
||||
|
||||
/// <summary>
|
||||
/// Gets the settings file path.
|
||||
/// </summary>
|
||||
string GetSettingsFilePath();
|
||||
|
||||
/// <summary>
|
||||
/// Validates settings and fixes any invalid values.
|
||||
/// </summary>
|
||||
void ValidateAndFixSettings();
|
||||
|
||||
/// <summary>
|
||||
/// Exports settings to a file.
|
||||
/// </summary>
|
||||
Task ExportSettingsAsync(string filePath);
|
||||
|
||||
/// <summary>
|
||||
/// Imports settings from a file.
|
||||
/// </summary>
|
||||
Task ImportSettingsAsync(string filePath);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Event args for settings changed event.
|
||||
/// </summary>
|
||||
public class ApplicationSettingsChangedEventArgs : EventArgs
|
||||
{
|
||||
public ApplicationSettingsModel OldSettings { get; }
|
||||
|
||||
public ApplicationSettingsModel NewSettings { get; }
|
||||
|
||||
public string[] ChangedProperties { get; }
|
||||
|
||||
public ApplicationSettingsChangedEventArgs(
|
||||
ApplicationSettingsModel oldSettings,
|
||||
ApplicationSettingsModel newSettings,
|
||||
string[] changedProperties)
|
||||
{
|
||||
this.OldSettings = oldSettings;
|
||||
this.NewSettings = newSettings;
|
||||
this.ChangedProperties = changedProperties;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
namespace ThreadPilot.Services
|
||||
{
|
||||
using System;
|
||||
using System.Threading.Tasks;
|
||||
using ThreadPilot.Models;
|
||||
|
||||
public interface IApplicationSettingsService
|
||||
{
|
||||
event EventHandler<ApplicationSettingsChangedEventArgs>? SettingsChanged;
|
||||
|
||||
ApplicationSettingsModel Settings { get; }
|
||||
|
||||
Task LoadSettingsAsync();
|
||||
|
||||
Task SaveSettingsAsync();
|
||||
|
||||
Task UpdateSettingsAsync(ApplicationSettingsModel newSettings);
|
||||
|
||||
Task ResetToDefaultsAsync();
|
||||
|
||||
string GetSettingsFilePath();
|
||||
|
||||
void ValidateAndFixSettings();
|
||||
|
||||
Task ExportSettingsAsync(string filePath);
|
||||
|
||||
Task ImportSettingsAsync(string filePath);
|
||||
}
|
||||
|
||||
public class ApplicationSettingsChangedEventArgs : EventArgs
|
||||
{
|
||||
public ApplicationSettingsModel OldSettings { get; }
|
||||
|
||||
public ApplicationSettingsModel NewSettings { get; }
|
||||
|
||||
public string[] ChangedProperties { get; }
|
||||
|
||||
public ApplicationSettingsChangedEventArgs(
|
||||
ApplicationSettingsModel oldSettings,
|
||||
ApplicationSettingsModel newSettings,
|
||||
string[] changedProperties)
|
||||
{
|
||||
this.OldSettings = oldSettings;
|
||||
this.NewSettings = newSettings;
|
||||
this.ChangedProperties = changedProperties;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+44
-117
@@ -1,117 +1,44 @@
|
||||
/*
|
||||
* ThreadPilot - Advanced Windows Process and Power Plan Manager
|
||||
* Copyright (C) 2025 Prime Build
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published by
|
||||
* the Free Software Foundation, version 3 only.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
namespace ThreadPilot.Services
|
||||
{
|
||||
using System;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
/// <summary>
|
||||
/// Interface for managing Windows autostart functionality.
|
||||
/// </summary>
|
||||
public interface IAutostartService
|
||||
{
|
||||
/// <summary>
|
||||
/// Occurs when autostart state changes.
|
||||
/// </summary>
|
||||
event EventHandler<AutostartStatusChangedEventArgs>? AutostartStatusChanged;
|
||||
|
||||
/// <summary>
|
||||
/// Gets a value indicating whether gets whether the application is currently set to autostart with Windows.
|
||||
/// </summary>
|
||||
bool IsAutostartEnabled { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the current autostart registry entry path.
|
||||
/// </summary>
|
||||
string? AutostartPath { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Enables autostart with Windows.
|
||||
/// </summary>
|
||||
/// <param name="startMinimized">Whether to start the application minimized.</param>
|
||||
/// <returns>True if successful, false otherwise.</returns>
|
||||
Task<bool> EnableAutostartAsync(bool startMinimized = true);
|
||||
|
||||
/// <summary>
|
||||
/// Disables autostart with Windows.
|
||||
/// </summary>
|
||||
/// <returns>True if successful, false otherwise.</returns>
|
||||
Task<bool> DisableAutostartAsync();
|
||||
|
||||
/// <summary>
|
||||
/// Checks if autostart is currently enabled.
|
||||
/// </summary>
|
||||
/// <returns>True if autostart is enabled, false otherwise.</returns>
|
||||
Task<bool> CheckAutostartStatusAsync();
|
||||
|
||||
/// <summary>
|
||||
/// Updates the autostart entry with new parameters.
|
||||
/// </summary>
|
||||
/// <param name="startMinimized">Whether to start minimized.</param>
|
||||
/// <returns>True if successful, false otherwise.</returns>
|
||||
Task<bool> UpdateAutostartAsync(bool startMinimized = true);
|
||||
|
||||
/// <summary>
|
||||
/// Gets the command line arguments for autostart.
|
||||
/// </summary>
|
||||
/// <param name="startMinimized">Whether to include start minimized flag.</param>
|
||||
/// <returns>Command line arguments string.</returns>
|
||||
string GetAutostartArguments(bool startMinimized = true);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Event arguments for autostart status changes.
|
||||
/// </summary>
|
||||
public class AutostartStatusChangedEventArgs : EventArgs
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets a value indicating whether autostart is currently enabled.
|
||||
/// </summary>
|
||||
public bool IsEnabled { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets a value indicating whether startup should launch minimized.
|
||||
/// </summary>
|
||||
public bool StartMinimized { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the registry command value currently used for startup.
|
||||
/// </summary>
|
||||
public string? RegistryPath { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the error that caused the status update when the operation failed.
|
||||
/// </summary>
|
||||
public Exception? Error { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="AutostartStatusChangedEventArgs"/> class.
|
||||
/// </summary>
|
||||
/// <param name="isEnabled">Whether autostart is enabled.</param>
|
||||
/// <param name="startMinimized">Whether startup should launch minimized.</param>
|
||||
/// <param name="registryPath">The autostart registry value when available.</param>
|
||||
/// <param name="error">The failure that occurred, if any.</param>
|
||||
public AutostartStatusChangedEventArgs(bool isEnabled, bool startMinimized = false, string? registryPath = null, Exception? error = null)
|
||||
{
|
||||
this.IsEnabled = isEnabled;
|
||||
this.StartMinimized = startMinimized;
|
||||
this.RegistryPath = registryPath;
|
||||
this.Error = error;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
namespace ThreadPilot.Services
|
||||
{
|
||||
using System;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
public interface IAutostartService
|
||||
{
|
||||
event EventHandler<AutostartStatusChangedEventArgs>? AutostartStatusChanged;
|
||||
|
||||
bool IsAutostartEnabled { get; }
|
||||
|
||||
string? AutostartPath { get; }
|
||||
|
||||
Task<bool> EnableAutostartAsync(bool startMinimized = true);
|
||||
|
||||
Task<bool> DisableAutostartAsync();
|
||||
|
||||
Task<bool> CheckAutostartStatusAsync();
|
||||
|
||||
Task<bool> UpdateAutostartAsync(bool startMinimized = true);
|
||||
|
||||
string GetAutostartArguments(bool startMinimized = true);
|
||||
}
|
||||
|
||||
public class AutostartStatusChangedEventArgs : EventArgs
|
||||
{
|
||||
public bool IsEnabled { get; }
|
||||
|
||||
public bool StartMinimized { get; }
|
||||
|
||||
public string? RegistryPath { get; }
|
||||
|
||||
public Exception? Error { get; }
|
||||
|
||||
public AutostartStatusChangedEventArgs(bool isEnabled, bool startMinimized = false, string? registryPath = null, Exception? error = null)
|
||||
{
|
||||
this.IsEnabled = isEnabled;
|
||||
this.StartMinimized = startMinimized;
|
||||
this.RegistryPath = registryPath;
|
||||
this.Error = error;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,162 +1,77 @@
|
||||
/*
|
||||
* ThreadPilot - Advanced Windows Process and Power Plan Manager
|
||||
* Copyright (C) 2025 Prime Build
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published by
|
||||
* the Free Software Foundation, version 3 only.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
namespace ThreadPilot.Services
|
||||
{
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Threading.Tasks;
|
||||
using ThreadPilot.Models;
|
||||
|
||||
/// <summary>
|
||||
/// Event arguments for profile application events.
|
||||
/// </summary>
|
||||
public class ProfileApplicationEventArgs : EventArgs
|
||||
{
|
||||
public ConditionalProcessProfile Profile { get; set; } = new();
|
||||
|
||||
public ProcessModel Process { get; set; } = new();
|
||||
|
||||
public SystemState SystemState { get; set; } = new();
|
||||
|
||||
public bool WasApplied { get; set; }
|
||||
|
||||
public string Reason { get; set; } = string.Empty;
|
||||
|
||||
public DateTime Timestamp { get; set; } = DateTime.UtcNow;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Event arguments for profile conflict events.
|
||||
/// </summary>
|
||||
public class ProfileConflictEventArgs : EventArgs
|
||||
{
|
||||
public List<ConditionalProcessProfile> ConflictingProfiles { get; set; } = new();
|
||||
|
||||
public ProcessModel Process { get; set; } = new();
|
||||
|
||||
public ConditionalProcessProfile SelectedProfile { get; set; } = new();
|
||||
|
||||
public string Resolution { get; set; } = string.Empty;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Service for managing conditional process profiles.
|
||||
/// </summary>
|
||||
public interface IConditionalProfileService
|
||||
{
|
||||
/// <summary>
|
||||
/// Initialize the conditional profile service.
|
||||
/// </summary>
|
||||
Task InitializeAsync();
|
||||
|
||||
/// <summary>
|
||||
/// Add a conditional profile.
|
||||
/// </summary>
|
||||
Task AddProfileAsync(ConditionalProcessProfile profile);
|
||||
|
||||
/// <summary>
|
||||
/// Remove a conditional profile.
|
||||
/// </summary>
|
||||
Task RemoveProfileAsync(string profileId);
|
||||
|
||||
/// <summary>
|
||||
/// Update an existing conditional profile.
|
||||
/// </summary>
|
||||
Task UpdateProfileAsync(ConditionalProcessProfile profile);
|
||||
|
||||
/// <summary>
|
||||
/// Get all conditional profiles.
|
||||
/// </summary>
|
||||
Task<List<ConditionalProcessProfile>> GetAllProfilesAsync();
|
||||
|
||||
/// <summary>
|
||||
/// Get profiles for a specific process.
|
||||
/// </summary>
|
||||
Task<List<ConditionalProcessProfile>> GetProfilesForProcessAsync(string processName);
|
||||
|
||||
/// <summary>
|
||||
/// Evaluate all profiles for a process and return applicable ones.
|
||||
/// </summary>
|
||||
Task<List<ConditionalProcessProfile>> EvaluateProfilesAsync(ProcessModel process);
|
||||
|
||||
/// <summary>
|
||||
/// Apply the best matching profile for a process.
|
||||
/// </summary>
|
||||
Task<bool> ApplyBestProfileAsync(ProcessModel process);
|
||||
|
||||
/// <summary>
|
||||
/// Get current system state for condition evaluation.
|
||||
/// </summary>
|
||||
Task<SystemState> GetSystemStateAsync();
|
||||
|
||||
/// <summary>
|
||||
/// Start automatic profile monitoring and application.
|
||||
/// </summary>
|
||||
Task StartMonitoringAsync();
|
||||
|
||||
/// <summary>
|
||||
/// Stop automatic profile monitoring.
|
||||
/// </summary>
|
||||
Task StopMonitoringAsync();
|
||||
|
||||
/// <summary>
|
||||
/// Gets a value indicating whether check if monitoring is active.
|
||||
/// </summary>
|
||||
bool IsMonitoring { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Resolve conflicts when multiple profiles match.
|
||||
/// </summary>
|
||||
ConditionalProcessProfile ResolveProfileConflict(List<ConditionalProcessProfile> conflictingProfiles, ProcessModel process);
|
||||
|
||||
/// <summary>
|
||||
/// Create a default conditional profile template.
|
||||
/// </summary>
|
||||
ConditionalProcessProfile CreateDefaultProfile(string processName);
|
||||
|
||||
/// <summary>
|
||||
/// Validate a conditional profile.
|
||||
/// </summary>
|
||||
Task<(bool IsValid, List<string> Errors)> ValidateProfileAsync(ConditionalProcessProfile profile);
|
||||
|
||||
/// <summary>
|
||||
/// Export profiles to JSON.
|
||||
/// </summary>
|
||||
Task<string> ExportProfilesToJsonAsync();
|
||||
|
||||
/// <summary>
|
||||
/// Import profiles from JSON.
|
||||
/// </summary>
|
||||
Task<int> ImportProfilesFromJsonAsync(string json);
|
||||
|
||||
/// <summary>
|
||||
/// Event raised when a profile is automatically applied
|
||||
/// </summary>
|
||||
event EventHandler<ProfileApplicationEventArgs>? ProfileApplied;
|
||||
|
||||
/// <summary>
|
||||
/// Event raised when profile conflicts are resolved
|
||||
/// </summary>
|
||||
event EventHandler<ProfileConflictEventArgs>? ProfileConflictResolved;
|
||||
|
||||
/// <summary>
|
||||
/// Event raised when system state changes significantly
|
||||
/// </summary>
|
||||
event EventHandler<SystemState>? SystemStateChanged;
|
||||
}
|
||||
}
|
||||
|
||||
namespace ThreadPilot.Services
|
||||
{
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Threading.Tasks;
|
||||
using ThreadPilot.Models;
|
||||
|
||||
public class ProfileApplicationEventArgs : EventArgs
|
||||
{
|
||||
public ConditionalProcessProfile Profile { get; set; } = new();
|
||||
|
||||
public ProcessModel Process { get; set; } = new();
|
||||
|
||||
public SystemState SystemState { get; set; } = new();
|
||||
|
||||
public bool WasApplied { get; set; }
|
||||
|
||||
public string Reason { get; set; } = string.Empty;
|
||||
|
||||
public DateTime Timestamp { get; set; } = DateTime.UtcNow;
|
||||
}
|
||||
|
||||
public class ProfileConflictEventArgs : EventArgs
|
||||
{
|
||||
public List<ConditionalProcessProfile> ConflictingProfiles { get; set; } = new();
|
||||
|
||||
public ProcessModel Process { get; set; } = new();
|
||||
|
||||
public ConditionalProcessProfile SelectedProfile { get; set; } = new();
|
||||
|
||||
public string Resolution { get; set; } = string.Empty;
|
||||
}
|
||||
|
||||
public interface IConditionalProfileService
|
||||
{
|
||||
Task InitializeAsync();
|
||||
|
||||
Task AddProfileAsync(ConditionalProcessProfile profile);
|
||||
|
||||
Task RemoveProfileAsync(string profileId);
|
||||
|
||||
Task UpdateProfileAsync(ConditionalProcessProfile profile);
|
||||
|
||||
Task<List<ConditionalProcessProfile>> GetAllProfilesAsync();
|
||||
|
||||
Task<List<ConditionalProcessProfile>> GetProfilesForProcessAsync(string processName);
|
||||
|
||||
Task<List<ConditionalProcessProfile>> EvaluateProfilesAsync(ProcessModel process);
|
||||
|
||||
Task<bool> ApplyBestProfileAsync(ProcessModel process);
|
||||
|
||||
Task<SystemState> GetSystemStateAsync();
|
||||
|
||||
Task StartMonitoringAsync();
|
||||
|
||||
Task StopMonitoringAsync();
|
||||
|
||||
bool IsMonitoring { get; }
|
||||
|
||||
ConditionalProcessProfile ResolveProfileConflict(List<ConditionalProcessProfile> conflictingProfiles, ProcessModel process);
|
||||
|
||||
ConditionalProcessProfile CreateDefaultProfile(string processName);
|
||||
|
||||
Task<(bool IsValid, List<string> Errors)> ValidateProfileAsync(ConditionalProcessProfile profile);
|
||||
|
||||
Task<string> ExportProfilesToJsonAsync();
|
||||
|
||||
Task<int> ImportProfilesFromJsonAsync(string json);
|
||||
|
||||
event EventHandler<ProfileApplicationEventArgs>? ProfileApplied;
|
||||
|
||||
event EventHandler<ProfileConflictEventArgs>? ProfileConflictResolved;
|
||||
|
||||
event EventHandler<SystemState>? SystemStateChanged;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+47
-120
@@ -1,120 +1,47 @@
|
||||
/*
|
||||
* ThreadPilot - Advanced Windows Process and Power Plan Manager
|
||||
* Copyright (C) 2025 Prime Build
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published by
|
||||
* the Free Software Foundation, version 3 only.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
namespace ThreadPilot.Services
|
||||
{
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.ObjectModel;
|
||||
using System.Threading.Tasks;
|
||||
using ThreadPilot.Models;
|
||||
|
||||
/// <summary>
|
||||
/// Service for managing CPU core affinity masks.
|
||||
/// </summary>
|
||||
public interface ICoreMaskService
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets all available core masks.
|
||||
/// </summary>
|
||||
ObservableCollection<CoreMask> AvailableMasks { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the default mask (all cores).
|
||||
/// </summary>
|
||||
CoreMask? DefaultMask { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Initializes the service and loads masks from storage.
|
||||
/// </summary>
|
||||
Task InitializeAsync();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new core mask.
|
||||
/// </summary>
|
||||
Task<CoreMask> CreateMaskAsync(string name, string description, IEnumerable<bool> boolMask);
|
||||
|
||||
/// <summary>
|
||||
/// Updates an existing mask.
|
||||
/// </summary>
|
||||
Task UpdateMaskAsync(CoreMask mask);
|
||||
|
||||
/// <summary>
|
||||
/// Deletes a mask by ID.
|
||||
/// </summary>
|
||||
Task DeleteMaskAsync(string maskId);
|
||||
|
||||
/// <summary>
|
||||
/// Gets a mask by ID.
|
||||
/// </summary>
|
||||
CoreMask? GetMaskById(string maskId);
|
||||
|
||||
/// <summary>
|
||||
/// Gets a mask by name.
|
||||
/// </summary>
|
||||
CoreMask? GetMaskByName(string name);
|
||||
|
||||
/// <summary>
|
||||
/// Saves all masks to persistent storage.
|
||||
/// </summary>
|
||||
Task SaveMasksAsync();
|
||||
|
||||
/// <summary>
|
||||
/// Loads masks from persistent storage.
|
||||
/// </summary>
|
||||
Task LoadMasksAsync();
|
||||
|
||||
/// <summary>
|
||||
/// Checks if a mask is referenced by any profile or rule (not necessarily active).
|
||||
/// </summary>
|
||||
Task<bool> IsMaskReferencedByProfilesAsync(string maskId);
|
||||
|
||||
/// <summary>
|
||||
/// Checks if a mask is actively applied to any running process.
|
||||
/// </summary>
|
||||
Task<bool> IsMaskActivelyAppliedAsync(string maskId);
|
||||
|
||||
/// <summary>
|
||||
/// Gets the names of profiles/rules that reference a specific mask.
|
||||
/// </summary>
|
||||
Task<IEnumerable<string>> GetProfilesReferencingMaskAsync(string maskId);
|
||||
|
||||
/// <summary>
|
||||
/// Updates all profiles referencing a mask to use the default "All Cores" mask.
|
||||
/// </summary>
|
||||
Task UpdateProfilesToDefaultMaskAsync(string maskId);
|
||||
|
||||
/// <summary>
|
||||
/// Creates default masks for the system based on CPU topology.
|
||||
/// </summary>
|
||||
Task CreateDefaultMasksAsync();
|
||||
|
||||
/// <summary>
|
||||
/// Gets the "All Cores" baseline mask (cannot be deleted).
|
||||
/// </summary>
|
||||
CoreMask? GetAllCoresMask();
|
||||
|
||||
/// <summary>
|
||||
/// Registers that a mask has been applied to a running process.
|
||||
/// </summary>
|
||||
void RegisterMaskApplication(int processId, string maskId);
|
||||
|
||||
/// <summary>
|
||||
/// Unregisters mask tracking when a process exits or a mask is removed.
|
||||
/// </summary>
|
||||
void UnregisterMaskApplication(int processId);
|
||||
}
|
||||
}
|
||||
|
||||
namespace ThreadPilot.Services
|
||||
{
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.ObjectModel;
|
||||
using System.Threading.Tasks;
|
||||
using ThreadPilot.Models;
|
||||
|
||||
public interface ICoreMaskService
|
||||
{
|
||||
ObservableCollection<CoreMask> AvailableMasks { get; }
|
||||
|
||||
CoreMask? DefaultMask { get; }
|
||||
|
||||
Task InitializeAsync();
|
||||
|
||||
Task<CoreMask> CreateMaskAsync(string name, string description, IEnumerable<bool> boolMask);
|
||||
|
||||
Task UpdateMaskAsync(CoreMask mask);
|
||||
|
||||
Task DeleteMaskAsync(string maskId);
|
||||
|
||||
CoreMask? GetMaskById(string maskId);
|
||||
|
||||
CoreMask? GetMaskByName(string name);
|
||||
|
||||
Task SaveMasksAsync();
|
||||
|
||||
Task LoadMasksAsync();
|
||||
|
||||
Task<bool> IsMaskReferencedByProfilesAsync(string maskId);
|
||||
|
||||
Task<bool> IsMaskActivelyAppliedAsync(string maskId);
|
||||
|
||||
Task<IEnumerable<string>> GetProfilesReferencingMaskAsync(string maskId);
|
||||
|
||||
Task UpdateProfilesToDefaultMaskAsync(string maskId);
|
||||
|
||||
Task CreateDefaultMasksAsync();
|
||||
|
||||
CoreMask? GetAllCoresMask();
|
||||
|
||||
void RegisterMaskApplication(int processId, string maskId);
|
||||
|
||||
void UnregisterMaskApplication(int processId);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,27 +1,11 @@
|
||||
/*
|
||||
* ThreadPilot - Advanced Windows Process and Power Plan Manager
|
||||
* Copyright (C) 2025 Prime Build
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published by
|
||||
* the Free Software Foundation, version 3 only.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
namespace ThreadPilot.Services
|
||||
{
|
||||
using ThreadPilot.Models;
|
||||
|
||||
public interface ICpuPresetGenerator
|
||||
{
|
||||
IReadOnlyList<CpuPreset> Generate(
|
||||
CpuTopologySnapshot topology,
|
||||
CpuPresetGenerationOptions? options = null);
|
||||
}
|
||||
}
|
||||
namespace ThreadPilot.Services
|
||||
{
|
||||
using ThreadPilot.Models;
|
||||
|
||||
public interface ICpuPresetGenerator
|
||||
{
|
||||
IReadOnlyList<CpuPreset> Generate(
|
||||
CpuTopologySnapshot topology,
|
||||
CpuPresetGenerationOptions? options = null);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,33 +1,11 @@
|
||||
/*
|
||||
* ThreadPilot - Advanced Windows Process and Power Plan Manager
|
||||
* Copyright (C) 2025 Prime Build
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published by
|
||||
* the Free Software Foundation, version 3 only.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
namespace ThreadPilot.Services
|
||||
{
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using ThreadPilot.Models;
|
||||
|
||||
/// <summary>
|
||||
/// Provides a topology-aware CPU snapshot without applying runtime affinity changes.
|
||||
/// </summary>
|
||||
public interface ICpuTopologyProvider
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets a current CPU topology snapshot.
|
||||
/// </summary>
|
||||
Task<CpuTopologySnapshot> GetTopologySnapshotAsync(CancellationToken cancellationToken = default);
|
||||
}
|
||||
}
|
||||
namespace ThreadPilot.Services
|
||||
{
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using ThreadPilot.Models;
|
||||
|
||||
public interface ICpuTopologyProvider
|
||||
{
|
||||
Task<CpuTopologySnapshot> GetTopologySnapshotAsync(CancellationToken cancellationToken = default);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,87 +1,44 @@
|
||||
/*
|
||||
* ThreadPilot - Advanced Windows Process and Power Plan Manager
|
||||
* Copyright (C) 2025 Prime Build
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published by
|
||||
* the Free Software Foundation, version 3 only.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
namespace ThreadPilot.Services
|
||||
{
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Threading.Tasks;
|
||||
using ThreadPilot.Models;
|
||||
|
||||
/// <summary>
|
||||
/// Service for detecting and managing CPU topology information.
|
||||
/// </summary>
|
||||
public interface ICpuTopologyService
|
||||
{
|
||||
/// <summary>
|
||||
/// Event fired when CPU topology is detected or updated
|
||||
/// </summary>
|
||||
event EventHandler<CpuTopologyDetectedEventArgs>? TopologyDetected;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the current CPU topology information.
|
||||
/// </summary>
|
||||
CpuTopologyModel? CurrentTopology { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Detects CPU topology information.
|
||||
/// </summary>
|
||||
Task<CpuTopologyModel> DetectTopologyAsync();
|
||||
|
||||
/// <summary>
|
||||
/// Gets available affinity presets based on current topology.
|
||||
/// </summary>
|
||||
IEnumerable<CpuAffinityPreset> GetAffinityPresets();
|
||||
|
||||
/// <summary>
|
||||
/// Validates if an affinity mask is valid for the current system.
|
||||
/// </summary>
|
||||
bool IsAffinityMaskValid(long affinityMask);
|
||||
|
||||
/// <summary>
|
||||
/// Gets the maximum number of logical cores supported.
|
||||
/// </summary>
|
||||
int GetMaxLogicalCores();
|
||||
|
||||
/// <summary>
|
||||
/// Refreshes topology information (useful for hot-plug scenarios).
|
||||
/// </summary>
|
||||
Task RefreshTopologyAsync();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Event arguments for CPU topology detection.
|
||||
/// </summary>
|
||||
public class CpuTopologyDetectedEventArgs : EventArgs
|
||||
{
|
||||
public CpuTopologyModel Topology { get; }
|
||||
|
||||
public bool DetectionSuccessful { get; }
|
||||
|
||||
public string? ErrorMessage { get; }
|
||||
|
||||
public DateTime DetectionTime { get; }
|
||||
|
||||
public CpuTopologyDetectedEventArgs(CpuTopologyModel topology, bool successful, string? errorMessage = null)
|
||||
{
|
||||
this.Topology = topology;
|
||||
this.DetectionSuccessful = successful;
|
||||
this.ErrorMessage = errorMessage;
|
||||
this.DetectionTime = DateTime.Now;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
namespace ThreadPilot.Services
|
||||
{
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Threading.Tasks;
|
||||
using ThreadPilot.Models;
|
||||
|
||||
public interface ICpuTopologyService
|
||||
{
|
||||
event EventHandler<CpuTopologyDetectedEventArgs>? TopologyDetected;
|
||||
|
||||
CpuTopologyModel? CurrentTopology { get; }
|
||||
|
||||
Task<CpuTopologyModel> DetectTopologyAsync();
|
||||
|
||||
IEnumerable<CpuAffinityPreset> GetAffinityPresets();
|
||||
|
||||
bool IsAffinityMaskValid(long affinityMask);
|
||||
|
||||
int GetMaxLogicalCores();
|
||||
|
||||
Task RefreshTopologyAsync();
|
||||
}
|
||||
|
||||
public class CpuTopologyDetectedEventArgs : EventArgs
|
||||
{
|
||||
public CpuTopologyModel Topology { get; }
|
||||
|
||||
public bool DetectionSuccessful { get; }
|
||||
|
||||
public string? ErrorMessage { get; }
|
||||
|
||||
public DateTime DetectionTime { get; }
|
||||
|
||||
public CpuTopologyDetectedEventArgs(CpuTopologyModel topology, bool successful, string? errorMessage = null)
|
||||
{
|
||||
this.Topology = topology;
|
||||
this.DetectionSuccessful = successful;
|
||||
this.ErrorMessage = errorMessage;
|
||||
this.DetectionTime = DateTime.Now;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,68 +1,21 @@
|
||||
/*
|
||||
* ThreadPilot - Advanced Windows Process and Power Plan Manager
|
||||
* Copyright (C) 2025 Prime Build
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published by
|
||||
* the Free Software Foundation, version 3 only.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
namespace ThreadPilot.Services
|
||||
{
|
||||
using System.Threading.Tasks;
|
||||
|
||||
/// <summary>
|
||||
/// Service for managing Scheduled Task-based elevation entrypoints.
|
||||
/// </summary>
|
||||
public interface IElevatedTaskService
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets the managed task name used for on-demand elevated launch.
|
||||
/// </summary>
|
||||
string LaunchTaskName { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the managed task name used for elevated logon autostart.
|
||||
/// </summary>
|
||||
string AutostartTaskName { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Ensures the managed on-demand elevated launch task exists and targets the current executable.
|
||||
/// </summary>
|
||||
/// <returns>True when the task exists and is up to date; otherwise false.</returns>
|
||||
Task<bool> EnsureLaunchTaskAsync();
|
||||
|
||||
/// <summary>
|
||||
/// Runs the managed on-demand elevated launch task.
|
||||
/// </summary>
|
||||
/// <returns>True if task execution was started successfully; otherwise false.</returns>
|
||||
Task<bool> TryRunLaunchTaskAsync();
|
||||
|
||||
/// <summary>
|
||||
/// Ensures elevated autostart task exists and points to the provided executable command.
|
||||
/// </summary>
|
||||
/// <param name="executablePath">Absolute executable path.</param>
|
||||
/// <param name="arguments">Command-line arguments for autostart launches.</param>
|
||||
/// <returns>True if task was created/updated successfully; otherwise false.</returns>
|
||||
Task<bool> EnsureAutostartTaskAsync(string executablePath, string arguments);
|
||||
|
||||
/// <summary>
|
||||
/// Removes the managed elevated autostart task.
|
||||
/// </summary>
|
||||
/// <returns>True when the task is removed (or already absent); otherwise false.</returns>
|
||||
Task<bool> RemoveAutostartTaskAsync();
|
||||
|
||||
/// <summary>
|
||||
/// Checks whether the managed elevated autostart task is currently registered.
|
||||
/// </summary>
|
||||
/// <returns>True when the task exists; otherwise false.</returns>
|
||||
Task<bool> IsAutostartTaskRegisteredAsync();
|
||||
}
|
||||
}
|
||||
namespace ThreadPilot.Services
|
||||
{
|
||||
using System.Threading.Tasks;
|
||||
|
||||
public interface IElevatedTaskService
|
||||
{
|
||||
string LaunchTaskName { get; }
|
||||
|
||||
string AutostartTaskName { get; }
|
||||
|
||||
Task<bool> EnsureLaunchTaskAsync();
|
||||
|
||||
Task<bool> TryRunLaunchTaskAsync();
|
||||
|
||||
Task<bool> EnsureAutostartTaskAsync(string executablePath, string arguments);
|
||||
|
||||
Task<bool> RemoveAutostartTaskAsync();
|
||||
|
||||
Task<bool> IsAutostartTaskRegisteredAsync();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,59 +1,18 @@
|
||||
/*
|
||||
* ThreadPilot - Advanced Windows Process and Power Plan Manager
|
||||
* Copyright (C) 2025 Prime Build
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published by
|
||||
* the Free Software Foundation, version 3 only.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
namespace ThreadPilot.Services
|
||||
{
|
||||
using System.Threading.Tasks;
|
||||
|
||||
/// <summary>
|
||||
/// Service for managing application elevation and administrator privileges.
|
||||
/// </summary>
|
||||
public interface IElevationService
|
||||
{
|
||||
/// <summary>
|
||||
/// Checks if the current process is running with administrator privileges.
|
||||
/// </summary>
|
||||
/// <returns>True if running as administrator, false otherwise.</returns>
|
||||
bool IsRunningAsAdministrator();
|
||||
|
||||
/// <summary>
|
||||
/// Requests elevation if the current process is not running as administrator.
|
||||
/// </summary>
|
||||
/// <returns>True if already elevated or elevation was successful, false if elevation failed or was cancelled.</returns>
|
||||
Task<bool> RequestElevationIfNeeded();
|
||||
|
||||
/// <summary>
|
||||
/// Restarts the application with administrator privileges.
|
||||
/// </summary>
|
||||
/// <param name="arguments">Command line arguments to pass to the elevated process.</param>
|
||||
/// <returns>True if restart was initiated successfully, false otherwise.</returns>
|
||||
Task<bool> RestartWithElevation(string[]? arguments = null);
|
||||
|
||||
/// <summary>
|
||||
/// Validates that the current process has the necessary privileges for the specified operation.
|
||||
/// </summary>
|
||||
/// <param name="operation">The operation that requires validation.</param>
|
||||
/// <returns>True if the operation can be performed, false otherwise.</returns>
|
||||
bool ValidateElevationForOperation(string operation);
|
||||
|
||||
/// <summary>
|
||||
/// Gets the current elevation status as a user-friendly string.
|
||||
/// </summary>
|
||||
/// <returns>Elevation status description.</returns>
|
||||
string GetElevationStatus();
|
||||
}
|
||||
}
|
||||
|
||||
namespace ThreadPilot.Services
|
||||
{
|
||||
using System.Threading.Tasks;
|
||||
|
||||
public interface IElevationService
|
||||
{
|
||||
bool IsRunningAsAdministrator();
|
||||
|
||||
Task<bool> RequestElevationIfNeeded();
|
||||
|
||||
Task<bool> RestartWithElevation(string[]? arguments = null);
|
||||
|
||||
bool ValidateElevationForOperation(string operation);
|
||||
|
||||
string GetElevationStatus();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+104
-189
@@ -1,189 +1,104 @@
|
||||
/*
|
||||
* ThreadPilot - Advanced Windows Process and Power Plan Manager
|
||||
* Copyright (C) 2025 Prime Build
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published by
|
||||
* the Free Software Foundation, version 3 only.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
namespace ThreadPilot.Services
|
||||
{
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
/// <summary>
|
||||
/// Enhanced logging service interface for persistent, structured logging.
|
||||
/// </summary>
|
||||
public interface IEnhancedLoggingService
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets the current log file path.
|
||||
/// </summary>
|
||||
string CurrentLogFilePath { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the log directory path.
|
||||
/// </summary>
|
||||
string LogDirectoryPath { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets a value indicating whether gets whether debug logging is enabled.
|
||||
/// </summary>
|
||||
bool IsDebugLoggingEnabled { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Event raised when a critical error occurs
|
||||
/// </summary>
|
||||
event EventHandler<CriticalErrorEventArgs>? CriticalErrorOccurred;
|
||||
|
||||
/// <summary>
|
||||
/// Initialize the logging service.
|
||||
/// </summary>
|
||||
Task InitializeAsync();
|
||||
|
||||
/// <summary>
|
||||
/// Log a power plan change event.
|
||||
/// </summary>
|
||||
Task LogPowerPlanChangeAsync(string fromPlan, string toPlan, string reason, string? processName = null);
|
||||
|
||||
/// <summary>
|
||||
/// Log a process monitoring event.
|
||||
/// </summary>
|
||||
Task LogProcessMonitoringEventAsync(string eventType, string processName, int processId, string details);
|
||||
|
||||
/// <summary>
|
||||
/// Log a user action.
|
||||
/// </summary>
|
||||
Task LogUserActionAsync(string action, string details, string? context = null);
|
||||
|
||||
/// <summary>
|
||||
/// Log a system event.
|
||||
/// </summary>
|
||||
Task LogSystemEventAsync(string eventType, string message, LogLevel level = LogLevel.Information);
|
||||
|
||||
/// <summary>
|
||||
/// Log an error with structured data.
|
||||
/// </summary>
|
||||
Task LogErrorAsync(Exception exception, string context, Dictionary<string, object>? additionalData = null);
|
||||
|
||||
/// <summary>
|
||||
/// Log application startup/shutdown events.
|
||||
/// </summary>
|
||||
Task LogApplicationLifecycleEventAsync(string eventType, string details);
|
||||
|
||||
/// <summary>
|
||||
/// Get recent log entries.
|
||||
/// </summary>
|
||||
Task<List<LogEntry>> GetRecentLogEntriesAsync(int count = 100);
|
||||
|
||||
/// <summary>
|
||||
/// Begin a correlated operation scope for better debugging.
|
||||
/// </summary>
|
||||
IDisposable BeginScope(string operationName, object? parameters = null);
|
||||
|
||||
/// <summary>
|
||||
/// Get the current correlation ID.
|
||||
/// </summary>
|
||||
string? GetCurrentCorrelationId();
|
||||
|
||||
/// <summary>
|
||||
/// Get log entries for a specific date range.
|
||||
/// </summary>
|
||||
Task<List<LogEntry>> GetLogEntriesAsync(DateTime fromDate, DateTime toDate);
|
||||
|
||||
/// <summary>
|
||||
/// Clean up old log files based on retention policy.
|
||||
/// </summary>
|
||||
Task CleanupOldLogsAsync();
|
||||
|
||||
/// <summary>
|
||||
/// Get log file statistics.
|
||||
/// </summary>
|
||||
Task<LogFileStatistics> GetLogStatisticsAsync();
|
||||
|
||||
/// <summary>
|
||||
/// Export logs to a file.
|
||||
/// </summary>
|
||||
Task<string> ExportLogsAsync(DateTime fromDate, DateTime toDate, string? exportPath = null);
|
||||
|
||||
/// <summary>
|
||||
/// Update logging configuration.
|
||||
/// </summary>
|
||||
Task UpdateConfigurationAsync(bool enableDebugLogging, int maxFileSizeMb, int retentionDays);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Event args for critical errors.
|
||||
/// </summary>
|
||||
public class CriticalErrorEventArgs : EventArgs
|
||||
{
|
||||
public Exception Exception { get; }
|
||||
|
||||
public string Context { get; }
|
||||
|
||||
public DateTime Timestamp { get; }
|
||||
|
||||
public Dictionary<string, object> AdditionalData { get; }
|
||||
|
||||
public CriticalErrorEventArgs(Exception exception, string context, Dictionary<string, object>? additionalData = null)
|
||||
{
|
||||
this.Exception = exception;
|
||||
this.Context = context;
|
||||
this.Timestamp = DateTime.UtcNow;
|
||||
this.AdditionalData = additionalData ?? new Dictionary<string, object>();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Represents a log entry.
|
||||
/// </summary>
|
||||
public class LogEntry
|
||||
{
|
||||
public DateTime Timestamp { get; set; }
|
||||
|
||||
public LogLevel Level { get; set; }
|
||||
|
||||
public string Category { get; set; } = string.Empty;
|
||||
|
||||
public string Message { get; set; } = string.Empty;
|
||||
|
||||
public string? Exception { get; set; }
|
||||
|
||||
public Dictionary<string, object> Properties { get; set; } = new();
|
||||
|
||||
public string? CorrelationId { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Log file statistics.
|
||||
/// </summary>
|
||||
public class LogFileStatistics
|
||||
{
|
||||
public long CurrentFileSizeBytes { get; set; }
|
||||
|
||||
public int TotalLogFiles { get; set; }
|
||||
|
||||
public long TotalLogSizeBytes { get; set; }
|
||||
|
||||
public DateTime OldestLogDate { get; set; }
|
||||
|
||||
public DateTime NewestLogDate { get; set; }
|
||||
|
||||
public int ErrorCount { get; set; }
|
||||
|
||||
public int WarningCount { get; set; }
|
||||
|
||||
public int InfoCount { get; set; }
|
||||
}
|
||||
}
|
||||
|
||||
namespace ThreadPilot.Services
|
||||
{
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
public interface IEnhancedLoggingService
|
||||
{
|
||||
string CurrentLogFilePath { get; }
|
||||
|
||||
string LogDirectoryPath { get; }
|
||||
|
||||
bool IsDebugLoggingEnabled { get; }
|
||||
|
||||
event EventHandler<CriticalErrorEventArgs>? CriticalErrorOccurred;
|
||||
|
||||
Task InitializeAsync();
|
||||
|
||||
Task LogPowerPlanChangeAsync(string fromPlan, string toPlan, string reason, string? processName = null);
|
||||
|
||||
Task LogProcessMonitoringEventAsync(string eventType, string processName, int processId, string details);
|
||||
|
||||
Task LogUserActionAsync(string action, string details, string? context = null);
|
||||
|
||||
Task LogSystemEventAsync(string eventType, string message, LogLevel level = LogLevel.Information);
|
||||
|
||||
Task LogErrorAsync(Exception exception, string context, Dictionary<string, object>? additionalData = null);
|
||||
|
||||
Task LogApplicationLifecycleEventAsync(string eventType, string details);
|
||||
|
||||
Task<List<LogEntry>> GetRecentLogEntriesAsync(int count = 100);
|
||||
|
||||
IDisposable BeginScope(string operationName, object? parameters = null);
|
||||
|
||||
string? GetCurrentCorrelationId();
|
||||
|
||||
Task<List<LogEntry>> GetLogEntriesAsync(DateTime fromDate, DateTime toDate);
|
||||
|
||||
Task CleanupOldLogsAsync();
|
||||
|
||||
Task<LogFileStatistics> GetLogStatisticsAsync();
|
||||
|
||||
Task<string> ExportLogsAsync(DateTime fromDate, DateTime toDate, string? exportPath = null);
|
||||
|
||||
Task UpdateConfigurationAsync(bool enableDebugLogging, int maxFileSizeMb, int retentionDays);
|
||||
}
|
||||
|
||||
public class CriticalErrorEventArgs : EventArgs
|
||||
{
|
||||
public Exception Exception { get; }
|
||||
|
||||
public string Context { get; }
|
||||
|
||||
public DateTime Timestamp { get; }
|
||||
|
||||
public Dictionary<string, object> AdditionalData { get; }
|
||||
|
||||
public CriticalErrorEventArgs(Exception exception, string context, Dictionary<string, object>? additionalData = null)
|
||||
{
|
||||
this.Exception = exception;
|
||||
this.Context = context;
|
||||
this.Timestamp = DateTime.UtcNow;
|
||||
this.AdditionalData = additionalData ?? new Dictionary<string, object>();
|
||||
}
|
||||
}
|
||||
|
||||
public class LogEntry
|
||||
{
|
||||
public DateTime Timestamp { get; set; }
|
||||
|
||||
public LogLevel Level { get; set; }
|
||||
|
||||
public string Category { get; set; } = string.Empty;
|
||||
|
||||
public string Message { get; set; } = string.Empty;
|
||||
|
||||
public string? Exception { get; set; }
|
||||
|
||||
public Dictionary<string, object> Properties { get; set; } = new();
|
||||
|
||||
public string? CorrelationId { get; set; }
|
||||
}
|
||||
|
||||
public class LogFileStatistics
|
||||
{
|
||||
public long CurrentFileSizeBytes { get; set; }
|
||||
|
||||
public int TotalLogFiles { get; set; }
|
||||
|
||||
public long TotalLogSizeBytes { get; set; }
|
||||
|
||||
public DateTime OldestLogDate { get; set; }
|
||||
|
||||
public DateTime NewestLogDate { get; set; }
|
||||
|
||||
public int ErrorCount { get; set; }
|
||||
|
||||
public int WarningCount { get; set; }
|
||||
|
||||
public int InfoCount { get; set; }
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,157 +0,0 @@
|
||||
/*
|
||||
* ThreadPilot - Advanced Windows Process and Power Plan Manager
|
||||
* Copyright (C) 2025 Prime Build
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published by
|
||||
* the Free Software Foundation, version 3 only.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Threading.Tasks;
|
||||
using ThreadPilot.Models;
|
||||
|
||||
namespace ThreadPilot.Services
|
||||
{
|
||||
/// <summary>
|
||||
/// Interface for Game Boost mode functionality
|
||||
/// </summary>
|
||||
public interface IGameBoostService
|
||||
{
|
||||
/// <summary>
|
||||
/// Event fired when Game Boost mode is activated
|
||||
/// </summary>
|
||||
event EventHandler<GameBoostActivatedEventArgs>? GameBoostActivated;
|
||||
|
||||
/// <summary>
|
||||
/// Event fired when Game Boost mode is deactivated
|
||||
/// </summary>
|
||||
event EventHandler<GameBoostDeactivatedEventArgs>? GameBoostDeactivated;
|
||||
|
||||
/// <summary>
|
||||
/// Event fired when a game is detected
|
||||
/// </summary>
|
||||
event EventHandler<GameDetectedEventArgs>? GameDetected;
|
||||
|
||||
/// <summary>
|
||||
/// Gets whether Game Boost mode is currently active
|
||||
/// </summary>
|
||||
bool IsGameBoostActive { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the currently detected game process
|
||||
/// </summary>
|
||||
ProcessModel? CurrentGameProcess { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the list of known game executables
|
||||
/// </summary>
|
||||
IReadOnlyList<string> KnownGameExecutables { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the list of known game executables as a collection
|
||||
/// </summary>
|
||||
IReadOnlyList<string> GetKnownGameExecutables();
|
||||
|
||||
/// <summary>
|
||||
/// Enables Game Boost mode
|
||||
/// </summary>
|
||||
Task<bool> EnableGameBoostAsync();
|
||||
|
||||
/// <summary>
|
||||
/// Disables Game Boost mode
|
||||
/// </summary>
|
||||
Task<bool> DisableGameBoostAsync();
|
||||
|
||||
/// <summary>
|
||||
/// Manually activates Game Boost for a specific process
|
||||
/// </summary>
|
||||
/// <param name="process">The process to boost</param>
|
||||
Task<bool> ActivateGameBoostAsync(ProcessModel process);
|
||||
|
||||
/// <summary>
|
||||
/// Manually deactivates Game Boost
|
||||
/// </summary>
|
||||
Task<bool> DeactivateGameBoostAsync();
|
||||
|
||||
/// <summary>
|
||||
/// Adds a game executable to the known games list
|
||||
/// </summary>
|
||||
/// <param name="executableName">Name of the executable (e.g., "game.exe")</param>
|
||||
Task<bool> AddKnownGameAsync(string executableName);
|
||||
|
||||
/// <summary>
|
||||
/// Removes a game executable from the known games list
|
||||
/// </summary>
|
||||
/// <param name="executableName">Name of the executable to remove</param>
|
||||
Task<bool> RemoveKnownGameAsync(string executableName);
|
||||
|
||||
/// <summary>
|
||||
/// Checks if a process is considered a game
|
||||
/// </summary>
|
||||
/// <param name="process">The process to check</param>
|
||||
bool IsGameProcess(ProcessModel process);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Event arguments for Game Boost activation
|
||||
/// </summary>
|
||||
public class GameBoostActivatedEventArgs : EventArgs
|
||||
{
|
||||
public ProcessModel GameProcess { get; }
|
||||
public string PowerPlanId { get; }
|
||||
public DateTime ActivatedAt { get; }
|
||||
|
||||
public GameBoostActivatedEventArgs(ProcessModel gameProcess, string powerPlanId)
|
||||
{
|
||||
GameProcess = gameProcess;
|
||||
PowerPlanId = powerPlanId;
|
||||
ActivatedAt = DateTime.Now;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Event arguments for Game Boost deactivation
|
||||
/// </summary>
|
||||
public class GameBoostDeactivatedEventArgs : EventArgs
|
||||
{
|
||||
public ProcessModel? GameProcess { get; }
|
||||
public string? RestoredPowerPlanId { get; }
|
||||
public DateTime DeactivatedAt { get; }
|
||||
public TimeSpan Duration { get; }
|
||||
|
||||
public GameBoostDeactivatedEventArgs(ProcessModel? gameProcess, string? restoredPowerPlanId, TimeSpan duration)
|
||||
{
|
||||
GameProcess = gameProcess;
|
||||
RestoredPowerPlanId = restoredPowerPlanId;
|
||||
DeactivatedAt = DateTime.Now;
|
||||
Duration = duration;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Event arguments for game detection
|
||||
/// </summary>
|
||||
public class GameDetectedEventArgs : EventArgs
|
||||
{
|
||||
public ProcessModel GameProcess { get; }
|
||||
public bool IsKnownGame { get; }
|
||||
public DateTime DetectedAt { get; }
|
||||
|
||||
public GameDetectedEventArgs(ProcessModel gameProcess, bool isKnownGame)
|
||||
{
|
||||
GameProcess = gameProcess;
|
||||
IsKnownGame = isKnownGame;
|
||||
DetectedAt = DateTime.Now;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,259 +0,0 @@
|
||||
/*
|
||||
* ThreadPilot - Advanced Windows Process and Power Plan Manager
|
||||
* Copyright (C) 2025 Prime Build
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published by
|
||||
* the Free Software Foundation, version 3 only.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.Threading.Tasks;
|
||||
using ThreadPilot.Models;
|
||||
|
||||
namespace ThreadPilot.Services
|
||||
{
|
||||
/// <summary>
|
||||
/// Game classification confidence levels
|
||||
/// </summary>
|
||||
public enum GameConfidenceLevel
|
||||
{
|
||||
VeryLow = 0, // 0-20%
|
||||
Low = 1, // 20-40%
|
||||
Medium = 2, // 40-60%
|
||||
High = 3, // 60-80%
|
||||
VeryHigh = 4 // 80-100%
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Game detection result with confidence scoring
|
||||
/// </summary>
|
||||
public class GameDetectionResult
|
||||
{
|
||||
public bool IsGame { get; set; }
|
||||
public float Confidence { get; set; }
|
||||
public GameConfidenceLevel ConfidenceLevel => Confidence switch
|
||||
{
|
||||
>= 0.8f => GameConfidenceLevel.VeryHigh,
|
||||
>= 0.6f => GameConfidenceLevel.High,
|
||||
>= 0.4f => GameConfidenceLevel.Medium,
|
||||
>= 0.2f => GameConfidenceLevel.Low,
|
||||
_ => GameConfidenceLevel.VeryLow
|
||||
};
|
||||
public string GameName { get; set; } = string.Empty;
|
||||
public string DetectionMethod { get; set; } = string.Empty;
|
||||
public Dictionary<string, object> Features { get; set; } = new();
|
||||
public DateTime DetectionTime { get; set; } = DateTime.UtcNow;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Real-time game performance metrics
|
||||
/// </summary>
|
||||
public class GamePerformanceMetrics
|
||||
{
|
||||
public int ProcessId { get; set; }
|
||||
public string GameName { get; set; } = string.Empty;
|
||||
public float FrameRate { get; set; }
|
||||
public double CpuUsage { get; set; }
|
||||
public long MemoryUsage { get; set; }
|
||||
public double GpuUsage { get; set; }
|
||||
public long GpuMemoryUsage { get; set; }
|
||||
public DateTime Timestamp { get; set; } = DateTime.UtcNow;
|
||||
public bool IsFullscreen { get; set; }
|
||||
public string Resolution { get; set; } = string.Empty;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Process features for ML classification
|
||||
/// </summary>
|
||||
public class ProcessFeatures
|
||||
{
|
||||
public string ProcessName { get; set; } = string.Empty;
|
||||
public string ExecutablePath { get; set; } = string.Empty;
|
||||
public bool HasVisibleWindow { get; set; }
|
||||
public bool IsFullscreen { get; set; }
|
||||
public double CpuUsage { get; set; }
|
||||
public long MemoryUsage { get; set; }
|
||||
public int ThreadCount { get; set; }
|
||||
public int HandleCount { get; set; }
|
||||
public bool HasDirectXDlls { get; set; }
|
||||
public bool HasOpenGLDlls { get; set; }
|
||||
public bool HasVulkanDlls { get; set; }
|
||||
public bool HasAudioDlls { get; set; }
|
||||
public bool HasNetworkActivity { get; set; }
|
||||
public string FileDescription { get; set; } = string.Empty;
|
||||
public string CompanyName { get; set; } = string.Empty;
|
||||
public bool IsInGamesFolder { get; set; }
|
||||
public bool HasGameKeywords { get; set; }
|
||||
public float WindowAspectRatio { get; set; }
|
||||
public bool IsElevated { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Service for detecting running games and applying optimal performance profiles
|
||||
/// </summary>
|
||||
public interface IGameDetectionService
|
||||
{
|
||||
/// <summary>
|
||||
/// Detect if a process is a known game
|
||||
/// </summary>
|
||||
Task<GameProfile?> DetectGameAsync(ProcessModel process);
|
||||
|
||||
/// <summary>
|
||||
/// Detect if a process is a game using ML classification
|
||||
/// </summary>
|
||||
Task<GameDetectionResult> DetectGameWithMLAsync(ProcessModel process);
|
||||
|
||||
/// <summary>
|
||||
/// Extract features from a process for ML classification
|
||||
/// </summary>
|
||||
Task<ProcessFeatures> ExtractProcessFeaturesAsync(ProcessModel process);
|
||||
|
||||
/// <summary>
|
||||
/// Get real-time performance metrics for a game
|
||||
/// </summary>
|
||||
Task<GamePerformanceMetrics> GetGamePerformanceAsync(ProcessModel process);
|
||||
|
||||
/// <summary>
|
||||
/// Get all currently running games
|
||||
/// </summary>
|
||||
Task<List<GameProfile>> GetRunningGamesAsync();
|
||||
|
||||
/// <summary>
|
||||
/// Apply optimal settings for a detected game
|
||||
/// </summary>
|
||||
Task<bool> ApplyGameOptimizationsAsync(ProcessModel process, GameProfile gameProfile);
|
||||
|
||||
/// <summary>
|
||||
/// Check if a process is running through Steam
|
||||
/// </summary>
|
||||
Task<bool> IsSteamGameAsync(ProcessModel process);
|
||||
|
||||
/// <summary>
|
||||
/// Check if a process is running through Epic Games Launcher
|
||||
/// </summary>
|
||||
Task<bool> IsEpicGameAsync(ProcessModel process);
|
||||
|
||||
/// <summary>
|
||||
/// Get game profile for a Steam game
|
||||
/// </summary>
|
||||
Task<GameProfile?> GetSteamGameProfileAsync(ProcessModel process);
|
||||
|
||||
/// <summary>
|
||||
/// Get game profile for an Epic Games game
|
||||
/// </summary>
|
||||
Task<GameProfile?> GetEpicGameProfileAsync(ProcessModel process);
|
||||
|
||||
/// <summary>
|
||||
/// Add or update a custom game profile
|
||||
/// </summary>
|
||||
Task AddCustomGameProfileAsync(string processName, GameProfile profile);
|
||||
|
||||
/// <summary>
|
||||
/// Remove a custom game profile
|
||||
/// </summary>
|
||||
Task RemoveCustomGameProfileAsync(string processName);
|
||||
|
||||
/// <summary>
|
||||
/// Get all available game profiles
|
||||
/// </summary>
|
||||
Task<Dictionary<string, GameProfile>> GetAllGameProfilesAsync();
|
||||
|
||||
/// <summary>
|
||||
/// Event raised when a new game is detected
|
||||
/// </summary>
|
||||
event EventHandler<GameProfileDetectedEventArgs>? GameDetected;
|
||||
|
||||
/// <summary>
|
||||
/// Event raised when a game stops running
|
||||
/// </summary>
|
||||
event EventHandler<GameStoppedEventArgs>? GameStopped;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Represents a game profile with optimal settings
|
||||
/// </summary>
|
||||
public class GameProfile
|
||||
{
|
||||
public string Name { get; set; } = string.Empty;
|
||||
public string ProcessName { get; set; } = string.Empty;
|
||||
public string OptimalCores { get; set; } = "All"; // "All", "Physical", "P-Cores", "E-Cores", "Custom"
|
||||
public ProcessPriorityClass Priority { get; set; } = ProcessPriorityClass.High;
|
||||
public string? PowerPlan { get; set; }
|
||||
public bool DisableFullscreenOptimizations { get; set; } = true;
|
||||
public bool HighDpiAware { get; set; } = true;
|
||||
public string? CustomAffinityMask { get; set; }
|
||||
public Dictionary<string, object> CustomSettings { get; set; } = new();
|
||||
public DateTime LastDetected { get; set; }
|
||||
public int DetectionCount { get; set; }
|
||||
public string? SteamAppId { get; set; }
|
||||
public string? EpicAppId { get; set; }
|
||||
public GameCategory Category { get; set; } = GameCategory.Unknown;
|
||||
public string? Description { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Game categories for better organization
|
||||
/// </summary>
|
||||
public enum GameCategory
|
||||
{
|
||||
Unknown,
|
||||
FPS,
|
||||
MOBA,
|
||||
RTS,
|
||||
RPG,
|
||||
Racing,
|
||||
Sports,
|
||||
Simulation,
|
||||
Strategy,
|
||||
Action,
|
||||
Adventure,
|
||||
Indie
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Event args for game profile detection
|
||||
/// </summary>
|
||||
public class GameProfileDetectedEventArgs : EventArgs
|
||||
{
|
||||
public ProcessModel Process { get; }
|
||||
public GameProfile GameProfile { get; }
|
||||
public DateTime DetectedAt { get; }
|
||||
|
||||
public GameProfileDetectedEventArgs(ProcessModel process, GameProfile gameProfile)
|
||||
{
|
||||
Process = process;
|
||||
GameProfile = gameProfile;
|
||||
DetectedAt = DateTime.UtcNow;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Event args for game stopped
|
||||
/// </summary>
|
||||
public class GameStoppedEventArgs : EventArgs
|
||||
{
|
||||
public string ProcessName { get; }
|
||||
public GameProfile GameProfile { get; }
|
||||
public DateTime StoppedAt { get; }
|
||||
public TimeSpan PlayDuration { get; }
|
||||
|
||||
public GameStoppedEventArgs(string processName, GameProfile gameProfile, TimeSpan playDuration)
|
||||
{
|
||||
ProcessName = processName;
|
||||
GameProfile = gameProfile;
|
||||
StoppedAt = DateTime.UtcNow;
|
||||
PlayDuration = playDuration;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,48 +1,14 @@
|
||||
/*
|
||||
* ThreadPilot - Advanced Windows Process and Power Plan Manager
|
||||
* Copyright (C) 2025 Prime Build
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published by
|
||||
* the Free Software Foundation, version 3 only.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
namespace ThreadPilot.Services
|
||||
{
|
||||
using System.Threading.Tasks;
|
||||
|
||||
/// <summary>
|
||||
/// Service for managing Windows Game Mode settings
|
||||
/// Game Mode can interfere with CPU affinity settings, particularly on AMD systems.
|
||||
/// </summary>
|
||||
public interface IGameModeService
|
||||
{
|
||||
/// <summary>
|
||||
/// Checks if Windows Game Mode is currently enabled.
|
||||
/// </summary>
|
||||
/// <returns>True if Game Mode is enabled, false otherwise.</returns>
|
||||
Task<bool> IsGameModeEnabledAsync();
|
||||
|
||||
/// <summary>
|
||||
/// Sets Windows Game Mode to enabled or disabled.
|
||||
/// </summary>
|
||||
/// <param name="enabled">True to enable Game Mode, false to disable.</param>
|
||||
/// <returns>True if the operation succeeded, false otherwise.</returns>
|
||||
Task<bool> SetGameModeAsync(bool enabled);
|
||||
|
||||
/// <summary>
|
||||
/// Disables Game Mode for better CPU affinity control
|
||||
/// This is a non-intrusive operation that only disables if currently enabled.
|
||||
/// </summary>
|
||||
/// <returns>True if Game Mode was disabled, false if it was already disabled or operation failed.</returns>
|
||||
Task<bool> DisableGameModeForAffinityAsync();
|
||||
}
|
||||
}
|
||||
|
||||
namespace ThreadPilot.Services
|
||||
{
|
||||
using System.Threading.Tasks;
|
||||
|
||||
public interface IGameModeService
|
||||
{
|
||||
Task<bool> IsGameModeEnabledAsync();
|
||||
|
||||
Task<bool> SetGameModeAsync(bool enabled);
|
||||
|
||||
Task<bool> DisableGameModeForAffinityAsync();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,164 +1,106 @@
|
||||
/*
|
||||
* ThreadPilot - Advanced Windows Process and Power Plan Manager
|
||||
* Copyright (C) 2025 Prime Build
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published by
|
||||
* the Free Software Foundation, version 3 only.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
namespace ThreadPilot.Services
|
||||
{
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Threading.Tasks;
|
||||
using System.Windows.Input;
|
||||
|
||||
/// <summary>
|
||||
/// Service for managing global keyboard shortcuts.
|
||||
/// </summary>
|
||||
public interface IKeyboardShortcutService
|
||||
{
|
||||
/// <summary>
|
||||
/// Event raised when a registered shortcut is activated
|
||||
/// </summary>
|
||||
event EventHandler<ShortcutActivatedEventArgs>? ShortcutActivated;
|
||||
|
||||
/// <summary>
|
||||
/// Register a global keyboard shortcut.
|
||||
/// </summary>
|
||||
Task<bool> RegisterShortcutAsync(string actionName, Key key, ModifierKeys modifiers);
|
||||
|
||||
/// <summary>
|
||||
/// Unregister a keyboard shortcut.
|
||||
/// </summary>
|
||||
Task<bool> UnregisterShortcutAsync(string actionName);
|
||||
|
||||
/// <summary>
|
||||
/// Update an existing shortcut with new key combination.
|
||||
/// </summary>
|
||||
Task<bool> UpdateShortcutAsync(string actionName, Key key, ModifierKeys modifiers);
|
||||
|
||||
/// <summary>
|
||||
/// Get all registered shortcuts.
|
||||
/// </summary>
|
||||
Task<Dictionary<string, KeyboardShortcut>> GetRegisteredShortcutsAsync();
|
||||
|
||||
/// <summary>
|
||||
/// Check if a key combination is already registered.
|
||||
/// </summary>
|
||||
Task<bool> IsShortcutRegisteredAsync(Key key, ModifierKeys modifiers);
|
||||
|
||||
/// <summary>
|
||||
/// Load shortcuts from settings.
|
||||
/// </summary>
|
||||
Task LoadShortcutsFromSettingsAsync();
|
||||
|
||||
/// <summary>
|
||||
/// Save shortcuts to settings.
|
||||
/// </summary>
|
||||
Task SaveShortcutsToSettingsAsync();
|
||||
|
||||
/// <summary>
|
||||
/// Clear all registered shortcuts.
|
||||
/// </summary>
|
||||
Task ClearAllShortcutsAsync();
|
||||
|
||||
/// <summary>
|
||||
/// Get the default shortcuts for the application.
|
||||
/// </summary>
|
||||
Dictionary<string, KeyboardShortcut> GetDefaultShortcuts();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Represents a keyboard shortcut.
|
||||
/// </summary>
|
||||
public class KeyboardShortcut
|
||||
{
|
||||
public string ActionName { get; set; } = string.Empty;
|
||||
|
||||
public Key Key { get; set; }
|
||||
|
||||
public ModifierKeys Modifiers { get; set; }
|
||||
|
||||
public string Description { get; set; } = string.Empty;
|
||||
|
||||
public bool IsEnabled { get; set; } = true;
|
||||
|
||||
public bool IsGlobal { get; set; } = true;
|
||||
|
||||
public override string ToString()
|
||||
{
|
||||
var parts = new List<string>();
|
||||
|
||||
if (this.Modifiers.HasFlag(ModifierKeys.Control))
|
||||
{
|
||||
parts.Add("Ctrl");
|
||||
}
|
||||
|
||||
if (this.Modifiers.HasFlag(ModifierKeys.Alt))
|
||||
{
|
||||
parts.Add("Alt");
|
||||
}
|
||||
|
||||
if (this.Modifiers.HasFlag(ModifierKeys.Shift))
|
||||
{
|
||||
parts.Add("Shift");
|
||||
}
|
||||
|
||||
if (this.Modifiers.HasFlag(ModifierKeys.Windows))
|
||||
{
|
||||
parts.Add("Win");
|
||||
}
|
||||
|
||||
parts.Add(this.Key.ToString());
|
||||
|
||||
return string.Join(" + ", parts);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Event args for shortcut activation.
|
||||
/// </summary>
|
||||
public class ShortcutActivatedEventArgs : EventArgs
|
||||
{
|
||||
public string ActionName { get; }
|
||||
|
||||
public KeyboardShortcut Shortcut { get; }
|
||||
|
||||
public DateTime ActivationTime { get; }
|
||||
|
||||
public ShortcutActivatedEventArgs(string actionName, KeyboardShortcut shortcut)
|
||||
{
|
||||
this.ActionName = actionName;
|
||||
this.Shortcut = shortcut;
|
||||
this.ActivationTime = DateTime.UtcNow;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Predefined shortcut actions.
|
||||
/// </summary>
|
||||
public static class ShortcutActions
|
||||
{
|
||||
public const string QuickApply = "QuickApply";
|
||||
public const string ToggleMonitoring = "ToggleMonitoring";
|
||||
public const string ShowMainWindow = "ShowMainWindow";
|
||||
public const string HideToTray = "HideToTray";
|
||||
public const string PowerPlanBalanced = "PowerPlanBalanced";
|
||||
public const string PowerPlanHighPerformance = "PowerPlanHighPerformance";
|
||||
public const string PowerPlanPowerSaver = "PowerPlanPowerSaver";
|
||||
public const string RefreshProcessList = "RefreshProcessList";
|
||||
public const string OpenSettings = "OpenSettings";
|
||||
public const string OpenTweaks = "OpenTweaks";
|
||||
public const string ExitApplication = "ExitApplication";
|
||||
}
|
||||
}
|
||||
|
||||
namespace ThreadPilot.Services
|
||||
{
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Threading.Tasks;
|
||||
using System.Windows.Input;
|
||||
|
||||
public interface IKeyboardShortcutService
|
||||
{
|
||||
event EventHandler<ShortcutActivatedEventArgs>? ShortcutActivated;
|
||||
|
||||
Task<bool> RegisterShortcutAsync(string actionName, Key key, ModifierKeys modifiers);
|
||||
|
||||
Task<bool> UnregisterShortcutAsync(string actionName);
|
||||
|
||||
Task<bool> UpdateShortcutAsync(string actionName, Key key, ModifierKeys modifiers);
|
||||
|
||||
Task<Dictionary<string, KeyboardShortcut>> GetRegisteredShortcutsAsync();
|
||||
|
||||
Task<bool> IsShortcutRegisteredAsync(Key key, ModifierKeys modifiers);
|
||||
|
||||
Task LoadShortcutsFromSettingsAsync();
|
||||
|
||||
Task SaveShortcutsToSettingsAsync();
|
||||
|
||||
Task ClearAllShortcutsAsync();
|
||||
|
||||
Dictionary<string, KeyboardShortcut> GetDefaultShortcuts();
|
||||
}
|
||||
|
||||
public class KeyboardShortcut
|
||||
{
|
||||
public string ActionName { get; set; } = string.Empty;
|
||||
|
||||
public Key Key { get; set; }
|
||||
|
||||
public ModifierKeys Modifiers { get; set; }
|
||||
|
||||
public string Description { get; set; } = string.Empty;
|
||||
|
||||
public bool IsEnabled { get; set; } = true;
|
||||
|
||||
public bool IsGlobal { get; set; } = true;
|
||||
|
||||
public override string ToString()
|
||||
{
|
||||
var parts = new List<string>();
|
||||
|
||||
if (this.Modifiers.HasFlag(ModifierKeys.Control))
|
||||
{
|
||||
parts.Add("Ctrl");
|
||||
}
|
||||
|
||||
if (this.Modifiers.HasFlag(ModifierKeys.Alt))
|
||||
{
|
||||
parts.Add("Alt");
|
||||
}
|
||||
|
||||
if (this.Modifiers.HasFlag(ModifierKeys.Shift))
|
||||
{
|
||||
parts.Add("Shift");
|
||||
}
|
||||
|
||||
if (this.Modifiers.HasFlag(ModifierKeys.Windows))
|
||||
{
|
||||
parts.Add("Win");
|
||||
}
|
||||
|
||||
parts.Add(this.Key.ToString());
|
||||
|
||||
return string.Join(" + ", parts);
|
||||
}
|
||||
}
|
||||
|
||||
public class ShortcutActivatedEventArgs : EventArgs
|
||||
{
|
||||
public string ActionName { get; }
|
||||
|
||||
public KeyboardShortcut Shortcut { get; }
|
||||
|
||||
public DateTime ActivationTime { get; }
|
||||
|
||||
public ShortcutActivatedEventArgs(string actionName, KeyboardShortcut shortcut)
|
||||
{
|
||||
this.ActionName = actionName;
|
||||
this.Shortcut = shortcut;
|
||||
this.ActivationTime = DateTime.UtcNow;
|
||||
}
|
||||
}
|
||||
|
||||
public static class ShortcutActions
|
||||
{
|
||||
public const string QuickApply = "QuickApply";
|
||||
public const string ToggleMonitoring = "ToggleMonitoring";
|
||||
public const string ShowMainWindow = "ShowMainWindow";
|
||||
public const string HideToTray = "HideToTray";
|
||||
public const string PowerPlanBalanced = "PowerPlanBalanced";
|
||||
public const string PowerPlanHighPerformance = "PowerPlanHighPerformance";
|
||||
public const string PowerPlanPowerSaver = "PowerPlanPowerSaver";
|
||||
public const string RefreshProcessList = "RefreshProcessList";
|
||||
public const string OpenSettings = "OpenSettings";
|
||||
public const string OpenTweaks = "OpenTweaks";
|
||||
public const string ExitApplication = "ExitApplication";
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,44 +1,13 @@
|
||||
/*
|
||||
* ThreadPilot - Advanced Windows Process and Power Plan Manager
|
||||
* Copyright (C) 2025 Prime Build
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published by
|
||||
* the Free Software Foundation, version 3 only.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
namespace ThreadPilot.Services
|
||||
{
|
||||
/// <summary>
|
||||
/// Service for managing application localization and display language.
|
||||
/// </summary>
|
||||
public interface ILocalizationService
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets the current display language.
|
||||
/// </summary>
|
||||
string CurrentLanguage { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Event fired when the active language changes.
|
||||
/// </summary>
|
||||
event EventHandler<string>? LanguageChanged;
|
||||
|
||||
/// <summary>
|
||||
/// Applies the specified display language.
|
||||
/// </summary>
|
||||
void ApplyLanguage(string? language);
|
||||
|
||||
/// <summary>
|
||||
/// Gets the localized string for the specified key.
|
||||
/// </summary>
|
||||
string GetString(string key);
|
||||
}
|
||||
}
|
||||
namespace ThreadPilot.Services
|
||||
{
|
||||
public interface ILocalizationService
|
||||
{
|
||||
string CurrentLanguage { get; }
|
||||
|
||||
event EventHandler<string>? LanguageChanged;
|
||||
|
||||
void ApplyLanguage(string? language);
|
||||
|
||||
string GetString(string key);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,169 +1,78 @@
|
||||
/*
|
||||
* ThreadPilot - Advanced Windows Process and Power Plan Manager
|
||||
* Copyright (C) 2025 Prime Build
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published by
|
||||
* the Free Software Foundation, version 3 only.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
namespace ThreadPilot.Services
|
||||
{
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Threading.Tasks;
|
||||
using ThreadPilot.Models;
|
||||
|
||||
/// <summary>
|
||||
/// Service for managing notifications (balloon tips and toast notifications).
|
||||
/// </summary>
|
||||
public interface INotificationService
|
||||
{
|
||||
/// <summary>
|
||||
/// Event fired when a notification is shown
|
||||
/// </summary>
|
||||
event EventHandler<NotificationEventArgs>? NotificationShown;
|
||||
|
||||
/// <summary>
|
||||
/// Event fired when a notification is dismissed
|
||||
/// </summary>
|
||||
event EventHandler<NotificationEventArgs>? NotificationDismissed;
|
||||
|
||||
/// <summary>
|
||||
/// Event fired when a notification action is clicked
|
||||
/// </summary>
|
||||
event EventHandler<NotificationActionEventArgs>? NotificationActionClicked;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the notification history.
|
||||
/// </summary>
|
||||
IReadOnlyList<NotificationModel> NotificationHistory { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Shows a simple notification.
|
||||
/// </summary>
|
||||
Task ShowNotificationAsync(string title, string message, NotificationType type = NotificationType.Information);
|
||||
|
||||
/// <summary>
|
||||
/// Shows a notification with custom settings.
|
||||
/// </summary>
|
||||
Task ShowNotificationAsync(NotificationModel notification);
|
||||
|
||||
/// <summary>
|
||||
/// Shows a balloon tip notification.
|
||||
/// </summary>
|
||||
Task ShowBalloonTipAsync(string title, string message, NotificationType type = NotificationType.Information, int timeoutMs = 3000);
|
||||
|
||||
/// <summary>
|
||||
/// Shows a Windows toast notification (if available).
|
||||
/// </summary>
|
||||
Task ShowToastNotificationAsync(string title, string message, NotificationType type = NotificationType.Information);
|
||||
|
||||
/// <summary>
|
||||
/// Shows a notification for power plan changes.
|
||||
/// </summary>
|
||||
Task ShowPowerPlanChangeNotificationAsync(string oldPlan, string newPlan, string processName = "");
|
||||
|
||||
/// <summary>
|
||||
/// Shows a notification for process monitoring events.
|
||||
/// </summary>
|
||||
Task ShowProcessMonitoringNotificationAsync(string message, bool isEnabled);
|
||||
|
||||
/// <summary>
|
||||
/// Shows a notification for CPU affinity changes.
|
||||
/// </summary>
|
||||
Task ShowCpuAffinityNotificationAsync(string processName, string affinityInfo);
|
||||
|
||||
/// <summary>
|
||||
/// Shows an error notification.
|
||||
/// </summary>
|
||||
Task ShowErrorNotificationAsync(string title, string message, Exception? exception = null);
|
||||
|
||||
/// <summary>
|
||||
/// Shows a success notification.
|
||||
/// </summary>
|
||||
Task ShowSuccessNotificationAsync(string title, string message);
|
||||
|
||||
/// <summary>
|
||||
/// Dismisses a specific notification.
|
||||
/// </summary>
|
||||
Task DismissNotificationAsync(string notificationId);
|
||||
|
||||
/// <summary>
|
||||
/// Dismisses all notifications.
|
||||
/// </summary>
|
||||
Task DismissAllNotificationsAsync();
|
||||
|
||||
/// <summary>
|
||||
/// Clears notification history.
|
||||
/// </summary>
|
||||
Task ClearNotificationHistoryAsync();
|
||||
|
||||
/// <summary>
|
||||
/// Gets unread notification count.
|
||||
/// </summary>
|
||||
int GetUnreadNotificationCount();
|
||||
|
||||
/// <summary>
|
||||
/// Marks all notifications as read.
|
||||
/// </summary>
|
||||
Task MarkAllNotificationsAsReadAsync();
|
||||
|
||||
/// <summary>
|
||||
/// Checks if notifications are enabled for the given type.
|
||||
/// </summary>
|
||||
bool AreNotificationsEnabled(NotificationType type);
|
||||
|
||||
/// <summary>
|
||||
/// Updates notification settings.
|
||||
/// </summary>
|
||||
void UpdateSettings(ApplicationSettingsModel settings);
|
||||
|
||||
/// <summary>
|
||||
/// Initializes the notification service.
|
||||
/// </summary>
|
||||
Task InitializeAsync();
|
||||
|
||||
/// <summary>
|
||||
/// Disposes the notification service.
|
||||
/// </summary>
|
||||
void Dispose();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Event args for notification events.
|
||||
/// </summary>
|
||||
public class NotificationEventArgs : EventArgs
|
||||
{
|
||||
public NotificationModel Notification { get; }
|
||||
|
||||
public NotificationEventArgs(NotificationModel notification)
|
||||
{
|
||||
this.Notification = notification;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Event args for notification action events.
|
||||
/// </summary>
|
||||
public class NotificationActionEventArgs : EventArgs
|
||||
{
|
||||
public NotificationModel Notification { get; }
|
||||
|
||||
public string ActionCommand { get; }
|
||||
|
||||
public NotificationActionEventArgs(NotificationModel notification, string actionCommand)
|
||||
{
|
||||
this.Notification = notification;
|
||||
this.ActionCommand = actionCommand;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
namespace ThreadPilot.Services
|
||||
{
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Threading.Tasks;
|
||||
using ThreadPilot.Models;
|
||||
|
||||
public interface INotificationService
|
||||
{
|
||||
event EventHandler<NotificationEventArgs>? NotificationShown;
|
||||
|
||||
event EventHandler<NotificationEventArgs>? NotificationDismissed;
|
||||
|
||||
event EventHandler<NotificationActionEventArgs>? NotificationActionClicked;
|
||||
|
||||
IReadOnlyList<NotificationModel> NotificationHistory { get; }
|
||||
|
||||
Task ShowNotificationAsync(string title, string message, NotificationType type = NotificationType.Information);
|
||||
|
||||
Task ShowNotificationAsync(NotificationModel notification);
|
||||
|
||||
Task ShowBalloonTipAsync(string title, string message, NotificationType type = NotificationType.Information, int timeoutMs = 3000);
|
||||
|
||||
Task ShowToastNotificationAsync(string title, string message, NotificationType type = NotificationType.Information);
|
||||
|
||||
Task ShowPowerPlanChangeNotificationAsync(string oldPlan, string newPlan, string processName = "");
|
||||
|
||||
Task ShowProcessMonitoringNotificationAsync(string message, bool isEnabled);
|
||||
|
||||
Task ShowCpuAffinityNotificationAsync(string processName, string affinityInfo);
|
||||
|
||||
Task ShowErrorNotificationAsync(string title, string message, Exception? exception = null);
|
||||
|
||||
Task ShowSuccessNotificationAsync(string title, string message);
|
||||
|
||||
Task DismissNotificationAsync(string notificationId);
|
||||
|
||||
Task DismissAllNotificationsAsync();
|
||||
|
||||
Task ClearNotificationHistoryAsync();
|
||||
|
||||
int GetUnreadNotificationCount();
|
||||
|
||||
Task MarkAllNotificationsAsReadAsync();
|
||||
|
||||
bool AreNotificationsEnabled(NotificationType type);
|
||||
|
||||
void UpdateSettings(ApplicationSettingsModel settings);
|
||||
|
||||
Task InitializeAsync();
|
||||
|
||||
void Dispose();
|
||||
}
|
||||
|
||||
public class NotificationEventArgs : EventArgs
|
||||
{
|
||||
public NotificationModel Notification { get; }
|
||||
|
||||
public NotificationEventArgs(NotificationModel notification)
|
||||
{
|
||||
this.Notification = notification;
|
||||
}
|
||||
}
|
||||
|
||||
public class NotificationActionEventArgs : EventArgs
|
||||
{
|
||||
public NotificationModel Notification { get; }
|
||||
|
||||
public string ActionCommand { get; }
|
||||
|
||||
public NotificationActionEventArgs(NotificationModel notification, string actionCommand)
|
||||
{
|
||||
this.Notification = notification;
|
||||
this.ActionCommand = actionCommand;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,240 +1,176 @@
|
||||
/*
|
||||
* ThreadPilot - Advanced Windows Process and Power Plan Manager
|
||||
* Copyright (C) 2025 Prime Build
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published by
|
||||
* the Free Software Foundation, version 3 only.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
namespace ThreadPilot.Services
|
||||
{
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Threading.Tasks;
|
||||
using ThreadPilot.Models;
|
||||
|
||||
/// <summary>
|
||||
/// Service for real-time performance monitoring.
|
||||
/// </summary>
|
||||
public interface IPerformanceMonitoringService
|
||||
{
|
||||
/// <summary>
|
||||
/// Get current system performance metrics.
|
||||
/// </summary>
|
||||
Task<SystemPerformanceMetrics> GetSystemMetricsAsync(bool lightweight = false);
|
||||
|
||||
/// <summary>
|
||||
/// Get per-core CPU usage.
|
||||
/// </summary>
|
||||
Task<List<CpuCoreUsage>> GetCpuCoreUsageAsync();
|
||||
|
||||
/// <summary>
|
||||
/// Get memory usage information.
|
||||
/// </summary>
|
||||
Task<MemoryUsageInfo> GetMemoryUsageAsync();
|
||||
|
||||
/// <summary>
|
||||
/// Get top CPU consuming processes.
|
||||
/// </summary>
|
||||
Task<List<ProcessPerformanceInfo>> GetTopCpuProcessesAsync(int count = 10);
|
||||
|
||||
/// <summary>
|
||||
/// Get top memory consuming processes.
|
||||
/// </summary>
|
||||
Task<List<ProcessPerformanceInfo>> GetTopMemoryProcessesAsync(int count = 10);
|
||||
|
||||
/// <summary>
|
||||
/// Start real-time monitoring.
|
||||
/// </summary>
|
||||
Task StartMonitoringAsync();
|
||||
|
||||
/// <summary>
|
||||
/// Stop real-time monitoring.
|
||||
/// </summary>
|
||||
Task StopMonitoringAsync();
|
||||
|
||||
/// <summary>
|
||||
/// Event raised when performance metrics are updated
|
||||
/// </summary>
|
||||
event EventHandler<PerformanceMetricsUpdatedEventArgs>? MetricsUpdated;
|
||||
|
||||
/// <summary>
|
||||
/// Get historical performance data.
|
||||
/// </summary>
|
||||
Task<List<SystemPerformanceMetrics>> GetHistoricalDataAsync(TimeSpan duration);
|
||||
|
||||
/// <summary>
|
||||
/// Clear historical performance data.
|
||||
/// </summary>
|
||||
Task ClearHistoricalDataAsync();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// System performance metrics.
|
||||
/// </summary>
|
||||
public class SystemPerformanceMetrics
|
||||
{
|
||||
public DateTime Timestamp { get; set; } = DateTime.UtcNow;
|
||||
|
||||
public double TotalCpuUsage { get; set; }
|
||||
|
||||
public long TotalMemoryUsage { get; set; }
|
||||
|
||||
public long AvailableMemory { get; set; }
|
||||
|
||||
public long TotalMemory { get; set; }
|
||||
|
||||
public double MemoryUsagePercentage { get; set; }
|
||||
|
||||
public int Gen0Collections { get; set; }
|
||||
|
||||
public int Gen1Collections { get; set; }
|
||||
|
||||
public int Gen2Collections { get; set; }
|
||||
|
||||
public int Gen0CollectionsDelta { get; set; }
|
||||
|
||||
public int Gen1CollectionsDelta { get; set; }
|
||||
|
||||
public int Gen2CollectionsDelta { get; set; }
|
||||
|
||||
public long TotalAllocatedBytes { get; set; }
|
||||
|
||||
public long AllocatedBytesDelta { get; set; }
|
||||
|
||||
public long ManagedHeapSizeBytes { get; set; }
|
||||
|
||||
public long GcCommittedBytes { get; set; }
|
||||
|
||||
public double LastGcPauseMs { get; set; }
|
||||
|
||||
public double MaxGcPauseMs { get; set; }
|
||||
|
||||
public int HandleCount { get; set; }
|
||||
|
||||
public long ProcessWorkingSetBytes { get; set; }
|
||||
|
||||
public List<CpuCoreUsage> CpuCoreUsages { get; set; } = new();
|
||||
|
||||
public ProcessPerformanceInfo? TopCpuProcess { get; set; }
|
||||
|
||||
public ProcessPerformanceInfo? TopMemoryProcess { get; set; }
|
||||
|
||||
public int ActiveProcessCount { get; set; }
|
||||
|
||||
public int ThreadCount { get; set; }
|
||||
|
||||
public double DiskUsage { get; set; }
|
||||
|
||||
public double NetworkUsage { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// CPU core usage information.
|
||||
/// </summary>
|
||||
public class CpuCoreUsage
|
||||
{
|
||||
public int CoreId { get; set; }
|
||||
|
||||
public string CoreName { get; set; } = string.Empty;
|
||||
|
||||
public double Usage { get; set; }
|
||||
|
||||
public string CoreType { get; set; } = "Unknown"; // P-Core, E-Core, etc.
|
||||
|
||||
public bool IsHyperThreaded { get; set; }
|
||||
|
||||
public int PhysicalCoreId { get; set; }
|
||||
|
||||
public double Frequency { get; set; }
|
||||
|
||||
public double Temperature { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Memory usage information.
|
||||
/// </summary>
|
||||
public class MemoryUsageInfo
|
||||
{
|
||||
public long TotalPhysicalMemory { get; set; }
|
||||
|
||||
public long AvailablePhysicalMemory { get; set; }
|
||||
|
||||
public long UsedPhysicalMemory { get; set; }
|
||||
|
||||
public double PhysicalMemoryUsagePercentage { get; set; }
|
||||
|
||||
public long TotalVirtualMemory { get; set; }
|
||||
|
||||
public long AvailableVirtualMemory { get; set; }
|
||||
|
||||
public long UsedVirtualMemory { get; set; }
|
||||
|
||||
public double VirtualMemoryUsagePercentage { get; set; }
|
||||
|
||||
public long PageFileSize { get; set; }
|
||||
|
||||
public long PageFileUsage { get; set; }
|
||||
|
||||
public double PageFileUsagePercentage { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Process performance information.
|
||||
/// </summary>
|
||||
public class ProcessPerformanceInfo
|
||||
{
|
||||
public int ProcessId { get; set; }
|
||||
|
||||
public string ProcessName { get; set; } = string.Empty;
|
||||
|
||||
public string WindowTitle { get; set; } = string.Empty;
|
||||
|
||||
public double CpuUsage { get; set; }
|
||||
|
||||
public long MemoryUsage { get; set; }
|
||||
|
||||
public long VirtualMemoryUsage { get; set; }
|
||||
|
||||
public int ThreadCount { get; set; }
|
||||
|
||||
public int HandleCount { get; set; }
|
||||
|
||||
public DateTime StartTime { get; set; }
|
||||
|
||||
public TimeSpan RunTime { get; set; }
|
||||
|
||||
public string ExecutablePath { get; set; } = string.Empty;
|
||||
|
||||
public bool IsResponding { get; set; }
|
||||
|
||||
public string Priority { get; set; } = string.Empty;
|
||||
|
||||
public IntPtr ProcessorAffinity { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Event args for performance metrics updates.
|
||||
/// </summary>
|
||||
public class PerformanceMetricsUpdatedEventArgs : EventArgs
|
||||
{
|
||||
public SystemPerformanceMetrics Metrics { get; }
|
||||
|
||||
public DateTime UpdateTime { get; }
|
||||
|
||||
public PerformanceMetricsUpdatedEventArgs(SystemPerformanceMetrics metrics)
|
||||
{
|
||||
this.Metrics = metrics;
|
||||
this.UpdateTime = DateTime.UtcNow;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
namespace ThreadPilot.Services
|
||||
{
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Threading.Tasks;
|
||||
using ThreadPilot.Models;
|
||||
|
||||
public interface IPerformanceMonitoringService
|
||||
{
|
||||
Task<SystemPerformanceMetrics> GetSystemMetricsAsync(bool lightweight = false);
|
||||
|
||||
Task<List<CpuCoreUsage>> GetCpuCoreUsageAsync();
|
||||
|
||||
Task<MemoryUsageInfo> GetMemoryUsageAsync();
|
||||
|
||||
Task<List<ProcessPerformanceInfo>> GetTopCpuProcessesAsync(int count = 10);
|
||||
|
||||
Task<List<ProcessPerformanceInfo>> GetTopMemoryProcessesAsync(int count = 10);
|
||||
|
||||
Task StartMonitoringAsync();
|
||||
|
||||
Task StopMonitoringAsync();
|
||||
|
||||
event EventHandler<PerformanceMetricsUpdatedEventArgs>? MetricsUpdated;
|
||||
|
||||
Task<List<SystemPerformanceMetrics>> GetHistoricalDataAsync(TimeSpan duration);
|
||||
|
||||
Task ClearHistoricalDataAsync();
|
||||
}
|
||||
|
||||
public class SystemPerformanceMetrics
|
||||
{
|
||||
public DateTime Timestamp { get; set; } = DateTime.UtcNow;
|
||||
|
||||
public double TotalCpuUsage { get; set; }
|
||||
|
||||
public long TotalMemoryUsage { get; set; }
|
||||
|
||||
public long AvailableMemory { get; set; }
|
||||
|
||||
public long TotalMemory { get; set; }
|
||||
|
||||
public double MemoryUsagePercentage { get; set; }
|
||||
|
||||
public int Gen0Collections { get; set; }
|
||||
|
||||
public int Gen1Collections { get; set; }
|
||||
|
||||
public int Gen2Collections { get; set; }
|
||||
|
||||
public int Gen0CollectionsDelta { get; set; }
|
||||
|
||||
public int Gen1CollectionsDelta { get; set; }
|
||||
|
||||
public int Gen2CollectionsDelta { get; set; }
|
||||
|
||||
public long TotalAllocatedBytes { get; set; }
|
||||
|
||||
public long AllocatedBytesDelta { get; set; }
|
||||
|
||||
public long ManagedHeapSizeBytes { get; set; }
|
||||
|
||||
public long GcCommittedBytes { get; set; }
|
||||
|
||||
public double LastGcPauseMs { get; set; }
|
||||
|
||||
public double MaxGcPauseMs { get; set; }
|
||||
|
||||
public int HandleCount { get; set; }
|
||||
|
||||
public long ProcessWorkingSetBytes { get; set; }
|
||||
|
||||
public List<CpuCoreUsage> CpuCoreUsages { get; set; } = new();
|
||||
|
||||
public ProcessPerformanceInfo? TopCpuProcess { get; set; }
|
||||
|
||||
public ProcessPerformanceInfo? TopMemoryProcess { get; set; }
|
||||
|
||||
public int ActiveProcessCount { get; set; }
|
||||
|
||||
public int ThreadCount { get; set; }
|
||||
|
||||
public double DiskUsage { get; set; }
|
||||
|
||||
public double NetworkUsage { get; set; }
|
||||
}
|
||||
|
||||
public class CpuCoreUsage
|
||||
{
|
||||
public int CoreId { get; set; }
|
||||
|
||||
public string CoreName { get; set; } = string.Empty;
|
||||
|
||||
public double Usage { get; set; }
|
||||
|
||||
public string CoreType { get; set; } = "Unknown"; // P-Core, E-Core, etc.
|
||||
|
||||
public bool IsHyperThreaded { get; set; }
|
||||
|
||||
public int PhysicalCoreId { get; set; }
|
||||
|
||||
public double Frequency { get; set; }
|
||||
|
||||
public double Temperature { get; set; }
|
||||
}
|
||||
|
||||
public class MemoryUsageInfo
|
||||
{
|
||||
public long TotalPhysicalMemory { get; set; }
|
||||
|
||||
public long AvailablePhysicalMemory { get; set; }
|
||||
|
||||
public long UsedPhysicalMemory { get; set; }
|
||||
|
||||
public double PhysicalMemoryUsagePercentage { get; set; }
|
||||
|
||||
public long TotalVirtualMemory { get; set; }
|
||||
|
||||
public long AvailableVirtualMemory { get; set; }
|
||||
|
||||
public long UsedVirtualMemory { get; set; }
|
||||
|
||||
public double VirtualMemoryUsagePercentage { get; set; }
|
||||
|
||||
public long PageFileSize { get; set; }
|
||||
|
||||
public long PageFileUsage { get; set; }
|
||||
|
||||
public double PageFileUsagePercentage { get; set; }
|
||||
}
|
||||
|
||||
public class ProcessPerformanceInfo
|
||||
{
|
||||
public int ProcessId { get; set; }
|
||||
|
||||
public string ProcessName { get; set; } = string.Empty;
|
||||
|
||||
public string WindowTitle { get; set; } = string.Empty;
|
||||
|
||||
public double CpuUsage { get; set; }
|
||||
|
||||
public long MemoryUsage { get; set; }
|
||||
|
||||
public long VirtualMemoryUsage { get; set; }
|
||||
|
||||
public int ThreadCount { get; set; }
|
||||
|
||||
public int HandleCount { get; set; }
|
||||
|
||||
public DateTime StartTime { get; set; }
|
||||
|
||||
public TimeSpan RunTime { get; set; }
|
||||
|
||||
public string ExecutablePath { get; set; } = string.Empty;
|
||||
|
||||
public bool IsResponding { get; set; }
|
||||
|
||||
public string Priority { get; set; } = string.Empty;
|
||||
|
||||
public IntPtr ProcessorAffinity { get; set; }
|
||||
}
|
||||
|
||||
public class PerformanceMetricsUpdatedEventArgs : EventArgs
|
||||
{
|
||||
public SystemPerformanceMetrics Metrics { get; }
|
||||
|
||||
public DateTime UpdateTime { get; }
|
||||
|
||||
public PerformanceMetricsUpdatedEventArgs(SystemPerformanceMetrics metrics)
|
||||
{
|
||||
this.Metrics = metrics;
|
||||
this.UpdateTime = DateTime.UtcNow;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,14 +1,14 @@
|
||||
/*
|
||||
* ThreadPilot - persistent process rule store contract.
|
||||
*/
|
||||
namespace ThreadPilot.Services
|
||||
{
|
||||
using ThreadPilot.Models;
|
||||
|
||||
public interface IPersistentProcessRuleStore
|
||||
{
|
||||
Task<IReadOnlyList<PersistentProcessRule>> LoadAsync();
|
||||
|
||||
Task SaveAsync(IReadOnlyList<PersistentProcessRule> rules);
|
||||
}
|
||||
}
|
||||
/*
|
||||
* ThreadPilot - persistent process rule store contract.
|
||||
*/
|
||||
namespace ThreadPilot.Services
|
||||
{
|
||||
using ThreadPilot.Models;
|
||||
|
||||
public interface IPersistentProcessRuleStore
|
||||
{
|
||||
Task<IReadOnlyList<PersistentProcessRule>> LoadAsync();
|
||||
|
||||
Task SaveAsync(IReadOnlyList<PersistentProcessRule> rules);
|
||||
}
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user