chore: initial enterprise setup - governance, CI/CD, security hardening batch 1
This commit is contained in:
@@ -0,0 +1,32 @@
|
||||
root = true
|
||||
|
||||
[*]
|
||||
charset = utf-8
|
||||
end_of_line = crlf
|
||||
insert_final_newline = true
|
||||
trim_trailing_whitespace = true
|
||||
indent_style = space
|
||||
indent_size = 4
|
||||
|
||||
[*.{cs,csx}]
|
||||
dotnet_sort_system_directives_first = true
|
||||
dotnet_separate_import_directive_groups = false
|
||||
csharp_new_line_before_open_brace = all
|
||||
csharp_style_var_for_built_in_types = false:suggestion
|
||||
csharp_style_var_when_type_is_apparent = false:suggestion
|
||||
csharp_style_var_elsewhere = false:suggestion
|
||||
csharp_prefer_braces = true:warning
|
||||
dotnet_style_qualification_for_field = false:suggestion
|
||||
dotnet_style_qualification_for_property = false:suggestion
|
||||
dotnet_style_qualification_for_method = false:suggestion
|
||||
dotnet_style_qualification_for_event = false:suggestion
|
||||
dotnet_style_object_initializer = true:suggestion
|
||||
dotnet_style_collection_initializer = true:suggestion
|
||||
dotnet_style_predefined_type_for_locals_parameters_members = true:suggestion
|
||||
dotnet_style_predefined_type_for_member_access = true:suggestion
|
||||
|
||||
[*.xaml]
|
||||
indent_size = 2
|
||||
|
||||
[*.md]
|
||||
trim_trailing_whitespace = false
|
||||
@@ -0,0 +1,11 @@
|
||||
* @PrimeBuild-pc
|
||||
|
||||
# Core system and process management
|
||||
/Services/ @PrimeBuild-pc
|
||||
/ViewModels/ @PrimeBuild-pc
|
||||
/Platforms/ @PrimeBuild-pc
|
||||
|
||||
# Build and release
|
||||
/.github/workflows/ @PrimeBuild-pc
|
||||
/build-release.ps1 @PrimeBuild-pc
|
||||
/setup.iss @PrimeBuild-pc
|
||||
@@ -0,0 +1,48 @@
|
||||
name: Bug Report
|
||||
description: Report a reproducible bug in ThreadPilot
|
||||
labels: [bug]
|
||||
body:
|
||||
- type: markdown
|
||||
attributes:
|
||||
value: |
|
||||
Please include clear reproduction steps and environment details.
|
||||
- type: input
|
||||
id: version
|
||||
attributes:
|
||||
label: Version
|
||||
placeholder: 1.1.0
|
||||
validations:
|
||||
required: true
|
||||
- type: dropdown
|
||||
id: os
|
||||
attributes:
|
||||
label: Windows Version
|
||||
options:
|
||||
- Windows 11
|
||||
- Windows 10 22H2+
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: steps
|
||||
attributes:
|
||||
label: Reproduction Steps
|
||||
description: Step-by-step instructions to reproduce the issue
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: expected
|
||||
attributes:
|
||||
label: Expected Behavior
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: actual
|
||||
attributes:
|
||||
label: Actual Behavior
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: logs
|
||||
attributes:
|
||||
label: Logs and Diagnostics
|
||||
description: Include relevant app logs and stack traces
|
||||
@@ -0,0 +1,5 @@
|
||||
blank_issues_enabled: false
|
||||
contact_links:
|
||||
- name: Security Report
|
||||
url: https://github.com/PrimeBuild-pc/ThreadPilot/security/advisories/new
|
||||
about: Report vulnerabilities privately using GitHub Security Advisories.
|
||||
@@ -0,0 +1,27 @@
|
||||
name: Feature Request
|
||||
description: Suggest an improvement for ThreadPilot
|
||||
labels: [enhancement]
|
||||
body:
|
||||
- type: textarea
|
||||
id: problem
|
||||
attributes:
|
||||
label: Problem Statement
|
||||
description: What problem are you trying to solve?
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: proposal
|
||||
attributes:
|
||||
label: Proposed Solution
|
||||
description: Describe your preferred solution
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: alternatives
|
||||
attributes:
|
||||
label: Alternatives Considered
|
||||
- type: textarea
|
||||
id: impact
|
||||
attributes:
|
||||
label: Impact Areas
|
||||
description: Process management, affinity, power plans, UI, performance, etc.
|
||||
@@ -0,0 +1,25 @@
|
||||
## Summary
|
||||
|
||||
Describe what changed and why.
|
||||
|
||||
## Type of Change
|
||||
- [ ] Bug fix
|
||||
- [ ] Feature
|
||||
- [ ] Refactor
|
||||
- [ ] Documentation
|
||||
- [ ] Security hardening
|
||||
- [ ] Performance improvement
|
||||
|
||||
## Validation
|
||||
- [ ] Built Debug and Release successfully
|
||||
- [ ] Ran automated tests
|
||||
- [ ] Verified impacted UI flows
|
||||
- [ ] Verified no secrets/credentials introduced
|
||||
|
||||
## Security and Risk Notes
|
||||
List any impact on elevation, process control, power plan operations, or persisted configuration.
|
||||
|
||||
## Checklist
|
||||
- [ ] Updated docs where relevant
|
||||
- [ ] Added or updated tests where relevant
|
||||
- [ ] Kept changes scoped and backwards compatible where possible
|
||||
@@ -0,0 +1,10 @@
|
||||
version: 2
|
||||
updates:
|
||||
- package-ecosystem: nuget
|
||||
directory: /
|
||||
schedule:
|
||||
interval: weekly
|
||||
open-pull-requests-limit: 10
|
||||
labels:
|
||||
- dependencies
|
||||
- security
|
||||
@@ -4,9 +4,14 @@ on:
|
||||
push:
|
||||
branches: ["main", "master"]
|
||||
pull_request:
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
actions: read
|
||||
|
||||
jobs:
|
||||
build-and-scan:
|
||||
build-test-scan:
|
||||
runs-on: windows-latest
|
||||
|
||||
steps:
|
||||
@@ -19,42 +24,63 @@ jobs:
|
||||
dotnet-version: "8.0.x"
|
||||
|
||||
- name: Restore
|
||||
run: dotnet restore "ThreadPilot.csproj"
|
||||
run: dotnet restore "ThreadPilot_1.sln"
|
||||
|
||||
- name: Verify formatting
|
||||
continue-on-error: true
|
||||
run: dotnet format "ThreadPilot_1.sln" --verify-no-changes --verbosity diagnostic --report dotnet-format-report.json
|
||||
|
||||
- name: Build Debug
|
||||
run: dotnet build "ThreadPilot.csproj" --configuration Debug --no-restore
|
||||
run: dotnet build "ThreadPilot_1.sln" --configuration Debug --no-restore
|
||||
|
||||
- name: Build Release
|
||||
run: dotnet build "ThreadPilot.csproj" --configuration Release --no-restore
|
||||
run: dotnet build "ThreadPilot_1.sln" --configuration Release --no-restore
|
||||
|
||||
- name: Dependency Audit
|
||||
run: dotnet list "ThreadPilot.csproj" package --vulnerable --include-transitive
|
||||
- name: Run tests
|
||||
run: dotnet test "ThreadPilot_1.sln" --configuration Release --no-build --verbosity normal
|
||||
|
||||
- name: Secret Scan (Gitleaks)
|
||||
- name: Dependency vulnerability audit
|
||||
shell: pwsh
|
||||
run: |
|
||||
$ErrorActionPreference = "Stop"
|
||||
$audit = dotnet list "ThreadPilot.csproj" package --vulnerable --include-transitive
|
||||
$audit | Out-String | Write-Host
|
||||
|
||||
if ($LASTEXITCODE -ne 0) {
|
||||
throw "dotnet list package --vulnerable failed."
|
||||
}
|
||||
|
||||
if ($audit -match "has the following vulnerable packages") {
|
||||
throw "Vulnerable packages detected."
|
||||
}
|
||||
|
||||
- name: Secret scan (Gitleaks)
|
||||
shell: pwsh
|
||||
run: |
|
||||
$ErrorActionPreference = "Stop"
|
||||
$version = "8.24.3"
|
||||
$baseUrl = "https://github.com/gitleaks/gitleaks/releases/download/v$version"
|
||||
$zipAsset = "gitleaks_${version}_windows_x64.zip"
|
||||
$tarAsset = "gitleaks_${version}_windows_x64.tar.gz"
|
||||
|
||||
Write-Host "Installing Gitleaks v$version"
|
||||
|
||||
try {
|
||||
Invoke-WebRequest -Uri "$baseUrl/$zipAsset" -OutFile "gitleaks.zip"
|
||||
Expand-Archive -Path "gitleaks.zip" -DestinationPath ".\\gitleaks-bin" -Force
|
||||
}
|
||||
catch {
|
||||
Write-Host "ZIP download failed, trying tar.gz fallback"
|
||||
Invoke-WebRequest -Uri "$baseUrl/$tarAsset" -OutFile "gitleaks.tar.gz"
|
||||
New-Item -ItemType Directory -Force -Path ".\\gitleaks-bin" | Out-Null
|
||||
tar -xzf "gitleaks.tar.gz" -C ".\\gitleaks-bin"
|
||||
}
|
||||
|
||||
$gitleaksExe = Resolve-Path ".\\gitleaks-bin\\gitleaks.exe"
|
||||
& $gitleaksExe version
|
||||
& $gitleaksExe detect --source "." --redact --verbose --report-format json --report-path gitleaks-report.json
|
||||
|
||||
# Scan working tree for hardcoded secrets.
|
||||
& $gitleaksExe detect --source "." --redact --verbose
|
||||
- name: Upload security artifacts
|
||||
if: always()
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: security-reports
|
||||
path: |
|
||||
gitleaks-report.json
|
||||
dotnet-format-report.json
|
||||
|
||||
@@ -1,10 +1,7 @@
|
||||
name: .NET Build
|
||||
name: .NET Compatibility Build
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [ "main" ]
|
||||
pull_request:
|
||||
branches: [ "main" ]
|
||||
workflow_dispatch:
|
||||
|
||||
jobs:
|
||||
build:
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
name: Release
|
||||
|
||||
on:
|
||||
push:
|
||||
tags:
|
||||
- "v*.*.*"
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
|
||||
jobs:
|
||||
build-and-release:
|
||||
runs-on: windows-latest
|
||||
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Setup .NET
|
||||
uses: actions/setup-dotnet@v4
|
||||
with:
|
||||
dotnet-version: "8.0.x"
|
||||
|
||||
- name: Restore
|
||||
run: dotnet restore "ThreadPilot_1.sln"
|
||||
|
||||
- name: Build
|
||||
run: dotnet build "ThreadPilot_1.sln" --configuration Release --no-restore
|
||||
|
||||
- name: Publish self-contained app
|
||||
run: dotnet publish "ThreadPilot.csproj" --configuration Release --runtime win-x64 --self-contained true -o artifacts/release/win-x64
|
||||
|
||||
- name: Create release package
|
||||
shell: pwsh
|
||||
run: |
|
||||
$ErrorActionPreference = "Stop"
|
||||
$version = "${{ github.ref_name }}"
|
||||
$zipName = "ThreadPilot_$version`_win-x64.zip"
|
||||
Compress-Archive -Path "artifacts/release/win-x64/*" -DestinationPath "artifacts/release/$zipName" -Force
|
||||
|
||||
- name: Generate checksums
|
||||
shell: pwsh
|
||||
run: |
|
||||
$ErrorActionPreference = "Stop"
|
||||
$hashFile = "artifacts/release/SHA256SUMS.txt"
|
||||
Get-ChildItem "artifacts/release" -File | ForEach-Object {
|
||||
$hash = Get-FileHash $_.FullName -Algorithm SHA256
|
||||
"$($hash.Hash) $($_.Name)" | Out-File -FilePath $hashFile -Append -Encoding utf8
|
||||
}
|
||||
|
||||
- name: Publish GitHub release
|
||||
uses: softprops/action-gh-release@v2
|
||||
with:
|
||||
files: |
|
||||
artifacts/release/*.zip
|
||||
artifacts/release/SHA256SUMS.txt
|
||||
generate_release_notes: true
|
||||
+1
-13
@@ -120,16 +120,4 @@ secrets.json
|
||||
*.mdmp
|
||||
crashdumps/
|
||||
*.binlog
|
||||
nul
|
||||
|
||||
ADVANCED_CPU_FEATURES.md
|
||||
API_REFERENCE.md
|
||||
ARCHITECTURE_GUIDE.md
|
||||
CLAUDE.md
|
||||
DEVELOPER_GUIDE.md
|
||||
GAME_BOOST_VALIDATION.md
|
||||
PROJECT_STRUCTURE.md
|
||||
TRADEMARK.md
|
||||
UI_STYLE_GUIDE.md
|
||||
COMPLIANCE_AUDIT.md
|
||||
implementation_plan.md
|
||||
nul
|
||||
@@ -0,0 +1,128 @@
|
||||
# Advanced CPU Core Detection and Affinity Selection
|
||||
|
||||
## Overview
|
||||
|
||||
ThreadPilot now includes advanced CPU topology detection and dynamic core selection capabilities, supporting modern CPU architectures including multi-socket systems, AMD CCD (Core Complex Die), Intel Hybrid (P-core/E-core), and SMT/HyperThreading.
|
||||
|
||||
## Features
|
||||
|
||||
### 🔍 CPU Topology Detection
|
||||
- **Automatic Detection**: Uses WMI (Windows Management Instrumentation) to detect CPU topology
|
||||
- **Fallback Support**: Graceful degradation when advanced topology information is unavailable
|
||||
- **Real-time Updates**: Event-driven topology detection with UI updates
|
||||
- **Architecture Support**:
|
||||
- Intel Hybrid (Performance + Efficiency cores)
|
||||
- AMD CCD (Core Complex Die) detection
|
||||
- SMT/HyperThreading identification
|
||||
- Multi-socket systems
|
||||
|
||||
### 🎯 Quick Selection Controls
|
||||
- **All Cores**: Select all available CPU cores
|
||||
- **Physical Cores Only**: Select only physical cores (excludes hyperthreaded siblings)
|
||||
- **Performance Cores**: Select Intel P-cores only (Intel Hybrid)
|
||||
- **Efficiency Cores**: Select Intel E-cores only (Intel Hybrid)
|
||||
- **CCD Selection**: Select cores from specific CCDs (AMD processors)
|
||||
|
||||
### 🖥️ Dynamic UI
|
||||
- **Adaptive Interface**: CPU core grid adapts to detected topology
|
||||
- **Visual Indicators**: Color-coded core types and status
|
||||
- **Topology Status**: Real-time display of detection success/failure
|
||||
- **Scrollable Grid**: Supports systems with many CPU cores
|
||||
|
||||
### ⚡ Power Plan Integration
|
||||
- **Combined Application**: Apply both CPU affinity and power plan in one action
|
||||
- **Quick Apply**: Fast reapplication of settings to selected processes
|
||||
- **System Tray**: Context menu for quick access without opening main window
|
||||
|
||||
## Usage
|
||||
|
||||
### Basic Usage
|
||||
1. **Select a Process**: Choose a process from the process list
|
||||
2. **View Topology**: CPU topology is automatically detected and displayed
|
||||
3. **Select Cores**: Use quick selection buttons or manually select individual cores
|
||||
4. **Apply Settings**: Use "Apply Affinity" or "Quick Apply Affinity & Power Plan"
|
||||
|
||||
### Quick Selection Buttons
|
||||
- **All Cores**: Selects all available CPU cores
|
||||
- **Physical Only**: Selects only physical cores (useful for avoiding HT conflicts)
|
||||
- **P-Cores**: Selects Intel Performance cores (Intel 12th gen+)
|
||||
- **E-Cores**: Selects Intel Efficiency cores (Intel 12th gen+)
|
||||
- **CCD 0/1/2...**: Selects cores from specific AMD CCDs
|
||||
|
||||
### System Tray Integration
|
||||
- **Quick Apply**: Right-click tray icon → "Quick Apply to [ProcessName]"
|
||||
- **Show Window**: Double-click tray icon or right-click → "Show ThreadPilot"
|
||||
- **Minimize to Tray**: Window minimizes to system tray instead of taskbar
|
||||
|
||||
## Technical Details
|
||||
|
||||
### CPU Topology Models
|
||||
- **CpuTopologyModel**: Main topology container with architecture detection
|
||||
- **CpuCoreModel**: Individual core representation with type and topology info
|
||||
- **CpuAffinityPreset**: Pre-configured affinity selections for quick access
|
||||
|
||||
### Services
|
||||
- **ICpuTopologyService**: Interface for CPU topology detection and management
|
||||
- **CpuTopologyService**: WMI-based implementation with fallback mechanisms
|
||||
- **ISystemTrayService**: System tray icon and context menu management
|
||||
|
||||
### Architecture Detection
|
||||
- **Intel Hybrid**: Detects P-cores and E-cores using WMI processor information
|
||||
- **AMD CCD**: Identifies Core Complex Dies for NUMA-aware core selection
|
||||
- **SMT/HyperThreading**: Distinguishes physical cores from logical threads
|
||||
- **Multi-socket**: Supports systems with multiple CPU sockets
|
||||
|
||||
## Testing
|
||||
|
||||
### Test Mode
|
||||
Run the application with `--test` parameter to execute CPU topology detection tests:
|
||||
```
|
||||
ThreadPilot.exe --test
|
||||
```
|
||||
|
||||
### Manual Testing
|
||||
1. Open ThreadPilot
|
||||
2. Navigate to Process Management tab
|
||||
3. Select any process
|
||||
4. Verify CPU topology detection status
|
||||
5. Test quick selection buttons
|
||||
6. Apply affinity settings and verify they take effect
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### Topology Detection Failed
|
||||
- **Cause**: WMI access restrictions or unsupported hardware
|
||||
- **Solution**: Run as Administrator or use fallback mode
|
||||
- **Fallback**: Basic core enumeration without advanced features
|
||||
|
||||
### Quick Selection Not Working
|
||||
- **Cause**: No process selected or topology detection failed
|
||||
- **Solution**: Select a process and ensure topology detection succeeded
|
||||
- **Check**: Topology status indicator in the UI
|
||||
|
||||
### System Tray Not Visible
|
||||
- **Cause**: Windows Forms package not available or permissions issue
|
||||
- **Solution**: Ensure System.Windows.Forms package is installed
|
||||
- **Alternative**: Use main window controls
|
||||
|
||||
## Performance Considerations
|
||||
|
||||
- **WMI Queries**: Topology detection uses cached results to minimize overhead
|
||||
- **UI Updates**: Core selection changes are batched for better performance
|
||||
- **Memory Usage**: Topology models are lightweight and reused across processes
|
||||
- **Background Detection**: Topology detection runs asynchronously without blocking UI
|
||||
|
||||
## Compatibility
|
||||
|
||||
- **Windows Version**: Windows 7 or later (WMI support required)
|
||||
- **CPU Support**: Intel and AMD processors with standard WMI interfaces
|
||||
- **Architecture**: x64 and ARM64 (where WMI topology data is available)
|
||||
- **.NET Version**: .NET 9.0 or later
|
||||
|
||||
## Future Enhancements
|
||||
|
||||
- **NUMA Awareness**: Automatic NUMA node detection and optimization
|
||||
- **Performance Monitoring**: Real-time CPU usage per core type
|
||||
- **Profile Management**: Save/load CPU affinity profiles
|
||||
- **Scheduler Integration**: Windows scheduler hint optimization
|
||||
- **Advanced Presets**: Custom affinity patterns for specific workloads
|
||||
@@ -0,0 +1,318 @@
|
||||
# ThreadPilot API Reference
|
||||
|
||||
## Core Interfaces
|
||||
|
||||
### ISystemService
|
||||
Base interface for all system services providing lifecycle management.
|
||||
|
||||
```csharp
|
||||
public interface ISystemService
|
||||
{
|
||||
bool IsAvailable { get; }
|
||||
event EventHandler<ServiceAvailabilityChangedEventArgs>? AvailabilityChanged;
|
||||
Task InitializeAsync();
|
||||
Task DisposeAsync();
|
||||
}
|
||||
```
|
||||
|
||||
**Key Methods:**
|
||||
- `InitializeAsync()`: Initialize service resources
|
||||
- `DisposeAsync()`: Clean up service resources
|
||||
- `IsAvailable`: Indicates if service is operational
|
||||
|
||||
### IRepository<T>
|
||||
Generic repository interface for data access operations.
|
||||
|
||||
```csharp
|
||||
public interface IRepository<T> : IRepository<T, string> where T : class
|
||||
{
|
||||
Task<T?> GetByIdAsync(string id);
|
||||
Task<IEnumerable<T>> GetAllAsync();
|
||||
Task<IEnumerable<T>> FindAsync(Expression<Func<T, bool>> predicate);
|
||||
Task<T> AddAsync(T entity);
|
||||
Task<T> UpdateAsync(T entity);
|
||||
Task<bool> DeleteAsync(string id);
|
||||
Task<bool> ExistsAsync(string id);
|
||||
Task<int> CountAsync();
|
||||
}
|
||||
```
|
||||
|
||||
## Core Services
|
||||
|
||||
### IProcessService
|
||||
Manages process enumeration and manipulation.
|
||||
|
||||
```csharp
|
||||
public interface IProcessService
|
||||
{
|
||||
Task<IEnumerable<ProcessModel>> GetRunningProcessesAsync();
|
||||
Task<bool> SetProcessPriorityAsync(int processId, ProcessPriorityClass priority);
|
||||
Task<bool> SetProcessAffinityAsync(int processId, long affinityMask);
|
||||
Task<ProcessModel?> GetProcessByIdAsync(int processId);
|
||||
bool IsProcessRunning(string processName);
|
||||
}
|
||||
```
|
||||
|
||||
**Key Features:**
|
||||
- Async process enumeration
|
||||
- Priority and affinity management
|
||||
- Process existence checking
|
||||
|
||||
### IPowerPlanService
|
||||
Manages Windows power plans.
|
||||
|
||||
```csharp
|
||||
public interface IPowerPlanService
|
||||
{
|
||||
Task<IEnumerable<PowerPlanModel>> GetAvailablePowerPlansAsync();
|
||||
Task<PowerPlanModel?> GetActivePowerPlanAsync();
|
||||
Task<bool> SetActivePowerPlanAsync(string powerPlanGuid);
|
||||
Task<PowerPlanModel?> GetPowerPlanByGuidAsync(string guid);
|
||||
event EventHandler<PowerPlanChangedEventArgs>? PowerPlanChanged;
|
||||
}
|
||||
```
|
||||
|
||||
**Key Features:**
|
||||
- Power plan enumeration and activation
|
||||
- Change event notifications
|
||||
- GUID-based plan identification
|
||||
|
||||
### ICpuTopologyService
|
||||
Provides CPU topology detection and affinity management.
|
||||
|
||||
```csharp
|
||||
public interface ICpuTopologyService
|
||||
{
|
||||
Task<CpuTopologyModel> DetectTopologyAsync();
|
||||
Task<bool> SetProcessAffinityAsync(int processId, IEnumerable<int> coreIds);
|
||||
Task<long> GetProcessAffinityAsync(int processId);
|
||||
event EventHandler<CpuTopologyDetectedEventArgs>? TopologyDetected;
|
||||
}
|
||||
```
|
||||
|
||||
**Key Features:**
|
||||
- Modern CPU architecture detection
|
||||
- Core affinity management
|
||||
- Support for hybrid architectures
|
||||
|
||||
## Business Logic Services
|
||||
|
||||
### IProcessMonitorManagerService
|
||||
Orchestrates process monitoring and power plan switching.
|
||||
|
||||
```csharp
|
||||
public interface IProcessMonitorManagerService
|
||||
{
|
||||
bool IsMonitoringActive { get; }
|
||||
Task StartMonitoringAsync();
|
||||
Task StopMonitoringAsync();
|
||||
event EventHandler<ProcessEventArgs>? ProcessStarted;
|
||||
event EventHandler<ProcessEventArgs>? ProcessStopped;
|
||||
event EventHandler? MonitoringStarted;
|
||||
event EventHandler? MonitoringStopped;
|
||||
}
|
||||
```
|
||||
|
||||
**Key Features:**
|
||||
- WMI-based process monitoring
|
||||
- Automatic power plan switching
|
||||
- Fallback polling mechanism
|
||||
|
||||
### IGameBoostService
|
||||
Manages game detection and performance optimization.
|
||||
|
||||
```csharp
|
||||
public interface IGameBoostService
|
||||
{
|
||||
bool IsGameBoostActive { get; }
|
||||
string? CurrentGameName { get; }
|
||||
Task<bool> ActivateGameBoostAsync(ProcessModel gameProcess);
|
||||
Task DeactivateGameBoostAsync();
|
||||
Task<bool> AddKnownGameAsync(string executableName);
|
||||
Task<bool> RemoveKnownGameAsync(string executableName);
|
||||
event EventHandler<GameBoostEventArgs>? GameBoostActivated;
|
||||
event EventHandler<GameBoostEventArgs>? GameBoostDeactivated;
|
||||
}
|
||||
```
|
||||
|
||||
**Key Features:**
|
||||
- Automatic game detection
|
||||
- Performance optimization
|
||||
- Configurable game database
|
||||
|
||||
## Application Services
|
||||
|
||||
### IApplicationSettingsService
|
||||
Manages application configuration and persistence.
|
||||
|
||||
```csharp
|
||||
public interface IApplicationSettingsService
|
||||
{
|
||||
ApplicationSettingsModel Settings { get; }
|
||||
Task LoadSettingsAsync();
|
||||
Task SaveSettingsAsync();
|
||||
Task ResetToDefaultsAsync();
|
||||
Task<bool> ExportSettingsAsync(string filePath);
|
||||
Task<bool> ImportSettingsAsync(string filePath);
|
||||
event EventHandler<SettingsChangedEventArgs>? SettingsChanged;
|
||||
}
|
||||
```
|
||||
|
||||
**Key Features:**
|
||||
- Automatic settings persistence
|
||||
- Import/export functionality
|
||||
- Change notifications
|
||||
|
||||
### INotificationService
|
||||
Handles user notifications and system tray integration.
|
||||
|
||||
```csharp
|
||||
public interface INotificationService
|
||||
{
|
||||
Task ShowNotificationAsync(string title, string message, NotificationType type);
|
||||
Task ShowBalloonNotificationAsync(string title, string message, int duration);
|
||||
Task ShowToastNotificationAsync(string title, string message);
|
||||
Task ClearAllNotificationsAsync();
|
||||
}
|
||||
```
|
||||
|
||||
**Key Features:**
|
||||
- Multiple notification types
|
||||
- System tray balloon tips
|
||||
- Windows toast notifications
|
||||
|
||||
### IEnhancedLoggingService
|
||||
Provides structured logging with file persistence.
|
||||
|
||||
```csharp
|
||||
public interface IEnhancedLoggingService
|
||||
{
|
||||
Task LogPowerPlanChangeAsync(string fromPlan, string toPlan, string reason);
|
||||
Task LogProcessEventAsync(string processName, string eventType, string details);
|
||||
Task LogGameBoostEventAsync(string gameName, string action, string details);
|
||||
Task LogUserActionAsync(string action, string details, string? context = null);
|
||||
Task LogErrorAsync(string source, string error, string? stackTrace = null);
|
||||
Task<IEnumerable<LogEntry>> GetLogEntriesAsync(DateTime? fromDate = null, DateTime? toDate = null);
|
||||
}
|
||||
```
|
||||
|
||||
**Key Features:**
|
||||
- Structured event logging
|
||||
- File rotation and management
|
||||
- Query capabilities
|
||||
|
||||
## Data Models
|
||||
|
||||
### ProcessModel
|
||||
Represents a system process with extended information.
|
||||
|
||||
```csharp
|
||||
public partial class ProcessModel : ObservableObject
|
||||
{
|
||||
public int ProcessId { get; set; }
|
||||
public string Name { get; set; }
|
||||
public string ExecutablePath { get; set; }
|
||||
public ProcessPriorityClass Priority { get; set; }
|
||||
public long ProcessorAffinity { get; set; }
|
||||
public double CpuUsage { get; set; }
|
||||
public long WorkingSet { get; set; }
|
||||
}
|
||||
```
|
||||
|
||||
### PowerPlanModel
|
||||
Represents a Windows power plan.
|
||||
|
||||
```csharp
|
||||
public partial class PowerPlanModel : ObservableObject
|
||||
{
|
||||
public string Guid { get; set; }
|
||||
public string Name { get; set; }
|
||||
public string Description { get; set; }
|
||||
public bool IsActive { get; set; }
|
||||
}
|
||||
```
|
||||
|
||||
### CpuTopologyModel
|
||||
Represents CPU topology information.
|
||||
|
||||
```csharp
|
||||
public partial class CpuTopologyModel : ObservableObject
|
||||
{
|
||||
public int TotalCores { get; set; }
|
||||
public int PhysicalCores { get; set; }
|
||||
public int LogicalCores { get; set; }
|
||||
public bool HasHybridArchitecture { get; set; }
|
||||
public ObservableCollection<CpuCoreModel> Cores { get; set; }
|
||||
}
|
||||
```
|
||||
|
||||
## Event Arguments
|
||||
|
||||
### ProcessEventArgs
|
||||
Provides data for process-related events.
|
||||
|
||||
```csharp
|
||||
public class ProcessEventArgs : EventArgs
|
||||
{
|
||||
public ProcessModel Process { get; }
|
||||
public DateTime Timestamp { get; }
|
||||
public string EventType { get; }
|
||||
}
|
||||
```
|
||||
|
||||
### PowerPlanChangedEventArgs
|
||||
Provides data for power plan change events.
|
||||
|
||||
```csharp
|
||||
public class PowerPlanChangedEventArgs : EventArgs
|
||||
{
|
||||
public PowerPlanModel? PreviousPlan { get; }
|
||||
public PowerPlanModel CurrentPlan { get; }
|
||||
public string Reason { get; }
|
||||
public DateTime Timestamp { get; }
|
||||
}
|
||||
```
|
||||
|
||||
### GameBoostEventArgs
|
||||
Provides data for game boost events.
|
||||
|
||||
```csharp
|
||||
public class GameBoostEventArgs : EventArgs
|
||||
{
|
||||
public ProcessModel? GameProcess { get; }
|
||||
public bool IsActivated { get; }
|
||||
public DateTime Timestamp { get; }
|
||||
}
|
||||
```
|
||||
|
||||
## Configuration Enums
|
||||
|
||||
### NotificationType
|
||||
Defines notification types for the notification service.
|
||||
|
||||
```csharp
|
||||
public enum NotificationType
|
||||
{
|
||||
Information,
|
||||
Warning,
|
||||
Error,
|
||||
Success
|
||||
}
|
||||
```
|
||||
|
||||
### ProcessPriorityClass
|
||||
Standard .NET process priority enumeration.
|
||||
|
||||
```csharp
|
||||
public enum ProcessPriorityClass
|
||||
{
|
||||
Idle,
|
||||
BelowNormal,
|
||||
Normal,
|
||||
AboveNormal,
|
||||
High,
|
||||
RealTime
|
||||
}
|
||||
```
|
||||
|
||||
This API reference provides comprehensive documentation for all public interfaces and key classes in ThreadPilot.
|
||||
@@ -0,0 +1,199 @@
|
||||
# ThreadPilot Architecture Guide
|
||||
|
||||
## Overview
|
||||
This document describes the modular architecture of ThreadPilot, designed for maintainability, testability, and future extensibility.
|
||||
|
||||
## Architecture Principles
|
||||
|
||||
### 1. Separation of Concerns
|
||||
- **Core Services**: Direct OS interaction (Process, Power Plan, CPU Topology)
|
||||
- **Process Management**: Business logic for process monitoring and management
|
||||
- **Application Services**: UI and application-level functionality
|
||||
- **Presentation Layer**: ViewModels and Views with MVVM pattern
|
||||
|
||||
### 2. Dependency Injection
|
||||
- Centralized service configuration in `ServiceConfiguration.cs`
|
||||
- Service factory pattern for advanced service management
|
||||
- Proper lifecycle management for all services
|
||||
|
||||
### 3. Event-Driven Architecture
|
||||
- Services communicate through well-defined events
|
||||
- Loose coupling between components
|
||||
- Reactive UI updates through observable patterns
|
||||
|
||||
## Project Structure
|
||||
|
||||
```
|
||||
ThreadPilot/
|
||||
├── Services/
|
||||
│ ├── Core/ # Base interfaces and implementations
|
||||
│ │ ├── ISystemService.cs # Base interface for system services
|
||||
│ │ └── BaseSystemService.cs # Base implementation with common functionality
|
||||
│ ├── ProcessManagement/ # Process-related services
|
||||
│ │ └── IProcessManagementService.cs
|
||||
│ ├── ServiceConfiguration.cs # Centralized DI configuration
|
||||
│ └── ServiceFactory.cs # Service factory for advanced management
|
||||
├── Models/
|
||||
│ ├── Core/ # Base model interfaces and implementations
|
||||
│ │ └── IModel.cs # Base model interface and validation
|
||||
│ ├── Process/ # Process-related models
|
||||
│ ├── PowerPlan/ # Power plan models
|
||||
│ └── Configuration/ # Configuration models
|
||||
├── ViewModels/
|
||||
│ ├── BaseViewModel.cs # Enhanced base ViewModel with error handling
|
||||
│ └── ViewModelFactory.cs # Factory for ViewModel creation and management
|
||||
├── Views/ # XAML views and code-behind
|
||||
├── Converters/ # Value converters for data binding
|
||||
├── Helpers/ # Utility classes and extension methods
|
||||
└── Tests/ # Unit and integration tests
|
||||
```
|
||||
|
||||
## Service Layer Architecture
|
||||
|
||||
### Core Services (`Services/Core/`)
|
||||
Base interfaces and implementations for all services:
|
||||
|
||||
- **ISystemService**: Base interface with availability tracking and lifecycle management
|
||||
- **BaseSystemService**: Common functionality for initialization, disposal, and error handling
|
||||
|
||||
### Service Categories
|
||||
|
||||
#### 1. Core System Services
|
||||
Direct interaction with the operating system:
|
||||
- `IProcessService`: Process enumeration and manipulation
|
||||
- `IPowerPlanService`: Windows power plan management
|
||||
- `ICpuTopologyService`: CPU topology detection and affinity management
|
||||
|
||||
#### 2. Process Management Services
|
||||
Business logic for process monitoring:
|
||||
- `IProcessMonitorService`: WMI-based process event monitoring
|
||||
- `IProcessPowerPlanAssociationService`: Process-to-power plan associations
|
||||
- `IProcessMonitorManagerService`: Orchestrates process monitoring
|
||||
- `IGameBoostService`: Game detection and performance optimization
|
||||
|
||||
#### 3. Application Services
|
||||
Application-level functionality:
|
||||
- `IApplicationSettingsService`: Configuration persistence
|
||||
- `INotificationService`: User notifications and system tray
|
||||
- `IAutostartService`: Windows startup integration
|
||||
- `IEnhancedLoggingService`: Structured logging with file persistence
|
||||
|
||||
### Service Factory Pattern
|
||||
The `ServiceFactory` class provides:
|
||||
- Centralized service creation with dependency resolution
|
||||
- Lifecycle management for `ISystemService` implementations
|
||||
- Automatic initialization and disposal of managed services
|
||||
- Error handling and logging for service operations
|
||||
|
||||
## Presentation Layer Architecture
|
||||
|
||||
### Enhanced BaseViewModel
|
||||
The `BaseViewModel` class provides:
|
||||
- **Error Handling**: Centralized error management with logging
|
||||
- **Status Management**: Busy states and status messages
|
||||
- **Async Operations**: Helper methods for async operations with error handling
|
||||
- **Logging Integration**: Automatic user action logging
|
||||
- **Lifecycle Management**: Proper initialization and disposal
|
||||
|
||||
### ViewModel Factory
|
||||
The `ViewModelFactory` class provides:
|
||||
- Dependency injection for ViewModels
|
||||
- Automatic initialization of ViewModels
|
||||
- Lifecycle management and disposal
|
||||
- Error handling during creation and initialization
|
||||
|
||||
## Model Layer Architecture
|
||||
|
||||
### Base Model Interface
|
||||
The `IModel` interface provides:
|
||||
- **Identity**: Unique ID and timestamps
|
||||
- **Validation**: Built-in validation framework
|
||||
- **Change Tracking**: Property change notifications
|
||||
- **Cloning**: Deep copy support
|
||||
|
||||
### Domain-Specific Models
|
||||
Models are organized by domain:
|
||||
- **Process Models**: Process information and metadata
|
||||
- **Power Plan Models**: Power plan configurations
|
||||
- **Configuration Models**: Application settings and associations
|
||||
|
||||
## Configuration and Dependency Injection
|
||||
|
||||
### ServiceConfiguration Class
|
||||
Centralized configuration with methods for each service category:
|
||||
- `ConfigureServiceInfrastructure()`: Logging and factories
|
||||
- `ConfigureCoreSystemServices()`: OS interaction services
|
||||
- `ConfigureProcessManagementServices()`: Business logic services
|
||||
- `ConfigureApplicationLevelServices()`: UI and application services
|
||||
- `ConfigurePresentationLayer()`: ViewModels and Views
|
||||
|
||||
### Service Validation
|
||||
Automatic validation of service configuration at startup:
|
||||
- Ensures all required services can be resolved
|
||||
- Validates service dependencies
|
||||
- Provides clear error messages for configuration issues
|
||||
|
||||
## Error Handling and Logging
|
||||
|
||||
### Structured Logging
|
||||
- **Enhanced Logging Service**: File-based logging with rotation
|
||||
- **Structured Events**: Predefined event types for different operations
|
||||
- **User Action Logging**: Audit trail for user interactions
|
||||
- **Error Correlation**: Consistent error tracking across services
|
||||
|
||||
### Error Handling Patterns
|
||||
- **Service Level**: Try-catch with logging and graceful degradation
|
||||
- **ViewModel Level**: User-friendly error messages with technical logging
|
||||
- **Application Level**: Global exception handling with recovery
|
||||
|
||||
## Testing Strategy
|
||||
|
||||
### Unit Testing
|
||||
- Service interfaces enable easy mocking
|
||||
- BaseViewModel provides testable error handling
|
||||
- Model validation can be tested independently
|
||||
|
||||
### Integration Testing
|
||||
- Service factory enables testing of service interactions
|
||||
- Event-driven architecture allows testing of component communication
|
||||
- Configuration validation ensures proper setup
|
||||
|
||||
## Future Extensibility
|
||||
|
||||
### Adding New Services
|
||||
1. Implement appropriate base interface (`ISystemService` for system services)
|
||||
2. Add to relevant service category in `ServiceConfiguration`
|
||||
3. Follow established patterns for error handling and logging
|
||||
|
||||
### Adding New Features
|
||||
1. Create domain-specific models with validation
|
||||
2. Implement services following the established patterns
|
||||
3. Create ViewModels inheriting from `BaseViewModel`
|
||||
4. Use dependency injection for all dependencies
|
||||
|
||||
### Performance Optimization
|
||||
- Service factory enables lazy loading of services
|
||||
- Event-driven architecture allows for efficient updates
|
||||
- Structured logging provides performance monitoring data
|
||||
|
||||
## Best Practices
|
||||
|
||||
### Service Development
|
||||
- Always implement proper disposal for resources
|
||||
- Use structured logging for all operations
|
||||
- Implement graceful degradation for optional features
|
||||
- Follow async/await patterns consistently
|
||||
|
||||
### ViewModel Development
|
||||
- Inherit from `BaseViewModel` for consistent functionality
|
||||
- Use `ExecuteAsync` methods for error handling
|
||||
- Implement proper disposal for event subscriptions
|
||||
- Log user actions for audit purposes
|
||||
|
||||
### Model Development
|
||||
- Implement validation for all business rules
|
||||
- Use property change notifications for UI binding
|
||||
- Provide meaningful error messages
|
||||
- Support cloning for undo/redo functionality
|
||||
|
||||
This architecture provides a solid foundation for maintainable, testable, and extensible code while following established patterns and best practices.
|
||||
@@ -0,0 +1,24 @@
|
||||
# Changelog
|
||||
|
||||
All notable changes to this project are documented in this file.
|
||||
|
||||
The format is based on Keep a Changelog, and this project follows Semantic Versioning.
|
||||
|
||||
## [1.1.0] - 2026-04-12
|
||||
### Added
|
||||
- Enterprise release hardening baseline for repository governance, CI/CD, and security policy.
|
||||
- Dedicated GitHub contribution and security disclosure templates.
|
||||
- Analyzer and formatting foundation for consistent code quality enforcement.
|
||||
|
||||
### Changed
|
||||
- README updated to align with v1.1.0 messaging and release workflow.
|
||||
- CI workflow expanded with formatting, analyzer, and dependency vulnerability checks.
|
||||
|
||||
### Security
|
||||
- Added centralized vulnerability disclosure policy and reporting process.
|
||||
- Started hardening process/power-plan command validation paths.
|
||||
|
||||
## [1.0.0] - 2025-12-21
|
||||
### Added
|
||||
- Initial public release with process management, CPU affinity, and power plan automation.
|
||||
- MVVM architecture with dependency injection and performance-focused process workflows.
|
||||
@@ -0,0 +1,238 @@
|
||||
# CLAUDE.md
|
||||
|
||||
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
|
||||
|
||||
## Project Overview
|
||||
|
||||
ThreadPilot is a professional Windows process and power plan manager built with WPF and .NET 8.0. It provides advanced process management, intelligent power plan automation, ML-based game detection, and system optimization tools for power users, gamers, and system administrators.
|
||||
|
||||
## Build and Development Commands
|
||||
|
||||
### Building
|
||||
```bash
|
||||
# Build the project
|
||||
dotnet build --configuration Release
|
||||
|
||||
# Build for debugging
|
||||
dotnet build --configuration Debug
|
||||
```
|
||||
|
||||
### Running
|
||||
```bash
|
||||
# Run the application
|
||||
dotnet run --configuration Release
|
||||
|
||||
# Run with command-line arguments
|
||||
dotnet run --configuration Release -- --test # Run tests
|
||||
dotnet run --configuration Release -- --start-minimized # Start minimized
|
||||
dotnet run --configuration Release -- --autostart # Autostart mode
|
||||
```
|
||||
|
||||
### Publishing
|
||||
```bash
|
||||
# Publish as self-contained portable executable
|
||||
dotnet publish --configuration Release --runtime win-x64 --self-contained true
|
||||
```
|
||||
|
||||
### Testing
|
||||
The application includes an integrated test suite:
|
||||
- Press `Ctrl+Shift+T` in the running application to execute Game Boost integration tests
|
||||
- Run `dotnet run --configuration Release -- --test` to run tests in console mode
|
||||
- Tests are located in the `Tests/` directory
|
||||
|
||||
## Architecture Overview
|
||||
|
||||
### MVVM Pattern with Dependency Injection
|
||||
The application follows strict MVVM architecture using CommunityToolkit.Mvvm with centralized DI configuration:
|
||||
|
||||
- **Models/** - Data models using ObservableObject base class
|
||||
- **Views/** - WPF XAML views with code-behind
|
||||
- **ViewModels/** - View models implementing INotifyPropertyChanged via source generators
|
||||
- **Services/** - Business logic and system interaction layer
|
||||
|
||||
### Service Configuration
|
||||
All services are configured in `Services/ServiceConfiguration.cs` using extension methods organized by layer:
|
||||
- `ConfigureServiceInfrastructure()` - Logging, caching, health monitoring, retry policies
|
||||
- `ConfigureCoreSystemServices()` - OS interaction (ProcessService, PowerPlanService, CpuTopologyService)
|
||||
- `ConfigureProcessManagementServices()` - Process monitoring, game detection, boost services
|
||||
- `ConfigureApplicationLevelServices()` - Settings, notifications, system tray, security
|
||||
- `ConfigurePresentationLayer()` - ViewModels and Views
|
||||
|
||||
### Service Lifetime Strategy
|
||||
- **Singletons**: Core services, ViewModels that share state (ProcessViewModel, MasksViewModel)
|
||||
- **Transients**: UI-specific ViewModels and Views (PowerPlanViewModel, SettingsViewModel, MainWindow)
|
||||
|
||||
### CPU Topology and Affinity Management
|
||||
The application has sophisticated CPU topology awareness:
|
||||
- **CpuTopologyService** - Detects P-cores/E-cores (Intel Hybrid), AMD CCD layout, NUMA nodes
|
||||
- **CoreMaskService** - Manages CPU affinity masks for precise core assignment
|
||||
- **ProcessCpuSetHandler** (Platforms/Windows/) - Uses Windows CPU Sets API for modern affinity control on Windows 11+
|
||||
- Fallback to traditional `ProcessorAffinity` for Windows 10 compatibility
|
||||
|
||||
CPU Sets vs ProcessorAffinity:
|
||||
- CPU Sets (Windows 11+): More granular control, respects system scheduling policies
|
||||
- ProcessorAffinity (legacy): Direct affinity mask, used as fallback
|
||||
|
||||
### Power Plan Management
|
||||
- Integrates with Windows Power Plans via `powercfg` command-line tool
|
||||
- Supports custom .pow power plan imports from hardcoded path (see PowerPlanService.cs:15)
|
||||
- Process-based automatic power plan switching via `ProcessPowerPlanAssociationService`
|
||||
- Real-time power plan monitoring with change event notifications
|
||||
|
||||
### Game Detection and Boost
|
||||
- **GameDetectionService** - ML-based game detection with 95% accuracy (heuristics-based)
|
||||
- **GameBoostService** - Automatic performance optimization for detected games
|
||||
- **PerformanceMonitoringService** - Real-time FPS estimation and resource tracking
|
||||
- User override system with persistent manual classification
|
||||
|
||||
### Notification System
|
||||
- **NotificationService** - Basic Windows notifications
|
||||
- **SmartNotificationService** - Intelligent throttling, deduplication, DND mode, priority queuing
|
||||
- Category-based notification preferences
|
||||
- Integrates with system tray for balloon tips
|
||||
|
||||
### Process Monitoring
|
||||
- **ProcessMonitorService** - Low-level WMI-based process event monitoring
|
||||
- **ProcessMonitorManagerService** - Orchestrates monitoring, profile application, power plan switching
|
||||
- **VirtualizedProcessService** - Handles 5000+ processes efficiently with UI virtualization
|
||||
- Background refresh with intelligent throttling to reduce resource usage
|
||||
|
||||
### System Tweaks
|
||||
- Core parking control
|
||||
- C-States management
|
||||
- System service tweaks (SysMain, Prefetch, power throttling)
|
||||
- HPET configuration
|
||||
- High-priority scheduling category management
|
||||
|
||||
### Security and Elevation
|
||||
- **ElevationService** - Manages administrator privilege detection and elevation requests
|
||||
- **SecurityService** - Security-related functionality
|
||||
- Application can run in limited mode without admin privileges
|
||||
- Prompts for elevation when needed for specific features
|
||||
|
||||
## Key Implementation Details
|
||||
|
||||
### Async Initialization Pattern
|
||||
MainWindow uses a sophisticated async initialization pattern with loading overlay:
|
||||
1. Loading overlay displayed during startup
|
||||
2. ViewModels initialized with timeout protection (prevents hanging)
|
||||
3. Services initialized in specific order with fallback strategies
|
||||
4. System tray and monitoring started last
|
||||
5. Graceful degradation if components fail (e.g., basic tray mode if full init times out)
|
||||
|
||||
### Cross-Thread Marshaling
|
||||
UI updates from background threads must be marshaled via `Dispatcher.InvokeAsync()`:
|
||||
```csharp
|
||||
Dispatcher.InvokeAsync(() => {
|
||||
// UI updates here
|
||||
});
|
||||
```
|
||||
|
||||
### Memory Management
|
||||
- `IServiceHealthMonitor` and `IServiceDisposalCoordinator` for lifecycle management
|
||||
- `IRetryPolicyService` for automatic retry with exponential backoff
|
||||
- Memory cache (Microsoft.Extensions.Caching.Memory) for performance optimization
|
||||
- Proper cleanup of timers, event handlers, and WMI watchers
|
||||
|
||||
### Logging
|
||||
- Uses Microsoft.Extensions.Logging with console output
|
||||
- **EnhancedLoggingService** provides correlation IDs and structured logging
|
||||
- Debug logging to temp file during initialization (see MainWindow.xaml.cs:45)
|
||||
|
||||
### Settings Persistence
|
||||
- Settings stored via `ApplicationSettingsService` (JSON-based)
|
||||
- Profiles stored in ApplicationData\ThreadPilot\Profiles as JSON files
|
||||
- Power plans exported as .pow files in hardcoded directory
|
||||
|
||||
### Keyboard Shortcuts
|
||||
- **KeyboardShortcutService** manages global hotkeys via Win32 API
|
||||
- RegisterHotKey/UnregisterHotKey integration
|
||||
- Actions: ShowMainWindow, ToggleMonitoring, GameBoostToggle, OpenTweaks, OpenSettings, etc.
|
||||
- Shortcuts loaded from settings
|
||||
|
||||
### System Tray Integration
|
||||
- **SystemTrayService** with context menu for quick actions
|
||||
- Power plan switching directly from tray
|
||||
- Monitoring status display (CPU/Memory usage)
|
||||
- Game Boost status indicator
|
||||
- Periodic updates every 10 seconds (performance-optimized)
|
||||
|
||||
### Platform-Specific Code
|
||||
- Windows-specific functionality isolated in `Platforms/Windows/`
|
||||
- P/Invoke calls for CPU Sets API (CpuSetNativeMethods.cs)
|
||||
- Requires `AllowUnsafeBlocks` for native interop
|
||||
|
||||
## Common Development Patterns
|
||||
|
||||
### Creating New Services
|
||||
1. Define interface in `Services/I*.cs`
|
||||
2. Implement in `Services/*.cs` with constructor injection
|
||||
3. Register in `ServiceConfiguration.cs` in appropriate layer method
|
||||
4. Inject into ViewModels or other services as needed
|
||||
|
||||
### Adding ViewModels
|
||||
1. Inherit from `BaseViewModel` or `ObservableObject`
|
||||
2. Use `[ObservableProperty]` source generators for properties
|
||||
3. Use `[RelayCommand]` for commands
|
||||
4. Register in `ServiceConfiguration.ConfigurePresentationLayer()`
|
||||
5. Choose Singleton (shared state) or Transient (per-instance) lifetime
|
||||
|
||||
### Working with Processes
|
||||
- Use `IProcessService` for basic process operations
|
||||
- Use `IVirtualizedProcessService` for large process lists in UI
|
||||
- Update ProcessModel properties to trigger UI updates automatically
|
||||
- CPU usage calculation requires two samples (see ProcessService.CalculateCpuUsage)
|
||||
|
||||
### Adding System Tweaks
|
||||
- Implement tweak logic in `SystemTweaksService`
|
||||
- Add corresponding properties/commands to `SystemTweaksViewModel`
|
||||
- Update UI in `Views/SystemTweaksView.xaml`
|
||||
- Most tweaks require administrator privileges
|
||||
|
||||
## Project Structure Notes
|
||||
|
||||
- **Converters/** - WPF value converters (e.g., ItemIndexConverter for list numbering)
|
||||
- **Models/** - Core data models (ProcessModel, PowerPlanModel, ProcessPowerPlanAssociation, CoreMask)
|
||||
- **app.manifest** - Defines UAC elevation requirements and compatibility
|
||||
- **ico.ico** - Application icon used in loading overlay and system tray
|
||||
- **ThreadPilot.csproj** - Configured for single-file publish, self-contained, win-x64 only
|
||||
|
||||
## Important Implementation Notes
|
||||
|
||||
### Startup Sequence
|
||||
1. App.xaml.cs configures DI container via ServiceConfiguration
|
||||
2. Validates core service resolution
|
||||
3. Checks elevation status (shows warning if not admin)
|
||||
4. Parses command-line arguments (--test, --start-minimized, --autostart)
|
||||
5. MainWindow constructor initializes loading overlay
|
||||
6. Async initialization loads ViewModels, Services, starts monitoring
|
||||
7. Loading overlay hidden when complete (with timeout protection)
|
||||
|
||||
### Error Handling Strategy
|
||||
- Global exception handlers in App.xaml.cs (domain + dispatcher)
|
||||
- Timeout protection on async operations (typically 5-8 seconds)
|
||||
- Fallback strategies for failed initializations (e.g., basic system tray)
|
||||
- User-friendly error dialogs with retry options
|
||||
- Detailed logging with correlation IDs
|
||||
|
||||
### Performance Considerations
|
||||
- Process list refresh paused when window minimized
|
||||
- System tray updates throttled to 10-second intervals
|
||||
- Virtualized UI for large datasets (process lists)
|
||||
- CPU usage calculations cached per process
|
||||
- Intelligent notification deduplication and throttling
|
||||
|
||||
### Windows Version Compatibility
|
||||
- Targets .NET 8.0 Windows only (UseWPF + UseWindowsForms)
|
||||
- CPU Sets API used on Windows 11+, falls back to ProcessorAffinity on Windows 10
|
||||
- Requires Windows 10/11 for full functionality
|
||||
- Some features require administrator privileges
|
||||
|
||||
## Gotchas and Known Issues
|
||||
|
||||
- PowerPlanService.cs:15 has hardcoded path `C:\Users\Administrator\Desktop\Project\ThreadPilot_1\Powerplans`
|
||||
- WMI monitoring may fail on some systems (graceful degradation implemented)
|
||||
- Process CPU Sets require Windows 11 - application auto-detects and falls back
|
||||
- System tray context menu updates can timeout if performance metrics take too long (2s timeout)
|
||||
- Loading overlay initialization has 15-second timeout with retry option
|
||||
- Elevation dialogs can be suppressed during autostart to avoid interrupting user
|
||||
@@ -0,0 +1,33 @@
|
||||
# Contributor Covenant Code of Conduct
|
||||
|
||||
## Our Pledge
|
||||
We pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation.
|
||||
|
||||
## Our Standards
|
||||
Examples of behavior that contributes to a positive environment include:
|
||||
- Demonstrating empathy and kindness.
|
||||
- Being respectful of differing opinions and experiences.
|
||||
- Giving and gracefully accepting constructive feedback.
|
||||
- Taking responsibility and apologizing to those affected by our mistakes.
|
||||
- Focusing on what is best for the community.
|
||||
|
||||
Examples of unacceptable behavior include:
|
||||
- The use of sexualized language or imagery, and sexual attention or advances.
|
||||
- Trolling, insulting or derogatory comments, and personal or political attacks.
|
||||
- Public or private harassment.
|
||||
- Publishing others private information without explicit permission.
|
||||
- Other conduct that could reasonably be considered inappropriate in a professional setting.
|
||||
|
||||
## Enforcement Responsibilities
|
||||
Project maintainers are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior they deem inappropriate, threatening, offensive, or harmful.
|
||||
|
||||
## Scope
|
||||
This Code of Conduct applies within all community spaces and applies when an individual is officially representing the project in public spaces.
|
||||
|
||||
## Enforcement
|
||||
Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the maintainers by opening a confidential report through repository security reporting channels listed in SECURITY.md.
|
||||
|
||||
All complaints will be reviewed and investigated promptly and fairly.
|
||||
|
||||
## Attribution
|
||||
This Code of Conduct is adapted from the Contributor Covenant, version 2.1.
|
||||
@@ -0,0 +1,130 @@
|
||||
# Compliance and Quality Audit
|
||||
|
||||
This document captures the current compliance posture of ThreadPilot and the concrete actions required to align with requested standards.
|
||||
|
||||
## Scope
|
||||
|
||||
- Product: ThreadPilot (`net8.0-windows`, WPF desktop app)
|
||||
- Baseline date: 2026-04-11
|
||||
- Audit method: static repository review + architecture inspection
|
||||
|
||||
## Executive Summary
|
||||
|
||||
- The application has solid architecture foundations (MVVM, DI, structured services, logging, error handling) but lacks formal governance artifacts required for enterprise compliance.
|
||||
- Most requested standards are process- and evidence-heavy and require dedicated lifecycle artifacts, traceability, and automated pipeline enforcement.
|
||||
- Immediate technical risk addressed in this pass: UI re-entrancy and collection concurrency faults in fast tab switching scenarios.
|
||||
|
||||
## ISO/Standards Mapping
|
||||
|
||||
### ISO 25010 (Product Quality)
|
||||
|
||||
Current strengths:
|
||||
- Functional suitability: rich process/power-plan management feature set
|
||||
- Usability: themed UI with tray integration and status signaling
|
||||
- Maintainability: modular services + DI configuration (`Services/ServiceConfiguration.cs`)
|
||||
|
||||
Gaps:
|
||||
- No formal quality model matrix with measurable criteria
|
||||
- No non-functional acceptance thresholds documented per release
|
||||
|
||||
Required artifacts:
|
||||
- `docs/quality/iso25010-quality-model.md`
|
||||
- Quality gates (performance, reliability, security, maintainability)
|
||||
|
||||
### ISO 12207 (Software Lifecycle)
|
||||
|
||||
Current strengths:
|
||||
- Defined architecture and service layering in docs and code
|
||||
|
||||
Gaps:
|
||||
- No lifecycle process assets (requirements baseline, verification plan, transition evidence)
|
||||
- No formal traceability from requirement to tests and releases
|
||||
|
||||
Required artifacts:
|
||||
- Lifecycle plan
|
||||
- Requirements traceability matrix
|
||||
- Release readiness checklist
|
||||
|
||||
### OWASP + ISO 27001 (Security)
|
||||
|
||||
Current strengths:
|
||||
- Elevated privilege checks and guarded admin operations
|
||||
- Some defensive error handling and service-level logging
|
||||
|
||||
Gaps:
|
||||
- Missing threat model and secure coding policy document
|
||||
- No automated SAST/dependency/secrets scanning pipeline
|
||||
- No formal control mapping to ISO 27001 Annex A controls
|
||||
|
||||
Required controls:
|
||||
- SAST + dependency + secrets scan in CI
|
||||
- Security issue triage SLA
|
||||
- Signed release and artifact integrity checks
|
||||
|
||||
### CI/CD + DevSecOps
|
||||
|
||||
Current state:
|
||||
- No repository CI workflows detected
|
||||
|
||||
Required:
|
||||
- Build, test, and security workflow on pull requests and main
|
||||
- Release pipeline with immutable artifacts and provenance metadata
|
||||
|
||||
### ISTQB / ISO 29119 (Testing)
|
||||
|
||||
Current strengths:
|
||||
- Integrated runtime tests in `Tests/`
|
||||
|
||||
Gaps:
|
||||
- No standardized test specification set (plan/design/cases/procedure)
|
||||
- Not integrated with `dotnet test` framework and CI coverage reporting
|
||||
|
||||
Required:
|
||||
- Test strategy and test design docs
|
||||
- Structured test execution reports in CI
|
||||
|
||||
### Microsoft + HLK Guidance
|
||||
|
||||
Current strengths:
|
||||
- Windows-targeted app with manifest and platform-specific integration
|
||||
|
||||
Gaps:
|
||||
- No formal HLK-aligned validation checklist or records
|
||||
- No packaging/signing verification evidence in pipeline
|
||||
|
||||
Required:
|
||||
- Windows compatibility checklist
|
||||
- Release validation records for startup, tray, privilege modes, and resiliency
|
||||
|
||||
### Secure Coding (CERT / MISRA)
|
||||
|
||||
Applicability note:
|
||||
- CERT secure coding is applicable to C#/.NET development practices.
|
||||
- MISRA is primarily aimed at C/C++ in safety-critical embedded domains; use only for native interop boundaries if mandated by policy.
|
||||
|
||||
Required:
|
||||
- Secure coding standard tailored for C# + interop
|
||||
- Static analysis ruleset and coding exceptions register
|
||||
|
||||
## Immediate Technical Remediation Applied
|
||||
|
||||
- Added re-entrancy guards for fast tab switching in `MainWindow.xaml.cs`
|
||||
- Hardened collection update patterns in `ViewModels/ProcessViewModel.cs` and `ViewModels/PerformanceViewModel.cs`
|
||||
- Added UI exception dialog throttling in `App.xaml.cs` to prevent dialog storms
|
||||
- Removed problematic gear glyph usage and normalized section labels
|
||||
- Restored denser content spacing while preserving modern visual style in theme dictionaries
|
||||
|
||||
## Recommended Next Implementation Sprint
|
||||
|
||||
1. Add CI workflow: build + smoke tests + static analysis.
|
||||
2. Add security workflow: dependency audit + CodeQL/SAST + secret scanning.
|
||||
3. Introduce test project for `dotnet test` and keep integrated runtime tests for operational checks.
|
||||
4. Publish quality and security governance docs under `docs/` with ownership and review cadence.
|
||||
5. Add release checklist with HLK-aligned Windows validation evidence.
|
||||
|
||||
## Acceptance Criteria For Compliance Baseline
|
||||
|
||||
- CI required on all pull requests and main branch merges.
|
||||
- Security scans block merges on high/critical findings.
|
||||
- Traceability matrix links features -> tests -> release notes.
|
||||
- Documented quality metrics and release thresholds are versioned.
|
||||
@@ -0,0 +1,40 @@
|
||||
# Contributing to ThreadPilot
|
||||
|
||||
Thanks for helping improve ThreadPilot.
|
||||
|
||||
## Before You Start
|
||||
- Search existing issues before opening a new one.
|
||||
- Keep pull requests scoped to a single concern.
|
||||
- For security issues, do not open a public issue. Follow the process in SECURITY.md.
|
||||
|
||||
## Development Setup
|
||||
1. Install .NET 8 SDK.
|
||||
2. Clone the repository.
|
||||
3. Restore and build:
|
||||
- dotnet restore ThreadPilot_1.sln
|
||||
- dotnet build ThreadPilot_1.sln --configuration Release
|
||||
4. Run application:
|
||||
- dotnet run --project ThreadPilot.csproj --configuration Release
|
||||
|
||||
## Branch and Commit Guidelines
|
||||
- Use short-lived feature branches.
|
||||
- Use clear commit messages in imperative mood.
|
||||
- Keep history clean and avoid unrelated formatting churn.
|
||||
|
||||
## Pull Request Checklist
|
||||
- I built the solution successfully in Debug and Release.
|
||||
- I ran tests and validated impacted features.
|
||||
- I updated documentation for any user-facing or architectural changes.
|
||||
- I validated no credentials or secrets were introduced.
|
||||
- I included risk notes for any changes touching elevation, process control, or power plans.
|
||||
|
||||
## Coding Standards
|
||||
- Follow existing MVVM and DI patterns.
|
||||
- Prefer async APIs and avoid blocking calls on UI paths.
|
||||
- Add XML documentation comments for public APIs.
|
||||
- Keep classes cohesive and avoid mixing UI logic with system logic.
|
||||
|
||||
## Testing Expectations
|
||||
- Add unit tests for new logic when feasible.
|
||||
- Add or update integration checks for process and power plan workflows.
|
||||
- Validate behavior on Windows 11; Windows 10 is best effort.
|
||||
@@ -0,0 +1,322 @@
|
||||
# ThreadPilot Developer Guide
|
||||
|
||||
## Quick Start for New Developers
|
||||
|
||||
### Prerequisites
|
||||
- .NET 8.0 SDK
|
||||
- Visual Studio 2022 or VS Code with C# extension
|
||||
- Windows 10/11 (for WMI and power plan features)
|
||||
|
||||
### Building the Project
|
||||
```bash
|
||||
git clone <repository-url>
|
||||
cd ThreadPilot
|
||||
dotnet restore
|
||||
dotnet build
|
||||
```
|
||||
|
||||
### Running the Application
|
||||
```bash
|
||||
dotnet run --project ThreadPilot
|
||||
```
|
||||
|
||||
## Key Architectural Concepts
|
||||
|
||||
### 1. Service-Oriented Architecture
|
||||
ThreadPilot uses a layered service architecture with dependency injection:
|
||||
|
||||
- **Core Services**: Direct OS interaction (Process, Power Plan, CPU)
|
||||
- **Business Services**: Application logic (Process Monitoring, Game Boost)
|
||||
- **Application Services**: UI and configuration (Settings, Notifications)
|
||||
|
||||
### 2. MVVM Pattern with Enhanced BaseViewModel
|
||||
All ViewModels inherit from `BaseViewModel` which provides:
|
||||
- Centralized error handling with logging
|
||||
- Async operation helpers with status management
|
||||
- User action logging for audit trails
|
||||
- Proper disposal and lifecycle management
|
||||
|
||||
### 3. Repository Pattern for Data Access
|
||||
Data persistence uses the repository pattern with:
|
||||
- Generic `IRepository<T>` interface for CRUD operations
|
||||
- JSON file-based implementation with thread-safe operations
|
||||
- Centralized data access through `IDataAccessService`
|
||||
- Model validation and integrity checking
|
||||
|
||||
## Adding New Features
|
||||
|
||||
### 1. Adding a New Service
|
||||
|
||||
**Step 1**: Create the interface in appropriate folder:
|
||||
```csharp
|
||||
// Services/YourDomain/IYourService.cs
|
||||
public interface IYourService : ISystemService
|
||||
{
|
||||
Task<bool> DoSomethingAsync();
|
||||
event EventHandler<YourEventArgs>? SomethingHappened;
|
||||
}
|
||||
```
|
||||
|
||||
**Step 2**: Implement the service:
|
||||
```csharp
|
||||
// Services/YourDomain/YourService.cs
|
||||
public class YourService : BaseSystemService, IYourService
|
||||
{
|
||||
public YourService(ILogger<YourService> logger) : base(logger) { }
|
||||
|
||||
public async Task<bool> DoSomethingAsync()
|
||||
{
|
||||
// Implementation
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Step 3**: Register in `ServiceConfiguration.cs`:
|
||||
```csharp
|
||||
services.AddSingleton<IYourService, YourService>();
|
||||
```
|
||||
|
||||
### 2. Adding a New ViewModel
|
||||
|
||||
**Step 1**: Create ViewModel inheriting from BaseViewModel:
|
||||
```csharp
|
||||
public partial class YourViewModel : BaseViewModel
|
||||
{
|
||||
private readonly IYourService _yourService;
|
||||
|
||||
public YourViewModel(
|
||||
ILogger<YourViewModel> logger,
|
||||
IYourService yourService,
|
||||
IEnhancedLoggingService? enhancedLoggingService = null)
|
||||
: base(logger, enhancedLoggingService)
|
||||
{
|
||||
_yourService = yourService;
|
||||
}
|
||||
|
||||
[RelayCommand]
|
||||
private async Task DoSomethingAsync()
|
||||
{
|
||||
await ExecuteAsync(async () =>
|
||||
{
|
||||
await _yourService.DoSomethingAsync();
|
||||
await LogUserActionAsync("YourAction", "Did something", "User interaction");
|
||||
}, "Doing something...", "Operation completed successfully");
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Step 2**: Register in `ServiceConfiguration.cs`:
|
||||
```csharp
|
||||
services.AddTransient<YourViewModel>();
|
||||
```
|
||||
|
||||
### 3. Adding a New Model
|
||||
|
||||
**Step 1**: Create model implementing IModel:
|
||||
```csharp
|
||||
public partial class YourModel : 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;
|
||||
|
||||
// IModel implementation
|
||||
public string Id => id;
|
||||
public DateTime CreatedAt => createdAt;
|
||||
public DateTime UpdatedAt => updatedAt;
|
||||
|
||||
public ValidationResult Validate()
|
||||
{
|
||||
var errors = new List<string>();
|
||||
if (string.IsNullOrWhiteSpace(Name))
|
||||
errors.Add("Name is required");
|
||||
return errors.Count == 0 ? ValidationResult.Success() : ValidationResult.Failure(errors.ToArray());
|
||||
}
|
||||
|
||||
public IModel Clone()
|
||||
{
|
||||
return new YourModel
|
||||
{
|
||||
id = Guid.NewGuid().ToString(),
|
||||
Name = this.Name,
|
||||
createdAt = DateTime.UtcNow,
|
||||
updatedAt = DateTime.UtcNow
|
||||
};
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Common Patterns and Best Practices
|
||||
|
||||
### Error Handling
|
||||
Always use the BaseViewModel's error handling methods:
|
||||
```csharp
|
||||
// For async operations with user feedback
|
||||
await ExecuteAsync(async () =>
|
||||
{
|
||||
// Your operation
|
||||
}, "Loading...", "Completed successfully");
|
||||
|
||||
// For setting errors manually
|
||||
SetError("Something went wrong", exception);
|
||||
|
||||
// For clearing errors
|
||||
ClearError();
|
||||
```
|
||||
|
||||
### Logging
|
||||
Use structured logging throughout the application:
|
||||
```csharp
|
||||
// In services
|
||||
Logger.LogInformation("Operation completed for {EntityId}", entityId);
|
||||
|
||||
// In ViewModels (for user actions)
|
||||
await LogUserActionAsync("ActionName", "Description", "Context");
|
||||
```
|
||||
|
||||
### Event Handling
|
||||
Follow the established event pattern:
|
||||
```csharp
|
||||
public event EventHandler<YourEventArgs>? YourEvent;
|
||||
|
||||
protected virtual void OnYourEvent(YourEventArgs args)
|
||||
{
|
||||
YourEvent?.Invoke(this, args);
|
||||
}
|
||||
```
|
||||
|
||||
### Async Operations
|
||||
Always use proper async/await patterns:
|
||||
```csharp
|
||||
// Good
|
||||
public async Task<bool> DoSomethingAsync()
|
||||
{
|
||||
await SomeAsyncOperation();
|
||||
return true;
|
||||
}
|
||||
|
||||
// Avoid blocking calls
|
||||
public bool DoSomething()
|
||||
{
|
||||
DoSomethingAsync().Wait(); // DON'T DO THIS
|
||||
return true;
|
||||
}
|
||||
```
|
||||
|
||||
## Testing Guidelines
|
||||
|
||||
### Unit Testing Services
|
||||
```csharp
|
||||
[Test]
|
||||
public async Task YourService_DoSomething_ReturnsExpectedResult()
|
||||
{
|
||||
// Arrange
|
||||
var logger = Mock.Of<ILogger<YourService>>();
|
||||
var service = new YourService(logger);
|
||||
|
||||
// Act
|
||||
var result = await service.DoSomethingAsync();
|
||||
|
||||
// Assert
|
||||
Assert.IsTrue(result);
|
||||
}
|
||||
```
|
||||
|
||||
### Testing ViewModels
|
||||
```csharp
|
||||
[Test]
|
||||
public async Task YourViewModel_DoSomething_UpdatesStatusCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
var logger = Mock.Of<ILogger<YourViewModel>>();
|
||||
var service = Mock.Of<IYourService>();
|
||||
var viewModel = new YourViewModel(logger, service);
|
||||
|
||||
// Act
|
||||
await viewModel.DoSomethingCommand.ExecuteAsync(null);
|
||||
|
||||
// Assert
|
||||
Assert.IsFalse(viewModel.HasError);
|
||||
}
|
||||
```
|
||||
|
||||
## Performance Considerations
|
||||
|
||||
### Memory Management
|
||||
- Always dispose of services that implement IDisposable
|
||||
- Unsubscribe from events in ViewModel disposal
|
||||
- Use weak event patterns for long-lived subscriptions
|
||||
|
||||
### Threading
|
||||
- UI operations must be on the UI thread
|
||||
- Use ConfigureAwait(false) for non-UI async operations
|
||||
- Protect shared resources with appropriate synchronization
|
||||
|
||||
### Data Access
|
||||
- Repository operations are thread-safe
|
||||
- Use batch operations when possible
|
||||
- Implement proper caching for frequently accessed data
|
||||
|
||||
## Troubleshooting Common Issues
|
||||
|
||||
### Service Resolution Errors
|
||||
Check `ServiceConfiguration.cs` to ensure all dependencies are registered with correct lifetimes.
|
||||
|
||||
### ViewModel Constructor Issues
|
||||
Ensure all ViewModels call the base constructor with required logger parameter.
|
||||
|
||||
### Data Persistence Issues
|
||||
Check file permissions and ensure data directory exists. Use logging to trace repository operations.
|
||||
|
||||
### Event Subscription Leaks
|
||||
Always unsubscribe from events in the ViewModel's OnDispose method.
|
||||
|
||||
## Configuration and Settings
|
||||
|
||||
### Application Settings
|
||||
Settings are managed through `IApplicationSettingsService` and persisted automatically:
|
||||
```csharp
|
||||
// Access current settings
|
||||
var settings = _settingsService.Settings;
|
||||
|
||||
// Modify settings
|
||||
settings.EnableNotifications = true;
|
||||
|
||||
// Save changes (automatic on property change)
|
||||
await _settingsService.SaveSettingsAsync();
|
||||
```
|
||||
|
||||
### Logging Configuration
|
||||
Enhanced logging is configured in `ServiceConfiguration.cs`:
|
||||
- Console logging for development
|
||||
- File-based logging with rotation for production
|
||||
- Structured events for different operation types
|
||||
|
||||
### Data Storage Locations
|
||||
- **Settings**: `%AppData%\ThreadPilot\settings.json`
|
||||
- **Associations**: `%AppData%\ThreadPilot\Data\ProcessAssociations.json`
|
||||
- **Profiles**: `%AppData%\ThreadPilot\Data\ProcessProfiles.json`
|
||||
- **Logs**: `%AppData%\ThreadPilot\Logs\`
|
||||
|
||||
## Deployment and Distribution
|
||||
|
||||
### Release Build
|
||||
```bash
|
||||
dotnet publish -c Release -r win-x64 --self-contained true
|
||||
```
|
||||
|
||||
### Installer Considerations
|
||||
- Register for Windows autostart if enabled
|
||||
- Create application data directories
|
||||
- Set appropriate file permissions
|
||||
- Register WMI event handlers
|
||||
|
||||
This guide provides the foundation for extending ThreadPilot while maintaining code quality and architectural consistency.
|
||||
@@ -0,0 +1,12 @@
|
||||
<Project>
|
||||
<PropertyGroup>
|
||||
<EnforceCodeStyleInBuild>true</EnforceCodeStyleInBuild>
|
||||
<EnableNETAnalyzers>true</EnableNETAnalyzers>
|
||||
<AnalysisLevel>latest</AnalysisLevel>
|
||||
<GenerateDocumentationFile>true</GenerateDocumentationFile>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="StyleCop.Analyzers" Version="1.1.118" PrivateAssets="all" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
@@ -0,0 +1,153 @@
|
||||
# Game Boost Integration - Validation and Testing Guide
|
||||
|
||||
## Overview
|
||||
This document provides comprehensive validation and testing instructions for the Game Boost Mode feature that has been successfully integrated into ThreadPilot.
|
||||
|
||||
## Feature Summary
|
||||
|
||||
### ✅ **Completed Implementation**
|
||||
The Game Boost Mode feature is **fully implemented** and includes:
|
||||
|
||||
1. **Automatic Game Detection** - Detects games using advanced heuristics and a comprehensive known games database (150+ games)
|
||||
2. **Process Priority Management** - Automatically sets high priority for detected games
|
||||
3. **Power Plan Switching** - Switches to high-performance power plan when games are active
|
||||
4. **CPU Affinity Optimization** - Optimizes CPU core allocation for better gaming performance
|
||||
5. **System Tray Integration** - Shows Game Boost status in system tray with shield icon
|
||||
6. **Main Window Status Display** - Visual indicators in the main UI showing active Game Boost status
|
||||
7. **User Notifications** - Toast notifications when Game Boost activates/deactivates
|
||||
8. **Manual Game Management** - UI for adding/removing games from the known games list
|
||||
|
||||
### 🔧 **Key Components**
|
||||
|
||||
#### Services
|
||||
- **GameBoostService** - Core game boost functionality
|
||||
- **ProcessMonitorManagerService** - Integrates game detection with process monitoring
|
||||
- **SystemTrayService** - Enhanced with Game Boost status display
|
||||
- **NotificationService** - Provides user feedback
|
||||
|
||||
#### UI Components
|
||||
- **SettingsView** - Game management interface
|
||||
- **MainWindow** - Status display with visual indicators
|
||||
- **System Tray** - Context menu and icon state management
|
||||
|
||||
#### Models
|
||||
- **ApplicationSettingsModel** - Game Boost configuration options
|
||||
- **ProcessModel** - Enhanced for game detection
|
||||
- **Event Args** - GameBoostActivatedEventArgs, GameBoostDeactivatedEventArgs
|
||||
|
||||
## Testing Instructions
|
||||
|
||||
### 🧪 **Automated Testing**
|
||||
The application includes built-in integration tests that can be run using:
|
||||
|
||||
**Keyboard Shortcut: `Ctrl+Shift+T`**
|
||||
|
||||
This will execute comprehensive tests including:
|
||||
1. Service resolution validation
|
||||
2. Game detection logic testing
|
||||
3. Known games management testing
|
||||
4. System tray integration testing
|
||||
|
||||
### 🎮 **Manual Testing Workflow**
|
||||
|
||||
#### 1. **Enable Game Boost Mode**
|
||||
1. Open ThreadPilot
|
||||
2. Go to Settings tab
|
||||
3. Enable "Game Boost Mode"
|
||||
4. Configure desired settings:
|
||||
- Set high priority for games
|
||||
- Optimize CPU affinity
|
||||
- Select Game Boost power plan
|
||||
5. Save settings
|
||||
|
||||
#### 2. **Test Automatic Game Detection**
|
||||
1. Start a known game (e.g., Steam, any game from the known games list)
|
||||
2. Verify Game Boost activates automatically:
|
||||
- System tray icon changes to shield
|
||||
- Context menu shows "Game Boost: Active (GameName)"
|
||||
- Main window status bar shows green "Game Boost: Active" with shield emoji
|
||||
- Notification appears: "Game Boost Activated"
|
||||
|
||||
#### 3. **Test Game Boost Deactivation**
|
||||
1. Close the game
|
||||
2. Verify Game Boost deactivates:
|
||||
- System tray icon returns to normal
|
||||
- Context menu shows "Game Boost: Inactive"
|
||||
- Main window status shows gray "Game Boost: Inactive"
|
||||
- Notification appears: "Game Boost Deactivated"
|
||||
|
||||
#### 4. **Test Manual Game Management**
|
||||
1. Go to Settings → Game Management section
|
||||
2. Add a custom game executable (e.g., "mygame.exe")
|
||||
3. Verify it appears in the known games list
|
||||
4. Test removing games from the list
|
||||
5. Verify changes are persisted after restart
|
||||
|
||||
#### 5. **Test System Integration**
|
||||
1. Verify power plan switching works correctly
|
||||
2. Check process priority is set to High for games
|
||||
3. Confirm CPU affinity optimization (if enabled)
|
||||
4. Test with multiple games running simultaneously
|
||||
|
||||
### 📊 **Expected Behavior**
|
||||
|
||||
#### Game Detection
|
||||
- **Known Games**: 150+ popular games are pre-configured
|
||||
- **Auto-Detection**: Advanced heuristics detect likely game processes
|
||||
- **Manual Addition**: Users can add custom games via UI
|
||||
|
||||
#### Performance Optimization
|
||||
- **Process Priority**: Games get High priority class
|
||||
- **Power Plan**: Switches to high-performance plan
|
||||
- **CPU Affinity**: Optimizes core allocation for better performance
|
||||
- **Restoration**: All settings restored when games close
|
||||
|
||||
#### User Interface
|
||||
- **System Tray**: Shield icon when active, context menu status
|
||||
- **Main Window**: StatusBar with color-coded Game Boost status
|
||||
- **Notifications**: Toast notifications for activation/deactivation
|
||||
- **Settings**: Comprehensive configuration options
|
||||
|
||||
### 🔍 **Validation Checklist**
|
||||
|
||||
#### Core Functionality
|
||||
- [ ] Game Boost activates when known games start
|
||||
- [ ] Game Boost deactivates when games close
|
||||
- [ ] Process priority is set correctly
|
||||
- [ ] Power plan switching works
|
||||
- [ ] CPU affinity optimization functions (if enabled)
|
||||
|
||||
#### User Interface
|
||||
- [ ] System tray shows correct Game Boost status
|
||||
- [ ] Main window StatusBar displays Game Boost state
|
||||
- [ ] Shield icons appear when Game Boost is active
|
||||
- [ ] Context menu shows current game name
|
||||
- [ ] Settings UI allows game management
|
||||
|
||||
#### Integration
|
||||
- [ ] Works with existing process monitoring
|
||||
- [ ] Notifications appear at appropriate times
|
||||
- [ ] Settings are persisted correctly
|
||||
- [ ] Multiple games handled properly
|
||||
- [ ] Error handling works gracefully
|
||||
|
||||
#### Performance
|
||||
- [ ] No significant performance impact when inactive
|
||||
- [ ] Quick activation/deactivation response times
|
||||
- [ ] Stable operation during extended gaming sessions
|
||||
- [ ] Proper cleanup when application closes
|
||||
|
||||
### 🚨 **Known Limitations**
|
||||
1. Requires administrator privileges for process priority changes
|
||||
2. Some games may not be detected automatically (can be added manually)
|
||||
3. Power plan switching requires appropriate Windows permissions
|
||||
4. CPU affinity optimization depends on system configuration
|
||||
|
||||
### 📝 **Troubleshooting**
|
||||
- **Game not detected**: Add manually via Settings → Game Management
|
||||
- **Priority not set**: Ensure application runs with sufficient privileges
|
||||
- **Power plan not switching**: Check Windows power management permissions
|
||||
- **Tests failing**: Check logs for detailed error information
|
||||
|
||||
## Conclusion
|
||||
The Game Boost Mode feature is fully implemented and ready for production use. The comprehensive testing framework ensures reliability, and the user-friendly interface makes it accessible to all users.
|
||||
@@ -0,0 +1,690 @@
|
||||
GNU General Public License v3.0
|
||||
|
||||
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/>.
|
||||
|
||||
GNU GENERAL PUBLIC LICENSE
|
||||
Version 3, 29 June 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The GNU General Public License is a free, copyleft license for
|
||||
software and other kinds of works.
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
the GNU General Public License is intended to guarantee your freedom to
|
||||
share and change all versions of a program--to make sure it remains free
|
||||
software for all its users. We, the Free Software Foundation, use the
|
||||
GNU General Public License for most of our software; it applies also to
|
||||
any other work released this way by its authors. You can apply it to
|
||||
your programs, too.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
them if you wish), that you receive source code or can get it if you
|
||||
want it, that you can change the software or use pieces of it in new
|
||||
free programs, and that you know you can do these things.
|
||||
|
||||
To protect your rights, we need to prevent others from denying you
|
||||
these rights or asking you to surrender the rights. Therefore, you have
|
||||
certain responsibilities if you distribute copies of the software, or if
|
||||
you modify it: responsibilities to respect the freedom of others.
|
||||
|
||||
For example, if you distribute copies of such a program, whether
|
||||
gratis or for a fee, you must pass on to the recipients the same
|
||||
freedoms that you received. You must make sure that they, too, receive
|
||||
or can get the source code. And you must show them these terms so they
|
||||
know their rights.
|
||||
|
||||
Developers that use the GNU GPL protect your rights with two steps:
|
||||
(1) assert copyright on the software, and (2) offer you this License
|
||||
giving you legal permission to copy, distribute and/or modify it.
|
||||
|
||||
For the developers' and authors' protection, the GPL clearly explains
|
||||
that there is no warranty for this free software. For both users' and
|
||||
authors' sake, the GPL requires that modified versions be marked as
|
||||
changed, so that their problems will not be attributed erroneously to
|
||||
authors of previous versions.
|
||||
|
||||
Some devices are designed to deny users access to install or run
|
||||
modified versions of the software inside them, although the manufacturer
|
||||
can do so. This is fundamentally incompatible with the aim of
|
||||
protecting users' freedom to change the software. The systematic
|
||||
pattern of such abuse occurs in the area of products for individuals to
|
||||
use, which is precisely where it is most unacceptable. Therefore, we
|
||||
have designed this version of the GPL to prohibit the practice for those
|
||||
products. If such problems arise substantially in other domains, we
|
||||
stand ready to extend this provision to those domains in future versions
|
||||
of the GPL, as needed to protect the freedom of users.
|
||||
|
||||
Finally, every program is threatened constantly by software patents.
|
||||
States should not allow patents to restrict development and use of
|
||||
software on general-purpose computers, but in those that do, we wish to
|
||||
avoid the special danger that patents applied to a free program could
|
||||
make it effectively proprietary. To prevent this, the GPL assures that
|
||||
patents cannot be used to render the program non-free.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
0. Definitions.
|
||||
|
||||
"This License" refers to version 3 of the GNU General Public License.
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||
works, such as semiconductor masks.
|
||||
|
||||
"The Program" refers to any copyrightable work licensed under this
|
||||
License. Each licensee is addressed as "you". "Licensees" and
|
||||
"recipients" may be individuals or organizations.
|
||||
|
||||
To "modify" a work means to copy from or adapt all or part of the work
|
||||
in a fashion requiring copyright permission, other than the making of an
|
||||
exact copy. The resulting work is called a "modified version" of the
|
||||
earlier work or a work "based on" the earlier work.
|
||||
|
||||
A "covered work" means either the unmodified Program or a work based
|
||||
on the Program.
|
||||
|
||||
To "propagate" a work means to do anything with it that, without
|
||||
permission, would make you directly or secondarily liable for
|
||||
infringement under applicable copyright law, except executing it on a
|
||||
computer or modifying a private copy. Propagation includes copying,
|
||||
distribution (with or without modification), making available to the
|
||||
public, and in some countries other activities as well.
|
||||
|
||||
To "convey" a work means any kind of propagation that enables other
|
||||
parties to make or receive copies. Mere interaction with a user through
|
||||
a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
An interactive user interface displays "Appropriate Legal Notices"
|
||||
to the extent that it includes a convenient and prominently visible
|
||||
feature that (1) displays an appropriate copyright notice, and (2)
|
||||
tells the user that there is no warranty for the work (except to the
|
||||
extent that warranties are provided), that licensees may convey the
|
||||
work under this License, and how to view a copy of this License. If
|
||||
the interface presents a list of user commands or options, such as a
|
||||
menu, a prominent item in the list meets this criterion.
|
||||
|
||||
1. Source Code.
|
||||
|
||||
The "source code" for a work means the preferred form of the work
|
||||
for making modifications to it. "Object code" means any non-source
|
||||
form of a work.
|
||||
|
||||
A "Standard Interface" means an interface that either is an official
|
||||
standard defined by a recognized standards body, or, in the case of
|
||||
interfaces specified for a particular programming language, one that
|
||||
is widely used among developers working in that language.
|
||||
|
||||
The "System Libraries" of an executable work include anything, other
|
||||
than the work as a whole, that (a) is included in the normal form of
|
||||
packaging a Major Component, but which is not part of that Major
|
||||
Component, and (b) serves only to enable use of the work with that
|
||||
Major Component, or to implement a Standard Interface for which an
|
||||
implementation is available to the public in source code form. A
|
||||
"Major Component", in this context, means a major essential component
|
||||
(kernel, window system, and so on) of the specific operating system
|
||||
(if any) on which the executable work runs, or a compiler used to
|
||||
produce the work, or an object code interpreter used to run it.
|
||||
|
||||
The "Corresponding Source" for a work in object code form means all
|
||||
the source code needed to generate, install, and (for an executable
|
||||
work) run the object code and to modify the work, including scripts to
|
||||
control those activities. However, it does not include the work's
|
||||
System Libraries, or general-purpose tools or generally available free
|
||||
programs which are used unmodified in performing those activities but
|
||||
which are not part of the work. For example, Corresponding Source
|
||||
includes interface definition files associated with source files for
|
||||
the work, and the source code for shared libraries and dynamically
|
||||
linked subprograms that the work is specifically designed to require,
|
||||
such as by intimate data communication or control flow between those
|
||||
subprograms and other parts of the work.
|
||||
|
||||
The Corresponding Source need not include anything that users
|
||||
can regenerate automatically from other parts of the Corresponding
|
||||
Source.
|
||||
|
||||
The Corresponding Source for a work in source code form is that
|
||||
same work.
|
||||
|
||||
2. Basic Permissions.
|
||||
|
||||
All rights granted under this License are granted for the term of
|
||||
copyright on the Program, and are irrevocable provided the stated
|
||||
conditions are met. This License explicitly affirms your unlimited
|
||||
permission to run the unmodified Program. The output from running a
|
||||
covered work is covered by this License only if the output, given its
|
||||
content, constitutes a covered work. This License acknowledges your
|
||||
rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
You may make, run and propagate covered works that you do not
|
||||
convey, without conditions so long as your license otherwise remains
|
||||
in force. You may convey covered works to others for the sole purpose
|
||||
of having them make modifications exclusively for you, or provide you
|
||||
with facilities for running those works, provided that you comply with
|
||||
the terms of this License in conveying all material for which you do
|
||||
not control copyright. Those thus making or running the covered works
|
||||
for you must do so exclusively on your behalf, under your direction
|
||||
and control, on terms that prohibit them from making any copies of
|
||||
your copyrighted material outside their relationship with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under
|
||||
the conditions stated below. Sublicensing is not allowed; section 10
|
||||
makes it unnecessary.
|
||||
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
|
||||
No covered work shall be deemed part of an effective technological
|
||||
measure under any applicable law fulfilling obligations under article
|
||||
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||
similar laws prohibiting or restricting circumvention of such
|
||||
measures.
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid
|
||||
circumvention of technological measures to the extent such circumvention
|
||||
is effected by exercising rights under this License with respect to
|
||||
the covered work, and you disclaim any intention to limit operation or
|
||||
modification of the work as a means of enforcing, against the work's
|
||||
users, your or third parties' legal rights to forbid circumvention of
|
||||
technological measures.
|
||||
|
||||
4. Conveying Verbatim Copies.
|
||||
|
||||
You may convey verbatim copies of the Program's source code as you
|
||||
receive it, in any medium, provided that you conspicuously and
|
||||
appropriately publish on each copy an appropriate copyright notice;
|
||||
keep intact all notices stating that this License and any
|
||||
non-permissive terms added in accord with section 7 apply to the code;
|
||||
keep intact all notices of the absence of any warranty; and give all
|
||||
recipients a copy of this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey,
|
||||
and you may offer support or warranty protection for a fee.
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
|
||||
You may convey a work based on the Program, or the modifications to
|
||||
produce it from the Program, in the form of source code under the
|
||||
terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
a) The work must carry prominent notices stating that you modified
|
||||
it, and giving a relevant date.
|
||||
|
||||
b) The work must carry prominent notices stating that it is
|
||||
released under this License and any conditions added under section
|
||||
7. This requirement modifies the requirement in section 4 to
|
||||
"keep intact all notices".
|
||||
|
||||
c) You must license the entire work, as a whole, under this
|
||||
License to anyone who comes into possession of a copy. This
|
||||
License will therefore apply, along with any applicable section 7
|
||||
additional terms, to the whole of the work, and all its parts,
|
||||
regardless of how they are packaged. This License gives no
|
||||
permission to license the work in any other way, but it does not
|
||||
invalidate such permission if you have separately received it.
|
||||
|
||||
d) If the work has interactive user interfaces, each must display
|
||||
Appropriate Legal Notices; however, if the Program has interactive
|
||||
interfaces that do not display Appropriate Legal Notices, your
|
||||
work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent
|
||||
works, which are not by their nature extensions of the covered work,
|
||||
and which are not combined with it such as to form a larger program,
|
||||
in or on a volume of a storage or distribution medium, is called an
|
||||
"aggregate" if the compilation and its resulting copyright are not
|
||||
used to limit the access or legal rights of the compilation's users
|
||||
beyond what the individual works permit. Inclusion of a covered work
|
||||
in an aggregate does not cause this License to apply to the other
|
||||
parts of the aggregate.
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
|
||||
You may convey a covered work in object code form under the terms
|
||||
of sections 4 and 5, provided that you also convey the
|
||||
machine-readable Corresponding Source under the terms of this License,
|
||||
in one of these ways:
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by the
|
||||
Corresponding Source fixed on a durable physical medium
|
||||
customarily used for software interchange.
|
||||
|
||||
b) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by a
|
||||
written offer, valid for at least three years and valid for as
|
||||
long as you offer spare parts or customer support for that product
|
||||
model, to give anyone who possesses the object code either (1) a
|
||||
copy of the Corresponding Source for all the software in the
|
||||
product that is covered by this License, on a durable physical
|
||||
medium customarily used for software interchange, for a price no
|
||||
more than your reasonable cost of physically performing this
|
||||
conveying of source, or (2) access to copy the
|
||||
Corresponding Source from a network server at no charge.
|
||||
|
||||
c) Convey individual copies of the object code with a copy of the
|
||||
written offer to provide the Corresponding Source. This
|
||||
alternative is allowed only occasionally and noncommercially, and
|
||||
only if you received the object code with such an offer, in accord
|
||||
with subsection 6b.
|
||||
|
||||
d) Convey the object code by offering access from a designated
|
||||
place (gratis or for a charge), and offer equivalent access to the
|
||||
Corresponding Source in the same way through the same place at no
|
||||
further charge. You need not require recipients to copy the
|
||||
Corresponding Source along with the object code. If the place to
|
||||
copy the object code is a network server, the Corresponding Source
|
||||
may be on a different server (operated by you or a third party)
|
||||
that supports equivalent copying facilities, provided you maintain
|
||||
clear directions next to the object code saying where to find the
|
||||
Corresponding Source. Regardless of what server hosts the
|
||||
Corresponding Source, you remain obligated to ensure that it is
|
||||
available for as long as needed to satisfy these requirements.
|
||||
|
||||
e) Convey the object code using peer-to-peer transmission, provided
|
||||
you inform other peers where the object code and Corresponding
|
||||
Source of the work are being offered to the general public at no
|
||||
charge under subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded
|
||||
from the Corresponding Source as a System Library, need not be
|
||||
included in conveying the object code work.
|
||||
|
||||
A "User Product" is either (1) a "consumer product", which means any
|
||||
tangible personal property which is normally used for personal, family,
|
||||
or household purposes, or (2) anything designed or sold for incorporation
|
||||
into a dwelling. In determining whether a product is a consumer product,
|
||||
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||
product received by a particular user, "normally used" refers to a
|
||||
typical or common use of that class of product, regardless of the status
|
||||
of the particular user or of the way in which the particular user
|
||||
actually uses, or expects or is expected to use, the product. A product
|
||||
is a consumer product regardless of whether the product has substantial
|
||||
commercial, industrial or non-consumer uses, unless such uses represent
|
||||
the only significant mode of use of the product.
|
||||
|
||||
"Installation Information" for a User Product means any methods,
|
||||
procedures, authorization keys, or other information required to install
|
||||
and execute modified versions of a covered work in that User Product from
|
||||
a modified version of its Corresponding Source. The information must
|
||||
suffice to ensure that the continued functioning of the modified object
|
||||
code is in no case prevented or interfered with solely because
|
||||
modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or
|
||||
specifically for use in, a User Product, and the conveying occurs as
|
||||
part of a transaction in which the right of possession and use of the
|
||||
User Product is transferred to the recipient in perpetuity or for a
|
||||
fixed term (regardless of how the transaction is characterized), the
|
||||
Corresponding Source conveyed under this section must be accompanied
|
||||
by the Installation Information. But this requirement does not apply
|
||||
if neither you nor any third party retains the ability to install
|
||||
modified object code on the User Product (for example, the work has
|
||||
been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a
|
||||
requirement to continue to provide support service, warranty, or updates
|
||||
for a work that has been modified or installed by the recipient, or for
|
||||
the User Product in which it has been modified or installed. Access to a
|
||||
network may be denied when the modification itself materially and
|
||||
adversely affects the operation of the network or violates the rules and
|
||||
protocols for communication across the network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided,
|
||||
in accord with this section must be in a format that is publicly
|
||||
documented (and with an implementation available to the public in
|
||||
source code form), and must require no special password or key for
|
||||
unpacking, reading or copying.
|
||||
|
||||
7. Additional Terms.
|
||||
|
||||
"Additional permissions" are terms that supplement the terms of this
|
||||
License by making exceptions from one or more of its conditions.
|
||||
Additional permissions that are applicable to the entire Program shall
|
||||
be treated as though they were included in this License, to the extent
|
||||
that they are valid under applicable law. If additional permissions
|
||||
apply only to part of the Program, that part may be used separately
|
||||
under those permissions, but the entire Program remains governed by
|
||||
this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option
|
||||
remove any additional permissions from that copy, or from any part of
|
||||
it. (Additional permissions may be written to require their own
|
||||
removal in certain cases when you modify the work.) You may place
|
||||
additional permissions on material, added by you to a covered work,
|
||||
for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you
|
||||
add to a covered work, you may (if authorized by the copyright holders of
|
||||
that material) supplement the terms of this License with terms:
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the
|
||||
terms of sections 15 and 16 of this License; or
|
||||
|
||||
b) Requiring preservation of specified reasonable legal notices or
|
||||
author attributions in that material or in the Appropriate Legal
|
||||
Notices displayed by works containing it; or
|
||||
|
||||
c) Prohibiting misrepresentation of the origin of that material, or
|
||||
requiring that modified versions of such material be marked in
|
||||
reasonable ways as different from the original version; or
|
||||
|
||||
d) Limiting the use for publicity purposes of names of licensors or
|
||||
authors of the material; or
|
||||
|
||||
e) Declining to grant rights under trademark law for use of some
|
||||
trade names, trademarks, or service marks; or
|
||||
|
||||
f) Requiring indemnification of licensors and authors of that
|
||||
material by anyone who conveys the material (or modified versions of
|
||||
it) with contractual assumptions of liability to the recipient, for
|
||||
any liability that these contractual assumptions directly impose on
|
||||
those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered "further
|
||||
restrictions" within the meaning of section 10. If the Program as you
|
||||
received it, or any part of it, contains a notice stating that it is
|
||||
governed by this License along with a term that is a further
|
||||
restriction, you may remove that term. If a license document contains
|
||||
a further restriction but permits relicensing or conveying under this
|
||||
License, you may add to a covered work material governed by the terms
|
||||
of that license document, provided that the further restriction does
|
||||
not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you
|
||||
must place, in the relevant source files, a statement of the
|
||||
additional terms that apply to those files, or a notice indicating
|
||||
where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the
|
||||
form of a separately written license, or stated as exceptions;
|
||||
the above requirements apply either way.
|
||||
|
||||
8. Termination.
|
||||
|
||||
You may not propagate or modify a covered work except as expressly
|
||||
provided under this License. Any attempt otherwise to propagate or
|
||||
modify it is void, and will automatically terminate your rights under
|
||||
this License (including any patent licenses granted under the third
|
||||
paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your
|
||||
license from a particular copyright holder is reinstated (a)
|
||||
provisionally, unless and until the copyright holder explicitly and
|
||||
finally terminates your license, and (b) permanently, if the copyright
|
||||
holder fails to notify you of the violation by some reasonable means
|
||||
prior to 60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is
|
||||
reinstated permanently if the copyright holder notifies you of the
|
||||
violation by some reasonable means, this is the first time you have
|
||||
received notice of violation of this License (for any work) from that
|
||||
copyright holder, and you cure the violation prior to 30 days after
|
||||
your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the
|
||||
licenses of parties who have received copies or rights from you under
|
||||
this License. If your rights have been terminated and not permanently
|
||||
reinstated, you do not qualify to receive new licenses for the same
|
||||
material under section 10.
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
|
||||
You are not required to accept this License in order to receive or
|
||||
run a copy of the Program. Ancillary propagation of a covered work
|
||||
occurring solely as a consequence of using peer-to-peer transmission
|
||||
to receive a copy likewise does not require acceptance. However,
|
||||
nothing other than this License grants you permission to propagate or
|
||||
modify any covered work. These actions infringe copyright if you do
|
||||
not accept this License. Therefore, by modifying or propagating a
|
||||
covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
|
||||
Each time you convey a covered work, the recipient automatically
|
||||
receives a license from the original licensors, to run, modify and
|
||||
propagate that work, subject to this License. You are not responsible
|
||||
for enforcing compliance by third parties with this License.
|
||||
|
||||
An "entity transaction" is a transaction transferring control of an
|
||||
organization, or substantially all assets of one, or subdividing an
|
||||
organization, or merging organizations. If propagation of a covered
|
||||
work results from an entity transaction, each party to that
|
||||
transaction who receives a copy of the work also receives whatever
|
||||
licenses to the work the party's predecessor in interest had or could
|
||||
give under the previous paragraph, plus a right to possession of the
|
||||
Corresponding Source of the work from the predecessor in interest, if
|
||||
the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the
|
||||
rights granted or affirmed under this License. For example, you may
|
||||
not impose a license fee, royalty, or other charge for exercise of
|
||||
rights granted under this License, and you may not initiate litigation
|
||||
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||
any patent claim is infringed by making, using, selling, offering for
|
||||
sale, or importing the Program or any portion of it.
|
||||
|
||||
11. Patents.
|
||||
|
||||
A "contributor" is a copyright holder who authorizes use under this
|
||||
License of the Program or a work on which the Program is based. The
|
||||
work thus licensed is called the contributor's "contributor version".
|
||||
|
||||
A contributor's "essential patent claims" are all patent claims
|
||||
owned or controlled by the contributor, whether already acquired or
|
||||
hereafter acquired, that would be infringed by some manner, permitted
|
||||
by this License, of making, using, or selling its contributor version,
|
||||
but do not include claims that would be infringed only as a
|
||||
consequence of further modification of the contributor version. For
|
||||
purposes of this definition, "control" includes the right to grant
|
||||
patent sublicenses in a manner consistent with the requirements of
|
||||
this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||
patent license under the contributor's essential patent claims, to
|
||||
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||
propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a "patent license" is any express
|
||||
agreement or commitment, however denominated, not to enforce a patent
|
||||
(such as an express permission to practice a patent or covenant not to
|
||||
sue for patent infringement). To "grant" such a patent license to a
|
||||
party means to make such an agreement or commitment not to enforce a
|
||||
patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license,
|
||||
and the Corresponding Source of the work is not available for anyone
|
||||
to copy, free of charge and under the terms of this License, through a
|
||||
publicly available network server or other readily accessible means,
|
||||
then you must either (1) cause the Corresponding Source to be so
|
||||
available, or (2) arrange to deprive yourself of the benefit of the
|
||||
patent license for this particular work, or (3) arrange, in a manner
|
||||
consistent with the requirements of this License, to extend the patent
|
||||
license to downstream recipients. "Knowingly relying" means you have
|
||||
actual knowledge that, but for the patent license, your conveying the
|
||||
covered work in a country, or your recipient's use of the covered work
|
||||
in a country, would infringe one or more identifiable patents in that
|
||||
country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or
|
||||
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||
covered work, and grant a patent license to some of the parties
|
||||
receiving the covered work authorizing them to use, propagate, modify
|
||||
or convey a specific copy of the covered work, then the patent license
|
||||
you grant is automatically extended to all recipients of the covered
|
||||
work and works based on it.
|
||||
|
||||
A patent license is "discriminatory" if it does not include within
|
||||
the scope of its coverage, prohibits the exercise of, or is
|
||||
conditioned on the non-exercise of one or more of the rights that are
|
||||
specifically granted under this License. You may not convey a covered
|
||||
work if you are a party to an arrangement with a third party that is
|
||||
in the business of distributing software, under which you make payment
|
||||
to the third party based on the extent of your activity of conveying
|
||||
the work, and under which the third party grants, to any of the
|
||||
parties who would receive the covered work from you, a discriminatory
|
||||
patent license (a) in connection with copies of the covered work
|
||||
conveyed by you (or copies made from those copies), or (b) primarily
|
||||
for and in connection with specific products or compilations that
|
||||
contain the covered work, unless you entered into that arrangement,
|
||||
or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting
|
||||
any implied license or other defenses to infringement that may
|
||||
otherwise be available to you under applicable patent law.
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
|
||||
If conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot convey a
|
||||
covered work so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you may
|
||||
not convey it at all. For example, if you agree to terms that obligate you
|
||||
to collect a royalty for further conveying from those to whom you convey
|
||||
the Program, the only way you could satisfy both those terms and this
|
||||
License would be to refrain entirely from conveying the Program.
|
||||
|
||||
13. Use with the GNU Affero General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, you have
|
||||
permission to link or combine any covered work with a work licensed
|
||||
under version 3 of the GNU Affero General Public License into a single
|
||||
combined work, and to convey the resulting work. The terms of this
|
||||
License will continue to apply to the part which is the covered work,
|
||||
but the special requirements of the GNU Affero General Public License,
|
||||
section 13, concerning interaction through a network will apply to the
|
||||
combination as such.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU General Public License from time to time. Such new versions will
|
||||
be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Program specifies that a certain numbered version of the GNU General
|
||||
Public License "or any later version" applies to it, you have the
|
||||
option of following the terms and conditions either of that numbered
|
||||
version or of any later version published by the Free Software
|
||||
Foundation. If the Program does not specify a version number of the
|
||||
GNU General Public License, you may choose any version ever published
|
||||
by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future
|
||||
versions of the GNU General Public License can be used, that proxy's
|
||||
public statement of acceptance of a version permanently authorizes you
|
||||
to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different
|
||||
permissions. However, no additional obligations are imposed on any
|
||||
author or copyright holder as a result of your choosing to follow a
|
||||
later version.
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. Limitation of Liability.
|
||||
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||
SUCH DAMAGES.
|
||||
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
|
||||
If the disclaimer of warranty and limitation of liability provided
|
||||
above cannot be given local legal effect according to their terms,
|
||||
reviewing courts shall apply local law that most closely approximates
|
||||
an absolute waiver of all civil liability in connection with the
|
||||
Program, unless a warranty or assumption of liability accompanies a
|
||||
copy of the Program in return for a fee.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
state the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
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, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
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/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If the program does terminal interaction, make it output a short
|
||||
notice like this when it starts in an interactive mode:
|
||||
|
||||
<program> Copyright (C) <year> <name of author>
|
||||
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
||||
This is free software, and you are welcome to redistribute it
|
||||
under certain conditions; type `show c' for details.
|
||||
|
||||
The hypothetical commands `show w' and `show c' should show the appropriate
|
||||
parts of the General Public License. Of course, your program's commands
|
||||
might be different; for a GUI interface, you would use an "about box".
|
||||
|
||||
You should also get your employer (if you work as a programmer) or school,
|
||||
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||
For more information on this, and how to apply and follow the GNU GPL, see
|
||||
<https://www.gnu.org/licenses/>.
|
||||
|
||||
The GNU General Public License does not permit incorporating your program
|
||||
into proprietary programs. If your program is a subroutine library, you
|
||||
may consider it more useful to permit linking proprietary applications with
|
||||
the library. If this is what you want to do, use the GNU Lesser General
|
||||
Public License instead of this License. But first, please read
|
||||
<https://www.gnu.org/licenses/why-not-lgpl.html>.
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
MIT License
|
||||
GNU General Public License v3.0
|
||||
|
||||
Copyright (C) 2025 Prime Build
|
||||
|
||||
|
||||
@@ -0,0 +1,188 @@
|
||||
# ThreadPilot Project Structure
|
||||
|
||||
## Overview
|
||||
This document describes the organized project structure of ThreadPilot, designed for maintainability, scalability, and clear separation of concerns.
|
||||
|
||||
## Root Directory Structure
|
||||
|
||||
```
|
||||
ThreadPilot/
|
||||
├── Services/ # Service layer with business logic
|
||||
│ ├── Core/ # Base interfaces and implementations
|
||||
│ ├── ProcessManagement/ # Process monitoring and management
|
||||
│ ├── ServiceConfiguration.cs # Centralized DI configuration
|
||||
│ └── ServiceFactory.cs # Service factory pattern
|
||||
├── ViewModels/ # MVVM ViewModels
|
||||
│ ├── BaseViewModel.cs # Enhanced base ViewModel
|
||||
│ └── ViewModelFactory.cs # ViewModel factory
|
||||
├── Views/ # XAML views and code-behind
|
||||
├── Models/ # Data models and domain objects
|
||||
│ └── Core/ # Base model interfaces
|
||||
├── Data/ # Data access layer
|
||||
│ ├── IRepository.cs # Repository interfaces
|
||||
│ ├── JsonRepository.cs # JSON file implementation
|
||||
│ └── DataAccessService.cs # Centralized data access
|
||||
├── Converters/ # Value converters for data binding
|
||||
├── Helpers/ # Utility classes and extensions
|
||||
├── Tests/ # Unit and integration tests
|
||||
├── Documentation/ # Project documentation
|
||||
│ ├── ARCHITECTURE_GUIDE.md # Architecture overview
|
||||
│ ├── DEVELOPER_GUIDE.md # Development guidelines
|
||||
│ ├── API_REFERENCE.md # API documentation
|
||||
│ └── PROJECT_STRUCTURE.md # This file
|
||||
└── Configuration Files
|
||||
├── App.xaml # Application configuration
|
||||
├── App.xaml.cs # Application startup
|
||||
└── ThreadPilot.csproj # Project file
|
||||
```
|
||||
|
||||
## Service Layer Organization
|
||||
|
||||
### Core Services (`Services/Core/`)
|
||||
**Purpose**: Base interfaces and common functionality for all services.
|
||||
|
||||
- `ISystemService.cs` - Base interface with lifecycle management
|
||||
- `BaseSystemService.cs` - Common service implementation
|
||||
- `ServiceAvailabilityChangedEventArgs.cs` - Service availability events
|
||||
|
||||
### Process Management (`Services/ProcessManagement/`)
|
||||
**Purpose**: Process monitoring, detection, and management services.
|
||||
|
||||
- `IProcessManagementService.cs` - Unified process management interface
|
||||
- `IProcessMonitorService.cs` - WMI-based process monitoring
|
||||
- `IProcessMonitorManagerService.cs` - Process monitoring orchestration
|
||||
- `IGameBoostService.cs` - Game detection and optimization
|
||||
|
||||
### Service Infrastructure
|
||||
- `ServiceConfiguration.cs` - Centralized dependency injection configuration
|
||||
- `ServiceFactory.cs` - Advanced service creation and lifecycle management
|
||||
|
||||
## Data Layer Organization
|
||||
|
||||
### Repository Pattern (`Data/`)
|
||||
**Purpose**: Abstracted data access with consistent patterns.
|
||||
|
||||
- `IRepository.cs` - Generic repository interfaces
|
||||
- `JsonRepository.cs` - JSON file-based implementation
|
||||
- `IDataAccessService.cs` - Centralized data coordination
|
||||
- `DataAccessService.cs` - Implementation with validation and backup
|
||||
|
||||
### Model Organization (`Models/`)
|
||||
**Purpose**: Domain models with validation and change tracking.
|
||||
|
||||
- `Core/IModel.cs` - Base model interface with validation
|
||||
- Domain-specific models implementing IModel interface
|
||||
- Observable properties for UI binding
|
||||
- Built-in validation and cloning support
|
||||
|
||||
## Presentation Layer Organization
|
||||
|
||||
### ViewModels (`ViewModels/`)
|
||||
**Purpose**: MVVM ViewModels with consistent patterns.
|
||||
|
||||
- `BaseViewModel.cs` - Enhanced base with error handling and logging
|
||||
- `ViewModelFactory.cs` - Centralized ViewModel creation and management
|
||||
- Domain-specific ViewModels inheriting from BaseViewModel
|
||||
- Proper dependency injection and lifecycle management
|
||||
|
||||
### Views (`Views/`)
|
||||
**Purpose**: XAML views with code-behind.
|
||||
|
||||
- Organized by functional area
|
||||
- Consistent naming conventions
|
||||
- Proper data binding to ViewModels
|
||||
|
||||
## Utility and Support
|
||||
|
||||
### Converters (`Converters/`)
|
||||
**Purpose**: Value converters for data binding.
|
||||
|
||||
- Type conversion for UI binding
|
||||
- Formatting and display logic
|
||||
- Reusable across multiple views
|
||||
|
||||
### Helpers (`Helpers/`)
|
||||
**Purpose**: Utility classes and extension methods.
|
||||
|
||||
- Common functionality
|
||||
- Extension methods
|
||||
- Static utility classes
|
||||
|
||||
## Configuration and Startup
|
||||
|
||||
### Application Configuration
|
||||
- `App.xaml` - Application-level resources and configuration
|
||||
- `App.xaml.cs` - Dependency injection setup and application lifecycle
|
||||
- `ServiceConfiguration.cs` - Centralized service registration
|
||||
|
||||
### Project Configuration
|
||||
- `ThreadPilot.csproj` - Project dependencies and build configuration
|
||||
- Package references for modern .NET development
|
||||
- Target framework and platform specifications
|
||||
|
||||
## Naming Conventions
|
||||
|
||||
### Namespaces
|
||||
- `ThreadPilot` - Root namespace
|
||||
- `ThreadPilot.Services` - Service layer
|
||||
- `ThreadPilot.Services.Core` - Core service infrastructure
|
||||
- `ThreadPilot.Services.ProcessManagement` - Process-related services
|
||||
- `ThreadPilot.ViewModels` - Presentation layer ViewModels
|
||||
- `ThreadPilot.Models` - Data models
|
||||
- `ThreadPilot.Models.Core` - Base model infrastructure
|
||||
- `ThreadPilot.Data` - Data access layer
|
||||
|
||||
### File Naming
|
||||
- Interfaces: `I{Name}.cs` (e.g., `IProcessService.cs`)
|
||||
- Implementations: `{Name}.cs` (e.g., `ProcessService.cs`)
|
||||
- ViewModels: `{Name}ViewModel.cs` (e.g., `ProcessViewModel.cs`)
|
||||
- Models: `{Name}Model.cs` (e.g., `ProcessModel.cs`)
|
||||
- Event Args: `{Name}EventArgs.cs` (e.g., `ProcessEventArgs.cs`)
|
||||
|
||||
### Class Organization
|
||||
- Public interfaces first
|
||||
- Public classes
|
||||
- Internal classes
|
||||
- Private nested classes
|
||||
|
||||
## Dependency Flow
|
||||
|
||||
### Service Dependencies
|
||||
```
|
||||
Application Services → Business Services → Core Services → OS APIs
|
||||
```
|
||||
|
||||
### Presentation Dependencies
|
||||
```
|
||||
Views → ViewModels → Services → Models → Data Layer
|
||||
```
|
||||
|
||||
### Data Flow
|
||||
```
|
||||
UI Events → ViewModels → Services → Repository → File System
|
||||
```
|
||||
|
||||
## Best Practices Enforced
|
||||
|
||||
### Service Layer
|
||||
- Interface-based design for testability
|
||||
- Dependency injection for loose coupling
|
||||
- Async/await patterns throughout
|
||||
- Comprehensive error handling and logging
|
||||
- Event-driven communication between services
|
||||
|
||||
### Presentation Layer
|
||||
- MVVM pattern with proper separation
|
||||
- Command pattern for user interactions
|
||||
- Observable properties for data binding
|
||||
- Centralized error handling in BaseViewModel
|
||||
- Proper disposal and lifecycle management
|
||||
|
||||
### Data Layer
|
||||
- Repository pattern for data abstraction
|
||||
- Model validation and integrity checking
|
||||
- Thread-safe operations
|
||||
- Backup and restore capabilities
|
||||
- Consistent error handling
|
||||
|
||||
This structure provides a solid foundation for maintainable, testable, and extensible code while following established architectural patterns and best practices.
|
||||
@@ -1,90 +1,108 @@
|
||||
# ThreadPilot ✈️ <sup><kbd>v1.0.0</kbd></sup>
|
||||
# ThreadPilot v1.1.0
|
||||
|
||||
[]()
|
||||
[](https://www.microsoft.com/windows)
|
||||
[](https://dotnet.microsoft.com/)
|
||||
[](https://docs.microsoft.com/en-us/dotnet/desktop/wpf/)
|
||||
[](.github/workflows/ci-devsecops.yml)
|
||||
[](https://www.microsoft.com/windows)
|
||||
[](https://dotnet.microsoft.com/)
|
||||
[](LICENSE)
|
||||
[](../../releases)
|
||||
[](https://docs.microsoft.com/en-us/windows/win32/)
|
||||
|
||||
**ThreadPilot** is a Windows application for advanced **process management**, **CPU affinity control**, and **power plan automation**.
|
||||
Built with WPF and .NET 8, it is focused on deterministic performance workflows for power users, gamers, and system admins who want precise control over system resources.
|
||||
ThreadPilot is a free and open-source Windows process and power plan manager focused on deterministic performance workflows.
|
||||
|
||||
[](https://postimg.cc/cr0hkLd9)
|
||||
The project targets users who need Process Lasso style capabilities in a modern WPF desktop application with enterprise-grade reliability, security hardening, and automation support.
|
||||
|
||||
## ✨ Features & Highlights
|
||||
## Key Features
|
||||
|
||||
- **Advanced Process Management:** Real-time monitoring with CPU affinity and priority controls.
|
||||
- **Enterprise-Grade Rules & Automation:** Rule-based automation for process-triggered power plan behavior, featuring graceful failure handling for Anti-Cheat protected games (Vanguard, EAC, BattlEye).
|
||||
- **Performance Intelligence Dashboard:** Interactive dashboard with process hotspots, rule impact analysis, and timeline events.
|
||||
- **Global vs. Per-Process Control:** Explicit visual separation of global power plan management from per-process actions.
|
||||
- **System Tweaks:** Advanced Windows performance settings panel.
|
||||
- **Dynamic Theming:** Light/Dark theming with seamless runtime switching.
|
||||
- **Profile-based Configuration:** Persistent settings, customizable notification levels, and low-overhead minimized tray mode.
|
||||
- Process management with live refresh, filtering, and high-volume process handling.
|
||||
- CPU affinity and priority controls with topology-aware logic.
|
||||
- I/O and scheduling related tuning utilities.
|
||||
- Rule-driven power plan switching based on process start/stop events.
|
||||
- Conditional profiles, system tray controls, and runtime monitoring.
|
||||
- Windows 11 first-class support; Windows 10 support is best effort.
|
||||
|
||||
<img width="1474" height="920" alt="Screenshot 2025-12-21 044753" src="https://github.com/user-attachments/assets/77fc944e-d2a1-4cc7-9915-e01b0776106c" />
|
||||
## Screenshots
|
||||
|
||||
## ⚙️ Requirements
|
||||
<img width="1474" height="920" alt="ThreadPilot main view" src="https://github.com/user-attachments/assets/77fc944e-d2a1-4cc7-9915-e01b0776106c" />
|
||||
|
||||
- **OS:** Windows 10 / 11 (x64)
|
||||
- **Privileges:** Administrator privileges required for full WMI functionality and process control.
|
||||
- **SDK:** .NET 8.0 SDK (only required for building from source).
|
||||
## Requirements
|
||||
|
||||
---
|
||||
- Windows 11 (official support), Windows 10 22H2+ (best effort).
|
||||
- .NET 8 SDK for source builds.
|
||||
- Administrator privileges for advanced process and power operations.
|
||||
|
||||
## 📦 Installation
|
||||
## Installation
|
||||
|
||||
### Portable / Setup (Recommended)
|
||||
1. Download the latest `ThreadPilot_v1.0.0` release from [GitHub Releases](../../releases)
|
||||
2. Extract the archive
|
||||
3. Run `ThreadPilot.exe` **as Administrator**
|
||||
### Prebuilt Release
|
||||
1. Download the latest package from Releases.
|
||||
2. Extract the archive.
|
||||
3. Start ThreadPilot as Administrator for full functionality.
|
||||
|
||||
### Build from source
|
||||
```bash
|
||||
git clone [https://github.com/PrimeBuild-pc/ThreadPilot.git](https://github.com/PrimeBuild-pc/ThreadPilot.git)
|
||||
### Build from Source
|
||||
|
||||
```powershell
|
||||
git clone https://github.com/PrimeBuild-pc/ThreadPilot.git
|
||||
cd ThreadPilot
|
||||
dotnet build "ThreadPilot_1.sln" --configuration Release
|
||||
dotnet run --project "ThreadPilot.csproj" --configuration Release
|
||||
````
|
||||
|
||||
*Useful startup arguments: `--start-minimized`, `--autostart`, `--test`*
|
||||
|
||||
-----
|
||||
|
||||
## 🧪 Test Mode
|
||||
|
||||
Console test mode runs via the app entrypoint and uses the integrated `TestRunner.cs`.
|
||||
*(Note: `dotnet test` will only execute tests in dedicated test projects; this repository currently uses an integrated runtime test runner).*
|
||||
|
||||
```bash
|
||||
dotnet run --project "ThreadPilot.csproj" --configuration Release -- --test
|
||||
dotnet restore ThreadPilot_1.sln
|
||||
dotnet build ThreadPilot_1.sln --configuration Release
|
||||
dotnet run --project ThreadPilot.csproj --configuration Release
|
||||
```
|
||||
|
||||
*Note: In environments where elevation is required to start the app process, test mode requires an elevated terminal.*
|
||||
Useful startup arguments:
|
||||
|
||||
-----
|
||||
- --start-minimized
|
||||
- --autostart
|
||||
- --test
|
||||
|
||||
## 🛠️ Architecture & Tech Stack
|
||||
## Usage Examples
|
||||
|
||||
* **.NET 8.0** & **WPF**
|
||||
* **MVVM** pattern using `CommunityToolkit.Mvvm`
|
||||
* **Dependency Injection** (`Services/ServiceConfiguration.cs`)
|
||||
* **Rules & Automation Engine** (`Services/ProcessPowerPlanAssociationService.cs` & `ViewModels/ProcessPowerPlanAssociationViewModel.cs`)
|
||||
* **Performance Dashboard** (`Views/PerformanceView.xaml` & `ViewModels/PerformanceViewModel.cs`)
|
||||
Run integrated runtime tests:
|
||||
|
||||
-----
|
||||
```powershell
|
||||
dotnet run --project ThreadPilot.csproj --configuration Release -- --test
|
||||
```
|
||||
|
||||
## 📄 License
|
||||
Publish a self-contained build:
|
||||
|
||||
This project is licensed under the **GNU General Public License v3.0**.
|
||||
See [LICENSE](https://www.google.com/search?q=LICENSE) for details.
|
||||
```powershell
|
||||
dotnet publish ThreadPilot.csproj --configuration Release --runtime win-x64 --self-contained true
|
||||
```
|
||||
|
||||
-----
|
||||
Build release artifacts via script:
|
||||
|
||||
## 📞 Support
|
||||
```powershell
|
||||
./build-release.ps1
|
||||
```
|
||||
|
||||
**Made for Windows power users☕** [](https://paypal.me/PrimeBuildOfficial?country.x=IT&locale.x=it_IT)
|
||||
## Quality and Security
|
||||
|
||||
* **Issues**: [https://github.com/PrimeBuild-pc/ThreadPilot/issues](https://github.com/PrimeBuild-pc/ThreadPilot/issues)
|
||||
* **Discussions**: [https://github.com/PrimeBuild-pc/ThreadPilot/discussions](https://github.com/PrimeBuild-pc/ThreadPilot/discussions)
|
||||
- CI validates build, formatting, analyzers, vulnerability checks, and secret scanning.
|
||||
- Security disclosures are handled through private GitHub advisories. See SECURITY.md.
|
||||
- Change history is tracked in CHANGELOG.md.
|
||||
|
||||
## Repository Docs
|
||||
|
||||
- docs/README.md
|
||||
- docs/RELEASE_SIGNING.md
|
||||
- ARCHITECTURE_GUIDE.md
|
||||
- API_REFERENCE.md
|
||||
- DEVELOPER_GUIDE.md
|
||||
- PROJECT_STRUCTURE.md
|
||||
- UI_STYLE_GUIDE.md
|
||||
|
||||
## Contributing
|
||||
|
||||
See CONTRIBUTING.md and CODE_OF_CONDUCT.md before opening pull requests.
|
||||
|
||||
## Roadmap
|
||||
|
||||
- Expand dedicated unit and integration coverage for core services.
|
||||
- Continue async reliability refactoring for long-running monitoring paths.
|
||||
- Improve accessibility and localization readiness in all major views.
|
||||
- Formalize release signing and distribution hardening.
|
||||
|
||||
## License
|
||||
|
||||
Licensed under GNU General Public License v3.0. See LICENSE.
|
||||
|
||||
## Support
|
||||
|
||||
- Issues: https://github.com/PrimeBuild-pc/ThreadPilot/issues
|
||||
- Discussions: https://github.com/PrimeBuild-pc/ThreadPilot/discussions
|
||||
+35
@@ -0,0 +1,35 @@
|
||||
# Security Policy
|
||||
|
||||
## Supported Versions
|
||||
| Version | Supported |
|
||||
| --- | --- |
|
||||
| 1.1.x | Yes |
|
||||
| 1.0.x | Best effort |
|
||||
| < 1.0 | No |
|
||||
|
||||
## Reporting a Vulnerability
|
||||
If you discover a security issue, do not disclose it publicly before a fix is available.
|
||||
|
||||
1. Open a private security advisory in GitHub Security tab.
|
||||
2. Include reproduction steps, impact assessment, and affected versions.
|
||||
3. If possible, include logs, stack traces, and a minimal proof of concept.
|
||||
|
||||
## Response Targets
|
||||
- Initial acknowledgment: within 72 hours.
|
||||
- Triage decision: within 7 days.
|
||||
- Fix timeline: based on severity and exploitability.
|
||||
|
||||
## Scope Notes
|
||||
ThreadPilot includes privileged operations for process and power management.
|
||||
Please prioritize reports involving:
|
||||
- elevation and privilege boundaries,
|
||||
- process manipulation safety,
|
||||
- command execution and input validation,
|
||||
- configuration parsing and path handling.
|
||||
|
||||
## Disclosure Process
|
||||
We follow coordinated disclosure:
|
||||
- confirm report,
|
||||
- reproduce and triage,
|
||||
- fix and validate,
|
||||
- publish release notes and mitigation guidance.
|
||||
@@ -18,6 +18,8 @@ using System;
|
||||
using System.Diagnostics;
|
||||
using System.Linq;
|
||||
using System.Security.Principal;
|
||||
using System.Text;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using System.Windows;
|
||||
using Microsoft.Extensions.Logging;
|
||||
@@ -31,6 +33,7 @@ namespace ThreadPilot.Services
|
||||
{
|
||||
private readonly ILogger<ElevationService> _logger;
|
||||
private readonly ISecurityService _securityService;
|
||||
private readonly SemaphoreSlim _elevationRequestSemaphore = new(1, 1);
|
||||
|
||||
public ElevationService(ILogger<ElevationService> logger, ISecurityService securityService)
|
||||
{
|
||||
@@ -85,6 +88,7 @@ namespace ThreadPilot.Services
|
||||
|
||||
public async Task<bool> RestartWithElevation(string[]? arguments = null)
|
||||
{
|
||||
await _elevationRequestSemaphore.WaitAsync();
|
||||
try
|
||||
{
|
||||
var currentProcess = Process.GetCurrentProcess();
|
||||
@@ -99,7 +103,7 @@ namespace ThreadPilot.Services
|
||||
// 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(arg => $"\"{arg}\""));
|
||||
var argumentString = string.Join(" ", allArgs.Select(EscapeCommandLineArgument));
|
||||
|
||||
var startInfo = new ProcessStartInfo
|
||||
{
|
||||
@@ -145,6 +149,10 @@ namespace ThreadPilot.Services
|
||||
|
||||
return false;
|
||||
}
|
||||
finally
|
||||
{
|
||||
_elevationRequestSemaphore.Release();
|
||||
}
|
||||
}
|
||||
|
||||
public bool ValidateElevationForOperation(string operation)
|
||||
@@ -166,6 +174,32 @@ namespace ThreadPilot.Services
|
||||
? "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();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+245
-183
@@ -15,6 +15,7 @@
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.ObjectModel;
|
||||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
@@ -30,6 +31,8 @@ namespace ThreadPilot.Services
|
||||
{
|
||||
private static readonly Lazy<string> _powerPlansPath = new(GetPowerPlansPath);
|
||||
private static readonly string _powerCfgExecutablePath = Path.Combine(Environment.SystemDirectory, "powercfg.exe");
|
||||
private static readonly Regex _powerSchemeRegex = new(@"Power Scheme GUID: (.*?) \((.*?)\)", RegexOptions.Multiline | RegexOptions.Compiled);
|
||||
private static readonly Regex _pathTraversalRegex = new(@"(^|[\\/])\.\.([\\/]|$)", RegexOptions.Compiled);
|
||||
private static string PowerPlansPath => _powerPlansPath.Value;
|
||||
|
||||
private readonly object _lockObject = new();
|
||||
@@ -97,70 +100,54 @@ namespace ThreadPilot.Services
|
||||
|
||||
public async Task<ObservableCollection<PowerPlanModel>> GetPowerPlansAsync()
|
||||
{
|
||||
return await Task.Run(async () =>
|
||||
{
|
||||
var powerPlans = new ObservableCollection<PowerPlanModel>();
|
||||
var activePlan = await GetActivePowerPlan();
|
||||
var powerPlans = new ObservableCollection<PowerPlanModel>();
|
||||
var activePlan = await GetActivePowerPlan();
|
||||
|
||||
var process = new Process
|
||||
using var process = CreatePowerCfgProcess("/list");
|
||||
process.Start();
|
||||
string output = await process.StandardOutput.ReadToEndAsync();
|
||||
await process.WaitForExitAsync();
|
||||
|
||||
var matches = _powerSchemeRegex.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
|
||||
{
|
||||
StartInfo = new ProcessStartInfo
|
||||
{
|
||||
FileName = _powerCfgExecutablePath,
|
||||
Arguments = "/list",
|
||||
UseShellExecute = false,
|
||||
RedirectStandardOutput = true,
|
||||
CreateNoWindow = true
|
||||
}
|
||||
Guid = guid,
|
||||
Name = name,
|
||||
IsActive = guid == activePlan?.Guid,
|
||||
IsCustomPlan = false
|
||||
};
|
||||
|
||||
process.Start();
|
||||
string output = await process.StandardOutput.ReadToEndAsync();
|
||||
await process.WaitForExitAsync();
|
||||
powerPlans.Add(plan);
|
||||
}
|
||||
|
||||
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;
|
||||
});
|
||||
return powerPlans;
|
||||
}
|
||||
|
||||
public async Task<ObservableCollection<PowerPlanModel>> GetCustomPowerPlansAsync()
|
||||
{
|
||||
return await Task.Run(() =>
|
||||
var customPlans = new ObservableCollection<PowerPlanModel>();
|
||||
if (!Directory.Exists(PowerPlansPath))
|
||||
{
|
||||
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;
|
||||
});
|
||||
}
|
||||
|
||||
foreach (var file in Directory.GetFiles(PowerPlansPath, "*.pow"))
|
||||
{
|
||||
customPlans.Add(new PowerPlanModel
|
||||
{
|
||||
Name = Path.GetFileNameWithoutExtension(file),
|
||||
FilePath = file,
|
||||
IsCustomPlan = true
|
||||
});
|
||||
}
|
||||
|
||||
return await Task.FromResult(customPlans);
|
||||
}
|
||||
|
||||
public async Task<bool> SetActivePowerPlan(PowerPlanModel powerPlan)
|
||||
@@ -170,168 +157,159 @@ namespace ThreadPilot.Services
|
||||
|
||||
public async Task<bool> SetActivePowerPlanByGuidAsync(string powerPlanGuid, bool preventDuplicateChanges = true)
|
||||
{
|
||||
return await Task.Run(async () =>
|
||||
if (!Guid.TryParse(powerPlanGuid, out _))
|
||||
{
|
||||
try
|
||||
_logger.LogWarning("Rejected invalid power plan GUID: {PowerPlanGuid}", powerPlanGuid);
|
||||
return false;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
// Check if change is needed when duplicate prevention is enabled
|
||||
if (preventDuplicateChanges)
|
||||
{
|
||||
// Check if change is needed when duplicate prevention is enabled
|
||||
if (preventDuplicateChanges)
|
||||
var isChangeNeeded = await IsPowerPlanChangeNeededAsync(powerPlanGuid);
|
||||
if (!isChangeNeeded)
|
||||
{
|
||||
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
|
||||
}
|
||||
_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");
|
||||
|
||||
using var process = CreatePowerCfgProcess($"/setactive {powerPlanGuid}");
|
||||
process.Start();
|
||||
var stdError = await process.StandardError.ReadToEndAsync();
|
||||
await process.WaitForExitAsync();
|
||||
|
||||
var success = process.ExitCode == 0;
|
||||
|
||||
if (success)
|
||||
{
|
||||
lock (_lockObject)
|
||||
{
|
||||
_lastActivePowerPlanGuid = powerPlanGuid;
|
||||
}
|
||||
|
||||
var previousPowerPlan = await GetActivePowerPlan();
|
||||
var targetPowerPlan = await GetPowerPlanByGuidAsync(powerPlanGuid);
|
||||
var newPowerPlan = await GetPowerPlanByGuidAsync(powerPlanGuid);
|
||||
|
||||
_logger.LogInformation("Attempting to change power plan from '{FromPlan}' to '{ToPlan}'",
|
||||
previousPowerPlan?.Name ?? "Unknown", targetPowerPlan?.Name ?? "Unknown");
|
||||
_logger.LogInformation("Power plan successfully changed to '{PowerPlan}'", newPowerPlan?.Name ?? "Unknown");
|
||||
|
||||
await _enhancedLogger.LogPowerPlanChangeAsync(
|
||||
previousPowerPlan?.Name ?? "Unknown",
|
||||
targetPowerPlan?.Name ?? "Unknown",
|
||||
"Manual power plan change requested");
|
||||
newPowerPlan?.Name ?? "Unknown",
|
||||
"Manual power plan change completed");
|
||||
|
||||
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;
|
||||
PowerPlanChanged?.Invoke(this, new PowerPlanChangedEventArgs(
|
||||
previousPowerPlan, newPowerPlan, "Manual power plan change"));
|
||||
}
|
||||
catch (Exception ex)
|
||||
else
|
||||
{
|
||||
_logger.LogError(ex, "Exception occurred while changing power plan to '{PowerPlanGuid}'", powerPlanGuid);
|
||||
_logger.LogWarning(
|
||||
"Failed to change power plan to '{PowerPlanGuid}' - powercfg exit code: {ExitCode}, stderr: {StdErr}",
|
||||
powerPlanGuid,
|
||||
process.ExitCode,
|
||||
stdError);
|
||||
|
||||
await _enhancedLogger.LogErrorAsync(ex, "PowerPlanService.SetActivePowerPlanByGuidAsync",
|
||||
new Dictionary<string, object>
|
||||
{
|
||||
["PowerPlanGuid"] = powerPlanGuid,
|
||||
["PreventDuplicateChanges"] = preventDuplicateChanges
|
||||
});
|
||||
|
||||
return false;
|
||||
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
|
||||
{
|
||||
try
|
||||
using var process = CreatePowerCfgProcess("/getactivescheme");
|
||||
process.Start();
|
||||
string output = await process.StandardOutput.ReadToEndAsync();
|
||||
await process.WaitForExitAsync();
|
||||
|
||||
var match = _powerSchemeRegex.Match(output);
|
||||
|
||||
if (match.Success)
|
||||
{
|
||||
var process = new Process
|
||||
return new PowerPlanModel
|
||||
{
|
||||
StartInfo = new ProcessStartInfo
|
||||
{
|
||||
FileName = _powerCfgExecutablePath,
|
||||
Arguments = "/getactivescheme",
|
||||
UseShellExecute = false,
|
||||
RedirectStandardOutput = true,
|
||||
CreateNoWindow = true
|
||||
}
|
||||
Guid = match.Groups[1].Value.Trim(),
|
||||
Name = match.Groups[2].Value.Trim(),
|
||||
IsActive = 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;
|
||||
}
|
||||
});
|
||||
|
||||
_logger.LogWarning("Could not parse active power plan from powercfg output.");
|
||||
return null;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Failed to read active power plan.");
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<bool> ImportCustomPowerPlan(string filePath)
|
||||
{
|
||||
return await Task.Run(() =>
|
||||
if (!TryNormalizePowerPlanPath(filePath, out var normalizedPath, out var validationError))
|
||||
{
|
||||
try
|
||||
{
|
||||
var process = new Process
|
||||
{
|
||||
StartInfo = new ProcessStartInfo
|
||||
{
|
||||
FileName = _powerCfgExecutablePath,
|
||||
Arguments = $"/import \"{filePath}\"",
|
||||
UseShellExecute = false,
|
||||
RedirectStandardOutput = true,
|
||||
CreateNoWindow = true
|
||||
}
|
||||
};
|
||||
_logger.LogWarning("Rejected power plan import path '{FilePath}': {ValidationError}", filePath, validationError);
|
||||
return false;
|
||||
}
|
||||
|
||||
process.Start();
|
||||
process.WaitForExit();
|
||||
try
|
||||
{
|
||||
using var process = CreatePowerCfgProcess($"/import {QuoteArgument(normalizedPath)}");
|
||||
process.Start();
|
||||
var stdError = await process.StandardError.ReadToEndAsync();
|
||||
await process.WaitForExitAsync();
|
||||
|
||||
return process.ExitCode == 0;
|
||||
}
|
||||
catch (Exception)
|
||||
if (process.ExitCode != 0)
|
||||
{
|
||||
_logger.LogWarning(
|
||||
"Power plan import failed for '{Path}' with exit code {ExitCode}. stderr: {StdErr}",
|
||||
normalizedPath,
|
||||
process.ExitCode,
|
||||
stdError);
|
||||
|
||||
return false;
|
||||
}
|
||||
});
|
||||
|
||||
_logger.LogInformation("Imported custom power plan from '{Path}'", normalizedPath);
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception occurred while importing custom power plan from '{Path}'", normalizedPath);
|
||||
await _enhancedLogger.LogErrorAsync(ex, "PowerPlanService.ImportCustomPowerPlan",
|
||||
new Dictionary<string, object> { ["Path"] = normalizedPath });
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<string?> GetActivePowerPlanGuidAsync()
|
||||
@@ -342,12 +320,22 @@ namespace ThreadPilot.Services
|
||||
|
||||
public async Task<bool> PowerPlanExistsAsync(string powerPlanGuid)
|
||||
{
|
||||
if (!Guid.TryParse(powerPlanGuid, out _))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var powerPlans = await GetPowerPlansAsync();
|
||||
return powerPlans.Any(p => string.Equals(p.Guid, powerPlanGuid, StringComparison.OrdinalIgnoreCase));
|
||||
}
|
||||
|
||||
public async Task<PowerPlanModel?> GetPowerPlanByGuidAsync(string powerPlanGuid)
|
||||
{
|
||||
if (!Guid.TryParse(powerPlanGuid, out _))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var powerPlans = await GetPowerPlansAsync();
|
||||
return powerPlans.FirstOrDefault(p => string.Equals(p.Guid, powerPlanGuid, StringComparison.OrdinalIgnoreCase));
|
||||
}
|
||||
@@ -375,10 +363,84 @@ namespace ThreadPilot.Services
|
||||
|
||||
return true; // Change is needed
|
||||
}
|
||||
catch
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogWarning(ex, "Could not determine if power plan change is needed for '{PowerPlanGuid}'", targetPowerPlanGuid);
|
||||
return true; // If we can't determine, assume change is needed
|
||||
}
|
||||
}
|
||||
|
||||
private static string QuoteArgument(string value) => $"\"{value.Replace("\"", "\\\"")}\"";
|
||||
|
||||
private bool TryNormalizePowerPlanPath(string filePath, out string normalizedPath, out string error)
|
||||
{
|
||||
normalizedPath = string.Empty;
|
||||
|
||||
if (string.IsNullOrWhiteSpace(filePath))
|
||||
{
|
||||
error = "Path is empty.";
|
||||
return false;
|
||||
}
|
||||
|
||||
if (_pathTraversalRegex.IsMatch(filePath))
|
||||
{
|
||||
error = "Path traversal segments are not allowed.";
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!Path.IsPathFullyQualified(filePath))
|
||||
{
|
||||
error = "Path must be absolute.";
|
||||
return false;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
normalizedPath = Path.GetFullPath(filePath);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
error = $"Invalid file path: {ex.Message}";
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!string.Equals(Path.GetExtension(normalizedPath), ".pow", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
error = "Only .pow files are supported.";
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!File.Exists(normalizedPath))
|
||||
{
|
||||
error = "File does not exist.";
|
||||
return false;
|
||||
}
|
||||
|
||||
var fileInfo = new FileInfo(normalizedPath);
|
||||
if (fileInfo.Length > 10 * 1024 * 1024)
|
||||
{
|
||||
error = "Power plan file size exceeds 10 MB limit.";
|
||||
return false;
|
||||
}
|
||||
|
||||
error = string.Empty;
|
||||
return true;
|
||||
}
|
||||
|
||||
private static Process CreatePowerCfgProcess(string arguments)
|
||||
{
|
||||
return new Process
|
||||
{
|
||||
StartInfo = new ProcessStartInfo
|
||||
{
|
||||
FileName = _powerCfgExecutablePath,
|
||||
Arguments = arguments,
|
||||
UseShellExecute = false,
|
||||
RedirectStandardOutput = true,
|
||||
RedirectStandardError = true,
|
||||
CreateNoWindow = true
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
# Trademark Policy
|
||||
|
||||
The name "ThreadPilot", the logo, and all branding elements associated with this project
|
||||
are NOT licensed under the GNU General Public License v3.0.
|
||||
|
||||
## Usage Restrictions
|
||||
|
||||
1. **Project Name**: The name "ThreadPilot" may not be used to endorse or promote
|
||||
derivative works without explicit written permission from Prime Build.
|
||||
|
||||
2. **Logo and Branding**: The ThreadPilot logo and visual branding elements may not
|
||||
be used in derivative works or forks without explicit written permission.
|
||||
|
||||
3. **Permitted Uses**:
|
||||
- Attribution in documentation (e.g., "Based on ThreadPilot")
|
||||
- Factual references to the original project
|
||||
- Use in news articles, reviews, and educational content
|
||||
|
||||
4. **Forks and Derivatives**: If you fork or create derivative works, you must:
|
||||
- Choose a different name for your project
|
||||
- Create your own branding and logo
|
||||
- Clearly indicate that your project is a fork/derivative
|
||||
|
||||
## Contact
|
||||
|
||||
For trademark inquiries or permission requests, please contact the project maintainers
|
||||
through the official GitHub repository.
|
||||
|
||||
---
|
||||
|
||||
Copyright (C) 2025 Prime Build. All rights reserved.
|
||||
@@ -0,0 +1,74 @@
|
||||
/*
|
||||
* ThreadPilot - Core security unit tests.
|
||||
*/
|
||||
namespace ThreadPilot.Core.Tests
|
||||
{
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
using Moq;
|
||||
using ThreadPilot.Services;
|
||||
|
||||
/// <summary>
|
||||
/// Unit tests for security-focused validation behavior in <see cref="PowerPlanService"/>.
|
||||
/// </summary>
|
||||
public sealed class PowerPlanServiceSecurityTests
|
||||
{
|
||||
/// <summary>
|
||||
/// Ensures relative import paths are rejected.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task ImportCustomPowerPlan_ReturnsFalse_ForRelativePath()
|
||||
{
|
||||
var service = CreateService();
|
||||
|
||||
var result = await service.ImportCustomPowerPlan("..\\evil.pow");
|
||||
|
||||
Assert.False(result);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Ensures non-.pow files are rejected.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task ImportCustomPowerPlan_ReturnsFalse_ForInvalidExtension()
|
||||
{
|
||||
var service = CreateService();
|
||||
var filePath = Path.Combine(Path.GetTempPath(), "threadpilot-test.txt");
|
||||
await File.WriteAllTextAsync(filePath, "content");
|
||||
|
||||
try
|
||||
{
|
||||
var result = await service.ImportCustomPowerPlan(filePath);
|
||||
Assert.False(result);
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (File.Exists(filePath))
|
||||
{
|
||||
File.Delete(filePath);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Ensures invalid GUID values are rejected before invoking powercfg.
|
||||
/// </summary>
|
||||
[Theory]
|
||||
[InlineData("")]
|
||||
[InlineData("invalid-guid")]
|
||||
[InlineData("1234")]
|
||||
public async Task SetActivePowerPlanByGuidAsync_ReturnsFalse_ForInvalidGuid(string guid)
|
||||
{
|
||||
var service = CreateService();
|
||||
|
||||
var result = await service.SetActivePowerPlanByGuidAsync(guid);
|
||||
|
||||
Assert.False(result);
|
||||
}
|
||||
|
||||
private static PowerPlanService CreateService()
|
||||
{
|
||||
var enhancedLogger = new Mock<IEnhancedLoggingService>(MockBehavior.Loose);
|
||||
return new PowerPlanService(NullLogger<PowerPlanService>.Instance, enhancedLogger.Object);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net8.0-windows10.0.22000.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
<IsPackable>false</IsPackable>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="coverlet.collector" Version="6.0.4" />
|
||||
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="9.0.0" />
|
||||
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.14.1" />
|
||||
<PackageReference Include="Moq" Version="4.20.72" />
|
||||
<PackageReference Include="xunit" Version="2.9.3" />
|
||||
<PackageReference Include="xunit.runner.visualstudio" Version="3.1.4" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\ThreadPilot.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Using Include="Xunit" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -55,9 +55,12 @@
|
||||
<!-- Exclude upstream CPUSetSetter reference files from this project build -->
|
||||
<ItemGroup>
|
||||
<Compile Remove="CPUSetSetter-main\**\*.cs" />
|
||||
<Compile Remove="Tests\ThreadPilot.Core.Tests\**\*.cs" />
|
||||
<Page Remove="CPUSetSetter-main\**\*.xaml" />
|
||||
<Resource Remove="CPUSetSetter-main\**\*.*" />
|
||||
<None Remove="CPUSetSetter-main\**\*.*" />
|
||||
<EmbeddedResource Remove="Tests\ThreadPilot.Core.Tests\**\*.*" />
|
||||
<None Remove="Tests\ThreadPilot.Core.Tests\**\*.*" />
|
||||
<!-- Remove Activity Logs screen -->
|
||||
<Compile Remove="ViewModels\LogViewerViewModel.cs" />
|
||||
<Compile Remove="Views\LogViewerView.xaml.cs" />
|
||||
|
||||
@@ -1,23 +1,55 @@
|
||||
|
||||
Microsoft Visual Studio Solution File, Format Version 12.00
|
||||
# Visual Studio Version 17
|
||||
VisualStudioVersion = 17.5.2.0
|
||||
MinimumVisualStudioVersion = 10.0.40219.1
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ThreadPilot", "ThreadPilot.csproj", "{7D717FFA-22B9-8F31-841D-F60409F9FC7D}"
|
||||
EndProject
|
||||
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "tests", "tests", "{0AB3BF05-4346-4AA6-1389-037BE0695223}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ThreadPilot.Core.Tests", "tests\ThreadPilot.Core.Tests\ThreadPilot.Core.Tests.csproj", "{77089555-3BCF-4CED-A423-5BD426EDFC97}"
|
||||
EndProject
|
||||
Global
|
||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||
Debug|Any CPU = Debug|Any CPU
|
||||
Debug|x64 = Debug|x64
|
||||
Debug|x86 = Debug|x86
|
||||
Release|Any CPU = Release|Any CPU
|
||||
Release|x64 = Release|x64
|
||||
Release|x86 = Release|x86
|
||||
EndGlobalSection
|
||||
GlobalSection(ProjectConfigurationPlatforms) = postSolution
|
||||
{7D717FFA-22B9-8F31-841D-F60409F9FC7D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{7D717FFA-22B9-8F31-841D-F60409F9FC7D}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{7D717FFA-22B9-8F31-841D-F60409F9FC7D}.Debug|x64.ActiveCfg = Debug|Any CPU
|
||||
{7D717FFA-22B9-8F31-841D-F60409F9FC7D}.Debug|x64.Build.0 = Debug|Any CPU
|
||||
{7D717FFA-22B9-8F31-841D-F60409F9FC7D}.Debug|x86.ActiveCfg = Debug|Any CPU
|
||||
{7D717FFA-22B9-8F31-841D-F60409F9FC7D}.Debug|x86.Build.0 = Debug|Any CPU
|
||||
{7D717FFA-22B9-8F31-841D-F60409F9FC7D}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{7D717FFA-22B9-8F31-841D-F60409F9FC7D}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{7D717FFA-22B9-8F31-841D-F60409F9FC7D}.Release|x64.ActiveCfg = Release|Any CPU
|
||||
{7D717FFA-22B9-8F31-841D-F60409F9FC7D}.Release|x64.Build.0 = Release|Any CPU
|
||||
{7D717FFA-22B9-8F31-841D-F60409F9FC7D}.Release|x86.ActiveCfg = Release|Any CPU
|
||||
{7D717FFA-22B9-8F31-841D-F60409F9FC7D}.Release|x86.Build.0 = Release|Any CPU
|
||||
{77089555-3BCF-4CED-A423-5BD426EDFC97}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{77089555-3BCF-4CED-A423-5BD426EDFC97}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{77089555-3BCF-4CED-A423-5BD426EDFC97}.Debug|x64.ActiveCfg = Debug|Any CPU
|
||||
{77089555-3BCF-4CED-A423-5BD426EDFC97}.Debug|x64.Build.0 = Debug|Any CPU
|
||||
{77089555-3BCF-4CED-A423-5BD426EDFC97}.Debug|x86.ActiveCfg = Debug|Any CPU
|
||||
{77089555-3BCF-4CED-A423-5BD426EDFC97}.Debug|x86.Build.0 = Debug|Any CPU
|
||||
{77089555-3BCF-4CED-A423-5BD426EDFC97}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{77089555-3BCF-4CED-A423-5BD426EDFC97}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{77089555-3BCF-4CED-A423-5BD426EDFC97}.Release|x64.ActiveCfg = Release|Any CPU
|
||||
{77089555-3BCF-4CED-A423-5BD426EDFC97}.Release|x64.Build.0 = Release|Any CPU
|
||||
{77089555-3BCF-4CED-A423-5BD426EDFC97}.Release|x86.ActiveCfg = Release|Any CPU
|
||||
{77089555-3BCF-4CED-A423-5BD426EDFC97}.Release|x86.Build.0 = Release|Any CPU
|
||||
EndGlobalSection
|
||||
GlobalSection(SolutionProperties) = preSolution
|
||||
HideSolutionNode = FALSE
|
||||
EndGlobalSection
|
||||
GlobalSection(NestedProjects) = preSolution
|
||||
{77089555-3BCF-4CED-A423-5BD426EDFC97} = {0AB3BF05-4346-4AA6-1389-037BE0695223}
|
||||
EndGlobalSection
|
||||
GlobalSection(ExtensibilityGlobals) = postSolution
|
||||
SolutionGuid = {41195CDE-B973-425F-9B16-D0BF741D1950}
|
||||
EndGlobalSection
|
||||
|
||||
@@ -0,0 +1,201 @@
|
||||
# ThreadPilot UI Style Guide
|
||||
|
||||
## Overview
|
||||
This document defines the UI standards, terminology, and style guidelines for the ThreadPilot application to ensure consistency across all components and future development.
|
||||
|
||||
## Application Structure
|
||||
|
||||
### Main Window Layout
|
||||
- **Title**: "ThreadPilot - Process & Power Plan Manager"
|
||||
- **Layout**: Grid with TabControl for main content and StatusBar at bottom
|
||||
- **Tabs**: Organized with emoji icons for visual clarity
|
||||
- 🔧 Process Management
|
||||
- ⚡ Power Plans
|
||||
- 🔗 Process Associations
|
||||
- ⚙️ Settings
|
||||
|
||||
### Status Bar
|
||||
- Left: General status messages
|
||||
- Right: Game Boost status with visual indicators (🛡️ when active)
|
||||
|
||||
## UI Component Standards
|
||||
|
||||
### Buttons
|
||||
- **Standard Padding**: `10,5` for main action buttons
|
||||
- **Small Buttons**: `5,2` for utility buttons with `FontSize="10"`
|
||||
- **Icons**: Use emoji prefixes for visual clarity (🔄 Refresh, ⚙️ Settings)
|
||||
- **Colors**:
|
||||
- Update/Save: `#007ACC` background, white foreground
|
||||
- Remove/Delete: `#D13438` background, white foreground
|
||||
- Default: System colors
|
||||
|
||||
### GroupBox Headers
|
||||
- Use emoji prefixes for visual organization
|
||||
- Examples:
|
||||
- 🔍 Process Search & Control
|
||||
- ⚡ Available Power Plans
|
||||
- 📋 Current Associations
|
||||
- ⚙️ Configuration
|
||||
|
||||
### Text Input Controls
|
||||
- **Search boxes**: Width="200" with descriptive tooltips
|
||||
- **Background**: `#3C3C3C` for dark theme areas
|
||||
- **Foreground**: White for dark theme areas
|
||||
- **Border**: `#404040` for dark theme areas
|
||||
|
||||
### Data Grids
|
||||
- **Selection**: Single selection mode
|
||||
- **Headers**: Column headers visible
|
||||
- **Grid Lines**: Horizontal only
|
||||
- **Resizing**: Allow column resizing and sorting
|
||||
|
||||
## Color Scheme
|
||||
|
||||
### Light Theme (Default)
|
||||
- **Background**: System default (white/light gray)
|
||||
- **Foreground**: System default (black/dark gray)
|
||||
- **Accent**: `#007ACC` (blue)
|
||||
- **Error**: `#D13438` (red)
|
||||
- **Success**: System green
|
||||
|
||||
### Dark Theme Areas
|
||||
- **Background**: `#1E1E1E` (main), `#3C3C3C` (controls)
|
||||
- **Foreground**: White, `#CCCCCC` (secondary text)
|
||||
- **Border**: `#404040`
|
||||
|
||||
## Typography
|
||||
|
||||
### Font Sizes
|
||||
- **Default**: System default
|
||||
- **Small Controls**: `FontSize="10"` for utility buttons
|
||||
- **Secondary Text**: `FontSize="12"` for descriptions
|
||||
- **Headers**: Default with bold weight when active
|
||||
|
||||
### Font Weights
|
||||
- **Active Items**: Bold (using BoolToFontWeightConverter)
|
||||
- **Normal Items**: Normal weight
|
||||
- **Secondary Text**: Normal weight
|
||||
|
||||
## Icons and Visual Indicators
|
||||
|
||||
### Emoji Usage
|
||||
- 🔧 Process/System Management
|
||||
- ⚡ Power/Energy related
|
||||
- 🔗 Connections/Associations
|
||||
- 📋 Lists/Logs/Data
|
||||
- ⚙️ Settings/Configuration
|
||||
- 🔍 Search functionality
|
||||
- 🔄 Refresh/Reload
|
||||
- 🛡️ Game Boost/Protection
|
||||
- ✅ Success/Enabled
|
||||
- ❌ Error/Disabled
|
||||
|
||||
### Status Indicators
|
||||
- **Game Boost Active**: Bold text + 🛡️ icon
|
||||
- **Monitoring Active**: System tray icon changes
|
||||
- **Error States**: Red text/background
|
||||
- **Success States**: Green text/background
|
||||
|
||||
## Tooltips and Help Text
|
||||
|
||||
### Tooltip Standards
|
||||
- **Buttons**: Describe the action clearly
|
||||
- "Refresh the process list"
|
||||
- "Apply the selected CPU core affinity to the process"
|
||||
- **Input Fields**: Describe expected input
|
||||
- "Search processes by name"
|
||||
- "Enter the executable name (e.g., game.exe)"
|
||||
- **Checkboxes**: Explain the behavior
|
||||
- "Match processes by full path instead of just executable name"
|
||||
|
||||
### Help Text Format
|
||||
- Use clear, concise language
|
||||
- Avoid technical jargon where possible
|
||||
- Provide examples when helpful
|
||||
- Use consistent terminology (see Terminology section)
|
||||
|
||||
## Layout Guidelines
|
||||
|
||||
### Spacing and Margins
|
||||
- **Main Container**: `Margin="10"`
|
||||
- **GroupBox Content**: `Margin="5"`
|
||||
- **Control Spacing**: `Margin="0,0,10,0"` for horizontal spacing
|
||||
- **Section Spacing**: `Margin="0,0,0,10"` for vertical spacing
|
||||
|
||||
### Grid Organization
|
||||
- Use GroupBox for logical sections
|
||||
- Separate related controls visually
|
||||
- Maintain consistent spacing between elements
|
||||
- Use separators in context menus
|
||||
|
||||
### Responsive Design
|
||||
- Allow column resizing in data grids
|
||||
- Use appropriate width constraints
|
||||
- Ensure controls scale properly
|
||||
|
||||
## Terminology Standards
|
||||
|
||||
### Process Management
|
||||
- **Process**: Running application/executable
|
||||
- **Executable**: The .exe file name
|
||||
- **Process Name**: Display name of the process
|
||||
- **CPU Affinity**: Which CPU cores a process can use
|
||||
- **Priority**: Process execution priority level
|
||||
|
||||
### Power Management
|
||||
- **Power Plan**: Windows power configuration scheme
|
||||
- **Active Power Plan**: Currently selected power plan
|
||||
- **Default Power Plan**: Fallback power plan when no processes are running
|
||||
- **Power Plan Association**: Link between process and power plan
|
||||
|
||||
### Game Boost
|
||||
- **Game Boost**: High-performance mode for games
|
||||
- **Game Detection**: Automatic identification of game processes
|
||||
- **Known Games**: Pre-configured list of game executables
|
||||
|
||||
### Monitoring
|
||||
- **Event-based Monitoring**: Real-time WMI process monitoring
|
||||
- **Fallback Polling**: Backup monitoring method
|
||||
- **Process Association**: Configured process-to-power plan mapping
|
||||
|
||||
## Accessibility Guidelines
|
||||
|
||||
### Keyboard Navigation
|
||||
- Ensure all controls are keyboard accessible
|
||||
- Provide logical tab order
|
||||
- Support standard keyboard shortcuts
|
||||
|
||||
### Screen Reader Support
|
||||
- Use descriptive control names
|
||||
- Provide appropriate ARIA labels where needed
|
||||
- Ensure status information is announced
|
||||
|
||||
### Visual Accessibility
|
||||
- Maintain sufficient color contrast
|
||||
- Don't rely solely on color for information
|
||||
- Provide text alternatives for visual indicators
|
||||
|
||||
## Future Development Guidelines
|
||||
|
||||
### Adding New Features
|
||||
1. Follow existing naming conventions
|
||||
2. Use consistent spacing and layout patterns
|
||||
3. Add appropriate tooltips and help text
|
||||
4. Update this style guide with new patterns
|
||||
5. Test with both light and dark theme areas
|
||||
|
||||
### Code Organization
|
||||
- Keep XAML clean and well-commented
|
||||
- Use consistent indentation (4 spaces)
|
||||
- Group related controls logically
|
||||
- Use meaningful names for controls that need code-behind access
|
||||
|
||||
### Testing Considerations
|
||||
- Test all UI changes with different screen sizes
|
||||
- Verify tooltip text is helpful and accurate
|
||||
- Ensure consistent behavior across all tabs
|
||||
- Test keyboard navigation paths
|
||||
|
||||
## Version History
|
||||
- **v1.0** (2025-01-28): Initial style guide creation
|
||||
- Covers current UI implementation with logging, game boost, and process monitoring features
|
||||
@@ -0,0 +1,8 @@
|
||||
# Assets
|
||||
|
||||
This folder is reserved for project assets used in documentation, branding, and release packaging.
|
||||
|
||||
Suggested subfolders:
|
||||
- screenshots/
|
||||
- icons/
|
||||
- branding/
|
||||
@@ -0,0 +1,21 @@
|
||||
# Documentation
|
||||
|
||||
This folder contains release and engineering documentation for ThreadPilot.
|
||||
|
||||
## Core Documents
|
||||
- Architecture: ../ARCHITECTURE_GUIDE.md
|
||||
- API reference: ../API_REFERENCE.md
|
||||
- Developer guide: ../DEVELOPER_GUIDE.md
|
||||
- Project structure: ../PROJECT_STRUCTURE.md
|
||||
- UI style guide: ../UI_STYLE_GUIDE.md
|
||||
- Advanced CPU features: ../ADVANCED_CPU_FEATURES.md
|
||||
- Game boost validation: ../GAME_BOOST_VALIDATION.md
|
||||
|
||||
## Release and Governance
|
||||
- Security policy: ../SECURITY.md
|
||||
- Contributing: ../CONTRIBUTING.md
|
||||
- Code of Conduct: ../CODE_OF_CONDUCT.md
|
||||
- Changelog: ../CHANGELOG.md
|
||||
|
||||
## Migration Note
|
||||
Repository documentation is being progressively consolidated under docs/ as part of the v1.1.0 enterprise hardening cycle.
|
||||
@@ -0,0 +1,35 @@
|
||||
# Release Signing Guide
|
||||
|
||||
This document describes how to prepare ThreadPilot for signed production releases.
|
||||
|
||||
## Objectives
|
||||
- Authenticate official binaries.
|
||||
- Reduce SmartScreen friction.
|
||||
- Provide traceability for shipped artifacts.
|
||||
|
||||
## Recommended Strategy
|
||||
1. Use an Authenticode code-signing certificate from a trusted CA.
|
||||
2. Store signing secrets in GitHub Environments with required approvals.
|
||||
3. Sign binaries only in protected release workflows triggered by tags.
|
||||
|
||||
## Local Signing Example
|
||||
```powershell
|
||||
signtool sign /fd SHA256 /tr http://timestamp.digicert.com /td SHA256 /a "ThreadPilot.exe"
|
||||
```
|
||||
|
||||
## CI Signing Steps
|
||||
1. Decode PFX from encrypted secret at workflow runtime.
|
||||
2. Import certificate into current user certificate store.
|
||||
3. Sign release binaries and installer artifacts.
|
||||
4. Publish SHA256 checksums and signature verification instructions.
|
||||
|
||||
## Verification
|
||||
```powershell
|
||||
Get-AuthenticodeSignature .\ThreadPilot.exe
|
||||
Get-FileHash .\ThreadPilot.exe -Algorithm SHA256
|
||||
```
|
||||
|
||||
## Operational Notes
|
||||
- Never commit certificates or private keys.
|
||||
- Rotate secrets periodically.
|
||||
- Require maintainer approval for release jobs.
|
||||
@@ -0,0 +1,74 @@
|
||||
# 🌊 Fluent Design Migration Plan (Safe & Incremental)
|
||||
|
||||
This revised plan adopts `Wpf.Ui` to natively implement Windows 11 Fluent Design while strictly avoiding a destructive rewrite. We will use a staged deprecation model to gracefully phase out legacy custom styles without causing UI collapses or broken resource references.
|
||||
|
||||
## 1. Staged Deprecation Plan
|
||||
|
||||
**Rule:** We will *not* delete all custom styles at once.
|
||||
|
||||
| Category | Action | Reasoning |
|
||||
| :--- | :--- | :--- |
|
||||
| **Control Templates** (TabControl, TabItem, ComboBox, Button, TextBox) | **Remove Immediately** (in Phase 1) | `Wpf.Ui`'s global `ControlsDictionary` implicitly and instantly styles these when custom styles are cleared. Keeping custom styles causes collisions. |
|
||||
| **Structural Styles** (Grid, Border layout snaps) | **Preserve Temporarily** | These don't conflict with Fluent Design and prevent immediate layout shifts. |
|
||||
| **Color Brushes** (SurfaceBrush, AccentBrush, etc.) | **Preserve via Aliasing** | Explicitly mapping our legacy brush names to `Wpf.Ui` keys ensures un-migrated Views do not crash or turn transparent. |
|
||||
| **State Brushes** (SuccessBackgroundBrush, etc.) | **Preserve Permanently** | `Wpf.Ui` focuses on structural elements; maintaining our custom success/error semantic tokens is necessary for valid status bars. |
|
||||
|
||||
## 2. Brush Migration Strategy & Mapping
|
||||
|
||||
To prevent broken `DynamicResource` bindings during the transition, we will transform `Themes/FluentDark.xaml` into an **Alias Dictionary**.
|
||||
|
||||
| Current Custom Brush | `Wpf.Ui` Equivalent Target |
|
||||
| :--- | :--- |
|
||||
| `AppBackgroundBrush` | `ApplicationBackgroundBrush` |
|
||||
| `SurfaceBrush` | `CardBackgroundFillColorDefaultBrush` (or `ControlFillColorDefaultBrush`) |
|
||||
| `SurfaceAltBrush` | `CardBackgroundFillColorSecondaryBrush` |
|
||||
| `TextPrimaryBrush` | `TextFillColorPrimaryBrush` |
|
||||
| `TextSecondaryBrush` | `TextFillColorSecondaryBrush` |
|
||||
| `TextDisabledBrush` | `TextFillColorDisabledBrush` |
|
||||
| `AccentBrush` | `SystemAccentColorPrimaryBrush` |
|
||||
| `AccentAltBrush` | `SystemAccentColorSecondaryBrush` |
|
||||
| `BorderBrush` | `CardStrokeColorDefaultBrush` |
|
||||
| `InputBorderBrush` | `ControlStrokeColorDefaultBrush` |
|
||||
|
||||
*Fallback strategy:* If a specific legacy brush requires an exact opacity/hex that Fluent lacks, we will retain the exact `<SolidColorBrush>` entry rather than mapping it.
|
||||
|
||||
## 3. Control Migration Scope (Phase 1)
|
||||
|
||||
Only the following core interactive elements will be yielded to Fluent styling during the infrastructure phase:
|
||||
|
||||
- **TabControl / TabItem**: Will switch to Fluent tabs. Wpf.Ui native tabs use underline selection effects instead of filled block backgrounds.
|
||||
- **ComboBox**: Will transition to modern, rounded popup cards.
|
||||
- **Buttons**: Will adopt Fluent background states and rounded corners (`CornerRadius="4"` default).
|
||||
- **ListView / DataGrid**: Will adopt Fluent bordered-row styles natively.
|
||||
|
||||
**Known Structural Risks in Scope**:
|
||||
- Fluent `DataGrid` rows have larger innate vertical padding. This may cause scrollbars to appear earlier in constrained `Heights`.
|
||||
- Fluent `ComboBox` dropdowns render outside the parent visual tree constraints (Popup), which usually resolves Z-index issues perfectly but may alter perceived alignment if wrapped tightly in a canvas.
|
||||
|
||||
## 4. Risk Mitigation Strategies
|
||||
|
||||
1. **Preventing UI Regressions**: We will explicitly map `System.Windows.Controls` styles prior to deleting any custom XAML headers. Un-migrated tabs will still visually resolve their `Background="{DynamicResource SurfaceBrush}"` to a Fluent native shade.
|
||||
2. **Preventing Broken Bindings**: No C# `DataContext` or `Binding` logic will be altered during XAML structural updates.
|
||||
3. **Preventing Layout Collapses**: As elements transition to Fluent geometries, we will systematically strip fixed `Height="XXX"` or `MaxLength` restraints globally from elements, instead leveraging `Grid.RowDefinitions="Auto,*"` to allow fluent elements to define their own organic sizing needs.
|
||||
|
||||
## 5. Incremental Execution Plan
|
||||
|
||||
We divide Phase 2 into strict atomic units to test visually before advancing.
|
||||
|
||||
### Step 1: Framework Base & Aliasing (The Infrastructure)
|
||||
- `dotnet add package Wpf.Ui`
|
||||
- Update `App.xaml` with core `.MergedDictionaries`.
|
||||
- Strip `Themes/FluentDark.xaml` of all `<Style TargetType="Button">`, `<Style TargetType="ComboBox">`, etc.
|
||||
- Rewrite remaining `SolidColorBrush` definitions in `FluentDark.xaml` to `DynamicResource` aliases to Wpf.Ui.
|
||||
|
||||
### Step 2: MainWindow Integration
|
||||
- Transform the root `<Window>` into `<ui:FluentWindow>` to unlock Mica backdrop effects and custom titlebars.
|
||||
- Replace the legacy `<TabControl>` with Wpf.Ui native navigation (or clean native TabControl). Verify it renders precisely.
|
||||
|
||||
### Step 3: View Anchor Migration (LogViewer)
|
||||
- Target `LogViewerView.xaml`.
|
||||
- Cleanse it of rigid layout blocks. Implement responsive `<Grid>` expansions to distribute columns evenly.
|
||||
- Swap explicit legacy Brush calls (e.g. `Foreground="{DynamicResource TextPrimaryBrush}"`) for direct `Wpf.Ui` brush keys.
|
||||
|
||||
### Step 4: Iterative Rollout
|
||||
Target the remaining views (`ProcessManagementView`, `MasksView`, `PowerPlanView`) sequentially, verifying their respective grids, slider components, and checkboxes adopt Fluent visuals flawlessly.
|
||||
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"$schema": "https://raw.githubusercontent.com/DotNetAnalyzers/StyleCopAnalyzers/master/StyleCop.Analyzers/StyleCop.Analyzers.StyleCopSettings.schema.json",
|
||||
"settings": {
|
||||
"documentationRules": {
|
||||
"companyName": "Prime Build",
|
||||
"copyrightText": "ThreadPilot - Advanced Windows Process and Power Plan Manager"
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user