010dee679f
Large changeset adding documentation, themes, converters and wiring between UI and services. Key changes: - Rewrote .gitignore to standardize build, IDE, OS and project-specific ignores. - Added comprehensive documentation: ADVANCED_CPU_FEATURES.md, API_REFERENCE.md, ARCHITECTURE_GUIDE.md, DEVELOPER_GUIDE.md, GAME_BOOST_VALIDATION.md, CLAUDE.md, PROJECT_STRUCTURE.md, UI_STYLE_GUIDE.md, TRADEMARK.md. - Added theme resources (Themes/FluentLight.xaml, Themes/FluentDark.xaml) and merged FluentLight into App.xaml resource dictionary. - Added NullToBoolConverter and registered it in App.xaml. - Enabled a DEBUG-only console test mode in App.xaml.cs (--test flag) and guarded AllocConsole with #if DEBUG. - Added new service/support files (AtomicFileWriter, StoragePaths, ThemeService) and numerous updates across Services (CpuTopologyService, CoreMaskService, PowerPlanService, ProcessMonitorManagerService, ProcessService, NotificationService, SystemTrayService, SystemTweaksService, EnhancedLoggingService, etc.). - Updated many ViewModels and Views to support new functionality (CPU topology, power plan and game-boost features) and tests (Tests/TestRunner.cs). - Added build-release.ps1 and various project metadata updates. Overall this commit introduces documentation, theming, new converters and test/debug support, plus extensive service and UI wiring for CPU topology, process monitoring, power plans and game boost features.
385 lines
15 KiB
C#
385 lines
15 KiB
C#
/*
|
|
* 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 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 General Public License for more details.
|
|
*
|
|
* You should have received a copy of the GNU General Public License
|
|
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
|
*/
|
|
using System;
|
|
using System.Collections.ObjectModel;
|
|
using System.Diagnostics;
|
|
using System.IO;
|
|
using System.Linq;
|
|
using System.Text.RegularExpressions;
|
|
using System.Threading.Tasks;
|
|
using Microsoft.Extensions.Logging;
|
|
using ThreadPilot.Models;
|
|
|
|
namespace ThreadPilot.Services
|
|
{
|
|
public class PowerPlanService : IPowerPlanService
|
|
{
|
|
private static readonly Lazy<string> _powerPlansPath = new(GetPowerPlansPath);
|
|
private static readonly string _powerCfgExecutablePath = Path.Combine(Environment.SystemDirectory, "powercfg.exe");
|
|
private static string PowerPlansPath => _powerPlansPath.Value;
|
|
|
|
private readonly object _lockObject = new();
|
|
private readonly ILogger<PowerPlanService> _logger;
|
|
private readonly IEnhancedLoggingService _enhancedLogger;
|
|
private string? _lastActivePowerPlanGuid;
|
|
|
|
public event EventHandler<PowerPlanChangedEventArgs>? PowerPlanChanged;
|
|
|
|
public PowerPlanService(ILogger<PowerPlanService> logger, IEnhancedLoggingService enhancedLogger)
|
|
{
|
|
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
|
|
_enhancedLogger = enhancedLogger ?? throw new ArgumentNullException(nameof(enhancedLogger));
|
|
}
|
|
|
|
/// <summary>
|
|
/// Gets the power plans path using smart detection:
|
|
/// - Portable mode: Powerplans folder next to EXE
|
|
/// - Installed mode: %AppData%\ThreadPilot\Powerplans
|
|
/// </summary>
|
|
private static string GetPowerPlansPath()
|
|
{
|
|
StoragePaths.EnsureAppDataDirectories();
|
|
|
|
// Check portable mode first (Powerplans folder next to EXE)
|
|
var exeDir = AppContext.BaseDirectory;
|
|
var portablePath = Path.Combine(exeDir, "Powerplans");
|
|
if (Directory.Exists(portablePath) && Directory.GetFiles(portablePath, "*.pow").Length > 0)
|
|
{
|
|
return portablePath;
|
|
}
|
|
|
|
// Installed mode: use AppData
|
|
var appDataPath = StoragePaths.PowerPlansDirectory;
|
|
|
|
// Ensure directory exists
|
|
if (!Directory.Exists(appDataPath))
|
|
{
|
|
Directory.CreateDirectory(appDataPath);
|
|
|
|
// If portable path exists but was empty, or we have bundled plans to copy
|
|
// Copy any .pow files from portable location to AppData
|
|
if (Directory.Exists(portablePath))
|
|
{
|
|
foreach (var file in Directory.GetFiles(portablePath, "*.pow"))
|
|
{
|
|
var destFile = Path.Combine(appDataPath, Path.GetFileName(file));
|
|
if (!File.Exists(destFile))
|
|
{
|
|
try
|
|
{
|
|
File.Copy(file, destFile);
|
|
}
|
|
catch
|
|
{
|
|
// Ignore copy errors, plans may not be available
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
return appDataPath;
|
|
}
|
|
|
|
public async Task<ObservableCollection<PowerPlanModel>> GetPowerPlansAsync()
|
|
{
|
|
return await Task.Run(async () =>
|
|
{
|
|
var powerPlans = new ObservableCollection<PowerPlanModel>();
|
|
var activePlan = await GetActivePowerPlan();
|
|
|
|
var process = new Process
|
|
{
|
|
StartInfo = new ProcessStartInfo
|
|
{
|
|
FileName = _powerCfgExecutablePath,
|
|
Arguments = "/list",
|
|
UseShellExecute = false,
|
|
RedirectStandardOutput = true,
|
|
CreateNoWindow = true
|
|
}
|
|
};
|
|
|
|
process.Start();
|
|
string output = await process.StandardOutput.ReadToEndAsync();
|
|
await process.WaitForExitAsync();
|
|
|
|
var regex = new Regex(@"Power Scheme GUID: (.*?) \((.*?)\)", RegexOptions.Multiline);
|
|
var matches = regex.Matches(output);
|
|
|
|
foreach (Match match in matches)
|
|
{
|
|
var guid = match.Groups[1].Value.Trim();
|
|
var name = match.Groups[2].Value.Trim();
|
|
|
|
var plan = new PowerPlanModel
|
|
{
|
|
Guid = guid,
|
|
Name = name,
|
|
IsActive = guid == activePlan?.Guid,
|
|
IsCustomPlan = false
|
|
};
|
|
|
|
powerPlans.Add(plan);
|
|
}
|
|
|
|
return powerPlans;
|
|
});
|
|
}
|
|
|
|
public async Task<ObservableCollection<PowerPlanModel>> GetCustomPowerPlansAsync()
|
|
{
|
|
return await Task.Run(() =>
|
|
{
|
|
var customPlans = new ObservableCollection<PowerPlanModel>();
|
|
if (!Directory.Exists(PowerPlansPath))
|
|
return customPlans;
|
|
|
|
foreach (var file in Directory.GetFiles(PowerPlansPath, "*.pow"))
|
|
{
|
|
customPlans.Add(new PowerPlanModel
|
|
{
|
|
Name = Path.GetFileNameWithoutExtension(file),
|
|
FilePath = file,
|
|
IsCustomPlan = true
|
|
});
|
|
}
|
|
|
|
return customPlans;
|
|
});
|
|
}
|
|
|
|
public async Task<bool> SetActivePowerPlan(PowerPlanModel powerPlan)
|
|
{
|
|
return await SetActivePowerPlanByGuidAsync(powerPlan.Guid, false);
|
|
}
|
|
|
|
public async Task<bool> SetActivePowerPlanByGuidAsync(string powerPlanGuid, bool preventDuplicateChanges = true)
|
|
{
|
|
return await Task.Run(async () =>
|
|
{
|
|
try
|
|
{
|
|
// Check if change is needed when duplicate prevention is enabled
|
|
if (preventDuplicateChanges)
|
|
{
|
|
var isChangeNeeded = await IsPowerPlanChangeNeededAsync(powerPlanGuid);
|
|
if (!isChangeNeeded)
|
|
{
|
|
_logger.LogDebug("Power plan change skipped - already active: {PowerPlanGuid}", powerPlanGuid);
|
|
return true; // No change needed, consider it successful
|
|
}
|
|
}
|
|
|
|
var previousPowerPlan = await GetActivePowerPlan();
|
|
var targetPowerPlan = await GetPowerPlanByGuidAsync(powerPlanGuid);
|
|
|
|
_logger.LogInformation("Attempting to change power plan from '{FromPlan}' to '{ToPlan}'",
|
|
previousPowerPlan?.Name ?? "Unknown", targetPowerPlan?.Name ?? "Unknown");
|
|
|
|
await _enhancedLogger.LogPowerPlanChangeAsync(
|
|
previousPowerPlan?.Name ?? "Unknown",
|
|
targetPowerPlan?.Name ?? "Unknown",
|
|
"Manual power plan change requested");
|
|
|
|
var process = new Process
|
|
{
|
|
StartInfo = new ProcessStartInfo
|
|
{
|
|
FileName = _powerCfgExecutablePath,
|
|
Arguments = $"/setactive {powerPlanGuid}",
|
|
UseShellExecute = false,
|
|
RedirectStandardOutput = true,
|
|
CreateNoWindow = true
|
|
}
|
|
};
|
|
|
|
process.Start();
|
|
process.WaitForExit();
|
|
|
|
var success = process.ExitCode == 0;
|
|
|
|
if (success)
|
|
{
|
|
lock (_lockObject)
|
|
{
|
|
_lastActivePowerPlanGuid = powerPlanGuid;
|
|
}
|
|
|
|
var newPowerPlan = await GetPowerPlanByGuidAsync(powerPlanGuid);
|
|
|
|
_logger.LogInformation("Power plan successfully changed to '{PowerPlan}'", newPowerPlan?.Name ?? "Unknown");
|
|
|
|
await _enhancedLogger.LogPowerPlanChangeAsync(
|
|
previousPowerPlan?.Name ?? "Unknown",
|
|
newPowerPlan?.Name ?? "Unknown",
|
|
"Manual power plan change completed");
|
|
|
|
PowerPlanChanged?.Invoke(this, new PowerPlanChangedEventArgs(
|
|
previousPowerPlan, newPowerPlan, "Manual power plan change"));
|
|
}
|
|
else
|
|
{
|
|
_logger.LogWarning("Failed to change power plan to '{PowerPlanGuid}' - powercfg exit code: {ExitCode}",
|
|
powerPlanGuid, process.ExitCode);
|
|
|
|
await _enhancedLogger.LogSystemEventAsync(LogEventTypes.PowerPlan.ChangeFailed,
|
|
$"Failed to change power plan to '{targetPowerPlan?.Name ?? powerPlanGuid}' - Exit code: {process.ExitCode}",
|
|
Microsoft.Extensions.Logging.LogLevel.Warning);
|
|
}
|
|
|
|
return success;
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
_logger.LogError(ex, "Exception occurred while changing power plan to '{PowerPlanGuid}'", powerPlanGuid);
|
|
|
|
await _enhancedLogger.LogErrorAsync(ex, "PowerPlanService.SetActivePowerPlanByGuidAsync",
|
|
new Dictionary<string, object>
|
|
{
|
|
["PowerPlanGuid"] = powerPlanGuid,
|
|
["PreventDuplicateChanges"] = preventDuplicateChanges
|
|
});
|
|
|
|
return false;
|
|
}
|
|
});
|
|
}
|
|
|
|
public async Task<PowerPlanModel?> GetActivePowerPlan()
|
|
{
|
|
return await Task.Run(() =>
|
|
{
|
|
try
|
|
{
|
|
var process = new Process
|
|
{
|
|
StartInfo = new ProcessStartInfo
|
|
{
|
|
FileName = _powerCfgExecutablePath,
|
|
Arguments = "/getactivescheme",
|
|
UseShellExecute = false,
|
|
RedirectStandardOutput = true,
|
|
CreateNoWindow = true
|
|
}
|
|
};
|
|
|
|
process.Start();
|
|
string output = process.StandardOutput.ReadToEnd();
|
|
process.WaitForExit();
|
|
|
|
var regex = new Regex(@"Power Scheme GUID: (.*?) \((.*?)\)", RegexOptions.Multiline);
|
|
var match = regex.Match(output);
|
|
|
|
if (match.Success)
|
|
{
|
|
return new PowerPlanModel
|
|
{
|
|
Guid = match.Groups[1].Value.Trim(),
|
|
Name = match.Groups[2].Value.Trim(),
|
|
IsActive = true
|
|
};
|
|
}
|
|
|
|
return null;
|
|
}
|
|
catch (Exception)
|
|
{
|
|
return null;
|
|
}
|
|
});
|
|
}
|
|
|
|
public async Task<bool> ImportCustomPowerPlan(string filePath)
|
|
{
|
|
return await Task.Run(() =>
|
|
{
|
|
try
|
|
{
|
|
var process = new Process
|
|
{
|
|
StartInfo = new ProcessStartInfo
|
|
{
|
|
FileName = _powerCfgExecutablePath,
|
|
Arguments = $"/import \"{filePath}\"",
|
|
UseShellExecute = false,
|
|
RedirectStandardOutput = true,
|
|
CreateNoWindow = true
|
|
}
|
|
};
|
|
|
|
process.Start();
|
|
process.WaitForExit();
|
|
|
|
return process.ExitCode == 0;
|
|
}
|
|
catch (Exception)
|
|
{
|
|
return false;
|
|
}
|
|
});
|
|
}
|
|
|
|
public async Task<string?> GetActivePowerPlanGuidAsync()
|
|
{
|
|
var activePlan = await GetActivePowerPlan();
|
|
return activePlan?.Guid;
|
|
}
|
|
|
|
public async Task<bool> PowerPlanExistsAsync(string powerPlanGuid)
|
|
{
|
|
var powerPlans = await GetPowerPlansAsync();
|
|
return powerPlans.Any(p => string.Equals(p.Guid, powerPlanGuid, StringComparison.OrdinalIgnoreCase));
|
|
}
|
|
|
|
public async Task<PowerPlanModel?> GetPowerPlanByGuidAsync(string powerPlanGuid)
|
|
{
|
|
var powerPlans = await GetPowerPlansAsync();
|
|
return powerPlans.FirstOrDefault(p => string.Equals(p.Guid, powerPlanGuid, StringComparison.OrdinalIgnoreCase));
|
|
}
|
|
|
|
public async Task<bool> IsPowerPlanChangeNeededAsync(string targetPowerPlanGuid)
|
|
{
|
|
try
|
|
{
|
|
var currentGuid = await GetActivePowerPlanGuidAsync();
|
|
|
|
// Check if the target power plan is already active
|
|
if (string.Equals(currentGuid, targetPowerPlanGuid, StringComparison.OrdinalIgnoreCase))
|
|
{
|
|
return false; // No change needed
|
|
}
|
|
|
|
// Check if we recently set this power plan (to prevent rapid switching)
|
|
lock (_lockObject)
|
|
{
|
|
if (string.Equals(_lastActivePowerPlanGuid, targetPowerPlanGuid, StringComparison.OrdinalIgnoreCase))
|
|
{
|
|
return false; // We recently set this plan
|
|
}
|
|
}
|
|
|
|
return true; // Change is needed
|
|
}
|
|
catch
|
|
{
|
|
return true; // If we can't determine, assume change is needed
|
|
}
|
|
}
|
|
}
|
|
}
|