commit cff7d00067cdb514f6345c94cc97998f52a54a2b Author: Focaccina-Ripiena37 Date: Sun Dec 21 04:19:52 2025 +0100 Initial clean import diff --git a/.claude/settings.local.json b/.claude/settings.local.json new file mode 100644 index 0000000..0982ce5 --- /dev/null +++ b/.claude/settings.local.json @@ -0,0 +1,13 @@ +{ + "permissions": { + "allow": [ + "Bash(dotnet build:*)", + "Bash(Select-String -Pattern \"error|Build succeeded|Build FAILED\" -Context 0,2)", + "Bash(ls -la \"c:\\\\Users\\\\Lorenzo\\\\Documents\\\\Projects\\\\CPUSetSetter-main\\\\CPUSetSetter\"\" | grep -i \".xaml \")", + "Bash(cat:*)", + "Bash(grep:*)", + "Bash(dotnet run:*)", + "Bash(powershell -Command \"Start-Process ''C:\\\\Users\\\\Lorenzo\\\\Documents\\\\Projects\\\\ThreadPilot\\\\bin\\\\Release\\\\net8.0-windows\\\\win-x64\\\\ThreadPilot.exe'' -Verb RunAs\")" + ] + } +} diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..519cb3f --- /dev/null +++ b/.gitignore @@ -0,0 +1,265 @@ +# Escludi tutti gli .exe +*.exe + +# Escludi la sorgente CPUSetSetter upstream +/CPUSetSetter-main/ + +# Escludi Markdown tranne il README principale +*.md +!README.md + +# Escludi directory di build comuni +/bin/ +/obj/ +/publish/ +/publish_*/ + +# .NET Core / .NET 5+ specifici +*.deps.json +*.runtimeconfig.json +*.dll.config +project.lock.json +project.fragment.lock.json +artifacts/ + +# Visual Studio specifici +.vs/ +*.user +*.suo +*.userosscache +*.sln.docstates +*.vcxproj.filters +*.vcxproj.user + +# Rider / JetBrains +.idea/ +*.sln.iml + +# Resharper +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +[Ww][Ii][Nn]32/ +[Aa][Rr][Mm]/ +[Aa][Rr][Mm]64/ +bld/ +[Bb]in/ +[Oo]bj/ +[Ll]og/ +[Ll]ogs/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUnit +*.VisualState.xml +TestResult.xml +nunit-*.xml + +# Coverage reports +coverage*.json +coverage*.xml +coverage*.info +*.coverage +*.coveragexml + +# NuGet +*.nupkg +*.snupkg +.nuget/ +packages/ +!packages/build/ +!packages/repositories.config + +# Package manager files +paket-files/ +.paket/paket.exe +.fake/ + +# Windows specifici +Thumbs.db +ehthumbs.db +Desktop.ini +$RECYCLE.BIN/ +*.cab +*.msi +*.msix +*.msm +*.msp +*.lnk + +# Temporary files +*.tmp +*.temp +*~ +*.swp +*.swo + +# Log files +*.log +logs/ +Logs/ + +# Configuration files con dati sensibili +appsettings.local.json +appsettings.*.local.json +secrets.json +*.secrets.json + +# ThreadPilot specifici +# Dati utente e configurazioni locali +/Configuration/UserSettings.json +/Configuration/ProcessProfiles.json +/Data/ +/AppData/ +%AppData%/ThreadPilot/ + +# File di backup automatici +*.bak +*.backup +*_backup.* +*_old.* + +# Crash dumps e diagnostici +*.dmp +*.mdmp +crashdumps/ + +# Performance profiling +*.psess +*.vsp +*.vspx +*.sap + +# Installer files +*.msi +*.cab +*.msm +*.msp +*.exe.config + +# ClickOnce directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +*.pubxml +*.publishproj + +# Microsoft Azure Web App publish settings +PublishScripts/ + +# Node.js (se usato per build tools) +node_modules/ +npm-debug.log* +yarn-debug.log* +yarn-error.log* + +# Python (se usato per script di build) +__pycache__/ +*.py[cod] +*$py.class + +# macOS (per sviluppatori cross-platform) +.DS_Store +.AppleDouble +.LSOverride + +# Linux +*~ +.fuse_hidden* +.directory +.Trash-* + +# Backup files da editor +*.orig +*.rej + +# JetBrains Rider +.idea/ +*.sln.iml + +# CodeRush personal settings +.cr/personal + +# Python Tools for Visual Studio (PTVS) +__pycache__/ +*.pyc + +# Cake - Uncomment if you are using it +# tools/** +# !tools/packages.config + +# Tabs Studio +*.tss + +# Telerik's JustMock configuration file +*.jmconfig + +# BizTalk build output +*.btp.cs +*.btm.cs +*.odx.cs +*.xsd.cs + +# OpenCover UI analysis results +OpenCover/ + +# Azure Stream Analytics local run output +ASALocalRun/ + +# MSBuild Binary and Structured Log +*.binlog + +# NVidia Nsight GPU debugger configuration file +*.nvuser + +# MFractors (Xamarin productivity tool) working folder +.mfractor/ + +# Local History for Visual Studio +.localhistory/ + +# BeatPulse healthcheck temp database +healthchecksdb + +# Backup folder for Package Reference Convert tool in Visual Studio 2017 +MigrationBackup/ + +# Ionide (cross platform F# VS Code tools) working folder +.ionide/ + +# Fody - auto-generated XML schema +FodyWeavers.xsd + +# VS Code +.vscode/ +!.vscode/settings.json +!.vscode/tasks.json +!.vscode/launch.json +!.vscode/extensions.json +*.code-workspace + +# Local History for Visual Studio Code +.history/ + +# Windows Installer files from build outputs +*.msi +*.msm +*.msp + +# JetBrains Rider +*.sln.iml + +# Continue.dev (AI coding assistant) +.continue/ \ No newline at end of file diff --git a/ADVANCED_CPU_FEATURES.md b/ADVANCED_CPU_FEATURES.md new file mode 100644 index 0000000..a73b271 --- /dev/null +++ b/ADVANCED_CPU_FEATURES.md @@ -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 diff --git a/API_REFERENCE.md b/API_REFERENCE.md new file mode 100644 index 0000000..4df0029 --- /dev/null +++ b/API_REFERENCE.md @@ -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? AvailabilityChanged; + Task InitializeAsync(); + Task DisposeAsync(); +} +``` + +**Key Methods:** +- `InitializeAsync()`: Initialize service resources +- `DisposeAsync()`: Clean up service resources +- `IsAvailable`: Indicates if service is operational + +### IRepository +Generic repository interface for data access operations. + +```csharp +public interface IRepository : IRepository where T : class +{ + Task GetByIdAsync(string id); + Task> GetAllAsync(); + Task> FindAsync(Expression> predicate); + Task AddAsync(T entity); + Task UpdateAsync(T entity); + Task DeleteAsync(string id); + Task ExistsAsync(string id); + Task CountAsync(); +} +``` + +## Core Services + +### IProcessService +Manages process enumeration and manipulation. + +```csharp +public interface IProcessService +{ + Task> GetRunningProcessesAsync(); + Task SetProcessPriorityAsync(int processId, ProcessPriorityClass priority); + Task SetProcessAffinityAsync(int processId, long affinityMask); + Task 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> GetAvailablePowerPlansAsync(); + Task GetActivePowerPlanAsync(); + Task SetActivePowerPlanAsync(string powerPlanGuid); + Task GetPowerPlanByGuidAsync(string guid); + event EventHandler? 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 DetectTopologyAsync(); + Task SetProcessAffinityAsync(int processId, IEnumerable coreIds); + Task GetProcessAffinityAsync(int processId); + event EventHandler? 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? ProcessStarted; + event EventHandler? 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 ActivateGameBoostAsync(ProcessModel gameProcess); + Task DeactivateGameBoostAsync(); + Task AddKnownGameAsync(string executableName); + Task RemoveKnownGameAsync(string executableName); + event EventHandler? GameBoostActivated; + event EventHandler? 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 ExportSettingsAsync(string filePath); + Task ImportSettingsAsync(string filePath); + event EventHandler? 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> 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 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. diff --git a/ARCHITECTURE_GUIDE.md b/ARCHITECTURE_GUIDE.md new file mode 100644 index 0000000..cce5c37 --- /dev/null +++ b/ARCHITECTURE_GUIDE.md @@ -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. diff --git a/App.xaml b/App.xaml new file mode 100644 index 0000000..99952d1 --- /dev/null +++ b/App.xaml @@ -0,0 +1,21 @@ +๏ปฟ + + + + + + + + + + + + + + + diff --git a/App.xaml.cs b/App.xaml.cs new file mode 100644 index 0000000..383966d --- /dev/null +++ b/App.xaml.cs @@ -0,0 +1,238 @@ +๏ปฟusing System; +using System.Linq; +using System.Security.Principal; +using System.Threading; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Threading; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using ThreadPilot.Services; +using ThreadPilot.ViewModels; + +namespace ThreadPilot +{ + public partial class App : System.Windows.Application + { + private Mutex? _singleInstanceMutex; + public IServiceProvider ServiceProvider { get; private set; } + + public App() + { + ServiceCollection services = new ServiceCollection(); + + // Use the new centralized service configuration + services.ConfigureApplicationServices(); + + ServiceProvider = services.BuildServiceProvider(); + + // Validate service configuration + ServiceConfiguration.ValidateServiceConfiguration(ServiceProvider); + } + + + + protected override void OnStartup(StartupEventArgs e) + { + // Enforce single-instance: bail out if another instance is already running + bool createdNew; + _singleInstanceMutex = new Mutex(initiallyOwned: true, name: "Global\\ThreadPilot_SingleInstance", createdNew: out createdNew); + if (!createdNew) + { + System.Windows.MessageBox.Show( + "ThreadPilot รจ giร  in esecuzione.", + "Istanza giร  aperta", + MessageBoxButton.OK, + MessageBoxImage.Information); + + Shutdown(); + return; + } + + // Set up global exception handlers first + AppDomain.CurrentDomain.UnhandledException += OnUnhandledException; + DispatcherUnhandledException += OnDispatcherUnhandledException; + + // Check elevation status first + var elevationService = ServiceProvider.GetRequiredService(); + var logger = ServiceProvider.GetRequiredService>(); + + if (!elevationService.IsRunningAsAdministrator()) + { + logger.LogWarning("Application is not running with administrator privileges"); + ShowElevationRequiredMessage(); + + // Allow the application to continue in read-only mode + // The UI will handle showing elevation prompts as needed + } + else + { + logger.LogInformation("Application is running with administrator privileges"); + } + + base.OnStartup(e); + + // Parse command line arguments + bool startMinimized = false; + bool isAutostart = false; + bool isTestMode = false; + + foreach (var arg in e.Args) + { + switch (arg.ToLowerInvariant()) + { + case "--test": + isTestMode = true; + break; + case "--start-minimized": + startMinimized = true; + break; + case "--autostart": + isAutostart = true; + break; + case "--startup": // Alternative startup argument + isAutostart = true; + startMinimized = true; + break; + } + } + + // Check for test mode + if (isTestMode) + { + // Run in console test mode + AllocConsole(); + _ = Task.Run(async () => + { + await TestRunner.RunTests(); + Dispatcher.Invoke(() => Shutdown()); + }); + return; + } + + var mainWindow = ServiceProvider.GetRequiredService(); + + // Handle startup behavior with comprehensive error handling + try + { + logger.LogInformation("Attempting to show main window..."); + + // Ensure the window is properly initialized + if (mainWindow == null) + { + throw new InvalidOperationException("MainWindow could not be created"); + } + + // Show the window with explicit visibility settings + mainWindow.Visibility = Visibility.Visible; + mainWindow.WindowState = (startMinimized || isAutostart) + ? WindowState.Minimized + : WindowState.Normal; + mainWindow.Show(); + if (mainWindow.WindowState != WindowState.Minimized) + { + mainWindow.Activate(); + } + + logger.LogInformation("Main window displayed successfully"); + } + catch (Exception ex) + { + logger.LogError(ex, "Critical error during application startup"); + + // Show error message and exit gracefully + var errorMessage = $"ThreadPilot failed to start:\n\n{ex.Message}\n\nStack Trace:\n{ex.StackTrace}"; + System.Windows.MessageBox.Show(errorMessage, "ThreadPilot Startup Error", + MessageBoxButton.OK, MessageBoxImage.Error); + + // Exit the application + Shutdown(1); + return; + } + } + + protected override void OnExit(ExitEventArgs e) + { + if (_singleInstanceMutex != null) + { + try + { + _singleInstanceMutex.ReleaseMutex(); + } + catch + { + // Ignore; we just want to clean up quietly + } + _singleInstanceMutex.Dispose(); + _singleInstanceMutex = null; + } + + base.OnExit(e); + } + + [System.Runtime.InteropServices.DllImport("kernel32.dll")] + private static extern bool AllocConsole(); + + /// + /// Shows a message to the user about elevation requirements + /// + private void ShowElevationRequiredMessage() + { + // Don't show the message during autostart to avoid interrupting the user + var args = Environment.GetCommandLineArgs(); + if (args.Any(arg => arg.Equals("--autostart", StringComparison.OrdinalIgnoreCase) || + arg.Equals("--startup", StringComparison.OrdinalIgnoreCase))) + { + return; + } + + System.Windows.MessageBox.Show( + "ThreadPilot is running with limited privileges. Some features may not be available.\n\n" + + "For full functionality including process affinity and power plan management, " + + "administrator privileges are required.\n\n" + + "You can request elevation from the application menu when needed.", + "Limited Privileges", + MessageBoxButton.OK, + MessageBoxImage.Information); + } + + /// + /// Handles unhandled exceptions in the application domain + /// + private void OnUnhandledException(object sender, UnhandledExceptionEventArgs e) + { + var exception = e.ExceptionObject as Exception; + var logger = ServiceProvider?.GetService>(); + + logger?.LogCritical(exception, "Unhandled exception occurred"); + + var errorMessage = $"A critical error occurred:\n\n{exception?.Message}\n\nThe application will now exit."; + System.Windows.MessageBox.Show(errorMessage, "Critical Error", + MessageBoxButton.OK, MessageBoxImage.Error); + } + + /// + /// Handles unhandled exceptions on the UI thread + /// + private void OnDispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e) + { + var logger = ServiceProvider?.GetService>(); + + logger?.LogError(e.Exception, "Unhandled dispatcher exception occurred"); + + var errorMessage = $"An error occurred in the user interface:\n\n{e.Exception.Message}\n\nDo you want to continue?"; + var result = System.Windows.MessageBox.Show(errorMessage, "UI Error", + MessageBoxButton.YesNo, MessageBoxImage.Error); + + if (result == MessageBoxResult.Yes) + { + e.Handled = true; // Continue running + } + else + { + e.Handled = false; // Let the application crash + } + } + } +} + diff --git a/AssemblyInfo.cs b/AssemblyInfo.cs new file mode 100644 index 0000000..cc29e7f --- /dev/null +++ b/AssemblyInfo.cs @@ -0,0 +1,10 @@ +using System.Windows; + +[assembly:ThemeInfo( + ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located + //(used if a resource is not found in the page, + // or application resource dictionaries) + ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located + //(used if a resource is not found in the page, + // app, or any theme specific resource dictionaries) +)] diff --git a/Configuration/ProcessPowerPlanAssociations.json b/Configuration/ProcessPowerPlanAssociations.json new file mode 100644 index 0000000..bd15237 --- /dev/null +++ b/Configuration/ProcessPowerPlanAssociations.json @@ -0,0 +1,22 @@ +{ + "DefaultPowerPlanGuid": "", + "DefaultPowerPlanName": "", + "IsEventBasedMonitoringEnabled": true, + "IsFallbackPollingEnabled": true, + "PollingIntervalSeconds": 5, + "PreventDuplicatePowerPlanChanges": true, + "PowerPlanChangeDelayMs": 1000, + "Associations": [ + { + "Id": "sample-gaming-association", + "ExecutableName": "game.exe", + "ExecutablePath": "", + "PowerPlanGuid": "8c5e7fda-e8bf-4a96-9a85-a6e23a8c635c", + "PowerPlanName": "High performance", + "MatchByPath": false, + "Priority": 10, + "Description": "Sample gaming association - switch to high performance for games", + "IsEnabled": false + } + ] +} diff --git a/Converters/BoolToColorConverter.cs b/Converters/BoolToColorConverter.cs new file mode 100644 index 0000000..0df167e --- /dev/null +++ b/Converters/BoolToColorConverter.cs @@ -0,0 +1,26 @@ +using System; +using System.Globalization; +using System.Windows.Data; +using System.Windows.Media; + +namespace ThreadPilot +{ + public class BoolToColorConverter : IValueConverter + { + public static readonly BoolToColorConverter Instance = new(); + + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) + { + if (value is bool boolValue && boolValue) + { + return new SolidColorBrush(Colors.Green); + } + return new SolidColorBrush(Colors.Gray); + } + + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + { + throw new NotImplementedException(); + } + } +} diff --git a/Converters/BoolToFontWeightConverter.cs b/Converters/BoolToFontWeightConverter.cs new file mode 100644 index 0000000..9053e35 --- /dev/null +++ b/Converters/BoolToFontWeightConverter.cs @@ -0,0 +1,26 @@ +using System; +using System.Globalization; +using System.Windows; +using System.Windows.Data; + +namespace ThreadPilot +{ + public class BoolToFontWeightConverter : IValueConverter + { + public static readonly BoolToFontWeightConverter Instance = new(); + + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) + { + if (value is bool boolValue && boolValue) + { + return FontWeights.Bold; + } + return FontWeights.Normal; + } + + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + { + throw new NotImplementedException(); + } + } +} diff --git a/Converters/BoolToStringConverter.cs b/Converters/BoolToStringConverter.cs new file mode 100644 index 0000000..486d97d --- /dev/null +++ b/Converters/BoolToStringConverter.cs @@ -0,0 +1,31 @@ +using System; +using System.Globalization; +using System.Windows.Data; + +namespace ThreadPilot.Converters +{ + /// + /// Converts boolean values to strings based on parameter format + /// + public class BoolToStringConverter : IValueConverter + { + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) + { + if (value is bool boolValue && parameter is string paramString) + { + var parts = paramString.Split('|'); + if (parts.Length == 2) + { + return boolValue ? parts[0] : parts[1]; + } + } + + return value?.ToString() ?? string.Empty; + } + + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + { + throw new NotImplementedException(); + } + } +} diff --git a/Converters/BoolToVisibilityConverter.cs b/Converters/BoolToVisibilityConverter.cs new file mode 100644 index 0000000..2948376 --- /dev/null +++ b/Converters/BoolToVisibilityConverter.cs @@ -0,0 +1,30 @@ +using System; +using System.Globalization; +using System.Windows; +using System.Windows.Data; + +namespace ThreadPilot +{ + public class BoolToVisibilityConverter : IValueConverter + { + public static readonly BoolToVisibilityConverter Instance = new(); + + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) + { + if (value is bool boolValue && boolValue) + { + return Visibility.Visible; + } + return Visibility.Collapsed; + } + + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + { + if (value is Visibility visibility) + { + return visibility == Visibility.Visible; + } + return false; + } + } +} diff --git a/Converters/BytesToStringConverter.cs b/Converters/BytesToStringConverter.cs new file mode 100644 index 0000000..3b9abdd --- /dev/null +++ b/Converters/BytesToStringConverter.cs @@ -0,0 +1,47 @@ +using System; +using System.Globalization; +using System.Windows.Data; + +namespace ThreadPilot.Converters +{ + /// + /// Converts byte values to human-readable string format + /// + public class BytesToStringConverter : IValueConverter + { + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) + { + if (value is long bytes) + { + return FormatBytes(bytes); + } + + if (value is int intBytes) + { + return FormatBytes(intBytes); + } + + return "0 B"; + } + + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + { + throw new NotImplementedException(); + } + + private static string FormatBytes(long bytes) + { + string[] suffixes = { "B", "KB", "MB", "GB", "TB" }; + int counter = 0; + decimal number = bytes; + + while (Math.Round(number / 1024) >= 1) + { + number /= 1024; + counter++; + } + + return $"{number:n1} {suffixes[counter]}"; + } + } +} diff --git a/Converters/CpuTopologyConverters.cs b/Converters/CpuTopologyConverters.cs new file mode 100644 index 0000000..6ab58fb --- /dev/null +++ b/Converters/CpuTopologyConverters.cs @@ -0,0 +1,150 @@ +using System; +using System.Globalization; +using System.Windows; +using System.Windows.Data; +using System.Windows.Media; +using ThreadPilot.Models; + +namespace ThreadPilot.Converters +{ + /// + /// Converter for CPU core type to color + /// + public class CoreTypeToColorConverter : IMultiValueConverter + { + public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture) + { + if (values.Length < 2) return System.Windows.Media.Brushes.Black; + + var coreType = values[0] as CpuCoreType? ?? CpuCoreType.Unknown; + var isHyperThreaded = values[1] as bool? ?? false; + + return coreType switch + { + CpuCoreType.PerformanceCore => isHyperThreaded ? System.Windows.Media.Brushes.DarkBlue : System.Windows.Media.Brushes.Blue, + CpuCoreType.EfficiencyCore => isHyperThreaded ? System.Windows.Media.Brushes.DarkGreen : System.Windows.Media.Brushes.Green, + CpuCoreType.Zen or CpuCoreType.ZenPlus or CpuCoreType.Zen2 or CpuCoreType.Zen3 or CpuCoreType.Zen4 => + isHyperThreaded ? System.Windows.Media.Brushes.DarkRed : System.Windows.Media.Brushes.Red, + _ => isHyperThreaded ? System.Windows.Media.Brushes.DarkGray : System.Windows.Media.Brushes.Black + }; + } + + public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture) + { + throw new NotImplementedException(); + } + } + + /// + /// Converter for boolean to color (success/failure indication) + /// + public class BoolToColorConverter : IValueConverter + { + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) + { + if (value is bool success) + { + return success ? System.Windows.Media.Brushes.Green : System.Windows.Media.Brushes.Red; + } + return System.Windows.Media.Brushes.Black; + } + + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + { + throw new NotImplementedException(); + } + } + + /// + /// Converter for boolean to visibility + /// + public class BoolToVisibilityConverter : IValueConverter + { + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) + { + if (value is bool visible) + { + return visible ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed; + } + return System.Windows.Visibility.Collapsed; + } + + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + { + throw new NotImplementedException(); + } + } + + /// + /// Converter for affinity mask to readable string + /// + public class AffinityMaskConverter : IValueConverter + { + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) + { + if (value is long mask) + { + if (mask == 0) return "None"; + + var cores = new System.Collections.Generic.List(); + for (int i = 0; i < 64; i++) + { + if ((mask & (1L << i)) != 0) + { + cores.Add(i); + } + } + + if (cores.Count == 0) return "None"; + if (cores.Count == 1) return $"Core {cores[0]}"; + if (cores.Count <= 4) return $"Cores {string.Join(", ", cores)}"; + + return $"Cores {cores[0]}-{cores[cores.Count - 1]} ({cores.Count} cores)"; + } + return "Unknown"; + } + + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + { + throw new NotImplementedException(); + } + } + + /// + /// Converter for bytes to megabytes + /// + public class BytesToMbConverter : IValueConverter + { + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) + { + if (value is long bytes) + { + return (bytes / (1024.0 * 1024.0)).ToString("F1"); + } + return "0.0"; + } + + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + { + throw new NotImplementedException(); + } + } + + /// + /// Converter for string to visibility (empty/null = collapsed) + /// + public class StringToVisibilityConverter : IValueConverter + { + public static readonly StringToVisibilityConverter Instance = new(); + + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) + { + return string.IsNullOrEmpty(value as string) ? System.Windows.Visibility.Collapsed : System.Windows.Visibility.Visible; + } + + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + { + throw new NotImplementedException(); + } + } +} diff --git a/Converters/InverseBooleanConverter.cs b/Converters/InverseBooleanConverter.cs new file mode 100644 index 0000000..71a44ed --- /dev/null +++ b/Converters/InverseBooleanConverter.cs @@ -0,0 +1,32 @@ +using System; +using System.Globalization; +using System.Windows.Data; + +namespace ThreadPilot.Converters +{ + /// + /// Converter to invert boolean values + /// + public class InverseBooleanConverter : IValueConverter + { + public static readonly InverseBooleanConverter Instance = new(); + + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) + { + if (value is bool boolValue) + { + return !boolValue; + } + return true; + } + + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + { + if (value is bool boolValue) + { + return !boolValue; + } + return false; + } + } +} diff --git a/Converters/ItemIndexConverter.cs b/Converters/ItemIndexConverter.cs new file mode 100644 index 0000000..57e9b73 --- /dev/null +++ b/Converters/ItemIndexConverter.cs @@ -0,0 +1,34 @@ +using System; +using System.Globalization; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Data; + +namespace ThreadPilot.Converters +{ + /// + /// Converter to get the index of an item in an ItemsControl + /// + public class ItemIndexConverter : IValueConverter + { + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) + { + if (value is DependencyObject item) + { + var itemsControl = ItemsControl.ItemsControlFromItemContainer(item); + if (itemsControl != null) + { + int index = itemsControl.ItemContainerGenerator.IndexFromContainer(item); + return index; + } + } + + return -1; + } + + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + { + throw new NotImplementedException(); + } + } +} diff --git a/DEVELOPER_GUIDE.md b/DEVELOPER_GUIDE.md new file mode 100644 index 0000000..5a3f70b --- /dev/null +++ b/DEVELOPER_GUIDE.md @@ -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 +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` 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 DoSomethingAsync(); + event EventHandler? SomethingHappened; +} +``` + +**Step 2**: Implement the service: +```csharp +// Services/YourDomain/YourService.cs +public class YourService : BaseSystemService, IYourService +{ + public YourService(ILogger logger) : base(logger) { } + + public async Task DoSomethingAsync() + { + // Implementation + } +} +``` + +**Step 3**: Register in `ServiceConfiguration.cs`: +```csharp +services.AddSingleton(); +``` + +### 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 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(); +``` + +### 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(); + 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? YourEvent; + +protected virtual void OnYourEvent(YourEventArgs args) +{ + YourEvent?.Invoke(this, args); +} +``` + +### Async Operations +Always use proper async/await patterns: +```csharp +// Good +public async Task 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>(); + 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>(); + var service = Mock.Of(); + 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. diff --git a/GAME_BOOST_VALIDATION.md b/GAME_BOOST_VALIDATION.md new file mode 100644 index 0000000..730c612 --- /dev/null +++ b/GAME_BOOST_VALIDATION.md @@ -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. diff --git a/Helpers/AffinityHelper.cs b/Helpers/AffinityHelper.cs new file mode 100644 index 0000000..5f8e539 --- /dev/null +++ b/Helpers/AffinityHelper.cs @@ -0,0 +1,25 @@ +using System.Collections.Generic; +using System.Linq; +using System.Windows.Controls; + +namespace ThreadPilot.Helpers +{ + public static class AffinityHelper + { + public static long CalculateAffinityMask(IEnumerable cpuCheckboxes) + { + return cpuCheckboxes + .Where(cb => cb.IsChecked == true) + .Sum(cb => (long)cb.Tag); + } + + public static void UpdateCheckboxesFromMask(IEnumerable cpuCheckboxes, long affinityMask) + { + foreach (var checkbox in cpuCheckboxes) + { + var cpuBit = (long)checkbox.Tag; + checkbox.IsChecked = (affinityMask & cpuBit) != 0; + } + } + } +} \ No newline at end of file diff --git a/Helpers/Converters.cs b/Helpers/Converters.cs new file mode 100644 index 0000000..6e9f8ad --- /dev/null +++ b/Helpers/Converters.cs @@ -0,0 +1,104 @@ +using System; +using System.Globalization; +using System.Windows; +using System.Windows.Data; + +namespace ThreadPilot.Helpers +{ + public class BytesToMbConverter : IValueConverter + { + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) + { + if (value is long bytes) + { + return Math.Round((double)bytes / (1024 * 1024), 1); + } + return 0; + } + + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + { + throw new NotImplementedException(); + } + } + + public class AffinityMaskConverter : IValueConverter + { + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) + { + if (value is long mask) + { + var selectedIndices = new System.Collections.Generic.List(); + // Dynamic core count based on system, limited to 64 (long is 64-bit) + int maxCores = Math.Min(64, Environment.ProcessorCount); + + for (int i = 0; i < maxCores; i++) + { + if ((mask & (1L << i)) != 0) + { + selectedIndices.Add(i); + } + } + + if (selectedIndices.Count == 0) + return "None"; + + // Build the display string + var indicesStr = string.Join(", ", selectedIndices); + int selectedCount = selectedIndices.Count; + + // Detect if this is likely physical cores only (every other logical processor) + // This heuristic checks if selected indices are evenly spaced by 2 (e.g., 0,2,4,6,8...) + bool isProbablyPhysicalCoresOnly = false; + if (selectedCount > 1 && selectedCount <= maxCores / 2) + { + isProbablyPhysicalCoresOnly = true; + for (int i = 1; i < selectedIndices.Count; i++) + { + if (selectedIndices[i] - selectedIndices[i - 1] != 2) + { + isProbablyPhysicalCoresOnly = false; + break; + } + } + } + + // Choose terminology based on what's selected + string label; + if (selectedCount == maxCores) + { + label = $"All threads (0-{maxCores - 1})"; + } + else if (isProbablyPhysicalCoresOnly && selectedIndices[0] == 0) + { + label = $"Physical cores ({indicesStr}) - {selectedCount} cores"; + } + else + { + label = $"Threads ({indicesStr}) - {selectedCount} threads"; + } + + return label; + } + return "Unknown"; + } + + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + { + throw new NotImplementedException(); + } + } + + public class BoolToFontWeightConverter : IValueConverter + { + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) + { + return (bool)value ? FontWeights.Bold : FontWeights.Normal; + } + + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + { + throw new NotImplementedException(); + } + } +} \ No newline at end of file diff --git a/Helpers/ServiceProviderExtensions.cs b/Helpers/ServiceProviderExtensions.cs new file mode 100644 index 0000000..8ec9c2c --- /dev/null +++ b/Helpers/ServiceProviderExtensions.cs @@ -0,0 +1,15 @@ +using System; +using Microsoft.Extensions.DependencyInjection; + +namespace ThreadPilot.Helpers +{ + public static class ServiceProviderExtensions + { + public static IServiceProvider Services => ((App)App.Current).ServiceProvider; + + public static T? GetService() where T : class + { + return Services.GetService(typeof(T)) as T; + } + } +} \ No newline at end of file diff --git a/Installer/Installer.iss b/Installer/Installer.iss new file mode 100644 index 0000000..f52af82 --- /dev/null +++ b/Installer/Installer.iss @@ -0,0 +1,59 @@ +; ThreadPilot installer script (Inno Setup) +; Requires Inno Setup to build the installer. Adjust MyAppVersion/MyAppBuildDir as needed. + +#define MyAppName "ThreadPilot" +#define MyAppPublisher "ThreadPilot" +#define MyAppURL "https://github.com/" +#define MyAppExeName "ThreadPilot.exe" +#define MyAppVersion "1.0.0" +; Point this to the folder containing the published binaries (e.g. dotnet publish -c Release -r win-x64) +#define MyAppBuildDir "..\\artifacts\\build" + +[Setup] +AppId={{A2A4C8B5-4A9A-4B1B-93F4-5F8B1C7E8C2A} +AppName={#MyAppName} +AppVersion={#MyAppVersion} +AppVerName={#MyAppName} {#MyAppVersion} +AppPublisher={#MyAppPublisher} +AppPublisherURL={#MyAppURL} +AppSupportURL={#MyAppURL} +AppUpdatesURL={#MyAppURL} +DefaultDirName={autopf}\{#MyAppName} +UninstallDisplayIcon={app}\{#MyAppExeName} +ArchitecturesAllowed=x64compatible +ArchitecturesInstallIn64BitMode=x64compatible +DefaultGroupName={#MyAppName} +AllowNoIcons=yes +PrivilegesRequiredOverridesAllowed=dialog +OutputBaseFilename=ThreadPilot_Setup +SetupIconFile=..\ico.ico +SolidCompression=yes +WizardStyle=modern + +[Languages] +Name: "english"; MessagesFile: "compiler:Default.isl" + +[Tasks] +Name: "desktopicon"; Description: "{cm:CreateDesktopIcon}"; GroupDescription: "{cm:AdditionalIcons}"; Flags: unchecked + +[Files] +Source: "{#MyAppBuildDir}\*"; DestDir: "{app}"; Flags: ignoreversion recursesubdirs createallsubdirs; BeforeInstall: KillRunningInstance() + +[Icons] +Name: "{group}\{#MyAppName}"; Filename: "{app}\{#MyAppExeName}" +Name: "{autodesktop}\{#MyAppName}"; Filename: "{app}\{#MyAppExeName}"; Tasks: desktopicon + +[Run] +Filename: "{app}\{#MyAppExeName}"; Description: "{cm:LaunchProgram,{#StringChange(MyAppName, '&', '&&')}}"; Flags: nowait postinstall skipifsilent + +[UninstallRun] +Filename: taskkill.exe; Parameters: "/IM '{#MyAppExeName}' /F"; Flags: runhidden waituntilterminated; RunOnceId: UninstallKill + +[Code] + +procedure KillRunningInstance(); +var + ResultCode: Integer; +begin + Exec('taskkill.exe', '/IM "{#MyAppExeName}" /F', '', SW_HIDE, ewWaitUntilTerminated, ResultCode); +end; diff --git a/LICENSE.md b/LICENSE.md new file mode 100644 index 0000000..cdca915 --- /dev/null +++ b/LICENSE.md @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2025 Prime Build + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. \ No newline at end of file diff --git a/MainWindow.xaml b/MainWindow.xaml new file mode 100644 index 0000000..c5cfac5 --- /dev/null +++ b/MainWindow.xaml @@ -0,0 +1,169 @@ +๏ปฟ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +